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