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_string_nohtmltag(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  $error = 0;
1294 
1295  $this->db->begin();
1296 
1297  if (!$error && empty($notrigger)) {
1298  // Call trigger
1299  $this->context['contact_id'] = ((int) $rowid);
1300  $result = $this->call_trigger(strtoupper($this->element).'_DELETE_CONTACT', $user);
1301  if ($result < 0) {
1302  $error++;
1303  }
1304  // End call triggers
1305  }
1306 
1307  if (!$error) {
1308  dol_syslog(get_class($this)."::delete_contact", LOG_DEBUG);
1309 
1310  $sql = "DELETE FROM ".MAIN_DB_PREFIX."element_contact";
1311  $sql .= " WHERE rowid = ".((int) $rowid);
1312 
1313  $result = $this->db->query($sql);
1314  if (!$result) {
1315  $error++;
1316  $this->errors[] = $this->db->lasterror();
1317  }
1318  }
1319 
1320  if (!$error) {
1321  $this->db->commit();
1322  return 1;
1323  } else {
1324  $this->error = $this->db->lasterror();
1325  $this->db->rollback();
1326  return -1;
1327  }
1328  }
1329 
1330  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1338  public function delete_linked_contact($source = '', $code = '')
1339  {
1340  // phpcs:enable
1341  $listId = '';
1342  $temp = array();
1343  $typeContact = $this->liste_type_contact($source, '', 0, 0, $code);
1344 
1345  if (!empty($typeContact)) {
1346  foreach ($typeContact as $key => $value) {
1347  array_push($temp, $key);
1348  }
1349  $listId = implode(",", $temp);
1350  }
1351 
1352  // If $listId is empty, we have not criteria on fk_c_type_contact so we will delete record on element_id for
1353  // any type or record instead of only the ones of the current object. So we do nothing in such a case.
1354  if (empty($listId)) {
1355  return 0;
1356  }
1357 
1358  $sql = "DELETE FROM ".$this->db->prefix()."element_contact";
1359  $sql .= " WHERE element_id = ".((int) $this->id);
1360  $sql .= " AND fk_c_type_contact IN (".$this->db->sanitize($listId).")";
1361 
1362  dol_syslog(get_class($this)."::delete_linked_contact", LOG_DEBUG);
1363  if ($this->db->query($sql)) {
1364  return 1;
1365  } else {
1366  $this->error = $this->db->lasterror();
1367  return -1;
1368  }
1369  }
1370 
1371  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1383  public function liste_contact($statusoflink = -1, $source = 'external', $list = 0, $code = '', $status = -1, $arrayoftcids = array())
1384  {
1385  // phpcs:enable
1386  global $langs;
1387 
1388  $tab = array();
1389 
1390  $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
1391  if ($source == 'internal') {
1392  $sql .= ", '-1' as socid, t.statut as statuscontact, t.login, t.photo";
1393  }
1394  if ($source == 'external' || $source == 'thirdparty') {
1395  $sql .= ", t.fk_soc as socid, t.statut as statuscontact";
1396  }
1397  $sql .= ", t.civility as civility, t.lastname as lastname, t.firstname, t.email";
1398  $sql .= ", tc.source, tc.element, tc.code, tc.libelle";
1399  $sql .= " FROM ".$this->db->prefix()."c_type_contact tc";
1400  $sql .= ", ".$this->db->prefix()."element_contact ec";
1401  if ($source == 'internal') { // internal contact (user)
1402  $sql .= " LEFT JOIN ".$this->db->prefix()."user t on ec.fk_socpeople = t.rowid";
1403  }
1404  if ($source == 'external' || $source == 'thirdparty') { // external contact (socpeople)
1405  $sql .= " LEFT JOIN ".$this->db->prefix()."socpeople t on ec.fk_socpeople = t.rowid";
1406  }
1407  $sql .= " WHERE ec.element_id = ".((int) $this->id);
1408  $sql .= " AND ec.fk_c_type_contact = tc.rowid";
1409  $sql .= " AND tc.element = '".$this->db->escape($this->element)."'";
1410  if ($code) {
1411  $sql .= " AND tc.code = '".$this->db->escape($code)."'";
1412  }
1413  if ($source == 'internal') {
1414  $sql .= " AND tc.source = 'internal'";
1415  if ($status >= 0) {
1416  $sql .= " AND t.statut = ".((int) $status);
1417  }
1418  }
1419  if ($source == 'external' || $source == 'thirdparty') {
1420  $sql .= " AND tc.source = 'external'";
1421  if ($status >= 0) {
1422  $sql .= " AND t.statut = ".((int) $status); // t is llx_socpeople
1423  }
1424  }
1425  $sql .= " AND tc.active = 1";
1426  if ($statusoflink >= 0) {
1427  $sql .= " AND ec.statut = ".((int) $statusoflink);
1428  }
1429  $sql .= " ORDER BY t.lastname ASC";
1430 
1431  dol_syslog(get_class($this)."::liste_contact", LOG_DEBUG);
1432  $resql = $this->db->query($sql);
1433  if ($resql) {
1434  $num = $this->db->num_rows($resql);
1435  $i = 0;
1436  while ($i < $num) {
1437  $obj = $this->db->fetch_object($resql);
1438 
1439  if (!$list) {
1440  $transkey = "TypeContact_".$obj->element."_".$obj->source."_".$obj->code;
1441  $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle);
1442  $tab[$i] = array(
1443  'source' => $obj->source,
1444  'socid' => $obj->socid,
1445  'id' => $obj->id,
1446  'nom' => $obj->lastname, // For backward compatibility
1447  'civility' => $obj->civility,
1448  'lastname' => $obj->lastname,
1449  'firstname' => $obj->firstname,
1450  'email'=>$obj->email,
1451  'login'=> (empty($obj->login) ? '' : $obj->login),
1452  'photo' => (empty($obj->photo) ? '' : $obj->photo),
1453  'statuscontact' => $obj->statuscontact,
1454  'rowid' => $obj->rowid,
1455  'code' => $obj->code,
1456  'libelle' => $libelle_type,
1457  'status' => $obj->statuslink,
1458  'fk_c_type_contact' => $obj->fk_c_type_contact
1459  );
1460  } else {
1461  $tab[$i] = $obj->id;
1462  }
1463 
1464  $i++;
1465  }
1466 
1467  return $tab;
1468  } else {
1469  $this->error = $this->db->lasterror();
1470  dol_print_error($this->db);
1471  return -1;
1472  }
1473  }
1474 
1475 
1482  public function swapContactStatus($rowid)
1483  {
1484  $sql = "SELECT ec.datecreate, ec.statut, ec.fk_socpeople, ec.fk_c_type_contact,";
1485  $sql .= " tc.code, tc.libelle";
1486  $sql .= " FROM (".$this->db->prefix()."element_contact as ec, ".$this->db->prefix()."c_type_contact as tc)";
1487  $sql .= " WHERE ec.rowid =".((int) $rowid);
1488  $sql .= " AND ec.fk_c_type_contact=tc.rowid";
1489  $sql .= " AND tc.element = '".$this->db->escape($this->element)."'";
1490 
1491  dol_syslog(get_class($this)."::swapContactStatus", LOG_DEBUG);
1492  $resql = $this->db->query($sql);
1493  if ($resql) {
1494  $obj = $this->db->fetch_object($resql);
1495  $newstatut = ($obj->statut == 4) ? 5 : 4;
1496  $result = $this->update_contact($rowid, $newstatut);
1497  $this->db->free($resql);
1498  return $result;
1499  } else {
1500  $this->error = $this->db->error();
1501  dol_print_error($this->db);
1502  return -1;
1503  }
1504  }
1505 
1506  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1517  public function liste_type_contact($source = 'internal', $order = 'position', $option = 0, $activeonly = 0, $code = '')
1518  {
1519  // phpcs:enable
1520  global $langs;
1521 
1522  if (empty($order)) {
1523  $order = 'position';
1524  }
1525  if ($order == 'position') {
1526  $order .= ',code';
1527  }
1528 
1529  $tab = array();
1530  $sql = "SELECT DISTINCT tc.rowid, tc.code, tc.libelle, tc.position";
1531  $sql .= " FROM ".$this->db->prefix()."c_type_contact as tc";
1532  $sql .= " WHERE tc.element='".$this->db->escape($this->element)."'";
1533  if ($activeonly == 1) {
1534  $sql .= " AND tc.active=1"; // only the active types
1535  }
1536  if (!empty($source) && $source != 'all') {
1537  $sql .= " AND tc.source='".$this->db->escape($source)."'";
1538  }
1539  if (!empty($code)) {
1540  $sql .= " AND tc.code='".$this->db->escape($code)."'";
1541  }
1542  $sql .= $this->db->order($order, 'ASC');
1543 
1544  //print "sql=".$sql;
1545  $resql = $this->db->query($sql);
1546  if ($resql) {
1547  $num = $this->db->num_rows($resql);
1548  $i = 0;
1549  while ($i < $num) {
1550  $obj = $this->db->fetch_object($resql);
1551 
1552  $transkey = "TypeContact_".$this->element."_".$source."_".$obj->code;
1553  $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle);
1554  if (empty($option)) {
1555  $tab[$obj->rowid] = $libelle_type;
1556  } else {
1557  $tab[$obj->code] = $libelle_type;
1558  }
1559  $i++;
1560  }
1561  return $tab;
1562  } else {
1563  $this->error = $this->db->lasterror();
1564  //dol_print_error($this->db);
1565  return null;
1566  }
1567  }
1568 
1580  public function listeTypeContacts($source = 'internal', $option = 0, $activeonly = 0, $code = '', $element = '', $excludeelement = '')
1581  {
1582  global $langs, $conf;
1583 
1584  $langs->loadLangs(array('bills', 'contracts', 'interventions', 'orders', 'projects', 'propal', 'ticket', 'agenda'));
1585 
1586  $tab = array();
1587 
1588  $sql = "SELECT DISTINCT tc.rowid, tc.code, tc.libelle, tc.position, tc.element";
1589  $sql .= " FROM ".$this->db->prefix()."c_type_contact as tc";
1590 
1591  $sqlWhere = array();
1592  if (!empty($element)) {
1593  $sqlWhere[] = " tc.element='".$this->db->escape($element)."'";
1594  }
1595  if (!empty($excludeelement)) {
1596  $sqlWhere[] = " tc.element <> '".$this->db->escape($excludeelement)."'";
1597  }
1598 
1599  if ($activeonly == 1) {
1600  $sqlWhere[] = " tc.active=1"; // only the active types
1601  }
1602 
1603  if (!empty($source) && $source != 'all') {
1604  $sqlWhere[] = " tc.source='".$this->db->escape($source)."'";
1605  }
1606 
1607  if (!empty($code)) {
1608  $sqlWhere[] = " tc.code='".$this->db->escape($code)."'";
1609  }
1610 
1611  if (count($sqlWhere) > 0) {
1612  $sql .= " WHERE ".implode(' AND ', $sqlWhere);
1613  }
1614 
1615  $sql .= $this->db->order('tc.element, tc.position', 'ASC');
1616 
1617  dol_syslog(__METHOD__, LOG_DEBUG);
1618  $resql = $this->db->query($sql);
1619  if ($resql) {
1620  $num = $this->db->num_rows($resql);
1621  if ($num > 0) {
1622  $langs->loadLangs(array("propal", "orders", "bills", "suppliers", "contracts", "supplier_proposal"));
1623 
1624  while ($obj = $this->db->fetch_object($resql)) {
1625  $modulename = $obj->element;
1626  if (strpos($obj->element, 'project') !== false) {
1627  $modulename = 'projet';
1628  } elseif ($obj->element == 'contrat') {
1629  $element = 'contract';
1630  } elseif ($obj->element == 'action') {
1631  $modulename = 'agenda';
1632  } elseif (strpos($obj->element, 'supplier') !== false && $obj->element != 'supplier_proposal') {
1633  $modulename = 'fournisseur';
1634  } elseif (strpos($obj->element, 'supplier') !== false && $obj->element != 'supplier_proposal') {
1635  $modulename = 'fournisseur';
1636  }
1637  if (!empty($conf->{$modulename}->enabled)) {
1638  $libelle_element = $langs->trans('ContactDefault_'.$obj->element);
1639  $tmpelement = $obj->element;
1640  $transkey = "TypeContact_".$tmpelement."_".$source."_".$obj->code;
1641  $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle);
1642  if (empty($option)) {
1643  $tab[$obj->rowid] = $libelle_element.' - '.$libelle_type;
1644  } else {
1645  $tab[$obj->rowid] = $libelle_element.' - '.$libelle_type;
1646  }
1647  }
1648  }
1649  }
1650  return $tab;
1651  } else {
1652  $this->error = $this->db->lasterror();
1653  return null;
1654  }
1655  }
1656 
1668  public function getIdContact($source, $code, $status = 0)
1669  {
1670  global $conf;
1671 
1672  $result = array();
1673  $i = 0;
1674  //cas particulier pour les expeditions
1675  if ($this->element == 'shipping' && $this->origin_id != 0) {
1676  $id = $this->origin_id;
1677  $element = 'commande';
1678  } elseif ($this->element == 'reception' && $this->origin_id != 0) {
1679  $id = $this->origin_id;
1680  $element = 'order_supplier';
1681  } else {
1682  $id = $this->id;
1683  $element = $this->element;
1684  }
1685 
1686  $sql = "SELECT ec.fk_socpeople";
1687  $sql .= " FROM ".$this->db->prefix()."element_contact as ec,";
1688  if ($source == 'internal') {
1689  $sql .= " ".$this->db->prefix()."user as c,";
1690  }
1691  if ($source == 'external') {
1692  $sql .= " ".$this->db->prefix()."socpeople as c,";
1693  }
1694  $sql .= " ".$this->db->prefix()."c_type_contact as tc";
1695  $sql .= " WHERE ec.element_id = ".((int) $id);
1696  $sql .= " AND ec.fk_socpeople = c.rowid";
1697  if ($source == 'internal') {
1698  $sql .= " AND c.entity IN (".getEntity('user').")";
1699  }
1700  if ($source == 'external') {
1701  $sql .= " AND c.entity IN (".getEntity('societe').")";
1702  }
1703  $sql .= " AND ec.fk_c_type_contact = tc.rowid";
1704  $sql .= " AND tc.element = '".$this->db->escape($element)."'";
1705  $sql .= " AND tc.source = '".$this->db->escape($source)."'";
1706  if ($code) {
1707  $sql .= " AND tc.code = '".$this->db->escape($code)."'";
1708  }
1709  $sql .= " AND tc.active = 1";
1710  if ($status) {
1711  $sql .= " AND ec.statut = ".((int) $status);
1712  }
1713 
1714  dol_syslog(get_class($this)."::getIdContact", LOG_DEBUG);
1715  $resql = $this->db->query($sql);
1716  if ($resql) {
1717  while ($obj = $this->db->fetch_object($resql)) {
1718  $result[$i] = $obj->fk_socpeople;
1719  $i++;
1720  }
1721  } else {
1722  $this->error = $this->db->error();
1723  return null;
1724  }
1725 
1726  return $result;
1727  }
1728 
1729  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1736  public function fetch_contact($contactid = null)
1737  {
1738  // phpcs:enable
1739  if (empty($contactid)) {
1740  $contactid = $this->contact_id;
1741  }
1742 
1743  if (empty($contactid)) {
1744  return 0;
1745  }
1746 
1747  require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
1748  $contact = new Contact($this->db);
1749  $result = $contact->fetch($contactid);
1750  $this->contact = $contact;
1751  return $result;
1752  }
1753 
1754  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1761  public function fetch_thirdparty($force_thirdparty_id = 0)
1762  {
1763  // phpcs:enable
1764  global $conf;
1765 
1766  if (empty($this->socid) && empty($this->fk_soc) && empty($force_thirdparty_id)) {
1767  return 0;
1768  }
1769 
1770  require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
1771 
1772  $idtofetch = isset($this->socid) ? $this->socid : (isset($this->fk_soc) ? $this->fk_soc : 0);
1773  if ($force_thirdparty_id) {
1774  $idtofetch = $force_thirdparty_id;
1775  }
1776 
1777  if ($idtofetch) {
1778  $thirdparty = new Societe($this->db);
1779  $result = $thirdparty->fetch($idtofetch);
1780  if ($result<0) {
1781  $this->errors=array_merge($this->errors, $thirdparty->errors);
1782  }
1783  $this->thirdparty = $thirdparty;
1784 
1785  // Use first price level if level not defined for third party
1786  if (!empty($conf->global->PRODUIT_MULTIPRICES) && empty($this->thirdparty->price_level)) {
1787  $this->thirdparty->price_level = 1;
1788  }
1789 
1790  return $result;
1791  } else {
1792  return -1;
1793  }
1794  }
1795 
1796 
1804  public function fetchOneLike($ref)
1805  {
1806  if (!$this->table_ref_field) {
1807  return 0;
1808  }
1809 
1810  $sql = "SELECT rowid FROM ".$this->db->prefix().$this->table_element." WHERE ".$this->table_ref_field." LIKE '".$this->db->escape($ref)."' LIMIT 1";
1811 
1812  $query = $this->db->query($sql);
1813 
1814  if (!$this->db->num_rows($query)) {
1815  return 0;
1816  }
1817 
1818  $result = $this->db->fetch_object($query);
1819 
1820  return $this->fetch($result->rowid);
1821  }
1822 
1823  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1831  public function fetch_barcode()
1832  {
1833  // phpcs:enable
1834  global $conf;
1835 
1836  dol_syslog(get_class($this).'::fetch_barcode this->element='.$this->element.' this->barcode_type='.$this->barcode_type);
1837 
1838  $idtype = $this->barcode_type;
1839  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
1840  if ($this->element == 'product' && !empty($conf->global->PRODUIT_DEFAULT_BARCODE_TYPE)) {
1841  $idtype = $conf->global->PRODUIT_DEFAULT_BARCODE_TYPE;
1842  } elseif ($this->element == 'societe') {
1843  $idtype = $conf->global->GENBARCODE_BARCODETYPE_THIRDPARTY;
1844  } else {
1845  dol_syslog('Call fetch_barcode with barcode_type not defined and cant be guessed', LOG_WARNING);
1846  }
1847  }
1848 
1849  if ($idtype > 0) {
1850  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
1851  $sql = "SELECT rowid, code, libelle as label, coder";
1852  $sql .= " FROM ".$this->db->prefix()."c_barcode_type";
1853  $sql .= " WHERE rowid = ".((int) $idtype);
1854  dol_syslog(get_class($this).'::fetch_barcode', LOG_DEBUG);
1855  $resql = $this->db->query($sql);
1856  if ($resql) {
1857  $obj = $this->db->fetch_object($resql);
1858  $this->barcode_type = $obj->rowid;
1859  $this->barcode_type_code = $obj->code;
1860  $this->barcode_type_label = $obj->label;
1861  $this->barcode_type_coder = $obj->coder;
1862  return 1;
1863  } else {
1864  dol_print_error($this->db);
1865  return -1;
1866  }
1867  }
1868  }
1869  return 0;
1870  }
1871 
1872  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1878  public function fetch_project()
1879  {
1880  // phpcs:enable
1881  return $this->fetch_projet();
1882  }
1883 
1884  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1890  public function fetch_projet()
1891  {
1892  // phpcs:enable
1893  include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
1894 
1895  if (empty($this->fk_project) && !empty($this->fk_projet)) {
1896  $this->fk_project = $this->fk_projet; // For backward compatibility
1897  }
1898  if (empty($this->fk_project)) {
1899  return 0;
1900  }
1901 
1902  $project = new Project($this->db);
1903  $result = $project->fetch($this->fk_project);
1904 
1905  $this->projet = $project; // deprecated
1906  $this->project = $project;
1907  return $result;
1908  }
1909 
1910  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1916  public function fetch_product()
1917  {
1918  // phpcs:enable
1919  include_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
1920 
1921  if (empty($this->fk_product)) {
1922  return 0;
1923  }
1924 
1925  $product = new Product($this->db);
1926  $result = $product->fetch($this->fk_product);
1927 
1928  $this->product = $product;
1929  return $result;
1930  }
1931 
1932  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1939  public function fetch_user($userid)
1940  {
1941  // phpcs:enable
1942  $user = new User($this->db);
1943  $result = $user->fetch($userid);
1944  $this->user = $user;
1945  return $result;
1946  }
1947 
1948  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1954  public function fetch_origin()
1955  {
1956  // phpcs:enable
1957  if ($this->origin == 'shipping') {
1958  $this->origin = 'expedition';
1959  }
1960  if ($this->origin == 'delivery') {
1961  $this->origin = 'livraison';
1962  }
1963  if ($this->origin == 'order_supplier') {
1964  $this->origin = 'commandeFournisseur';
1965  }
1966 
1967  $origin = $this->origin;
1968 
1969  $classname = ucfirst($origin);
1970  $this->$origin = new $classname($this->db);
1971  $this->$origin->fetch($this->origin_id);
1972  }
1973 
1983  public function fetchObjectFrom($table, $field, $key, $element = null)
1984  {
1985  global $conf;
1986 
1987  $result = false;
1988 
1989  $sql = "SELECT rowid FROM ".$this->db->prefix().$table;
1990  $sql .= " WHERE ".$field." = '".$this->db->escape($key)."'";
1991  if (!empty($element)) {
1992  $sql .= " AND entity IN (".getEntity($element).")";
1993  } else {
1994  $sql .= " AND entity = ".((int) $conf->entity);
1995  }
1996 
1997  dol_syslog(get_class($this).'::fetchObjectFrom', LOG_DEBUG);
1998  $resql = $this->db->query($sql);
1999  if ($resql) {
2000  $row = $this->db->fetch_row($resql);
2001  // Test for avoid error -1
2002  if ($row[0] > 0) {
2003  $result = $this->fetch($row[0]);
2004  }
2005  }
2006 
2007  return $result;
2008  }
2009 
2018  public function getValueFrom($table, $id, $field)
2019  {
2020  $result = false;
2021  if (!empty($id) && !empty($field) && !empty($table)) {
2022  $sql = "SELECT ".$field." FROM ".$this->db->prefix().$table;
2023  $sql .= " WHERE rowid = ".((int) $id);
2024 
2025  dol_syslog(get_class($this).'::getValueFrom', LOG_DEBUG);
2026  $resql = $this->db->query($sql);
2027  if ($resql) {
2028  $row = $this->db->fetch_row($resql);
2029  $result = $row[0];
2030  }
2031  }
2032  return $result;
2033  }
2034 
2051  public function setValueFrom($field, $value, $table = '', $id = null, $format = '', $id_field = '', $fuser = null, $trigkey = '', $fk_user_field = 'fk_user_modif')
2052  {
2053  global $user, $langs, $conf;
2054 
2055  if (empty($table)) {
2056  $table = $this->table_element;
2057  }
2058  if (empty($id)) {
2059  $id = $this->id;
2060  }
2061  if (empty($format)) {
2062  $format = 'text';
2063  }
2064  if (empty($id_field)) {
2065  $id_field = 'rowid';
2066  }
2067 
2068  $error = 0;
2069 
2070  $this->db->begin();
2071 
2072  // Special case
2073  if ($table == 'product' && $field == 'note_private') {
2074  $field = 'note';
2075  }
2076  if (in_array($table, array('actioncomm', 'adherent', 'advtargetemailing', 'cronjob', 'establishment'))) {
2077  $fk_user_field = 'fk_user_mod';
2078  }
2079 
2080  $sql = "UPDATE ".$this->db->prefix().$table." SET ";
2081 
2082  if ($format == 'text') {
2083  $sql .= $field." = '".$this->db->escape($value)."'";
2084  } elseif ($format == 'int') {
2085  $sql .= $field." = ".((int) $value);
2086  } elseif ($format == 'date') {
2087  $sql .= $field." = ".($value ? "'".$this->db->idate($value)."'" : "null");
2088  }
2089 
2090  if ($fk_user_field) {
2091  if (!empty($fuser) && is_object($fuser)) {
2092  $sql .= ", ".$fk_user_field." = ".((int) $fuser->id);
2093  } elseif (empty($fuser) || $fuser != 'none') {
2094  $sql .= ", ".$fk_user_field." = ".((int) $user->id);
2095  }
2096  }
2097 
2098  $sql .= " WHERE ".$id_field." = ".((int) $id);
2099 
2100  dol_syslog(__METHOD__."", LOG_DEBUG);
2101  $resql = $this->db->query($sql);
2102  if ($resql) {
2103  if ($trigkey) {
2104  // call trigger with updated object values
2105  if (method_exists($this, 'fetch')) {
2106  $result = $this->fetch($id);
2107  } else {
2108  $result = $this->fetchCommon($id);
2109  }
2110  if ($result >= 0) {
2111  $result = $this->call_trigger($trigkey, (!empty($fuser) && is_object($fuser)) ? $fuser : $user); // This may set this->errors
2112  }
2113  if ($result < 0) {
2114  $error++;
2115  }
2116  }
2117 
2118  if (!$error) {
2119  if (property_exists($this, $field)) {
2120  $this->$field = $value;
2121  }
2122  $this->db->commit();
2123  return 1;
2124  } else {
2125  $this->db->rollback();
2126  return -2;
2127  }
2128  } else {
2129  if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
2130  $this->error = 'DB_ERROR_RECORD_ALREADY_EXISTS';
2131  } else {
2132  $this->error = $this->db->lasterror();
2133  }
2134  $this->db->rollback();
2135  return -1;
2136  }
2137  }
2138 
2139  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2148  public function load_previous_next_ref($filter, $fieldid, $nodbprefix = 0)
2149  {
2150  // phpcs:enable
2151  global $conf, $user;
2152 
2153  if (!$this->table_element) {
2154  dol_print_error('', get_class($this)."::load_previous_next_ref was called on objet with property table_element not defined");
2155  return -1;
2156  }
2157  if ($fieldid == 'none') {
2158  return 1;
2159  }
2160 
2161  // For backward compatibility
2162  if (in_array($this->table_element, array('facture_rec', 'facture_fourn_rec')) && $fieldid == 'title') {
2163  $fieldid = 'titre';
2164  }
2165 
2166  // Security on socid
2167  $socid = 0;
2168  if ($user->socid > 0) {
2169  $socid = $user->socid;
2170  }
2171 
2172  // this->ismultientitymanaged contains
2173  // 0=No test on entity, 1=Test with field entity, 'field@table'=Test with link by field@table
2174  $aliastablesociete = 's';
2175  if ($this->element == 'societe') {
2176  $aliastablesociete = 'te'; // te as table_element
2177  }
2178  $restrictiononfksoc = empty($this->restrictiononfksoc) ? 0 : $this->restrictiononfksoc;
2179  $sql = "SELECT MAX(te.".$fieldid.")";
2180  $sql .= " FROM ".(empty($nodbprefix) ?$this->db->prefix():'').$this->table_element." as te";
2181  if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
2182  $sql .= ",".$this->db->prefix()."usergroup_user as ug";
2183  }
2184  if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2185  $tmparray = explode('@', $this->ismultientitymanaged);
2186  $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
2187  } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
2188  $sql .= ", ".$this->db->prefix()."societe as s"; // If we need to link to societe to limit select to socid
2189  } elseif ($restrictiononfksoc == 2 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
2190  $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
2191  }
2192  if ($restrictiononfksoc && empty($user->rights->societe->client->voir) && !$socid) {
2193  $sql .= " LEFT JOIN ".$this->db->prefix()."societe_commerciaux as sc ON ".$aliastablesociete.".rowid = sc.fk_soc";
2194  }
2195  $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)
2196  if ($restrictiononfksoc == 1 && empty($user->rights->societe->client->voir) && !$socid) {
2197  $sql .= " AND sc.fk_user = ".((int) $user->id);
2198  }
2199  if ($restrictiononfksoc == 2 && empty($user->rights->societe->client->voir) && !$socid) {
2200  $sql .= " AND (sc.fk_user = ".((int) $user->id).' OR te.fk_soc IS NULL)';
2201  }
2202  if (!empty($filter)) {
2203  if (!preg_match('/^\s*AND/i', $filter)) {
2204  $sql .= " AND "; // For backward compatibility
2205  }
2206  $sql .= $filter;
2207  }
2208  if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2209  $tmparray = explode('@', $this->ismultientitymanaged);
2210  $sql .= " AND te.".$tmparray[0]." = ".($tmparray[1] == "societe" ? "s" : "parenttable").".rowid"; // If we need to link to this table to limit select to entity
2211  } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
2212  $sql .= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to socid
2213  }
2214  if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
2215  if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
2216  if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
2217  $sql .= " AND te.entity IS NOT NULL"; // Show all users
2218  } else {
2219  $sql .= " AND ug.fk_user = te.rowid";
2220  $sql .= " AND ug.entity IN (".getEntity('usergroup').")";
2221  }
2222  } else {
2223  $sql .= ' AND te.entity IN ('.getEntity($this->element).')';
2224  }
2225  }
2226  if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged) && $this->element != 'societe') {
2227  $tmparray = explode('@', $this->ismultientitymanaged);
2228  $sql .= ' AND parenttable.entity IN ('.getEntity($tmparray[1]).')';
2229  }
2230  if ($restrictiononfksoc == 1 && $socid && $this->element != 'societe') {
2231  $sql .= ' AND te.fk_soc = '.((int) $socid);
2232  }
2233  if ($restrictiononfksoc == 2 && $socid && $this->element != 'societe') {
2234  $sql .= ' AND (te.fk_soc = '.((int) $socid).' OR te.fk_soc IS NULL)';
2235  }
2236  if ($restrictiononfksoc && $socid && $this->element == 'societe') {
2237  $sql .= ' AND te.rowid = '.((int) $socid);
2238  }
2239  //print 'socid='.$socid.' restrictiononfksoc='.$restrictiononfksoc.' ismultientitymanaged = '.$this->ismultientitymanaged.' filter = '.$filter.' -> '.$sql."<br>";
2240 
2241  $result = $this->db->query($sql);
2242  if (!$result) {
2243  $this->error = $this->db->lasterror();
2244  return -1;
2245  }
2246  $row = $this->db->fetch_row($result);
2247  $this->ref_previous = $row[0];
2248 
2249  $sql = "SELECT MIN(te.".$fieldid.")";
2250  $sql .= " FROM ".(empty($nodbprefix) ?$this->db->prefix():'').$this->table_element." as te";
2251  if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
2252  $sql .= ",".$this->db->prefix()."usergroup_user as ug";
2253  }
2254  if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2255  $tmparray = explode('@', $this->ismultientitymanaged);
2256  $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
2257  } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
2258  $sql .= ", ".$this->db->prefix()."societe as s"; // If we need to link to societe to limit select to socid
2259  } elseif ($restrictiononfksoc == 2 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
2260  $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
2261  }
2262  if ($restrictiononfksoc && empty($user->rights->societe->client->voir) && !$socid) {
2263  $sql .= " LEFT JOIN ".$this->db->prefix()."societe_commerciaux as sc ON ".$aliastablesociete.".rowid = sc.fk_soc";
2264  }
2265  $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)
2266  if ($restrictiononfksoc == 1 && empty($user->rights->societe->client->voir) && !$socid) {
2267  $sql .= " AND sc.fk_user = ".((int) $user->id);
2268  }
2269  if ($restrictiononfksoc == 2 && empty($user->rights->societe->client->voir) && !$socid) {
2270  $sql .= " AND (sc.fk_user = ".((int) $user->id).' OR te.fk_soc IS NULL)';
2271  }
2272  if (!empty($filter)) {
2273  if (!preg_match('/^\s*AND/i', $filter)) {
2274  $sql .= " AND "; // For backward compatibility
2275  }
2276  $sql .= $filter;
2277  }
2278  if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2279  $tmparray = explode('@', $this->ismultientitymanaged);
2280  $sql .= " AND te.".$tmparray[0]." = ".($tmparray[1] == "societe" ? "s" : "parenttable").".rowid"; // If we need to link to this table to limit select to entity
2281  } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
2282  $sql .= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to socid
2283  }
2284  if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
2285  if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
2286  if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
2287  $sql .= " AND te.entity IS NOT NULL"; // Show all users
2288  } else {
2289  $sql .= " AND ug.fk_user = te.rowid";
2290  $sql .= " AND ug.entity IN (".getEntity('usergroup').")";
2291  }
2292  } else {
2293  $sql .= ' AND te.entity IN ('.getEntity($this->element).')';
2294  }
2295  }
2296  if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged) && $this->element != 'societe') {
2297  $tmparray = explode('@', $this->ismultientitymanaged);
2298  $sql .= ' AND parenttable.entity IN ('.getEntity($tmparray[1]).')';
2299  }
2300  if ($restrictiononfksoc == 1 && $socid && $this->element != 'societe') {
2301  $sql .= ' AND te.fk_soc = '.((int) $socid);
2302  }
2303  if ($restrictiononfksoc == 2 && $socid && $this->element != 'societe') {
2304  $sql .= ' AND (te.fk_soc = '.((int) $socid).' OR te.fk_soc IS NULL)';
2305  }
2306  if ($restrictiononfksoc && $socid && $this->element == 'societe') {
2307  $sql .= ' AND te.rowid = '.((int) $socid);
2308  }
2309  //print 'socid='.$socid.' restrictiononfksoc='.$restrictiononfksoc.' ismultientitymanaged = '.$this->ismultientitymanaged.' filter = '.$filter.' -> '.$sql."<br>";
2310  // 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
2311 
2312  $result = $this->db->query($sql);
2313  if (!$result) {
2314  $this->error = $this->db->lasterror();
2315  return -2;
2316  }
2317  $row = $this->db->fetch_row($result);
2318  $this->ref_next = $row[0];
2319 
2320  return 1;
2321  }
2322 
2323 
2331  public function getListContactId($source = 'external')
2332  {
2333  $contactAlreadySelected = array();
2334  $tab = $this->liste_contact(-1, $source);
2335  $num = count($tab);
2336  $i = 0;
2337  while ($i < $num) {
2338  if ($source == 'thirdparty') {
2339  $contactAlreadySelected[$i] = $tab[$i]['socid'];
2340  } else {
2341  $contactAlreadySelected[$i] = $tab[$i]['id'];
2342  }
2343  $i++;
2344  }
2345  return $contactAlreadySelected;
2346  }
2347 
2348 
2356  public function setProject($projectid, $notrigger = 0)
2357  {
2358  global $user;
2359  $error = 0;
2360 
2361  if (!$this->table_element) {
2362  dol_syslog(get_class($this)."::setProject was called on objet with property table_element not defined", LOG_ERR);
2363  return -1;
2364  }
2365 
2366  $sql = "UPDATE ".$this->db->prefix().$this->table_element;
2367  if (!empty($this->fields['fk_project'])) { // Common case
2368  if ($projectid) {
2369  $sql .= " SET fk_project = ".((int) $projectid);
2370  } else {
2371  $sql .= " SET fk_project = NULL";
2372  }
2373  $sql .= ' WHERE rowid = '.((int) $this->id);
2374  } elseif ($this->table_element == 'actioncomm') { // Special case for actioncomm
2375  if ($projectid) {
2376  $sql .= " SET fk_project = ".((int) $projectid);
2377  } else {
2378  $sql .= " SET fk_project = NULL";
2379  }
2380  $sql .= ' WHERE id = '.((int) $this->id);
2381  } else // Special case for old architecture objects
2382  {
2383  if ($projectid) {
2384  $sql .= ' SET fk_projet = '.((int) $projectid);
2385  } else {
2386  $sql .= ' SET fk_projet = NULL';
2387  }
2388  $sql .= " WHERE rowid = ".((int) $this->id);
2389  }
2390 
2391  $this->db->begin();
2392 
2393  dol_syslog(get_class($this)."::setProject", LOG_DEBUG);
2394  if ($this->db->query($sql)) {
2395  $this->fk_project = ((int) $projectid);
2396  } else {
2397  dol_print_error($this->db);
2398  $error++;
2399  }
2400 
2401  // Triggers
2402  if (!$error && !$notrigger) {
2403  // Call triggers
2404  $result = $this->call_trigger(strtoupper($this->element) . '_MODIFY', $user);
2405  if ($result < 0) {
2406  $error++;
2407  } //Do also here what you must do to rollback action if trigger fail
2408  // End call triggers
2409  }
2410 
2411  // Commit or rollback
2412  if ($error) {
2413  $this->db->rollback();
2414  return -1;
2415  } else {
2416  $this->db->commit();
2417  return 1;
2418  }
2419  }
2420 
2427  public function setPaymentMethods($id)
2428  {
2429  global $user;
2430 
2431  $error = 0; $notrigger = 0;
2432 
2433  dol_syslog(get_class($this).'::setPaymentMethods('.$id.')');
2434 
2435  if ($this->statut >= 0 || $this->element == 'societe') {
2436  // TODO uniformize field name
2437  $fieldname = 'fk_mode_reglement';
2438  if ($this->element == 'societe') {
2439  $fieldname = 'mode_reglement';
2440  }
2441  if (get_class($this) == 'Fournisseur') {
2442  $fieldname = 'mode_reglement_supplier';
2443  }
2444  if (get_class($this) == 'Tva') {
2445  $fieldname = 'fk_typepayment';
2446  }
2447  if (get_class($this) == 'Salary') {
2448  $fieldname = 'fk_typepayment';
2449  }
2450 
2451  $sql = "UPDATE ".$this->db->prefix().$this->table_element;
2452  $sql .= " SET ".$fieldname." = ".(($id > 0 || $id == '0') ? ((int) $id) : 'NULL');
2453  $sql .= ' WHERE rowid='.((int) $this->id);
2454 
2455  if ($this->db->query($sql)) {
2456  $this->mode_reglement_id = $id;
2457  // for supplier
2458  if (get_class($this) == 'Fournisseur') {
2459  $this->mode_reglement_supplier_id = $id;
2460  }
2461  // Triggers
2462  if (!$error && !$notrigger) {
2463  // Call triggers
2464  if (get_class($this) == 'Commande') {
2465  $result = $this->call_trigger('ORDER_MODIFY', $user);
2466  } else {
2467  $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $user);
2468  }
2469  if ($result < 0) {
2470  $error++;
2471  }
2472  // End call triggers
2473  }
2474  return 1;
2475  } else {
2476  dol_syslog(get_class($this).'::setPaymentMethods Error '.$this->db->error());
2477  $this->error = $this->db->error();
2478  return -1;
2479  }
2480  } else {
2481  dol_syslog(get_class($this).'::setPaymentMethods, status of the object is incompatible');
2482  $this->error = 'Status of the object is incompatible '.$this->statut;
2483  return -2;
2484  }
2485  }
2486 
2493  public function setMulticurrencyCode($code)
2494  {
2495  dol_syslog(get_class($this).'::setMulticurrencyCode('.$code.')');
2496  if ($this->statut >= 0 || $this->element == 'societe') {
2497  $fieldname = 'multicurrency_code';
2498 
2499  $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
2500  $sql .= " SET ".$fieldname." = '".$this->db->escape($code)."'";
2501  $sql .= ' WHERE rowid='.((int) $this->id);
2502 
2503  if ($this->db->query($sql)) {
2504  $this->multicurrency_code = $code;
2505 
2506  list($fk_multicurrency, $rate) = MultiCurrency::getIdAndTxFromCode($this->db, $code);
2507  if ($rate) {
2508  $this->setMulticurrencyRate($rate, 2);
2509  }
2510 
2511  return 1;
2512  } else {
2513  dol_syslog(get_class($this).'::setMulticurrencyCode Error '.$sql.' - '.$this->db->error());
2514  $this->error = $this->db->error();
2515  return -1;
2516  }
2517  } else {
2518  dol_syslog(get_class($this).'::setMulticurrencyCode, status of the object is incompatible');
2519  $this->error = 'Status of the object is incompatible '.$this->statut;
2520  return -2;
2521  }
2522  }
2523 
2531  public function setMulticurrencyRate($rate, $mode = 1)
2532  {
2533  dol_syslog(get_class($this).'::setMulticurrencyRate('.$rate.','.$mode.')');
2534  if ($this->statut >= 0 || $this->element == 'societe') {
2535  $fieldname = 'multicurrency_tx';
2536 
2537  $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
2538  $sql .= " SET ".$fieldname." = ".((float) $rate);
2539  $sql .= ' WHERE rowid='.((int) $this->id);
2540 
2541  if ($this->db->query($sql)) {
2542  $this->multicurrency_tx = $rate;
2543 
2544  // Update line price
2545  if (!empty($this->lines)) {
2546  foreach ($this->lines as &$line) {
2547  // Amounts in company currency will be recalculated
2548  if ($mode == 1) {
2549  $line->subprice = 0;
2550  }
2551 
2552  // Amounts in foreign currency will be recalculated
2553  if ($mode == 2) {
2554  $line->multicurrency_subprice = 0;
2555  }
2556 
2557  switch ($this->element) {
2558  case 'propal':
2559  $this->updateline(
2560  $line->id,
2561  $line->subprice,
2562  $line->qty,
2563  $line->remise_percent,
2564  $line->tva_tx,
2565  $line->localtax1_tx,
2566  $line->localtax2_tx,
2567  ($line->description ? $line->description : $line->desc),
2568  'HT',
2569  $line->info_bits,
2570  $line->special_code,
2571  $line->fk_parent_line,
2572  $line->skip_update_total,
2573  $line->fk_fournprice,
2574  $line->pa_ht,
2575  $line->label,
2576  $line->product_type,
2577  $line->date_start,
2578  $line->date_end,
2579  $line->array_options,
2580  $line->fk_unit,
2581  $line->multicurrency_subprice
2582  );
2583  break;
2584  case 'commande':
2585  $this->updateline(
2586  $line->id,
2587  ($line->description ? $line->description : $line->desc),
2588  $line->subprice,
2589  $line->qty,
2590  $line->remise_percent,
2591  $line->tva_tx,
2592  $line->localtax1_tx,
2593  $line->localtax2_tx,
2594  'HT',
2595  $line->info_bits,
2596  $line->date_start,
2597  $line->date_end,
2598  $line->product_type,
2599  $line->fk_parent_line,
2600  $line->skip_update_total,
2601  $line->fk_fournprice,
2602  $line->pa_ht,
2603  $line->label,
2604  $line->special_code,
2605  $line->array_options,
2606  $line->fk_unit,
2607  $line->multicurrency_subprice
2608  );
2609  break;
2610  case 'facture':
2611  $this->updateline(
2612  $line->id,
2613  ($line->description ? $line->description : $line->desc),
2614  $line->subprice,
2615  $line->qty,
2616  $line->remise_percent,
2617  $line->date_start,
2618  $line->date_end,
2619  $line->tva_tx,
2620  $line->localtax1_tx,
2621  $line->localtax2_tx,
2622  'HT',
2623  $line->info_bits,
2624  $line->product_type,
2625  $line->fk_parent_line,
2626  $line->skip_update_total,
2627  $line->fk_fournprice,
2628  $line->pa_ht,
2629  $line->label,
2630  $line->special_code,
2631  $line->array_options,
2632  $line->situation_percent,
2633  $line->fk_unit,
2634  $line->multicurrency_subprice
2635  );
2636  break;
2637  case 'supplier_proposal':
2638  $this->updateline(
2639  $line->id,
2640  $line->subprice,
2641  $line->qty,
2642  $line->remise_percent,
2643  $line->tva_tx,
2644  $line->localtax1_tx,
2645  $line->localtax2_tx,
2646  ($line->description ? $line->description : $line->desc),
2647  'HT',
2648  $line->info_bits,
2649  $line->special_code,
2650  $line->fk_parent_line,
2651  $line->skip_update_total,
2652  $line->fk_fournprice,
2653  $line->pa_ht,
2654  $line->label,
2655  $line->product_type,
2656  $line->array_options,
2657  $line->ref_fourn,
2658  $line->multicurrency_subprice
2659  );
2660  break;
2661  case 'order_supplier':
2662  $this->updateline(
2663  $line->id,
2664  ($line->description ? $line->description : $line->desc),
2665  $line->subprice,
2666  $line->qty,
2667  $line->remise_percent,
2668  $line->tva_tx,
2669  $line->localtax1_tx,
2670  $line->localtax2_tx,
2671  'HT',
2672  $line->info_bits,
2673  $line->product_type,
2674  false,
2675  $line->date_start,
2676  $line->date_end,
2677  $line->array_options,
2678  $line->fk_unit,
2679  $line->multicurrency_subprice,
2680  $line->ref_supplier
2681  );
2682  break;
2683  case 'invoice_supplier':
2684  $this->updateline(
2685  $line->id,
2686  ($line->description ? $line->description : $line->desc),
2687  $line->subprice,
2688  $line->tva_tx,
2689  $line->localtax1_tx,
2690  $line->localtax2_tx,
2691  $line->qty,
2692  0,
2693  'HT',
2694  $line->info_bits,
2695  $line->product_type,
2696  $line->remise_percent,
2697  false,
2698  $line->date_start,
2699  $line->date_end,
2700  $line->array_options,
2701  $line->fk_unit,
2702  $line->multicurrency_subprice,
2703  $line->ref_supplier
2704  );
2705  break;
2706  default:
2707  dol_syslog(get_class($this).'::setMulticurrencyRate no updateline defined', LOG_DEBUG);
2708  break;
2709  }
2710  }
2711  }
2712 
2713  return 1;
2714  } else {
2715  dol_syslog(get_class($this).'::setMulticurrencyRate Error '.$sql.' - '.$this->db->error());
2716  $this->error = $this->db->error();
2717  return -1;
2718  }
2719  } else {
2720  dol_syslog(get_class($this).'::setMulticurrencyRate, status of the object is incompatible');
2721  $this->error = 'Status of the object is incompatible '.$this->statut;
2722  return -2;
2723  }
2724  }
2725 
2733  public function setPaymentTerms($id, $deposit_percent = null)
2734  {
2735  dol_syslog(get_class($this).'::setPaymentTerms('.$id.', '.var_export($deposit_percent, true).')');
2736  if ($this->statut >= 0 || $this->element == 'societe') {
2737  // TODO uniformize field name
2738  $fieldname = 'fk_cond_reglement';
2739  if ($this->element == 'societe') {
2740  $fieldname = 'cond_reglement';
2741  }
2742  if (get_class($this) == 'Fournisseur') {
2743  $fieldname = 'cond_reglement_supplier';
2744  }
2745 
2746  if (empty($deposit_percent) || $deposit_percent < 0) {
2747  $deposit_percent = getDictionaryValue('c_payment_term', 'deposit_percent', $id);
2748  }
2749 
2750  if ($deposit_percent > 100) {
2751  $deposit_percent = 100;
2752  }
2753 
2754  $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
2755  $sql .= " SET ".$fieldname." = ".(($id > 0 || $id == '0') ? ((int) $id) : 'NULL');
2756  if (in_array($this->table_element, array('propal', 'commande', 'societe'))) {
2757  $sql .= " , deposit_percent = " . (empty($deposit_percent) ? 'NULL' : "'".$this->db->escape($deposit_percent)."'");
2758  }
2759  $sql .= ' WHERE rowid='.((int) $this->id);
2760 
2761  if ($this->db->query($sql)) {
2762  $this->cond_reglement_id = $id;
2763  // for supplier
2764  if (get_class($this) == 'Fournisseur') {
2765  $this->cond_reglement_supplier_id = $id;
2766  }
2767  $this->cond_reglement = $id; // for compatibility
2768  $this->deposit_percent = $deposit_percent;
2769  return 1;
2770  } else {
2771  dol_syslog(get_class($this).'::setPaymentTerms Error '.$sql.' - '.$this->db->error());
2772  $this->error = $this->db->error();
2773  return -1;
2774  }
2775  } else {
2776  dol_syslog(get_class($this).'::setPaymentTerms, status of the object is incompatible');
2777  $this->error = 'Status of the object is incompatible '.$this->statut;
2778  return -2;
2779  }
2780  }
2781 
2788  public function setTransportMode($id)
2789  {
2790  dol_syslog(get_class($this).'::setTransportMode('.$id.')');
2791  if ($this->statut >= 0 || $this->element == 'societe') {
2792  $fieldname = 'fk_transport_mode';
2793  if ($this->element == 'societe') {
2794  $fieldname = 'transport_mode';
2795  }
2796  if (get_class($this) == 'Fournisseur') {
2797  $fieldname = 'transport_mode_supplier';
2798  }
2799 
2800  $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
2801  $sql .= " SET ".$fieldname." = ".(($id > 0 || $id == '0') ? ((int) $id) : 'NULL');
2802  $sql .= ' WHERE rowid='.((int) $this->id);
2803 
2804  if ($this->db->query($sql)) {
2805  $this->transport_mode_id = $id;
2806  // for supplier
2807  if (get_class($this) == 'Fournisseur') {
2808  $this->transport_mode_supplier_id = $id;
2809  }
2810  return 1;
2811  } else {
2812  dol_syslog(get_class($this).'::setTransportMode Error '.$sql.' - '.$this->db->error());
2813  $this->error = $this->db->error();
2814  return -1;
2815  }
2816  } else {
2817  dol_syslog(get_class($this).'::setTransportMode, status of the object is incompatible');
2818  $this->error = 'Status of the object is incompatible '.$this->statut;
2819  return -2;
2820  }
2821  }
2822 
2829  public function setRetainedWarrantyPaymentTerms($id)
2830  {
2831  dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms('.$id.')');
2832  if ($this->statut >= 0 || $this->element == 'societe') {
2833  $fieldname = 'retained_warranty_fk_cond_reglement';
2834 
2835  $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
2836  $sql .= " SET ".$fieldname." = ".((int) $id);
2837  $sql .= ' WHERE rowid='.((int) $this->id);
2838 
2839  if ($this->db->query($sql)) {
2840  $this->retained_warranty_fk_cond_reglement = $id;
2841  return 1;
2842  } else {
2843  dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms Error '.$sql.' - '.$this->db->error());
2844  $this->error = $this->db->error();
2845  return -1;
2846  }
2847  } else {
2848  dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms, status of the object is incompatible');
2849  $this->error = 'Status of the object is incompatible '.$this->statut;
2850  return -2;
2851  }
2852  }
2853 
2861  public function setDeliveryAddress($id)
2862  {
2863  $fieldname = 'fk_delivery_address';
2864  if ($this->element == 'delivery' || $this->element == 'shipping') {
2865  $fieldname = 'fk_address';
2866  }
2867 
2868  $sql = "UPDATE ".$this->db->prefix().$this->table_element." SET ".$fieldname." = ".((int) $id);
2869  $sql .= " WHERE rowid = ".((int) $this->id)." AND fk_statut = 0";
2870 
2871  if ($this->db->query($sql)) {
2872  $this->fk_delivery_address = $id;
2873  return 1;
2874  } else {
2875  $this->error = $this->db->error();
2876  dol_syslog(get_class($this).'::setDeliveryAddress Error '.$this->error);
2877  return -1;
2878  }
2879  }
2880 
2881 
2891  public function setShippingMethod($shipping_method_id, $notrigger = false, $userused = null)
2892  {
2893  global $user;
2894 
2895  if (empty($userused)) {
2896  $userused = $user;
2897  }
2898 
2899  $error = 0;
2900 
2901  if (!$this->table_element) {
2902  dol_syslog(get_class($this)."::setShippingMethod was called on objet with property table_element not defined", LOG_ERR);
2903  return -1;
2904  }
2905 
2906  $this->db->begin();
2907 
2908  if ($shipping_method_id < 0) {
2909  $shipping_method_id = 'NULL';
2910  }
2911  dol_syslog(get_class($this).'::setShippingMethod('.$shipping_method_id.')');
2912 
2913  $sql = "UPDATE ".$this->db->prefix().$this->table_element;
2914  $sql .= " SET fk_shipping_method = ".((int) $shipping_method_id);
2915  $sql .= " WHERE rowid=".((int) $this->id);
2916  $resql = $this->db->query($sql);
2917  if (!$resql) {
2918  dol_syslog(get_class($this).'::setShippingMethod Error ', LOG_DEBUG);
2919  $this->error = $this->db->lasterror();
2920  $error++;
2921  } else {
2922  if (!$notrigger) {
2923  // Call trigger
2924  $this->context = array('shippingmethodupdate'=>1);
2925  $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $userused);
2926  if ($result < 0) {
2927  $error++;
2928  }
2929  // End call trigger
2930  }
2931  }
2932  if ($error) {
2933  $this->db->rollback();
2934  return -1;
2935  } else {
2936  $this->shipping_method_id = ($shipping_method_id == 'NULL') ?null:$shipping_method_id;
2937  $this->db->commit();
2938  return 1;
2939  }
2940  }
2941 
2942 
2949  public function setWarehouse($warehouse_id)
2950  {
2951  if (!$this->table_element) {
2952  dol_syslog(get_class($this)."::setWarehouse was called on objet with property table_element not defined", LOG_ERR);
2953  return -1;
2954  }
2955  if ($warehouse_id < 0) {
2956  $warehouse_id = 'NULL';
2957  }
2958  dol_syslog(get_class($this).'::setWarehouse('.$warehouse_id.')');
2959 
2960  $sql = "UPDATE ".$this->db->prefix().$this->table_element;
2961  $sql .= " SET fk_warehouse = ".((int) $warehouse_id);
2962  $sql .= " WHERE rowid=".((int) $this->id);
2963 
2964  if ($this->db->query($sql)) {
2965  $this->warehouse_id = ($warehouse_id == 'NULL') ?null:$warehouse_id;
2966  return 1;
2967  } else {
2968  dol_syslog(get_class($this).'::setWarehouse Error ', LOG_DEBUG);
2969  $this->error = $this->db->error();
2970  return 0;
2971  }
2972  }
2973 
2974 
2982  public function setDocModel($user, $modelpdf)
2983  {
2984  if (!$this->table_element) {
2985  dol_syslog(get_class($this)."::setDocModel was called on objet with property table_element not defined", LOG_ERR);
2986  return -1;
2987  }
2988 
2989  $newmodelpdf = dol_trunc($modelpdf, 255);
2990 
2991  $sql = "UPDATE ".$this->db->prefix().$this->table_element;
2992  $sql .= " SET model_pdf = '".$this->db->escape($newmodelpdf)."'";
2993  $sql .= " WHERE rowid = ".((int) $this->id);
2994 
2995  dol_syslog(get_class($this)."::setDocModel", LOG_DEBUG);
2996  $resql = $this->db->query($sql);
2997  if ($resql) {
2998  $this->model_pdf = $modelpdf;
2999  $this->modelpdf = $modelpdf; // For bakward compatibility
3000  return 1;
3001  } else {
3002  dol_print_error($this->db);
3003  return 0;
3004  }
3005  }
3006 
3007 
3016  public function setBankAccount($fk_account, $notrigger = false, $userused = null)
3017  {
3018  global $user;
3019 
3020  if (empty($userused)) {
3021  $userused = $user;
3022  }
3023 
3024  $error = 0;
3025 
3026  if (!$this->table_element) {
3027  dol_syslog(get_class($this)."::setBankAccount was called on objet with property table_element not defined", LOG_ERR);
3028  return -1;
3029  }
3030  $this->db->begin();
3031 
3032  if ($fk_account < 0) {
3033  $fk_account = 'NULL';
3034  }
3035  dol_syslog(get_class($this).'::setBankAccount('.$fk_account.')');
3036 
3037  $sql = "UPDATE ".$this->db->prefix().$this->table_element;
3038  $sql .= " SET fk_account = ".((int) $fk_account);
3039  $sql .= " WHERE rowid=".((int) $this->id);
3040 
3041  $resql = $this->db->query($sql);
3042  if (!$resql) {
3043  dol_syslog(get_class($this).'::setBankAccount Error '.$sql.' - '.$this->db->error());
3044  $this->error = $this->db->lasterror();
3045  $error++;
3046  } else {
3047  if (!$notrigger) {
3048  // Call trigger
3049  $this->context = array('bankaccountupdate'=>1);
3050  $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $userused);
3051  if ($result < 0) {
3052  $error++;
3053  }
3054  // End call trigger
3055  }
3056  }
3057  if ($error) {
3058  $this->db->rollback();
3059  return -1;
3060  } else {
3061  $this->fk_account = ($fk_account == 'NULL') ?null:$fk_account;
3062  $this->db->commit();
3063  return 1;
3064  }
3065  }
3066 
3067 
3068  // TODO: Move line related operations to CommonObjectLine?
3069 
3070  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3080  public function line_order($renum = false, $rowidorder = 'ASC', $fk_parent_line = true)
3081  {
3082  // phpcs:enable
3083  if (!$this->table_element_line) {
3084  dol_syslog(get_class($this)."::line_order was called on objet with property table_element_line not defined", LOG_ERR);
3085  return -1;
3086  }
3087  if (!$this->fk_element) {
3088  dol_syslog(get_class($this)."::line_order was called on objet with property fk_element not defined", LOG_ERR);
3089  return -1;
3090  }
3091 
3092  $fieldposition = 'rang'; // @todo Rename 'rang' into 'position'
3093  if (in_array($this->table_element_line, array('bom_bomline', 'ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
3094  $fieldposition = 'position';
3095  }
3096 
3097  // Count number of lines to reorder (according to choice $renum)
3098  $nl = 0;
3099  $sql = "SELECT count(rowid) FROM ".$this->db->prefix().$this->table_element_line;
3100  $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
3101  if (!$renum) {
3102  $sql .= " AND " . $fieldposition . " = 0";
3103  }
3104  if ($renum) {
3105  $sql .= " AND " . $fieldposition . " <> 0";
3106  }
3107 
3108  dol_syslog(get_class($this)."::line_order", LOG_DEBUG);
3109  $resql = $this->db->query($sql);
3110  if ($resql) {
3111  $row = $this->db->fetch_row($resql);
3112  $nl = $row[0];
3113  } else {
3114  dol_print_error($this->db);
3115  }
3116  if ($nl > 0) {
3117  // The goal of this part is to reorder all lines, with all children lines sharing the same counter that parents.
3118  $rows = array();
3119 
3120  // We first search all lines that are parent lines (for multilevel details lines)
3121  $sql = "SELECT rowid FROM ".$this->db->prefix().$this->table_element_line;
3122  $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
3123  if ($fk_parent_line) {
3124  $sql .= ' AND fk_parent_line IS NULL';
3125  }
3126  $sql .= " ORDER BY " . $fieldposition . " ASC, rowid " . $rowidorder;
3127 
3128  dol_syslog(get_class($this)."::line_order search all parent lines", LOG_DEBUG);
3129  $resql = $this->db->query($sql);
3130  if ($resql) {
3131  $i = 0;
3132  $num = $this->db->num_rows($resql);
3133  while ($i < $num) {
3134  $row = $this->db->fetch_row($resql);
3135  $rows[] = $row[0]; // Add parent line into array rows
3136  $childrens = $this->getChildrenOfLine($row[0]);
3137  if (!empty($childrens)) {
3138  foreach ($childrens as $child) {
3139  array_push($rows, $child);
3140  }
3141  }
3142  $i++;
3143  }
3144 
3145  // Now we set a new number for each lines (parent and children with children included into parent tree)
3146  if (!empty($rows)) {
3147  foreach ($rows as $key => $row) {
3148  $this->updateRangOfLine($row, ($key + 1));
3149  }
3150  }
3151  } else {
3152  dol_print_error($this->db);
3153  }
3154  }
3155  return 1;
3156  }
3157 
3165  public function getChildrenOfLine($id, $includealltree = 0)
3166  {
3167  $fieldposition = 'rang'; // @todo Rename 'rang' into 'position'
3168  if (in_array($this->table_element_line, array('bom_bomline', 'ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
3169  $fieldposition = 'position';
3170  }
3171 
3172  $rows = array();
3173 
3174  $sql = "SELECT rowid FROM ".$this->db->prefix().$this->table_element_line;
3175  $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
3176  $sql .= ' AND fk_parent_line = '.((int) $id);
3177  $sql .= " ORDER BY " . $fieldposition . " ASC";
3178 
3179  dol_syslog(get_class($this)."::getChildrenOfLine search children lines for line ".$id, LOG_DEBUG);
3180  $resql = $this->db->query($sql);
3181  if ($resql) {
3182  if ($this->db->num_rows($resql) > 0) {
3183  while ($row = $this->db->fetch_row($resql)) {
3184  $rows[] = $row[0];
3185  if (!empty($includealltree)) {
3186  $rows = array_merge($rows, $this->getChildrenOfLine($row[0]), $includealltree);
3187  }
3188  }
3189  }
3190  }
3191  return $rows;
3192  }
3193 
3194  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3202  public function line_up($rowid, $fk_parent_line = true)
3203  {
3204  // phpcs:enable
3205  $this->line_order(false, 'ASC', $fk_parent_line);
3206 
3207  // Get rang of line
3208  $rang = $this->getRangOfLine($rowid);
3209 
3210  // Update position of line
3211  $this->updateLineUp($rowid, $rang);
3212  }
3213 
3214  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3222  public function line_down($rowid, $fk_parent_line = true)
3223  {
3224  // phpcs:enable
3225  $this->line_order(false, 'ASC', $fk_parent_line);
3226 
3227  // Get rang of line
3228  $rang = $this->getRangOfLine($rowid);
3229 
3230  // Get max value for rang
3231  $max = $this->line_max();
3232 
3233  // Update position of line
3234  $this->updateLineDown($rowid, $rang, $max);
3235  }
3236 
3244  public function updateRangOfLine($rowid, $rang)
3245  {
3246  global $hookmanager;
3247  $fieldposition = 'rang'; // @todo Rename 'rang' into 'position'
3248  if (in_array($this->table_element_line, array('bom_bomline', 'ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
3249  $fieldposition = 'position';
3250  }
3251 
3252  $sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldposition." = ".((int) $rang);
3253  $sql .= ' WHERE rowid = '.((int) $rowid);
3254 
3255  dol_syslog(get_class($this)."::updateRangOfLine", LOG_DEBUG);
3256  if (!$this->db->query($sql)) {
3257  dol_print_error($this->db);
3258  return -1;
3259  } else {
3260  $parameters=array('rowid'=>$rowid, 'rang'=>$rang, 'fieldposition' => $fieldposition);
3261  $action='';
3262  $reshook = $hookmanager->executeHooks('afterRankOfLineUpdate', $parameters, $this, $action);
3263  return 1;
3264  }
3265  }
3266 
3267  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3274  public function line_ajaxorder($rows)
3275  {
3276  // phpcs:enable
3277  $num = count($rows);
3278  for ($i = 0; $i < $num; $i++) {
3279  $this->updateRangOfLine($rows[$i], ($i + 1));
3280  }
3281  }
3282 
3290  public function updateLineUp($rowid, $rang)
3291  {
3292  if ($rang > 1) {
3293  $fieldposition = 'rang';
3294  if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
3295  $fieldposition = 'position';
3296  }
3297 
3298  $sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldposition." = ".((int) $rang);
3299  $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
3300  $sql .= " AND " . $fieldposition . " = " . ((int) ($rang - 1));
3301  if ($this->db->query($sql)) {
3302  $sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldposition." = ".((int) ($rang - 1));
3303  $sql .= ' WHERE rowid = '.((int) $rowid);
3304  if (!$this->db->query($sql)) {
3305  dol_print_error($this->db);
3306  }
3307  } else {
3308  dol_print_error($this->db);
3309  }
3310  }
3311  }
3312 
3321  public function updateLineDown($rowid, $rang, $max)
3322  {
3323  if ($rang < $max) {
3324  $fieldposition = 'rang';
3325  if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
3326  $fieldposition = 'position';
3327  }
3328 
3329  $sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldposition." = ".((int) $rang);
3330  $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
3331  $sql .= " AND " . $fieldposition . " = " . ((int) ($rang + 1));
3332  if ($this->db->query($sql)) {
3333  $sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldposition." = ".((int) ($rang + 1));
3334  $sql .= ' WHERE rowid = '.((int) $rowid);
3335  if (!$this->db->query($sql)) {
3336  dol_print_error($this->db);
3337  }
3338  } else {
3339  dol_print_error($this->db);
3340  }
3341  }
3342  }
3343 
3350  public function getRangOfLine($rowid)
3351  {
3352  $fieldposition = 'rang';
3353  if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
3354  $fieldposition = 'position';
3355  }
3356 
3357  $sql = "SELECT " . $fieldposition . " FROM ".$this->db->prefix().$this->table_element_line;
3358  $sql .= " WHERE rowid = ".((int) $rowid);
3359 
3360  dol_syslog(get_class($this)."::getRangOfLine", LOG_DEBUG);
3361  $resql = $this->db->query($sql);
3362  if ($resql) {
3363  $row = $this->db->fetch_row($resql);
3364  return $row[0];
3365  }
3366  }
3367 
3374  public function getIdOfLine($rang)
3375  {
3376  $fieldposition = 'rang';
3377  if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
3378  $fieldposition = 'position';
3379  }
3380 
3381  $sql = "SELECT rowid FROM ".$this->db->prefix().$this->table_element_line;
3382  $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
3383  $sql .= " AND " . $fieldposition . " = ".((int) $rang);
3384  $resql = $this->db->query($sql);
3385  if ($resql) {
3386  $row = $this->db->fetch_row($resql);
3387  return $row[0];
3388  }
3389  }
3390 
3391  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3398  public function line_max($fk_parent_line = 0)
3399  {
3400  // phpcs:enable
3401  $positionfield = 'rang';
3402  if (in_array($this->table_element, array('bom_bom', 'product_attribute'))) {
3403  $positionfield = 'position';
3404  }
3405 
3406  // Search the last rang with fk_parent_line
3407  if ($fk_parent_line) {
3408  $sql = "SELECT max(".$positionfield.") FROM ".$this->db->prefix().$this->table_element_line;
3409  $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
3410  $sql .= " AND fk_parent_line = ".((int) $fk_parent_line);
3411 
3412  dol_syslog(get_class($this)."::line_max", LOG_DEBUG);
3413  $resql = $this->db->query($sql);
3414  if ($resql) {
3415  $row = $this->db->fetch_row($resql);
3416  if (!empty($row[0])) {
3417  return $row[0];
3418  } else {
3419  return $this->getRangOfLine($fk_parent_line);
3420  }
3421  }
3422  } else {
3423  // If not, search the last rang of element
3424  $sql = "SELECT max(".$positionfield.") FROM ".$this->db->prefix().$this->table_element_line;
3425  $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
3426 
3427  dol_syslog(get_class($this)."::line_max", LOG_DEBUG);
3428  $resql = $this->db->query($sql);
3429  if ($resql) {
3430  $row = $this->db->fetch_row($resql);
3431  return $row[0];
3432  }
3433  }
3434  }
3435 
3436  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3443  public function update_ref_ext($ref_ext)
3444  {
3445  // phpcs:enable
3446  if (!$this->table_element) {
3447  dol_syslog(get_class($this)."::update_ref_ext was called on objet with property table_element not defined", LOG_ERR);
3448  return -1;
3449  }
3450 
3451  $sql = "UPDATE ".$this->db->prefix().$this->table_element;
3452  $sql .= " SET ref_ext = '".$this->db->escape($ref_ext)."'";
3453  $sql .= " WHERE ".(isset($this->table_rowid) ? $this->table_rowid : 'rowid')." = ".((int) $this->id);
3454 
3455  dol_syslog(get_class($this)."::update_ref_ext", LOG_DEBUG);
3456  if ($this->db->query($sql)) {
3457  $this->ref_ext = $ref_ext;
3458  return 1;
3459  } else {
3460  $this->error = $this->db->error();
3461  return -1;
3462  }
3463  }
3464 
3465  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3473  public function update_note($note, $suffix = '')
3474  {
3475  // phpcs:enable
3476  global $user;
3477 
3478  if (!$this->table_element) {
3479  $this->error = 'update_note was called on objet with property table_element not defined';
3480  dol_syslog(get_class($this)."::update_note was called on objet with property table_element not defined", LOG_ERR);
3481  return -1;
3482  }
3483  if (!in_array($suffix, array('', '_public', '_private'))) {
3484  $this->error = 'update_note Parameter suffix must be empty, \'_private\' or \'_public\'';
3485  dol_syslog(get_class($this)."::update_note Parameter suffix must be empty, '_private' or '_public'", LOG_ERR);
3486  return -2;
3487  }
3488 
3489  $newsuffix = $suffix;
3490 
3491  // Special cas
3492  if ($this->table_element == 'product' && $newsuffix == '_private') {
3493  $newsuffix = '';
3494  }
3495  if (in_array($this->table_element, array('actioncomm', 'adherent', 'advtargetemailing', 'cronjob', 'establishment'))) {
3496  $fieldusermod = "fk_user_mod";
3497  } elseif ($this->table_element == 'ecm_files') {
3498  $fieldusermod = "fk_user_m";
3499  } else {
3500  $fieldusermod = "fk_user_modif";
3501  }
3502  $sql = "UPDATE ".$this->db->prefix().$this->table_element;
3503  $sql .= " SET note".$newsuffix." = ".(!empty($note) ? ("'".$this->db->escape($note)."'") : "NULL");
3504  $sql .= ", ".$fieldusermod." = ".((int) $user->id);
3505  $sql .= " WHERE rowid = ".((int) $this->id);
3506 
3507  dol_syslog(get_class($this)."::update_note", LOG_DEBUG);
3508  if ($this->db->query($sql)) {
3509  if ($suffix == '_public') {
3510  $this->note_public = $note;
3511  } elseif ($suffix == '_private') {
3512  $this->note_private = $note;
3513  } else {
3514  $this->note = $note; // deprecated
3515  $this->note_private = $note;
3516  }
3517  return 1;
3518  } else {
3519  $this->error = $this->db->lasterror();
3520  return -1;
3521  }
3522  }
3523 
3524  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3533  public function update_note_public($note)
3534  {
3535  // phpcs:enable
3536  return $this->update_note($note, '_public');
3537  }
3538 
3539  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3550  public function update_price($exclspec = 0, $roundingadjust = 'none', $nodatabaseupdate = 0, $seller = null)
3551  {
3552  // phpcs:enable
3553  global $conf, $hookmanager, $action;
3554 
3555  $parameters = array('exclspec' => $exclspec, 'roundingadjust' => $roundingadjust, 'nodatabaseupdate' => $nodatabaseupdate, 'seller' => $seller);
3556  $reshook = $hookmanager->executeHooks('updateTotalPrice', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
3557  if ($reshook > 0) {
3558  return 1; // replacement code
3559  } elseif ($reshook < 0) {
3560  return -1; // failure
3561  } // reshook = 0 => execute normal code
3562 
3563  // Some external module want no update price after a trigger because they have another method to calculate the total (ex: with an extrafield)
3564  $MODULE = "";
3565  if ($this->element == 'propal') {
3566  $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_PROPOSAL";
3567  } elseif ($this->element == 'commande' || $this->element == 'order') {
3568  $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_ORDER";
3569  } elseif ($this->element == 'facture' || $this->element == 'invoice') {
3570  $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_INVOICE";
3571  } elseif ($this->element == 'facture_fourn' || $this->element == 'supplier_invoice' || $this->element == 'invoice_supplier' || $this->element == 'invoice_supplier_rec') {
3572  $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_INVOICE";
3573  } elseif ($this->element == 'order_supplier' || $this->element == 'supplier_order') {
3574  $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_ORDER";
3575  } elseif ($this->element == 'supplier_proposal') {
3576  $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_PROPOSAL";
3577  }
3578 
3579  if (!empty($MODULE)) {
3580  if (!empty($conf->global->$MODULE)) {
3581  $modsactivated = explode(',', $conf->global->$MODULE);
3582  foreach ($modsactivated as $mod) {
3583  if (isModEnabled($mod)) {
3584  return 1; // update was disabled by specific setup
3585  }
3586  }
3587  }
3588  }
3589 
3590  include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
3591 
3592  $forcedroundingmode = $roundingadjust;
3593  if ($forcedroundingmode == 'auto' && isset($conf->global->MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND)) {
3594  $forcedroundingmode = getDolGlobalString('MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND');
3595  } elseif ($forcedroundingmode == 'auto') {
3596  $forcedroundingmode = '0';
3597  }
3598 
3599  $error = 0;
3600 
3601  $multicurrency_tx = !empty($this->multicurrency_tx) ? $this->multicurrency_tx : 1;
3602 
3603  // Define constants to find lines to sum (field name int the table_element_line not into table_element)
3604  $fieldtva = 'total_tva';
3605  $fieldlocaltax1 = 'total_localtax1';
3606  $fieldlocaltax2 = 'total_localtax2';
3607  $fieldup = 'subprice';
3608  if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier') {
3609  $fieldtva = 'tva';
3610  $fieldup = 'pu_ht';
3611  }
3612  if ($this->element == 'invoice_supplier_rec') {
3613  $fieldup = 'pu_ht';
3614  }
3615  if ($this->element == 'expensereport') {
3616  $fieldup = 'value_unit';
3617  }
3618 
3619  $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,";
3620  $sql .= ' tva_tx as vatrate, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type, info_bits, product_type';
3621  if ($this->table_element_line == 'facturedet') {
3622  $sql .= ', situation_percent';
3623  }
3624  $sql .= ', multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc';
3625  $sql .= " FROM ".$this->db->prefix().$this->table_element_line;
3626  $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
3627  if ($exclspec) {
3628  $product_field = 'product_type';
3629  if ($this->table_element_line == 'contratdet') {
3630  $product_field = ''; // contratdet table has no product_type field
3631  }
3632  if ($product_field) {
3633  $sql .= " AND ".$product_field." <> 9";
3634  }
3635  }
3636  $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
3637 
3638  dol_syslog(get_class($this)."::update_price", LOG_DEBUG);
3639 
3640  $resql = $this->db->query($sql);
3641  if ($resql) {
3642  $this->total_ht = 0;
3643  $this->total_tva = 0;
3644  $this->total_localtax1 = 0;
3645  $this->total_localtax2 = 0;
3646  $this->total_ttc = 0;
3647  $total_ht_by_vats = array();
3648  $total_tva_by_vats = array();
3649  $total_ttc_by_vats = array();
3650  $this->multicurrency_total_ht = 0;
3651  $this->multicurrency_total_tva = 0;
3652  $this->multicurrency_total_ttc = 0;
3653 
3654  $num = $this->db->num_rows($resql);
3655  $i = 0;
3656  while ($i < $num) {
3657  $obj = $this->db->fetch_object($resql);
3658 
3659  // Note: There is no check on detail line and no check on total, if $forcedroundingmode = 'none'
3660  $parameters = array('fk_element' => $obj->rowid);
3661  $reshook = $hookmanager->executeHooks('changeRoundingMode', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
3662 
3663  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'
3664  // This part of code is to fix data. We should not call it too often.
3665  $localtax_array = array($obj->localtax1_type, $obj->localtax1_tx, $obj->localtax2_type, $obj->localtax2_tx);
3666  $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);
3667 
3668  $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.
3669  $diff_on_current_total = price2num($obj->total_ttc - $obj->total_ht - $obj->total_tva - $obj->total_localtax1 - $obj->total_localtax2, 'MT', 1);
3670  //var_dump($obj->total_ht.' '.$obj->total_tva.' '.$obj->total_localtax1.' '.$obj->total_localtax2.' => '.$obj->total_ttc);
3671  //var_dump($diff_when_using_price_ht.' '.$diff_on_current_total);
3672 
3673  if ($diff_on_current_total) {
3674  // This should not happen, we should always have in table: total_ttc = total_ht + total_vat + total_localtax1 + total_localtax2
3675  $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);
3676  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);
3677  $resqlfix = $this->db->query($sqlfix);
3678  if (!$resqlfix) {
3679  dol_print_error($this->db, 'Failed to update line');
3680  }
3681  $obj->total_tva = $tmpcal[1];
3682  $obj->total_ttc = $tmpcal[2];
3683  } elseif ($diff_when_using_price_ht && $roundingadjust == '0') {
3684  // After calculation from HT, total is consistent but we have found a difference between VAT part in calculation and into database and
3685  // we ask to force the use of rounding on line (like done on calculation) so we force update of line
3686  $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);
3687  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);
3688  $resqlfix = $this->db->query($sqlfix);
3689  if (!$resqlfix) {
3690  dol_print_error($this->db, 'Failed to update line');
3691  }
3692  $obj->total_tva = $tmpcal[1];
3693  $obj->total_ttc = $tmpcal[2];
3694  }
3695  }
3696 
3697  $this->total_ht += $obj->total_ht; // The field visible at end of line detail
3698  $this->total_tva += $obj->total_tva;
3699  $this->total_localtax1 += $obj->total_localtax1;
3700  $this->total_localtax2 += $obj->total_localtax2;
3701  $this->total_ttc += $obj->total_ttc;
3702  $this->multicurrency_total_ht += $obj->multicurrency_total_ht; // The field visible at end of line detail
3703  $this->multicurrency_total_tva += $obj->multicurrency_total_tva;
3704  $this->multicurrency_total_ttc += $obj->multicurrency_total_ttc;
3705 
3706  if (!isset($total_ht_by_vats[$obj->vatrate])) {
3707  $total_ht_by_vats[$obj->vatrate] = 0;
3708  }
3709  if (!isset($total_tva_by_vats[$obj->vatrate])) {
3710  $total_tva_by_vats[$obj->vatrate] = 0;
3711  }
3712  if (!isset($total_ttc_by_vats[$obj->vatrate])) {
3713  $total_ttc_by_vats[$obj->vatrate] = 0;
3714  }
3715  $total_ht_by_vats[$obj->vatrate] += $obj->total_ht;
3716  $total_tva_by_vats[$obj->vatrate] += $obj->total_tva;
3717  $total_ttc_by_vats[$obj->vatrate] += $obj->total_ttc;
3718 
3719  if ($forcedroundingmode == '1') { // Check if we need adjustement onto line for vat. TODO This works on the company currency but not on multicurrency
3720  $tmpvat = price2num($total_ht_by_vats[$obj->vatrate] * $obj->vatrate / 100, 'MT', 1);
3721  $diff = price2num($total_tva_by_vats[$obj->vatrate] - $tmpvat, 'MT', 1);
3722  //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";
3723  if ($diff) {
3724  if (abs($diff) > (10 * pow(10, -1 * getDolGlobalInt('MAIN_MAX_DECIMALS_TOT', 0)))) {
3725  // If error is more than 10 times the accurancy of rounding. This should not happen.
3726  $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.';
3727  dol_syslog($errmsg, LOG_WARNING);
3728  dol_print_error('', $errmsg);
3729  exit;
3730  }
3731  $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);
3732  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);
3733 
3734  $resqlfix = $this->db->query($sqlfix);
3735 
3736  if (!$resqlfix) {
3737  dol_print_error($this->db, 'Failed to update line');
3738  }
3739 
3740  $this->total_tva = (float) price2num($this->total_tva - $diff, '', 1);
3741  $this->total_ttc = (float) price2num($this->total_ttc - $diff, '', 1);
3742  $total_tva_by_vats[$obj->vatrate] = (float) price2num($total_tva_by_vats[$obj->vatrate] - $diff, '', 1);
3743  $total_ttc_by_vats[$obj->vatrate] = (float) price2num($total_ttc_by_vats[$obj->vatrate] - $diff, '', 1);
3744  }
3745  }
3746 
3747  $i++;
3748  }
3749 
3750  // Add revenue stamp to total
3751  $this->total_ttc += isset($this->revenuestamp) ? $this->revenuestamp : 0;
3752  $this->multicurrency_total_ttc += isset($this->revenuestamp) ? ($this->revenuestamp * $multicurrency_tx) : 0;
3753 
3754  // Situations totals
3755  if (!empty($this->situation_cycle_ref) && $this->situation_counter > 1 && method_exists($this, 'get_prev_sits') && $this->type != $this::TYPE_CREDIT_NOTE) {
3756  $prev_sits = $this->get_prev_sits();
3757 
3758  foreach ($prev_sits as $sit) { // $sit is an object Facture loaded with a fetch.
3759  $this->total_ht -= $sit->total_ht;
3760  $this->total_tva -= $sit->total_tva;
3761  $this->total_localtax1 -= $sit->total_localtax1;
3762  $this->total_localtax2 -= $sit->total_localtax2;
3763  $this->total_ttc -= $sit->total_ttc;
3764  $this->multicurrency_total_ht -= $sit->multicurrency_total_ht;
3765  $this->multicurrency_total_tva -= $sit->multicurrency_total_tva;
3766  $this->multicurrency_total_ttc -= $sit->multicurrency_total_ttc;
3767  }
3768  }
3769 
3770  // Clean total
3771  $this->total_ht = (float) price2num($this->total_ht);
3772  $this->total_tva = (float) price2num($this->total_tva);
3773  $this->total_localtax1 = (float) price2num($this->total_localtax1);
3774  $this->total_localtax2 = (float) price2num($this->total_localtax2);
3775  $this->total_ttc = (float) price2num($this->total_ttc);
3776 
3777  $this->db->free($resql);
3778 
3779  // Now update global fields total_ht, total_ttc, total_tva, total_localtax1, total_localtax2, multicurrency_total_* of main object
3780  $fieldht = 'total_ht';
3781  $fieldtva = 'tva';
3782  $fieldlocaltax1 = 'localtax1';
3783  $fieldlocaltax2 = 'localtax2';
3784  $fieldttc = 'total_ttc';
3785  // Specific code for backward compatibility with old field names
3786  if (in_array($this->element, array('propal', 'commande', 'facture', 'facturerec', 'supplier_proposal', 'order_supplier', 'facture_fourn', 'invoice_supplier', 'invoice_supplier_rec', 'expensereport'))) {
3787  $fieldtva = 'total_tva';
3788  }
3789 
3790  if (empty($nodatabaseupdate)) {
3791  $sql = "UPDATE ".$this->db->prefix().$this->table_element.' SET';
3792  $sql .= " ".$fieldht." = ".((float) price2num($this->total_ht, 'MT', 1)).",";
3793  $sql .= " ".$fieldtva." = ".((float) price2num($this->total_tva, 'MT', 1)).",";
3794  $sql .= " ".$fieldlocaltax1." = ".((float) price2num($this->total_localtax1, 'MT', 1)).",";
3795  $sql .= " ".$fieldlocaltax2." = ".((float) price2num($this->total_localtax2, 'MT', 1)).",";
3796  $sql .= " ".$fieldttc." = ".((float) price2num($this->total_ttc, 'MT', 1));
3797  $sql .= ", multicurrency_total_ht = ".((float) price2num($this->multicurrency_total_ht, 'MT', 1));
3798  $sql .= ", multicurrency_total_tva = ".((float) price2num($this->multicurrency_total_tva, 'MT', 1));
3799  $sql .= ", multicurrency_total_ttc = ".((float) price2num($this->multicurrency_total_ttc, 'MT', 1));
3800  $sql .= " WHERE rowid = ".((int) $this->id);
3801 
3802  dol_syslog(get_class($this)."::update_price", LOG_DEBUG);
3803  $resql = $this->db->query($sql);
3804 
3805  if (!$resql) {
3806  $error++;
3807  $this->error = $this->db->lasterror();
3808  $this->errors[] = $this->db->lasterror();
3809  }
3810  }
3811 
3812  if (!$error) {
3813  return 1;
3814  } else {
3815  return -1;
3816  }
3817  } else {
3818  dol_print_error($this->db, 'Bad request in update_price');
3819  return -1;
3820  }
3821  }
3822 
3823  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3834  public function add_object_linked($origin = null, $origin_id = null, $f_user = null, $notrigger = 0)
3835  {
3836  // phpcs:enable
3837  global $user, $hookmanager, $action;
3838  $origin = (!empty($origin) ? $origin : $this->origin);
3839  $origin_id = (!empty($origin_id) ? $origin_id : $this->origin_id);
3840  $f_user = isset($f_user) ? $f_user : $user;
3841 
3842  // Special case
3843  if ($origin == 'order') {
3844  $origin = 'commande';
3845  }
3846  if ($origin == 'invoice') {
3847  $origin = 'facture';
3848  }
3849  if ($origin == 'invoice_template') {
3850  $origin = 'facturerec';
3851  }
3852  if ($origin == 'supplierorder') {
3853  $origin = 'order_supplier';
3854  }
3855 
3856  // 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.
3857  // 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.
3858  $coremodule = array('knowledgemanagement', 'partnership', 'workstation', 'ticket', 'recruitment', 'eventorganization', 'asset');
3859  // Add module part to target type if object has $module property and isn't in core modules.
3860  $targettype = ((!empty($this->module) && ! in_array($this->module, $coremodule)) ? $this->module.'_' : '').$this->element;
3861 
3862  $parameters = array('targettype'=>$targettype);
3863  // Hook for explicitly set the targettype if it must be differtent than $this->element
3864  $reshook = $hookmanager->executeHooks('setLinkedObjectSourceTargetType', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
3865  if ($reshook > 0) {
3866  if (!empty($hookmanager->resArray['targettype'])) $targettype = $hookmanager->resArray['targettype'];
3867  }
3868 
3869  $this->db->begin();
3870  $error = 0;
3871 
3872  $sql = "INSERT INTO " . $this->db->prefix() . "element_element (";
3873  $sql .= "fk_source";
3874  $sql .= ", sourcetype";
3875  $sql .= ", fk_target";
3876  $sql .= ", targettype";
3877  $sql .= ") VALUES (";
3878  $sql .= ((int) $origin_id);
3879  $sql .= ", '" . $this->db->escape($origin) . "'";
3880  $sql .= ", " . ((int) $this->id);
3881  $sql .= ", '" . $this->db->escape($targettype) . "'";
3882  $sql .= ")";
3883 
3884  dol_syslog(get_class($this) . "::add_object_linked", LOG_DEBUG);
3885  if ($this->db->query($sql)) {
3886  if (!$notrigger) {
3887  // Call trigger
3888  $this->context['link_origin'] = $origin;
3889  $this->context['link_origin_id'] = $origin_id;
3890  $result = $this->call_trigger('OBJECT_LINK_INSERT', $f_user);
3891  if ($result < 0) {
3892  $error++;
3893  }
3894  // End call triggers
3895  }
3896  } else {
3897  $this->error = $this->db->lasterror();
3898  $error++;
3899  }
3900 
3901  if (!$error) {
3902  $this->db->commit();
3903  return 1;
3904  } else {
3905  $this->db->rollback();
3906  return 0;
3907  }
3908  }
3909 
3932  public function fetchObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $clause = 'OR', $alsosametype = 1, $orderby = 'sourcetype', $loadalsoobjects = 1)
3933  {
3934  global $conf, $hookmanager, $action;
3935 
3936  // Important for pdf generation time reduction
3937  // This boolean is true if $this->linkedObjects has already been loaded with all objects linked without filter
3938  if ($this->id > 0 && !empty($this->linkedObjectsFullLoaded[$this->id])) {
3939  return 1;
3940  }
3941 
3942  $this->linkedObjectsIds = array();
3943  $this->linkedObjects = array();
3944 
3945  $justsource = false;
3946  $justtarget = false;
3947  $withtargettype = false;
3948  $withsourcetype = false;
3949 
3950  $parameters = array('sourcetype'=>$sourcetype, 'sourceid'=>$sourceid, 'targettype'=>$targettype, 'targetid'=>$targetid);
3951  // Hook for explicitly set the targettype if it must be differtent than $this->element
3952  $reshook = $hookmanager->executeHooks('setLinkedObjectSourceTargetType', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
3953  if ($reshook > 0) {
3954  if (!empty($hookmanager->resArray['sourcetype'])) $sourcetype = $hookmanager->resArray['sourcetype'];
3955  if (!empty($hookmanager->resArray['sourceid'])) $sourceid = $hookmanager->resArray['sourceid'];
3956  if (!empty($hookmanager->resArray['targettype'])) $targettype = $hookmanager->resArray['targettype'];
3957  if (!empty($hookmanager->resArray['targetid'])) $targetid = $hookmanager->resArray['targetid'];
3958  }
3959 
3960  if (!empty($sourceid) && !empty($sourcetype) && empty($targetid)) {
3961  $justsource = true; // the source (id and type) is a search criteria
3962  if (!empty($targettype)) {
3963  $withtargettype = true;
3964  }
3965  }
3966  if (!empty($targetid) && !empty($targettype) && empty($sourceid)) {
3967  $justtarget = true; // the target (id and type) is a search criteria
3968  if (!empty($sourcetype)) {
3969  $withsourcetype = true;
3970  }
3971  }
3972 
3973  $sourceid = (!empty($sourceid) ? $sourceid : $this->id);
3974  $targetid = (!empty($targetid) ? $targetid : $this->id);
3975  $sourcetype = (!empty($sourcetype) ? $sourcetype : $this->element);
3976  $targettype = (!empty($targettype) ? $targettype : $this->element);
3977 
3978  /*if (empty($sourceid) && empty($targetid))
3979  {
3980  dol_syslog('Bad usage of function. No source nor target id defined (nor as parameter nor as object id)', LOG_ERR);
3981  return -1;
3982  }*/
3983 
3984  // Links between objects are stored in table element_element
3985  $sql = "SELECT rowid, fk_source, sourcetype, fk_target, targettype";
3986  $sql .= " FROM ".$this->db->prefix()."element_element";
3987  $sql .= " WHERE ";
3988  if ($justsource || $justtarget) {
3989  if ($justsource) {
3990  $sql .= "fk_source = ".((int) $sourceid)." AND sourcetype = '".$this->db->escape($sourcetype)."'";
3991  if ($withtargettype) {
3992  $sql .= " AND targettype = '".$this->db->escape($targettype)."'";
3993  }
3994  } elseif ($justtarget) {
3995  $sql .= "fk_target = ".((int) $targetid)." AND targettype = '".$this->db->escape($targettype)."'";
3996  if ($withsourcetype) {
3997  $sql .= " AND sourcetype = '".$this->db->escape($sourcetype)."'";
3998  }
3999  }
4000  } else {
4001  $sql .= "(fk_source = ".((int) $sourceid)." AND sourcetype = '".$this->db->escape($sourcetype)."')";
4002  $sql .= " ".$clause." (fk_target = ".((int) $targetid)." AND targettype = '".$this->db->escape($targettype)."')";
4003  if ($loadalsoobjects && $this->id > 0 && $sourceid == $this->id && $sourcetype == $this->element && $targetid == $this->id && $targettype == $this->element && $clause == 'OR') {
4004  $this->linkedObjectsFullLoaded[$this->id] = true;
4005  }
4006  }
4007  $sql .= " ORDER BY ".$orderby;
4008 
4009  dol_syslog(get_class($this)."::fetchObjectLink", LOG_DEBUG);
4010  $resql = $this->db->query($sql);
4011  if ($resql) {
4012  $num = $this->db->num_rows($resql);
4013  $i = 0;
4014  while ($i < $num) {
4015  $obj = $this->db->fetch_object($resql);
4016  if ($justsource || $justtarget) {
4017  if ($justsource) {
4018  $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
4019  } elseif ($justtarget) {
4020  $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
4021  }
4022  } else {
4023  if ($obj->fk_source == $sourceid && $obj->sourcetype == $sourcetype) {
4024  $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
4025  }
4026  if ($obj->fk_target == $targetid && $obj->targettype == $targettype) {
4027  $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
4028  }
4029  }
4030  $i++;
4031  }
4032 
4033  if (!empty($this->linkedObjectsIds)) {
4034  $tmparray = $this->linkedObjectsIds;
4035  foreach ($tmparray as $objecttype => $objectids) { // $objecttype is a module name ('facture', 'mymodule', ...) or a module name with a suffix ('project_task', 'mymodule_myobj', ...)
4036  // Parse element/subelement (ex: project_task, cabinetmed_consultation, ...)
4037  $module = $element = $subelement = $objecttype;
4038  $regs = array();
4039  if ($objecttype != 'supplier_proposal' && $objecttype != 'order_supplier' && $objecttype != 'invoice_supplier'
4040  && preg_match('/^([^_]+)_([^_]+)/i', $objecttype, $regs)) {
4041  $module = $element = $regs[1];
4042  $subelement = $regs[2];
4043  }
4044 
4045  $classpath = $element.'/class';
4046  // To work with non standard classpath or module name
4047  if ($objecttype == 'facture') {
4048  $classpath = 'compta/facture/class';
4049  } elseif ($objecttype == 'facturerec') {
4050  $classpath = 'compta/facture/class';
4051  $module = 'facture';
4052  } elseif ($objecttype == 'propal') {
4053  $classpath = 'comm/propal/class';
4054  } elseif ($objecttype == 'supplier_proposal') {
4055  $classpath = 'supplier_proposal/class';
4056  } elseif ($objecttype == 'shipping') {
4057  $classpath = 'expedition/class';
4058  $subelement = 'expedition';
4059  $module = 'expedition_bon';
4060  } elseif ($objecttype == 'delivery') {
4061  $classpath = 'delivery/class';
4062  $subelement = 'delivery';
4063  $module = 'delivery_note';
4064  } elseif ($objecttype == 'invoice_supplier' || $objecttype == 'order_supplier') {
4065  $classpath = 'fourn/class';
4066  $module = 'fournisseur';
4067  } elseif ($objecttype == 'fichinter') {
4068  $classpath = 'fichinter/class';
4069  $subelement = 'fichinter';
4070  $module = 'ficheinter';
4071  } elseif ($objecttype == 'subscription') {
4072  $classpath = 'adherents/class';
4073  $module = 'adherent';
4074  } elseif ($objecttype == 'contact') {
4075  $module = 'societe';
4076  }
4077  // Set classfile
4078  $classfile = strtolower($subelement);
4079  $classname = ucfirst($subelement);
4080 
4081  if ($objecttype == 'order') {
4082  $classfile = 'commande';
4083  $classname = 'Commande';
4084  } elseif ($objecttype == 'invoice_supplier') {
4085  $classfile = 'fournisseur.facture';
4086  $classname = 'FactureFournisseur';
4087  } elseif ($objecttype == 'order_supplier') {
4088  $classfile = 'fournisseur.commande';
4089  $classname = 'CommandeFournisseur';
4090  } elseif ($objecttype == 'supplier_proposal') {
4091  $classfile = 'supplier_proposal';
4092  $classname = 'SupplierProposal';
4093  } elseif ($objecttype == 'facturerec') {
4094  $classfile = 'facture-rec';
4095  $classname = 'FactureRec';
4096  } elseif ($objecttype == 'subscription') {
4097  $classfile = 'subscription';
4098  $classname = 'Subscription';
4099  } elseif ($objecttype == 'project' || $objecttype == 'projet') {
4100  $classpath = 'projet/class';
4101  $classfile = 'project';
4102  $classname = 'Project';
4103  } elseif ($objecttype == 'conferenceorboothattendee') {
4104  $classpath = 'eventorganization/class';
4105  $classfile = 'conferenceorboothattendee';
4106  $classname = 'ConferenceOrBoothAttendee';
4107  $module = 'eventorganization';
4108  } elseif ($objecttype == 'conferenceorbooth') {
4109  $classpath = 'eventorganization/class';
4110  $classfile = 'conferenceorbooth';
4111  $classname = 'ConferenceOrBooth';
4112  $module = 'eventorganization';
4113  } elseif ($objecttype == 'mo') {
4114  $classpath = 'mrp/class';
4115  $classfile = 'mo';
4116  $classname = 'Mo';
4117  $module = 'mrp';
4118  }
4119 
4120  // Here $module, $classfile and $classname are set, we can use them.
4121  if (isModEnabled($module) && (($element != $this->element) || $alsosametype)) {
4122  if ($loadalsoobjects && (is_numeric($loadalsoobjects) || ($loadalsoobjects === $objecttype))) {
4123  dol_include_once('/'.$classpath.'/'.$classfile.'.class.php');
4124  //print '/'.$classpath.'/'.$classfile.'.class.php '.class_exists($classname);
4125  if (class_exists($classname)) {
4126  foreach ($objectids as $i => $objectid) { // $i is rowid into llx_element_element
4127  $object = new $classname($this->db);
4128  $ret = $object->fetch($objectid);
4129  if ($ret >= 0) {
4130  $this->linkedObjects[$objecttype][$i] = $object;
4131  }
4132  }
4133  }
4134  }
4135  } else {
4136  unset($this->linkedObjectsIds[$objecttype]);
4137  }
4138  }
4139  }
4140  return 1;
4141  } else {
4142  dol_print_error($this->db);
4143  return -1;
4144  }
4145  }
4146 
4153  public function clearObjectLinkedCache()
4154  {
4155  if ($this->id > 0 && !empty($this->linkedObjectsFullLoaded[$this->id])) {
4156  unset($this->linkedObjectsFullLoaded[$this->id]);
4157  }
4158 
4159  return 1;
4160  }
4161 
4174  public function updateObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $f_user = null, $notrigger = 0)
4175  {
4176  global $user;
4177  $updatesource = false;
4178  $updatetarget = false;
4179  $f_user = isset($f_user) ? $f_user : $user;
4180 
4181  if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) {
4182  $updatesource = true;
4183  } elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) {
4184  $updatetarget = true;
4185  }
4186 
4187  $this->db->begin();
4188  $error = 0;
4189 
4190  $sql = "UPDATE " . $this->db->prefix() . "element_element SET ";
4191  if ($updatesource) {
4192  $sql .= "fk_source = " . ((int) $sourceid);
4193  $sql .= ", sourcetype = '" . $this->db->escape($sourcetype) . "'";
4194  $sql .= " WHERE fk_target = " . ((int) $this->id);
4195  $sql .= " AND targettype = '" . $this->db->escape($this->element) . "'";
4196  } elseif ($updatetarget) {
4197  $sql .= "fk_target = " . ((int) $targetid);
4198  $sql .= ", targettype = '" . $this->db->escape($targettype) . "'";
4199  $sql .= " WHERE fk_source = " . ((int) $this->id);
4200  $sql .= " AND sourcetype = '" . $this->db->escape($this->element) . "'";
4201  }
4202 
4203  dol_syslog(get_class($this) . "::updateObjectLinked", LOG_DEBUG);
4204  if ($this->db->query($sql)) {
4205  if (!$notrigger) {
4206  // Call trigger
4207  $this->context['link_source_id'] = $sourceid;
4208  $this->context['link_source_type'] = $sourcetype;
4209  $this->context['link_target_id'] = $targetid;
4210  $this->context['link_target_type'] = $targettype;
4211  $result = $this->call_trigger('OBJECT_LINK_MODIFY', $f_user);
4212  if ($result < 0) {
4213  $error++;
4214  }
4215  // End call triggers
4216  }
4217  } else {
4218  $this->error = $this->db->lasterror();
4219  $error++;
4220  }
4221 
4222  if (!$error) {
4223  $this->db->commit();
4224  return 1;
4225  } else {
4226  $this->db->rollback();
4227  return -1;
4228  }
4229  }
4230 
4244  public function deleteObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $rowid = '', $f_user = null, $notrigger = 0)
4245  {
4246  global $user;
4247  $deletesource = false;
4248  $deletetarget = false;
4249  $f_user = isset($f_user) ? $f_user : $user;
4250 
4251  if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) {
4252  $deletesource = true;
4253  } elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) {
4254  $deletetarget = true;
4255  }
4256 
4257  $sourceid = (!empty($sourceid) ? $sourceid : $this->id);
4258  $sourcetype = (!empty($sourcetype) ? $sourcetype : $this->element);
4259  $targetid = (!empty($targetid) ? $targetid : $this->id);
4260  $targettype = (!empty($targettype) ? $targettype : $this->element);
4261  $this->db->begin();
4262  $error = 0;
4263 
4264  if (!$notrigger) {
4265  // Call trigger
4266  $this->context['link_id'] = $rowid;
4267  $this->context['link_source_id'] = $sourceid;
4268  $this->context['link_source_type'] = $sourcetype;
4269  $this->context['link_target_id'] = $targetid;
4270  $this->context['link_target_type'] = $targettype;
4271  $result = $this->call_trigger('OBJECT_LINK_DELETE', $f_user);
4272  if ($result < 0) {
4273  $error++;
4274  }
4275  // End call triggers
4276  }
4277 
4278  if (!$error) {
4279  $sql = "DELETE FROM " . $this->db->prefix() . "element_element";
4280  $sql .= " WHERE";
4281  if ($rowid > 0) {
4282  $sql .= " rowid = " . ((int) $rowid);
4283  } else {
4284  if ($deletesource) {
4285  $sql .= " fk_source = " . ((int) $sourceid) . " AND sourcetype = '" . $this->db->escape($sourcetype) . "'";
4286  $sql .= " AND fk_target = " . ((int) $this->id) . " AND targettype = '" . $this->db->escape($this->element) . "'";
4287  } elseif ($deletetarget) {
4288  $sql .= " fk_target = " . ((int) $targetid) . " AND targettype = '" . $this->db->escape($targettype) . "'";
4289  $sql .= " AND fk_source = " . ((int) $this->id) . " AND sourcetype = '" . $this->db->escape($this->element) . "'";
4290  } else {
4291  $sql .= " (fk_source = " . ((int) $this->id) . " AND sourcetype = '" . $this->db->escape($this->element) . "')";
4292  $sql .= " OR";
4293  $sql .= " (fk_target = " . ((int) $this->id) . " AND targettype = '" . $this->db->escape($this->element) . "')";
4294  }
4295  }
4296 
4297  dol_syslog(get_class($this) . "::deleteObjectLinked", LOG_DEBUG);
4298  if (!$this->db->query($sql)) {
4299  $this->error = $this->db->lasterror();
4300  $this->errors[] = $this->error;
4301  $error++;
4302  }
4303  }
4304 
4305  if (!$error) {
4306  $this->db->commit();
4307  return 1;
4308  } else {
4309  $this->db->rollback();
4310  return 0;
4311  }
4312  }
4313 
4323  public static function getAllItemsLinkedByObjectID($fk_object_where, $field_select, $field_where, $table_element)
4324  {
4325  if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
4326  return -1;
4327  }
4328 
4329  global $db;
4330 
4331  $sql = "SELECT ".$field_select." FROM ".$db->prefix().$table_element." WHERE ".$field_where." = ".((int) $fk_object_where);
4332  $resql = $db->query($sql);
4333 
4334  $TRes = array();
4335  if (!empty($resql)) {
4336  while ($res = $db->fetch_object($resql)) {
4337  $TRes[] = $res->{$field_select};
4338  }
4339  }
4340 
4341  return $TRes;
4342  }
4343 
4352  public static function deleteAllItemsLinkedByObjectID($fk_object_where, $field_where, $table_element)
4353  {
4354  if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
4355  return -1;
4356  }
4357 
4358  global $db;
4359 
4360  $sql = "DELETE FROM ".$db->prefix().$table_element." WHERE ".$field_where." = ".((int) $fk_object_where);
4361  $resql = $db->query($sql);
4362 
4363  if (empty($resql)) {
4364  return 0;
4365  }
4366 
4367  return 1;
4368  }
4369 
4380  public function setStatut($status, $elementId = null, $elementType = '', $trigkey = '', $fieldstatus = 'fk_statut')
4381  {
4382  global $user, $langs, $conf;
4383 
4384  $savElementId = $elementId; // To be used later to know if we were using the method using the id of this or not.
4385 
4386  $elementId = (!empty($elementId) ? $elementId : $this->id);
4387  $elementTable = (!empty($elementType) ? $elementType : $this->table_element);
4388 
4389  $this->db->begin();
4390 
4391  if ($elementTable == 'facture_rec') {
4392  $fieldstatus = "suspended";
4393  }
4394  if ($elementTable == 'mailing') {
4395  $fieldstatus = "statut";
4396  }
4397  if ($elementTable == 'cronjob') {
4398  $fieldstatus = "status";
4399  }
4400  if ($elementTable == 'user') {
4401  $fieldstatus = "statut";
4402  }
4403  if ($elementTable == 'expensereport') {
4404  $fieldstatus = "fk_statut";
4405  }
4406  if ($elementTable == 'commande_fournisseur_dispatch') {
4407  $fieldstatus = "status";
4408  }
4409  if (isset($this->fields) && is_array($this->fields) && array_key_exists('status', $this->fields)) {
4410  $fieldstatus = 'status';
4411  }
4412 
4413  $sql = "UPDATE ".$this->db->prefix().$elementTable;
4414  $sql .= " SET ".$fieldstatus." = ".((int) $status);
4415  // If status = 1 = validated, update also fk_user_valid
4416  // TODO Replace the test on $elementTable by doing a test on existence of the field in $this->fields
4417  if ($status == 1 && in_array($elementTable, array('expensereport', 'inventory'))) {
4418  $sql .= ", fk_user_valid = ".((int) $user->id);
4419  }
4420  if ($status == 1 && in_array($elementTable, array('expensereport'))) {
4421  $sql .= ", date_valid = '".$this->db->idate(dol_now())."'";
4422  }
4423  if ($status == 1 && in_array($elementTable, array('inventory'))) {
4424  $sql .= ", date_validation = '".$this->db->idate(dol_now())."'";
4425  }
4426  $sql .= " WHERE rowid = ".((int) $elementId);
4427  $sql .= " AND ".$fieldstatus." <> ".((int) $status); // We avoid update if status already correct
4428 
4429  dol_syslog(get_class($this)."::setStatut", LOG_DEBUG);
4430  $resql = $this->db->query($sql);
4431  if ($resql) {
4432  $error = 0;
4433 
4434  $nb_rows_affected = $this->db->affected_rows($resql); // should be 1 or 0 if status was already correct
4435 
4436  if ($nb_rows_affected > 0) {
4437  if (empty($trigkey)) {
4438  // Try to guess trigkey (for backward compatibility, now we should have trigkey defined into the call of setStatus)
4439  if ($this->element == 'supplier_proposal' && $status == 2) {
4440  $trigkey = 'SUPPLIER_PROPOSAL_SIGN'; // 2 = SupplierProposal::STATUS_SIGNED. Can't use constant into this generic class
4441  }
4442  if ($this->element == 'supplier_proposal' && $status == 3) {
4443  $trigkey = 'SUPPLIER_PROPOSAL_REFUSE'; // 3 = SupplierProposal::STATUS_REFUSED. Can't use constant into this generic class
4444  }
4445  if ($this->element == 'supplier_proposal' && $status == 4) {
4446  $trigkey = 'SUPPLIER_PROPOSAL_CLOSE'; // 4 = SupplierProposal::STATUS_CLOSED. Can't use constant into this generic class
4447  }
4448  if ($this->element == 'fichinter' && $status == 3) {
4449  $trigkey = 'FICHINTER_CLASSIFY_DONE';
4450  }
4451  if ($this->element == 'fichinter' && $status == 2) {
4452  $trigkey = 'FICHINTER_CLASSIFY_BILLED';
4453  }
4454  if ($this->element == 'fichinter' && $status == 1) {
4455  $trigkey = 'FICHINTER_CLASSIFY_UNBILLED';
4456  }
4457  }
4458 
4459  if ($trigkey) {
4460  // Call trigger
4461  $result = $this->call_trigger($trigkey, $user);
4462  if ($result < 0) {
4463  $error++;
4464  }
4465  // End call triggers
4466  }
4467  } else {
4468  // The status was probably already good. We do nothing more, no triggers.
4469  }
4470 
4471  if (!$error) {
4472  $this->db->commit();
4473 
4474  if (empty($savElementId)) {
4475  // If the element we update is $this (so $elementId was provided as null)
4476  if ($fieldstatus == 'tosell') {
4477  $this->status = $status;
4478  } elseif ($fieldstatus == 'tobuy') {
4479  $this->status_buy = $status;
4480  } else {
4481  $this->statut = $status;
4482  $this->status = $status;
4483  }
4484  }
4485 
4486  return 1;
4487  } else {
4488  $this->db->rollback();
4489  dol_syslog(get_class($this)."::setStatut ".$this->error, LOG_ERR);
4490  return -1;
4491  }
4492  } else {
4493  $this->error = $this->db->lasterror();
4494  $this->db->rollback();
4495  return -1;
4496  }
4497  }
4498 
4499 
4507  public function getCanvas($id = 0, $ref = '')
4508  {
4509  global $conf;
4510 
4511  if (empty($id) && empty($ref)) {
4512  return 0;
4513  }
4514  if (!empty($conf->global->MAIN_DISABLE_CANVAS)) {
4515  return 0; // To increase speed. Not enabled by default.
4516  }
4517 
4518  // Clean parameters
4519  $ref = trim($ref);
4520 
4521  $sql = "SELECT rowid, canvas";
4522  $sql .= " FROM ".$this->db->prefix().$this->table_element;
4523  $sql .= " WHERE entity IN (".getEntity($this->element).")";
4524  if (!empty($id)) {
4525  $sql .= " AND rowid = ".((int) $id);
4526  }
4527  if (!empty($ref)) {
4528  $sql .= " AND ref = '".$this->db->escape($ref)."'";
4529  }
4530 
4531  $resql = $this->db->query($sql);
4532  if ($resql) {
4533  $obj = $this->db->fetch_object($resql);
4534  if ($obj) {
4535  $this->canvas = $obj->canvas;
4536  return 1;
4537  } else {
4538  return 0;
4539  }
4540  } else {
4541  dol_print_error($this->db);
4542  return -1;
4543  }
4544  }
4545 
4546 
4553  public function getSpecialCode($lineid)
4554  {
4555  $sql = "SELECT special_code FROM ".$this->db->prefix().$this->table_element_line;
4556  $sql .= " WHERE rowid = ".((int) $lineid);
4557  $resql = $this->db->query($sql);
4558  if ($resql) {
4559  $row = $this->db->fetch_row($resql);
4560  return $row[0];
4561  }
4562  }
4563 
4572  public function isObjectUsed($id = 0, $entity = 0)
4573  {
4574  global $langs;
4575 
4576  if (empty($id)) {
4577  $id = $this->id;
4578  }
4579 
4580  // Check parameters
4581  if (!isset($this->childtables) || !is_array($this->childtables) || count($this->childtables) == 0) {
4582  dol_print_error('Called isObjectUsed on a class with property this->childtables not defined');
4583  return -1;
4584  }
4585 
4586  $arraytoscan = $this->childtables;
4587  // For backward compatibility, we check if array is old format array('table1', 'table2', ...)
4588  $tmparray = array_keys($this->childtables);
4589  if (is_numeric($tmparray[0])) {
4590  $arraytoscan = array_flip($this->childtables);
4591  }
4592 
4593  // Test if child exists
4594  $haschild = 0;
4595  foreach ($arraytoscan as $table => $element) {
4596  //print $id.'-'.$table.'-'.$elementname.'<br>';
4597  // Check if element can be deleted
4598  $sql = "SELECT COUNT(*) as nb";
4599  $sql.= " FROM ".$this->db->prefix().$table." as c";
4600  if (!empty($element['parent']) && !empty($element['parentkey'])) {
4601  $sql.= ", ".$this->db->prefix().$element['parent']." as p";
4602  }
4603  $sql.= " WHERE c.".$this->fk_element." = ".((int) $id);
4604  if (!empty($element['parent']) && !empty($element['parentkey'])) {
4605  $sql.= " AND c.".$element['parentkey']." = p.rowid";
4606  }
4607  if (!empty($entity)) {
4608  if (!empty($element['parent']) && !empty($element['parentkey'])) {
4609  $sql.= " AND p.entity = ".((int) $entity);
4610  } else {
4611  $sql.= " AND c.entity = ".((int) $entity);
4612  }
4613  }
4614  $resql = $this->db->query($sql);
4615  if ($resql) {
4616  $obj = $this->db->fetch_object($resql);
4617  if ($obj->nb > 0) {
4618  $langs->load("errors");
4619  //print 'Found into table '.$table.', type '.$langs->transnoentitiesnoconv($elementname).', haschild='.$haschild;
4620  $haschild += $obj->nb;
4621  if (is_numeric($element)) { // very old usage array('table1', 'table2', ...)
4622  $this->errors[] = $langs->transnoentitiesnoconv("ErrorRecordHasAtLeastOneChildOfType", method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref, $table);
4623  } elseif (is_string($element)) { // old usage array('table1' => 'TranslateKey1', 'table2' => 'TranslateKey2', ...)
4624  $this->errors[] = $langs->transnoentitiesnoconv("ErrorRecordHasAtLeastOneChildOfType", method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref, $langs->transnoentitiesnoconv($element));
4625  } else { // new usage: $element['name']=Translation key
4626  $this->errors[] = $langs->transnoentitiesnoconv("ErrorRecordHasAtLeastOneChildOfType", method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref, $langs->transnoentitiesnoconv($element['name']));
4627  }
4628  break; // We found at least one, we stop here
4629  }
4630  } else {
4631  $this->errors[] = $this->db->lasterror();
4632  return -1;
4633  }
4634  }
4635  if ($haschild > 0) {
4636  $this->errors[] = "ErrorRecordHasChildren";
4637  return $haschild;
4638  } else {
4639  return 0;
4640  }
4641  }
4642 
4649  public function hasProductsOrServices($predefined = -1)
4650  {
4651  $nb = 0;
4652 
4653  foreach ($this->lines as $key => $val) {
4654  $qualified = 0;
4655  if ($predefined == -1) {
4656  $qualified = 1;
4657  }
4658  if ($predefined == 1 && $val->fk_product > 0) {
4659  $qualified = 1;
4660  }
4661  if ($predefined == 0 && $val->fk_product <= 0) {
4662  $qualified = 1;
4663  }
4664  if ($predefined == 2 && $val->fk_product > 0 && $val->product_type == 0) {
4665  $qualified = 1;
4666  }
4667  if ($predefined == 3 && $val->fk_product > 0 && $val->product_type == 1) {
4668  $qualified = 1;
4669  }
4670  if ($qualified) {
4671  $nb++;
4672  }
4673  }
4674  dol_syslog(get_class($this).'::hasProductsOrServices we found '.$nb.' qualified lines of products/servcies');
4675  return $nb;
4676  }
4677 
4683  public function getTotalDiscount()
4684  {
4685  if (!empty($this->table_element_line) ) {
4686  $total_discount = 0.00;
4687 
4688  $sql = "SELECT subprice as pu_ht, qty, remise_percent, total_ht";
4689  $sql .= " FROM ".$this->db->prefix().$this->table_element_line;
4690  $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
4691 
4692  dol_syslog(get_class($this).'::getTotalDiscount', LOG_DEBUG);
4693  $resql = $this->db->query($sql);
4694  if ($resql) {
4695  $num = $this->db->num_rows($resql);
4696  $i = 0;
4697  while ($i < $num) {
4698  $obj = $this->db->fetch_object($resql);
4699 
4700  $pu_ht = $obj->pu_ht;
4701  $qty = $obj->qty;
4702  $total_ht = $obj->total_ht;
4703 
4704  $total_discount_line = floatval(price2num(($pu_ht * $qty) - $total_ht, 'MT'));
4705  $total_discount += $total_discount_line;
4706 
4707  $i++;
4708  }
4709  }
4710 
4711  //print $total_discount; exit;
4712  return price2num($total_discount);
4713  }
4714 
4715  return null;
4716  }
4717 
4718 
4725  public function getTotalWeightVolume()
4726  {
4727  $totalWeight = 0;
4728  $totalVolume = 0;
4729  // defined for shipment only
4730  $totalOrdered = '';
4731  // defined for shipment only
4732  $totalToShip = '';
4733 
4734  foreach ($this->lines as $line) {
4735  if (isset($line->qty_asked)) {
4736  if (empty($totalOrdered)) {
4737  $totalOrdered = 0; // Avoid warning because $totalOrdered is ''
4738  }
4739  $totalOrdered += $line->qty_asked; // defined for shipment only
4740  }
4741  if (isset($line->qty_shipped)) {
4742  if (empty($totalToShip)) {
4743  $totalToShip = 0; // Avoid warning because $totalToShip is ''
4744  }
4745  $totalToShip += $line->qty_shipped; // defined for shipment only
4746  } elseif ($line->element == 'commandefournisseurdispatch' && isset($line->qty)) {
4747  if (empty($totalToShip)) {
4748  $totalToShip = 0;
4749  }
4750  $totalToShip += $line->qty; // defined for reception only
4751  }
4752 
4753  // Define qty, weight, volume, weight_units, volume_units
4754  if ($this->element == 'shipping') {
4755  // for shipments
4756  $qty = $line->qty_shipped ? $line->qty_shipped : 0;
4757  } else {
4758  $qty = $line->qty ? $line->qty : 0;
4759  }
4760 
4761  $weight = !empty($line->weight) ? $line->weight : 0;
4762  ($weight == 0 && !empty($line->product->weight)) ? $weight = $line->product->weight : 0;
4763  $volume = !empty($line->volume) ? $line->volume : 0;
4764  ($volume == 0 && !empty($line->product->volume)) ? $volume = $line->product->volume : 0;
4765 
4766  $weight_units = !empty($line->weight_units) ? $line->weight_units : 0;
4767  ($weight_units == 0 && !empty($line->product->weight_units)) ? $weight_units = $line->product->weight_units : 0;
4768  $volume_units = !empty($line->volume_units) ? $line->volume_units : 0;
4769  ($volume_units == 0 && !empty($line->product->volume_units)) ? $volume_units = $line->product->volume_units : 0;
4770 
4771  $weightUnit = 0;
4772  $volumeUnit = 0;
4773  if (!empty($weight_units)) {
4774  $weightUnit = $weight_units;
4775  }
4776  if (!empty($volume_units)) {
4777  $volumeUnit = $volume_units;
4778  }
4779 
4780  if (empty($totalWeight)) {
4781  $totalWeight = 0; // Avoid warning because $totalWeight is ''
4782  }
4783  if (empty($totalVolume)) {
4784  $totalVolume = 0; // Avoid warning because $totalVolume is ''
4785  }
4786 
4787  //var_dump($line->volume_units);
4788  if ($weight_units < 50) { // < 50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch)
4789  $trueWeightUnit = pow(10, $weightUnit);
4790  $totalWeight += $weight * $qty * $trueWeightUnit;
4791  } else {
4792  if ($weight_units == 99) {
4793  // conversion 1 Pound = 0.45359237 KG
4794  $trueWeightUnit = 0.45359237;
4795  $totalWeight += $weight * $qty * $trueWeightUnit;
4796  } elseif ($weight_units == 98) {
4797  // conversion 1 Ounce = 0.0283495 KG
4798  $trueWeightUnit = 0.0283495;
4799  $totalWeight += $weight * $qty * $trueWeightUnit;
4800  } else {
4801  $totalWeight += $weight * $qty; // This may be wrong if we mix different units
4802  }
4803  }
4804  if ($volume_units < 50) { // >50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch)
4805  //print $line->volume."x".$line->volume_units."x".($line->volume_units < 50)."x".$volumeUnit;
4806  $trueVolumeUnit = pow(10, $volumeUnit);
4807  //print $line->volume;
4808  $totalVolume += $volume * $qty * $trueVolumeUnit;
4809  } else {
4810  $totalVolume += $volume * $qty; // This may be wrong if we mix different units
4811  }
4812  }
4813 
4814  return array('weight'=>$totalWeight, 'volume'=>$totalVolume, 'ordered'=>$totalOrdered, 'toship'=>$totalToShip);
4815  }
4816 
4817 
4823  public function setExtraParameters()
4824  {
4825  $this->db->begin();
4826 
4827  $extraparams = (!empty($this->extraparams) ? json_encode($this->extraparams) : null);
4828 
4829  $sql = "UPDATE ".$this->db->prefix().$this->table_element;
4830  $sql .= " SET extraparams = ".(!empty($extraparams) ? "'".$this->db->escape($extraparams)."'" : "null");
4831  $sql .= " WHERE rowid = ".((int) $this->id);
4832 
4833  dol_syslog(get_class($this)."::setExtraParameters", LOG_DEBUG);
4834  $resql = $this->db->query($sql);
4835  if (!$resql) {
4836  $this->error = $this->db->lasterror();
4837  $this->db->rollback();
4838  return -1;
4839  } else {
4840  $this->db->commit();
4841  return 1;
4842  }
4843  }
4844 
4845 
4846  // --------------------
4847  // TODO: All functions here must be redesigned and moved as they are not business functions but output functions
4848  // --------------------
4849 
4850  /* This is to show add lines */
4851 
4861  public function formAddObjectLine($dateSelector, $seller, $buyer, $defaulttpldir = '/core/tpl')
4862  {
4863  global $conf, $user, $langs, $object, $hookmanager, $extrafields;
4864  global $form;
4865 
4866  // Line extrafield
4867  if (!is_object($extrafields)) {
4868  require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
4869  $extrafields = new ExtraFields($this->db);
4870  }
4871  $extrafields->fetch_name_optionals_label($this->table_element_line);
4872 
4873  // Output template part (modules that overwrite templates must declare this into descriptor)
4874  // Use global variables + $dateSelector + $seller and $buyer
4875  // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook 'formAddObjectLine'.
4876  $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
4877  foreach ($dirtpls as $module => $reldir) {
4878  if (!empty($module)) {
4879  $tpl = dol_buildpath($reldir.'/objectline_create.tpl.php');
4880  } else {
4881  $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_create.tpl.php';
4882  }
4883 
4884  if (empty($conf->file->strict_mode)) {
4885  $res = @include $tpl;
4886  } else {
4887  $res = include $tpl; // for debug
4888  }
4889  if ($res) {
4890  break;
4891  }
4892  }
4893  }
4894 
4895 
4896 
4897  /* This is to show array of line of details */
4898 
4899 
4914  public function printObjectLines($action, $seller, $buyer, $selected = 0, $dateSelector = 0, $defaulttpldir = '/core/tpl')
4915  {
4916  global $conf, $hookmanager, $langs, $user, $form, $extrafields, $object;
4917  // TODO We should not use global var for this
4918  global $inputalsopricewithtax, $usemargins, $disableedit, $disablemove, $disableremove, $outputalsopricetotalwithtax;
4919 
4920  // Define usemargins
4921  $usemargins = 0;
4922  if (isModEnabled('margin') && !empty($this->element) && in_array($this->element, array('facture', 'facturerec', 'propal', 'commande'))) {
4923  $usemargins = 1;
4924  }
4925 
4926  $num = count($this->lines);
4927 
4928  // Line extrafield
4929  if (!is_object($extrafields)) {
4930  require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
4931  $extrafields = new ExtraFields($this->db);
4932  }
4933  $extrafields->fetch_name_optionals_label($this->table_element_line);
4934 
4935  $parameters = array('num'=>$num, 'dateSelector'=>$dateSelector, 'seller'=>$seller, 'buyer'=>$buyer, 'selected'=>$selected, 'table_element_line'=>$this->table_element_line);
4936  $reshook = $hookmanager->executeHooks('printObjectLineTitle', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
4937  if (empty($reshook)) {
4938  // Output template part (modules that overwrite templates must declare this into descriptor)
4939  // Use global variables + $dateSelector + $seller and $buyer
4940  // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook.
4941  $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
4942  foreach ($dirtpls as $module => $reldir) {
4943  $res = 0;
4944  if (!empty($module)) {
4945  $tpl = dol_buildpath($reldir.'/objectline_title.tpl.php');
4946  } else {
4947  $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_title.tpl.php';
4948  }
4949  if (file_exists($tpl)) {
4950  if (empty($conf->file->strict_mode)) {
4951  $res = @include $tpl;
4952  } else {
4953  $res = include $tpl; // for debug
4954  }
4955  }
4956  if ($res) {
4957  break;
4958  }
4959  }
4960  }
4961 
4962  $i = 0;
4963 
4964  print "<!-- begin printObjectLines() --><tbody>\n";
4965  foreach ($this->lines as $line) {
4966  //Line extrafield
4967  $line->fetch_optionals();
4968 
4969  //if (is_object($hookmanager) && (($line->product_type == 9 && !empty($line->special_code)) || !empty($line->fk_parent_line)))
4970  if (is_object($hookmanager)) { // Old code is commented on preceding line.
4971  if (empty($line->fk_parent_line)) {
4972  $parameters = array('line'=>$line, 'num'=>$num, 'i'=>$i, 'dateSelector'=>$dateSelector, 'seller'=>$seller, 'buyer'=>$buyer, 'selected'=>$selected, 'table_element_line'=>$line->table_element);
4973  $reshook = $hookmanager->executeHooks('printObjectLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
4974  } else {
4975  $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);
4976  $reshook = $hookmanager->executeHooks('printObjectSubLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
4977  }
4978  }
4979  if (empty($reshook)) {
4980  $this->printObjectLine($action, $line, '', $num, $i, $dateSelector, $seller, $buyer, $selected, $extrafields, $defaulttpldir);
4981  }
4982 
4983  $i++;
4984  }
4985  print "</tbody><!-- end printObjectLines() -->\n";
4986  }
4987 
5005  public function printObjectLine($action, $line, $var, $num, $i, $dateSelector, $seller, $buyer, $selected = 0, $extrafields = null, $defaulttpldir = '/core/tpl')
5006  {
5007  global $conf, $langs, $user, $object, $hookmanager;
5008  global $form;
5009  global $object_rights, $disableedit, $disablemove, $disableremove; // TODO We should not use global var for this !
5010 
5011  $object_rights = $this->getRights();
5012 
5013  $element = $this->element;
5014 
5015  $text = '';
5016  $description = '';
5017 
5018  // Line in view mode
5019  if ($action != 'editline' || $selected != $line->id) {
5020  // Product
5021  if (!empty($line->fk_product) && $line->fk_product > 0) {
5022  $product_static = new Product($this->db);
5023  $product_static->fetch($line->fk_product);
5024 
5025  $product_static->ref = $line->ref; //can change ref in hook
5026  $product_static->label = !empty($line->label) ? $line->label : ""; //can change label in hook
5027 
5028  $text = $product_static->getNomUrl(1);
5029 
5030  // Define output language and label
5031  if (getDolGlobalInt('MAIN_MULTILANGS')) {
5032  if (property_exists($this, 'socid') && !is_object($this->thirdparty)) {
5033  dol_print_error('', 'Error: Method printObjectLine was called on an object and object->fetch_thirdparty was not done before');
5034  return;
5035  }
5036 
5037  $prod = new Product($this->db);
5038  $prod->fetch($line->fk_product);
5039 
5040  $outputlangs = $langs;
5041  $newlang = '';
5042  if (empty($newlang) && GETPOST('lang_id', 'aZ09')) {
5043  $newlang = GETPOST('lang_id', 'aZ09');
5044  }
5045  if (!empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE) && empty($newlang) && is_object($this->thirdparty)) {
5046  $newlang = $this->thirdparty->default_lang; // To use language of customer
5047  }
5048  if (!empty($newlang)) {
5049  $outputlangs = new Translate("", $conf);
5050  $outputlangs->setDefaultLang($newlang);
5051  }
5052 
5053  $label = (!empty($prod->multilangs[$outputlangs->defaultlang]["label"])) ? $prod->multilangs[$outputlangs->defaultlang]["label"] : $line->product_label;
5054  } else {
5055  $label = $line->product_label;
5056  }
5057 
5058  $text .= ' - '.(!empty($line->label) ? $line->label : $label);
5059  $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.
5060  }
5061 
5062  $line->pu_ttc = price2num((!empty($line->subprice) ? $line->subprice : 0) * (1 + ((!empty($line->tva_tx) ? $line->tva_tx : 0) / 100)), 'MU');
5063 
5064  // Output template part (modules that overwrite templates must declare this into descriptor)
5065  // Use global variables + $dateSelector + $seller and $buyer
5066  // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook printObjectLine and printObjectSubLine.
5067  $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
5068  foreach ($dirtpls as $module => $reldir) {
5069  $res = 0;
5070  if (!empty($module)) {
5071  $tpl = dol_buildpath($reldir.'/objectline_view.tpl.php');
5072  } else {
5073  $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_view.tpl.php';
5074  }
5075  if (file_exists($tpl)) {
5076  if (empty($conf->file->strict_mode)) {
5077  $res = @include $tpl;
5078  } else {
5079  $res = include $tpl; // for debug
5080  }
5081  }
5082  if ($res) {
5083  break;
5084  }
5085  }
5086  }
5087 
5088  // Line in update mode
5089  if ($this->statut == 0 && $action == 'editline' && $selected == $line->id) {
5090  $label = (!empty($line->label) ? $line->label : (($line->fk_product > 0) ? $line->product_label : ''));
5091 
5092  $line->pu_ttc = price2num($line->subprice * (1 + ($line->tva_tx / 100)), 'MU');
5093 
5094  // Output template part (modules that overwrite templates must declare this into descriptor)
5095  // Use global variables + $dateSelector + $seller and $buyer
5096  // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook printObjectLine and printObjectSubLine.
5097  $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
5098  foreach ($dirtpls as $module => $reldir) {
5099  if (!empty($module)) {
5100  $tpl = dol_buildpath($reldir.'/objectline_edit.tpl.php');
5101  } else {
5102  $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_edit.tpl.php';
5103  }
5104 
5105  if (empty($conf->file->strict_mode)) {
5106  $res = @include $tpl;
5107  } else {
5108  $res = include $tpl; // for debug
5109  }
5110  if ($res) {
5111  break;
5112  }
5113  }
5114  }
5115  }
5116 
5117 
5118  /* This is to show array of line of details of source object */
5119 
5120 
5131  public function printOriginLinesList($restrictlist = '', $selectedLines = array())
5132  {
5133  global $langs, $hookmanager, $conf, $form, $action;
5134 
5135  print '<tr class="liste_titre">';
5136  print '<td class="linecolref">'.$langs->trans('Ref').'</td>';
5137  print '<td class="linecoldescription">'.$langs->trans('Description').'</td>';
5138  print '<td class="linecolvat right">'.$langs->trans('VATRate').'</td>';
5139  print '<td class="linecoluht right">'.$langs->trans('PriceUHT').'</td>';
5140  if (isModEnabled("multicurrency")) {
5141  print '<td class="linecoluht_currency right">'.$langs->trans('PriceUHTCurrency').'</td>';
5142  }
5143  print '<td class="linecolqty right">'.$langs->trans('Qty').'</td>';
5144  if (!empty($conf->global->PRODUCT_USE_UNITS)) {
5145  print '<td class="linecoluseunit left">'.$langs->trans('Unit').'</td>';
5146  }
5147  print '<td class="linecoldiscount right">'.$langs->trans('ReductionShort').'</td>';
5148  print '<td class="linecolht right">'.$langs->trans('TotalHT').'</td>';
5149  print '<td class="center">'.$form->showCheckAddButtons('checkforselect', 1).'</td>';
5150  print '</tr>';
5151  $i = 0;
5152 
5153  if (!empty($this->lines)) {
5154  foreach ($this->lines as $line) {
5155  $reshook = 0;
5156  //if (is_object($hookmanager) && (($line->product_type == 9 && !empty($line->special_code)) || !empty($line->fk_parent_line))) {
5157  if (is_object($hookmanager)) { // Old code is commented on preceding line.
5158  $parameters = array('line'=>$line, 'i'=>$i, 'restrictlist'=>$restrictlist, 'selectedLines'=> $selectedLines);
5159  if (!empty($line->fk_parent_line)) { $parameters['fk_parent_line'] = $line->fk_parent_line; }
5160  $reshook = $hookmanager->executeHooks('printOriginObjectLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
5161  }
5162  if (empty($reshook)) {
5163  $this->printOriginLine($line, '', $restrictlist, '/core/tpl', $selectedLines);
5164  }
5165 
5166  $i++;
5167  }
5168  }
5169  }
5170 
5184  public function printOriginLine($line, $var, $restrictlist = '', $defaulttpldir = '/core/tpl', $selectedLines = array())
5185  {
5186  global $langs, $conf;
5187 
5188  //var_dump($line);
5189  if (!empty($line->date_start)) {
5190  $date_start = $line->date_start;
5191  } else {
5192  $date_start = $line->date_debut_prevue;
5193  if ($line->date_debut_reel) {
5194  $date_start = $line->date_debut_reel;
5195  }
5196  }
5197  if (!empty($line->date_end)) {
5198  $date_end = $line->date_end;
5199  } else {
5200  $date_end = $line->date_fin_prevue;
5201  if ($line->date_fin_reel) {
5202  $date_end = $line->date_fin_reel;
5203  }
5204  }
5205 
5206  $this->tpl['id'] = $line->id;
5207 
5208  $this->tpl['label'] = '';
5209  if (!empty($line->fk_parent_line)) {
5210  $this->tpl['label'] .= img_picto('', 'rightarrow');
5211  }
5212 
5213  if (($line->info_bits & 2) == 2) { // TODO Not sure this is used for source object
5214  $discount = new DiscountAbsolute($this->db);
5215  $discount->fk_soc = $this->socid;
5216  $this->tpl['label'] .= $discount->getNomUrl(0, 'discount');
5217  } elseif (!empty($line->fk_product)) {
5218  $productstatic = new Product($this->db);
5219  $productstatic->id = $line->fk_product;
5220  $productstatic->ref = $line->ref;
5221  $productstatic->type = $line->fk_product_type;
5222  if (empty($productstatic->ref)) {
5223  $line->fetch_product();
5224  $productstatic = $line->product;
5225  }
5226 
5227  $this->tpl['label'] .= $productstatic->getNomUrl(1);
5228  $this->tpl['label'] .= ' - '.(!empty($line->label) ? $line->label : $line->product_label);
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  } else {
5234  $this->tpl['label'] .= ($line->product_type == -1 ? '&nbsp;' : ($line->product_type == 1 ? img_object($langs->trans(''), 'service') : img_object($langs->trans(''), 'product')));
5235  if (!empty($line->desc)) {
5236  $this->tpl['label'] .= $line->desc;
5237  } else {
5238  $this->tpl['label'] .= ($line->label ? '&nbsp;'.$line->label : '');
5239  }
5240 
5241  // Dates
5242  if ($line->product_type == 1 && ($date_start || $date_end)) {
5243  $this->tpl['label'] .= get_date_range($date_start, $date_end);
5244  }
5245  }
5246 
5247  if (!empty($line->desc)) {
5248  if ($line->desc == '(CREDIT_NOTE)') { // TODO Not sure this is used for source object
5249  $discount = new DiscountAbsolute($this->db);
5250  $discount->fetch($line->fk_remise_except);
5251  $this->tpl['description'] = $langs->transnoentities("DiscountFromCreditNote", $discount->getNomUrl(0));
5252  } elseif ($line->desc == '(DEPOSIT)') { // TODO Not sure this is used for source object
5253  $discount = new DiscountAbsolute($this->db);
5254  $discount->fetch($line->fk_remise_except);
5255  $this->tpl['description'] = $langs->transnoentities("DiscountFromDeposit", $discount->getNomUrl(0));
5256  } elseif ($line->desc == '(EXCESS RECEIVED)') {
5257  $discount = new DiscountAbsolute($this->db);
5258  $discount->fetch($line->fk_remise_except);
5259  $this->tpl['description'] = $langs->transnoentities("DiscountFromExcessReceived", $discount->getNomUrl(0));
5260  } elseif ($line->desc == '(EXCESS PAID)') {
5261  $discount = new DiscountAbsolute($this->db);
5262  $discount->fetch($line->fk_remise_except);
5263  $this->tpl['description'] = $langs->transnoentities("DiscountFromExcessPaid", $discount->getNomUrl(0));
5264  } else {
5265  $this->tpl['description'] = dol_trunc($line->desc, 60);
5266  }
5267  } else {
5268  $this->tpl['description'] = '&nbsp;';
5269  }
5270 
5271  // VAT Rate
5272  $this->tpl['vat_rate'] = vatrate($line->tva_tx, true);
5273  $this->tpl['vat_rate'] .= (($line->info_bits & 1) == 1) ? '*' : '';
5274  if (!empty($line->vat_src_code) && !preg_match('/\(/', $this->tpl['vat_rate'])) {
5275  $this->tpl['vat_rate'] .= ' ('.$line->vat_src_code.')';
5276  }
5277 
5278  $this->tpl['price'] = price($line->subprice);
5279  $this->tpl['total_ht'] = price($line->total_ht);
5280  $this->tpl['multicurrency_price'] = price($line->multicurrency_subprice);
5281  $this->tpl['qty'] = (($line->info_bits & 2) != 2) ? $line->qty : '&nbsp;';
5282  if (!empty($conf->global->PRODUCT_USE_UNITS)) {
5283  $this->tpl['unit'] = $langs->transnoentities($line->getLabelOfUnit('long'));
5284  }
5285  $this->tpl['remise_percent'] = (($line->info_bits & 2) != 2) ? vatrate($line->remise_percent, true) : '&nbsp;';
5286 
5287  // Is the line strike or not
5288  $this->tpl['strike'] = 0;
5289  if ($restrictlist == 'services' && $line->product_type != Product::TYPE_SERVICE) {
5290  $this->tpl['strike'] = 1;
5291  }
5292 
5293  // Output template part (modules that overwrite templates must declare this into descriptor)
5294  // Use global variables + $dateSelector + $seller and $buyer
5295  $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
5296  foreach ($dirtpls as $module => $reldir) {
5297  if (!empty($module)) {
5298  $tpl = dol_buildpath($reldir.'/originproductline.tpl.php');
5299  } else {
5300  $tpl = DOL_DOCUMENT_ROOT.$reldir.'/originproductline.tpl.php';
5301  }
5302 
5303  if (empty($conf->file->strict_mode)) {
5304  $res = @include $tpl;
5305  } else {
5306  $res = include $tpl; // for debug
5307  }
5308  if ($res) {
5309  break;
5310  }
5311  }
5312  }
5313 
5314 
5315  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5326  public function add_element_resource($resource_id, $resource_type, $busy = 0, $mandatory = 0)
5327  {
5328  // phpcs:enable
5329  $this->db->begin();
5330 
5331  $sql = "INSERT INTO ".$this->db->prefix()."element_resources (";
5332  $sql .= "resource_id";
5333  $sql .= ", resource_type";
5334  $sql .= ", element_id";
5335  $sql .= ", element_type";
5336  $sql .= ", busy";
5337  $sql .= ", mandatory";
5338  $sql .= ") VALUES (";
5339  $sql .= $resource_id;
5340  $sql .= ", '".$this->db->escape($resource_type)."'";
5341  $sql .= ", '".$this->db->escape($this->id)."'";
5342  $sql .= ", '".$this->db->escape($this->element)."'";
5343  $sql .= ", '".$this->db->escape($busy)."'";
5344  $sql .= ", '".$this->db->escape($mandatory)."'";
5345  $sql .= ")";
5346 
5347  dol_syslog(get_class($this)."::add_element_resource", LOG_DEBUG);
5348  if ($this->db->query($sql)) {
5349  $this->db->commit();
5350  return 1;
5351  } else {
5352  $this->error = $this->db->lasterror();
5353  $this->db->rollback();
5354  return 0;
5355  }
5356  }
5357 
5358  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5367  public function delete_resource($rowid, $element, $notrigger = 0)
5368  {
5369  // phpcs:enable
5370  global $user;
5371 
5372  $this->db->begin();
5373 
5374  $sql = "DELETE FROM ".$this->db->prefix()."element_resources";
5375  $sql .= " WHERE rowid = ".((int) $rowid);
5376 
5377  dol_syslog(get_class($this)."::delete_resource", LOG_DEBUG);
5378 
5379  $resql = $this->db->query($sql);
5380  if (!$resql) {
5381  $this->error = $this->db->lasterror();
5382  $this->db->rollback();
5383  return -1;
5384  } else {
5385  if (!$notrigger) {
5386  $result = $this->call_trigger(strtoupper($element).'_DELETE_RESOURCE', $user);
5387  if ($result < 0) {
5388  $this->db->rollback();
5389  return -1;
5390  }
5391  }
5392  $this->db->commit();
5393  return 1;
5394  }
5395  }
5396 
5397 
5403  public function __clone()
5404  {
5405  // Force a copy of this->lines, otherwise it will point to same object.
5406  if (isset($this->lines) && is_array($this->lines)) {
5407  $nboflines = count($this->lines);
5408  for ($i = 0; $i < $nboflines; $i++) {
5409  $this->lines[$i] = clone $this->lines[$i];
5410  }
5411  }
5412  }
5413 
5427  protected function commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams = null)
5428  {
5429  global $conf, $langs, $user, $hookmanager, $action;
5430 
5431  $srctemplatepath = '';
5432 
5433  $parameters = array('modelspath'=>$modelspath, 'modele'=>$modele, 'outputlangs'=>$outputlangs, 'hidedetails'=>$hidedetails, 'hidedesc'=>$hidedesc, 'hideref'=>$hideref, 'moreparams'=>$moreparams);
5434  $reshook = $hookmanager->executeHooks('commonGenerateDocument', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
5435 
5436  if (empty($reshook)) {
5437  dol_syslog("commonGenerateDocument modele=".$modele." outputlangs->defaultlang=".(is_object($outputlangs) ? $outputlangs->defaultlang : 'null'));
5438 
5439  if (empty($modele)) {
5440  $this->error = 'BadValueForParameterModele';
5441  return -1;
5442  }
5443 
5444  // Increase limit for PDF build
5445  $err = error_reporting();
5446  error_reporting(0);
5447  @set_time_limit(120);
5448  error_reporting($err);
5449 
5450  // If selected model is a filename template (then $modele="modelname" or "modelname:filename")
5451  $tmp = explode(':', $modele, 2);
5452  if (!empty($tmp[1])) {
5453  $modele = $tmp[0];
5454  $srctemplatepath = $tmp[1];
5455  }
5456 
5457  // Search template files
5458  $file = '';
5459  $classname = '';
5460  $filefound = '';
5461  $dirmodels = array('/');
5462  if (is_array($conf->modules_parts['models'])) {
5463  $dirmodels = array_merge($dirmodels, $conf->modules_parts['models']);
5464  }
5465  foreach ($dirmodels as $reldir) {
5466  foreach (array('doc', 'pdf') as $prefix) {
5467  if (in_array(get_class($this), array('Adherent'))) {
5468  // Member module use prefix_modele.class.php
5469  $file = $prefix."_".$modele.".class.php";
5470  } else {
5471  // Other module use prefix_modele.modules.php
5472  $file = $prefix."_".$modele.".modules.php";
5473  }
5474 
5475  // On verifie l'emplacement du modele
5476  $file = dol_buildpath($reldir.$modelspath.$file, 0);
5477  if (file_exists($file)) {
5478  $filefound = $file;
5479  $classname = $prefix.'_'.$modele;
5480  break;
5481  }
5482  }
5483  if ($filefound) {
5484  break;
5485  }
5486  }
5487 
5488  // If generator was found
5489  if ($filefound) {
5490  global $db; // Required to solve a conception default making an include of code using $db instead of $this->db just after.
5491 
5492  require_once $file;
5493 
5494  $obj = new $classname($this->db);
5495 
5496  // If generator is ODT, we must have srctemplatepath defined, if not we set it.
5497  if ($obj->type == 'odt' && empty($srctemplatepath)) {
5498  $varfortemplatedir = $obj->scandir;
5499  if ($varfortemplatedir && !empty($conf->global->$varfortemplatedir)) {
5500  $dirtoscan = $conf->global->$varfortemplatedir;
5501 
5502  $listoffiles = array();
5503 
5504  // Now we add first model found in directories scanned
5505  $listofdir = explode(',', $dirtoscan);
5506  foreach ($listofdir as $key => $tmpdir) {
5507  $tmpdir = trim($tmpdir);
5508  $tmpdir = preg_replace('/DOL_DATA_ROOT/', DOL_DATA_ROOT, $tmpdir);
5509  if (!$tmpdir) {
5510  unset($listofdir[$key]);
5511  continue;
5512  }
5513  if (is_dir($tmpdir)) {
5514  $tmpfiles = dol_dir_list($tmpdir, 'files', 0, '\.od(s|t)$', '', 'name', SORT_ASC, 0);
5515  if (count($tmpfiles)) {
5516  $listoffiles = array_merge($listoffiles, $tmpfiles);
5517  }
5518  }
5519  }
5520 
5521  if (count($listoffiles)) {
5522  foreach ($listoffiles as $record) {
5523  $srctemplatepath = $record['fullname'];
5524  break;
5525  }
5526  }
5527  }
5528 
5529  if (empty($srctemplatepath)) {
5530  $this->error = 'ErrorGenerationAskedForOdtTemplateWithSrcFileNotDefined';
5531  return -1;
5532  }
5533  }
5534 
5535  if ($obj->type == 'odt' && !empty($srctemplatepath)) {
5536  if (!dol_is_file($srctemplatepath)) {
5537  dol_syslog("Failed to locate template file ".$srctemplatepath, LOG_WARNING);
5538  $this->error = 'ErrorGenerationAskedForOdtTemplateWithSrcFileNotFound';
5539  return -1;
5540  }
5541  }
5542 
5543  // We save charset_output to restore it because write_file can change it if needed for
5544  // output format that does not support UTF8.
5545  $sav_charset_output = empty($outputlangs->charset_output) ? '' : $outputlangs->charset_output;
5546 
5547  if (in_array(get_class($this), array('Adherent'))) {
5548  $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, 'member', 1, 'tmp_cards', $moreparams);
5549  } else {
5550  $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, $hidedetails, $hidedesc, $hideref, $moreparams);
5551  }
5552  // After call of write_file $obj->result['fullpath'] is set with generated file. It will be used to update the ECM database index.
5553 
5554  if ($resultwritefile > 0) {
5555  $outputlangs->charset_output = $sav_charset_output;
5556 
5557  // We delete old preview
5558  require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
5559  dol_delete_preview($this);
5560 
5561  // Index file in database
5562  if (!empty($obj->result['fullpath'])) {
5563  $destfull = $obj->result['fullpath'];
5564 
5565  // Update the last_main_doc field into main object (if document generator has property ->update_main_doc_field set)
5566  $update_main_doc_field = 0;
5567  if (!empty($obj->update_main_doc_field)) {
5568  $update_main_doc_field = 1;
5569  }
5570 
5571  $this->indexFile($destfull, $update_main_doc_field);
5572  } else {
5573  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);
5574  }
5575 
5576  // Success in building document. We build meta file.
5577  dol_meta_create($this);
5578 
5579  return 1;
5580  } else {
5581  $outputlangs->charset_output = $sav_charset_output;
5582  $this->error = $obj->error;
5583  $this->errors = $obj->errors;
5584  dol_syslog("Error generating document for ".__CLASS__.". Error: ".$obj->error, LOG_ERR);
5585  return -1;
5586  }
5587  } else {
5588  if (!$filefound) {
5589  $this->error = $langs->trans("Error").' Failed to load doc generator with modelpaths='.$modelspath.' - modele='.$modele;
5590  $this->errors[] = $this->error;
5591  dol_syslog($this->error, LOG_ERR);
5592  } else {
5593  $this->error = $langs->trans("Error")." ".$langs->trans("ErrorFileDoesNotExists", $filefound);
5594  $this->errors[] = $this->error;
5595  dol_syslog($this->error, LOG_ERR);
5596  }
5597  return -1;
5598  }
5599  } else {
5600  return $reshook;
5601  }
5602  }
5603 
5613  public function indexFile($destfull, $update_main_doc_field)
5614  {
5615  global $conf, $user;
5616 
5617  $upload_dir = dirname($destfull);
5618  $destfile = basename($destfull);
5619  $rel_dir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $upload_dir);
5620 
5621  if (!preg_match('/[\\/]temp[\\/]|[\\/]thumbs|\.meta$/', $rel_dir)) { // If not a tmp dir
5622  $filename = basename($destfile);
5623  $rel_dir = preg_replace('/[\\/]$/', '', $rel_dir);
5624  $rel_dir = preg_replace('/^[\\/]/', '', $rel_dir);
5625 
5626  include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
5627  $ecmfile = new EcmFiles($this->db);
5628  $result = $ecmfile->fetch(0, '', ($rel_dir ? $rel_dir.'/' : '').$filename);
5629 
5630  // Set the public "share" key
5631  $setsharekey = false;
5632  if ($this->element == 'propal' || $this->element == 'proposal') {
5633  if (!isset($conf->global->PROPOSAL_ALLOW_ONLINESIGN) || !empty($conf->global->PROPOSAL_ALLOW_ONLINESIGN)) {
5634  $setsharekey = true; // feature to make online signature is not set or set to on (default)
5635  }
5636  if (!empty($conf->global->PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD)) {
5637  $setsharekey = true;
5638  }
5639  }
5640  if ($this->element == 'commande' && !empty($conf->global->ORDER_ALLOW_EXTERNAL_DOWNLOAD)) {
5641  $setsharekey = true;
5642  }
5643  if ($this->element == 'facture' && !empty($conf->global->INVOICE_ALLOW_EXTERNAL_DOWNLOAD)) {
5644  $setsharekey = true;
5645  }
5646  if ($this->element == 'bank_account' && !empty($conf->global->BANK_ACCOUNT_ALLOW_EXTERNAL_DOWNLOAD)) {
5647  $setsharekey = true;
5648  }
5649  if ($this->element == 'product' && !empty($conf->global->PRODUCT_ALLOW_EXTERNAL_DOWNLOAD)) {
5650  $setsharekey = true;
5651  }
5652  if ($this->element == 'contrat' && !empty($conf->global->CONTRACT_ALLOW_EXTERNAL_DOWNLOAD)) {
5653  $setsharekey = true;
5654  }
5655  if ($this->element == 'fichinter' && !empty($conf->global->FICHINTER_ALLOW_EXTERNAL_DOWNLOAD)) {
5656  $setsharekey = true;
5657  }
5658  if ($this->element == 'supplier_proposal' && !empty($conf->global->SUPPLIER_PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD)) {
5659  $setsharekey = true;
5660  }
5661 
5662  if ($setsharekey) {
5663  if (empty($ecmfile->share)) { // Because object not found or share not set yet
5664  require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
5665  $ecmfile->share = getRandomPassword(true);
5666  }
5667  }
5668 
5669  if ($result > 0) {
5670  $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
5671  $ecmfile->fullpath_orig = '';
5672  $ecmfile->gen_or_uploaded = 'generated';
5673  $ecmfile->description = ''; // indexed content
5674  $ecmfile->keywords = ''; // keyword content
5675  $result = $ecmfile->update($user);
5676  if ($result < 0) {
5677  setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
5678  return -1;
5679  }
5680  } else {
5681  $ecmfile->entity = $conf->entity;
5682  $ecmfile->filepath = $rel_dir;
5683  $ecmfile->filename = $filename;
5684  $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
5685  $ecmfile->fullpath_orig = '';
5686  $ecmfile->gen_or_uploaded = 'generated';
5687  $ecmfile->description = ''; // indexed content
5688  $ecmfile->keywords = ''; // keyword content
5689  $ecmfile->src_object_type = $this->table_element; // $this->table_name is 'myobject' or 'mymodule_myobject'.
5690  $ecmfile->src_object_id = $this->id;
5691 
5692  $result = $ecmfile->create($user);
5693  if ($result < 0) {
5694  setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
5695  return -1;
5696  }
5697  }
5698 
5699  /*$this->result['fullname']=$destfull;
5700  $this->result['filepath']=$ecmfile->filepath;
5701  $this->result['filename']=$ecmfile->filename;*/
5702  //var_dump($obj->update_main_doc_field);exit;
5703 
5704  if ($update_main_doc_field && !empty($this->table_element)) {
5705  $sql = "UPDATE ".$this->db->prefix().$this->table_element." SET last_main_doc = '".$this->db->escape($ecmfile->filepath."/".$ecmfile->filename)."'";
5706  $sql .= " WHERE rowid = ".((int) $this->id);
5707 
5708  $resql = $this->db->query($sql);
5709  if (!$resql) {
5710  dol_print_error($this->db);
5711  return -1;
5712  } else {
5713  $this->last_main_doc = $ecmfile->filepath.'/'.$ecmfile->filename;
5714  }
5715  }
5716  }
5717 
5718  return 1;
5719  }
5720 
5728  public function addThumbs($file)
5729  {
5730  require_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
5731 
5732  $tmparraysize = getDefaultImageSizes();
5733  $maxwidthsmall = $tmparraysize['maxwidthsmall'];
5734  $maxheightsmall = $tmparraysize['maxheightsmall'];
5735  $maxwidthmini = $tmparraysize['maxwidthmini'];
5736  $maxheightmini = $tmparraysize['maxheightmini'];
5737  //$quality = $tmparraysize['quality'];
5738  $quality = 50; // For thumbs, we force quality to 50
5739 
5740  $file_osencoded = dol_osencode($file);
5741  if (file_exists($file_osencoded)) {
5742  // Create small thumbs for company (Ratio is near 16/9)
5743  // Used on logon for example
5744  vignette($file_osencoded, $maxwidthsmall, $maxheightsmall, '_small', $quality);
5745 
5746  // Create mini thumbs for company (Ratio is near 16/9)
5747  // Used on menu or for setup page for example
5748  vignette($file_osencoded, $maxwidthmini, $maxheightmini, '_mini', $quality);
5749  }
5750  }
5751 
5752 
5753  /* Functions common to commonobject and commonobjectline */
5754 
5755  /* For default values */
5756 
5769  public function getDefaultCreateValueFor($fieldname, $alternatevalue = null)
5770  {
5771  global $conf, $_POST;
5772 
5773  // If param here has been posted, we use this value first.
5774  if (GETPOSTISSET($fieldname)) {
5775  return GETPOST($fieldname, 'alphanohtml', 3);
5776  }
5777 
5778  if (isset($alternatevalue)) {
5779  return $alternatevalue;
5780  }
5781 
5782  $newelement = $this->element;
5783  if ($newelement == 'facture') {
5784  $newelement = 'invoice';
5785  }
5786  if ($newelement == 'commande') {
5787  $newelement = 'order';
5788  }
5789  if (empty($newelement)) {
5790  dol_syslog("Ask a default value using common method getDefaultCreateValueForField on an object with no property ->element defined. Return empty string.", LOG_WARNING);
5791  return '';
5792  }
5793 
5794  $keyforfieldname = strtoupper($newelement.'_DEFAULT_'.$fieldname);
5795  //var_dump($keyforfieldname);
5796  if (isset($conf->global->$keyforfieldname)) {
5797  return $conf->global->$keyforfieldname;
5798  }
5799 
5800  // TODO Ad here a scan into table llx_overwrite_default with a filter on $this->element and $fieldname
5801  }
5802 
5803 
5804  /* For triggers */
5805 
5806 
5807  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5818  public function call_trigger($triggerName, $user)
5819  {
5820  // phpcs:enable
5821  global $langs, $conf;
5822  if (!empty(self::TRIGGER_PREFIX) && strpos($triggerName, self::TRIGGER_PREFIX . '_') !== 0) {
5823  dol_print_error('', 'The trigger "' . $triggerName . '" does not start with "' . self::TRIGGER_PREFIX . '_" as required.');
5824  exit;
5825  }
5826  if (!is_object($langs)) { // If lang was not defined, we set it. It is required by run_triggers.
5827  include_once DOL_DOCUMENT_ROOT.'/core/class/translate.class.php';
5828  $langs = new Translate('', $conf);
5829  }
5830 
5831  include_once DOL_DOCUMENT_ROOT.'/core/class/interfaces.class.php';
5832  $interface = new Interfaces($this->db);
5833  $result = $interface->run_triggers($triggerName, $this, $user, $langs, $conf);
5834 
5835  if ($result < 0) {
5836  if (!empty($this->errors)) {
5837  $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.
5838  } else {
5839  $this->errors = $interface->errors;
5840  }
5841  }
5842  return $result;
5843  }
5844 
5845 
5846  /* Functions for data in other language */
5847 
5848 
5856  public function fetchValuesForExtraLanguages()
5857  {
5858  // To avoid SQL errors. Probably not the better solution though
5859  if (!$this->element) {
5860  return 0;
5861  }
5862  if (!($this->id > 0)) {
5863  return 0;
5864  }
5865  if (is_array($this->array_languages)) {
5866  return 1;
5867  }
5868 
5869  $this->array_languages = array();
5870 
5871  $element = $this->element;
5872  if ($element == 'categorie') {
5873  $element = 'categories'; // For compatibility
5874  }
5875 
5876  // Request to get translation values for object
5877  $sql = "SELECT rowid, property, lang , value";
5878  $sql .= " FROM ".$this->db->prefix()."object_lang";
5879  $sql .= " WHERE type_object = '".$this->db->escape($element)."'";
5880  $sql .= " AND fk_object = ".((int) $this->id);
5881 
5882  //dol_syslog(get_class($this)."::fetch_optionals get extrafields data for ".$this->table_element, LOG_DEBUG); // Too verbose
5883  $resql = $this->db->query($sql);
5884  if ($resql) {
5885  $numrows = $this->db->num_rows($resql);
5886  if ($numrows) {
5887  $i = 0;
5888  while ($i < $numrows) {
5889  $obj = $this->db->fetch_object($resql);
5890  $key = $obj->property;
5891  $value = $obj->value;
5892  $codelang = $obj->lang;
5893  $type = $this->fields[$key]['type'];
5894 
5895  // we can add this attribute to object
5896  if (preg_match('/date/', $type)) {
5897  $this->array_languages[$key][$codelang] = $this->db->jdate($value);
5898  } else {
5899  $this->array_languages[$key][$codelang] = $value;
5900  }
5901 
5902  $i++;
5903  }
5904  }
5905 
5906  $this->db->free($resql);
5907 
5908  if ($numrows) {
5909  return $numrows;
5910  } else {
5911  return 0;
5912  }
5913  } else {
5914  dol_print_error($this->db);
5915  return -1;
5916  }
5917  }
5918 
5925  public function setValuesForExtraLanguages($onlykey = '')
5926  {
5927  global $_POST, $langs;
5928 
5929  // Get extra fields
5930  foreach ($_POST as $postfieldkey => $postfieldvalue) {
5931  $tmparray = explode('-', $postfieldkey);
5932  if ($tmparray[0] != 'field') {
5933  continue;
5934  }
5935 
5936  $element = $tmparray[1];
5937  $key = $tmparray[2];
5938  $codelang = $tmparray[3];
5939  //var_dump("postfieldkey=".$postfieldkey." element=".$element." key=".$key." codelang=".$codelang);
5940 
5941  if (!empty($onlykey) && $key != $onlykey) {
5942  continue;
5943  }
5944  if ($element != $this->element) {
5945  continue;
5946  }
5947 
5948  $key_type = $this->fields[$key]['type'];
5949 
5950  $enabled = 1;
5951  if (isset($this->fields[$key]['enabled'])) {
5952  $enabled = dol_eval($this->fields[$key]['enabled'], 1, 1, '1');
5953  }
5954  /*$perms = 1;
5955  if (isset($this->fields[$key]['perms']))
5956  {
5957  $perms = dol_eval($this->fields[$key]['perms'], 1, 1, '1');
5958  }*/
5959  if (empty($enabled)) {
5960  continue;
5961  }
5962  //if (empty($perms)) continue;
5963 
5964  if (in_array($key_type, array('date'))) {
5965  // Clean parameters
5966  // TODO GMT date in memory must be GMT so we should add gm=true in parameters
5967  $value_key = dol_mktime(0, 0, 0, GETPOST($postfieldkey."month", 'int'), GETPOST($postfieldkey."day", 'int'), GETPOST($postfieldkey."year", 'int'));
5968  } elseif (in_array($key_type, array('datetime'))) {
5969  // Clean parameters
5970  // TODO GMT date in memory must be GMT so we should add gm=true in parameters
5971  $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'));
5972  } elseif (in_array($key_type, array('checkbox', 'chkbxlst'))) {
5973  $value_arr = GETPOST($postfieldkey, 'array'); // check if an array
5974  if (!empty($value_arr)) {
5975  $value_key = implode(',', $value_arr);
5976  } else {
5977  $value_key = '';
5978  }
5979  } elseif (in_array($key_type, array('price', 'double'))) {
5980  $value_arr = GETPOST($postfieldkey, 'alpha');
5981  $value_key = price2num($value_arr);
5982  } else {
5983  $value_key = GETPOST($postfieldkey);
5984  if (in_array($key_type, array('link')) && $value_key == '-1') {
5985  $value_key = '';
5986  }
5987  }
5988 
5989  $this->array_languages[$key][$codelang] = $value_key;
5990 
5991  /*if ($nofillrequired) {
5992  $langs->load('errors');
5993  setEventMessages($langs->trans('ErrorFieldsRequired').' : '.implode(', ', $error_field_required), null, 'errors');
5994  return -1;
5995  }*/
5996  }
5997 
5998  return 1;
5999  }
6000 
6001 
6002  /* Functions for extrafields */
6003 
6010  public function fetchNoCompute($id)
6011  {
6012  global $conf;
6013 
6014  $savDisableCompute = $conf->disable_compute;
6015  $conf->disable_compute = 1;
6016 
6017  $ret = $this->fetch($id);
6018 
6019  $conf->disable_compute = $savDisableCompute;
6020 
6021  return $ret;
6022  }
6023 
6024  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
6034  public function fetch_optionals($rowid = null, $optionsArray = null)
6035  {
6036  // phpcs:enable
6037  global $conf, $extrafields;
6038 
6039  if (empty($rowid)) {
6040  $rowid = $this->id;
6041  }
6042  if (empty($rowid) && isset($this->rowid)) {
6043  $rowid = $this->rowid; // deprecated
6044  }
6045 
6046  // To avoid SQL errors. Probably not the better solution though
6047  if (!$this->table_element) {
6048  return 0;
6049  }
6050 
6051  $this->array_options = array();
6052 
6053  if (!is_array($optionsArray)) {
6054  // If $extrafields is not a known object, we initialize it. Best practice is to have $extrafields defined into card.php or list.php page.
6055  if (!isset($extrafields) || !is_object($extrafields)) {
6056  require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
6057  $extrafields = new ExtraFields($this->db);
6058  }
6059 
6060  // Load array of extrafields for elementype = $this->table_element
6061  if (empty($extrafields->attributes[$this->table_element]['loaded'])) {
6062  $extrafields->fetch_name_optionals_label($this->table_element);
6063  }
6064  $optionsArray = (!empty($extrafields->attributes[$this->table_element]['label']) ? $extrafields->attributes[$this->table_element]['label'] : null);
6065  } else {
6066  global $extrafields;
6067  dol_syslog("Warning: fetch_optionals was called with param optionsArray defined when you should pass null now", LOG_WARNING);
6068  }
6069 
6070  $table_element = $this->table_element;
6071  if ($table_element == 'categorie') {
6072  $table_element = 'categories'; // For compatibility
6073  }
6074 
6075  // Request to get complementary values
6076  if (is_array($optionsArray) && count($optionsArray) > 0) {
6077  $sql = "SELECT rowid";
6078  foreach ($optionsArray as $name => $label) {
6079  if (empty($extrafields->attributes[$this->table_element]['type'][$name]) || $extrafields->attributes[$this->table_element]['type'][$name] != 'separate') {
6080  $sql .= ", ".$name;
6081  }
6082  }
6083  $sql .= " FROM ".$this->db->prefix().$table_element."_extrafields";
6084  $sql .= " WHERE fk_object = ".((int) $rowid);
6085 
6086  //dol_syslog(get_class($this)."::fetch_optionals get extrafields data for ".$this->table_element, LOG_DEBUG); // Too verbose
6087  $resql = $this->db->query($sql);
6088  if ($resql) {
6089  $numrows = $this->db->num_rows($resql);
6090  if ($numrows) {
6091  $tab = $this->db->fetch_array($resql);
6092 
6093  foreach ($tab as $key => $value) {
6094  // 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)
6095  if ($key != 'rowid' && $key != 'tms' && $key != 'fk_member' && !is_int($key)) {
6096  // we can add this attribute to object
6097  if (!empty($extrafields->attributes[$this->table_element]) && in_array($extrafields->attributes[$this->table_element]['type'][$key], array('date', 'datetime'))) {
6098  //var_dump($extrafields->attributes[$this->table_element]['type'][$key]);
6099  $this->array_options["options_".$key] = $this->db->jdate($value);
6100  } else {
6101  $this->array_options["options_".$key] = $value;
6102  }
6103 
6104  //var_dump('key '.$key.' '.$value.' type='.$extrafields->attributes[$this->table_element]['type'][$key].' '.$this->array_options["options_".$key]);
6105  }
6106  }
6107  }
6108 
6109  // If field is a computed field, value must become result of compute (regardless of whether a row exists
6110  // in the element's extrafields table)
6111  if (is_array($extrafields->attributes[$this->table_element]['label'])) {
6112  foreach ($extrafields->attributes[$this->table_element]['label'] as $key => $val) {
6113  if (!empty($extrafields->attributes[$this->table_element]) && !empty($extrafields->attributes[$this->table_element]['computed'][$key])) {
6114  //var_dump($conf->disable_compute);
6115  if (empty($conf->disable_compute)) {
6116  global $objectoffield; // We set a global variable to $objectoffield so
6117  $objectoffield = $this; // we can use it inside computed formula
6118  $this->array_options['options_' . $key] = dol_eval($extrafields->attributes[$this->table_element]['computed'][$key], 1, 0, '');
6119  }
6120  }
6121  }
6122  }
6123 
6124  $this->db->free($resql);
6125 
6126  if ($numrows) {
6127  return $numrows;
6128  } else {
6129  return 0;
6130  }
6131  } else {
6132  $this->errors[]=$this->db->lasterror;
6133  return -1;
6134  }
6135  }
6136  return 0;
6137  }
6138 
6145  public function deleteExtraFields()
6146  {
6147  global $conf;
6148 
6149  if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
6150  return 0;
6151  }
6152 
6153  $this->db->begin();
6154 
6155  $table_element = $this->table_element;
6156  if ($table_element == 'categorie') {
6157  $table_element = 'categories'; // For compatibility
6158  }
6159 
6160  dol_syslog(get_class($this)."::deleteExtraFields delete", LOG_DEBUG);
6161 
6162  $sql_del = "DELETE FROM ".$this->db->prefix().$table_element."_extrafields WHERE fk_object = ".((int) $this->id);
6163 
6164  $resql = $this->db->query($sql_del);
6165  if (!$resql) {
6166  $this->error = $this->db->lasterror();
6167  $this->db->rollback();
6168  return -1;
6169  } else {
6170  $this->db->commit();
6171  return 1;
6172  }
6173  }
6174 
6185  public function insertExtraFields($trigger = '', $userused = null)
6186  {
6187  global $conf, $langs, $user;
6188 
6189  if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
6190  return 0;
6191  }
6192 
6193  if (empty($userused)) {
6194  $userused = $user;
6195  }
6196 
6197  $error = 0;
6198 
6199  if (!empty($this->array_options)) {
6200  // Check parameters
6201  $langs->load('admin');
6202  require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
6203  $extrafields = new ExtraFields($this->db);
6204  $target_extrafields = $extrafields->fetch_name_optionals_label($this->table_element);
6205 
6206  // Eliminate copied source object extra fields that do not exist in target object
6207  $new_array_options = array();
6208  foreach ($this->array_options as $key => $value) {
6209  if (in_array(substr($key, 8), array_keys($target_extrafields))) { // We remove the 'options_' from $key for test
6210  $new_array_options[$key] = $value;
6211  } elseif (in_array($key, array_keys($target_extrafields))) { // We test on $key that does not contains the 'options_' prefix
6212  $new_array_options['options_'.$key] = $value;
6213  }
6214  }
6215 
6216  foreach ($new_array_options as $key => $value) {
6217  $attributeKey = substr($key, 8); // Remove 'options_' prefix
6218  $attributeType = $extrafields->attributes[$this->table_element]['type'][$attributeKey];
6219  $attributeLabel = $extrafields->attributes[$this->table_element]['label'][$attributeKey];
6220  $attributeParam = $extrafields->attributes[$this->table_element]['param'][$attributeKey];
6221  $attributeRequired = $extrafields->attributes[$this->table_element]['required'][$attributeKey];
6222  $attributeUnique = $extrafields->attributes[$this->table_element]['unique'][$attributeKey];
6223  $attrfieldcomputed = $extrafields->attributes[$this->table_element]['computed'][$attributeKey];
6224 
6225  // If we clone, we have to clean unique extrafields to prevent duplicates.
6226  // This behaviour can be prevented by external code by changing $this->context['createfromclone'] value in createFrom hook
6227  if (!empty($this->context['createfromclone']) && $this->context['createfromclone'] == 'createfromclone' && !empty($attributeUnique)) {
6228  $new_array_options[$key] = null;
6229  }
6230 
6231  // Similar code than into insertExtraFields
6232  if ($attributeRequired) {
6233  $mandatorypb = false;
6234  if ($attributeType == 'link' && $this->array_options[$key] == '-1') {
6235  $mandatorypb = true;
6236  }
6237  if ($this->array_options[$key] === '') {
6238  $mandatorypb = true;
6239  }
6240  if ($attributeType == 'sellist' && $this->array_options[$key] == '0') {
6241  $mandatorypb = true;
6242  }
6243  if ($mandatorypb) {
6244  $langs->load("errors");
6245  dol_syslog("Mandatory field '".$key."' is empty during create and set to required into definition of extrafields");
6246  $this->errors[] = $langs->trans('ErrorFieldRequired', $attributeLabel);
6247  return -1;
6248  }
6249  }
6250 
6251  //dol_syslog("attributeLabel=".$attributeLabel, LOG_DEBUG);
6252  //dol_syslog("attributeType=".$attributeType, LOG_DEBUG);
6253 
6254  if (!empty($attrfieldcomputed)) {
6255  if (!empty($conf->global->MAIN_STORE_COMPUTED_EXTRAFIELDS)) {
6256  $value = dol_eval($attrfieldcomputed, 1, 0, '');
6257  dol_syslog($langs->trans("Extrafieldcomputed")." sur ".$attributeLabel."(".$value.")", LOG_DEBUG);
6258  $new_array_options[$key] = $value;
6259  } else {
6260  $new_array_options[$key] = null;
6261  }
6262  }
6263 
6264  switch ($attributeType) {
6265  case 'int':
6266  if (!is_numeric($value) && $value != '') {
6267  $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
6268  return -1;
6269  } elseif ($value == '') {
6270  $new_array_options[$key] = null;
6271  }
6272  break;
6273  case 'price':
6274  case 'double':
6275  $value = price2num($value);
6276  if (!is_numeric($value) && $value != '') {
6277  dol_syslog($langs->trans("ExtraFieldHasWrongValue")." for ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
6278  $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
6279  return -1;
6280  } elseif ($value == '') {
6281  $value = null;
6282  }
6283  //dol_syslog("double value"." sur ".$attributeLabel."(".$value." is '".$attributeType."')", LOG_DEBUG);
6284  $new_array_options[$key] = $value;
6285  break;
6286  /*case 'select': // Not required, we chosed value='0' for undefined values
6287  if ($value=='-1')
6288  {
6289  $this->array_options[$key] = null;
6290  }
6291  break;*/
6292  case 'password':
6293  $algo = '';
6294  if ($this->array_options[$key] != '' && is_array($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options'])) {
6295  // If there is an encryption choice, we use it to crypt data before insert
6296  $tmparrays = array_keys($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options']);
6297  $algo = reset($tmparrays);
6298  if ($algo != '') {
6299  //global $action; // $action may be 'create', 'update', 'update_extras'...
6300  //var_dump($action);
6301  //var_dump($this->oldcopy);exit;
6302  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
6303  //var_dump($this->oldcopy->array_options[$key]); var_dump($this->array_options[$key]);
6304  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.
6305  $new_array_options[$key] = $this->array_options[$key]; // Value is kept
6306  } else {
6307  // var_dump($algo);
6308  $newvalue = dol_hash($this->array_options[$key], $algo);
6309  $new_array_options[$key] = $newvalue;
6310  }
6311  } else {
6312  $new_array_options[$key] = $this->array_options[$key]; // Value is kept
6313  }
6314  }
6315  } else // Common usage
6316  {
6317  $new_array_options[$key] = $this->array_options[$key];
6318  }
6319  break;
6320  case 'date':
6321  case 'datetime':
6322  // If data is a string instead of a timestamp, we convert it
6323  if (!is_numeric($this->array_options[$key]) || $this->array_options[$key] != intval($this->array_options[$key])) {
6324  $this->array_options[$key] = strtotime($this->array_options[$key]);
6325  }
6326  $new_array_options[$key] = $this->db->idate($this->array_options[$key]);
6327  break;
6328  case 'link':
6329  $param_list = array_keys($attributeParam['options']);
6330  // 0 : ObjectName
6331  // 1 : classPath
6332  $InfoFieldList = explode(":", $param_list[0]);
6333  dol_include_once($InfoFieldList[1]);
6334  if ($InfoFieldList[0] && class_exists($InfoFieldList[0])) {
6335  if ($value == '-1') { // -1 is key for no defined in combo list of objects
6336  $new_array_options[$key] = '';
6337  } elseif ($value) {
6338  $object = new $InfoFieldList[0]($this->db);
6339  if (is_numeric($value)) {
6340  $res = $object->fetch($value); // Common case
6341  } else {
6342  $res = $object->fetch('', $value); // For compatibility
6343  }
6344 
6345  if ($res > 0) {
6346  $new_array_options[$key] = $object->id;
6347  } else {
6348  $this->error = "Id/Ref '".$value."' for object '".$object->element."' not found";
6349  return -1;
6350  }
6351  }
6352  } else {
6353  dol_syslog('Error bad setup of extrafield', LOG_WARNING);
6354  }
6355  break;
6356  }
6357  }
6358 
6359  $this->db->begin();
6360 
6361  $table_element = $this->table_element;
6362  if ($table_element == 'categorie') {
6363  $table_element = 'categories'; // For compatibility
6364  }
6365 
6366  dol_syslog(get_class($this)."::insertExtraFields delete then insert", LOG_DEBUG);
6367 
6368  $sql_del = "DELETE FROM ".$this->db->prefix().$table_element."_extrafields WHERE fk_object = ".((int) $this->id);
6369  $this->db->query($sql_del);
6370 
6371  $sql = "INSERT INTO ".$this->db->prefix().$table_element."_extrafields (fk_object";
6372  foreach ($new_array_options as $key => $value) {
6373  $attributeKey = substr($key, 8); // Remove 'options_' prefix
6374  // Add field of attribut
6375  if ($extrafields->attributes[$this->table_element]['type'][$attributeKey] != 'separate') { // Only for other type than separator
6376  $sql .= ",".$attributeKey;
6377  }
6378  }
6379  // We must insert a default value for fields for other entities that are mandatory to avoid not null error
6380  if (!empty($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities']) && is_array($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'])) {
6381  foreach ($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'] as $tmpkey => $tmpval) {
6382  if (!isset($extrafields->attributes[$this->table_element]['type'][$tmpkey])) { // If field not already added previously
6383  $sql .= ",".$tmpkey;
6384  }
6385  }
6386  }
6387  $sql .= ") VALUES (".$this->id;
6388 
6389  foreach ($new_array_options as $key => $value) {
6390  $attributeKey = substr($key, 8); // Remove 'options_' prefix
6391  // Add field of attribute
6392  if ($extrafields->attributes[$this->table_element]['type'][$attributeKey] != 'separate') { // Only for other type than separator)
6393  if ($new_array_options[$key] != '' || $new_array_options[$key] == '0') {
6394  $sql .= ",'".$this->db->escape($new_array_options[$key])."'";
6395  } else {
6396  $sql .= ",null";
6397  }
6398  }
6399  }
6400  // We must insert a default value for fields for other entities that are mandatory to avoid not null error
6401  if (!empty($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities']) && is_array($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'])) {
6402  foreach ($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'] as $tmpkey => $tmpval) {
6403  if (!isset($extrafields->attributes[$this->table_element]['type'][$tmpkey])) { // If field not already added previously
6404  if (in_array($tmpval, array('int', 'double', 'price'))) {
6405  $sql .= ", 0";
6406  } else {
6407  $sql .= ", ''";
6408  }
6409  }
6410  }
6411  }
6412 
6413  $sql .= ")";
6414 
6415  $resql = $this->db->query($sql);
6416  if (!$resql) {
6417  $this->error = $this->db->lasterror();
6418  $error++;
6419  }
6420 
6421  if (!$error && $trigger) {
6422  // Call trigger
6423  $this->context = array('extrafieldaddupdate'=>1);
6424  $result = $this->call_trigger($trigger, $userused);
6425  if ($result < 0) {
6426  $error++;
6427  }
6428  // End call trigger
6429  }
6430 
6431  if ($error) {
6432  $this->db->rollback();
6433  return -1;
6434  } else {
6435  $this->db->commit();
6436  return 1;
6437  }
6438  } else {
6439  return 0;
6440  }
6441  }
6442 
6453  public function insertExtraLanguages($trigger = '', $userused = null)
6454  {
6455  global $conf, $langs, $user;
6456 
6457  if (empty($userused)) {
6458  $userused = $user;
6459  }
6460 
6461  $error = 0;
6462 
6463  if (!empty($conf->global->MAIN_EXTRALANGUAGES_DISABLED)) {
6464  return 0; // For avoid conflicts if trigger used
6465  }
6466 
6467  if (is_array($this->array_languages)) {
6468  $new_array_languages = $this->array_languages;
6469 
6470  foreach ($new_array_languages as $key => $value) {
6471  $attributeKey = $key;
6472  $attributeType = $this->fields[$attributeKey]['type'];
6473  $attributeLabel = $this->fields[$attributeKey]['label'];
6474 
6475  //dol_syslog("attributeLabel=".$attributeLabel, LOG_DEBUG);
6476  //dol_syslog("attributeType=".$attributeType, LOG_DEBUG);
6477 
6478  switch ($attributeType) {
6479  case 'int':
6480  if (!is_numeric($value) && $value != '') {
6481  $this->errors[] = $langs->trans("ExtraLanguageHasWrongValue", $attributeLabel);
6482  return -1;
6483  } elseif ($value == '') {
6484  $new_array_languages[$key] = null;
6485  }
6486  break;
6487  case 'double':
6488  $value = price2num($value);
6489  if (!is_numeric($value) && $value != '') {
6490  dol_syslog($langs->trans("ExtraLanguageHasWrongValue")." sur ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
6491  $this->errors[] = $langs->trans("ExtraLanguageHasWrongValue", $attributeLabel);
6492  return -1;
6493  } elseif ($value == '') {
6494  $new_array_languages[$key] = null;
6495  }
6496  //dol_syslog("double value"." sur ".$attributeLabel."(".$value." is '".$attributeType."')", LOG_DEBUG);
6497  $new_array_languages[$key] = $value;
6498  break;
6499  /*case 'select': // Not required, we chosed value='0' for undefined values
6500  if ($value=='-1')
6501  {
6502  $this->array_options[$key] = null;
6503  }
6504  break;*/
6505  }
6506  }
6507 
6508  $this->db->begin();
6509 
6510  $table_element = $this->table_element;
6511  if ($table_element == 'categorie') {
6512  $table_element = 'categories'; // For compatibility
6513  }
6514 
6515  dol_syslog(get_class($this)."::insertExtraLanguages delete then insert", LOG_DEBUG);
6516 
6517  foreach ($new_array_languages as $key => $langcodearray) { // $key = 'name', 'town', ...
6518  foreach ($langcodearray as $langcode => $value) {
6519  $sql_del = "DELETE FROM ".$this->db->prefix()."object_lang";
6520  $sql_del .= " WHERE fk_object = ".((int) $this->id)." AND property = '".$this->db->escape($key)."' AND type_object = '".$this->db->escape($table_element)."'";
6521  $sql_del .= " AND lang = '".$this->db->escape($langcode)."'";
6522  $this->db->query($sql_del);
6523 
6524  if ($value !== '') {
6525  $sql = "INSERT INTO ".$this->db->prefix()."object_lang (fk_object, property, type_object, lang, value";
6526  $sql .= ") VALUES (".$this->id.", '".$this->db->escape($key)."', '".$this->db->escape($table_element)."', '".$this->db->escape($langcode)."', '".$this->db->escape($value)."'";
6527  $sql .= ")";
6528 
6529  $resql = $this->db->query($sql);
6530  if (!$resql) {
6531  $this->error = $this->db->lasterror();
6532  $error++;
6533  break;
6534  }
6535  }
6536  }
6537  }
6538 
6539  if (!$error && $trigger) {
6540  // Call trigger
6541  $this->context = array('extralanguagesaddupdate'=>1);
6542  $result = $this->call_trigger($trigger, $userused);
6543  if ($result < 0) {
6544  $error++;
6545  }
6546  // End call trigger
6547  }
6548 
6549  if ($error) {
6550  $this->db->rollback();
6551  return -1;
6552  } else {
6553  $this->db->commit();
6554  return 1;
6555  }
6556  } else {
6557  return 0;
6558  }
6559  }
6560 
6571  public function updateExtraField($key, $trigger = null, $userused = null)
6572  {
6573  global $conf, $langs, $user;
6574 
6575  if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
6576  return 0;
6577  }
6578 
6579  if (empty($userused)) {
6580  $userused = $user;
6581  }
6582 
6583  $error = 0;
6584 
6585  if (!empty($this->array_options) && isset($this->array_options["options_".$key])) {
6586  // Check parameters
6587  $langs->load('admin');
6588  require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
6589  $extrafields = new ExtraFields($this->db);
6590  $extrafields->fetch_name_optionals_label($this->table_element);
6591 
6592  $value = $this->array_options["options_".$key];
6593 
6594  $attributeType = $extrafields->attributes[$this->table_element]['type'][$key];
6595  $attributeLabel = $extrafields->attributes[$this->table_element]['label'][$key];
6596  $attributeParam = $extrafields->attributes[$this->table_element]['param'][$key];
6597  $attributeRequired = $extrafields->attributes[$this->table_element]['required'][$key];
6598  $attrfieldcomputed = $extrafields->attributes[$this->table_element]['computed'][$key];
6599 
6600  // Similar code than into insertExtraFields
6601  if ($attributeRequired) {
6602  $mandatorypb = false;
6603  if ($attributeType == 'link' && $this->array_options["options_".$key] == '-1') {
6604  $mandatorypb = true;
6605  }
6606  if ($this->array_options["options_".$key] === '') {
6607  $mandatorypb = true;
6608  }
6609  if ($mandatorypb) {
6610  $langs->load("errors");
6611  dol_syslog("Mandatory field 'options_".$key."' is empty during update and set to required into definition of extrafields");
6612  $this->errors[] = $langs->trans('ErrorFieldRequired', $attributeLabel);
6613  return -1;
6614  }
6615  }
6616 
6617  //dol_syslog("attributeLabel=".$attributeLabel, LOG_DEBUG);
6618  //dol_syslog("attributeType=".$attributeType, LOG_DEBUG);
6619 
6620  if (!empty($attrfieldcomputed)) {
6621  if (!empty($conf->global->MAIN_STORE_COMPUTED_EXTRAFIELDS)) {
6622  $value = dol_eval($attrfieldcomputed, 1, 0, '');
6623  dol_syslog($langs->trans("Extrafieldcomputed")." sur ".$attributeLabel."(".$value.")", LOG_DEBUG);
6624  $this->array_options["options_".$key] = $value;
6625  } else {
6626  $this->array_options["options_".$key] = null;
6627  }
6628  }
6629 
6630  switch ($attributeType) {
6631  case 'int':
6632  if (!is_numeric($value) && $value != '') {
6633  $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
6634  return -1;
6635  } elseif ($value === '') {
6636  $this->array_options["options_".$key] = null;
6637  }
6638  break;
6639  case 'double':
6640  $value = price2num($value);
6641  if (!is_numeric($value) && $value != '') {
6642  dol_syslog($langs->trans("ExtraFieldHasWrongValue")." sur ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
6643  $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
6644  return -1;
6645  } elseif ($value === '') {
6646  $value = null;
6647  }
6648  //dol_syslog("double value"." sur ".$attributeLabel."(".$value." is '".$attributeType."')", LOG_DEBUG);
6649  $this->array_options["options_".$key] = $value;
6650  break;
6651  /*case 'select': // Not required, we chosed value='0' for undefined values
6652  if ($value=='-1')
6653  {
6654  $this->array_options[$key] = null;
6655  }
6656  break;*/
6657  case 'price':
6658  $this->array_options["options_".$key] = price2num($this->array_options["options_".$key]);
6659  break;
6660  case 'date':
6661  case 'datetime':
6662  if (empty($this->array_options["options_".$key])) {
6663  $this->array_options["options_".$key] = null;
6664  } else {
6665  $this->array_options["options_".$key] = $this->db->idate($this->array_options["options_".$key]);
6666  }
6667  break;
6668  case 'boolean':
6669  if (empty($this->array_options["options_".$key])) {
6670  $this->array_options["options_".$key] = null;
6671  }
6672  break;
6673  case 'link':
6674  if ($this->array_options["options_".$key] === '') {
6675  $this->array_options["options_".$key] = null;
6676  }
6677  break;
6678  /*
6679  case 'link':
6680  $param_list = array_keys($attributeParam['options']);
6681  // 0 : ObjectName
6682  // 1 : classPath
6683  $InfoFieldList = explode(":", $param_list[0]);
6684  dol_include_once($InfoFieldList[1]);
6685  if ($InfoFieldList[0] && class_exists($InfoFieldList[0]))
6686  {
6687  if ($value == '-1') // -1 is key for no defined in combo list of objects
6688  {
6689  $new_array_options[$key] = '';
6690  } elseif ($value) {
6691  $object = new $InfoFieldList[0]($this->db);
6692  if (is_numeric($value)) $res = $object->fetch($value); // Common case
6693  else $res = $object->fetch('', $value); // For compatibility
6694 
6695  if ($res > 0) $new_array_options[$key] = $object->id;
6696  else {
6697  $this->error = "Id/Ref '".$value."' for object '".$object->element."' not found";
6698  $this->db->rollback();
6699  return -1;
6700  }
6701  }
6702  } else {
6703  dol_syslog('Error bad setup of extrafield', LOG_WARNING);
6704  }
6705  break;
6706  */
6707  }
6708 
6709  $this->db->begin();
6710 
6711  $linealreadyfound = 0;
6712 
6713  // 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)
6714  $sql = "SELECT COUNT(rowid) as nb FROM ".$this->db->prefix().$this->table_element."_extrafields WHERE fk_object = ".((int) $this->id);
6715  $resql = $this->db->query($sql);
6716  if ($resql) {
6717  $tmpobj = $this->db->fetch_object($resql);
6718  if ($tmpobj) {
6719  $linealreadyfound = $tmpobj->nb;
6720  }
6721  }
6722 
6723  if ($linealreadyfound) {
6724  if ($this->array_options["options_".$key] === null) {
6725  $sql = "UPDATE ".$this->db->prefix().$this->table_element."_extrafields SET ".$key." = null";
6726  } else {
6727  $sql = "UPDATE ".$this->db->prefix().$this->table_element."_extrafields SET ".$key." = '".$this->db->escape($this->array_options["options_".$key])."'";
6728  }
6729  $sql .= " WHERE fk_object = ".((int) $this->id);
6730  } else {
6731  $result = $this->insertExtraFields('', $user);
6732  if ($result < 0) {
6733  $error++;
6734  }
6735  }
6736 
6737  $resql = $this->db->query($sql);
6738  if (!$resql) {
6739  $error++;
6740  $this->error = $this->db->lasterror();
6741  }
6742  if (!$error && $trigger) {
6743  // Call trigger
6744  $this->context = array('extrafieldupdate'=>1);
6745  $result = $this->call_trigger($trigger, $userused);
6746  if ($result < 0) {
6747  $error++;
6748  }
6749  // End call trigger
6750  }
6751 
6752  if ($error) {
6753  dol_syslog(__METHOD__.$this->error, LOG_ERR);
6754  $this->db->rollback();
6755  return -1;
6756  } else {
6757  $this->db->commit();
6758  return 1;
6759  }
6760  } else {
6761  return 0;
6762  }
6763  }
6764 
6775  public function updateExtraLanguages($key, $trigger = null, $userused = null)
6776  {
6777  global $conf, $langs, $user;
6778 
6779  if (empty($userused)) {
6780  $userused = $user;
6781  }
6782 
6783  $error = 0;
6784 
6785  if (!empty($conf->global->MAIN_EXTRALANGUAGES_DISABLED)) {
6786  return 0; // For avoid conflicts if trigger used
6787  }
6788 
6789  return 0;
6790  }
6791 
6792 
6807  public function showInputField($val, $key, $value, $moreparam = '', $keysuffix = '', $keyprefix = '', $morecss = 0, $nonewbutton = 0)
6808  {
6809  global $conf, $langs, $form;
6810 
6811  if (!is_object($form)) {
6812  require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
6813  $form = new Form($this->db);
6814  }
6815 
6816  if (!empty($this->fields)) {
6817  $val = $this->fields[$key];
6818  }
6819 
6820  // Validation tests and output
6821  $fieldValidationErrorMsg = '';
6822  $validationClass = '';
6823  $fieldValidationErrorMsg = $this->getFieldError($key);
6824  if (!empty($fieldValidationErrorMsg)) {
6825  $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
6826  } else {
6827  $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
6828  }
6829 
6830  $out = '';
6831  $type = '';
6832  $isDependList = 0;
6833  $param = array();
6834  $param['options'] = array();
6835  $reg = array();
6836  $size = !empty($this->fields[$key]['size']) ? $this->fields[$key]['size'] : 0;
6837  // Because we work on extrafields
6838  if (preg_match('/^(integer|link):(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
6839  $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4].':'.$reg[5] => 'N');
6840  $type = 'link';
6841  } elseif (preg_match('/^(integer|link):(.*):(.*):(.*)/i', $val['type'], $reg)) {
6842  $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4] => 'N');
6843  $type = 'link';
6844  } elseif (preg_match('/^(integer|link):(.*):(.*)/i', $val['type'], $reg)) {
6845  $param['options'] = array($reg[2].':'.$reg[3] => 'N');
6846  $type = 'link';
6847  } elseif (preg_match('/^(sellist):(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
6848  $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4].':'.$reg[5] => 'N');
6849  $type = 'sellist';
6850  } elseif (preg_match('/^(sellist):(.*):(.*):(.*)/i', $val['type'], $reg)) {
6851  $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4] => 'N');
6852  $type = 'sellist';
6853  } elseif (preg_match('/^(sellist):(.*):(.*)/i', $val['type'], $reg)) {
6854  $param['options'] = array($reg[2].':'.$reg[3] => 'N');
6855  $type = 'sellist';
6856  } elseif (preg_match('/^chkbxlst:(.*)/i', $val['type'], $reg)) {
6857  $param['options'] = array($reg[1] => 'N');
6858  $type = 'chkbxlst';
6859  } elseif (preg_match('/varchar\((\d+)\)/', $val['type'], $reg)) {
6860  $param['options'] = array();
6861  $type = 'varchar';
6862  $size = $reg[1];
6863  } elseif (preg_match('/varchar/', $val['type'])) {
6864  $param['options'] = array();
6865  $type = 'varchar';
6866  } else {
6867  $param['options'] = array();
6868  $type = $this->fields[$key]['type'];
6869  }
6870 
6871  // Special case that force options and type ($type can be integer, varchar, ...)
6872  if (!empty($this->fields[$key]['arrayofkeyval']) && is_array($this->fields[$key]['arrayofkeyval'])) {
6873  $param['options'] = $this->fields[$key]['arrayofkeyval'];
6874  $type = 'select';
6875  }
6876 
6877  $label = $this->fields[$key]['label'];
6878  //$elementtype=$this->fields[$key]['elementtype']; // Seems not used
6879  $default = (!empty($this->fields[$key]['default']) ? $this->fields[$key]['default'] : '');
6880  $computed = (!empty($this->fields[$key]['computed']) ? $this->fields[$key]['computed'] : '');
6881  $unique = (!empty($this->fields[$key]['unique']) ? $this->fields[$key]['unique'] : 0);
6882  $required = (!empty($this->fields[$key]['required']) ? $this->fields[$key]['required'] : 0);
6883  $autofocusoncreate = (!empty($this->fields[$key]['autofocusoncreate']) ? $this->fields[$key]['autofocusoncreate'] : 0);
6884 
6885  $langfile = (!empty($this->fields[$key]['langfile']) ? $this->fields[$key]['langfile'] : '');
6886  $list = (!empty($this->fields[$key]['list']) ? $this->fields[$key]['list'] : 0);
6887  $hidden = (in_array(abs($this->fields[$key]['visible']), array(0, 2)) ? 1 : 0);
6888 
6889  $objectid = $this->id;
6890 
6891  if ($computed) {
6892  if (!preg_match('/^search_/', $keyprefix)) {
6893  return '<span class="opacitymedium">'.$langs->trans("AutomaticallyCalculated").'</span>';
6894  } else {
6895  return '';
6896  }
6897  }
6898 
6899  // Set value of $morecss. For this, we use in priority showsize from parameters, then $val['css'] then autodefine
6900  if (empty($morecss) && !empty($val['css'])) {
6901  $morecss = $val['css'];
6902  } elseif (empty($morecss)) {
6903  if ($type == 'date') {
6904  $morecss = 'minwidth100imp';
6905  } elseif ($type == 'datetime' || $type == 'link') { // link means an foreign key to another primary id
6906  $morecss = 'minwidth200imp';
6907  } elseif (in_array($type, array('int', 'integer', 'price')) || preg_match('/^double(\([0-9],[0-9]\)){0,1}/', $type)) {
6908  $morecss = 'maxwidth75';
6909  } elseif ($type == 'url') {
6910  $morecss = 'minwidth400';
6911  } elseif ($type == 'boolean') {
6912  $morecss = '';
6913  } else {
6914  if (round($size) < 12) {
6915  $morecss = 'minwidth100';
6916  } elseif (round($size) <= 48) {
6917  $morecss = 'minwidth200';
6918  } else {
6919  $morecss = 'minwidth400';
6920  }
6921  }
6922  }
6923 
6924  // Add validation state class
6925  if (!empty($validationClass)) {
6926  $morecss.= $validationClass;
6927  }
6928 
6929  if (in_array($type, array('date'))) {
6930  $tmp = explode(',', $size);
6931  $newsize = $tmp[0];
6932  $showtime = 0;
6933 
6934  // Do not show current date when field not required (see selectDate() method)
6935  if (!$required && $value == '') {
6936  $value = '-1';
6937  }
6938 
6939  // TODO Must also support $moreparam
6940  $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required, '', 1, (($keyprefix != 'search_' && $keyprefix != 'search_options_') ? 1 : 0), 0, 1);
6941  } elseif (in_array($type, array('datetime'))) {
6942  $tmp = explode(',', $size);
6943  $newsize = $tmp[0];
6944  $showtime = 1;
6945 
6946  // Do not show current date when field not required (see selectDate() method)
6947  if (!$required && $value == '') $value = '-1';
6948 
6949  // TODO Must also support $moreparam
6950  $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required, '', 1, (($keyprefix != 'search_' && $keyprefix != 'search_options_') ? 1 : 0), 0, 1, '', '', '', 1, '', '', 'tzuserrel');
6951  } elseif (in_array($type, array('duration'))) {
6952  $out = $form->select_duration($keyprefix.$key.$keysuffix, $value, 0, 'text', 0, 1);
6953  } elseif (in_array($type, array('int', 'integer'))) {
6954  $tmp = explode(',', $size);
6955  $newsize = $tmp[0];
6956  $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' : '').'>';
6957  } elseif (in_array($type, array('real'))) {
6958  $out = '<input type="text" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'"'.($moreparam ? $moreparam : '').($autofocusoncreate ? ' autofocus' : '').'>';
6959  } elseif (preg_match('/varchar/', $type)) {
6960  $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' : '').'>';
6961  } elseif (in_array($type, array('email', 'mail', 'phone', 'url', 'ip'))) {
6962  $out = '<input type="text" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').($autofocusoncreate ? ' autofocus' : '').'>';
6963  } elseif (preg_match('/^text/', $type)) {
6964  if (!preg_match('/search_/', $keyprefix)) { // If keyprefix is search_ or search_options_, we must just use a simple text field
6965  require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
6966  $doleditor = new DolEditor($keyprefix.$key.$keysuffix, $value, '', 200, 'dolibarr_notes', 'In', false, false, false, ROWS_5, '90%');
6967  $out = $doleditor->Create(1);
6968  } else {
6969  $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').'>';
6970  }
6971  } elseif (preg_match('/^html/', $type)) {
6972  if (!preg_match('/search_/', $keyprefix)) { // If keyprefix is search_ or search_options_, we must just use a simple text field
6973  require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
6974  $doleditor = new DolEditor($keyprefix.$key.$keysuffix, $value, '', 200, 'dolibarr_notes', 'In', false, false, isModEnabled('fckeditor') && $conf->global->FCKEDITOR_ENABLE_SOCIETE, ROWS_5, '90%');
6975  $out = $doleditor->Create(1, '', true, '', '', $moreparam, $morecss);
6976  } else {
6977  $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').'>';
6978  }
6979  } elseif ($type == 'boolean') {
6980  $checked = '';
6981  if (!empty($value)) {
6982  $checked = ' checked value="1" ';
6983  } else {
6984  $checked = ' value="1" ';
6985  }
6986  $out = '<input type="checkbox" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.$checked.' '.($moreparam ? $moreparam : '').'>';
6987  } elseif ($type == 'price') {
6988  if (!empty($value)) { // $value in memory is a php numeric, we format it into user number format.
6989  $value = price($value);
6990  }
6991  $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'> '.$langs->getCurrencySymbol($conf->currency);
6992  } elseif (preg_match('/^double(\([0-9],[0-9]\)){0,1}/', $type)) {
6993  if (!empty($value)) { // $value in memory is a php numeric, we format it into user number format.
6994  $value = price($value);
6995  }
6996  $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'> ';
6997  } elseif ($type == 'select') {
6998  $out = '';
6999  if (!empty($conf->use_javascript_ajax) && empty($conf->global->MAIN_EXTRAFIELDS_DISABLE_SELECT2)) {
7000  include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
7001  $out .= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
7002  }
7003 
7004  $out .= '<select class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '').'>';
7005  if ((!isset($this->fields[$key]['default'])) || ($this->fields[$key]['notnull'] != 1)) {
7006  $out .= '<option value="0">&nbsp;</option>';
7007  }
7008  foreach ($param['options'] as $keyb => $valb) {
7009  if ((string) $keyb == '') {
7010  continue;
7011  }
7012  if (strpos($valb, "|") !== false) {
7013  list($valb, $parent) = explode('|', $valb);
7014  }
7015  $out .= '<option value="'.$keyb.'"';
7016  $out .= (((string) $value == (string) $keyb) ? ' selected' : '');
7017  $out .= (!empty($parent) ? ' parent="'.$parent.'"' : '');
7018  $out .= '>'.$valb.'</option>';
7019  }
7020  $out .= '</select>';
7021  } elseif ($type == 'sellist') {
7022  $out = '';
7023  if (!empty($conf->use_javascript_ajax) && empty($conf->global->MAIN_EXTRAFIELDS_DISABLE_SELECT2)) {
7024  include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
7025  $out .= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
7026  }
7027 
7028  $out .= '<select class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '').'>';
7029  if (is_array($param['options'])) {
7030  $param_list = array_keys($param['options']);
7031  $InfoFieldList = explode(":", $param_list[0]);
7032  $parentName = '';
7033  $parentField = '';
7034  // 0 : tableName
7035  // 1 : label field name
7036  // 2 : key fields name (if differ of rowid)
7037  // 3 : key field parent (for dependent lists)
7038  // 4 : where clause filter on column or table extrafield, syntax field='value' or extra.field=value
7039  // 5 : id category type
7040  // 6 : ids categories list separated by comma for category root
7041  $keyList = (empty($InfoFieldList[2]) ? 'rowid' : $InfoFieldList[2].' as rowid');
7042 
7043  if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
7044  if (strpos($InfoFieldList[4], 'extra.') !== false) {
7045  $keyList = 'main.'.$InfoFieldList[2].' as rowid';
7046  } else {
7047  $keyList = $InfoFieldList[2].' as rowid';
7048  }
7049  }
7050  if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
7051  list($parentName, $parentField) = explode('|', $InfoFieldList[3]);
7052  $keyList .= ', '.$parentField;
7053  }
7054 
7055  $filter_categorie = false;
7056  if (count($InfoFieldList) > 5) {
7057  if ($InfoFieldList[0] == 'categorie') {
7058  $filter_categorie = true;
7059  }
7060  }
7061 
7062  if ($filter_categorie === false) {
7063  $fields_label = explode('|', $InfoFieldList[1]);
7064  if (is_array($fields_label)) {
7065  $keyList .= ', ';
7066  $keyList .= implode(', ', $fields_label);
7067  }
7068 
7069  $sqlwhere = '';
7070  $sql = "SELECT " . $keyList;
7071  $sql .= " FROM " . $this->db->prefix() . $InfoFieldList[0];
7072  if (!empty($InfoFieldList[4])) {
7073  // can use SELECT request
7074  if (strpos($InfoFieldList[4], '$SEL$') !== false) {
7075  $InfoFieldList[4] = str_replace('$SEL$', 'SELECT', $InfoFieldList[4]);
7076  }
7077 
7078  // current object id can be use into filter
7079  if (strpos($InfoFieldList[4], '$ID$') !== false && !empty($objectid)) {
7080  $InfoFieldList[4] = str_replace('$ID$', $objectid, $InfoFieldList[4]);
7081  } else {
7082  $InfoFieldList[4] = str_replace('$ID$', '0', $InfoFieldList[4]);
7083  }
7084 
7085  //We have to join on extrafield table
7086  if (strpos($InfoFieldList[4], 'extra') !== false) {
7087  $sql .= " as main, " . $this->db->prefix() . $InfoFieldList[0] . "_extrafields as extra";
7088  $sqlwhere .= " WHERE extra.fk_object=main." . $InfoFieldList[2] . " AND " . $InfoFieldList[4];
7089  } else {
7090  $sqlwhere .= " WHERE " . $InfoFieldList[4];
7091  }
7092  } else {
7093  $sqlwhere .= ' WHERE 1=1';
7094  }
7095  // Some tables may have field, some other not. For the moment we disable it.
7096  if (in_array($InfoFieldList[0], array('tablewithentity'))) {
7097  $sqlwhere .= " AND entity = " . ((int) $conf->entity);
7098  }
7099  $sql .= $sqlwhere;
7100  //print $sql;
7101 
7102  $sql .= ' ORDER BY ' . implode(', ', $fields_label);
7103 
7104  dol_syslog(get_class($this) . '::showInputField type=sellist', LOG_DEBUG);
7105  $resql = $this->db->query($sql);
7106  if ($resql) {
7107  $out .= '<option value="0">&nbsp;</option>';
7108  $num = $this->db->num_rows($resql);
7109  $i = 0;
7110  while ($i < $num) {
7111  $labeltoshow = '';
7112  $obj = $this->db->fetch_object($resql);
7113 
7114  // Several field into label (eq table:code|libelle:rowid)
7115  $notrans = false;
7116  $fields_label = explode('|', $InfoFieldList[1]);
7117  if (count($fields_label) > 1) {
7118  $notrans = true;
7119  foreach ($fields_label as $field_toshow) {
7120  $labeltoshow .= $obj->$field_toshow . ' ';
7121  }
7122  } else {
7123  $labeltoshow = $obj->{$InfoFieldList[1]};
7124  }
7125  $labeltoshow = dol_trunc($labeltoshow, 45);
7126 
7127  if ($value == $obj->rowid) {
7128  foreach ($fields_label as $field_toshow) {
7129  $translabel = $langs->trans($obj->$field_toshow);
7130  if ($translabel != $obj->$field_toshow) {
7131  $labeltoshow = dol_trunc($translabel) . ' ';
7132  } else {
7133  $labeltoshow = dol_trunc($obj->$field_toshow) . ' ';
7134  }
7135  }
7136  $out .= '<option value="' . $obj->rowid . '" selected>' . $labeltoshow . '</option>';
7137  } else {
7138  if (!$notrans) {
7139  $translabel = $langs->trans($obj->{$InfoFieldList[1]});
7140  if ($translabel != $obj->{$InfoFieldList[1]}) {
7141  $labeltoshow = dol_trunc($translabel, 18);
7142  } else {
7143  $labeltoshow = dol_trunc($obj->{$InfoFieldList[1]});
7144  }
7145  }
7146  if (empty($labeltoshow)) {
7147  $labeltoshow = '(not defined)';
7148  }
7149  if ($value == $obj->rowid) {
7150  $out .= '<option value="' . $obj->rowid . '" selected>' . $labeltoshow . '</option>';
7151  }
7152 
7153  if (!empty($InfoFieldList[3]) && $parentField) {
7154  $parent = $parentName . ':' . $obj->{$parentField};
7155  $isDependList = 1;
7156  }
7157 
7158  $out .= '<option value="' . $obj->rowid . '"';
7159  $out .= ($value == $obj->rowid ? ' selected' : '');
7160  $out .= (!empty($parent) ? ' parent="' . $parent . '"' : '');
7161  $out .= '>' . $labeltoshow . '</option>';
7162  }
7163 
7164  $i++;
7165  }
7166  $this->db->free($resql);
7167  } else {
7168  print 'Error in request ' . $sql . ' ' . $this->db->lasterror() . '. Check setup of extra parameters.<br>';
7169  }
7170  } else {
7171  require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
7172  $data = $form->select_all_categories(Categorie::$MAP_ID_TO_CODE[$InfoFieldList[5]], '', 'parent', 64, $InfoFieldList[6], 1, 1);
7173  $out .= '<option value="0">&nbsp;</option>';
7174  foreach ($data as $data_key => $data_value) {
7175  $out .= '<option value="' . $data_key . '"';
7176  $out .= ($value == $data_key ? ' selected' : '');
7177  $out .= '>' . $data_value . '</option>';
7178  }
7179  }
7180  }
7181  $out .= '</select>';
7182  } elseif ($type == 'checkbox') {
7183  $value_arr = explode(',', $value);
7184  $out = $form->multiselectarray($keyprefix.$key.$keysuffix, (empty($param['options']) ?null:$param['options']), $value_arr, '', 0, $morecss, 0, '100%');
7185  } elseif ($type == 'radio') {
7186  $out = '';
7187  foreach ($param['options'] as $keyopt => $valopt) {
7188  $out .= '<input class="flat '.$morecss.'" type="radio" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '');
7189  $out .= ' value="'.$keyopt.'"';
7190  $out .= ' id="'.$keyprefix.$key.$keysuffix.'_'.$keyopt.'"';
7191  $out .= ($value == $keyopt ? 'checked' : '');
7192  $out .= '/><label for="'.$keyprefix.$key.$keysuffix.'_'.$keyopt.'">'.$valopt.'</label><br>';
7193  }
7194  } elseif ($type == 'chkbxlst') {
7195  if (is_array($value)) {
7196  $value_arr = $value;
7197  } else {
7198  $value_arr = explode(',', $value);
7199  }
7200 
7201  if (is_array($param['options'])) {
7202  $param_list = array_keys($param['options']);
7203  $InfoFieldList = explode(":", $param_list[0]);
7204  $parentName = '';
7205  $parentField = '';
7206  // 0 : tableName
7207  // 1 : label field name
7208  // 2 : key fields name (if differ of rowid)
7209  // 3 : key field parent (for dependent lists)
7210  // 4 : where clause filter on column or table extrafield, syntax field='value' or extra.field=value
7211  // 5 : id category type
7212  // 6 : ids categories list separated by comma for category root
7213  $keyList = (empty($InfoFieldList[2]) ? 'rowid' : $InfoFieldList[2].' as rowid');
7214 
7215  if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
7216  list ($parentName, $parentField) = explode('|', $InfoFieldList[3]);
7217  $keyList .= ', '.$parentField;
7218  }
7219  if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
7220  if (strpos($InfoFieldList[4], 'extra.') !== false) {
7221  $keyList = 'mai