dolibarr  16.0.5
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-2019 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  *
20  * This program is free software; you can redistribute it and/or modify
21  * it under the terms of the GNU General Public License as published by
22  * the Free Software Foundation; either version 3 of the License, or
23  * (at your option) any later version.
24  *
25  * This program is distributed in the hope that it will be useful,
26  * but WITHOUT ANY WARRANTY; without even the implied warranty of
27  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
28  * GNU General Public License for more details.
29  *
30  * You should have received a copy of the GNU General Public License
31  * along with this program. If not, see <https://www.gnu.org/licenses/>.
32  */
33 
44 abstract class CommonObject
45 {
46  const TRIGGER_PREFIX = ''; // to be overriden in child class implementations, i.e. 'BILL', 'TASK', 'PROPAL', etc.
50  public $db;
51 
55  public $id;
56 
60  public $entity;
61 
66  public $error;
67 
71  public $errorhidden;
72 
76  public $errors = array();
77 
81  public $validateFieldsErrors = array();
82 
86  public $element;
87 
91  public $element_for_permission;
92 
96  public $table_element;
97 
101  public $table_element_line = '';
102 
106  public $import_key;
107 
111  public $array_options = array();
112 
116  public $array_languages = null; // Value is array() when load already tried
117 
121  public $contacts_ids;
122 
126  public $linked_objects;
127 
131  public $linkedObjectsIds;
132 
136  public $linkedObjects;
137 
141  public $linkedObjectsFullLoaded = array();
142 
146  public $oldcopy;
147 
151  protected $table_ref_field = '';
152 
156  public $restrictiononfksoc = 0;
157 
158 
159  // Following vars are used by some objects only. We keep this property here in CommonObject to be able to provide common method using them.
160 
164  public $context = array();
165 
169  public $canvas;
170 
175  public $project;
176 
181  public $fk_project;
182 
187  public $projet;
188 
193  public $fk_projet;
194 
199  public $contact;
200 
205  public $contact_id;
206 
211  public $thirdparty;
212 
217  public $user;
218 
223  public $origin;
224 
229  public $origin_id;
230 
234  public $ref;
235 
239  public $ref_ext;
240 
244  public $ref_previous;
245 
249  public $ref_next;
250 
254  public $newref;
255 
260  public $statut;
261 
266  public $status;
267 
268 
273  public $country;
274 
279  public $country_id;
280 
285  public $country_code;
286 
291  public $state;
292 
297  public $state_id;
298 
303  public $state_code;
304 
309  public $region_id;
310 
315  public $region_code;
316 
321  public $region;
322 
323 
328  public $barcode_type;
329 
334  public $barcode_type_code;
335 
340  public $barcode_type_label;
341 
346  public $barcode_type_coder;
347 
352  public $mode_reglement_id;
353 
358  public $cond_reglement_id;
359 
363  public $demand_reason_id;
364 
369  public $transport_mode_id;
370 
376  public $cond_reglement;
377 
383  public $fk_delivery_address;
384 
389  public $shipping_method_id;
390 
395  public $model_pdf;
396 
402  public $modelpdf;
403 
408  public $last_main_doc;
409 
415  public $fk_bank;
416 
421  public $fk_account;
422 
426  public $openid;
427 
432  public $note_public;
433 
438  public $note_private;
439 
444  public $note;
445 
450  public $total_ht;
451 
456  public $total_tva;
457 
462  public $total_localtax1;
463 
468  public $total_localtax2;
469 
474  public $total_ttc;
475 
479  public $lines;
480 
485  public $comments = array();
486 
490  public $name;
491 
495  public $lastname;
496 
500  public $firstname;
501 
505  public $civility_id;
506 
507  // Dates
511  public $date_creation;
512 
516  public $date_validation; // Date validation
517 
521  public $date_modification; // Date last change (tms field)
522 
526  public $date_cloture; // Date closing (tms field)
527 
532  public $user_author;
537  public $user_creation;
541  public $user_creation_id;
542 
547  public $user_valid;
552  public $user_validation;
556  public $user_validation_id;
560  public $user_closing_id;
561 
566  public $user_modification;
570  public $user_modification_id;
571 
572 
573  public $next_prev_filter;
574 
578  public $specimen = 0;
579 
583  public $sendtoid;
584 
588  public $alreadypaid;
589 
590 
594  protected $childtables = array();
595 
601  protected $childtablesoncascade = array();
602 
603 
604  // No constructor as it is an abstract class
605 
606 
617  public static function isExistingObject($element, $id, $ref = '', $ref_ext = '')
618  {
619  global $db, $conf;
620 
621  $sql = "SELECT rowid, ref, ref_ext";
622  $sql .= " FROM ".$db->prefix().$element;
623  $sql .= " WHERE entity IN (".getEntity($element).")";
624 
625  if ($id > 0) {
626  $sql .= " AND rowid = ".((int) $id);
627  } elseif ($ref) {
628  $sql .= " AND ref = '".$db->escape($ref)."'";
629  } elseif ($ref_ext) {
630  $sql .= " AND ref_ext = '".$db->escape($ref_ext)."'";
631  } else {
632  $error = 'ErrorWrongParameters';
633  dol_print_error(get_class()."::isExistingObject ".$error, LOG_ERR);
634  return -1;
635  }
636  if ($ref || $ref_ext) { // Because the same ref can exists in 2 different entities, we force the current one in priority
637  $sql .= " AND entity = ".((int) $conf->entity);
638  }
639 
640  dol_syslog(get_class()."::isExistingObject", LOG_DEBUG);
641  $resql = $db->query($sql);
642  if ($resql) {
643  $num = $db->num_rows($resql);
644  if ($num > 0) {
645  return 1;
646  } else {
647  return 0;
648  }
649  }
650  return -1;
651  }
652 
653 
659  public function errorsToString()
660  {
661  return $this->error.(is_array($this->errors) ? (($this->error != '' ? ', ' : '').join(', ', $this->errors)) : '');
662  }
663 
664 
671  public function getFormatedCustomerRef($objref)
672  {
673  global $hookmanager;
674 
675  $parameters = array('objref'=>$objref);
676  $action = '';
677  $reshook = $hookmanager->executeHooks('getFormatedCustomerRef', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
678  if ($reshook > 0) {
679  return $hookmanager->resArray['objref'];
680  }
681  return $objref.(isset($hookmanager->resArray['objref']) ? $hookmanager->resArray['objref'] : '');
682  }
683 
690  public function getFormatedSupplierRef($objref)
691  {
692  global $hookmanager;
693 
694  $parameters = array('objref'=>$objref);
695  $action = '';
696  $reshook = $hookmanager->executeHooks('getFormatedSupplierRef', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
697  if ($reshook > 0) {
698  return $hookmanager->resArray['objref'];
699  }
700  return $objref.(isset($hookmanager->resArray['objref']) ? $hookmanager->resArray['objref'] : '');
701  }
702 
712  public function getFullName($langs, $option = 0, $nameorder = -1, $maxlen = 0)
713  {
714  //print "lastname=".$this->lastname." name=".$this->name." nom=".$this->nom."<br>\n";
715  $lastname = $this->lastname;
716  $firstname = $this->firstname;
717  if (empty($lastname)) {
718  $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 : '')))));
719  }
720 
721  $ret = '';
722  if (!empty($option) && !empty($this->civility_code)) {
723  if ($langs->transnoentitiesnoconv("Civility".$this->civility_code) != "Civility".$this->civility_code) {
724  $ret .= $langs->transnoentitiesnoconv("Civility".$this->civility_code).' ';
725  } else {
726  $ret .= $this->civility_code.' ';
727  }
728  }
729 
730  $ret .= dolGetFirstLastname($firstname, $lastname, $nameorder);
731 
732  return dol_trunc($ret, $maxlen);
733  }
734 
740  public function setUpperOrLowerCase()
741  {
742  global $conf;
743  if (!empty($conf->global->MAIN_FIRST_TO_UPPER)) {
744  $this->lastname = dol_ucwords(dol_strtolower($this->lastname));
745  $this->firstname = dol_ucwords(dol_strtolower($this->firstname));
746  $this->name = dol_ucwords(dol_strtolower($this->name));
747  $this->name_alias = dol_ucwords(dol_strtolower($this->name_alias));
748  }
749  if (!empty($conf->global->MAIN_ALL_TO_UPPER)) {
750  $this->lastname = dol_strtoupper($this->lastname);
751  $this->name = dol_strtoupper($this->name);
752  $this->name_alias = dol_strtoupper($this->name_alias);
753  }
754  if (!empty($conf->global->MAIN_ALL_TOWN_TO_UPPER)) {
755  $this->address = dol_strtoupper($this->address);
756  $this->town = dol_strtoupper($this->town);
757  }
758  }
759 
766  public function getKanbanView($option = '')
767  {
768  $return = '<div class="box-flex-item box-flex-grow-zero">';
769  $return .= '<div class="info-box info-box-sm">';
770  $return .= '<span class="info-box-icon bg-infobox-action">';
771  $return .= img_picto('', $this->picto);
772  //$return .= '<i class="fa fa-dol-action"></i>'; // Can be image
773  $return .= '</span>';
774  $return .= '<div class="info-box-content">';
775  $return .= '<span class="info-box-ref">'.(method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref).'</span>';
776  if (property_exists($this, 'label')) {
777  $return .= '<br><span class="info-box-label opacitymedium">'.$this->label.'</span>';
778  }
779  if (method_exists($this, 'getLibStatut')) {
780  $return .= '<br><div class="info-box-status margintoponly">'.$this->getLibStatut(5).'</div>';
781  }
782  $return .= '</div>';
783  $return .= '</div>';
784  $return .= '</div>';
785 
786  return $return;
787  }
788 
798  public function getFullAddress($withcountry = 0, $sep = "\n", $withregion = 0, $extralangcode = '')
799  {
800  if ($withcountry && $this->country_id && (empty($this->country_code) || empty($this->country))) {
801  require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
802  $tmparray = getCountry($this->country_id, 'all');
803  $this->country_code = $tmparray['code'];
804  $this->country = $tmparray['label'];
805  }
806 
807  if ($withregion && $this->state_id && (empty($this->state_code) || empty($this->state) || empty($this->region) || empty($this->region_code))) {
808  require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
809  $tmparray = getState($this->state_id, 'all', 0, 1);
810  $this->state_code = $tmparray['code'];
811  $this->state = $tmparray['label'];
812  $this->region_code = $tmparray['region_code'];
813  $this->region = $tmparray['region'];
814  }
815 
816  return dol_format_address($this, $withcountry, $sep, '', 0, $extralangcode);
817  }
818 
819 
827  public function getBannerAddress($htmlkey, $object)
828  {
829  global $conf, $langs, $form, $extralanguages;
830 
831  $countriesusingstate = array('AU', 'US', 'IN', 'GB', 'ES', 'UK', 'TR'); // See also option MAIN_FORCE_STATE_INTO_ADDRESS
832 
833  $contactid = 0;
834  $thirdpartyid = 0;
835  $elementforaltlanguage = $this->element;
836  if ($this->element == 'societe') {
837  $thirdpartyid = $this->id;
838  }
839  if ($this->element == 'contact') {
840  $contactid = $this->id;
841  $thirdpartyid = empty($object->fk_soc) ? 0 : $object->fk_soc;
842  }
843  if ($this->element == 'user') {
844  $contactid = $this->contact_id;
845  $thirdpartyid = empty($object->fk_soc) ? 0 : $object->fk_soc;
846  }
847 
848  $out = '';
849 
850  $outdone = 0;
851  $coords = $this->getFullAddress(1, ', ', (!empty($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT) ? $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT : 0));
852  if ($coords) {
853  if (!empty($conf->use_javascript_ajax)) {
854  // Add picto with tooltip on map
855  $namecoords = '';
856  if ($this->element == 'contact' && !empty($conf->global->MAIN_SHOW_COMPANY_NAME_IN_BANNER_ADDRESS)) {
857  $namecoords .= $object->name.'<br>';
858  }
859  $namecoords .= $this->getFullName($langs, 1).'<br>'.$coords;
860  // hideonsmatphone because copyToClipboard call jquery dialog that does not work with jmobile
861  $out .= '<a href="#" class="hideonsmartphone" onclick="return copyToClipboard(\''.dol_escape_js($namecoords).'\',\''.dol_escape_js($langs->trans("HelpCopyToClipboard")).'\');">';
862  $out .= img_picto($langs->trans("Address"), 'map-marker-alt');
863  $out .= '</a> ';
864  }
865  $out .= dol_print_address($coords, 'address_'.$htmlkey.'_'.$this->id, $this->element, $this->id, 1, ', ');
866  $outdone++;
867  $outdone++;
868 
869  // List of extra languages
870  $arrayoflangcode = array();
871  if (!empty($conf->global->PDF_USE_ALSO_LANGUAGE_CODE)) {
872  $arrayoflangcode[] = $conf->global->PDF_USE_ALSO_LANGUAGE_CODE;
873  }
874 
875  if (is_array($arrayoflangcode) && count($arrayoflangcode)) {
876  if (!is_object($extralanguages)) {
877  include_once DOL_DOCUMENT_ROOT.'/core/class/extralanguages.class.php';
878  $extralanguages = new ExtraLanguages($this->db);
879  }
880  $extralanguages->fetch_name_extralanguages($elementforaltlanguage);
881 
882  if (!empty($extralanguages->attributes[$elementforaltlanguage]['address']) || !empty($extralanguages->attributes[$elementforaltlanguage]['town'])) {
883  $out .= "<!-- alternatelanguage for '".$elementforaltlanguage."' set to fields '".join(',', $extralanguages->attributes[$elementforaltlanguage])."' -->\n";
884  $this->fetchValuesForExtraLanguages();
885  if (!is_object($form)) {
886  $form = new Form($this->db);
887  }
888  $htmltext = '';
889  // If there is extra languages
890  foreach ($arrayoflangcode as $extralangcode) {
891  $s = picto_from_langcode($extralangcode, 'class="pictoforlang paddingright"');
892  $coords = $this->getFullAddress(1, ', ', $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT, $extralangcode);
893  $htmltext .= $s.dol_print_address($coords, 'address_'.$htmlkey.'_'.$this->id, $this->element, $this->id, 1, ', ');
894  }
895  $out .= $form->textwithpicto('', $htmltext, -1, 'language', 'opacitymedium paddingleft');
896  }
897  }
898  }
899 
900  if (!in_array($this->country_code, $countriesusingstate) && empty($conf->global->MAIN_FORCE_STATE_INTO_ADDRESS) // If MAIN_FORCE_STATE_INTO_ADDRESS is on, state is already returned previously with getFullAddress
901  && empty($conf->global->SOCIETE_DISABLE_STATE) && $this->state) {
902  if (!empty($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT) && $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT == 1 && $this->region) {
903  $out .= ($outdone ? ' - ' : '').$this->region.' - '.$this->state;
904  } else {
905  $out .= ($outdone ? ' - ' : '').$this->state;
906  }
907  $outdone++;
908  }
909 
910  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)) {
911  $out .= ($outdone ? '<br>' : '');
912  }
913  if (!empty($this->phone) && empty($this->phone_pro)) { // For objects that store pro phone into ->phone
914  $out .= dol_print_phone($this->phone, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'phone', $langs->trans("PhonePro"));
915  $outdone++;
916  }
917  if (!empty($this->phone_pro)) {
918  $out .= dol_print_phone($this->phone_pro, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'phone', $langs->trans("PhonePro"));
919  $outdone++;
920  }
921  if (!empty($this->phone_mobile)) {
922  $out .= dol_print_phone($this->phone_mobile, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'mobile', $langs->trans("PhoneMobile"));
923  $outdone++;
924  }
925  if (!empty($this->phone_perso)) {
926  $out .= dol_print_phone($this->phone_perso, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'phone', $langs->trans("PhonePerso"));
927  $outdone++;
928  }
929  if (!empty($this->office_phone)) {
930  $out .= dol_print_phone($this->office_phone, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'phone', $langs->trans("PhonePro"));
931  $outdone++;
932  }
933  if (!empty($this->user_mobile)) {
934  $out .= dol_print_phone($this->user_mobile, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'mobile', $langs->trans("PhoneMobile"));
935  $outdone++;
936  }
937  if (!empty($this->fax)) {
938  $out .= dol_print_phone($this->fax, $this->country_code, $contactid, $thirdpartyid, 'AC_FAX', '&nbsp;', 'fax', $langs->trans("Fax"));
939  $outdone++;
940  }
941  if (!empty($this->office_fax)) {
942  $out .= dol_print_phone($this->office_fax, $this->country_code, $contactid, $thirdpartyid, 'AC_FAX', '&nbsp;', 'fax', $langs->trans("Fax"));
943  $outdone++;
944  }
945 
946  if ($out) {
947  $out .= '<div style="clear: both;"></div>';
948  }
949  $outdone = 0;
950  if (!empty($this->email)) {
951  $out .= dol_print_email($this->email, $this->id, $object->id, 'AC_EMAIL', 0, 0, 1);
952  $outdone++;
953  }
954  if (!empty($this->url)) {
955  //$out.=dol_print_url($this->url,'_goout',0,1);//steve changed to blank
956  $out .= dol_print_url($this->url, '_blank', 0, 1);
957  $outdone++;
958  }
959 
960  if (!empty($conf->socialnetworks->enabled)) {
961  $outsocialnetwork = '';
962 
963  if (!empty($this->socialnetworks) && is_array($this->socialnetworks) && count($this->socialnetworks) > 0) {
964  $socialnetworksdict = getArrayOfSocialNetworks();
965  foreach ($this->socialnetworks as $key => $value) {
966  if ($value) {
967  $outsocialnetwork .= dol_print_socialnetworks($value, $this->id, $object->id, $key, $socialnetworksdict);
968  }
969  $outdone++;
970  }
971  } else { // Old code to remove
972  if (!empty($this->skype)) {
973  $outsocialnetwork .= dol_print_socialnetworks($this->skype, $this->id, $object->id, 'skype');
974  }
975  $outdone++;
976  if (!empty($this->jabberid)) {
977  $outsocialnetwork .= dol_print_socialnetworks($this->jabberid, $this->id, $object->id, 'jabber');
978  }
979  $outdone++;
980  if (!empty($this->twitter)) {
981  $outsocialnetwork .= dol_print_socialnetworks($this->twitter, $this->id, $object->id, 'twitter');
982  }
983  $outdone++;
984  if (!empty($this->facebook)) {
985  $outsocialnetwork .= dol_print_socialnetworks($this->facebook, $this->id, $object->id, 'facebook');
986  }
987  $outdone++;
988  if (!empty($this->linkedin)) {
989  $outsocialnetwork .= dol_print_socialnetworks($this->linkedin, $this->id, $object->id, 'linkedin');
990  }
991  $outdone++;
992  }
993 
994  if ($outsocialnetwork) {
995  $out .= '<div style="clear: both;">'.$outsocialnetwork.'</div>';
996  }
997  }
998 
999  if ($out) {
1000  return '<!-- BEGIN part to show address block -->'."\n".$out.'<!-- END Part to show address block -->'."\n";
1001  } else {
1002  return '';
1003  }
1004  }
1005 
1014  public function getLastMainDocLink($modulepart, $initsharekey = 0, $relativelink = 0)
1015  {
1016  global $user, $dolibarr_main_url_root;
1017 
1018  if (empty($this->last_main_doc)) {
1019  return ''; // No way to known which document name to use
1020  }
1021 
1022  include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
1023  $ecmfile = new EcmFiles($this->db);
1024  $result = $ecmfile->fetch(0, '', $this->last_main_doc);
1025  if ($result < 0) {
1026  $this->error = $ecmfile->error;
1027  $this->errors = $ecmfile->errors;
1028  return -1;
1029  }
1030 
1031  if (empty($ecmfile->id)) {
1032  // Add entry into index
1033  if ($initsharekey) {
1034  require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
1035 
1036  // 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
1037  /*
1038  $ecmfile->filepath = $rel_dir;
1039  $ecmfile->filename = $filename;
1040  $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
1041  $ecmfile->fullpath_orig = '';
1042  $ecmfile->gen_or_uploaded = 'generated';
1043  $ecmfile->description = ''; // indexed content
1044  $ecmfile->keywords = ''; // keyword content
1045  $ecmfile->share = getRandomPassword(true);
1046  $result = $ecmfile->create($user);
1047  if ($result < 0)
1048  {
1049  $this->error = $ecmfile->error;
1050  $this->errors = $ecmfile->errors;
1051  }
1052  */
1053  } else {
1054  return '';
1055  }
1056  } elseif (empty($ecmfile->share)) {
1057  // Add entry into index
1058  if ($initsharekey) {
1059  require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
1060  $ecmfile->share = getRandomPassword(true);
1061  $ecmfile->update($user);
1062  } else {
1063  return '';
1064  }
1065  }
1066  // Define $urlwithroot
1067  $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
1068  // This is to use external domain name found into config file
1069  //if (DOL_URL_ROOT && ! preg_match('/\/$/', $urlwithouturlroot) && ! preg_match('/^\//', DOL_URL_ROOT)) $urlwithroot=$urlwithouturlroot.'/'.DOL_URL_ROOT;
1070  //else
1071  $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT;
1072  //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
1073 
1074  $forcedownload = 0;
1075 
1076  $paramlink = '';
1077  //if (! empty($modulepart)) $paramlink.=($paramlink?'&':'').'modulepart='.$modulepart; // For sharing with hash (so public files), modulepart is not required.
1078  //if (! empty($ecmfile->entity)) $paramlink.='&entity='.$ecmfile->entity; // For sharing with hash (so public files), entity is not required.
1079  //$paramlink.=($paramlink?'&':'').'file='.urlencode($filepath); // No need of name of file for public link, we will use the hash
1080  if (!empty($ecmfile->share)) {
1081  $paramlink .= ($paramlink ? '&' : '').'hashp='.$ecmfile->share; // Hash for public share
1082  }
1083  if ($forcedownload) {
1084  $paramlink .= ($paramlink ? '&' : '').'attachment=1';
1085  }
1086 
1087  if ($relativelink) {
1088  $linktoreturn = 'document.php'.($paramlink ? '?'.$paramlink : '');
1089  } else {
1090  $linktoreturn = $urlwithroot.'/document.php'.($paramlink ? '?'.$paramlink : '');
1091  }
1092 
1093  // Here $ecmfile->share is defined
1094  return $linktoreturn;
1095  }
1096 
1097 
1098  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1108  public function add_contact($fk_socpeople, $type_contact, $source = 'external', $notrigger = 0)
1109  {
1110  // phpcs:enable
1111  global $user, $langs;
1112 
1113 
1114  dol_syslog(get_class($this)."::add_contact $fk_socpeople, $type_contact, $source, $notrigger");
1115 
1116  // Check parameters
1117  if ($fk_socpeople <= 0) {
1118  $langs->load("errors");
1119  $this->error = $langs->trans("ErrorWrongValueForParameterX", "1");
1120  dol_syslog(get_class($this)."::add_contact ".$this->error, LOG_ERR);
1121  return -1;
1122  }
1123  if (!$type_contact) {
1124  $langs->load("errors");
1125  $this->error = $langs->trans("ErrorWrongValueForParameterX", "2");
1126  dol_syslog(get_class($this)."::add_contact ".$this->error, LOG_ERR);
1127  return -2;
1128  }
1129 
1130  $id_type_contact = 0;
1131  if (is_numeric($type_contact)) {
1132  $id_type_contact = $type_contact;
1133  } else {
1134  // We look for id type_contact
1135  $sql = "SELECT tc.rowid";
1136  $sql .= " FROM ".$this->db->prefix()."c_type_contact as tc";
1137  $sql .= " WHERE tc.element='".$this->db->escape($this->element)."'";
1138  $sql .= " AND tc.source='".$this->db->escape($source)."'";
1139  $sql .= " AND tc.code='".$this->db->escape($type_contact)."' AND tc.active=1";
1140  //print $sql;
1141  $resql = $this->db->query($sql);
1142  if ($resql) {
1143  $obj = $this->db->fetch_object($resql);
1144  if ($obj) {
1145  $id_type_contact = $obj->rowid;
1146  }
1147  }
1148  }
1149 
1150  if ($id_type_contact == 0) {
1151  $this->error = 'CODE_NOT_VALID_FOR_THIS_ELEMENT';
1152  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");
1153  return -3;
1154  }
1155 
1156  $datecreate = dol_now();
1157 
1158  // Socpeople must have already been added by some trigger, then we have to check it to avoid DB_ERROR_RECORD_ALREADY_EXISTS error
1159  $TListeContacts = $this->liste_contact(-1, $source);
1160  $already_added = false;
1161  if (is_array($TListeContacts) && !empty($TListeContacts)) {
1162  foreach ($TListeContacts as $array_contact) {
1163  if ($array_contact['status'] == 4 && $array_contact['id'] == $fk_socpeople && $array_contact['fk_c_type_contact'] == $id_type_contact) {
1164  $already_added = true;
1165  break;
1166  }
1167  }
1168  }
1169 
1170  if (!$already_added) {
1171  $this->db->begin();
1172 
1173  // Insert into database
1174  $sql = "INSERT INTO ".$this->db->prefix()."element_contact";
1175  $sql .= " (element_id, fk_socpeople, datecreate, statut, fk_c_type_contact) ";
1176  $sql .= " VALUES (".$this->id.", ".((int) $fk_socpeople)." , ";
1177  $sql .= "'".$this->db->idate($datecreate)."'";
1178  $sql .= ", 4, ".((int) $id_type_contact);
1179  $sql .= ")";
1180 
1181  $resql = $this->db->query($sql);
1182  if ($resql) {
1183  if (!$notrigger) {
1184  $result = $this->call_trigger(strtoupper($this->element).'_ADD_CONTACT', $user);
1185  if ($result < 0) {
1186  $this->db->rollback();
1187  return -1;
1188  }
1189  }
1190 
1191  $this->db->commit();
1192  return 1;
1193  } else {
1194  if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
1195  $this->error = $this->db->errno();
1196  $this->db->rollback();
1197  return -2;
1198  } else {
1199  $this->error = $this->db->lasterror();
1200  $this->db->rollback();
1201  return -1;
1202  }
1203  }
1204  } else {
1205  return 0;
1206  }
1207  }
1208 
1209  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1217  public function copy_linked_contact($objFrom, $source = 'internal')
1218  {
1219  // phpcs:enable
1220  $contacts = $objFrom->liste_contact(-1, $source);
1221  foreach ($contacts as $contact) {
1222  if ($this->add_contact($contact['id'], $contact['fk_c_type_contact'], $contact['source']) < 0) {
1223  return -1;
1224  }
1225  }
1226  return 1;
1227  }
1228 
1229  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1239  public function update_contact($rowid, $statut, $type_contact_id = 0, $fk_socpeople = 0)
1240  {
1241  // phpcs:enable
1242  // Insert into database
1243  $sql = "UPDATE ".$this->db->prefix()."element_contact set";
1244  $sql .= " statut = ".$statut;
1245  if ($type_contact_id) {
1246  $sql .= ", fk_c_type_contact = ".((int) $type_contact_id);
1247  }
1248  if ($fk_socpeople) {
1249  $sql .= ", fk_socpeople = ".((int) $fk_socpeople);
1250  }
1251  $sql .= " where rowid = ".((int) $rowid);
1252  $resql = $this->db->query($sql);
1253  if ($resql) {
1254  return 0;
1255  } else {
1256  $this->error = $this->db->lasterror();
1257  return -1;
1258  }
1259  }
1260 
1261  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1269  public function delete_contact($rowid, $notrigger = 0)
1270  {
1271  // phpcs:enable
1272  global $user;
1273 
1274  $error = 0;
1275 
1276  $this->db->begin();
1277 
1278  if (!$error && empty($notrigger)) {
1279  // Call trigger
1280  $this->context['contact_id'] = ((int) $rowid);
1281  $result = $this->call_trigger(strtoupper($this->element).'_DELETE_CONTACT', $user);
1282  if ($result < 0) {
1283  $error++;
1284  }
1285  // End call triggers
1286  }
1287 
1288  if (!$error) {
1289  dol_syslog(get_class($this)."::delete_contact", LOG_DEBUG);
1290 
1291  $sql = "DELETE FROM ".MAIN_DB_PREFIX."element_contact";
1292  $sql .= " WHERE rowid = ".((int) $rowid);
1293 
1294  $result = $this->db->query($sql);
1295  if (!$result) {
1296  $error++;
1297  $this->errors[] = $this->db->lasterror();
1298  }
1299  }
1300 
1301  if (!$error) {
1302  $this->db->commit();
1303  return 1;
1304  } else {
1305  $this->error = $this->db->lasterror();
1306  $this->db->rollback();
1307  return -1;
1308  }
1309  }
1310 
1311  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1319  public function delete_linked_contact($source = '', $code = '')
1320  {
1321  // phpcs:enable
1322  $listId = '';
1323  $temp = array();
1324  $typeContact = $this->liste_type_contact($source, '', 0, 0, $code);
1325 
1326  if (!empty($typeContact)) {
1327  foreach ($typeContact as $key => $value) {
1328  array_push($temp, $key);
1329  }
1330  $listId = implode(",", $temp);
1331  }
1332 
1333  // If $listId is empty, we have not criteria on fk_c_type_contact so we will delete record on element_id for
1334  // any type or record instead of only the ones of the current object. So we do nothing in such a case.
1335  if (empty($listId)) {
1336  return 0;
1337  }
1338 
1339  $sql = "DELETE FROM ".$this->db->prefix()."element_contact";
1340  $sql .= " WHERE element_id = ".((int) $this->id);
1341  $sql .= " AND fk_c_type_contact IN (".$this->db->sanitize($listId).")";
1342 
1343  dol_syslog(get_class($this)."::delete_linked_contact", LOG_DEBUG);
1344  if ($this->db->query($sql)) {
1345  return 1;
1346  } else {
1347  $this->error = $this->db->lasterror();
1348  return -1;
1349  }
1350  }
1351 
1352  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1362  public function liste_contact($status = -1, $source = 'external', $list = 0, $code = '')
1363  {
1364  // phpcs:enable
1365  global $langs;
1366 
1367  $tab = array();
1368 
1369  $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
1370  if ($source == 'internal') {
1371  $sql .= ", '-1' as socid, t.statut as statuscontact, t.login, t.photo";
1372  }
1373  if ($source == 'external' || $source == 'thirdparty') {
1374  $sql .= ", t.fk_soc as socid, t.statut as statuscontact";
1375  }
1376  $sql .= ", t.civility as civility, t.lastname as lastname, t.firstname, t.email";
1377  $sql .= ", tc.source, tc.element, tc.code, tc.libelle";
1378  $sql .= " FROM ".$this->db->prefix()."c_type_contact tc";
1379  $sql .= ", ".$this->db->prefix()."element_contact ec";
1380  if ($source == 'internal') {
1381  $sql .= " LEFT JOIN ".$this->db->prefix()."user t on ec.fk_socpeople = t.rowid";
1382  }
1383  if ($source == 'external' || $source == 'thirdparty') {
1384  $sql .= " LEFT JOIN ".$this->db->prefix()."socpeople t on ec.fk_socpeople = t.rowid";
1385  }
1386  $sql .= " WHERE ec.element_id = ".((int) $this->id);
1387  $sql .= " AND ec.fk_c_type_contact = tc.rowid";
1388  $sql .= " AND tc.element = '".$this->db->escape($this->element)."'";
1389  if ($code) {
1390  $sql .= " AND tc.code = '".$this->db->escape($code)."'";
1391  }
1392  if ($source == 'internal') {
1393  $sql .= " AND tc.source = 'internal'";
1394  }
1395  if ($source == 'external' || $source == 'thirdparty') {
1396  $sql .= " AND tc.source = 'external'";
1397  }
1398  $sql .= " AND tc.active=1";
1399  if ($status >= 0) {
1400  $sql .= " AND ec.statut = ".((int) $status);
1401  }
1402  $sql .= " ORDER BY t.lastname ASC";
1403 
1404  dol_syslog(get_class($this)."::liste_contact", LOG_DEBUG);
1405  $resql = $this->db->query($sql);
1406  if ($resql) {
1407  $num = $this->db->num_rows($resql);
1408  $i = 0;
1409  while ($i < $num) {
1410  $obj = $this->db->fetch_object($resql);
1411 
1412  if (!$list) {
1413  $transkey = "TypeContact_".$obj->element."_".$obj->source."_".$obj->code;
1414  $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle);
1415  $tab[$i] = array(
1416  'source' => $obj->source,
1417  'socid' => $obj->socid,
1418  'id' => $obj->id,
1419  'nom' => $obj->lastname, // For backward compatibility
1420  'civility' => $obj->civility,
1421  'lastname' => $obj->lastname,
1422  'firstname' => $obj->firstname,
1423  'email'=>$obj->email,
1424  'login'=> (empty($obj->login) ? '' : $obj->login),
1425  'photo' => (empty($obj->photo) ? '' : $obj->photo),
1426  'statuscontact' => $obj->statuscontact,
1427  'rowid' => $obj->rowid,
1428  'code' => $obj->code,
1429  'libelle' => $libelle_type,
1430  'status' => $obj->statuslink,
1431  'fk_c_type_contact' => $obj->fk_c_type_contact
1432  );
1433  } else {
1434  $tab[$i] = $obj->id;
1435  }
1436 
1437  $i++;
1438  }
1439 
1440  return $tab;
1441  } else {
1442  $this->error = $this->db->lasterror();
1443  dol_print_error($this->db);
1444  return -1;
1445  }
1446  }
1447 
1448 
1455  public function swapContactStatus($rowid)
1456  {
1457  $sql = "SELECT ec.datecreate, ec.statut, ec.fk_socpeople, ec.fk_c_type_contact,";
1458  $sql .= " tc.code, tc.libelle";
1459  $sql .= " FROM (".$this->db->prefix()."element_contact as ec, ".$this->db->prefix()."c_type_contact as tc)";
1460  $sql .= " WHERE ec.rowid =".((int) $rowid);
1461  $sql .= " AND ec.fk_c_type_contact=tc.rowid";
1462  $sql .= " AND tc.element = '".$this->db->escape($this->element)."'";
1463 
1464  dol_syslog(get_class($this)."::swapContactStatus", LOG_DEBUG);
1465  $resql = $this->db->query($sql);
1466  if ($resql) {
1467  $obj = $this->db->fetch_object($resql);
1468  $newstatut = ($obj->statut == 4) ? 5 : 4;
1469  $result = $this->update_contact($rowid, $newstatut);
1470  $this->db->free($resql);
1471  return $result;
1472  } else {
1473  $this->error = $this->db->error();
1474  dol_print_error($this->db);
1475  return -1;
1476  }
1477  }
1478 
1479  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1490  public function liste_type_contact($source = 'internal', $order = 'position', $option = 0, $activeonly = 0, $code = '')
1491  {
1492  // phpcs:enable
1493  global $langs;
1494 
1495  if (empty($order)) {
1496  $order = 'position';
1497  }
1498  if ($order == 'position') {
1499  $order .= ',code';
1500  }
1501 
1502  $tab = array();
1503  $sql = "SELECT DISTINCT tc.rowid, tc.code, tc.libelle, tc.position";
1504  $sql .= " FROM ".$this->db->prefix()."c_type_contact as tc";
1505  $sql .= " WHERE tc.element='".$this->db->escape($this->element)."'";
1506  if ($activeonly == 1) {
1507  $sql .= " AND tc.active=1"; // only the active types
1508  }
1509  if (!empty($source) && $source != 'all') {
1510  $sql .= " AND tc.source='".$this->db->escape($source)."'";
1511  }
1512  if (!empty($code)) {
1513  $sql .= " AND tc.code='".$this->db->escape($code)."'";
1514  }
1515  $sql .= $this->db->order($order, 'ASC');
1516 
1517  //print "sql=".$sql;
1518  $resql = $this->db->query($sql);
1519  if ($resql) {
1520  $num = $this->db->num_rows($resql);
1521  $i = 0;
1522  while ($i < $num) {
1523  $obj = $this->db->fetch_object($resql);
1524 
1525  $transkey = "TypeContact_".$this->element."_".$source."_".$obj->code;
1526  $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle);
1527  if (empty($option)) {
1528  $tab[$obj->rowid] = $libelle_type;
1529  } else {
1530  $tab[$obj->code] = $libelle_type;
1531  }
1532  $i++;
1533  }
1534  return $tab;
1535  } else {
1536  $this->error = $this->db->lasterror();
1537  //dol_print_error($this->db);
1538  return null;
1539  }
1540  }
1541 
1542  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1554  public function listeTypeContacts($source = 'internal', $option = 0, $activeonly = 0, $code = '', $element = '', $excludeelement = '')
1555  {
1556  // phpcs:enable
1557  global $langs, $conf;
1558 
1559  $langs->loadLangs(array('bills', 'contracts', 'interventions', 'orders', 'projects', 'propal', 'ticket', 'agenda'));
1560 
1561  $tab = array();
1562 
1563  $sql = "SELECT DISTINCT tc.rowid, tc.code, tc.libelle, tc.position, tc.element";
1564  $sql .= " FROM ".$this->db->prefix()."c_type_contact as tc";
1565 
1566  $sqlWhere = array();
1567  if (!empty($element)) {
1568  $sqlWhere[] = " tc.element='".$this->db->escape($element)."'";
1569  }
1570  if (!empty($excludeelement)) {
1571  $sqlWhere[] = " tc.element <> '".$this->db->escape($excludeelement)."'";
1572  }
1573 
1574  if ($activeonly == 1) {
1575  $sqlWhere[] = " tc.active=1"; // only the active types
1576  }
1577 
1578  if (!empty($source) && $source != 'all') {
1579  $sqlWhere[] = " tc.source='".$this->db->escape($source)."'";
1580  }
1581 
1582  if (!empty($code)) {
1583  $sqlWhere[] = " tc.code='".$this->db->escape($code)."'";
1584  }
1585 
1586  if (count($sqlWhere) > 0) {
1587  $sql .= " WHERE ".implode(' AND ', $sqlWhere);
1588  }
1589 
1590  $sql .= $this->db->order('tc.element, tc.position', 'ASC');
1591 
1592  dol_syslog(__METHOD__, LOG_DEBUG);
1593  $resql = $this->db->query($sql);
1594  if ($resql) {
1595  $num = $this->db->num_rows($resql);
1596  if ($num > 0) {
1597  $langs->loadLangs(array("propal", "orders", "bills", "suppliers", "contracts", "supplier_proposal"));
1598 
1599  while ($obj = $this->db->fetch_object($resql)) {
1600  $modulename = $obj->element;
1601  if (strpos($obj->element, 'project') !== false) {
1602  $modulename = 'projet';
1603  } elseif ($obj->element == 'contrat') {
1604  $element = 'contract';
1605  } elseif ($obj->element == 'action') {
1606  $modulename = 'agenda';
1607  } elseif (strpos($obj->element, 'supplier') !== false && $obj->element != 'supplier_proposal') {
1608  $modulename = 'fournisseur';
1609  } elseif (strpos($obj->element, 'supplier') !== false && $obj->element != 'supplier_proposal') {
1610  $modulename = 'fournisseur';
1611  }
1612  if (!empty($conf->{$modulename}->enabled)) {
1613  $libelle_element = $langs->trans('ContactDefault_'.$obj->element);
1614  $tmpelement = $obj->element;
1615  $transkey = "TypeContact_".$tmpelement."_".$source."_".$obj->code;
1616  $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle);
1617  if (empty($option)) {
1618  $tab[$obj->rowid] = $libelle_element.' - '.$libelle_type;
1619  } else {
1620  $tab[$obj->rowid] = $libelle_element.' - '.$libelle_type;
1621  }
1622  }
1623  }
1624  }
1625  return $tab;
1626  } else {
1627  $this->error = $this->db->lasterror();
1628  return null;
1629  }
1630  }
1631 
1643  public function getIdContact($source, $code, $status = 0)
1644  {
1645  global $conf;
1646 
1647  $result = array();
1648  $i = 0;
1649  //cas particulier pour les expeditions
1650  if ($this->element == 'shipping' && $this->origin_id != 0) {
1651  $id = $this->origin_id;
1652  $element = 'commande';
1653  } elseif ($this->element == 'reception' && $this->origin_id != 0) {
1654  $id = $this->origin_id;
1655  $element = 'order_supplier';
1656  } else {
1657  $id = $this->id;
1658  $element = $this->element;
1659  }
1660 
1661  $sql = "SELECT ec.fk_socpeople";
1662  $sql .= " FROM ".$this->db->prefix()."element_contact as ec,";
1663  if ($source == 'internal') {
1664  $sql .= " ".$this->db->prefix()."user as c,";
1665  }
1666  if ($source == 'external') {
1667  $sql .= " ".$this->db->prefix()."socpeople as c,";
1668  }
1669  $sql .= " ".$this->db->prefix()."c_type_contact as tc";
1670  $sql .= " WHERE ec.element_id = ".((int) $id);
1671  $sql .= " AND ec.fk_socpeople = c.rowid";
1672  if ($source == 'internal') {
1673  $sql .= " AND c.entity IN (".getEntity('user').")";
1674  }
1675  if ($source == 'external') {
1676  $sql .= " AND c.entity IN (".getEntity('societe').")";
1677  }
1678  $sql .= " AND ec.fk_c_type_contact = tc.rowid";
1679  $sql .= " AND tc.element = '".$this->db->escape($element)."'";
1680  $sql .= " AND tc.source = '".$this->db->escape($source)."'";
1681  if ($code) {
1682  $sql .= " AND tc.code = '".$this->db->escape($code)."'";
1683  }
1684  $sql .= " AND tc.active = 1";
1685  if ($status) {
1686  $sql .= " AND ec.statut = ".((int) $status);
1687  }
1688 
1689  dol_syslog(get_class($this)."::getIdContact", LOG_DEBUG);
1690  $resql = $this->db->query($sql);
1691  if ($resql) {
1692  while ($obj = $this->db->fetch_object($resql)) {
1693  $result[$i] = $obj->fk_socpeople;
1694  $i++;
1695  }
1696  } else {
1697  $this->error = $this->db->error();
1698  return null;
1699  }
1700 
1701  return $result;
1702  }
1703 
1704  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1711  public function fetch_contact($contactid = null)
1712  {
1713  // phpcs:enable
1714  if (empty($contactid)) {
1715  $contactid = $this->contact_id;
1716  }
1717 
1718  if (empty($contactid)) {
1719  return 0;
1720  }
1721 
1722  require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
1723  $contact = new Contact($this->db);
1724  $result = $contact->fetch($contactid);
1725  $this->contact = $contact;
1726  return $result;
1727  }
1728 
1729  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1736  public function fetch_thirdparty($force_thirdparty_id = 0)
1737  {
1738  // phpcs:enable
1739  global $conf;
1740 
1741  if (empty($this->socid) && empty($this->fk_soc) && empty($force_thirdparty_id)) {
1742  return 0;
1743  }
1744 
1745  require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
1746 
1747  $idtofetch = isset($this->socid) ? $this->socid : (isset($this->fk_soc) ? $this->fk_soc : 0);
1748  if ($force_thirdparty_id) {
1749  $idtofetch = $force_thirdparty_id;
1750  }
1751 
1752  if ($idtofetch) {
1753  $thirdparty = new Societe($this->db);
1754  $result = $thirdparty->fetch($idtofetch);
1755  if ($result<0) {
1756  $this->errors=array_merge($this->errors, $thirdparty->errors);
1757  }
1758  $this->thirdparty = $thirdparty;
1759 
1760  // Use first price level if level not defined for third party
1761  if (!empty($conf->global->PRODUIT_MULTIPRICES) && empty($this->thirdparty->price_level)) {
1762  $this->thirdparty->price_level = 1;
1763  }
1764 
1765  return $result;
1766  } else {
1767  return -1;
1768  }
1769  }
1770 
1771 
1779  public function fetchOneLike($ref)
1780  {
1781  if (!$this->table_ref_field) {
1782  return 0;
1783  }
1784 
1785  $sql = "SELECT rowid FROM ".$this->db->prefix().$this->table_element." WHERE ".$this->table_ref_field." LIKE '".$this->db->escape($ref)."' LIMIT 1";
1786 
1787  $query = $this->db->query($sql);
1788 
1789  if (!$this->db->num_rows($query)) {
1790  return 0;
1791  }
1792 
1793  $result = $this->db->fetch_object($query);
1794 
1795  return $this->fetch($result->rowid);
1796  }
1797 
1798  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1806  public function fetch_barcode()
1807  {
1808  // phpcs:enable
1809  global $conf;
1810 
1811  dol_syslog(get_class($this).'::fetch_barcode this->element='.$this->element.' this->barcode_type='.$this->barcode_type);
1812 
1813  $idtype = $this->barcode_type;
1814  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
1815  if ($this->element == 'product' && !empty($conf->global->PRODUIT_DEFAULT_BARCODE_TYPE)) {
1816  $idtype = $conf->global->PRODUIT_DEFAULT_BARCODE_TYPE;
1817  } elseif ($this->element == 'societe') {
1818  $idtype = $conf->global->GENBARCODE_BARCODETYPE_THIRDPARTY;
1819  } else {
1820  dol_syslog('Call fetch_barcode with barcode_type not defined and cant be guessed', LOG_WARNING);
1821  }
1822  }
1823 
1824  if ($idtype > 0) {
1825  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
1826  $sql = "SELECT rowid, code, libelle as label, coder";
1827  $sql .= " FROM ".$this->db->prefix()."c_barcode_type";
1828  $sql .= " WHERE rowid = ".((int) $idtype);
1829  dol_syslog(get_class($this).'::fetch_barcode', LOG_DEBUG);
1830  $resql = $this->db->query($sql);
1831  if ($resql) {
1832  $obj = $this->db->fetch_object($resql);
1833  $this->barcode_type = $obj->rowid;
1834  $this->barcode_type_code = $obj->code;
1835  $this->barcode_type_label = $obj->label;
1836  $this->barcode_type_coder = $obj->coder;
1837  return 1;
1838  } else {
1839  dol_print_error($this->db);
1840  return -1;
1841  }
1842  }
1843  }
1844  return 0;
1845  }
1846 
1847  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1853  public function fetch_project()
1854  {
1855  // phpcs:enable
1856  return $this->fetch_projet();
1857  }
1858 
1859  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1865  public function fetch_projet()
1866  {
1867  // phpcs:enable
1868  include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
1869 
1870  if (empty($this->fk_project) && !empty($this->fk_projet)) {
1871  $this->fk_project = $this->fk_projet; // For backward compatibility
1872  }
1873  if (empty($this->fk_project)) {
1874  return 0;
1875  }
1876 
1877  $project = new Project($this->db);
1878  $result = $project->fetch($this->fk_project);
1879 
1880  $this->projet = $project; // deprecated
1881  $this->project = $project;
1882  return $result;
1883  }
1884 
1885  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1891  public function fetch_product()
1892  {
1893  // phpcs:enable
1894  include_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
1895 
1896  if (empty($this->fk_product)) {
1897  return 0;
1898  }
1899 
1900  $product = new Product($this->db);
1901  $result = $product->fetch($this->fk_product);
1902 
1903  $this->product = $product;
1904  return $result;
1905  }
1906 
1907  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1914  public function fetch_user($userid)
1915  {
1916  // phpcs:enable
1917  $user = new User($this->db);
1918  $result = $user->fetch($userid);
1919  $this->user = $user;
1920  return $result;
1921  }
1922 
1923  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1929  public function fetch_origin()
1930  {
1931  // phpcs:enable
1932  if ($this->origin == 'shipping') {
1933  $this->origin = 'expedition';
1934  }
1935  if ($this->origin == 'delivery') {
1936  $this->origin = 'livraison';
1937  }
1938  if ($this->origin == 'order_supplier') {
1939  $this->origin = 'commandeFournisseur';
1940  }
1941 
1942  $origin = $this->origin;
1943 
1944  $classname = ucfirst($origin);
1945  $this->$origin = new $classname($this->db);
1946  $this->$origin->fetch($this->origin_id);
1947  }
1948 
1958  public function fetchObjectFrom($table, $field, $key, $element = null)
1959  {
1960  global $conf;
1961 
1962  $result = false;
1963 
1964  $sql = "SELECT rowid FROM ".$this->db->prefix().$table;
1965  $sql .= " WHERE ".$field." = '".$this->db->escape($key)."'";
1966  if (!empty($element)) {
1967  $sql .= " AND entity IN (".getEntity($element).")";
1968  } else {
1969  $sql .= " AND entity = ".((int) $conf->entity);
1970  }
1971 
1972  dol_syslog(get_class($this).'::fetchObjectFrom', LOG_DEBUG);
1973  $resql = $this->db->query($sql);
1974  if ($resql) {
1975  $row = $this->db->fetch_row($resql);
1976  // Test for avoid error -1
1977  if ($row[0] > 0) {
1978  $result = $this->fetch($row[0]);
1979  }
1980  }
1981 
1982  return $result;
1983  }
1984 
1993  public function getValueFrom($table, $id, $field)
1994  {
1995  $result = false;
1996  if (!empty($id) && !empty($field) && !empty($table)) {
1997  $sql = "SELECT ".$field." FROM ".$this->db->prefix().$table;
1998  $sql .= " WHERE rowid = ".((int) $id);
1999 
2000  dol_syslog(get_class($this).'::getValueFrom', LOG_DEBUG);
2001  $resql = $this->db->query($sql);
2002  if ($resql) {
2003  $row = $this->db->fetch_row($resql);
2004  $result = $row[0];
2005  }
2006  }
2007  return $result;
2008  }
2009 
2026  public function setValueFrom($field, $value, $table = '', $id = null, $format = '', $id_field = '', $fuser = null, $trigkey = '', $fk_user_field = 'fk_user_modif')
2027  {
2028  global $user, $langs, $conf;
2029 
2030  if (empty($table)) {
2031  $table = $this->table_element;
2032  }
2033  if (empty($id)) {
2034  $id = $this->id;
2035  }
2036  if (empty($format)) {
2037  $format = 'text';
2038  }
2039  if (empty($id_field)) {
2040  $id_field = 'rowid';
2041  }
2042 
2043  $error = 0;
2044 
2045  $this->db->begin();
2046 
2047  // Special case
2048  if ($table == 'product' && $field == 'note_private') {
2049  $field = 'note';
2050  }
2051  if (in_array($table, array('actioncomm', 'adherent', 'advtargetemailing', 'cronjob', 'establishment'))) {
2052  $fk_user_field = 'fk_user_mod';
2053  }
2054 
2055  $sql = "UPDATE ".$this->db->prefix().$table." SET ";
2056 
2057  if ($format == 'text') {
2058  $sql .= $field." = '".$this->db->escape($value)."'";
2059  } elseif ($format == 'int') {
2060  $sql .= $field." = ".((int) $value);
2061  } elseif ($format == 'date') {
2062  $sql .= $field." = ".($value ? "'".$this->db->idate($value)."'" : "null");
2063  }
2064 
2065  if ($fk_user_field) {
2066  if (!empty($fuser) && is_object($fuser)) {
2067  $sql .= ", ".$fk_user_field." = ".((int) $fuser->id);
2068  } elseif (empty($fuser) || $fuser != 'none') {
2069  $sql .= ", ".$fk_user_field." = ".((int) $user->id);
2070  }
2071  }
2072 
2073  $sql .= " WHERE ".$id_field." = ".((int) $id);
2074 
2075  dol_syslog(__METHOD__."", LOG_DEBUG);
2076  $resql = $this->db->query($sql);
2077  if ($resql) {
2078  if ($trigkey) {
2079  // call trigger with updated object values
2080  if (empty($this->fields) && method_exists($this, 'fetch')) {
2081  $result = $this->fetch($id);
2082  } else {
2083  $result = $this->fetchCommon($id);
2084  }
2085  if ($result >= 0) {
2086  $result = $this->call_trigger($trigkey, (!empty($fuser) && is_object($fuser)) ? $fuser : $user); // This may set this->errors
2087  }
2088  if ($result < 0) {
2089  $error++;
2090  }
2091  }
2092 
2093  if (!$error) {
2094  if (property_exists($this, $field)) {
2095  $this->$field = $value;
2096  }
2097  $this->db->commit();
2098  return 1;
2099  } else {
2100  $this->db->rollback();
2101  return -2;
2102  }
2103  } else {
2104  if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
2105  $this->error = 'DB_ERROR_RECORD_ALREADY_EXISTS';
2106  } else {
2107  $this->error = $this->db->lasterror();
2108  }
2109  $this->db->rollback();
2110  return -1;
2111  }
2112  }
2113 
2114  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2123  public function load_previous_next_ref($filter, $fieldid, $nodbprefix = 0)
2124  {
2125  // phpcs:enable
2126  global $conf, $user;
2127 
2128  if (!$this->table_element) {
2129  dol_print_error('', get_class($this)."::load_previous_next_ref was called on objet with property table_element not defined");
2130  return -1;
2131  }
2132  if ($fieldid == 'none') {
2133  return 1;
2134  }
2135 
2136  // For backward compatibility
2137  if (in_array($this->table_element, array('facture_rec', 'facture_fourn_rec')) && $fieldid == 'title') {
2138  $fieldid = 'titre';
2139  }
2140 
2141  // Security on socid
2142  $socid = 0;
2143  if ($user->socid > 0) {
2144  $socid = $user->socid;
2145  }
2146 
2147  // this->ismultientitymanaged contains
2148  // 0=No test on entity, 1=Test with field entity, 'field@table'=Test with link by field@table
2149  $aliastablesociete = 's';
2150  if ($this->element == 'societe') {
2151  $aliastablesociete = 'te'; // te as table_element
2152  }
2153  $restrictiononfksoc = empty($this->restrictiononfksoc) ? 0 : $this->restrictiononfksoc;
2154  $sql = "SELECT MAX(te.".$fieldid.")";
2155  $sql .= " FROM ".(empty($nodbprefix) ?$this->db->prefix():'').$this->table_element." as te";
2156  if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
2157  $sql .= ",".$this->db->prefix()."usergroup_user as ug";
2158  }
2159  if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2160  $tmparray = explode('@', $this->ismultientitymanaged);
2161  $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
2162  } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
2163  $sql .= ", ".$this->db->prefix()."societe as s"; // If we need to link to societe to limit select to socid
2164  } elseif ($restrictiononfksoc == 2 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
2165  $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
2166  }
2167  if ($restrictiononfksoc && empty($user->rights->societe->client->voir) && !$socid) {
2168  $sql .= " LEFT JOIN ".$this->db->prefix()."societe_commerciaux as sc ON ".$aliastablesociete.".rowid = sc.fk_soc";
2169  }
2170  $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)
2171  if ($restrictiononfksoc == 1 && empty($user->rights->societe->client->voir) && !$socid) {
2172  $sql .= " AND sc.fk_user = ".((int) $user->id);
2173  }
2174  if ($restrictiononfksoc == 2 && empty($user->rights->societe->client->voir) && !$socid) {
2175  $sql .= " AND (sc.fk_user = ".((int) $user->id).' OR te.fk_soc IS NULL)';
2176  }
2177  if (!empty($filter)) {
2178  if (!preg_match('/^\s*AND/i', $filter)) {
2179  $sql .= " AND "; // For backward compatibility
2180  }
2181  $sql .= $filter;
2182  }
2183  if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2184  $tmparray = explode('@', $this->ismultientitymanaged);
2185  $sql .= " AND te.".$tmparray[0]." = ".($tmparray[1] == "societe" ? "s" : "parenttable").".rowid"; // If we need to link to this table to limit select to entity
2186  } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
2187  $sql .= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to socid
2188  }
2189  if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
2190  if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
2191  if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
2192  $sql .= " AND te.entity IS NOT NULL"; // Show all users
2193  } else {
2194  $sql .= " AND ug.fk_user = te.rowid";
2195  $sql .= " AND ug.entity IN (".getEntity('usergroup').")";
2196  }
2197  } else {
2198  $sql .= ' AND te.entity IN ('.getEntity($this->element).')';
2199  }
2200  }
2201  if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged) && $this->element != 'societe') {
2202  $tmparray = explode('@', $this->ismultientitymanaged);
2203  $sql .= ' AND parenttable.entity IN ('.getEntity($tmparray[1]).')';
2204  }
2205  if ($restrictiononfksoc == 1 && $socid && $this->element != 'societe') {
2206  $sql .= ' AND te.fk_soc = '.((int) $socid);
2207  }
2208  if ($restrictiononfksoc == 2 && $socid && $this->element != 'societe') {
2209  $sql .= ' AND (te.fk_soc = '.((int) $socid).' OR te.fk_soc IS NULL)';
2210  }
2211  if ($restrictiononfksoc && $socid && $this->element == 'societe') {
2212  $sql .= ' AND te.rowid = '.((int) $socid);
2213  }
2214  //print 'socid='.$socid.' restrictiononfksoc='.$restrictiononfksoc.' ismultientitymanaged = '.$this->ismultientitymanaged.' filter = '.$filter.' -> '.$sql."<br>";
2215 
2216  $result = $this->db->query($sql);
2217  if (!$result) {
2218  $this->error = $this->db->lasterror();
2219  return -1;
2220  }
2221  $row = $this->db->fetch_row($result);
2222  $this->ref_previous = $row[0];
2223 
2224  $sql = "SELECT MIN(te.".$fieldid.")";
2225  $sql .= " FROM ".(empty($nodbprefix) ?$this->db->prefix():'').$this->table_element." as te";
2226  if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
2227  $sql .= ",".$this->db->prefix()."usergroup_user as ug";
2228  }
2229  if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2230  $tmparray = explode('@', $this->ismultientitymanaged);
2231  $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
2232  } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
2233  $sql .= ", ".$this->db->prefix()."societe as s"; // If we need to link to societe to limit select to socid
2234  } elseif ($restrictiononfksoc == 2 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
2235  $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
2236  }
2237  if ($restrictiononfksoc && empty($user->rights->societe->client->voir) && !$socid) {
2238  $sql .= " LEFT JOIN ".$this->db->prefix()."societe_commerciaux as sc ON ".$aliastablesociete.".rowid = sc.fk_soc";
2239  }
2240  $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)
2241  if ($restrictiononfksoc == 1 && empty($user->rights->societe->client->voir) && !$socid) {
2242  $sql .= " AND sc.fk_user = ".((int) $user->id);
2243  }
2244  if ($restrictiononfksoc == 2 && empty($user->rights->societe->client->voir) && !$socid) {
2245  $sql .= " AND (sc.fk_user = ".((int) $user->id).' OR te.fk_soc IS NULL)';
2246  }
2247  if (!empty($filter)) {
2248  if (!preg_match('/^\s*AND/i', $filter)) {
2249  $sql .= " AND "; // For backward compatibility
2250  }
2251  $sql .= $filter;
2252  }
2253  if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2254  $tmparray = explode('@', $this->ismultientitymanaged);
2255  $sql .= " AND te.".$tmparray[0]." = ".($tmparray[1] == "societe" ? "s" : "parenttable").".rowid"; // If we need to link to this table to limit select to entity
2256  } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
2257  $sql .= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to socid
2258  }
2259  if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
2260  if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
2261  if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
2262  $sql .= " AND te.entity IS NOT NULL"; // Show all users
2263  } else {
2264  $sql .= " AND ug.fk_user = te.rowid";
2265  $sql .= " AND ug.entity IN (".getEntity('usergroup').")";
2266  }
2267  } else {
2268  $sql .= ' AND te.entity IN ('.getEntity($this->element).')';
2269  }
2270  }
2271  if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged) && $this->element != 'societe') {
2272  $tmparray = explode('@', $this->ismultientitymanaged);
2273  $sql .= ' AND parenttable.entity IN ('.getEntity($tmparray[1]).')';
2274  }
2275  if ($restrictiononfksoc == 1 && $socid && $this->element != 'societe') {
2276  $sql .= ' AND te.fk_soc = '.((int) $socid);
2277  }
2278  if ($restrictiononfksoc == 2 && $socid && $this->element != 'societe') {
2279  $sql .= ' AND (te.fk_soc = '.((int) $socid).' OR te.fk_soc IS NULL)';
2280  }
2281  if ($restrictiononfksoc && $socid && $this->element == 'societe') {
2282  $sql .= ' AND te.rowid = '.((int) $socid);
2283  }
2284  //print 'socid='.$socid.' restrictiononfksoc='.$restrictiononfksoc.' ismultientitymanaged = '.$this->ismultientitymanaged.' filter = '.$filter.' -> '.$sql."<br>";
2285  // 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
2286 
2287  $result = $this->db->query($sql);
2288  if (!$result) {
2289  $this->error = $this->db->lasterror();
2290  return -2;
2291  }
2292  $row = $this->db->fetch_row($result);
2293  $this->ref_next = $row[0];
2294 
2295  return 1;
2296  }
2297 
2298 
2306  public function getListContactId($source = 'external')
2307  {
2308  $contactAlreadySelected = array();
2309  $tab = $this->liste_contact(-1, $source);
2310  $num = count($tab);
2311  $i = 0;
2312  while ($i < $num) {
2313  if ($source == 'thirdparty') {
2314  $contactAlreadySelected[$i] = $tab[$i]['socid'];
2315  } else {
2316  $contactAlreadySelected[$i] = $tab[$i]['id'];
2317  }
2318  $i++;
2319  }
2320  return $contactAlreadySelected;
2321  }
2322 
2323 
2331  public function setProject($projectid, $notrigger = 0)
2332  {
2333  global $user;
2334  $error = 0;
2335 
2336  if (!$this->table_element) {
2337  dol_syslog(get_class($this)."::setProject was called on objet with property table_element not defined", LOG_ERR);
2338  return -1;
2339  }
2340 
2341  $sql = "UPDATE ".$this->db->prefix().$this->table_element;
2342  if (!empty($this->fields['fk_project'])) { // Common case
2343  if ($projectid) {
2344  $sql .= " SET fk_project = ".((int) $projectid);
2345  } else {
2346  $sql .= " SET fk_project = NULL";
2347  }
2348  $sql .= ' WHERE rowid = '.((int) $this->id);
2349  } elseif ($this->table_element == 'actioncomm') { // Special case for actioncomm
2350  if ($projectid) {
2351  $sql .= " SET fk_project = ".((int) $projectid);
2352  } else {
2353  $sql .= " SET fk_project = NULL";
2354  }
2355  $sql .= ' WHERE id = '.((int) $this->id);
2356  } else // Special case for old architecture objects
2357  {
2358  if ($projectid) {
2359  $sql .= ' SET fk_projet = '.((int) $projectid);
2360  } else {
2361  $sql .= ' SET fk_projet = NULL';
2362  }
2363  $sql .= " WHERE rowid = ".((int) $this->id);
2364  }
2365 
2366  $this->db->begin();
2367 
2368  dol_syslog(get_class($this)."::setProject", LOG_DEBUG);
2369  if ($this->db->query($sql)) {
2370  $this->fk_project = ((int) $projectid);
2371  } else {
2372  dol_print_error($this->db);
2373  $error++;
2374  }
2375 
2376  // Triggers
2377  if (!$error && !$notrigger) {
2378  // Call triggers
2379  $result = $this->call_trigger(strtoupper($this->element) . '_MODIFY', $user);
2380  if ($result < 0) {
2381  $error++;
2382  } //Do also here what you must do to rollback action if trigger fail
2383  // End call triggers
2384  }
2385 
2386  // Commit or rollback
2387  if ($error) {
2388  $this->db->rollback();
2389  return -1;
2390  } else {
2391  $this->db->commit();
2392  return 1;
2393  }
2394  }
2395 
2402  public function setPaymentMethods($id)
2403  {
2404  global $user;
2405 
2406  $error = 0; $notrigger = 0;
2407 
2408  dol_syslog(get_class($this).'::setPaymentMethods('.$id.')');
2409 
2410  if ($this->statut >= 0 || $this->element == 'societe') {
2411  // TODO uniformize field name
2412  $fieldname = 'fk_mode_reglement';
2413  if ($this->element == 'societe') {
2414  $fieldname = 'mode_reglement';
2415  }
2416  if (get_class($this) == 'Fournisseur') {
2417  $fieldname = 'mode_reglement_supplier';
2418  }
2419  if (get_class($this) == 'Tva') {
2420  $fieldname = 'fk_typepayment';
2421  }
2422  if (get_class($this) == 'Salary') {
2423  $fieldname = 'fk_typepayment';
2424  }
2425 
2426  $sql = "UPDATE ".$this->db->prefix().$this->table_element;
2427  $sql .= " SET ".$fieldname." = ".(($id > 0 || $id == '0') ? ((int) $id) : 'NULL');
2428  $sql .= ' WHERE rowid='.((int) $this->id);
2429 
2430  if ($this->db->query($sql)) {
2431  $this->mode_reglement_id = $id;
2432  // for supplier
2433  if (get_class($this) == 'Fournisseur') {
2434  $this->mode_reglement_supplier_id = $id;
2435  }
2436  // Triggers
2437  if (!$error && !$notrigger) {
2438  // Call triggers
2439  if (get_class($this) == 'Commande') {
2440  $result = $this->call_trigger('ORDER_MODIFY', $user);
2441  } else {
2442  $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $user);
2443  }
2444  if ($result < 0) {
2445  $error++;
2446  }
2447  // End call triggers
2448  }
2449  return 1;
2450  } else {
2451  dol_syslog(get_class($this).'::setPaymentMethods Error '.$this->db->error());
2452  $this->error = $this->db->error();
2453  return -1;
2454  }
2455  } else {
2456  dol_syslog(get_class($this).'::setPaymentMethods, status of the object is incompatible');
2457  $this->error = 'Status of the object is incompatible '.$this->statut;
2458  return -2;
2459  }
2460  }
2461 
2468  public function setMulticurrencyCode($code)
2469  {
2470  dol_syslog(get_class($this).'::setMulticurrencyCode('.$code.')');
2471  if ($this->statut >= 0 || $this->element == 'societe') {
2472  $fieldname = 'multicurrency_code';
2473 
2474  $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
2475  $sql .= " SET ".$fieldname." = '".$this->db->escape($code)."'";
2476  $sql .= ' WHERE rowid='.((int) $this->id);
2477 
2478  if ($this->db->query($sql)) {
2479  $this->multicurrency_code = $code;
2480 
2481  list($fk_multicurrency, $rate) = MultiCurrency::getIdAndTxFromCode($this->db, $code);
2482  if ($rate) {
2483  $this->setMulticurrencyRate($rate, 2);
2484  }
2485 
2486  return 1;
2487  } else {
2488  dol_syslog(get_class($this).'::setMulticurrencyCode Error '.$sql.' - '.$this->db->error());
2489  $this->error = $this->db->error();
2490  return -1;
2491  }
2492  } else {
2493  dol_syslog(get_class($this).'::setMulticurrencyCode, status of the object is incompatible');
2494  $this->error = 'Status of the object is incompatible '.$this->statut;
2495  return -2;
2496  }
2497  }
2498 
2506  public function setMulticurrencyRate($rate, $mode = 1)
2507  {
2508  dol_syslog(get_class($this).'::setMulticurrencyRate('.$rate.','.$mode.')');
2509  if ($this->statut >= 0 || $this->element == 'societe') {
2510  $fieldname = 'multicurrency_tx';
2511 
2512  $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
2513  $sql .= " SET ".$fieldname." = ".((float) $rate);
2514  $sql .= ' WHERE rowid='.((int) $this->id);
2515 
2516  if ($this->db->query($sql)) {
2517  $this->multicurrency_tx = $rate;
2518 
2519  // Update line price
2520  if (!empty($this->lines)) {
2521  foreach ($this->lines as &$line) {
2522  // Amounts in company currency will be recalculated
2523  if ($mode == 1) {
2524  $line->subprice = 0;
2525  }
2526 
2527  // Amounts in foreign currency will be recalculated
2528  if ($mode == 2) {
2529  $line->multicurrency_subprice = 0;
2530  }
2531 
2532  switch ($this->element) {
2533  case 'propal':
2534  $this->updateline(
2535  $line->id,
2536  $line->subprice,
2537  $line->qty,
2538  $line->remise_percent,
2539  $line->tva_tx,
2540  $line->localtax1_tx,
2541  $line->localtax2_tx,
2542  ($line->description ? $line->description : $line->desc),
2543  'HT',
2544  $line->info_bits,
2545  $line->special_code,
2546  $line->fk_parent_line,
2547  $line->skip_update_total,
2548  $line->fk_fournprice,
2549  $line->pa_ht,
2550  $line->label,
2551  $line->product_type,
2552  $line->date_start,
2553  $line->date_end,
2554  $line->array_options,
2555  $line->fk_unit,
2556  $line->multicurrency_subprice
2557  );
2558  break;
2559  case 'commande':
2560  $this->updateline(
2561  $line->id,
2562  ($line->description ? $line->description : $line->desc),
2563  $line->subprice,
2564  $line->qty,
2565  $line->remise_percent,
2566  $line->tva_tx,
2567  $line->localtax1_tx,
2568  $line->localtax2_tx,
2569  'HT',
2570  $line->info_bits,
2571  $line->date_start,
2572  $line->date_end,
2573  $line->product_type,
2574  $line->fk_parent_line,
2575  $line->skip_update_total,
2576  $line->fk_fournprice,
2577  $line->pa_ht,
2578  $line->label,
2579  $line->special_code,
2580  $line->array_options,
2581  $line->fk_unit,
2582  $line->multicurrency_subprice
2583  );
2584  break;
2585  case 'facture':
2586  $this->updateline(
2587  $line->id,
2588  ($line->description ? $line->description : $line->desc),
2589  $line->subprice,
2590  $line->qty,
2591  $line->remise_percent,
2592  $line->date_start,
2593  $line->date_end,
2594  $line->tva_tx,
2595  $line->localtax1_tx,
2596  $line->localtax2_tx,
2597  'HT',
2598  $line->info_bits,
2599  $line->product_type,
2600  $line->fk_parent_line,
2601  $line->skip_update_total,
2602  $line->fk_fournprice,
2603  $line->pa_ht,
2604  $line->label,
2605  $line->special_code,
2606  $line->array_options,
2607  $line->situation_percent,
2608  $line->fk_unit,
2609  $line->multicurrency_subprice
2610  );
2611  break;
2612  case 'supplier_proposal':
2613  $this->updateline(
2614  $line->id,
2615  $line->subprice,
2616  $line->qty,
2617  $line->remise_percent,
2618  $line->tva_tx,
2619  $line->localtax1_tx,
2620  $line->localtax2_tx,
2621  ($line->description ? $line->description : $line->desc),
2622  'HT',
2623  $line->info_bits,
2624  $line->special_code,
2625  $line->fk_parent_line,
2626  $line->skip_update_total,
2627  $line->fk_fournprice,
2628  $line->pa_ht,
2629  $line->label,
2630  $line->product_type,
2631  $line->array_options,
2632  $line->ref_fourn,
2633  $line->multicurrency_subprice
2634  );
2635  break;
2636  case 'order_supplier':
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->tva_tx,
2644  $line->localtax1_tx,
2645  $line->localtax2_tx,
2646  'HT',
2647  $line->info_bits,
2648  $line->product_type,
2649  false,
2650  $line->date_start,
2651  $line->date_end,
2652  $line->array_options,
2653  $line->fk_unit,
2654  $line->multicurrency_subprice,
2655  $line->ref_supplier
2656  );
2657  break;
2658  case 'invoice_supplier':
2659  $this->updateline(
2660  $line->id,
2661  ($line->description ? $line->description : $line->desc),
2662  $line->subprice,
2663  $line->tva_tx,
2664  $line->localtax1_tx,
2665  $line->localtax2_tx,
2666  $line->qty,
2667  0,
2668  'HT',
2669  $line->info_bits,
2670  $line->product_type,
2671  $line->remise_percent,
2672  false,
2673  $line->date_start,
2674  $line->date_end,
2675  $line->array_options,
2676  $line->fk_unit,
2677  $line->multicurrency_subprice,
2678  $line->ref_supplier
2679  );
2680  break;
2681  default:
2682  dol_syslog(get_class($this).'::setMulticurrencyRate no updateline defined', LOG_DEBUG);
2683  break;
2684  }
2685  }
2686  }
2687 
2688  return 1;
2689  } else {
2690  dol_syslog(get_class($this).'::setMulticurrencyRate Error '.$sql.' - '.$this->db->error());
2691  $this->error = $this->db->error();
2692  return -1;
2693  }
2694  } else {
2695  dol_syslog(get_class($this).'::setMulticurrencyRate, status of the object is incompatible');
2696  $this->error = 'Status of the object is incompatible '.$this->statut;
2697  return -2;
2698  }
2699  }
2700 
2708  public function setPaymentTerms($id, $deposit_percent = null)
2709  {
2710  dol_syslog(get_class($this).'::setPaymentTerms('.$id.', '.var_export($deposit_percent, true).')');
2711  if ($this->statut >= 0 || $this->element == 'societe') {
2712  // TODO uniformize field name
2713  $fieldname = 'fk_cond_reglement';
2714  if ($this->element == 'societe') {
2715  $fieldname = 'cond_reglement';
2716  }
2717  if (get_class($this) == 'Fournisseur') {
2718  $fieldname = 'cond_reglement_supplier';
2719  }
2720 
2721  if (empty($deposit_percent) || $deposit_percent < 0) {
2722  $deposit_percent = getDictionaryValue('c_payment_term', 'deposit_percent', $id);
2723  }
2724 
2725  if ($deposit_percent > 100) {
2726  $deposit_percent = 100;
2727  }
2728 
2729  $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
2730  $sql .= " SET ".$fieldname." = ".(($id > 0 || $id == '0') ? ((int) $id) : 'NULL');
2731  if (in_array($this->table_element, array('propal', 'commande'))) {
2732  $sql .= " , deposit_percent = " . (empty($deposit_percent) ? 'NULL' : "'".$this->db->escape($deposit_percent)."'");
2733  }
2734  $sql .= ' WHERE rowid='.((int) $this->id);
2735 
2736  if ($this->db->query($sql)) {
2737  $this->cond_reglement_id = $id;
2738  // for supplier
2739  if (get_class($this) == 'Fournisseur') {
2740  $this->cond_reglement_supplier_id = $id;
2741  }
2742  $this->cond_reglement = $id; // for compatibility
2743  $this->deposit_percent = $deposit_percent;
2744  return 1;
2745  } else {
2746  dol_syslog(get_class($this).'::setPaymentTerms Error '.$sql.' - '.$this->db->error());
2747  $this->error = $this->db->error();
2748  return -1;
2749  }
2750  } else {
2751  dol_syslog(get_class($this).'::setPaymentTerms, status of the object is incompatible');
2752  $this->error = 'Status of the object is incompatible '.$this->statut;
2753  return -2;
2754  }
2755  }
2756 
2763  public function setTransportMode($id)
2764  {
2765  dol_syslog(get_class($this).'::setTransportMode('.$id.')');
2766  if ($this->statut >= 0 || $this->element == 'societe') {
2767  $fieldname = 'fk_transport_mode';
2768  if ($this->element == 'societe') {
2769  $fieldname = 'transport_mode';
2770  }
2771  if (get_class($this) == 'Fournisseur') {
2772  $fieldname = 'transport_mode_supplier';
2773  }
2774 
2775  $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
2776  $sql .= " SET ".$fieldname." = ".(($id > 0 || $id == '0') ? ((int) $id) : 'NULL');
2777  $sql .= ' WHERE rowid='.((int) $this->id);
2778 
2779  if ($this->db->query($sql)) {
2780  $this->transport_mode_id = $id;
2781  // for supplier
2782  if (get_class($this) == 'Fournisseur') {
2783  $this->transport_mode_supplier_id = $id;
2784  }
2785  return 1;
2786  } else {
2787  dol_syslog(get_class($this).'::setTransportMode Error '.$sql.' - '.$this->db->error());
2788  $this->error = $this->db->error();
2789  return -1;
2790  }
2791  } else {
2792  dol_syslog(get_class($this).'::setTransportMode, status of the object is incompatible');
2793  $this->error = 'Status of the object is incompatible '.$this->statut;
2794  return -2;
2795  }
2796  }
2797 
2804  public function setRetainedWarrantyPaymentTerms($id)
2805  {
2806  dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms('.$id.')');
2807  if ($this->statut >= 0 || $this->element == 'societe') {
2808  $fieldname = 'retained_warranty_fk_cond_reglement';
2809 
2810  $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
2811  $sql .= " SET ".$fieldname." = ".((int) $id);
2812  $sql .= ' WHERE rowid='.((int) $this->id);
2813 
2814  if ($this->db->query($sql)) {
2815  $this->retained_warranty_fk_cond_reglement = $id;
2816  return 1;
2817  } else {
2818  dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms Error '.$sql.' - '.$this->db->error());
2819  $this->error = $this->db->error();
2820  return -1;
2821  }
2822  } else {
2823  dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms, status of the object is incompatible');
2824  $this->error = 'Status of the object is incompatible '.$this->statut;
2825  return -2;
2826  }
2827  }
2828 
2836  public function setDeliveryAddress($id)
2837  {
2838  $fieldname = 'fk_delivery_address';
2839  if ($this->element == 'delivery' || $this->element == 'shipping') {
2840  $fieldname = 'fk_address';
2841  }
2842 
2843  $sql = "UPDATE ".$this->db->prefix().$this->table_element." SET ".$fieldname." = ".((int) $id);
2844  $sql .= " WHERE rowid = ".((int) $this->id)." AND fk_statut = 0";
2845 
2846  if ($this->db->query($sql)) {
2847  $this->fk_delivery_address = $id;
2848  return 1;
2849  } else {
2850  $this->error = $this->db->error();
2851  dol_syslog(get_class($this).'::setDeliveryAddress Error '.$this->error);
2852  return -1;
2853  }
2854  }
2855 
2856 
2866  public function setShippingMethod($shipping_method_id, $notrigger = false, $userused = null)
2867  {
2868  global $user;
2869 
2870  if (empty($userused)) {
2871  $userused = $user;
2872  }
2873 
2874  $error = 0;
2875 
2876  if (!$this->table_element) {
2877  dol_syslog(get_class($this)."::setShippingMethod was called on objet with property table_element not defined", LOG_ERR);
2878  return -1;
2879  }
2880 
2881  $this->db->begin();
2882 
2883  if ($shipping_method_id < 0) {
2884  $shipping_method_id = 'NULL';
2885  }
2886  dol_syslog(get_class($this).'::setShippingMethod('.$shipping_method_id.')');
2887 
2888  $sql = "UPDATE ".$this->db->prefix().$this->table_element;
2889  $sql .= " SET fk_shipping_method = ".((int) $shipping_method_id);
2890  $sql .= " WHERE rowid=".((int) $this->id);
2891  $resql = $this->db->query($sql);
2892  if (!$resql) {
2893  dol_syslog(get_class($this).'::setShippingMethod Error ', LOG_DEBUG);
2894  $this->error = $this->db->lasterror();
2895  $error++;
2896  } else {
2897  if (!$notrigger) {
2898  // Call trigger
2899  $this->context = array('shippingmethodupdate'=>1);
2900  $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $userused);
2901  if ($result < 0) {
2902  $error++;
2903  }
2904  // End call trigger
2905  }
2906  }
2907  if ($error) {
2908  $this->db->rollback();
2909  return -1;
2910  } else {
2911  $this->shipping_method_id = ($shipping_method_id == 'NULL') ?null:$shipping_method_id;
2912  $this->db->commit();
2913  return 1;
2914  }
2915  }
2916 
2917 
2924  public function setWarehouse($warehouse_id)
2925  {
2926  if (!$this->table_element) {
2927  dol_syslog(get_class($this)."::setWarehouse was called on objet with property table_element not defined", LOG_ERR);
2928  return -1;
2929  }
2930  if ($warehouse_id < 0) {
2931  $warehouse_id = 'NULL';
2932  }
2933  dol_syslog(get_class($this).'::setWarehouse('.$warehouse_id.')');
2934 
2935  $sql = "UPDATE ".$this->db->prefix().$this->table_element;
2936  $sql .= " SET fk_warehouse = ".((int) $warehouse_id);
2937  $sql .= " WHERE rowid=".((int) $this->id);
2938 
2939  if ($this->db->query($sql)) {
2940  $this->warehouse_id = ($warehouse_id == 'NULL') ?null:$warehouse_id;
2941  return 1;
2942  } else {
2943  dol_syslog(get_class($this).'::setWarehouse Error ', LOG_DEBUG);
2944  $this->error = $this->db->error();
2945  return 0;
2946  }
2947  }
2948 
2949 
2957  public function setDocModel($user, $modelpdf)
2958  {
2959  if (!$this->table_element) {
2960  dol_syslog(get_class($this)."::setDocModel was called on objet with property table_element not defined", LOG_ERR);
2961  return -1;
2962  }
2963 
2964  $newmodelpdf = dol_trunc($modelpdf, 255);
2965 
2966  $sql = "UPDATE ".$this->db->prefix().$this->table_element;
2967  $sql .= " SET model_pdf = '".$this->db->escape($newmodelpdf)."'";
2968  $sql .= " WHERE rowid = ".((int) $this->id);
2969 
2970  dol_syslog(get_class($this)."::setDocModel", LOG_DEBUG);
2971  $resql = $this->db->query($sql);
2972  if ($resql) {
2973  $this->model_pdf = $modelpdf;
2974  $this->modelpdf = $modelpdf; // For bakward compatibility
2975  return 1;
2976  } else {
2977  dol_print_error($this->db);
2978  return 0;
2979  }
2980  }
2981 
2982 
2991  public function setBankAccount($fk_account, $notrigger = false, $userused = null)
2992  {
2993  global $user;
2994 
2995  if (empty($userused)) {
2996  $userused = $user;
2997  }
2998 
2999  $error = 0;
3000 
3001  if (!$this->table_element) {
3002  dol_syslog(get_class($this)."::setBankAccount was called on objet with property table_element not defined", LOG_ERR);
3003  return -1;
3004  }
3005  $this->db->begin();
3006 
3007  if ($fk_account < 0) {
3008  $fk_account = 'NULL';
3009  }
3010  dol_syslog(get_class($this).'::setBankAccount('.$fk_account.')');
3011 
3012  $sql = "UPDATE ".$this->db->prefix().$this->table_element;
3013  $sql .= " SET fk_account = ".((int) $fk_account);
3014  $sql .= " WHERE rowid=".((int) $this->id);
3015 
3016  $resql = $this->db->query($sql);
3017  if (!$resql) {
3018  dol_syslog(get_class($this).'::setBankAccount Error '.$sql.' - '.$this->db->error());
3019  $this->error = $this->db->lasterror();
3020  $error++;
3021  } else {
3022  if (!$notrigger) {
3023  // Call trigger
3024  $this->context = array('bankaccountupdate'=>1);
3025  $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $userused);
3026  if ($result < 0) {
3027  $error++;
3028  }
3029  // End call trigger
3030  }
3031  }
3032  if ($error) {
3033  $this->db->rollback();
3034  return -1;
3035  } else {
3036  $this->fk_account = ($fk_account == 'NULL') ?null:$fk_account;
3037  $this->db->commit();
3038  return 1;
3039  }
3040  }
3041 
3042 
3043  // TODO: Move line related operations to CommonObjectLine?
3044 
3045  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3055  public function line_order($renum = false, $rowidorder = 'ASC', $fk_parent_line = true)
3056  {
3057  // phpcs:enable
3058  if (!$this->table_element_line) {
3059  dol_syslog(get_class($this)."::line_order was called on objet with property table_element_line not defined", LOG_ERR);
3060  return -1;
3061  }
3062  if (!$this->fk_element) {
3063  dol_syslog(get_class($this)."::line_order was called on objet with property fk_element not defined", LOG_ERR);
3064  return -1;
3065  }
3066 
3067  $fieldposition = 'rang'; // @todo Rename 'rang' into 'position'
3068  if (in_array($this->table_element_line, array('bom_bomline', 'ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
3069  $fieldposition = 'position';
3070  }
3071 
3072  // Count number of lines to reorder (according to choice $renum)
3073  $nl = 0;
3074  $sql = "SELECT count(rowid) FROM ".$this->db->prefix().$this->table_element_line;
3075  $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
3076  if (!$renum) {
3077  $sql .= " AND " . $fieldposition . " = 0";
3078  }
3079  if ($renum) {
3080  $sql .= " AND " . $fieldposition . " <> 0";
3081  }
3082 
3083  dol_syslog(get_class($this)."::line_order", LOG_DEBUG);
3084  $resql = $this->db->query($sql);
3085  if ($resql) {
3086  $row = $this->db->fetch_row($resql);
3087  $nl = $row[0];
3088  } else {
3089  dol_print_error($this->db);
3090  }
3091  if ($nl > 0) {
3092  // The goal of this part is to reorder all lines, with all children lines sharing the same counter that parents.
3093  $rows = array();
3094 
3095  // We first search all lines that are parent lines (for multilevel details lines)
3096  $sql = "SELECT rowid FROM ".$this->db->prefix().$this->table_element_line;
3097  $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
3098  if ($fk_parent_line) {
3099  $sql .= ' AND fk_parent_line IS NULL';
3100  }
3101  $sql .= " ORDER BY " . $fieldposition . " ASC, rowid " . $rowidorder;
3102 
3103  dol_syslog(get_class($this)."::line_order search all parent lines", LOG_DEBUG);
3104  $resql = $this->db->query($sql);
3105  if ($resql) {
3106  $i = 0;
3107  $num = $this->db->num_rows($resql);
3108  while ($i < $num) {
3109  $row = $this->db->fetch_row($resql);
3110  $rows[] = $row[0]; // Add parent line into array rows
3111  $childrens = $this->getChildrenOfLine($row[0]);
3112  if (!empty($childrens)) {
3113  foreach ($childrens as $child) {
3114  array_push($rows, $child);
3115  }
3116  }
3117  $i++;
3118  }
3119 
3120  // Now we set a new number for each lines (parent and children with children included into parent tree)
3121  if (!empty($rows)) {
3122  foreach ($rows as $key => $row) {
3123  $this->updateRangOfLine($row, ($key + 1));
3124  }
3125  }
3126  } else {
3127  dol_print_error($this->db);
3128  }
3129  }
3130  return 1;
3131  }
3132 
3140  public function getChildrenOfLine($id, $includealltree = 0)
3141  {
3142  $fieldposition = 'rang'; // @todo Rename 'rang' into 'position'
3143  if (in_array($this->table_element_line, array('bom_bomline', 'ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
3144  $fieldposition = 'position';
3145  }
3146 
3147  $rows = array();
3148 
3149  $sql = "SELECT rowid FROM ".$this->db->prefix().$this->table_element_line;
3150  $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
3151  $sql .= ' AND fk_parent_line = '.((int) $id);
3152  $sql .= " ORDER BY " . $fieldposition . " ASC";
3153 
3154  dol_syslog(get_class($this)."::getChildrenOfLine search children lines for line ".$id, LOG_DEBUG);
3155  $resql = $this->db->query($sql);
3156  if ($resql) {
3157  if ($this->db->num_rows($resql) > 0) {
3158  while ($row = $this->db->fetch_row($resql)) {
3159  $rows[] = $row[0];
3160  if (!empty($includealltree)) {
3161  $rows = array_merge($rows, $this->getChildrenOfLine($row[0]), $includealltree);
3162  }
3163  }
3164  }
3165  }
3166  return $rows;
3167  }
3168 
3169  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3177  public function line_up($rowid, $fk_parent_line = true)
3178  {
3179  // phpcs:enable
3180  $this->line_order(false, 'ASC', $fk_parent_line);
3181 
3182  // Get rang of line
3183  $rang = $this->getRangOfLine($rowid);
3184 
3185  // Update position of line
3186  $this->updateLineUp($rowid, $rang);
3187  }
3188 
3189  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3197  public function line_down($rowid, $fk_parent_line = true)
3198  {
3199  // phpcs:enable
3200  $this->line_order(false, 'ASC', $fk_parent_line);
3201 
3202  // Get rang of line
3203  $rang = $this->getRangOfLine($rowid);
3204 
3205  // Get max value for rang
3206  $max = $this->line_max();
3207 
3208  // Update position of line
3209  $this->updateLineDown($rowid, $rang, $max);
3210  }
3211 
3219  public function updateRangOfLine($rowid, $rang)
3220  {
3221  global $hookmanager;
3222  $fieldposition = 'rang'; // @todo Rename 'rang' into 'position'
3223  if (in_array($this->table_element_line, array('bom_bomline', 'ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
3224  $fieldposition = 'position';
3225  }
3226 
3227  $sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldposition." = ".((int) $rang);
3228  $sql .= ' WHERE rowid = '.((int) $rowid);
3229 
3230  dol_syslog(get_class($this)."::updateRangOfLine", LOG_DEBUG);
3231  if (!$this->db->query($sql)) {
3232  dol_print_error($this->db);
3233  return -1;
3234  } else {
3235  $parameters=array('rowid'=>$rowid, 'rang'=>$rang, 'fieldposition' => $fieldposition);
3236  $action='';
3237  $reshook = $hookmanager->executeHooks('afterRankOfLineUpdate', $parameters, $this, $action);
3238  return 1;
3239  }
3240  }
3241 
3242  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3249  public function line_ajaxorder($rows)
3250  {
3251  // phpcs:enable
3252  $num = count($rows);
3253  for ($i = 0; $i < $num; $i++) {
3254  $this->updateRangOfLine($rows[$i], ($i + 1));
3255  }
3256  }
3257 
3265  public function updateLineUp($rowid, $rang)
3266  {
3267  if ($rang > 1) {
3268  $fieldposition = 'rang';
3269  if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
3270  $fieldposition = 'position';
3271  }
3272 
3273  $sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldposition." = ".((int) $rang);
3274  $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
3275  $sql .= " AND " . $fieldposition . " = " . ((int) ($rang - 1));
3276  if ($this->db->query($sql)) {
3277  $sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldposition." = ".((int) ($rang - 1));
3278  $sql .= ' WHERE rowid = '.((int) $rowid);
3279  if (!$this->db->query($sql)) {
3280  dol_print_error($this->db);
3281  }
3282  } else {
3283  dol_print_error($this->db);
3284  }
3285  }
3286  }
3287 
3296  public function updateLineDown($rowid, $rang, $max)
3297  {
3298  if ($rang < $max) {
3299  $fieldposition = 'rang';
3300  if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
3301  $fieldposition = 'position';
3302  }
3303 
3304  $sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldposition." = ".((int) $rang);
3305  $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
3306  $sql .= " AND " . $fieldposition . " = " . ((int) ($rang + 1));
3307  if ($this->db->query($sql)) {
3308  $sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldposition." = ".((int) ($rang + 1));
3309  $sql .= ' WHERE rowid = '.((int) $rowid);
3310  if (!$this->db->query($sql)) {
3311  dol_print_error($this->db);
3312  }
3313  } else {
3314  dol_print_error($this->db);
3315  }
3316  }
3317  }
3318 
3325  public function getRangOfLine($rowid)
3326  {
3327  $fieldposition = 'rang';
3328  if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
3329  $fieldposition = 'position';
3330  }
3331 
3332  $sql = "SELECT " . $fieldposition . " FROM ".$this->db->prefix().$this->table_element_line;
3333  $sql .= " WHERE rowid = ".((int) $rowid);
3334 
3335  dol_syslog(get_class($this)."::getRangOfLine", LOG_DEBUG);
3336  $resql = $this->db->query($sql);
3337  if ($resql) {
3338  $row = $this->db->fetch_row($resql);
3339  return $row[0];
3340  }
3341  }
3342 
3349  public function getIdOfLine($rang)
3350  {
3351  $fieldposition = 'rang';
3352  if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
3353  $fieldposition = 'position';
3354  }
3355 
3356  $sql = "SELECT rowid FROM ".$this->db->prefix().$this->table_element_line;
3357  $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
3358  $sql .= " AND " . $fieldposition . " = ".((int) $rang);
3359  $resql = $this->db->query($sql);
3360  if ($resql) {
3361  $row = $this->db->fetch_row($resql);
3362  return $row[0];
3363  }
3364  }
3365 
3366  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3373  public function line_max($fk_parent_line = 0)
3374  {
3375  // phpcs:enable
3376  $positionfield = 'rang';
3377  if (in_array($this->table_element, array('bom_bom', 'product_attribute'))) {
3378  $positionfield = 'position';
3379  }
3380 
3381  // Search the last rang with fk_parent_line
3382  if ($fk_parent_line) {
3383  $sql = "SELECT max(".$positionfield.") FROM ".$this->db->prefix().$this->table_element_line;
3384  $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
3385  $sql .= " AND fk_parent_line = ".((int) $fk_parent_line);
3386 
3387  dol_syslog(get_class($this)."::line_max", LOG_DEBUG);
3388  $resql = $this->db->query($sql);
3389  if ($resql) {
3390  $row = $this->db->fetch_row($resql);
3391  if (!empty($row[0])) {
3392  return $row[0];
3393  } else {
3394  return $this->getRangOfLine($fk_parent_line);
3395  }
3396  }
3397  } else {
3398  // If not, search the last rang of element
3399  $sql = "SELECT max(".$positionfield.") FROM ".$this->db->prefix().$this->table_element_line;
3400  $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
3401 
3402  dol_syslog(get_class($this)."::line_max", LOG_DEBUG);
3403  $resql = $this->db->query($sql);
3404  if ($resql) {
3405  $row = $this->db->fetch_row($resql);
3406  return $row[0];
3407  }
3408  }
3409  }
3410 
3411  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3418  public function update_ref_ext($ref_ext)
3419  {
3420  // phpcs:enable
3421  if (!$this->table_element) {
3422  dol_syslog(get_class($this)."::update_ref_ext was called on objet with property table_element not defined", LOG_ERR);
3423  return -1;
3424  }
3425 
3426  $sql = "UPDATE ".$this->db->prefix().$this->table_element;
3427  $sql .= " SET ref_ext = '".$this->db->escape($ref_ext)."'";
3428  $sql .= " WHERE ".(isset($this->table_rowid) ? $this->table_rowid : 'rowid')." = ".((int) $this->id);
3429 
3430  dol_syslog(get_class($this)."::update_ref_ext", LOG_DEBUG);
3431  if ($this->db->query($sql)) {
3432  $this->ref_ext = $ref_ext;
3433  return 1;
3434  } else {
3435  $this->error = $this->db->error();
3436  return -1;
3437  }
3438  }
3439 
3440  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3448  public function update_note($note, $suffix = '')
3449  {
3450  // phpcs:enable
3451  global $user;
3452 
3453  if (!$this->table_element) {
3454  $this->error = 'update_note was called on objet with property table_element not defined';
3455  dol_syslog(get_class($this)."::update_note was called on objet with property table_element not defined", LOG_ERR);
3456  return -1;
3457  }
3458  if (!in_array($suffix, array('', '_public', '_private'))) {
3459  $this->error = 'update_note Parameter suffix must be empty, \'_private\' or \'_public\'';
3460  dol_syslog(get_class($this)."::update_note Parameter suffix must be empty, '_private' or '_public'", LOG_ERR);
3461  return -2;
3462  }
3463 
3464  $newsuffix = $suffix;
3465 
3466  // Special cas
3467  if ($this->table_element == 'product' && $newsuffix == '_private') {
3468  $newsuffix = '';
3469  }
3470  if (in_array($this->table_element, array('actioncomm', 'adherent', 'advtargetemailing', 'cronjob', 'establishment'))) {
3471  $fieldusermod = "fk_user_mod";
3472  } elseif ($this->table_element == 'ecm_files') {
3473  $fieldusermod = "fk_user_m";
3474  } else {
3475  $fieldusermod = "fk_user_modif";
3476  }
3477  $sql = "UPDATE ".$this->db->prefix().$this->table_element;
3478  $sql .= " SET note".$newsuffix." = ".(!empty($note) ? ("'".$this->db->escape($note)."'") : "NULL");
3479  $sql .= ", ".$fieldusermod." = ".((int) $user->id);
3480  $sql .= " WHERE rowid = ".((int) $this->id);
3481 
3482  dol_syslog(get_class($this)."::update_note", LOG_DEBUG);
3483  if ($this->db->query($sql)) {
3484  if ($suffix == '_public') {
3485  $this->note_public = $note;
3486  } elseif ($suffix == '_private') {
3487  $this->note_private = $note;
3488  } else {
3489  $this->note = $note; // deprecated
3490  $this->note_private = $note;
3491  }
3492  return 1;
3493  } else {
3494  $this->error = $this->db->lasterror();
3495  return -1;
3496  }
3497  }
3498 
3499  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3508  public function update_note_public($note)
3509  {
3510  // phpcs:enable
3511  return $this->update_note($note, '_public');
3512  }
3513 
3514  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3525  public function update_price($exclspec = 0, $roundingadjust = 'none', $nodatabaseupdate = 0, $seller = null)
3526  {
3527  // phpcs:enable
3528  global $conf, $hookmanager, $action;
3529 
3530  $parameters = array('exclspec' => $exclspec, 'roundingadjust' => $roundingadjust, 'nodatabaseupdate' => $nodatabaseupdate, 'seller' => $seller);
3531  $reshook = $hookmanager->executeHooks('updateTotalPrice', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
3532  if ($reshook > 0) {
3533  return 1; // replacement code
3534  } elseif ($reshook < 0) {
3535  return -1; // failure
3536  } // reshook = 0 => execute normal code
3537 
3538  // Some external module want no update price after a trigger because they have another method to calculate the total (ex: with an extrafield)
3539  $MODULE = "";
3540  if ($this->element == 'propal') {
3541  $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_PROPOSAL";
3542  } elseif ($this->element == 'commande' || $this->element == 'order') {
3543  $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_ORDER";
3544  } elseif ($this->element == 'facture' || $this->element == 'invoice') {
3545  $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_INVOICE";
3546  } elseif ($this->element == 'facture_fourn' || $this->element == 'supplier_invoice' || $this->element == 'invoice_supplier' || $this->element == 'invoice_supplier_rec') {
3547  $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_INVOICE";
3548  } elseif ($this->element == 'order_supplier' || $this->element == 'supplier_order') {
3549  $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_ORDER";
3550  } elseif ($this->element == 'supplier_proposal') {
3551  $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_PROPOSAL";
3552  }
3553 
3554  if (!empty($MODULE)) {
3555  if (!empty($conf->global->$MODULE)) {
3556  $modsactivated = explode(',', $conf->global->$MODULE);
3557  foreach ($modsactivated as $mod) {
3558  if ($conf->$mod->enabled) {
3559  return 1; // update was disabled by specific setup
3560  }
3561  }
3562  }
3563  }
3564 
3565  include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
3566 
3567  if ($roundingadjust == '-1') {
3568  $roundingadjust = 'auto'; // For backward compatibility
3569  }
3570 
3571  $forcedroundingmode = $roundingadjust;
3572  if ($forcedroundingmode == 'auto' && isset($conf->global->MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND)) {
3573  $forcedroundingmode = getDolGlobalString('MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND');
3574  } elseif ($forcedroundingmode == 'auto') {
3575  $forcedroundingmode = '0';
3576  }
3577 
3578  $error = 0;
3579 
3580  $multicurrency_tx = !empty($this->multicurrency_tx) ? $this->multicurrency_tx : 1;
3581 
3582  // Define constants to find lines to sum
3583  $fieldtva = 'total_tva';
3584  $fieldlocaltax1 = 'total_localtax1';
3585  $fieldlocaltax2 = 'total_localtax2';
3586  $fieldup = 'subprice';
3587  if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier') {
3588  $fieldtva = 'tva';
3589  $fieldup = 'pu_ht';
3590  }
3591  if ($this->element == 'invoice_supplier_rec') {
3592  $fieldup = 'pu_ht';
3593  }
3594  if ($this->element == 'expensereport') {
3595  $fieldup = 'value_unit';
3596  }
3597 
3598  $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,";
3599  $sql .= ' tva_tx as vatrate, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type, info_bits, product_type';
3600  if ($this->table_element_line == 'facturedet') {
3601  $sql .= ', situation_percent';
3602  }
3603  $sql .= ', multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc';
3604  $sql .= " FROM ".$this->db->prefix().$this->table_element_line;
3605  $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
3606  if ($exclspec) {
3607  $product_field = 'product_type';
3608  if ($this->table_element_line == 'contratdet') {
3609  $product_field = ''; // contratdet table has no product_type field
3610  }
3611  if ($product_field) {
3612  $sql .= " AND ".$product_field." <> 9";
3613  }
3614  }
3615  $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
3616 
3617  dol_syslog(get_class($this)."::update_price", LOG_DEBUG);
3618  $resql = $this->db->query($sql);
3619  if ($resql) {
3620  $this->total_ht = 0;
3621  $this->total_tva = 0;
3622  $this->total_localtax1 = 0;
3623  $this->total_localtax2 = 0;
3624  $this->total_ttc = 0;
3625  $total_ht_by_vats = array();
3626  $total_tva_by_vats = array();
3627  $total_ttc_by_vats = array();
3628  $this->multicurrency_total_ht = 0;
3629  $this->multicurrency_total_tva = 0;
3630  $this->multicurrency_total_ttc = 0;
3631 
3632  $num = $this->db->num_rows($resql);
3633  $i = 0;
3634  while ($i < $num) {
3635  $obj = $this->db->fetch_object($resql);
3636 
3637  // Note: There is no check on detail line and no check on total, if $forcedroundingmode = 'none'
3638  $parameters = array('fk_element' => $obj->rowid);
3639  $reshook = $hookmanager->executeHooks('changeRoundingMode', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
3640 
3641  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'
3642  // This part of code is to fix data. We should not call it too often.
3643  $localtax_array = array($obj->localtax1_type, $obj->localtax1_tx, $obj->localtax2_type, $obj->localtax2_tx);
3644  $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);
3645 
3646  $diff_when_using_price_ht = price2num($tmpcal[1] - $obj->total_tva, 'MT', 1); // If price was set with tax price adn unit price HT has a low number of digits, then we may have a diff on recalculation from unit price HT.
3647  $diff_on_current_total = price2num($obj->total_ttc - $obj->total_ht - $obj->total_tva - $obj->total_localtax1 - $obj->total_localtax2, 'MT', 1);
3648  //var_dump($obj->total_ht.' '.$obj->total_tva.' '.$obj->total_localtax1.' '.$obj->total_localtax2.' =? '.$obj->total_ttc);
3649  //var_dump($diff_when_using_price_ht.' '.$diff_on_current_total);
3650 
3651  if ($diff_when_using_price_ht && $diff_on_current_total) {
3652  $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);
3653  dol_syslog('We found unconsistent 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, LOG_WARNING);
3654  $resqlfix = $this->db->query($sqlfix);
3655  if (!$resqlfix) {
3656  dol_print_error($this->db, 'Failed to update line');
3657  }
3658  $obj->total_tva = $tmpcal[1];
3659  $obj->total_ttc = $tmpcal[2];
3660  }
3661  }
3662 
3663  $this->total_ht += $obj->total_ht; // The field visible at end of line detail
3664  $this->total_tva += $obj->total_tva;
3665  $this->total_localtax1 += $obj->total_localtax1;
3666  $this->total_localtax2 += $obj->total_localtax2;
3667  $this->total_ttc += $obj->total_ttc;
3668  $this->multicurrency_total_ht += $obj->multicurrency_total_ht; // The field visible at end of line detail
3669  $this->multicurrency_total_tva += $obj->multicurrency_total_tva;
3670  $this->multicurrency_total_ttc += $obj->multicurrency_total_ttc;
3671 
3672  if (!isset($total_ht_by_vats[$obj->vatrate])) {
3673  $total_ht_by_vats[$obj->vatrate] = 0;
3674  }
3675  if (!isset($total_tva_by_vats[$obj->vatrate])) {
3676  $total_tva_by_vats[$obj->vatrate] = 0;
3677  }
3678  if (!isset($total_ttc_by_vats[$obj->vatrate])) {
3679  $total_ttc_by_vats[$obj->vatrate] = 0;
3680  }
3681  $total_ht_by_vats[$obj->vatrate] += $obj->total_ht;
3682  $total_tva_by_vats[$obj->vatrate] += $obj->total_tva;
3683  $total_ttc_by_vats[$obj->vatrate] += $obj->total_ttc;
3684 
3685  if ($forcedroundingmode == '1') { // Check if we need adjustement onto line for vat. TODO This works on the company currency but not on multicurrency
3686  $tmpvat = price2num($total_ht_by_vats[$obj->vatrate] * $obj->vatrate / 100, 'MT', 1);
3687  $diff = price2num($total_tva_by_vats[$obj->vatrate] - $tmpvat, 'MT', 1);
3688  //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";
3689  if ($diff) {
3690  if (abs($diff) > (10 * pow(10, -1 * getDolGlobalInt('MAIN_MAX_DECIMALS_TOT', 0)))) {
3691  // If error is more than 10 times the accurancy of rounding. This should not happen.
3692  $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.';
3693  dol_syslog($errmsg, LOG_WARNING);
3694  dol_print_error('', $errmsg);
3695  exit;
3696  }
3697  $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);
3698  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);
3699 
3700  $resqlfix = $this->db->query($sqlfix);
3701 
3702  if (!$resqlfix) {
3703  dol_print_error($this->db, 'Failed to update line');
3704  }
3705 
3706  $this->total_tva = (float) price2num($this->total_tva - $diff, '', 1);
3707  $this->total_ttc = (float) price2num($this->total_ttc - $diff, '', 1);
3708  $total_tva_by_vats[$obj->vatrate] = (float) price2num($total_tva_by_vats[$obj->vatrate] - $diff, '', 1);
3709  $total_ttc_by_vats[$obj->vatrate] = (float) price2num($total_ttc_by_vats[$obj->vatrate] - $diff, '', 1);
3710  }
3711  }
3712 
3713  $i++;
3714  }
3715 
3716  // Add revenue stamp to total
3717  $this->total_ttc += isset($this->revenuestamp) ? $this->revenuestamp : 0;
3718  $this->multicurrency_total_ttc += isset($this->revenuestamp) ? ($this->revenuestamp * $multicurrency_tx) : 0;
3719 
3720  // Situations totals
3721  if (!empty($this->situation_cycle_ref) && $this->situation_counter > 1 && method_exists($this, 'get_prev_sits') && $this->type != $this::TYPE_CREDIT_NOTE) {
3722  $prev_sits = $this->get_prev_sits();
3723 
3724  foreach ($prev_sits as $sit) { // $sit is an object Facture loaded with a fetch.
3725  $this->total_ht -= $sit->total_ht;
3726  $this->total_tva -= $sit->total_tva;
3727  $this->total_localtax1 -= $sit->total_localtax1;
3728  $this->total_localtax2 -= $sit->total_localtax2;
3729  $this->total_ttc -= $sit->total_ttc;
3730  $this->multicurrency_total_ht -= $sit->multicurrency_total_ht;
3731  $this->multicurrency_total_tva -= $sit->multicurrency_total_tva;
3732  $this->multicurrency_total_ttc -= $sit->multicurrency_total_ttc;
3733  }
3734  }
3735 
3736  // Clean total
3737  $this->total_ht = (float) price2num($this->total_ht);
3738  $this->total_tva = (float) price2num($this->total_tva);
3739  $this->total_localtax1 = (float) price2num($this->total_localtax1);
3740  $this->total_localtax2 = (float) price2num($this->total_localtax2);
3741  $this->total_ttc = (float) price2num($this->total_ttc);
3742 
3743  $this->db->free($resql);
3744 
3745  // Now update global fields total_ht, total_ttc, total_tva, total_localtax1, total_localtax2, multicurrency_total_*
3746  $fieldht = 'total_ht';
3747  $fieldtva = 'tva';
3748  $fieldlocaltax1 = 'localtax1';
3749  $fieldlocaltax2 = 'localtax2';
3750  $fieldttc = 'total_ttc';
3751  // Specific code for backward compatibility with old field names
3752  if ($this->element == 'facture' || $this->element == 'facturerec') {
3753  $fieldtva = 'total_tva';
3754  }
3755  if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier' || $this->element == 'invoice_supplier_rec') {
3756  $fieldtva = 'total_tva';
3757  }
3758  if ($this->element == 'propal') {
3759  $fieldtva = 'total_tva';
3760  }
3761  if ($this->element == 'expensereport') {
3762  $fieldtva = 'total_tva';
3763  }
3764  if ($this->element == 'supplier_proposal') {
3765  $fieldtva = 'total_tva';
3766  }
3767  if ($this->element == 'commande') {
3768  $fieldtva = 'total_tva';
3769  }
3770  if ($this->element == 'order_supplier') {
3771  $fieldtva = 'total_tva';
3772  }
3773 
3774  if (empty($nodatabaseupdate)) {
3775  $sql = "UPDATE ".$this->db->prefix().$this->table_element.' SET';
3776  $sql .= " ".$fieldht." = ".((float) price2num($this->total_ht, 'MT', 1)).",";
3777  $sql .= " ".$fieldtva." = ".((float) price2num($this->total_tva, 'MT', 1)).",";
3778  $sql .= " ".$fieldlocaltax1." = ".((float) price2num($this->total_localtax1, 'MT', 1)).",";
3779  $sql .= " ".$fieldlocaltax2." = ".((float) price2num($this->total_localtax2, 'MT', 1)).",";
3780  $sql .= " ".$fieldttc." = ".((float) price2num($this->total_ttc, 'MT', 1));
3781  $sql .= ", multicurrency_total_ht = ".((float) price2num($this->multicurrency_total_ht, 'MT', 1));
3782  $sql .= ", multicurrency_total_tva = ".((float) price2num($this->multicurrency_total_tva, 'MT', 1));
3783  $sql .= ", multicurrency_total_ttc = ".((float) price2num($this->multicurrency_total_ttc, 'MT', 1));
3784  $sql .= " WHERE rowid = ".((int) $this->id);
3785 
3786  dol_syslog(get_class($this)."::update_price", LOG_DEBUG);
3787  $resql = $this->db->query($sql);
3788 
3789  if (!$resql) {
3790  $error++;
3791  $this->error = $this->db->lasterror();
3792  $this->errors[] = $this->db->lasterror();
3793  }
3794  }
3795 
3796  if (!$error) {
3797  return 1;
3798  } else {
3799  return -1;
3800  }
3801  } else {
3802  dol_print_error($this->db, 'Bad request in update_price');
3803  return -1;
3804  }
3805  }
3806 
3807  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3818  public function add_object_linked($origin = null, $origin_id = null, $f_user = null, $notrigger = 0)
3819  {
3820  // phpcs:enable
3821  global $user, $hookmanager, $action;
3822  $origin = (!empty($origin) ? $origin : $this->origin);
3823  $origin_id = (!empty($origin_id) ? $origin_id : $this->origin_id);
3824  $f_user = isset($f_user) ? $f_user : $user;
3825 
3826  // Special case
3827  if ($origin == 'order') {
3828  $origin = 'commande';
3829  }
3830  if ($origin == 'invoice') {
3831  $origin = 'facture';
3832  }
3833  if ($origin == 'invoice_template') {
3834  $origin = 'facturerec';
3835  }
3836  if ($origin == 'supplierorder') {
3837  $origin = 'order_supplier';
3838  }
3839 
3840  // 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.
3841  // 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.
3842  $coremodule = array('knowledgemanagement', 'partnership', 'workstation', 'ticket', 'recruitment', 'eventorganization', 'asset');
3843  // Add module part to target type if object has $module property and isn't in core modules.
3844  $targettype = ((!empty($this->module) && ! in_array($this->module, $coremodule)) ? $this->module.'_' : '').$this->element;
3845 
3846  $parameters = array('targettype'=>$targettype);
3847  // Hook for explicitly set the targettype if it must be differtent than $this->element
3848  $reshook = $hookmanager->executeHooks('setLinkedObjectSourceTargetType', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
3849  if ($reshook > 0) {
3850  if (!empty($hookmanager->resArray['targettype'])) $targettype = $hookmanager->resArray['targettype'];
3851  }
3852 
3853  $this->db->begin();
3854  $error = 0;
3855 
3856  $sql = "INSERT INTO " . $this->db->prefix() . "element_element (";
3857  $sql .= "fk_source";
3858  $sql .= ", sourcetype";
3859  $sql .= ", fk_target";
3860  $sql .= ", targettype";
3861  $sql .= ") VALUES (";
3862  $sql .= ((int) $origin_id);
3863  $sql .= ", '" . $this->db->escape($origin) . "'";
3864  $sql .= ", " . ((int) $this->id);
3865  $sql .= ", '" . $this->db->escape($targettype) . "'";
3866  $sql .= ")";
3867 
3868  dol_syslog(get_class($this) . "::add_object_linked", LOG_DEBUG);
3869  if ($this->db->query($sql)) {
3870  if (!$notrigger) {
3871  // Call trigger
3872  $this->context['link_origin'] = $origin;
3873  $this->context['link_origin_id'] = $origin_id;
3874  $result = $this->call_trigger('OBJECT_LINK_INSERT', $f_user);
3875  if ($result < 0) {
3876  $error++;
3877  }
3878  // End call triggers
3879  }
3880  } else {
3881  $this->error = $this->db->lasterror();
3882  $error++;
3883  }
3884 
3885  if (!$error) {
3886  $this->db->commit();
3887  return 1;
3888  } else {
3889  $this->db->rollback();
3890  return 0;
3891  }
3892  }
3893 
3916  public function fetchObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $clause = 'OR', $alsosametype = 1, $orderby = 'sourcetype', $loadalsoobjects = 1)
3917  {
3918  global $conf, $hookmanager, $action;
3919 
3920  // Important for pdf generation time reduction
3921  // This boolean is true if $this->linkedObjects has already been loaded with all objects linked without filter
3922  if ($this->id > 0 && !empty($this->linkedObjectsFullLoaded[$this->id])) {
3923  return 1;
3924  }
3925 
3926  $this->linkedObjectsIds = array();
3927  $this->linkedObjects = array();
3928 
3929  $justsource = false;
3930  $justtarget = false;
3931  $withtargettype = false;
3932  $withsourcetype = false;
3933 
3934  $parameters = array('sourcetype'=>$sourcetype, 'sourceid'=>$sourceid, 'targettype'=>$targettype, 'targetid'=>$targetid);
3935  // Hook for explicitly set the targettype if it must be differtent than $this->element
3936  $reshook = $hookmanager->executeHooks('setLinkedObjectSourceTargetType', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
3937  if ($reshook > 0) {
3938  if (!empty($hookmanager->resArray['sourcetype'])) $sourcetype = $hookmanager->resArray['sourcetype'];
3939  if (!empty($hookmanager->resArray['sourceid'])) $sourceid = $hookmanager->resArray['sourceid'];
3940  if (!empty($hookmanager->resArray['targettype'])) $targettype = $hookmanager->resArray['targettype'];
3941  if (!empty($hookmanager->resArray['targetid'])) $targetid = $hookmanager->resArray['targetid'];
3942  }
3943 
3944  if (!empty($sourceid) && !empty($sourcetype) && empty($targetid)) {
3945  $justsource = true; // the source (id and type) is a search criteria
3946  if (!empty($targettype)) {
3947  $withtargettype = true;
3948  }
3949  }
3950  if (!empty($targetid) && !empty($targettype) && empty($sourceid)) {
3951  $justtarget = true; // the target (id and type) is a search criteria
3952  if (!empty($sourcetype)) {
3953  $withsourcetype = true;
3954  }
3955  }
3956 
3957  $sourceid = (!empty($sourceid) ? $sourceid : $this->id);
3958  $targetid = (!empty($targetid) ? $targetid : $this->id);
3959  $sourcetype = (!empty($sourcetype) ? $sourcetype : $this->element);
3960  $targettype = (!empty($targettype) ? $targettype : $this->element);
3961 
3962  /*if (empty($sourceid) && empty($targetid))
3963  {
3964  dol_syslog('Bad usage of function. No source nor target id defined (nor as parameter nor as object id)', LOG_ERR);
3965  return -1;
3966  }*/
3967 
3968  // Links between objects are stored in table element_element
3969  $sql = "SELECT rowid, fk_source, sourcetype, fk_target, targettype";
3970  $sql .= " FROM ".$this->db->prefix()."element_element";
3971  $sql .= " WHERE ";
3972  if ($justsource || $justtarget) {
3973  if ($justsource) {
3974  $sql .= "fk_source = ".((int) $sourceid)." AND sourcetype = '".$this->db->escape($sourcetype)."'";
3975  if ($withtargettype) {
3976  $sql .= " AND targettype = '".$this->db->escape($targettype)."'";
3977  }
3978  } elseif ($justtarget) {
3979  $sql .= "fk_target = ".((int) $targetid)." AND targettype = '".$this->db->escape($targettype)."'";
3980  if ($withsourcetype) {
3981  $sql .= " AND sourcetype = '".$this->db->escape($sourcetype)."'";
3982  }
3983  }
3984  } else {
3985  $sql .= "(fk_source = ".((int) $sourceid)." AND sourcetype = '".$this->db->escape($sourcetype)."')";
3986  $sql .= " ".$clause." (fk_target = ".((int) $targetid)." AND targettype = '".$this->db->escape($targettype)."')";
3987  if ($loadalsoobjects && $this->id > 0 && $sourceid == $this->id && $sourcetype == $this->element && $targetid == $this->id && $targettype == $this->element && $clause == 'OR') {
3988  $this->linkedObjectsFullLoaded[$this->id] = true;
3989  }
3990  }
3991  $sql .= " ORDER BY ".$orderby;
3992 
3993  dol_syslog(get_class($this)."::fetchObjectLink", LOG_DEBUG);
3994  $resql = $this->db->query($sql);
3995  if ($resql) {
3996  $num = $this->db->num_rows($resql);
3997  $i = 0;
3998  while ($i < $num) {
3999  $obj = $this->db->fetch_object($resql);
4000  if ($justsource || $justtarget) {
4001  if ($justsource) {
4002  $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
4003  } elseif ($justtarget) {
4004  $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
4005  }
4006  } else {
4007  if ($obj->fk_source == $sourceid && $obj->sourcetype == $sourcetype) {
4008  $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
4009  }
4010  if ($obj->fk_target == $targetid && $obj->targettype == $targettype) {
4011  $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
4012  }
4013  }
4014  $i++;
4015  }
4016 
4017  if (!empty($this->linkedObjectsIds)) {
4018  $tmparray = $this->linkedObjectsIds;
4019  foreach ($tmparray as $objecttype => $objectids) { // $objecttype is a module name ('facture', 'mymodule', ...) or a module name with a suffix ('project_task', 'mymodule_myobj', ...)
4020  // Parse element/subelement (ex: project_task, cabinetmed_consultation, ...)
4021  $module = $element = $subelement = $objecttype;
4022  $regs = array();
4023  if ($objecttype != 'supplier_proposal' && $objecttype != 'order_supplier' && $objecttype != 'invoice_supplier'
4024  && preg_match('/^([^_]+)_([^_]+)/i', $objecttype, $regs)) {
4025  $module = $element = $regs[1];
4026  $subelement = $regs[2];
4027  }
4028 
4029  $classpath = $element.'/class';
4030  // To work with non standard classpath or module name
4031  if ($objecttype == 'facture') {
4032  $classpath = 'compta/facture/class';
4033  } elseif ($objecttype == 'facturerec') {
4034  $classpath = 'compta/facture/class';
4035  $module = 'facture';
4036  } elseif ($objecttype == 'propal') {
4037  $classpath = 'comm/propal/class';
4038  } elseif ($objecttype == 'supplier_proposal') {
4039  $classpath = 'supplier_proposal/class';
4040  } elseif ($objecttype == 'shipping') {
4041  $classpath = 'expedition/class';
4042  $subelement = 'expedition';
4043  $module = 'expedition_bon';
4044  } elseif ($objecttype == 'delivery') {
4045  $classpath = 'delivery/class';
4046  $subelement = 'delivery';
4047  $module = 'delivery_note';
4048  } elseif ($objecttype == 'invoice_supplier' || $objecttype == 'order_supplier') {
4049  $classpath = 'fourn/class';
4050  $module = 'fournisseur';
4051  } elseif ($objecttype == 'fichinter') {
4052  $classpath = 'fichinter/class';
4053  $subelement = 'fichinter';
4054  $module = 'ficheinter';
4055  } elseif ($objecttype == 'subscription') {
4056  $classpath = 'adherents/class';
4057  $module = 'adherent';
4058  } elseif ($objecttype == 'contact') {
4059  $module = 'societe';
4060  }
4061  // Set classfile
4062  $classfile = strtolower($subelement);
4063  $classname = ucfirst($subelement);
4064 
4065  if ($objecttype == 'order') {
4066  $classfile = 'commande';
4067  $classname = 'Commande';
4068  } elseif ($objecttype == 'invoice_supplier') {
4069  $classfile = 'fournisseur.facture';
4070  $classname = 'FactureFournisseur';
4071  } elseif ($objecttype == 'order_supplier') {
4072  $classfile = 'fournisseur.commande';
4073  $classname = 'CommandeFournisseur';
4074  } elseif ($objecttype == 'supplier_proposal') {
4075  $classfile = 'supplier_proposal';
4076  $classname = 'SupplierProposal';
4077  } elseif ($objecttype == 'facturerec') {
4078  $classfile = 'facture-rec';
4079  $classname = 'FactureRec';
4080  } elseif ($objecttype == 'subscription') {
4081  $classfile = 'subscription';
4082  $classname = 'Subscription';
4083  } elseif ($objecttype == 'project' || $objecttype == 'projet') {
4084  $classpath = 'projet/class';
4085  $classfile = 'project';
4086  $classname = 'Project';
4087  } elseif ($objecttype == 'conferenceorboothattendee') {
4088  $classpath = 'eventorganization/class';
4089  $classfile = 'conferenceorboothattendee';
4090  $classname = 'ConferenceOrBoothAttendee';
4091  $module = 'eventorganization';
4092  } elseif ($objecttype == 'conferenceorbooth') {
4093  $classpath = 'eventorganization/class';
4094  $classfile = 'conferenceorbooth';
4095  $classname = 'ConferenceOrBooth';
4096  $module = 'eventorganization';
4097  } elseif ($objecttype == 'mo') {
4098  $classpath = 'mrp/class';
4099  $classfile = 'mo';
4100  $classname = 'Mo';
4101  $module = 'mrp';
4102  }
4103 
4104  // Here $module, $classfile and $classname are set, we can use them.
4105  if ($conf->$module->enabled && (($element != $this->element) || $alsosametype)) {
4106  if ($loadalsoobjects && (is_numeric($loadalsoobjects) || ($loadalsoobjects === $objecttype))) {
4107  dol_include_once('/'.$classpath.'/'.$classfile.'.class.php');
4108  //print '/'.$classpath.'/'.$classfile.'.class.php '.class_exists($classname);
4109  if (class_exists($classname)) {
4110  foreach ($objectids as $i => $objectid) { // $i is rowid into llx_element_element
4111  $object = new $classname($this->db);
4112  $ret = $object->fetch($objectid);
4113  if ($ret >= 0) {
4114  $this->linkedObjects[$objecttype][$i] = $object;
4115  }
4116  }
4117  }
4118  }
4119  } else {
4120  unset($this->linkedObjectsIds[$objecttype]);
4121  }
4122  }
4123  }
4124  return 1;
4125  } else {
4126  dol_print_error($this->db);
4127  return -1;
4128  }
4129  }
4130 
4137  public function clearObjectLinkedCache()
4138  {
4139  if ($this->id > 0 && !empty($this->linkedObjectsFullLoaded[$this->id])) {
4140  unset($this->linkedObjectsFullLoaded[$this->id]);
4141  }
4142 
4143  return 1;
4144  }
4145 
4158  public function updateObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $f_user = null, $notrigger = 0)
4159  {
4160  global $user;
4161  $updatesource = false;
4162  $updatetarget = false;
4163  $f_user = isset($f_user) ? $f_user : $user;
4164 
4165  if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) {
4166  $updatesource = true;
4167  } elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) {
4168  $updatetarget = true;
4169  }
4170 
4171  $this->db->begin();
4172  $error = 0;
4173 
4174  $sql = "UPDATE " . $this->db->prefix() . "element_element SET ";
4175  if ($updatesource) {
4176  $sql .= "fk_source = " . ((int) $sourceid);
4177  $sql .= ", sourcetype = '" . $this->db->escape($sourcetype) . "'";
4178  $sql .= " WHERE fk_target = " . ((int) $this->id);
4179  $sql .= " AND targettype = '" . $this->db->escape($this->element) . "'";
4180  } elseif ($updatetarget) {
4181  $sql .= "fk_target = " . ((int) $targetid);
4182  $sql .= ", targettype = '" . $this->db->escape($targettype) . "'";
4183  $sql .= " WHERE fk_source = " . ((int) $this->id);
4184  $sql .= " AND sourcetype = '" . $this->db->escape($this->element) . "'";
4185  }
4186 
4187  dol_syslog(get_class($this) . "::updateObjectLinked", LOG_DEBUG);
4188  if ($this->db->query($sql)) {
4189  if (!$notrigger) {
4190  // Call trigger
4191  $this->context['link_source_id'] = $sourceid;
4192  $this->context['link_source_type'] = $sourcetype;
4193  $this->context['link_target_id'] = $targetid;
4194  $this->context['link_target_type'] = $targettype;
4195  $result = $this->call_trigger('OBJECT_LINK_MODIFY', $f_user);
4196  if ($result < 0) {
4197  $error++;
4198  }
4199  // End call triggers
4200  }
4201  } else {
4202  $this->error = $this->db->lasterror();
4203  $error++;
4204  }
4205 
4206  if (!$error) {
4207  $this->db->commit();
4208  return 1;
4209  } else {
4210  $this->db->rollback();
4211  return -1;
4212  }
4213  }
4214 
4228  public function deleteObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $rowid = '', $f_user = null, $notrigger = 0)
4229  {
4230  global $user;
4231  $deletesource = false;
4232  $deletetarget = false;
4233  $f_user = isset($f_user) ? $f_user : $user;
4234 
4235  if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) {
4236  $deletesource = true;
4237  } elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) {
4238  $deletetarget = true;
4239  }
4240 
4241  $sourceid = (!empty($sourceid) ? $sourceid : $this->id);
4242  $sourcetype = (!empty($sourcetype) ? $sourcetype : $this->element);
4243  $targetid = (!empty($targetid) ? $targetid : $this->id);
4244  $targettype = (!empty($targettype) ? $targettype : $this->element);
4245  $this->db->begin();
4246  $error = 0;
4247 
4248  if (!$notrigger) {
4249  // Call trigger
4250  $this->context['link_id'] = $rowid;
4251  $this->context['link_source_id'] = $sourceid;
4252  $this->context['link_source_type'] = $sourcetype;
4253  $this->context['link_target_id'] = $targetid;
4254  $this->context['link_target_type'] = $targettype;
4255  $result = $this->call_trigger('OBJECT_LINK_DELETE', $f_user);
4256  if ($result < 0) {
4257  $error++;
4258  }
4259  // End call triggers
4260  }
4261 
4262  if (!$error) {
4263  $sql = "DELETE FROM " . $this->db->prefix() . "element_element";
4264  $sql .= " WHERE";
4265  if ($rowid > 0) {
4266  $sql .= " rowid = " . ((int) $rowid);
4267  } else {
4268  if ($deletesource) {
4269  $sql .= " fk_source = " . ((int) $sourceid) . " AND sourcetype = '" . $this->db->escape($sourcetype) . "'";
4270  $sql .= " AND fk_target = " . ((int) $this->id) . " AND targettype = '" . $this->db->escape($this->element) . "'";
4271  } elseif ($deletetarget) {
4272  $sql .= " fk_target = " . ((int) $targetid) . " AND targettype = '" . $this->db->escape($targettype) . "'";
4273  $sql .= " AND fk_source = " . ((int) $this->id) . " AND sourcetype = '" . $this->db->escape($this->element) . "'";
4274  } else {
4275  $sql .= " (fk_source = " . ((int) $this->id) . " AND sourcetype = '" . $this->db->escape($this->element) . "')";
4276  $sql .= " OR";
4277  $sql .= " (fk_target = " . ((int) $this->id) . " AND targettype = '" . $this->db->escape($this->element) . "')";
4278  }
4279  }
4280 
4281  dol_syslog(get_class($this) . "::deleteObjectLinked", LOG_DEBUG);
4282  if (!$this->db->query($sql)) {
4283  $this->error = $this->db->lasterror();
4284  $this->errors[] = $this->error;
4285  $error++;
4286  }
4287  }
4288 
4289  if (!$error) {
4290  $this->db->commit();
4291  return 1;
4292  } else {
4293  $this->db->rollback();
4294  return 0;
4295  }
4296  }
4297 
4307  public static function getAllItemsLinkedByObjectID($fk_object_where, $field_select, $field_where, $table_element)
4308  {
4309  if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
4310  return -1;
4311  }
4312 
4313  global $db;
4314 
4315  $sql = "SELECT ".$field_select." FROM ".$db->prefix().$table_element." WHERE ".$field_where." = ".((int) $fk_object_where);
4316  $resql = $db->query($sql);
4317 
4318  $TRes = array();
4319  if (!empty($resql)) {
4320  while ($res = $db->fetch_object($resql)) {
4321  $TRes[] = $res->{$field_select};
4322  }
4323  }
4324 
4325  return $TRes;
4326  }
4327 
4336  public static function deleteAllItemsLinkedByObjectID($fk_object_where, $field_where, $table_element)
4337  {
4338  if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
4339  return -1;
4340  }
4341 
4342  global $db;
4343 
4344  $sql = "DELETE FROM ".$db->prefix().$table_element." WHERE ".$field_where." = ".((int) $fk_object_where);
4345  $resql = $db->query($sql);
4346 
4347  if (empty($resql)) {
4348  return 0;
4349  }
4350 
4351  return 1;
4352  }
4353 
4364  public function setStatut($status, $elementId = null, $elementType = '', $trigkey = '', $fieldstatus = 'fk_statut')
4365  {
4366  global $user, $langs, $conf;
4367 
4368  $savElementId = $elementId; // To be used later to know if we were using the method using the id of this or not.
4369 
4370  $elementId = (!empty($elementId) ? $elementId : $this->id);
4371  $elementTable = (!empty($elementType) ? $elementType : $this->table_element);
4372 
4373  $this->db->begin();
4374 
4375  if ($elementTable == 'facture_rec') {
4376  $fieldstatus = "suspended";
4377  }
4378  if ($elementTable == 'mailing') {
4379  $fieldstatus = "statut";
4380  }
4381  if ($elementTable == 'cronjob') {
4382  $fieldstatus = "status";
4383  }
4384  if ($elementTable == 'user') {
4385  $fieldstatus = "statut";
4386  }
4387  if ($elementTable == 'expensereport') {
4388  $fieldstatus = "fk_statut";
4389  }
4390  if ($elementTable == 'commande_fournisseur_dispatch') {
4391  $fieldstatus = "status";
4392  }
4393  if (isset($this->fields) && is_array($this->fields) && array_key_exists('status', $this->fields)) {
4394  $fieldstatus = 'status';
4395  }
4396 
4397  $sql = "UPDATE ".$this->db->prefix().$elementTable;
4398  $sql .= " SET ".$fieldstatus." = ".((int) $status);
4399  // If status = 1 = validated, update also fk_user_valid
4400  // TODO Replace the test on $elementTable by doing a test on existence of the field in $this->fields
4401  if ($status == 1 && in_array($elementTable, array('expensereport', 'inventory'))) {
4402  $sql .= ", fk_user_valid = ".((int) $user->id);
4403  }
4404  if ($status == 1 && in_array($elementTable, array('expensereport'))) {
4405  $sql .= ", date_valid = '".$this->db->idate(dol_now())."'";
4406  }
4407  if ($status == 1 && in_array($elementTable, array('inventory'))) {
4408  $sql .= ", date_validation = '".$this->db->idate(dol_now())."'";
4409  }
4410  $sql .= " WHERE rowid = ".((int) $elementId);
4411  $sql .= " AND ".$fieldstatus." <> ".((int) $status); // We avoid update if status already correct
4412 
4413  dol_syslog(get_class($this)."::setStatut", LOG_DEBUG);
4414  $resql = $this->db->query($sql);
4415  if ($resql) {
4416  $error = 0;
4417 
4418  $nb_rows_affected = $this->db->affected_rows($resql); // should be 1 or 0 if status was already correct
4419 
4420  if ($nb_rows_affected > 0) {
4421  if (empty($trigkey)) {
4422  // Try to guess trigkey (for backward compatibility, now we should have trigkey defined into the call of setStatus)
4423  if ($this->element == 'supplier_proposal' && $status == 2) {
4424  $trigkey = 'SUPPLIER_PROPOSAL_SIGN'; // 2 = SupplierProposal::STATUS_SIGNED. Can't use constant into this generic class
4425  }
4426  if ($this->element == 'supplier_proposal' && $status == 3) {
4427  $trigkey = 'SUPPLIER_PROPOSAL_REFUSE'; // 3 = SupplierProposal::STATUS_REFUSED. Can't use constant into this generic class
4428  }
4429  if ($this->element == 'supplier_proposal' && $status == 4) {
4430  $trigkey = 'SUPPLIER_PROPOSAL_CLOSE'; // 4 = SupplierProposal::STATUS_CLOSED. Can't use constant into this generic class
4431  }
4432  if ($this->element == 'fichinter' && $status == 3) {
4433  $trigkey = 'FICHINTER_CLASSIFY_DONE';
4434  }
4435  if ($this->element == 'fichinter' && $status == 2) {
4436  $trigkey = 'FICHINTER_CLASSIFY_BILLED';
4437  }
4438  if ($this->element == 'fichinter' && $status == 1) {
4439  $trigkey = 'FICHINTER_CLASSIFY_UNBILLED';
4440  }
4441  }
4442 
4443  if ($trigkey) {
4444  // Call trigger
4445  $result = $this->call_trigger($trigkey, $user);
4446  if ($result < 0) {
4447  $error++;
4448  }
4449  // End call triggers
4450  }
4451  } else {
4452  // The status was probably already good. We do nothing more, no triggers.
4453  }
4454 
4455  if (!$error) {
4456  $this->db->commit();
4457 
4458  if (empty($savElementId)) {
4459  // If the element we update is $this (so $elementId was provided as null)
4460  if ($fieldstatus == 'tosell') {
4461  $this->status = $status;
4462  } elseif ($fieldstatus == 'tobuy') {
4463  $this->status_buy = $status;
4464  } else {
4465  $this->statut = $status;
4466  $this->status = $status;
4467  }
4468  }
4469 
4470  return 1;
4471  } else {
4472  $this->db->rollback();
4473  dol_syslog(get_class($this)."::setStatut ".$this->error, LOG_ERR);
4474  return -1;
4475  }
4476  } else {
4477  $this->error = $this->db->lasterror();
4478  $this->db->rollback();
4479  return -1;
4480  }
4481  }
4482 
4483 
4491  public function getCanvas($id = 0, $ref = '')
4492  {
4493  global $conf;
4494 
4495  if (empty($id) && empty($ref)) {
4496  return 0;
4497  }
4498  if (!empty($conf->global->MAIN_DISABLE_CANVAS)) {
4499  return 0; // To increase speed. Not enabled by default.
4500  }
4501 
4502  // Clean parameters
4503  $ref = trim($ref);
4504 
4505  $sql = "SELECT rowid, canvas";
4506  $sql .= " FROM ".$this->db->prefix().$this->table_element;
4507  $sql .= " WHERE entity IN (".getEntity($this->element).")";
4508  if (!empty($id)) {
4509  $sql .= " AND rowid = ".((int) $id);
4510  }
4511  if (!empty($ref)) {
4512  $sql .= " AND ref = '".$this->db->escape($ref)."'";
4513  }
4514 
4515  $resql = $this->db->query($sql);
4516  if ($resql) {
4517  $obj = $this->db->fetch_object($resql);
4518  if ($obj) {
4519  $this->canvas = $obj->canvas;
4520  return 1;
4521  } else {
4522  return 0;
4523  }
4524  } else {
4525  dol_print_error($this->db);
4526  return -1;
4527  }
4528  }
4529 
4530 
4537  public function getSpecialCode($lineid)
4538  {
4539  $sql = "SELECT special_code FROM ".$this->db->prefix().$this->table_element_line;
4540  $sql .= " WHERE rowid = ".((int) $lineid);
4541  $resql = $this->db->query($sql);
4542  if ($resql) {
4543  $row = $this->db->fetch_row($resql);
4544  return $row[0];
4545  }
4546  }
4547 
4556  public function isObjectUsed($id = 0, $entity = 0)
4557  {
4558  global $langs;
4559 
4560  if (empty($id)) {
4561  $id = $this->id;
4562  }
4563 
4564  // Check parameters
4565  if (!isset($this->childtables) || !is_array($this->childtables) || count($this->childtables) == 0) {
4566  dol_print_error('Called isObjectUsed on a class with property this->childtables not defined');
4567  return -1;
4568  }
4569 
4570  $arraytoscan = $this->childtables;
4571  // For backward compatibility, we check if array is old format array('table1', 'table2', ...)
4572  $tmparray = array_keys($this->childtables);
4573  if (is_numeric($tmparray[0])) {
4574  $arraytoscan = array_flip($this->childtables);
4575  }
4576 
4577  // Test if child exists
4578  $haschild = 0;
4579  foreach ($arraytoscan as $table => $element) {
4580  //print $id.'-'.$table.'-'.$elementname.'<br>';
4581  // Check if element can be deleted
4582  $sql = "SELECT COUNT(*) as nb";
4583  $sql.= " FROM ".$this->db->prefix().$table." as c";
4584  if (!empty($element['parent']) && !empty($element['parentkey'])) {
4585  $sql.= ", ".$this->db->prefix().$element['parent']." as p";
4586  }
4587  $sql.= " WHERE c.".$this->fk_element." = ".((int) $id);
4588  if (!empty($element['parent']) && !empty($element['parentkey'])) {
4589  $sql.= " AND c.".$element['parentkey']." = p.rowid";
4590  }
4591  if (!empty($entity)) {
4592  if (!empty($element['parent']) && !empty($element['parentkey'])) {
4593  $sql.= " AND p.entity = ".((int) $entity);
4594  } else {
4595  $sql.= " AND c.entity = ".((int) $entity);
4596  }
4597  }
4598  $resql = $this->db->query($sql);
4599  if ($resql) {
4600  $obj = $this->db->fetch_object($resql);
4601  if ($obj->nb > 0) {
4602  $langs->load("errors");
4603  //print 'Found into table '.$table.', type '.$langs->transnoentitiesnoconv($elementname).', haschild='.$haschild;
4604  $haschild += $obj->nb;
4605  if (is_numeric($element)) { // very old usage array('table1', 'table2', ...)
4606  $this->errors[] = $langs->transnoentitiesnoconv("ErrorRecordHasAtLeastOneChildOfType", method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref, $table);
4607  } elseif (is_string($element)) { // old usage array('table1' => 'TranslateKey1', 'table2' => 'TranslateKey2', ...)
4608  $this->errors[] = $langs->transnoentitiesnoconv("ErrorRecordHasAtLeastOneChildOfType", method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref, $langs->transnoentitiesnoconv($element));
4609  } else { // new usage: $element['name']=Translation key
4610  $this->errors[] = $langs->transnoentitiesnoconv("ErrorRecordHasAtLeastOneChildOfType", method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref, $langs->transnoentitiesnoconv($element['name']));
4611  }
4612  break; // We found at least one, we stop here
4613  }
4614  } else {
4615  $this->errors[] = $this->db->lasterror();
4616  return -1;
4617  }
4618  }
4619  if ($haschild > 0) {
4620  $this->errors[] = "ErrorRecordHasChildren";
4621  return $haschild;
4622  } else {
4623  return 0;
4624  }
4625  }
4626 
4633  public function hasProductsOrServices($predefined = -1)
4634  {
4635  $nb = 0;
4636 
4637  foreach ($this->lines as $key => $val) {
4638  $qualified = 0;
4639  if ($predefined == -1) {
4640  $qualified = 1;
4641  }
4642  if ($predefined == 1 && $val->fk_product > 0) {
4643  $qualified = 1;
4644  }
4645  if ($predefined == 0 && $val->fk_product <= 0) {
4646  $qualified = 1;
4647  }
4648  if ($predefined == 2 && $val->fk_product > 0 && $val->product_type == 0) {
4649  $qualified = 1;
4650  }
4651  if ($predefined == 3 && $val->fk_product > 0 && $val->product_type == 1) {
4652  $qualified = 1;
4653  }
4654  if ($qualified) {
4655  $nb++;
4656  }
4657  }
4658  dol_syslog(get_class($this).'::hasProductsOrServices we found '.$nb.' qualified lines of products/servcies');
4659  return $nb;
4660  }
4661 
4667  public function getTotalDiscount()
4668  {
4669  if (!empty($this->table_element_line) ) {
4670  $total_discount = 0.00;
4671 
4672  $sql = "SELECT subprice as pu_ht, qty, remise_percent, total_ht";
4673  $sql .= " FROM ".$this->db->prefix().$this->table_element_line;
4674  $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
4675 
4676  dol_syslog(get_class($this).'::getTotalDiscount', LOG_DEBUG);
4677  $resql = $this->db->query($sql);
4678  if ($resql) {
4679  $num = $this->db->num_rows($resql);
4680  $i = 0;
4681  while ($i < $num) {
4682  $obj = $this->db->fetch_object($resql);
4683 
4684  $pu_ht = $obj->pu_ht;
4685  $qty = $obj->qty;
4686  $total_ht = $obj->total_ht;
4687 
4688  $total_discount_line = floatval(price2num(($pu_ht * $qty) - $total_ht, 'MT'));
4689  $total_discount += $total_discount_line;
4690 
4691  $i++;
4692  }
4693  }
4694 
4695  //print $total_discount; exit;
4696  return price2num($total_discount);
4697  }
4698 
4699  return null;
4700  }
4701 
4702 
4709  public function getTotalWeightVolume()
4710  {
4711  $totalWeight = 0;
4712  $totalVolume = 0;
4713  // defined for shipment only
4714  $totalOrdered = '';
4715  // defined for shipment only
4716  $totalToShip = '';
4717 
4718  foreach ($this->lines as $line) {
4719  if (isset($line->qty_asked)) {
4720  if (empty($totalOrdered)) {
4721  $totalOrdered = 0; // Avoid warning because $totalOrdered is ''
4722  }
4723  $totalOrdered += $line->qty_asked; // defined for shipment only
4724  }
4725  if (isset($line->qty_shipped)) {
4726  if (empty($totalToShip)) {
4727  $totalToShip = 0; // Avoid warning because $totalToShip is ''
4728  }
4729  $totalToShip += $line->qty_shipped; // defined for shipment only
4730  } elseif ($line->element == 'commandefournisseurdispatch' && isset($line->qty)) {
4731  if (empty($totalToShip)) {
4732  $totalToShip = 0;
4733  }
4734  $totalToShip += $line->qty; // defined for reception only
4735  }
4736 
4737  // Define qty, weight, volume, weight_units, volume_units
4738  if ($this->element == 'shipping') {
4739  // for shipments
4740  $qty = $line->qty_shipped ? $line->qty_shipped : 0;
4741  } else {
4742  $qty = $line->qty ? $line->qty : 0;
4743  }
4744 
4745  $weight = !empty($line->weight) ? $line->weight : 0;
4746  ($weight == 0 && !empty($line->product->weight)) ? $weight = $line->product->weight : 0;
4747  $volume = !empty($line->volume) ? $line->volume : 0;
4748  ($volume == 0 && !empty($line->product->volume)) ? $volume = $line->product->volume : 0;
4749 
4750  $weight_units = !empty($line->weight_units) ? $line->weight_units : 0;
4751  ($weight_units == 0 && !empty($line->product->weight_units)) ? $weight_units = $line->product->weight_units : 0;
4752  $volume_units = !empty($line->volume_units) ? $line->volume_units : 0;
4753  ($volume_units == 0 && !empty($line->product->volume_units)) ? $volume_units = $line->product->volume_units : 0;
4754 
4755  $weightUnit = 0;
4756  $volumeUnit = 0;
4757  if (!empty($weight_units)) {
4758  $weightUnit = $weight_units;
4759  }
4760  if (!empty($volume_units)) {
4761  $volumeUnit = $volume_units;
4762  }
4763 
4764  if (empty($totalWeight)) {
4765  $totalWeight = 0; // Avoid warning because $totalWeight is ''
4766  }
4767  if (empty($totalVolume)) {
4768  $totalVolume = 0; // Avoid warning because $totalVolume is ''
4769  }
4770 
4771  //var_dump($line->volume_units);
4772  if ($weight_units < 50) { // < 50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch)
4773  $trueWeightUnit = pow(10, $weightUnit);
4774  $totalWeight += $weight * $qty * $trueWeightUnit;
4775  } else {
4776  if ($weight_units == 99) {
4777  // conversion 1 Pound = 0.45359237 KG
4778  $trueWeightUnit = 0.45359237;
4779  $totalWeight += $weight * $qty * $trueWeightUnit;
4780  } elseif ($weight_units == 98) {
4781  // conversion 1 Ounce = 0.0283495 KG
4782  $trueWeightUnit = 0.0283495;
4783  $totalWeight += $weight * $qty * $trueWeightUnit;
4784  } else {
4785  $totalWeight += $weight * $qty; // This may be wrong if we mix different units
4786  }
4787  }
4788  if ($volume_units < 50) { // >50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch)
4789  //print $line->volume."x".$line->volume_units."x".($line->volume_units < 50)."x".$volumeUnit;
4790  $trueVolumeUnit = pow(10, $volumeUnit);
4791  //print $line->volume;
4792  $totalVolume += $volume * $qty * $trueVolumeUnit;
4793  } else {
4794  $totalVolume += $volume * $qty; // This may be wrong if we mix different units
4795  }
4796  }
4797 
4798  return array('weight'=>$totalWeight, 'volume'=>$totalVolume, 'ordered'=>$totalOrdered, 'toship'=>$totalToShip);
4799  }
4800 
4801 
4807  public function setExtraParameters()
4808  {
4809  $this->db->begin();
4810 
4811  $extraparams = (!empty($this->extraparams) ? json_encode($this->extraparams) : null);
4812 
4813  $sql = "UPDATE ".$this->db->prefix().$this->table_element;
4814  $sql .= " SET extraparams = ".(!empty($extraparams) ? "'".$this->db->escape($extraparams)."'" : "null");
4815  $sql .= " WHERE rowid = ".((int) $this->id);
4816 
4817  dol_syslog(get_class($this)."::setExtraParameters", LOG_DEBUG);
4818  $resql = $this->db->query($sql);
4819  if (!$resql) {
4820  $this->error = $this->db->lasterror();
4821  $this->db->rollback();
4822  return -1;
4823  } else {
4824  $this->db->commit();
4825  return 1;
4826  }
4827  }
4828 
4829 
4830  // --------------------
4831  // TODO: All functions here must be redesigned and moved as they are not business functions but output functions
4832  // --------------------
4833 
4834  /* This is to show add lines */
4835 
4845  public function formAddObjectLine($dateSelector, $seller, $buyer, $defaulttpldir = '/core/tpl')
4846  {
4847  global $conf, $user, $langs, $object, $hookmanager, $extrafields;
4848  global $form;
4849 
4850  // Line extrafield
4851  if (!is_object($extrafields)) {
4852  require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
4853  $extrafields = new ExtraFields($this->db);
4854  }
4855  $extrafields->fetch_name_optionals_label($this->table_element_line);
4856 
4857  // Output template part (modules that overwrite templates must declare this into descriptor)
4858  // Use global variables + $dateSelector + $seller and $buyer
4859  // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook 'formAddObjectLine'.
4860  $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
4861  foreach ($dirtpls as $module => $reldir) {
4862  if (!empty($module)) {
4863  $tpl = dol_buildpath($reldir.'/objectline_create.tpl.php');
4864  } else {
4865  $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_create.tpl.php';
4866  }
4867 
4868  if (empty($conf->file->strict_mode)) {
4869  $res = @include $tpl;
4870  } else {
4871  $res = include $tpl; // for debug
4872  }
4873  if ($res) {
4874  break;
4875  }
4876  }
4877  }
4878 
4879 
4880 
4881  /* This is to show array of line of details */
4882 
4883 
4898  public function printObjectLines($action, $seller, $buyer, $selected = 0, $dateSelector = 0, $defaulttpldir = '/core/tpl')
4899  {
4900  global $conf, $hookmanager, $langs, $user, $form, $extrafields, $object;
4901  // TODO We should not use global var for this
4902  global $inputalsopricewithtax, $usemargins, $disableedit, $disablemove, $disableremove, $outputalsopricetotalwithtax;
4903 
4904  // Define usemargins
4905  $usemargins = 0;
4906  if (!empty($conf->margin->enabled) && !empty($this->element) && in_array($this->element, array('facture', 'facturerec', 'propal', 'commande'))) {
4907  $usemargins = 1;
4908  }
4909 
4910  $num = count($this->lines);
4911 
4912  // Line extrafield
4913  if (!is_object($extrafields)) {
4914  require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
4915  $extrafields = new ExtraFields($this->db);
4916  }
4917  $extrafields->fetch_name_optionals_label($this->table_element_line);
4918 
4919  $parameters = array('num'=>$num, 'dateSelector'=>$dateSelector, 'seller'=>$seller, 'buyer'=>$buyer, 'selected'=>$selected, 'table_element_line'=>$this->table_element_line);
4920  $reshook = $hookmanager->executeHooks('printObjectLineTitle', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
4921  if (empty($reshook)) {
4922  // Output template part (modules that overwrite templates must declare this into descriptor)
4923  // Use global variables + $dateSelector + $seller and $buyer
4924  // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook.
4925  $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
4926  foreach ($dirtpls as $module => $reldir) {
4927  if (!empty($module)) {
4928  $tpl = dol_buildpath($reldir.'/objectline_title.tpl.php');
4929  } else {
4930  $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_title.tpl.php';
4931  }
4932  if (empty($conf->file->strict_mode)) {
4933  $res = @include $tpl;
4934  } else {
4935  $res = include $tpl; // for debug
4936  }
4937  if ($res) {
4938  break;
4939  }
4940  }
4941  }
4942 
4943  $i = 0;
4944 
4945  print "<!-- begin printObjectLines() --><tbody>\n";
4946  foreach ($this->lines as $line) {
4947  //Line extrafield
4948  $line->fetch_optionals();
4949 
4950  //if (is_object($hookmanager) && (($line->product_type == 9 && ! empty($line->special_code)) || ! empty($line->fk_parent_line)))
4951  if (is_object($hookmanager)) { // Old code is commented on preceding line.
4952  if (empty($line->fk_parent_line)) {
4953  $parameters = array('line'=>$line, 'num'=>$num, 'i'=>$i, 'dateSelector'=>$dateSelector, 'seller'=>$seller, 'buyer'=>$buyer, 'selected'=>$selected, 'table_element_line'=>$line->table_element);
4954  $reshook = $hookmanager->executeHooks('printObjectLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
4955  } else {
4956  $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);
4957  $reshook = $hookmanager->executeHooks('printObjectSubLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
4958  }
4959  }
4960  if (empty($reshook)) {
4961  $this->printObjectLine($action, $line, '', $num, $i, $dateSelector, $seller, $buyer, $selected, $extrafields, $defaulttpldir);
4962  }
4963 
4964  $i++;
4965  }
4966  print "</tbody><!-- end printObjectLines() -->\n";
4967  }
4968 
4986  public function printObjectLine($action, $line, $var, $num, $i, $dateSelector, $seller, $buyer, $selected = 0, $extrafields = null, $defaulttpldir = '/core/tpl')
4987  {
4988  global $conf, $langs, $user, $object, $hookmanager;
4989  global $form;
4990  global $object_rights, $disableedit, $disablemove, $disableremove; // TODO We should not use global var for this !
4991 
4992  $object_rights = $this->getRights();
4993 
4994  $element = $this->element;
4995 
4996  $text = '';
4997  $description = '';
4998 
4999  // Line in view mode
5000  if ($action != 'editline' || $selected != $line->id) {
5001  // Product
5002  if ($line->fk_product > 0) {
5003  $product_static = new Product($this->db);
5004  $product_static->fetch($line->fk_product);
5005 
5006  $product_static->ref = $line->ref; //can change ref in hook
5007  $product_static->label = !empty($line->label) ? $line->label : ""; //can change label in hook
5008 
5009  $text = $product_static->getNomUrl(1);
5010 
5011  // Define output language and label
5012  if (!empty($conf->global->MAIN_MULTILANGS)) {
5013  if (property_exists($this, 'socid') && !is_object($this->thirdparty)) {
5014  dol_print_error('', 'Error: Method printObjectLine was called on an object and object->fetch_thirdparty was not done before');
5015  return;
5016  }
5017 
5018  $prod = new Product($this->db);
5019  $prod->fetch($line->fk_product);
5020 
5021  $outputlangs = $langs;
5022  $newlang = '';
5023  if (empty($newlang) && GETPOST('lang_id', 'aZ09')) {
5024  $newlang = GETPOST('lang_id', 'aZ09');
5025  }
5026  if (!empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE) && empty($newlang) && is_object($this->thirdparty)) {
5027  $newlang = $this->thirdparty->default_lang; // To use language of customer
5028  }
5029  if (!empty($newlang)) {
5030  $outputlangs = new Translate("", $conf);
5031  $outputlangs->setDefaultLang($newlang);
5032  }
5033 
5034  $label = (!empty($prod->multilangs[$outputlangs->defaultlang]["label"])) ? $prod->multilangs[$outputlangs->defaultlang]["label"] : $line->product_label;
5035  } else {
5036  $label = $line->product_label;
5037  }
5038 
5039  $text .= ' - '.(!empty($line->label) ? $line->label : $label);
5040  $description .= (!empty($conf->global->PRODUIT_DESC_IN_FORM) ? '' : (!empty($line->description) ? dol_htmlentitiesbr($line->description) : '')); // Description is what to show on popup. We shown nothing if already into desc.
5041  }
5042 
5043  $line->pu_ttc = price2num((!empty($line->subprice) ? $line->subprice : 0) * (1 + ((!empty($line->tva_tx) ? $line->tva_tx : 0) / 100)), 'MU');
5044 
5045  // Output template part (modules that overwrite templates must declare this into descriptor)
5046  // Use global variables + $dateSelector + $seller and $buyer
5047  // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook printObjectLine and printObjectSubLine.
5048  $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
5049  foreach ($dirtpls as $module => $reldir) {
5050  if (!empty($module)) {
5051  $tpl = dol_buildpath($reldir.'/objectline_view.tpl.php');
5052  } else {
5053  $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_view.tpl.php';
5054  }
5055 
5056  if (empty($conf->file->strict_mode)) {
5057  $res = @include $tpl;
5058  } else {
5059  $res = include $tpl; // for debug
5060  }
5061  if ($res) {
5062  break;
5063  }
5064  }
5065  }
5066 
5067  // Line in update mode
5068  if ($this->statut == 0 && $action == 'editline' && $selected == $line->id) {
5069  $label = (!empty($line->label) ? $line->label : (($line->fk_product > 0) ? $line->product_label : ''));
5070 
5071  $line->pu_ttc = price2num($line->subprice * (1 + ($line->tva_tx / 100)), 'MU');
5072 
5073  // Output template part (modules that overwrite templates must declare this into descriptor)
5074  // Use global variables + $dateSelector + $seller and $buyer
5075  // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook printObjectLine and printObjectSubLine.
5076  $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
5077  foreach ($dirtpls as $module => $reldir) {
5078  if (!empty($module)) {
5079  $tpl = dol_buildpath($reldir.'/objectline_edit.tpl.php');
5080  } else {
5081  $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_edit.tpl.php';
5082  }
5083 
5084  if (empty($conf->file->strict_mode)) {
5085  $res = @include $tpl;
5086  } else {
5087  $res = include $tpl; // for debug
5088  }
5089  if ($res) {
5090  break;
5091  }
5092  }
5093  }
5094  }
5095 
5096 
5097  /* This is to show array of line of details of source object */
5098 
5099 
5110  public function printOriginLinesList($restrictlist = '', $selectedLines = array())
5111  {
5112  global $langs, $hookmanager, $conf, $form, $action;
5113 
5114  print '<tr class="liste_titre">';
5115  print '<td class="linecolref">'.$langs->trans('Ref').'</td>';
5116  print '<td class="linecoldescription">'.$langs->trans('Description').'</td>';
5117  print '<td class="linecolvat right">'.$langs->trans('VATRate').'</td>';
5118  print '<td class="linecoluht right">'.$langs->trans('PriceUHT').'</td>';
5119  if (!empty($conf->multicurrency->enabled)) {
5120  print '<td class="linecoluht_currency right">'.$langs->trans('PriceUHTCurrency').'</td>';
5121  }
5122  print '<td class="linecolqty right">'.$langs->trans('Qty').'</td>';
5123  if (!empty($conf->global->PRODUCT_USE_UNITS)) {
5124  print '<td class="linecoluseunit left">'.$langs->trans('Unit').'</td>';
5125  }
5126  print '<td class="linecoldiscount right">'.$langs->trans('ReductionShort').'</td>';
5127  print '<td class="linecolht right">'.$langs->trans('TotalHT').'</td>';
5128  print '<td class="center">'.$form->showCheckAddButtons('checkforselect', 1).'</td>';
5129  print '</tr>';
5130  $i = 0;
5131 
5132  if (!empty($this->lines)) {
5133  foreach ($this->lines as $line) {
5134  $reshook = 0;
5135  //if (is_object($hookmanager) && (($line->product_type == 9 && !empty($line->special_code)) || !empty($line->fk_parent_line))) {
5136  if (is_object($hookmanager)) { // Old code is commented on preceding line.
5137  $parameters = array('line'=>$line, 'i'=>$i, 'restrictlist'=>$restrictlist, 'selectedLines'=> $selectedLines);
5138  if (!empty($line->fk_parent_line)) { $parameters['fk_parent_line'] = $line->fk_parent_line; }
5139  $reshook = $hookmanager->executeHooks('printOriginObjectLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
5140  }
5141  if (empty($reshook)) {
5142  $this->printOriginLine($line, '', $restrictlist, '/core/tpl', $selectedLines);
5143  }
5144 
5145  $i++;
5146  }
5147  }
5148  }
5149 
5163  public function printOriginLine($line, $var, $restrictlist = '', $defaulttpldir = '/core/tpl', $selectedLines = array())
5164  {
5165  global $langs, $conf;
5166 
5167  //var_dump($line);
5168  if (!empty($line->date_start)) {
5169  $date_start = $line->date_start;
5170  } else {
5171  $date_start = $line->date_debut_prevue;
5172  if ($line->date_debut_reel) {
5173  $date_start = $line->date_debut_reel;
5174  }
5175  }
5176  if (!empty($line->date_end)) {
5177  $date_end = $line->date_end;
5178  } else {
5179  $date_end = $line->date_fin_prevue;
5180  if ($line->date_fin_reel) {
5181  $date_end = $line->date_fin_reel;
5182  }
5183  }
5184 
5185  $this->tpl['id'] = $line->id;
5186 
5187  $this->tpl['label'] = '';
5188  if (!empty($line->fk_parent_line)) {
5189  $this->tpl['label'] .= img_picto('', 'rightarrow');
5190  }
5191 
5192  if (($line->info_bits & 2) == 2) { // TODO Not sure this is used for source object
5193  $discount = new DiscountAbsolute($this->db);
5194  $discount->fk_soc = $this->socid;
5195  $this->tpl['label'] .= $discount->getNomUrl(0, 'discount');
5196  } elseif (!empty($line->fk_product)) {
5197  $productstatic = new Product($this->db);
5198  $productstatic->id = $line->fk_product;
5199  $productstatic->ref = $line->ref;
5200  $productstatic->type = $line->fk_product_type;
5201  if (empty($productstatic->ref)) {
5202  $line->fetch_product();
5203  $productstatic = $line->product;
5204  }
5205 
5206  $this->tpl['label'] .= $productstatic->getNomUrl(1);
5207  $this->tpl['label'] .= ' - '.(!empty($line->label) ? $line->label : $line->product_label);
5208  // Dates
5209  if ($line->product_type == 1 && ($date_start || $date_end)) {
5210  $this->tpl['label'] .= get_date_range($date_start, $date_end);
5211  }
5212  } else {
5213  $this->tpl['label'] .= ($line->product_type == -1 ? '&nbsp;' : ($line->product_type == 1 ? img_object($langs->trans(''), 'service') : img_object($langs->trans(''), 'product')));
5214  if (!empty($line->desc)) {
5215  $this->tpl['label'] .= $line->desc;
5216  } else {
5217  $this->tpl['label'] .= ($line->label ? '&nbsp;'.$line->label : '');
5218  }
5219 
5220  // Dates
5221  if ($line->product_type == 1 && ($date_start || $date_end)) {
5222  $this->tpl['label'] .= get_date_range($date_start, $date_end);
5223  }
5224  }
5225 
5226  if (!empty($line->desc)) {
5227  if ($line->desc == '(CREDIT_NOTE)') { // TODO Not sure this is used for source object
5228  $discount = new DiscountAbsolute($this->db);
5229  $discount->fetch($line->fk_remise_except);
5230  $this->tpl['description'] = $langs->transnoentities("DiscountFromCreditNote", $discount->getNomUrl(0));
5231  } elseif ($line->desc == '(DEPOSIT)') { // TODO Not sure this is used for source object
5232  $discount = new DiscountAbsolute($this->db);
5233  $discount->fetch($line->fk_remise_except);
5234  $this->tpl['description'] = $langs->transnoentities("DiscountFromDeposit", $discount->getNomUrl(0));
5235  } elseif ($line->desc == '(EXCESS RECEIVED)') {
5236  $discount = new DiscountAbsolute($this->db);
5237  $discount->fetch($line->fk_remise_except);
5238  $this->tpl['description'] = $langs->transnoentities("DiscountFromExcessReceived", $discount->getNomUrl(0));
5239  } elseif ($line->desc == '(EXCESS PAID)') {
5240  $discount = new DiscountAbsolute($this->db);
5241  $discount->fetch($line->fk_remise_except);
5242  $this->tpl['description'] = $langs->transnoentities("DiscountFromExcessPaid", $discount->getNomUrl(0));
5243  } else {
5244  $this->tpl['description'] = dol_trunc($line->desc, 60);
5245  }
5246  } else {
5247  $this->tpl['description'] = '&nbsp;';
5248  }
5249 
5250  // VAT Rate
5251  $this->tpl['vat_rate'] = vatrate($line->tva_tx, true);
5252  $this->tpl['vat_rate'] .= (($line->info_bits & 1) == 1) ? '*' : '';
5253  if (!empty($line->vat_src_code) && !preg_match('/\(/', $this->tpl['vat_rate'])) {
5254  $this->tpl['vat_rate'] .= ' ('.$line->vat_src_code.')';
5255  }
5256 
5257  $this->tpl['price'] = price($line->subprice);
5258  $this->tpl['total_ht'] = price($line->total_ht);
5259  $this->tpl['multicurrency_price'] = price($line->multicurrency_subprice);
5260  $this->tpl['qty'] = (($line->info_bits & 2) != 2) ? $line->qty : '&nbsp;';
5261  if (!empty($conf->global->PRODUCT_USE_UNITS)) {
5262  $this->tpl['unit'] = $langs->transnoentities($line->getLabelOfUnit('long'));
5263  }
5264  $this->tpl['remise_percent'] = (($line->info_bits & 2) != 2) ? vatrate($line->remise_percent, true) : '&nbsp;';
5265 
5266  // Is the line strike or not
5267  $this->tpl['strike'] = 0;
5268  if ($restrictlist == 'services' && $line->product_type != Product::TYPE_SERVICE) {
5269  $this->tpl['strike'] = 1;
5270  }
5271 
5272  // Output template part (modules that overwrite templates must declare this into descriptor)
5273  // Use global variables + $dateSelector + $seller and $buyer
5274  $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
5275  foreach ($dirtpls as $module => $reldir) {
5276  if (!empty($module)) {
5277  $tpl = dol_buildpath($reldir.'/originproductline.tpl.php');
5278  } else {
5279  $tpl = DOL_DOCUMENT_ROOT.$reldir.'/originproductline.tpl.php';
5280  }
5281 
5282  if (empty($conf->file->strict_mode)) {
5283  $res = @include $tpl;
5284  } else {
5285  $res = include $tpl; // for debug
5286  }
5287  if ($res) {
5288  break;
5289  }
5290  }
5291  }
5292 
5293 
5294  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5305  public function add_element_resource($resource_id, $resource_type, $busy = 0, $mandatory = 0)
5306  {
5307  // phpcs:enable
5308  $this->db->begin();
5309 
5310  $sql = "INSERT INTO ".$this->db->prefix()."element_resources (";
5311  $sql .= "resource_id";
5312  $sql .= ", resource_type";
5313  $sql .= ", element_id";
5314  $sql .= ", element_type";
5315  $sql .= ", busy";
5316  $sql .= ", mandatory";
5317  $sql .= ") VALUES (";
5318  $sql .= $resource_id;
5319  $sql .= ", '".$this->db->escape($resource_type)."'";
5320  $sql .= ", '".$this->db->escape($this->id)."'";
5321  $sql .= ", '".$this->db->escape($this->element)."'";
5322  $sql .= ", '".$this->db->escape($busy)."'";
5323  $sql .= ", '".$this->db->escape($mandatory)."'";
5324  $sql .= ")";
5325 
5326  dol_syslog(get_class($this)."::add_element_resource", LOG_DEBUG);
5327  if ($this->db->query($sql)) {
5328  $this->db->commit();
5329  return 1;
5330  } else {
5331  $this->error = $this->db->lasterror();
5332  $this->db->rollback();
5333  return 0;
5334  }
5335  }
5336 
5337  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5346  public function delete_resource($rowid, $element, $notrigger = 0)
5347  {
5348  // phpcs:enable
5349  global $user;
5350 
5351  $this->db->begin();
5352 
5353  $sql = "DELETE FROM ".$this->db->prefix()."element_resources";
5354  $sql .= " WHERE rowid = ".((int) $rowid);
5355 
5356  dol_syslog(get_class($this)."::delete_resource", LOG_DEBUG);
5357 
5358  $resql = $this->db->query($sql);
5359  if (!$resql) {
5360  $this->error = $this->db->lasterror();
5361  $this->db->rollback();
5362  return -1;
5363  } else {
5364  if (!$notrigger) {
5365  $result = $this->call_trigger(strtoupper($element).'_DELETE_RESOURCE', $user);
5366  if ($result < 0) {
5367  $this->db->rollback();
5368  return -1;
5369  }
5370  }
5371  $this->db->commit();
5372  return 1;
5373  }
5374  }
5375 
5376 
5382  public function __clone()
5383  {
5384  // Force a copy of this->lines, otherwise it will point to same object.
5385  if (isset($this->lines) && is_array($this->lines)) {
5386  $nboflines = count($this->lines);
5387  for ($i = 0; $i < $nboflines; $i++) {
5388  $this->lines[$i] = clone $this->lines[$i];
5389  }
5390  }
5391  }
5392 
5406  protected function commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams = null)
5407  {
5408  global $conf, $langs, $user, $hookmanager, $action;
5409 
5410  $srctemplatepath = '';
5411 
5412  $parameters = array('modelspath'=>$modelspath, 'modele'=>$modele, 'outputlangs'=>$outputlangs, 'hidedetails'=>$hidedetails, 'hidedesc'=>$hidedesc, 'hideref'=>$hideref, 'moreparams'=>$moreparams);
5413  $reshook = $hookmanager->executeHooks('commonGenerateDocument', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
5414 
5415  if (empty($reshook)) {
5416  dol_syslog("commonGenerateDocument modele=".$modele." outputlangs->defaultlang=".(is_object($outputlangs) ? $outputlangs->defaultlang : 'null'));
5417 
5418  if (empty($modele)) {
5419  $this->error = 'BadValueForParameterModele';
5420  return -1;
5421  }
5422 
5423  // Increase limit for PDF build
5424  $err = error_reporting();
5425  error_reporting(0);
5426  @set_time_limit(120);
5427  error_reporting($err);
5428 
5429  // If selected model is a filename template (then $modele="modelname" or "modelname:filename")
5430  $tmp = explode(':', $modele, 2);
5431  if (!empty($tmp[1])) {
5432  $modele = $tmp[0];
5433  $srctemplatepath = $tmp[1];
5434  }
5435 
5436  // Search template files
5437  $file = '';
5438  $classname = '';
5439  $filefound = '';
5440  $dirmodels = array('/');
5441  if (is_array($conf->modules_parts['models'])) {
5442  $dirmodels = array_merge($dirmodels, $conf->modules_parts['models']);
5443  }
5444  foreach ($dirmodels as $reldir) {
5445  foreach (array('doc', 'pdf') as $prefix) {
5446  if (in_array(get_class($this), array('Adherent'))) {
5447  // Member module use prefix_modele.class.php
5448  $file = $prefix."_".$modele.".class.php";
5449  } else {
5450  // Other module use prefix_modele.modules.php
5451  $file = $prefix."_".$modele.".modules.php";
5452  }
5453 
5454  // On verifie l'emplacement du modele
5455  $file = dol_buildpath($reldir.$modelspath.$file, 0);
5456  if (file_exists($file)) {
5457  $filefound = $file;
5458  $classname = $prefix.'_'.$modele;
5459  break;
5460  }
5461  }
5462  if ($filefound) {
5463  break;
5464  }
5465  }
5466 
5467  // If generator was found
5468  if ($filefound) {
5469  global $db; // Required to solve a conception default making an include of code using $db instead of $this->db just after.
5470 
5471  require_once $file;
5472 
5473  $obj = new $classname($this->db);
5474 
5475  // If generator is ODT, we must have srctemplatepath defined, if not we set it.
5476  if ($obj->type == 'odt' && empty($srctemplatepath)) {
5477  $varfortemplatedir = $obj->scandir;
5478  if ($varfortemplatedir && !empty($conf->global->$varfortemplatedir)) {
5479  $dirtoscan = $conf->global->$varfortemplatedir;
5480 
5481  $listoffiles = array();
5482 
5483  // Now we add first model found in directories scanned
5484  $listofdir = explode(',', $dirtoscan);
5485  foreach ($listofdir as $key => $tmpdir) {
5486  $tmpdir = trim($tmpdir);
5487  $tmpdir = preg_replace('/DOL_DATA_ROOT/', DOL_DATA_ROOT, $tmpdir);
5488  if (!$tmpdir) {
5489  unset($listofdir[$key]);
5490  continue;
5491  }
5492  if (is_dir($tmpdir)) {
5493  $tmpfiles = dol_dir_list($tmpdir, 'files', 0, '\.od(s|t)$', '', 'name', SORT_ASC, 0);
5494  if (count($tmpfiles)) {
5495  $listoffiles = array_merge($listoffiles, $tmpfiles);
5496  }
5497  }
5498  }
5499 
5500  if (count($listoffiles)) {
5501  foreach ($listoffiles as $record) {
5502  $srctemplatepath = $record['fullname'];
5503  break;
5504  }
5505  }
5506  }
5507 
5508  if (empty($srctemplatepath)) {
5509  $this->error = 'ErrorGenerationAskedForOdtTemplateWithSrcFileNotDefined';
5510  return -1;
5511  }
5512  }
5513 
5514  if ($obj->type == 'odt' && !empty($srctemplatepath)) {
5515  if (!dol_is_file($srctemplatepath)) {
5516  dol_syslog("Failed to locate template file ".$srctemplatepath, LOG_WARNING);
5517  $this->error = 'ErrorGenerationAskedForOdtTemplateWithSrcFileNotFound';
5518  return -1;
5519  }
5520  }
5521 
5522  // We save charset_output to restore it because write_file can change it if needed for
5523  // output format that does not support UTF8.
5524  $sav_charset_output = empty($outputlangs->charset_output) ? '' : $outputlangs->charset_output;
5525 
5526  if (in_array(get_class($this), array('Adherent'))) {
5527  $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, 'member', 1, 'tmp_cards', $moreparams);
5528  } else {
5529  $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, $hidedetails, $hidedesc, $hideref, $moreparams);
5530  }
5531  // After call of write_file $obj->result['fullpath'] is set with generated file. It will be used to update the ECM database index.
5532 
5533  if ($resultwritefile > 0) {
5534  $outputlangs->charset_output = $sav_charset_output;
5535 
5536  // We delete old preview
5537  require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
5538  dol_delete_preview($this);
5539 
5540  // Index file in database
5541  if (!empty($obj->result['fullpath'])) {
5542  $destfull = $obj->result['fullpath'];
5543 
5544  // Update the last_main_doc field into main object (if document generator has property ->update_main_doc_field set)
5545  $update_main_doc_field = 0;
5546  if (!empty($obj->update_main_doc_field)) {
5547  $update_main_doc_field = 1;
5548  }
5549 
5550  $this->indexFile($destfull, $update_main_doc_field);
5551  } else {
5552  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);
5553  }
5554 
5555  // Success in building document. We build meta file.
5556  dol_meta_create($this);
5557 
5558  return 1;
5559  } else {
5560  $outputlangs->charset_output = $sav_charset_output;
5561  $this->error = $obj->error;
5562  $this->errors = $obj->errors;
5563  dol_syslog("Error generating document for ".__CLASS__.". Error: ".$obj->error, LOG_ERR);
5564  return -1;
5565  }
5566  } else {
5567  if (!$filefound) {
5568  $this->error = $langs->trans("Error").' Failed to load doc generator with modelpaths='.$modelspath.' - modele='.$modele;
5569  $this->errors[] = $this->error;
5570  dol_syslog($this->error, LOG_ERR);
5571  } else {
5572  $this->error = $langs->trans("Error")." ".$langs->trans("ErrorFileDoesNotExists", $filefound);
5573  $this->errors[] = $this->error;
5574  dol_syslog($this->error, LOG_ERR);
5575  }
5576  return -1;
5577  }
5578  } else {
5579  return $reshook;
5580  }
5581  }
5582 
5592  public function indexFile($destfull, $update_main_doc_field)
5593  {
5594  global $conf, $user;
5595 
5596  $upload_dir = dirname($destfull);
5597  $destfile = basename($destfull);
5598  $rel_dir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $upload_dir);
5599 
5600  if (!preg_match('/[\\/]temp[\\/]|[\\/]thumbs|\.meta$/', $rel_dir)) { // If not a tmp dir
5601  $filename = basename($destfile);
5602  $rel_dir = preg_replace('/[\\/]$/', '', $rel_dir);
5603  $rel_dir = preg_replace('/^[\\/]/', '', $rel_dir);
5604 
5605  include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
5606  $ecmfile = new EcmFiles($this->db);
5607  $result = $ecmfile->fetch(0, '', ($rel_dir ? $rel_dir.'/' : '').$filename);
5608 
5609  // Set the public "share" key
5610  $setsharekey = false;
5611  if ($this->element == 'propal' || $this->element == 'proposal') {
5612  if (!isset($conf->global->PROPOSAL_ALLOW_ONLINESIGN) || !empty($conf->global->PROPOSAL_ALLOW_ONLINESIGN)) {
5613  $setsharekey = true; // feature to make online signature is not set or set to on (default)
5614  }
5615  if (!empty($conf->global->PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD)) {
5616  $setsharekey = true;
5617  }
5618  }
5619  if ($this->element == 'commande' && !empty($conf->global->ORDER_ALLOW_EXTERNAL_DOWNLOAD)) {
5620  $setsharekey = true;
5621  }
5622  if ($this->element == 'facture' && !empty($conf->global->INVOICE_ALLOW_EXTERNAL_DOWNLOAD)) {
5623  $setsharekey = true;
5624  }
5625  if ($this->element == 'bank_account' && !empty($conf->global->BANK_ACCOUNT_ALLOW_EXTERNAL_DOWNLOAD)) {
5626  $setsharekey = true;
5627  }
5628  if ($this->element == 'contrat' && !empty($conf->global->CONTRACT_ALLOW_EXTERNAL_DOWNLOAD)) {
5629  $setsharekey = true;
5630  }
5631  if ($this->element == 'supplier_proposal' && !empty($conf->global->SUPPLIER_PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD)) {
5632  $setsharekey = true;
5633  }
5634 
5635  if ($setsharekey) {
5636  if (empty($ecmfile->share)) { // Because object not found or share not set yet
5637  require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
5638  $ecmfile->share = getRandomPassword(true);
5639  }
5640  }
5641 
5642  if ($result > 0) {
5643  $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
5644  $ecmfile->fullpath_orig = '';
5645  $ecmfile->gen_or_uploaded = 'generated';
5646  $ecmfile->description = ''; // indexed content
5647  $ecmfile->keywords = ''; // keyword content
5648  $result = $ecmfile->update($user);
5649  if ($result < 0) {
5650  setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
5651  return -1;
5652  }
5653  } else {
5654  $ecmfile->entity = $conf->entity;
5655  $ecmfile->filepath = $rel_dir;
5656  $ecmfile->filename = $filename;
5657  $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
5658  $ecmfile->fullpath_orig = '';
5659  $ecmfile->gen_or_uploaded = 'generated';
5660  $ecmfile->description = ''; // indexed content
5661  $ecmfile->keywords = ''; // keyword content
5662  $ecmfile->src_object_type = $this->table_element; // $this->table_name is 'myobject' or 'mymodule_myobject'.
5663  $ecmfile->src_object_id = $this->id;
5664 
5665  $result = $ecmfile->create($user);
5666  if ($result < 0) {
5667  setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
5668  return -1;
5669  }
5670  }
5671 
5672  /*$this->result['fullname']=$destfull;
5673  $this->result['filepath']=$ecmfile->filepath;
5674  $this->result['filename']=$ecmfile->filename;*/
5675  //var_dump($obj->update_main_doc_field);exit;
5676 
5677  if ($update_main_doc_field && !empty($this->table_element)) {
5678  $sql = "UPDATE ".$this->db->prefix().$this->table_element." SET last_main_doc = '".$this->db->escape($ecmfile->filepath."/".$ecmfile->filename)."'";
5679  $sql .= " WHERE rowid = ".((int) $this->id);
5680 
5681  $resql = $this->db->query($sql);
5682  if (!$resql) {
5683  dol_print_error($this->db);
5684  return -1;
5685  } else {
5686  $this->last_main_doc = $ecmfile->filepath.'/'.$ecmfile->filename;
5687  }
5688  }
5689  }
5690 
5691  return 1;
5692  }
5693 
5701  public function addThumbs($file)
5702  {
5703  require_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
5704 
5705  $tmparraysize = getDefaultImageSizes();
5706  $maxwidthsmall = $tmparraysize['maxwidthsmall'];
5707  $maxheightsmall = $tmparraysize['maxheightsmall'];
5708  $maxwidthmini = $tmparraysize['maxwidthmini'];
5709  $maxheightmini = $tmparraysize['maxheightmini'];
5710  //$quality = $tmparraysize['quality'];
5711  $quality = 50; // For thumbs, we force quality to 50
5712 
5713  $file_osencoded = dol_osencode($file);
5714  if (file_exists($file_osencoded)) {
5715  // Create small thumbs for company (Ratio is near 16/9)
5716  // Used on logon for example
5717  vignette($file_osencoded, $maxwidthsmall, $maxheightsmall, '_small', $quality);
5718 
5719  // Create mini thumbs for company (Ratio is near 16/9)
5720  // Used on menu or for setup page for example
5721  vignette($file_osencoded, $maxwidthmini, $maxheightmini, '_mini', $quality);
5722  }
5723  }
5724 
5725 
5726  /* Functions common to commonobject and commonobjectline */
5727 
5728  /* For default values */
5729 
5742  public function getDefaultCreateValueFor($fieldname, $alternatevalue = null)
5743  {
5744  global $conf, $_POST;
5745 
5746  // If param here has been posted, we use this value first.
5747  if (GETPOSTISSET($fieldname)) {
5748  return GETPOST($fieldname, 'alphanohtml', 3);
5749  }
5750 
5751  if (isset($alternatevalue)) {
5752  return $alternatevalue;
5753  }
5754 
5755  $newelement = $this->element;
5756  if ($newelement == 'facture') {
5757  $newelement = 'invoice';
5758  }
5759  if ($newelement == 'commande') {
5760  $newelement = 'order';
5761  }
5762  if (empty($newelement)) {
5763  dol_syslog("Ask a default value using common method getDefaultCreateValueForField on an object with no property ->element defined. Return empty string.", LOG_WARNING);
5764  return '';
5765  }
5766 
5767  $keyforfieldname = strtoupper($newelement.'_DEFAULT_'.$fieldname);
5768  //var_dump($keyforfieldname);
5769  if (isset($conf->global->$keyforfieldname)) {
5770  return $conf->global->$keyforfieldname;
5771  }
5772 
5773  // TODO Ad here a scan into table llx_overwrite_default with a filter on $this->element and $fieldname
5774  }
5775 
5776 
5777  /* For triggers */
5778 
5779 
5780  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5791  public function call_trigger($triggerName, $user)
5792  {
5793  // phpcs:enable
5794  global $langs, $conf;
5795  if (!empty(self::TRIGGER_PREFIX) && strpos($triggerName, self::TRIGGER_PREFIX . '_') !== 0) {
5796  dol_print_error('', 'The trigger "' . $triggerName . '" does not start with "' . self::TRIGGER_PREFIX . '_" as required.');
5797  exit;
5798  }
5799  if (!is_object($langs)) { // If lang was not defined, we set it. It is required by run_triggers.
5800  include_once DOL_DOCUMENT_ROOT.'/core/class/translate.class.php';
5801  $langs = new Translate('', $conf);
5802  }
5803 
5804  include_once DOL_DOCUMENT_ROOT.'/core/class/interfaces.class.php';
5805  $interface = new Interfaces($this->db);
5806  $result = $interface->run_triggers($triggerName, $this, $user, $langs, $conf);
5807 
5808  if ($result < 0) {
5809  if (!empty($this->errors)) {
5810  $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.
5811  } else {
5812  $this->errors = $interface->errors;
5813  }
5814  }
5815  return $result;
5816  }
5817 
5818 
5819  /* Functions for data in other language */
5820 
5821 
5829  public function fetchValuesForExtraLanguages()
5830  {
5831  // To avoid SQL errors. Probably not the better solution though
5832  if (!$this->element) {
5833  return 0;
5834  }
5835  if (!($this->id > 0)) {
5836  return 0;
5837  }
5838  if (is_array($this->array_languages)) {
5839  return 1;
5840  }
5841 
5842  $this->array_languages = array();
5843 
5844  $element = $this->element;
5845  if ($element == 'categorie') {
5846  $element = 'categories'; // For compatibility
5847  }
5848 
5849  // Request to get translation values for object
5850  $sql = "SELECT rowid, property, lang , value";
5851  $sql .= " FROM ".$this->db->prefix()."object_lang";
5852  $sql .= " WHERE type_object = '".$this->db->escape($element)."'";
5853  $sql .= " AND fk_object = ".((int) $this->id);
5854 
5855  //dol_syslog(get_class($this)."::fetch_optionals get extrafields data for ".$this->table_element, LOG_DEBUG); // Too verbose
5856  $resql = $this->db->query($sql);
5857  if ($resql) {
5858  $numrows = $this->db->num_rows($resql);
5859  if ($numrows) {
5860  $i = 0;
5861  while ($i < $numrows) {
5862  $obj = $this->db->fetch_object($resql);
5863  $key = $obj->property;
5864  $value = $obj->value;
5865  $codelang = $obj->lang;
5866  $type = $this->fields[$key]['type'];
5867 
5868  // we can add this attribute to object
5869  if (preg_match('/date/', $type)) {
5870  $this->array_languages[$key][$codelang] = $this->db->jdate($value);
5871  } else {
5872  $this->array_languages[$key][$codelang] = $value;
5873  }
5874 
5875  $i++;
5876  }
5877  }
5878 
5879  $this->db->free($resql);
5880 
5881  if ($numrows) {
5882  return $numrows;
5883  } else {
5884  return 0;
5885  }
5886  } else {
5887  dol_print_error($this->db);
5888  return -1;
5889  }
5890  }
5891 
5898  public function setValuesForExtraLanguages($onlykey = '')
5899  {
5900  global $_POST, $langs;
5901 
5902  // Get extra fields
5903  foreach ($_POST as $postfieldkey => $postfieldvalue) {
5904  $tmparray = explode('-', $postfieldkey);
5905  if ($tmparray[0] != 'field') {
5906  continue;
5907  }
5908 
5909  $element = $tmparray[1];
5910  $key = $tmparray[2];
5911  $codelang = $tmparray[3];
5912  //var_dump("postfieldkey=".$postfieldkey." element=".$element." key=".$key." codelang=".$codelang);
5913 
5914  if (!empty($onlykey) && $key != $onlykey) {
5915  continue;
5916  }
5917  if ($element != $this->element) {
5918  continue;
5919  }
5920 
5921  $key_type = $this->fields[$key]['type'];
5922 
5923  $enabled = 1;
5924  if (isset($this->fields[$key]['enabled'])) {
5925  $enabled = dol_eval($this->fields[$key]['enabled'], 1, 1, '1');
5926  }
5927  /*$perms = 1;
5928  if (isset($this->fields[$key]['perms']))
5929  {
5930  $perms = dol_eval($this->fields[$key]['perms'], 1, 1, '1');
5931  }*/
5932  if (empty($enabled)) {
5933  continue;
5934  }
5935  //if (empty($perms)) continue;
5936 
5937  if (in_array($key_type, array('date'))) {
5938  // Clean parameters
5939  // TODO GMT date in memory must be GMT so we should add gm=true in parameters
5940  $value_key = dol_mktime(0, 0, 0, GETPOST($postfieldkey."month", 'int'), GETPOST($postfieldkey."day", 'int'), GETPOST($postfieldkey."year", 'int'));
5941  } elseif (in_array($key_type, array('datetime'))) {
5942  // Clean parameters
5943  // TODO GMT date in memory must be GMT so we should add gm=true in parameters
5944  $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'));
5945  } elseif (in_array($key_type, array('checkbox', 'chkbxlst'))) {
5946  $value_arr = GETPOST($postfieldkey, 'array'); // check if an array
5947  if (!empty($value_arr)) {
5948  $value_key = implode(',', $value_arr);
5949  } else {
5950  $value_key = '';
5951  }
5952  } elseif (in_array($key_type, array('price', 'double'))) {
5953  $value_arr = GETPOST($postfieldkey, 'alpha');
5954  $value_key = price2num($value_arr);
5955  } else {
5956  $value_key = GETPOST($postfieldkey);
5957  if (in_array($key_type, array('link')) && $value_key == '-1') {
5958  $value_key = '';
5959  }
5960  }
5961 
5962  $this->array_languages[$key][$codelang] = $value_key;
5963 
5964  /*if ($nofillrequired) {
5965  $langs->load('errors');
5966  setEventMessages($langs->trans('ErrorFieldsRequired').' : '.implode(', ', $error_field_required), null, 'errors');
5967  return -1;
5968  }*/
5969  }
5970 
5971  return 1;
5972  }
5973 
5974 
5975  /* Functions for extrafields */
5976 
5983  public function fetchNoCompute($id)
5984  {
5985  global $conf;
5986 
5987  $savDisableCompute = $conf->disable_compute;
5988  $conf->disable_compute = 1;
5989 
5990  $ret = $this->fetch($id);
5991 
5992  $conf->disable_compute = $savDisableCompute;
5993 
5994  return $ret;
5995  }
5996 
5997  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
6007  public function fetch_optionals($rowid = null, $optionsArray = null)
6008  {
6009  // phpcs:enable
6010  global $conf, $extrafields;
6011 
6012  if (empty($rowid)) {
6013  $rowid = $this->id;
6014  }
6015  if (empty($rowid) && isset($this->rowid)) {
6016  $rowid = $this->rowid; // deprecated
6017  }
6018 
6019  // To avoid SQL errors. Probably not the better solution though
6020  if (!$this->table_element) {
6021  return 0;
6022  }
6023 
6024  $this->array_options = array();
6025 
6026  if (!is_array($optionsArray)) {
6027  // If $extrafields is not a known object, we initialize it. Best practice is to have $extrafields defined into card.php or list.php page.
6028  if (!isset($extrafields) || !is_object($extrafields)) {
6029  require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
6030  $extrafields = new ExtraFields($this->db);
6031  }
6032 
6033  // Load array of extrafields for elementype = $this->table_element
6034  if (empty($extrafields->attributes[$this->table_element]['loaded'])) {
6035  $extrafields->fetch_name_optionals_label($this->table_element);
6036  }
6037  $optionsArray = (!empty($extrafields->attributes[$this->table_element]['label']) ? $extrafields->attributes[$this->table_element]['label'] : null);
6038  } else {
6039  global $extrafields;
6040  dol_syslog("Warning: fetch_optionals was called with param optionsArray defined when you should pass null now", LOG_WARNING);
6041  }
6042 
6043  $table_element = $this->table_element;
6044  if ($table_element == 'categorie') {
6045  $table_element = 'categories'; // For compatibility
6046  }
6047 
6048  // Request to get complementary values
6049  if (is_array($optionsArray) && count($optionsArray) > 0) {
6050  $sql = "SELECT rowid";
6051  foreach ($optionsArray as $name => $label) {
6052  if (empty($extrafields->attributes[$this->table_element]['type'][$name]) || $extrafields->attributes[$this->table_element]['type'][$name] != 'separate') {
6053  $sql .= ", ".$name;
6054  }
6055  }
6056  $sql .= " FROM ".$this->db->prefix().$table_element."_extrafields";
6057  $sql .= " WHERE fk_object = ".((int) $rowid);
6058 
6059  //dol_syslog(get_class($this)."::fetch_optionals get extrafields data for ".$this->table_element, LOG_DEBUG); // Too verbose
6060  $resql = $this->db->query($sql);
6061  if ($resql) {
6062  $numrows = $this->db->num_rows($resql);
6063  if ($numrows) {
6064  $tab = $this->db->fetch_array($resql);
6065 
6066  foreach ($tab as $key => $value) {
6067  // 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)
6068  if ($key != 'rowid' && $key != 'tms' && $key != 'fk_member' && !is_int($key)) {
6069  // we can add this attribute to object
6070  if (!empty($extrafields->attributes[$this->table_element]) && in_array($extrafields->attributes[$this->table_element]['type'][$key], array('date', 'datetime'))) {
6071  //var_dump($extrafields->attributes[$this->table_element]['type'][$key]);
6072  $this->array_options["options_".$key] = $this->db->jdate($value);
6073  } else {
6074  $this->array_options["options_".$key] = $value;
6075  }
6076 
6077  //var_dump('key '.$key.' '.$value.' type='.$extrafields->attributes[$this->table_element]['type'][$key].' '.$this->array_options["options_".$key]);
6078  }
6079  }
6080  }
6081 
6082  // If field is a computed field, value must become result of compute (regardless of whether a row exists
6083  // in the element's extrafields table)
6084  foreach ($extrafields->attributes[$this->table_element]['label'] as $key => $val) {
6085  if (!empty($extrafields->attributes[$this->table_element]) && !empty($extrafields->attributes[$this->table_element]['computed'][$key])) {
6086  //var_dump($conf->disable_compute);
6087  if (empty($conf->disable_compute)) {
6088  global $objectoffield; // We set a global variable to $objectoffield so
6089  $objectoffield = $this; // we can use it inside computed formula
6090  $this->array_options["options_".$key] = dol_eval($extrafields->attributes[$this->table_element]['computed'][$key], 1, 0, '');
6091  }
6092  }
6093  }
6094 
6095  $this->db->free($resql);
6096 
6097  if ($numrows) {
6098  return $numrows;
6099  } else {
6100  return 0;
6101  }
6102  } else {
6103  $this->errors[]=$this->db->lasterror;
6104  return -1;
6105  }
6106  }
6107  return 0;
6108  }
6109 
6116  public function deleteExtraFields()
6117  {
6118  global $conf;
6119 
6120  if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
6121  return 0;
6122  }
6123 
6124  $this->db->begin();
6125 
6126  $table_element = $this->table_element;
6127  if ($table_element == 'categorie') {
6128  $table_element = 'categories'; // For compatibility
6129  }
6130 
6131  dol_syslog(get_class($this)."::deleteExtraFields delete", LOG_DEBUG);
6132 
6133  $sql_del = "DELETE FROM ".$this->db->prefix().$table_element."_extrafields WHERE fk_object = ".((int) $this->id);
6134 
6135  $resql = $this->db->query($sql_del);
6136  if (!$resql) {
6137  $this->error = $this->db->lasterror();
6138  $this->db->rollback();
6139  return -1;
6140  } else {
6141  $this->db->commit();
6142  return 1;
6143  }
6144  }
6145 
6156  public function insertExtraFields($trigger = '', $userused = null)
6157  {
6158  global $conf, $langs, $user;
6159 
6160  if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
6161  return 0;
6162  }
6163 
6164  if (empty($userused)) {
6165  $userused = $user;
6166  }
6167 
6168  $error = 0;
6169 
6170  if (!empty($this->array_options)) {
6171  // Check parameters
6172  $langs->load('admin');
6173  require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
6174  $extrafields = new ExtraFields($this->db);
6175  $target_extrafields = $extrafields->fetch_name_optionals_label($this->table_element);
6176 
6177  // Eliminate copied source object extra fields that do not exist in target object
6178  $new_array_options = array();
6179  foreach ($this->array_options as $key => $value) {
6180  if (in_array(substr($key, 8), array_keys($target_extrafields))) { // We remove the 'options_' from $key for test
6181  $new_array_options[$key] = $value;
6182  } elseif (in_array($key, array_keys($target_extrafields))) { // We test on $key that does not contains the 'options_' prefix
6183  $new_array_options['options_'.$key] = $value;
6184  }
6185  }
6186 
6187  foreach ($new_array_options as $key => $value) {
6188  $attributeKey = substr($key, 8); // Remove 'options_' prefix
6189  $attributeType = $extrafields->attributes[$this->table_element]['type'][$attributeKey];
6190  $attributeLabel = $extrafields->attributes[$this->table_element]['label'][$attributeKey];
6191  $attributeParam = $extrafields->attributes[$this->table_element]['param'][$attributeKey];
6192  $attributeRequired = $extrafields->attributes[$this->table_element]['required'][$attributeKey];
6193  $attributeUnique = $extrafields->attributes[$this->table_element]['unique'][$attributeKey];
6194  $attrfieldcomputed = $extrafields->attributes[$this->table_element]['computed'][$attributeKey];
6195 
6196  // If we clone, we have to clean unique extrafields to prevent duplicates.
6197  // This behaviour can be prevented by external code by changing $this->context['createfromclone'] value in createFrom hook
6198  if (! empty($this->context['createfromclone']) && $this->context['createfromclone'] == 'createfromclone' && ! empty($attributeUnique)) {
6199  $new_array_options[$key] = null;
6200  }
6201 
6202  // Similar code than into insertExtraFields
6203  if ($attributeRequired) {
6204  $mandatorypb = false;
6205  if ($attributeType == 'link' && $this->array_options[$key] == '-1') {
6206  $mandatorypb = true;
6207  }
6208  if ($this->array_options[$key] === '') {
6209  $mandatorypb = true;
6210  }
6211  if ($attributeType == 'sellist' && $this->array_options[$key] == '0') {
6212  $mandatorypb = true;
6213  }
6214  if ($mandatorypb) {
6215  $langs->load("errors");
6216  dol_syslog("Mandatory field '".$key."' is empty during create and set to required into definition of extrafields");
6217  $this->errors[] = $langs->trans('ErrorFieldRequired', $attributeLabel);
6218  return -1;
6219  }
6220  }
6221 
6222  //dol_syslog("attributeLabel=".$attributeLabel, LOG_DEBUG);
6223  //dol_syslog("attributeType=".$attributeType, LOG_DEBUG);
6224 
6225  if (!empty($attrfieldcomputed)) {
6226  if (!empty($conf->global->MAIN_STORE_COMPUTED_EXTRAFIELDS)) {
6227  $value = dol_eval($attrfieldcomputed, 1, 0, '');
6228  dol_syslog($langs->trans("Extrafieldcomputed")." sur ".$attributeLabel."(".$value.")", LOG_DEBUG);
6229  $new_array_options[$key] = $value;
6230  } else {
6231  $new_array_options[$key] = null;
6232  }
6233  }
6234 
6235  switch ($attributeType) {
6236  case 'int':
6237  if (!is_numeric($value) && $value != '') {
6238  $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
6239  return -1;
6240  } elseif ($value == '') {
6241  $new_array_options[$key] = null;
6242  }
6243  break;
6244  case 'price':
6245  case 'double':
6246  $value = price2num($value);
6247  if (!is_numeric($value) && $value != '') {
6248  dol_syslog($langs->trans("ExtraFieldHasWrongValue")." for ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
6249  $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
6250  return -1;
6251  } elseif ($value == '') {
6252  $value = null;
6253  }
6254  //dol_syslog("double value"." sur ".$attributeLabel."(".$value." is '".$attributeType."')", LOG_DEBUG);
6255  $new_array_options[$key] = $value;
6256  break;
6257  /*case 'select': // Not required, we chosed value='0' for undefined values
6258  if ($value=='-1')
6259  {
6260  $this->array_options[$key] = null;
6261  }
6262  break;*/
6263  case 'password':
6264  $algo = '';
6265  if ($this->array_options[$key] != '' && is_array($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options'])) {
6266  // If there is an encryption choice, we use it to crypt data before insert
6267  $tmparrays = array_keys($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options']);
6268  $algo = reset($tmparrays);
6269  if ($algo != '') {
6270  //global $action; // $action may be 'create', 'update', 'update_extras'...
6271  //var_dump($action);
6272  //var_dump($this->oldcopy);exit;
6273  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
6274  //var_dump($this->oldcopy->array_options[$key]); var_dump($this->array_options[$key]);
6275  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.
6276  $new_array_options[$key] = $this->array_options[$key]; // Value is kept
6277  } else {
6278  // var_dump($algo);
6279  $newvalue = dol_hash($this->array_options[$key], $algo);
6280  $new_array_options[$key] = $newvalue;
6281  }
6282  } else {
6283  $new_array_options[$key] = $this->array_options[$key]; // Value is kept
6284  }
6285  }
6286  } else // Common usage
6287  {
6288  $new_array_options[$key] = $this->array_options[$key];
6289  }
6290  break;
6291  case 'date':
6292  case 'datetime':
6293  // If data is a string instead of a timestamp, we convert it
6294  if (!is_int($this->array_options[$key])) {
6295  $this->array_options[$key] = strtotime($this->array_options[$key]);
6296  }
6297  $new_array_options[$key] = $this->db->idate($this->array_options[$key]);
6298  break;
6299  case 'link':
6300  $param_list = array_keys($attributeParam['options']);
6301  // 0 : ObjectName
6302  // 1 : classPath
6303  $InfoFieldList = explode(":", $param_list[0]);
6304  dol_include_once($InfoFieldList[1]);
6305  if ($InfoFieldList[0] && class_exists($InfoFieldList[0])) {
6306  if ($value == '-1') { // -1 is key for no defined in combo list of objects
6307  $new_array_options[$key] = '';
6308  } elseif ($value) {
6309  $object = new $InfoFieldList[0]($this->db);
6310  if (is_numeric($value)) {
6311  $res = $object->fetch($value); // Common case
6312  } else {
6313  $res = $object->fetch('', $value); // For compatibility
6314  }
6315 
6316  if ($res > 0) {
6317  $new_array_options[$key] = $object->id;
6318  } else {
6319  $this->error = "Id/Ref '".$value."' for object '".$object->element."' not found";
6320  return -1;
6321  }
6322  }
6323  } else {
6324  dol_syslog('Error bad setup of extrafield', LOG_WARNING);
6325  }
6326  break;
6327  }
6328  }
6329 
6330  $this->db->begin();
6331 
6332  $table_element = $this->table_element;
6333  if ($table_element == 'categorie') {
6334  $table_element = 'categories'; // For compatibility
6335  }
6336 
6337  dol_syslog(get_class($this)."::insertExtraFields delete then insert", LOG_DEBUG);
6338 
6339  $sql_del = "DELETE FROM ".$this->db->prefix().$table_element."_extrafields WHERE fk_object = ".((int) $this->id);
6340  $this->db->query($sql_del);
6341 
6342  $sql = "INSERT INTO ".$this->db->prefix().$table_element."_extrafields (fk_object";
6343  foreach ($new_array_options as $key => $value) {
6344  $attributeKey = substr($key, 8); // Remove 'options_' prefix
6345  // Add field of attribut
6346  if ($extrafields->attributes[$this->table_element]['type'][$attributeKey] != 'separate') { // Only for other type than separator
6347  $sql .= ",".$attributeKey;
6348  }
6349  }
6350  // We must insert a default value for fields for other entities that are mandatory to avoid not null error
6351  if (!empty($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities']) && is_array($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'])) {
6352  foreach ($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'] as $tmpkey => $tmpval) {
6353  if (!isset($extrafields->attributes[$this->table_element]['type'][$tmpkey])) { // If field not already added previously
6354  $sql .= ",".$tmpkey;
6355  }
6356  }
6357  }
6358  $sql .= ") VALUES (".$this->id;
6359 
6360  foreach ($new_array_options as $key => $value) {
6361  $attributeKey = substr($key, 8); // Remove 'options_' prefix
6362  // Add field of attribute
6363  if ($extrafields->attributes[$this->table_element]['type'][$attributeKey] != 'separate') { // Only for other type than separator)
6364  if ($new_array_options[$key] != '' || $new_array_options[$key] == '0') {
6365  $sql .= ",'".$this->db->escape($new_array_options[$key])."'";
6366  } else {
6367  $sql .= ",null";
6368  }
6369  }
6370  }
6371  // We must insert a default value for fields for other entities that are mandatory to avoid not null error
6372  if (!empty($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities']) && is_array($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'])) {
6373  foreach ($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'] as $tmpkey => $tmpval) {
6374  if (!isset($extrafields->attributes[$this->table_element]['type'][$tmpkey])) { // If field not already added previously
6375  if (in_array($tmpval, array('int', 'double', 'price'))) {
6376  $sql .= ", 0";
6377  } else {
6378  $sql .= ", ''";
6379  }
6380  }
6381  }
6382  }
6383 
6384  $sql .= ")";
6385 
6386  $resql = $this->db->query($sql);
6387  if (!$resql) {
6388  $this->error = $this->db->lasterror();
6389  $error++;
6390  }
6391 
6392  if (!$error && $trigger) {
6393  // Call trigger
6394  $this->context = array('extrafieldaddupdate'=>1);
6395  $result = $this->call_trigger($trigger, $userused);
6396  if ($result < 0) {
6397  $error++;
6398  }
6399  // End call trigger
6400  }
6401 
6402  if ($error) {
6403  $this->db->rollback();
6404  return -1;
6405  } else {
6406  $this->db->commit();
6407  return 1;
6408  }
6409  } else {
6410  return 0;
6411  }
6412  }
6413 
6424  public function insertExtraLanguages($trigger = '', $userused = null)
6425  {
6426  global $conf, $langs, $user;
6427 
6428  if (empty($userused)) {
6429  $userused = $user;
6430  }
6431 
6432  $error = 0;
6433 
6434  if (!empty($conf->global->MAIN_EXTRALANGUAGES_DISABLED)) {
6435  return 0; // For avoid conflicts if trigger used
6436  }
6437 
6438  if (is_array($this->array_languages)) {
6439  $new_array_languages = $this->array_languages;
6440 
6441  foreach ($new_array_languages as $key => $value) {
6442  $attributeKey = $key;
6443  $attributeType = $this->fields[$attributeKey]['type'];
6444  $attributeLabel = $this->fields[$attributeKey]['label'];
6445 
6446  //dol_syslog("attributeLabel=".$attributeLabel, LOG_DEBUG);
6447  //dol_syslog("attributeType=".$attributeType, LOG_DEBUG);
6448 
6449  switch ($attributeType) {
6450  case 'int':
6451  if (!is_numeric($value) && $value != '') {
6452  $this->errors[] = $langs->trans("ExtraLanguageHasWrongValue", $attributeLabel);
6453  return -1;
6454  } elseif ($value == '') {
6455  $new_array_languages[$key] = null;
6456  }
6457  break;
6458  case 'double':
6459  $value = price2num($value);
6460  if (!is_numeric($value) && $value != '') {
6461  dol_syslog($langs->trans("ExtraLanguageHasWrongValue")." sur ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
6462  $this->errors[] = $langs->trans("ExtraLanguageHasWrongValue", $attributeLabel);
6463  return -1;
6464  } elseif ($value == '') {
6465  $new_array_languages[$key] = null;
6466  }
6467  //dol_syslog("double value"." sur ".$attributeLabel."(".$value." is '".$attributeType."')", LOG_DEBUG);
6468  $new_array_languages[$key] = $value;
6469  break;
6470  /*case 'select': // Not required, we chosed value='0' for undefined values
6471  if ($value=='-1')
6472  {
6473  $this->array_options[$key] = null;
6474  }
6475  break;*/
6476  }
6477  }
6478 
6479  $this->db->begin();
6480 
6481  $table_element = $this->table_element;
6482  if ($table_element == 'categorie') {
6483  $table_element = 'categories'; // For compatibility
6484  }
6485 
6486  dol_syslog(get_class($this)."::insertExtraLanguages delete then insert", LOG_DEBUG);
6487 
6488  foreach ($new_array_languages as $key => $langcodearray) { // $key = 'name', 'town', ...
6489  foreach ($langcodearray as $langcode => $value) {
6490  $sql_del = "DELETE FROM ".$this->db->prefix()."object_lang";
6491  $sql_del .= " WHERE fk_object = ".((int) $this->id)." AND property = '".$this->db->escape($key)."' AND type_object = '".$this->db->escape($table_element)."'";
6492  $sql_del .= " AND lang = '".$this->db->escape($langcode)."'";
6493  $this->db->query($sql_del);
6494 
6495  if ($value !== '') {
6496  $sql = "INSERT INTO ".$this->db->prefix()."object_lang (fk_object, property, type_object, lang, value";
6497  $sql .= ") VALUES (".$this->id.", '".$this->db->escape($key)."', '".$this->db->escape($table_element)."', '".$this->db->escape($langcode)."', '".$this->db->escape($value)."'";
6498  $sql .= ")";
6499 
6500  $resql = $this->db->query($sql);
6501  if (!$resql) {
6502  $this->error = $this->db->lasterror();
6503  $error++;
6504  break;
6505  }
6506  }
6507  }
6508  }
6509 
6510  if (!$error && $trigger) {
6511  // Call trigger
6512  $this->context = array('extralanguagesaddupdate'=>1);
6513  $result = $this->call_trigger($trigger, $userused);
6514  if ($result < 0) {
6515  $error++;
6516  }
6517  // End call trigger
6518  }
6519 
6520  if ($error) {
6521  $this->db->rollback();
6522  return -1;
6523  } else {
6524  $this->db->commit();
6525  return 1;
6526  }
6527  } else {
6528  return 0;
6529  }
6530  }
6531 
6542  public function updateExtraField($key, $trigger = null, $userused = null)
6543  {
6544  global $conf, $langs, $user;
6545 
6546  if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
6547  return 0;
6548  }
6549 
6550  if (empty($userused)) {
6551  $userused = $user;
6552  }
6553 
6554  $error = 0;
6555 
6556  if (!empty($this->array_options) && isset($this->array_options["options_".$key])) {
6557  // Check parameters
6558  $langs->load('admin');
6559  require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
6560  $extrafields = new ExtraFields($this->db);
6561  $extrafields->fetch_name_optionals_label($this->table_element);
6562 
6563  $value = $this->array_options["options_".$key];
6564 
6565  $attributeType = $extrafields->attributes[$this->table_element]['type'][$key];
6566  $attributeLabel = $extrafields->attributes[$this->table_element]['label'][$key];
6567  $attributeParam = $extrafields->attributes[$this->table_element]['param'][$key];
6568  $attributeRequired = $extrafields->attributes[$this->table_element]['required'][$key];
6569  $attrfieldcomputed = $extrafields->attributes[$this->table_element]['computed'][$key];
6570 
6571  // Similar code than into insertExtraFields
6572  if ($attributeRequired) {
6573  $mandatorypb = false;
6574  if ($attributeType == 'link' && $this->array_options["options_".$key] == '-1') {
6575  $mandatorypb = true;
6576  }
6577  if ($this->array_options["options_".$key] === '') {
6578  $mandatorypb = true;
6579  }
6580  if ($mandatorypb) {
6581  $langs->load("errors");
6582  dol_syslog("Mandatory field 'options_".$key."' is empty during update and set to required into definition of extrafields");
6583  $this->errors[] = $langs->trans('ErrorFieldRequired', $attributeLabel);
6584  return -1;
6585  }
6586  }
6587 
6588  //dol_syslog("attributeLabel=".$attributeLabel, LOG_DEBUG);
6589  //dol_syslog("attributeType=".$attributeType, LOG_DEBUG);
6590 
6591  if (!empty($attrfieldcomputed)) {
6592  if (!empty($conf->global->MAIN_STORE_COMPUTED_EXTRAFIELDS)) {
6593  $value = dol_eval($attrfieldcomputed, 1, 0, '');
6594  dol_syslog($langs->trans("Extrafieldcomputed")." sur ".$attributeLabel."(".$value.")", LOG_DEBUG);
6595  $this->array_options["options_".$key] = $value;
6596  } else {
6597  $this->array_options["options_".$key] = null;
6598  }
6599  }
6600 
6601  switch ($attributeType) {
6602  case 'int':
6603  if (!is_numeric($value) && $value != '') {
6604  $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
6605  return -1;
6606  } elseif ($value === '') {
6607  $this->array_options["options_".$key] = null;
6608  }
6609  break;
6610  case 'double':
6611  $value = price2num($value);
6612  if (!is_numeric($value) && $value != '') {
6613  dol_syslog($langs->trans("ExtraFieldHasWrongValue")." sur ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
6614  $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
6615  return -1;
6616  } elseif ($value === '') {
6617  $value = null;
6618  }
6619  //dol_syslog("double value"." sur ".$attributeLabel."(".$value." is '".$attributeType."')", LOG_DEBUG);
6620  $this->array_options["options_".$key] = $value;
6621  break;
6622  /*case 'select': // Not required, we chosed value='0' for undefined values
6623  if ($value=='-1')
6624  {
6625  $this->array_options[$key] = null;
6626  }
6627  break;*/
6628  case 'price':
6629  $this->array_options["options_".$key] = price2num($this->array_options["options_".$key]);
6630  break;
6631  case 'date':
6632  case 'datetime':
6633  if (empty($this->array_options["options_".$key])) {
6634  $this->array_options["options_".$key] = null;
6635  } else {
6636  $this->array_options["options_".$key] = $this->db->idate($this->array_options["options_".$key]);
6637  }
6638  break;
6639  case 'boolean':
6640  if (empty($this->array_options["options_".$key])) {
6641  $this->array_options["options_".$key] = null;
6642  }
6643  break;
6644  case 'link':
6645  if ($this->array_options["options_".$key] === '') {
6646  $this->array_options["options_".$key] = null;
6647  }
6648  break;
6649  /*
6650  case 'link':
6651  $param_list = array_keys($attributeParam['options']);
6652  // 0 : ObjectName
6653  // 1 : classPath
6654  $InfoFieldList = explode(":", $param_list[0]);
6655  dol_include_once($InfoFieldList[1]);
6656  if ($InfoFieldList[0] && class_exists($InfoFieldList[0]))
6657  {
6658  if ($value == '-1') // -1 is key for no defined in combo list of objects
6659  {
6660  $new_array_options[$key] = '';
6661  } elseif ($value) {
6662  $object = new $InfoFieldList[0]($this->db);
6663  if (is_numeric($value)) $res = $object->fetch($value); // Common case
6664  else $res = $object->fetch('', $value); // For compatibility
6665 
6666  if ($res > 0) $new_array_options[$key] = $object->id;
6667  else {
6668  $this->error = "Id/Ref '".$value."' for object '".$object->element."' not found";
6669  $this->db->rollback();
6670  return -1;
6671  }
6672  }
6673  } else {
6674  dol_syslog('Error bad setup of extrafield', LOG_WARNING);
6675  }
6676  break;
6677  */
6678  }
6679 
6680  $this->db->begin();
6681 
6682  $linealreadyfound = 0;
6683 
6684  // 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)
6685  $sql = "SELECT COUNT(rowid) as nb FROM ".$this->db->prefix().$this->table_element."_extrafields WHERE fk_object = ".((int) $this->id);
6686  $resql = $this->db->query($sql);
6687  if ($resql) {
6688  $tmpobj = $this->db->fetch_object($resql);
6689  if ($tmpobj) {
6690  $linealreadyfound = $tmpobj->nb;
6691  }
6692  }
6693 
6694  if ($linealreadyfound) {
6695  if ($this->array_options["options_".$key] === null) {
6696  $sql = "UPDATE ".$this->db->prefix().$this->table_element."_extrafields SET ".$key." = null";
6697  } else {
6698  $sql = "UPDATE ".$this->db->prefix().$this->table_element."_extrafields SET ".$key." = '".$this->db->escape($this->array_options["options_".$key])."'";
6699  }
6700  $sql .= " WHERE fk_object = ".((int) $this->id);
6701  } else {
6702  $result = $this->insertExtraFields('', $user);
6703  if ($result < 0) {
6704  $error++;
6705  }
6706  }
6707 
6708  $resql = $this->db->query($sql);
6709  if (!$resql) {
6710  $error++;
6711  $this->error = $this->db->lasterror();
6712  }
6713  if (!$error && $trigger) {
6714  // Call trigger
6715  $this->context = array('extrafieldupdate'=>1);
6716  $result = $this->call_trigger($trigger, $userused);
6717  if ($result < 0) {
6718  $error++;
6719  }
6720  // End call trigger
6721  }
6722 
6723  if ($error) {
6724  dol_syslog(__METHOD__.$this->error, LOG_ERR);
6725  $this->db->rollback();
6726  return -1;
6727  } else {
6728  $this->db->commit();
6729  return 1;
6730  }
6731  } else {
6732  return 0;
6733  }
6734  }
6735 
6746  public function updateExtraLanguages($key, $trigger = null, $userused = null)
6747  {
6748  global $conf, $langs, $user;
6749 
6750  if (empty($userused)) {
6751  $userused = $user;
6752  }
6753 
6754  $error = 0;
6755 
6756  if (!empty($conf->global->MAIN_EXTRALANGUAGES_DISABLED)) {
6757  return 0; // For avoid conflicts if trigger used
6758  }
6759 
6760  return 0;
6761  }
6762 
6763 
6778  public function showInputField($val, $key, $value, $moreparam = '', $keysuffix = '', $keyprefix = '', $morecss = 0, $nonewbutton = 0)
6779  {
6780  global $conf, $langs, $form;
6781 
6782  if (!is_object($form)) {
6783  require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
6784  $form = new Form($this->db);
6785  }
6786 
6787  if (!empty($this->fields)) {
6788  $val = $this->fields[$key];
6789  }
6790 
6791  // Validation tests and output
6792  $fieldValidationErrorMsg = '';
6793  $validationClass = '';
6794  $fieldValidationErrorMsg = $this->getFieldError($key);
6795  if (!empty($fieldValidationErrorMsg)) {
6796  $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
6797  } else {
6798  $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
6799  }
6800 
6801  $out = '';
6802  $type = '';
6803  $isDependList = 0;
6804  $param = array();
6805  $param['options'] = array();
6806  $reg = array();
6807  $size = !empty($this->fields[$key]['size']) ? $this->fields[$key]['size'] : 0;
6808  // Because we work on extrafields
6809  if (preg_match('/^(integer|link):(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
6810  $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4].':'.$reg[5] => 'N');
6811  $type = 'link';
6812  } elseif (preg_match('/^(integer|link):(.*):(.*):(.*)/i', $val['type'], $reg)) {
6813  $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4] => 'N');
6814  $type = 'link';
6815  } elseif (preg_match('/^(integer|link):(.*):(.*)/i', $val['type'], $reg)) {
6816  $param['options'] = array($reg[2].':'.$reg[3] => 'N');
6817  $type = 'link';
6818  } elseif (preg_match('/^(sellist):(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
6819  $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4].':'.$reg[5] => 'N');
6820  $type = 'sellist';
6821  } elseif (preg_match('/^(sellist):(.*):(.*):(.*)/i', $val['type'], $reg)) {
6822  $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4] => 'N');
6823  $type = 'sellist';
6824  } elseif (preg_match('/^(sellist):(.*):(.*)/i', $val['type'], $reg)) {
6825  $param['options'] = array($reg[2].':'.$reg[3] => 'N');
6826  $type = 'sellist';
6827  } elseif (preg_match('/varchar\((\d+)\)/', $val['type'], $reg)) {
6828  $param['options'] = array();
6829  $type = 'varchar';
6830  $size = $reg[1];
6831  } elseif (preg_match('/varchar/', $val['type'])) {
6832  $param['options'] = array();
6833  $type = 'varchar';
6834  } else {
6835  $param['options'] = array();
6836  $type = $this->fields[$key]['type'];
6837  }
6838 
6839  // Special case that force options and type ($type can be integer, varchar, ...)
6840  if (!empty($this->fields[$key]['arrayofkeyval']) && is_array($this->fields[$key]['arrayofkeyval'])) {
6841  $param['options'] = $this->fields[$key]['arrayofkeyval'];
6842  $type = 'select';
6843  }
6844 
6845  $label = $this->fields[$key]['label'];
6846  //$elementtype=$this->fields[$key]['elementtype']; // Seems not used
6847  $default = (!empty($this->fields[$key]['default']) ? $this->fields[$key]['default'] : '');
6848  $computed = (!empty($this->fields[$key]['computed']) ? $this->fields[$key]['computed'] : '');
6849  $unique = (!empty($this->fields[$key]['unique']) ? $this->fields[$key]['unique'] : 0);
6850  $required = (!empty($this->fields[$key]['required']) ? $this->fields[$key]['required'] : 0);
6851  $autofocusoncreate = (!empty($this->fields[$key]['autofocusoncreate']) ? $this->fields[$key]['autofocusoncreate'] : 0);
6852 
6853  $langfile = (!empty($this->fields[$key]['langfile']) ? $this->fields[$key]['langfile'] : '');
6854  $list = (!empty($this->fields[$key]['list']) ? $this->fields[$key]['list'] : 0);
6855  $hidden = (in_array(abs($this->fields[$key]['visible']), array(0, 2)) ? 1 : 0);
6856 
6857  $objectid = $this->id;
6858 
6859  if ($computed) {
6860  if (!preg_match('/^search_/', $keyprefix)) {
6861  return '<span class="opacitymedium">'.$langs->trans("AutomaticallyCalculated").'</span>';
6862  } else {
6863  return '';
6864  }
6865  }
6866 
6867  // Set value of $morecss. For this, we use in priority showsize from parameters, then $val['css'] then autodefine
6868  if (empty($morecss) && !empty($val['css'])) {
6869  $morecss = $val['css'];
6870  } elseif (empty($morecss)) {
6871  if ($type == 'date') {
6872  $morecss = 'minwidth100imp';
6873  } elseif ($type == 'datetime' || $type == 'link') { // link means an foreign key to another primary id
6874  $morecss = 'minwidth200imp';
6875  } elseif (in_array($type, array('int', 'integer', 'price')) || preg_match('/^double(\([0-9],[0-9]\)){0,1}/', $type)) {
6876  $morecss = 'maxwidth75';
6877  } elseif ($type == 'url') {
6878  $morecss = 'minwidth400';
6879  } elseif ($type == 'boolean') {
6880  $morecss = '';
6881  } else {
6882  if (round($size) < 12) {
6883  $morecss = 'minwidth100';
6884  } elseif (round($size) <= 48) {
6885  $morecss = 'minwidth200';
6886  } else {
6887  $morecss = 'minwidth400';
6888  }
6889  }
6890  }
6891 
6892  // Add validation state class
6893  if (!empty($validationClass)) {
6894  $morecss.= $validationClass;
6895  }
6896 
6897  if (in_array($type, array('date'))) {
6898  $tmp = explode(',', $size);
6899  $newsize = $tmp[0];
6900  $showtime = 0;
6901 
6902  // Do not show current date when field not required (see selectDate() method)
6903  if (!$required && $value == '') {
6904  $value = '-1';
6905  }
6906 
6907  // TODO Must also support $moreparam
6908  $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required, '', 1, (($keyprefix != 'search_' && $keyprefix != 'search_options_') ? 1 : 0), 0, 1);
6909  } elseif (in_array($type, array('datetime'))) {
6910  $tmp = explode(',', $size);
6911  $newsize = $tmp[0];
6912  $showtime = 1;
6913 
6914  // Do not show current date when field not required (see selectDate() method)
6915  if (!$required && $value == '') $value = '-1';
6916 
6917  // TODO Must also support $moreparam
6918  $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required, '', 1, (($keyprefix != 'search_' && $keyprefix != 'search_options_') ? 1 : 0), 0, 1, '', '', '', 1, '', '', 'tzuserrel');
6919  } elseif (in_array($type, array('duration'))) {
6920  $out = $form->select_duration($keyprefix.$key.$keysuffix, $value, 0, 'text', 0, 1);
6921  } elseif (in_array($type, array('int', 'integer'))) {
6922  $tmp = explode(',', $size);
6923  $newsize = $tmp[0];
6924  $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' : '').'>';
6925  } elseif (in_array($type, array('real'))) {
6926  $out = '<input type="text" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'"'.($moreparam ? $moreparam : '').($autofocusoncreate ? ' autofocus' : '').'>';
6927  } elseif (preg_match('/varchar/', $type)) {
6928  $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' : '').'>';
6929  } elseif (in_array($type, array('email', 'mail', 'phone', 'url'))) {
6930  $out = '<input type="text" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').($autofocusoncreate ? ' autofocus' : '').'>';
6931  } elseif (preg_match('/^text/', $type)) {
6932  if (!preg_match('/search_/', $keyprefix)) { // If keyprefix is search_ or search_options_, we must just use a simple text field
6933  require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
6934  $doleditor = new DolEditor($keyprefix.$key.$keysuffix, $value, '', 200, 'dolibarr_notes', 'In', false, false, false, ROWS_5, '90%');
6935  $out = $doleditor->Create(1);
6936  } else {
6937  $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').'>';
6938  }
6939  } elseif (preg_match('/^html/', $type)) {
6940  if (!preg_match('/search_/', $keyprefix)) { // If keyprefix is search_ or search_options_, we must just use a simple text field
6941  require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
6942  $doleditor = new DolEditor($keyprefix.$key.$keysuffix, $value, '', 200, 'dolibarr_notes', 'In', false, false, !empty($conf->fckeditor->enabled) && $conf->global->FCKEDITOR_ENABLE_SOCIETE, ROWS_5, '90%');
6943  $out = $doleditor->Create(1, '', true, '', '', $moreparam, $morecss);
6944  } else {
6945  $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').'>';
6946  }
6947  } elseif ($type == 'boolean') {
6948  $checked = '';
6949  if (!empty($value)) {
6950  $checked = ' checked value="1" ';
6951  } else {
6952  $checked = ' value="1" ';
6953  }
6954  $out = '<input type="checkbox" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.$checked.' '.($moreparam ? $moreparam : '').'>';
6955  } elseif ($type == 'price') {
6956  if (!empty($value)) { // $value in memory is a php numeric, we format it into user number format.
6957  $value = price($value);
6958  }
6959  $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'> '.$langs->getCurrencySymbol($conf->currency);
6960  } elseif (preg_match('/^double(\([0-9],[0-9]\)){0,1}/', $type)) {
6961  if (!empty($value)) { // $value in memory is a php numeric, we format it into user number format.
6962  $value = price($value);
6963  }
6964  $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'> ';
6965  } elseif ($type == 'select') {
6966  $out = '';
6967  if (!empty($conf->use_javascript_ajax) && empty($conf->global->MAIN_EXTRAFIELDS_DISABLE_SELECT2)) {
6968  include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
6969  $out .= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
6970  }
6971 
6972  $out .= '<select class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '').'>';
6973  if ((!isset($this->fields[$key]['default'])) || ($this->fields[$key]['notnull'] != 1)) {
6974  $out .= '<option value="0">&nbsp;</option>';
6975  }
6976  foreach ($param['options'] as $keyb => $valb) {
6977  if ((string) $keyb == '') {
6978  continue;
6979  }
6980  if (strpos($valb, "|") !== false) {
6981  list($valb, $parent) = explode('|', $valb);
6982  }
6983  $out .= '<option value="'.$keyb.'"';
6984  $out .= (((string) $value == (string) $keyb) ? ' selected' : '');
6985  $out .= (!empty($parent) ? ' parent="'.$parent.'"' : '');
6986  $out .= '>'.$valb.'</option>';
6987  }
6988  $out .= '</select>';
6989  } elseif ($type == 'sellist') {
6990  $out = '';
6991  if (!empty($conf->use_javascript_ajax) && empty($conf->global->MAIN_EXTRAFIELDS_DISABLE_SELECT2)) {
6992  include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
6993  $out .= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
6994  }
6995 
6996  $out .= '<select class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '').'>';
6997  if (is_array($param['options'])) {
6998  $param_list = array_keys($param['options']);
6999  $InfoFieldList = explode(":", $param_list[0]);
7000  $parentName = '';
7001  $parentField = '';
7002  // 0 : tableName
7003  // 1 : label field name
7004  // 2 : key fields name (if differ of rowid)
7005  // 3 : key field parent (for dependent lists)
7006  // 4 : where clause filter on column or table extrafield, syntax field='value' or extra.field=value
7007  $keyList = (empty($InfoFieldList[2]) ? 'rowid' : $InfoFieldList[2].' as rowid');
7008 
7009  if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
7010  if (strpos($InfoFieldList[4], 'extra.') !== false) {
7011  $keyList = 'main.'.$InfoFieldList[2].' as rowid';
7012  } else {
7013  $keyList = $InfoFieldList[2].' as rowid';
7014  }
7015  }
7016  if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
7017  list($parentName, $parentField) = explode('|', $InfoFieldList[3]);
7018  $keyList .= ', '.$parentField;
7019  }
7020 
7021  $fields_label = explode('|', $InfoFieldList[1]);
7022  if (is_array($fields_label)) {
7023  $keyList .= ', ';
7024  $keyList .= implode(', ', $fields_label);
7025  }
7026 
7027  $sqlwhere = '';
7028  $sql = "SELECT ".$keyList;
7029  $sql .= " FROM ".$this->db->prefix().$InfoFieldList[0];
7030  if (!empty($InfoFieldList[4])) {
7031  // can use SELECT request
7032  if (strpos($InfoFieldList[4], '$SEL$') !== false) {
7033  $InfoFieldList[4] = str_replace('$SEL$', 'SELECT', $InfoFieldList[4]);
7034  }
7035 
7036  // current object id can be use into filter
7037  if (strpos($InfoFieldList[4], '$ID$') !== false && !empty($objectid)) {
7038  $InfoFieldList[4] = str_replace('$ID$', $objectid, $InfoFieldList[4]);
7039  } else {
7040  $InfoFieldList[4] = str_replace('$ID$', '0', $InfoFieldList[4]);
7041  }
7042 
7043  //We have to join on extrafield table
7044  if (strpos($InfoFieldList[4], 'extra') !== false) {
7045  $sql .= " as main, ".$this->db->prefix().$InfoFieldList[0]."_extrafields as extra";
7046  $sqlwhere .= " WHERE extra.fk_object=main.".$InfoFieldList[2]." AND ".$InfoFieldList[4];
7047  } else {
7048  $sqlwhere .= " WHERE ".$InfoFieldList[4];
7049  }
7050  } else {
7051  $sqlwhere .= ' WHERE 1=1';
7052  }
7053  // Some tables may have field, some other not. For the moment we disable it.
7054  if (in_array($InfoFieldList[0], array('tablewithentity'))) {
7055  $sqlwhere .= " AND entity = ".((int) $conf->entity);
7056  }
7057  $sql .= $sqlwhere;
7058  //print $sql;
7059 
7060  $sql .= ' ORDER BY '.implode(', ', $fields_label);
7061 
7062  dol_syslog(get_class($this).'::showInputField type=sellist', LOG_DEBUG);
7063  $resql = $this->db->query($sql);
7064  if ($resql) {
7065  $out .= '<option value="0">&nbsp;</option>';
7066  $num = $this->db->num_rows($resql);
7067  $i = 0;
7068  while ($i < $num) {
7069  $labeltoshow = '';
7070  $obj = $this->db->fetch_object($resql);
7071 
7072  // Several field into label (eq table:code|libelle:rowid)
7073  $notrans = false;
7074  $fields_label = explode('|', $InfoFieldList[1]);
7075  if (count($fields_label) > 1) {
7076  $notrans = true;
7077  foreach ($fields_label as $field_toshow) {
7078  $labeltoshow .= $obj->$field_toshow.' ';
7079  }
7080  } else {
7081  $labeltoshow = $obj->{$InfoFieldList[1]};
7082  }
7083  $labeltoshow = dol_trunc($labeltoshow, 45);
7084 
7085  if ($value == $obj->rowid) {
7086  foreach ($fields_label as $field_toshow) {
7087  $translabel = $langs->trans($obj->$field_toshow);
7088  if ($translabel != $obj->$field_toshow) {
7089  $labeltoshow = dol_trunc($translabel).' ';
7090  } else {
7091  $labeltoshow = dol_trunc($obj->$field_toshow).' ';
7092  }
7093  }
7094  $out .= '<option value="'.$obj->rowid.'" selected>'.$labeltoshow.'</option>';
7095  } else {
7096  if (!$notrans) {
7097  $translabel = $langs->trans($obj->{$InfoFieldList[1]});
7098  if ($translabel != $obj->{$InfoFieldList[1]}) {
7099  $labeltoshow = dol_trunc($translabel, 18);
7100  } else {
7101  $labeltoshow = dol_trunc($obj->{$InfoFieldList[1]});
7102  }
7103  }
7104  if (empty($labeltoshow)) {
7105  $labeltoshow = '(not defined)';
7106  }
7107  if ($value == $obj->rowid) {
7108  $out .= '<option value="'.$obj->rowid.'" selected>'.$labeltoshow.'</option>';
7109  }
7110 
7111  if (!empty($InfoFieldList[3]) && $parentField) {
7112  $parent = $parentName.':'.$obj->{$parentField};
7113  $isDependList = 1;
7114  }
7115 
7116  $out .= '<option value="'.$obj->rowid.'"';
7117  $out .= ($value == $obj->rowid ? ' selected' : '');
7118  $out .= (!empty($parent) ? ' parent="'.$parent.'"' : '');
7119  $out .= '>'.$labeltoshow.'</option>';
7120  }
7121 
7122  $i++;
7123  }
7124  $this->db->free($resql);
7125  } else {
7126  print 'Error in request '.$sql.' '.$this->db->lasterror().'. Check setup of extra parameters.<br>';
7127  }
7128  }
7129  $out .= '</select>';
7130  } elseif ($type == 'checkbox') {
7131  $value_arr = explode(',', $value);
7132  $out = $form->multiselectarray($keyprefix.$key.$keysuffix, (empty($param['options']) ?null:$param['options']), $value_arr, '', 0, $morecss, 0, '100%');
7133  } elseif ($type == 'radio') {
7134  $out = '';
7135  foreach ($param['options'] as $keyopt => $valopt) {
7136  $out .= '<input class="flat '.$morecss.'" type="radio" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '');
7137  $out .= ' value="'.$keyopt.'"';
7138  $out .= ' id="'.$keyprefix.$key.$keysuffix.'_'.$keyopt.'"';
7139  $out .= ($value == $keyopt ? 'checked' : '');
7140  $out .= '/><label for="'.$keyprefix.$key.$keysuffix.'_'.$keyopt.'">'.$valopt.'</label><br>';
7141  }
7142  } elseif ($type == 'chkbxlst') {
7143  if (is_array($value)) {
7144  $value_arr = $value;
7145  } else {
7146  $value_arr = explode(',', $value);
7147  }
7148 
7149  if (is_array($param['options'])) {
7150  $param_list = array_keys($param['options']);
7151  $InfoFieldList = explode(":", $param_list[0]);
7152  $parentName = '';
7153  $parentField = '';
7154  // 0 : tableName
7155  // 1 : label field name
7156  // 2 : key fields name (if differ of rowid)
7157  // 3 : key field parent (for dependent lists)
7158  // 4 : where clause filter on column or table extrafield, syntax field='value' or extra.field=value
7159  $keyList = (empty($InfoFieldList[2]) ? 'rowid' : $InfoFieldList[2].' as rowid');
7160 
7161  if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
7162  list ($parentName, $parentField) = explode('|', $InfoFieldList[3]);
7163  $keyList .= ', '.$parentField;
7164  }
7165  if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
7166  if (strpos($InfoFieldList[4], 'extra.') !== false) {
7167  $keyList = 'main.'.$InfoFieldList[2].' as rowid';
7168  } else {
7169  $keyList = $InfoFieldList[2].' as rowid';
7170  }
7171  }
7172 
7173  $fields_label = explode('|', $InfoFieldList[1]);
7174  if (is_array($fields_label)) {
7175  $keyList .= ', ';
7176  $keyList .= implode(', ', $fields_label);
7177  }
7178 
7179  $sqlwhere = '';
7180  $sql = "SELECT ".$keyList;
7181  $sql .= ' FROM '.$this->db->prefix().$InfoFieldList[0];
7182  if (!empty($InfoFieldList[4])) {
7183  // can use SELECT request
7184  if (strpos($InfoFieldList[4], '$SEL$') !== false) {
7185  $InfoFieldList[4] = str_replace('$SEL$', 'SELECT', $InfoFieldList[4]);
7186  }
7187 
7188  // current object id can be use into filter
7189  if (strpos($InfoFieldList[4], '$ID$') !== false && !empty($objectid)) {
7190  $InfoFieldList[4] = str_replace('$ID$', $objectid, $InfoFieldList[4]);
7191  } else {
7192  $InfoFieldList[4] = str_replace('$ID$', '0', $InfoFieldList[4]);
7193  }
7194 
7195  // We have to join on extrafield table
7196  if (strpos($InfoFieldList[4], 'extra') !== false) {
7197  $sql .= ' as main, '.$this->db->prefix().$InfoFieldList[0].'_extrafields as extra';
7198  $sqlwhere .= " WHERE extra.fk_object=main.".$InfoFieldList[2]." AND ".$InfoFieldList[4];
7199  } else {
7200  $sqlwhere .= " WHERE ".$InfoFieldList[4];
7201  }
7202  } else {
7203  $sqlwhere .= ' WHERE 1=1';
7204  }
7205  // Some tables may have field, some other not. For the moment we disable it.
7206  if (in_array($InfoFieldList[0], array('tablewithentity'))) {
7207  $sqlwhere .= " AND entity = ".((int) $conf->entity);
7208  }
7209  // $sql.=preg_replace('/^ AND /','',$sqlwhere);
7210  // print $sql;
7211 
7212  $sql .= $sqlwhere;
7213  dol_syslog(get_class($this).'::showInputField type=chkbxlst', LOG_DEBUG);
7214  $resql = $this->db->query($sql);
7215  if ($resql) {
7216  $num = $this->db->num_rows($resql);
7217  $i = 0;
7218 
7219  $data = array();
7220 
7221  while ($i < $num) {
7222  $labeltoshow = '';
7223  $obj = $this->db->fetch_object($resql);
7224 
7225  $notrans = false;
7226  // Several field into label (eq table:code|libelle:rowid)
7227  $fields_label = explode('|', $InfoFieldList[1]);
7228  if (count($fields_label) > 1) {
7229  $notrans = true;
7230  foreach ($fields_label as $field_toshow) {
7231  $labeltoshow .= $obj->$field_toshow.' ';
7232