43require_once DOL_DOCUMENT_ROOT.
'/core/class/doldeprecationhandler.class.php';
52 use DolDeprecationHandler;
54 const TRIGGER_PREFIX =
'';
90 public $errors = array();
95 private $validateFieldsErrors = array();
113 public $element_for_permission;
118 public $table_element;
123 public $table_element_line =
'';
129 public $ismultientitymanaged;
139 public $array_options = array();
145 public $fields = array();
152 public $array_languages =
null;
157 public $contacts_ids;
162 public $linked_objects;
167 public $linkedObjectsIds;
172 public $linkedObjects;
177 private $linkedObjectsFullLoaded = array();
192 protected $table_ref_field =
'';
197 public $restrictiononfksoc = 0;
206 public $context = array();
318 private $commandeFournisseur;
334 public $ref_previous;
381 public $country_code;
399 public $fk_departement;
430 public $barcode_type;
436 public $barcode_type_code;
442 public $barcode_type_label;
448 public $barcode_type_coder;
454 public $mode_reglement_id;
460 public $cond_reglement_id;
465 public $demand_reason_id;
471 public $transport_mode_id;
480 private $cond_reglement;
484 protected $depr_cond_reglement;
491 public $fk_delivery_address;
497 public $shipping_method_id;
503 public $shipping_method;
509 public $fk_multicurrency;
515 public $multicurrency_code;
521 public $multicurrency_tx;
526 public $multicurrency_total_ht;
531 public $multicurrency_total_tva;
536 public $multicurrency_total_ttc;
541 public $multicurrency_total_localtax1;
546 public $multicurrency_total_localtax2;
558 public $last_main_doc;
583 public $note_private;
608 public $total_localtax1;
614 public $total_localtax2;
631 public $actiontypecode;
637 public $comments = array();
663 public $date_creation;
668 public $date_validation;
673 public $date_modification;
687 private $date_update;
692 public $date_cloture;
704 public $user_creation;
709 public $user_creation_id;
721 public $user_validation;
726 public $user_validation_id;
731 public $user_closing_id;
737 public $user_modification;
742 public $user_modification_id;
748 public $fk_user_creat;
754 public $fk_user_modif;
760 public $next_prev_filter;
765 public $specimen = 0;
787 public $labelStatus = array();
792 public $labelStatusShort = array();
803 public $showphoto_on_popup;
808 public $nb = array();
823 public $extraparams = array();
828 protected $childtables = array();
835 protected $childtablesoncascade = array();
845 public $cond_reglement_supplier_id;
852 public $deposit_percent;
858 public $retained_warranty_fk_cond_reglement;
863 public $warehouse_id;
868 public $isextrafieldmanaged = 0;
881 'alreadypaid' =>
'totalpaid',
882 'cond_reglement' =>
'depr_cond_reglement',
884 'commandeFournisseur' =>
'origin_object',
885 'expedition' =>
'origin_object',
886 'fk_project' =>
'fk_project',
887 'livraison' =>
'origin_object',
888 'projet' =>
'project',
889 'statut' =>
'status',
908 $sql =
"SELECT rowid, ref, ref_ext";
909 $sql .=
" FROM ".$db->prefix().$element;
910 $sql .=
" WHERE entity IN (".getEntity($element).
")";
913 $sql .=
" AND rowid = ".((int) $id);
915 $sql .=
" AND ref = '".$db->escape($ref).
"'";
916 } elseif ($ref_ext) {
917 $sql .=
" AND ref_ext = '".$db->escape($ref_ext).
"'";
919 $error =
'ErrorWrongParameters';
920 dol_syslog(get_class().
"::isExistingObject ".$error, LOG_ERR);
923 if ($ref || $ref_ext) {
924 $sql .=
" AND entity = ".((int)
$conf->entity);
927 dol_syslog(get_class().
"::isExistingObject", LOG_DEBUG);
928 $resql = $db->query($sql);
930 $num = $db->num_rows($resql);
947 return (empty($this->
id));
962 $this->errors = array_merge($this->errors,
$object->errors);
987 global $action, $extrafields, $langs, $hookmanager;
990 $MAX_EXTRAFIELDS_TO_SHOW_IN_TOOLTIP =
getDolGlobalInt(
'MAX_EXTRAFIELDS_TO_SHOW_IN_TOOLTIP', 3);
996 if (!empty($extrafields->attributes[$this->table_element][
'label'])) {
997 $data[
'opendivextra'] =
'<div class="centpercent wordbreak divtooltipextra">';
998 foreach ($extrafields->attributes[$this->table_element][
'label'] as $key => $val) {
999 if ($extrafields->attributes[$this->table_element][
'type'][$key] ==
'separate') {
1002 if ($count >= abs($MAX_EXTRAFIELDS_TO_SHOW_IN_TOOLTIP)) {
1003 $data[
'more_extrafields'] =
'<br>...';
1007 if ($enabled && isset($extrafields->attributes[$this->table_element][
'enabled'][$key])) {
1008 $enabled = (int)
dol_eval((
string) $extrafields->attributes[$this->table_element][
'enabled'][$key], 1, 1,
'2');
1010 if ($enabled && isset($extrafields->attributes[$this->table_element][
'list'][$key])) {
1011 $enabled = (int)
dol_eval($extrafields->attributes[$this->table_element][
'list'][$key], 1, 1,
'2');
1014 if ($perms && isset($extrafields->attributes[$this->table_element][
'perms'][$key])) {
1015 $perms = (int)
dol_eval($extrafields->attributes[$this->table_element][
'perms'][$key], 1, 1,
'2');
1017 if (empty($enabled)) {
1020 if (abs($enabled) != 1 && abs($enabled) != 3 && abs($enabled) != 5 && abs($enabled) != 4) {
1023 if (empty($perms)) {
1026 if (!empty($extrafields->attributes[$this->table_element][
'langfile'][$key])) {
1027 $langs->load($extrafields->attributes[$this->table_element][
'langfile'][$key]);
1029 $labelextra = $langs->trans((
string) $extrafields->attributes[$this->table_element][
'label'][$key]);
1030 if ($extrafields->attributes[$this->table_element][
'type'][$key] ==
'separate') {
1031 $data[$key] =
'<br><b><u>'. $labelextra .
'</u></b>';
1033 $value = (empty($this->array_options[
'options_' . $key]) ?
'' : $this->array_options[
'options_' . $key]);
1034 $data[$key] =
'<br><b>'. $labelextra .
':</b> ' . $extrafields->showOutputField($key, $value,
'', $this->table_element);
1038 $data[
'closedivextra'] =
'</div>';
1041 $hookmanager->initHooks(array($this->element .
'dao'));
1042 $parameters = array(
1043 'tooltipcontentarray' => &$data,
1044 'params' => $params,
1047 $hookmanager->executeHooks(
'getTooltipContent', $parameters, $this, $action);
1050 $label = implode($data);
1063 return $this->error.(is_array($this->errors) ? (($this->error !=
'' ?
', ' :
'').implode(
', ', $this->errors)) :
'');
1075 global $hookmanager;
1077 $parameters = array(
'objref' => $objref);
1079 $reshook = $hookmanager->executeHooks(
'getFormatedCustomerRef', $parameters, $this, $action);
1081 return $hookmanager->resArray[
'objref'];
1083 return $objref.(isset($hookmanager->resArray[
'objref']) ? $hookmanager->resArray[
'objref'] :
'');
1094 global $hookmanager;
1096 $parameters = array(
'objref' => $objref);
1098 $reshook = $hookmanager->executeHooks(
'getFormatedSupplierRef', $parameters, $this, $action);
1100 return $hookmanager->resArray[
'objref'];
1102 return $objref.(isset($hookmanager->resArray[
'objref']) ? $hookmanager->resArray[
'objref'] :
'');
1114 public function getFullAddress($withcountry = 0, $sep =
"\n", $withregion = 0, $extralangcode =
'')
1116 if ($withcountry && $this->country_id && (empty($this->country_code) || empty($this->country))) {
1117 require_once DOL_DOCUMENT_ROOT.
'/core/lib/company.lib.php';
1118 $tmparray =
getCountry($this->country_id,
'all');
1119 $this->country_code = $tmparray[
'code'];
1120 $this->country = $tmparray[
'label'];
1123 if ($withregion && $this->state_id && (empty($this->state_code) || empty($this->state) || empty($this->region) || empty($this->region_code))) {
1124 require_once DOL_DOCUMENT_ROOT.
'/core/lib/company.lib.php';
1125 $tmparray =
getState($this->state_id,
'all',
null, 1);
1126 $this->state_code = $tmparray[
'code'];
1127 $this->state = $tmparray[
'label'];
1128 $this->region_code = $tmparray[
'region_code'];
1129 $this->region = $tmparray[
'region'];
1146 global $user, $dolibarr_main_url_root;
1148 if (empty($this->last_main_doc)) {
1152 include_once DOL_DOCUMENT_ROOT.
'/ecm/class/ecmfiles.class.php';
1153 $ecmfile =
new EcmFiles($this->db);
1154 $result = $ecmfile->fetch(0,
'', $this->last_main_doc);
1156 $this->error = $ecmfile->error;
1157 $this->errors = $ecmfile->errors;
1161 if (empty($ecmfile->id)) {
1163 if ($initsharekey) {
1164 require_once DOL_DOCUMENT_ROOT.
'/core/lib/security2.lib.php';
1186 } elseif (empty($ecmfile->share)) {
1188 if ($initsharekey) {
1189 require_once DOL_DOCUMENT_ROOT.
'/core/lib/security2.lib.php';
1191 $ecmfile->update($user);
1197 $urlwithouturlroot = preg_replace(
'/'.preg_quote(DOL_URL_ROOT,
'/').
'$/i',
'', trim($dolibarr_main_url_root));
1201 $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT;
1210 if (!empty($ecmfile->share)) {
1211 $paramlink .= ($paramlink ?
'&' :
'').
'hashp='.$ecmfile->share;
1213 if ($forcedownload) {
1214 $paramlink .= ($paramlink ?
'&' :
'').
'attachment=1';
1217 if ($relativelink) {
1218 $linktoreturn =
'document.php'.($paramlink ?
'?'.$paramlink :
'');
1220 $linktoreturn = $urlwithroot.
'/document.php'.($paramlink ?
'?'.$paramlink :
'');
1224 return $linktoreturn;
1238 public function add_contact($fk_socpeople, $type_contact, $source =
'external', $notrigger = 0)
1241 global $user, $langs;
1244 dol_syslog(get_class($this).
"::add_contact $fk_socpeople, $type_contact, $source, $notrigger");
1247 if ($fk_socpeople <= 0) {
1248 $langs->load(
"errors");
1249 $this->error = $langs->trans(
"ErrorWrongValueForParameterX",
"1");
1250 dol_syslog(get_class($this).
"::add_contact ".$this->error, LOG_ERR);
1253 if (!$type_contact) {
1254 $langs->load(
"errors");
1255 $this->error = $langs->trans(
"ErrorWrongValueForParameterX",
"2");
1256 dol_syslog(get_class($this).
"::add_contact ".$this->error, LOG_ERR);
1260 $id_type_contact = 0;
1261 if (is_numeric($type_contact)) {
1262 $id_type_contact = $type_contact;
1265 $sql =
"SELECT tc.rowid";
1266 $sql .=
" FROM ".$this->db->prefix().
"c_type_contact as tc";
1267 $sql .=
" WHERE tc.element='".$this->db->escape($this->element).
"'";
1268 $sql .=
" AND tc.source='".$this->db->escape($source).
"'";
1269 $sql .=
" AND tc.code='".$this->db->escape($type_contact).
"' AND tc.active=1";
1271 $resql = $this->db->query($sql);
1273 $obj = $this->db->fetch_object($resql);
1275 $id_type_contact = $obj->rowid;
1280 if ($id_type_contact == 0) {
1281 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");
1289 $already_added =
false;
1290 if (is_array($TListeContacts) && !empty($TListeContacts)) {
1291 foreach ($TListeContacts as $array_contact) {
1292 if ($array_contact[
'status'] == 4 && $array_contact[
'id'] == $fk_socpeople && $array_contact[
'fk_c_type_contact'] == $id_type_contact) {
1293 $already_added =
true;
1299 if (!$already_added) {
1303 $sql =
"INSERT INTO ".$this->db->prefix().
"element_contact";
1304 $sql .=
" (element_id, fk_socpeople, datecreate, statut, fk_c_type_contact) ";
1305 $sql .=
" VALUES (".$this->id.
", ".((int) $fk_socpeople).
" , ";
1306 $sql .=
"'".$this->db->idate($datecreate).
"'";
1307 $sql .=
", 4, ".((int) $id_type_contact);
1310 $resql = $this->db->query($sql);
1313 $result = $this->
call_trigger(strtoupper($this->element).
'_ADD_CONTACT', $user);
1315 $this->db->rollback();
1320 $this->db->commit();
1323 if ($this->db->errno() ==
'DB_ERROR_RECORD_ALREADY_EXISTS') {
1324 $this->error = $this->db->errno();
1325 $this->db->rollback();
1328 $this->error = $this->db->lasterror();
1329 $this->db->rollback();
1349 $contacts = $objFrom->liste_contact(-1, $source);
1350 foreach ($contacts as $contact) {
1351 if ($this->
add_contact($contact[
'id'], $contact[
'fk_c_type_contact'], $contact[
'source']) < 0) {
1368 public function update_contact($rowid, $statut, $type_contact_id = 0, $fk_socpeople = 0)
1372 $sql =
"UPDATE ".$this->db->prefix().
"element_contact set";
1373 $sql .=
" statut = ".((int) $statut);
1374 if ($type_contact_id) {
1375 $sql .=
", fk_c_type_contact = ".((int) $type_contact_id);
1377 if ($fk_socpeople) {
1378 $sql .=
", fk_socpeople = ".((int) $fk_socpeople);
1380 $sql .=
" where rowid = ".((int) $rowid);
1382 $resql = $this->db->query($sql);
1386 $this->error = $this->db->lasterror();
1408 if (!$error && empty($notrigger)) {
1410 $this->context[
'contact_id'] = ((int) $rowid);
1411 $result = $this->
call_trigger(strtoupper($this->element).
'_DELETE_CONTACT', $user);
1419 dol_syslog(get_class($this).
"::delete_contact", LOG_DEBUG);
1421 $sql =
"DELETE FROM ".MAIN_DB_PREFIX.
"element_contact";
1422 $sql .=
" WHERE rowid = ".((int) $rowid);
1424 $result = $this->db->query($sql);
1427 $this->errors[] = $this->db->lasterror();
1432 $this->db->commit();
1435 $this->error = $this->db->lasterror();
1436 $this->db->rollback();
1456 if (!empty($typeContact)) {
1457 foreach ($typeContact as $key => $value) {
1458 array_push($temp, $key);
1460 $listId = implode(
",", $temp);
1465 if (empty($listId)) {
1469 $sql =
"DELETE FROM ".$this->db->prefix().
"element_contact";
1470 $sql .=
" WHERE element_id = ".((int) $this->
id);
1471 $sql .=
" AND fk_c_type_contact IN (".$this->db->sanitize($listId).
")";
1473 dol_syslog(get_class($this).
"::delete_linked_contact", LOG_DEBUG);
1474 if ($this->db->query($sql)) {
1477 $this->error = $this->db->lasterror();
1494 public function liste_contact($statusoflink = -1, $source =
'external', $list = 0, $code =
'', $status = -1, $arrayoftcids = array())
1501 $sql =
"SELECT ec.rowid, ec.statut as statuslink, ec.fk_socpeople as id, ec.fk_c_type_contact";
1502 if ($source ==
'internal') {
1503 $sql .=
", '-1' as socid, t.statut as statuscontact, t.login, t.photo, t.gender";
1505 if ($source ==
'external' || $source ==
'thirdparty') {
1506 $sql .=
", t.fk_soc as socid, t.statut as statuscontact";
1508 $sql .=
", t.civility as civility, t.lastname as lastname, t.firstname, t.email";
1509 if (empty($arrayoftcids)) {
1510 $sql .=
", tc.source, tc.element, tc.code, tc.libelle as type_label";
1513 if (empty($arrayoftcids)) {
1514 $sql .=
" ".$this->db->prefix().
"c_type_contact as tc,";
1516 $sql .=
" ".$this->db->prefix().
"element_contact as ec";
1517 if ($source ==
'internal') {
1518 $sql .=
" LEFT JOIN ".$this->db->prefix().
"user as t on ec.fk_socpeople = t.rowid";
1520 if ($source ==
'external' || $source ==
'thirdparty') {
1521 $sql .=
" LEFT JOIN ".$this->db->prefix().
"socpeople as t on ec.fk_socpeople = t.rowid";
1523 $sql .=
" WHERE ec.element_id = ".((int) $this->
id);
1524 if (empty($arrayoftcids)) {
1525 $sql .=
" AND ec.fk_c_type_contact = tc.rowid";
1526 $sql .=
" AND tc.element = '".$this->db->escape($this->element).
"'";
1528 $sql .=
" AND tc.code = '".$this->db->escape($code).
"'";
1530 if ($source ==
'internal') {
1531 $sql .=
" AND tc.source = 'internal'";
1533 if ($source ==
'external' || $source ==
'thirdparty') {
1534 $sql .=
" AND tc.source = 'external'";
1536 $sql .=
" AND tc.active = 1";
1538 $sql .=
" AND ec.fk_c_type_contact IN (".$this->db->sanitize(implode(
',', $arrayoftcids)).
")";
1541 $sql .=
" AND t.statut = ".((int) $status);
1543 if ($statusoflink >= 0) {
1544 $sql .=
" AND ec.statut = ".((int) $statusoflink);
1546 $sql .=
" ORDER BY t.lastname ASC";
1548 dol_syslog(get_class($this).
"::liste_contact", LOG_DEBUG);
1549 $resql = $this->db->query($sql);
1551 $num = $this->db->num_rows($resql);
1554 $obj = $this->db->fetch_object($resql);
1557 $transkey =
"TypeContact_".$obj->element.
"_".$obj->source.
"_".$obj->code;
1558 $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->type_label);
1560 'parentId' => $this->
id,
1561 'source' => $obj->source,
1562 'socid' => $obj->socid,
1564 'nom' => $obj->lastname,
1565 'civility' => $obj->civility,
1566 'lastname' => $obj->lastname,
1567 'firstname' => $obj->firstname,
1568 'email' => $obj->email,
1569 'login' => (empty($obj->login) ?
'' : $obj->login),
1570 'photo' => (empty($obj->photo) ?
'' : $obj->photo),
1571 'gender' => (empty($obj->gender) ?
'' : $obj->gender),
1572 'statuscontact' => $obj->statuscontact,
1573 'rowid' => $obj->rowid,
1574 'code' => $obj->code,
1575 'libelle' => $libelle_type,
1576 'status' => $obj->statuslink,
1577 'fk_c_type_contact' => $obj->fk_c_type_contact
1580 $tab[$i] = $obj->id;
1588 $this->error = $this->db->lasterror();
1603 $sql =
"SELECT ec.datecreate, ec.statut, ec.fk_socpeople, ec.fk_c_type_contact,";
1604 $sql .=
" tc.code, tc.libelle as type_label";
1605 $sql .=
" FROM (".$this->db->prefix().
"element_contact as ec, ".$this->db->prefix().
"c_type_contact as tc)";
1606 $sql .=
" WHERE ec.rowid =".((int) $rowid);
1607 $sql .=
" AND ec.fk_c_type_contact = tc.rowid";
1608 $sql .=
" AND tc.element = '".$this->db->escape($this->element).
"'";
1610 dol_syslog(get_class($this).
"::swapContactStatus", LOG_DEBUG);
1611 $resql = $this->db->query($sql);
1613 $obj = $this->db->fetch_object($resql);
1614 $newstatut = ($obj->statut == 4) ? 5 : 4;
1616 $this->db->free($resql);
1619 $this->error = $this->db->error();
1636 public function liste_type_contact($source =
'internal', $order =
'position', $option = 0, $activeonly = 0, $code =
'')
1641 if (empty($order)) {
1642 $order =
'position';
1644 if ($order ==
'position') {
1650 $sql =
"SELECT DISTINCT tc.rowid, tc.code, tc.libelle as type_label, tc.position";
1651 $sql .=
" FROM ".$this->db->prefix().
"c_type_contact as tc";
1652 $sql .=
" WHERE tc.element = '".$this->db->escape($this->element).
"'";
1653 if ($activeonly == 1) {
1654 $sql .=
" AND tc.active = 1";
1656 if (!empty($source) && $source !=
'all') {
1657 $sql .=
" AND tc.source = '".$this->db->escape($source).
"'";
1659 if (!empty($code)) {
1660 $sql .=
" AND tc.code = '".$this->db->escape($code).
"'";
1662 $sql .= $this->db->order($order,
'ASC');
1665 $resql = $this->db->query($sql);
1667 $this->error = $this->db->lasterror();
1672 $num = $this->db->num_rows($resql);
1675 $obj = $this->db->fetch_object($resql);
1677 $transkey =
"TypeContact_".$this->element.
"_".$source.
"_".$obj->code;
1678 $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->type_label);
1679 if (empty($option)) {
1680 $tab[$obj->rowid] = $libelle_type;
1681 } elseif ($option == 1) {
1682 $tab[$obj->code] = $libelle_type;
1684 $tab[$obj->rowid] = array(
'id' => $obj->rowid,
'code' => $obj->code,
'label' => $libelle_type);
1703 public function listeTypeContacts($source =
'internal', $option = 0, $activeonly = 0, $code =
'', $element =
'', $excludeelement =
'')
1707 $langs->loadLangs(array(
'bills',
'contracts',
'interventions',
'orders',
'projects',
'propal',
'ticket',
'agenda'));
1711 $sql =
"SELECT DISTINCT tc.rowid, tc.code, tc.libelle as type_label, tc.position, tc.element, tc.module";
1712 $sql .=
" FROM ".$this->db->prefix().
"c_type_contact as tc";
1714 $sqlWhere = array();
1715 if (!empty($element)) {
1716 $sqlWhere[] =
" tc.element='".$this->db->escape($element).
"'";
1718 if (!empty($excludeelement)) {
1719 $sqlWhere[] =
" tc.element <> '".$this->db->escape($excludeelement).
"'";
1722 if ($activeonly == 1) {
1723 $sqlWhere[] =
" tc.active=1";
1726 if (!empty($source) && $source !=
'all') {
1727 $sqlWhere[] =
" tc.source='".$this->db->escape($source).
"'";
1730 if (!empty($code)) {
1731 $sqlWhere[] =
" tc.code='".$this->db->escape($code).
"'";
1734 if (count($sqlWhere) > 0) {
1735 $sql .=
" WHERE ".implode(
' AND ', $sqlWhere);
1738 $sql .= $this->db->order(
'tc.element, tc.position',
'ASC');
1741 $resql = $this->db->query($sql);
1743 $num = $this->db->num_rows($resql);
1745 $langs->loadLangs(array(
"propal",
"orders",
"bills",
"suppliers",
"contracts",
"supplier_proposal"));
1747 while ($obj = $this->db->fetch_object($resql)) {
1748 $modulename = $obj->module ?? $obj->element;
1749 if (strpos($obj->element,
'project') !==
false) {
1750 $modulename =
'projet';
1751 } elseif ($obj->element ==
'contrat') {
1752 $element =
'contract';
1753 } elseif ($obj->element ==
'action') {
1754 $modulename =
'agenda';
1755 } elseif (strpos($obj->element,
'supplier') !==
false && $obj->element !=
'supplier_proposal') {
1756 $modulename =
'fournisseur';
1758 if (isModEnabled($modulename)) {
1759 $libelle_element = $langs->trans(
'ContactDefault_'.$obj->element);
1760 $tmpelement = $obj->element;
1761 $transkey =
"TypeContact_".$tmpelement.
"_".$source.
"_".$obj->code;
1762 $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->type_label);
1763 $tab[$obj->rowid] = $libelle_element.
' - '.$libelle_type;
1769 $this->error = $this->db->lasterror();
1790 if ($this->element ==
'shipping' && $this->origin_id != 0) {
1791 $id = $this->origin_id;
1792 $element =
'commande';
1793 } elseif ($this->element ==
'reception' && $this->origin_id != 0) {
1794 $id = $this->origin_id;
1795 $element =
'order_supplier';
1798 $element = $this->element;
1801 $sql =
"SELECT ec.fk_socpeople";
1802 $sql .=
" FROM ".$this->db->prefix().
"element_contact as ec,";
1803 if ($source ==
'internal') {
1804 $sql .=
" ".$this->db->prefix().
"user as c,";
1806 if ($source ==
'external') {
1807 $sql .=
" ".$this->db->prefix().
"socpeople as c,";
1809 $sql .=
" ".$this->db->prefix().
"c_type_contact as tc";
1810 $sql .=
" WHERE ec.element_id = ".((int) $id);
1811 $sql .=
" AND ec.fk_socpeople = c.rowid";
1812 if ($source ==
'internal') {
1813 $sql .=
" AND c.entity IN (".getEntity(
'user').
")";
1815 if ($source ==
'external') {
1816 $sql .=
" AND c.entity IN (".getEntity(
'societe').
")";
1818 $sql .=
" AND ec.fk_c_type_contact = tc.rowid";
1819 $sql .=
" AND tc.element = '".$this->db->escape($element).
"'";
1820 $sql .=
" AND tc.source = '".$this->db->escape($source).
"'";
1822 $sql .=
" AND tc.code = '".$this->db->escape($code).
"'";
1824 $sql .=
" AND tc.active = 1";
1826 $sql .=
" AND ec.statut = ".((int) $status);
1829 dol_syslog(get_class($this).
"::getIdContact", LOG_DEBUG);
1830 $resql = $this->db->query($sql);
1832 while ($obj = $this->db->fetch_object($resql)) {
1833 $result[$i] = $obj->fk_socpeople;
1837 $this->error = $this->db->error();
1854 if (empty($contactid)) {
1855 $contactid = $this->contact_id;
1858 if (empty($contactid)) {
1862 require_once DOL_DOCUMENT_ROOT.
'/contact/class/contact.class.php';
1863 $contact =
new Contact($this->db);
1864 $result = $contact->fetch($contactid);
1865 $this->contact = $contact;
1880 if (empty($this->socid) && empty($this->fk_soc) && empty($force_thirdparty_id)) {
1884 require_once DOL_DOCUMENT_ROOT.
'/societe/class/societe.class.php';
1886 $idtofetch = isset($this->socid) ? $this->socid : (isset($this->fk_soc) ? $this->fk_soc : 0);
1887 if ($force_thirdparty_id) {
1888 $idtofetch = $force_thirdparty_id;
1892 $thirdparty =
new Societe($this->db);
1893 $result = $thirdparty->fetch($idtofetch);
1895 $this->errors = array_merge($this->errors, $thirdparty->errors);
1897 $this->thirdparty = $thirdparty;
1901 $this->thirdparty->price_level = 1;
1920 if (!$this->table_ref_field) {
1924 $sql =
"SELECT rowid FROM ".$this->db->prefix().$this->table_element;
1925 $sql .=
" WHERE ".$this->table_ref_field.
" LIKE '".$this->db->escape($ref).
"'";
1928 $query = $this->db->query($sql);
1930 if (!$this->db->num_rows($query)) {
1934 $result = $this->db->fetch_object($query);
1936 if (method_exists($this,
'fetch')) {
1937 return $this->fetch($result->rowid);
1939 $this->error =
'Fetch method not implemented on '.get_class($this);
1940 dol_syslog(get_class($this).
'::fetchOneLike Error='.$this->error, LOG_ERR);
1941 array_push($this->errors, $this->error);
1970 dol_syslog(get_class($this).
'::fetchBarCode this->element='.$this->element.
' this->barcode_type='.$this->barcode_type);
1972 $idtype = $this->barcode_type;
1973 if (empty($idtype) && $idtype !=
'0') {
1974 if ($this->element ==
'product' &&
getDolGlobalString(
'PRODUIT_DEFAULT_BARCODE_TYPE')) {
1976 } elseif ($this->element ==
'societe') {
1979 dol_syslog(
'Call fetchBarCode with barcode_type not defined and cannot be guessed', LOG_WARNING);
1984 if (empty($this->barcode_type) || empty($this->barcode_type_code) || empty($this->barcode_type_label) || empty($this->barcode_type_coder)) {
1985 $sql =
"SELECT rowid, code, libelle as label, coder";
1986 $sql .=
" FROM ".$this->db->prefix().
"c_barcode_type";
1987 $sql .=
" WHERE rowid = ".((int) $idtype);
1989 $resql = $this->db->query($sql);
1991 $obj = $this->db->fetch_object($resql);
1993 $this->barcode_type = $obj->rowid;
1994 $this->barcode_type_code = $obj->code;
1995 $this->barcode_type_label = $obj->label;
1996 $this->barcode_type_coder = $obj->coder;
2014 include_once DOL_DOCUMENT_ROOT.
'/projet/class/project.class.php';
2016 if (empty($this->fk_project) && !empty($this->fk_projet)) {
2017 $this->fk_project = $this->fk_projet;
2019 if (empty($this->fk_project)) {
2023 $project =
new Project($this->db);
2024 $result = $project->fetch($this->fk_project);
2026 $this->projet = $project;
2027 $this->project = $project;
2069 include_once DOL_DOCUMENT_ROOT.
'/product/class/product.class.php';
2072 if (empty($this->fk_product)) {
2076 $product =
new Product($this->db);
2078 $result = $product->fetch($this->fk_product);
2080 $this->product = $product;
2094 $user =
new User($this->db);
2095 $result = $user->fetch($userid);
2096 $this->
user = $user;
2110 $origin = $this->origin ? $this->origin : $this->origin_type;
2113 if ($origin ==
'shipping') {
2114 $origin =
'expedition';
2116 if ($origin ==
'delivery') {
2117 $origin =
'livraison';
2119 if ($origin ==
'order_supplier' || $origin ==
'supplier_order') {
2120 $origin =
'commandeFournisseur';
2123 $classname = ucfirst($origin);
2124 $this->origin_object =
new $classname($this->db);
2126 $this->origin_object->fetch($this->origin_id);
2144 $sql =
"SELECT rowid FROM ".$this->db->prefix().$table;
2145 $sql .=
" WHERE ".$field.
" = '".$this->db->escape($key).
"'";
2146 if (!empty($element)) {
2147 $sql .=
" AND entity IN (".getEntity($element).
")";
2149 $sql .=
" AND entity = ".((int)
$conf->entity);
2152 dol_syslog(get_class($this).
'::fetchObjectFrom', LOG_DEBUG);
2153 $resql = $this->db->query($sql);
2155 $obj = $this->db->fetch_object($resql);
2158 if (method_exists($this,
'fetch')) {
2159 $result = $this->fetch($obj->rowid);
2161 $this->error =
'fetch() method not implemented on '.get_class($this);
2162 dol_syslog(get_class($this).
'::fetchOneLike Error='.$this->error, LOG_ERR);
2163 array_push($this->errors, $this->error);
2183 if (!empty($id) && !empty($field) && !empty($table)) {
2184 $sql =
"SELECT ".$field.
" FROM ".$this->db->prefix().$table;
2185 $sql .=
" WHERE rowid = ".((int) $id);
2187 dol_syslog(get_class($this).
'::getValueFrom', LOG_DEBUG);
2188 $resql = $this->db->query($sql);
2190 $row = $this->db->fetch_row($resql);
2213 public function setValueFrom($field, $value, $table =
'', $id =
null, $format =
'', $id_field =
'', $fuser =
null, $trigkey =
'', $fk_user_field =
'fk_user_modif')
2217 if (empty($table)) {
2218 $table = $this->table_element;
2223 if (empty($format)) {
2226 if (empty($id_field)) {
2227 $id_field =
'rowid';
2231 if ($table ==
'product' && $field ==
'note_private') {
2235 if (in_array($table, array(
'actioncomm',
'adherent',
'advtargetemailing',
'cronjob',
'establishment'))) {
2236 $fk_user_field =
'fk_user_mod';
2238 if (in_array($table, array(
'prelevement_bons'))) {
2239 $fk_user_field =
'';
2244 $sql =
"SELECT " . $field;
2245 $sql .=
" FROM " . MAIN_DB_PREFIX . $table;
2246 $sql .=
" WHERE " . $id_field .
" = " . ((int) $id);
2248 $resql = $this->db->query($sql);
2250 if ($obj = $this->db->fetch_object($resql)) {
2251 if ($format ==
'date') {
2252 $oldvalue = $this->db->jdate($obj->$field);
2254 $oldvalue = $obj->$field;
2258 $this->error = $this->db->lasterror();
2269 $sql =
"UPDATE ".$this->db->prefix().$table.
" SET ";
2271 if ($format ==
'text') {
2272 $sql .= $field.
" = '".$this->db->escape($value).
"'";
2273 } elseif ($format ==
'int') {
2274 $sql .= $field.
" = ".((int) $value);
2275 } elseif ($format ==
'date') {
2276 $sql .= $field.
" = ".($value ?
"'".$this->db->idate($value).
"'" :
"null");
2277 } elseif ($format ==
'dategmt') {
2278 $sql .= $field.
" = ".($value ?
"'".$this->db->idate($value,
'gmt').
"'" :
"null");
2281 if ($fk_user_field) {
2282 if (!empty($fuser) && is_object($fuser)) {
2283 $sql .=
", ".$fk_user_field.
" = ".((int) $fuser->id);
2284 } elseif (empty($fuser) || $fuser !=
'none') {
2285 $sql .=
", ".$fk_user_field.
" = ".((int) $user->id);
2289 $sql .=
" WHERE ".$id_field.
" = ".((int) $id);
2291 $resql = $this->db->query($sql);
2295 if (method_exists($this,
'fetch')) {
2296 $result = $this->fetch($id);
2300 $this->oldcopy = clone $this;
2301 if (property_exists($this->oldcopy, $field)) {
2302 $this->oldcopy->$field = $oldvalue;
2306 $result = $this->
call_trigger($trigkey, (!empty($fuser) && is_object($fuser)) ? $fuser : $user);
2314 if (property_exists($this, $field)) {
2315 $this->$field = $value;
2317 $this->db->commit();
2320 $this->db->rollback();
2324 if ($this->db->lasterrno() ==
'DB_ERROR_RECORD_ALREADY_EXISTS') {
2325 $this->error =
'DB_ERROR_RECORD_ALREADY_EXISTS';
2327 $this->error = $this->db->lasterror();
2329 $this->db->rollback();
2348 global
$conf, $user;
2350 if (!$this->table_element) {
2351 dol_print_error(
null, get_class($this).
"::load_previous_next_ref was called on object with property table_element not defined");
2354 if ($fieldid ==
'none') {
2359 if (in_array($this->table_element, array(
'facture_rec',
'facture_fourn_rec')) && $fieldid ==
'title') {
2365 if ($user->socid > 0) {
2366 $socid = $user->socid;
2371 $aliastablesociete =
's';
2372 if ($this->element ==
'societe') {
2373 $aliastablesociete =
'te';
2375 $restrictiononfksoc = empty($this->restrictiononfksoc) ? 0 : $this->restrictiononfksoc;
2376 $sql =
"SELECT MAX(te.".$fieldid.
")";
2377 $sql .=
" FROM ".(empty($nodbprefix) ? $this->db->prefix() :
'').$this->table_element.
" as te";
2378 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2379 $tmparray = explode(
'@', $this->ismultientitymanaged);
2380 $sql .=
", ".$this->db->prefix().$tmparray[1].
" as ".($tmparray[1] ==
'societe' ?
's' :
'parenttable');
2381 } elseif ($restrictiononfksoc == 1 && $this->element !=
'societe' && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2382 $sql .=
", ".$this->db->prefix().
"societe as s";
2383 } elseif ($restrictiononfksoc == 2 && $this->element !=
'societe' && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2384 $sql .=
" LEFT JOIN ".$this->db->prefix().
"societe as s ON te.fk_soc = s.rowid";
2386 if ($restrictiononfksoc && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2387 $sql .=
" LEFT JOIN ".$this->db->prefix().
"societe_commerciaux as sc ON ".$aliastablesociete.
".rowid = sc.fk_soc";
2389 if ($fieldid ==
'rowid') {
2390 $sql .=
" WHERE te.".$fieldid.
" < ".((int) $this->
id);
2392 $sql .=
" WHERE te.".$fieldid.
" < '".$this->db->escape($this->
ref).
"'";
2394 if ($restrictiononfksoc == 1 && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2395 $sql .=
" AND sc.fk_user = ".((int) $user->id);
2397 if ($restrictiononfksoc == 2 && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2398 $sql .=
" AND (sc.fk_user = ".((int) $user->id).
' OR te.fk_soc IS NULL)';
2401 $filtermax = $filter;
2406 if ($errormessage) {
2407 if (!preg_match(
'/^\s*AND/i', $filtermax)) {
2415 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2416 $tmparray = explode(
'@', $this->ismultientitymanaged);
2417 $sql .=
" AND te.".$tmparray[0].
" = ".($tmparray[1] ==
"societe" ?
"s" :
"parenttable").
".rowid";
2418 } elseif ($restrictiononfksoc == 1 && $this->element !=
'societe' && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2419 $sql .=
' AND te.fk_soc = s.rowid';
2421 if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
2422 if ($this->element ==
'user' &&
getDolGlobalInt(
'MULTICOMPANY_TRANSVERSE_MODE')) {
2423 if (!empty($user->admin) && empty($user->entity) &&
$conf->entity == 1) {
2424 $sql .=
" AND te.entity IS NOT NULL";
2426 $sql .=
" AND te.rowid IN (SELECT ug.fk_user FROM ".$this->db->prefix().
"usergroup_user as ug WHERE ug.entity IN (".
getEntity(
'usergroup').
"))";
2429 $sql .=
' AND te.entity IN ('.getEntity($this->element).
')';
2432 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged) && $this->element !=
'societe') {
2433 $tmparray = explode(
'@', $this->ismultientitymanaged);
2434 $sql .=
' AND parenttable.entity IN ('.getEntity($tmparray[1]).
')';
2436 if ($restrictiononfksoc == 1 && $socid && $this->element !=
'societe') {
2437 $sql .=
' AND te.fk_soc = '.((int) $socid);
2439 if ($restrictiononfksoc == 2 && $socid && $this->element !=
'societe') {
2440 $sql .=
' AND (te.fk_soc = '.((int) $socid).
' OR te.fk_soc IS NULL)';
2442 if ($restrictiononfksoc && $socid && $this->element ==
'societe') {
2443 $sql .=
' AND te.rowid = '.((int) $socid);
2447 $result = $this->db->query($sql);
2449 $this->error = $this->db->lasterror();
2452 $row = $this->db->fetch_row($result);
2453 $this->ref_previous = $row[0];
2455 $sql =
"SELECT MIN(te.".$fieldid.
")";
2456 $sql .=
" FROM ".(empty($nodbprefix) ? $this->db->prefix() :
'').$this->table_element.
" as te";
2457 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2458 $tmparray = explode(
'@', $this->ismultientitymanaged);
2459 $sql .=
", ".$this->db->prefix().$tmparray[1].
" as ".($tmparray[1] ==
'societe' ?
's' :
'parenttable');
2460 } elseif ($restrictiononfksoc == 1 && $this->element !=
'societe' && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2461 $sql .=
", ".$this->db->prefix().
"societe as s";
2462 } elseif ($restrictiononfksoc == 2 && $this->element !=
'societe' && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2463 $sql .=
" LEFT JOIN ".$this->db->prefix().
"societe as s ON te.fk_soc = s.rowid";
2465 if ($restrictiononfksoc && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2466 $sql .=
" LEFT JOIN ".$this->db->prefix().
"societe_commerciaux as sc ON ".$aliastablesociete.
".rowid = sc.fk_soc";
2468 if ($fieldid ==
'rowid') {
2469 $sql .=
" WHERE te.".$fieldid.
" > ".((int) $this->
id);
2471 $sql .=
" WHERE te.".$fieldid.
" > '".$this->db->escape($this->
ref).
"'";
2473 if ($restrictiononfksoc == 1 && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2474 $sql .=
" AND (sc.fk_user = ".((int) $user->id);
2476 $userschilds = $user->getAllChildIds();
2477 $sql .=
" OR sc.fk_user IN (".$this->db->sanitize(implode(
',', $userschilds)).
")";
2481 if ($restrictiononfksoc == 2 && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2482 $sql .=
" AND (sc.fk_user = ".((int) $user->id).
' OR te.fk_soc IS NULL)';
2485 $filtermin = $filter;
2490 if ($errormessage) {
2491 if (!preg_match(
'/^\s*AND/i', $filtermin)) {
2501 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2502 $tmparray = explode(
'@', $this->ismultientitymanaged);
2503 $sql .=
" AND te.".$tmparray[0].
" = ".($tmparray[1] ==
"societe" ?
"s" :
"parenttable").
".rowid";
2504 } elseif ($restrictiononfksoc == 1 && $this->element !=
'societe' && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2505 $sql .=
' AND te.fk_soc = s.rowid';
2507 if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
2508 if ($this->element ==
'user' &&
getDolGlobalInt(
'MULTICOMPANY_TRANSVERSE_MODE')) {
2509 if (!empty($user->admin) && empty($user->entity) &&
$conf->entity == 1) {
2510 $sql .=
" AND te.entity IS NOT NULL";
2512 $sql .=
" AND te.rowid IN (SELECT ug.fk_user FROM ".$this->db->prefix().
"usergroup_user as ug WHERE ug.entity IN (".
getEntity(
'usergroup').
"))";
2515 $sql .=
' AND te.entity IN ('.getEntity($this->element).
')';
2518 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged) && $this->element !=
'societe') {
2519 $tmparray = explode(
'@', $this->ismultientitymanaged);
2520 $sql .=
' AND parenttable.entity IN ('.getEntity($tmparray[1]).
')';
2522 if ($restrictiononfksoc == 1 && $socid && $this->element !=
'societe') {
2523 $sql .=
' AND te.fk_soc = '.((int) $socid);
2525 if ($restrictiononfksoc == 2 && $socid && $this->element !=
'societe') {
2526 $sql .=
' AND (te.fk_soc = '.((int) $socid).
' OR te.fk_soc IS NULL)';
2528 if ($restrictiononfksoc && $socid && $this->element ==
'societe') {
2529 $sql .=
' AND te.rowid = '.((int) $socid);
2534 $result = $this->db->query($sql);
2536 $this->error = $this->db->lasterror();
2539 $row = $this->db->fetch_row($result);
2540 $this->ref_next = $row[0];
2555 $contactAlreadySelected = array();
2560 if ($source ==
'thirdparty') {
2561 $contactAlreadySelected[$i] = $tab[$i][
'socid'];
2563 $contactAlreadySelected[$i] = $tab[$i][
'id'];
2567 return $contactAlreadySelected;
2583 if (!$this->table_element) {
2584 dol_syslog(get_class($this).
"::setProject was called on object with property table_element not defined", LOG_ERR);
2588 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
2590 if (!empty($this->fields[
'fk_project'])) {
2592 $sql .=
" SET fk_project = ".((int) $projectid);
2594 $sql .=
" SET fk_project = NULL";
2596 $sql .=
' WHERE rowid = '.((int) $this->
id);
2597 } elseif ($this->table_element ==
'actioncomm') {
2599 $sql .=
" SET fk_project = ".((int) $projectid);
2601 $sql .=
" SET fk_project = NULL";
2603 $sql .=
' WHERE id = '.((int) $this->
id);
2606 $sql .=
' SET fk_projet = '.((int) $projectid);
2608 $sql .=
' SET fk_projet = NULL';
2610 $sql .=
" WHERE rowid = ".((int) $this->
id);
2615 dol_syslog(get_class($this).
"::setProject", LOG_DEBUG);
2616 if ($this->db->query($sql)) {
2617 $this->fk_project = ((int) $projectid);
2624 if (!$error && !$notrigger) {
2626 $result = $this->
call_trigger(strtoupper($this->element) .
'_MODIFY', $user);
2635 $this->db->rollback();
2638 $this->db->commit();
2656 dol_syslog(get_class($this).
'::setPaymentMethods('.$id.
')');
2658 if ($this->
status >= 0 || $this->element ==
'societe') {
2660 $fieldname =
'fk_mode_reglement';
2661 if ($this->element ==
'societe') {
2662 $fieldname =
'mode_reglement';
2664 if (get_class($this) ==
'Fournisseur') {
2665 $fieldname =
'mode_reglement_supplier';
2667 if (get_class($this) ==
'Tva') {
2668 $fieldname =
'fk_typepayment';
2670 if (get_class($this) ==
'Salary') {
2671 $fieldname =
'fk_typepayment';
2674 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
2675 $sql .=
" SET ".$fieldname.
" = ".(($id > 0 || $id ==
'0') ? ((
int) $id) :
'NULL');
2676 $sql .=
' WHERE rowid='.((int) $this->
id);
2678 if ($this->db->query($sql)) {
2679 $this->mode_reglement_id = $id;
2681 if (get_class($this) ==
'Fournisseur') {
2682 $this->mode_reglement_supplier_id = $id;
2685 if (!$error && !$notrigger) {
2687 if (get_class($this) ==
'Commande') {
2690 $result = $this->
call_trigger(strtoupper(get_class($this)).
'_MODIFY', $user);
2699 dol_syslog(get_class($this).
'::setPaymentMethods Error '.$this->db->error());
2700 $this->error = $this->db->error();
2704 dol_syslog(get_class($this).
'::setPaymentMethods, status of the object is incompatible');
2705 $this->error =
'Status of the object is incompatible '.$this->status;
2718 dol_syslog(get_class($this).
'::setMulticurrencyCode('.$code.
')');
2719 if ($this->
status >= 0 || $this->element ==
'societe') {
2720 $fieldname =
'multicurrency_code';
2722 $sql =
'UPDATE '.$this->db->prefix().$this->table_element;
2723 $sql .=
" SET ".$fieldname.
" = '".$this->db->escape($code).
"'";
2724 $sql .=
' WHERE rowid='.((int) $this->
id);
2726 if ($this->db->query($sql)) {
2727 $this->multicurrency_code = $code;
2731 $this->setMulticurrencyRate($rate, 2);
2736 dol_syslog(get_class($this).
'::setMulticurrencyCode Error '.$sql.
' - '.$this->db->error());
2737 $this->error = $this->db->error();
2741 dol_syslog(get_class($this).
'::setMulticurrencyCode, status of the object is incompatible');
2742 $this->error =
'Status of the object is incompatible '.$this->status;
2754 public function setMulticurrencyRate($rate, $mode = 1)
2756 dol_syslog(get_class($this).
'::setMulticurrencyRate('.$rate.
', '.$mode.
')');
2757 if ($this->
status >= 0 || $this->element ==
'societe') {
2758 $fieldname =
'multicurrency_tx';
2760 $sql =
'UPDATE '.$this->db->prefix().$this->table_element;
2761 $sql .=
" SET ".$fieldname.
" = ".((float) $rate);
2762 $sql .=
' WHERE rowid='.((int) $this->
id);
2764 if ($this->db->query($sql)) {
2765 $this->multicurrency_tx = $rate;
2768 if (!empty($this->lines)) {
2769 foreach ($this->lines as &$line) {
2772 $line->subprice = 0;
2777 $line->multicurrency_subprice = 0;
2780 switch ($this->element) {
2784 '@phan-var-force Propal $this';
2785 '@phan-var-force PropaleLigne $line';
2790 $line->remise_percent,
2792 $line->localtax1_tx,
2793 $line->localtax2_tx,
2794 ($line->description ? $line->description : $line->desc),
2797 $line->special_code,
2798 $line->fk_parent_line,
2799 $line->skip_update_total,
2800 $line->fk_fournprice,
2803 $line->product_type,
2806 $line->array_options,
2808 $line->multicurrency_subprice
2814 '@phan-var-force Commande $this';
2815 '@phan-var-force OrderLine $line';
2818 ($line->description ? $line->description : $line->desc),
2821 $line->remise_percent,
2823 $line->localtax1_tx,
2824 $line->localtax2_tx,
2829 $line->product_type,
2830 $line->fk_parent_line,
2831 $line->skip_update_total,
2832 $line->fk_fournprice,
2835 $line->special_code,
2836 $line->array_options,
2838 $line->multicurrency_subprice
2844 '@phan-var-force Facture $this';
2845 '@phan-var-force FactureLigne $line';
2848 ($line->description ? $line->description : $line->desc),
2851 $line->remise_percent,
2855 $line->localtax1_tx,
2856 $line->localtax2_tx,
2859 $line->product_type,
2860 $line->fk_parent_line,
2861 $line->skip_update_total,
2862 $line->fk_fournprice,
2865 $line->special_code,
2866 $line->array_options,
2867 $line->situation_percent,
2869 $line->multicurrency_subprice
2872 case 'supplier_proposal':
2875 '@phan-var-force SupplierProposal $this';
2876 '@phan-var-force SupplierProposalLine $line';
2881 $line->remise_percent,
2883 $line->localtax1_tx,
2884 $line->localtax2_tx,
2885 ($line->description ? $line->description : $line->desc),
2888 $line->special_code,
2889 $line->fk_parent_line,
2890 $line->skip_update_total,
2891 $line->fk_fournprice,
2894 $line->product_type,
2895 $line->array_options,
2897 $line->multicurrency_subprice
2900 case 'order_supplier':
2903 '@phan-var-force CommandeFournisseur $this';
2904 '@phan-var-force CommandeFournisseurLigne $line';
2907 ($line->description ? $line->description : $line->desc),
2910 $line->remise_percent,
2912 $line->localtax1_tx,
2913 $line->localtax2_tx,
2916 $line->product_type,
2920 $line->array_options,
2922 $line->multicurrency_subprice,
2926 case 'invoice_supplier':
2929 '@phan-var-force FactureFournisseur $this';
2930 '@phan-var-force SupplierInvoiceLIne $line';
2933 ($line->description ? $line->description : $line->desc),
2936 $line->localtax1_tx,
2937 $line->localtax2_tx,
2942 $line->product_type,
2943 $line->remise_percent,
2947 $line->array_options,
2949 $line->multicurrency_subprice,
2954 dol_syslog(get_class($this).
'::setMulticurrencyRate no updateline defined', LOG_DEBUG);
2962 dol_syslog(get_class($this).
'::setMulticurrencyRate Error '.$sql.
' - '.$this->db->error());
2963 $this->error = $this->db->error();
2967 dol_syslog(get_class($this).
'::setMulticurrencyRate, status of the object is incompatible');
2968 $this->error =
'Status of the object is incompatible '.$this->status;
2982 dol_syslog(get_class($this).
'::setPaymentTerms('.$id.
', '.var_export($deposit_percent,
true).
')');
2983 if ($this->
status >= 0 || $this->element ==
'societe') {
2985 $fieldname =
'fk_cond_reglement';
2986 if ($this->element ==
'societe') {
2987 $fieldname =
'cond_reglement';
2989 if (get_class($this) ==
'Fournisseur') {
2990 $fieldname =
'cond_reglement_supplier';
2993 if (empty($deposit_percent) || $deposit_percent < 0) {
2994 $deposit_percent = (float)
getDictionaryValue(
'c_payment_term',
'deposit_percent', $id);
2997 if ($deposit_percent > 100) {
2998 $deposit_percent = 100;
3001 $sql =
'UPDATE '.$this->db->prefix().$this->table_element;
3002 $sql .=
" SET ".$fieldname.
" = ".(($id > 0 || $id ==
'0') ? ((
int) $id) :
'NULL');
3003 if (in_array($this->table_element, array(
'propal',
'commande',
'societe'))) {
3004 $sql .=
" , deposit_percent = " . (empty($deposit_percent) ?
'NULL' :
"'".$this->db->escape($deposit_percent).
"'");
3006 $sql .=
' WHERE rowid='.((int) $this->
id);
3008 if ($this->db->query($sql)) {
3009 $this->cond_reglement_id = $id;
3011 if (get_class($this) ==
'Fournisseur') {
3012 $this->cond_reglement_supplier_id = $id;
3014 $this->cond_reglement = $id;
3015 $this->deposit_percent = $deposit_percent;
3018 dol_syslog(get_class($this).
'::setPaymentTerms Error '.$sql.
' - '.$this->db->error());
3019 $this->error = $this->db->error();
3023 dol_syslog(get_class($this).
'::setPaymentTerms, status of the object is incompatible');
3024 $this->error =
'Status of the object is incompatible '.$this->status;
3037 dol_syslog(get_class($this).
'::setTransportMode('.$id.
')');
3038 if ($this->
status >= 0 || $this->element ==
'societe') {
3039 $fieldname =
'fk_transport_mode';
3040 if ($this->element ==
'societe') {
3041 $fieldname =
'transport_mode';
3043 if (get_class($this) ==
'Fournisseur') {
3044 $fieldname =
'transport_mode_supplier';
3047 $sql =
'UPDATE '.$this->db->prefix().$this->table_element;
3048 $sql .=
" SET ".$fieldname.
" = ".(($id > 0 || $id ==
'0') ? ((
int) $id) :
'NULL');
3049 $sql .=
' WHERE rowid='.((int) $this->
id);
3051 if ($this->db->query($sql)) {
3052 $this->transport_mode_id = $id;
3054 if (get_class($this) ==
'Fournisseur') {
3055 $this->transport_mode_supplier_id = $id;
3059 dol_syslog(get_class($this).
'::setTransportMode Error '.$sql.
' - '.$this->db->error());
3060 $this->error = $this->db->error();
3064 dol_syslog(get_class($this).
'::setTransportMode, status of the object is incompatible');
3065 $this->error =
'Status of the object is incompatible '.$this->status;
3078 dol_syslog(get_class($this).
'::setRetainedWarrantyPaymentTerms('.$id.
')');
3079 if ($this->
status >= 0 || $this->element ==
'societe') {
3080 $fieldname =
'retained_warranty_fk_cond_reglement';
3082 $sql =
'UPDATE '.$this->db->prefix().$this->table_element;
3083 $sql .=
" SET ".$fieldname.
" = ".((int) $id);
3084 $sql .=
' WHERE rowid='.((int) $this->
id);
3086 if ($this->db->query($sql)) {
3087 $this->retained_warranty_fk_cond_reglement = $id;
3090 dol_syslog(get_class($this).
'::setRetainedWarrantyPaymentTerms Error '.$sql.
' - '.$this->db->error());
3091 $this->error = $this->db->error();
3095 dol_syslog(get_class($this).
'::setRetainedWarrantyPaymentTerms, status of the object is incompatible');
3096 $this->error =
'Status of the object is incompatible '.$this->status;
3110 $fieldname =
'fk_delivery_address';
3111 if ($this->element ==
'delivery' || $this->element ==
'shipping') {
3112 $fieldname =
'fk_address';
3115 $sql =
"UPDATE ".$this->db->prefix().$this->table_element.
" SET ".$fieldname.
" = ".((int) $id);
3116 $sql .=
" WHERE rowid = ".((int) $this->
id).
" AND fk_statut = 0";
3118 if ($this->db->query($sql)) {
3119 $this->fk_delivery_address = $id;
3122 $this->error = $this->db->error();
3123 dol_syslog(get_class($this).
'::setDeliveryAddress Error '.$this->error);
3141 if (empty($userused)) {
3147 if (!$this->table_element) {
3148 dol_syslog(get_class($this).
"::setShippingMethod was called on object with property table_element not defined", LOG_ERR);
3154 if ($shipping_method_id < 0) {
3155 $shipping_method_id =
'NULL';
3157 dol_syslog(get_class($this).
'::setShippingMethod('.$shipping_method_id.
')');
3159 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
3160 $sql .=
" SET fk_shipping_method = ".((int) $shipping_method_id);
3161 $sql .=
" WHERE rowid=".((int) $this->
id);
3162 $resql = $this->db->query($sql);
3164 dol_syslog(get_class($this).
'::setShippingMethod Error ', LOG_DEBUG);
3165 $this->error = $this->db->lasterror();
3170 $this->context = array(
'shippingmethodupdate' => 1);
3171 $result = $this->
call_trigger(strtoupper(get_class($this)).
'_MODIFY', $userused);
3179 $this->db->rollback();
3182 $this->shipping_method_id = ($shipping_method_id ==
'NULL') ?
null : $shipping_method_id;
3183 $this->db->commit();
3197 if (!$this->table_element) {
3198 dol_syslog(get_class($this).
"::setWarehouse was called on object with property table_element not defined", LOG_ERR);
3201 if ($warehouse_id < 0) {
3202 $warehouse_id =
'NULL';
3204 dol_syslog(get_class($this).
'::setWarehouse('.$warehouse_id.
')');
3206 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
3207 $sql .=
" SET fk_warehouse = ".((int) $warehouse_id);
3208 $sql .=
" WHERE rowid=".((int) $this->
id);
3210 if ($this->db->query($sql)) {
3211 $this->warehouse_id = ($warehouse_id ==
'NULL') ?
null : $warehouse_id;
3214 dol_syslog(get_class($this).
'::setWarehouse Error ', LOG_DEBUG);
3215 $this->error = $this->db->error();
3230 if (!$this->table_element) {
3231 dol_syslog(get_class($this).
"::setDocModel was called on object with property table_element not defined", LOG_ERR);
3235 $newmodelpdf =
dol_trunc($modelpdf, 255);
3237 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
3238 $sql .=
" SET model_pdf = '".$this->db->escape($newmodelpdf).
"'";
3239 $sql .=
" WHERE rowid = ".((int) $this->
id);
3241 dol_syslog(get_class($this).
"::setDocModel", LOG_DEBUG);
3242 $resql = $this->db->query($sql);
3244 $this->model_pdf = $modelpdf;
3265 if (empty($userused)) {
3271 if (!$this->table_element) {
3272 dol_syslog(get_class($this).
"::setBankAccount was called on object with property table_element not defined", LOG_ERR);
3277 if ($fk_account < 0) {
3278 $fk_account =
'NULL';
3280 dol_syslog(get_class($this).
'::setBankAccount('.$fk_account.
')');
3282 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
3283 $sql .=
" SET fk_account = ".((int) $fk_account);
3284 $sql .=
" WHERE rowid=".((int) $this->
id);
3286 $resql = $this->db->query($sql);
3288 dol_syslog(get_class($this).
'::setBankAccount Error '.$sql.
' - '.$this->db->error());
3289 $this->error = $this->db->lasterror();
3294 $this->context[
'bankaccountupdate'] = 1;
3295 $triggerName = strtoupper(get_class($this)).
'_MODIFY';
3297 if ($triggerName ==
'FACTUREREC_MODIFY') {
3298 $triggerName =
'BILLREC_MODIFY';
3300 $result = $this->
call_trigger($triggerName, $userused);
3308 $this->db->rollback();
3311 $this->fk_account = ($fk_account ==
'NULL') ?
null : $fk_account;
3312 $this->db->commit();
3330 public function line_order($renum =
false, $rowidorder =
'ASC', $fk_parent_line =
true)
3333 if (!$this->table_element_line) {
3334 dol_syslog(get_class($this).
"::line_order was called on object with property table_element_line not defined", LOG_ERR);
3337 if (!$this->fk_element) {
3338 dol_syslog(get_class($this).
"::line_order was called on object with property fk_element not defined", LOG_ERR);
3342 $fieldposition =
'rang';
3343 if (in_array($this->table_element_line, array(
'bom_bomline',
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3344 $fieldposition =
'position';
3349 $sql =
"SELECT count(rowid) FROM ".$this->db->prefix().$this->table_element_line;
3350 $sql .=
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
3352 $sql .=
" AND " . $fieldposition .
" = 0";
3355 $sql .=
" AND " . $fieldposition .
" <> 0";
3358 dol_syslog(get_class($this).
"::line_order", LOG_DEBUG);
3359 $resql = $this->db->query($sql);
3361 $row = $this->db->fetch_row($resql);
3371 $sql =
"SELECT rowid FROM ".$this->db->prefix().$this->table_element_line;
3372 $sql .=
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
3373 if ($fk_parent_line) {
3374 $sql .=
' AND fk_parent_line IS NULL';
3376 $sql .=
" ORDER BY " . $fieldposition .
" ASC, rowid " . $rowidorder;
3378 dol_syslog(get_class($this).
"::line_order search all parent lines", LOG_DEBUG);
3379 $resql = $this->db->query($sql);
3382 $num = $this->db->num_rows($resql);
3385 $row = $this->db->fetch_row($resql);
3388 if (!empty($children)) {
3389 foreach ($children as $child) {
3390 array_push($rows, $child);
3397 if (!empty($rows)) {
3398 foreach ($rows as $key => $row) {
3418 $fieldposition =
'rang';
3419 if (in_array($this->table_element_line, array(
'bom_bomline',
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3420 $fieldposition =
'position';
3425 $sql =
"SELECT rowid FROM ".$this->db->prefix().$this->table_element_line;
3426 $sql .=
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
3427 $sql .=
' AND fk_parent_line = '.((int) $id);
3428 $sql .=
" ORDER BY " . $fieldposition .
" ASC";
3430 dol_syslog(get_class($this).
"::getChildrenOfLine search children lines for line ".$id, LOG_DEBUG);
3432 $resql = $this->db->query($sql);
3434 if ($this->db->num_rows($resql) > 0) {
3435 while ($row = $this->db->fetch_row($resql)) {
3437 if (!empty($includealltree) && $includealltree <= 1000) {
3438 $rows = array_merge($rows, $this->
getChildrenOfLine($row[0], $includealltree + 1));
3454 public function line_up($rowid, $fk_parent_line =
true)
3457 $this->
line_order(
false,
'ASC', $fk_parent_line);
3477 $this->
line_order(
false,
'ASC', $fk_parent_line);
3498 global $hookmanager;
3499 $fieldposition =
'rang';
3500 if (in_array($this->table_element_line, array(
'bom_bomline',
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3501 $fieldposition =
'position';
3504 $sql =
"UPDATE ".$this->db->prefix().$this->table_element_line.
" SET ".$fieldposition.
" = ".((int) $rang);
3505 $sql .=
' WHERE rowid = '.((int) $rowid);
3507 dol_syslog(get_class($this).
"::updateRangOfLine", LOG_DEBUG);
3508 if (!$this->db->query($sql)) {
3512 $parameters = array(
'rowid' => $rowid,
'rang' => $rang,
'fieldposition' => $fieldposition);
3514 $reshook = $hookmanager->executeHooks(
'afterRankOfLineUpdate', $parameters, $this, $action);
3529 $num = count($rows);
3530 for ($i = 0; $i < $num; $i++) {
3545 $fieldposition =
'rang';
3546 if (in_array($this->table_element_line, array(
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3547 $fieldposition =
'position';
3550 $sql =
"UPDATE ".$this->db->prefix().$this->table_element_line.
" SET ".$fieldposition.
" = ".((int) $rang);
3551 $sql .=
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
3552 $sql .=
" AND " . $fieldposition .
" = " . ((int) ($rang - 1));
3553 if ($this->db->query($sql)) {
3554 $sql =
"UPDATE ".$this->db->prefix().$this->table_element_line.
" SET ".$fieldposition.
" = ".((int) ($rang - 1));
3555 $sql .=
' WHERE rowid = '.((int) $rowid);
3556 if (!$this->db->query($sql)) {
3576 $fieldposition =
'rang';
3577 if (in_array($this->table_element_line, array(
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3578 $fieldposition =
'position';
3581 $sql =
"UPDATE ".$this->db->prefix().$this->table_element_line.
" SET ".$fieldposition.
" = ".((int) $rang);
3582 $sql .=
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
3583 $sql .=
" AND " . $fieldposition .
" = " . ((int) ($rang + 1));
3584 if ($this->db->query($sql)) {
3585 $sql =
"UPDATE ".$this->db->prefix().$this->table_element_line.
" SET ".$fieldposition.
" = ".((int) ($rang + 1));
3586 $sql .=
' WHERE rowid = '.((int) $rowid);
3587 if (!$this->db->query($sql)) {
3604 $fieldposition =
'rang';
3605 if (in_array($this->table_element_line, array(
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3606 $fieldposition =
'position';
3609 $sql =
"SELECT " . $fieldposition .
" FROM ".$this->db->prefix().$this->table_element_line;
3610 $sql .=
" WHERE rowid = ".((int) $rowid);
3612 dol_syslog(get_class($this).
"::getRangOfLine", LOG_DEBUG);
3613 $resql = $this->db->query($sql);
3615 $row = $this->db->fetch_row($resql);
3630 $fieldposition =
'rang';
3631 if (in_array($this->table_element_line, array(
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3632 $fieldposition =
'position';
3635 $sql =
"SELECT rowid FROM ".$this->db->prefix().$this->table_element_line;
3636 $sql .=
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
3637 $sql .=
" AND " . $fieldposition .
" = ".((int) $rang);
3638 $resql = $this->db->query($sql);
3640 $row = $this->db->fetch_row($resql);
3657 $positionfield =
'rang';
3658 if (in_array($this->table_element, array(
'bom_bom',
'product_attribute'))) {
3659 $positionfield =
'position';
3663 if ($fk_parent_line) {
3664 $sql =
"SELECT max(".$positionfield.
") FROM ".$this->db->prefix().$this->table_element_line;
3665 $sql .=
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
3666 $sql .=
" AND fk_parent_line = ".((int) $fk_parent_line);
3668 dol_syslog(get_class($this).
"::line_max", LOG_DEBUG);
3669 $resql = $this->db->query($sql);
3671 $row = $this->db->fetch_row($resql);
3672 if (!empty($row[0])) {
3680 $sql =
"SELECT max(".$positionfield.
") FROM ".$this->db->prefix().$this->table_element_line;
3681 $sql .=
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
3683 dol_syslog(get_class($this).
"::line_max", LOG_DEBUG);
3684 $resql = $this->db->query($sql);
3686 $row = $this->db->fetch_row($resql);
3704 if (!$this->table_element) {
3705 dol_syslog(get_class($this).
"::update_ref_ext was called on object with property table_element not defined", LOG_ERR);
3709 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
3710 $sql .=
" SET ref_ext = '".$this->db->escape($ref_ext).
"'";
3712 $sql .=
" WHERE ".(isset($this->table_rowid) ? $this->table_rowid :
'rowid').
" = ".((
int) $this->id);
3714 dol_syslog(get_class($this).
"::update_ref_ext", LOG_DEBUG);
3715 if ($this->db->query($sql)) {
3716 $this->ref_ext = $ref_ext;
3719 $this->error = $this->db->error();
3738 if (!$this->table_element) {
3739 $this->error =
'update_note was called on object with property table_element not defined';
3740 dol_syslog(get_class($this).
"::update_note was called on object with property table_element not defined", LOG_ERR);
3743 if (!in_array($suffix, array(
'',
'_public',
'_private'))) {
3744 $this->error =
'update_note Parameter suffix must be empty, \'_private\' or \'_public\'';
3745 dol_syslog(get_class($this).
"::update_note Parameter suffix must be empty, '_private' or '_public'", LOG_ERR);
3749 $newsuffix = $suffix;
3752 if ($this->table_element ==
'product' && $newsuffix ==
'_private') {
3755 if (in_array($this->table_element, array(
'actioncomm',
'adherent',
'advtargetemailing',
'cronjob',
'establishment'))) {
3756 $fieldusermod =
"fk_user_mod";
3757 } elseif ($this->table_element ==
'ecm_files') {
3758 $fieldusermod =
"fk_user_m";
3760 $fieldusermod =
"fk_user_modif";
3762 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
3763 $sql .=
" SET note".$newsuffix.
" = ".(!empty($note) ? (
"'".$this->db->escape($note).
"'") :
"NULL");
3764 $sql .=
", ".$fieldusermod.
" = ".((int) $user->id);
3765 $sql .=
" WHERE rowid = ".((int) $this->
id);
3767 dol_syslog(get_class($this).
"::update_note", LOG_DEBUG);
3768 if ($this->db->query($sql)) {
3769 if ($suffix ==
'_public') {
3770 $this->note_public = $note;
3771 } elseif ($suffix ==
'_private') {
3772 $this->note_private = $note;
3774 $this->note = $note;
3775 $this->note_private = $note;
3777 if (empty($notrigger)) {
3778 switch ($this->element) {
3780 $trigger_name =
'COMPANY_MODIFY';
3783 $trigger_name =
'ORDER_MODIFY';
3786 $trigger_name =
'BILL_MODIFY';
3788 case 'invoice_supplier':
3789 $trigger_name =
'BILL_SUPPLIER_MODIFY';
3792 $trigger_name =
'BILLREC_MODIFIY';
3794 case 'expensereport':
3795 $trigger_name =
'EXPENSE_REPORT_MODIFY';
3798 $trigger_name = strtoupper($this->element) .
'_MODIFY';
3807 $this->error = $this->db->lasterror();
3838 public function update_price($exclspec = 0, $roundingadjust =
'auto', $nodatabaseupdate = 0, $seller =
null)
3841 global
$conf, $hookmanager, $action;
3843 $parameters = array(
'exclspec' => $exclspec,
'roundingadjust' => $roundingadjust,
'nodatabaseupdate' => $nodatabaseupdate,
'seller' => $seller);
3844 $reshook = $hookmanager->executeHooks(
'updateTotalPrice', $parameters, $this, $action);
3847 } elseif ($reshook < 0) {
3852 $isElementForSupplier =
false;
3853 $roundTotalConstName =
'MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND';
3855 if ($this->element ==
'propal') {
3856 $MODULE =
"MODULE_DISALLOW_UPDATE_PRICE_PROPOSAL";
3857 } elseif ($this->element ==
'commande' || $this->element ==
'order') {
3858 $MODULE =
"MODULE_DISALLOW_UPDATE_PRICE_ORDER";
3859 } elseif ($this->element ==
'facture' || $this->element ==
'invoice') {
3860 $MODULE =
"MODULE_DISALLOW_UPDATE_PRICE_INVOICE";
3861 } elseif ($this->element ==
'facture_fourn' || $this->element ==
'supplier_invoice' || $this->element ==
'invoice_supplier' || $this->element ==
'invoice_supplier_rec') {
3862 $isElementForSupplier =
true;
3863 $MODULE =
"MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_INVOICE";
3864 } elseif ($this->element ==
'order_supplier' || $this->element ==
'supplier_order') {
3865 $isElementForSupplier =
true;
3866 $MODULE =
"MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_ORDER";
3867 } elseif ($this->element ==
'supplier_proposal') {
3868 $isElementForSupplier =
true;
3869 $MODULE =
"MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_PROPOSAL";
3871 if ($isElementForSupplier) {
3872 $roundTotalConstName =
'MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND_SUPPLIER';
3875 if (!empty($MODULE)) {
3878 foreach ($modsactivated as $mod) {
3879 if (isModEnabled($mod)) {
3886 include_once DOL_DOCUMENT_ROOT.
'/core/lib/price.lib.php';
3888 $forcedroundingmode = $roundingadjust;
3889 if ($forcedroundingmode ==
'auto' && isset(
$conf->global->{$roundTotalConstName})) {
3891 } elseif ($forcedroundingmode ==
'auto') {
3892 $forcedroundingmode =
'0';
3897 $multicurrency_tx = !empty($this->multicurrency_tx) ? $this->multicurrency_tx : 1;
3900 $fieldtva =
'total_tva';
3901 $fieldlocaltax1 =
'total_localtax1';
3902 $fieldlocaltax2 =
'total_localtax2';
3903 $fieldup =
'subprice';
3904 $base_price_type =
'HT';
3905 if ($this->element ==
'facture_fourn' || $this->element ==
'invoice_supplier') {
3909 if ($this->element ==
'invoice_supplier_rec') {
3912 if ($this->element ==
'expensereport') {
3916 $forcedroundingmode =
'0';
3917 $fieldup =
'value_unit';
3918 $base_price_type =
'TTC';
3921 $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,";
3922 $sql .=
' tva_tx as vatrate, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type, info_bits, product_type';
3923 if ($this->table_element_line ==
'facturedet') {
3924 $sql .=
', situation_percent';
3926 $sql .=
', multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc';
3927 $sql .=
" FROM ".$this->db->prefix().$this->table_element_line;
3928 $sql .=
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
3930 $product_field =
'product_type';
3931 if ($this->table_element_line ==
'contratdet') {
3932 $product_field =
'';
3934 if ($product_field) {
3935 $sql .=
" AND ".$product_field.
" <> 9";
3938 $sql .=
' ORDER by rowid';
3940 dol_syslog(get_class($this).
"::update_price", LOG_DEBUG);
3942 $resql = $this->db->query($sql);
3944 $this->total_ht = 0;
3945 $this->total_tva = 0;
3946 $this->total_localtax1 = 0;
3947 $this->total_localtax2 = 0;
3948 $this->total_ttc = 0;
3949 $total_ht_by_vats = array();
3950 $total_tva_by_vats = array();
3951 $total_ttc_by_vats = array();
3952 $this->multicurrency_total_ht = 0;
3953 $this->multicurrency_total_tva = 0;
3954 $this->multicurrency_total_ttc = 0;
3958 $num = $this->db->num_rows($resql);
3961 $obj = $this->db->fetch_object($resql);
3964 $parameters = array(
'fk_element' => $obj->rowid);
3965 $reshook = $hookmanager->executeHooks(
'changeRoundingMode', $parameters, $this, $action);
3967 if (empty($reshook) && $forcedroundingmode ==
'0') {
3969 $localtax_array = array($obj->localtax1_type, $obj->localtax1_tx, $obj->localtax2_type, $obj->localtax2_tx);
3970 $tmpcal =
calcul_price_total($obj->qty, $obj->up, $obj->remise_percent, $obj->vatrate, $obj->localtax1_tx, $obj->localtax2_tx, 0, $base_price_type, $obj->info_bits, $obj->product_type, $seller, $localtax_array, (isset($obj->situation_percent) ? $obj->situation_percent : 100), $multicurrency_tx);
3972 $diff_when_using_price_ht =
price2num((
float) $tmpcal[1] - $obj->total_tva,
'MT', 1);
3973 $diff_on_current_total =
price2num($obj->total_ttc - $obj->total_ht - $obj->total_tva - $obj->total_localtax1 - $obj->total_localtax2,
'MT', 1);
3977 if ($diff_on_current_total) {
3979 $sqlfix =
"UPDATE ".$this->db->prefix().$this->table_element_line;
3980 $sqlfix .=
" SET ".$fieldtva.
" = ".
price2num((
float) $tmpcal[1]).
", total_ttc = ".
price2num((
float) $tmpcal[2]);
3981 $sqlfix .=
", multicurrency_total_tva = ".price2num((
float) $tmpcal[17]).
", multicurrency_total_ttc = ".
price2num((
float) $tmpcal[18]);
3982 $sqlfix .=
" WHERE rowid = ".((int) $obj->rowid);
3983 dol_syslog(
'Warn1: We found inconsistent 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);
3984 $resqlfix = $this->db->query($sqlfix);
3988 $obj->total_tva = $tmpcal[1];
3989 $obj->total_ttc = $tmpcal[2];
3990 $obj->multicurrency_total_tva = $tmpcal[17];
3991 $obj->multicurrency_total_ttc = $tmpcal[18];
3992 } elseif ($diff_when_using_price_ht) {
3995 if ((
float) $tmpcal[0] == (
float) $obj->total_ht) {
4000 $sqlfix =
"UPDATE ".$this->db->prefix().$this->table_element_line;
4001 $sqlfix .=
" SET ".$fieldtva.
" = ".
price2num((
float) $tmpcal[1]).
", total_ttc = ".
price2num((
float) $tmpcal[2]);
4002 $sqlfix .=
", multicurrency_total_tva = ".price2num((
float) $tmpcal[17]).
", multicurrency_total_ttc = ".
price2num((
float) $tmpcal[18]);
4003 $sqlfix .=
" WHERE rowid = ".((int) $obj->rowid);
4004 dol_syslog(
'Warn2: 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);
4005 $resqlfix = $this->db->query($sqlfix);
4009 $obj->total_tva = $tmpcal[1];
4010 $obj->total_ttc = $tmpcal[2];
4011 $obj->multicurrency_total_tva = $tmpcal[17];
4012 $obj->multicurrency_total_ttc = $tmpcal[18];
4017 $this->total_ht += $obj->total_ht;
4018 $this->total_tva += $obj->total_tva;
4019 $this->total_localtax1 += $obj->total_localtax1;
4020 $this->total_localtax2 += $obj->total_localtax2;
4021 $this->total_ttc += $obj->total_ttc;
4022 $this->multicurrency_total_ht += $obj->multicurrency_total_ht;
4023 $this->multicurrency_total_tva += $obj->multicurrency_total_tva;
4024 $this->multicurrency_total_ttc += $obj->multicurrency_total_ttc;
4026 if (!isset($total_ht_by_vats[$obj->vatrate])) {
4027 $total_ht_by_vats[$obj->vatrate] = 0;
4029 if (!isset($total_tva_by_vats[$obj->vatrate])) {
4030 $total_tva_by_vats[$obj->vatrate] = 0;
4032 if (!isset($total_ttc_by_vats[$obj->vatrate])) {
4033 $total_ttc_by_vats[$obj->vatrate] = 0;
4035 $total_ht_by_vats[$obj->vatrate] += $obj->total_ht;
4036 $total_tva_by_vats[$obj->vatrate] += $obj->total_tva;
4037 $total_ttc_by_vats[$obj->vatrate] += $obj->total_ttc;
4039 if ($forcedroundingmode ==
'1') {
4040 if ($base_price_type ==
'TTC') {
4041 $tmpvat =
price2num($total_ttc_by_vats[$obj->vatrate] * $obj->vatrate / (100 + $obj->vatrate),
'MT', 1);
4043 $tmpvat =
price2num($total_ht_by_vats[$obj->vatrate] * $obj->vatrate / 100,
'MT', 1);
4045 $diff =
price2num($total_tva_by_vats[$obj->vatrate] - (
float) $tmpvat,
'MT', 1);
4048 $maxdiff = (10 * pow(10, -1 *
getDolGlobalInt(
'MAIN_MAX_DECIMALS_TOT', 0)));
4049 if (abs((
float) $diff) > $maxdiff) {
4051 $errmsg =
'We found a rounding difference after line '.($obj->rowid).
' between HT*VAT='.$tmpvat.
' and total in database='.$total_tva_by_vats[$obj->vatrate].
' (calculated with UP*qty) but diff='.$diff.
' is too high (> '.$maxdiff.
') to be corrected. Some data in your lines may be corrupted. Try to edit each line manually to fix this before restarting.';
4053 $this->error = $errmsg;
4058 if ($base_price_type ==
'TTC') {
4059 $sqlfix =
"UPDATE ".$this->db->prefix().$this->table_element_line.
" SET ".$fieldtva.
" = ".
price2num($obj->total_tva - (
float) $diff).
", total_ht = ".
price2num($obj->total_ht + (
float) $diff).
" WHERE rowid = ".((int) $obj->rowid);
4060 dol_syslog(
'We found a difference of '.$diff.
' for line rowid = '.$obj->rowid.
' between TotalHT('.$total_ht_by_vats[$obj->vatrate].
')*VATrate('.$obj->vatrate.
')='.$tmpvat.
' and total in database='.$total_tva_by_vats[$obj->vatrate].
" (calculated with UP*qty). We fix the total_vat and total_ht of line by running sqlfix = ".$sqlfix);
4062 $sqlfix =
"UPDATE ".$this->db->prefix().$this->table_element_line.
" SET ".$fieldtva.
" = ".
price2num($obj->total_tva - (
float) $diff).
", total_ttc = ".
price2num($obj->total_ttc - (
float) $diff).
" WHERE rowid = ".((int) $obj->rowid);
4063 dol_syslog(
'We found a difference of '.$diff.
' for line rowid = '.$obj->rowid.
' between TotalHT('.$total_ht_by_vats[$obj->vatrate].
')*VATrate('.$obj->vatrate.
')='.$tmpvat.
' and total in database='.$total_tva_by_vats[$obj->vatrate].
" (calculated with UP*qty). We fix the total_vat and total_ttc of line by running sqlfix = ".$sqlfix);
4066 $resqlfix = $this->db->query($sqlfix);
4072 $this->total_tva = (float)
price2num($this->total_tva - (
float) $diff,
'', 1);
4073 $total_tva_by_vats[$obj->vatrate] = (float)
price2num($total_tva_by_vats[$obj->vatrate] - (
float) $diff,
'', 1);
4074 if ($base_price_type ==
'TTC') {
4075 $this->total_ht = (float)
price2num($this->total_ht + (
float) $diff,
'', 1);
4076 $total_ht_by_vats[$obj->vatrate] = (float)
price2num($total_ht_by_vats[$obj->vatrate] + (
float) $diff,
'', 1);
4078 $this->total_ttc = (float)
price2num($this->total_ttc - (
float) $diff,
'', 1);
4079 $total_ttc_by_vats[$obj->vatrate] = (float)
price2num($total_ttc_by_vats[$obj->vatrate] - (
float) $diff,
'', 1);
4089 $this->total_ttc += isset($this->revenuestamp) ? $this->revenuestamp : 0;
4091 $this->multicurrency_total_ttc += isset($this->revenuestamp) ? ($this->revenuestamp * $multicurrency_tx) : 0;
4094 if (!empty($this->situation_cycle_ref) && !empty($this->situation_counter) && $this->situation_counter > 1 && method_exists($this,
'get_prev_sits')) {
4095 '@phan-var-force Facture $this';
4096 include_once DOL_DOCUMENT_ROOT.
'/compta/facture/class/facture.class.php';
4099 $prev_sits = $this->get_prev_sits();
4101 foreach ($prev_sits as $sit) {
4102 $this->total_ht -= $sit->total_ht;
4103 $this->total_tva -= $sit->total_tva;
4104 $this->total_localtax1 -= $sit->total_localtax1;
4105 $this->total_localtax2 -= $sit->total_localtax2;
4106 $this->total_ttc -= $sit->total_ttc;
4107 $this->multicurrency_total_ht -= $sit->multicurrency_total_ht;
4108 $this->multicurrency_total_tva -= $sit->multicurrency_total_tva;
4109 $this->multicurrency_total_ttc -= $sit->multicurrency_total_ttc;
4116 $this->total_ht = (float)
price2num($this->total_ht);
4117 $this->total_tva = (float)
price2num($this->total_tva);
4118 $this->total_localtax1 = (float)
price2num($this->total_localtax1);
4119 $this->total_localtax2 = (float)
price2num($this->total_localtax2);
4120 $this->total_ttc = (float)
price2num($this->total_ttc);
4122 $this->db->free($resql);
4125 $fieldht =
'total_ht';
4127 $fieldlocaltax1 =
'localtax1';
4128 $fieldlocaltax2 =
'localtax2';
4129 $fieldttc =
'total_ttc';
4131 if (in_array($this->element, array(
'propal',
'commande',
'facture',
'facturerec',
'supplier_proposal',
'order_supplier',
'facture_fourn',
'invoice_supplier',
'invoice_supplier_rec',
'expensereport'))) {
4132 $fieldtva =
'total_tva';
4135 if (!$error && empty($nodatabaseupdate)) {
4136 $sql =
"UPDATE ".$this->db->prefix().$this->table_element.
' SET';
4137 $sql .=
" ".$this->db->sanitize($fieldht).
" = ".((float)
price2num($this->total_ht,
'MT', 1)).
",";
4138 $sql .=
" ".$this->db->sanitize($fieldtva).
" = ".((float)
price2num($this->total_tva,
'MT', 1)).
",";
4139 $sql .=
" ".$this->db->sanitize($fieldlocaltax1).
" = ".((float)
price2num($this->total_localtax1,
'MT', 1)).
",";
4140 $sql .=
" ".$this->db->sanitize($fieldlocaltax2).
" = ".((float)
price2num($this->total_localtax2,
'MT', 1)).
",";
4141 $sql .=
" ".$this->db->sanitize($fieldttc).
" = ".((float)
price2num($this->total_ttc,
'MT', 1));
4142 $sql .=
", multicurrency_total_ht = ".((float)
price2num($this->multicurrency_total_ht,
'MT', 1));
4143 $sql .=
", multicurrency_total_tva = ".((float)
price2num($this->multicurrency_total_tva,
'MT', 1));
4144 $sql .=
", multicurrency_total_ttc = ".((float)
price2num($this->multicurrency_total_ttc,
'MT', 1));
4145 $sql .=
" WHERE rowid = ".((int) $this->
id);
4147 dol_syslog(get_class($this).
"::update_price", LOG_DEBUG);
4148 $resql = $this->db->query($sql);
4152 $this->error = $this->db->lasterror();
4153 $this->errors[] = $this->db->lasterror();
4158 $this->db->commit();
4161 $this->db->rollback();
4181 public function add_object_linked($origin =
null, $origin_id =
null, $f_user =
null, $notrigger = 0)
4184 global $user, $hookmanager, $action;
4185 $origin = (!empty($origin) ? $origin : $this->origin);
4186 $origin_id = (!empty($origin_id) ? $origin_id : $this->origin_id);
4187 $f_user = isset($f_user) ? $f_user : $user;
4190 if ($origin ==
'order') {
4191 $origin =
'commande';
4193 if ($origin ==
'invoice') {
4194 $origin =
'facture';
4196 if ($origin ==
'invoice_template') {
4197 $origin =
'facturerec';
4199 if ($origin ==
'supplierorder') {
4200 $origin =
'order_supplier';
4204 $targettype = $this->getElementType();
4206 $parameters = array(
'targettype' => $targettype);
4208 $reshook = $hookmanager->executeHooks(
'setLinkedObjectSourceTargetType', $parameters, $this, $action);
4210 if (!empty($hookmanager->resArray[
'targettype'])) {
4211 $targettype = $hookmanager->resArray[
'targettype'];
4218 $sql =
"INSERT INTO " . $this->db->prefix() .
"element_element (";
4219 $sql .=
"fk_source";
4220 $sql .=
", sourcetype";
4221 $sql .=
", fk_target";
4222 $sql .=
", targettype";
4223 $sql .=
") VALUES (";
4224 $sql .= ((int) $origin_id);
4225 $sql .=
", '" . $this->db->escape($origin) .
"'";
4226 $sql .=
", " . ((int) $this->
id);
4227 $sql .=
", '" . $this->db->escape($targettype) .
"'";
4230 dol_syslog(get_class($this) .
"::add_object_linked", LOG_DEBUG);
4231 if ($this->db->query($sql)) {
4234 $this->context[
'link_origin'] = $origin;
4235 $this->context[
'link_origin_id'] = $origin_id;
4236 $result = $this->call_trigger(
'OBJECT_LINK_INSERT', $f_user);
4243 $this->error = $this->db->lasterror();
4248 $this->db->commit();
4251 $this->db->rollback();
4265 $coreModule = array(
'knowledgemanagement',
'partnership',
'workstation',
'ticket',
'recruitment',
'eventorganization',
'asset');
4267 return ((!empty($this->module) && !in_array($this->module, $coreModule)) ? $this->module.
'_' :
'').$this->element;
4293 public function fetchObjectLinked($sourceid =
null, $sourcetype =
'', $targetid =
null, $targettype =
'', $clause =
'OR', $alsosametype = 1, $orderby =
'sourcetype', $loadalsoobjects = 1)
4295 global $hookmanager, $action;
4300 if ($this->
id > 0 && !empty($this->linkedObjectsFullLoaded[$this->
id])) {
4304 $this->linkedObjectsIds = array();
4305 $this->linkedObjects = array();
4307 $justsource =
false;
4308 $justtarget =
false;
4309 $withtargettype =
false;
4310 $withsourcetype =
false;
4312 $parameters = array(
'sourcetype' => $sourcetype,
'sourceid' => $sourceid,
'targettype' => $targettype,
'targetid' => $targetid);
4314 $reshook = $hookmanager->executeHooks(
'setLinkedObjectSourceTargetType', $parameters, $this, $action);
4316 if (!empty($hookmanager->resArray[
'sourcetype'])) {
4317 $sourcetype = $hookmanager->resArray[
'sourcetype'];
4319 if (!empty($hookmanager->resArray[
'sourceid'])) {
4320 $sourceid = $hookmanager->resArray[
'sourceid'];
4322 if (!empty($hookmanager->resArray[
'targettype'])) {
4323 $targettype = $hookmanager->resArray[
'targettype'];
4325 if (!empty($hookmanager->resArray[
'targetid'])) {
4326 $targetid = $hookmanager->resArray[
'targetid'];
4330 if (!empty($sourceid) && !empty($sourcetype) && empty($targetid)) {
4332 if (!empty($targettype)) {
4333 $withtargettype =
true;
4336 if (!empty($targetid) && !empty($targettype) && empty($sourceid)) {
4338 if (!empty($sourcetype)) {
4339 $withsourcetype =
true;
4343 $sourceid = (!empty($sourceid) ? $sourceid :
$this->id);
4344 $targetid = (!empty($targetid) ? $targetid :
$this->id);
4345 $sourcetype = (!empty($sourcetype) ? $sourcetype : $this->getElementType());
4346 $targettype = (!empty($targettype) ? $targettype : $this->getElementType());
4355 $sql =
"SELECT rowid, fk_source, sourcetype, fk_target, targettype";
4356 $sql .=
" FROM ".$this->db->prefix().
"element_element";
4358 if ($justsource || $justtarget) {
4360 $sql .=
"fk_source = ".((int) $sourceid).
" AND sourcetype = '".$this->db->escape($sourcetype).
"'";
4361 if ($withtargettype) {
4362 $sql .=
" AND targettype = '".$this->db->escape($targettype).
"'";
4364 } elseif ($justtarget) {
4365 $sql .=
"fk_target = ".((int) $targetid).
" AND targettype = '".$this->db->escape($targettype).
"'";
4366 if ($withsourcetype) {
4367 $sql .=
" AND sourcetype = '".$this->db->escape($sourcetype).
"'";
4371 $sql .=
"(fk_source = ".((int) $sourceid).
" AND sourcetype = '".$this->db->escape($sourcetype).
"')";
4372 $sql .=
" ".$clause.
" (fk_target = ".((int) $targetid).
" AND targettype = '".$this->db->escape($targettype).
"')";
4373 if ($loadalsoobjects && $this->
id > 0 && $sourceid == $this->
id && $sourcetype == $this->element && $targetid == $this->
id && $targettype == $this->element && $clause ==
'OR') {
4374 $this->linkedObjectsFullLoaded[
$this->id] =
true;
4377 $sql .=
" ORDER BY ".$orderby;
4379 dol_syslog(get_class($this).
"::fetchObjectLink", LOG_DEBUG);
4380 $resql = $this->db->query($sql);
4382 $num = $this->db->num_rows($resql);
4385 $obj = $this->db->fetch_object($resql);
4386 if ($justsource || $justtarget) {
4388 $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
4389 } elseif ($justtarget) {
4390 $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
4393 if ($obj->fk_source == $sourceid && $obj->sourcetype == $sourcetype) {
4394 $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
4396 if ($obj->fk_target == $targetid && $obj->targettype == $targettype) {
4397 $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
4403 if (!empty($this->linkedObjectsIds)) {
4404 $tmparray = $this->linkedObjectsIds;
4405 foreach ($tmparray as $objecttype => $objectids) {
4407 $element = $element_properties[
'element'];
4408 $classPath = $element_properties[
'classpath'];
4409 $classFile = $element_properties[
'classfile'];
4410 $className = $element_properties[
'classname'];
4411 $module = $element_properties[
'module'];
4414 if (isModEnabled($module) && (($element != $this->element) || $alsosametype)) {
4415 if ($loadalsoobjects && (is_numeric($loadalsoobjects) || ($loadalsoobjects === $objecttype))) {
4417 if (class_exists($className)) {
4418 foreach ($objectids as $i => $objectid) {
4419 $object =
new $className($this->db);
4420 '@phan-var-force CommonObject $object';
4421 $ret =
$object->fetch($objectid);
4423 $this->linkedObjects[$objecttype][$i] =
$object;
4429 unset($this->linkedObjectsIds[$objecttype]);
4448 if ($this->
id > 0 && !empty($this->linkedObjectsFullLoaded[$this->
id])) {
4449 unset($this->linkedObjectsFullLoaded[$this->
id]);
4467 public function updateObjectLinked($sourceid =
null, $sourcetype =
'', $targetid =
null, $targettype =
'', $f_user =
null, $notrigger = 0)
4470 $updatesource =
false;
4471 $updatetarget =
false;
4472 $f_user = isset($f_user) ? $f_user : $user;
4474 if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) {
4475 $updatesource =
true;
4476 } elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) {
4477 $updatetarget =
true;
4483 $sql =
"UPDATE " . $this->db->prefix() .
"element_element SET ";
4484 if ($updatesource) {
4485 $sql .=
"fk_source = " . ((int) $sourceid);
4486 $sql .=
", sourcetype = '" . $this->db->escape($sourcetype) .
"'";
4487 $sql .=
" WHERE fk_target = " . ((int) $this->
id);
4488 $sql .=
" AND targettype = '" . $this->db->escape($this->element) .
"'";
4489 } elseif ($updatetarget) {
4490 $sql .=
"fk_target = " . ((int) $targetid);
4491 $sql .=
", targettype = '" . $this->db->escape($targettype) .
"'";
4492 $sql .=
" WHERE fk_source = " . ((int) $this->
id);
4493 $sql .=
" AND sourcetype = '" . $this->db->escape($this->element) .
"'";
4496 dol_syslog(get_class($this) .
"::updateObjectLinked", LOG_DEBUG);
4497 if ($this->db->query($sql)) {
4500 $this->context[
'link_source_id'] = $sourceid;
4501 $this->context[
'link_source_type'] = $sourcetype;
4502 $this->context[
'link_target_id'] = $targetid;
4503 $this->context[
'link_target_type'] = $targettype;
4504 $result = $this->call_trigger(
'OBJECT_LINK_MODIFY', $f_user);
4511 $this->error = $this->db->lasterror();
4516 $this->db->commit();
4519 $this->db->rollback();
4537 public function deleteObjectLinked($sourceid =
null, $sourcetype =
'', $targetid =
null, $targettype =
'', $rowid = 0, $f_user =
null, $notrigger = 0)
4540 $deletesource =
false;
4541 $deletetarget =
false;
4542 $f_user = isset($f_user) ? $f_user : $user;
4544 if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) {
4545 $deletesource =
true;
4546 } elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) {
4547 $deletetarget =
true;
4550 $sourceid = (!empty($sourceid) ? $sourceid :
$this->id);
4551 $sourcetype = (!empty($sourcetype) ? $sourcetype : $this->element);
4552 $targetid = (!empty($targetid) ? $targetid :
$this->id);
4553 $targettype = (!empty($targettype) ? $targettype : $this->element);
4559 $this->context[
'link_id'] = $rowid;
4560 $this->context[
'link_source_id'] = $sourceid;
4561 $this->context[
'link_source_type'] = $sourcetype;
4562 $this->context[
'link_target_id'] = $targetid;
4563 $this->context[
'link_target_type'] = $targettype;
4564 $result = $this->call_trigger(
'OBJECT_LINK_DELETE', $f_user);
4572 $sql =
"DELETE FROM " . $this->db->prefix() .
"element_element";
4575 $sql .=
" rowid = " . ((int) $rowid);
4577 if ($deletesource) {
4578 $sql .=
" fk_source = " . ((int) $sourceid) .
" AND sourcetype = '" . $this->db->escape($sourcetype) .
"'";
4579 $sql .=
" AND fk_target = " . ((int) $this->
id) .
" AND targettype = '" . $this->db->escape($this->element) .
"'";
4580 } elseif ($deletetarget) {
4581 $sql .=
" fk_target = " . ((int) $targetid) .
" AND targettype = '" . $this->db->escape($targettype) .
"'";
4582 $sql .=
" AND fk_source = " . ((int) $this->
id) .
" AND sourcetype = '" . $this->db->escape($this->element) .
"'";
4584 $sql .=
" (fk_source = " . ((int) $this->
id) .
" AND sourcetype = '" . $this->db->escape($this->element) .
"')";
4586 $sql .=
" (fk_target = " . ((int) $this->
id) .
" AND targettype = '" . $this->db->escape($this->element) .
"')";
4590 dol_syslog(get_class($this) .
"::deleteObjectLinked", LOG_DEBUG);
4591 if (!$this->db->query($sql)) {
4592 $this->error = $this->db->lasterror();
4593 $this->errors[] = $this->error;
4599 $this->db->commit();
4602 $this->db->rollback();
4618 if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
4621 if (!preg_match(
'/^[_a-zA-Z0-9]+$/', $field_select)) {
4622 dol_syslog(
'Invalid value $field_select for parameter '.$field_select.
' in call to getAllItemsLinkedByObjectID(). Must be a single field name.', LOG_ERR);
4627 $sql =
"SELECT ".$field_select.
" FROM ".$db->prefix().$table_element.
" WHERE ".$field_where.
" = ".((int) $fk_object_where);
4628 $resql = $db->query($sql);
4631 if (!empty($resql)) {
4632 while ($res = $db->fetch_object($resql)) {
4633 $TRes[] = $res->{$field_select};
4650 if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
4656 $sql =
"SELECT COUNT(*) as nb FROM ".$db->prefix().$table_element.
" WHERE ".$field_where.
" = ".((int) $fk_object_where);
4657 $resql = $db->query($sql);
4660 $res = $db->fetch_object($resql);
4679 if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
4685 $sql =
"DELETE FROM ".$db->prefix().$table_element.
" WHERE ".$field_where.
" = ".((int) $fk_object_where);
4686 $resql = $db->query($sql);
4688 if (empty($resql)) {
4705 public function setStatut($status, $elementId =
null, $elementType =
'', $trigkey =
'', $fieldstatus =
'fk_statut')
4709 $savElementId = $elementId;
4711 $elementId = (!empty($elementId) ? $elementId :
$this->id);
4712 $elementTable = (!empty($elementType) ? $elementType : $this->table_element);
4716 if ($elementTable ==
'facture_rec') {
4717 $fieldstatus =
"suspended";
4719 if ($elementTable ==
'mailing') {
4720 $fieldstatus =
"statut";
4722 if ($elementTable ==
'cronjob') {
4723 $fieldstatus =
"status";
4725 if ($elementTable ==
'user') {
4726 $fieldstatus =
"statut";
4728 if ($elementTable ==
'expensereport') {
4729 $fieldstatus =
"fk_statut";
4731 if ($elementTable ==
'receptiondet_batch') {
4732 $fieldstatus =
"status";
4734 if ($elementTable ==
'prelevement_bons') {
4735 $fieldstatus =
"statut";
4737 if (isset($this->fields) && is_array($this->fields) && array_key_exists(
'status', $this->fields)) {
4738 $fieldstatus =
'status';
4741 $sql =
"UPDATE ".$this->db->prefix().$this->db->sanitize($elementTable);
4742 $sql .=
" SET ".$this->db->sanitize($fieldstatus).
" = ".((int) $status);
4745 if ($status == 1 && in_array($elementTable, array(
'expensereport',
'inventory'))) {
4746 $sql .=
", fk_user_valid = ".((int) $user->id);
4748 if ($status == 1 && in_array($elementTable, array(
'expensereport'))) {
4749 $sql .=
", date_valid = '".$this->db->idate(
dol_now()).
"'";
4751 if ($status == 1 && in_array($elementTable, array(
'inventory'))) {
4752 $sql .=
", date_validation = '".$this->db->idate(
dol_now()).
"'";
4754 $sql .=
" WHERE rowid = ".((int) $elementId);
4755 $sql .=
" AND ".$fieldstatus.
" <> ".((int) $status);
4757 dol_syslog(get_class($this).
"::setStatut", LOG_DEBUG);
4758 $resql = $this->db->query($sql);
4762 $nb_rows_affected = $this->db->affected_rows($resql);
4764 if ($nb_rows_affected > 0) {
4765 if (empty($trigkey)) {
4767 if ($this->element ==
'supplier_proposal' && $status == 2) {
4768 $trigkey =
'SUPPLIER_PROPOSAL_SIGN';
4770 if ($this->element ==
'supplier_proposal' && $status == 3) {
4771 $trigkey =
'SUPPLIER_PROPOSAL_REFUSE';
4773 if ($this->element ==
'supplier_proposal' && $status == 4) {
4774 $trigkey =
'SUPPLIER_PROPOSAL_CLOSE';
4776 if ($this->element ==
'fichinter' && $status == 3) {
4777 $trigkey =
'FICHINTER_CLASSIFY_DONE';
4779 if ($this->element ==
'fichinter' && $status == 2) {
4780 $trigkey =
'FICHINTER_CLASSIFY_BILLED';
4782 if ($this->element ==
'fichinter' && $status == 1) {
4783 $trigkey =
'FICHINTER_CLASSIFY_UNBILLED';
4787 $this->context = array_merge($this->context, array(
'newstatus' => $status));
4791 $result = $this->call_trigger($trigkey, $user);
4802 $this->db->commit();
4804 if (empty($savElementId)) {
4806 if ($fieldstatus ==
'tosell') {
4808 } elseif ($fieldstatus ==
'tobuy') {
4809 $this->status_buy = $status;
4817 $this->db->rollback();
4818 dol_syslog(get_class($this).
"::setStatut ".$this->error, LOG_ERR);
4822 $this->error = $this->db->lasterror();
4823 $this->db->rollback();
4840 if (empty(
$id) && empty($ref)) {
4850 $sql =
"SELECT rowid, canvas";
4851 $sql .=
" FROM ".$this->db->prefix().$this->table_element;
4852 $sql .=
" WHERE entity IN (".getEntity($this->element).
")";
4854 $sql .=
" AND rowid = ".((int)
$id);
4857 $sql .=
" AND ref = '".$this->db->escape($ref).
"'";
4860 $resql = $this->db->query($sql);
4862 $obj = $this->db->fetch_object($resql);
4864 $this->canvas = $obj->canvas;
4884 $sql =
"SELECT special_code FROM ".$this->db->prefix().$this->table_element_line;
4885 $sql .=
" WHERE rowid = ".((int) $lineid);
4886 $resql = $this->db->query($sql);
4888 $row = $this->db->fetch_row($resql);
4889 return (!empty($row[0]) ? $row[0] : 0);
4912 if (!isset($this->childtables) || !is_array($this->childtables) || count($this->childtables) == 0) {
4913 dol_print_error(
null,
'Called isObjectUsed on a class with property this->childtables not defined');
4917 $arraytoscan = $this->childtables;
4919 $tmparray = array_keys($this->childtables);
4920 if (is_numeric($tmparray[0])) {
4921 $arraytoscan = array_flip($this->childtables);
4926 foreach ($arraytoscan as $table => $element) {
4930 if (isset($element[
'enabled']) && !empty($element[
'enabled'])) {
4931 $enabled = (int)
dol_eval($element[
'enabled'], 1);
4932 if (empty($enabled)) {
4938 $sql =
"SELECT COUNT(*) as nb";
4939 $sql .=
" FROM ".$this->db->prefix().$table.
" as c";
4940 if (!empty($element[
'parent']) && !empty($element[
'parentkey'])) {
4941 $sql .=
", ".$this->db->prefix().$element[
'parent'].
" as p";
4943 if (!empty($element[
'fk_element'])) {
4944 $sql .=
" WHERE c.".$element[
'fk_element'].
" = ".((int)
$id);
4946 $sql .=
" WHERE c.".$this->fk_element.
" = ".((int)
$id);
4948 if (!empty($element[
'parent']) && !empty($element[
'parentkey'])) {
4949 $sql .=
" AND c.".$element[
'parentkey'].
" = p.rowid";
4951 if (!empty($element[
'parent']) && !empty($element[
'parenttypefield']) && !empty($element[
'parenttypevalue'])) {
4952 $sql .=
" AND c.".$element[
'parenttypefield'].
" = '".$this->db->escape($element[
'parenttypevalue']).
"'";
4954 if (!empty($entity)) {
4955 if (!empty($element[
'parent']) && !empty($element[
'parentkey'])) {
4956 $sql .=
" AND p.entity = ".((int) $entity);
4958 $sql .=
" AND c.entity = ".((int) $entity);
4962 $resql = $this->db->query($sql);
4964 $obj = $this->db->fetch_object($resql);
4966 $langs->load(
"errors");
4968 $haschild += $obj->nb;
4969 if (is_numeric($element)) {
4970 $this->errors[] = $langs->transnoentitiesnoconv(
"ErrorRecordHasAtLeastOneChildOfType", method_exists($this,
'getNomUrl') ? $this->getNomUrl() : $this->ref, $table);
4971 } elseif (is_string($element)) {
4972 $this->errors[] = $langs->transnoentitiesnoconv(
"ErrorRecordHasAtLeastOneChildOfType", method_exists($this,
'getNomUrl') ? $this->getNomUrl() : $this->ref, $langs->transnoentitiesnoconv($element));
4974 $this->errors[] = $langs->transnoentitiesnoconv(
"ErrorRecordHasAtLeastOneChildOfType", method_exists($this,
'getNomUrl') ? $this->getNomUrl() : $this->ref, $langs->transnoentitiesnoconv($element[
'name']));
4979 $this->errors[] = $this->db->lasterror();
4983 if ($haschild > 0) {
4984 $this->errors[] =
"ErrorRecordHasChildren";
5001 foreach ($this->lines as $key => $val) {
5003 if ($predefined == -1) {
5006 if ($predefined == 1 && $val->fk_product > 0) {
5009 if ($predefined == 0 && $val->fk_product <= 0) {
5012 if ($predefined == 2 && $val->fk_product > 0 && $val->product_type == 0) {
5015 if ($predefined == 3 && $val->fk_product > 0 && $val->product_type == 1) {
5022 dol_syslog(get_class($this).
'::hasProductsOrServices we found '.$nb.
' qualified lines of products/servcies');
5033 if (!empty($this->table_element_line) && ($this->table_element_line !=
'expeditiondet')) {
5034 $total_discount = 0.00;
5036 $sql =
"SELECT subprice as pu_ht, qty, remise_percent, total_ht";
5037 $sql .=
" FROM ".$this->db->prefix().$this->table_element_line;
5038 $sql .=
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
5040 dol_syslog(get_class($this).
'::getTotalDiscount', LOG_DEBUG);
5041 $resql = $this->db->query($sql);
5043 $num = $this->db->num_rows($resql);
5046 $obj = $this->db->fetch_object($resql);
5048 $pu_ht = $obj->pu_ht;
5050 $total_ht = $obj->total_ht;
5052 $total_discount_line = (float)
price2num(($pu_ht * $qty) - $total_ht,
'MT');
5053 $total_discount += $total_discount_line;
5060 return (
float)
price2num($total_discount);
5082 if (empty($this->lines)) {
5083 return array(
'weight' => $totalWeight,
'volume' => $totalVolume,
'ordered' => $totalOrdered,
'toship' => $totalToShip);
5086 foreach ($this->lines as $line) {
5087 if (isset($line->qty_asked)) {
5088 $totalOrdered += $line->qty_asked;
5090 if (isset($line->qty_shipped)) {
5091 $totalToShip += $line->qty_shipped;
5092 } elseif ($line->element ==
'commandefournisseurdispatch' && isset($line->qty)) {
5093 if (empty($totalToShip)) {
5096 $totalToShip += $line->qty;
5100 if ($this->element ==
'shipping') {
5102 $qty = $line->qty_shipped ? $line->qty_shipped : 0;
5104 $qty = $line->qty ? $line->qty : 0;
5107 $weight = !empty($line->weight) ? $line->weight : 0;
5108 ($weight == 0 && !empty($line->product->weight)) ? $weight = $line->product->weight : 0;
5109 $volume = !empty($line->volume) ? $line->volume : 0;
5110 ($volume == 0 && !empty($line->product->volume)) ? $volume = $line->product->volume : 0;
5112 $weight_units = !empty($line->weight_units) ? $line->weight_units : 0;
5113 ($weight_units == 0 && !empty($line->product->weight_units)) ? $weight_units = $line->product->weight_units : 0;
5114 $volume_units = !empty($line->volume_units) ? $line->volume_units : 0;
5115 ($volume_units == 0 && !empty($line->product->volume_units)) ? $volume_units = $line->product->volume_units : 0;
5119 if (!empty($weight_units)) {
5120 $weightUnit = $weight_units;
5122 if (!empty($volume_units)) {
5123 $volumeUnit = $volume_units;
5126 if (empty($totalWeight)) {
5129 if (empty($totalVolume)) {
5134 if ($weight_units < 50) {
5135 $trueWeightUnit = pow(10, $weightUnit);
5136 $totalWeight += $weight * $qty * $trueWeightUnit;
5138 if ($weight_units == 99) {
5140 $trueWeightUnit = 0.45359237;
5141 $totalWeight += $weight * $qty * $trueWeightUnit;
5142 } elseif ($weight_units == 98) {
5144 $trueWeightUnit = 0.0283495;
5145 $totalWeight += $weight * $qty * $trueWeightUnit;
5147 $totalWeight += $weight * $qty;
5150 if ($volume_units < 50) {
5152 $trueVolumeUnit = pow(10, $volumeUnit);
5154 $totalVolume += $volume * $qty * $trueVolumeUnit;
5156 $totalVolume += $volume * $qty;
5160 return array(
'weight' => $totalWeight,
'volume' => $totalVolume,
'ordered' => $totalOrdered,
'toship' => $totalToShip);
5173 $extraparams = (!empty($this->extraparams) ? json_encode($this->extraparams) :
null);
5175 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
5176 $sql .=
" SET extraparams = ".(!empty($extraparams) ?
"'".$this->db->escape($extraparams).
"'" :
"null");
5177 $sql .=
" WHERE rowid = ".((int) $this->
id);
5179 dol_syslog(get_class($this).
"::setExtraParameters", LOG_DEBUG);
5180 $resql = $this->db->query($sql);
5182 $this->error = $this->db->lasterror();
5183 $this->db->rollback();
5186 $this->db->commit();
5209 global
$conf, $user, $langs,
$object, $hookmanager, $extrafields, $form;
5212 if (!is_object($extrafields)) {
5213 require_once DOL_DOCUMENT_ROOT.
'/core/class/extrafields.class.php';
5216 $extrafields->fetch_name_optionals_label($this->table_element_line);
5221 $dirtpls = array_merge(
$conf->modules_parts[
'tpl'], array($defaulttpldir));
5222 foreach ($dirtpls as $module => $reldir) {
5223 if (!empty($module)) {
5226 $tpl = DOL_DOCUMENT_ROOT.$reldir.
'/objectline_create.tpl.php';
5229 if (empty(
$conf->file->strict_mode)) {
5230 $res = @include $tpl;
5232 $res = include $tpl;
5259 public function printObjectLines($action, $seller, $buyer, $selected = 0, $dateSelector = 0, $defaulttpldir =
'/core/tpl')
5261 global
$conf, $hookmanager, $langs, $user, $form, $extrafields,
$object;
5263 global $inputalsopricewithtax, $usemargins, $disableedit, $disablemove, $disableremove, $outputalsopricetotalwithtax;
5267 if (isModEnabled(
'margin') && !empty($this->element) && in_array($this->element, array(
'facture',
'facturerec',
'propal',
'commande'))) {
5271 $num = count($this->lines);
5274 if (!is_object($extrafields)) {
5275 require_once DOL_DOCUMENT_ROOT.
'/core/class/extrafields.class.php';
5278 $extrafields->fetch_name_optionals_label($this->table_element_line);
5280 if (method_exists($this,
'loadExpeditions')) {
5281 $this->loadExpeditions();
5284 $parameters = array(
'num' => $num,
'dateSelector' => $dateSelector,
'seller' => $seller,
'buyer' => $buyer,
'selected' => $selected,
'table_element_line' => $this->table_element_line);
5285 $reshook = $hookmanager->executeHooks(
'printObjectLineTitle', $parameters, $this, $action);
5286 if (empty($reshook)) {
5290 $dirtpls = array_merge(
$conf->modules_parts[
'tpl'], array($defaulttpldir));
5291 foreach ($dirtpls as $module => $reldir) {
5293 if (!empty($module)) {
5296 $tpl = DOL_DOCUMENT_ROOT.$reldir.
'/objectline_title.tpl.php';
5298 if (file_exists($tpl)) {
5299 if (empty(
$conf->file->strict_mode)) {
5300 $res = @include $tpl;
5302 $res = include $tpl;
5313 print
"<!-- begin printObjectLines() -->\n";
5314 foreach ($this->lines as $line) {
5316 $line->fetch_optionals();
5319 if (is_object($hookmanager)) {
5320 if (empty($line->fk_parent_line)) {
5321 $parameters = array(
'line' => $line,
'num' => $num,
'i' => $i,
'dateSelector' => $dateSelector,
'seller' => $seller,
'buyer' => $buyer,
'selected' => $selected,
'table_element_line' => $line->table_element,
'defaulttpldir' => $defaulttpldir);
5322 $reshook = $hookmanager->executeHooks(
'printObjectLine', $parameters, $this, $action);
5324 $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);
5325 $reshook = $hookmanager->executeHooks(
'printObjectSubLine', $parameters, $this, $action);
5328 if (empty($reshook)) {
5329 $this->printObjectLine($action, $line,
'', $num, $i, $dateSelector, $seller, $buyer, $selected, $extrafields, $defaulttpldir);
5334 print
"<!-- end printObjectLines() -->\n";
5354 public function printObjectLine($action, $line, $var, $num, $i, $dateSelector, $seller, $buyer, $selected = 0, $extrafields =
null, $defaulttpldir =
'/core/tpl')
5358 global $disableedit, $disablemove, $disableremove;
5365 if ($action !=
'editline' || $selected != $line->id) {
5367 if (!empty($line->fk_product) && $line->fk_product > 0) {
5368 $product_static =
new Product($this->db);
5369 $product_static->fetch($line->fk_product);
5371 $product_static->ref = $line->ref;
5372 $product_static->label = !empty($line->label) ? $line->label :
"";
5374 $text = $product_static->getNomUrl(1);
5378 if (property_exists($this,
'socid') && !is_object($this->thirdparty)) {
5379 dol_print_error(
null,
'Error: Method printObjectLine was called on an object and object->fetch_thirdparty was not done before');
5383 $prod =
new Product($this->db);
5384 $prod->fetch($line->fk_product);
5386 $outputlangs = $langs;
5388 if (empty($newlang) &&
GETPOST(
'lang_id',
'aZ09')) {
5389 $newlang =
GETPOST(
'lang_id',
'aZ09');
5391 if (
getDolGlobalString(
'PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE') && empty($newlang) && is_object($this->thirdparty)) {
5392 $newlang = $this->thirdparty->default_lang;
5394 if (!empty($newlang)) {
5396 $outputlangs->setDefaultLang($newlang);
5399 $label = (!empty($prod->multilangs[$outputlangs->defaultlang][
"label"])) ? $prod->multilangs[$outputlangs->defaultlang][
"label"] : $line->product_label;
5401 $label = $line->product_label;
5404 $text .=
' - '.(!empty($line->label) ? $line->label : $label);
5405 $description .= (
getDolGlobalInt(
'PRODUIT_DESC_IN_FORM_ACCORDING_TO_DEVICE') ?
'' : (!empty($line->description) ?
dol_htmlentitiesbr($line->description) :
''));
5408 $line->pu_ttc =
price2num((!empty($line->subprice) ? $line->subprice : 0) * (1 + ((!empty($line->tva_tx) ? $line->tva_tx : 0) / 100)),
'MU');
5415 if (isset($this->expeditions[$line->id])) {
5416 $qty_shipped = $this->expeditions[$line->id];
5418 $disableedit = ($qty_shipped > 0) && ($qty_shipped >= $line->qty);
5420 $dirtpls = array_merge(
$conf->modules_parts[
'tpl'], array($defaulttpldir));
5421 foreach ($dirtpls as $module => $reldir) {
5423 if (!empty($module)) {
5426 $tpl = DOL_DOCUMENT_ROOT.$reldir.
'/objectline_view.tpl.php';
5429 if (file_exists($tpl)) {
5430 if (empty(
$conf->file->strict_mode)) {
5431 $res = @include $tpl;
5433 $res = include $tpl;
5443 if ($this->
status == 0 && $action ==
'editline' && $selected == $line->id) {
5444 $label = (!empty($line->label) ? $line->label : (($line->fk_product > 0) ? $line->product_label :
''));
5446 $line->pu_ttc =
price2num($line->subprice * (1 + ($line->tva_tx / 100)),
'MU');
5451 $dirtpls = array_merge(
$conf->modules_parts[
'tpl'], array($defaulttpldir));
5452 foreach ($dirtpls as $module => $reldir) {
5453 if (!empty($module)) {
5456 $tpl = DOL_DOCUMENT_ROOT.$reldir.
'/objectline_edit.tpl.php';
5459 if (empty(
$conf->file->strict_mode)) {
5460 $res = @include $tpl;
5462 $res = include $tpl;
5487 global $langs, $hookmanager, $form, $action;
5489 print
'<tr class="liste_titre">';
5490 print
'<td class="linecolref">'.$langs->trans(
'Ref').
'</td>';
5491 print
'<td class="linecoldescription">'.$langs->trans(
'Description').
'</td>';
5492 print
'<td class="linecolvat right">'.$langs->trans(
'VATRate').
'</td>';
5493 print
'<td class="linecoluht right">'.$langs->trans(
'PriceUHT').
'</td>';
5494 if (isModEnabled(
"multicurrency")) {
5495 print
'<td class="linecoluht_currency right">'.$langs->trans(
'PriceUHTCurrency').
'</td>';
5497 print
'<td class="linecolqty right">'.$langs->trans(
'Qty').
'</td>';
5499 print
'<td class="linecoluseunit left">'.$langs->trans(
'Unit').
'</td>';
5501 print
'<td class="linecoldiscount right">'.$langs->trans(
'ReductionShort').
'</td>';
5502 print
'<td class="linecolht right">'.$langs->trans(
'TotalHT').
'</td>';
5503 print
'<td class="center">'.$form->showCheckAddButtons(
'checkforselect', 1).
'</td>';
5507 if (!empty($this->lines)) {
5508 foreach ($this->lines as $line) {
5511 if (is_object($hookmanager)) {
5512 $parameters = array(
'line' => $line,
'i' => $i,
'restrictlist' => $restrictlist,
'selectedLines' => $selectedLines);
5513 if (!empty($line->fk_parent_line)) {
5514 $parameters[
'fk_parent_line'] = $line->fk_parent_line;
5516 $reshook = $hookmanager->executeHooks(
'printOriginObjectLine', $parameters, $this, $action);
5518 if (empty($reshook)) {
5519 $this->printOriginLine($line,
'', $restrictlist,
'/core/tpl', $selectedLines);
5540 public function printOriginLine($line, $var, $restrictlist =
'', $defaulttpldir =
'/core/tpl', $selectedLines = array())
5542 global $langs,
$conf;
5545 if (!empty($line->date_start)) {
5547 $date_start = $line->date_start;
5549 $date_start = $line->date_debut_prevue;
5550 if ($line->date_debut_reel) {
5551 $date_start = $line->date_debut_reel;
5554 if (!empty($line->date_end)) {
5556 $date_end = $line->date_end;
5558 $date_end = $line->date_fin_prevue;
5559 if ($line->date_fin_reel) {
5560 $date_end = $line->date_fin_reel;
5564 $this->tpl[
'id'] = $line->id;
5566 $this->tpl[
'label'] =
'';
5567 if (!empty($line->fk_parent_line)) {
5568 $this->tpl[
'label'] .=
img_picto(
'',
'rightarrow');
5571 if (($line->info_bits & 2) == 2) {
5573 if (property_exists($this,
'socid')) {
5574 $discount->fk_soc = $this->socid;
5575 $discount->socid = $this->socid;
5577 $this->tpl[
'label'] .= $discount->getNomUrl(0,
'discount');
5578 } elseif (!empty($line->fk_product)) {
5579 $productstatic =
new Product($this->db);
5580 $productstatic->id = $line->fk_product;
5581 $productstatic->ref = $line->ref;
5582 $productstatic->type = $line->fk_product_type;
5583 if (empty($productstatic->ref)) {
5584 $line->fetch_product();
5585 $productstatic = $line->product;
5588 $this->tpl[
'label'] .= $productstatic->getNomUrl(1);
5589 $this->tpl[
'label'] .=
' - '.(!empty($line->label) ? $line->label : $line->product_label);
5591 if ($line->product_type == 1 && ($date_start || $date_end)) {
5595 $this->tpl[
'label'] .= ($line->product_type == -1 ?
' ' : ($line->product_type == 1 ?
img_object($langs->trans(
''),
'service') :
img_object($langs->trans(
''),
'product')));
5596 if (!empty($line->desc)) {
5597 $this->tpl[
'label'] .= $line->desc;
5599 $this->tpl[
'label'] .= ($line->label ?
' '.$line->label :
'');
5603 if ($line->product_type == 1 && ($date_start || $date_end)) {
5608 if (!empty($line->desc)) {
5609 '@phan-var-force OrderLine|FactureLigne|ContratLigne|FactureFournisseurLigneRec|SupplierInvoiceLine|SupplierProposalLine $line';
5610 if ($line->desc ==
'(CREDIT_NOTE)') {
5612 $discount->fetch($line->fk_remise_except);
5613 $this->tpl[
'description'] = $langs->transnoentities(
"DiscountFromCreditNote", $discount->getNomUrl(0));
5614 } elseif ($line->desc ==
'(DEPOSIT)') {
5616 $discount->fetch($line->fk_remise_except);
5617 $this->tpl[
'description'] = $langs->transnoentities(
"DiscountFromDeposit", $discount->getNomUrl(0));
5618 } elseif ($line->desc ==
'(EXCESS RECEIVED)') {
5620 $discount->fetch($line->fk_remise_except);
5621 $this->tpl[
'description'] = $langs->transnoentities(
"DiscountFromExcessReceived", $discount->getNomUrl(0));
5622 } elseif ($line->desc ==
'(EXCESS PAID)') {
5624 $discount->fetch($line->fk_remise_except);
5625 $this->tpl[
'description'] = $langs->transnoentities(
"DiscountFromExcessPaid", $discount->getNomUrl(0));
5627 $this->tpl[
'description'] =
dol_trunc($line->desc, 60);
5630 $this->tpl[
'description'] =
' ';
5634 $this->tpl[
'vat_rate'] =
vatrate($line->tva_tx,
true);
5635 $this->tpl[
'vat_rate'] .= (($line->info_bits & 1) == 1) ?
'*' :
'';
5636 if (!empty($line->vat_src_code) && !preg_match(
'/\(/', $this->tpl[
'vat_rate'])) {
5637 $this->tpl[
'vat_rate'] .=
' ('.$line->vat_src_code.
')';
5640 $this->tpl[
'price'] =
price($line->subprice);
5641 $this->tpl[
'total_ht'] =
price($line->total_ht);
5642 $this->tpl[
'multicurrency_price'] =
price($line->multicurrency_subprice);
5643 $this->tpl[
'qty'] = (($line->info_bits & 2) != 2) ? $line->qty :
' ';
5645 $this->tpl[
'unit'] = $line->getLabelOfUnit(
'long', $langs);
5646 $this->tpl[
'unit_short'] = $line->getLabelOfUnit(
'short', $langs);
5649 $this->tpl[
'remise_percent'] = (($line->info_bits & 2) != 2) ?
vatrate((
string) $line->remise_percent,
true) :
' ';
5652 $this->tpl[
'strike'] = 0;
5654 $this->tpl[
'strike'] = 1;
5659 $dirtpls = array_merge(
$conf->modules_parts[
'tpl'], array($defaulttpldir));
5660 foreach ($dirtpls as $module => $reldir) {
5661 if (!empty($module)) {
5664 $tpl = DOL_DOCUMENT_ROOT.$reldir.
'/originproductline.tpl.php';
5667 if (empty(
$conf->file->strict_mode)) {
5668 $res = @include $tpl;
5670 $res = include $tpl;
5695 $sql =
"INSERT INTO ".$this->db->prefix().
"element_resources (";
5696 $sql .=
"resource_id";
5697 $sql .=
", resource_type";
5698 $sql .=
", element_id";
5699 $sql .=
", element_type";
5701 $sql .=
", mandatory";
5702 $sql .=
") VALUES (";
5703 $sql .= ((int) $resource_id);
5704 $sql .=
", '".$this->db->escape($resource_type).
"'";
5705 $sql .=
", '".$this->db->escape($this->
id).
"'";
5706 $sql .=
", '".$this->db->escape($this->element).
"'";
5707 $sql .=
", '".$this->db->escape($busy).
"'";
5708 $sql .=
", '".$this->db->escape($mandatory).
"'";
5711 dol_syslog(get_class($this).
"::add_element_resource", LOG_DEBUG);
5712 if ($this->db->query($sql)) {
5713 $this->db->commit();
5716 $this->error = $this->db->lasterror();
5717 $this->db->rollback();
5738 $sql =
"DELETE FROM ".$this->db->prefix().
"element_resources";
5739 $sql .=
" WHERE rowid = ".((int) $rowid);
5741 dol_syslog(get_class($this).
"::delete_resource", LOG_DEBUG);
5743 $resql = $this->db->query($sql);
5745 $this->error = $this->db->lasterror();
5746 $this->db->rollback();
5750 $result = $this->call_trigger(strtoupper($element).
'_DELETE_RESOURCE', $user);
5752 $this->db->rollback();
5756 $this->db->commit();
5770 if (isset($this->lines) && is_array($this->lines)) {
5771 $nboflines = count($this->lines);
5772 for ($i = 0; $i < $nboflines; $i++) {
5773 if (is_object($this->lines[$i])) {
5774 $this->lines[$i] = clone $this->lines[$i];
5793 protected function commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams =
null)
5795 global
$conf, $langs, $user, $hookmanager, $action;
5797 $srctemplatepath =
'';
5799 $parameters = array(
'modelspath' => $modelspath,
'modele' => $modele,
'outputlangs' => $outputlangs,
'hidedetails' => $hidedetails,
'hidedesc' => $hidedesc,
'hideref' => $hideref,
'moreparams' => $moreparams);
5800 $reshook = $hookmanager->executeHooks(
'commonGenerateDocument', $parameters, $this, $action);
5802 if (!empty($reshook)) {
5806 dol_syslog(
"commonGenerateDocument modele=".$modele.
" outputlangs->defaultlang=".(is_object($outputlangs) ? $outputlangs->defaultlang :
'null'));
5808 if (empty($modele)) {
5809 $this->error =
'BadValueForParameterModele';
5814 $err = error_reporting();
5816 @set_time_limit(120);
5817 error_reporting($err);
5820 $tmp = explode(
':', $modele, 2);
5821 $saved_model = $modele;
5822 if (!empty($tmp[1])) {
5824 $srctemplatepath = $tmp[1];
5831 $dirmodels = array(
'/');
5832 if (is_array(
$conf->modules_parts[
'models'])) {
5833 $dirmodels = array_merge($dirmodels,
$conf->modules_parts[
'models']);
5835 foreach ($dirmodels as $reldir) {
5836 foreach (array(
'doc',
'pdf') as $prefix) {
5837 if (in_array(get_class($this), array(
'Adherent'))) {
5839 $file = $prefix.
"_".$modele.
".class.php";
5842 $file = $prefix.
"_".$modele.
".modules.php";
5849 if (file_exists($file)) {
5851 $classname = $prefix.
'_'.$modele;
5860 if ($filefound ===
'' || $classname ===
'') {
5861 $this->error = $langs->trans(
"Error").
' Failed to load doc generator with modelpaths='.$modelspath.
' - modele='.$modele;
5862 $this->errors[] = $this->error;
5873 require_once $filefound;
5875 $obj =
new $classname($this->db);
5887 '@phan-var-force ModelePDFMember $obj';
5891 if ($obj->type ==
'odt' && empty($srctemplatepath)) {
5892 $varfortemplatedir = $obj->scandir;
5896 $listoffiles = array();
5899 $listofdir = explode(
',', $dirtoscan);
5900 foreach ($listofdir as $key => $tmpdir) {
5901 $tmpdir = trim($tmpdir);
5902 $tmpdir = preg_replace(
'/DOL_DATA_ROOT/', DOL_DATA_ROOT, $tmpdir);
5904 unset($listofdir[$key]);
5907 if (is_dir($tmpdir)) {
5908 $tmpfiles =
dol_dir_list($tmpdir,
'files', 0,
'\.od(s|t)$',
'',
'name', SORT_ASC, 0);
5909 if (count($tmpfiles)) {
5910 $listoffiles = array_merge($listoffiles, $tmpfiles);
5915 if (count($listoffiles)) {
5916 foreach ($listoffiles as $record) {
5917 $srctemplatepath = $record[
'fullname'];
5923 if (empty($srctemplatepath)) {
5924 $this->error =
'ErrorGenerationAskedForOdtTemplateWithSrcFileNotDefined';
5929 if ($obj->type ==
'odt' && !empty($srctemplatepath)) {
5931 dol_syslog(
"Failed to locate template file ".$srctemplatepath, LOG_WARNING);
5932 $this->error =
'ErrorGenerationAskedForOdtTemplateWithSrcFileNotFound';
5939 $sav_charset_output = empty($outputlangs->charset_output) ?
'' : $outputlangs->charset_output;
5942 $this->model_pdf = $saved_model;
5945 $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath,
'member', 1,
'tmp_cards');
5948 '@phan-var-force ModeleBarCode|ModeleDon|ModeleExports|ModeleImports|ModelePDFAsset|ModelePDFContract|ModelePDFDeliveryOrder|ModelePDFEvaluation|ModelePDFFactures|ModelePDFFicheinter|ModelePDFMo|ModelePDFMovement|ModelePDFProduct|ModelePDFProjects|ModelePDFPropales|ModelePDFRecruitmentJobPosition|ModelePDFStock|ModelePDFStockTransfer|ModelePDFSupplierProposal|ModelePDFSuppliersInvoices|ModelePDFSuppliersOrders|ModelePDFSuppliersPayments|ModelePDFTask|ModelePDFTicket|ModelePDFUser|ModelePDFUserGroup|ModelePdfExpedition|ModelePdfReception|ModeleThirdPartyDoc $obj';
5949 $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, $hidedetails, $hidedesc, $hideref, $moreparams);
5953 if ($resultwritefile > 0) {
5954 $outputlangs->charset_output = $sav_charset_output;
5957 require_once DOL_DOCUMENT_ROOT.
'/core/lib/files.lib.php';
5961 if (!empty($obj->result[
'fullpath'])) {
5962 $destfull = $obj->result[
'fullpath'];
5965 $update_main_doc_field = 0;
5966 if (!empty($obj->update_main_doc_field)) {
5967 $update_main_doc_field = 1;
5973 $this->indexFile($destfull, $update_main_doc_field);
5976 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);
5984 $outputlangs->charset_output = $sav_charset_output;
5985 $this->error = $obj->error;
5986 $this->errors = $obj->errors;
5987 dol_syslog(
"Error generating document for ".__CLASS__.
". Error: ".$obj->error, LOG_ERR);
6001 public function indexFile($destfull, $update_main_doc_field)
6003 global
$conf, $user;
6005 $upload_dir = dirname($destfull);
6006 $destfile = basename($destfull);
6007 $rel_dir = preg_replace(
'/^'.preg_quote(DOL_DATA_ROOT,
'/').
'/',
'', $upload_dir);
6009 if (!preg_match(
'/[\\/]temp[\\/]|[\\/]thumbs|\.meta$/', $rel_dir)) {
6010 $filename = basename($destfile);
6011 $rel_dir = preg_replace(
'/[\\/]$/',
'', $rel_dir);
6012 $rel_dir = preg_replace(
'/^[\\/]/',
'', $rel_dir);
6014 include_once DOL_DOCUMENT_ROOT.
'/ecm/class/ecmfiles.class.php';
6015 $ecmfile =
new EcmFiles($this->db);
6016 $result = $ecmfile->fetch(0,
'', ($rel_dir ? $rel_dir.
'/' :
'').$filename);
6019 $setsharekey =
false;
6020 if ($this->element ==
'propal' || $this->element ==
'proposal') {
6022 $setsharekey =
true;
6025 $setsharekey =
true;
6028 if ($this->element ==
'commande' &&
getDolGlobalInt(
"ORDER_ALLOW_EXTERNAL_DOWNLOAD")) {
6029 $setsharekey =
true;
6031 if ($this->element ==
'facture' &&
getDolGlobalInt(
"INVOICE_ALLOW_EXTERNAL_DOWNLOAD")) {
6032 $setsharekey =
true;
6034 if ($this->element ==
'bank_account' &&
getDolGlobalInt(
"BANK_ACCOUNT_ALLOW_EXTERNAL_DOWNLOAD")) {
6035 $setsharekey =
true;
6037 if ($this->element ==
'product' &&
getDolGlobalInt(
"PRODUCT_ALLOW_EXTERNAL_DOWNLOAD")) {
6038 $setsharekey =
true;
6040 if ($this->element ==
'contrat' &&
getDolGlobalInt(
"CONTRACT_ALLOW_EXTERNAL_DOWNLOAD")) {
6041 $setsharekey =
true;
6043 if ($this->element ==
'fichinter' &&
getDolGlobalInt(
"FICHINTER_ALLOW_EXTERNAL_DOWNLOAD")) {
6044 $setsharekey =
true;
6046 if ($this->element ==
'supplier_proposal' &&
getDolGlobalInt(
"SUPPLIER_PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD")) {
6047 $setsharekey =
true;
6049 if ($this->element ==
'societe_rib' &&
getDolGlobalInt(
"SOCIETE_RIB_ALLOW_ONLINESIGN")) {
6050 $setsharekey =
true;
6054 if (empty($ecmfile->share)) {
6055 require_once DOL_DOCUMENT_ROOT.
'/core/lib/security2.lib.php';
6062 $ecmfile->fullpath_orig =
'';
6063 $ecmfile->gen_or_uploaded =
'generated';
6064 $ecmfile->description =
'';
6065 $ecmfile->keywords =
'';
6066 $ecmfile->src_object_type = $this->table_element;
6068 $result = $ecmfile->update($user);
6074 $ecmfile->entity =
$conf->entity;
6075 $ecmfile->filepath = $rel_dir;
6076 $ecmfile->filename = $filename;
6078 $ecmfile->fullpath_orig =
'';
6079 $ecmfile->gen_or_uploaded =
'generated';
6080 $ecmfile->description =
'';
6081 $ecmfile->keywords =
'';
6082 $ecmfile->src_object_type = $this->table_element;
6085 $result = $ecmfile->create($user);
6097 if ($update_main_doc_field && !empty($this->table_element)) {
6098 $sql =
"UPDATE ".$this->db->prefix().$this->table_element.
" SET last_main_doc = '".$this->db->escape($ecmfile->filepath.
"/".$ecmfile->filename).
"'";
6099 $sql .=
" WHERE rowid = ".((int) $this->
id);
6101 $resql = $this->db->query($sql);
6106 $this->last_main_doc = $ecmfile->filepath.
'/'.$ecmfile->filename;
6126 if (file_exists($file_osencoded)) {
6127 require_once DOL_DOCUMENT_ROOT.
'/core/lib/images.lib.php';
6130 $maxwidthsmall = $tmparraysize[
'maxwidthsmall'];
6131 $maxheightsmall = $tmparraysize[
'maxheightsmall'];
6132 $maxwidthmini = $tmparraysize[
'maxwidthmini'];
6133 $maxheightmini = $tmparraysize[
'maxheightmini'];
6138 vignette($file_osencoded, $maxwidthsmall, $maxheightsmall,
'_small', $quality);
6142 vignette($file_osencoded, $maxwidthmini, $maxheightmini,
'_mini', $quality);
6182 if (GETPOSTISSET($fieldname)) {
6183 return GETPOST($fieldname, $type, 3);
6186 if (isset($alternatevalue)) {
6187 return $alternatevalue;
6190 $newelement = $this->element;
6191 if ($newelement ==
'facture') {
6192 $newelement =
'invoice';
6194 if ($newelement ==
'commande') {
6195 $newelement =
'order';
6197 if (empty($newelement)) {
6198 dol_syslog(
"Ask a default value using common method getDefaultCreateValueForField on an object with no property ->element defined. Return empty string.", LOG_WARNING);
6202 $keyforfieldname = strtoupper($newelement.
'_DEFAULT_'.$fieldname);
6232 global $langs,
$conf;
6234 if (!empty(self::TRIGGER_PREFIX) && strpos($triggerName, self::TRIGGER_PREFIX .
'_') !== 0) {
6235 dol_print_error(
null,
'The trigger "' . $triggerName .
'" does not start with "' . self::TRIGGER_PREFIX .
'_" as required.');
6238 if (!is_object($langs)) {
6240 include_once DOL_DOCUMENT_ROOT.
'/core/class/translate.class.php';
6242 $langs->load(
"main");
6245 include_once DOL_DOCUMENT_ROOT.
'/core/class/interfaces.class.php';
6247 $result = $interface->run_triggers($triggerName, $this, $user, $langs,
$conf);
6250 if (!empty($this->errors)) {
6251 $this->errors = array_unique(array_merge($this->errors, $interface->errors));
6253 $this->errors = $interface->errors;
6273 if (!$this->element) {
6276 if (!($this->
id > 0)) {
6279 if (is_array($this->array_languages)) {
6283 $this->array_languages = array();
6285 $element = $this->element;
6286 if ($element ==
'categorie') {
6287 $element =
'categories';
6291 $sql =
"SELECT rowid, property, lang , value";
6292 $sql .=
" FROM ".$this->db->prefix().
"object_lang";
6293 $sql .=
" WHERE type_object = '".$this->db->escape($element).
"'";
6294 $sql .=
" AND fk_object = ".((int) $this->
id);
6297 $resql = $this->db->query($sql);
6299 $numrows = $this->db->num_rows($resql);
6302 while ($i < $numrows) {
6303 $obj = $this->db->fetch_object($resql);
6304 $key = $obj->property;
6305 $value = $obj->value;
6306 $codelang = $obj->lang;
6307 $type = $this->fields[$key][
'type'];
6310 if (preg_match(
'/date/', $type)) {
6311 $this->array_languages[$key][$codelang] = $this->db->jdate($value);
6313 $this->array_languages[$key][$codelang] = $value;
6320 $this->db->free($resql);
6342 foreach ($_POST as $postfieldkey => $postfieldvalue) {
6343 $tmparray = explode(
'-', $postfieldkey);
6344 if ($tmparray[0] !=
'field') {
6348 $element = $tmparray[1];
6349 $key = $tmparray[2];
6350 $codelang = $tmparray[3];
6353 if (!empty($onlykey) && $key != $onlykey) {
6356 if ($element != $this->element) {
6360 $key_type = $this->fields[$key][
'type'];
6363 if (isset($this->fields[$key][
'enabled'])) {
6364 $enabled = (int)
dol_eval($this->fields[$key][
'enabled'], 1, 1,
'1');
6371 if (empty($enabled)) {
6376 if (in_array($key_type, array(
'date'))) {
6380 } elseif (in_array($key_type, array(
'datetime'))) {
6384 } elseif (in_array($key_type, array(
'checkbox',
'chkbxlst'))) {
6385 $value_arr =
GETPOST($postfieldkey,
'array');
6386 if (!empty($value_arr)) {
6387 $value_key = implode(
',', $value_arr);
6391 } elseif (in_array($key_type, array(
'price',
'double'))) {
6392 $value_arr =
GETPOST($postfieldkey,
'alpha');
6395 $value_key =
GETPOST($postfieldkey);
6396 if (in_array($key_type, array(
'link')) && $value_key ==
'-1') {
6401 $this->array_languages[$key][$codelang] = $value_key;
6426 $savDisableCompute =
$conf->disable_compute;
6427 $conf->disable_compute = 1;
6429 $ret = $this->fetch(
$id);
6431 $conf->disable_compute = $savDisableCompute;
6449 global
$conf, $extrafields;
6451 if (empty($rowid)) {
6454 if (empty($rowid) && isset($this->rowid)) {
6455 $rowid = $this->rowid;
6459 if (!$this->table_element) {
6463 $this->array_options = array();
6465 if (!is_array($optionsArray)) {
6467 if (!isset($extrafields) || !is_object($extrafields)) {
6468 require_once DOL_DOCUMENT_ROOT.
'/core/class/extrafields.class.php';
6473 if (empty($extrafields->attributes[$this->table_element][
'loaded'])) {
6474 $extrafields->fetch_name_optionals_label($this->table_element);
6476 $optionsArray = (!empty($extrafields->attributes[$this->table_element][
'label']) ? $extrafields->attributes[$this->table_element][
'label'] :
null);
6478 global $extrafields;
6479 dol_syslog(
"Warning: fetch_optionals was called with param optionsArray defined when you should pass null now", LOG_WARNING);
6482 $table_element = $this->table_element;
6483 if ($table_element ==
'categorie') {
6484 $table_element =
'categories';
6488 if (is_array($optionsArray) && count($optionsArray) > 0) {
6489 $sql =
"SELECT rowid";
6490 foreach ($optionsArray as $name => $label) {
6491 if (empty($extrafields->attributes[$this->table_element][
'type'][$name]) || (!in_array($extrafields->attributes[$this->table_element][
'type'][$name], [
'separate',
'point',
'multipts',
'linestrg',
'polygon']))) {
6495 if (empty($extrafields->attributes[$this->table_element][
'type'][$name]) || $extrafields->attributes[$this->table_element][
'type'][$name] ==
'point') {
6496 $sql .=
", ST_AsWKT(".$name.
") as ".$name;
6498 if (empty($extrafields->attributes[$this->table_element][
'type'][$name]) || $extrafields->attributes[$this->table_element][
'type'][$name] ==
'multipts') {
6499 $sql .=
", ST_AsWKT(".$name.
") as ".$name;
6501 if (empty($extrafields->attributes[$this->table_element][
'type'][$name]) || $extrafields->attributes[$this->table_element][
'type'][$name] ==
'linestrg') {
6502 $sql .=
", ST_AsWKT(".$name.
") as ".$name;
6504 if (empty($extrafields->attributes[$this->table_element][
'type'][$name]) || $extrafields->attributes[$this->table_element][
'type'][$name] ==
'polygon') {
6505 $sql .=
", ST_AsWKT(".$name.
") as ".$name;
6508 $sql .=
" FROM ".$this->db->prefix().$table_element.
"_extrafields";
6509 $sql .=
" WHERE fk_object = ".((int) $rowid);
6512 $resql = $this->db->query($sql);
6514 $numrows = $this->db->num_rows($resql);
6516 $tab = $this->db->fetch_array($resql);
6518 foreach ($tab as $key => $value) {
6520 if ($key !=
'rowid' && $key !=
'tms' && $key !=
'fk_member' && !is_int($key)) {
6522 if (!empty($extrafields->attributes[$this->table_element]) && in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'date',
'datetime'))) {
6524 $this->array_options[
"options_".$key] = $this->db->jdate($value);
6526 $this->array_options[
"options_".$key] = $value;
6531 if (!empty($extrafields->attributes[$this->table_element][
'type'][$key]) && $extrafields->attributes[$this->table_element][
'type'][$key] ==
'password') {
6532 if (!empty($value) && preg_match(
'/^dolcrypt:/', $value)) {
6533 $this->array_options[
"options_".$key] =
dolDecrypt($value);
6542 if (is_array($extrafields->attributes[$this->table_element][
'label'])) {
6543 foreach ($extrafields->attributes[$this->table_element][
'label'] as $key => $val) {
6544 $this->array_options[
'options_' . $key] =
null;
6551 if (is_array($extrafields->attributes[$this->table_element][
'label'])) {
6552 foreach ($extrafields->attributes[$this->table_element][
'label'] as $key => $val) {
6553 if (!empty($extrafields->attributes[$this->table_element]) && !empty($extrafields->attributes[$this->table_element][
'computed'][$key])) {
6555 if (empty(
$conf->disable_compute)) {
6556 global $objectoffield;
6557 $objectoffield = $this;
6558 $this->array_options[
'options_' . $key] =
dol_eval($extrafields->attributes[$this->table_element][
'computed'][$key], 1, 0,
'2');
6564 $this->db->free($resql);
6572 $this->errors[] = $this->db->lasterror;
6595 $table_element = $this->table_element;
6596 if ($table_element ==
'categorie') {
6597 $table_element =
'categories';
6600 dol_syslog(get_class($this).
"::deleteExtraFields delete", LOG_DEBUG);
6602 $sql_del =
"DELETE FROM ".$this->db->prefix().$table_element.
"_extrafields WHERE fk_object = ".((int) $this->
id);
6604 $resql = $this->db->query($sql_del);
6606 $this->error = $this->db->lasterror();
6607 $this->db->rollback();
6610 $this->db->commit();
6627 global $langs, $user;
6633 if (empty($userused)) {
6639 if (!empty($this->array_options)) {
6641 $langs->load(
'admin');
6642 require_once DOL_DOCUMENT_ROOT.
'/core/class/extrafields.class.php';
6644 $target_extrafields = $extrafields->fetch_name_optionals_label($this->table_element);
6647 $new_array_options = array();
6648 foreach ($this->array_options as $key => $value) {
6649 if (in_array(substr($key, 8), array_keys($target_extrafields))) {
6650 $new_array_options[$key] = $value;
6651 } elseif (in_array($key, array_keys($target_extrafields))) {
6652 $new_array_options[
'options_'.$key] = $value;
6656 foreach ($new_array_options as $key => $value) {
6657 $attributeKey = substr($key, 8);
6658 $attributeType = $extrafields->attributes[$this->table_element][
'type'][$attributeKey];
6659 $attributeLabel = $langs->transnoentities($extrafields->attributes[$this->table_element][
'label'][$attributeKey]);
6660 $attributeParam = $extrafields->attributes[$this->table_element][
'param'][$attributeKey];
6661 $attributeRequired = $extrafields->attributes[$this->table_element][
'required'][$attributeKey];
6662 $attributeUnique = $extrafields->attributes[$this->table_element][
'unique'][$attributeKey];
6663 $attrfieldcomputed = $extrafields->attributes[$this->table_element][
'computed'][$attributeKey];
6667 if (!empty($this->context[
'createfromclone']) && $this->context[
'createfromclone'] ==
'createfromclone' && !empty($attributeUnique)) {
6668 $new_array_options[$key] =
null;
6673 if (!empty($this->context[
'createproductcombination']) && $this->context[
'createproductcombination'] ==
'createproductcombination' && !empty($attributeUnique)) {
6674 $new_array_options[$key] =
null;
6678 if ($attributeRequired) {
6679 $v = $this->array_options[$key];
6681 $langs->load(
"errors");
6682 dol_syslog(
"Mandatory field '".$key.
"' is empty during create and set to required into definition of extrafields");
6683 $this->errors[] = $langs->trans(
'ErrorFieldRequired', $attributeLabel);
6691 if (!empty($attrfieldcomputed)) {
6693 $value =
dol_eval($attrfieldcomputed, 1, 0,
'2');
6694 dol_syslog($langs->trans(
"Extrafieldcomputed").
" on ".$attributeLabel.
"(".$value.
")", LOG_DEBUG);
6695 $new_array_options[$key] = $value;
6697 $new_array_options[$key] =
null;
6701 switch ($attributeType) {
6703 if (!is_numeric($value) && $value !=
'') {
6704 $this->errors[] = $langs->trans(
"ExtraFieldHasWrongValue", $attributeLabel);
6706 } elseif ($value ==
'') {
6707 $new_array_options[$key] =
null;
6713 if (!is_numeric($value) && $value !=
'') {
6714 dol_syslog($langs->trans(
"ExtraFieldHasWrongValue").
" for ".$attributeLabel.
"(".$value.
"is not '".$attributeType.
"')", LOG_DEBUG);
6715 $this->errors[] = $langs->trans(
"ExtraFieldHasWrongValue", $attributeLabel);
6717 } elseif ($value ==
'') {
6721 $new_array_options[$key] = $value;
6731 if ($this->array_options[$key] !=
'' && is_array($extrafields->attributes[$this->table_element][
'param'][$attributeKey][
'options'])) {
6733 $tmparrays = array_keys($extrafields->attributes[$this->table_element][
'param'][$attributeKey][
'options']);
6734 $algo = reset($tmparrays);
6739 if (is_object($this->oldcopy)) {
6741 if (isset($this->oldcopy->array_options[$key]) && $this->array_options[$key] == $this->oldcopy->array_options[$key]) {
6743 if ($algo ==
'dolcrypt') {
6744 if (!preg_match(
'/^dolcrypt:/', $this->array_options[$key])) {
6745 $new_array_options[$key] =
dolEncrypt($this->array_options[$key]);
6747 $new_array_options[$key] = $this->array_options[$key];
6750 $new_array_options[$key] = $this->array_options[$key];
6754 if ($algo ==
'dolcrypt') {
6755 if (!preg_match(
'/^dolcrypt:/', $this->array_options[$key])) {
6756 $new_array_options[$key] =
dolEncrypt($this->array_options[$key]);
6758 $new_array_options[$key] = $this->array_options[$key];
6761 $new_array_options[$key] =
dol_hash($this->array_options[$key], $algo);
6767 if ($algo ==
'dolcrypt' && !preg_match(
'/^dolcrypt:/', $this->array_options[$key])) {
6768 $new_array_options[$key] =
dolEncrypt($this->array_options[$key]);
6770 $new_array_options[$key] = $this->array_options[$key];
6775 $new_array_options[$key] = $this->array_options[$key];
6778 $new_array_options[$key] = $this->array_options[$key];
6784 if (!is_numeric($this->array_options[$key]) || $this->array_options[$key] != intval($this->array_options[$key])) {
6785 $this->array_options[$key] = strtotime($this->array_options[$key]);
6787 $new_array_options[$key] = $this->db->idate($this->array_options[$key]);
6791 if (!is_numeric($this->array_options[$key]) || $this->array_options[$key] != intval($this->array_options[$key])) {
6792 $this->array_options[$key] = strtotime($this->array_options[$key]);
6794 $new_array_options[$key] = $this->db->idate($this->array_options[$key],
'gmt');
6797 $param_list = array_keys($attributeParam[
'options']);
6800 $InfoFieldList = explode(
":", $param_list[0]);
6802 if ($InfoFieldList[0] && class_exists($InfoFieldList[0])) {
6803 if ($value ==
'-1') {
6804 $new_array_options[$key] =
'';
6806 $object =
new $InfoFieldList[0]($this->db);
6807 '@phan-var-force CommonObject $object';
6808 if (is_numeric($value)) {
6809 $res =
$object->fetch($value);
6811 $res =
$object->fetch(0, $value);
6815 $new_array_options[$key] =
$object->id;
6817 $this->error =
"Id/Ref '".$value.
"' for object '".
$object->element.
"' not found";
6822 dol_syslog(
'Error bad setup of extrafield', LOG_WARNING);
6827 if (is_array($this->array_options[$key])) {
6828 $new_array_options[$key] = implode(
',', $this->array_options[$key]);
6830 $new_array_options[$key] = $this->array_options[$key];
6838 $table_element = $this->table_element;
6839 if ($table_element ==
'categorie') {
6840 $table_element =
'categories';
6843 dol_syslog(get_class($this).
"::insertExtraFields delete then insert", LOG_DEBUG);
6845 $sql_del =
"DELETE FROM ".$this->db->prefix().$table_element.
"_extrafields WHERE fk_object = ".((int) $this->
id);
6846 $this->db->query($sql_del);
6848 $sql =
"INSERT INTO ".$this->db->prefix().$table_element.
"_extrafields (fk_object";
6849 foreach ($new_array_options as $key => $value) {
6850 $attributeKey = substr($key, 8);
6852 if ($extrafields->attributes[$this->table_element][
'type'][$attributeKey] !=
'separate') {
6853 $sql .=
",".$attributeKey;
6857 if (!empty($extrafields->attributes[$this->table_element][
'mandatoryfieldsofotherentities']) && is_array($extrafields->attributes[$this->table_element][
'mandatoryfieldsofotherentities'])) {
6858 foreach ($extrafields->attributes[$this->table_element][
'mandatoryfieldsofotherentities'] as $tmpkey => $tmpval) {
6859 if (!isset($extrafields->attributes[$this->table_element][
'type'][$tmpkey])) {
6860 $sql .=
",".$tmpkey;
6864 $sql .=
") VALUES (".$this->id;
6866 foreach ($new_array_options as $key => $value) {
6867 $attributeKey = substr($key, 8);
6869 if (!in_array($extrafields->attributes[$this->table_element][
'type'][$attributeKey], [
'separate',
'point',
'multipts',
'linestrg',
'polygon'])) {
6870 if ($new_array_options[$key] !=
'' || $new_array_options[$key] ==
'0') {
6871 $sql .=
",'".$this->db->escape($new_array_options[$key]).
"'";
6876 if ($extrafields->attributes[$this->table_element][
'type'][$attributeKey] ==
'point') {
6877 if (!empty($new_array_options[$key])) {
6878 if (!preg_match(
'/error/i', $new_array_options[$key])) {
6880 $sql .=
",ST_PointFromText('".$this->db->escape($new_array_options[$key]).
"')";
6882 dol_syslog(
"Bad syntax string for point ".$new_array_options[$key].
" to generate SQL request", LOG_WARNING);
6889 if ($extrafields->attributes[$this->table_element][
'type'][$attributeKey] ==
'multipts') {
6890 if (!empty($new_array_options[$key])) {
6891 if (!preg_match(
'/error/i', $new_array_options[$key])) {
6893 $sql .=
",ST_MultiPointFromText('".$this->db->escape($new_array_options[$key]).
"')";
6895 dol_syslog(
"Bad syntax string for multipoint ".$new_array_options[$key].
" to generate SQL request", LOG_WARNING);
6902 if ($extrafields->attributes[$this->table_element][
'type'][$attributeKey] ==
'linestrg') {
6903 if (!empty($new_array_options[$key])) {
6904 if (!preg_match(
'/error/i', $new_array_options[$key])) {
6906 $sql .=
",ST_LineFromText('".$this->db->escape($new_array_options[$key]).
"')";
6908 dol_syslog(
"Bad syntax string for line ".$new_array_options[$key].
" to generate SQL request", LOG_WARNING);
6915 if ($extrafields->attributes[$this->table_element][
'type'][$attributeKey] ==
'polygon') {
6916 if (!empty($new_array_options[$key])) {
6917 if (!preg_match(
'/error/i', $new_array_options[$key])) {
6919 $sql .=
",ST_PolyFromText('".$this->db->escape($new_array_options[$key]).
"')";
6921 dol_syslog(
"Bad syntax string for polygon ".$new_array_options[$key].
" to generate SQL request", LOG_WARNING);
6930 if (!empty($extrafields->attributes[$this->table_element][
'mandatoryfieldsofotherentities']) && is_array($extrafields->attributes[$this->table_element][
'mandatoryfieldsofotherentities'])) {
6931 foreach ($extrafields->attributes[$this->table_element][
'mandatoryfieldsofotherentities'] as $tmpkey => $tmpval) {
6932 if (!isset($extrafields->attributes[$this->table_element][
'type'][$tmpkey])) {
6933 if (in_array($tmpval, array(
'int',
'double',
'price'))) {
6944 $resql = $this->db->query($sql);
6946 $this->error = $this->db->lasterror();
6950 if (!$error && $trigger) {
6952 $this->context = array(
'extrafieldaddupdate' => 1);
6953 $result = $this->call_trigger($trigger, $userused);
6961 $this->db->rollback();
6964 $this->db->commit();
6984 global
$conf, $langs, $user;
6986 if (empty($userused)) {
6996 if (is_array($this->array_languages)) {
6997 $new_array_languages = $this->array_languages;
6999 foreach ($new_array_languages as $key => $value) {
7000 $attributeKey = $key;
7001 $attributeType = $this->fields[$attributeKey][
'type'];
7002 $attributeLabel = $this->fields[$attributeKey][
'label'];
7007 switch ($attributeType) {
7009 if (is_array($value) || (!is_numeric($value) && $value !=
'')) {
7010 $this->errors[] = $langs->trans(
"ExtraLanguageHasWrongValue", $attributeLabel);
7012 } elseif ($value ==
'') {
7013 $new_array_languages[$key] =
null;
7018 if (!is_numeric($value) && $value !=
'') {
7019 dol_syslog($langs->trans(
"ExtraLanguageHasWrongValue").
" on ".$attributeLabel.
"(".$value.
"is not '".$attributeType.
"')", LOG_DEBUG);
7020 $this->errors[] = $langs->trans(
"ExtraLanguageHasWrongValue", $attributeLabel);
7022 } elseif ($value ==
'') {
7023 $new_array_languages[$key] =
null;
7025 $new_array_languages[$key] = $value;
7039 $table_element = $this->table_element;
7040 if ($table_element ==
'categorie') {
7041 $table_element =
'categories';
7044 dol_syslog(get_class($this).
"::insertExtraLanguages delete then insert", LOG_DEBUG);
7046 foreach ($new_array_languages as $key => $langcodearray) {
7047 foreach ($langcodearray as $langcode => $value) {
7048 $sql_del =
"DELETE FROM ".$this->db->prefix().
"object_lang";
7049 $sql_del .=
" WHERE fk_object = ".((int) $this->
id).
" AND property = '".$this->db->escape($key).
"' AND type_object = '".$this->db->escape($table_element).
"'";
7050 $sql_del .=
" AND lang = '".$this->db->escape($langcode).
"'";
7051 $this->db->query($sql_del);
7053 if ($value !==
'') {
7054 $sql =
"INSERT INTO ".$this->db->prefix().
"object_lang (fk_object, property, type_object, lang, value";
7055 $sql .=
") VALUES (".$this->id.
", '".$this->db->escape($key).
"', '".$this->db->escape($table_element).
"', '".$this->db->escape($langcode).
"', '".$this->db->escape($value).
"'";
7058 $resql = $this->db->query($sql);
7060 $this->error = $this->db->lasterror();
7068 if (!$error && $trigger) {
7070 $this->context = array(
'extralanguagesaddupdate' => 1);
7071 $result = $this->call_trigger($trigger, $userused);
7079 $this->db->rollback();
7082 $this->db->commit();
7102 global
$conf, $langs, $user, $hookmanager;
7108 if (empty($userused)) {
7114 if (!empty($this->array_options) && isset($this->array_options[
"options_".$key])) {
7116 $langs->load(
'admin');
7117 require_once DOL_DOCUMENT_ROOT.
'/core/class/extrafields.class.php';
7119 $extrafields->fetch_name_optionals_label($this->table_element);
7121 $value = $this->array_options[
"options_".$key];
7123 $attributeKey = $key;
7124 $attributeType = $extrafields->attributes[$this->table_element][
'type'][$key];
7125 $attributeLabel = $extrafields->attributes[$this->table_element][
'label'][$key];
7126 $attributeParam = $extrafields->attributes[$this->table_element][
'param'][$key];
7127 $attributeRequired = $extrafields->attributes[$this->table_element][
'required'][$key];
7128 $attributeUnique = $extrafields->attributes[$this->table_element][
'unique'][$attributeKey];
7129 $attrfieldcomputed = $extrafields->attributes[$this->table_element][
'computed'][$key];
7132 if ($attributeRequired) {
7133 $mandatorypb =
false;
7134 if ($attributeType ==
'link' && $this->array_options[
"options_".$key] ==
'-1') {
7135 $mandatorypb =
true;
7137 if ($this->array_options[
"options_".$key] ===
'') {
7138 $mandatorypb =
true;
7141 $langs->load(
"errors");
7142 dol_syslog(
"Mandatory field 'options_".$key.
"' is empty during update and set to required into definition of extrafields");
7143 $this->errors[] = $langs->trans(
'ErrorFieldRequired', $attributeLabel);
7149 $new_array_options = $this->array_options;
7153 if (!empty($attrfieldcomputed)) {
7155 $value =
dol_eval($attrfieldcomputed, 1, 0,
'2');
7156 dol_syslog($langs->trans(
"Extrafieldcomputed").
" on ".$attributeLabel.
"(".$value.
")", LOG_DEBUG);
7158 $new_array_options[
"options_".$key] = $value;
7160 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7162 $new_array_options[
"options_".$key] =
null;
7164 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7168 switch ($attributeType) {
7170 if (!is_numeric($value) && $value !=
'') {
7171 $this->errors[] = $langs->trans(
"ExtraFieldHasWrongValue", $attributeLabel);
7173 } elseif ($value ===
'') {
7174 $new_array_options[
"options_".$key] =
null;
7176 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7182 if (!is_numeric($value) && $value !=
'') {
7183 dol_syslog($langs->trans(
"ExtraFieldHasWrongValue").
" on ".$attributeLabel.
"(".$value.
"is not '".$attributeType.
"')", LOG_DEBUG);
7184 $this->errors[] = $langs->trans(
"ExtraFieldHasWrongValue", $attributeLabel);
7186 } elseif ($value ===
'') {
7190 $new_array_options[
"options_".$key] = $value;
7192 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7204 if ($this->array_options[
"options_".$key] !=
'' && is_array($extrafields->attributes[$this->table_element][
'param'][$attributeKey][
'options'])) {
7206 $tmparrays = array_keys($extrafields->attributes[$this->table_element][
'param'][$attributeKey][
'options']);
7207 $algo = reset($tmparrays);
7213 if (is_object($this->oldcopy)) {
7215 if (isset($this->oldcopy->array_options[
"options_".$key]) && $this->array_options[
"options_".$key] == $this->oldcopy->array_options[
"options_".$key]) {
7216 if ($algo ==
'dolcrypt') {
7217 if (!preg_match(
'/^dolcrypt:/', $this->array_options[
"options_".$key])) {
7218 $new_array_options[
"options_".$key] =
dolEncrypt($this->array_options[
"options_".$key]);
7220 $new_array_options[
"options_".$key] = $this->array_options[
"options_".$key];
7223 $new_array_options[
"options_".$key] = $this->array_options[
"options_".$key];
7226 if ($algo ==
'dolcrypt') {
7227 if (!preg_match(
'/^dolcrypt:/', $this->array_options[
"options_".$key])) {
7228 $new_array_options[
"options_".$key] =
dolEncrypt($this->array_options[
"options_".$key]);
7230 $new_array_options[
"options_".$key] = $this->array_options[
"options_".$key];
7233 $new_array_options[
"options_".$key] =
dol_hash($this->array_options[
"options_".$key], $algo);
7237 if ($algo ==
'dolcrypt' && !preg_match(
'/^dolcrypt:/', $this->array_options[
"options_".$key])) {
7238 $new_array_options[
"options_".$key] =
dolEncrypt($this->array_options[
"options_".$key]);
7240 $new_array_options[
"options_".$key] = $this->array_options[
"options_".$key];
7245 $new_array_options[
"options_".$key] = $this->array_options[
"options_".$key];
7248 $new_array_options[
"options_".$key] = $this->array_options[
"options_".$key];
7251 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7255 if (empty($this->array_options[
"options_".$key])) {
7256 $new_array_options[
"options_".$key] =
null;
7258 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7260 $new_array_options[
"options_".$key] = $this->db->idate($this->array_options[
"options_".$key]);
7264 if (empty($this->array_options[
"options_".$key])) {
7265 $new_array_options[
"options_".$key] =
null;
7267 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7269 $new_array_options[
"options_".$key] = $this->db->idate($this->array_options[
"options_".$key],
'gmt');
7273 if (empty($this->array_options[
"options_".$key])) {
7274 $new_array_options[
"options_".$key] =
null;
7276 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7280 if ($this->array_options[
"options_".$key] ===
'') {
7281 $new_array_options[
"options_".$key] =
null;
7283 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7317 $new_array_options = array();
7318 if (is_array($this->array_options[
"options_".$key])) {
7319 $new_array_options[
"options_".$key] = implode(
',', $this->array_options[
"options_".$key]);
7321 $new_array_options[
"options_".$key] = $this->array_options[
"options_".$key];
7324 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7330 $linealreadyfound = 0;
7333 $table_element = $this->table_element;
7334 if ($table_element ==
'categorie') {
7335 $table_element =
'categories';
7338 $sql =
"SELECT COUNT(rowid) as nb FROM ".$this->db->prefix().$table_element.
"_extrafields WHERE fk_object = ".((int) $this->
id);
7339 $resql = $this->db->query($sql);
7341 $tmpobj = $this->db->fetch_object($resql);
7343 $linealreadyfound = $tmpobj->nb;
7348 if ($linealreadyfound) {
7349 if ($this->array_options[
"options_".$key] ===
null) {
7350 $sql =
"UPDATE ".$this->db->prefix().$table_element.
"_extrafields SET ".$key.
" = null";
7352 $sql =
"UPDATE ".$this->db->prefix().$table_element.
"_extrafields SET ".$key.
" = '".$this->db->escape($new_array_options[
"options_".$key]).
"'";
7354 $sql .=
" WHERE fk_object = ".((int) $this->
id);
7356 $resql = $this->db->query($sql);
7359 $this->error = $this->db->lasterror();
7362 $result = $this->insertExtraFields(
'', $user);
7369 $parameters = array(
'key' => $key);
7371 $reshook = $hookmanager->executeHooks(
'updateExtraFieldBeforeCommit', $parameters, $this, $action);
7377 if (!$error && $trigger) {
7379 $this->context = array(
'extrafieldupdate' => 1);
7380 $result = $this->call_trigger($trigger, $userused);
7388 dol_syslog(__METHOD__.$this->error, LOG_ERR);
7389 $this->db->rollback();
7392 $this->db->commit();
7408 return $this->array_options[
'options_'.$key] ??
null;
7420 $this->array_options[
'options_'.$key] = $value;
7435 global
$conf, $langs, $user;
7437 if (empty($userused)) {
7466 public function showInputField($val, $key, $value, $moreparam =
'', $keysuffix =
'', $keyprefix =
'', $morecss = 0, $nonewbutton = 0)
7468 global
$conf, $langs, $form;
7472 if (!is_object($form)) {
7473 require_once DOL_DOCUMENT_ROOT.
'/core/class/html.form.class.php';
7474 $form =
new Form($this->db);
7477 if (!empty($this->fields)) {
7478 $val = $this->fields[$key];
7482 $fieldValidationErrorMsg =
'';
7483 $validationClass =
'';
7484 $fieldValidationErrorMsg = $this->getFieldError($key);
7485 if (!empty($fieldValidationErrorMsg)) {
7486 $validationClass =
' --error';
7488 $validationClass =
' --success';
7496 $param[
'options'] = array();
7499 $size = !empty($this->fields[$key][
'size']) ? $this->fields[$key][
'size'] : 0;
7501 if (preg_match(
'/^(integer|link):(.*):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
7502 $param[
'options'] = array($reg[2].
':'.$reg[3].
':'.$reg[4].
':'.$reg[5] =>
'N');
7504 } elseif (preg_match(
'/^(integer|link):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
7505 $param[
'options'] = array($reg[2].
':'.$reg[3].
':'.$reg[4] =>
'N');
7507 } elseif (preg_match(
'/^(integer|link):(.*):(.*)/i', $val[
'type'], $reg)) {
7508 $param[
'options'] = array($reg[2].
':'.$reg[3] =>
'N');
7510 } elseif (preg_match(
'/^(sellist):(.*):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
7511 $param[
'options'] = array($reg[2].
':'.$reg[3].
':'.$reg[4].
':'.$reg[5] =>
'N');
7513 } elseif (preg_match(
'/^(sellist):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
7514 $param[
'options'] = array($reg[2].
':'.$reg[3].
':'.$reg[4] =>
'N');
7516 } elseif (preg_match(
'/^(sellist):(.*):(.*)/i', $val[
'type'], $reg)) {
7517 $param[
'options'] = array($reg[2].
':'.$reg[3] =>
'N');
7519 } elseif (preg_match(
'/^chkbxlst:(.*)/i', $val[
'type'], $reg)) {
7520 $param[
'options'] = array($reg[1] =>
'N');
7522 } elseif (preg_match(
'/varchar\((\d+)\)/', $val[
'type'], $reg)) {
7523 $param[
'options'] = array();
7526 } elseif (preg_match(
'/varchar/', $val[
'type'])) {
7527 $param[
'options'] = array();
7529 } elseif (preg_match(
'/stars\((\d+)\)/', $val[
'type'], $reg)) {
7530 $param[
'options'] = array();
7534 $param[
'options'] = array();
7535 $type = $this->fields[$key][
'type'];
7540 if (!empty($this->fields[$key][
'arrayofkeyval']) && is_array($this->fields[$key][
'arrayofkeyval'])) {
7541 $param[
'options'] = $this->fields[$key][
'arrayofkeyval'];
7543 if (empty($this->fields[$key][
'multiinput'])) {
7544 $type = (($this->fields[$key][
'type'] ==
'checkbox') ? $this->fields[$key][
'type'] :
'select');
7548 $label = $this->fields[$key][
'label'];
7551 $default = (!empty($this->fields[$key][
'default']) ? $this->fields[$key][
'default'] :
'');
7553 $computed = (!empty($this->fields[$key][
'computed']) ? $this->fields[$key][
'computed'] :
'');
7555 $unique = (!empty($this->fields[$key][
'unique']) ? $this->fields[$key][
'unique'] : 0);
7557 $required = (!empty($this->fields[$key][
'required']) ? $this->fields[$key][
'required'] : 0);
7559 $autofocusoncreate = (!empty($this->fields[$key][
'autofocusoncreate']) ? $this->fields[$key][
'autofocusoncreate'] : 0);
7561 $placeholder = (!empty($this->fields[$key][
'placeholder']) ? $this->fields[$key][
'placeholder'] : 0);
7564 $langfile = (!empty($this->fields[$key][
'langfile']) ? $this->fields[$key][
'langfile'] :
'');
7566 $list = (!empty($this->fields[$key][
'list']) ? $this->fields[$key][
'list'] : 0);
7567 $hidden = (in_array(abs($this->fields[$key][
'visible']), array(0, 2)) ? 1 : 0);
7572 if (!preg_match(
'/^search_/', $keyprefix)) {
7573 return '<span class="opacitymedium">'.$langs->trans(
"AutomaticallyCalculated").
'</span>';
7580 if (empty($morecss) && !empty($val[
'css'])) {
7581 $morecss = $val[
'css'];
7582 } elseif (empty($morecss)) {
7583 if ($type ==
'date') {
7584 $morecss =
'minwidth100imp';
7585 } elseif ($type ==
'datetime' || $type ==
'link') {
7586 $morecss =
'minwidth200imp';
7587 } elseif (in_array($type, array(
'int',
'integer',
'price')) || preg_match(
'/^double(\([0-9],[0-9]\)){0,1}/', (
string) $type)) {
7588 $morecss =
'maxwidth75';
7589 } elseif ($type ==
'url') {
7590 $morecss =
'minwidth400';
7591 } elseif ($type ==
'boolean') {
7594 if (is_numeric($size) && round((
float) $size) < 12) {
7595 $morecss =
'minwidth100';
7596 } elseif (is_numeric($size) && round((
float) $size) <= 48) {
7597 $morecss =
'minwidth200';
7599 $morecss =
'minwidth400';
7605 if (!empty($validationClass)) {
7606 $morecss .= $validationClass;
7609 if (in_array($type, array(
'date'))) {
7610 $tmp = explode(
',', $size);
7615 if (!$required && $value ==
'') {
7620 $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required,
'', 1, (($keyprefix !=
'search_' && $keyprefix !=
'search_options_') ? 1 : 0), 0, 1);
7621 } elseif (in_array($type, array(
'datetime'))) {
7622 $tmp = explode(
',', $size);
7627 if (!$required && $value ==
'') {
7632 $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required,
'', 1, (($keyprefix !=
'search_' && $keyprefix !=
'search_options_') ? 1 : 0), 0, 1,
'',
'',
'', 1,
'',
'',
'tzuserrel');
7633 } elseif (in_array($type, array(
'duration'))) {
7634 $out = $form->select_duration($keyprefix.$key.$keysuffix, $value, 0,
'text', 0, 1);
7635 } elseif (in_array($type, array(
'int',
'integer'))) {
7636 $tmp = explode(
',', $size);
7638 $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' :
'').
'>';
7639 } elseif (in_array($type, array(
'real'))) {
7640 $out =
'<input type="text" class="flat '.$morecss.
'" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.
dol_escape_htmltag($value).
'"'.($moreparam ? $moreparam :
'').($autofocusoncreate ?
' autofocus' :
'').
'>';
7641 } elseif (preg_match(
'/varchar/', (
string) $type)) {
7642 $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 :
'').($placeholder ?
' placeholder="'.
dolPrintHTMLForAttribute($placeholder).
'"' :
'').($autofocusoncreate ?
' autofocus' :
'').
'>';
7643 } elseif (in_array($type, array(
'email',
'mail',
'phone',
'url',
'ip'))) {
7644 $out =
'<input type="text" class="flat '.$morecss.
'" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.
dol_escape_htmltag($value).
'" '.($moreparam ? $moreparam :
'').($autofocusoncreate ?
' autofocus' :
'').
'>';
7645 } elseif (preg_match(
'/^text/', (
string) $type)) {
7646 if (!preg_match(
'/search_/', $keyprefix)) {
7647 if (!empty($param[
'options'])) {
7650 $out .= $form->selectarray($keyprefix.$key.$keysuffix.
"_multiinput", $param[
'options'],
'', 1, 0, 0,
"flat maxwidthonphone".$morecss);
7651 $out .=
'<input id="'.$keyprefix.$key.$keysuffix.
'_multiinputadd" type="button" class="button" value="'.$langs->trans(
"Add").
'">';
7654 function handlemultiinputdisabling(htmlname){
7655 console.log("We handle the disabling of used options for "+htmlname+"_multiinput");
7656 multiinput = $("#"+htmlname+"_multiinput");
7657 multiinput.find("option").each(function(){
7658 tmpval = $("#"+htmlname).val();
7659 tmpvalarray = tmpval.split("\n");
7660 valtotest = $(this).val();
7661 if(tmpvalarray.includes(valtotest)){
7662 $(this).prop("disabled",true);
7664 if($(this).prop("disabled") == true){
7665 console.log(valtotest)
7666 $(this).prop("disabled", false);
7672 $(document).ready(function () {
7673 $("#'.$keyprefix.$key.$keysuffix.
'_multiinputadd").on("click",function() {
7674 tmpval = $("#'.$keyprefix.$key.$keysuffix.
'").val();
7675 tmpvalarray = tmpval.split(",");
7676 valtotest = $("#'.$keyprefix.$key.$keysuffix.
'_multiinput").val();
7677 if(valtotest != -1 && !tmpvalarray.includes(valtotest)){
7678 console.log("We add the selected value to the text area '.$keyprefix.$key.$keysuffix.
'");
7682 tmpval = tmpval + "\n" + valtotest;
7684 $("#'.$keyprefix.$key.$keysuffix.
'").val(tmpval);
7685 handlemultiinputdisabling("'.$keyprefix.$key.$keysuffix.
'");
7686 $("#'.$keyprefix.$key.$keysuffix.
'_multiinput").val(-1);
7688 console.log("We add nothing the text area '.$keyprefix.$key.$keysuffix.
'");
7691 $("#'.$keyprefix.$key.$keysuffix.
'").on("change",function(){
7692 handlemultiinputdisabling("'.$keyprefix.$key.$keysuffix.
'");
7694 handlemultiinputdisabling("'.$keyprefix.$key.$keysuffix.
'");
7696 $out .=
"</script>";
7697 $value = str_replace(
',',
"\n", $value);
7699 require_once DOL_DOCUMENT_ROOT.
'/core/class/doleditor.class.php';
7700 $doleditor =
new DolEditor($keyprefix.$key.$keysuffix, $value,
'', 200,
'dolibarr_notes',
'In',
false,
false,
false, ROWS_5,
'90%');
7701 $out .= (string) $doleditor->Create(1,
'',
true,
'',
'',
'', $morecss);
7703 $out =
'<input type="text" class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.
dol_escape_htmltag($value).
'" '.($moreparam ? $moreparam :
'').
'>';
7705 } elseif (preg_match(
'/^html/', (
string) $type)) {
7706 if (!preg_match(
'/search_/', $keyprefix)) {
7707 require_once DOL_DOCUMENT_ROOT.
'/core/class/doleditor.class.php';
7708 $doleditor =
new DolEditor($keyprefix.$key.$keysuffix, $value,
'', 200,
'dolibarr_notes',
'In',
false,
false, isModEnabled(
'fckeditor') &&
getDolGlobalInt(
'FCKEDITOR_ENABLE_SOCIETE'), ROWS_5,
'90%');
7709 $out = (string) $doleditor->Create(1,
'',
true,
'',
'', $moreparam, $morecss);
7711 $out =
'<input type="text" class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.
dol_escape_htmltag($value).
'" '.($moreparam ? $moreparam :
'').
'>';
7713 } elseif ($type ==
'boolean') {
7715 if (!empty($value)) {
7716 $checked =
' checked value="1" ';
7718 $checked =
' value="1" ';
7720 $out =
'<input type="checkbox" class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" '.$checked.
' '.($moreparam ? $moreparam :
'').
'>';
7721 } elseif ($type ==
'price') {
7722 if (!empty($value)) {
7723 $value =
price($value);
7725 $out =
'<input type="text" class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.$value.
'" '.($moreparam ? $moreparam :
'').
'> '.$langs->getCurrencySymbol(
$conf->currency);
7726 } elseif ($type ==
'stars') {
7727 $out =
'<input type="hidden" class="flat '.$morecss.
'" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.
dol_escape_htmltag($value).
'"'.($moreparam ? $moreparam :
'').($autofocusoncreate ?
' autofocus' :
'').
'>';
7728 $out .=
'<div class="star-selection" id="'.$keyprefix.$key.$keysuffix.
'_selection">';
7730 while ($i <= $size) {
7731 $out .=
'<span class="star" data-value="'.$i.
'">'.
img_picto(
'',
'fontawesome_star_fas').
'</span>';
7736 jQuery(function($) {
7737 let container = $("#'.$keyprefix.$key.$keysuffix.
'_selection");
7738 let selectedStars = parseInt($("#'.$keyprefix.$key.$keysuffix.
'").val()) || 0;
7739 container.find(".star").each(function() {
7740 $(this).toggleClass("active", $(this).data("value") <= selectedStars);
7742 container.find(".star").on("mouseover", function() {
7743 let selectedStar = $(this).data("value");
7744 container.find(".star").each(function() {
7745 $(this).toggleClass("active", $(this).data("value") <= selectedStar);
7748 container.on("mouseout", function() {
7749 container.find(".star").each(function() {
7750 $(this).toggleClass("active", $(this).data("value") <= selectedStars);
7753 container.find(".star").off("click").on("click", function() {
7754 selectedStars = $(this).data("value");
7755 if (selectedStars === 1 && $("#'.$keyprefix.$key.$keysuffix.
'").val() == 1) {
7758 $("#'.$keyprefix.$key.$keysuffix.
'").val(selectedStars);
7759 container.find(".star").each(function() {
7760 $(this).toggleClass("active", $(this).data("value") <= selectedStars);
7765 } elseif (preg_match(
'/^double(\([0-9],[0-9]\)){0,1}/', (
string) $type)) {
7766 if (!empty($value)) {
7767 $value =
price($value);
7769 $out =
'<input type="text" class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.$value.
'" '.($moreparam ? $moreparam :
'').
'> ';
7770 } elseif ($type ==
'select') {
7773 include_once DOL_DOCUMENT_ROOT.
'/core/lib/ajax.lib.php';
7774 $out .=
ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
7780 foreach ($param[
'options'] as $keyb => $valb) {
7781 if ((
string) $keyb ==
'') {
7784 if (strpos($valb,
"|") !==
false) {
7785 list($valb, $parent) = explode(
'|', $valb);
7788 $tmpselect .=
'<option value="'.$keyb.
'"';
7789 $tmpselect .= (((string) $value == (
string) $keyb) ?
' selected' :
'');
7790 if (!empty($parent)) {
7793 $tmpselect .= (!empty($parent) ?
' parent="'.$parent.
'"' :
'');
7794 $tmpselect .=
'>'.$langs->trans($valb).
'</option>';
7797 $out .=
'<select class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" '.($moreparam ? $moreparam :
'').
'>';
7798 if ((!isset($this->fields[$key][
'default'])) || empty($this->fields[$key][
'notnull']) || ($this->fields[$key][
'notnull'] != 1) || $nbchoice >= 2) {
7799 $out .=
'<option value="0"> </option>';
7802 $out .=
'</select>';
7803 } elseif ($type ==
'sellist') {
7806 include_once DOL_DOCUMENT_ROOT.
'/core/lib/ajax.lib.php';
7807 $out .=
ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
7810 $out .=
'<select class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" '.($moreparam ? $moreparam :
'').
'>';
7811 if (is_array($param[
'options'])) {
7812 $tmpparamoptions = array_keys($param[
'options']);
7813 $paramoptions = preg_split(
'/[\r\n]+/', $tmpparamoptions[0]);
7815 $InfoFieldList = explode(
":", $paramoptions[0], 5);
7827 if (! empty($InfoFieldList[4])) {
7829 $parenthesisopen = 0;
7830 while (substr($InfoFieldList[4], $pos, 1) !==
'' && ($parenthesisopen || $pos == 0 || substr($InfoFieldList[4], $pos, 1) !=
':')) {
7831 if (substr($InfoFieldList[4], $pos, 1) ==
'(') {
7834 if (substr($InfoFieldList[4], $pos, 1) ==
')') {
7839 $tmpbefore = substr($InfoFieldList[4], 0, $pos);
7840 $tmpafter = substr($InfoFieldList[4], $pos + 1);
7842 $InfoFieldList[4] = $tmpbefore;
7843 if ($tmpafter !==
'') {
7844 $InfoFieldList = array_merge($InfoFieldList, explode(
':', $tmpafter));
7850 if (preg_match(
'/^\(?([a-z0-9]+)([=<>]+)(\d+)\)?$/i', $InfoFieldList[4], $reg)) {
7851 $InfoFieldList[4] =
'('.$reg[1].
':'.$reg[2].
':'.$reg[3].
')';
7862 $keyList = (empty($InfoFieldList[2]) ?
'rowid' : $InfoFieldList[2].
' as rowid');
7864 if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
7865 if (strpos($InfoFieldList[4],
'extra.') !==
false) {
7866 $keyList =
'main.'.$InfoFieldList[2].
' as rowid';
7868 $keyList = $InfoFieldList[2].
' as rowid';
7871 if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
7872 list($parentName, $parentField) = explode(
'|', $InfoFieldList[3]);
7873 $keyList .=
', '.$parentField;
7876 $filter_categorie =
false;
7877 if (count($InfoFieldList) > 5) {
7878 if ($InfoFieldList[0] ==
'categorie') {
7879 $filter_categorie =
true;
7883 if (!$filter_categorie) {
7884 $fields_label = explode(
'|', $InfoFieldList[1]);
7885 if (is_array($fields_label)) {
7887 $keyList .= implode(
', ', $fields_label);
7891 $sql =
"SELECT " . $keyList;
7892 $sql .=
" FROM " . $this->db->prefix() . $InfoFieldList[0];
7894 if (!empty($InfoFieldList[4])) {
7896 if (strpos($InfoFieldList[4],
'$SEL$') !==
false) {
7897 $InfoFieldList[4] = str_replace(
'$SEL$',
'SELECT', $InfoFieldList[4]);
7901 if (strpos($InfoFieldList[4],
'$ID$') !==
false && !empty($objectid)) {
7902 $InfoFieldList[4] = str_replace(
'$ID$', (
string) $objectid, $InfoFieldList[4]);
7904 $InfoFieldList[4] = str_replace(
'$ID$',
'0', $InfoFieldList[4]);
7909 if (strpos($InfoFieldList[4],
'extra') !==
false) {
7910 $sql .=
" as main, " . $this->db->sanitize($this->db->prefix() . $InfoFieldList[0]) .
"_extrafields as extra";
7911 $sqlwhere .=
" WHERE extra.fk_object = main." . $this->db->sanitize($InfoFieldList[2]);
7917 $sqlwhere .=
' WHERE 1=1';
7934 if (in_array($InfoFieldList[0], array(
'tablewithentity'))) {
7935 $sqlwhere .=
" AND entity = " . ((int)
$conf->entity);
7940 if (isset($InfoFieldList[7]) && preg_match(
'/^[a-z0-9_\-,]+$/i', $InfoFieldList[7])) {
7941 $sql .=
" ORDER BY ".$this->db->escape($InfoFieldList[7]);
7943 $sql .=
" ORDER BY ".$this->db->sanitize(implode(
', ', $fields_label));
7946 dol_syslog(get_class($this) .
'::showInputField type=sellist', LOG_DEBUG);
7947 $resql = $this->db->query($sql);
7949 $out .=
'<option value="0"> </option>';
7950 $num = $this->db->num_rows($resql);
7954 $obj = $this->db->fetch_object($resql);
7958 $fields_label = explode(
'|', $InfoFieldList[1]);
7959 if (count($fields_label) > 1) {
7961 foreach ($fields_label as $field_toshow) {
7962 $labeltoshow .= $obj->$field_toshow .
' ';
7965 $labeltoshow = $obj->{$InfoFieldList[1]};
7967 $labeltoshow =
dol_trunc($labeltoshow, 45);
7969 if ($value == $obj->rowid) {
7970 foreach ($fields_label as $field_toshow) {
7971 $translabel = $langs->trans($obj->$field_toshow);
7972 if ($translabel != $obj->$field_toshow) {
7973 $labeltoshow =
dol_trunc($translabel) .
' ';
7975 $labeltoshow =
dol_trunc($obj->$field_toshow) .
' ';
7978 $out .=
'<option value="' . $obj->rowid .
'" selected>' . $labeltoshow .
'</option>';
7981 $translabel = $langs->trans($obj->{$InfoFieldList[1]});
7982 if ($translabel != $obj->{$InfoFieldList[1]}) {
7983 $labeltoshow =
dol_trunc($translabel, 18);
7985 $labeltoshow =
dol_trunc($obj->{$InfoFieldList[1]});
7988 if (empty($labeltoshow)) {
7989 $labeltoshow =
'(not defined)';
7991 if ($value == $obj->rowid) {
7992 $out .=
'<option value="' . $obj->rowid .
'" selected>' . $labeltoshow .
'</option>';
7995 if (!empty($InfoFieldList[3]) && $parentField) {
7996 $parent = $parentName .
':' . $obj->{$parentField};
8000 $out .=
'<option value="' . $obj->rowid .
'"';
8001 $out .= ($value == $obj->rowid ?
' selected' :
'');
8002 $out .= (!empty($parent) ?
' parent="' . $parent .
'"' :
'');
8003 $out .=
'>' . $labeltoshow .
'</option>';
8008 $this->db->free($resql);
8010 print
'Error in request ' . $sql .
' ' . $this->db->lasterror() .
'. Check setup of extra parameters.<br>';
8013 require_once DOL_DOCUMENT_ROOT.
'/categories/class/categorie.class.php';
8014 $data = $form->select_all_categories(Categorie::$MAP_ID_TO_CODE[$InfoFieldList[5]],
'',
'parent', 64, $InfoFieldList[6], 1, 1);
8015 $out .=
'<option value="0"> </option>';
8016 foreach ($data as $data_key => $data_value) {
8017 $out .=
'<option value="' . $data_key .
'"';
8018 $out .= ($value == $data_key ?
' selected' :
'');
8019 $out .=
'>' . $data_value .
'</option>';
8023 $out .=
'</select>';
8024 } elseif ($type ==
'checkbox') {
8025 $value_arr = explode(
',', $value);
8026 $out = $form->multiselectarray($keyprefix.$key.$keysuffix, (empty($param[
'options']) ?
null : $param[
'options']), $value_arr, 0, 0, $morecss, 0,
'100%');
8027 } elseif ($type ==
'radio') {
8029 foreach ($param[
'options'] as $keyopt => $valopt) {
8030 $out .=
'<input class="flat '.$morecss.
'" type="radio" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" '.($moreparam ? $moreparam :
'');
8031 $out .=
' value="'.$keyopt.
'"';
8032 $out .=
' id="'.$keyprefix.$key.$keysuffix.
'_'.$keyopt.
'"';
8033 $out .= ($value == $keyopt ?
'checked' :
'');
8034 $out .=
'/><label for="'.$keyprefix.$key.$keysuffix.
'_'.$keyopt.
'">'.$valopt.
'</label><br>';
8036 } elseif ($type ==
'chkbxlst') {
8037 if (is_array($value)) {
8038 $value_arr = $value;
8040 $value_arr = explode(
',', $value);
8043 if (is_array($param[
'options'])) {
8044 $tmpparamoptions = array_keys($param[
'options']);
8045 $paramoptions = preg_split(
'/[\r\n]+/', $tmpparamoptions[0]);
8047 $InfoFieldList = explode(
":", $paramoptions[0], 5);
8059 if (! empty($InfoFieldList[4])) {
8061 $parenthesisopen = 0;
8062 while (substr($InfoFieldList[4], $pos, 1) !==
'' && ($parenthesisopen || $pos == 0 || substr($InfoFieldList[4], $pos, 1) !=
':')) {
8063 if (substr($InfoFieldList[4], $pos, 1) ==
'(') {
8066 if (substr($InfoFieldList[4], $pos, 1) ==
')') {
8071 $tmpbefore = substr($InfoFieldList[4], 0, $pos);
8072 $tmpafter = substr($InfoFieldList[4], $pos + 1);
8074 $InfoFieldList[4] = $tmpbefore;
8075 if ($tmpafter !==
'') {
8076 $InfoFieldList = array_merge($InfoFieldList, explode(
':', $tmpafter));
8081 if (preg_match(
'/^\(?([a-z0-9]+)([=<>]+)(\d+)\)?$/i', $InfoFieldList[4], $reg)) {
8082 $InfoFieldList[4] =
'('.$reg[1].
':'.$reg[2].
':'.$reg[3].
')';
8090 '@phan-var-force array{0:string,1:string,2:string,3:string,3:string,5:string,6:string} $InfoFieldList';
8095 $keyList = (empty($InfoFieldList[2]) ?
'rowid' : $InfoFieldList[2].
' as rowid');
8097 if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
8098 list($parentName, $parentField) = explode(
'|', $InfoFieldList[3]);
8099 $keyList .=
', '.$parentField;
8101 if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
8102 if (strpos($InfoFieldList[4],
'extra.') !==
false) {
8103 $keyList =
'main.'.$InfoFieldList[2].
' as rowid';
8105 $keyList = $InfoFieldList[2].
' as rowid';
8109 $filter_categorie =
false;
8110 if (count($InfoFieldList) > 5) {
8111 if ($InfoFieldList[0] ==
'categorie') {
8112 $filter_categorie =
true;
8117 if (!$filter_categorie) {
8118 $fields_label = explode(
'|', $InfoFieldList[1]);
8119 if (is_array($fields_label)) {
8121 $keyList .= implode(
', ', $fields_label);
8125 $sql =
"SELECT " . $keyList;
8126 $sql .=
' FROM ' . $this->db->prefix() . $InfoFieldList[0];
8128 if (!empty($InfoFieldList[4])) {
8130 if (strpos($InfoFieldList[4],
'$SEL$') !==
false) {
8131 $InfoFieldList[4] = str_replace(
'$SEL$',
'SELECT', $InfoFieldList[4]);
8135 if (strpos($InfoFieldList[4],
'$ID$') !==
false && !empty($objectid)) {
8136 $InfoFieldList[4] = str_replace(
'$ID$', (
string) $objectid, $InfoFieldList[4]);
8138 $InfoFieldList[4] = str_replace(
'$ID$',
'0', $InfoFieldList[4]);
8143 if (strpos($InfoFieldList[4],
'extra') !==
false) {
8144 $sql .=
' as main, ' . $this->db->sanitize($this->db->prefix() . $InfoFieldList[0]) .
'_extrafields as extra';
8145 $sqlwhere .=
" WHERE extra.fk_object = main." . $this->db->sanitize($InfoFieldList[2]);
8146 $sqlwhere .=
" AND " . $InfoFieldList[4];
8148 $sqlwhere .=
" WHERE " . $InfoFieldList[4];
8151 $sqlwhere .=
' WHERE 1=1';
8168 if (in_array($InfoFieldList[0], array(
'tablewithentity'))) {
8169 $sqlwhere .=
" AND entity = " . ((int)
$conf->entity);
8176 dol_syslog(get_class($this) .
'::showInputField type=chkbxlst', LOG_DEBUG);
8178 $resql = $this->db->query($sql);
8180 $num = $this->db->num_rows($resql);
8187 $obj = $this->db->fetch_object($resql);
8191 $fields_label = explode(
'|', $InfoFieldList[1]);
8192 if (count($fields_label) > 1) {
8194 foreach ($fields_label as $field_toshow) {
8195 $labeltoshow .= $obj->$field_toshow .
' ';
8198 $labeltoshow = $obj->{$InfoFieldList[1]};
8200 $labeltoshow =
dol_trunc($labeltoshow, 45);
8202 if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
8203 foreach ($fields_label as $field_toshow) {
8204 $translabel = $langs->trans($obj->$field_toshow);
8205 if ($translabel != $obj->$field_toshow) {
8206 $labeltoshow =
dol_trunc($translabel, 18) .
' ';
8208 $labeltoshow =
dol_trunc($obj->$field_toshow, 18) .
' ';
8212 $data[$obj->rowid] = $labeltoshow;
8215 $translabel = $langs->trans($obj->{$InfoFieldList[1]});
8216 if ($translabel != $obj->{$InfoFieldList[1]}) {
8217 $labeltoshow =
dol_trunc($translabel, 18);
8219 $labeltoshow =
dol_trunc($obj->{$InfoFieldList[1]}, 18);
8222 if (empty($labeltoshow)) {
8223 $labeltoshow =
'(not defined)';
8226 if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
8227 $data[$obj->rowid] = $labeltoshow;
8230 if (!empty($InfoFieldList[3]) && $parentField) {
8231 $parent = $parentName .
':' . $obj->{$parentField};
8235 $data[(int) $obj->rowid] = $labeltoshow;
8240 $this->db->free($resql);
8242 $out = $form->multiselectarray($keyprefix . $key . $keysuffix, $data, $value_arr, 0, 0, $morecss, 0,
'100%');
8244 print
'Error in request ' . $sql .
' ' . $this->db->lasterror() .
'. Check setup of extra parameters.<br>';
8247 require_once DOL_DOCUMENT_ROOT.
'/categories/class/categorie.class.php';
8248 $data = $form->select_all_categories(Categorie::$MAP_ID_TO_CODE[(
int) $InfoFieldList[5]],
'',
'parent', 64, $InfoFieldList[6], 1, 1);
8249 $out = $form->multiselectarray($keyprefix . $key . $keysuffix, $data, $value_arr, 0, 0, $morecss, 0,
'100%');
8252 } elseif ($type ==
'link') {
8255 $param_list = array_keys($param[
'options']);
8256 $param_list_array = explode(
':', $param_list[0], 4);
8258 $showempty = (($required && $default !=
'') ? 0 : 1);
8260 if (!preg_match(
'/search_/', $keyprefix)) {
8261 if (!empty($param_list_array[2])) {
8263 if (!empty($this->fields[$key][
'picto'])) {
8264 $morecss .=
' widthcentpercentminusxx';
8266 $morecss .=
' widthcentpercentminusx';
8270 if (!empty($this->fields[$key][
'picto'])) {
8271 $morecss .=
' widthcentpercentminusx';
8275 $objectfield = $this->element.($this->module ?
'@'.$this->module :
'').
':'.$key.$keysuffix;
8276 $out = $form->selectForForms($param_list_array[0], $keyprefix.$key.$keysuffix, $value, $showempty,
'',
'', $morecss, $moreparam, 0, (empty($val[
'disabled']) ? 0 : 1),
'', $objectfield);
8278 if (!empty($param_list_array[2])) {
8279 if ((!GETPOSTISSET(
'backtopage') || strpos(
GETPOST(
'backtopage'), $_SERVER[
'PHP_SELF']) === 0)
8280 && empty($val[
'disabled']) && empty($nonewbutton)) {
8281 list($class, $classfile) = explode(
':', $param_list[0]);
8282 if (file_exists(
dol_buildpath(dirname(dirname($classfile)).
'/card.php'))) {
8283 $url_path =
dol_buildpath(dirname(dirname($classfile)).
'/card.php', 1);
8285 $url_path =
dol_buildpath(dirname(dirname($classfile)).
'/'.strtolower($class).
'_card.php', 1);
8287 $paramforthenewlink =
'';
8288 $paramforthenewlink .= (GETPOSTISSET(
'action') ?
'&action='.GETPOST(
'action',
'aZ09') :
'');
8289 $paramforthenewlink .= (GETPOSTISSET(
'id') ?
'&id='.GETPOSTINT(
'id') :
'');
8290 $paramforthenewlink .= (GETPOSTISSET(
'origin') ?
'&origin='.GETPOST(
'origin',
'aZ09') :
'');
8291 $paramforthenewlink .= (GETPOSTISSET(
'originid') ?
'&originid='.GETPOSTINT(
'originid') :
'');
8292 $paramforthenewlink .=
'&fk_'.strtolower($class).
'=--IDFORBACKTOPAGE--';
8294 $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>';
8297 } elseif ($type ==
'password') {
8299 if ($keyprefix.$key.$keysuffix ==
'pass_crypted') {
8300 $out =
'<input type="'.($keyprefix ==
'search_' ?
'text' :
'password').
'" class="flat '.$morecss.
'" name="pass" id="pass" value="" '.($moreparam ? $moreparam :
'').
'>';
8301 $out .=
'<input type="hidden" name="pass_crypted" id="pass_crypted" value="'.$value.
'" '.($moreparam ? $moreparam :
'').
'>';
8303 $out =
'<input type="'.($keyprefix ==
'search_' ?
'text' :
'password').
'" class="flat '.$morecss.
'" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.$value.
'" '.($moreparam ? $moreparam :
'').
'>';
8305 } elseif ($type ==
'array') {
8307 $newval[
'type'] =
'varchar(256)';
8310 if (!empty($value)) {
8311 foreach ($value as $option) {
8312 $out .=
'<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).
'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
8313 $out .= $this->showInputField($newval, $keyprefix.$key.$keysuffix.
'[]', $option, $moreparam,
'',
'', $morecss).
'<br></span>';
8316 $out .=
'<a id="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).
'_add" href="javascript:;"><span class="fa fa-plus-circle valignmiddle"></span></a>';
8318 $newInput =
'<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).
'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
8319 $newInput .= $this->showInputField($newval, $keyprefix.$key.$keysuffix.
'[]',
'', $moreparam,
'',
'', $morecss).
'<br></span>';
8321 if (!empty(
$conf->use_javascript_ajax)) {
8323 <script nonce="'.getNonce().
'">
8324 $(document).ready(function() {
8325 $("a#'.
dol_escape_js($keyprefix.$key.$keysuffix).
'_add").click(function() {
8329 $(document).on("click", "a.'.
dol_escape_js($keyprefix.$key.$keysuffix).
'_del", function() {
8330 $(this).parent().remove();
8336 if (!empty($hidden)) {
8337 $out =
'<input type="hidden" value="'.$value.
'" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'"/>';
8340 if ($isDependList == 1) {
8341 $out .= $this->getJSListDependancies(
'_common');
8349 if (!empty($fieldValidationErrorMsg) && function_exists(
'getFieldErrorIcon')) {
8350 $out .=
' '.getFieldErrorIcon($fieldValidationErrorMsg);
8369 public function showOutputField($val, $key, $value, $moreparam =
'', $keysuffix =
'', $keyprefix =
'', $morecss =
'')
8371 global
$conf, $langs, $form;
8375 if (!is_object($form)) {
8376 require_once DOL_DOCUMENT_ROOT.
'/core/class/html.form.class.php';
8377 $form =
new Form($this->db);
8381 $type = empty($val[
'type']) ?
'' : $val[
'type'];
8382 $size = empty($val[
'css']) ?
'' : $val[
'css'];
8386 if (preg_match(
'/varchar\((\d+)\)/', $type, $reg)) {
8389 } elseif (preg_match(
'/varchar/', $type)) {
8392 if (!empty($val[
'arrayofkeyval']) && is_array($val[
'arrayofkeyval'])) {
8394 if (empty($this->fields[$key][
'multiinput'])) {
8395 $type = (($this->fields[$key][
'type'] ==
'checkbox') ? $this->fields[$key][
'type'] :
'select');
8398 if (preg_match(
'/^integer:(.*):(.*)/i', $val[
'type'], $reg)) {
8402 $default = empty($val[
'default']) ?
'' : $val[
'default'];
8403 $computed = empty($val[
'computed']) ?
'' : $val[
'computed'];
8404 $unique = empty($val[
'unique']) ?
'' : $val[
'unique'];
8405 $required = empty($val[
'required']) ?
'' : $val[
'required'];
8407 $param[
'options'] = array();
8409 if (!empty($val[
'arrayofkeyval']) && is_array($val[
'arrayofkeyval'])) {
8410 $param[
'options'] = $val[
'arrayofkeyval'];
8412 if (preg_match(
'/^integer:([^:]*):([^:]*)/i', $val[
'type'], $reg)) {
8414 $stringforoptions = $reg[1].
':'.$reg[2];
8416 if ($reg[1] ==
'User') {
8417 $stringforoptions .=
':#getnomurlparam1=-1';
8419 $param[
'options'] = array($stringforoptions => $stringforoptions);
8420 } elseif (preg_match(
'/^sellist:(.*):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
8421 $param[
'options'] = array($reg[1].
':'.$reg[2].
':'.$reg[3].
':'.$reg[4] =>
'N');
8423 } elseif (preg_match(
'/^sellist:(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
8424 $param[
'options'] = array($reg[1].
':'.$reg[2].
':'.$reg[3] =>
'N');
8426 } elseif (preg_match(
'/^sellist:(.*):(.*)/i', $val[
'type'], $reg)) {
8427 $param[
'options'] = array($reg[1].
':'.$reg[2] =>
'N');
8429 } elseif (preg_match(
'/^chkbxlst:(.*)/i', $val[
'type'], $reg)) {
8430 $param[
'options'] = array($reg[1] =>
'N');
8432 } elseif (preg_match(
'/stars\((\d+)\)/', $val[
'type'], $reg)) {
8433 $param[
'options'] = array();
8438 $langfile = empty($val[
'langfile']) ?
'' : $val[
'langfile'];
8439 $list = (empty($val[
'list']) ?
'' : $val[
'list']);
8440 $help = (empty($val[
'help']) ?
'' : $val[
'help']);
8441 $hidden = (($val[
'visible'] == 0) ? 1 : 0);
8451 $value =
dol_eval($computed, 1, 0,
'2');
8454 if (empty($morecss)) {
8455 if ($type ==
'date') {
8456 $morecss =
'minwidth100imp';
8457 } elseif ($type ==
'datetime' || $type ==
'timestamp') {
8458 $morecss =
'minwidth200imp';
8459 } elseif (in_array($type, array(
'int',
'double',
'price'))) {
8460 $morecss =
'maxwidth75';
8461 } elseif ($type ==
'url') {
8462 $morecss =
'minwidth400';
8463 } elseif ($type ==
'boolean') {
8466 if (is_numeric($size) && round((
float) $size) < 12) {
8467 $morecss =
'minwidth100';
8468 } elseif (is_numeric($size) && round((
float) $size) <= 48) {
8469 $morecss =
'minwidth200';
8471 $morecss =
'minwidth400';
8477 if (in_array($key, array(
'rowid',
'ref')) && method_exists($this,
'getNomUrl')) {
8479 if ($key !=
'rowid' || empty($this->fields[
'ref'])) {
8480 $value = $this->getNomUrl(1,
'', 0,
'', 1);
8482 } elseif ($key ==
'status' && method_exists($this,
'getLibStatut')) {
8483 $value = $this->getLibStatut(3);
8484 } elseif ($type ==
'date') {
8485 if (!empty($value)) {
8490 } elseif ($type ==
'datetime' || $type ==
'timestamp') {
8491 if (!empty($value)) {
8496 } elseif ($type ==
'duration') {
8497 include_once DOL_DOCUMENT_ROOT.
'/core/lib/date.lib.php';
8498 if (!is_null($value) && $value !==
'') {
8501 } elseif ($type ==
'double' || $type ==
'real') {
8502 if (!is_null($value) && $value !==
'') {
8503 $value =
price($value);
8505 } elseif ($type ==
'boolean') {
8507 if (!empty($value)) {
8508 $checked =
' checked ';
8511 $value =
'<input type="checkbox" '.$checked.
' '.($moreparam ? $moreparam :
'').
' readonly disabled>';
8513 $value =
yn($value ? 1 : 0);
8515 } elseif ($type ==
'mail' || $type ==
'email') {
8517 } elseif ($type ==
'url') {
8519 } elseif ($type ==
'phone') {
8521 } elseif ($type ==
'ip') {
8523 } elseif ($type ==
'stars') {
8524 $value =
'<input type="hidden" class="flat '.$morecss.
'" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.$this->id.
'" value="'.
dol_escape_htmltag($value).
'"'.($moreparam ? $moreparam :
'').
'>';
8525 $value .=
'<div class="star-selection" id="'.$keyprefix.$key.$keysuffix.$this->id.
'_selection">';
8527 while ($i <= $size) {
8528 $value .=
'<span class="star" data-value="'.$i.
'">'.
img_picto(
'',
'fontawesome_star_fas').
'</span>';
8533 $(document).ready(function() {
8534 let container = $("#'.$keyprefix.$key.$keysuffix.$this->id.
'_selection");
8535 let selectedStars = parseInt($("#'.$keyprefix.$key.$keysuffix.$this->id.
'").val()) || 0;
8536 container.find(".star").each(function() {
8537 $(this).toggleClass("active", $(this).data("value") <= selectedStars);
8539 container.find(".star").on("mouseover", function() {
8540 let selectedStar = $(this).data("value");
8541 container.find(".star").each(function() {
8542 $(this).toggleClass("active", $(this).data("value") <= selectedStar);
8545 container.on("mouseout", function() {
8546 container.find(".star").each(function() {
8547 $(this).toggleClass("active", $(this).data("value") <= selectedStars);
8550 container.find(".star").off("click").on("click", function() {
8551 selectedStars = $(this).data("value");
8552 if (selectedStars == 1 && $("#'.$keyprefix.$key.$keysuffix.$this->id.
'").val() == 1) {
8555 container.find("#'.$keyprefix.$key.$keysuffix.$this->id.
'").val(selectedStars);
8556 container.find(".star").each(function() {
8557 $(this).toggleClass("active", $(this).data("value") <= selectedStars);
8560 url: "ajax/'.$this->element.
'.php",
8563 objectId: "'.$this->
id.
'",
8564 field: "'.$keyprefix.$key.$keysuffix.
'",
8565 value: selectedStars,
8568 success: function(response) {
8569 var res = JSON.parse(response);
8570 console[res.status === "success" ? "log" : "error"](res.message);
8572 error: function(xhr, status, error) {
8573 console.log("Ajax request failed while updating '.$keyprefix.$key.$keysuffix.
':", error);
8579 } elseif ($type ==
'price') {
8580 if (!is_null($value) && $value !==
'') {
8581 $value =
price($value, 0, $langs, 0, 0, -1,
$conf->currency);
8583 } elseif ($type ==
'select') {
8584 $value = isset($param[
'options'][(
string) $value]) ? $param[
'options'][(string) $value] :
'';
8585 if (strpos($value,
"|") !==
false) {
8586 $value = $langs->trans(explode(
'|', $value)[0]);
8587 } elseif (! is_numeric($value)) {
8588 $value = $langs->trans($value);
8590 } elseif ($type ==
'sellist') {
8591 $param_list = array_keys($param[
'options']);
8592 $InfoFieldList = explode(
":", $param_list[0]);
8594 $selectkey =
"rowid";
8597 if (count($InfoFieldList) > 2 && !empty($InfoFieldList[2])) {
8598 $selectkey = $InfoFieldList[2];
8599 $keyList = $InfoFieldList[2].
' as rowid';
8602 $fields_label = explode(
'|', $InfoFieldList[1]);
8603 if (is_array($fields_label)) {
8605 $keyList .= implode(
', ', $fields_label);
8608 $filter_categorie =
false;
8609 if (count($InfoFieldList) > 5) {
8610 if ($InfoFieldList[0] ==
'categorie') {
8611 $filter_categorie =
true;
8615 $sql =
"SELECT ".$keyList;
8616 $sql .=
' FROM '.$this->db->prefix().$InfoFieldList[0];
8617 if (isset($InfoFieldList[4]) && strpos($InfoFieldList[4],
'extra') !==
false) {
8620 if ($selectkey ==
'rowid' && empty($value)) {
8621 $sql .=
" WHERE ".$selectkey.
" = 0";
8622 } elseif ($selectkey ==
'rowid') {
8623 $sql .=
" WHERE ".$selectkey.
" = ".((int) $value);
8625 $sql .=
" WHERE ".$selectkey.
" = '".$this->db->escape($value).
"'";
8630 dol_syslog(get_class($this).
':showOutputField:$type=sellist', LOG_DEBUG);
8631 $resql = $this->db->query($sql);
8633 if (!$filter_categorie) {
8635 $numrows = $this->db->num_rows($resql);
8637 $obj = $this->db->fetch_object($resql);
8640 $fields_label = explode(
'|', $InfoFieldList[1]);
8642 if (is_array($fields_label) && count($fields_label) > 1) {
8643 foreach ($fields_label as $field_toshow) {
8645 if (!empty($obj->$field_toshow)) {
8646 $translabel = $langs->trans($obj->$field_toshow);
8648 if ($translabel != $field_toshow) {
8649 $value .=
dol_trunc($translabel, 18) .
' ';
8651 $value .= $obj->$field_toshow .
' ';
8656 if (!empty($obj->{$InfoFieldList[1]})) {
8657 $translabel = $langs->trans($obj->{$InfoFieldList[1]});
8659 if ($translabel != $obj->{$InfoFieldList[1]}) {
8662 $value = $obj->{$InfoFieldList[1]};
8667 require_once DOL_DOCUMENT_ROOT .
'/categories/class/categorie.class.php';
8670 $obj = $this->db->fetch_object($resql);
8672 $c->fetch($obj->rowid);
8673 $ways =
$c->print_all_ways();
8674 foreach ($ways as $way) {
8675 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories"' . (
$c->color ?
' style="background: #' .
$c->color .
';"' :
' style="background: #aaa"') .
'>' .
img_object(
'',
'category') .
' ' . $way .
'</li>';
8677 $value =
'<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(
' ', $toprint).
'</ul></div>';
8680 dol_syslog(get_class($this).
'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
8682 } elseif ($type ==
'radio') {
8683 $value = $param[
'options'][(string) $value];
8684 } elseif ($type ==
'checkbox') {
8685 $value_arr = explode(
',', (
string) $value);
8687 if (is_array($value_arr) && count($value_arr) > 0) {
8689 foreach ($value_arr as $keyval => $valueval) {
8690 if (!empty($valueval)) {
8691 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' . $param[
'options'][$valueval] .
'</li>';
8694 if (!empty($toprint)) {
8695 $value =
'<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">' . implode(
' ', $toprint) .
'</ul></div>';
8698 } elseif ($type ==
'chkbxlst') {
8699 $value_arr = (isset($value) ? explode(
',', $value) : array());
8701 $param_list = array_keys($param[
'options']);
8702 $InfoFieldList = explode(
":", $param_list[0]);
8704 $selectkey =
"rowid";
8707 if (count($InfoFieldList) >= 3) {
8708 $selectkey = $InfoFieldList[2];
8709 $keyList = $InfoFieldList[2].
' as rowid';
8712 $fields_label = explode(
'|', $InfoFieldList[1]);
8713 if (is_array($fields_label)) {
8715 $keyList .= implode(
', ', $fields_label);
8718 $filter_categorie =
false;
8719 if (count($InfoFieldList) > 5) {
8720 if ($InfoFieldList[0] ==
'categorie') {
8721 $filter_categorie =
true;
8725 $sql =
"SELECT ".$keyList;
8726 $sql .=
' FROM '.$this->db->prefix().$InfoFieldList[0];
8727 if (isset($InfoFieldList[4]) && strpos($InfoFieldList[4],
'extra') !==
false) {
8733 dol_syslog(get_class($this).
':showOutputField:$type=chkbxlst', LOG_DEBUG);
8734 $resql = $this->db->query($sql);
8736 if (!$filter_categorie) {
8739 while ($obj = $this->db->fetch_object($resql)) {
8741 $fields_label = explode(
'|', $InfoFieldList[1]);
8742 if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
8743 if (is_array($fields_label) && count($fields_label) > 1) {
8744 foreach ($fields_label as $field_toshow) {
8746 if (!empty($obj->$field_toshow)) {
8747 $translabel = $langs->trans($obj->$field_toshow);
8749 if ($translabel != $field_toshow) {
8750 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' .
dol_trunc($translabel, 18) .
'</li>';
8752 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' . $obj->$field_toshow .
'</li>';
8757 if (!empty($obj->{$InfoFieldList[1]})) {
8758 $translabel = $langs->trans($obj->{$InfoFieldList[1]});
8760 if ($translabel != $obj->{$InfoFieldList[1]}) {
8761 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' .
dol_trunc($translabel, 18) .
'</li>';
8763 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' . $obj->{$InfoFieldList[1]} .
'</li>';
8769 require_once DOL_DOCUMENT_ROOT .
'/categories/class/categorie.class.php';
8772 while ($obj = $this->db->fetch_object($resql)) {
8773 if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
8775 $c->fetch($obj->rowid);
8776 $ways =
$c->print_all_ways();
8777 foreach ($ways as $way) {
8778 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories"' . (
$c->color ?
' style="background: #' .
$c->color .
';"' :
' style="background: #aaa"') .
'>' .
img_object(
'',
'category') .
' ' . $way .
'</li>';
8783 $value =
'<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(
' ', $toprint).
'</ul></div>';
8785 dol_syslog(get_class($this).
'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
8787 } elseif ($type ==
'link') {
8792 $param_list = array_keys($param[
'options']);
8796 $InfoFieldList = explode(
":", $param_list[0]);
8798 $classname = $InfoFieldList[0];
8799 $classpath = $InfoFieldList[1];
8802 $getnomurlparam = 3;
8803 $getnomurlparam2 =
'';
8805 if (preg_match(
'/#getnomurlparam1=([^#]*)/', $param_list[0], $regtmp)) {
8806 $getnomurlparam = $regtmp[1];
8808 if (preg_match(
'/#getnomurlparam2=([^#]*)/', $param_list[0], $regtmp)) {
8809 $getnomurlparam2 = $regtmp[1];
8812 if (!empty($classpath)) {
8815 if ($classname && !class_exists($classname)) {
8819 if ($element_prop) {
8820 $classname = $element_prop[
'classname'];
8825 if ($classname && class_exists($classname)) {
8826 $object =
new $classname($this->db);
8827 '@phan-var-force CommonObject $object';
8828 if (
$object->element ===
'product') {
8829 '@phan-var-force Product $object';
8830 $result =
$object->fetch($value,
'',
'',
'', 0, 1, 1);
8832 $result =
$object->fetch($value);
8835 if (
$object->element ===
'product') {
8836 '@phan-var-force Product $object';
8837 $get_name_url_param_arr = array($getnomurlparam, $getnomurlparam2, 0, -1, 0,
'', 0);
8838 if (isset($val[
'get_name_url_params'])) {
8839 $get_name_url_params = explode(
':', $val[
'get_name_url_params']);
8840 if (!empty($get_name_url_params)) {
8841 $param_num_max = count($get_name_url_param_arr) - 1;
8842 foreach ($get_name_url_params as $param_num => $param_value) {
8843 if ($param_num > $param_num_max) {
8846 $get_name_url_param_arr[$param_num] = $param_value;
8854 $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]);
8856 $value =
$object->getNomUrl($getnomurlparam, $getnomurlparam2);
8863 dol_syslog(
'Error bad setup of extrafield', LOG_WARNING);
8864 return 'Error bad setup of extrafield';
8869 } elseif ($type ==
'password') {
8870 $value =
'<span class="opacitymedium">'.$langs->trans(
"Encrypted").
'</span>';
8872 } elseif ($type ==
'array') {
8873 if (is_array($value)) {
8874 $value = implode(
'<br>', $value);
8876 dol_syslog(__METHOD__.
' Expected array from dol_eval, but got '.gettype($value), LOG_ERR);
8877 return 'Error unexpected result from code evaluation';
8880 if (!empty($value) && preg_match(
'/^text/', (
string) $type) && !preg_match(
'/search_/', $keyprefix) && !empty($param[
'options'])) {
8881 $value = str_replace(
',',
"\n", $value);
8889 return is_null($out) ?
'' : $out;
8901 unset($this->validateFieldsErrors[$fieldKey]);
8915 $msg = $langs->trans(
"UnknownError");
8918 $this->error = $this->validateFieldsErrors[$fieldKey] = $msg;
8929 if (!empty($this->validateFieldsErrors[$fieldKey])) {
8930 return $this->validateFieldsErrors[$fieldKey];
8947 if (!class_exists(
'Validate')) {
8948 require_once DOL_DOCUMENT_ROOT .
'/core/class/validate.class.php';
8951 $this->clearFieldError($fieldKey);
8953 if (!array_key_exists($fieldKey, $fields) || !is_array($fields[$fieldKey])) {
8954 $this->setFieldError($fieldKey, $langs->trans(
'FieldNotFoundInObject'));
8958 $val = $fields[$fieldKey];
8961 $param[
'options'] = array();
8962 $type = $val[
'type'];
8965 if (isset($val[
'notnull']) && $val[
'notnull'] === 1) {
8979 if (preg_match(
'/varchar\((\d+)\)/', $type, $reg)) {
8982 } elseif (preg_match(
'/varchar/', $type)) {
8986 if (!empty($val[
'arrayofkeyval']) && is_array($val[
'arrayofkeyval'])) {
8990 if (!empty($val[
'type']) && preg_match(
'/^integer:(.*):(.*)/i', $val[
'type'], $reg)) {
8994 if (!empty($val[
'arrayofkeyval']) && is_array($val[
'arrayofkeyval'])) {
8995 $param[
'options'] = $val[
'arrayofkeyval'];
8998 if (preg_match(
'/^integer:(.*):(.*)/i', $val[
'type'], $reg)) {
9000 $param[
'options'] = array($reg[1].
':'.$reg[2] => $reg[1].
':'.$reg[2]);
9001 } elseif (preg_match(
'/^sellist:(.*):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
9002 $param[
'options'] = array($reg[1].
':'.$reg[2].
':'.$reg[3].
':'.$reg[4] =>
'N');
9004 } elseif (preg_match(
'/^sellist:(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
9005 $param[
'options'] = array($reg[1].
':'.$reg[2].
':'.$reg[3] =>
'N');
9007 } elseif (preg_match(
'/^sellist:(.*):(.*)/i', $val[
'type'], $reg)) {
9008 $param[
'options'] = array($reg[1].
':'.$reg[2] =>
'N');
9017 $validate =
new Validate($this->db, $langs);
9027 if ($required && !$validate->isNotEmptyString($fieldValue)) {
9028 $this->setFieldError($fieldKey, $validate->error);
9030 } elseif (!$required && !$validate->isNotEmptyString($fieldValue)) {
9036 if (!empty($maxSize) && !$validate->isMaxLength($fieldValue, $maxSize)) {
9037 $this->setFieldError($fieldKey, $validate->error);
9042 if (!empty($minSize) && !$validate->isMinLength($fieldValue, $minSize)) {
9043 $this->setFieldError($fieldKey, $validate->error);
9051 if (in_array($type, array(
'date',
'datetime',
'timestamp'))) {
9052 if (!$validate->isTimestamp($fieldValue)) {
9053 $this->setFieldError($fieldKey, $validate->error);
9058 } elseif ($type ==
'duration') {
9059 if (!$validate->isDuration($fieldValue)) {
9060 $this->setFieldError($fieldKey, $validate->error);
9065 } elseif (in_array($type, array(
'double',
'real',
'price'))) {
9067 if (!$validate->isNumeric($fieldValue)) {
9068 $this->setFieldError($fieldKey, $validate->error);
9073 } elseif ($type ==
'boolean') {
9074 if (!$validate->isBool($fieldValue)) {
9075 $this->setFieldError($fieldKey, $validate->error);
9080 } elseif ($type ==
'mail') {
9081 if (!$validate->isEmail($fieldValue)) {
9082 $this->setFieldError($fieldKey, $validate->error);
9085 } elseif ($type ==
'url') {
9086 if (!$validate->isUrl($fieldValue)) {
9087 $this->setFieldError($fieldKey, $validate->error);
9092 } elseif ($type ==
'phone') {
9093 if (!$validate->isPhone($fieldValue)) {
9094 $this->setFieldError($fieldKey, $validate->error);
9099 } elseif ($type ==
'select' || $type ==
'radio') {
9100 if (!isset($param[
'options'][$fieldValue])) {
9101 $this->error = $langs->trans(
'RequireValidValue');
9106 } elseif ($type ==
'sellist' || $type ==
'chkbxlst') {
9107 $param_list = array_keys($param[
'options']);
9108 $InfoFieldList = explode(
":", $param_list[0]);
9109 $value_arr = explode(
',', $fieldValue);
9110 $value_arr = array_map(array($this->db,
'escape'), $value_arr);
9112 $selectkey =
"rowid";
9113 if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
9114 $selectkey = $InfoFieldList[2];
9117 if (!$validate->isInDb($value_arr, $InfoFieldList[0], $selectkey)) {
9118 $this->setFieldError($fieldKey, $validate->error);
9123 } elseif ($type ==
'link') {
9124 $param_list = array_keys($param[
'options']);
9125 $InfoFieldList = explode(
":", $param_list[0]);
9126 $classname = $InfoFieldList[0];
9127 $classpath = $InfoFieldList[1];
9128 if (!$validate->isFetchable($fieldValue, $classname, $classpath)) {
9129 $lastIsFetchableError = $validate->error;
9132 if ($validate->isFetchableElement($fieldValue, $classname)) {
9136 $this->setFieldError($fieldKey, $lastIsFetchableError);
9160 public function showOptionals($extrafields, $mode =
'view', $params =
null, $keysuffix =
'', $keyprefix =
'', $onetrtd =
'', $display_type =
'card')
9162 global $db,
$conf, $langs, $action, $form, $hookmanager;
9164 if (!is_object($form)) {
9165 $form =
new Form($db);
9167 if (!is_object($extrafields)) {
9168 dol_syslog(
'Bad parameter extrafields for showOptionals', LOG_ERR);
9169 return 'Bad parameter extrafields for showOptionals';
9171 if (!is_array($extrafields->attributes[$this->table_element])) {
9172 dol_syslog(
"extrafields->attributes was not loaded with extrafields->fetch_name_optionals_label(table_element);", LOG_WARNING);
9177 $parameters = array(
'mode' => $mode,
'params' => $params,
'keysuffix' => $keysuffix,
'keyprefix' => $keyprefix,
'display_type' => $display_type);
9178 $reshook = $hookmanager->executeHooks(
'showOptionals', $parameters, $this, $action);
9180 if (empty($reshook)) {
9181 if (is_array($extrafields->attributes[$this->table_element]) && array_key_exists(
'label', $extrafields->attributes[$this->table_element]) && is_array($extrafields->attributes[$this->table_element][
'label']) && count($extrafields->attributes[$this->table_element][
'label']) > 0) {
9183 $out .=
'<!-- commonobject:showOptionals --> ';
9186 $nbofextrafieldsshown = 0;
9189 $lastseparatorkeyfound =
'';
9190 $extrafields_collapse_num =
'';
9191 $extrafields_collapse_num_old =
'';
9194 foreach ($extrafields->attributes[$this->table_element][
'label'] as $key => $label) {
9198 if (is_array($params) && array_key_exists(
'onlykey', $params) && $key != $params[
'onlykey']) {
9204 if ($enabled && isset($extrafields->attributes[$this->table_element][
'enabled'][$key])) {
9205 $enabled = (int)
dol_eval((
string) $extrafields->attributes[$this->table_element][
'enabled'][$key], 1, 1,
'2');
9207 if (empty($enabled)) {
9212 if (isset($extrafields->attributes[$this->table_element][
'list'][$key])) {
9213 $visibility = (int)
dol_eval($extrafields->attributes[$this->table_element][
'list'][$key], 1, 1,
'2');
9217 if ($perms && isset($extrafields->attributes[$this->table_element][
'perms'][$key])) {
9218 $perms = (int)
dol_eval($extrafields->attributes[$this->table_element][
'perms'][$key], 1, 1,
'2');
9221 if (($mode ==
'create') && !in_array(abs($visibility), array(1, 3))) {
9223 } elseif (($mode ==
'edit') && !in_array(abs($visibility), array(1, 3, 4))) {
9225 $ef_name =
'options_' . $key;
9226 $ef_value = $this->array_options[$ef_name];
9227 $out .=
'<input type="hidden" name="' . $ef_name .
'" id="' . $ef_name .
'" value="' . $ef_value .
'" />' .
"\n";
9229 } elseif ($mode ==
'view' && empty($visibility)) {
9232 if (empty($perms)) {
9237 if (!empty($extrafields->attributes[$this->table_element][
'langfile'][$key])) {
9238 $langs->load($extrafields->attributes[$this->table_element][
'langfile'][$key]);
9243 if (is_array($params) && count($params) > 0 && $display_type ==
'card') {
9244 if (array_key_exists(
'cols', $params)) {
9245 $colspan = $params[
'cols'];
9246 } elseif (array_key_exists(
'colspan', $params)) {
9248 if (preg_match(
'/colspan="(\d+)"/', $params[
'colspan'], $reg)) {
9251 $colspan = $params[
'colspan'];
9255 $colspan = intval($colspan);
9259 $value = ((!empty($this->array_options) && array_key_exists(
"options_".$key.$keysuffix, $this->array_options)) ? $this->array_options[
"options_".$key.$keysuffix] :
null);
9265 $check =
'alphanohtml';
9266 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'html',
'text'))) {
9267 $check =
'restricthtml';
9269 $getposttemp =
GETPOST($keyprefix.
'options_'.$key.$keysuffix, $check, 3);
9271 if (is_array($getposttemp) || $getposttemp !=
'' || GETPOSTISSET($keyprefix.
'options_'.$key.$keysuffix)) {
9272 if (is_array($getposttemp)) {
9274 $value = implode(
",", $getposttemp);
9276 $value = $getposttemp;
9278 } elseif (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'int'))) {
9279 $value = (!empty($this->array_options[
"options_".$key]) || (isset($this->array_options[
"options_".$key]) && $this->array_options[
"options_".$key] ===
'0')) ? $this->array_options[
"options_".$key] :
'';
9281 $value = (!empty($this->array_options[
"options_".$key]) ? $this->array_options[
"options_".$key] :
'');
9287 $nbofextrafieldsshown++;
9290 if ($extrafields->attributes[$this->table_element][
'type'][$key] ==
'separate') {
9291 $extrafields_collapse_num = $key;
9309 $out .= $extrafields->showSeparator($key, $this, ($colspan ? $colspan + 1 : 2), $display_type, $mode);
9311 $lastseparatorkeyfound = $key;
9313 $collapse_group = $extrafields_collapse_num.(!empty($this->
id) ?
'_'.$this->id :
'');
9315 $class = (!empty($extrafields->attributes[$this->table_element][
'hidden'][$key]) ?
'hideobject ' :
'');
9317 if (is_array($params) && count($params) > 0) {
9318 if (array_key_exists(
'class', $params)) {
9319 $class .= $params[
'class'].
' ';
9321 if (array_key_exists(
'style', $params)) {
9322 $csstyle = $params[
'style'];
9327 $domData =
' data-element="extrafield"';
9328 $domData .=
' data-targetelement="'.$this->element.
'"';
9329 $domData .=
' data-targetid="'.$this->id.
'"';
9331 $html_id = (empty($this->
id) ?
'' :
'extrarow-'.$this->element.
'_'.$key.
'_'.
$this->id);
9332 if ($display_type ==
'card') {
9337 if ($action ==
'selectlines') {
9343 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'date'))) {
9344 $datenotinstring =
null;
9345 if (array_key_exists(
'options_'.$key, $this->array_options)) {
9346 $datenotinstring = $this->array_options[
'options_'.$key];
9347 if (!is_numeric($this->array_options[
'options_'.$key])) {
9348 $datenotinstring = $this->db->jdate($datenotinstring);
9351 $datekey = $keyprefix.
'options_'.$key.$keysuffix;
9354 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'datetime'))) {
9355 $datenotinstring =
null;
9356 if (array_key_exists(
'options_'.$key, $this->array_options)) {
9357 $datenotinstring = $this->array_options[
'options_'.$key];
9358 if (!is_numeric($this->array_options[
'options_'.$key])) {
9359 $datenotinstring = $this->db->jdate($datenotinstring);
9362 $timekey = $keyprefix.
'options_'.$key.$keysuffix;
9363 $value = (GETPOSTISSET($timekey)) ?
dol_mktime(
GETPOSTINT($timekey.
'hour', 3),
GETPOSTINT($timekey.
'min', 3),
GETPOSTINT($timekey.
'sec', 3),
GETPOSTINT($timekey.
'month', 3),
GETPOSTINT($timekey.
'day', 3),
GETPOSTINT($timekey.
'year', 3),
'tzuserrel') : $datenotinstring;
9366 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'price',
'double'))) {
9367 if (GETPOSTISSET($keyprefix.
'options_'.$key.$keysuffix) || $value) {
9369 } elseif (isset($this->array_options[
'options_'.$key])) {
9370 $value = $this->array_options[
'options_'.$key];
9375 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'html',
'text',
'varchar',
'select',
'radio',
'int',
'boolean'))) {
9376 if ($action ==
'create' || $mode ==
'create') {
9377 $value = (GETPOSTISSET($keyprefix.
'options_'.$key.$keysuffix) || $value) ? $value : $extrafields->attributes[$this->table_element][
'default'][$key];
9381 $labeltoshow = $langs->trans($label);
9382 $helptoshow = $langs->trans($extrafields->attributes[$this->table_element][
'help'][$key]);
9383 if ($display_type ==
'card') {
9384 $out .=
'<tr '.($html_id ?
'id="'.$html_id.
'" ' :
'').$csstyle.
' class="field_options_'.$key.
' '.$class.$this->element.
'_extras_'.$key.
' trextrafields_collapse'.$collapse_group.
'" '.$domData.
' >';
9385 if (
getDolGlobalString(
'MAIN_VIEW_LINE_NUMBER') && ($action ==
'view' || $action ==
'valid' || $action ==
'editline' || $action ==
'confirm_valid' || $action ==
'confirm_cancel')) {
9386 $out .=
'<td></td>';
9388 $out .=
'<td class="'.(empty($params[
'tdclass']) ?
'titlefieldmax45' : $params[
'tdclass']).
' wordbreak';
9389 if ($extrafields->attributes[$this->table_element][
'type'][$key] ==
'text') {
9392 } elseif ($display_type ==
'line') {
9393 $out .=
'<div '.($html_id ?
'id="'.$html_id.
'" ' :
'').$csstyle.
' class="fieldline_options_'.$key.
' '.$class.$this->element.
'_extras_'.$key.
' trextrafields_collapse'.$collapse_group.
'" '.$domData.
' >';
9394 $out .=
'<div style="display: inline-block; padding-right:4px" class="wordbreak';
9399 $tpl_context = isset($params[
"tpl_context"]) ? $params[
"tpl_context"] :
"none";
9400 if ($tpl_context !=
"public") {
9401 if ($mode !=
'view' && !empty($extrafields->attributes[$this->table_element][
'required'][$key])) {
9402 $out .=
' fieldrequired';
9406 if ($tpl_context ==
"public") {
9407 if (!empty($extrafields->attributes[$this->table_element][
'help'][$key])) {
9408 $out .= $form->textwithpicto($labeltoshow, $helptoshow);
9410 $out .= $labeltoshow;
9412 if ($mode !=
'view' && !empty($extrafields->attributes[$this->table_element][
'required'][$key])) {
9413 $out .=
' <span style="color: red">*</span>';
9416 if (!empty($extrafields->attributes[$this->table_element][
'help'][$key])) {
9417 $out .= $form->textwithpicto($labeltoshow, $helptoshow);
9419 $out .= $labeltoshow;
9423 $out .= ($display_type ==
'card' ?
'</td>' :
'</div>');
9426 $html_id = !empty($this->
id) ? $this->element.
'_extras_'.$key.
'_'.$this->id :
'';
9427 if ($display_type ==
'card') {
9429 $out .=
'<td '.($html_id ?
'id="'.$html_id.
'" ' :
'').
' class="valuefieldcreate '.$this->element.
'_extras_'.$key;
9430 $out .=
'" '.($colspan ?
' colspan="'.$colspan.
'"' :
'');
9432 } elseif ($display_type ==
'line') {
9433 $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].
'">';
9438 $out .= $extrafields->showOutputField($key, $value,
'', $this->table_element);
9441 $listoftypestoshowpicto = explode(
',',
getDolGlobalString(
'MAIN_TYPES_TO_SHOW_PICTO',
'email,phone,ip,password'));
9442 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], $listoftypestoshowpicto)) {
9443 $out .=
getPictoForType($extrafields->attributes[$this->table_element][
'type'][$key], ($extrafields->attributes[$this->table_element][
'type'][$key] ==
'text' ?
'tdtop' :
''));
9446 $out .= $extrafields->showInputField($key, $value,
'', $keysuffix,
'', 0, $this, $this->table_element);
9449 $listoftypestoshowpicto = explode(
',',
getDolGlobalString(
'MAIN_TYPES_TO_SHOW_PICTO',
'email,phone,ip,password'));
9450 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], $listoftypestoshowpicto)) {
9451 $out .=
getPictoForType($extrafields->attributes[$this->table_element][
'type'][$key], ($extrafields->attributes[$this->table_element][
'type'][$key] ==
'text' ?
'tdtop' :
''));
9453 $out .= $extrafields->showInputField($key, $value,
'', $keysuffix,
'',
'', $this, $this->table_element);
9457 $out .= ($display_type ==
'card' ?
'</td>' :
'</div>');
9458 $out .= ($display_type ==
'card' ?
'</tr>'.
"\n" :
'</div>');
9464 if (!empty(
$conf->use_javascript_ajax)) {
9465 $out .= $this->getJSListDependancies();
9468 $out .=
'<!-- commonobject:showOptionals end --> '.
"\n";
9470 if (empty($nbofextrafieldsshown)) {
9476 $out .= $hookmanager->resPrint;
9488 <script nonce="'.getNonce().
'">
9489 jQuery(document).ready(function() {
9490 function showOptions'.$type.
'(child_list, parent_list, orig_select)
9492 var val = $("select[name=\""+parent_list+"\"]").val();
9493 var parentVal = parent_list + ":" + val;
9494 if(typeof val == "string"){
9496 var options = orig_select.find("option[parent=\""+parentVal+"\"]").clone();
9497 $("select[name=\""+child_list+"\"] option[parent]").remove();
9498 $("select[name=\""+child_list+"\"]").append(options);
9500 var options = orig_select.find("option[parent]").clone();
9501 $("select[name=\""+child_list+"\"] option[parent]").remove();
9502 $("select[name=\""+child_list+"\"]").append(options);
9504 } else if(val > 0) {
9505 var options = orig_select.find("option[parent=\""+parentVal+"\"]").clone();
9506 $("select[name=\""+child_list+"\"] option[parent]").remove();
9507 $("select[name=\""+child_list+"\"]").append(options);
9509 var options = orig_select.find("option[parent]").clone();
9510 $("select[name=\""+child_list+"\"] option[parent]").remove();
9511 $("select[name=\""+child_list+"\"]").append(options);
9514 function setListDependencies'.$type.
'() {
9515 jQuery("select option[parent]").parent().each(function() {
9516 var orig_select = {};
9517 var child_list = $(this).attr("name");
9518 orig_select[child_list] = $(this).clone();
9519 var parent = $(this).find("option[parent]:first").attr("parent");
9520 var infos = parent.split(":");
9521 var parent_list = infos[0];
9523 //Hide daughters lists
9524 if ($("#"+child_list).val() == 0 && $("#"+parent_list).val() == 0){
9525 $("#"+child_list).hide();
9527 } else if ($("#"+parent_list).val() != 0){
9528 $("#"+parent_list).show();
9530 //Show the child list if the parent list value is selected
9531 $("select[name=\""+parent_list+"\"]").click(function() {
9532 if ($(this).val() != 0){
9533 $("#"+child_list).show()
9537 //When we change parent list
9538 $("select[name=\""+parent_list+"\"]").change(function() {
9539 showOptions'.$type.
'(child_list, parent_list, orig_select[child_list]);
9540 //Select the value 0 on child list after a change on the parent list
9541 $("#"+child_list).val(0).trigger("change");
9542 //Hide child lists if the parent value is set to 0
9543 if ($(this).val() == 0){
9544 $("#"+child_list).hide();
9550 setListDependencies'.$type.
'();
9565 $module = empty($this->module) ?
'' : $this->module;
9566 $element = $this->element;
9568 if ($element ==
'facturerec') {
9569 $element =
'facture';
9570 } elseif ($element ==
'invoice_supplier_rec') {
9571 return !$user->hasRight(
'fournisseur',
'facture') ? null : $user->hasRight(
'fournisseur',
'facture');
9572 } elseif ($module && $user->hasRight($module, $element)) {
9574 return $user->hasRight($module, $element);
9577 return $user->rights->$element;
9594 global $hookmanager;
9596 $parameters = array(
9597 'origin_id' => $origin_id,
9598 'dest_id' => $dest_id,
9599 'tables' => $tables,
9601 $reshook = $hookmanager->executeHooks(
'commonReplaceThirdparty', $parameters);
9604 } elseif ($reshook < 0) {
9605 return $ignoreerrors === 1;
9608 foreach ($tables as $table) {
9609 $sql =
'UPDATE '.$dbs->prefix().$table.
' SET fk_soc = '.((int) $dest_id).
' WHERE fk_soc = '.((int) $origin_id);
9611 if (!$dbs->
query($sql)) {
9612 if ($ignoreerrors) {
9637 foreach ($tables as $table) {
9638 $sql =
'UPDATE '.MAIN_DB_PREFIX.$table.
' SET fk_product = '.((int) $dest_id).
' WHERE fk_product = '.((int) $origin_id);
9640 if (!$dbs->
query($sql)) {
9641 if ($ignoreerrors) {
9664 public function defineBuyPrice($unitPrice = 0.0, $discountPercent = 0.0, $fk_product = 0)
9670 if (($unitPrice > 0) && (isset(
$conf->global->ForceBuyingPriceIfNull) &&
getDolGlobalInt(
'ForceBuyingPriceIfNull') > 0)) {
9672 $buyPrice = $unitPrice * (1 - $discountPercent / 100);
9675 if (!empty($fk_product) && $fk_product > 0) {
9678 require_once DOL_DOCUMENT_ROOT.
'/product/class/product.class.php';
9679 $product =
new Product($this->db);
9680 $result = $product->fetch($fk_product);
9682 $this->errors[] =
'ErrorProductIdDoesNotExists';
9685 if ($product->cost_price > 0) {
9686 $buyPrice = $product->cost_price;
9687 } elseif ($product->pmp > 0) {
9688 $buyPrice = $product->pmp;
9691 require_once DOL_DOCUMENT_ROOT.
'/product/class/product.class.php';
9692 $product =
new Product($this->db);
9693 $result = $product->fetch($fk_product);
9695 $this->errors[] =
'ErrorProductIdDoesNotExists';
9698 if ($product->pmp > 0) {
9699 $buyPrice = $product->pmp;
9703 if (empty($buyPrice) && isset(
$conf->global->MARGIN_TYPE) && in_array(
$conf->global->MARGIN_TYPE, array(
'1',
'pmp',
'costprice'))) {
9704 require_once DOL_DOCUMENT_ROOT.
'/fourn/class/fournisseur.product.class.php';
9706 if (($result = $productFournisseur->find_min_price_product_fournisseur($fk_product)) > 0) {
9707 $buyPrice = $productFournisseur->fourn_unitprice;
9708 } elseif ($result < 0) {
9709 $this->errors[] = $productFournisseur->error;
9716 return (
float) $buyPrice;
9729 return array(
'dir' =>
'',
'file' =>
'',
'originalfile' =>
'',
'altfile' =>
'',
'email' =>
'',
'capture' =>
'');
9753 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')
9756 global $user, $langs;
9758 include_once DOL_DOCUMENT_ROOT.
'/core/lib/files.lib.php';
9759 include_once DOL_DOCUMENT_ROOT.
'/core/lib/images.lib.php';
9761 $sortfield =
'position_name';
9767 $dir .=
get_exdir(0, 0, 0, 0, $this, $modulepart);
9768 $pdir .=
get_exdir(0, 0, 0, 0, $this, $modulepart);
9771 if ($modulepart ==
'product') {
9773 $dir = $sdir.
'/'.
get_exdir($this->
id, 2, 0, 0, $this, $modulepart).$this->id.
"/photos/";
9774 $pdir =
'/'.get_exdir($this->
id, 2, 0, 0, $this, $modulepart).$this->id.
"/photos/";
9777 if ($modulepart ==
'category') {
9778 $dir = $sdir.
'/'.
get_exdir($this->
id, 2, 0, 0, $this, $modulepart).$this->id.
"/photos/";
9779 $pdir =
'/'.get_exdir($this->
id, 2, 0, 0, $this, $modulepart).$this->id.
"/photos/";
9785 $relativedir = preg_replace(
'/^'.preg_quote(DOL_DATA_ROOT,
'/').
'/',
'', $dir);
9786 $relativedir = preg_replace(
'/^[\\/]/',
'', $relativedir);
9787 $relativedir = preg_replace(
'/[\\/]$/',
'', $relativedir);
9790 $dirthumb = $dir.
'thumbs/';
9791 $pdirthumb = $pdir.
'thumbs/';
9793 $return =
'<!-- Photo -->'.
"\n";
9796 $filearray =
dol_dir_list($dir,
"files", 0,
'',
'(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) ==
'desc' ? SORT_DESC : SORT_ASC), 1);
9805 '@phan-var-force array<array{name:string,path:string,level1name:string,relativename:string,fullname:string,date:string,size:int,perm:int,type:string,position_name:string,cover:string,keywords:string,acl:string,rowid:int,label:string,share:string}> $filearray';
9807 if (count($filearray)) {
9808 if ($sortfield && $sortorder) {
9812 foreach ($filearray as $key => $val) {
9814 $file = $val[
'name'];
9820 $viewfilename = $file;
9822 if ($size == 1 || $size ==
'small') {
9829 $photo_vignette = basename($file);
9836 if ($nbphoto == 1) {
9837 $return .=
'<table class="valigntop center centpercent" style="border: 0; padding: 2px; border-spacing: 2px; border-collapse: separate;">';
9840 if ($nbphoto % $nbbyrow == 1) {
9841 $return .=
'<tr class="center valignmiddle" style="border: 1px">';
9843 $return .=
'<td style="width: '.ceil(100 / $nbbyrow).
'%" class="photo">'.
"\n";
9844 } elseif ($nbbyrow < 0) {
9845 $return .=
'<div class="inline-block">'.
"\n";
9848 $relativefile = preg_replace(
'/^\//',
'', $pdir.$photo);
9849 if (empty($nolink)) {
9852 $return .=
'<a href="'.$urladvanced.
'">';
9854 $return .=
'<a href="'.DOL_URL_ROOT.
'/viewimage.php?modulepart='.$modulepart.
'&entity='.$this->entity.
'&file='.urlencode($pdir.$photo).
'" class="aphoto" target="_blank" rel="noopener noreferrer">';
9860 $alt = $langs->transnoentitiesnoconv(
'File').
': '.$relativefile;
9861 $alt .=
' - '.$langs->transnoentitiesnoconv(
'Size').
': '.$imgarray[
'width'].
'x'.$imgarray[
'height'];
9862 if ($overwritetitle) {
9863 if (is_numeric($overwritetitle)) {
9866 $alt = $overwritetitle;
9869 if (empty($cache) && !empty($val[
'label'])) {
9872 $cache = $val[
'label'];
9874 if ($usesharelink) {
9875 if (array_key_exists(
'share', $val) && $val[
'share']) {
9876 if (empty($maxHeight) || ($photo_vignette && $imgarray[
'height'] > $maxHeight)) {
9877 $return .=
'<!-- Show original file (thumb not yet available with shared links) -->';
9878 $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).
'">';
9880 $return .=
'<!-- Show original file -->';
9881 $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).
'">';
9884 $return .=
'<!-- Show nophoto file (because file is not shared) -->';
9885 $return .=
'<img class="photo photowithmargin'.($addphotorefcss ?
' '.$addphotorefcss :
'').
'" height="'.$maxHeight.
'" src="'.DOL_URL_ROOT.
'/public/theme/common/nophoto.png" title="'.
dol_escape_htmltag($alt).
'">';
9888 if (empty($maxHeight) || ($photo_vignette && $imgarray[
'height'] > $maxHeight)) {
9889 $return .=
'<!-- Show thumb -->';
9890 $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).
'">';
9892 $return .=
'<!-- Show original file -->';
9893 $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).
'">';
9897 if (empty($nolink)) {
9901 if ($showfilename) {
9902 $return .=
'<br>'.$viewfilename;
9907 if ($photo_vignette && (
image_format_supported($photo) > 0) && ((isset($imgarray[
'width']) && $imgarray[
'width'] > $maxWidth) || (isset($imgarray[
'width']) && $imgarray[
'width'] > $maxHeight))) {
9908 $return .=
'<a href="'.$_SERVER[
"PHP_SELF"].
'?id='.$this->
id.
'&action=addthumb&token='.
newToken().
'&file='.urlencode($pdir.$viewfilename).
'">'.
img_picto($langs->trans(
'GenerateThumb'),
'refresh').
' </a>';
9911 if ($modulepart ==
'product' && ($user->hasRight(
'produit',
'creer') || $user->hasRight(
'service',
'creer'))) {
9913 $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> ';
9916 $return .=
'<a href="'.$_SERVER[
"PHP_SELF"].
'?id='.$this->
id.
'&action=delete&token='.
newToken().
'&file='.urlencode($pdir.$viewfilename).
'">';
9924 if (($nbphoto % $nbbyrow) == 0) {
9927 } elseif ($nbbyrow < 0) {
9928 $return .=
'</div>'.
"\n";
9933 $return .=
'<img class="photo photowithmargin" src="'.DOL_URL_ROOT.
'/viewimage.php?modulepart='.$modulepart.
'&entity='.$this->entity.
'&file='.urlencode($pdir.$photo).
'">';
9935 if ($showfilename) {
9936 $return .=
'<br>'.$viewfilename;
9940 if ($modulepart ==
'product' && ($user->hasRight(
'produit',
'creer') || $user->hasRight(
'service',
'creer'))) {
9942 $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> ';
9945 $return .=
'<a href="'.$_SERVER[
"PHP_SELF"].
'?id='.$this->
id.
'&action=delete&token='.
newToken().
'&file='.urlencode($pdir.$viewfilename).
'">';
9952 if ($nbmax && $nbphoto >= $nbmax) {
9958 if ($size == 1 || $size ==
'small') {
9961 while ($nbphoto % $nbbyrow) {
9962 $return .=
'<td style="width: '.ceil(100 / $nbbyrow).
'%"> </td>';
9967 $return .=
'</table>';
9973 $this->nbphoto = $nbphoto;
9987 if (is_array($info)) {
9988 if (isset($info[
'type']) && $info[
'type'] ==
'array') {
10005 if (isset($info[
'type']) && ($info[
'type'] ==
'date' || $info[
'type'] ==
'datetime' || $info[
'type'] ==
'timestamp')) {
10019 if (is_array($info)) {
10020 if (isset($info[
'type']) && ($info[
'type'] ==
'duration')) {
10038 if (is_array($info)) {
10039 if (isset($info[
'type']) && (preg_match(
'/(^int|int$)/i', $info[
'type']))) {
10057 if (is_array($info)) {
10058 if (isset($info[
'type']) && (preg_match(
'/^(double|real|price)/i', $info[
'type']))) {
10075 if (is_array($info)) {
10076 if (isset($info[
'type']) && $info[
'type'] ==
'text') {
10093 if (is_array($info)) {
10094 if (array_key_exists(
'notnull', $info) && $info[
'notnull'] !=
'1') {
10111 if (is_array($info)) {
10112 if (array_key_exists(
'notnull', $info) && $info[
'notnull'] ==
'-1') {
10129 if (is_array($info)) {
10130 if (array_key_exists(
'index', $info) && $info[
'index'] ==
true) {
10152 $queryarray = array();
10153 foreach ($this->fields as $field => $info) {
10155 if ($this->isDate($info)) {
10156 if (empty($this->{$field})) {
10157 $queryarray[$field] =
null;
10159 $queryarray[$field] = $this->db->idate($this->{$field});
10161 } elseif ($this->isDuration($info)) {
10163 if ((isset($this->{$field}) && $this->{$field} !=
'') || !empty($info[
'notnull'])) {
10164 if (!isset($this->{$field})) {
10165 if (!empty($info[
'default'])) {
10166 $queryarray[$field] = $info[
'default'];
10168 $queryarray[$field] = 0;
10171 $queryarray[$field] = (int) $this->{$field};
10174 $queryarray[$field] =
null;
10176 } elseif ($this->isInt($info) || $this->isFloat($info)) {
10177 if ($field ==
'entity' && is_null($this->{$field})) {
10178 $queryarray[$field] = ((int)
$conf->entity);
10181 if ((isset($this->{$field}) && ((
string) $this->{$field}) !=
'') || !empty($info[
'notnull'])) {
10182 if (!isset($this->{$field})) {
10183 $queryarray[$field] = 0;
10184 } elseif ($this->isInt($info)) {
10185 $queryarray[$field] = (int) $this->{$field};
10186 } elseif ($this->isFloat($info)) {
10187 $queryarray[$field] = (float) $this->{$field};
10190 $queryarray[$field] =
null;
10196 $queryarray[$field] = $this->{$field};
10199 if (array_key_exists(
'type', $info) && $info[
'type'] ==
'timestamp' && empty($queryarray[$field])) {
10200 unset($queryarray[$field]);
10202 if (!empty($info[
'notnull']) && $info[
'notnull'] == -1 && empty($queryarray[$field])) {
10203 $queryarray[$field] =
null;
10207 return $queryarray;
10220 foreach ($this->fields as $field => $info) {
10221 if ($this->isDate($info)) {
10222 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') {
10223 $this->$field =
'';
10225 $this->$field = $db->jdate($obj->$field);
10227 } elseif ($this->isInt($info)) {
10228 if ($field ==
'rowid') {
10229 $this->
id = (int) $obj->$field;
10231 if ($this->isForcedToNullIfZero($info)) {
10232 if (empty($obj->$field)) {
10233 $this->$field =
null;
10235 $this->$field = (int) $obj->$field;
10238 if (isset($obj->$field) && (!is_null($obj->$field) || (array_key_exists(
'notnull', $info) && $info[
'notnull'] == 1))) {
10239 $this->$field = (int) $obj->$field;
10241 $this->$field =
null;
10245 } elseif ($this->isFloat($info)) {
10246 if ($this->isForcedToNullIfZero($info)) {
10247 if (empty($obj->$field)) {
10248 $this->$field =
null;
10250 $this->$field = (float) $obj->$field;
10253 if (isset($obj->$field) && (!is_null($obj->$field) || (array_key_exists(
'notnull', $info) && $info[
'notnull'] == 1))) {
10254 $this->$field = (float) $obj->$field;
10256 $this->$field =
null;
10260 $this->$field = isset($obj->$field) ? $obj->$field :
null;
10265 if (!isset($this->fields[
'ref']) && isset($this->
id)) {
10266 $this->
ref = (string) $this->
id;
10276 foreach ($this->fields as $field => $arr) {
10277 $this->$field =
null;
10290 $keys = array_keys($this->fields);
10291 if (!empty($alias)) {
10292 $keys_with_alias = array();
10293 foreach ($keys as $fieldname) {
10294 if (!empty($excludefields)) {
10295 if (in_array($fieldname, $excludefields)) {
10299 $keys_with_alias[] = $alias .
'.' . $fieldname;
10301 return implode(
',', $keys_with_alias);
10303 return implode(
',', $keys);
10314 protected function quote($value, $fieldsentry)
10316 if (is_null($value)) {
10318 } elseif (preg_match(
'/^(int|double|real|price)/i', $fieldsentry[
'type'])) {
10320 } elseif (preg_match(
'/int$/i', $fieldsentry[
'type'])) {
10321 return (
int) $value;
10322 } elseif ($fieldsentry[
'type'] ==
'boolean') {
10329 return "'".$this->db->escape($value).
"'";
10345 dol_syslog(get_class($this).
"::createCommon create", LOG_DEBUG);
10351 $fieldvalues = $this->setSaveQuery();
10355 if (array_key_exists(
'date_creation', $fieldvalues) && empty($fieldvalues[
'date_creation'])) {
10356 $fieldvalues[
'date_creation'] = $this->db->idate($now);
10357 $this->date_creation = $this->db->idate($now);
10360 if (array_key_exists(
'fk_user_creat', $fieldvalues) && !($fieldvalues[
'fk_user_creat'] > 0)) {
10361 $fieldvalues[
'fk_user_creat'] = $user->id;
10362 $this->fk_user_creat = $user->id;
10364 if (array_key_exists(
'user_creation_id', $fieldvalues) && !($fieldvalues[
'user_creation_id'] > 0)) {
10365 $fieldvalues[
'user_creation_id'] = $user->id;
10366 $this->user_creation_id = $user->id;
10368 if (array_key_exists(
'pass_crypted', $fieldvalues) && property_exists($this,
'pass')) {
10370 $tmparray =
dol_hash($this->pass,
'0', 0, 1);
10371 $fieldvalues[
'pass_crypted'] = $tmparray[
'pass_encrypted'];
10372 if (array_key_exists(
'pass_encoding', $fieldvalues) && property_exists($this,
'pass_encoding')) {
10373 $fieldvalues[
'pass_encoding'] = $tmparray[
'pass_encoding'];
10376 if (array_key_exists(
'ref', $fieldvalues)) {
10380 unset($fieldvalues[
'rowid']);
10384 foreach ($fieldvalues as $k => $v) {
10386 $value = $this->fields[$k];
10388 $values[$k] = $this->quote($v, $value);
10392 foreach ($keys as $key) {
10393 if (!isset($this->fields[$key])) {
10396 $key_fields = $this->fields[$key];
10399 if (preg_match(
'/^integer:/i', $key_fields[
'type']) && $values[$key] ==
'-1') {
10400 $values[$key] =
'';
10402 if (!empty($key_fields[
'foreignkey']) && $values[$key] ==
'-1') {
10403 $values[$key] =
'';
10406 if (isset($key_fields[
'notnull']) && $key_fields[
'notnull'] == 1 && (!isset($values[$key]) || $values[$key] ===
'NULL') && (!isset($key_fields[
'default']) || is_null($key_fields[
'default']))) {
10408 $langs->load(
"errors");
10409 dol_syslog(
"Mandatory field '".$key.
"' is empty and required into ->fields definition of class");
10410 $this->errors[] = $langs->trans(
"ErrorFieldRequired", isset($key_fields[
'label']) ? $key_fields[
'label'] : $key);
10414 if (isset($key_fields[
'notnull']) && $key_fields[
'notnull'] == 1 && (!isset($values[$key]) || $values[$key] ===
'NULL') && !is_null($key_fields[
'default'])) {
10415 $values[$key] = $this->quote($key_fields[
'default'], $key_fields);
10419 if (isset($key_fields[
'type']) && preg_match(
'/^integer:/i', $key_fields[
'type']) && empty($values[$key])) {
10420 if (isset($key_fields[
'default'])) {
10421 $values[$key] = ((int) $key_fields[
'default']);
10423 $values[$key] =
'null';
10426 if (!empty($key_fields[
'foreignkey']) && empty($values[$key])) {
10427 $values[$key] =
'null';
10435 $this->db->begin();
10438 $sql =
"INSERT INTO ".$this->db->prefix().$this->table_element;
10439 $sql .=
" (".implode(
", ", $keys).
')';
10440 $sql .=
" VALUES (".implode(
", ", $values).
")";
10442 $res = $this->db->query($sql);
10445 if ($this->db->lasterrno() ==
'DB_ERROR_RECORD_ALREADY_EXISTS') {
10446 $this->errors[] =
"ErrorRefAlreadyExists";
10448 $this->errors[] = $this->db->lasterror();
10454 $this->
id = $this->db->last_insert_id($this->db->prefix().$this->table_element);
10460 if (array_key_exists(
'ref', $this->fields) && array_key_exists(
'notnull', $this->fields[
'ref']) && $this->fields[
'ref'][
'notnull'] > 0 && array_key_exists(
'default', $this->fields[
'ref']) && $this->fields[
'ref'][
'default'] ==
'(PROV)') {
10461 $sql =
"UPDATE ".$this->db->prefix().$this->table_element.
" SET ref = '(PROV".((int) $this->
id).
")' WHERE (ref = '(PROV)' OR ref = '') AND rowid = ".((int) $this->
id);
10462 $resqlupdate = $this->db->query($sql);
10464 if ($resqlupdate ===
false) {
10466 $this->errors[] = $this->db->lasterror();
10468 $this->
ref =
'(PROV'.$this->id.
')';
10475 $result = $this->insertExtraFields();
10482 if (!empty($this->table_element_line) && !empty($this->fk_element) && !empty($this->lines)) {
10483 foreach ($this->lines as $line) {
10484 $keyforparent = $this->fk_element;
10489 if (!is_object($line)) {
10490 $line = (object) $line;
10494 if (method_exists($line,
'insert')) {
10495 $result = $line->insert($user, 1);
10496 } elseif (method_exists($line,
'create')) {
10497 $result = $line->create($user, 1);
10500 $this->error = $line->error;
10501 $this->db->rollback();
10508 if (!$error && !$notrigger) {
10510 $result = $this->call_trigger(strtoupper(get_class($this)).
'_CREATE', $user);
10519 $this->db->rollback();
10522 $this->db->commit();
10539 if (empty(
$id) && empty($ref) && empty($morewhere)) {
10543 $fieldlist = $this->getFieldList(
't');
10544 if (empty($fieldlist)) {
10548 $sql =
"SELECT ".$fieldlist;
10549 $sql .=
" FROM ".$this->db->prefix().$this->table_element.
' as t';
10552 $sql .=
' WHERE t.rowid = '.((int)
$id);
10553 } elseif (!empty($ref)) {
10554 $sql .=
" WHERE t.ref = '".$this->db->escape($ref).
"'";
10556 $sql .=
' WHERE 1 = 1';
10558 if (empty(
$id) && isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
10559 $sql .=
' AND t.entity IN ('.getEntity($this->element).
')';
10562 $sql .= $morewhere;
10564 $sql .=
' LIMIT 1';
10566 $res = $this->db->query($sql);
10568 $obj = $this->db->fetch_object($res);
10570 $this->setVarsFromFetchObj($obj);
10574 if (empty($noextrafields)) {
10575 $result = $this->fetch_optionals();
10577 $this->error = $this->db->lasterror();
10578 $this->errors[] = $this->error;
10588 $this->error = $this->db->lasterror();
10589 $this->errors[] = $this->error;
10603 $objectlineclassname = get_class($this).
'Line';
10604 if (!class_exists($objectlineclassname)) {
10605 $this->error =
'Error, class '.$objectlineclassname.
' not found during call of fetchLinesCommon';
10609 $objectline =
new $objectlineclassname($this->db);
10610 '@phan-var-force CommonObjectLine $objectline';
10612 $sql =
"SELECT ".$objectline->getFieldList(
'l');
10613 $sql .=
" FROM ".$this->db->prefix().$objectline->table_element.
" as l";
10614 $sql .=
" WHERE l.fk_".$this->db->escape($this->element).
" = ".((int) $this->
id);
10616 $sql .= $morewhere;
10618 if (isset($objectline->fields[
'position'])) {
10619 $sql .= $this->db->order(
'position',
'ASC');
10622 $resql = $this->db->query($sql);
10624 $num_rows = $this->db->num_rows($resql);
10626 $this->lines = array();
10627 while ($i < $num_rows) {
10628 $obj = $this->db->fetch_object($resql);
10630 $newline =
new $objectlineclassname($this->db);
10631 '@phan-var-force CommonObjectLine $newline';
10632 $newline->setVarsFromFetchObj($obj);
10640 $this->lines[] = $newline;
10647 $this->error = $this->db->lasterror();
10648 $this->errors[] = $this->error;
10662 dol_syslog(get_class($this).
"::updateCommon update", LOG_DEBUG);
10674 $fieldvalues = $this->setSaveQuery();
10678 if (array_key_exists(
'date_modification', $fieldvalues) && empty($fieldvalues[
'date_modification'])) {
10679 $fieldvalues[
'date_modification'] = $this->db->idate($now);
10681 if (array_key_exists(
'fk_user_modif', $fieldvalues) && !($fieldvalues[
'fk_user_modif'] > 0)) {
10682 $fieldvalues[
'fk_user_modif'] = $user->id;
10684 if (array_key_exists(
'user_modification_id', $fieldvalues) && !($fieldvalues[
'user_modification_id'] > 0)) {
10685 $fieldvalues[
'user_modification_id'] = $user->id;
10687 if (array_key_exists(
'pass_crypted', $fieldvalues) && property_exists($this,
'pass') && !empty($this->pass)) {
10689 $tmparray =
dol_hash($this->pass,
'0', 0, 1);
10690 $fieldvalues[
'pass_crypted'] = $tmparray[
'pass_encrypted'];
10691 if (array_key_exists(
'pass_encoding', $fieldvalues) && property_exists($this,
'pass_encoding')) {
10692 $fieldvalues[
'pass_encoding'] = $tmparray[
'pass_encoding'];
10695 if (array_key_exists(
'ref', $fieldvalues)) {
10699 unset($fieldvalues[
'rowid']);
10705 foreach ($fieldvalues as $k => $v) {
10707 $value = $this->fields[$k];
10709 $values[$k] = $this->quote($v, $value);
10710 if (($value[
"type"] ==
"text") && !empty($value[
'arrayofkeyval']) && is_array($value[
'arrayofkeyval'])) {
10712 $v = preg_replace(
'/\s/',
',', $v);
10713 $v = preg_replace(
'/,+/',
',', $v);
10716 $tmp[] = $k.
'='.$this->quote($v, $this->fields[$k]);
10720 foreach ($keys as $key) {
10721 if (preg_match(
'/^integer:/i', $this->fields[$key][
'type']) && $values[$key] ==
'-1') {
10722 $values[$key] =
'';
10724 if (!empty($this->fields[$key][
'foreignkey']) && $values[$key] ==
'-1') {
10725 $values[$key] =
'';
10737 $sql =
'UPDATE '.$this->db->prefix().$this->table_element.
' SET '.implode(
', ', $tmp).
' WHERE rowid='.((int) $this->
id);
10739 $this->db->begin();
10742 $res = $this->db->query($sql);
10745 $this->errors[] = $this->db->lasterror();
10751 $result = $this->insertExtraFields();
10758 if (!$error && !$notrigger) {
10760 $result = $this->call_trigger(strtoupper(get_class($this)).
'_MODIFY', $user);
10769 $this->db->rollback();
10772 $this->db->commit();
10787 dol_syslog(get_class($this).
"::deleteCommon delete", LOG_DEBUG);
10791 $this->db->begin();
10793 if ($forcechilddeletion) {
10794 foreach ($this->childtables as $table) {
10795 $sql =
"DELETE FROM ".$this->db->prefix().$table.
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
10796 $resql = $this->db->query($sql);
10798 $this->error = $this->db->lasterror();
10799 $this->errors[] = $this->error;
10800 $this->db->rollback();
10804 } elseif (!empty($this->childtables)) {
10805 $objectisused = $this->isObjectUsed($this->
id);
10806 if (!empty($objectisused)) {
10807 dol_syslog(get_class($this).
"::deleteCommon Can't delete record as it has some child", LOG_WARNING);
10808 $this->error =
'ErrorRecordHasChildren';
10809 $this->errors[] = $this->error;
10810 $this->db->rollback();
10816 if (is_array($this->childtablesoncascade) && !empty($this->childtablesoncascade)) {
10817 foreach ($this->childtablesoncascade as $tabletodelete) {
10818 $deleteFromObject = explode(
':', $tabletodelete, 4);
10819 if (count($deleteFromObject) >= 2) {
10820 $className = str_replace(
'@',
'', $deleteFromObject[0]);
10821 $filePath = $deleteFromObject[1];
10822 $columnName = $deleteFromObject[2];
10824 if (!empty($deleteFromObject[3])) {
10825 $filter = $deleteFromObject[3];
10828 $childObject =
new $className($this->db);
10829 if (method_exists($childObject,
'deleteByParentField')) {
10830 '@phan-var-force CommonObject $childObject';
10831 $result = $childObject->deleteByParentField($this->
id, $columnName, $filter);
10834 $this->errors[] = $childObject->error;
10839 $this->errors[] =
"You defined a cascade delete on an object $className/$this->id but there is no method deleteByParentField for it";
10844 $this->errors[] =
'Cannot include child class file '.$filePath;
10849 $sql =
"DELETE FROM ".$this->db->prefix().$tabletodelete.
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
10851 $resql = $this->db->query($sql);
10854 $this->error = $this->db->lasterror();
10855 $this->errors[] = $this->error;
10865 $result = $this->call_trigger(strtoupper(get_class($this)).
'_DELETE', $user);
10875 $res = $this->deleteEcmFiles(1);
10882 $res = $this->deleteObjectLinked();
10887 if (!$error && !empty($this->isextrafieldmanaged)) {
10888 $result = $this->deleteExtraFields();
10895 $sql =
'DELETE FROM '.$this->db->prefix().$this->table_element.
' WHERE rowid='.((int) $this->
id);
10897 $resql = $this->db->query($sql);
10900 $this->errors[] = $this->db->lasterror();
10906 $this->db->rollback();
10909 $this->db->commit();
10932 if (!empty($parentId) && !empty($parentField)) {
10933 $this->db->begin();
10935 $sql =
"SELECT rowid FROM ".$this->db->prefix().$this->table_element;
10936 $sql .=
" WHERE ".$this->db->sanitize($parentField).
" = ".(int) $parentId;
10939 $errormessage =
'';
10941 if ($errormessage) {
10942 $this->errors[] = $errormessage;
10943 dol_syslog(__METHOD__.
' '.implode(
',', $this->errors), LOG_ERR);
10947 $resql = $this->db->query($sql);
10949 $this->errors[] = $this->db->lasterror();
10952 while ($obj = $this->db->fetch_object($resql)) {
10953 $result = $this->fetch($obj->rowid);
10956 $this->errors[] = $this->error;
10958 $result = $this->
delete($user);
10961 $this->errors[] = $this->error;
10969 if (empty($error)) {
10970 $this->db->commit();
10973 $this->error = implode(
', ', $this->errors);
10974 $this->db->rollback();
10975 return $error * -1;
10994 $tmpforobjectclass = get_class($this);
10995 $tmpforobjectlineclass = ucfirst($tmpforobjectclass).
'Line';
10997 $this->db->begin();
11000 $result = $this->call_trigger(
'LINE'.strtoupper($tmpforobjectclass).
'_DELETE', $user);
11006 if (empty($error)) {
11007 $sql =
"DELETE FROM ".$this->db->prefix().$this->table_element_line;
11008 $sql .=
" WHERE rowid = ".((int) $idline);
11010 $resql = $this->db->query($sql);
11012 $this->error =
"Error ".$this->db->lasterror();
11017 if (empty($error)) {
11019 $tmpobjectline =
new $tmpforobjectlineclass($this->db);
11020 '@phan-var-force CommonObjectLine $tmpobjectline';
11021 if (!isset($tmpobjectline->isextrafieldmanaged) || !empty($tmpobjectline->isextrafieldmanaged)) {
11022 $tmpobjectline->id = $idline;
11023 $result = $tmpobjectline->deleteExtraFields();
11026 $this->error =
"Error ".get_class($this).
"::deleteLineCommon deleteExtraFields error -4 ".$tmpobjectline->error;
11031 if (empty($error)) {
11032 $this->db->commit();
11035 dol_syslog(get_class($this).
"::deleteLineCommon ERROR:".$this->error, LOG_ERR);
11036 $this->db->rollback();
11055 $this->db->begin();
11057 $statusfield =
'status';
11058 if (in_array($this->element, array(
'don',
'donation',
'shipping'))) {
11059 $statusfield =
'fk_statut';
11062 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
11063 $sql .=
" SET ".$statusfield.
" = ".((int) $status);
11064 $sql .=
" WHERE rowid = ".((int) $this->
id);
11066 if ($this->db->query($sql)) {
11068 $this->oldcopy = clone $this;
11071 if (!$error && !$notrigger) {
11073 $result = $this->call_trigger($triggercode, $user);
11080 $this->
status = $status;
11081 if (property_exists($this,
'statut')) {
11082 $this->statut = $status;
11084 $this->db->commit();
11087 $this->db->rollback();
11091 $this->error = $this->db->error();
11092 $this->db->rollback();
11108 $this->specimen = 1;
11110 'label' =>
'This is label',
11111 'ref' =>
'ABCD1234',
11112 'description' =>
'This is a description',
11114 'note_public' =>
'Public note',
11115 'note_private' =>
'Private note',
11116 'date_creation' => (
dol_now() - 3600 * 48),
11117 'date_modification' => (
dol_now() - 3600 * 24),
11118 'fk_user_creat' => $user->id,
11119 'fk_user_modif' => $user->id,
11122 foreach ($fields as $key => $value) {
11123 if (array_key_exists($key, $this->fields)) {
11124 $this->{$key} = $value;
11129 if (property_exists($this,
'fields')) {
11130 foreach ($this->fields as $key => $value) {
11132 if (array_key_exists($key, $fields)) {
11136 if (!empty($value[
'default'])) {
11137 $this->$key = $value[
'default'];
11155 require_once DOL_DOCUMENT_ROOT.
'/core/class/comment.class.php';
11157 $comment =
new Comment($this->db);
11158 $result = $comment->fetchAllFor($this->element, $this->
id);
11160 $this->errors = array_merge($this->errors, $comment->errors);
11163 $this->comments = $comment->comments;
11165 return count($this->comments);
11175 return count($this->comments);
11186 if (!is_array($parameters)) {
11189 foreach ($parameters as $parameter) {
11190 if (isset($this->$parameter)) {
11191 $this->$parameter = trim($this->$parameter);
11210 require_once DOL_DOCUMENT_ROOT.
'/categories/class/categorie.class.php';
11214 $existing =
$c->containing($this->
id, $type_categ,
'id');
11234 if (!is_array($categories)) {
11235 $categories = array($categories);
11238 dol_syslog(get_class($this).
"::setCategoriesCommon Object Id:".$this->
id.
' type_categ:'.$type_categ.
' nb tag add:'.count($categories), LOG_DEBUG);
11240 require_once DOL_DOCUMENT_ROOT.
'/categories/class/categorie.class.php';
11242 if (empty($type_categ)) {
11243 dol_syslog(__METHOD__.
': Type '.$type_categ.
'is an unknown category type. Done nothing.', LOG_ERR);
11249 $existing =
$c->containing($this->
id, $type_categ,
'id');
11250 if ($remove_existing) {
11252 if (is_array($existing)) {
11253 $to_del = array_diff($existing, $categories);
11254 $to_add = array_diff($categories, $existing);
11257 $to_add = $categories;
11261 $to_add = array_diff($categories, $existing);
11268 foreach ($to_del as $del) {
11269 if (
$c->fetch($del) > 0) {
11270 $result =
$c->del_type($this, $type_categ);
11273 $this->error =
$c->error;
11274 $this->errors =
$c->errors;
11281 foreach ($to_add as $add) {
11282 if (
$c->fetch($add) > 0) {
11283 $result =
$c->add_type($this, $type_categ);
11286 $this->error =
$c->error;
11287 $this->errors =
$c->errors;
11295 return $error ? (-1 * $error) : $ok;
11308 $this->db->begin();
11310 if (empty($type)) {
11311 $type = $this->table_element;
11314 require_once DOL_DOCUMENT_ROOT.
'/categories/class/categorie.class.php';
11315 $categorystatic =
new Categorie($this->db);
11317 $sql =
"INSERT INTO ".$this->db->prefix().
"categorie_".(empty($categorystatic->MAP_CAT_TABLE[$type]) ? $type : $categorystatic->MAP_CAT_TABLE[$type]).
" (fk_categorie, fk_product)";
11318 $sql .=
" SELECT fk_categorie, $toId FROM ".$this->db->prefix().
"categorie_".(empty($categorystatic->MAP_CAT_TABLE[$type]) ? $type : $categorystatic->MAP_CAT_TABLE[$type]);
11319 $sql .=
" WHERE fk_product = ".((int) $fromId);
11321 if (!$this->db->query($sql)) {
11322 $this->error = $this->db->lasterror();
11323 $this->db->rollback();
11327 $this->db->commit();
11341 $this->db->begin();
11345 switch ($this->element) {
11347 $element =
'propale';
11350 $element =
'produit';
11352 case 'order_supplier':
11353 $element =
'fournisseur/commande';
11355 case 'invoice_supplier':
11358 $element =
'fournisseur/facture/'.get_exdir($this->
id, 2, 0, 1, $this,
'invoice_supplier');
11361 $element =
'expedition/sending';
11364 case 'project_task':
11365 require_once DOL_DOCUMENT_ROOT.
'/projet/class/task.class.php';
11367 $project_result = $this->fetchProject();
11368 if ($project_result >= 0) {
11369 $element =
'projet/'.dol_sanitizeFileName($this->project->ref).
'/';
11373 $element = $this->element;
11375 '@phan-var-force string $element';
11378 $sql =
"DELETE FROM ".$this->db->prefix().
"ecm_files_extrafields WHERE fk_object IN (";
11379 $sql .=
" SELECT rowid FROM ".$this->db->prefix().
"ecm_files WHERE filename LIKE '".$this->db->escape($this->
ref).
"%'";
11380 $sql .=
" AND filepath = '".$this->db->escape($element).
"/".$this->db->escape($this->
ref).
"' AND entity = ".((int)
$conf->entity);
11383 if (!$this->db->query($sql)) {
11384 $this->error = $this->db->lasterror();
11385 $this->db->rollback();
11390 $sql =
"DELETE FROM ".$this->db->prefix().
"ecm_files";
11391 $sql .=
" WHERE filename LIKE '".$this->db->escape($this->
ref).
"%'";
11392 $sql .=
" AND filepath = '".$this->db->escape($element).
"/".$this->db->escape($this->
ref).
"' AND entity = ".((int)
$conf->entity);
11394 if (!$this->db->query($sql)) {
11395 $this->error = $this->db->lasterror();
11396 $this->db->rollback();
11403 $sql =
'DELETE FROM '.$this->db->prefix().
"ecm_files_extrafields";
11404 $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).
")";
11405 $resql = $this->db->query($sql);
11407 $this->error = $this->db->lasterror();
11408 $this->db->rollback();
11412 $sql =
'DELETE FROM '.$this->db->prefix().
"ecm_files";
11413 $sql .=
" WHERE src_object_type = '".$this->db->escape($this->table_element.(empty($this->module) ?
"" :
"@".$this->module)).
"' AND src_object_id = ".((int) $this->
id);
11414 $resql = $this->db->query($sql);
11416 $this->error = $this->db->lasterror();
11417 $this->db->rollback();
11422 $this->db->commit();
if( $user->socid > 0) if(! $user->hasRight('accounting', 'chartofaccount')) $object
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.
deleteLineCommon(User $user, $idline, $notrigger=0)
Delete a line of object in database.
isEmpty()
isEmpty We consider CommonObject isEmpty if this->id is empty
clearFieldError($fieldKey)
clear validation message result for a field
static getCountOfItemsLinkedByObjectID($fk_object_where, $field_where, $table_element)
Count items linked to an object id in association table.
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
update_price($exclspec=0, $roundingadjust='auto', $nodatabaseupdate=0, $seller=null)
Update total_ht, total_ttc, total_vat, total_localtax1, total_localtax2 for an object (sum of lines).
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.
fetchProject()
Load the project with id $this->fk_project into this->project.
fetch_thirdparty($force_thirdparty_id=0)
Load the third party of object, from id $this->socid or $this->fk_soc, into this->thirdparty.
static deleteAllItemsLinkedByObjectID($fk_object_where, $field_where, $table_element)
Function used to remove all items linked to an object id in association table.
setFieldError($fieldKey, $msg='')
set validation error message a field
validateField($fields, $fieldKey, $fieldValue)
Return validation test result for a field.
getDataToShowPhoto($modulepart, $imagesize)
Function used to get the logos or photos of an object.
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...
emtpyObjectVars()
Sets all object fields to null.
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.
setExtraField($key, $value)
Convenience method for setting the value of an extrafield without actually updating it in the databas...
setDocModel($user, $modelpdf)
Set last model used by doc generator.
deleteObjectLinked($sourceid=null, $sourcetype='', $targetid=null, $targettype='', $rowid=0, $f_user=null, $notrigger=0)
Delete all links between an object $this.
getExtraField($key)
Convenience method for retrieving the value of an extrafield without actually fetching it from the da...
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.
setBankAccount($fk_account, $notrigger=0, $userused=null)
Change the bank account.
setExtraParameters()
Set extra parameters.
setErrorsFromObject($object)
setErrorsFromObject
setShippingMethod($shipping_method_id, $notrigger=0, $userused=null)
Change the shipping method.
update_note_public($note)
Update public note (kept for backward compatibility)
getSpecialCode($lineid)
Get special code of a line.
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...
hasProductsOrServices($predefined=-1)
Function to say how many lines object contains.
static isExistingObject($element, $id, $ref='', $ref_ext='')
Check if an object id or ref exists If you don't need or want to instantiate the object and just need...
isObjectUsed($id=0, $entity=0)
Function to check if an object is used by others (by children).
updateRangOfLine($rowid, $rang)
Update position of line (rang)
getDefaultCreateValueFor($fieldname, $alternatevalue=null, $type='alphanohtml')
Return the default value to use for a field when showing the create form of object.
createCommon(User $user, $notrigger=0)
Create object in the database.
getTotalWeightVolume()
Return into unit=0, the calculated total of weight and volume of all lines * qty Calculate by adding ...
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.
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.
updateCommon(User $user, $notrigger=0)
Update object into database.
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.
deprecatedProperties()
Provide list of deprecated properties and replacements.
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.
getListContactId($source='external')
Return list of id of contacts of object.
setWarehouse($warehouse_id)
Change the warehouse.
setDeliveryAddress($id)
Define delivery address.
fetchBarCode()
Load data for barcode into properties ->barcode_type* Properties ->barcode_type that is id of barcode...
getTotalDiscount()
Function that returns the total amount HT of discounts applied for all lines.
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.
fetchLinesCommon($morewhere='', $noextrafields=0)
Load object in memory from the 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.
getElementType()
Return an element type string formatted like element_element target_type and source_type.
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 ...
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.
deleteByParentField($parentId=0, $parentField='', $filter='', $filtermode="AND")
Delete all child object from a parent ID.
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.
fetchCommon($id, $ref=null, $morewhere='', $noextrafields=0)
Load object in memory from the database.
deleteCommon(User $user, $notrigger=0, $forcechilddeletion=0)
Delete object in database.
getFormatedCustomerRef($objref)
Return customer ref for screen output.
getTooltipContentArray($params)
Return array of data 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...
showOptionals($extrafields, $mode='view', $params=null, $keysuffix='', $keyprefix='', $onetrtd='', $display_type='card')
Function to show lines of extrafields with output data.
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.
addThumbs($file, $quality=50)
Build thumb.
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.
const TYPE_CREDIT_NOTE
Credit note invoice.
Class to manage triggers.
Parent class to manage intervention document templates.
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 titre as m m statut as status
Or an array listing all the potential status of the object: array: int of the status => translated la...
getCountry($searchkey, $withcode='', $dbtouse=null, $outputlangs=null, $entconv=1, $searchlabel='')
Return country label, code or id from an id, code or label.
getState($id, $withcode='0', $dbtouse=null, $withregion=0, $outputlangs=null, $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.
completeFileArrayWithDatabaseInfo(&$filearray, $relativedir, $object=null)
Complete $filearray with data from database.
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($utf8_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.
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 information (by default a local PHP server timestamp) Rep...
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='', $noduplicate=0, $attop=0)
Set event messages in dol_events session object.
vatrate($rate, $addpercent=false, $info_bits=0, $usestarfornpr=0, $html=0)
Return a string with VAT rate label formatted for view output Used into pdf and HTML pages.
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2, $allowothertags=array())
Show picto whatever it's its name (generic function)
dol_print_ip($ip, $mode=0)
Return an IP formatted to be shown on screen.
img_delete($titlealt='default', $other='class="pictodelete"', $morecss='')
Show delete logo.
GETPOSTINT($paramname, $method=0)
Return the value of a $_GET or $_POST supervariable, converted into integer.
dol_format_address($object, $withcountry=0, $sep="\n", $outputlangs=null, $mode=0, $extralangcode='')
Return a formatted address (part address/zip/town/state) according to country rules.
dol_print_phone($phone, $countrycode='', $cid=0, $socid=0, $addlink='', $separ=" ", $withpicto='', $titlealt='', $adddivfloat=0, $morecss='paddingright')
Format phone numbers according to country.
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 '.
getCallerInfoString()
Get caller info as a string that can be appended to a log message.
dol_string_nospecial($str, $newstr='_', $badcharstoreplace='', $badcharstoremove='', $keepspaces=0)
Clean a string from all punctuation characters to use it as a ref or login.
dol_eval($s, $returnvalue=1, $hideerrors=1, $onlysimplestring='1')
Replace eval function to add more security.
img_object($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $allowothertags=array())
Show a picto called object_picto (generic function)
dol_print_url($url, $target='_blank', $max=32, $withpicto=0, $morecss='')
Show Url link.
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.
getPictoForType($key, $morecss='')
Return the picto for a data type.
forgeSQLFromUniversalSearchCriteria($filter, &$errorstr='', $noand=0, $nopar=0, $noerror=0)
forgeSQLFromUniversalSearchCriteria
dol_now($mode='auto')
Return date for now.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
getElementProperties($elementType)
Get an array with properties of an element.
dol_escape_js($stringtoescape, $mode=0, $noescapebackslashn=0)
Returns text escaped for inclusion into javascript code.
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false)
Output date in a string format according to outputlangs (or langs if not defined).
dol_sort_array(&$array, $index, $order='asc', $natsort=0, $case_sensitive=0, $keepindex=0)
Advanced sort array by the value of a given key, which produces ascending (default) or descending out...
if(!function_exists( 'dol_getprefix')) dol_include_once($relpath, $classname='')
Make an include_once using default root and alternate root if it fails.
newToken()
Return the value of token currently saved into session with name 'newtoken'.
dolPrintHTMLForAttribute($s, $escapeonlyhtmltags=0, $allowothertags=array())
Return a string ready to be output into an HTML attribute (alt, title, data-html, ....
dol_print_email($email, $cid=0, $socid=0, $addlink=0, $max=64, $showinvalid=1, $withpicto=0, $morecss='paddingrightonly')
Show EMail link formatted for HTML output.
getImageFileNameForSize($file, $extName, $extImgTarget='')
Return the filename of file to get the thumbs.
yn($yesno, $format=1, $color=0)
Return yes or no in current language.
get_date_range($date_start, $date_end, $format='', $outputlangs=null, $withparenthesis=1)
Format output for start and end date.
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.
dol_buildpath($path, $type=0, $returnemptyifnotfound=0)
Return path of url or filesystem.
dol_print_error($db=null, $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
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...
dol_sanitizeFileName($str, $newstr='_', $unaccent=1, $includequotes=0)
Clean a string to use it as a file name.
getDolGlobalString($key, $default='')
Return a 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.
getEntity($element, $shared=1, $currentobject=null)
Get list of entity id to use.
dol_sanitizePathName($str, $newstr='_', $unaccent=1)
Clean a string to use it as a path name.
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).
if(!defined( 'IMAGETYPE_WEBP')) 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.
global $conf
The following vars must be defined: $type2label $form $conf, $lang, The following vars may also be de...
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.
$conf db user
Active Directory does not allow anonymous connections.
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', $nosalt=0, $mode=0)
Returns a hash (non reversible encryption) of a string.
dolEncrypt($chain, $key='', $ciphering='', $forceseed='')
Encode a string with a symmetric encryption.
dolDecrypt($chain, $key='')
Decode a string with a symmetric encryption.