dolibarr  16.0.1
commonobject.class.php
Go to the documentation of this file.
1 <?php
2 /* Copyright (C) 2006-2015 Laurent Destailleur <eldy@users.sourceforge.net>
3  * Copyright (C) 2005-2013 Regis Houssin <regis.houssin@inodbox.com>
4  * Copyright (C) 2010-2020 Juanjo Menent <jmenent@2byte.es>
5  * Copyright (C) 2012-2013 Christophe Battarel <christophe.battarel@altairis.fr>
6  * Copyright (C) 2011-2019 Philippe Grand <philippe.grand@atoo-net.com>
7  * Copyright (C) 2012-2015 Marcos García <marcosgdf@gmail.com>
8  * Copyright (C) 2012-2015 Raphaël Doursenaud <rdoursenaud@gpcsolutions.fr>
9  * Copyright (C) 2012 Cedric Salvador <csalvador@gpcsolutions.fr>
10  * Copyright (C) 2015-2022 Alexandre Spangaro <aspangaro@open-dsi.fr>
11  * Copyright (C) 2016 Bahfir abbes <dolipar@dolipar.org>
12  * Copyright (C) 2017 ATM Consulting <support@atm-consulting.fr>
13  * Copyright (C) 2017-2019 Nicolas ZABOURI <info@inovea-conseil.com>
14  * Copyright (C) 2017 Rui Strecht <rui.strecht@aliartalentos.com>
15  * Copyright (C) 2018-2021 Frédéric France <frederic.france@netlogic.fr>
16  * Copyright (C) 2018 Josep Lluís Amador <joseplluis@lliuretic.cat>
17  * Copyright (C) 2021 Gauthier VERDOL <gauthier.verdol@atm-consulting.fr>
18  * Copyright (C) 2021 Grégory Blémand <gregory.blemand@atm-consulting.fr>
19  *
20  * This program is free software; you can redistribute it and/or modify
21  * it under the terms of the GNU General Public License as published by
22  * the Free Software Foundation; either version 3 of the License, or
23  * (at your option) any later version.
24  *
25  * This program is distributed in the hope that it will be useful,
26  * but WITHOUT ANY WARRANTY; without even the implied warranty of
27  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
28  * GNU General Public License for more details.
29  *
30  * You should have received a copy of the GNU General Public License
31  * along with this program. If not, see <https://www.gnu.org/licenses/>.
32  */
33 
44 abstract class CommonObject
45 {
46  const TRIGGER_PREFIX = ''; // to be overriden in child class implementations, i.e. 'BILL', 'TASK', 'PROPAL', etc.
50  public $db;
51 
55  public $id;
56 
60  public $entity;
61 
66  public $error;
67 
71  public $errorhidden;
72 
76  public $errors = array();
77 
81  public $validateFieldsErrors = array();
82 
86  public $element;
87 
91  public $element_for_permission;
92 
96  public $table_element;
97 
101  public $table_element_line = '';
102 
106  public $import_key;
107 
111  public $array_options = array();
112 
116  public $array_languages = null; // Value is array() when load already tried
117 
121  public $contacts_ids;
122 
126  public $linked_objects;
127 
131  public $linkedObjectsIds;
132 
136  public $linkedObjects;
137 
141  public $linkedObjectsFullLoaded = array();
142 
146  public $oldcopy;
147 
151  protected $table_ref_field = '';
152 
156  public $restrictiononfksoc = 0;
157 
158 
159  // Following vars are used by some objects only. We keep this property here in CommonObject to be able to provide common method using them.
160 
164  public $context = array();
165 
169  public $canvas;
170 
175  public $project;
176 
181  public $fk_project;
182 
187  public $projet;
188 
193  public $fk_projet;
194 
199  public $contact;
200 
205  public $contact_id;
206 
211  public $thirdparty;
212 
217  public $user;
218 
223  public $origin;
224 
229  public $origin_id;
230 
234  public $ref;
235 
239  public $ref_ext;
240 
244  public $ref_previous;
245 
249  public $ref_next;
250 
254  public $newref;
255 
260  public $statut;
261 
266  public $status;
267 
268 
273  public $country;
274 
279  public $country_id;
280 
285  public $country_code;
286 
291  public $state;
292 
297  public $state_id;
298 
303  public $state_code;
304 
309  public $region_id;
310 
315  public $region_code;
316 
321  public $region;
322 
323 
328  public $barcode_type;
329 
334  public $barcode_type_code;
335 
340  public $barcode_type_label;
341 
346  public $barcode_type_coder;
347 
352  public $mode_reglement_id;
353 
358  public $cond_reglement_id;
359 
363  public $demand_reason_id;
364 
369  public $transport_mode_id;
370 
376  public $cond_reglement;
377 
383  public $fk_delivery_address;
384 
389  public $shipping_method_id;
390 
395  public $model_pdf;
396 
402  public $modelpdf;
403 
408  public $last_main_doc;
409 
415  public $fk_bank;
416 
421  public $fk_account;
422 
426  public $openid;
427 
432  public $note_public;
433 
438  public $note_private;
439 
444  public $note;
445 
450  public $total_ht;
451 
456  public $total_tva;
457 
462  public $total_localtax1;
463 
468  public $total_localtax2;
469 
474  public $total_ttc;
475 
479  public $lines;
480 
485  public $comments = array();
486 
490  public $name;
491 
495  public $lastname;
496 
500  public $firstname;
501 
505  public $civility_id;
506 
507  // Dates
511  public $date_creation;
512 
516  public $date_validation; // Date validation
517 
521  public $date_modification; // Date last change (tms field)
522 
526  public $date_cloture; // Date closing (tms field)
527 
532  public $user_author;
537  public $user_creation;
541  public $user_creation_id;
542 
547  public $user_valid;
552  public $user_validation;
556  public $user_validation_id;
560  public $user_closing_id;
561 
566  public $user_modification;
570  public $user_modification_id;
571 
572 
573  public $next_prev_filter;
574 
578  public $specimen = 0;
579 
583  public $sendtoid;
584 
588  public $alreadypaid;
589 
590 
594  protected $childtables = array();
595 
601  protected $childtablesoncascade = array();
602 
603 
604  // No constructor as it is an abstract class
605 
606 
617  public static function isExistingObject($element, $id, $ref = '', $ref_ext = '')
618  {
619  global $db, $conf;
620 
621  $sql = "SELECT rowid, ref, ref_ext";
622  $sql .= " FROM ".$db->prefix().$element;
623  $sql .= " WHERE entity IN (".getEntity($element).")";
624 
625  if ($id > 0) {
626  $sql .= " AND rowid = ".((int) $id);
627  } elseif ($ref) {
628  $sql .= " AND ref = '".$db->escape($ref)."'";
629  } elseif ($ref_ext) {
630  $sql .= " AND ref_ext = '".$db->escape($ref_ext)."'";
631  } else {
632  $error = 'ErrorWrongParameters';
633  dol_print_error(get_class()."::isExistingObject ".$error, LOG_ERR);
634  return -1;
635  }
636  if ($ref || $ref_ext) { // Because the same ref can exists in 2 different entities, we force the current one in priority
637  $sql .= " AND entity = ".((int) $conf->entity);
638  }
639 
640  dol_syslog(get_class()."::isExistingObject", LOG_DEBUG);
641  $resql = $db->query($sql);
642  if ($resql) {
643  $num = $db->num_rows($resql);
644  if ($num > 0) {
645  return 1;
646  } else {
647  return 0;
648  }
649  }
650  return -1;
651  }
652 
653 
659  public function errorsToString()
660  {
661  return $this->error.(is_array($this->errors) ? (($this->error != '' ? ', ' : '').join(', ', $this->errors)) : '');
662  }
663 
664 
671  public function getFormatedCustomerRef($objref)
672  {
673  global $hookmanager;
674 
675  $parameters = array('objref'=>$objref);
676  $action = '';
677  $reshook = $hookmanager->executeHooks('getFormatedCustomerRef', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
678  if ($reshook > 0) {
679  return $hookmanager->resArray['objref'];
680  }
681  return $objref.(isset($hookmanager->resArray['objref']) ? $hookmanager->resArray['objref'] : '');
682  }
683 
690  public function getFormatedSupplierRef($objref)
691  {
692  global $hookmanager;
693 
694  $parameters = array('objref'=>$objref);
695  $action = '';
696  $reshook = $hookmanager->executeHooks('getFormatedSupplierRef', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
697  if ($reshook > 0) {
698  return $hookmanager->resArray['objref'];
699  }
700  return $objref.(isset($hookmanager->resArray['objref']) ? $hookmanager->resArray['objref'] : '');
701  }
702 
712  public function getFullName($langs, $option = 0, $nameorder = -1, $maxlen = 0)
713  {
714  //print "lastname=".$this->lastname." name=".$this->name." nom=".$this->nom."<br>\n";
715  $lastname = $this->lastname;
716  $firstname = $this->firstname;
717  if (empty($lastname)) {
718  $lastname = (isset($this->lastname) ? $this->lastname : (isset($this->name) ? $this->name : (isset($this->nom) ? $this->nom : (isset($this->societe) ? $this->societe : (isset($this->company) ? $this->company : '')))));
719  }
720 
721  $ret = '';
722  if (!empty($option) && !empty($this->civility_code)) {
723  if ($langs->transnoentitiesnoconv("Civility".$this->civility_code) != "Civility".$this->civility_code) {
724  $ret .= $langs->transnoentitiesnoconv("Civility".$this->civility_code).' ';
725  } else {
726  $ret .= $this->civility_code.' ';
727  }
728  }
729 
730  $ret .= dolGetFirstLastname($firstname, $lastname, $nameorder);
731 
732  return dol_trunc($ret, $maxlen);
733  }
734 
740  public function setUpperOrLowerCase()
741  {
742  global $conf;
743  if (!empty($conf->global->MAIN_FIRST_TO_UPPER)) {
744  $this->lastname = dol_ucwords(dol_strtolower($this->lastname));
745  $this->firstname = dol_ucwords(dol_strtolower($this->firstname));
746  $this->name = dol_ucwords(dol_strtolower($this->name));
747  $this->name_alias = dol_ucwords(dol_strtolower($this->name_alias));
748  }
749  if (!empty($conf->global->MAIN_ALL_TO_UPPER)) {
750  $this->lastname = dol_strtoupper($this->lastname);
751  $this->name = dol_strtoupper($this->name);
752  $this->name_alias = dol_strtoupper($this->name_alias);
753  }
754  if (!empty($conf->global->MAIN_ALL_TOWN_TO_UPPER)) {
755  $this->address = dol_strtoupper($this->address);
756  $this->town = dol_strtoupper($this->town);
757  }
758  }
759 
766  public function getKanbanView($option = '')
767  {
768  $return = '<div class="box-flex-item box-flex-grow-zero">';
769  $return .= '<div class="info-box info-box-sm">';
770  $return .= '<span class="info-box-icon bg-infobox-action">';
771  $return .= img_picto('', $this->picto);
772  //$return .= '<i class="fa fa-dol-action"></i>'; // Can be image
773  $return .= '</span>';
774  $return .= '<div class="info-box-content">';
775  $return .= '<span class="info-box-ref">'.(method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref).'</span>';
776  if (property_exists($this, 'label')) {
777  $return .= '<br><span class="info-box-label opacitymedium">'.$this->label.'</span>';
778  }
779  if (method_exists($this, 'getLibStatut')) {
780  $return .= '<br><div class="info-box-status margintoponly">'.$this->getLibStatut(5).'</div>';
781  }
782  $return .= '</div>';
783  $return .= '</div>';
784  $return .= '</div>';
785 
786  return $return;
787  }
788 
798  public function getFullAddress($withcountry = 0, $sep = "\n", $withregion = 0, $extralangcode = '')
799  {
800  if ($withcountry && $this->country_id && (empty($this->country_code) || empty($this->country))) {
801  require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
802  $tmparray = getCountry($this->country_id, 'all');
803  $this->country_code = $tmparray['code'];
804  $this->country = $tmparray['label'];
805  }
806 
807  if ($withregion && $this->state_id && (empty($this->state_code) || empty($this->state) || empty($this->region) || empty($this->region_code))) {
808  require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
809  $tmparray = getState($this->state_id, 'all', 0, 1);
810  $this->state_code = $tmparray['code'];
811  $this->state = $tmparray['label'];
812  $this->region_code = $tmparray['region_code'];
813  $this->region = $tmparray['region'];
814  }
815 
816  return dol_format_address($this, $withcountry, $sep, '', 0, $extralangcode);
817  }
818 
819 
827  public function getBannerAddress($htmlkey, $object)
828  {
829  global $conf, $langs, $form, $extralanguages;
830 
831  $countriesusingstate = array('AU', 'US', 'IN', 'GB', 'ES', 'UK', 'TR'); // See also option MAIN_FORCE_STATE_INTO_ADDRESS
832 
833  $contactid = 0;
834  $thirdpartyid = 0;
835  $elementforaltlanguage = $this->element;
836  if ($this->element == 'societe') {
837  $thirdpartyid = $this->id;
838  }
839  if ($this->element == 'contact') {
840  $contactid = $this->id;
841  $thirdpartyid = empty($object->fk_soc) ? 0 : $object->fk_soc;
842  }
843  if ($this->element == 'user') {
844  $contactid = $this->contact_id;
845  $thirdpartyid = empty($object->fk_soc) ? 0 : $object->fk_soc;
846  }
847 
848  $out = '';
849 
850  $outdone = 0;
851  $coords = $this->getFullAddress(1, ', ', (!empty($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT) ? $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT : 0));
852  if ($coords) {
853  if (!empty($conf->use_javascript_ajax)) {
854  // Add picto with tooltip on map
855  $namecoords = '';
856  if ($this->element == 'contact' && !empty($conf->global->MAIN_SHOW_COMPANY_NAME_IN_BANNER_ADDRESS)) {
857  $namecoords .= $object->name.'<br>';
858  }
859  $namecoords .= $this->getFullName($langs, 1).'<br>'.$coords;
860  // hideonsmatphone because copyToClipboard call jquery dialog that does not work with jmobile
861  $out .= '<a href="#" class="hideonsmartphone" onclick="return copyToClipboard(\''.dol_escape_js($namecoords).'\',\''.dol_escape_js($langs->trans("HelpCopyToClipboard")).'\');">';
862  $out .= img_picto($langs->trans("Address"), 'map-marker-alt');
863  $out .= '</a> ';
864  }
865  $out .= dol_print_address($coords, 'address_'.$htmlkey.'_'.$this->id, $this->element, $this->id, 1, ', ');
866  $outdone++;
867  $outdone++;
868 
869  // List of extra languages
870  $arrayoflangcode = array();
871  if (!empty($conf->global->PDF_USE_ALSO_LANGUAGE_CODE)) {
872  $arrayoflangcode[] = $conf->global->PDF_USE_ALSO_LANGUAGE_CODE;
873  }
874 
875  if (is_array($arrayoflangcode) && count($arrayoflangcode)) {
876  if (!is_object($extralanguages)) {
877  include_once DOL_DOCUMENT_ROOT.'/core/class/extralanguages.class.php';
878  $extralanguages = new ExtraLanguages($this->db);
879  }
880  $extralanguages->fetch_name_extralanguages($elementforaltlanguage);
881 
882  if (!empty($extralanguages->attributes[$elementforaltlanguage]['address']) || !empty($extralanguages->attributes[$elementforaltlanguage]['town'])) {
883  $out .= "<!-- alternatelanguage for '".$elementforaltlanguage."' set to fields '".join(',', $extralanguages->attributes[$elementforaltlanguage])."' -->\n";
884  $this->fetchValuesForExtraLanguages();
885  if (!is_object($form)) {
886  $form = new Form($this->db);
887  }
888  $htmltext = '';
889  // If there is extra languages
890  foreach ($arrayoflangcode as $extralangcode) {
891  $s = picto_from_langcode($extralangcode, 'class="pictoforlang paddingright"');
892  $coords = $this->getFullAddress(1, ', ', $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT, $extralangcode);
893  $htmltext .= $s.dol_print_address($coords, 'address_'.$htmlkey.'_'.$this->id, $this->element, $this->id, 1, ', ');
894  }
895  $out .= $form->textwithpicto('', $htmltext, -1, 'language', 'opacitymedium paddingleft');
896  }
897  }
898  }
899 
900  if (!in_array($this->country_code, $countriesusingstate) && empty($conf->global->MAIN_FORCE_STATE_INTO_ADDRESS) // If MAIN_FORCE_STATE_INTO_ADDRESS is on, state is already returned previously with getFullAddress
901  && empty($conf->global->SOCIETE_DISABLE_STATE) && $this->state) {
902  if (!empty($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT) && $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT == 1 && $this->region) {
903  $out .= ($outdone ? ' - ' : '').$this->region.' - '.$this->state;
904  } else {
905  $out .= ($outdone ? ' - ' : '').$this->state;
906  }
907  $outdone++;
908  }
909 
910  if (!empty($this->phone) || !empty($this->phone_pro) || !empty($this->phone_mobile) || !empty($this->phone_perso) || !empty($this->fax) || !empty($this->office_phone) || !empty($this->user_mobile) || !empty($this->office_fax)) {
911  $out .= ($outdone ? '<br>' : '');
912  }
913  if (!empty($this->phone) && empty($this->phone_pro)) { // For objects that store pro phone into ->phone
914  $out .= dol_print_phone($this->phone, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'phone', $langs->trans("PhonePro"));
915  $outdone++;
916  }
917  if (!empty($this->phone_pro)) {
918  $out .= dol_print_phone($this->phone_pro, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'phone', $langs->trans("PhonePro"));
919  $outdone++;
920  }
921  if (!empty($this->phone_mobile)) {
922  $out .= dol_print_phone($this->phone_mobile, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'mobile', $langs->trans("PhoneMobile"));
923  $outdone++;
924  }
925  if (!empty($this->phone_perso)) {
926  $out .= dol_print_phone($this->phone_perso, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'phone', $langs->trans("PhonePerso"));
927  $outdone++;
928  }
929  if (!empty($this->office_phone)) {
930  $out .= dol_print_phone($this->office_phone, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'phone', $langs->trans("PhonePro"));
931  $outdone++;
932  }
933  if (!empty($this->user_mobile)) {
934  $out .= dol_print_phone($this->user_mobile, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'mobile', $langs->trans("PhoneMobile"));
935  $outdone++;
936  }
937  if (!empty($this->fax)) {
938  $out .= dol_print_phone($this->fax, $this->country_code, $contactid, $thirdpartyid, 'AC_FAX', '&nbsp;', 'fax', $langs->trans("Fax"));
939  $outdone++;
940  }
941  if (!empty($this->office_fax)) {
942  $out .= dol_print_phone($this->office_fax, $this->country_code, $contactid, $thirdpartyid, 'AC_FAX', '&nbsp;', 'fax', $langs->trans("Fax"));
943  $outdone++;
944  }
945 
946  if ($out) {
947  $out .= '<div style="clear: both;"></div>';
948  }
949  $outdone = 0;
950  if (!empty($this->email)) {
951  $out .= dol_print_email($this->email, $this->id, $object->id, 'AC_EMAIL', 0, 0, 1);
952  $outdone++;
953  }
954  if (!empty($this->url)) {
955  //$out.=dol_print_url($this->url,'_goout',0,1);//steve changed to blank
956  $out .= dol_print_url($this->url, '_blank', 0, 1);
957  $outdone++;
958  }
959 
960  if (!empty($conf->socialnetworks->enabled)) {
961  $outsocialnetwork = '';
962 
963  if (!empty($this->socialnetworks) && is_array($this->socialnetworks) && count($this->socialnetworks) > 0) {
964  $socialnetworksdict = getArrayOfSocialNetworks();
965  foreach ($this->socialnetworks as $key => $value) {
966  if ($value) {
967  $outsocialnetwork .= dol_print_socialnetworks($value, $this->id, $object->id, $key, $socialnetworksdict);
968  }
969  $outdone++;
970  }
971  } else { // Old code to remove
972  if (!empty($this->skype)) {
973  $outsocialnetwork .= dol_print_socialnetworks($this->skype, $this->id, $object->id, 'skype');
974  }
975  $outdone++;
976  if (!empty($this->jabberid)) {
977  $outsocialnetwork .= dol_print_socialnetworks($this->jabberid, $this->id, $object->id, 'jabber');
978  }
979  $outdone++;
980  if (!empty($this->twitter)) {
981  $outsocialnetwork .= dol_print_socialnetworks($this->twitter, $this->id, $object->id, 'twitter');
982  }
983  $outdone++;
984  if (!empty($this->facebook)) {
985  $outsocialnetwork .= dol_print_socialnetworks($this->facebook, $this->id, $object->id, 'facebook');
986  }
987  $outdone++;
988  if (!empty($this->linkedin)) {
989  $outsocialnetwork .= dol_print_socialnetworks($this->linkedin, $this->id, $object->id, 'linkedin');
990  }
991  $outdone++;
992  }
993 
994  if ($outsocialnetwork) {
995  $out .= '<div style="clear: both;">'.$outsocialnetwork.'</div>';
996  }
997  }
998 
999  if ($out) {
1000  return '<!-- BEGIN part to show address block -->'."\n".$out.'<!-- END Part to show address block -->'."\n";
1001  } else {
1002  return '';
1003  }
1004  }
1005 
1014  public function getLastMainDocLink($modulepart, $initsharekey = 0, $relativelink = 0)
1015  {
1016  global $user, $dolibarr_main_url_root;
1017 
1018  if (empty($this->last_main_doc)) {
1019  return ''; // No way to known which document name to use
1020  }
1021 
1022  include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
1023  $ecmfile = new EcmFiles($this->db);
1024  $result = $ecmfile->fetch(0, '', $this->last_main_doc);
1025  if ($result < 0) {
1026  $this->error = $ecmfile->error;
1027  $this->errors = $ecmfile->errors;
1028  return -1;
1029  }
1030 
1031  if (empty($ecmfile->id)) {
1032  // Add entry into index
1033  if ($initsharekey) {
1034  require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
1035 
1036  // TODO We can't, we dont' have full path of file, only last_main_doc and ->element, so we must first rebuild full path $destfull
1037  /*
1038  $ecmfile->filepath = $rel_dir;
1039  $ecmfile->filename = $filename;
1040  $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
1041  $ecmfile->fullpath_orig = '';
1042  $ecmfile->gen_or_uploaded = 'generated';
1043  $ecmfile->description = ''; // indexed content
1044  $ecmfile->keywords = ''; // keyword content
1045  $ecmfile->share = getRandomPassword(true);
1046  $result = $ecmfile->create($user);
1047  if ($result < 0)
1048  {
1049  $this->error = $ecmfile->error;
1050  $this->errors = $ecmfile->errors;
1051  }
1052  */
1053  } else {
1054  return '';
1055  }
1056  } elseif (empty($ecmfile->share)) {
1057  // Add entry into index
1058  if ($initsharekey) {
1059  require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
1060  $ecmfile->share = getRandomPassword(true);
1061  $ecmfile->update($user);
1062  } else {
1063  return '';
1064  }
1065  }
1066  // Define $urlwithroot
1067  $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
1068  // This is to use external domain name found into config file
1069  //if (DOL_URL_ROOT && ! preg_match('/\/$/', $urlwithouturlroot) && ! preg_match('/^\//', DOL_URL_ROOT)) $urlwithroot=$urlwithouturlroot.'/'.DOL_URL_ROOT;
1070  //else
1071  $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT;
1072  //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
1073 
1074  $forcedownload = 0;
1075 
1076  $paramlink = '';
1077  //if (! empty($modulepart)) $paramlink.=($paramlink?'&':'').'modulepart='.$modulepart; // For sharing with hash (so public files), modulepart is not required.
1078  //if (! empty($ecmfile->entity)) $paramlink.='&entity='.$ecmfile->entity; // For sharing with hash (so public files), entity is not required.
1079  //$paramlink.=($paramlink?'&':'').'file='.urlencode($filepath); // No need of name of file for public link, we will use the hash
1080  if (!empty($ecmfile->share)) {
1081  $paramlink .= ($paramlink ? '&' : '').'hashp='.$ecmfile->share; // Hash for public share
1082  }
1083  if ($forcedownload) {
1084  $paramlink .= ($paramlink ? '&' : '').'attachment=1';
1085  }
1086 
1087  if ($relativelink) {
1088  $linktoreturn = 'document.php'.($paramlink ? '?'.$paramlink : '');
1089  } else {
1090  $linktoreturn = $urlwithroot.'/document.php'.($paramlink ? '?'.$paramlink : '');
1091  }
1092 
1093  // Here $ecmfile->share is defined
1094  return $linktoreturn;
1095  }
1096 
1097 
1098  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1108  public function add_contact($fk_socpeople, $type_contact, $source = 'external', $notrigger = 0)
1109  {
1110  // phpcs:enable
1111  global $user, $langs;
1112 
1113 
1114  dol_syslog(get_class($this)."::add_contact $fk_socpeople, $type_contact, $source, $notrigger");
1115 
1116  // Check parameters
1117  if ($fk_socpeople <= 0) {
1118  $langs->load("errors");
1119  $this->error = $langs->trans("ErrorWrongValueForParameterX", "1");
1120  dol_syslog(get_class($this)."::add_contact ".$this->error, LOG_ERR);
1121  return -1;
1122  }
1123  if (!$type_contact) {
1124  $langs->load("errors");
1125  $this->error = $langs->trans("ErrorWrongValueForParameterX", "2");
1126  dol_syslog(get_class($this)."::add_contact ".$this->error, LOG_ERR);
1127  return -2;
1128  }
1129 
1130  $id_type_contact = 0;
1131  if (is_numeric($type_contact)) {
1132  $id_type_contact = $type_contact;
1133  } else {
1134  // We look for id type_contact
1135  $sql = "SELECT tc.rowid";
1136  $sql .= " FROM ".$this->db->prefix()."c_type_contact as tc";
1137  $sql .= " WHERE tc.element='".$this->db->escape($this->element)."'";
1138  $sql .= " AND tc.source='".$this->db->escape($source)."'";
1139  $sql .= " AND tc.code='".$this->db->escape($type_contact)."' AND tc.active=1";
1140  //print $sql;
1141  $resql = $this->db->query($sql);
1142  if ($resql) {
1143  $obj = $this->db->fetch_object($resql);
1144  if ($obj) {
1145  $id_type_contact = $obj->rowid;
1146  }
1147  }
1148  }
1149 
1150  if ($id_type_contact == 0) {
1151  $this->error = 'CODE_NOT_VALID_FOR_THIS_ELEMENT';
1152  dol_syslog("CODE_NOT_VALID_FOR_THIS_ELEMENT: Code type of contact '".$type_contact."' does not exists or is not active for element ".$this->element.", we can ignore it");
1153  return -3;
1154  }
1155 
1156  $datecreate = dol_now();
1157 
1158  // Socpeople must have already been added by some trigger, then we have to check it to avoid DB_ERROR_RECORD_ALREADY_EXISTS error
1159  $TListeContacts = $this->liste_contact(-1, $source);
1160  $already_added = false;
1161  if (is_array($TListeContacts) && !empty($TListeContacts)) {
1162  foreach ($TListeContacts as $array_contact) {
1163  if ($array_contact['status'] == 4 && $array_contact['id'] == $fk_socpeople && $array_contact['fk_c_type_contact'] == $id_type_contact) {
1164  $already_added = true;
1165  break;
1166  }
1167  }
1168  }
1169 
1170  if (!$already_added) {
1171  $this->db->begin();
1172 
1173  // Insert into database
1174  $sql = "INSERT INTO ".$this->db->prefix()."element_contact";
1175  $sql .= " (element_id, fk_socpeople, datecreate, statut, fk_c_type_contact) ";
1176  $sql .= " VALUES (".$this->id.", ".((int) $fk_socpeople)." , ";
1177  $sql .= "'".$this->db->idate($datecreate)."'";
1178  $sql .= ", 4, ".((int) $id_type_contact);
1179  $sql .= ")";
1180 
1181  $resql = $this->db->query($sql);
1182  if ($resql) {
1183  if (!$notrigger) {
1184  $result = $this->call_trigger(strtoupper($this->element).'_ADD_CONTACT', $user);
1185  if ($result < 0) {
1186  $this->db->rollback();
1187  return -1;
1188  }
1189  }
1190 
1191  $this->db->commit();
1192  return 1;
1193  } else {
1194  if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
1195  $this->error = $this->db->errno();
1196  $this->db->rollback();
1197  return -2;
1198  } else {
1199  $this->error = $this->db->lasterror();
1200  $this->db->rollback();
1201  return -1;
1202  }
1203  }
1204  } else {
1205  return 0;
1206  }
1207  }
1208 
1209  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1217  public function copy_linked_contact($objFrom, $source = 'internal')
1218  {
1219  // phpcs:enable
1220  $contacts = $objFrom->liste_contact(-1, $source);
1221  foreach ($contacts as $contact) {
1222  if ($this->add_contact($contact['id'], $contact['fk_c_type_contact'], $contact['source']) < 0) {
1223  return -1;
1224  }
1225  }
1226  return 1;
1227  }
1228 
1229  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1239  public function update_contact($rowid, $statut, $type_contact_id = 0, $fk_socpeople = 0)
1240  {
1241  // phpcs:enable
1242  // Insert into database
1243  $sql = "UPDATE ".$this->db->prefix()."element_contact set";
1244  $sql .= " statut = ".$statut;
1245  if ($type_contact_id) {
1246  $sql .= ", fk_c_type_contact = ".((int) $type_contact_id);
1247  }
1248  if ($fk_socpeople) {
1249  $sql .= ", fk_socpeople = ".((int) $fk_socpeople);
1250  }
1251  $sql .= " where rowid = ".((int) $rowid);
1252  $resql = $this->db->query($sql);
1253  if ($resql) {
1254  return 0;
1255  } else {
1256  $this->error = $this->db->lasterror();
1257  return -1;
1258  }
1259  }
1260 
1261  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1269  public function delete_contact($rowid, $notrigger = 0)
1270  {
1271  // phpcs:enable
1272  global $user;
1273 
1274 
1275  $this->db->begin();
1276 
1277  $sql = "DELETE FROM ".$this->db->prefix()."element_contact";
1278  $sql .= " WHERE rowid = ".((int) $rowid);
1279 
1280  dol_syslog(get_class($this)."::delete_contact", LOG_DEBUG);
1281  if ($this->db->query($sql)) {
1282  if (!$notrigger) {
1283  $result = $this->call_trigger(strtoupper($this->element).'_DELETE_CONTACT', $user);
1284  if ($result < 0) {
1285  $this->db->rollback();
1286  return -1;
1287  }
1288  }
1289 
1290  $this->db->commit();
1291  return 1;
1292  } else {
1293  $this->error = $this->db->lasterror();
1294  $this->db->rollback();
1295  return -1;
1296  }
1297  }
1298 
1299  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1307  public function delete_linked_contact($source = '', $code = '')
1308  {
1309  // phpcs:enable
1310  $listId = '';
1311  $temp = array();
1312  $typeContact = $this->liste_type_contact($source, '', 0, 0, $code);
1313 
1314  if (!empty($typeContact)) {
1315  foreach ($typeContact as $key => $value) {
1316  array_push($temp, $key);
1317  }
1318  $listId = implode(",", $temp);
1319  }
1320 
1321  $sql = "DELETE FROM ".$this->db->prefix()."element_contact";
1322  $sql .= " WHERE element_id = ".((int) $this->id);
1323  if (!empty($listId)) {
1324  $sql .= " AND fk_c_type_contact IN (".$this->db->sanitize($listId).")";
1325  }
1326 
1327  dol_syslog(get_class($this)."::delete_linked_contact", LOG_DEBUG);
1328  if ($this->db->query($sql)) {
1329  return 1;
1330  } else {
1331  $this->error = $this->db->lasterror();
1332  return -1;
1333  }
1334  }
1335 
1336  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1346  public function liste_contact($status = -1, $source = 'external', $list = 0, $code = '')
1347  {
1348  // phpcs:enable
1349  global $langs;
1350 
1351  $tab = array();
1352 
1353  $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
1354  if ($source == 'internal') {
1355  $sql .= ", '-1' as socid, t.statut as statuscontact, t.login, t.photo";
1356  }
1357  if ($source == 'external' || $source == 'thirdparty') {
1358  $sql .= ", t.fk_soc as socid, t.statut as statuscontact";
1359  }
1360  $sql .= ", t.civility as civility, t.lastname as lastname, t.firstname, t.email";
1361  $sql .= ", tc.source, tc.element, tc.code, tc.libelle";
1362  $sql .= " FROM ".$this->db->prefix()."c_type_contact tc";
1363  $sql .= ", ".$this->db->prefix()."element_contact ec";
1364  if ($source == 'internal') {
1365  $sql .= " LEFT JOIN ".$this->db->prefix()."user t on ec.fk_socpeople = t.rowid";
1366  }
1367  if ($source == 'external' || $source == 'thirdparty') {
1368  $sql .= " LEFT JOIN ".$this->db->prefix()."socpeople t on ec.fk_socpeople = t.rowid";
1369  }
1370  $sql .= " WHERE ec.element_id = ".((int) $this->id);
1371  $sql .= " AND ec.fk_c_type_contact = tc.rowid";
1372  $sql .= " AND tc.element = '".$this->db->escape($this->element)."'";
1373  if ($code) {
1374  $sql .= " AND tc.code = '".$this->db->escape($code)."'";
1375  }
1376  if ($source == 'internal') {
1377  $sql .= " AND tc.source = 'internal'";
1378  }
1379  if ($source == 'external' || $source == 'thirdparty') {
1380  $sql .= " AND tc.source = 'external'";
1381  }
1382  $sql .= " AND tc.active=1";
1383  if ($status >= 0) {
1384  $sql .= " AND ec.statut = ".((int) $status);
1385  }
1386  $sql .= " ORDER BY t.lastname ASC";
1387 
1388  dol_syslog(get_class($this)."::liste_contact", LOG_DEBUG);
1389  $resql = $this->db->query($sql);
1390  if ($resql) {
1391  $num = $this->db->num_rows($resql);
1392  $i = 0;
1393  while ($i < $num) {
1394  $obj = $this->db->fetch_object($resql);
1395 
1396  if (!$list) {
1397  $transkey = "TypeContact_".$obj->element."_".$obj->source."_".$obj->code;
1398  $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle);
1399  $tab[$i] = array(
1400  'source' => $obj->source,
1401  'socid' => $obj->socid,
1402  'id' => $obj->id,
1403  'nom' => $obj->lastname, // For backward compatibility
1404  'civility' => $obj->civility,
1405  'lastname' => $obj->lastname,
1406  'firstname' => $obj->firstname,
1407  'email'=>$obj->email,
1408  'login'=> (empty($obj->login) ? '' : $obj->login),
1409  'photo' => (empty($obj->photo) ? '' : $obj->photo),
1410  'statuscontact' => $obj->statuscontact,
1411  'rowid' => $obj->rowid,
1412  'code' => $obj->code,
1413  'libelle' => $libelle_type,
1414  'status' => $obj->statuslink,
1415  'fk_c_type_contact' => $obj->fk_c_type_contact
1416  );
1417  } else {
1418  $tab[$i] = $obj->id;
1419  }
1420 
1421  $i++;
1422  }
1423 
1424  return $tab;
1425  } else {
1426  $this->error = $this->db->lasterror();
1427  dol_print_error($this->db);
1428  return -1;
1429  }
1430  }
1431 
1432 
1439  public function swapContactStatus($rowid)
1440  {
1441  $sql = "SELECT ec.datecreate, ec.statut, ec.fk_socpeople, ec.fk_c_type_contact,";
1442  $sql .= " tc.code, tc.libelle";
1443  $sql .= " FROM (".$this->db->prefix()."element_contact as ec, ".$this->db->prefix()."c_type_contact as tc)";
1444  $sql .= " WHERE ec.rowid =".((int) $rowid);
1445  $sql .= " AND ec.fk_c_type_contact=tc.rowid";
1446  $sql .= " AND tc.element = '".$this->db->escape($this->element)."'";
1447 
1448  dol_syslog(get_class($this)."::swapContactStatus", LOG_DEBUG);
1449  $resql = $this->db->query($sql);
1450  if ($resql) {
1451  $obj = $this->db->fetch_object($resql);
1452  $newstatut = ($obj->statut == 4) ? 5 : 4;
1453  $result = $this->update_contact($rowid, $newstatut);
1454  $this->db->free($resql);
1455  return $result;
1456  } else {
1457  $this->error = $this->db->error();
1458  dol_print_error($this->db);
1459  return -1;
1460  }
1461  }
1462 
1463  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1474  public function liste_type_contact($source = 'internal', $order = 'position', $option = 0, $activeonly = 0, $code = '')
1475  {
1476  // phpcs:enable
1477  global $langs;
1478 
1479  if (empty($order)) {
1480  $order = 'position';
1481  }
1482  if ($order == 'position') {
1483  $order .= ',code';
1484  }
1485 
1486  $tab = array();
1487  $sql = "SELECT DISTINCT tc.rowid, tc.code, tc.libelle, tc.position";
1488  $sql .= " FROM ".$this->db->prefix()."c_type_contact as tc";
1489  $sql .= " WHERE tc.element='".$this->db->escape($this->element)."'";
1490  if ($activeonly == 1) {
1491  $sql .= " AND tc.active=1"; // only the active types
1492  }
1493  if (!empty($source) && $source != 'all') {
1494  $sql .= " AND tc.source='".$this->db->escape($source)."'";
1495  }
1496  if (!empty($code)) {
1497  $sql .= " AND tc.code='".$this->db->escape($code)."'";
1498  }
1499  $sql .= $this->db->order($order, 'ASC');
1500 
1501  //print "sql=".$sql;
1502  $resql = $this->db->query($sql);
1503  if ($resql) {
1504  $num = $this->db->num_rows($resql);
1505  $i = 0;
1506  while ($i < $num) {
1507  $obj = $this->db->fetch_object($resql);
1508 
1509  $transkey = "TypeContact_".$this->element."_".$source."_".$obj->code;
1510  $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle);
1511  if (empty($option)) {
1512  $tab[$obj->rowid] = $libelle_type;
1513  } else {
1514  $tab[$obj->code] = $libelle_type;
1515  }
1516  $i++;
1517  }
1518  return $tab;
1519  } else {
1520  $this->error = $this->db->lasterror();
1521  //dol_print_error($this->db);
1522  return null;
1523  }
1524  }
1525 
1526  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1538  public function listeTypeContacts($source = 'internal', $option = 0, $activeonly = 0, $code = '', $element = '', $excludeelement = '')
1539  {
1540  // phpcs:enable
1541  global $langs, $conf;
1542 
1543  $langs->loadLangs(array('bills', 'contracts', 'interventions', 'orders', 'projects', 'propal', 'ticket', 'agenda'));
1544 
1545  $tab = array();
1546 
1547  $sql = "SELECT DISTINCT tc.rowid, tc.code, tc.libelle, tc.position, tc.element";
1548  $sql .= " FROM ".$this->db->prefix()."c_type_contact as tc";
1549 
1550  $sqlWhere = array();
1551  if (!empty($element)) {
1552  $sqlWhere[] = " tc.element='".$this->db->escape($element)."'";
1553  }
1554  if (!empty($excludeelement)) {
1555  $sqlWhere[] = " tc.element <> '".$this->db->escape($excludeelement)."'";
1556  }
1557 
1558  if ($activeonly == 1) {
1559  $sqlWhere[] = " tc.active=1"; // only the active types
1560  }
1561 
1562  if (!empty($source) && $source != 'all') {
1563  $sqlWhere[] = " tc.source='".$this->db->escape($source)."'";
1564  }
1565 
1566  if (!empty($code)) {
1567  $sqlWhere[] = " tc.code='".$this->db->escape($code)."'";
1568  }
1569 
1570  if (count($sqlWhere) > 0) {
1571  $sql .= " WHERE ".implode(' AND ', $sqlWhere);
1572  }
1573 
1574  $sql .= $this->db->order('tc.element, tc.position', 'ASC');
1575 
1576  dol_syslog(__METHOD__, LOG_DEBUG);
1577  $resql = $this->db->query($sql);
1578  if ($resql) {
1579  $num = $this->db->num_rows($resql);
1580  if ($num > 0) {
1581  $langs->loadLangs(array("propal", "orders", "bills", "suppliers", "contracts", "supplier_proposal"));
1582 
1583  while ($obj = $this->db->fetch_object($resql)) {
1584  $modulename = $obj->element;
1585  if (strpos($obj->element, 'project') !== false) {
1586  $modulename = 'projet';
1587  } elseif ($obj->element == 'contrat') {
1588  $element = 'contract';
1589  } elseif ($obj->element == 'action') {
1590  $modulename = 'agenda';
1591  } elseif (strpos($obj->element, 'supplier') !== false && $obj->element != 'supplier_proposal') {
1592  $modulename = 'fournisseur';
1593  } elseif (strpos($obj->element, 'supplier') !== false && $obj->element != 'supplier_proposal') {
1594  $modulename = 'fournisseur';
1595  }
1596  if (!empty($conf->{$modulename}->enabled)) {
1597  $libelle_element = $langs->trans('ContactDefault_'.$obj->element);
1598  $tmpelement = $obj->element;
1599  $transkey = "TypeContact_".$tmpelement."_".$source."_".$obj->code;
1600  $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle);
1601  if (empty($option)) {
1602  $tab[$obj->rowid] = $libelle_element.' - '.$libelle_type;
1603  } else {
1604  $tab[$obj->rowid] = $libelle_element.' - '.$libelle_type;
1605  }
1606  }
1607  }
1608  }
1609  return $tab;
1610  } else {
1611  $this->error = $this->db->lasterror();
1612  return null;
1613  }
1614  }
1615 
1627  public function getIdContact($source, $code, $status = 0)
1628  {
1629  global $conf;
1630 
1631  $result = array();
1632  $i = 0;
1633  //cas particulier pour les expeditions
1634  if ($this->element == 'shipping' && $this->origin_id != 0) {
1635  $id = $this->origin_id;
1636  $element = 'commande';
1637  } elseif ($this->element == 'reception' && $this->origin_id != 0) {
1638  $id = $this->origin_id;
1639  $element = 'order_supplier';
1640  } else {
1641  $id = $this->id;
1642  $element = $this->element;
1643  }
1644 
1645  $sql = "SELECT ec.fk_socpeople";
1646  $sql .= " FROM ".$this->db->prefix()."element_contact as ec,";
1647  if ($source == 'internal') {
1648  $sql .= " ".$this->db->prefix()."user as c,";
1649  }
1650  if ($source == 'external') {
1651  $sql .= " ".$this->db->prefix()."socpeople as c,";
1652  }
1653  $sql .= " ".$this->db->prefix()."c_type_contact as tc";
1654  $sql .= " WHERE ec.element_id = ".((int) $id);
1655  $sql .= " AND ec.fk_socpeople = c.rowid";
1656  if ($source == 'internal') {
1657  $sql .= " AND c.entity IN (".getEntity('user').")";
1658  }
1659  if ($source == 'external') {
1660  $sql .= " AND c.entity IN (".getEntity('societe').")";
1661  }
1662  $sql .= " AND ec.fk_c_type_contact = tc.rowid";
1663  $sql .= " AND tc.element = '".$this->db->escape($element)."'";
1664  $sql .= " AND tc.source = '".$this->db->escape($source)."'";
1665  if ($code) {
1666  $sql .= " AND tc.code = '".$this->db->escape($code)."'";
1667  }
1668  $sql .= " AND tc.active = 1";
1669  if ($status) {
1670  $sql .= " AND ec.statut = ".((int) $status);
1671  }
1672 
1673  dol_syslog(get_class($this)."::getIdContact", LOG_DEBUG);
1674  $resql = $this->db->query($sql);
1675  if ($resql) {
1676  while ($obj = $this->db->fetch_object($resql)) {
1677  $result[$i] = $obj->fk_socpeople;
1678  $i++;
1679  }
1680  } else {
1681  $this->error = $this->db->error();
1682  return null;
1683  }
1684 
1685  return $result;
1686  }
1687 
1688  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1695  public function fetch_contact($contactid = null)
1696  {
1697  // phpcs:enable
1698  if (empty($contactid)) {
1699  $contactid = $this->contact_id;
1700  }
1701 
1702  if (empty($contactid)) {
1703  return 0;
1704  }
1705 
1706  require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
1707  $contact = new Contact($this->db);
1708  $result = $contact->fetch($contactid);
1709  $this->contact = $contact;
1710  return $result;
1711  }
1712 
1713  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1720  public function fetch_thirdparty($force_thirdparty_id = 0)
1721  {
1722  // phpcs:enable
1723  global $conf;
1724 
1725  if (empty($this->socid) && empty($this->fk_soc) && empty($force_thirdparty_id)) {
1726  return 0;
1727  }
1728 
1729  require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
1730 
1731  $idtofetch = isset($this->socid) ? $this->socid : (isset($this->fk_soc) ? $this->fk_soc : 0);
1732  if ($force_thirdparty_id) {
1733  $idtofetch = $force_thirdparty_id;
1734  }
1735 
1736  if ($idtofetch) {
1737  $thirdparty = new Societe($this->db);
1738  $result = $thirdparty->fetch($idtofetch);
1739  if ($result<0) {
1740  $this->errors=array_merge($this->errors, $thirdparty->errors);
1741  }
1742  $this->thirdparty = $thirdparty;
1743 
1744  // Use first price level if level not defined for third party
1745  if (!empty($conf->global->PRODUIT_MULTIPRICES) && empty($this->thirdparty->price_level)) {
1746  $this->thirdparty->price_level = 1;
1747  }
1748 
1749  return $result;
1750  } else {
1751  return -1;
1752  }
1753  }
1754 
1755 
1763  public function fetchOneLike($ref)
1764  {
1765  if (!$this->table_ref_field) {
1766  return 0;
1767  }
1768 
1769  $sql = "SELECT rowid FROM ".$this->db->prefix().$this->table_element." WHERE ".$this->table_ref_field." LIKE '".$this->db->escape($ref)."' LIMIT 1";
1770 
1771  $query = $this->db->query($sql);
1772 
1773  if (!$this->db->num_rows($query)) {
1774  return 0;
1775  }
1776 
1777  $result = $this->db->fetch_object($query);
1778 
1779  return $this->fetch($result->rowid);
1780  }
1781 
1782  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1790  public function fetch_barcode()
1791  {
1792  // phpcs:enable
1793  global $conf;
1794 
1795  dol_syslog(get_class($this).'::fetch_barcode this->element='.$this->element.' this->barcode_type='.$this->barcode_type);
1796 
1797  $idtype = $this->barcode_type;
1798  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
1799  if ($this->element == 'product' && !empty($conf->global->PRODUIT_DEFAULT_BARCODE_TYPE)) {
1800  $idtype = $conf->global->PRODUIT_DEFAULT_BARCODE_TYPE;
1801  } elseif ($this->element == 'societe') {
1802  $idtype = $conf->global->GENBARCODE_BARCODETYPE_THIRDPARTY;
1803  } else {
1804  dol_syslog('Call fetch_barcode with barcode_type not defined and cant be guessed', LOG_WARNING);
1805  }
1806  }
1807 
1808  if ($idtype > 0) {
1809  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
1810  $sql = "SELECT rowid, code, libelle as label, coder";
1811  $sql .= " FROM ".$this->db->prefix()."c_barcode_type";
1812  $sql .= " WHERE rowid = ".((int) $idtype);
1813  dol_syslog(get_class($this).'::fetch_barcode', LOG_DEBUG);
1814  $resql = $this->db->query($sql);
1815  if ($resql) {
1816  $obj = $this->db->fetch_object($resql);
1817  $this->barcode_type = $obj->rowid;
1818  $this->barcode_type_code = $obj->code;
1819  $this->barcode_type_label = $obj->label;
1820  $this->barcode_type_coder = $obj->coder;
1821  return 1;
1822  } else {
1823  dol_print_error($this->db);
1824  return -1;
1825  }
1826  }
1827  }
1828  return 0;
1829  }
1830 
1831  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1837  public function fetch_project()
1838  {
1839  // phpcs:enable
1840  return $this->fetch_projet();
1841  }
1842 
1843  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1849  public function fetch_projet()
1850  {
1851  // phpcs:enable
1852  include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
1853 
1854  if (empty($this->fk_project) && !empty($this->fk_projet)) {
1855  $this->fk_project = $this->fk_projet; // For backward compatibility
1856  }
1857  if (empty($this->fk_project)) {
1858  return 0;
1859  }
1860 
1861  $project = new Project($this->db);
1862  $result = $project->fetch($this->fk_project);
1863 
1864  $this->projet = $project; // deprecated
1865  $this->project = $project;
1866  return $result;
1867  }
1868 
1869  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1875  public function fetch_product()
1876  {
1877  // phpcs:enable
1878  include_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
1879 
1880  if (empty($this->fk_product)) {
1881  return 0;
1882  }
1883 
1884  $product = new Product($this->db);
1885  $result = $product->fetch($this->fk_product);
1886 
1887  $this->product = $product;
1888  return $result;
1889  }
1890 
1891  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1898  public function fetch_user($userid)
1899  {
1900  // phpcs:enable
1901  $user = new User($this->db);
1902  $result = $user->fetch($userid);
1903  $this->user = $user;
1904  return $result;
1905  }
1906 
1907  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1913  public function fetch_origin()
1914  {
1915  // phpcs:enable
1916  if ($this->origin == 'shipping') {
1917  $this->origin = 'expedition';
1918  }
1919  if ($this->origin == 'delivery') {
1920  $this->origin = 'livraison';
1921  }
1922  if ($this->origin == 'order_supplier') {
1923  $this->origin = 'commandeFournisseur';
1924  }
1925 
1926  $origin = $this->origin;
1927 
1928  $classname = ucfirst($origin);
1929  $this->$origin = new $classname($this->db);
1930  $this->$origin->fetch($this->origin_id);
1931  }
1932 
1942  public function fetchObjectFrom($table, $field, $key, $element = null)
1943  {
1944  global $conf;
1945 
1946  $result = false;
1947 
1948  $sql = "SELECT rowid FROM ".$this->db->prefix().$table;
1949  $sql .= " WHERE ".$field." = '".$this->db->escape($key)."'";
1950  if (!empty($element)) {
1951  $sql .= " AND entity IN (".getEntity($element).")";
1952  } else {
1953  $sql .= " AND entity = ".((int) $conf->entity);
1954  }
1955 
1956  dol_syslog(get_class($this).'::fetchObjectFrom', LOG_DEBUG);
1957  $resql = $this->db->query($sql);
1958  if ($resql) {
1959  $row = $this->db->fetch_row($resql);
1960  // Test for avoid error -1
1961  if ($row[0] > 0) {
1962  $result = $this->fetch($row[0]);
1963  }
1964  }
1965 
1966  return $result;
1967  }
1968 
1977  public function getValueFrom($table, $id, $field)
1978  {
1979  $result = false;
1980  if (!empty($id) && !empty($field) && !empty($table)) {
1981  $sql = "SELECT ".$field." FROM ".$this->db->prefix().$table;
1982  $sql .= " WHERE rowid = ".((int) $id);
1983 
1984  dol_syslog(get_class($this).'::getValueFrom', LOG_DEBUG);
1985  $resql = $this->db->query($sql);
1986  if ($resql) {
1987  $row = $this->db->fetch_row($resql);
1988  $result = $row[0];
1989  }
1990  }
1991  return $result;
1992  }
1993 
2010  public function setValueFrom($field, $value, $table = '', $id = null, $format = '', $id_field = '', $fuser = null, $trigkey = '', $fk_user_field = 'fk_user_modif')
2011  {
2012  global $user, $langs, $conf;
2013 
2014  if (empty($table)) {
2015  $table = $this->table_element;
2016  }
2017  if (empty($id)) {
2018  $id = $this->id;
2019  }
2020  if (empty($format)) {
2021  $format = 'text';
2022  }
2023  if (empty($id_field)) {
2024  $id_field = 'rowid';
2025  }
2026 
2027  $error = 0;
2028 
2029  $this->db->begin();
2030 
2031  // Special case
2032  if ($table == 'product' && $field == 'note_private') {
2033  $field = 'note';
2034  }
2035  if (in_array($table, array('actioncomm', 'adherent', 'advtargetemailing', 'cronjob', 'establishment'))) {
2036  $fk_user_field = 'fk_user_mod';
2037  }
2038 
2039  $sql = "UPDATE ".$this->db->prefix().$table." SET ";
2040 
2041  if ($format == 'text') {
2042  $sql .= $field." = '".$this->db->escape($value)."'";
2043  } elseif ($format == 'int') {
2044  $sql .= $field." = ".((int) $value);
2045  } elseif ($format == 'date') {
2046  $sql .= $field." = ".($value ? "'".$this->db->idate($value)."'" : "null");
2047  }
2048 
2049  if ($fk_user_field) {
2050  if (!empty($fuser) && is_object($fuser)) {
2051  $sql .= ", ".$fk_user_field." = ".((int) $fuser->id);
2052  } elseif (empty($fuser) || $fuser != 'none') {
2053  $sql .= ", ".$fk_user_field." = ".((int) $user->id);
2054  }
2055  }
2056 
2057  $sql .= " WHERE ".$id_field." = ".((int) $id);
2058 
2059  dol_syslog(__METHOD__."", LOG_DEBUG);
2060  $resql = $this->db->query($sql);
2061  if ($resql) {
2062  if ($trigkey) {
2063  // call trigger with updated object values
2064  if (empty($this->fields) && method_exists($this, 'fetch')) {
2065  $result = $this->fetch($id);
2066  } else {
2067  $result = $this->fetchCommon($id);
2068  }
2069  if ($result >= 0) {
2070  $result = $this->call_trigger($trigkey, (!empty($fuser) && is_object($fuser)) ? $fuser : $user); // This may set this->errors
2071  }
2072  if ($result < 0) {
2073  $error++;
2074  }
2075  }
2076 
2077  if (!$error) {
2078  if (property_exists($this, $field)) {
2079  $this->$field = $value;
2080  }
2081  $this->db->commit();
2082  return 1;
2083  } else {
2084  $this->db->rollback();
2085  return -2;
2086  }
2087  } else {
2088  if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
2089  $this->error = 'DB_ERROR_RECORD_ALREADY_EXISTS';
2090  } else {
2091  $this->error = $this->db->lasterror();
2092  }
2093  $this->db->rollback();
2094  return -1;
2095  }
2096  }
2097 
2098  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2107  public function load_previous_next_ref($filter, $fieldid, $nodbprefix = 0)
2108  {
2109  // phpcs:enable
2110  global $conf, $user;
2111 
2112  if (!$this->table_element) {
2113  dol_print_error('', get_class($this)."::load_previous_next_ref was called on objet with property table_element not defined");
2114  return -1;
2115  }
2116  if ($fieldid == 'none') {
2117  return 1;
2118  }
2119 
2120  // For backward compatibility
2121  if ($this->table_element == 'facture_rec' && $fieldid == 'title') {
2122  $fieldid = 'titre';
2123  }
2124 
2125  // Security on socid
2126  $socid = 0;
2127  if ($user->socid > 0) {
2128  $socid = $user->socid;
2129  }
2130 
2131  // this->ismultientitymanaged contains
2132  // 0=No test on entity, 1=Test with field entity, 'field@table'=Test with link by field@table
2133  $aliastablesociete = 's';
2134  if ($this->element == 'societe') {
2135  $aliastablesociete = 'te'; // te as table_element
2136  }
2137  $restrictiononfksoc = empty($this->restrictiononfksoc) ? 0 : $this->restrictiononfksoc;
2138  $sql = "SELECT MAX(te.".$fieldid.")";
2139  $sql .= " FROM ".(empty($nodbprefix) ?$this->db->prefix():'').$this->table_element." as te";
2140  if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
2141  $sql .= ",".$this->db->prefix()."usergroup_user as ug";
2142  }
2143  if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2144  $tmparray = explode('@', $this->ismultientitymanaged);
2145  $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
2146  } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
2147  $sql .= ", ".$this->db->prefix()."societe as s"; // If we need to link to societe to limit select to socid
2148  } elseif ($restrictiononfksoc == 2 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
2149  $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
2150  }
2151  if ($restrictiononfksoc && empty($user->rights->societe->client->voir) && !$socid) {
2152  $sql .= " LEFT JOIN ".$this->db->prefix()."societe_commerciaux as sc ON ".$aliastablesociete.".rowid = sc.fk_soc";
2153  }
2154  $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)
2155  if ($restrictiononfksoc == 1 && empty($user->rights->societe->client->voir) && !$socid) {
2156  $sql .= " AND sc.fk_user = ".((int) $user->id);
2157  }
2158  if ($restrictiononfksoc == 2 && empty($user->rights->societe->client->voir) && !$socid) {
2159  $sql .= " AND (sc.fk_user = ".((int) $user->id).' OR te.fk_soc IS NULL)';
2160  }
2161  if (!empty($filter)) {
2162  if (!preg_match('/^\s*AND/i', $filter)) {
2163  $sql .= " AND "; // For backward compatibility
2164  }
2165  $sql .= $filter;
2166  }
2167  if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2168  $tmparray = explode('@', $this->ismultientitymanaged);
2169  $sql .= " AND te.".$tmparray[0]." = ".($tmparray[1] == "societe" ? "s" : "parenttable").".rowid"; // If we need to link to this table to limit select to entity
2170  } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
2171  $sql .= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to socid
2172  }
2173  if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
2174  if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
2175  if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
2176  $sql .= " AND te.entity IS NOT NULL"; // Show all users
2177  } else {
2178  $sql .= " AND ug.fk_user = te.rowid";
2179  $sql .= " AND ug.entity IN (".getEntity($this->element).")";
2180  }
2181  } else {
2182  $sql .= ' AND te.entity IN ('.getEntity($this->element).')';
2183  }
2184  }
2185  if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged) && $this->element != 'societe') {
2186  $tmparray = explode('@', $this->ismultientitymanaged);
2187  $sql .= ' AND parenttable.entity IN ('.getEntity($tmparray[1]).')';
2188  }
2189  if ($restrictiononfksoc == 1 && $socid && $this->element != 'societe') {
2190  $sql .= ' AND te.fk_soc = '.((int) $socid);
2191  }
2192  if ($restrictiononfksoc == 2 && $socid && $this->element != 'societe') {
2193  $sql .= ' AND (te.fk_soc = '.((int) $socid).' OR te.fk_soc IS NULL)';
2194  }
2195  if ($restrictiononfksoc && $socid && $this->element == 'societe') {
2196  $sql .= ' AND te.rowid = '.((int) $socid);
2197  }
2198  //print 'socid='.$socid.' restrictiononfksoc='.$restrictiononfksoc.' ismultientitymanaged = '.$this->ismultientitymanaged.' filter = '.$filter.' -> '.$sql."<br>";
2199 
2200  $result = $this->db->query($sql);
2201  if (!$result) {
2202  $this->error = $this->db->lasterror();
2203  return -1;
2204  }
2205  $row = $this->db->fetch_row($result);
2206  $this->ref_previous = $row[0];
2207 
2208  $sql = "SELECT MIN(te.".$fieldid.")";
2209  $sql .= " FROM ".(empty($nodbprefix) ?$this->db->prefix():'').$this->table_element." as te";
2210  if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
2211  $sql .= ",".$this->db->prefix()."usergroup_user as ug";
2212  }
2213  if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2214  $tmparray = explode('@', $this->ismultientitymanaged);
2215  $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
2216  } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
2217  $sql .= ", ".$this->db->prefix()."societe as s"; // If we need to link to societe to limit select to socid
2218  } elseif ($restrictiononfksoc == 2 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
2219  $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
2220  }
2221  if ($restrictiononfksoc && empty($user->rights->societe->client->voir) && !$socid) {
2222  $sql .= " LEFT JOIN ".$this->db->prefix()."societe_commerciaux as sc ON ".$aliastablesociete.".rowid = sc.fk_soc";
2223  }
2224  $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)
2225  if ($restrictiononfksoc == 1 && empty($user->rights->societe->client->voir) && !$socid) {
2226  $sql .= " AND sc.fk_user = ".((int) $user->id);
2227  }
2228  if ($restrictiononfksoc == 2 && empty($user->rights->societe->client->voir) && !$socid) {
2229  $sql .= " AND (sc.fk_user = ".((int) $user->id).' OR te.fk_soc IS NULL)';
2230  }
2231  if (!empty($filter)) {
2232  if (!preg_match('/^\s*AND/i', $filter)) {
2233  $sql .= " AND "; // For backward compatibility
2234  }
2235  $sql .= $filter;
2236  }
2237  if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2238  $tmparray = explode('@', $this->ismultientitymanaged);
2239  $sql .= " AND te.".$tmparray[0]." = ".($tmparray[1] == "societe" ? "s" : "parenttable").".rowid"; // If we need to link to this table to limit select to entity
2240  } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
2241  $sql .= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to socid
2242  }
2243  if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
2244  if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
2245  if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
2246  $sql .= " AND te.entity IS NOT NULL"; // Show all users
2247  } else {
2248  $sql .= " AND ug.fk_user = te.rowid";
2249  $sql .= " AND ug.entity IN (".getEntity($this->element).")";
2250  }
2251  } else {
2252  $sql .= ' AND te.entity IN ('.getEntity($this->element).')';
2253  }
2254  }
2255  if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged) && $this->element != 'societe') {
2256  $tmparray = explode('@', $this->ismultientitymanaged);
2257  $sql .= ' AND parenttable.entity IN ('.getEntity($tmparray[1]).')';
2258  }
2259  if ($restrictiononfksoc == 1 && $socid && $this->element != 'societe') {
2260  $sql .= ' AND te.fk_soc = '.((int) $socid);
2261  }
2262  if ($restrictiononfksoc == 2 && $socid && $this->element != 'societe') {
2263  $sql .= ' AND (te.fk_soc = '.((int) $socid).' OR te.fk_soc IS NULL)';
2264  }
2265  if ($restrictiononfksoc && $socid && $this->element == 'societe') {
2266  $sql .= ' AND te.rowid = '.((int) $socid);
2267  }
2268  //print 'socid='.$socid.' restrictiononfksoc='.$restrictiononfksoc.' ismultientitymanaged = '.$this->ismultientitymanaged.' filter = '.$filter.' -> '.$sql."<br>";
2269  // 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
2270 
2271  $result = $this->db->query($sql);
2272  if (!$result) {
2273  $this->error = $this->db->lasterror();
2274  return -2;
2275  }
2276  $row = $this->db->fetch_row($result);
2277  $this->ref_next = $row[0];
2278 
2279  return 1;
2280  }
2281 
2282 
2290  public function getListContactId($source = 'external')
2291  {
2292  $contactAlreadySelected = array();
2293  $tab = $this->liste_contact(-1, $source);
2294  $num = count($tab);
2295  $i = 0;
2296  while ($i < $num) {
2297  if ($source == 'thirdparty') {
2298  $contactAlreadySelected[$i] = $tab[$i]['socid'];
2299  } else {
2300  $contactAlreadySelected[$i] = $tab[$i]['id'];
2301  }
2302  $i++;
2303  }
2304  return $contactAlreadySelected;
2305  }
2306 
2307 
2315  public function setProject($projectid, $notrigger = 0)
2316  {
2317  global $user;
2318  $error = 0;
2319 
2320  if (!$this->table_element) {
2321  dol_syslog(get_class($this)."::setProject was called on objet with property table_element not defined", LOG_ERR);
2322  return -1;
2323  }
2324 
2325  $sql = "UPDATE ".$this->db->prefix().$this->table_element;
2326  if (!empty($this->fields['fk_project'])) { // Common case
2327  if ($projectid) {
2328  $sql .= " SET fk_project = ".((int) $projectid);
2329  } else {
2330  $sql .= " SET fk_project = NULL";
2331  }
2332  $sql .= ' WHERE rowid = '.((int) $this->id);
2333  } elseif ($this->table_element == 'actioncomm') { // Special case for actioncomm
2334  if ($projectid) {
2335  $sql .= " SET fk_project = ".((int) $projectid);
2336  } else {
2337  $sql .= " SET fk_project = NULL";
2338  }
2339  $sql .= ' WHERE id = '.((int) $this->id);
2340  } else // Special case for old architecture objects
2341  {
2342  if ($projectid) {
2343  $sql .= ' SET fk_projet = '.((int) $projectid);
2344  } else {
2345  $sql .= ' SET fk_projet = NULL';
2346  }
2347  $sql .= " WHERE rowid = ".((int) $this->id);
2348  }
2349 
2350  $this->db->begin();
2351 
2352  dol_syslog(get_class($this)."::setProject", LOG_DEBUG);
2353  if ($this->db->query($sql)) {
2354  $this->fk_project = ((int) $projectid);
2355  } else {
2356  dol_print_error($this->db);
2357  $error++;
2358  }
2359 
2360  // Triggers
2361  if (!$error && !$notrigger) {
2362  // Call triggers
2363  $result = $this->call_trigger(strtoupper($this->element) . '_MODIFY', $user);
2364  if ($result < 0) {
2365  $error++;
2366  } //Do also here what you must do to rollback action if trigger fail
2367  // End call triggers
2368  }
2369 
2370  // Commit or rollback
2371  if ($error) {
2372  $this->db->rollback();
2373  return -1;
2374  } else {
2375  $this->db->commit();
2376  return 1;
2377  }
2378  }
2379 
2386  public function setPaymentMethods($id)
2387  {
2388  global $user;
2389 
2390  $error = 0; $notrigger = 0;
2391 
2392  dol_syslog(get_class($this).'::setPaymentMethods('.$id.')');
2393 
2394  if ($this->statut >= 0 || $this->element == 'societe') {
2395  // TODO uniformize field name
2396  $fieldname = 'fk_mode_reglement';
2397  if ($this->element == 'societe') {
2398  $fieldname = 'mode_reglement';
2399  }
2400  if (get_class($this) == 'Fournisseur') {
2401  $fieldname = 'mode_reglement_supplier';
2402  }
2403  if (get_class($this) == 'Tva') {
2404  $fieldname = 'fk_typepayment';
2405  }
2406  if (get_class($this) == 'Salary') {
2407  $fieldname = 'fk_typepayment';
2408  }
2409 
2410  $sql = "UPDATE ".$this->db->prefix().$this->table_element;
2411  $sql .= " SET ".$fieldname." = ".(($id > 0 || $id == '0') ? ((int) $id) : 'NULL');
2412  $sql .= ' WHERE rowid='.((int) $this->id);
2413 
2414  if ($this->db->query($sql)) {
2415  $this->mode_reglement_id = $id;
2416  // for supplier
2417  if (get_class($this) == 'Fournisseur') {
2418  $this->mode_reglement_supplier_id = $id;
2419  }
2420  // Triggers
2421  if (!$error && !$notrigger) {
2422  // Call triggers
2423  if (get_class($this) == 'Commande') {
2424  $result = $this->call_trigger('ORDER_MODIFY', $user);
2425  } else {
2426  $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $user);
2427  }
2428  if ($result < 0) {
2429  $error++;
2430  }
2431  // End call triggers
2432  }
2433  return 1;
2434  } else {
2435  dol_syslog(get_class($this).'::setPaymentMethods Error '.$this->db->error());
2436  $this->error = $this->db->error();
2437  return -1;
2438  }
2439  } else {
2440  dol_syslog(get_class($this).'::setPaymentMethods, status of the object is incompatible');
2441  $this->error = 'Status of the object is incompatible '.$this->statut;
2442  return -2;
2443  }
2444  }
2445 
2452  public function setMulticurrencyCode($code)
2453  {
2454  dol_syslog(get_class($this).'::setMulticurrencyCode('.$code.')');
2455  if ($this->statut >= 0 || $this->element == 'societe') {
2456  $fieldname = 'multicurrency_code';
2457 
2458  $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
2459  $sql .= " SET ".$fieldname." = '".$this->db->escape($code)."'";
2460  $sql .= ' WHERE rowid='.((int) $this->id);
2461 
2462  if ($this->db->query($sql)) {
2463  $this->multicurrency_code = $code;
2464 
2465  list($fk_multicurrency, $rate) = MultiCurrency::getIdAndTxFromCode($this->db, $code);
2466  if ($rate) {
2467  $this->setMulticurrencyRate($rate, 2);
2468  }
2469 
2470  return 1;
2471  } else {
2472  dol_syslog(get_class($this).'::setMulticurrencyCode Error '.$sql.' - '.$this->db->error());
2473  $this->error = $this->db->error();
2474  return -1;
2475  }
2476  } else {
2477  dol_syslog(get_class($this).'::setMulticurrencyCode, status of the object is incompatible');
2478  $this->error = 'Status of the object is incompatible '.$this->statut;
2479  return -2;
2480  }
2481  }
2482 
2490  public function setMulticurrencyRate($rate, $mode = 1)
2491  {
2492  dol_syslog(get_class($this).'::setMulticurrencyRate('.$rate.','.$mode.')');
2493  if ($this->statut >= 0 || $this->element == 'societe') {
2494  $fieldname = 'multicurrency_tx';
2495 
2496  $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
2497  $sql .= " SET ".$fieldname." = ".((float) $rate);
2498  $sql .= ' WHERE rowid='.((int) $this->id);
2499 
2500  if ($this->db->query($sql)) {
2501  $this->multicurrency_tx = $rate;
2502 
2503  // Update line price
2504  if (!empty($this->lines)) {
2505  foreach ($this->lines as &$line) {
2506  // Amounts in company currency will be recalculated
2507  if ($mode == 1) {
2508  $line->subprice = 0;
2509  }
2510 
2511  // Amounts in foreign currency will be recalculated
2512  if ($mode == 2) {
2513  $line->multicurrency_subprice = 0;
2514  }
2515 
2516  switch ($this->element) {
2517  case 'propal':
2518  $this->updateline(
2519  $line->id,
2520  $line->subprice,
2521  $line->qty,
2522  $line->remise_percent,
2523  $line->tva_tx,
2524  $line->localtax1_tx,
2525  $line->localtax2_tx,
2526  ($line->description ? $line->description : $line->desc),
2527  'HT',
2528  $line->info_bits,
2529  $line->special_code,
2530  $line->fk_parent_line,
2531  $line->skip_update_total,
2532  $line->fk_fournprice,
2533  $line->pa_ht,
2534  $line->label,
2535  $line->product_type,
2536  $line->date_start,
2537  $line->date_end,
2538  $line->array_options,
2539  $line->fk_unit,
2540  $line->multicurrency_subprice
2541  );
2542  break;
2543  case 'commande':
2544  $this->updateline(
2545  $line->id,
2546  ($line->description ? $line->description : $line->desc),
2547  $line->subprice,
2548  $line->qty,
2549  $line->remise_percent,
2550  $line->tva_tx,
2551  $line->localtax1_tx,
2552  $line->localtax2_tx,
2553  'HT',
2554  $line->info_bits,
2555  $line->date_start,
2556  $line->date_end,
2557  $line->product_type,
2558  $line->fk_parent_line,
2559  $line->skip_update_total,
2560  $line->fk_fournprice,
2561  $line->pa_ht,
2562  $line->label,
2563  $line->special_code,
2564  $line->array_options,
2565  $line->fk_unit,
2566  $line->multicurrency_subprice
2567  );
2568  break;
2569  case 'facture':
2570  $this->updateline(
2571  $line->id,
2572  ($line->description ? $line->description : $line->desc),
2573  $line->subprice,
2574  $line->qty,
2575  $line->remise_percent,
2576  $line->date_start,
2577  $line->date_end,
2578  $line->tva_tx,
2579  $line->localtax1_tx,
2580  $line->localtax2_tx,
2581  'HT',
2582  $line->info_bits,
2583  $line->product_type,
2584  $line->fk_parent_line,
2585  $line->skip_update_total,
2586  $line->fk_fournprice,
2587  $line->pa_ht,
2588  $line->label,
2589  $line->special_code,
2590  $line->array_options,
2591  $line->situation_percent,
2592  $line->fk_unit,
2593  $line->multicurrency_subprice
2594  );
2595  break;
2596  case 'supplier_proposal':
2597  $this->updateline(
2598  $line->id,
2599  $line->subprice,
2600  $line->qty,
2601  $line->remise_percent,
2602  $line->tva_tx,
2603  $line->localtax1_tx,
2604  $line->localtax2_tx,
2605  ($line->description ? $line->description : $line->desc),
2606  'HT',
2607  $line->info_bits,
2608  $line->special_code,
2609  $line->fk_parent_line,
2610  $line->skip_update_total,
2611  $line->fk_fournprice,
2612  $line->pa_ht,
2613  $line->label,
2614  $line->product_type,
2615  $line->array_options,
2616  $line->ref_fourn,
2617  $line->multicurrency_subprice
2618  );
2619  break;
2620  case 'order_supplier':
2621  $this->updateline(
2622  $line->id,
2623  ($line->description ? $line->description : $line->desc),
2624  $line->subprice,
2625  $line->qty,
2626  $line->remise_percent,
2627  $line->tva_tx,
2628  $line->localtax1_tx,
2629  $line->localtax2_tx,
2630  'HT',
2631  $line->info_bits,
2632  $line->product_type,
2633  false,
2634  $line->date_start,
2635  $line->date_end,
2636  $line->array_options,
2637  $line->fk_unit,
2638  $line->multicurrency_subprice,
2639  $line->ref_supplier
2640  );
2641  break;
2642  case 'invoice_supplier':
2643  $this->updateline(
2644  $line->id,
2645  ($line->description ? $line->description : $line->desc),
2646  $line->subprice,
2647  $line->tva_tx,
2648  $line->localtax1_tx,
2649  $line->localtax2_tx,
2650  $line->qty,
2651  0,
2652  'HT',
2653  $line->info_bits,
2654  $line->product_type,
2655  $line->remise_percent,
2656  false,
2657  $line->date_start,
2658  $line->date_end,
2659  $line->array_options,
2660  $line->fk_unit,
2661  $line->multicurrency_subprice,
2662  $line->ref_supplier
2663  );
2664  break;
2665  default:
2666  dol_syslog(get_class($this).'::setMulticurrencyRate no updateline defined', LOG_DEBUG);
2667  break;
2668  }
2669  }
2670  }
2671 
2672  return 1;
2673  } else {
2674  dol_syslog(get_class($this).'::setMulticurrencyRate Error '.$sql.' - '.$this->db->error());
2675  $this->error = $this->db->error();
2676  return -1;
2677  }
2678  } else {
2679  dol_syslog(get_class($this).'::setMulticurrencyRate, status of the object is incompatible');
2680  $this->error = 'Status of the object is incompatible '.$this->statut;
2681  return -2;
2682  }
2683  }
2684 
2692  public function setPaymentTerms($id, $deposit_percent = null)
2693  {
2694  dol_syslog(get_class($this).'::setPaymentTerms('.$id.', '.var_export($deposit_percent, true).')');
2695  if ($this->statut >= 0 || $this->element == 'societe') {
2696  // TODO uniformize field name
2697  $fieldname = 'fk_cond_reglement';
2698  if ($this->element == 'societe') {
2699  $fieldname = 'cond_reglement';
2700  }
2701  if (get_class($this) == 'Fournisseur') {
2702  $fieldname = 'cond_reglement_supplier';
2703  }
2704 
2705  if (empty($deposit_percent) || $deposit_percent < 0) {
2706  $deposit_percent = getDictionaryValue('c_payment_term', 'deposit_percent', $id);
2707  }
2708 
2709  if ($deposit_percent > 100) {
2710  $deposit_percent = 100;
2711  }
2712 
2713  $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
2714  $sql .= " SET ".$fieldname." = ".(($id > 0 || $id == '0') ? ((int) $id) : 'NULL');
2715  if (in_array($this->table_element, array('propal', 'commande'))) {
2716  $sql .= " , deposit_percent = " . (empty($deposit_percent) ? 'NULL' : "'".$this->db->escape($deposit_percent)."'");
2717  }
2718  $sql .= ' WHERE rowid='.((int) $this->id);
2719 
2720  if ($this->db->query($sql)) {
2721  $this->cond_reglement_id = $id;
2722  // for supplier
2723  if (get_class($this) == 'Fournisseur') {
2724  $this->cond_reglement_supplier_id = $id;
2725  }
2726  $this->cond_reglement = $id; // for compatibility
2727  $this->deposit_percent = $deposit_percent;
2728  return 1;
2729  } else {
2730  dol_syslog(get_class($this).'::setPaymentTerms Error '.$sql.' - '.$this->db->error());
2731  $this->error = $this->db->error();
2732  return -1;
2733  }
2734  } else {
2735  dol_syslog(get_class($this).'::setPaymentTerms, status of the object is incompatible');
2736  $this->error = 'Status of the object is incompatible '.$this->statut;
2737  return -2;
2738  }
2739  }
2740 
2747  public function setTransportMode($id)
2748  {
2749  dol_syslog(get_class($this).'::setTransportMode('.$id.')');
2750  if ($this->statut >= 0 || $this->element == 'societe') {
2751  $fieldname = 'fk_transport_mode';
2752  if ($this->element == 'societe') {
2753  $fieldname = 'transport_mode';
2754  }
2755  if (get_class($this) == 'Fournisseur') {
2756  $fieldname = 'transport_mode_supplier';
2757  }
2758 
2759  $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
2760  $sql .= " SET ".$fieldname." = ".(($id > 0 || $id == '0') ? ((int) $id) : 'NULL');
2761  $sql .= ' WHERE rowid='.((int) $this->id);
2762 
2763  if ($this->db->query($sql)) {
2764  $this->transport_mode_id = $id;
2765  // for supplier
2766  if (get_class($this) == 'Fournisseur') {
2767  $this->transport_mode_supplier_id = $id;
2768  }
2769  return 1;
2770  } else {
2771  dol_syslog(get_class($this).'::setTransportMode Error '.$sql.' - '.$this->db->error());
2772  $this->error = $this->db->error();
2773  return -1;
2774  }
2775  } else {
2776  dol_syslog(get_class($this).'::setTransportMode, status of the object is incompatible');
2777  $this->error = 'Status of the object is incompatible '.$this->statut;
2778  return -2;
2779  }
2780  }
2781 
2788  public function setRetainedWarrantyPaymentTerms($id)
2789  {
2790  dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms('.$id.')');
2791  if ($this->statut >= 0 || $this->element == 'societe') {
2792  $fieldname = 'retained_warranty_fk_cond_reglement';
2793 
2794  $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
2795  $sql .= " SET ".$fieldname." = ".((int) $id);
2796  $sql .= ' WHERE rowid='.((int) $this->id);
2797 
2798  if ($this->db->query($sql)) {
2799  $this->retained_warranty_fk_cond_reglement = $id;
2800  return 1;
2801  } else {
2802  dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms Error '.$sql.' - '.$this->db->error());
2803  $this->error = $this->db->error();
2804  return -1;
2805  }
2806  } else {
2807  dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms, status of the object is incompatible');
2808  $this->error = 'Status of the object is incompatible '.$this->statut;
2809  return -2;
2810  }
2811  }
2812 
2820  public function setDeliveryAddress($id)
2821  {
2822  $fieldname = 'fk_delivery_address';
2823  if ($this->element == 'delivery' || $this->element == 'shipping') {
2824  $fieldname = 'fk_address';
2825  }
2826 
2827  $sql = "UPDATE ".$this->db->prefix().$this->table_element." SET ".$fieldname." = ".((int) $id);
2828  $sql .= " WHERE rowid = ".((int) $this->id)." AND fk_statut = 0";
2829 
2830  if ($this->db->query($sql)) {
2831  $this->fk_delivery_address = $id;
2832  return 1;
2833  } else {
2834  $this->error = $this->db->error();
2835  dol_syslog(get_class($this).'::setDeliveryAddress Error '.$this->error);
2836  return -1;
2837  }
2838  }
2839 
2840 
2850  public function setShippingMethod($shipping_method_id, $notrigger = false, $userused = null)
2851  {
2852  global $user;
2853 
2854  if (empty($userused)) {
2855  $userused = $user;
2856  }
2857 
2858  $error = 0;
2859 
2860  if (!$this->table_element) {
2861  dol_syslog(get_class($this)."::setShippingMethod was called on objet with property table_element not defined", LOG_ERR);
2862  return -1;
2863  }
2864 
2865  $this->db->begin();
2866 
2867  if ($shipping_method_id < 0) {
2868  $shipping_method_id = 'NULL';
2869  }
2870  dol_syslog(get_class($this).'::setShippingMethod('.$shipping_method_id.')');
2871 
2872  $sql = "UPDATE ".$this->db->prefix().$this->table_element;
2873  $sql .= " SET fk_shipping_method = ".((int) $shipping_method_id);
2874  $sql .= " WHERE rowid=".((int) $this->id);
2875  $resql = $this->db->query($sql);
2876  if (!$resql) {
2877  dol_syslog(get_class($this).'::setShippingMethod Error ', LOG_DEBUG);
2878  $this->error = $this->db->lasterror();
2879  $error++;
2880  } else {
2881  if (!$notrigger) {
2882  // Call trigger
2883  $this->context = array('shippingmethodupdate'=>1);
2884  $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $userused);
2885  if ($result < 0) {
2886  $error++;
2887  }
2888  // End call trigger
2889  }
2890  }
2891  if ($error) {
2892  $this->db->rollback();
2893  return -1;
2894  } else {
2895  $this->shipping_method_id = ($shipping_method_id == 'NULL') ?null:$shipping_method_id;
2896  $this->db->commit();
2897  return 1;
2898  }
2899  }
2900 
2901 
2908  public function setWarehouse($warehouse_id)
2909  {
2910  if (!$this->table_element) {
2911  dol_syslog(get_class($this)."::setWarehouse was called on objet with property table_element not defined", LOG_ERR);
2912  return -1;
2913  }
2914  if ($warehouse_id < 0) {
2915  $warehouse_id = 'NULL';
2916  }
2917  dol_syslog(get_class($this).'::setWarehouse('.$warehouse_id.')');
2918 
2919  $sql = "UPDATE ".$this->db->prefix().$this->table_element;
2920  $sql .= " SET fk_warehouse = ".((int) $warehouse_id);
2921  $sql .= " WHERE rowid=".((int) $this->id);
2922 
2923  if ($this->db->query($sql)) {
2924  $this->warehouse_id = ($warehouse_id == 'NULL') ?null:$warehouse_id;
2925  return 1;
2926  } else {
2927  dol_syslog(get_class($this).'::setWarehouse Error ', LOG_DEBUG);
2928  $this->error = $this->db->error();
2929  return 0;
2930  }
2931  }
2932 
2933 
2941  public function setDocModel($user, $modelpdf)
2942  {
2943  if (!$this->table_element) {
2944  dol_syslog(get_class($this)."::setDocModel was called on objet with property table_element not defined", LOG_ERR);
2945  return -1;
2946  }
2947 
2948  $newmodelpdf = dol_trunc($modelpdf, 255);
2949 
2950  $sql = "UPDATE ".$this->db->prefix().$this->table_element;
2951  $sql .= " SET model_pdf = '".$this->db->escape($newmodelpdf)."'";
2952  $sql .= " WHERE rowid = ".((int) $this->id);
2953 
2954  dol_syslog(get_class($this)."::setDocModel", LOG_DEBUG);
2955  $resql = $this->db->query($sql);
2956  if ($resql) {
2957  $this->model_pdf = $modelpdf;
2958  $this->modelpdf = $modelpdf; // For bakward compatibility
2959  return 1;
2960  } else {
2961  dol_print_error($this->db);
2962  return 0;
2963  }
2964  }
2965 
2966 
2975  public function setBankAccount($fk_account, $notrigger = false, $userused = null)
2976  {
2977  global $user;
2978 
2979  if (empty($userused)) {
2980  $userused = $user;
2981  }
2982 
2983  $error = 0;
2984 
2985  if (!$this->table_element) {
2986  dol_syslog(get_class($this)."::setBankAccount was called on objet with property table_element not defined", LOG_ERR);
2987  return -1;
2988  }
2989  $this->db->begin();
2990 
2991  if ($fk_account < 0) {
2992  $fk_account = 'NULL';
2993  }
2994  dol_syslog(get_class($this).'::setBankAccount('.$fk_account.')');
2995 
2996  $sql = "UPDATE ".$this->db->prefix().$this->table_element;
2997  $sql .= " SET fk_account = ".((int) $fk_account);
2998  $sql .= " WHERE rowid=".((int) $this->id);
2999 
3000  $resql = $this->db->query($sql);
3001  if (!$resql) {
3002  dol_syslog(get_class($this).'::setBankAccount Error '.$sql.' - '.$this->db->error());
3003  $this->error = $this->db->lasterror();
3004  $error++;
3005  } else {
3006  if (!$notrigger) {
3007  // Call trigger
3008  $this->context = array('bankaccountupdate'=>1);
3009  $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $userused);
3010  if ($result < 0) {
3011  $error++;
3012  }
3013  // End call trigger
3014  }
3015  }
3016  if ($error) {
3017  $this->db->rollback();
3018  return -1;
3019  } else {
3020  $this->fk_account = ($fk_account == 'NULL') ?null:$fk_account;
3021  $this->db->commit();
3022  return 1;
3023  }
3024  }
3025 
3026 
3027  // TODO: Move line related operations to CommonObjectLine?
3028 
3029  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3039  public function line_order($renum = false, $rowidorder = 'ASC', $fk_parent_line = true)
3040  {
3041  // phpcs:enable
3042  if (!$this->table_element_line) {
3043  dol_syslog(get_class($this)."::line_order was called on objet with property table_element_line not defined", LOG_ERR);
3044  return -1;
3045  }
3046  if (!$this->fk_element) {
3047  dol_syslog(get_class($this)."::line_order was called on objet with property fk_element not defined", LOG_ERR);
3048  return -1;
3049  }
3050 
3051  $fieldposition = 'rang'; // @todo Rename 'rang' into 'position'
3052  if (in_array($this->table_element_line, array('bom_bomline', 'ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
3053  $fieldposition = 'position';
3054  }
3055 
3056  // Count number of lines to reorder (according to choice $renum)
3057  $nl = 0;
3058  $sql = "SELECT count(rowid) FROM ".$this->db->prefix().$this->table_element_line;
3059  $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
3060  if (!$renum) {
3061  $sql .= " AND " . $fieldposition . " = 0";
3062  }
3063  if ($renum) {
3064  $sql .= " AND " . $fieldposition . " <> 0";
3065  }
3066 
3067  dol_syslog(get_class($this)."::line_order", LOG_DEBUG);
3068  $resql = $this->db->query($sql);
3069  if ($resql) {
3070  $row = $this->db->fetch_row($resql);
3071  $nl = $row[0];
3072  } else {
3073  dol_print_error($this->db);
3074  }
3075  if ($nl > 0) {
3076  // The goal of this part is to reorder all lines, with all children lines sharing the same counter that parents.
3077  $rows = array();
3078 
3079  // We first search all lines that are parent lines (for multilevel details lines)
3080  $sql = "SELECT rowid FROM ".$this->db->prefix().$this->table_element_line;
3081  $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
3082  if ($fk_parent_line) {
3083  $sql .= ' AND fk_parent_line IS NULL';
3084  }
3085  $sql .= " ORDER BY " . $fieldposition . " ASC, rowid " . $rowidorder;
3086 
3087  dol_syslog(get_class($this)."::line_order search all parent lines", LOG_DEBUG);
3088  $resql = $this->db->query($sql);
3089  if ($resql) {
3090  $i = 0;
3091  $num = $this->db->num_rows($resql);
3092  while ($i < $num) {
3093  $row = $this->db->fetch_row($resql);
3094  $rows[] = $row[0]; // Add parent line into array rows
3095  $childrens = $this->getChildrenOfLine($row[0]);
3096  if (!empty($childrens)) {
3097  foreach ($childrens as $child) {
3098  array_push($rows, $child);
3099  }
3100  }
3101  $i++;
3102  }
3103 
3104  // Now we set a new number for each lines (parent and children with children included into parent tree)
3105  if (!empty($rows)) {
3106  foreach ($rows as $key => $row) {
3107  $this->updateRangOfLine($row, ($key + 1));
3108  }
3109  }
3110  } else {
3111  dol_print_error($this->db);
3112  }
3113  }
3114  return 1;
3115  }
3116 
3124  public function getChildrenOfLine($id, $includealltree = 0)
3125  {
3126  $fieldposition = 'rang'; // @todo Rename 'rang' into 'position'
3127  if (in_array($this->table_element_line, array('bom_bomline', 'ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
3128  $fieldposition = 'position';
3129  }
3130 
3131  $rows = array();
3132 
3133  $sql = "SELECT rowid FROM ".$this->db->prefix().$this->table_element_line;
3134  $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
3135  $sql .= ' AND fk_parent_line = '.((int) $id);
3136  $sql .= " ORDER BY " . $fieldposition . " ASC";
3137 
3138  dol_syslog(get_class($this)."::getChildrenOfLine search children lines for line ".$id, LOG_DEBUG);
3139  $resql = $this->db->query($sql);
3140  if ($resql) {
3141  if ($this->db->num_rows($resql) > 0) {
3142  while ($row = $this->db->fetch_row($resql)) {
3143  $rows[] = $row[0];
3144  if (!empty($includealltree)) {
3145  $rows = array_merge($rows, $this->getChildrenOfLine($row[0]), $includealltree);
3146  }
3147  }
3148  }
3149  }
3150  return $rows;
3151  }
3152 
3153  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3161  public function line_up($rowid, $fk_parent_line = true)
3162  {
3163  // phpcs:enable
3164  $this->line_order(false, 'ASC', $fk_parent_line);
3165 
3166  // Get rang of line
3167  $rang = $this->getRangOfLine($rowid);
3168 
3169  // Update position of line
3170  $this->updateLineUp($rowid, $rang);
3171  }
3172 
3173  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3181  public function line_down($rowid, $fk_parent_line = true)
3182  {
3183  // phpcs:enable
3184  $this->line_order(false, 'ASC', $fk_parent_line);
3185 
3186  // Get rang of line
3187  $rang = $this->getRangOfLine($rowid);
3188 
3189  // Get max value for rang
3190  $max = $this->line_max();
3191 
3192  // Update position of line
3193  $this->updateLineDown($rowid, $rang, $max);
3194  }
3195 
3203  public function updateRangOfLine($rowid, $rang)
3204  {
3205  global $hookmanager;
3206  $fieldposition = 'rang'; // @todo Rename 'rang' into 'position'
3207  if (in_array($this->table_element_line, array('bom_bomline', 'ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
3208  $fieldposition = 'position';
3209  }
3210 
3211  $sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldposition." = ".((int) $rang);
3212  $sql .= ' WHERE rowid = '.((int) $rowid);
3213 
3214  dol_syslog(get_class($this)."::updateRangOfLine", LOG_DEBUG);
3215  if (!$this->db->query($sql)) {
3216  dol_print_error($this->db);
3217  return -1;
3218  } else {
3219  $parameters=array('rowid'=>$rowid, 'rang'=>$rang, 'fieldposition' => $fieldposition);
3220  $action='';
3221  $reshook = $hookmanager->executeHooks('afterRankOfLineUpdate', $parameters, $this, $action);
3222  return 1;
3223  }
3224  }
3225 
3226  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3233  public function line_ajaxorder($rows)
3234  {
3235  // phpcs:enable
3236  $num = count($rows);
3237  for ($i = 0; $i < $num; $i++) {
3238  $this->updateRangOfLine($rows[$i], ($i + 1));
3239  }
3240  }
3241 
3249  public function updateLineUp($rowid, $rang)
3250  {
3251  if ($rang > 1) {
3252  $fieldposition = 'rang';
3253  if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
3254  $fieldposition = 'position';
3255  }
3256 
3257  $sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldposition." = ".((int) $rang);
3258  $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
3259  $sql .= " AND " . $fieldposition . " = " . ((int) ($rang - 1));
3260  if ($this->db->query($sql)) {
3261  $sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldposition." = ".((int) ($rang - 1));
3262  $sql .= ' WHERE rowid = '.((int) $rowid);
3263  if (!$this->db->query($sql)) {
3264  dol_print_error($this->db);
3265  }
3266  } else {
3267  dol_print_error($this->db);
3268  }
3269  }
3270  }
3271 
3280  public function updateLineDown($rowid, $rang, $max)
3281  {
3282  if ($rang < $max) {
3283  $fieldposition = 'rang';
3284  if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
3285  $fieldposition = 'position';
3286  }
3287 
3288  $sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldposition." = ".((int) $rang);
3289  $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
3290  $sql .= " AND " . $fieldposition . " = " . ((int) ($rang + 1));
3291  if ($this->db->query($sql)) {
3292  $sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldposition." = ".((int) ($rang + 1));
3293  $sql .= ' WHERE rowid = '.((int) $rowid);
3294  if (!$this->db->query($sql)) {
3295  dol_print_error($this->db);
3296  }
3297  } else {
3298  dol_print_error($this->db);
3299  }
3300  }
3301  }
3302 
3309  public function getRangOfLine($rowid)
3310  {
3311  $fieldposition = 'rang';
3312  if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
3313  $fieldposition = 'position';
3314  }
3315 
3316  $sql = "SELECT " . $fieldposition . " FROM ".$this->db->prefix().$this->table_element_line;
3317  $sql .= " WHERE rowid = ".((int) $rowid);
3318 
3319  dol_syslog(get_class($this)."::getRangOfLine", LOG_DEBUG);
3320  $resql = $this->db->query($sql);
3321  if ($resql) {
3322  $row = $this->db->fetch_row($resql);
3323  return $row[0];
3324  }
3325  }
3326 
3333  public function getIdOfLine($rang)
3334  {
3335  $fieldposition = 'rang';
3336  if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
3337  $fieldposition = 'position';
3338  }
3339 
3340  $sql = "SELECT rowid FROM ".$this->db->prefix().$this->table_element_line;
3341  $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
3342  $sql .= " AND " . $fieldposition . " = ".((int) $rang);
3343  $resql = $this->db->query($sql);
3344  if ($resql) {
3345  $row = $this->db->fetch_row($resql);
3346  return $row[0];
3347  }
3348  }
3349 
3350  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3357  public function line_max($fk_parent_line = 0)
3358  {
3359  // phpcs:enable
3360  $positionfield = 'rang';
3361  if (in_array($this->table_element, array('bom_bom', 'product_attribute'))) {
3362  $positionfield = 'position';
3363  }
3364 
3365  // Search the last rang with fk_parent_line
3366  if ($fk_parent_line) {
3367  $sql = "SELECT max(".$positionfield.") FROM ".$this->db->prefix().$this->table_element_line;
3368  $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
3369  $sql .= " AND fk_parent_line = ".((int) $fk_parent_line);
3370 
3371  dol_syslog(get_class($this)."::line_max", LOG_DEBUG);
3372  $resql = $this->db->query($sql);
3373  if ($resql) {
3374  $row = $this->db->fetch_row($resql);
3375  if (!empty($row[0])) {
3376  return $row[0];
3377  } else {
3378  return $this->getRangOfLine($fk_parent_line);
3379  }
3380  }
3381  } else {
3382  // If not, search the last rang of element
3383  $sql = "SELECT max(".$positionfield.") FROM ".$this->db->prefix().$this->table_element_line;
3384  $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
3385 
3386  dol_syslog(get_class($this)."::line_max", LOG_DEBUG);
3387  $resql = $this->db->query($sql);
3388  if ($resql) {
3389  $row = $this->db->fetch_row($resql);
3390  return $row[0];
3391  }
3392  }
3393  }
3394 
3395  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3402  public function update_ref_ext($ref_ext)
3403  {
3404  // phpcs:enable
3405  if (!$this->table_element) {
3406  dol_syslog(get_class($this)."::update_ref_ext was called on objet with property table_element not defined", LOG_ERR);
3407  return -1;
3408  }
3409 
3410  $sql = "UPDATE ".$this->db->prefix().$this->table_element;
3411  $sql .= " SET ref_ext = '".$this->db->escape($ref_ext)."'";
3412  $sql .= " WHERE ".(isset($this->table_rowid) ? $this->table_rowid : 'rowid')." = ".((int) $this->id);
3413 
3414  dol_syslog(get_class($this)."::update_ref_ext", LOG_DEBUG);
3415  if ($this->db->query($sql)) {
3416  $this->ref_ext = $ref_ext;
3417  return 1;
3418  } else {
3419  $this->error = $this->db->error();
3420  return -1;
3421  }
3422  }
3423 
3424  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3432  public function update_note($note, $suffix = '')
3433  {
3434  // phpcs:enable
3435  global $user;
3436 
3437  if (!$this->table_element) {
3438  $this->error = 'update_note was called on objet with property table_element not defined';
3439  dol_syslog(get_class($this)."::update_note was called on objet with property table_element not defined", LOG_ERR);
3440  return -1;
3441  }
3442  if (!in_array($suffix, array('', '_public', '_private'))) {
3443  $this->error = 'update_note Parameter suffix must be empty, \'_private\' or \'_public\'';
3444  dol_syslog(get_class($this)."::update_note Parameter suffix must be empty, '_private' or '_public'", LOG_ERR);
3445  return -2;
3446  }
3447 
3448  $newsuffix = $suffix;
3449 
3450  // Special cas
3451  if ($this->table_element == 'product' && $newsuffix == '_private') {
3452  $newsuffix = '';
3453  }
3454  if (in_array($this->table_element, array('actioncomm', 'adherent', 'advtargetemailing', 'cronjob', 'establishment'))) {
3455  $fieldusermod = "fk_user_mod";
3456  } elseif ($this->table_element == 'ecm_files') {
3457  $fieldusermod = "fk_user_m";
3458  } else {
3459  $fieldusermod = "fk_user_modif";
3460  }
3461  $sql = "UPDATE ".$this->db->prefix().$this->table_element;
3462  $sql .= " SET note".$newsuffix." = ".(!empty($note) ? ("'".$this->db->escape($note)."'") : "NULL");
3463  $sql .= ", ".$fieldusermod." = ".((int) $user->id);
3464  $sql .= " WHERE rowid = ".((int) $this->id);
3465 
3466  dol_syslog(get_class($this)."::update_note", LOG_DEBUG);
3467  if ($this->db->query($sql)) {
3468  if ($suffix == '_public') {
3469  $this->note_public = $note;
3470  } elseif ($suffix == '_private') {
3471  $this->note_private = $note;
3472  } else {
3473  $this->note = $note; // deprecated
3474  $this->note_private = $note;
3475  }
3476  return 1;
3477  } else {
3478  $this->error = $this->db->lasterror();
3479  return -1;
3480  }
3481  }
3482 
3483  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3492  public function update_note_public($note)
3493  {
3494  // phpcs:enable
3495  return $this->update_note($note, '_public');
3496  }
3497 
3498  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3509  public function update_price($exclspec = 0, $roundingadjust = 'none', $nodatabaseupdate = 0, $seller = null)
3510  {
3511  // phpcs:enable
3512  global $conf, $hookmanager, $action;
3513 
3514  $parameters = array('exclspec' => $exclspec, 'roundingadjust' => $roundingadjust, 'nodatabaseupdate' => $nodatabaseupdate, 'seller' => $seller);
3515  $reshook = $hookmanager->executeHooks('updateTotalPrice', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
3516  if ($reshook > 0) {
3517  return 1; // replacement code
3518  } elseif ($reshook < 0) {
3519  return -1; // failure
3520  } // reshook = 0 => execute normal code
3521 
3522  // Some external module want no update price after a trigger because they have another method to calculate the total (ex: with an extrafield)
3523  $MODULE = "";
3524  if ($this->element == 'propal') {
3525  $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_PROPOSAL";
3526  } elseif ($this->element == 'commande' || $this->element == 'order') {
3527  $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_ORDER";
3528  } elseif ($this->element == 'facture' || $this->element == 'invoice') {
3529  $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_INVOICE";
3530  } elseif ($this->element == 'facture_fourn' || $this->element == 'supplier_invoice' || $this->element == 'invoice_supplier' || $this->element == 'invoice_supplier_rec') {
3531  $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_INVOICE";
3532  } elseif ($this->element == 'order_supplier' || $this->element == 'supplier_order') {
3533  $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_ORDER";
3534  } elseif ($this->element == 'supplier_proposal') {
3535  $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_PROPOSAL";
3536  }
3537 
3538  if (!empty($MODULE)) {
3539  if (!empty($conf->global->$MODULE)) {
3540  $modsactivated = explode(',', $conf->global->$MODULE);
3541  foreach ($modsactivated as $mod) {
3542  if ($conf->$mod->enabled) {
3543  return 1; // update was disabled by specific setup
3544  }
3545  }
3546  }
3547  }
3548 
3549  include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
3550 
3551  if ($roundingadjust == '-1') {
3552  $roundingadjust = 'auto'; // For backward compatibility
3553  }
3554 
3555  $forcedroundingmode = $roundingadjust;
3556  if ($forcedroundingmode == 'auto' && isset($conf->global->MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND)) {
3557  $forcedroundingmode = getDolGlobalString('MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND');
3558  } elseif ($forcedroundingmode == 'auto') {
3559  $forcedroundingmode = '0';
3560  }
3561 
3562  $error = 0;
3563 
3564  $multicurrency_tx = !empty($this->multicurrency_tx) ? $this->multicurrency_tx : 1;
3565 
3566  // Define constants to find lines to sum
3567  $fieldtva = 'total_tva';
3568  $fieldlocaltax1 = 'total_localtax1';
3569  $fieldlocaltax2 = 'total_localtax2';
3570  $fieldup = 'subprice';
3571  if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier') {
3572  $fieldtva = 'tva';
3573  $fieldup = 'pu_ht';
3574  }
3575  if ($this->element == 'invoice_supplier_rec') {
3576  $fieldup = 'pu_ht';
3577  }
3578  if ($this->element == 'expensereport') {
3579  $fieldup = 'value_unit';
3580  }
3581 
3582  $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,";
3583  $sql .= ' tva_tx as vatrate, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type, info_bits, product_type';
3584  if ($this->table_element_line == 'facturedet') {
3585  $sql .= ', situation_percent';
3586  }
3587  $sql .= ', multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc';
3588  $sql .= " FROM ".$this->db->prefix().$this->table_element_line;
3589  $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
3590  if ($exclspec) {
3591  $product_field = 'product_type';
3592  if ($this->table_element_line == 'contratdet') {
3593  $product_field = ''; // contratdet table has no product_type field
3594  }
3595  if ($product_field) {
3596  $sql .= " AND ".$product_field." <> 9";
3597  }
3598  }
3599  $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
3600 
3601  dol_syslog(get_class($this)."::update_price", LOG_DEBUG);
3602  $resql = $this->db->query($sql);
3603  if ($resql) {
3604  $this->total_ht = 0;
3605  $this->total_tva = 0;
3606  $this->total_localtax1 = 0;
3607  $this->total_localtax2 = 0;
3608  $this->total_ttc = 0;
3609  $total_ht_by_vats = array();
3610  $total_tva_by_vats = array();
3611  $total_ttc_by_vats = array();
3612  $this->multicurrency_total_ht = 0;
3613  $this->multicurrency_total_tva = 0;
3614  $this->multicurrency_total_ttc = 0;
3615 
3616  $num = $this->db->num_rows($resql);
3617  $i = 0;
3618  while ($i < $num) {
3619  $obj = $this->db->fetch_object($resql);
3620 
3621  // Note: There is no check on detail line and no check on total, if $forcedroundingmode = 'none'
3622  $parameters = array('fk_element' => $obj->rowid);
3623  $reshook = $hookmanager->executeHooks('changeRoundingMode', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
3624 
3625  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'
3626  // This part of code is to fix data. We should not call it too often.
3627  $localtax_array = array($obj->localtax1_type, $obj->localtax1_tx, $obj->localtax2_type, $obj->localtax2_tx);
3628  $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);
3629 
3630  $diff_when_using_price_ht = price2num($tmpcal[1] - $obj->total_tva, 'MT', 1); // If price was set with tax price adn unit price HT has a low number of digits, then we may have a diff on recalculation from unit price HT.
3631  $diff_on_current_total = price2num($obj->total_ttc - $obj->total_ht - $obj->total_tva - $obj->total_localtax1 - $obj->total_localtax2, 'MT', 1);
3632  //var_dump($obj->total_ht.' '.$obj->total_tva.' '.$obj->total_localtax1.' '.$obj->total_localtax2.' =? '.$obj->total_ttc);
3633  //var_dump($diff_when_using_price_ht.' '.$diff_on_current_total);
3634 
3635  if ($diff_when_using_price_ht && $diff_on_current_total) {
3636  $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);
3637  dol_syslog('We found unconsistent data into detailed line (diff_when_using_price_ht = '.$diff_when_using_price_ht.' and diff_on_current_total = '.$diff_on_current_total.') for line rowid = '.$obj->rowid." (total vat of line calculated=".$tmpcal[1].", database=".$obj->total_tva."). We fix the total_vat and total_ttc of line by running sqlfix = ".$sqlfix, LOG_WARNING);
3638  $resqlfix = $this->db->query($sqlfix);
3639  if (!$resqlfix) {
3640  dol_print_error($this->db, 'Failed to update line');
3641  }
3642  $obj->total_tva = $tmpcal[1];
3643  $obj->total_ttc = $tmpcal[2];
3644  }
3645  }
3646 
3647  $this->total_ht += $obj->total_ht; // The field visible at end of line detail
3648  $this->total_tva += $obj->total_tva;
3649  $this->total_localtax1 += $obj->total_localtax1;
3650  $this->total_localtax2 += $obj->total_localtax2;
3651  $this->total_ttc += $obj->total_ttc;
3652  $this->multicurrency_total_ht += $obj->multicurrency_total_ht; // The field visible at end of line detail
3653  $this->multicurrency_total_tva += $obj->multicurrency_total_tva;
3654  $this->multicurrency_total_ttc += $obj->multicurrency_total_ttc;
3655 
3656  if (!isset($total_ht_by_vats[$obj->vatrate])) {
3657  $total_ht_by_vats[$obj->vatrate] = 0;
3658  }
3659  if (!isset($total_tva_by_vats[$obj->vatrate])) {
3660  $total_tva_by_vats[$obj->vatrate] = 0;
3661  }
3662  if (!isset($total_ttc_by_vats[$obj->vatrate])) {
3663  $total_ttc_by_vats[$obj->vatrate] = 0;
3664  }
3665  $total_ht_by_vats[$obj->vatrate] += $obj->total_ht;
3666  $total_tva_by_vats[$obj->vatrate] += $obj->total_tva;
3667  $total_ttc_by_vats[$obj->vatrate] += $obj->total_ttc;
3668 
3669  if ($forcedroundingmode == '1') { // Check if we need adjustement onto line for vat. TODO This works on the company currency but not on multicurrency
3670  $tmpvat = price2num($total_ht_by_vats[$obj->vatrate] * $obj->vatrate / 100, 'MT', 1);
3671  $diff = price2num($total_tva_by_vats[$obj->vatrate] - $tmpvat, 'MT', 1);
3672  //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";
3673  if ($diff) {
3674  if (abs($diff) > 0.1) {
3675  $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.';
3676  dol_syslog($errmsg, LOG_WARNING);
3677  dol_print_error('', $errmsg);
3678  exit;
3679  }
3680  $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);
3681  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);
3682 
3683  $resqlfix = $this->db->query($sqlfix);
3684 
3685  if (!$resqlfix) {
3686  dol_print_error($this->db, 'Failed to update line');
3687  }
3688 
3689  $this->total_tva = (float) price2num($this->total_tva - $diff, '', 1);
3690  $this->total_ttc = (float) price2num($this->total_ttc - $diff, '', 1);
3691  $total_tva_by_vats[$obj->vatrate] = (float) price2num($total_tva_by_vats[$obj->vatrate] - $diff, '', 1);
3692  $total_ttc_by_vats[$obj->vatrate] = (float) price2num($total_ttc_by_vats[$obj->vatrate] - $diff, '', 1);
3693  }
3694  }
3695 
3696  $i++;
3697  }
3698 
3699  // Add revenue stamp to total
3700  $this->total_ttc += isset($this->revenuestamp) ? $this->revenuestamp : 0;
3701  $this->multicurrency_total_ttc += isset($this->revenuestamp) ? ($this->revenuestamp * $multicurrency_tx) : 0;
3702 
3703  // Situations totals
3704  if (!empty($this->situation_cycle_ref) && $this->situation_counter > 1 && method_exists($this, 'get_prev_sits') && $this->type != $this::TYPE_CREDIT_NOTE) {
3705  $prev_sits = $this->get_prev_sits();
3706 
3707  foreach ($prev_sits as $sit) { // $sit is an object Facture loaded with a fetch.
3708  $this->total_ht -= $sit->total_ht;
3709  $this->total_tva -= $sit->total_tva;
3710  $this->total_localtax1 -= $sit->total_localtax1;
3711  $this->total_localtax2 -= $sit->total_localtax2;
3712  $this->total_ttc -= $sit->total_ttc;
3713  $this->multicurrency_total_ht -= $sit->multicurrency_total_ht;
3714  $this->multicurrency_total_tva -= $sit->multicurrency_total_tva;
3715  $this->multicurrency_total_ttc -= $sit->multicurrency_total_ttc;
3716  }
3717  }
3718 
3719  // Clean total
3720  $this->total_ht = (float) price2num($this->total_ht);
3721  $this->total_tva = (float) price2num($this->total_tva);
3722  $this->total_localtax1 = (float) price2num($this->total_localtax1);
3723  $this->total_localtax2 = (float) price2num($this->total_localtax2);
3724  $this->total_ttc = (float) price2num($this->total_ttc);
3725 
3726  $this->db->free($resql);
3727 
3728  // Now update global fields total_ht, total_ttc, total_tva, total_localtax1, total_localtax2, multicurrency_total_*
3729  $fieldht = 'total_ht';
3730  $fieldtva = 'tva';
3731  $fieldlocaltax1 = 'localtax1';
3732  $fieldlocaltax2 = 'localtax2';
3733  $fieldttc = 'total_ttc';
3734  // Specific code for backward compatibility with old field names
3735  if ($this->element == 'facture' || $this->element == 'facturerec') {
3736  $fieldtva = 'total_tva';
3737  }
3738  if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier' || $this->element == 'invoice_supplier_rec') {
3739  $fieldtva = 'total_tva';
3740  }
3741  if ($this->element == 'propal') {
3742  $fieldtva = 'total_tva';
3743  }
3744  if ($this->element == 'expensereport') {
3745  $fieldtva = 'total_tva';
3746  }
3747  if ($this->element == 'supplier_proposal') {
3748  $fieldtva = 'total_tva';
3749  }
3750  if ($this->element == 'commande') {
3751  $fieldtva = 'total_tva';
3752  }
3753  if ($this->element == 'order_supplier') {
3754  $fieldtva = 'total_tva';
3755  }
3756 
3757  if (empty($nodatabaseupdate)) {
3758  $sql = "UPDATE ".$this->db->prefix().$this->table_element.' SET';
3759  $sql .= " ".$fieldht." = ".((float) price2num($this->total_ht, 'MT', 1)).",";
3760  $sql .= " ".$fieldtva." = ".((float) price2num($this->total_tva, 'MT', 1)).",";
3761  $sql .= " ".$fieldlocaltax1." = ".((float) price2num($this->total_localtax1, 'MT', 1)).",";
3762  $sql .= " ".$fieldlocaltax2." = ".((float) price2num($this->total_localtax2, 'MT', 1)).",";
3763  $sql .= " ".$fieldttc." = ".((float) price2num($this->total_ttc, 'MT', 1));
3764  $sql .= ", multicurrency_total_ht = ".((float) price2num($this->multicurrency_total_ht, 'MT', 1));
3765  $sql .= ", multicurrency_total_tva = ".((float) price2num($this->multicurrency_total_tva, 'MT', 1));
3766  $sql .= ", multicurrency_total_ttc = ".((float) price2num($this->multicurrency_total_ttc, 'MT', 1));
3767  $sql .= " WHERE rowid = ".((int) $this->id);
3768 
3769  dol_syslog(get_class($this)."::update_price", LOG_DEBUG);
3770  $resql = $this->db->query($sql);
3771 
3772  if (!$resql) {
3773  $error++;
3774  $this->error = $this->db->lasterror();
3775  $this->errors[] = $this->db->lasterror();
3776  }
3777  }
3778 
3779  if (!$error) {
3780  return 1;
3781  } else {
3782  return -1;
3783  }
3784  } else {
3785  dol_print_error($this->db, 'Bad request in update_price');
3786  return -1;
3787  }
3788  }
3789 
3790  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3801  public function add_object_linked($origin = null, $origin_id = null, $f_user = null, $notrigger = 0)
3802  {
3803  // phpcs:enable
3804  global $user, $hookmanager, $action;
3805  $origin = (!empty($origin) ? $origin : $this->origin);
3806  $origin_id = (!empty($origin_id) ? $origin_id : $this->origin_id);
3807  $f_user = isset($f_user) ? $f_user : $user;
3808 
3809  // Special case
3810  if ($origin == 'order') {
3811  $origin = 'commande';
3812  }
3813  if ($origin == 'invoice') {
3814  $origin = 'facture';
3815  }
3816  if ($origin == 'invoice_template') {
3817  $origin = 'facturerec';
3818  }
3819  if ($origin == 'supplierorder') {
3820  $origin = 'order_supplier';
3821  }
3822 
3823  // 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.
3824  // 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.
3825  $coremodule = array('knowledgemanagement', 'partnership', 'workstation', 'ticket', 'recruitment', 'eventorganization', 'asset');
3826  // Add module part to target type if object has $module property and isn't in core modules.
3827  $targettype = ((!empty($this->module) && ! in_array($this->module, $coremodule)) ? $this->module.'_' : '').$this->element;
3828 
3829  $parameters = array('targettype'=>$targettype);
3830  // Hook for explicitly set the targettype if it must be differtent than $this->element
3831  $reshook = $hookmanager->executeHooks('setLinkedObjectSourceTargetType', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
3832  if ($reshook > 0) {
3833  if (!empty($hookmanager->resArray['targettype'])) $targettype = $hookmanager->resArray['targettype'];
3834  }
3835 
3836  $this->db->begin();
3837  $error = 0;
3838 
3839  $sql = "INSERT INTO " . $this->db->prefix() . "element_element (";
3840  $sql .= "fk_source";
3841  $sql .= ", sourcetype";
3842  $sql .= ", fk_target";
3843  $sql .= ", targettype";
3844  $sql .= ") VALUES (";
3845  $sql .= ((int) $origin_id);
3846  $sql .= ", '" . $this->db->escape($origin) . "'";
3847  $sql .= ", " . ((int) $this->id);
3848  $sql .= ", '" . $this->db->escape($targettype) . "'";
3849  $sql .= ")";
3850 
3851  dol_syslog(get_class($this) . "::add_object_linked", LOG_DEBUG);
3852  if ($this->db->query($sql)) {
3853  if (!$notrigger) {
3854  // Call trigger
3855  $this->context['link_origin'] = $origin;
3856  $this->context['link_origin_id'] = $origin_id;
3857  $result = $this->call_trigger('OBJECT_LINK_INSERT', $f_user);
3858  if ($result < 0) {
3859  $error++;
3860  }
3861  // End call triggers
3862  }
3863  } else {
3864  $this->error = $this->db->lasterror();
3865  $error++;
3866  }
3867 
3868  if (!$error) {
3869  $this->db->commit();
3870  return 1;
3871  } else {
3872  $this->db->rollback();
3873  return 0;
3874  }
3875  }
3876 
3899  public function fetchObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $clause = 'OR', $alsosametype = 1, $orderby = 'sourcetype', $loadalsoobjects = 1)
3900  {
3901  global $conf, $hookmanager, $action;
3902 
3903  // Important for pdf generation time reduction
3904  // This boolean is true if $this->linkedObjects has already been loaded with all objects linked without filter
3905  if ($this->id > 0 && !empty($this->linkedObjectsFullLoaded[$this->id])) {
3906  return 1;
3907  }
3908 
3909  $this->linkedObjectsIds = array();
3910  $this->linkedObjects = array();
3911 
3912  $justsource = false;
3913  $justtarget = false;
3914  $withtargettype = false;
3915  $withsourcetype = false;
3916 
3917  $parameters = array('sourcetype'=>$sourcetype, 'sourceid'=>$sourceid, 'targettype'=>$targettype, 'targetid'=>$targetid);
3918  // Hook for explicitly set the targettype if it must be differtent than $this->element
3919  $reshook = $hookmanager->executeHooks('setLinkedObjectSourceTargetType', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
3920  if ($reshook > 0) {
3921  if (!empty($hookmanager->resArray['sourcetype'])) $sourcetype = $hookmanager->resArray['sourcetype'];
3922  if (!empty($hookmanager->resArray['sourceid'])) $sourceid = $hookmanager->resArray['sourceid'];
3923  if (!empty($hookmanager->resArray['targettype'])) $targettype = $hookmanager->resArray['targettype'];
3924  if (!empty($hookmanager->resArray['targetid'])) $targetid = $hookmanager->resArray['targetid'];
3925  }
3926 
3927  if (!empty($sourceid) && !empty($sourcetype) && empty($targetid)) {
3928  $justsource = true; // the source (id and type) is a search criteria
3929  if (!empty($targettype)) {
3930  $withtargettype = true;
3931  }
3932  }
3933  if (!empty($targetid) && !empty($targettype) && empty($sourceid)) {
3934  $justtarget = true; // the target (id and type) is a search criteria
3935  if (!empty($sourcetype)) {
3936  $withsourcetype = true;
3937  }
3938  }
3939 
3940  $sourceid = (!empty($sourceid) ? $sourceid : $this->id);
3941  $targetid = (!empty($targetid) ? $targetid : $this->id);
3942  $sourcetype = (!empty($sourcetype) ? $sourcetype : $this->element);
3943  $targettype = (!empty($targettype) ? $targettype : $this->element);
3944 
3945  /*if (empty($sourceid) && empty($targetid))
3946  {
3947  dol_syslog('Bad usage of function. No source nor target id defined (nor as parameter nor as object id)', LOG_ERR);
3948  return -1;
3949  }*/
3950 
3951  // Links between objects are stored in table element_element
3952  $sql = "SELECT rowid, fk_source, sourcetype, fk_target, targettype";
3953  $sql .= " FROM ".$this->db->prefix()."element_element";
3954  $sql .= " WHERE ";
3955  if ($justsource || $justtarget) {
3956  if ($justsource) {
3957  $sql .= "fk_source = ".((int) $sourceid)." AND sourcetype = '".$this->db->escape($sourcetype)."'";
3958  if ($withtargettype) {
3959  $sql .= " AND targettype = '".$this->db->escape($targettype)."'";
3960  }
3961  } elseif ($justtarget) {
3962  $sql .= "fk_target = ".((int) $targetid)." AND targettype = '".$this->db->escape($targettype)."'";
3963  if ($withsourcetype) {
3964  $sql .= " AND sourcetype = '".$this->db->escape($sourcetype)."'";
3965  }
3966  }
3967  } else {
3968  $sql .= "(fk_source = ".((int) $sourceid)." AND sourcetype = '".$this->db->escape($sourcetype)."')";
3969  $sql .= " ".$clause." (fk_target = ".((int) $targetid)." AND targettype = '".$this->db->escape($targettype)."')";
3970  if ($loadalsoobjects && $this->id > 0 && $sourceid == $this->id && $sourcetype == $this->element && $targetid == $this->id && $targettype == $this->element && $clause == 'OR') {
3971  $this->linkedObjectsFullLoaded[$this->id] = true;
3972  }
3973  }
3974  $sql .= " ORDER BY ".$orderby;
3975 
3976  dol_syslog(get_class($this)."::fetchObjectLink", LOG_DEBUG);
3977  $resql = $this->db->query($sql);
3978  if ($resql) {
3979  $num = $this->db->num_rows($resql);
3980  $i = 0;
3981  while ($i < $num) {
3982  $obj = $this->db->fetch_object($resql);
3983  if ($justsource || $justtarget) {
3984  if ($justsource) {
3985  $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
3986  } elseif ($justtarget) {
3987  $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
3988  }
3989  } else {
3990  if ($obj->fk_source == $sourceid && $obj->sourcetype == $sourcetype) {
3991  $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
3992  }
3993  if ($obj->fk_target == $targetid && $obj->targettype == $targettype) {
3994  $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
3995  }
3996  }
3997  $i++;
3998  }
3999 
4000  if (!empty($this->linkedObjectsIds)) {
4001  $tmparray = $this->linkedObjectsIds;
4002  foreach ($tmparray as $objecttype => $objectids) { // $objecttype is a module name ('facture', 'mymodule', ...) or a module name with a suffix ('project_task', 'mymodule_myobj', ...)
4003  // Parse element/subelement (ex: project_task, cabinetmed_consultation, ...)
4004  $module = $element = $subelement = $objecttype;
4005  $regs = array();
4006  if ($objecttype != 'supplier_proposal' && $objecttype != 'order_supplier' && $objecttype != 'invoice_supplier'
4007  && preg_match('/^([^_]+)_([^_]+)/i', $objecttype, $regs)) {
4008  $module = $element = $regs[1];
4009  $subelement = $regs[2];
4010  }
4011 
4012  $classpath = $element.'/class';
4013  // To work with non standard classpath or module name
4014  if ($objecttype == 'facture') {
4015  $classpath = 'compta/facture/class';
4016  } elseif ($objecttype == 'facturerec') {
4017  $classpath = 'compta/facture/class';
4018  $module = 'facture';
4019  } elseif ($objecttype == 'propal') {
4020  $classpath = 'comm/propal/class';
4021  } elseif ($objecttype == 'supplier_proposal') {
4022  $classpath = 'supplier_proposal/class';
4023  } elseif ($objecttype == 'shipping') {
4024  $classpath = 'expedition/class';
4025  $subelement = 'expedition';
4026  $module = 'expedition_bon';
4027  } elseif ($objecttype == 'delivery') {
4028  $classpath = 'delivery/class';
4029  $subelement = 'delivery';
4030  $module = 'delivery_note';
4031  } elseif ($objecttype == 'invoice_supplier' || $objecttype == 'order_supplier') {
4032  $classpath = 'fourn/class';
4033  $module = 'fournisseur';
4034  } elseif ($objecttype == 'fichinter') {
4035  $classpath = 'fichinter/class';
4036  $subelement = 'fichinter';
4037  $module = 'ficheinter';
4038  } elseif ($objecttype == 'subscription') {
4039  $classpath = 'adherents/class';
4040  $module = 'adherent';
4041  } elseif ($objecttype == 'contact') {
4042  $module = 'societe';
4043  }
4044  // Set classfile
4045  $classfile = strtolower($subelement);
4046  $classname = ucfirst($subelement);
4047 
4048  if ($objecttype == 'order') {
4049  $classfile = 'commande';
4050  $classname = 'Commande';
4051  } elseif ($objecttype == 'invoice_supplier') {
4052  $classfile = 'fournisseur.facture';
4053  $classname = 'FactureFournisseur';
4054  } elseif ($objecttype == 'order_supplier') {
4055  $classfile = 'fournisseur.commande';
4056  $classname = 'CommandeFournisseur';
4057  } elseif ($objecttype == 'supplier_proposal') {
4058  $classfile = 'supplier_proposal';
4059  $classname = 'SupplierProposal';
4060  } elseif ($objecttype == 'facturerec') {
4061  $classfile = 'facture-rec';
4062  $classname = 'FactureRec';
4063  } elseif ($objecttype == 'subscription') {
4064  $classfile = 'subscription';
4065  $classname = 'Subscription';
4066  } elseif ($objecttype == 'project' || $objecttype == 'projet') {
4067  $classpath = 'projet/class';
4068  $classfile = 'project';
4069  $classname = 'Project';
4070  } elseif ($objecttype == 'conferenceorboothattendee') {
4071  $classpath = 'eventorganization/class';
4072  $classfile = 'conferenceorboothattendee';
4073  $classname = 'ConferenceOrBoothAttendee';
4074  $module = 'eventorganization';
4075  } elseif ($objecttype == 'conferenceorbooth') {
4076  $classpath = 'eventorganization/class';
4077  $classfile = 'conferenceorbooth';
4078  $classname = 'ConferenceOrBooth';
4079  $module = 'eventorganization';
4080  } elseif ($objecttype == 'mo') {
4081  $classpath = 'mrp/class';
4082  $classfile = 'mo';
4083  $classname = 'Mo';
4084  $module = 'mrp';
4085  }
4086 
4087  // Here $module, $classfile and $classname are set, we can use them.
4088  if ($conf->$module->enabled && (($element != $this->element) || $alsosametype)) {
4089  if ($loadalsoobjects && (is_numeric($loadalsoobjects) || ($loadalsoobjects === $objecttype))) {
4090  dol_include_once('/'.$classpath.'/'.$classfile.'.class.php');
4091  //print '/'.$classpath.'/'.$classfile.'.class.php '.class_exists($classname);
4092  if (class_exists($classname)) {
4093  foreach ($objectids as $i => $objectid) { // $i is rowid into llx_element_element
4094  $object = new $classname($this->db);
4095  $ret = $object->fetch($objectid);
4096  if ($ret >= 0) {
4097  $this->linkedObjects[$objecttype][$i] = $object;
4098  }
4099  }
4100  }
4101  }
4102  } else {
4103  unset($this->linkedObjectsIds[$objecttype]);
4104  }
4105  }
4106  }
4107  return 1;
4108  } else {
4109  dol_print_error($this->db);
4110  return -1;
4111  }
4112  }
4113 
4126  public function updateObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $f_user = null, $notrigger = 0)
4127  {
4128  global $user;
4129  $updatesource = false;
4130  $updatetarget = false;
4131  $f_user = isset($f_user) ? $f_user : $user;
4132 
4133  if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) {
4134  $updatesource = true;
4135  } elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) {
4136  $updatetarget = true;
4137  }
4138 
4139  $this->db->begin();
4140  $error = 0;
4141 
4142  $sql = "UPDATE " . $this->db->prefix() . "element_element SET ";
4143  if ($updatesource) {
4144  $sql .= "fk_source = " . ((int) $sourceid);
4145  $sql .= ", sourcetype = '" . $this->db->escape($sourcetype) . "'";
4146  $sql .= " WHERE fk_target = " . ((int) $this->id);
4147  $sql .= " AND targettype = '" . $this->db->escape($this->element) . "'";
4148  } elseif ($updatetarget) {
4149  $sql .= "fk_target = " . ((int) $targetid);
4150  $sql .= ", targettype = '" . $this->db->escape($targettype) . "'";
4151  $sql .= " WHERE fk_source = " . ((int) $this->id);
4152  $sql .= " AND sourcetype = '" . $this->db->escape($this->element) . "'";
4153  }
4154 
4155  dol_syslog(get_class($this) . "::updateObjectLinked", LOG_DEBUG);
4156  if ($this->db->query($sql)) {
4157  if (!$notrigger) {
4158  // Call trigger
4159  $this->context['link_source_id'] = $sourceid;
4160  $this->context['link_source_type'] = $sourcetype;
4161  $this->context['link_target_id'] = $targetid;
4162  $this->context['link_target_type'] = $targettype;
4163  $result = $this->call_trigger('OBJECT_LINK_MODIFY', $f_user);
4164  if ($result < 0) {
4165  $error++;
4166  }
4167  // End call triggers
4168  }
4169  } else {
4170  $this->error = $this->db->lasterror();
4171  $error++;
4172  }
4173 
4174  if (!$error) {
4175  $this->db->commit();
4176  return 1;
4177  } else {
4178  $this->db->rollback();
4179  return -1;
4180  }
4181  }
4182 
4196  public function deleteObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $rowid = '', $f_user = null, $notrigger = 0)
4197  {
4198  global $user;
4199  $deletesource = false;
4200  $deletetarget = false;
4201  $f_user = isset($f_user) ? $f_user : $user;
4202 
4203  if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) {
4204  $deletesource = true;
4205  } elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) {
4206  $deletetarget = true;
4207  }
4208 
4209  $sourceid = (!empty($sourceid) ? $sourceid : $this->id);
4210  $sourcetype = (!empty($sourcetype) ? $sourcetype : $this->element);
4211  $targetid = (!empty($targetid) ? $targetid : $this->id);
4212  $targettype = (!empty($targettype) ? $targettype : $this->element);
4213  $this->db->begin();
4214  $error = 0;
4215 
4216  if (!$notrigger) {
4217  // Call trigger
4218  $this->context['link_id'] = $rowid;
4219  $this->context['link_source_id'] = $sourceid;
4220  $this->context['link_source_type'] = $sourcetype;
4221  $this->context['link_target_id'] = $targetid;
4222  $this->context['link_target_type'] = $targettype;
4223  $result = $this->call_trigger('OBJECT_LINK_DELETE', $f_user);
4224  if ($result < 0) {
4225  $error++;
4226  }
4227  // End call triggers
4228  }
4229 
4230  if (!$error) {
4231  $sql = "DELETE FROM " . $this->db->prefix() . "element_element";
4232  $sql .= " WHERE";
4233  if ($rowid > 0) {
4234  $sql .= " rowid = " . ((int) $rowid);
4235  } else {
4236  if ($deletesource) {
4237  $sql .= " fk_source = " . ((int) $sourceid) . " AND sourcetype = '" . $this->db->escape($sourcetype) . "'";
4238  $sql .= " AND fk_target = " . ((int) $this->id) . " AND targettype = '" . $this->db->escape($this->element) . "'";
4239  } elseif ($deletetarget) {
4240  $sql .= " fk_target = " . ((int) $targetid) . " AND targettype = '" . $this->db->escape($targettype) . "'";
4241  $sql .= " AND fk_source = " . ((int) $this->id) . " AND sourcetype = '" . $this->db->escape($this->element) . "'";
4242  } else {
4243  $sql .= " (fk_source = " . ((int) $this->id) . " AND sourcetype = '" . $this->db->escape($this->element) . "')";
4244  $sql .= " OR";
4245  $sql .= " (fk_target = " . ((int) $this->id) . " AND targettype = '" . $this->db->escape($this->element) . "')";
4246  }
4247  }
4248 
4249  dol_syslog(get_class($this) . "::deleteObjectLinked", LOG_DEBUG);
4250  if (!$this->db->query($sql)) {
4251  $this->error = $this->db->lasterror();
4252  $this->errors[] = $this->error;
4253  $error++;
4254  }
4255  }
4256 
4257  if (!$error) {
4258  $this->db->commit();
4259  return 1;
4260  } else {
4261  $this->db->rollback();
4262  return 0;
4263  }
4264  }
4265 
4275  public static function getAllItemsLinkedByObjectID($fk_object_where, $field_select, $field_where, $table_element)
4276  {
4277  if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
4278  return -1;
4279  }
4280 
4281  global $db;
4282 
4283  $sql = "SELECT ".$field_select." FROM ".$db->prefix().$table_element." WHERE ".$field_where." = ".((int) $fk_object_where);
4284  $resql = $db->query($sql);
4285 
4286  $TRes = array();
4287  if (!empty($resql)) {
4288  while ($res = $db->fetch_object($resql)) {
4289  $TRes[] = $res->{$field_select};
4290  }
4291  }
4292 
4293  return $TRes;
4294  }
4295 
4304  public static function deleteAllItemsLinkedByObjectID($fk_object_where, $field_where, $table_element)
4305  {
4306  if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
4307  return -1;
4308  }
4309 
4310  global $db;
4311 
4312  $sql = "DELETE FROM ".$db->prefix().$table_element." WHERE ".$field_where." = ".((int) $fk_object_where);
4313  $resql = $db->query($sql);
4314 
4315  if (empty($resql)) {
4316  return 0;
4317  }
4318 
4319  return 1;
4320  }
4321 
4332  public function setStatut($status, $elementId = null, $elementType = '', $trigkey = '', $fieldstatus = 'fk_statut')
4333  {
4334  global $user, $langs, $conf;
4335 
4336  $savElementId = $elementId; // To be used later to know if we were using the method using the id of this or not.
4337 
4338  $elementId = (!empty($elementId) ? $elementId : $this->id);
4339  $elementTable = (!empty($elementType) ? $elementType : $this->table_element);
4340 
4341  $this->db->begin();
4342 
4343  if ($elementTable == 'facture_rec') {
4344  $fieldstatus = "suspended";
4345  }
4346  if ($elementTable == 'mailing') {
4347  $fieldstatus = "statut";
4348  }
4349  if ($elementTable == 'cronjob') {
4350  $fieldstatus = "status";
4351  }
4352  if ($elementTable == 'user') {
4353  $fieldstatus = "statut";
4354  }
4355  if ($elementTable == 'expensereport') {
4356  $fieldstatus = "fk_statut";
4357  }
4358  if ($elementTable == 'commande_fournisseur_dispatch') {
4359  $fieldstatus = "status";
4360  }
4361  if (isset($this->fields) && is_array($this->fields) && array_key_exists('status', $this->fields)) {
4362  $fieldstatus = 'status';
4363  }
4364 
4365  $sql = "UPDATE ".$this->db->prefix().$elementTable;
4366  $sql .= " SET ".$fieldstatus." = ".((int) $status);
4367  // If status = 1 = validated, update also fk_user_valid
4368  // TODO Replace the test on $elementTable by doing a test on existence of the field in $this->fields
4369  if ($status == 1 && in_array($elementTable, array('expensereport', 'inventory'))) {
4370  $sql .= ", fk_user_valid = ".((int) $user->id);
4371  }
4372  if ($status == 1 && in_array($elementTable, array('expensereport'))) {
4373  $sql .= ", date_valid = '".$this->db->idate(dol_now())."'";
4374  }
4375  if ($status == 1 && in_array($elementTable, array('inventory'))) {
4376  $sql .= ", date_validation = '".$this->db->idate(dol_now())."'";
4377  }
4378  $sql .= " WHERE rowid = ".((int) $elementId);
4379  $sql .= " AND ".$fieldstatus." <> ".((int) $status); // We avoid update if status already correct
4380 
4381  dol_syslog(get_class($this)."::setStatut", LOG_DEBUG);
4382  $resql = $this->db->query($sql);
4383  if ($resql) {
4384  $error = 0;
4385 
4386  $nb_rows_affected = $this->db->affected_rows($resql); // should be 1 or 0 if status was already correct
4387 
4388  if ($nb_rows_affected >= 0) {
4389  if (empty($trigkey)) {
4390  // Try to guess trigkey (for backward compatibility, now we should have trigkey defined into the call of setStatus)
4391  if ($this->element == 'supplier_proposal' && $status == 2) {
4392  $trigkey = 'SUPPLIER_PROPOSAL_SIGN'; // 2 = SupplierProposal::STATUS_SIGNED. Can't use constant into this generic class
4393  }
4394  if ($this->element == 'supplier_proposal' && $status == 3) {
4395  $trigkey = 'SUPPLIER_PROPOSAL_REFUSE'; // 3 = SupplierProposal::STATUS_REFUSED. Can't use constant into this generic class
4396  }
4397  if ($this->element == 'supplier_proposal' && $status == 4) {
4398  $trigkey = 'SUPPLIER_PROPOSAL_CLOSE'; // 4 = SupplierProposal::STATUS_CLOSED. Can't use constant into this generic class
4399  }
4400  if ($this->element == 'fichinter' && $status == 3) {
4401  $trigkey = 'FICHINTER_CLASSIFY_DONE';
4402  }
4403  if ($this->element == 'fichinter' && $status == 2) {
4404  $trigkey = 'FICHINTER_CLASSIFY_BILLED';
4405  }
4406  if ($this->element == 'fichinter' && $status == 1) {
4407  $trigkey = 'FICHINTER_CLASSIFY_UNBILLED';
4408  }
4409  }
4410 
4411  if ($trigkey) {
4412  // Call trigger
4413  $result = $this->call_trigger($trigkey, $user);
4414  if ($result < 0) {
4415  $error++;
4416  }
4417  // End call triggers
4418  }
4419  } else {
4420  // The status was probably already good. We do nothing more, no triggers.
4421  }
4422 
4423  if (!$error) {
4424  $this->db->commit();
4425 
4426  if (empty($savElementId)) {
4427  // If the element we update is $this (so $elementId was provided as null)
4428  if ($fieldstatus == 'tosell') {
4429  $this->status = $status;
4430  } elseif ($fieldstatus == 'tobuy') {
4431  $this->status_buy = $status;
4432  } else {
4433  $this->statut = $status;
4434  $this->status = $status;
4435  }
4436  }
4437 
4438  return 1;
4439  } else {
4440  $this->db->rollback();
4441  dol_syslog(get_class($this)."::setStatut ".$this->error, LOG_ERR);
4442  return -1;
4443  }
4444  } else {
4445  $this->error = $this->db->lasterror();
4446  $this->db->rollback();
4447  return -1;
4448  }
4449  }
4450 
4451 
4459  public function getCanvas($id = 0, $ref = '')
4460  {
4461  global $conf;
4462 
4463  if (empty($id) && empty($ref)) {
4464  return 0;
4465  }
4466  if (!empty($conf->global->MAIN_DISABLE_CANVAS)) {
4467  return 0; // To increase speed. Not enabled by default.
4468  }
4469 
4470  // Clean parameters
4471  $ref = trim($ref);
4472 
4473  $sql = "SELECT rowid, canvas";
4474  $sql .= " FROM ".$this->db->prefix().$this->table_element;
4475  $sql .= " WHERE entity IN (".getEntity($this->element).")";
4476  if (!empty($id)) {
4477  $sql .= " AND rowid = ".((int) $id);
4478  }
4479  if (!empty($ref)) {
4480  $sql .= " AND ref = '".$this->db->escape($ref)."'";
4481  }
4482 
4483  $resql = $this->db->query($sql);
4484  if ($resql) {
4485  $obj = $this->db->fetch_object($resql);
4486  if ($obj) {
4487  $this->canvas = $obj->canvas;
4488  return 1;
4489  } else {
4490  return 0;
4491  }
4492  } else {
4493  dol_print_error($this->db);
4494  return -1;
4495  }
4496  }
4497 
4498 
4505  public function getSpecialCode($lineid)
4506  {
4507  $sql = "SELECT special_code FROM ".$this->db->prefix().$this->table_element_line;
4508  $sql .= " WHERE rowid = ".((int) $lineid);
4509  $resql = $this->db->query($sql);
4510  if ($resql) {
4511  $row = $this->db->fetch_row($resql);
4512  return $row[0];
4513  }
4514  }
4515 
4524  public function isObjectUsed($id = 0, $entity = 0)
4525  {
4526  global $langs;
4527 
4528  if (empty($id)) {
4529  $id = $this->id;
4530  }
4531 
4532  // Check parameters
4533  if (!isset($this->childtables) || !is_array($this->childtables) || count($this->childtables) == 0) {
4534  dol_print_error('Called isObjectUsed on a class with property this->childtables not defined');
4535  return -1;
4536  }
4537 
4538  $arraytoscan = $this->childtables;
4539  // For backward compatibility, we check if array is old format array('table1', 'table2', ...)
4540  $tmparray = array_keys($this->childtables);
4541  if (is_numeric($tmparray[0])) {
4542  $arraytoscan = array_flip($this->childtables);
4543  }
4544 
4545  // Test if child exists
4546  $haschild = 0;
4547  foreach ($arraytoscan as $table => $element) {
4548  //print $id.'-'.$table.'-'.$elementname.'<br>';
4549  // Check if element can be deleted
4550  $sql = "SELECT COUNT(*) as nb";
4551  $sql.= " FROM ".$this->db->prefix().$table." as c";
4552  if (!empty($element['parent']) && !empty($element['parentkey'])) {
4553  $sql.= ", ".$this->db->prefix().$element['parent']." as p";
4554  }
4555  $sql.= " WHERE c.".$this->fk_element." = ".((int) $id);
4556  if (!empty($element['parent']) && !empty($element['parentkey'])) {
4557  $sql.= " AND c.".$element['parentkey']." = p.rowid";
4558  }
4559  if (!empty($entity)) {
4560  if (!empty($element['parent']) && !empty($element['parentkey'])) {
4561  $sql.= " AND p.entity = ".((int) $entity);
4562  } else {
4563  $sql.= " AND c.entity = ".((int) $entity);
4564  }
4565  }
4566  $resql = $this->db->query($sql);
4567  if ($resql) {
4568  $obj = $this->db->fetch_object($resql);
4569  if ($obj->nb > 0) {
4570  $langs->load("errors");
4571  //print 'Found into table '.$table.', type '.$langs->transnoentitiesnoconv($elementname).', haschild='.$haschild;
4572  $haschild += $obj->nb;
4573  if (is_numeric($element)) { // very old usage array('table1', 'table2', ...)
4574  $this->errors[] = $langs->transnoentitiesnoconv("ErrorRecordHasAtLeastOneChildOfType", method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref, $table);
4575  } elseif (is_string($element)) { // old usage array('table1' => 'TranslateKey1', 'table2' => 'TranslateKey2', ...)
4576  $this->errors[] = $langs->transnoentitiesnoconv("ErrorRecordHasAtLeastOneChildOfType", method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref, $langs->transnoentitiesnoconv($element));
4577  } else { // new usage: $element['name']=Translation key
4578  $this->errors[] = $langs->transnoentitiesnoconv("ErrorRecordHasAtLeastOneChildOfType", method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref, $langs->transnoentitiesnoconv($element['name']));
4579  }
4580  break; // We found at least one, we stop here
4581  }
4582  } else {
4583  $this->errors[] = $this->db->lasterror();
4584  return -1;
4585  }
4586  }
4587  if ($haschild > 0) {
4588  $this->errors[] = "ErrorRecordHasChildren";
4589  return $haschild;
4590  } else {
4591  return 0;
4592  }
4593  }
4594 
4601  public function hasProductsOrServices($predefined = -1)
4602  {
4603  $nb = 0;
4604 
4605  foreach ($this->lines as $key => $val) {
4606  $qualified = 0;
4607  if ($predefined == -1) {
4608  $qualified = 1;
4609  }
4610  if ($predefined == 1 && $val->fk_product > 0) {
4611  $qualified = 1;
4612  }
4613  if ($predefined == 0 && $val->fk_product <= 0) {
4614  $qualified = 1;
4615  }
4616  if ($predefined == 2 && $val->fk_product > 0 && $val->product_type == 0) {
4617  $qualified = 1;
4618  }
4619  if ($predefined == 3 && $val->fk_product > 0 && $val->product_type == 1) {
4620  $qualified = 1;
4621  }
4622  if ($qualified) {
4623  $nb++;
4624  }
4625  }
4626  dol_syslog(get_class($this).'::hasProductsOrServices we found '.$nb.' qualified lines of products/servcies');
4627  return $nb;
4628  }
4629 
4635  public function getTotalDiscount()
4636  {
4637  if (!empty($this->table_element_line) ) {
4638  $total_discount = 0.00;
4639 
4640  $sql = "SELECT subprice as pu_ht, qty, remise_percent, total_ht";
4641  $sql .= " FROM ".$this->db->prefix().$this->table_element_line;
4642  $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
4643 
4644  dol_syslog(get_class($this).'::getTotalDiscount', LOG_DEBUG);
4645  $resql = $this->db->query($sql);
4646  if ($resql) {
4647  $num = $this->db->num_rows($resql);
4648  $i = 0;
4649  while ($i < $num) {
4650  $obj = $this->db->fetch_object($resql);
4651 
4652  $pu_ht = $obj->pu_ht;
4653  $qty = $obj->qty;
4654  $total_ht = $obj->total_ht;
4655 
4656  $total_discount_line = floatval(price2num(($pu_ht * $qty) - $total_ht, 'MT'));
4657  $total_discount += $total_discount_line;
4658 
4659  $i++;
4660  }
4661  }
4662 
4663  //print $total_discount; exit;
4664  return price2num($total_discount);
4665  }
4666 
4667  return null;
4668  }
4669 
4670 
4677  public function getTotalWeightVolume()
4678  {
4679  $totalWeight = 0;
4680  $totalVolume = 0;
4681  // defined for shipment only
4682  $totalOrdered = '';
4683  // defined for shipment only
4684  $totalToShip = '';
4685 
4686  foreach ($this->lines as $line) {
4687  if (isset($line->qty_asked)) {
4688  if (empty($totalOrdered)) {
4689  $totalOrdered = 0; // Avoid warning because $totalOrdered is ''
4690  }
4691  $totalOrdered += $line->qty_asked; // defined for shipment only
4692  }
4693  if (isset($line->qty_shipped)) {
4694  if (empty($totalToShip)) {
4695  $totalToShip = 0; // Avoid warning because $totalToShip is ''
4696  }
4697  $totalToShip += $line->qty_shipped; // defined for shipment only
4698  } elseif ($line->element == 'commandefournisseurdispatch' && isset($line->qty)) {
4699  if (empty($totalToShip)) {
4700  $totalToShip = 0;
4701  }
4702  $totalToShip += $line->qty; // defined for reception only
4703  }
4704 
4705  // Define qty, weight, volume, weight_units, volume_units
4706  if ($this->element == 'shipping') {
4707  // for shipments
4708  $qty = $line->qty_shipped ? $line->qty_shipped : 0;
4709  } else {
4710  $qty = $line->qty ? $line->qty : 0;
4711  }
4712 
4713  $weight = !empty($line->weight) ? $line->weight : 0;
4714  ($weight == 0 && !empty($line->product->weight)) ? $weight = $line->product->weight : 0;
4715  $volume = !empty($line->volume) ? $line->volume : 0;
4716  ($volume == 0 && !empty($line->product->volume)) ? $volume = $line->product->volume : 0;
4717 
4718  $weight_units = !empty($line->weight_units) ? $line->weight_units : 0;
4719  ($weight_units == 0 && !empty($line->product->weight_units)) ? $weight_units = $line->product->weight_units : 0;
4720  $volume_units = !empty($line->volume_units) ? $line->volume_units : 0;
4721  ($volume_units == 0 && !empty($line->product->volume_units)) ? $volume_units = $line->product->volume_units : 0;
4722 
4723  $weightUnit = 0;
4724  $volumeUnit = 0;
4725  if (!empty($weight_units)) {
4726  $weightUnit = $weight_units;
4727  }
4728  if (!empty($volume_units)) {
4729  $volumeUnit = $volume_units;
4730  }
4731 
4732  if (empty($totalWeight)) {
4733  $totalWeight = 0; // Avoid warning because $totalWeight is ''
4734  }
4735  if (empty($totalVolume)) {
4736  $totalVolume = 0; // Avoid warning because $totalVolume is ''
4737  }
4738 
4739  //var_dump($line->volume_units);
4740  if ($weight_units < 50) { // < 50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch)
4741  $trueWeightUnit = pow(10, $weightUnit);
4742  $totalWeight += $weight * $qty * $trueWeightUnit;
4743  } else {
4744  if ($weight_units == 99) {
4745  // conversion 1 Pound = 0.45359237 KG
4746  $trueWeightUnit = 0.45359237;
4747  $totalWeight += $weight * $qty * $trueWeightUnit;
4748  } elseif ($weight_units == 98) {
4749  // conversion 1 Ounce = 0.0283495 KG
4750  $trueWeightUnit = 0.0283495;
4751  $totalWeight += $weight * $qty * $trueWeightUnit;
4752  } else {
4753  $totalWeight += $weight * $qty; // This may be wrong if we mix different units
4754  }
4755  }
4756  if ($volume_units < 50) { // >50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch)
4757  //print $line->volume."x".$line->volume_units."x".($line->volume_units < 50)."x".$volumeUnit;
4758  $trueVolumeUnit = pow(10, $volumeUnit);
4759  //print $line->volume;
4760  $totalVolume += $volume * $qty * $trueVolumeUnit;
4761  } else {
4762  $totalVolume += $volume * $qty; // This may be wrong if we mix different units
4763  }
4764  }
4765 
4766  return array('weight'=>$totalWeight, 'volume'=>$totalVolume, 'ordered'=>$totalOrdered, 'toship'=>$totalToShip);
4767  }
4768 
4769 
4775  public function setExtraParameters()
4776  {
4777  $this->db->begin();
4778 
4779  $extraparams = (!empty($this->extraparams) ? json_encode($this->extraparams) : null);
4780 
4781  $sql = "UPDATE ".$this->db->prefix().$this->table_element;
4782  $sql .= " SET extraparams = ".(!empty($extraparams) ? "'".$this->db->escape($extraparams)."'" : "null");
4783  $sql .= " WHERE rowid = ".((int) $this->id);
4784 
4785  dol_syslog(get_class($this)."::setExtraParameters", LOG_DEBUG);
4786  $resql = $this->db->query($sql);
4787  if (!$resql) {
4788  $this->error = $this->db->lasterror();
4789  $this->db->rollback();
4790  return -1;
4791  } else {
4792  $this->db->commit();
4793  return 1;
4794  }
4795  }
4796 
4797 
4798  // --------------------
4799  // TODO: All functions here must be redesigned and moved as they are not business functions but output functions
4800  // --------------------
4801 
4802  /* This is to show add lines */
4803 
4813  public function formAddObjectLine($dateSelector, $seller, $buyer, $defaulttpldir = '/core/tpl')
4814  {
4815  global $conf, $user, $langs, $object, $hookmanager, $extrafields;
4816  global $form;
4817 
4818  // Line extrafield
4819  if (!is_object($extrafields)) {
4820  require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
4821  $extrafields = new ExtraFields($this->db);
4822  }
4823  $extrafields->fetch_name_optionals_label($this->table_element_line);
4824 
4825  // Output template part (modules that overwrite templates must declare this into descriptor)
4826  // Use global variables + $dateSelector + $seller and $buyer
4827  // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook 'formAddObjectLine'.
4828  $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
4829  foreach ($dirtpls as $module => $reldir) {
4830  if (!empty($module)) {
4831  $tpl = dol_buildpath($reldir.'/objectline_create.tpl.php');
4832  } else {
4833  $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_create.tpl.php';
4834  }
4835 
4836  if (empty($conf->file->strict_mode)) {
4837  $res = @include $tpl;
4838  } else {
4839  $res = include $tpl; // for debug
4840  }
4841  if ($res) {
4842  break;
4843  }
4844  }
4845  }
4846 
4847 
4848 
4849  /* This is to show array of line of details */
4850 
4851 
4866  public function printObjectLines($action, $seller, $buyer, $selected = 0, $dateSelector = 0, $defaulttpldir = '/core/tpl')
4867  {
4868  global $conf, $hookmanager, $langs, $user, $form, $extrafields, $object;
4869  // TODO We should not use global var for this
4870  global $inputalsopricewithtax, $usemargins, $disableedit, $disablemove, $disableremove, $outputalsopricetotalwithtax;
4871 
4872  // Define usemargins
4873  $usemargins = 0;
4874  if (!empty($conf->margin->enabled) && !empty($this->element) && in_array($this->element, array('facture', 'facturerec', 'propal', 'commande'))) {
4875  $usemargins = 1;
4876  }
4877 
4878  $num = count($this->lines);
4879 
4880  // Line extrafield
4881  if (!is_object($extrafields)) {
4882  require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
4883  $extrafields = new ExtraFields($this->db);
4884  }
4885  $extrafields->fetch_name_optionals_label($this->table_element_line);
4886 
4887  $parameters = array('num'=>$num, 'dateSelector'=>$dateSelector, 'seller'=>$seller, 'buyer'=>$buyer, 'selected'=>$selected, 'table_element_line'=>$this->table_element_line);
4888  $reshook = $hookmanager->executeHooks('printObjectLineTitle', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
4889  if (empty($reshook)) {
4890  // Output template part (modules that overwrite templates must declare this into descriptor)
4891  // Use global variables + $dateSelector + $seller and $buyer
4892  // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook.
4893  $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
4894  foreach ($dirtpls as $module => $reldir) {
4895  if (!empty($module)) {
4896  $tpl = dol_buildpath($reldir.'/objectline_title.tpl.php');
4897  } else {
4898  $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_title.tpl.php';
4899  }
4900  if (empty($conf->file->strict_mode)) {
4901  $res = @include $tpl;
4902  } else {
4903  $res = include $tpl; // for debug
4904  }
4905  if ($res) {
4906  break;
4907  }
4908  }
4909  }
4910 
4911  $i = 0;
4912 
4913  print "<!-- begin printObjectLines() --><tbody>\n";
4914  foreach ($this->lines as $line) {
4915  //Line extrafield
4916  $line->fetch_optionals();
4917 
4918  //if (is_object($hookmanager) && (($line->product_type == 9 && ! empty($line->special_code)) || ! empty($line->fk_parent_line)))
4919  if (is_object($hookmanager)) { // Old code is commented on preceding line.
4920  if (empty($line->fk_parent_line)) {
4921  $parameters = array('line'=>$line, 'num'=>$num, 'i'=>$i, 'dateSelector'=>$dateSelector, 'seller'=>$seller, 'buyer'=>$buyer, 'selected'=>$selected, 'table_element_line'=>$line->table_element);
4922  $reshook = $hookmanager->executeHooks('printObjectLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
4923  } else {
4924  $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);
4925  $reshook = $hookmanager->executeHooks('printObjectSubLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
4926  }
4927  }
4928  if (empty($reshook)) {
4929  $this->printObjectLine($action, $line, '', $num, $i, $dateSelector, $seller, $buyer, $selected, $extrafields, $defaulttpldir);
4930  }
4931 
4932  $i++;
4933  }
4934  print "</tbody><!-- end printObjectLines() -->\n";
4935  }
4936 
4954  public function printObjectLine($action, $line, $var, $num, $i, $dateSelector, $seller, $buyer, $selected = 0, $extrafields = null, $defaulttpldir = '/core/tpl')
4955  {
4956  global $conf, $langs, $user, $object, $hookmanager;
4957  global $form;
4958  global $object_rights, $disableedit, $disablemove, $disableremove; // TODO We should not use global var for this !
4959 
4960  $object_rights = $this->getRights();
4961 
4962  $element = $this->element;
4963 
4964  $text = '';
4965  $description = '';
4966 
4967  // Line in view mode
4968  if ($action != 'editline' || $selected != $line->id) {
4969  // Product
4970  if ($line->fk_product > 0) {
4971  $product_static = new Product($this->db);
4972  $product_static->fetch($line->fk_product);
4973 
4974  $product_static->ref = $line->ref; //can change ref in hook
4975  $product_static->label = !empty($line->label) ? $line->label : ""; //can change label in hook
4976 
4977  $text = $product_static->getNomUrl(1);
4978 
4979  // Define output language and label
4980  if (!empty($conf->global->MAIN_MULTILANGS)) {
4981  if (property_exists($this, 'socid') && !is_object($this->thirdparty)) {
4982  dol_print_error('', 'Error: Method printObjectLine was called on an object and object->fetch_thirdparty was not done before');
4983  return;
4984  }
4985 
4986  $prod = new Product($this->db);
4987  $prod->fetch($line->fk_product);
4988 
4989  $outputlangs = $langs;
4990  $newlang = '';
4991  if (empty($newlang) && GETPOST('lang_id', 'aZ09')) {
4992  $newlang = GETPOST('lang_id', 'aZ09');
4993  }
4994  if (!empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE) && empty($newlang) && is_object($this->thirdparty)) {
4995  $newlang = $this->thirdparty->default_lang; // To use language of customer
4996  }
4997  if (!empty($newlang)) {
4998  $outputlangs = new Translate("", $conf);
4999  $outputlangs->setDefaultLang($newlang);
5000  }
5001 
5002  $label = (!empty($prod->multilangs[$outputlangs->defaultlang]["label"])) ? $prod->multilangs[$outputlangs->defaultlang]["label"] : $line->product_label;
5003  } else {
5004  $label = $line->product_label;
5005  }
5006 
5007  $text .= ' - '.(!empty($line->label) ? $line->label : $label);
5008  $description .= (!empty($conf->global->PRODUIT_DESC_IN_FORM) ? '' : (!empty($line->description) ? dol_htmlentitiesbr($line->description) : '')); // Description is what to show on popup. We shown nothing if already into desc.
5009  }
5010 
5011  $line->pu_ttc = price2num((!empty($line->subprice) ? $line->subprice : 0) * (1 + ((!empty($line->tva_tx) ? $line->tva_tx : 0) / 100)), 'MU');
5012 
5013  // Output template part (modules that overwrite templates must declare this into descriptor)
5014  // Use global variables + $dateSelector + $seller and $buyer
5015  // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook printObjectLine and printObjectSubLine.
5016  $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
5017  foreach ($dirtpls as $module => $reldir) {
5018  if (!empty($module)) {
5019  $tpl = dol_buildpath($reldir.'/objectline_view.tpl.php');
5020  } else {
5021  $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_view.tpl.php';
5022  }
5023 
5024  if (empty($conf->file->strict_mode)) {
5025  $res = @include $tpl;
5026  } else {
5027  $res = include $tpl; // for debug
5028  }
5029  if ($res) {
5030  break;
5031  }
5032  }
5033  }
5034 
5035  // Line in update mode
5036  if ($this->statut == 0 && $action == 'editline' && $selected == $line->id) {
5037  $label = (!empty($line->label) ? $line->label : (($line->fk_product > 0) ? $line->product_label : ''));
5038 
5039  $line->pu_ttc = price2num($line->subprice * (1 + ($line->tva_tx / 100)), 'MU');
5040 
5041  // Output template part (modules that overwrite templates must declare this into descriptor)
5042  // Use global variables + $dateSelector + $seller and $buyer
5043  // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook printObjectLine and printObjectSubLine.
5044  $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
5045  foreach ($dirtpls as $module => $reldir) {
5046  if (!empty($module)) {
5047  $tpl = dol_buildpath($reldir.'/objectline_edit.tpl.php');
5048  } else {
5049  $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_edit.tpl.php';
5050  }
5051 
5052  if (empty($conf->file->strict_mode)) {
5053  $res = @include $tpl;
5054  } else {
5055  $res = include $tpl; // for debug
5056  }
5057  if ($res) {
5058  break;
5059  }
5060  }
5061  }
5062  }
5063 
5064 
5065  /* This is to show array of line of details of source object */
5066 
5067 
5078  public function printOriginLinesList($restrictlist = '', $selectedLines = array())
5079  {
5080  global $langs, $hookmanager, $conf, $form, $action;
5081 
5082  print '<tr class="liste_titre">';
5083  print '<td class="linecolref">'.$langs->trans('Ref').'</td>';
5084  print '<td class="linecoldescription">'.$langs->trans('Description').'</td>';
5085  print '<td class="linecolvat right">'.$langs->trans('VATRate').'</td>';
5086  print '<td class="linecoluht right">'.$langs->trans('PriceUHT').'</td>';
5087  if (!empty($conf->multicurrency->enabled)) {
5088  print '<td class="linecoluht_currency right">'.$langs->trans('PriceUHTCurrency').'</td>';
5089  }
5090  print '<td class="linecolqty right">'.$langs->trans('Qty').'</td>';
5091  if (!empty($conf->global->PRODUCT_USE_UNITS)) {
5092  print '<td class="linecoluseunit left">'.$langs->trans('Unit').'</td>';
5093  }
5094  print '<td class="linecoldiscount right">'.$langs->trans('ReductionShort').'</td>';
5095  print '<td class="linecolht right">'.$langs->trans('TotalHT').'</td>';
5096  print '<td class="center">'.$form->showCheckAddButtons('checkforselect', 1).'</td>';
5097  print '</tr>';
5098  $i = 0;
5099 
5100  if (!empty($this->lines)) {
5101  foreach ($this->lines as $line) {
5102  $reshook = 0;
5103  //if (is_object($hookmanager) && (($line->product_type == 9 && !empty($line->special_code)) || !empty($line->fk_parent_line))) {
5104  if (is_object($hookmanager)) { // Old code is commented on preceding line.
5105  $parameters = array('line'=>$line, 'i'=>$i, 'restrictlist'=>$restrictlist, 'selectedLines'=> $selectedLines);
5106  if (!empty($line->fk_parent_line)) { $parameters['fk_parent_line'] = $line->fk_parent_line; }
5107  $reshook = $hookmanager->executeHooks('printOriginObjectLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
5108  }
5109  if (empty($reshook)) {
5110  $this->printOriginLine($line, '', $restrictlist, '/core/tpl', $selectedLines);
5111  }
5112 
5113  $i++;
5114  }
5115  }
5116  }
5117 
5131  public function printOriginLine($line, $var, $restrictlist = '', $defaulttpldir = '/core/tpl', $selectedLines = array())
5132  {
5133  global $langs, $conf;
5134 
5135  //var_dump($line);
5136  if (!empty($line->date_start)) {
5137  $date_start = $line->date_start;
5138  } else {
5139  $date_start = $line->date_debut_prevue;
5140  if ($line->date_debut_reel) {
5141  $date_start = $line->date_debut_reel;
5142  }
5143  }
5144  if (!empty($line->date_end)) {
5145  $date_end = $line->date_end;
5146  } else {
5147  $date_end = $line->date_fin_prevue;
5148  if ($line->date_fin_reel) {
5149  $date_end = $line->date_fin_reel;
5150  }
5151  }
5152 
5153  $this->tpl['id'] = $line->id;
5154 
5155  $this->tpl['label'] = '';
5156  if (!empty($line->fk_parent_line)) {
5157  $this->tpl['label'] .= img_picto('', 'rightarrow');
5158  }
5159 
5160  if (($line->info_bits & 2) == 2) { // TODO Not sure this is used for source object
5161  $discount = new DiscountAbsolute($this->db);
5162  $discount->fk_soc = $this->socid;
5163  $this->tpl['label'] .= $discount->getNomUrl(0, 'discount');
5164  } elseif (!empty($line->fk_product)) {
5165  $productstatic = new Product($this->db);
5166  $productstatic->id = $line->fk_product;
5167  $productstatic->ref = $line->ref;
5168  $productstatic->type = $line->fk_product_type;
5169  if (empty($productstatic->ref)) {
5170  $line->fetch_product();
5171  $productstatic = $line->product;
5172  }
5173 
5174  $this->tpl['label'] .= $productstatic->getNomUrl(1);
5175  $this->tpl['label'] .= ' - '.(!empty($line->label) ? $line->label : $line->product_label);
5176  // Dates
5177  if ($line->product_type == 1 && ($date_start || $date_end)) {
5178  $this->tpl['label'] .= get_date_range($date_start, $date_end);
5179  }
5180  } else {
5181  $this->tpl['label'] .= ($line->product_type == -1 ? '&nbsp;' : ($line->product_type == 1 ? img_object($langs->trans(''), 'service') : img_object($langs->trans(''), 'product')));
5182  if (!empty($line->desc)) {
5183  $this->tpl['label'] .= $line->desc;
5184  } else {
5185  $this->tpl['label'] .= ($line->label ? '&nbsp;'.$line->label : '');
5186  }
5187 
5188  // Dates
5189  if ($line->product_type == 1 && ($date_start || $date_end)) {
5190  $this->tpl['label'] .= get_date_range($date_start, $date_end);
5191  }
5192  }
5193 
5194  if (!empty($line->desc)) {
5195  if ($line->desc == '(CREDIT_NOTE)') { // TODO Not sure this is used for source object
5196  $discount = new DiscountAbsolute($this->db);
5197  $discount->fetch($line->fk_remise_except);
5198  $this->tpl['description'] = $langs->transnoentities("DiscountFromCreditNote", $discount->getNomUrl(0));
5199  } elseif ($line->desc == '(DEPOSIT)') { // TODO Not sure this is used for source object
5200  $discount = new DiscountAbsolute($this->db);
5201  $discount->fetch($line->fk_remise_except);
5202  $this->tpl['description'] = $langs->transnoentities("DiscountFromDeposit", $discount->getNomUrl(0));
5203  } elseif ($line->desc == '(EXCESS RECEIVED)') {
5204  $discount = new DiscountAbsolute($this->db);
5205  $discount->fetch($line->fk_remise_except);
5206  $this->tpl['description'] = $langs->transnoentities("DiscountFromExcessReceived", $discount->getNomUrl(0));
5207  } elseif ($line->desc == '(EXCESS PAID)') {
5208  $discount = new DiscountAbsolute($this->db);
5209  $discount->fetch($line->fk_remise_except);
5210  $this->tpl['description'] = $langs->transnoentities("DiscountFromExcessPaid", $discount->getNomUrl(0));
5211  } else {
5212  $this->tpl['description'] = dol_trunc($line->desc, 60);
5213  }
5214  } else {
5215  $this->tpl['description'] = '&nbsp;';
5216  }
5217 
5218  // VAT Rate
5219  $this->tpl['vat_rate'] = vatrate($line->tva_tx, true);
5220  $this->tpl['vat_rate'] .= (($line->info_bits & 1) == 1) ? '*' : '';
5221  if (!empty($line->vat_src_code) && !preg_match('/\(/', $this->tpl['vat_rate'])) {
5222  $this->tpl['vat_rate'] .= ' ('.$line->vat_src_code.')';
5223  }
5224 
5225  $this->tpl['price'] = price($line->subprice);
5226  $this->tpl['total_ht'] = price($line->total_ht);
5227  $this->tpl['multicurrency_price'] = price($line->multicurrency_subprice);
5228  $this->tpl['qty'] = (($line->info_bits & 2) != 2) ? $line->qty : '&nbsp;';
5229  if (!empty($conf->global->PRODUCT_USE_UNITS)) {
5230  $this->tpl['unit'] = $langs->transnoentities($line->getLabelOfUnit('long'));
5231  }
5232  $this->tpl['remise_percent'] = (($line->info_bits & 2) != 2) ? vatrate($line->remise_percent, true) : '&nbsp;';
5233 
5234  // Is the line strike or not
5235  $this->tpl['strike'] = 0;
5236  if ($restrictlist == 'services' && $line->product_type != Product::TYPE_SERVICE) {
5237  $this->tpl['strike'] = 1;
5238  }
5239 
5240  // Output template part (modules that overwrite templates must declare this into descriptor)
5241  // Use global variables + $dateSelector + $seller and $buyer
5242  $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
5243  foreach ($dirtpls as $module => $reldir) {
5244  if (!empty($module)) {
5245  $tpl = dol_buildpath($reldir.'/originproductline.tpl.php');
5246  } else {
5247  $tpl = DOL_DOCUMENT_ROOT.$reldir.'/originproductline.tpl.php';
5248  }
5249 
5250  if (empty($conf->file->strict_mode)) {
5251  $res = @include $tpl;
5252  } else {
5253  $res = include $tpl; // for debug
5254  }
5255  if ($res) {
5256  break;
5257  }
5258  }
5259  }
5260 
5261 
5262  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5273  public function add_element_resource($resource_id, $resource_type, $busy = 0, $mandatory = 0)
5274  {
5275  // phpcs:enable
5276  $this->db->begin();
5277 
5278  $sql = "INSERT INTO ".$this->db->prefix()."element_resources (";
5279  $sql .= "resource_id";
5280  $sql .= ", resource_type";
5281  $sql .= ", element_id";
5282  $sql .= ", element_type";
5283  $sql .= ", busy";
5284  $sql .= ", mandatory";
5285  $sql .= ") VALUES (";
5286  $sql .= $resource_id;
5287  $sql .= ", '".$this->db->escape($resource_type)."'";
5288  $sql .= ", '".$this->db->escape($this->id)."'";
5289  $sql .= ", '".$this->db->escape($this->element)."'";
5290  $sql .= ", '".$this->db->escape($busy)."'";
5291  $sql .= ", '".$this->db->escape($mandatory)."'";
5292  $sql .= ")";
5293 
5294  dol_syslog(get_class($this)."::add_element_resource", LOG_DEBUG);
5295  if ($this->db->query($sql)) {
5296  $this->db->commit();
5297  return 1;
5298  } else {
5299  $this->error = $this->db->lasterror();
5300  $this->db->rollback();
5301  return 0;
5302  }
5303  }
5304 
5305  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5314  public function delete_resource($rowid, $element, $notrigger = 0)
5315  {
5316  // phpcs:enable
5317  global $user;
5318 
5319  $this->db->begin();
5320 
5321  $sql = "DELETE FROM ".$this->db->prefix()."element_resources";
5322  $sql .= " WHERE rowid = ".((int) $rowid);
5323 
5324  dol_syslog(get_class($this)."::delete_resource", LOG_DEBUG);
5325 
5326  $resql = $this->db->query($sql);
5327  if (!$resql) {
5328  $this->error = $this->db->lasterror();
5329  $this->db->rollback();
5330  return -1;
5331  } else {
5332  if (!$notrigger) {
5333  $result = $this->call_trigger(strtoupper($element).'_DELETE_RESOURCE', $user);
5334  if ($result < 0) {
5335  $this->db->rollback();
5336  return -1;
5337  }
5338  }
5339  $this->db->commit();
5340  return 1;
5341  }
5342  }
5343 
5344 
5350  public function __clone()
5351  {
5352  // Force a copy of this->lines, otherwise it will point to same object.
5353  if (isset($this->lines) && is_array($this->lines)) {
5354  $nboflines = count($this->lines);
5355  for ($i = 0; $i < $nboflines; $i++) {
5356  $this->lines[$i] = clone $this->lines[$i];
5357  }
5358  }
5359  }
5360 
5374  protected function commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams = null)
5375  {
5376  global $conf, $langs, $user, $hookmanager, $action;
5377 
5378  $srctemplatepath = '';
5379 
5380  $parameters = array('modelspath'=>$modelspath, 'modele'=>$modele, 'outputlangs'=>$outputlangs, 'hidedetails'=>$hidedetails, 'hidedesc'=>$hidedesc, 'hideref'=>$hideref, 'moreparams'=>$moreparams);
5381  $reshook = $hookmanager->executeHooks('commonGenerateDocument', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
5382 
5383  if (empty($reshook)) {
5384  dol_syslog("commonGenerateDocument modele=".$modele." outputlangs->defaultlang=".(is_object($outputlangs) ? $outputlangs->defaultlang : 'null'));
5385 
5386  if (empty($modele)) {
5387  $this->error = 'BadValueForParameterModele';
5388  return -1;
5389  }
5390 
5391  // Increase limit for PDF build
5392  $err = error_reporting();
5393  error_reporting(0);
5394  @set_time_limit(120);
5395  error_reporting($err);
5396 
5397  // If selected model is a filename template (then $modele="modelname" or "modelname:filename")
5398  $tmp = explode(':', $modele, 2);
5399  if (!empty($tmp[1])) {
5400  $modele = $tmp[0];
5401  $srctemplatepath = $tmp[1];
5402  }
5403 
5404  // Search template files
5405  $file = '';
5406  $classname = '';
5407  $filefound = '';
5408  $dirmodels = array('/');
5409  if (is_array($conf->modules_parts['models'])) {
5410  $dirmodels = array_merge($dirmodels, $conf->modules_parts['models']);
5411  }
5412  foreach ($dirmodels as $reldir) {
5413  foreach (array('doc', 'pdf') as $prefix) {
5414  if (in_array(get_class($this), array('Adherent'))) {
5415  // Member module use prefix_modele.class.php
5416  $file = $prefix."_".$modele.".class.php";
5417  } else {
5418  // Other module use prefix_modele.modules.php
5419  $file = $prefix."_".$modele.".modules.php";
5420  }
5421 
5422  // On verifie l'emplacement du modele
5423  $file = dol_buildpath($reldir.$modelspath.$file, 0);
5424  if (file_exists($file)) {
5425  $filefound = $file;
5426  $classname = $prefix.'_'.$modele;
5427  break;
5428  }
5429  }
5430  if ($filefound) {
5431  break;
5432  }
5433  }
5434 
5435  // If generator was found
5436  if ($filefound) {
5437  global $db; // Required to solve a conception default making an include of code using $db instead of $this->db just after.
5438 
5439  require_once $file;
5440 
5441  $obj = new $classname($this->db);
5442 
5443  // If generator is ODT, we must have srctemplatepath defined, if not we set it.
5444  if ($obj->type == 'odt' && empty($srctemplatepath)) {
5445  $varfortemplatedir = $obj->scandir;
5446  if ($varfortemplatedir && !empty($conf->global->$varfortemplatedir)) {
5447  $dirtoscan = $conf->global->$varfortemplatedir;
5448 
5449  $listoffiles = array();
5450 
5451  // Now we add first model found in directories scanned
5452  $listofdir = explode(',', $dirtoscan);
5453  foreach ($listofdir as $key => $tmpdir) {
5454  $tmpdir = trim($tmpdir);
5455  $tmpdir = preg_replace('/DOL_DATA_ROOT/', DOL_DATA_ROOT, $tmpdir);
5456  if (!$tmpdir) {
5457  unset($listofdir[$key]);
5458  continue;
5459  }
5460  if (is_dir($tmpdir)) {
5461  $tmpfiles = dol_dir_list($tmpdir, 'files', 0, '\.od(s|t)$', '', 'name', SORT_ASC, 0);
5462  if (count($tmpfiles)) {
5463  $listoffiles = array_merge($listoffiles, $tmpfiles);
5464  }
5465  }
5466  }
5467 
5468  if (count($listoffiles)) {
5469  foreach ($listoffiles as $record) {
5470  $srctemplatepath = $record['fullname'];
5471  break;
5472  }
5473  }
5474  }
5475 
5476  if (empty($srctemplatepath)) {
5477  $this->error = 'ErrorGenerationAskedForOdtTemplateWithSrcFileNotDefined';
5478  return -1;
5479  }
5480  }
5481 
5482  if ($obj->type == 'odt' && !empty($srctemplatepath)) {
5483  if (!dol_is_file($srctemplatepath)) {
5484  dol_syslog("Failed to locate template file ".$srctemplatepath, LOG_WARNING);
5485  $this->error = 'ErrorGenerationAskedForOdtTemplateWithSrcFileNotFound';
5486  return -1;
5487  }
5488  }
5489 
5490  // We save charset_output to restore it because write_file can change it if needed for
5491  // output format that does not support UTF8.
5492  $sav_charset_output = empty($outputlangs->charset_output) ? '' : $outputlangs->charset_output;
5493 
5494  if (in_array(get_class($this), array('Adherent'))) {
5495  $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, 'member', 1, 'tmp_cards', $moreparams);
5496  } else {
5497  $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, $hidedetails, $hidedesc, $hideref, $moreparams);
5498  }
5499  // After call of write_file $obj->result['fullpath'] is set with generated file. It will be used to update the ECM database index.
5500 
5501  if ($resultwritefile > 0) {
5502  $outputlangs->charset_output = $sav_charset_output;
5503 
5504  // We delete old preview
5505  require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
5506  dol_delete_preview($this);
5507 
5508  // Index file in database
5509  if (!empty($obj->result['fullpath'])) {
5510  $destfull = $obj->result['fullpath'];
5511 
5512  // Update the last_main_doc field into main object (if document generator has property ->update_main_doc_field set)
5513  $update_main_doc_field = 0;
5514  if (!empty($obj->update_main_doc_field)) {
5515  $update_main_doc_field = 1;
5516  }
5517 
5518  $this->indexFile($destfull, $update_main_doc_field);
5519  } else {
5520  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);
5521  }
5522 
5523  // Success in building document. We build meta file.
5524  dol_meta_create($this);
5525 
5526  return 1;
5527  } else {
5528  $outputlangs->charset_output = $sav_charset_output;
5529  $this->error = $obj->error;
5530  $this->errors = $obj->errors;
5531  dol_syslog("Error generating document for ".__CLASS__.". Error: ".$obj->error, LOG_ERR);
5532  return -1;
5533  }
5534  } else {
5535  if (!$filefound) {
5536  $this->error = $langs->trans("Error").' Failed to load doc generator with modelpaths='.$modelspath.' - modele='.$modele;
5537  $this->errors[] = $this->error;
5538  dol_syslog($this->error, LOG_ERR);
5539  } else {
5540  $this->error = $langs->trans("Error")." ".$langs->trans("ErrorFileDoesNotExists", $filefound);
5541  $this->errors[] = $this->error;
5542  dol_syslog($this->error, LOG_ERR);
5543  }
5544  return -1;
5545  }
5546  } else {
5547  return $reshook;
5548  }
5549  }
5550 
5560  public function indexFile($destfull, $update_main_doc_field)
5561  {
5562  global $conf, $user;
5563 
5564  $upload_dir = dirname($destfull);
5565  $destfile = basename($destfull);
5566  $rel_dir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $upload_dir);
5567 
5568  if (!preg_match('/[\\/]temp[\\/]|[\\/]thumbs|\.meta$/', $rel_dir)) { // If not a tmp dir
5569  $filename = basename($destfile);
5570  $rel_dir = preg_replace('/[\\/]$/', '', $rel_dir);
5571  $rel_dir = preg_replace('/^[\\/]/', '', $rel_dir);
5572 
5573  include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
5574  $ecmfile = new EcmFiles($this->db);
5575  $result = $ecmfile->fetch(0, '', ($rel_dir ? $rel_dir.'/' : '').$filename);
5576 
5577  // Set the public "share" key
5578  $setsharekey = false;
5579  if ($this->element == 'propal' || $this->element == 'proposal') {
5580  if (!isset($conf->global->PROPOSAL_ALLOW_ONLINESIGN) || !empty($conf->global->PROPOSAL_ALLOW_ONLINESIGN)) {
5581  $setsharekey = true; // feature to make online signature is not set or set to on (default)
5582  }
5583  if (!empty($conf->global->PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD)) {
5584  $setsharekey = true;
5585  }
5586  }
5587  if ($this->element == 'commande' && !empty($conf->global->ORDER_ALLOW_EXTERNAL_DOWNLOAD)) {
5588  $setsharekey = true;
5589  }
5590  if ($this->element == 'facture' && !empty($conf->global->INVOICE_ALLOW_EXTERNAL_DOWNLOAD)) {
5591  $setsharekey = true;
5592  }
5593  if ($this->element == 'bank_account' && !empty($conf->global->BANK_ACCOUNT_ALLOW_EXTERNAL_DOWNLOAD)) {
5594  $setsharekey = true;
5595  }
5596  if ($this->element == 'contrat' && !empty($conf->global->CONTRACT_ALLOW_EXTERNAL_DOWNLOAD)) {
5597  $setsharekey = true;
5598  }
5599  if ($this->element == 'supplier_proposal' && !empty($conf->global->SUPPLIER_PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD)) {
5600  $setsharekey = true;
5601  }
5602 
5603  if ($setsharekey) {
5604  if (empty($ecmfile->share)) { // Because object not found or share not set yet
5605  require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
5606  $ecmfile->share = getRandomPassword(true);
5607  }
5608  }
5609 
5610  if ($result > 0) {
5611  $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
5612  $ecmfile->fullpath_orig = '';
5613  $ecmfile->gen_or_uploaded = 'generated';
5614  $ecmfile->description = ''; // indexed content
5615  $ecmfile->keywords = ''; // keyword content
5616  $result = $ecmfile->update($user);
5617  if ($result < 0) {
5618  setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
5619  return -1;
5620  }
5621  } else {
5622  $ecmfile->entity = $conf->entity;
5623  $ecmfile->filepath = $rel_dir;
5624  $ecmfile->filename = $filename;
5625  $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
5626  $ecmfile->fullpath_orig = '';
5627  $ecmfile->gen_or_uploaded = 'generated';
5628  $ecmfile->description = ''; // indexed content
5629  $ecmfile->keywords = ''; // keyword content
5630  $ecmfile->src_object_type = $this->table_element; // $this->table_name is 'myobject' or 'mymodule_myobject'.
5631  $ecmfile->src_object_id = $this->id;
5632 
5633  $result = $ecmfile->create($user);
5634  if ($result < 0) {
5635  setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
5636  return -1;
5637  }
5638  }
5639 
5640  /*$this->result['fullname']=$destfull;
5641  $this->result['filepath']=$ecmfile->filepath;
5642  $this->result['filename']=$ecmfile->filename;*/
5643  //var_dump($obj->update_main_doc_field);exit;
5644 
5645  if ($update_main_doc_field && !empty($this->table_element)) {
5646  $sql = "UPDATE ".$this->db->prefix().$this->table_element." SET last_main_doc = '".$this->db->escape($ecmfile->filepath."/".$ecmfile->filename)."'";
5647  $sql .= " WHERE rowid = ".((int) $this->id);
5648 
5649  $resql = $this->db->query($sql);
5650  if (!$resql) {
5651  dol_print_error($this->db);
5652  return -1;
5653  } else {
5654  $this->last_main_doc = $ecmfile->filepath.'/'.$ecmfile->filename;
5655  }
5656  }
5657  }
5658 
5659  return 1;
5660  }
5661 
5669  public function addThumbs($file)
5670  {
5671  global $maxwidthsmall, $maxheightsmall, $maxwidthmini, $maxheightmini, $quality;
5672 
5673  require_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php'; // This define also $maxwidthsmall, $quality, ...
5674 
5675  $file_osencoded = dol_osencode($file);
5676  if (file_exists($file_osencoded)) {
5677  // Create small thumbs for company (Ratio is near 16/9)
5678  // Used on logon for example
5679  vignette($file_osencoded, $maxwidthsmall, $maxheightsmall, '_small', $quality);
5680 
5681  // Create mini thumbs for company (Ratio is near 16/9)
5682  // Used on menu or for setup page for example
5683  vignette($file_osencoded, $maxwidthmini, $maxheightmini, '_mini', $quality);
5684  }
5685  }
5686 
5687 
5688  /* Functions common to commonobject and commonobjectline */
5689 
5690  /* For default values */
5691 
5704  public function getDefaultCreateValueFor($fieldname, $alternatevalue = null)
5705  {
5706  global $conf, $_POST;
5707 
5708  // If param here has been posted, we use this value first.
5709  if (GETPOSTISSET($fieldname)) {
5710  return GETPOST($fieldname, 'alphanohtml', 3);
5711  }
5712 
5713  if (isset($alternatevalue)) {
5714  return $alternatevalue;
5715  }
5716 
5717  $newelement = $this->element;
5718  if ($newelement == 'facture') {
5719  $newelement = 'invoice';
5720  }
5721  if ($newelement == 'commande') {
5722  $newelement = 'order';
5723  }
5724  if (empty($newelement)) {
5725  dol_syslog("Ask a default value using common method getDefaultCreateValueForField on an object with no property ->element defined. Return empty string.", LOG_WARNING);
5726  return '';
5727  }
5728 
5729  $keyforfieldname = strtoupper($newelement.'_DEFAULT_'.$fieldname);
5730  //var_dump($keyforfieldname);
5731  if (isset($conf->global->$keyforfieldname)) {
5732  return $conf->global->$keyforfieldname;
5733  }
5734 
5735  // TODO Ad here a scan into table llx_overwrite_default with a filter on $this->element and $fieldname
5736  }
5737 
5738 
5739  /* For triggers */
5740 
5741 
5742  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5753  public function call_trigger($triggerName, $user)
5754  {
5755  // phpcs:enable
5756  global $langs, $conf;
5757  if (!empty(self::TRIGGER_PREFIX) && strpos($triggerName, self::TRIGGER_PREFIX . '_') !== 0) {
5758  dol_print_error('', 'The trigger "' . $triggerName . '" does not start with "' . self::TRIGGER_PREFIX . '_" as required.');
5759  exit;
5760  }
5761  if (!is_object($langs)) { // If lang was not defined, we set it. It is required by run_triggers.
5762  include_once DOL_DOCUMENT_ROOT.'/core/class/translate.class.php';
5763  $langs = new Translate('', $conf);
5764  }
5765 
5766  include_once DOL_DOCUMENT_ROOT.'/core/class/interfaces.class.php';
5767  $interface = new Interfaces($this->db);
5768  $result = $interface->run_triggers($triggerName, $this, $user, $langs, $conf);
5769 
5770  if ($result < 0) {
5771  if (!empty($this->errors)) {
5772  $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.
5773  } else {
5774  $this->errors = $interface->errors;
5775  }
5776  }
5777  return $result;
5778  }
5779 
5780 
5781  /* Functions for data in other language */
5782 
5783 
5791  public function fetchValuesForExtraLanguages()
5792  {
5793  // To avoid SQL errors. Probably not the better solution though
5794  if (!$this->element) {
5795  return 0;
5796  }
5797  if (!($this->id > 0)) {
5798  return 0;
5799  }
5800  if (is_array($this->array_languages)) {
5801  return 1;
5802  }
5803 
5804  $this->array_languages = array();
5805 
5806  $element = $this->element;
5807  if ($element == 'categorie') {
5808  $element = 'categories'; // For compatibility
5809  }
5810 
5811  // Request to get translation values for object
5812  $sql = "SELECT rowid, property, lang , value";
5813  $sql .= " FROM ".$this->db->prefix()."object_lang";
5814  $sql .= " WHERE type_object = '".$this->db->escape($element)."'";
5815  $sql .= " AND fk_object = ".((int) $this->id);
5816 
5817  //dol_syslog(get_class($this)."::fetch_optionals get extrafields data for ".$this->table_element, LOG_DEBUG); // Too verbose
5818  $resql = $this->db->query($sql);
5819  if ($resql) {
5820  $numrows = $this->db->num_rows($resql);
5821  if ($numrows) {
5822  $i = 0;
5823  while ($i < $numrows) {
5824  $obj = $this->db->fetch_object($resql);
5825  $key = $obj->property;
5826  $value = $obj->value;
5827  $codelang = $obj->lang;
5828  $type = $this->fields[$key]['type'];
5829 
5830  // we can add this attribute to object
5831  if (preg_match('/date/', $type)) {
5832  $this->array_languages[$key][$codelang] = $this->db->jdate($value);
5833  } else {
5834  $this->array_languages[$key][$codelang] = $value;
5835  }
5836 
5837  $i++;
5838  }
5839  }
5840 
5841  $this->db->free($resql);
5842 
5843  if ($numrows) {
5844  return $numrows;
5845  } else {
5846  return 0;
5847  }
5848  } else {
5849  dol_print_error($this->db);
5850  return -1;
5851  }
5852  }
5853 
5860  public function setValuesForExtraLanguages($onlykey = '')
5861  {
5862  global $_POST, $langs;
5863 
5864  // Get extra fields
5865  foreach ($_POST as $postfieldkey => $postfieldvalue) {
5866  $tmparray = explode('-', $postfieldkey);
5867  if ($tmparray[0] != 'field') {
5868  continue;
5869  }
5870 
5871  $element = $tmparray[1];
5872  $key = $tmparray[2];
5873  $codelang = $tmparray[3];
5874  //var_dump("postfieldkey=".$postfieldkey." element=".$element." key=".$key." codelang=".$codelang);
5875 
5876  if (!empty($onlykey) && $key != $onlykey) {
5877  continue;
5878  }
5879  if ($element != $this->element) {
5880  continue;
5881  }
5882 
5883  $key_type = $this->fields[$key]['type'];
5884 
5885  $enabled = 1;
5886  if (isset($this->fields[$key]['enabled'])) {
5887  $enabled = dol_eval($this->fields[$key]['enabled'], 1, 1, '1');
5888  }
5889  /*$perms = 1;
5890  if (isset($this->fields[$key]['perms']))
5891  {
5892  $perms = dol_eval($this->fields[$key]['perms'], 1, 1, '1');
5893  }*/
5894  if (empty($enabled)) {
5895  continue;
5896  }
5897  //if (empty($perms)) continue;
5898 
5899  if (in_array($key_type, array('date'))) {
5900  // Clean parameters
5901  // TODO GMT date in memory must be GMT so we should add gm=true in parameters
5902  $value_key = dol_mktime(0, 0, 0, GETPOST($postfieldkey."month", 'int'), GETPOST($postfieldkey."day", 'int'), GETPOST($postfieldkey."year", 'int'));
5903  } elseif (in_array($key_type, array('datetime'))) {
5904  // Clean parameters
5905  // TODO GMT date in memory must be GMT so we should add gm=true in parameters
5906  $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'));
5907  } elseif (in_array($key_type, array('checkbox', 'chkbxlst'))) {
5908  $value_arr = GETPOST($postfieldkey, 'array'); // check if an array
5909  if (!empty($value_arr)) {
5910  $value_key = implode(',', $value_arr);
5911  } else {
5912  $value_key = '';
5913  }
5914  } elseif (in_array($key_type, array('price', 'double'))) {
5915  $value_arr = GETPOST($postfieldkey, 'alpha');
5916  $value_key = price2num($value_arr);
5917  } else {
5918  $value_key = GETPOST($postfieldkey);
5919  if (in_array($key_type, array('link')) && $value_key == '-1') {
5920  $value_key = '';
5921  }
5922  }
5923 
5924  $this->array_languages[$key][$codelang] = $value_key;
5925 
5926  /*if ($nofillrequired) {
5927  $langs->load('errors');
5928  setEventMessages($langs->trans('ErrorFieldsRequired').' : '.implode(', ', $error_field_required), null, 'errors');
5929  return -1;
5930  }*/
5931  }
5932 
5933  return 1;
5934  }
5935 
5936 
5937  /* Functions for extrafields */
5938 
5945  public function fetchNoCompute($id)
5946  {
5947  global $conf;
5948 
5949  $savDisableCompute = $conf->disable_compute;
5950  $conf->disable_compute = 1;
5951 
5952  $ret = $this->fetch($id);
5953 
5954  $conf->disable_compute = $savDisableCompute;
5955 
5956  return $ret;
5957  }
5958 
5959  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5969  public function fetch_optionals($rowid = null, $optionsArray = null)
5970  {
5971  // phpcs:enable
5972  global $conf, $extrafields;
5973 
5974  if (empty($rowid)) {
5975  $rowid = $this->id;
5976  }
5977  if (empty($rowid) && isset($this->rowid)) {
5978  $rowid = $this->rowid; // deprecated
5979  }
5980 
5981  // To avoid SQL errors. Probably not the better solution though
5982  if (!$this->table_element) {
5983  return 0;
5984  }
5985 
5986  $this->array_options = array();
5987 
5988  if (!is_array($optionsArray)) {
5989  // If $extrafields is not a known object, we initialize it. Best practice is to have $extrafields defined into card.php or list.php page.
5990  if (!isset($extrafields) || !is_object($extrafields)) {
5991  require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
5992  $extrafields = new ExtraFields($this->db);
5993  }
5994 
5995  // Load array of extrafields for elementype = $this->table_element
5996  if (empty($extrafields->attributes[$this->table_element]['loaded'])) {
5997  $extrafields->fetch_name_optionals_label($this->table_element);
5998  }
5999  $optionsArray = (!empty($extrafields->attributes[$this->table_element]['label']) ? $extrafields->attributes[$this->table_element]['label'] : null);
6000  } else {
6001  global $extrafields;
6002  dol_syslog("Warning: fetch_optionals was called with param optionsArray defined when you should pass null now", LOG_WARNING);
6003  }
6004 
6005  $table_element = $this->table_element;
6006  if ($table_element == 'categorie') {
6007  $table_element = 'categories'; // For compatibility
6008  }
6009 
6010  // Request to get complementary values
6011  if (is_array($optionsArray) && count($optionsArray) > 0) {
6012  $sql = "SELECT rowid";
6013  foreach ($optionsArray as $name => $label) {
6014  if (empty($extrafields->attributes[$this->table_element]['type'][$name]) || $extrafields->attributes[$this->table_element]['type'][$name] != 'separate') {
6015  $sql .= ", ".$name;
6016  }
6017  }
6018  $sql .= " FROM ".$this->db->prefix().$table_element."_extrafields";
6019  $sql .= " WHERE fk_object = ".((int) $rowid);
6020 
6021  //dol_syslog(get_class($this)."::fetch_optionals get extrafields data for ".$this->table_element, LOG_DEBUG); // Too verbose
6022  $resql = $this->db->query($sql);
6023  if ($resql) {
6024  $numrows = $this->db->num_rows($resql);
6025  if ($numrows) {
6026  $tab = $this->db->fetch_array($resql);
6027 
6028  foreach ($tab as $key => $value) {
6029  // 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)
6030  if ($key != 'rowid' && $key != 'tms' && $key != 'fk_member' && !is_int($key)) {
6031  // we can add this attribute to object
6032  if (!empty($extrafields->attributes[$this->table_element]) && in_array($extrafields->attributes[$this->table_element]['type'][$key], array('date', 'datetime'))) {
6033  //var_dump($extrafields->attributes[$this->table_element]['type'][$key]);
6034  $this->array_options["options_".$key] = $this->db->jdate($value);
6035  } else {
6036  $this->array_options["options_".$key] = $value;
6037  }
6038 
6039  //var_dump('key '.$key.' '.$value.' type='.$extrafields->attributes[$this->table_element]['type'][$key].' '.$this->array_options["options_".$key]);
6040  }
6041  }
6042 
6043  // If field is a computed field, value must become result of compute
6044  foreach ($tab as $key => $value) {
6045  if (!empty($extrafields->attributes[$this->table_element]) && !empty($extrafields->attributes[$this->table_element]['computed'][$key])) {
6046  //var_dump($conf->disable_compute);
6047  if (empty($conf->disable_compute)) {
6048  $this->array_options["options_".$key] = dol_eval($extrafields->attributes[$this->table_element]['computed'][$key], 1, 0, '');
6049  }
6050  }
6051  }
6052  }
6053 
6054  $this->db->free($resql);
6055 
6056  if ($numrows) {
6057  return $numrows;
6058  } else {
6059  return 0;
6060  }
6061  } else {
6062  $this->errors[]=$this->db->lasterror;
6063  return -1;
6064  }
6065  }
6066  return 0;
6067  }
6068 
6075  public function deleteExtraFields()
6076  {
6077  global $conf;
6078 
6079  if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
6080  return 0;
6081  }
6082 
6083  $this->db->begin();
6084 
6085  $table_element = $this->table_element;
6086  if ($table_element == 'categorie') {
6087  $table_element = 'categories'; // For compatibility
6088  }
6089 
6090  dol_syslog(get_class($this)."::deleteExtraFields delete", LOG_DEBUG);
6091 
6092  $sql_del = "DELETE FROM ".$this->db->prefix().$table_element."_extrafields WHERE fk_object = ".((int) $this->id);
6093 
6094  $resql = $this->db->query($sql_del);
6095  if (!$resql) {
6096  $this->error = $this->db->lasterror();
6097  $this->db->rollback();
6098  return -1;
6099  } else {
6100  $this->db->commit();
6101  return 1;
6102  }
6103  }
6104 
6115  public function insertExtraFields($trigger = '', $userused = null)
6116  {
6117  global $conf, $langs, $user;
6118 
6119  if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
6120  return 0;
6121  }
6122 
6123  if (empty($userused)) {
6124  $userused = $user;
6125  }
6126 
6127  $error = 0;
6128 
6129  if (!empty($this->array_options)) {
6130  // Check parameters
6131  $langs->load('admin');
6132  require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
6133  $extrafields = new ExtraFields($this->db);
6134  $target_extrafields = $extrafields->fetch_name_optionals_label($this->table_element);
6135 
6136  // Eliminate copied source object extra fields that do not exist in target object
6137  $new_array_options = array();
6138  foreach ($this->array_options as $key => $value) {
6139  if (in_array(substr($key, 8), array_keys($target_extrafields))) { // We remove the 'options_' from $key for test
6140  $new_array_options[$key] = $value;
6141  } elseif (in_array($key, array_keys($target_extrafields))) { // We test on $key that does not contains the 'options_' prefix
6142  $new_array_options['options_'.$key] = $value;
6143  }
6144  }
6145 
6146  foreach ($new_array_options as $key => $value) {
6147  $attributeKey = substr($key, 8); // Remove 'options_' prefix
6148  $attributeType = $extrafields->attributes[$this->table_element]['type'][$attributeKey];
6149  $attributeLabel = $extrafields->attributes[$this->table_element]['label'][$attributeKey];
6150  $attributeParam = $extrafields->attributes[$this->table_element]['param'][$attributeKey];
6151  $attributeRequired = $extrafields->attributes[$this->table_element]['required'][$attributeKey];
6152  $attributeUnique = $extrafields->attributes[$this->table_element]['unique'][$attributeKey];
6153  $attrfieldcomputed = $extrafields->attributes[$this->table_element]['computed'][$attributeKey];
6154 
6155  // If we clone, we have to clean unique extrafields to prevent duplicates.
6156  // This behaviour can be prevented by external code by changing $this->context['createfromclone'] value in createFrom hook
6157  if (! empty($this->context['createfromclone']) && $this->context['createfromclone'] == 'createfromclone' && ! empty($attributeUnique)) {
6158  $new_array_options[$key] = null;
6159  }
6160 
6161  // Similar code than into insertExtraFields
6162  if ($attributeRequired) {
6163  $mandatorypb = false;
6164  if ($attributeType == 'link' && $this->array_options[$key] == '-1') {
6165  $mandatorypb = true;
6166  }
6167  if ($this->array_options[$key] === '') {
6168  $mandatorypb = true;
6169  }
6170  if ($attributeType == 'sellist' && $this->array_options[$key] == '0') {
6171  $mandatorypb = true;
6172  }
6173  if ($mandatorypb) {
6174  $langs->load("errors");
6175  dol_syslog("Mandatory field '".$key."' is empty during create and set to required into definition of extrafields");
6176  $this->errors[] = $langs->trans('ErrorFieldRequired', $attributeLabel);
6177  return -1;
6178  }
6179  }
6180 
6181  //dol_syslog("attributeLabel=".$attributeLabel, LOG_DEBUG);
6182  //dol_syslog("attributeType=".$attributeType, LOG_DEBUG);
6183 
6184  if (!empty($attrfieldcomputed)) {
6185  if (!empty($conf->global->MAIN_STORE_COMPUTED_EXTRAFIELDS)) {
6186  $value = dol_eval($attrfieldcomputed, 1, 0, '');
6187  dol_syslog($langs->trans("Extrafieldcomputed")." sur ".$attributeLabel."(".$value.")", LOG_DEBUG);
6188  $new_array_options[$key] = $value;
6189  } else {
6190  $new_array_options[$key] = null;
6191  }
6192  }
6193 
6194  switch ($attributeType) {
6195  case 'int':
6196  if (!is_numeric($value) && $value != '') {
6197  $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
6198  return -1;
6199  } elseif ($value == '') {
6200  $new_array_options[$key] = null;
6201  }
6202  break;
6203  case 'price':
6204  case 'double':
6205  $value = price2num($value);
6206  if (!is_numeric($value) && $value != '') {
6207  dol_syslog($langs->trans("ExtraFieldHasWrongValue")." for ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
6208  $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
6209  return -1;
6210  } elseif ($value == '') {
6211  $value = null;
6212  }
6213  //dol_syslog("double value"." sur ".$attributeLabel."(".$value." is '".$attributeType."')", LOG_DEBUG);
6214  $new_array_options[$key] = $value;
6215  break;
6216  /*case 'select': // Not required, we chosed value='0' for undefined values
6217  if ($value=='-1')
6218  {
6219  $this->array_options[$key] = null;
6220  }
6221  break;*/
6222  case 'password':
6223  $algo = '';
6224  if ($this->array_options[$key] != '' && is_array($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options'])) {
6225  // If there is an encryption choice, we use it to crypt data before insert
6226  $tmparrays = array_keys($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options']);
6227  $algo = reset($tmparrays);
6228  if ($algo != '') {
6229  //global $action; // $action may be 'create', 'update', 'update_extras'...
6230  //var_dump($action);
6231  //var_dump($this->oldcopy);exit;
6232  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
6233  //var_dump($this->oldcopy->array_options[$key]); var_dump($this->array_options[$key]);
6234  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.
6235  $new_array_options[$key] = $this->array_options[$key]; // Value is kept
6236  } else {
6237  // var_dump($algo);
6238  $newvalue = dol_hash($this->array_options[$key], $algo);
6239  $new_array_options[$key] = $newvalue;
6240  }
6241  } else {
6242  $new_array_options[$key] = $this->array_options[$key]; // Value is kept
6243  }
6244  }
6245  } else // Common usage
6246  {
6247  $new_array_options[$key] = $this->array_options[$key];
6248  }
6249  break;
6250  case 'date':
6251  case 'datetime':
6252  // If data is a string instead of a timestamp, we convert it
6253  if (!is_int($this->array_options[$key])) {
6254  $this->array_options[$key] = strtotime($this->array_options[$key]);
6255  }
6256  $new_array_options[$key] = $this->db->idate($this->array_options[$key]);
6257  break;
6258  case 'link':
6259  $param_list = array_keys($attributeParam['options']);
6260  // 0 : ObjectName
6261  // 1 : classPath
6262  $InfoFieldList = explode(":", $param_list[0]);
6263  dol_include_once($InfoFieldList[1]);
6264  if ($InfoFieldList[0] && class_exists($InfoFieldList[0])) {
6265  if ($value == '-1') { // -1 is key for no defined in combo list of objects
6266  $new_array_options[$key] = '';
6267  } elseif ($value) {
6268  $object = new $InfoFieldList[0]($this->db);
6269  if (is_numeric($value)) {
6270  $res = $object->fetch($value); // Common case
6271  } else {
6272  $res = $object->fetch('', $value); // For compatibility
6273  }
6274 
6275  if ($res > 0) {
6276  $new_array_options[$key] = $object->id;
6277  } else {
6278  $this->error = "Id/Ref '".$value."' for object '".$object->element."' not found";
6279  $this->db->rollback();
6280  return -1;
6281  }
6282  }
6283  } else {
6284  dol_syslog('Error bad setup of extrafield', LOG_WARNING);
6285  }
6286  break;
6287  }
6288  }
6289 
6290  $this->db->begin();
6291 
6292  $table_element = $this->table_element;
6293  if ($table_element == 'categorie') {
6294  $table_element = 'categories'; // For compatibility
6295  }
6296 
6297  dol_syslog(get_class($this)."::insertExtraFields delete then insert", LOG_DEBUG);
6298 
6299  $sql_del = "DELETE FROM ".$this->db->prefix().$table_element."_extrafields WHERE fk_object = ".((int) $this->id);
6300  $this->db->query($sql_del);
6301 
6302  $sql = "INSERT INTO ".$this->db->prefix().$table_element."_extrafields (fk_object";
6303  foreach ($new_array_options as $key => $value) {
6304  $attributeKey = substr($key, 8); // Remove 'options_' prefix
6305  // Add field of attribut
6306  if ($extrafields->attributes[$this->table_element]['type'][$attributeKey] != 'separate') { // Only for other type than separator
6307  $sql .= ",".$attributeKey;
6308  }
6309  }
6310  // We must insert a default value for fields for other entities that are mandatory to avoid not null error
6311  if (!empty($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities']) && is_array($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'])) {
6312  foreach ($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'] as $tmpkey => $tmpval) {
6313  if (!isset($extrafields->attributes[$this->table_element]['type'][$tmpkey])) { // If field not already added previously
6314  $sql .= ",".$tmpkey;
6315  }
6316  }
6317  }
6318  $sql .= ") VALUES (".$this->id;
6319 
6320  foreach ($new_array_options as $key => $value) {
6321  $attributeKey = substr($key, 8); // Remove 'options_' prefix
6322  // Add field of attribute
6323  if ($extrafields->attributes[$this->table_element]['type'][$attributeKey] != 'separate') { // Only for other type than separator)
6324  if ($new_array_options[$key] != '' || $new_array_options[$key] == '0') {
6325  $sql .= ",'".$this->db->escape($new_array_options[$key])."'";
6326  } else {
6327  $sql .= ",null";
6328  }
6329  }
6330  }
6331  // We must insert a default value for fields for other entities that are mandatory to avoid not null error
6332  if (!empty($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities']) && is_array($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'])) {
6333  foreach ($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'] as $tmpkey => $tmpval) {
6334  if (!isset($extrafields->attributes[$this->table_element]['type'][$tmpkey])) { // If field not already added previously
6335  if (in_array($tmpval, array('int', 'double', 'price'))) {
6336  $sql .= ", 0";
6337  } else {
6338  $sql .= ", ''";
6339  }
6340  }
6341  }
6342  }
6343 
6344  $sql .= ")";
6345 
6346  $resql = $this->db->query($sql);
6347  if (!$resql) {
6348  $this->error = $this->db->lasterror();
6349  $error++;
6350  }
6351 
6352  if (!$error && $trigger) {
6353  // Call trigger
6354  $this->context = array('extrafieldaddupdate'=>1);
6355  $result = $this->call_trigger($trigger, $userused);
6356  if ($result < 0) {
6357  $error++;
6358  }
6359  // End call trigger
6360  }
6361 
6362  if ($error) {
6363  $this->db->rollback();
6364  return -1;
6365  } else {
6366  $this->db->commit();
6367  return 1;
6368  }
6369  } else {
6370  return 0;
6371  }
6372  }
6373 
6384  public function insertExtraLanguages($trigger = '', $userused = null)
6385  {
6386  global $conf, $langs, $user;
6387 
6388  if (empty($userused)) {
6389  $userused = $user;
6390  }
6391 
6392  $error = 0;
6393 
6394  if (!empty($conf->global->MAIN_EXTRALANGUAGES_DISABLED)) {
6395  return 0; // For avoid conflicts if trigger used
6396  }
6397 
6398  if (is_array($this->array_languages)) {
6399  $new_array_languages = $this->array_languages;
6400 
6401  foreach ($new_array_languages as $key => $value) {
6402  $attributeKey = $key;
6403  $attributeType = $this->fields[$attributeKey]['type'];
6404  $attributeLabel = $this->fields[$attributeKey]['label'];
6405 
6406  //dol_syslog("attributeLabel=".$attributeLabel, LOG_DEBUG);
6407  //dol_syslog("attributeType=".$attributeType, LOG_DEBUG);
6408 
6409  switch ($attributeType) {
6410  case 'int':
6411  if (!is_numeric($value) && $value != '') {
6412  $this->errors[] = $langs->trans("ExtraLanguageHasWrongValue", $attributeLabel);
6413  return -1;
6414  } elseif ($value == '') {
6415  $new_array_languages[$key] = null;
6416  }
6417  break;
6418  case 'double':
6419  $value = price2num($value);
6420  if (!is_numeric($value) && $value != '') {
6421  dol_syslog($langs->trans("ExtraLanguageHasWrongValue")." sur ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
6422  $this->errors[] = $langs->trans("ExtraLanguageHasWrongValue", $attributeLabel);
6423  return -1;
6424  } elseif ($value == '') {
6425  $new_array_languages[$key] = null;
6426  }
6427  //dol_syslog("double value"." sur ".$attributeLabel."(".$value." is '".$attributeType."')", LOG_DEBUG);
6428  $new_array_languages[$key] = $value;
6429  break;
6430  /*case 'select': // Not required, we chosed value='0' for undefined values
6431  if ($value=='-1')
6432  {
6433  $this->array_options[$key] = null;
6434  }
6435  break;*/
6436  }
6437  }
6438 
6439  $this->db->begin();
6440 
6441  $table_element = $this->table_element;
6442  if ($table_element == 'categorie') {
6443  $table_element = 'categories'; // For compatibility
6444  }
6445 
6446  dol_syslog(get_class($this)."::insertExtraLanguages delete then insert", LOG_DEBUG);
6447 
6448  foreach ($new_array_languages as $key => $langcodearray) { // $key = 'name', 'town', ...
6449  foreach ($langcodearray as $langcode => $value) {
6450  $sql_del = "DELETE FROM ".$this->db->prefix()."object_lang";
6451  $sql_del .= " WHERE fk_object = ".((int) $this->id)." AND property = '".$this->db->escape($key)."' AND type_object = '".$this->db->escape($table_element)."'";
6452  $sql_del .= " AND lang = '".$this->db->escape($langcode)."'";
6453  $this->db->query($sql_del);
6454 
6455  if ($value !== '') {
6456  $sql = "INSERT INTO ".$this->db->prefix()."object_lang (fk_object, property, type_object, lang, value";
6457  $sql .= ") VALUES (".$this->id.", '".$this->db->escape($key)."', '".$this->db->escape($table_element)."', '".$this->db->escape($langcode)."', '".$this->db->escape($value)."'";
6458  $sql .= ")";
6459 
6460  $resql = $this->db->query($sql);
6461  if (!$resql) {
6462  $this->error = $this->db->lasterror();
6463  $error++;
6464  break;
6465  }
6466  }
6467  }
6468  }
6469 
6470  if (!$error && $trigger) {
6471  // Call trigger
6472  $this->context = array('extralanguagesaddupdate'=>1);
6473  $result = $this->call_trigger($trigger, $userused);
6474  if ($result < 0) {
6475  $error++;
6476  }
6477  // End call trigger
6478  }
6479 
6480  if ($error) {
6481  $this->db->rollback();
6482  return -1;
6483  } else {
6484  $this->db->commit();
6485  return 1;
6486  }
6487  } else {
6488  return 0;
6489  }
6490  }
6491 
6502  public function updateExtraField($key, $trigger = null, $userused = null)
6503  {
6504  global $conf, $langs, $user;
6505 
6506  if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
6507  return 0;
6508  }
6509 
6510  if (empty($userused)) {
6511  $userused = $user;
6512  }
6513 
6514  $error = 0;
6515 
6516  if (!empty($this->array_options) && isset($this->array_options["options_".$key])) {
6517  // Check parameters
6518  $langs->load('admin');
6519  require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
6520  $extrafields = new ExtraFields($this->db);
6521  $extrafields->fetch_name_optionals_label($this->table_element);
6522 
6523  $value = $this->array_options["options_".$key];
6524 
6525  $attributeType = $extrafields->attributes[$this->table_element]['type'][$key];
6526  $attributeLabel = $extrafields->attributes[$this->table_element]['label'][$key];
6527  $attributeParam = $extrafields->attributes[$this->table_element]['param'][$key];
6528  $attributeRequired = $extrafields->attributes[$this->table_element]['required'][$key];
6529  $attrfieldcomputed = $extrafields->attributes[$this->table_element]['computed'][$key];
6530 
6531  // Similar code than into insertExtraFields
6532  if ($attributeRequired) {
6533  $mandatorypb = false;
6534  if ($attributeType == 'link' && $this->array_options["options_".$key] == '-1') {
6535  $mandatorypb = true;
6536  }
6537  if ($this->array_options["options_".$key] === '') {
6538  $mandatorypb = true;
6539  }
6540  if ($mandatorypb) {
6541  $langs->load("errors");
6542  dol_syslog("Mandatory field 'options_".$key."' is empty during update and set to required into definition of extrafields");
6543  $this->errors[] = $langs->trans('ErrorFieldRequired', $attributeLabel);
6544  return -1;
6545  }
6546  }
6547 
6548  //dol_syslog("attributeLabel=".$attributeLabel, LOG_DEBUG);
6549  //dol_syslog("attributeType=".$attributeType, LOG_DEBUG);
6550 
6551  if (!empty($attrfieldcomputed)) {
6552  if (!empty($conf->global->MAIN_STORE_COMPUTED_EXTRAFIELDS)) {
6553  $value = dol_eval($attrfieldcomputed, 1, 0, '');
6554  dol_syslog($langs->trans("Extrafieldcomputed")." sur ".$attributeLabel."(".$value.")", LOG_DEBUG);
6555  $this->array_options["options_".$key] = $value;
6556  } else {
6557  $this->array_options["options_".$key] = null;
6558  }
6559  }
6560 
6561  switch ($attributeType) {
6562  case 'int':
6563  if (!is_numeric($value) && $value != '') {
6564  $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
6565  return -1;
6566  } elseif ($value === '') {
6567  $this->array_options["options_".$key] = null;
6568  }
6569  break;
6570  case 'double':
6571  $value = price2num($value);
6572  if (!is_numeric($value) && $value != '') {
6573  dol_syslog($langs->trans("ExtraFieldHasWrongValue")." sur ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
6574  $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
6575  return -1;
6576  } elseif ($value === '') {
6577  $value = null;
6578  }
6579  //dol_syslog("double value"." sur ".$attributeLabel."(".$value." is '".$attributeType."')", LOG_DEBUG);
6580  $this->array_options["options_".$key] = $value;
6581  break;
6582  /*case 'select': // Not required, we chosed value='0' for undefined values
6583  if ($value=='-1')
6584  {
6585  $this->array_options[$key] = null;
6586  }
6587  break;*/
6588  case 'price':
6589  $this->array_options["options_".$key] = price2num($this->array_options["options_".$key]);
6590  break;
6591  case 'date':
6592  case 'datetime':
6593  if (empty($this->array_options["options_".$key])) {
6594  $this->array_options["options_".$key] = null;
6595  } else {
6596  $this->array_options["options_".$key] = $this->db->idate($this->array_options["options_".$key]);
6597  }
6598  break;
6599  case 'boolean':
6600  if (empty($this->array_options["options_".$key])) {
6601  $this->array_options["options_".$key] = null;
6602  }
6603  break;
6604  /*
6605  case 'link':
6606  $param_list = array_keys($attributeParam['options']);
6607  // 0 : ObjectName
6608  // 1 : classPath
6609  $InfoFieldList = explode(":", $param_list[0]);
6610  dol_include_once($InfoFieldList[1]);
6611  if ($InfoFieldList[0] && class_exists($InfoFieldList[0]))
6612  {
6613  if ($value == '-1') // -1 is key for no defined in combo list of objects
6614  {
6615  $new_array_options[$key] = '';
6616  } elseif ($value) {
6617  $object = new $InfoFieldList[0]($this->db);
6618  if (is_numeric($value)) $res = $object->fetch($value); // Common case
6619  else $res = $object->fetch('', $value); // For compatibility
6620 
6621  if ($res > 0) $new_array_options[$key] = $object->id;
6622  else {
6623  $this->error = "Id/Ref '".$value."' for object '".$object->element."' not found";
6624  $this->db->rollback();
6625  return -1;
6626  }
6627  }
6628  } else {
6629  dol_syslog('Error bad setup of extrafield', LOG_WARNING);
6630  }
6631  break;
6632  */
6633  }
6634 
6635  $this->db->begin();
6636 
6637  $linealreadyfound = 0;
6638 
6639  // 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)
6640  $sql = "SELECT COUNT(rowid) as nb FROM ".$this->db->prefix().$this->table_element."_extrafields WHERE fk_object = ".((int) $this->id);
6641  $resql = $this->db->query($sql);
6642  if ($resql) {
6643  $tmpobj = $this->db->fetch_object($resql);
6644  if ($tmpobj) {
6645  $linealreadyfound = $tmpobj->nb;
6646  }
6647  }
6648 
6649  if ($linealreadyfound) {
6650  if ($this->array_options["options_".$key] === null) {
6651  $sql = "UPDATE ".$this->db->prefix().$this->table_element."_extrafields SET ".$key." = null";
6652  } else {
6653  $sql = "UPDATE ".$this->db->prefix().$this->table_element."_extrafields SET ".$key." = '".$this->db->escape($this->array_options["options_".$key])."'";
6654  }
6655  $sql .= " WHERE fk_object = ".((int) $this->id);
6656  } else {
6657  $result = $this->insertExtraFields('', $user);
6658  if ($result < 0) {
6659  $error++;
6660  }
6661  }
6662 
6663  $resql = $this->db->query($sql);
6664  if (!$resql) {
6665  $error++;
6666  $this->error = $this->db->lasterror();
6667  }
6668  if (!$error && $trigger) {
6669  // Call trigger
6670  $this->context = array('extrafieldupdate'=>1);
6671  $result = $this->call_trigger($trigger, $userused);
6672  if ($result < 0) {
6673  $error++;
6674  }
6675  // End call trigger
6676  }
6677 
6678  if ($error) {
6679  dol_syslog(__METHOD__.$this->error, LOG_ERR);
6680  $this->db->rollback();
6681  return -1;
6682  } else {
6683  $this->db->commit();
6684  return 1;
6685  }
6686  } else {
6687  return 0;
6688  }
6689  }
6690 
6701  public function updateExtraLanguages($key, $trigger = null, $userused = null)
6702  {
6703  global $conf, $langs, $user;
6704 
6705  if (empty($userused)) {
6706  $userused = $user;
6707  }
6708 
6709  $error = 0;
6710 
6711  if (!empty($conf->global->MAIN_EXTRALANGUAGES_DISABLED)) {
6712  return 0; // For avoid conflicts if trigger used
6713  }
6714 
6715  return 0;
6716  }
6717 
6718 
6733  public function showInputField($val, $key, $value, $moreparam = '', $keysuffix = '', $keyprefix = '', $morecss = 0, $nonewbutton = 0)
6734  {
6735  global $conf, $langs, $form;
6736 
6737  if (!is_object($form)) {
6738  require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
6739  $form = new Form($this->db);
6740  }
6741 
6742  if (!empty($this->fields)) {
6743  $val = $this->fields[$key];
6744  }
6745 
6746  // Validation tests and output
6747  $fieldValidationErrorMsg = '';
6748  $validationClass = '';
6749  $fieldValidationErrorMsg = $this->getFieldError($key);
6750  if (!empty($fieldValidationErrorMsg)) {
6751  $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
6752  } else {
6753  $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
6754  }
6755 
6756  $out = '';
6757  $type = '';
6758  $isDependList = 0;
6759  $param = array();
6760  $param['options'] = array();
6761  $reg = array();
6762  $size = !empty($this->fields[$key]['size']) ? $this->fields[$key]['size'] : 0;
6763  // Because we work on extrafields
6764  if (preg_match('/^(integer|link):(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
6765  $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4].':'.$reg[5] => 'N');
6766  $type = 'link';
6767  } elseif (preg_match('/^(integer|link):(.*):(.*):(.*)/i', $val['type'], $reg)) {
6768  $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4] => 'N');
6769  $type = 'link';
6770  } elseif (preg_match('/^(integer|link):(.*):(.*)/i', $val['type'], $reg)) {
6771  $param['options'] = array($reg[2].':'.$reg[3] => 'N');
6772  $type = 'link';
6773  } elseif (preg_match('/^(sellist):(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
6774  $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4].':'.$reg[5] => 'N');
6775  $type = 'sellist';
6776  } elseif (preg_match('/^(sellist):(.*):(.*):(.*)/i', $val['type'], $reg)) {
6777  $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4] => 'N');
6778  $type = 'sellist';
6779  } elseif (preg_match('/^(sellist):(.*):(.*)/i', $val['type'], $reg)) {
6780  $param['options'] = array($reg[2].':'.$reg[3] => 'N');
6781  $type = 'sellist';
6782  } elseif (preg_match('/varchar\((\d+)\)/', $val['type'], $reg)) {
6783  $param['options'] = array();
6784  $type = 'varchar';
6785  $size = $reg[1];
6786  } elseif (preg_match('/varchar/', $val['type'])) {
6787  $param['options'] = array();
6788  $type = 'varchar';
6789  } else {
6790  $param['options'] = array();
6791  $type = $this->fields[$key]['type'];
6792  }
6793 
6794  // Special case that force options and type ($type can be integer, varchar, ...)
6795  if (!empty($this->fields[$key]['arrayofkeyval']) && is_array($this->fields[$key]['arrayofkeyval'])) {
6796  $param['options'] = $this->fields[$key]['arrayofkeyval'];
6797  $type = 'select';
6798  }
6799 
6800  $label = $this->fields[$key]['label'];
6801  //$elementtype=$this->fields[$key]['elementtype']; // Seems not used
6802  $default = (!empty($this->fields[$key]['default']) ? $this->fields[$key]['default'] : '');
6803  $computed = (!empty($this->fields[$key]['computed']) ? $this->fields[$key]['computed'] : '');
6804  $unique = (!empty($this->fields[$key]['unique']) ? $this->fields[$key]['unique'] : 0);
6805  $required = (!empty($this->fields[$key]['required']) ? $this->fields[$key]['required'] : 0);
6806  $autofocusoncreate = (!empty($this->fields[$key]['autofocusoncreate']) ? $this->fields[$key]['autofocusoncreate'] : 0);
6807 
6808  $langfile = (!empty($this->fields[$key]['langfile']) ? $this->fields[$key]['langfile'] : '');
6809  $list = (!empty($this->fields[$key]['list']) ? $this->fields[$key]['list'] : 0);
6810  $hidden = (in_array(abs($this->fields[$key]['visible']), array(0, 2)) ? 1 : 0);
6811 
6812  $objectid = $this->id;
6813 
6814  if ($computed) {
6815  if (!preg_match('/^search_/', $keyprefix)) {
6816  return '<span class="opacitymedium">'.$langs->trans("AutomaticallyCalculated").'</span>';
6817  } else {
6818  return '';
6819  }
6820  }
6821 
6822  // Set value of $morecss. For this, we use in priority showsize from parameters, then $val['css'] then autodefine
6823  if (empty($morecss) && !empty($val['css'])) {
6824  $morecss = $val['css'];
6825  } elseif (empty($morecss)) {
6826  if ($type == 'date') {
6827  $morecss = 'minwidth100imp';
6828  } elseif ($type == 'datetime' || $type == 'link') { // link means an foreign key to another primary id
6829  $morecss = 'minwidth200imp';
6830  } elseif (in_array($type, array('int', 'integer', 'price')) || preg_match('/^double(\([0-9],[0-9]\)){0,1}/', $type)) {
6831  $morecss = 'maxwidth75';
6832  } elseif ($type == 'url') {
6833  $morecss = 'minwidth400';
6834  } elseif ($type == 'boolean') {
6835  $morecss = '';
6836  } else {
6837  if (round($size) < 12) {
6838  $morecss = 'minwidth100';
6839  } elseif (round($size) <= 48) {
6840  $morecss = 'minwidth200';
6841  } else {
6842  $morecss = 'minwidth400';
6843  }
6844  }
6845  }
6846 
6847  // Add validation state class
6848  if (!empty($validationClass)) {
6849  $morecss.= $validationClass;
6850  }
6851 
6852  if (in_array($type, array('date'))) {
6853  $tmp = explode(',', $size);
6854  $newsize = $tmp[0];
6855  $showtime = 0;
6856 
6857  // Do not show current date when field not required (see selectDate() method)
6858  if (!$required && $value == '') {
6859  $value = '-1';
6860  }
6861 
6862  // TODO Must also support $moreparam
6863  $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required, '', 1, (($keyprefix != 'search_' && $keyprefix != 'search_options_') ? 1 : 0), 0, 1);
6864  } elseif (in_array($type, array('datetime'))) {
6865  $tmp = explode(',', $size);
6866  $newsize = $tmp[0];
6867  $showtime = 1;
6868 
6869  // Do not show current date when field not required (see selectDate() method)
6870  if (!$required && $value == '') $value = '-1';
6871 
6872  // TODO Must also support $moreparam
6873  $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required, '', 1, (($keyprefix != 'search_' && $keyprefix != 'search_options_') ? 1 : 0), 0, 1, '', '', '', 1, '', '', 'tzuserrel');
6874  } elseif (in_array($type, array('duration'))) {
6875  $out = $form->select_duration($keyprefix.$key.$keysuffix, $value, 0, 'text', 0, 1);
6876  } elseif (in_array($type, array('int', 'integer'))) {
6877  $tmp = explode(',', $size);
6878  $newsize = $tmp[0];
6879  $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' : '').'>';
6880  } elseif (in_array($type, array('real'))) {
6881  $out = '<input type="text" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'"'.($moreparam ? $moreparam : '').($autofocusoncreate ? ' autofocus' : '').'>';
6882  } elseif (preg_match('/varchar/', $type)) {
6883  $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' : '').'>';
6884  } elseif (in_array($type, array('email', 'mail', 'phone', 'url'))) {
6885  $out = '<input type="text" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').($autofocusoncreate ? ' autofocus' : '').'>';
6886  } elseif (preg_match('/^text/', $type)) {
6887  if (!preg_match('/search_/', $keyprefix)) { // If keyprefix is search_ or search_options_, we must just use a simple text field
6888  require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
6889  $doleditor = new DolEditor($keyprefix.$key.$keysuffix, $value, '', 200, 'dolibarr_notes', 'In', false, false, false, ROWS_5, '90%');
6890  $out = $doleditor->Create(1);
6891  } else {
6892  $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').'>';
6893  }
6894  } elseif (preg_match('/^html/', $type)) {
6895  if (!preg_match('/search_/', $keyprefix)) { // If keyprefix is search_ or search_options_, we must just use a simple text field
6896  require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
6897  $doleditor = new DolEditor($keyprefix.$key.$keysuffix, $value, '', 200, 'dolibarr_notes', 'In', false, false, !empty($conf->fckeditor->enabled) && $conf->global->FCKEDITOR_ENABLE_SOCIETE, ROWS_5, '90%');
6898  $out = $doleditor->Create(1, '', true, '', '', $moreparam, $morecss);
6899  } else {
6900  $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').'>';
6901  }
6902  } elseif ($type == 'boolean') {
6903  $checked = '';
6904  if (!empty($value)) {
6905  $checked = ' checked value="1" ';
6906  } else {
6907  $checked = ' value="1" ';
6908  }
6909  $out = '<input type="checkbox" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.$checked.' '.($moreparam ? $moreparam : '').'>';
6910  } elseif ($type == 'price') {
6911  if (!empty($value)) { // $value in memory is a php numeric, we format it into user number format.
6912  $value = price($value);
6913  }
6914  $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'> '.$langs->getCurrencySymbol($conf->currency);
6915  } elseif (preg_match('/^double(\([0-9],[0-9]\)){0,1}/', $type)) {
6916  if (!empty($value)) { // $value in memory is a php numeric, we format it into user number format.
6917  $value = price($value);
6918  }
6919  $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'> ';
6920  } elseif ($type == 'select') {
6921  $out = '';
6922  if (!empty($conf->use_javascript_ajax) && empty($conf->global->MAIN_EXTRAFIELDS_DISABLE_SELECT2)) {
6923  include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
6924  $out .= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
6925  }
6926 
6927  $out .= '<select class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '').'>';
6928  if ((!isset($this->fields[$key]['default'])) || ($this->fields[$key]['notnull'] != 1)) {
6929  $out .= '<option value="0">&nbsp;</option>';
6930  }
6931  foreach ($param['options'] as $keyb => $valb) {
6932  if ((string) $keyb == '') {
6933  continue;
6934  }
6935  if (strpos($valb, "|") !== false) {
6936  list($valb, $parent) = explode('|', $valb);
6937  }
6938  $out .= '<option value="'.$keyb.'"';
6939  $out .= (((string) $value == (string) $keyb) ? ' selected' : '');
6940  $out .= (!empty($parent) ? ' parent="'.$parent.'"' : '');
6941  $out .= '>'.$valb.'</option>';
6942  }
6943  $out .= '</select>';
6944  } elseif ($type == 'sellist') {
6945  $out = '';
6946  if (!empty($conf->use_javascript_ajax) && empty($conf->global->MAIN_EXTRAFIELDS_DISABLE_SELECT2)) {
6947  include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
6948  $out .= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
6949  }
6950 
6951  $out .= '<select class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '').'>';
6952  if (is_array($param['options'])) {
6953  $param_list = array_keys($param['options']);
6954  $InfoFieldList = explode(":", $param_list[0]);
6955  $parentName = '';
6956  $parentField = '';
6957  // 0 : tableName
6958  // 1 : label field name
6959  // 2 : key fields name (if differ of rowid)
6960  // 3 : key field parent (for dependent lists)
6961  // 4 : where clause filter on column or table extrafield, syntax field='value' or extra.field=value
6962  $keyList = (empty($InfoFieldList[2]) ? 'rowid' : $InfoFieldList[2].' as rowid');
6963 
6964  if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
6965  if (strpos($InfoFieldList[4], 'extra.') !== false) {
6966  $keyList = 'main.'.$InfoFieldList[2].' as rowid';
6967  } else {
6968  $keyList = $InfoFieldList[2].' as rowid';
6969  }
6970  }
6971  if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
6972  list($parentName, $parentField) = explode('|', $InfoFieldList[3]);
6973  $keyList .= ', '.$parentField;
6974  }
6975 
6976  $fields_label = explode('|', $InfoFieldList[1]);
6977  if (is_array($fields_label)) {
6978  $keyList .= ', ';
6979  $keyList .= implode(', ', $fields_label);
6980  }
6981 
6982  $sqlwhere = '';
6983  $sql = "SELECT ".$keyList;
6984  $sql .= " FROM ".$this->db->prefix().$InfoFieldList[0];
6985  if (!empty($InfoFieldList[4])) {
6986  // can use SELECT request
6987  if (strpos($InfoFieldList[4], '$SEL$') !== false) {
6988  $InfoFieldList[4] = str_replace('$SEL$', 'SELECT', $InfoFieldList[4]);
6989  }
6990 
6991  // current object id can be use into filter
6992  if (strpos($InfoFieldList[4], '$ID$') !== false && !empty($objectid)) {
6993  $InfoFieldList[4] = str_replace('$ID$', $objectid, $InfoFieldList[4]);
6994  } else {
6995  $InfoFieldList[4] = str_replace('$ID$', '0', $InfoFieldList[4]);
6996  }
6997 
6998  //We have to join on extrafield table
6999  if (strpos($InfoFieldList[4], 'extra') !== false) {
7000  $sql .= " as main, ".$this->db->prefix().$InfoFieldList[0]."_extrafields as extra";
7001  $sqlwhere .= " WHERE extra.fk_object=main.".$InfoFieldList[2]." AND ".$InfoFieldList[4];
7002  } else {
7003  $sqlwhere .= " WHERE ".$InfoFieldList[4];
7004  }
7005  } else {
7006  $sqlwhere .= ' WHERE 1=1';
7007  }
7008  // Some tables may have field, some other not. For the moment we disable it.
7009  if (in_array($InfoFieldList[0], array('tablewithentity'))) {
7010  $sqlwhere .= " AND entity = ".((int) $conf->entity);
7011  }
7012  $sql .= $sqlwhere;
7013  //print $sql;
7014 
7015  $sql .= ' ORDER BY '.implode(', ', $fields_label);
7016 
7017  dol_syslog(get_class($this).'::showInputField type=sellist', LOG_DEBUG);
7018  $resql = $this->db->query($sql);
7019  if ($resql) {
7020  $out .= '<option value="0">&nbsp;</option>';
7021  $num = $this->db->num_rows($resql);
7022  $i = 0;
7023  while ($i < $num) {
7024  $labeltoshow = '';
7025  $obj = $this->db->fetch_object($resql);
7026 
7027  // Several field into label (eq table:code|libelle:rowid)
7028  $notrans = false;
7029  $fields_label = explode('|', $InfoFieldList[1]);
7030  if (count($fields_label) > 1) {
7031  $notrans = true;
7032  foreach ($fields_label as $field_toshow) {
7033  $labeltoshow .= $obj->$field_toshow.' ';
7034  }
7035  } else {
7036  $labeltoshow = $obj->{$InfoFieldList[1]};
7037  }
7038  $labeltoshow = dol_trunc($labeltoshow, 45);
7039 
7040  if ($value == $obj->rowid) {
7041  foreach ($fields_label as $field_toshow) {
7042  $translabel = $langs->trans($obj->$field_toshow);
7043  if ($translabel != $obj->$field_toshow) {
7044  $labeltoshow = dol_trunc($translabel).' ';
7045  } else {
7046  $labeltoshow = dol_trunc($obj->$field_toshow).' ';
7047  }
7048  }
7049  $out .= '<option value="'.$obj->rowid.'" selected>'.$labeltoshow.'</option>';
7050  } else {
7051  if (!$notrans) {
7052  $translabel = $langs->trans($obj->{$InfoFieldList[1]});
7053  if ($translabel != $obj->{$InfoFieldList[1]}) {
7054  $labeltoshow = dol_trunc($translabel, 18);
7055  } else {
7056  $labeltoshow = dol_trunc($obj->{$InfoFieldList[1]});
7057  }
7058  }
7059  if (empty($labeltoshow)) {
7060  $labeltoshow = '(not defined)';
7061  }
7062  if ($value == $obj->rowid) {
7063  $out .= '<option value="'.$obj->rowid.'" selected>'.$labeltoshow.'</option>';
7064  }
7065 
7066  if (!empty($InfoFieldList[3]) && $parentField) {
7067  $parent = $parentName.':'.$obj->{$parentField};
7068  $isDependList = 1;
7069  }
7070 
7071  $out .= '<option value="'.$obj->rowid.'"';
7072  $out .= ($value == $obj->rowid ? ' selected' : '');
7073  $out .= (!empty($parent) ? ' parent="'.$parent.'"' : '');
7074  $out .= '>'.$labeltoshow.'</option>';
7075  }
7076 
7077  $i++;
7078  }
7079  $this->db->free($resql);
7080  } else {
7081  print 'Error in request '.$sql.' '.$this->db->lasterror().'. Check setup of extra parameters.<br>';
7082  }
7083  }
7084  $out .= '</select>';
7085  } elseif ($type == 'checkbox') {
7086  $value_arr = explode(',', $value);
7087  $out = $form->multiselectarray($keyprefix.$key.$keysuffix, (empty($param['options']) ?null:$param['options']), $value_arr, '', 0, $morecss, 0, '100%');
7088  } elseif ($type == 'radio') {
7089  $out = '';
7090  foreach ($param['options'] as $keyopt => $valopt) {
7091  $out .= '<input class="flat '.$morecss.'" type="radio" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '');
7092  $out .= ' value="'.$keyopt.'"';
7093  $out .= ' id="'.$keyprefix.$key.$keysuffix.'_'.$keyopt.'"';
7094  $out .= ($value == $keyopt ? 'checked' : '');
7095  $out .= '/><label for="'.$keyprefix.$key.$keysuffix.'_'.$keyopt.'">'.$valopt.'</label><br>';
7096  }
7097  } elseif ($type == 'chkbxlst') {
7098  if (is_array($value)) {
7099  $value_arr = $value;
7100  } else {
7101  $value_arr = explode(',', $value);
7102  }
7103 
7104  if (is_array($param['options'])) {
7105  $param_list = array_keys($param['options']);
7106  $InfoFieldList = explode(":", $param_list[0]);
7107  $parentName = '';
7108  $parentField = '';
7109  // 0 : tableName
7110  // 1 : label field name
7111  // 2 : key fields name (if differ of rowid)
7112  // 3 : key field parent (for dependent lists)
7113  // 4 : where clause filter on column or table extrafield, syntax field='value' or extra.field=value
7114  $keyList = (empty($InfoFieldList[2]) ? 'rowid' : $InfoFieldList[2].' as rowid');
7115 
7116  if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
7117  list ($parentName, $parentField) = explode('|', $InfoFieldList[3]);
7118  $keyList .= ', '.$parentField;
7119  }
7120  if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
7121  if (strpos($InfoFieldList[4], 'extra.') !== false) {
7122  $keyList = 'main.'.$InfoFieldList[2].' as rowid';
7123  } else {
7124  $keyList = $InfoFieldList[2].' as rowid';
7125  }
7126  }
7127 
7128  $fields_label = explode('|', $InfoFieldList[1]);
7129  if (is_array($fields_label)) {
7130  $keyList .= ', ';
7131  $keyList .= implode(', ', $fields_label);
7132  }
7133 
7134  $sqlwhere = '';
7135  $sql = "SELECT ".$keyList;
7136  $sql .= ' FROM '.$this->db->prefix().$InfoFieldList[0];
7137  if (!empty($InfoFieldList[4])) {
7138  // can use SELECT request
7139  if (strpos($InfoFieldList[4], '$SEL$') !== false) {
7140  $InfoFieldList[4] = str_replace('$SEL$', 'SELECT', $InfoFieldList[4]);
7141  }
7142 
7143  // current object id can be use into filter
7144  if (strpos($InfoFieldList[4], '$ID$') !== false && !empty($objectid)) {
7145  $InfoFieldList[4] = str_replace('$ID$', $objectid, $InfoFieldList[4]);
7146  } else {
7147  $InfoFieldList[4] = str_replace('$ID$', '0', $InfoFieldList[4]);
7148  }
7149 
7150  // We have to join on extrafield table
7151  if (strpos($InfoFieldList[4], 'extra') !== false) {
7152  $sql .= ' as main, '.$this->db->prefix().$InfoFieldList[0].'_extrafields as extra';
7153  $sqlwhere .= " WHERE extra.fk_object=main.".$InfoFieldList[2]." AND ".$InfoFieldList[4];
7154  } else {
7155  $sqlwhere .= " WHERE ".$InfoFieldList[4];
7156  }
7157  } else {
7158  $sqlwhere .= ' WHERE 1=1';
7159  }
7160  // Some tables may have field, some other not. For the moment we disable it.
7161  if (in_array($InfoFieldList[0], array('tablewithentity'))) {
7162  $sqlwhere .= " AND entity = ".((int) $conf->entity);
7163  }
7164  // $sql.=preg_replace('/^ AND /','',$sqlwhere);
7165  // print $sql;
7166 
7167  $sql .= $sqlwhere;
7168  dol_syslog(get_class($this).'::showInputField type=chkbxlst', LOG_DEBUG);
7169  $resql = $this->db->query($sql);
7170  if ($resql) {
7171  $num = $this->db->num_rows($resql);
7172  $i = 0;
7173 
7174  $data = array();
7175 
7176  while ($i < $num) {
7177  $labeltoshow = '';
7178  $obj = $this->db->fetch_object($resql);
7179 
7180  $notrans = false;
7181  // Several field into label (eq table:code|libelle:rowid)
7182  $fields_label = explode('|', $InfoFieldList[1]);
7183  if (count($fields_label) > 1) {
7184  $notrans = true;
7185  foreach ($fields_label as $field_toshow) {
7186  $labeltoshow .= $obj->$field_toshow.' ';
7187  }
7188  } else {
7189  $labeltoshow = $obj->{$InfoFieldList[1]};
7190  }
7191  $labeltoshow = dol_trunc($labeltoshow, 45);
7192 
7193  if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
7194  foreach ($fields_label as $field_toshow) {
7195  $translabel = $langs->trans($obj->$field_toshow);
7196  if ($translabel != $obj->$field_toshow) {
7197  $labeltoshow = dol_trunc($translabel, 18).' ';
7198  } else {
7199  $labeltoshow = dol_trunc($obj->$field_toshow, 18).' ';
7200  }
7201  }
7202 
7203  $data[$obj->rowid] = $labeltoshow;
7204  } else {
7205  if (!$notrans) {
7206  $translabel = $langs->trans($obj->{$InfoFieldList[1]});
7207  if ($translabel != $obj->{$InfoFieldList[1]}) {
7208  $labeltoshow = dol_trunc($translabel, 18);
7209  } else {
7210  $labeltoshow = dol_trunc($obj->{$InfoFieldList[1]}, 18);
7211  }
7212  }
7213  if (empty($labeltoshow)) {
7214  $labeltoshow = '(not defined)';
7215  }
7216 
7217  if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
7218  $data[$obj->rowid] = $labeltoshow;
7219  }
7220 
7221  if (!empty($InfoFieldList[3]) && $parentField) {
7222  $parent = $parentName.':'.$obj->{$parentField};
7223  $isDependList = 1;
7224  }
7225 
7226  $data[$obj->rowid] = $labeltoshow;
7227  }
7228 
7229  $i++;
7230  }
7231  $this->db->free($resql);
7232 
7233  $out = $form->multiselectarray($keyprefix.$key.$keysuffix, $data, $value_arr, '', 0, '', 0, '100%');
7234  } else {
7235  print 'Error in request '.$sql.' '.$this->db->lasterror().'. Check setup of extra parameters.<br>';
7236  }
7237  }
7238  } elseif ($type == 'link') {
7239  $param_list = array_keys($param['options']); // $param_list='ObjectName:classPath[:AddCreateButtonOrNot[:Filter[:Sortfield]]]'
7240  $param_list_array = explode(':', $param_list[0]);
7241  $showempty = (($required && $default != '') ? 0 : 1);
7242 
7243  if (!preg_match('/search_/', $keyprefix)) {
7244  if (!empty($param_list_array[2])) { // If the entry into $fields is set to add a create button
7245  if (!empty($this->fields[$key]['picto'])) {
7246  $morecss .= ' widthcentpercentminusxx';
7247  } else {
7248  $morecss .= ' widthcentpercentminusx';
7249  }
7250  } else {
7251  if (!empty($this->fields[$key]['picto'])) {
7252  $morecss .= ' widthcentpercentminusx';
7253  }
7254  }
7255  }
7256 
7257  $out = $form->selectForForms($param_list[0], $keyprefix.$key.$keysuffix, $value, $showempty, '', '', $morecss, $moreparam, 0, empty($val['disabled']) ? 0 : 1);
7258 
7259  if (!empty($param_list_array[2])) { // If the entry into $fields is set to add a create button
7260  if (!GETPOSTISSET('backtopage') && empty($val['disabled']) && empty($nonewbutton)) { // To avoid to open several times the 'Create Object' button and to avoid to have button if field is protected by a "disabled".
7261  list($class, $classfile) = explode(':', $param_list[0]);
7262  if (file_exists(dol_buildpath(dirname(dirname($classfile)).'/card.php'))) {
7263  $url_path = dol_buildpath(dirname(dirname($classfile)).'/card.php', 1);
7264  } else {
7265  $url_path = dol_buildpath(dirname(dirname($classfile)).'/'.strtolower($class).'_card.php', 1);
7266  }
7267  $paramforthenewlink = '';
7268  $paramforthenewlink .= (GETPOSTISSET('action') ? '&action='.GETPOST('action', 'aZ09') : '');
7269  $paramforthenewlink .= (GETPOSTISSET('id') ? '&id='.GETPOST('id', 'int') : '');
7270  $paramforthenewlink .= (GETPOSTISSET('origin') ? '&origin='.GETPOST('origin', 'aZ09') : '');
7271  $paramforthenewlink .= (GETPOSTISSET('originid') ? '&originid='.GETPOST('originid', 'int') : '');
7272  $paramforthenewlink .= '&fk_'.strtolower($class).'=--IDFORBACKTOPAGE--';
7273  // TODO Add Javascript code to add input fields already filled into $paramforthenewlink so we won't loose them when going back to main page
7274  $out .= '<a class="butActionNew" title="'.$langs->trans("New").'" href="'.$url_path.'?action=create&backtopage='.urlencode($_SERVER['PHP_SELF'].($paramforthenewlink ? '?'.$paramforthenewlink : '')).'"><span class="fa fa-plus-circle valignmiddle"></span></a>';
7275  }
7276  }
7277  } elseif ($type == 'password') {
7278  // If prefix is 'search_', field is used as a filter, we use a common text field.
7279  $out = '<input type="'.($keyprefix == 'search_' ? 'text' : 'password').'" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'>';
7280  } elseif ($type == 'array') {
7281  $newval = $val;
7282  $newval['type'] = 'varchar(256)';
7283 
7284  $out = '';
7285  if (!empty($value)) {
7286  foreach ($value as $option) {
7287  $out .= '<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
7288  $out .= $this->showInputField($newval, $keyprefix.$key.$keysuffix.'[]', $option, $moreparam, '', '', $morecss).'<br></span>';
7289  }
7290  }
7291  $out .= '<a id="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_add" href="javascript:;"><span class="fa fa-plus-circle valignmiddle"></span></a>';
7292 
7293  $newInput = '<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
7294  $newInput .= $this->showInputField($newval, $keyprefix.$key.$keysuffix.'[]', '', $moreparam, '', '', $morecss).'<br></span>';
7295 
7296  if (!empty($conf->use_javascript_ajax)) {
7297  $out .= '
7298  <script>
7299  $(document).ready(function() {
7300  $("a#'.dol_escape_js($keyprefix.$key.$keysuffix).'_add").click(function() {
7301  $("'.dol_escape_js($newInput).'").insertBefore(this);
7302  });
7303 
7304  $(document).on("click", "a.'.dol_escape_js($keyprefix.$key.$keysuffix).'_del", function() {
7305  $(this).parent().remove();
7306  });
7307  });
7308  </script>';
7309  }
7310  }
7311  if (!empty($hidden)) {
7312  $out = '<input type="hidden" value="'.$value.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'"/>';
7313  }
7314 
7315  if ($isDependList==1) {
7316  $out .= $this->getJSListDependancies('_common');
7317  }
7318  /* Add comments
7319  if ($type == 'date') $out.=' (YYYY-MM-DD)';
7320  elseif ($type == 'datetime') $out.=' (YYYY-MM-DD HH:MM:SS)';
7321  */
7322 
7323  // Display error message for field
7324  if (!empty($fieldValidationErrorMsg) && function_exists('getFieldErrorIcon')) {
7325  $out .= ' '.getFieldErrorIcon($fieldValidationErrorMsg);
7326  }
7327 
7328  return $out;
7329  }
7330 
7344  public function showOutputField($val, $key, $value, $moreparam = '', $keysuffix = '', $keyprefix = '', $morecss = '')
7345  {
7346  global $conf, $langs, $form;
7347 
7348  if (!is_object($form)) {
7349  require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
7350  $form = new Form($this->db);
7351  }
7352 
7353  $objectid = $this->id; // Not used ???
7354 
7355  $label = empty($val['label']) ? '' : $val['label'];
7356  $type = empty($val['type']) ? '' : $val['type'];
7357  $size = empty($val['css']) ? '' : $val['css'];
7358  $reg = array();
7359 
7360  // Convert var to be able to share same code than showOutputField of extrafields
7361  if (preg_match('/varchar\((\d+)\)/', $type, $reg)) {
7362  $type = 'varchar'; // convert varchar(xx) int varchar
7363  $size = $reg[1];
7364  } elseif (preg_match('/varchar/', $type)) {
7365  $type = 'varchar'; // convert varchar(xx) int varchar
7366  }
7367  if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
7368  $type = 'select';
7369  }
7370  if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) {
7371  $type = 'link';
7372  }
7373 
7374  $default = empty($val['default']) ? '' : $val['default'];
7375  $computed = empty($val['computed']) ? '' : $val['computed'];
7376  $unique = empty($val['unique']) ? '' : $val['unique'];
7377  $required = empty($val['required']) ? '' : $val['required'];
7378  $param = array();
7379  $param['options'] = array();
7380 
7381  if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
7382  $param['options'] = $val['arrayofkeyval'];
7383  }
7384  if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) {
7385  $type = 'link';
7386  $param['options'] = array($reg[1].':'.$reg[2]=>$reg[1].':'.$reg[2]);
7387  } elseif (preg_match('/^sellist:(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
7388  $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3].':'.$reg[4] => 'N');
7389  $type = 'sellist';
7390  } elseif (preg_match('/^sellist:(.*):(.*):(.*)/i', $val['type'], $reg)) {
7391  $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3] => 'N');
7392  $type = 'sellist';
7393  } elseif (preg_match('/^sellist:(.*):(.*)/i', $val['type'], $reg)) {
7394  $param['options'] = array($reg[1].':'.$reg[2] => 'N');
7395  $type = 'sellist';
7396  }
7397 
7398  $langfile = empty($val['langfile']) ? '' : $val['langfile'];
7399  $list = (empty($val['list']) ? '' : $val['list']);
7400  $help = (empty($val['help']) ? '' : $val['help']);
7401  $hidden = (($val['visible'] == 0) ? 1 : 0); // If zero, we are sure it is hidden, otherwise we show. If it depends on mode (view/create/edit form or list, this must be filtered by caller)
7402 
7403  if ($hidden) {
7404  return '';
7405  }
7406 
7407  // If field is a computed field, value must become result of compute
7408  if ($computed) {
7409  // Make the eval of compute string
7410  //var_dump($computed);
7411  $value = dol_eval($computed, 1, 0, '');
7412  }
7413 
7414  if (empty($morecss)) {
7415  if ($type == 'date') {
7416  $morecss = 'minwidth100imp';
7417  } elseif ($type == 'datetime' || $type == 'timestamp') {
7418  $morecss = 'minwidth200imp';
7419  } elseif (in_array($type, array('int', 'double', 'price'))) {
7420  $morecss = 'maxwidth75';
7421  } elseif ($type == 'url') {
7422  $morecss = 'minwidth400';
7423  } elseif ($type == 'boolean') {
7424  $morecss = '';
7425  } else {
7426  if (is_numeric($size) && round($size) < 12) {
7427  $morecss = 'minwidth100';
7428  } elseif (is_numeric($size) && round($size) <= 48) {
7429  $morecss = 'minwidth200';
7430  } else {
7431  $morecss = 'minwidth400';
7432  }
7433  }
7434  }
7435 
7436  // Format output value differently according to properties of field
7437  if (in_array($key, array('rowid', 'ref')) && method_exists($this, 'getNomUrl')) {
7438  if ($key != 'rowid' || empty($this->fields['ref'])) { // If we want ref field or if we want ID and there is no ref field, we show the link.
7439  $value = $this->getNomUrl(1, '', 0, '', 1);
7440  }
7441  } elseif ($key == 'status' && method_exists($this, 'getLibStatut')) {
7442  $value = $this->getLibStatut(3);
7443  } elseif ($type == 'date') {
7444  if (!empty($value)) {
7445  $value = dol_print_date($value, 'day'); // We suppose dates without time are always gmt (storage of course + output)
7446  } else {
7447  $value = '';
7448  }
7449  } elseif ($type == 'datetime' || $type == 'timestamp') {
7450  if (!empty($value)) {
7451  $value = dol_print_date($value, 'dayhour', 'tzuserrel');
7452  } else {
7453  $value = '';
7454  }
7455  } elseif ($type == 'duration') {
7456  include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
7457  if (!is_null($value) && $value !== '') {
7458  $value = convertSecondToTime($value, 'allhourmin');
7459  }
7460  } elseif ($type == 'double' || $type == 'real') {
7461  if (!is_null($value) && $value !== '') {
7462  $value = price($value);
7463  }
7464  } elseif ($type == 'boolean') {
7465  $checked = '';
7466  if (!empty($value)) {
7467  $checked = ' checked ';
7468  }
7469  $value = '<input type="checkbox" '.$checked.' '.($moreparam ? $moreparam : '').' readonly disabled>';
7470  } elseif ($type == 'mail' || $type == 'email') {
7471  $value = dol_print_email($value, 0, 0, 0, 64, 1, 1);
7472  } elseif ($type == 'url') {
7473  $value = dol_print_url($value, '_blank', 32, 1);
7474  } elseif ($type == 'phone') {
7475  $value = dol_print_phone($value, '', 0, 0, '', '&nbsp;', 'phone');
7476  } elseif ($type == 'price') {
7477  if (!is_null($value) && $value !== '') {
7478  $value = price($value, 0, $langs, 0, 0, -1, $conf->currency);
7479  }
7480  } elseif ($type == 'select') {
7481  $value = isset($param['options'][$value])?$param['options'][$value]:'';
7482  } elseif ($type == 'sellist') {
7483  $param_list = array_keys($param['options']);
7484  $InfoFieldList = explode(":", $param_list[0]);
7485 
7486  $selectkey = "rowid";
7487  $keyList = 'rowid';
7488 
7489  if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
7490  $selectkey = $InfoFieldList[2];
7491  $keyList = $InfoFieldList[2].' as rowid';
7492  }
7493 
7494  $fields_label = explode('|', $InfoFieldList[1]);
7495  if (is_array($fields_label)) {
7496  $keyList .= ', ';
7497  $keyList .= implode(', ', $fields_label);
7498  }
7499 
7500  $sql = "SELECT ".$keyList;
7501  $sql .= ' FROM '.$this->db->prefix().$InfoFieldList[0];
7502  if (strpos($InfoFieldList[4], 'extra') !== false) {
7503  $sql .= ' as main';
7504  }
7505  if ($selectkey == 'rowid' && empty($value)) {
7506  $sql .= " WHERE ".$selectkey." = 0";
7507  } elseif ($selectkey == 'rowid') {
7508  $sql .= " WHERE ".$selectkey." = ".((int) $value);
7509  } else {
7510  $sql .= " WHERE ".$selectkey." = '".$this->db->escape($value)."'";
7511  }
7512 
7513  //$sql.= ' AND entity = '.$conf->entity;
7514 
7515  dol_syslog(get_class($this).':showOutputField:$type=sellist', LOG_DEBUG);
7516  $resql = $this->db->query($sql);
7517  if ($resql) {
7518  $value = ''; // value was used, so now we reste it to use it to build final output
7519  $numrows = $this->db->num_rows($resql);
7520  if ($numrows) {
7521  $obj = $this->db->fetch_object($resql);
7522 
7523  // Several field into label (eq table:code|libelle:rowid)
7524  $fields_label = explode('|', $InfoFieldList[1]);
7525 
7526  if (is_array($fields_label) && count($fields_label) > 1) {
7527  foreach ($fields_label as $field_toshow) {
7528  $translabel = '';
7529  if (!empty($obj->$field_toshow)) {
7530  $translabel = $langs->trans($obj->$field_toshow);
7531  }
7532  if ($translabel != $field_toshow) {
7533  $value .= dol_trunc($translabel, 18).' ';
7534  } else {
7535  $value .= $obj->$field_toshow.' ';
7536  }
7537  }
7538  } else {
7539  $translabel = '';
7540  if (!empty($obj->{$InfoFieldList[1]})) {
7541  $translabel = $langs->trans($obj->{$InfoFieldList[1]});
7542  }
7543  if ($translabel != $obj->{$InfoFieldList[1]}) {
7544  $value = dol_trunc($translabel, 18);
7545  } else {
7546  $value = $obj->{$InfoFieldList[1]};
7547  }
7548  }
7549  }
7550  } else {
7551  dol_syslog(get_class($this).'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
7552  }
7553  } elseif ($type == 'radio') {
7554  $value = $param['options'][$value];
7555  } elseif ($type == 'checkbox') {
7556  $value_arr = explode(',', $value);
7557  $value = '';
7558  if (is_array($value_arr) && count($value_arr) > 0) {
7559  $toprint = array();
7560  foreach ($value_arr as $keyval => $valueval) {
7561  $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">'.$param['options'][$valueval].'</li>';
7562  }
7563  $value = '<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
7564  }
7565  } elseif ($type == 'chkbxlst') {
7566  $value_arr = explode(',', $value);
7567 
7568  $param_list = array_keys($param['options']);
7569  $InfoFieldList = explode(":", $param_list[0]);
7570 
7571  $selectkey = "rowid";
7572  $keyList = 'rowid';
7573 
7574  if (count($InfoFieldList) >= 3) {
7575  $selectkey = $InfoFieldList[2];
7576  $keyList = $InfoFieldList[2].' as rowid';
7577  }
7578 
7579  $fields_label = explode('|', $InfoFieldList[1]);
7580  if (is_array($fields_label)) {
7581  $keyList .= ', ';
7582  $keyList .= implode(', ', $fields_label);
7583  }
7584 
7585  $sql = "SELECT ".$keyList;
7586  $sql .= ' FROM '.$this->db->prefix().$InfoFieldList[0];
7587  if (strpos($InfoFieldList[4], 'extra') !== false) {
7588  $sql .= ' as main';
7589  }
7590  // $sql.= " WHERE ".$selectkey."='".$this->db->escape($value)."'";
7591  // $sql.= ' AND entity = '.$conf->entity;
7592 
7593  dol_syslog(get_class($this).':showOutputField:$type=chkbxlst', LOG_DEBUG);
7594  $resql = $this->db->query($sql);
7595  if ($resql) {
7596  $value = ''; // value was used, so now we reste it to use it to build final output
7597  $toprint = array();
7598  while ($obj = $this->db->fetch_object($resql)) {
7599  // Several field into label (eq table:code|libelle:rowid)
7600  $fields_label = explode('|', $InfoFieldList[1]);
7601  if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
7602  if (is_array($fields_label) && count($fields_label) > 1) {
7603  foreach ($fields_label as $field_toshow) {
7604  $translabel = '';
7605  if (!empty($obj->$field_toshow)) {
7606  $translabel = $langs->trans($obj->$field_toshow);
7607  }
7608  if ($translabel != $field_toshow) {
7609  $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">'.dol_trunc($translabel, 18).'</li>';
7610  } else {
7611  $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">'.$obj->$field_toshow.'</li>';
7612  }
7613  }
7614  } else {
7615  $translabel = '';
7616  if (!empty($obj->{$InfoFieldList[1]})) {
7617  $translabel = $langs->trans($obj->{$InfoFieldList[1]});
7618  }
7619  if ($translabel != $obj->{$InfoFieldList[1]}) {
7620  $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">'.dol_trunc($translabel, 18).'</li>';
7621  } else {
7622  $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">'.$obj->{$InfoFieldList[1]}.'</li>';
7623  }
7624  }
7625  }
7626  }
7627  $value = '<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
7628  } else {
7629  dol_syslog(get_class($this).'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
7630  }
7631  } elseif ($type == 'link') {
7632  $out = '';
7633 
7634  // only if something to display (perf)
7635  if ($value) {
7636  $param_list = array_keys($param['options']); // $param_list='ObjectName:classPath'
7637 
7638  $InfoFieldList = explode(":", $param_list[0]);
7639  $classname = $InfoFieldList[0];
7640  $classpath = $InfoFieldList[1];
7641  $getnomurlparam = (empty($InfoFieldList[2]) ? 3 : $InfoFieldList[2]);
7642  $getnomurlparam2 = (empty($InfoFieldList[4]) ? '' : $InfoFieldList[4]);
7643  if (!empty($classpath)) {
7644  dol_include_once($InfoFieldList[1]);
7645  if ($classname && class_exists($classname)) {
7646  $object = new $classname($this->db);
7647  if ($object->element === 'product') { // Special cas for product because default valut of fetch are wrong
7648  $result = $object->fetch($value, '', '', '', 0, 1, 1);
7649  } else {
7650  $result = $object->fetch($value);
7651  }
7652  if ($result > 0) {
7653  $value = $object->getNomUrl($getnomurlparam, $getnomurlparam2);
7654  } else {
7655  $value = '';
7656  }
7657  }
7658  } else {
7659  dol_syslog('Error bad setup of extrafield', LOG_WARNING);
7660  return 'Error bad setup of extrafield';
7661  }
7662  } else {
7663  $value = '';
7664  }
7665  } elseif ($type == 'password') {
7666  $value = preg_replace('/./i', '*', $value);
7667  } elseif ($type == 'array') {
7668  $value = implode('<br>', $value);
7669  } else { // text|html|varchar
7670  $value = dol_htmlentitiesbr($value);
7671  }
7672 
7673  //print $type.'-'.$size.'-'.$value;
7674  $out = $value;
7675 
7676  return $out;
7677  }
7678 
7685  public function clearFieldError($fieldKey)
7686  {
7687  $this->error = '';
7688  unset($this->validateFieldsErrors[$fieldKey]);
7689  }
7690 
7698  public function setFieldError($fieldKey, $msg = '')
7699  {
7700  global $langs;
7701  if (empty($msg)) { $msg = $langs->trans("UnknowError"); }
7702 
7703  $this->error = $this->validateFieldsErrors[$fieldKey] = $msg;
7704  }
7705 
7712  public function getFieldError($fieldKey)
7713  {
7714  if (!empty($this->validateFieldsErrors[$fieldKey])) {
7715  return $this->validateFieldsErrors[$fieldKey];
7716  }
7717  return '';
7718  }
7719 
7728  public function validateField($val, $fieldKey, $fieldValue)
7729  {
7730  global $langs;
7731 
7732  if (!class_exists('Validate')) { require_once DOL_DOCUMENT_ROOT . '/core/class/validate.class.php'; }
7733 
7734  $this->clearFieldError($fieldKey);
7735 
7736  if (!isset($val[$fieldKey])) {
7737  $this->setFieldError($fieldKey, $langs->trans('FieldNotFoundInObject'));
7738  return false;
7739  }
7740 
7741  $param = array();
7742  $param['options'] = array();
7743  $type = $val[$fieldKey]['type'];
7744 
7745  $required = false;
7746  if (isset($val[$fieldKey]['notnull']) && $val[$fieldKey]['notnull'] === 1) {
7747  // 'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0).
7748  $required = true;
7749  }
7750 
7751  $maxSize = 0;
7752  $minSize = 0;
7753 
7754  //
7755  // PREPARE Elements
7756  //
7757 
7758  // Convert var to be able to share same code than showOutputField of extrafields
7759  if (preg_match('/varchar\((\d+)\)/', $type, $reg)) {
7760  $type = 'varchar'; // convert varchar(xx) int varchar
7761  $maxSize = $reg[1];
7762  } elseif (preg_match('/varchar/', $type)) {
7763  $type = 'varchar'; // convert varchar(xx) int varchar
7764  }
7765 
7766  if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
7767  $type = 'select';
7768  }
7769 
7770  if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) {
7771  $type = 'link';
7772  }
7773 
7774  if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
7775  $param['options'] = $val['arrayofkeyval'];
7776  }
7777 
7778  if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) {
7779  $type = 'link';
7780  $param['options'] = array($reg[1].':'.$reg[2]=>$reg[1].':'.$reg[2]);
7781  } elseif (preg_match('/^sellist:(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
7782  $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3].':'.$reg[4] => 'N');
7783  $type = 'sellist';
7784  } elseif (preg_match('/^sellist:(.*):(.*):(.*)/i', $val['type'], $reg)) {
7785  $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3] => 'N');
7786  $type = 'sellist';
7787  } elseif (preg_match('/^sellist:(.*):(.*)/i', $val['type'], $reg)) {
7788  $param['options'] = array($reg[1].':'.$reg[2] => 'N');
7789  $type = 'sellist';
7790  }
7791 
7792  //
7793  // TEST Value
7794  //
7795 
7796  // Use Validate class to allow external Modules to use data validation part instead of concentrate all test here (factoring) or just for reuse
7797  $validate = new Validate($this->db, $langs);
7798 
7799 
7800  // little trick : to perform tests with good performances sort tests by quick to low
7801 
7802  //
7803  // COMMON TESTS
7804  //
7805 
7806  // Required test and empty value
7807  if ($required && !$validate->isNotEmptyString($fieldValue)) {
7808  $this->setFieldError($fieldKey, $validate->error);
7809  return false;
7810  } elseif (!$required && !$validate->isNotEmptyString($fieldValue)) {
7811  // if no value sent and the field is not mandatory, no need to perform tests
7812  return true;
7813  }
7814 
7815  // MAX Size test
7816  if (!empty($maxSize) && !$validate->isMaxLength($fieldValue, $maxSize)) {
7817  $this->setFieldError($fieldKey, $validate->error);
7818  return false;
7819  }
7820 
7821  // MIN Size test
7822  if (!empty($minSize) && !$validate->isMinLength($fieldValue, $minSize)) {
7823  $this->setFieldError($fieldKey, $validate->error);
7824  return false;
7825  }
7826 
7827  //
7828  // TESTS for TYPE
7829  //
7830 
7831  if (in_array($type, array('date', 'datetime', 'timestamp'))) {
7832  if (!$validate->isTimestamp($fieldValue)) {
7833  $this->setFieldError($fieldKey, $validate->error);
7834  return false;
7835  } else { return true; }
7836  } elseif ($type == 'duration') {
7837  if (!$validate->isDuration($fieldValue)) {
7838  $this->setFieldError($fieldKey, $validate->error);
7839  return false;
7840  } else { return true; }
7841  } elseif (in_array($type, array('double', 'real', 'price'))) {
7842  // is numeric
7843  if (!$validate->isNumeric($fieldValue)) {
7844  $this->setFieldError($fieldKey, $validate->error);
7845  return false;
7846  } else { return true; }
7847  } elseif ($type == 'boolean') {
7848  if (!$validate->isBool($fieldValue)) {
7849  $this->setFieldError($fieldKey, $validate->error);
7850  return false;
7851  } else { return true; }
7852  } elseif ($type == 'mail') {
7853  if (!$validate->isEmail($fieldValue)) {
7854  $this->setFieldError($fieldKey, $validate->error);
7855  return false;
7856  }
7857  } elseif ($type == 'url') {
7858  if (!$validate->isUrl($fieldValue)) {
7859  $this->setFieldError($fieldKey, $validate->error);
7860  return false;
7861  } else { return true; }
7862  } elseif ($type == 'phone') {
7863  if (!$validate->isPhone($fieldValue)) {
7864  $this->setFieldError($fieldKey, $validate->error);
7865  return false;
7866  } else { return true; }
7867  } elseif ($type == 'select' || $type == 'radio') {
7868  if (!isset($param['options'][$fieldValue])) {
7869  $this->error = $langs->trans('RequireValidValue');
7870  return false;
7871  } else { return true; }
7872  } elseif ($type == 'sellist' || $type == 'chkbxlst') {
7873  $param_list = array_keys($param['options']);
7874  $InfoFieldList = explode(":", $param_list[0]);
7875  $value_arr = explode(',', $fieldValue);
7876  $value_arr = array_map(array($this->db, 'escape'), $value_arr);
7877 
7878  $selectkey = "rowid";
7879  if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
7880  $selectkey = $InfoFieldList[2];
7881  }
7882 
7883  if (!$validate->isInDb($value_arr, $InfoFieldList[0], $selectkey)) {
7884  $this->setFieldError($fieldKey, $validate->error);
7885  return false;
7886  } else { return true; }
7887  } elseif ($type == 'link') {
7888  $param_list = array_keys($param['options']); // $param_list='ObjectName:classPath'
7889  $InfoFieldList = explode(":", $param_list[0]);
7890  $classname = $InfoFieldList[0];
7891  $classpath = $InfoFieldList[1];
7892  if (!$validate->isFetchable($fieldValue, $classname, $classpath)) {
7893  $this->setFieldError($fieldKey, $validate->error);
7894  return false;
7895  } else { return true; }
7896  }
7897 
7898  // if no test failled all is ok
7899  return true;
7900  }
7901 
7915  public function showOptionals($extrafields, $mode = 'view', $params = null, $keysuffix = '', $keyprefix = '', $onetrtd = 0, $display_type = 'card')
7916  {
7917  global $db, $conf, $langs, $action, $form, $hookmanager;
7918 
7919  if (!is_object($form)) {
7920  $form = new Form($db);
7921  }
7922  if (!is_object($extrafields)) {
7923  dol_syslog('Bad parameter extrafields for showOptionals', LOG_ERR);
7924  return 'Bad parameter extrafields for showOptionals';
7925  }
7926  if (!is_array($extrafields->attributes[$this->table_element])) {
7927  dol_syslog("extrafields->attributes was not loaded with extrafields->fetch_name_optionals_label(table_element);", LOG_WARNING);
7928  }
7929 
7930  $out = '';
7931 
7932  $parameters = array();
7933  $reshook = $hookmanager->executeHooks('showOptionals', $parameters, $this, $action); // Note that $action and $object may have been modified by hook
7934  if (empty($reshook)) {
7935  if (is_array($extrafields->attributes[$this->table_element]) && key_exists('label', $extrafields->attributes[$this->table_element]) && is_array($extrafields->attributes[$this->table_element]['label']) && count($extrafields->attributes[$this->table_element]['label']) > 0) {
7936  $out .= "\n";
7937  $out .= '<!-- commonobject:showOptionals --> ';
7938  $out .= "\n";
7939 
7940  $extrafields_collapse_num = '';
7941  $e = 0;
7942  foreach ($extrafields->attributes[$this->table_element]['label'] as $key => $label) {
7943  // Show only the key field in params
7944  if (is_array($params) && array_key_exists('onlykey', $params) && $key != $params['onlykey']) {
7945  continue;
7946  }
7947 
7948  // Test on 'enabled' ('enabled' is different than 'list' = 'visibility')
7949  $enabled = 1;
7950  if ($enabled && isset($extrafields->attributes[$this->table_element]['enabled'][$key])) {
7951  $enabled = dol_eval($extrafields->attributes[$this->table_element]['enabled'][$key], 1, 1, '1');
7952  }
7953  if (empty($enabled)) {
7954  continue;
7955  }
7956 
7957  $visibility = 1;
7958  if ($visibility && isset($extrafields->attributes[$this->table_element]['list'][$key])) {
7959  $visibility = dol_eval($extrafields->attributes[$this->table_element]['list'][$key], 1, 1, '1');
7960  }
7961 
7962  $perms = 1;
7963  if ($perms && isset($extrafields->attributes[$this->table_element]['perms'][$key])) {
7964  $perms = dol_eval($extrafields->attributes[$this->table_element]['perms'][$key], 1, 1, '1');
7965  }
7966 
7967  if (($mode == 'create') && abs($visibility) != 1 && abs($visibility) != 3) {
7968  continue; // <> -1 and <> 1 and <> 3 = not visible on forms, only on list
7969  } elseif (($mode == 'edit') && abs($visibility) != 1 && abs($visibility) != 3 && abs($visibility) != 4) {
7970  continue; // <> -1 and <> 1 and <> 3 = not visible on forms, only on list and <> 4 = not visible at the creation
7971  } elseif ($mode == 'view' && empty($visibility)) {
7972  continue;
7973  }
7974  if (empty($perms)) {
7975  continue;
7976  }
7977  // Load language if required
7978  if (!empty($extrafields->attributes[$this->table_element]['langfile'][$key])) {
7979  $langs->load($extrafields->attributes[$this->table_element]['langfile'][$key]);
7980  }
7981 
7982  $colspan = 0;
7983  if (is_array($params) && count($params) > 0 && $display_type=='card') {
7984  if (array_key_exists('cols', $params)) {
7985  $colspan = $params['cols'];
7986  } elseif (array_key_exists('colspan', $params)) { // For backward compatibility. Use cols instead now.
7987  $reg = array();
7988  if (preg_match('/colspan="(\d+)"/', $params['colspan'], $reg)) {
7989  $colspan = $reg[1];
7990  } else {
7991  $colspan = $params['colspan'];
7992  }
7993  }
7994  }
7995  $colspan = intval($colspan);
7996 
7997  switch ($mode) {
7998  case "view":
7999  $value = ((!empty($this->array_options) && array_key_exists("options_".$key.$keysuffix, $this->array_options)) ? $this->array_options["options_".$key.$keysuffix] : null); // Value may be cleaned or formated later
8000  break;
8001  case "create":
8002  case "edit":
8003  // We get the value of property found with GETPOST so it takes into account:
8004  // default values overwrite, restore back to list link, ... (but not 'default value in database' of field)
8005  $check = 'alphanohtml';
8006  if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('html', 'text'))) {
8007  $check = 'restricthtml';
8008  }
8009  $getposttemp = GETPOST($keyprefix.'options_'.$key.$keysuffix, $check, 3); // GETPOST can get value from GET, POST or setup of default values overwrite.
8010  // GETPOST("options_" . $key) can be 'abc' or array(0=>'abc')
8011  if (is_array($getposttemp) || $getposttemp != '' || GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix)) {
8012  if (is_array($getposttemp)) {
8013  // $getposttemp is an array but following code expects a comma separated string
8014  $value = implode(",", $getposttemp);
8015  } else {
8016  $value = $getposttemp;
8017  }
8018  } else {
8019  $value = (!empty($this->array_options["options_".$key]) ? $this->array_options["options_".$key] : ''); // No GET, no POST, no default value, so we take value of object.
8020  }
8021  //var_dump($keyprefix.' - '.$key.' - '.$keysuffix.' - '.$keyprefix.'options_'.$key.$keysuffix.' - '.$this->array_options["options_".$key.$keysuffix].' - '.$getposttemp.' - '.$value);
8022  break;
8023  }
8024 
8025  // Output value of the current field
8026  if ($extrafields->attributes[$this->table_element]['type'][$key] == 'separate') {
8027  $extrafields_collapse_num = '';
8028  $extrafield_param = $extrafields->attributes[$this->table_element]['param'][$key];
8029  if (!empty($extrafield_param) && is_array($extrafield_param)) {
8030  $extrafield_param_list = array_keys($extrafield_param['options']);
8031 
8032  if (count($extrafield_param_list) > 0) {
8033  $extrafield_collapse_display_value = intval($extrafield_param_list[0]);
8034 
8035  if ($extrafield_collapse_display_value == 1 || $extrafield_collapse_display_value == 2) {
8036  $extrafields_collapse_num = $extrafields->attributes[$this->table_element]['pos'][$key];
8037  }
8038  }
8039  }
8040 
8041  // if colspan=0 or 1, the second column is not extended, so the separator must be on 2 columns
8042  $out .= $extrafields->showSeparator($key, $this, ($colspan ? $colspan + 1 : 2), $display_type, $mode);
8043  } else {
8044  $class = (!empty($extrafields->attributes[$this->table_element]['hidden'][$key]) ? 'hideobject ' : '');
8045  $csstyle = '';
8046  if (is_array($params) && count($params) > 0) {
8047  if (array_key_exists('class', $params)) {
8048  $class .= $params['class'].' ';
8049  }
8050  if (array_key_exists('style', $params)) {
8051  $csstyle = $params['style'];
8052  }
8053  }
8054 
8055  // add html5 elements
8056  $domData = ' data-element="extrafield"';
8057  $domData .= ' data-targetelement="'.$this->element.'"';
8058  $domData .= ' data-targetid="'.$this->id.'"';
8059 
8060  $html_id = (empty($this->id) ? '' : 'extrarow-'.$this->element.'_'.$key.'_'.$this->id);
8061  if ($display_type=='card') {
8062  if (!empty($conf->global->MAIN_EXTRAFIELDS_USE_TWO_COLUMS) && ($e % 2) == 0) {
8063  $colspan = 0;
8064  }
8065 
8066  if ($action == 'selectlines') {
8067  $colspan++;
8068  }
8069  }
8070 
8071  // Convert date into timestamp format (value in memory must be a timestamp)
8072  if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('date'))) {
8073  $datenotinstring = null;
8074  if (array_key_exists('options_'.$key, $this->array_options)) {
8075  $datenotinstring = $this->array_options['options_'.$key];
8076  if (!is_numeric($this->array_options['options_'.$key])) { // For backward compatibility
8077  $datenotinstring = $this->db->jdate($datenotinstring);
8078  }
8079  }
8080  $datekey = $keyprefix.'options_'.$key.$keysuffix;
8081  $value = (GETPOSTISSET($datekey)) ? dol_mktime(12, 0, 0, GETPOST($datekey.'month', 'int', 3), GETPOST($datekey.'day', 'int', 3), GETPOST($datekey.'year', 'int', 3)) : $datenotinstring;
8082  }
8083  if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('datetime'))) {
8084  $datenotinstring = null;
8085  if (array_key_exists('options_'.$key, $this->array_options)) {
8086  $datenotinstring = $this->array_options['options_'.$key];
8087  if (!is_numeric($this->array_options['options_'.$key])) { // For backward compatibility
8088  $datenotinstring = $this->db->jdate($datenotinstring);
8089  }
8090  }
8091  $timekey = $keyprefix.'options_'.$key.$keysuffix;
8092  $value = (GETPOSTISSET($timekey)) ? dol_mktime(GETPOST($timekey.'hour', 'int', 3), GETPOST($timekey.'min', 'int', 3), GETPOST($timekey.'sec', 'int', 3), GETPOST($timekey.'month', 'int', 3), GETPOST($timekey.'day', 'int', 3), GETPOST($timekey.'year', 'int', 3), 'tzuserrel') : $datenotinstring;
8093  }
8094  // Convert float submited string into real php numeric (value in memory must be a php numeric)
8095  if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('price', 'double'))) {
8096  if (GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix) || $value) {
8097  $value = price2num($value);
8098  } elseif (isset($this->array_options['options_'.$key])) {
8099  $value = $this->array_options['options_'.$key];
8100  }
8101  }
8102 
8103  // HTML, text, select, integer and varchar: take into account default value in database if in create mode
8104  if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('html', 'text', 'varchar', 'select', 'int', 'boolean'))) {
8105  if ($action == 'create') {
8106  $value = (GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix) || $value) ? $value : $extrafields->attributes[$this->table_element]['default'][$key];
8107  }
8108  }
8109 
8110  $labeltoshow = $langs->trans($label);
8111  $helptoshow = $langs->trans($extrafields->attributes[$this->table_element]['help'][$key]);
8112 
8113  if ($display_type == 'card') {
8114  $out .= '<tr '.($html_id ? 'id="'.$html_id.'" ' : '').$csstyle.' class="field_options_'.$key.' '.$class.$this->element.'_extras_'.$key.' trextrafields_collapse'.$extrafields_collapse_num.(!empty($this->id)?'_'.$this->id:'').'" '.$domData.' >';
8115  if (!empty($conf->global->MAIN_VIEW_LINE_NUMBER) && ($action == 'view' || $action == 'valid' || $action == 'editline')) {
8116  $out .= '<td></td>';
8117  }
8118  $out .= '<td class="titlefieldcreate wordbreak';
8119  } elseif ($display_type == 'line') {
8120  $out .= '<div '.($html_id ? 'id="'.$html_id.'" ' : '').$csstyle.' class="fieldline_options_'.$key.' '.$class.$this->element.'_extras_'.$key.' trextrafields_collapse'.$extrafields_collapse_num.(!empty($this->id)?'_'.$this->id:'').'" '.$domData.' >';
8121  $out .= '<div style="display: inline-block; padding-right:4px" class="titlefieldcreate wordbreak';
8122  }
8123  //$out .= "titlefield";
8124  //if (GETPOST('action', 'restricthtml') == 'create') $out.='create';
8125  // BUG #11554 : For public page, use red dot for required fields, instead of bold label
8126  $tpl_context = isset($params["tpl_context"]) ? $params["tpl_context"] : "none";
8127  if ($tpl_context != "public") { // Public page : red dot instead of fieldrequired characters
8128  if ($mode != 'view' && !empty($extrafields->attributes[$this->table_element]['required'][$key])) {
8129  $out .= ' fieldrequired';
8130  }
8131  }
8132  $out .= '">';
8133  if ($tpl_context == "public") { // Public page : red dot instead of fieldrequired characters
8134  if (!empty($extrafields->attributes[$this->table_element]['help'][$key])) {
8135  $out .= $form->textwithpicto($labeltoshow, $helptoshow);
8136  } else {
8137  $out .= $labeltoshow;
8138  }
8139  if ($mode != 'view' && !empty($extrafields->attributes[$this->table_element]['required'][$key])) {
8140  $out .= '&nbsp;<span style="color: red">*</span>';
8141  }
8142  } else {
8143  if (!empty($extrafields->attributes[$this->table_element]['help'][$key])) {
8144  $out .= $form->textwithpicto($labeltoshow, $helptoshow);
8145  } else {
8146  $out .= $labeltoshow;
8147  }
8148  }
8149 
8150  $out .= ($display_type == 'card' ? '</td>' : '</div>');
8151 
8152  $html_id = !empty($this->id) ? $this->element.'_extras_'.$key.'_'.$this->id : '';
8153  if ($display_type == 'card') {
8154  // a first td column was already output (and may be another on before if MAIN_VIEW_LINE_NUMBER set), so this td is the next one
8155  $out .= '<td '.($html_id ? 'id="'.$html_id.'" ' : '').' class="valuefieldcreate '.$this->element.'_extras_'.$key.'" '.($colspan ? ' colspan="'.$colspan.'"' : '').'>';
8156  } elseif ($display_type == 'line') {
8157  $out .= '<div '.($html_id ? 'id="'.$html_id.'" ' : '').' style="display: inline-block" class="valuefieldcreate '.$this->element.'_extras_'.$key.' extra_inline_'.$extrafields->attributes[$this->table_element]['type'][$key].'">';
8158  }
8159 
8160  switch ($mode) {
8161  case "view":
8162  $out .= $extrafields->showOutputField($key, $value, '', $this->table_element);
8163  break;
8164  case "create":
8165  $out .= $extrafields->showInputField($key, $value, '', $keysuffix, '', 0, $this->id, $this->table_element);
8166  break;
8167  case "edit":
8168  $out .= $extrafields->showInputField($key, $value, '', $keysuffix, '', 0, $this->id, $this->table_element);
8169  break;
8170  }
8171 
8172  $out .= ($display_type=='card' ? '</td>' : '</div>');
8173 
8174  if (!empty($conf->global->MAIN_EXTRAFIELDS_USE_TWO_COLUMS) && (($e % 2) == 1)) {
8175  $out .= ($display_type=='card' ? '</tr>' : '</div>');
8176  } else {
8177  $out .= ($display_type=='card' ? '</tr>' : '</div>');
8178  }
8179  $e++;
8180  }
8181  }
8182  $out .= "\n";
8183  // Add code to manage list depending on others
8184  if (!empty($conf->use_javascript_ajax)) {
8185  $out .= $this->getJSListDependancies();
8186  }
8187 
8188  $out .= '<!-- commonobject:showOptionals end --> '."\n";
8189  }
8190  }
8191 
8192  $out .= $hookmanager->resPrint;
8193 
8194  return $out;
8195  }
8196 
8201  public function getJSListDependancies($type = '_extra')
8202  {
8203  $out = '
8204  <script>
8205  jQuery(document).ready(function() {
8206  function showOptions'.$type.'(child_list, parent_list, orig_select)
8207  {
8208  var val = $("select[name=\""+parent_list+"\"]").val();
8209  var parentVal = parent_list + ":" + val;
8210  if(typeof val == "string"){
8211  if(val != "") {
8212  var options = orig_select.find("option[parent=\""+parentVal+"\"]").clone();
8213  $("select[name=\""+child_list+"\"] option[parent]").remove();
8214  $("select[name=\""+child_list+"\"]").append(options);
8215  } else {
8216  var options = orig_select.find("option[parent]").clone();
8217  $("select[name=\""+child_list+"\"] option[parent]").remove();
8218  $("select[name=\""+child_list+"\"]").append(options);
8219  }
8220  } else if(val > 0) {
8221  var options = orig_select.find("option[parent=\""+parentVal+"\"]").clone();
8222  $("select[name=\""+child_list+"\"] option[parent]").remove();
8223  $("select[name=\""+child_list+"\"]").append(options);
8224  } else {
8225  var options = orig_select.find("option[parent]").clone();
8226  $("select[name=\""+child_list+"\"] option[parent]").remove();
8227  $("select[name=\""+child_list+"\"]").append(options);
8228  }
8229  }
8230  function setListDependencies'.$type.'() {
8231  jQuery("select option[parent]").parent().each(function() {
8232  var orig_select = {};
8233  var child_list = $(this).attr("name");
8234  orig_select[child_list] = $(this).clone();
8235  var parent = $(this).find("option[parent]:first").attr("parent");
8236  var infos = parent.split(":");
8237  var parent_list = infos[0];
8238 
8239  //Hide daughters lists
8240  if ($("#"+child_list).val() == 0 && $("#"+parent_list).val() == 0){
8241  $("#"+child_list).hide();
8242  //Show mother lists
8243  } else if ($("#"+parent_list).val() != 0){
8244  $("#"+parent_list).show();
8245  }
8246  //Show the child list if the parent list value is selected
8247  $("select[name=\""+parent_list+"\"]").click(function() {
8248  if ($(this).val() != 0){
8249  $("#"+child_list).show()
8250  }
8251  });
8252 
8253  //When we change parent list
8254  $("select[name=\""+parent_list+"\"]").change(function() {
8255  showOptions'.$type.'(child_list, parent_list, orig_select[child_list]);
8256  //Select the value 0 on child list after a change on the parent list
8257  $("#"+child_list).val(0).trigger("change");
8258  //Hide child lists if the parent value is set to 0
8259  if ($(this).val() == 0){
8260  $("#"+child_list).hide();
8261  }
8262  });
8263  });
8264  }
8265 
8266  setListDependencies'.$type.'();
8267  });
8268  </script>'."\n";
8269  return $out;
8270  }
8271 
8276  public function getRights()
8277  {
8278  global $user;
8279 
8280  $element = $this->element;
8281  if ($element == 'facturerec') {
8282  $element = 'facture';
8283  } elseif ($element == 'invoice_supplier_rec') {
8284  return $user->rights->fournisseur->facture;
8285  }
8286 
8287  return $user->rights->{$element};
8288  }
8289 
8302  public static function commonReplaceThirdparty(DoliDB $db, $origin_id, $dest_id, array $tables, $ignoreerrors = 0)
8303  {
8304  foreach ($tables as $table) {
8305  $sql = 'UPDATE '.$db->prefix().$table.' SET fk_soc = '.((int) $dest_id).' WHERE fk_soc = '.((int) $origin_id);
8306 
8307  if (!$db->query($sql)) {
8308  if ($ignoreerrors) {
8309  return true; // TODO Not enough. If there is A-B on kept thirdparty and B-C on old one, we must get A-B-C after merge. Not A-B.
8310  }
8311  //$this->errors = $db->lasterror();
8312  return false;
8313  }
8314  }
8315 
8316  return true;
8317  }
8318 
8331  public static function commonReplaceProduct(DoliDB $db, $origin_id, $dest_id, array $tables, $ignoreerrors = 0)
8332  {
8333  foreach ($tables as $table) {
8334  $sql = 'UPDATE '.MAIN_DB_PREFIX.$table.' SET fk_product = '.((int) $dest_id).' WHERE fk_product = '.((int) $origin_id);
8335 
8336  if (!$db->query($sql)) {
8337  if ($ignoreerrors) {
8338  return true; // TODO Not enough. If there is A-B on kept product and B-C on old one, we must get A-B-C after merge. Not A-B.
8339  }
8340  //$this->errors = $db->lasterror();
8341  return false;
8342  }
8343  }
8344 
8345  return true;
8346  }
8347 
8360  public function defineBuyPrice($unitPrice = 0.0, $discountPercent = 0.0, $fk_product = 0)
8361  {
8362  global $conf;
8363 
8364  $buyPrice = 0;
8365 
8366  if (($unitPrice > 0) && (isset($conf->global->ForceBuyingPriceIfNull) && $conf->global->ForceBuyingPriceIfNull > 0)) {
8367  // When ForceBuyingPriceIfNull is set
8368  $buyPrice = $unitPrice * (1 - $discountPercent / 100);
8369  } else {
8370  // Get cost price for margin calculation
8371  if (!empty($fk_product) && $fk_product > 0) {
8372  if (isset($conf->global->MARGIN_TYPE) && $conf->global->MARGIN_TYPE == 'costprice') {
8373  require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
8374  $product = new Product($this->db);
8375  $result = $product->fetch($fk_product);
8376  if ($result <= 0) {
8377  $this->errors[] = 'ErrorProductIdDoesNotExists';
8378  return -1;
8379  }
8380  if ($product->cost_price > 0) {
8381  $buyPrice = $product->cost_price;
8382  } elseif ($product->pmp > 0) {
8383  $buyPrice = $product->pmp;
8384  }
8385  } elseif (isset($conf->global->MARGIN_TYPE) && $conf->global->MARGIN_TYPE == 'pmp') {
8386  require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
8387  $product = new Product($this->db);
8388  $result = $product->fetch($fk_product);
8389  if ($result <= 0) {
8390  $this->errors[] = 'ErrorProductIdDoesNotExists';
8391  return -1;
8392  }
8393  if ($product->pmp > 0) {
8394  $buyPrice = $product->pmp;
8395  }
8396  }
8397 
8398  if (empty($buyPrice) && isset($conf->global->MARGIN_TYPE) && in_array($conf->global->MARGIN_TYPE, array('1', 'pmp', 'costprice'))) {
8399  require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
8400  $productFournisseur = new ProductFournisseur($this->db);
8401  if (($result = $productFournisseur->find_min_price_product_fournisseur($fk_product)) > 0) {
8402  $buyPrice = $productFournisseur->fourn_unitprice;
8403  } elseif ($result < 0) {
8404  $this->errors[] = $productFournisseur->error;
8405  return -2;
8406  }
8407  }
8408  }
8409  }
8410  return $buyPrice;
8411  }
8412 
8413  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
8431  public function show_photos($modulepart, $sdir, $size = 0, $nbmax = 0, $nbbyrow = 5, $showfilename = 0, $showaction = 0, $maxHeight = 120, $maxWidth = 160, $nolink = 0, $notitle = 0, $usesharelink = 0)
8432  {
8433  // phpcs:enable
8434  global $conf, $user, $langs;
8435 
8436  include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
8437  include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
8438 
8439  $sortfield = 'position_name';
8440  $sortorder = 'asc';
8441 
8442  $dir = $sdir.'/';
8443  $pdir = '/';
8444 
8445  $dir .= get_exdir(0, 0, 0, 0, $this, $modulepart);
8446  $pdir .= get_exdir(0, 0, 0, 0, $this, $modulepart);
8447 
8448  // For backward compatibility
8449  if ($modulepart == 'product') {
8450  if (!empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) {
8451  $dir = $sdir.'/'.get_exdir($this->id, 2, 0, 0, $this, $modulepart).$this->id."/photos/";
8452  $pdir = '/'.get_exdir($this->id, 2, 0, 0, $this, $modulepart).$this->id."/photos/";
8453  }
8454  }
8455 
8456  // Defined relative dir to DOL_DATA_ROOT
8457  $relativedir = '';
8458  if ($dir) {
8459  $relativedir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $dir);
8460  $relativedir = preg_replace('/^[\\/]/', '', $relativedir);
8461  $relativedir = preg_replace('/[\\/]$/', '', $relativedir);
8462  }
8463 
8464  $dirthumb = $dir.'thumbs/';
8465  $pdirthumb = $pdir.'thumbs/';
8466 
8467  $return = '<!-- Photo -->'."\n";
8468  $nbphoto = 0;
8469 
8470  $filearray = dol_dir_list($dir, "files", 0, '', '(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) == 'desc' ?SORT_DESC:SORT_ASC), 1);
8471 
8472  /*if (! empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) // For backward compatiblity, we scan also old dirs
8473  {
8474  $filearrayold=dol_dir_list($dirold,"files",0,'','(\.meta|_preview.*\.png)$',$sortfield,(strtolower($sortorder)=='desc'?SORT_DESC:SORT_ASC),1);
8475  $filearray=array_merge($filearray, $filearrayold);
8476  }*/
8477 
8478  completeFileArrayWithDatabaseInfo($filearray, $relativedir);
8479 
8480  if (count($filearray)) {
8481  if ($sortfield && $sortorder) {
8482  $filearray = dol_sort_array($filearray, $sortfield, $sortorder);
8483  }
8484 
8485  foreach ($filearray as $key => $val) {
8486  $photo = '';
8487  $file = $val['name'];
8488 
8489  //if (dol_is_file($dir.$file) && image_format_supported($file) >= 0)
8490  if (image_format_supported($file) >= 0) {
8491  $nbphoto++;
8492  $photo = $file;
8493  $viewfilename = $file;
8494 
8495  if ($size == 1 || $size == 'small') { // Format vignette
8496  // Find name of thumb file
8497  $photo_vignette = basename(getImageFileNameForSize($dir.$file, '_small'));
8498  if (!dol_is_file($dirthumb.$photo_vignette)) {
8499  $photo_vignette = '';
8500  }
8501 
8502  // Get filesize of original file
8503  $imgarray = dol_getImageSize($dir.$photo);
8504 
8505  if ($nbbyrow > 0) {
8506  if ($nbphoto == 1) {
8507  $return .= '<table class="valigntop center centpercent" style="border: 0; padding: 2px; border-spacing: 2px; border-collapse: separate;">';
8508  }
8509 
8510  if ($nbphoto % $nbbyrow == 1) {
8511  $return .= '<tr class="center valignmiddle" style="border: 1px">';
8512  }
8513  $return .= '<td style="width: '.ceil(100 / $nbbyrow).'%" class="photo">';
8514  } elseif ($nbbyrow < 0) {
8515  $return .= '<div class="inline-block">';
8516  }
8517 
8518  $return .= "\n";
8519 
8520  $relativefile = preg_replace('/^\//', '', $pdir.$photo);
8521  if (empty($nolink)) {
8522  $urladvanced = getAdvancedPreviewUrl($modulepart, $relativefile, 0, 'entity='.$this->entity);
8523  if ($urladvanced) {
8524  $return .= '<a href="'.$urladvanced.'">';
8525  } else {
8526  $return .= '<a href="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdir.$photo).'" class="aphoto" target="_blank" rel="noopener noreferrer">';
8527  }
8528  }
8529 
8530  // Show image (width height=$maxHeight)
8531  // Si fichier vignette disponible et image source trop grande, on utilise la vignette, sinon on utilise photo origine
8532  $alt = $langs->transnoentitiesnoconv('File').': '.$relativefile;
8533  $alt .= ' - '.$langs->transnoentitiesnoconv('Size').': '.$imgarray['width'].'x'.$imgarray['height'];
8534  if ($notitle) {
8535  $alt = '';
8536  }
8537 
8538  $addphotorefcss = 1;
8539 
8540  if ($usesharelink) {
8541  if ($val['share']) {
8542  if (empty($maxHeight) || $photo_vignette && $imgarray['height'] > $maxHeight) {
8543  $return .= '<!-- Show original file (thumb not yet available with shared links) -->';
8544  $return .= '<img class="photo photowithmargin'.($addphotorefcss ? ' photoref' : '').'" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/viewimage.php?hashp='.urlencode($val['share']).'" title="'.dol_escape_htmltag($alt).'">';
8545  } else {
8546  $return .= '<!-- Show original file -->';
8547  $return .= '<img class="photo photowithmargin'.($addphotorefcss ? ' photoref' : '').'" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/viewimage.php?hashp='.urlencode($val['share']).'" title="'.dol_escape_htmltag($alt).'">';
8548  }
8549  } else {
8550  $return .= '<!-- Show nophoto file (because file is not shared) -->';
8551  $return .= '<img class="photo photowithmargin'.($addphotorefcss ? ' photoref' : '').'" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/public/theme/common/nophoto.png" title="'.dol_escape_htmltag($alt).'">';
8552  }
8553  } else {
8554  if (empty($maxHeight) || $photo_vignette && $imgarray['height'] > $maxHeight) {
8555  $return .= '<!-- Show thumb -->';
8556  $return .= '<img class="photo photowithmargin'.($addphotorefcss ? ' photoref' : '').' maxwidth150onsmartphone maxwidth200" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdirthumb.$photo_vignette).'" title="'.dol_escape_htmltag($alt).'">';
8557  } else {
8558  $return .= '<!-- Show original file -->';
8559  $return .= '<img class="photo photowithmargin'.($addphotorefcss ? ' photoref' : '').'" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdir.$photo).'" title="'.dol_escape_htmltag($alt).'">';
8560  }
8561  }
8562 
8563  if (empty($nolink)) {
8564  $return .= '</a>';
8565  }
8566  $return .= "\n";
8567 
8568  if ($showfilename) {
8569  $return .= '<br>'.$viewfilename;
8570  }
8571  if ($showaction) {
8572  $return .= '<br>';
8573  // On propose la generation de la vignette si elle n'existe pas et si la taille est superieure aux limites
8574  if ($photo_vignette && (image_format_supported($photo) > 0) && ($this->imgWidth > $maxWidth || $this->imgHeight > $maxHeight)) {
8575  $return .= '<a href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&action=addthumb&token='.newToken().'&file='.urlencode($pdir.$viewfilename).'">'.img_picto($langs->trans('GenerateThumb'), 'refresh').'&nbsp;&nbsp;</a>';
8576  }
8577  // Special cas for product
8578  if ($modulepart == 'product' && ($user->rights->produit->creer || $user->rights->service->creer)) {
8579  // Link to resize
8580  $return .= '<a href="'.DOL_URL_ROOT.'/core/photos_resize.php?modulepart='.urlencode('produit|service').'&id='.$this->id.'&file='.urlencode($pdir.$viewfilename).'" title="'.dol_escape_htmltag($langs->trans("Resize")).'">'.img_picto($langs->trans("Resize"), 'resize', '').'</a> &nbsp; ';
8581 
8582  // Link to delete
8583  $return .= '<a href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&action=delete&token='.newToken().'&file='.urlencode($pdir.$viewfilename).'">';
8584  $return .= img_delete().'</a>';
8585  }
8586  }
8587  $return .= "\n";
8588 
8589  if ($nbbyrow > 0) {
8590  $return .= '</td>';
8591  if (($nbphoto % $nbbyrow) == 0) {
8592  $return .= '</tr>';
8593  }
8594  } elseif ($nbbyrow < 0) {
8595  $return .= '</div>';
8596  }
8597  }
8598 
8599  if (empty($size)) { // Format origine
8600  $return .= '<img class="photo photowithmargin" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdir.$photo).'">';
8601 
8602  if ($showfilename) {
8603  $return .= '<br>'.$viewfilename;
8604  }
8605  if ($showaction) {
8606  // Special case for product
8607  if ($modulepart == 'product' && ($user->rights->produit->creer || $user->rights->service->creer)) {
8608  // Link to resize
8609  $return .= '<a href="'.DOL_URL_ROOT.'/core/photos_resize.php?modulepart='.urlencode('produit|service').'&id='.$this->id.'&file='.urlencode($pdir.$viewfilename).'" title="'.dol_escape_htmltag($langs->trans("Resize")).'">'.img_picto($langs->trans("Resize"), 'resize', '').'</a> &nbsp; ';
8610 
8611  // Link to delete
8612  $return .= '<a href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&action=delete&token='.newToken().'&file='.urlencode($pdir.$viewfilename).'">';
8613  $return .= img_delete().'</a>';
8614  }
8615  }
8616  }
8617 
8618  // On continue ou on arrete de boucler ?
8619  if ($nbmax && $nbphoto >= $nbmax) {
8620  break;
8621  }
8622  }
8623  }
8624 
8625  if ($size == 1 || $size == 'small') {
8626  if ($nbbyrow > 0) {
8627  // Ferme tableau
8628  while ($nbphoto % $nbbyrow) {
8629  $return .= '<td style="width: '.ceil(100 / $nbbyrow).'%">&nbsp;</td>';
8630  $nbphoto++;
8631  }
8632 
8633  if ($nbphoto) {
8634  $return .= '</table>';
8635  }
8636  }
8637  }
8638  }
8639 
8640  $this->nbphoto = $nbphoto;
8641 
8642  return $return;
8643  }
8644 
8645 
8652  protected function isArray($info)
8653  {
8654  if (is_array($info)) {
8655  if (isset($info['type']) && $info['type'] == 'array') {
8656  return true;
8657  } else {
8658  return false;
8659  }
8660  }
8661  return false;
8662  }
8663 
8670  public function isDate($info)
8671  {
8672  if (isset($info['type']) && ($info['type'] == 'date' || $info['type'] == 'datetime' || $info['type'] == 'timestamp')) {
8673  return true;
8674  }
8675  return false;
8676  }
8677 
8684  public function isDuration($info)
8685  {
8686  if (is_array($info)) {
8687  if (isset($info['type']) && ($info['type'] == 'duration')) {
8688  return true;
8689  } else {
8690  return false;
8691  }
8692  } else {
8693  return false;
8694  }
8695  }
8696 
8703  public function isInt($info)
8704  {
8705  if (is_array($info)) {
8706  if (isset($info['type']) && (preg_match('/(^int|int$)/i', $info['type']))) {
8707  return true;
8708  } else {
8709  return false;
8710  }
8711  } else {
8712  return false;
8713  }
8714  }
8715 
8722  public function isFloat($info)
8723  {
8724  if (is_array($info)) {
8725  if (isset($info['type']) && (preg_match('/^(double|real|price)/i', $info['type']))) {
8726  return true;
8727  } else {
8728  return false;
8729  }
8730  }
8731  return false;
8732  }
8733 
8740  public function isText($info)
8741  {
8742  if (is_array($info)) {
8743  if (isset($info['type']) && $info['type'] == 'text') {
8744  return true;
8745  } else {
8746  return false;
8747  }
8748  }
8749  return false;
8750  }
8751 
8758  protected function canBeNull($info)
8759  {
8760  if (is_array($info)) {
8761  if (isset($info['notnull']) && $info['notnull'] != '1') {
8762  return true;
8763  } else {
8764  return false;
8765  }
8766  }
8767  return true;
8768  }
8769 
8776  protected function isForcedToNullIfZero($info)
8777  {
8778  if (is_array($info)) {
8779  if (isset($info['notnull']) && $info['notnull'] == '-1') {
8780  return true;
8781  } else {
8782  return false;
8783  }
8784  }
8785  return false;
8786  }
8787 
8794  protected function isIndex($info)
8795  {
8796  if (is_array($info)) {
8797  if (isset($info['index']) && $info['index'] == true) {
8798  return true;
8799  } else {
8800  return false;
8801  }
8802  }
8803  return false;
8804  }
8805 
8806 
8814  protected function setSaveQuery()
8815  {
8816  global $conf;
8817 
8818  $queryarray = array();
8819  foreach ($this->fields as $field => $info) { // Loop on definition of fields
8820  // Depending on field type ('datetime', ...)
8821  if ($this->isDate($info)) {
8822  if (empty($this->{$field})) {
8823  $queryarray[$field] = null;
8824  } else {
8825  $queryarray[$field] = $this->db->idate($this->{$field});
8826  }
8827  } elseif ($this->isDuration($info)) {
8828  // $this->{$field} may be null, '', 0, '0', 123, '123'
8829  if ((isset($this->{$field}) && $this->{$field} != '') || !empty($info['notnull'])) {
8830  if (!isset($this->{$field})) {
8831  $queryarray[$field] = 0;
8832  } else {
8833  $queryarray[$field] = (int) $this->{$field}; // If '0', it may be set to null later if $info['notnull'] == -1
8834  }
8835  } else {
8836  $queryarray[$field] = null;
8837  }
8838  } elseif ($this->isInt($info) || $this->isFloat($info)) {
8839  if ($field == 'entity' && is_null($this->{$field})) {
8840  $queryarray[$field] = $conf->entity;
8841  } else {
8842  // $this->{$field} may be null, '', 0, '0', 123, '123'
8843  if ((isset($this->{$field}) && $this->{$field} != '') || !empty($info['notnull'])) {
8844  if (!isset($this->{$field})) {
8845  $queryarray[$field] = 0;
8846  } elseif ($this->isInt($info)) {
8847  $queryarray[$field] = (int) $this->{$field}; // If '0', it may be set to null later if $info['notnull'] == -1
8848  } elseif ($this->isFloat($info)) {
8849  $queryarray[$field] = (double) $this->{$field}; // If '0', it may be set to null later if $info['notnull'] == -1
8850  }
8851  } else {
8852  $queryarray[$field] = null;
8853  }
8854  }
8855  } else {
8856  // Note: If $this->{$field} is not defined, it means there is a bug into definition of ->fields or a missing declaration of property
8857  // We should keep the warning generated by this because it is a bug somewhere else in code, not here.
8858  $queryarray[$field] = $this->{$field};
8859  }
8860 
8861  if ($info['type'] == 'timestamp' && empty($queryarray[$field])) {
8862  unset($queryarray[$field]);
8863  }
8864  if (!empty($info['notnull']) && $info['notnull'] == -1 && empty($queryarray[$field])) {
8865  $queryarray[$field] = null; // May force 0 to null
8866  }
8867  }
8868 
8869  return $queryarray;
8870  }
8871 
8878  public function setVarsFromFetchObj(&$obj)
8879  {
8880  global $db;
8881 
8882  foreach ($this->fields as $field => $info) {
8883  if ($this->isDate($info)) {
8884  if (is_null($obj->{$field}) || $obj->{$field} === '' || $obj->{$field} === '0000-00-00 00:00:00' || $obj->{$field} === '1000-01-01 00:00:00') {
8885  $this->{$field} = '';
8886  } else {
8887  $this->{$field} = $db->jdate($obj->{$field});
8888  }
8889  } elseif ($this->isInt($info)) {
8890  if ($field == 'rowid') {
8891  $this->id = (int) $obj->{$field};
8892  } else {
8893  if ($this->isForcedToNullIfZero($info)) {
8894  if (empty($obj->{$field})) {
8895  $this->{$field} = null;
8896  } else {
8897  $this->{$field} = (double) $obj->{$field};
8898  }
8899  } else {
8900  if (!is_null($obj->{$field}) || (isset($info['notnull']) && $info['notnull'] == 1)) {
8901  $this->{$field} = (int) $obj->{$field};
8902  } else {
8903  $this->{$field} = null;
8904  }
8905  }
8906  }
8907  } elseif ($this->isFloat($info)) {
8908  if ($this->isForcedToNullIfZero($info)) {
8909  if (empty($obj->{$field})) {
8910  $this->{$field} = null;
8911  } else {
8912  $this->{$field} = (double) $obj->{$field};
8913  }
8914  } else {
8915  if (!is_null($obj->{$field}) || (isset($info['notnull']) && $info['notnull'] == 1)) {
8916  $this->{$field} = (double) $obj->{$field};
8917  } else {
8918  $this->{$field} = null;
8919  }
8920  }
8921  } else {
8922  $this->{$field} = isset($obj->{$field}) ? $obj->{$field} : null;
8923  }
8924  }
8925 
8926  // If there is no 'ref' field, we force property ->ref to ->id for a better compatibility with common functions.
8927  if (!isset($this->fields['ref']) && isset($this->id)) {
8928  $this->ref = $this->id;
8929  }
8930  }
8931 
8938  public function getFieldList($alias = '')
8939  {
8940  $keys = array_keys($this->fields);
8941  if (!empty($alias)) {
8942  $keys_with_alias = array();
8943  foreach ($keys as $fieldname) {
8944  $keys_with_alias[] = $alias . '.' . $fieldname;
8945  }
8946  return implode(',', $keys_with_alias);
8947  } else {
8948  return implode(',', $keys);
8949  }
8950  }
8951 
8959  protected function quote($value, $fieldsentry)
8960  {
8961  if (is_null($value)) {
8962  return 'NULL';
8963  } elseif (preg_match('/^(int|double|real|price)/i', $fieldsentry['type'])) {
8964  return price2num("$value");
8965  } elseif (preg_match('/int$/i', $fieldsentry['type'])) {
8966  return (int) $value;
8967  } elseif ($fieldsentry['type'] == 'boolean') {
8968  if ($value) {
8969  return 'true';
8970  } else {
8971  return 'false';
8972  }
8973  } else {
8974  return "'".$this->db->escape($value)."'";
8975  }
8976  }
8977 
8978 
8986  public function createCommon(User $user, $notrigger = false)
8987  {
8988  global $langs;
8989  dol_syslog(get_class($this)."::createCommon create", LOG_DEBUG);
8990 
8991  $error = 0;
8992 
8993  $now = dol_now();
8994 
8995  $fieldvalues = $this->setSaveQuery();
8996 
8997  if (array_key_exists('date_creation', $fieldvalues) && empty($fieldvalues['date_creation'])) {
8998  $fieldvalues['date_creation'] = $this->db->idate($now);
8999  }
9000  if (array_key_exists('fk_user_creat', $fieldvalues) && !($fieldvalues['fk_user_creat'] > 0)) {
9001  $fieldvalues['fk_user_creat'] = $user->id;
9002  }
9003  unset($fieldvalues['rowid']); // The field 'rowid' is reserved field name for autoincrement field so we don't need it into insert.
9004  if (array_key_exists('ref', $fieldvalues)) {
9005  $fieldvalues['ref'] = dol_string_nospecial($fieldvalues['ref']); // If field is a ref, we sanitize data
9006  }
9007 
9008  $keys = array();
9009  $values = array(); // Array to store string forged for SQL syntax
9010  foreach ($fieldvalues as $k => $v) {
9011  $keys[$k] = $k;
9012  $value = $this->fields[$k];
9013  $values[$k] = $this->quote($v, $value); // May return string 'NULL' if $value is null
9014  }
9015 
9016  // Clean and check mandatory
9017  foreach ($keys as $key) {
9018  // If field is an implicit foreign key field (so type = 'integer:...')
9019  if (preg_match('/^integer:/i', $this->fields[$key]['type']) && $values[$key] == '-1') {
9020  $values[$key] = '';
9021  }
9022  if (!empty($this->fields[$key]['foreignkey']) && $values[$key] == '-1') {
9023  $values[$key] = '';
9024  }
9025 
9026  if (isset($this->fields[$key]['notnull']) && $this->fields[$key]['notnull'] == 1 && (!isset($values[$key]) || $values[$key] === 'NULL') && is_null($this->fields[$key]['default'])) {
9027  $error++;
9028  $langs->load("errors");
9029  dol_syslog("Mandatory field '".$key."' is empty and required into ->fields definition of class");
9030  $this->errors[] = $langs->trans("ErrorFieldRequired", $this->fields[$key]['label']);
9031  }
9032 
9033  // If value is null and there is a default value for field
9034  if (isset($this->fields[$key]['notnull']) && $this->fields[$key]['notnull'] == 1 && (!isset($values[$key]) || $values[$key] === 'NULL') && !is_null($this->fields[$key]['default'])) {
9035  $values[$key] = $this->quote($this->fields[$key]['default'], $this->fields[$key]);
9036  }
9037 
9038  // If field is an implicit foreign key field (so type = 'integer:...')
9039  if (preg_match('/^integer:/i', $this->fields[$key]['type']) && empty($values[$key])) {
9040  if (isset($this->fields[$key]['default'])) {
9041  $values[$key] = ((int) $this->fields[$key]['default']);
9042  } else {
9043  $values[$key] = 'null';
9044  }
9045  }
9046  if (!empty($this->fields[$key]['foreignkey']) && empty($values[$key])) {
9047  $values[$key] = 'null';
9048  }
9049  }
9050 
9051  if ($error) {
9052  return -1;
9053  }
9054 
9055  $this->db->begin();
9056 
9057  if (!$error) {
9058  $sql = "INSERT INTO ".$this->db->prefix().$this->table_element;
9059  $sql .= " (".implode(", ", $keys).')';
9060  $sql .= " VALUES (".implode(", ", $values).")"; // $values can contains 'abc' or 123
9061 
9062  $res = $this->db->query($sql);
9063  if (!$res) {
9064  $error++;
9065  if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
9066  $this->errors[] = "ErrorRefAlreadyExists";
9067  } else {
9068  $this->errors[] = $this->db->lasterror();
9069  }
9070  }
9071  }
9072 
9073  if (!$error) {
9074  $this->id = $this->db->last_insert_id($this->db->prefix().$this->table_element);
9075  }
9076 
9077  // If we have a field ref with a default value of (PROV)
9078  if (!$error) {
9079  if (key_exists('ref', $this->fields) && $this->fields['ref']['notnull'] > 0 && key_exists('default', $this->fields['ref']) && $this->fields['ref']['default'] == '(PROV)') {
9080  $sql = "UPDATE ".$this->db->prefix().$this->table_element." SET ref = '(PROV".((int) $this->id).")' WHERE (ref = '(PROV)' OR ref = '') AND rowid = ".((int) $this->id);
9081  $resqlupdate = $this->db->query($sql);
9082 
9083  if ($resqlupdate === false) {
9084  $error++;
9085  $this->errors[] = $this->db->lasterror();
9086  } else {
9087  $this->ref = '(PROV'.$this->id.')';
9088  }
9089  }
9090  }
9091 
9092  // Create extrafields
9093  if (!$error) {
9094  $result = $this->insertExtraFields();
9095  if ($result < 0) {
9096  $error++;
9097  }
9098  }
9099 
9100  // Create lines
9101  if (!empty($this->table_element_line) && !empty($this->fk_element)) {
9102  $num = (is_array($this->lines) ? count($this->lines) : 0);
9103  for ($i = 0; $i < $num; $i++) {
9104  $line = $this->lines[$i];
9105 
9106  $keyforparent = $this->fk_element;
9107  $line->$keyforparent = $this->id;
9108 
9109  // Test and convert into object this->lines[$i]. When coming from REST API, we may still have an array
9110  //if (! is_object($line)) $line=json_decode(json_encode($line), false); // convert recursively array into object.
9111  if (!is_object($line)) {
9112  $line = (object) $line;
9113  }
9114 
9115  $result = $line->create($user, 1);
9116  if ($result < 0) {
9117  $this->error = $line->error;
9118  $this->db->rollback();
9119  return -1;
9120  }
9121  }
9122  }
9123 
9124  // Triggers
9125  if (!$error && !$notrigger) {
9126  // Call triggers
9127  $result = $this->call_trigger(strtoupper(get_class($this)).'_CREATE', $user);
9128  if ($result < 0) {
9129  $error++;
9130  }
9131  // End call triggers
9132  }
9133 
9134  // Commit or rollback
9135  if ($error) {
9136  $this->db->rollback();
9137  return -1;
9138  } else {
9139  $this->db->commit();
9140  return $this->id;
9141  }
9142  }
9143 
9144 
9153  public function fetchCommon($id, $ref = null, $morewhere = '')
9154  {
9155  if (empty($id) && empty($ref) && empty($morewhere)) {
9156  return -1;
9157  }
9158 
9159  $fieldlist = $this->getFieldList('t');
9160  if (empty($fieldlist)) {
9161  return 0;
9162  }
9163 
9164  $sql = "SELECT ".$fieldlist;
9165  $sql .= " FROM ".$this->db->prefix().$this->table_element.' as t';
9166 
9167  if (!empty($id)) {
9168  $sql .= ' WHERE t.rowid = '.((int) $id);
9169  } elseif (!empty($ref)) {
9170  $sql .= " WHERE t.ref = '".$this->db->escape($ref)."'";
9171  } else {
9172  $sql .= ' WHERE 1 = 1'; // usage with empty id and empty ref is very rare
9173  }
9174  if (empty($id) && isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
9175  $sql .= ' AND t.entity IN ('.getEntity($this->table_element).')';
9176  }
9177  if ($morewhere) {
9178  $sql .= $morewhere;
9179  }
9180  $sql .= ' LIMIT 1'; // This is a fetch, to be sure to get only one record
9181 
9182  $res = $this->db->query($sql);
9183  if ($res) {
9184  $obj = $this->db->fetch_object($res);
9185  if ($obj) {
9186  $this->setVarsFromFetchObj($obj);
9187 
9188  // Retrieve all extrafield
9189  // fetch optionals attributes and labels
9190  $this->fetch_optionals();
9191 
9192  return $this->id;
9193  } else {
9194  return 0;
9195  }
9196  } else {
9197  $this->error = $this->db->lasterror();
9198  $this->errors[] = $this->error;
9199  return -1;
9200  }
9201  }
9202 
9209  public function fetchLinesCommon($morewhere = '')
9210  {
9211  $objectlineclassname = get_class($this).'Line';
9212  if (!class_exists($objectlineclassname)) {
9213  $this->error = 'Error, class '.$objectlineclassname.' not found during call of fetchLinesCommon';
9214  return -1;
9215  }
9216 
9217  $objectline = new $objectlineclassname($this->db);
9218 
9219  $sql = "SELECT ".$objectline->getFieldList('l');
9220  $sql .= " FROM ".$this->db->prefix().$objectline->table_element." as l";
9221  $sql .= " WHERE l.fk_".$this->db->escape($this->element)." = ".((int) $this->id);
9222  if ($morewhere) {
9223  $sql .= $morewhere;
9224  }
9225  if (isset($objectline->fields['position'])) {
9226  $sql .= $this->db->order('position', 'ASC');
9227  }
9228 
9229  $resql = $this->db->query($sql);
9230  if ($resql) {
9231  $num_rows = $this->db->num_rows($resql);
9232  $i = 0;
9233  while ($i < $num_rows) {
9234  $obj = $this->db->fetch_object($resql);
9235  if ($obj) {
9236  $newline = new $objectlineclassname($this->db);
9237  $newline->setVarsFromFetchObj($obj);
9238 
9239  $this->lines[] = $newline;
9240  }
9241  $i++;
9242  }
9243 
9244  return 1;
9245  } else {
9246  $this->error = $this->db->lasterror();
9247  $this->errors[] = $this->error;
9248  return -1;
9249  }
9250  }
9251 
9259  public function updateCommon(User $user, $notrigger = false)
9260  {
9261  global $conf, $langs;
9262  dol_syslog(get_class($this)."::updateCommon update", LOG_DEBUG);
9263 
9264  $error = 0;
9265 
9266  $now = dol_now();
9267 
9268  $fieldvalues = $this->setSaveQuery();
9269 
9270  if (array_key_exists('date_modification', $fieldvalues) && empty($fieldvalues['date_modification'])) {
9271  $fieldvalues['date_modification'] = $this->db->idate($now);
9272  }
9273  if (array_key_exists('fk_user_modif', $fieldvalues) && !($fieldvalues['fk_user_modif'] > 0)) {
9274  $fieldvalues['fk_user_modif'] = $user->id;
9275  }
9276  unset($fieldvalues['rowid']); // The field 'rowid' is reserved field name for autoincrement field so we don't need it into update.
9277  if (array_key_exists('ref', $fieldvalues)) {
9278  $fieldvalues['ref'] = dol_string_nospecial($fieldvalues['ref']); // If field is a ref, we sanitize data
9279  }
9280 
9281  // Add quotes and escape on fields with type string
9282  $keys = array();
9283  $values = array();
9284  $tmp = array();
9285  foreach ($fieldvalues as $k => $v) {
9286  $keys[$k] = $k;
9287  $value = $this->fields[$k];
9288  $values[$k] = $this->quote($v, $value);
9289  $tmp[] = $k.'='.$this->quote($v, $this->fields[$k]);
9290  }
9291 
9292  // Clean and check mandatory fields
9293  foreach ($keys as $key) {
9294  if (preg_match('/^integer:/i', $this->fields[$key]['type']) && $values[$key] == '-1') {
9295  $values[$key] = ''; // This is an implicit foreign key field
9296  }
9297  if (!empty($this->fields[$key]['foreignkey']) && $values[$key] == '-1') {
9298  $values[$key] = ''; // This is an explicit foreign key field
9299  }
9300 
9301  //var_dump($key.'-'.$values[$key].'-'.($this->fields[$key]['notnull'] == 1));
9302  /*
9303  if ($this->fields[$key]['notnull'] == 1 && empty($values[$key]))
9304  {
9305  $error++;
9306  $this->errors[]=$langs->trans("ErrorFieldRequired", $this->fields[$key]['label']);
9307  }*/
9308  }
9309 
9310  $sql = 'UPDATE '.$this->db->prefix().$this->table_element.' SET '.implode(', ', $tmp).' WHERE rowid='.((int) $this->id);
9311 
9312  $this->db->begin();
9313  if (!$error) {
9314  $res = $this->db->query($sql);
9315  if (!$res) {
9316  $error++;
9317  $this->errors[] = $this->db->lasterror();
9318  }
9319  }
9320 
9321  // Update extrafield
9322  if (!$error) {
9323  $result = $this->insertExtraFields();
9324  if ($result < 0) {
9325  $error++;
9326  }
9327  }
9328 
9329  // Triggers
9330  if (!$error && !$notrigger) {
9331  // Call triggers
9332  $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $user);
9333  if ($result < 0) {
9334  $error++;
9335  } //Do also here what you must do to rollback action if trigger fail
9336  // End call triggers
9337  }
9338 
9339  // Commit or rollback
9340  if ($error) {
9341  $this->db->rollback();
9342  return -1;
9343  } else {
9344  $this->db->commit();
9345  return $this->id;
9346  }
9347  }
9348 
9357  public function deleteCommon(User $user, $notrigger = false, $forcechilddeletion = 0)
9358  {
9359  dol_syslog(get_class($this)."::deleteCommon delete", LOG_DEBUG);
9360 
9361  $error = 0;
9362 
9363  $this->db->begin();
9364 
9365  if ($forcechilddeletion) { // Force also delete of childtables that should lock deletion in standard case when option force is off
9366  foreach ($this->childtables as $table) {
9367  $sql = "DELETE FROM ".$this->db->prefix().$table." WHERE ".$this->fk_element." = ".((int) $this->id);
9368  $resql = $this->db->query($sql);
9369  if (!$resql) {
9370  $this->error = $this->db->lasterror();
9371  $this->errors[] = $this->error;
9372  $this->db->rollback();
9373  return -1;
9374  }
9375  }
9376  } elseif (!empty($this->fk_element) && !empty($this->childtables)) { // If object has childs linked with a foreign key field, we check all child tables.
9377  $objectisused = $this->isObjectUsed($this->id);
9378  if (!empty($objectisused)) {
9379  dol_syslog(get_class($this)."::deleteCommon Can't delete record as it has some child", LOG_WARNING);
9380  $this->error = 'ErrorRecordHasChildren';
9381  $this->errors[] = $this->error;
9382  $this->db->rollback();
9383  return 0;
9384  }
9385  }
9386 
9387  // Delete cascade first
9388  if (is_array($this->childtablesoncascade) && !empty($this->childtablesoncascade)) {
9389  foreach ($this->childtablesoncascade as $table) {
9390  $deleteFromObject = explode(':', $table);
9391  if (count($deleteFromObject) >= 2) {
9392  $className = str_replace('@', '', $deleteFromObject[0]);
9393  $filePath = $deleteFromObject[1];
9394  $columnName = $deleteFromObject[2];
9395  $TMoreSQL = array();
9396  $more_sql = $deleteFromObject[3];
9397  if (!empty($more_sql)) {
9398  $TMoreSQL['customsql'] = $more_sql;
9399  }
9400  if (dol_include_once($filePath)) {
9401  $childObject = new $className($this->db);
9402  if (method_exists($childObject, 'deleteByParentField')) {
9403  $result = $childObject->deleteByParentField($this->id, $columnName, $TMoreSQL);
9404  if ($result < 0) {
9405  $error++;
9406  $this->errors[] = $childObject->error;
9407  break;
9408  }
9409  } else {
9410  $error++;
9411  $this->errors[] = "You defined a cascade delete on an object $childObject but there is no method deleteByParentField for it";
9412  break;
9413  }
9414  } else {
9415  $error++;
9416  $this->errors[] = 'Cannot include child class file '.$filePath;
9417  break;
9418  }
9419  } else {
9420  // Delete record in child table
9421  $sql = "DELETE FROM ".$this->db->prefix().$table." WHERE ".$this->fk_element." = ".((int) $this->id);
9422 
9423  $resql = $this->db->query($sql);
9424  if (!$resql) {
9425  $error++;
9426  $this->error = $this->db->lasterror();
9427  $this->errors[] = $this->error;
9428  break;
9429  }
9430  }
9431  }
9432  }
9433 
9434  if (!$error) {
9435  if (!$notrigger) {
9436  // Call triggers
9437  $result = $this->call_trigger(strtoupper(get_class($this)).'_DELETE', $user);
9438  if ($result < 0) {
9439  $error++;
9440  } // Do also here what you must do to rollback action if trigger fail
9441  // End call triggers
9442  }
9443  }
9444 
9445  // Delete llx_ecm_files
9446  if (!$error) {
9447  $res = $this->deleteEcmFiles(1); // Deleting files physically is done later with the dol_delete_dir_recursive
9448  if (!$res) {
9449  $error++;
9450  }
9451  }
9452 
9453  if (!$error && !empty($this->isextrafieldmanaged)) {
9454  $result = $this->deleteExtraFields();
9455  if ($result < 0) {
9456  $error++;
9457  }
9458  }
9459 
9460  if (!$error) {
9461  $sql = 'DELETE FROM '.$this->db->prefix().$this->table_element.' WHERE rowid='.((int) $this->id);
9462 
9463  $resql = $this->db->query($sql);
9464  if (!$resql) {
9465  $error++;
9466  $this->errors[] = $this->db->lasterror();
9467  }
9468  }
9469 
9470  // Commit or rollback
9471  if ($error) {
9472  $this->db->rollback();
9473  return -1;
9474  } else {
9475  $this->db->commit();
9476  return 1;
9477  }
9478  }
9479 
9490  public function deleteByParentField($parentId = 0, $parentField = '', $filter = array(), $filtermode = "AND")
9491  {
9492  global $user;
9493 
9494  $error = 0;
9495  $deleted = 0;
9496 
9497  if (!empty($parentId) && !empty($parentField)) {
9498  $this->db->begin();
9499 
9500  $sql = "SELECT rowid FROM ".$this->db->prefix().$this->table_element;
9501  $sql .= " WHERE ".$parentField." = ".(int) $parentId;
9502 
9503  // Manage filters
9504  $sqlwhere = array();
9505  if (count($filter) > 0) {
9506  foreach ($filter as $key => $value) {
9507  if ($key == 'customsql') {
9508  $sqlwhere[] = $value;
9509  } elseif (strpos($value, '%') === false) {
9510  $sqlwhere[] = $key." IN (".$this->db->sanitize($this->db->escape($value)).")";
9511  } else {
9512  $sqlwhere[] = $key." LIKE '%".$this->db->escape($value)."%'";
9513  }
9514  }
9515  }
9516  if (count($sqlwhere) > 0) {
9517  $sql .= " AND (".implode(" ".$filtermode." ", $sqlwhere).")";
9518  }
9519 
9520  $resql = $this->db->query($sql);
9521  if (!$resql) {
9522  $this->errors[] = $this->db->lasterror();
9523  $error++;
9524  } else {
9525  while ($obj = $this->db->fetch_object($resql)) {
9526  $result = $this->fetch($obj->rowid);
9527  if ($result < 0) {
9528  $error++;
9529  $this->errors[] = $this->error;
9530  } else {
9531  if (get_class($this) == 'Contact') { // TODO special code because delete() for contact has not been standardized like other delete.
9532  $result = $this->delete();
9533  } else {
9534  $result = $this->delete($user);
9535  }
9536  if ($result < 0) {
9537  $error++;
9538  $this->errors[] = $this->error;
9539  } else {
9540  $deleted++;
9541  }
9542  }
9543  }
9544  }
9545 
9546  if (empty($error)) {
9547  $this->db->commit();
9548  return $deleted;
9549  } else {
9550  $this->error = implode(', ', $this->errors);
9551  $this->db->rollback();
9552  return $error * -1;
9553  }
9554  }
9555 
9556  return $deleted;
9557  }
9558 
9567  public function deleteLineCommon(User $user, $idline, $notrigger = false)
9568  {
9569  global $conf;
9570 
9571  $error = 0;
9572 
9573  $tmpforobjectclass = get_class($this);
9574  $tmpforobjectlineclass = ucfirst($tmpforobjectclass).'Line';
9575 
9576  // Call trigger
9577  $result = $this->call_trigger('LINE'.strtoupper($tmpforobjectclass).'_DELETE', $user);
9578  if ($result < 0) {
9579  return -1;
9580  }
9581  // End call triggers
9582 
9583  $this->db->begin();
9584 
9585  $sql = "DELETE FROM ".$this->db->prefix().$this->table_element_line;
9586  $sql .= " WHERE rowid = ".((int) $idline);
9587 
9588  dol_syslog(get_class($this)."::deleteLineCommon", LOG_DEBUG);
9589  $resql = $this->db->query($sql);
9590  if (!$resql) {
9591  $this->error = "Error ".$this->db->lasterror();
9592  $error++;
9593  }
9594 
9595  if (empty($error)) {
9596  // Remove extrafields
9597  $tmpobjectline = new $tmpforobjectlineclass($this->db);
9598  if (!isset($tmpobjectline->isextrafieldmanaged) || !empty($tmpobjectline->isextrafieldmanaged)) {
9599  $tmpobjectline->id = $idline;
9600  $result = $tmpobjectline->deleteExtraFields();
9601  if ($result < 0) {
9602  $error++;
9603  $this->error = "Error ".get_class($this)."::deleteLineCommon deleteExtraFields error -4 ".$tmpobjectline->error;
9604  }
9605  }
9606  }
9607 
9608  if (empty($error)) {
9609  $this->db->commit();
9610  return 1;
9611  } else {
9612  dol_syslog(get_class($this)."::deleteLineCommon ERROR:".$this->error, LOG_ERR);
9613  $this->db->rollback();
9614  return -1;
9615  }
9616  }
9617 
9618 
9628  public function setStatusCommon($user, $status, $notrigger = 0, $triggercode = '')
9629  {
9630  $error = 0;
9631 
9632  $this->db->begin();
9633 
9634  $statusfield = 'status';
9635  if ($this->element == 'don' || $this->element == 'donation') {
9636  $statusfield = 'fk_statut';
9637  }
9638 
9639  $sql = "UPDATE ".$this->db->prefix().$this->table_element;
9640  $sql .= " SET ".$statusfield." = ".((int) $status);
9641  $sql .= " WHERE rowid = ".((int) $this->id);
9642 
9643  if ($this->db->query($sql)) {
9644  if (!$error) {
9645  $this->oldcopy = clone $this;
9646  }
9647 
9648  if (!$error && !$notrigger) {
9649  // Call trigger
9650  $result = $this->call_trigger($triggercode, $user);
9651  if ($result < 0) {
9652  $error++;
9653  }
9654  }
9655 
9656  if (!$error) {
9657  $this->status = $status;
9658  $this->db->commit();
9659  return 1;
9660  } else {
9661  $this->db->rollback();
9662  return -1;
9663  }
9664  } else {
9665  $this->error = $this->db->error();
9666  $this->db->rollback();
9667  return -1;
9668  }
9669  }
9670 
9671 
9678  public function initAsSpecimenCommon()
9679  {
9680  global $user;
9681 
9682  $this->id = 0;
9683  $this->specimen = 1;
9684  $fields = array(
9685  'label' => 'This is label',
9686  'ref' => 'ABCD1234',
9687  'description' => 'This is a description',
9688  'qty' => 123.12,
9689  'note_public' => 'Public note',
9690  'note_private' => 'Private note',
9691  'date_creation' => (dol_now() - 3600 * 48),
9692  'date_modification' => (dol_now() - 3600 * 24),
9693  'fk_user_creat' => $user->id,
9694  'fk_user_modif' => $user->id,
9695  'date' => dol_now(),
9696  );
9697  foreach ($fields as $key => $value) {
9698  if (array_key_exists($key, $this->fields)) {
9699  $this->{$key} = $value;
9700  }
9701  }
9702  return 1;
9703  }
9704 
9705 
9706  /* Part for comments */
9707 
9712  public function fetchComments()
9713  {
9714  require_once DOL_DOCUMENT_ROOT.'/core/class/comment.class.php';
9715 
9716  $comment = new Comment($this->db);
9717  $result = $comment->fetchAllFor($this->element, $this->id);
9718  if ($result < 0) {
9719  $this->errors = array_merge($this->errors, $comment->errors);
9720  return -1;
9721  } else {
9722  $this->comments = $comment->comments;
9723  }
9724  return count($this->comments);
9725  }
9726 
9732  public function getNbComments()
9733  {
9734  return count($this->comments);
9735  }
9736 
9743  public function trimParameters($parameters)
9744  {
9745  if (!is_array($parameters)) {
9746  return;
9747  }
9748  foreach ($parameters as $parameter) {
9749  if (isset($this->$parameter)) {
9750  $this->$parameter = trim($this->$parameter);
9751  }
9752  }
9753  }
9754 
9755  /* Part for categories/tags */
9756 
9767  public function getCategoriesCommon($type_categ)
9768  {
9769  require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
9770 
9771  // Get current categories
9772  $c = new Categorie($this->db);
9773  $existing = $c->containing($this->id, $type_categ, 'id');
9774 
9775  return $existing;
9776  }
9777 
9790  public function setCategoriesCommon($categories, $type_categ = '', $remove_existing = true)
9791  {
9792  // Handle single category
9793  if (!is_array($categories)) {
9794  $categories = array($categories);
9795  }
9796 
9797  dol_syslog(get_class($this)."::setCategoriesCommon Oject Id:".$this->id.' type_categ:'.$type_categ.' nb tag add:'.count($categories), LOG_DEBUG);
9798 
9799  require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
9800 
9801  if (empty($type_categ)) {
9802  dol_syslog(__METHOD__.': Type '.$type_categ.'is an unknown category type. Done nothing.', LOG_ERR);
9803  return -1;
9804  }
9805 
9806  // Get current categories
9807  $c = new Categorie($this->db);
9808  $existing = $c->containing($this->id, $type_categ, 'id');
9809  if ($remove_existing) {
9810  // Diff
9811  if (is_array($existing)) {
9812  $to_del = array_diff($existing, $categories);
9813  $to_add = array_diff($categories, $existing);
9814  } else {
9815  $to_del = array(); // Nothing to delete
9816  $to_add = $categories;
9817  }
9818  } else {
9819  $to_del = array(); // Nothing to delete
9820  $to_add = array_diff($categories, $existing);
9821  }
9822 
9823  $error = 0;
9824  $ok = 0;
9825 
9826  // Process
9827  foreach ($to_del as $del) {
9828  if ($c->fetch($del) > 0) {
9829  $result=$c->del_type($this, $type_categ);
9830  if ($result < 0) {
9831  $error++;
9832  $this->error = $c->error;
9833  $this->errors = $c->errors;
9834  break;
9835  } else {
9836  $ok += $result;
9837  }
9838  }
9839  }
9840  foreach ($to_add as $add) {
9841  if ($c->fetch($add) > 0) {
9842  $result = $c->add_type($this, $type_categ);
9843  if ($result < 0) {
9844  $error++;
9845  $this->error = $c->error;
9846  $this->errors = $c->errors;
9847  break;
9848  } else {
9849  $ok += $result;
9850  }
9851  }
9852  }
9853 
9854  return $error ? -1 * $error : $ok;
9855  }
9856 
9865  public function cloneCategories($fromId, $toId, $type = '')
9866  {
9867  $this->db->begin();
9868 
9869  if (empty($type)) {
9870  $type = $this->table_element;
9871  }
9872 
9873  require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
9874  $categorystatic = new Categorie($this->db);
9875 
9876  $sql = "INSERT INTO ".$this->db->prefix()."categorie_".(empty($categorystatic->MAP_CAT_TABLE[$type]) ? $type : $categorystatic->MAP_CAT_TABLE[$type])." (fk_categorie, fk_product)";
9877  $sql .= " SELECT fk_categorie, $toId FROM ".$this->db->prefix()."categorie_".(empty($categorystatic->MAP_CAT_TABLE[$type]) ? $type : $categorystatic->MAP_CAT_TABLE[$type]);
9878  $sql .= " WHERE fk_product = ".((int) $fromId);
9879 
9880  if (!$this->db->query($sql)) {
9881  $this->error = $this->db->lasterror();
9882  $this->db->rollback();
9883  return -1;
9884  }
9885 
9886  $this->db->commit();
9887  return 1;
9888  }
9889 
9896  public function deleteEcmFiles($mode = 0)
9897  {
9898  global $conf;
9899 
9900  $this->db->begin();
9901 
9902  // Delete in database with mode 0
9903  if ($mode == 0) {
9904  switch ($this->element) {
9905  case 'propal':
9906  $element = 'propale';
9907  break;
9908  case 'product':
9909  $element = 'produit';
9910  break;
9911  case 'order_supplier':
9912  $element = 'fournisseur/commande';
9913  break;
9914  case 'invoice_supplier':
9915  $element = 'fournisseur/facture/'.get_exdir($this->id, 2, 0, 1, $this, 'invoice_supplier');
9916  break;
9917  case 'shipping':
9918  $element = 'expedition/sending';
9919  break;
9920  default:
9921  $element = $this->element;
9922  }
9923 
9924  // Delete ecm_files extrafields
9925  $sql = "DELETE FROM ".$this->db->prefix()."ecm_files_extrafields WHERE fk_object IN (";
9926  $sql .= " SELECT rowid FROM ".$this->db->prefix()."ecm_files WHERE filename LIKE '".$this->db->escape($this->ref)."%'";
9927  $sql .= " AND filepath = '".$this->db->escape($element)."/".$this->db->escape($this->ref)."' AND entity = ".((int) $conf->entity); // No need of getEntity here
9928  $sql .= ")";
9929 
9930  if (!$this->db->query($sql)) {
9931  $this->error = $this->db->lasterror();
9932  $this->db->rollback();
9933  return false;
9934  }
9935 
9936  // Delete ecm_files
9937  $sql = "DELETE FROM ".$this->db->prefix()."ecm_files";
9938  $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%'";
9939  $sql .= " AND filepath = '".$this->db->escape($element)."/".$this->db->escape($this->ref)."' AND entity = ".((int) $conf->entity); // No need of getEntity here
9940 
9941  if (!$this->db->query($sql)) {
9942  $this->error = $this->db->lasterror();
9943  $this->db->rollback();
9944  return false;
9945  }
9946  }
9947 
9948  // Delete in database with mode 1
9949  if ($mode == 1) {
9950  $sql = 'DELETE FROM '.$this->db->prefix()."ecm_files_extrafields";
9951  $sql .= " WHERE fk_object IN (SELECT rowid FROM ".$this->db->prefix()."ecm_files WHERE src_object_type = '".$this->db->escape($this->table_element.(empty($this->module) ? "" : "@".$this->module))."' AND src_object_id = ".((int) $this->id).")";
9952  $resql = $this->db->query($sql);
9953  if (!$resql) {
9954  $this->error = $this->db->lasterror();
9955  $this->db->rollback();
9956  return false;
9957  }
9958 
9959  $sql = 'DELETE FROM '.$this->db->prefix()."ecm_files";
9960  $sql .= " WHERE src_object_type = '".$this->db->escape($this->table_element.(empty($this->module) ? "" : "@".$this->module))."' AND src_object_id = ".((int) $this->id);
9961  $resql = $this->db->query($sql);
9962  if (!$resql) {
9963  $this->error = $this->db->lasterror();
9964  $this->db->rollback();
9965  return false;
9966  }
9967  }
9968 
9969  $this->db->commit();
9970  return true;
9971  }
9972 }
if(!function_exists('dol_getprefix')) dol_include_once($relpath, $classname= '')
Make an include_once using default root and alternate root if it fails.
setProject($projectid, $notrigger=0)
Link element with a project.
getCategoriesCommon($type_categ)
Sets object to given categories.
deleteCommon(User $user, $notrigger=false, $forcechilddeletion=0)
Delete object in database.
setExtraParameters()
Set extra parameters.
getFullAddress($withcountry=0, $sep="\n", $withregion=0, $extralangcode= '')
Return full address of contact.
getKanbanView($option= '')
Return clicable link of object (with eventually picto)
getIdContact($source, $code, $status=0)
Return id of contacts for a source and a contact code.
if($cancel &&!$id) if($action== 'add'&&!$cancel) if($action== 'delete') if($id) $form
Actions.
Definition: card.php:142
static isExistingObject($element, $id, $ref= '', $ref_ext= '')
Check an object id/ref exists If you don&#39;t need/want to instantiate object and just need to know if o...
isFloat($info)
Function test if type is float.
isInt($info)
Function test if type is integer.
printObjectLines($action, $seller, $buyer, $selected=0, $dateSelector=0, $defaulttpldir= '/core/tpl')
Return HTML table for object lines TODO Move this into an output class file (htmlline.class.php) If lines are into a template, title must also be into a template But for the moment we don&#39;t know if it&#39;s possible as we keep a method available on overloaded objects.
dol_format_address($object, $withcountry=0, $sep="\n", $outputlangs= '', $mode=0, $extralangcode= '')
Return a formated address (part address/zip/town/state) according to country rules.
setUpperOrLowerCase()
Set to upper or ucwords/lower if needed.
fetchLinesCommon($morewhere= '')
Load object in memory from the database.
isText($info)
Function test if type is text.
$conf db
API class for accounts.
Definition: inc.php:41
updateRangOfLine($rowid, $rang)
Update position of line (rang)
setCategoriesCommon($categories, $type_categ= '', $remove_existing=true)
Sets object to given categories.
cloneCategories($fromId, $toId, $type= '')
Copy related categories to another object.
dol_now($mode= 'auto')
Return date for now.
line_order($renum=false, $rowidorder= 'ASC', $fk_parent_line=true)
Save a new position (field rang) for details lines.
deleteObjectLinked($sourceid=null, $sourcetype= '', $targetid=null, $targettype= '', $rowid= '', $f_user=null, $notrigger=0)
Delete all links between an object $this.
delete_linked_contact($source= '', $code= '')
Delete all links between an object $this and all its contacts.
Class to manage Dolibarr users.
Definition: user.class.php:44
dol_strtoupper($string, $encoding="UTF-8")
Convert a string to upper.
add_contact($fk_socpeople, $type_contact, $source= 'external', $notrigger=0)
Add a link between element $this-&gt;element and a contact.
swapContactStatus($rowid)
Update status of a contact linked to object.
updateObjectLinked($sourceid=null, $sourcetype= '', $targetid=null, $targettype= '', $f_user=null, $notrigger=0)
Update object linked of a current object.
isDate($info)
Function test if type is date.
commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams=null)
Common function for all objects extending CommonObject for generating documents.
delete_resource($rowid, $element, $notrigger=0)
Delete a link to resource line.
deleteByParentField($parentId=0, $parentField= '', $filter=array(), $filtermode="AND")
Delete all child object from a parent ID.
quote($value, $fieldsentry)
Add quote to field value if necessary.
initAsSpecimenCommon()
Initialise object with example values Id must be 0 if object instance is a specimen.
createCommon(User $user, $notrigger=false)
Create object into database.
dol_string_nospecial($str, $newstr= '_', $badcharstoreplace= '', $badcharstoremove= '')
Clean a string from all punctuation characters to use it as a ref or login.
getFullName($langs, $option=0, $nameorder=-1, $maxlen=0)
Return full name (civility+&#39; &#39;+name+&#39; &#39;+lastname)
isArray($info)
Function test if type is array.
$conf db name
Only used if Module[ID]Name translation string is not found.
Definition: repair.php:122
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $noescapetags= '', $escapeonlyhtmltags=0)
Returns text escaped for inclusion in HTML alt or title tags, or into values of HTML input fields...
canBeNull($info)
Function test if field can be null.
image_format_supported($file, $acceptsvg=0)
Return if a filename is file name of a supported image format.
Definition: images.lib.php:58
insertExtraFields($trigger= '', $userused=null)
Add/Update all extra fields values for the current object.
setVarsFromFetchObj(&$obj)
Function to load data from a SQL pointer into properties of current object $this. ...
getRangOfLine($rowid)
Get position of line (rang)
fetchComments()
Load comments linked with current task.
Class to manage categories.
update_note($note, $suffix= '')
Update note of element.
line_max($fk_parent_line=0)
Get max value used for position of line (rang)
print *****$script_file(".$version.") pid code
! Closing after partial payment: discount_vat, badcustomer or badsupplier, bankcharge, other ! Closing when no payment: replaced, abandoned
setBankAccount($fk_account, $notrigger=false, $userused=null)
Change the bank account.
getFieldList($alias= '')
Function to concat keys of fields.
price2num($amount, $rounding= '', $option=0)
Function that return a number with universal decimal format (decimal separator is &#39;...
load_previous_next_ref($filter, $fieldid, $nodbprefix=0)
Load properties id_previous and id_next by comparing $fieldid with $this-&gt;ref.
deleteEcmFiles($mode=0)
Delete related files of object in database.
img_picto($titlealt, $picto, $moreatt= '', $pictoisfullpath=false, $srconly=0, $notitle=0, $alt= '', $morecss= '', $marginleftonlyshort=2)
Show picto whatever it&#39;s its name (generic function)
getFormatedSupplierRef($objref)
Return supplier ref for screen output.
getBannerAddress($htmlkey, $object)
Return full address for banner.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename= '', $restricttologhandler= '', $logcontext=null)
Write log message into outputs.
getChildrenOfLine($id, $includealltree=0)
Get children of line.
getFormatedCustomerRef($objref)
Return customer ref for screen output.
setWarehouse($warehouse_id)
Change the warehouse.
$conf db user
Definition: repair.php:123
add_element_resource($resource_id, $resource_type, $busy=0, $mandatory=0)
Add resources to the current object : add entry into llx_element_resources Need $this-&gt;element &amp; $thi...
deleteExtraFields()
Delete all extra fields values for the current object.
updateCommon(User $user, $notrigger=false)
Update object into database.
getState($id, $withcode= '', $dbtouse=0, $withregion=0, $outputlangs= '', $entconv=1)
Return state translated from an id.
setShippingMethod($shipping_method_id, $notrigger=false, $userused=null)
Change the shipping method.
fetch_optionals($rowid=null, $optionsArray=null)
Function to get extra fields of an object into $this-&gt;array_options This method is in most cases call...
if(isModEnabled('facture')&&!empty($user->rights->facture->lire)) if((isModEnabled('fournisseur')&&empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD)&&$user->rights->fournisseur->facture->lire)||(isModEnabled('supplier_invoice')&&$user->rights->supplier_invoice->lire)) if(isModEnabled('don')&&!empty($user->rights->don->lire)) if(isModEnabled('tax')&&!empty($user->rights->tax->charges->lire)) if(isModEnabled('facture')&&isModEnabled('commande')&&$user->rights->commande->lire &&empty($conf->global->WORKFLOW_DISABLE_CREATE_INVOICE_FROM_ORDER)) $resql
Social contributions to pay.
Definition: index.php:742
setDocModel($user, $modelpdf)
Set last model used by doc generator.
dol_ucwords($string, $encoding="UTF-8")
Convert first character of all the words of a string to upper.
Class to manage comment.
deleteLineCommon(User $user, $idline, $notrigger=false)
Delete a line of object in database.
add_object_linked($origin=null, $origin_id=null, $f_user=null, $notrigger=0)
Add objects linked in llx_element_element.
$object ref
Definition: info.php:77
dol_print_error($db= '', $error= '', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
isForcedToNullIfZero($info)
Function test if field is forced to null if zero or empty.
newToken()
Return the value of token currently saved into session with name &#39;newtoken&#39;.
setStatusCommon($user, $status, $notrigger=0, $triggercode= '')
Set to a status.
dol_trunc($string, $size=40, $trunc= 'right', $stringencoding= 'UTF-8', $nodot=0, $display=0)
Truncate a string to a particular length adding &#39;…&#39; if string larger than length. ...
liste_contact($status=-1, $source= 'external', $list=0, $code= '')
Get array of all contacts for an object.
update_ref_ext($ref_ext)
Update external ref of element.
getNbComments()
Return nb comments already posted.
isIndex($info)
Function test if is indexed.
errorsToString()
Method to output saved errors.
update_price($exclspec=0, $roundingadjust= 'none', $nodatabaseupdate=0, $seller=null)
Update total_ht, total_ttc, total_vat, total_localtax1, total_localtax2 for an object (sum of lines)...
img_delete($titlealt= 'default', $other= 'class="pictodelete"', $morecss= '')
Show delete logo.
setStatut($status, $elementId=null, $elementType= '', $trigkey= '', $fieldstatus= 'fk_statut')
Set status of an object.
setSaveQuery()
Function to prepare a part of the query for insert.
isDuration($info)
Function test if type is duration.
getAdvancedPreviewUrl($modulepart, $relativepath, $alldata=0, $param= '')
Return URL we can use for advanced preview links.
showOptionals($extrafields, $mode= 'view', $params=null, $keysuffix= '', $keyprefix= '', $onetrtd=0, $display_type= 'card')
Function to show lines of extrafields with output datas.
delete_contact($rowid, $notrigger=0)
Delete a link to contact line.
if(preg_match('/crypted:/i', $dolibarr_main_db_pass)||!empty($dolibarr_main_db_encrypted_pass)) $conf db type
Definition: repair.php:119
getCountry($searchkey, $withcode= '', $dbtouse=0, $outputlangs= '', $entconv=1, $searchlabel= '')
Return country label, code or id from an id, code or label.
Parent class of all other business classes (invoices, contracts, proposals, orders, ...)
dol_strtolower($string, $encoding="UTF-8")
Convert a string to lower.
fetchCommon($id, $ref=null, $morewhere= '')
Load object in memory from the database.
dolGetFirstLastname($firstname, $lastname, $nameorder=-1)
Return firstname and lastname in correct order.
trimParameters($parameters)
Trim object parameters.
insertExtraLanguages($trigger= '', $userused=null)
Add/Update all extra fields values for the current object.
print *****$script_file(".$version.") pid c cd cd cd description as p label as s rowid