dolibarr  16.0.5
commonobject.class.php
Go to the documentation of this file.
1 <?php
2 /* Copyright (C) 2006-2015 Laurent Destailleur <eldy@users.sourceforge.net>
3  * Copyright (C) 2005-2013 Regis Houssin <regis.houssin@inodbox.com>
4  * Copyright (C) 2010-2020 Juanjo Menent <jmenent@2byte.es>
5  * Copyright (C) 2012-2013 Christophe Battarel <christophe.battarel@altairis.fr>
6  * Copyright (C) 2011-2019 Philippe Grand <philippe.grand@atoo-net.com>
7  * Copyright (C) 2012-2015 Marcos García <marcosgdf@gmail.com>
8  * Copyright (C) 2012-2015 Raphaël Doursenaud <rdoursenaud@gpcsolutions.fr>
9  * Copyright (C) 2012 Cedric Salvador <csalvador@gpcsolutions.fr>
10  * Copyright (C) 2015-2022 Alexandre Spangaro <aspangaro@open-dsi.fr>
11  * Copyright (C) 2016 Bahfir abbes <dolipar@dolipar.org>
12  * Copyright (C) 2017 ATM Consulting <support@atm-consulting.fr>
13  * Copyright (C) 2017-2019 Nicolas ZABOURI <info@inovea-conseil.com>
14  * Copyright (C) 2017 Rui Strecht <rui.strecht@aliartalentos.com>
15  * Copyright (C) 2018-2021 Frédéric France <frederic.france@netlogic.fr>
16  * Copyright (C) 2018 Josep Lluís Amador <joseplluis@lliuretic.cat>
17  * Copyright (C) 2021 Gauthier VERDOL <gauthier.verdol@atm-consulting.fr>
18  * Copyright (C) 2021 Grégory Blémand <gregory.blemand@atm-consulting.fr>
19  *
20  * This program is free software; you can redistribute it and/or modify
21  * it under the terms of the GNU General Public License as published by
22  * the Free Software Foundation; either version 3 of the License, or
23  * (at your option) any later version.
24  *
25  * This program is distributed in the hope that it will be useful,
26  * but WITHOUT ANY WARRANTY; without even the implied warranty of
27  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
28  * GNU General Public License for more details.
29  *
30  * You should have received a copy of the GNU General Public License
31  * along with this program. If not, see <https://www.gnu.org/licenses/>.
32  */
33 
44 abstract class CommonObject
45 {
46  const TRIGGER_PREFIX = ''; // to be overriden in child class implementations, i.e. 'BILL', 'TASK', 'PROPAL', etc.
50  public $db;
51 
55  public $id;
56 
60  public $entity;
61 
66  public $error;
67 
71  public $errorhidden;
72 
76  public $errors = array();
77 
81  public $validateFieldsErrors = array();
82 
86  public $element;
87 
91  public $element_for_permission;
92 
96  public $table_element;
97 
101  public $table_element_line = '';
102 
106  public $import_key;
107 
111  public $array_options = array();
112 
116  public $array_languages = null; // Value is array() when load already tried
117 
121  public $contacts_ids;
122 
126  public $linked_objects;
127 
131  public $linkedObjectsIds;
132 
136  public $linkedObjects;
137 
141  public $linkedObjectsFullLoaded = array();
142 
146  public $oldcopy;
147 
151  protected $table_ref_field = '';
152 
156  public $restrictiononfksoc = 0;
157 
158 
159  // Following vars are used by some objects only. We keep this property here in CommonObject to be able to provide common method using them.
160 
164  public $context = array();
165 
169  public $canvas;
170 
175  public $project;
176 
181  public $fk_project;
182 
187  public $projet;
188 
193  public $fk_projet;
194 
199  public $contact;
200 
205  public $contact_id;
206 
211  public $thirdparty;
212 
217  public $user;
218 
223  public $origin;
224 
229  public $origin_id;
230 
234  public $ref;
235 
239  public $ref_ext;
240 
244  public $ref_previous;
245 
249  public $ref_next;
250 
254  public $newref;
255 
260  public $statut;
261 
266  public $status;
267 
268 
273  public $country;
274 
279  public $country_id;
280 
285  public $country_code;
286 
291  public $state;
292 
297  public $state_id;
298 
303  public $state_code;
304 
309  public $region_id;
310 
315  public $region_code;
316 
321  public $region;
322 
323 
328  public $barcode_type;
329 
334  public $barcode_type_code;
335 
340  public $barcode_type_label;
341 
346  public $barcode_type_coder;
347 
352  public $mode_reglement_id;
353 
358  public $cond_reglement_id;
359 
363  public $demand_reason_id;
364 
369  public $transport_mode_id;
370 
376  public $cond_reglement;
377 
383  public $fk_delivery_address;
384 
389  public $shipping_method_id;
390 
395  public $model_pdf;
396 
402  public $modelpdf;
403 
408  public $last_main_doc;
409 
415  public $fk_bank;
416 
421  public $fk_account;
422 
426  public $openid;
427 
432  public $note_public;
433 
438  public $note_private;
439 
444  public $note;
445 
450  public $total_ht;
451 
456  public $total_tva;
457 
462  public $total_localtax1;
463 
468  public $total_localtax2;
469 
474  public $total_ttc;
475 
479  public $lines;
480 
485  public $comments = array();
486 
490  public $name;
491 
495  public $lastname;
496 
500  public $firstname;
501 
505  public $civility_id;
506 
507  // Dates
511  public $date_creation;
512 
516  public $date_validation; // Date validation
517 
521  public $date_modification; // Date last change (tms field)
522 
526  public $date_cloture; // Date closing (tms field)
527 
532  public $user_author;
537  public $user_creation;
541  public $user_creation_id;
542 
547  public $user_valid;
552  public $user_validation;
556  public $user_validation_id;
560  public $user_closing_id;
561 
566  public $user_modification;
570  public $user_modification_id;
571 
572 
573  public $next_prev_filter;
574 
578  public $specimen = 0;
579 
583  public $sendtoid;
584 
588  public $alreadypaid;
589 
590 
594  protected $childtables = array();
595 
601  protected $childtablesoncascade = array();
602 
603 
604  // No constructor as it is an abstract class
605 
606 
617  public static function isExistingObject($element, $id, $ref = '', $ref_ext = '')
618  {
619  global $db, $conf;
620 
621  $sql = "SELECT rowid, ref, ref_ext";
622  $sql .= " FROM ".$db->prefix().$element;
623  $sql .= " WHERE entity IN (".getEntity($element).")";
624 
625  if ($id > 0) {
626  $sql .= " AND rowid = ".((int) $id);
627  } elseif ($ref) {
628  $sql .= " AND ref = '".$db->escape($ref)."'";
629  } elseif ($ref_ext) {
630  $sql .= " AND ref_ext = '".$db->escape($ref_ext)."'";
631  } else {
632  $error = 'ErrorWrongParameters';
633  dol_print_error(get_class()."::isExistingObject ".$error, LOG_ERR);
634  return -1;
635  }
636  if ($ref || $ref_ext) { // Because the same ref can exists in 2 different entities, we force the current one in priority
637  $sql .= " AND entity = ".((int) $conf->entity);
638  }
639 
640  dol_syslog(get_class()."::isExistingObject", LOG_DEBUG);
641  $resql = $db->query($sql);
642  if ($resql) {
643  $num = $db->num_rows($resql);
644  if ($num > 0) {
645  return 1;
646  } else {
647  return 0;
648  }
649  }
650  return -1;
651  }
652 
653 
659  public function errorsToString()
660  {
661  return $this->error.(is_array($this->errors) ? (($this->error != '' ? ', ' : '').join(', ', $this->errors)) : '');
662  }
663 
664 
671  public function getFormatedCustomerRef($objref)
672  {
673  global $hookmanager;
674 
675  $parameters = array('objref'=>$objref);
676  $action = '';
677  $reshook = $hookmanager->executeHooks('getFormatedCustomerRef', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
678  if ($reshook > 0) {
679  return $hookmanager->resArray['objref'];
680  }
681  return $objref.(isset($hookmanager->resArray['objref']) ? $hookmanager->resArray['objref'] : '');
682  }
683 
690  public function getFormatedSupplierRef($objref)
691  {
692  global $hookmanager;
693 
694  $parameters = array('objref'=>$objref);
695  $action = '';
696  $reshook = $hookmanager->executeHooks('getFormatedSupplierRef', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
697  if ($reshook > 0) {
698  return $hookmanager->resArray['objref'];
699  }
700  return $objref.(isset($hookmanager->resArray['objref']) ? $hookmanager->resArray['objref'] : '');
701  }
702 
712  public function getFullName($langs, $option = 0, $nameorder = -1, $maxlen = 0)
713  {
714  //print "lastname=".$this->lastname." name=".$this->name." nom=".$this->nom."<br>\n";
715  $lastname = $this->lastname;
716  $firstname = $this->firstname;
717  if (empty($lastname)) {
718  $lastname = (isset($this->lastname) ? $this->lastname : (isset($this->name) ? $this->name : (isset($this->nom) ? $this->nom : (isset($this->societe) ? $this->societe : (isset($this->company) ? $this->company : '')))));
719  }
720 
721  $ret = '';
722  if (!empty($option) && !empty($this->civility_code)) {
723  if ($langs->transnoentitiesnoconv("Civility".$this->civility_code) != "Civility".$this->civility_code) {
724  $ret .= $langs->transnoentitiesnoconv("Civility".$this->civility_code).' ';
725  } else {
726  $ret .= $this->civility_code.' ';
727  }
728  }
729 
730  $ret .= dolGetFirstLastname($firstname, $lastname, $nameorder);
731 
732  return dol_trunc($ret, $maxlen);
733  }
734 
740  public function setUpperOrLowerCase()
741  {
742  global $conf;
743  if (!empty($conf->global->MAIN_FIRST_TO_UPPER)) {
744  $this->lastname = dol_ucwords(dol_strtolower($this->lastname));
745  $this->firstname = dol_ucwords(dol_strtolower($this->firstname));
746  $this->name = dol_ucwords(dol_strtolower($this->name));
747  $this->name_alias = dol_ucwords(dol_strtolower($this->name_alias));
748  }
749  if (!empty($conf->global->MAIN_ALL_TO_UPPER)) {
750  $this->lastname = dol_strtoupper($this->lastname);
751  $this->name = dol_strtoupper($this->name);
752  $this->name_alias = dol_strtoupper($this->name_alias);
753  }
754  if (!empty($conf->global->MAIN_ALL_TOWN_TO_UPPER)) {
755  $this->address = dol_strtoupper($this->address);
756  $this->town = dol_strtoupper($this->town);
757  }
758  }
759 
766  public function getKanbanView($option = '')
767  {
768  $return = '<div class="box-flex-item box-flex-grow-zero">';
769  $return .= '<div class="info-box info-box-sm">';
770  $return .= '<span class="info-box-icon bg-infobox-action">';
771  $return .= img_picto('', $this->picto);
772  //$return .= '<i class="fa fa-dol-action"></i>'; // Can be image
773  $return .= '</span>';
774  $return .= '<div class="info-box-content">';
775  $return .= '<span class="info-box-ref">'.(method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref).'</span>';
776  if (property_exists($this, 'label')) {
777  $return .= '<br><span class="info-box-label opacitymedium">'.$this->label.'</span>';
778  }
779  if (method_exists($this, 'getLibStatut')) {
780  $return .= '<br><div class="info-box-status margintoponly">'.$this->getLibStatut(5).'</div>';
781  }
782  $return .= '</div>';
783  $return .= '</div>';
784  $return .= '</div>';
785 
786  return $return;
787  }
788 
798  public function getFullAddress($withcountry = 0, $sep = "\n", $withregion = 0, $extralangcode = '')
799  {
800  if ($withcountry && $this->country_id && (empty($this->country_code) || empty($this->country))) {
801  require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
802  $tmparray = getCountry($this->country_id, 'all');
803  $this->country_code = $tmparray['code'];
804  $this->country = $tmparray['label'];
805  }
806 
807  if ($withregion && $this->state_id && (empty($this->state_code) || empty($this->state) || empty($this->region) || empty($this->region_code))) {
808  require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
809  $tmparray = getState($this->state_id, 'all', 0, 1);
810  $this->state_code = $tmparray['code'];
811  $this->state = $tmparray['label'];
812  $this->region_code = $tmparray['region_code'];
813  $this->region = $tmparray['region'];
814  }
815 
816  return dol_format_address($this, $withcountry, $sep, '', 0, $extralangcode);
817  }
818 
819 
827  public function getBannerAddress($htmlkey, $object)
828  {
829  global $conf, $langs, $form, $extralanguages;
830 
831  $countriesusingstate = array('AU', 'US', 'IN', 'GB', 'ES', 'UK', 'TR'); // See also option MAIN_FORCE_STATE_INTO_ADDRESS
832 
833  $contactid = 0;
834  $thirdpartyid = 0;
835  $elementforaltlanguage = $this->element;
836  if ($this->element == 'societe') {
837  $thirdpartyid = $this->id;
838  }
839  if ($this->element == 'contact') {
840  $contactid = $this->id;
841  $thirdpartyid = empty($object->fk_soc) ? 0 : $object->fk_soc;
842  }
843  if ($this->element == 'user') {
844  $contactid = $this->contact_id;
845  $thirdpartyid = empty($object->fk_soc) ? 0 : $object->fk_soc;
846  }
847 
848  $out = '';
849 
850  $outdone = 0;
851  $coords = $this->getFullAddress(1, ', ', (!empty($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT) ? $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT : 0));
852  if ($coords) {
853  if (!empty($conf->use_javascript_ajax)) {
854  // Add picto with tooltip on map
855  $namecoords = '';
856  if ($this->element == 'contact' && !empty($conf->global->MAIN_SHOW_COMPANY_NAME_IN_BANNER_ADDRESS)) {
857  $namecoords .= $object->name.'<br>';
858  }
859  $namecoords .= $this->getFullName($langs, 1).'<br>'.$coords;
860  // hideonsmatphone because copyToClipboard call jquery dialog that does not work with jmobile
861  $out .= '<a href="#" class="hideonsmartphone" onclick="return copyToClipboard(\''.dol_escape_js($namecoords).'\',\''.dol_escape_js($langs->trans("HelpCopyToClipboard")).'\');">';
862  $out .= img_picto($langs->trans("Address"), 'map-marker-alt');
863  $out .= '</a> ';
864  }
865  $out .= dol_print_address($coords, 'address_'.$htmlkey.'_'.$this->id, $this->element, $this->id, 1, ', ');
866  $outdone++;
867  $outdone++;
868 
869  // List of extra languages
870  $arrayoflangcode = array();
871  if (!empty($conf->global->PDF_USE_ALSO_LANGUAGE_CODE)) {
872  $arrayoflangcode[] = $conf->global->PDF_USE_ALSO_LANGUAGE_CODE;
873  }
874 
875  if (is_array($arrayoflangcode) && count($arrayoflangcode)) {
876  if (!is_object($extralanguages)) {
877  include_once DOL_DOCUMENT_ROOT.'/core/class/extralanguages.class.php';
878  $extralanguages = new ExtraLanguages($this->db);
879  }
880  $extralanguages->fetch_name_extralanguages($elementforaltlanguage);
881 
882  if (!empty($extralanguages->attributes[$elementforaltlanguage]['address']) || !empty($extralanguages->attributes[$elementforaltlanguage]['town'])) {
883  $out .= "<!-- alternatelanguage for '".$elementforaltlanguage."' set to fields '".join(',', $extralanguages->attributes[$elementforaltlanguage])."' -->\n";
884  $this->fetchValuesForExtraLanguages();
885  if (!is_object($form)) {
886  $form = new Form($this->db);
887  }
888  $htmltext = '';
889  // If there is extra languages
890  foreach ($arrayoflangcode as $extralangcode) {
891  $s = picto_from_langcode($extralangcode, 'class="pictoforlang paddingright"');
892  $coords = $this->getFullAddress(1, ', ', $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT, $extralangcode);
893  $htmltext .= $s.dol_print_address($coords, 'address_'.$htmlkey.'_'.$this->id, $this->element, $this->id, 1, ', ');
894  }
895  $out .= $form->textwithpicto('', $htmltext, -1, 'language', 'opacitymedium paddingleft');
896  }
897  }
898  }
899 
900  if (!in_array($this->country_code, $countriesusingstate) && empty($conf->global->MAIN_FORCE_STATE_INTO_ADDRESS) // If MAIN_FORCE_STATE_INTO_ADDRESS is on, state is already returned previously with getFullAddress
901  && empty($conf->global->SOCIETE_DISABLE_STATE) && $this->state) {
902  if (!empty($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT) && $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT == 1 && $this->region) {
903  $out .= ($outdone ? ' - ' : '').$this->region.' - '.$this->state;
904  } else {
905  $out .= ($outdone ? ' - ' : '').$this->state;
906  }
907  $outdone++;
908  }
909 
910  if (!empty($this->phone) || !empty($this->phone_pro) || !empty($this->phone_mobile) || !empty($this->phone_perso) || !empty($this->fax) || !empty($this->office_phone) || !empty($this->user_mobile) || !empty($this->office_fax)) {
911  $out .= ($outdone ? '<br>' : '');
912  }
913  if (!empty($this->phone) && empty($this->phone_pro)) { // For objects that store pro phone into ->phone
914  $out .= dol_print_phone($this->phone, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'phone', $langs->trans("PhonePro"));
915  $outdone++;
916  }
917  if (!empty($this->phone_pro)) {
918  $out .= dol_print_phone($this->phone_pro, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'phone', $langs->trans("PhonePro"));
919  $outdone++;
920  }
921  if (!empty($this->phone_mobile)) {
922  $out .= dol_print_phone($this->phone_mobile, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'mobile', $langs->trans("PhoneMobile"));
923  $outdone++;
924  }
925  if (!empty($this->phone_perso)) {
926  $out .= dol_print_phone($this->phone_perso, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'phone', $langs->trans("PhonePerso"));
927  $outdone++;
928  }
929  if (!empty($this->office_phone)) {
930  $out .= dol_print_phone($this->office_phone, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'phone', $langs->trans("PhonePro"));
931  $outdone++;
932  }
933  if (!empty($this->user_mobile)) {
934  $out .= dol_print_phone($this->user_mobile, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'mobile', $langs->trans("PhoneMobile"));
935  $outdone++;
936  }
937  if (!empty($this->fax)) {
938  $out .= dol_print_phone($this->fax, $this->country_code, $contactid, $thirdpartyid, 'AC_FAX', '&nbsp;', 'fax', $langs->trans("Fax"));
939  $outdone++;
940  }
941  if (!empty($this->office_fax)) {
942  $out .= dol_print_phone($this->office_fax, $this->country_code, $contactid, $thirdpartyid, 'AC_FAX', '&nbsp;', 'fax', $langs->trans("Fax"));
943  $outdone++;
944  }
945 
946  if ($out) {
947  $out .= '<div style="clear: both;"></div>';
948  }
949  $outdone = 0;
950  if (!empty($this->email)) {
951  $out .= dol_print_email($this->email, $this->id, $object->id, 'AC_EMAIL', 0, 0, 1);
952  $outdone++;
953  }
954  if (!empty($this->url)) {
955  //$out.=dol_print_url($this->url,'_goout',0,1);//steve changed to blank
956  $out .= dol_print_url($this->url, '_blank', 0, 1);
957  $outdone++;
958  }
959 
960  if (!empty($conf->socialnetworks->enabled)) {
961  $outsocialnetwork = '';
962 
963  if (!empty($this->socialnetworks) && is_array($this->socialnetworks) && count($this->socialnetworks) > 0) {
964  $socialnetworksdict = getArrayOfSocialNetworks();
965  foreach ($this->socialnetworks as $key => $value) {
966  if ($value) {
967  $outsocialnetwork .= dol_print_socialnetworks($value, $this->id, $object->id, $key, $socialnetworksdict);
968  }
969  $outdone++;
970  }
971  } else { // Old code to remove
972  if (!empty($this->skype)) {
973  $outsocialnetwork .= dol_print_socialnetworks($this->skype, $this->id, $object->id, 'skype');
974  }
975  $outdone++;
976  if (!empty($this->jabberid)) {
977  $outsocialnetwork .= dol_print_socialnetworks($this->jabberid, $this->id, $object->id, 'jabber');
978  }
979  $outdone++;
980  if (!empty($this->twitter)) {
981  $outsocialnetwork .= dol_print_socialnetworks($this->twitter, $this->id, $object->id, 'twitter');
982  }
983  $outdone++;
984  if (!empty($this->facebook)) {
985  $outsocialnetwork .= dol_print_socialnetworks($this->facebook, $this->id, $object->id, 'facebook');
986  }
987  $outdone++;
988  if (!empty($this->linkedin)) {
989  $outsocialnetwork .= dol_print_socialnetworks($this->linkedin, $this->id, $object->id, 'linkedin');
990  }
991  $outdone++;
992  }
993 
994  if ($outsocialnetwork) {
995  $out .= '<div style="clear: both;">'.$outsocialnetwork.'</div>';
996  }
997  }
998 
999  if ($out) {
1000  return '<!-- BEGIN part to show address block -->'."\n".$out.'<!-- END Part to show address block -->'."\n";
1001  } else {
1002  return '';
1003  }
1004  }
1005 
1014  public function getLastMainDocLink($modulepart, $initsharekey = 0, $relativelink = 0)
1015  {
1016  global $user, $dolibarr_main_url_root;
1017 
1018  if (empty($this->last_main_doc)) {
1019  return ''; // No way to known which document name to use
1020  }
1021 
1022  include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
1023  $ecmfile = new EcmFiles($this->db);
1024  $result = $ecmfile->fetch(0, '', $this->last_main_doc);
1025  if ($result < 0) {
1026  $this->error = $ecmfile->error;
1027  $this->errors = $ecmfile->errors;
1028  return -1;
1029  }
1030 
1031  if (empty($ecmfile->id)) {
1032  // Add entry into index
1033  if ($initsharekey) {
1034  require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
1035 
1036  // TODO We can't, we dont' have full path of file, only last_main_doc and ->element, so we must first rebuild full path $destfull
1037  /*
1038  $ecmfile->filepath = $rel_dir;
1039  $ecmfile->filename = $filename;
1040  $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
1041  $ecmfile->fullpath_orig = '';
1042  $ecmfile->gen_or_uploaded = 'generated';
1043  $ecmfile->description = ''; // indexed content
1044  $ecmfile->keywords = ''; // keyword content
1045  $ecmfile->share = getRandomPassword(true);
1046  $result = $ecmfile->create($user);
1047  if ($result < 0)
1048  {
1049  $this->error = $ecmfile->error;
1050  $this->errors = $ecmfile->errors;
1051  }
1052  */
1053  } else {
1054  return '';
1055  }
1056  } elseif (empty($ecmfile->share)) {
1057  // Add entry into index
1058  if ($initsharekey) {
1059  require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
1060  $ecmfile->share = getRandomPassword(true);
1061  $ecmfile->update($user);
1062  } else {
1063  return '';
1064  }
1065  }
1066  // Define $urlwithroot
1067  $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
1068  // This is to use external domain name found into config file
1069  //if (DOL_URL_ROOT && ! preg_match('/\/$/', $urlwithouturlroot) && ! preg_match('/^\//', DOL_URL_ROOT)) $urlwithroot=$urlwithouturlroot.'/'.DOL_URL_ROOT;
1070  //else
1071  $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT;
1072  //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
1073 
1074  $forcedownload = 0;
1075 
1076  $paramlink = '';
1077  //if (! empty($modulepart)) $paramlink.=($paramlink?'&':'').'modulepart='.$modulepart; // For sharing with hash (so public files), modulepart is not required.
1078  //if (! empty($ecmfile->entity)) $paramlink.='&entity='.$ecmfile->entity; // For sharing with hash (so public files), entity is not required.
1079  //$paramlink.=($paramlink?'&':'').'file='.urlencode($filepath); // No need of name of file for public link, we will use the hash
1080  if (!empty($ecmfile->share)) {
1081  $paramlink .= ($paramlink ? '&' : '').'hashp='.$ecmfile->share; // Hash for public share
1082  }
1083  if ($forcedownload) {
1084  $paramlink .= ($paramlink ? '&' : '').'attachment=1';
1085  }
1086 
1087  if ($relativelink) {
1088  $linktoreturn = 'document.php'.($paramlink ? '?'.$paramlink : '');
1089  } else {
1090  $linktoreturn = $urlwithroot.'/document.php'.($paramlink ? '?'.$paramlink : '');
1091  }
1092 
1093  // Here $ecmfile->share is defined
1094  return $linktoreturn;
1095  }
1096 
1097 
1098  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1108  public function add_contact($fk_socpeople, $type_contact, $source = 'external', $notrigger = 0)
1109  {
1110  // phpcs:enable
1111  global $user, $langs;
1112 
1113 
1114  dol_syslog(get_class($this)."::add_contact $fk_socpeople, $type_contact, $source, $notrigger");
1115 
1116  // Check parameters
1117  if ($fk_socpeople <= 0) {
1118  $langs->load("errors");
1119  $this->error = $langs->trans("ErrorWrongValueForParameterX", "1");
1120  dol_syslog(get_class($this)."::add_contact ".$this->error, LOG_ERR);
1121  return -1;
1122  }
1123  if (!$type_contact) {
1124  $langs->load("errors");
1125  $this->error = $langs->trans("ErrorWrongValueForParameterX", "2");
1126  dol_syslog(get_class($this)."::add_contact ".$this->error, LOG_ERR);
1127  return -2;
1128  }
1129 
1130  $id_type_contact = 0;
1131  if (is_numeric($type_contact)) {
1132  $id_type_contact = $type_contact;
1133  } else {
1134  // We look for id type_contact
1135  $sql = "SELECT tc.rowid";
1136  $sql .= " FROM ".$this->db->prefix()."c_type_contact as tc";
1137  $sql .= " WHERE tc.element='".$this->db->escape($this->element)."'";
1138  $sql .= " AND tc.source='".$this->db->escape($source)."'";
1139  $sql .= " AND tc.code='".$this->db->escape($type_contact)."' AND tc.active=1";
1140  //print $sql;
1141  $resql = $this->db->query($sql);
1142  if ($resql) {
1143  $obj = $this->db->fetch_object($resql);
1144  if ($obj) {
1145  $id_type_contact = $obj->rowid;
1146  }
1147  }
1148  }
1149 
1150  if ($id_type_contact == 0) {
1151  $this->error = 'CODE_NOT_VALID_FOR_THIS_ELEMENT';
1152  dol_syslog("CODE_NOT_VALID_FOR_THIS_ELEMENT: Code type of contact '".$type_contact."' does not exists or is not active for element ".$this->element.", we can ignore it");
1153  return -3;
1154  }
1155 
1156  $datecreate = dol_now();
1157 
1158  // Socpeople must have already been added by some trigger, then we have to check it to avoid DB_ERROR_RECORD_ALREADY_EXISTS error
1159  $TListeContacts = $this->liste_contact(-1, $source);
1160  $already_added = false;
1161  if (is_array($TListeContacts) && !empty($TListeContacts)) {
1162  foreach ($TListeContacts as $array_contact) {
1163  if ($array_contact['status'] == 4 && $array_contact['id'] == $fk_socpeople && $array_contact['fk_c_type_contact'] == $id_type_contact) {
1164  $already_added = true;
1165  break;
1166  }
1167  }
1168  }
1169 
1170  if (!$already_added) {
1171  $this->db->begin();
1172 
1173  // Insert into database
1174  $sql = "INSERT INTO ".$this->db->prefix()."element_contact";
1175  $sql .= " (element_id, fk_socpeople, datecreate, statut, fk_c_type_contact) ";
1176  $sql .= " VALUES (".$this->id.", ".((int) $fk_socpeople)." , ";
1177  $sql .= "'".$this->db->idate($datecreate)."'";
1178  $sql .= ", 4, ".((int) $id_type_contact);
1179  $sql .= ")";
1180 
1181  $resql = $this->db->query($sql);
1182  if ($resql) {
1183  if (!$notrigger) {
1184  $result = $this->call_trigger(strtoupper($this->element).'_ADD_CONTACT', $user);
1185  if ($result < 0) {
1186  $this->db->rollback();
1187  return -1;
1188  }
1189  }
1190 
1191  $this->db->commit();
1192  return 1;
1193  } else {
1194  if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
1195  $this->error = $this->db->errno();
1196  $this->db->rollback();
1197  return -2;
1198  } else {
1199  $this->error = $this->db->lasterror();
1200  $this->db->rollback();
1201  return -1;
1202  }
1203  }
1204  } else {
1205  return 0;
1206  }
1207  }
1208 
1209  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1217  public function copy_linked_contact($objFrom, $source = 'internal')
1218  {
1219  // phpcs:enable
1220  $contacts = $objFrom->liste_contact(-1, $source);
1221  foreach ($contacts as $contact) {
1222  if ($this->add_contact($contact['id'], $contact['fk_c_type_contact'], $contact['source']) < 0) {
1223  return -1;
1224  }
1225  }
1226  return 1;
1227  }
1228 
1229  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1239  public function update_contact($rowid, $statut, $type_contact_id = 0, $fk_socpeople = 0)
1240  {
1241  // phpcs:enable
1242  // Insert into database
1243  $sql = "UPDATE ".$this->db->prefix()."element_contact set";
1244  $sql .= " statut = ".$statut;
1245  if ($type_contact_id) {
1246  $sql .= ", fk_c_type_contact = ".((int) $type_contact_id);
1247  }
1248  if ($fk_socpeople) {
1249  $sql .= ", fk_socpeople = ".((int) $fk_socpeople);
1250  }
1251  $sql .= " where rowid = ".((int) $rowid);
1252  $resql = $this->db->query($sql);
1253  if ($resql) {
1254  return 0;
1255  } else {
1256  $this->error = $this->db->lasterror();
1257  return -1;
1258  }
1259  }
1260 
1261  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1269  public function delete_contact($rowid, $notrigger = 0)
1270  {
1271  // phpcs:enable
1272  global $user;
1273 
1274  $error = 0;
1275 
1276  $this->db->begin();
1277 
1278  if (!$error && empty($notrigger)) {
1279  // Call trigger
1280  $this->context['contact_id'] = ((int) $rowid);
1281  $result = $this->call_trigger(strtoupper($this->element).'_DELETE_CONTACT', $user);
1282  if ($result < 0) {
1283  $error++;
1284  }
1285  // End call triggers
1286  }
1287 
1288  if (!$error) {
1289  dol_syslog(get_class($this)."::delete_contact", LOG_DEBUG);
1290 
1291  $sql = "DELETE FROM ".MAIN_DB_PREFIX."element_contact";
1292  $sql .= " WHERE rowid = ".((int) $rowid);
1293 
1294  $result = $this->db->query($sql);
1295  if (!$result) {
1296  $error++;
1297  $this->errors[] = $this->db->lasterror();
1298  }
1299  }
1300 
1301  if (!$error) {
1302  $this->db->commit();
1303  return 1;
1304  } else {
1305  $this->error = $this->db->lasterror();
1306  $this->db->rollback();
1307  return -1;
1308  }
1309  }
1310 
1311  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1319  public function delete_linked_contact($source = '', $code = '')
1320  {
1321  // phpcs:enable
1322  $listId = '';
1323  $temp = array();
1324  $typeContact = $this->liste_type_contact($source, '', 0, 0, $code);
1325 
1326  if (!empty($typeContact)) {
1327  foreach ($typeContact as $key => $value) {
1328  array_push($temp, $key);
1329  }
1330  $listId = implode(",", $temp);
1331  }
1332 
1333  // If $listId is empty, we have not criteria on fk_c_type_contact so we will delete record on element_id for
1334  // any type or record instead of only the ones of the current object. So we do nothing in such a case.
1335  if (empty($listId)) {
1336  return 0;
1337  }
1338 
1339  $sql = "DELETE FROM ".$this->db->prefix()."element_contact";
1340  $sql .= " WHERE element_id = ".((int) $this->id);
1341  $sql .= " AND fk_c_type_contact IN (".$this->db->sanitize($listId).")";
1342 
1343  dol_syslog(get_class($this)."::delete_linked_contact", LOG_DEBUG);
1344  if ($this->db->query($sql)) {
1345  return 1;
1346  } else {
1347  $this->error = $this->db->lasterror();
1348  return -1;
1349  }
1350  }
1351 
1352  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1362  public function liste_contact($status = -1, $source = 'external', $list = 0, $code = '')
1363  {
1364  // phpcs:enable
1365  global $langs;
1366 
1367  $tab = array();
1368 
1369  $sql = "SELECT ec.rowid, ec.statut as statuslink, ec.fk_socpeople as id, ec.fk_c_type_contact"; // This field contains id of llx_socpeople or id of llx_user
1370  if ($source == 'internal') {
1371  $sql .= ", '-1' as socid, t.statut as statuscontact, t.login, t.photo";
1372  }
1373  if ($source == 'external' || $source == 'thirdparty') {
1374  $sql .= ", t.fk_soc as socid, t.statut as statuscontact";
1375  }
1376  $sql .= ", t.civility as civility, t.lastname as lastname, t.firstname, t.email";
1377  $sql .= ", tc.source, tc.element, tc.code, tc.libelle";
1378  $sql .= " FROM ".$this->db->prefix()."c_type_contact tc";
1379  $sql .= ", ".$this->db->prefix()."element_contact ec";
1380  if ($source == 'internal') {
1381  $sql .= " LEFT JOIN ".$this->db->prefix()."user t on ec.fk_socpeople = t.rowid";
1382  }
1383  if ($source == 'external' || $source == 'thirdparty') {
1384  $sql .= " LEFT JOIN ".$this->db->prefix()."socpeople t on ec.fk_socpeople = t.rowid";
1385  }
1386  $sql .= " WHERE ec.element_id = ".((int) $this->id);
1387  $sql .= " AND ec.fk_c_type_contact = tc.rowid";
1388  $sql .= " AND tc.element = '".$this->db->escape($this->element)."'";
1389  if ($code) {
1390  $sql .= " AND tc.code = '".$this->db->escape($code)."'";
1391  }
1392  if ($source == 'internal') {
1393  $sql .= " AND tc.source = 'internal'";
1394  }
1395  if ($source == 'external' || $source == 'thirdparty') {
1396  $sql .= " AND tc.source = 'external'";
1397  }
1398  $sql .= " AND tc.active=1";
1399  if ($status >= 0) {
1400  $sql .= " AND ec.statut = ".((int) $status);
1401  }
1402  $sql .= " ORDER BY t.lastname ASC";
1403 
1404  dol_syslog(get_class($this)."::liste_contact", LOG_DEBUG);
1405  $resql = $this->db->query($sql);
1406  if ($resql) {
1407  $num = $this->db->num_rows($resql);
1408  $i = 0;
1409  while ($i < $num) {
1410  $obj = $this->db->fetch_object($resql);
1411 
1412  if (!$list) {
1413  $transkey = "TypeContact_".$obj->element."_".$obj->source."_".$obj->code;
1414  $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle);
1415  $tab[$i] = array(
1416  'source' => $obj->source,
1417  'socid' => $obj->socid,
1418  'id' => $obj->id,
1419  'nom' => $obj->lastname, // For backward compatibility
1420  'civility' => $obj->civility,
1421  'lastname' => $obj->lastname,
1422  'firstname' => $obj->firstname,
1423  'email'=>$obj->email,
1424  'login'=> (empty($obj->login) ? '' : $obj->login),
1425  'photo' => (empty($obj->photo) ? '' : $obj->photo),
1426  'statuscontact' => $obj->statuscontact,
1427  'rowid' => $obj->rowid,
1428  'code' => $obj->code,
1429  'libelle' => $libelle_type,
1430  'status' => $obj->statuslink,
1431  'fk_c_type_contact' => $obj->fk_c_type_contact
1432  );
1433  } else {
1434  $tab[$i] = $obj->id;
1435  }
1436 
1437  $i++;
1438  }
1439 
1440  return $tab;
1441  } else {
1442  $this->error = $this->db->lasterror();
1443  dol_print_error($this->db);
1444  return -1;
1445  }
1446  }
1447 
1448 
1455  public function swapContactStatus($rowid)
1456  {
1457  $sql = "SELECT ec.datecreate, ec.statut, ec.fk_socpeople, ec.fk_c_type_contact,";
1458  $sql .= " tc.code, tc.libelle";
1459  $sql .= " FROM (".$this->db->prefix()."element_contact as ec, ".$this->db->prefix()."c_type_contact as tc)";
1460  $sql .= " WHERE ec.rowid =".((int) $rowid);
1461  $sql .= " AND ec.fk_c_type_contact=tc.rowid";
1462  $sql .= " AND tc.element = '".$this->db->escape($this->element)."'";
1463 
1464  dol_syslog(get_class($this)."::swapContactStatus", LOG_DEBUG);
1465  $resql = $this->db->query($sql);
1466  if ($resql) {
1467  $obj = $this->db->fetch_object($resql);
1468  $newstatut = ($obj->statut == 4) ? 5 : 4;
1469  $result = $this->update_contact($rowid, $newstatut);
1470  $this->db->free($resql);
1471  return $result;
1472  } else {
1473  $this->error = $this->db->error();
1474  dol_print_error($this->db);
1475  return -1;
1476  }
1477  }
1478 
1479  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1490  public function liste_type_contact($source = 'internal', $order = 'position', $option = 0, $activeonly = 0, $code = '')
1491  {
1492  // phpcs:enable
1493  global $langs;
1494 
1495  if (empty($order)) {
1496  $order = 'position';
1497  }
1498  if ($order == 'position') {
1499  $order .= ',code';
1500  }
1501 
1502  $tab = array();
1503  $sql = "SELECT DISTINCT tc.rowid, tc.code, tc.libelle, tc.position";
1504  $sql .= " FROM ".$this->db->prefix()."c_type_contact as tc";
1505  $sql .= " WHERE tc.element='".$this->db->escape($this->element)."'";
1506  if ($activeonly == 1) {
1507  $sql .= " AND tc.active=1"; // only the active types
1508  }
1509  if (!empty($source) && $source != 'all') {
1510  $sql .= " AND tc.source='".$this->db->escape($source)."'";
1511  }
1512  if (!empty($code)) {
1513  $sql .= " AND tc.code='".$this->db->escape($code)."'";
1514  }
1515  $sql .= $this->db->order($order, 'ASC');
1516 
1517  //print "sql=".$sql;
1518  $resql = $this->db->query($sql);
1519  if ($resql) {
1520  $num = $this->db->num_rows($resql);
1521  $i = 0;
1522  while ($i < $num) {
1523  $obj = $this->db->fetch_object($resql);
1524 
1525  $transkey = "TypeContact_".$this->element."_".$source."_".$obj->code;
1526  $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle);
1527  if (empty($option)) {
1528  $tab[$obj->rowid] = $libelle_type;
1529  } else {
1530  $tab[$obj->code] = $libelle_type;
1531  }
1532  $i++;
1533  }
1534  return $tab;
1535  } else {
1536  $this->error = $this->db->lasterror();
1537  //dol_print_error($this->db);
1538  return null;
1539  }
1540  }
1541 
1542  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1554  public function listeTypeContacts($source = 'internal', $option = 0, $activeonly = 0, $code = '', $element = '', $excludeelement = '')
1555  {
1556  // phpcs:enable
1557  global $langs, $conf;
1558 
1559  $langs->loadLangs(array('bills', 'contracts', 'interventions', 'orders', 'projects', 'propal', 'ticket', 'agenda'));
1560 
1561  $tab = array();
1562 
1563  $sql = "SELECT DISTINCT tc.rowid, tc.code, tc.libelle, tc.position, tc.element";
1564  $sql .= " FROM ".$this->db->prefix()."c_type_contact as tc";
1565 
1566  $sqlWhere = array();
1567  if (!empty($element)) {
1568  $sqlWhere[] = " tc.element='".$this->db->escape($element)."'";
1569  }
1570  if (!empty($excludeelement)) {
1571  $sqlWhere[] = " tc.element <> '".$this->db->escape($excludeelement)."'";
1572  }
1573 
1574  if ($activeonly == 1) {
1575  $sqlWhere[] = " tc.active=1"; // only the active types
1576  }
1577 
1578  if (!empty($source) && $source != 'all') {
1579  $sqlWhere[] = " tc.source='".$this->db->escape($source)."'";
1580  }
1581 
1582  if (!empty($code)) {
1583  $sqlWhere[] = " tc.code='".$this->db->escape($code)."'";
1584  }
1585 
1586  if (count($sqlWhere) > 0) {
1587  $sql .= " WHERE ".implode(' AND ', $sqlWhere);
1588  }
1589 
1590  $sql .= $this->db->order('tc.element, tc.position', 'ASC');
1591 
1592  dol_syslog(__METHOD__, LOG_DEBUG);
1593  $resql = $this->db->query($sql);
1594  if ($resql) {
1595  $num = $this->db->num_rows($resql);
1596  if ($num > 0) {
1597  $langs->loadLangs(array("propal", "orders", "bills", "suppliers", "contracts", "supplier_proposal"));
1598 
1599  while ($obj = $this->db->fetch_object($resql)) {
1600  $modulename = $obj->element;
1601  if (strpos($obj->element, 'project') !== false) {
1602  $modulename = 'projet';
1603  } elseif ($obj->element == 'contrat') {
1604  $element = 'contract';
1605  } elseif ($obj->element == 'action') {
1606  $modulename = 'agenda';
1607  } elseif (strpos($obj->element, 'supplier') !== false && $obj->element != 'supplier_proposal') {
1608  $modulename = 'fournisseur';
1609  } elseif (strpos($obj->element, 'supplier') !== false && $obj->element != 'supplier_proposal') {
1610  $modulename = 'fournisseur';
1611  }
1612  if (!empty($conf->{$modulename}->enabled)) {
1613  $libelle_element = $langs->trans('ContactDefault_'.$obj->element);
1614  $tmpelement = $obj->element;
1615  $transkey = "TypeContact_".$tmpelement."_".$source."_".$obj->code;
1616  $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle);
1617  if (empty($option)) {
1618  $tab[$obj->rowid] = $libelle_element.' - '.$libelle_type;
1619  } else {
1620  $tab[$obj->rowid] = $libelle_element.' - '.$libelle_type;
1621  }
1622  }
1623  }
1624  }
1625  return $tab;
1626  } else {
1627  $this->error = $this->db->lasterror();
1628  return null;
1629  }
1630  }
1631 
1643  public function getIdContact($source, $code, $status = 0)
1644  {
1645  global $conf;
1646 
1647  $result = array();
1648  $i = 0;
1649  //cas particulier pour les expeditions
1650  if ($this->element == 'shipping' && $this->origin_id != 0) {
1651  $id = $this->origin_id;
1652  $element = 'commande';
1653  } elseif ($this->element == 'reception' && $this->origin_id != 0) {
1654  $id = $this->origin_id;
1655  $element = 'order_supplier';
1656  } else {
1657  $id = $this->id;
1658  $element = $this->element;
1659  }
1660 
1661  $sql = "SELECT ec.fk_socpeople";
1662  $sql .= " FROM ".$this->db->prefix()."element_contact as ec,";
1663  if ($source == 'internal') {
1664  $sql .= " ".$this->db->prefix()."user as c,";
1665  }
1666  if ($source == 'external') {
1667  $sql .= " ".$this->db->prefix()."socpeople as c,";
1668  }
1669  $sql .= " ".$this->db->prefix()."c_type_contact as tc";
1670  $sql .= " WHERE ec.element_id = ".((int) $id);
1671  $sql .= " AND ec.fk_socpeople = c.rowid";
1672  if ($source == 'internal') {
1673  $sql .= " AND c.entity IN (".getEntity('user').")";
1674  }
1675  if ($source == 'external') {
1676  $sql .= " AND c.entity IN (".getEntity('societe').")";
1677  }
1678  $sql .= " AND ec.fk_c_type_contact = tc.rowid";
1679  $sql .= " AND tc.element = '".$this->db->escape($element)."'";
1680  $sql .= " AND tc.source = '".$this->db->escape($source)."'";
1681  if ($code) {
1682  $sql .= " AND tc.code = '".$this->db->escape($code)."'";
1683  }
1684  $sql .= " AND tc.active = 1";
1685  if ($status) {
1686  $sql .= " AND ec.statut = ".((int) $status);
1687  }
1688 
1689  dol_syslog(get_class($this)."::getIdContact", LOG_DEBUG);
1690  $resql = $this->db->query($sql);
1691  if ($resql) {
1692  while ($obj = $this->db->fetch_object($resql)) {
1693  $result[$i] = $obj->fk_socpeople;
1694  $i++;
1695  }
1696  } else {
1697  $this->error = $this->db->error();
1698  return null;
1699  }
1700 
1701  return $result;
1702  }
1703 
1704  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1711  public function fetch_contact($contactid = null)
1712  {
1713  // phpcs:enable
1714  if (empty($contactid)) {
1715  $contactid = $this->contact_id;
1716  }
1717 
1718  if (empty($contactid)) {
1719  return 0;
1720  }
1721 
1722  require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
1723  $contact = new Contact($this->db);
1724  $result = $contact->fetch($contactid);
1725  $this->contact = $contact;
1726  return $result;
1727  }
1728 
1729  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1736  public function fetch_thirdparty($force_thirdparty_id = 0)
1737  {
1738  // phpcs:enable
1739  global $conf;
1740 
1741  if (empty($this->socid) && empty($this->fk_soc) && empty($force_thirdparty_id)) {
1742  return 0;
1743  }
1744 
1745  require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
1746 
1747  $idtofetch = isset($this->socid) ? $this->socid : (isset($this->fk_soc) ? $this->fk_soc : 0);
1748  if ($force_thirdparty_id) {
1749  $idtofetch = $force_thirdparty_id;
1750  }
1751 
1752  if ($idtofetch) {
1753  $thirdparty = new Societe($this->db);
1754  $result = $thirdparty->fetch($idtofetch);
1755  if ($result<0) {
1756  $this->errors=array_merge($this->errors, $thirdparty->errors);
1757  }
1758  $this->thirdparty = $thirdparty;
1759 
1760  // Use first price level if level not defined for third party
1761  if (!empty($conf->global->PRODUIT_MULTIPRICES) && empty($this->thirdparty->price_level)) {
1762  $this->thirdparty->price_level = 1;
1763  }
1764 
1765  return $result;
1766  } else {
1767  return -1;
1768  }
1769  }
1770 
1771 
1779  public function fetchOneLike($ref)
1780  {
1781  if (!$this->table_ref_field) {
1782  return 0;
1783  }
1784 
1785  $sql = "SELECT rowid FROM ".$this->db->prefix().$this->table_element." WHERE ".$this->table_ref_field." LIKE '".$this->db->escape($ref)."' LIMIT 1";
1786 
1787  $query = $this->db->query($sql);
1788 
1789  if (!$this->db->num_rows($query)) {
1790  return 0;
1791  }
1792 
1793  $result = $this->db->fetch_object($query);
1794 
1795  return $this->fetch($result->rowid);
1796  }
1797 
1798  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1806  public function fetch_barcode()
1807  {
1808  // phpcs:enable
1809  global $conf;
1810 
1811  dol_syslog(get_class($this).'::fetch_barcode this->element='.$this->element.' this->barcode_type='.$this->barcode_type);
1812 
1813  $idtype = $this->barcode_type;
1814  if (empty($idtype) && $idtype != '0') { // If type of barcode no set, we try to guess. If set to '0' it means we forced to have type remain not defined
1815  if ($this->element == 'product' && !empty($conf->global->PRODUIT_DEFAULT_BARCODE_TYPE)) {
1816  $idtype = $conf->global->PRODUIT_DEFAULT_BARCODE_TYPE;
1817  } elseif ($this->element == 'societe') {
1818  $idtype = $conf->global->GENBARCODE_BARCODETYPE_THIRDPARTY;
1819  } else {
1820  dol_syslog('Call fetch_barcode with barcode_type not defined and cant be guessed', LOG_WARNING);
1821  }
1822  }
1823 
1824  if ($idtype > 0) {
1825  if (empty($this->barcode_type) || empty($this->barcode_type_code) || empty($this->barcode_type_label) || empty($this->barcode_type_coder)) { // If data not already loaded
1826  $sql = "SELECT rowid, code, libelle as label, coder";
1827  $sql .= " FROM ".$this->db->prefix()."c_barcode_type";
1828  $sql .= " WHERE rowid = ".((int) $idtype);
1829  dol_syslog(get_class($this).'::fetch_barcode', LOG_DEBUG);
1830  $resql = $this->db->query($sql);
1831  if ($resql) {
1832  $obj = $this->db->fetch_object($resql);
1833  $this->barcode_type = $obj->rowid;
1834  $this->barcode_type_code = $obj->code;
1835  $this->barcode_type_label = $obj->label;
1836  $this->barcode_type_coder = $obj->coder;
1837  return 1;
1838  } else {
1839  dol_print_error($this->db);
1840  return -1;
1841  }
1842  }
1843  }
1844  return 0;
1845  }
1846 
1847  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1853  public function fetch_project()
1854  {
1855  // phpcs:enable
1856  return $this->fetch_projet();
1857  }
1858 
1859  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1865  public function fetch_projet()
1866  {
1867  // phpcs:enable
1868  include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
1869 
1870  if (empty($this->fk_project) && !empty($this->fk_projet)) {
1871  $this->fk_project = $this->fk_projet; // For backward compatibility
1872  }
1873  if (empty($this->fk_project)) {
1874  return 0;
1875  }
1876 
1877  $project = new Project($this->db);
1878  $result = $project->fetch($this->fk_project);
1879 
1880  $this->projet = $project; // deprecated
1881  $this->project = $project;
1882  return $result;
1883  }
1884 
1885  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1891  public function fetch_product()
1892  {
1893  // phpcs:enable
1894  include_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
1895 
1896  if (empty($this->fk_product)) {
1897  return 0;
1898  }
1899 
1900  $product = new Product($this->db);
1901  $result = $product->fetch($this->fk_product);
1902 
1903  $this->product = $product;
1904  return $result;
1905  }
1906 
1907  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1914  public function fetch_user($userid)
1915  {
1916  // phpcs:enable
1917  $user = new User($this->db);
1918  $result = $user->fetch($userid);
1919  $this->user = $user;
1920  return $result;
1921  }
1922 
1923  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1929  public function fetch_origin()
1930  {
1931  // phpcs:enable
1932  if ($this->origin == 'shipping') {
1933  $this->origin = 'expedition';
1934  }
1935  if ($this->origin == 'delivery') {
1936  $this->origin = 'livraison';
1937  }
1938  if ($this->origin == 'order_supplier') {
1939  $this->origin = 'commandeFournisseur';
1940  }
1941 
1942  $origin = $this->origin;
1943 
1944  $classname = ucfirst($origin);
1945  $this->$origin = new $classname($this->db);
1946  $this->$origin->fetch($this->origin_id);
1947  }
1948 
1958  public function fetchObjectFrom($table, $field, $key, $element = null)
1959  {
1960  global $conf;
1961 
1962  $result = false;
1963 
1964  $sql = "SELECT rowid FROM ".$this->db->prefix().$table;
1965  $sql .= " WHERE ".$field." = '".$this->db->escape($key)."'";
1966  if (!empty($element)) {
1967  $sql .= " AND entity IN (".getEntity($element).")";
1968  } else {
1969  $sql .= " AND entity = ".((int) $conf->entity);
1970  }
1971 
1972  dol_syslog(get_class($this).'::fetchObjectFrom', LOG_DEBUG);
1973  $resql = $this->db->query($sql);
1974  if ($resql) {
1975  $row = $this->db->fetch_row($resql);
1976  // Test for avoid error -1
1977  if ($row[0] > 0) {
1978  $result = $this->fetch($row[0]);
1979  }
1980  }
1981 
1982  return $result;
1983  }
1984 
1993  public function getValueFrom($table, $id, $field)
1994  {
1995  $result = false;
1996  if (!empty($id) && !empty($field) && !empty($table)) {
1997  $sql = "SELECT ".$field." FROM ".$this->db->prefix().$table;
1998  $sql .= " WHERE rowid = ".((int) $id);
1999 
2000  dol_syslog(get_class($this).'::getValueFrom', LOG_DEBUG);
2001  $resql = $this->db->query($sql);
2002  if ($resql) {
2003  $row = $this->db->fetch_row($resql);
2004  $result = $row[0];
2005  }
2006  }
2007  return $result;
2008  }
2009 
2026  public function setValueFrom($field, $value, $table = '', $id = null, $format = '', $id_field = '', $fuser = null, $trigkey = '', $fk_user_field = 'fk_user_modif')
2027  {
2028  global $user, $langs, $conf;
2029 
2030  if (empty($table)) {
2031  $table = $this->table_element;
2032  }
2033  if (empty($id)) {
2034  $id = $this->id;
2035  }
2036  if (empty($format)) {
2037  $format = 'text';
2038  }
2039  if (empty($id_field)) {
2040  $id_field = 'rowid';
2041  }
2042 
2043  $error = 0;
2044 
2045  $this->db->begin();
2046 
2047  // Special case
2048  if ($table == 'product' && $field == 'note_private') {
2049  $field = 'note';
2050  }
2051  if (in_array($table, array('actioncomm', 'adherent', 'advtargetemailing', 'cronjob', 'establishment'))) {
2052  $fk_user_field = 'fk_user_mod';
2053  }
2054 
2055  $sql = "UPDATE ".$this->db->prefix().$table." SET ";
2056 
2057  if ($format == 'text') {
2058  $sql .= $field." = '".$this->db->escape($value)."'";
2059  } elseif ($format == 'int') {
2060  $sql .= $field." = ".((int) $value);
2061  } elseif ($format == 'date') {
2062  $sql .= $field." = ".($value ? "'".$this->db->idate($value)."'" : "null");
2063  }
2064 
2065  if ($fk_user_field) {
2066  if (!empty($fuser) && is_object($fuser)) {
2067  $sql .= ", ".$fk_user_field." = ".((int) $fuser->id);
2068  } elseif (empty($fuser) || $fuser != 'none') {
2069  $sql .= ", ".$fk_user_field." = ".((int) $user->id);
2070  }
2071  }
2072 
2073  $sql .= " WHERE ".$id_field." = ".((int) $id);
2074 
2075  dol_syslog(__METHOD__."", LOG_DEBUG);
2076  $resql = $this->db->query($sql);
2077  if ($resql) {
2078  if ($trigkey) {
2079  // call trigger with updated object values
2080  if (empty($this->fields) && method_exists($this, 'fetch')) {
2081  $result = $this->fetch($id);
2082  } else {
2083  $result = $this->fetchCommon($id);
2084  }
2085  if ($result >= 0) {
2086  $result = $this->call_trigger($trigkey, (!empty($fuser) && is_object($fuser)) ? $fuser : $user); // This may set this->errors
2087  }
2088  if ($result < 0) {
2089  $error++;
2090  }
2091  }
2092 
2093  if (!$error) {
2094  if (property_exists($this, $field)) {
2095  $this->$field = $value;
2096  }
2097  $this->db->commit();
2098  return 1;
2099  } else {
2100  $this->db->rollback();
2101  return -2;
2102  }
2103  } else {
2104  if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
2105  $this->error = 'DB_ERROR_RECORD_ALREADY_EXISTS';
2106  } else {
2107  $this->error = $this->db->lasterror();
2108  }
2109  $this->db->rollback();
2110  return -1;
2111  }
2112  }
2113 
2114  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2123  public function load_previous_next_ref($filter, $fieldid, $nodbprefix = 0)
2124  {
2125  // phpcs:enable
2126  global $conf, $user;
2127 
2128  if (!$this->table_element) {
2129  dol_print_error('', get_class($this)."::load_previous_next_ref was called on objet with property table_element not defined");
2130  return -1;
2131  }
2132  if ($fieldid == 'none') {
2133  return 1;
2134  }
2135 
2136  // For backward compatibility
2137  if (in_array($this->table_element, array('facture_rec', 'facture_fourn_rec')) && $fieldid == 'title') {
2138  $fieldid = 'titre';
2139  }
2140 
2141  // Security on socid
2142  $socid = 0;
2143  if ($user->socid > 0) {
2144  $socid = $user->socid;
2145  }
2146 
2147  // this->ismultientitymanaged contains
2148  // 0=No test on entity, 1=Test with field entity, 'field@table'=Test with link by field@table
2149  $aliastablesociete = 's';
2150  if ($this->element == 'societe') {
2151  $aliastablesociete = 'te'; // te as table_element
2152  }
2153  $restrictiononfksoc = empty($this->restrictiononfksoc) ? 0 : $this->restrictiononfksoc;
2154  $sql = "SELECT MAX(te.".$fieldid.")";
2155  $sql .= " FROM ".(empty($nodbprefix) ?$this->db->prefix():'').$this->table_element." as te";
2156  if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
2157  $sql .= ",".$this->db->prefix()."usergroup_user as ug";
2158  }
2159  if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2160  $tmparray = explode('@', $this->ismultientitymanaged);
2161  $sql .= ", ".$this->db->prefix().$tmparray[1]." as ".($tmparray[1] == 'societe' ? 's' : 'parenttable'); // If we need to link to this table to limit select to entity
2162  } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
2163  $sql .= ", ".$this->db->prefix()."societe as s"; // If we need to link to societe to limit select to socid
2164  } elseif ($restrictiononfksoc == 2 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
2165  $sql .= " LEFT JOIN ".$this->db->prefix()."societe as s ON te.fk_soc = s.rowid"; // If we need to link to societe to limit select to socid
2166  }
2167  if ($restrictiononfksoc && empty($user->rights->societe->client->voir) && !$socid) {
2168  $sql .= " LEFT JOIN ".$this->db->prefix()."societe_commerciaux as sc ON ".$aliastablesociete.".rowid = sc.fk_soc";
2169  }
2170  $sql .= " WHERE te.".$fieldid." < '".$this->db->escape($fieldid == 'rowid' ? $this->id : $this->ref)."'"; // ->ref must always be defined (set to id if field does not exists)
2171  if ($restrictiononfksoc == 1 && empty($user->rights->societe->client->voir) && !$socid) {
2172  $sql .= " AND sc.fk_user = ".((int) $user->id);
2173  }
2174  if ($restrictiononfksoc == 2 && empty($user->rights->societe->client->voir) && !$socid) {
2175  $sql .= " AND (sc.fk_user = ".((int) $user->id).' OR te.fk_soc IS NULL)';
2176  }
2177  if (!empty($filter)) {
2178  if (!preg_match('/^\s*AND/i', $filter)) {
2179  $sql .= " AND "; // For backward compatibility
2180  }
2181  $sql .= $filter;
2182  }
2183  if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2184  $tmparray = explode('@', $this->ismultientitymanaged);
2185  $sql .= " AND te.".$tmparray[0]." = ".($tmparray[1] == "societe" ? "s" : "parenttable").".rowid"; // If we need to link to this table to limit select to entity
2186  } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
2187  $sql .= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to socid
2188  }
2189  if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
2190  if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
2191  if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
2192  $sql .= " AND te.entity IS NOT NULL"; // Show all users
2193  } else {
2194  $sql .= " AND ug.fk_user = te.rowid";
2195  $sql .= " AND ug.entity IN (".getEntity('usergroup').")";
2196  }
2197  } else {
2198  $sql .= ' AND te.entity IN ('.getEntity($this->element).')';
2199  }
2200  }
2201  if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged) && $this->element != 'societe') {
2202  $tmparray = explode('@', $this->ismultientitymanaged);
2203  $sql .= ' AND parenttable.entity IN ('.getEntity($tmparray[1]).')';
2204  }
2205  if ($restrictiononfksoc == 1 && $socid && $this->element != 'societe') {
2206  $sql .= ' AND te.fk_soc = '.((int) $socid);
2207  }
2208  if ($restrictiononfksoc == 2 && $socid && $this->element != 'societe') {
2209  $sql .= ' AND (te.fk_soc = '.((int) $socid).' OR te.fk_soc IS NULL)';
2210  }
2211  if ($restrictiononfksoc && $socid && $this->element == 'societe') {
2212  $sql .= ' AND te.rowid = '.((int) $socid);
2213  }
2214  //print 'socid='.$socid.' restrictiononfksoc='.$restrictiononfksoc.' ismultientitymanaged = '.$this->ismultientitymanaged.' filter = '.$filter.' -> '.$sql."<br>";
2215 
2216  $result = $this->db->query($sql);
2217  if (!$result) {
2218  $this->error = $this->db->lasterror();
2219  return -1;
2220  }
2221  $row = $this->db->fetch_row($result);
2222  $this->ref_previous = $row[0];
2223 
2224  $sql = "SELECT MIN(te.".$fieldid.")";
2225  $sql .= " FROM ".(empty($nodbprefix) ?$this->db->prefix():'').$this->table_element." as te";
2226  if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
2227  $sql .= ",".$this->db->prefix()."usergroup_user as ug";
2228  }
2229  if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2230  $tmparray = explode('@', $this->ismultientitymanaged);
2231  $sql .= ", ".$this->db->prefix().$tmparray[1]." as ".($tmparray[1] == 'societe' ? 's' : 'parenttable'); // If we need to link to this table to limit select to entity
2232  } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
2233  $sql .= ", ".$this->db->prefix()."societe as s"; // If we need to link to societe to limit select to socid
2234  } elseif ($restrictiononfksoc == 2 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
2235  $sql .= " LEFT JOIN ".$this->db->prefix()."societe as s ON te.fk_soc = s.rowid"; // If we need to link to societe to limit select to socid
2236  }
2237  if ($restrictiononfksoc && empty($user->rights->societe->client->voir) && !$socid) {
2238  $sql .= " LEFT JOIN ".$this->db->prefix()."societe_commerciaux as sc ON ".$aliastablesociete.".rowid = sc.fk_soc";
2239  }
2240  $sql .= " WHERE te.".$fieldid." > '".$this->db->escape($fieldid == 'rowid' ? $this->id : $this->ref)."'"; // ->ref must always be defined (set to id if field does not exists)
2241  if ($restrictiononfksoc == 1 && empty($user->rights->societe->client->voir) && !$socid) {
2242  $sql .= " AND sc.fk_user = ".((int) $user->id);
2243  }
2244  if ($restrictiononfksoc == 2 && empty($user->rights->societe->client->voir) && !$socid) {
2245  $sql .= " AND (sc.fk_user = ".((int) $user->id).' OR te.fk_soc IS NULL)';
2246  }
2247  if (!empty($filter)) {
2248  if (!preg_match('/^\s*AND/i', $filter)) {
2249  $sql .= " AND "; // For backward compatibility
2250  }
2251  $sql .= $filter;
2252  }
2253  if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2254  $tmparray = explode('@', $this->ismultientitymanaged);
2255  $sql .= " AND te.".$tmparray[0]." = ".($tmparray[1] == "societe" ? "s" : "parenttable").".rowid"; // If we need to link to this table to limit select to entity
2256  } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
2257  $sql .= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to socid
2258  }
2259  if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
2260  if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
2261  if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
2262  $sql .= " AND te.entity IS NOT NULL"; // Show all users
2263  } else {
2264  $sql .= " AND ug.fk_user = te.rowid";
2265  $sql .= " AND ug.entity IN (".getEntity('usergroup').")";
2266  }
2267  } else {
2268  $sql .= ' AND te.entity IN ('.getEntity($this->element).')';
2269  }
2270  }
2271  if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged) && $this->element != 'societe') {
2272  $tmparray = explode('@', $this->ismultientitymanaged);
2273  $sql .= ' AND parenttable.entity IN ('.getEntity($tmparray[1]).')';
2274  }
2275  if ($restrictiononfksoc == 1 && $socid && $this->element != 'societe') {
2276  $sql .= ' AND te.fk_soc = '.((int) $socid);
2277  }
2278  if ($restrictiononfksoc == 2 && $socid && $this->element != 'societe') {
2279  $sql .= ' AND (te.fk_soc = '.((int) $socid).' OR te.fk_soc IS NULL)';
2280  }
2281  if ($restrictiononfksoc && $socid && $this->element == 'societe') {
2282  $sql .= ' AND te.rowid = '.((int) $socid);
2283  }
2284  //print 'socid='.$socid.' restrictiononfksoc='.$restrictiononfksoc.' ismultientitymanaged = '.$this->ismultientitymanaged.' filter = '.$filter.' -> '.$sql."<br>";
2285  // Rem: Bug in some mysql version: SELECT MIN(rowid) FROM llx_socpeople WHERE rowid > 1 when one row in database with rowid=1, returns 1 instead of null
2286 
2287  $result = $this->db->query($sql);
2288  if (!$result) {
2289  $this->error = $this->db->lasterror();
2290  return -2;
2291  }
2292  $row = $this->db->fetch_row($result);
2293  $this->ref_next = $row[0];
2294 
2295  return 1;
2296  }
2297 
2298 
2306  public function getListContactId($source = 'external')
2307  {
2308  $contactAlreadySelected = array();
2309  $tab = $this->liste_contact(-1, $source);
2310  $num = count($tab);
2311  $i = 0;
2312  while ($i < $num) {
2313  if ($source == 'thirdparty') {
2314  $contactAlreadySelected[$i] = $tab[$i]['socid'];
2315  } else {
2316  $contactAlreadySelected[$i] = $tab[$i]['id'];
2317  }
2318  $i++;
2319  }
2320  return $contactAlreadySelected;
2321  }
2322 
2323 
2331  public function setProject($projectid, $notrigger = 0)
2332  {
2333  global $user;
2334  $error = 0;
2335 
2336  if (!$this->table_element) {
2337  dol_syslog(get_class($this)."::setProject was called on objet with property table_element not defined", LOG_ERR);
2338  return -1;
2339  }
2340 
2341  $sql = "UPDATE ".$this->db->prefix().$this->table_element;
2342  if (!empty($this->fields['fk_project'])) { // Common case
2343  if ($projectid) {
2344  $sql .= " SET fk_project = ".((int) $projectid);
2345  } else {
2346  $sql .= " SET fk_project = NULL";
2347  }
2348  $sql .= ' WHERE rowid = '.((int) $this->id);
2349  } elseif ($this->table_element == 'actioncomm') { // Special case for actioncomm
2350  if ($projectid) {
2351  $sql .= " SET fk_project = ".((int) $projectid);
2352  } else {
2353  $sql .= " SET fk_project = NULL";
2354  }
2355  $sql .= ' WHERE id = '.((int) $this->id);
2356  } else // Special case for old architecture objects
2357  {
2358  if ($projectid) {
2359  $sql .= ' SET fk_projet = '.((int) $projectid);
2360  } else {
2361  $sql .= ' SET fk_projet = NULL';
2362  }
2363  $sql .= " WHERE rowid = ".((int) $this->id);
2364  }
2365 
2366  $this->db->begin();
2367 
2368  dol_syslog(get_class($this)."::setProject", LOG_DEBUG);
2369  if ($this->db->query($sql)) {
2370  $this->fk_project = ((int) $projectid);
2371  } else {
2372  dol_print_error($this->db);
2373  $error++;
2374  }
2375 
2376  // Triggers
2377  if (!$error && !$notrigger) {
2378  // Call triggers
2379  $result = $this->call_trigger(strtoupper($this->element) . '_MODIFY', $user);
2380  if ($result < 0) {
2381  $error++;
2382  } //Do also here what you must do to rollback action if trigger fail
2383  // End call triggers
2384  }
2385 
2386  // Commit or rollback
2387  if ($error) {
2388  $this->db->rollback();
2389  return -1;
2390  } else {
2391  $this->db->commit();
2392  return 1;
2393  }
2394  }
2395 
2402  public function setPaymentMethods($id)
2403  {
2404  global $user;
2405 
2406  $error = 0; $notrigger = 0;
2407 
2408  dol_syslog(get_class($this).'::setPaymentMethods('.$id.')');
2409 
2410  if ($this->statut >= 0 || $this->element == 'societe') {
2411  // TODO uniformize field name
2412  $fieldname = 'fk_mode_reglement';
2413  if ($this->element == 'societe') {
2414  $fieldname = 'mode_reglement';
2415  }
2416  if (get_class($this) == 'Fournisseur') {
2417  $fieldname = 'mode_reglement_supplier';
2418  }
2419  if (get_class($this) == 'Tva') {
2420  $fieldname = 'fk_typepayment';
2421  }
2422  if (get_class($this) == 'Salary') {
2423  $fieldname = 'fk_typepayment';
2424  }
2425 
2426  $sql = "UPDATE ".$this->db->prefix().$this->table_element;
2427  $sql .= " SET ".$fieldname." = ".(($id > 0 || $id == '0') ? ((int) $id) : 'NULL');
2428  $sql .= ' WHERE rowid='.((int) $this->id);
2429 
2430  if ($this->db->query($sql)) {
2431  $this->mode_reglement_id = $id;
2432  // for supplier
2433  if (get_class($this) == 'Fournisseur') {
2434  $this->mode_reglement_supplier_id = $id;
2435  }
2436  // Triggers
2437  if (!$error && !$notrigger) {
2438  // Call triggers
2439  if (get_class($this) == 'Commande') {
2440  $result = $this->call_trigger('ORDER_MODIFY', $user);
2441  } else {
2442  $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $user);
2443  }
2444  if ($result < 0) {
2445  $error++;
2446  }
2447  // End call triggers
2448  }
2449  return 1;
2450  } else {
2451  dol_syslog(get_class($this).'::setPaymentMethods Error '.$this->db->error());
2452  $this->error = $this->db->error();
2453  return -1;
2454  }
2455  } else {
2456  dol_syslog(get_class($this).'::setPaymentMethods, status of the object is incompatible');
2457  $this->error = 'Status of the object is incompatible '.$this->statut;
2458  return -2;
2459  }
2460  }
2461 
2468  public function setMulticurrencyCode($code)
2469  {
2470  dol_syslog(get_class($this).'::setMulticurrencyCode('.$code.')');
2471  if ($this->statut >= 0 || $this->element == 'societe') {
2472  $fieldname = 'multicurrency_code';
2473 
2474  $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
2475  $sql .= " SET ".$fieldname." = '".$this->db->escape($code)."'";
2476  $sql .= ' WHERE rowid='.((int) $this->id);
2477 
2478  if ($this->db->query($sql)) {
2479  $this->multicurrency_code = $code;
2480 
2481  list($fk_multicurrency, $rate) = MultiCurrency::getIdAndTxFromCode($this->db, $code);
2482  if ($rate) {
2483  $this->setMulticurrencyRate($rate, 2);
2484  }
2485 
2486  return 1;
2487  } else {
2488  dol_syslog(get_class($this).'::setMulticurrencyCode Error '.$sql.' - '.$this->db->error());
2489  $this->error = $this->db->error();
2490  return -1;
2491  }
2492  } else {
2493  dol_syslog(get_class($this).'::setMulticurrencyCode, status of the object is incompatible');
2494  $this->error = 'Status of the object is incompatible '.$this->statut;
2495  return -2;
2496  }
2497  }
2498 
2506  public function setMulticurrencyRate($rate, $mode = 1)
2507  {
2508  dol_syslog(get_class($this).'::setMulticurrencyRate('.$rate.','.$mode.')');
2509  if ($this->statut >= 0 || $this->element == 'societe') {
2510  $fieldname = 'multicurrency_tx';
2511 
2512  $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
2513  $sql .= " SET ".$fieldname." = ".((float) $rate);
2514  $sql .= ' WHERE rowid='.((int) $this->id);
2515 
2516  if ($this->db->query($sql)) {
2517  $this->multicurrency_tx = $rate;
2518 
2519  // Update line price
2520  if (!empty($this->lines)) {
2521  foreach ($this->lines as &$line) {
2522  // Amounts in company currency will be recalculated
2523  if ($mode == 1) {
2524  $line->subprice = 0;
2525  }
2526 
2527  // Amounts in foreign currency will be recalculated
2528  if ($mode == 2) {
2529  $line->multicurrency_subprice = 0;
2530  }
2531 
2532  switch ($this->element) {
2533  case 'propal':
2534  $this->updateline(
2535  $line->id,
2536  $line->subprice,
2537  $line->qty,
2538  $line->remise_percent,
2539  $line->tva_tx,
2540  $line->localtax1_tx,
2541  $line->localtax2_tx,
2542  ($line->description ? $line->description : $line->desc),
2543  'HT',
2544  $line->info_bits,
2545  $line->special_code,
2546  $line->fk_parent_line,
2547  $line->skip_update_total,
2548  $line->fk_fournprice,
2549  $line->pa_ht,
2550  $line->label,
2551  $line->product_type,
2552  $line->date_start,
2553  $line->date_end,
2554  $line->array_options,
2555  $line->fk_unit,
2556  $line->multicurrency_subprice
2557  );
2558  break;
2559  case 'commande':
2560  $this->updateline(
2561  $line->id,
2562  ($line->description ? $line->description : $line->desc),
2563  $line->subprice,
2564  $line->qty,
2565  $line->remise_percent,
2566  $line->tva_tx,
2567  $line->localtax1_tx,
2568  $line->localtax2_tx,
2569  'HT',
2570  $line->info_bits,
2571  $line->date_start,
2572  $line->date_end,
2573  $line->product_type,
2574  $line->fk_parent_line,
2575  $line->skip_update_total,
2576  $line->fk_fournprice,
2577  $line->pa_ht,
2578  $line->label,
2579  $line->special_code,
2580  $line->array_options,
2581  $line->fk_unit,
2582  $line->multicurrency_subprice
2583  );
2584  break;
2585  case 'facture':
2586  $this->updateline(
2587  $line->id,
2588  ($line->description ? $line->description : $line->desc),
2589  $line->subprice,
2590  $line->qty,
2591  $line->remise_percent,
2592  $line->date_start,
2593  $line->date_end,
2594  $line->tva_tx,
2595  $line->localtax1_tx,
2596  $line->localtax2_tx,
2597  'HT',
2598  $line->info_bits,
2599  $line->product_type,
2600  $line->fk_parent_line,
2601  $line->skip_update_total,
2602  $line->fk_fournprice,
2603  $line->pa_ht,
2604  $line->label,
2605  $line->special_code,
2606  $line->array_options,
2607  $line->situation_percent,
2608  $line->fk_unit,
2609  $line->multicurrency_subprice
2610  );
2611  break;
2612  case 'supplier_proposal':
2613  $this->updateline(
2614  $line->id,
2615  $line->subprice,
2616  $line->qty,
2617  $line->remise_percent,
2618  $line->tva_tx,
2619  $line->localtax1_tx,
2620  $line->localtax2_tx,
2621  ($line->description ? $line->description : $line->desc),
2622  'HT',
2623  $line->info_bits,
2624  $line->special_code,
2625  $line->fk_parent_line,
2626  $line->skip_update_total,
2627  $line->fk_fournprice,
2628  $line->pa_ht,
2629  $line->label,
2630  $line->product_type,
2631  $line->array_options,
2632  $line->ref_fourn,
2633  $line->multicurrency_subprice
2634  );
2635  break;
2636  case 'order_supplier':
2637  $this->updateline(
2638  $line->id,
2639  ($line->description ? $line->description : $line->desc),
2640  $line->subprice,
2641  $line->qty,
2642  $line->remise_percent,
2643  $line->tva_tx,
2644  $line->localtax1_tx,
2645  $line->localtax2_tx,
2646  'HT',
2647  $line->info_bits,
2648  $line->product_type,
2649  false,
2650  $line->date_start,
2651  $line->date_end,
2652  $line->array_options,
2653  $line->fk_unit,
2654  $line->multicurrency_subprice,
2655  $line->ref_supplier
2656  );
2657  break;
2658  case 'invoice_supplier':
2659  $this->updateline(
2660  $line->id,
2661  ($line->description ? $line->description : $line->desc),
2662  $line->subprice,
2663  $line->tva_tx,
2664  $line->localtax1_tx,
2665  $line->localtax2_tx,
2666  $line->qty,
2667  0,
2668  'HT',
2669  $line->info_bits,
2670  $line->product_type,
2671  $line->remise_percent,
2672  false,
2673  $line->date_start,
2674  $line->date_end,
2675  $line->array_options,
2676  $line->fk_unit,
2677  $line->multicurrency_subprice,
2678  $line->ref_supplier
2679  );
2680  break;
2681  default:
2682  dol_syslog(get_class($this).'::setMulticurrencyRate no updateline defined', LOG_DEBUG);
2683  break;
2684  }
2685  }
2686  }
2687 
2688  return 1;
2689  } else {
2690  dol_syslog(get_class($this).'::setMulticurrencyRate Error '.$sql.' - '.$this->db->error());
2691  $this->error = $this->db->error();
2692  return -1;
2693  }
2694  } else {
2695  dol_syslog(get_class($this).'::setMulticurrencyRate, status of the object is incompatible');
2696  $this->error = 'Status of the object is incompatible '.$this->statut;
2697  return -2;
2698  }
2699  }
2700 
2708  public function setPaymentTerms($id, $deposit_percent = null)
2709  {
2710  dol_syslog(get_class($this).'::setPaymentTerms('.$id.', '.var_export($deposit_percent, true).')');
2711  if ($this->statut >= 0 || $this->element == 'societe') {
2712  // TODO uniformize field name
2713  $fieldname = 'fk_cond_reglement';
2714  if ($this->element == 'societe') {
2715  $fieldname = 'cond_reglement';
2716  }
2717  if (get_class($this) == 'Fournisseur') {
2718  $fieldname = 'cond_reglement_supplier';
2719  }
2720 
2721  if (empty($deposit_percent) || $deposit_percent < 0) {
2722  $deposit_percent = getDictionaryValue('c_payment_term', 'deposit_percent', $id);
2723  }
2724 
2725  if ($deposit_percent > 100) {
2726  $deposit_percent = 100;
2727  }
2728 
2729  $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
2730  $sql .= " SET ".$fieldname." = ".(($id > 0 || $id == '0') ? ((int) $id) : 'NULL');
2731  if (in_array($this->table_element, array('propal', 'commande'))) {
2732  $sql .= " , deposit_percent = " . (empty($deposit_percent) ? 'NULL' : "'".$this->db->escape($deposit_percent)."'");
2733  }
2734  $sql .= ' WHERE rowid='.((int) $this->id);
2735 
2736  if ($this->db->query($sql)) {
2737  $this->cond_reglement_id = $id;
2738  // for supplier
2739  if (get_class($this) == 'Fournisseur') {
2740  $this->cond_reglement_supplier_id = $id;
2741  }
2742  $this->cond_reglement = $id; // for compatibility
2743  $this->deposit_percent = $deposit_percent;
2744  return 1;
2745  } else {
2746  dol_syslog(get_class($this).'::setPaymentTerms Error '.$sql.' - '.$this->db->error());
2747  $this->error = $this->db->error();
2748  return -1;
2749  }
2750  } else {
2751  dol_syslog(get_class($this).'::setPaymentTerms, status of the object is incompatible');
2752  $this->error = 'Status of the object is incompatible '.$this->statut;
2753  return -2;
2754  }
2755  }
2756 
2763  public function setTransportMode($id)
2764  {
2765  dol_syslog(get_class($this).'::setTransportMode('.$id.')');
2766  if ($this->statut >= 0 || $this->element == 'societe') {
2767  $fieldname = 'fk_transport_mode';
2768  if ($this->element == 'societe') {
2769  $fieldname = 'transport_mode';
2770  }
2771  if (get_class($this) == 'Fournisseur') {
2772  $fieldname = 'transport_mode_supplier';
2773  }
2774 
2775  $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
2776  $sql .= " SET ".$fieldname." = ".(($id > 0 || $id == '0') ? ((int) $id) : 'NULL');
2777  $sql .= ' WHERE rowid='.((int) $this->id);
2778 
2779  if ($this->db->query($sql)) {
2780  $this->transport_mode_id = $id;
2781  // for supplier
2782  if (get_class($this) == 'Fournisseur') {
2783  $this->transport_mode_supplier_id = $id;
2784  }
2785  return 1;
2786  } else {
2787  dol_syslog(get_class($this).'::setTransportMode Error '.$sql.' - '.$this->db->error());
2788  $this->error = $this->db->error();
2789  return -1;
2790  }
2791  } else {
2792  dol_syslog(get_class($this).'::setTransportMode, status of the object is incompatible');
2793  $this->error = 'Status of the object is incompatible '.$this->statut;
2794  return -2;
2795  }
2796  }
2797 
2804  public function setRetainedWarrantyPaymentTerms($id)
2805  {
2806  dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms('.$id.')');
2807  if ($this->statut >= 0 || $this->element == 'societe') {
2808  $fieldname = 'retained_warranty_fk_cond_reglement';
2809 
2810  $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
2811  $sql .= " SET ".$fieldname." = ".((int) $id);
2812  $sql .= ' WHERE rowid='.((int) $this->id);
2813 
2814  if ($this->db->query($sql)) {
2815  $this->retained_warranty_fk_cond_reglement = $id;
2816  return 1;
2817  } else {
2818  dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms Error '.$sql.' - '.$this->db->error());
2819  $this->error = $this->db->error();
2820  return -1;
2821  }
2822  } else {
2823  dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms, status of the object is incompatible');
2824  $this->error = 'Status of the object is incompatible '.$this->statut;
2825  return -2;
2826  }
2827  }
2828 
2836  public function setDeliveryAddress($id)
2837  {
2838  $fieldname = 'fk_delivery_address';
2839  if ($this->element == 'delivery' || $this->element == 'shipping') {
2840  $fieldname = 'fk_address';
2841  }
2842 
2843  $sql = "UPDATE ".$this->db->prefix().$this->table_element." SET ".$fieldname." = ".((int) $id);
2844  $sql .= " WHERE rowid = ".((int) $this->id)." AND fk_statut = 0";
2845 
2846  if ($this->db->query($sql)) {
2847  $this->fk_delivery_address = $id;
2848  return 1;
2849  } else {
2850  $this->error = $this->db->error();
2851  dol_syslog(get_class($this).'::setDeliveryAddress Error '.$this->error);
2852  return -1;
2853  }
2854  }
2855 
2856 
2866  public function setShippingMethod($shipping_method_id, $notrigger = false, $userused = null)
2867  {
2868  global $user;
2869 
2870  if (empty($userused)) {
2871  $userused = $user;
2872  }
2873 
2874  $error = 0;
2875 
2876  if (!$this->table_element) {
2877  dol_syslog(get_class($this)."::setShippingMethod was called on objet with property table_element not defined", LOG_ERR);
2878  return -1;
2879  }
2880 
2881  $this->db->begin();
2882 
2883  if ($shipping_method_id < 0) {
2884  $shipping_method_id = 'NULL';
2885  }
2886  dol_syslog(get_class($this).'::setShippingMethod('.$shipping_method_id.')');
2887 
2888  $sql = "UPDATE ".$this->db->prefix().$this->table_element;
2889  $sql .= " SET fk_shipping_method = ".((int) $shipping_method_id);
2890  $sql .= " WHERE rowid=".((int) $this->id);
2891  $resql = $this->db->query($sql);
2892  if (!$resql) {
2893  dol_syslog(get_class($this).'::setShippingMethod Error ', LOG_DEBUG);
2894  $this->error = $this->db->lasterror();
2895  $error++;
2896  } else {
2897  if (!$notrigger) {
2898  // Call trigger
2899  $this->context = array('shippingmethodupdate'=>1);
2900  $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $userused);
2901  if ($result < 0) {
2902  $error++;
2903  }
2904  // End call trigger
2905  }
2906  }
2907  if ($error) {
2908  $this->db->rollback();
2909  return -1;
2910  } else {
2911  $this->shipping_method_id = ($shipping_method_id == 'NULL') ?null:$shipping_method_id;
2912  $this->db->commit();
2913  return 1;
2914  }
2915  }
2916 
2917 
2924  public function setWarehouse($warehouse_id)
2925  {
2926  if (!$this->table_element) {
2927  dol_syslog(get_class($this)."::setWarehouse was called on objet with property table_element not defined", LOG_ERR);
2928  return -1;
2929  }
2930  if ($warehouse_id < 0) {
2931  $warehouse_id = 'NULL';
2932  }
2933  dol_syslog(get_class($this).'::setWarehouse('.$warehouse_id.')');
2934 
2935  $sql = "UPDATE ".$this->db->prefix().$this->table_element;
2936  $sql .= " SET fk_warehouse = ".((int) $warehouse_id);
2937  $sql .= " WHERE rowid=".((int) $this->id);
2938 
2939  if ($this->db->query($sql)) {
2940  $this->warehouse_id = ($warehouse_id == 'NULL') ?null:$warehouse_id;
2941  return 1;
2942  } else {
2943  dol_syslog(get_class($this).'::setWarehouse Error ', LOG_DEBUG);
2944  $this->error = $this->db->error();
2945  return 0;
2946  }
2947  }
2948 
2949 
2957  public function setDocModel($user, $modelpdf)
2958  {
2959  if (!$this->table_element) {
2960  dol_syslog(get_class($this)."::setDocModel was called on objet with property table_element not defined", LOG_ERR);
2961  return -1;
2962  }
2963 
2964  $newmodelpdf = dol_trunc($modelpdf, 255);
2965 
2966  $sql = "UPDATE ".$this->db->prefix().$this->table_element;
2967  $sql .= " SET model_pdf = '".$this->db->escape($newmodelpdf)."'";
2968  $sql .= " WHERE rowid = ".((int) $this->id);
2969 
2970  dol_syslog(get_class($this)."::setDocModel", LOG_DEBUG);
2971  $resql = $this->db->query($sql);
2972  if ($resql) {
2973  $this->model_pdf = $modelpdf;
2974  $this->modelpdf = $modelpdf; // For bakward compatibility
2975  return 1;
2976  } else {
2977  dol_print_error($this->db);
2978  return 0;
2979  }
2980  }
2981 
2982 
2991  public function setBankAccount($fk_account, $notrigger = false, $userused = null)
2992  {
2993  global $user;
2994 
2995  if (empty($userused)) {
2996  $userused = $user;
2997  }
2998 
2999  $error = 0;
3000 
3001  if (!$this->table_element) {
3002  dol_syslog(get_class($this)."::setBankAccount was called on objet with property table_element not defined", LOG_ERR);
3003  return -1;
3004  }
3005  $this->db->begin();
3006 
3007  if ($fk_account < 0) {
3008  $fk_account = 'NULL';
3009  }
3010  dol_syslog(get_class($this).'::setBankAccount('.$fk_account.')');
3011 
3012  $sql = "UPDATE ".$this->db->prefix().$this->table_element;
3013  $sql .= " SET fk_account = ".((int) $fk_account);
3014  $sql .= " WHERE rowid=".((int) $this->id);
3015 
3016  $resql = $this->db->query($sql);
3017  if (!$resql) {
3018  dol_syslog(get_class($this).'::setBankAccount Error '.$sql.' - '.$this->db->error());
3019  $this->error = $this->db->lasterror();
3020  $error++;
3021  } else {
3022  if (!$notrigger) {
3023  // Call trigger
3024  $this->context = array('bankaccountupdate'=>1);
3025  $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $userused);
3026  if ($result < 0) {
3027  $error++;
3028  }
3029  // End call trigger
3030  }
3031  }
3032  if ($error) {
3033  $this->db->rollback();
3034  return -1;
3035  } else {
3036  $this->fk_account = ($fk_account == 'NULL') ?null:$fk_account;
3037  $this->db->commit();
3038  return 1;
3039  }
3040  }
3041 
3042 
3043  // TODO: Move line related operations to CommonObjectLine?
3044 
3045  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3055  public function line_order($renum = false, $rowidorder = 'ASC', $fk_parent_line = true)
3056  {
3057  // phpcs:enable
3058  if (!$this->table_element_line) {
3059  dol_syslog(get_class($this)."::line_order was called on objet with property table_element_line not defined", LOG_ERR);
3060  return -1;
3061  }
3062  if (!$this->fk_element) {
3063  dol_syslog(get_class($this)."::line_order was called on objet with property fk_element not defined", LOG_ERR);
3064  return -1;
3065  }
3066 
3067  $fieldposition = 'rang'; // @todo Rename 'rang' into 'position'
3068  if (in_array($this->table_element_line, array('bom_bomline', 'ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
3069  $fieldposition = 'position';
3070  }
3071 
3072  // Count number of lines to reorder (according to choice $renum)
3073  $nl = 0;
3074  $sql = "SELECT count(rowid) FROM ".$this->db->prefix().$this->table_element_line;
3075  $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
3076  if (!$renum) {
3077  $sql .= " AND " . $fieldposition . " = 0";
3078  }
3079  if ($renum) {
3080  $sql .= " AND " . $fieldposition . " <> 0";
3081  }
3082 
3083  dol_syslog(get_class($this)."::line_order", LOG_DEBUG);
3084  $resql = $this->db->query($sql);
3085  if ($resql) {
3086  $row = $this->db->fetch_row($resql);
3087  $nl = $row[0];
3088  } else {
3089  dol_print_error($this->db);
3090  }
3091  if ($nl > 0) {
3092  // The goal of this part is to reorder all lines, with all children lines sharing the same counter that parents.
3093  $rows = array();
3094 
3095  // We first search all lines that are parent lines (for multilevel details lines)
3096  $sql = "SELECT rowid FROM ".$this->db->prefix().$this->table_element_line;
3097  $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
3098  if ($fk_parent_line) {
3099  $sql .= ' AND fk_parent_line IS NULL';
3100  }
3101  $sql .= " ORDER BY " . $fieldposition . " ASC, rowid " . $rowidorder;
3102 
3103  dol_syslog(get_class($this)."::line_order search all parent lines", LOG_DEBUG);
3104  $resql = $this->db->query($sql);
3105  if ($resql) {
3106  $i = 0;
3107  $num = $this->db->num_rows($resql);
3108  while ($i < $num) {
3109  $row = $this->db->fetch_row($resql);
3110  $rows[] = $row[0]; // Add parent line into array rows
3111  $childrens = $this->getChildrenOfLine($row[0]);
3112  if (!empty($childrens)) {
3113  foreach ($childrens as $child) {
3114  array_push($rows, $child);
3115  }
3116  }
3117  $i++;
3118  }
3119 
3120  // Now we set a new number for each lines (parent and children with children included into parent tree)
3121  if (!empty($rows)) {
3122  foreach ($rows as $key => $row) {
3123  $this->updateRangOfLine($row, ($key + 1));
3124  }
3125  }
3126  } else {
3127  dol_print_error($this->db);
3128  }
3129  }
3130  return 1;
3131  }
3132 
3140  public function getChildrenOfLine($id, $includealltree = 0)
3141  {
3142  $fieldposition = 'rang'; // @todo Rename 'rang' into 'position'
3143  if (in_array($this->table_element_line, array('bom_bomline', 'ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
3144  $fieldposition = 'position';
3145  }
3146 
3147  $rows = array();
3148 
3149  $sql = "SELECT rowid FROM ".$this->db->prefix().$this->table_element_line;
3150  $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
3151  $sql .= ' AND fk_parent_line = '.((int) $id);
3152  $sql .= " ORDER BY " . $fieldposition . " ASC";
3153 
3154  dol_syslog(get_class($this)."::getChildrenOfLine search children lines for line ".$id, LOG_DEBUG);
3155  $resql = $this->db->query($sql);
3156  if ($resql) {
3157  if ($this->db->num_rows($resql) > 0) {
3158  while ($row = $this->db->fetch_row($resql)) {
3159  $rows[] = $row[0];
3160  if (!empty($includealltree)) {
3161  $rows = array_merge($rows, $this->getChildrenOfLine($row[0]), $includealltree);
3162  }
3163  }
3164  }
3165  }
3166  return $rows;
3167  }
3168 
3169  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3177  public function line_up($rowid, $fk_parent_line = true)
3178  {
3179  // phpcs:enable
3180  $this->line_order(false, 'ASC', $fk_parent_line);
3181 
3182  // Get rang of line
3183  $rang = $this->getRangOfLine($rowid);
3184 
3185  // Update position of line
3186  $this->updateLineUp($rowid, $rang);
3187  }
3188 
3189  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3197  public function line_down($rowid, $fk_parent_line = true)
3198  {
3199  // phpcs:enable
3200  $this->line_order(false, 'ASC', $fk_parent_line);
3201 
3202  // Get rang of line
3203  $rang = $this->getRangOfLine($rowid);
3204 
3205  // Get max value for rang
3206  $max = $this->line_max();
3207 
3208  // Update position of line
3209  $this->updateLineDown($rowid, $rang, $max);
3210  }
3211 
3219  public function updateRangOfLine($rowid, $rang)
3220  {
3221  global $hookmanager;
3222  $fieldposition = 'rang'; // @todo Rename 'rang' into 'position'
3223  if (in_array($this->table_element_line, array('bom_bomline', 'ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
3224  $fieldposition = 'position';
3225  }
3226 
3227  $sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldposition." = ".((int) $rang);
3228  $sql .= ' WHERE rowid = '.((int) $rowid);
3229 
3230  dol_syslog(get_class($this)."::updateRangOfLine", LOG_DEBUG);
3231  if (!$this->db->query($sql)) {
3232  dol_print_error($this->db);
3233  return -1;
3234  } else {
3235  $parameters=array('rowid'=>$rowid, 'rang'=>$rang, 'fieldposition' => $fieldposition);
3236  $action='';
3237  $reshook = $hookmanager->executeHooks('afterRankOfLineUpdate', $parameters, $this, $action);
3238  return 1;
3239  }
3240  }
3241 
3242  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3249  public function line_ajaxorder($rows)
3250  {
3251  // phpcs:enable
3252  $num = count($rows);
3253  for ($i = 0; $i < $num; $i++) {
3254  $this->updateRangOfLine($rows[$i], ($i + 1));
3255  }
3256  }
3257 
3265  public function updateLineUp($rowid, $rang)
3266  {
3267  if ($rang > 1) {
3268  $fieldposition = 'rang';
3269  if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
3270  $fieldposition = 'position';
3271  }
3272 
3273  $sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldposition." = ".((int) $rang);
3274  $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
3275  $sql .= " AND " . $fieldposition . " = " . ((int) ($rang - 1));
3276  if ($this->db->query($sql)) {
3277  $sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldposition." = ".((int) ($rang - 1));
3278  $sql .= ' WHERE rowid = '.((int) $rowid);
3279  if (!$this->db->query($sql)) {
3280  dol_print_error($this->db);
3281  }
3282  } else {
3283  dol_print_error($this->db);
3284  }
3285  }
3286  }
3287 
3296  public function updateLineDown($rowid, $rang, $max)
3297  {
3298  if ($rang < $max) {
3299  $fieldposition = 'rang';
3300  if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
3301  $fieldposition = 'position';
3302  }
3303 
3304  $sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldposition." = ".((int) $rang);
3305  $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
3306  $sql .= " AND " . $fieldposition . " = " . ((int) ($rang + 1));
3307  if ($this->db->query($sql)) {
3308  $sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldposition." = ".((int) ($rang + 1));
3309  $sql .= ' WHERE rowid = '.((int) $rowid);
3310  if (!$this->db->query($sql)) {
3311  dol_print_error($this->db);
3312  }
3313  } else {
3314  dol_print_error($this->db);
3315  }
3316  }
3317  }
3318 
3325  public function getRangOfLine($rowid)
3326  {
3327  $fieldposition = 'rang';
3328  if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
3329  $fieldposition = 'position';
3330  }
3331 
3332  $sql = "SELECT " . $fieldposition . " FROM ".$this->db->prefix().$this->table_element_line;
3333  $sql .= " WHERE rowid = ".((int) $rowid);
3334 
3335  dol_syslog(get_class($this)."::getRangOfLine", LOG_DEBUG);
3336  $resql = $this->db->query($sql);
3337  if ($resql) {
3338  $row = $this->db->fetch_row($resql);
3339  return $row[0];
3340  }
3341  }
3342 
3349  public function getIdOfLine($rang)
3350  {
3351  $fieldposition = 'rang';
3352  if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
3353  $fieldposition = 'position';
3354  }
3355 
3356  $sql = "SELECT rowid FROM ".$this->db->prefix().$this->table_element_line;
3357  $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
3358  $sql .= " AND " . $fieldposition . " = ".((int) $rang);
3359  $resql = $this->db->query($sql);
3360  if ($resql) {
3361  $row = $this->db->fetch_row($resql);
3362  return $row[0];
3363  }
3364  }
3365 
3366  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3373  public function line_max($fk_parent_line = 0)
3374  {
3375  // phpcs:enable
3376  $positionfield = 'rang';
3377  if (in_array($this->table_element, array('bom_bom', 'product_attribute'))) {
3378  $positionfield = 'position';
3379  }
3380 
3381  // Search the last rang with fk_parent_line
3382  if ($fk_parent_line) {
3383  $sql = "SELECT max(".$positionfield.") FROM ".$this->db->prefix().$this->table_element_line;
3384  $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
3385  $sql .= " AND fk_parent_line = ".((int) $fk_parent_line);
3386 
3387  dol_syslog(get_class($this)."::line_max", LOG_DEBUG);
3388  $resql = $this->db->query($sql);
3389  if ($resql) {
3390  $row = $this->db->fetch_row($resql);
3391  if (!empty($row[0])) {
3392  return $row[0];
3393  } else {
3394  return $this->getRangOfLine($fk_parent_line);
3395  }
3396  }
3397  } else {
3398  // If not, search the last rang of element
3399  $sql = "SELECT max(".$positionfield.") FROM ".$this->db->prefix().$this->table_element_line;
3400  $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
3401 
3402  dol_syslog(get_class($this)."::line_max", LOG_DEBUG);
3403  $resql = $this->db->query($sql);
3404  if ($resql) {
3405  $row = $this->db->fetch_row($resql);
3406  return $row[0];
3407  }
3408  }
3409  }
3410 
3411  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3418  public function update_ref_ext($ref_ext)
3419  {
3420  // phpcs:enable
3421  if (!$this->table_element) {
3422  dol_syslog(get_class($this)."::update_ref_ext was called on objet with property table_element not defined", LOG_ERR);
3423  return -1;
3424  }
3425 
3426  $sql = "UPDATE ".$this->db->prefix().$this->table_element;
3427  $sql .= " SET ref_ext = '".$this->db->escape($ref_ext)."'";
3428  $sql .= " WHERE ".(isset($this->table_rowid) ? $this->table_rowid : 'rowid')." = ".((int) $this->id);
3429 
3430  dol_syslog(get_class($this)."::update_ref_ext", LOG_DEBUG);
3431  if ($this->db->query($sql)) {
3432  $this->ref_ext = $ref_ext;
3433  return 1;
3434  } else {
3435  $this->error = $this->db->error();
3436  return -1;
3437  }
3438  }
3439 
3440  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3448  public function update_note($note, $suffix = '')
3449  {
3450  // phpcs:enable
3451  global $user;
3452 
3453  if (!$this->table_element) {
3454  $this->error = 'update_note was called on objet with property table_element not defined';
3455  dol_syslog(get_class($this)."::update_note was called on objet with property table_element not defined", LOG_ERR);
3456  return -1;
3457  }
3458  if (!in_array($suffix, array('', '_public', '_private'))) {
3459  $this->error = 'update_note Parameter suffix must be empty, \'_private\' or \'_public\'';
3460  dol_syslog(get_class($this)."::update_note Parameter suffix must be empty, '_private' or '_public'", LOG_ERR);
3461  return -2;
3462  }
3463 
3464  $newsuffix = $suffix;
3465 
3466  // Special cas
3467  if ($this->table_element == 'product' && $newsuffix == '_private') {
3468  $newsuffix = '';
3469  }
3470  if (in_array($this->table_element, array('actioncomm', 'adherent', 'advtargetemailing', 'cronjob', 'establishment'))) {
3471  $fieldusermod = "fk_user_mod";
3472  } elseif ($this->table_element == 'ecm_files') {
3473  $fieldusermod = "fk_user_m";
3474  } else {
3475  $fieldusermod = "fk_user_modif";
3476  }
3477  $sql = "UPDATE ".$this->db->prefix().$this->table_element;
3478  $sql .= " SET note".$newsuffix." = ".(!empty($note) ? ("'".$this->db->escape($note)."'") : "NULL");
3479  $sql .= ", ".$fieldusermod." = ".((int) $user->id);
3480  $sql .= " WHERE rowid = ".((int) $this->id);
3481 
3482  dol_syslog(get_class($this)."::update_note", LOG_DEBUG);
3483  if ($this->db->query($sql)) {
3484  if ($suffix == '_public') {
3485  $this->note_public = $note;
3486  } elseif ($suffix == '_private') {
3487  $this->note_private = $note;
3488  } else {
3489  $this->note = $note; // deprecated
3490  $this->note_private = $note;
3491  }
3492  return 1;
3493  } else {
3494  $this->error = $this->db->lasterror();
3495  return -1;
3496  }
3497  }
3498 
3499  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3508  public function update_note_public($note)
3509  {
3510  // phpcs:enable
3511  return $this->update_note($note, '_public');
3512  }
3513 
3514  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3525  public function update_price($exclspec = 0, $roundingadjust = 'none', $nodatabaseupdate = 0, $seller = null)
3526  {
3527  // phpcs:enable
3528  global $conf, $hookmanager, $action;
3529 
3530  $parameters = array('exclspec' => $exclspec, 'roundingadjust' => $roundingadjust, 'nodatabaseupdate' => $nodatabaseupdate, 'seller' => $seller);
3531  $reshook = $hookmanager->executeHooks('updateTotalPrice', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
3532  if ($reshook > 0) {
3533  return 1; // replacement code
3534  } elseif ($reshook < 0) {
3535  return -1; // failure
3536  } // reshook = 0 => execute normal code
3537 
3538  // Some external module want no update price after a trigger because they have another method to calculate the total (ex: with an extrafield)
3539  $MODULE = "";
3540  if ($this->element == 'propal') {
3541  $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_PROPOSAL";
3542  } elseif ($this->element == 'commande' || $this->element == 'order') {
3543  $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_ORDER";
3544  } elseif ($this->element == 'facture' || $this->element == 'invoice') {
3545  $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_INVOICE";
3546  } elseif ($this->element == 'facture_fourn' || $this->element == 'supplier_invoice' || $this->element == 'invoice_supplier' || $this->element == 'invoice_supplier_rec') {
3547  $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_INVOICE";
3548  } elseif ($this->element == 'order_supplier' || $this->element == 'supplier_order') {
3549  $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_ORDER";
3550  } elseif ($this->element == 'supplier_proposal') {
3551  $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_PROPOSAL";
3552  }
3553 
3554  if (!empty($MODULE)) {
3555  if (!empty($conf->global->$MODULE)) {
3556  $modsactivated = explode(',', $conf->global->$MODULE);
3557  foreach ($modsactivated as $mod) {
3558  if ($conf->$mod->enabled) {
3559  return 1; // update was disabled by specific setup
3560  }
3561  }
3562  }
3563  }
3564 
3565  include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
3566 
3567  if ($roundingadjust == '-1') {
3568  $roundingadjust = 'auto'; // For backward compatibility
3569  }
3570 
3571  $forcedroundingmode = $roundingadjust;
3572  if ($forcedroundingmode == 'auto' && isset($conf->global->MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND)) {
3573  $forcedroundingmode = getDolGlobalString('MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND');
3574  } elseif ($forcedroundingmode == 'auto') {
3575  $forcedroundingmode = '0';
3576  }
3577 
3578  $error = 0;
3579 
3580  $multicurrency_tx = !empty($this->multicurrency_tx) ? $this->multicurrency_tx : 1;
3581 
3582  // Define constants to find lines to sum
3583  $fieldtva = 'total_tva';
3584  $fieldlocaltax1 = 'total_localtax1';
3585  $fieldlocaltax2 = 'total_localtax2';
3586  $fieldup = 'subprice';
3587  if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier') {
3588  $fieldtva = 'tva';
3589  $fieldup = 'pu_ht';
3590  }
3591  if ($this->element == 'invoice_supplier_rec') {
3592  $fieldup = 'pu_ht';
3593  }
3594  if ($this->element == 'expensereport') {
3595  $fieldup = 'value_unit';
3596  }
3597 
3598  $sql = "SELECT rowid, qty, ".$fieldup." as up, remise_percent, total_ht, ".$fieldtva." as total_tva, total_ttc, ".$fieldlocaltax1." as total_localtax1, ".$fieldlocaltax2." as total_localtax2,";
3599  $sql .= ' tva_tx as vatrate, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type, info_bits, product_type';
3600  if ($this->table_element_line == 'facturedet') {
3601  $sql .= ', situation_percent';
3602  }
3603  $sql .= ', multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc';
3604  $sql .= " FROM ".$this->db->prefix().$this->table_element_line;
3605  $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
3606  if ($exclspec) {
3607  $product_field = 'product_type';
3608  if ($this->table_element_line == 'contratdet') {
3609  $product_field = ''; // contratdet table has no product_type field
3610  }
3611  if ($product_field) {
3612  $sql .= " AND ".$product_field." <> 9";
3613  }
3614  }
3615  $sql .= ' ORDER by rowid'; // We want to be sure to always use same order of line to not change lines differently when option MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND is used
3616 
3617  dol_syslog(get_class($this)."::update_price", LOG_DEBUG);
3618  $resql = $this->db->query($sql);
3619  if ($resql) {
3620  $this->total_ht = 0;
3621  $this->total_tva = 0;
3622  $this->total_localtax1 = 0;
3623  $this->total_localtax2 = 0;
3624  $this->total_ttc = 0;
3625  $total_ht_by_vats = array();
3626  $total_tva_by_vats = array();
3627  $total_ttc_by_vats = array();
3628  $this->multicurrency_total_ht = 0;
3629  $this->multicurrency_total_tva = 0;
3630  $this->multicurrency_total_ttc = 0;
3631 
3632  $num = $this->db->num_rows($resql);
3633  $i = 0;
3634  while ($i < $num) {
3635  $obj = $this->db->fetch_object($resql);
3636 
3637  // Note: There is no check on detail line and no check on total, if $forcedroundingmode = 'none'
3638  $parameters = array('fk_element' => $obj->rowid);
3639  $reshook = $hookmanager->executeHooks('changeRoundingMode', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
3640 
3641  if (empty($reshook) && $forcedroundingmode == '0') { // Check if data on line are consistent. This may solve lines that were not consistent because set with $forcedroundingmode='auto'
3642  // This part of code is to fix data. We should not call it too often.
3643  $localtax_array = array($obj->localtax1_type, $obj->localtax1_tx, $obj->localtax2_type, $obj->localtax2_tx);
3644  $tmpcal = calcul_price_total($obj->qty, $obj->up, $obj->remise_percent, $obj->vatrate, $obj->localtax1_tx, $obj->localtax2_tx, 0, 'HT', $obj->info_bits, $obj->product_type, $seller, $localtax_array, (isset($obj->situation_percent) ? $obj->situation_percent : 100), $multicurrency_tx);
3645 
3646  $diff_when_using_price_ht = price2num($tmpcal[1] - $obj->total_tva, 'MT', 1); // If price was set with tax price adn unit price HT has a low number of digits, then we may have a diff on recalculation from unit price HT.
3647  $diff_on_current_total = price2num($obj->total_ttc - $obj->total_ht - $obj->total_tva - $obj->total_localtax1 - $obj->total_localtax2, 'MT', 1);
3648  //var_dump($obj->total_ht.' '.$obj->total_tva.' '.$obj->total_localtax1.' '.$obj->total_localtax2.' =? '.$obj->total_ttc);
3649  //var_dump($diff_when_using_price_ht.' '.$diff_on_current_total);
3650 
3651  if ($diff_when_using_price_ht && $diff_on_current_total) {
3652  $sqlfix = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldtva." = ".price2num((float) $tmpcal[1]).", total_ttc = ".price2num((float) $tmpcal[2])." WHERE rowid = ".((int) $obj->rowid);
3653  dol_syslog('We found unconsistent data into detailed line (diff_when_using_price_ht = '.$diff_when_using_price_ht.' and diff_on_current_total = '.$diff_on_current_total.') for line rowid = '.$obj->rowid." (total vat of line calculated=".$tmpcal[1].", database=".$obj->total_tva."). We fix the total_vat and total_ttc of line by running sqlfix = ".$sqlfix, LOG_WARNING);
3654  $resqlfix = $this->db->query($sqlfix);
3655  if (!$resqlfix) {
3656  dol_print_error($this->db, 'Failed to update line');
3657  }
3658  $obj->total_tva = $tmpcal[1];
3659  $obj->total_ttc = $tmpcal[2];
3660  }
3661  }
3662 
3663  $this->total_ht += $obj->total_ht; // The field visible at end of line detail
3664  $this->total_tva += $obj->total_tva;
3665  $this->total_localtax1 += $obj->total_localtax1;
3666  $this->total_localtax2 += $obj->total_localtax2;
3667  $this->total_ttc += $obj->total_ttc;
3668  $this->multicurrency_total_ht += $obj->multicurrency_total_ht; // The field visible at end of line detail
3669  $this->multicurrency_total_tva += $obj->multicurrency_total_tva;
3670  $this->multicurrency_total_ttc += $obj->multicurrency_total_ttc;
3671 
3672  if (!isset($total_ht_by_vats[$obj->vatrate])) {
3673  $total_ht_by_vats[$obj->vatrate] = 0;
3674  }
3675  if (!isset($total_tva_by_vats[$obj->vatrate])) {
3676  $total_tva_by_vats[$obj->vatrate] = 0;
3677  }
3678  if (!isset($total_ttc_by_vats[$obj->vatrate])) {
3679  $total_ttc_by_vats[$obj->vatrate] = 0;
3680  }
3681  $total_ht_by_vats[$obj->vatrate] += $obj->total_ht;
3682  $total_tva_by_vats[$obj->vatrate] += $obj->total_tva;
3683  $total_ttc_by_vats[$obj->vatrate] += $obj->total_ttc;
3684 
3685  if ($forcedroundingmode == '1') { // Check if we need adjustement onto line for vat. TODO This works on the company currency but not on multicurrency
3686  $tmpvat = price2num($total_ht_by_vats[$obj->vatrate] * $obj->vatrate / 100, 'MT', 1);
3687  $diff = price2num($total_tva_by_vats[$obj->vatrate] - $tmpvat, 'MT', 1);
3688  //print 'Line '.$i.' rowid='.$obj->rowid.' vat_rate='.$obj->vatrate.' total_ht='.$obj->total_ht.' total_tva='.$obj->total_tva.' total_ttc='.$obj->total_ttc.' total_ht_by_vats='.$total_ht_by_vats[$obj->vatrate].' total_tva_by_vats='.$total_tva_by_vats[$obj->vatrate].' (new calculation = '.$tmpvat.') total_ttc_by_vats='.$total_ttc_by_vats[$obj->vatrate].($diff?" => DIFF":"")."<br>\n";
3689  if ($diff) {
3690  if (abs($diff) > (10 * pow(10, -1 * getDolGlobalInt('MAIN_MAX_DECIMALS_TOT', 0)))) {
3691  // If error is more than 10 times the accurancy of rounding. This should not happen.
3692  $errmsg = 'A rounding difference was detected into TOTAL but is too high to be corrected. Some data in your line may be corrupted. Try to edit each line manually.';
3693  dol_syslog($errmsg, LOG_WARNING);
3694  dol_print_error('', $errmsg);
3695  exit;
3696  }
3697  $sqlfix = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldtva." = ".price2num($obj->total_tva - $diff).", total_ttc = ".price2num($obj->total_ttc - $diff)." WHERE rowid = ".((int) $obj->rowid);
3698  dol_syslog('We found a difference of '.$diff.' for line rowid = '.$obj->rowid.". We fix the total_vat and total_ttc of line by running sqlfix = ".$sqlfix);
3699 
3700  $resqlfix = $this->db->query($sqlfix);
3701 
3702  if (!$resqlfix) {
3703  dol_print_error($this->db, 'Failed to update line');
3704  }
3705 
3706  $this->total_tva = (float) price2num($this->total_tva - $diff, '', 1);
3707  $this->total_ttc = (float) price2num($this->total_ttc - $diff, '', 1);
3708  $total_tva_by_vats[$obj->vatrate] = (float) price2num($total_tva_by_vats[$obj->vatrate] - $diff, '', 1);
3709  $total_ttc_by_vats[$obj->vatrate] = (float) price2num($total_ttc_by_vats[$obj->vatrate] - $diff, '', 1);
3710  }
3711  }
3712 
3713  $i++;
3714  }
3715 
3716  // Add revenue stamp to total
3717  $this->total_ttc += isset($this->revenuestamp) ? $this->revenuestamp : 0;
3718  $this->multicurrency_total_ttc += isset($this->revenuestamp) ? ($this->revenuestamp * $multicurrency_tx) : 0;
3719 
3720  // Situations totals
3721  if (!empty($this->situation_cycle_ref) && $this->situation_counter > 1 && method_exists($this, 'get_prev_sits') && $this->type != $this::TYPE_CREDIT_NOTE) {
3722  $prev_sits = $this->get_prev_sits();
3723 
3724  foreach ($prev_sits as $sit) { // $sit is an object Facture loaded with a fetch.
3725  $this->total_ht -= $sit->total_ht;
3726  $this->total_tva -= $sit->total_tva;
3727  $this->total_localtax1 -= $sit->total_localtax1;
3728  $this->total_localtax2 -= $sit->total_localtax2;
3729  $this->total_ttc -= $sit->total_ttc;
3730  $this->multicurrency_total_ht -= $sit->multicurrency_total_ht;
3731  $this->multicurrency_total_tva -= $sit->multicurrency_total_tva;
3732  $this->multicurrency_total_ttc -= $sit->multicurrency_total_ttc;
3733  }
3734  }
3735 
3736  // Clean total
3737  $this->total_ht = (float) price2num($this->total_ht);
3738  $this->total_tva = (float) price2num($this->total_tva);
3739  $this->total_localtax1 = (float) price2num($this->total_localtax1);
3740  $this->total_localtax2 = (float) price2num($this->total_localtax2);
3741  $this->total_ttc = (float) price2num($this->total_ttc);
3742 
3743  $this->db->free($resql);
3744 
3745  // Now update global fields total_ht, total_ttc, total_tva, total_localtax1, total_localtax2, multicurrency_total_*
3746  $fieldht = 'total_ht';
3747  $fieldtva = 'tva';
3748  $fieldlocaltax1 = 'localtax1';
3749  $fieldlocaltax2 = 'localtax2';
3750  $fieldttc = 'total_ttc';
3751  // Specific code for backward compatibility with old field names
3752  if ($this->element == 'facture' || $this->element == 'facturerec') {
3753  $fieldtva = 'total_tva';
3754  }
3755  if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier' || $this->element == 'invoice_supplier_rec') {
3756  $fieldtva = 'total_tva';
3757  }
3758  if ($this->element == 'propal') {
3759  $fieldtva = 'total_tva';
3760  }
3761  if ($this->element == 'expensereport') {
3762  $fieldtva = 'total_tva';
3763  }
3764  if ($this->element == 'supplier_proposal') {
3765  $fieldtva = 'total_tva';
3766  }
3767  if ($this->element == 'commande') {
3768  $fieldtva = 'total_tva';
3769  }
3770  if ($this->element == 'order_supplier') {
3771  $fieldtva = 'total_tva';
3772  }
3773 
3774  if (empty($nodatabaseupdate)) {
3775  $sql = "UPDATE ".$this->db->prefix().$this->table_element.' SET';
3776  $sql .= " ".$fieldht." = ".((float) price2num($this->total_ht, 'MT', 1)).",";
3777  $sql .= " ".$fieldtva." = ".((float) price2num($this->total_tva, 'MT', 1)).",";
3778  $sql .= " ".$fieldlocaltax1." = ".((float) price2num($this->total_localtax1, 'MT', 1)).",";
3779  $sql .= " ".$fieldlocaltax2." = ".((float) price2num($this->total_localtax2, 'MT', 1)).",";
3780  $sql .= " ".$fieldttc." = ".((float) price2num($this->total_ttc, 'MT', 1));
3781  $sql .= ", multicurrency_total_ht = ".((float) price2num($this->multicurrency_total_ht, 'MT', 1));
3782  $sql .= ", multicurrency_total_tva = ".((float) price2num($this->multicurrency_total_tva, 'MT', 1));
3783  $sql .= ", multicurrency_total_ttc = ".((float) price2num($this->multicurrency_total_ttc, 'MT', 1));
3784  $sql .= " WHERE rowid = ".((int) $this->id);
3785 
3786  dol_syslog(get_class($this)."::update_price", LOG_DEBUG);
3787  $resql = $this->db->query($sql);
3788 
3789  if (!$resql) {
3790  $error++;
3791  $this->error = $this->db->lasterror();
3792  $this->errors[] = $this->db->lasterror();
3793  }
3794  }
3795 
3796  if (!$error) {
3797  return 1;
3798  } else {
3799  return -1;
3800  }
3801  } else {
3802  dol_print_error($this->db, 'Bad request in update_price');
3803  return -1;
3804  }
3805  }
3806 
3807  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3818  public function add_object_linked($origin = null, $origin_id = null, $f_user = null, $notrigger = 0)
3819  {
3820  // phpcs:enable
3821  global $user, $hookmanager, $action;
3822  $origin = (!empty($origin) ? $origin : $this->origin);
3823  $origin_id = (!empty($origin_id) ? $origin_id : $this->origin_id);
3824  $f_user = isset($f_user) ? $f_user : $user;
3825 
3826  // Special case
3827  if ($origin == 'order') {
3828  $origin = 'commande';
3829  }
3830  if ($origin == 'invoice') {
3831  $origin = 'facture';
3832  }
3833  if ($origin == 'invoice_template') {
3834  $origin = 'facturerec';
3835  }
3836  if ($origin == 'supplierorder') {
3837  $origin = 'order_supplier';
3838  }
3839 
3840  // Elements of the core modules which have `$module` property but may to which we don't want to prefix module part to the element name for finding the linked object in llx_element_element.
3841  // It's because an entry for this element may be exist in llx_element_element before this modification (version <=14.2) and ave named only with their element name in fk_source or fk_target.
3842  $coremodule = array('knowledgemanagement', 'partnership', 'workstation', 'ticket', 'recruitment', 'eventorganization', 'asset');
3843  // Add module part to target type if object has $module property and isn't in core modules.
3844  $targettype = ((!empty($this->module) && ! in_array($this->module, $coremodule)) ? $this->module.'_' : '').$this->element;
3845 
3846  $parameters = array('targettype'=>$targettype);
3847  // Hook for explicitly set the targettype if it must be differtent than $this->element
3848  $reshook = $hookmanager->executeHooks('setLinkedObjectSourceTargetType', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
3849  if ($reshook > 0) {
3850  if (!empty($hookmanager->resArray['targettype'])) $targettype = $hookmanager->resArray['targettype'];
3851  }
3852 
3853  $this->db->begin();
3854  $error = 0;
3855 
3856  $sql = "INSERT INTO " . $this->db->prefix() . "element_element (";
3857  $sql .= "fk_source";
3858  $sql .= ", sourcetype";
3859  $sql .= ", fk_target";
3860  $sql .= ", targettype";
3861  $sql .= ") VALUES (";
3862  $sql .= ((int) $origin_id);
3863  $sql .= ", '" . $this->db->escape($origin) . "'";
3864  $sql .= ", " . ((int) $this->id);
3865  $sql .= ", '" . $this->db->escape($targettype) . "'";
3866  $sql .= ")";
3867 
3868  dol_syslog(get_class($this) . "::add_object_linked", LOG_DEBUG);
3869  if ($this->db->query($sql)) {
3870  if (!$notrigger) {
3871  // Call trigger
3872  $this->context['link_origin'] = $origin;
3873  $this->context['link_origin_id'] = $origin_id;
3874  $result = $this->call_trigger('OBJECT_LINK_INSERT', $f_user);
3875  if ($result < 0) {
3876  $error++;
3877  }
3878  // End call triggers
3879  }
3880  } else {
3881  $this->error = $this->db->lasterror();
3882  $error++;
3883  }
3884 
3885  if (!$error) {
3886  $this->db->commit();
3887  return 1;
3888  } else {
3889  $this->db->rollback();
3890  return 0;
3891  }
3892  }
3893 
3916  public function fetchObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $clause = 'OR', $alsosametype = 1, $orderby = 'sourcetype', $loadalsoobjects = 1)
3917  {
3918  global $conf, $hookmanager, $action;
3919 
3920  // Important for pdf generation time reduction
3921  // This boolean is true if $this->linkedObjects has already been loaded with all objects linked without filter
3922  if ($this->id > 0 && !empty($this->linkedObjectsFullLoaded[$this->id])) {
3923  return 1;
3924  }
3925 
3926  $this->linkedObjectsIds = array();
3927  $this->linkedObjects = array();
3928 
3929  $justsource = false;
3930  $justtarget = false;
3931  $withtargettype = false;
3932  $withsourcetype = false;
3933 
3934  $parameters = array('sourcetype'=>$sourcetype, 'sourceid'=>$sourceid, 'targettype'=>$targettype, 'targetid'=>$targetid);
3935  // Hook for explicitly set the targettype if it must be differtent than $this->element
3936  $reshook = $hookmanager->executeHooks('setLinkedObjectSourceTargetType', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
3937  if ($reshook > 0) {
3938  if (!empty($hookmanager->resArray['sourcetype'])) $sourcetype = $hookmanager->resArray['sourcetype'];
3939  if (!empty($hookmanager->resArray['sourceid'])) $sourceid = $hookmanager->resArray['sourceid'];
3940  if (!empty($hookmanager->resArray['targettype'])) $targettype = $hookmanager->resArray['targettype'];
3941  if (!empty($hookmanager->resArray['targetid'])) $targetid = $hookmanager->resArray['targetid'];
3942  }
3943 
3944  if (!empty($sourceid) && !empty($sourcetype) && empty($targetid)) {
3945  $justsource = true; // the source (id and type) is a search criteria
3946  if (!empty($targettype)) {
3947  $withtargettype = true;
3948  }
3949  }
3950  if (!empty($targetid) && !empty($targettype) && empty($sourceid)) {
3951  $justtarget = true; // the target (id and type) is a search criteria
3952  if (!empty($sourcetype)) {
3953  $withsourcetype = true;
3954  }
3955  }
3956 
3957  $sourceid = (!empty($sourceid) ? $sourceid : $this->id);
3958  $targetid = (!empty($targetid) ? $targetid : $this->id);
3959  $sourcetype = (!empty($sourcetype) ? $sourcetype : $this->element);
3960  $targettype = (!empty($targettype) ? $targettype : $this->element);
3961 
3962  /*if (empty($sourceid) && empty($targetid))
3963  {
3964  dol_syslog('Bad usage of function. No source nor target id defined (nor as parameter nor as object id)', LOG_ERR);
3965  return -1;
3966  }*/
3967 
3968  // Links between objects are stored in table element_element
3969  $sql = "SELECT rowid, fk_source, sourcetype, fk_target, targettype";
3970  $sql .= " FROM ".$this->db->prefix()."element_element";
3971  $sql .= " WHERE ";
3972  if ($justsource || $justtarget) {
3973  if ($justsource) {
3974  $sql .= "fk_source = ".((int) $sourceid)." AND sourcetype = '".$this->db->escape($sourcetype)."'";
3975  if ($withtargettype) {
3976  $sql .= " AND targettype = '".$this->db->escape($targettype)."'";
3977  }
3978  } elseif ($justtarget) {
3979  $sql .= "fk_target = ".((int) $targetid)." AND targettype = '".$this->db->escape($targettype)."'";
3980  if ($withsourcetype) {
3981  $sql .= " AND sourcetype = '".$this->db->escape($sourcetype)."'";
3982  }
3983  }
3984  } else {
3985  $sql .= "(fk_source = ".((int) $sourceid)." AND sourcetype = '".$this->db->escape($sourcetype)."')";
3986  $sql .= " ".$clause." (fk_target = ".((int) $targetid)." AND targettype = '".$this->db->escape($targettype)."')";
3987  if ($loadalsoobjects && $this->id > 0 && $sourceid == $this->id && $sourcetype == $this->element && $targetid == $this->id && $targettype == $this->element && $clause == 'OR') {
3988  $this->linkedObjectsFullLoaded[$this->id] = true;
3989  }
3990  }
3991  $sql .= " ORDER BY ".$orderby;
3992 
3993  dol_syslog(get_class($this)."::fetchObjectLink", LOG_DEBUG);
3994  $resql = $this->db->query($sql);
3995  if ($resql) {
3996  $num = $this->db->num_rows($resql);
3997  $i = 0;
3998  while ($i < $num) {
3999  $obj = $this->db->fetch_object($resql);
4000  if ($justsource || $justtarget) {
4001  if ($justsource) {
4002  $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
4003  } elseif ($justtarget) {
4004  $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
4005  }
4006  } else {
4007  if ($obj->fk_source == $sourceid && $obj->sourcetype == $sourcetype) {
4008  $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
4009  }
4010  if ($obj->fk_target == $targetid && $obj->targettype == $targettype) {
4011  $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
4012  }
4013  }
4014  $i++;
4015  }
4016 
4017  if (!empty($this->linkedObjectsIds)) {
4018  $tmparray = $this->linkedObjectsIds;
4019  foreach ($tmparray as $objecttype => $objectids) { // $objecttype is a module name ('facture', 'mymodule', ...) or a module name with a suffix ('project_task', 'mymodule_myobj', ...)
4020  // Parse element/subelement (ex: project_task, cabinetmed_consultation, ...)
4021  $module = $element = $subelement = $objecttype;
4022  $regs = array();
4023  if ($objecttype != 'supplier_proposal' && $objecttype != 'order_supplier' && $objecttype != 'invoice_supplier'
4024  && preg_match('/^([^_]+)_([^_]+)/i', $objecttype, $regs)) {
4025  $module = $element = $regs[1];
4026  $subelement = $regs[2];
4027  }
4028 
4029  $classpath = $element.'/class';
4030  // To work with non standard classpath or module name
4031  if ($objecttype == 'facture') {
4032  $classpath = 'compta/facture/class';
4033  } elseif ($objecttype == 'facturerec') {
4034  $classpath = 'compta/facture/class';
4035  $module = 'facture';
4036  } elseif ($objecttype == 'propal') {
4037  $classpath = 'comm/propal/class';
4038  } elseif ($objecttype == 'supplier_proposal') {
4039  $classpath = 'supplier_proposal/class';
4040  } elseif ($objecttype == 'shipping') {
4041  $classpath = 'expedition/class';
4042  $subelement = 'expedition';
4043  $module = 'expedition_bon';
4044  } elseif ($objecttype == 'delivery') {
4045  $classpath = 'delivery/class';
4046  $subelement = 'delivery';
4047  $module = 'delivery_note';
4048  } elseif ($objecttype == 'invoice_supplier' || $objecttype == 'order_supplier') {
4049  $classpath = 'fourn/class';
4050  $module = 'fournisseur';
4051  } elseif ($objecttype == 'fichinter') {
4052  $classpath = 'fichinter/class';
4053  $subelement = 'fichinter';
4054  $module = 'ficheinter';
4055  } elseif ($objecttype == 'subscription') {
4056  $classpath = 'adherents/class';
4057  $module = 'adherent';
4058  } elseif ($objecttype == 'contact') {
4059  $module = 'societe';
4060  }
4061  // Set classfile
4062  $classfile = strtolower($subelement);
4063  $classname = ucfirst($subelement);
4064 
4065  if ($objecttype == 'order') {
4066  $classfile = 'commande';
4067  $classname = 'Commande';
4068  } elseif ($objecttype == 'invoice_supplier') {
4069  $classfile = 'fournisseur.facture';
4070  $classname = 'FactureFournisseur';
4071  } elseif ($objecttype == 'order_supplier') {
4072  $classfile = 'fournisseur.commande';
4073  $classname = 'CommandeFournisseur';
4074  } elseif ($objecttype == 'supplier_proposal') {
4075  $classfile = 'supplier_proposal';
4076  $classname = 'SupplierProposal';
4077  } elseif ($objecttype == 'facturerec') {
4078  $classfile = 'facture-rec';
4079  $classname = 'FactureRec';
4080  } elseif ($objecttype == 'subscription') {
4081  $classfile = 'subscription';
4082  $classname = 'Subscription';
4083  } elseif ($objecttype == 'project' || $objecttype == 'projet') {
4084  $classpath = 'projet/class';
4085  $classfile = 'project';
4086  $classname = 'Project';
4087  } elseif ($objecttype == 'conferenceorboothattendee') {
4088  $classpath = 'eventorganization/class';
4089  $classfile = 'conferenceorboothattendee';
4090  $classname = 'ConferenceOrBoothAttendee';
4091  $module = 'eventorganization';
4092  } elseif ($objecttype == 'conferenceorbooth') {
4093  $classpath = 'eventorganization/class';
4094  $classfile = 'conferenceorbooth';
4095  $classname = 'ConferenceOrBooth';
4096  $module = 'eventorganization';
4097  } elseif ($objecttype == 'mo') {
4098  $classpath = 'mrp/class';
4099  $classfile = 'mo';
4100  $classname = 'Mo';
4101  $module = 'mrp';
4102  }
4103 
4104  // Here $module, $classfile and $classname are set, we can use them.
4105  if ($conf->$module->enabled && (($element != $this->element) || $alsosametype)) {
4106  if ($loadalsoobjects && (is_numeric($loadalsoobjects) || ($loadalsoobjects === $objecttype))) {
4107  dol_include_once('/'.$classpath.'/'.$classfile.'.class.php');
4108  //print '/'.$classpath.'/'.$classfile.'.class.php '.class_exists($classname);
4109  if (class_exists($classname)) {
4110  foreach ($objectids as $i => $objectid) { // $i is rowid into llx_element_element
4111  $object = new $classname($this->db);
4112  $ret = $object->fetch($objectid);
4113  if ($ret >= 0) {
4114  $this->linkedObjects[$objecttype][$i] = $object;
4115  }
4116  }
4117  }
4118  }
4119  } else {
4120  unset($this->linkedObjectsIds[$objecttype]);
4121  }
4122  }
4123  }
4124  return 1;
4125  } else {
4126  dol_print_error($this->db);
4127  return -1;
4128  }
4129  }
4130 
4137  public function clearObjectLinkedCache()
4138  {
4139  if ($this->id > 0 && !empty($this->linkedObjectsFullLoaded[$this->id])) {
4140  unset($this->linkedObjectsFullLoaded[$this->id]);
4141  }
4142 
4143  return 1;
4144  }
4145 
4158  public function updateObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $f_user = null, $notrigger = 0)
4159  {
4160  global $user;
4161  $updatesource = false;
4162  $updatetarget = false;
4163  $f_user = isset($f_user) ? $f_user : $user;
4164 
4165  if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) {
4166  $updatesource = true;
4167  } elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) {
4168  $updatetarget = true;
4169  }
4170 
4171  $this->db->begin();
4172  $error = 0;
4173 
4174  $sql = "UPDATE " . $this->db->prefix() . "element_element SET ";
4175  if ($updatesource) {
4176  $sql .= "fk_source = " . ((int) $sourceid);
4177  $sql .= ", sourcetype = '" . $this->db->escape($sourcetype) . "'";
4178  $sql .= " WHERE fk_target = " . ((int) $this->id);
4179  $sql .= " AND targettype = '" . $this->db->escape($this->element) . "'";
4180  } elseif ($updatetarget) {
4181  $sql .= "fk_target = " . ((int) $targetid);
4182  $sql .= ", targettype = '" . $this->db->escape($targettype) . "'";
4183  $sql .= " WHERE fk_source = " . ((int) $this->id);
4184  $sql .= " AND sourcetype = '" . $this->db->escape($this->element) . "'";
4185  }
4186 
4187  dol_syslog(get_class($this) . "::updateObjectLinked", LOG_DEBUG);
4188  if ($this->db->query($sql)) {
4189  if (!$notrigger) {
4190  // Call trigger
4191  $this->context['link_source_id'] = $sourceid;
4192  $this->context['link_source_type'] = $sourcetype;
4193  $this->context['link_target_id'] = $targetid;
4194  $this->context['link_target_type'] = $targettype;
4195  $result = $this->call_trigger('OBJECT_LINK_MODIFY', $f_user);
4196  if ($result < 0) {
4197  $error++;
4198  }
4199  // End call triggers
4200  }
4201  } else {
4202  $this->error = $this->db->lasterror();
4203  $error++;
4204  }
4205 
4206  if (!$error) {
4207  $this->db->commit();
4208  return 1;
4209  } else {
4210  $this->db->rollback();
4211  return -1;
4212  }
4213  }
4214 
4228  public function deleteObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $rowid = '', $f_user = null, $notrigger = 0)
4229  {
4230  global $user;
4231  $deletesource = false;
4232  $deletetarget = false;
4233  $f_user = isset($f_user) ? $f_user : $user;
4234 
4235  if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) {
4236  $deletesource = true;
4237  } elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) {
4238  $deletetarget = true;
4239  }
4240 
4241  $sourceid = (!empty($sourceid) ? $sourceid : $this->id);
4242  $sourcetype = (!empty($sourcetype) ? $sourcetype : $this->element);
4243  $targetid = (!empty($targetid) ? $targetid : $this->id);
4244  $targettype = (!empty($targettype) ? $targettype : $this->element);
4245  $this->db->begin();
4246  $error = 0;
4247 
4248  if (!$notrigger) {
4249  // Call trigger
4250  $this->context['link_id'] = $rowid;
4251  $this->context['link_source_id'] = $sourceid;
4252  $this->context['link_source_type'] = $sourcetype;
4253  $this->context['link_target_id'] = $targetid;
4254  $this->context['link_target_type'] = $targettype;
4255  $result = $this->call_trigger('OBJECT_LINK_DELETE', $f_user);
4256  if ($result < 0) {
4257  $error++;
4258  }
4259  // End call triggers
4260  }
4261 
4262  if (!$error) {
4263  $sql = "DELETE FROM " . $this->db->prefix() . "element_element";
4264  $sql .= " WHERE";
4265  if ($rowid > 0) {
4266  $sql .= " rowid = " . ((int) $rowid);
4267  } else {
4268  if ($deletesource) {
4269  $sql .= " fk_source = " . ((int) $sourceid) . " AND sourcetype = '" . $this->db->escape($sourcetype) . "'";
4270  $sql .= " AND fk_target = " . ((int) $this->id) . " AND targettype = '" . $this->db->escape($this->element) . "'";
4271  } elseif ($deletetarget) {
4272  $sql .= " fk_target = " . ((int) $targetid) . " AND targettype = '" . $this->db->escape($targettype) . "'";
4273  $sql .= " AND fk_source = " . ((int) $this->id) . " AND sourcetype = '" . $this->db->escape($this->element) . "'";
4274  } else {
4275  $sql .= " (fk_source = " . ((int) $this->id) . " AND sourcetype = '" . $this->db->escape($this->element) . "')";
4276  $sql .= " OR";
4277  $sql .= " (fk_target = " . ((int) $this->id) . " AND targettype = '" . $this->db->escape($this->element) . "')";
4278  }
4279  }
4280 
4281  dol_syslog(get_class($this) . "::deleteObjectLinked", LOG_DEBUG);
4282  if (!$this->db->query($sql)) {
4283  $this->error = $this->db->lasterror();
4284  $this->errors[] = $this->error;
4285  $error++;
4286  }
4287  }
4288 
4289  if (!$error) {
4290  $this->db->commit();
4291  return 1;
4292  } else {
4293  $this->db->rollback();
4294  return 0;
4295  }
4296  }
4297 
4307  public static function getAllItemsLinkedByObjectID($fk_object_where, $field_select, $field_where, $table_element)
4308  {
4309  if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
4310  return -1;
4311  }
4312 
4313  global $db;
4314 
4315  $sql = "SELECT ".$field_select." FROM ".$db->prefix().$table_element." WHERE ".$field_where." = ".((int) $fk_object_where);
4316  $resql = $db->query($sql);
4317 
4318  $TRes = array();
4319  if (!empty($resql)) {
4320  while ($res = $db->fetch_object($resql)) {
4321  $TRes[] = $res->{$field_select};
4322  }
4323  }
4324 
4325  return $TRes;
4326  }
4327 
4336  public static function deleteAllItemsLinkedByObjectID($fk_object_where, $field_where, $table_element)
4337  {
4338  if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
4339  return -1;
4340  }
4341 
4342  global $db;
4343 
4344  $sql = "DELETE FROM ".$db->prefix().$table_element." WHERE ".$field_where." = ".((int) $fk_object_where);
4345  $resql = $db->query($sql);
4346 
4347  if (empty($resql)) {
4348  return 0;
4349  }
4350 
4351  return 1;
4352  }
4353 
4364  public function setStatut($status, $elementId = null, $elementType = '', $trigkey = '', $fieldstatus = 'fk_statut')
4365  {
4366  global $user, $langs, $conf;
4367 
4368  $savElementId = $elementId; // To be used later to know if we were using the method using the id of this or not.
4369 
4370  $elementId = (!empty($elementId) ? $elementId : $this->id);
4371  $elementTable = (!empty($elementType) ? $elementType : $this->table_element);
4372 
4373  $this->db->begin();
4374 
4375  if ($elementTable == 'facture_rec') {
4376  $fieldstatus = "suspended";
4377  }
4378  if ($elementTable == 'mailing') {
4379  $fieldstatus = "statut";
4380  }
4381  if ($elementTable == 'cronjob') {
4382  $fieldstatus = "status";
4383  }
4384  if ($elementTable == 'user') {
4385  $fieldstatus = "statut";
4386  }
4387  if ($elementTable == 'expensereport') {
4388  $fieldstatus = "fk_statut";
4389  }
4390  if ($elementTable == 'commande_fournisseur_dispatch') {
4391  $fieldstatus = "status";
4392  }
4393  if (isset($this->fields) && is_array($this->fields) && array_key_exists('status', $this->fields)) {
4394  $fieldstatus = 'status';
4395  }
4396 
4397  $sql = "UPDATE ".$this->db->prefix().$elementTable;
4398  $sql .= " SET ".$fieldstatus." = ".((int) $status);
4399  // If status = 1 = validated, update also fk_user_valid
4400  // TODO Replace the test on $elementTable by doing a test on existence of the field in $this->fields
4401  if ($status == 1 && in_array($elementTable, array('expensereport', 'inventory'))) {
4402  $sql .= ", fk_user_valid = ".((int) $user->id);
4403  }
4404  if ($status == 1 && in_array($elementTable, array('expensereport'))) {
4405  $sql .= ", date_valid = '".$this->db->idate(dol_now())."'";
4406  }
4407  if ($status == 1 && in_array($elementTable, array('inventory'))) {
4408  $sql .= ", date_validation = '".$this->db->idate(dol_now())."'";
4409  }
4410  $sql .= " WHERE rowid = ".((int) $elementId);
4411  $sql .= " AND ".$fieldstatus." <> ".((int) $status); // We avoid update if status already correct
4412 
4413  dol_syslog(get_class($this)."::setStatut", LOG_DEBUG);
4414  $resql = $this->db->query($sql);
4415  if ($resql) {
4416  $error = 0;
4417 
4418  $nb_rows_affected = $this->db->affected_rows($resql); // should be 1 or 0 if status was already correct
4419 
4420  if ($nb_rows_affected > 0) {
4421  if (empty($trigkey)) {
4422  // Try to guess trigkey (for backward compatibility, now we should have trigkey defined into the call of setStatus)
4423  if ($this->element == 'supplier_proposal' && $status == 2) {
4424  $trigkey = 'SUPPLIER_PROPOSAL_SIGN'; // 2 = SupplierProposal::STATUS_SIGNED. Can't use constant into this generic class
4425  }
4426  if ($this->element == 'supplier_proposal' && $status == 3) {
4427  $trigkey = 'SUPPLIER_PROPOSAL_REFUSE'; // 3 = SupplierProposal::STATUS_REFUSED. Can't use constant into this generic class
4428  }
4429  if ($this->element == 'supplier_proposal' && $status == 4) {
4430  $trigkey = 'SUPPLIER_PROPOSAL_CLOSE'; // 4 = SupplierProposal::STATUS_CLOSED. Can't use constant into this generic class
4431  }
4432  if ($this->element == 'fichinter' && $status == 3) {
4433  $trigkey = 'FICHINTER_CLASSIFY_DONE';
4434  }
4435  if ($this->element == 'fichinter' && $status == 2) {
4436  $trigkey = 'FICHINTER_CLASSIFY_BILLED';
4437  }
4438  if ($this->element == 'fichinter' && $status == 1) {
4439  $trigkey = 'FICHINTER_CLASSIFY_UNBILLED';
4440  }
4441  }
4442 
4443  if ($trigkey) {
4444  // Call trigger
4445  $result = $this->call_trigger($trigkey, $user);
4446  if ($result < 0) {
4447  $error++;
4448  }
4449  // End call triggers
4450  }
4451  } else {
4452  // The status was probably already good. We do nothing more, no triggers.
4453  }
4454 
4455  if (!$error) {
4456  $this->db->commit();
4457 
4458  if (empty($savElementId)) {
4459  // If the element we update is $this (so $elementId was provided as null)
4460  if ($fieldstatus == 'tosell') {
4461  $this->status = $status;
4462  } elseif ($fieldstatus == 'tobuy') {
4463  $this->status_buy = $status;
4464  } else {
4465  $this->statut = $status;
4466  $this->status = $status;
4467  }
4468  }
4469 
4470  return 1;
4471  } else {
4472  $this->db->rollback();
4473  dol_syslog(get_class($this)."::setStatut ".$this->error, LOG_ERR);
4474  return -1;
4475  }
4476  } else {
4477  $this->error = $this->db->lasterror();
4478  $this->db->rollback();
4479  return -1;
4480  }
4481  }
4482 
4483 
4491  public function getCanvas($id = 0, $ref = '')
4492  {
4493  global $conf;
4494 
4495  if (empty($id) && empty($ref)) {
4496  return 0;
4497  }
4498  if (!empty($conf->global->MAIN_DISABLE_CANVAS)) {
4499  return 0; // To increase speed. Not enabled by default.
4500  }
4501 
4502  // Clean parameters
4503  $ref = trim($ref);
4504 
4505  $sql = "SELECT rowid, canvas";
4506  $sql .= " FROM ".$this->db->prefix().$this->table_element;
4507  $sql .= " WHERE entity IN (".getEntity($this->element).")";
4508  if (!empty($id)) {
4509  $sql .= " AND rowid = ".((int) $id);
4510  }
4511  if (!empty($ref)) {
4512  $sql .= " AND ref = '".$this->db->escape($ref)."'";
4513  }
4514 
4515  $resql = $this->db->query($sql);
4516  if ($resql) {
4517  $obj = $this->db->fetch_object($resql);
4518  if ($obj) {
4519  $this->canvas = $obj->canvas;
4520  return 1;
4521  } else {
4522  return 0;
4523  }
4524  } else {
4525  dol_print_error($this->db);
4526  return -1;
4527  }
4528  }
4529 
4530 
4537  public function getSpecialCode($lineid)
4538  {
4539  $sql = "SELECT special_code FROM ".$this->db->prefix().$this->table_element_line;
4540  $sql .= " WHERE rowid = ".((int) $lineid);
4541  $resql = $this->db->query($sql);
4542  if ($resql) {
4543  $row = $this->db->fetch_row($resql);
4544  return $row[0];
4545  }
4546  }
4547 
4556  public function isObjectUsed($id = 0, $entity = 0)
4557  {
4558  global $langs;
4559 
4560  if (empty($id)) {
4561  $id = $this->id;
4562  }
4563 
4564  // Check parameters
4565  if (!isset($this->childtables) || !is_array($this->childtables) || count($this->childtables) == 0) {
4566  dol_print_error('Called isObjectUsed on a class with property this->childtables not defined');
4567  return -1;
4568  }
4569 
4570  $arraytoscan = $this->childtables;
4571  // For backward compatibility, we check if array is old format array('table1', 'table2', ...)
4572  $tmparray = array_keys($this->childtables);
4573  if (is_numeric($tmparray[0])) {
4574  $arraytoscan = array_flip($this->childtables);
4575  }
4576 
4577  // Test if child exists
4578  $haschild = 0;
4579  foreach ($arraytoscan as $table => $element) {
4580  //print $id.'-'.$table.'-'.$elementname.'<br>';
4581  // Check if element can be deleted
4582  $sql = "SELECT COUNT(*) as nb";
4583  $sql.= " FROM ".$this->db->prefix().$table." as c";
4584  if (!empty($element['parent']) && !empty($element['parentkey'])) {
4585  $sql.= ", ".$this->db->prefix().$element['parent']." as p";
4586  }
4587  $sql.= " WHERE c.".$this->fk_element." = ".((int) $id);
4588  if (!empty($element['parent']) && !empty($element['parentkey'])) {
4589  $sql.= " AND c.".$element['parentkey']." = p.rowid";
4590  }
4591  if (!empty($entity)) {
4592  if (!empty($element['parent']) && !empty($element['parentkey'])) {
4593  $sql.= " AND p.entity = ".((int) $entity);
4594  } else {
4595  $sql.= " AND c.entity = ".((int) $entity);
4596  }
4597  }
4598  $resql = $this->db->query($sql);
4599  if ($resql) {
4600  $obj = $this->db->fetch_object($resql);
4601  if ($obj->nb > 0) {
4602  $langs->load("errors");
4603  //print 'Found into table '.$table.', type '.$langs->transnoentitiesnoconv($elementname).', haschild='.$haschild;
4604  $haschild += $obj->nb;
4605  if (is_numeric($element)) { // very old usage array('table1', 'table2', ...)
4606  $this->errors[] = $langs->transnoentitiesnoconv("ErrorRecordHasAtLeastOneChildOfType", method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref, $table);
4607  } elseif (is_string($element)) { // old usage array('table1' => 'TranslateKey1', 'table2' => 'TranslateKey2', ...)
4608  $this->errors[] = $langs->transnoentitiesnoconv("ErrorRecordHasAtLeastOneChildOfType", method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref, $langs->transnoentitiesnoconv($element));
4609  } else { // new usage: $element['name']=Translation key
4610  $this->errors[] = $langs->transnoentitiesnoconv("ErrorRecordHasAtLeastOneChildOfType", method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref, $langs->transnoentitiesnoconv($element['name']));
4611  }
4612  break; // We found at least one, we stop here
4613  }
4614  } else {
4615  $this->errors[] = $this->db->lasterror();
4616  return -1;
4617  }
4618  }
4619  if ($haschild > 0) {
4620  $this->errors[] = "ErrorRecordHasChildren";
4621  return $haschild;
4622  } else {
4623  return 0;
4624  }
4625  }
4626 
4633  public function hasProductsOrServices($predefined = -1)
4634  {
4635  $nb = 0;
4636 
4637  foreach ($this->lines as $key => $val) {
4638  $qualified = 0;
4639  if ($predefined == -1) {
4640  $qualified = 1;
4641  }
4642  if ($predefined == 1 && $val->fk_product > 0) {
4643  $qualified = 1;
4644  }
4645  if ($predefined == 0 && $val->fk_product <= 0) {
4646  $qualified = 1;
4647  }
4648  if ($predefined == 2 && $val->fk_product > 0 && $val->product_type == 0) {
4649  $qualified = 1;
4650  }
4651  if ($predefined == 3 && $val->fk_product > 0 && $val->product_type == 1) {
4652  $qualified = 1;
4653  }
4654  if ($qualified) {
4655  $nb++;
4656  }
4657  }
4658  dol_syslog(get_class($this).'::hasProductsOrServices we found '.$nb.' qualified lines of products/servcies');
4659  return $nb;
4660  }
4661 
4667  public function getTotalDiscount()
4668  {
4669  if (!empty($this->table_element_line) ) {
4670  $total_discount = 0.00;
4671 
4672  $sql = "SELECT subprice as pu_ht, qty, remise_percent, total_ht";
4673  $sql .= " FROM ".$this->db->prefix().$this->table_element_line;
4674  $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
4675 
4676  dol_syslog(get_class($this).'::getTotalDiscount', LOG_DEBUG);
4677  $resql = $this->db->query($sql);
4678  if ($resql) {
4679  $num = $this->db->num_rows($resql);
4680  $i = 0;
4681  while ($i < $num) {
4682  $obj = $this->db->fetch_object($resql);
4683 
4684  $pu_ht = $obj->pu_ht;
4685  $qty = $obj->qty;
4686  $total_ht = $obj->total_ht;
4687 
4688  $total_discount_line = floatval(price2num(($pu_ht * $qty) - $total_ht, 'MT'));
4689  $total_discount += $total_discount_line;
4690 
4691  $i++;
4692  }
4693  }
4694 
4695  //print $total_discount; exit;
4696  return price2num($total_discount);
4697  }
4698 
4699  return null;
4700  }
4701 
4702 
4709  public function getTotalWeightVolume()
4710  {
4711  $totalWeight = 0;
4712  $totalVolume = 0;
4713  // defined for shipment only
4714  $totalOrdered = '';
4715  // defined for shipment only
4716  $totalToShip = '';
4717 
4718  foreach ($this->lines as $line) {
4719  if (isset($line->qty_asked)) {
4720  if (empty($totalOrdered)) {
4721  $totalOrdered = 0; // Avoid warning because $totalOrdered is ''
4722  }
4723  $totalOrdered += $line->qty_asked; // defined for shipment only
4724  }
4725  if (isset($line->qty_shipped)) {
4726  if (empty($totalToShip)) {
4727  $totalToShip = 0; // Avoid warning because $totalToShip is ''
4728  }
4729  $totalToShip += $line->qty_shipped; // defined for shipment only
4730  } elseif ($line->element == 'commandefournisseurdispatch' && isset($line->qty)) {
4731  if (empty($totalToShip)) {
4732  $totalToShip = 0;
4733  }
4734  $totalToShip += $line->qty; // defined for reception only
4735  }
4736 
4737  // Define qty, weight, volume, weight_units, volume_units
4738  if ($this->element == 'shipping') {
4739  // for shipments
4740  $qty = $line->qty_shipped ? $line->qty_shipped : 0;
4741  } else {
4742  $qty = $line->qty ? $line->qty : 0;
4743  }
4744 
4745  $weight = !empty($line->weight) ? $line->weight : 0;
4746  ($weight == 0 && !empty($line->product->weight)) ? $weight = $line->product->weight : 0;
4747  $volume = !empty($line->volume) ? $line->volume : 0;
4748  ($volume == 0 && !empty($line->product->volume)) ? $volume = $line->product->volume : 0;
4749 
4750  $weight_units = !empty($line->weight_units) ? $line->weight_units : 0;
4751  ($weight_units == 0 && !empty($line->product->weight_units)) ? $weight_units = $line->product->weight_units : 0;
4752  $volume_units = !empty($line->volume_units) ? $line->volume_units : 0;
4753  ($volume_units == 0 && !empty($line->product->volume_units)) ? $volume_units = $line->product->volume_units : 0;
4754 
4755  $weightUnit = 0;
4756  $volumeUnit = 0;
4757  if (!empty($weight_units)) {
4758  $weightUnit = $weight_units;
4759  }
4760  if (!empty($volume_units)) {
4761  $volumeUnit = $volume_units;
4762  }
4763 
4764  if (empty($totalWeight)) {
4765  $totalWeight = 0; // Avoid warning because $totalWeight is ''
4766  }
4767  if (empty($totalVolume)) {
4768  $totalVolume = 0; // Avoid warning because $totalVolume is ''
4769  }
4770 
4771  //var_dump($line->volume_units);
4772  if ($weight_units < 50) { // < 50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch)
4773  $trueWeightUnit = pow(10, $weightUnit);
4774  $totalWeight += $weight * $qty * $trueWeightUnit;
4775  } else {
4776  if ($weight_units == 99) {
4777  // conversion 1 Pound = 0.45359237 KG
4778  $trueWeightUnit = 0.45359237;
4779  $totalWeight += $weight * $qty * $trueWeightUnit;
4780  } elseif ($weight_units == 98) {
4781  // conversion 1 Ounce = 0.0283495 KG
4782  $trueWeightUnit = 0.0283495;
4783  $totalWeight += $weight * $qty * $trueWeightUnit;
4784  } else {
4785  $totalWeight += $weight * $qty; // This may be wrong if we mix different units
4786  }
4787  }
4788  if ($volume_units < 50) { // >50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch)
4789  //print $line->volume."x".$line->volume_units."x".($line->volume_units < 50)."x".$volumeUnit;
4790  $trueVolumeUnit = pow(10, $volumeUnit);
4791  //print $line->volume;
4792  $totalVolume += $volume * $qty * $trueVolumeUnit;
4793  } else {
4794  $totalVolume += $volume * $qty; // This may be wrong if we mix different units
4795  }
4796  }
4797 
4798  return array('weight'=>$totalWeight, 'volume'=>$totalVolume, 'ordered'=>$totalOrdered, 'toship'=>$totalToShip);
4799  }
4800 
4801 
4807  public function setExtraParameters()
4808  {
4809  $this->db->begin();
4810 
4811  $extraparams = (!empty($this->extraparams) ? json_encode($this->extraparams) : null);
4812 
4813  $sql = "UPDATE ".$this->db->prefix().$this->table_element;
4814  $sql .= " SET extraparams = ".(!empty($extraparams) ? "'".$this->db->escape($extraparams)."'" : "null");
4815  $sql .= " WHERE rowid = ".((int) $this->id);
4816 
4817  dol_syslog(get_class($this)."::setExtraParameters", LOG_DEBUG);
4818  $resql = $this->db->query($sql);
4819  if (!$resql) {
4820  $this->error = $this->db->lasterror();
4821  $this->db->rollback();
4822  return -1;
4823  } else {
4824  $this->db->commit();
4825  return 1;
4826  }
4827  }
4828 
4829 
4830  // --------------------
4831  // TODO: All functions here must be redesigned and moved as they are not business functions but output functions
4832  // --------------------
4833 
4834  /* This is to show add lines */
4835 
4845  public function formAddObjectLine($dateSelector, $seller, $buyer, $defaulttpldir = '/core/tpl')
4846  {
4847  global $conf, $user, $langs, $object, $hookmanager, $extrafields;
4848  global $form;
4849 
4850  // Line extrafield
4851  if (!is_object($extrafields)) {
4852  require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
4853  $extrafields = new ExtraFields($this->db);
4854  }
4855  $extrafields->fetch_name_optionals_label($this->table_element_line);
4856 
4857  // Output template part (modules that overwrite templates must declare this into descriptor)
4858  // Use global variables + $dateSelector + $seller and $buyer
4859  // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook 'formAddObjectLine'.
4860  $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
4861  foreach ($dirtpls as $module => $reldir) {
4862  if (!empty($module)) {
4863  $tpl = dol_buildpath($reldir.'/objectline_create.tpl.php');
4864  } else {
4865  $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_create.tpl.php';
4866  }
4867 
4868  if (empty($conf->file->strict_mode)) {
4869  $res = @include $tpl;
4870  } else {
4871  $res = include $tpl; // for debug
4872  }
4873  if ($res) {
4874  break;
4875  }
4876  }
4877  }
4878 
4879 
4880 
4881  /* This is to show array of line of details */
4882 
4883 
4898  public function printObjectLines($action, $seller, $buyer, $selected = 0, $dateSelector = 0, $defaulttpldir = '/core/tpl')
4899  {
4900  global $conf, $hookmanager, $langs, $user, $form, $extrafields, $object;
4901  // TODO We should not use global var for this
4902  global $inputalsopricewithtax, $usemargins, $disableedit, $disablemove, $disableremove, $outputalsopricetotalwithtax;
4903 
4904  // Define usemargins
4905  $usemargins = 0;
4906  if (!empty($conf->margin->enabled) && !empty($this->element) && in_array($this->element, array('facture', 'facturerec', 'propal', 'commande'))) {
4907  $usemargins = 1;
4908  }
4909 
4910  $num = count($this->lines);
4911 
4912  // Line extrafield
4913  if (!is_object($extrafields)) {
4914  require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
4915  $extrafields = new ExtraFields($this->db);
4916  }
4917  $extrafields->fetch_name_optionals_label($this->table_element_line);
4918 
4919  $parameters = array('num'=>$num, 'dateSelector'=>$dateSelector, 'seller'=>$seller, 'buyer'=>$buyer, 'selected'=>$selected, 'table_element_line'=>$this->table_element_line);
4920  $reshook = $hookmanager->executeHooks('printObjectLineTitle', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
4921  if (empty($reshook)) {
4922  // Output template part (modules that overwrite templates must declare this into descriptor)
4923  // Use global variables + $dateSelector + $seller and $buyer
4924  // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook.
4925  $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
4926  foreach ($dirtpls as $module => $reldir) {
4927  if (!empty($module)) {
4928  $tpl = dol_buildpath($reldir.'/objectline_title.tpl.php');
4929  } else {
4930  $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_title.tpl.php';
4931  }
4932  if (empty($conf->file->strict_mode)) {
4933  $res = @include $tpl;
4934  } else {
4935  $res = include $tpl; // for debug
4936  }
4937  if ($res) {
4938  break;
4939  }
4940  }
4941  }
4942 
4943  $i = 0;
4944 
4945  print "<!-- begin printObjectLines() --><tbody>\n";
4946  foreach ($this->lines as $line) {
4947  //Line extrafield
4948  $line->fetch_optionals();
4949 
4950  //if (is_object($hookmanager) && (($line->product_type == 9 && ! empty($line->special_code)) || ! empty($line->fk_parent_line)))
4951  if (is_object($hookmanager)) { // Old code is commented on preceding line.
4952  if (empty($line->fk_parent_line)) {
4953  $parameters = array('line'=>$line, 'num'=>$num, 'i'=>$i, 'dateSelector'=>$dateSelector, 'seller'=>$seller, 'buyer'=>$buyer, 'selected'=>$selected, 'table_element_line'=>$line->table_element);
4954  $reshook = $hookmanager->executeHooks('printObjectLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
4955  } else {
4956  $parameters = array('line'=>$line, 'num'=>$num, 'i'=>$i, 'dateSelector'=>$dateSelector, 'seller'=>$seller, 'buyer'=>$buyer, 'selected'=>$selected, 'table_element_line'=>$line->table_element, 'fk_parent_line'=>$line->fk_parent_line);
4957  $reshook = $hookmanager->executeHooks('printObjectSubLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
4958  }
4959  }
4960  if (empty($reshook)) {
4961  $this->printObjectLine($action, $line, '', $num, $i, $dateSelector, $seller, $buyer, $selected, $extrafields, $defaulttpldir);
4962  }
4963 
4964  $i++;
4965  }
4966  print "</tbody><!-- end printObjectLines() -->\n";
4967  }
4968 
4986  public function printObjectLine($action, $line, $var, $num, $i, $dateSelector, $seller, $buyer, $selected = 0, $extrafields = null, $defaulttpldir = '/core/tpl')
4987  {
4988  global $conf, $langs, $user, $object, $hookmanager;
4989  global $form;
4990  global $object_rights, $disableedit, $disablemove, $disableremove; // TODO We should not use global var for this !
4991 
4992  $object_rights = $this->getRights();
4993 
4994  $element = $this->element;
4995 
4996  $text = '';
4997  $description = '';
4998 
4999  // Line in view mode
5000  if ($action != 'editline' || $selected != $line->id) {
5001  // Product
5002  if ($line->fk_product > 0) {
5003  $product_static = new Product($this->db);
5004  $product_static->fetch($line->fk_product);
5005 
5006  $product_static->ref = $line->ref; //can change ref in hook
5007  $product_static->label = !empty($line->label) ? $line->label : ""; //can change label in hook
5008 
5009  $text = $product_static->getNomUrl(1);
5010 
5011  // Define output language and label
5012  if (!empty($conf->global->MAIN_MULTILANGS)) {
5013  if (property_exists($this, 'socid') && !is_object($this->thirdparty)) {
5014  dol_print_error('', 'Error: Method printObjectLine was called on an object and object->fetch_thirdparty was not done before');
5015  return;
5016  }
5017 
5018  $prod = new Product($this->db);
5019  $prod->fetch($line->fk_product);
5020 
5021  $outputlangs = $langs;
5022  $newlang = '';
5023  if (empty($newlang) && GETPOST('lang_id', 'aZ09')) {
5024  $newlang = GETPOST('lang_id', 'aZ09');
5025  }
5026  if (!empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE) && empty($newlang) && is_object($this->thirdparty)) {
5027  $newlang = $this->thirdparty->default_lang; // To use language of customer
5028  }
5029  if (!empty($newlang)) {
5030  $outputlangs = new Translate("", $conf);
5031  $outputlangs->setDefaultLang($newlang);
5032  }
5033 
5034  $label = (!empty($prod->multilangs[$outputlangs->defaultlang]["label"])) ? $prod->multilangs[$outputlangs->defaultlang]["label"] : $line->product_label;
5035  } else {
5036  $label = $line->product_label;
5037  }
5038 
5039  $text .= ' - '.(!empty($line->label) ? $line->label : $label);
5040  $description .= (!empty($conf->global->PRODUIT_DESC_IN_FORM) ? '' : (!empty($line->description) ? dol_htmlentitiesbr($line->description) : '')); // Description is what to show on popup. We shown nothing if already into desc.
5041  }
5042 
5043  $line->pu_ttc = price2num((!empty($line->subprice) ? $line->subprice : 0) * (1 + ((!empty($line->tva_tx) ? $line->tva_tx : 0) / 100)), 'MU');
5044 
5045  // Output template part (modules that overwrite templates must declare this into descriptor)
5046  // Use global variables + $dateSelector + $seller and $buyer
5047  // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook printObjectLine and printObjectSubLine.
5048  $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
5049  foreach ($dirtpls as $module => $reldir) {
5050  if (!empty($module)) {
5051  $tpl = dol_buildpath($reldir.'/objectline_view.tpl.php');
5052  } else {
5053  $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_view.tpl.php';
5054  }
5055 
5056  if (empty($conf->file->strict_mode)) {
5057  $res = @include $tpl;
5058  } else {
5059  $res = include $tpl; // for debug
5060  }
5061  if ($res) {
5062  break;
5063  }
5064  }
5065  }
5066 
5067  // Line in update mode
5068  if ($this->statut == 0 && $action == 'editline' && $selected == $line->id) {
5069  $label = (!empty($line->label) ? $line->label : (($line->fk_product > 0) ? $line->product_label : ''));
5070 
5071  $line->pu_ttc = price2num($line->subprice * (1 + ($line->tva_tx / 100)), 'MU');
5072 
5073  // Output template part (modules that overwrite templates must declare this into descriptor)
5074  // Use global variables + $dateSelector + $seller and $buyer
5075  // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook printObjectLine and printObjectSubLine.
5076  $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
5077  foreach ($dirtpls as $module => $reldir) {
5078  if (!empty($module)) {
5079  $tpl = dol_buildpath($reldir.'/objectline_edit.tpl.php');
5080  } else {
5081  $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_edit.tpl.php';
5082  }
5083 
5084  if (empty($conf->file->strict_mode)) {
5085  $res = @include $tpl;
5086  } else {
5087  $res = include $tpl; // for debug
5088  }
5089  if ($res) {
5090  break;
5091  }
5092  }
5093  }
5094  }
5095 
5096 
5097  /* This is to show array of line of details of source object */
5098 
5099 
5110  public function printOriginLinesList($restrictlist = '', $selectedLines = array())
5111  {
5112  global $langs, $hookmanager, $conf, $form, $action;
5113 
5114  print '<tr class="liste_titre">';
5115  print '<td class="linecolref">'.$langs->trans('Ref').'</td>';
5116  print '<td class="linecoldescription">'.$langs->trans('Description').'</td>';
5117  print '<td class="linecolvat right">'.$langs->trans('VATRate').'</td>';
5118  print '<td class="linecoluht right">'.$langs->trans('PriceUHT').'</td>';
5119  if (!empty($conf->multicurrency->enabled)) {
5120  print '<td class="linecoluht_currency right">'.$langs->trans('PriceUHTCurrency').'</td>';
5121  }
5122  print '<td class="linecolqty right">'.$langs->trans('Qty').'</td>';
5123  if (!empty($conf->global->PRODUCT_USE_UNITS)) {
5124  print '<td class="linecoluseunit left">'.$langs->trans('Unit').'</td>';
5125  }
5126  print '<td class="linecoldiscount right">'.$langs->trans('ReductionShort').'</td>';
5127  print '<td class="linecolht right">'.$langs->trans('TotalHT').'</td>';
5128  print '<td class="center">'.$form->showCheckAddButtons('checkforselect', 1).'</td>';
5129  print '</tr>';
5130  $i = 0;
5131 
5132  if (!empty($this->lines)) {
5133  foreach ($this->lines as $line) {
5134  $reshook = 0;
5135  //if (is_object($hookmanager) && (($line->product_type == 9 && !empty($line->special_code)) || !empty($line->fk_parent_line))) {
5136  if (is_object($hookmanager)) { // Old code is commented on preceding line.
5137  $parameters = array('line'=>$line, 'i'=>$i, 'restrictlist'=>$restrictlist, 'selectedLines'=> $selectedLines);
5138  if (!empty($line->fk_parent_line)) { $parameters['fk_parent_line'] = $line->fk_parent_line; }
5139  $reshook = $hookmanager->executeHooks('printOriginObjectLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
5140  }
5141  if (empty($reshook)) {
5142  $this->printOriginLine($line, '', $restrictlist, '/core/tpl', $selectedLines);
5143  }
5144 
5145  $i++;
5146  }
5147  }
5148  }
5149 
5163  public function printOriginLine($line, $var, $restrictlist = '', $defaulttpldir = '/core/tpl', $selectedLines = array())
5164  {
5165  global $langs, $conf;
5166 
5167  //var_dump($line);
5168  if (!empty($line->date_start)) {
5169  $date_start = $line->date_start;
5170  } else {
5171  $date_start = $line->date_debut_prevue;
5172  if ($line->date_debut_reel) {
5173  $date_start = $line->date_debut_reel;
5174  }
5175  }
5176  if (!empty($line->date_end)) {
5177  $date_end = $line->date_end;
5178  } else {
5179  $date_end = $line->date_fin_prevue;
5180  if ($line->date_fin_reel) {
5181  $date_end = $line->date_fin_reel;
5182  }
5183  }
5184 
5185  $this->tpl['id'] = $line->id;
5186 
5187  $this->tpl['label'] = '';
5188  if (!empty($line->fk_parent_line)) {
5189  $this->tpl['label'] .= img_picto('', 'rightarrow');
5190  }
5191 
5192  if (($line->info_bits & 2) == 2) { // TODO Not sure this is used for source object
5193  $discount = new DiscountAbsolute($this->db);
5194  $discount->fk_soc = $this->socid;
5195  $this->tpl['label'] .= $discount->getNomUrl(0, 'discount');
5196  } elseif (!empty($line->fk_product)) {
5197  $productstatic = new Product($this->db);
5198  $productstatic->id = $line->fk_product;
5199  $productstatic->ref = $line->ref;
5200  $productstatic->type = $line->fk_product_type;
5201  if (empty($productstatic->ref)) {
5202  $line->fetch_product();
5203  $productstatic = $line->product;
5204  }
5205 
5206  $this->tpl['label'] .= $productstatic->getNomUrl(1);
5207  $this->tpl['label'] .= ' - '.(!empty($line->label) ? $line->label : $line->product_label);
5208  // Dates
5209  if ($line->product_type == 1 && ($date_start || $date_end)) {
5210  $this->tpl['label'] .= get_date_range($date_start, $date_end);
5211  }
5212  } else {
5213  $this->tpl['label'] .= ($line->product_type == -1 ? '&nbsp;' : ($line->product_type == 1 ? img_object($langs->trans(''), 'service') : img_object($langs->trans(''), 'product')));
5214  if (!empty($line->desc)) {
5215  $this->tpl['label'] .= $line->desc;
5216  } else {
5217  $this->tpl['label'] .= ($line->label ? '&nbsp;'.$line->label : '');
5218  }
5219 
5220  // Dates
5221  if ($line->product_type == 1 && ($date_start || $date_end)) {
5222  $this->tpl['label'] .= get_date_range($date_start, $date_end);
5223  }
5224  }
5225 
5226  if (!empty($line->desc)) {
5227  if ($line->desc == '(CREDIT_NOTE)') { // TODO Not sure this is used for source object
5228  $discount = new DiscountAbsolute($this->db);
5229  $discount->fetch($line->fk_remise_except);
5230  $this->tpl['description'] = $langs->transnoentities("DiscountFromCreditNote", $discount->getNomUrl(0));
5231  } elseif ($line->desc == '(DEPOSIT)') { // TODO Not sure this is used for source object
5232  $discount = new DiscountAbsolute($this->db);
5233  $discount->fetch($line->fk_remise_except);
5234  $this->tpl['description'] = $langs->transnoentities("DiscountFromDeposit", $discount->getNomUrl(0));
5235  } elseif ($line->desc == '(EXCESS RECEIVED)') {
5236  $discount = new DiscountAbsolute($this->db);
5237  $discount->fetch($line->fk_remise_except);
5238  $this->tpl['description'] = $langs->transnoentities("DiscountFromExcessReceived", $discount->getNomUrl(0));
5239  } elseif ($line->desc == '(EXCESS PAID)') {
5240  $discount = new DiscountAbsolute($this->db);
5241  $discount->fetch($line->fk_remise_except);
5242  $this->tpl['description'] = $langs->transnoentities("DiscountFromExcessPaid", $discount->getNomUrl(0));
5243  } else {
5244  $this->tpl['description'] = dol_trunc($line->desc, 60);
5245  }
5246  } else {
5247  $this->tpl['description'] = '&nbsp;';
5248  }
5249 
5250  // VAT Rate
5251  $this->tpl['vat_rate'] = vatrate($line->tva_tx, true);
5252  $this->tpl['vat_rate'] .= (($line->info_bits & 1) == 1) ? '*' : '';
5253  if (!empty($line->vat_src_code) && !preg_match('/\(/', $this->tpl['vat_rate'])) {
5254  $this->tpl['vat_rate'] .= ' ('.$line->vat_src_code.')';
5255  }
5256 
5257  $this->tpl['price'] = price($line->subprice);
5258  $this->tpl['total_ht'] = price($line->total_ht);
5259  $this->tpl['multicurrency_price'] = price($line->multicurrency_subprice);
5260  $this->tpl['qty'] = (($line->info_bits & 2) != 2) ? $line->qty : '&nbsp;';
5261  if (!empty($conf->global->PRODUCT_USE_UNITS)) {
5262  $this->tpl['unit'] = $langs->transnoentities($line->getLabelOfUnit('long'));
5263  }
5264  $this->tpl['remise_percent'] = (($line->info_bits & 2) != 2) ? vatrate($line->remise_percent, true) : '&nbsp;';
5265 
5266  // Is the line strike or not
5267  $this->tpl['strike'] = 0;
5268  if ($restrictlist == 'services' && $line->product_type != Product::TYPE_SERVICE) {
5269  $this->tpl['strike'] = 1;
5270  }
5271 
5272  // Output template part (modules that overwrite templates must declare this into descriptor)
5273  // Use global variables + $dateSelector + $seller and $buyer
5274  $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
5275  foreach ($dirtpls as $module => $reldir) {
5276  if (!empty($module)) {
5277  $tpl = dol_buildpath($reldir.'/originproductline.tpl.php');
5278  } else {
5279  $tpl = DOL_DOCUMENT_ROOT.$reldir.'/originproductline.tpl.php';
5280  }
5281 
5282  if (empty($conf->file->strict_mode)) {
5283  $res = @include $tpl;
5284  } else {
5285  $res = include $tpl; // for debug
5286  }
5287  if ($res) {
5288  break;
5289  }
5290  }
5291  }
5292 
5293 
5294  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5305  public function add_element_resource($resource_id, $resource_type, $busy = 0, $mandatory = 0)
5306  {
5307  // phpcs:enable
5308  $this->db->begin();
5309 
5310  $sql = "INSERT INTO ".$this->db->prefix()."element_resources (";
5311  $sql .= "resource_id";
5312  $sql .= ", resource_type";
5313  $sql .= ", element_id";
5314  $sql .= ", element_type";
5315  $sql .= ", busy";
5316  $sql .= ", mandatory";
5317  $sql .= ") VALUES (";
5318  $sql .= $resource_id;
5319  $sql .= ", '".$this->db->escape($resource_type)."'";
5320  $sql .= ", '".$this->db->escape($this->id)."'";
5321  $sql .= ", '".$this->db->escape($this->element)."'";
5322  $sql .= ", '".$this->db->escape($busy)."'";
5323  $sql .= ", '".$this->db->escape($mandatory)."'";
5324  $sql .= ")";
5325 
5326  dol_syslog(get_class($this)."::add_element_resource", LOG_DEBUG);
5327  if ($this->db->query($sql)) {
5328  $this->db->commit();
5329  return 1;
5330  } else {
5331  $this->error = $this->db->lasterror();
5332  $this->db->rollback();
5333  return 0;
5334  }
5335  }
5336 
5337  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5346  public function delete_resource($rowid, $element, $notrigger = 0)
5347  {
5348  // phpcs:enable
5349  global $user;
5350 
5351  $this->db->begin();
5352 
5353  $sql = "DELETE FROM ".$this->db->prefix()."element_resources";
5354  $sql .= " WHERE rowid = ".((int) $rowid);
5355 
5356  dol_syslog(get_class($this)."::delete_resource", LOG_DEBUG);
5357 
5358  $resql = $this->db->query($sql);
5359  if (!$resql) {
5360  $this->error = $this->db->lasterror();
5361  $this->db->rollback();
5362  return -1;
5363  } else {
5364  if (!$notrigger) {
5365  $result = $this->call_trigger(strtoupper($element).'_DELETE_RESOURCE', $user);
5366  if ($result < 0) {
5367  $this->db->rollback();
5368  return -1;
5369  }
5370  }
5371  $this->db->commit();
5372  return 1;
5373  }
5374  }
5375 
5376 
5382  public function __clone()
5383  {
5384  // Force a copy of this->lines, otherwise it will point to same object.
5385  if (isset($this->lines) && is_array($this->lines)) {
5386  $nboflines = count($this->lines);
5387  for ($i = 0; $i < $nboflines; $i++) {
5388  $this->lines[$i] = clone $this->lines[$i];
5389  }
5390  }
5391  }
5392 
5406  protected function commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams = null)
5407  {
5408  global $conf, $langs, $user, $hookmanager, $action;
5409 
5410  $srctemplatepath = '';
5411 
5412  $parameters = array('modelspath'=>$modelspath, 'modele'=>$modele, 'outputlangs'=>$outputlangs, 'hidedetails'=>$hidedetails, 'hidedesc'=>$hidedesc, 'hideref'=>$hideref, 'moreparams'=>$moreparams);
5413  $reshook = $hookmanager->executeHooks('commonGenerateDocument', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
5414 
5415  if (empty($reshook)) {
5416  dol_syslog("commonGenerateDocument modele=".$modele." outputlangs->defaultlang=".(is_object($outputlangs) ? $outputlangs->defaultlang : 'null'));
5417 
5418  if (empty($modele)) {
5419  $this->error = 'BadValueForParameterModele';
5420  return -1;
5421  }
5422 
5423  // Increase limit for PDF build
5424  $err = error_reporting();
5425  error_reporting(0);
5426  @set_time_limit(120);
5427  error_reporting($err);
5428 
5429  // If selected model is a filename template (then $modele="modelname" or "modelname:filename")
5430  $tmp = explode(':', $modele, 2);
5431  if (!empty($tmp[1])) {
5432  $modele = $tmp[0];
5433  $srctemplatepath = $tmp[1];
5434  }
5435 
5436  // Search template files
5437  $file = '';
5438  $classname = '';
5439  $filefound = '';
5440  $dirmodels = array('/');
5441  if (is_array($conf->modules_parts['models'])) {
5442  $dirmodels = array_merge($dirmodels, $conf->modules_parts['models']);
5443  }
5444  foreach ($dirmodels as $reldir) {
5445  foreach (array('doc', 'pdf') as $prefix) {
5446  if (in_array(get_class($this), array('Adherent'))) {
5447  // Member module use prefix_modele.class.php
5448  $file = $prefix."_".$modele.".class.php";
5449  } else {
5450  // Other module use prefix_modele.modules.php
5451  $file = $prefix."_".$modele.".modules.php";
5452  }
5453 
5454  // On verifie l'emplacement du modele
5455  $file = dol_buildpath($reldir.$modelspath.$file, 0);
5456  if (file_exists($file)) {
5457  $filefound = $file;
5458  $classname = $prefix.'_'.$modele;
5459  break;
5460  }
5461  }
5462  if ($filefound) {
5463  break;
5464  }
5465  }
5466 
5467  // If generator was found
5468  if ($filefound) {
5469  global $db; // Required to solve a conception default making an include of code using $db instead of $this->db just after.
5470 
5471  require_once $file;
5472 
5473  $obj = new $classname($this->db);
5474 
5475  // If generator is ODT, we must have srctemplatepath defined, if not we set it.
5476  if ($obj->type == 'odt' && empty($srctemplatepath)) {
5477  $varfortemplatedir = $obj->scandir;
5478  if ($varfortemplatedir && !empty($conf->global->$varfortemplatedir)) {
5479  $dirtoscan = $conf->global->$varfortemplatedir;
5480 
5481  $listoffiles = array();
5482 
5483  // Now we add first model found in directories scanned
5484  $listofdir = explode(',', $dirtoscan);
5485  foreach ($listofdir as $key => $tmpdir) {
5486  $tmpdir = trim($tmpdir);
5487  $tmpdir = preg_replace('/DOL_DATA_ROOT/', DOL_DATA_ROOT, $tmpdir);
5488  if (!$tmpdir) {
5489  unset($listofdir[$key]);
5490  continue;
5491  }
5492  if (is_dir($tmpdir)) {
5493  $tmpfiles = dol_dir_list($tmpdir, 'files', 0, '\.od(s|t)$', '', 'name', SORT_ASC, 0);
5494  if (count($tmpfiles)) {
5495  $listoffiles = array_merge($listoffiles, $tmpfiles);
5496  }
5497  }
5498  }
5499 
5500  if (count($listoffiles)) {
5501  foreach ($listoffiles as $record) {
5502  $srctemplatepath = $record['fullname'];
5503  break;
5504  }
5505  }
5506  }
5507 
5508  if (empty($srctemplatepath)) {
5509  $this->error = 'ErrorGenerationAskedForOdtTemplateWithSrcFileNotDefined';
5510  return -1;
5511  }
5512  }
5513 
5514  if ($obj->type == 'odt' && !empty($srctemplatepath)) {
5515  if (!dol_is_file($srctemplatepath)) {
5516  dol_syslog("Failed to locate template file ".$srctemplatepath, LOG_WARNING);
5517  $this->error = 'ErrorGenerationAskedForOdtTemplateWithSrcFileNotFound';
5518  return -1;
5519  }
5520  }
5521 
5522  // We save charset_output to restore it because write_file can change it if needed for
5523  // output format that does not support UTF8.
5524  $sav_charset_output = empty($outputlangs->charset_output) ? '' : $outputlangs->charset_output;
5525 
5526  if (in_array(get_class($this), array('Adherent'))) {
5527  $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, 'member', 1, 'tmp_cards', $moreparams);
5528  } else {
5529  $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, $hidedetails, $hidedesc, $hideref, $moreparams);
5530  }
5531  // After call of write_file $obj->result['fullpath'] is set with generated file. It will be used to update the ECM database index.
5532 
5533  if ($resultwritefile > 0) {
5534  $outputlangs->charset_output = $sav_charset_output;
5535 
5536  // We delete old preview
5537  require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
5538  dol_delete_preview($this);
5539 
5540  // Index file in database
5541  if (!empty($obj->result['fullpath'])) {
5542  $destfull = $obj->result['fullpath'];
5543 
5544  // Update the last_main_doc field into main object (if document generator has property ->update_main_doc_field set)
5545  $update_main_doc_field = 0;
5546  if (!empty($obj->update_main_doc_field)) {
5547  $update_main_doc_field = 1;
5548  }
5549 
5550  $this->indexFile($destfull, $update_main_doc_field);
5551  } else {
5552  dol_syslog('Method ->write_file was called on object '.get_class($obj).' and return a success but the return array ->result["fullpath"] was not set.', LOG_WARNING);
5553  }
5554 
5555  // Success in building document. We build meta file.
5556  dol_meta_create($this);
5557 
5558  return 1;
5559  } else {
5560  $outputlangs->charset_output = $sav_charset_output;
5561  $this->error = $obj->error;
5562  $this->errors = $obj->errors;
5563  dol_syslog("Error generating document for ".__CLASS__.". Error: ".$obj->error, LOG_ERR);
5564  return -1;
5565  }
5566  } else {
5567  if (!$filefound) {
5568  $this->error = $langs->trans("Error").' Failed to load doc generator with modelpaths='.$modelspath.' - modele='.$modele;
5569  $this->errors[] = $this->error;
5570  dol_syslog($this->error, LOG_ERR);
5571  } else {
5572  $this->error = $langs->trans("Error")." ".$langs->trans("ErrorFileDoesNotExists", $filefound);
5573  $this->errors[] = $this->error;
5574  dol_syslog($this->error, LOG_ERR);
5575  }
5576  return -1;
5577  }
5578  } else {
5579  return $reshook;
5580  }
5581  }
5582 
5592  public function indexFile($destfull, $update_main_doc_field)
5593  {
5594  global $conf, $user;
5595 
5596  $upload_dir = dirname($destfull);
5597  $destfile = basename($destfull);
5598  $rel_dir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $upload_dir);
5599 
5600  if (!preg_match('/[\\/]temp[\\/]|[\\/]thumbs|\.meta$/', $rel_dir)) { // If not a tmp dir
5601  $filename = basename($destfile);
5602  $rel_dir = preg_replace('/[\\/]$/', '', $rel_dir);
5603  $rel_dir = preg_replace('/^[\\/]/', '', $rel_dir);
5604 
5605  include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
5606  $ecmfile = new EcmFiles($this->db);
5607  $result = $ecmfile->fetch(0, '', ($rel_dir ? $rel_dir.'/' : '').$filename);
5608 
5609  // Set the public "share" key
5610  $setsharekey = false;
5611  if ($this->element == 'propal' || $this->element == 'proposal') {
5612  if (!isset($conf->global->PROPOSAL_ALLOW_ONLINESIGN) || !empty($conf->global->PROPOSAL_ALLOW_ONLINESIGN)) {
5613  $setsharekey = true; // feature to make online signature is not set or set to on (default)
5614  }
5615  if (!empty($conf->global->PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD)) {
5616  $setsharekey = true;
5617  }
5618  }
5619  if ($this->element == 'commande' && !empty($conf->global->ORDER_ALLOW_EXTERNAL_DOWNLOAD)) {
5620  $setsharekey = true;
5621  }
5622  if ($this->element == 'facture' && !empty($conf->global->INVOICE_ALLOW_EXTERNAL_DOWNLOAD)) {
5623  $setsharekey = true;
5624  }
5625  if ($this->element == 'bank_account' && !empty($conf->global->BANK_ACCOUNT_ALLOW_EXTERNAL_DOWNLOAD)) {
5626  $setsharekey = true;
5627  }
5628  if ($this->element == 'contrat' && !empty($conf->global->CONTRACT_ALLOW_EXTERNAL_DOWNLOAD)) {
5629  $setsharekey = true;
5630  }
5631  if ($this->element == 'supplier_proposal' && !empty($conf->global->SUPPLIER_PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD)) {
5632  $setsharekey = true;
5633  }
5634 
5635  if ($setsharekey) {
5636  if (empty($ecmfile->share)) { // Because object not found or share not set yet
5637  require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
5638  $ecmfile->share = getRandomPassword(true);
5639  }
5640  }
5641 
5642  if ($result > 0) {
5643  $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
5644  $ecmfile->fullpath_orig = '';
5645  $ecmfile->gen_or_uploaded = 'generated';
5646  $ecmfile->description = ''; // indexed content
5647  $ecmfile->keywords = ''; // keyword content
5648  $result = $ecmfile->update($user);
5649  if ($result < 0) {
5650  setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
5651  return -1;
5652  }
5653  } else {
5654  $ecmfile->entity = $conf->entity;
5655  $ecmfile->filepath = $rel_dir;
5656  $ecmfile->filename = $filename;
5657  $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
5658  $ecmfile->fullpath_orig = '';
5659  $ecmfile->gen_or_uploaded = 'generated';
5660  $ecmfile->description = ''; // indexed content
5661  $ecmfile->keywords = ''; // keyword content
5662  $ecmfile->src_object_type = $this->table_element; // $this->table_name is 'myobject' or 'mymodule_myobject'.
5663  $ecmfile->src_object_id = $this->id;
5664 
5665  $result = $ecmfile->create($user);
5666  if ($result < 0) {
5667  setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
5668  return -1;
5669  }
5670  }
5671 
5672  /*$this->result['fullname']=$destfull;
5673  $this->result['filepath']=$ecmfile->filepath;
5674  $this->result['filename']=$ecmfile->filename;*/
5675  //var_dump($obj->update_main_doc_field);exit;
5676 
5677  if ($update_main_doc_field && !empty($this->table_element)) {
5678  $sql = "UPDATE ".$this->db->prefix().$this->table_element." SET last_main_doc = '".$this->db->escape($ecmfile->filepath."/".$ecmfile->filename)."'";
5679  $sql .= " WHERE rowid = ".((int) $this->id);
5680 
5681  $resql = $this->db->query($sql);
5682  if (!$resql) {
5683  dol_print_error($this->db);
5684  return -1;
5685  } else {
5686  $this->last_main_doc = $ecmfile->filepath.'/'.$ecmfile->filename;
5687  }
5688  }
5689  }
5690 
5691  return 1;
5692  }
5693 
5701  public function addThumbs($file)
5702  {
5703  require_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
5704 
5705  $tmparraysize = getDefaultImageSizes();
5706  $maxwidthsmall = $tmparraysize['maxwidthsmall'];
5707  $maxheightsmall = $tmparraysize['maxheightsmall'];
5708  $maxwidthmini = $tmparraysize['maxwidthmini'];
5709  $maxheightmini = $tmparraysize['maxheightmini'];
5710  //$quality = $tmparraysize['quality'];
5711  $quality = 50; // For thumbs, we force quality to 50
5712 
5713  $file_osencoded = dol_osencode($file);
5714  if (file_exists($file_osencoded)) {
5715  // Create small thumbs for company (Ratio is near 16/9)
5716  // Used on logon for example
5717  vignette($file_osencoded, $maxwidthsmall, $maxheightsmall, '_small', $quality);
5718 
5719  // Create mini thumbs for company (Ratio is near 16/9)
5720  // Used on menu or for setup page for example
5721  vignette($file_osencoded, $maxwidthmini, $maxheightmini, '_mini', $quality);
5722  }
5723  }
5724 
5725 
5726  /* Functions common to commonobject and commonobjectline */
5727 
5728  /* For default values */
5729 
5742  public function getDefaultCreateValueFor($fieldname, $alternatevalue = null)
5743  {
5744  global $conf, $_POST;
5745 
5746  // If param here has been posted, we use this value first.
5747  if (GETPOSTISSET($fieldname)) {
5748  return GETPOST($fieldname, 'alphanohtml', 3);
5749  }
5750 
5751  if (isset($alternatevalue)) {
5752  return $alternatevalue;
5753  }
5754 
5755  $newelement = $this->element;
5756  if ($newelement == 'facture') {
5757  $newelement = 'invoice';
5758  }
5759  if ($newelement == 'commande') {
5760  $newelement = 'order';
5761  }
5762  if (empty($newelement)) {
5763  dol_syslog("Ask a default value using common method getDefaultCreateValueForField on an object with no property ->element defined. Return empty string.", LOG_WARNING);
5764  return '';
5765  }
5766 
5767  $keyforfieldname = strtoupper($newelement.'_DEFAULT_'.$fieldname);
5768  //var_dump($keyforfieldname);
5769  if (isset($conf->global->$keyforfieldname)) {
5770  return $conf->global->$keyforfieldname;
5771  }
5772 
5773  // TODO Ad here a scan into table llx_overwrite_default with a filter on $this->element and $fieldname
5774  }
5775 
5776 
5777  /* For triggers */
5778 
5779 
5780  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5791  public function call_trigger($triggerName, $user)
5792  {
5793  // phpcs:enable
5794  global $langs, $conf;
5795  if (!empty(self::TRIGGER_PREFIX) && strpos($triggerName, self::TRIGGER_PREFIX . '_') !== 0) {
5796  dol_print_error('', 'The trigger "' . $triggerName . '" does not start with "' . self::TRIGGER_PREFIX . '_" as required.');
5797  exit;
5798  }
5799  if (!is_object($langs)) { // If lang was not defined, we set it. It is required by run_triggers.
5800  include_once DOL_DOCUMENT_ROOT.'/core/class/translate.class.php';
5801  $langs = new Translate('', $conf);
5802  }
5803 
5804  include_once DOL_DOCUMENT_ROOT.'/core/class/interfaces.class.php';
5805  $interface = new Interfaces($this->db);
5806  $result = $interface->run_triggers($triggerName, $this, $user, $langs, $conf);
5807 
5808  if ($result < 0) {
5809  if (!empty($this->errors)) {
5810  $this->errors = array_unique(array_merge($this->errors, $interface->errors)); // We use array_unique because when a trigger call another trigger on same object, this->errors is added twice.
5811  } else {
5812  $this->errors = $interface->errors;
5813  }
5814  }
5815  return $result;
5816  }
5817 
5818 
5819  /* Functions for data in other language */
5820 
5821 
5829  public function fetchValuesForExtraLanguages()
5830  {
5831  // To avoid SQL errors. Probably not the better solution though
5832  if (!$this->element) {
5833  return 0;
5834  }
5835  if (!($this->id > 0)) {
5836  return 0;
5837  }
5838  if (is_array($this->array_languages)) {
5839  return 1;
5840  }
5841 
5842  $this->array_languages = array();
5843 
5844  $element = $this->element;
5845  if ($element == 'categorie') {
5846  $element = 'categories'; // For compatibility
5847  }
5848 
5849  // Request to get translation values for object
5850  $sql = "SELECT rowid, property, lang , value";
5851  $sql .= " FROM ".$this->db->prefix()."object_lang";
5852  $sql .= " WHERE type_object = '".$this->db->escape($element)."'";
5853  $sql .= " AND fk_object = ".((int) $this->id);
5854 
5855  //dol_syslog(get_class($this)."::fetch_optionals get extrafields data for ".$this->table_element, LOG_DEBUG); // Too verbose
5856  $resql = $this->db->query($sql);
5857  if ($resql) {
5858  $numrows = $this->db->num_rows($resql);
5859  if ($numrows) {
5860  $i = 0;
5861  while ($i < $numrows) {
5862  $obj = $this->db->fetch_object($resql);
5863  $key = $obj->property;
5864  $value = $obj->value;
5865  $codelang = $obj->lang;
5866  $type = $this->fields[$key]['type'];
5867 
5868  // we can add this attribute to object
5869  if (preg_match('/date/', $type)) {
5870  $this->array_languages[$key][$codelang] = $this->db->jdate($value);
5871  } else {
5872  $this->array_languages[$key][$codelang] = $value;
5873  }
5874 
5875  $i++;
5876  }
5877  }
5878 
5879  $this->db->free($resql);
5880 
5881  if ($numrows) {
5882  return $numrows;
5883  } else {
5884  return 0;
5885  }
5886  } else {
5887  dol_print_error($this->db);
5888  return -1;
5889  }
5890  }
5891 
5898  public function setValuesForExtraLanguages($onlykey = '')
5899  {
5900  global $_POST, $langs;
5901 
5902  // Get extra fields
5903  foreach ($_POST as $postfieldkey => $postfieldvalue) {
5904  $tmparray = explode('-', $postfieldkey);
5905  if ($tmparray[0] != 'field') {
5906  continue;
5907  }
5908 
5909  $element = $tmparray[1];
5910  $key = $tmparray[2];
5911  $codelang = $tmparray[3];
5912  //var_dump("postfieldkey=".$postfieldkey." element=".$element." key=".$key." codelang=".$codelang);
5913 
5914  if (!empty($onlykey) && $key != $onlykey) {
5915  continue;
5916  }
5917  if ($element != $this->element) {
5918  continue;
5919  }
5920 
5921  $key_type = $this->fields[$key]['type'];
5922 
5923  $enabled = 1;
5924  if (isset($this->fields[$key]['enabled'])) {
5925  $enabled = dol_eval($this->fields[$key]['enabled'], 1, 1, '1');
5926  }
5927  /*$perms = 1;
5928  if (isset($this->fields[$key]['perms']))
5929  {
5930  $perms = dol_eval($this->fields[$key]['perms'], 1, 1, '1');
5931  }*/
5932  if (empty($enabled)) {
5933  continue;
5934  }
5935  //if (empty($perms)) continue;
5936 
5937  if (in_array($key_type, array('date'))) {
5938  // Clean parameters
5939  // TODO GMT date in memory must be GMT so we should add gm=true in parameters
5940  $value_key = dol_mktime(0, 0, 0, GETPOST($postfieldkey."month", 'int'), GETPOST($postfieldkey."day", 'int'), GETPOST($postfieldkey."year", 'int'));
5941  } elseif (in_array($key_type, array('datetime'))) {
5942  // Clean parameters
5943  // TODO GMT date in memory must be GMT so we should add gm=true in parameters
5944  $value_key = dol_mktime(GETPOST($postfieldkey."hour", 'int'), GETPOST($postfieldkey."min", 'int'), 0, GETPOST($postfieldkey."month", 'int'), GETPOST($postfieldkey."day", 'int'), GETPOST($postfieldkey."year", 'int'));
5945  } elseif (in_array($key_type, array('checkbox', 'chkbxlst'))) {
5946  $value_arr = GETPOST($postfieldkey, 'array'); // check if an array
5947  if (!empty($value_arr)) {
5948  $value_key = implode(',', $value_arr);
5949  } else {
5950  $value_key = '';
5951  }
5952  } elseif (in_array($key_type, array('price', 'double'))) {
5953  $value_arr = GETPOST($postfieldkey, 'alpha');
5954  $value_key = price2num($value_arr);
5955  } else {
5956  $value_key = GETPOST($postfieldkey);
5957  if (in_array($key_type, array('link')) && $value_key == '-1') {
5958  $value_key = '';
5959  }
5960  }
5961 
5962  $this->array_languages[$key][$codelang] = $value_key;
5963 
5964  /*if ($nofillrequired) {
5965  $langs->load('errors');
5966  setEventMessages($langs->trans('ErrorFieldsRequired').' : '.implode(', ', $error_field_required), null, 'errors');
5967  return -1;
5968  }*/
5969  }
5970 
5971  return 1;
5972  }
5973 
5974 
5975  /* Functions for extrafields */
5976 
5983  public function fetchNoCompute($id)
5984  {
5985  global $conf;
5986 
5987  $savDisableCompute = $conf->disable_compute;
5988  $conf->disable_compute = 1;
5989 
5990  $ret = $this->fetch($id);
5991 
5992  $conf->disable_compute = $savDisableCompute;
5993 
5994  return $ret;
5995  }
5996 
5997  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
6007  public function fetch_optionals($rowid = null, $optionsArray = null)
6008  {
6009  // phpcs:enable
6010  global $conf, $extrafields;
6011 
6012  if (empty($rowid)) {
6013  $rowid = $this->id;
6014  }
6015  if (empty($rowid) && isset($this->rowid)) {
6016  $rowid = $this->rowid; // deprecated
6017  }
6018 
6019  // To avoid SQL errors. Probably not the better solution though
6020  if (!$this->table_element) {
6021  return 0;
6022  }
6023 
6024  $this->array_options = array();
6025 
6026  if (!is_array($optionsArray)) {
6027  // If $extrafields is not a known object, we initialize it. Best practice is to have $extrafields defined into card.php or list.php page.
6028  if (!isset($extrafields) || !is_object($extrafields)) {
6029  require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
6030  $extrafields = new ExtraFields($this->db);
6031  }
6032 
6033  // Load array of extrafields for elementype = $this->table_element
6034  if (empty($extrafields->attributes[$this->table_element]['loaded'])) {
6035  $extrafields->fetch_name_optionals_label($this->table_element);
6036  }
6037  $optionsArray = (!empty($extrafields->attributes[$this->table_element]['label']) ? $extrafields->attributes[$this->table_element]['label'] : null);
6038  } else {
6039  global $extrafields;
6040  dol_syslog("Warning: fetch_optionals was called with param optionsArray defined when you should pass null now", LOG_WARNING);
6041  }
6042 
6043  $table_element = $this->table_element;
6044  if ($table_element == 'categorie') {
6045  $table_element = 'categories'; // For compatibility
6046  }
6047 
6048  // Request to get complementary values
6049  if (is_array($optionsArray) && count($optionsArray) > 0) {
6050  $sql = "SELECT rowid";
6051  foreach ($optionsArray as $name => $label) {
6052  if (empty($extrafields->attributes[$this->table_element]['type'][$name]) || $extrafields->attributes[$this->table_element]['type'][$name] != 'separate') {
6053  $sql .= ", ".$name;
6054  }
6055  }
6056  $sql .= " FROM ".$this->db->prefix().$table_element."_extrafields";
6057  $sql .= " WHERE fk_object = ".((int) $rowid);
6058 
6059  //dol_syslog(get_class($this)."::fetch_optionals get extrafields data for ".$this->table_element, LOG_DEBUG); // Too verbose
6060  $resql = $this->db->query($sql);
6061  if ($resql) {
6062  $numrows = $this->db->num_rows($resql);
6063  if ($numrows) {
6064  $tab = $this->db->fetch_array($resql);
6065 
6066  foreach ($tab as $key => $value) {
6067  // Test fetch_array ! is_int($key) because fetch_array result is a mix table with Key as alpha and Key as int (depend db engine)
6068  if ($key != 'rowid' && $key != 'tms' && $key != 'fk_member' && !is_int($key)) {
6069  // we can add this attribute to object
6070  if (!empty($extrafields->attributes[$this->table_element]) && in_array($extrafields->attributes[$this->table_element]['type'][$key], array('date', 'datetime'))) {
6071  //var_dump($extrafields->attributes[$this->table_element]['type'][$key]);
6072  $this->array_options["options_".$key] = $this->db->jdate($value);
6073  } else {
6074  $this->array_options["options_".$key] = $value;
6075  }
6076 
6077  //var_dump('key '.$key.' '.$value.' type='.$extrafields->attributes[$this->table_element]['type'][$key].' '.$this->array_options["options_".$key]);
6078  }
6079  }
6080  }
6081 
6082  // If field is a computed field, value must become result of compute (regardless of whether a row exists
6083  // in the element's extrafields table)
6084  foreach ($extrafields->attributes[$this->table_element]['label'] as $key => $val) {
6085  if (!empty($extrafields->attributes[$this->table_element]) && !empty($extrafields->attributes[$this->table_element]['computed'][$key])) {
6086  //var_dump($conf->disable_compute);
6087  if (empty($conf->disable_compute)) {
6088  global $objectoffield; // We set a global variable to $objectoffield so
6089  $objectoffield = $this; // we can use it inside computed formula
6090  $this->array_options["options_".$key] = dol_eval($extrafields->attributes[$this->table_element]['computed'][$key], 1, 0, '');
6091  }
6092  }
6093  }
6094 
6095  $this->db->free($resql);
6096 
6097  if ($numrows) {
6098  return $numrows;
6099  } else {
6100  return 0;
6101  }
6102  } else {
6103  $this->errors[]=$this->db->lasterror;
6104  return -1;
6105  }
6106  }
6107  return 0;
6108  }
6109 
6116  public function deleteExtraFields()
6117  {
6118  global $conf;
6119 
6120  if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
6121  return 0;
6122  }
6123 
6124  $this->db->begin();
6125 
6126  $table_element = $this->table_element;
6127  if ($table_element == 'categorie') {
6128  $table_element = 'categories'; // For compatibility
6129  }
6130 
6131  dol_syslog(get_class($this)."::deleteExtraFields delete", LOG_DEBUG);
6132 
6133  $sql_del = "DELETE FROM ".$this->db->prefix().$table_element."_extrafields WHERE fk_object = ".((int) $this->id);
6134 
6135  $resql = $this->db->query($sql_del);
6136  if (!$resql) {
6137  $this->error = $this->db->lasterror();
6138  $this->db->rollback();
6139  return -1;
6140  } else {
6141  $this->db->commit();
6142  return 1;
6143  }
6144  }
6145 
6156  public function insertExtraFields($trigger = '', $userused = null)
6157  {
6158  global $conf, $langs, $user;
6159 
6160  if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
6161  return 0;
6162  }
6163 
6164  if (empty($userused)) {
6165  $userused = $user;
6166  }
6167 
6168  $error = 0;
6169 
6170  if (!empty($this->array_options)) {
6171  // Check parameters
6172  $langs->load('admin');
6173  require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
6174  $extrafields = new ExtraFields($this->db);
6175  $target_extrafields = $extrafields->fetch_name_optionals_label($this->table_element);
6176 
6177  // Eliminate copied source object extra fields that do not exist in target object
6178  $new_array_options = array();
6179  foreach ($this->array_options as $key => $value) {
6180  if (in_array(substr($key, 8), array_keys($target_extrafields))) { // We remove the 'options_' from $key for test
6181  $new_array_options[$key] = $value;
6182  } elseif (in_array($key, array_keys($target_extrafields))) { // We test on $key that does not contains the 'options_' prefix
6183  $new_array_options['options_'.$key] = $value;
6184  }
6185  }
6186 
6187  foreach ($new_array_options as $key => $value) {
6188  $attributeKey = substr($key, 8); // Remove 'options_' prefix
6189  $attributeType = $extrafields->attributes[$this->table_element]['type'][$attributeKey];
6190  $attributeLabel = $extrafields->attributes[$this->table_element]['label'][$attributeKey];
6191  $attributeParam = $extrafields->attributes[$this->table_element]['param'][$attributeKey];
6192  $attributeRequired = $extrafields->attributes[$this->table_element]['required'][$attributeKey];
6193  $attributeUnique = $extrafields->attributes[$this->table_element]['unique'][$attributeKey];
6194  $attrfieldcomputed = $extrafields->attributes[$this->table_element]['computed'][$attributeKey];
6195 
6196  // If we clone, we have to clean unique extrafields to prevent duplicates.
6197  // This behaviour can be prevented by external code by changing $this->context['createfromclone'] value in createFrom hook
6198  if (! empty($this->context['createfromclone']) && $this->context['createfromclone'] == 'createfromclone' && ! empty($attributeUnique)) {
6199  $new_array_options[$key] = null;
6200  }
6201 
6202  // Similar code than into insertExtraFields
6203  if ($attributeRequired) {
6204  $mandatorypb = false;
6205  if ($attributeType == 'link' && $this->array_options[$key] == '-1') {
6206  $mandatorypb = true;
6207  }
6208  if ($this->array_options[$key] === '') {
6209  $mandatorypb = true;
6210  }
6211  if ($attributeType == 'sellist' && $this->array_options[$key] == '0') {
6212  $mandatorypb = true;
6213  }
6214  if ($mandatorypb) {
6215  $langs->load("errors");
6216  dol_syslog("Mandatory field '".$key."' is empty during create and set to required into definition of extrafields");
6217  $this->errors[] = $langs->trans('ErrorFieldRequired', $attributeLabel);
6218  return -1;
6219  }
6220  }
6221 
6222  //dol_syslog("attributeLabel=".$attributeLabel, LOG_DEBUG);
6223  //dol_syslog("attributeType=".$attributeType, LOG_DEBUG);
6224 
6225  if (!empty($attrfieldcomputed)) {
6226  if (!empty($conf->global->MAIN_STORE_COMPUTED_EXTRAFIELDS)) {
6227  $value = dol_eval($attrfieldcomputed, 1, 0, '');
6228  dol_syslog($langs->trans("Extrafieldcomputed")." sur ".$attributeLabel."(".$value.")", LOG_DEBUG);
6229  $new_array_options[$key] = $value;
6230  } else {
6231  $new_array_options[$key] = null;
6232  }
6233  }
6234 
6235  switch ($attributeType) {
6236  case 'int':
6237  if (!is_numeric($value) && $value != '') {
6238  $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
6239  return -1;
6240  } elseif ($value == '') {
6241  $new_array_options[$key] = null;
6242  }
6243  break;
6244  case 'price':
6245  case 'double':
6246  $value = price2num($value);
6247  if (!is_numeric($value) && $value != '') {
6248  dol_syslog($langs->trans("ExtraFieldHasWrongValue")." for ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
6249  $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
6250  return -1;
6251  } elseif ($value == '') {
6252  $value = null;
6253  }
6254  //dol_syslog("double value"." sur ".$attributeLabel."(".$value." is '".$attributeType."')", LOG_DEBUG);
6255  $new_array_options[$key] = $value;
6256  break;
6257  /*case 'select': // Not required, we chosed value='0' for undefined values
6258  if ($value=='-1')
6259  {
6260  $this->array_options[$key] = null;
6261  }
6262  break;*/
6263  case 'password':
6264  $algo = '';
6265  if ($this->array_options[$key] != '' && is_array($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options'])) {
6266  // If there is an encryption choice, we use it to crypt data before insert
6267  $tmparrays = array_keys($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options']);
6268  $algo = reset($tmparrays);
6269  if ($algo != '') {
6270  //global $action; // $action may be 'create', 'update', 'update_extras'...
6271  //var_dump($action);
6272  //var_dump($this->oldcopy);exit;
6273  if (is_object($this->oldcopy)) { // If this->oldcopy is not defined, we can't know if we change attribute or not, so we must keep value
6274  //var_dump($this->oldcopy->array_options[$key]); var_dump($this->array_options[$key]);
6275  if (isset($this->oldcopy->array_options[$key]) && $this->array_options[$key] == $this->oldcopy->array_options[$key]) { // If old value crypted in database is same than submited new value, it means we don't change it, so we don't update.
6276  $new_array_options[$key] = $this->array_options[$key]; // Value is kept
6277  } else {
6278  // var_dump($algo);
6279  $newvalue = dol_hash($this->array_options[$key], $algo);
6280  $new_array_options[$key] = $newvalue;
6281  }
6282  } else {
6283  $new_array_options[$key] = $this->array_options[$key]; // Value is kept
6284  }
6285  }
6286  } else // Common usage
6287  {
6288  $new_array_options[$key] = $this->array_options[$key];
6289  }
6290  break;
6291  case 'date':
6292  case 'datetime':
6293  // If data is a string instead of a timestamp, we convert it
6294  if (!is_int($this->array_options[$key])) {
6295  $this->array_options[$key] = strtotime($this->array_options[$key]);
6296  }
6297  $new_array_options[$key] = $this->db->idate($this->array_options[$key]);
6298  break;
6299  case 'link':
6300  $param_list = array_keys($attributeParam['options']);
6301  // 0 : ObjectName
6302  // 1 : classPath
6303  $InfoFieldList = explode(":", $param_list[0]);
6304  dol_include_once($InfoFieldList[1]);
6305  if ($InfoFieldList[0] && class_exists($InfoFieldList[0])) {
6306  if ($value == '-1') { // -1 is key for no defined in combo list of objects
6307  $new_array_options[$key] = '';
6308  } elseif ($value) {
6309  $object = new $InfoFieldList[0]($this->db);
6310  if (is_numeric($value)) {
6311  $res = $object->fetch($value); // Common case
6312  } else {
6313  $res = $object->fetch('', $value); // For compatibility
6314  }
6315 
6316  if ($res > 0) {
6317  $new_array_options[$key] = $object->id;
6318  } else {
6319  $this->error = "Id/Ref '".$value."' for object '".$object->element."' not found";
6320  return -1;
6321  }
6322  }
6323  } else {
6324  dol_syslog('Error bad setup of extrafield', LOG_WARNING);
6325  }
6326  break;
6327  }
6328  }
6329 
6330  $this->db->begin();
6331 
6332  $table_element = $this->table_element;
6333  if ($table_element == 'categorie') {
6334  $table_element = 'categories'; // For compatibility
6335  }
6336 
6337  dol_syslog(get_class($this)."::insertExtraFields delete then insert", LOG_DEBUG);
6338 
6339  $sql_del = "DELETE FROM ".$this->db->prefix().$table_element."_extrafields WHERE fk_object = ".((int) $this->id);
6340  $this->db->query($sql_del);
6341 
6342  $sql = "INSERT INTO ".$this->db->prefix().$table_element."_extrafields (fk_object";
6343  foreach ($new_array_options as $key => $value) {
6344  $attributeKey = substr($key, 8); // Remove 'options_' prefix
6345  // Add field of attribut
6346  if ($extrafields->attributes[$this->table_element]['type'][$attributeKey] != 'separate') { // Only for other type than separator
6347  $sql .= ",".$attributeKey;
6348  }
6349  }
6350  // We must insert a default value for fields for other entities that are mandatory to avoid not null error
6351  if (!empty($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities']) && is_array($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'])) {
6352  foreach ($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'] as $tmpkey => $tmpval) {
6353  if (!isset($extrafields->attributes[$this->table_element]['type'][$tmpkey])) { // If field not already added previously
6354  $sql .= ",".$tmpkey;
6355  }
6356  }
6357  }
6358  $sql .= ") VALUES (".$this->id;
6359 
6360  foreach ($new_array_options as $key => $value) {
6361  $attributeKey = substr($key, 8); // Remove 'options_' prefix
6362  // Add field of attribute
6363  if ($extrafields->attributes[$this->table_element]['type'][$attributeKey] != 'separate') { // Only for other type than separator)
6364  if ($new_array_options[$key] != '' || $new_array_options[$key] == '0') {
6365  $sql .= ",'".$this->db->escape($new_array_options[$key])."'";
6366  } else {
6367  $sql .= ",null";
6368  }
6369  }
6370  }
6371  // We must insert a default value for fields for other entities that are mandatory to avoid not null error
6372  if (!empty($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities']) && is_array($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'])) {
6373  foreach ($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'] as $tmpkey => $tmpval) {
6374  if (!isset($extrafields->attributes[$this->table_element]['type'][$tmpkey])) { // If field not already added previously
6375  if (in_array($tmpval, array('int', 'double', 'price'))) {
6376  $sql .= ", 0";
6377  } else {
6378  $sql .= ", ''";
6379  }
6380  }
6381  }
6382  }
6383 
6384  $sql .= ")";
6385 
6386  $resql = $this->db->query($sql);
6387  if (!$resql) {
6388  $this->error = $this->db->lasterror();
6389  $error++;
6390  }
6391 
6392  if (!$error && $trigger) {
6393  // Call trigger
6394  $this->context = array('extrafieldaddupdate'=>1);
6395  $result = $this->call_trigger($trigger, $userused);
6396  if ($result < 0) {
6397  $error++;
6398  }
6399  // End call trigger
6400  }
6401 
6402  if ($error) {
6403  $this->db->rollback();
6404  return -1;
6405  } else {
6406  $this->db->commit();
6407  return 1;
6408  }
6409  } else {
6410  return 0;
6411  }
6412  }
6413 
6424  public function insertExtraLanguages($trigger = '', $userused = null)
6425  {
6426  global $conf, $langs, $user;
6427 
6428  if (empty($userused)) {
6429  $userused = $user;
6430  }
6431 
6432  $error = 0;
6433 
6434  if (!empty($conf->global->MAIN_EXTRALANGUAGES_DISABLED)) {
6435  return 0; // For avoid conflicts if trigger used
6436  }
6437 
6438  if (is_array($this->array_languages)) {
6439  $new_array_languages = $this->array_languages;
6440 
6441  foreach ($new_array_languages as $key => $value) {
6442  $attributeKey = $key;
6443  $attributeType = $this->fields[$attributeKey]['type'];
6444  $attributeLabel = $this->fields[$attributeKey]['label'];
6445 
6446  //dol_syslog("attributeLabel=".$attributeLabel, LOG_DEBUG);
6447  //dol_syslog("attributeType=".$attributeType, LOG_DEBUG);
6448 
6449  switch ($attributeType) {
6450  case 'int':
6451  if (!is_numeric($value) && $value != '') {
6452  $this->errors[] = $langs->trans("ExtraLanguageHasWrongValue", $attributeLabel);
6453  return -1;
6454  } elseif ($value == '') {
6455  $new_array_languages[$key] = null;
6456  }
6457  break;
6458  case 'double':
6459  $value = price2num($value);
6460  if (!is_numeric($value) && $value != '') {
6461  dol_syslog($langs->trans("ExtraLanguageHasWrongValue")." sur ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
6462  $this->errors[] = $langs->trans("ExtraLanguageHasWrongValue", $attributeLabel);
6463  return -1;
6464  } elseif ($value == '') {
6465  $new_array_languages[$key] = null;
6466  }
6467  //dol_syslog("double value"." sur ".$attributeLabel."(".$value." is '".$attributeType."')", LOG_DEBUG);
6468  $new_array_languages[$key] = $value;
6469  break;
6470  /*case 'select': // Not required, we chosed value='0' for undefined values
6471  if ($value=='-1')
6472  {
6473  $this->array_options[$key] = null;
6474  }
6475  break;*/
6476  }
6477  }
6478 
6479  $this->db->begin();
6480 
6481  $table_element = $this->table_element;
6482  if ($table_element == 'categorie') {
6483  $table_element = 'categories'; // For compatibility
6484  }
6485 
6486  dol_syslog(get_class($this)."::insertExtraLanguages delete then insert", LOG_DEBUG);
6487 
6488  foreach ($new_array_languages as $key => $langcodearray) { // $key = 'name', 'town', ...
6489  foreach ($langcodearray as $langcode => $value) {
6490  $sql_del = "DELETE FROM ".$this->db->prefix()."object_lang";
6491  $sql_del .= " WHERE fk_object = ".((int) $this->id)." AND property = '".$this->db->escape($key)."' AND type_object = '".$this->db->escape($table_element)."'";
6492  $sql_del .= " AND lang = '".$this->db->escape($langcode)."'";
6493  $this->db->query($sql_del);
6494 
6495  if ($value !== '') {
6496  $sql = "INSERT INTO ".$this->db->prefix()."object_lang (fk_object, property, type_object, lang, value";
6497  $sql .= ") VALUES (".$this->id.", '".$this->db->escape($key)."', '".$this->db->escape($table_element)."', '".$this->db->escape($langcode)."', '".$this->db->escape($value)."'";
6498  $sql .= ")";
6499 
6500  $resql = $this->db->query($sql);
6501  if (!$resql) {
6502  $this->error = $this->db->lasterror();
6503  $error++;
6504  break;
6505  }
6506  }
6507  }
6508  }
6509 
6510  if (!$error && $trigger) {
6511  // Call trigger
6512  $this->context = array('extralanguagesaddupdate'=>1);
6513  $result = $this->call_trigger($trigger, $userused);
6514  if ($result < 0) {
6515  $error++;
6516  }
6517  // End call trigger
6518  }
6519 
6520  if ($error) {
6521  $this->db->rollback();
6522  return -1;
6523  } else {
6524  $this->db->commit();
6525  return 1;
6526  }
6527  } else {
6528  return 0;
6529  }
6530  }
6531 
6542  public function updateExtraField($key, $trigger = null, $userused = null)
6543  {
6544  global $conf, $langs, $user;
6545 
6546  if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
6547  return 0;
6548  }
6549 
6550  if (empty($userused)) {
6551  $userused = $user;
6552  }
6553 
6554  $error = 0;
6555 
6556  if (!empty($this->array_options) && isset($this->array_options["options_".$key])) {
6557  // Check parameters
6558  $langs->load('admin');
6559  require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
6560  $extrafields = new ExtraFields($this->db);
6561  $extrafields->fetch_name_optionals_label($this->table_element);
6562 
6563  $value = $this->array_options["options_".$key];
6564 
6565  $attributeType = $extrafields->attributes[$this->table_element]['type'][$key];
6566  $attributeLabel = $extrafields->attributes[$this->table_element]['label'][$key];
6567  $attributeParam = $extrafields->attributes[$this->table_element]['param'][$key];
6568  $attributeRequired = $extrafields->attributes[$this->table_element]['required'][$key];
6569  $attrfieldcomputed = $extrafields->attributes[$this->table_element]['computed'][$key];
6570 
6571  // Similar code than into insertExtraFields
6572  if ($attributeRequired) {
6573  $mandatorypb = false;
6574  if ($attributeType == 'link' && $this->array_options["options_".$key] == '-1') {
6575  $mandatorypb = true;
6576  }
6577  if ($this->array_options["options_".$key] === '') {
6578  $mandatorypb = true;
6579  }
6580  if ($mandatorypb) {
6581  $langs->load("errors");
6582  dol_syslog("Mandatory field 'options_".$key."' is empty during update and set to required into definition of extrafields");
6583  $this->errors[] = $langs->trans('ErrorFieldRequired', $attributeLabel);
6584  return -1;
6585  }
6586  }
6587 
6588  //dol_syslog("attributeLabel=".$attributeLabel, LOG_DEBUG);
6589  //dol_syslog("attributeType=".$attributeType, LOG_DEBUG);
6590 
6591  if (!empty($attrfieldcomputed)) {
6592  if (!empty($conf->global->MAIN_STORE_COMPUTED_EXTRAFIELDS)) {
6593  $value = dol_eval($attrfieldcomputed, 1, 0, '');
6594  dol_syslog($langs->trans("Extrafieldcomputed")." sur ".$attributeLabel."(".$value.")", LOG_DEBUG);
6595  $this->array_options["options_".$key] = $value;
6596  } else {
6597  $this->array_options["options_".$key] = null;
6598  }
6599  }
6600 
6601  switch ($attributeType) {
6602  case 'int':
6603  if (!is_numeric($value) && $value != '') {
6604  $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
6605  return -1;
6606  } elseif ($value === '') {
6607  $this->array_options["options_".$key] = null;
6608  }
6609  break;
6610  case 'double':
6611  $value = price2num($value);
6612  if (!is_numeric($value) && $value != '') {
6613  dol_syslog($langs->trans("ExtraFieldHasWrongValue")." sur ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
6614  $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
6615  return -1;
6616  } elseif ($value === '') {
6617  $value = null;
6618  }
6619  //dol_syslog("double value"." sur ".$attributeLabel."(".$value." is '".$attributeType."')", LOG_DEBUG);
6620  $this->array_options["options_".$key] = $value;
6621  break;
6622  /*case 'select': // Not required, we chosed value='0' for undefined values
6623  if ($value=='-1')
6624  {
6625  $this->array_options[$key] = null;
6626  }
6627  break;*/
6628  case 'price':
6629  $this->array_options["options_".$key] = price2num($this->array_options["options_".$key]);
6630  break;
6631  case 'date':
6632  case 'datetime':
6633  if (empty($this->array_options["options_".$key])) {
6634  $this->array_options["options_".$key] = null;
6635  } else {
6636  $this->array_options["options_".$key] = $this->db->idate($this->array_options["options_".$key]);
6637  }
6638  break;
6639  case 'boolean':
6640  if (empty($this->array_options["options_".$key])) {
6641  $this->array_options["options_".$key] = null;
6642  }
6643  break;
6644  case 'link':
6645  if ($this->array_options["options_".$key] === '') {
6646  $this->array_options["options_".$key] = null;
6647  }
6648  break;
6649  /*
6650  case 'link':
6651  $param_list = array_keys($attributeParam['options']);
6652  // 0 : ObjectName
6653  // 1 : classPath
6654  $InfoFieldList = explode(":", $param_list[0]);
6655  dol_include_once($InfoFieldList[1]);
6656  if ($InfoFieldList[0] && class_exists($InfoFieldList[0]))
6657  {
6658  if ($value == '-1') // -1 is key for no defined in combo list of objects
6659  {
6660  $new_array_options[$key] = '';
6661  } elseif ($value) {
6662  $object = new $InfoFieldList[0]($this->db);
6663  if (is_numeric($value)) $res = $object->fetch($value); // Common case
6664  else $res = $object->fetch('', $value); // For compatibility
6665 
6666  if ($res > 0) $new_array_options[$key] = $object->id;
6667  else {
6668  $this->error = "Id/Ref '".$value."' for object '".$object->element."' not found";
6669  $this->db->rollback();
6670  return -1;
6671  }
6672  }
6673  } else {
6674  dol_syslog('Error bad setup of extrafield', LOG_WARNING);
6675  }
6676  break;
6677  */
6678  }
6679 
6680  $this->db->begin();
6681 
6682  $linealreadyfound = 0;
6683 
6684  // Check if there is already a line for this object (in most cases, it is, but sometimes it is not, for example when extra field has been created after), so we must keep this overload)
6685  $sql = "SELECT COUNT(rowid) as nb FROM ".$this->db->prefix().$this->table_element."_extrafields WHERE fk_object = ".((int) $this->id);
6686  $resql = $this->db->query($sql);
6687  if ($resql) {
6688  $tmpobj = $this->db->fetch_object($resql);
6689  if ($tmpobj) {
6690  $linealreadyfound = $tmpobj->nb;
6691  }
6692  }
6693 
6694  if ($linealreadyfound) {
6695  if ($this->array_options["options_".$key] === null) {
6696  $sql = "UPDATE ".$this->db->prefix().$this->table_element."_extrafields SET ".$key." = null";
6697  } else {
6698  $sql = "UPDATE ".$this->db->prefix().$this->table_element."_extrafields SET ".$key." = '".$this->db->escape($this->array_options["options_".$key])."'";
6699  }
6700  $sql .= " WHERE fk_object = ".((int) $this->id);
6701  } else {
6702  $result = $this->insertExtraFields('', $user);
6703  if ($result < 0) {
6704  $error++;
6705  }
6706  }
6707 
6708  $resql = $this->db->query($sql);
6709  if (!$resql) {
6710  $error++;
6711  $this->error = $this->db->lasterror();
6712  }
6713  if (!$error && $trigger) {
6714  // Call trigger
6715  $this->context = array('extrafieldupdate'=>1);
6716  $result = $this->call_trigger($trigger, $userused);
6717  if ($result < 0) {
6718  $error++;
6719  }
6720  // End call trigger
6721  }
6722 
6723  if ($error) {
6724  dol_syslog(__METHOD__.$this->error, LOG_ERR);
6725  $this->db->rollback();
6726  return -1;
6727  } else {
6728  $this->db->commit();
6729  return 1;
6730  }
6731  } else {
6732  return 0;
6733  }
6734  }
6735 
6746  public function updateExtraLanguages($key, $trigger = null, $userused = null)
6747  {
6748  global $conf, $langs, $user;
6749 
6750  if (empty($userused)) {
6751  $userused = $user;
6752  }
6753 
6754  $error = 0;
6755 
6756  if (!empty($conf->global->MAIN_EXTRALANGUAGES_DISABLED)) {
6757  return 0; // For avoid conflicts if trigger used
6758  }
6759 
6760  return 0;
6761  }
6762 
6763 
6778  public function showInputField($val, $key, $value, $moreparam = '', $keysuffix = '', $keyprefix = '', $morecss = 0, $nonewbutton = 0)
6779  {
6780  global $conf, $langs, $form;
6781 
6782  if (!is_object($form)) {
6783  require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
6784  $form = new Form($this->db);
6785  }
6786 
6787  if (!empty($this->fields)) {
6788  $val = $this->fields[$key];
6789  }
6790 
6791  // Validation tests and output
6792  $fieldValidationErrorMsg = '';
6793  $validationClass = '';
6794  $fieldValidationErrorMsg = $this->getFieldError($key);
6795  if (!empty($fieldValidationErrorMsg)) {
6796  $validationClass = ' --error'; // the -- is use as class state in css : .--error can't be be defined alone it must be define with another class like .my-class.--error or input.--error
6797  } else {
6798  $validationClass = ' --success'; // the -- is use as class state in css : .--success can't be be defined alone it must be define with another class like .my-class.--success or input.--success
6799  }
6800 
6801  $out = '';
6802  $type = '';
6803  $isDependList = 0;
6804  $param = array();
6805  $param['options'] = array();
6806  $reg = array();
6807  $size = !empty($this->fields[$key]['size']) ? $this->fields[$key]['size'] : 0;
6808  // Because we work on extrafields
6809  if (preg_match('/^(integer|link):(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
6810  $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4].':'.$reg[5] => 'N');
6811  $type = 'link';
6812  } elseif (preg_match('/^(integer|link):(.*):(.*):(.*)/i', $val['type'], $reg)) {
6813  $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4] => 'N');
6814  $type = 'link';
6815  } elseif (preg_match('/^(integer|link):(.*):(.*)/i', $val['type'], $reg)) {
6816  $param['options'] = array($reg[2].':'.$reg[3] => 'N');
6817  $type = 'link';
6818  } elseif (preg_match('/^(sellist):(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
6819  $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4].':'.$reg[5] => 'N');
6820  $type = 'sellist';
6821  } elseif (preg_match('/^(sellist):(.*):(.*):(.*)/i', $val['type'], $reg)) {
6822  $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4] => 'N');
6823  $type = 'sellist';
6824  } elseif (preg_match('/^(sellist):(.*):(.*)/i', $val['type'], $reg)) {
6825  $param['options'] = array($reg[2].':'.$reg[3] => 'N');
6826  $type = 'sellist';
6827  } elseif (preg_match('/varchar\((\d+)\)/', $val['type'], $reg)) {
6828  $param['options'] = array();
6829  $type = 'varchar';
6830  $size = $reg[1];
6831  } elseif (preg_match('/varchar/', $val['type'])) {
6832  $param['options'] = array();
6833  $type = 'varchar';
6834  } else {
6835  $param['options'] = array();
6836  $type = $this->fields[$key]['type'];
6837  }
6838 
6839  // Special case that force options and type ($type can be integer, varchar, ...)
6840  if (!empty($this->fields[$key]['arrayofkeyval']) && is_array($this->fields[$key]['arrayofkeyval'])) {
6841  $param['options'] = $this->fields[$key]['arrayofkeyval'];
6842  $type = 'select';
6843  }
6844 
6845  $label = $this->fields[$key]['label'];
6846  //$elementtype=$this->fields[$key]['elementtype']; // Seems not used
6847  $default = (!empty($this->fields[$key]['default']) ? $this->fields[$key]['default'] : '');
6848  $computed = (!empty($this->fields[$key]['computed']) ? $this->fields[$key]['computed'] : '');
6849  $unique = (!empty($this->fields[$key]['unique']) ? $this->fields[$key]['unique'] : 0);
6850  $required = (!empty($this->fields[$key]['required']) ? $this->fields[$key]['required'] : 0);
6851  $autofocusoncreate = (!empty($this->fields[$key]['autofocusoncreate']) ? $this->fields[$key]['autofocusoncreate'] : 0);
6852 
6853  $langfile = (!empty($this->fields[$key]['langfile']) ? $this->fields[$key]['langfile'] : '');
6854  $list = (!empty($this->fields[$key]['list']) ? $this->fields[$key]['list'] : 0);
6855  $hidden = (in_array(abs($this->fields[$key]['visible']), array(0, 2)) ? 1 : 0);
6856 
6857  $objectid = $this->id;
6858 
6859  if ($computed) {
6860  if (!preg_match('/^search_/', $keyprefix)) {
6861  return '<span class="opacitymedium">'.$langs->trans("AutomaticallyCalculated").'</span>';
6862  } else {
6863  return '';
6864  }
6865  }
6866 
6867  // Set value of $morecss. For this, we use in priority showsize from parameters, then $val['css'] then autodefine
6868  if (empty($morecss) && !empty($val['css'])) {
6869  $morecss = $val['css'];
6870  } elseif (empty($morecss)) {
6871  if ($type == 'date') {
6872  $morecss = 'minwidth100imp';
6873  } elseif ($type == 'datetime' || $type == 'link') { // link means an foreign key to another primary id
6874  $morecss = 'minwidth200imp';
6875  } elseif (in_array($type, array('int', 'integer', 'price')) || preg_match('/^double(\([0-9],[0-9]\)){0,1}/', $type)) {
6876  $morecss = 'maxwidth75';
6877  } elseif ($type == 'url') {
6878  $morecss = 'minwidth400';
6879  } elseif ($type == 'boolean') {
6880  $morecss = '';
6881  } else {
6882  if (round($size) < 12) {
6883  $morecss = 'minwidth100';
6884  } elseif (round($size) <= 48) {
6885  $morecss = 'minwidth200';
6886  } else {
6887  $morecss = 'minwidth400';
6888  }
6889  }
6890  }
6891 
6892  // Add validation state class
6893  if (!empty($validationClass)) {
6894  $morecss.= $validationClass;
6895  }
6896 
6897  if (in_array($type, array('date'))) {
6898  $tmp = explode(',', $size);
6899  $newsize = $tmp[0];
6900  $showtime = 0;
6901 
6902  // Do not show current date when field not required (see selectDate() method)
6903  if (!$required && $value == '') {
6904  $value = '-1';
6905  }
6906 
6907  // TODO Must also support $moreparam
6908  $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required, '', 1, (($keyprefix != 'search_' && $keyprefix != 'search_options_') ? 1 : 0), 0, 1);
6909  } elseif (in_array($type, array('datetime'))) {
6910  $tmp = explode(',', $size);
6911  $newsize = $tmp[0];
6912  $showtime = 1;
6913 
6914  // Do not show current date when field not required (see selectDate() method)
6915  if (!$required && $value == '') $value = '-1';
6916 
6917  // TODO Must also support $moreparam
6918  $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required, '', 1, (($keyprefix != 'search_' && $keyprefix != 'search_options_') ? 1 : 0), 0, 1, '', '', '', 1, '', '', 'tzuserrel');
6919  } elseif (in_array($type, array('duration'))) {
6920  $out = $form->select_duration($keyprefix.$key.$keysuffix, $value, 0, 'text', 0, 1);
6921  } elseif (in_array($type, array('int', 'integer'))) {
6922  $tmp = explode(',', $size);
6923  $newsize = $tmp[0];
6924  $out = '<input type="text" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'"'.($newsize > 0 ? ' maxlength="'.$newsize.'"' : '').' value="'.dol_escape_htmltag($value).'"'.($moreparam ? $moreparam : '').($autofocusoncreate ? ' autofocus' : '').'>';
6925  } elseif (in_array($type, array('real'))) {
6926  $out = '<input type="text" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'"'.($moreparam ? $moreparam : '').($autofocusoncreate ? ' autofocus' : '').'>';
6927  } elseif (preg_match('/varchar/', $type)) {
6928  $out = '<input type="text" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'"'.($size > 0 ? ' maxlength="'.$size.'"' : '').' value="'.dol_escape_htmltag($value).'"'.($moreparam ? $moreparam : '').($autofocusoncreate ? ' autofocus' : '').'>';
6929  } elseif (in_array($type, array('email', 'mail', 'phone', 'url'))) {
6930  $out = '<input type="text" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').($autofocusoncreate ? ' autofocus' : '').'>';
6931  } elseif (preg_match('/^text/', $type)) {
6932  if (!preg_match('/search_/', $keyprefix)) { // If keyprefix is search_ or search_options_, we must just use a simple text field
6933  require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
6934  $doleditor = new DolEditor($keyprefix.$key.$keysuffix, $value, '', 200, 'dolibarr_notes', 'In', false, false, false, ROWS_5, '90%');
6935  $out = $doleditor->Create(1);
6936  } else {
6937  $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').'>';
6938  }
6939  } elseif (preg_match('/^html/', $type)) {
6940  if (!preg_match('/search_/', $keyprefix)) { // If keyprefix is search_ or search_options_, we must just use a simple text field
6941  require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
6942  $doleditor = new DolEditor($keyprefix.$key.$keysuffix, $value, '', 200, 'dolibarr_notes', 'In', false, false, !empty($conf->fckeditor->enabled) && $conf->global->FCKEDITOR_ENABLE_SOCIETE, ROWS_5, '90%');
6943  $out = $doleditor->Create(1, '', true, '', '', $moreparam, $morecss);
6944  } else {
6945  $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').'>';
6946  }
6947  } elseif ($type == 'boolean') {
6948  $checked = '';
6949  if (!empty($value)) {
6950  $checked = ' checked value="1" ';
6951  } else {
6952  $checked = ' value="1" ';
6953  }
6954  $out = '<input type="checkbox" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.$checked.' '.($moreparam ? $moreparam : '').'>';
6955  } elseif ($type == 'price') {
6956  if (!empty($value)) { // $value in memory is a php numeric, we format it into user number format.
6957  $value = price($value);
6958  }
6959  $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'> '.$langs->getCurrencySymbol($conf->currency);
6960  } elseif (preg_match('/^double(\([0-9],[0-9]\)){0,1}/', $type)) {
6961  if (!empty($value)) { // $value in memory is a php numeric, we format it into user number format.
6962  $value = price($value);
6963  }
6964  $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'> ';
6965  } elseif ($type == 'select') {
6966  $out = '';
6967  if (!empty($conf->use_javascript_ajax) && empty($conf->global->MAIN_EXTRAFIELDS_DISABLE_SELECT2)) {
6968  include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
6969  $out .= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
6970  }
6971 
6972  $out .= '<select class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '').'>';
6973  if ((!isset($this->fields[$key]['default'])) || ($this->fields[$key]['notnull'] != 1)) {
6974  $out .= '<option value="0">&nbsp;</option>';
6975  }
6976  foreach ($param['options'] as $keyb => $valb) {
6977  if ((string) $keyb == '') {
6978  continue;
6979  }
6980  if (strpos($valb, "|") !== false) {
6981  list($valb, $parent) = explode('|', $valb);
6982  }
6983  $out .= '<option value="'.$keyb.'"';
6984  $out .= (((string) $value == (string) $keyb) ? ' selected' : '');
6985  $out .= (!empty($parent) ? ' parent="'.$parent.'"' : '');
6986  $out .= '>'.$valb.'</option>';
6987  }
6988  $out .= '</select>';
6989  } elseif ($type == 'sellist') {
6990  $out = '';
6991  if (!empty($conf->use_javascript_ajax) && empty($conf->global->MAIN_EXTRAFIELDS_DISABLE_SELECT2)) {
6992  include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
6993  $out .= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
6994  }
6995 
6996  $out .= '<select class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '').'>';
6997  if (is_array($param['options'])) {
6998  $param_list = array_keys($param['options']);
6999  $InfoFieldList = explode(":", $param_list[0]);
7000  $parentName = '';
7001  $parentField = '';
7002  // 0 : tableName
7003  // 1 : label field name
7004  // 2 : key fields name (if differ of rowid)
7005  // 3 : key field parent (for dependent lists)
7006  // 4 : where clause filter on column or table extrafield, syntax field='value' or extra.field=value
7007  $keyList = (empty($InfoFieldList[2]) ? 'rowid' : $InfoFieldList[2].' as rowid');
7008 
7009  if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
7010  if (strpos($InfoFieldList[4], 'extra.') !== false) {
7011  $keyList = 'main.'.$InfoFieldList[2].' as rowid';
7012  } else {
7013  $keyList = $InfoFieldList[2].' as rowid';
7014  }
7015  }
7016  if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
7017  list($parentName, $parentField) = explode('|', $InfoFieldList[3]);
7018  $keyList .= ', '.$parentField;
7019  }
7020 
7021  $fields_label = explode('|', $InfoFieldList[1]);
7022  if (is_array($fields_label)) {
7023  $keyList .= ', ';
7024  $keyList .= implode(', ', $fields_label);
7025  }
7026 
7027  $sqlwhere = '';
7028  $sql = "SELECT ".$keyList;
7029  $sql .= " FROM ".$this->db->prefix().$InfoFieldList[0];
7030  if (!empty($InfoFieldList[4])) {
7031  // can use SELECT request
7032  if (strpos($InfoFieldList[4], '$SEL$') !== false) {
7033  $InfoFieldList[4] = str_replace('$SEL$', 'SELECT', $InfoFieldList[4]);
7034  }
7035 
7036  // current object id can be use into filter
7037  if (strpos($InfoFieldList[4], '$ID$') !== false && !empty($objectid)) {
7038  $InfoFieldList[4] = str_replace('$ID$', $objectid, $InfoFieldList[4]);
7039  } else {
7040  $InfoFieldList[4] = str_replace('$ID$', '0', $InfoFieldList[4]);
7041  }
7042 
7043  //We have to join on extrafield table
7044  if (strpos($InfoFieldList[4], 'extra') !== false) {
7045  $sql .= " as main, ".$this->db->prefix().$InfoFieldList[0]."_extrafields as extra";
7046  $sqlwhere .= " WHERE extra.fk_object=main.".$InfoFieldList[2]." AND ".$InfoFieldList[4];
7047  } else {
7048  $sqlwhere .= " WHERE ".$InfoFieldList[4];
7049  }
7050  } else {
7051  $sqlwhere .= ' WHERE 1=1';
7052  }
7053  // Some tables may have field, some other not. For the moment we disable it.
7054  if (in_array($InfoFieldList[0], array('tablewithentity'))) {
7055  $sqlwhere .= " AND entity = ".((int) $conf->entity);
7056  }
7057  $sql .= $sqlwhere;
7058  //print $sql;
7059 
7060  $sql .= ' ORDER BY '.implode(', ', $fields_label);
7061 
7062  dol_syslog(get_class($this).'::showInputField type=sellist', LOG_DEBUG);
7063  $resql = $this->db->query($sql);
7064  if ($resql) {
7065  $out .= '<option value="0">&nbsp;</option>';
7066  $num = $this->db->num_rows($resql);
7067  $i = 0;
7068  while ($i < $num) {
7069  $labeltoshow = '';
7070  $obj = $this->db->fetch_object($resql);
7071 
7072  // Several field into label (eq table:code|libelle:rowid)
7073  $notrans = false;
7074  $fields_label = explode('|', $InfoFieldList[1]);
7075  if (count($fields_label) > 1) {
7076  $notrans = true;
7077  foreach ($fields_label as $field_toshow) {
7078  $labeltoshow .= $obj->$field_toshow.' ';
7079  }
7080  } else {
7081  $labeltoshow = $obj->{$InfoFieldList[1]};
7082  }
7083  $labeltoshow = dol_trunc($labeltoshow, 45);
7084 
7085  if ($value == $obj->rowid) {
7086  foreach ($fields_label as $field_toshow) {
7087  $translabel = $langs->trans($obj->$field_toshow);
7088  if ($translabel != $obj->$field_toshow) {
7089  $labeltoshow = dol_trunc($translabel).' ';
7090  } else {
7091  $labeltoshow = dol_trunc($obj->$field_toshow).' ';
7092  }
7093  }
7094  $out .= '<option value="'.$obj->rowid.'" selected>'.$labeltoshow.'</option>';
7095  } else {
7096  if (!$notrans) {
7097  $translabel = $langs->trans($obj->{$InfoFieldList[1]});
7098  if ($translabel != $obj->{$InfoFieldList[1]}) {
7099  $labeltoshow = dol_trunc($translabel, 18);
7100  } else {
7101  $labeltoshow = dol_trunc($obj->{$InfoFieldList[1]});
7102  }
7103  }
7104  if (empty($labeltoshow)) {
7105  $labeltoshow = '(not defined)';
7106  }
7107  if ($value == $obj->rowid) {
7108  $out .= '<option value="'.$obj->rowid.'" selected>'.$labeltoshow.'</option>';
7109  }
7110 
7111  if (!empty($InfoFieldList[3]) && $parentField) {
7112  $parent = $parentName.':'.$obj->{$parentField};
7113  $isDependList = 1;
7114  }
7115 
7116  $out .= '<option value="'.$obj->rowid.'"';
7117  $out .= ($value == $obj->rowid ? ' selected' : '');
7118  $out .= (!empty($parent) ? ' parent="'.$parent.'"' : '');
7119  $out .= '>'.$labeltoshow.'</option>';
7120  }
7121 
7122  $i++;
7123  }
7124  $this->db->free($resql);
7125  } else {
7126  print 'Error in request '.$sql.' '.$this->db->lasterror().'. Check setup of extra parameters.<br>';
7127  }
7128  }
7129  $out .= '</select>';
7130  } elseif ($type == 'checkbox') {
7131  $value_arr = explode(',', $value);
7132  $out = $form->multiselectarray($keyprefix.$key.$keysuffix, (empty($param['options']) ?null:$param['options']), $value_arr, '', 0, $morecss, 0, '100%');
7133  } elseif ($type == 'radio') {
7134  $out = '';
7135  foreach ($param['options'] as $keyopt => $valopt) {
7136  $out .= '<input class="flat '.$morecss.'" type="radio" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '');
7137  $out .= ' value="'.$keyopt.'"';
7138  $out .= ' id="'.$keyprefix.$key.$keysuffix.'_'.$keyopt.'"';
7139  $out .= ($value == $keyopt ? 'checked' : '');
7140  $out .= '/><label for="'.$keyprefix.$key.$keysuffix.'_'.$keyopt.'">'.$valopt.'</label><br>';
7141  }
7142  } elseif ($type == 'chkbxlst') {
7143  if (is_array($value)) {
7144  $value_arr = $value;
7145  } else {
7146  $value_arr = explode(',', $value);
7147  }
7148 
7149  if (is_array($param['options'])) {
7150  $param_list = array_keys($param['options']);
7151  $InfoFieldList = explode(":", $param_list[0]);
7152  $parentName = '';
7153  $parentField = '';
7154  // 0 : tableName
7155  // 1 : label field name
7156  // 2 : key fields name (if differ of rowid)
7157  // 3 : key field parent (for dependent lists)
7158  // 4 : where clause filter on column or table extrafield, syntax field='value' or extra.field=value
7159  $keyList = (empty($InfoFieldList[2]) ? 'rowid' : $InfoFieldList[2].' as rowid');
7160 
7161  if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
7162  list ($parentName, $parentField) = explode('|', $InfoFieldList[3]);
7163  $keyList .= ', '.$parentField;
7164  }
7165  if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
7166  if (strpos($InfoFieldList[4], 'extra.') !== false) {
7167  $keyList = 'main.'.$InfoFieldList[2].' as rowid';
7168  } else {
7169  $keyList = $InfoFieldList[2].' as rowid';
7170  }
7171  }
7172 
7173  $fields_label = explode('|', $InfoFieldList[1]);
7174  if (is_array($fields_label)) {
7175  $keyList .= ', ';
7176  $keyList .= implode(', ', $fields_label);
7177  }
7178 
7179  $sqlwhere = '';
7180  $sql = "SELECT ".$keyList;
7181  $sql .= ' FROM '.$this->db->prefix().$InfoFieldList[0];
7182  if (!empty($InfoFieldList[4])) {
7183  // can use SELECT request
7184  if (strpos($InfoFieldList[4], '$SEL$') !== false) {
7185  $InfoFieldList[4] = str_replace('$SEL$', 'SELECT', $InfoFieldList[4]);
7186  }
7187 
7188  // current object id can be use into filter
7189  if (strpos($InfoFieldList[4], '$ID$') !== false && !empty($objectid)) {
7190  $InfoFieldList[4] = str_replace('$ID$', $objectid, $InfoFieldList[4]);
7191  } else {
7192  $InfoFieldList[4] = str_replace('$ID$', '0', $InfoFieldList[4]);
7193  }
7194 
7195  // We have to join on extrafield table
7196  if (strpos($InfoFieldList[4], 'extra') !== false) {
7197  $sql .= ' as main, '.$this->db->prefix().$InfoFieldList[0].'_extrafields as extra';
7198  $sqlwhere .= " WHERE extra.fk_object=main.".$InfoFieldList[2]." AND ".$InfoFieldList[4];
7199  } else {
7200  $sqlwhere .= " WHERE ".$InfoFieldList[4];
7201  }
7202  } else {
7203  $sqlwhere .= ' WHERE 1=1';
7204  }
7205  // Some tables may have field, some other not. For the moment we disable it.
7206  if (in_array($InfoFieldList[0], array('tablewithentity'))) {
7207  $sqlwhere .= " AND entity = ".((int) $conf->entity);
7208  }
7209  // $sql.=preg_replace('/^ AND /','',$sqlwhere);
7210  // print $sql;
7211 
7212  $sql .= $sqlwhere;
7213  dol_syslog(get_class($this).'::showInputField type=chkbxlst', LOG_DEBUG);
7214  $resql = $this->db->query($sql);
7215  if ($resql) {
7216  $num = $this->db->num_rows($resql);
7217  $i = 0;
7218 
7219  $data = array();
7220 
7221  while ($i < $num) {
7222  $labeltoshow = '';
7223  $obj = $this->db->fetch_object($resql);
7224 
7225  $notrans = false;
7226  // Several field into label (eq table:code|libelle:rowid)
7227  $fields_label = explode('|', $InfoFieldList[1]);
7228  if (count($fields_label) > 1) {
7229  $notrans = true;
7230  foreach ($fields_label as $field_toshow) {
7231  $labeltoshow .= $obj->$field_toshow.' ';
7232  }
7233  } else {
7234  $labeltoshow = $obj->{$InfoFieldList[1]};
7235  }
7236  $labeltoshow = dol_trunc($labeltoshow, 45);
7237 
7238  if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
7239  foreach ($fields_label as $field_toshow) {
7240  $translabel = $langs->trans($obj->$field_toshow);
7241  if ($translabel != $obj->$field_toshow) {
7242  $labeltoshow = dol_trunc($translabel, 18).' ';
7243  } else {
7244  $labeltoshow = dol_trunc($obj->$field_toshow, 18).' ';
7245  }
7246  }
7247 
7248  $data[$obj->rowid] = $labeltoshow;
7249  } else {
7250  if (!$notrans) {
7251  $translabel = $langs->trans($obj->{$InfoFieldList[1]});
7252  if ($translabel != $obj->{$InfoFieldList[1]}) {
7253  $labeltoshow = dol_trunc($translabel, 18);
7254  } else {
7255  $labeltoshow = dol_trunc($obj->{$InfoFieldList[1]}, 18);
7256  }
7257  }
7258  if (empty($labeltoshow)) {
7259  $labeltoshow = '(not defined)';
7260  }
7261 
7262  if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
7263  $data[$obj->rowid] = $labeltoshow;
7264  }
7265 
7266  if (!empty($InfoFieldList[3]) && $parentField) {
7267  $parent = $parentName.':'.$obj->{$parentField};
7268  $isDependList = 1;
7269  }
7270 
7271  $data[$obj->rowid] = $labeltoshow;
7272  }
7273 
7274  $i++;
7275  }
7276  $this->db->free($resql);
7277 
7278  $out = $form->multiselectarray($keyprefix.$key.$keysuffix, $data, $value_arr, '', 0, '', 0, '100%');
7279  } else {
7280  print 'Error in request '.$sql.' '.$this->db->lasterror().'. Check setup of extra parameters.<br>';
7281  }
7282  }
7283  } elseif ($type == 'link') {
7284  $param_list = array_keys($param['options']); // $param_list='ObjectName:classPath[:AddCreateButtonOrNot[:Filter[:Sortfield]]]'
7285  $param_list_array = explode(':', $param_list[0]);
7286  $showempty = (($required && $default != '') ? 0 : 1);
7287 
7288  if (!preg_match('/search_/', $keyprefix)) {
7289  if (!empty($param_list_array[2])) { // If the entry into $fields is set to add a create button
7290  if (!empty($this->fields[$key]['picto'])) {
7291  $morecss .= ' widthcentpercentminusxx';
7292  } else {
7293  $morecss .= ' widthcentpercentminusx';
7294  }
7295  } else {
7296  if (!empty($this->fields[$key]['picto'])) {
7297  $morecss .= ' widthcentpercentminusx';
7298  }
7299  }
7300  }
7301 
7302  $out = $form->selectForForms($param_list[0], $keyprefix.$key.$keysuffix, $value, $showempty, '', '', $morecss, $moreparam, 0, empty($val['disabled']) ? 0 : 1);
7303 
7304  if (!empty($param_list_array[2])) { // If the entry into $fields is set to add a create button
7305  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".
7306  list($class, $classfile) = explode(':', $param_list[0]);
7307  if (file_exists(dol_buildpath(dirname(dirname($classfile)).'/card.php'))) {
7308  $url_path = dol_buildpath(dirname(dirname($classfile)).'/card.php', 1);
7309  } else {
7310  $url_path = dol_buildpath(dirname(dirname($classfile)).'/'.strtolower($class).'_card.php', 1);
7311  }
7312  $paramforthenewlink = '';
7313  $paramforthenewlink .= (GETPOSTISSET('action') ? '&action='.GETPOST('action', 'aZ09') : '');
7314  $paramforthenewlink .= (GETPOSTISSET('id') ? '&id='.GETPOST('id', 'int') : '');
7315  $paramforthenewlink .= (GETPOSTISSET('origin') ? '&origin='.GETPOST('origin', 'aZ09') : '');
7316  $paramforthenewlink .= (GETPOSTISSET('originid') ? '&originid='.GETPOST('originid', 'int') : '');
7317  $paramforthenewlink .= '&fk_'.strtolower($class).'=--IDFORBACKTOPAGE--';
7318  // TODO Add Javascript code to add input fields already filled into $paramforthenewlink so we won't loose them when going back to main page
7319  $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>';
7320  }
7321  }
7322  } elseif ($type == 'password') {
7323  // If prefix is 'search_', field is used as a filter, we use a common text field.
7324  $out = '<input type="'.($keyprefix == 'search_' ? 'text' : 'password').'" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'>';
7325  } elseif ($type == 'array') {
7326  $newval = $val;
7327  $newval['type'] = 'varchar(256)';
7328 
7329  $out = '';
7330  if (!empty($value)) {
7331  foreach ($value as $option) {
7332  $out .= '<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
7333  $out .= $this->showInputField($newval, $keyprefix.$key.$keysuffix.'[]', $option, $moreparam, '', '', $morecss).'<br></span>';
7334  }
7335  }
7336  $out .= '<a id="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_add" href="javascript:;"><span class="fa fa-plus-circle valignmiddle"></span></a>';
7337 
7338  $newInput = '<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
7339  $newInput .= $this->showInputField($newval, $keyprefix.$key.$keysuffix.'[]', '', $moreparam, '', '', $morecss).'<br></span>';
7340 
7341  if (!empty($conf->use_javascript_ajax)) {
7342  $out .= '
7343  <script>
7344  $(document).ready(function() {
7345  $("a#'.dol_escape_js($keyprefix.$key.$keysuffix).'_add").click(function() {
7346  $("'.dol_escape_js($newInput).'").insertBefore(this);
7347  });
7348 
7349  $(document).on("click", "a.'.dol_escape_js($keyprefix.$key.$keysuffix).'_del", function() {
7350  $(this).parent().remove();
7351  });
7352  });
7353  </script>';
7354  }
7355  }
7356  if (!empty($hidden)) {
7357  $out = '<input type="hidden" value="'.$value.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'"/>';
7358  }
7359 
7360  if ($isDependList==1) {
7361  $out .= $this->getJSListDependancies('_common');
7362  }
7363  /* Add comments
7364  if ($type == 'date') $out.=' (YYYY-MM-DD)';
7365  elseif ($type == 'datetime') $out.=' (YYYY-MM-DD HH:MM:SS)';
7366  */
7367 
7368  // Display error message for field
7369  if (!empty($fieldValidationErrorMsg) && function_exists('getFieldErrorIcon')) {
7370  $out .= ' '.getFieldErrorIcon($fieldValidationErrorMsg);
7371  }
7372 
7373  return $out;
7374  }
7375 
7389  public function showOutputField($val, $key, $value, $moreparam = '', $keysuffix = '', $keyprefix = '', $morecss = '')
7390  {
7391  global $conf, $langs, $form;
7392 
7393  if (!is_object($form)) {
7394  require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
7395  $form = new Form($this->db);
7396  }
7397 
7398  $objectid = $this->id; // Not used ???
7399 
7400  $label = empty($val['label']) ? '' : $val['label'];
7401  $type = empty($val['type']) ? '' : $val['type'];
7402  $size = empty($val['css']) ? '' : $val['css'];
7403  $reg = array();
7404 
7405  // Convert var to be able to share same code than showOutputField of extrafields
7406  if (preg_match('/varchar\((\d+)\)/', $type, $reg)) {
7407  $type = 'varchar'; // convert varchar(xx) int varchar
7408  $size = $reg[1];
7409  } elseif (preg_match('/varchar/', $type)) {
7410  $type = 'varchar'; // convert varchar(xx) int varchar
7411  }
7412  if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
7413  $type = 'select';
7414  }
7415  if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) {
7416  $type = 'link';
7417  }
7418 
7419  $default = empty($val['default']) ? '' : $val['default'];
7420  $computed = empty($val['computed']) ? '' : $val['computed'];
7421  $unique = empty($val['unique']) ? '' : $val['unique'];
7422  $required = empty($val['required']) ? '' : $val['required'];
7423  $param = array();
7424  $param['options'] = array();
7425 
7426  if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
7427  $param['options'] = $val['arrayofkeyval'];
7428  }
7429  if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) {
7430  $type = 'link';
7431  $param['options'] = array($reg[1].':'.$reg[2]=>$reg[1].':'.$reg[2]);
7432  } elseif (preg_match('/^sellist:(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
7433  $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3].':'.$reg[4] => 'N');
7434  $type = 'sellist';
7435  } elseif (preg_match('/^sellist:(.*):(.*):(.*)/i', $val['type'], $reg)) {
7436  $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3] => 'N');
7437  $type = 'sellist';
7438  } elseif (preg_match('/^sellist:(.*):(.*)/i', $val['type'], $reg)) {
7439  $param['options'] = array($reg[1].':'.$reg[2] => 'N');
7440  $type = 'sellist';
7441  }
7442 
7443  $langfile = empty($val['langfile']) ? '' : $val['langfile'];
7444  $list = (empty($val['list']) ? '' : $val['list']);
7445  $help = (empty($val['help']) ? '' : $val['help']);
7446  $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)
7447 
7448  if ($hidden) {
7449  return '';
7450  }
7451 
7452  // If field is a computed field, value must become result of compute
7453  if ($computed) {
7454  // Make the eval of compute string
7455  //var_dump($computed);
7456  $value = dol_eval($computed, 1, 0, '');
7457  }
7458 
7459  if (empty($morecss)) {
7460  if ($type == 'date') {
7461  $morecss = 'minwidth100imp';
7462  } elseif ($type == 'datetime' || $type == 'timestamp') {
7463  $morecss = 'minwidth200imp';
7464  } elseif (in_array($type, array('int', 'double', 'price'))) {
7465  $morecss = 'maxwidth75';
7466  } elseif ($type == 'url') {
7467  $morecss = 'minwidth400';
7468  } elseif ($type == 'boolean') {
7469  $morecss = '';
7470  } else {
7471  if (is_numeric($size) && round($size) < 12) {
7472  $morecss = 'minwidth100';
7473  } elseif (is_numeric($size) && round($size) <= 48) {
7474  $morecss = 'minwidth200';
7475  } else {
7476  $morecss = 'minwidth400';
7477  }
7478  }
7479  }
7480 
7481  // Format output value differently according to properties of field
7482  if (in_array($key, array('rowid', 'ref')) && method_exists($this, 'getNomUrl')) {
7483  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.
7484  $value = $this->getNomUrl(1, '', 0, '', 1);
7485  }
7486  } elseif ($key == 'status' && method_exists($this, 'getLibStatut')) {
7487  $value = $this->getLibStatut(3);
7488  } elseif ($type == 'date') {
7489  if (!empty($value)) {
7490  $value = dol_print_date($value, 'day'); // We suppose dates without time are always gmt (storage of course + output)
7491  } else {
7492  $value = '';
7493  }
7494  } elseif ($type == 'datetime' || $type == 'timestamp') {
7495  if (!empty($value)) {
7496  $value = dol_print_date($value, 'dayhour', 'tzuserrel');
7497  } else {
7498  $value = '';
7499  }
7500  } elseif ($type == 'duration') {
7501  include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
7502  if (!is_null($value) && $value !== '') {
7503  $value = convertSecondToTime($value, 'allhourmin');
7504  }
7505  } elseif ($type == 'double' || $type == 'real') {
7506  if (!is_null($value) && $value !== '') {
7507  $value = price($value);
7508  }
7509  } elseif ($type == 'boolean') {
7510  $checked = '';
7511  if (!empty($value)) {
7512  $checked = ' checked ';
7513  }
7514  $value = '<input type="checkbox" '.$checked.' '.($moreparam ? $moreparam : '').' readonly disabled>';
7515  } elseif ($type == 'mail' || $type == 'email') {
7516  $value = dol_print_email($value, 0, 0, 0, 64, 1, 1);
7517  } elseif ($type == 'url') {
7518  $value = dol_print_url($value, '_blank', 32, 1);
7519  } elseif ($type == 'phone') {
7520  $value = dol_print_phone($value, '', 0, 0, '', '&nbsp;', 'phone');
7521  } elseif ($type == 'price') {
7522  if (!is_null($value) && $value !== '') {
7523  $value = price($value, 0, $langs, 0, 0, -1, $conf->currency);
7524  }
7525  } elseif ($type == 'select') {
7526  $value = isset($param['options'][$value])?$param['options'][$value]:'';
7527  } elseif ($type == 'sellist') {
7528  $param_list = array_keys($param['options']);
7529  $InfoFieldList = explode(":", $param_list[0]);
7530 
7531  $selectkey = "rowid";
7532  $keyList = 'rowid';
7533 
7534  if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
7535  $selectkey = $InfoFieldList[2];
7536  $keyList = $InfoFieldList[2].' as rowid';
7537  }
7538 
7539  $fields_label = explode('|', $InfoFieldList[1]);
7540  if (is_array($fields_label)) {
7541  $keyList .= ', ';
7542  $keyList .= implode(', ', $fields_label);
7543  }
7544 
7545  $sql = "SELECT ".$keyList;
7546  $sql .= ' FROM '.$this->db->prefix().$InfoFieldList[0];
7547  if (strpos($InfoFieldList[4], 'extra') !== false) {
7548  $sql .= ' as main';
7549  }
7550  if ($selectkey == 'rowid' && empty($value)) {
7551  $sql .= " WHERE ".$selectkey." = 0";
7552  } elseif ($selectkey == 'rowid') {
7553  $sql .= " WHERE ".$selectkey." = ".((int) $value);
7554  } else {
7555  $sql .= " WHERE ".$selectkey." = '".$this->db->escape($value)."'";
7556  }
7557 
7558  //$sql.= ' AND entity = '.$conf->entity;
7559 
7560  dol_syslog(get_class($this).':showOutputField:$type=sellist', LOG_DEBUG);
7561  $resql = $this->db->query($sql);
7562  if ($resql) {
7563  $value = ''; // value was used, so now we reste it to use it to build final output
7564  $numrows = $this->db->num_rows($resql);
7565  if ($numrows) {
7566  $obj = $this->db->fetch_object($resql);
7567 
7568  // Several field into label (eq table:code|libelle:rowid)
7569  $fields_label = explode('|', $InfoFieldList[1]);
7570 
7571  if (is_array($fields_label) && count($fields_label) > 1) {
7572  foreach ($fields_label as $field_toshow) {
7573  $translabel = '';
7574  if (!empty($obj->$field_toshow)) {
7575  $translabel = $langs->trans($obj->$field_toshow);
7576  }
7577  if ($translabel != $field_toshow) {
7578  $value .= dol_trunc($translabel, 18).' ';
7579  } else {
7580  $value .= $obj->$field_toshow.' ';
7581  }
7582  }
7583  } else {
7584  $translabel = '';
7585  if (!empty($obj->{$InfoFieldList[1]})) {
7586  $translabel = $langs->trans($obj->{$InfoFieldList[1]});
7587  }
7588  if ($translabel != $obj->{$InfoFieldList[1]}) {
7589  $value = dol_trunc($translabel, 18);
7590  } else {
7591  $value = $obj->{$InfoFieldList[1]};
7592  }
7593  }
7594  }
7595  } else {
7596  dol_syslog(get_class($this).'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
7597  }
7598  } elseif ($type == 'radio') {
7599  $value = $param['options'][$value];
7600  } elseif ($type == 'checkbox') {
7601  $value_arr = explode(',', $value);
7602  $value = '';
7603  if (is_array($value_arr) && count($value_arr) > 0) {
7604  $toprint = array();
7605  foreach ($value_arr as $keyval => $valueval) {
7606  $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">'.$param['options'][$valueval].'</li>';
7607  }
7608  $value = '<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
7609  }
7610  } elseif ($type == 'chkbxlst') {
7611  $value_arr = explode(',', $value);
7612 
7613  $param_list = array_keys($param['options']);
7614  $InfoFieldList = explode(":", $param_list[0]);
7615 
7616  $selectkey = "rowid";
7617  $keyList = 'rowid';
7618 
7619  if (count($InfoFieldList) >= 3) {
7620  $selectkey = $InfoFieldList[2];
7621  $keyList = $InfoFieldList[2].' as rowid';
7622  }
7623 
7624  $fields_label = explode('|', $InfoFieldList[1]);
7625  if (is_array($fields_label)) {
7626  $keyList .= ', ';
7627  $keyList .= implode(', ', $fields_label);
7628  }
7629 
7630  $sql = "SELECT ".$keyList;
7631  $sql .= ' FROM '.$this->db->prefix().$InfoFieldList[0];
7632  if (strpos($InfoFieldList[4], 'extra') !== false) {
7633  $sql .= ' as main';
7634  }
7635  // $sql.= " WHERE ".$selectkey."='".$this->db->escape($value)."'";
7636  // $sql.= ' AND entity = '.$conf->entity;
7637 
7638  dol_syslog(get_class($this).':showOutputField:$type=chkbxlst', LOG_DEBUG);
7639  $resql = $this->db->query($sql);
7640  if ($resql) {
7641  $value = ''; // value was used, so now we reste it to use it to build final output
7642  $toprint = array();
7643  while ($obj = $this->db->fetch_object($resql)) {
7644  // Several field into label (eq table:code|libelle:rowid)
7645  $fields_label = explode('|', $InfoFieldList[1]);
7646  if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
7647  if (is_array($fields_label) && count($fields_label) > 1) {
7648  foreach ($fields_label as $field_toshow) {
7649  $translabel = '';
7650  if (!empty($obj->$field_toshow)) {
7651  $translabel = $langs->trans($obj->$field_toshow);
7652  }
7653  if ($translabel != $field_toshow) {
7654  $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">'.dol_trunc($translabel, 18).'</li>';
7655  } else {
7656  $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">'.$obj->$field_toshow.'</li>';
7657  }
7658  }
7659  } else {
7660  $translabel = '';
7661  if (!empty($obj->{$InfoFieldList[1]})) {
7662  $translabel = $langs->trans($obj->{$InfoFieldList[1]});
7663  }
7664  if ($translabel != $obj->{$InfoFieldList[1]}) {
7665  $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">'.dol_trunc($translabel, 18).'</li>';
7666  } else {
7667  $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">'.$obj->{$InfoFieldList[1]}.'</li>';
7668  }
7669  }
7670  }
7671  }
7672  $value = '<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
7673  } else {
7674  dol_syslog(get_class($this).'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
7675  }
7676  } elseif ($type == 'link') {
7677  $out = '';
7678 
7679  // only if something to display (perf)
7680  if ($value) {
7681  $param_list = array_keys($param['options']); // $param_list='ObjectName:classPath'
7682 
7683  $InfoFieldList = explode(":", $param_list[0]);
7684  $classname = $InfoFieldList[0];
7685  $classpath = $InfoFieldList[1];
7686  $getnomurlparam = (empty($InfoFieldList[2]) ? 3 : $InfoFieldList[2]);
7687  $getnomurlparam2 = (empty($InfoFieldList[4]) ? '' : $InfoFieldList[4]);
7688  if (!empty($classpath)) {
7689  dol_include_once($InfoFieldList[1]);
7690  if ($classname && class_exists($classname)) {
7691  $object = new $classname($this->db);
7692  if ($object->element === 'product') { // Special cas for product because default valut of fetch are wrong
7693  $result = $object->fetch($value, '', '', '', 0, 1, 1);
7694  } else {
7695  $result = $object->fetch($value);
7696  }
7697  if ($result > 0) {
7698  $value = $object->getNomUrl($getnomurlparam, $getnomurlparam2);
7699  } else {
7700  $value = '';
7701  }
7702  }
7703  } else {
7704  dol_syslog('Error bad setup of extrafield', LOG_WARNING);
7705  return 'Error bad setup of extrafield';
7706  }
7707  } else {
7708  $value = '';
7709  }
7710  } elseif ($type == 'password') {
7711  $value = preg_replace('/./i', '*', $value);
7712  } elseif ($type == 'array') {
7713  $value = implode('<br>', $value);
7714  } else { // text|html|varchar
7715  $value = dol_htmlentitiesbr($value);
7716  }
7717 
7718  //print $type.'-'.$size.'-'.$value;
7719  $out = $value;
7720 
7721  return $out;
7722  }
7723 
7730  public function clearFieldError($fieldKey)
7731  {
7732  $this->error = '';
7733  unset($this->validateFieldsErrors[$fieldKey]);
7734  }
7735 
7743  public function setFieldError($fieldKey, $msg = '')
7744  {
7745  global $langs;
7746  if (empty($msg)) { $msg = $langs->trans("UnknowError"); }
7747 
7748  $this->error = $this->validateFieldsErrors[$fieldKey] = $msg;
7749  }
7750 
7757  public function getFieldError($fieldKey)
7758  {
7759  if (!empty($this->validateFieldsErrors[$fieldKey])) {
7760  return $this->validateFieldsErrors[$fieldKey];
7761  }
7762  return '';
7763  }
7764 
7773  public function validateField($val, $fieldKey, $fieldValue)
7774  {
7775  global $langs;
7776 
7777  if (!class_exists('Validate')) { require_once DOL_DOCUMENT_ROOT . '/core/class/validate.class.php'; }
7778 
7779  $this->clearFieldError($fieldKey);
7780 
7781  if (!isset($val[$fieldKey])) {
7782  $this->setFieldError($fieldKey, $langs->trans('FieldNotFoundInObject'));
7783  return false;
7784  }
7785 
7786  $param = array();
7787  $param['options'] = array();
7788  $type = $val[$fieldKey]['type'];
7789 
7790  $required = false;
7791  if (isset($val[$fieldKey]['notnull']) && $val[$fieldKey]['notnull'] === 1) {
7792  // 'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0).
7793  $required = true;
7794  }
7795 
7796  $maxSize = 0;
7797  $minSize = 0;
7798 
7799  //
7800  // PREPARE Elements
7801  //
7802 
7803  // Convert var to be able to share same code than showOutputField of extrafields
7804  if (preg_match('/varchar\((\d+)\)/', $type, $reg)) {
7805  $type = 'varchar'; // convert varchar(xx) int varchar
7806  $maxSize = $reg[1];
7807  } elseif (preg_match('/varchar/', $type)) {
7808  $type = 'varchar'; // convert varchar(xx) int varchar
7809  }
7810 
7811  if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
7812  $type = 'select';
7813  }
7814 
7815  if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) {
7816  $type = 'link';
7817  }
7818 
7819  if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
7820  $param['options'] = $val['arrayofkeyval'];
7821  }
7822 
7823  if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) {
7824  $type = 'link';
7825  $param['options'] = array($reg[1].':'.$reg[2]=>$reg[1].':'.$reg[2]);
7826  } elseif (preg_match('/^sellist:(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
7827  $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3].':'.$reg[4] => 'N');
7828  $type = 'sellist';
7829  } elseif (preg_match('/^sellist:(.*):(.*):(.*)/i', $val['type'], $reg)) {
7830  $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3] => 'N');
7831  $type = 'sellist';
7832  } elseif (preg_match('/^sellist:(.*):(.*)/i', $val['type'], $reg)) {
7833  $param['options'] = array($reg[1].':'.$reg[2] => 'N');
7834  $type = 'sellist';
7835  }
7836 
7837  //
7838  // TEST Value
7839  //
7840 
7841  // Use Validate class to allow external Modules to use data validation part instead of concentrate all test here (factoring) or just for reuse
7842  $validate = new Validate($this->db, $langs);
7843 
7844 
7845  // little trick : to perform tests with good performances sort tests by quick to low
7846 
7847  //
7848  // COMMON TESTS
7849  //
7850 
7851  // Required test and empty value
7852  if ($required && !$validate->isNotEmptyString($fieldValue)) {
7853  $this->setFieldError($fieldKey, $validate->error);
7854  return false;
7855  } elseif (!$required && !$validate->isNotEmptyString($fieldValue)) {
7856  // if no value sent and the field is not mandatory, no need to perform tests
7857  return true;
7858  }
7859 
7860  // MAX Size test
7861  if (!empty($maxSize) && !$validate->isMaxLength($fieldValue, $maxSize)) {
7862  $this->setFieldError($fieldKey, $validate->error);
7863  return false;
7864  }
7865 
7866  // MIN Size test
7867  if (!empty($minSize) && !$validate->isMinLength($fieldValue, $minSize)) {
7868  $this->setFieldError($fieldKey, $validate->error);
7869  return false;
7870  }
7871 
7872  //
7873  // TESTS for TYPE
7874  //
7875 
7876  if (in_array($type, array('date', 'datetime', 'timestamp'))) {
7877  if (!$validate->isTimestamp($fieldValue)) {
7878  $this->setFieldError($fieldKey, $validate->error);
7879  return false;
7880  } else { return true; }
7881  } elseif ($type == 'duration') {
7882  if (!$validate->isDuration($fieldValue)) {
7883  $this->setFieldError($fieldKey, $validate->error);
7884  return false;
7885  } else { return true; }
7886  } elseif (in_array($type, array('double', 'real', 'price'))) {
7887  // is numeric
7888  if (!$validate->isNumeric($fieldValue)) {
7889  $this->setFieldError($fieldKey, $validate->error);
7890  return false;
7891  } else { return true; }
7892  } elseif ($type == 'boolean') {
7893  if (!$validate->isBool($fieldValue)) {
7894  $this->setFieldError($fieldKey, $validate->error);
7895  return false;
7896  } else { return true; }
7897  } elseif ($type == 'mail') {
7898  if (!$validate->isEmail($fieldValue)) {
7899  $this->setFieldError($fieldKey, $validate->error);
7900  return false;
7901  }
7902  } elseif ($type == 'url') {
7903  if (!$validate->isUrl($fieldValue)) {
7904  $this->setFieldError($fieldKey, $validate->error);
7905  return false;
7906  } else { return true; }
7907  } elseif ($type == 'phone') {
7908  if (!$validate->isPhone($fieldValue)) {
7909  $this->setFieldError($fieldKey, $validate->error);
7910  return false;
7911  } else { return true; }
7912  } elseif ($type == 'select' || $type == 'radio') {
7913  if (!isset($param['options'][$fieldValue])) {
7914  $this->error = $langs->trans('RequireValidValue');
7915  return false;
7916  } else { return true; }
7917  } elseif ($type == 'sellist' || $type == 'chkbxlst') {
7918  $param_list = array_keys($param['options']);
7919  $InfoFieldList = explode(":", $param_list[0]);
7920  $value_arr = explode(',', $fieldValue);
7921  $value_arr = array_map(array($this->db, 'escape'), $value_arr);
7922 
7923  $selectkey = "rowid";
7924  if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
7925  $selectkey = $InfoFieldList[2];
7926  }
7927 
7928  if (!$validate->isInDb($value_arr, $InfoFieldList[0], $selectkey)) {
7929  $this->setFieldError($fieldKey, $validate->error);
7930  return false;
7931  } else { return true; }
7932  } elseif ($type == 'link') {
7933  $param_list = array_keys($param['options']); // $param_list='ObjectName:classPath'
7934  $InfoFieldList = explode(":", $param_list[0]);
7935  $classname = $InfoFieldList[0];
7936  $classpath = $InfoFieldList[1];
7937  if (!$validate->isFetchable($fieldValue, $classname, $classpath)) {
7938  $this->setFieldError($fieldKey, $validate->error);
7939  return false;
7940  } else { return true; }
7941  }
7942 
7943  // if no test failled all is ok
7944  return true;
7945  }
7946 
7960  public function showOptionals($extrafields, $mode = 'view', $params = null, $keysuffix = '', $keyprefix = '', $onetrtd = 0, $display_type = 'card')
7961  {
7962  global $db, $conf, $langs, $action, $form, $hookmanager;
7963 
7964  if (!is_object($form)) {
7965  $form = new Form($db);
7966  }
7967  if (!is_object($extrafields)) {
7968  dol_syslog('Bad parameter extrafields for showOptionals', LOG_ERR);
7969  return 'Bad parameter extrafields for showOptionals';
7970  }
7971  if (!is_array($extrafields->attributes[$this->table_element])) {
7972  dol_syslog("extrafields->attributes was not loaded with extrafields->fetch_name_optionals_label(table_element);", LOG_WARNING);
7973  }
7974 
7975  $out = '';
7976 
7977  $parameters = array();
7978  $reshook = $hookmanager->executeHooks('showOptionals', $parameters, $this, $action); // Note that $action and $object may have been modified by hook
7979  if (empty($reshook)) {
7980  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) {
7981  $out .= "\n";
7982  $out .= '<!-- commonobject:showOptionals --> ';
7983  $out .= "\n";
7984 
7985  $extrafields_collapse_num = '';
7986  $e = 0;
7987  foreach ($extrafields->attributes[$this->table_element]['label'] as $key => $label) {
7988  // Show only the key field in params
7989  if (is_array($params) && array_key_exists('onlykey', $params) && $key != $params['onlykey']) {
7990  continue;
7991  }
7992 
7993  // Test on 'enabled' ('enabled' is different than 'list' = 'visibility')
7994  $enabled = 1;
7995  if ($enabled && isset($extrafields->attributes[$this->table_element]['enabled'][$key])) {
7996  $enabled = dol_eval($extrafields->attributes[$this->table_element]['enabled'][$key], 1, 1, '1');
7997  }
7998  if (empty($enabled)) {
7999  continue;
8000  }
8001 
8002  $visibility = 1;
8003  if ($visibility && isset($extrafields->attributes[$this->table_element]['list'][$key])) {
8004  $visibility = dol_eval($extrafields->attributes[$this->table_element]['list'][$key], 1, 1, '1');
8005  }
8006 
8007  $perms = 1;
8008  if ($perms && isset($extrafields->attributes[$this->table_element]['perms'][$key])) {
8009  $perms = dol_eval($extrafields->attributes[$this->table_element]['perms'][$key], 1, 1, '1');
8010  }
8011 
8012  if (($mode == 'create') && abs($visibility) != 1 && abs($visibility) != 3) {
8013  continue; // <> -1 and <> 1 and <> 3 = not visible on forms, only on list
8014  } elseif (($mode == 'edit') && abs($visibility) != 1 && abs($visibility) != 3 && abs($visibility) != 4) {
8015  continue; // <> -1 and <> 1 and <> 3 = not visible on forms, only on list and <> 4 = not visible at the creation
8016  } elseif ($mode == 'view' && empty($visibility)) {
8017  continue;
8018  }
8019  if (empty($perms)) {
8020  continue;
8021  }
8022  // Load language if required
8023  if (!empty($extrafields->attributes[$this->table_element]['langfile'][$key])) {
8024  $langs->load($extrafields->attributes[$this->table_element]['langfile'][$key]);
8025  }
8026 
8027  $colspan = 0;
8028  if (is_array($params) && count($params) > 0 && $display_type=='card') {
8029  if (array_key_exists('cols', $params)) {
8030  $colspan = $params['cols'];
8031  } elseif (array_key_exists('colspan', $params)) { // For backward compatibility. Use cols instead now.
8032  $reg = array();
8033  if (preg_match('/colspan="(\d+)"/', $params['colspan'], $reg)) {
8034  $colspan = $reg[1];
8035  } else {
8036  $colspan = $params['colspan'];
8037  }
8038  }
8039  }
8040  $colspan = intval($colspan);
8041 
8042  switch ($mode) {
8043  case "view":
8044  $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
8045  break;
8046  case "create":
8047  case "edit":
8048  // We get the value of property found with GETPOST so it takes into account:
8049  // default values overwrite, restore back to list link, ... (but not 'default value in database' of field)
8050  $check = 'alphanohtml';
8051  if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('html', 'text'))) {
8052  $check = 'restricthtml';
8053  }
8054  $getposttemp = GETPOST($keyprefix.'options_'.$key.$keysuffix, $check, 3); // GETPOST can get value from GET, POST or setup of default values overwrite.
8055  // GETPOST("options_" . $key) can be 'abc' or array(0=>'abc')
8056  if (is_array($getposttemp) || $getposttemp != '' || GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix)) {
8057  if (is_array($getposttemp)) {
8058  // $getposttemp is an array but following code expects a comma separated string
8059  $value = implode(",", $getposttemp);
8060  } else {
8061  $value = $getposttemp;
8062  }
8063  } else {
8064  $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.
8065  }
8066  //var_dump($keyprefix.' - '.$key.' - '.$keysuffix.' - '.$keyprefix.'options_'.$key.$keysuffix.' - '.$this->array_options["options_".$key.$keysuffix].' - '.$getposttemp.' - '.$value);
8067  break;
8068  }
8069 
8070  // Output value of the current field
8071  if ($extrafields->attributes[$this->table_element]['type'][$key] == 'separate') {
8072  $extrafields_collapse_num = '';
8073  $extrafield_param = $extrafields->attributes[$this->table_element]['param'][$key];
8074  if (!empty($extrafield_param) && is_array($extrafield_param)) {
8075  $extrafield_param_list = array_keys($extrafield_param['options']);
8076 
8077  if (count($extrafield_param_list) > 0) {
8078  $extrafield_collapse_display_value = intval($extrafield_param_list[0]);
8079 
8080  if ($extrafield_collapse_display_value == 1 || $extrafield_collapse_display_value == 2) {
8081  $extrafields_collapse_num = $extrafields->attributes[$this->table_element]['pos'][$key];
8082  }
8083  }
8084  }
8085 
8086  // if colspan=0 or 1, the second column is not extended, so the separator must be on 2 columns
8087  $out .= $extrafields->showSeparator($key, $this, ($colspan ? $colspan + 1 : 2), $display_type, $mode);
8088  } else {
8089  $class = (!empty($extrafields->attributes[$this->table_element]['hidden'][$key]) ? 'hideobject ' : '');
8090  $csstyle = '';
8091  if (is_array($params) && count($params) > 0) {
8092  if (array_key_exists('class', $params)) {
8093  $class .= $params['class'].' ';
8094  }
8095  if (array_key_exists('style', $params)) {
8096  $csstyle = $params['style'];
8097  }
8098  }
8099 
8100  // add html5 elements
8101  $domData = ' data-element="extrafield"';
8102  $domData .= ' data-targetelement="'.$this->element.'"';
8103  $domData .= ' data-targetid="'.$this->id.'"';
8104 
8105  $html_id = (empty($this->id) ? '' : 'extrarow-'.$this->element.'_'.$key.'_'.$this->id);
8106  if ($display_type=='card') {
8107  if (!empty($conf->global->MAIN_EXTRAFIELDS_USE_TWO_COLUMS) && ($e % 2) == 0) {
8108  $colspan = 0;
8109  }
8110 
8111  if ($action == 'selectlines') {
8112  $colspan++;
8113  }
8114  }
8115 
8116  // Convert date into timestamp format (value in memory must be a timestamp)
8117  if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('date'))) {
8118  $datenotinstring = null;
8119  if (array_key_exists('options_'.$key, $this->array_options)) {
8120  $datenotinstring = $this->array_options['options_'.$key];
8121  if (!is_numeric($this->array_options['options_'.$key])) { // For backward compatibility
8122  $datenotinstring = $this->db->jdate($datenotinstring);
8123  }
8124  }
8125  $datekey = $keyprefix.'options_'.$key.$keysuffix;
8126  $value = (GETPOSTISSET($datekey)) ? dol_mktime(12, 0, 0, GETPOST($datekey.'month', 'int', 3), GETPOST($datekey.'day', 'int', 3), GETPOST($datekey.'year', 'int', 3)) : $datenotinstring;
8127  }
8128  if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('datetime'))) {
8129  $datenotinstring = null;
8130  if (array_key_exists('options_'.$key, $this->array_options)) {
8131  $datenotinstring = $this->array_options['options_'.$key];
8132  if (!is_numeric($this->array_options['options_'.$key])) { // For backward compatibility
8133  $datenotinstring = $this->db->jdate($datenotinstring);
8134  }
8135  }
8136  $timekey = $keyprefix.'options_'.$key.$keysuffix;
8137  $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;
8138  }
8139  // Convert float submited string into real php numeric (value in memory must be a php numeric)
8140  if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('price', 'double'))) {
8141  if (GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix) || $value) {
8142  $value = price2num($value);
8143  } elseif (isset($this->array_options['options_'.$key])) {
8144  $value = $this->array_options['options_'.$key];
8145  }
8146  }
8147 
8148  // HTML, text, select, integer and varchar: take into account default value in database if in create mode
8149  if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('html', 'text', 'varchar', 'select', 'int', 'boolean'))) {
8150  if ($action == 'create') {
8151  $value = (GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix) || $value) ? $value : $extrafields->attributes[$this->table_element]['default'][$key];
8152  }
8153  }
8154 
8155  $labeltoshow = $langs->trans($label);
8156  $helptoshow = $langs->trans($extrafields->attributes[$this->table_element]['help'][$key]);
8157 
8158  if ($display_type == 'card') {
8159  $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.' >';
8160  if (!empty($conf->global->MAIN_VIEW_LINE_NUMBER) && ($action == 'view' || $action == 'valid' || $action == 'editline' || $action == 'confirm_valid' || $action == 'confirm_cancel')) {
8161  $out .= '<td></td>';
8162  }
8163  $out .= '<td class="titlefieldcreate wordbreak';
8164  } elseif ($display_type == 'line') {
8165  $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.' >';
8166  $out .= '<div style="display: inline-block; padding-right:4px" class="titlefieldcreate wordbreak';
8167  }
8168  //$out .= "titlefield";
8169  //if (GETPOST('action', 'restricthtml') == 'create') $out.='create';
8170  // BUG #11554 : For public page, use red dot for required fields, instead of bold label
8171  $tpl_context = isset($params["tpl_context"]) ? $params["tpl_context"] : "none";
8172  if ($tpl_context != "public") { // Public page : red dot instead of fieldrequired characters
8173  if ($mode != 'view' && !empty($extrafields->attributes[$this->table_element]['required'][$key])) {
8174  $out .= ' fieldrequired';
8175  }
8176  }
8177  $out .= '">';
8178  if ($tpl_context == "public") { // Public page : red dot instead of fieldrequired characters
8179  if (!empty($extrafields->attributes[$this->table_element]['help'][$key])) {
8180  $out .= $form->textwithpicto($labeltoshow, $helptoshow);
8181  } else {
8182  $out .= $labeltoshow;
8183  }
8184  if ($mode != 'view' && !empty($extrafields->attributes[$this->table_element]['required'][$key])) {
8185  $out .= '&nbsp;<span style="color: red">*</span>';
8186  }
8187  } else {
8188  if (!empty($extrafields->attributes[$this->table_element]['help'][$key])) {
8189  $out .= $form->textwithpicto($labeltoshow, $helptoshow);
8190  } else {
8191  $out .= $labeltoshow;
8192  }
8193  }
8194 
8195  $out .= ($display_type == 'card' ? '</td>' : '</div>');
8196 
8197  $html_id = !empty($this->id) ? $this->element.'_extras_'.$key.'_'.$this->id : '';
8198  if ($display_type == 'card') {
8199  // 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
8200  $out .= '<td '.($html_id ? 'id="'.$html_id.'" ' : '').' class="valuefieldcreate '.$this->element.'_extras_'.$key.'" '.($colspan ? ' colspan="'.$colspan.'"' : '').'>';
8201  } elseif ($display_type == 'line') {
8202  $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].'">';
8203  }
8204 
8205  switch ($mode) {
8206  case "view":
8207  $out .= $extrafields->showOutputField($key, $value, '', $this->table_element);
8208  break;
8209  case "create":
8210  $out .= $extrafields->showInputField($key, $value, '', $keysuffix, '', 0, $this->id, $this->table_element);
8211  break;
8212  case "edit":
8213  $out .= $extrafields->showInputField($key, $value, '', $keysuffix, '', 0, $this->id, $this->table_element);
8214  break;
8215  }
8216 
8217  $out .= ($display_type=='card' ? '</td>' : '</div>');
8218 
8219  if (!empty($conf->global->MAIN_EXTRAFIELDS_USE_TWO_COLUMS) && (($e % 2) == 1)) {
8220  $out .= ($display_type=='card' ? '</tr>' : '</div>');
8221  } else {
8222  $out .= ($display_type=='card' ? '</tr>' : '</div>');
8223  }
8224  $e++;
8225  }
8226  }
8227  $out .= "\n";
8228  // Add code to manage list depending on others
8229  if (!empty($conf->use_javascript_ajax)) {
8230  $out .= $this->getJSListDependancies();
8231  }
8232 
8233  $out .= '<!-- commonobject:showOptionals end --> '."\n";
8234  }
8235  }
8236 
8237  $out .= $hookmanager->resPrint;
8238 
8239  return $out;
8240  }
8241 
8246  public function getJSListDependancies($type = '_extra')
8247  {
8248  $out = '
8249  <script>
8250  jQuery(document).ready(function() {
8251  function showOptions'.$type.'(child_list, parent_list, orig_select)
8252  {
8253  var val = $("select[name=\""+parent_list+"\"]").val();
8254  var parentVal = parent_list + ":" + val;
8255  if(typeof val == "string"){
8256  if(val != "") {
8257  var options = orig_select.find("option[parent=\""+parentVal+"\"]").clone();
8258  $("select[name=\""+child_list+"\"] option[parent]").remove();
8259  $("select[name=\""+child_list+"\"]").append(options);
8260  } else {
8261  var options = orig_select.find("option[parent]").clone();
8262  $("select[name=\""+child_list+"\"] option[parent]").remove();
8263  $("select[name=\""+child_list+"\"]").append(options);
8264  }
8265  } else if(val > 0) {
8266  var options = orig_select.find("option[parent=\""+parentVal+"\"]").clone();
8267  $("select[name=\""+child_list+"\"] option[parent]").remove();
8268  $("select[name=\""+child_list+"\"]").append(options);
8269  } else {
8270  var options = orig_select.find("option[parent]").clone();
8271  $("select[name=\""+child_list+"\"] option[parent]").remove();
8272  $("select[name=\""+child_list+"\"]").append(options);
8273  }
8274  }
8275  function setListDependencies'.$type.'() {
8276  jQuery("select option[parent]").parent().each(function() {
8277  var orig_select = {};
8278  var child_list = $(this).attr("name");
8279  orig_select[child_list] = $(this).clone();
8280  var parent = $(this).find("option[parent]:first").attr("parent");
8281  var infos = parent.split(":");
8282  var parent_list = infos[0];
8283 
8284  //Hide daughters lists
8285  if ($("#"+child_list).val() == 0 && $("#"+parent_list).val() == 0){
8286  $("#"+child_list).hide();
8287  //Show mother lists
8288  } else if ($("#"+parent_list).val() != 0){
8289  $("#"+parent_list).show();
8290  }
8291  //Show the child list if the parent list value is selected
8292  $("select[name=\""+parent_list+"\"]").click(function() {
8293  if ($(this).val() != 0){
8294  $("#"+child_list).show()
8295  }
8296  });
8297 
8298  //When we change parent list
8299  $("select[name=\""+parent_list+"\"]").change(function() {
8300  showOptions'.$type.'(child_list, parent_list, orig_select[child_list]);
8301  //Select the value 0 on child list after a change on the parent list
8302  $("#"+child_list).val(0).trigger("change");
8303  //Hide child lists if the parent value is set to 0
8304  if ($(this).val() == 0){
8305  $("#"+child_list).hide();
8306  }
8307  });
8308  });
8309  }
8310 
8311  setListDependencies'.$type.'();
8312  });
8313  </script>'."\n";
8314  return $out;
8315  }
8316 
8321  public function getRights()
8322  {
8323  global $user;
8324 
8325  $element = $this->element;
8326  if ($element == 'facturerec') {
8327  $element = 'facture';
8328  } elseif ($element == 'invoice_supplier_rec') {
8329  return $user->rights->fournisseur->facture;
8330  }
8331 
8332  return $user->rights->{$element};
8333  }
8334 
8347  public static function commonReplaceThirdparty(DoliDB $db, $origin_id, $dest_id, array $tables, $ignoreerrors = 0)
8348  {
8349  foreach ($tables as $table) {
8350  $sql = 'UPDATE '.$db->prefix().$table.' SET fk_soc = '.((int) $dest_id).' WHERE fk_soc = '.((int) $origin_id);
8351 
8352  if (!$db->query($sql)) {
8353  if ($ignoreerrors) {
8354  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.
8355  }
8356  //$this->errors = $db->lasterror();
8357  return false;
8358  }
8359  }
8360 
8361  return true;
8362  }
8363 
8376  public static function commonReplaceProduct(DoliDB $db, $origin_id, $dest_id, array $tables, $ignoreerrors = 0)
8377  {
8378  foreach ($tables as $table) {
8379  $sql = 'UPDATE '.MAIN_DB_PREFIX.$table.' SET fk_product = '.((int) $dest_id).' WHERE fk_product = '.((int) $origin_id);
8380 
8381  if (!$db->query($sql)) {
8382  if ($ignoreerrors) {
8383  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.
8384  }
8385  //$this->errors = $db->lasterror();
8386  return false;
8387  }
8388  }
8389 
8390  return true;
8391  }
8392 
8405  public function defineBuyPrice($unitPrice = 0.0, $discountPercent = 0.0, $fk_product = 0)
8406  {
8407  global $conf;
8408 
8409  $buyPrice = 0;
8410 
8411  if (($unitPrice > 0) && (isset($conf->global->ForceBuyingPriceIfNull) && $conf->global->ForceBuyingPriceIfNull > 0)) {
8412  // When ForceBuyingPriceIfNull is set
8413  $buyPrice = $unitPrice * (1 - $discountPercent / 100);
8414  } else {
8415  // Get cost price for margin calculation
8416  if (!empty($fk_product) && $fk_product > 0) {
8417  if (isset($conf->global->MARGIN_TYPE) && $conf->global->MARGIN_TYPE == 'costprice') {
8418  require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
8419  $product = new Product($this->db);
8420  $result = $product->fetch($fk_product);
8421  if ($result <= 0) {
8422  $this->errors[] = 'ErrorProductIdDoesNotExists';
8423  return -1;
8424  }
8425  if ($product->cost_price > 0) {
8426  $buyPrice = $product->cost_price;
8427  } elseif ($product->pmp > 0) {
8428  $buyPrice = $product->pmp;
8429  }
8430  } elseif (isset($conf->global->MARGIN_TYPE) && $conf->global->MARGIN_TYPE == 'pmp') {
8431  require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
8432  $product = new Product($this->db);
8433  $result = $product->fetch($fk_product);
8434  if ($result <= 0) {
8435  $this->errors[] = 'ErrorProductIdDoesNotExists';
8436  return -1;
8437  }
8438  if ($product->pmp > 0) {
8439  $buyPrice = $product->pmp;
8440  }
8441  }
8442 
8443  if (empty($buyPrice) && isset($conf->global->MARGIN_TYPE) && in_array($conf->global->MARGIN_TYPE, array('1', 'pmp', 'costprice'))) {
8444  require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
8445  $productFournisseur = new ProductFournisseur($this->db);
8446  if (($result = $productFournisseur->find_min_price_product_fournisseur($fk_product)) > 0) {
8447  $buyPrice = $productFournisseur->fourn_unitprice;
8448  } elseif ($result < 0) {
8449  $this->errors[] = $productFournisseur->error;
8450  return -2;
8451  }
8452  }
8453  }
8454  }
8455  return $buyPrice;
8456  }
8457 
8458  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
8476  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)
8477  {
8478  // phpcs:enable
8479  global $conf, $user, $langs;
8480 
8481  include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
8482  include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
8483 
8484  $sortfield = 'position_name';
8485  $sortorder = 'asc';
8486 
8487  $dir = $sdir.'/';
8488  $pdir = '/';
8489 
8490  $dir .= get_exdir(0, 0, 0, 0, $this, $modulepart);
8491  $pdir .= get_exdir(0, 0, 0, 0, $this, $modulepart);
8492 
8493  // For backward compatibility
8494  if ($modulepart == 'product') {
8495  if (!empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) {
8496  $dir = $sdir.'/'.get_exdir($this->id, 2, 0, 0, $this, $modulepart).$this->id."/photos/";
8497  $pdir = '/'.get_exdir($this->id, 2, 0, 0, $this, $modulepart).$this->id."/photos/";
8498  }
8499  }
8500 
8501  // Defined relative dir to DOL_DATA_ROOT
8502  $relativedir = '';
8503  if ($dir) {
8504  $relativedir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $dir);
8505  $relativedir = preg_replace('/^[\\/]/', '', $relativedir);
8506  $relativedir = preg_replace('/[\\/]$/', '', $relativedir);
8507  }
8508 
8509  $dirthumb = $dir.'thumbs/';
8510  $pdirthumb = $pdir.'thumbs/';
8511 
8512  $return = '<!-- Photo -->'."\n";
8513  $nbphoto = 0;
8514 
8515  $filearray = dol_dir_list($dir, "files", 0, '', '(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) == 'desc' ?SORT_DESC:SORT_ASC), 1);
8516 
8517  /*if (! empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) // For backward compatiblity, we scan also old dirs
8518  {
8519  $filearrayold=dol_dir_list($dirold,"files",0,'','(\.meta|_preview.*\.png)$',$sortfield,(strtolower($sortorder)=='desc'?SORT_DESC:SORT_ASC),1);
8520  $filearray=array_merge($filearray, $filearrayold);
8521  }*/
8522 
8523  completeFileArrayWithDatabaseInfo($filearray, $relativedir);
8524 
8525  if (count($filearray)) {
8526  if ($sortfield && $sortorder) {
8527  $filearray = dol_sort_array($filearray, $sortfield, $sortorder);
8528  }
8529 
8530  foreach ($filearray as $key => $val) {
8531  $photo = '';
8532  $file = $val['name'];
8533 
8534  //if (dol_is_file($dir.$file) && image_format_supported($file) >= 0)
8535  if (image_format_supported($file) >= 0) {
8536  $nbphoto++;
8537  $photo = $file;
8538  $viewfilename = $file;
8539 
8540  if ($size == 1 || $size == 'small') { // Format vignette
8541  // Find name of thumb file
8542  $photo_vignette = basename(getImageFileNameForSize($dir.$file, '_small'));
8543  if (!dol_is_file($dirthumb.$photo_vignette)) {
8544  $photo_vignette = '';
8545  }
8546 
8547  // Get filesize of original file
8548  $imgarray = dol_getImageSize($dir.$photo);
8549 
8550  if ($nbbyrow > 0) {
8551  if ($nbphoto == 1) {
8552  $return .= '<table class="valigntop center centpercent" style="border: 0; padding: 2px; border-spacing: 2px; border-collapse: separate;">';
8553  }
8554 
8555  if ($nbphoto % $nbbyrow == 1) {
8556  $return .= '<tr class="center valignmiddle" style="border: 1px">';
8557  }
8558  $return .= '<td style="width: '.ceil(100 / $nbbyrow).'%" class="photo">';
8559  } elseif ($nbbyrow < 0) {
8560  $return .= '<div class="inline-block">';
8561  }
8562 
8563  $return .= "\n";
8564 
8565  $relativefile = preg_replace('/^\//', '', $pdir.$photo);
8566  if (empty($nolink)) {
8567  $urladvanced = getAdvancedPreviewUrl($modulepart, $relativefile, 0, 'entity='.$this->entity);
8568  if ($urladvanced) {
8569  $return .= '<a href="'.$urladvanced.'">';
8570  } else {
8571  $return .= '<a href="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdir.$photo).'" class="aphoto" target="_blank" rel="noopener noreferrer">';
8572  }
8573  }
8574 
8575  // Show image (width height=$maxHeight)
8576  // Si fichier vignette disponible et image source trop grande, on utilise la vignette, sinon on utilise photo origine
8577  $alt = $langs->transnoentitiesnoconv('File').': '.$relativefile;
8578  $alt .= ' - '.$langs->transnoentitiesnoconv('Size').': '.$imgarray['width'].'x'.$imgarray['height'];
8579  if ($notitle) {
8580  $alt = '';
8581  }
8582 
8583  $addphotorefcss = 1;
8584 
8585  if ($usesharelink) {
8586  if ($val['share']) {
8587  if (empty($maxHeight) || $photo_vignette && $imgarray['height'] > $maxHeight) {
8588  $return .= '<!-- Show original file (thumb not yet available with shared links) -->';
8589  $return .= '<img class="photo photowithmargin'.($addphotorefcss ? ' photoref' : '').'" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/viewimage.php?hashp='.urlencode($val['share']).'" title="'.dol_escape_htmltag($alt).'">';
8590  } else {
8591  $return .= '<!-- Show original file -->';
8592  $return .= '<img class="photo photowithmargin'.($addphotorefcss ? ' photoref' : '').'" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/viewimage.php?hashp='.urlencode($val['share']).'" title="'.dol_escape_htmltag($alt).'">';
8593  }
8594  } else {
8595  $return .= '<!-- Show nophoto file (because file is not shared) -->';
8596  $return .= '<img class="photo photowithmargin'.($addphotorefcss ? ' photoref' : '').'" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/public/theme/common/nophoto.png" title="'.dol_escape_htmltag($alt).'">';
8597  }
8598  } else {
8599  if (empty($maxHeight) || $photo_vignette && $imgarray['height'] > $maxHeight) {
8600  $return .= '<!-- Show thumb -->';
8601  $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).'">';
8602  } else {
8603  $return .= '<!-- Show original file -->';
8604  $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).'">';
8605  }
8606  }
8607 
8608  if (empty($nolink)) {
8609  $return .= '</a>';
8610  }
8611  $return .= "\n";
8612 
8613  if ($showfilename) {
8614  $return .= '<br>'.$viewfilename;
8615  }
8616  if ($showaction) {
8617  $return .= '<br>';
8618  // On propose la generation de la vignette si elle n'existe pas et si la taille est superieure aux limites
8619  if ($photo_vignette && (image_format_supported($photo) > 0) && ($this->imgWidth > $maxWidth || $this->imgHeight > $maxHeight)) {
8620  $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>';
8621  }
8622  // Special cas for product
8623  if ($modulepart == 'product' && ($user->rights->produit->creer || $user->rights->service->creer)) {
8624  // Link to resize
8625  $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; ';
8626 
8627  // Link to delete
8628  $return .= '<a href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&action=delete&token='.newToken().'&file='.urlencode($pdir.$viewfilename).'">';
8629  $return .= img_delete().'</a>';
8630  }
8631  }
8632  $return .= "\n";
8633 
8634  if ($nbbyrow > 0) {
8635  $return .= '</td>';
8636  if (($nbphoto % $nbbyrow) == 0) {
8637  $return .= '</tr>';
8638  }
8639  } elseif ($nbbyrow < 0) {
8640  $return .= '</div>';
8641  }
8642  }
8643 
8644  if (empty($size)) { // Format origine
8645  $return .= '<img class="photo photowithmargin" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdir.$photo).'">';
8646 
8647  if ($showfilename) {
8648  $return .= '<br>'.$viewfilename;
8649  }
8650  if ($showaction) {
8651  // Special case for product
8652  if ($modulepart == 'product' && ($user->rights->produit->creer || $user->rights->service->creer)) {
8653  // Link to resize
8654  $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; ';
8655 
8656  // Link to delete
8657  $return .= '<a href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&action=delete&token='.newToken().'&file='.urlencode($pdir.$viewfilename).'">';
8658  $return .= img_delete().'</a>';
8659  }
8660  }
8661  }
8662 
8663  // On continue ou on arrete de boucler ?
8664  if ($nbmax && $nbphoto >= $nbmax) {
8665  break;
8666  }
8667  }
8668  }
8669 
8670  if ($size == 1 || $size == 'small') {
8671  if ($nbbyrow > 0) {
8672  // Ferme tableau
8673  while ($nbphoto % $nbbyrow) {
8674  $return .= '<td style="width: '.ceil(100 / $nbbyrow).'%">&nbsp;</td>';
8675  $nbphoto++;
8676  }
8677 
8678  if ($nbphoto) {
8679  $return .= '</table>';
8680  }
8681  }
8682  }
8683  }
8684 
8685  $this->nbphoto = $nbphoto;
8686 
8687  return $return;
8688  }
8689 
8690 
8697  protected function isArray($info)
8698  {
8699  if (is_array($info)) {
8700  if (isset($info['type']) && $info['type'] == 'array') {
8701  return true;
8702  } else {
8703  return false;
8704  }
8705  }
8706  return false;
8707  }
8708 
8715  public function isDate($info)
8716  {
8717  if (isset($info['type']) && ($info['type'] == 'date' || $info['type'] == 'datetime' || $info['type'] == 'timestamp')) {
8718  return true;
8719  }
8720  return false;
8721  }
8722 
8729  public function isDuration($info)
8730  {
8731  if (is_array($info)) {
8732  if (isset($info['type']) && ($info['type'] == 'duration')) {
8733  return true;
8734  } else {
8735  return false;
8736  }
8737  } else {
8738  return false;
8739  }
8740  }
8741 
8748  public function isInt($info)
8749  {
8750  if (is_array($info)) {
8751  if (isset($info['type']) && (preg_match('/(^int|int$)/i', $info['type']))) {
8752  return true;
8753  } else {
8754  return false;
8755  }
8756  } else {
8757  return false;
8758  }
8759  }
8760 
8767  public function isFloat($info)
8768  {
8769  if (is_array($info)) {
8770  if (isset($info['type']) && (preg_match('/^(double|real|price)/i', $info['type']))) {
8771  return true;
8772  } else {
8773  return false;
8774  }
8775  }
8776  return false;
8777  }
8778 
8785  public function isText($info)
8786  {
8787  if (is_array($info)) {
8788  if (isset($info['type']) && $info['type'] == 'text') {
8789  return true;
8790  } else {
8791  return false;
8792  }
8793  }
8794  return false;
8795  }
8796 
8803  protected function canBeNull($info)
8804  {
8805  if (is_array($info)) {
8806  if (isset($info['notnull']) && $info['notnull'] != '1') {
8807  return true;
8808  } else {
8809  return false;
8810  }
8811  }
8812  return true;
8813  }
8814 
8821  protected function isForcedToNullIfZero($info)
8822  {
8823  if (is_array($info)) {
8824  if (isset($info['notnull']) && $info['notnull'] == '-1') {
8825  return true;
8826  } else {
8827  return false;
8828  }
8829  }
8830  return false;
8831  }
8832 
8839  protected function isIndex($info)
8840  {
8841  if (is_array($info)) {
8842  if (isset($info['index']) && $info['index'] == true) {
8843  return true;
8844  } else {
8845  return false;
8846  }
8847  }
8848  return false;
8849  }
8850 
8851 
8859  protected function setSaveQuery()
8860  {
8861  global $conf;
8862 
8863  $queryarray = array();
8864  foreach ($this->fields as $field => $info) { // Loop on definition of fields
8865  // Depending on field type ('datetime', ...)
8866  if ($this->isDate($info)) {
8867  if (empty($this->{$field})) {
8868  $queryarray[$field] = null;
8869  } else {
8870  $queryarray[$field] = $this->db->idate($this->{$field});
8871  }
8872  } elseif ($this->isDuration($info)) {
8873  // $this->{$field} may be null, '', 0, '0', 123, '123'
8874  if ((isset($this->{$field}) && $this->{$field} != '') || !empty($info['notnull'])) {
8875  if (!isset($this->{$field})) {
8876  if (!empty($info['default'])) {
8877  $queryarray[$field] = $info['default'];
8878  } else {
8879  $queryarray[$field] = 0;
8880  }
8881  } else {
8882  $queryarray[$field] = (int) $this->{$field}; // If '0', it may be set to null later if $info['notnull'] == -1
8883  }
8884  } else {
8885  $queryarray[$field] = null;
8886  }
8887  } elseif ($this->isInt($info) || $this->isFloat($info)) {
8888  if ($field == 'entity' && is_null($this->{$field})) {
8889  $queryarray[$field] = $conf->entity;
8890  } else {
8891  // $this->{$field} may be null, '', 0, '0', 123, '123'
8892  if ((isset($this->{$field}) && $this->{$field} != '') || !empty($info['notnull'])) {
8893  if (!isset($this->{$field})) {
8894  $queryarray[$field] = 0;
8895  } elseif ($this->isInt($info)) {
8896  $queryarray[$field] = (int) $this->{$field}; // If '0', it may be set to null later if $info['notnull'] == -1
8897  } elseif ($this->isFloat($info)) {
8898  $queryarray[$field] = (double) $this->{$field}; // If '0', it may be set to null later if $info['notnull'] == -1
8899  }
8900  } else {
8901  $queryarray[$field] = null;
8902  }
8903  }
8904  } else {
8905  // Note: If $this->{$field} is not defined, it means there is a bug into definition of ->fields or a missing declaration of property
8906  // We should keep the warning generated by this because it is a bug somewhere else in code, not here.
8907  $queryarray[$field] = $this->{$field};
8908  }
8909 
8910  if ($info['type'] == 'timestamp' && empty($queryarray[$field])) {
8911  unset($queryarray[$field]);
8912  }
8913  if (!empty($info['notnull']) && $info['notnull'] == -1 && empty($queryarray[$field])) {
8914  $queryarray[$field] = null; // May force 0 to null
8915  }
8916  }
8917 
8918  return $queryarray;
8919  }
8920 
8927  public function setVarsFromFetchObj(&$obj)
8928  {
8929  global $db;
8930 
8931  foreach ($this->fields as $field => $info) {
8932  if ($this->isDate($info)) {
8933  if (is_null($obj->{$field}) || $obj->{$field} === '' || $obj->{$field} === '0000-00-00 00:00:00' || $obj->{$field} === '1000-01-01 00:00:00') {
8934  $this->{$field} = '';
8935  } else {
8936  $this->{$field} = $db->jdate($obj->{$field});
8937  }
8938  } elseif ($this->isInt($info)) {
8939  if ($field == 'rowid') {
8940  $this->id = (int) $obj->{$field};
8941  } else {
8942  if ($this->isForcedToNullIfZero($info)) {
8943  if (empty($obj->{$field})) {
8944  $this->{$field} = null;
8945  } else {
8946  $this->{$field} = (double) $obj->{$field};
8947  }
8948  } else {
8949  if (!is_null($obj->{$field}) || (isset($info['notnull']) && $info['notnull'] == 1)) {
8950  $this->{$field} = (int) $obj->{$field};
8951  } else {
8952  $this->{$field} = null;
8953  }
8954  }
8955  }
8956  } elseif ($this->isFloat($info)) {
8957  if ($this->isForcedToNullIfZero($info)) {
8958  if (empty($obj->{$field})) {
8959  $this->{$field} = null;
8960  } else {
8961  $this->{$field} = (double) $obj->{$field};
8962  }
8963  } else {
8964  if (!is_null($obj->{$field}) || (isset($info['notnull']) && $info['notnull'] == 1)) {
8965  $this->{$field} = (double) $obj->{$field};
8966  } else {
8967  $this->{$field} = null;
8968  }
8969  }
8970  } else {
8971  $this->{$field} = isset($obj->{$field}) ? $obj->{$field} : null;
8972  }
8973  }
8974 
8975  // If there is no 'ref' field, we force property ->ref to ->id for a better compatibility with common functions.
8976  if (!isset($this->fields['ref']) && isset($this->id)) {
8977  $this->ref = $this->id;
8978  }
8979  }
8980 
8987  public function getFieldList($alias = '')
8988  {
8989  $keys = array_keys($this->fields);
8990  if (!empty($alias)) {
8991  $keys_with_alias = array();
8992  foreach ($keys as $fieldname) {
8993  $keys_with_alias[] = $alias . '.' . $fieldname;
8994  }
8995  return implode(',', $keys_with_alias);
8996  } else {
8997  return implode(',', $keys);
8998  }
8999  }
9000 
9008  protected function quote($value, $fieldsentry)
9009  {
9010  if (is_null($value)) {
9011  return 'NULL';
9012  } elseif (preg_match('/^(int|double|real|price)/i', $fieldsentry['type'])) {
9013  return price2num("$value");
9014  } elseif (preg_match('/int$/i', $fieldsentry['type'])) {
9015  return (int) $value;
9016  } elseif ($fieldsentry['type'] == 'boolean') {
9017  if ($value) {
9018  return 'true';
9019  } else {
9020  return 'false';
9021  }
9022  } else {
9023  return "'".$this->db->escape($value)."'";
9024  }
9025  }
9026 
9027 
9035  public function createCommon(User $user, $notrigger = false)
9036  {
9037  global $langs;
9038  dol_syslog(get_class($this)."::createCommon create", LOG_DEBUG);
9039 
9040  $error = 0;
9041 
9042  $now = dol_now();
9043 
9044  $fieldvalues = $this->setSaveQuery();
9045 
9046  if (array_key_exists('date_creation', $fieldvalues) && empty($fieldvalues['date_creation'])) {
9047  $fieldvalues['date_creation'] = $this->db->idate($now);
9048  }
9049  if (array_key_exists('fk_user_creat', $fieldvalues) && !($fieldvalues['fk_user_creat'] > 0)) {
9050  $fieldvalues['fk_user_creat'] = $user->id;
9051  }
9052  unset($fieldvalues['rowid']); // The field 'rowid' is reserved field name for autoincrement field so we don't need it into insert.
9053  if (array_key_exists('ref', $fieldvalues)) {
9054  $fieldvalues['ref'] = dol_string_nospecial($fieldvalues['ref']); // If field is a ref, we sanitize data
9055  }
9056 
9057  $keys = array();
9058  $values = array(); // Array to store string forged for SQL syntax
9059  foreach ($fieldvalues as $k => $v) {
9060  $keys[$k] = $k;
9061  $value = $this->fields[$k];
9062  $values[$k] = $this->quote($v, $value); // May return string 'NULL' if $value is null
9063  }
9064 
9065  // Clean and check mandatory
9066  foreach ($keys as $key) {
9067  // If field is an implicit foreign key field (so type = 'integer:...')
9068  if (preg_match('/^integer:/i', $this->fields[$key]['type']) && $values[$key] == '-1') {
9069  $values[$key] = '';
9070  }
9071  if (!empty($this->fields[$key]['foreignkey']) && $values[$key] == '-1') {
9072  $values[$key] = '';
9073  }
9074 
9075  if (isset($this->fields[$key]['notnull']) && $this->fields[$key]['notnull'] == 1 && (!isset($values[$key]) || $values[$key] === 'NULL') && is_null($this->fields[$key]['default'])) {
9076  $error++;
9077  $langs->load("errors");
9078  dol_syslog("Mandatory field '".$key."' is empty and required into ->fields definition of class");
9079  $this->errors[] = $langs->trans("ErrorFieldRequired", $this->fields[$key]['label']);
9080  }
9081 
9082  // If value is null and there is a default value for field
9083  if (isset($this->fields[$key]['notnull']) && $this->fields[$key]['notnull'] == 1 && (!isset($values[$key]) || $values[$key] === 'NULL') && !is_null($this->fields[$key]['default'])) {
9084  $values[$key] = $this->quote($this->fields[$key]['default'], $this->fields[$key]);
9085  }
9086 
9087  // If field is an implicit foreign key field (so type = 'integer:...')
9088  if (preg_match('/^integer:/i', $this->fields[$key]['type']) && empty($values[$key])) {
9089  if (isset($this->fields[$key]['default'])) {
9090  $values[$key] = ((int) $this->fields[$key]['default']);
9091  } else {
9092  $values[$key] = 'null';
9093  }
9094  }
9095  if (!empty($this->fields[$key]['foreignkey']) && empty($values[$key])) {
9096  $values[$key] = 'null';
9097  }
9098  }
9099 
9100  if ($error) {
9101  return -1;
9102  }
9103 
9104  $this->db->begin();
9105 
9106  if (!$error) {
9107  $sql = "INSERT INTO ".$this->db->prefix().$this->table_element;
9108  $sql .= " (".implode(", ", $keys).')';
9109  $sql .= " VALUES (".implode(", ", $values).")"; // $values can contains 'abc' or 123
9110 
9111  $res = $this->db->query($sql);
9112  if (!$res) {
9113  $error++;
9114  if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
9115  $this->errors[] = "ErrorRefAlreadyExists";
9116  } else {
9117  $this->errors[] = $this->db->lasterror();
9118  }
9119  }
9120  }
9121 
9122  if (!$error) {
9123  $this->id = $this->db->last_insert_id($this->db->prefix().$this->table_element);
9124  }
9125 
9126  // If we have a field ref with a default value of (PROV)
9127  if (!$error) {
9128  if (key_exists('ref', $this->fields) && $this->fields['ref']['notnull'] > 0 && key_exists('default', $this->fields['ref']) && $this->fields['ref']['default'] == '(PROV)') {
9129  $sql = "UPDATE ".$this->db->prefix().$this->table_element." SET ref = '(PROV".((int) $this->id).")' WHERE (ref = '(PROV)' OR ref = '') AND rowid = ".((int) $this->id);
9130  $resqlupdate = $this->db->query($sql);
9131 
9132  if ($resqlupdate === false) {
9133  $error++;
9134  $this->errors[] = $this->db->lasterror();
9135  } else {
9136  $this->ref = '(PROV'.$this->id.')';
9137  }
9138  }
9139  }
9140 
9141  // Create extrafields
9142  if (!$error) {
9143  $result = $this->insertExtraFields();
9144  if ($result < 0) {
9145  $error++;
9146  }
9147  }
9148 
9149  // Create lines
9150  if (!empty($this->table_element_line) && !empty($this->fk_element)) {
9151  $num = (is_array($this->lines) ? count($this->lines) : 0);
9152  for ($i = 0; $i < $num; $i++) {
9153  $line = $this->lines[$i];
9154 
9155  $keyforparent = $this->fk_element;
9156  $line->$keyforparent = $this->id;
9157 
9158  // Test and convert into object this->lines[$i]. When coming from REST API, we may still have an array
9159  //if (! is_object($line)) $line=json_decode(json_encode($line), false); // convert recursively array into object.
9160  if (!is_object($line)) {
9161  $line = (object) $line;
9162  }
9163 
9164  $result = $line->create($user, 1);
9165  if ($result < 0) {
9166  $this->error = $line->error;
9167  $this->db->rollback();
9168  return -1;
9169  }
9170  }
9171  }
9172 
9173  // Triggers
9174  if (!$error && !$notrigger) {
9175  // Call triggers
9176  $result = $this->call_trigger(strtoupper(get_class($this)).'_CREATE', $user);
9177  if ($result < 0) {
9178  $error++;
9179  }
9180  // End call triggers
9181  }
9182 
9183  // Commit or rollback
9184  if ($error) {
9185  $this->db->rollback();
9186  return -1;
9187  } else {
9188  $this->db->commit();
9189  return $this->id;
9190  }
9191  }
9192 
9193 
9202  public function fetchCommon($id, $ref = null, $morewhere = '')
9203  {
9204  if (empty($id) && empty($ref) && empty($morewhere)) {
9205  return -1;
9206  }
9207 
9208  $fieldlist = $this->getFieldList('t');
9209  if (empty($fieldlist)) {
9210  return 0;
9211  }
9212 
9213  $sql = "SELECT ".$fieldlist;
9214  $sql .= " FROM ".$this->db->prefix().$this->table_element.' as t';
9215 
9216  if (!empty($id)) {
9217  $sql .= ' WHERE t.rowid = '.((int) $id);
9218  } elseif (!empty($ref)) {
9219  $sql .= " WHERE t.ref = '".$this->db->escape($ref)."'";
9220  } else {
9221  $sql .= ' WHERE 1 = 1'; // usage with empty id and empty ref is very rare
9222  }
9223  if (empty($id) && isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
9224  $sql .= ' AND t.entity IN ('.getEntity($this->table_element).')';
9225  }
9226  if ($morewhere) {
9227  $sql .= $morewhere;
9228  }
9229  $sql .= ' LIMIT 1'; // This is a fetch, to be sure to get only one record
9230 
9231  $res = $this->db->query($sql);
9232  if ($res) {
9233  $obj = $this->db->fetch_object($res);
9234  if ($obj) {
9235  $this->setVarsFromFetchObj($obj);
9236 
9237  // Retrieve all extrafield
9238  // fetch optionals attributes and labels
9239  $this->fetch_optionals();
9240 
9241  return $this->id;
9242  } else {
9243  return 0;
9244  }
9245  } else {
9246  $this->error = $this->db->lasterror();
9247  $this->errors[] = $this->error;
9248  return -1;
9249  }
9250  }
9251 
9258  public function fetchLinesCommon($morewhere = '')
9259  {
9260  $objectlineclassname = get_class($this).'Line';
9261  if (!class_exists($objectlineclassname)) {
9262  $this->error = 'Error, class '.$objectlineclassname.' not found during call of fetchLinesCommon';
9263  return -1;
9264  }
9265 
9266  $objectline = new $objectlineclassname($this->db);
9267 
9268  $sql = "SELECT ".$objectline->getFieldList('l');
9269  $sql .= " FROM ".$this->db->prefix().$objectline->table_element." as l";
9270  $sql .= " WHERE l.fk_".$this->db->escape($this->element)." = ".((int) $this->id);
9271  if ($morewhere) {
9272  $sql .= $morewhere;
9273  }
9274  if (isset($objectline->fields['position'])) {
9275  $sql .= $this->db->order('position', 'ASC');
9276  }
9277 
9278  $resql = $this->db->query($sql);
9279  if ($resql) {
9280  $num_rows = $this->db->num_rows($resql);
9281  $i = 0;
9282  while ($i < $num_rows) {
9283  $obj = $this->db->fetch_object($resql);
9284  if ($obj) {
9285  $newline = new $objectlineclassname($this->db);
9286  $newline->setVarsFromFetchObj($obj);
9287 
9288  $this->lines[] = $newline;
9289  }
9290  $i++;
9291  }
9292 
9293  return 1;
9294  } else {
9295  $this->error = $this->db->lasterror();
9296  $this->errors[] = $this->error;
9297  return -1;
9298  }
9299  }
9300 
9308  public function updateCommon(User $user, $notrigger = false)
9309  {
9310  global $conf, $langs;
9311  dol_syslog(get_class($this)."::updateCommon update", LOG_DEBUG);
9312 
9313  $error = 0;
9314 
9315  $now = dol_now();
9316 
9317  $fieldvalues = $this->setSaveQuery();
9318 
9319  if (array_key_exists('date_modification', $fieldvalues) && empty($fieldvalues['date_modification'])) {
9320  $fieldvalues['date_modification'] = $this->db->idate($now);
9321  }
9322  if (array_key_exists('fk_user_modif', $fieldvalues) && !($fieldvalues['fk_user_modif'] > 0)) {
9323  $fieldvalues['fk_user_modif'] = $user->id;
9324  }
9325  unset($fieldvalues['rowid']); // The field 'rowid' is reserved field name for autoincrement field so we don't need it into update.
9326  if (array_key_exists('ref', $fieldvalues)) {
9327  $fieldvalues['ref'] = dol_string_nospecial($fieldvalues['ref']); // If field is a ref, we sanitize data
9328  }
9329 
9330  // Add quotes and escape on fields with type string
9331  $keys = array();
9332  $values = array();
9333  $tmp = array();
9334  foreach ($fieldvalues as $k => $v) {
9335  $keys[$k] = $k;
9336  $value = $this->fields[$k];
9337  $values[$k] = $this->quote($v, $value);
9338  $tmp[] = $k.'='.$this->quote($v, $this->fields[$k]);
9339  }
9340 
9341  // Clean and check mandatory fields
9342  foreach ($keys as $key) {
9343  if (preg_match('/^integer:/i', $this->fields[$key]['type']) && $values[$key] == '-1') {
9344  $values[$key] = ''; // This is an implicit foreign key field
9345  }
9346  if (!empty($this->fields[$key]['foreignkey']) && $values[$key] == '-1') {
9347  $values[$key] = ''; // This is an explicit foreign key field
9348  }
9349 
9350  //var_dump($key.'-'.$values[$key].'-'.($this->fields[$key]['notnull'] == 1));
9351  /*
9352  if ($this->fields[$key]['notnull'] == 1 && empty($values[$key]))
9353  {
9354  $error++;
9355  $this->errors[]=$langs->trans("ErrorFieldRequired", $this->fields[$key]['label']);
9356  }*/
9357  }
9358 
9359  $sql = 'UPDATE '.$this->db->prefix().$this->table_element.' SET '.implode(', ', $tmp).' WHERE rowid='.((int) $this->id);
9360 
9361  $this->db->begin();
9362  if (!$error) {
9363  $res = $this->db->query($sql);
9364  if (!$res) {
9365  $error++;
9366  $this->errors[] = $this->db->lasterror();
9367  }
9368  }
9369 
9370  // Update extrafield
9371  if (!$error) {
9372  $result = $this->insertExtraFields();
9373  if ($result < 0) {
9374  $error++;
9375  }
9376  }
9377 
9378  // Triggers
9379  if (!$error && !$notrigger) {
9380  // Call triggers
9381  $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $user);
9382  if ($result < 0) {
9383  $error++;
9384  } //Do also here what you must do to rollback action if trigger fail
9385  // End call triggers
9386  }
9387 
9388  // Commit or rollback
9389  if ($error) {
9390  $this->db->rollback();
9391  return -1;
9392  } else {
9393  $this->db->commit();
9394  return $this->id;
9395  }
9396  }
9397 
9406  public function deleteCommon(User $user, $notrigger = false, $forcechilddeletion = 0)
9407  {
9408  dol_syslog(get_class($this)."::deleteCommon delete", LOG_DEBUG);
9409 
9410  $error = 0;
9411 
9412  $this->db->begin();
9413 
9414  if ($forcechilddeletion) { // Force also delete of childtables that should lock deletion in standard case when option force is off
9415  foreach ($this->childtables as $table) {
9416  $sql = "DELETE FROM ".$this->db->prefix().$table." WHERE ".$this->fk_element." = ".((int) $this->id);
9417  $resql = $this->db->query($sql);
9418  if (!$resql) {
9419  $this->error = $this->db->lasterror();
9420  $this->errors[] = $this->error;
9421  $this->db->rollback();
9422  return -1;
9423  }
9424  }
9425  } elseif (!empty($this->fk_element) && !empty($this->childtables)) { // If object has childs linked with a foreign key field, we check all child tables.
9426  $objectisused = $this->isObjectUsed($this->id);
9427  if (!empty($objectisused)) {
9428  dol_syslog(get_class($this)."::deleteCommon Can't delete record as it has some child", LOG_WARNING);
9429  $this->error = 'ErrorRecordHasChildren';
9430  $this->errors[] = $this->error;
9431  $this->db->rollback();
9432  return 0;
9433  }
9434  }
9435 
9436  // Delete cascade first
9437  if (is_array($this->childtablesoncascade) && !empty($this->childtablesoncascade)) {
9438  foreach ($this->childtablesoncascade as $table) {
9439  $deleteFromObject = explode(':', $table);
9440  if (count($deleteFromObject) >= 2) {
9441  $className = str_replace('@', '', $deleteFromObject[0]);
9442  $filePath = $deleteFromObject[1];
9443  $columnName = $deleteFromObject[2];
9444  $TMoreSQL = array();
9445  $more_sql = $deleteFromObject[3];
9446  if (!empty($more_sql)) {
9447  $TMoreSQL['customsql'] = $more_sql;
9448  }
9449  if (dol_include_once($filePath)) {
9450  $childObject = new $className($this->db);
9451  if (method_exists($childObject, 'deleteByParentField')) {
9452  $result = $childObject->deleteByParentField($this->id, $columnName, $TMoreSQL);
9453  if ($result < 0) {
9454  $error++;
9455  $this->errors[] = $childObject->error;
9456  break;
9457  }
9458  } else {
9459  $error++;
9460  $this->errors[] = "You defined a cascade delete on an object $childObject but there is no method deleteByParentField for it";
9461  break;
9462  }
9463  } else {
9464  $error++;
9465  $this->errors[] = 'Cannot include child class file '.$filePath;
9466  break;
9467  }
9468  } else {
9469  // Delete record in child table
9470  $sql = "DELETE FROM ".$this->db->prefix().$table." WHERE ".$this->fk_element." = ".((int) $this->id);
9471 
9472  $resql = $this->db->query($sql);
9473  if (!$resql) {
9474  $error++;
9475  $this->error = $this->db->lasterror();
9476  $this->errors[] = $this->error;
9477  break;
9478  }
9479  }
9480  }
9481  }
9482 
9483  if (!$error) {
9484  if (!$notrigger) {
9485  // Call triggers
9486  $result = $this->call_trigger(strtoupper(get_class($this)).'_DELETE', $user);
9487  if ($result < 0) {
9488  $error++;
9489  } // Do also here what you must do to rollback action if trigger fail
9490  // End call triggers
9491  }
9492  }
9493 
9494  // Delete llx_ecm_files
9495  if (!$error) {
9496  $res = $this->deleteEcmFiles(1); // Deleting files physically is done later with the dol_delete_dir_recursive
9497  if (!$res) {
9498  $error++;
9499  }
9500  }
9501 
9502  // Delete linked object
9503  $res = $this->deleteObjectLinked();
9504  if ($res < 0) {
9505  $error++;
9506  }
9507 
9508  if (!$error && !empty($this->isextrafieldmanaged)) {
9509  $result = $this->deleteExtraFields();
9510  if ($result < 0) {
9511  $error++;
9512  }
9513  }
9514 
9515  if (!$error) {
9516  $sql = 'DELETE FROM '.$this->db->prefix().$this->table_element.' WHERE rowid='.((int) $this->id);
9517 
9518  $resql = $this->db->query($sql);
9519  if (!$resql) {
9520  $error++;
9521  $this->errors[] = $this->db->lasterror();
9522  }
9523  }
9524 
9525  // Commit or rollback
9526  if ($error) {
9527  $this->db->rollback();
9528  return -1;
9529  } else {
9530  $this->db->commit();
9531  return 1;
9532  }
9533  }
9534 
9545  public function deleteByParentField($parentId = 0, $parentField = '', $filter = array(), $filtermode = "AND")
9546  {
9547  global $user;
9548 
9549  $error = 0;
9550  $deleted = 0;
9551 
9552  if (!empty($parentId) && !empty($parentField)) {
9553  $this->db->begin();
9554 
9555  $sql = "SELECT rowid FROM ".$this->db->prefix().$this->table_element;
9556  $sql .= " WHERE ".$parentField." = ".(int) $parentId;
9557 
9558  // Manage filters
9559  $sqlwhere = array();
9560  if (count($filter) > 0) {
9561  foreach ($filter as $key => $value) {
9562  if ($key == 'customsql') {
9563  $sqlwhere[] = $value;
9564  } elseif (strpos($value, '%') === false) {
9565  $sqlwhere[] = $key." IN (".$this->db->sanitize($this->db->escape($value)).")";
9566  } else {
9567  $sqlwhere[] = $key." LIKE '%".$this->db->escape($value)."%'";
9568  }
9569  }
9570  }
9571  if (count($sqlwhere) > 0) {
9572  $sql .= " AND (".implode(" ".$filtermode." ", $sqlwhere).")";
9573  }
9574 
9575  $resql = $this->db->query($sql);
9576  if (!$resql) {
9577  $this->errors[] = $this->db->lasterror();
9578  $error++;
9579  } else {
9580  while ($obj = $this->db->fetch_object($resql)) {
9581  $result = $this->fetch($obj->rowid);
9582  if ($result < 0) {
9583  $error++;
9584  $this->errors[] = $this->error;
9585  } else {
9586  if (get_class($this) == 'Contact') { // TODO special code because delete() for contact has not been standardized like other delete.
9587  $result = $this->delete();
9588  } else {
9589  $result = $this->delete($user);
9590  }
9591  if ($result < 0) {
9592  $error++;
9593  $this->errors[] = $this->error;
9594  } else {
9595  $deleted++;
9596  }
9597  }
9598  }
9599  }
9600 
9601  if (empty($error)) {
9602  $this->db->commit();
9603  return $deleted;
9604  } else {
9605  $this->error = implode(', ', $this->errors);
9606  $this->db->rollback();
9607  return $error * -1;
9608  }
9609  }
9610 
9611  return $deleted;
9612  }
9613 
9622  public function deleteLineCommon(User $user, $idline, $notrigger = false)
9623  {
9624  global $conf;
9625 
9626  $error = 0;
9627 
9628  $tmpforobjectclass = get_class($this);
9629  $tmpforobjectlineclass = ucfirst($tmpforobjectclass).'Line';
9630 
9631  // Call trigger
9632  $result = $this->call_trigger('LINE'.strtoupper($tmpforobjectclass).'_DELETE', $user);
9633  if ($result < 0) {
9634  return -1;
9635  }
9636  // End call triggers
9637 
9638  $this->db->begin();
9639 
9640  $sql = "DELETE FROM ".$this->db->prefix().$this->table_element_line;
9641  $sql .= " WHERE rowid = ".((int) $idline);
9642 
9643  dol_syslog(get_class($this)."::deleteLineCommon", LOG_DEBUG);
9644  $resql = $this->db->query($sql);
9645  if (!$resql) {
9646  $this->error = "Error ".$this->db->lasterror();
9647  $error++;
9648  }
9649 
9650  if (empty($error)) {
9651  // Remove extrafields
9652  $tmpobjectline = new $tmpforobjectlineclass($this->db);
9653  if (!isset($tmpobjectline->isextrafieldmanaged) || !empty($tmpobjectline->isextrafieldmanaged)) {
9654  $tmpobjectline->id = $idline;
9655  $result = $tmpobjectline->deleteExtraFields();
9656  if ($result < 0) {
9657  $error++;
9658  $this->error = "Error ".get_class($this)."::deleteLineCommon deleteExtraFields error -4 ".$tmpobjectline->error;
9659  }
9660  }
9661  }
9662 
9663  if (empty($error)) {
9664  $this->db->commit();
9665  return 1;
9666  } else {
9667  dol_syslog(get_class($this)."::deleteLineCommon ERROR:".$this->error, LOG_ERR);
9668  $this->db->rollback();
9669  return -1;
9670  }
9671  }
9672 
9673 
9683  public function setStatusCommon($user, $status, $notrigger = 0, $triggercode = '')
9684  {
9685  $error = 0;
9686 
9687  $this->db->begin();
9688 
9689  $statusfield = 'status';
9690  if ($this->element == 'don' || $this->element == 'donation') {
9691  $statusfield = 'fk_statut';
9692  }
9693 
9694  $sql = "UPDATE ".$this->db->prefix().$this->table_element;
9695  $sql .= " SET ".$statusfield." = ".((int) $status);
9696  $sql .= " WHERE rowid = ".((int) $this->id);
9697 
9698  if ($this->db->query($sql)) {
9699  if (!$error) {
9700  $this->oldcopy = clone $this;
9701  }
9702 
9703  if (!$error && !$notrigger) {
9704  // Call trigger
9705  $result = $this->call_trigger($triggercode, $user);
9706  if ($result < 0) {
9707  $error++;
9708  }
9709  }
9710 
9711  if (!$error) {
9712  $this->status = $status;
9713  $this->db->commit();
9714  return 1;
9715  } else {
9716  $this->db->rollback();
9717  return -1;
9718  }
9719  } else {
9720  $this->error = $this->db->error();
9721  $this->db->rollback();
9722  return -1;
9723  }
9724  }
9725 
9726 
9733  public function initAsSpecimenCommon()
9734  {
9735  global $user;
9736 
9737  $this->id = 0;
9738  $this->specimen = 1;
9739  $fields = array(
9740  'label' => 'This is label',
9741  'ref' => 'ABCD1234',
9742  'description' => 'This is a description',
9743  'qty' => 123.12,
9744  'note_public' => 'Public note',
9745  'note_private' => 'Private note',
9746  'date_creation' => (dol_now() - 3600 * 48),
9747  'date_modification' => (dol_now() - 3600 * 24),
9748  'fk_user_creat' => $user->id,
9749  'fk_user_modif' => $user->id,
9750  'date' => dol_now(),
9751  );
9752  foreach ($fields as $key => $value) {
9753  if (array_key_exists($key, $this->fields)) {
9754  $this->{$key} = $value;
9755  }
9756  }
9757 
9758  // Force values to default values when known
9759  if (property_exists($this, 'fields')) {
9760  foreach ($this->fields as $key => $value) {
9761  // If fields are already set, do nothing
9762  if (array_key_exists($key, $fields)) {
9763  continue;
9764  }
9765 
9766  if (!empty($value['default'])) {
9767  $this->$key = $value['default'];
9768  }
9769  }
9770  }
9771 
9772  return 1;
9773  }
9774 
9775 
9776  /* Part for comments */
9777 
9782  public function fetchComments()
9783  {
9784  require_once DOL_DOCUMENT_ROOT.'/core/class/comment.class.php';
9785 
9786  $comment = new Comment($this->db);
9787  $result = $comment->fetchAllFor($this->element, $this->id);
9788  if ($result < 0) {
9789  $this->errors = array_merge($this->errors, $comment->errors);
9790  return -1;
9791  } else {
9792  $this->comments = $comment->comments;
9793  }
9794  return count($this->comments);
9795  }
9796 
9802  public function getNbComments()
9803  {
9804  return count($this->comments);
9805  }
9806 
9813  public function trimParameters($parameters)
9814  {
9815  if (!is_array($parameters)) {
9816  return;
9817  }
9818  foreach ($parameters as $parameter) {
9819  if (isset($this->$parameter)) {
9820  $this->$parameter = trim($this->$parameter);
9821  }
9822  }
9823  }
9824 
9825  /* Part for categories/tags */
9826 
9837  public function getCategoriesCommon($type_categ)
9838  {
9839  require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
9840 
9841  // Get current categories
9842  $c = new Categorie($this->db);
9843  $existing = $c->containing($this->id, $type_categ, 'id');
9844 
9845  return $existing;
9846  }
9847 
9860  public function setCategoriesCommon($categories, $type_categ = '', $remove_existing = true)
9861  {
9862  // Handle single category
9863  if (!is_array($categories)) {
9864  $categories = array($categories);
9865  }
9866 
9867  dol_syslog(get_class($this)."::setCategoriesCommon Oject Id:".$this->id.' type_categ:'.$type_categ.' nb tag add:'.count($categories), LOG_DEBUG);
9868 
9869  require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
9870 
9871  if (empty($type_categ)) {
9872  dol_syslog(__METHOD__.': Type '.$type_categ.'is an unknown category type. Done nothing.', LOG_ERR);
9873  return -1;
9874  }
9875 
9876  // Get current categories
9877  $c = new Categorie($this->db);
9878  $existing = $c->containing($this->id, $type_categ, 'id');
9879  if ($remove_existing) {
9880  // Diff
9881  if (is_array($existing)) {
9882  $to_del = array_diff($existing, $categories);
9883  $to_add = array_diff($categories, $existing);
9884  } else {
9885  $to_del = array(); // Nothing to delete
9886  $to_add = $categories;
9887  }
9888  } else {
9889  $to_del = array(); // Nothing to delete
9890  $to_add = array_diff($categories, $existing);
9891  }
9892 
9893  $error = 0;
9894  $ok = 0;
9895 
9896  // Process
9897  foreach ($to_del as $del) {
9898  if ($c->fetch($del) > 0) {
9899  $result=$c->del_type($this, $type_categ);
9900  if ($result < 0) {
9901  $error++;
9902  $this->error = $c->error;
9903  $this->errors = $c->errors;
9904  break;
9905  } else {
9906  $ok += $result;
9907  }
9908  }
9909  }
9910  foreach ($to_add as $add) {
9911  if ($c->fetch($add) > 0) {
9912  $result = $c->add_type($this, $type_categ);
9913  if ($result < 0) {
9914  $error++;
9915  $this->error = $c->error;
9916  $this->errors = $c->errors;
9917  break;
9918  } else {
9919  $ok += $result;
9920  }
9921  }
9922  }
9923 
9924  return $error ? -1 * $error : $ok;
9925  }
9926 
9935  public function cloneCategories($fromId, $toId, $type = '')
9936  {
9937  $this->db->begin();
9938 
9939  if (empty($type)) {
9940  $type = $this->table_element;
9941  }
9942 
9943  require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
9944  $categorystatic = new Categorie($this->db);
9945 
9946  $sql = "INSERT INTO ".$this->db->prefix()."categorie_".(empty($categorystatic->MAP_CAT_TABLE[$type]) ? $type : $categorystatic->MAP_CAT_TABLE[$type])." (fk_categorie, fk_product)";
9947  $sql .= " SELECT fk_categorie, $toId FROM ".$this->db->prefix()."categorie_".(empty($categorystatic->MAP_CAT_TABLE[$type]) ? $type : $categorystatic->MAP_CAT_TABLE[$type]);
9948  $sql .= " WHERE fk_product = ".((int) $fromId);
9949 
9950  if (!$this->db->query($sql)) {
9951  $this->error = $this->db->lasterror();
9952  $this->db->rollback();
9953  return -1;
9954  }
9955 
9956  $this->db->commit();
9957  return 1;
9958  }
9959 
9966  public function deleteEcmFiles($mode = 0)
9967  {
9968  global $conf;
9969 
9970  $this->db->begin();
9971 
9972  // Delete in database with mode 0
9973  if ($mode == 0) {
9974  switch ($this->element) {
9975  case 'propal':
9976  $element = 'propale';
9977  break;
9978  case 'product':
9979  $element = 'produit';
9980  break;
9981  case 'order_supplier':
9982  $element = 'fournisseur/commande';
9983  break;
9984  case 'invoice_supplier':
9985  $element = 'fournisseur/facture/'.get_exdir($this->id, 2, 0, 1, $this, 'invoice_supplier');
9986  break;
9987  case 'shipping':
9988  $element = 'expedition/sending';
9989  break;
9990  default:
9991  $element = $this->element;
9992  }
9993 
9994  // Delete ecm_files extrafields
9995  $sql = "DELETE FROM ".$this->db->prefix()."ecm_files_extrafields WHERE fk_object IN (";
9996  $sql .= " SELECT rowid FROM ".$this->db->prefix()."ecm_files WHERE filename LIKE '".$this->db->escape($this->ref)."%'";
9997  $sql .= " AND filepath = '".$this->db->escape($element)."/".$this->db->escape($this->ref)."' AND entity = ".((int) $conf->entity); // No need of getEntity here
9998  $sql .= ")";
9999 
10000  if (!$this->db->query($sql)) {
10001  $this->error = $this->db->lasterror();
10002  $this->db->rollback();
10003  return false;
10004  }
10005 
10006  // Delete ecm_files
10007  $sql = "DELETE FROM ".$this->db->prefix()."ecm_files";
10008  $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%'";
10009  $sql .= " AND filepath = '".$this->db->escape($element)."/".$this->db->escape($this->ref)."' AND entity = ".((int) $conf->entity); // No need of getEntity here
10010 
10011  if (!$this->db->query($sql)) {
10012  $this->error = $this->db->lasterror();
10013  $this->db->rollback();
10014  return false;
10015  }
10016  }
10017 
10018  // Delete in database with mode 1
10019  if ($mode == 1) {
10020  $sql = 'DELETE FROM '.$this->db->prefix()."ecm_files_extrafields";
10021  $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).")";
10022  $resql = $this->db->query($sql);
10023  if (!$resql) {
10024  $this->error = $this->db->lasterror();
10025  $this->db->rollback();
10026  return false;
10027  }
10028 
10029  $sql = 'DELETE FROM '.$this->db->prefix()."ecm_files";
10030  $sql .= " WHERE src_object_type = '".$this->db->escape($this->table_element.(empty($this->module) ? "" : "@".$this->module))."' AND src_object_id = ".((int) $this->id);
10031  $resql = $this->db->query($sql);
10032  if (!$resql) {
10033  $this->error = $this->db->lasterror();
10034  $this->db->rollback();
10035  return false;
10036  }
10037  }
10038 
10039  $this->db->commit();
10040  return true;
10041  }
10042 }
CommonObject\trimParameters
trimParameters($parameters)
Trim object parameters.
Definition: commonobject.class.php:9813
CommonObject\deleteCommon
deleteCommon(User $user, $notrigger=false, $forcechilddeletion=0)
Delete object in database.
Definition: commonobject.class.php:9406
CommonObject\setExtraParameters
setExtraParameters()
Set extra parameters.
Definition: commonobject.class.php:4807
CommonObject\setStatusCommon
setStatusCommon($user, $status, $notrigger=0, $triggercode='')
Set to a status.
Definition: commonobject.class.php:9683
CommonObject\liste_contact
liste_contact($status=-1, $source='external', $list=0, $code='')
Get array of all contacts for an object.
Definition: commonobject.class.php:1362
db
$conf db
API class for accounts.
Definition: inc.php:41
dol_escape_htmltag
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.
Definition: functions.lib.php:1468
CommonObject\fetchCommon
fetchCommon($id, $ref=null, $morewhere='')
Load object in memory from the database.
Definition: commonobject.class.php:9202
dol_trunc
dol_trunc($string, $size=40, $trunc='right', $stringencoding='UTF-8', $nodot=0, $display=0)
Truncate a string to a particular length adding '…' if string larger than length.
Definition: functions.lib.php:3805
CommonObject\getIdContact
getIdContact($source, $code, $status=0)
Return id of contacts for a source and a contact code.
Definition: commonobject.class.php:1643
CommonObject\getKanbanView
getKanbanView($option='')
Return clicable link of object (with eventually picto)
Definition: commonobject.class.php:766
CommonObject\isFloat
isFloat($info)
Function test if type is float.
Definition: commonobject.class.php:8767
CommonObject\setProject
setProject($projectid, $notrigger=0)
Link element with a project.
Definition: commonobject.class.php:2331
CommonObject\updateRangOfLine
updateRangOfLine($rowid, $rang)
Update position of line (rang)
Definition: commonobject.class.php:3219
CommonObject\setUpperOrLowerCase
setUpperOrLowerCase()
Set to upper or ucwords/lower if needed.
Definition: commonobject.class.php:740
CommonObject\isDate
isDate($info)
Function test if type is date.
Definition: commonobject.class.php:8715
dol_print_error
dol_print_error($db='', $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
Definition: functions.lib.php:4844
dol_include_once
if(!function_exists('dol_getprefix')) dol_include_once($relpath, $classname='')
Make an include_once using default root and alternate root if it fails.
Definition: functions.lib.php:1033
CommonObject\fetchLinesCommon
fetchLinesCommon($morewhere='')
Load object in memory from the database.
Definition: commonobject.class.php:9258
CommonObject\deleteObjectLinked
deleteObjectLinked($sourceid=null, $sourcetype='', $targetid=null, $targettype='', $rowid='', $f_user=null, $notrigger=0)
Delete all links between an object $this.
Definition: commonobject.class.php:4228
CommonObject\isArray
isArray($info)
Function test if type is array.
Definition: commonobject.class.php:8697
ref
$object ref
Definition: info.php:77
CommonObject\canBeNull
canBeNull($info)
Function test if field can be null.
Definition: commonobject.class.php:8803
CommonObject\swapContactStatus
swapContactStatus($rowid)
Update status of a contact linked to object.
Definition: commonobject.class.php:1455
$form
if($cancel &&! $id) if($action=='add' &&! $cancel) if($action=='delete') if($id) $form
Actions.
Definition: card.php:142
CommonObject\isText
isText($info)
Function test if type is text.
Definition: commonobject.class.php:8785
CommonObject\deleteByParentField
deleteByParentField($parentId=0, $parentField='', $filter=array(), $filtermode="AND")
Delete all child object from a parent ID.
Definition: commonobject.class.php:9545
rowid
print *****$script_file(".$version.") pid c cd cd cd description as p label as s rowid
Definition: email_expire_services_to_representatives.php:79
image_format_supported
image_format_supported($file, $acceptsvg=0)
Return if a filename is file name of a supported image format.
Definition: images.lib.php:80
CommonObject\setStatut
setStatut($status, $elementId=null, $elementType='', $trigkey='', $fieldstatus='fk_statut')
Set status of an object.
Definition: commonobject.class.php:4364
CommonObject\quote
quote($value, $fieldsentry)
Add quote to field value if necessary.
Definition: commonobject.class.php:9008
CommonObject\initAsSpecimenCommon
initAsSpecimenCommon()
Initialise object with example values Id must be 0 if object instance is a specimen.
Definition: commonobject.class.php:9733
name
$conf db name
Definition: repair.php:122
Comment
Class to manage comment.
Definition: comment.class.php:22
Categorie
Class to manage categories.
Definition: categorie.class.php:47
CommonObject
Parent class of all other business classes (invoices, contracts, proposals, orders,...
Definition: commonobject.class.php:44
CommonObject\getFullName
getFullName($langs, $option=0, $nameorder=-1, $maxlen=0)
Return full name (civility+' '+name+' '+lastname)
Definition: commonobject.class.php:712
price2num
price2num($amount, $rounding='', $option=0)
Function that return a number with universal decimal format (decimal separator is '.
Definition: functions.lib.php:5661
CommonObject\insertExtraLanguages
insertExtraLanguages($trigger='', $userused=null)
Add/Update all extra fields values for the current object.
Definition: commonobject.class.php:6424
getState
getState($id, $withcode='', $dbtouse=0, $withregion=0, $outputlangs='', $entconv=1)
Return state translated from an id.
Definition: company.lib.php:569
img_picto
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=false, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2)
Show picto whatever it's its name (generic function)
Definition: functions.lib.php:3880
CommonObject\commonGenerateDocument
commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams=null)
Common function for all objects extending CommonObject for generating documents.
Definition: commonobject.class.php:5406
CommonObject\delete_resource
delete_resource($rowid, $element, $notrigger=0)
Delete a link to resource line.
Definition: commonobject.class.php:5346
dol_strtoupper
dol_strtoupper($string, $encoding="UTF-8")
Convert a string to upper.
Definition: functions.lib.php:1541
CommonObject\cloneCategories
cloneCategories($fromId, $toId, $type='')
Copy related categories to another object.
Definition: commonobject.class.php:9935
CommonObject\createCommon
createCommon(User $user, $notrigger=false)
Create object into database.
Definition: commonobject.class.php:9035
CommonObject\getRangOfLine
getRangOfLine($rowid)
Get position of line (rang)
Definition: commonobject.class.php:3325
CommonObject\update_price
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).
Definition: commonobject.class.php:3525
img_delete
img_delete($titlealt='default', $other='class="pictodelete"', $morecss='')
Show delete logo.
Definition: functions.lib.php:4429
CommonObject\showOptionals
showOptionals($extrafields, $mode='view', $params=null, $keysuffix='', $keyprefix='', $onetrtd=0, $display_type='card')
Function to show lines of extrafields with output datas.
Definition: commonobject.class.php:7960
CommonObject\getFormatedSupplierRef
getFormatedSupplierRef($objref)
Return supplier ref for screen output.
Definition: commonobject.class.php:690
CommonObject\getFullAddress
getFullAddress($withcountry=0, $sep="\n", $withregion=0, $extralangcode='')
Return full address of contact.
Definition: commonobject.class.php:798
CommonObject\getChildrenOfLine
getChildrenOfLine($id, $includealltree=0)
Get children of line.
Definition: commonobject.class.php:3140
code
print *****$script_file(".$version.") pid code
! Closing after partial payment: discount_vat, badcustomer or badsupplier, bankcharge,...
Definition: sync_members_ldap2dolibarr.php:60
CommonObject\setWarehouse
setWarehouse($warehouse_id)
Change the warehouse.
Definition: commonobject.class.php:2924
dol_string_nospecial
dol_string_nospecial($str, $newstr='_', $badcharstoreplace='', $badcharstoremove='')
Clean a string from all punctuation characters to use it as a ref or login.
Definition: functions.lib.php:1376
CommonObject\insertExtraFields
insertExtraFields($trigger='', $userused=null)
Add/Update all extra fields values for the current object.
Definition: commonobject.class.php:6156
CommonObject\load_previous_next_ref
load_previous_next_ref($filter, $fieldid, $nodbprefix=0)
Load properties id_previous and id_next by comparing $fieldid with $this->ref.
Definition: commonobject.class.php:2123
getAdvancedPreviewUrl
getAdvancedPreviewUrl($modulepart, $relativepath, $alldata=0, $param='')
Return URL we can use for advanced preview links.
Definition: functions.lib.php:9646
CommonObject\fetchComments
fetchComments()
Load comments linked with current task.
Definition: commonobject.class.php:9782
CommonObject\isExistingObject
static isExistingObject($element, $id, $ref='', $ref_ext='')
Check an object id/ref exists If you don't need/want to instantiate object and just need to know if o...
Definition: commonobject.class.php:617
CommonObject\delete_linked_contact
delete_linked_contact($source='', $code='')
Delete all links between an object $this and all its contacts in llx_element_contact.
Definition: commonobject.class.php:1319
CommonObject\setBankAccount
setBankAccount($fk_account, $notrigger=false, $userused=null)
Change the bank account.
Definition: commonobject.class.php:2991
CommonObject\getBannerAddress
getBannerAddress($htmlkey, $object)
Return full address for banner.
Definition: commonobject.class.php:827
CommonObject\setVarsFromFetchObj
setVarsFromFetchObj(&$obj)
Function to load data from a SQL pointer into properties of current object $this.
Definition: commonobject.class.php:8927
CommonObject\deleteEcmFiles
deleteEcmFiles($mode=0)
Delete related files of object in database.
Definition: commonobject.class.php:9966
CommonObject\add_contact
add_contact($fk_socpeople, $type_contact, $source='external', $notrigger=0)
Add a link between element $this->element and a contact.
Definition: commonobject.class.php:1108
dol_syslog
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
Definition: functions.lib.php:1603
CommonObject\line_max
line_max($fk_parent_line=0)
Get max value used for position of line (rang)
Definition: commonobject.class.php:3373
CommonObject\update_note
update_note($note, $suffix='')
Update note of element.
Definition: commonobject.class.php:3448
CommonObject\setShippingMethod
setShippingMethod($shipping_method_id, $notrigger=false, $userused=null)
Change the shipping method.
Definition: commonobject.class.php:2866
dol_format_address
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.
Definition: functions.lib.php:2393
CommonObject\fetch_optionals
fetch_optionals($rowid=null, $optionsArray=null)
Function to get extra fields of an object into $this->array_options This method is in most cases call...
Definition: commonobject.class.php:6007
CommonObject\add_element_resource
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->element & $thi...
Definition: commonobject.class.php:5305
CommonObject\updateCommon
updateCommon(User $user, $notrigger=false)
Update object into database.
Definition: commonobject.class.php:9308
CommonObject\isForcedToNullIfZero
isForcedToNullIfZero($info)
Function test if field is forced to null if zero or empty.
Definition: commonobject.class.php:8821
newToken
newToken()
Return the value of token currently saved into session with name 'newtoken'.
Definition: functions.lib.php:10878
CommonObject\getFormatedCustomerRef
getFormatedCustomerRef($objref)
Return customer ref for screen output.
Definition: commonobject.class.php:671
dolGetFirstLastname
dolGetFirstLastname($firstname, $lastname, $nameorder=-1)
Return firstname and lastname in correct order.
Definition: functions.lib.php:8062
CommonObject\updateObjectLinked
updateObjectLinked($sourceid=null, $sourcetype='', $targetid=null, $targettype='', $f_user=null, $notrigger=0)
Update object linked of a current object.
Definition: commonobject.class.php:4158
User
Class to manage Dolibarr users.
Definition: user.class.php:44
CommonObject\deleteExtraFields
deleteExtraFields()
Delete all extra fields values for the current object.
Definition: commonobject.class.php:6116
CommonObject\$note
$note
Definition: commonobject.class.php:444
CommonObject\add_object_linked
add_object_linked($origin=null, $origin_id=null, $f_user=null, $notrigger=0)
Add an object link into llx_element_element.
Definition: commonobject.class.php:3818
CommonObject\setDocModel
setDocModel($user, $modelpdf)
Set last model used by doc generator.
Definition: commonobject.class.php:2957
dol_now
dol_now($mode='auto')
Return date for now.
Definition: functions.lib.php:2845
$resql
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
CommonObject\deleteLineCommon
deleteLineCommon(User $user, $idline, $notrigger=false)
Delete a line of object in database.
Definition: commonobject.class.php:9622
CommonObject\update_ref_ext
update_ref_ext($ref_ext)
Update external ref of element.
Definition: commonobject.class.php:3418
CommonObject\isIndex
isIndex($info)
Function test if is indexed.
Definition: commonobject.class.php:8839
getCountry
getCountry($searchkey, $withcode='', $dbtouse=0, $outputlangs='', $entconv=1, $searchlabel='')
Return country label, code or id from an id, code or label.
Definition: company.lib.php:489
CommonObject\errorsToString
errorsToString()
Method to output saved errors.
Definition: commonobject.class.php:659
CommonObject\setCategoriesCommon
setCategoriesCommon($categories, $type_categ='', $remove_existing=true)
Sets object to given categories.
Definition: commonobject.class.php:9860
user
$conf db user
Definition: repair.php:123
CommonObject\printObjectLines
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....
Definition: commonobject.class.php:4898
CommonObject\setSaveQuery
setSaveQuery()
Function to prepare a part of the query for insert.
Definition: commonobject.class.php:8859
CommonObject\getCategoriesCommon
getCategoriesCommon($type_categ)
Sets object to given categories.
Definition: commonobject.class.php:9837
CommonObject\$projet
$projet
Definition: commonobject.class.php:187
CommonObject\line_order
line_order($renum=false, $rowidorder='ASC', $fk_parent_line=true)
Save a new position (field rang) for details lines.
Definition: commonobject.class.php:3055
CommonObject\getFieldList
getFieldList($alias='')
Function to concat keys of fields.
Definition: commonobject.class.php:8987
type
if(preg_match('/crypted:/i', $dolibarr_main_db_pass)||!empty($dolibarr_main_db_encrypted_pass)) $conf db type
Definition: repair.php:119
CommonObject\$fk_projet
$fk_projet
Definition: commonobject.class.php:193
CommonObject\isDuration
isDuration($info)
Function test if type is duration.
Definition: commonobject.class.php:8729
dol_strtolower
dol_strtolower($string, $encoding="UTF-8")
Convert a string to lower.
Definition: functions.lib.php:1525
CommonObject\getNbComments
getNbComments()
Return nb comments already posted.
Definition: commonobject.class.php:9802
CommonObject\delete_contact
delete_contact($rowid, $notrigger=0)
Delete a link to contact line.
Definition: commonobject.class.php:1269
dol_ucwords
dol_ucwords($string, $encoding="UTF-8")
Convert first character of all the words of a string to upper.
Definition: functions.lib.php:1573
CommonObject\isInt
isInt($info)
Function test if type is integer.
Definition: commonobject.class.php:8748