dolibarr  x.y.z
commonobject.class.php
Go to the documentation of this file.
1 <?php
2 /* Copyright (C) 2006-2015 Laurent Destailleur <eldy@users.sourceforge.net>
3  * Copyright (C) 2005-2013 Regis Houssin <regis.houssin@inodbox.com>
4  * Copyright (C) 2010-2020 Juanjo Menent <jmenent@2byte.es>
5  * Copyright (C) 2012-2013 Christophe Battarel <christophe.battarel@altairis.fr>
6  * Copyright (C) 2011-2022 Philippe Grand <philippe.grand@atoo-net.com>
7  * Copyright (C) 2012-2015 Marcos García <marcosgdf@gmail.com>
8  * Copyright (C) 2012-2015 Raphaël Doursenaud <rdoursenaud@gpcsolutions.fr>
9  * Copyright (C) 2012 Cedric Salvador <csalvador@gpcsolutions.fr>
10  * Copyright (C) 2015-2022 Alexandre Spangaro <aspangaro@open-dsi.fr>
11  * Copyright (C) 2016 Bahfir abbes <dolipar@dolipar.org>
12  * Copyright (C) 2017 ATM Consulting <support@atm-consulting.fr>
13  * Copyright (C) 2017-2019 Nicolas ZABOURI <info@inovea-conseil.com>
14  * Copyright (C) 2017 Rui Strecht <rui.strecht@aliartalentos.com>
15  * Copyright (C) 2018-2021 Frédéric France <frederic.france@netlogic.fr>
16  * Copyright (C) 2018 Josep Lluís Amador <joseplluis@lliuretic.cat>
17  * Copyright (C) 2021 Gauthier VERDOL <gauthier.verdol@atm-consulting.fr>
18  * Copyright (C) 2021 Grégory Blémand <gregory.blemand@atm-consulting.fr>
19  *
20  * This program is free software; you can redistribute it and/or modify
21  * it under the terms of the GNU General Public License as published by
22  * the Free Software Foundation; either version 3 of the License, or
23  * (at your option) any later version.
24  *
25  * This program is distributed in the hope that it will be useful,
26  * but WITHOUT ANY WARRANTY; without even the implied warranty of
27  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
28  * GNU General Public License for more details.
29  *
30  * You should have received a copy of the GNU General Public License
31  * along with this program. If not, see <https://www.gnu.org/licenses/>.
32  */
33 
44 abstract class CommonObject
45 {
46  const TRIGGER_PREFIX = ''; // to be overriden in child class implementations, i.e. 'BILL', 'TASK', 'PROPAL', etc.
50  public $db;
51 
55  public $id;
56 
60  public $entity;
61 
66  public $error;
67 
71  public $errorhidden;
72 
76  public $errors = array();
77 
81  private $validateFieldsErrors = array();
82 
86  public $element;
87 
92  public $element_for_permission;
93 
97  public $table_element;
98 
102  public $table_element_line = '';
103 
107  public $import_key;
108 
112  public $array_options = array();
113 
117  public $array_languages = null; // Value is array() when load already tried
118 
122  public $contacts_ids;
123 
127  public $linked_objects;
128 
132  public $linkedObjectsIds;
133 
137  public $linkedObjects;
138 
142  private $linkedObjectsFullLoaded = array();
143 
147  public $oldcopy;
148 
152  protected $table_ref_field = '';
153 
157  public $restrictiononfksoc = 0;
158 
159 
160  // Following vars are used by some objects only. We keep this property here in CommonObject to be able to provide common method using them.
161 
165  public $context = array();
166 
170  public $canvas;
171 
176  public $project;
177 
182  public $fk_project;
183 
188  public $projet;
189 
194  public $fk_projet;
195 
200  public $contact;
201 
206  public $contact_id;
207 
212  public $thirdparty;
213 
218  public $user;
219 
224  public $origin;
225 
230  public $origin_id;
231 
235  public $ref;
236 
240  public $ref_ext;
241 
245  public $ref_previous;
246 
250  public $ref_next;
251 
255  public $newref;
256 
261  public $statut;
262 
267  public $status;
268 
269 
274  public $country;
275 
280  public $country_id;
281 
286  public $country_code;
287 
292  public $state;
293 
298  public $state_id;
299 
304  public $state_code;
305 
310  public $region_id;
311 
316  public $region_code;
317 
322  public $region;
323 
324 
329  public $barcode_type;
330 
335  public $barcode_type_code;
336 
341  public $barcode_type_label;
342 
347  public $barcode_type_coder;
348 
353  public $mode_reglement_id;
354 
359  public $cond_reglement_id;
360 
364  public $demand_reason_id;
365 
370  public $transport_mode_id;
371 
377  public $cond_reglement;
378 
384  public $fk_delivery_address;
385 
390  public $shipping_method_id;
391 
396  public $model_pdf;
397 
403  public $modelpdf;
404 
409  public $last_main_doc;
410 
416  public $fk_bank;
417 
422  public $fk_account;
423 
427  public $openid;
428 
433  public $note_public;
434 
439  public $note_private;
440 
445  public $note;
446 
451  public $total_ht;
452 
457  public $total_tva;
458 
463  public $total_localtax1;
464 
469  public $total_localtax2;
470 
475  public $total_ttc;
476 
480  public $lines;
481 
486  public $comments = array();
487 
491  public $name;
492 
496  public $lastname;
497 
501  public $firstname;
502 
506  public $civility_id;
507 
508  // Dates
512  public $date_creation;
513 
517  public $date_validation; // Date validation
518 
522  public $date_modification; // Date last change (tms field)
523 
527  public $date_cloture; // Date closing (tms field)
528 
533  public $user_author;
538  public $user_creation;
542  public $user_creation_id;
543 
548  public $user_valid;
553  public $user_validation;
557  public $user_validation_id;
561  public $user_closing_id;
562 
567  public $user_modification;
571  public $user_modification_id;
572 
573 
574  public $next_prev_filter;
575 
579  public $specimen = 0;
580 
584  public $sendtoid;
585 
589  public $alreadypaid;
590 
591 
592  protected $labelStatus;
593  protected $labelStatusShort;
594 
595 
599  protected $childtables = array();
600 
606  protected $childtablesoncascade = array();
607 
608 
609  // No constructor as it is an abstract class
610 
611 
622  public static function isExistingObject($element, $id, $ref = '', $ref_ext = '')
623  {
624  global $db, $conf;
625 
626  $sql = "SELECT rowid, ref, ref_ext";
627  $sql .= " FROM ".$db->prefix().$element;
628  $sql .= " WHERE entity IN (".getEntity($element).")";
629 
630  if ($id > 0) {
631  $sql .= " AND rowid = ".((int) $id);
632  } elseif ($ref) {
633  $sql .= " AND ref = '".$db->escape($ref)."'";
634  } elseif ($ref_ext) {
635  $sql .= " AND ref_ext = '".$db->escape($ref_ext)."'";
636  } else {
637  $error = 'ErrorWrongParameters';
638  dol_print_error(get_class()."::isExistingObject ".$error, LOG_ERR);
639  return -1;
640  }
641  if ($ref || $ref_ext) { // Because the same ref can exists in 2 different entities, we force the current one in priority
642  $sql .= " AND entity = ".((int) $conf->entity);
643  }
644 
645  dol_syslog(get_class()."::isExistingObject", LOG_DEBUG);
646  $resql = $db->query($sql);
647  if ($resql) {
648  $num = $db->num_rows($resql);
649  if ($num > 0) {
650  return 1;
651  } else {
652  return 0;
653  }
654  }
655  return -1;
656  }
657 
658 
664  public function errorsToString()
665  {
666  return $this->error.(is_array($this->errors) ? (($this->error != '' ? ', ' : '').join(', ', $this->errors)) : '');
667  }
668 
669 
676  public function getFormatedCustomerRef($objref)
677  {
678  global $hookmanager;
679 
680  $parameters = array('objref'=>$objref);
681  $action = '';
682  $reshook = $hookmanager->executeHooks('getFormatedCustomerRef', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
683  if ($reshook > 0) {
684  return $hookmanager->resArray['objref'];
685  }
686  return $objref.(isset($hookmanager->resArray['objref']) ? $hookmanager->resArray['objref'] : '');
687  }
688 
695  public function getFormatedSupplierRef($objref)
696  {
697  global $hookmanager;
698 
699  $parameters = array('objref'=>$objref);
700  $action = '';
701  $reshook = $hookmanager->executeHooks('getFormatedSupplierRef', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
702  if ($reshook > 0) {
703  return $hookmanager->resArray['objref'];
704  }
705  return $objref.(isset($hookmanager->resArray['objref']) ? $hookmanager->resArray['objref'] : '');
706  }
707 
717  public function getFullName($langs, $option = 0, $nameorder = -1, $maxlen = 0)
718  {
719  //print "lastname=".$this->lastname." name=".$this->name." nom=".$this->nom."<br>\n";
720  $lastname = $this->lastname;
721  $firstname = $this->firstname;
722  if (empty($lastname)) {
723  $lastname = (isset($this->lastname) ? $this->lastname : (isset($this->name) ? $this->name : (isset($this->nom) ? $this->nom : (isset($this->societe) ? $this->societe : (isset($this->company) ? $this->company : '')))));
724  }
725 
726  $ret = '';
727  if (!empty($option) && !empty($this->civility_code)) {
728  if ($langs->transnoentitiesnoconv("Civility".$this->civility_code) != "Civility".$this->civility_code) {
729  $ret .= $langs->transnoentitiesnoconv("Civility".$this->civility_code).' ';
730  } else {
731  $ret .= $this->civility_code.' ';
732  }
733  }
734 
735  $ret .= dolGetFirstLastname($firstname, $lastname, $nameorder);
736 
737  return dol_trunc($ret, $maxlen);
738  }
739 
745  public function setUpperOrLowerCase()
746  {
747  global $conf;
748 
749  if (!empty($conf->global->MAIN_FIRST_TO_UPPER)) {
750  $this->lastname = dol_ucwords(dol_strtolower($this->lastname));
751  $this->firstname = dol_ucwords(dol_strtolower($this->firstname));
752  $this->name = dol_ucwords(dol_strtolower($this->name));
753  $this->name_alias = isset($this->name_alias)?dol_ucwords(dol_strtolower($this->name_alias)):'';
754  }
755  if (!empty($conf->global->MAIN_ALL_TO_UPPER)) {
756  $this->lastname = dol_strtoupper($this->lastname);
757  $this->name = dol_strtoupper($this->name);
758  $this->name_alias = dol_strtoupper($this->name_alias);
759  }
760  if (!empty($conf->global->MAIN_ALL_TOWN_TO_UPPER)) {
761  $this->address = dol_strtoupper($this->address);
762  $this->town = dol_strtoupper($this->town);
763  }
764  if (isset($this->email)) {
765  $this->email = dol_strtolower($this->email);
766  }
767  if (isset($this->personal_email)) {
768  $this->personal_email = dol_strtolower($this->personal_email);
769  }
770  }
771 
778  public function getKanbanView($option = '')
779  {
780  $return = '<div class="box-flex-item box-flex-grow-zero">';
781  $return .= '<div class="info-box info-box-sm">';
782  $return .= '<span class="info-box-icon bg-infobox-action">';
783  $return .= img_picto('', $this->picto);
784  $return .= '</span>';
785  $return .= '<div class="info-box-content">';
786  $return .= '<span class="info-box-ref">'.(method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref).'</span>';
787  if (property_exists($this, 'label')) {
788  $return .= '<br><span class="info-box-label opacitymedium">'.$this->label.'</span>';
789  }
790  if (method_exists($this, 'getLibStatut')) {
791  $return .= '<br><div class="info-box-status margintoponly">'.$this->getLibStatut(5).'</div>';
792  }
793  $return .= '</div>';
794  $return .= '</div>';
795  $return .= '</div>';
796 
797  return $return;
798  }
799 
809  public function getFullAddress($withcountry = 0, $sep = "\n", $withregion = 0, $extralangcode = '')
810  {
811  if ($withcountry && $this->country_id && (empty($this->country_code) || empty($this->country))) {
812  require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
813  $tmparray = getCountry($this->country_id, 'all');
814  $this->country_code = $tmparray['code'];
815  $this->country = $tmparray['label'];
816  }
817 
818  if ($withregion && $this->state_id && (empty($this->state_code) || empty($this->state) || empty($this->region) || empty($this->region_code))) {
819  require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
820  $tmparray = getState($this->state_id, 'all', 0, 1);
821  $this->state_code = $tmparray['code'];
822  $this->state = $tmparray['label'];
823  $this->region_code = $tmparray['region_code'];
824  $this->region = $tmparray['region'];
825  }
826 
827  return dol_format_address($this, $withcountry, $sep, '', 0, $extralangcode);
828  }
829 
830 
838  public function getBannerAddress($htmlkey, $object)
839  {
840  global $conf, $langs, $form, $extralanguages;
841 
842  $countriesusingstate = array('AU', 'US', 'IN', 'GB', 'ES', 'UK', 'TR'); // See also option MAIN_FORCE_STATE_INTO_ADDRESS
843 
844  $contactid = 0;
845  $thirdpartyid = 0;
846  $elementforaltlanguage = $this->element;
847  if ($this->element == 'societe') {
848  $thirdpartyid = $this->id;
849  }
850  if ($this->element == 'contact') {
851  $contactid = $this->id;
852  $thirdpartyid = empty($object->fk_soc) ? 0 : $object->fk_soc;
853  }
854  if ($this->element == 'user') {
855  $contactid = $this->contact_id;
856  $thirdpartyid = empty($object->fk_soc) ? 0 : $object->fk_soc;
857  }
858 
859  $out = '';
860 
861  $outdone = 0;
862  $coords = $this->getFullAddress(1, ', ', (!empty($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT) ? $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT : 0));
863  if ($coords) {
864  if (!empty($conf->use_javascript_ajax)) {
865  // Add picto with tooltip on map
866  $namecoords = '';
867  if ($this->element == 'contact' && !empty($conf->global->MAIN_SHOW_COMPANY_NAME_IN_BANNER_ADDRESS)) {
868  $namecoords .= $object->name.'<br>';
869  }
870  $namecoords .= $this->getFullName($langs, 1).'<br>'.$coords;
871  // hideonsmatphone because copyToClipboard call jquery dialog that does not work with jmobile
872  $out .= '<a href="#" class="hideonsmartphone" onclick="return copyToClipboard(\''.dol_escape_js($namecoords).'\',\''.dol_escape_js($langs->trans("HelpCopyToClipboard")).'\');">';
873  $out .= img_picto($langs->trans("Address"), 'map-marker-alt');
874  $out .= '</a> ';
875  }
876  $out .= dol_print_address($coords, 'address_'.$htmlkey.'_'.$this->id, $this->element, $this->id, 1, ', ');
877  $outdone++;
878  $outdone++;
879 
880  // List of extra languages
881  $arrayoflangcode = array();
882  if (!empty($conf->global->PDF_USE_ALSO_LANGUAGE_CODE)) {
883  $arrayoflangcode[] = $conf->global->PDF_USE_ALSO_LANGUAGE_CODE;
884  }
885 
886  if (is_array($arrayoflangcode) && count($arrayoflangcode)) {
887  if (!is_object($extralanguages)) {
888  include_once DOL_DOCUMENT_ROOT.'/core/class/extralanguages.class.php';
889  $extralanguages = new ExtraLanguages($this->db);
890  }
891  $extralanguages->fetch_name_extralanguages($elementforaltlanguage);
892 
893  if (!empty($extralanguages->attributes[$elementforaltlanguage]['address']) || !empty($extralanguages->attributes[$elementforaltlanguage]['town'])) {
894  $out .= "<!-- alternatelanguage for '".$elementforaltlanguage."' set to fields '".join(',', $extralanguages->attributes[$elementforaltlanguage])."' -->\n";
895  $this->fetchValuesForExtraLanguages();
896  if (!is_object($form)) {
897  $form = new Form($this->db);
898  }
899  $htmltext = '';
900  // If there is extra languages
901  foreach ($arrayoflangcode as $extralangcode) {
902  $s = picto_from_langcode($extralangcode, 'class="pictoforlang paddingright"');
903  $coords = $this->getFullAddress(1, ', ', $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT, $extralangcode);
904  $htmltext .= $s.dol_print_address($coords, 'address_'.$htmlkey.'_'.$this->id, $this->element, $this->id, 1, ', ');
905  }
906  $out .= $form->textwithpicto('', $htmltext, -1, 'language', 'opacitymedium paddingleft');
907  }
908  }
909  }
910 
911  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
912  && empty($conf->global->SOCIETE_DISABLE_STATE) && $this->state) {
913  if (!empty($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT) && $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT == 1 && $this->region) {
914  $out .= ($outdone ? ' - ' : '').$this->region.' - '.$this->state;
915  } else {
916  $out .= ($outdone ? ' - ' : '').$this->state;
917  }
918  $outdone++;
919  }
920 
921  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)) {
922  $out .= ($outdone ? '<br>' : '');
923  }
924  if (!empty($this->phone) && empty($this->phone_pro)) { // For objects that store pro phone into ->phone
925  $out .= dol_print_phone($this->phone, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'phone', $langs->trans("PhonePro"));
926  $outdone++;
927  }
928  if (!empty($this->phone_pro)) {
929  $out .= dol_print_phone($this->phone_pro, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'phone', $langs->trans("PhonePro"));
930  $outdone++;
931  }
932  if (!empty($this->phone_mobile)) {
933  $out .= dol_print_phone($this->phone_mobile, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'mobile', $langs->trans("PhoneMobile"));
934  $outdone++;
935  }
936  if (!empty($this->phone_perso)) {
937  $out .= dol_print_phone($this->phone_perso, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'phone', $langs->trans("PhonePerso"));
938  $outdone++;
939  }
940  if (!empty($this->office_phone)) {
941  $out .= dol_print_phone($this->office_phone, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'phone', $langs->trans("PhonePro"));
942  $outdone++;
943  }
944  if (!empty($this->user_mobile)) {
945  $out .= dol_print_phone($this->user_mobile, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'mobile', $langs->trans("PhoneMobile"));
946  $outdone++;
947  }
948  if (!empty($this->fax)) {
949  $out .= dol_print_phone($this->fax, $this->country_code, $contactid, $thirdpartyid, 'AC_FAX', '&nbsp;', 'fax', $langs->trans("Fax"));
950  $outdone++;
951  }
952  if (!empty($this->office_fax)) {
953  $out .= dol_print_phone($this->office_fax, $this->country_code, $contactid, $thirdpartyid, 'AC_FAX', '&nbsp;', 'fax', $langs->trans("Fax"));
954  $outdone++;
955  }
956 
957  if ($out) {
958  $out .= '<div style="clear: both;"></div>';
959  }
960  $outdone = 0;
961  if (!empty($this->email)) {
962  $out .= dol_print_email($this->email, $this->id, $object->id, 'AC_EMAIL', 0, 0, 1);
963  $outdone++;
964  }
965  if (!empty($this->url)) {
966  //$out.=dol_print_url($this->url,'_goout',0,1);//steve changed to blank
967  $out .= dol_print_url($this->url, '_blank', 0, 1);
968  $outdone++;
969  }
970 
971  if (isModEnabled('socialnetworks')) {
972  $outsocialnetwork = '';
973 
974  if (!empty($this->socialnetworks) && is_array($this->socialnetworks) && count($this->socialnetworks) > 0) {
975  $socialnetworksdict = getArrayOfSocialNetworks();
976  foreach ($this->socialnetworks as $key => $value) {
977  if ($value) {
978  $outsocialnetwork .= dol_print_socialnetworks($value, $this->id, $object->id, $key, $socialnetworksdict);
979  }
980  $outdone++;
981  }
982  } else { // Old code to remove
983  if (!empty($this->skype)) {
984  $outsocialnetwork .= dol_print_socialnetworks($this->skype, $this->id, $object->id, 'skype');
985  }
986  $outdone++;
987  if (!empty($this->jabberid)) {
988  $outsocialnetwork .= dol_print_socialnetworks($this->jabberid, $this->id, $object->id, 'jabber');
989  }
990  $outdone++;
991  if (!empty($this->twitter)) {
992  $outsocialnetwork .= dol_print_socialnetworks($this->twitter, $this->id, $object->id, 'twitter');
993  }
994  $outdone++;
995  if (!empty($this->facebook)) {
996  $outsocialnetwork .= dol_print_socialnetworks($this->facebook, $this->id, $object->id, 'facebook');
997  }
998  $outdone++;
999  if (!empty($this->linkedin)) {
1000  $outsocialnetwork .= dol_print_socialnetworks($this->linkedin, $this->id, $object->id, 'linkedin');
1001  }
1002  $outdone++;
1003  }
1004 
1005  if ($outsocialnetwork) {
1006  $out .= '<div style="clear: both;">'.$outsocialnetwork.'</div>';
1007  }
1008  }
1009 
1010  if ($out) {
1011  return '<!-- BEGIN part to show address block -->'."\n".$out.'<!-- END Part to show address block -->'."\n";
1012  } else {
1013  return '';
1014  }
1015  }
1016 
1025  public function getLastMainDocLink($modulepart, $initsharekey = 0, $relativelink = 0)
1026  {
1027  global $user, $dolibarr_main_url_root;
1028 
1029  if (empty($this->last_main_doc)) {
1030  return ''; // No way to known which document name to use
1031  }
1032 
1033  include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
1034  $ecmfile = new EcmFiles($this->db);
1035  $result = $ecmfile->fetch(0, '', $this->last_main_doc);
1036  if ($result < 0) {
1037  $this->error = $ecmfile->error;
1038  $this->errors = $ecmfile->errors;
1039  return -1;
1040  }
1041 
1042  if (empty($ecmfile->id)) {
1043  // Add entry into index
1044  if ($initsharekey) {
1045  require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
1046 
1047  // 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
1048  /*
1049  $ecmfile->filepath = $rel_dir;
1050  $ecmfile->filename = $filename;
1051  $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
1052  $ecmfile->fullpath_orig = '';
1053  $ecmfile->gen_or_uploaded = 'generated';
1054  $ecmfile->description = ''; // indexed content
1055  $ecmfile->keywords = ''; // keyword content
1056  $ecmfile->share = getRandomPassword(true);
1057  $result = $ecmfile->create($user);
1058  if ($result < 0)
1059  {
1060  $this->error = $ecmfile->error;
1061  $this->errors = $ecmfile->errors;
1062  }
1063  */
1064  } else {
1065  return '';
1066  }
1067  } elseif (empty($ecmfile->share)) {
1068  // Add entry into index
1069  if ($initsharekey) {
1070  require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
1071  $ecmfile->share = getRandomPassword(true);
1072  $ecmfile->update($user);
1073  } else {
1074  return '';
1075  }
1076  }
1077  // Define $urlwithroot
1078  $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
1079  // This is to use external domain name found into config file
1080  //if (DOL_URL_ROOT && ! preg_match('/\/$/', $urlwithouturlroot) && ! preg_match('/^\//', DOL_URL_ROOT)) $urlwithroot=$urlwithouturlroot.'/'.DOL_URL_ROOT;
1081  //else
1082  $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT;
1083  //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
1084 
1085  $forcedownload = 0;
1086 
1087  $paramlink = '';
1088  //if (!empty($modulepart)) $paramlink.=($paramlink?'&':'').'modulepart='.$modulepart; // For sharing with hash (so public files), modulepart is not required.
1089  //if (!empty($ecmfile->entity)) $paramlink.='&entity='.$ecmfile->entity; // For sharing with hash (so public files), entity is not required.
1090  //$paramlink.=($paramlink?'&':'').'file='.urlencode($filepath); // No need of name of file for public link, we will use the hash
1091  if (!empty($ecmfile->share)) {
1092  $paramlink .= ($paramlink ? '&' : '').'hashp='.$ecmfile->share; // Hash for public share
1093  }
1094  if ($forcedownload) {
1095  $paramlink .= ($paramlink ? '&' : '').'attachment=1';
1096  }
1097 
1098  if ($relativelink) {
1099  $linktoreturn = 'document.php'.($paramlink ? '?'.$paramlink : '');
1100  } else {
1101  $linktoreturn = $urlwithroot.'/document.php'.($paramlink ? '?'.$paramlink : '');
1102  }
1103 
1104  // Here $ecmfile->share is defined
1105  return $linktoreturn;
1106  }
1107 
1108 
1109  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1119  public function add_contact($fk_socpeople, $type_contact, $source = 'external', $notrigger = 0)
1120  {
1121  // phpcs:enable
1122  global $user, $langs;
1123 
1124 
1125  dol_syslog(get_class($this)."::add_contact $fk_socpeople, $type_contact, $source, $notrigger");
1126 
1127  // Check parameters
1128  if ($fk_socpeople <= 0) {
1129  $langs->load("errors");
1130  $this->error = $langs->trans("ErrorWrongValueForParameterX", "1");
1131  dol_syslog(get_class($this)."::add_contact ".$this->error, LOG_ERR);
1132  return -1;
1133  }
1134  if (!$type_contact) {
1135  $langs->load("errors");
1136  $this->error = $langs->trans("ErrorWrongValueForParameterX", "2");
1137  dol_syslog(get_class($this)."::add_contact ".$this->error, LOG_ERR);
1138  return -2;
1139  }
1140 
1141  $id_type_contact = 0;
1142  if (is_numeric($type_contact)) {
1143  $id_type_contact = $type_contact;
1144  } else {
1145  // We look for id type_contact
1146  $sql = "SELECT tc.rowid";
1147  $sql .= " FROM ".$this->db->prefix()."c_type_contact as tc";
1148  $sql .= " WHERE tc.element='".$this->db->escape($this->element)."'";
1149  $sql .= " AND tc.source='".$this->db->escape($source)."'";
1150  $sql .= " AND tc.code='".$this->db->escape($type_contact)."' AND tc.active=1";
1151  //print $sql;
1152  $resql = $this->db->query($sql);
1153  if ($resql) {
1154  $obj = $this->db->fetch_object($resql);
1155  if ($obj) {
1156  $id_type_contact = $obj->rowid;
1157  }
1158  }
1159  }
1160 
1161  if ($id_type_contact == 0) {
1162  $this->error = 'CODE_NOT_VALID_FOR_THIS_ELEMENT';
1163  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");
1164  return -3;
1165  }
1166 
1167  $datecreate = dol_now();
1168 
1169  // Socpeople must have already been added by some trigger, then we have to check it to avoid DB_ERROR_RECORD_ALREADY_EXISTS error
1170  $TListeContacts = $this->liste_contact(-1, $source);
1171  $already_added = false;
1172  if (is_array($TListeContacts) && !empty($TListeContacts)) {
1173  foreach ($TListeContacts as $array_contact) {
1174  if ($array_contact['status'] == 4 && $array_contact['id'] == $fk_socpeople && $array_contact['fk_c_type_contact'] == $id_type_contact) {
1175  $already_added = true;
1176  break;
1177  }
1178  }
1179  }
1180 
1181  if (!$already_added) {
1182  $this->db->begin();
1183 
1184  // Insert into database
1185  $sql = "INSERT INTO ".$this->db->prefix()."element_contact";
1186  $sql .= " (element_id, fk_socpeople, datecreate, statut, fk_c_type_contact) ";
1187  $sql .= " VALUES (".$this->id.", ".((int) $fk_socpeople)." , ";
1188  $sql .= "'".$this->db->idate($datecreate)."'";
1189  $sql .= ", 4, ".((int) $id_type_contact);
1190  $sql .= ")";
1191 
1192  $resql = $this->db->query($sql);
1193  if ($resql) {
1194  if (!$notrigger) {
1195  $result = $this->call_trigger(strtoupper($this->element).'_ADD_CONTACT', $user);
1196  if ($result < 0) {
1197  $this->db->rollback();
1198  return -1;
1199  }
1200  }
1201 
1202  $this->db->commit();
1203  return 1;
1204  } else {
1205  if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
1206  $this->error = $this->db->errno();
1207  $this->db->rollback();
1208  return -2;
1209  } else {
1210  $this->error = $this->db->lasterror();
1211  $this->db->rollback();
1212  return -1;
1213  }
1214  }
1215  } else {
1216  return 0;
1217  }
1218  }
1219 
1220  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1228  public function copy_linked_contact($objFrom, $source = 'internal')
1229  {
1230  // phpcs:enable
1231  $contacts = $objFrom->liste_contact(-1, $source);
1232  foreach ($contacts as $contact) {
1233  if ($this->add_contact($contact['id'], $contact['fk_c_type_contact'], $contact['source']) < 0) {
1234  return -1;
1235  }
1236  }
1237  return 1;
1238  }
1239 
1240  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1250  public function update_contact($rowid, $statut, $type_contact_id = 0, $fk_socpeople = 0)
1251  {
1252  // phpcs:enable
1253  // Insert into database
1254  $sql = "UPDATE ".$this->db->prefix()."element_contact set";
1255  $sql .= " statut = ".$statut;
1256  if ($type_contact_id) {
1257  $sql .= ", fk_c_type_contact = ".((int) $type_contact_id);
1258  }
1259  if ($fk_socpeople) {
1260  $sql .= ", fk_socpeople = ".((int) $fk_socpeople);
1261  }
1262  $sql .= " where rowid = ".((int) $rowid);
1263  $resql = $this->db->query($sql);
1264  if ($resql) {
1265  return 0;
1266  } else {
1267  $this->error = $this->db->lasterror();
1268  return -1;
1269  }
1270  }
1271 
1272  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1280  public function delete_contact($rowid, $notrigger = 0)
1281  {
1282  // phpcs:enable
1283  global $user;
1284 
1285 
1286  $this->db->begin();
1287 
1288  $sql = "DELETE FROM ".$this->db->prefix()."element_contact";
1289  $sql .= " WHERE rowid = ".((int) $rowid);
1290 
1291  dol_syslog(get_class($this)."::delete_contact", LOG_DEBUG);
1292  if ($this->db->query($sql)) {
1293  if (!$notrigger) {
1294  $result = $this->call_trigger(strtoupper($this->element).'_DELETE_CONTACT', $user);
1295  if ($result < 0) {
1296  $this->db->rollback();
1297  return -1;
1298  }
1299  }
1300 
1301  $this->db->commit();
1302  return 1;
1303  } else {
1304  $this->error = $this->db->lasterror();
1305  $this->db->rollback();
1306  return -1;
1307  }
1308  }
1309 
1310  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1318  public function delete_linked_contact($source = '', $code = '')
1319  {
1320  // phpcs:enable
1321  $listId = '';
1322  $temp = array();
1323  $typeContact = $this->liste_type_contact($source, '', 0, 0, $code);
1324 
1325  if (!empty($typeContact)) {
1326  foreach ($typeContact as $key => $value) {
1327  array_push($temp, $key);
1328  }
1329  $listId = implode(",", $temp);
1330  }
1331 
1332  $sql = "DELETE FROM ".$this->db->prefix()."element_contact";
1333  $sql .= " WHERE element_id = ".((int) $this->id);
1334  if (!empty($listId)) {
1335  $sql .= " AND fk_c_type_contact IN (".$this->db->sanitize($listId).")";
1336  }
1337 
1338  dol_syslog(get_class($this)."::delete_linked_contact", LOG_DEBUG);
1339  if ($this->db->query($sql)) {
1340  return 1;
1341  } else {
1342  $this->error = $this->db->lasterror();
1343  return -1;
1344  }
1345  }
1346 
1347  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1358  public function liste_contact($statusoflink = -1, $source = 'external', $list = 0, $code = '', $status = -1)
1359  {
1360  // phpcs:enable
1361  global $langs;
1362 
1363  $tab = array();
1364 
1365  $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
1366  if ($source == 'internal') {
1367  $sql .= ", '-1' as socid, t.statut as statuscontact, t.login, t.photo";
1368  }
1369  if ($source == 'external' || $source == 'thirdparty') {
1370  $sql .= ", t.fk_soc as socid, t.statut as statuscontact";
1371  }
1372  $sql .= ", t.civility as civility, t.lastname as lastname, t.firstname, t.email";
1373  $sql .= ", tc.source, tc.element, tc.code, tc.libelle";
1374  $sql .= " FROM ".$this->db->prefix()."c_type_contact tc";
1375  $sql .= ", ".$this->db->prefix()."element_contact ec";
1376  if ($source == 'internal') { // internal contact (user)
1377  $sql .= " LEFT JOIN ".$this->db->prefix()."user t on ec.fk_socpeople = t.rowid";
1378  }
1379  if ($source == 'external' || $source == 'thirdparty') { // external contact (socpeople)
1380  $sql .= " LEFT JOIN ".$this->db->prefix()."socpeople t on ec.fk_socpeople = t.rowid";
1381  }
1382  $sql .= " WHERE ec.element_id = ".((int) $this->id);
1383  $sql .= " AND ec.fk_c_type_contact = tc.rowid";
1384  $sql .= " AND tc.element = '".$this->db->escape($this->element)."'";
1385  if ($code) {
1386  $sql .= " AND tc.code = '".$this->db->escape($code)."'";
1387  }
1388  if ($source == 'internal') {
1389  $sql .= " AND tc.source = 'internal'";
1390  if ($status >= 0) {
1391  $sql .= " AND t.statut = ".((int) $status);
1392  }
1393  }
1394  if ($source == 'external' || $source == 'thirdparty') {
1395  $sql .= " AND tc.source = 'external'";
1396  if ($status >= 0) {
1397  $sql .= " AND t.statut = ".((int) $status); // t is llx_socpeople
1398  }
1399  }
1400  $sql .= " AND tc.active=1";
1401  if ($statusoflink >= 0) {
1402  $sql .= " AND ec.statut = ".((int) $statusoflink);
1403  }
1404  $sql .= " ORDER BY t.lastname ASC";
1405 
1406  dol_syslog(get_class($this)."::liste_contact", LOG_DEBUG);
1407  $resql = $this->db->query($sql);
1408  if ($resql) {
1409  $num = $this->db->num_rows($resql);
1410  $i = 0;
1411  while ($i < $num) {
1412  $obj = $this->db->fetch_object($resql);
1413 
1414  if (!$list) {
1415  $transkey = "TypeContact_".$obj->element."_".$obj->source."_".$obj->code;
1416  $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle);
1417  $tab[$i] = array(
1418  'source' => $obj->source,
1419  'socid' => $obj->socid,
1420  'id' => $obj->id,
1421  'nom' => $obj->lastname, // For backward compatibility
1422  'civility' => $obj->civility,
1423  'lastname' => $obj->lastname,
1424  'firstname' => $obj->firstname,
1425  'email'=>$obj->email,
1426  'login'=> (empty($obj->login) ? '' : $obj->login),
1427  'photo' => (empty($obj->photo) ? '' : $obj->photo),
1428  'statuscontact' => $obj->statuscontact,
1429  'rowid' => $obj->rowid,
1430  'code' => $obj->code,
1431  'libelle' => $libelle_type,
1432  'status' => $obj->statuslink,
1433  'fk_c_type_contact' => $obj->fk_c_type_contact
1434  );
1435  } else {
1436  $tab[$i] = $obj->id;
1437  }
1438 
1439  $i++;
1440  }
1441 
1442  return $tab;
1443  } else {
1444  $this->error = $this->db->lasterror();
1445  dol_print_error($this->db);
1446  return -1;
1447  }
1448  }
1449 
1450 
1457  public function swapContactStatus($rowid)
1458  {
1459  $sql = "SELECT ec.datecreate, ec.statut, ec.fk_socpeople, ec.fk_c_type_contact,";
1460  $sql .= " tc.code, tc.libelle";
1461  $sql .= " FROM (".$this->db->prefix()."element_contact as ec, ".$this->db->prefix()."c_type_contact as tc)";
1462  $sql .= " WHERE ec.rowid =".((int) $rowid);
1463  $sql .= " AND ec.fk_c_type_contact=tc.rowid";
1464  $sql .= " AND tc.element = '".$this->db->escape($this->element)."'";
1465 
1466  dol_syslog(get_class($this)."::swapContactStatus", LOG_DEBUG);
1467  $resql = $this->db->query($sql);
1468  if ($resql) {
1469  $obj = $this->db->fetch_object($resql);
1470  $newstatut = ($obj->statut == 4) ? 5 : 4;
1471  $result = $this->update_contact($rowid, $newstatut);
1472  $this->db->free($resql);
1473  return $result;
1474  } else {
1475  $this->error = $this->db->error();
1476  dol_print_error($this->db);
1477  return -1;
1478  }
1479  }
1480 
1481  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1492  public function liste_type_contact($source = 'internal', $order = 'position', $option = 0, $activeonly = 0, $code = '')
1493  {
1494  // phpcs:enable
1495  global $langs;
1496 
1497  if (empty($order)) {
1498  $order = 'position';
1499  }
1500  if ($order == 'position') {
1501  $order .= ',code';
1502  }
1503 
1504  $tab = array();
1505  $sql = "SELECT DISTINCT tc.rowid, tc.code, tc.libelle, tc.position";
1506  $sql .= " FROM ".$this->db->prefix()."c_type_contact as tc";
1507  $sql .= " WHERE tc.element='".$this->db->escape($this->element)."'";
1508  if ($activeonly == 1) {
1509  $sql .= " AND tc.active=1"; // only the active types
1510  }
1511  if (!empty($source) && $source != 'all') {
1512  $sql .= " AND tc.source='".$this->db->escape($source)."'";
1513  }
1514  if (!empty($code)) {
1515  $sql .= " AND tc.code='".$this->db->escape($code)."'";
1516  }
1517  $sql .= $this->db->order($order, 'ASC');
1518 
1519  //print "sql=".$sql;
1520  $resql = $this->db->query($sql);
1521  if ($resql) {
1522  $num = $this->db->num_rows($resql);
1523  $i = 0;
1524  while ($i < $num) {
1525  $obj = $this->db->fetch_object($resql);
1526 
1527  $transkey = "TypeContact_".$this->element."_".$source."_".$obj->code;
1528  $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle);
1529  if (empty($option)) {
1530  $tab[$obj->rowid] = $libelle_type;
1531  } else {
1532  $tab[$obj->code] = $libelle_type;
1533  }
1534  $i++;
1535  }
1536  return $tab;
1537  } else {
1538  $this->error = $this->db->lasterror();
1539  //dol_print_error($this->db);
1540  return null;
1541  }
1542  }
1543 
1555  public function listeTypeContacts($source = 'internal', $option = 0, $activeonly = 0, $code = '', $element = '', $excludeelement = '')
1556  {
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 (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 ($this->table_element == 'facture_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  return 0;
3343  }
3344 
3351  public function getIdOfLine($rang)
3352  {
3353  $fieldposition = 'rang';
3354  if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
3355  $fieldposition = 'position';
3356  }
3357 
3358  $sql = "SELECT rowid FROM ".$this->db->prefix().$this->table_element_line;
3359  $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
3360  $sql .= " AND " . $fieldposition . " = ".((int) $rang);
3361  $resql = $this->db->query($sql);
3362  if ($resql) {
3363  $row = $this->db->fetch_row($resql);
3364  return $row[0];
3365  }
3366 
3367  return 0;
3368  }
3369 
3370  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3377  public function line_max($fk_parent_line = 0)
3378  {
3379  // phpcs:enable
3380  $positionfield = 'rang';
3381  if (in_array($this->table_element, array('bom_bom', 'product_attribute'))) {
3382  $positionfield = 'position';
3383  }
3384 
3385  // Search the last rang with fk_parent_line
3386  if ($fk_parent_line) {
3387  $sql = "SELECT max(".$positionfield.") FROM ".$this->db->prefix().$this->table_element_line;
3388  $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
3389  $sql .= " AND fk_parent_line = ".((int) $fk_parent_line);
3390 
3391  dol_syslog(get_class($this)."::line_max", LOG_DEBUG);
3392  $resql = $this->db->query($sql);
3393  if ($resql) {
3394  $row = $this->db->fetch_row($resql);
3395  if (!empty($row[0])) {
3396  return $row[0];
3397  } else {
3398  return $this->getRangOfLine($fk_parent_line);
3399  }
3400  }
3401  } else {
3402  // If not, search the last rang of element
3403  $sql = "SELECT max(".$positionfield.") FROM ".$this->db->prefix().$this->table_element_line;
3404  $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
3405 
3406  dol_syslog(get_class($this)."::line_max", LOG_DEBUG);
3407  $resql = $this->db->query($sql);
3408  if ($resql) {
3409  $row = $this->db->fetch_row($resql);
3410  return $row[0];
3411  }
3412  }
3413 
3414  return 0;
3415  }
3416 
3417  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3424  public function update_ref_ext($ref_ext)
3425  {
3426  // phpcs:enable
3427  if (!$this->table_element) {
3428  dol_syslog(get_class($this)."::update_ref_ext was called on objet with property table_element not defined", LOG_ERR);
3429  return -1;
3430  }
3431 
3432  $sql = "UPDATE ".$this->db->prefix().$this->table_element;
3433  $sql .= " SET ref_ext = '".$this->db->escape($ref_ext)."'";
3434  $sql .= " WHERE ".(isset($this->table_rowid) ? $this->table_rowid : 'rowid')." = ".((int) $this->id);
3435 
3436  dol_syslog(get_class($this)."::update_ref_ext", LOG_DEBUG);
3437  if ($this->db->query($sql)) {
3438  $this->ref_ext = $ref_ext;
3439  return 1;
3440  } else {
3441  $this->error = $this->db->error();
3442  return -1;
3443  }
3444  }
3445 
3446  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3454  public function update_note($note, $suffix = '')
3455  {
3456  // phpcs:enable
3457  global $user;
3458 
3459  if (!$this->table_element) {
3460  $this->error = 'update_note was called on objet with property table_element not defined';
3461  dol_syslog(get_class($this)."::update_note was called on objet with property table_element not defined", LOG_ERR);
3462  return -1;
3463  }
3464  if (!in_array($suffix, array('', '_public', '_private'))) {
3465  $this->error = 'update_note Parameter suffix must be empty, \'_private\' or \'_public\'';
3466  dol_syslog(get_class($this)."::update_note Parameter suffix must be empty, '_private' or '_public'", LOG_ERR);
3467  return -2;
3468  }
3469 
3470  $newsuffix = $suffix;
3471 
3472  // Special cas
3473  if ($this->table_element == 'product' && $newsuffix == '_private') {
3474  $newsuffix = '';
3475  }
3476  if (in_array($this->table_element, array('actioncomm', 'adherent', 'advtargetemailing', 'cronjob', 'establishment'))) {
3477  $fieldusermod = "fk_user_mod";
3478  } elseif ($this->table_element == 'ecm_files') {
3479  $fieldusermod = "fk_user_m";
3480  } else {
3481  $fieldusermod = "fk_user_modif";
3482  }
3483  $sql = "UPDATE ".$this->db->prefix().$this->table_element;
3484  $sql .= " SET note".$newsuffix." = ".(!empty($note) ? ("'".$this->db->escape($note)."'") : "NULL");
3485  $sql .= ", ".$fieldusermod." = ".((int) $user->id);
3486  $sql .= " WHERE rowid = ".((int) $this->id);
3487 
3488  dol_syslog(get_class($this)."::update_note", LOG_DEBUG);
3489  if ($this->db->query($sql)) {
3490  if ($suffix == '_public') {
3491  $this->note_public = $note;
3492  } elseif ($suffix == '_private') {
3493  $this->note_private = $note;
3494  } else {
3495  $this->note = $note; // deprecated
3496  $this->note_private = $note;
3497  }
3498  return 1;
3499  } else {
3500  $this->error = $this->db->lasterror();
3501  return -1;
3502  }
3503  }
3504 
3505  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3514  public function update_note_public($note)
3515  {
3516  // phpcs:enable
3517  return $this->update_note($note, '_public');
3518  }
3519 
3520  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3531  public function update_price($exclspec = 0, $roundingadjust = 'none', $nodatabaseupdate = 0, $seller = null)
3532  {
3533  // phpcs:enable
3534  global $conf, $hookmanager, $action;
3535 
3536  $parameters = array('exclspec' => $exclspec, 'roundingadjust' => $roundingadjust, 'nodatabaseupdate' => $nodatabaseupdate, 'seller' => $seller);
3537  $reshook = $hookmanager->executeHooks('updateTotalPrice', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
3538  if ($reshook > 0) {
3539  return 1; // replacement code
3540  } elseif ($reshook < 0) {
3541  return -1; // failure
3542  } // reshook = 0 => execute normal code
3543 
3544  // Some external module want no update price after a trigger because they have another method to calculate the total (ex: with an extrafield)
3545  $MODULE = "";
3546  if ($this->element == 'propal') {
3547  $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_PROPOSAL";
3548  } elseif ($this->element == 'commande' || $this->element == 'order') {
3549  $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_ORDER";
3550  } elseif ($this->element == 'facture' || $this->element == 'invoice') {
3551  $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_INVOICE";
3552  } elseif ($this->element == 'facture_fourn' || $this->element == 'supplier_invoice' || $this->element == 'invoice_supplier' || $this->element == 'invoice_supplier_rec') {
3553  $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_INVOICE";
3554  } elseif ($this->element == 'order_supplier' || $this->element == 'supplier_order') {
3555  $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_ORDER";
3556  } elseif ($this->element == 'supplier_proposal') {
3557  $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_PROPOSAL";
3558  }
3559 
3560  if (!empty($MODULE)) {
3561  if (!empty($conf->global->$MODULE)) {
3562  $modsactivated = explode(',', $conf->global->$MODULE);
3563  foreach ($modsactivated as $mod) {
3564  if (isModEnabled($mod)) {
3565  return 1; // update was disabled by specific setup
3566  }
3567  }
3568  }
3569  }
3570 
3571  include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
3572 
3573  $forcedroundingmode = $roundingadjust;
3574  if ($forcedroundingmode == 'auto' && isset($conf->global->MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND)) {
3575  $forcedroundingmode = getDolGlobalString('MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND');
3576  } elseif ($forcedroundingmode == 'auto') {
3577  $forcedroundingmode = '0';
3578  }
3579 
3580  $error = 0;
3581 
3582  $multicurrency_tx = !empty($this->multicurrency_tx) ? $this->multicurrency_tx : 1;
3583 
3584  // Define constants to find lines to sum (field name int the table_element_line not into table_element)
3585  $fieldtva = 'total_tva';
3586  $fieldlocaltax1 = 'total_localtax1';
3587  $fieldlocaltax2 = 'total_localtax2';
3588  $fieldup = 'subprice';
3589  if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier') {
3590  $fieldtva = 'tva';
3591  $fieldup = 'pu_ht';
3592  }
3593  if ($this->element == 'invoice_supplier_rec') {
3594  $fieldup = 'pu_ht';
3595  }
3596  if ($this->element == 'expensereport') {
3597  $fieldup = 'value_unit';
3598  }
3599 
3600  $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,";
3601  $sql .= ' tva_tx as vatrate, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type, info_bits, product_type';
3602  if ($this->table_element_line == 'facturedet') {
3603  $sql .= ', situation_percent';
3604  }
3605  $sql .= ', multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc';
3606  $sql .= " FROM ".$this->db->prefix().$this->table_element_line;
3607  $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
3608  if ($exclspec) {
3609  $product_field = 'product_type';
3610  if ($this->table_element_line == 'contratdet') {
3611  $product_field = ''; // contratdet table has no product_type field
3612  }
3613  if ($product_field) {
3614  $sql .= " AND ".$product_field." <> 9";
3615  }
3616  }
3617  $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
3618 
3619  dol_syslog(get_class($this)."::update_price", LOG_DEBUG);
3620 
3621  $resql = $this->db->query($sql);
3622  if ($resql) {
3623  $this->total_ht = 0;
3624  $this->total_tva = 0;
3625  $this->total_localtax1 = 0;
3626  $this->total_localtax2 = 0;
3627  $this->total_ttc = 0;
3628  $total_ht_by_vats = array();
3629  $total_tva_by_vats = array();
3630  $total_ttc_by_vats = array();
3631  $this->multicurrency_total_ht = 0;
3632  $this->multicurrency_total_tva = 0;
3633  $this->multicurrency_total_ttc = 0;
3634 
3635  $num = $this->db->num_rows($resql);
3636  $i = 0;
3637  while ($i < $num) {
3638  $obj = $this->db->fetch_object($resql);
3639 
3640  // Note: There is no check on detail line and no check on total, if $forcedroundingmode = 'none'
3641  $parameters = array('fk_element' => $obj->rowid);
3642  $reshook = $hookmanager->executeHooks('changeRoundingMode', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
3643 
3644  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'
3645  // This part of code is to fix data. We should not call it too often.
3646  $localtax_array = array($obj->localtax1_type, $obj->localtax1_tx, $obj->localtax2_type, $obj->localtax2_tx);
3647  $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);
3648 
3649  $diff_when_using_price_ht = price2num($tmpcal[1] - $obj->total_tva, 'MT', 1); // If price was set with tax price and unit price HT has a low number of digits, then we may have a diff on recalculation from unit price HT.
3650  $diff_on_current_total = price2num($obj->total_ttc - $obj->total_ht - $obj->total_tva - $obj->total_localtax1 - $obj->total_localtax2, 'MT', 1);
3651  //var_dump($obj->total_ht.' '.$obj->total_tva.' '.$obj->total_localtax1.' '.$obj->total_localtax2.' => '.$obj->total_ttc);
3652  //var_dump($diff_when_using_price_ht.' '.$diff_on_current_total);
3653 
3654  if ($diff_on_current_total) {
3655  // This should not happen, we should always have in table: total_ttc = total_ht + total_vat + total_localtax1 + total_localtax2
3656  $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);
3657  dol_syslog('We found unconsistent data into detailed line (diff_on_current_total = '.$diff_on_current_total.') for line rowid = '.$obj->rowid." (ht=".$obj->total_ht." vat=".$obj->total_tva." tax1=".$obj->total_localtax1." tax2=".$obj->total_localtax2." ttc=".$obj->total_ttc."). We fix the total_vat and total_ttc of line by running sqlfix = ".$sqlfix, LOG_WARNING);
3658  $resqlfix = $this->db->query($sqlfix);
3659  if (!$resqlfix) {
3660  dol_print_error($this->db, 'Failed to update line');
3661  }
3662  $obj->total_tva = $tmpcal[1];
3663  $obj->total_ttc = $tmpcal[2];
3664  } elseif ($diff_when_using_price_ht && $roundingadjust == '0') {
3665  // After calculation from HT, total is consistent but we have found a difference between VAT part in calculation and into database and
3666  // we ask to force the use of rounding on line (like done on calculation) so we force update of line
3667  $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);
3668  dol_syslog('We found a line with different rounding data into detailed line (diff_when_using_price_ht = '.$diff_when_using_price_ht.' and diff_on_current_total = '.$diff_on_current_total.') for line rowid = '.$obj->rowid." (total vat of line calculated=".$tmpcal[1].", database=".$obj->total_tva."). We fix the total_vat and total_ttc of line by running sqlfix = ".$sqlfix);
3669  $resqlfix = $this->db->query($sqlfix);
3670  if (!$resqlfix) {
3671  dol_print_error($this->db, 'Failed to update line');
3672  }
3673  $obj->total_tva = $tmpcal[1];
3674  $obj->total_ttc = $tmpcal[2];
3675  }
3676  }
3677 
3678  $this->total_ht += $obj->total_ht; // The field visible at end of line detail
3679  $this->total_tva += $obj->total_tva;
3680  $this->total_localtax1 += $obj->total_localtax1;
3681  $this->total_localtax2 += $obj->total_localtax2;
3682  $this->total_ttc += $obj->total_ttc;
3683  $this->multicurrency_total_ht += $obj->multicurrency_total_ht; // The field visible at end of line detail
3684  $this->multicurrency_total_tva += $obj->multicurrency_total_tva;
3685  $this->multicurrency_total_ttc += $obj->multicurrency_total_ttc;
3686 
3687  if (!isset($total_ht_by_vats[$obj->vatrate])) {
3688  $total_ht_by_vats[$obj->vatrate] = 0;
3689  }
3690  if (!isset($total_tva_by_vats[$obj->vatrate])) {
3691  $total_tva_by_vats[$obj->vatrate] = 0;
3692  }
3693  if (!isset($total_ttc_by_vats[$obj->vatrate])) {
3694  $total_ttc_by_vats[$obj->vatrate] = 0;
3695  }
3696  $total_ht_by_vats[$obj->vatrate] += $obj->total_ht;
3697  $total_tva_by_vats[$obj->vatrate] += $obj->total_tva;
3698  $total_ttc_by_vats[$obj->vatrate] += $obj->total_ttc;
3699 
3700  if ($forcedroundingmode == '1') { // Check if we need adjustement onto line for vat. TODO This works on the company currency but not on multicurrency
3701  $tmpvat = price2num($total_ht_by_vats[$obj->vatrate] * $obj->vatrate / 100, 'MT', 1);
3702  $diff = price2num($total_tva_by_vats[$obj->vatrate] - $tmpvat, 'MT', 1);
3703  //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";
3704  if ($diff) {
3705  if (abs($diff) > 0.1) {
3706  $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.';
3707  dol_syslog($errmsg, LOG_WARNING);
3708  dol_print_error('', $errmsg);
3709  exit;
3710  }
3711  $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);
3712  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);
3713 
3714  $resqlfix = $this->db->query($sqlfix);
3715 
3716  if (!$resqlfix) {
3717  dol_print_error($this->db, 'Failed to update line');
3718  }
3719 
3720  $this->total_tva = (float) price2num($this->total_tva - $diff, '', 1);
3721  $this->total_ttc = (float) price2num($this->total_ttc - $diff, '', 1);
3722  $total_tva_by_vats[$obj->vatrate] = (float) price2num($total_tva_by_vats[$obj->vatrate] - $diff, '', 1);
3723  $total_ttc_by_vats[$obj->vatrate] = (float) price2num($total_ttc_by_vats[$obj->vatrate] - $diff, '', 1);
3724  }
3725  }
3726 
3727  $i++;
3728  }
3729 
3730  // Add revenue stamp to total
3731  $this->total_ttc += isset($this->revenuestamp) ? $this->revenuestamp : 0;
3732  $this->multicurrency_total_ttc += isset($this->revenuestamp) ? ($this->revenuestamp * $multicurrency_tx) : 0;
3733 
3734  // Situations totals
3735  if (!empty($this->situation_cycle_ref) && $this->situation_counter > 1 && method_exists($this, 'get_prev_sits') && $this->type != $this::TYPE_CREDIT_NOTE) {
3736  $prev_sits = $this->get_prev_sits();
3737 
3738  foreach ($prev_sits as $sit) { // $sit is an object Facture loaded with a fetch.
3739  $this->total_ht -= $sit->total_ht;
3740  $this->total_tva -= $sit->total_tva;
3741  $this->total_localtax1 -= $sit->total_localtax1;
3742  $this->total_localtax2 -= $sit->total_localtax2;
3743  $this->total_ttc -= $sit->total_ttc;
3744  $this->multicurrency_total_ht -= $sit->multicurrency_total_ht;
3745  $this->multicurrency_total_tva -= $sit->multicurrency_total_tva;
3746  $this->multicurrency_total_ttc -= $sit->multicurrency_total_ttc;
3747  }
3748  }
3749 
3750  // Clean total
3751  $this->total_ht = (float) price2num($this->total_ht);
3752  $this->total_tva = (float) price2num($this->total_tva);
3753  $this->total_localtax1 = (float) price2num($this->total_localtax1);
3754  $this->total_localtax2 = (float) price2num($this->total_localtax2);
3755  $this->total_ttc = (float) price2num($this->total_ttc);
3756 
3757  $this->db->free($resql);
3758 
3759  // Now update global fields total_ht, total_ttc, total_tva, total_localtax1, total_localtax2, multicurrency_total_* of main object
3760  $fieldht = 'total_ht';
3761  $fieldtva = 'tva';
3762  $fieldlocaltax1 = 'localtax1';
3763  $fieldlocaltax2 = 'localtax2';
3764  $fieldttc = 'total_ttc';
3765  // Specific code for backward compatibility with old field names
3766  if (in_array($this->element, array('propal', 'commande', 'facture', 'facturerec', 'supplier_proposal', 'order_supplier', 'facture_fourn', 'invoice_supplier', 'invoice_supplier_rec', 'expensereport'))) {
3767  $fieldtva = 'total_tva';
3768  }
3769 
3770  if (empty($nodatabaseupdate)) {
3771  $sql = "UPDATE ".$this->db->prefix().$this->table_element.' SET';
3772  $sql .= " ".$fieldht." = ".((float) price2num($this->total_ht, 'MT', 1)).",";
3773  $sql .= " ".$fieldtva." = ".((float) price2num($this->total_tva, 'MT', 1)).",";
3774  $sql .= " ".$fieldlocaltax1." = ".((float) price2num($this->total_localtax1, 'MT', 1)).",";
3775  $sql .= " ".$fieldlocaltax2." = ".((float) price2num($this->total_localtax2, 'MT', 1)).",";
3776  $sql .= " ".$fieldttc." = ".((float) price2num($this->total_ttc, 'MT', 1));
3777  $sql .= ", multicurrency_total_ht = ".((float) price2num($this->multicurrency_total_ht, 'MT', 1));
3778  $sql .= ", multicurrency_total_tva = ".((float) price2num($this->multicurrency_total_tva, 'MT', 1));
3779  $sql .= ", multicurrency_total_ttc = ".((float) price2num($this->multicurrency_total_ttc, 'MT', 1));
3780  $sql .= " WHERE rowid = ".((int) $this->id);
3781 
3782  dol_syslog(get_class($this)."::update_price", LOG_DEBUG);
3783  $resql = $this->db->query($sql);
3784 
3785  if (!$resql) {
3786  $error++;
3787  $this->error = $this->db->lasterror();
3788  $this->errors[] = $this->db->lasterror();
3789  }
3790  }
3791 
3792  if (!$error) {
3793  return 1;
3794  } else {
3795  return -1;
3796  }
3797  } else {
3798  dol_print_error($this->db, 'Bad request in update_price');
3799  return -1;
3800  }
3801  }
3802 
3803  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3814  public function add_object_linked($origin = null, $origin_id = null, $f_user = null, $notrigger = 0)
3815  {
3816  // phpcs:enable
3817  global $user, $hookmanager, $action;
3818  $origin = (!empty($origin) ? $origin : $this->origin);
3819  $origin_id = (!empty($origin_id) ? $origin_id : $this->origin_id);
3820  $f_user = isset($f_user) ? $f_user : $user;
3821 
3822  // Special case
3823  if ($origin == 'order') {
3824  $origin = 'commande';
3825  }
3826  if ($origin == 'invoice') {
3827  $origin = 'facture';
3828  }
3829  if ($origin == 'invoice_template') {
3830  $origin = 'facturerec';
3831  }
3832  if ($origin == 'supplierorder') {
3833  $origin = 'order_supplier';
3834  }
3835 
3836  // 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.
3837  // 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.
3838  $coremodule = array('knowledgemanagement', 'partnership', 'workstation', 'ticket', 'recruitment', 'eventorganization', 'asset');
3839  // Add module part to target type if object has $module property and isn't in core modules.
3840  $targettype = ((!empty($this->module) && ! in_array($this->module, $coremodule)) ? $this->module.'_' : '').$this->element;
3841 
3842  $parameters = array('targettype'=>$targettype);
3843  // Hook for explicitly set the targettype if it must be differtent than $this->element
3844  $reshook = $hookmanager->executeHooks('setLinkedObjectSourceTargetType', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
3845  if ($reshook > 0) {
3846  if (!empty($hookmanager->resArray['targettype'])) $targettype = $hookmanager->resArray['targettype'];
3847  }
3848 
3849  $this->db->begin();
3850  $error = 0;
3851 
3852  $sql = "INSERT INTO " . $this->db->prefix() . "element_element (";
3853  $sql .= "fk_source";
3854  $sql .= ", sourcetype";
3855  $sql .= ", fk_target";
3856  $sql .= ", targettype";
3857  $sql .= ") VALUES (";
3858  $sql .= ((int) $origin_id);
3859  $sql .= ", '" . $this->db->escape($origin) . "'";
3860  $sql .= ", " . ((int) $this->id);
3861  $sql .= ", '" . $this->db->escape($targettype) . "'";
3862  $sql .= ")";
3863 
3864  dol_syslog(get_class($this) . "::add_object_linked", LOG_DEBUG);
3865  if ($this->db->query($sql)) {
3866  if (!$notrigger) {
3867  // Call trigger
3868  $this->context['link_origin'] = $origin;
3869  $this->context['link_origin_id'] = $origin_id;
3870  $result = $this->call_trigger('OBJECT_LINK_INSERT', $f_user);
3871  if ($result < 0) {
3872  $error++;
3873  }
3874  // End call triggers
3875  }
3876  } else {
3877  $this->error = $this->db->lasterror();
3878  $error++;
3879  }
3880 
3881  if (!$error) {
3882  $this->db->commit();
3883  return 1;
3884  } else {
3885  $this->db->rollback();
3886  return 0;
3887  }
3888  }
3889 
3912  public function fetchObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $clause = 'OR', $alsosametype = 1, $orderby = 'sourcetype', $loadalsoobjects = 1)
3913  {
3914  global $conf, $hookmanager, $action;
3915 
3916  // Important for pdf generation time reduction
3917  // This boolean is true if $this->linkedObjects has already been loaded with all objects linked without filter
3918  if ($this->id > 0 && !empty($this->linkedObjectsFullLoaded[$this->id])) {
3919  return 1;
3920  }
3921 
3922  $this->linkedObjectsIds = array();
3923  $this->linkedObjects = array();
3924 
3925  $justsource = false;
3926  $justtarget = false;
3927  $withtargettype = false;
3928  $withsourcetype = false;
3929 
3930  $parameters = array('sourcetype'=>$sourcetype, 'sourceid'=>$sourceid, 'targettype'=>$targettype, 'targetid'=>$targetid);
3931  // Hook for explicitly set the targettype if it must be differtent than $this->element
3932  $reshook = $hookmanager->executeHooks('setLinkedObjectSourceTargetType', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
3933  if ($reshook > 0) {
3934  if (!empty($hookmanager->resArray['sourcetype'])) $sourcetype = $hookmanager->resArray['sourcetype'];
3935  if (!empty($hookmanager->resArray['sourceid'])) $sourceid = $hookmanager->resArray['sourceid'];
3936  if (!empty($hookmanager->resArray['targettype'])) $targettype = $hookmanager->resArray['targettype'];
3937  if (!empty($hookmanager->resArray['targetid'])) $targetid = $hookmanager->resArray['targetid'];
3938  }
3939 
3940  if (!empty($sourceid) && !empty($sourcetype) && empty($targetid)) {
3941  $justsource = true; // the source (id and type) is a search criteria
3942  if (!empty($targettype)) {
3943  $withtargettype = true;
3944  }
3945  }
3946  if (!empty($targetid) && !empty($targettype) && empty($sourceid)) {
3947  $justtarget = true; // the target (id and type) is a search criteria
3948  if (!empty($sourcetype)) {
3949  $withsourcetype = true;
3950  }
3951  }
3952 
3953  $sourceid = (!empty($sourceid) ? $sourceid : $this->id);
3954  $targetid = (!empty($targetid) ? $targetid : $this->id);
3955  $sourcetype = (!empty($sourcetype) ? $sourcetype : $this->element);
3956  $targettype = (!empty($targettype) ? $targettype : $this->element);
3957 
3958  /*if (empty($sourceid) && empty($targetid))
3959  {
3960  dol_syslog('Bad usage of function. No source nor target id defined (nor as parameter nor as object id)', LOG_ERR);
3961  return -1;
3962  }*/
3963 
3964  // Links between objects are stored in table element_element
3965  $sql = "SELECT rowid, fk_source, sourcetype, fk_target, targettype";
3966  $sql .= " FROM ".$this->db->prefix()."element_element";
3967  $sql .= " WHERE ";
3968  if ($justsource || $justtarget) {
3969  if ($justsource) {
3970  $sql .= "fk_source = ".((int) $sourceid)." AND sourcetype = '".$this->db->escape($sourcetype)."'";
3971  if ($withtargettype) {
3972  $sql .= " AND targettype = '".$this->db->escape($targettype)."'";
3973  }
3974  } elseif ($justtarget) {
3975  $sql .= "fk_target = ".((int) $targetid)." AND targettype = '".$this->db->escape($targettype)."'";
3976  if ($withsourcetype) {
3977  $sql .= " AND sourcetype = '".$this->db->escape($sourcetype)."'";
3978  }
3979  }
3980  } else {
3981  $sql .= "(fk_source = ".((int) $sourceid)." AND sourcetype = '".$this->db->escape($sourcetype)."')";
3982  $sql .= " ".$clause." (fk_target = ".((int) $targetid)." AND targettype = '".$this->db->escape($targettype)."')";
3983  if ($loadalsoobjects && $this->id > 0 && $sourceid == $this->id && $sourcetype == $this->element && $targetid == $this->id && $targettype == $this->element && $clause == 'OR') {
3984  $this->linkedObjectsFullLoaded[$this->id] = true;
3985  }
3986  }
3987  $sql .= " ORDER BY ".$orderby;
3988 
3989  dol_syslog(get_class($this)."::fetchObjectLink", LOG_DEBUG);
3990  $resql = $this->db->query($sql);
3991  if ($resql) {
3992  $num = $this->db->num_rows($resql);
3993  $i = 0;
3994  while ($i < $num) {
3995  $obj = $this->db->fetch_object($resql);
3996  if ($justsource || $justtarget) {
3997  if ($justsource) {
3998  $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
3999  } elseif ($justtarget) {
4000  $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
4001  }
4002  } else {
4003  if ($obj->fk_source == $sourceid && $obj->sourcetype == $sourcetype) {
4004  $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
4005  }
4006  if ($obj->fk_target == $targetid && $obj->targettype == $targettype) {
4007  $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
4008  }
4009  }
4010  $i++;
4011  }
4012 
4013  if (!empty($this->linkedObjectsIds)) {
4014  $tmparray = $this->linkedObjectsIds;
4015  foreach ($tmparray as $objecttype => $objectids) { // $objecttype is a module name ('facture', 'mymodule', ...) or a module name with a suffix ('project_task', 'mymodule_myobj', ...)
4016  // Parse element/subelement (ex: project_task, cabinetmed_consultation, ...)
4017  $module = $element = $subelement = $objecttype;
4018  $regs = array();
4019  if ($objecttype != 'supplier_proposal' && $objecttype != 'order_supplier' && $objecttype != 'invoice_supplier'
4020  && preg_match('/^([^_]+)_([^_]+)/i', $objecttype, $regs)) {
4021  $module = $element = $regs[1];
4022  $subelement = $regs[2];
4023  }
4024 
4025  $classpath = $element.'/class';
4026  // To work with non standard classpath or module name
4027  if ($objecttype == 'facture') {
4028  $classpath = 'compta/facture/class';
4029  } elseif ($objecttype == 'facturerec') {
4030  $classpath = 'compta/facture/class';
4031  $module = 'facture';
4032  } elseif ($objecttype == 'propal') {
4033  $classpath = 'comm/propal/class';
4034  } elseif ($objecttype == 'supplier_proposal') {
4035  $classpath = 'supplier_proposal/class';
4036  } elseif ($objecttype == 'shipping') {
4037  $classpath = 'expedition/class';
4038  $subelement = 'expedition';
4039  $module = 'expedition_bon';
4040  } elseif ($objecttype == 'delivery') {
4041  $classpath = 'delivery/class';
4042  $subelement = 'delivery';
4043  $module = 'delivery_note';
4044  } elseif ($objecttype == 'invoice_supplier' || $objecttype == 'order_supplier') {
4045  $classpath = 'fourn/class';
4046  $module = 'fournisseur';
4047  } elseif ($objecttype == 'fichinter') {
4048  $classpath = 'fichinter/class';
4049  $subelement = 'fichinter';
4050  $module = 'ficheinter';
4051  } elseif ($objecttype == 'subscription') {
4052  $classpath = 'adherents/class';
4053  $module = 'adherent';
4054  } elseif ($objecttype == 'contact') {
4055  $module = 'societe';
4056  }
4057  // Set classfile
4058  $classfile = strtolower($subelement);
4059  $classname = ucfirst($subelement);
4060 
4061  if ($objecttype == 'order') {
4062  $classfile = 'commande';
4063  $classname = 'Commande';
4064  } elseif ($objecttype == 'invoice_supplier') {
4065  $classfile = 'fournisseur.facture';
4066  $classname = 'FactureFournisseur';
4067  } elseif ($objecttype == 'order_supplier') {
4068  $classfile = 'fournisseur.commande';
4069  $classname = 'CommandeFournisseur';
4070  } elseif ($objecttype == 'supplier_proposal') {
4071  $classfile = 'supplier_proposal';
4072  $classname = 'SupplierProposal';
4073  } elseif ($objecttype == 'facturerec') {
4074  $classfile = 'facture-rec';
4075  $classname = 'FactureRec';
4076  } elseif ($objecttype == 'subscription') {
4077  $classfile = 'subscription';
4078  $classname = 'Subscription';
4079  } elseif ($objecttype == 'project' || $objecttype == 'projet') {
4080  $classpath = 'projet/class';
4081  $classfile = 'project';
4082  $classname = 'Project';
4083  } elseif ($objecttype == 'conferenceorboothattendee') {
4084  $classpath = 'eventorganization/class';
4085  $classfile = 'conferenceorboothattendee';
4086  $classname = 'ConferenceOrBoothAttendee';
4087  $module = 'eventorganization';
4088  } elseif ($objecttype == 'conferenceorbooth') {
4089  $classpath = 'eventorganization/class';
4090  $classfile = 'conferenceorbooth';
4091  $classname = 'ConferenceOrBooth';
4092  $module = 'eventorganization';
4093  } elseif ($objecttype == 'mo') {
4094  $classpath = 'mrp/class';
4095  $classfile = 'mo';
4096  $classname = 'Mo';
4097  $module = 'mrp';
4098  }
4099 
4100  // Here $module, $classfile and $classname are set, we can use them.
4101  if (isModEnabled($module) && (($element != $this->element) || $alsosametype)) {
4102  if ($loadalsoobjects && (is_numeric($loadalsoobjects) || ($loadalsoobjects === $objecttype))) {
4103  dol_include_once('/'.$classpath.'/'.$classfile.'.class.php');
4104  //print '/'.$classpath.'/'.$classfile.'.class.php '.class_exists($classname);
4105  if (class_exists($classname)) {
4106  foreach ($objectids as $i => $objectid) { // $i is rowid into llx_element_element
4107  $object = new $classname($this->db);
4108  $ret = $object->fetch($objectid);
4109  if ($ret >= 0) {
4110  $this->linkedObjects[$objecttype][$i] = $object;
4111  }
4112  }
4113  }
4114  }
4115  } else {
4116  unset($this->linkedObjectsIds[$objecttype]);
4117  }
4118  }
4119  }
4120  return 1;
4121  } else {
4122  dol_print_error($this->db);
4123  return -1;
4124  }
4125  }
4126 
4133  public function clearObjectLinkedCache()
4134  {
4135  if ($this->id > 0 && !empty($this->linkedObjectsFullLoaded[$this->id])) {
4136  unset($this->linkedObjectsFullLoaded[$this->id]);
4137  }
4138 
4139  return 1;
4140  }
4141 
4154  public function updateObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $f_user = null, $notrigger = 0)
4155  {
4156  global $user;
4157  $updatesource = false;
4158  $updatetarget = false;
4159  $f_user = isset($f_user) ? $f_user : $user;
4160 
4161  if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) {
4162  $updatesource = true;
4163  } elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) {
4164  $updatetarget = true;
4165  }
4166 
4167  $this->db->begin();
4168  $error = 0;
4169 
4170  $sql = "UPDATE " . $this->db->prefix() . "element_element SET ";
4171  if ($updatesource) {
4172  $sql .= "fk_source = " . ((int) $sourceid);
4173  $sql .= ", sourcetype = '" . $this->db->escape($sourcetype) . "'";
4174  $sql .= " WHERE fk_target = " . ((int) $this->id);
4175  $sql .= " AND targettype = '" . $this->db->escape($this->element) . "'";
4176  } elseif ($updatetarget) {
4177  $sql .= "fk_target = " . ((int) $targetid);
4178  $sql .= ", targettype = '" . $this->db->escape($targettype) . "'";
4179  $sql .= " WHERE fk_source = " . ((int) $this->id);
4180  $sql .= " AND sourcetype = '" . $this->db->escape($this->element) . "'";
4181  }
4182 
4183  dol_syslog(get_class($this) . "::updateObjectLinked", LOG_DEBUG);
4184  if ($this->db->query($sql)) {
4185  if (!$notrigger) {
4186  // Call trigger
4187  $this->context['link_source_id'] = $sourceid;
4188  $this->context['link_source_type'] = $sourcetype;
4189  $this->context['link_target_id'] = $targetid;
4190  $this->context['link_target_type'] = $targettype;
4191  $result = $this->call_trigger('OBJECT_LINK_MODIFY', $f_user);
4192  if ($result < 0) {
4193  $error++;
4194  }
4195  // End call triggers
4196  }
4197  } else {
4198  $this->error = $this->db->lasterror();
4199  $error++;
4200  }
4201 
4202  if (!$error) {
4203  $this->db->commit();
4204  return 1;
4205  } else {
4206  $this->db->rollback();
4207  return -1;
4208  }
4209  }
4210 
4224  public function deleteObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $rowid = '', $f_user = null, $notrigger = 0)
4225  {
4226  global $user;
4227  $deletesource = false;
4228  $deletetarget = false;
4229  $f_user = isset($f_user) ? $f_user : $user;
4230 
4231  if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) {
4232  $deletesource = true;
4233  } elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) {
4234  $deletetarget = true;
4235  }
4236 
4237  $sourceid = (!empty($sourceid) ? $sourceid : $this->id);
4238  $sourcetype = (!empty($sourcetype) ? $sourcetype : $this->element);
4239  $targetid = (!empty($targetid) ? $targetid : $this->id);
4240  $targettype = (!empty($targettype) ? $targettype : $this->element);
4241  $this->db->begin();
4242  $error = 0;
4243 
4244  if (!$notrigger) {
4245  // Call trigger
4246  $this->context['link_id'] = $rowid;
4247  $this->context['link_source_id'] = $sourceid;
4248  $this->context['link_source_type'] = $sourcetype;
4249  $this->context['link_target_id'] = $targetid;
4250  $this->context['link_target_type'] = $targettype;
4251  $result = $this->call_trigger('OBJECT_LINK_DELETE', $f_user);
4252  if ($result < 0) {
4253  $error++;
4254  }
4255  // End call triggers
4256  }
4257 
4258  if (!$error) {
4259  $sql = "DELETE FROM " . $this->db->prefix() . "element_element";
4260  $sql .= " WHERE";
4261  if ($rowid > 0) {
4262  $sql .= " rowid = " . ((int) $rowid);
4263  } else {
4264  if ($deletesource) {
4265  $sql .= " fk_source = " . ((int) $sourceid) . " AND sourcetype = '" . $this->db->escape($sourcetype) . "'";
4266  $sql .= " AND fk_target = " . ((int) $this->id) . " AND targettype = '" . $this->db->escape($this->element) . "'";
4267  } elseif ($deletetarget) {
4268  $sql .= " fk_target = " . ((int) $targetid) . " AND targettype = '" . $this->db->escape($targettype) . "'";
4269  $sql .= " AND fk_source = " . ((int) $this->id) . " AND sourcetype = '" . $this->db->escape($this->element) . "'";
4270  } else {
4271  $sql .= " (fk_source = " . ((int) $this->id) . " AND sourcetype = '" . $this->db->escape($this->element) . "')";
4272  $sql .= " OR";
4273  $sql .= " (fk_target = " . ((int) $this->id) . " AND targettype = '" . $this->db->escape($this->element) . "')";
4274  }
4275  }
4276 
4277  dol_syslog(get_class($this) . "::deleteObjectLinked", LOG_DEBUG);
4278  if (!$this->db->query($sql)) {
4279  $this->error = $this->db->lasterror();
4280  $this->errors[] = $this->error;
4281  $error++;
4282  }
4283  }
4284 
4285  if (!$error) {
4286  $this->db->commit();
4287  return 1;
4288  } else {
4289  $this->db->rollback();
4290  return 0;
4291  }
4292  }
4293 
4303  public static function getAllItemsLinkedByObjectID($fk_object_where, $field_select, $field_where, $table_element)
4304  {
4305  if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
4306  return -1;
4307  }
4308 
4309  global $db;
4310 
4311  $sql = "SELECT ".$field_select." FROM ".$db->prefix().$table_element." WHERE ".$field_where." = ".((int) $fk_object_where);
4312  $resql = $db->query($sql);
4313 
4314  $TRes = array();
4315  if (!empty($resql)) {
4316  while ($res = $db->fetch_object($resql)) {
4317  $TRes[] = $res->{$field_select};
4318  }
4319  }
4320 
4321  return $TRes;
4322  }
4323 
4332  public static function deleteAllItemsLinkedByObjectID($fk_object_where, $field_where, $table_element)
4333  {
4334  if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
4335  return -1;
4336  }
4337 
4338  global $db;
4339 
4340  $sql = "DELETE FROM ".$db->prefix().$table_element." WHERE ".$field_where." = ".((int) $fk_object_where);
4341  $resql = $db->query($sql);
4342 
4343  if (empty($resql)) {
4344  return 0;
4345  }
4346 
4347  return 1;
4348  }
4349 
4360  public function setStatut($status, $elementId = null, $elementType = '', $trigkey = '', $fieldstatus = 'fk_statut')
4361  {
4362  global $user, $langs, $conf;
4363 
4364  $savElementId = $elementId; // To be used later to know if we were using the method using the id of this or not.
4365 
4366  $elementId = (!empty($elementId) ? $elementId : $this->id);
4367  $elementTable = (!empty($elementType) ? $elementType : $this->table_element);
4368 
4369  $this->db->begin();
4370 
4371  if ($elementTable == 'facture_rec') {
4372  $fieldstatus = "suspended";
4373  }
4374  if ($elementTable == 'mailing') {
4375  $fieldstatus = "statut";
4376  }
4377  if ($elementTable == 'cronjob') {
4378  $fieldstatus = "status";
4379  }
4380  if ($elementTable == 'user') {
4381  $fieldstatus = "statut";
4382  }
4383  if ($elementTable == 'expensereport') {
4384  $fieldstatus = "fk_statut";
4385  }
4386  if ($elementTable == 'commande_fournisseur_dispatch') {
4387  $fieldstatus = "status";
4388  }
4389  if (isset($this->fields) && is_array($this->fields) && array_key_exists('status', $this->fields)) {
4390  $fieldstatus = 'status';
4391  }
4392 
4393  $sql = "UPDATE ".$this->db->prefix().$elementTable;
4394  $sql .= " SET ".$fieldstatus." = ".((int) $status);
4395  // If status = 1 = validated, update also fk_user_valid
4396  // TODO Replace the test on $elementTable by doing a test on existence of the field in $this->fields
4397  if ($status == 1 && in_array($elementTable, array('expensereport', 'inventory'))) {
4398  $sql .= ", fk_user_valid = ".((int) $user->id);
4399  }
4400  if ($status == 1 && in_array($elementTable, array('expensereport'))) {
4401  $sql .= ", date_valid = '".$this->db->idate(dol_now())."'";
4402  }
4403  if ($status == 1 && in_array($elementTable, array('inventory'))) {
4404  $sql .= ", date_validation = '".$this->db->idate(dol_now())."'";
4405  }
4406  $sql .= " WHERE rowid = ".((int) $elementId);
4407  $sql .= " AND ".$fieldstatus." <> ".((int) $status); // We avoid update if status already correct
4408 
4409  dol_syslog(get_class($this)."::setStatut", LOG_DEBUG);
4410  $resql = $this->db->query($sql);
4411  if ($resql) {
4412  $error = 0;
4413 
4414  $nb_rows_affected = $this->db->affected_rows($resql); // should be 1 or 0 if status was already correct
4415 
4416  if ($nb_rows_affected > 0) {
4417  if (empty($trigkey)) {
4418  // Try to guess trigkey (for backward compatibility, now we should have trigkey defined into the call of setStatus)
4419  if ($this->element == 'supplier_proposal' && $status == 2) {
4420  $trigkey = 'SUPPLIER_PROPOSAL_SIGN'; // 2 = SupplierProposal::STATUS_SIGNED. Can't use constant into this generic class
4421  }
4422  if ($this->element == 'supplier_proposal' && $status == 3) {
4423  $trigkey = 'SUPPLIER_PROPOSAL_REFUSE'; // 3 = SupplierProposal::STATUS_REFUSED. Can't use constant into this generic class
4424  }
4425  if ($this->element == 'supplier_proposal' && $status == 4) {
4426  $trigkey = 'SUPPLIER_PROPOSAL_CLOSE'; // 4 = SupplierProposal::STATUS_CLOSED. Can't use constant into this generic class
4427  }
4428  if ($this->element == 'fichinter' && $status == 3) {
4429  $trigkey = 'FICHINTER_CLASSIFY_DONE';
4430  }
4431  if ($this->element == 'fichinter' && $status == 2) {
4432  $trigkey = 'FICHINTER_CLASSIFY_BILLED';
4433  }
4434  if ($this->element == 'fichinter' && $status == 1) {
4435  $trigkey = 'FICHINTER_CLASSIFY_UNBILLED';
4436  }
4437  }
4438 
4439  if ($trigkey) {
4440  // Call trigger
4441  $result = $this->call_trigger($trigkey, $user);
4442  if ($result < 0) {
4443  $error++;
4444  }
4445  // End call triggers
4446  }
4447  } else {
4448  // The status was probably already good. We do nothing more, no triggers.
4449  }
4450 
4451  if (!$error) {
4452  $this->db->commit();
4453 
4454  if (empty($savElementId)) {
4455  // If the element we update is $this (so $elementId was provided as null)
4456  if ($fieldstatus == 'tosell') {
4457  $this->status = $status;
4458  } elseif ($fieldstatus == 'tobuy') {
4459  $this->status_buy = $status;
4460  } else {
4461  $this->statut = $status;
4462  $this->status = $status;
4463  }
4464  }
4465 
4466  return 1;
4467  } else {
4468  $this->db->rollback();
4469  dol_syslog(get_class($this)."::setStatut ".$this->error, LOG_ERR);
4470  return -1;
4471  }
4472  } else {
4473  $this->error = $this->db->lasterror();
4474  $this->db->rollback();
4475  return -1;
4476  }
4477  }
4478 
4479 
4487  public function getCanvas($id = 0, $ref = '')
4488  {
4489  global $conf;
4490 
4491  if (empty($id) && empty($ref)) {
4492  return 0;
4493  }
4494  if (!empty($conf->global->MAIN_DISABLE_CANVAS)) {
4495  return 0; // To increase speed. Not enabled by default.
4496  }
4497 
4498  // Clean parameters
4499  $ref = trim($ref);
4500 
4501  $sql = "SELECT rowid, canvas";
4502  $sql .= " FROM ".$this->db->prefix().$this->table_element;
4503  $sql .= " WHERE entity IN (".getEntity($this->element).")";
4504  if (!empty($id)) {
4505  $sql .= " AND rowid = ".((int) $id);
4506  }
4507  if (!empty($ref)) {
4508  $sql .= " AND ref = '".$this->db->escape($ref)."'";
4509  }
4510 
4511  $resql = $this->db->query($sql);
4512  if ($resql) {
4513  $obj = $this->db->fetch_object($resql);
4514  if ($obj) {
4515  $this->canvas = $obj->canvas;
4516  return 1;
4517  } else {
4518  return 0;
4519  }
4520  } else {
4521  dol_print_error($this->db);
4522  return -1;
4523  }
4524  }
4525 
4526 
4533  public function getSpecialCode($lineid)
4534  {
4535  $sql = "SELECT special_code FROM ".$this->db->prefix().$this->table_element_line;
4536  $sql .= " WHERE rowid = ".((int) $lineid);
4537  $resql = $this->db->query($sql);
4538  if ($resql) {
4539  $row = $this->db->fetch_row($resql);
4540  return $row[0];
4541  }
4542  }
4543 
4552  public function isObjectUsed($id = 0, $entity = 0)
4553  {
4554  global $langs;
4555 
4556  if (empty($id)) {
4557  $id = $this->id;
4558  }
4559 
4560  // Check parameters
4561  if (!isset($this->childtables) || !is_array($this->childtables) || count($this->childtables) == 0) {
4562  dol_print_error('Called isObjectUsed on a class with property this->childtables not defined');
4563  return -1;
4564  }
4565 
4566  $arraytoscan = $this->childtables;
4567  // For backward compatibility, we check if array is old format array('table1', 'table2', ...)
4568  $tmparray = array_keys($this->childtables);
4569  if (is_numeric($tmparray[0])) {
4570  $arraytoscan = array_flip($this->childtables);
4571  }
4572 
4573  // Test if child exists
4574  $haschild = 0;
4575  foreach ($arraytoscan as $table => $element) {
4576  //print $id.'-'.$table.'-'.$elementname.'<br>';
4577  // Check if element can be deleted
4578  $sql = "SELECT COUNT(*) as nb";
4579  $sql.= " FROM ".$this->db->prefix().$table." as c";
4580  if (!empty($element['parent']) && !empty($element['parentkey'])) {
4581  $sql.= ", ".$this->db->prefix().$element['parent']." as p";
4582  }
4583  $sql.= " WHERE c.".$this->fk_element." = ".((int) $id);
4584  if (!empty($element['parent']) && !empty($element['parentkey'])) {
4585  $sql.= " AND c.".$element['parentkey']." = p.rowid";
4586  }
4587  if (!empty($entity)) {
4588  if (!empty($element['parent']) && !empty($element['parentkey'])) {
4589  $sql.= " AND p.entity = ".((int) $entity);
4590  } else {
4591  $sql.= " AND c.entity = ".((int) $entity);
4592  }
4593  }
4594  $resql = $this->db->query($sql);
4595  if ($resql) {
4596  $obj = $this->db->fetch_object($resql);
4597  if ($obj->nb > 0) {
4598  $langs->load("errors");
4599  //print 'Found into table '.$table.', type '.$langs->transnoentitiesnoconv($elementname).', haschild='.$haschild;
4600  $haschild += $obj->nb;
4601  if (is_numeric($element)) { // very old usage array('table1', 'table2', ...)
4602  $this->errors[] = $langs->transnoentitiesnoconv("ErrorRecordHasAtLeastOneChildOfType", method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref, $table);
4603  } elseif (is_string($element)) { // old usage array('table1' => 'TranslateKey1', 'table2' => 'TranslateKey2', ...)
4604  $this->errors[] = $langs->transnoentitiesnoconv("ErrorRecordHasAtLeastOneChildOfType", method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref, $langs->transnoentitiesnoconv($element));
4605  } else { // new usage: $element['name']=Translation key
4606  $this->errors[] = $langs->transnoentitiesnoconv("ErrorRecordHasAtLeastOneChildOfType", method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref, $langs->transnoentitiesnoconv($element['name']));
4607  }
4608  break; // We found at least one, we stop here
4609  }
4610  } else {
4611  $this->errors[] = $this->db->lasterror();
4612  return -1;
4613  }
4614  }
4615  if ($haschild > 0) {
4616  $this->errors[] = "ErrorRecordHasChildren";
4617  return $haschild;
4618  } else {
4619  return 0;
4620  }
4621  }
4622 
4629  public function hasProductsOrServices($predefined = -1)
4630  {
4631  $nb = 0;
4632 
4633  foreach ($this->lines as $key => $val) {
4634  $qualified = 0;
4635  if ($predefined == -1) {
4636  $qualified = 1;
4637  }
4638  if ($predefined == 1 && $val->fk_product > 0) {
4639  $qualified = 1;
4640  }
4641  if ($predefined == 0 && $val->fk_product <= 0) {
4642  $qualified = 1;
4643  }
4644  if ($predefined == 2 && $val->fk_product > 0 && $val->product_type == 0) {
4645  $qualified = 1;
4646  }
4647  if ($predefined == 3 && $val->fk_product > 0 && $val->product_type == 1) {
4648  $qualified = 1;
4649  }
4650  if ($qualified) {
4651  $nb++;
4652  }
4653  }
4654  dol_syslog(get_class($this).'::hasProductsOrServices we found '.$nb.' qualified lines of products/servcies');
4655  return $nb;
4656  }
4657 
4663  public function getTotalDiscount()
4664  {
4665  if (!empty($this->table_element_line) ) {
4666  $total_discount = 0.00;
4667 
4668  $sql = "SELECT subprice as pu_ht, qty, remise_percent, total_ht";
4669  $sql .= " FROM ".$this->db->prefix().$this->table_element_line;
4670  $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
4671 
4672  dol_syslog(get_class($this).'::getTotalDiscount', LOG_DEBUG);
4673  $resql = $this->db->query($sql);
4674  if ($resql) {
4675  $num = $this->db->num_rows($resql);
4676  $i = 0;
4677  while ($i < $num) {
4678  $obj = $this->db->fetch_object($resql);
4679 
4680  $pu_ht = $obj->pu_ht;
4681  $qty = $obj->qty;
4682  $total_ht = $obj->total_ht;
4683 
4684  $total_discount_line = floatval(price2num(($pu_ht * $qty) - $total_ht, 'MT'));
4685  $total_discount += $total_discount_line;
4686 
4687  $i++;
4688  }
4689  }
4690 
4691  //print $total_discount; exit;
4692  return price2num($total_discount);
4693  }
4694 
4695  return null;
4696  }
4697 
4698 
4705  public function getTotalWeightVolume()
4706  {
4707  $totalWeight = 0;
4708  $totalVolume = 0;
4709  // defined for shipment only
4710  $totalOrdered = '';
4711  // defined for shipment only
4712  $totalToShip = '';
4713 
4714  foreach ($this->lines as $line) {
4715  if (isset($line->qty_asked)) {
4716  if (empty($totalOrdered)) {
4717  $totalOrdered = 0; // Avoid warning because $totalOrdered is ''
4718  }
4719  $totalOrdered += $line->qty_asked; // defined for shipment only
4720  }
4721  if (isset($line->qty_shipped)) {
4722  if (empty($totalToShip)) {
4723  $totalToShip = 0; // Avoid warning because $totalToShip is ''
4724  }
4725  $totalToShip += $line->qty_shipped; // defined for shipment only
4726  } elseif ($line->element == 'commandefournisseurdispatch' && isset($line->qty)) {
4727  if (empty($totalToShip)) {
4728  $totalToShip = 0;
4729  }
4730  $totalToShip += $line->qty; // defined for reception only
4731  }
4732 
4733  // Define qty, weight, volume, weight_units, volume_units
4734  if ($this->element == 'shipping') {
4735  // for shipments
4736  $qty = $line->qty_shipped ? $line->qty_shipped : 0;
4737  } else {
4738  $qty = $line->qty ? $line->qty : 0;
4739  }
4740 
4741  $weight = !empty($line->weight) ? $line->weight : 0;
4742  ($weight == 0 && !empty($line->product->weight)) ? $weight = $line->product->weight : 0;
4743  $volume = !empty($line->volume) ? $line->volume : 0;
4744  ($volume == 0 && !empty($line->product->volume)) ? $volume = $line->product->volume : 0;
4745 
4746  $weight_units = !empty($line->weight_units) ? $line->weight_units : 0;
4747  ($weight_units == 0 && !empty($line->product->weight_units)) ? $weight_units = $line->product->weight_units : 0;
4748  $volume_units = !empty($line->volume_units) ? $line->volume_units : 0;
4749  ($volume_units == 0 && !empty($line->product->volume_units)) ? $volume_units = $line->product->volume_units : 0;
4750 
4751  $weightUnit = 0;
4752  $volumeUnit = 0;
4753  if (!empty($weight_units)) {
4754  $weightUnit = $weight_units;
4755  }
4756  if (!empty($volume_units)) {
4757  $volumeUnit = $volume_units;
4758  }
4759 
4760  if (empty($totalWeight)) {
4761  $totalWeight = 0; // Avoid warning because $totalWeight is ''
4762  }
4763  if (empty($totalVolume)) {
4764  $totalVolume = 0; // Avoid warning because $totalVolume is ''
4765  }
4766 
4767  //var_dump($line->volume_units);
4768  if ($weight_units < 50) { // < 50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch)
4769  $trueWeightUnit = pow(10, $weightUnit);
4770  $totalWeight += $weight * $qty * $trueWeightUnit;
4771  } else {
4772  if ($weight_units == 99) {
4773  // conversion 1 Pound = 0.45359237 KG
4774  $trueWeightUnit = 0.45359237;
4775  $totalWeight += $weight * $qty * $trueWeightUnit;
4776  } elseif ($weight_units == 98) {
4777  // conversion 1 Ounce = 0.0283495 KG
4778  $trueWeightUnit = 0.0283495;
4779  $totalWeight += $weight * $qty * $trueWeightUnit;
4780  } else {
4781  $totalWeight += $weight * $qty; // This may be wrong if we mix different units
4782  }
4783  }
4784  if ($volume_units < 50) { // >50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch)
4785  //print $line->volume."x".$line->volume_units."x".($line->volume_units < 50)."x".$volumeUnit;
4786  $trueVolumeUnit = pow(10, $volumeUnit);
4787  //print $line->volume;
4788  $totalVolume += $volume * $qty * $trueVolumeUnit;
4789  } else {
4790  $totalVolume += $volume * $qty; // This may be wrong if we mix different units
4791  }
4792  }
4793 
4794  return array('weight'=>$totalWeight, 'volume'=>$totalVolume, 'ordered'=>$totalOrdered, 'toship'=>$totalToShip);
4795  }
4796 
4797 
4803  public function setExtraParameters()
4804  {
4805  $this->db->begin();
4806 
4807  $extraparams = (!empty($this->extraparams) ? json_encode($this->extraparams) : null);
4808 
4809  $sql = "UPDATE ".$this->db->prefix().$this->table_element;
4810  $sql .= " SET extraparams = ".(!empty($extraparams) ? "'".$this->db->escape($extraparams)."'" : "null");
4811  $sql .= " WHERE rowid = ".((int) $this->id);
4812 
4813  dol_syslog(get_class($this)."::setExtraParameters", LOG_DEBUG);
4814  $resql = $this->db->query($sql);
4815  if (!$resql) {
4816  $this->error = $this->db->lasterror();
4817  $this->db->rollback();
4818  return -1;
4819  } else {
4820  $this->db->commit();
4821  return 1;
4822  }
4823  }
4824 
4825 
4826  // --------------------
4827  // TODO: All functions here must be redesigned and moved as they are not business functions but output functions
4828  // --------------------
4829 
4830  /* This is to show add lines */
4831 
4841  public function formAddObjectLine($dateSelector, $seller, $buyer, $defaulttpldir = '/core/tpl')
4842  {
4843  global $conf, $user, $langs, $object, $hookmanager, $extrafields;
4844  global $form;
4845 
4846  // Line extrafield
4847  if (!is_object($extrafields)) {
4848  require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
4849  $extrafields = new ExtraFields($this->db);
4850  }
4851  $extrafields->fetch_name_optionals_label($this->table_element_line);
4852 
4853  // Output template part (modules that overwrite templates must declare this into descriptor)
4854  // Use global variables + $dateSelector + $seller and $buyer
4855  // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook 'formAddObjectLine'.
4856  $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
4857  foreach ($dirtpls as $module => $reldir) {
4858  if (!empty($module)) {
4859  $tpl = dol_buildpath($reldir.'/objectline_create.tpl.php');
4860  } else {
4861  $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_create.tpl.php';
4862  }
4863 
4864  if (empty($conf->file->strict_mode)) {
4865  $res = @include $tpl;
4866  } else {
4867  $res = include $tpl; // for debug
4868  }
4869  if ($res) {
4870  break;
4871  }
4872  }
4873  }
4874 
4875 
4876 
4877  /* This is to show array of line of details */
4878 
4879 
4894  public function printObjectLines($action, $seller, $buyer, $selected = 0, $dateSelector = 0, $defaulttpldir = '/core/tpl')
4895  {
4896  global $conf, $hookmanager, $langs, $user, $form, $extrafields, $object;
4897  // TODO We should not use global var for this
4898  global $inputalsopricewithtax, $usemargins, $disableedit, $disablemove, $disableremove, $outputalsopricetotalwithtax;
4899 
4900  // Define usemargins
4901  $usemargins = 0;
4902  if (isModEnabled('margin') && !empty($this->element) && in_array($this->element, array('facture', 'facturerec', 'propal', 'commande'))) {
4903  $usemargins = 1;
4904  }
4905 
4906  $num = count($this->lines);
4907 
4908  // Line extrafield
4909  if (!is_object($extrafields)) {
4910  require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
4911  $extrafields = new ExtraFields($this->db);
4912  }
4913  $extrafields->fetch_name_optionals_label($this->table_element_line);
4914 
4915  $parameters = array('num'=>$num, 'dateSelector'=>$dateSelector, 'seller'=>$seller, 'buyer'=>$buyer, 'selected'=>$selected, 'table_element_line'=>$this->table_element_line);
4916  $reshook = $hookmanager->executeHooks('printObjectLineTitle', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
4917  if (empty($reshook)) {
4918  // Output template part (modules that overwrite templates must declare this into descriptor)
4919  // Use global variables + $dateSelector + $seller and $buyer
4920  // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook.
4921  $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
4922  foreach ($dirtpls as $module => $reldir) {
4923  $res = 0;
4924  if (!empty($module)) {
4925  $tpl = dol_buildpath($reldir.'/objectline_title.tpl.php');
4926  } else {
4927  $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_title.tpl.php';
4928  }
4929  if (file_exists($tpl)) {
4930  if (empty($conf->file->strict_mode)) {
4931  $res = @include $tpl;
4932  } else {
4933  $res = include $tpl; // for debug
4934  }
4935  }
4936  if ($res) {
4937  break;
4938  }
4939  }
4940  }
4941 
4942  $i = 0;
4943 
4944  print "<!-- begin printObjectLines() --><tbody>\n";
4945  foreach ($this->lines as $line) {
4946  //Line extrafield
4947  $line->fetch_optionals();
4948 
4949  //if (is_object($hookmanager) && (($line->product_type == 9 && !empty($line->special_code)) || !empty($line->fk_parent_line)))
4950  if (is_object($hookmanager)) { // Old code is commented on preceding line.
4951  if (empty($line->fk_parent_line)) {
4952  $parameters = array('line'=>$line, 'num'=>$num, 'i'=>$i, 'dateSelector'=>$dateSelector, 'seller'=>$seller, 'buyer'=>$buyer, 'selected'=>$selected, 'table_element_line'=>$line->table_element);
4953  $reshook = $hookmanager->executeHooks('printObjectLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
4954  } else {
4955  $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);
4956  $reshook = $hookmanager->executeHooks('printObjectSubLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
4957  }
4958  }
4959  if (empty($reshook)) {
4960  $this->printObjectLine($action, $line, '', $num, $i, $dateSelector, $seller, $buyer, $selected, $extrafields, $defaulttpldir);
4961  }
4962 
4963  $i++;
4964  }
4965  print "</tbody><!-- end printObjectLines() -->\n";
4966  }
4967 
4985  public function printObjectLine($action, $line, $var, $num, $i, $dateSelector, $seller, $buyer, $selected = 0, $extrafields = null, $defaulttpldir = '/core/tpl')
4986  {
4987  global $conf, $langs, $user, $object, $hookmanager;
4988  global $form;
4989  global $object_rights, $disableedit, $disablemove, $disableremove; // TODO We should not use global var for this !
4990 
4991  $object_rights = $this->getRights();
4992 
4993  $element = $this->element;
4994 
4995  $text = '';
4996  $description = '';
4997 
4998  // Line in view mode
4999  if ($action != 'editline' || $selected != $line->id) {
5000  // Product
5001  if (!empty($line->fk_product) && $line->fk_product > 0) {
5002  $product_static = new Product($this->db);
5003  $product_static->fetch($line->fk_product);
5004 
5005  $product_static->ref = $line->ref; //can change ref in hook
5006  $product_static->label = !empty($line->label) ? $line->label : ""; //can change label in hook
5007 
5008  $text = $product_static->getNomUrl(1);
5009 
5010  // Define output language and label
5011  if (getDolGlobalInt('MAIN_MULTILANGS')) {
5012  if (property_exists($this, 'socid') && !is_object($this->thirdparty)) {
5013  dol_print_error('', 'Error: Method printObjectLine was called on an object and object->fetch_thirdparty was not done before');
5014  return;
5015  }
5016 
5017  $prod = new Product($this->db);
5018  $prod->fetch($line->fk_product);
5019 
5020  $outputlangs = $langs;
5021  $newlang = '';
5022  if (empty($newlang) && GETPOST('lang_id', 'aZ09')) {
5023  $newlang = GETPOST('lang_id', 'aZ09');
5024  }
5025  if (!empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE) && empty($newlang) && is_object($this->thirdparty)) {
5026  $newlang = $this->thirdparty->default_lang; // To use language of customer
5027  }
5028  if (!empty($newlang)) {
5029  $outputlangs = new Translate("", $conf);
5030  $outputlangs->setDefaultLang($newlang);
5031  }
5032 
5033  $label = (!empty($prod->multilangs[$outputlangs->defaultlang]["label"])) ? $prod->multilangs[$outputlangs->defaultlang]["label"] : $line->product_label;
5034  } else {
5035  $label = $line->product_label;
5036  }
5037 
5038  $text .= ' - '.(!empty($line->label) ? $line->label : $label);
5039  $description .= (getDolGlobalInt('PRODUIT_DESC_IN_FORM_ACCORDING_TO_DEVICE') ? '' : (!empty($line->description) ? dol_htmlentitiesbr($line->description) : '')); // Description is what to show on popup. We shown nothing if already into desc.
5040  }
5041 
5042  $line->pu_ttc = price2num((!empty($line->subprice) ? $line->subprice : 0) * (1 + ((!empty($line->tva_tx) ? $line->tva_tx : 0) / 100)), 'MU');
5043 
5044  // Output template part (modules that overwrite templates must declare this into descriptor)
5045  // Use global variables + $dateSelector + $seller and $buyer
5046  // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook printObjectLine and printObjectSubLine.
5047  $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
5048  foreach ($dirtpls as $module => $reldir) {
5049  $res = 0;
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  if (file_exists($tpl)) {
5056  if (empty($conf->file->strict_mode)) {
5057  $res = @include $tpl;
5058  } else {
5059  $res = include $tpl; // for debug
5060  }
5061  }
5062  if ($res) {
5063  break;
5064  }
5065  }
5066  }
5067 
5068  // Line in update mode
5069  if ($this->statut == 0 && $action == 'editline' && $selected == $line->id) {
5070  $label = (!empty($line->label) ? $line->label : (($line->fk_product > 0) ? $line->product_label : ''));
5071 
5072  $line->pu_ttc = price2num($line->subprice * (1 + ($line->tva_tx / 100)), 'MU');
5073 
5074  // Output template part (modules that overwrite templates must declare this into descriptor)
5075  // Use global variables + $dateSelector + $seller and $buyer
5076  // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook printObjectLine and printObjectSubLine.
5077  $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
5078  foreach ($dirtpls as $module => $reldir) {
5079  if (!empty($module)) {
5080  $tpl = dol_buildpath($reldir.'/objectline_edit.tpl.php');
5081  } else {
5082  $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_edit.tpl.php';
5083  }
5084 
5085  if (empty($conf->file->strict_mode)) {
5086  $res = @include $tpl;
5087  } else {
5088  $res = include $tpl; // for debug
5089  }
5090  if ($res) {
5091  break;
5092  }
5093  }
5094  }
5095  }
5096 
5097 
5098  /* This is to show array of line of details of source object */
5099 
5100 
5111  public function printOriginLinesList($restrictlist = '', $selectedLines = array())
5112  {
5113  global $langs, $hookmanager, $conf, $form, $action;
5114 
5115  print '<tr class="liste_titre">';
5116  print '<td class="linecolref">'.$langs->trans('Ref').'</td>';
5117  print '<td class="linecoldescription">'.$langs->trans('Description').'</td>';
5118  print '<td class="linecolvat right">'.$langs->trans('VATRate').'</td>';
5119  print '<td class="linecoluht right">'.$langs->trans('PriceUHT').'</td>';
5120  if (isModEnabled("multicurrency")) {
5121  print '<td class="linecoluht_currency right">'.$langs->trans('PriceUHTCurrency').'</td>';
5122  }
5123  print '<td class="linecolqty right">'.$langs->trans('Qty').'</td>';
5124  if (getDolGlobalInt('PRODUCT_USE_UNITS')) {
5125  print '<td class="linecoluseunit left">'.$langs->trans('Unit').'</td>';
5126  }
5127  print '<td class="linecoldiscount right">'.$langs->trans('ReductionShort').'</td>';
5128  print '<td class="linecolht right">'.$langs->trans('TotalHT').'</td>';
5129  print '<td class="center">'.$form->showCheckAddButtons('checkforselect', 1).'</td>';
5130  print '</tr>';
5131  $i = 0;
5132 
5133  if (!empty($this->lines)) {
5134  foreach ($this->lines as $line) {
5135  $reshook = 0;
5136  //if (is_object($hookmanager) && (($line->product_type == 9 && !empty($line->special_code)) || !empty($line->fk_parent_line))) {
5137  if (is_object($hookmanager)) { // Old code is commented on preceding line.
5138  $parameters = array('line'=>$line, 'i'=>$i, 'restrictlist'=>$restrictlist, 'selectedLines'=> $selectedLines);
5139  if (!empty($line->fk_parent_line)) { $parameters['fk_parent_line'] = $line->fk_parent_line; }
5140  $reshook = $hookmanager->executeHooks('printOriginObjectLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
5141  }
5142  if (empty($reshook)) {
5143  $this->printOriginLine($line, '', $restrictlist, '/core/tpl', $selectedLines);
5144  }
5145 
5146  $i++;
5147  }
5148  }
5149  }
5150 
5164  public function printOriginLine($line, $var, $restrictlist = '', $defaulttpldir = '/core/tpl', $selectedLines = array())
5165  {
5166  global $langs, $conf;
5167 
5168  //var_dump($line);
5169  if (!empty($line->date_start)) {
5170  $date_start = $line->date_start;
5171  } else {
5172  $date_start = $line->date_debut_prevue;
5173  if ($line->date_debut_reel) {
5174  $date_start = $line->date_debut_reel;
5175  }
5176  }
5177  if (!empty($line->date_end)) {
5178  $date_end = $line->date_end;
5179  } else {
5180  $date_end = $line->date_fin_prevue;
5181  if ($line->date_fin_reel) {
5182  $date_end = $line->date_fin_reel;
5183  }
5184  }
5185 
5186  $this->tpl['id'] = $line->id;
5187 
5188  $this->tpl['label'] = '';
5189  if (!empty($line->fk_parent_line)) {
5190  $this->tpl['label'] .= img_picto('', 'rightarrow');
5191  }
5192 
5193  if (($line->info_bits & 2) == 2) { // TODO Not sure this is used for source object
5194  $discount = new DiscountAbsolute($this->db);
5195  $discount->fk_soc = $this->socid;
5196  $this->tpl['label'] .= $discount->getNomUrl(0, 'discount');
5197  } elseif (!empty($line->fk_product)) {
5198  $productstatic = new Product($this->db);
5199  $productstatic->id = $line->fk_product;
5200  $productstatic->ref = $line->ref;
5201  $productstatic->type = $line->fk_product_type;
5202  if (empty($productstatic->ref)) {
5203  $line->fetch_product();
5204  $productstatic = $line->product;
5205  }
5206 
5207  $this->tpl['label'] .= $productstatic->getNomUrl(1);
5208  $this->tpl['label'] .= ' - '.(!empty($line->label) ? $line->label : $line->product_label);
5209  // Dates
5210  if ($line->product_type == 1 && ($date_start || $date_end)) {
5211  $this->tpl['label'] .= get_date_range($date_start, $date_end);
5212  }
5213  } else {
5214  $this->tpl['label'] .= ($line->product_type == -1 ? '&nbsp;' : ($line->product_type == 1 ? img_object($langs->trans(''), 'service') : img_object($langs->trans(''), 'product')));
5215  if (!empty($line->desc)) {
5216  $this->tpl['label'] .= $line->desc;
5217  } else {
5218  $this->tpl['label'] .= ($line->label ? '&nbsp;'.$line->label : '');
5219  }
5220 
5221  // Dates
5222  if ($line->product_type == 1 && ($date_start || $date_end)) {
5223  $this->tpl['label'] .= get_date_range($date_start, $date_end);
5224  }
5225  }
5226 
5227  if (!empty($line->desc)) {
5228  if ($line->desc == '(CREDIT_NOTE)') { // TODO Not sure this is used for source object
5229  $discount = new DiscountAbsolute($this->db);
5230  $discount->fetch($line->fk_remise_except);
5231  $this->tpl['description'] = $langs->transnoentities("DiscountFromCreditNote", $discount->getNomUrl(0));
5232  } elseif ($line->desc == '(DEPOSIT)') { // TODO Not sure this is used for source object
5233  $discount = new DiscountAbsolute($this->db);
5234  $discount->fetch($line->fk_remise_except);
5235  $this->tpl['description'] = $langs->transnoentities("DiscountFromDeposit", $discount->getNomUrl(0));
5236  } elseif ($line->desc == '(EXCESS RECEIVED)') {
5237  $discount = new DiscountAbsolute($this->db);
5238  $discount->fetch($line->fk_remise_except);
5239  $this->tpl['description'] = $langs->transnoentities("DiscountFromExcessReceived", $discount->getNomUrl(0));
5240  } elseif ($line->desc == '(EXCESS PAID)') {
5241  $discount = new DiscountAbsolute($this->db);
5242  $discount->fetch($line->fk_remise_except);
5243  $this->tpl['description'] = $langs->transnoentities("DiscountFromExcessPaid", $discount->getNomUrl(0));
5244  } else {
5245  $this->tpl['description'] = dol_trunc($line->desc, 60);
5246  }
5247  } else {
5248  $this->tpl['description'] = '&nbsp;';
5249  }
5250 
5251  // VAT Rate
5252  $this->tpl['vat_rate'] = vatrate($line->tva_tx, true);
5253  $this->tpl['vat_rate'] .= (($line->info_bits & 1) == 1) ? '*' : '';
5254  if (!empty($line->vat_src_code) && !preg_match('/\‍(/', $this->tpl['vat_rate'])) {
5255  $this->tpl['vat_rate'] .= ' ('.$line->vat_src_code.')';
5256  }
5257 
5258  $this->tpl['price'] = price($line->subprice);
5259  $this->tpl['total_ht'] = price($line->total_ht);
5260  $this->tpl['multicurrency_price'] = price($line->multicurrency_subprice);
5261  $this->tpl['qty'] = (($line->info_bits & 2) != 2) ? $line->qty : '&nbsp;';
5262  if (getDolGlobalInt('PRODUCT_USE_UNITS')) {
5263  $this->tpl['unit'] = $langs->transnoentities($line->getLabelOfUnit('long'));
5264  }
5265  $this->tpl['remise_percent'] = (($line->info_bits & 2) != 2) ? vatrate($line->remise_percent, true) : '&nbsp;';
5266 
5267  // Is the line strike or not
5268  $this->tpl['strike'] = 0;
5269  if ($restrictlist == 'services' && $line->product_type != Product::TYPE_SERVICE) {
5270  $this->tpl['strike'] = 1;
5271  }
5272 
5273  // Output template part (modules that overwrite templates must declare this into descriptor)
5274  // Use global variables + $dateSelector + $seller and $buyer
5275  $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
5276  foreach ($dirtpls as $module => $reldir) {
5277  if (!empty($module)) {
5278  $tpl = dol_buildpath($reldir.'/originproductline.tpl.php');
5279  } else {
5280  $tpl = DOL_DOCUMENT_ROOT.$reldir.'/originproductline.tpl.php';
5281  }
5282 
5283  if (empty($conf->file->strict_mode)) {
5284  $res = @include $tpl;
5285  } else {
5286  $res = include $tpl; // for debug
5287  }
5288  if ($res) {
5289  break;
5290  }
5291  }
5292  }
5293 
5294 
5295  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5306  public function add_element_resource($resource_id, $resource_type, $busy = 0, $mandatory = 0)
5307  {
5308  // phpcs:enable
5309  $this->db->begin();
5310 
5311  $sql = "INSERT INTO ".$this->db->prefix()."element_resources (";
5312  $sql .= "resource_id";
5313  $sql .= ", resource_type";
5314  $sql .= ", element_id";
5315  $sql .= ", element_type";
5316  $sql .= ", busy";
5317  $sql .= ", mandatory";
5318  $sql .= ") VALUES (";
5319  $sql .= $resource_id;
5320  $sql .= ", '".$this->db->escape($resource_type)."'";
5321  $sql .= ", '".$this->db->escape($this->id)."'";
5322  $sql .= ", '".$this->db->escape($this->element)."'";
5323  $sql .= ", '".$this->db->escape($busy)."'";
5324  $sql .= ", '".$this->db->escape($mandatory)."'";
5325  $sql .= ")";
5326 
5327  dol_syslog(get_class($this)."::add_element_resource", LOG_DEBUG);
5328  if ($this->db->query($sql)) {
5329  $this->db->commit();
5330  return 1;
5331  } else {
5332  $this->error = $this->db->lasterror();
5333  $this->db->rollback();
5334  return 0;
5335  }
5336  }
5337 
5338  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5347  public function delete_resource($rowid, $element, $notrigger = 0)
5348  {
5349  // phpcs:enable
5350  global $user;
5351 
5352  $this->db->begin();
5353 
5354  $sql = "DELETE FROM ".$this->db->prefix()."element_resources";
5355  $sql .= " WHERE rowid = ".((int) $rowid);
5356 
5357  dol_syslog(get_class($this)."::delete_resource", LOG_DEBUG);
5358 
5359  $resql = $this->db->query($sql);
5360  if (!$resql) {
5361  $this->error = $this->db->lasterror();
5362  $this->db->rollback();
5363  return -1;
5364  } else {
5365  if (!$notrigger) {
5366  $result = $this->call_trigger(strtoupper($element).'_DELETE_RESOURCE', $user);
5367  if ($result < 0) {
5368  $this->db->rollback();
5369  return -1;
5370  }
5371  }
5372  $this->db->commit();
5373  return 1;
5374  }
5375  }
5376 
5377 
5383  public function __clone()
5384  {
5385  // Force a copy of this->lines, otherwise it will point to same object.
5386  if (isset($this->lines) && is_array($this->lines)) {
5387  $nboflines = count($this->lines);
5388  for ($i = 0; $i < $nboflines; $i++) {
5389  $this->lines[$i] = clone $this->lines[$i];
5390  }
5391  }
5392  }
5393 
5407  protected function commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams = null)
5408  {
5409  global $conf, $langs, $user, $hookmanager, $action;
5410 
5411  $srctemplatepath = '';
5412 
5413  $parameters = array('modelspath'=>$modelspath, 'modele'=>$modele, 'outputlangs'=>$outputlangs, 'hidedetails'=>$hidedetails, 'hidedesc'=>$hidedesc, 'hideref'=>$hideref, 'moreparams'=>$moreparams);
5414  $reshook = $hookmanager->executeHooks('commonGenerateDocument', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
5415 
5416  if (empty($reshook)) {
5417  dol_syslog("commonGenerateDocument modele=".$modele." outputlangs->defaultlang=".(is_object($outputlangs) ? $outputlangs->defaultlang : 'null'));
5418 
5419  if (empty($modele)) {
5420  $this->error = 'BadValueForParameterModele';
5421  return -1;
5422  }
5423 
5424  // Increase limit for PDF build
5425  $err = error_reporting();
5426  error_reporting(0);
5427  @set_time_limit(120);
5428  error_reporting($err);
5429 
5430  // If selected model is a filename template (then $modele="modelname" or "modelname:filename")
5431  $tmp = explode(':', $modele, 2);
5432  if (!empty($tmp[1])) {
5433  $modele = $tmp[0];
5434  $srctemplatepath = $tmp[1];
5435  }
5436 
5437  // Search template files
5438  $file = '';
5439  $classname = '';
5440  $filefound = '';
5441  $dirmodels = array('/');
5442  if (is_array($conf->modules_parts['models'])) {
5443  $dirmodels = array_merge($dirmodels, $conf->modules_parts['models']);
5444  }
5445  foreach ($dirmodels as $reldir) {
5446  foreach (array('doc', 'pdf') as $prefix) {
5447  if (in_array(get_class($this), array('Adherent'))) {
5448  // Member module use prefix_modele.class.php
5449  $file = $prefix."_".$modele.".class.php";
5450  } else {
5451  // Other module use prefix_modele.modules.php
5452  $file = $prefix."_".$modele.".modules.php";
5453  }
5454 
5455  // On verifie l'emplacement du modele
5456  $file = dol_buildpath($reldir.$modelspath.$file, 0);
5457  if (file_exists($file)) {
5458  $filefound = $file;
5459  $classname = $prefix.'_'.$modele;
5460  break;
5461  }
5462  }
5463  if ($filefound) {
5464  break;
5465  }
5466  }
5467 
5468  // If generator was found
5469  if ($filefound) {
5470  global $db; // Required to solve a conception default making an include of code using $db instead of $this->db just after.
5471 
5472  require_once $file;
5473 
5474  $obj = new $classname($this->db);
5475 
5476  // If generator is ODT, we must have srctemplatepath defined, if not we set it.
5477  if ($obj->type == 'odt' && empty($srctemplatepath)) {
5478  $varfortemplatedir = $obj->scandir;
5479  if ($varfortemplatedir && !empty($conf->global->$varfortemplatedir)) {
5480  $dirtoscan = $conf->global->$varfortemplatedir;
5481 
5482  $listoffiles = array();
5483 
5484  // Now we add first model found in directories scanned
5485  $listofdir = explode(',', $dirtoscan);
5486  foreach ($listofdir as $key => $tmpdir) {
5487  $tmpdir = trim($tmpdir);
5488  $tmpdir = preg_replace('/DOL_DATA_ROOT/', DOL_DATA_ROOT, $tmpdir);
5489  if (!$tmpdir) {
5490  unset($listofdir[$key]);
5491  continue;
5492  }
5493  if (is_dir($tmpdir)) {
5494  $tmpfiles = dol_dir_list($tmpdir, 'files', 0, '\.od(s|t)$', '', 'name', SORT_ASC, 0);
5495  if (count($tmpfiles)) {
5496  $listoffiles = array_merge($listoffiles, $tmpfiles);
5497  }
5498  }
5499  }
5500 
5501  if (count($listoffiles)) {
5502  foreach ($listoffiles as $record) {
5503  $srctemplatepath = $record['fullname'];
5504  break;
5505  }
5506  }
5507  }
5508 
5509  if (empty($srctemplatepath)) {
5510  $this->error = 'ErrorGenerationAskedForOdtTemplateWithSrcFileNotDefined';
5511  return -1;
5512  }
5513  }
5514 
5515  if ($obj->type == 'odt' && !empty($srctemplatepath)) {
5516  if (!dol_is_file($srctemplatepath)) {
5517  dol_syslog("Failed to locate template file ".$srctemplatepath, LOG_WARNING);
5518  $this->error = 'ErrorGenerationAskedForOdtTemplateWithSrcFileNotFound';
5519  return -1;
5520  }
5521  }
5522 
5523  // We save charset_output to restore it because write_file can change it if needed for
5524  // output format that does not support UTF8.
5525  $sav_charset_output = empty($outputlangs->charset_output) ? '' : $outputlangs->charset_output;
5526 
5527  if (in_array(get_class($this), array('Adherent'))) {
5528  $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, 'member', 1, 'tmp_cards', $moreparams);
5529  } else {
5530  $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, $hidedetails, $hidedesc, $hideref, $moreparams);
5531  }
5532  // After call of write_file $obj->result['fullpath'] is set with generated file. It will be used to update the ECM database index.
5533 
5534  if ($resultwritefile > 0) {
5535  $outputlangs->charset_output = $sav_charset_output;
5536 
5537  // We delete old preview
5538  require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
5539  dol_delete_preview($this);
5540 
5541  // Index file in database
5542  if (!empty($obj->result['fullpath'])) {
5543  $destfull = $obj->result['fullpath'];
5544 
5545  // Update the last_main_doc field into main object (if document generator has property ->update_main_doc_field set)
5546  $update_main_doc_field = 0;
5547  if (!empty($obj->update_main_doc_field)) {
5548  $update_main_doc_field = 1;
5549  }
5550 
5551  $this->indexFile($destfull, $update_main_doc_field);
5552  } else {
5553  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);
5554  }
5555 
5556  // Success in building document. We build meta file.
5557  dol_meta_create($this);
5558 
5559  return 1;
5560  } else {
5561  $outputlangs->charset_output = $sav_charset_output;
5562  $this->error = $obj->error;
5563  $this->errors = $obj->errors;
5564  dol_syslog("Error generating document for ".__CLASS__.". Error: ".$obj->error, LOG_ERR);
5565  return -1;
5566  }
5567  } else {
5568  if (!$filefound) {
5569  $this->error = $langs->trans("Error").' Failed to load doc generator with modelpaths='.$modelspath.' - modele='.$modele;
5570  $this->errors[] = $this->error;
5571  dol_syslog($this->error, LOG_ERR);
5572  } else {
5573  $this->error = $langs->trans("Error")." ".$langs->trans("ErrorFileDoesNotExists", $filefound);
5574  $this->errors[] = $this->error;
5575  dol_syslog($this->error, LOG_ERR);
5576  }
5577  return -1;
5578  }
5579  } else {
5580  return $reshook;
5581  }
5582  }
5583 
5593  public function indexFile($destfull, $update_main_doc_field)
5594  {
5595  global $conf, $user;
5596 
5597  $upload_dir = dirname($destfull);
5598  $destfile = basename($destfull);
5599  $rel_dir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $upload_dir);
5600 
5601  if (!preg_match('/[\\/]temp[\\/]|[\\/]thumbs|\.meta$/', $rel_dir)) { // If not a tmp dir
5602  $filename = basename($destfile);
5603  $rel_dir = preg_replace('/[\\/]$/', '', $rel_dir);
5604  $rel_dir = preg_replace('/^[\\/]/', '', $rel_dir);
5605 
5606  include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
5607  $ecmfile = new EcmFiles($this->db);
5608  $result = $ecmfile->fetch(0, '', ($rel_dir ? $rel_dir.'/' : '').$filename);
5609 
5610  // Set the public "share" key
5611  $setsharekey = false;
5612  if ($this->element == 'propal' || $this->element == 'proposal') {
5613  if (!isset($conf->global->PROPOSAL_ALLOW_ONLINESIGN) || !empty($conf->global->PROPOSAL_ALLOW_ONLINESIGN)) {
5614  $setsharekey = true; // feature to make online signature is not set or set to on (default)
5615  }
5616  if (!empty($conf->global->PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD)) {
5617  $setsharekey = true;
5618  }
5619  }
5620  if ($this->element == 'commande' && !empty($conf->global->ORDER_ALLOW_EXTERNAL_DOWNLOAD)) {
5621  $setsharekey = true;
5622  }
5623  if ($this->element == 'facture' && !empty($conf->global->INVOICE_ALLOW_EXTERNAL_DOWNLOAD)) {
5624  $setsharekey = true;
5625  }
5626  if ($this->element == 'bank_account' && !empty($conf->global->BANK_ACCOUNT_ALLOW_EXTERNAL_DOWNLOAD)) {
5627  $setsharekey = true;
5628  }
5629  if ($this->element == 'product' && !empty($conf->global->PRODUCT_ALLOW_EXTERNAL_DOWNLOAD)) {
5630  $setsharekey = true;
5631  }
5632  if ($this->element == 'contrat' && !empty($conf->global->CONTRACT_ALLOW_EXTERNAL_DOWNLOAD)) {
5633  $setsharekey = true;
5634  }
5635  if ($this->element == 'fichinter' && !empty($conf->global->FICHINTER_ALLOW_EXTERNAL_DOWNLOAD)) {
5636  $setsharekey = true;
5637  }
5638  if ($this->element == 'supplier_proposal' && !empty($conf->global->SUPPLIER_PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD)) {
5639  $setsharekey = true;
5640  }
5641 
5642  if ($setsharekey) {
5643  if (empty($ecmfile->share)) { // Because object not found or share not set yet
5644  require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
5645  $ecmfile->share = getRandomPassword(true);
5646  }
5647  }
5648 
5649  if ($result > 0) {
5650  $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
5651  $ecmfile->fullpath_orig = '';
5652  $ecmfile->gen_or_uploaded = 'generated';
5653  $ecmfile->description = ''; // indexed content
5654  $ecmfile->keywords = ''; // keyword content
5655  $result = $ecmfile->update($user);
5656  if ($result < 0) {
5657  setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
5658  return -1;
5659  }
5660  } else {
5661  $ecmfile->entity = $conf->entity;
5662  $ecmfile->filepath = $rel_dir;
5663  $ecmfile->filename = $filename;
5664  $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
5665  $ecmfile->fullpath_orig = '';
5666  $ecmfile->gen_or_uploaded = 'generated';
5667  $ecmfile->description = ''; // indexed content
5668  $ecmfile->keywords = ''; // keyword content
5669  $ecmfile->src_object_type = $this->table_element; // $this->table_name is 'myobject' or 'mymodule_myobject'.
5670  $ecmfile->src_object_id = $this->id;
5671 
5672  $result = $ecmfile->create($user);
5673  if ($result < 0) {
5674  setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
5675  return -1;
5676  }
5677  }
5678 
5679  /*$this->result['fullname']=$destfull;
5680  $this->result['filepath']=$ecmfile->filepath;
5681  $this->result['filename']=$ecmfile->filename;*/
5682  //var_dump($obj->update_main_doc_field);exit;
5683 
5684  if ($update_main_doc_field && !empty($this->table_element)) {
5685  $sql = "UPDATE ".$this->db->prefix().$this->table_element." SET last_main_doc = '".$this->db->escape($ecmfile->filepath."/".$ecmfile->filename)."'";
5686  $sql .= " WHERE rowid = ".((int) $this->id);
5687 
5688  $resql = $this->db->query($sql);
5689  if (!$resql) {
5690  dol_print_error($this->db);
5691  return -1;
5692  } else {
5693  $this->last_main_doc = $ecmfile->filepath.'/'.$ecmfile->filename;
5694  }
5695  }
5696  }
5697 
5698  return 1;
5699  }
5700 
5708  public function addThumbs($file)
5709  {
5710  global $maxwidthsmall, $maxheightsmall, $maxwidthmini, $maxheightmini, $quality;
5711 
5712  require_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php'; // This define also $maxwidthsmall, $quality, ...
5713 
5714  $file_osencoded = dol_osencode($file);
5715  if (file_exists($file_osencoded)) {
5716  // Create small thumbs for company (Ratio is near 16/9)
5717  // Used on logon for example
5718  vignette($file_osencoded, $maxwidthsmall, $maxheightsmall, '_small', $quality);
5719 
5720  // Create mini thumbs for company (Ratio is near 16/9)
5721  // Used on menu or for setup page for example
5722  vignette($file_osencoded, $maxwidthmini, $maxheightmini, '_mini', $quality);
5723  }
5724  }
5725 
5726 
5727  /* Functions common to commonobject and commonobjectline */
5728 
5729  /* For default values */
5730 
5743  public function getDefaultCreateValueFor($fieldname, $alternatevalue = null)
5744  {
5745  global $conf, $_POST;
5746 
5747  // If param here has been posted, we use this value first.
5748  if (GETPOSTISSET($fieldname)) {
5749  return GETPOST($fieldname, 'alphanohtml', 3);
5750  }
5751 
5752  if (isset($alternatevalue)) {
5753  return $alternatevalue;
5754  }
5755 
5756  $newelement = $this->element;
5757  if ($newelement == 'facture') {
5758  $newelement = 'invoice';
5759  }
5760  if ($newelement == 'commande') {
5761  $newelement = 'order';
5762  }
5763  if (empty($newelement)) {
5764  dol_syslog("Ask a default value using common method getDefaultCreateValueForField on an object with no property ->element defined. Return empty string.", LOG_WARNING);
5765  return '';
5766  }
5767 
5768  $keyforfieldname = strtoupper($newelement.'_DEFAULT_'.$fieldname);
5769  //var_dump($keyforfieldname);
5770  if (isset($conf->global->$keyforfieldname)) {
5771  return $conf->global->$keyforfieldname;
5772  }
5773 
5774  // TODO Ad here a scan into table llx_overwrite_default with a filter on $this->element and $fieldname
5775  }
5776 
5777 
5778  /* For triggers */
5779 
5780 
5781  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5792  public function call_trigger($triggerName, $user)
5793  {
5794  // phpcs:enable
5795  global $langs, $conf;
5796  if (!empty(self::TRIGGER_PREFIX) && strpos($triggerName, self::TRIGGER_PREFIX . '_') !== 0) {
5797  dol_print_error('', 'The trigger "' . $triggerName . '" does not start with "' . self::TRIGGER_PREFIX . '_" as required.');
5798  exit;
5799  }
5800  if (!is_object($langs)) { // If lang was not defined, we set it. It is required by run_triggers.
5801  include_once DOL_DOCUMENT_ROOT.'/core/class/translate.class.php';
5802  $langs = new Translate('', $conf);
5803  }
5804 
5805  include_once DOL_DOCUMENT_ROOT.'/core/class/interfaces.class.php';
5806  $interface = new Interfaces($this->db);
5807  $result = $interface->run_triggers($triggerName, $this, $user, $langs, $conf);
5808 
5809  if ($result < 0) {
5810  if (!empty($this->errors)) {
5811  $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.
5812  } else {
5813  $this->errors = $interface->errors;
5814  }
5815  }
5816  return $result;
5817  }
5818 
5819 
5820  /* Functions for data in other language */
5821 
5822 
5830  public function fetchValuesForExtraLanguages()
5831  {
5832  // To avoid SQL errors. Probably not the better solution though
5833  if (!$this->element) {
5834  return 0;
5835  }
5836  if (!($this->id > 0)) {
5837  return 0;
5838  }
5839  if (is_array($this->array_languages)) {
5840  return 1;
5841  }
5842 
5843  $this->array_languages = array();
5844 
5845  $element = $this->element;
5846  if ($element == 'categorie') {
5847  $element = 'categories'; // For compatibility
5848  }
5849 
5850  // Request to get translation values for object
5851  $sql = "SELECT rowid, property, lang , value";
5852  $sql .= " FROM ".$this->db->prefix()."object_lang";
5853  $sql .= " WHERE type_object = '".$this->db->escape($element)."'";
5854  $sql .= " AND fk_object = ".((int) $this->id);
5855 
5856  //dol_syslog(get_class($this)."::fetch_optionals get extrafields data for ".$this->table_element, LOG_DEBUG); // Too verbose
5857  $resql = $this->db->query($sql);
5858  if ($resql) {
5859  $numrows = $this->db->num_rows($resql);
5860  if ($numrows) {
5861  $i = 0;
5862  while ($i < $numrows) {
5863  $obj = $this->db->fetch_object($resql);
5864  $key = $obj->property;
5865  $value = $obj->value;
5866  $codelang = $obj->lang;
5867  $type = $this->fields[$key]['type'];
5868 
5869  // we can add this attribute to object
5870  if (preg_match('/date/', $type)) {
5871  $this->array_languages[$key][$codelang] = $this->db->jdate($value);
5872  } else {
5873  $this->array_languages[$key][$codelang] = $value;
5874  }
5875 
5876  $i++;
5877  }
5878  }
5879 
5880  $this->db->free($resql);
5881 
5882  if ($numrows) {
5883  return $numrows;
5884  } else {
5885  return 0;
5886  }
5887  } else {
5888  dol_print_error($this->db);
5889  return -1;
5890  }
5891  }
5892 
5899  public function setValuesForExtraLanguages($onlykey = '')
5900  {
5901  global $_POST, $langs;
5902 
5903  // Get extra fields
5904  foreach ($_POST as $postfieldkey => $postfieldvalue) {
5905  $tmparray = explode('-', $postfieldkey);
5906  if ($tmparray[0] != 'field') {
5907  continue;
5908  }
5909 
5910  $element = $tmparray[1];
5911  $key = $tmparray[2];
5912  $codelang = $tmparray[3];
5913  //var_dump("postfieldkey=".$postfieldkey." element=".$element." key=".$key." codelang=".$codelang);
5914 
5915  if (!empty($onlykey) && $key != $onlykey) {
5916  continue;
5917  }
5918  if ($element != $this->element) {
5919  continue;
5920  }
5921 
5922  $key_type = $this->fields[$key]['type'];
5923 
5924  $enabled = 1;
5925  if (isset($this->fields[$key]['enabled'])) {
5926  $enabled = dol_eval($this->fields[$key]['enabled'], 1, 1, '1');
5927  }
5928  /*$perms = 1;
5929  if (isset($this->fields[$key]['perms']))
5930  {
5931  $perms = dol_eval($this->fields[$key]['perms'], 1, 1, '1');
5932  }*/
5933  if (empty($enabled)) {
5934  continue;
5935  }
5936  //if (empty($perms)) continue;
5937 
5938  if (in_array($key_type, array('date'))) {
5939  // Clean parameters
5940  // TODO GMT date in memory must be GMT so we should add gm=true in parameters
5941  $value_key = dol_mktime(0, 0, 0, GETPOST($postfieldkey."month", 'int'), GETPOST($postfieldkey."day", 'int'), GETPOST($postfieldkey."year", 'int'));
5942  } elseif (in_array($key_type, array('datetime'))) {
5943  // Clean parameters
5944  // TODO GMT date in memory must be GMT so we should add gm=true in parameters
5945  $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'));
5946  } elseif (in_array($key_type, array('checkbox', 'chkbxlst'))) {
5947  $value_arr = GETPOST($postfieldkey, 'array'); // check if an array
5948  if (!empty($value_arr)) {
5949  $value_key = implode(',', $value_arr);
5950  } else {
5951  $value_key = '';
5952  }
5953  } elseif (in_array($key_type, array('price', 'double'))) {
5954  $value_arr = GETPOST($postfieldkey, 'alpha');
5955  $value_key = price2num($value_arr);
5956  } else {
5957  $value_key = GETPOST($postfieldkey);
5958  if (in_array($key_type, array('link')) && $value_key == '-1') {
5959  $value_key = '';
5960  }
5961  }
5962 
5963  $this->array_languages[$key][$codelang] = $value_key;
5964 
5965  /*if ($nofillrequired) {
5966  $langs->load('errors');
5967  setEventMessages($langs->trans('ErrorFieldsRequired').' : '.implode(', ', $error_field_required), null, 'errors');
5968  return -1;
5969  }*/
5970  }
5971 
5972  return 1;
5973  }
5974 
5975 
5976  /* Functions for extrafields */
5977 
5984  public function fetchNoCompute($id)
5985  {
5986  global $conf;
5987 
5988  $savDisableCompute = $conf->disable_compute;
5989  $conf->disable_compute = 1;
5990 
5991  $ret = $this->fetch($id);
5992 
5993  $conf->disable_compute = $savDisableCompute;
5994 
5995  return $ret;
5996  }
5997 
5998  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
6008  public function fetch_optionals($rowid = null, $optionsArray = null)
6009  {
6010  // phpcs:enable
6011  global $conf, $extrafields;
6012 
6013  if (empty($rowid)) {
6014  $rowid = $this->id;
6015  }
6016  if (empty($rowid) && isset($this->rowid)) {
6017  $rowid = $this->rowid; // deprecated
6018  }
6019 
6020  // To avoid SQL errors. Probably not the better solution though
6021  if (!$this->table_element) {
6022  return 0;
6023  }
6024 
6025  $this->array_options = array();
6026 
6027  if (!is_array($optionsArray)) {
6028  // If $extrafields is not a known object, we initialize it. Best practice is to have $extrafields defined into card.php or list.php page.
6029  if (!isset($extrafields) || !is_object($extrafields)) {
6030  require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
6031  $extrafields = new ExtraFields($this->db);
6032  }
6033 
6034  // Load array of extrafields for elementype = $this->table_element
6035  if (empty($extrafields->attributes[$this->table_element]['loaded'])) {
6036  $extrafields->fetch_name_optionals_label($this->table_element);
6037  }
6038  $optionsArray = (!empty($extrafields->attributes[$this->table_element]['label']) ? $extrafields->attributes[$this->table_element]['label'] : null);
6039  } else {
6040  global $extrafields;
6041  dol_syslog("Warning: fetch_optionals was called with param optionsArray defined when you should pass null now", LOG_WARNING);
6042  }
6043 
6044  $table_element = $this->table_element;
6045  if ($table_element == 'categorie') {
6046  $table_element = 'categories'; // For compatibility
6047  }
6048 
6049  // Request to get complementary values
6050  if (is_array($optionsArray) && count($optionsArray) > 0) {
6051  $sql = "SELECT rowid";
6052  foreach ($optionsArray as $name => $label) {
6053  if (empty($extrafields->attributes[$this->table_element]['type'][$name]) || $extrafields->attributes[$this->table_element]['type'][$name] != 'separate') {
6054  $sql .= ", ".$name;
6055  }
6056  }
6057  $sql .= " FROM ".$this->db->prefix().$table_element."_extrafields";
6058  $sql .= " WHERE fk_object = ".((int) $rowid);
6059 
6060  //dol_syslog(get_class($this)."::fetch_optionals get extrafields data for ".$this->table_element, LOG_DEBUG); // Too verbose
6061  $resql = $this->db->query($sql);
6062  if ($resql) {
6063  $numrows = $this->db->num_rows($resql);
6064  if ($numrows) {
6065  $tab = $this->db->fetch_array($resql);
6066 
6067  foreach ($tab as $key => $value) {
6068  // 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)
6069  if ($key != 'rowid' && $key != 'tms' && $key != 'fk_member' && !is_int($key)) {
6070  // we can add this attribute to object
6071  if (!empty($extrafields->attributes[$this->table_element]) && in_array($extrafields->attributes[$this->table_element]['type'][$key], array('date', 'datetime'))) {
6072  //var_dump($extrafields->attributes[$this->table_element]['type'][$key]);
6073  $this->array_options["options_".$key] = $this->db->jdate($value);
6074  } else {
6075  $this->array_options["options_".$key] = $value;
6076  }
6077 
6078  //var_dump('key '.$key.' '.$value.' type='.$extrafields->attributes[$this->table_element]['type'][$key].' '.$this->array_options["options_".$key]);
6079  }
6080  }
6081  }
6082 
6083  // If field is a computed field, value must become result of compute (regardless of whether a row exists
6084  // in the element's extrafields table)
6085  foreach ($extrafields->attributes[$this->table_element]['label'] as $key => $val) {
6086  if (!empty($extrafields->attributes[$this->table_element]) && !empty($extrafields->attributes[$this->table_element]['computed'][$key])) {
6087  //var_dump($conf->disable_compute);
6088  if (empty($conf->disable_compute)) {
6089  $this->array_options["options_".$key] = dol_eval($extrafields->attributes[$this->table_element]['computed'][$key], 1, 0, '');
6090  }
6091  }
6092  }
6093 
6094  $this->db->free($resql);
6095 
6096  if ($numrows) {
6097  return $numrows;
6098  } else {
6099  return 0;
6100  }
6101  } else {
6102  $this->errors[]=$this->db->lasterror;
6103  return -1;
6104  }
6105  }
6106  return 0;
6107  }
6108 
6115  public function deleteExtraFields()
6116  {
6117  global $conf;
6118 
6119  if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
6120  return 0;
6121  }
6122 
6123  $this->db->begin();
6124 
6125  $table_element = $this->table_element;
6126  if ($table_element == 'categorie') {
6127  $table_element = 'categories'; // For compatibility
6128  }
6129 
6130  dol_syslog(get_class($this)."::deleteExtraFields delete", LOG_DEBUG);
6131 
6132  $sql_del = "DELETE FROM ".$this->db->prefix().$table_element."_extrafields WHERE fk_object = ".((int) $this->id);
6133 
6134  $resql = $this->db->query($sql_del);
6135  if (!$resql) {
6136  $this->error = $this->db->lasterror();
6137  $this->db->rollback();
6138  return -1;
6139  } else {
6140  $this->db->commit();
6141  return 1;
6142  }
6143  }
6144 
6155  public function insertExtraFields($trigger = '', $userused = null)
6156  {
6157  global $conf, $langs, $user;
6158 
6159  if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
6160  return 0;
6161  }
6162 
6163  if (empty($userused)) {
6164  $userused = $user;
6165  }
6166 
6167  $error = 0;
6168 
6169  if (!empty($this->array_options)) {
6170  // Check parameters
6171  $langs->load('admin');
6172  require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
6173  $extrafields = new ExtraFields($this->db);
6174  $target_extrafields = $extrafields->fetch_name_optionals_label($this->table_element);
6175 
6176  // Eliminate copied source object extra fields that do not exist in target object
6177  $new_array_options = array();
6178  foreach ($this->array_options as $key => $value) {
6179  if (in_array(substr($key, 8), array_keys($target_extrafields))) { // We remove the 'options_' from $key for test
6180  $new_array_options[$key] = $value;
6181  } elseif (in_array($key, array_keys($target_extrafields))) { // We test on $key that does not contains the 'options_' prefix
6182  $new_array_options['options_'.$key] = $value;
6183  }
6184  }
6185 
6186  foreach ($new_array_options as $key => $value) {
6187  $attributeKey = substr($key, 8); // Remove 'options_' prefix
6188  $attributeType = $extrafields->attributes[$this->table_element]['type'][$attributeKey];
6189  $attributeLabel = $extrafields->attributes[$this->table_element]['label'][$attributeKey];
6190  $attributeParam = $extrafields->attributes[$this->table_element]['param'][$attributeKey];
6191  $attributeRequired = $extrafields->attributes[$this->table_element]['required'][$attributeKey];
6192  $attributeUnique = $extrafields->attributes[$this->table_element]['unique'][$attributeKey];
6193  $attrfieldcomputed = $extrafields->attributes[$this->table_element]['computed'][$attributeKey];
6194 
6195  // If we clone, we have to clean unique extrafields to prevent duplicates.
6196  // This behaviour can be prevented by external code by changing $this->context['createfromclone'] value in createFrom hook
6197  if (!empty($this->context['createfromclone']) && $this->context['createfromclone'] == 'createfromclone' && !empty($attributeUnique)) {
6198  $new_array_options[$key] = null;
6199  }
6200 
6201  // Similar code than into insertExtraFields
6202  if ($attributeRequired) {
6203  $mandatorypb = false;
6204  if ($attributeType == 'link' && $this->array_options[$key] == '-1') {
6205  $mandatorypb = true;
6206  }
6207  if ($this->array_options[$key] === '') {
6208  $mandatorypb = true;
6209  }
6210  if ($attributeType == 'sellist' && $this->array_options[$key] == '0') {
6211  $mandatorypb = true;
6212  }
6213  if ($mandatorypb) {
6214  $langs->load("errors");
6215  dol_syslog("Mandatory field '".$key."' is empty during create and set to required into definition of extrafields");
6216  $this->errors[] = $langs->trans('ErrorFieldRequired', $attributeLabel);
6217  return -1;
6218  }
6219  }
6220 
6221  //dol_syslog("attributeLabel=".$attributeLabel, LOG_DEBUG);
6222  //dol_syslog("attributeType=".$attributeType, LOG_DEBUG);
6223 
6224  if (!empty($attrfieldcomputed)) {
6225  if (!empty($conf->global->MAIN_STORE_COMPUTED_EXTRAFIELDS)) {
6226  $value = dol_eval($attrfieldcomputed, 1, 0, '');
6227  dol_syslog($langs->trans("Extrafieldcomputed")." sur ".$attributeLabel."(".$value.")", LOG_DEBUG);
6228  $new_array_options[$key] = $value;
6229  } else {
6230  $new_array_options[$key] = null;
6231  }
6232  }
6233 
6234  switch ($attributeType) {
6235  case 'int':
6236  if (!is_numeric($value) && $value != '') {
6237  $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
6238  return -1;
6239  } elseif ($value == '') {
6240  $new_array_options[$key] = null;
6241  }
6242  break;
6243  case 'price':
6244  case 'double':
6245  $value = price2num($value);
6246  if (!is_numeric($value) && $value != '') {
6247  dol_syslog($langs->trans("ExtraFieldHasWrongValue")." for ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
6248  $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
6249  return -1;
6250  } elseif ($value == '') {
6251  $value = null;
6252  }
6253  //dol_syslog("double value"." sur ".$attributeLabel."(".$value." is '".$attributeType."')", LOG_DEBUG);
6254  $new_array_options[$key] = $value;
6255  break;
6256  /*case 'select': // Not required, we chosed value='0' for undefined values
6257  if ($value=='-1')
6258  {
6259  $this->array_options[$key] = null;
6260  }
6261  break;*/
6262  case 'password':
6263  $algo = '';
6264  if ($this->array_options[$key] != '' && is_array($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options'])) {
6265  // If there is an encryption choice, we use it to crypt data before insert
6266  $tmparrays = array_keys($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options']);
6267  $algo = reset($tmparrays);
6268  if ($algo != '') {
6269  //global $action; // $action may be 'create', 'update', 'update_extras'...
6270  //var_dump($action);
6271  //var_dump($this->oldcopy);exit;
6272  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
6273  //var_dump($this->oldcopy->array_options[$key]); var_dump($this->array_options[$key]);
6274  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.
6275  $new_array_options[$key] = $this->array_options[$key]; // Value is kept
6276  } else {
6277  // var_dump($algo);
6278  $newvalue = dol_hash($this->array_options[$key], $algo);
6279  $new_array_options[$key] = $newvalue;
6280  }
6281  } else {
6282  $new_array_options[$key] = $this->array_options[$key]; // Value is kept
6283  }
6284  }
6285  } else // Common usage
6286  {
6287  $new_array_options[$key] = $this->array_options[$key];
6288  }
6289  break;
6290  case 'date':
6291  case 'datetime':
6292  // If data is a string instead of a timestamp, we convert it
6293  if (!is_numeric($this->array_options[$key]) || $this->array_options[$key] != intval($this->array_options[$key])) {
6294  $this->array_options[$key] = strtotime($this->array_options[$key]);
6295  }
6296  $new_array_options[$key] = $this->db->idate($this->array_options[$key]);
6297  break;
6298  case 'link':
6299  $param_list = array_keys($attributeParam['options']);
6300  // 0 : ObjectName
6301  // 1 : classPath
6302  $InfoFieldList = explode(":", $param_list[0]);
6303  dol_include_once($InfoFieldList[1]);
6304  if ($InfoFieldList[0] && class_exists($InfoFieldList[0])) {
6305  if ($value == '-1') { // -1 is key for no defined in combo list of objects
6306  $new_array_options[$key] = '';
6307  } elseif ($value) {
6308  $object = new $InfoFieldList[0]($this->db);
6309  if (is_numeric($value)) {
6310  $res = $object->fetch($value); // Common case
6311  } else {
6312  $res = $object->fetch('', $value); // For compatibility
6313  }
6314 
6315  if ($res > 0) {
6316  $new_array_options[$key] = $object->id;
6317  } else {
6318  $this->error = "Id/Ref '".$value."' for object '".$object->element."' not found";
6319  $this->db->rollback();
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  } else {
6467  $new_array_languages[$key] = $value;
6468  }
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  /*
6645  case 'link':
6646  $param_list = array_keys($attributeParam['options']);
6647  // 0 : ObjectName
6648  // 1 : classPath
6649  $InfoFieldList = explode(":", $param_list[0]);
6650  dol_include_once($InfoFieldList[1]);
6651  if ($InfoFieldList[0] && class_exists($InfoFieldList[0]))
6652  {
6653  if ($value == '-1') // -1 is key for no defined in combo list of objects
6654  {
6655  $new_array_options[$key] = '';
6656  } elseif ($value) {
6657  $object = new $InfoFieldList[0]($this->db);
6658  if (is_numeric($value)) $res = $object->fetch($value); // Common case
6659  else $res = $object->fetch('', $value); // For compatibility
6660 
6661  if ($res > 0) $new_array_options[$key] = $object->id;
6662  else {
6663  $this->error = "Id/Ref '".$value."' for object '".$object->element."' not found";
6664  $this->db->rollback();
6665  return -1;
6666  }
6667  }
6668  } else {
6669  dol_syslog('Error bad setup of extrafield', LOG_WARNING);
6670  }
6671  break;
6672  */
6673  }
6674 
6675  $this->db->begin();
6676 
6677  $linealreadyfound = 0;
6678 
6679  // 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)
6680  $sql = "SELECT COUNT(rowid) as nb FROM ".$this->db->prefix().$this->table_element."_extrafields WHERE fk_object = ".((int) $this->id);
6681  $resql = $this->db->query($sql);
6682  if ($resql) {
6683  $tmpobj = $this->db->fetch_object($resql);
6684  if ($tmpobj) {
6685  $linealreadyfound = $tmpobj->nb;
6686  }
6687  }
6688 
6689  if ($linealreadyfound) {
6690  if ($this->array_options["options_".$key] === null) {
6691  $sql = "UPDATE ".$this->db->prefix().$this->table_element."_extrafields SET ".$key." = null";
6692  } else {
6693  $sql = "UPDATE ".$this->db->prefix().$this->table_element."_extrafields SET ".$key." = '".$this->db->escape($this->array_options["options_".$key])."'";
6694  }
6695  $sql .= " WHERE fk_object = ".((int) $this->id);
6696  } else {
6697  $result = $this->insertExtraFields('', $user);
6698  if ($result < 0) {
6699  $error++;
6700  }
6701  }
6702 
6703  $resql = $this->db->query($sql);
6704  if (!$resql) {
6705  $error++;
6706  $this->error = $this->db->lasterror();
6707  }
6708  if (!$error && $trigger) {
6709  // Call trigger
6710  $this->context = array('extrafieldupdate'=>1);
6711  $result = $this->call_trigger($trigger, $userused);
6712  if ($result < 0) {
6713  $error++;
6714  }
6715  // End call trigger
6716  }
6717 
6718  if ($error) {
6719  dol_syslog(__METHOD__.$this->error, LOG_ERR);
6720  $this->db->rollback();
6721  return -1;
6722  } else {
6723  $this->db->commit();
6724  return 1;
6725  }
6726  } else {
6727  return 0;
6728  }
6729  }
6730 
6741  public function updateExtraLanguages($key, $trigger = null, $userused = null)
6742  {
6743  global $conf, $langs, $user;
6744 
6745  if (empty($userused)) {
6746  $userused = $user;
6747  }
6748 
6749  $error = 0;
6750 
6751  if (!empty($conf->global->MAIN_EXTRALANGUAGES_DISABLED)) {
6752  return 0; // For avoid conflicts if trigger used
6753  }
6754 
6755  return 0;
6756  }
6757 
6758 
6773  public function showInputField($val, $key, $value, $moreparam = '', $keysuffix = '', $keyprefix = '', $morecss = 0, $nonewbutton = 0)
6774  {
6775  global $conf, $langs, $form;
6776 
6777  if (!is_object($form)) {
6778  require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
6779  $form = new Form($this->db);
6780  }
6781 
6782  if (!empty($this->fields)) {
6783  $val = $this->fields[$key];
6784  }
6785 
6786  // Validation tests and output
6787  $fieldValidationErrorMsg = '';
6788  $validationClass = '';
6789  $fieldValidationErrorMsg = $this->getFieldError($key);
6790  if (!empty($fieldValidationErrorMsg)) {
6791  $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
6792  } else {
6793  $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
6794  }
6795 
6796  $out = '';
6797  $type = '';
6798  $isDependList = 0;
6799  $param = array();
6800  $param['options'] = array();
6801  $reg = array();
6802  $size = !empty($this->fields[$key]['size']) ? $this->fields[$key]['size'] : 0;
6803  // Because we work on extrafields
6804  if (preg_match('/^(integer|link):(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
6805  $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4].':'.$reg[5] => 'N');
6806  $type = 'link';
6807  } elseif (preg_match('/^(integer|link):(.*):(.*):(.*)/i', $val['type'], $reg)) {
6808  $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4] => 'N');
6809  $type = 'link';
6810  } elseif (preg_match('/^(integer|link):(.*):(.*)/i', $val['type'], $reg)) {
6811  $param['options'] = array($reg[2].':'.$reg[3] => 'N');
6812  $type = 'link';
6813  } elseif (preg_match('/^(sellist):(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
6814  $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4].':'.$reg[5] => 'N');
6815  $type = 'sellist';
6816  } elseif (preg_match('/^(sellist):(.*):(.*):(.*)/i', $val['type'], $reg)) {
6817  $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4] => 'N');
6818  $type = 'sellist';
6819  } elseif (preg_match('/^(sellist):(.*):(.*)/i', $val['type'], $reg)) {
6820  $param['options'] = array($reg[2].':'.$reg[3] => 'N');
6821  $type = 'sellist';
6822  } elseif (preg_match('/^chkbxlst:(.*)/i', $val['type'], $reg)) {
6823  $param['options'] = array($reg[1] => 'N');
6824  $type = 'chkbxlst';
6825  } elseif (preg_match('/varchar\‍((\d+)\‍)/', $val['type'], $reg)) {
6826  $param['options'] = array();
6827  $type = 'varchar';
6828  $size = $reg[1];
6829  } elseif (preg_match('/varchar/', $val['type'])) {
6830  $param['options'] = array();
6831  $type = 'varchar';
6832  } else {
6833  $param['options'] = array();
6834  $type = $this->fields[$key]['type'];
6835  }
6836 
6837  // Special case that force options and type ($type can be integer, varchar, ...)
6838  if (!empty($this->fields[$key]['arrayofkeyval']) && is_array($this->fields[$key]['arrayofkeyval'])) {
6839  $param['options'] = $this->fields[$key]['arrayofkeyval'];
6840  $type = 'select';
6841  }
6842 
6843  $label = $this->fields[$key]['label'];
6844  //$elementtype=$this->fields[$key]['elementtype']; // Seems not used
6845  $default = (!empty($this->fields[$key]['default']) ? $this->fields[$key]['default'] : '');
6846  $computed = (!empty($this->fields[$key]['computed']) ? $this->fields[$key]['computed'] : '');
6847  $unique = (!empty($this->fields[$key]['unique']) ? $this->fields[$key]['unique'] : 0);
6848  $required = (!empty($this->fields[$key]['required']) ? $this->fields[$key]['required'] : 0);
6849  $autofocusoncreate = (!empty($this->fields[$key]['autofocusoncreate']) ? $this->fields[$key]['autofocusoncreate'] : 0);
6850 
6851  $langfile = (!empty($this->fields[$key]['langfile']) ? $this->fields[$key]['langfile'] : '');
6852  $list = (!empty($this->fields[$key]['list']) ? $this->fields[$key]['list'] : 0);
6853  $hidden = (in_array(abs($this->fields[$key]['visible']), array(0, 2)) ? 1 : 0);
6854 
6855  $objectid = $this->id;
6856 
6857  if ($computed) {
6858  if (!preg_match('/^search_/', $keyprefix)) {
6859  return '<span class="opacitymedium">'.$langs->trans("AutomaticallyCalculated").'</span>';
6860  } else {
6861  return '';
6862  }
6863  }
6864 
6865  // Set value of $morecss. For this, we use in priority showsize from parameters, then $val['css'] then autodefine
6866  if (empty($morecss) && !empty($val['css'])) {
6867  $morecss = $val['css'];
6868  } elseif (empty($morecss)) {
6869  if ($type == 'date') {
6870  $morecss = 'minwidth100imp';
6871  } elseif ($type == 'datetime' || $type == 'link') { // link means an foreign key to another primary id
6872  $morecss = 'minwidth200imp';
6873  } elseif (in_array($type, array('int', 'integer', 'price')) || preg_match('/^double(\‍([0-9],[0-9]\‍)){0,1}/', $type)) {
6874  $morecss = 'maxwidth75';
6875  } elseif ($type == 'url') {
6876  $morecss = 'minwidth400';
6877  } elseif ($type == 'boolean') {
6878  $morecss = '';
6879  } else {
6880  if (round($size) < 12) {
6881  $morecss = 'minwidth100';
6882  } elseif (round($size) <= 48) {
6883  $morecss = 'minwidth200';
6884  } else {
6885  $morecss = 'minwidth400';
6886  }
6887  }
6888  }
6889 
6890  // Add validation state class
6891  if (!empty($validationClass)) {
6892  $morecss.= $validationClass;
6893  }
6894 
6895  if (in_array($type, array('date'))) {
6896  $tmp = explode(',', $size);
6897  $newsize = $tmp[0];
6898  $showtime = 0;
6899 
6900  // Do not show current date when field not required (see selectDate() method)
6901  if (!$required && $value == '') {
6902  $value = '-1';
6903  }
6904 
6905  // TODO Must also support $moreparam
6906  $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required, '', 1, (($keyprefix != 'search_' && $keyprefix != 'search_options_') ? 1 : 0), 0, 1);
6907  } elseif (in_array($type, array('datetime'))) {
6908  $tmp = explode(',', $size);
6909  $newsize = $tmp[0];
6910  $showtime = 1;
6911 
6912  // Do not show current date when field not required (see selectDate() method)
6913  if (!$required && $value == '') $value = '-1';
6914 
6915  // TODO Must also support $moreparam
6916  $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required, '', 1, (($keyprefix != 'search_' && $keyprefix != 'search_options_') ? 1 : 0), 0, 1, '', '', '', 1, '', '', 'tzuserrel');
6917  } elseif (in_array($type, array('duration'))) {
6918  $out = $form->select_duration($keyprefix.$key.$keysuffix, $value, 0, 'text', 0, 1);
6919  } elseif (in_array($type, array('int', 'integer'))) {
6920  $tmp = explode(',', $size);
6921  $newsize = $tmp[0];
6922  $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' : '').'>';
6923  } elseif (in_array($type, array('real'))) {
6924  $out = '<input type="text" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'"'.($moreparam ? $moreparam : '').($autofocusoncreate ? ' autofocus' : '').'>';
6925  } elseif (preg_match('/varchar/', $type)) {
6926  $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' : '').'>';
6927  } elseif (in_array($type, array('email', 'mail', 'phone', 'url', 'ip'))) {
6928  $out = '<input type="text" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').($autofocusoncreate ? ' autofocus' : '').'>';
6929  } elseif (preg_match('/^text/', $type)) {
6930  if (!preg_match('/search_/', $keyprefix)) { // If keyprefix is search_ or search_options_, we must just use a simple text field
6931  require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
6932  $doleditor = new DolEditor($keyprefix.$key.$keysuffix, $value, '', 200, 'dolibarr_notes', 'In', false, false, false, ROWS_5, '90%');
6933  $out = $doleditor->Create(1);
6934  } else {
6935  $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').'>';
6936  }
6937  } elseif (preg_match('/^html/', $type)) {
6938  if (!preg_match('/search_/', $keyprefix)) { // If keyprefix is search_ or search_options_, we must just use a simple text field
6939  require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
6940  $doleditor = new DolEditor($keyprefix.$key.$keysuffix, $value, '', 200, 'dolibarr_notes', 'In', false, false, isModEnabled('fckeditor') && $conf->global->FCKEDITOR_ENABLE_SOCIETE, ROWS_5, '90%');
6941  $out = $doleditor->Create(1, '', true, '', '', $moreparam, $morecss);
6942  } else {
6943  $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').'>';
6944  }
6945  } elseif ($type == 'boolean') {
6946  $checked = '';
6947  if (!empty($value)) {
6948  $checked = ' checked value="1" ';
6949  } else {
6950  $checked = ' value="1" ';
6951  }
6952  $out = '<input type="checkbox" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.$checked.' '.($moreparam ? $moreparam : '').'>';
6953  } elseif ($type == 'price') {
6954  if (!empty($value)) { // $value in memory is a php numeric, we format it into user number format.
6955  $value = price($value);
6956  }
6957  $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'> '.$langs->getCurrencySymbol($conf->currency);
6958  } elseif (preg_match('/^double(\‍([0-9],[0-9]\‍)){0,1}/', $type)) {
6959  if (!empty($value)) { // $value in memory is a php numeric, we format it into user number format.
6960  $value = price($value);
6961  }
6962  $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'> ';
6963  } elseif ($type == 'select') {
6964  $out = '';
6965  if (!empty($conf->use_javascript_ajax) && empty($conf->global->MAIN_EXTRAFIELDS_DISABLE_SELECT2)) {
6966  include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
6967  $out .= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
6968  }
6969 
6970  $out .= '<select class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '').'>';
6971  if ((!isset($this->fields[$key]['default'])) || ($this->fields[$key]['notnull'] != 1)) {
6972  $out .= '<option value="0">&nbsp;</option>';
6973  }
6974  foreach ($param['options'] as $keyb => $valb) {
6975  if ((string) $keyb == '') {
6976  continue;
6977  }
6978  if (strpos($valb, "|") !== false) {
6979  list($valb, $parent) = explode('|', $valb);
6980  }
6981  $out .= '<option value="'.$keyb.'"';
6982  $out .= (((string) $value == (string) $keyb) ? ' selected' : '');
6983  $out .= (!empty($parent) ? ' parent="'.$parent.'"' : '');
6984  $out .= '>'.$valb.'</option>';
6985  }
6986  $out .= '</select>';
6987  } elseif ($type == 'sellist') {
6988  $out = '';
6989  if (!empty($conf->use_javascript_ajax) && empty($conf->global->MAIN_EXTRAFIELDS_DISABLE_SELECT2)) {
6990  include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
6991  $out .= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
6992  }
6993 
6994  $out .= '<select class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '').'>';
6995  if (is_array($param['options'])) {
6996  $param_list = array_keys($param['options']);
6997  $InfoFieldList = explode(":", $param_list[0]);
6998  $parentName = '';
6999  $parentField = '';
7000  // 0 : tableName
7001  // 1 : label field name
7002  // 2 : key fields name (if differ of rowid)
7003  // 3 : key field parent (for dependent lists)
7004  // 4 : where clause filter on column or table extrafield, syntax field='value' or extra.field=value
7005  // 5 : id category type
7006  // 6 : ids categories list separated by comma for category root
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  $filter_categorie = false;
7022  if (count($InfoFieldList) > 5) {
7023  if ($InfoFieldList[0] == 'categorie') {
7024  $filter_categorie = true;
7025  }
7026  }
7027 
7028  if ($filter_categorie === false) {
7029  $fields_label = explode('|', $InfoFieldList[1]);
7030  if (is_array($fields_label)) {
7031  $keyList .= ', ';
7032  $keyList .= implode(', ', $fields_label);
7033  }
7034 
7035  $sqlwhere = '';
7036  $sql = "SELECT " . $keyList;
7037  $sql .= " FROM " . $this->db->prefix() . $InfoFieldList[0];
7038  if (!empty($InfoFieldList[4])) {
7039  // can use SELECT request
7040  if (strpos($InfoFieldList[4], '$SEL$') !== false) {
7041  $InfoFieldList[4] = str_replace('$SEL$', 'SELECT', $InfoFieldList[4]);
7042  }
7043 
7044  // current object id can be use into filter
7045  if (strpos($InfoFieldList[4], '$ID$') !== false && !empty($objectid)) {
7046  $InfoFieldList[4] = str_replace('$ID$', $objectid, $InfoFieldList[4]);
7047  } else {
7048  $InfoFieldList[4] = str_replace('$ID$', '0', $InfoFieldList[4]);
7049  }
7050 
7051  //We have to join on extrafield table
7052  if (strpos($InfoFieldList[4], 'extra') !== false) {
7053  $sql .= " as main, " . $this->db->prefix() . $InfoFieldList[0] . "_extrafields as extra";
7054  $sqlwhere .= " WHERE extra.fk_object=main." . $InfoFieldList[2] . " AND " . $InfoFieldList[4];
7055  } else {
7056  $sqlwhere .= " WHERE " . $InfoFieldList[4];
7057  }
7058  } else {
7059  $sqlwhere .= ' WHERE 1=1';
7060  }
7061  // Some tables may have field, some other not. For the moment we disable it.
7062  if (in_array($InfoFieldList[0], array('tablewithentity'))) {
7063  $sqlwhere .= " AND entity = " . ((int) $conf->entity);
7064  }
7065  $sql .= $sqlwhere;
7066  //print $sql;
7067 
7068  $sql .= ' ORDER BY ' . implode(', ', $fields_label);
7069 
7070  dol_syslog(get_class($this) . '::showInputField type=sellist', LOG_DEBUG);
7071  $resql = $this->db->query($sql);
7072  if ($resql) {
7073  $out .= '<option value="0">&nbsp;</option>';
7074  $num = $this->db->num_rows($resql);
7075  $i = 0;
7076  while ($i < $num) {
7077  $labeltoshow = '';
7078  $obj = $this->db->fetch_object($resql);
7079 
7080  // Several field into label (eq table:code|libelle:rowid)
7081  $notrans = false;
7082  $fields_label = explode('|', $InfoFieldList[1]);
7083  if (count($fields_label) > 1) {
7084  $notrans = true;
7085  foreach ($fields_label as $field_toshow) {
7086  $labeltoshow .= $obj->$field_toshow . ' ';
7087  }
7088  } else {
7089  $labeltoshow = $obj->{$InfoFieldList[1]};
7090  }
7091  $labeltoshow = dol_trunc($labeltoshow, 45);
7092 
7093  if ($value == $obj->rowid) {
7094  foreach ($fields_label as $field_toshow) {
7095  $translabel = $langs->trans($obj->$field_toshow);
7096  if ($translabel != $obj->$field_toshow) {
7097  $labeltoshow = dol_trunc($translabel) . ' ';
7098  } else {
7099  $labeltoshow = dol_trunc($obj->$field_toshow) . ' ';
7100  }
7101  }
7102  $out .= '<option value="' . $obj->rowid . '" selected>' . $labeltoshow . '</option>';
7103  } else {
7104  if (!$notrans) {
7105  $translabel = $langs->trans($obj->{$InfoFieldList[1]});
7106  if ($translabel != $obj->{$InfoFieldList[1]}) {
7107  $labeltoshow = dol_trunc($translabel, 18);
7108  } else {
7109  $labeltoshow = dol_trunc($obj->{$InfoFieldList[1]});
7110  }
7111  }
7112  if (empty($labeltoshow)) {
7113  $labeltoshow = '(not defined)';
7114  }
7115  if ($value == $obj->rowid) {
7116  $out .= '<option value="' . $obj->rowid . '" selected>' . $labeltoshow . '</option>';
7117  }
7118 
7119  if (!empty($InfoFieldList[3]) && $parentField) {
7120  $parent = $parentName . ':' . $obj->{$parentField};
7121  $isDependList = 1;
7122  }
7123 
7124  $out .= '<option value="' . $obj->rowid . '"';
7125  $out .= ($value == $obj->rowid ? ' selected' : '');
7126  $out .= (!empty($parent) ? ' parent="' . $parent . '"' : '');
7127  $out .= '>' . $labeltoshow . '</option>';
7128  }
7129 
7130  $i++;
7131  }
7132  $this->db->free($resql);
7133  } else {
7134  print 'Error in request ' . $sql . ' ' . $this->db->lasterror() . '. Check setup of extra parameters.<br>';
7135  }
7136  } else {
7137  require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
7138  $data = $form->select_all_categories(Categorie::$MAP_ID_TO_CODE[$InfoFieldList[5]], '', 'parent', 64, $InfoFieldList[6], 1, 1);
7139  $out .= '<option value="0">&nbsp;</option>';
7140  foreach ($data as $data_key => $data_value) {
7141  $out .= '<option value="' . $data_key . '"';
7142  $out .= ($value == $data_key ? ' selected' : '');
7143  $out .= '>' . $data_value . '</option>';
7144  }
7145  }
7146  }
7147  $out .= '</select>';
7148  } elseif ($type == 'checkbox') {
7149  $value_arr = explode(',', $value);
7150  $out = $form->multiselectarray($keyprefix.$key.$keysuffix, (empty($param['options']) ?null:$param['options']), $value_arr, '', 0, $morecss, 0, '100%');
7151  } elseif ($type == 'radio') {
7152  $out = '';
7153  foreach ($param['options'] as $keyopt => $valopt) {
7154  $out .= '<input class="flat '.$morecss.'" type="radio" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '');
7155  $out .= ' value="'.$keyopt.'"';
7156  $out .= ' id="'.$keyprefix.$key.$keysuffix.'_'.$keyopt.'"';
7157  $out .= ($value == $keyopt ? 'checked' : '');
7158  $out .= '/><label for="'.$keyprefix.$key.$keysuffix.'_'.$keyopt.'">'.$valopt.'</label><br>';
7159  }
7160  } elseif ($type == 'chkbxlst') {
7161  if (is_array($value)) {
7162  $value_arr = $value;
7163  } else {
7164  $value_arr = explode(',', $value);
7165  }
7166 
7167  if (is_array($param['options'])) {
7168  $param_list = array_keys($param['options']);
7169  $InfoFieldList = explode(":", $param_list[0]);
7170  $parentName = '';
7171  $parentField = '';
7172  // 0 : tableName
7173  // 1 : label field name
7174  // 2 : key fields name (if differ of rowid)
7175  // 3 : key field parent (for dependent lists)
7176  // 4 : where clause filter on column or table extrafield, syntax field='value' or extra.field=value
7177  // 5 : id category type
7178  // 6 : ids categories list separated by comma for category root
7179  $keyList = (empty($InfoFieldList[2]) ? 'rowid' : $InfoFieldList[2].' as rowid');
7180 
7181  if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
7182  list ($parentName, $parentField) = explode('|', $InfoFieldList[3]);
7183  $keyList .= ', '.$parentField;
7184  }
7185  if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
7186  if (strpos($InfoFieldList[4], 'extra.') !== false) {
7187  $keyList = 'main.'.$InfoFieldList[2].' as rowid';
7188  } else {
7189  $keyList = $InfoFieldList[2].' as rowid';
7190  }
7191  }
7192 
7193  $filter_categorie = false;
7194  if (count($InfoFieldList) > 5) {
7195  if ($InfoFieldList[0] == 'categorie') {
7196  $filter_categorie = true;
7197  }
7198  }
7199 
7200  if ($filter_categorie === false) {
7201  $fields_label = explode('|', $InfoFieldList[1]);
7202  if (is_array($fields_label)) {
7203  $keyList .= ', ';
7204  $keyList .= implode(', ', $fields_label);
7205  }
7206 
7207  $sqlwhere = '';
7208  $sql = "SELECT " . $keyList;
7209  $sql .= ' FROM ' . $this->db->prefix() . $InfoFieldList[0];
7210  if (!empty($InfoFieldList[4])) {
7211  // can use SELECT request
7212  if (strpos($InfoFieldList[4], '$SEL$') !== false) {
7213  $InfoFieldList[4] = str_replace('$SEL$', 'SELECT', $InfoFieldList[4]);
7214  }
7215 
7216  // current object id can be use into filter
7217  if (strpos($InfoFieldList[4], '$ID$') !== false && !empty($objectid)) {
7218  $InfoFieldList[4] = str_replace('$ID$', $objectid, $InfoFieldList[4]);
7219  } else {
7220  $InfoFieldList[4] = str_replace('$ID$', '0', $InfoFieldList[4]);
7221  }
7222 
7223  // We have to join on extrafield table
7224  if (strpos($InfoFieldList[4], 'extra') !== false) {
7225  $sql .= ' as main, ' . $this->db->prefix() . $InfoFieldList[0] . '_extrafields as extra';
7226  $sqlwhere .= " WHERE extra.fk_object=main." . $InfoFieldList[2] . " AND " . $InfoFieldList[4];
7227  } else {
7228  $sqlwhere .= " WHERE " . $InfoFieldList[4];
7229  }
7230  } else {
7231  $sqlwhere .= ' WHERE 1=1';
7232  }
7233  // Some tables may have field, some other not. For the moment we disable it.
7234  if (in_array($InfoFieldList[0], array('tablewithentity'))) {
7235  $sqlwhere .= " AND entity = " . ((int) $conf->entity);
7236  }
7237  // $sql.=preg_replace('/^ AND /','',$sqlwhere);
7238  // print $sql;
7239 
7240  $sql .= $sqlwhere;
7241  dol_syslog(get_class($this) . '::showInputField type=chkbxlst', LOG_DEBUG);
7242  $resql = $this->db->query($sql);
7243  if ($resql) {
7244  $num = $this->db->num_rows($resql);
7245  $i = 0;
7246 
7247  $data = array();
7248 
7249  while ($i < $num) {
7250  $labeltoshow = '';
7251  $obj = $this->db->fetch_object($resql);
7252 
7253  $notrans = false;
7254  // Several field into label (eq table:code|libelle:rowid)
7255  $fields_label = explode('|', $InfoFieldList[1]);
7256  if (count($fields_label) > 1) {
7257  $notrans = true;
7258  foreach ($fields_label as $field_toshow) {
7259  $labeltoshow .= $obj->$field_toshow . ' ';
7260  }
7261  } else {
7262  $labeltoshow = $obj->{$InfoFieldList[1]};
7263  }
7264  $labeltoshow = dol_trunc($labeltoshow, 45);
7265 
7266  if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
7267  foreach ($fields_label as $field_toshow) {
7268  $translabel = $langs->trans($obj->$field_toshow);
7269  if ($translabel != $obj->$field_toshow) {
7270  $labeltoshow = dol_trunc($translabel, 18) . ' ';
7271  } else {
7272  $labeltoshow = dol_trunc($obj->$field_toshow, 18) . ' ';
7273  }
7274  }
7275 
7276  $data[$obj->rowid] = $labeltoshow;
7277  } else {
7278  if (!$notrans) {
7279  $translabel = $langs->trans($obj->{$InfoFieldList[1]});
7280  if ($translabel != $obj->{$InfoFieldList[1]}) {
7281  $labeltoshow = dol_trunc($translabel, 18);
7282  } else {
7283  $labeltoshow = dol_trunc($obj->{$InfoFieldList[1]}, 18);
7284  }
7285  }
7286  if (empty($labeltoshow)) {
7287  $labeltoshow = '(not defined)';
7288  }
7289 
7290  if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
7291  $data[$obj->rowid] = $labeltoshow;
7292  }
7293 
7294  if (!empty($InfoFieldList[3]) && $parentField) {
7295  $parent = $parentName . ':' . $obj->{$parentField};
7296  $isDependList = 1;
7297  }
7298 
7299  $data[$obj->rowid] = $labeltoshow;
7300  }
7301 
7302  $i++;
7303  }
7304  $this->db->free($resql);
7305 
7306  $out = $form->multiselectarray($keyprefix . $key . $keysuffix, $data, $value_arr, '', 0, $morecss, 0, '100%');
7307  } else {
7308  print 'Error in request ' . $sql . ' ' . $this->db->lasterror() . '. Check setup of extra parameters.<br>';
7309  }
7310  } else {
7311  require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
7312  $data = $form->select_all_categories(Categorie::$MAP_ID_TO_CODE[$InfoFieldList[5]], '', 'parent', 64, $InfoFieldList[6], 1, 1);
7313  $out = $form->multiselectarray($keyprefix . $key . $keysuffix, $data, $value_arr, '', 0, $morecss, 0, '100%');
7314  }
7315  }
7316  } elseif ($type == 'link') {
7317  $param_list = array_keys($param['options']); // $param_list='ObjectName:classPath[:AddCreateButtonOrNot[:Filter[:Sortfield]]]'
7318  $param_list_array = explode(':', $param_list[0]);
7319  $showempty = (($required && $default != '') ? 0 : 1);
7320 
7321  if (!preg_match('/search_/', $keyprefix)) {
7322  if (!empty($param_list_array[2])) { // If the entry into $fields is set to add a create button
7323  if (!empty($this->fields[$key]['picto'])) {
7324  $morecss .= ' widthcentpercentminusxx';
7325  } else {
7326  $morecss .= ' widthcentpercentminusx';
7327  }
7328  } else {
7329  if (!empty($this->fields[$key]['picto'])) {
7330  $morecss .= ' widthcentpercentminusx';
7331  }
7332  }
7333  }
7334 
7335  $out = $form->selectForForms($param_list[0], $keyprefix.$key.$keysuffix, $value, $showempty, '', '', $morecss, $moreparam, 0, empty($val['disabled']) ? 0 : 1);
7336 
7337  if (!empty($param_list_array[2])) { // If the entry into $fields is set to add a create button
7338  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".
7339  list($class, $classfile) = explode(':', $param_list[0]);
7340  if (file_exists(dol_buildpath(dirname(dirname($classfile)).'/card.php'))) {
7341  $url_path = dol_buildpath(dirname(dirname($classfile)).'/card.php', 1);
7342  } else {
7343  $url_path = dol_buildpath(dirname(dirname($classfile)).'/'.strtolower($class).'_card.php', 1);
7344  }
7345  $paramforthenewlink = '';
7346  $paramforthenewlink .= (GETPOSTISSET('action') ? '&action='.GETPOST('action', 'aZ09') : '');
7347  $paramforthenewlink .= (GETPOSTISSET('id') ? '&id='.GETPOST('id', 'int') : '');
7348  $paramforthenewlink .= (GETPOSTISSET('origin') ? '&origin='.GETPOST('origin', 'aZ09') : '');
7349  $paramforthenewlink .= (GETPOSTISSET('originid') ? '&originid='.GETPOST('originid', 'int') : '');
7350  $paramforthenewlink .= '&fk_'.strtolower($class).'=--IDFORBACKTOPAGE--';
7351  // TODO Add Javascript code to add input fields already filled into $paramforthenewlink so we won't loose them when going back to main page
7352  $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>';
7353  }
7354  }
7355  } elseif ($type == 'password') {
7356  // If prefix is 'search_', field is used as a filter, we use a common text field.
7357  $out = '<input type="'.($keyprefix == 'search_' ? 'text' : 'password').'" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'>';
7358  } elseif ($type == 'array') {
7359  $newval = $val;
7360  $newval['type'] = 'varchar(256)';
7361 
7362  $out = '';
7363  if (!empty($value)) {
7364  foreach ($value as $option) {
7365  $out .= '<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
7366  $out .= $this->showInputField($newval, $keyprefix.$key.$keysuffix.'[]', $option, $moreparam, '', '', $morecss).'<br></span>';
7367  }
7368  }
7369  $out .= '<a id="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_add" href="javascript:;"><span class="fa fa-plus-circle valignmiddle"></span></a>';
7370 
7371  $newInput = '<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
7372  $newInput .= $this->showInputField($newval, $keyprefix.$key.$keysuffix.'[]', '', $moreparam, '', '', $morecss).'<br></span>';
7373 
7374  if (!empty($conf->use_javascript_ajax)) {
7375  $out .= '
7376  <script>
7377  $(document).ready(function() {
7378  $("a#'.dol_escape_js($keyprefix.$key.$keysuffix).'_add").click(function() {
7379  $("'.dol_escape_js($newInput).'").insertBefore(this);
7380  });
7381 
7382  $(document).on("click", "a.'.dol_escape_js($keyprefix.$key.$keysuffix).'_del", function() {
7383  $(this).parent().remove();
7384  });
7385  });
7386  </script>';
7387  }
7388  }
7389  if (!empty($hidden)) {
7390  $out = '<input type="hidden" value="'.$value.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'"/>';
7391  }
7392 
7393  if ($isDependList==1) {
7394  $out .= $this->getJSListDependancies('_common');
7395  }
7396  /* Add comments
7397  if ($type == 'date') $out.=' (YYYY-MM-DD)';
7398  elseif ($type == 'datetime') $out.=' (YYYY-MM-DD HH:MM:SS)';
7399  */
7400 
7401  // Display error message for field
7402  if (!empty($fieldValidationErrorMsg) && function_exists('getFieldErrorIcon')) {
7403  $out .= ' '.getFieldErrorIcon($fieldValidationErrorMsg);
7404  }
7405 
7406  return $out;
7407  }
7408 
7422  public function showOutputField($val, $key, $value, $moreparam = '', $keysuffix = '', $keyprefix = '', $morecss = '')
7423  {
7424  global $conf, $langs, $form;
7425 
7426  if (!is_object($form)) {
7427  require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
7428  $form = new Form($this->db);
7429  }
7430 
7431  $objectid = $this->id; // Not used ???
7432 
7433  $label = empty($val['label']) ? '' : $val['label'];
7434  $type = empty($val['type']) ? '' : $val['type'];
7435  $size = empty($val['css']) ? '' : $val['css'];
7436  $reg = array();
7437 
7438  // Convert var to be able to share same code than showOutputField of extrafields
7439  if (preg_match('/varchar\‍((\d+)\‍)/', $type, $reg)) {
7440  $type = 'varchar'; // convert varchar(xx) int varchar
7441  $size = $reg[1];
7442  } elseif (preg_match('/varchar/', $type)) {
7443  $type = 'varchar'; // convert varchar(xx) int varchar
7444  }
7445  if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
7446  $type = 'select';
7447  }
7448  if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) {
7449  $type = 'link';
7450  }
7451 
7452  $default = empty($val['default']) ? '' : $val['default'];
7453  $computed = empty($val['computed']) ? '' : $val['computed'];
7454  $unique = empty($val['unique']) ? '' : $val['unique'];
7455  $required = empty($val['required']) ? '' : $val['required'];
7456  $param = array();
7457  $param['options'] = array();
7458 
7459  if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
7460  $param['options'] = $val['arrayofkeyval'];
7461  }
7462  if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) {
7463  $type = 'link';
7464  $param['options'] = array($reg[1].':'.$reg[2]=>$reg[1].':'.$reg[2]);
7465  } elseif (preg_match('/^sellist:(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
7466  $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3].':'.$reg[4] => 'N');
7467  $type = 'sellist';
7468  } elseif (preg_match('/^sellist:(.*):(.*):(.*)/i', $val['type'], $reg)) {
7469  $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3] => 'N');
7470  $type = 'sellist';
7471  } elseif (preg_match('/^sellist:(.*):(.*)/i', $val['type'], $reg)) {
7472  $param['options'] = array($reg[1].':'.$reg[2] => 'N');
7473  $type = 'sellist';
7474  } elseif (preg_match('/^chkbxlst:(.*)/i', $val['type'], $reg)) {
7475  $param['options'] = array($reg[1] => 'N');
7476  $type = 'chkbxlst';
7477  }
7478 
7479  $langfile = empty($val['langfile']) ? '' : $val['langfile'];
7480  $list = (empty($val['list']) ? '' : $val['list']);
7481  $help = (empty($val['help']) ? '' : $val['help']);
7482  $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)
7483 
7484  if ($hidden) {
7485  return '';
7486  }
7487 
7488  // If field is a computed field, value must become result of compute
7489  if ($computed) {
7490  // Make the eval of compute string
7491  //var_dump($computed);
7492  $value = dol_eval($computed, 1, 0, '');
7493  }
7494 
7495  if (empty($morecss)) {
7496  if ($type == 'date') {
7497  $morecss = 'minwidth100imp';
7498  } elseif ($type == 'datetime' || $type == 'timestamp') {
7499  $morecss = 'minwidth200imp';
7500  } elseif (in_array($type, array('int', 'double', 'price'))) {
7501  $morecss = 'maxwidth75';
7502  } elseif ($type == 'url') {
7503  $morecss = 'minwidth400';
7504  } elseif ($type == 'boolean') {
7505  $morecss = '';
7506  } else {
7507  if (is_numeric($size) && round($size) < 12) {
7508  $morecss = 'minwidth100';
7509  } elseif (is_numeric($size) && round($size) <= 48) {
7510  $morecss = 'minwidth200';
7511  } else {
7512  $morecss = 'minwidth400';
7513  }
7514  }
7515  }
7516 
7517  // Format output value differently according to properties of field
7518  if (in_array($key, array('rowid', 'ref')) && method_exists($this, 'getNomUrl')) {
7519  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.
7520  $value = $this->getNomUrl(1, '', 0, '', 1);
7521  }
7522  } elseif ($key == 'status' && method_exists($this, 'getLibStatut')) {
7523  $value = $this->getLibStatut(3);
7524  } elseif ($type == 'date') {
7525  if (!empty($value)) {
7526  $value = dol_print_date($value, 'day'); // We suppose dates without time are always gmt (storage of course + output)
7527  } else {
7528  $value = '';
7529  }
7530  } elseif ($type == 'datetime' || $type == 'timestamp') {
7531  if (!empty($value)) {
7532  $value = dol_print_date($value, 'dayhour', 'tzuserrel');
7533  } else {
7534  $value = '';
7535  }
7536  } elseif ($type == 'duration') {
7537  include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
7538  if (!is_null($value) && $value !== '') {
7539  $value = convertSecondToTime($value, 'allhourmin');
7540  }
7541  } elseif ($type == 'double' || $type == 'real') {
7542  if (!is_null($value) && $value !== '') {
7543  $value = price($value);
7544  }
7545  } elseif ($type == 'boolean') {
7546  $checked = '';
7547  if (!empty($value)) {
7548  $checked = ' checked ';
7549  }
7550  $value = '<input type="checkbox" '.$checked.' '.($moreparam ? $moreparam : '').' readonly disabled>';
7551  } elseif ($type == 'mail' || $type == 'email') {
7552  $value = dol_print_email($value, 0, 0, 0, 64, 1, 1);
7553  } elseif ($type == 'url') {
7554  $value = dol_print_url($value, '_blank', 32, 1);
7555  } elseif ($type == 'phone') {
7556  $value = dol_print_phone($value, '', 0, 0, '', '&nbsp;', 'phone');
7557  } elseif ($type == 'ip') {
7558  $value = dol_print_ip($value, 0);
7559  } elseif ($type == 'price') {
7560  if (!is_null($value) && $value !== '') {
7561  $value = price($value, 0, $langs, 0, 0, -1, $conf->currency);
7562  }
7563  } elseif ($type == 'select') {
7564  $value = isset($param['options'][$value])?$param['options'][$value]:'';
7565  } elseif ($type == 'sellist') {
7566  $param_list = array_keys($param['options']);
7567  $InfoFieldList = explode(":", $param_list[0]);
7568 
7569  $selectkey = "rowid";
7570  $keyList = 'rowid';
7571 
7572  if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
7573  $selectkey = $InfoFieldList[2];
7574  $keyList = $InfoFieldList[2].' as rowid';
7575  }
7576 
7577  $fields_label = explode('|', $InfoFieldList[1]);
7578  if (is_array($fields_label)) {
7579  $keyList .= ', ';
7580  $keyList .= implode(', ', $fields_label);
7581  }
7582 
7583  $filter_categorie = false;
7584  if (count($InfoFieldList) > 5) {
7585  if ($InfoFieldList[0] == 'categorie') {
7586  $filter_categorie = true;
7587  }
7588  }
7589 
7590  $sql = "SELECT ".$keyList;
7591  $sql .= ' FROM '.$this->db->prefix().$InfoFieldList[0];
7592  if (strpos($InfoFieldList[4], 'extra') !== false) {
7593  $sql .= ' as main';
7594  }
7595  if ($selectkey == 'rowid' && empty($value)) {
7596  $sql .= " WHERE ".$selectkey." = 0";
7597  } elseif ($selectkey == 'rowid') {
7598  $sql .= " WHERE ".$selectkey." = ".((int) $value);
7599  } else {
7600  $sql .= " WHERE ".$selectkey." = '".$this->db->escape($value)."'";
7601  }
7602 
7603  //$sql.= ' AND entity = '.$conf->entity;
7604 
7605  dol_syslog(get_class($this).':showOutputField:$type=sellist', LOG_DEBUG);
7606  $resql = $this->db->query($sql);
7607  if ($resql) {
7608  if ($filter_categorie === false) {
7609  $value = ''; // value was used, so now we reste it to use it to build final output
7610  $numrows = $this->db->num_rows($resql);
7611  if ($numrows) {
7612  $obj = $this->db->fetch_object($resql);
7613 
7614  // Several field into label (eq table:code|libelle:rowid)
7615  $fields_label = explode('|', $InfoFieldList[1]);
7616 
7617  if (is_array($fields_label) && count($fields_label) > 1) {
7618  foreach ($fields_label as $field_toshow) {
7619  $translabel = '';
7620  if (!empty($obj->$field_toshow)) {
7621  $translabel = $langs->trans($obj->$field_toshow);
7622  }
7623  if ($translabel != $field_toshow) {
7624  $value .= dol_trunc($translabel, 18) . ' ';
7625  } else {
7626  $value .= $obj->$field_toshow . ' ';
7627  }
7628  }
7629  } else {
7630  $translabel = '';
7631  if (!empty($obj->{$InfoFieldList[1]})) {
7632  $translabel = $langs->trans($obj->{$InfoFieldList[1]});
7633  }
7634  if ($translabel != $obj->{$InfoFieldList[1]}) {
7635  $value = dol_trunc($translabel, 18);
7636  } else {
7637  $value = $obj->{$InfoFieldList[1]};
7638  }
7639  }
7640  }
7641  } else {
7642  require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
7643 
7644  $toprint = array();
7645  $obj = $this->db->fetch_object($resql);
7646  $c = new Categorie($this->db);
7647  $c->fetch($obj->rowid);
7648  $ways = $c->print_all_ways(); // $ways[0] = "ccc2 >> ccc2a >> ccc2a1" with html formatted text
7649  foreach ($ways as $way) {
7650  $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories"' . ($c->color ? ' style="background: #' . $c->color . ';"' : ' style="background: #aaa"') . '>' . img_object('', 'category') . ' ' . $way . '</li>';
7651  }
7652  $value = '<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
7653  }
7654  } else {
7655  dol_syslog(get_class($this).'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
7656  }
7657  } elseif ($type == 'radio') {
7658  $value = $param['options'][$value];
7659  } elseif ($type == 'checkbox') {
7660  $value_arr = explode(',', $value);
7661  $value = '';
7662  if (is_array($value_arr) && count($value_arr) > 0) {
7663  $toprint = array();
7664  foreach ($value_arr as $keyval => $valueval) {
7665  $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">'.$param['options'][$valueval].'</li>';
7666  }
7667  $value = '<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
7668  }
7669  } elseif ($type == 'chkbxlst') {
7670  $value_arr = explode(',', $value);
7671 
7672  $param_list = array_keys($param['options']);
7673  $InfoFieldList = explode(":", $param_list[0]);
7674 
7675  $selectkey = "rowid";
7676  $keyList = 'rowid';
7677 
7678  if (count($InfoFieldList) >= 3) {
7679  $selectkey = $InfoFieldList[2];
7680  $keyList = $InfoFieldList[2].' as rowid';
7681  }
7682 
7683  $fields_label = explode('|', $InfoFieldList[1]);
7684  if (is_array($fields_label)) {
7685  $keyList .= ', ';
7686  $keyList .= implode(', ', $fields_label);
7687  }
7688 
7689  $filter_categorie = false;
7690  if (count($InfoFieldList) > 5) {
7691  if ($InfoFieldList[0] == 'categorie') {
7692  $filter_categorie = true;
7693  }
7694  }
7695 
7696  $sql = "SELECT ".$keyList;
7697  $sql .= ' FROM '.$this->db->prefix().$InfoFieldList[0];
7698  if (strpos($InfoFieldList[4], 'extra') !== false) {
7699  $sql .= ' as main';
7700  }
7701  // $sql.= " WHERE ".$selectkey."='".$this->db->escape($value)."'";
7702  // $sql.= ' AND entity = '.$conf->entity;
7703 
7704  dol_syslog(get_class($this).':showOutputField:$type=chkbxlst', LOG_DEBUG);
7705  $resql = $this->db->query($sql);
7706  if ($resql) {
7707  if ($filter_categorie === false) {
7708  $value = ''; // value was used, so now we reste it to use it to build final output
7709  $toprint = array();
7710  while ($obj = $this->db->fetch_object($resql)) {
7711  // Several field into label (eq table:code|libelle:rowid)
7712  $fields_label = explode('|', $InfoFieldList[1]);
7713  if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
7714  if (is_array($fields_label) && count($fields_label) > 1) {
7715  foreach ($fields_label as $field_toshow) {
7716  $translabel = '';
7717  if (!empty($obj->$field_toshow)) {
7718  $translabel = $langs->trans($obj->$field_toshow);
7719  }
7720  if ($translabel != $field_toshow) {
7721  $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' . dol_trunc($translabel, 18) . '</li>';
7722  } else {
7723  $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' . $obj->$field_toshow . '</li>';
7724  }
7725  }
7726  } else {
7727  $translabel = '';
7728  if (!empty($obj->{$InfoFieldList[1]})) {
7729  $translabel = $langs->trans($obj->{$InfoFieldList[1]});
7730  }
7731  if ($translabel != $obj->{$InfoFieldList[1]}) {
7732  $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' . dol_trunc($translabel, 18) . '</li>';
7733  } else {
7734  $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' . $obj->{$InfoFieldList[1]} . '</li>';
7735  }
7736  }
7737  }
7738  }
7739  } else {
7740  require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
7741 
7742  $toprint = array();
7743  while ($obj = $this->db->fetch_object($resql)) {
7744  if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
7745  $c = new Categorie($this->db);
7746  $c->fetch($obj->rowid);
7747  $ways = $c->print_all_ways(); // $ways[0] = "ccc2 >> ccc2a >> ccc2a1" with html formatted text
7748  foreach ($ways as $way) {
7749  $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories"' . ($c->color ? ' style="background: #' . $c->color . ';"' : ' style="background: #aaa"') . '>' . img_object('', 'category') . ' ' . $way . '</li>';
7750  }
7751  }
7752  }
7753  }
7754  $value = '<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
7755  } else {
7756  dol_syslog(get_class($this).'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
7757  }
7758  } elseif ($type == 'link') {
7759  $out = '';
7760 
7761  // only if something to display (perf)
7762  if ($value) {
7763  $param_list = array_keys($param['options']); // $param_list='ObjectName:classPath'
7764 
7765  $InfoFieldList = explode(":", $param_list[0]);
7766  $classname = $InfoFieldList[0];
7767  $classpath = $InfoFieldList[1];
7768  $getnomurlparam = (empty($InfoFieldList[2]) ? 3 : $InfoFieldList[2]);
7769  $getnomurlparam2 = (empty($InfoFieldList[4]) ? '' : $InfoFieldList[4]);
7770  if (!empty($classpath)) {
7771  dol_include_once($InfoFieldList[1]);
7772  if ($classname && class_exists($classname)) {
7773  $object = new $classname($this->db);
7774  if ($object->element === 'product') { // Special cas for product because default valut of fetch are wrong
7775  $result = $object->fetch($value, '', '', '', 0, 1, 1);
7776  } else {
7777  $result = $object->fetch($value);
7778  }
7779  if ($result > 0) {
7780  if ($object->element === 'product') {
7781  $get_name_url_param_arr = array($getnomurlparam, $getnomurlparam2, 0, -1, 0, '', 0);
7782  if (isset($val['get_name_url_params'])) {
7783  $get_name_url_params = explode(':', $val['get_name_url_params']);
7784  if (!empty($get_name_url_params)) {
7785  $param_num_max = count($get_name_url_param_arr) - 1;
7786  foreach ($get_name_url_params as $param_num => $param_value) {
7787  if ($param_num > $param_num_max) {
7788  break;
7789  }
7790  $get_name_url_param_arr[$param_num] = $param_value;
7791  }
7792  }
7793  }
7794 
7798  $value = $object->getNomUrl($get_name_url_param_arr[0], $get_name_url_param_arr[1], $get_name_url_param_arr[2], $get_name_url_param_arr[3], $get_name_url_param_arr[4], $get_name_url_param_arr[5], $get_name_url_param_arr[6]);
7799  } else {
7800  $value = $object->getNomUrl($getnomurlparam, $getnomurlparam2);
7801  }
7802  } else {
7803  $value = '';
7804  }
7805  }
7806  } else {
7807  dol_syslog('Error bad setup of extrafield', LOG_WARNING);
7808  return 'Error bad setup of extrafield';
7809  }
7810  } else {
7811  $value = '';
7812  }
7813  } elseif ($type == 'password') {
7814  $value = preg_replace('/./i', '*', $value);
7815  } elseif ($type == 'array') {
7816  $value = implode('<br>', $value);
7817  } else { // text|html|varchar
7818  $value = dol_htmlentitiesbr($value);
7819  }
7820 
7821  //print $type.'-'.$size.'-'.$value;
7822  $out = $value;
7823 
7824  return $out;
7825  }
7826 
7833  public function clearFieldError($fieldKey)
7834  {
7835  $this->error = '';
7836  unset($this->validateFieldsErrors[$fieldKey]);
7837  }
7838 
7846  public function setFieldError($fieldKey, $msg = '')
7847  {
7848  global $langs;
7849  if (empty($msg)) { $msg = $langs->trans("UnknowError"); }
7850 
7851  $this->error = $this->validateFieldsErrors[$fieldKey] = $msg;
7852  }
7853 
7860  public function getFieldError($fieldKey)
7861  {
7862  if (!empty($this->validateFieldsErrors[$fieldKey])) {
7863  return $this->validateFieldsErrors[$fieldKey];
7864  }
7865  return '';
7866  }
7867 
7876  public function validateField($val, $fieldKey, $fieldValue)
7877  {
7878  global $langs;
7879 
7880  if (!class_exists('Validate')) { require_once DOL_DOCUMENT_ROOT . '/core/class/validate.class.php'; }
7881 
7882  $this->clearFieldError($fieldKey);
7883 
7884  if (!isset($val[$fieldKey])) {
7885  $this->setFieldError($fieldKey, $langs->trans('FieldNotFoundInObject'));
7886  return false;
7887  }
7888 
7889  $param = array();
7890  $param['options'] = array();
7891  $type = $val[$fieldKey]['type'];
7892 
7893  $required = false;
7894  if (isset($val[$fieldKey]['notnull']) && $val[$fieldKey]['notnull'] === 1) {
7895  // 'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0).
7896  $required = true;
7897  }
7898 
7899  $maxSize = 0;
7900  $minSize = 0;
7901 
7902  //
7903  // PREPARE Elements
7904  //
7905 
7906  // Convert var to be able to share same code than showOutputField of extrafields
7907  if (preg_match('/varchar\‍((\d+)\‍)/', $type, $reg)) {
7908  $type = 'varchar'; // convert varchar(xx) int varchar
7909  $maxSize = $reg[1];
7910  } elseif (preg_match('/varchar/', $type)) {
7911  $type = 'varchar'; // convert varchar(xx) int varchar
7912  }
7913 
7914  if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
7915  $type = 'select';
7916  }
7917 
7918  if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) {
7919  $type = 'link';
7920  }
7921 
7922  if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
7923  $param['options'] = $val['arrayofkeyval'];
7924  }
7925 
7926  if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) {
7927  $type = 'link';
7928  $param['options'] = array($reg[1].':'.$reg[2]=>$reg[1].':'.$reg[2]);
7929  } elseif (preg_match('/^sellist:(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
7930  $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3].':'.$reg[4] => 'N');
7931  $type = 'sellist';
7932  } elseif (preg_match('/^sellist:(.*):(.*):(.*)/i', $val['type'], $reg)) {
7933  $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3] => 'N');
7934  $type = 'sellist';
7935  } elseif (preg_match('/^sellist:(.*):(.*)/i', $val['type'], $reg)) {
7936  $param['options'] = array($reg[1].':'.$reg[2] => 'N');
7937  $type = 'sellist';
7938  }
7939 
7940  //
7941  // TEST Value
7942  //
7943 
7944  // Use Validate class to allow external Modules to use data validation part instead of concentrate all test here (factoring) or just for reuse
7945  $validate = new Validate($this->db, $langs);
7946 
7947 
7948  // little trick : to perform tests with good performances sort tests by quick to low
7949 
7950  //
7951  // COMMON TESTS
7952  //
7953 
7954  // Required test and empty value
7955  if ($required && !$validate->isNotEmptyString($fieldValue)) {
7956  $this->setFieldError($fieldKey, $validate->error);
7957  return false;
7958  } elseif (!$required && !$validate->isNotEmptyString($fieldValue)) {
7959  // if no value sent and the field is not mandatory, no need to perform tests
7960  return true;
7961  }
7962 
7963  // MAX Size test
7964  if (!empty($maxSize) && !$validate->isMaxLength($fieldValue, $maxSize)) {
7965  $this->setFieldError($fieldKey, $validate->error);
7966  return false;
7967  }
7968 
7969  // MIN Size test
7970  if (!empty($minSize) && !$validate->isMinLength($fieldValue, $minSize)) {
7971  $this->setFieldError($fieldKey, $validate->error);
7972  return false;
7973  }
7974 
7975  //
7976  // TESTS for TYPE
7977  //
7978 
7979  if (in_array($type, array('date', 'datetime', 'timestamp'))) {
7980  if (!$validate->isTimestamp($fieldValue)) {
7981  $this->setFieldError($fieldKey, $validate->error);
7982  return false;
7983  } else { return true; }
7984  } elseif ($type == 'duration') {
7985  if (!$validate->isDuration($fieldValue)) {
7986  $this->setFieldError($fieldKey, $validate->error);
7987  return false;
7988  } else { return true; }
7989  } elseif (in_array($type, array('double', 'real', 'price'))) {
7990  // is numeric
7991  if (!$validate->isNumeric($fieldValue)) {
7992  $this->setFieldError($fieldKey, $validate->error);
7993  return false;
7994  } else { return true; }
7995  } elseif ($type == 'boolean') {
7996  if (!$validate->isBool($fieldValue)) {
7997  $this->setFieldError($fieldKey, $validate->error);
7998  return false;
7999  } else { return true; }
8000  } elseif ($type == 'mail') {
8001  if (!$validate->isEmail($fieldValue)) {
8002  $this->setFieldError($fieldKey, $validate->error);
8003  return false;
8004  }
8005  } elseif ($type == 'url') {
8006  if (!$validate->isUrl($fieldValue)) {
8007  $this->setFieldError($fieldKey, $validate->error);
8008  return false;
8009  } else { return true; }
8010  } elseif ($type == 'phone') {
8011  if (!$validate->isPhone($fieldValue)) {
8012  $this->setFieldError($fieldKey, $validate->error);
8013  return false;
8014  } else { return true; }
8015  } elseif ($type == 'select' || $type == 'radio') {
8016  if (!isset($param['options'][$fieldValue])) {
8017  $this->error = $langs->trans('RequireValidValue');
8018  return false;
8019  } else { return true; }
8020  } elseif ($type == 'sellist' || $type == 'chkbxlst') {
8021  $param_list = array_keys($param['options']);
8022  $InfoFieldList = explode(":", $param_list[0]);
8023  $value_arr = explode(',', $fieldValue);
8024  $value_arr = array_map(array($this->db, 'escape'), $value_arr);
8025 
8026  $selectkey = "rowid";
8027  if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
8028  $selectkey = $InfoFieldList[2];
8029  }
8030 
8031  if (!$validate->isInDb($value_arr, $InfoFieldList[0], $selectkey)) {
8032  $this->setFieldError($fieldKey, $validate->error);
8033  return false;
8034  } else { return true; }
8035  } elseif ($type == 'link') {
8036  $param_list = array_keys($param['options']); // $param_list='ObjectName:classPath'
8037  $InfoFieldList = explode(":", $param_list[0]);
8038  $classname = $InfoFieldList[0];
8039  $classpath = $InfoFieldList[1];
8040  if (!$validate->isFetchable($fieldValue, $classname, $classpath)) {
8041  $this->setFieldError($fieldKey, $validate->error);
8042  return false;
8043  } else { return true; }
8044  }
8045 
8046  // if no test failled all is ok
8047  return true;
8048  }
8049 
8063  public function showOptionals($extrafields, $mode = 'view', $params = null, $keysuffix = '', $keyprefix = '', $onetrtd = 0, $display_type = 'card')
8064  {
8065  global $db, $conf, $langs, $action, $form, $hookmanager;
8066 
8067  if (!is_object($form)) {
8068  $form = new Form($db);
8069  }
8070  if (!is_object($extrafields)) {
8071  dol_syslog('Bad parameter extrafields for showOptionals', LOG_ERR);
8072  return 'Bad parameter extrafields for showOptionals';
8073  }
8074  if (!is_array($extrafields->attributes[$this->table_element])) {
8075  dol_syslog("extrafields->attributes was not loaded with extrafields->fetch_name_optionals_label(table_element);", LOG_WARNING);
8076  }
8077 
8078  $out = '';
8079 
8080  $parameters = array('mode'=>$mode, 'params'=>$params, 'keysuffix'=>$keysuffix, 'keyprefix'=>$keyprefix, 'display_type'=>$display_type);
8081  $reshook = $hookmanager->executeHooks('showOptionals', $parameters, $this, $action); // Note that $action and $object may have been modified by hook
8082 
8083  if (empty($reshook)) {
8084  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) {
8085  $out .= "\n";
8086  $out .= '<!-- commonobject:showOptionals --> ';
8087  $out .= "\n";
8088 
8089  $nbofextrafieldsshown = 0;
8090  $extrafields_collapse_num = '';
8091  $e = 0; // var to manage the modulo (odd/even)
8092 
8093  foreach ($extrafields->attributes[$this->table_element]['label'] as $key => $label) {
8094  // Show only the key field in params
8095  if (is_array($params) && array_key_exists('onlykey', $params) && $key != $params['onlykey']) {
8096  continue;
8097  }
8098 
8099  // Test on 'enabled' ('enabled' is different than 'list' = 'visibility')
8100  $enabled = 1;
8101  if ($enabled && isset($extrafields->attributes[$this->table_element]['enabled'][$key])) {
8102  $enabled = dol_eval($extrafields->attributes[$this->table_element]['enabled'][$key], 1, 1, '1');
8103  }
8104  if (empty($enabled)) {
8105  continue;
8106  }
8107 
8108  $visibility = 1;
8109  if ($visibility && isset($extrafields->attributes[$this->table_element]['list'][$key])) {
8110  $visibility = dol_eval($extrafields->attributes[$this->table_element]['list'][$key], 1, 1, '1');
8111  }
8112 
8113  $perms = 1;
8114  if ($perms && isset($extrafields->attributes[$this->table_element]['perms'][$key])) {
8115  $perms = dol_eval($extrafields->attributes[$this->table_element]['perms'][$key], 1, 1, '1');
8116  }
8117 
8118  if (($mode == 'create') && abs($visibility) != 1 && abs($visibility) != 3) {
8119  continue; // <> -1 and <> 1 and <> 3 = not visible on forms, only on list
8120  } elseif (($mode == 'edit') && abs($visibility) != 1 && abs($visibility) != 3 && abs($visibility) != 4) {
8121  continue; // <> -1 and <> 1 and <> 3 = not visible on forms, only on list and <> 4 = not visible at the creation
8122  } elseif ($mode == 'view' && empty($visibility)) {
8123  continue;
8124  }
8125  if (empty($perms)) {
8126  continue;
8127  }
8128  // Load language if required
8129  if (!empty($extrafields->attributes[$this->table_element]['langfile'][$key])) {
8130  $langs->load($extrafields->attributes[$this->table_element]['langfile'][$key]);
8131  }
8132 
8133  $colspan = 0;
8134  if (is_array($params) && count($params) > 0 && $display_type=='card') {
8135  if (array_key_exists('cols', $params)) {
8136  $colspan = $params['cols'];
8137  } elseif (array_key_exists('colspan', $params)) { // For backward compatibility. Use cols instead now.
8138  $reg = array();
8139  if (preg_match('/colspan="(\d+)"/', $params['colspan'], $reg)) {
8140  $colspan = $reg[1];
8141  } else {
8142  $colspan = $params['colspan'];
8143  }
8144  }
8145  }
8146  $colspan = intval($colspan);
8147 
8148  switch ($mode) {
8149  case "view":
8150  $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
8151  break;
8152  case "create":
8153  case "edit":
8154  // We get the value of property found with GETPOST so it takes into account:
8155  // default values overwrite, restore back to list link, ... (but not 'default value in database' of field)
8156  $check = 'alphanohtml';
8157  if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('html', 'text'))) {
8158  $check = 'restricthtml';
8159  }
8160  $getposttemp = GETPOST($keyprefix.'options_'.$key.$keysuffix, $check, 3); // GETPOST can get value from GET, POST or setup of default values overwrite.
8161  // GETPOST("options_" . $key) can be 'abc' or array(0=>'abc')
8162  if (is_array($getposttemp) || $getposttemp != '' || GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix)) {
8163  if (is_array($getposttemp)) {
8164  // $getposttemp is an array but following code expects a comma separated string
8165  $value = implode(",", $getposttemp);
8166  } else {
8167  $value = $getposttemp;
8168  }
8169  } else {
8170  $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.
8171  }
8172  //var_dump($keyprefix.' - '.$key.' - '.$keysuffix.' - '.$keyprefix.'options_'.$key.$keysuffix.' - '.$this->array_options["options_".$key.$keysuffix].' - '.$getposttemp.' - '.$value);
8173  break;
8174  }
8175 
8176  $nbofextrafieldsshown++;
8177 
8178  // Output value of the current field
8179  if ($extrafields->attributes[$this->table_element]['type'][$key] == 'separate') {
8180  $extrafields_collapse_num = '';
8181  $extrafield_param = $extrafields->attributes[$this->table_element]['param'][$key];
8182  if (!empty($extrafield_param) && is_array($extrafield_param)) {
8183  $extrafield_param_list = array_keys($extrafield_param['options']);
8184 
8185  if (count($extrafield_param_list) > 0) {
8186  $extrafield_collapse_display_value = intval($extrafield_param_list[0]);
8187 
8188  if ($extrafield_collapse_display_value == 1 || $extrafield_collapse_display_value == 2) {
8189  $extrafields_collapse_num = $extrafields->attributes[$this->table_element]['pos'][$key];
8190  }
8191  }
8192  }
8193 
8194  // if colspan=0 or 1, the second column is not extended, so the separator must be on 2 columns
8195  $out .= $extrafields->showSeparator($key, $this, ($colspan ? $colspan + 1 : 2), $display_type, $mode);
8196  } else {
8197  $class = (!empty($extrafields->attributes[$this->table_element]['hidden'][$key]) ? 'hideobject ' : '');
8198  $csstyle = '';
8199  if (is_array($params) && count($params) > 0) {
8200  if (array_key_exists('class', $params)) {
8201  $class .= $params['class'].' ';
8202  }
8203  if (array_key_exists('style', $params)) {
8204  $csstyle = $params['style'];
8205  }
8206  }
8207 
8208  // add html5 elements
8209  $domData = ' data-element="extrafield"';
8210  $domData .= ' data-targetelement="'.$this->element.'"';
8211  $domData .= ' data-targetid="'.$this->id.'"';
8212 
8213  $html_id = (empty($this->id) ? '' : 'extrarow-'.$this->element.'_'.$key.'_'.$this->id);
8214  if ($display_type=='card') {
8215  if (!empty($conf->global->MAIN_EXTRAFIELDS_USE_TWO_COLUMS) && ($e % 2) == 0) {
8216  $colspan = 0;
8217  }
8218 
8219  if ($action == 'selectlines') {
8220  $colspan++;
8221  }
8222  }
8223 
8224  // Convert date into timestamp format (value in memory must be a timestamp)
8225  if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('date'))) {
8226  $datenotinstring = null;
8227  if (array_key_exists('options_'.$key, $this->array_options)) {
8228  $datenotinstring = $this->array_options['options_'.$key];
8229  if (!is_numeric($this->array_options['options_'.$key])) { // For backward compatibility
8230  $datenotinstring = $this->db->jdate($datenotinstring);
8231  }
8232  }
8233  $datekey = $keyprefix.'options_'.$key.$keysuffix;
8234  $value = (GETPOSTISSET($datekey)) ? dol_mktime(12, 0, 0, GETPOST($datekey.'month', 'int', 3), GETPOST($datekey.'day', 'int', 3), GETPOST($datekey.'year', 'int', 3)) : $datenotinstring;
8235  }
8236  if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('datetime'))) {
8237  $datenotinstring = null;
8238  if (array_key_exists('options_'.$key, $this->array_options)) {
8239  $datenotinstring = $this->array_options['options_'.$key];
8240  if (!is_numeric($this->array_options['options_'.$key])) { // For backward compatibility
8241  $datenotinstring = $this->db->jdate($datenotinstring);
8242  }
8243  }
8244  $timekey = $keyprefix.'options_'.$key.$keysuffix;
8245  $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;
8246  }
8247  // Convert float submited string into real php numeric (value in memory must be a php numeric)
8248  if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('price', 'double'))) {
8249  if (GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix) || $value) {
8250  $value = price2num($value);
8251  } elseif (isset($this->array_options['options_'.$key])) {
8252  $value = $this->array_options['options_'.$key];
8253  }
8254  }
8255 
8256  // HTML, text, select, integer and varchar: take into account default value in database if in create mode
8257  if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('html', 'text', 'varchar', 'select', 'int', 'boolean'))) {
8258  if ($action == 'create') {
8259  $value = (GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix) || $value) ? $value : $extrafields->attributes[$this->table_element]['default'][$key];
8260  }
8261  }
8262 
8263  $labeltoshow = $langs->trans($label);
8264  $helptoshow = $langs->trans($extrafields->attributes[$this->table_element]['help'][$key]);
8265 
8266  if ($display_type == 'card') {
8267  $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.' >';
8268  if (!empty($conf->global->MAIN_VIEW_LINE_NUMBER) && ($action == 'view' || $action == 'valid' || $action == 'editline' || $action == 'confirm_valid' || $action == 'confirm_cancel')) {
8269  $out .= '<td></td>';
8270  }
8271  $out .= '<td class="titlefieldcreate wordbreak';
8272  } elseif ($display_type == 'line') {
8273  $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.' >';
8274  $out .= '<div style="display: inline-block; padding-right:4px" class="wordbreak';
8275  }
8276  //$out .= "titlefield";
8277  //if (GETPOST('action', 'restricthtml') == 'create') $out.='create';
8278  // BUG #11554 : For public page, use red dot for required fields, instead of bold label
8279  $tpl_context = isset($params["tpl_context"]) ? $params["tpl_context"] : "none";
8280  if ($tpl_context != "public") { // Public page : red dot instead of fieldrequired characters
8281  if ($mode != 'view' && !empty($extrafields->attributes[$this->table_element]['required'][$key])) {
8282  $out .= ' fieldrequired';
8283  }
8284  }
8285  $out .= '">';
8286  if ($tpl_context == "public") { // Public page : red dot instead of fieldrequired characters
8287  if (!empty($extrafields->attributes[$this->table_element]['help'][$key])) {
8288  $out .= $form->textwithpicto($labeltoshow, $helptoshow);
8289  } else {
8290  $out .= $labeltoshow;
8291  }
8292  if ($mode != 'view' && !empty($extrafields->attributes[$this->table_element]['required'][$key])) {
8293  $out .= '&nbsp;<span style="color: red">*</span>';
8294  }
8295  } else {
8296  if (!empty($extrafields->attributes[$this->table_element]['help'][$key])) {
8297  $out .= $form->textwithpicto($labeltoshow, $helptoshow);
8298  } else {
8299  $out .= $labeltoshow;
8300  }
8301  }
8302 
8303  $out .= ($display_type == 'card' ? '</td>' : '</div>');
8304 
8305  $html_id = !empty($this->id) ? $this->element.'_extras_'.$key.'_'.$this->id : '';
8306  if ($display_type == 'card') {
8307  // 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
8308  $out .= '<td '.($html_id ? 'id="'.$html_id.'" ' : '').' class="valuefieldcreate '.$this->element.'_extras_'.$key.'" '.($colspan ? ' colspan="'.$colspan.'"' : '').'>';
8309  } elseif ($display_type == 'line') {
8310  $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].'">';
8311  }
8312 
8313  switch ($mode) {
8314  case "view":
8315  $out .= $extrafields->showOutputField($key, $value, '', $this->table_element);
8316  break;
8317  case "create":
8318  $out .= $extrafields->showInputField($key, $value, '', $keysuffix, '', 0, $this->id, $this->table_element);
8319  break;
8320  case "edit":
8321  $out .= $extrafields->showInputField($key, $value, '', $keysuffix, '', 0, $this->id, $this->table_element);
8322  break;
8323  }
8324 
8325  $out .= ($display_type=='card' ? '</td>' : '</div>');
8326 
8327  if (!empty($conf->global->MAIN_EXTRAFIELDS_USE_TWO_COLUMS) && (($e % 2) == 1)) {
8328  $out .= ($display_type=='card' ? '</tr>' : '</div>');
8329  } else {
8330  $out .= ($display_type=='card' ? '</tr>' : '</div>');
8331  }
8332 
8333  $e++;
8334  }
8335  }
8336  $out .= "\n";
8337  // Add code to manage list depending on others
8338  if (!empty($conf->use_javascript_ajax)) {
8339  $out .= $this->getJSListDependancies();
8340  }
8341 
8342  $out .= '<!-- commonobject:showOptionals end --> '."\n";
8343 
8344  if (empty($nbofextrafieldsshown)) {
8345  $out = '';
8346  }
8347  }
8348  }
8349 
8350  $out .= $hookmanager->resPrint;
8351 
8352  return $out;
8353  }
8354 
8359  public function getJSListDependancies($type = '_extra')
8360  {
8361  $out = '
8362  <script>
8363  jQuery(document).ready(function() {
8364  function showOptions'.$type.'(child_list, parent_list, orig_select)
8365  {
8366  var val = $("select[name=\""+parent_list+"\"]").val();
8367  var parentVal = parent_list + ":" + val;
8368  if(typeof val == "string"){
8369  if(val != "") {
8370  var options = orig_select.find("option[parent=\""+parentVal+"\"]").clone();
8371  $("select[name=\""+child_list+"\"] option[parent]").remove();
8372  $("select[name=\""+child_list+"\"]").append(options);
8373  } else {
8374  var options = orig_select.find("option[parent]").clone();
8375  $("select[name=\""+child_list+"\"] option[parent]").remove();
8376  $("select[name=\""+child_list+"\"]").append(options);
8377  }
8378  } else if(val > 0) {
8379  var options = orig_select.find("option[parent=\""+parentVal+"\"]").clone();
8380  $("select[name=\""+child_list+"\"] option[parent]").remove();
8381  $("select[name=\""+child_list+"\"]").append(options);
8382  } else {
8383  var options = orig_select.find("option[parent]").clone();
8384  $("select[name=\""+child_list+"\"] option[parent]").remove();
8385  $("select[name=\""+child_list+"\"]").append(options);
8386  }
8387  }
8388  function setListDependencies'.$type.'() {
8389  jQuery("select option[parent]").parent().each(function() {
8390  var orig_select = {};
8391  var child_list = $(this).attr("name");
8392  orig_select[child_list] = $(this).clone();
8393  var parent = $(this).find("option[parent]:first").attr("parent");
8394  var infos = parent.split(":");
8395  var parent_list = infos[0];
8396 
8397  //Hide daughters lists
8398  if ($("#"+child_list).val() == 0 && $("#"+parent_list).val() == 0){
8399  $("#"+child_list).hide();
8400  //Show mother lists
8401  } else if ($("#"+parent_list).val() != 0){
8402  $("#"+parent_list).show();
8403  }
8404  //Show the child list if the parent list value is selected
8405  $("select[name=\""+parent_list+"\"]").click(function() {
8406  if ($(this).val() != 0){
8407  $("#"+child_list).show()
8408  }
8409  });
8410 
8411  //When we change parent list
8412  $("select[name=\""+parent_list+"\"]").change(function() {
8413  showOptions'.$type.'(child_list, parent_list, orig_select[child_list]);
8414  //Select the value 0 on child list after a change on the parent list
8415  $("#"+child_list).val(0).trigger("change");
8416  //Hide child lists if the parent value is set to 0
8417  if ($(this).val() == 0){
8418  $("#"+child_list).hide();
8419  }
8420  });
8421  });
8422  }
8423 
8424  setListDependencies'.$type.'();
8425  });
8426  </script>'."\n";
8427  return $out;
8428  }
8429 
8434  public function getRights()
8435  {
8436  global $user;
8437 
8438  $element = $this->element;
8439  if ($element == 'facturerec') {
8440  $element = 'facture';
8441  } elseif ($element == 'invoice_supplier_rec') {
8442  return $user->rights->fournisseur->facture;
8443  } elseif ($element == 'evaluation') {
8444  return $user->rights->hrm->evaluation;
8445  }
8446 
8447  return $user->rights->{$element};
8448  }
8449 
8462  public static function commonReplaceThirdparty(DoliDB $dbs, $origin_id, $dest_id, array $tables, $ignoreerrors = 0)
8463  {
8464  foreach ($tables as $table) {
8465  $sql = 'UPDATE '.$dbs->prefix().$table.' SET fk_soc = '.((int) $dest_id).' WHERE fk_soc = '.((int) $origin_id);
8466 
8467  if (!$dbs->query($sql)) {
8468  if ($ignoreerrors) {
8469  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.
8470  }
8471  //$this->errors = $db->lasterror();
8472  return false;
8473  }
8474  }
8475 
8476  return true;
8477  }
8478 
8491  public static function commonReplaceProduct(DoliDB $dbs, $origin_id, $dest_id, array $tables, $ignoreerrors = 0)
8492  {
8493  foreach ($tables as $table) {
8494  $sql = 'UPDATE '.MAIN_DB_PREFIX.$table.' SET fk_product = '.((int) $dest_id).' WHERE fk_product = '.((int) $origin_id);
8495 
8496  if (!$dbs->query($sql)) {
8497  if ($ignoreerrors) {
8498  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.
8499  }
8500  //$this->errors = $db->lasterror();
8501  return false;
8502  }
8503  }
8504 
8505  return true;
8506  }
8507 
8520  public function defineBuyPrice($unitPrice = 0.0, $discountPercent = 0.0, $fk_product = 0)
8521  {
8522  global $conf;
8523 
8524  $buyPrice = 0;
8525 
8526  if (($unitPrice > 0) && (isset($conf->global->ForceBuyingPriceIfNull) && $conf->global->ForceBuyingPriceIfNull > 0)) {
8527  // When ForceBuyingPriceIfNull is set
8528  $buyPrice = $unitPrice * (1 - $discountPercent / 100);
8529  } else {
8530  // Get cost price for margin calculation
8531  if (!empty($fk_product) && $fk_product > 0) {
8532  if (isset($conf->global->MARGIN_TYPE) && $conf->global->MARGIN_TYPE == 'costprice') {
8533  require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
8534  $product = new Product($this->db);
8535  $result = $product->fetch($fk_product);
8536  if ($result <= 0) {
8537  $this->errors[] = 'ErrorProductIdDoesNotExists';
8538  return -1;
8539  }
8540  if ($product->cost_price > 0) {
8541  $buyPrice = $product->cost_price;
8542  } elseif ($product->pmp > 0) {
8543  $buyPrice = $product->pmp;
8544  }
8545  } elseif (isset($conf->global->MARGIN_TYPE) && $conf->global->MARGIN_TYPE == 'pmp') {
8546  require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
8547  $product = new Product($this->db);
8548  $result = $product->fetch($fk_product);
8549  if ($result <= 0) {
8550  $this->errors[] = 'ErrorProductIdDoesNotExists';
8551  return -1;
8552  }
8553  if ($product->pmp > 0) {
8554  $buyPrice = $product->pmp;
8555  }
8556  }
8557 
8558  if (empty($buyPrice) && isset($conf->global->MARGIN_TYPE) && in_array($conf->global->MARGIN_TYPE, array('1', 'pmp', 'costprice'))) {
8559  require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
8560  $productFournisseur = new ProductFournisseur($this->db);
8561  if (($result = $productFournisseur->find_min_price_product_fournisseur($fk_product)) > 0) {
8562  $buyPrice = $productFournisseur->fourn_unitprice;
8563  } elseif ($result < 0) {
8564  $this->errors[] = $productFournisseur->error;
8565  return -2;
8566  }
8567  }
8568  }
8569  }
8570  return $buyPrice;
8571  }
8572 
8573  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
8591  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)
8592  {
8593  // phpcs:enable
8594  global $conf, $user, $langs;
8595 
8596  include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
8597  include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
8598 
8599  $sortfield = 'position_name';
8600  $sortorder = 'asc';
8601 
8602  $dir = $sdir.'/';
8603  $pdir = '/';
8604 
8605  $dir .= get_exdir(0, 0, 0, 0, $this, $modulepart);
8606  $pdir .= get_exdir(0, 0, 0, 0, $this, $modulepart);
8607 
8608  // For backward compatibility
8609  if ($modulepart == 'product') {
8610  if (getDolGlobalInt('PRODUCT_USE_OLD_PATH_FOR_PHOTO')) {
8611  $dir = $sdir.'/'.get_exdir($this->id, 2, 0, 0, $this, $modulepart).$this->id."/photos/";
8612  $pdir = '/'.get_exdir($this->id, 2, 0, 0, $this, $modulepart).$this->id."/photos/";
8613  }
8614  }
8615 
8616  // Defined relative dir to DOL_DATA_ROOT
8617  $relativedir = '';
8618  if ($dir) {
8619  $relativedir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $dir);
8620  $relativedir = preg_replace('/^[\\/]/', '', $relativedir);
8621  $relativedir = preg_replace('/[\\/]$/', '', $relativedir);
8622  }
8623 
8624  $dirthumb = $dir.'thumbs/';
8625  $pdirthumb = $pdir.'thumbs/';
8626 
8627  $return = '<!-- Photo -->'."\n";
8628  $nbphoto = 0;
8629 
8630  $filearray = dol_dir_list($dir, "files", 0, '', '(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) == 'desc' ?SORT_DESC:SORT_ASC), 1);
8631 
8632  /*if (getDolGlobalInt('PRODUCT_USE_OLD_PATH_FOR_PHOTO')) // For backward compatiblity, we scan also old dirs
8633  {
8634  $filearrayold=dol_dir_list($dirold,"files",0,'','(\.meta|_preview.*\.png)$',$sortfield,(strtolower($sortorder)=='desc'?SORT_DESC:SORT_ASC),1);
8635  $filearray=array_merge($filearray, $filearrayold);
8636  }*/
8637 
8638  completeFileArrayWithDatabaseInfo($filearray, $relativedir);
8639 
8640  if (count($filearray)) {
8641  if ($sortfield && $sortorder) {
8642  $filearray = dol_sort_array($filearray, $sortfield, $sortorder);
8643  }
8644 
8645  foreach ($filearray as $key => $val) {
8646  $photo = '';
8647  $file = $val['name'];
8648 
8649  //if (dol_is_file($dir.$file) && image_format_supported($file) >= 0)
8650  if (image_format_supported($file) >= 0) {
8651  $nbphoto++;
8652  $photo = $file;
8653  $viewfilename = $file;
8654 
8655  if ($size == 1 || $size == 'small') { // Format vignette
8656  // Find name of thumb file
8657  $photo_vignette = basename(getImageFileNameForSize($dir.$file, '_small'));
8658  if (!dol_is_file($dirthumb.$photo_vignette)) {
8659  $photo_vignette = '';
8660  }
8661 
8662  // Get filesize of original file
8663  $imgarray = dol_getImageSize($dir.$photo);
8664 
8665  if ($nbbyrow > 0) {
8666  if ($nbphoto == 1) {
8667  $return .= '<table class="valigntop center centpercent" style="border: 0; padding: 2px; border-spacing: 2px; border-collapse: separate;">';
8668  }
8669 
8670  if ($nbphoto % $nbbyrow == 1) {
8671  $return .= '<tr class="center valignmiddle" style="border: 1px">';
8672  }
8673  $return .= '<td style="width: '.ceil(100 / $nbbyrow).'%" class="photo">';
8674  } elseif ($nbbyrow < 0) {
8675  $return .= '<div class="inline-block">';
8676  }
8677 
8678  $return .= "\n";
8679 
8680  $relativefile = preg_replace('/^\//', '', $pdir.$photo);
8681  if (empty($nolink)) {
8682  $urladvanced = getAdvancedPreviewUrl($modulepart, $relativefile, 0, 'entity='.$this->entity);
8683  if ($urladvanced) {
8684  $return .= '<a href="'.$urladvanced.'">';
8685  } else {
8686  $return .= '<a href="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdir.$photo).'" class="aphoto" target="_blank" rel="noopener noreferrer">';
8687  }
8688  }
8689 
8690  // Show image (width height=$maxHeight)
8691  // Si fichier vignette disponible et image source trop grande, on utilise la vignette, sinon on utilise photo origine
8692  $alt = $langs->transnoentitiesnoconv('File').': '.$relativefile;
8693  $alt .= ' - '.$langs->transnoentitiesnoconv('Size').': '.$imgarray['width'].'x'.$imgarray['height'];
8694  if ($notitle) {
8695  $alt = '';
8696  }
8697 
8698  $addphotorefcss = 1;
8699 
8700  if ($usesharelink) {
8701  if ($val['share']) {
8702  if (empty($maxHeight) || $photo_vignette && $imgarray['height'] > $maxHeight) {
8703  $return .= '<!-- Show original file (thumb not yet available with shared links) -->';
8704  $return .= '<img class="photo photowithmargin'.($addphotorefcss ? ' photoref' : '').'" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/viewimage.php?hashp='.urlencode($val['share']).'" title="'.dol_escape_htmltag($alt).'">';
8705  } else {
8706  $return .= '<!-- Show original file -->';
8707  $return .= '<img class="photo photowithmargin'.($addphotorefcss ? ' photoref' : '').'" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/viewimage.php?hashp='.urlencode($val['share']).'" title="'.dol_escape_htmltag($alt).'">';
8708  }
8709  } else {
8710  $return .= '<!-- Show nophoto file (because file is not shared) -->';
8711  $return .= '<img class="photo photowithmargin'.($addphotorefcss ? ' photoref' : '').'" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/public/theme/common/nophoto.png" title="'.dol_escape_htmltag($alt).'">';
8712  }
8713  } else {
8714  if (empty($maxHeight) || $photo_vignette && $imgarray['height'] > $maxHeight) {
8715  $return .= '<!-- Show thumb -->';
8716  $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).'">';
8717  } else {
8718  $return .= '<!-- Show original file -->';
8719  $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).'">';
8720  }
8721  }
8722 
8723  if (empty($nolink)) {
8724  $return .= '</a>';
8725  }
8726  $return .= "\n";
8727 
8728  if ($showfilename) {
8729  $return .= '<br>'.$viewfilename;
8730  }
8731  if ($showaction) {
8732  $return .= '<br>';
8733  // On propose la generation de la vignette si elle n'existe pas et si la taille est superieure aux limites
8734  if ($photo_vignette && (image_format_supported($photo) > 0) && ($this->imgWidth > $maxWidth || $this->imgHeight > $maxHeight)) {
8735  $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>';
8736  }
8737  // Special cas for product
8738  if ($modulepart == 'product' && ($user->rights->produit->creer || $user->rights->service->creer)) {
8739  // Link to resize
8740  $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; ';
8741 
8742  // Link to delete
8743  $return .= '<a href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&action=delete&token='.newToken().'&file='.urlencode($pdir.$viewfilename).'">';
8744  $return .= img_delete().'</a>';
8745  }
8746  }
8747  $return .= "\n";
8748 
8749  if ($nbbyrow > 0) {
8750  $return .= '</td>';
8751  if (($nbphoto % $nbbyrow) == 0) {
8752  $return .= '</tr>';
8753  }
8754  } elseif ($nbbyrow < 0) {
8755  $return .= '</div>';
8756  }
8757  }
8758 
8759  if (empty($size)) { // Format origine
8760  $return .= '<img class="photo photowithmargin" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdir.$photo).'">';
8761 
8762  if ($showfilename) {
8763  $return .= '<br>'.$viewfilename;
8764  }
8765  if ($showaction) {
8766  // Special case for product
8767  if ($modulepart == 'product' && ($user->rights->produit->creer || $user->rights->service->creer)) {
8768  // Link to resize
8769  $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; ';
8770 
8771  // Link to delete
8772  $return .= '<a href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&action=delete&token='.newToken().'&file='.urlencode($pdir.$viewfilename).'">';
8773  $return .= img_delete().'</a>';
8774  }
8775  }
8776  }
8777 
8778  // On continue ou on arrete de boucler ?
8779  if ($nbmax && $nbphoto >= $nbmax) {
8780  break;
8781  }
8782  }
8783  }
8784 
8785  if ($size == 1 || $size == 'small') {
8786  if ($nbbyrow > 0) {
8787  // Ferme tableau
8788  while ($nbphoto % $nbbyrow) {
8789  $return .= '<td style="width: '.ceil(100 / $nbbyrow).'%">&nbsp;</td>';
8790  $nbphoto++;
8791  }
8792 
8793  if ($nbphoto) {
8794  $return .= '</table>';
8795  }
8796  }
8797  }
8798  }
8799 
8800  $this->nbphoto = $nbphoto;
8801 
8802  return $return;
8803  }
8804 
8805 
8812  protected function isArray($info)
8813  {
8814  if (is_array($info)) {
8815  if (isset($info['type']) && $info['type'] == 'array') {
8816  return true;
8817  } else {
8818  return false;
8819  }
8820  }
8821  return false;
8822  }
8823 
8830  public function isDate($info)
8831  {
8832  if (isset($info['type']) && ($info['type'] == 'date' || $info['type'] == 'datetime' || $info['type'] == 'timestamp')) {
8833  return true;
8834  }
8835  return false;
8836  }
8837 
8844  public function isDuration($info)
8845  {
8846  if (is_array($info)) {
8847  if (isset($info['type']) && ($info['type'] == 'duration')) {
8848  return true;
8849  } else {
8850  return false;
8851  }
8852  } else {
8853  return false;
8854  }
8855  }
8856 
8863  public function isInt($info)
8864  {
8865  if (is_array($info)) {
8866  if (isset($info['type']) && (preg_match('/(^int|int$)/i', $info['type']))) {
8867  return true;
8868  } else {
8869  return false;
8870  }
8871  } else {
8872  return false;
8873  }
8874  }
8875 
8882  public function isFloat($info)
8883  {
8884  if (is_array($info)) {
8885  if (isset($info['type']) && (preg_match('/^(double|real|price)/i', $info['type']))) {
8886  return true;
8887  } else {
8888  return false;
8889  }
8890  }
8891  return false;
8892  }
8893 
8900  public function isText($info)
8901  {
8902  if (is_array($info)) {
8903  if (isset($info['type']) && $info['type'] == 'text') {
8904  return true;
8905  } else {
8906  return false;
8907  }
8908  }
8909  return false;
8910  }
8911 
8918  protected function canBeNull($info)
8919  {
8920  if (is_array($info)) {
8921  if (isset($info['notnull']) && $info['notnull'] != '1') {
8922  return true;
8923  } else {
8924  return false;
8925  }
8926  }
8927  return true;
8928  }
8929 
8936  protected function isForcedToNullIfZero($info)
8937  {
8938  if (is_array($info)) {
8939  if (isset($info['notnull']) && $info['notnull'] == '-1') {
8940  return true;
8941  } else {
8942  return false;
8943  }
8944  }
8945  return false;
8946  }
8947 
8954  protected function isIndex($info)
8955  {
8956  if (is_array($info)) {
8957  if (isset($info['index']) && $info['index'] == true) {
8958  return true;
8959  } else {
8960  return false;
8961  }
8962  }
8963  return false;
8964  }
8965 
8966 
8975  protected function setSaveQuery()
8976  {
8977  global $conf;
8978 
8979  $queryarray = array();
8980  foreach ($this->fields as $field => $info) { // Loop on definition of fields
8981  // Depending on field type ('datetime', ...)
8982  if ($this->isDate($info)) {
8983  if (empty($this->{$field})) {
8984  $queryarray[$field] = null;
8985  } else {
8986  $queryarray[$field] = $this->db->idate($this->{$field});
8987  }
8988  } elseif ($this->isDuration($info)) {
8989  // $this->{$field} may be null, '', 0, '0', 123, '123'
8990  if ((isset($this->{$field}) && $this->{$field} != '') || !empty($info['notnull'])) {
8991  if (!isset($this->{$field})) {
8992  if (!empty($info['default'])) {
8993  $queryarray[$field] = $info['default'];
8994  } else {
8995  $queryarray[$field] = 0;
8996  }
8997  } else {
8998  $queryarray[$field] = (int) $this->{$field}; // If '0', it may be set to null later if $info['notnull'] == -1
8999  }
9000  } else {
9001  $queryarray[$field] = null;
9002  }
9003  } elseif ($this->isInt($info) || $this->isFloat($info)) {
9004  if ($field == 'entity' && is_null($this->{$field})) {
9005  $queryarray[$field] = ((int) $conf->entity);
9006  } else {
9007  // $this->{$field} may be null, '', 0, '0', 123, '123'
9008  if ((isset($this->{$field}) && $this->{$field} != '') || !empty($info['notnull'])) {
9009  if (!isset($this->{$field})) {
9010  $queryarray[$field] = 0;
9011  } elseif ($this->isInt($info)) {
9012  $queryarray[$field] = (int) $this->{$field}; // If '0', it may be set to null later if $info['notnull'] == -1
9013  } elseif ($this->isFloat($info)) {
9014  $queryarray[$field] = (double) $this->{$field}; // If '0', it may be set to null later if $info['notnull'] == -1
9015  }
9016  } else {
9017  $queryarray[$field] = null;
9018  }
9019  }
9020  } else {
9021  // Note: If $this->{$field} is not defined, it means there is a bug into definition of ->fields or a missing declaration of property
9022  // We should keep the warning generated by this because it is a bug somewhere else in code, not here.
9023  $queryarray[$field] = $this->{$field};
9024  }
9025 
9026  if ($info['type'] == 'timestamp' && empty($queryarray[$field])) {
9027  unset($queryarray[$field]);
9028  }
9029  if (!empty($info['notnull']) && $info['notnull'] == -1 && empty($queryarray[$field])) {
9030  $queryarray[$field] = null; // May force 0 to null
9031  }
9032  }
9033 
9034  return $queryarray;
9035  }
9036 
9043  public function setVarsFromFetchObj(&$obj)
9044  {
9045  global $db;
9046 
9047  foreach ($this->fields as $field => $info) {
9048  if ($this->isDate($info)) {
9049  if (is_null($obj->{$field}) || $obj->{$field} === '' || $obj->{$field} === '0000-00-00 00:00:00' || $obj->{$field} === '1000-01-01 00:00:00') {
9050  $this->{$field} = '';
9051  } else {
9052  $this->{$field} = $db->jdate($obj->{$field});
9053  }
9054  } elseif ($this->isInt($info)) {
9055  if ($field == 'rowid') {
9056  $this->id = (int) $obj->{$field};
9057  } else {
9058  if ($this->isForcedToNullIfZero($info)) {
9059  if (empty($obj->{$field})) {
9060  $this->{$field} = null;
9061  } else {
9062  $this->{$field} = (double) $obj->{$field};
9063  }
9064  } else {
9065  if (!is_null($obj->{$field}) || (isset($info['notnull']) && $info['notnull'] == 1)) {
9066  $this->{$field} = (int) $obj->{$field};
9067  } else {
9068  $this->{$field} = null;
9069  }
9070  }
9071  }
9072  } elseif ($this->isFloat($info)) {
9073  if ($this->isForcedToNullIfZero($info)) {
9074  if (empty($obj->{$field})) {
9075  $this->{$field} = null;
9076  } else {
9077  $this->{$field} = (double) $obj->{$field};
9078  }
9079  } else {
9080  if (!is_null($obj->{$field}) || (isset($info['notnull']) && $info['notnull'] == 1)) {
9081  $this->{$field} = (double) $obj->{$field};
9082  } else {
9083  $this->{$field} = null;
9084  }
9085  }
9086  } else {
9087  $this->{$field} = isset($obj->{$field}) ? $obj->{$field} : null;
9088  }
9089  }
9090 
9091  // If there is no 'ref' field, we force property ->ref to ->id for a better compatibility with common functions.
9092  if (!isset($this->fields['ref']) && isset($this->id)) {
9093  $this->ref = $this->id;
9094  }
9095  }
9096 
9103  public function getFieldList($alias = '')
9104  {
9105  $keys = array_keys($this->fields);
9106  if (!empty($alias)) {
9107  $keys_with_alias = array();
9108  foreach ($keys as $fieldname) {
9109  $keys_with_alias[] = $alias . '.' . $fieldname;
9110  }
9111  return implode(',', $keys_with_alias);
9112  } else {
9113  return implode(',', $keys);
9114  }
9115  }
9116 
9124  protected function quote($value, $fieldsentry)
9125  {
9126  if (is_null($value)) {
9127  return 'NULL';
9128  } elseif (preg_match('/^(int|double|real|price)/i', $fieldsentry['type'])) {
9129  return price2num("$value");
9130  } elseif (preg_match('/int$/i', $fieldsentry['type'])) {
9131  return (int) $value;
9132  } elseif ($fieldsentry['type'] == 'boolean') {
9133  if ($value) {
9134  return 'true';
9135  } else {
9136  return 'false';
9137  }
9138  } else {
9139  return "'".$this->db->escape($value)."'";
9140  }
9141  }
9142 
9143 
9151  public function createCommon(User $user, $notrigger = false)
9152  {
9153  global $langs;
9154  dol_syslog(get_class($this)."::createCommon create", LOG_DEBUG);
9155 
9156  $error = 0;
9157 
9158  $now = dol_now();
9159 
9160  $fieldvalues = $this->setSaveQuery();
9161 
9162  if (array_key_exists('date_creation', $fieldvalues) && empty($fieldvalues['date_creation'])) {
9163  $fieldvalues['date_creation'] = $this->db->idate($now);
9164  }
9165  if (array_key_exists('fk_user_creat', $fieldvalues) && !($fieldvalues['fk_user_creat'] > 0)) {
9166  $fieldvalues['fk_user_creat'] = $user->id;
9167  }
9168  unset($fieldvalues['rowid']); // The field 'rowid' is reserved field name for autoincrement field so we don't need it into insert.
9169  if (array_key_exists('ref', $fieldvalues)) {
9170  $fieldvalues['ref'] = dol_string_nospecial($fieldvalues['ref']); // If field is a ref, we sanitize data
9171  }
9172 
9173  $keys = array();
9174  $values = array(); // Array to store string forged for SQL syntax
9175  foreach ($fieldvalues as $k => $v) {
9176  $keys[$k] = $k;
9177  $value = $this->fields[$k];
9178  $values[$k] = $this->quote($v, $value); // May return string 'NULL' if $value is null
9179  }
9180 
9181  // Clean and check mandatory
9182  foreach ($keys as $key) {
9183  // If field is an implicit foreign key field (so type = 'integer:...')
9184  if (preg_match('/^integer:/i', $this->fields[$key]['type']) && $values[$key] == '-1') {
9185  $values[$key] = '';
9186  }
9187  if (!empty($this->fields[$key]['foreignkey']) && $values[$key] == '-1') {
9188  $values[$key] = '';
9189  }
9190 
9191  if (isset($this->fields[$key]['notnull']) && $this->fields[$key]['notnull'] == 1 && (!isset($values[$key]) || $values[$key] === 'NULL') && is_null($this->fields[$key]['default'])) {
9192  $error++;
9193  $langs->load("errors");
9194  dol_syslog("Mandatory field '".$key."' is empty and required into ->fields definition of class");
9195  $this->errors[] = $langs->trans("ErrorFieldRequired", $this->fields[$key]['label']);
9196  }
9197 
9198  // If value is null and there is a default value for field
9199  if (isset($this->fields[$key]['notnull']) && $this->fields[$key]['notnull'] == 1 && (!isset($values[$key]) || $values[$key] === 'NULL') && !is_null($this->fields[$key]['default'])) {
9200  $values[$key] = $this->quote($this->fields[$key]['default'], $this->fields[$key]);
9201  }
9202 
9203  // If field is an implicit foreign key field (so type = 'integer:...')
9204  if (preg_match('/^integer:/i', $this->fields[$key]['type']) && empty($values[$key])) {
9205  if (isset($this->fields[$key]['default'])) {
9206  $values[$key] = ((int) $this->fields[$key]['default']);
9207  } else {
9208  $values[$key] = 'null';
9209  }
9210  }
9211  if (!empty($this->fields[$key]['foreignkey']) && empty($values[$key])) {
9212  $values[$key] = 'null';
9213  }
9214  }
9215 
9216  if ($error) {
9217  return -1;
9218  }
9219 
9220  $this->db->begin();
9221 
9222  if (!$error) {
9223  $sql = "INSERT INTO ".$this->db->prefix().$this->table_element;
9224  $sql .= " (".implode(", ", $keys).')';
9225  $sql .= " VALUES (".implode(", ", $values).")"; // $values can contains 'abc' or 123
9226 
9227  $res = $this->db->query($sql);
9228  if (!$res) {
9229  $error++;
9230  if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
9231  $this->errors[] = "ErrorRefAlreadyExists";
9232  } else {
9233  $this->errors[] = $this->db->lasterror();
9234  }
9235  }
9236  }
9237 
9238  if (!$error) {
9239  $this->id = $this->db->last_insert_id($this->db->prefix().$this->table_element);
9240  }
9241 
9242  // If we have a field ref with a default value of (PROV)
9243  if (!$error) {
9244  if (key_exists('ref', $this->fields) && $this->fields['ref']['notnull'] > 0 && key_exists('default', $this->fields['ref']) && $this->fields['ref']['default'] == '(PROV)') {
9245  $sql = "UPDATE ".$this->db->prefix().$this->table_element." SET ref = '(PROV".((int) $this->id).")' WHERE (ref = '(PROV)' OR ref = '') AND rowid = ".((int) $this->id);
9246  $resqlupdate = $this->db->query($sql);
9247 
9248  if ($resqlupdate === false) {
9249  $error++;
9250  $this->errors[] = $this->db->lasterror();
9251  } else {
9252  $this->ref = '(PROV'.$this->id.')';
9253  }
9254  }
9255  }
9256 
9257  // Create extrafields
9258  if (!$error) {
9259  $result = $this->insertExtraFields();
9260  if ($result < 0) {
9261  $error++;
9262  }
9263  }
9264 
9265  // Create lines
9266  if (!empty($this->table_element_line) && !empty($this->fk_element)) {
9267  $num = (is_array($this->lines) ? count($this->lines) : 0);
9268  for ($i = 0; $i < $num; $i++) {
9269  $line = $this->lines[$i];
9270 
9271  $keyforparent = $this->fk_element;
9272  $line->$keyforparent = $this->id;
9273 
9274  // Test and convert into object this->lines[$i]. When coming from REST API, we may still have an array
9275  //if (! is_object($line)) $line=json_decode(json_encode($line), false); // convert recursively array into object.
9276  if (!is_object($line)) {
9277  $line = (object) $line;
9278  }
9279 
9280  $result = $line->create($user, 1);
9281  if ($result < 0) {
9282  $this->error = $line->error;
9283  $this->db->rollback();
9284  return -1;
9285  }
9286  }
9287  }
9288 
9289  // Triggers
9290  if (!$error && !$notrigger) {
9291  // Call triggers
9292  $result = $this->call_trigger(strtoupper(get_class($this)).'_CREATE', $user);
9293  if ($result < 0) {
9294  $error++;
9295  }
9296  // End call triggers
9297  }
9298 
9299  // Commit or rollback
9300  if ($error) {
9301  $this->db->rollback();
9302  return -1;
9303  } else {
9304  $this->db->commit();
9305  return $this->id;
9306  }
9307  }
9308 
9309 
9318  public function fetchCommon($id, $ref = null, $morewhere = '')
9319  {
9320  if (empty($id) && empty($ref) && empty($morewhere)) {
9321  return -1;
9322  }
9323 
9324  $fieldlist = $this->getFieldList('t');
9325  if (empty($fieldlist)) {
9326  return 0;
9327  }
9328 
9329  $sql = "SELECT ".$fieldlist;
9330  $sql .= " FROM ".$this->db->prefix().$this->table_element.' as t';
9331 
9332  if (!empty($id)) {
9333  $sql .= ' WHERE t.rowid = '.((int) $id);
9334  } elseif (!empty($ref)) {
9335  $sql .= " WHERE t.ref = '".$this->db->escape($ref)."'";
9336  } else {
9337  $sql .= ' WHERE 1 = 1'; // usage with empty id and empty ref is very rare
9338  }
9339  if (empty($id) && isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
9340  $sql .= ' AND t.entity IN ('.getEntity($this->table_element).')';
9341  }
9342  if ($morewhere) {
9343  $sql .= $morewhere;
9344  }
9345  $sql .= ' LIMIT 1'; // This is a fetch, to be sure to get only one record
9346 
9347  $res = $this->db->query($sql);
9348  if ($res) {
9349  $obj = $this->db->fetch_object($res);
9350  if ($obj) {
9351  $this->setVarsFromFetchObj($obj);
9352 
9353  // Retrieve all extrafield
9354  // fetch optionals attributes and labels
9355  $this->fetch_optionals();
9356 
9357  return $this->id;
9358  } else {
9359  return 0;
9360  }
9361  } else {
9362  $this->error = $this->db->lasterror();
9363  $this->errors[] = $this->error;
9364  return -1;
9365  }
9366  }
9367 
9374  public function fetchLinesCommon($morewhere = '')
9375  {
9376  $objectlineclassname = get_class($this).'Line';
9377  if (!class_exists($objectlineclassname)) {
9378  $this->error = 'Error, class '.$objectlineclassname.' not found during call of fetchLinesCommon';
9379  return -1;
9380  }
9381 
9382  $objectline = new $objectlineclassname($this->db);
9383 
9384  $sql = "SELECT ".$objectline->getFieldList('l');
9385  $sql .= " FROM ".$this->db->prefix().$objectline->table_element." as l";
9386  $sql .= " WHERE l.fk_".$this->db->escape($this->element)." = ".((int) $this->id);
9387  if ($morewhere) {
9388  $sql .= $morewhere;
9389  }
9390  if (isset($objectline->fields['position'])) {
9391  $sql .= $this->db->order('position', 'ASC');
9392  }
9393 
9394  $resql = $this->db->query($sql);
9395  if ($resql) {
9396  $num_rows = $this->db->num_rows($resql);
9397  $i = 0;
9398  while ($i < $num_rows) {
9399  $obj = $this->db->fetch_object($resql);
9400  if ($obj) {
9401  $newline = new $objectlineclassname($this->db);
9402  $newline->setVarsFromFetchObj($obj);
9403 
9404  $this->lines[] = $newline;
9405  }
9406  $i++;
9407  }
9408 
9409  return 1;
9410  } else {
9411  $this->error = $this->db->lasterror();
9412  $this->errors[] = $this->error;
9413  return -1;
9414  }
9415  }
9416 
9424  public function updateCommon(User $user, $notrigger = false)
9425  {
9426  global $conf, $langs;
9427  dol_syslog(get_class($this)."::updateCommon update", LOG_DEBUG);
9428 
9429  $error = 0;
9430 
9431  $now = dol_now();
9432 
9433  // $this->oldcopy should have been set by the caller of update
9434  //if (empty($this->oldcopy)) {
9435  // $this->oldcopy = dol_clone($this);
9436  //}
9437 
9438  $fieldvalues = $this->setSaveQuery();
9439 
9440  if (array_key_exists('date_modification', $fieldvalues) && empty($fieldvalues['date_modification'])) {
9441  $fieldvalues['date_modification'] = $this->db->idate($now);
9442  }
9443  if (array_key_exists('fk_user_modif', $fieldvalues) && !($fieldvalues['fk_user_modif'] > 0)) {
9444  $fieldvalues['fk_user_modif'] = $user->id;
9445  }
9446  unset($fieldvalues['rowid']); // The field 'rowid' is reserved field name for autoincrement field so we don't need it into update.
9447  if (array_key_exists('ref', $fieldvalues)) {
9448  $fieldvalues['ref'] = dol_string_nospecial($fieldvalues['ref']); // If field is a ref, we sanitize data
9449  }
9450 
9451  // Add quotes and escape on fields with type string
9452  $keys = array();
9453  $values = array();
9454  $tmp = array();
9455  foreach ($fieldvalues as $k => $v) {
9456  $keys[$k] = $k;
9457  $value = $this->fields[$k];
9458  $values[$k] = $this->quote($v, $value);
9459  $tmp[] = $k.'='.$this->quote($v, $this->fields[$k]);
9460  }
9461 
9462  // Clean and check mandatory fields
9463  foreach ($keys as $key) {
9464  if (preg_match('/^integer:/i', $this->fields[$key]['type']) && $values[$key] == '-1') {
9465  $values[$key] = ''; // This is an implicit foreign key field
9466  }
9467  if (!empty($this->fields[$key]['foreignkey']) && $values[$key] == '-1') {
9468  $values[$key] = ''; // This is an explicit foreign key field
9469  }
9470 
9471  //var_dump($key.'-'.$values[$key].'-'.($this->fields[$key]['notnull'] == 1));
9472  /*
9473  if ($this->fields[$key]['notnull'] == 1 && empty($values[$key]))
9474  {
9475  $error++;
9476  $this->errors[]=$langs->trans("ErrorFieldRequired", $this->fields[$key]['label']);
9477  }*/
9478  }
9479 
9480  $sql = 'UPDATE '.$this->db->prefix().$this->table_element.' SET '.implode(', ', $tmp).' WHERE rowid='.((int) $this->id);
9481 
9482  $this->db->begin();
9483 
9484  if (!$error) {
9485  $res = $this->db->query($sql);
9486  if (!$res) {
9487  $error++;
9488  $this->errors[] = $this->db->lasterror();
9489  }
9490  }
9491 
9492  // Update extrafield
9493  if (!$error) {
9494  $result = $this->insertExtraFields();
9495  if ($result < 0) {
9496  $error++;
9497  }
9498  }
9499 
9500  // Triggers
9501  if (!$error && !$notrigger) {
9502  // Call triggers
9503  $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $user);
9504  if ($result < 0) {
9505  $error++;
9506  } //Do also here what you must do to rollback action if trigger fail
9507  // End call triggers
9508  }
9509 
9510  // Commit or rollback
9511  if ($error) {
9512  $this->db->rollback();
9513  return -1;
9514  } else {
9515  $this->db->commit();
9516  return $this->id;
9517  }
9518  }
9519 
9528  public function deleteCommon(User $user, $notrigger = false, $forcechilddeletion = 0)
9529  {
9530  dol_syslog(get_class($this)."::deleteCommon delete", LOG_DEBUG);
9531 
9532  $error = 0;
9533 
9534  $this->db->begin();
9535 
9536  if ($forcechilddeletion) { // Force also delete of childtables that should lock deletion in standard case when option force is off
9537  foreach ($this->childtables as $table) {
9538  $sql = "DELETE FROM ".$this->db->prefix().$table." WHERE ".$this->fk_element." = ".((int) $this->id);
9539  $resql = $this->db->query($sql);
9540  if (!$resql) {
9541  $this->error = $this->db->lasterror();
9542  $this->errors[] = $this->error;
9543  $this->db->rollback();
9544  return -1;
9545  }
9546  }
9547  } elseif (!empty($this->fk_element) && !empty($this->childtables)) { // If object has childs linked with a foreign key field, we check all child tables.
9548  $objectisused = $this->isObjectUsed($this->id);
9549  if (!empty($objectisused)) {
9550  dol_syslog(get_class($this)."::deleteCommon Can't delete record as it has some child", LOG_WARNING);
9551  $this->error = 'ErrorRecordHasChildren';
9552  $this->errors[] = $this->error;
9553  $this->db->rollback();
9554  return 0;
9555  }
9556  }
9557 
9558  // Delete cascade first
9559  if (is_array($this->childtablesoncascade) && !empty($this->childtablesoncascade)) {
9560  foreach ($this->childtablesoncascade as $table) {
9561  $deleteFromObject = explode(':', $table);
9562  if (count($deleteFromObject) >= 2) {
9563  $className = str_replace('@', '', $deleteFromObject[0]);
9564  $filePath = $deleteFromObject[1];
9565  $columnName = $deleteFromObject[2];
9566  $TMoreSQL = array();
9567  $more_sql = $deleteFromObject[3];
9568  if (!empty($more_sql)) {
9569  $TMoreSQL['customsql'] = $more_sql;
9570  }
9571  if (dol_include_once($filePath)) {
9572  $childObject = new $className($this->db);
9573  if (method_exists($childObject, 'deleteByParentField')) {
9574  $result = $childObject->deleteByParentField($this->id, $columnName, $TMoreSQL);
9575  if ($result < 0) {
9576  $error++;
9577  $this->errors[] = $childObject->error;
9578  break;
9579  }
9580  } else {
9581  $error++;
9582  $this->errors[] = "You defined a cascade delete on an object $childObject but there is no method deleteByParentField for it";
9583  break;
9584  }
9585  } else {
9586  $error++;
9587  $this->errors[] = 'Cannot include child class file '.$filePath;
9588  break;
9589  }
9590  } else {
9591  // Delete record in child table
9592  $sql = "DELETE FROM ".$this->db->prefix().$table." WHERE ".$this->fk_element." = ".((int) $this->id);
9593 
9594  $resql = $this->db->query($sql);
9595  if (!$resql) {
9596  $error++;
9597  $this->error = $this->db->lasterror();
9598  $this->errors[] = $this->error;
9599  break;
9600  }
9601  }
9602  }
9603  }
9604 
9605  if (!$error) {
9606  if (!$notrigger) {
9607  // Call triggers
9608  $result = $this->call_trigger(strtoupper(get_class($this)).'_DELETE', $user);
9609  if ($result < 0) {
9610  $error++;
9611  } // Do also here what you must do to rollback action if trigger fail
9612  // End call triggers
9613  }
9614  }
9615 
9616  // Delete llx_ecm_files
9617  if (!$error) {
9618  $res = $this->deleteEcmFiles(1); // Deleting files physically is done later with the dol_delete_dir_recursive
9619  if (!$res) {
9620  $error++;
9621  }
9622  }
9623 
9624  // Delete linked object
9625  $res = $this->deleteObjectLinked();
9626  if ($res < 0) {
9627  $error++;
9628  }
9629 
9630  if (!$error && !empty($this->isextrafieldmanaged)) {
9631  $result = $this->deleteExtraFields();
9632  if ($result < 0) {
9633  $error++;
9634  }
9635  }
9636 
9637  if (!$error) {
9638  $sql = 'DELETE FROM '.$this->db->prefix().$this->table_element.' WHERE rowid='.((int) $this->id);
9639 
9640  $resql = $this->db->query($sql);
9641  if (!$resql) {
9642  $error++;
9643  $this->errors[] = $this->db->lasterror();
9644  }
9645  }
9646 
9647  // Commit or rollback
9648  if ($error) {
9649  $this->db->rollback();
9650  return -1;
9651  } else {
9652  $this->db->commit();
9653  return 1;
9654  }
9655  }
9656 
9667  public function deleteByParentField($parentId = 0, $parentField = '', $filter = array(), $filtermode = "AND")
9668  {
9669  global $user;
9670 
9671  $error = 0;
9672  $deleted = 0;
9673 
9674  if (!empty($parentId) && !empty($parentField)) {
9675  $this->db->begin();
9676 
9677  $sql = "SELECT rowid FROM ".$this->db->prefix().$this->table_element;
9678  $sql .= " WHERE ".$parentField." = ".(int) $parentId;
9679 
9680  // Manage filters
9681  $sqlwhere = array();
9682  if (count($filter) > 0) {
9683  foreach ($filter as $key => $value) {
9684  if ($key == 'customsql') {
9685  $sqlwhere[] = $value;
9686  } elseif (strpos($value, '%') === false) {
9687  $sqlwhere[] = $key." IN (".$this->db->sanitize($this->db->escape($value)).")";
9688  } else {
9689  $sqlwhere[] = $key." LIKE '%".$this->db->escape($value)."%'";
9690  }
9691  }
9692  }
9693  if (count($sqlwhere) > 0) {
9694  $sql .= " AND (".implode(" ".$filtermode." ", $sqlwhere).")";
9695  }
9696 
9697  $resql = $this->db->query($sql);
9698  if (!$resql) {
9699  $this->errors[] = $this->db->lasterror();
9700  $error++;
9701  } else {
9702  while ($obj = $this->db->fetch_object($resql)) {
9703  $result = $this->fetch($obj->rowid);
9704  if ($result < 0) {
9705  $error++;
9706  $this->errors[] = $this->error;
9707  } else {
9708  if (get_class($this) == 'Contact') { // TODO special code because delete() for contact has not been standardized like other delete.
9709  $result = $this->delete();
9710  } else {
9711  $result = $this->delete($user);
9712  }
9713  if ($result < 0) {
9714  $error++;
9715  $this->errors[] = $this->error;
9716  } else {
9717  $deleted++;
9718  }
9719  }
9720  }
9721  }
9722 
9723  if (empty($error)) {
9724  $this->db->commit();
9725  return $deleted;
9726  } else {
9727  $this->error = implode(', ', $this->errors);
9728  $this->db->rollback();
9729  return $error * -1;
9730  }
9731  }
9732 
9733  return $deleted;
9734  }
9735 
9744  public function deleteLineCommon(User $user, $idline, $notrigger = false)
9745  {
9746  global $conf;
9747 
9748  $error = 0;
9749 
9750  $tmpforobjectclass = get_class($this);
9751  $tmpforobjectlineclass = ucfirst($tmpforobjectclass).'Line';
9752 
9753  $this->db->begin();
9754 
9755  // Call trigger
9756  $result = $this->call_trigger('LINE'.strtoupper($tmpforobjectclass).'_DELETE', $user);
9757  if ($result < 0) {
9758  $error++;
9759  }
9760  // End call triggers
9761 
9762  if (empty($error)) {
9763  $sql = "DELETE FROM ".$this->db->prefix().$this->table_element_line;
9764  $sql .= " WHERE rowid = ".((int) $idline);
9765 
9766  $resql = $this->db->query($sql);
9767  if (!$resql) {
9768  $this->error = "Error ".$this->db->lasterror();
9769  $error++;
9770  }
9771  }
9772 
9773  if (empty($error)) {
9774  // Remove extrafields
9775  $tmpobjectline = new $tmpforobjectlineclass($this->db);
9776  if (!isset($tmpobjectline->isextrafieldmanaged) || !empty($tmpobjectline->isextrafieldmanaged)) {
9777  $tmpobjectline->id = $idline;
9778  $result = $tmpobjectline->deleteExtraFields();
9779  if ($result < 0) {
9780  $error++;
9781  $this->error = "Error ".get_class($this)."::deleteLineCommon deleteExtraFields error -4 ".$tmpobjectline->error;
9782  }
9783  }
9784  }
9785 
9786  if (empty($error)) {
9787  $this->db->commit();
9788  return 1;
9789  } else {
9790  dol_syslog(get_class($this)."::deleteLineCommon ERROR:".$this->error, LOG_ERR);
9791  $this->db->rollback();
9792  return -1;
9793  }
9794  }
9795 
9796 
9806  public function setStatusCommon($user, $status, $notrigger = 0, $triggercode = '')
9807  {
9808  $error = 0;
9809 
9810  $this->db->begin();
9811 
9812  $statusfield = 'status';
9813  if ($this->element == 'don' || $this->element == 'donation') {
9814  $statusfield = 'fk_statut';
9815  }
9816 
9817  $sql = "UPDATE ".$this->db->prefix().$this->table_element;
9818  $sql .= " SET ".$statusfield." = ".((int) $status);
9819  $sql .= " WHERE rowid = ".((int) $this->id);
9820 
9821  if ($this->db->query($sql)) {
9822  if (!$error) {
9823  $this->oldcopy = clone $this;
9824  }
9825 
9826  if (!$error && !$notrigger) {
9827  // Call trigger
9828  $result = $this->call_trigger($triggercode, $user);
9829  if ($result < 0) {
9830  $error++;
9831  }
9832  }
9833 
9834  if (!$error) {
9835  $this->status = $status;
9836  $this->db->commit();
9837  return 1;
9838  } else {
9839  $this->db->rollback();
9840  return -1;
9841  }
9842  } else {
9843  $this->error = $this->db->error();
9844  $this->db->rollback();
9845  return -1;
9846  }
9847  }
9848 
9849 
9856  public function initAsSpecimenCommon()
9857  {
9858  global $user;
9859 
9860  $this->id = 0;
9861  $this->specimen = 1;
9862  $fields = array(
9863  'label' => 'This is label',
9864  'ref' => 'ABCD1234',
9865  'description' => 'This is a description',
9866  'qty' => 123.12,
9867  'note_public' => 'Public note',
9868  'note_private' => 'Private note',
9869  'date_creation' => (dol_now() - 3600 * 48),
9870  'date_modification' => (dol_now() - 3600 * 24),
9871  'fk_user_creat' => $user->id,
9872  'fk_user_modif' => $user->id,
9873  'date' => dol_now(),
9874  );
9875  foreach ($fields as $key => $value) {
9876  if (array_key_exists($key, $this->fields)) {
9877  $this->{$key} = $value;
9878  }
9879  }
9880  return 1;
9881  }
9882 
9883 
9884  /* Part for comments */
9885 
9890  public function fetchComments()
9891  {
9892  require_once DOL_DOCUMENT_ROOT.'/core/class/comment.class.php';
9893 
9894  $comment = new Comment($this->db);
9895  $result = $comment->fetchAllFor($this->element, $this->id);
9896  if ($result < 0) {
9897  $this->errors = array_merge($this->errors, $comment->errors);
9898  return -1;
9899  } else {
9900  $this->comments = $comment->comments;
9901  }
9902  return count($this->comments);
9903  }
9904 
9910  public function getNbComments()
9911  {
9912  return count($this->comments);
9913  }
9914 
9921  public function trimParameters($parameters)
9922  {
9923  if (!is_array($parameters)) {
9924  return;
9925  }
9926  foreach ($parameters as $parameter) {
9927  if (isset($this->$parameter)) {
9928  $this->$parameter = trim($this->$parameter);
9929  }
9930  }
9931  }
9932 
9933  /* Part for categories/tags */
9934 
9945  public function getCategoriesCommon($type_categ)
9946  {
9947  require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
9948 
9949  // Get current categories
9950  $c = new Categorie($this->db);
9951  $existing = $c->containing($this->id, $type_categ, 'id');
9952 
9953  return $existing;
9954  }
9955 
9968  public function setCategoriesCommon($categories, $type_categ = '', $remove_existing = true)
9969  {
9970  // Handle single category
9971  if (!is_array($categories)) {
9972  $categories = array($categories);
9973  }
9974 
9975  dol_syslog(get_class($this)."::setCategoriesCommon Oject Id:".$this->id.' type_categ:'.$type_categ.' nb tag add:'.count($categories), LOG_DEBUG);
9976 
9977  require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
9978 
9979  if (empty($type_categ)) {
9980  dol_syslog(__METHOD__.': Type '.$type_categ.'is an unknown category type. Done nothing.', LOG_ERR);
9981  return -1;
9982  }
9983 
9984  // Get current categories
9985  $c = new Categorie($this->db);
9986  $existing = $c->containing($this->id, $type_categ, 'id');
9987  if ($remove_existing) {
9988  // Diff
9989  if (is_array($existing)) {
9990  $to_del = array_diff($existing, $categories);
9991  $to_add = array_diff($categories, $existing);
9992  } else {
9993  $to_del = array(); // Nothing to delete
9994  $to_add = $categories;
9995  }
9996  } else {
9997  $to_del = array(); // Nothing to delete
9998  $to_add = array_diff($categories, $existing);
9999  }
10000 
10001  $error = 0;
10002  $ok = 0;
10003 
10004  // Process
10005  foreach ($to_del as $del) {
10006  if ($c->fetch($del) > 0) {
10007  $result=$c->del_type($this, $type_categ);
10008  if ($result < 0) {
10009  $error++;
10010  $this->error = $c->error;
10011  $this->errors = $c->errors;
10012  break;
10013  } else {
10014  $ok += $result;
10015  }
10016  }
10017  }
10018  foreach ($to_add as $add) {
10019  if ($c->fetch($add) > 0) {
10020  $result = $c->add_type($this, $type_categ);
10021  if ($result < 0) {
10022  $error++;
10023  $this->error = $c->error;
10024  $this->errors = $c->errors;
10025  break;
10026  } else {
10027  $ok += $result;
10028  }
10029  }
10030  }
10031 
10032  return $error ? (-1 * $error) : $ok;
10033  }
10034 
10043  public function cloneCategories($fromId, $toId, $type = '')
10044  {
10045  $this->db->begin();
10046 
10047  if (empty($type)) {
10048  $type = $this->table_element;
10049  }
10050 
10051  require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
10052  $categorystatic = new Categorie($this->db);
10053 
10054  $sql = "INSERT INTO ".$this->db->prefix()."categorie_".(empty($categorystatic->MAP_CAT_TABLE[$type]) ? $type : $categorystatic->MAP_CAT_TABLE[$type])." (fk_categorie, fk_product)";
10055  $sql .= " SELECT fk_categorie, $toId FROM ".$this->db->prefix()."categorie_".(empty($categorystatic->MAP_CAT_TABLE[$type]) ? $type : $categorystatic->MAP_CAT_TABLE[$type]);
10056  $sql .= " WHERE fk_product = ".((int) $fromId);
10057 
10058  if (!$this->db->query($sql)) {
10059  $this->error = $this->db->lasterror();
10060  $this->db->rollback();
10061  return -1;
10062  }
10063 
10064  $this->db->commit();
10065  return 1;
10066  }
10067 
10074  public function deleteEcmFiles($mode = 0)
10075  {
10076  global $conf;
10077 
10078  $this->db->begin();
10079 
10080  // Delete in database with mode 0
10081  if ($mode == 0) {
10082  switch ($this->element) {
10083  case 'propal':
10084  $element = 'propale';
10085  break;
10086  case 'product':
10087  $element = 'produit';
10088  break;
10089  case 'order_supplier':
10090  $element = 'fournisseur/commande';
10091  break;
10092  case 'invoice_supplier':
10093  $element = 'fournisseur/facture/'.get_exdir($this->id, 2, 0, 1, $this, 'invoice_supplier');
10094  break;
10095  case 'shipping':
10096  $element = 'expedition/sending';
10097  break;
10098  default:
10099  $element = $this->element;
10100  }
10101 
10102  // Delete ecm_files extrafields
10103  $sql = "DELETE FROM ".$this->db->prefix()."ecm_files_extrafields WHERE fk_object IN (";
10104  $sql .= " SELECT rowid FROM ".$this->db->prefix()."ecm_files WHERE filename LIKE '".$this->db->escape($this->ref)."%'";
10105  $sql .= " AND filepath = '".$this->db->escape($element)."/".$this->db->escape($this->ref)."' AND entity = ".((int) $conf->entity); // No need of getEntity here
10106  $sql .= ")";
10107 
10108  if (!$this->db->query($sql)) {
10109  $this->error = $this->db->lasterror();
10110  $this->db->rollback();
10111  return false;
10112  }
10113 
10114  // Delete ecm_files
10115  $sql = "DELETE FROM ".$this->db->prefix()."ecm_files";
10116  $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%'";
10117  $sql .= " AND filepath = '".$this->db->escape($element)."/".$this->db->escape($this->ref)."' AND entity = ".((int) $conf->entity); // No need of getEntity here
10118 
10119  if (!$this->db->query($sql)) {
10120  $this->error = $this->db->lasterror();
10121  $this->db->rollback();
10122  return false;
10123  }
10124  }
10125 
10126  // Delete in database with mode 1
10127  if ($mode == 1) {
10128  $sql = 'DELETE FROM '.$this->db->prefix()."ecm_files_extrafields";
10129  $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).")";
10130  $resql = $this->db->query($sql);
10131  if (!$resql) {
10132  $this->error = $this->db->lasterror();
10133  $this->db->rollback();
10134  return false;
10135  }
10136 
10137  $sql = 'DELETE FROM '.$this->db->prefix()."ecm_files";
10138  $sql .= " WHERE src_object_type = '".$this->db->escape($this->table_element.(empty($this->module) ? "" : "@".$this->module))."' AND src_object_id = ".((int) $this->id);
10139  $resql = $this->db->query($sql);
10140  if (!$resql) {
10141  $this->error = $this->db->lasterror();
10142  $this->db->rollback();
10143  return false;
10144  }
10145  }
10146 
10147  $this->db->commit();
10148  return true;
10149  }
10150 }
$object ref
Definition: info.php:78
Class to manage categories.
Class to manage comment.
Parent class of all other business classes (invoices, contracts, proposals, orders,...
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...
getCategoriesCommon($type_categ)
Sets object to given categories.
getFormatedSupplierRef($objref)
Return supplier ref for screen output.
line_order($renum=false, $rowidorder='ASC', $fk_parent_line=true)
Save a new position (field rang) for details lines.
deleteEcmFiles($mode=0)
Delete related files of object in database.
getBannerAddress($htmlkey, $object)
Return full address for banner.
swapContactStatus($rowid)
Update status of a contact linked to object.
add_object_linked($origin=null, $origin_id=null, $f_user=null, $notrigger=0)
Add an object link into llx_element_element.
updateObjectLinked($sourceid=null, $sourcetype='', $targetid=null, $targettype='', $f_user=null, $notrigger=0)
Update object linked of a current object.
setUpperOrLowerCase()
Set to upper or ucwords/lower if needed.
commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams=null)
Common function for all objects extending CommonObject for generating documents.
deleteLineCommon(User $user, $idline, $notrigger=false)
Delete a line of object in database.
deleteByParentField($parentId=0, $parentField='', $filter=array(), $filtermode="AND")
Delete all child object from a parent ID.
getFieldList($alias='')
Function to concat keys of fields.
getFullName($langs, $option=0, $nameorder=-1, $maxlen=0)
Return full name (civility+' '+name+' '+lastname)
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...
getIdContact($source, $code, $status=0)
Return id of contacts for a source and a contact code.
setDocModel($user, $modelpdf)
Set last model used by doc generator.
isFloat($info)
Function test if type is float.
setExtraParameters()
Set extra parameters.
fetchCommon($id, $ref=null, $morewhere='')
Load object in memory from the database.
update_ref_ext($ref_ext)
Update external ref of element.
showOptionals($extrafields, $mode='view', $params=null, $keysuffix='', $keyprefix='', $onetrtd=0, $display_type='card')
Function to show lines of extrafields with output datas.
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...
createCommon(User $user, $notrigger=false)
Create object into database.
updateRangOfLine($rowid, $rang)
Update position of line (rang)
deleteObjectLinked($sourceid=null, $sourcetype='', $targetid=null, $targettype='', $rowid='', $f_user=null, $notrigger=0)
Delete all links between an object $this.
deleteCommon(User $user, $notrigger=false, $forcechilddeletion=0)
Delete object in database.
getFullAddress($withcountry=0, $sep="\n", $withregion=0, $extralangcode='')
Return full address of contact.
setStatut($status, $elementId=null, $elementType='', $trigkey='', $fieldstatus='fk_statut')
Set status of an object.
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).
getNbComments()
Return nb comments already posted.
setVarsFromFetchObj(&$obj)
Function to load data from a SQL pointer into properties of current object $this.
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....
getChildrenOfLine($id, $includealltree=0)
Get children of line.
deleteExtraFields()
Delete all extra fields values for the current object.
setStatusCommon($user, $status, $notrigger=0, $triggercode='')
Set to a status.
setSaveQuery()
Function to prepare a part of the query for insert by returning an array with all properties of objec...
insertExtraLanguages($trigger='', $userused=null)
Add/Update all extra fields values for the current object.
isArray($info)
Function test if type is array.
isInt($info)
Function test if type is integer.
delete_contact($rowid, $notrigger=0)
Delete a link to contact line.
errorsToString()
Method to output saved errors.
setBankAccount($fk_account, $notrigger=false, $userused=null)
Change the bank account.
liste_contact($statusoflink=-1, $source='external', $list=0, $code='', $status=-1)
Get array of all contacts for an object.
setWarehouse($warehouse_id)
Change the warehouse.
setShippingMethod($shipping_method_id, $notrigger=false, $userused=null)
Change the shipping method.
initAsSpecimenCommon()
Initialise object with example values Id must be 0 if object instance is a specimen.
trimParameters($parameters)
Trim object parameters.
isIndex($info)
Function test if is indexed.
quote($value, $fieldsentry)
Add quote to field value if necessary.
fetchComments()
Load comments linked with current task.
updateCommon(User $user, $notrigger=false)
Update object into database.
getRangOfLine($rowid)
Get position of line (rang)
delete_resource($rowid, $element, $notrigger=0)
Delete a link to resource line.
update_note($note, $suffix='')
Update note of element.
load_previous_next_ref($filter, $fieldid, $nodbprefix=0)
Load properties id_previous and id_next by comparing $fieldid with $this->ref.
setCategoriesCommon($categories, $type_categ='', $remove_existing=true)
Sets object to given categories.
line_max($fk_parent_line=0)
Get max value used for position of line (rang)
setProject($projectid, $notrigger=0)
Link element with a project.
isForcedToNullIfZero($info)
Function test if field is forced to null if zero or empty.
getKanbanView($option='')
Return clicable link of object (with eventually picto)
fetchLinesCommon($morewhere='')
Load object in memory from the database.
insertExtraFields($trigger='', $userused=null)
Add/Update all extra fields values for the current object.
delete_linked_contact($source='', $code='')
Delete all links between an object $this and all its contacts.
getFormatedCustomerRef($objref)
Return customer ref for screen output.
isText($info)
Function test if type is text.
isDate($info)
Function test if type is date.
isDuration($info)
Function test if type is duration.
canBeNull($info)
Function test if field can be null.
add_contact($fk_socpeople, $type_contact, $source='external', $notrigger=0)
Add a link between element $this->element and a contact.
cloneCategories($fromId, $toId, $type='')
Copy related categories to another object.
Class to manage Dolibarr users.
Definition: user.class.php:45
getCountry($searchkey, $withcode='', $dbtouse=0, $outputlangs='', $entconv=1, $searchlabel='')
Return country label, code or id from an id, code or label.
getState($id, $withcode='', $dbtouse=0, $withregion=0, $outputlangs='', $entconv=1)
Return state translated from an id.
if(isModEnabled('facture') &&!empty($user->rights->facture->lire)) if((isModEnabled('fournisseur') &&empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) && $user->hasRight("fournisseur", "facture", "lire"))||(isModEnabled('supplier_invoice') && $user->hasRight("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->hasRight("commande", "lire") &&empty($conf->global->WORKFLOW_DISABLE_CREATE_INVOICE_FROM_ORDER)) $resql
Social contributions to pay.
Definition: index.php:745
if($cancel &&! $id) if($action=='add' &&! $cancel) if($action=='delete') if($id) $form
Actions.
Definition: card.php:143
print *****$script_file(".$version.") pid c cd cd cd description as p label as s rowid
dol_strtolower($string, $encoding="UTF-8")
Convert a string to lower.
img_delete($titlealt='default', $other='class="pictodelete"', $morecss='')
Show delete logo.
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.
price2num($amount, $rounding='', $option=0)
Function that return a number with universal decimal format (decimal separator is '.
dol_print_error($db='', $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
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.
if(!function_exists('dol_getprefix')) dol_include_once($relpath, $classname='')
Make an include_once using default root and alternate root if it fails.
dol_now($mode='auto')
Return date for now.
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=false, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2)
Show picto whatever it's its name (generic function)
newToken()
Return the value of token currently saved into session with name 'newtoken'.
dolGetFirstLastname($firstname, $lastname, $nameorder=-1)
Return firstname and lastname in correct order.
dol_string_nospecial($str, $newstr='_', $badcharstoreplace='', $badcharstoremove='')
Clean a string from all punctuation characters to use it as a ref or login.
dol_strtoupper($string, $encoding="UTF-8")
Convert a string to upper.
getAdvancedPreviewUrl($modulepart, $relativepath, $alldata=0, $param='')
Return URL we can use for advanced preview links.
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.
dol_ucwords($string, $encoding="UTF-8")
Convert first character of all the words of a string to upper.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
image_format_supported($file, $acceptsvg=0)
Return if a filename is file name of a supported image format.
Definition: images.lib.php:58
if(preg_match('/crypted:/i', $dolibarr_main_db_pass)||!empty($dolibarr_main_db_encrypted_pass)) $conf db type
Definition: repair.php:119
$conf db user
Definition: repair.php:123
$conf db name
Only used if Module[ID]Name translation string is not found.
Definition: repair.php:122
$conf db
API class for accounts.
Definition: inc.php:41
print *****$script_file(".$version.") pid code
! Closing after partial payment: discount_vat, badcustomer or badsupplier, bankcharge,...