47 const TRIGGER_PREFIX =
'';
83 public $errors = array();
88 private $validateFieldsErrors = array();
104 public $element_for_permission;
109 public $table_element;
114 public $table_element_line =
'';
119 public $ismultientitymanaged;
129 public $array_options = array();
134 public $fields = array();
139 public $array_languages =
null;
144 public $contacts_ids;
149 public $linked_objects;
154 public $linkedObjectsIds;
159 public $linkedObjects;
164 private $linkedObjectsFullLoaded = array();
178 protected $table_ref_field =
'';
183 public $restrictiononfksoc = 0;
191 public $context = array();
272 public $ref_previous;
313 public $country_code;
356 public $barcode_type;
362 public $barcode_type_code;
368 public $barcode_type_label;
374 public $barcode_type_coder;
380 public $mode_reglement_id;
386 public $cond_reglement_id;
391 public $demand_reason_id;
397 public $transport_mode_id;
404 public $cond_reglement;
411 public $fk_delivery_address;
417 public $shipping_method_id;
423 public $shipping_method;
428 public $multicurrency_code;
433 public $multicurrency_tx;
452 public $last_main_doc;
482 public $note_private;
506 public $total_localtax1;
512 public $total_localtax2;
529 public $comments = array();
555 public $date_creation;
560 public $date_validation;
575 public $date_cloture;
586 public $user_creation;
590 public $user_creation_id;
601 public $user_validation;
605 public $user_validation_id;
609 public $user_closing_id;
615 public $user_modification;
619 public $user_modification_id;
626 public $fk_user_creat;
632 public $fk_user_modif;
634 public $next_prev_filter;
639 public $specimen = 0;
653 protected $labelStatusShort;
658 public $showphoto_on_popup;
663 public $nb = array();
673 public $extraparams = array();
678 protected $childtables = array();
685 protected $childtablesoncascade = array();
705 $sql =
"SELECT rowid, ref, ref_ext";
706 $sql .=
" FROM ".$db->prefix().$element;
707 $sql .=
" WHERE entity IN (".getEntity($element).
")";
710 $sql .=
" AND rowid = ".((int) $id);
712 $sql .=
" AND ref = '".$db->escape($ref).
"'";
713 } elseif ($ref_ext) {
714 $sql .=
" AND ref_ext = '".$db->escape($ref_ext).
"'";
716 $error =
'ErrorWrongParameters';
720 if ($ref || $ref_ext) {
721 $sql .=
" AND entity = ".((int) $conf->entity);
724 dol_syslog(get_class().
"::isExistingObject", LOG_DEBUG);
725 $resql = $db->query($sql);
727 $num = $db->num_rows($resql);
745 if (!empty($object->error)) {
746 $this->error = $object->error;
748 if (!empty($object->errors)) {
749 $this->errors = array_merge($this->errors, $object->errors);
774 global $action, $extrafields, $langs, $hookmanager;
777 $MAX_EXTRAFIELDS_TO_SHOW_IN_TOOLTIP =
getDolGlobalInt(
'MAX_EXTRAFIELDS_TO_SHOW_IN_TOOLTIP', 3);
783 if (!empty($extrafields->attributes[$this->table_element][
'label'])) {
784 foreach ($extrafields->attributes[$this->table_element][
'label'] as $key => $val) {
785 if ($extrafields->attributes[$this->table_element][
'type'][$key] ==
'separate') {
788 if ($count >= abs($MAX_EXTRAFIELDS_TO_SHOW_IN_TOOLTIP)) {
789 $datas[
'more_extrafields'] =
'<br>...';
793 if ($enabled && isset($extrafields->attributes[$this->table_element][
'enabled'][$key])) {
794 $enabled =
dol_eval($extrafields->attributes[$this->table_element][
'enabled'][$key], 1, 1,
'2');
796 if ($enabled && isset($extrafields->attributes[$this->table_element][
'list'][$key])) {
797 $enabled =
dol_eval($extrafields->attributes[$this->table_element][
'list'][$key], 1, 1,
'2');
800 if ($perms && isset($extrafields->attributes[$this->table_element][
'perms'][$key])) {
801 $perms =
dol_eval($extrafields->attributes[$this->table_element][
'perms'][$key], 1, 1,
'2');
803 if (empty($enabled)) {
806 if (abs($enabled) != 1 && abs($enabled) != 3 && abs($enabled) != 5 && abs($enabled) != 4) {
812 if (!empty($extrafields->attributes[$this->table_element][
'langfile'][$key])) {
813 $langs->load($extrafields->attributes[$this->table_element][
'langfile'][$key]);
815 $labelextra = $langs->trans((
string) $extrafields->attributes[$this->table_element][
'label'][$key]);
816 if ($extrafields->attributes[$this->table_element][
'type'][$key] ==
'separate') {
817 $datas[$key]=
'<br><b><u>'. $labelextra .
'</u></b>';
819 $value = (empty($this->array_options[
'options_' . $key]) ?
'' : $this->array_options[
'options_' . $key]);
820 $datas[$key]=
'<br><b>'. $labelextra .
':</b> ' . $extrafields->showOutputField($key, $value,
'', $this->table_element);
826 $hookmanager->initHooks(array($this->element .
'dao'));
828 'tooltipcontentarray' => &$datas,
832 $hookmanager->executeHooks(
'getTooltipContent', $parameters, $this, $action);
835 $label = implode($datas);
848 return $this->error.(is_array($this->errors) ? (($this->error !=
'' ?
', ' :
'').join(
', ', $this->errors)) :
'');
862 $parameters = array(
'objref'=>$objref);
864 $reshook = $hookmanager->executeHooks(
'getFormatedCustomerRef', $parameters, $this, $action);
866 return $hookmanager->resArray[
'objref'];
868 return $objref.(isset($hookmanager->resArray[
'objref']) ? $hookmanager->resArray[
'objref'] :
'');
881 $parameters = array(
'objref'=>$objref);
883 $reshook = $hookmanager->executeHooks(
'getFormatedSupplierRef', $parameters, $this, $action);
885 return $hookmanager->resArray[
'objref'];
887 return $objref.(isset($hookmanager->resArray[
'objref']) ? $hookmanager->resArray[
'objref'] :
'');
899 public function getFullAddress($withcountry = 0, $sep =
"\n", $withregion = 0, $extralangcode =
'')
901 if ($withcountry && $this->country_id && (empty($this->country_code) || empty($this->country))) {
902 require_once DOL_DOCUMENT_ROOT.
'/core/lib/company.lib.php';
903 $tmparray =
getCountry($this->country_id,
'all');
904 $this->country_code = $tmparray[
'code'];
905 $this->country = $tmparray[
'label'];
908 if ($withregion && $this->state_id && (empty($this->state_code) || empty($this->state) || empty($this->region) || empty($this->region_code))) {
909 require_once DOL_DOCUMENT_ROOT.
'/core/lib/company.lib.php';
910 $tmparray =
getState($this->state_id,
'all', 0, 1);
911 $this->state_code = $tmparray[
'code'];
912 $this->state = $tmparray[
'label'];
913 $this->region_code = $tmparray[
'region_code'];
914 $this->region = $tmparray[
'region'];
931 global $user, $dolibarr_main_url_root;
933 if (empty($this->last_main_doc)) {
937 include_once DOL_DOCUMENT_ROOT.
'/ecm/class/ecmfiles.class.php';
939 $result = $ecmfile->fetch(0,
'', $this->last_main_doc);
941 $this->error = $ecmfile->error;
942 $this->errors = $ecmfile->errors;
946 if (empty($ecmfile->id)) {
949 require_once DOL_DOCUMENT_ROOT.
'/core/lib/security2.lib.php';
971 } elseif (empty($ecmfile->share)) {
974 require_once DOL_DOCUMENT_ROOT.
'/core/lib/security2.lib.php';
976 $ecmfile->update($user);
982 $urlwithouturlroot = preg_replace(
'/'.preg_quote(DOL_URL_ROOT,
'/').
'$/i',
'', trim($dolibarr_main_url_root));
986 $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT;
995 if (!empty($ecmfile->share)) {
996 $paramlink .= ($paramlink ?
'&' :
'').
'hashp='.$ecmfile->share;
998 if ($forcedownload) {
999 $paramlink .= ($paramlink ?
'&' :
'').
'attachment=1';
1002 if ($relativelink) {
1003 $linktoreturn =
'document.php'.($paramlink ?
'?'.$paramlink :
'');
1005 $linktoreturn = $urlwithroot.
'/document.php'.($paramlink ?
'?'.$paramlink :
'');
1009 return $linktoreturn;
1023 public function add_contact($fk_socpeople, $type_contact, $source =
'external', $notrigger = 0)
1026 global $user, $langs;
1029 dol_syslog(get_class($this).
"::add_contact $fk_socpeople, $type_contact, $source, $notrigger");
1032 if ($fk_socpeople <= 0) {
1033 $langs->load(
"errors");
1034 $this->error = $langs->trans(
"ErrorWrongValueForParameterX",
"1");
1035 dol_syslog(get_class($this).
"::add_contact ".$this->error, LOG_ERR);
1038 if (!$type_contact) {
1039 $langs->load(
"errors");
1040 $this->error = $langs->trans(
"ErrorWrongValueForParameterX",
"2");
1041 dol_syslog(get_class($this).
"::add_contact ".$this->error, LOG_ERR);
1045 $id_type_contact = 0;
1046 if (is_numeric($type_contact)) {
1047 $id_type_contact = $type_contact;
1050 $sql =
"SELECT tc.rowid";
1051 $sql .=
" FROM ".$this->db->prefix().
"c_type_contact as tc";
1052 $sql .=
" WHERE tc.element='".$this->db->escape($this->element).
"'";
1053 $sql .=
" AND tc.source='".$this->db->escape($source).
"'";
1054 $sql .=
" AND tc.code='".$this->db->escape($type_contact).
"' AND tc.active=1";
1056 $resql = $this->db->query($sql);
1058 $obj = $this->db->fetch_object($resql);
1060 $id_type_contact = $obj->rowid;
1065 if ($id_type_contact == 0) {
1066 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");
1074 $already_added =
false;
1075 if (is_array($TListeContacts) && !empty($TListeContacts)) {
1076 foreach ($TListeContacts as $array_contact) {
1077 if ($array_contact[
'status'] == 4 && $array_contact[
'id'] == $fk_socpeople && $array_contact[
'fk_c_type_contact'] == $id_type_contact) {
1078 $already_added =
true;
1084 if (!$already_added) {
1088 $sql =
"INSERT INTO ".$this->db->prefix().
"element_contact";
1089 $sql .=
" (element_id, fk_socpeople, datecreate, statut, fk_c_type_contact) ";
1090 $sql .=
" VALUES (".$this->id.
", ".((int) $fk_socpeople).
" , ";
1091 $sql .=
"'".$this->db->idate($datecreate).
"'";
1092 $sql .=
", 4, ".((int) $id_type_contact);
1095 $resql = $this->db->query($sql);
1098 $result = $this->
call_trigger(strtoupper($this->element).
'_ADD_CONTACT', $user);
1100 $this->db->rollback();
1105 $this->db->commit();
1108 if ($this->db->errno() ==
'DB_ERROR_RECORD_ALREADY_EXISTS') {
1109 $this->error = $this->db->errno();
1110 $this->db->rollback();
1113 $this->error = $this->db->lasterror();
1114 $this->db->rollback();
1134 $contacts = $objFrom->liste_contact(-1, $source);
1135 foreach ($contacts as $contact) {
1136 if ($this->
add_contact($contact[
'id'], $contact[
'fk_c_type_contact'], $contact[
'source']) < 0) {
1153 public function update_contact($rowid, $statut, $type_contact_id = 0, $fk_socpeople = 0)
1157 $sql =
"UPDATE ".$this->db->prefix().
"element_contact set";
1158 $sql .=
" statut = ".$statut;
1159 if ($type_contact_id) {
1160 $sql .=
", fk_c_type_contact = ".((int) $type_contact_id);
1162 if ($fk_socpeople) {
1163 $sql .=
", fk_socpeople = ".((int) $fk_socpeople);
1165 $sql .=
" where rowid = ".((int) $rowid);
1166 $resql = $this->db->query($sql);
1170 $this->error = $this->db->lasterror();
1192 if (!$error && empty($notrigger)) {
1194 $this->context[
'contact_id'] = ((int) $rowid);
1195 $result = $this->
call_trigger(strtoupper($this->element).
'_DELETE_CONTACT', $user);
1203 dol_syslog(get_class($this).
"::delete_contact", LOG_DEBUG);
1205 $sql =
"DELETE FROM ".MAIN_DB_PREFIX.
"element_contact";
1206 $sql .=
" WHERE rowid = ".((int) $rowid);
1208 $result = $this->db->query($sql);
1211 $this->errors[] = $this->db->lasterror();
1216 $this->db->commit();
1219 $this->error = $this->db->lasterror();
1220 $this->db->rollback();
1240 if (!empty($typeContact)) {
1241 foreach ($typeContact as $key => $value) {
1242 array_push($temp, $key);
1244 $listId = implode(
",", $temp);
1249 if (empty($listId)) {
1253 $sql =
"DELETE FROM ".$this->db->prefix().
"element_contact";
1254 $sql .=
" WHERE element_id = ".((int) $this->
id);
1255 $sql .=
" AND fk_c_type_contact IN (".$this->db->sanitize($listId).
")";
1257 dol_syslog(get_class($this).
"::delete_linked_contact", LOG_DEBUG);
1258 if ($this->db->query($sql)) {
1261 $this->error = $this->db->lasterror();
1278 public function liste_contact($statusoflink = -1, $source =
'external', $list = 0, $code =
'', $status = -1, $arrayoftcids = array())
1285 $sql =
"SELECT ec.rowid, ec.statut as statuslink, ec.fk_socpeople as id, ec.fk_c_type_contact";
1286 if ($source ==
'internal') {
1287 $sql .=
", '-1' as socid, t.statut as statuscontact, t.login, t.photo";
1289 if ($source ==
'external' || $source ==
'thirdparty') {
1290 $sql .=
", t.fk_soc as socid, t.statut as statuscontact";
1292 $sql .=
", t.civility as civility, t.lastname as lastname, t.firstname, t.email";
1293 $sql .=
", tc.source, tc.element, tc.code, tc.libelle";
1294 $sql .=
" FROM ".$this->db->prefix().
"c_type_contact tc,";
1295 $sql .=
" ".$this->db->prefix().
"element_contact ec";
1296 if ($source ==
'internal') {
1297 $sql .=
" LEFT JOIN ".$this->db->prefix().
"user t on ec.fk_socpeople = t.rowid";
1299 if ($source ==
'external' || $source ==
'thirdparty') {
1300 $sql .=
" LEFT JOIN ".$this->db->prefix().
"socpeople t on ec.fk_socpeople = t.rowid";
1302 $sql .=
" WHERE ec.element_id = ".((int) $this->
id);
1303 $sql .=
" AND ec.fk_c_type_contact = tc.rowid";
1304 $sql .=
" AND tc.element = '".$this->db->escape($this->element).
"'";
1306 $sql .=
" AND tc.code = '".$this->db->escape($code).
"'";
1308 if ($source ==
'internal') {
1309 $sql .=
" AND tc.source = 'internal'";
1311 $sql .=
" AND t.statut = ".((int) $status);
1314 if ($source ==
'external' || $source ==
'thirdparty') {
1315 $sql .=
" AND tc.source = 'external'";
1317 $sql .=
" AND t.statut = ".((int) $status);
1320 $sql .=
" AND tc.active = 1";
1321 if ($statusoflink >= 0) {
1322 $sql .=
" AND ec.statut = ".((int) $statusoflink);
1324 $sql .=
" ORDER BY t.lastname ASC";
1326 dol_syslog(get_class($this).
"::liste_contact", LOG_DEBUG);
1327 $resql = $this->db->query($sql);
1329 $num = $this->db->num_rows($resql);
1332 $obj = $this->db->fetch_object($resql);
1335 $transkey =
"TypeContact_".$obj->element.
"_".$obj->source.
"_".$obj->code;
1336 $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle);
1338 'parentId' => $this->
id,
1339 'source' => $obj->source,
1340 'socid' => $obj->socid,
1342 'nom' => $obj->lastname,
1343 'civility' => $obj->civility,
1344 'lastname' => $obj->lastname,
1345 'firstname' => $obj->firstname,
1346 'email'=>$obj->email,
1347 'login'=> (empty($obj->login) ?
'' : $obj->login),
1348 'photo' => (empty($obj->photo) ?
'' : $obj->photo),
1349 'statuscontact' => $obj->statuscontact,
1350 'rowid' => $obj->rowid,
1351 'code' => $obj->code,
1352 'libelle' => $libelle_type,
1353 'status' => $obj->statuslink,
1354 'fk_c_type_contact' => $obj->fk_c_type_contact
1357 $tab[$i] = $obj->id;
1365 $this->error = $this->db->lasterror();
1380 $sql =
"SELECT ec.datecreate, ec.statut, ec.fk_socpeople, ec.fk_c_type_contact,";
1381 $sql .=
" tc.code, tc.libelle";
1382 $sql .=
" FROM (".$this->db->prefix().
"element_contact as ec, ".$this->db->prefix().
"c_type_contact as tc)";
1383 $sql .=
" WHERE ec.rowid =".((int) $rowid);
1384 $sql .=
" AND ec.fk_c_type_contact=tc.rowid";
1385 $sql .=
" AND tc.element = '".$this->db->escape($this->element).
"'";
1387 dol_syslog(get_class($this).
"::swapContactStatus", LOG_DEBUG);
1388 $resql = $this->db->query($sql);
1390 $obj = $this->db->fetch_object($resql);
1391 $newstatut = ($obj->statut == 4) ? 5 : 4;
1393 $this->db->free($resql);
1396 $this->error = $this->db->error();
1413 public function liste_type_contact($source =
'internal', $order =
'position', $option = 0, $activeonly = 0, $code =
'')
1418 if (empty($order)) {
1419 $order =
'position';
1421 if ($order ==
'position') {
1426 $sql =
"SELECT DISTINCT tc.rowid, tc.code, tc.libelle, tc.position";
1427 $sql .=
" FROM ".$this->db->prefix().
"c_type_contact as tc";
1428 $sql .=
" WHERE tc.element='".$this->db->escape($this->element).
"'";
1429 if ($activeonly == 1) {
1430 $sql .=
" AND tc.active=1";
1432 if (!empty($source) && $source !=
'all') {
1433 $sql .=
" AND tc.source='".$this->db->escape($source).
"'";
1435 if (!empty($code)) {
1436 $sql .=
" AND tc.code='".$this->db->escape($code).
"'";
1438 $sql .= $this->db->order($order,
'ASC');
1441 $resql = $this->db->query($sql);
1443 $num = $this->db->num_rows($resql);
1446 $obj = $this->db->fetch_object($resql);
1448 $transkey =
"TypeContact_".$this->element.
"_".$source.
"_".$obj->code;
1449 $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle);
1450 if (empty($option)) {
1451 $tab[$obj->rowid] = $libelle_type;
1453 $tab[$obj->code] = $libelle_type;
1459 $this->error = $this->db->lasterror();
1476 public function listeTypeContacts($source =
'internal', $option = 0, $activeonly = 0, $code =
'', $element =
'', $excludeelement =
'')
1478 global $langs, $conf;
1480 $langs->loadLangs(array(
'bills',
'contracts',
'interventions',
'orders',
'projects',
'propal',
'ticket',
'agenda'));
1484 $sql =
"SELECT DISTINCT tc.rowid, tc.code, tc.libelle, tc.position, tc.element";
1485 $sql .=
" FROM ".$this->db->prefix().
"c_type_contact as tc";
1487 $sqlWhere = array();
1488 if (!empty($element)) {
1489 $sqlWhere[] =
" tc.element='".$this->db->escape($element).
"'";
1491 if (!empty($excludeelement)) {
1492 $sqlWhere[] =
" tc.element <> '".$this->db->escape($excludeelement).
"'";
1495 if ($activeonly == 1) {
1496 $sqlWhere[] =
" tc.active=1";
1499 if (!empty($source) && $source !=
'all') {
1500 $sqlWhere[] =
" tc.source='".$this->db->escape($source).
"'";
1503 if (!empty($code)) {
1504 $sqlWhere[] =
" tc.code='".$this->db->escape($code).
"'";
1507 if (count($sqlWhere) > 0) {
1508 $sql .=
" WHERE ".implode(
' AND ', $sqlWhere);
1511 $sql .= $this->db->order(
'tc.element, tc.position',
'ASC');
1514 $resql = $this->db->query($sql);
1516 $num = $this->db->num_rows($resql);
1518 $langs->loadLangs(array(
"propal",
"orders",
"bills",
"suppliers",
"contracts",
"supplier_proposal"));
1520 while ($obj = $this->db->fetch_object($resql)) {
1521 $modulename = $obj->element;
1522 if (strpos($obj->element,
'project') !==
false) {
1523 $modulename =
'projet';
1524 } elseif ($obj->element ==
'contrat') {
1525 $element =
'contract';
1526 } elseif ($obj->element ==
'action') {
1527 $modulename =
'agenda';
1528 } elseif (strpos($obj->element,
'supplier') !==
false && $obj->element !=
'supplier_proposal') {
1529 $modulename =
'fournisseur';
1530 } elseif (strpos($obj->element,
'supplier') !==
false && $obj->element !=
'supplier_proposal') {
1531 $modulename =
'fournisseur';
1533 if (!empty($conf->{$modulename}->enabled)) {
1534 $libelle_element = $langs->trans(
'ContactDefault_'.$obj->element);
1535 $tmpelement = $obj->element;
1536 $transkey =
"TypeContact_".$tmpelement.
"_".$source.
"_".$obj->code;
1537 $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle);
1538 if (empty($option)) {
1539 $tab[$obj->rowid] = $libelle_element.
' - '.$libelle_type;
1541 $tab[$obj->rowid] = $libelle_element.
' - '.$libelle_type;
1548 $this->error = $this->db->lasterror();
1571 if ($this->element ==
'shipping' && $this->origin_id != 0) {
1572 $id = $this->origin_id;
1573 $element =
'commande';
1574 } elseif ($this->element ==
'reception' && $this->origin_id != 0) {
1575 $id = $this->origin_id;
1576 $element =
'order_supplier';
1579 $element = $this->element;
1582 $sql =
"SELECT ec.fk_socpeople";
1583 $sql .=
" FROM ".$this->db->prefix().
"element_contact as ec,";
1584 if ($source ==
'internal') {
1585 $sql .=
" ".$this->db->prefix().
"user as c,";
1587 if ($source ==
'external') {
1588 $sql .=
" ".$this->db->prefix().
"socpeople as c,";
1590 $sql .=
" ".$this->db->prefix().
"c_type_contact as tc";
1591 $sql .=
" WHERE ec.element_id = ".((int) $id);
1592 $sql .=
" AND ec.fk_socpeople = c.rowid";
1593 if ($source ==
'internal') {
1594 $sql .=
" AND c.entity IN (".getEntity(
'user').
")";
1596 if ($source ==
'external') {
1597 $sql .=
" AND c.entity IN (".getEntity(
'societe').
")";
1599 $sql .=
" AND ec.fk_c_type_contact = tc.rowid";
1600 $sql .=
" AND tc.element = '".$this->db->escape($element).
"'";
1601 $sql .=
" AND tc.source = '".$this->db->escape($source).
"'";
1603 $sql .=
" AND tc.code = '".$this->db->escape($code).
"'";
1605 $sql .=
" AND tc.active = 1";
1607 $sql .=
" AND ec.statut = ".((int) $status);
1610 dol_syslog(get_class($this).
"::getIdContact", LOG_DEBUG);
1611 $resql = $this->db->query($sql);
1613 while ($obj = $this->db->fetch_object($resql)) {
1614 $result[$i] = $obj->fk_socpeople;
1618 $this->error = $this->db->error();
1635 if (empty($contactid)) {
1636 $contactid = $this->contact_id;
1639 if (empty($contactid)) {
1643 require_once DOL_DOCUMENT_ROOT.
'/contact/class/contact.class.php';
1644 $contact =
new Contact($this->db);
1645 $result = $contact->fetch($contactid);
1646 $this->contact = $contact;
1662 if (empty($this->socid) && empty($this->fk_soc) && empty($force_thirdparty_id)) {
1666 require_once DOL_DOCUMENT_ROOT.
'/societe/class/societe.class.php';
1668 $idtofetch = isset($this->socid) ? $this->socid : (isset($this->fk_soc) ? $this->fk_soc : 0);
1669 if ($force_thirdparty_id) {
1670 $idtofetch = $force_thirdparty_id;
1674 $thirdparty =
new Societe($this->db);
1675 $result = $thirdparty->fetch($idtofetch);
1677 $this->errors=array_merge($this->errors, $thirdparty->errors);
1679 $this->thirdparty = $thirdparty;
1682 if (!empty($conf->global->PRODUIT_MULTIPRICES) && empty($this->thirdparty->price_level)) {
1683 $this->thirdparty->price_level = 1;
1702 if (!$this->table_ref_field) {
1706 $sql =
"SELECT rowid FROM ".$this->db->prefix().$this->table_element.
" WHERE ".$this->table_ref_field.
" LIKE '".$this->db->escape($ref).
"' LIMIT 1";
1708 $query = $this->db->query($sql);
1710 if (!$this->db->num_rows($query)) {
1714 $result = $this->db->fetch_object($query);
1716 return $this->fetch($result->rowid);
1732 dol_syslog(get_class($this).
'::fetch_barcode this->element='.$this->element.
' this->barcode_type='.$this->barcode_type);
1734 $idtype = $this->barcode_type;
1735 if (empty($idtype) && $idtype !=
'0') {
1736 if ($this->element ==
'product' && !empty($conf->global->PRODUIT_DEFAULT_BARCODE_TYPE)) {
1737 $idtype = $conf->global->PRODUIT_DEFAULT_BARCODE_TYPE;
1738 } elseif ($this->element ==
'societe') {
1739 $idtype = $conf->global->GENBARCODE_BARCODETYPE_THIRDPARTY;
1741 dol_syslog(
'Call fetch_barcode with barcode_type not defined and cant be guessed', LOG_WARNING);
1746 if (empty($this->barcode_type) || empty($this->barcode_type_code) || empty($this->barcode_type_label) || empty($this->barcode_type_coder)) {
1747 $sql =
"SELECT rowid, code, libelle as label, coder";
1748 $sql .=
" FROM ".$this->db->prefix().
"c_barcode_type";
1749 $sql .=
" WHERE rowid = ".((int) $idtype);
1750 dol_syslog(get_class($this).
'::fetch_barcode', LOG_DEBUG);
1751 $resql = $this->db->query($sql);
1753 $obj = $this->db->fetch_object($resql);
1754 $this->barcode_type = $obj->rowid;
1755 $this->barcode_type_code = $obj->code;
1756 $this->barcode_type_label = $obj->label;
1757 $this->barcode_type_coder = $obj->coder;
1777 return $this->fetch_projet();
1789 include_once DOL_DOCUMENT_ROOT.
'/projet/class/project.class.php';
1791 if (empty($this->fk_project) && !empty($this->fk_projet)) {
1792 $this->fk_project = $this->fk_projet;
1794 if (empty($this->fk_project)) {
1798 $project =
new Project($this->db);
1799 $result = $project->fetch($this->fk_project);
1801 $this->projet = $project;
1802 $this->project = $project;
1815 include_once DOL_DOCUMENT_ROOT.
'/product/class/product.class.php';
1817 if (empty($this->fk_product)) {
1821 $product =
new Product($this->db);
1822 $result = $product->fetch($this->fk_product);
1824 $this->product = $product;
1838 $user =
new User($this->db);
1839 $result = $user->fetch($userid);
1840 $this->
user = $user;
1853 if ($this->origin ==
'shipping') {
1854 $this->origin =
'expedition';
1856 if ($this->origin ==
'delivery') {
1857 $this->origin =
'livraison';
1859 if ($this->origin ==
'order_supplier') {
1860 $this->origin =
'commandeFournisseur';
1863 $origin = $this->origin;
1865 $classname = ucfirst($origin);
1866 $this->$origin =
new $classname($this->db);
1867 $this->$origin->fetch($this->origin_id);
1885 $sql =
"SELECT rowid FROM ".$this->db->prefix().$table;
1886 $sql .=
" WHERE ".$field.
" = '".$this->db->escape($key).
"'";
1887 if (!empty($element)) {
1888 $sql .=
" AND entity IN (".getEntity($element).
")";
1890 $sql .=
" AND entity = ".((int) $conf->entity);
1893 dol_syslog(get_class($this).
'::fetchObjectFrom', LOG_DEBUG);
1894 $resql = $this->db->query($sql);
1896 $row = $this->db->fetch_row($resql);
1899 $result = $this->fetch($row[0]);
1917 if (!empty($id) && !empty($field) && !empty($table)) {
1918 $sql =
"SELECT ".$field.
" FROM ".$this->db->prefix().$table;
1919 $sql .=
" WHERE rowid = ".((int) $id);
1921 dol_syslog(get_class($this).
'::getValueFrom', LOG_DEBUG);
1922 $resql = $this->db->query($sql);
1924 $row = $this->db->fetch_row($resql);
1947 public function setValueFrom($field, $value, $table =
'', $id =
null, $format =
'', $id_field =
'', $fuser =
null, $trigkey =
'', $fk_user_field =
'fk_user_modif')
1951 if (empty($table)) {
1952 $table = $this->table_element;
1957 if (empty($format)) {
1960 if (empty($id_field)) {
1961 $id_field =
'rowid';
1965 if ($table ==
'product' && $field ==
'note_private') {
1969 if (in_array($table, array(
'actioncomm',
'adherent',
'advtargetemailing',
'cronjob',
'establishment'))) {
1970 $fk_user_field =
'fk_user_mod';
1972 if (in_array($table, array(
'prelevement_bons'))) {
1973 $fk_user_field =
'';
1979 $sql =
"SELECT " . $field;
1980 $sql .=
" FROM " . MAIN_DB_PREFIX . $table;
1981 $sql .=
" WHERE " . $id_field .
" = " . ((int) $id);
1983 $resql = $this->db->query($sql);
1985 if ($obj = $this->db->fetch_object($resql)) {
1986 if ($format ==
'date') {
1987 $oldvalue = $this->db->jdate($obj->$field);
1989 $oldvalue = $obj->$field;
1993 $this->error = $this->db->lasterror();
2004 $sql =
"UPDATE ".$this->db->prefix().$table.
" SET ";
2006 if ($format ==
'text') {
2007 $sql .= $field.
" = '".$this->db->escape($value).
"'";
2008 } elseif ($format ==
'int') {
2009 $sql .= $field.
" = ".((int) $value);
2010 } elseif ($format ==
'date') {
2011 $sql .= $field.
" = ".($value ?
"'".$this->db->idate($value).
"'" :
"null");
2012 } elseif ($format ==
'dategmt') {
2013 $sql .= $field.
" = ".($value ?
"'".$this->db->idate($value,
'gmt').
"'" :
"null");
2016 if ($fk_user_field) {
2017 if (!empty($fuser) && is_object($fuser)) {
2018 $sql .=
", ".$fk_user_field.
" = ".((int) $fuser->id);
2019 } elseif (empty($fuser) || $fuser !=
'none') {
2020 $sql .=
", ".$fk_user_field.
" = ".((int) $user->id);
2024 $sql .=
" WHERE ".$id_field.
" = ".((int) $id);
2026 $resql = $this->db->query($sql);
2030 if (method_exists($this,
'fetch')) {
2031 $result = $this->fetch($id);
2033 $result = $this->fetchCommon($id);
2035 $this->oldcopy = clone $this;
2036 if (property_exists($this->oldcopy, $field)) {
2037 $this->oldcopy->$field = $oldvalue;
2041 $result = $this->call_trigger($trigkey, (!empty($fuser) && is_object($fuser)) ? $fuser : $user);
2049 if (property_exists($this, $field)) {
2050 $this->$field = $value;
2052 $this->db->commit();
2055 $this->db->rollback();
2059 if ($this->db->lasterrno() ==
'DB_ERROR_RECORD_ALREADY_EXISTS') {
2060 $this->error =
'DB_ERROR_RECORD_ALREADY_EXISTS';
2062 $this->error = $this->db->lasterror();
2064 $this->db->rollback();
2082 global $conf, $user;
2084 if (!$this->table_element) {
2085 dol_print_error(
'', get_class($this).
"::load_previous_next_ref was called on objet with property table_element not defined");
2088 if ($fieldid ==
'none') {
2093 if (in_array($this->table_element, array(
'facture_rec',
'facture_fourn_rec')) && $fieldid ==
'title') {
2099 if ($user->socid > 0) {
2100 $socid = $user->socid;
2105 $aliastablesociete =
's';
2106 if ($this->element ==
'societe') {
2107 $aliastablesociete =
'te';
2109 $restrictiononfksoc = empty($this->restrictiononfksoc) ? 0 : $this->restrictiononfksoc;
2110 $sql =
"SELECT MAX(te.".$fieldid.
")";
2111 $sql .=
" FROM ".(empty($nodbprefix) ?$this->db->prefix():
'').$this->table_element.
" as te";
2112 if ($this->element ==
'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
2113 if (empty($user->admin) || !empty($user->entity) || $conf->entity != 1) {
2114 $sql .=
" INNER JOIN ".MAIN_DB_PREFIX.
"usergroup_user as ug ON ug.fk_user = te.rowid";
2117 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2118 $tmparray = explode(
'@', $this->ismultientitymanaged);
2119 $sql .=
", ".$this->db->prefix().$tmparray[1].
" as ".($tmparray[1] ==
'societe' ?
's' :
'parenttable');
2120 } elseif ($restrictiononfksoc == 1 && $this->element !=
'societe' && empty($user->rights->societe->client->voir) && !$socid) {
2121 $sql .=
", ".$this->db->prefix().
"societe as s";
2122 } elseif ($restrictiononfksoc == 2 && $this->element !=
'societe' && empty($user->rights->societe->client->voir) && !$socid) {
2123 $sql .=
" LEFT JOIN ".$this->db->prefix().
"societe as s ON te.fk_soc = s.rowid";
2125 if ($restrictiononfksoc && empty($user->rights->societe->client->voir) && !$socid) {
2126 $sql .=
" LEFT JOIN ".$this->db->prefix().
"societe_commerciaux as sc ON ".$aliastablesociete.
".rowid = sc.fk_soc";
2128 $sql .=
" WHERE te.".$fieldid.
" < '".$this->db->escape($fieldid ==
'rowid' ? $this->
id : $this->ref).
"'";
2129 if ($restrictiononfksoc == 1 && empty($user->rights->societe->client->voir) && !$socid) {
2130 $sql .=
" AND sc.fk_user = ".((int) $user->id);
2132 if ($restrictiononfksoc == 2 && empty($user->rights->societe->client->voir) && !$socid) {
2133 $sql .=
" AND (sc.fk_user = ".((int) $user->id).
' OR te.fk_soc IS NULL)';
2135 if (!empty($filter)) {
2136 if (!preg_match(
'/^\s*AND/i', $filter)) {
2141 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2142 $tmparray = explode(
'@', $this->ismultientitymanaged);
2143 $sql .=
" AND te.".$tmparray[0].
" = ".($tmparray[1] ==
"societe" ?
"s" :
"parenttable").
".rowid";
2144 } elseif ($restrictiononfksoc == 1 && $this->element !=
'societe' && empty($user->rights->societe->client->voir) && !$socid) {
2145 $sql .=
' AND te.fk_soc = s.rowid';
2147 if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
2148 if ($this->element ==
'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
2149 if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
2150 $sql .=
" AND te.entity IS NOT NULL";
2152 $sql .=
" AND ug.entity IN (".getEntity(
'usergroup').
")";
2155 $sql .=
' AND te.entity IN ('.getEntity($this->element).
')';
2158 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged) && $this->element !=
'societe') {
2159 $tmparray = explode(
'@', $this->ismultientitymanaged);
2160 $sql .=
' AND parenttable.entity IN ('.getEntity($tmparray[1]).
')';
2162 if ($restrictiononfksoc == 1 && $socid && $this->element !=
'societe') {
2163 $sql .=
' AND te.fk_soc = '.((int) $socid);
2165 if ($restrictiononfksoc == 2 && $socid && $this->element !=
'societe') {
2166 $sql .=
' AND (te.fk_soc = '.((int) $socid).
' OR te.fk_soc IS NULL)';
2168 if ($restrictiononfksoc && $socid && $this->element ==
'societe') {
2169 $sql .=
' AND te.rowid = '.((int) $socid);
2173 $result = $this->db->query($sql);
2175 $this->error = $this->db->lasterror();
2178 $row = $this->db->fetch_row($result);
2179 $this->ref_previous = $row[0];
2181 $sql =
"SELECT MIN(te.".$fieldid.
")";
2182 $sql .=
" FROM ".(empty($nodbprefix) ?$this->db->prefix():
'').$this->table_element.
" as te";
2183 if ($this->element ==
'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
2184 if (empty($user->admin) || !empty($user->entity) || $conf->entity != 1) {
2185 $sql .=
" INNER JOIN ".MAIN_DB_PREFIX.
"usergroup_user as ug ON ug.fk_user = te.rowid";
2188 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2189 $tmparray = explode(
'@', $this->ismultientitymanaged);
2190 $sql .=
", ".$this->db->prefix().$tmparray[1].
" as ".($tmparray[1] ==
'societe' ?
's' :
'parenttable');
2191 } elseif ($restrictiononfksoc == 1 && $this->element !=
'societe' && empty($user->rights->societe->client->voir) && !$socid) {
2192 $sql .=
", ".$this->db->prefix().
"societe as s";
2193 } elseif ($restrictiononfksoc == 2 && $this->element !=
'societe' && empty($user->rights->societe->client->voir) && !$socid) {
2194 $sql .=
" LEFT JOIN ".$this->db->prefix().
"societe as s ON te.fk_soc = s.rowid";
2196 if ($restrictiononfksoc && empty($user->rights->societe->client->voir) && !$socid) {
2197 $sql .=
" LEFT JOIN ".$this->db->prefix().
"societe_commerciaux as sc ON ".$aliastablesociete.
".rowid = sc.fk_soc";
2199 $sql .=
" WHERE te.".$fieldid.
" > '".$this->db->escape($fieldid ==
'rowid' ? $this->
id : $this->ref).
"'";
2200 if ($restrictiononfksoc == 1 && empty($user->rights->societe->client->voir) && !$socid) {
2201 $sql .=
" AND sc.fk_user = ".((int) $user->id);
2203 if ($restrictiononfksoc == 2 && empty($user->rights->societe->client->voir) && !$socid) {
2204 $sql .=
" AND (sc.fk_user = ".((int) $user->id).
' OR te.fk_soc IS NULL)';
2206 if (!empty($filter)) {
2207 if (!preg_match(
'/^\s*AND/i', $filter)) {
2212 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2213 $tmparray = explode(
'@', $this->ismultientitymanaged);
2214 $sql .=
" AND te.".$tmparray[0].
" = ".($tmparray[1] ==
"societe" ?
"s" :
"parenttable").
".rowid";
2215 } elseif ($restrictiononfksoc == 1 && $this->element !=
'societe' && empty($user->rights->societe->client->voir) && !$socid) {
2216 $sql .=
' AND te.fk_soc = s.rowid';
2218 if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
2219 if ($this->element ==
'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
2220 if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
2221 $sql .=
" AND te.entity IS NOT NULL";
2223 $sql .=
" AND ug.entity IN (".getEntity(
'usergroup').
")";
2226 $sql .=
' AND te.entity IN ('.getEntity($this->element).
')';
2229 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged) && $this->element !=
'societe') {
2230 $tmparray = explode(
'@', $this->ismultientitymanaged);
2231 $sql .=
' AND parenttable.entity IN ('.getEntity($tmparray[1]).
')';
2233 if ($restrictiononfksoc == 1 && $socid && $this->element !=
'societe') {
2234 $sql .=
' AND te.fk_soc = '.((int) $socid);
2236 if ($restrictiononfksoc == 2 && $socid && $this->element !=
'societe') {
2237 $sql .=
' AND (te.fk_soc = '.((int) $socid).
' OR te.fk_soc IS NULL)';
2239 if ($restrictiononfksoc && $socid && $this->element ==
'societe') {
2240 $sql .=
' AND te.rowid = '.((int) $socid);
2245 $result = $this->db->query($sql);
2247 $this->error = $this->db->lasterror();
2250 $row = $this->db->fetch_row($result);
2251 $this->ref_next = $row[0];
2266 $contactAlreadySelected = array();
2267 $tab = $this->liste_contact(-1, $source);
2271 if ($source ==
'thirdparty') {
2272 $contactAlreadySelected[$i] = $tab[$i][
'socid'];
2274 $contactAlreadySelected[$i] = $tab[$i][
'id'];
2278 return $contactAlreadySelected;
2294 if (!$this->table_element) {
2295 dol_syslog(get_class($this).
"::setProject was called on objet with property table_element not defined", LOG_ERR);
2299 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
2300 if (!empty($this->fields[
'fk_project'])) {
2302 $sql .=
" SET fk_project = ".((int) $projectid);
2304 $sql .=
" SET fk_project = NULL";
2306 $sql .=
' WHERE rowid = '.((int) $this->
id);
2307 } elseif ($this->table_element ==
'actioncomm') {
2309 $sql .=
" SET fk_project = ".((int) $projectid);
2311 $sql .=
" SET fk_project = NULL";
2313 $sql .=
' WHERE id = '.((int) $this->
id);
2317 $sql .=
' SET fk_projet = '.((int) $projectid);
2319 $sql .=
' SET fk_projet = NULL';
2321 $sql .=
" WHERE rowid = ".((int) $this->
id);
2326 dol_syslog(get_class($this).
"::setProject", LOG_DEBUG);
2327 if ($this->db->query($sql)) {
2328 $this->fk_project = ((int) $projectid);
2335 if (!$error && !$notrigger) {
2337 $result = $this->call_trigger(strtoupper($this->element) .
'_MODIFY', $user);
2346 $this->db->rollback();
2349 $this->db->commit();
2364 $error = 0; $notrigger = 0;
2366 dol_syslog(get_class($this).
'::setPaymentMethods('.$id.
')');
2368 if ($this->
statut >= 0 || $this->element ==
'societe') {
2370 $fieldname =
'fk_mode_reglement';
2371 if ($this->element ==
'societe') {
2372 $fieldname =
'mode_reglement';
2374 if (get_class($this) ==
'Fournisseur') {
2375 $fieldname =
'mode_reglement_supplier';
2377 if (get_class($this) ==
'Tva') {
2378 $fieldname =
'fk_typepayment';
2380 if (get_class($this) ==
'Salary') {
2381 $fieldname =
'fk_typepayment';
2384 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
2385 $sql .=
" SET ".$fieldname.
" = ".(($id > 0 || $id ==
'0') ? ((
int) $id) :
'NULL');
2386 $sql .=
' WHERE rowid='.((int) $this->
id);
2388 if ($this->db->query($sql)) {
2389 $this->mode_reglement_id = $id;
2391 if (get_class($this) ==
'Fournisseur') {
2392 $this->mode_reglement_supplier_id = $id;
2395 if (!$error && !$notrigger) {
2397 if (get_class($this) ==
'Commande') {
2398 $result = $this->call_trigger(
'ORDER_MODIFY', $user);
2400 $result = $this->call_trigger(strtoupper(get_class($this)).
'_MODIFY', $user);
2409 dol_syslog(get_class($this).
'::setPaymentMethods Error '.$this->db->error());
2410 $this->error = $this->db->error();
2414 dol_syslog(get_class($this).
'::setPaymentMethods, status of the object is incompatible');
2415 $this->error =
'Status of the object is incompatible '.$this->statut;
2428 dol_syslog(get_class($this).
'::setMulticurrencyCode('.$code.
')');
2429 if ($this->
statut >= 0 || $this->element ==
'societe') {
2430 $fieldname =
'multicurrency_code';
2432 $sql =
'UPDATE '.$this->db->prefix().$this->table_element;
2433 $sql .=
" SET ".$fieldname.
" = '".$this->db->escape($code).
"'";
2434 $sql .=
' WHERE rowid='.((int) $this->
id);
2436 if ($this->db->query($sql)) {
2437 $this->multicurrency_code = $code;
2441 $this->setMulticurrencyRate($rate, 2);
2446 dol_syslog(get_class($this).
'::setMulticurrencyCode Error '.$sql.
' - '.$this->db->error());
2447 $this->error = $this->db->error();
2451 dol_syslog(get_class($this).
'::setMulticurrencyCode, status of the object is incompatible');
2452 $this->error =
'Status of the object is incompatible '.$this->statut;
2464 public function setMulticurrencyRate($rate, $mode = 1)
2466 dol_syslog(get_class($this).
'::setMulticurrencyRate('.$rate.
','.$mode.
')');
2467 if ($this->
statut >= 0 || $this->element ==
'societe') {
2468 $fieldname =
'multicurrency_tx';
2470 $sql =
'UPDATE '.$this->db->prefix().$this->table_element;
2471 $sql .=
" SET ".$fieldname.
" = ".((float) $rate);
2472 $sql .=
' WHERE rowid='.((int) $this->
id);
2474 if ($this->db->query($sql)) {
2475 $this->multicurrency_tx = $rate;
2478 if (!empty($this->lines)) {
2479 foreach ($this->lines as &$line) {
2482 $line->subprice = 0;
2487 $line->multicurrency_subprice = 0;
2490 switch ($this->element) {
2498 $line->remise_percent,
2500 $line->localtax1_tx,
2501 $line->localtax2_tx,
2502 ($line->description ? $line->description : $line->desc),
2505 $line->special_code,
2506 $line->fk_parent_line,
2507 $line->skip_update_total,
2508 $line->fk_fournprice,
2511 $line->product_type,
2514 $line->array_options,
2516 $line->multicurrency_subprice
2524 ($line->description ? $line->description : $line->desc),
2527 $line->remise_percent,
2529 $line->localtax1_tx,
2530 $line->localtax2_tx,
2535 $line->product_type,
2536 $line->fk_parent_line,
2537 $line->skip_update_total,
2538 $line->fk_fournprice,
2541 $line->special_code,
2542 $line->array_options,
2544 $line->multicurrency_subprice
2552 ($line->description ? $line->description : $line->desc),
2555 $line->remise_percent,
2559 $line->localtax1_tx,
2560 $line->localtax2_tx,
2563 $line->product_type,
2564 $line->fk_parent_line,
2565 $line->skip_update_total,
2566 $line->fk_fournprice,
2569 $line->special_code,
2570 $line->array_options,
2571 $line->situation_percent,
2573 $line->multicurrency_subprice
2576 case 'supplier_proposal':
2583 $line->remise_percent,
2585 $line->localtax1_tx,
2586 $line->localtax2_tx,
2587 ($line->description ? $line->description : $line->desc),
2590 $line->special_code,
2591 $line->fk_parent_line,
2592 $line->skip_update_total,
2593 $line->fk_fournprice,
2596 $line->product_type,
2597 $line->array_options,
2599 $line->multicurrency_subprice
2602 case 'order_supplier':
2607 ($line->description ? $line->description : $line->desc),
2610 $line->remise_percent,
2612 $line->localtax1_tx,
2613 $line->localtax2_tx,
2616 $line->product_type,
2620 $line->array_options,
2622 $line->multicurrency_subprice,
2626 case 'invoice_supplier':
2631 ($line->description ? $line->description : $line->desc),
2634 $line->localtax1_tx,
2635 $line->localtax2_tx,
2640 $line->product_type,
2641 $line->remise_percent,
2645 $line->array_options,
2647 $line->multicurrency_subprice,
2652 dol_syslog(get_class($this).
'::setMulticurrencyRate no updateline defined', LOG_DEBUG);
2660 dol_syslog(get_class($this).
'::setMulticurrencyRate Error '.$sql.
' - '.$this->db->error());
2661 $this->error = $this->db->error();
2665 dol_syslog(get_class($this).
'::setMulticurrencyRate, status of the object is incompatible');
2666 $this->error =
'Status of the object is incompatible '.$this->statut;
2680 dol_syslog(get_class($this).
'::setPaymentTerms('.$id.
', '.var_export($deposit_percent,
true).
')');
2681 if ($this->
statut >= 0 || $this->element ==
'societe') {
2683 $fieldname =
'fk_cond_reglement';
2684 if ($this->element ==
'societe') {
2685 $fieldname =
'cond_reglement';
2687 if (get_class($this) ==
'Fournisseur') {
2688 $fieldname =
'cond_reglement_supplier';
2691 if (empty($deposit_percent) || $deposit_percent < 0) {
2695 if ($deposit_percent > 100) {
2696 $deposit_percent = 100;
2699 $sql =
'UPDATE '.$this->db->prefix().$this->table_element;
2700 $sql .=
" SET ".$fieldname.
" = ".(($id > 0 || $id ==
'0') ? ((
int) $id) :
'NULL');
2701 if (in_array($this->table_element, array(
'propal',
'commande',
'societe'))) {
2702 $sql .=
" , deposit_percent = " . (empty($deposit_percent) ?
'NULL' :
"'".$this->db->escape($deposit_percent).
"'");
2704 $sql .=
' WHERE rowid='.((int) $this->
id);
2706 if ($this->db->query($sql)) {
2707 $this->cond_reglement_id = $id;
2709 if (get_class($this) ==
'Fournisseur') {
2710 $this->cond_reglement_supplier_id = $id;
2712 $this->cond_reglement = $id;
2713 $this->deposit_percent = $deposit_percent;
2716 dol_syslog(get_class($this).
'::setPaymentTerms Error '.$sql.
' - '.$this->db->error());
2717 $this->error = $this->db->error();
2721 dol_syslog(get_class($this).
'::setPaymentTerms, status of the object is incompatible');
2722 $this->error =
'Status of the object is incompatible '.$this->statut;
2735 dol_syslog(get_class($this).
'::setTransportMode('.$id.
')');
2736 if ($this->
statut >= 0 || $this->element ==
'societe') {
2737 $fieldname =
'fk_transport_mode';
2738 if ($this->element ==
'societe') {
2739 $fieldname =
'transport_mode';
2741 if (get_class($this) ==
'Fournisseur') {
2742 $fieldname =
'transport_mode_supplier';
2745 $sql =
'UPDATE '.$this->db->prefix().$this->table_element;
2746 $sql .=
" SET ".$fieldname.
" = ".(($id > 0 || $id ==
'0') ? ((
int) $id) :
'NULL');
2747 $sql .=
' WHERE rowid='.((int) $this->
id);
2749 if ($this->db->query($sql)) {
2750 $this->transport_mode_id = $id;
2752 if (get_class($this) ==
'Fournisseur') {
2753 $this->transport_mode_supplier_id = $id;
2757 dol_syslog(get_class($this).
'::setTransportMode Error '.$sql.
' - '.$this->db->error());
2758 $this->error = $this->db->error();
2762 dol_syslog(get_class($this).
'::setTransportMode, status of the object is incompatible');
2763 $this->error =
'Status of the object is incompatible '.$this->statut;
2776 dol_syslog(get_class($this).
'::setRetainedWarrantyPaymentTerms('.$id.
')');
2777 if ($this->
statut >= 0 || $this->element ==
'societe') {
2778 $fieldname =
'retained_warranty_fk_cond_reglement';
2780 $sql =
'UPDATE '.$this->db->prefix().$this->table_element;
2781 $sql .=
" SET ".$fieldname.
" = ".((int) $id);
2782 $sql .=
' WHERE rowid='.((int) $this->
id);
2784 if ($this->db->query($sql)) {
2785 $this->retained_warranty_fk_cond_reglement = $id;
2788 dol_syslog(get_class($this).
'::setRetainedWarrantyPaymentTerms Error '.$sql.
' - '.$this->db->error());
2789 $this->error = $this->db->error();
2793 dol_syslog(get_class($this).
'::setRetainedWarrantyPaymentTerms, status of the object is incompatible');
2794 $this->error =
'Status of the object is incompatible '.$this->statut;
2808 $fieldname =
'fk_delivery_address';
2809 if ($this->element ==
'delivery' || $this->element ==
'shipping') {
2810 $fieldname =
'fk_address';
2813 $sql =
"UPDATE ".$this->db->prefix().$this->table_element.
" SET ".$fieldname.
" = ".((int) $id);
2814 $sql .=
" WHERE rowid = ".((int) $this->
id).
" AND fk_statut = 0";
2816 if ($this->db->query($sql)) {
2817 $this->fk_delivery_address = $id;
2820 $this->error = $this->db->error();
2821 dol_syslog(get_class($this).
'::setDeliveryAddress Error '.$this->error);
2840 if (empty($userused)) {
2846 if (!$this->table_element) {
2847 dol_syslog(get_class($this).
"::setShippingMethod was called on objet with property table_element not defined", LOG_ERR);
2853 if ($shipping_method_id < 0) {
2854 $shipping_method_id =
'NULL';
2856 dol_syslog(get_class($this).
'::setShippingMethod('.$shipping_method_id.
')');
2858 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
2859 $sql .=
" SET fk_shipping_method = ".((int) $shipping_method_id);
2860 $sql .=
" WHERE rowid=".((int) $this->
id);
2861 $resql = $this->db->query($sql);
2863 dol_syslog(get_class($this).
'::setShippingMethod Error ', LOG_DEBUG);
2864 $this->error = $this->db->lasterror();
2869 $this->context = array(
'shippingmethodupdate'=>1);
2870 $result = $this->call_trigger(strtoupper(get_class($this)).
'_MODIFY', $userused);
2878 $this->db->rollback();
2881 $this->shipping_method_id = ($shipping_method_id ==
'NULL') ?
null:$shipping_method_id;
2882 $this->db->commit();
2896 if (!$this->table_element) {
2897 dol_syslog(get_class($this).
"::setWarehouse was called on objet with property table_element not defined", LOG_ERR);
2900 if ($warehouse_id < 0) {
2901 $warehouse_id =
'NULL';
2903 dol_syslog(get_class($this).
'::setWarehouse('.$warehouse_id.
')');
2905 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
2906 $sql .=
" SET fk_warehouse = ".((int) $warehouse_id);
2907 $sql .=
" WHERE rowid=".((int) $this->
id);
2909 if ($this->db->query($sql)) {
2910 $this->warehouse_id = ($warehouse_id ==
'NULL') ?
null:$warehouse_id;
2913 dol_syslog(get_class($this).
'::setWarehouse Error ', LOG_DEBUG);
2914 $this->error = $this->db->error();
2929 if (!$this->table_element) {
2930 dol_syslog(get_class($this).
"::setDocModel was called on objet with property table_element not defined", LOG_ERR);
2934 $newmodelpdf =
dol_trunc($modelpdf, 255);
2936 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
2937 $sql .=
" SET model_pdf = '".$this->db->escape($newmodelpdf).
"'";
2938 $sql .=
" WHERE rowid = ".((int) $this->
id);
2940 dol_syslog(get_class($this).
"::setDocModel", LOG_DEBUG);
2941 $resql = $this->db->query($sql);
2943 $this->model_pdf = $modelpdf;
2944 $this->modelpdf = $modelpdf;
2965 if (empty($userused)) {
2971 if (!$this->table_element) {
2972 dol_syslog(get_class($this).
"::setBankAccount was called on objet with property table_element not defined", LOG_ERR);
2977 if ($fk_account < 0) {
2978 $fk_account =
'NULL';
2980 dol_syslog(get_class($this).
'::setBankAccount('.$fk_account.
')');
2982 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
2983 $sql .=
" SET fk_account = ".((int) $fk_account);
2984 $sql .=
" WHERE rowid=".((int) $this->
id);
2986 $resql = $this->db->query($sql);
2988 dol_syslog(get_class($this).
'::setBankAccount Error '.$sql.
' - '.$this->db->error());
2989 $this->error = $this->db->lasterror();
2994 $this->context = array(
'bankaccountupdate'=>1);
2995 $result = $this->call_trigger(strtoupper(get_class($this)).
'_MODIFY', $userused);
3003 $this->db->rollback();
3006 $this->fk_account = ($fk_account ==
'NULL') ?
null:$fk_account;
3007 $this->db->commit();
3025 public function line_order($renum =
false, $rowidorder =
'ASC', $fk_parent_line =
true)
3028 if (!$this->table_element_line) {
3029 dol_syslog(get_class($this).
"::line_order was called on objet with property table_element_line not defined", LOG_ERR);
3032 if (!$this->fk_element) {
3033 dol_syslog(get_class($this).
"::line_order was called on objet with property fk_element not defined", LOG_ERR);
3037 $fieldposition =
'rang';
3038 if (in_array($this->table_element_line, array(
'bom_bomline',
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3039 $fieldposition =
'position';
3044 $sql =
"SELECT count(rowid) FROM ".$this->db->prefix().$this->table_element_line;
3045 $sql .=
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
3047 $sql .=
" AND " . $fieldposition .
" = 0";
3050 $sql .=
" AND " . $fieldposition .
" <> 0";
3053 dol_syslog(get_class($this).
"::line_order", LOG_DEBUG);
3054 $resql = $this->db->query($sql);
3056 $row = $this->db->fetch_row($resql);
3066 $sql =
"SELECT rowid FROM ".$this->db->prefix().$this->table_element_line;
3067 $sql .=
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
3068 if ($fk_parent_line) {
3069 $sql .=
' AND fk_parent_line IS NULL';
3071 $sql .=
" ORDER BY " . $fieldposition .
" ASC, rowid " . $rowidorder;
3073 dol_syslog(get_class($this).
"::line_order search all parent lines", LOG_DEBUG);
3074 $resql = $this->db->query($sql);
3077 $num = $this->db->num_rows($resql);
3079 $row = $this->db->fetch_row($resql);
3081 $childrens = $this->getChildrenOfLine($row[0]);
3082 if (!empty($childrens)) {
3083 foreach ($childrens as $child) {
3084 array_push($rows, $child);
3091 if (!empty($rows)) {
3092 foreach ($rows as $key => $row) {
3093 $this->updateRangOfLine($row, ($key + 1));
3112 $fieldposition =
'rang';
3113 if (in_array($this->table_element_line, array(
'bom_bomline',
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3114 $fieldposition =
'position';
3119 $sql =
"SELECT rowid FROM ".$this->db->prefix().$this->table_element_line;
3120 $sql .=
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
3121 $sql .=
' AND fk_parent_line = '.((int) $id);
3122 $sql .=
" ORDER BY " . $fieldposition .
" ASC";
3124 dol_syslog(get_class($this).
"::getChildrenOfLine search children lines for line ".$id, LOG_DEBUG);
3125 $resql = $this->db->query($sql);
3127 if ($this->db->num_rows($resql) > 0) {
3128 while ($row = $this->db->fetch_row($resql)) {
3130 if (!empty($includealltree)) {
3131 $rows = array_merge($rows, $this->getChildrenOfLine($row[0], $includealltree));
3147 public function line_up($rowid, $fk_parent_line =
true)
3150 $this->line_order(
false,
'ASC', $fk_parent_line);
3153 $rang = $this->getRangOfLine($rowid);
3156 $this->updateLineUp($rowid, $rang);
3170 $this->line_order(
false,
'ASC', $fk_parent_line);
3173 $rang = $this->getRangOfLine($rowid);
3176 $max = $this->line_max();
3179 $this->updateLineDown($rowid, $rang, $max);
3191 global $hookmanager;
3192 $fieldposition =
'rang';
3193 if (in_array($this->table_element_line, array(
'bom_bomline',
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3194 $fieldposition =
'position';
3197 $sql =
"UPDATE ".$this->db->prefix().$this->table_element_line.
" SET ".$fieldposition.
" = ".((int) $rang);
3198 $sql .=
' WHERE rowid = '.((int) $rowid);
3200 dol_syslog(get_class($this).
"::updateRangOfLine", LOG_DEBUG);
3201 if (!$this->db->query($sql)) {
3205 $parameters=array(
'rowid'=>$rowid,
'rang'=>$rang,
'fieldposition' => $fieldposition);
3207 $reshook = $hookmanager->executeHooks(
'afterRankOfLineUpdate', $parameters, $this, $action);
3222 $num = count($rows);
3223 for ($i = 0; $i < $num; $i++) {
3224 $this->updateRangOfLine($rows[$i], ($i + 1));
3238 $fieldposition =
'rang';
3239 if (in_array($this->table_element_line, array(
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3240 $fieldposition =
'position';
3243 $sql =
"UPDATE ".$this->db->prefix().$this->table_element_line.
" SET ".$fieldposition.
" = ".((int) $rang);
3244 $sql .=
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
3245 $sql .=
" AND " . $fieldposition .
" = " . ((int) ($rang - 1));
3246 if ($this->db->query($sql)) {
3247 $sql =
"UPDATE ".$this->db->prefix().$this->table_element_line.
" SET ".$fieldposition.
" = ".((int) ($rang - 1));
3248 $sql .=
' WHERE rowid = '.((int) $rowid);
3249 if (!$this->db->query($sql)) {
3269 $fieldposition =
'rang';
3270 if (in_array($this->table_element_line, array(
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3271 $fieldposition =
'position';
3274 $sql =
"UPDATE ".$this->db->prefix().$this->table_element_line.
" SET ".$fieldposition.
" = ".((int) $rang);
3275 $sql .=
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
3276 $sql .=
" AND " . $fieldposition .
" = " . ((int) ($rang + 1));
3277 if ($this->db->query($sql)) {
3278 $sql =
"UPDATE ".$this->db->prefix().$this->table_element_line.
" SET ".$fieldposition.
" = ".((int) ($rang + 1));
3279 $sql .=
' WHERE rowid = '.((int) $rowid);
3280 if (!$this->db->query($sql)) {
3297 $fieldposition =
'rang';
3298 if (in_array($this->table_element_line, array(
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3299 $fieldposition =
'position';
3302 $sql =
"SELECT " . $fieldposition .
" FROM ".$this->db->prefix().$this->table_element_line;
3303 $sql .=
" WHERE rowid = ".((int) $rowid);
3305 dol_syslog(get_class($this).
"::getRangOfLine", LOG_DEBUG);
3306 $resql = $this->db->query($sql);
3308 $row = $this->db->fetch_row($resql);
3323 $fieldposition =
'rang';
3324 if (in_array($this->table_element_line, array(
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3325 $fieldposition =
'position';
3328 $sql =
"SELECT rowid FROM ".$this->db->prefix().$this->table_element_line;
3329 $sql .=
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
3330 $sql .=
" AND " . $fieldposition .
" = ".((int) $rang);
3331 $resql = $this->db->query($sql);
3333 $row = $this->db->fetch_row($resql);
3350 $positionfield =
'rang';
3351 if (in_array($this->table_element, array(
'bom_bom',
'product_attribute'))) {
3352 $positionfield =
'position';
3356 if ($fk_parent_line) {
3357 $sql =
"SELECT max(".$positionfield.
") FROM ".$this->db->prefix().$this->table_element_line;
3358 $sql .=
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
3359 $sql .=
" AND fk_parent_line = ".((int) $fk_parent_line);
3361 dol_syslog(get_class($this).
"::line_max", LOG_DEBUG);
3362 $resql = $this->db->query($sql);
3364 $row = $this->db->fetch_row($resql);
3365 if (!empty($row[0])) {
3368 return $this->getRangOfLine($fk_parent_line);
3373 $sql =
"SELECT max(".$positionfield.
") FROM ".$this->db->prefix().$this->table_element_line;
3374 $sql .=
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
3376 dol_syslog(get_class($this).
"::line_max", LOG_DEBUG);
3377 $resql = $this->db->query($sql);
3379 $row = $this->db->fetch_row($resql);
3397 if (!$this->table_element) {
3398 dol_syslog(get_class($this).
"::update_ref_ext was called on objet with property table_element not defined", LOG_ERR);
3402 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
3403 $sql .=
" SET ref_ext = '".$this->db->escape($ref_ext).
"'";
3404 $sql .=
" WHERE ".(isset($this->table_rowid) ? $this->table_rowid :
'rowid').
" = ".((
int) $this->id);
3406 dol_syslog(get_class($this).
"::update_ref_ext", LOG_DEBUG);
3407 if ($this->db->query($sql)) {
3408 $this->ref_ext = $ref_ext;
3411 $this->error = $this->db->error();
3430 if (!$this->table_element) {
3431 $this->error =
'update_note was called on objet with property table_element not defined';
3432 dol_syslog(get_class($this).
"::update_note was called on objet with property table_element not defined", LOG_ERR);
3435 if (!in_array($suffix, array(
'',
'_public',
'_private'))) {
3436 $this->error =
'update_note Parameter suffix must be empty, \'_private\' or \'_public\'';
3437 dol_syslog(get_class($this).
"::update_note Parameter suffix must be empty, '_private' or '_public'", LOG_ERR);
3441 $newsuffix = $suffix;
3444 if ($this->table_element ==
'product' && $newsuffix ==
'_private') {
3447 if (in_array($this->table_element, array(
'actioncomm',
'adherent',
'advtargetemailing',
'cronjob',
'establishment'))) {
3448 $fieldusermod =
"fk_user_mod";
3449 } elseif ($this->table_element ==
'ecm_files') {
3450 $fieldusermod =
"fk_user_m";
3452 $fieldusermod =
"fk_user_modif";
3454 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
3455 $sql .=
" SET note".$newsuffix.
" = ".(!empty($note) ? (
"'".$this->db->escape($note).
"'") :
"NULL");
3456 $sql .=
", ".$fieldusermod.
" = ".((int) $user->id);
3457 $sql .=
" WHERE rowid = ".((int) $this->
id);
3459 dol_syslog(get_class($this).
"::update_note", LOG_DEBUG);
3460 if ($this->db->query($sql)) {
3461 if ($suffix ==
'_public') {
3462 $this->note_public = $note;
3463 } elseif ($suffix ==
'_private') {
3464 $this->note_private = $note;
3466 $this->note = $note;
3467 $this->note_private = $note;
3469 if (empty($notrigger)) {
3470 switch ($this->element) {
3472 $trigger_name =
'COMPANY_MODIFY';
3475 $trigger_name =
'ORDER_MODIFY';
3478 $trigger_name =
'BILL_MODIFY';
3480 case 'invoice_supplier':
3481 $trigger_name =
'BILL_SUPPLIER_MODIFY';
3484 $trigger_name =
'BILLREC_MODIFIY';
3486 case 'expensereport':
3487 $trigger_name =
'EXPENSE_REPORT_MODIFY';
3490 $trigger_name = strtoupper($this->element) .
'_MODIFY';
3492 $ret = $this->call_trigger($trigger_name, $user);
3499 $this->error = $this->db->lasterror();
3516 return $this->update_note($note,
'_public');
3530 public function update_price($exclspec = 0, $roundingadjust =
'none', $nodatabaseupdate = 0, $seller =
null)
3533 global $conf, $hookmanager, $action;
3535 $parameters = array(
'exclspec' => $exclspec,
'roundingadjust' => $roundingadjust,
'nodatabaseupdate' => $nodatabaseupdate,
'seller' => $seller);
3536 $reshook = $hookmanager->executeHooks(
'updateTotalPrice', $parameters, $this, $action);
3539 } elseif ($reshook < 0) {
3545 if ($this->element ==
'propal') {
3546 $MODULE =
"MODULE_DISALLOW_UPDATE_PRICE_PROPOSAL";
3547 } elseif ($this->element ==
'commande' || $this->element ==
'order') {
3548 $MODULE =
"MODULE_DISALLOW_UPDATE_PRICE_ORDER";
3549 } elseif ($this->element ==
'facture' || $this->element ==
'invoice') {
3550 $MODULE =
"MODULE_DISALLOW_UPDATE_PRICE_INVOICE";
3551 } elseif ($this->element ==
'facture_fourn' || $this->element ==
'supplier_invoice' || $this->element ==
'invoice_supplier' || $this->element ==
'invoice_supplier_rec') {
3552 $MODULE =
"MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_INVOICE";
3553 } elseif ($this->element ==
'order_supplier' || $this->element ==
'supplier_order') {
3554 $MODULE =
"MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_ORDER";
3555 } elseif ($this->element ==
'supplier_proposal') {
3556 $MODULE =
"MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_PROPOSAL";
3559 if (!empty($MODULE)) {
3560 if (!empty($conf->global->$MODULE)) {
3561 $modsactivated = explode(
',', $conf->global->$MODULE);
3562 foreach ($modsactivated as $mod) {
3563 if (isModEnabled($mod)) {
3570 include_once DOL_DOCUMENT_ROOT.
'/core/lib/price.lib.php';
3572 $forcedroundingmode = $roundingadjust;
3573 if ($forcedroundingmode ==
'auto' && isset($conf->global->MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND)) {
3575 } elseif ($forcedroundingmode ==
'auto') {
3576 $forcedroundingmode =
'0';
3581 $multicurrency_tx = !empty($this->multicurrency_tx) ? $this->multicurrency_tx : 1;
3584 $fieldtva =
'total_tva';
3585 $fieldlocaltax1 =
'total_localtax1';
3586 $fieldlocaltax2 =
'total_localtax2';
3587 $fieldup =
'subprice';
3588 if ($this->element ==
'facture_fourn' || $this->element ==
'invoice_supplier') {
3592 if ($this->element ==
'invoice_supplier_rec') {
3595 if ($this->element ==
'expensereport') {
3596 $fieldup =
'value_unit';
3599 $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,";
3600 $sql .=
' tva_tx as vatrate, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type, info_bits, product_type';
3601 if ($this->table_element_line ==
'facturedet') {
3602 $sql .=
', situation_percent';
3604 $sql .=
', multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc';
3605 $sql .=
" FROM ".$this->db->prefix().$this->table_element_line;
3606 $sql .=
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
3608 $product_field =
'product_type';
3609 if ($this->table_element_line ==
'contratdet') {
3610 $product_field =
'';
3612 if ($product_field) {
3613 $sql .=
" AND ".$product_field.
" <> 9";
3616 $sql .=
' ORDER by rowid';
3618 dol_syslog(get_class($this).
"::update_price", LOG_DEBUG);
3620 $resql = $this->db->query($sql);
3622 $this->total_ht = 0;
3623 $this->total_tva = 0;
3624 $this->total_localtax1 = 0;
3625 $this->total_localtax2 = 0;
3626 $this->total_ttc = 0;
3627 $total_ht_by_vats = array();
3628 $total_tva_by_vats = array();
3629 $total_ttc_by_vats = array();
3630 $this->multicurrency_total_ht = 0;
3631 $this->multicurrency_total_tva = 0;
3632 $this->multicurrency_total_ttc = 0;
3636 $num = $this->db->num_rows($resql);
3639 $obj = $this->db->fetch_object($resql);
3642 $parameters = array(
'fk_element' => $obj->rowid);
3643 $reshook = $hookmanager->executeHooks(
'changeRoundingMode', $parameters, $this, $action);
3645 if (empty($reshook) && $forcedroundingmode ==
'0') {
3647 $localtax_array = array($obj->localtax1_type, $obj->localtax1_tx, $obj->localtax2_type, $obj->localtax2_tx);
3648 $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);
3650 $diff_when_using_price_ht =
price2num($tmpcal[1] - $obj->total_tva,
'MT', 1);
3651 $diff_on_current_total =
price2num($obj->total_ttc - $obj->total_ht - $obj->total_tva - $obj->total_localtax1 - $obj->total_localtax2,
'MT', 1);
3655 if ($diff_on_current_total) {
3657 $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);
3658 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);
3659 $resqlfix = $this->db->query($sqlfix);
3663 $obj->total_tva = $tmpcal[1];
3664 $obj->total_ttc = $tmpcal[2];
3665 } elseif ($diff_when_using_price_ht && $roundingadjust ==
'0') {
3668 $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);
3669 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);
3670 $resqlfix = $this->db->query($sqlfix);
3674 $obj->total_tva = $tmpcal[1];
3675 $obj->total_ttc = $tmpcal[2];
3679 $this->total_ht += $obj->total_ht;
3680 $this->total_tva += $obj->total_tva;
3681 $this->total_localtax1 += $obj->total_localtax1;
3682 $this->total_localtax2 += $obj->total_localtax2;
3683 $this->total_ttc += $obj->total_ttc;
3684 $this->multicurrency_total_ht += $obj->multicurrency_total_ht;
3685 $this->multicurrency_total_tva += $obj->multicurrency_total_tva;
3686 $this->multicurrency_total_ttc += $obj->multicurrency_total_ttc;
3688 if (!isset($total_ht_by_vats[$obj->vatrate])) {
3689 $total_ht_by_vats[$obj->vatrate] = 0;
3691 if (!isset($total_tva_by_vats[$obj->vatrate])) {
3692 $total_tva_by_vats[$obj->vatrate] = 0;
3694 if (!isset($total_ttc_by_vats[$obj->vatrate])) {
3695 $total_ttc_by_vats[$obj->vatrate] = 0;
3697 $total_ht_by_vats[$obj->vatrate] += $obj->total_ht;
3698 $total_tva_by_vats[$obj->vatrate] += $obj->total_tva;
3699 $total_ttc_by_vats[$obj->vatrate] += $obj->total_ttc;
3701 if ($forcedroundingmode ==
'1') {
3702 $tmpvat =
price2num($total_ht_by_vats[$obj->vatrate] * $obj->vatrate / 100,
'MT', 1);
3703 $diff =
price2num($total_tva_by_vats[$obj->vatrate] - $tmpvat,
'MT', 1);
3706 if (abs($diff) > (10 * pow(10, -1 *
getDolGlobalInt(
'MAIN_MAX_DECIMALS_TOT', 0)))) {
3708 $errmsg =
'A rounding difference was detected into TOTAL but is too high to be corrected. Some data in your lines may be corrupted. Try to edit each line manually to fix this before restarting.';
3710 $this->error = $errmsg;
3714 $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);
3715 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);
3717 $resqlfix = $this->db->query($sqlfix);
3723 $this->total_tva = (float)
price2num($this->total_tva - $diff,
'', 1);
3724 $this->total_ttc = (float)
price2num($this->total_ttc - $diff,
'', 1);
3725 $total_tva_by_vats[$obj->vatrate] = (float)
price2num($total_tva_by_vats[$obj->vatrate] - $diff,
'', 1);
3726 $total_ttc_by_vats[$obj->vatrate] = (float)
price2num($total_ttc_by_vats[$obj->vatrate] - $diff,
'', 1);
3734 $this->total_ttc += isset($this->revenuestamp) ? $this->revenuestamp : 0;
3735 $this->multicurrency_total_ttc += isset($this->revenuestamp) ? ($this->revenuestamp * $multicurrency_tx) : 0;
3738 if (!empty($this->situation_cycle_ref) && $this->situation_counter > 1 && method_exists($this,
'get_prev_sits') && $this->
type != $this::TYPE_CREDIT_NOTE) {
3739 $prev_sits = $this->get_prev_sits();
3741 foreach ($prev_sits as $sit) {
3742 $this->total_ht -= $sit->total_ht;
3743 $this->total_tva -= $sit->total_tva;
3744 $this->total_localtax1 -= $sit->total_localtax1;
3745 $this->total_localtax2 -= $sit->total_localtax2;
3746 $this->total_ttc -= $sit->total_ttc;
3747 $this->multicurrency_total_ht -= $sit->multicurrency_total_ht;
3748 $this->multicurrency_total_tva -= $sit->multicurrency_total_tva;
3749 $this->multicurrency_total_ttc -= $sit->multicurrency_total_ttc;
3754 $this->total_ht = (float)
price2num($this->total_ht);
3755 $this->total_tva = (float)
price2num($this->total_tva);
3756 $this->total_localtax1 = (float)
price2num($this->total_localtax1);
3757 $this->total_localtax2 = (float)
price2num($this->total_localtax2);
3758 $this->total_ttc = (float)
price2num($this->total_ttc);
3760 $this->db->free($resql);
3763 $fieldht =
'total_ht';
3765 $fieldlocaltax1 =
'localtax1';
3766 $fieldlocaltax2 =
'localtax2';
3767 $fieldttc =
'total_ttc';
3769 if (in_array($this->element, array(
'propal',
'commande',
'facture',
'facturerec',
'supplier_proposal',
'order_supplier',
'facture_fourn',
'invoice_supplier',
'invoice_supplier_rec',
'expensereport'))) {
3770 $fieldtva =
'total_tva';
3773 if (!$error && empty($nodatabaseupdate)) {
3774 $sql =
"UPDATE ".$this->db->prefix().$this->table_element.
' SET';
3775 $sql .=
" ".$fieldht.
" = ".((float)
price2num($this->total_ht,
'MT', 1)).
",";
3776 $sql .=
" ".$fieldtva.
" = ".((float)
price2num($this->total_tva,
'MT', 1)).
",";
3777 $sql .=
" ".$fieldlocaltax1.
" = ".((float)
price2num($this->total_localtax1,
'MT', 1)).
",";
3778 $sql .=
" ".$fieldlocaltax2.
" = ".((float)
price2num($this->total_localtax2,
'MT', 1)).
",";
3779 $sql .=
" ".$fieldttc.
" = ".((float)
price2num($this->total_ttc,
'MT', 1));
3780 $sql .=
", multicurrency_total_ht = ".((float)
price2num($this->multicurrency_total_ht,
'MT', 1));
3781 $sql .=
", multicurrency_total_tva = ".((float)
price2num($this->multicurrency_total_tva,
'MT', 1));
3782 $sql .=
", multicurrency_total_ttc = ".((float)
price2num($this->multicurrency_total_ttc,
'MT', 1));
3783 $sql .=
" WHERE rowid = ".((int) $this->
id);
3785 dol_syslog(get_class($this).
"::update_price", LOG_DEBUG);
3786 $resql = $this->db->query($sql);
3790 $this->error = $this->db->lasterror();
3791 $this->errors[] = $this->db->lasterror();
3796 $this->db->commit();
3799 $this->db->rollback();
3819 public function add_object_linked($origin =
null, $origin_id =
null, $f_user =
null, $notrigger = 0)
3822 global $user, $hookmanager, $action;
3823 $origin = (!empty($origin) ? $origin : $this->origin);
3824 $origin_id = (!empty($origin_id) ? $origin_id : $this->origin_id);
3825 $f_user = isset($f_user) ? $f_user : $user;
3828 if ($origin ==
'order') {
3829 $origin =
'commande';
3831 if ($origin ==
'invoice') {
3832 $origin =
'facture';
3834 if ($origin ==
'invoice_template') {
3835 $origin =
'facturerec';
3837 if ($origin ==
'supplierorder') {
3838 $origin =
'order_supplier';
3843 $coremodule = array(
'knowledgemanagement',
'partnership',
'workstation',
'ticket',
'recruitment',
'eventorganization',
'asset');
3845 $targettype = ((!empty($this->module) && ! in_array($this->module, $coremodule)) ? $this->module.
'_' :
'').$this->element;
3847 $parameters = array(
'targettype'=>$targettype);
3849 $reshook = $hookmanager->executeHooks(
'setLinkedObjectSourceTargetType', $parameters, $this, $action);
3851 if (!empty($hookmanager->resArray[
'targettype'])) $targettype = $hookmanager->resArray[
'targettype'];
3857 $sql =
"INSERT INTO " . $this->db->prefix() .
"element_element (";
3858 $sql .=
"fk_source";
3859 $sql .=
", sourcetype";
3860 $sql .=
", fk_target";
3861 $sql .=
", targettype";
3862 $sql .=
") VALUES (";
3863 $sql .= ((int) $origin_id);
3864 $sql .=
", '" . $this->db->escape($origin) .
"'";
3865 $sql .=
", " . ((int) $this->
id);
3866 $sql .=
", '" . $this->db->escape($targettype) .
"'";
3869 dol_syslog(get_class($this) .
"::add_object_linked", LOG_DEBUG);
3870 if ($this->db->query($sql)) {
3873 $this->context[
'link_origin'] = $origin;
3874 $this->context[
'link_origin_id'] = $origin_id;
3875 $result = $this->call_trigger(
'OBJECT_LINK_INSERT', $f_user);
3882 $this->error = $this->db->lasterror();
3887 $this->db->commit();
3890 $this->db->rollback();
3917 public function fetchObjectLinked($sourceid =
null, $sourcetype =
'', $targetid =
null, $targettype =
'', $clause =
'OR', $alsosametype = 1, $orderby =
'sourcetype', $loadalsoobjects = 1)
3919 global $conf, $hookmanager, $action;
3923 if ($this->
id > 0 && !empty($this->linkedObjectsFullLoaded[$this->
id])) {
3927 $this->linkedObjectsIds = array();
3928 $this->linkedObjects = array();
3930 $justsource =
false;
3931 $justtarget =
false;
3932 $withtargettype =
false;
3933 $withsourcetype =
false;
3935 $parameters = array(
'sourcetype'=>$sourcetype,
'sourceid'=>$sourceid,
'targettype'=>$targettype,
'targetid'=>$targetid);
3937 $reshook = $hookmanager->executeHooks(
'setLinkedObjectSourceTargetType', $parameters, $this, $action);
3939 if (!empty($hookmanager->resArray[
'sourcetype'])) $sourcetype = $hookmanager->resArray[
'sourcetype'];
3940 if (!empty($hookmanager->resArray[
'sourceid'])) $sourceid = $hookmanager->resArray[
'sourceid'];
3941 if (!empty($hookmanager->resArray[
'targettype'])) $targettype = $hookmanager->resArray[
'targettype'];
3942 if (!empty($hookmanager->resArray[
'targetid'])) $targetid = $hookmanager->resArray[
'targetid'];
3945 if (!empty($sourceid) && !empty($sourcetype) && empty($targetid)) {
3947 if (!empty($targettype)) {
3948 $withtargettype =
true;
3951 if (!empty($targetid) && !empty($targettype) && empty($sourceid)) {
3953 if (!empty($sourcetype)) {
3954 $withsourcetype =
true;
3958 $sourceid = (!empty($sourceid) ? $sourceid : $this->id);
3959 $targetid = (!empty($targetid) ? $targetid : $this->id);
3960 $sourcetype = (!empty($sourcetype) ? $sourcetype : $this->element);
3961 $targettype = (!empty($targettype) ? $targettype : $this->element);
3970 $sql =
"SELECT rowid, fk_source, sourcetype, fk_target, targettype";
3971 $sql .=
" FROM ".$this->db->prefix().
"element_element";
3973 if ($justsource || $justtarget) {
3975 $sql .=
"fk_source = ".((int) $sourceid).
" AND sourcetype = '".$this->db->escape($sourcetype).
"'";
3976 if ($withtargettype) {
3977 $sql .=
" AND targettype = '".$this->db->escape($targettype).
"'";
3979 } elseif ($justtarget) {
3980 $sql .=
"fk_target = ".((int) $targetid).
" AND targettype = '".$this->db->escape($targettype).
"'";
3981 if ($withsourcetype) {
3982 $sql .=
" AND sourcetype = '".$this->db->escape($sourcetype).
"'";
3986 $sql .=
"(fk_source = ".((int) $sourceid).
" AND sourcetype = '".$this->db->escape($sourcetype).
"')";
3987 $sql .=
" ".$clause.
" (fk_target = ".((int) $targetid).
" AND targettype = '".$this->db->escape($targettype).
"')";
3988 if ($loadalsoobjects && $this->
id > 0 && $sourceid == $this->
id && $sourcetype == $this->element && $targetid == $this->
id && $targettype == $this->element && $clause ==
'OR') {
3989 $this->linkedObjectsFullLoaded[$this->id] =
true;
3992 $sql .=
" ORDER BY ".$orderby;
3994 dol_syslog(get_class($this).
"::fetchObjectLink", LOG_DEBUG);
3995 $resql = $this->db->query($sql);
3997 $num = $this->db->num_rows($resql);
4000 $obj = $this->db->fetch_object($resql);
4001 if ($justsource || $justtarget) {
4003 $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
4004 } elseif ($justtarget) {
4005 $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
4008 if ($obj->fk_source == $sourceid && $obj->sourcetype == $sourcetype) {
4009 $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
4011 if ($obj->fk_target == $targetid && $obj->targettype == $targettype) {
4012 $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
4018 if (!empty($this->linkedObjectsIds)) {
4019 $tmparray = $this->linkedObjectsIds;
4020 foreach ($tmparray as $objecttype => $objectids) {
4022 $module = $element = $subelement = $objecttype;
4024 if ($objecttype !=
'supplier_proposal' && $objecttype !=
'order_supplier' && $objecttype !=
'invoice_supplier'
4025 && preg_match(
'/^([^_]+)_([^_]+)/i', $objecttype, $regs)) {
4026 $module = $element = $regs[1];
4027 $subelement = $regs[2];
4030 $classpath = $element.
'/class';
4032 if ($objecttype ==
'facture') {
4033 $classpath =
'compta/facture/class';
4034 } elseif ($objecttype ==
'facturerec') {
4035 $classpath =
'compta/facture/class';
4036 $module =
'facture';
4037 } elseif ($objecttype ==
'propal') {
4038 $classpath =
'comm/propal/class';
4039 } elseif ($objecttype ==
'supplier_proposal') {
4040 $classpath =
'supplier_proposal/class';
4041 } elseif ($objecttype ==
'shipping') {
4042 $classpath =
'expedition/class';
4043 $subelement =
'expedition';
4044 $module =
'expedition';
4045 } elseif ($objecttype ==
'delivery') {
4046 $classpath =
'delivery/class';
4047 $subelement =
'delivery';
4048 $module =
'delivery_note';
4049 } elseif ($objecttype ==
'invoice_supplier' || $objecttype ==
'order_supplier') {
4050 $classpath =
'fourn/class';
4051 $module =
'fournisseur';
4052 } elseif ($objecttype ==
'fichinter') {
4053 $classpath =
'fichinter/class';
4054 $subelement =
'fichinter';
4055 $module =
'ficheinter';
4056 } elseif ($objecttype ==
'subscription') {
4057 $classpath =
'adherents/class';
4058 $module =
'adherent';
4059 } elseif ($objecttype ==
'contact') {
4060 $module =
'societe';
4061 } elseif ($objecttype ==
'action') {
4063 $subelement =
'actionComm';
4067 $classfile = strtolower($subelement);
4068 $classname = ucfirst($subelement);
4070 if ($objecttype ==
'order') {
4071 $classfile =
'commande';
4072 $classname =
'Commande';
4073 } elseif ($objecttype ==
'invoice_supplier') {
4074 $classfile =
'fournisseur.facture';
4075 $classname =
'FactureFournisseur';
4076 } elseif ($objecttype ==
'order_supplier') {
4077 $classfile =
'fournisseur.commande';
4078 $classname =
'CommandeFournisseur';
4079 } elseif ($objecttype ==
'supplier_proposal') {
4080 $classfile =
'supplier_proposal';
4081 $classname =
'SupplierProposal';
4082 } elseif ($objecttype ==
'facturerec') {
4083 $classfile =
'facture-rec';
4084 $classname =
'FactureRec';
4085 } elseif ($objecttype ==
'subscription') {
4086 $classfile =
'subscription';
4087 $classname =
'Subscription';
4088 } elseif ($objecttype ==
'project' || $objecttype ==
'projet') {
4089 $classpath =
'projet/class';
4090 $classfile =
'project';
4091 $classname =
'Project';
4092 } elseif ($objecttype ==
'conferenceorboothattendee') {
4093 $classpath =
'eventorganization/class';
4094 $classfile =
'conferenceorboothattendee';
4095 $classname =
'ConferenceOrBoothAttendee';
4096 $module =
'eventorganization';
4097 } elseif ($objecttype ==
'conferenceorbooth') {
4098 $classpath =
'eventorganization/class';
4099 $classfile =
'conferenceorbooth';
4100 $classname =
'ConferenceOrBooth';
4101 $module =
'eventorganization';
4102 } elseif ($objecttype ==
'mo') {
4103 $classpath =
'mrp/class';
4110 if (isModEnabled($module) && (($element != $this->element) || $alsosametype)) {
4111 if ($loadalsoobjects && (is_numeric($loadalsoobjects) || ($loadalsoobjects === $objecttype))) {
4114 if (class_exists($classname)) {
4115 foreach ($objectids as $i => $objectid) {
4116 $object =
new $classname($this->db);
4117 $ret = $object->fetch($objectid);
4119 $this->linkedObjects[$objecttype][$i] = $object;
4125 unset($this->linkedObjectsIds[$objecttype]);
4144 if ($this->
id > 0 && !empty($this->linkedObjectsFullLoaded[$this->
id])) {
4145 unset($this->linkedObjectsFullLoaded[$this->
id]);
4163 public function updateObjectLinked($sourceid =
null, $sourcetype =
'', $targetid =
null, $targettype =
'', $f_user =
null, $notrigger = 0)
4166 $updatesource =
false;
4167 $updatetarget =
false;
4168 $f_user = isset($f_user) ? $f_user : $user;
4170 if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) {
4171 $updatesource =
true;
4172 } elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) {
4173 $updatetarget =
true;
4179 $sql =
"UPDATE " . $this->db->prefix() .
"element_element SET ";
4180 if ($updatesource) {
4181 $sql .=
"fk_source = " . ((int) $sourceid);
4182 $sql .=
", sourcetype = '" . $this->db->escape($sourcetype) .
"'";
4183 $sql .=
" WHERE fk_target = " . ((int) $this->
id);
4184 $sql .=
" AND targettype = '" . $this->db->escape($this->element) .
"'";
4185 } elseif ($updatetarget) {
4186 $sql .=
"fk_target = " . ((int) $targetid);
4187 $sql .=
", targettype = '" . $this->db->escape($targettype) .
"'";
4188 $sql .=
" WHERE fk_source = " . ((int) $this->
id);
4189 $sql .=
" AND sourcetype = '" . $this->db->escape($this->element) .
"'";
4192 dol_syslog(get_class($this) .
"::updateObjectLinked", LOG_DEBUG);
4193 if ($this->db->query($sql)) {
4196 $this->context[
'link_source_id'] = $sourceid;
4197 $this->context[
'link_source_type'] = $sourcetype;
4198 $this->context[
'link_target_id'] = $targetid;
4199 $this->context[
'link_target_type'] = $targettype;
4200 $result = $this->call_trigger(
'OBJECT_LINK_MODIFY', $f_user);
4207 $this->error = $this->db->lasterror();
4212 $this->db->commit();
4215 $this->db->rollback();
4233 public function deleteObjectLinked($sourceid =
null, $sourcetype =
'', $targetid =
null, $targettype =
'', $rowid =
'', $f_user =
null, $notrigger = 0)
4236 $deletesource =
false;
4237 $deletetarget =
false;
4238 $f_user = isset($f_user) ? $f_user : $user;
4240 if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) {
4241 $deletesource =
true;
4242 } elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) {
4243 $deletetarget =
true;
4246 $sourceid = (!empty($sourceid) ? $sourceid : $this->id);
4247 $sourcetype = (!empty($sourcetype) ? $sourcetype : $this->element);
4248 $targetid = (!empty($targetid) ? $targetid : $this->id);
4249 $targettype = (!empty($targettype) ? $targettype : $this->element);
4255 $this->context[
'link_id'] = $rowid;
4256 $this->context[
'link_source_id'] = $sourceid;
4257 $this->context[
'link_source_type'] = $sourcetype;
4258 $this->context[
'link_target_id'] = $targetid;
4259 $this->context[
'link_target_type'] = $targettype;
4260 $result = $this->call_trigger(
'OBJECT_LINK_DELETE', $f_user);
4268 $sql =
"DELETE FROM " . $this->db->prefix() .
"element_element";
4271 $sql .=
" rowid = " . ((int) $rowid);
4273 if ($deletesource) {
4274 $sql .=
" fk_source = " . ((int) $sourceid) .
" AND sourcetype = '" . $this->db->escape($sourcetype) .
"'";
4275 $sql .=
" AND fk_target = " . ((int) $this->
id) .
" AND targettype = '" . $this->db->escape($this->element) .
"'";
4276 } elseif ($deletetarget) {
4277 $sql .=
" fk_target = " . ((int) $targetid) .
" AND targettype = '" . $this->db->escape($targettype) .
"'";
4278 $sql .=
" AND fk_source = " . ((int) $this->
id) .
" AND sourcetype = '" . $this->db->escape($this->element) .
"'";
4280 $sql .=
" (fk_source = " . ((int) $this->
id) .
" AND sourcetype = '" . $this->db->escape($this->element) .
"')";
4282 $sql .=
" (fk_target = " . ((int) $this->
id) .
" AND targettype = '" . $this->db->escape($this->element) .
"')";
4286 dol_syslog(get_class($this) .
"::deleteObjectLinked", LOG_DEBUG);
4287 if (!$this->db->query($sql)) {
4288 $this->error = $this->db->lasterror();
4289 $this->errors[] = $this->error;
4295 $this->db->commit();
4298 $this->db->rollback();
4314 if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
4320 $sql =
"SELECT ".$field_select.
" FROM ".$db->prefix().$table_element.
" WHERE ".$field_where.
" = ".((int) $fk_object_where);
4321 $resql = $db->query($sql);
4324 if (!empty($resql)) {
4325 while ($res = $db->fetch_object($resql)) {
4326 $TRes[] = $res->{$field_select};
4343 if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
4349 $sql =
"DELETE FROM ".$db->prefix().$table_element.
" WHERE ".$field_where.
" = ".((int) $fk_object_where);
4350 $resql = $db->query($sql);
4352 if (empty($resql)) {
4369 public function setStatut($status, $elementId =
null, $elementType =
'', $trigkey =
'', $fieldstatus =
'fk_statut')
4371 global $user, $langs, $conf;
4373 $savElementId = $elementId;
4375 $elementId = (!empty($elementId) ? $elementId : $this->id);
4376 $elementTable = (!empty($elementType) ? $elementType : $this->table_element);
4380 if ($elementTable ==
'facture_rec') {
4381 $fieldstatus =
"suspended";
4383 if ($elementTable ==
'mailing') {
4384 $fieldstatus =
"statut";
4386 if ($elementTable ==
'cronjob') {
4387 $fieldstatus =
"status";
4389 if ($elementTable ==
'user') {
4390 $fieldstatus =
"statut";
4392 if ($elementTable ==
'expensereport') {
4393 $fieldstatus =
"fk_statut";
4395 if ($elementTable ==
'commande_fournisseur_dispatch') {
4396 $fieldstatus =
"status";
4398 if (isset($this->fields) && is_array($this->fields) && array_key_exists(
'status', $this->fields)) {
4399 $fieldstatus =
'status';
4402 $sql =
"UPDATE ".$this->db->prefix().$elementTable;
4403 $sql .=
" SET ".$fieldstatus.
" = ".((int) $status);
4406 if ($status == 1 && in_array($elementTable, array(
'expensereport',
'inventory'))) {
4407 $sql .=
", fk_user_valid = ".((int) $user->id);
4409 if ($status == 1 && in_array($elementTable, array(
'expensereport'))) {
4410 $sql .=
", date_valid = '".$this->db->idate(
dol_now()).
"'";
4412 if ($status == 1 && in_array($elementTable, array(
'inventory'))) {
4413 $sql .=
", date_validation = '".$this->db->idate(
dol_now()).
"'";
4415 $sql .=
" WHERE rowid = ".((int) $elementId);
4416 $sql .=
" AND ".$fieldstatus.
" <> ".((int) $status);
4418 dol_syslog(get_class($this).
"::setStatut", LOG_DEBUG);
4419 $resql = $this->db->query($sql);
4423 $nb_rows_affected = $this->db->affected_rows($resql);
4425 if ($nb_rows_affected > 0) {
4426 if (empty($trigkey)) {
4428 if ($this->element ==
'supplier_proposal' && $status == 2) {
4429 $trigkey =
'SUPPLIER_PROPOSAL_SIGN';
4431 if ($this->element ==
'supplier_proposal' && $status == 3) {
4432 $trigkey =
'SUPPLIER_PROPOSAL_REFUSE';
4434 if ($this->element ==
'supplier_proposal' && $status == 4) {
4435 $trigkey =
'SUPPLIER_PROPOSAL_CLOSE';
4437 if ($this->element ==
'fichinter' && $status == 3) {
4438 $trigkey =
'FICHINTER_CLASSIFY_DONE';
4440 if ($this->element ==
'fichinter' && $status == 2) {
4441 $trigkey =
'FICHINTER_CLASSIFY_BILLED';
4443 if ($this->element ==
'fichinter' && $status == 1) {
4444 $trigkey =
'FICHINTER_CLASSIFY_UNBILLED';
4450 $result = $this->call_trigger($trigkey, $user);
4461 $this->db->commit();
4463 if (empty($savElementId)) {
4465 if ($fieldstatus ==
'tosell') {
4466 $this->status = $status;
4467 } elseif ($fieldstatus ==
'tobuy') {
4468 $this->status_buy = $status;
4471 $this->status = $status;
4477 $this->db->rollback();
4478 dol_syslog(get_class($this).
"::setStatut ".$this->error, LOG_ERR);
4482 $this->error = $this->db->lasterror();
4483 $this->db->rollback();
4500 if (empty($id) && empty($ref)) {
4503 if (!empty($conf->global->MAIN_DISABLE_CANVAS)) {
4510 $sql =
"SELECT rowid, canvas";
4511 $sql .=
" FROM ".$this->db->prefix().$this->table_element;
4512 $sql .=
" WHERE entity IN (".getEntity($this->element).
")";
4514 $sql .=
" AND rowid = ".((int) $id);
4517 $sql .=
" AND ref = '".$this->db->escape($ref).
"'";
4520 $resql = $this->db->query($sql);
4522 $obj = $this->db->fetch_object($resql);
4524 $this->canvas = $obj->canvas;
4544 $sql =
"SELECT special_code FROM ".$this->db->prefix().$this->table_element_line;
4545 $sql .=
" WHERE rowid = ".((int) $lineid);
4546 $resql = $this->db->query($sql);
4548 $row = $this->db->fetch_row($resql);
4549 return (!empty($row[0]) ? $row[0] : 0);
4572 if (!isset($this->childtables) || !is_array($this->childtables) || count($this->childtables) == 0) {
4573 dol_print_error(
'Called isObjectUsed on a class with property this->childtables not defined');
4577 $arraytoscan = $this->childtables;
4579 $tmparray = array_keys($this->childtables);
4580 if (is_numeric($tmparray[0])) {
4581 $arraytoscan = array_flip($this->childtables);
4586 foreach ($arraytoscan as $table => $element) {
4589 $sql =
"SELECT COUNT(*) as nb";
4590 $sql.=
" FROM ".$this->db->prefix().$table.
" as c";
4591 if (!empty($element[
'parent']) && !empty($element[
'parentkey'])) {
4592 $sql.=
", ".$this->db->prefix().$element[
'parent'].
" as p";
4594 if (!empty($element[
'fk_element'])) {
4595 $sql.=
" WHERE c.".$element[
'fk_element'].
" = ".((int) $id);
4597 $sql.=
" WHERE c.".$this->fk_element.
" = ".((int) $id);
4599 if (!empty($element[
'parent']) && !empty($element[
'parentkey'])) {
4600 $sql.=
" AND c.".$element[
'parentkey'].
" = p.rowid";
4602 if (!empty($element[
'parent']) && !empty($element[
'parenttypefield']) && !empty($element[
'parenttypevalue'])) {
4603 $sql.=
" AND c.".$element[
'parenttypefield'].
" = '".$this->db->escape($element[
'parenttypevalue']).
"'";
4605 if (!empty($entity)) {
4606 if (!empty($element[
'parent']) && !empty($element[
'parentkey'])) {
4607 $sql.=
" AND p.entity = ".((int) $entity);
4609 $sql.=
" AND c.entity = ".((int) $entity);
4613 $resql = $this->db->query($sql);
4615 $obj = $this->db->fetch_object($resql);
4617 $langs->load(
"errors");
4619 $haschild += $obj->nb;
4620 if (is_numeric($element)) {
4621 $this->errors[] = $langs->transnoentitiesnoconv(
"ErrorRecordHasAtLeastOneChildOfType", method_exists($this,
'getNomUrl') ? $this->getNomUrl() : $this->ref, $table);
4622 } elseif (is_string($element)) {
4623 $this->errors[] = $langs->transnoentitiesnoconv(
"ErrorRecordHasAtLeastOneChildOfType", method_exists($this,
'getNomUrl') ? $this->getNomUrl() : $this->ref, $langs->transnoentitiesnoconv($element));
4625 $this->errors[] = $langs->transnoentitiesnoconv(
"ErrorRecordHasAtLeastOneChildOfType", method_exists($this,
'getNomUrl') ? $this->getNomUrl() : $this->ref, $langs->transnoentitiesnoconv($element[
'name']));
4630 $this->errors[] = $this->db->lasterror();
4634 if ($haschild > 0) {
4635 $this->errors[] =
"ErrorRecordHasChildren";
4652 foreach ($this->lines as $key => $val) {
4654 if ($predefined == -1) {
4657 if ($predefined == 1 && $val->fk_product > 0) {
4660 if ($predefined == 0 && $val->fk_product <= 0) {
4663 if ($predefined == 2 && $val->fk_product > 0 && $val->product_type == 0) {
4666 if ($predefined == 3 && $val->fk_product > 0 && $val->product_type == 1) {
4673 dol_syslog(get_class($this).
'::hasProductsOrServices we found '.$nb.
' qualified lines of products/servcies');
4684 if (!empty($this->table_element_line) ) {
4685 $total_discount = 0.00;
4687 $sql =
"SELECT subprice as pu_ht, qty, remise_percent, total_ht";
4688 $sql .=
" FROM ".$this->db->prefix().$this->table_element_line;
4689 $sql .=
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
4691 dol_syslog(get_class($this).
'::getTotalDiscount', LOG_DEBUG);
4692 $resql = $this->db->query($sql);
4694 $num = $this->db->num_rows($resql);
4697 $obj = $this->db->fetch_object($resql);
4699 $pu_ht = $obj->pu_ht;
4701 $total_ht = $obj->total_ht;
4703 $total_discount_line = floatval(
price2num(($pu_ht * $qty) - $total_ht,
'MT'));
4704 $total_discount += $total_discount_line;
4733 foreach ($this->lines as $line) {
4734 if (isset($line->qty_asked)) {
4735 if (empty($totalOrdered)) {
4738 $totalOrdered += $line->qty_asked;
4740 if (isset($line->qty_shipped)) {
4741 if (empty($totalToShip)) {
4744 $totalToShip += $line->qty_shipped;
4745 } elseif ($line->element ==
'commandefournisseurdispatch' && isset($line->qty)) {
4746 if (empty($totalToShip)) {
4749 $totalToShip += $line->qty;
4753 if ($this->element ==
'shipping') {
4755 $qty = $line->qty_shipped ? $line->qty_shipped : 0;
4757 $qty = $line->qty ? $line->qty : 0;
4760 $weight = !empty($line->weight) ? $line->weight : 0;
4761 ($weight == 0 && !empty($line->product->weight)) ? $weight = $line->product->weight : 0;
4762 $volume = !empty($line->volume) ? $line->volume : 0;
4763 ($volume == 0 && !empty($line->product->volume)) ? $volume = $line->product->volume : 0;
4765 $weight_units = !empty($line->weight_units) ? $line->weight_units : 0;
4766 ($weight_units == 0 && !empty($line->product->weight_units)) ? $weight_units = $line->product->weight_units : 0;
4767 $volume_units = !empty($line->volume_units) ? $line->volume_units : 0;
4768 ($volume_units == 0 && !empty($line->product->volume_units)) ? $volume_units = $line->product->volume_units : 0;
4772 if (!empty($weight_units)) {
4773 $weightUnit = $weight_units;
4775 if (!empty($volume_units)) {
4776 $volumeUnit = $volume_units;
4779 if (empty($totalWeight)) {
4782 if (empty($totalVolume)) {
4787 if ($weight_units < 50) {
4788 $trueWeightUnit = pow(10, $weightUnit);
4789 $totalWeight += $weight * $qty * $trueWeightUnit;
4791 if ($weight_units == 99) {
4793 $trueWeightUnit = 0.45359237;
4794 $totalWeight += $weight * $qty * $trueWeightUnit;
4795 } elseif ($weight_units == 98) {
4797 $trueWeightUnit = 0.0283495;
4798 $totalWeight += $weight * $qty * $trueWeightUnit;
4800 $totalWeight += $weight * $qty;
4803 if ($volume_units < 50) {
4805 $trueVolumeUnit = pow(10, $volumeUnit);
4807 $totalVolume += $volume * $qty * $trueVolumeUnit;
4809 $totalVolume += $volume * $qty;
4813 return array(
'weight'=>$totalWeight,
'volume'=>$totalVolume,
'ordered'=>$totalOrdered,
'toship'=>$totalToShip);
4826 $extraparams = (!empty($this->extraparams) ? json_encode($this->extraparams) :
null);
4828 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
4829 $sql .=
" SET extraparams = ".(!empty($extraparams) ?
"'".$this->db->escape($extraparams).
"'" :
"null");
4830 $sql .=
" WHERE rowid = ".((int) $this->
id);
4832 dol_syslog(get_class($this).
"::setExtraParameters", LOG_DEBUG);
4833 $resql = $this->db->query($sql);
4835 $this->error = $this->db->lasterror();
4836 $this->db->rollback();
4839 $this->db->commit();
4862 global $conf, $user, $langs, $object, $hookmanager, $extrafields;
4866 if (!is_object($extrafields)) {
4867 require_once DOL_DOCUMENT_ROOT.
'/core/class/extrafields.class.php';
4870 $extrafields->fetch_name_optionals_label($this->table_element_line);
4875 $dirtpls = array_merge($conf->modules_parts[
'tpl'], array($defaulttpldir));
4876 foreach ($dirtpls as $module => $reldir) {
4877 if (!empty($module)) {
4880 $tpl = DOL_DOCUMENT_ROOT.$reldir.
'/objectline_create.tpl.php';
4883 if (empty($conf->file->strict_mode)) {
4884 $res = @include $tpl;
4886 $res = include $tpl;
4913 public function printObjectLines($action, $seller, $buyer, $selected = 0, $dateSelector = 0, $defaulttpldir =
'/core/tpl')
4915 global $conf, $hookmanager, $langs, $user, $form, $extrafields, $object;
4917 global $inputalsopricewithtax, $usemargins, $disableedit, $disablemove, $disableremove, $outputalsopricetotalwithtax;
4921 if (isModEnabled(
'margin') && !empty($this->element) && in_array($this->element, array(
'facture',
'facturerec',
'propal',
'commande'))) {
4925 $num = count($this->lines);
4928 if (!is_object($extrafields)) {
4929 require_once DOL_DOCUMENT_ROOT.
'/core/class/extrafields.class.php';
4932 $extrafields->fetch_name_optionals_label($this->table_element_line);
4934 $parameters = array(
'num'=>$num,
'dateSelector'=>$dateSelector,
'seller'=>$seller,
'buyer'=>$buyer,
'selected'=>$selected,
'table_element_line'=>$this->table_element_line);
4935 $reshook = $hookmanager->executeHooks(
'printObjectLineTitle', $parameters, $this, $action);
4936 if (empty($reshook)) {
4940 $dirtpls = array_merge($conf->modules_parts[
'tpl'], array($defaulttpldir));
4941 foreach ($dirtpls as $module => $reldir) {
4943 if (!empty($module)) {
4946 $tpl = DOL_DOCUMENT_ROOT.$reldir.
'/objectline_title.tpl.php';
4948 if (file_exists($tpl)) {
4949 if (empty($conf->file->strict_mode)) {
4950 $res = @include $tpl;
4952 $res = include $tpl;
4963 print
"<!-- begin printObjectLines() --><tbody>\n";
4964 foreach ($this->lines as $line) {
4966 $line->fetch_optionals();
4969 if (is_object($hookmanager)) {
4970 if (empty($line->fk_parent_line)) {
4971 $parameters = array(
'line'=>$line,
'num'=>$num,
'i'=>$i,
'dateSelector'=>$dateSelector,
'seller'=>$seller,
'buyer'=>$buyer,
'selected'=>$selected,
'table_element_line'=>$line->table_element,
'defaulttpldir'=>$defaulttpldir);
4972 $reshook = $hookmanager->executeHooks(
'printObjectLine', $parameters, $this, $action);
4974 $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,
'defaulttpldir'=>$defaulttpldir);
4975 $reshook = $hookmanager->executeHooks(
'printObjectSubLine', $parameters, $this, $action);
4978 if (empty($reshook)) {
4979 $this->printObjectLine($action, $line,
'', $num, $i, $dateSelector, $seller, $buyer, $selected, $extrafields, $defaulttpldir);
4984 print
"</tbody><!-- end printObjectLines() -->\n";
5004 public function printObjectLine($action, $line, $var, $num, $i, $dateSelector, $seller, $buyer, $selected = 0, $extrafields =
null, $defaulttpldir =
'/core/tpl')
5006 global $conf, $langs, $user, $object, $hookmanager;
5008 global $object_rights, $disableedit, $disablemove, $disableremove;
5010 $object_rights = $this->getRights();
5016 if ($action !=
'editline' || $selected != $line->id) {
5018 if (!empty($line->fk_product) && $line->fk_product > 0) {
5019 $product_static =
new Product($this->db);
5020 $product_static->fetch($line->fk_product);
5022 $product_static->ref = $line->ref;
5023 $product_static->label = !empty($line->label) ? $line->label :
"";
5025 $text = $product_static->getNomUrl(1);
5029 if (property_exists($this,
'socid') && !is_object($this->thirdparty)) {
5030 dol_print_error(
'',
'Error: Method printObjectLine was called on an object and object->fetch_thirdparty was not done before');
5034 $prod =
new Product($this->db);
5035 $prod->fetch($line->fk_product);
5037 $outputlangs = $langs;
5039 if (empty($newlang) &&
GETPOST(
'lang_id',
'aZ09')) {
5040 $newlang =
GETPOST(
'lang_id',
'aZ09');
5042 if (!empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE) && empty($newlang) && is_object($this->thirdparty)) {
5043 $newlang = $this->thirdparty->default_lang;
5045 if (!empty($newlang)) {
5046 $outputlangs =
new Translate(
"", $conf);
5047 $outputlangs->setDefaultLang($newlang);
5050 $label = (!empty($prod->multilangs[$outputlangs->defaultlang][
"label"])) ? $prod->multilangs[$outputlangs->defaultlang][
"label"] : $line->product_label;
5052 $label = $line->product_label;
5055 $text .=
' - '.(!empty($line->label) ? $line->label : $label);
5056 $description .= (
getDolGlobalInt(
'PRODUIT_DESC_IN_FORM_ACCORDING_TO_DEVICE') ?
'' : (!empty($line->description) ?
dol_htmlentitiesbr($line->description) :
''));
5059 $line->pu_ttc =
price2num((!empty($line->subprice) ? $line->subprice : 0) * (1 + ((!empty($line->tva_tx) ? $line->tva_tx : 0) / 100)),
'MU');
5064 $dirtpls = array_merge($conf->modules_parts[
'tpl'], array($defaulttpldir));
5065 foreach ($dirtpls as $module => $reldir) {
5067 if (!empty($module)) {
5070 $tpl = DOL_DOCUMENT_ROOT.$reldir.
'/objectline_view.tpl.php';
5072 if (file_exists($tpl)) {
5073 if (empty($conf->file->strict_mode)) {
5074 $res = @include $tpl;
5076 $res = include $tpl;
5086 if ($this->
statut == 0 && $action ==
'editline' && $selected == $line->id) {
5087 $label = (!empty($line->label) ? $line->label : (($line->fk_product > 0) ? $line->product_label :
''));
5089 $line->pu_ttc =
price2num($line->subprice * (1 + ($line->tva_tx / 100)),
'MU');
5094 $dirtpls = array_merge($conf->modules_parts[
'tpl'], array($defaulttpldir));
5095 foreach ($dirtpls as $module => $reldir) {
5096 if (!empty($module)) {
5099 $tpl = DOL_DOCUMENT_ROOT.$reldir.
'/objectline_edit.tpl.php';
5102 if (empty($conf->file->strict_mode)) {
5103 $res = @include $tpl;
5105 $res = include $tpl;
5130 global $langs, $hookmanager, $conf, $form, $action;
5132 print
'<tr class="liste_titre">';
5133 print
'<td class="linecolref">'.$langs->trans(
'Ref').
'</td>';
5134 print
'<td class="linecoldescription">'.$langs->trans(
'Description').
'</td>';
5135 print
'<td class="linecolvat right">'.$langs->trans(
'VATRate').
'</td>';
5136 print
'<td class="linecoluht right">'.$langs->trans(
'PriceUHT').
'</td>';
5137 if (isModEnabled(
"multicurrency")) {
5138 print
'<td class="linecoluht_currency right">'.$langs->trans(
'PriceUHTCurrency').
'</td>';
5140 print
'<td class="linecolqty right">'.$langs->trans(
'Qty').
'</td>';
5142 print
'<td class="linecoluseunit left">'.$langs->trans(
'Unit').
'</td>';
5144 print
'<td class="linecoldiscount right">'.$langs->trans(
'ReductionShort').
'</td>';
5145 print
'<td class="linecolht right">'.$langs->trans(
'TotalHT').
'</td>';
5146 print
'<td class="center">'.$form->showCheckAddButtons(
'checkforselect', 1).
'</td>';
5150 if (!empty($this->lines)) {
5151 foreach ($this->lines as $line) {
5154 if (is_object($hookmanager)) {
5155 $parameters = array(
'line'=>$line,
'i'=>$i,
'restrictlist'=>$restrictlist,
'selectedLines'=> $selectedLines);
5156 if (!empty($line->fk_parent_line)) { $parameters[
'fk_parent_line'] = $line->fk_parent_line; }
5157 $reshook = $hookmanager->executeHooks(
'printOriginObjectLine', $parameters, $this, $action);
5159 if (empty($reshook)) {
5160 $this->printOriginLine($line,
'', $restrictlist,
'/core/tpl', $selectedLines);
5181 public function printOriginLine($line, $var, $restrictlist =
'', $defaulttpldir =
'/core/tpl', $selectedLines = array())
5183 global $langs, $conf;
5186 if (!empty($line->date_start)) {
5187 $date_start = $line->date_start;
5189 $date_start = $line->date_debut_prevue;
5190 if ($line->date_debut_reel) {
5191 $date_start = $line->date_debut_reel;
5194 if (!empty($line->date_end)) {
5195 $date_end = $line->date_end;
5197 $date_end = $line->date_fin_prevue;
5198 if ($line->date_fin_reel) {
5199 $date_end = $line->date_fin_reel;
5203 $this->tpl[
'id'] = $line->id;
5205 $this->tpl[
'label'] =
'';
5206 if (!empty($line->fk_parent_line)) {
5207 $this->tpl[
'label'] .=
img_picto(
'',
'rightarrow');
5210 if (($line->info_bits & 2) == 2) {
5212 $discount->fk_soc = $this->socid;
5213 $this->tpl[
'label'] .= $discount->getNomUrl(0,
'discount');
5214 } elseif (!empty($line->fk_product)) {
5215 if (empty($line->product)) {
5216 $line->fetch_product();
5218 $productstatic = $line->product;
5220 $this->tpl[
'label'] .= (is_object($productstatic) ? $productstatic->getNomUrl(1) : $line->ref);
5221 $this->tpl[
'label'] .=
' - '.(!empty($line->label) ? $line->label : $line->product_label);
5223 if ($line->product_type == 1 && ($date_start || $date_end)) {
5227 $this->tpl[
'label'] .= ($line->product_type == -1 ?
' ' : ($line->product_type == 1 ?
img_object($langs->trans(
''),
'service') :
img_object($langs->trans(
''),
'product')));
5228 if (!empty($line->desc)) {
5229 $this->tpl[
'label'] .= $line->desc;
5231 $this->tpl[
'label'] .= ($line->label ?
' '.$line->label :
'');
5235 if ($line->product_type == 1 && ($date_start || $date_end)) {
5240 if (!empty($line->desc)) {
5241 if ($line->desc ==
'(CREDIT_NOTE)') {
5243 $discount->fetch($line->fk_remise_except);
5244 $this->tpl[
'description'] = $langs->transnoentities(
"DiscountFromCreditNote", $discount->getNomUrl(0));
5245 } elseif ($line->desc ==
'(DEPOSIT)') {
5247 $discount->fetch($line->fk_remise_except);
5248 $this->tpl[
'description'] = $langs->transnoentities(
"DiscountFromDeposit", $discount->getNomUrl(0));
5249 } elseif ($line->desc ==
'(EXCESS RECEIVED)') {
5251 $discount->fetch($line->fk_remise_except);
5252 $this->tpl[
'description'] = $langs->transnoentities(
"DiscountFromExcessReceived", $discount->getNomUrl(0));
5253 } elseif ($line->desc ==
'(EXCESS PAID)') {
5255 $discount->fetch($line->fk_remise_except);
5256 $this->tpl[
'description'] = $langs->transnoentities(
"DiscountFromExcessPaid", $discount->getNomUrl(0));
5258 $this->tpl[
'description'] =
dol_trunc($line->desc, 60);
5261 $this->tpl[
'description'] =
' ';
5265 $this->tpl[
'vat_rate'] =
vatrate($line->tva_tx,
true);
5266 $this->tpl[
'vat_rate'] .= (($line->info_bits & 1) == 1) ?
'*' :
'';
5267 if (!empty($line->vat_src_code) && !preg_match(
'/\(/', $this->tpl[
'vat_rate'])) {
5268 $this->tpl[
'vat_rate'] .=
' ('.$line->vat_src_code.
')';
5271 $this->tpl[
'price'] =
price($line->subprice);
5272 $this->tpl[
'total_ht'] =
price($line->total_ht);
5273 $this->tpl[
'multicurrency_price'] =
price($line->multicurrency_subprice);
5274 $this->tpl[
'qty'] = (($line->info_bits & 2) != 2) ? $line->qty :
' ';
5276 $this->tpl[
'unit'] = $langs->transnoentities($line->getLabelOfUnit(
'long'));
5278 $this->tpl[
'remise_percent'] = (($line->info_bits & 2) != 2) ?
vatrate($line->remise_percent,
true) :
' ';
5281 $this->tpl[
'strike'] = 0;
5283 $this->tpl[
'strike'] = 1;
5288 $dirtpls = array_merge($conf->modules_parts[
'tpl'], array($defaulttpldir));
5289 foreach ($dirtpls as $module => $reldir) {
5290 if (!empty($module)) {
5293 $tpl = DOL_DOCUMENT_ROOT.$reldir.
'/originproductline.tpl.php';
5296 if (empty($conf->file->strict_mode)) {
5297 $res = @include $tpl;
5299 $res = include $tpl;
5324 $sql =
"INSERT INTO ".$this->db->prefix().
"element_resources (";
5325 $sql .=
"resource_id";
5326 $sql .=
", resource_type";
5327 $sql .=
", element_id";
5328 $sql .=
", element_type";
5330 $sql .=
", mandatory";
5331 $sql .=
") VALUES (";
5332 $sql .= ((int) $resource_id);
5333 $sql .=
", '".$this->db->escape($resource_type).
"'";
5334 $sql .=
", '".$this->db->escape($this->
id).
"'";
5335 $sql .=
", '".$this->db->escape($this->element).
"'";
5336 $sql .=
", '".$this->db->escape($busy).
"'";
5337 $sql .=
", '".$this->db->escape($mandatory).
"'";
5340 dol_syslog(get_class($this).
"::add_element_resource", LOG_DEBUG);
5341 if ($this->db->query($sql)) {
5342 $this->db->commit();
5345 $this->error = $this->db->lasterror();
5346 $this->db->rollback();
5367 $sql =
"DELETE FROM ".$this->db->prefix().
"element_resources";
5368 $sql .=
" WHERE rowid = ".((int) $rowid);
5370 dol_syslog(get_class($this).
"::delete_resource", LOG_DEBUG);
5372 $resql = $this->db->query($sql);
5374 $this->error = $this->db->lasterror();
5375 $this->db->rollback();
5379 $result = $this->call_trigger(strtoupper($element).
'_DELETE_RESOURCE', $user);
5381 $this->db->rollback();
5385 $this->db->commit();
5399 if (isset($this->lines) && is_array($this->lines)) {
5400 $nboflines = count($this->lines);
5401 for ($i = 0; $i < $nboflines; $i++) {
5402 if (is_object($this->lines[$i])) {
5403 $this->lines[$i] = clone $this->lines[$i];
5422 protected function commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams =
null)
5424 global $conf, $langs, $user, $hookmanager, $action;
5426 $srctemplatepath =
'';
5428 $parameters = array(
'modelspath'=>$modelspath,
'modele'=>$modele,
'outputlangs'=>$outputlangs,
'hidedetails'=>$hidedetails,
'hidedesc'=>$hidedesc,
'hideref'=>$hideref,
'moreparams'=>$moreparams);
5429 $reshook = $hookmanager->executeHooks(
'commonGenerateDocument', $parameters, $this, $action);
5431 if (!empty($reshook)) {
5435 dol_syslog(
"commonGenerateDocument modele=".$modele.
" outputlangs->defaultlang=".(is_object($outputlangs) ? $outputlangs->defaultlang :
'null'));
5437 if (empty($modele)) {
5438 $this->error =
'BadValueForParameterModele';
5443 $err = error_reporting();
5445 @set_time_limit(120);
5446 error_reporting($err);
5449 $tmp = explode(
':', $modele, 2);
5450 if (!empty($tmp[1])) {
5452 $srctemplatepath = $tmp[1];
5459 $dirmodels = array(
'/');
5460 if (is_array($conf->modules_parts[
'models'])) {
5461 $dirmodels = array_merge($dirmodels, $conf->modules_parts[
'models']);
5463 foreach ($dirmodels as $reldir) {
5464 foreach (array(
'doc',
'pdf') as $prefix) {
5465 if (in_array(get_class($this), array(
'Adherent'))) {
5467 $file = $prefix.
"_".$modele.
".class.php";
5470 $file = $prefix.
"_".$modele.
".modules.php";
5475 if (file_exists($file)) {
5477 $classname = $prefix.
'_'.$modele;
5487 $this->error = $langs->trans(
"Error").
' Failed to load doc generator with modelpaths='.$modelspath.
' - modele='.$modele;
5488 $this->errors[] = $this->error;
5498 $obj =
new $classname($this->db);
5501 if ($obj->type ==
'odt' && empty($srctemplatepath)) {
5502 $varfortemplatedir = $obj->scandir;
5503 if ($varfortemplatedir && !empty($conf->global->$varfortemplatedir)) {
5504 $dirtoscan = $conf->global->$varfortemplatedir;
5506 $listoffiles = array();
5509 $listofdir = explode(
',', $dirtoscan);
5510 foreach ($listofdir as $key => $tmpdir) {
5511 $tmpdir = trim($tmpdir);
5512 $tmpdir = preg_replace(
'/DOL_DATA_ROOT/', DOL_DATA_ROOT, $tmpdir);
5514 unset($listofdir[$key]);
5517 if (is_dir($tmpdir)) {
5518 $tmpfiles =
dol_dir_list($tmpdir,
'files', 0,
'\.od(s|t)$',
'',
'name', SORT_ASC, 0);
5519 if (count($tmpfiles)) {
5520 $listoffiles = array_merge($listoffiles, $tmpfiles);
5525 if (count($listoffiles)) {
5526 foreach ($listoffiles as $record) {
5527 $srctemplatepath = $record[
'fullname'];
5533 if (empty($srctemplatepath)) {
5534 $this->error =
'ErrorGenerationAskedForOdtTemplateWithSrcFileNotDefined';
5539 if ($obj->type ==
'odt' && !empty($srctemplatepath)) {
5541 dol_syslog(
"Failed to locate template file ".$srctemplatepath, LOG_WARNING);
5542 $this->error =
'ErrorGenerationAskedForOdtTemplateWithSrcFileNotFound';
5549 $sav_charset_output = empty($outputlangs->charset_output) ?
'' : $outputlangs->charset_output;
5551 if (in_array(get_class($this), array(
'Adherent'))) {
5552 $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath,
'member', 1,
'tmp_cards', $moreparams);
5554 $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, $hidedetails, $hidedesc, $hideref, $moreparams);
5558 if ($resultwritefile > 0) {
5559 $outputlangs->charset_output = $sav_charset_output;
5562 require_once DOL_DOCUMENT_ROOT.
'/core/lib/files.lib.php';
5566 if (!empty($obj->result[
'fullpath'])) {
5567 $destfull = $obj->result[
'fullpath'];
5570 $update_main_doc_field = 0;
5571 if (!empty($obj->update_main_doc_field)) {
5572 $update_main_doc_field = 1;
5578 $this->indexFile($destfull, $update_main_doc_field);
5581 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);
5589 $outputlangs->charset_output = $sav_charset_output;
5590 $this->error = $obj->error;
5591 $this->errors = $obj->errors;
5592 dol_syslog(
"Error generating document for ".__CLASS__.
". Error: ".$obj->error, LOG_ERR);
5606 public function indexFile($destfull, $update_main_doc_field)
5608 global $conf, $user;
5610 $upload_dir = dirname($destfull);
5611 $destfile = basename($destfull);
5612 $rel_dir = preg_replace(
'/^'.preg_quote(DOL_DATA_ROOT,
'/').
'/',
'', $upload_dir);
5614 if (!preg_match(
'/[\\/]temp[\\/]|[\\/]thumbs|\.meta$/', $rel_dir)) {
5615 $filename = basename($destfile);
5616 $rel_dir = preg_replace(
'/[\\/]$/',
'', $rel_dir);
5617 $rel_dir = preg_replace(
'/^[\\/]/',
'', $rel_dir);
5619 include_once DOL_DOCUMENT_ROOT.
'/ecm/class/ecmfiles.class.php';
5620 $ecmfile =
new EcmFiles($this->db);
5621 $result = $ecmfile->fetch(0,
'', ($rel_dir ? $rel_dir.
'/' :
'').$filename);
5624 $setsharekey =
false;
5625 if ($this->element ==
'propal' || $this->element ==
'proposal') {
5626 if (!isset($conf->global->PROPOSAL_ALLOW_ONLINESIGN) || !empty($conf->global->PROPOSAL_ALLOW_ONLINESIGN)) {
5627 $setsharekey =
true;
5629 if (!empty($conf->global->PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD)) {
5630 $setsharekey =
true;
5633 if ($this->element ==
'commande' && !empty($conf->global->ORDER_ALLOW_EXTERNAL_DOWNLOAD)) {
5634 $setsharekey =
true;
5636 if ($this->element ==
'facture' && !empty($conf->global->INVOICE_ALLOW_EXTERNAL_DOWNLOAD)) {
5637 $setsharekey =
true;
5639 if ($this->element ==
'bank_account' && !empty($conf->global->BANK_ACCOUNT_ALLOW_EXTERNAL_DOWNLOAD)) {
5640 $setsharekey =
true;
5642 if ($this->element ==
'product' && !empty($conf->global->PRODUCT_ALLOW_EXTERNAL_DOWNLOAD)) {
5643 $setsharekey =
true;
5645 if ($this->element ==
'contrat' && !empty($conf->global->CONTRACT_ALLOW_EXTERNAL_DOWNLOAD)) {
5646 $setsharekey =
true;
5648 if ($this->element ==
'fichinter' && !empty($conf->global->FICHINTER_ALLOW_EXTERNAL_DOWNLOAD)) {
5649 $setsharekey =
true;
5651 if ($this->element ==
'supplier_proposal' && !empty($conf->global->SUPPLIER_PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD)) {
5652 $setsharekey =
true;
5656 if (empty($ecmfile->share)) {
5657 require_once DOL_DOCUMENT_ROOT.
'/core/lib/security2.lib.php';
5664 $ecmfile->fullpath_orig =
'';
5665 $ecmfile->gen_or_uploaded =
'generated';
5666 $ecmfile->description =
'';
5667 $ecmfile->keywords =
'';
5668 $result = $ecmfile->update($user);
5674 $ecmfile->entity = $conf->entity;
5675 $ecmfile->filepath = $rel_dir;
5676 $ecmfile->filename = $filename;
5678 $ecmfile->fullpath_orig =
'';
5679 $ecmfile->gen_or_uploaded =
'generated';
5680 $ecmfile->description =
'';
5681 $ecmfile->keywords =
'';
5682 $ecmfile->src_object_type = $this->table_element;
5683 $ecmfile->src_object_id = $this->id;
5685 $result = $ecmfile->create($user);
5697 if ($update_main_doc_field && !empty($this->table_element)) {
5698 $sql =
"UPDATE ".$this->db->prefix().$this->table_element.
" SET last_main_doc = '".$this->db->escape($ecmfile->filepath.
"/".$ecmfile->filename).
"'";
5699 $sql .=
" WHERE rowid = ".((int) $this->
id);
5701 $resql = $this->db->query($sql);
5706 $this->last_main_doc = $ecmfile->filepath.
'/'.$ecmfile->filename;
5725 if (file_exists($file_osencoded)) {
5726 require_once DOL_DOCUMENT_ROOT.
'/core/lib/images.lib.php';
5729 $maxwidthsmall = $tmparraysize[
'maxwidthsmall'];
5730 $maxheightsmall = $tmparraysize[
'maxheightsmall'];
5731 $maxwidthmini = $tmparraysize[
'maxwidthmini'];
5732 $maxheightmini = $tmparraysize[
'maxheightmini'];
5738 vignette($file_osencoded, $maxwidthsmall, $maxheightsmall,
'_small', $quality);
5742 vignette($file_osencoded, $maxwidthmini, $maxheightmini,
'_mini', $quality);
5781 global $conf, $_POST;
5784 if (GETPOSTISSET($fieldname)) {
5785 return GETPOST($fieldname, $type, 3);
5788 if (isset($alternatevalue)) {
5789 return $alternatevalue;
5792 $newelement = $this->element;
5793 if ($newelement ==
'facture') {
5794 $newelement =
'invoice';
5796 if ($newelement ==
'commande') {
5797 $newelement =
'order';
5799 if (empty($newelement)) {
5800 dol_syslog(
"Ask a default value using common method getDefaultCreateValueForField on an object with no property ->element defined. Return empty string.", LOG_WARNING);
5804 $keyforfieldname = strtoupper($newelement.
'_DEFAULT_'.$fieldname);
5806 if (isset($conf->global->$keyforfieldname)) {
5807 return $conf->global->$keyforfieldname;
5834 global $langs, $conf;
5835 if (!empty(self::TRIGGER_PREFIX) && strpos($triggerName, self::TRIGGER_PREFIX .
'_') !== 0) {
5836 dol_print_error(
'',
'The trigger "' . $triggerName .
'" does not start with "' . self::TRIGGER_PREFIX .
'_" as required.');
5839 if (!is_object($langs)) {
5840 include_once DOL_DOCUMENT_ROOT.
'/core/class/translate.class.php';
5844 include_once DOL_DOCUMENT_ROOT.
'/core/class/interfaces.class.php';
5846 $result = $interface->run_triggers($triggerName, $this, $user, $langs, $conf);
5849 if (!empty($this->errors)) {
5850 $this->errors = array_unique(array_merge($this->errors, $interface->errors));
5852 $this->errors = $interface->errors;
5872 if (!$this->element) {
5875 if (!($this->
id > 0)) {
5878 if (is_array($this->array_languages)) {
5882 $this->array_languages = array();
5884 $element = $this->element;
5885 if ($element ==
'categorie') {
5886 $element =
'categories';
5890 $sql =
"SELECT rowid, property, lang , value";
5891 $sql .=
" FROM ".$this->db->prefix().
"object_lang";
5892 $sql .=
" WHERE type_object = '".$this->db->escape($element).
"'";
5893 $sql .=
" AND fk_object = ".((int) $this->
id);
5896 $resql = $this->db->query($sql);
5898 $numrows = $this->db->num_rows($resql);
5901 while ($i < $numrows) {
5902 $obj = $this->db->fetch_object($resql);
5903 $key = $obj->property;
5904 $value = $obj->value;
5905 $codelang = $obj->lang;
5906 $type = $this->fields[$key][
'type'];
5909 if (preg_match(
'/date/', $type)) {
5910 $this->array_languages[$key][$codelang] = $this->db->jdate($value);
5912 $this->array_languages[$key][$codelang] = $value;
5919 $this->db->free($resql);
5940 global $_POST, $langs;
5943 foreach ($_POST as $postfieldkey => $postfieldvalue) {
5944 $tmparray = explode(
'-', $postfieldkey);
5945 if ($tmparray[0] !=
'field') {
5949 $element = $tmparray[1];
5950 $key = $tmparray[2];
5951 $codelang = $tmparray[3];
5954 if (!empty($onlykey) && $key != $onlykey) {
5957 if ($element != $this->element) {
5961 $key_type = $this->fields[$key][
'type'];
5964 if (isset($this->fields[$key][
'enabled'])) {
5965 $enabled =
dol_eval($this->fields[$key][
'enabled'], 1, 1,
'1');
5972 if (empty($enabled)) {
5977 if (in_array($key_type, array(
'date'))) {
5981 } elseif (in_array($key_type, array(
'datetime'))) {
5984 $value_key =
dol_mktime(
GETPOST($postfieldkey.
"hour",
'int'),
GETPOST($postfieldkey.
"min",
'int'), 0,
GETPOST($postfieldkey.
"month",
'int'),
GETPOST($postfieldkey.
"day",
'int'),
GETPOST($postfieldkey.
"year",
'int'));
5985 } elseif (in_array($key_type, array(
'checkbox',
'chkbxlst'))) {
5986 $value_arr =
GETPOST($postfieldkey,
'array');
5987 if (!empty($value_arr)) {
5988 $value_key = implode(
',', $value_arr);
5992 } elseif (in_array($key_type, array(
'price',
'double'))) {
5993 $value_arr =
GETPOST($postfieldkey,
'alpha');
5996 $value_key =
GETPOST($postfieldkey);
5997 if (in_array($key_type, array(
'link')) && $value_key ==
'-1') {
6002 $this->array_languages[$key][$codelang] = $value_key;
6027 $savDisableCompute = $conf->disable_compute;
6028 $conf->disable_compute = 1;
6030 $ret = $this->fetch($id);
6032 $conf->disable_compute = $savDisableCompute;
6050 global $conf, $extrafields;
6052 if (empty($rowid)) {
6055 if (empty($rowid) && isset($this->
rowid)) {
6056 $rowid = $this->rowid;
6060 if (!$this->table_element) {
6064 $this->array_options = array();
6066 if (!is_array($optionsArray)) {
6068 if (!isset($extrafields) || !is_object($extrafields)) {
6069 require_once DOL_DOCUMENT_ROOT.
'/core/class/extrafields.class.php';
6074 if (empty($extrafields->attributes[$this->table_element][
'loaded'])) {
6075 $extrafields->fetch_name_optionals_label($this->table_element);
6077 $optionsArray = (!empty($extrafields->attributes[$this->table_element][
'label']) ? $extrafields->attributes[$this->table_element][
'label'] :
null);
6079 global $extrafields;
6080 dol_syslog(
"Warning: fetch_optionals was called with param optionsArray defined when you should pass null now", LOG_WARNING);
6083 $table_element = $this->table_element;
6084 if ($table_element ==
'categorie') {
6085 $table_element =
'categories';
6089 if (is_array($optionsArray) && count($optionsArray) > 0) {
6090 $sql =
"SELECT rowid";
6091 foreach ($optionsArray as $name => $label) {
6092 if (empty($extrafields->attributes[$this->table_element][
'type'][$name]) || $extrafields->attributes[$this->table_element][
'type'][$name] !=
'separate') {
6096 $sql .=
" FROM ".$this->db->prefix().$table_element.
"_extrafields";
6097 $sql .=
" WHERE fk_object = ".((int) $rowid);
6100 $resql = $this->db->query($sql);
6102 $numrows = $this->db->num_rows($resql);
6104 $tab = $this->db->fetch_array($resql);
6106 foreach ($tab as $key => $value) {
6108 if ($key !=
'rowid' && $key !=
'tms' && $key !=
'fk_member' && !is_int($key)) {
6110 if (!empty($extrafields->attributes[$this->table_element]) && in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'date',
'datetime'))) {
6112 $this->array_options[
"options_".$key] = $this->db->jdate($value);
6114 $this->array_options[
"options_".$key] = $value;
6124 if (is_array($extrafields->attributes[$this->table_element][
'label'])) {
6125 foreach ($extrafields->attributes[$this->table_element][
'label'] as $key => $val) {
6126 if (!empty($extrafields->attributes[$this->table_element]) && !empty($extrafields->attributes[$this->table_element][
'computed'][$key])) {
6128 if (empty($conf->disable_compute)) {
6129 global $objectoffield;
6130 $objectoffield = $this;
6131 $this->array_options[
'options_' . $key] =
dol_eval($extrafields->attributes[$this->table_element][
'computed'][$key], 1, 0,
'');
6137 $this->db->free($resql);
6145 $this->errors[]=$this->db->lasterror;
6162 if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
6168 $table_element = $this->table_element;
6169 if ($table_element ==
'categorie') {
6170 $table_element =
'categories';
6173 dol_syslog(get_class($this).
"::deleteExtraFields delete", LOG_DEBUG);
6175 $sql_del =
"DELETE FROM ".$this->db->prefix().$table_element.
"_extrafields WHERE fk_object = ".((int) $this->
id);
6177 $resql = $this->db->query($sql_del);
6179 $this->error = $this->db->lasterror();
6180 $this->db->rollback();
6183 $this->db->commit();
6200 global $conf, $langs, $user;
6202 if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
6206 if (empty($userused)) {
6212 if (!empty($this->array_options)) {
6214 $langs->load(
'admin');
6215 require_once DOL_DOCUMENT_ROOT.
'/core/class/extrafields.class.php';
6217 $target_extrafields = $extrafields->fetch_name_optionals_label($this->table_element);
6220 $new_array_options = array();
6221 foreach ($this->array_options as $key => $value) {
6222 if (in_array(substr($key, 8), array_keys($target_extrafields))) {
6223 $new_array_options[$key] = $value;
6224 } elseif (in_array($key, array_keys($target_extrafields))) {
6225 $new_array_options[
'options_'.$key] = $value;
6229 foreach ($new_array_options as $key => $value) {
6230 $attributeKey = substr($key, 8);
6231 $attributeType = $extrafields->attributes[$this->table_element][
'type'][$attributeKey];
6232 $attributeLabel = $langs->transnoentities($extrafields->attributes[$this->table_element][
'label'][$attributeKey]);
6233 $attributeParam = $extrafields->attributes[$this->table_element][
'param'][$attributeKey];
6234 $attributeRequired = $extrafields->attributes[$this->table_element][
'required'][$attributeKey];
6235 $attributeUnique = $extrafields->attributes[$this->table_element][
'unique'][$attributeKey];
6236 $attrfieldcomputed = $extrafields->attributes[$this->table_element][
'computed'][$attributeKey];
6240 if (!empty($this->context[
'createfromclone']) && $this->context[
'createfromclone'] ==
'createfromclone' && !empty($attributeUnique)) {
6241 $new_array_options[$key] =
null;
6245 if ($attributeRequired) {
6246 $mandatorypb =
false;
6247 if ($attributeType ==
'link' && $this->array_options[$key] ==
'-1') {
6248 $mandatorypb =
true;
6250 if ($this->array_options[$key] ===
'') {
6251 $mandatorypb =
true;
6253 if ($attributeType ==
'sellist' && $this->array_options[$key] ==
'0') {
6254 $mandatorypb =
true;
6257 $langs->load(
"errors");
6258 dol_syslog(
"Mandatory field '".$key.
"' is empty during create and set to required into definition of extrafields");
6259 $this->errors[] = $langs->trans(
'ErrorFieldRequired', $attributeLabel);
6267 if (!empty($attrfieldcomputed)) {
6268 if (!empty($conf->global->MAIN_STORE_COMPUTED_EXTRAFIELDS)) {
6269 $value =
dol_eval($attrfieldcomputed, 1, 0,
'');
6270 dol_syslog($langs->trans(
"Extrafieldcomputed").
" sur ".$attributeLabel.
"(".$value.
")", LOG_DEBUG);
6271 $new_array_options[$key] = $value;
6273 $new_array_options[$key] =
null;
6277 switch ($attributeType) {
6279 if (!is_numeric($value) && $value !=
'') {
6280 $this->errors[] = $langs->trans(
"ExtraFieldHasWrongValue", $attributeLabel);
6282 } elseif ($value ==
'') {
6283 $new_array_options[$key] =
null;
6289 if (!is_numeric($value) && $value !=
'') {
6290 dol_syslog($langs->trans(
"ExtraFieldHasWrongValue").
" for ".$attributeLabel.
"(".$value.
"is not '".$attributeType.
"')", LOG_DEBUG);
6291 $this->errors[] = $langs->trans(
"ExtraFieldHasWrongValue", $attributeLabel);
6293 } elseif ($value ==
'') {
6297 $new_array_options[$key] = $value;
6307 if ($this->array_options[$key] !=
'' && is_array($extrafields->attributes[$this->table_element][
'param'][$attributeKey][
'options'])) {
6309 $tmparrays = array_keys($extrafields->attributes[$this->table_element][
'param'][$attributeKey][
'options']);
6310 $algo = reset($tmparrays);
6315 if (is_object($this->oldcopy)) {
6317 if (isset($this->oldcopy->array_options[$key]) && $this->array_options[$key] == $this->oldcopy->array_options[$key]) {
6318 $new_array_options[$key] = $this->array_options[$key];
6321 $newvalue =
dol_hash($this->array_options[$key], $algo);
6322 $new_array_options[$key] = $newvalue;
6325 $new_array_options[$key] = $this->array_options[$key];
6330 $new_array_options[$key] = $this->array_options[$key];
6336 if (!is_numeric($this->array_options[$key]) || $this->array_options[$key] != intval($this->array_options[$key])) {
6337 $this->array_options[$key] = strtotime($this->array_options[$key]);
6339 $new_array_options[$key] = $this->db->idate($this->array_options[$key]);
6343 if (!is_numeric($this->array_options[$key]) || $this->array_options[$key] != intval($this->array_options[$key])) {
6344 $this->array_options[$key] = strtotime($this->array_options[$key]);
6346 $new_array_options[$key] = $this->db->idate($this->array_options[$key],
'gmt');
6349 $param_list = array_keys($attributeParam[
'options']);
6352 $InfoFieldList = explode(
":", $param_list[0]);
6354 if ($InfoFieldList[0] && class_exists($InfoFieldList[0])) {
6355 if ($value ==
'-1') {
6356 $new_array_options[$key] =
'';
6358 $object =
new $InfoFieldList[0]($this->db);
6359 if (is_numeric($value)) {
6360 $res = $object->fetch($value);
6362 $res = $object->fetch(
'', $value);
6366 $new_array_options[$key] = $object->id;
6368 $this->error =
"Id/Ref '".$value.
"' for object '".$object->element.
"' not found";
6373 dol_syslog(
'Error bad setup of extrafield', LOG_WARNING);
6378 if (is_array($this->array_options[$key])) {
6379 $new_array_options[$key] = implode(
',', $this->array_options[$key]);
6381 $new_array_options[$key] = $this->array_options[$key];
6389 $table_element = $this->table_element;
6390 if ($table_element ==
'categorie') {
6391 $table_element =
'categories';
6394 dol_syslog(get_class($this).
"::insertExtraFields delete then insert", LOG_DEBUG);
6396 $sql_del =
"DELETE FROM ".$this->db->prefix().$table_element.
"_extrafields WHERE fk_object = ".((int) $this->
id);
6397 $this->db->query($sql_del);
6399 $sql =
"INSERT INTO ".$this->db->prefix().$table_element.
"_extrafields (fk_object";
6400 foreach ($new_array_options as $key => $value) {
6401 $attributeKey = substr($key, 8);
6403 if ($extrafields->attributes[$this->table_element][
'type'][$attributeKey] !=
'separate') {
6404 $sql .=
",".$attributeKey;
6408 if (!empty($extrafields->attributes[$this->table_element][
'mandatoryfieldsofotherentities']) && is_array($extrafields->attributes[$this->table_element][
'mandatoryfieldsofotherentities'])) {
6409 foreach ($extrafields->attributes[$this->table_element][
'mandatoryfieldsofotherentities'] as $tmpkey => $tmpval) {
6410 if (!isset($extrafields->attributes[$this->table_element][
'type'][$tmpkey])) {
6411 $sql .=
",".$tmpkey;
6415 $sql .=
") VALUES (".$this->id;
6417 foreach ($new_array_options as $key => $value) {
6418 $attributeKey = substr($key, 8);
6420 if ($extrafields->attributes[$this->table_element][
'type'][$attributeKey] !=
'separate') {
6421 if ($new_array_options[$key] !=
'' || $new_array_options[$key] ==
'0') {
6422 $sql .=
",'".$this->db->escape($new_array_options[$key]).
"'";
6429 if (!empty($extrafields->attributes[$this->table_element][
'mandatoryfieldsofotherentities']) && is_array($extrafields->attributes[$this->table_element][
'mandatoryfieldsofotherentities'])) {
6430 foreach ($extrafields->attributes[$this->table_element][
'mandatoryfieldsofotherentities'] as $tmpkey => $tmpval) {
6431 if (!isset($extrafields->attributes[$this->table_element][
'type'][$tmpkey])) {
6432 if (in_array($tmpval, array(
'int',
'double',
'price'))) {
6443 $resql = $this->db->query($sql);
6445 $this->error = $this->db->lasterror();
6449 if (!$error && $trigger) {
6451 $this->context = array(
'extrafieldaddupdate'=>1);
6452 $result = $this->call_trigger($trigger, $userused);
6460 $this->db->rollback();
6463 $this->db->commit();
6483 global $conf, $langs, $user;
6485 if (empty($userused)) {
6491 if (!empty($conf->global->MAIN_EXTRALANGUAGES_DISABLED)) {
6495 if (is_array($this->array_languages)) {
6496 $new_array_languages = $this->array_languages;
6498 foreach ($new_array_languages as $key => $value) {
6499 $attributeKey = $key;
6500 $attributeType = $this->fields[$attributeKey][
'type'];
6501 $attributeLabel = $this->fields[$attributeKey][
'label'];
6506 switch ($attributeType) {
6508 if (!is_numeric($value) && $value !=
'') {
6509 $this->errors[] = $langs->trans(
"ExtraLanguageHasWrongValue", $attributeLabel);
6511 } elseif ($value ==
'') {
6512 $new_array_languages[$key] =
null;
6517 if (!is_numeric($value) && $value !=
'') {
6518 dol_syslog($langs->trans(
"ExtraLanguageHasWrongValue").
" sur ".$attributeLabel.
"(".$value.
"is not '".$attributeType.
"')", LOG_DEBUG);
6519 $this->errors[] = $langs->trans(
"ExtraLanguageHasWrongValue", $attributeLabel);
6521 } elseif ($value ==
'') {
6522 $new_array_languages[$key] =
null;
6524 $new_array_languages[$key] = $value;
6538 $table_element = $this->table_element;
6539 if ($table_element ==
'categorie') {
6540 $table_element =
'categories';
6543 dol_syslog(get_class($this).
"::insertExtraLanguages delete then insert", LOG_DEBUG);
6545 foreach ($new_array_languages as $key => $langcodearray) {
6546 foreach ($langcodearray as $langcode => $value) {
6547 $sql_del =
"DELETE FROM ".$this->db->prefix().
"object_lang";
6548 $sql_del .=
" WHERE fk_object = ".((int) $this->
id).
" AND property = '".$this->db->escape($key).
"' AND type_object = '".$this->db->escape($table_element).
"'";
6549 $sql_del .=
" AND lang = '".$this->db->escape($langcode).
"'";
6550 $this->db->query($sql_del);
6552 if ($value !==
'') {
6553 $sql =
"INSERT INTO ".$this->db->prefix().
"object_lang (fk_object, property, type_object, lang, value";
6554 $sql .=
") VALUES (".$this->id.
", '".$this->db->escape($key).
"', '".$this->db->escape($table_element).
"', '".$this->db->escape($langcode).
"', '".$this->db->escape($value).
"'";
6557 $resql = $this->db->query($sql);
6559 $this->error = $this->db->lasterror();
6567 if (!$error && $trigger) {
6569 $this->context = array(
'extralanguagesaddupdate'=>1);
6570 $result = $this->call_trigger($trigger, $userused);
6578 $this->db->rollback();
6581 $this->db->commit();
6601 global $conf, $langs, $user;
6603 if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
6607 if (empty($userused)) {
6613 if (!empty($this->array_options) && isset($this->array_options[
"options_".$key])) {
6615 $langs->load(
'admin');
6616 require_once DOL_DOCUMENT_ROOT.
'/core/class/extrafields.class.php';
6618 $extrafields->fetch_name_optionals_label($this->table_element);
6620 $value = $this->array_options[
"options_".$key];
6622 $attributeType = $extrafields->attributes[$this->table_element][
'type'][$key];
6623 $attributeLabel = $extrafields->attributes[$this->table_element][
'label'][$key];
6624 $attributeParam = $extrafields->attributes[$this->table_element][
'param'][$key];
6625 $attributeRequired = $extrafields->attributes[$this->table_element][
'required'][$key];
6626 $attrfieldcomputed = $extrafields->attributes[$this->table_element][
'computed'][$key];
6629 if ($attributeRequired) {
6630 $mandatorypb =
false;
6631 if ($attributeType ==
'link' && $this->array_options[
"options_".$key] ==
'-1') {
6632 $mandatorypb =
true;
6634 if ($this->array_options[
"options_".$key] ===
'') {
6635 $mandatorypb =
true;
6638 $langs->load(
"errors");
6639 dol_syslog(
"Mandatory field 'options_".$key.
"' is empty during update and set to required into definition of extrafields");
6640 $this->errors[] = $langs->trans(
'ErrorFieldRequired', $attributeLabel);
6648 if (!empty($attrfieldcomputed)) {
6649 if (!empty($conf->global->MAIN_STORE_COMPUTED_EXTRAFIELDS)) {
6650 $value =
dol_eval($attrfieldcomputed, 1, 0,
'');
6651 dol_syslog($langs->trans(
"Extrafieldcomputed").
" sur ".$attributeLabel.
"(".$value.
")", LOG_DEBUG);
6652 $this->array_options[
"options_".$key] = $value;
6654 $this->array_options[
"options_".$key] =
null;
6658 switch ($attributeType) {
6660 if (!is_numeric($value) && $value !=
'') {
6661 $this->errors[] = $langs->trans(
"ExtraFieldHasWrongValue", $attributeLabel);
6663 } elseif ($value ===
'') {
6664 $this->array_options[
"options_".$key] =
null;
6670 if (!is_numeric($value) && $value !=
'') {
6671 dol_syslog($langs->trans(
"ExtraFieldHasWrongValue").
" sur ".$attributeLabel.
"(".$value.
"is not '".$attributeType.
"')", LOG_DEBUG);
6672 $this->errors[] = $langs->trans(
"ExtraFieldHasWrongValue", $attributeLabel);
6674 } elseif ($value ===
'') {
6678 $this->array_options[
"options_".$key] = $value;
6688 if (empty($this->array_options[
"options_".$key])) {
6689 $this->array_options[
"options_".$key] =
null;
6691 $this->array_options[
"options_".$key] = $this->db->idate($this->array_options[
"options_".$key]);
6695 if (empty($this->array_options[
"options_".$key])) {
6696 $this->array_options[
"options_".$key] =
null;
6698 $this->array_options[
"options_".$key] = $this->db->idate($this->array_options[
"options_".$key],
'gmt');
6702 if (empty($this->array_options[
"options_".$key])) {
6703 $this->array_options[
"options_".$key] =
null;
6707 if ($this->array_options[
"options_".$key] ===
'') {
6708 $this->array_options[
"options_".$key] =
null;
6742 if (is_array($this->array_options[$key])) {
6743 $new_array_options[$key] = implode(
',', $this->array_options[$key]);
6745 $new_array_options[$key] = $this->array_options[$key];
6752 $linealreadyfound = 0;
6755 $sql =
"SELECT COUNT(rowid) as nb FROM ".$this->db->prefix().$this->table_element.
"_extrafields WHERE fk_object = ".((int) $this->
id);
6756 $resql = $this->db->query($sql);
6758 $tmpobj = $this->db->fetch_object($resql);
6760 $linealreadyfound = $tmpobj->nb;
6764 if ($linealreadyfound) {
6765 if ($this->array_options[
"options_".$key] ===
null) {
6766 $sql =
"UPDATE ".$this->db->prefix().$this->table_element.
"_extrafields SET ".$key.
" = null";
6768 $sql =
"UPDATE ".$this->db->prefix().$this->table_element.
"_extrafields SET ".$key.
" = '".$this->db->escape($this->array_options[
"options_".$key]).
"'";
6770 $sql .=
" WHERE fk_object = ".((int) $this->
id);
6772 $result = $this->insertExtraFields(
'', $user);
6778 $resql = $this->db->query($sql);
6781 $this->error = $this->db->lasterror();
6783 if (!$error && $trigger) {
6785 $this->context = array(
'extrafieldupdate'=>1);
6786 $result = $this->call_trigger($trigger, $userused);
6794 dol_syslog(__METHOD__.$this->error, LOG_ERR);
6795 $this->db->rollback();
6798 $this->db->commit();
6818 global $conf, $langs, $user;
6820 if (empty($userused)) {
6826 if (!empty($conf->global->MAIN_EXTRALANGUAGES_DISABLED)) {
6848 public function showInputField($val, $key, $value, $moreparam =
'', $keysuffix =
'', $keyprefix =
'', $morecss = 0, $nonewbutton = 0)
6850 global $conf, $langs, $form;
6852 if (!is_object($form)) {
6853 require_once DOL_DOCUMENT_ROOT.
'/core/class/html.form.class.php';
6854 $form =
new Form($this->db);
6857 if (!empty($this->fields)) {
6858 $val = $this->fields[$key];
6862 $fieldValidationErrorMsg =
'';
6863 $validationClass =
'';
6864 $fieldValidationErrorMsg = $this->getFieldError($key);
6865 if (!empty($fieldValidationErrorMsg)) {
6866 $validationClass =
' --error';
6868 $validationClass =
' --success';
6875 $param[
'options'] = array();
6877 $size = !empty($this->fields[$key][
'size']) ? $this->fields[$key][
'size'] : 0;
6879 if (preg_match(
'/^(integer|link):(.*):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
6880 $param[
'options'] = array($reg[2].
':'.$reg[3].
':'.$reg[4].
':'.$reg[5] =>
'N');
6882 } elseif (preg_match(
'/^(integer|link):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
6883 $param[
'options'] = array($reg[2].
':'.$reg[3].
':'.$reg[4] =>
'N');
6885 } elseif (preg_match(
'/^(integer|link):(.*):(.*)/i', $val[
'type'], $reg)) {
6886 $param[
'options'] = array($reg[2].
':'.$reg[3] =>
'N');
6888 } elseif (preg_match(
'/^(sellist):(.*):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
6889 $param[
'options'] = array($reg[2].
':'.$reg[3].
':'.$reg[4].
':'.$reg[5] =>
'N');
6891 } elseif (preg_match(
'/^(sellist):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
6892 $param[
'options'] = array($reg[2].
':'.$reg[3].
':'.$reg[4] =>
'N');
6894 } elseif (preg_match(
'/^(sellist):(.*):(.*)/i', $val[
'type'], $reg)) {
6895 $param[
'options'] = array($reg[2].
':'.$reg[3] =>
'N');
6897 } elseif (preg_match(
'/^chkbxlst:(.*)/i', $val[
'type'], $reg)) {
6898 $param[
'options'] = array($reg[1] =>
'N');
6900 } elseif (preg_match(
'/varchar\((\d+)\)/', $val[
'type'], $reg)) {
6901 $param[
'options'] = array();
6904 } elseif (preg_match(
'/varchar/', $val[
'type'])) {
6905 $param[
'options'] = array();
6908 $param[
'options'] = array();
6909 $type = $this->fields[$key][
'type'];
6913 if (!empty($this->fields[$key][
'arrayofkeyval']) && is_array($this->fields[$key][
'arrayofkeyval'])) {
6914 $param[
'options'] = $this->fields[$key][
'arrayofkeyval'];
6918 $label = $this->fields[$key][
'label'];
6920 $default = (!empty($this->fields[$key][
'default']) ? $this->fields[$key][
'default'] :
'');
6921 $computed = (!empty($this->fields[$key][
'computed']) ? $this->fields[$key][
'computed'] :
'');
6922 $unique = (!empty($this->fields[$key][
'unique']) ? $this->fields[$key][
'unique'] : 0);
6923 $required = (!empty($this->fields[$key][
'required']) ? $this->fields[$key][
'required'] : 0);
6924 $autofocusoncreate = (!empty($this->fields[$key][
'autofocusoncreate']) ? $this->fields[$key][
'autofocusoncreate'] : 0);
6926 $langfile = (!empty($this->fields[$key][
'langfile']) ? $this->fields[$key][
'langfile'] :
'');
6927 $list = (!empty($this->fields[$key][
'list']) ? $this->fields[$key][
'list'] : 0);
6928 $hidden = (in_array(abs($this->fields[$key][
'visible']), array(0, 2)) ? 1 : 0);
6930 $objectid = $this->id;
6933 if (!preg_match(
'/^search_/', $keyprefix)) {
6934 return '<span class="opacitymedium">'.$langs->trans(
"AutomaticallyCalculated").
'</span>';
6941 if (empty($morecss) && !empty($val[
'css'])) {
6942 $morecss = $val[
'css'];
6943 } elseif (empty($morecss)) {
6944 if ($type ==
'date') {
6945 $morecss =
'minwidth100imp';
6946 } elseif ($type ==
'datetime' || $type ==
'link') {
6947 $morecss =
'minwidth200imp';
6948 } elseif (in_array($type, array(
'int',
'integer',
'price')) || preg_match(
'/^double(\([0-9],[0-9]\)){0,1}/', $type)) {
6949 $morecss =
'maxwidth75';
6950 } elseif ($type ==
'url') {
6951 $morecss =
'minwidth400';
6952 } elseif ($type ==
'boolean') {
6955 if (round($size) < 12) {
6956 $morecss =
'minwidth100';
6957 } elseif (round($size) <= 48) {
6958 $morecss =
'minwidth200';
6960 $morecss =
'minwidth400';
6966 if (!empty($validationClass)) {
6967 $morecss.= $validationClass;
6970 if (in_array($type, array(
'date'))) {
6971 $tmp = explode(
',', $size);
6976 if (!$required && $value ==
'') {
6981 $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required,
'', 1, (($keyprefix !=
'search_' && $keyprefix !=
'search_options_') ? 1 : 0), 0, 1);
6982 } elseif (in_array($type, array(
'datetime'))) {
6983 $tmp = explode(
',', $size);
6988 if (!$required && $value ==
'') $value =
'-1';
6991 $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required,
'', 1, (($keyprefix !=
'search_' && $keyprefix !=
'search_options_') ? 1 : 0), 0, 1,
'',
'',
'', 1,
'',
'',
'tzuserrel');
6992 } elseif (in_array($type, array(
'duration'))) {
6993 $out = $form->select_duration($keyprefix.$key.$keysuffix, $value, 0,
'text', 0, 1);
6994 } elseif (in_array($type, array(
'int',
'integer'))) {
6995 $tmp = explode(
',', $size);
6997 $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' :
'').
'>';
6998 } elseif (in_array($type, array(
'real'))) {
6999 $out =
'<input type="text" class="flat '.$morecss.
'" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.
dol_escape_htmltag($value).
'"'.($moreparam ? $moreparam :
'').($autofocusoncreate ?
' autofocus' :
'').
'>';
7000 } elseif (preg_match(
'/varchar/', $type)) {
7001 $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' :
'').
'>';
7002 } elseif (in_array($type, array(
'email',
'mail',
'phone',
'url',
'ip'))) {
7003 $out =
'<input type="text" class="flat '.$morecss.
'" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.
dol_escape_htmltag($value).
'" '.($moreparam ? $moreparam :
'').($autofocusoncreate ?
' autofocus' :
'').
'>';
7004 } elseif (preg_match(
'/^text/', $type)) {
7005 if (!preg_match(
'/search_/', $keyprefix)) {
7006 require_once DOL_DOCUMENT_ROOT.
'/core/class/doleditor.class.php';
7007 $doleditor =
new DolEditor($keyprefix.$key.$keysuffix, $value,
'', 200,
'dolibarr_notes',
'In',
false,
false,
false, ROWS_5,
'90%');
7008 $out = $doleditor->Create(1);
7010 $out =
'<input type="text" class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.
dol_escape_htmltag($value).
'" '.($moreparam ? $moreparam :
'').
'>';
7012 } elseif (preg_match(
'/^html/', $type)) {
7013 if (!preg_match(
'/search_/', $keyprefix)) {
7014 require_once DOL_DOCUMENT_ROOT.
'/core/class/doleditor.class.php';
7015 $doleditor =
new DolEditor($keyprefix.$key.$keysuffix, $value,
'', 200,
'dolibarr_notes',
'In',
false,
false, isModEnabled(
'fckeditor') && $conf->global->FCKEDITOR_ENABLE_SOCIETE, ROWS_5,
'90%');
7016 $out = $doleditor->Create(1,
'',
true,
'',
'', $moreparam, $morecss);
7018 $out =
'<input type="text" class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.
dol_escape_htmltag($value).
'" '.($moreparam ? $moreparam :
'').
'>';
7020 } elseif ($type ==
'boolean') {
7022 if (!empty($value)) {
7023 $checked =
' checked value="1" ';
7025 $checked =
' value="1" ';
7027 $out =
'<input type="checkbox" class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" '.$checked.
' '.($moreparam ? $moreparam :
'').
'>';
7028 } elseif ($type ==
'price') {
7029 if (!empty($value)) {
7030 $value =
price($value);
7032 $out =
'<input type="text" class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.$value.
'" '.($moreparam ? $moreparam :
'').
'> '.$langs->getCurrencySymbol($conf->currency);
7033 } elseif (preg_match(
'/^double(\([0-9],[0-9]\)){0,1}/', $type)) {
7034 if (!empty($value)) {
7035 $value =
price($value);
7037 $out =
'<input type="text" class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.$value.
'" '.($moreparam ? $moreparam :
'').
'> ';
7038 } elseif ($type ==
'select') {
7040 if (!empty($conf->use_javascript_ajax) && empty($conf->global->MAIN_EXTRAFIELDS_DISABLE_SELECT2)) {
7041 include_once DOL_DOCUMENT_ROOT.
'/core/lib/ajax.lib.php';
7042 $out .=
ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
7045 $out .=
'<select class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" '.($moreparam ? $moreparam :
'').
'>';
7046 if ((!isset($this->fields[$key][
'default'])) || empty($this->fields[$key][
'notnull']) || ($this->fields[$key][
'notnull'] != 1)) {
7047 $out .=
'<option value="0"> </option>';
7049 foreach ($param[
'options'] as $keyb => $valb) {
7050 if ((
string) $keyb ==
'') {
7053 if (strpos($valb,
"|") !==
false) {
7054 list($valb, $parent) = explode(
'|', $valb);
7056 $out .=
'<option value="'.$keyb.
'"';
7057 $out .= (((string) $value == (
string) $keyb) ?
' selected' :
'');
7058 $out .= (!empty($parent) ?
' parent="'.$parent.
'"' :
'');
7059 $out .=
'>'.$valb.
'</option>';
7061 $out .=
'</select>';
7062 } elseif ($type ==
'sellist') {
7064 if (!empty($conf->use_javascript_ajax) && empty($conf->global->MAIN_EXTRAFIELDS_DISABLE_SELECT2)) {
7065 include_once DOL_DOCUMENT_ROOT.
'/core/lib/ajax.lib.php';
7066 $out .=
ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
7069 $out .=
'<select class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" '.($moreparam ? $moreparam :
'').
'>';
7070 if (is_array($param[
'options'])) {
7071 $param_list = array_keys($param[
'options']);
7072 $InfoFieldList = explode(
":", $param_list[0]);
7082 $keyList = (empty($InfoFieldList[2]) ?
'rowid' : $InfoFieldList[2].
' as rowid');
7084 if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
7085 if (strpos($InfoFieldList[4],
'extra.') !==
false) {
7086 $keyList =
'main.'.$InfoFieldList[2].
' as rowid';
7088 $keyList = $InfoFieldList[2].
' as rowid';
7091 if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
7092 list($parentName, $parentField) = explode(
'|', $InfoFieldList[3]);
7093 $keyList .=
', '.$parentField;
7096 $filter_categorie =
false;
7097 if (count($InfoFieldList) > 5) {
7098 if ($InfoFieldList[0] ==
'categorie') {
7099 $filter_categorie =
true;
7103 if ($filter_categorie ===
false) {
7104 $fields_label = explode(
'|', $InfoFieldList[1]);
7105 if (is_array($fields_label)) {
7107 $keyList .= implode(
', ', $fields_label);
7111 $sql =
"SELECT " . $keyList;
7112 $sql .=
" FROM " . $this->db->prefix() . $InfoFieldList[0];
7113 if (!empty($InfoFieldList[4])) {
7115 if (strpos($InfoFieldList[4],
'$SEL$') !==
false) {
7116 $InfoFieldList[4] = str_replace(
'$SEL$',
'SELECT', $InfoFieldList[4]);
7120 if (strpos($InfoFieldList[4],
'$ID$') !==
false && !empty($objectid)) {
7121 $InfoFieldList[4] = str_replace(
'$ID$', $objectid, $InfoFieldList[4]);
7123 $InfoFieldList[4] = str_replace(
'$ID$',
'0', $InfoFieldList[4]);
7127 if (strpos($InfoFieldList[4],
'extra') !==
false) {
7128 $sql .=
" as main, " . $this->db->prefix() . $InfoFieldList[0] .
"_extrafields as extra";
7129 $sqlwhere .=
" WHERE extra.fk_object=main." . $InfoFieldList[2] .
" AND " . $InfoFieldList[4];
7131 $sqlwhere .=
" WHERE " . $InfoFieldList[4];
7134 $sqlwhere .=
' WHERE 1=1';
7137 if (in_array($InfoFieldList[0], array(
'tablewithentity'))) {
7138 $sqlwhere .=
" AND entity = " . ((int) $conf->entity);
7143 $sql .=
' ORDER BY ' . implode(
', ', $fields_label);
7145 dol_syslog(get_class($this) .
'::showInputField type=sellist', LOG_DEBUG);
7146 $resql = $this->db->query($sql);
7148 $out .=
'<option value="0"> </option>';
7149 $num = $this->db->num_rows($resql);
7153 $obj = $this->db->fetch_object($resql);
7157 $fields_label = explode(
'|', $InfoFieldList[1]);
7158 if (count($fields_label) > 1) {
7160 foreach ($fields_label as $field_toshow) {
7161 $labeltoshow .= $obj->$field_toshow .
' ';
7164 $labeltoshow = $obj->{$InfoFieldList[1]};
7166 $labeltoshow =
dol_trunc($labeltoshow, 45);
7168 if ($value == $obj->rowid) {
7169 foreach ($fields_label as $field_toshow) {
7170 $translabel = $langs->trans($obj->$field_toshow);
7171 if ($translabel != $obj->$field_toshow) {
7172 $labeltoshow =
dol_trunc($translabel) .
' ';
7174 $labeltoshow =
dol_trunc($obj->$field_toshow) .
' ';
7177 $out .=
'<option value="' . $obj->rowid .
'" selected>' . $labeltoshow .
'</option>';
7180 $translabel = $langs->trans($obj->{$InfoFieldList[1]});
7181 if ($translabel != $obj->{$InfoFieldList[1]}) {
7182 $labeltoshow =
dol_trunc($translabel, 18);
7184 $labeltoshow =
dol_trunc($obj->{$InfoFieldList[1]});
7187 if (empty($labeltoshow)) {
7188 $labeltoshow =
'(not defined)';
7190 if ($value == $obj->rowid) {
7191 $out .=
'<option value="' . $obj->rowid .
'" selected>' . $labeltoshow .
'</option>';
7194 if (!empty($InfoFieldList[3]) && $parentField) {
7195 $parent = $parentName .
':' . $obj->{$parentField};
7199 $out .=
'<option value="' . $obj->rowid .
'"';
7200 $out .= ($value == $obj->rowid ?
' selected' :
'');
7201 $out .= (!empty($parent) ?
' parent="' . $parent .
'"' :
'');
7202 $out .=
'>' . $labeltoshow .
'</option>';
7207 $this->db->free($resql);
7209 print
'Error in request ' . $sql .
' ' . $this->db->lasterror() .
'. Check setup of extra parameters.<br>';
7212 require_once DOL_DOCUMENT_ROOT.
'/categories/class/categorie.class.php';
7213 $data = $form->select_all_categories(Categorie::$MAP_ID_TO_CODE[$InfoFieldList[5]],
'',
'parent', 64, $InfoFieldList[6], 1, 1);
7214 $out .=
'<option value="0"> </option>';
7215 foreach ($data as $data_key => $data_value) {
7216 $out .=
'<option value="' . $data_key .
'"';
7217 $out .= ($value == $data_key ?
' selected' :
'');
7218 $out .=
'>' . $data_value .
'</option>';
7222 $out .=
'</select>';
7223 } elseif ($type ==
'checkbox') {
7224 $value_arr = explode(
',', $value);
7225 $out = $form->multiselectarray($keyprefix.$key.$keysuffix, (empty($param[
'options']) ?
null:$param[
'options']), $value_arr,
'', 0, $morecss, 0,
'100%');
7226 } elseif ($type ==
'radio') {
7228 foreach ($param[
'options'] as $keyopt => $valopt) {
7229 $out .=
'<input class="flat '.$morecss.
'" type="radio" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" '.($moreparam ? $moreparam :
'');
7230 $out .=
' value="'.$keyopt.
'"';
7231 $out .=
' id="'.$keyprefix.$key.$keysuffix.
'_'.$keyopt.
'"';
7232 $out .= ($value == $keyopt ?
'checked' :
'');
7233 $out .=
'/><label for="'.$keyprefix.$key.$keysuffix.
'_'.$keyopt.
'">'.$valopt.
'</label><br>';
7235 } elseif ($type ==
'chkbxlst') {
7236 if (is_array($value)) {
7237 $value_arr = $value;
7239 $value_arr = explode(
',', $value);
7242 if (is_array($param[
'options'])) {
7243 $param_list = array_keys($param[
'options']);
7244 $InfoFieldList = explode(
":", $param_list[0]);
7254 $keyList = (empty($InfoFieldList[2]) ?
'rowid' : $InfoFieldList[2].
' as rowid');
7256 if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
7257 list ($parentName, $parentField) = explode(
'|', $InfoFieldList[3]);
7258 $keyList .=
', '.$parentField;
7260 if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
7261 if (strpos($InfoFieldList[4],
'extra.') !==
false) {
7262 $keyList =
'main.'.$InfoFieldList[2].
' as rowid';
7264 $keyList = $InfoFieldList[2].
' as rowid';
7268 $filter_categorie =
false;
7269 if (count($InfoFieldList) > 5) {
7270 if ($InfoFieldList[0] ==
'categorie') {
7271 $filter_categorie =
true;
7275 if ($filter_categorie ===
false) {
7276 $fields_label = explode(
'|', $InfoFieldList[1]);
7277 if (is_array($fields_label)) {
7279 $keyList .= implode(
', ', $fields_label);
7283 $sql =
"SELECT " . $keyList;
7284 $sql .=
' FROM ' . $this->db->prefix() . $InfoFieldList[0];
7285 if (!empty($InfoFieldList[4])) {
7287 if (strpos($InfoFieldList[4],
'$SEL$') !==
false) {
7288 $InfoFieldList[4] = str_replace(
'$SEL$',
'SELECT', $InfoFieldList[4]);
7292 if (strpos($InfoFieldList[4],
'$ID$') !==
false && !empty($objectid)) {
7293 $InfoFieldList[4] = str_replace(
'$ID$', $objectid, $InfoFieldList[4]);
7295 $InfoFieldList[4] = str_replace(
'$ID$',
'0', $InfoFieldList[4]);
7299 if (strpos($InfoFieldList[4],
'extra') !==
false) {
7300 $sql .=
' as main, ' . $this->db->prefix() . $InfoFieldList[0] .
'_extrafields as extra';
7301 $sqlwhere .=
" WHERE extra.fk_object=main." . $InfoFieldList[2] .
" AND " . $InfoFieldList[4];
7303 $sqlwhere .=
" WHERE " . $InfoFieldList[4];
7306 $sqlwhere .=
' WHERE 1=1';
7309 if (in_array($InfoFieldList[0], array(
'tablewithentity'))) {
7310 $sqlwhere .=
" AND entity = " . ((int) $conf->entity);
7316 dol_syslog(get_class($this) .
'::showInputField type=chkbxlst', LOG_DEBUG);
7317 $resql = $this->db->query($sql);
7319 $num = $this->db->num_rows($resql);
7326 $obj = $this->db->fetch_object($resql);
7330 $fields_label = explode(
'|', $InfoFieldList[1]);
7331 if (count($fields_label) > 1) {
7333 foreach ($fields_label as $field_toshow) {
7334 $labeltoshow .= $obj->$field_toshow .
' ';
7337 $labeltoshow = $obj->{$InfoFieldList[1]};
7339 $labeltoshow =
dol_trunc($labeltoshow, 45);
7341 if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
7342 foreach ($fields_label as $field_toshow) {
7343 $translabel = $langs->trans($obj->$field_toshow);
7344 if ($translabel != $obj->$field_toshow) {
7345 $labeltoshow =
dol_trunc($translabel, 18) .
' ';
7347 $labeltoshow =
dol_trunc($obj->$field_toshow, 18) .
' ';
7351 $data[$obj->rowid] = $labeltoshow;
7354 $translabel = $langs->trans($obj->{$InfoFieldList[1]});
7355 if ($translabel != $obj->{$InfoFieldList[1]}) {
7356 $labeltoshow =
dol_trunc($translabel, 18);
7358 $labeltoshow =
dol_trunc($obj->{$InfoFieldList[1]}, 18);
7361 if (empty($labeltoshow)) {
7362 $labeltoshow =
'(not defined)';
7365 if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
7366 $data[$obj->rowid] = $labeltoshow;
7369 if (!empty($InfoFieldList[3]) && $parentField) {
7370 $parent = $parentName .
':' . $obj->{$parentField};
7374 $data[$obj->rowid] = $labeltoshow;
7379 $this->db->free($resql);
7381 $out = $form->multiselectarray($keyprefix . $key . $keysuffix, $data, $value_arr,
'', 0, $morecss, 0,
'100%');
7383 print
'Error in request ' . $sql .
' ' . $this->db->lasterror() .
'. Check setup of extra parameters.<br>';
7386 require_once DOL_DOCUMENT_ROOT.
'/categories/class/categorie.class.php';
7387 $data = $form->select_all_categories(Categorie::$MAP_ID_TO_CODE[$InfoFieldList[5]],
'',
'parent', 64, $InfoFieldList[6], 1, 1);
7388 $out = $form->multiselectarray($keyprefix . $key . $keysuffix, $data, $value_arr,
'', 0, $morecss, 0,
'100%');
7391 } elseif ($type ==
'link') {
7392 $param_list = array_keys($param[
'options']);
7393 $param_list_array = explode(
':', $param_list[0]);
7394 $showempty = (($required && $default !=
'') ? 0 : 1);
7396 if (!preg_match(
'/search_/', $keyprefix)) {
7397 if (!empty($param_list_array[2])) {
7398 if (!empty($this->fields[$key][
'picto'])) {
7399 $morecss .=
' widthcentpercentminusxx';
7401 $morecss .=
' widthcentpercentminusx';
7404 if (!empty($this->fields[$key][
'picto'])) {
7405 $morecss .=
' widthcentpercentminusx';
7410 $out = $form->selectForForms($param_list[0], $keyprefix.$key.$keysuffix, $value, $showempty,
'',
'', $morecss, $moreparam, 0, empty($val[
'disabled']) ? 0 : 1);
7412 if (!empty($param_list_array[2])) {
7413 if ((!GETPOSTISSET(
'backtopage') || strpos(
GETPOST(
'backtopage'), $_SERVER[
'PHP_SELF']) === 0)
7414 && empty($val[
'disabled']) && empty($nonewbutton)) {
7415 list($class, $classfile) = explode(
':', $param_list[0]);
7416 if (file_exists(
dol_buildpath(dirname(dirname($classfile)).
'/card.php'))) {
7417 $url_path =
dol_buildpath(dirname(dirname($classfile)).
'/card.php', 1);
7419 $url_path =
dol_buildpath(dirname(dirname($classfile)).
'/'.strtolower($class).
'_card.php', 1);
7421 $paramforthenewlink =
'';
7422 $paramforthenewlink .= (GETPOSTISSET(
'action') ?
'&action='.GETPOST(
'action',
'aZ09') :
'');
7423 $paramforthenewlink .= (GETPOSTISSET(
'id') ?
'&id='.GETPOST(
'id',
'int') :
'');
7424 $paramforthenewlink .= (GETPOSTISSET(
'origin') ?
'&origin='.GETPOST(
'origin',
'aZ09') :
'');
7425 $paramforthenewlink .= (GETPOSTISSET(
'originid') ?
'&originid='.GETPOST(
'originid',
'int') :
'');
7426 $paramforthenewlink .=
'&fk_'.strtolower($class).
'=--IDFORBACKTOPAGE--';
7428 $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>';
7431 } elseif ($type ==
'password') {
7433 $out =
'<input type="'.($keyprefix ==
'search_' ?
'text' :
'password').
'" class="flat '.$morecss.
'" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.$value.
'" '.($moreparam ? $moreparam :
'').
'>';
7434 } elseif ($type ==
'array') {
7436 $newval[
'type'] =
'varchar(256)';
7439 if (!empty($value)) {
7440 foreach ($value as $option) {
7441 $out .=
'<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).
'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
7442 $out .= $this->showInputField($newval, $keyprefix.$key.$keysuffix.
'[]', $option, $moreparam,
'',
'', $morecss).
'<br></span>';
7445 $out .=
'<a id="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).
'_add" href="javascript:;"><span class="fa fa-plus-circle valignmiddle"></span></a>';
7447 $newInput =
'<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).
'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
7448 $newInput .= $this->showInputField($newval, $keyprefix.$key.$keysuffix.
'[]',
'', $moreparam,
'',
'', $morecss).
'<br></span>';
7450 if (!empty($conf->use_javascript_ajax)) {
7452 <script nonce="'.getNonce().
'">
7453 $(document).ready(function() {
7454 $("a#'.
dol_escape_js($keyprefix.$key.$keysuffix).
'_add").click(function() {
7458 $(document).on("click", "a.'.
dol_escape_js($keyprefix.$key.$keysuffix).
'_del", function() {
7459 $(this).parent().remove();
7465 if (!empty($hidden)) {
7466 $out =
'<input type="hidden" value="'.$value.
'" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'"/>';
7469 if ($isDependList==1) {
7470 $out .= $this->getJSListDependancies(
'_common');
7478 if (!empty($fieldValidationErrorMsg) && function_exists(
'getFieldErrorIcon')) {
7479 $out .=
' '.getFieldErrorIcon($fieldValidationErrorMsg);
7498 public function showOutputField($val, $key, $value, $moreparam =
'', $keysuffix =
'', $keyprefix =
'', $morecss =
'')
7500 global $conf, $langs, $form;
7502 if (!is_object($form)) {
7503 require_once DOL_DOCUMENT_ROOT.
'/core/class/html.form.class.php';
7504 $form =
new Form($this->db);
7507 $label = empty($val[
'label']) ?
'' : $val[
'label'];
7508 $type = empty($val[
'type']) ?
'' : $val[
'type'];
7509 $size = empty($val[
'css']) ?
'' : $val[
'css'];
7513 if (preg_match(
'/varchar\((\d+)\)/', $type, $reg)) {
7516 } elseif (preg_match(
'/varchar/', $type)) {
7519 if (!empty($val[
'arrayofkeyval']) && is_array($val[
'arrayofkeyval'])) {
7522 if (preg_match(
'/^integer:(.*):(.*)/i', $val[
'type'], $reg)) {
7526 $default = empty($val[
'default']) ?
'' : $val[
'default'];
7527 $computed = empty($val[
'computed']) ?
'' : $val[
'computed'];
7528 $unique = empty($val[
'unique']) ?
'' : $val[
'unique'];
7529 $required = empty($val[
'required']) ?
'' : $val[
'required'];
7531 $param[
'options'] = array();
7533 if (!empty($val[
'arrayofkeyval']) && is_array($val[
'arrayofkeyval'])) {
7534 $param[
'options'] = $val[
'arrayofkeyval'];
7536 if (preg_match(
'/^integer:(.*):(.*)/i', $val[
'type'], $reg)) {
7538 $stringforoptions = $reg[1].
':'.$reg[2];
7539 if ($reg[1] ==
'User') {
7540 $stringforoptions .=
':-1';
7542 $param[
'options'] = array($stringforoptions => $stringforoptions);
7543 } elseif (preg_match(
'/^sellist:(.*):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
7544 $param[
'options'] = array($reg[1].
':'.$reg[2].
':'.$reg[3].
':'.$reg[4] =>
'N');
7546 } elseif (preg_match(
'/^sellist:(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
7547 $param[
'options'] = array($reg[1].
':'.$reg[2].
':'.$reg[3] =>
'N');
7549 } elseif (preg_match(
'/^sellist:(.*):(.*)/i', $val[
'type'], $reg)) {
7550 $param[
'options'] = array($reg[1].
':'.$reg[2] =>
'N');
7552 } elseif (preg_match(
'/^chkbxlst:(.*)/i', $val[
'type'], $reg)) {
7553 $param[
'options'] = array($reg[1] =>
'N');
7557 $langfile = empty($val[
'langfile']) ?
'' : $val[
'langfile'];
7558 $list = (empty($val[
'list']) ?
'' : $val[
'list']);
7559 $help = (empty($val[
'help']) ?
'' : $val[
'help']);
7560 $hidden = (($val[
'visible'] == 0) ? 1 : 0);
7570 $value =
dol_eval($computed, 1, 0,
'');
7573 if (empty($morecss)) {
7574 if ($type ==
'date') {
7575 $morecss =
'minwidth100imp';
7576 } elseif ($type ==
'datetime' || $type ==
'timestamp') {
7577 $morecss =
'minwidth200imp';
7578 } elseif (in_array($type, array(
'int',
'double',
'price'))) {
7579 $morecss =
'maxwidth75';
7580 } elseif ($type ==
'url') {
7581 $morecss =
'minwidth400';
7582 } elseif ($type ==
'boolean') {
7585 if (is_numeric($size) && round($size) < 12) {
7586 $morecss =
'minwidth100';
7587 } elseif (is_numeric($size) && round($size) <= 48) {
7588 $morecss =
'minwidth200';
7590 $morecss =
'minwidth400';
7596 if (in_array($key, array(
'rowid',
'ref')) && method_exists($this,
'getNomUrl')) {
7597 if ($key !=
'rowid' || empty($this->fields[
'ref'])) {
7598 $value = $this->getNomUrl(1,
'', 0,
'', 1);
7600 } elseif ($key ==
'status' && method_exists($this,
'getLibStatut')) {
7601 $value = $this->getLibStatut(3);
7602 } elseif ($type ==
'date') {
7603 if (!empty($value)) {
7608 } elseif ($type ==
'datetime' || $type ==
'timestamp') {
7609 if (!empty($value)) {
7614 } elseif ($type ==
'duration') {
7615 include_once DOL_DOCUMENT_ROOT.
'/core/lib/date.lib.php';
7616 if (!is_null($value) && $value !==
'') {
7619 } elseif ($type ==
'double' || $type ==
'real') {
7620 if (!is_null($value) && $value !==
'') {
7621 $value =
price($value);
7623 } elseif ($type ==
'boolean') {
7625 if (!empty($value)) {
7626 $checked =
' checked ';
7628 $value =
'<input type="checkbox" '.$checked.
' '.($moreparam ? $moreparam :
'').
' readonly disabled>';
7629 } elseif ($type ==
'mail' || $type ==
'email') {
7631 } elseif ($type ==
'url') {
7633 } elseif ($type ==
'phone') {
7635 } elseif ($type ==
'ip') {
7637 } elseif ($type ==
'price') {
7638 if (!is_null($value) && $value !==
'') {
7639 $value =
price($value, 0, $langs, 0, 0, -1, $conf->currency);
7641 } elseif ($type ==
'select') {
7642 $value = isset($param[
'options'][$value])?$param[
'options'][$value]:
'';
7643 } elseif ($type ==
'sellist') {
7644 $param_list = array_keys($param[
'options']);
7645 $InfoFieldList = explode(
":", $param_list[0]);
7647 $selectkey =
"rowid";
7650 if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
7651 $selectkey = $InfoFieldList[2];
7652 $keyList = $InfoFieldList[2].
' as rowid';
7655 $fields_label = explode(
'|', $InfoFieldList[1]);
7656 if (is_array($fields_label)) {
7658 $keyList .= implode(
', ', $fields_label);
7661 $filter_categorie =
false;
7662 if (count($InfoFieldList) > 5) {
7663 if ($InfoFieldList[0] ==
'categorie') {
7664 $filter_categorie =
true;
7668 $sql =
"SELECT ".$keyList;
7669 $sql .=
' FROM '.$this->db->prefix().$InfoFieldList[0];
7670 if (strpos($InfoFieldList[4],
'extra') !==
false) {
7673 if ($selectkey ==
'rowid' && empty($value)) {
7674 $sql .=
" WHERE ".$selectkey.
" = 0";
7675 } elseif ($selectkey ==
'rowid') {
7676 $sql .=
" WHERE ".$selectkey.
" = ".((int) $value);
7678 $sql .=
" WHERE ".$selectkey.
" = '".$this->db->escape($value).
"'";
7683 dol_syslog(get_class($this).
':showOutputField:$type=sellist', LOG_DEBUG);
7684 $resql = $this->db->query($sql);
7686 if ($filter_categorie ===
false) {
7688 $numrows = $this->db->num_rows($resql);
7690 $obj = $this->db->fetch_object($resql);
7693 $fields_label = explode(
'|', $InfoFieldList[1]);
7695 if (is_array($fields_label) && count($fields_label) > 1) {
7696 foreach ($fields_label as $field_toshow) {
7698 if (!empty($obj->$field_toshow)) {
7699 $translabel = $langs->trans($obj->$field_toshow);
7701 if ($translabel != $field_toshow) {
7702 $value .=
dol_trunc($translabel, 18) .
' ';
7704 $value .= $obj->$field_toshow .
' ';
7709 if (!empty($obj->{$InfoFieldList[1]})) {
7710 $translabel = $langs->trans($obj->{$InfoFieldList[1]});
7712 if ($translabel != $obj->{$InfoFieldList[1]}) {
7715 $value = $obj->{$InfoFieldList[1]};
7720 require_once DOL_DOCUMENT_ROOT .
'/categories/class/categorie.class.php';
7723 $obj = $this->db->fetch_object($resql);
7725 $c->fetch($obj->rowid);
7726 $ways = $c->print_all_ways();
7727 foreach ($ways as $way) {
7728 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories"' . ($c->color ?
' style="background: #' . $c->color .
';"' :
' style="background: #aaa"') .
'>' .
img_object(
'',
'category') .
' ' . $way .
'</li>';
7730 $value =
'<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(
' ', $toprint).
'</ul></div>';
7733 dol_syslog(get_class($this).
'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
7735 } elseif ($type ==
'radio') {
7736 $value = $param[
'options'][$value];
7737 } elseif ($type ==
'checkbox') {
7738 $value_arr = explode(
',', $value);
7740 if (is_array($value_arr) && count($value_arr) > 0) {
7742 foreach ($value_arr as $keyval => $valueval) {
7743 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">'.$param[
'options'][$valueval].
'</li>';
7745 $value =
'<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(
' ', $toprint).
'</ul></div>';
7747 } elseif ($type ==
'chkbxlst') {
7748 $value_arr = explode(
',', $value);
7750 $param_list = array_keys($param[
'options']);
7751 $InfoFieldList = explode(
":", $param_list[0]);
7753 $selectkey =
"rowid";
7756 if (count($InfoFieldList) >= 3) {
7757 $selectkey = $InfoFieldList[2];
7758 $keyList = $InfoFieldList[2].
' as rowid';
7761 $fields_label = explode(
'|', $InfoFieldList[1]);
7762 if (is_array($fields_label)) {
7764 $keyList .= implode(
', ', $fields_label);
7767 $filter_categorie =
false;
7768 if (count($InfoFieldList) > 5) {
7769 if ($InfoFieldList[0] ==
'categorie') {
7770 $filter_categorie =
true;
7774 $sql =
"SELECT ".$keyList;
7775 $sql .=
' FROM '.$this->db->prefix().$InfoFieldList[0];
7776 if (strpos($InfoFieldList[4],
'extra') !==
false) {
7782 dol_syslog(get_class($this).
':showOutputField:$type=chkbxlst', LOG_DEBUG);
7783 $resql = $this->db->query($sql);
7785 if ($filter_categorie ===
false) {
7788 while ($obj = $this->db->fetch_object($resql)) {
7790 $fields_label = explode(
'|', $InfoFieldList[1]);
7791 if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
7792 if (is_array($fields_label) && count($fields_label) > 1) {
7793 foreach ($fields_label as $field_toshow) {
7795 if (!empty($obj->$field_toshow)) {
7796 $translabel = $langs->trans($obj->$field_toshow);
7798 if ($translabel != $field_toshow) {
7799 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' .
dol_trunc($translabel, 18) .
'</li>';
7801 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' . $obj->$field_toshow .
'</li>';
7806 if (!empty($obj->{$InfoFieldList[1]})) {
7807 $translabel = $langs->trans($obj->{$InfoFieldList[1]});
7809 if ($translabel != $obj->{$InfoFieldList[1]}) {
7810 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' .
dol_trunc($translabel, 18) .
'</li>';
7812 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' . $obj->{$InfoFieldList[1]} .
'</li>';
7818 require_once DOL_DOCUMENT_ROOT .
'/categories/class/categorie.class.php';
7821 while ($obj = $this->db->fetch_object($resql)) {
7822 if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
7824 $c->fetch($obj->rowid);
7825 $ways = $c->print_all_ways();
7826 foreach ($ways as $way) {
7827 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories"' . ($c->color ?
' style="background: #' . $c->color .
';"' :
' style="background: #aaa"') .
'>' .
img_object(
'',
'category') .
' ' . $way .
'</li>';
7832 $value =
'<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(
' ', $toprint).
'</ul></div>';
7834 dol_syslog(get_class($this).
'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
7836 } elseif ($type ==
'link') {
7841 $param_list = array_keys($param[
'options']);
7843 $InfoFieldList = explode(
":", $param_list[0]);
7844 $classname = $InfoFieldList[0];
7845 $classpath = $InfoFieldList[1];
7846 $getnomurlparam = (empty($InfoFieldList[2]) ? 3 : $InfoFieldList[2]);
7847 $getnomurlparam2 = (empty($InfoFieldList[4]) ?
'' : $InfoFieldList[4]);
7848 if (!empty($classpath)) {
7850 if ($classname && class_exists($classname)) {
7851 $object =
new $classname($this->db);
7852 if ($object->element ===
'product') {
7853 $result = $object->fetch($value,
'',
'',
'', 0, 1, 1);
7855 $result = $object->fetch($value);
7858 if ($object->element ===
'product') {
7859 $get_name_url_param_arr = array($getnomurlparam, $getnomurlparam2, 0, -1, 0,
'', 0);
7860 if (isset($val[
'get_name_url_params'])) {
7861 $get_name_url_params = explode(
':', $val[
'get_name_url_params']);
7862 if (!empty($get_name_url_params)) {
7863 $param_num_max = count($get_name_url_param_arr) - 1;
7864 foreach ($get_name_url_params as $param_num => $param_value) {
7865 if ($param_num > $param_num_max) {
7868 $get_name_url_param_arr[$param_num] = $param_value;
7876 $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]);
7878 $value = $object->getNomUrl($getnomurlparam, $getnomurlparam2);
7885 dol_syslog(
'Error bad setup of extrafield', LOG_WARNING);
7886 return 'Error bad setup of extrafield';
7891 } elseif ($type ==
'password') {
7892 $value = preg_replace(
'/./i',
'*', $value);
7893 } elseif ($type ==
'array') {
7894 $value = implode(
'<br>', $value);
7914 unset($this->validateFieldsErrors[$fieldKey]);
7928 $msg = $langs->trans(
"UnknowError");
7931 $this->error = $this->validateFieldsErrors[$fieldKey] = $msg;
7942 if (!empty($this->validateFieldsErrors[$fieldKey])) {
7943 return $this->validateFieldsErrors[$fieldKey];
7960 if (!class_exists(
'Validate')) {
7961 require_once DOL_DOCUMENT_ROOT .
'/core/class/validate.class.php';
7964 $this->clearFieldError($fieldKey);
7966 if (!isset($fields[$fieldKey])) {
7967 $this->setFieldError($fieldKey, $langs->trans(
'FieldNotFoundInObject'));
7971 $val = $fields[$fieldKey];
7974 $param[
'options'] = array();
7975 $type = $val[
'type'];
7978 if (isset($val[
'notnull']) && $val[
'notnull'] === 1) {
7992 if (preg_match(
'/varchar\((\d+)\)/', $type, $reg)) {
7995 } elseif (preg_match(
'/varchar/', $type)) {
7999 if (!empty($val[
'arrayofkeyval']) && is_array($val[
'arrayofkeyval'])) {
8003 if (!empty($val[
'type']) && preg_match(
'/^integer:(.*):(.*)/i', $val[
'type'], $reg)) {
8007 if (!empty($val[
'arrayofkeyval']) && is_array($val[
'arrayofkeyval'])) {
8008 $param[
'options'] = $val[
'arrayofkeyval'];
8011 if (preg_match(
'/^integer:(.*):(.*)/i', $val[
'type'], $reg)) {
8013 $param[
'options'] = array($reg[1].
':'.$reg[2]=>$reg[1].
':'.$reg[2]);
8014 } elseif (preg_match(
'/^sellist:(.*):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
8015 $param[
'options'] = array($reg[1].
':'.$reg[2].
':'.$reg[3].
':'.$reg[4] =>
'N');
8017 } elseif (preg_match(
'/^sellist:(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
8018 $param[
'options'] = array($reg[1].
':'.$reg[2].
':'.$reg[3] =>
'N');
8020 } elseif (preg_match(
'/^sellist:(.*):(.*)/i', $val[
'type'], $reg)) {
8021 $param[
'options'] = array($reg[1].
':'.$reg[2] =>
'N');
8030 $validate =
new Validate($this->db, $langs);
8040 if ($required && !$validate->isNotEmptyString($fieldValue)) {
8041 $this->setFieldError($fieldKey, $validate->error);
8043 } elseif (!$required && !$validate->isNotEmptyString($fieldValue)) {
8049 if (!empty($maxSize) && !$validate->isMaxLength($fieldValue, $maxSize)) {
8050 $this->setFieldError($fieldKey, $validate->error);
8055 if (!empty($minSize) && !$validate->isMinLength($fieldValue, $minSize)) {
8056 $this->setFieldError($fieldKey, $validate->error);
8064 if (in_array($type, array(
'date',
'datetime',
'timestamp'))) {
8065 if (!$validate->isTimestamp($fieldValue)) {
8066 $this->setFieldError($fieldKey, $validate->error);
8068 }
else {
return true; }
8069 } elseif ($type ==
'duration') {
8070 if (!$validate->isDuration($fieldValue)) {
8071 $this->setFieldError($fieldKey, $validate->error);
8073 }
else {
return true; }
8074 } elseif (in_array($type, array(
'double',
'real',
'price'))) {
8076 if (!$validate->isNumeric($fieldValue)) {
8077 $this->setFieldError($fieldKey, $validate->error);
8079 }
else {
return true; }
8080 } elseif ($type ==
'boolean') {
8081 if (!$validate->isBool($fieldValue)) {
8082 $this->setFieldError($fieldKey, $validate->error);
8084 }
else {
return true; }
8085 } elseif ($type ==
'mail') {
8086 if (!$validate->isEmail($fieldValue)) {
8087 $this->setFieldError($fieldKey, $validate->error);
8090 } elseif ($type ==
'url') {
8091 if (!$validate->isUrl($fieldValue)) {
8092 $this->setFieldError($fieldKey, $validate->error);
8094 }
else {
return true; }
8095 } elseif ($type ==
'phone') {
8096 if (!$validate->isPhone($fieldValue)) {
8097 $this->setFieldError($fieldKey, $validate->error);
8099 }
else {
return true; }
8100 } elseif ($type ==
'select' || $type ==
'radio') {
8101 if (!isset($param[
'options'][$fieldValue])) {
8102 $this->error = $langs->trans(
'RequireValidValue');
8104 }
else {
return true; }
8105 } elseif ($type ==
'sellist' || $type ==
'chkbxlst') {
8106 $param_list = array_keys($param[
'options']);
8107 $InfoFieldList = explode(
":", $param_list[0]);
8108 $value_arr = explode(
',', $fieldValue);
8109 $value_arr = array_map(array($this->db,
'escape'), $value_arr);
8111 $selectkey =
"rowid";
8112 if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
8113 $selectkey = $InfoFieldList[2];
8116 if (!$validate->isInDb($value_arr, $InfoFieldList[0], $selectkey)) {
8117 $this->setFieldError($fieldKey, $validate->error);
8119 }
else {
return true; }
8120 } elseif ($type ==
'link') {
8121 $param_list = array_keys($param[
'options']);
8122 $InfoFieldList = explode(
":", $param_list[0]);
8123 $classname = $InfoFieldList[0];
8124 $classpath = $InfoFieldList[1];
8125 if (!$validate->isFetchable($fieldValue, $classname, $classpath)) {
8126 $this->setFieldError($fieldKey, $validate->error);
8128 }
else {
return true; }
8148 public function showOptionals($extrafields, $mode =
'view', $params =
null, $keysuffix =
'', $keyprefix =
'', $onetrtd = 0, $display_type =
'card')
8150 global $db, $conf, $langs, $action, $form, $hookmanager;
8152 if (!is_object($form)) {
8153 $form =
new Form($db);
8155 if (!is_object($extrafields)) {
8156 dol_syslog(
'Bad parameter extrafields for showOptionals', LOG_ERR);
8157 return 'Bad parameter extrafields for showOptionals';
8159 if (!is_array($extrafields->attributes[$this->table_element])) {
8160 dol_syslog(
"extrafields->attributes was not loaded with extrafields->fetch_name_optionals_label(table_element);", LOG_WARNING);
8165 $parameters = array(
'mode'=>$mode,
'params'=>$params,
'keysuffix'=>$keysuffix,
'keyprefix'=>$keyprefix,
'display_type'=>$display_type);
8166 $reshook = $hookmanager->executeHooks(
'showOptionals', $parameters, $this, $action);
8168 if (empty($reshook)) {
8169 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) {
8171 $out .=
'<!-- commonobject:showOptionals --> ';
8174 $nbofextrafieldsshown = 0;
8177 $lastseparatorkeyfound =
'';
8178 $extrafields_collapse_num =
'';
8179 $extrafields_collapse_num_old =
'';
8182 foreach ($extrafields->attributes[$this->table_element][
'label'] as $key => $label) {
8186 if (is_array($params) && array_key_exists(
'onlykey', $params) && $key != $params[
'onlykey']) {
8192 if ($enabled && isset($extrafields->attributes[$this->table_element][
'enabled'][$key])) {
8193 $enabled =
dol_eval($extrafields->attributes[$this->table_element][
'enabled'][$key], 1, 1,
'2');
8195 if (empty($enabled)) {
8200 if ($visibility && isset($extrafields->attributes[$this->table_element][
'list'][$key])) {
8201 $visibility =
dol_eval($extrafields->attributes[$this->table_element][
'list'][$key], 1, 1,
'2');
8205 if ($perms && isset($extrafields->attributes[$this->table_element][
'perms'][$key])) {
8206 $perms =
dol_eval($extrafields->attributes[$this->table_element][
'perms'][$key], 1, 1,
'2');
8209 if (($mode ==
'create') && abs($visibility) != 1 && abs($visibility) != 3) {
8211 } elseif (($mode ==
'edit') && abs($visibility) != 1 && abs($visibility) != 3 && abs($visibility) != 4) {
8213 $ef_name =
'options_' . $key;
8214 $ef_value = $this->array_options[$ef_name];
8215 $out .=
'<input type="hidden" name="' . $ef_name .
'" id="' . $ef_name .
'" value="' . $ef_value .
'" />' .
"\n";
8217 } elseif ($mode ==
'view' && empty($visibility)) {
8220 if (empty($perms)) {
8225 if (!empty($extrafields->attributes[$this->table_element][
'langfile'][$key])) {
8226 $langs->load($extrafields->attributes[$this->table_element][
'langfile'][$key]);
8230 if (is_array($params) && count($params) > 0 && $display_type==
'card') {
8231 if (array_key_exists(
'cols', $params)) {
8232 $colspan = $params[
'cols'];
8233 } elseif (array_key_exists(
'colspan', $params)) {
8235 if (preg_match(
'/colspan="(\d+)"/', $params[
'colspan'], $reg)) {
8238 $colspan = $params[
'colspan'];
8242 $colspan = intval($colspan);
8246 $value = ((!empty($this->array_options) && array_key_exists(
"options_".$key.$keysuffix, $this->array_options)) ? $this->array_options[
"options_".$key.$keysuffix] :
null);
8252 $check =
'alphanohtml';
8253 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'html',
'text'))) {
8254 $check =
'restricthtml';
8256 $getposttemp =
GETPOST($keyprefix.
'options_'.$key.$keysuffix, $check, 3);
8258 if (is_array($getposttemp) || $getposttemp !=
'' || GETPOSTISSET($keyprefix.
'options_'.$key.$keysuffix)) {
8259 if (is_array($getposttemp)) {
8261 $value = implode(
",", $getposttemp);
8263 $value = $getposttemp;
8266 $value = (!empty($this->array_options[
"options_".$key]) ? $this->array_options[
"options_".$key] :
'');
8272 $nbofextrafieldsshown++;
8275 if ($extrafields->attributes[$this->table_element][
'type'][$key] ==
'separate') {
8276 $extrafields_collapse_num = $key;
8294 $out .= $extrafields->showSeparator($key, $this, ($colspan ? $colspan + 1 : 2), $display_type, $mode);
8296 $lastseparatorkeyfound = $key;
8298 $collapse_group = $extrafields_collapse_num.(!empty($this->
id) ?
'_'.$this->id :
'');
8300 $class = (!empty($extrafields->attributes[$this->table_element][
'hidden'][$key]) ?
'hideobject ' :
'');
8302 if (is_array($params) && count($params) > 0) {
8303 if (array_key_exists(
'class', $params)) {
8304 $class .= $params[
'class'].
' ';
8306 if (array_key_exists(
'style', $params)) {
8307 $csstyle = $params[
'style'];
8312 $domData =
' data-element="extrafield"';
8313 $domData .=
' data-targetelement="'.$this->element.
'"';
8314 $domData .=
' data-targetid="'.$this->id.
'"';
8316 $html_id = (empty($this->
id) ?
'' :
'extrarow-'.$this->element.
'_'.$key.
'_'.$this->id);
8317 if ($display_type==
'card') {
8318 if (!empty($conf->global->MAIN_EXTRAFIELDS_USE_TWO_COLUMS) && ($e % 2) == 0) {
8322 if ($action ==
'selectlines') {
8328 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'date'))) {
8329 $datenotinstring =
null;
8330 if (array_key_exists(
'options_'.$key, $this->array_options)) {
8331 $datenotinstring = $this->array_options[
'options_'.$key];
8332 if (!is_numeric($this->array_options[
'options_'.$key])) {
8333 $datenotinstring = $this->db->jdate($datenotinstring);
8336 $datekey = $keyprefix.
'options_'.$key.$keysuffix;
8337 $value = (GETPOSTISSET($datekey) && $this->
id ==
GETPOST(
'elrowid',
'int')) ?
dol_mktime(12, 0, 0,
GETPOST($datekey.
'month',
'int', 3),
GETPOST($datekey.
'day',
'int', 3),
GETPOST($datekey.
'year',
'int', 3)) : $datenotinstring;
8339 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'datetime'))) {
8340 $datenotinstring =
null;
8341 if (array_key_exists(
'options_'.$key, $this->array_options)) {
8342 $datenotinstring = $this->array_options[
'options_'.$key];
8343 if (!is_numeric($this->array_options[
'options_'.$key])) {
8344 $datenotinstring = $this->db->jdate($datenotinstring);
8347 $timekey = $keyprefix.
'options_'.$key.$keysuffix;
8348 $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;
8351 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'price',
'double'))) {
8352 if (GETPOSTISSET($keyprefix.
'options_'.$key.$keysuffix) || $value) {
8354 } elseif (isset($this->array_options[
'options_'.$key])) {
8355 $value = $this->array_options[
'options_'.$key];
8360 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'html',
'text',
'varchar',
'select',
'radio',
'int',
'boolean'))) {
8361 if ($action ==
'create') {
8362 $value = (GETPOSTISSET($keyprefix.
'options_'.$key.$keysuffix) || $value) ? $value : $extrafields->attributes[$this->table_element][
'default'][$key];
8366 $labeltoshow = $langs->trans($label);
8367 $helptoshow = $langs->trans($extrafields->attributes[$this->table_element][
'help'][$key]);
8369 if ($display_type ==
'card') {
8370 $out .=
'<tr '.($html_id ?
'id="'.$html_id.
'" ' :
'').$csstyle.
' class="field_options_'.$key.
' '.$class.$this->element.
'_extras_'.$key.
' trextrafields_collapse'.$collapse_group.
'" '.$domData.
' >';
8371 if (!empty($conf->global->MAIN_VIEW_LINE_NUMBER) && ($action ==
'view' || $action ==
'valid' || $action ==
'editline' || $action ==
'confirm_valid' || $action ==
'confirm_cancel')) {
8372 $out .=
'<td></td>';
8374 $out .=
'<td class="'.(empty($params[
'tdclass']) ?
'titlefieldcreate' : $params[
'tdclass']).
' wordbreak';
8375 } elseif ($display_type ==
'line') {
8376 $out .=
'<div '.($html_id ?
'id="'.$html_id.
'" ' :
'').$csstyle.
' class="fieldline_options_'.$key.
' '.$class.$this->element.
'_extras_'.$key.
' trextrafields_collapse'.$collapse_group.
'" '.$domData.
' >';
8377 $out .=
'<div style="display: inline-block; padding-right:4px" class="wordbreak';
8382 $tpl_context = isset($params[
"tpl_context"]) ? $params[
"tpl_context"] :
"none";
8383 if ($tpl_context !=
"public") {
8384 if ($mode !=
'view' && !empty($extrafields->attributes[$this->table_element][
'required'][$key])) {
8385 $out .=
' fieldrequired';
8389 if ($tpl_context ==
"public") {
8390 if (!empty($extrafields->attributes[$this->table_element][
'help'][$key])) {
8391 $out .= $form->textwithpicto($labeltoshow, $helptoshow);
8393 $out .= $labeltoshow;
8395 if ($mode !=
'view' && !empty($extrafields->attributes[$this->table_element][
'required'][$key])) {
8396 $out .=
' <span style="color: red">*</span>';
8399 if (!empty($extrafields->attributes[$this->table_element][
'help'][$key])) {
8400 $out .= $form->textwithpicto($labeltoshow, $helptoshow);
8402 $out .= $labeltoshow;
8406 $out .= ($display_type ==
'card' ?
'</td>' :
'</div>');
8408 $html_id = !empty($this->
id) ? $this->element.
'_extras_'.$key.
'_'.$this->id :
'';
8409 if ($display_type ==
'card') {
8411 $out .=
'<td '.($html_id ?
'id="'.$html_id.
'" ' :
'').
' class="valuefieldcreate '.$this->element.
'_extras_'.$key.
'" '.($colspan ?
' colspan="'.$colspan.
'"' :
'').
'>';
8412 } elseif ($display_type ==
'line') {
8413 $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].
'">';
8418 $out .= $extrafields->showOutputField($key, $value,
'', $this->table_element);
8421 $out .= $extrafields->showInputField($key, $value,
'', $keysuffix,
'', 0, $this->
id, $this->table_element);
8424 $out .= $extrafields->showInputField($key, $value,
'', $keysuffix,
'', 0, $this->
id, $this->table_element);
8428 $out .= ($display_type==
'card' ?
'</td>' :
'</div>');
8430 if (!empty($conf->global->MAIN_EXTRAFIELDS_USE_TWO_COLUMS) && (($e % 2) == 1)) {
8431 $out .= ($display_type==
'card' ?
'</tr>' :
'</div>');
8433 $out .= ($display_type==
'card' ?
'</tr>' :
'</div>');
8441 if (!empty($conf->use_javascript_ajax)) {
8442 $out .= $this->getJSListDependancies();
8445 $out .=
'<!-- commonobject:showOptionals end --> '.
"\n";
8447 if (empty($nbofextrafieldsshown)) {
8453 $out .= $hookmanager->resPrint;
8465 <script nonce="'.getNonce().
'">
8466 jQuery(document).ready(function() {
8467 function showOptions'.$type.
'(child_list, parent_list, orig_select)
8469 var val = $("select[name=\""+parent_list+"\"]").val();
8470 var parentVal = parent_list + ":" + val;
8471 if(typeof val == "string"){
8473 var options = orig_select.find("option[parent=\""+parentVal+"\"]").clone();
8474 $("select[name=\""+child_list+"\"] option[parent]").remove();
8475 $("select[name=\""+child_list+"\"]").append(options);
8477 var options = orig_select.find("option[parent]").clone();
8478 $("select[name=\""+child_list+"\"] option[parent]").remove();
8479 $("select[name=\""+child_list+"\"]").append(options);
8481 } else if(val > 0) {
8482 var options = orig_select.find("option[parent=\""+parentVal+"\"]").clone();
8483 $("select[name=\""+child_list+"\"] option[parent]").remove();
8484 $("select[name=\""+child_list+"\"]").append(options);
8486 var options = orig_select.find("option[parent]").clone();
8487 $("select[name=\""+child_list+"\"] option[parent]").remove();
8488 $("select[name=\""+child_list+"\"]").append(options);
8491 function setListDependencies'.$type.
'() {
8492 jQuery("select option[parent]").parent().each(function() {
8493 var orig_select = {};
8494 var child_list = $(this).attr("name");
8495 orig_select[child_list] = $(this).clone();
8496 var parent = $(this).find("option[parent]:first").attr("parent");
8497 var infos = parent.split(":");
8498 var parent_list = infos[0];
8500 //Hide daughters lists
8501 if ($("#"+child_list).val() == 0 && $("#"+parent_list).val() == 0){
8502 $("#"+child_list).hide();
8504 } else if ($("#"+parent_list).val() != 0){
8505 $("#"+parent_list).show();
8507 //Show the child list if the parent list value is selected
8508 $("select[name=\""+parent_list+"\"]").click(function() {
8509 if ($(this).val() != 0){
8510 $("#"+child_list).show()
8514 //When we change parent list
8515 $("select[name=\""+parent_list+"\"]").change(function() {
8516 showOptions'.$type.
'(child_list, parent_list, orig_select[child_list]);
8517 //Select the value 0 on child list after a change on the parent list
8518 $("#"+child_list).val(0).trigger("change");
8519 //Hide child lists if the parent value is set to 0
8520 if ($(this).val() == 0){
8521 $("#"+child_list).hide();
8527 setListDependencies'.$type.
'();
8542 $module = empty($this->module) ?
'' : $this->module;
8543 $element = $this->element;
8545 if ($element ==
'facturerec') {
8546 $element =
'facture';
8547 } elseif ($element ==
'invoice_supplier_rec') {
8548 return empty($user->rights->fournisseur->facture) ? null : $user->rights->fournisseur->facture;
8549 } elseif ($module && !empty($user->rights->$module->$element)) {
8551 return $user->rights->$module->$element;
8554 return $user->rights->$element;
8571 foreach ($tables as $table) {
8572 $sql =
'UPDATE '.$dbs->prefix().$table.
' SET fk_soc = '.((int) $dest_id).
' WHERE fk_soc = '.((int) $origin_id);
8574 if (!$dbs->
query($sql)) {
8575 if ($ignoreerrors) {
8600 foreach ($tables as $table) {
8601 $sql =
'UPDATE '.MAIN_DB_PREFIX.$table.
' SET fk_product = '.((int) $dest_id).
' WHERE fk_product = '.((int) $origin_id);
8603 if (!$dbs->
query($sql)) {
8604 if ($ignoreerrors) {
8627 public function defineBuyPrice($unitPrice = 0.0, $discountPercent = 0.0, $fk_product = 0)
8633 if (($unitPrice > 0) && (isset($conf->global->ForceBuyingPriceIfNull) && $conf->global->ForceBuyingPriceIfNull > 0)) {
8635 $buyPrice = $unitPrice * (1 - $discountPercent / 100);
8638 if (!empty($fk_product) && $fk_product > 0) {
8639 if (isset($conf->global->MARGIN_TYPE) && $conf->global->MARGIN_TYPE ==
'costprice') {
8640 require_once DOL_DOCUMENT_ROOT.
'/product/class/product.class.php';
8641 $product =
new Product($this->db);
8642 $result = $product->fetch($fk_product);
8644 $this->errors[] =
'ErrorProductIdDoesNotExists';
8647 if ($product->cost_price > 0) {
8648 $buyPrice = $product->cost_price;
8649 } elseif ($product->pmp > 0) {
8650 $buyPrice = $product->pmp;
8652 } elseif (isset($conf->global->MARGIN_TYPE) && $conf->global->MARGIN_TYPE ==
'pmp') {
8653 require_once DOL_DOCUMENT_ROOT.
'/product/class/product.class.php';
8654 $product =
new Product($this->db);
8655 $result = $product->fetch($fk_product);
8657 $this->errors[] =
'ErrorProductIdDoesNotExists';
8660 if ($product->pmp > 0) {
8661 $buyPrice = $product->pmp;
8665 if (empty($buyPrice) && isset($conf->global->MARGIN_TYPE) && in_array($conf->global->MARGIN_TYPE, array(
'1',
'pmp',
'costprice'))) {
8666 require_once DOL_DOCUMENT_ROOT.
'/fourn/class/fournisseur.product.class.php';
8668 if (($result = $productFournisseur->find_min_price_product_fournisseur($fk_product)) > 0) {
8669 $buyPrice = $productFournisseur->fourn_unitprice;
8670 } elseif ($result < 0) {
8671 $this->errors[] = $productFournisseur->error;
8700 public function show_photos($modulepart, $sdir, $size = 0, $nbmax = 0, $nbbyrow = 5, $showfilename = 0, $showaction = 0, $maxHeight = 120, $maxWidth = 160, $nolink = 0, $overwritetitle = 0, $usesharelink = 0, $cache =
'', $addphotorefcss =
'photoref')
8703 global $conf, $user, $langs;
8705 include_once DOL_DOCUMENT_ROOT.
'/core/lib/files.lib.php';
8706 include_once DOL_DOCUMENT_ROOT.
'/core/lib/images.lib.php';
8708 $sortfield =
'position_name';
8714 $dir .=
get_exdir(0, 0, 0, 0, $this, $modulepart);
8715 $pdir .=
get_exdir(0, 0, 0, 0, $this, $modulepart);
8718 if ($modulepart ==
'product') {
8720 $dir = $sdir.
'/'.
get_exdir($this->
id, 2, 0, 0, $this, $modulepart).$this->id.
"/photos/";
8721 $pdir =
'/'.get_exdir($this->
id, 2, 0, 0, $this, $modulepart).$this->id.
"/photos/";
8728 $relativedir = preg_replace(
'/^'.preg_quote(DOL_DATA_ROOT,
'/').
'/',
'', $dir);
8729 $relativedir = preg_replace(
'/^[\\/]/',
'', $relativedir);
8730 $relativedir = preg_replace(
'/[\\/]$/',
'', $relativedir);
8733 $dirthumb = $dir.
'thumbs/';
8734 $pdirthumb = $pdir.
'thumbs/';
8736 $return =
'<!-- Photo -->'.
"\n";
8739 $filearray =
dol_dir_list($dir,
"files", 0,
'',
'(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) ==
'desc' ?SORT_DESC:SORT_ASC), 1);
8749 if (count($filearray)) {
8750 if ($sortfield && $sortorder) {
8754 foreach ($filearray as $key => $val) {
8756 $file = $val[
'name'];
8762 $viewfilename = $file;
8764 if ($size == 1 || $size ==
'small') {
8771 $photo_vignette = basename($file);
8778 if ($nbphoto == 1) {
8779 $return .=
'<table class="valigntop center centpercent" style="border: 0; padding: 2px; border-spacing: 2px; border-collapse: separate;">';
8782 if ($nbphoto % $nbbyrow == 1) {
8783 $return .=
'<tr class="center valignmiddle" style="border: 1px">';
8785 $return .=
'<td style="width: '.ceil(100 / $nbbyrow).
'%" class="photo">'.
"\n";
8786 } elseif ($nbbyrow < 0) {
8787 $return .=
'<div class="inline-block">'.
"\n";
8790 $relativefile = preg_replace(
'/^\//',
'', $pdir.$photo);
8791 if (empty($nolink)) {
8794 $return .=
'<a href="'.$urladvanced.
'">';
8796 $return .=
'<a href="'.DOL_URL_ROOT.
'/viewimage.php?modulepart='.$modulepart.
'&entity='.$this->entity.
'&file='.urlencode($pdir.$photo).
'" class="aphoto" target="_blank" rel="noopener noreferrer">';
8802 $alt = $langs->transnoentitiesnoconv(
'File').
': '.$relativefile;
8803 $alt .=
' - '.$langs->transnoentitiesnoconv(
'Size').
': '.$imgarray[
'width'].
'x'.$imgarray[
'height'];
8804 if ($overwritetitle) {
8805 if (is_numeric($overwritetitle)) {
8808 $alt = $overwritetitle;
8812 if ($usesharelink) {
8813 if ($val[
'share']) {
8814 if (empty($maxHeight) || ($photo_vignette && $imgarray[
'height'] > $maxHeight)) {
8815 $return .=
'<!-- Show original file (thumb not yet available with shared links) -->';
8816 $return .=
'<img class="photo photowithmargin'.($addphotorefcss ?
' '.$addphotorefcss :
'').
'"'.($maxHeight ?
' height="'.$maxHeight.
'"':
'').
' src="'.DOL_URL_ROOT.
'/viewimage.php?hashp='.urlencode($val[
'share']).($cache ?
'&cache='.urlencode($cache) :
'').
'" title="'.
dol_escape_htmltag($alt).
'">';
8818 $return .=
'<!-- Show original file -->';
8819 $return .=
'<img class="photo photowithmargin'.($addphotorefcss ?
' '.$addphotorefcss :
'').
'" height="'.$maxHeight.
'" src="'.DOL_URL_ROOT.
'/viewimage.php?hashp='.urlencode($val[
'share']).($cache ?
'&cache='.urlencode($cache) :
'').
'" title="'.
dol_escape_htmltag($alt).
'">';
8822 $return .=
'<!-- Show nophoto file (because file is not shared) -->';
8823 $return .=
'<img class="photo photowithmargin'.($addphotorefcss ?
' '.$addphotorefcss :
'').
'" height="'.$maxHeight.
'" src="'.DOL_URL_ROOT.
'/public/theme/common/nophoto.png" title="'.
dol_escape_htmltag($alt).
'">';
8826 if (empty($maxHeight) || ($photo_vignette && $imgarray[
'height'] > $maxHeight)) {
8827 $return .=
'<!-- Show thumb -->';
8828 $return .=
'<img class="photo photowithmargin'.($addphotorefcss ?
' '.$addphotorefcss :
'').
' maxwidth150onsmartphone maxwidth200"'.($maxHeight ?
' height="'.$maxHeight.
'"':
'').
' src="'.DOL_URL_ROOT.
'/viewimage.php?modulepart='.$modulepart.
'&entity='.$this->entity.($cache ?
'&cache='.urlencode($cache) :
'').
'&file='.urlencode($pdirthumb.$photo_vignette).
'" title="'.
dol_escape_htmltag($alt).
'">';
8830 $return .=
'<!-- Show original file -->';
8831 $return .=
'<img class="photo photowithmargin'.($addphotorefcss ?
' '.$addphotorefcss :
'').
'" height="'.$maxHeight.
'" src="'.DOL_URL_ROOT.
'/viewimage.php?modulepart='.$modulepart.
'&entity='.$this->entity.($cache ?
'&cache='.urlencode($cache) :
'').
'&file='.urlencode($pdir.$photo).
'" title="'.
dol_escape_htmltag($alt).
'">';
8835 if (empty($nolink)) {
8839 if ($showfilename) {
8840 $return .=
'<br>'.$viewfilename;
8845 if ($photo_vignette && (
image_format_supported($photo) > 0) && ($this->imgWidth > $maxWidth || $this->imgHeight > $maxHeight)) {
8846 $return .=
'<a href="'.$_SERVER[
"PHP_SELF"].
'?id='.$this->
id.
'&action=addthumb&token='.newToken().
'&file='.urlencode($pdir.$viewfilename).
'">'.
img_picto($langs->trans(
'GenerateThumb'),
'refresh').
' </a>';
8849 if ($modulepart ==
'product' && ($user->hasRight(
'produit',
'creer') || $user->hasRight(
'service',
'creer'))) {
8851 $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> ';
8854 $return .=
'<a href="'.$_SERVER[
"PHP_SELF"].
'?id='.$this->
id.
'&action=delete&token='.newToken().
'&file='.urlencode($pdir.$viewfilename).
'">';
8862 if (($nbphoto % $nbbyrow) == 0) {
8865 } elseif ($nbbyrow < 0) {
8866 $return .=
'</div>'.
"\n";
8871 $return .=
'<img class="photo photowithmargin" src="'.DOL_URL_ROOT.
'/viewimage.php?modulepart='.$modulepart.
'&entity='.$this->entity.
'&file='.urlencode($pdir.$photo).
'">';
8873 if ($showfilename) {
8874 $return .=
'<br>'.$viewfilename;
8878 if ($modulepart ==
'product' && ($user->hasRight(
'produit',
'creer') || $user->hasRight(
'service',
'creer'))) {
8880 $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> ';
8883 $return .=
'<a href="'.$_SERVER[
"PHP_SELF"].
'?id='.$this->
id.
'&action=delete&token='.newToken().
'&file='.urlencode($pdir.$viewfilename).
'">';
8890 if ($nbmax && $nbphoto >= $nbmax) {
8896 if ($size == 1 || $size ==
'small') {
8899 while ($nbphoto % $nbbyrow) {
8900 $return .=
'<td style="width: '.ceil(100 / $nbbyrow).
'%"> </td>';
8905 $return .=
'</table>';
8911 $this->nbphoto = $nbphoto;
8925 if (is_array($info)) {
8926 if (isset($info[
'type']) && $info[
'type'] ==
'array') {
8943 if (isset($info[
'type']) && ($info[
'type'] ==
'date' || $info[
'type'] ==
'datetime' || $info[
'type'] ==
'timestamp')) {
8957 if (is_array($info)) {
8958 if (isset($info[
'type']) && ($info[
'type'] ==
'duration')) {
8976 if (is_array($info)) {
8977 if (isset($info[
'type']) && (preg_match(
'/(^int|int$)/i', $info[
'type']))) {
8995 if (is_array($info)) {
8996 if (isset($info[
'type']) && (preg_match(
'/^(double|real|price)/i', $info[
'type']))) {
9013 if (is_array($info)) {
9014 if (isset($info[
'type']) && $info[
'type'] ==
'text') {
9031 if (is_array($info)) {
9032 if (isset($info[
'notnull']) && $info[
'notnull'] !=
'1') {
9049 if (is_array($info)) {
9050 if (isset($info[
'notnull']) && $info[
'notnull'] ==
'-1') {
9067 if (is_array($info)) {
9068 if (isset($info[
'index']) && $info[
'index'] ==
true) {
9090 $queryarray = array();
9091 foreach ($this->fields as $field => $info) {
9093 if ($this->isDate($info)) {
9094 if (empty($this->{$field})) {
9095 $queryarray[$field] =
null;
9097 $queryarray[$field] = $this->db->idate($this->{$field});
9099 } elseif ($this->isDuration($info)) {
9101 if ((isset($this->{$field}) && $this->{$field} !=
'') || !empty($info[
'notnull'])) {
9102 if (!isset($this->{$field})) {
9103 if (!empty($info[
'default'])) {
9104 $queryarray[$field] = $info[
'default'];
9106 $queryarray[$field] = 0;
9109 $queryarray[$field] = (int) $this->{$field};
9112 $queryarray[$field] =
null;
9114 } elseif ($this->isInt($info) || $this->isFloat($info)) {
9115 if ($field ==
'entity' && is_null($this->{$field})) {
9116 $queryarray[$field] = ((int) $conf->entity);
9119 if ((isset($this->{$field}) && $this->{$field} !=
'') || !empty($info[
'notnull'])) {
9120 if (!isset($this->{$field})) {
9121 $queryarray[$field] = 0;
9122 } elseif ($this->isInt($info)) {
9123 $queryarray[$field] = (int) $this->{$field};
9124 } elseif ($this->isFloat($info)) {
9125 $queryarray[$field] = (double) $this->{$field};
9128 $queryarray[$field] =
null;
9134 $queryarray[$field] = $this->{$field};
9137 if ($info[
'type'] ==
'timestamp' && empty($queryarray[$field])) {
9138 unset($queryarray[$field]);
9140 if (!empty($info[
'notnull']) && $info[
'notnull'] == -1 && empty($queryarray[$field])) {
9141 $queryarray[$field] =
null;
9158 foreach ($this->fields as $field => $info) {
9159 if ($this->isDate($info)) {
9160 if (!isset($obj->$field) || is_null($obj->$field) || $obj->$field ===
'' || $obj->$field ===
'0000-00-00 00:00:00' || $obj->$field ===
'1000-01-01 00:00:00') {
9163 $this->$field = $db->jdate($obj->$field);
9165 } elseif ($this->isInt($info)) {
9166 if ($field ==
'rowid') {
9167 $this->
id = (int) $obj->$field;
9169 if ($this->isForcedToNullIfZero($info)) {
9170 if (empty($obj->$field)) {
9171 $this->$field =
null;
9173 $this->$field = (double) $obj->$field;
9176 if (isset($obj->$field) && (!is_null($obj->$field) || (isset($info[
'notnull']) && $info[
'notnull'] == 1))) {
9177 $this->$field = (int) $obj->$field;
9179 $this->$field =
null;
9183 } elseif ($this->isFloat($info)) {
9184 if ($this->isForcedToNullIfZero($info)) {
9185 if (empty($obj->$field)) {
9186 $this->$field =
null;
9188 $this->$field = (double) $obj->$field;
9191 if (isset($obj->$field) && (!is_null($obj->$field) || (isset($info[
'notnull']) && $info[
'notnull'] == 1))) {
9192 $this->$field = (double) $obj->$field;
9194 $this->$field =
null;
9198 $this->$field = isset($obj->$field) ? $obj->$field :
null;
9203 if (!isset($this->fields[
'ref']) && isset($this->
id)) {
9204 $this->
ref = $this->id;
9217 $keys = array_keys($this->fields);
9218 if (!empty($alias)) {
9219 $keys_with_alias = array();
9220 foreach ($keys as $fieldname) {
9221 if (!empty($excludefields)) {
9222 if (in_array($fieldname, $excludefields)) {
9226 $keys_with_alias[] = $alias .
'.' . $fieldname;
9228 return implode(
',', $keys_with_alias);
9230 return implode(
',', $keys);
9241 protected function quote($value, $fieldsentry)
9243 if (is_null($value)) {
9245 } elseif (preg_match(
'/^(int|double|real|price)/i', $fieldsentry[
'type'])) {
9247 } elseif (preg_match(
'/int$/i', $fieldsentry[
'type'])) {
9248 return (
int) $value;
9249 } elseif ($fieldsentry[
'type'] ==
'boolean') {
9256 return "'".$this->db->escape($value).
"'";
9271 dol_syslog(get_class($this).
"::createCommon create", LOG_DEBUG);
9277 $fieldvalues = $this->setSaveQuery();
9279 if (array_key_exists(
'date_creation', $fieldvalues) && empty($fieldvalues[
'date_creation'])) {
9280 $fieldvalues[
'date_creation'] = $this->db->idate($now);
9282 if (array_key_exists(
'fk_user_creat', $fieldvalues) && !($fieldvalues[
'fk_user_creat'] > 0)) {
9283 $fieldvalues[
'fk_user_creat'] = $user->id;
9284 $this->fk_user_creat = $user->id;
9286 if (array_key_exists(
'user_modification_id', $fieldvalues) && !($fieldvalues[
'user_modification_id'] > 0)) {
9287 $fieldvalues[
'user_modification_id'] = $user->id;
9288 $this->user_modification_id = $user->id;
9290 unset($fieldvalues[
'rowid']);
9291 if (array_key_exists(
'ref', $fieldvalues)) {
9297 foreach ($fieldvalues as $k => $v) {
9299 $value = $this->fields[$k];
9300 $values[$k] = $this->quote($v, $value);
9304 foreach ($keys as $key) {
9306 if (preg_match(
'/^integer:/i', $this->fields[$key][
'type']) && $values[$key] ==
'-1') {
9309 if (!empty($this->fields[$key][
'foreignkey']) && $values[$key] ==
'-1') {
9313 if (isset($this->fields[$key][
'notnull']) && $this->fields[$key][
'notnull'] == 1 && (!isset($values[$key]) || $values[$key] ===
'NULL') && is_null($this->fields[$key][
'default'])) {
9315 $langs->load(
"errors");
9316 dol_syslog(
"Mandatory field '".$key.
"' is empty and required into ->fields definition of class");
9317 $this->errors[] = $langs->trans(
"ErrorFieldRequired", $this->fields[$key][
'label']);
9321 if (isset($this->fields[$key][
'notnull']) && $this->fields[$key][
'notnull'] == 1 && (!isset($values[$key]) || $values[$key] ===
'NULL') && !is_null($this->fields[$key][
'default'])) {
9322 $values[$key] = $this->quote($this->fields[$key][
'default'], $this->fields[$key]);
9326 if (preg_match(
'/^integer:/i', $this->fields[$key][
'type']) && empty($values[$key])) {
9327 if (isset($this->fields[$key][
'default'])) {
9328 $values[$key] = ((int) $this->fields[$key][
'default']);
9330 $values[$key] =
'null';
9333 if (!empty($this->fields[$key][
'foreignkey']) && empty($values[$key])) {
9334 $values[$key] =
'null';
9345 $sql =
"INSERT INTO ".$this->db->prefix().$this->table_element;
9346 $sql .=
" (".implode(
", ", $keys).
')';
9347 $sql .=
" VALUES (".implode(
", ", $values).
")";
9349 $res = $this->db->query($sql);
9352 if ($this->db->lasterrno() ==
'DB_ERROR_RECORD_ALREADY_EXISTS') {
9353 $this->errors[] =
"ErrorRefAlreadyExists";
9355 $this->errors[] = $this->db->lasterror();
9361 $this->
id = $this->db->last_insert_id($this->db->prefix().$this->table_element);
9366 if (key_exists(
'ref', $this->fields) && $this->fields[
'ref'][
'notnull'] > 0 && key_exists(
'default', $this->fields[
'ref']) && $this->fields[
'ref'][
'default'] ==
'(PROV)') {
9367 $sql =
"UPDATE ".$this->db->prefix().$this->table_element.
" SET ref = '(PROV".((int) $this->
id).
")' WHERE (ref = '(PROV)' OR ref = '') AND rowid = ".((int) $this->
id);
9368 $resqlupdate = $this->db->query($sql);
9370 if ($resqlupdate ===
false) {
9372 $this->errors[] = $this->db->lasterror();
9374 $this->
ref =
'(PROV'.$this->id.
')';
9381 $result = $this->insertExtraFields();
9388 if (!empty($this->table_element_line) && !empty($this->fk_element)) {
9389 $num = (is_array($this->lines) ? count($this->lines) : 0);
9390 for ($i = 0; $i < $num; $i++) {
9391 $line = $this->lines[$i];
9393 $keyforparent = $this->fk_element;
9394 $line->$keyforparent = $this->id;
9398 if (!is_object($line)) {
9399 $line = (object) $line;
9403 if (method_exists($line,
'insert')) {
9404 $result = $line->insert($user, 1);
9405 } elseif (method_exists($line,
'create')) {
9406 $result = $line->create($user, 1);
9409 $this->error = $line->error;
9410 $this->db->rollback();
9417 if (!$error && !$notrigger) {
9419 $result = $this->call_trigger(strtoupper(get_class($this)).
'_CREATE', $user);
9428 $this->db->rollback();
9431 $this->db->commit();
9447 if (empty($id) && empty($ref) && empty($morewhere)) {
9451 $fieldlist = $this->getFieldList(
't');
9452 if (empty($fieldlist)) {
9456 $sql =
"SELECT ".$fieldlist;
9457 $sql .=
" FROM ".$this->db->prefix().$this->table_element.
' as t';
9460 $sql .=
' WHERE t.rowid = '.((int) $id);
9461 } elseif (!empty($ref)) {
9462 $sql .=
" WHERE t.ref = '".$this->db->escape($ref).
"'";
9464 $sql .=
' WHERE 1 = 1';
9466 if (empty($id) && isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
9467 $sql .=
' AND t.entity IN ('.getEntity($this->element).
')';
9474 $res = $this->db->query($sql);
9476 $obj = $this->db->fetch_object($res);
9478 $this->setVarsFromFetchObj($obj);
9482 $this->fetch_optionals();
9489 $this->error = $this->db->lasterror();
9490 $this->errors[] = $this->error;
9503 $objectlineclassname = get_class($this).
'Line';
9504 if (!class_exists($objectlineclassname)) {
9505 $this->error =
'Error, class '.$objectlineclassname.
' not found during call of fetchLinesCommon';
9509 $objectline =
new $objectlineclassname($this->db);
9511 $sql =
"SELECT ".$objectline->getFieldList(
'l');
9512 $sql .=
" FROM ".$this->db->prefix().$objectline->table_element.
" as l";
9513 $sql .=
" WHERE l.fk_".$this->db->escape($this->element).
" = ".((int) $this->
id);
9517 if (isset($objectline->fields[
'position'])) {
9518 $sql .= $this->db->order(
'position',
'ASC');
9521 $resql = $this->db->query($sql);
9523 $num_rows = $this->db->num_rows($resql);
9525 $this->lines = array();
9526 while ($i < $num_rows) {
9527 $obj = $this->db->fetch_object($resql);
9529 $newline =
new $objectlineclassname($this->db);
9530 $newline->setVarsFromFetchObj($obj);
9532 $this->lines[] = $newline;
9539 $this->error = $this->db->lasterror();
9540 $this->errors[] = $this->error;
9554 global $conf, $langs;
9555 dol_syslog(get_class($this).
"::updateCommon update", LOG_DEBUG);
9566 $fieldvalues = $this->setSaveQuery();
9568 if (array_key_exists(
'date_modification', $fieldvalues) && empty($fieldvalues[
'date_modification'])) {
9569 $fieldvalues[
'date_modification'] = $this->db->idate($now);
9571 if (array_key_exists(
'fk_user_modif', $fieldvalues) && !($fieldvalues[
'fk_user_modif'] > 0)) {
9572 $fieldvalues[
'fk_user_modif'] = $user->id;
9574 unset($fieldvalues[
'rowid']);
9575 if (array_key_exists(
'ref', $fieldvalues)) {
9583 foreach ($fieldvalues as $k => $v) {
9585 $value = $this->fields[$k];
9586 $values[$k] = $this->quote($v, $value);
9587 $tmp[] = $k.
'='.$this->quote($v, $this->fields[$k]);
9591 foreach ($keys as $key) {
9592 if (preg_match(
'/^integer:/i', $this->fields[$key][
'type']) && $values[$key] ==
'-1') {
9595 if (!empty($this->fields[$key][
'foreignkey']) && $values[$key] ==
'-1') {
9608 $sql =
'UPDATE '.$this->db->prefix().$this->table_element.
' SET '.implode(
', ', $tmp).
' WHERE rowid='.((int) $this->
id);
9613 $res = $this->db->query($sql);
9616 $this->errors[] = $this->db->lasterror();
9622 $result = $this->insertExtraFields();
9629 if (!$error && !$notrigger) {
9631 $result = $this->call_trigger(strtoupper(get_class($this)).
'_MODIFY', $user);
9640 $this->db->rollback();
9643 $this->db->commit();
9658 dol_syslog(get_class($this).
"::deleteCommon delete", LOG_DEBUG);
9664 if ($forcechilddeletion) {
9665 foreach ($this->childtables as $table) {
9666 $sql =
"DELETE FROM ".$this->db->prefix().$table.
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
9667 $resql = $this->db->query($sql);
9669 $this->error = $this->db->lasterror();
9670 $this->errors[] = $this->error;
9671 $this->db->rollback();
9675 } elseif (!empty($this->childtables)) {
9676 $objectisused = $this->isObjectUsed($this->
id);
9677 if (!empty($objectisused)) {
9678 dol_syslog(get_class($this).
"::deleteCommon Can't delete record as it has some child", LOG_WARNING);
9679 $this->error =
'ErrorRecordHasChildren';
9680 $this->errors[] = $this->error;
9681 $this->db->rollback();
9687 if (is_array($this->childtablesoncascade) && !empty($this->childtablesoncascade)) {
9688 foreach ($this->childtablesoncascade as $table) {
9689 $deleteFromObject = explode(
':', $table);
9690 if (count($deleteFromObject) >= 2) {
9691 $className = str_replace(
'@',
'', $deleteFromObject[0]);
9692 $filePath = $deleteFromObject[1];
9693 $columnName = $deleteFromObject[2];
9694 $TMoreSQL = array();
9695 $more_sql = $deleteFromObject[3];
9696 if (!empty($more_sql)) {
9697 $TMoreSQL[
'customsql'] = $more_sql;
9700 $childObject =
new $className($this->db);
9701 if (method_exists($childObject,
'deleteByParentField')) {
9702 $result = $childObject->deleteByParentField($this->
id, $columnName, $TMoreSQL);
9705 $this->errors[] = $childObject->error;
9710 $this->errors[] =
"You defined a cascade delete on an object $childObject but there is no method deleteByParentField for it";
9715 $this->errors[] =
'Cannot include child class file '.$filePath;
9720 $sql =
"DELETE FROM ".$this->db->prefix().$table.
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
9722 $resql = $this->db->query($sql);
9725 $this->error = $this->db->lasterror();
9726 $this->errors[] = $this->error;
9736 $result = $this->call_trigger(strtoupper(get_class($this)).
'_DELETE', $user);
9746 $res = $this->deleteEcmFiles(1);
9753 $res = $this->deleteObjectLinked();
9758 if (!$error && !empty($this->isextrafieldmanaged)) {
9759 $result = $this->deleteExtraFields();
9766 $sql =
'DELETE FROM '.$this->db->prefix().$this->table_element.
' WHERE rowid='.((int) $this->
id);
9768 $resql = $this->db->query($sql);
9771 $this->errors[] = $this->db->lasterror();
9777 $this->db->rollback();
9780 $this->db->commit();
9802 if (!empty($parentId) && !empty($parentField)) {
9805 $sql =
"SELECT rowid FROM ".$this->db->prefix().$this->table_element;
9806 $sql .=
" WHERE ".$parentField.
" = ".(int) $parentId;
9809 $sqlwhere = array();
9810 if (count($filter) > 0) {
9811 foreach ($filter as $key => $value) {
9812 if ($key ==
'customsql') {
9813 $sqlwhere[] = $value;
9814 } elseif (strpos($value,
'%') ===
false) {
9815 $sqlwhere[] = $key.
" IN (".$this->db->sanitize($this->db->escape($value)).
")";
9817 $sqlwhere[] = $key.
" LIKE '%".$this->db->escape($value).
"%'";
9821 if (count($sqlwhere) > 0) {
9822 $sql .=
" AND (".implode(
" ".$filtermode.
" ", $sqlwhere).
")";
9825 $resql = $this->db->query($sql);
9827 $this->errors[] = $this->db->lasterror();
9830 while ($obj = $this->db->fetch_object($resql)) {
9831 $result = $this->fetch($obj->rowid);
9834 $this->errors[] = $this->error;
9836 if (get_class($this) ==
'Contact') {
9837 $result = $this->
delete();
9839 $result = $this->
delete($user);
9843 $this->errors[] = $this->error;
9851 if (empty($error)) {
9852 $this->db->commit();
9855 $this->error = implode(
', ', $this->errors);
9856 $this->db->rollback();
9878 $tmpforobjectclass = get_class($this);
9879 $tmpforobjectlineclass = ucfirst($tmpforobjectclass).
'Line';
9884 $result = $this->call_trigger(
'LINE'.strtoupper($tmpforobjectclass).
'_DELETE', $user);
9890 if (empty($error)) {
9891 $sql =
"DELETE FROM ".$this->db->prefix().$this->table_element_line;
9892 $sql .=
" WHERE rowid = ".((int) $idline);
9894 $resql = $this->db->query($sql);
9896 $this->error =
"Error ".$this->db->lasterror();
9901 if (empty($error)) {
9903 $tmpobjectline =
new $tmpforobjectlineclass($this->db);
9904 if (!isset($tmpobjectline->isextrafieldmanaged) || !empty($tmpobjectline->isextrafieldmanaged)) {
9905 $tmpobjectline->id = $idline;
9906 $result = $tmpobjectline->deleteExtraFields();
9909 $this->error =
"Error ".get_class($this).
"::deleteLineCommon deleteExtraFields error -4 ".$tmpobjectline->error;
9914 if (empty($error)) {
9915 $this->db->commit();
9918 dol_syslog(get_class($this).
"::deleteLineCommon ERROR:".$this->error, LOG_ERR);
9919 $this->db->rollback();
9940 $statusfield =
'status';
9941 if (in_array($this->element, array(
'don',
'donation',
'shipping'))) {
9942 $statusfield =
'fk_statut';
9945 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
9946 $sql .=
" SET ".$statusfield.
" = ".((int) $status);
9947 $sql .=
" WHERE rowid = ".((int) $this->
id);
9949 if ($this->db->query($sql)) {
9951 $this->oldcopy = clone $this;
9954 if (!$error && !$notrigger) {
9956 $result = $this->call_trigger($triggercode, $user);
9963 $this->status = $status;
9964 $this->db->commit();
9967 $this->db->rollback();
9971 $this->error = $this->db->error();
9972 $this->db->rollback();
9989 $this->specimen = 1;
9991 'label' =>
'This is label',
9992 'ref' =>
'ABCD1234',
9993 'description' =>
'This is a description',
9995 'note_public' =>
'Public note',
9996 'note_private' =>
'Private note',
9997 'date_creation' => (
dol_now() - 3600 * 48),
9998 'date_modification' => (
dol_now() - 3600 * 24),
9999 'fk_user_creat' => $user->id,
10000 'fk_user_modif' => $user->id,
10003 foreach ($fields as $key => $value) {
10004 if (array_key_exists($key, $this->fields)) {
10005 $this->{$key} = $value;
10010 if (property_exists($this,
'fields')) {
10011 foreach ($this->fields as $key => $value) {
10013 if (array_key_exists($key, $fields)) {
10017 if (!empty($value[
'default'])) {
10018 $this->$key = $value[
'default'];
10035 require_once DOL_DOCUMENT_ROOT.
'/core/class/comment.class.php';
10037 $comment =
new Comment($this->db);
10038 $result = $comment->fetchAllFor($this->element, $this->
id);
10040 $this->errors = array_merge($this->errors, $comment->errors);
10043 $this->comments = $comment->comments;
10045 return count($this->comments);
10055 return count($this->comments);
10066 if (!is_array($parameters)) {
10069 foreach ($parameters as $parameter) {
10070 if (isset($this->$parameter)) {
10071 $this->$parameter = trim($this->$parameter);
10090 require_once DOL_DOCUMENT_ROOT.
'/categories/class/categorie.class.php';
10094 $existing = $c->containing($this->
id, $type_categ,
'id');
10114 if (!is_array($categories)) {
10115 $categories = array($categories);
10118 dol_syslog(get_class($this).
"::setCategoriesCommon Oject Id:".$this->
id.
' type_categ:'.$type_categ.
' nb tag add:'.count($categories), LOG_DEBUG);
10120 require_once DOL_DOCUMENT_ROOT.
'/categories/class/categorie.class.php';
10122 if (empty($type_categ)) {
10123 dol_syslog(__METHOD__.
': Type '.$type_categ.
'is an unknown category type. Done nothing.', LOG_ERR);
10129 $existing = $c->containing($this->
id, $type_categ,
'id');
10130 if ($remove_existing) {
10132 if (is_array($existing)) {
10133 $to_del = array_diff($existing, $categories);
10134 $to_add = array_diff($categories, $existing);
10137 $to_add = $categories;
10141 $to_add = array_diff($categories, $existing);
10148 foreach ($to_del as $del) {
10149 if ($c->fetch($del) > 0) {
10150 $result=$c->del_type($this, $type_categ);
10153 $this->error = $c->error;
10154 $this->errors = $c->errors;
10161 foreach ($to_add as $add) {
10162 if ($c->fetch($add) > 0) {
10163 $result = $c->add_type($this, $type_categ);
10166 $this->error = $c->error;
10167 $this->errors = $c->errors;
10175 return $error ? (-1 * $error) : $ok;
10188 $this->db->begin();
10190 if (empty($type)) {
10191 $type = $this->table_element;
10194 require_once DOL_DOCUMENT_ROOT.
'/categories/class/categorie.class.php';
10195 $categorystatic =
new Categorie($this->db);
10197 $sql =
"INSERT INTO ".$this->db->prefix().
"categorie_".(empty($categorystatic->MAP_CAT_TABLE[$type]) ? $type : $categorystatic->MAP_CAT_TABLE[$type]).
" (fk_categorie, fk_product)";
10198 $sql .=
" SELECT fk_categorie, $toId FROM ".$this->db->prefix().
"categorie_".(empty($categorystatic->MAP_CAT_TABLE[$type]) ? $type : $categorystatic->MAP_CAT_TABLE[$type]);
10199 $sql .=
" WHERE fk_product = ".((int) $fromId);
10201 if (!$this->db->query($sql)) {
10202 $this->error = $this->db->lasterror();
10203 $this->db->rollback();
10207 $this->db->commit();
10221 $this->db->begin();
10225 switch ($this->element) {
10227 $element =
'propale';
10230 $element =
'produit';
10232 case 'order_supplier':
10233 $element =
'fournisseur/commande';
10235 case 'invoice_supplier':
10236 $element =
'fournisseur/facture/'.get_exdir($this->
id, 2, 0, 1, $this,
'invoice_supplier');
10239 $element =
'expedition/sending';
10242 $element = $this->element;
10246 $sql =
"DELETE FROM ".$this->db->prefix().
"ecm_files_extrafields WHERE fk_object IN (";
10247 $sql .=
" SELECT rowid FROM ".$this->db->prefix().
"ecm_files WHERE filename LIKE '".$this->db->escape($this->
ref).
"%'";
10248 $sql .=
" AND filepath = '".$this->db->escape($element).
"/".$this->db->escape($this->
ref).
"' AND entity = ".((int) $conf->entity);
10251 if (!$this->db->query($sql)) {
10252 $this->error = $this->db->lasterror();
10253 $this->db->rollback();
10258 $sql =
"DELETE FROM ".$this->db->prefix().
"ecm_files";
10259 $sql .=
" WHERE filename LIKE '".$this->db->escape($this->
ref).
"%'";
10260 $sql .=
" AND filepath = '".$this->db->escape($element).
"/".$this->db->escape($this->
ref).
"' AND entity = ".((int) $conf->entity);
10262 if (!$this->db->query($sql)) {
10263 $this->error = $this->db->lasterror();
10264 $this->db->rollback();
10271 $sql =
'DELETE FROM '.$this->db->prefix().
"ecm_files_extrafields";
10272 $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).
")";
10273 $resql = $this->db->query($sql);
10275 $this->error = $this->db->lasterror();
10276 $this->db->rollback();
10280 $sql =
'DELETE FROM '.$this->db->prefix().
"ecm_files";
10281 $sql .=
" WHERE src_object_type = '".$this->db->escape($this->table_element.(empty($this->module) ?
"" :
"@".$this->module)).
"' AND src_object_id = ".((int) $this->
id);
10282 $resql = $this->db->query($sql);
10284 $this->error = $this->db->lasterror();
10285 $this->db->rollback();
10290 $this->db->commit();
ajax_combobox($htmlname, $events=array(), $minLengthToAutocomplete=0, $forcefocus=0, $widthTypeOfAutocomplete='resolve', $idforemptyvalue='-1', $morecss='')
Convert a html select field into an ajax combobox.
Class to manage categories.
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.
indexFile($destfull, $update_main_doc_field)
Index a file into the ECM database.
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.
clearFieldError($fieldKey)
clear validation message result for a field
deleteEcmFiles($mode=0)
Delete related files of object in database.
getLastMainDocLink($modulepart, $initsharekey=0, $relativelink=0)
Return the link of last main doc file for direct public download.
liste_type_contact($source='internal', $order='position', $option=0, $activeonly=0, $code='')
Return array with list of possible values for type of contacts.
getTooltipContent($params)
getTooltipContent
swapContactStatus($rowid)
Update status of a contact linked to object.
getFieldError($fieldKey)
get field error message
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.
defineBuyPrice($unitPrice=0.0, $discountPercent=0.0, $fk_product=0)
Get buy price to use for margin calculation.
commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams=null)
Common function for all objects extending CommonObject for generating documents.
liste_contact($statusoflink=-1, $source='external', $list=0, $code='', $status=-1, $arrayoftcids=array())
Get array of all contacts for an object.
fetchObjectFrom($table, $field, $key, $element=null)
Load object from specific field.
fetch_thirdparty($force_thirdparty_id=0)
Load the third party of object, from id $this->socid or $this->fk_soc, into this->thirdparty.
deleteLineCommon(User $user, $idline, $notrigger=false)
Delete a line of object in database.
static deleteAllItemsLinkedByObjectID($fk_object_where, $field_where, $table_element)
Function used to remove all items linked to an object id in association table.
deleteByParentField($parentId=0, $parentField='', $filter=array(), $filtermode="AND")
Delete all child object from a parent ID.
setFieldError($fieldKey, $msg='')
set validation error message a field
validateField($fields, $fieldKey, $fieldValue)
Return validation test result for a field.
setMulticurrencyCode($code)
Change the multicurrency code.
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...
fetch_projet()
Load the project with id $this->fk_project into this->project.
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.
updateExtraField($key, $trigger=null, $userused=null)
Update 1 extra field value for the current object.
setPaymentTerms($id, $deposit_percent=null)
Change the payments terms.
isFloat($info)
Function test if type is float.
setExtraParameters()
Set extra parameters.
setErrorsFromObject($object)
setErrorsFromObject
update_note_public($note)
Update public note (kept for backward compatibility)
getSpecialCode($lineid)
Get special code of a line.
fetchCommon($id, $ref=null, $morewhere='')
Load object in memory from the database.
clearObjectLinkedCache()
Clear the cache saying that all linked object were already loaded.
update_ref_ext($ref_ext)
Update external ref of element.
fetchOneLike($ref)
Looks for an object with ref matching the wildcard provided It does only work when $this->table_ref_f...
showOptionals($extrafields, $mode='view', $params=null, $keysuffix='', $keyprefix='', $onetrtd=0, $display_type='card')
Function to show lines of extrafields with output datas.
hasProductsOrServices($predefined=-1)
Function to say how many lines object contains.
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...
isObjectUsed($id=0, $entity=0)
Function to check if an object is used by others (by children).
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.
getDefaultCreateValueFor($fieldname, $alternatevalue=null, $type='alphanohtml')
Return the default value to use for a field when showing the create form of object.
getTotalWeightVolume()
Return into unit=0, the calculated total of weight and volume of all lines * qty Calculate by adding ...
deleteCommon(User $user, $notrigger=false, $forcechilddeletion=0)
Delete object in database.
update_note($note, $suffix='', $notrigger=0)
Update note of element.
getFullAddress($withcountry=0, $sep="\n", $withregion=0, $extralangcode='')
Return full address of contact.
fetch_project()
Load the project with id $this->fk_project into this->project.
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).
getFieldList($alias='', $excludefields=array())
Function to concat keys of fields.
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.
updateExtraLanguages($key, $trigger=null, $userused=null)
Update an extra language value for the current object.
deleteExtraFields()
Delete all extra fields values for the current object.
setStatusCommon($user, $status, $notrigger=0, $triggercode='')
Set to a status.
addThumbs($file)
Build thumb.
setSaveQuery()
Function to return the array of data key-value from the ->fields and all the ->properties of an objec...
setValuesForExtraLanguages($onlykey='')
Fill array_options property of object by extrafields value (using for data sent by forms)
insertExtraLanguages($trigger='', $userused=null)
Add/Update all extra fields values for the current object.
setTransportMode($id)
Change the transport mode methods.
isArray($info)
Function test if type is array.
isInt($info)
Function test if type is integer.
fetchObjectLinked($sourceid=null, $sourcetype='', $targetid=null, $targettype='', $clause='OR', $alsosametype=1, $orderby='sourcetype', $loadalsoobjects=1)
Fetch array of objects linked to current object (object of enabled modules only).
delete_contact($rowid, $notrigger=0)
Delete a link to contact line.
updateLineUp($rowid, $rang)
Update position of line up (rang)
fetch_user($userid)
Load the user with id $userid into this->user.
errorsToString()
Method to output saved errors.
setBankAccount($fk_account, $notrigger=false, $userused=null)
Change the bank account.
getListContactId($source='external')
Return list of id of contacts of object.
setWarehouse($warehouse_id)
Change the warehouse.
setDeliveryAddress($id)
Define delivery address.
getTotalDiscount()
Function that returns the total amount HT of discounts applied for all lines.
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.
printObjectLine($action, $line, $var, $num, $i, $dateSelector, $seller, $buyer, $selected=0, $extrafields=null, $defaulttpldir='/core/tpl')
Return HTML content of a detail line TODO Move this into an output class file (htmlline....
copy_linked_contact($objFrom, $source='internal')
Copy contact from one element to current.
static commonReplaceThirdparty(DoliDB $dbs, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
Function used to replace a thirdparty id with another one.
getValueFrom($table, $id, $field)
Getter generic.
trimParameters($parameters)
Trim object parameters.
fetch_product()
Load the product with id $this->fk_product into this->product.
isIndex($info)
Function test if is indexed.
quote($value, $fieldsentry)
Add quote to field value if necessary.
formAddObjectLine($dateSelector, $seller, $buyer, $defaulttpldir='/core/tpl')
Show add free and predefined products/services form.
fetchComments()
Load comments linked with current task.
line_down($rowid, $fk_parent_line=true)
Update a line to have a higher rank.
setValueFrom($field, $value, $table='', $id=null, $format='', $id_field='', $fuser=null, $trigkey='', $fk_user_field='fk_user_modif')
Setter generic.
fetch_contact($contactid=null)
Load object contact with id=$this->contact_id into $this->contact.
setRetainedWarrantyPaymentTerms($id)
Change the retained warranty payments terms.
delThumbs($file)
Delete thumbs.
show_photos($modulepart, $sdir, $size=0, $nbmax=0, $nbbyrow=5, $showfilename=0, $showaction=0, $maxHeight=120, $maxWidth=160, $nolink=0, $overwritetitle=0, $usesharelink=0, $cache='', $addphotorefcss='photoref')
Show photos of an object (nbmax maximum), into several columns.
updateCommon(User $user, $notrigger=false)
Update object into database.
static commonReplaceProduct(DoliDB $dbs, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
Function used to replace a product id with another one.
getRangOfLine($rowid)
Get position of line (rang)
showInputField($val, $key, $value, $moreparam='', $keysuffix='', $keyprefix='', $morecss=0, $nonewbutton=0)
Return HTML string to put an input field into a page Code very similar with showInputField of extra f...
delete_resource($rowid, $element, $notrigger=0)
Delete a link to resource line.
update_contact($rowid, $statut, $type_contact_id=0, $fk_socpeople=0)
Update a link to contact line.
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.
fetchValuesForExtraLanguages()
Function to get alternative languages of a data into $this->array_languages This method is NOT called...
fetchNoCompute($id)
Function to make a fetch but set environment to avoid to load computed values before.
line_max($fk_parent_line=0)
Get max value used for position of line (rang)
getJSListDependancies($type='_extra')
setProject($projectid, $notrigger=0)
Link element with a project.
isForcedToNullIfZero($info)
Function test if field is forced to null if zero or empty.
line_ajaxorder($rows)
Update position of line with ajax (rang)
printOriginLinesList($restrictlist='', $selectedLines=array())
Return HTML table table of source object lines TODO Move this and previous function into output html ...
fetchLinesCommon($morewhere='')
Load object in memory from the database.
fetch_origin()
Read linked origin object.
getIdOfLine($rang)
Get rowid of the line relative to its position.
insertExtraFields($trigger='', $userused=null)
Add/Update all extra fields values for the current object.
static getAllItemsLinkedByObjectID($fk_object_where, $field_select, $field_where, $table_element)
Function used to get an array with all items linked to an object id in association table.
__clone()
Overwrite magic function to solve problem of cloning object that are kept as references.
setPaymentMethods($id)
Change the payments methods.
updateLineDown($rowid, $rang, $max)
Update position of line down (rang)
delete_linked_contact($source='', $code='')
Delete all links between an object $this and all its contacts in llx_element_contact.
getFormatedCustomerRef($objref)
Return customer ref for screen output.
getTooltipContentArray($params)
Return array of datas to show into a tooltip.
isText($info)
Function test if type is text.
isDate($info)
Function test if type is date.
printOriginLine($line, $var, $restrictlist='', $defaulttpldir='/core/tpl', $selectedLines=array())
Return HTML with a line of table array of source object lines TODO Move this and previous function in...
getCanvas($id=0, $ref='')
Load type of canvas of an object if it exists.
line_up($rowid, $fk_parent_line=true)
Update a line to have a lower rank.
isDuration($info)
Function test if type is duration.
canBeNull($info)
Function test if field can be null.
listeTypeContacts($source='internal', $option=0, $activeonly=0, $code='', $element='', $excludeelement='')
Return array with list of possible values for type of contacts.
call_trigger($triggerName, $user)
Call trigger based on this instance.
getRights()
Returns the rights used for this class.
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.
fetch_barcode()
Load data for barcode into properties ->barcode_type* Properties ->barcode_type that is id of barcode...
Class to manage absolute discounts.
Class to manage a WYSIWYG editor.
Class to manage Dolibarr database access.
Class to manage ECM files.
Class to manage triggers.
static getIdAndTxFromCode($dbs, $code, $date_document='')
Get id and rate of currency from code.
Class to manage predefined suppliers products.
Class to manage products or services.
const TYPE_SERVICE
Service.
Class to manage projects.
Class to manage third parties objects (customers, suppliers, prospects...)
Class to manage translations.
Class to manage Dolibarr users.
Class toolbox to validate values.
print $langs trans("Ref").' m m m statut
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.
convertSecondToTime($iSecond, $format='all', $lengthOfDay=86400, $lengthOfWeek=7)
Return, in clear text, value of a number of seconds in days, hours and minutes.
dol_meta_create($object)
Create a meta file with document file into same directory.
dol_delete_file($file, $disableglob=0, $nophperrors=0, $nohook=0, $object=null, $allowdotdot=false, $indexdatabase=1, $nolog=0)
Remove a file or several files with a mask.
dol_is_file($pathoffile)
Return if path is a file.
dol_dir_list($path, $types="all", $recursive=0, $filter="", $excludefilter=null, $sortcriteria="name", $sortorder=SORT_ASC, $mode=0, $nohook=0, $relativename="", $donotfollowsymlinks=0, $nbsecondsold=0)
Scan a directory and return a list of files/directories.
completeFileArrayWithDatabaseInfo(&$filearray, $relativedir)
Complete $filearray with data from database.
dol_delete_preview($object)
Delete all preview files linked to object instance.
dol_mktime($hour, $minute, $second, $month, $day, $year, $gm='auto', $check=1)
Return a timestamp date built from detailed informations (by default a local PHP server timestamp) Re...
vatrate($rate, $addpercent=false, $info_bits=0, $usestarfornpr=0, $html=0)
Return a string with VAT rate label formated for view output Used into pdf and HTML pages.
dol_print_ip($ip, $mode=0)
Return an IP formated to be shown on screen.
img_delete($titlealt='default', $other='class="pictodelete"', $morecss='')
Show delete logo.
dol_osencode($str)
Return a string encoded into OS filesystem encoding.
price2num($amount, $rounding='', $option=0)
Function that return a number with universal decimal format (decimal separator is '.
get_date_range($date_start, $date_end, $format='', $outputlangs='', $withparenthesis=1)
Format output for start and end date.
dol_print_error($db='', $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
img_object($titlealt, $picto, $moreatt='', $pictoisfullpath=false, $srconly=0, $notitle=0)
Show a picto called object_picto (generic function)
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.
dol_string_nospecial($str, $newstr='_', $badcharstoreplace='', $badcharstoremove='', $keepspaces=0)
Clean a string from all punctuation characters to use it as a ref or login.
price($amount, $form=0, $outlangs='', $trunc=1, $rounding=-1, $forcerounding=-1, $currency_code='')
Function to format a value into an amount for visual output Function used into PDF and HTML pages.
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs='', $encodetooutput=false)
Output date in a string format according to outputlangs (or langs if not defined).
dol_print_email($email, $cid=0, $socid=0, $addlink=0, $max=64, $showinvalid=1, $withpicto=0)
Show EMail link formatted for HTML output.
dol_print_phone($phone, $countrycode='', $cid=0, $socid=0, $addlink='', $separ=" ", $withpicto='', $titlealt='', $adddivfloat=0)
Format phone numbers according to country.
dol_now($mode='auto')
Return date for now.
getDolGlobalInt($key, $default=0)
Return dolibarr global constant int value.
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=false, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2)
Show picto whatever it's its name (generic function)
dol_escape_js($stringtoescape, $mode=0, $noescapebackslashn=0)
Returns text escaped for inclusion into javascript code.
dol_sort_array(&$array, $index, $order='asc', $natsort=0, $case_sensitive=0, $keepindex=0)
Advanced sort array by second index function, which produces ascending (default) or descending output...
if(!function_exists( 'dol_getprefix')) dol_include_once($relpath, $classname='')
Make an include_once using default root and alternate root if it fails.
dol_eval($s, $returnvalue=0, $hideerrors=1, $onlysimplestring='1')
Replace eval function to add more security.
getImageFileNameForSize($file, $extName, $extImgTarget='')
Return the filename of file to get the thumbs.
getAdvancedPreviewUrl($modulepart, $relativepath, $alldata=0, $param='')
Return URL we can use for advanced preview links.
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0)
Return value of a param into GET or POST supervariable.
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='', $noduplicate=0)
Set event messages in dol_events session object.
dol_print_url($url, $target='_blank', $max=32, $withpicto=0, $morecss='float')
Show Url link.
dol_buildpath($path, $type=0, $returnemptyifnotfound=0)
Return path of url or filesystem.
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_htmlentitiesbr($stringtoencode, $nl2brmode=0, $pagecodefrom='UTF-8', $removelasteolbr=1)
This function is called to encode a string into a HTML string but differs from htmlentities because a...
getDolGlobalString($key, $default='')
Return dolibarr global constant string value.
getDictionaryValue($tablename, $field, $id, $checkentity=false, $rowidfield='rowid')
Return the value of a filed into a dictionary for the record $id.
get_exdir($num, $level, $alpha, $withoutslash, $object, $modulepart='')
Return a path to have a the directory according to object where files are stored.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $noescapetags='', $escapeonlyhtmltags=0, $cleanalsojavascript=0)
Returns text escaped for inclusion in HTML alt or title or value tags, or into values of HTML input f...
vignette($file, $maxWidth=160, $maxHeight=120, $extName='_small', $quality=50, $outdir='thumbs', $targetformat=0)
Create a thumbnail from an image file (Supported extensions are gif, jpg, png and bmp).
getDefaultImageSizes()
Return default values for image sizes.
dol_getImageSize($file, $url=false)
Return size of image file on disk (Supported extensions are gif, jpg, png, bmp and webp)
image_format_supported($file, $acceptsvg=0)
Return if a filename is file name of a supported image format.
query($query, $usesavepoint=0, $type='auto', $result_mode=0)
Execute a SQL request and return the resultset.
publicphonebutton2 phonegreen basiclayout basiclayout TotalHT VATCode TotalVAT TotalLT1 TotalLT2 TotalTTC TotalHT clearboth nowraponall right right takeposterminal SELECT e rowid
calcul_price_total($qty, $pu, $remise_percent_ligne, $txtva, $uselocaltax1_rate, $uselocaltax2_rate, $remise_percent_global, $price_base_type, $info_bits, $type, $seller='', $localtaxes_array='', $progress=100, $multicurrency_tx=1, $pu_devise=0, $multicurrency_code='')
Calculate totals (net, vat, ...) of a line.
if(preg_match('/crypted:/i', $dolibarr_main_db_pass)||!empty($dolibarr_main_db_encrypted_pass)) $conf db type
getRandomPassword($generic=false, $replaceambiguouschars=null, $length=32)
Return a generated password using default module.
dol_hash($chain, $type='0')
Returns a hash (non reversible encryption) of a string.