dolibarr  18.0.0-alpha
commonobject.class.php
Go to the documentation of this file.
1 <?php
2 /* Copyright (C) 2006-2015 Laurent Destailleur <eldy@users.sourceforge.net>
3  * Copyright (C) 2005-2013 Regis Houssin <regis.houssin@inodbox.com>
4  * Copyright (C) 2010-2020 Juanjo Menent <jmenent@2byte.es>
5  * Copyright (C) 2012-2013 Christophe Battarel <christophe.battarel@altairis.fr>
6  * Copyright (C) 2011-2022 Philippe Grand <philippe.grand@atoo-net.com>
7  * Copyright (C) 2012-2015 Marcos García <marcosgdf@gmail.com>
8  * Copyright (C) 2012-2015 Raphaël Doursenaud <rdoursenaud@gpcsolutions.fr>
9  * Copyright (C) 2012 Cedric Salvador <csalvador@gpcsolutions.fr>
10  * Copyright (C) 2015-2022 Alexandre Spangaro <aspangaro@open-dsi.fr>
11  * Copyright (C) 2016 Bahfir abbes <dolipar@dolipar.org>
12  * Copyright (C) 2017 ATM Consulting <support@atm-consulting.fr>
13  * Copyright (C) 2017-2019 Nicolas ZABOURI <info@inovea-conseil.com>
14  * Copyright (C) 2017 Rui Strecht <rui.strecht@aliartalentos.com>
15  * Copyright (C) 2018-2021 Frédéric France <frederic.france@netlogic.fr>
16  * Copyright (C) 2018 Josep Lluís Amador <joseplluis@lliuretic.cat>
17  * Copyright (C) 2021 Gauthier VERDOL <gauthier.verdol@atm-consulting.fr>
18  * Copyright (C) 2021 Grégory Blémand <gregory.blemand@atm-consulting.fr>
19  * Copyright (C) 2023 Lenin Rivas <lenin.rivas777@gmail.com>
20  *
21  * This program is free software; you can redistribute it and/or modify
22  * it under the terms of the GNU General Public License as published by
23  * the Free Software Foundation; either version 3 of the License, or
24  * (at your option) any later version.
25  *
26  * This program is distributed in the hope that it will be useful,
27  * but WITHOUT ANY WARRANTY; without even the implied warranty of
28  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
29  * GNU General Public License for more details.
30  *
31  * You should have received a copy of the GNU General Public License
32  * along with this program. If not, see <https://www.gnu.org/licenses/>.
33  */
34 
45 abstract class CommonObject
46 {
47  const TRIGGER_PREFIX = ''; // to be overriden in child class implementations, i.e. 'BILL', 'TASK', 'PROPAL', etc.
51  public $db;
52 
56  public $id;
57 
61  public $entity;
62 
67  public $error;
68 
72  public $errorhidden;
73 
77  public $errors = array();
78 
82  private $validateFieldsErrors = array();
83 
87  public $element;
88 
93  public $element_for_permission;
94 
98  public $table_element;
99 
103  public $table_element_line = '';
104 
108  public $import_key;
109 
113  public $array_options = array();
114 
118  public $array_languages = null; // Value is array() when load already tried
119 
123  public $contacts_ids;
124 
128  public $linked_objects;
129 
133  public $linkedObjectsIds;
134 
138  public $linkedObjects;
139 
143  private $linkedObjectsFullLoaded = array();
144 
148  public $oldcopy;
149 
153  protected $table_ref_field = '';
154 
158  public $restrictiononfksoc = 0;
159 
160 
161  // Following vars are used by some objects only. We keep this property here in CommonObject to be able to provide common method using them.
162 
166  public $context = array();
167 
171  public $canvas;
172 
177  public $project;
178 
183  public $fk_project;
184 
189  public $projet;
190 
195  public $fk_projet;
196 
201  public $contact;
202 
207  public $contact_id;
208 
213  public $thirdparty;
214 
219  public $user;
220 
225  public $origin;
226 
231  public $origin_id;
232 
236  public $ref;
237 
241  public $ref_ext;
242 
246  public $ref_previous;
247 
251  public $ref_next;
252 
256  public $newref;
257 
262  public $statut;
263 
268  public $status;
269 
270 
275  public $country;
276 
281  public $country_id;
282 
287  public $country_code;
288 
293  public $state;
294 
299  public $state_id;
300 
305  public $state_code;
306 
311  public $region_id;
312 
317  public $region_code;
318 
323  public $region;
324 
325 
330  public $barcode_type;
331 
336  public $barcode_type_code;
337 
342  public $barcode_type_label;
343 
348  public $barcode_type_coder;
349 
354  public $mode_reglement_id;
355 
360  public $cond_reglement_id;
361 
365  public $demand_reason_id;
366 
371  public $transport_mode_id;
372 
378  public $cond_reglement;
379 
385  public $fk_delivery_address;
386 
391  public $shipping_method_id;
392 
397  public $model_pdf;
398 
404  public $modelpdf;
405 
410  public $last_main_doc;
411 
417  public $fk_bank;
418 
423  public $fk_account;
424 
428  public $openid;
429 
434  public $note_public;
435 
440  public $note_private;
441 
446  public $note;
447 
452  public $total_ht;
453 
458  public $total_tva;
459 
464  public $total_localtax1;
465 
470  public $total_localtax2;
471 
476  public $total_ttc;
477 
481  public $lines;
482 
487  public $comments = array();
488 
492  public $name;
493 
497  public $lastname;
498 
502  public $firstname;
503 
507  public $civility_id;
508 
509  // Dates
513  public $date_creation;
514 
518  public $date_validation; // Date validation
519 
523  public $date_modification; // Date last change (tms field)
524 
528  public $date_cloture; // Date closing (tms field)
529 
534  public $user_author;
539  public $user_creation;
543  public $user_creation_id;
544 
549  public $user_valid;
554  public $user_validation;
558  public $user_validation_id;
562  public $user_closing_id;
563 
568  public $user_modification;
572  public $user_modification_id;
573 
574 
575  public $next_prev_filter;
576 
580  public $specimen = 0;
581 
585  public $sendtoid;
586 
590  public $alreadypaid;
591 
592 
593  protected $labelStatus;
594  protected $labelStatusShort;
595 
599  public $showphoto_on_popup;
600 
604  public $nb = array();
605 
609  public $output;
610 
614  protected $childtables = array();
615 
621  protected $childtablesoncascade = array();
622 
623 
624  // No constructor as it is an abstract class
625 
626 
637  public static function isExistingObject($element, $id, $ref = '', $ref_ext = '')
638  {
639  global $db, $conf;
640 
641  $sql = "SELECT rowid, ref, ref_ext";
642  $sql .= " FROM ".$db->prefix().$element;
643  $sql .= " WHERE entity IN (".getEntity($element).")";
644 
645  if ($id > 0) {
646  $sql .= " AND rowid = ".((int) $id);
647  } elseif ($ref) {
648  $sql .= " AND ref = '".$db->escape($ref)."'";
649  } elseif ($ref_ext) {
650  $sql .= " AND ref_ext = '".$db->escape($ref_ext)."'";
651  } else {
652  $error = 'ErrorWrongParameters';
653  dol_print_error(get_class()."::isExistingObject ".$error, LOG_ERR);
654  return -1;
655  }
656  if ($ref || $ref_ext) { // Because the same ref can exists in 2 different entities, we force the current one in priority
657  $sql .= " AND entity = ".((int) $conf->entity);
658  }
659 
660  dol_syslog(get_class()."::isExistingObject", LOG_DEBUG);
661  $resql = $db->query($sql);
662  if ($resql) {
663  $num = $db->num_rows($resql);
664  if ($num > 0) {
665  return 1;
666  } else {
667  return 0;
668  }
669  }
670  return -1;
671  }
672 
679  public function setErrorsFromObject($object)
680  {
681  if (!empty($object->error)) {
682  $this->error = $object->error;
683  }
684  if (!empty($object->errors)) {
685  $this->errors = array_merge($this->errors, $object->errors);
686  }
687  }
688 
696  public function getTooltipContentArray($params)
697  {
698  return [];
699  }
700 
708  public function getTooltipContent($params)
709  {
710  global $action, $extrafields, $langs, $hookmanager;
711 
712  $datas = $this->getTooltipContentArray($params);
713 
714  if (!empty($extrafields->attributes[$this->table_element]['label'])) {
715  foreach ($extrafields->attributes[$this->table_element]['label'] as $key => $val) {
716  if (!empty($extrafields->attributes[$this->table_element]['langfile'][$key])) {
717  $langs->load($extrafields->attributes[$this->table_element]['langfile'][$key]);
718  }
719  $labelextra = $langs->trans((string) $extrafields->attributes[$this->table_element]['label'][$key]);
720  if ($extrafields->attributes[$this->table_element]['type'][$key] == 'separate') {
721  $datas[$key]= '<br><b><u>'. $labelextra . '</u></b>';
722  } else {
723  $value = $this->array_options['options_' . $key];
724  $datas[$key]= '<br><b>'. $labelextra . ':</b> ' . $extrafields->showOutputField($key, $value, '', $this->table_element);
725  }
726  }
727  }
728 
729  $hookmanager->initHooks(array($this->element . 'dao'));
730  $parameters = array(
731  'tooltipcontentarray' => &$datas
732  );
733  // Note that $action and $object may have been modified by some hooks
734  $hookmanager->executeHooks('getTooltipContent', $parameters, $this, $action);
735 
736  $label = implode($datas);
737 
738  return $label;
739  }
740 
741 
747  public function errorsToString()
748  {
749  return $this->error.(is_array($this->errors) ? (($this->error != '' ? ', ' : '').join(', ', $this->errors)) : '');
750  }
751 
752 
759  public function getFormatedCustomerRef($objref)
760  {
761  global $hookmanager;
762 
763  $parameters = array('objref'=>$objref);
764  $action = '';
765  $reshook = $hookmanager->executeHooks('getFormatedCustomerRef', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
766  if ($reshook > 0) {
767  return $hookmanager->resArray['objref'];
768  }
769  return $objref.(isset($hookmanager->resArray['objref']) ? $hookmanager->resArray['objref'] : '');
770  }
771 
778  public function getFormatedSupplierRef($objref)
779  {
780  global $hookmanager;
781 
782  $parameters = array('objref'=>$objref);
783  $action = '';
784  $reshook = $hookmanager->executeHooks('getFormatedSupplierRef', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
785  if ($reshook > 0) {
786  return $hookmanager->resArray['objref'];
787  }
788  return $objref.(isset($hookmanager->resArray['objref']) ? $hookmanager->resArray['objref'] : '');
789  }
790 
800  public function getFullName($langs, $option = 0, $nameorder = -1, $maxlen = 0)
801  {
802  //print "lastname=".$this->lastname." name=".$this->name." nom=".$this->nom."<br>\n";
803  $lastname = $this->lastname;
804  $firstname = $this->firstname;
805  if (empty($lastname)) {
806  $lastname = (isset($this->lastname) ? $this->lastname : (isset($this->name) ? $this->name : (isset($this->nom) ? $this->nom : (isset($this->societe) ? $this->societe : (isset($this->company) ? $this->company : '')))));
807  }
808 
809  $ret = '';
810  if (!empty($option) && !empty($this->civility_code)) {
811  if ($langs->transnoentitiesnoconv("Civility".$this->civility_code) != "Civility".$this->civility_code) {
812  $ret .= $langs->transnoentitiesnoconv("Civility".$this->civility_code).' ';
813  } else {
814  $ret .= $this->civility_code.' ';
815  }
816  }
817 
818  $ret .= dolGetFirstLastname($firstname, $lastname, $nameorder);
819 
820  return dol_trunc($ret, $maxlen);
821  }
822 
828  public function setUpperOrLowerCase()
829  {
830  global $conf;
831 
832  if (!empty($conf->global->MAIN_FIRST_TO_UPPER)) {
833  $this->lastname = dol_ucwords(dol_strtolower($this->lastname));
834  $this->firstname = dol_ucwords(dol_strtolower($this->firstname));
835  $this->name = dol_ucwords(dol_strtolower($this->name));
836  $this->name_alias = isset($this->name_alias)?dol_ucwords(dol_strtolower($this->name_alias)):'';
837  }
838  if (!empty($conf->global->MAIN_ALL_TO_UPPER)) {
839  $this->lastname = dol_strtoupper($this->lastname);
840  $this->name = dol_strtoupper($this->name);
841  $this->name_alias = dol_strtoupper($this->name_alias);
842  }
843  if (!empty($conf->global->MAIN_ALL_TOWN_TO_UPPER)) {
844  $this->address = dol_strtoupper($this->address);
845  $this->town = dol_strtoupper($this->town);
846  }
847  if (isset($this->email)) {
848  $this->email = dol_strtolower($this->email);
849  }
850  if (isset($this->personal_email)) {
851  $this->personal_email = dol_strtolower($this->personal_email);
852  }
853  }
854 
864  public function getFullAddress($withcountry = 0, $sep = "\n", $withregion = 0, $extralangcode = '')
865  {
866  if ($withcountry && $this->country_id && (empty($this->country_code) || empty($this->country))) {
867  require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
868  $tmparray = getCountry($this->country_id, 'all');
869  $this->country_code = $tmparray['code'];
870  $this->country = $tmparray['label'];
871  }
872 
873  if ($withregion && $this->state_id && (empty($this->state_code) || empty($this->state) || empty($this->region) || empty($this->region_code))) {
874  require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
875  $tmparray = getState($this->state_id, 'all', 0, 1);
876  $this->state_code = $tmparray['code'];
877  $this->state = $tmparray['label'];
878  $this->region_code = $tmparray['region_code'];
879  $this->region = $tmparray['region'];
880  }
881 
882  return dol_format_address($this, $withcountry, $sep, '', 0, $extralangcode);
883  }
884 
885 
893  public function getBannerAddress($htmlkey, $object)
894  {
895  global $conf, $langs, $form, $extralanguages;
896 
897  $countriesusingstate = array('AU', 'US', 'IN', 'GB', 'ES', 'UK', 'TR'); // See also option MAIN_FORCE_STATE_INTO_ADDRESS
898 
899  $contactid = 0;
900  $thirdpartyid = 0;
901  $elementforaltlanguage = $this->element;
902  if ($this->element == 'societe') {
903  $thirdpartyid = $this->id;
904  }
905  if ($this->element == 'contact') {
906  $contactid = $this->id;
907  $thirdpartyid = empty($this->fk_soc) ? 0 : $this->fk_soc;
908  }
909  if ($this->element == 'user') {
910  $contactid = $this->contact_id;
911  $thirdpartyid = empty($object->fk_soc) ? 0 : $object->fk_soc;
912  }
913 
914  $out = '';
915 
916  $outdone = 0;
917  $coords = $this->getFullAddress(1, ', ', (!empty($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT) ? $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT : 0));
918  if ($coords) {
919  if (!empty($conf->use_javascript_ajax)) {
920  // Add picto with tooltip on map
921  $namecoords = '';
922  if ($this->element == 'contact' && !empty($conf->global->MAIN_SHOW_COMPANY_NAME_IN_BANNER_ADDRESS)) {
923  $namecoords .= $object->name.'<br>';
924  }
925  $namecoords .= $this->getFullName($langs, 1).'<br>'.$coords;
926  // hideonsmatphone because copyToClipboard call jquery dialog that does not work with jmobile
927  $out .= '<a href="#" class="hideonsmartphone" onclick="return copyToClipboard(\''.dol_escape_js($namecoords).'\',\''.dol_escape_js($langs->trans("HelpCopyToClipboard")).'\');">';
928  $out .= img_picto($langs->trans("Address"), 'map-marker-alt');
929  $out .= '</a> ';
930  }
931  $address = dol_print_address($coords, 'address_'.$htmlkey.'_'.$this->id, $this->element, $this->id, 1, ', ');
932  if ($address) {
933  $out .= $address;
934  $outdone++;
935  }
936  $outdone++;
937 
938  // List of extra languages
939  $arrayoflangcode = array();
940  if (!empty($conf->global->PDF_USE_ALSO_LANGUAGE_CODE)) {
941  $arrayoflangcode[] = $conf->global->PDF_USE_ALSO_LANGUAGE_CODE;
942  }
943 
944  if (is_array($arrayoflangcode) && count($arrayoflangcode)) {
945  if (!is_object($extralanguages)) {
946  include_once DOL_DOCUMENT_ROOT.'/core/class/extralanguages.class.php';
947  $extralanguages = new ExtraLanguages($this->db);
948  }
949  $extralanguages->fetch_name_extralanguages($elementforaltlanguage);
950 
951  if (!empty($extralanguages->attributes[$elementforaltlanguage]['address']) || !empty($extralanguages->attributes[$elementforaltlanguage]['town'])) {
952  $out .= "<!-- alternatelanguage for '".$elementforaltlanguage."' set to fields '".join(',', $extralanguages->attributes[$elementforaltlanguage])."' -->\n";
953  $this->fetchValuesForExtraLanguages();
954  if (!is_object($form)) {
955  $form = new Form($this->db);
956  }
957  $htmltext = '';
958  // If there is extra languages
959  foreach ($arrayoflangcode as $extralangcode) {
960  $s = picto_from_langcode($extralangcode, 'class="pictoforlang paddingright"');
961  // This also call dol_format_address()
962  $coords = $this->getFullAddress(1, ', ', $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT, $extralangcode);
963  $htmltext .= $s.dol_print_address($coords, 'address_'.$htmlkey.'_'.$this->id, $this->element, $this->id, 1, ', ');
964  }
965  $out .= $form->textwithpicto('', $htmltext, -1, 'language', 'opacitymedium paddingleft');
966  }
967  }
968  }
969 
970  // If MAIN_FORCE_STATE_INTO_ADDRESS is on, state is already returned previously with getFullAddress
971  if (!in_array($this->country_code, $countriesusingstate) && empty($conf->global->MAIN_FORCE_STATE_INTO_ADDRESS)
972  && empty($conf->global->SOCIETE_DISABLE_STATE) && $this->state) {
973  if (!empty($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT) && $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT == 1 && $this->region) {
974  $out .= ($outdone ? ' - ' : '').$this->region.' - '.$this->state;
975  } else {
976  $out .= ($outdone ? ' - ' : '').$this->state;
977  }
978  $outdone++;
979  }
980 
981  if ($outdone) {
982  $out = '<div class="address inline-block">'.$out.'</div>';
983  }
984 
985  if (!empty($this->phone) || !empty($this->phone_pro) || !empty($this->phone_mobile) || !empty($this->phone_perso) || !empty($this->fax) || !empty($this->office_phone) || !empty($this->user_mobile) || !empty($this->office_fax)) {
986  $out .= ($outdone ? '<br>' : '');
987  }
988  if (!empty($this->phone) && empty($this->phone_pro)) { // For objects that store pro phone into ->phone
989  $out .= dol_print_phone($this->phone, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'phone', $langs->trans("PhonePro"));
990  $outdone++;
991  }
992  if (!empty($this->phone_pro)) {
993  $out .= dol_print_phone($this->phone_pro, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'phone', $langs->trans("PhonePro"));
994  $outdone++;
995  }
996  if (!empty($this->phone_mobile)) {
997  $out .= dol_print_phone($this->phone_mobile, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'mobile', $langs->trans("PhoneMobile"));
998  $outdone++;
999  }
1000  if (!empty($this->phone_perso)) {
1001  $out .= dol_print_phone($this->phone_perso, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'phone', $langs->trans("PhonePerso"));
1002  $outdone++;
1003  }
1004  if (!empty($this->office_phone)) {
1005  $out .= dol_print_phone($this->office_phone, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'phone', $langs->trans("PhonePro"));
1006  $outdone++;
1007  }
1008  if (!empty($this->user_mobile)) {
1009  $out .= dol_print_phone($this->user_mobile, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'mobile', $langs->trans("PhoneMobile"));
1010  $outdone++;
1011  }
1012  if (!empty($this->fax)) {
1013  $out .= dol_print_phone($this->fax, $this->country_code, $contactid, $thirdpartyid, 'AC_FAX', '&nbsp;', 'fax', $langs->trans("Fax"));
1014  $outdone++;
1015  }
1016  if (!empty($this->office_fax)) {
1017  $out .= dol_print_phone($this->office_fax, $this->country_code, $contactid, $thirdpartyid, 'AC_FAX', '&nbsp;', 'fax', $langs->trans("Fax"));
1018  $outdone++;
1019  }
1020 
1021  if ($out) {
1022  $out .= '<div style="clear: both;"></div>';
1023  }
1024  $outdone = 0;
1025  if (!empty($this->email)) {
1026  $out .= dol_print_email($this->email, $this->id, $object->id, 'AC_EMAIL', 0, 0, 1);
1027  $outdone++;
1028  }
1029  if (!empty($this->url)) {
1030  //$out.=dol_print_url($this->url,'_goout',0,1);//steve changed to blank
1031  $out .= dol_print_url($this->url, '_blank', 0, 1);
1032  $outdone++;
1033  }
1034 
1035  if (isModEnabled('socialnetworks')) {
1036  $outsocialnetwork = '';
1037 
1038  if (!empty($this->socialnetworks) && is_array($this->socialnetworks) && count($this->socialnetworks) > 0) {
1039  $socialnetworksdict = getArrayOfSocialNetworks();
1040  foreach ($this->socialnetworks as $key => $value) {
1041  if ($value) {
1042  $outsocialnetwork .= dol_print_socialnetworks($value, $this->id, $object->id, $key, $socialnetworksdict);
1043  }
1044  $outdone++;
1045  }
1046  }
1047 
1048  if ($outsocialnetwork) {
1049  $out .= '<div style="clear: both;">'.$outsocialnetwork.'</div>';
1050  }
1051  }
1052 
1053  if ($out) {
1054  return '<!-- BEGIN part to show address block -->'."\n".$out.'<!-- END Part to show address block -->'."\n";
1055  } else {
1056  return '';
1057  }
1058  }
1059 
1068  public function getLastMainDocLink($modulepart, $initsharekey = 0, $relativelink = 0)
1069  {
1070  global $user, $dolibarr_main_url_root;
1071 
1072  if (empty($this->last_main_doc)) {
1073  return ''; // No way to known which document name to use
1074  }
1075 
1076  include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
1077  $ecmfile = new EcmFiles($this->db);
1078  $result = $ecmfile->fetch(0, '', $this->last_main_doc);
1079  if ($result < 0) {
1080  $this->error = $ecmfile->error;
1081  $this->errors = $ecmfile->errors;
1082  return -1;
1083  }
1084 
1085  if (empty($ecmfile->id)) {
1086  // Add entry into index
1087  if ($initsharekey) {
1088  require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
1089 
1090  // TODO We can't, we dont' have full path of file, only last_main_doc and ->element, so we must first rebuild full path $destfull
1091  /*
1092  $ecmfile->filepath = $rel_dir;
1093  $ecmfile->filename = $filename;
1094  $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
1095  $ecmfile->fullpath_orig = '';
1096  $ecmfile->gen_or_uploaded = 'generated';
1097  $ecmfile->description = ''; // indexed content
1098  $ecmfile->keywords = ''; // keyword content
1099  $ecmfile->share = getRandomPassword(true);
1100  $result = $ecmfile->create($user);
1101  if ($result < 0)
1102  {
1103  $this->error = $ecmfile->error;
1104  $this->errors = $ecmfile->errors;
1105  }
1106  */
1107  } else {
1108  return '';
1109  }
1110  } elseif (empty($ecmfile->share)) {
1111  // Add entry into index
1112  if ($initsharekey) {
1113  require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
1114  $ecmfile->share = getRandomPassword(true);
1115  $ecmfile->update($user);
1116  } else {
1117  return '';
1118  }
1119  }
1120  // Define $urlwithroot
1121  $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
1122  // This is to use external domain name found into config file
1123  //if (DOL_URL_ROOT && ! preg_match('/\/$/', $urlwithouturlroot) && ! preg_match('/^\//', DOL_URL_ROOT)) $urlwithroot=$urlwithouturlroot.'/'.DOL_URL_ROOT;
1124  //else
1125  $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT;
1126  //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
1127 
1128  $forcedownload = 0;
1129 
1130  $paramlink = '';
1131  //if (!empty($modulepart)) $paramlink.=($paramlink?'&':'').'modulepart='.$modulepart; // For sharing with hash (so public files), modulepart is not required.
1132  //if (!empty($ecmfile->entity)) $paramlink.='&entity='.$ecmfile->entity; // For sharing with hash (so public files), entity is not required.
1133  //$paramlink.=($paramlink?'&':'').'file='.urlencode($filepath); // No need of name of file for public link, we will use the hash
1134  if (!empty($ecmfile->share)) {
1135  $paramlink .= ($paramlink ? '&' : '').'hashp='.$ecmfile->share; // Hash for public share
1136  }
1137  if ($forcedownload) {
1138  $paramlink .= ($paramlink ? '&' : '').'attachment=1';
1139  }
1140 
1141  if ($relativelink) {
1142  $linktoreturn = 'document.php'.($paramlink ? '?'.$paramlink : '');
1143  } else {
1144  $linktoreturn = $urlwithroot.'/document.php'.($paramlink ? '?'.$paramlink : '');
1145  }
1146 
1147  // Here $ecmfile->share is defined
1148  return $linktoreturn;
1149  }
1150 
1151 
1152  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1162  public function add_contact($fk_socpeople, $type_contact, $source = 'external', $notrigger = 0)
1163  {
1164  // phpcs:enable
1165  global $user, $langs;
1166 
1167 
1168  dol_syslog(get_class($this)."::add_contact $fk_socpeople, $type_contact, $source, $notrigger");
1169 
1170  // Check parameters
1171  if ($fk_socpeople <= 0) {
1172  $langs->load("errors");
1173  $this->error = $langs->trans("ErrorWrongValueForParameterX", "1");
1174  dol_syslog(get_class($this)."::add_contact ".$this->error, LOG_ERR);
1175  return -1;
1176  }
1177  if (!$type_contact) {
1178  $langs->load("errors");
1179  $this->error = $langs->trans("ErrorWrongValueForParameterX", "2");
1180  dol_syslog(get_class($this)."::add_contact ".$this->error, LOG_ERR);
1181  return -2;
1182  }
1183 
1184  $id_type_contact = 0;
1185  if (is_numeric($type_contact)) {
1186  $id_type_contact = $type_contact;
1187  } else {
1188  // We look for id type_contact
1189  $sql = "SELECT tc.rowid";
1190  $sql .= " FROM ".$this->db->prefix()."c_type_contact as tc";
1191  $sql .= " WHERE tc.element='".$this->db->escape($this->element)."'";
1192  $sql .= " AND tc.source='".$this->db->escape($source)."'";
1193  $sql .= " AND tc.code='".$this->db->escape($type_contact)."' AND tc.active=1";
1194  //print $sql;
1195  $resql = $this->db->query($sql);
1196  if ($resql) {
1197  $obj = $this->db->fetch_object($resql);
1198  if ($obj) {
1199  $id_type_contact = $obj->rowid;
1200  }
1201  }
1202  }
1203 
1204  if ($id_type_contact == 0) {
1205  $this->error = 'CODE_NOT_VALID_FOR_THIS_ELEMENT';
1206  dol_syslog("CODE_NOT_VALID_FOR_THIS_ELEMENT: Code type of contact '".$type_contact."' does not exists or is not active for element ".$this->element.", we can ignore it");
1207  return -3;
1208  }
1209 
1210  $datecreate = dol_now();
1211 
1212  // Socpeople must have already been added by some trigger, then we have to check it to avoid DB_ERROR_RECORD_ALREADY_EXISTS error
1213  $TListeContacts = $this->liste_contact(-1, $source);
1214  $already_added = false;
1215  if (is_array($TListeContacts) && !empty($TListeContacts)) {
1216  foreach ($TListeContacts as $array_contact) {
1217  if ($array_contact['status'] == 4 && $array_contact['id'] == $fk_socpeople && $array_contact['fk_c_type_contact'] == $id_type_contact) {
1218  $already_added = true;
1219  break;
1220  }
1221  }
1222  }
1223 
1224  if (!$already_added) {
1225  $this->db->begin();
1226 
1227  // Insert into database
1228  $sql = "INSERT INTO ".$this->db->prefix()."element_contact";
1229  $sql .= " (element_id, fk_socpeople, datecreate, statut, fk_c_type_contact) ";
1230  $sql .= " VALUES (".$this->id.", ".((int) $fk_socpeople)." , ";
1231  $sql .= "'".$this->db->idate($datecreate)."'";
1232  $sql .= ", 4, ".((int) $id_type_contact);
1233  $sql .= ")";
1234 
1235  $resql = $this->db->query($sql);
1236  if ($resql) {
1237  if (!$notrigger) {
1238  $result = $this->call_trigger(strtoupper($this->element).'_ADD_CONTACT', $user);
1239  if ($result < 0) {
1240  $this->db->rollback();
1241  return -1;
1242  }
1243  }
1244 
1245  $this->db->commit();
1246  return 1;
1247  } else {
1248  if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
1249  $this->error = $this->db->errno();
1250  $this->db->rollback();
1251  return -2;
1252  } else {
1253  $this->error = $this->db->lasterror();
1254  $this->db->rollback();
1255  return -1;
1256  }
1257  }
1258  } else {
1259  return 0;
1260  }
1261  }
1262 
1263  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1271  public function copy_linked_contact($objFrom, $source = 'internal')
1272  {
1273  // phpcs:enable
1274  $contacts = $objFrom->liste_contact(-1, $source);
1275  foreach ($contacts as $contact) {
1276  if ($this->add_contact($contact['id'], $contact['fk_c_type_contact'], $contact['source']) < 0) {
1277  return -1;
1278  }
1279  }
1280  return 1;
1281  }
1282 
1283  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1293  public function update_contact($rowid, $statut, $type_contact_id = 0, $fk_socpeople = 0)
1294  {
1295  // phpcs:enable
1296  // Insert into database
1297  $sql = "UPDATE ".$this->db->prefix()."element_contact set";
1298  $sql .= " statut = ".$statut;
1299  if ($type_contact_id) {
1300  $sql .= ", fk_c_type_contact = ".((int) $type_contact_id);
1301  }
1302  if ($fk_socpeople) {
1303  $sql .= ", fk_socpeople = ".((int) $fk_socpeople);
1304  }
1305  $sql .= " where rowid = ".((int) $rowid);
1306  $resql = $this->db->query($sql);
1307  if ($resql) {
1308  return 0;
1309  } else {
1310  $this->error = $this->db->lasterror();
1311  return -1;
1312  }
1313  }
1314 
1315  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1323  public function delete_contact($rowid, $notrigger = 0)
1324  {
1325  // phpcs:enable
1326  global $user;
1327 
1328 
1329  $this->db->begin();
1330 
1331  $sql = "DELETE FROM ".$this->db->prefix()."element_contact";
1332  $sql .= " WHERE rowid = ".((int) $rowid);
1333 
1334  dol_syslog(get_class($this)."::delete_contact", LOG_DEBUG);
1335  if ($this->db->query($sql)) {
1336  if (!$notrigger) {
1337  $result = $this->call_trigger(strtoupper($this->element).'_DELETE_CONTACT', $user);
1338  if ($result < 0) {
1339  $this->db->rollback();
1340  return -1;
1341  }
1342  }
1343 
1344  $this->db->commit();
1345  return 1;
1346  } else {
1347  $this->error = $this->db->lasterror();
1348  $this->db->rollback();
1349  return -1;
1350  }
1351  }
1352 
1353  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1361  public function delete_linked_contact($source = '', $code = '')
1362  {
1363  // phpcs:enable
1364  $listId = '';
1365  $temp = array();
1366  $typeContact = $this->liste_type_contact($source, '', 0, 0, $code);
1367 
1368  if (!empty($typeContact)) {
1369  foreach ($typeContact as $key => $value) {
1370  array_push($temp, $key);
1371  }
1372  $listId = implode(",", $temp);
1373  }
1374 
1375  // If $listId is empty, we have not criteria on fk_c_type_contact so we will delete record on element_id for
1376  // any type or record instead of only the ones of the current object. So we do nothing in such a case.
1377  if (empty($listId)) {
1378  return 0;
1379  }
1380 
1381  $sql = "DELETE FROM ".$this->db->prefix()."element_contact";
1382  $sql .= " WHERE element_id = ".((int) $this->id);
1383  $sql .= " AND fk_c_type_contact IN (".$this->db->sanitize($listId).")";
1384 
1385  dol_syslog(get_class($this)."::delete_linked_contact", LOG_DEBUG);
1386  if ($this->db->query($sql)) {
1387  return 1;
1388  } else {
1389  $this->error = $this->db->lasterror();
1390  return -1;
1391  }
1392  }
1393 
1394  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1406  public function liste_contact($statusoflink = -1, $source = 'external', $list = 0, $code = '', $status = -1, $arrayoftcids = array())
1407  {
1408  // phpcs:enable
1409  global $langs;
1410 
1411  $tab = array();
1412 
1413  $sql = "SELECT ec.rowid, ec.statut as statuslink, ec.fk_socpeople as id, ec.fk_c_type_contact"; // This field contains id of llx_socpeople or id of llx_user
1414  if ($source == 'internal') {
1415  $sql .= ", '-1' as socid, t.statut as statuscontact, t.login, t.photo";
1416  }
1417  if ($source == 'external' || $source == 'thirdparty') {
1418  $sql .= ", t.fk_soc as socid, t.statut as statuscontact";
1419  }
1420  $sql .= ", t.civility as civility, t.lastname as lastname, t.firstname, t.email";
1421  $sql .= ", tc.source, tc.element, tc.code, tc.libelle";
1422  $sql .= " FROM ".$this->db->prefix()."c_type_contact tc,";
1423  $sql .= " ".$this->db->prefix()."element_contact ec";
1424  if ($source == 'internal') { // internal contact (user)
1425  $sql .= " LEFT JOIN ".$this->db->prefix()."user t on ec.fk_socpeople = t.rowid";
1426  }
1427  if ($source == 'external' || $source == 'thirdparty') { // external contact (socpeople)
1428  $sql .= " LEFT JOIN ".$this->db->prefix()."socpeople t on ec.fk_socpeople = t.rowid";
1429  }
1430  $sql .= " WHERE ec.element_id = ".((int) $this->id);
1431  $sql .= " AND ec.fk_c_type_contact = tc.rowid";
1432  $sql .= " AND tc.element = '".$this->db->escape($this->element)."'";
1433  if ($code) {
1434  $sql .= " AND tc.code = '".$this->db->escape($code)."'";
1435  }
1436  if ($source == 'internal') {
1437  $sql .= " AND tc.source = 'internal'";
1438  if ($status >= 0) {
1439  $sql .= " AND t.statut = ".((int) $status);
1440  }
1441  }
1442  if ($source == 'external' || $source == 'thirdparty') {
1443  $sql .= " AND tc.source = 'external'";
1444  if ($status >= 0) {
1445  $sql .= " AND t.statut = ".((int) $status); // t is llx_socpeople
1446  }
1447  }
1448  $sql .= " AND tc.active = 1";
1449  if ($statusoflink >= 0) {
1450  $sql .= " AND ec.statut = ".((int) $statusoflink);
1451  }
1452  $sql .= " ORDER BY t.lastname ASC";
1453 
1454  dol_syslog(get_class($this)."::liste_contact", LOG_DEBUG);
1455  $resql = $this->db->query($sql);
1456  if ($resql) {
1457  $num = $this->db->num_rows($resql);
1458  $i = 0;
1459  while ($i < $num) {
1460  $obj = $this->db->fetch_object($resql);
1461 
1462  if (!$list) {
1463  $transkey = "TypeContact_".$obj->element."_".$obj->source."_".$obj->code;
1464  $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle);
1465  $tab[$i] = array(
1466  'parentId' => $this->id,
1467  'source' => $obj->source,
1468  'socid' => $obj->socid,
1469  'id' => $obj->id,
1470  'nom' => $obj->lastname, // For backward compatibility
1471  'civility' => $obj->civility,
1472  'lastname' => $obj->lastname,
1473  'firstname' => $obj->firstname,
1474  'email'=>$obj->email,
1475  'login'=> (empty($obj->login) ? '' : $obj->login),
1476  'photo' => (empty($obj->photo) ? '' : $obj->photo),
1477  'statuscontact' => $obj->statuscontact,
1478  'rowid' => $obj->rowid,
1479  'code' => $obj->code,
1480  'libelle' => $libelle_type,
1481  'status' => $obj->statuslink,
1482  'fk_c_type_contact' => $obj->fk_c_type_contact
1483  );
1484  } else {
1485  $tab[$i] = $obj->id;
1486  }
1487 
1488  $i++;
1489  }
1490 
1491  return $tab;
1492  } else {
1493  $this->error = $this->db->lasterror();
1494  dol_print_error($this->db);
1495  return -1;
1496  }
1497  }
1498 
1499 
1506  public function swapContactStatus($rowid)
1507  {
1508  $sql = "SELECT ec.datecreate, ec.statut, ec.fk_socpeople, ec.fk_c_type_contact,";
1509  $sql .= " tc.code, tc.libelle";
1510  $sql .= " FROM (".$this->db->prefix()."element_contact as ec, ".$this->db->prefix()."c_type_contact as tc)";
1511  $sql .= " WHERE ec.rowid =".((int) $rowid);
1512  $sql .= " AND ec.fk_c_type_contact=tc.rowid";
1513  $sql .= " AND tc.element = '".$this->db->escape($this->element)."'";
1514 
1515  dol_syslog(get_class($this)."::swapContactStatus", LOG_DEBUG);
1516  $resql = $this->db->query($sql);
1517  if ($resql) {
1518  $obj = $this->db->fetch_object($resql);
1519  $newstatut = ($obj->statut == 4) ? 5 : 4;
1520  $result = $this->update_contact($rowid, $newstatut);
1521  $this->db->free($resql);
1522  return $result;
1523  } else {
1524  $this->error = $this->db->error();
1525  dol_print_error($this->db);
1526  return -1;
1527  }
1528  }
1529 
1530  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1541  public function liste_type_contact($source = 'internal', $order = 'position', $option = 0, $activeonly = 0, $code = '')
1542  {
1543  // phpcs:enable
1544  global $langs;
1545 
1546  if (empty($order)) {
1547  $order = 'position';
1548  }
1549  if ($order == 'position') {
1550  $order .= ',code';
1551  }
1552 
1553  $tab = array();
1554  $sql = "SELECT DISTINCT tc.rowid, tc.code, tc.libelle, tc.position";
1555  $sql .= " FROM ".$this->db->prefix()."c_type_contact as tc";
1556  $sql .= " WHERE tc.element='".$this->db->escape($this->element)."'";
1557  if ($activeonly == 1) {
1558  $sql .= " AND tc.active=1"; // only the active types
1559  }
1560  if (!empty($source) && $source != 'all') {
1561  $sql .= " AND tc.source='".$this->db->escape($source)."'";
1562  }
1563  if (!empty($code)) {
1564  $sql .= " AND tc.code='".$this->db->escape($code)."'";
1565  }
1566  $sql .= $this->db->order($order, 'ASC');
1567 
1568  //print "sql=".$sql;
1569  $resql = $this->db->query($sql);
1570  if ($resql) {
1571  $num = $this->db->num_rows($resql);
1572  $i = 0;
1573  while ($i < $num) {
1574  $obj = $this->db->fetch_object($resql);
1575 
1576  $transkey = "TypeContact_".$this->element."_".$source."_".$obj->code;
1577  $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle);
1578  if (empty($option)) {
1579  $tab[$obj->rowid] = $libelle_type;
1580  } else {
1581  $tab[$obj->code] = $libelle_type;
1582  }
1583  $i++;
1584  }
1585  return $tab;
1586  } else {
1587  $this->error = $this->db->lasterror();
1588  //dol_print_error($this->db);
1589  return null;
1590  }
1591  }
1592 
1604  public function listeTypeContacts($source = 'internal', $option = 0, $activeonly = 0, $code = '', $element = '', $excludeelement = '')
1605  {
1606  global $langs, $conf;
1607 
1608  $langs->loadLangs(array('bills', 'contracts', 'interventions', 'orders', 'projects', 'propal', 'ticket', 'agenda'));
1609 
1610  $tab = array();
1611 
1612  $sql = "SELECT DISTINCT tc.rowid, tc.code, tc.libelle, tc.position, tc.element";
1613  $sql .= " FROM ".$this->db->prefix()."c_type_contact as tc";
1614 
1615  $sqlWhere = array();
1616  if (!empty($element)) {
1617  $sqlWhere[] = " tc.element='".$this->db->escape($element)."'";
1618  }
1619  if (!empty($excludeelement)) {
1620  $sqlWhere[] = " tc.element <> '".$this->db->escape($excludeelement)."'";
1621  }
1622 
1623  if ($activeonly == 1) {
1624  $sqlWhere[] = " tc.active=1"; // only the active types
1625  }
1626 
1627  if (!empty($source) && $source != 'all') {
1628  $sqlWhere[] = " tc.source='".$this->db->escape($source)."'";
1629  }
1630 
1631  if (!empty($code)) {
1632  $sqlWhere[] = " tc.code='".$this->db->escape($code)."'";
1633  }
1634 
1635  if (count($sqlWhere) > 0) {
1636  $sql .= " WHERE ".implode(' AND ', $sqlWhere);
1637  }
1638 
1639  $sql .= $this->db->order('tc.element, tc.position', 'ASC');
1640 
1641  dol_syslog(__METHOD__, LOG_DEBUG);
1642  $resql = $this->db->query($sql);
1643  if ($resql) {
1644  $num = $this->db->num_rows($resql);
1645  if ($num > 0) {
1646  $langs->loadLangs(array("propal", "orders", "bills", "suppliers", "contracts", "supplier_proposal"));
1647 
1648  while ($obj = $this->db->fetch_object($resql)) {
1649  $modulename = $obj->element;
1650  if (strpos($obj->element, 'project') !== false) {
1651  $modulename = 'projet';
1652  } elseif ($obj->element == 'contrat') {
1653  $element = 'contract';
1654  } elseif ($obj->element == 'action') {
1655  $modulename = 'agenda';
1656  } elseif (strpos($obj->element, 'supplier') !== false && $obj->element != 'supplier_proposal') {
1657  $modulename = 'fournisseur';
1658  } elseif (strpos($obj->element, 'supplier') !== false && $obj->element != 'supplier_proposal') {
1659  $modulename = 'fournisseur';
1660  }
1661  if (!empty($conf->{$modulename}->enabled)) {
1662  $libelle_element = $langs->trans('ContactDefault_'.$obj->element);
1663  $tmpelement = $obj->element;
1664  $transkey = "TypeContact_".$tmpelement."_".$source."_".$obj->code;
1665  $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle);
1666  if (empty($option)) {
1667  $tab[$obj->rowid] = $libelle_element.' - '.$libelle_type;
1668  } else {
1669  $tab[$obj->rowid] = $libelle_element.' - '.$libelle_type;
1670  }
1671  }
1672  }
1673  }
1674  return $tab;
1675  } else {
1676  $this->error = $this->db->lasterror();
1677  return null;
1678  }
1679  }
1680 
1692  public function getIdContact($source, $code, $status = 0)
1693  {
1694  global $conf;
1695 
1696  $result = array();
1697  $i = 0;
1698  //cas particulier pour les expeditions
1699  if ($this->element == 'shipping' && $this->origin_id != 0) {
1700  $id = $this->origin_id;
1701  $element = 'commande';
1702  } elseif ($this->element == 'reception' && $this->origin_id != 0) {
1703  $id = $this->origin_id;
1704  $element = 'order_supplier';
1705  } else {
1706  $id = $this->id;
1707  $element = $this->element;
1708  }
1709 
1710  $sql = "SELECT ec.fk_socpeople";
1711  $sql .= " FROM ".$this->db->prefix()."element_contact as ec,";
1712  if ($source == 'internal') {
1713  $sql .= " ".$this->db->prefix()."user as c,";
1714  }
1715  if ($source == 'external') {
1716  $sql .= " ".$this->db->prefix()."socpeople as c,";
1717  }
1718  $sql .= " ".$this->db->prefix()."c_type_contact as tc";
1719  $sql .= " WHERE ec.element_id = ".((int) $id);
1720  $sql .= " AND ec.fk_socpeople = c.rowid";
1721  if ($source == 'internal') {
1722  $sql .= " AND c.entity IN (".getEntity('user').")";
1723  }
1724  if ($source == 'external') {
1725  $sql .= " AND c.entity IN (".getEntity('societe').")";
1726  }
1727  $sql .= " AND ec.fk_c_type_contact = tc.rowid";
1728  $sql .= " AND tc.element = '".$this->db->escape($element)."'";
1729  $sql .= " AND tc.source = '".$this->db->escape($source)."'";
1730  if ($code) {
1731  $sql .= " AND tc.code = '".$this->db->escape($code)."'";
1732  }
1733  $sql .= " AND tc.active = 1";
1734  if ($status) {
1735  $sql .= " AND ec.statut = ".((int) $status);
1736  }
1737 
1738  dol_syslog(get_class($this)."::getIdContact", LOG_DEBUG);
1739  $resql = $this->db->query($sql);
1740  if ($resql) {
1741  while ($obj = $this->db->fetch_object($resql)) {
1742  $result[$i] = $obj->fk_socpeople;
1743  $i++;
1744  }
1745  } else {
1746  $this->error = $this->db->error();
1747  return null;
1748  }
1749 
1750  return $result;
1751  }
1752 
1753  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1760  public function fetch_contact($contactid = null)
1761  {
1762  // phpcs:enable
1763  if (empty($contactid)) {
1764  $contactid = $this->contact_id;
1765  }
1766 
1767  if (empty($contactid)) {
1768  return 0;
1769  }
1770 
1771  require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
1772  $contact = new Contact($this->db);
1773  $result = $contact->fetch($contactid);
1774  $this->contact = $contact;
1775  return $result;
1776  }
1777 
1778  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1785  public function fetch_thirdparty($force_thirdparty_id = 0)
1786  {
1787  // phpcs:enable
1788  global $conf;
1789 
1790  if (empty($this->socid) && empty($this->fk_soc) && empty($force_thirdparty_id)) {
1791  return 0;
1792  }
1793 
1794  require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
1795 
1796  $idtofetch = isset($this->socid) ? $this->socid : (isset($this->fk_soc) ? $this->fk_soc : 0);
1797  if ($force_thirdparty_id) {
1798  $idtofetch = $force_thirdparty_id;
1799  }
1800 
1801  if ($idtofetch) {
1802  $thirdparty = new Societe($this->db);
1803  $result = $thirdparty->fetch($idtofetch);
1804  if ($result<0) {
1805  $this->errors=array_merge($this->errors, $thirdparty->errors);
1806  }
1807  $this->thirdparty = $thirdparty;
1808 
1809  // Use first price level if level not defined for third party
1810  if (!empty($conf->global->PRODUIT_MULTIPRICES) && empty($this->thirdparty->price_level)) {
1811  $this->thirdparty->price_level = 1;
1812  }
1813 
1814  return $result;
1815  } else {
1816  return -1;
1817  }
1818  }
1819 
1820 
1828  public function fetchOneLike($ref)
1829  {
1830  if (!$this->table_ref_field) {
1831  return 0;
1832  }
1833 
1834  $sql = "SELECT rowid FROM ".$this->db->prefix().$this->table_element." WHERE ".$this->table_ref_field." LIKE '".$this->db->escape($ref)."' LIMIT 1";
1835 
1836  $query = $this->db->query($sql);
1837 
1838  if (!$this->db->num_rows($query)) {
1839  return 0;
1840  }
1841 
1842  $result = $this->db->fetch_object($query);
1843 
1844  return $this->fetch($result->rowid);
1845  }
1846 
1847  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1855  public function fetch_barcode()
1856  {
1857  // phpcs:enable
1858  global $conf;
1859 
1860  dol_syslog(get_class($this).'::fetch_barcode this->element='.$this->element.' this->barcode_type='.$this->barcode_type);
1861 
1862  $idtype = $this->barcode_type;
1863  if (empty($idtype) && $idtype != '0') { // If type of barcode no set, we try to guess. If set to '0' it means we forced to have type remain not defined
1864  if ($this->element == 'product' && !empty($conf->global->PRODUIT_DEFAULT_BARCODE_TYPE)) {
1865  $idtype = $conf->global->PRODUIT_DEFAULT_BARCODE_TYPE;
1866  } elseif ($this->element == 'societe') {
1867  $idtype = $conf->global->GENBARCODE_BARCODETYPE_THIRDPARTY;
1868  } else {
1869  dol_syslog('Call fetch_barcode with barcode_type not defined and cant be guessed', LOG_WARNING);
1870  }
1871  }
1872 
1873  if ($idtype > 0) {
1874  if (empty($this->barcode_type) || empty($this->barcode_type_code) || empty($this->barcode_type_label) || empty($this->barcode_type_coder)) { // If data not already loaded
1875  $sql = "SELECT rowid, code, libelle as label, coder";
1876  $sql .= " FROM ".$this->db->prefix()."c_barcode_type";
1877  $sql .= " WHERE rowid = ".((int) $idtype);
1878  dol_syslog(get_class($this).'::fetch_barcode', LOG_DEBUG);
1879  $resql = $this->db->query($sql);
1880  if ($resql) {
1881  $obj = $this->db->fetch_object($resql);
1882  $this->barcode_type = $obj->rowid;
1883  $this->barcode_type_code = $obj->code;
1884  $this->barcode_type_label = $obj->label;
1885  $this->barcode_type_coder = $obj->coder;
1886  return 1;
1887  } else {
1888  dol_print_error($this->db);
1889  return -1;
1890  }
1891  }
1892  }
1893  return 0;
1894  }
1895 
1896  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1902  public function fetch_project()
1903  {
1904  // phpcs:enable
1905  return $this->fetch_projet();
1906  }
1907 
1908  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1914  public function fetch_projet()
1915  {
1916  // phpcs:enable
1917  include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
1918 
1919  if (empty($this->fk_project) && !empty($this->fk_projet)) {
1920  $this->fk_project = $this->fk_projet; // For backward compatibility
1921  }
1922  if (empty($this->fk_project)) {
1923  return 0;
1924  }
1925 
1926  $project = new Project($this->db);
1927  $result = $project->fetch($this->fk_project);
1928 
1929  $this->projet = $project; // deprecated
1930  $this->project = $project;
1931  return $result;
1932  }
1933 
1934  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1940  public function fetch_product()
1941  {
1942  // phpcs:enable
1943  include_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
1944 
1945  if (empty($this->fk_product)) {
1946  return 0;
1947  }
1948 
1949  $product = new Product($this->db);
1950  $result = $product->fetch($this->fk_product);
1951 
1952  $this->product = $product;
1953  return $result;
1954  }
1955 
1956  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1963  public function fetch_user($userid)
1964  {
1965  // phpcs:enable
1966  $user = new User($this->db);
1967  $result = $user->fetch($userid);
1968  $this->user = $user;
1969  return $result;
1970  }
1971 
1972  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1978  public function fetch_origin()
1979  {
1980  // phpcs:enable
1981  if ($this->origin == 'shipping') {
1982  $this->origin = 'expedition';
1983  }
1984  if ($this->origin == 'delivery') {
1985  $this->origin = 'livraison';
1986  }
1987  if ($this->origin == 'order_supplier') {
1988  $this->origin = 'commandeFournisseur';
1989  }
1990 
1991  $origin = $this->origin;
1992 
1993  $classname = ucfirst($origin);
1994  $this->$origin = new $classname($this->db);
1995  $this->$origin->fetch($this->origin_id);
1996  }
1997 
2007  public function fetchObjectFrom($table, $field, $key, $element = null)
2008  {
2009  global $conf;
2010 
2011  $result = false;
2012 
2013  $sql = "SELECT rowid FROM ".$this->db->prefix().$table;
2014  $sql .= " WHERE ".$field." = '".$this->db->escape($key)."'";
2015  if (!empty($element)) {
2016  $sql .= " AND entity IN (".getEntity($element).")";
2017  } else {
2018  $sql .= " AND entity = ".((int) $conf->entity);
2019  }
2020 
2021  dol_syslog(get_class($this).'::fetchObjectFrom', LOG_DEBUG);
2022  $resql = $this->db->query($sql);
2023  if ($resql) {
2024  $row = $this->db->fetch_row($resql);
2025  // Test for avoid error -1
2026  if ($row[0] > 0) {
2027  $result = $this->fetch($row[0]);
2028  }
2029  }
2030 
2031  return $result;
2032  }
2033 
2042  public function getValueFrom($table, $id, $field)
2043  {
2044  $result = false;
2045  if (!empty($id) && !empty($field) && !empty($table)) {
2046  $sql = "SELECT ".$field." FROM ".$this->db->prefix().$table;
2047  $sql .= " WHERE rowid = ".((int) $id);
2048 
2049  dol_syslog(get_class($this).'::getValueFrom', LOG_DEBUG);
2050  $resql = $this->db->query($sql);
2051  if ($resql) {
2052  $row = $this->db->fetch_row($resql);
2053  $result = $row[0];
2054  }
2055  }
2056  return $result;
2057  }
2058 
2075  public function setValueFrom($field, $value, $table = '', $id = null, $format = '', $id_field = '', $fuser = null, $trigkey = '', $fk_user_field = 'fk_user_modif')
2076  {
2077  global $user, $langs, $conf;
2078 
2079  if (empty($table)) {
2080  $table = $this->table_element;
2081  }
2082  if (empty($id)) {
2083  $id = $this->id;
2084  }
2085  if (empty($format)) {
2086  $format = 'text';
2087  }
2088  if (empty($id_field)) {
2089  $id_field = 'rowid';
2090  }
2091 
2092  $error = 0;
2093 
2094  $this->db->begin();
2095 
2096  // Special case
2097  if ($table == 'product' && $field == 'note_private') {
2098  $field = 'note';
2099  }
2100  if (in_array($table, array('actioncomm', 'adherent', 'advtargetemailing', 'cronjob', 'establishment'))) {
2101  $fk_user_field = 'fk_user_mod';
2102  }
2103 
2104  $sql = "UPDATE ".$this->db->prefix().$table." SET ";
2105 
2106  if ($format == 'text') {
2107  $sql .= $field." = '".$this->db->escape($value)."'";
2108  } elseif ($format == 'int') {
2109  $sql .= $field." = ".((int) $value);
2110  } elseif ($format == 'date') {
2111  $sql .= $field." = ".($value ? "'".$this->db->idate($value)."'" : "null");
2112  } elseif ($format == 'dategmt') {
2113  $sql .= $field." = ".($value ? "'".$this->db->idate($value, 'gmt')."'" : "null");
2114  }
2115 
2116  if ($fk_user_field) {
2117  if (!empty($fuser) && is_object($fuser)) {
2118  $sql .= ", ".$fk_user_field." = ".((int) $fuser->id);
2119  } elseif (empty($fuser) || $fuser != 'none') {
2120  $sql .= ", ".$fk_user_field." = ".((int) $user->id);
2121  }
2122  }
2123 
2124  $sql .= " WHERE ".$id_field." = ".((int) $id);
2125 
2126  dol_syslog(__METHOD__, LOG_DEBUG);
2127  $resql = $this->db->query($sql);
2128  if ($resql) {
2129  if ($trigkey) {
2130  // call trigger with updated object values
2131  if (method_exists($this, 'fetch')) {
2132  $result = $this->fetch($id);
2133  } else {
2134  $result = $this->fetchCommon($id);
2135  }
2136  if ($result >= 0) {
2137  $result = $this->call_trigger($trigkey, (!empty($fuser) && is_object($fuser)) ? $fuser : $user); // This may set this->errors
2138  }
2139  if ($result < 0) {
2140  $error++;
2141  }
2142  }
2143 
2144  if (!$error) {
2145  if (property_exists($this, $field)) {
2146  $this->$field = $value;
2147  }
2148  $this->db->commit();
2149  return 1;
2150  } else {
2151  $this->db->rollback();
2152  return -2;
2153  }
2154  } else {
2155  if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
2156  $this->error = 'DB_ERROR_RECORD_ALREADY_EXISTS';
2157  } else {
2158  $this->error = $this->db->lasterror();
2159  }
2160  $this->db->rollback();
2161  return -1;
2162  }
2163  }
2164 
2165  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2174  public function load_previous_next_ref($filter, $fieldid, $nodbprefix = 0)
2175  {
2176  // phpcs:enable
2177  global $conf, $user;
2178 
2179  if (!$this->table_element) {
2180  dol_print_error('', get_class($this)."::load_previous_next_ref was called on objet with property table_element not defined");
2181  return -1;
2182  }
2183  if ($fieldid == 'none') {
2184  return 1;
2185  }
2186 
2187  // For backward compatibility
2188  if ($this->table_element == 'facture_rec' && $fieldid == 'title') {
2189  $fieldid = 'titre';
2190  }
2191 
2192  // Security on socid
2193  $socid = 0;
2194  if ($user->socid > 0) {
2195  $socid = $user->socid;
2196  }
2197 
2198  // this->ismultientitymanaged contains
2199  // 0=No test on entity, 1=Test with field entity, 'field@table'=Test with link by field@table
2200  $aliastablesociete = 's';
2201  if ($this->element == 'societe') {
2202  $aliastablesociete = 'te'; // te as table_element
2203  }
2204  $restrictiononfksoc = empty($this->restrictiononfksoc) ? 0 : $this->restrictiononfksoc;
2205  $sql = "SELECT MAX(te.".$fieldid.")";
2206  $sql .= " FROM ".(empty($nodbprefix) ?$this->db->prefix():'').$this->table_element." as te";
2207  if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
2208  $sql .= ",".$this->db->prefix()."usergroup_user as ug";
2209  }
2210  if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2211  $tmparray = explode('@', $this->ismultientitymanaged);
2212  $sql .= ", ".$this->db->prefix().$tmparray[1]." as ".($tmparray[1] == 'societe' ? 's' : 'parenttable'); // If we need to link to this table to limit select to entity
2213  } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
2214  $sql .= ", ".$this->db->prefix()."societe as s"; // If we need to link to societe to limit select to socid
2215  } elseif ($restrictiononfksoc == 2 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
2216  $sql .= " LEFT JOIN ".$this->db->prefix()."societe as s ON te.fk_soc = s.rowid"; // If we need to link to societe to limit select to socid
2217  }
2218  if ($restrictiononfksoc && empty($user->rights->societe->client->voir) && !$socid) {
2219  $sql .= " LEFT JOIN ".$this->db->prefix()."societe_commerciaux as sc ON ".$aliastablesociete.".rowid = sc.fk_soc";
2220  }
2221  $sql .= " WHERE te.".$fieldid." < '".$this->db->escape($fieldid == 'rowid' ? $this->id : $this->ref)."'"; // ->ref must always be defined (set to id if field does not exists)
2222  if ($restrictiononfksoc == 1 && empty($user->rights->societe->client->voir) && !$socid) {
2223  $sql .= " AND sc.fk_user = ".((int) $user->id);
2224  }
2225  if ($restrictiononfksoc == 2 && empty($user->rights->societe->client->voir) && !$socid) {
2226  $sql .= " AND (sc.fk_user = ".((int) $user->id).' OR te.fk_soc IS NULL)';
2227  }
2228  if (!empty($filter)) {
2229  if (!preg_match('/^\s*AND/i', $filter)) {
2230  $sql .= " AND "; // For backward compatibility
2231  }
2232  $sql .= $filter;
2233  }
2234  if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2235  $tmparray = explode('@', $this->ismultientitymanaged);
2236  $sql .= " AND te.".$tmparray[0]." = ".($tmparray[1] == "societe" ? "s" : "parenttable").".rowid"; // If we need to link to this table to limit select to entity
2237  } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
2238  $sql .= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to socid
2239  }
2240  if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
2241  if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
2242  if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
2243  $sql .= " AND te.entity IS NOT NULL"; // Show all users
2244  } else {
2245  $sql .= " AND ug.fk_user = te.rowid";
2246  $sql .= " AND ug.entity IN (".getEntity('usergroup').")";
2247  }
2248  } else {
2249  $sql .= ' AND te.entity IN ('.getEntity($this->element).')';
2250  }
2251  }
2252  if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged) && $this->element != 'societe') {
2253  $tmparray = explode('@', $this->ismultientitymanaged);
2254  $sql .= ' AND parenttable.entity IN ('.getEntity($tmparray[1]).')';
2255  }
2256  if ($restrictiononfksoc == 1 && $socid && $this->element != 'societe') {
2257  $sql .= ' AND te.fk_soc = '.((int) $socid);
2258  }
2259  if ($restrictiononfksoc == 2 && $socid && $this->element != 'societe') {
2260  $sql .= ' AND (te.fk_soc = '.((int) $socid).' OR te.fk_soc IS NULL)';
2261  }
2262  if ($restrictiononfksoc && $socid && $this->element == 'societe') {
2263  $sql .= ' AND te.rowid = '.((int) $socid);
2264  }
2265  //print 'socid='.$socid.' restrictiononfksoc='.$restrictiononfksoc.' ismultientitymanaged = '.$this->ismultientitymanaged.' filter = '.$filter.' -> '.$sql."<br>";
2266 
2267  $result = $this->db->query($sql);
2268  if (!$result) {
2269  $this->error = $this->db->lasterror();
2270  return -1;
2271  }
2272  $row = $this->db->fetch_row($result);
2273  $this->ref_previous = $row[0];
2274 
2275  $sql = "SELECT MIN(te.".$fieldid.")";
2276  $sql .= " FROM ".(empty($nodbprefix) ?$this->db->prefix():'').$this->table_element." as te";
2277  if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
2278  $sql .= ",".$this->db->prefix()."usergroup_user as ug";
2279  }
2280  if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2281  $tmparray = explode('@', $this->ismultientitymanaged);
2282  $sql .= ", ".$this->db->prefix().$tmparray[1]." as ".($tmparray[1] == 'societe' ? 's' : 'parenttable'); // If we need to link to this table to limit select to entity
2283  } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
2284  $sql .= ", ".$this->db->prefix()."societe as s"; // If we need to link to societe to limit select to socid
2285  } elseif ($restrictiononfksoc == 2 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
2286  $sql .= " LEFT JOIN ".$this->db->prefix()."societe as s ON te.fk_soc = s.rowid"; // If we need to link to societe to limit select to socid
2287  }
2288  if ($restrictiononfksoc && empty($user->rights->societe->client->voir) && !$socid) {
2289  $sql .= " LEFT JOIN ".$this->db->prefix()."societe_commerciaux as sc ON ".$aliastablesociete.".rowid = sc.fk_soc";
2290  }
2291  $sql .= " WHERE te.".$fieldid." > '".$this->db->escape($fieldid == 'rowid' ? $this->id : $this->ref)."'"; // ->ref must always be defined (set to id if field does not exists)
2292  if ($restrictiononfksoc == 1 && empty($user->rights->societe->client->voir) && !$socid) {
2293  $sql .= " AND sc.fk_user = ".((int) $user->id);
2294  }
2295  if ($restrictiononfksoc == 2 && empty($user->rights->societe->client->voir) && !$socid) {
2296  $sql .= " AND (sc.fk_user = ".((int) $user->id).' OR te.fk_soc IS NULL)';
2297  }
2298  if (!empty($filter)) {
2299  if (!preg_match('/^\s*AND/i', $filter)) {
2300  $sql .= " AND "; // For backward compatibility
2301  }
2302  $sql .= $filter;
2303  }
2304  if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2305  $tmparray = explode('@', $this->ismultientitymanaged);
2306  $sql .= " AND te.".$tmparray[0]." = ".($tmparray[1] == "societe" ? "s" : "parenttable").".rowid"; // If we need to link to this table to limit select to entity
2307  } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
2308  $sql .= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to socid
2309  }
2310  if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
2311  if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
2312  if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
2313  $sql .= " AND te.entity IS NOT NULL"; // Show all users
2314  } else {
2315  $sql .= " AND ug.fk_user = te.rowid";
2316  $sql .= " AND ug.entity IN (".getEntity('usergroup').")";
2317  }
2318  } else {
2319  $sql .= ' AND te.entity IN ('.getEntity($this->element).')';
2320  }
2321  }
2322  if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged) && $this->element != 'societe') {
2323  $tmparray = explode('@', $this->ismultientitymanaged);
2324  $sql .= ' AND parenttable.entity IN ('.getEntity($tmparray[1]).')';
2325  }
2326  if ($restrictiononfksoc == 1 && $socid && $this->element != 'societe') {
2327  $sql .= ' AND te.fk_soc = '.((int) $socid);
2328  }
2329  if ($restrictiononfksoc == 2 && $socid && $this->element != 'societe') {
2330  $sql .= ' AND (te.fk_soc = '.((int) $socid).' OR te.fk_soc IS NULL)';
2331  }
2332  if ($restrictiononfksoc && $socid && $this->element == 'societe') {
2333  $sql .= ' AND te.rowid = '.((int) $socid);
2334  }
2335  //print 'socid='.$socid.' restrictiononfksoc='.$restrictiononfksoc.' ismultientitymanaged = '.$this->ismultientitymanaged.' filter = '.$filter.' -> '.$sql."<br>";
2336  // Rem: Bug in some mysql version: SELECT MIN(rowid) FROM llx_socpeople WHERE rowid > 1 when one row in database with rowid=1, returns 1 instead of null
2337 
2338  $result = $this->db->query($sql);
2339  if (!$result) {
2340  $this->error = $this->db->lasterror();
2341  return -2;
2342  }
2343  $row = $this->db->fetch_row($result);
2344  $this->ref_next = $row[0];
2345 
2346  return 1;
2347  }
2348 
2349 
2357  public function getListContactId($source = 'external')
2358  {
2359  $contactAlreadySelected = array();
2360  $tab = $this->liste_contact(-1, $source);
2361  $num = count($tab);
2362  $i = 0;
2363  while ($i < $num) {
2364  if ($source == 'thirdparty') {
2365  $contactAlreadySelected[$i] = $tab[$i]['socid'];
2366  } else {
2367  $contactAlreadySelected[$i] = $tab[$i]['id'];
2368  }
2369  $i++;
2370  }
2371  return $contactAlreadySelected;
2372  }
2373 
2374 
2382  public function setProject($projectid, $notrigger = 0)
2383  {
2384  global $user;
2385  $error = 0;
2386 
2387  if (!$this->table_element) {
2388  dol_syslog(get_class($this)."::setProject was called on objet with property table_element not defined", LOG_ERR);
2389  return -1;
2390  }
2391 
2392  $sql = "UPDATE ".$this->db->prefix().$this->table_element;
2393  if (!empty($this->fields['fk_project'])) { // Common case
2394  if ($projectid) {
2395  $sql .= " SET fk_project = ".((int) $projectid);
2396  } else {
2397  $sql .= " SET fk_project = NULL";
2398  }
2399  $sql .= ' WHERE rowid = '.((int) $this->id);
2400  } elseif ($this->table_element == 'actioncomm') { // Special case for actioncomm
2401  if ($projectid) {
2402  $sql .= " SET fk_project = ".((int) $projectid);
2403  } else {
2404  $sql .= " SET fk_project = NULL";
2405  }
2406  $sql .= ' WHERE id = '.((int) $this->id);
2407  } else // Special case for old architecture objects
2408  {
2409  if ($projectid) {
2410  $sql .= ' SET fk_projet = '.((int) $projectid);
2411  } else {
2412  $sql .= ' SET fk_projet = NULL';
2413  }
2414  $sql .= " WHERE rowid = ".((int) $this->id);
2415  }
2416 
2417  $this->db->begin();
2418 
2419  dol_syslog(get_class($this)."::setProject", LOG_DEBUG);
2420  if ($this->db->query($sql)) {
2421  $this->fk_project = ((int) $projectid);
2422  } else {
2423  dol_print_error($this->db);
2424  $error++;
2425  }
2426 
2427  // Triggers
2428  if (!$error && !$notrigger) {
2429  // Call triggers
2430  $result = $this->call_trigger(strtoupper($this->element) . '_MODIFY', $user);
2431  if ($result < 0) {
2432  $error++;
2433  } //Do also here what you must do to rollback action if trigger fail
2434  // End call triggers
2435  }
2436 
2437  // Commit or rollback
2438  if ($error) {
2439  $this->db->rollback();
2440  return -1;
2441  } else {
2442  $this->db->commit();
2443  return 1;
2444  }
2445  }
2446 
2453  public function setPaymentMethods($id)
2454  {
2455  global $user;
2456 
2457  $error = 0; $notrigger = 0;
2458 
2459  dol_syslog(get_class($this).'::setPaymentMethods('.$id.')');
2460 
2461  if ($this->statut >= 0 || $this->element == 'societe') {
2462  // TODO uniformize field name
2463  $fieldname = 'fk_mode_reglement';
2464  if ($this->element == 'societe') {
2465  $fieldname = 'mode_reglement';
2466  }
2467  if (get_class($this) == 'Fournisseur') {
2468  $fieldname = 'mode_reglement_supplier';
2469  }
2470  if (get_class($this) == 'Tva') {
2471  $fieldname = 'fk_typepayment';
2472  }
2473  if (get_class($this) == 'Salary') {
2474  $fieldname = 'fk_typepayment';
2475  }
2476 
2477  $sql = "UPDATE ".$this->db->prefix().$this->table_element;
2478  $sql .= " SET ".$fieldname." = ".(($id > 0 || $id == '0') ? ((int) $id) : 'NULL');
2479  $sql .= ' WHERE rowid='.((int) $this->id);
2480 
2481  if ($this->db->query($sql)) {
2482  $this->mode_reglement_id = $id;
2483  // for supplier
2484  if (get_class($this) == 'Fournisseur') {
2485  $this->mode_reglement_supplier_id = $id;
2486  }
2487  // Triggers
2488  if (!$error && !$notrigger) {
2489  // Call triggers
2490  if (get_class($this) == 'Commande') {
2491  $result = $this->call_trigger('ORDER_MODIFY', $user);
2492  } else {
2493  $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $user);
2494  }
2495  if ($result < 0) {
2496  $error++;
2497  }
2498  // End call triggers
2499  }
2500  return 1;
2501  } else {
2502  dol_syslog(get_class($this).'::setPaymentMethods Error '.$this->db->error());
2503  $this->error = $this->db->error();
2504  return -1;
2505  }
2506  } else {
2507  dol_syslog(get_class($this).'::setPaymentMethods, status of the object is incompatible');
2508  $this->error = 'Status of the object is incompatible '.$this->statut;
2509  return -2;
2510  }
2511  }
2512 
2519  public function setMulticurrencyCode($code)
2520  {
2521  dol_syslog(get_class($this).'::setMulticurrencyCode('.$code.')');
2522  if ($this->statut >= 0 || $this->element == 'societe') {
2523  $fieldname = 'multicurrency_code';
2524 
2525  $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
2526  $sql .= " SET ".$fieldname." = '".$this->db->escape($code)."'";
2527  $sql .= ' WHERE rowid='.((int) $this->id);
2528 
2529  if ($this->db->query($sql)) {
2530  $this->multicurrency_code = $code;
2531 
2532  list($fk_multicurrency, $rate) = MultiCurrency::getIdAndTxFromCode($this->db, $code);
2533  if ($rate) {
2534  $this->setMulticurrencyRate($rate, 2);
2535  }
2536 
2537  return 1;
2538  } else {
2539  dol_syslog(get_class($this).'::setMulticurrencyCode Error '.$sql.' - '.$this->db->error());
2540  $this->error = $this->db->error();
2541  return -1;
2542  }
2543  } else {
2544  dol_syslog(get_class($this).'::setMulticurrencyCode, status of the object is incompatible');
2545  $this->error = 'Status of the object is incompatible '.$this->statut;
2546  return -2;
2547  }
2548  }
2549 
2557  public function setMulticurrencyRate($rate, $mode = 1)
2558  {
2559  dol_syslog(get_class($this).'::setMulticurrencyRate('.$rate.','.$mode.')');
2560  if ($this->statut >= 0 || $this->element == 'societe') {
2561  $fieldname = 'multicurrency_tx';
2562 
2563  $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
2564  $sql .= " SET ".$fieldname." = ".((float) $rate);
2565  $sql .= ' WHERE rowid='.((int) $this->id);
2566 
2567  if ($this->db->query($sql)) {
2568  $this->multicurrency_tx = $rate;
2569 
2570  // Update line price
2571  if (!empty($this->lines)) {
2572  foreach ($this->lines as &$line) {
2573  // Amounts in company currency will be recalculated
2574  if ($mode == 1) {
2575  $line->subprice = 0;
2576  }
2577 
2578  // Amounts in foreign currency will be recalculated
2579  if ($mode == 2) {
2580  $line->multicurrency_subprice = 0;
2581  }
2582 
2583  switch ($this->element) {
2584  case 'propal':
2585  $this->updateline(
2586  $line->id,
2587  $line->subprice,
2588  $line->qty,
2589  $line->remise_percent,
2590  $line->tva_tx,
2591  $line->localtax1_tx,
2592  $line->localtax2_tx,
2593  ($line->description ? $line->description : $line->desc),
2594  'HT',
2595  $line->info_bits,
2596  $line->special_code,
2597  $line->fk_parent_line,
2598  $line->skip_update_total,
2599  $line->fk_fournprice,
2600  $line->pa_ht,
2601  $line->label,
2602  $line->product_type,
2603  $line->date_start,
2604  $line->date_end,
2605  $line->array_options,
2606  $line->fk_unit,
2607  $line->multicurrency_subprice
2608  );
2609  break;
2610  case 'commande':
2611  $this->updateline(
2612  $line->id,
2613  ($line->description ? $line->description : $line->desc),
2614  $line->subprice,
2615  $line->qty,
2616  $line->remise_percent,
2617  $line->tva_tx,
2618  $line->localtax1_tx,
2619  $line->localtax2_tx,
2620  'HT',
2621  $line->info_bits,
2622  $line->date_start,
2623  $line->date_end,
2624  $line->product_type,
2625  $line->fk_parent_line,
2626  $line->skip_update_total,
2627  $line->fk_fournprice,
2628  $line->pa_ht,
2629  $line->label,
2630  $line->special_code,
2631  $line->array_options,
2632  $line->fk_unit,
2633  $line->multicurrency_subprice
2634  );
2635  break;
2636  case 'facture':
2637  $this->updateline(
2638  $line->id,
2639  ($line->description ? $line->description : $line->desc),
2640  $line->subprice,
2641  $line->qty,
2642  $line->remise_percent,
2643  $line->date_start,
2644  $line->date_end,
2645  $line->tva_tx,
2646  $line->localtax1_tx,
2647  $line->localtax2_tx,
2648  'HT',
2649  $line->info_bits,
2650  $line->product_type,
2651  $line->fk_parent_line,
2652  $line->skip_update_total,
2653  $line->fk_fournprice,
2654  $line->pa_ht,
2655  $line->label,
2656  $line->special_code,
2657  $line->array_options,
2658  $line->situation_percent,
2659  $line->fk_unit,
2660  $line->multicurrency_subprice
2661  );
2662  break;
2663  case 'supplier_proposal':
2664  $this->updateline(
2665  $line->id,
2666  $line->subprice,
2667  $line->qty,
2668  $line->remise_percent,
2669  $line->tva_tx,
2670  $line->localtax1_tx,
2671  $line->localtax2_tx,
2672  ($line->description ? $line->description : $line->desc),
2673  'HT',
2674  $line->info_bits,
2675  $line->special_code,
2676  $line->fk_parent_line,
2677  $line->skip_update_total,
2678  $line->fk_fournprice,
2679  $line->pa_ht,
2680  $line->label,
2681  $line->product_type,
2682  $line->array_options,
2683  $line->ref_fourn,
2684  $line->multicurrency_subprice
2685  );
2686  break;
2687  case 'order_supplier':
2688  $this->updateline(
2689  $line->id,
2690  ($line->description ? $line->description : $line->desc),
2691  $line->subprice,
2692  $line->qty,
2693  $line->remise_percent,
2694  $line->tva_tx,
2695  $line->localtax1_tx,
2696  $line->localtax2_tx,
2697  'HT',
2698  $line->info_bits,
2699  $line->product_type,
2700  false,
2701  $line->date_start,
2702  $line->date_end,
2703  $line->array_options,
2704  $line->fk_unit,
2705  $line->multicurrency_subprice,
2706  $line->ref_supplier
2707  );
2708  break;
2709  case 'invoice_supplier':
2710  $this->updateline(
2711  $line->id,
2712  ($line->description ? $line->description : $line->desc),
2713  $line->subprice,
2714  $line->tva_tx,
2715  $line->localtax1_tx,
2716  $line->localtax2_tx,
2717  $line->qty,
2718  0,
2719  'HT',
2720  $line->info_bits,
2721  $line->product_type,
2722  $line->remise_percent,
2723  false,
2724  $line->date_start,
2725  $line->date_end,
2726  $line->array_options,
2727  $line->fk_unit,
2728  $line->multicurrency_subprice,
2729  $line->ref_supplier
2730  );
2731  break;
2732  default:
2733  dol_syslog(get_class($this).'::setMulticurrencyRate no updateline defined', LOG_DEBUG);
2734  break;
2735  }
2736  }
2737  }
2738 
2739  return 1;
2740  } else {
2741  dol_syslog(get_class($this).'::setMulticurrencyRate Error '.$sql.' - '.$this->db->error());
2742  $this->error = $this->db->error();
2743  return -1;
2744  }
2745  } else {
2746  dol_syslog(get_class($this).'::setMulticurrencyRate, status of the object is incompatible');
2747  $this->error = 'Status of the object is incompatible '.$this->statut;
2748  return -2;
2749  }
2750  }
2751 
2759  public function setPaymentTerms($id, $deposit_percent = null)
2760  {
2761  dol_syslog(get_class($this).'::setPaymentTerms('.$id.', '.var_export($deposit_percent, true).')');
2762  if ($this->statut >= 0 || $this->element == 'societe') {
2763  // TODO uniformize field name
2764  $fieldname = 'fk_cond_reglement';
2765  if ($this->element == 'societe') {
2766  $fieldname = 'cond_reglement';
2767  }
2768  if (get_class($this) == 'Fournisseur') {
2769  $fieldname = 'cond_reglement_supplier';
2770  }
2771 
2772  if (empty($deposit_percent) || $deposit_percent < 0) {
2773  $deposit_percent = getDictionaryValue('c_payment_term', 'deposit_percent', $id);
2774  }
2775 
2776  if ($deposit_percent > 100) {
2777  $deposit_percent = 100;
2778  }
2779 
2780  $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
2781  $sql .= " SET ".$fieldname." = ".(($id > 0 || $id == '0') ? ((int) $id) : 'NULL');
2782  if (in_array($this->table_element, array('propal', 'commande'))) {
2783  $sql .= " , deposit_percent = " . (empty($deposit_percent) ? 'NULL' : "'".$this->db->escape($deposit_percent)."'");
2784  }
2785  $sql .= ' WHERE rowid='.((int) $this->id);
2786 
2787  if ($this->db->query($sql)) {
2788  $this->cond_reglement_id = $id;
2789  // for supplier
2790  if (get_class($this) == 'Fournisseur') {
2791  $this->cond_reglement_supplier_id = $id;
2792  }
2793  $this->cond_reglement = $id; // for compatibility
2794  $this->deposit_percent = $deposit_percent;
2795  return 1;
2796  } else {
2797  dol_syslog(get_class($this).'::setPaymentTerms Error '.$sql.' - '.$this->db->error());
2798  $this->error = $this->db->error();
2799  return -1;
2800  }
2801  } else {
2802  dol_syslog(get_class($this).'::setPaymentTerms, status of the object is incompatible');
2803  $this->error = 'Status of the object is incompatible '.$this->statut;
2804  return -2;
2805  }
2806  }
2807 
2814  public function setTransportMode($id)
2815  {
2816  dol_syslog(get_class($this).'::setTransportMode('.$id.')');
2817  if ($this->statut >= 0 || $this->element == 'societe') {
2818  $fieldname = 'fk_transport_mode';
2819  if ($this->element == 'societe') {
2820  $fieldname = 'transport_mode';
2821  }
2822  if (get_class($this) == 'Fournisseur') {
2823  $fieldname = 'transport_mode_supplier';
2824  }
2825 
2826  $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
2827  $sql .= " SET ".$fieldname." = ".(($id > 0 || $id == '0') ? ((int) $id) : 'NULL');
2828  $sql .= ' WHERE rowid='.((int) $this->id);
2829 
2830  if ($this->db->query($sql)) {
2831  $this->transport_mode_id = $id;
2832  // for supplier
2833  if (get_class($this) == 'Fournisseur') {
2834  $this->transport_mode_supplier_id = $id;
2835  }
2836  return 1;
2837  } else {
2838  dol_syslog(get_class($this).'::setTransportMode Error '.$sql.' - '.$this->db->error());
2839  $this->error = $this->db->error();
2840  return -1;
2841  }
2842  } else {
2843  dol_syslog(get_class($this).'::setTransportMode, status of the object is incompatible');
2844  $this->error = 'Status of the object is incompatible '.$this->statut;
2845  return -2;
2846  }
2847  }
2848 
2855  public function setRetainedWarrantyPaymentTerms($id)
2856  {
2857  dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms('.$id.')');
2858  if ($this->statut >= 0 || $this->element == 'societe') {
2859  $fieldname = 'retained_warranty_fk_cond_reglement';
2860 
2861  $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
2862  $sql .= " SET ".$fieldname." = ".((int) $id);
2863  $sql .= ' WHERE rowid='.((int) $this->id);
2864 
2865  if ($this->db->query($sql)) {
2866  $this->retained_warranty_fk_cond_reglement = $id;
2867  return 1;
2868  } else {
2869  dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms Error '.$sql.' - '.$this->db->error());
2870  $this->error = $this->db->error();
2871  return -1;
2872  }
2873  } else {
2874  dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms, status of the object is incompatible');
2875  $this->error = 'Status of the object is incompatible '.$this->statut;
2876  return -2;
2877  }
2878  }
2879 
2887  public function setDeliveryAddress($id)
2888  {
2889  $fieldname = 'fk_delivery_address';
2890  if ($this->element == 'delivery' || $this->element == 'shipping') {
2891  $fieldname = 'fk_address';
2892  }
2893 
2894  $sql = "UPDATE ".$this->db->prefix().$this->table_element." SET ".$fieldname." = ".((int) $id);
2895  $sql .= " WHERE rowid = ".((int) $this->id)." AND fk_statut = 0";
2896 
2897  if ($this->db->query($sql)) {
2898  $this->fk_delivery_address = $id;
2899  return 1;
2900  } else {
2901  $this->error = $this->db->error();
2902  dol_syslog(get_class($this).'::setDeliveryAddress Error '.$this->error);
2903  return -1;
2904  }
2905  }
2906 
2907 
2917  public function setShippingMethod($shipping_method_id, $notrigger = false, $userused = null)
2918  {
2919  global $user;
2920 
2921  if (empty($userused)) {
2922  $userused = $user;
2923  }
2924 
2925  $error = 0;
2926 
2927  if (!$this->table_element) {
2928  dol_syslog(get_class($this)."::setShippingMethod was called on objet with property table_element not defined", LOG_ERR);
2929  return -1;
2930  }
2931 
2932  $this->db->begin();
2933 
2934  if ($shipping_method_id < 0) {
2935  $shipping_method_id = 'NULL';
2936  }
2937  dol_syslog(get_class($this).'::setShippingMethod('.$shipping_method_id.')');
2938 
2939  $sql = "UPDATE ".$this->db->prefix().$this->table_element;
2940  $sql .= " SET fk_shipping_method = ".((int) $shipping_method_id);
2941  $sql .= " WHERE rowid=".((int) $this->id);
2942  $resql = $this->db->query($sql);
2943  if (!$resql) {
2944  dol_syslog(get_class($this).'::setShippingMethod Error ', LOG_DEBUG);
2945  $this->error = $this->db->lasterror();
2946  $error++;
2947  } else {
2948  if (!$notrigger) {
2949  // Call trigger
2950  $this->context = array('shippingmethodupdate'=>1);
2951  $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $userused);
2952  if ($result < 0) {
2953  $error++;
2954  }
2955  // End call trigger
2956  }
2957  }
2958  if ($error) {
2959  $this->db->rollback();
2960  return -1;
2961  } else {
2962  $this->shipping_method_id = ($shipping_method_id == 'NULL') ?null:$shipping_method_id;
2963  $this->db->commit();
2964  return 1;
2965  }
2966  }
2967 
2968 
2975  public function setWarehouse($warehouse_id)
2976  {
2977  if (!$this->table_element) {
2978  dol_syslog(get_class($this)."::setWarehouse was called on objet with property table_element not defined", LOG_ERR);
2979  return -1;
2980  }
2981  if ($warehouse_id < 0) {
2982  $warehouse_id = 'NULL';
2983  }
2984  dol_syslog(get_class($this).'::setWarehouse('.$warehouse_id.')');
2985 
2986  $sql = "UPDATE ".$this->db->prefix().$this->table_element;
2987  $sql .= " SET fk_warehouse = ".((int) $warehouse_id);
2988  $sql .= " WHERE rowid=".((int) $this->id);
2989 
2990  if ($this->db->query($sql)) {
2991  $this->warehouse_id = ($warehouse_id == 'NULL') ?null:$warehouse_id;
2992  return 1;
2993  } else {
2994  dol_syslog(get_class($this).'::setWarehouse Error ', LOG_DEBUG);
2995  $this->error = $this->db->error();
2996  return 0;
2997  }
2998  }
2999 
3000 
3008  public function setDocModel($user, $modelpdf)
3009  {
3010  if (!$this->table_element) {
3011  dol_syslog(get_class($this)."::setDocModel was called on objet with property table_element not defined", LOG_ERR);
3012  return -1;
3013  }
3014 
3015  $newmodelpdf = dol_trunc($modelpdf, 255);
3016 
3017  $sql = "UPDATE ".$this->db->prefix().$this->table_element;
3018  $sql .= " SET model_pdf = '".$this->db->escape($newmodelpdf)."'";
3019  $sql .= " WHERE rowid = ".((int) $this->id);
3020 
3021  dol_syslog(get_class($this)."::setDocModel", LOG_DEBUG);
3022  $resql = $this->db->query($sql);
3023  if ($resql) {
3024  $this->model_pdf = $modelpdf;
3025  $this->modelpdf = $modelpdf; // For bakward compatibility
3026  return 1;
3027  } else {
3028  dol_print_error($this->db);
3029  return 0;
3030  }
3031  }
3032 
3033 
3042  public function setBankAccount($fk_account, $notrigger = false, $userused = null)
3043  {
3044  global $user;
3045 
3046  if (empty($userused)) {
3047  $userused = $user;
3048  }
3049 
3050  $error = 0;
3051 
3052  if (!$this->table_element) {
3053  dol_syslog(get_class($this)."::setBankAccount was called on objet with property table_element not defined", LOG_ERR);
3054  return -1;
3055  }
3056  $this->db->begin();
3057 
3058  if ($fk_account < 0) {
3059  $fk_account = 'NULL';
3060  }
3061  dol_syslog(get_class($this).'::setBankAccount('.$fk_account.')');
3062 
3063  $sql = "UPDATE ".$this->db->prefix().$this->table_element;
3064  $sql .= " SET fk_account = ".((int) $fk_account);
3065  $sql .= " WHERE rowid=".((int) $this->id);
3066 
3067  $resql = $this->db->query($sql);
3068  if (!$resql) {
3069  dol_syslog(get_class($this).'::setBankAccount Error '.$sql.' - '.$this->db->error());
3070  $this->error = $this->db->lasterror();
3071  $error++;
3072  } else {
3073  if (!$notrigger) {
3074  // Call trigger
3075  $this->context = array('bankaccountupdate'=>1);
3076  $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $userused);
3077  if ($result < 0) {
3078  $error++;
3079  }
3080  // End call trigger
3081  }
3082  }
3083  if ($error) {
3084  $this->db->rollback();
3085  return -1;
3086  } else {
3087  $this->fk_account = ($fk_account == 'NULL') ?null:$fk_account;
3088  $this->db->commit();
3089  return 1;
3090  }
3091  }
3092 
3093 
3094  // TODO: Move line related operations to CommonObjectLine?
3095 
3096  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3106  public function line_order($renum = false, $rowidorder = 'ASC', $fk_parent_line = true)
3107  {
3108  // phpcs:enable
3109  if (!$this->table_element_line) {
3110  dol_syslog(get_class($this)."::line_order was called on objet with property table_element_line not defined", LOG_ERR);
3111  return -1;
3112  }
3113  if (!$this->fk_element) {
3114  dol_syslog(get_class($this)."::line_order was called on objet with property fk_element not defined", LOG_ERR);
3115  return -1;
3116  }
3117 
3118  $fieldposition = 'rang'; // @todo Rename 'rang' into 'position'
3119  if (in_array($this->table_element_line, array('bom_bomline', 'ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
3120  $fieldposition = 'position';
3121  }
3122 
3123  // Count number of lines to reorder (according to choice $renum)
3124  $nl = 0;
3125  $sql = "SELECT count(rowid) FROM ".$this->db->prefix().$this->table_element_line;
3126  $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
3127  if (!$renum) {
3128  $sql .= " AND " . $fieldposition . " = 0";
3129  }
3130  if ($renum) {
3131  $sql .= " AND " . $fieldposition . " <> 0";
3132  }
3133 
3134  dol_syslog(get_class($this)."::line_order", LOG_DEBUG);
3135  $resql = $this->db->query($sql);
3136  if ($resql) {
3137  $row = $this->db->fetch_row($resql);
3138  $nl = $row[0];
3139  } else {
3140  dol_print_error($this->db);
3141  }
3142  if ($nl > 0) {
3143  // The goal of this part is to reorder all lines, with all children lines sharing the same counter that parents.
3144  $rows = array();
3145 
3146  // We first search all lines that are parent lines (for multilevel details lines)
3147  $sql = "SELECT rowid FROM ".$this->db->prefix().$this->table_element_line;
3148  $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
3149  if ($fk_parent_line) {
3150  $sql .= ' AND fk_parent_line IS NULL';
3151  }
3152  $sql .= " ORDER BY " . $fieldposition . " ASC, rowid " . $rowidorder;
3153 
3154  dol_syslog(get_class($this)."::line_order search all parent lines", LOG_DEBUG);
3155  $resql = $this->db->query($sql);
3156  if ($resql) {
3157  $i = 0;
3158  $num = $this->db->num_rows($resql);
3159  while ($i < $num) {
3160  $row = $this->db->fetch_row($resql);
3161  $rows[] = $row[0]; // Add parent line into array rows
3162  $childrens = $this->getChildrenOfLine($row[0]);
3163  if (!empty($childrens)) {
3164  foreach ($childrens as $child) {
3165  array_push($rows, $child);
3166  }
3167  }
3168  $i++;
3169  }
3170 
3171  // Now we set a new number for each lines (parent and children with children included into parent tree)
3172  if (!empty($rows)) {
3173  foreach ($rows as $key => $row) {
3174  $this->updateRangOfLine($row, ($key + 1));
3175  }
3176  }
3177  } else {
3178  dol_print_error($this->db);
3179  }
3180  }
3181  return 1;
3182  }
3183 
3191  public function getChildrenOfLine($id, $includealltree = 0)
3192  {
3193  $fieldposition = 'rang'; // @todo Rename 'rang' into 'position'
3194  if (in_array($this->table_element_line, array('bom_bomline', 'ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
3195  $fieldposition = 'position';
3196  }
3197 
3198  $rows = array();
3199 
3200  $sql = "SELECT rowid FROM ".$this->db->prefix().$this->table_element_line;
3201  $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
3202  $sql .= ' AND fk_parent_line = '.((int) $id);
3203  $sql .= " ORDER BY " . $fieldposition . " ASC";
3204 
3205  dol_syslog(get_class($this)."::getChildrenOfLine search children lines for line ".$id, LOG_DEBUG);
3206  $resql = $this->db->query($sql);
3207  if ($resql) {
3208  if ($this->db->num_rows($resql) > 0) {
3209  while ($row = $this->db->fetch_row($resql)) {
3210  $rows[] = $row[0];
3211  if (!empty($includealltree)) {
3212  $rows = array_merge($rows, $this->getChildrenOfLine($row[0]), $includealltree);
3213  }
3214  }
3215  }
3216  }
3217  return $rows;
3218  }
3219 
3220  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3228  public function line_up($rowid, $fk_parent_line = true)
3229  {
3230  // phpcs:enable
3231  $this->line_order(false, 'ASC', $fk_parent_line);
3232 
3233  // Get rang of line
3234  $rang = $this->getRangOfLine($rowid);
3235 
3236  // Update position of line
3237  $this->updateLineUp($rowid, $rang);
3238  }
3239 
3240  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3248  public function line_down($rowid, $fk_parent_line = true)
3249  {
3250  // phpcs:enable
3251  $this->line_order(false, 'ASC', $fk_parent_line);
3252 
3253  // Get rang of line
3254  $rang = $this->getRangOfLine($rowid);
3255 
3256  // Get max value for rang
3257  $max = $this->line_max();
3258 
3259  // Update position of line
3260  $this->updateLineDown($rowid, $rang, $max);
3261  }
3262 
3270  public function updateRangOfLine($rowid, $rang)
3271  {
3272  global $hookmanager;
3273  $fieldposition = 'rang'; // @todo Rename 'rang' into 'position'
3274  if (in_array($this->table_element_line, array('bom_bomline', 'ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
3275  $fieldposition = 'position';
3276  }
3277 
3278  $sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldposition." = ".((int) $rang);
3279  $sql .= ' WHERE rowid = '.((int) $rowid);
3280 
3281  dol_syslog(get_class($this)."::updateRangOfLine", LOG_DEBUG);
3282  if (!$this->db->query($sql)) {
3283  dol_print_error($this->db);
3284  return -1;
3285  } else {
3286  $parameters=array('rowid'=>$rowid, 'rang'=>$rang, 'fieldposition' => $fieldposition);
3287  $action='';
3288  $reshook = $hookmanager->executeHooks('afterRankOfLineUpdate', $parameters, $this, $action);
3289  return 1;
3290  }
3291  }
3292 
3293  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3300  public function line_ajaxorder($rows)
3301  {
3302  // phpcs:enable
3303  $num = count($rows);
3304  for ($i = 0; $i < $num; $i++) {
3305  $this->updateRangOfLine($rows[$i], ($i + 1));
3306  }
3307  }
3308 
3316  public function updateLineUp($rowid, $rang)
3317  {
3318  if ($rang > 1) {
3319  $fieldposition = 'rang';
3320  if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
3321  $fieldposition = 'position';
3322  }
3323 
3324  $sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldposition." = ".((int) $rang);
3325  $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
3326  $sql .= " AND " . $fieldposition . " = " . ((int) ($rang - 1));
3327  if ($this->db->query($sql)) {
3328  $sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldposition." = ".((int) ($rang - 1));
3329  $sql .= ' WHERE rowid = '.((int) $rowid);
3330  if (!$this->db->query($sql)) {
3331  dol_print_error($this->db);
3332  }
3333  } else {
3334  dol_print_error($this->db);
3335  }
3336  }
3337  }
3338 
3347  public function updateLineDown($rowid, $rang, $max)
3348  {
3349  if ($rang < $max) {
3350  $fieldposition = 'rang';
3351  if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
3352  $fieldposition = 'position';
3353  }
3354 
3355  $sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldposition." = ".((int) $rang);
3356  $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
3357  $sql .= " AND " . $fieldposition . " = " . ((int) ($rang + 1));
3358  if ($this->db->query($sql)) {
3359  $sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldposition." = ".((int) ($rang + 1));
3360  $sql .= ' WHERE rowid = '.((int) $rowid);
3361  if (!$this->db->query($sql)) {
3362  dol_print_error($this->db);
3363  }
3364  } else {
3365  dol_print_error($this->db);
3366  }
3367  }
3368  }
3369 
3376  public function getRangOfLine($rowid)
3377  {
3378  $fieldposition = 'rang';
3379  if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
3380  $fieldposition = 'position';
3381  }
3382 
3383  $sql = "SELECT " . $fieldposition . " FROM ".$this->db->prefix().$this->table_element_line;
3384  $sql .= " WHERE rowid = ".((int) $rowid);
3385 
3386  dol_syslog(get_class($this)."::getRangOfLine", LOG_DEBUG);
3387  $resql = $this->db->query($sql);
3388  if ($resql) {
3389  $row = $this->db->fetch_row($resql);
3390  return $row[0];
3391  }
3392 
3393  return 0;
3394  }
3395 
3402  public function getIdOfLine($rang)
3403  {
3404  $fieldposition = 'rang';
3405  if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
3406  $fieldposition = 'position';
3407  }
3408 
3409  $sql = "SELECT rowid FROM ".$this->db->prefix().$this->table_element_line;
3410  $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
3411  $sql .= " AND " . $fieldposition . " = ".((int) $rang);
3412  $resql = $this->db->query($sql);
3413  if ($resql) {
3414  $row = $this->db->fetch_row($resql);
3415  return $row[0];
3416  }
3417 
3418  return 0;
3419  }
3420 
3421  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3428  public function line_max($fk_parent_line = 0)
3429  {
3430  // phpcs:enable
3431  $positionfield = 'rang';
3432  if (in_array($this->table_element, array('bom_bom', 'product_attribute'))) {
3433  $positionfield = 'position';
3434  }
3435 
3436  // Search the last rang with fk_parent_line
3437  if ($fk_parent_line) {
3438  $sql = "SELECT max(".$positionfield.") FROM ".$this->db->prefix().$this->table_element_line;
3439  $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
3440  $sql .= " AND fk_parent_line = ".((int) $fk_parent_line);
3441 
3442  dol_syslog(get_class($this)."::line_max", LOG_DEBUG);
3443  $resql = $this->db->query($sql);
3444  if ($resql) {
3445  $row = $this->db->fetch_row($resql);
3446  if (!empty($row[0])) {
3447  return $row[0];
3448  } else {
3449  return $this->getRangOfLine($fk_parent_line);
3450  }
3451  }
3452  } else {
3453  // If not, search the last rang of element
3454  $sql = "SELECT max(".$positionfield.") FROM ".$this->db->prefix().$this->table_element_line;
3455  $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
3456 
3457  dol_syslog(get_class($this)."::line_max", LOG_DEBUG);
3458  $resql = $this->db->query($sql);
3459  if ($resql) {
3460  $row = $this->db->fetch_row($resql);
3461  return $row[0];
3462  }
3463  }
3464 
3465  return 0;
3466  }
3467 
3468  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3475  public function update_ref_ext($ref_ext)
3476  {
3477  // phpcs:enable
3478  if (!$this->table_element) {
3479  dol_syslog(get_class($this)."::update_ref_ext was called on objet with property table_element not defined", LOG_ERR);
3480  return -1;
3481  }
3482 
3483  $sql = "UPDATE ".$this->db->prefix().$this->table_element;
3484  $sql .= " SET ref_ext = '".$this->db->escape($ref_ext)."'";
3485  $sql .= " WHERE ".(isset($this->table_rowid) ? $this->table_rowid : 'rowid')." = ".((int) $this->id);
3486 
3487  dol_syslog(get_class($this)."::update_ref_ext", LOG_DEBUG);
3488  if ($this->db->query($sql)) {
3489  $this->ref_ext = $ref_ext;
3490  return 1;
3491  } else {
3492  $this->error = $this->db->error();
3493  return -1;
3494  }
3495  }
3496 
3497  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3505  public function update_note($note, $suffix = '')
3506  {
3507  // phpcs:enable
3508  global $user;
3509 
3510  if (!$this->table_element) {
3511  $this->error = 'update_note was called on objet with property table_element not defined';
3512  dol_syslog(get_class($this)."::update_note was called on objet with property table_element not defined", LOG_ERR);
3513  return -1;
3514  }
3515  if (!in_array($suffix, array('', '_public', '_private'))) {
3516  $this->error = 'update_note Parameter suffix must be empty, \'_private\' or \'_public\'';
3517  dol_syslog(get_class($this)."::update_note Parameter suffix must be empty, '_private' or '_public'", LOG_ERR);
3518  return -2;
3519  }
3520 
3521  $newsuffix = $suffix;
3522 
3523  // Special cas
3524  if ($this->table_element == 'product' && $newsuffix == '_private') {
3525  $newsuffix = '';
3526  }
3527  if (in_array($this->table_element, array('actioncomm', 'adherent', 'advtargetemailing', 'cronjob', 'establishment'))) {
3528  $fieldusermod = "fk_user_mod";
3529  } elseif ($this->table_element == 'ecm_files') {
3530  $fieldusermod = "fk_user_m";
3531  } else {
3532  $fieldusermod = "fk_user_modif";
3533  }
3534  $sql = "UPDATE ".$this->db->prefix().$this->table_element;
3535  $sql .= " SET note".$newsuffix." = ".(!empty($note) ? ("'".$this->db->escape($note)."'") : "NULL");
3536  $sql .= ", ".$fieldusermod." = ".((int) $user->id);
3537  $sql .= " WHERE rowid = ".((int) $this->id);
3538 
3539  dol_syslog(get_class($this)."::update_note", LOG_DEBUG);
3540  if ($this->db->query($sql)) {
3541  if ($suffix == '_public') {
3542  $this->note_public = $note;
3543  } elseif ($suffix == '_private') {
3544  $this->note_private = $note;
3545  } else {
3546  $this->note = $note; // deprecated
3547  $this->note_private = $note;
3548  }
3549  return 1;
3550  } else {
3551  $this->error = $this->db->lasterror();
3552  return -1;
3553  }
3554  }
3555 
3556  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3565  public function update_note_public($note)
3566  {
3567  // phpcs:enable
3568  return $this->update_note($note, '_public');
3569  }
3570 
3571  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3582  public function update_price($exclspec = 0, $roundingadjust = 'none', $nodatabaseupdate = 0, $seller = null)
3583  {
3584  // phpcs:enable
3585  global $conf, $hookmanager, $action;
3586 
3587  $parameters = array('exclspec' => $exclspec, 'roundingadjust' => $roundingadjust, 'nodatabaseupdate' => $nodatabaseupdate, 'seller' => $seller);
3588  $reshook = $hookmanager->executeHooks('updateTotalPrice', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
3589  if ($reshook > 0) {
3590  return 1; // replacement code
3591  } elseif ($reshook < 0) {
3592  return -1; // failure
3593  } // reshook = 0 => execute normal code
3594 
3595  // Some external module want no update price after a trigger because they have another method to calculate the total (ex: with an extrafield)
3596  $MODULE = "";
3597  if ($this->element == 'propal') {
3598  $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_PROPOSAL";
3599  } elseif ($this->element == 'commande' || $this->element == 'order') {
3600  $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_ORDER";
3601  } elseif ($this->element == 'facture' || $this->element == 'invoice') {
3602  $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_INVOICE";
3603  } elseif ($this->element == 'facture_fourn' || $this->element == 'supplier_invoice' || $this->element == 'invoice_supplier' || $this->element == 'invoice_supplier_rec') {
3604  $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_INVOICE";
3605  } elseif ($this->element == 'order_supplier' || $this->element == 'supplier_order') {
3606  $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_ORDER";
3607  } elseif ($this->element == 'supplier_proposal') {
3608  $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_PROPOSAL";
3609  }
3610 
3611  if (!empty($MODULE)) {
3612  if (!empty($conf->global->$MODULE)) {
3613  $modsactivated = explode(',', $conf->global->$MODULE);
3614  foreach ($modsactivated as $mod) {
3615  if (isModEnabled($mod)) {
3616  return 1; // update was disabled by specific setup
3617  }
3618  }
3619  }
3620  }
3621 
3622  include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
3623 
3624  $forcedroundingmode = $roundingadjust;
3625  if ($forcedroundingmode == 'auto' && isset($conf->global->MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND)) {
3626  $forcedroundingmode = getDolGlobalString('MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND');
3627  } elseif ($forcedroundingmode == 'auto') {
3628  $forcedroundingmode = '0';
3629  }
3630 
3631  $error = 0;
3632 
3633  $multicurrency_tx = !empty($this->multicurrency_tx) ? $this->multicurrency_tx : 1;
3634 
3635  // Define constants to find lines to sum (field name int the table_element_line not into table_element)
3636  $fieldtva = 'total_tva';
3637  $fieldlocaltax1 = 'total_localtax1';
3638  $fieldlocaltax2 = 'total_localtax2';
3639  $fieldup = 'subprice';
3640  if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier') {
3641  $fieldtva = 'tva';
3642  $fieldup = 'pu_ht';
3643  }
3644  if ($this->element == 'invoice_supplier_rec') {
3645  $fieldup = 'pu_ht';
3646  }
3647  if ($this->element == 'expensereport') {
3648  $fieldup = 'value_unit';
3649  }
3650 
3651  $sql = "SELECT rowid, qty, ".$fieldup." as up, remise_percent, total_ht, ".$fieldtva." as total_tva, total_ttc, ".$fieldlocaltax1." as total_localtax1, ".$fieldlocaltax2." as total_localtax2,";
3652  $sql .= ' tva_tx as vatrate, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type, info_bits, product_type';
3653  if ($this->table_element_line == 'facturedet') {
3654  $sql .= ', situation_percent';
3655  }
3656  $sql .= ', multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc';
3657  $sql .= " FROM ".$this->db->prefix().$this->table_element_line;
3658  $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
3659  if ($exclspec) {
3660  $product_field = 'product_type';
3661  if ($this->table_element_line == 'contratdet') {
3662  $product_field = ''; // contratdet table has no product_type field
3663  }
3664  if ($product_field) {
3665  $sql .= " AND ".$product_field." <> 9";
3666  }
3667  }
3668  $sql .= ' ORDER by rowid'; // We want to be sure to always use same order of line to not change lines differently when option MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND is used
3669 
3670  dol_syslog(get_class($this)."::update_price", LOG_DEBUG);
3671 
3672  $resql = $this->db->query($sql);
3673  if ($resql) {
3674  $this->total_ht = 0;
3675  $this->total_tva = 0;
3676  $this->total_localtax1 = 0;
3677  $this->total_localtax2 = 0;
3678  $this->total_ttc = 0;
3679  $total_ht_by_vats = array();
3680  $total_tva_by_vats = array();
3681  $total_ttc_by_vats = array();
3682  $this->multicurrency_total_ht = 0;
3683  $this->multicurrency_total_tva = 0;
3684  $this->multicurrency_total_ttc = 0;
3685 
3686  $num = $this->db->num_rows($resql);
3687  $i = 0;
3688  while ($i < $num) {
3689  $obj = $this->db->fetch_object($resql);
3690 
3691  // Note: There is no check on detail line and no check on total, if $forcedroundingmode = 'none'
3692  $parameters = array('fk_element' => $obj->rowid);
3693  $reshook = $hookmanager->executeHooks('changeRoundingMode', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
3694 
3695  if (empty($reshook) && $forcedroundingmode == '0') { // Check if data on line are consistent. This may solve lines that were not consistent because set with $forcedroundingmode='auto'
3696  // This part of code is to fix data. We should not call it too often.
3697  $localtax_array = array($obj->localtax1_type, $obj->localtax1_tx, $obj->localtax2_type, $obj->localtax2_tx);
3698  $tmpcal = calcul_price_total($obj->qty, $obj->up, $obj->remise_percent, $obj->vatrate, $obj->localtax1_tx, $obj->localtax2_tx, 0, 'HT', $obj->info_bits, $obj->product_type, $seller, $localtax_array, (isset($obj->situation_percent) ? $obj->situation_percent : 100), $multicurrency_tx);
3699 
3700  $diff_when_using_price_ht = price2num($tmpcal[1] - $obj->total_tva, 'MT', 1); // If price was set with tax price and unit price HT has a low number of digits, then we may have a diff on recalculation from unit price HT.
3701  $diff_on_current_total = price2num($obj->total_ttc - $obj->total_ht - $obj->total_tva - $obj->total_localtax1 - $obj->total_localtax2, 'MT', 1);
3702  //var_dump($obj->total_ht.' '.$obj->total_tva.' '.$obj->total_localtax1.' '.$obj->total_localtax2.' => '.$obj->total_ttc);
3703  //var_dump($diff_when_using_price_ht.' '.$diff_on_current_total);
3704 
3705  if ($diff_on_current_total) {
3706  // This should not happen, we should always have in table: total_ttc = total_ht + total_vat + total_localtax1 + total_localtax2
3707  $sqlfix = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldtva." = ".price2num((float) $tmpcal[1]).", total_ttc = ".price2num((float) $tmpcal[2])." WHERE rowid = ".((int) $obj->rowid);
3708  dol_syslog('We found unconsistent data into detailed line (diff_on_current_total = '.$diff_on_current_total.') for line rowid = '.$obj->rowid." (ht=".$obj->total_ht." vat=".$obj->total_tva." tax1=".$obj->total_localtax1." tax2=".$obj->total_localtax2." ttc=".$obj->total_ttc."). We fix the total_vat and total_ttc of line by running sqlfix = ".$sqlfix, LOG_WARNING);
3709  $resqlfix = $this->db->query($sqlfix);
3710  if (!$resqlfix) {
3711  dol_print_error($this->db, 'Failed to update line');
3712  }
3713  $obj->total_tva = $tmpcal[1];
3714  $obj->total_ttc = $tmpcal[2];
3715  } elseif ($diff_when_using_price_ht && $roundingadjust == '0') {
3716  // After calculation from HT, total is consistent but we have found a difference between VAT part in calculation and into database and
3717  // we ask to force the use of rounding on line (like done on calculation) so we force update of line
3718  $sqlfix = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldtva." = ".price2num((float) $tmpcal[1]).", total_ttc = ".price2num((float) $tmpcal[2])." WHERE rowid = ".((int) $obj->rowid);
3719  dol_syslog('We found a line with different rounding data into detailed line (diff_when_using_price_ht = '.$diff_when_using_price_ht.' and diff_on_current_total = '.$diff_on_current_total.') for line rowid = '.$obj->rowid." (total vat of line calculated=".$tmpcal[1].", database=".$obj->total_tva."). We fix the total_vat and total_ttc of line by running sqlfix = ".$sqlfix);
3720  $resqlfix = $this->db->query($sqlfix);
3721  if (!$resqlfix) {
3722  dol_print_error($this->db, 'Failed to update line');
3723  }
3724  $obj->total_tva = $tmpcal[1];
3725  $obj->total_ttc = $tmpcal[2];
3726  }
3727  }
3728 
3729  $this->total_ht += $obj->total_ht; // The field visible at end of line detail
3730  $this->total_tva += $obj->total_tva;
3731  $this->total_localtax1 += $obj->total_localtax1;
3732  $this->total_localtax2 += $obj->total_localtax2;
3733  $this->total_ttc += $obj->total_ttc;
3734  $this->multicurrency_total_ht += $obj->multicurrency_total_ht; // The field visible at end of line detail
3735  $this->multicurrency_total_tva += $obj->multicurrency_total_tva;
3736  $this->multicurrency_total_ttc += $obj->multicurrency_total_ttc;
3737 
3738  if (!isset($total_ht_by_vats[$obj->vatrate])) {
3739  $total_ht_by_vats[$obj->vatrate] = 0;
3740  }
3741  if (!isset($total_tva_by_vats[$obj->vatrate])) {
3742  $total_tva_by_vats[$obj->vatrate] = 0;
3743  }
3744  if (!isset($total_ttc_by_vats[$obj->vatrate])) {
3745  $total_ttc_by_vats[$obj->vatrate] = 0;
3746  }
3747  $total_ht_by_vats[$obj->vatrate] += $obj->total_ht;
3748  $total_tva_by_vats[$obj->vatrate] += $obj->total_tva;
3749  $total_ttc_by_vats[$obj->vatrate] += $obj->total_ttc;
3750 
3751  if ($forcedroundingmode == '1') { // Check if we need adjustement onto line for vat. TODO This works on the company currency but not on multicurrency
3752  $tmpvat = price2num($total_ht_by_vats[$obj->vatrate] * $obj->vatrate / 100, 'MT', 1);
3753  $diff = price2num($total_tva_by_vats[$obj->vatrate] - $tmpvat, 'MT', 1);
3754  //print 'Line '.$i.' rowid='.$obj->rowid.' vat_rate='.$obj->vatrate.' total_ht='.$obj->total_ht.' total_tva='.$obj->total_tva.' total_ttc='.$obj->total_ttc.' total_ht_by_vats='.$total_ht_by_vats[$obj->vatrate].' total_tva_by_vats='.$total_tva_by_vats[$obj->vatrate].' (new calculation = '.$tmpvat.') total_ttc_by_vats='.$total_ttc_by_vats[$obj->vatrate].($diff?" => DIFF":"")."<br>\n";
3755  if ($diff) {
3756  if (abs($diff) > 0.1) {
3757  $errmsg = 'A rounding difference was detected into TOTAL but is too high to be corrected. Some data in your line may be corrupted. Try to edit each line manually.';
3758  dol_syslog($errmsg, LOG_WARNING);
3759  dol_print_error('', $errmsg);
3760  exit;
3761  }
3762  $sqlfix = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldtva." = ".price2num($obj->total_tva - $diff).", total_ttc = ".price2num($obj->total_ttc - $diff)." WHERE rowid = ".((int) $obj->rowid);
3763  dol_syslog('We found a difference of '.$diff.' for line rowid = '.$obj->rowid.". We fix the total_vat and total_ttc of line by running sqlfix = ".$sqlfix);
3764 
3765  $resqlfix = $this->db->query($sqlfix);
3766 
3767  if (!$resqlfix) {
3768  dol_print_error($this->db, 'Failed to update line');
3769  }
3770 
3771  $this->total_tva = (float) price2num($this->total_tva - $diff, '', 1);
3772  $this->total_ttc = (float) price2num($this->total_ttc - $diff, '', 1);
3773  $total_tva_by_vats[$obj->vatrate] = (float) price2num($total_tva_by_vats[$obj->vatrate] - $diff, '', 1);
3774  $total_ttc_by_vats[$obj->vatrate] = (float) price2num($total_ttc_by_vats[$obj->vatrate] - $diff, '', 1);
3775  }
3776  }
3777 
3778  $i++;
3779  }
3780 
3781  // Add revenue stamp to total
3782  $this->total_ttc += isset($this->revenuestamp) ? $this->revenuestamp : 0;
3783  $this->multicurrency_total_ttc += isset($this->revenuestamp) ? ($this->revenuestamp * $multicurrency_tx) : 0;
3784 
3785  // Situations totals
3786  if (!empty($this->situation_cycle_ref) && $this->situation_counter > 1 && method_exists($this, 'get_prev_sits') && $this->type != $this::TYPE_CREDIT_NOTE) {
3787  $prev_sits = $this->get_prev_sits();
3788 
3789  foreach ($prev_sits as $sit) { // $sit is an object Facture loaded with a fetch.
3790  $this->total_ht -= $sit->total_ht;
3791  $this->total_tva -= $sit->total_tva;
3792  $this->total_localtax1 -= $sit->total_localtax1;
3793  $this->total_localtax2 -= $sit->total_localtax2;
3794  $this->total_ttc -= $sit->total_ttc;
3795  $this->multicurrency_total_ht -= $sit->multicurrency_total_ht;
3796  $this->multicurrency_total_tva -= $sit->multicurrency_total_tva;
3797  $this->multicurrency_total_ttc -= $sit->multicurrency_total_ttc;
3798  }
3799  }
3800 
3801  // Clean total
3802  $this->total_ht = (float) price2num($this->total_ht);
3803  $this->total_tva = (float) price2num($this->total_tva);
3804  $this->total_localtax1 = (float) price2num($this->total_localtax1);
3805  $this->total_localtax2 = (float) price2num($this->total_localtax2);
3806  $this->total_ttc = (float) price2num($this->total_ttc);
3807 
3808  $this->db->free($resql);
3809 
3810  // Now update global fields total_ht, total_ttc, total_tva, total_localtax1, total_localtax2, multicurrency_total_* of main object
3811  $fieldht = 'total_ht';
3812  $fieldtva = 'tva';
3813  $fieldlocaltax1 = 'localtax1';
3814  $fieldlocaltax2 = 'localtax2';
3815  $fieldttc = 'total_ttc';
3816  // Specific code for backward compatibility with old field names
3817  if (in_array($this->element, array('propal', 'commande', 'facture', 'facturerec', 'supplier_proposal', 'order_supplier', 'facture_fourn', 'invoice_supplier', 'invoice_supplier_rec', 'expensereport'))) {
3818  $fieldtva = 'total_tva';
3819  }
3820 
3821  if (empty($nodatabaseupdate)) {
3822  $sql = "UPDATE ".$this->db->prefix().$this->table_element.' SET';
3823  $sql .= " ".$fieldht." = ".((float) price2num($this->total_ht, 'MT', 1)).",";
3824  $sql .= " ".$fieldtva." = ".((float) price2num($this->total_tva, 'MT', 1)).",";
3825  $sql .= " ".$fieldlocaltax1." = ".((float) price2num($this->total_localtax1, 'MT', 1)).",";
3826  $sql .= " ".$fieldlocaltax2." = ".((float) price2num($this->total_localtax2, 'MT', 1)).",";
3827  $sql .= " ".$fieldttc." = ".((float) price2num($this->total_ttc, 'MT', 1));
3828  $sql .= ", multicurrency_total_ht = ".((float) price2num($this->multicurrency_total_ht, 'MT', 1));
3829  $sql .= ", multicurrency_total_tva = ".((float) price2num($this->multicurrency_total_tva, 'MT', 1));
3830  $sql .= ", multicurrency_total_ttc = ".((float) price2num($this->multicurrency_total_ttc, 'MT', 1));
3831  $sql .= " WHERE rowid = ".((int) $this->id);
3832 
3833  dol_syslog(get_class($this)."::update_price", LOG_DEBUG);
3834  $resql = $this->db->query($sql);
3835 
3836  if (!$resql) {
3837  $error++;
3838  $this->error = $this->db->lasterror();
3839  $this->errors[] = $this->db->lasterror();
3840  }
3841  }
3842 
3843  if (!$error) {
3844  return 1;
3845  } else {
3846  return -1;
3847  }
3848  } else {
3849  dol_print_error($this->db, 'Bad request in update_price');
3850  return -1;
3851  }
3852  }
3853 
3854  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3865  public function add_object_linked($origin = null, $origin_id = null, $f_user = null, $notrigger = 0)
3866  {
3867  // phpcs:enable
3868  global $user, $hookmanager, $action;
3869  $origin = (!empty($origin) ? $origin : $this->origin);
3870  $origin_id = (!empty($origin_id) ? $origin_id : $this->origin_id);
3871  $f_user = isset($f_user) ? $f_user : $user;
3872 
3873  // Special case
3874  if ($origin == 'order') {
3875  $origin = 'commande';
3876  }
3877  if ($origin == 'invoice') {
3878  $origin = 'facture';
3879  }
3880  if ($origin == 'invoice_template') {
3881  $origin = 'facturerec';
3882  }
3883  if ($origin == 'supplierorder') {
3884  $origin = 'order_supplier';
3885  }
3886 
3887  // Elements of the core modules which have `$module` property but may to which we don't want to prefix module part to the element name for finding the linked object in llx_element_element.
3888  // It's because an entry for this element may be exist in llx_element_element before this modification (version <=14.2) and ave named only with their element name in fk_source or fk_target.
3889  $coremodule = array('knowledgemanagement', 'partnership', 'workstation', 'ticket', 'recruitment', 'eventorganization', 'asset');
3890  // Add module part to target type if object has $module property and isn't in core modules.
3891  $targettype = ((!empty($this->module) && ! in_array($this->module, $coremodule)) ? $this->module.'_' : '').$this->element;
3892 
3893  $parameters = array('targettype'=>$targettype);
3894  // Hook for explicitly set the targettype if it must be differtent than $this->element
3895  $reshook = $hookmanager->executeHooks('setLinkedObjectSourceTargetType', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
3896  if ($reshook > 0) {
3897  if (!empty($hookmanager->resArray['targettype'])) $targettype = $hookmanager->resArray['targettype'];
3898  }
3899 
3900  $this->db->begin();
3901  $error = 0;
3902 
3903  $sql = "INSERT INTO " . $this->db->prefix() . "element_element (";
3904  $sql .= "fk_source";
3905  $sql .= ", sourcetype";
3906  $sql .= ", fk_target";
3907  $sql .= ", targettype";
3908  $sql .= ") VALUES (";
3909  $sql .= ((int) $origin_id);
3910  $sql .= ", '" . $this->db->escape($origin) . "'";
3911  $sql .= ", " . ((int) $this->id);
3912  $sql .= ", '" . $this->db->escape($targettype) . "'";
3913  $sql .= ")";
3914 
3915  dol_syslog(get_class($this) . "::add_object_linked", LOG_DEBUG);
3916  if ($this->db->query($sql)) {
3917  if (!$notrigger) {
3918  // Call trigger
3919  $this->context['link_origin'] = $origin;
3920  $this->context['link_origin_id'] = $origin_id;
3921  $result = $this->call_trigger('OBJECT_LINK_INSERT', $f_user);
3922  if ($result < 0) {
3923  $error++;
3924  }
3925  // End call triggers
3926  }
3927  } else {
3928  $this->error = $this->db->lasterror();
3929  $error++;
3930  }
3931 
3932  if (!$error) {
3933  $this->db->commit();
3934  return 1;
3935  } else {
3936  $this->db->rollback();
3937  return 0;
3938  }
3939  }
3940 
3963  public function fetchObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $clause = 'OR', $alsosametype = 1, $orderby = 'sourcetype', $loadalsoobjects = 1)
3964  {
3965  global $conf, $hookmanager, $action;
3966 
3967  // Important for pdf generation time reduction
3968  // This boolean is true if $this->linkedObjects has already been loaded with all objects linked without filter
3969  if ($this->id > 0 && !empty($this->linkedObjectsFullLoaded[$this->id])) {
3970  return 1;
3971  }
3972 
3973  $this->linkedObjectsIds = array();
3974  $this->linkedObjects = array();
3975 
3976  $justsource = false;
3977  $justtarget = false;
3978  $withtargettype = false;
3979  $withsourcetype = false;
3980 
3981  $parameters = array('sourcetype'=>$sourcetype, 'sourceid'=>$sourceid, 'targettype'=>$targettype, 'targetid'=>$targetid);
3982  // Hook for explicitly set the targettype if it must be differtent than $this->element
3983  $reshook = $hookmanager->executeHooks('setLinkedObjectSourceTargetType', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
3984  if ($reshook > 0) {
3985  if (!empty($hookmanager->resArray['sourcetype'])) $sourcetype = $hookmanager->resArray['sourcetype'];
3986  if (!empty($hookmanager->resArray['sourceid'])) $sourceid = $hookmanager->resArray['sourceid'];
3987  if (!empty($hookmanager->resArray['targettype'])) $targettype = $hookmanager->resArray['targettype'];
3988  if (!empty($hookmanager->resArray['targetid'])) $targetid = $hookmanager->resArray['targetid'];
3989  }
3990 
3991  if (!empty($sourceid) && !empty($sourcetype) && empty($targetid)) {
3992  $justsource = true; // the source (id and type) is a search criteria
3993  if (!empty($targettype)) {
3994  $withtargettype = true;
3995  }
3996  }
3997  if (!empty($targetid) && !empty($targettype) && empty($sourceid)) {
3998  $justtarget = true; // the target (id and type) is a search criteria
3999  if (!empty($sourcetype)) {
4000  $withsourcetype = true;
4001  }
4002  }
4003 
4004  $sourceid = (!empty($sourceid) ? $sourceid : $this->id);
4005  $targetid = (!empty($targetid) ? $targetid : $this->id);
4006  $sourcetype = (!empty($sourcetype) ? $sourcetype : $this->element);
4007  $targettype = (!empty($targettype) ? $targettype : $this->element);
4008 
4009  /*if (empty($sourceid) && empty($targetid))
4010  {
4011  dol_syslog('Bad usage of function. No source nor target id defined (nor as parameter nor as object id)', LOG_ERR);
4012  return -1;
4013  }*/
4014 
4015  // Links between objects are stored in table element_element
4016  $sql = "SELECT rowid, fk_source, sourcetype, fk_target, targettype";
4017  $sql .= " FROM ".$this->db->prefix()."element_element";
4018  $sql .= " WHERE ";
4019  if ($justsource || $justtarget) {
4020  if ($justsource) {
4021  $sql .= "fk_source = ".((int) $sourceid)." AND sourcetype = '".$this->db->escape($sourcetype)."'";
4022  if ($withtargettype) {
4023  $sql .= " AND targettype = '".$this->db->escape($targettype)."'";
4024  }
4025  } elseif ($justtarget) {
4026  $sql .= "fk_target = ".((int) $targetid)." AND targettype = '".$this->db->escape($targettype)."'";
4027  if ($withsourcetype) {
4028  $sql .= " AND sourcetype = '".$this->db->escape($sourcetype)."'";
4029  }
4030  }
4031  } else {
4032  $sql .= "(fk_source = ".((int) $sourceid)." AND sourcetype = '".$this->db->escape($sourcetype)."')";
4033  $sql .= " ".$clause." (fk_target = ".((int) $targetid)." AND targettype = '".$this->db->escape($targettype)."')";
4034  if ($loadalsoobjects && $this->id > 0 && $sourceid == $this->id && $sourcetype == $this->element && $targetid == $this->id && $targettype == $this->element && $clause == 'OR') {
4035  $this->linkedObjectsFullLoaded[$this->id] = true;
4036  }
4037  }
4038  $sql .= " ORDER BY ".$orderby;
4039 
4040  dol_syslog(get_class($this)."::fetchObjectLink", LOG_DEBUG);
4041  $resql = $this->db->query($sql);
4042  if ($resql) {
4043  $num = $this->db->num_rows($resql);
4044  $i = 0;
4045  while ($i < $num) {
4046  $obj = $this->db->fetch_object($resql);
4047  if ($justsource || $justtarget) {
4048  if ($justsource) {
4049  $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
4050  } elseif ($justtarget) {
4051  $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
4052  }
4053  } else {
4054  if ($obj->fk_source == $sourceid && $obj->sourcetype == $sourcetype) {
4055  $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
4056  }
4057  if ($obj->fk_target == $targetid && $obj->targettype == $targettype) {
4058  $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
4059  }
4060  }
4061  $i++;
4062  }
4063 
4064  if (!empty($this->linkedObjectsIds)) {
4065  $tmparray = $this->linkedObjectsIds;
4066  foreach ($tmparray as $objecttype => $objectids) { // $objecttype is a module name ('facture', 'mymodule', ...) or a module name with a suffix ('project_task', 'mymodule_myobj', ...)
4067  // Parse element/subelement (ex: project_task, cabinetmed_consultation, ...)
4068  $module = $element = $subelement = $objecttype;
4069  $regs = array();
4070  if ($objecttype != 'supplier_proposal' && $objecttype != 'order_supplier' && $objecttype != 'invoice_supplier'
4071  && preg_match('/^([^_]+)_([^_]+)/i', $objecttype, $regs)) {
4072  $module = $element = $regs[1];
4073  $subelement = $regs[2];
4074  }
4075 
4076  $classpath = $element.'/class';
4077  // To work with non standard classpath or module name
4078  if ($objecttype == 'facture') {
4079  $classpath = 'compta/facture/class';
4080  } elseif ($objecttype == 'facturerec') {
4081  $classpath = 'compta/facture/class';
4082  $module = 'facture';
4083  } elseif ($objecttype == 'propal') {
4084  $classpath = 'comm/propal/class';
4085  } elseif ($objecttype == 'supplier_proposal') {
4086  $classpath = 'supplier_proposal/class';
4087  } elseif ($objecttype == 'shipping') {
4088  $classpath = 'expedition/class';
4089  $subelement = 'expedition';
4090  $module = 'expedition_bon';
4091  } elseif ($objecttype == 'delivery') {
4092  $classpath = 'delivery/class';
4093  $subelement = 'delivery';
4094  $module = 'delivery_note';
4095  } elseif ($objecttype == 'invoice_supplier' || $objecttype == 'order_supplier') {
4096  $classpath = 'fourn/class';
4097  $module = 'fournisseur';
4098  } elseif ($objecttype == 'fichinter') {
4099  $classpath = 'fichinter/class';
4100  $subelement = 'fichinter';
4101  $module = 'ficheinter';
4102  } elseif ($objecttype == 'subscription') {
4103  $classpath = 'adherents/class';
4104  $module = 'adherent';
4105  } elseif ($objecttype == 'contact') {
4106  $module = 'societe';
4107  }
4108  // Set classfile
4109  $classfile = strtolower($subelement);
4110  $classname = ucfirst($subelement);
4111 
4112  if ($objecttype == 'order') {
4113  $classfile = 'commande';
4114  $classname = 'Commande';
4115  } elseif ($objecttype == 'invoice_supplier') {
4116  $classfile = 'fournisseur.facture';
4117  $classname = 'FactureFournisseur';
4118  } elseif ($objecttype == 'order_supplier') {
4119  $classfile = 'fournisseur.commande';
4120  $classname = 'CommandeFournisseur';
4121  } elseif ($objecttype == 'supplier_proposal') {
4122  $classfile = 'supplier_proposal';
4123  $classname = 'SupplierProposal';
4124  } elseif ($objecttype == 'facturerec') {
4125  $classfile = 'facture-rec';
4126  $classname = 'FactureRec';
4127  } elseif ($objecttype == 'subscription') {
4128  $classfile = 'subscription';
4129  $classname = 'Subscription';
4130  } elseif ($objecttype == 'project' || $objecttype == 'projet') {
4131  $classpath = 'projet/class';
4132  $classfile = 'project';
4133  $classname = 'Project';
4134  } elseif ($objecttype == 'conferenceorboothattendee') {
4135  $classpath = 'eventorganization/class';
4136  $classfile = 'conferenceorboothattendee';
4137  $classname = 'ConferenceOrBoothAttendee';
4138  $module = 'eventorganization';
4139  } elseif ($objecttype == 'conferenceorbooth') {
4140  $classpath = 'eventorganization/class';
4141  $classfile = 'conferenceorbooth';
4142  $classname = 'ConferenceOrBooth';
4143  $module = 'eventorganization';
4144  } elseif ($objecttype == 'mo') {
4145  $classpath = 'mrp/class';
4146  $classfile = 'mo';
4147  $classname = 'Mo';
4148  $module = 'mrp';
4149  }
4150 
4151  // Here $module, $classfile and $classname are set, we can use them.
4152  if (isModEnabled($module) && (($element != $this->element) || $alsosametype)) {
4153  if ($loadalsoobjects && (is_numeric($loadalsoobjects) || ($loadalsoobjects === $objecttype))) {
4154  dol_include_once('/'.$classpath.'/'.$classfile.'.class.php');
4155  //print '/'.$classpath.'/'.$classfile.'.class.php '.class_exists($classname);
4156  if (class_exists($classname)) {
4157  foreach ($objectids as $i => $objectid) { // $i is rowid into llx_element_element
4158  $object = new $classname($this->db);
4159  $ret = $object->fetch($objectid);
4160  if ($ret >= 0) {
4161  $this->linkedObjects[$objecttype][$i] = $object;
4162  }
4163  }
4164  }
4165  }
4166  } else {
4167  unset($this->linkedObjectsIds[$objecttype]);
4168  }
4169  }
4170  }
4171  return 1;
4172  } else {
4173  dol_print_error($this->db);
4174  return -1;
4175  }
4176  }
4177 
4184  public function clearObjectLinkedCache()
4185  {
4186  if ($this->id > 0 && !empty($this->linkedObjectsFullLoaded[$this->id])) {
4187  unset($this->linkedObjectsFullLoaded[$this->id]);
4188  }
4189 
4190  return 1;
4191  }
4192 
4205  public function updateObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $f_user = null, $notrigger = 0)
4206  {
4207  global $user;
4208  $updatesource = false;
4209  $updatetarget = false;
4210  $f_user = isset($f_user) ? $f_user : $user;
4211 
4212  if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) {
4213  $updatesource = true;
4214  } elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) {
4215  $updatetarget = true;
4216  }
4217 
4218  $this->db->begin();
4219  $error = 0;
4220 
4221  $sql = "UPDATE " . $this->db->prefix() . "element_element SET ";
4222  if ($updatesource) {
4223  $sql .= "fk_source = " . ((int) $sourceid);
4224  $sql .= ", sourcetype = '" . $this->db->escape($sourcetype) . "'";
4225  $sql .= " WHERE fk_target = " . ((int) $this->id);
4226  $sql .= " AND targettype = '" . $this->db->escape($this->element) . "'";
4227  } elseif ($updatetarget) {
4228  $sql .= "fk_target = " . ((int) $targetid);
4229  $sql .= ", targettype = '" . $this->db->escape($targettype) . "'";
4230  $sql .= " WHERE fk_source = " . ((int) $this->id);
4231  $sql .= " AND sourcetype = '" . $this->db->escape($this->element) . "'";
4232  }
4233 
4234  dol_syslog(get_class($this) . "::updateObjectLinked", LOG_DEBUG);
4235  if ($this->db->query($sql)) {
4236  if (!$notrigger) {
4237  // Call trigger
4238  $this->context['link_source_id'] = $sourceid;
4239  $this->context['link_source_type'] = $sourcetype;
4240  $this->context['link_target_id'] = $targetid;
4241  $this->context['link_target_type'] = $targettype;
4242  $result = $this->call_trigger('OBJECT_LINK_MODIFY', $f_user);
4243  if ($result < 0) {
4244  $error++;
4245  }
4246  // End call triggers
4247  }
4248  } else {
4249  $this->error = $this->db->lasterror();
4250  $error++;
4251  }
4252 
4253  if (!$error) {
4254  $this->db->commit();
4255  return 1;
4256  } else {
4257  $this->db->rollback();
4258  return -1;
4259  }
4260  }
4261 
4275  public function deleteObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $rowid = '', $f_user = null, $notrigger = 0)
4276  {
4277  global $user;
4278  $deletesource = false;
4279  $deletetarget = false;
4280  $f_user = isset($f_user) ? $f_user : $user;
4281 
4282  if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) {
4283  $deletesource = true;
4284  } elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) {
4285  $deletetarget = true;
4286  }
4287 
4288  $sourceid = (!empty($sourceid) ? $sourceid : $this->id);
4289  $sourcetype = (!empty($sourcetype) ? $sourcetype : $this->element);
4290  $targetid = (!empty($targetid) ? $targetid : $this->id);
4291  $targettype = (!empty($targettype) ? $targettype : $this->element);
4292  $this->db->begin();
4293  $error = 0;
4294 
4295  if (!$notrigger) {
4296  // Call trigger
4297  $this->context['link_id'] = $rowid;
4298  $this->context['link_source_id'] = $sourceid;
4299  $this->context['link_source_type'] = $sourcetype;
4300  $this->context['link_target_id'] = $targetid;
4301  $this->context['link_target_type'] = $targettype;
4302  $result = $this->call_trigger('OBJECT_LINK_DELETE', $f_user);
4303  if ($result < 0) {
4304  $error++;
4305  }
4306  // End call triggers
4307  }
4308 
4309  if (!$error) {
4310  $sql = "DELETE FROM " . $this->db->prefix() . "element_element";
4311  $sql .= " WHERE";
4312  if ($rowid > 0) {
4313  $sql .= " rowid = " . ((int) $rowid);
4314  } else {
4315  if ($deletesource) {
4316  $sql .= " fk_source = " . ((int) $sourceid) . " AND sourcetype = '" . $this->db->escape($sourcetype) . "'";
4317  $sql .= " AND fk_target = " . ((int) $this->id) . " AND targettype = '" . $this->db->escape($this->element) . "'";
4318  } elseif ($deletetarget) {
4319  $sql .= " fk_target = " . ((int) $targetid) . " AND targettype = '" . $this->db->escape($targettype) . "'";
4320  $sql .= " AND fk_source = " . ((int) $this->id) . " AND sourcetype = '" . $this->db->escape($this->element) . "'";
4321  } else {
4322  $sql .= " (fk_source = " . ((int) $this->id) . " AND sourcetype = '" . $this->db->escape($this->element) . "')";
4323  $sql .= " OR";
4324  $sql .= " (fk_target = " . ((int) $this->id) . " AND targettype = '" . $this->db->escape($this->element) . "')";
4325  }
4326  }
4327 
4328  dol_syslog(get_class($this) . "::deleteObjectLinked", LOG_DEBUG);
4329  if (!$this->db->query($sql)) {
4330  $this->error = $this->db->lasterror();
4331  $this->errors[] = $this->error;
4332  $error++;
4333  }
4334  }
4335 
4336  if (!$error) {
4337  $this->db->commit();
4338  return 1;
4339  } else {
4340  $this->db->rollback();
4341  return 0;
4342  }
4343  }
4344 
4354  public static function getAllItemsLinkedByObjectID($fk_object_where, $field_select, $field_where, $table_element)
4355  {
4356  if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
4357  return -1;
4358  }
4359 
4360  global $db;
4361 
4362  $sql = "SELECT ".$field_select." FROM ".$db->prefix().$table_element." WHERE ".$field_where." = ".((int) $fk_object_where);
4363  $resql = $db->query($sql);
4364 
4365  $TRes = array();
4366  if (!empty($resql)) {
4367  while ($res = $db->fetch_object($resql)) {
4368  $TRes[] = $res->{$field_select};
4369  }
4370  }
4371 
4372  return $TRes;
4373  }
4374 
4383  public static function deleteAllItemsLinkedByObjectID($fk_object_where, $field_where, $table_element)
4384  {
4385  if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
4386  return -1;
4387  }
4388 
4389  global $db;
4390 
4391  $sql = "DELETE FROM ".$db->prefix().$table_element." WHERE ".$field_where." = ".((int) $fk_object_where);
4392  $resql = $db->query($sql);
4393 
4394  if (empty($resql)) {
4395  return 0;
4396  }
4397 
4398  return 1;
4399  }
4400 
4411  public function setStatut($status, $elementId = null, $elementType = '', $trigkey = '', $fieldstatus = 'fk_statut')
4412  {
4413  global $user, $langs, $conf;
4414 
4415  $savElementId = $elementId; // To be used later to know if we were using the method using the id of this or not.
4416 
4417  $elementId = (!empty($elementId) ? $elementId : $this->id);
4418  $elementTable = (!empty($elementType) ? $elementType : $this->table_element);
4419 
4420  $this->db->begin();
4421 
4422  if ($elementTable == 'facture_rec') {
4423  $fieldstatus = "suspended";
4424  }
4425  if ($elementTable == 'mailing') {
4426  $fieldstatus = "statut";
4427  }
4428  if ($elementTable == 'cronjob') {
4429  $fieldstatus = "status";
4430  }
4431  if ($elementTable == 'user') {
4432  $fieldstatus = "statut";
4433  }
4434  if ($elementTable == 'expensereport') {
4435  $fieldstatus = "fk_statut";
4436  }
4437  if ($elementTable == 'commande_fournisseur_dispatch') {
4438  $fieldstatus = "status";
4439  }
4440  if (isset($this->fields) && is_array($this->fields) && array_key_exists('status', $this->fields)) {
4441  $fieldstatus = 'status';
4442  }
4443 
4444  $sql = "UPDATE ".$this->db->prefix().$elementTable;
4445  $sql .= " SET ".$fieldstatus." = ".((int) $status);
4446  // If status = 1 = validated, update also fk_user_valid
4447  // TODO Replace the test on $elementTable by doing a test on existence of the field in $this->fields
4448  if ($status == 1 && in_array($elementTable, array('expensereport', 'inventory'))) {
4449  $sql .= ", fk_user_valid = ".((int) $user->id);
4450  }
4451  if ($status == 1 && in_array($elementTable, array('expensereport'))) {
4452  $sql .= ", date_valid = '".$this->db->idate(dol_now())."'";
4453  }
4454  if ($status == 1 && in_array($elementTable, array('inventory'))) {
4455  $sql .= ", date_validation = '".$this->db->idate(dol_now())."'";
4456  }
4457  $sql .= " WHERE rowid = ".((int) $elementId);
4458  $sql .= " AND ".$fieldstatus." <> ".((int) $status); // We avoid update if status already correct
4459 
4460  dol_syslog(get_class($this)."::setStatut", LOG_DEBUG);
4461  $resql = $this->db->query($sql);
4462  if ($resql) {
4463  $error = 0;
4464 
4465  $nb_rows_affected = $this->db->affected_rows($resql); // should be 1 or 0 if status was already correct
4466 
4467  if ($nb_rows_affected > 0) {
4468  if (empty($trigkey)) {
4469  // Try to guess trigkey (for backward compatibility, now we should have trigkey defined into the call of setStatus)
4470  if ($this->element == 'supplier_proposal' && $status == 2) {
4471  $trigkey = 'SUPPLIER_PROPOSAL_SIGN'; // 2 = SupplierProposal::STATUS_SIGNED. Can't use constant into this generic class
4472  }
4473  if ($this->element == 'supplier_proposal' && $status == 3) {
4474  $trigkey = 'SUPPLIER_PROPOSAL_REFUSE'; // 3 = SupplierProposal::STATUS_REFUSED. Can't use constant into this generic class
4475  }
4476  if ($this->element == 'supplier_proposal' && $status == 4) {
4477  $trigkey = 'SUPPLIER_PROPOSAL_CLOSE'; // 4 = SupplierProposal::STATUS_CLOSED. Can't use constant into this generic class
4478  }
4479  if ($this->element == 'fichinter' && $status == 3) {
4480  $trigkey = 'FICHINTER_CLASSIFY_DONE';
4481  }
4482  if ($this->element == 'fichinter' && $status == 2) {
4483  $trigkey = 'FICHINTER_CLASSIFY_BILLED';
4484  }
4485  if ($this->element == 'fichinter' && $status == 1) {
4486  $trigkey = 'FICHINTER_CLASSIFY_UNBILLED';
4487  }
4488  }
4489 
4490  if ($trigkey) {
4491  // Call trigger
4492  $result = $this->call_trigger($trigkey, $user);
4493  if ($result < 0) {
4494  $error++;
4495  }
4496  // End call triggers
4497  }
4498  } else {
4499  // The status was probably already good. We do nothing more, no triggers.
4500  }
4501 
4502  if (!$error) {
4503  $this->db->commit();
4504 
4505  if (empty($savElementId)) {
4506  // If the element we update is $this (so $elementId was provided as null)
4507  if ($fieldstatus == 'tosell') {
4508  $this->status = $status;
4509  } elseif ($fieldstatus == 'tobuy') {
4510  $this->status_buy = $status;
4511  } else {
4512  $this->statut = $status;
4513  $this->status = $status;
4514  }
4515  }
4516 
4517  return 1;
4518  } else {
4519  $this->db->rollback();
4520  dol_syslog(get_class($this)."::setStatut ".$this->error, LOG_ERR);
4521  return -1;
4522  }
4523  } else {
4524  $this->error = $this->db->lasterror();
4525  $this->db->rollback();
4526  return -1;
4527  }
4528  }
4529 
4530 
4538  public function getCanvas($id = 0, $ref = '')
4539  {
4540  global $conf;
4541 
4542  if (empty($id) && empty($ref)) {
4543  return 0;
4544  }
4545  if (!empty($conf->global->MAIN_DISABLE_CANVAS)) {
4546  return 0; // To increase speed. Not enabled by default.
4547  }
4548 
4549  // Clean parameters
4550  $ref = trim($ref);
4551 
4552  $sql = "SELECT rowid, canvas";
4553  $sql .= " FROM ".$this->db->prefix().$this->table_element;
4554  $sql .= " WHERE entity IN (".getEntity($this->element).")";
4555  if (!empty($id)) {
4556  $sql .= " AND rowid = ".((int) $id);
4557  }
4558  if (!empty($ref)) {
4559  $sql .= " AND ref = '".$this->db->escape($ref)."'";
4560  }
4561 
4562  $resql = $this->db->query($sql);
4563  if ($resql) {
4564  $obj = $this->db->fetch_object($resql);
4565  if ($obj) {
4566  $this->canvas = $obj->canvas;
4567  return 1;
4568  } else {
4569  return 0;
4570  }
4571  } else {
4572  dol_print_error($this->db);
4573  return -1;
4574  }
4575  }
4576 
4577 
4584  public function getSpecialCode($lineid)
4585  {
4586  $sql = "SELECT special_code FROM ".$this->db->prefix().$this->table_element_line;
4587  $sql .= " WHERE rowid = ".((int) $lineid);
4588  $resql = $this->db->query($sql);
4589  if ($resql) {
4590  $row = $this->db->fetch_row($resql);
4591  return $row[0];
4592  }
4593 
4594  return 0;
4595  }
4596 
4605  public function isObjectUsed($id = 0, $entity = 0)
4606  {
4607  global $langs;
4608 
4609  if (empty($id)) {
4610  $id = $this->id;
4611  }
4612 
4613  // Check parameters
4614  if (!isset($this->childtables) || !is_array($this->childtables) || count($this->childtables) == 0) {
4615  dol_print_error('Called isObjectUsed on a class with property this->childtables not defined');
4616  return -1;
4617  }
4618 
4619  $arraytoscan = $this->childtables;
4620  // For backward compatibility, we check if array is old format array('table1', 'table2', ...)
4621  $tmparray = array_keys($this->childtables);
4622  if (is_numeric($tmparray[0])) {
4623  $arraytoscan = array_flip($this->childtables);
4624  }
4625 
4626  // Test if child exists
4627  $haschild = 0;
4628  foreach ($arraytoscan as $table => $element) {
4629  //print $id.'-'.$table.'-'.$elementname.'<br>';
4630  // Check if element can be deleted
4631  $sql = "SELECT COUNT(*) as nb";
4632  $sql.= " FROM ".$this->db->prefix().$table." as c";
4633  if (!empty($element['parent']) && !empty($element['parentkey'])) {
4634  $sql.= ", ".$this->db->prefix().$element['parent']." as p";
4635  }
4636  $sql.= " WHERE c.".$this->fk_element." = ".((int) $id);
4637  if (!empty($element['parent']) && !empty($element['parentkey'])) {
4638  $sql.= " AND c.".$element['parentkey']." = p.rowid";
4639  }
4640  if (!empty($entity)) {
4641  if (!empty($element['parent']) && !empty($element['parentkey'])) {
4642  $sql.= " AND p.entity = ".((int) $entity);
4643  } else {
4644  $sql.= " AND c.entity = ".((int) $entity);
4645  }
4646  }
4647  $resql = $this->db->query($sql);
4648  if ($resql) {
4649  $obj = $this->db->fetch_object($resql);
4650  if ($obj->nb > 0) {
4651  $langs->load("errors");
4652  //print 'Found into table '.$table.', type '.$langs->transnoentitiesnoconv($elementname).', haschild='.$haschild;
4653  $haschild += $obj->nb;
4654  if (is_numeric($element)) { // very old usage array('table1', 'table2', ...)
4655  $this->errors[] = $langs->transnoentitiesnoconv("ErrorRecordHasAtLeastOneChildOfType", method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref, $table);
4656  } elseif (is_string($element)) { // old usage array('table1' => 'TranslateKey1', 'table2' => 'TranslateKey2', ...)
4657  $this->errors[] = $langs->transnoentitiesnoconv("ErrorRecordHasAtLeastOneChildOfType", method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref, $langs->transnoentitiesnoconv($element));
4658  } else { // new usage: $element['name']=Translation key
4659  $this->errors[] = $langs->transnoentitiesnoconv("ErrorRecordHasAtLeastOneChildOfType", method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref, $langs->transnoentitiesnoconv($element['name']));
4660  }
4661  break; // We found at least one, we stop here
4662  }
4663  } else {
4664  $this->errors[] = $this->db->lasterror();
4665  return -1;
4666  }
4667  }
4668  if ($haschild > 0) {
4669  $this->errors[] = "ErrorRecordHasChildren";
4670  return $haschild;
4671  } else {
4672  return 0;
4673  }
4674  }
4675 
4682  public function hasProductsOrServices($predefined = -1)
4683  {
4684  $nb = 0;
4685 
4686  foreach ($this->lines as $key => $val) {
4687  $qualified = 0;
4688  if ($predefined == -1) {
4689  $qualified = 1;
4690  }
4691  if ($predefined == 1 && $val->fk_product > 0) {
4692  $qualified = 1;
4693  }
4694  if ($predefined == 0 && $val->fk_product <= 0) {
4695  $qualified = 1;
4696  }
4697  if ($predefined == 2 && $val->fk_product > 0 && $val->product_type == 0) {
4698  $qualified = 1;
4699  }
4700  if ($predefined == 3 && $val->fk_product > 0 && $val->product_type == 1) {
4701  $qualified = 1;
4702  }
4703  if ($qualified) {
4704  $nb++;
4705  }
4706  }
4707  dol_syslog(get_class($this).'::hasProductsOrServices we found '.$nb.' qualified lines of products/servcies');
4708  return $nb;
4709  }
4710 
4716  public function getTotalDiscount()
4717  {
4718  if (!empty($this->table_element_line) ) {
4719  $total_discount = 0.00;
4720 
4721  $sql = "SELECT subprice as pu_ht, qty, remise_percent, total_ht";
4722  $sql .= " FROM ".$this->db->prefix().$this->table_element_line;
4723  $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
4724 
4725  dol_syslog(get_class($this).'::getTotalDiscount', LOG_DEBUG);
4726  $resql = $this->db->query($sql);
4727  if ($resql) {
4728  $num = $this->db->num_rows($resql);
4729  $i = 0;
4730  while ($i < $num) {
4731  $obj = $this->db->fetch_object($resql);
4732 
4733  $pu_ht = $obj->pu_ht;
4734  $qty = $obj->qty;
4735  $total_ht = $obj->total_ht;
4736 
4737  $total_discount_line = floatval(price2num(($pu_ht * $qty) - $total_ht, 'MT'));
4738  $total_discount += $total_discount_line;
4739 
4740  $i++;
4741  }
4742  }
4743 
4744  //print $total_discount; exit;
4745  return price2num($total_discount);
4746  }
4747 
4748  return null;
4749  }
4750 
4751 
4758  public function getTotalWeightVolume()
4759  {
4760  $totalWeight = 0;
4761  $totalVolume = 0;
4762  // defined for shipment only
4763  $totalOrdered = '';
4764  // defined for shipment only
4765  $totalToShip = '';
4766 
4767  foreach ($this->lines as $line) {
4768  if (isset($line->qty_asked)) {
4769  if (empty($totalOrdered)) {
4770  $totalOrdered = 0; // Avoid warning because $totalOrdered is ''
4771  }
4772  $totalOrdered += $line->qty_asked; // defined for shipment only
4773  }
4774  if (isset($line->qty_shipped)) {
4775  if (empty($totalToShip)) {
4776  $totalToShip = 0; // Avoid warning because $totalToShip is ''
4777  }
4778  $totalToShip += $line->qty_shipped; // defined for shipment only
4779  } elseif ($line->element == 'commandefournisseurdispatch' && isset($line->qty)) {
4780  if (empty($totalToShip)) {
4781  $totalToShip = 0;
4782  }
4783  $totalToShip += $line->qty; // defined for reception only
4784  }
4785 
4786  // Define qty, weight, volume, weight_units, volume_units
4787  if ($this->element == 'shipping') {
4788  // for shipments
4789  $qty = $line->qty_shipped ? $line->qty_shipped : 0;
4790  } else {
4791  $qty = $line->qty ? $line->qty : 0;
4792  }
4793 
4794  $weight = !empty($line->weight) ? $line->weight : 0;
4795  ($weight == 0 && !empty($line->product->weight)) ? $weight = $line->product->weight : 0;
4796  $volume = !empty($line->volume) ? $line->volume : 0;
4797  ($volume == 0 && !empty($line->product->volume)) ? $volume = $line->product->volume : 0;
4798 
4799  $weight_units = !empty($line->weight_units) ? $line->weight_units : 0;
4800  ($weight_units == 0 && !empty($line->product->weight_units)) ? $weight_units = $line->product->weight_units : 0;
4801  $volume_units = !empty($line->volume_units) ? $line->volume_units : 0;
4802  ($volume_units == 0 && !empty($line->product->volume_units)) ? $volume_units = $line->product->volume_units : 0;
4803 
4804  $weightUnit = 0;
4805  $volumeUnit = 0;
4806  if (!empty($weight_units)) {
4807  $weightUnit = $weight_units;
4808  }
4809  if (!empty($volume_units)) {
4810  $volumeUnit = $volume_units;
4811  }
4812 
4813  if (empty($totalWeight)) {
4814  $totalWeight = 0; // Avoid warning because $totalWeight is ''
4815  }
4816  if (empty($totalVolume)) {
4817  $totalVolume = 0; // Avoid warning because $totalVolume is ''
4818  }
4819 
4820  //var_dump($line->volume_units);
4821  if ($weight_units < 50) { // < 50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch)
4822  $trueWeightUnit = pow(10, $weightUnit);
4823  $totalWeight += $weight * $qty * $trueWeightUnit;
4824  } else {
4825  if ($weight_units == 99) {
4826  // conversion 1 Pound = 0.45359237 KG
4827  $trueWeightUnit = 0.45359237;
4828  $totalWeight += $weight * $qty * $trueWeightUnit;
4829  } elseif ($weight_units == 98) {
4830  // conversion 1 Ounce = 0.0283495 KG
4831  $trueWeightUnit = 0.0283495;
4832  $totalWeight += $weight * $qty * $trueWeightUnit;
4833  } else {
4834  $totalWeight += $weight * $qty; // This may be wrong if we mix different units
4835  }
4836  }
4837  if ($volume_units < 50) { // >50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch)
4838  //print $line->volume."x".$line->volume_units."x".($line->volume_units < 50)."x".$volumeUnit;
4839  $trueVolumeUnit = pow(10, $volumeUnit);
4840  //print $line->volume;
4841  $totalVolume += $volume * $qty * $trueVolumeUnit;
4842  } else {
4843  $totalVolume += $volume * $qty; // This may be wrong if we mix different units
4844  }
4845  }
4846 
4847  return array('weight'=>$totalWeight, 'volume'=>$totalVolume, 'ordered'=>$totalOrdered, 'toship'=>$totalToShip);
4848  }
4849 
4850 
4856  public function setExtraParameters()
4857  {
4858  $this->db->begin();
4859 
4860  $extraparams = (!empty($this->extraparams) ? json_encode($this->extraparams) : null);
4861 
4862  $sql = "UPDATE ".$this->db->prefix().$this->table_element;
4863  $sql .= " SET extraparams = ".(!empty($extraparams) ? "'".$this->db->escape($extraparams)."'" : "null");
4864  $sql .= " WHERE rowid = ".((int) $this->id);
4865 
4866  dol_syslog(get_class($this)."::setExtraParameters", LOG_DEBUG);
4867  $resql = $this->db->query($sql);
4868  if (!$resql) {
4869  $this->error = $this->db->lasterror();
4870  $this->db->rollback();
4871  return -1;
4872  } else {
4873  $this->db->commit();
4874  return 1;
4875  }
4876  }
4877 
4878 
4879  // --------------------
4880  // TODO: All functions here must be redesigned and moved as they are not business functions but output functions
4881  // --------------------
4882 
4883  /* This is to show add lines */
4884 
4894  public function formAddObjectLine($dateSelector, $seller, $buyer, $defaulttpldir = '/core/tpl')
4895  {
4896  global $conf, $user, $langs, $object, $hookmanager, $extrafields;
4897  global $form;
4898 
4899  // Line extrafield
4900  if (!is_object($extrafields)) {
4901  require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
4902  $extrafields = new ExtraFields($this->db);
4903  }
4904  $extrafields->fetch_name_optionals_label($this->table_element_line);
4905 
4906  // Output template part (modules that overwrite templates must declare this into descriptor)
4907  // Use global variables + $dateSelector + $seller and $buyer
4908  // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook 'formAddObjectLine'.
4909  $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
4910  foreach ($dirtpls as $module => $reldir) {
4911  if (!empty($module)) {
4912  $tpl = dol_buildpath($reldir.'/objectline_create.tpl.php');
4913  } else {
4914  $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_create.tpl.php';
4915  }
4916 
4917  if (empty($conf->file->strict_mode)) {
4918  $res = @include $tpl;
4919  } else {
4920  $res = include $tpl; // for debug
4921  }
4922  if ($res) {
4923  break;
4924  }
4925  }
4926  }
4927 
4928 
4929 
4930  /* This is to show array of line of details */
4931 
4932 
4947  public function printObjectLines($action, $seller, $buyer, $selected = 0, $dateSelector = 0, $defaulttpldir = '/core/tpl')
4948  {
4949  global $conf, $hookmanager, $langs, $user, $form, $extrafields, $object;
4950  // TODO We should not use global var for this
4951  global $inputalsopricewithtax, $usemargins, $disableedit, $disablemove, $disableremove, $outputalsopricetotalwithtax;
4952 
4953  // Define usemargins
4954  $usemargins = 0;
4955  if (isModEnabled('margin') && !empty($this->element) && in_array($this->element, array('facture', 'facturerec', 'propal', 'commande'))) {
4956  $usemargins = 1;
4957  }
4958 
4959  $num = count($this->lines);
4960 
4961  // Line extrafield
4962  if (!is_object($extrafields)) {
4963  require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
4964  $extrafields = new ExtraFields($this->db);
4965  }
4966  $extrafields->fetch_name_optionals_label($this->table_element_line);
4967 
4968  $parameters = array('num'=>$num, 'dateSelector'=>$dateSelector, 'seller'=>$seller, 'buyer'=>$buyer, 'selected'=>$selected, 'table_element_line'=>$this->table_element_line);
4969  $reshook = $hookmanager->executeHooks('printObjectLineTitle', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
4970  if (empty($reshook)) {
4971  // Output template part (modules that overwrite templates must declare this into descriptor)
4972  // Use global variables + $dateSelector + $seller and $buyer
4973  // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook.
4974  $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
4975  foreach ($dirtpls as $module => $reldir) {
4976  $res = 0;
4977  if (!empty($module)) {
4978  $tpl = dol_buildpath($reldir.'/objectline_title.tpl.php');
4979  } else {
4980  $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_title.tpl.php';
4981  }
4982  if (file_exists($tpl)) {
4983  if (empty($conf->file->strict_mode)) {
4984  $res = @include $tpl;
4985  } else {
4986  $res = include $tpl; // for debug
4987  }
4988  }
4989  if ($res) {
4990  break;
4991  }
4992  }
4993  }
4994 
4995  $i = 0;
4996 
4997  print "<!-- begin printObjectLines() --><tbody>\n";
4998  foreach ($this->lines as $line) {
4999  //Line extrafield
5000  $line->fetch_optionals();
5001 
5002  //if (is_object($hookmanager) && (($line->product_type == 9 && !empty($line->special_code)) || !empty($line->fk_parent_line)))
5003  if (is_object($hookmanager)) { // Old code is commented on preceding line.
5004  if (empty($line->fk_parent_line)) {
5005  $parameters = array('line'=>$line, 'num'=>$num, 'i'=>$i, 'dateSelector'=>$dateSelector, 'seller'=>$seller, 'buyer'=>$buyer, 'selected'=>$selected, 'table_element_line'=>$line->table_element);
5006  $reshook = $hookmanager->executeHooks('printObjectLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
5007  } else {
5008  $parameters = array('line'=>$line, 'num'=>$num, 'i'=>$i, 'dateSelector'=>$dateSelector, 'seller'=>$seller, 'buyer'=>$buyer, 'selected'=>$selected, 'table_element_line'=>$line->table_element, 'fk_parent_line'=>$line->fk_parent_line);
5009  $reshook = $hookmanager->executeHooks('printObjectSubLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
5010  }
5011  }
5012  if (empty($reshook)) {
5013  $this->printObjectLine($action, $line, '', $num, $i, $dateSelector, $seller, $buyer, $selected, $extrafields, $defaulttpldir);
5014  }
5015 
5016  $i++;
5017  }
5018  print "</tbody><!-- end printObjectLines() -->\n";
5019  }
5020 
5038  public function printObjectLine($action, $line, $var, $num, $i, $dateSelector, $seller, $buyer, $selected = 0, $extrafields = null, $defaulttpldir = '/core/tpl')
5039  {
5040  global $conf, $langs, $user, $object, $hookmanager;
5041  global $form;
5042  global $object_rights, $disableedit, $disablemove, $disableremove; // TODO We should not use global var for this !
5043 
5044  $object_rights = $this->getRights();
5045 
5046  $element = $this->element;
5047 
5048  $text = '';
5049  $description = '';
5050 
5051  // Line in view mode
5052  if ($action != 'editline' || $selected != $line->id) {
5053  // Product
5054  if (!empty($line->fk_product) && $line->fk_product > 0) {
5055  $product_static = new Product($this->db);
5056  $product_static->fetch($line->fk_product);
5057 
5058  $product_static->ref = $line->ref; //can change ref in hook
5059  $product_static->label = !empty($line->label) ? $line->label : ""; //can change label in hook
5060 
5061  $text = $product_static->getNomUrl(1);
5062 
5063  // Define output language and label
5064  if (getDolGlobalInt('MAIN_MULTILANGS')) {
5065  if (property_exists($this, 'socid') && !is_object($this->thirdparty)) {
5066  dol_print_error('', 'Error: Method printObjectLine was called on an object and object->fetch_thirdparty was not done before');
5067  return;
5068  }
5069 
5070  $prod = new Product($this->db);
5071  $prod->fetch($line->fk_product);
5072 
5073  $outputlangs = $langs;
5074  $newlang = '';
5075  if (empty($newlang) && GETPOST('lang_id', 'aZ09')) {
5076  $newlang = GETPOST('lang_id', 'aZ09');
5077  }
5078  if (!empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE) && empty($newlang) && is_object($this->thirdparty)) {
5079  $newlang = $this->thirdparty->default_lang; // To use language of customer
5080  }
5081  if (!empty($newlang)) {
5082  $outputlangs = new Translate("", $conf);
5083  $outputlangs->setDefaultLang($newlang);
5084  }
5085 
5086  $label = (!empty($prod->multilangs[$outputlangs->defaultlang]["label"])) ? $prod->multilangs[$outputlangs->defaultlang]["label"] : $line->product_label;
5087  } else {
5088  $label = $line->product_label;
5089  }
5090 
5091  $text .= ' - '.(!empty($line->label) ? $line->label : $label);
5092  $description .= (getDolGlobalInt('PRODUIT_DESC_IN_FORM_ACCORDING_TO_DEVICE') ? '' : (!empty($line->description) ? dol_htmlentitiesbr($line->description) : '')); // Description is what to show on popup. We shown nothing if already into desc.
5093  }
5094 
5095  $line->pu_ttc = price2num((!empty($line->subprice) ? $line->subprice : 0) * (1 + ((!empty($line->tva_tx) ? $line->tva_tx : 0) / 100)), 'MU');
5096 
5097  // Output template part (modules that overwrite templates must declare this into descriptor)
5098  // Use global variables + $dateSelector + $seller and $buyer
5099  // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook printObjectLine and printObjectSubLine.
5100  $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
5101  foreach ($dirtpls as $module => $reldir) {
5102  $res = 0;
5103  if (!empty($module)) {
5104  $tpl = dol_buildpath($reldir.'/objectline_view.tpl.php');
5105  } else {
5106  $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_view.tpl.php';
5107  }
5108  if (file_exists($tpl)) {
5109  if (empty($conf->file->strict_mode)) {
5110  $res = @include $tpl;
5111  } else {
5112  $res = include $tpl; // for debug
5113  }
5114  }
5115  if ($res) {
5116  break;
5117  }
5118  }
5119  }
5120 
5121  // Line in update mode
5122  if ($this->statut == 0 && $action == 'editline' && $selected == $line->id) {
5123  $label = (!empty($line->label) ? $line->label : (($line->fk_product > 0) ? $line->product_label : ''));
5124 
5125  $line->pu_ttc = price2num($line->subprice * (1 + ($line->tva_tx / 100)), 'MU');
5126 
5127  // Output template part (modules that overwrite templates must declare this into descriptor)
5128  // Use global variables + $dateSelector + $seller and $buyer
5129  // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook printObjectLine and printObjectSubLine.
5130  $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
5131  foreach ($dirtpls as $module => $reldir) {
5132  if (!empty($module)) {
5133  $tpl = dol_buildpath($reldir.'/objectline_edit.tpl.php');
5134  } else {
5135  $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_edit.tpl.php';
5136  }
5137 
5138  if (empty($conf->file->strict_mode)) {
5139  $res = @include $tpl;
5140  } else {
5141  $res = include $tpl; // for debug
5142  }
5143  if ($res) {
5144  break;
5145  }
5146  }
5147  }
5148  }
5149 
5150 
5151  /* This is to show array of line of details of source object */
5152 
5153 
5164  public function printOriginLinesList($restrictlist = '', $selectedLines = array())
5165  {
5166  global $langs, $hookmanager, $conf, $form, $action;
5167 
5168  print '<tr class="liste_titre">';
5169  print '<td class="linecolref">'.$langs->trans('Ref').'</td>';
5170  print '<td class="linecoldescription">'.$langs->trans('Description').'</td>';
5171  print '<td class="linecolvat right">'.$langs->trans('VATRate').'</td>';
5172  print '<td class="linecoluht right">'.$langs->trans('PriceUHT').'</td>';
5173  if (isModEnabled("multicurrency")) {
5174  print '<td class="linecoluht_currency right">'.$langs->trans('PriceUHTCurrency').'</td>';
5175  }
5176  print '<td class="linecolqty right">'.$langs->trans('Qty').'</td>';
5177  if (getDolGlobalInt('PRODUCT_USE_UNITS')) {
5178  print '<td class="linecoluseunit left">'.$langs->trans('Unit').'</td>';
5179  }
5180  print '<td class="linecoldiscount right">'.$langs->trans('ReductionShort').'</td>';
5181  print '<td class="linecolht right">'.$langs->trans('TotalHT').'</td>';
5182  print '<td class="center">'.$form->showCheckAddButtons('checkforselect', 1).'</td>';
5183  print '</tr>';
5184  $i = 0;
5185 
5186  if (!empty($this->lines)) {
5187  foreach ($this->lines as $line) {
5188  $reshook = 0;
5189  //if (is_object($hookmanager) && (($line->product_type == 9 && !empty($line->special_code)) || !empty($line->fk_parent_line))) {
5190  if (is_object($hookmanager)) { // Old code is commented on preceding line.
5191  $parameters = array('line'=>$line, 'i'=>$i, 'restrictlist'=>$restrictlist, 'selectedLines'=> $selectedLines);
5192  if (!empty($line->fk_parent_line)) { $parameters['fk_parent_line'] = $line->fk_parent_line; }
5193  $reshook = $hookmanager->executeHooks('printOriginObjectLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
5194  }
5195  if (empty($reshook)) {
5196  $this->printOriginLine($line, '', $restrictlist, '/core/tpl', $selectedLines);
5197  }
5198 
5199  $i++;
5200  }
5201  }
5202  }
5203 
5217  public function printOriginLine($line, $var, $restrictlist = '', $defaulttpldir = '/core/tpl', $selectedLines = array())
5218  {
5219  global $langs, $conf;
5220 
5221  //var_dump($line);
5222  if (!empty($line->date_start)) {
5223  $date_start = $line->date_start;
5224  } else {
5225  $date_start = $line->date_debut_prevue;
5226  if ($line->date_debut_reel) {
5227  $date_start = $line->date_debut_reel;
5228  }
5229  }
5230  if (!empty($line->date_end)) {
5231  $date_end = $line->date_end;
5232  } else {
5233  $date_end = $line->date_fin_prevue;
5234  if ($line->date_fin_reel) {
5235  $date_end = $line->date_fin_reel;
5236  }
5237  }
5238 
5239  $this->tpl['id'] = $line->id;
5240 
5241  $this->tpl['label'] = '';
5242  if (!empty($line->fk_parent_line)) {
5243  $this->tpl['label'] .= img_picto('', 'rightarrow');
5244  }
5245 
5246  if (($line->info_bits & 2) == 2) { // TODO Not sure this is used for source object
5247  $discount = new DiscountAbsolute($this->db);
5248  $discount->fk_soc = $this->socid;
5249  $this->tpl['label'] .= $discount->getNomUrl(0, 'discount');
5250  } elseif (!empty($line->fk_product)) {
5251  $productstatic = new Product($this->db);
5252  $productstatic->id = $line->fk_product;
5253  $productstatic->ref = $line->ref;
5254  $productstatic->type = $line->fk_product_type;
5255  if (empty($productstatic->ref)) {
5256  $line->fetch_product();
5257  $productstatic = $line->product;
5258  }
5259 
5260  $this->tpl['label'] .= $productstatic->getNomUrl(1);
5261  $this->tpl['label'] .= ' - '.(!empty($line->label) ? $line->label : $line->product_label);
5262  // Dates
5263  if ($line->product_type == 1 && ($date_start || $date_end)) {
5264  $this->tpl['label'] .= get_date_range($date_start, $date_end);
5265  }
5266  } else {
5267  $this->tpl['label'] .= ($line->product_type == -1 ? '&nbsp;' : ($line->product_type == 1 ? img_object($langs->trans(''), 'service') : img_object($langs->trans(''), 'product')));
5268  if (!empty($line->desc)) {
5269  $this->tpl['label'] .= $line->desc;
5270  } else {
5271  $this->tpl['label'] .= ($line->label ? '&nbsp;'.$line->label : '');
5272  }
5273 
5274  // Dates
5275  if ($line->product_type == 1 && ($date_start || $date_end)) {
5276  $this->tpl['label'] .= get_date_range($date_start, $date_end);
5277  }
5278  }
5279 
5280  if (!empty($line->desc)) {
5281  if ($line->desc == '(CREDIT_NOTE)') { // TODO Not sure this is used for source object
5282  $discount = new DiscountAbsolute($this->db);
5283  $discount->fetch($line->fk_remise_except);
5284  $this->tpl['description'] = $langs->transnoentities("DiscountFromCreditNote", $discount->getNomUrl(0));
5285  } elseif ($line->desc == '(DEPOSIT)') { // TODO Not sure this is used for source object
5286  $discount = new DiscountAbsolute($this->db);
5287  $discount->fetch($line->fk_remise_except);
5288  $this->tpl['description'] = $langs->transnoentities("DiscountFromDeposit", $discount->getNomUrl(0));
5289  } elseif ($line->desc == '(EXCESS RECEIVED)') {
5290  $discount = new DiscountAbsolute($this->db);
5291  $discount->fetch($line->fk_remise_except);
5292  $this->tpl['description'] = $langs->transnoentities("DiscountFromExcessReceived", $discount->getNomUrl(0));
5293  } elseif ($line->desc == '(EXCESS PAID)') {
5294  $discount = new DiscountAbsolute($this->db);
5295  $discount->fetch($line->fk_remise_except);
5296  $this->tpl['description'] = $langs->transnoentities("DiscountFromExcessPaid", $discount->getNomUrl(0));
5297  } else {
5298  $this->tpl['description'] = dol_trunc($line->desc, 60);
5299  }
5300  } else {
5301  $this->tpl['description'] = '&nbsp;';
5302  }
5303 
5304  // VAT Rate
5305  $this->tpl['vat_rate'] = vatrate($line->tva_tx, true);
5306  $this->tpl['vat_rate'] .= (($line->info_bits & 1) == 1) ? '*' : '';
5307  if (!empty($line->vat_src_code) && !preg_match('/\(/', $this->tpl['vat_rate'])) {
5308  $this->tpl['vat_rate'] .= ' ('.$line->vat_src_code.')';
5309  }
5310 
5311  $this->tpl['price'] = price($line->subprice);
5312  $this->tpl['total_ht'] = price($line->total_ht);
5313  $this->tpl['multicurrency_price'] = price($line->multicurrency_subprice);
5314  $this->tpl['qty'] = (($line->info_bits & 2) != 2) ? $line->qty : '&nbsp;';
5315  if (getDolGlobalInt('PRODUCT_USE_UNITS')) {
5316  $this->tpl['unit'] = $langs->transnoentities($line->getLabelOfUnit('long'));
5317  }
5318  $this->tpl['remise_percent'] = (($line->info_bits & 2) != 2) ? vatrate($line->remise_percent, true) : '&nbsp;';
5319 
5320  // Is the line strike or not
5321  $this->tpl['strike'] = 0;
5322  if ($restrictlist == 'services' && $line->product_type != Product::TYPE_SERVICE) {
5323  $this->tpl['strike'] = 1;
5324  }
5325 
5326  // Output template part (modules that overwrite templates must declare this into descriptor)
5327  // Use global variables + $dateSelector + $seller and $buyer
5328  $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
5329  foreach ($dirtpls as $module => $reldir) {
5330  if (!empty($module)) {
5331  $tpl = dol_buildpath($reldir.'/originproductline.tpl.php');
5332  } else {
5333  $tpl = DOL_DOCUMENT_ROOT.$reldir.'/originproductline.tpl.php';
5334  }
5335 
5336  if (empty($conf->file->strict_mode)) {
5337  $res = @include $tpl;
5338  } else {
5339  $res = include $tpl; // for debug
5340  }
5341  if ($res) {
5342  break;
5343  }
5344  }
5345  }
5346 
5347 
5348  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5359  public function add_element_resource($resource_id, $resource_type, $busy = 0, $mandatory = 0)
5360  {
5361  // phpcs:enable
5362  $this->db->begin();
5363 
5364  $sql = "INSERT INTO ".$this->db->prefix()."element_resources (";
5365  $sql .= "resource_id";
5366  $sql .= ", resource_type";
5367  $sql .= ", element_id";
5368  $sql .= ", element_type";
5369  $sql .= ", busy";
5370  $sql .= ", mandatory";
5371  $sql .= ") VALUES (";
5372  $sql .= ((int) $resource_id);
5373  $sql .= ", '".$this->db->escape($resource_type)."'";
5374  $sql .= ", '".$this->db->escape($this->id)."'";
5375  $sql .= ", '".$this->db->escape($this->element)."'";
5376  $sql .= ", '".$this->db->escape($busy)."'";
5377  $sql .= ", '".$this->db->escape($mandatory)."'";
5378  $sql .= ")";
5379 
5380  dol_syslog(get_class($this)."::add_element_resource", LOG_DEBUG);
5381  if ($this->db->query($sql)) {
5382  $this->db->commit();
5383  return 1;
5384  } else {
5385  $this->error = $this->db->lasterror();
5386  $this->db->rollback();
5387  return 0;
5388  }
5389  }
5390 
5391  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5400  public function delete_resource($rowid, $element, $notrigger = 0)
5401  {
5402  // phpcs:enable
5403  global $user;
5404 
5405  $this->db->begin();
5406 
5407  $sql = "DELETE FROM ".$this->db->prefix()."element_resources";
5408  $sql .= " WHERE rowid = ".((int) $rowid);
5409 
5410  dol_syslog(get_class($this)."::delete_resource", LOG_DEBUG);
5411 
5412  $resql = $this->db->query($sql);
5413  if (!$resql) {
5414  $this->error = $this->db->lasterror();
5415  $this->db->rollback();
5416  return -1;
5417  } else {
5418  if (!$notrigger) {
5419  $result = $this->call_trigger(strtoupper($element).'_DELETE_RESOURCE', $user);
5420  if ($result < 0) {
5421  $this->db->rollback();
5422  return -1;
5423  }
5424  }
5425  $this->db->commit();
5426  return 1;
5427  }
5428  }
5429 
5430 
5436  public function __clone()
5437  {
5438  // Force a copy of this->lines, otherwise it will point to same object.
5439  if (isset($this->lines) && is_array($this->lines)) {
5440  $nboflines = count($this->lines);
5441  for ($i = 0; $i < $nboflines; $i++) {
5442  $this->lines[$i] = clone $this->lines[$i];
5443  }
5444  }
5445  }
5446 
5460  protected function commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams = null)
5461  {
5462  global $conf, $langs, $user, $hookmanager, $action;
5463 
5464  $srctemplatepath = '';
5465 
5466  $parameters = array('modelspath'=>$modelspath, 'modele'=>$modele, 'outputlangs'=>$outputlangs, 'hidedetails'=>$hidedetails, 'hidedesc'=>$hidedesc, 'hideref'=>$hideref, 'moreparams'=>$moreparams);
5467  $reshook = $hookmanager->executeHooks('commonGenerateDocument', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
5468 
5469  if (empty($reshook)) {
5470  dol_syslog("commonGenerateDocument modele=".$modele." outputlangs->defaultlang=".(is_object($outputlangs) ? $outputlangs->defaultlang : 'null'));
5471 
5472  if (empty($modele)) {
5473  $this->error = 'BadValueForParameterModele';
5474  return -1;
5475  }
5476 
5477  // Increase limit for PDF build
5478  $err = error_reporting();
5479  error_reporting(0);
5480  @set_time_limit(120);
5481  error_reporting($err);
5482 
5483  // If selected model is a filename template (then $modele="modelname" or "modelname:filename")
5484  $tmp = explode(':', $modele, 2);
5485  if (!empty($tmp[1])) {
5486  $modele = $tmp[0];
5487  $srctemplatepath = $tmp[1];
5488  }
5489 
5490  // Search template files
5491  $file = '';
5492  $classname = '';
5493  $filefound = '';
5494  $dirmodels = array('/');
5495  if (is_array($conf->modules_parts['models'])) {
5496  $dirmodels = array_merge($dirmodels, $conf->modules_parts['models']);
5497  }
5498  foreach ($dirmodels as $reldir) {
5499  foreach (array('doc', 'pdf') as $prefix) {
5500  if (in_array(get_class($this), array('Adherent'))) {
5501  // Member module use prefix_modele.class.php
5502  $file = $prefix."_".$modele.".class.php";
5503  } else {
5504  // Other module use prefix_modele.modules.php
5505  $file = $prefix."_".$modele.".modules.php";
5506  }
5507 
5508  // On verifie l'emplacement du modele
5509  $file = dol_buildpath($reldir.$modelspath.$file, 0);
5510  if (file_exists($file)) {
5511  $filefound = $file;
5512  $classname = $prefix.'_'.$modele;
5513  break;
5514  }
5515  }
5516  if ($filefound) {
5517  break;
5518  }
5519  }
5520 
5521  // If generator was found
5522  if ($filefound) {
5523  global $db; // Required to solve a conception default making an include of code using $db instead of $this->db just after.
5524 
5525  require_once $file;
5526 
5527  $obj = new $classname($this->db);
5528 
5529  // If generator is ODT, we must have srctemplatepath defined, if not we set it.
5530  if ($obj->type == 'odt' && empty($srctemplatepath)) {
5531  $varfortemplatedir = $obj->scandir;
5532  if ($varfortemplatedir && !empty($conf->global->$varfortemplatedir)) {
5533  $dirtoscan = $conf->global->$varfortemplatedir;
5534 
5535  $listoffiles = array();
5536 
5537  // Now we add first model found in directories scanned
5538  $listofdir = explode(',', $dirtoscan);
5539  foreach ($listofdir as $key => $tmpdir) {
5540  $tmpdir = trim($tmpdir);
5541  $tmpdir = preg_replace('/DOL_DATA_ROOT/', DOL_DATA_ROOT, $tmpdir);
5542  if (!$tmpdir) {
5543  unset($listofdir[$key]);
5544  continue;
5545  }
5546  if (is_dir($tmpdir)) {
5547  $tmpfiles = dol_dir_list($tmpdir, 'files', 0, '\.od(s|t)$', '', 'name', SORT_ASC, 0);
5548  if (count($tmpfiles)) {
5549  $listoffiles = array_merge($listoffiles, $tmpfiles);
5550  }
5551  }
5552  }
5553 
5554  if (count($listoffiles)) {
5555  foreach ($listoffiles as $record) {
5556  $srctemplatepath = $record['fullname'];
5557  break;
5558  }
5559  }
5560  }
5561 
5562  if (empty($srctemplatepath)) {
5563  $this->error = 'ErrorGenerationAskedForOdtTemplateWithSrcFileNotDefined';
5564  return -1;
5565  }
5566  }
5567 
5568  if ($obj->type == 'odt' && !empty($srctemplatepath)) {
5569  if (!dol_is_file($srctemplatepath)) {
5570  dol_syslog("Failed to locate template file ".$srctemplatepath, LOG_WARNING);
5571  $this->error = 'ErrorGenerationAskedForOdtTemplateWithSrcFileNotFound';
5572  return -1;
5573  }
5574  }
5575 
5576  // We save charset_output to restore it because write_file can change it if needed for
5577  // output format that does not support UTF8.
5578  $sav_charset_output = empty($outputlangs->charset_output) ? '' : $outputlangs->charset_output;
5579 
5580  if (in_array(get_class($this), array('Adherent'))) {
5581  $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, 'member', 1, 'tmp_cards', $moreparams);
5582  } else {
5583  $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, $hidedetails, $hidedesc, $hideref, $moreparams);
5584  }
5585  // After call of write_file $obj->result['fullpath'] is set with generated file. It will be used to update the ECM database index.
5586 
5587  if ($resultwritefile > 0) {
5588  $outputlangs->charset_output = $sav_charset_output;
5589 
5590  // We delete old preview
5591  require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
5592  dol_delete_preview($this);
5593 
5594  // Index file in database
5595  if (!empty($obj->result['fullpath'])) {
5596  $destfull = $obj->result['fullpath'];
5597 
5598  // Update the last_main_doc field into main object (if document generator has property ->update_main_doc_field set)
5599  $update_main_doc_field = 0;
5600  if (!empty($obj->update_main_doc_field)) {
5601  $update_main_doc_field = 1;
5602  }
5603 
5604  $this->indexFile($destfull, $update_main_doc_field);
5605  } else {
5606  dol_syslog('Method ->write_file was called on object '.get_class($obj).' and return a success but the return array ->result["fullpath"] was not set.', LOG_WARNING);
5607  }
5608 
5609  // Success in building document. We build meta file.
5610  dol_meta_create($this);
5611 
5612  return 1;
5613  } else {
5614  $outputlangs->charset_output = $sav_charset_output;
5615  $this->error = $obj->error;
5616  $this->errors = $obj->errors;
5617  dol_syslog("Error generating document for ".__CLASS__.". Error: ".$obj->error, LOG_ERR);
5618  return -1;
5619  }
5620  } else {
5621  if (!$filefound) {
5622  $this->error = $langs->trans("Error").' Failed to load doc generator with modelpaths='.$modelspath.' - modele='.$modele;
5623  $this->errors[] = $this->error;
5624  dol_syslog($this->error, LOG_ERR);
5625  } else {
5626  $this->error = $langs->trans("Error")." ".$langs->trans("ErrorFileDoesNotExists", $filefound);
5627  $this->errors[] = $this->error;
5628  dol_syslog($this->error, LOG_ERR);
5629  }
5630  return -1;
5631  }
5632  } else {
5633  return $reshook;
5634  }
5635  }
5636 
5646  public function indexFile($destfull, $update_main_doc_field)
5647  {
5648  global $conf, $user;
5649 
5650  $upload_dir = dirname($destfull);
5651  $destfile = basename($destfull);
5652  $rel_dir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $upload_dir);
5653 
5654  if (!preg_match('/[\\/]temp[\\/]|[\\/]thumbs|\.meta$/', $rel_dir)) { // If not a tmp dir
5655  $filename = basename($destfile);
5656  $rel_dir = preg_replace('/[\\/]$/', '', $rel_dir);
5657  $rel_dir = preg_replace('/^[\\/]/', '', $rel_dir);
5658 
5659  include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
5660  $ecmfile = new EcmFiles($this->db);
5661  $result = $ecmfile->fetch(0, '', ($rel_dir ? $rel_dir.'/' : '').$filename);
5662 
5663  // Set the public "share" key
5664  $setsharekey = false;
5665  if ($this->element == 'propal' || $this->element == 'proposal') {
5666  if (!isset($conf->global->PROPOSAL_ALLOW_ONLINESIGN) || !empty($conf->global->PROPOSAL_ALLOW_ONLINESIGN)) {
5667  $setsharekey = true; // feature to make online signature is not set or set to on (default)
5668  }
5669  if (!empty($conf->global->PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD)) {
5670  $setsharekey = true;
5671  }
5672  }
5673  if ($this->element == 'commande' && !empty($conf->global->ORDER_ALLOW_EXTERNAL_DOWNLOAD)) {
5674  $setsharekey = true;
5675  }
5676  if ($this->element == 'facture' && !empty($conf->global->INVOICE_ALLOW_EXTERNAL_DOWNLOAD)) {
5677  $setsharekey = true;
5678  }
5679  if ($this->element == 'bank_account' && !empty($conf->global->BANK_ACCOUNT_ALLOW_EXTERNAL_DOWNLOAD)) {
5680  $setsharekey = true;
5681  }
5682  if ($this->element == 'product' && !empty($conf->global->PRODUCT_ALLOW_EXTERNAL_DOWNLOAD)) {
5683  $setsharekey = true;
5684  }
5685  if ($this->element == 'contrat' && !empty($conf->global->CONTRACT_ALLOW_EXTERNAL_DOWNLOAD)) {
5686  $setsharekey = true;
5687  }
5688  if ($this->element == 'fichinter' && !empty($conf->global->FICHINTER_ALLOW_EXTERNAL_DOWNLOAD)) {
5689  $setsharekey = true;
5690  }
5691  if ($this->element == 'supplier_proposal' && !empty($conf->global->SUPPLIER_PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD)) {
5692  $setsharekey = true;
5693  }
5694 
5695  if ($setsharekey) {
5696  if (empty($ecmfile->share)) { // Because object not found or share not set yet
5697  require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
5698  $ecmfile->share = getRandomPassword(true);
5699  }
5700  }
5701 
5702  if ($result > 0) {
5703  $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
5704  $ecmfile->fullpath_orig = '';
5705  $ecmfile->gen_or_uploaded = 'generated';
5706  $ecmfile->description = ''; // indexed content
5707  $ecmfile->keywords = ''; // keyword content
5708  $result = $ecmfile->update($user);
5709  if ($result < 0) {
5710  setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
5711  return -1;
5712  }
5713  } else {
5714  $ecmfile->entity = $conf->entity;
5715  $ecmfile->filepath = $rel_dir;
5716  $ecmfile->filename = $filename;
5717  $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
5718  $ecmfile->fullpath_orig = '';
5719  $ecmfile->gen_or_uploaded = 'generated';
5720  $ecmfile->description = ''; // indexed content
5721  $ecmfile->keywords = ''; // keyword content
5722  $ecmfile->src_object_type = $this->table_element; // $this->table_name is 'myobject' or 'mymodule_myobject'.
5723  $ecmfile->src_object_id = $this->id;
5724 
5725  $result = $ecmfile->create($user);
5726  if ($result < 0) {
5727  setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
5728  return -1;
5729  }
5730  }
5731 
5732  /*$this->result['fullname']=$destfull;
5733  $this->result['filepath']=$ecmfile->filepath;
5734  $this->result['filename']=$ecmfile->filename;*/
5735  //var_dump($obj->update_main_doc_field);exit;
5736 
5737  if ($update_main_doc_field && !empty($this->table_element)) {
5738  $sql = "UPDATE ".$this->db->prefix().$this->table_element." SET last_main_doc = '".$this->db->escape($ecmfile->filepath."/".$ecmfile->filename)."'";
5739  $sql .= " WHERE rowid = ".((int) $this->id);
5740 
5741  $resql = $this->db->query($sql);
5742  if (!$resql) {
5743  dol_print_error($this->db);
5744  return -1;
5745  } else {
5746  $this->last_main_doc = $ecmfile->filepath.'/'.$ecmfile->filename;
5747  }
5748  }
5749  }
5750 
5751  return 1;
5752  }
5753 
5761  public function addThumbs($file)
5762  {
5763  $file_osencoded = dol_osencode($file);
5764  if (file_exists($file_osencoded)) {
5765  global $maxwidthsmall, $maxheightsmall, $maxwidthmini, $maxheightmini, $quality;
5766 
5767  require_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php'; // This define also $maxwidthsmall, $quality, ...
5768 
5769  // Create small thumbs for company (Ratio is near 16/9)
5770  // Used on logon for example
5771  vignette($file_osencoded, $maxwidthsmall, $maxheightsmall, '_small', $quality);
5772 
5773  // Create mini thumbs for company (Ratio is near 16/9)
5774  // Used on menu or for setup page for example
5775  vignette($file_osencoded, $maxwidthmini, $maxheightmini, '_mini', $quality);
5776  }
5777  }
5778 
5786  public function delThumbs($file)
5787  {
5788  $imgThumbName = getImageFileNameForSize($file, '_small'); // Full path of thumb file
5789  dol_delete_file($imgThumbName);
5790  $imgThumbName = getImageFileNameForSize($file, '_mini'); // Full path of thumb file
5791  dol_delete_file($imgThumbName);
5792  }
5793 
5794 
5795  /* Functions common to commonobject and commonobjectline */
5796 
5797  /* For default values */
5798 
5812  public function getDefaultCreateValueFor($fieldname, $alternatevalue = null, $type = 'alphanohtml')
5813  {
5814  global $conf, $_POST;
5815 
5816  // If param here has been posted, we use this value first.
5817  if (GETPOSTISSET($fieldname)) {
5818  return GETPOST($fieldname, $type, 3);
5819  }
5820 
5821  if (isset($alternatevalue)) {
5822  return $alternatevalue;
5823  }
5824 
5825  $newelement = $this->element;
5826  if ($newelement == 'facture') {
5827  $newelement = 'invoice';
5828  }
5829  if ($newelement == 'commande') {
5830  $newelement = 'order';
5831  }
5832  if (empty($newelement)) {
5833  dol_syslog("Ask a default value using common method getDefaultCreateValueForField on an object with no property ->element defined. Return empty string.", LOG_WARNING);
5834  return '';
5835  }
5836 
5837  $keyforfieldname = strtoupper($newelement.'_DEFAULT_'.$fieldname);
5838  //var_dump($keyforfieldname);
5839  if (isset($conf->global->$keyforfieldname)) {
5840  return $conf->global->$keyforfieldname;
5841  }
5842 
5843  // TODO Ad here a scan into table llx_overwrite_default with a filter on $this->element and $fieldname
5844  // store content into $conf->cache['overwrite_default']
5845 
5846  return '';
5847  }
5848 
5849 
5850  /* For triggers */
5851 
5852 
5853  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5864  public function call_trigger($triggerName, $user)
5865  {
5866  // phpcs:enable
5867  global $langs, $conf;
5868  if (!empty(self::TRIGGER_PREFIX) && strpos($triggerName, self::TRIGGER_PREFIX . '_') !== 0) {
5869  dol_print_error('', 'The trigger "' . $triggerName . '" does not start with "' . self::TRIGGER_PREFIX . '_" as required.');
5870  exit;
5871  }
5872  if (!is_object($langs)) { // If lang was not defined, we set it. It is required by run_triggers.
5873  include_once DOL_DOCUMENT_ROOT.'/core/class/translate.class.php';
5874  $langs = new Translate('', $conf);
5875  }
5876 
5877  include_once DOL_DOCUMENT_ROOT.'/core/class/interfaces.class.php';
5878  $interface = new Interfaces($this->db);
5879  $result = $interface->run_triggers($triggerName, $this, $user, $langs, $conf);
5880 
5881  if ($result < 0) {
5882  if (!empty($this->errors)) {
5883  $this->errors = array_unique(array_merge($this->errors, $interface->errors)); // We use array_unique because when a trigger call another trigger on same object, this->errors is added twice.
5884  } else {
5885  $this->errors = $interface->errors;
5886  }
5887  }
5888  return $result;
5889  }
5890 
5891 
5892  /* Functions for data in other language */
5893 
5894 
5902  public function fetchValuesForExtraLanguages()
5903  {
5904  // To avoid SQL errors. Probably not the better solution though
5905  if (!$this->element) {
5906  return 0;
5907  }
5908  if (!($this->id > 0)) {
5909  return 0;
5910  }
5911  if (is_array($this->array_languages)) {
5912  return 1;
5913  }
5914 
5915  $this->array_languages = array();
5916 
5917  $element = $this->element;
5918  if ($element == 'categorie') {
5919  $element = 'categories'; // For compatibility
5920  }
5921 
5922  // Request to get translation values for object
5923  $sql = "SELECT rowid, property, lang , value";
5924  $sql .= " FROM ".$this->db->prefix()."object_lang";
5925  $sql .= " WHERE type_object = '".$this->db->escape($element)."'";
5926  $sql .= " AND fk_object = ".((int) $this->id);
5927 
5928  //dol_syslog(get_class($this)."::fetch_optionals get extrafields data for ".$this->table_element, LOG_DEBUG); // Too verbose
5929  $resql = $this->db->query($sql);
5930  if ($resql) {
5931  $numrows = $this->db->num_rows($resql);
5932  if ($numrows) {
5933  $i = 0;
5934  while ($i < $numrows) {
5935  $obj = $this->db->fetch_object($resql);
5936  $key = $obj->property;
5937  $value = $obj->value;
5938  $codelang = $obj->lang;
5939  $type = $this->fields[$key]['type'];
5940 
5941  // we can add this attribute to object
5942  if (preg_match('/date/', $type)) {
5943  $this->array_languages[$key][$codelang] = $this->db->jdate($value);
5944  } else {
5945  $this->array_languages[$key][$codelang] = $value;
5946  }
5947 
5948  $i++;
5949  }
5950  }
5951 
5952  $this->db->free($resql);
5953 
5954  if ($numrows) {
5955  return $numrows;
5956  } else {
5957  return 0;
5958  }
5959  } else {
5960  dol_print_error($this->db);
5961  return -1;
5962  }
5963  }
5964 
5971  public function setValuesForExtraLanguages($onlykey = '')
5972  {
5973  global $_POST, $langs;
5974 
5975  // Get extra fields
5976  foreach ($_POST as $postfieldkey => $postfieldvalue) {
5977  $tmparray = explode('-', $postfieldkey);
5978  if ($tmparray[0] != 'field') {
5979  continue;
5980  }
5981 
5982  $element = $tmparray[1];
5983  $key = $tmparray[2];
5984  $codelang = $tmparray[3];
5985  //var_dump("postfieldkey=".$postfieldkey." element=".$element." key=".$key." codelang=".$codelang);
5986 
5987  if (!empty($onlykey) && $key != $onlykey) {
5988  continue;
5989  }
5990  if ($element != $this->element) {
5991  continue;
5992  }
5993 
5994  $key_type = $this->fields[$key]['type'];
5995 
5996  $enabled = 1;
5997  if (isset($this->fields[$key]['enabled'])) {
5998  $enabled = dol_eval($this->fields[$key]['enabled'], 1, 1, '1');
5999  }
6000  /*$perms = 1;
6001  if (isset($this->fields[$key]['perms']))
6002  {
6003  $perms = dol_eval($this->fields[$key]['perms'], 1, 1, '1');
6004  }*/
6005  if (empty($enabled)) {
6006  continue;
6007  }
6008  //if (empty($perms)) continue;
6009 
6010  if (in_array($key_type, array('date'))) {
6011  // Clean parameters
6012  // TODO GMT date in memory must be GMT so we should add gm=true in parameters
6013  $value_key = dol_mktime(0, 0, 0, GETPOST($postfieldkey."month", 'int'), GETPOST($postfieldkey."day", 'int'), GETPOST($postfieldkey."year", 'int'));
6014  } elseif (in_array($key_type, array('datetime'))) {
6015  // Clean parameters
6016  // TODO GMT date in memory must be GMT so we should add gm=true in parameters
6017  $value_key = dol_mktime(GETPOST($postfieldkey."hour", 'int'), GETPOST($postfieldkey."min", 'int'), 0, GETPOST($postfieldkey."month", 'int'), GETPOST($postfieldkey."day", 'int'), GETPOST($postfieldkey."year", 'int'));
6018  } elseif (in_array($key_type, array('checkbox', 'chkbxlst'))) {
6019  $value_arr = GETPOST($postfieldkey, 'array'); // check if an array
6020  if (!empty($value_arr)) {
6021  $value_key = implode(',', $value_arr);
6022  } else {
6023  $value_key = '';
6024  }
6025  } elseif (in_array($key_type, array('price', 'double'))) {
6026  $value_arr = GETPOST($postfieldkey, 'alpha');
6027  $value_key = price2num($value_arr);
6028  } else {
6029  $value_key = GETPOST($postfieldkey);
6030  if (in_array($key_type, array('link')) && $value_key == '-1') {
6031  $value_key = '';
6032  }
6033  }
6034 
6035  $this->array_languages[$key][$codelang] = $value_key;
6036 
6037  /*if ($nofillrequired) {
6038  $langs->load('errors');
6039  setEventMessages($langs->trans('ErrorFieldsRequired').' : '.implode(', ', $error_field_required), null, 'errors');
6040  return -1;
6041  }*/
6042  }
6043 
6044  return 1;
6045  }
6046 
6047 
6048  /* Functions for extrafields */
6049 
6056  public function fetchNoCompute($id)
6057  {
6058  global $conf;
6059 
6060  $savDisableCompute = $conf->disable_compute;
6061  $conf->disable_compute = 1;
6062 
6063  $ret = $this->fetch($id);
6064 
6065  $conf->disable_compute = $savDisableCompute;
6066 
6067  return $ret;
6068  }
6069 
6070  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
6080  public function fetch_optionals($rowid = null, $optionsArray = null)
6081  {
6082  // phpcs:enable
6083  global $conf, $extrafields;
6084 
6085  if (empty($rowid)) {
6086  $rowid = $this->id;
6087  }
6088  if (empty($rowid) && isset($this->rowid)) {
6089  $rowid = $this->rowid; // deprecated
6090  }
6091 
6092  // To avoid SQL errors. Probably not the better solution though
6093  if (!$this->table_element) {
6094  return 0;
6095  }
6096 
6097  $this->array_options = array();
6098 
6099  if (!is_array($optionsArray)) {
6100  // If $extrafields is not a known object, we initialize it. Best practice is to have $extrafields defined into card.php or list.php page.
6101  if (!isset($extrafields) || !is_object($extrafields)) {
6102  require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
6103  $extrafields = new ExtraFields($this->db);
6104  }
6105 
6106  // Load array of extrafields for elementype = $this->table_element
6107  if (empty($extrafields->attributes[$this->table_element]['loaded'])) {
6108  $extrafields->fetch_name_optionals_label($this->table_element);
6109  }
6110  $optionsArray = (!empty($extrafields->attributes[$this->table_element]['label']) ? $extrafields->attributes[$this->table_element]['label'] : null);
6111  } else {
6112  global $extrafields;
6113  dol_syslog("Warning: fetch_optionals was called with param optionsArray defined when you should pass null now", LOG_WARNING);
6114  }
6115 
6116  $table_element = $this->table_element;
6117  if ($table_element == 'categorie') {
6118  $table_element = 'categories'; // For compatibility
6119  }
6120 
6121  // Request to get complementary values
6122  if (is_array($optionsArray) && count($optionsArray) > 0) {
6123  $sql = "SELECT rowid";
6124  foreach ($optionsArray as $name => $label) {
6125  if (empty($extrafields->attributes[$this->table_element]['type'][$name]) || $extrafields->attributes[$this->table_element]['type'][$name] != 'separate') {
6126  $sql .= ", ".$name;
6127  }
6128  }
6129  $sql .= " FROM ".$this->db->prefix().$table_element."_extrafields";
6130  $sql .= " WHERE fk_object = ".((int) $rowid);
6131 
6132  //dol_syslog(get_class($this)."::fetch_optionals get extrafields data for ".$this->table_element, LOG_DEBUG); // Too verbose
6133  $resql = $this->db->query($sql);
6134  if ($resql) {
6135  $numrows = $this->db->num_rows($resql);
6136  if ($numrows) {
6137  $tab = $this->db->fetch_array($resql);
6138 
6139  foreach ($tab as $key => $value) {
6140  // Test fetch_array ! is_int($key) because fetch_array result is a mix table with Key as alpha and Key as int (depend db engine)
6141  if ($key != 'rowid' && $key != 'tms' && $key != 'fk_member' && !is_int($key)) {
6142  // we can add this attribute to object
6143  if (!empty($extrafields->attributes[$this->table_element]) && in_array($extrafields->attributes[$this->table_element]['type'][$key], array('date', 'datetime'))) {
6144  //var_dump($extrafields->attributes[$this->table_element]['type'][$key]);
6145  $this->array_options["options_".$key] = $this->db->jdate($value);
6146  } else {
6147  $this->array_options["options_".$key] = $value;
6148  }
6149 
6150  //var_dump('key '.$key.' '.$value.' type='.$extrafields->attributes[$this->table_element]['type'][$key].' '.$this->array_options["options_".$key]);
6151  }
6152  }
6153  }
6154 
6155  // If field is a computed field, value must become result of compute (regardless of whether a row exists
6156  // in the element's extrafields table)
6157  foreach ($extrafields->attributes[$this->table_element]['label'] as $key => $val) {
6158  if (!empty($extrafields->attributes[$this->table_element]) && !empty($extrafields->attributes[$this->table_element]['computed'][$key])) {
6159  //var_dump($conf->disable_compute);
6160  if (empty($conf->disable_compute)) {
6161  global $objectoffield; // We set a global variable to $objectoffield so
6162  $objectoffield = $this; // we can use it inside computed formula
6163  $this->array_options["options_".$key] = dol_eval($extrafields->attributes[$this->table_element]['computed'][$key], 1, 0, '');
6164  }
6165  }
6166  }
6167 
6168  $this->db->free($resql);
6169 
6170  if ($numrows) {
6171  return $numrows;
6172  } else {
6173  return 0;
6174  }
6175  } else {
6176  $this->errors[]=$this->db->lasterror;
6177  return -1;
6178  }
6179  }
6180  return 0;
6181  }
6182 
6189  public function deleteExtraFields()
6190  {
6191  global $conf;
6192 
6193  if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
6194  return 0;
6195  }
6196 
6197  $this->db->begin();
6198 
6199  $table_element = $this->table_element;
6200  if ($table_element == 'categorie') {
6201  $table_element = 'categories'; // For compatibility
6202  }
6203 
6204  dol_syslog(get_class($this)."::deleteExtraFields delete", LOG_DEBUG);
6205 
6206  $sql_del = "DELETE FROM ".$this->db->prefix().$table_element."_extrafields WHERE fk_object = ".((int) $this->id);
6207 
6208  $resql = $this->db->query($sql_del);
6209  if (!$resql) {
6210  $this->error = $this->db->lasterror();
6211  $this->db->rollback();
6212  return -1;
6213  } else {
6214  $this->db->commit();
6215  return 1;
6216  }
6217  }
6218 
6229  public function insertExtraFields($trigger = '', $userused = null)
6230  {
6231  global $conf, $langs, $user;
6232 
6233  if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
6234  return 0;
6235  }
6236 
6237  if (empty($userused)) {
6238  $userused = $user;
6239  }
6240 
6241  $error = 0;
6242 
6243  if (!empty($this->array_options)) {
6244  // Check parameters
6245  $langs->load('admin');
6246  require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
6247  $extrafields = new ExtraFields($this->db);
6248  $target_extrafields = $extrafields->fetch_name_optionals_label($this->table_element);
6249 
6250  // Eliminate copied source object extra fields that do not exist in target object
6251  $new_array_options = array();
6252  foreach ($this->array_options as $key => $value) {
6253  if (in_array(substr($key, 8), array_keys($target_extrafields))) { // We remove the 'options_' from $key for test
6254  $new_array_options[$key] = $value;
6255  } elseif (in_array($key, array_keys($target_extrafields))) { // We test on $key that does not contains the 'options_' prefix
6256  $new_array_options['options_'.$key] = $value;
6257  }
6258  }
6259 
6260  foreach ($new_array_options as $key => $value) {
6261  $attributeKey = substr($key, 8); // Remove 'options_' prefix
6262  $attributeType = $extrafields->attributes[$this->table_element]['type'][$attributeKey];
6263  $attributeLabel = $extrafields->attributes[$this->table_element]['label'][$attributeKey];
6264  $attributeParam = $extrafields->attributes[$this->table_element]['param'][$attributeKey];
6265  $attributeRequired = $extrafields->attributes[$this->table_element]['required'][$attributeKey];
6266  $attributeUnique = $extrafields->attributes[$this->table_element]['unique'][$attributeKey];
6267  $attrfieldcomputed = $extrafields->attributes[$this->table_element]['computed'][$attributeKey];
6268 
6269  // If we clone, we have to clean unique extrafields to prevent duplicates.
6270  // This behaviour can be prevented by external code by changing $this->context['createfromclone'] value in createFrom hook
6271  if (!empty($this->context['createfromclone']) && $this->context['createfromclone'] == 'createfromclone' && !empty($attributeUnique)) {
6272  $new_array_options[$key] = null;
6273  }
6274 
6275  // Similar code than into insertExtraFields
6276  if ($attributeRequired) {
6277  $mandatorypb = false;
6278  if ($attributeType == 'link' && $this->array_options[$key] == '-1') {
6279  $mandatorypb = true;
6280  }
6281  if ($this->array_options[$key] === '') {
6282  $mandatorypb = true;
6283  }
6284  if ($attributeType == 'sellist' && $this->array_options[$key] == '0') {
6285  $mandatorypb = true;
6286  }
6287  if ($mandatorypb) {
6288  $langs->load("errors");
6289  dol_syslog("Mandatory field '".$key."' is empty during create and set to required into definition of extrafields");
6290  $this->errors[] = $langs->trans('ErrorFieldRequired', $attributeLabel);
6291  return -1;
6292  }
6293  }
6294 
6295  //dol_syslog("attributeLabel=".$attributeLabel, LOG_DEBUG);
6296  //dol_syslog("attributeType=".$attributeType, LOG_DEBUG);
6297 
6298  if (!empty($attrfieldcomputed)) {
6299  if (!empty($conf->global->MAIN_STORE_COMPUTED_EXTRAFIELDS)) {
6300  $value = dol_eval($attrfieldcomputed, 1, 0, '');
6301  dol_syslog($langs->trans("Extrafieldcomputed")." sur ".$attributeLabel."(".$value.")", LOG_DEBUG);
6302  $new_array_options[$key] = $value;
6303  } else {
6304  $new_array_options[$key] = null;
6305  }
6306  }
6307 
6308  switch ($attributeType) {
6309  case 'int':
6310  if (!is_numeric($value) && $value != '') {
6311  $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
6312  return -1;
6313  } elseif ($value == '') {
6314  $new_array_options[$key] = null;
6315  }
6316  break;
6317  case 'price':
6318  case 'double':
6319  $value = price2num($value);
6320  if (!is_numeric($value) && $value != '') {
6321  dol_syslog($langs->trans("ExtraFieldHasWrongValue")." for ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
6322  $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
6323  return -1;
6324  } elseif ($value == '') {
6325  $value = null;
6326  }
6327  //dol_syslog("double value"." sur ".$attributeLabel."(".$value." is '".$attributeType."')", LOG_DEBUG);
6328  $new_array_options[$key] = $value;
6329  break;
6330  /*case 'select': // Not required, we chosed value='0' for undefined values
6331  if ($value=='-1')
6332  {
6333  $this->array_options[$key] = null;
6334  }
6335  break;*/
6336  case 'password':
6337  $algo = '';
6338  if ($this->array_options[$key] != '' && is_array($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options'])) {
6339  // If there is an encryption choice, we use it to crypt data before insert
6340  $tmparrays = array_keys($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options']);
6341  $algo = reset($tmparrays);
6342  if ($algo != '') {
6343  //global $action; // $action may be 'create', 'update', 'update_extras'...
6344  //var_dump($action);
6345  //var_dump($this->oldcopy);exit;
6346  if (is_object($this->oldcopy)) { // If this->oldcopy is not defined, we can't know if we change attribute or not, so we must keep value
6347  //var_dump($this->oldcopy->array_options[$key]); var_dump($this->array_options[$key]);
6348  if (isset($this->oldcopy->array_options[$key]) && $this->array_options[$key] == $this->oldcopy->array_options[$key]) { // If old value crypted in database is same than submited new value, it means we don't change it, so we don't update.
6349  $new_array_options[$key] = $this->array_options[$key]; // Value is kept
6350  } else {
6351  // var_dump($algo);
6352  $newvalue = dol_hash($this->array_options[$key], $algo);
6353  $new_array_options[$key] = $newvalue;
6354  }
6355  } else {
6356  $new_array_options[$key] = $this->array_options[$key]; // Value is kept
6357  }
6358  }
6359  } else // Common usage
6360  {
6361  $new_array_options[$key] = $this->array_options[$key];
6362  }
6363  break;
6364  case 'date':
6365  case 'datetime':
6366  // If data is a string instead of a timestamp, we convert it
6367  if (!is_numeric($this->array_options[$key]) || $this->array_options[$key] != intval($this->array_options[$key])) {
6368  $this->array_options[$key] = strtotime($this->array_options[$key]);
6369  }
6370  $new_array_options[$key] = $this->db->idate($this->array_options[$key]);
6371  break;
6372  case 'datetimegmt':
6373  // If data is a string instead of a timestamp, we convert it
6374  if (!is_numeric($this->array_options[$key]) || $this->array_options[$key] != intval($this->array_options[$key])) {
6375  $this->array_options[$key] = strtotime($this->array_options[$key]);
6376  }
6377  $new_array_options[$key] = $this->db->idate($this->array_options[$key], 'gmt');
6378  break;
6379  case 'link':
6380  $param_list = array_keys($attributeParam['options']);
6381  // 0 : ObjectName
6382  // 1 : classPath
6383  $InfoFieldList = explode(":", $param_list[0]);
6384  dol_include_once($InfoFieldList[1]);
6385  if ($InfoFieldList[0] && class_exists($InfoFieldList[0])) {
6386  if ($value == '-1') { // -1 is key for no defined in combo list of objects
6387  $new_array_options[$key] = '';
6388  } elseif ($value) {
6389  $object = new $InfoFieldList[0]($this->db);
6390  if (is_numeric($value)) {
6391  $res = $object->fetch($value); // Common case
6392  } else {
6393  $res = $object->fetch('', $value); // For compatibility
6394  }
6395 
6396  if ($res > 0) {
6397  $new_array_options[$key] = $object->id;
6398  } else {
6399  $this->error = "Id/Ref '".$value."' for object '".$object->element."' not found";
6400  return -1;
6401  }
6402  }
6403  } else {
6404  dol_syslog('Error bad setup of extrafield', LOG_WARNING);
6405  }
6406  break;
6407  }
6408  }
6409 
6410  $this->db->begin();
6411 
6412  $table_element = $this->table_element;
6413  if ($table_element == 'categorie') {
6414  $table_element = 'categories'; // For compatibility
6415  }
6416 
6417  dol_syslog(get_class($this)."::insertExtraFields delete then insert", LOG_DEBUG);
6418 
6419  $sql_del = "DELETE FROM ".$this->db->prefix().$table_element."_extrafields WHERE fk_object = ".((int) $this->id);
6420  $this->db->query($sql_del);
6421 
6422  $sql = "INSERT INTO ".$this->db->prefix().$table_element."_extrafields (fk_object";
6423  foreach ($new_array_options as $key => $value) {
6424  $attributeKey = substr($key, 8); // Remove 'options_' prefix
6425  // Add field of attribut
6426  if ($extrafields->attributes[$this->table_element]['type'][$attributeKey] != 'separate') { // Only for other type than separator
6427  $sql .= ",".$attributeKey;
6428  }
6429  }
6430  // We must insert a default value for fields for other entities that are mandatory to avoid not null error
6431  if (!empty($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities']) && is_array($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'])) {
6432  foreach ($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'] as $tmpkey => $tmpval) {
6433  if (!isset($extrafields->attributes[$this->table_element]['type'][$tmpkey])) { // If field not already added previously
6434  $sql .= ",".$tmpkey;
6435  }
6436  }
6437  }
6438  $sql .= ") VALUES (".$this->id;
6439 
6440  foreach ($new_array_options as $key => $value) {
6441  $attributeKey = substr($key, 8); // Remove 'options_' prefix
6442  // Add field of attribute
6443  if ($extrafields->attributes[$this->table_element]['type'][$attributeKey] != 'separate') { // Only for other type than separator)
6444  if ($new_array_options[$key] != '' || $new_array_options[$key] == '0') {
6445  $sql .= ",'".$this->db->escape($new_array_options[$key])."'";
6446  } else {
6447  $sql .= ",null";
6448  }
6449  }
6450  }
6451  // We must insert a default value for fields for other entities that are mandatory to avoid not null error
6452  if (!empty($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities']) && is_array($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'])) {
6453  foreach ($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'] as $tmpkey => $tmpval) {
6454  if (!isset($extrafields->attributes[$this->table_element]['type'][$tmpkey])) { // If field not already added previously
6455  if (in_array($tmpval, array('int', 'double', 'price'))) {
6456  $sql .= ", 0";
6457  } else {
6458  $sql .= ", ''";
6459  }
6460  }
6461  }
6462  }
6463 
6464  $sql .= ")";
6465 
6466  $resql = $this->db->query($sql);
6467  if (!$resql) {
6468  $this->error = $this->db->lasterror();
6469  $error++;
6470  }
6471 
6472  if (!$error && $trigger) {
6473  // Call trigger
6474  $this->context = array('extrafieldaddupdate'=>1);
6475  $result = $this->call_trigger($trigger, $userused);
6476  if ($result < 0) {
6477  $error++;
6478  }
6479  // End call trigger
6480  }
6481 
6482  if ($error) {
6483  $this->db->rollback();
6484  return -1;
6485  } else {
6486  $this->db->commit();
6487  return 1;
6488  }
6489  } else {
6490  return 0;
6491  }
6492  }
6493 
6504  public function insertExtraLanguages($trigger = '', $userused = null)
6505  {
6506  global $conf, $langs, $user;
6507 
6508  if (empty($userused)) {
6509  $userused = $user;
6510  }
6511 
6512  $error = 0;
6513 
6514  if (!empty($conf->global->MAIN_EXTRALANGUAGES_DISABLED)) {
6515  return 0; // For avoid conflicts if trigger used
6516  }
6517 
6518  if (is_array($this->array_languages)) {
6519  $new_array_languages = $this->array_languages;
6520 
6521  foreach ($new_array_languages as $key => $value) {
6522  $attributeKey = $key;
6523  $attributeType = $this->fields[$attributeKey]['type'];
6524  $attributeLabel = $this->fields[$attributeKey]['label'];
6525 
6526  //dol_syslog("attributeLabel=".$attributeLabel, LOG_DEBUG);
6527  //dol_syslog("attributeType=".$attributeType, LOG_DEBUG);
6528 
6529  switch ($attributeType) {
6530  case 'int':
6531  if (!is_numeric($value) && $value != '') {
6532  $this->errors[] = $langs->trans("ExtraLanguageHasWrongValue", $attributeLabel);
6533  return -1;
6534  } elseif ($value == '') {
6535  $new_array_languages[$key] = null;
6536  }
6537  break;
6538  case 'double':
6539  $value = price2num($value);
6540  if (!is_numeric($value) && $value != '') {
6541  dol_syslog($langs->trans("ExtraLanguageHasWrongValue")." sur ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
6542  $this->errors[] = $langs->trans("ExtraLanguageHasWrongValue", $attributeLabel);
6543  return -1;
6544  } elseif ($value == '') {
6545  $new_array_languages[$key] = null;
6546  } else {
6547  $new_array_languages[$key] = $value;
6548  }
6549  break;
6550  /*case 'select': // Not required, we chosed value='0' for undefined values
6551  if ($value=='-1')
6552  {
6553  $this->array_options[$key] = null;
6554  }
6555  break;*/
6556  }
6557  }
6558 
6559  $this->db->begin();
6560 
6561  $table_element = $this->table_element;
6562  if ($table_element == 'categorie') {
6563  $table_element = 'categories'; // For compatibility
6564  }
6565 
6566  dol_syslog(get_class($this)."::insertExtraLanguages delete then insert", LOG_DEBUG);
6567 
6568  foreach ($new_array_languages as $key => $langcodearray) { // $key = 'name', 'town', ...
6569  foreach ($langcodearray as $langcode => $value) {
6570  $sql_del = "DELETE FROM ".$this->db->prefix()."object_lang";
6571  $sql_del .= " WHERE fk_object = ".((int) $this->id)." AND property = '".$this->db->escape($key)."' AND type_object = '".$this->db->escape($table_element)."'";
6572  $sql_del .= " AND lang = '".$this->db->escape($langcode)."'";
6573  $this->db->query($sql_del);
6574 
6575  if ($value !== '') {
6576  $sql = "INSERT INTO ".$this->db->prefix()."object_lang (fk_object, property, type_object, lang, value";
6577  $sql .= ") VALUES (".$this->id.", '".$this->db->escape($key)."', '".$this->db->escape($table_element)."', '".$this->db->escape($langcode)."', '".$this->db->escape($value)."'";
6578  $sql .= ")";
6579 
6580  $resql = $this->db->query($sql);
6581  if (!$resql) {
6582  $this->error = $this->db->lasterror();
6583  $error++;
6584  break;
6585  }
6586  }
6587  }
6588  }
6589 
6590  if (!$error && $trigger) {
6591  // Call trigger
6592  $this->context = array('extralanguagesaddupdate'=>1);
6593  $result = $this->call_trigger($trigger, $userused);
6594  if ($result < 0) {
6595  $error++;
6596  }
6597  // End call trigger
6598  }
6599 
6600  if ($error) {
6601  $this->db->rollback();
6602  return -1;
6603  } else {
6604  $this->db->commit();
6605  return 1;
6606  }
6607  } else {
6608  return 0;
6609  }
6610  }
6611 
6622  public function updateExtraField($key, $trigger = null, $userused = null)
6623  {
6624  global $conf, $langs, $user;
6625 
6626  if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
6627  return 0;
6628  }
6629 
6630  if (empty($userused)) {
6631  $userused = $user;
6632  }
6633 
6634  $error = 0;
6635 
6636  if (!empty($this->array_options) && isset($this->array_options["options_".$key])) {
6637  // Check parameters
6638  $langs->load('admin');
6639  require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
6640  $extrafields = new ExtraFields($this->db);
6641  $extrafields->fetch_name_optionals_label($this->table_element);
6642 
6643  $value = $this->array_options["options_".$key];
6644 
6645  $attributeType = $extrafields->attributes[$this->table_element]['type'][$key];
6646  $attributeLabel = $extrafields->attributes[$this->table_element]['label'][$key];
6647  $attributeParam = $extrafields->attributes[$this->table_element]['param'][$key];
6648  $attributeRequired = $extrafields->attributes[$this->table_element]['required'][$key];
6649  $attrfieldcomputed = $extrafields->attributes[$this->table_element]['computed'][$key];
6650 
6651  // Similar code than into insertExtraFields
6652  if ($attributeRequired) {
6653  $mandatorypb = false;
6654  if ($attributeType == 'link' && $this->array_options["options_".$key] == '-1') {
6655  $mandatorypb = true;
6656  }
6657  if ($this->array_options["options_".$key] === '') {
6658  $mandatorypb = true;
6659  }
6660  if ($mandatorypb) {
6661  $langs->load("errors");
6662  dol_syslog("Mandatory field 'options_".$key."' is empty during update and set to required into definition of extrafields");
6663  $this->errors[] = $langs->trans('ErrorFieldRequired', $attributeLabel);
6664  return -1;
6665  }
6666  }
6667 
6668  //dol_syslog("attributeLabel=".$attributeLabel, LOG_DEBUG);
6669  //dol_syslog("attributeType=".$attributeType, LOG_DEBUG);
6670 
6671  if (!empty($attrfieldcomputed)) {
6672  if (!empty($conf->global->MAIN_STORE_COMPUTED_EXTRAFIELDS)) {
6673  $value = dol_eval($attrfieldcomputed, 1, 0, '');
6674  dol_syslog($langs->trans("Extrafieldcomputed")." sur ".$attributeLabel."(".$value.")", LOG_DEBUG);
6675  $this->array_options["options_".$key] = $value;
6676  } else {
6677  $this->array_options["options_".$key] = null;
6678  }
6679  }
6680 
6681  switch ($attributeType) {
6682  case 'int':
6683  if (!is_numeric($value) && $value != '') {
6684  $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
6685  return -1;
6686  } elseif ($value === '') {
6687  $this->array_options["options_".$key] = null;
6688  }
6689  break;
6690  case 'double':
6691  $value = price2num($value);
6692  if (!is_numeric($value) && $value != '') {
6693  dol_syslog($langs->trans("ExtraFieldHasWrongValue")." sur ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
6694  $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
6695  return -1;
6696  } elseif ($value === '') {
6697  $value = null;
6698  }
6699  //dol_syslog("double value"." sur ".$attributeLabel."(".$value." is '".$attributeType."')", LOG_DEBUG);
6700  $this->array_options["options_".$key] = $value;
6701  break;
6702  /*case 'select': // Not required, we chosed value='0' for undefined values
6703  if ($value=='-1')
6704  {
6705  $this->array_options[$key] = null;
6706  }
6707  break;*/
6708  case 'price':
6709  $this->array_options["options_".$key] = price2num($this->array_options["options_".$key]);
6710  break;
6711  case 'date':
6712  case 'datetime':
6713  if (empty($this->array_options["options_".$key])) {
6714  $this->array_options["options_".$key] = null;
6715  } else {
6716  $this->array_options["options_".$key] = $this->db->idate($this->array_options["options_".$key]);
6717  }
6718  break;
6719  case 'datetimegmt':
6720  if (empty($this->array_options["options_".$key])) {
6721  $this->array_options["options_".$key] = null;
6722  } else {
6723  $this->array_options["options_".$key] = $this->db->idate($this->array_options["options_".$key], 'gmt');
6724  }
6725  break;
6726  case 'boolean':
6727  if (empty($this->array_options["options_".$key])) {
6728  $this->array_options["options_".$key] = null;
6729  }
6730  break;
6731  /*
6732  case 'link':
6733  $param_list = array_keys($attributeParam['options']);
6734  // 0 : ObjectName
6735  // 1 : classPath
6736  $InfoFieldList = explode(":", $param_list[0]);
6737  dol_include_once($InfoFieldList[1]);
6738  if ($InfoFieldList[0] && class_exists($InfoFieldList[0]))
6739  {
6740  if ($value == '-1') // -1 is key for no defined in combo list of objects
6741  {
6742  $new_array_options[$key] = '';
6743  } elseif ($value) {
6744  $object = new $InfoFieldList[0]($this->db);
6745  if (is_numeric($value)) $res = $object->fetch($value); // Common case
6746  else $res = $object->fetch('', $value); // For compatibility
6747 
6748  if ($res > 0) $new_array_options[$key] = $object->id;
6749  else {
6750  $this->error = "Id/Ref '".$value."' for object '".$object->element."' not found";
6751  $this->db->rollback();
6752  return -1;
6753  }
6754  }
6755  } else {
6756  dol_syslog('Error bad setup of extrafield', LOG_WARNING);
6757  }
6758  break;
6759  */
6760  }
6761 
6762  $this->db->begin();
6763 
6764  $linealreadyfound = 0;
6765 
6766  // Check if there is already a line for this object (in most cases, it is, but sometimes it is not, for example when extra field has been created after), so we must keep this overload)
6767  $sql = "SELECT COUNT(rowid) as nb FROM ".$this->db->prefix().$this->table_element."_extrafields WHERE fk_object = ".((int) $this->id);
6768  $resql = $this->db->query($sql);
6769  if ($resql) {
6770  $tmpobj = $this->db->fetch_object($resql);
6771  if ($tmpobj) {
6772  $linealreadyfound = $tmpobj->nb;
6773  }
6774  }
6775 
6776  if ($linealreadyfound) {
6777  if ($this->array_options["options_".$key] === null) {
6778  $sql = "UPDATE ".$this->db->prefix().$this->table_element."_extrafields SET ".$key." = null";
6779  } else {
6780  $sql = "UPDATE ".$this->db->prefix().$this->table_element."_extrafields SET ".$key." = '".$this->db->escape($this->array_options["options_".$key])."'";
6781  }
6782  $sql .= " WHERE fk_object = ".((int) $this->id);
6783  } else {
6784  $result = $this->insertExtraFields('', $user);
6785  if ($result < 0) {
6786  $error++;
6787  }
6788  }
6789 
6790  $resql = $this->db->query($sql);
6791  if (!$resql) {
6792  $error++;
6793  $this->error = $this->db->lasterror();
6794  }
6795  if (!$error && $trigger) {
6796  // Call trigger
6797  $this->context = array('extrafieldupdate'=>1);
6798  $result = $this->call_trigger($trigger, $userused);
6799  if ($result < 0) {
6800  $error++;
6801  }
6802  // End call trigger
6803  }
6804 
6805  if ($error) {
6806  dol_syslog(__METHOD__.$this->error, LOG_ERR);
6807  $this->db->rollback();
6808  return -1;
6809  } else {
6810  $this->db->commit();
6811  return 1;
6812  }
6813  } else {
6814  return 0;
6815  }
6816  }
6817 
6828  public function updateExtraLanguages($key, $trigger = null, $userused = null)
6829  {
6830  global $conf, $langs, $user;
6831 
6832  if (empty($userused)) {
6833  $userused = $user;
6834  }
6835 
6836  $error = 0;
6837 
6838  if (!empty($conf->global->MAIN_EXTRALANGUAGES_DISABLED)) {
6839  return 0; // For avoid conflicts if trigger used
6840  }
6841 
6842  return 0;
6843  }
6844 
6845 
6860  public function showInputField($val, $key, $value, $moreparam = '', $keysuffix = '', $keyprefix = '', $morecss = 0, $nonewbutton = 0)
6861  {
6862  global $conf, $langs, $form;
6863 
6864  if (!is_object($form)) {
6865  require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
6866  $form = new Form($this->db);
6867  }
6868 
6869  if (!empty($this->fields)) {
6870  $val = $this->fields[$key];
6871  }
6872 
6873  // Validation tests and output
6874  $fieldValidationErrorMsg = '';
6875  $validationClass = '';
6876  $fieldValidationErrorMsg = $this->getFieldError($key);
6877  if (!empty($fieldValidationErrorMsg)) {
6878  $validationClass = ' --error'; // the -- is use as class state in css : .--error can't be be defined alone it must be define with another class like .my-class.--error or input.--error
6879  } else {
6880  $validationClass = ' --success'; // the -- is use as class state in css : .--success can't be be defined alone it must be define with another class like .my-class.--success or input.--success
6881  }
6882 
6883  $out = '';
6884  $type = '';
6885  $isDependList = 0;
6886  $param = array();
6887  $param['options'] = array();
6888  $reg = array();
6889  $size = !empty($this->fields[$key]['size']) ? $this->fields[$key]['size'] : 0;
6890  // Because we work on extrafields
6891  if (preg_match('/^(integer|link):(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
6892  $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4].':'.$reg[5] => 'N');
6893  $type = 'link';
6894  } elseif (preg_match('/^(integer|link):(.*):(.*):(.*)/i', $val['type'], $reg)) {
6895  $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4] => 'N');
6896  $type = 'link';
6897  } elseif (preg_match('/^(integer|link):(.*):(.*)/i', $val['type'], $reg)) {
6898  $param['options'] = array($reg[2].':'.$reg[3] => 'N');
6899  $type = 'link';
6900  } elseif (preg_match('/^(sellist):(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
6901  $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4].':'.$reg[5] => 'N');
6902  $type = 'sellist';
6903  } elseif (preg_match('/^(sellist):(.*):(.*):(.*)/i', $val['type'], $reg)) {
6904  $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4] => 'N');
6905  $type = 'sellist';
6906  } elseif (preg_match('/^(sellist):(.*):(.*)/i', $val['type'], $reg)) {
6907  $param['options'] = array($reg[2].':'.$reg[3] => 'N');
6908  $type = 'sellist';
6909  } elseif (preg_match('/^chkbxlst:(.*)/i', $val['type'], $reg)) {
6910  $param['options'] = array($reg[1] => 'N');
6911  $type = 'chkbxlst';
6912  } elseif (preg_match('/varchar\((\d+)\)/', $val['type'], $reg)) {
6913  $param['options'] = array();
6914  $type = 'varchar';
6915  $size = $reg[1];
6916  } elseif (preg_match('/varchar/', $val['type'])) {
6917  $param['options'] = array();
6918  $type = 'varchar';
6919  } else {
6920  $param['options'] = array();
6921  $type = $this->fields[$key]['type'];
6922  }
6923 
6924  // Special case that force options and type ($type can be integer, varchar, ...)
6925  if (!empty($this->fields[$key]['arrayofkeyval']) && is_array($this->fields[$key]['arrayofkeyval'])) {
6926  $param['options'] = $this->fields[$key]['arrayofkeyval'];
6927  $type = 'select';
6928  }
6929 
6930  $label = $this->fields[$key]['label'];
6931  //$elementtype=$this->fields[$key]['elementtype']; // Seems not used
6932  $default = (!empty($this->fields[$key]['default']) ? $this->fields[$key]['default'] : '');
6933  $computed = (!empty($this->fields[$key]['computed']) ? $this->fields[$key]['computed'] : '');
6934  $unique = (!empty($this->fields[$key]['unique']) ? $this->fields[$key]['unique'] : 0);
6935  $required = (!empty($this->fields[$key]['required']) ? $this->fields[$key]['required'] : 0);
6936  $autofocusoncreate = (!empty($this->fields[$key]['autofocusoncreate']) ? $this->fields[$key]['autofocusoncreate'] : 0);
6937 
6938  $langfile = (!empty($this->fields[$key]['langfile']) ? $this->fields[$key]['langfile'] : '');
6939  $list = (!empty($this->fields[$key]['list']) ? $this->fields[$key]['list'] : 0);
6940  $hidden = (in_array(abs($this->fields[$key]['visible']), array(0, 2)) ? 1 : 0);
6941 
6942  $objectid = $this->id;
6943 
6944  if ($computed) {
6945  if (!preg_match('/^search_/', $keyprefix)) {
6946  return '<span class="opacitymedium">'.$langs->trans("AutomaticallyCalculated").'</span>';
6947  } else {
6948  return '';
6949  }
6950  }
6951 
6952  // Set value of $morecss. For this, we use in priority showsize from parameters, then $val['css'] then autodefine
6953  if (empty($morecss) && !empty($val['css'])) {
6954  $morecss = $val['css'];
6955  } elseif (empty($morecss)) {
6956  if ($type == 'date') {
6957  $morecss = 'minwidth100imp';
6958  } elseif ($type == 'datetime' || $type == 'link') { // link means an foreign key to another primary id
6959  $morecss = 'minwidth200imp';
6960  } elseif (in_array($type, array('int', 'integer', 'price')) || preg_match('/^double(\([0-9],[0-9]\)){0,1}/', $type)) {
6961  $morecss = 'maxwidth75';
6962  } elseif ($type == 'url') {
6963  $morecss = 'minwidth400';
6964  } elseif ($type == 'boolean') {
6965  $morecss = '';
6966  } else {
6967  if (round($size) < 12) {
6968  $morecss = 'minwidth100';
6969  } elseif (round($size) <= 48) {
6970  $morecss = 'minwidth200';
6971  } else {
6972  $morecss = 'minwidth400';
6973  }
6974  }
6975  }
6976 
6977  // Add validation state class
6978  if (!empty($validationClass)) {
6979  $morecss.= $validationClass;
6980  }
6981 
6982  if (in_array($type, array('date'))) {
6983  $tmp = explode(',', $size);
6984  $newsize = $tmp[0];
6985  $showtime = 0;
6986 
6987  // Do not show current date when field not required (see selectDate() method)
6988  if (!$required && $value == '') {
6989  $value = '-1';
6990  }
6991 
6992  // TODO Must also support $moreparam
6993  $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required, '', 1, (($keyprefix != 'search_' && $keyprefix != 'search_options_') ? 1 : 0), 0, 1);
6994  } elseif (in_array($type, array('datetime'))) {
6995  $tmp = explode(',', $size);
6996  $newsize = $tmp[0];
6997  $showtime = 1;
6998 
6999  // Do not show current date when field not required (see selectDate() method)
7000  if (!$required && $value == '') $value = '-1';
7001 
7002  // TODO Must also support $moreparam
7003  $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required, '', 1, (($keyprefix != 'search_' && $keyprefix != 'search_options_') ? 1 : 0), 0, 1, '', '', '', 1, '', '', 'tzuserrel');
7004  } elseif (in_array($type, array('duration'))) {
7005  $out = $form->select_duration($keyprefix.$key.$keysuffix, $value, 0, 'text', 0, 1);
7006  } elseif (in_array($type, array('int', 'integer'))) {
7007  $tmp = explode(',', $size);
7008  $newsize = $tmp[0];
7009  $out = '<input type="text" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'"'.($newsize > 0 ? ' maxlength="'.$newsize.'"' : '').' value="'.dol_escape_htmltag($value).'"'.($moreparam ? $moreparam : '').($autofocusoncreate ? ' autofocus' : '').'>';
7010  } elseif (in_array($type, array('real'))) {
7011  $out = '<input type="text" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'"'.($moreparam ? $moreparam : '').($autofocusoncreate ? ' autofocus' : '').'>';
7012  } elseif (preg_match('/varchar/', $type)) {
7013  $out = '<input type="text" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'"'.($size > 0 ? ' maxlength="'.$size.'"' : '').' value="'.dol_escape_htmltag($value).'"'.($moreparam ? $moreparam : '').($autofocusoncreate ? ' autofocus' : '').'>';
7014  } elseif (in_array($type, array('email', 'mail', 'phone', 'url', 'ip'))) {
7015  $out = '<input type="text" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').($autofocusoncreate ? ' autofocus' : '').'>';
7016  } elseif (preg_match('/^text/', $type)) {
7017  if (!preg_match('/search_/', $keyprefix)) { // If keyprefix is search_ or search_options_, we must just use a simple text field
7018  require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
7019  $doleditor = new DolEditor($keyprefix.$key.$keysuffix, $value, '', 200, 'dolibarr_notes', 'In', false, false, false, ROWS_5, '90%');
7020  $out = $doleditor->Create(1);
7021  } else {
7022  $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').'>';
7023  }
7024  } elseif (preg_match('/^html/', $type)) {
7025  if (!preg_match('/search_/', $keyprefix)) { // If keyprefix is search_ or search_options_, we must just use a simple text field
7026  require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
7027  $doleditor = new DolEditor($keyprefix.$key.$keysuffix, $value, '', 200, 'dolibarr_notes', 'In', false, false, isModEnabled('fckeditor') && $conf->global->FCKEDITOR_ENABLE_SOCIETE, ROWS_5, '90%');
7028  $out = $doleditor->Create(1, '', true, '', '', $moreparam, $morecss);
7029  } else {
7030  $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').'>';
7031  }
7032  } elseif ($type == 'boolean') {
7033  $checked = '';
7034  if (!empty($value)) {
7035  $checked = ' checked value="1" ';
7036  } else {
7037  $checked = ' value="1" ';
7038  }
7039  $out = '<input type="checkbox" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.$checked.' '.($moreparam ? $moreparam : '').'>';
7040  } elseif ($type == 'price') {
7041  if (!empty($value)) { // $value in memory is a php numeric, we format it into user number format.
7042  $value = price($value);
7043  }
7044  $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'> '.$langs->getCurrencySymbol($conf->currency);
7045  } elseif (preg_match('/^double(\([0-9],[0-9]\)){0,1}/', $type)) {
7046  if (!empty($value)) { // $value in memory is a php numeric, we format it into user number format.
7047  $value = price($value);
7048  }
7049  $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'> ';
7050  } elseif ($type == 'select') {
7051  $out = '';
7052  if (!empty($conf->use_javascript_ajax) && empty($conf->global->MAIN_EXTRAFIELDS_DISABLE_SELECT2)) {
7053  include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
7054  $out .= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
7055  }
7056 
7057  $out .= '<select class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '').'>';
7058  if ((!isset($this->fields[$key]['default'])) || ($this->fields[$key]['notnull'] != 1)) {
7059  $out .= '<option value="0">&nbsp;</option>';
7060  }
7061  foreach ($param['options'] as $keyb => $valb) {
7062  if ((string) $keyb == '') {
7063  continue;
7064  }
7065  if (strpos($valb, "|") !== false) {
7066  list($valb, $parent) = explode('|', $valb);
7067  }
7068  $out .= '<option value="'.$keyb.'"';
7069  $out .= (((string) $value == (string) $keyb) ? ' selected' : '');
7070  $out .= (!empty($parent) ? ' parent="'.$parent.'"' : '');
7071  $out .= '>'.$valb.'</option>';
7072  }
7073  $out .= '</select>';
7074  } elseif ($type == 'sellist') {
7075  $out = '';
7076  if (!empty($conf->use_javascript_ajax) && empty($conf->global->MAIN_EXTRAFIELDS_DISABLE_SELECT2)) {
7077  include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
7078  $out .= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
7079  }
7080 
7081  $out .= '<select class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '').'>';
7082  if (is_array($param['options'])) {
7083  $param_list = array_keys($param['options']);
7084  $InfoFieldList = explode(":", $param_list[0]);
7085  $parentName = '';
7086  $parentField = '';
7087  // 0 : tableName
7088  // 1 : label field name
7089  // 2 : key fields name (if differ of rowid)
7090  // 3 : key field parent (for dependent lists)
7091  // 4 : where clause filter on column or table extrafield, syntax field='value' or extra.field=value
7092  // 5 : id category type
7093  // 6 : ids categories list separated by comma for category root
7094  $keyList = (empty($InfoFieldList[2]) ? 'rowid' : $InfoFieldList[2].' as rowid');
7095 
7096  if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
7097  if (strpos($InfoFieldList[4], 'extra.') !== false) {
7098  $keyList = 'main.'.$InfoFieldList[2].' as rowid';
7099  } else {
7100  $keyList = $InfoFieldList[2].' as rowid';
7101  }
7102  }
7103  if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
7104  list($parentName, $parentField) = explode('|', $InfoFieldList[3]);
7105  $keyList .= ', '.$parentField;
7106  }
7107 
7108  $filter_categorie = false;
7109  if (count($InfoFieldList) > 5) {
7110  if ($InfoFieldList[0] == 'categorie') {
7111  $filter_categorie = true;
7112  }
7113  }
7114 
7115  if ($filter_categorie === false) {
7116  $fields_label = explode('|', $InfoFieldList[1]);
7117  if (is_array($fields_label)) {
7118  $keyList .= ', ';
7119  $keyList .= implode(', ', $fields_label);
7120  }
7121 
7122  $sqlwhere = '';
7123  $sql = "SELECT " . $keyList;
7124  $sql .= " FROM " . $this->db->prefix() . $InfoFieldList[0];
7125  if (!empty($InfoFieldList[4])) {
7126  // can use SELECT request
7127  if (strpos($InfoFieldList[4], '$SEL$') !== false) {
7128  $InfoFieldList[4] = str_replace('$SEL$', 'SELECT', $InfoFieldList[4]);
7129  }
7130 
7131  // current object id can be use into filter
7132  if (strpos($InfoFieldList[4], '$ID$') !== false && !empty($objectid)) {
7133  $InfoFieldList[4] = str_replace('$ID$', $objectid, $InfoFieldList[4]);
7134  } else {
7135  $InfoFieldList[4] = str_replace('$ID$', '0', $InfoFieldList[4]);
7136  }
7137 
7138  //We have to join on extrafield table
7139  if (strpos($InfoFieldList[4], 'extra') !== false) {
7140  $sql .= " as main, " . $this->db->prefix() . $InfoFieldList[0] . "_extrafields as extra";
7141  $sqlwhere .= " WHERE extra.fk_object=main." . $InfoFieldList[2] . " AND " . $InfoFieldList[4];
7142  } else {
7143  $sqlwhere .= " WHERE " . $InfoFieldList[4];
7144  }
7145  } else {
7146  $sqlwhere .= ' WHERE 1=1';
7147  }
7148  // Some tables may have field, some other not. For the moment we disable it.
7149  if (in_array($InfoFieldList[0], array('tablewithentity'))) {
7150  $sqlwhere .= " AND entity = " . ((int) $conf->entity);
7151  }
7152  $sql .= $sqlwhere;
7153  //print $sql;
7154 
7155  $sql .= ' ORDER BY ' . implode(', ', $fields_label);
7156 
7157  dol_syslog(get_class($this) . '::showInputField type=sellist', LOG_DEBUG);
7158  $resql = $this->db->query($sql);
7159  if ($resql) {
7160  $out .= '<option value="0">&nbsp;</option>';
7161  $num = $this->db->num_rows($resql);
7162  $i = 0;
7163  while ($i < $num) {
7164  $labeltoshow = '';
7165  $obj = $this->db->fetch_object($resql);
7166 
7167  // Several field into label (eq table:code|libelle:rowid)
7168  $notrans = false;
7169  $fields_label = explode('|', $InfoFieldList[1]);
7170  if (count($fields_label) > 1) {
7171  $notrans = true;
7172  foreach ($fields_label as $field_toshow) {
7173  $labeltoshow .= $obj->$field_toshow . ' ';
7174  }
7175  } else {
7176  $labeltoshow = $obj->{$InfoFieldList[1]};
7177  }
7178  $labeltoshow = dol_trunc($labeltoshow, 45);
7179 
7180  if ($value == $obj->rowid) {
7181  foreach ($fields_label as $field_toshow) {
7182  $translabel = $langs->trans($obj->$field_toshow);
7183  if ($translabel != $obj->$field_toshow) {
7184  $labeltoshow = dol_trunc($translabel) . ' ';
7185  } else {
7186  $labeltoshow = dol_trunc($obj->$field_toshow) . ' ';
7187  }
7188  }
7189  $out .= '<option value="' . $obj->rowid . '" selected>' . $labeltoshow . '</option>';
7190  } else {
7191  if (!$notrans) {
7192  $translabel = $langs->trans($obj->{$InfoFieldList[1]});
7193  if ($translabel != $obj->{$InfoFieldList[1]}) {
7194  $labeltoshow = dol_trunc($translabel, 18);
7195  } else {
7196  $labeltoshow = dol_trunc($obj->{$InfoFieldList[1]});
7197  }
7198  }
7199  if (empty($labeltoshow)) {
7200  $labeltoshow = '(not defined)';
7201  }
7202  if ($value == $obj->rowid) {
7203  $out .= '<option value="' . $obj->rowid . '" selected>' . $labeltoshow . '</option>';
7204  }
7205 
7206  if (!empty($InfoFieldList[3]) && $parentField) {
7207  $parent = $parentName . ':' . $obj->{$parentField};
7208  $isDependList = 1;
7209  }
7210 
7211  $out .= '<option value="' . $obj->rowid . '"';
7212  $out .= ($value == $obj->rowid ? ' selected' : '');
7213  $out .= (!empty($parent) ? ' parent="' . $parent . '"' : '');
7214  $out .= '>' . $labeltoshow . '</option>';
7215  }
7216 
7217  $i++;
7218  }
7219  $this->db->free($resql);
7220  } else {
7221  print 'Error in request ' . $sql . ' ' . $this->db->lasterror() . '. Check setup of extra parameters.<br>';
7222  }
7223  } else {
7224  require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
7225  $data = $form->select_all_categories(Categorie::$MAP_ID_TO_CODE[$InfoFieldList[5]], '', 'parent', 64, $InfoFieldList[6], 1, 1);
7226  $out .= '<option value="0">&nbsp;</option>';
7227  foreach ($data as $data_key => $data_value) {
7228  $out .= '<option value="' . $data_key . '"';
7229  $out .= ($value == $data_key ? ' selected' : '');
7230  $out .= '>' . $data_value . '</option>';
7231  }
7232  }
7233  }
7234  $out .= '</select>';
7235  } elseif ($type == 'checkbox') {
7236  $value_arr = explode(',', $value);
7237  $out = $form->multiselectarray($keyprefix.$key.$keysuffix, (empty($param['options']) ?null:$param['options']), $value_arr, '', 0, $morecss, 0, '100%');
7238  } elseif ($type == 'radio') {
7239  $out = '';
7240  foreach ($param['options'] as $keyopt => $valopt) {
7241  $out .= '<input class="flat '.$morecss.'" type="radio" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '');
7242  $out .= ' value="'.$keyopt.'"';
7243  $out .= ' id="'.$keyprefix.$key.$keysuffix.'_'.$keyopt.'"';
7244  $out .= ($value == $keyopt ? 'checked' : '');
7245  $out .= '/><label for="'.$keyprefix.$key.$keysuffix.'_'.$keyopt.'">'.$valopt.'</label><br>';
7246  }
7247  } elseif ($type == 'chkbxlst') {
7248  if (is_array($value)) {
7249  $value_arr = $value;
7250  } else {
7251  $value_arr = explode(',', $value);
7252  }
7253 
7254  if (is_array($param['options'])) {
7255  $param_list = array_keys($param['options']);
7256  $InfoFieldList = explode(":", $param_list[0]);
725