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