49require_once DOL_DOCUMENT_ROOT.
'/core/class/doldeprecationhandler.class.php';
50require_once DOL_DOCUMENT_ROOT.
'/core/class/commontrigger.class.php';
61 use DolDeprecationHandler;
98 public $errors = array();
109 public $warnings = array();
114 private $validateFieldsErrors = array();
132 public $element_for_permission;
137 public $table_element;
147 public $table_element_line =
'';
153 public $ismultientitymanaged;
163 public $array_options = array();
248 public $fields = array();
255 public $array_languages =
null;
260 public $contacts_ids;
265 public $contacts_ids_internal;
270 public $linked_objects;
275 public $other_linked_objects;
280 public $linkedObjectsIds;
285 public $linkedObjects;
290 private $linkedObjectsFullLoaded = array();
305 protected $table_ref_field =
'';
310 public $restrictiononfksoc = 0;
319 public $context = array();
436 private $commandeFournisseur;
452 public $ref_previous;
498 public $country_code;
541 public $barcode_type;
547 public $barcode_type_code;
553 public $barcode_type_label;
559 public $barcode_type_coder;
565 public $mode_reglement_id;
571 public $cond_reglement_id;
576 public $demand_reason_id;
582 public $transport_mode_id;
594 protected $depr_cond_reglement;
601 public $fk_delivery_address;
607 public $shipping_method_id;
613 public $shipping_method;
619 public $fk_multicurrency;
625 public $multicurrency_code;
631 public $multicurrency_tx;
636 public $multicurrency_total_ht;
641 public $multicurrency_total_tva;
646 public $multicurrency_total_localtax1;
651 public $multicurrency_total_localtax2;
656 public $multicurrency_total_ttc;
669 public $last_main_doc;
694 public $note_private;
719 public $total_localtax1;
725 public $total_localtax2;
742 public $actiontypecode;
748 public $comments = array();
774 public $civility_code;
780 public $date_creation;
785 public $date_validation;
790 public $date_modification;
804 private $date_update;
809 public $date_cloture;
814 public $user_creation_id;
819 public $user_validation_id;
824 public $user_closing_id;
829 public $user_modification_id;
835 public $fk_user_creat;
841 public $fk_user_modif;
847 public $next_prev_filter;
852 public $specimen = 0;
876 public $totalpaid_multicurrency;
882 public $labelStatus = array();
887 public $labelStatusShort = array();
898 public $showphoto_on_popup;
903 public $nb = array();
918 public $extraparams = array();
923 protected $childtables = array();
930 protected $childtablesoncascade = array();
935 public $cond_reglement_supplier_id;
942 public $deposit_percent;
948 public $warehouse_id;
953 public $isextrafieldmanaged = 0;
963 public $attachedfiles;
977 'alreadypaid' =>
'totalpaid',
978 'cond_reglement' =>
'depr_cond_reglement',
980 'commandeFournisseur' =>
'origin_object',
981 'expedition' =>
'origin_object',
982 'fk_project' =>
'fk_project',
983 'livraison' =>
'origin_object',
984 'projet' =>
'project',
985 'statut' =>
'status',
1004 $sql =
"SELECT rowid";
1005 $sql .=
" FROM ".$db->prefix().$element;
1006 $sql .=
" WHERE entity IN (".getEntity($element).
")";
1009 $sql .=
" AND rowid = ".((int) $id);
1011 $sql .=
" AND ref = '".$db->escape($ref).
"'";
1012 } elseif ($ref_ext) {
1013 $sql .=
" AND ref_ext = '".$db->escape($ref_ext).
"'";
1015 $error =
'ErrorWrongParameters';
1016 dol_syslog(get_class().
"::isExistingObject ".$error, LOG_ERR);
1019 if ($ref || $ref_ext) {
1020 $sql .=
" AND entity = ".((int)
$conf->entity);
1023 dol_syslog(get_class().
"::isExistingObject", LOG_DEBUG);
1024 $resql = $db->query($sql);
1026 $num = $db->num_rows($resql);
1045 $this->error =
$object->error;
1047 if (!empty(
$object->errors)) {
1048 $this->errors = array_merge($this->errors,
$object->errors);
1073 global $action, $extrafields, $langs, $hookmanager;
1076 $MAX_EXTRAFIELDS_TO_SHOW_IN_TOOLTIP =
getDolGlobalInt(
'MAX_EXTRAFIELDS_TO_SHOW_IN_TOOLTIP', 3);
1082 if (!empty($extrafields->attributes[$this->table_element][
'label'])) {
1083 $data[
'opendivextra'] =
'<div class="centpercent wordbreak divtooltipextra">';
1084 foreach ($extrafields->attributes[$this->table_element][
'label'] as $key => $val) {
1085 if ($extrafields->attributes[$this->table_element][
'type'][$key] ==
'separate') {
1089 if (empty($extrafields->attributes[$this->table_element][
'showintooltip'][$key])) {
1094 if ($count >= abs($MAX_EXTRAFIELDS_TO_SHOW_IN_TOOLTIP)) {
1095 $data[
'more_extrafields'] =
'<br>...';
1099 if ($enabled && isset($extrafields->attributes[$this->table_element][
'enabled'][$key])) {
1100 $enabled = (int)
dol_eval((
string) $extrafields->attributes[$this->table_element][
'enabled'][$key], 1, 1,
'2');
1102 if ($enabled && isset($extrafields->attributes[$this->table_element][
'list'][$key])) {
1103 $enabled = (int)
dol_eval((
string) $extrafields->attributes[$this->table_element][
'list'][$key], 1, 1,
'2');
1106 if ($perms && isset($extrafields->attributes[$this->table_element][
'perms'][$key])) {
1107 $perms = (int)
dol_eval((
string) $extrafields->attributes[$this->table_element][
'perms'][$key], 1, 1,
'2');
1109 if (empty($enabled)) {
1112 if (abs($enabled) != 1 && abs($enabled) != 3 && abs($enabled) != 5 && abs($enabled) != 4) {
1115 if (empty($perms)) {
1118 if (!empty($extrafields->attributes[$this->table_element][
'langfile'][$key])) {
1119 $langs->load($extrafields->attributes[$this->table_element][
'langfile'][$key]);
1121 $labelextra = $langs->trans((
string) $extrafields->attributes[$this->table_element][
'label'][$key]);
1122 if ($extrafields->attributes[$this->table_element][
'type'][$key] ==
'separate') {
1123 $data[$key] =
'<br><b><u>'. $labelextra .
'</u></b>';
1125 $value = (empty($this->array_options[
'options_' . $key]) ?
'' : $this->array_options[
'options_' . $key]);
1126 $data[$key] =
'<br><b>'. $labelextra .
':</b> ' . $extrafields->showOutputField($key, $value,
'', $this->table_element);
1130 $data[
'closedivextra'] =
'</div>';
1133 $hookmanager->initHooks(array($this->element .
'dao'));
1134 $parameters = array(
1135 'tooltipcontentarray' => &$data,
1136 'params' => $params,
1139 $hookmanager->executeHooks(
'getTooltipContent', $parameters, $this, $action);
1142 $label = implode($data);
1155 return $this->error.(is_array($this->errors) && count($this->errors) > 0 ? (($this->error !=
'' ?
', ' :
'').implode(
', ', $this->errors)) :
'');
1167 global $hookmanager;
1169 $parameters = array(
'objref' => $objref);
1171 $reshook = $hookmanager->executeHooks(
'getFormatedCustomerRef', $parameters, $this, $action);
1173 return $hookmanager->resArray[
'objref'];
1175 return $objref.(isset($hookmanager->resArray[
'objref']) ? $hookmanager->resArray[
'objref'] :
'');
1186 global $hookmanager;
1188 $parameters = array(
'objref' => $objref);
1190 $reshook = $hookmanager->executeHooks(
'getFormatedSupplierRef', $parameters, $this, $action);
1192 return $hookmanager->resArray[
'objref'];
1194 return $objref.(isset($hookmanager->resArray[
'objref']) ? $hookmanager->resArray[
'objref'] :
'');
1206 public function getFullAddress($withcountry = 0, $sep =
"\n", $withregion = 0, $extralangcode =
'')
1208 if ($withcountry && $this->country_id && (empty($this->country_code) || empty($this->country))) {
1209 require_once DOL_DOCUMENT_ROOT.
'/core/lib/company.lib.php';
1210 $tmparray =
getCountry($this->country_id,
'all');
1211 $this->country_code = $tmparray[
'code'];
1212 $this->country = $tmparray[
'label'];
1215 if ($withregion && $this->state_id && (empty($this->state_code) || empty($this->state) || empty($this->region) || empty($this->region_code))) {
1216 require_once DOL_DOCUMENT_ROOT.
'/core/lib/company.lib.php';
1217 $tmparray =
getState($this->state_id,
'all',
null, 1);
1218 $this->state_code = $tmparray[
'code'];
1219 $this->state = $tmparray[
'label'];
1220 $this->region_code = $tmparray[
'region_code'];
1221 $this->region = $tmparray[
'region'];
1240 if (empty($this->last_main_doc)) {
1244 include_once DOL_DOCUMENT_ROOT.
'/ecm/class/ecmfiles.class.php';
1245 $ecmfile =
new EcmFiles($this->db);
1246 $result = $ecmfile->fetch(0,
'', $this->last_main_doc);
1248 $this->error = $ecmfile->error;
1249 $this->errors = $ecmfile->errors;
1253 if (empty($ecmfile->id)) {
1255 if ($initsharekey) {
1256 require_once DOL_DOCUMENT_ROOT.
'/core/lib/security2.lib.php';
1278 } elseif (empty($ecmfile->share)) {
1280 if ($initsharekey) {
1281 require_once DOL_DOCUMENT_ROOT.
'/core/lib/security2.lib.php';
1283 $ecmfile->update($user);
1289 $urlwithouturlroot = preg_replace(
'/'.preg_quote(DOL_URL_ROOT,
'/').
'$/i',
'', trim(
$dolibarr_main_url_root));
1293 $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT;
1302 if (!empty($ecmfile->share)) {
1303 $paramlink .= ($paramlink ?
'&' :
'').
'hashp='.$ecmfile->share;
1305 if ($forcedownload) {
1306 $paramlink .= ($paramlink ?
'&' :
'').
'attachment=1';
1309 if ($relativelink) {
1310 $linktoreturn =
'document.php'.($paramlink ?
'?'.$paramlink :
'');
1312 $linktoreturn = $urlwithroot.
'/document.php'.($paramlink ?
'?'.$paramlink :
'');
1316 return $linktoreturn;
1330 public function add_contact($fk_socpeople, $type_contact, $source =
'external', $notrigger = 0)
1333 global $user, $langs;
1335 dol_syslog(get_class($this).
"::add_contact $fk_socpeople, $type_contact, $source, $notrigger");
1338 if ($fk_socpeople <= 0) {
1339 $langs->load(
"errors");
1340 $this->error = $langs->trans(
"ErrorWrongValueForParameterX",
"1");
1341 dol_syslog(get_class($this).
"::add_contact ".$this->error, LOG_ERR);
1346 $sql_check =
"SELECT rowid FROM ".$this->db->prefix().($source ==
'internal' ?
"user" :
"socpeople").
" WHERE rowid = ".((
int) $fk_socpeople);
1347 $resql_check = $this->db->query($sql_check);
1349 if (!$this->db->num_rows($resql_check)) {
1350 $langs->load(
"errors");
1351 $this->error = $langs->trans(
"ErrorRecordNotFound");
1352 dol_syslog(get_class($this).
"::add_contact Contact/user id ".$fk_socpeople.
" does not exist", LOG_ERR);
1356 $this->error = $this->db->lasterror();
1360 if (!$type_contact) {
1361 $langs->load(
"errors");
1362 $this->error = $langs->trans(
"ErrorWrongValueForParameterX",
"2");
1363 dol_syslog(get_class($this).
"::add_contact ".$this->error, LOG_ERR);
1368 if ($this->restrictiononfksoc && property_exists($this,
'socid') && !empty($this->socid) && $user->id > 0 && !$user->hasRight(
'societe',
'client',
'voir')) {
1369 $sql_allowed_contacts =
'SELECT COUNT(*) as cnt FROM '.$this->db->prefix().
'societe_commerciaux as sc';
1371 $sql_allowed_contacts .=
' WHERE sc.fk_soc = '.(int) $this->socid;
1372 $sql_allowed_contacts .=
' AND sc.fk_user = '.(int) $user->id;
1374 $resql_allowed_contacts = $this->db->query($sql_allowed_contacts);
1376 if (!$resql_allowed_contacts) {
1377 $this->errors[] = $this->db->lasterror();
1379 } elseif ($obj = $this->db->fetch_object($resql_allowed_contacts)) {
1380 if ($obj->cnt == 0) {
1381 $langs->load(
"companies");
1382 $this->error = $langs->trans(
"ErrorCommercialNotAllowedForThirdparty", $user->id);
1383 dol_syslog(get_class($this).
"::add_contact ".$this->error, LOG_ERR);
1389 $id_type_contact = 0;
1390 if (is_numeric($type_contact)) {
1391 $id_type_contact = $type_contact;
1394 $sql =
"SELECT tc.rowid";
1395 $sql .=
" FROM ".$this->db->prefix().
"c_type_contact as tc";
1396 $sql .=
" WHERE tc.element='".$this->db->escape($this->element).
"'";
1397 $sql .=
" AND tc.source='".$this->db->escape($source).
"'";
1398 $sql .=
" AND tc.code='".$this->db->escape($type_contact).
"' AND tc.active=1";
1400 $resql = $this->db->query($sql);
1402 $obj = $this->db->fetch_object($resql);
1404 $id_type_contact = $obj->rowid;
1408 if ($id_type_contact == 0) {
1409 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");
1417 $already_added =
false;
1418 if (is_array($TListeContacts) && !empty($TListeContacts)) {
1419 foreach ($TListeContacts as $array_contact) {
1420 if ($array_contact[
'status'] == 4 && $array_contact[
'id'] == $fk_socpeople && $array_contact[
'fk_c_type_contact'] == $id_type_contact) {
1421 $already_added =
true;
1427 if (!$already_added) {
1431 $sql =
"INSERT INTO ".$this->db->prefix().
"element_contact";
1432 $sql .=
" (element_id, fk_socpeople, datecreate, statut, fk_c_type_contact) ";
1433 $sql .=
" VALUES (".((int) $this->
id).
", ".((int) $fk_socpeople).
" , ";
1434 $sql .=
"'".$this->db->idate($datecreate).
"'";
1435 $sql .=
", 4, ".((int) $id_type_contact);
1438 $resql = $this->db->query($sql);
1441 $triggerPrefix = (empty($this->TRIGGER_PREFIX) ? strtoupper($this->element) : $this->TRIGGER_PREFIX);
1442 $result = $this->call_trigger($triggerPrefix.
'_ADD_CONTACT', $user);
1444 $this->db->rollback();
1449 $this->db->commit();
1452 if ($this->db->errno() ==
'DB_ERROR_RECORD_ALREADY_EXISTS') {
1453 $this->error = $this->db->errno();
1454 $this->db->rollback();
1457 $this->error = $this->db->lasterror();
1458 $this->db->rollback();
1478 $contacts = $objFrom->liste_contact(-1, $source);
1479 foreach ($contacts as $contact) {
1480 if ($this->
add_contact($contact[
'id'], $contact[
'fk_c_type_contact'], $contact[
'source']) < 0) {
1497 public function update_contact($rowid, $statut, $type_contact_id = 0, $fk_socpeople = 0)
1501 $sql =
"UPDATE ".$this->db->prefix().
"element_contact set";
1502 $sql .=
" statut = ".((int) $statut);
1503 if ($type_contact_id) {
1504 $sql .=
", fk_c_type_contact = ".((int) $type_contact_id);
1506 if ($fk_socpeople) {
1507 $sql .=
", fk_socpeople = ".((int) $fk_socpeople);
1509 $sql .=
" where rowid = ".((int) $rowid);
1511 $resql = $this->db->query($sql);
1515 $this->error = $this->db->lasterror();
1536 if ($this->
id > 0) {
1537 $sql =
"SELECT ec.rowid FROM ".$this->db->prefix().
"element_contact as ec, ".$this->db->prefix().
"c_type_contact as tc";
1538 $sql .=
" WHERE ec.rowid = ".((int) $rowid).
" AND ec.element_id = ".((int) $this->
id);
1539 $sql .=
" AND ec.fk_c_type_contact = tc.rowid AND tc.element = '".$this->db->escape($this->element).
"'";
1540 $resql = $this->db->query($sql);
1541 if (!$resql || !$this->db->num_rows($resql)) {
1542 $this->error =
'ErrorRecordNotFound';
1549 if (!$error && empty($notrigger)) {
1551 $this->context[
'contact_id'] = ((int) $rowid);
1552 $triggerPrefix = (empty($this->TRIGGER_PREFIX) ? strtoupper($this->element) : $this->TRIGGER_PREFIX);
1553 $result = $this->call_trigger($triggerPrefix.
'_DELETE_CONTACT', $user);
1561 dol_syslog(get_class($this).
"::delete_contact", LOG_DEBUG);
1563 $sql =
"DELETE FROM ".MAIN_DB_PREFIX.
"element_contact";
1564 $sql .=
" WHERE rowid = ".((int) $rowid);
1566 $result = $this->db->query($sql);
1569 $this->errors[] = $this->db->lasterror();
1574 $this->db->commit();
1577 $this->error = $this->db->lasterror();
1578 $this->db->rollback();
1598 if (!empty($typeContact)) {
1599 foreach ($typeContact as $key => $value) {
1600 array_push($temp, $key);
1602 $listId = implode(
",", $temp);
1607 if (empty($listId)) {
1611 $sql =
"DELETE FROM ".$this->db->prefix().
"element_contact";
1612 $sql .=
" WHERE element_id = ".((int) $this->
id);
1613 $sql .=
" AND fk_c_type_contact IN (".$this->db->sanitize($listId).
")";
1615 dol_syslog(get_class($this).
"::delete_linked_contact", LOG_DEBUG);
1616 if ($this->db->query($sql)) {
1619 $this->error = $this->db->lasterror();
1636 public function liste_contact($statusoflink = -1, $source =
'external', $list = 0, $code =
'', $status = -1, $arrayoftcids = array())
1643 $sql =
"SELECT ec.rowid, ec.statut as statuslink, ec.fk_socpeople as id, ec.fk_c_type_contact";
1644 if ($source ==
'internal') {
1645 $sql .=
", '-1' as socid, t.statut as statuscontact, t.login, t.photo, t.gender, t.fk_country as country_id";
1647 if ($source ==
'external' || $source ==
'thirdparty') {
1648 $sql .=
", t.fk_soc as socid, t.statut as statuscontact, t.fk_pays as country_id";
1650 $sql .=
", t.civility as civility, t.lastname as lastname, t.firstname, t.email, t.address, t.zip, t.town";
1651 if (empty($arrayoftcids)) {
1652 $sql .=
", tc.source, tc.element, tc.code, tc.libelle as type_label, co.label as country";
1655 if (empty($arrayoftcids)) {
1656 $sql .=
" ".$this->db->prefix().
"c_type_contact as tc,";
1658 $sql .=
" ".$this->db->prefix().
"element_contact as ec";
1659 if ($source ==
'internal') {
1660 $sql .=
" LEFT JOIN ".$this->db->prefix().
"user as t on ec.fk_socpeople = t.rowid";
1661 $sql .=
" LEFT JOIN ".$this->db->prefix().
"c_country as co ON co.rowid = t.fk_country";
1663 if ($source ==
'external' || $source ==
'thirdparty') {
1664 $sql .=
" LEFT JOIN ".$this->db->prefix().
"socpeople as t on ec.fk_socpeople = t.rowid";
1665 $sql .=
" LEFT JOIN ".$this->db->prefix().
"c_country as co ON co.rowid = t.fk_pays";
1667 $sql .=
" WHERE ec.element_id = ".((int) $this->
id);
1668 if (empty($arrayoftcids)) {
1669 $sql .=
" AND ec.fk_c_type_contact = tc.rowid";
1670 $sql .=
" AND tc.element = '".$this->db->escape($this->element).
"'";
1672 $sql .=
" AND tc.code = '".$this->db->escape($code).
"'";
1674 if ($source ==
'internal') {
1675 $sql .=
" AND tc.source = 'internal'";
1677 if ($source ==
'external' || $source ==
'thirdparty') {
1678 $sql .=
" AND tc.source = 'external'";
1680 $sql .=
" AND tc.active = 1";
1682 $sql .=
" AND ec.fk_c_type_contact IN (".$this->db->sanitize(implode(
',', $arrayoftcids)).
")";
1685 $sql .=
" AND t.statut = ".((int) $status);
1687 if ($statusoflink >= 0) {
1688 $sql .=
" AND ec.statut = ".((int) $statusoflink);
1690 $sql .=
" ORDER BY t.lastname ASC";
1692 dol_syslog(get_class($this).
"::liste_contact", LOG_DEBUG);
1693 $resql = $this->db->query($sql);
1695 $num = $this->db->num_rows($resql);
1698 $obj = $this->db->fetch_object($resql);
1701 $transkey =
"TypeContact_".$obj->element.
"_".$obj->source.
"_".$obj->code;
1702 $label_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->type_label);
1704 'parentId' => $this->
id,
1705 'source' => $obj->source,
1706 'socid' => $obj->socid,
1708 'nom' => $obj->lastname,
1709 'civility' => $obj->civility,
1710 'lastname' => $obj->lastname,
1711 'firstname' => $obj->firstname,
1712 'email' => $obj->email,
1713 'address' => $obj->address,
1715 'town' => $obj->town,
1716 'country_id' => $obj->country_id,
1717 'country' => $obj->country,
1718 'login' => (empty($obj->login) ?
'' : $obj->login),
1719 'photo' => (empty($obj->photo) ?
'' : $obj->photo),
1720 'gender' => (empty($obj->gender) ?
'' : $obj->gender),
1721 'statuscontact' => $obj->statuscontact,
1722 'rowid' => $obj->rowid,
1723 'code' => $obj->code,
1724 'libelle' => $label_type,
1725 'status' => (
int) $obj->statuslink,
1726 'fk_c_type_contact' => $obj->fk_c_type_contact
1729 $tab[$i] = $obj->id;
1737 $this->error = $this->db->lasterror();
1738 dol_print_error($this->db);
1752 $sql =
"SELECT ec.datecreate, ec.statut, ec.fk_socpeople, ec.fk_c_type_contact,";
1753 $sql .=
" tc.code, tc.libelle as type_label";
1754 $sql .=
" FROM (".$this->db->prefix().
"element_contact as ec, ".$this->db->prefix().
"c_type_contact as tc)";
1755 $sql .=
" WHERE ec.rowid =".((int) $rowid);
1756 $sql .=
" AND ec.fk_c_type_contact = tc.rowid";
1757 $sql .=
" AND tc.element = '".$this->db->escape($this->element).
"'";
1759 dol_syslog(get_class($this).
"::swapContactStatus", LOG_DEBUG);
1760 $resql = $this->db->query($sql);
1762 $obj = $this->db->fetch_object($resql);
1763 $newstatut = ($obj->statut == 4) ? 5 : 4;
1765 $this->db->free($resql);
1768 $this->error = $this->db->error();
1769 dol_print_error($this->db);
1785 public function liste_type_contact($source =
'internal', $order =
'position', $option = 0, $activeonly = 0, $code =
'')
1790 $sanitized_order = $order;
1792 if (empty($sanitized_order)) {
1793 $sanitized_order =
'position';
1795 if ($sanitized_order ==
'position') {
1796 $sanitized_order .=
',code';
1801 $sql =
"SELECT DISTINCT tc.rowid, tc.code, tc.libelle as type_label, tc.position";
1802 $sql .=
" FROM ".$this->db->prefix().
"c_type_contact as tc";
1803 $sql .=
" WHERE tc.element = '".$this->db->escape($this->element).
"'";
1804 if ($activeonly == 1) {
1805 $sql .=
" AND tc.active = 1";
1807 if (!empty($source) && $source !=
'all') {
1808 $sql .=
" AND tc.source = '".$this->db->escape($source).
"'";
1810 if (!empty($code)) {
1811 $sql .=
" AND tc.code = '".$this->db->escape($code).
"'";
1813 $sql .= $this->db->order($sanitized_order,
'ASC');
1816 $resql = $this->db->query($sql);
1818 $this->error = $this->db->lasterror();
1823 $num = $this->db->num_rows($resql);
1826 $obj = $this->db->fetch_object($resql);
1828 $transkey =
"TypeContact_".$this->element.
"_".$source.
"_".$obj->code;
1829 $label_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $langs->trans($obj->type_label));
1830 if (empty($option)) {
1831 $tab[$obj->rowid] = $label_type;
1832 } elseif ($option == 1) {
1833 $tab[$obj->code] = $label_type;
1835 $tab[$obj->rowid] = array(
'id' => $obj->rowid,
'code' => $obj->code,
'label' => $label_type);
1854 public function listeTypeContacts($source =
'internal', $option = 0, $activeonly = 0, $code =
'', $element =
'', $excludeelement =
'')
1858 $langs->loadLangs(array(
'bills',
'contracts',
'interventions',
'orders',
'projects',
'propal',
'ticket',
'agenda'));
1862 $sql =
"SELECT DISTINCT tc.rowid, tc.code, tc.libelle as type_label, tc.position, tc.element, tc.module";
1863 $sql .=
" FROM ".$this->db->prefix().
"c_type_contact as tc";
1865 $sqlWhere = array();
1866 if (!empty($element)) {
1867 $sqlWhere[] =
" tc.element='".$this->db->escape($element).
"'";
1869 if (!empty($excludeelement)) {
1870 $sqlWhere[] =
" tc.element <> '".$this->db->escape($excludeelement).
"'";
1873 if ($activeonly == 1) {
1874 $sqlWhere[] =
" tc.active=1";
1877 if (!empty($source) && $source !=
'all') {
1878 $sqlWhere[] =
" tc.source='".$this->db->escape($source).
"'";
1881 if (!empty($code)) {
1882 $sqlWhere[] =
" tc.code='".$this->db->escape($code).
"'";
1885 if (count($sqlWhere) > 0) {
1886 $sql .=
" WHERE ".implode(
' AND ', $sqlWhere);
1889 $sql .= $this->db->order(
'tc.element, tc.position',
'ASC');
1892 $resql = $this->db->query($sql);
1894 $num = $this->db->num_rows($resql);
1896 $langs->loadLangs(array(
"propal",
"orders",
"bills",
"suppliers",
"contracts",
"supplier_proposal"));
1898 while ($obj = $this->db->fetch_object($resql)) {
1899 $modulename = $obj->module ?? $obj->element;
1900 if (strpos($obj->element,
'project') !==
false) {
1901 $modulename =
'projet';
1902 } elseif ($obj->element ==
'contrat') {
1903 $element =
'contract';
1904 } elseif ($obj->element ==
'action') {
1905 $modulename =
'agenda';
1906 } elseif (strpos($obj->element,
'supplier') !==
false && $obj->element !=
'supplier_proposal') {
1907 $modulename =
'fournisseur';
1910 $label_element = $langs->trans(
'ContactDefault_'.$obj->element);
1911 $tmpelement = $obj->element;
1912 $transkey =
"TypeContact_".$tmpelement.
"_".$source.
"_".$obj->code;
1913 $label_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->type_label);
1914 $tab[$obj->rowid] = $label_element.
' - '.$label_type;
1920 $this->error = $this->db->lasterror();
1941 if (!
getDolGlobalInt(
'SHIPPING_USE_ITS_OWN_CONTACTS') && $this->element ==
'shipping' && $this->origin_id != 0) {
1942 $id = $this->origin_id;
1943 $element =
'commande';
1944 } elseif ($this->element ==
'reception' && $this->origin_id != 0) {
1945 $id = $this->origin_id;
1946 $element =
'order_supplier';
1949 $element = $this->element;
1952 $sql =
"SELECT ec.fk_socpeople";
1953 $sql .=
" FROM ".$this->db->prefix().
"element_contact as ec,";
1954 if ($source ==
'internal') {
1955 $sql .=
" ".$this->db->prefix().
"user as c,";
1957 if ($source ==
'external') {
1958 $sql .=
" ".$this->db->prefix().
"socpeople as c,";
1960 $sql .=
" ".$this->db->prefix().
"c_type_contact as tc";
1961 $sql .=
" WHERE ec.element_id = ".((int) $id);
1962 $sql .=
" AND ec.fk_socpeople = c.rowid";
1963 if ($source ==
'internal') {
1964 $sql .=
" AND c.entity IN (".getEntity(
'user').
")";
1966 if ($source ==
'external') {
1967 $sql .=
" AND c.entity IN (".getEntity(
'societe').
")";
1969 $sql .=
" AND ec.fk_c_type_contact = tc.rowid";
1970 $sql .=
" AND tc.element = '".$this->db->escape($element).
"'";
1971 $sql .=
" AND tc.source = '".$this->db->escape($source).
"'";
1973 $sql .=
" AND tc.code = '".$this->db->escape($code).
"'";
1975 $sql .=
" AND tc.active = 1";
1977 $sql .=
" AND ec.statut = ".((int) $status);
1980 dol_syslog(get_class($this).
"::getIdContact", LOG_DEBUG);
1981 $resql = $this->db->query($sql);
1983 while ($obj = $this->db->fetch_object($resql)) {
1984 $result[$i] = $obj->fk_socpeople;
1988 $this->error = $this->db->error();
2005 if (empty($contactid)) {
2006 $contactid = $this->contact_id;
2009 if (empty($contactid)) {
2013 require_once DOL_DOCUMENT_ROOT.
'/contact/class/contact.class.php';
2014 $contact =
new Contact($this->db);
2015 $result = $contact->fetch($contactid);
2016 $this->contact = $contact;
2031 if (empty($this->socid) && empty($this->fk_soc) && empty($force_thirdparty_id)) {
2035 require_once DOL_DOCUMENT_ROOT.
'/societe/class/societe.class.php';
2037 $idtofetch = isset($this->socid) ? $this->socid : (isset($this->fk_soc) ? $this->fk_soc : 0);
2038 if ($force_thirdparty_id) {
2039 $idtofetch = $force_thirdparty_id;
2043 $thirdparty =
new Societe($this->db);
2044 $result = $thirdparty->fetch($idtofetch);
2046 $this->errors = array_merge($this->errors, $thirdparty->errors);
2048 $this->thirdparty = $thirdparty;
2052 $this->thirdparty->price_level = 1;
2071 if (!$this->table_ref_field) {
2075 $sql =
"SELECT rowid FROM ".$this->db->prefix().$this->table_element;
2076 $sql .=
" WHERE ".$this->db->sanitize($this->table_ref_field).
" LIKE '".$this->db->escape($ref).
"'";
2079 $query = $this->db->query($sql);
2081 if (!$this->db->num_rows($query)) {
2085 $result = $this->db->fetch_object($query);
2087 if (method_exists($this,
'fetch')) {
2088 return $this->fetch($result->rowid);
2090 $this->error =
'Fetch method not implemented on '.get_class($this);
2091 dol_syslog(get_class($this).
'::fetchOneLike Error='.$this->error, LOG_ERR);
2092 array_push($this->errors, $this->error);
2121 dol_syslog(get_class($this).
'::fetchBarCode this->element='.$this->element.
' this->barcode_type='.$this->barcode_type);
2123 $idtype = $this->barcode_type;
2124 if (empty($idtype) && $idtype !=
'0') {
2125 if ($this->element ==
'product' &&
getDolGlobalString(
'PRODUIT_DEFAULT_BARCODE_TYPE')) {
2127 } elseif ($this->element ==
'societe') {
2130 dol_syslog(
'Call fetchBarCode with barcode_type not defined and cannot be guessed', LOG_WARNING);
2135 if (empty($this->barcode_type) || empty($this->barcode_type_code) || empty($this->barcode_type_label) || empty($this->barcode_type_coder)) {
2136 $sql =
"SELECT rowid, code, libelle as label, coder";
2137 $sql .=
" FROM ".$this->db->prefix().
"c_barcode_type";
2138 $sql .=
" WHERE rowid = ".((int) $idtype);
2140 $resql = $this->db->query($sql);
2142 $obj = $this->db->fetch_object($resql);
2144 $this->barcode_type = $obj->rowid;
2145 $this->barcode_type_code = $obj->code;
2146 $this->barcode_type_label = $obj->label;
2147 $this->barcode_type_coder = $obj->coder;
2150 dol_print_error($this->db);
2165 include_once DOL_DOCUMENT_ROOT.
'/projet/class/project.class.php';
2172 if (empty($this->fk_project)) {
2176 $project =
new Project($this->db);
2177 $result = $project->fetch($this->fk_project);
2179 $this->project = $project;
2221 include_once DOL_DOCUMENT_ROOT.
'/product/class/product.class.php';
2224 if (empty($this->fk_product)) {
2228 $product =
new Product($this->db);
2230 $result = $product->fetch($this->fk_product);
2232 $this->product = $product;
2245 if (empty($this->warehouse_id) && empty($this->fk_warehouse) && empty($force_warehouse_id)) {
2249 include_once DOL_DOCUMENT_ROOT.
'/product/stock/class/entrepot.class.php';
2252 $idtofetch = isset($this->warehouse_id) ? $this->warehouse_id : (isset($this->fk_warehouse) ? $this->fk_warehouse : 0);
2253 if (!empty($force_warehouse_id)) {
2254 $idtofetch = $force_warehouse_id;
2258 $warehouse =
new Entrepot($this->db);
2259 $result = $warehouse->fetch($idtofetch);
2261 $this->errors = array_merge($this->errors, $warehouse->errors);
2263 $this->warehouse = $warehouse;
2281 $user =
new User($this->db);
2282 $result = $user->fetch($userid);
2283 $this->
user = $user;
2297 $tmpclassname = $this->origin ? $this->origin : $this->origin_type;
2300 if ($tmpclassname ==
'shipping') {
2301 $tmpclassname =
'Expedition';
2303 if ($tmpclassname ==
'delivery') {
2304 $tmpclassname =
'Livraison';
2306 if ($tmpclassname ==
'order_supplier' || $tmpclassname ==
'supplier_order') {
2307 $tmpclassname =
'CommandeFournisseur';
2310 $classname = ucfirst($tmpclassname);
2312 $this->origin_object =
new $classname($this->db);
2314 $this->origin_object->fetch($this->origin_id);
2332 $sql =
"SELECT rowid FROM ".$this->db->prefix().$table;
2333 $sql .=
" WHERE ".$this->db->sanitize($field).
" = '".$this->db->escape($key).
"'";
2334 if (!empty($element)) {
2335 $sql .=
" AND entity IN (".getEntity($element).
")";
2337 $sql .=
" AND entity = ".((int)
$conf->entity);
2340 dol_syslog(get_class($this).
'::fetchObjectFrom', LOG_DEBUG);
2341 $resql = $this->db->query($sql);
2343 $obj = $this->db->fetch_object($resql);
2346 if (method_exists($this,
'fetch')) {
2347 $result = $this->fetch($obj->rowid);
2349 $this->error =
'fetch() method not implemented on '.get_class($this);
2350 dol_syslog(get_class($this).
'::fetchOneLike Error='.$this->error, LOG_ERR);
2351 array_push($this->errors, $this->error);
2371 if (!empty($id) && !empty($field) && !empty($table)) {
2372 if (!preg_match(
'/^[a-zA-Z_][a-zA-Z0-9_]*$/', $table)) {
2373 dol_syslog(get_class($this).
'::getValueFrom Bad table name: '.$table, LOG_WARNING);
2376 if (!preg_match(
'/^[a-zA-Z_][a-zA-Z0-9_.]*$/', $field)) {
2377 dol_syslog(get_class($this).
'::getValueFrom Bad field name: '.$field, LOG_WARNING);
2381 $sql =
"SELECT ".$this->db->sanitize($field).
" FROM ".$this->db->prefix().$this->db->sanitize($table);
2382 $sql .=
" WHERE rowid = ".((int) $id);
2384 dol_syslog(get_class($this).
'::getValueFrom', LOG_DEBUG);
2385 $resql = $this->db->query($sql);
2387 $row = $this->db->fetch_row($resql);
2400 protected $fieldValueBeingSet = array();
2427 if (!empty($this->fieldValueBeingSet[$fieldKey])) {
2430 dol_syslog(get_class($this).
"::setFieldValue recursive call detected on field '".$fieldKey.
"', aborting to avoid infinite loop", LOG_WARNING);
2435 $this->
setFieldError($fieldKey, $langs->trans(
'FieldNotFoundInObject'));
2440 $this->
setFieldError($fieldKey, $langs->trans(
'FieldNotAllowedForEdit'));
2448 if ($this->oldcopy ===
null || !is_object($this->oldcopy)) {
2449 $this->oldcopy = clone $this;
2456 if (is_object($this->oldcopy) && property_exists($this, $property) && property_exists($this->oldcopy, $property)) {
2457 $this->oldcopy->$property = $this->$property;
2460 $this->fieldValueBeingSet[$fieldKey] =
true;
2463 $this->$property = $value;
2470 if (!empty($deprecatedProperties) && is_array($deprecatedProperties)) {
2471 foreach ($deprecatedProperties as $oldProperty => $newProperty) {
2472 if ($fieldKey === $oldProperty && property_exists($this, $newProperty)) {
2473 if (is_object($this->oldcopy) && property_exists($this->oldcopy, $newProperty) && property_exists($this->oldcopy, $oldProperty)) {
2474 $this->oldcopy->$newProperty = $this->oldcopy->$oldProperty;
2476 $this->$newProperty = $value;
2477 } elseif ($fieldKey === $newProperty && property_exists($this, $oldProperty)) {
2478 if (is_object($this->oldcopy) && property_exists($this->oldcopy, $oldProperty) && property_exists($this->oldcopy, $newProperty)) {
2479 $this->oldcopy->$oldProperty = $this->oldcopy->$newProperty;
2481 $this->$oldProperty = $value;
2490 unset($this->fieldValueBeingSet[$fieldKey]);
2538 return property_exists($this, $property) ? $this->$property :
null;
2552 if ($field ==
'note_public' || $field ==
'note_private') {
2553 return $this->
update_note((
string) $this->$field, $field ==
'note_public' ?
'_public' :
'_private');
2556 $type = $this->fields[$field][
'type'];
2557 if (preg_match(
'/^(int|integer)\b/', $type)) {
2559 } elseif (in_array($type, array(
'date',
'datetime',
'timestamp'))) {
2564 $trigkey = (property_exists($this,
'TRIGGER_PREFIX') && !empty($this->TRIGGER_PREFIX) ? $this->TRIGGER_PREFIX : strtoupper($this->element)).
'_MODIFY';
2584 $langs->load(
'errors');
2585 $this->error = $langs->trans(
'ErrorFieldIsNotEditable');
2586 $this->errors[] = $this->error;
2594 if (empty($this->error)) {
2597 $this->errors[] = $this->error;
2604 $this->$property = $oldvalue;
2605 if (empty($this->error) && !empty($this->errors)) {
2606 $this->error = implode(
', ', $this->errors);
2627 $key =
'ajaxfield_'.$field;
2628 $type = $this->fields[$field][
'type'];
2634 if ($type ==
'html') {
2636 } elseif (preg_match(
'/^(varchar|text)\b/', $type)) {
2637 return GETPOST($key,
'alphanohtml');
2638 } elseif (preg_match(
'/^(int|integer)\b/', $type)) {
2640 } elseif ($type ==
'date') {
2643 } elseif (in_array($type, array(
'datetime',
'timestamp'))) {
2664 $fielddef = $this->fields[$field];
2665 $fielddef[
'visible'] = 1;
2667 return $this->showOutputField($fielddef, $field, $this->
getFieldUiValue($field));
2682 $htmlname =
'ajaxfield_'.$field;
2685 if ($field ==
'note_public' || $field ==
'note_private') {
2686 require_once DOL_DOCUMENT_ROOT.
'/core/class/doleditor.class.php';
2687 $withckeditor =
isModEnabled(
'fckeditor') &&
getDolGlobalString($field ==
'note_public' ?
'FCKEDITOR_ENABLE_NOTE_PUBLIC' :
'FCKEDITOR_ENABLE_NOTE_PRIVATE');
2688 $doleditor =
new DolEditor($htmlname, (
string) $value,
'100%', 200,
'dolibarr_notes',
'In',
true,
false, $withckeditor, 12,
'95%');
2690 return (
string) $doleditor->Create(1);
2694 $fielddef = $this->fields[$field];
2695 $fielddef[
'visible'] = 1;
2697 return $this->
showInputField($fielddef, $field, $value,
'',
'',
'ajaxfield_');
2716 public function setValueFrom($field, $value, $table =
'', $id =
null, $format =
'', $id_field =
'', $fuser =
null, $trigkey =
'', $fk_user_field =
'fk_user_modif')
2720 if (empty($table)) {
2721 $table = $this->table_element;
2726 if (empty($format)) {
2729 if (empty($id_field)) {
2730 $id_field =
'rowid';
2733 $propfield = $field;
2737 if ($table ==
'product') {
2738 if ($field ==
'note_private') {
2740 $propfield =
'note_private';
2741 } elseif ($field ==
'status') {
2743 $propfield =
'status';
2744 } elseif ($field ==
'status_buy') {
2746 $propfield =
'status_buy';
2747 } elseif ($field ==
'status_batch') {
2749 $propfield =
'status_batch';
2753 if (in_array($table, array(
'actioncomm',
'adherent',
'advtargetemailing',
'cronjob',
'establishment'))) {
2754 $fk_user_field =
'fk_user_mod';
2756 if (in_array($table, array(
'prelevement_bons'))) {
2757 $fk_user_field =
'';
2760 if (!preg_match(
'/^[a-zA-Z_][a-zA-Z0-9_]*$/', $table)) {
2761 dol_syslog(get_class($this).
'::getValueFrom Bad table name: '.$table, LOG_WARNING);
2764 if (!preg_match(
'/^[a-zA-Z_][a-zA-Z0-9_.]*$/', $field)) {
2765 dol_syslog(get_class($this).
'::getValueFrom Bad field name: '.$field, LOG_WARNING);
2771 $sql =
"SELECT " . $this->db->sanitize($field);
2772 $sql .=
" FROM " . MAIN_DB_PREFIX . $this->db->sanitize($table);
2773 $sql .=
" WHERE " . $this->db->sanitize($id_field) .
" = " . ((int) $id);
2775 $resql = $this->db->query($sql);
2777 if ($obj = $this->db->fetch_object($resql)) {
2778 if ($format ==
'date') {
2779 $oldvalue = $this->db->jdate($obj->$field);
2781 $oldvalue = $obj->$field;
2785 $this->error = $this->db->lasterror();
2796 $sql =
"UPDATE ".$this->db->prefix().$table.
" SET ";
2798 if ($format ==
'text') {
2799 $sql .= $this->db->sanitize($field).
" = '".$this->db->escape($value).
"'";
2800 } elseif ($format ==
'int') {
2801 $sql .= $this->db->sanitize($field).
" = ".((int) $value);
2802 } elseif ($format ==
'date') {
2803 $sql .= $this->db->sanitize($field).
" = ".($value ?
"'".$this->db->idate($value).
"'" :
"null");
2804 } elseif ($format ==
'dategmt') {
2805 $sql .= $this->db->sanitize($field).
" = ".($value ?
"'".$this->db->idate($value,
'gmt').
"'" :
"null");
2808 if ($fk_user_field) {
2809 if (!empty($fuser) && is_object($fuser)) {
2810 $sql .=
", ".$this->db->sanitize($fk_user_field).
" = ".((int) $fuser->id);
2811 } elseif (empty($fuser) || $fuser !=
'none') {
2812 $sql .=
", ".$this->db->sanitize($fk_user_field).
" = ".((int) $user->id);
2816 $sql .=
" WHERE ".$this->db->sanitize($id_field).
" = ".((int) $id);
2818 $resql = $this->db->query($sql);
2822 if (method_exists($this,
'fetch')) {
2823 $result = $this->fetch(
$id);
2828 $this->oldcopy = clone $this;
2829 if (property_exists($this->oldcopy, $field)) {
2830 $this->oldcopy->$field = $oldvalue;
2832 if ($propfield != $field && property_exists($this->oldcopy, $propfield)) {
2833 $this->oldcopy->$propfield = $oldvalue;
2836 if (empty($this->context[
'actionmsgmore'])) {
2837 $this->context[
'actionmsgmore'] =
'Trigger called by setValueFrom';
2841 $result = $this->call_trigger($trigkey, (!empty($fuser) && is_object($fuser)) ? $fuser : $user);
2847 if (property_exists($this, $field)) {
2848 $this->$field = $value;
2850 if ($propfield != $field && property_exists($this, $propfield)) {
2851 $this->$propfield = $value;
2856 $this->db->commit();
2859 if (property_exists($this, $field)) {
2860 $this->$field = $oldvalue;
2862 if ($propfield != $field && property_exists($this, $propfield)) {
2863 $this->$propfield = $oldvalue;
2865 $this->db->rollback();
2869 if ($this->db->lasterrno() ==
'DB_ERROR_RECORD_ALREADY_EXISTS') {
2870 $this->error =
'DB_ERROR_RECORD_ALREADY_EXISTS';
2872 $this->error = $this->db->lasterror();
2874 $this->db->rollback();
2893 global
$conf, $user;
2895 if (!$this->table_element) {
2896 dol_print_error(
null, get_class($this).
"::load_previous_next_ref was called on object with property table_element not defined");
2899 if ($fieldid ==
'none') {
2904 if (in_array($this->table_element, array(
'facture_rec',
'facture_fourn_rec')) && $fieldid ==
'title') {
2910 if ($user->socid > 0) {
2911 $socid = $user->socid;
2916 $aliastablesociete =
's';
2917 if ($this->element ==
'societe') {
2918 $aliastablesociete =
'te';
2920 $restrictiononfksoc = empty($this->restrictiononfksoc) ? 0 : $this->restrictiononfksoc;
2923 $sql =
"SELECT te.".$this->db->sanitize($fieldid);
2924 $sql .=
" FROM ".(empty($nodbprefix) ? $this->db->prefix() :
'').$this->table_element.
" as te";
2925 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2926 $tmparray = explode(
'@', $this->ismultientitymanaged);
2927 $sql .=
", ".$this->db->prefix().$this->db->sanitize($tmparray[1]).
" as ".($tmparray[1] ==
'societe' ?
's' :
'parenttable');
2928 } elseif ($restrictiononfksoc == 1 && $this->element !=
'societe' && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2929 $sql .=
", ".$this->db->prefix().
"societe as s";
2930 } elseif ($restrictiononfksoc == 2 && $this->element !=
'societe' && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2931 $sql .=
" LEFT JOIN ".$this->db->prefix().
"societe as s ON te.fk_soc = s.rowid";
2933 if ($restrictiononfksoc && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2934 $sql .=
" LEFT JOIN ".$this->db->prefix().
"societe_commerciaux as sc ON ".$aliastablesociete.
".rowid = sc.fk_soc";
2936 if ($fieldid ==
'rowid') {
2937 $sql .=
" WHERE te.".$this->db->sanitize($fieldid).
" < ".((int) $this->
id);
2938 } elseif ($fieldid ==
'label') {
2940 $sql .=
" WHERE te.".$this->db->sanitize($fieldid).
" < '".$this->db->escape((
string) $this->label).
"'";
2942 $sql .=
" WHERE te.".$this->db->sanitize($fieldid).
" < '".$this->db->escape((
string) $this->
ref).
"'";
2944 if ($restrictiononfksoc == 1 && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2945 $sql .=
" AND sc.fk_user = ".((int) $user->id);
2947 if ($restrictiononfksoc == 2 && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2948 $sql .=
" AND (sc.fk_user = ".((int) $user->id).
' OR te.fk_soc IS NULL)';
2951 $filtermax = $filter;
2956 if ($errormessage) {
2957 if (!preg_match(
'/^\s*AND/i', $filtermax)) {
2965 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2966 $tmparray = explode(
'@', $this->ismultientitymanaged);
2967 $sql .=
" AND te.".$this->db->sanitize($tmparray[0]).
" = ".($tmparray[1] ==
"societe" ?
"s" :
"parenttable").
".rowid";
2968 } elseif ($restrictiononfksoc == 1 && $this->element !=
'societe' && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2969 $sql .=
' AND te.fk_soc = s.rowid';
2971 if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
2972 if ($this->element ==
'user' &&
getDolGlobalInt(
'MULTICOMPANY_TRANSVERSE_MODE')) {
2973 if (!empty($user->admin) && empty($user->entity) &&
$conf->entity == 1) {
2974 $sql .=
" AND te.entity IS NOT NULL";
2976 $sql .=
" AND te.rowid IN (SELECT ug.fk_user FROM ".$this->db->prefix().
"usergroup_user as ug WHERE ug.entity IN (".
getEntity(
'usergroup').
"))";
2979 $sql .=
' AND te.entity IN ('.getEntity($this->element).
')';
2982 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged) && $this->element !=
'societe') {
2983 $tmparray = explode(
'@', $this->ismultientitymanaged);
2984 $sql .=
' AND parenttable.entity IN ('.getEntity($tmparray[1]).
')';
2986 if ($restrictiononfksoc == 1 && $socid && $this->element !=
'societe') {
2987 $sql .=
' AND te.fk_soc = '.((int) $socid);
2989 if ($restrictiononfksoc == 2 && $socid && $this->element !=
'societe') {
2990 $sql .=
' AND (te.fk_soc = '.((int) $socid).
' OR te.fk_soc IS NULL)';
2992 if ($restrictiononfksoc && $socid && $this->element ==
'societe') {
2993 $sql .=
' AND te.rowid = '.((int) $socid);
2997 $sql .=
" ORDER BY te.".$this->db->sanitize($fieldid).
" DESC";
2998 $sql .= $this->db->plimit(1);
3000 $result = $this->db->query($sql);
3002 $this->error = $this->db->lasterror();
3005 $row = $this->db->fetch_row($result);
3006 $this->ref_previous = ($row ? $row[0] :
null);
3008 $sql =
"SELECT te.".$this->db->sanitize($fieldid);
3009 $sql .=
" FROM ".(empty($nodbprefix) ? $this->db->prefix() :
'').$this->table_element.
" as te";
3010 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
3011 $tmparray = explode(
'@', $this->ismultientitymanaged);
3012 $sql .=
", ".$this->db->prefix().$this->db->sanitize($tmparray[1]).
" as ".($tmparray[1] ==
'societe' ?
's' :
'parenttable');
3013 } elseif ($restrictiononfksoc == 1 && $this->element !=
'societe' && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
3014 $sql .=
", ".$this->db->prefix().
"societe as s";
3015 } elseif ($restrictiononfksoc == 2 && $this->element !=
'societe' && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
3016 $sql .=
" LEFT JOIN ".$this->db->prefix().
"societe as s ON te.fk_soc = s.rowid";
3018 if ($restrictiononfksoc && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
3019 $sql .=
" LEFT JOIN ".$this->db->prefix().
"societe_commerciaux as sc ON ".$aliastablesociete.
".rowid = sc.fk_soc";
3021 if ($fieldid ==
'rowid') {
3022 $sql .=
" WHERE te.".$this->db->sanitize($fieldid).
" > ".((int) $this->
id);
3023 } elseif ($fieldid ==
'label') {
3025 $sql .=
" WHERE te.".$this->db->sanitize($fieldid).
" > '".$this->db->escape((
string) $this->label).
"'";
3027 $sql .=
" WHERE te.".$this->db->sanitize($fieldid).
" > '".$this->db->escape((
string) $this->
ref).
"'";
3029 if ($restrictiononfksoc == 1 && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
3030 $sql .=
" AND (sc.fk_user = ".((int) $user->id);
3032 $userschilds = $user->getAllChildIds();
3033 $sql .=
" OR sc.fk_user IN (".$this->db->sanitize(implode(
',', $userschilds)).
")";
3037 if ($restrictiononfksoc == 2 && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
3038 $sql .=
" AND (sc.fk_user = ".((int) $user->id).
' OR te.fk_soc IS NULL)';
3041 $filtermin = $filter;
3046 if ($errormessage) {
3047 if (!preg_match(
'/^\s*AND/i', $filtermin)) {
3057 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
3058 $tmparray = explode(
'@', $this->ismultientitymanaged);
3059 $sql .=
" AND te.".$this->db->sanitize($tmparray[0]).
" = ".($tmparray[1] ==
"societe" ?
"s" :
"parenttable").
".rowid";
3060 } elseif ($restrictiononfksoc == 1 && $this->element !=
'societe' && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
3061 $sql .=
' AND te.fk_soc = s.rowid';
3063 if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
3064 if ($this->element ==
'user' &&
getDolGlobalInt(
'MULTICOMPANY_TRANSVERSE_MODE')) {
3065 if (!empty($user->admin) && empty($user->entity) &&
$conf->entity == 1) {
3066 $sql .=
" AND te.entity IS NOT NULL";
3068 $sql .=
" AND te.rowid IN (SELECT ug.fk_user FROM ".$this->db->prefix().
"usergroup_user as ug WHERE ug.entity IN (".
getEntity(
'usergroup').
"))";
3071 $sql .=
' AND te.entity IN ('.getEntity($this->element).
')';
3074 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged) && $this->element !=
'societe') {
3075 $tmparray = explode(
'@', $this->ismultientitymanaged);
3076 $sql .=
' AND parenttable.entity IN ('.getEntity($tmparray[1]).
')';
3078 if ($restrictiononfksoc == 1 && $socid && $this->element !=
'societe') {
3079 $sql .=
' AND te.fk_soc = '.((int) $socid);
3081 if ($restrictiononfksoc == 2 && $socid && $this->element !=
'societe') {
3082 $sql .=
' AND (te.fk_soc = '.((int) $socid).
' OR te.fk_soc IS NULL)';
3084 if ($restrictiononfksoc && $socid && $this->element ==
'societe') {
3085 $sql .=
' AND te.rowid = '.((int) $socid);
3090 $sql .=
" ORDER BY te.".$this->db->sanitize($fieldid).
" ASC";
3091 $sql .= $this->db->plimit(1);
3093 $result = $this->db->query($sql);
3095 $this->error = $this->db->lasterror();
3098 $row = $this->db->fetch_row($result);
3099 $this->ref_next = ($row ? $row[0] :
null);
3114 $contactAlreadySelected = array();
3119 if ($source ==
'thirdparty') {
3120 $contactAlreadySelected[$i] = $tab[$i][
'socid'];
3122 $contactAlreadySelected[$i] = $tab[$i][
'id'];
3126 return $contactAlreadySelected;
3142 if (!$this->table_element) {
3143 dol_syslog(get_class($this).
"::setProject was called on object with property table_element not defined", LOG_ERR);
3147 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
3148 if ($this->table_element ==
'actioncomm') {
3150 $sql .=
" SET fk_project = ".((int) $projectid);
3152 $sql .=
" SET fk_project = NULL";
3154 $sql .=
' WHERE id = '.((int) $this->
id);
3156 } elseif (!empty($this->fields[
'fk_project'])) {
3158 $sql .=
" SET fk_project = ".((int) $projectid);
3160 $sql .=
" SET fk_project = NULL";
3162 $sql .=
' WHERE rowid = '.((int) $this->
id);
3165 $sql .=
' SET fk_projet = '.((int) $projectid);
3167 $sql .=
' SET fk_projet = NULL';
3169 $sql .=
" WHERE rowid = ".((int) $this->
id);
3174 dol_syslog(get_class($this).
"::setProject", LOG_DEBUG);
3175 if ($this->db->query($sql)) {
3176 $this->fk_project = ((int) $projectid);
3178 dol_print_error($this->db);
3183 if (!$error && !$notrigger) {
3185 $result = $this->call_trigger(strtoupper($this->element) .
'_MODIFY', $user);
3194 $this->db->rollback();
3197 $this->db->commit();
3216 dol_syslog(get_class($this).
'::setPaymentMethods('.$id.
')');
3218 if ($this->
status >= 0 || $this->element ==
'societe') {
3222 $fieldname =
'fk_mode_reglement';
3223 $triggerName = (empty($this->TRIGGER_PREFIX) ? strtoupper(get_class($this)) : $this->TRIGGER_PREFIX);
3224 if ($this->element ==
'societe') {
3225 $fieldname =
'mode_reglement';
3226 $triggerName =
'COMPANY';
3228 if (get_class($this) ==
'Facture') {
3229 $triggerName =
'BILL';
3231 if (get_class($this) ==
'Fournisseur') {
3232 $fieldname =
'mode_reglement_supplier';
3233 $triggerName =
'BILL_SUPPLIER';
3235 if (get_class($this) ==
'Tva') {
3236 $fieldname =
'fk_typepayment';
3237 $triggerName =
'VAT';
3239 if (get_class($this) ==
'Salary') {
3240 $fieldname =
'fk_typepayment';
3243 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
3244 $sql .=
" SET ".$this->db->sanitize($fieldname).
" = ".(($id > 0 || $id ==
'0') ? ((
int) $id) :
'NULL');
3245 $sql .=
' WHERE rowid = '.((int) $this->
id);
3247 if ($this->db->query($sql)) {
3248 $this->mode_reglement_id = $id;
3250 if (get_class($this) ==
'Fournisseur') {
3251 $this->mode_reglement_supplier_id = $id;
3255 if (!$error && !$notrigger) {
3257 $result = $this->call_trigger($triggerName.
'_MODIFY', $user);
3265 dol_syslog(get_class($this).
'::setPaymentMethods Error '.$this->db->error());
3266 $this->error = $this->db->error();
3270 dol_syslog(get_class($this).
'::setPaymentMethods, status of the object is incompatible');
3271 $this->error =
'Status of the object is incompatible '.$this->status;
3284 dol_syslog(get_class($this).
'::setMulticurrencyCode('.$code.
')');
3285 if ($this->
status >= 0 || $this->element ==
'societe') {
3286 $sql =
'UPDATE '.$this->db->prefix().$this->table_element;
3287 $sql .=
" SET multicurrency_code = '".$this->db->escape($code).
"'";
3288 $sql .=
' WHERE rowid='.((int) $this->
id);
3290 if ($this->db->query($sql)) {
3291 $this->multicurrency_code = $code;
3295 $this->setMulticurrencyRate($rate, 2);
3300 dol_syslog(get_class($this).
'::setMulticurrencyCode Error '.$sql.
' - '.$this->db->error());
3301 $this->error = $this->db->error();
3305 dol_syslog(get_class($this).
'::setMulticurrencyCode, status of the object is incompatible');
3306 $this->error =
'Status of the object is incompatible '.$this->status;
3318 public function setMulticurrencyRate($rate, $mode = 1)
3320 dol_syslog(get_class($this).
'::setMulticurrencyRate('.$rate.
', '.$mode.
')');
3321 if ($this->
status >= 0 || $this->element ==
'societe') {
3322 $sql =
'UPDATE '.$this->db->prefix().$this->table_element;
3323 $sql .=
" SET multicurrency_tx = ".((float) $rate);
3324 $sql .=
' WHERE rowid='.((int) $this->
id);
3326 if ($this->db->query($sql)) {
3327 $this->multicurrency_tx = $rate;
3330 if (!empty($this->lines)) {
3331 foreach ($this->lines as &$line) {
3334 if (!empty($line->fk_remise_except)) {
3340 $line->subprice = 0;
3345 $line->multicurrency_subprice = 0;
3348 switch ($this->element) {
3350 if ($this instanceof
Propal) {
3352 '@phan-var-force PropaleLigne $line';
3357 $line->remise_percent,
3359 $line->localtax1_tx,
3360 $line->localtax2_tx,
3361 ($line->description ? $line->description : $line->desc),
3364 $line->special_code,
3365 $line->fk_parent_line,
3366 $line->skip_update_total,
3367 $line->fk_fournprice,
3370 $line->product_type,
3373 $line->array_options,
3375 $line->multicurrency_subprice
3382 '@phan-var-force OrderLine $line';
3385 ($line->description ? $line->description : $line->desc),
3388 $line->remise_percent,
3390 $line->localtax1_tx,
3391 $line->localtax2_tx,
3396 $line->product_type,
3397 $line->fk_parent_line,
3398 $line->skip_update_total,
3399 $line->fk_fournprice,
3402 $line->special_code,
3403 $line->array_options,
3405 $line->multicurrency_subprice
3410 if ($this instanceof
Facture) {
3412 '@phan-var-force FactureLigne $line';
3415 ($line->description ? $line->description : $line->desc),
3418 $line->remise_percent,
3422 $line->localtax1_tx,
3423 $line->localtax2_tx,
3426 $line->product_type,
3427 $line->fk_parent_line,
3428 $line->skip_update_total,
3429 $line->fk_fournprice,
3432 $line->special_code,
3433 $line->array_options,
3434 $line->situation_percent,
3436 $line->multicurrency_subprice
3443 '@phan-var-force FactureLigneRec $line';
3446 ($line->description ? $line->description : $line->desc),
3450 $line->localtax1_tx,
3451 $line->localtax2_tx,
3453 $line->remise_percent,
3458 $line->product_type,
3460 $line->special_code,
3463 $line->multicurrency_subprice,
3467 $line->fk_fournprice,
3469 $line->fk_parent_line
3473 case 'supplier_proposal':
3476 '@phan-var-force SupplierProposalLine $line';
3481 $line->remise_percent,
3483 $line->localtax1_tx,
3484 $line->localtax2_tx,
3485 ($line->description ? $line->description : $line->desc),
3488 $line->special_code,
3489 $line->fk_parent_line,
3490 $line->skip_update_total,
3491 $line->fk_fournprice,
3494 $line->product_type,
3495 $line->array_options,
3497 (int) $line->fk_unit,
3498 $line->multicurrency_subprice
3502 case 'order_supplier':
3504 '@phan-var-force CommandeFournisseur $this';
3505 '@phan-var-force CommandeFournisseurLigne $line';
3508 ($line->description ? $line->description : $line->desc),
3511 $line->remise_percent,
3513 $line->localtax1_tx,
3514 $line->localtax2_tx,
3517 $line->product_type,
3521 $line->array_options,
3523 $line->multicurrency_subprice,
3527 case 'invoice_supplier':
3529 '@phan-var-force FactureFournisseur $this';
3530 '@phan-var-force SupplierInvoiceLIne $line';
3533 ($line->description ? $line->description : $line->desc),
3536 $line->localtax1_tx,
3537 $line->localtax2_tx,
3542 $line->product_type,
3543 $line->remise_percent,
3547 $line->array_options,
3549 $line->multicurrency_subprice,
3554 dol_syslog(get_class($this).
'::setMulticurrencyRate no updateline defined', LOG_DEBUG);
3562 dol_syslog(get_class($this).
'::setMulticurrencyRate Error '.$sql.
' - '.$this->db->error());
3563 $this->error = $this->db->error();
3567 dol_syslog(get_class($this).
'::setMulticurrencyRate, status of the object is incompatible');
3568 $this->error =
'Status of the object is incompatible '.$this->status;
3583 if ($this->
status >= 0 || $this->element ==
'societe') {
3585 $fieldname =
'fk_cond_reglement';
3586 if ($this->element ==
'societe') {
3587 $fieldname =
'cond_reglement';
3589 if (get_class($this) ==
'Fournisseur') {
3590 $fieldname =
'cond_reglement_supplier';
3593 if (empty($deposit_percent) || $deposit_percent < 0) {
3594 $deposit_percent = (float)
getDictionaryValue(
'c_payment_term',
'deposit_percent', $id);
3597 if ($deposit_percent > 100) {
3598 $deposit_percent = 100;
3601 $sql =
'UPDATE '.$this->db->prefix().$this->table_element;
3602 $sql .=
" SET ".$this->db->sanitize($fieldname).
" = ".(($id > 0 || $id ==
'0') ? ((
int) $id) :
'NULL');
3603 if (in_array($this->table_element, array(
'propal',
'commande',
'supplier_proposal',
'commande_fournisseur',
'societe'))) {
3604 $sql .=
" , deposit_percent = " . (empty($deposit_percent) ?
'NULL' :
"'".$this->db->escape((
string) $deposit_percent).
"'");
3606 $sql .=
' WHERE rowid = '.((int) $this->
id);
3608 if ($this->db->query($sql)) {
3609 $this->cond_reglement_id = $id;
3611 if (get_class($this) ==
'Fournisseur') {
3612 $this->cond_reglement_supplier_id = $id;
3614 $this->deposit_percent = $deposit_percent;
3617 dol_syslog(get_class($this).
'::setPaymentTerms Error '.$sql.
' - '.$this->db->error());
3618 $this->error = $this->db->error();
3622 dol_syslog(get_class($this).
'::setPaymentTerms, status of the object is incompatible');
3623 $this->error =
'Status of the object is incompatible '.$this->status;
3636 dol_syslog(get_class($this).
'::setTransportMode('.$id.
')');
3637 if ($this->
status >= 0 || $this->element ==
'societe') {
3638 $fieldname =
'fk_transport_mode';
3639 if ($this->element ==
'societe') {
3640 $fieldname =
'transport_mode';
3642 if (get_class($this) ==
'Fournisseur') {
3643 $fieldname =
'transport_mode_supplier';
3646 $sql =
'UPDATE '.$this->db->prefix().$this->table_element;
3647 $sql .=
" SET ".$this->db->sanitize($fieldname).
" = ".(($id > 0 || $id ==
'0') ? ((
int) $id) :
'NULL');
3648 $sql .=
' WHERE rowid='.((int) $this->
id);
3650 if ($this->db->query($sql)) {
3651 $this->transport_mode_id = $id;
3653 if (get_class($this) ==
'Fournisseur') {
3654 $this->transport_mode_supplier_id = $id;
3658 dol_syslog(get_class($this).
'::setTransportMode Error '.$sql.
' - '.$this->db->error());
3659 $this->error = $this->db->error();
3663 dol_syslog(get_class($this).
'::setTransportMode, status of the object is incompatible');
3664 $this->error =
'Status of the object is incompatible '.$this->status;
3678 $fieldname =
'fk_delivery_address';
3679 if ($this->element ==
'delivery' || $this->element ==
'shipping') {
3680 $fieldname =
'fk_address';
3683 $sql =
"UPDATE ".$this->db->prefix().$this->table_element.
" SET ".$this->db->sanitize($fieldname).
" = ".((int) $id);
3684 $sql .=
" WHERE rowid = ".((int) $this->
id).
" AND fk_statut = 0";
3686 if ($this->db->query($sql)) {
3687 $this->fk_delivery_address =
$id;
3690 $this->error = $this->db->error();
3691 dol_syslog(get_class($this).
'::setDeliveryAddress Error '.$this->error);
3709 if (empty($userused)) {
3715 if (!$this->table_element) {
3716 dol_syslog(get_class($this).
"::setShippingMethod was called on object with property table_element not defined", LOG_ERR);
3722 if ($shipping_method_id < 0) {
3723 $shipping_method_id =
'NULL';
3725 dol_syslog(get_class($this).
'::setShippingMethod('.$shipping_method_id.
')');
3727 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
3728 $sql .=
" SET fk_shipping_method = ".((int) $shipping_method_id);
3729 $sql .=
" WHERE rowid=".((int) $this->
id);
3730 $resql = $this->db->query($sql);
3732 dol_syslog(get_class($this).
'::setShippingMethod Error ', LOG_DEBUG);
3733 $this->error = $this->db->lasterror();
3738 $this->context = array(
'shippingmethodupdate' => 1);
3739 $triggerPrefix = (empty($this->TRIGGER_PREFIX) ? strtoupper(get_class($this)) : $this->TRIGGER_PREFIX);
3740 $result = $this->call_trigger($triggerPrefix.
'_MODIFY', $userused);
3748 $this->db->rollback();
3751 $this->shipping_method_id = ($shipping_method_id ==
'NULL') ?
null : $shipping_method_id;
3752 $this->db->commit();
3766 if (!$this->table_element) {
3767 dol_syslog(get_class($this).
"::setWarehouse was called on object with property table_element not defined", LOG_ERR);
3770 if ($warehouse_id < 0) {
3771 $warehouse_id =
'NULL';
3773 dol_syslog(get_class($this).
'::setWarehouse('.$warehouse_id.
')');
3775 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
3776 $sql .=
" SET fk_warehouse = ".((int) $warehouse_id);
3777 $sql .=
" WHERE rowid=".((int) $this->
id);
3779 if ($this->db->query($sql)) {
3780 $this->warehouse_id = ($warehouse_id ==
'NULL') ?
null : $warehouse_id;
3783 dol_syslog(get_class($this).
'::setWarehouse Error ', LOG_DEBUG);
3784 $this->error = $this->db->error();
3799 if (!$this->table_element) {
3800 dol_syslog(get_class($this).
"::setDocModel was called on object with property table_element not defined", LOG_ERR);
3804 $newmodelpdf =
dol_trunc($modelpdf, 255);
3806 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
3807 $sql .=
" SET model_pdf = '".$this->db->escape($newmodelpdf).
"'";
3808 $sql .=
" WHERE rowid = ".((int) $this->
id);
3810 dol_syslog(get_class($this).
"::setDocModel", LOG_DEBUG);
3811 $resql = $this->db->query($sql);
3813 $this->model_pdf = $modelpdf;
3816 dol_print_error($this->db);
3834 if (empty($userused)) {
3840 if (!$this->table_element) {
3841 dol_syslog(get_class($this).
"::setBankAccount was called on object with property table_element not defined", LOG_ERR);
3846 if ($fk_account < 0) {
3847 $fk_account =
'NULL';
3849 dol_syslog(get_class($this).
'::setBankAccount('.$fk_account.
')');
3851 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
3852 $sql .=
" SET fk_account = ".((int) $fk_account);
3853 $sql .=
" WHERE rowid=".((int) $this->
id);
3855 $resql = $this->db->query($sql);
3857 dol_syslog(get_class($this).
'::setBankAccount Error '.$sql.
' - '.$this->db->error());
3858 $this->error = $this->db->lasterror();
3863 $this->context[
'bankaccountupdate'] = 1;
3865 $triggerName = (empty($this->TRIGGER_PREFIX) ? strtoupper(get_class($this)) : $this->TRIGGER_PREFIX);
3866 $result = $this->call_trigger($triggerName .
'_MODIFY', $userused);
3874 $this->db->rollback();
3877 $this->fk_account = ($fk_account ==
'NULL') ?
null : $fk_account;
3878 $this->db->commit();
3896 public function line_order($renum =
false, $rowidorder =
'ASC', $fk_parent_line =
true)
3899 if (!$this->table_element_line) {
3900 dol_syslog(get_class($this).
"::line_order was called on object with property table_element_line not defined", LOG_ERR);
3903 if (!$this->fk_element) {
3904 dol_syslog(get_class($this).
"::line_order was called on object with property fk_element not defined", LOG_ERR);
3908 $fieldposition =
'rang';
3909 if (in_array($this->table_element_line, array(
'bom_bomline',
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3910 $fieldposition =
'position';
3915 $sql =
"SELECT count(rowid) FROM ".$this->db->prefix().$this->db->sanitize($this->table_element_line);
3916 $sql .=
" WHERE ".$this->db->sanitize($this->fk_element).
" = ".((int) $this->
id);
3918 $sql .=
" AND " . $this->db->sanitize($fieldposition) .
" = 0";
3921 $sql .=
" AND " . $this->db->sanitize($fieldposition) .
" <> 0";
3924 dol_syslog(get_class($this).
"::line_order", LOG_DEBUG);
3925 $resql = $this->db->query($sql);
3927 $row = $this->db->fetch_row($resql);
3930 dol_print_error($this->db);
3937 $sql =
"SELECT rowid FROM ".$this->db->prefix().$this->db->sanitize($this->table_element_line);
3938 $sql .=
" WHERE ".$this->db->sanitize($this->fk_element).
" = ".((int) $this->
id);
3939 if ($fk_parent_line) {
3940 $sql .=
' AND fk_parent_line IS NULL';
3942 $sql .=
" ORDER BY " . $this->db->sanitize($fieldposition) .
" ASC, rowid " . $this->db->sanitize($rowidorder);
3944 dol_syslog(get_class($this).
"::line_order search all parent lines", LOG_DEBUG);
3945 $resql = $this->db->query($sql);
3948 $num = $this->db->num_rows($resql);
3951 $row = $this->db->fetch_row($resql);
3953 if ($fk_parent_line) {
3956 if (!empty($children)) {
3957 foreach ($children as $child) {
3958 array_push($rows, $child);
3965 if (!empty($rows)) {
3966 foreach ($rows as $key => $row) {
3971 dol_print_error($this->db);
3986 $fieldposition =
'rang';
3987 if (in_array($this->table_element_line, array(
'bom_bomline',
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3988 $fieldposition =
'position';
3993 $sql =
"SELECT rowid FROM ".$this->db->prefix().$this->db->sanitize($this->table_element_line);
3994 $sql .=
" WHERE ".$this->db->sanitize($this->fk_element).
" = ".((int) $this->
id);
3995 $sql .=
' AND fk_parent_line = '.((int) $id);
3996 $sql .=
" ORDER BY " . $this->db->sanitize($fieldposition) .
" ASC";
3998 dol_syslog(get_class($this).
"::getChildrenOfLine search children lines for line ".$id, LOG_DEBUG);
4000 $resql = $this->db->query($sql);
4001 if (!$resql || $this->db->num_rows($resql) <= 0) {
4005 while ($row = $this->db->fetch_row($resql)) {
4007 if (!empty($includealltree) && $includealltree <= 1000) {
4008 $rows = array_merge($rows, $this->
getChildrenOfLine($row[0], $includealltree + 1));
4022 public function line_up($rowid, $fk_parent_line =
true)
4025 $this->
line_order(
false,
'ASC', $fk_parent_line);
4045 $this->
line_order(
false,
'ASC', $fk_parent_line);
4066 global $hookmanager;
4067 $fieldposition =
'rang';
4068 if (in_array($this->table_element_line, array(
'bom_bomline',
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
4069 $fieldposition =
'position';
4072 $sql =
"UPDATE ".$this->db->prefix().$this->table_element_line.
" SET ".$this->db->sanitize($fieldposition).
" = ".((int) $rang);
4073 $sql .=
' WHERE rowid = '.((int) $rowid);
4074 if ($this->
id > 0 && !empty($this->fk_element)) {
4076 $sql .=
" AND ".$this->db->sanitize($this->fk_element).
" = ".((int) $this->
id);
4079 dol_syslog(get_class($this).
"::updateRangOfLine", LOG_DEBUG);
4080 if (!$this->db->query($sql)) {
4081 dol_print_error($this->db);
4085 $parameters = array(
'rowid' => $rowid,
'rang' => $rang,
'fieldposition' => $fieldposition);
4087 $reshook = $hookmanager->executeHooks(
'afterRankOfLineUpdate', $parameters, $this, $action);
4101 $num = count($rows);
4102 for ($i = 0; $i < $num; $i++) {
4120 $fieldposition =
'rang';
4121 if (in_array($this->table_element_line, array(
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
4122 $fieldposition =
'position';
4125 $sql =
"UPDATE ".$this->db->prefix().$this->db->sanitize($this->table_element_line).
" SET ".$this->db->sanitize($fieldposition).
" = ".((int) $rang);
4126 $sql .=
" WHERE ".$this->db->sanitize($this->fk_element).
" = ".((int) $this->
id);
4127 $sql .=
" AND " . $this->db->sanitize($fieldposition) .
" = " . ((int) ($rang - 1));
4128 if (!$this->db->query($sql)) {
4129 $this->error = $this->db->lasterror();
4133 $sql =
"UPDATE ".$this->db->prefix().$this->table_element_line.
" SET ".$this->db->sanitize($fieldposition).
" = ".((int) ($rang - 1));
4134 $sql .=
' WHERE rowid = '.((int) $rowid);
4135 if (!$this->db->query($sql)) {
4136 $this->error = $this->db->lasterror();
4153 if ($rang >= $max) {
4157 $fieldposition =
'rang';
4158 if (in_array($this->table_element_line, array(
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
4159 $fieldposition =
'position';
4162 $sql =
"UPDATE ".$this->db->prefix().$this->db->sanitize($this->table_element_line).
" SET ".$this->db->sanitize($fieldposition).
" = ".((int) $rang);
4163 $sql .=
" WHERE ".$this->db->sanitize($this->fk_element).
" = ".((int) $this->
id);
4164 $sql .=
" AND " . $this->db->sanitize($fieldposition) .
" = " . ((int) ($rang + 1));
4165 if (!$this->db->query($sql)) {
4166 $this->error = $this->db->lasterror();
4170 $sql =
"UPDATE ".$this->db->prefix().$this->table_element_line.
" SET ".$this->db->sanitize($fieldposition).
" = ".((int) ($rang + 1));
4171 $sql .=
' WHERE rowid = '.((int) $rowid);
4172 if (!$this->db->query($sql)) {
4173 $this->error = $this->db->lasterror();
4188 $fieldposition =
'rang';
4189 if (in_array($this->table_element_line, array(
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
4190 $fieldposition =
'position';
4193 $sql =
"SELECT " . $this->db->sanitize($fieldposition) .
" FROM ".$this->db->prefix().$this->db->sanitize($this->table_element_line);
4194 $sql .=
" WHERE rowid = ".((int) $rowid);
4196 dol_syslog(get_class($this).
"::getRangOfLine", LOG_DEBUG);
4197 $resql = $this->db->query($sql);
4202 $row = $this->db->fetch_row($resql);
4214 $fieldposition =
'rang';
4215 if (in_array($this->table_element_line, array(
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
4216 $fieldposition =
'position';
4219 $sql =
"SELECT rowid FROM ".$this->db->prefix().$this->db->sanitize($this->table_element_line);
4220 $sql .=
" WHERE ".$this->db->sanitize($this->fk_element).
" = ".((int) $this->
id);
4221 $sql .=
" AND " . $this->db->sanitize($fieldposition) .
" = ".((int) $rang);
4222 $resql = $this->db->query($sql);
4227 $row = $this->db->fetch_row($resql);
4242 if (empty($packaging) || !is_numeric($packaging) || (
float) $packaging <= 0) {
4245 $sign = ((float) $qty < 0 ? -1 : 1);
4246 $absqty = abs((
float) $qty);
4247 if ($absqty < (
float) $packaging) {
4248 return $sign * (float) $packaging;
4250 if ((
float)
price2num(fmod($absqty, (
float) $packaging),
'MS')) {
4251 $coeff = intval($absqty / (
float) $packaging) + 1;
4252 return $sign * (float)
price2num((
float) $packaging * $coeff,
'MS');
4267 $positionfield =
'rang';
4268 if (in_array($this->table_element, array(
'bom_bom',
'product_attribute'))) {
4269 $positionfield =
'position';
4272 $sql =
"SELECT max(".$this->db->sanitize($positionfield).
") FROM ".$this->db->prefix().$this->db->sanitize($this->table_element_line);
4273 $sql .=
" WHERE ".$this->db->sanitize($this->fk_element).
" = ".((int) $this->
id);
4276 if ($fk_parent_line) {
4277 $sql .=
" AND fk_parent_line = ".((int) $fk_parent_line);
4280 dol_syslog(get_class($this).
"::line_max", LOG_DEBUG);
4281 $resql = $this->db->query($sql);
4283 $row = $this->db->fetch_row($resql);
4285 if ($fk_parent_line) {
4286 if (!empty($row[0])) {
4309 if (!$this->table_element) {
4310 dol_syslog(get_class($this).
"::update_ref_ext was called on object with property table_element not defined", LOG_ERR);
4314 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
4315 $sql .=
" SET ref_ext = '".$this->db->escape($ref_ext).
"'";
4317 $sql .=
" WHERE ".(isset($this->table_rowid) ? $this->table_rowid :
'rowid').
" = ".((
int) $this->id);
4319 dol_syslog(get_class($this).
"::update_ref_ext", LOG_DEBUG);
4320 if ($this->db->query($sql)) {
4321 $this->ref_ext = $ref_ext;
4324 $this->error = $this->db->error();
4343 if (!$this->table_element) {
4344 $this->error =
'update_note was called on object with property table_element not defined';
4345 dol_syslog(get_class($this).
"::update_note was called on object with property table_element not defined", LOG_ERR);
4348 if (!in_array($suffix, array(
'',
'_public',
'_private'))) {
4349 $this->error =
'update_note Parameter suffix must be empty, \'_private\' or \'_public\'';
4350 dol_syslog(get_class($this).
"::update_note Parameter suffix must be empty, '_private' or '_public'", LOG_ERR);
4354 $newsuffix = $suffix;
4357 if ($this->table_element ==
'product' && $newsuffix ==
'_private') {
4360 if (in_array($this->table_element, array(
'actioncomm',
'adherent',
'advtargetemailing',
'cronjob',
'establishment'))) {
4361 $fieldusermod =
"fk_user_mod";
4362 } elseif ($this->table_element ==
'ecm_files') {
4363 $fieldusermod =
"fk_user_m";
4365 $fieldusermod =
"fk_user_modif";
4367 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
4368 $sql .=
" SET note".$this->db->sanitize($newsuffix).
" = ".(!empty($note) ? (
"'".$this->db->escape($note).
"'") :
"NULL");
4369 $sql .=
", ".$this->db->sanitize($fieldusermod).
" = ".((int) $user->id);
4370 $sql .=
" WHERE rowid = ".((int) $this->
id);
4372 dol_syslog(get_class($this).
"::update_note", LOG_DEBUG);
4373 if ($this->db->query($sql)) {
4374 if ($suffix ==
'_public') {
4375 $this->note_public = $note;
4376 } elseif ($suffix ==
'_private') {
4377 $this->note_private = $note;
4379 $this->note = $note;
4380 $this->note_private = $note;
4382 if (empty($notrigger)) {
4384 switch ($this->element) {
4386 $triggerName =
'COMPANY_MODIFY';
4389 $triggerName =
'BILL_MODIFY';
4391 case 'invoice_supplier':
4392 $triggerName =
'BILL_SUPPLIER_MODIFY';
4395 $triggerName =
'BILLREC_MODIFIY';
4397 case 'expensereport':
4398 $triggerName =
'EXPENSE_REPORT_MODIFY';
4401 $triggerName = (!empty($this->TRIGGER_PREFIX) ? $this->TRIGGER_PREFIX : strtoupper($this->element)) .
'_MODIFY';
4403 $ret = $this->call_trigger($triggerName, $user);
4410 $this->error = $this->db->lasterror();
4441 public function update_price($exclspec = 0, $roundingadjust =
'auto', $nodatabaseupdate = 0, $seller =
null)
4444 global
$conf, $hookmanager, $action;
4446 $parameters = array(
'exclspec' => $exclspec,
'roundingadjust' => $roundingadjust,
'nodatabaseupdate' => $nodatabaseupdate,
'seller' => $seller);
4447 $reshook = $hookmanager->executeHooks(
'updateTotalPrice', $parameters, $this, $action);
4450 } elseif ($reshook < 0) {
4455 $isElementForSupplier =
false;
4456 $roundTotalConstName =
'MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND';
4458 if ($this->element ==
'propal') {
4459 $MODULE =
"MODULE_DISALLOW_UPDATE_PRICE_PROPOSAL";
4460 } elseif ($this->element ==
'commande' || $this->element ==
'order') {
4461 $MODULE =
"MODULE_DISALLOW_UPDATE_PRICE_ORDER";
4462 } elseif ($this->element ==
'facture' || $this->element ==
'invoice') {
4463 $MODULE =
"MODULE_DISALLOW_UPDATE_PRICE_INVOICE";
4464 } elseif ($this->element ==
'facture_fourn' || $this->element ==
'supplier_invoice' || $this->element ==
'invoice_supplier' || $this->element ==
'invoice_supplier_rec') {
4465 $isElementForSupplier =
true;
4466 $MODULE =
"MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_INVOICE";
4467 } elseif ($this->element ==
'order_supplier' || $this->element ==
'supplier_order') {
4468 $isElementForSupplier =
true;
4469 $MODULE =
"MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_ORDER";
4470 } elseif ($this->element ==
'supplier_proposal') {
4471 $isElementForSupplier =
true;
4472 $MODULE =
"MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_PROPOSAL";
4474 if ($isElementForSupplier) {
4475 $roundTotalConstName =
'MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND_SUPPLIER';
4478 if (!empty($MODULE)) {
4481 foreach ($modsactivated as $mod) {
4489 include_once DOL_DOCUMENT_ROOT.
'/core/lib/price.lib.php';
4491 $forcedroundingmode = $roundingadjust;
4492 if ($forcedroundingmode ==
'auto' && isset(
$conf->global->{$roundTotalConstName})) {
4494 } elseif ($forcedroundingmode ==
'auto') {
4495 $forcedroundingmode =
'0';
4500 $multicurrency_tx = !empty($this->multicurrency_tx) ? $this->multicurrency_tx : 1;
4503 $fieldtva =
'total_tva';
4504 $fieldlocaltax1 =
'total_localtax1';
4505 $fieldlocaltax2 =
'total_localtax2';
4506 $fieldup =
'subprice';
4507 $base_price_type =
'HT';
4508 if ($this->element ==
'facture_fourn' || $this->element ==
'invoice_supplier') {
4512 if ($this->element ==
'invoice_supplier_rec') {
4515 if ($this->element ==
'expensereport') {
4519 $forcedroundingmode =
'0';
4520 $fieldup =
'value_unit';
4521 $base_price_type =
'TTC';
4524 $sql =
"SELECT rowid, qty, ".$this->db->sanitize($fieldup).
" as up, remise_percent,";
4525 $sql .=
" total_ht, ".$this->db->sanitize($fieldtva).
" as total_tva, total_ttc, ".$this->db->sanitize($fieldlocaltax1).
" as total_localtax1, ".$this->db->sanitize($fieldlocaltax2).
" as total_localtax2,";
4526 $sql .=
' tva_tx as vatrate, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type,';
4527 $sql .=
' info_bits, product_type,';
4528 if ($this->element ==
'expensereport') {
4529 $sql .=
' comments as description';
4531 $sql .=
' description';
4533 if ($this->table_element_line ==
'facturedet') {
4534 $sql .=
', situation_percent';
4536 $sql .=
', multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc';
4537 $sql .=
" FROM ".$this->db->prefix().$this->db->sanitize($this->table_element_line);
4538 $sql .=
" WHERE ".$this->db->sanitize($this->fk_element).
" = ".((int) $this->
id);
4540 $product_field =
'product_type';
4541 if ($this->table_element_line ==
'contratdet') {
4542 $product_field =
'';
4544 if ($product_field) {
4545 $sql .=
" AND ".$this->db->sanitize($product_field).
" <> 9";
4548 $sql .=
' ORDER by rowid';
4550 dol_syslog(get_class($this).
"::update_price", LOG_DEBUG);
4552 $resql = $this->db->query($sql);
4554 $this->total_ht = 0;
4555 $this->total_tva = 0;
4556 $this->total_localtax1 = 0;
4557 $this->total_localtax2 = 0;
4558 $this->total_ttc = 0;
4559 $total_ht_by_vats = array();
4560 $total_tva_by_vats = array();
4561 $total_ttc_by_vats = array();
4562 $this->multicurrency_total_ht = 0;
4563 $this->multicurrency_total_tva = 0;
4564 $this->multicurrency_total_ttc = 0;
4568 $num = $this->db->num_rows($resql);
4571 $obj = $this->db->fetch_object($resql);
4574 $parameters = array(
'fk_element' => $obj->rowid);
4575 $reshook = $hookmanager->executeHooks(
'changeRoundingMode', $parameters, $this, $action);
4577 if (empty($reshook) && $forcedroundingmode ==
'0') {
4579 $localtax_array = array($obj->localtax1_type, $obj->localtax1_tx, $obj->localtax2_type, $obj->localtax2_tx);
4580 $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, (isset($obj->multicurrency_subprice) ? $obj->multicurrency_subprice : 0), (isset($this->multicurrency_code) ? $this->multicurrency_code :
''));
4582 $diff_when_using_price_ht =
price2num((
float) $tmpcal[1] - $obj->total_tva,
'MT', 1);
4583 $diff_on_current_total =
price2num($obj->total_ttc - $obj->total_ht - $obj->total_tva - $obj->total_localtax1 - $obj->total_localtax2,
'MT', 1);
4587 if ($diff_on_current_total) {
4589 $sqlfix =
"UPDATE ".$this->db->prefix().$this->table_element_line;
4590 $sqlfix .=
" SET ".$this->db->sanitize($fieldtva).
" = ".
price2num((
float) $tmpcal[1]).
", total_ttc = ".
price2num((
float) $tmpcal[2]);
4591 $sqlfix .=
", multicurrency_total_tva = ".price2num((
float) $tmpcal[17]).
", multicurrency_total_ttc = ".
price2num((
float) $tmpcal[18]);
4592 $sqlfix .=
" WHERE rowid = ".((int) $obj->rowid);
4593 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);
4594 $resqlfix = $this->db->query($sqlfix);
4596 dol_print_error($this->db,
'Failed to update line');
4598 $obj->total_tva = $tmpcal[1];
4599 $obj->total_ttc = $tmpcal[2];
4600 $obj->multicurrency_total_tva = $tmpcal[17];
4601 $obj->multicurrency_total_ttc = $tmpcal[18];
4602 } elseif ($diff_when_using_price_ht) {
4606 if ((
float) $tmpcal[0] == (
float) $obj->total_ht) {
4609 if ($obj->description !=
'(DEPOSIT)' && !
getDolGlobalInt(
'MAIN_DISABLE_AUTOFIX_CORRUPTED_LINES_WHEN_TOTAL_DOES_NOT_MATCH_RECALCULATION_FROM_UP')) {
4613 $sqlfix =
"UPDATE ".$this->db->prefix().$this->table_element_line;
4614 $sqlfix .=
" SET ".$this->db->sanitize($fieldtva).
" = ".
price2num((
float) $tmpcal[1]).
", total_ttc = ".
price2num((
float) $tmpcal[2]);
4615 $sqlfix .=
", multicurrency_total_tva = ".price2num((
float) $tmpcal[17]).
", multicurrency_total_ttc = ".
price2num((
float) $tmpcal[18]);
4616 $sqlfix .=
" WHERE rowid = ".((int) $obj->rowid);
4618 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);
4620 $resqlfix = $this->db->query($sqlfix);
4622 dol_print_error($this->db,
'Failed to update line');
4624 $obj->total_tva = $tmpcal[1];
4625 $obj->total_ttc = $tmpcal[2];
4626 $obj->multicurrency_total_tva = $tmpcal[17];
4627 $obj->multicurrency_total_ttc = $tmpcal[18];
4633 $this->total_ht += $obj->total_ht;
4634 $this->total_tva += $obj->total_tva;
4635 $this->total_localtax1 += $obj->total_localtax1;
4636 $this->total_localtax2 += $obj->total_localtax2;
4637 $this->total_ttc += $obj->total_ttc;
4638 $this->multicurrency_total_ht += $obj->multicurrency_total_ht;
4639 $this->multicurrency_total_tva += $obj->multicurrency_total_tva;
4640 $this->multicurrency_total_ttc += $obj->multicurrency_total_ttc;
4642 if (!isset($total_ht_by_vats[$obj->vatrate])) {
4643 $total_ht_by_vats[$obj->vatrate] = 0;
4645 if (!isset($total_tva_by_vats[$obj->vatrate])) {
4646 $total_tva_by_vats[$obj->vatrate] = 0;
4648 if (!isset($total_ttc_by_vats[$obj->vatrate])) {
4649 $total_ttc_by_vats[$obj->vatrate] = 0;
4651 $total_ht_by_vats[$obj->vatrate] += $obj->total_ht;
4652 $total_tva_by_vats[$obj->vatrate] += $obj->total_tva;
4653 $total_ttc_by_vats[$obj->vatrate] += $obj->total_ttc;
4655 if ($forcedroundingmode ==
'1') {
4656 if ($base_price_type ==
'TTC') {
4657 $tmpvat =
price2num($total_ttc_by_vats[$obj->vatrate] * $obj->vatrate / (100 + $obj->vatrate),
'MT', 1);
4659 $tmpvat =
price2num($total_ht_by_vats[$obj->vatrate] * $obj->vatrate / 100,
'MT', 1);
4661 $diff =
price2num($total_tva_by_vats[$obj->vatrate] - (
float) $tmpvat,
'MT', 1);
4664 $maxdiff = (10 * pow(10, -1 *
getDolGlobalInt(
'MAIN_MAX_DECIMALS_TOT', 0)));
4665 if (abs((
float) $diff) > $maxdiff) {
4667 $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.';
4669 $this->error = $errmsg;
4674 if ($base_price_type ==
'TTC') {
4675 $sqlfix =
"UPDATE ".$this->db->prefix().$this->table_element_line.
" SET ".$this->db->sanitize($fieldtva).
" = ".
price2num($obj->total_tva - (
float) $diff).
", total_ht = ".
price2num($obj->total_ht + (
float) $diff).
" WHERE rowid = ".((int) $obj->rowid);
4676 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);
4678 $sqlfix =
"UPDATE ".$this->db->prefix().$this->table_element_line.
" SET ".$this->db->sanitize($fieldtva).
" = ".
price2num($obj->total_tva - (
float) $diff).
", total_ttc = ".
price2num($obj->total_ttc - (
float) $diff).
" WHERE rowid = ".((int) $obj->rowid);
4679 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);
4682 $resqlfix = $this->db->query($sqlfix);
4685 dol_print_error($this->db,
'Failed to update line');
4688 $this->total_tva = (float)
price2num($this->total_tva - (
float) $diff,
'', 1);
4689 $total_tva_by_vats[$obj->vatrate] = (float)
price2num($total_tva_by_vats[$obj->vatrate] - (
float) $diff,
'', 1);
4690 if ($base_price_type ==
'TTC') {
4691 $this->total_ht = (float)
price2num($this->total_ht + (
float) $diff,
'', 1);
4692 $total_ht_by_vats[$obj->vatrate] = (float)
price2num($total_ht_by_vats[$obj->vatrate] + (
float) $diff,
'', 1);
4694 $this->total_ttc = (float)
price2num($this->total_ttc - (
float) $diff,
'', 1);
4695 $total_ttc_by_vats[$obj->vatrate] = (float)
price2num($total_ttc_by_vats[$obj->vatrate] - (
float) $diff,
'', 1);
4705 $this->total_ttc += isset($this->revenuestamp) ? $this->revenuestamp : 0;
4707 $this->multicurrency_total_ttc += isset($this->revenuestamp) ? ($this->revenuestamp * $multicurrency_tx) : 0;
4710 if (!empty($this->situation_cycle_ref) && !empty($this->situation_counter) && $this->situation_counter > 1 && method_exists($this,
'get_prev_sits')) {
4711 '@phan-var-force Facture $this';
4712 include_once DOL_DOCUMENT_ROOT.
'/compta/facture/class/facture.class.php';
4715 $prev_sits = $this->get_prev_sits();
4717 foreach ($prev_sits as $sit) {
4718 $this->total_ht -= $sit->total_ht;
4719 $this->total_tva -= $sit->total_tva;
4720 $this->total_localtax1 -= $sit->total_localtax1;
4721 $this->total_localtax2 -= $sit->total_localtax2;
4722 $this->total_ttc -= $sit->total_ttc;
4723 $this->multicurrency_total_ht -= $sit->multicurrency_total_ht;
4724 $this->multicurrency_total_tva -= $sit->multicurrency_total_tva;
4725 $this->multicurrency_total_ttc -= $sit->multicurrency_total_ttc;
4732 $this->total_ht = (float)
price2num($this->total_ht);
4733 $this->total_tva = (float)
price2num($this->total_tva);
4734 $this->total_localtax1 = (float)
price2num($this->total_localtax1);
4735 $this->total_localtax2 = (float)
price2num($this->total_localtax2);
4736 $this->total_ttc = (float)
price2num($this->total_ttc);
4737 $this->multicurrency_total_ht = (float)
price2num($this->multicurrency_total_ht,
'CT', 0, (isset($this->multicurrency_code) ? $this->multicurrency_code :
''));
4738 $this->multicurrency_total_tva = (float)
price2num($this->multicurrency_total_tva,
'CT', 0, (isset($this->multicurrency_code) ? $this->multicurrency_code :
''));
4739 $this->multicurrency_total_ttc = (float)
price2num($this->multicurrency_total_ttc,
'CT', 0, (isset($this->multicurrency_code) ? $this->multicurrency_code :
''));
4741 $this->db->free($resql);
4744 $fieldht =
'total_ht';
4746 $fieldlocaltax1 =
'localtax1';
4747 $fieldlocaltax2 =
'localtax2';
4748 $fieldttc =
'total_ttc';
4750 if (in_array($this->element, array(
'propal',
'commande',
'facture',
'facturerec',
'supplier_proposal',
'order_supplier',
'facture_fourn',
'invoice_supplier',
'invoice_supplier_rec',
'expensereport'))) {
4751 $fieldtva =
'total_tva';
4754 if (!$error && empty($nodatabaseupdate)) {
4755 $sql =
"UPDATE ".$this->db->prefix().$this->table_element.
' SET';
4756 $sql .=
" ".$this->db->sanitize($fieldht).
" = ".((float)
price2num($this->total_ht,
'MT', 1)).
",";
4757 $sql .=
" ".$this->db->sanitize($fieldtva).
" = ".((float)
price2num($this->total_tva,
'MT', 1)).
",";
4758 $sql .=
" ".$this->db->sanitize($fieldlocaltax1).
" = ".((float)
price2num($this->total_localtax1,
'MT', 1)).
",";
4759 $sql .=
" ".$this->db->sanitize($fieldlocaltax2).
" = ".((float)
price2num($this->total_localtax2,
'MT', 1)).
",";
4760 $sql .=
" ".$this->db->sanitize($fieldttc).
" = ".((float)
price2num($this->total_ttc,
'MT', 1));
4761 $sql .=
", multicurrency_total_ht = ".((float)
price2num($this->multicurrency_total_ht,
'CT', 1, (isset($this->multicurrency_code) ? $this->multicurrency_code :
'')));
4762 $sql .=
", multicurrency_total_tva = ".((float)
price2num($this->multicurrency_total_tva,
'CT', 1, (isset($this->multicurrency_code) ? $this->multicurrency_code :
'')));
4763 $sql .=
", multicurrency_total_ttc = ".((float)
price2num($this->multicurrency_total_ttc,
'CT', 1, (isset($this->multicurrency_code) ? $this->multicurrency_code :
'')));
4764 $sql .=
" WHERE rowid = ".((int) $this->
id);
4766 dol_syslog(get_class($this).
"::update_price", LOG_DEBUG);
4767 $resql = $this->db->query($sql);
4771 $this->error = $this->db->lasterror();
4772 $this->errors[] = $this->db->lasterror();
4777 $this->db->commit();
4780 $this->db->rollback();
4784 dol_print_error($this->db,
'Bad request in update_price');
4800 public function add_object_linked($origin =
null, $origin_id =
null, $f_user =
null, $notrigger = 0)
4803 global $user, $hookmanager, $action;
4806 if (empty($this->origin_type) && !empty($this->origin)) {
4807 $this->origin_type = $this->origin;
4809 $origin = (!empty($origin) ? $origin : $this->origin_type);
4810 $origin_id = (!empty($origin_id) ? $origin_id : $this->origin_id);
4811 $f_user = isset($f_user) ? $f_user : $user;
4814 if ($origin ==
'order') {
4815 $origin =
'commande';
4817 if ($origin ==
'invoice') {
4818 $origin =
'facture';
4820 if ($origin ==
'invoice_template') {
4821 $origin =
'facturerec';
4823 if ($origin ==
'supplierorder') {
4824 $origin =
'order_supplier';
4828 $targettype = $this->getElementType();
4830 $parameters = array(
'targettype' => $targettype);
4832 $reshook = $hookmanager->executeHooks(
'setLinkedObjectSourceTargetType', $parameters, $this, $action);
4834 if (!empty($hookmanager->resArray[
'targettype'])) {
4835 $targettype = $hookmanager->resArray[
'targettype'];
4842 $sql =
"INSERT INTO " . $this->db->prefix() .
"element_element (";
4843 $sql .=
"fk_source";
4844 $sql .=
", sourcetype";
4845 $sql .=
", fk_target";
4846 $sql .=
", targettype";
4847 $sql .=
") VALUES (";
4848 $sql .= ((int) $origin_id);
4849 $sql .=
", '" . $this->db->escape($origin) .
"'";
4850 $sql .=
", " . ((int) $this->
id);
4851 $sql .=
", '" . $this->db->escape($targettype) .
"'";
4854 dol_syslog(get_class($this) .
"::add_object_linked", LOG_DEBUG);
4855 if ($this->db->query($sql)) {
4859 if ($origin ===
'order_supplier' && $targettype ===
'invoice_supplier' && $this->element ===
'invoice_supplier' && (
int) $origin_id > 0 && (
int) $this->
id > 0) {
4860 $sourceinvoices = array();
4862 $sqlsources =
"SELECT DISTINCT rc.fk_invoice_supplier_source as rowid";
4863 $sqlsources .=
" FROM ".$this->db->prefix().
"societe_remise_except as rc";
4864 $sqlsources .=
" WHERE rc.fk_invoice_supplier = ".((int) $this->
id);
4865 $sqlsources .=
" AND rc.fk_invoice_supplier_source IS NOT NULL";
4867 $resqlsources = $this->db->query($sqlsources);
4868 if ($resqlsources) {
4869 while ($objsrc = $this->db->fetch_object($resqlsources)) {
4870 $srcid = (int) $objsrc->rowid;
4871 if ($srcid > 0 && $srcid !== (
int) $this->
id) {
4872 $sourceinvoices[$srcid] = $srcid;
4876 dol_syslog(get_class($this).
"::add_object_linked Failed to read supplier invoice discounts sources", LOG_WARNING);
4879 if (!empty($sourceinvoices)) {
4880 $existing = array();
4881 $sourcelist = implode(
',', $sourceinvoices);
4883 $sqlexists =
"SELECT fk_target";
4884 $sqlexists .=
" FROM ".$this->db->prefix().
"element_element";
4885 $sqlexists .=
" WHERE fk_source = ".((int) $origin_id);
4886 $sqlexists .=
" AND sourcetype = '".$this->db->escape($origin).
"'";
4887 $sqlexists .=
" AND targettype = '".$this->db->escape($targettype).
"'";
4888 $sqlexists .=
" AND fk_target IN (".$this->db->sanitize($sourcelist).
")";
4890 $resqlexists = $this->db->query($sqlexists);
4892 while ($objexist = $this->db->fetch_object($resqlexists)) {
4893 $existing[(int) $objexist->fk_target] = 1;
4896 dol_syslog(get_class($this).
"::add_object_linked Failed to read existing linked supplier invoices", LOG_WARNING);
4899 foreach ($sourceinvoices as $srcid) {
4900 if (!empty($existing[(
int) $srcid])) {
4904 $sqladd =
"INSERT INTO " . $this->db->prefix() .
"element_element (fk_source, sourcetype, fk_target, targettype)";
4905 $sqladd .=
" VALUES (".((int) $origin_id).
", '".$this->db->escape($origin).
"', ".((int) $srcid).
", '".$this->db->escape($targettype).
"')";
4906 $this->db->query($sqladd);
4913 $this->context[
'link_origin'] = $origin;
4914 $this->context[
'link_origin_id'] = $origin_id;
4916 $result = $this->call_trigger(
'OBJECT_LINK_INSERT', $f_user);
4923 $this->error = $this->db->lasterror();
4928 $this->db->commit();
4931 $this->db->rollback();
4945 $coreModule = array(
'knowledgemanagement',
'partnership',
'workstation',
'ticket',
'recruitment',
'eventorganization',
'asset');
4947 return ((!empty($this->module) && !in_array($this->module, $coreModule)) ? $this->module.
'_' :
'').$this->element;
4973 public function fetchObjectLinked($sourceid =
null, $sourcetype =
'', $targetid =
null, $targettype =
'', $clause =
'OR', $alsosametype = 1, $orderby =
'sourcetype', $loadalsoobjects = 1)
4975 global $hookmanager, $action;
4980 if ($this->
id > 0 && !empty($this->linkedObjectsFullLoaded[$this->
id])) {
4984 $this->linkedObjectsIds = array();
4985 $this->linkedObjects = array();
4988 $parameters = array(
4989 'sourceid' => $sourceid,
4990 'sourcetype' => $sourcetype,
4991 'targetid' => $targetid,
4992 'targettype' => $targettype,
4993 'clause' => $clause,
4994 'alsosametype' => $alsosametype,
4995 'orderby' => $orderby,
4996 'loadalsoobjects' => $loadalsoobjects
4998 $reshook = $hookmanager->executeHooks(
'fetchObjectLinked', $parameters, $this, $action);
5003 $justsource =
false;
5004 $justtarget =
false;
5005 $withtargettype =
false;
5006 $withsourcetype =
false;
5009 if (is_object($hookmanager)) {
5010 $parameters = array(
'sourcetype' => $sourcetype,
'sourceid' => $sourceid,
'targettype' => $targettype,
'targetid' => $targetid);
5011 $reshook = $hookmanager->executeHooks(
'setLinkedObjectSourceTargetType', $parameters, $this, $action);
5013 if (!empty($hookmanager->resArray[
'sourcetype'])) {
5014 $sourcetype = $hookmanager->resArray[
'sourcetype'];
5016 if (!empty($hookmanager->resArray[
'sourceid'])) {
5017 $sourceid = $hookmanager->resArray[
'sourceid'];
5019 if (!empty($hookmanager->resArray[
'targettype'])) {
5020 $targettype = $hookmanager->resArray[
'targettype'];
5022 if (!empty($hookmanager->resArray[
'targetid'])) {
5023 $targetid = $hookmanager->resArray[
'targetid'];
5028 if (!empty($sourceid) && !empty($sourcetype) && empty($targetid)) {
5030 if (!empty($targettype)) {
5031 $withtargettype =
true;
5034 if (!empty($targetid) && !empty($targettype) && empty($sourceid)) {
5036 if (!empty($sourcetype)) {
5037 $withsourcetype =
true;
5041 $sourceid = (!empty($sourceid) ? $sourceid :
$this->id);
5042 $targetid = (!empty($targetid) ? $targetid :
$this->id);
5043 $sourcetype = (!empty($sourcetype) ? $sourcetype : $this->getElementType());
5044 $targettype = (!empty($targettype) ? $targettype : $this->getElementType());
5053 $sql =
"SELECT rowid, fk_source, sourcetype, fk_target, targettype";
5054 $sql .=
" FROM ".$this->db->prefix().
"element_element";
5056 if ($justsource || $justtarget) {
5058 $sql .=
"fk_source = ".((int) $sourceid).
" AND sourcetype = '".$this->db->escape($sourcetype).
"'";
5059 if ($withtargettype) {
5060 $sql .=
" AND targettype = '".$this->db->escape($targettype).
"'";
5062 } elseif ($justtarget) {
5063 $sql .=
"fk_target = ".((int) $targetid).
" AND targettype = '".$this->db->escape($targettype).
"'";
5064 if ($withsourcetype) {
5065 $sql .=
" AND sourcetype = '".$this->db->escape($sourcetype).
"'";
5069 $sql .=
"(fk_source = ".((int) $sourceid).
" AND sourcetype = '".$this->db->escape($sourcetype).
"')";
5070 $sql .=
" ".$this->db->sanitize($clause).
" (fk_target = ".((int) $targetid).
" AND targettype = '".$this->db->escape($targettype).
"')";
5071 if ($loadalsoobjects && $this->
id > 0 && $sourceid == $this->
id && $sourcetype == $this->element && $targetid == $this->
id && $targettype == $this->element && $clause ==
'OR') {
5072 $this->linkedObjectsFullLoaded[
$this->id] =
true;
5075 $sql .= $this->db->order($orderby);
5077 dol_syslog(get_class($this).
"::fetchObjectLink", LOG_DEBUG);
5079 $resql = $this->db->query($sql);
5081 $num = $this->db->num_rows($resql);
5084 $obj = $this->db->fetch_object($resql);
5085 if ($justsource || $justtarget) {
5087 $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
5088 } elseif ($justtarget) {
5089 $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
5092 if ($obj->fk_source == $sourceid && $obj->sourcetype == $sourcetype) {
5093 $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
5095 if ($obj->fk_target == $targetid && $obj->targettype == $targettype) {
5096 $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
5102 if (!empty($this->linkedObjectsIds)) {
5103 $tmparray = $this->linkedObjectsIds;
5104 foreach ($tmparray as $objecttype => $objectids) {
5106 $element = $element_properties[
'element'];
5107 $classPath = $element_properties[
'classpath'];
5108 $classFile = $element_properties[
'classfile'];
5109 $className = $element_properties[
'classname'];
5110 $module = $element_properties[
'module'];
5114 if ($loadalsoobjects && (is_numeric($loadalsoobjects) || ($loadalsoobjects === $objecttype))) {
5116 if (class_exists($className)) {
5117 foreach ($objectids as $i => $objectid) {
5118 $object =
new $className($this->db);
5119 '@phan-var-force CommonObject $object';
5120 $ret =
$object->fetch($objectid);
5122 $this->linkedObjects[$objecttype][$i] =
$object;
5128 unset($this->linkedObjectsIds[$objecttype]);
5134 dol_print_error($this->db);
5147 if ($this->
id > 0 && !empty($this->linkedObjectsFullLoaded[$this->
id])) {
5148 unset($this->linkedObjectsFullLoaded[$this->
id]);
5166 public function updateObjectLinked($sourceid =
null, $sourcetype =
'', $targetid =
null, $targettype =
'', $f_user =
null, $notrigger = 0)
5169 $updatesource =
false;
5170 $updatetarget =
false;
5171 $f_user = isset($f_user) ? $f_user : $user;
5174 if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) {
5175 $updatesource =
true;
5176 } elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) {
5177 $updatetarget =
true;
5183 $sql =
"UPDATE " . $this->db->prefix() .
"element_element SET ";
5184 if ($updatesource) {
5185 $sql .=
"fk_source = " . ((int) $sourceid);
5186 $sql .=
", sourcetype = '" . $this->db->escape($sourcetype) .
"'";
5187 $sql .=
" WHERE fk_target = " . ((int) $this->
id);
5188 $sql .=
" AND targettype = '" . $this->db->escape($this->element) .
"'";
5189 } elseif ($updatetarget) {
5190 $sql .=
"fk_target = " . ((int) $targetid);
5191 $sql .=
", targettype = '" . $this->db->escape($targettype) .
"'";
5192 $sql .=
" WHERE fk_source = " . ((int) $this->
id);
5193 $sql .=
" AND sourcetype = '" . $this->db->escape($this->element) .
"'";
5196 dol_syslog(get_class($this) .
"::updateObjectLinked", LOG_DEBUG);
5197 if ($this->db->query($sql)) {
5200 $this->context[
'link_source_id'] = $sourceid;
5201 $this->context[
'link_source_type'] = $sourcetype;
5202 $this->context[
'link_target_id'] = $targetid;
5203 $this->context[
'link_target_type'] = $targettype;
5205 $result = $this->call_trigger(
'OBJECT_LINK_MODIFY', $f_user);
5212 $this->error = $this->db->lasterror();
5217 $this->db->commit();
5220 $this->db->rollback();
5238 public function deleteObjectLinked($sourceid =
null, $sourcetype =
'', $targetid =
null, $targettype =
'', $rowid = 0, $f_user =
null, $notrigger = 0)
5241 $deletesource =
false;
5242 $deletetarget =
false;
5243 $f_user = isset($f_user) ? $f_user : $user;
5245 if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) {
5246 $deletesource =
true;
5247 } elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) {
5248 $deletetarget =
true;
5251 $element = $this->getElementType();
5252 $sourceid = (!empty($sourceid) ? $sourceid :
$this->id);
5253 $sourcetype = (!empty($sourcetype) ? $sourcetype : $element);
5254 $targetid = (!empty($targetid) ? $targetid :
$this->id);
5255 $targettype = (!empty($targettype) ? $targettype : $element);
5261 $this->context[
'link_id'] = $rowid;
5262 $this->context[
'link_source_id'] = $sourceid;
5263 $this->context[
'link_source_type'] = $sourcetype;
5264 $this->context[
'link_target_id'] = $targetid;
5265 $this->context[
'link_target_type'] = $targettype;
5267 $result = $this->call_trigger(
'OBJECT_LINK_DELETE', $f_user);
5275 $sql =
"DELETE FROM " . $this->db->prefix() .
"element_element";
5278 $sql .=
" rowid = " . ((int) $rowid);
5280 if ($deletesource) {
5281 $sql .=
" fk_source = " . ((int) $sourceid) .
" AND sourcetype = '" . $this->db->escape($sourcetype) .
"'";
5282 $sql .=
" AND fk_target = " . ((int) $this->
id) .
" AND targettype = '" . $this->db->escape($element) .
"'";
5283 } elseif ($deletetarget) {
5284 $sql .=
" fk_target = " . ((int) $targetid) .
" AND targettype = '" . $this->db->escape($targettype) .
"'";
5285 $sql .=
" AND fk_source = " . ((int) $this->
id) .
" AND sourcetype = '" . $this->db->escape($element) .
"'";
5287 $sql .=
" (fk_source = " . ((int) $this->
id) .
" AND sourcetype = '" . $this->db->escape($element) .
"')";
5289 $sql .=
" (fk_target = " . ((int) $this->
id) .
" AND targettype = '" . $this->db->escape($element) .
"')";
5293 dol_syslog(get_class($this) .
"::deleteObjectLinked", LOG_DEBUG);
5294 if (!$this->db->query($sql)) {
5295 $this->error = $this->db->lasterror();
5296 $this->errors[] = $this->error;
5302 $this->db->commit();
5305 $this->db->rollback();
5321 if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
5324 if (!preg_match(
'/^[_a-zA-Z0-9]+$/', $field_select)) {
5325 dol_syslog(
'Invalid value $field_select for parameter '.$field_select.
' in call to getAllItemsLinkedByObjectID(). Must be a single field name.', LOG_ERR);
5330 $sql =
"SELECT ".$db->sanitize($field_select).
" FROM ".$db->prefix().$db->sanitize($table_element).
" WHERE ".$db->sanitize($field_where).
" = ".((int) $fk_object_where);
5331 $resql = $db->query($sql);
5334 if (!empty($resql)) {
5335 while ($res = $db->fetch_object($resql)) {
5336 $TRes[] = $res->{$field_select};
5353 if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
5359 $sql =
"SELECT COUNT(*) as nb FROM ".$db->prefix().$db->sanitize($table_element).
" WHERE ".$db->sanitize($field_where).
" = ".((int) $fk_object_where);
5360 $resql = $db->query($sql);
5363 $res = $db->fetch_object($resql);
5382 if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
5388 $sql =
"DELETE FROM ".$db->prefix().$table_element.
" WHERE ".$db->sanitize($field_where).
" = ".((int) $fk_object_where);
5389 $resql = $db->query($sql);
5391 if (empty($resql)) {
5409 public function setStatut($status, $elementId =
null, $elementType =
'', $trigkey =
'', $fieldstatus =
'')
5413 $savElementId = $elementId;
5415 $elementId = (!empty($elementId) ? $elementId :
$this->id);
5416 $elementTable = (!empty($elementType) ? $elementType : $this->table_element);
5420 if (empty($fieldstatus)) {
5421 if ($elementTable ==
'facture_rec') {
5422 $fieldstatus =
"suspended";
5424 if ($elementTable ==
'mailing') {
5425 $fieldstatus =
"statut";
5427 if ($elementTable ==
'cronjob') {
5428 $fieldstatus =
"status";
5430 if ($elementTable ==
'user') {
5431 $fieldstatus =
"statut";
5433 if ($elementTable ==
'expensereport') {
5434 $fieldstatus =
"fk_statut";
5436 if ($elementTable ==
'receptiondet_batch') {
5437 $fieldstatus =
"status";
5439 if ($elementTable ==
'prelevement_bons') {
5440 $fieldstatus =
"statut";
5442 if ($elementTable ==
'bank_account') {
5443 $fieldstatus =
"clos";
5445 if (isset($this->fields) && is_array($this->fields) && array_key_exists(
'status', $this->fields)) {
5446 $fieldstatus =
'status';
5449 if (empty($fieldstatus)) {
5450 $fieldstatus =
'fk_statut';
5454 $sql =
"UPDATE ".$this->db->prefix().$this->db->sanitize($elementTable);
5455 $sql .=
" SET ".$this->db->sanitize($fieldstatus).
" = ".((int) $status);
5458 if ($status == 1 && in_array($elementTable, array(
'expensereport',
'inventory'))) {
5459 $sql .=
", fk_user_valid = ".((int) $user->id);
5461 if ($status == 1 && in_array($elementTable, array(
'expensereport'))) {
5462 $sql .=
", date_valid = '".$this->db->idate(
dol_now()).
"'";
5464 if ($status == 1 && in_array($elementTable, array(
'inventory'))) {
5465 $sql .=
", date_validation = '".$this->db->idate(
dol_now()).
"'";
5467 $sql .=
" WHERE rowid = ".((int) $elementId);
5468 $sql .=
" AND ".$this->db->sanitize($fieldstatus).
" <> ".((int) $status);
5470 dol_syslog(get_class($this).
"::setStatut", LOG_DEBUG);
5471 $resql = $this->db->query($sql);
5475 $nb_rows_affected = $this->db->affected_rows($resql);
5477 if ($nb_rows_affected > 0) {
5478 if (empty($trigkey)) {
5480 if ($this->element ==
'supplier_proposal' && $status == 2) {
5481 $trigkey =
'SUPPLIER_PROPOSAL_SIGN';
5483 if ($this->element ==
'supplier_proposal' && $status == 3) {
5484 $trigkey =
'SUPPLIER_PROPOSAL_REFUSE';
5486 if ($this->element ==
'supplier_proposal' && $status == 4) {
5487 $trigkey =
'SUPPLIER_PROPOSAL_CLOSE';
5489 if ($this->element ==
'fichinter' && $status == 3) {
5490 $trigkey =
'FICHINTER_CLASSIFY_DONE';
5492 if ($this->element ==
'fichinter' && $status == 2) {
5493 $trigkey =
'FICHINTER_CLASSIFY_BILLED';
5495 if ($this->element ==
'fichinter' && $status == 1) {
5496 $trigkey =
'FICHINTER_CLASSIFY_UNBILLED';
5500 $this->context = array_merge($this->context, array(
'newstatus' => $status));
5502 if ($trigkey && $trigkey !=
'none') {
5506 $result = $this->call_trigger($trigkey, $user);
5517 $this->db->commit();
5519 if (empty($savElementId)) {
5521 if ($fieldstatus ==
'dispute_status') {
5522 $this->dispute_status = $status;
5523 } elseif ($fieldstatus ==
'tosell') {
5525 } elseif ($fieldstatus ==
'tobuy') {
5526 $this->status_buy = $status;
5527 } elseif ($fieldstatus ==
'tobatch') {
5528 $this->status_batch = $status;
5529 } elseif ($fieldstatus ==
'stockable_product') {
5530 $this->stockable_product = $status;
5538 $this->db->rollback();
5539 dol_syslog(get_class($this).
"::setStatut ".$this->error, LOG_ERR);
5543 $this->error = $this->db->lasterror();
5544 $this->db->rollback();
5559 if (empty(
$id) && empty($ref)) {
5569 $sql =
"SELECT rowid, canvas";
5570 $sql .=
" FROM ".$this->db->prefix().$this->table_element;
5571 $sql .=
" WHERE entity IN (".getEntity($this->element).
")";
5573 $sql .=
" AND rowid = ".((int)
$id);
5576 $sql .=
" AND ref = '".$this->db->escape($ref).
"'";
5579 $resql = $this->db->query($sql);
5581 $obj = $this->db->fetch_object($resql);
5583 $this->canvas = $obj->canvas;
5589 dol_print_error($this->db);
5603 $sql =
"SELECT special_code FROM ".$this->db->prefix().$this->db->sanitize($this->table_element_line);
5604 $sql .=
" WHERE rowid = ".((int) $lineid);
5605 $resql = $this->db->query($sql);
5607 $row = $this->db->fetch_row($resql);
5608 return (!empty($row[0]) ? $row[0] : 0);
5631 if (!isset($this->childtables) || !is_array($this->childtables) || count($this->childtables) == 0) {
5632 dol_print_error(
null,
'Called isObjectUsed on a class with property this->childtables not defined');
5636 $arraytoscan = $this->childtables;
5638 $tmparray = array_keys($this->childtables);
5639 if (is_numeric($tmparray[0])) {
5640 $arraytoscan = array_flip($this->childtables);
5645 foreach ($arraytoscan as $table => $element) {
5649 if (isset($element[
'enabled']) && !empty($element[
'enabled'])) {
5650 $enabled = (int)
dol_eval((
string) $element[
'enabled'], 1);
5651 if (empty($enabled)) {
5657 $sql =
"SELECT COUNT(*) as nb";
5658 $sql .=
" FROM ".$this->db->prefix().$this->db->sanitize($table).
" as c";
5659 if (!empty($element[
'parent']) && !empty($element[
'parentkey'])) {
5660 $sql .=
", ".$this->db->prefix().$this->db->sanitize($element[
'parent']).
" as p";
5662 if (!empty($element[
'fk_element'])) {
5663 $sql .=
" WHERE c.".$this->db->sanitize($element[
'fk_element']).
" = ".((int)
$id);
5665 $sql .=
" WHERE c.".$this->db->sanitize($this->fk_element).
" = ".((int)
$id);
5667 if (!empty($element[
'parent']) && !empty($element[
'parentkey'])) {
5668 $sql .=
" AND c.".$this->db->sanitize($element[
'parentkey']).
" = p.rowid";
5670 if (!empty($element[
'parent']) && !empty($element[
'parenttypefield']) && !empty($element[
'parenttypevalue'])) {
5671 $sql .=
" AND c.".$this->db->sanitize($element[
'parenttypefield']).
" = '".$this->db->escape($element[
'parenttypevalue']).
"'";
5673 if (!empty($entity)) {
5674 if (!empty($element[
'parent']) && !empty($element[
'parentkey'])) {
5675 $sql .=
" AND p.entity = ".((int) $entity);
5677 $sql .=
" AND c.entity = ".((int) $entity);
5682 $resql = $this->db->query($sql);
5684 $obj = $this->db->fetch_object($resql);
5686 $langs->load(
"errors");
5688 $haschild += (int) $obj->nb;
5689 if (is_numeric($element)) {
5690 $this->errors[] = $langs->transnoentitiesnoconv(
"ErrorRecordHasAtLeastOneChildOfType", method_exists($this,
'getNomUrl') ? $this->getNomUrl() : $this->ref, $table);
5691 } elseif (is_string($element)) {
5692 $this->errors[] = $langs->transnoentitiesnoconv(
"ErrorRecordHasAtLeastOneChildOfType", method_exists($this,
'getNomUrl') ? $this->getNomUrl() : $this->ref, $langs->transnoentitiesnoconv($element));
5694 $this->errors[] = $langs->transnoentitiesnoconv(
"ErrorRecordHasAtLeastOneChildOfType", method_exists($this,
'getNomUrl') ? $this->getNomUrl() : $this->ref, $langs->transnoentitiesnoconv($element[
'name']));
5699 $this->errors[] = $this->db->lasterror();
5704 if ($haschild > 0) {
5705 $this->errors[] =
"ErrorRecordHasChildren";
5722 foreach ($this->lines as $key => $val) {
5724 if ($predefined == -1) {
5727 if ($predefined == 1 && $val->fk_product > 0) {
5730 if ($predefined == 0 && $val->fk_product <= 0) {
5733 if ($predefined == 2 && $val->fk_product > 0 && $val->product_type == 0) {
5736 if ($predefined == 3 && $val->fk_product > 0 && $val->product_type == 1) {
5743 dol_syslog(get_class($this).
'::hasProductsOrServices we found '.$nb.
' qualified lines of products/servcies');
5754 if (!empty($this->table_element_line) && ($this->table_element_line !=
'expeditiondet')) {
5755 $total_discount = 0.00;
5757 $sql =
"SELECT subprice as pu_ht, qty, remise_percent, total_ht";
5758 $sql .=
" FROM ".$this->db->prefix().$this->table_element_line;
5759 $sql .=
" WHERE ".$this->db->sanitize($this->fk_element).
" = ".((int) $this->
id);
5761 dol_syslog(get_class($this).
'::getTotalDiscount', LOG_DEBUG);
5762 $resql = $this->db->query($sql);
5764 $num = $this->db->num_rows($resql);
5767 $obj = $this->db->fetch_object($resql);
5769 $pu_ht = $obj->pu_ht;
5771 $total_ht = $obj->total_ht;
5773 $total_discount_line = (float)
price2num(($pu_ht * $qty) - $total_ht,
'MT');
5774 $total_discount += $total_discount_line;
5781 return (
float)
price2num($total_discount);
5803 if (empty($this->lines)) {
5804 return array(
'weight' => $totalWeight,
'volume' => $totalVolume,
'ordered' => $totalOrdered,
'toship' => $totalToShip);
5807 foreach ($this->lines as $line) {
5808 if (isset($line->qty_asked)) {
5809 $totalOrdered += $line->qty_asked;
5811 if (isset($line->qty_shipped)) {
5812 $totalToShip += $line->qty_shipped;
5813 } elseif ($line->element ==
'commandefournisseurdispatch' && isset($line->qty)) {
5814 if (empty($totalToShip)) {
5817 $totalToShip += $line->qty;
5821 if ($this->element ==
'shipping') {
5823 $qty = $line->qty_shipped ? $line->qty_shipped : 0;
5825 $qty = $line->qty ? $line->qty : 0;
5828 $weight = !empty($line->weight) ? $line->weight : 0;
5829 ($weight == 0 && !empty($line->product->weight)) ? $weight = $line->product->weight : 0;
5830 $volume = !empty($line->volume) ? $line->volume : 0;
5831 ($volume == 0 && !empty($line->product->volume)) ? $volume = $line->product->volume : 0;
5833 $weight_units = !empty($line->weight_units) ? $line->weight_units : 0;
5834 ($weight_units == 0 && !empty($line->product->weight_units)) ? $weight_units = $line->product->weight_units : 0;
5835 $volume_units = !empty($line->volume_units) ? $line->volume_units : 0;
5836 ($volume_units == 0 && !empty($line->product->volume_units)) ? $volume_units = $line->product->volume_units : 0;
5840 if (!empty($weight_units)) {
5841 $weightUnit = $weight_units;
5843 if (!empty($volume_units)) {
5844 $volumeUnit = $volume_units;
5847 if (empty($totalWeight)) {
5850 if (empty($totalVolume)) {
5855 if ($weight_units < 50) {
5856 $trueWeightUnit = pow(10, $weightUnit);
5857 $totalWeight += $weight * $qty * $trueWeightUnit;
5859 if ($weight_units == 99) {
5861 $trueWeightUnit = 0.45359237;
5862 $totalWeight += $weight * $qty * $trueWeightUnit;
5863 } elseif ($weight_units == 98) {
5865 $trueWeightUnit = 0.0283495;
5866 $totalWeight += $weight * $qty * $trueWeightUnit;
5868 $totalWeight += $weight * $qty;
5871 if ($volume_units < 50) {
5873 $trueVolumeUnit = pow(10, $volumeUnit);
5875 $totalVolume += $volume * $qty * $trueVolumeUnit;
5877 $totalVolume += $volume * $qty;
5881 return array(
'weight' => $totalWeight,
'volume' => $totalVolume,
'ordered' => $totalOrdered,
'toship' => $totalToShip);
5894 $extraparams = (!empty($this->extraparams) ? json_encode($this->extraparams) :
null);
5895 $extraparams =
dol_trunc($extraparams, 250);
5897 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
5898 $sql .=
" SET extraparams = ".(!empty($extraparams) ?
"'".$this->db->escape($extraparams).
"'" :
"null");
5899 $sql .=
" WHERE rowid = ".((int) $this->
id);
5901 dol_syslog(get_class($this).
"::setExtraParameters", LOG_DEBUG);
5902 $resql = $this->db->query($sql);
5904 $this->error = $this->db->lasterror();
5905 $this->db->rollback();
5908 $this->db->commit();
5931 global
$conf, $user, $langs,
$object, $hookmanager, $extrafields, $form;
5934 if (!is_object($extrafields)) {
5935 require_once DOL_DOCUMENT_ROOT.
'/core/class/extrafields.class.php';
5938 $extrafields->fetch_name_optionals_label($this->table_element_line);
5943 $dirtpls = array_merge(
$conf->modules_parts[
'tpl'], array($defaulttpldir));
5944 foreach ($dirtpls as
$module => $reldir) {
5948 $tpl = DOL_DOCUMENT_ROOT.$reldir.
'/objectline_create.tpl.php';
5951 if (empty(
$conf->file->strict_mode)) {
5952 $res = @include $tpl;
5954 $res = include $tpl;
5981 public function printObjectLines($action, $seller, $buyer, $selected = 0, $dateSelector = 0, $defaulttpldir =
'/core/tpl')
5983 global
$conf, $hookmanager, $langs, $user, $form, $extrafields,
$object;
5985 global $inputalsopricewithtax, $usemargins, $disableedit, $disablemove, $disableremove, $outputalsopricetotalwithtax;
5987 $this->prepareObjectLinesDisplay();
5989 $num = count($this->lines);
5991 $parameters = array();
5992 $reshook = $hookmanager->executeHooks(
'printObjectLinesBlock', $parameters, $this, $action);
5993 if (empty($reshook)) {
5994 $parameters = array(
'num' => $num,
'dateSelector' => $dateSelector,
'seller' => $seller,
'buyer' => $buyer,
'selected' => $selected,
'table_element_line' => $this->table_element_line);
5995 $reshook = $hookmanager->executeHooks(
'printObjectLineTitle', $parameters, $this, $action);
5996 if (empty($reshook)) {
6000 $dirtpls = array_merge(
$conf->modules_parts[
'tpl'], array($defaulttpldir));
6001 foreach ($dirtpls as
$module => $reldir) {
6006 $tpl = DOL_DOCUMENT_ROOT.$reldir.
'/objectline_title.tpl.php';
6008 if (file_exists($tpl)) {
6009 if (empty(
$conf->file->strict_mode)) {
6010 $res = @include $tpl;
6012 $res = include $tpl;
6023 print
"<!-- begin printObjectLines() -->\n";
6024 foreach ($this->lines as $line) {
6028 $this->printObjectLineWithHooks($action, $line, $num, $i, $dateSelector, $seller, $buyer, $selected, $extrafields, $defaulttpldir);
6032 print
"<!-- end printObjectLines() -->\n";
6044 global $extrafields, $usemargins;
6048 if (
isModEnabled(
'margin') && !empty($this->element) && in_array($this->element, array(
'facture',
'facturerec',
'propal',
'commande'))) {
6053 if (!is_object($extrafields)) {
6054 require_once DOL_DOCUMENT_ROOT.
'/core/class/extrafields.class.php';
6057 $extrafields->fetch_name_optionals_label($this->table_element_line);
6059 if (method_exists($this,
'loadExpeditions')) {
6061 $this->loadExpeditions();
6081 protected function printObjectLineWithHooks($action, $line, $num, $i, $dateSelector, $seller, $buyer, $selected, $extrafields, $defaulttpldir)
6083 global $hookmanager;
6087 $fk_parent_line = (empty($line->fk_parent_line) ? 0 : $line->fk_parent_line);
6090 if (is_object($hookmanager)) {
6091 if (empty($fk_parent_line)) {
6092 $parameters = array(
'line' => $line,
'num' => $num,
'i' => $i,
'dateSelector' => $dateSelector,
'seller' => $seller,
'buyer' => $buyer,
'selected' => $selected,
'table_element_line' => $line->table_element,
'defaulttpldir' => $defaulttpldir);
6093 $reshook = $hookmanager->executeHooks(
'printObjectLine', $parameters, $this, $action);
6095 $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' => $fk_parent_line,
'defaulttpldir' => $defaulttpldir);
6096 $reshook = $hookmanager->executeHooks(
'printObjectSubLine', $parameters, $this, $action);
6099 if (empty($reshook)) {
6100 $this->printObjectLine($action, $line,
'', $num, $i, $dateSelector, $seller, $buyer, $selected, $extrafields, $defaulttpldir);
6116 'buyer' => (is_object($this->thirdparty) ? $this->thirdparty :
null),
6117 'dateSelector' => 1,
6119 'senderissupplier' => 0,
6120 'inputalsopricewithtax' => 0,
6133 global $forceall, $senderissupplier, $inputalsopricewithtax;
6135 $context = $this->getObjectLinesDisplayContext();
6138 $senderissupplier =
$context[
'senderissupplier'];
6139 $inputalsopricewithtax =
$context[
'inputalsopricewithtax'];
6157 global
$object, $form, $extrafields;
6158 global $forceall, $senderissupplier, $inputalsopricewithtax, $usemargins;
6160 $lines = (is_array($this->lines) ? $this->lines : array());
6161 $num = count($lines);
6164 foreach ($lines as $tmpline) {
6165 if ($tmpline->id == $lineid) {
6171 if ($line ===
null) {
6172 $this->error =
'ErrorRecordNotFound';
6178 if (!is_object($this->thirdparty) && property_exists($this,
'socid') && !empty($this->socid)) {
6179 $this->fetch_thirdparty();
6183 $savedGlobals = array(
$object, $form, $extrafields, $forceall, $senderissupplier, $inputalsopricewithtax, $usemargins);
6186 if (!is_object($form)) {
6187 require_once DOL_DOCUMENT_ROOT.
'/core/class/html.form.class.php';
6188 $form =
new Form($this->db);
6190 $context = $this->initObjectLinesDisplay();
6191 $this->prepareObjectLinesDisplay();
6194 $this->printObjectLineWithHooks($action, $line, $num, $i,
$context[
'dateSelector'],
$context[
'seller'],
$context[
'buyer'], 0, $extrafields,
'/core/tpl');
6195 $out = ob_get_clean();
6197 list(
$object, $form, $extrafields, $forceall, $senderissupplier, $inputalsopricewithtax, $usemargins) = $savedGlobals;
6199 return (
string) $out;
6219 public function printObjectLine($action, $line, $var, $num, $i, $dateSelector, $seller, $buyer, $selected = 0, $extrafields =
null, $defaulttpldir =
'/core/tpl')
6223 global $disableedit, $disablemove, $disableremove;
6230 if ($action !=
'editline' || $selected != $line->id) {
6232 if (!empty($line->fk_product) && $line->fk_product > 0) {
6233 $product_static =
new Product($this->db);
6234 $product_static->fetch($line->fk_product);
6236 $product_static->ref = (string) $line->ref;
6238 $product_static->label = !empty($line->label) ? $line->label :
"";
6240 $text = $product_static->getNomUrl(1);
6245 if (property_exists($this,
'socid') && !empty($this->socid) && !is_object($this->thirdparty)) {
6246 dol_print_error(
null,
'Error: Method printObjectLine was called on an object and object->fetch_thirdparty was not done before');
6250 $prod =
new Product($this->db);
6251 $prod->fetch($line->fk_product);
6253 $outputlangs = $langs;
6255 if (
GETPOST(
'lang_id',
'aZ09')) {
6256 $newlang =
GETPOST(
'lang_id',
'aZ09');
6258 if (
getDolGlobalString(
'PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE') && empty($newlang) && is_object($this->thirdparty)) {
6259 $newlang = $this->thirdparty->default_lang;
6261 if (!empty($newlang)) {
6263 $outputlangs->setDefaultLang($newlang);
6266 $label = (!empty($prod->multilangs[$outputlangs->defaultlang][
"label"])) ? $prod->multilangs[$outputlangs->defaultlang][
"label"] : $line->product_label;
6268 $label = $line->product_label;
6272 $text .=
' - '.(!empty($line->label) ? $line->label : $label);
6273 $description .= (
getDolGlobalInt(
'PRODUIT_DESC_IN_FORM_ACCORDING_TO_DEVICE') ?
'' : (!empty($line->description) ?
dol_htmlentitiesbr($line->description) :
''));
6277 if (empty((
float) $line->subprice_ttc) && $line->qty) {
6280 if (empty((
float) $line->localtax1_tx) && empty((
float) $line->localtax2_tx) && !empty((
float) $line->subprice)) {
6282 $line->subprice_ttc = (float)
price2num($line->subprice * (1 + ((((
int) $line->info_bits & 1) ? 0 : (float) $line->tva_tx) / 100)),
'MU');
6283 } elseif ($line->remise_percent != 100) {
6285 $line->subprice_ttc = (float)
price2num($line->total_ttc * ($line->situation_percent ? 100 / $line->situation_percent : 1) / $line->qty / (1 - $line->remise_percent / 100),
'MU');
6288 $line->subprice_ttc = (float)
price2num((!empty($line->subprice) ? $line->subprice : 0) * (1 + ((!empty($line->tva_tx) ? $line->tva_tx : 0) / 100)),
'MU');
6291 $line->pu_ttc = $line->subprice_ttc;
6298 if (isset($this->expeditions[$line->id])) {
6300 $qty_shipped = $this->expeditions[$line->id];
6302 $disableedit = ($qty_shipped > 0) && ($qty_shipped >= $line->qty);
6304 $dirtpls = array_merge(
$conf->modules_parts[
'tpl'], array($defaulttpldir));
6305 foreach ($dirtpls as
$module => $reldir) {
6310 $tpl = DOL_DOCUMENT_ROOT.$reldir.
'/objectline_view.tpl.php';
6313 if (file_exists($tpl)) {
6314 if (empty(
$conf->file->strict_mode)) {
6315 $res = @include $tpl;
6317 $res = include $tpl;
6327 if ($this->
status == 0 && $action ==
'editline' && $selected == $line->id) {
6329 $label = (!empty($line->label) ? $line->label : (($line->fk_product > 0) ? $line->product_label :
''));
6331 $line->subprice_ttc = (float)
price2num($line->subprice * (1 + ($line->tva_tx / 100)),
'MU');
6332 $line->pu_ttc = $line->subprice_ttc;
6337 $dirtpls = array_merge(
$conf->modules_parts[
'tpl'], array($defaulttpldir));
6338 foreach ($dirtpls as
$module => $reldir) {
6342 $tpl = DOL_DOCUMENT_ROOT.$reldir.
'/objectline_edit.tpl.php';
6345 if (empty(
$conf->file->strict_mode)) {
6346 $res = @include $tpl;
6348 $res = include $tpl;
6373 global $langs, $hookmanager, $form, $action;
6375 print
'<!-- printOriginLinesList '.get_class($this).
' -->'.
"\n";
6376 print
'<tr class="liste_titre">';
6377 print
'<td class="linecolref">'.$langs->trans(
'Ref').
'</td>';
6378 print
'<td class="linecoldescription">'.$langs->trans(
'Description').
'</td>';
6379 print
'<td class="linecolvat right">'.$langs->trans(
'VATRate').
'</td>';
6380 print
'<td class="linecoluht right">'.$langs->trans(
'PriceUHT').
'</td>';
6382 print
'<td class="linecoluht_currency right">'.$langs->trans(
'PriceUHTCurrency').
'</td>';
6384 print
'<td class="linecolqty right">'.$langs->trans(
'Qty').
'</td>';
6386 print
'<td class="linecoluseunit left">'.$langs->trans(
'Unit').
'</td>';
6388 print
'<td class="linecoldiscount right">'.$langs->trans(
'ReductionShort').
'</td>';
6389 print
'<td class="linecolht right">'.$langs->trans(
'TotalHT').
'</td>';
6390 print
'<td class="center">';
6391 print $form->showCheckAddButtons(
'checkforselect', 1);
6396 if (!empty($this->lines)) {
6397 foreach ($this->lines as $line) {
6400 if (is_object($hookmanager)) {
6401 $parameters = array(
'line' => $line,
'i' => $i,
'restrictlist' => $restrictlist,
'selectedLines' => $selectedLines);
6402 if (!empty($line->fk_parent_line)) {
6403 $parameters[
'fk_parent_line'] = $line->fk_parent_line;
6405 $reshook = $hookmanager->executeHooks(
'printOriginObjectLine', $parameters, $this, $action);
6407 if (empty($reshook)) {
6408 $this->printOriginLine($line,
'', $restrictlist,
'/core/tpl', $selectedLines);
6429 public function printOriginLine($line, $var, $restrictlist =
'', $defaulttpldir =
'/core/tpl', $selectedLines = array())
6431 global $langs,
$conf;
6434 if (!empty($line->date_start)) {
6439 if ($line->date_debut_reel) {
6443 if (!empty($line->date_end)) {
6445 $date_end = $line->date_end;
6447 $date_end = $line->date_fin_prevue;
6448 if ($line->date_fin_reel) {
6449 $date_end = $line->date_fin_reel;
6454 $this->tpl[
'id'] = $line->id;
6456 $this->tpl[
'label'] =
'';
6457 if (!empty($line->fk_parent_line)) {
6458 $this->tpl[
'label'] .= img_picto(
'',
'rightarrow.png');
6461 if (((
int) $line->info_bits & 2) == 2) {
6463 if (property_exists($this,
'socid')) {
6465 $discount->fk_soc = $this->socid;
6467 $discount->socid = $this->socid;
6469 $this->tpl[
'label'] .= $discount->getNomUrl(0,
'discount');
6470 } elseif (!empty($line->fk_product)) {
6471 $productstatic =
new Product($this->db);
6472 $productstatic->id = $line->fk_product;
6473 $productstatic->ref = (string) $line->ref;
6474 $productstatic->type = $line->fk_product_type;
6475 if (empty($productstatic->ref)) {
6476 $line->fetch_product();
6477 $productstatic = $line->product;
6480 $this->tpl[
'label'] .= $productstatic->getNomUrl(1);
6482 $this->tpl[
'label'] .=
' - '.(!empty($line->label) ? $line->label : $line->product_label);
6484 if ($line->product_type == 1 && (
$date_start || $date_end)) {
6488 $this->tpl[
'label'] .= ($line->product_type == -1 ?
' ' : ($line->product_type == 1 ? img_object($langs->trans(
'Service'),
'service',
'class="pictofixedwidth"') : img_object($langs->trans(
'Product'),
'product',
'class="pictofixedwidth"')));
6489 if (!empty($line->desc)) {
6490 $this->tpl[
'label'] .= $line->desc;
6493 $this->tpl[
'label'] .= ($line->label ?
' '.$line->label :
'');
6497 if ($line->product_type == 1 && (
$date_start || $date_end)) {
6502 if (!empty($line->desc)) {
6503 '@phan-var-force OrderLine|FactureLigne|ContratLigne|FactureFournisseurLigneRec|SupplierInvoiceLine|SupplierProposalLine $line';
6504 if ($line->desc ==
'(CREDIT_NOTE)') {
6506 $discount->fetch($line->fk_remise_except);
6507 $this->tpl[
'description'] = $langs->transnoentities(
"DiscountFromCreditNote", $discount->getNomUrl(0));
6508 } elseif ($line->desc ==
'(DEPOSIT)') {
6510 $discount->fetch($line->fk_remise_except);
6511 $this->tpl[
'description'] = $langs->transnoentities(
"DiscountFromDeposit", $discount->getNomUrl(0));
6512 } elseif ($line->desc ==
'(EXCESS RECEIVED)') {
6514 $discount->fetch($line->fk_remise_except);
6515 $this->tpl[
'description'] = $langs->transnoentities(
"DiscountFromExcessReceived", $discount->getNomUrl(0));
6516 } elseif ($line->desc ==
'(EXCESS PAID)') {
6518 $discount->fetch($line->fk_remise_except);
6519 $this->tpl[
'description'] = $langs->transnoentities(
"DiscountFromExcessPaid", $discount->getNomUrl(0));
6521 $this->tpl[
'description'] =
dol_trunc($line->desc, 60);
6524 $this->tpl[
'description'] =
' ';
6528 $this->tpl[
'vat_rate'] =
vatrate($line->tva_tx,
true);
6529 $this->tpl[
'vat_rate'] .= (((int) $line->info_bits & 1) == 1) ?
'*' :
'';
6530 if (!empty($line->vat_src_code) && !preg_match(
'/\(/', $this->tpl[
'vat_rate'])) {
6531 $this->tpl[
'vat_rate'] .=
' ('.$line->vat_src_code.
')';
6534 $this->tpl[
'price'] =
price($line->subprice);
6535 $this->tpl[
'total_ht'] =
price($line->total_ht);
6536 $this->tpl[
'multicurrency_price'] =
price($line->multicurrency_subprice);
6537 $this->tpl[
'qty'] = (((int) $line->info_bits & 2) != 2) ? $line->qty :
' ';
6539 $this->tpl[
'unit'] = $line->getLabelOfUnit(
'long', $langs);
6540 $this->tpl[
'unit_short'] = $line->getLabelOfUnit(
'short', $langs);
6543 $this->tpl[
'remise_percent'] = (((int) $line->info_bits & 2) != 2) ?
vatrate((
string) $line->remise_percent,
true) :
' ';
6546 $this->tpl[
'strike'] = 0;
6548 $this->tpl[
'strike'] = 1;
6549 } elseif (defined(
'SUBTOTALS_SPECIAL_CODE') && $line->special_code == SUBTOTALS_SPECIAL_CODE) {
6554 $this->tpl[
'strike'] = 1;
6559 $dirtpls = array_merge(
$conf->modules_parts[
'tpl'], array($defaulttpldir));
6560 foreach ($dirtpls as
$module => $reldir) {
6564 $tpl = DOL_DOCUMENT_ROOT.$reldir.
'/originproductline.tpl.php';
6567 if (empty(
$conf->file->strict_mode)) {
6568 $res = @include $tpl;
6570 $res = include $tpl;
6597 $sql =
"INSERT INTO ".$this->db->prefix().
"element_resources (";
6598 $sql .=
"resource_id";
6599 $sql .=
", resource_type";
6600 $sql .=
", element_id";
6601 $sql .=
", element_type";
6603 $sql .=
", mandatory";
6604 $sql .=
") VALUES (";
6605 $sql .= ((int) $resource_id);
6606 $sql .=
", '".$this->db->escape($resource_type).
"'";
6607 $sql .=
", '".$this->db->escape((
string) $this->
id).
"'";
6608 $sql .=
", '".$this->db->escape($this->element).
"'";
6609 $sql .=
", '".$this->db->escape((
string) $busy).
"'";
6610 $sql .=
", '".$this->db->escape((
string) $mandatory).
"'";
6613 dol_syslog(get_class($this).
"::add_element_resource", LOG_DEBUG);
6614 if ($this->db->query($sql)) {
6616 $result = $this->call_trigger(strtoupper($this->TRIGGER_PREFIX).
'_ADD_RESOURCE', $user);
6618 $this->db->rollback();
6622 $this->db->commit();
6625 $this->error = $this->db->lasterror();
6626 $this->db->rollback();
6647 $sql =
"DELETE FROM ".$this->db->prefix().
"element_resources";
6648 $sql .=
" WHERE rowid = ".((int) $rowid);
6650 dol_syslog(get_class($this).
"::delete_resource", LOG_DEBUG);
6652 $resql = $this->db->query($sql);
6654 $this->error = $this->db->lasterror();
6655 $this->db->rollback();
6659 $result = $this->call_trigger(strtoupper($this->TRIGGER_PREFIX).
'_DELETE_RESOURCE', $user);
6661 $this->db->rollback();
6665 $this->db->commit();
6679 if (isset($this->lines) && is_array($this->lines)) {
6680 $nboflines = count($this->lines);
6681 for ($i = 0; $i < $nboflines; $i++) {
6682 if (is_object($this->lines[$i])) {
6683 $this->lines[$i] = clone $this->lines[$i];
6702 protected function commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams =
null)
6704 global
$conf, $langs, $hookmanager, $action;
6706 $srctemplatepath =
'';
6708 $parameters = array(
'modelspath' => $modelspath,
'modele' => $modele,
'outputlangs' => $outputlangs,
'hidedetails' => $hidedetails,
'hidedesc' => $hidedesc,
'hideref' => $hideref,
'moreparams' => $moreparams);
6709 $reshook = $hookmanager->executeHooks(
'commonGenerateDocument', $parameters, $this, $action);
6711 if (!empty($reshook)) {
6715 dol_syslog(
"commonGenerateDocument modele=".$modele.
" outputlangs->defaultlang=".(is_object($outputlangs) ? $outputlangs->defaultlang :
'null'));
6717 if (empty($modele)) {
6718 $this->error =
'BadValueForParameterModele';
6723 $err = error_reporting();
6725 @set_time_limit(120);
6726 error_reporting($err);
6729 $tmp = explode(
':', $modele, 2);
6730 $saved_model = $modele;
6731 if (!empty($tmp[1])) {
6733 $srctemplatepath = $tmp[1];
6735 if (!preg_match(
'/^'.preg_quote(DOL_DATA_ROOT,
'/').
'\/(ecm|doctemplates)/', $srctemplatepath)) {
6736 $this->error =
'BadDirForTemplateFile';
6745 $dirmodels = array(
'/');
6746 if (is_array(
$conf->modules_parts[
'models'])) {
6747 $dirmodels = array_merge($dirmodels,
$conf->modules_parts[
'models']);
6749 foreach ($dirmodels as $reldir) {
6750 foreach (array(
'doc',
'pdf') as $prefix) {
6751 if (in_array(get_class($this), array(
'Adherent'))) {
6753 $file = $prefix.
"_".$modele.
".class.php";
6756 $file = $prefix.
"_".$modele.
".modules.php";
6763 if (file_exists($file)) {
6765 $classname = $prefix.
'_'.$modele;
6774 if ($filefound ===
'' || $classname ===
'') {
6775 $this->error = $langs->trans(
"Error").
' Failed to load doc generator with modelpaths='.$modelspath.
' - modele='.$modele;
6776 $this->errors[] = $this->error;
6787 require_once $filefound;
6789 $obj =
new $classname($this->db);
6801 '@phan-var-force ModelePDFMember $obj';
6805 if ($obj->type ==
'odt' && empty($srctemplatepath)) {
6806 $varfortemplatedir = $obj->scandir;
6810 $listoffiles = array();
6813 $listofdir = explode(
',', $dirtoscan);
6814 foreach ($listofdir as $key => $tmpdir) {
6815 $tmpdir = trim($tmpdir);
6816 $tmpdir = preg_replace(
'/DOL_DATA_ROOT/', DOL_DATA_ROOT, $tmpdir);
6818 unset($listofdir[$key]);
6821 if (is_dir($tmpdir)) {
6822 $tmpfiles =
dol_dir_list($tmpdir,
'files', 0,
'\.od(s|t)$',
'',
'name', SORT_ASC, 0);
6823 if (count($tmpfiles)) {
6824 $listoffiles = array_merge($listoffiles, $tmpfiles);
6829 if (count($listoffiles)) {
6830 foreach ($listoffiles as $record) {
6831 $srctemplatepath = $record[
'fullname'];
6837 if (empty($srctemplatepath)) {
6838 $this->error =
'ErrorGenerationAskedForOdtTemplateWithSrcFileNotDefined';
6843 if ($obj->type ==
'odt' && !empty($srctemplatepath)) {
6845 dol_syslog(
"Failed to locate template file ".$srctemplatepath, LOG_WARNING);
6846 $this->error =
'ErrorGenerationAskedForOdtTemplateWithSrcFileNotFound';
6853 $sav_charset_output = empty($outputlangs->charset_output) ?
'' : $outputlangs->charset_output;
6856 $this->model_pdf = $saved_model;
6861 $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath,
'member', 1,
'tmp_cards');
6863 $resultwritefile = -1;
6864 dol_syslog(
"Error generating document - Provided ".get_class($this).
" to ".get_class($obj).
"::write_file()", LOG_ERR);
6868 if ($this instanceof
Don) {
6869 $resultwritefile = $obj->write_file($this, $outputlangs );
6871 $resultwritefile = -1;
6872 dol_syslog(
"Error generating document - Provided ".get_class($this).
" to Don::write_file()", LOG_ERR);
6876 '@phan-var-force ModeleBarCode|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';
6877 $this->context[
'moreparams'] = $moreparams;
6878 $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, $hidedetails, $hidedesc, $hideref);
6880 }
catch (\Throwable $e) {
6881 $resultwritefile = -1;
6882 $this->error = $e->getMessage();
6883 dol_syslog(
"Exception in write_file() for ".get_class($this).
": ".$e->getMessage(), LOG_ERR);
6888 if ($resultwritefile > 0) {
6889 $outputlangs->charset_output = $sav_charset_output;
6892 require_once DOL_DOCUMENT_ROOT.
'/core/lib/files.lib.php';
6896 if (!empty($obj->result[
'fullpath'])) {
6897 $destfull = $obj->result[
'fullpath'];
6900 $update_main_doc_field = 0;
6901 if (!empty($obj->update_main_doc_field)) {
6902 $update_main_doc_field = 1;
6908 $this->indexFile($destfull, $update_main_doc_field);
6911 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);
6917 $this->warnings = $obj->warnings;
6921 $outputlangs->charset_output = $sav_charset_output;
6922 if (empty($this->error)) {
6923 $this->error = $obj->error;
6925 if (empty($this->errors)) {
6926 $this->errors = $obj->errors;
6928 $this->warnings = $obj->warnings;
6929 dol_syslog(
"Error generating document for ".__CLASS__.
". Error: ".$this->error, LOG_ERR);
6943 public function indexFile($destfull, $update_main_doc_field)
6945 global
$conf, $user;
6947 $upload_dir = dirname($destfull);
6948 $destfile = basename($destfull);
6949 $rel_dir = preg_replace(
'/^'.preg_quote(DOL_DATA_ROOT,
'/').
'/',
'', $upload_dir);
6951 if (!preg_match(
'/[\\/]temp[\\/]|[\\/]thumbs|\.meta$/', $rel_dir)) {
6952 $filename = basename($destfile);
6953 $rel_dir = preg_replace(
'/[\\/]$/',
'', $rel_dir);
6954 $rel_dir = preg_replace(
'/^[\\/]/',
'', $rel_dir);
6956 include_once DOL_DOCUMENT_ROOT.
'/ecm/class/ecmfiles.class.php';
6957 $ecmfile =
new EcmFiles($this->db);
6958 $result = $ecmfile->fetch(0,
'', ($rel_dir ? $rel_dir.
'/' :
'').$filename);
6961 $setsharekey =
false;
6963 !empty($this->TRIGGER_PREFIX)
6966 $setsharekey =
true;
6969 if ($this->element ==
'propal' || $this->element ==
'proposal') {
6971 $setsharekey =
true;
6974 $setsharekey =
true;
6977 if ($this->element ==
'facture' &&
getDolGlobalInt(
"INVOICE_ALLOW_EXTERNAL_DOWNLOAD")) {
6978 $setsharekey =
true;
6980 if ($this->element ==
'bank_account' &&
getDolGlobalInt(
"BANK_ACCOUNT_ALLOW_EXTERNAL_DOWNLOAD")) {
6981 $setsharekey =
true;
6983 if ($this->element ==
'contrat' &&
getDolGlobalInt(
"CONTRACT_ALLOW_EXTERNAL_DOWNLOAD")) {
6984 $setsharekey =
true;
6986 if ($this->element ==
'supplier_proposal' &&
getDolGlobalInt(
"SUPPLIER_PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD")) {
6987 $setsharekey =
true;
6989 if ($this->element ==
'order_supplier' &&
getDolGlobalInt(
"SUPPLIER_ORDER_ALLOW_EXTERNAL_DOWNLOAD")) {
6990 $setsharekey =
true;
6992 if ($this->element ==
'invoice_supplier' &&
getDolGlobalInt(
"SUPPLIER_INVOICE_ALLOW_EXTERNAL_DOWNLOAD")) {
6993 $setsharekey =
true;
6995 if ($this->element ==
'societe_rib' &&
getDolGlobalInt(
"SOCIETE_RIB_ALLOW_ONLINESIGN")) {
6996 $setsharekey =
true;
7000 if (empty($ecmfile->share)) {
7001 require_once DOL_DOCUMENT_ROOT.
'/core/lib/security2.lib.php';
7008 $ecmfile->fullpath_orig =
'';
7009 $ecmfile->gen_or_uploaded =
'generated';
7010 $ecmfile->description =
'';
7011 $ecmfile->keywords =
'';
7012 $ecmfile->src_object_type = $this->table_element;
7014 $result = $ecmfile->update($user);
7016 setEventMessages($ecmfile->error, $ecmfile->errors,
'warnings');
7020 $ecmfile->entity =
$conf->entity;
7021 $ecmfile->filepath = $rel_dir;
7022 $ecmfile->filename = $filename;
7024 $ecmfile->fullpath_orig =
'';
7025 $ecmfile->gen_or_uploaded =
'generated';
7026 $ecmfile->description =
'';
7027 $ecmfile->keywords =
'';
7028 $ecmfile->src_object_type = $this->table_element;
7031 $result = $ecmfile->create($user);
7033 setEventMessages($ecmfile->error, $ecmfile->errors,
'warnings');
7043 if ($update_main_doc_field && !empty($this->table_element)) {
7044 $sql =
"UPDATE ".$this->db->prefix().$this->table_element.
" SET last_main_doc = '".$this->db->escape($ecmfile->filepath.
"/".$ecmfile->filename).
"'";
7045 $sql .=
" WHERE rowid = ".((int) $this->
id);
7047 $resql = $this->db->query($sql);
7049 dol_print_error($this->db);
7052 $this->last_main_doc = $ecmfile->filepath.
'/'.$ecmfile->filename;
7072 if (file_exists($file_osencoded)) {
7073 require_once DOL_DOCUMENT_ROOT.
'/core/lib/images.lib.php';
7076 $maxwidthsmall = $tmparraysize[
'maxwidthsmall'];
7077 $maxheightsmall = $tmparraysize[
'maxheightsmall'];
7078 $maxwidthmini = $tmparraysize[
'maxwidthmini'];
7079 $maxheightmini = $tmparraysize[
'maxheightmini'];
7084 vignette($file_osencoded, $maxwidthsmall, $maxheightsmall,
'_small', $quality);
7088 vignette($file_osencoded, $maxwidthmini, $maxheightmini,
'_mini', $quality);
7136 return GETPOST($fieldname, $type, 3);
7139 if (isset($alternatevalue)) {
7140 return $alternatevalue;
7143 $newelement = $this->element;
7144 if ($newelement ==
'facture') {
7145 $newelement =
'invoice';
7147 if ($newelement ==
'commande') {
7148 $newelement =
'order';
7150 if (empty($newelement)) {
7151 dol_syslog(
"Ask a default value using common method getDefaultCreateValueForField on an object with no property ->element defined. Return empty string.", LOG_WARNING);
7155 $keyforfieldname = strtoupper($newelement.
'_DEFAULT_'.$fieldname);
7182 if (!$this->element) {
7185 if (!($this->
id > 0)) {
7188 if (is_array($this->array_languages)) {
7192 $this->array_languages = array();
7194 $element = $this->element;
7195 if ($element ==
'categorie') {
7196 $element =
'categories';
7200 $sql =
"SELECT rowid, property, lang , value";
7201 $sql .=
" FROM ".$this->db->prefix().
"object_lang";
7202 $sql .=
" WHERE type_object = '".$this->db->escape($element).
"'";
7203 $sql .=
" AND fk_object = ".((int) $this->
id);
7205 $resql = $this->db->query($sql);
7207 $numrows = $this->db->num_rows($resql);
7210 while ($i < $numrows) {
7211 $obj = $this->db->fetch_object($resql);
7212 $key = $obj->property;
7213 $value = $obj->value;
7214 $codelang = $obj->lang;
7215 $type = $this->fields[$key][
'type'];
7218 if (preg_match(
'/date/', $type)) {
7219 $this->array_languages[$key][$codelang] = $this->db->jdate($value);
7221 $this->array_languages[$key][$codelang] = $value;
7228 $this->db->free($resql);
7236 dol_print_error($this->db);
7251 foreach ($_POST as $postfieldkey => $postfieldvalue) {
7252 $tmparray = explode(
'-', $postfieldkey);
7253 if ($tmparray[0] !=
'field') {
7257 $element = $tmparray[1];
7258 $key = $tmparray[2];
7259 $codelang = $tmparray[3];
7262 if (!empty($onlykey) && $key != $onlykey) {
7265 if ($element != $this->element) {
7269 $key_type = $this->fields[$key][
'type'];
7272 if (isset($this->fields[$key][
'enabled'])) {
7273 $enabled = (int)
dol_eval((
string) $this->fields[$key][
'enabled'], 1, 1,
'1');
7280 if (empty($enabled)) {
7285 if (in_array($key_type, array(
'date'))) {
7289 } elseif (in_array($key_type, array(
'datetime'))) {
7293 } elseif (in_array($key_type, array(
'checkbox',
'chkbxlst'))) {
7294 $value_arr =
GETPOST($postfieldkey,
'array');
7295 if (!empty($value_arr)) {
7296 $value_key = implode(
',', $value_arr);
7300 } elseif (in_array($key_type, array(
'price',
'double'))) {
7301 $value_arr =
GETPOST($postfieldkey,
'alpha');
7304 $value_key =
GETPOST($postfieldkey);
7305 if (in_array($key_type, array(
'link')) && $value_key ==
'-1') {
7310 $this->array_languages[$key][$codelang] = $value_key;
7335 $savDisableCompute =
$conf->disable_compute;
7336 $conf->disable_compute = 1;
7338 $ret = $this->fetch(
$id);
7340 $conf->disable_compute = $savDisableCompute;
7358 global
$conf, $extrafields;
7360 if (empty($rowid)) {
7363 if (empty($rowid) && isset($this->rowid)) {
7364 $rowid = $this->rowid;
7368 if (!$this->table_element) {
7371 $this->array_options = array();
7373 if (!is_array($optionsArray)) {
7375 if (!isset($extrafields) || !is_object($extrafields)) {
7376 require_once DOL_DOCUMENT_ROOT.
'/core/class/extrafields.class.php';
7381 if (empty($extrafields->attributes[$this->table_element][
'loaded'])) {
7382 $extrafields->fetch_name_optionals_label($this->table_element);
7384 $optionsArray = (!empty($extrafields->attributes[$this->table_element][
'label']) ? $extrafields->attributes[$this->table_element][
'label'] :
null);
7386 global $extrafields;
7387 dol_syslog(
"Warning: fetch_optionals was called with param optionsArray defined when you should pass null now", LOG_WARNING);
7390 $table_element = $this->table_element;
7391 if ($table_element ==
'categorie') {
7392 $table_element =
'categories';
7396 if (is_array($optionsArray) && count($optionsArray) > 0) {
7397 $sql =
"SELECT rowid";
7398 foreach ($optionsArray as $name => $label) {
7399 if (empty($extrafields->attributes[$this->table_element][
'type'][$name]) || (!in_array($extrafields->attributes[$this->table_element][
'type'][$name], [
'separate',
'point',
'multipts',
'linestrg',
'polygon']))) {
7400 $sql .=
", ".$this->db->sanitize($name);
7403 if (!empty($extrafields->attributes[$this->table_element][
'type'][$name]) && in_array($extrafields->attributes[$this->table_element][
'type'][$name], array(
'point',
'multipts',
'linestrg',
'polygon'))) {
7405 $sql .=
", ST_AsWKT(".$this->db->sanitize($name).
") as ".$this->db->sanitize($name);
7408 $sql .=
" FROM ".$this->db->prefix().$table_element.
"_extrafields";
7409 $sql .=
" WHERE fk_object = ".((int) $rowid);
7412 $resql = $this->db->query($sql);
7414 $numrows = $this->db->num_rows($resql);
7416 $tab = $this->db->fetch_array($resql);
7417 foreach ($tab as $key => $value) {
7419 if ($key !=
'rowid' && $key !=
'tms' && $key !=
'fk_member' && !is_int($key)) {
7421 if (!empty($extrafields->attributes[$this->table_element]) && in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'date',
'datetime'))) {
7423 $this->array_options[
"options_".$key] = $this->db->jdate($value);
7425 $this->array_options[
"options_".$key] = $value;
7430 if (!empty($extrafields->attributes[$this->table_element][
'type'][$key]) && $extrafields->attributes[$this->table_element][
'type'][$key] ==
'password') {
7431 if (!empty($value) && preg_match(
'/^dolcrypt:/', $value)) {
7432 $this->array_options[
"options_".$key] =
dolDecrypt($value);
7441 if (is_array($extrafields->attributes[$this->table_element][
'label'])) {
7442 foreach ($extrafields->attributes[$this->table_element][
'label'] as $key => $val) {
7443 $this->array_options[
'options_' . $key] =
null;
7450 if (is_array($extrafields->attributes[$this->table_element][
'label'])) {
7451 foreach ($extrafields->attributes[$this->table_element][
'label'] as $key => $val) {
7452 if (!empty($extrafields->attributes[$this->table_element]) && !empty($extrafields->attributes[$this->table_element][
'computed'][$key])) {
7454 if (empty(
$conf->disable_compute)) {
7456 global $objectoffield;
7458 $this->array_options[
'options_' . $key] =
dol_eval((
string) $extrafields->attributes[$this->table_element][
'computed'][$key], 1, 0,
'2');
7464 $this->db->free($resql);
7472 $this->errors[] = $this->db->lasterror();
7493 $table_element = $this->table_element;
7494 if ($table_element ==
'categorie') {
7495 $table_element =
'categories';
7498 dol_syslog(get_class($this).
"::deleteExtraFields delete", LOG_DEBUG);
7500 $sql_del =
"DELETE FROM ".$this->db->prefix().$table_element.
"_extrafields WHERE fk_object = ".((int) $this->
id);
7502 $resql = $this->db->query($sql_del);
7504 $this->error = $this->db->lasterror();
7505 $this->db->rollback();
7508 $this->db->commit();
7525 global $langs, $extrafields, $user;
7527 if (
getDolGlobalString(
'MAIN_EXTRAFIELDS_DISABLED') || empty($this->array_options)) {
7531 if (empty($userused)) {
7538 $langs->load(
'admin');
7539 if (!isset($extrafields) || !is_object($extrafields)) {
7540 require_once DOL_DOCUMENT_ROOT.
'/core/class/extrafields.class.php';
7543 $target_extrafields = $extrafields->fetch_name_optionals_label($this->table_element);
7546 $new_array_options = array();
7547 foreach ($this->array_options as $key => $value) {
7548 if (in_array(substr($key, 8), array_keys($target_extrafields))) {
7549 $new_array_options[$key] = $value;
7550 } elseif (in_array($key, array_keys($target_extrafields))) {
7551 $new_array_options[
'options_'.$key] = $value;
7555 foreach ($new_array_options as $key => $value) {
7556 $attributeKey = substr($key, 8);
7557 $attributeType = $extrafields->attributes[$this->table_element][
'type'][$attributeKey];
7558 $attributeLabel = $langs->transnoentities($extrafields->attributes[$this->table_element][
'label'][$attributeKey]);
7559 $attributeParam = $extrafields->attributes[$this->table_element][
'param'][$attributeKey];
7560 $attributeRequired = $extrafields->attributes[$this->table_element][
'required'][$attributeKey];
7561 $attributeUnique = $extrafields->attributes[$this->table_element][
'unique'][$attributeKey];
7562 $attrfieldcomputed = $extrafields->attributes[$this->table_element][
'computed'][$attributeKey];
7563 $attributeEmptyOnClone = $extrafields->attributes[$this->table_element][
'emptyonclone'][$attributeKey];
7575 if (!empty($this->context[
'createfromclone']) && $this->context[
'createfromclone'] ==
'createfromclone' && (!empty($attributeUnique) || !empty($attributeEmptyOnClone))) {
7576 $new_array_options[$key] =
null;
7582 if (!empty($this->context[
'createproductcombination']) && $this->context[
'createproductcombination'] ==
'createproductcombination' && !empty($attributeUnique)) {
7583 $new_array_options[$key] =
null;
7588 if ($attributeRequired) {
7589 $v = $this->array_options[$key];
7591 $langs->load(
"errors");
7592 dol_syslog(
"Mandatory field '".$key.
"' is empty during create and set to required into definition of extrafields");
7593 $this->errors[] = $langs->trans(
'ErrorFieldRequired', $attributeLabel);
7598 if (!empty($attrfieldcomputed)) {
7600 global $objectoffield;
7601 $objectoffield = $this;
7602 $value =
dol_eval((
string) $attrfieldcomputed, 1, 0,
'2');
7603 dol_syslog($langs->trans(
"Extrafieldcomputed").
" on ".$attributeLabel.
"(".$value.
")", LOG_DEBUG);
7604 $new_array_options[$key] = $value;
7606 $new_array_options[$key] =
null;
7611 switch ($attributeType) {
7615 if (!is_numeric($value) && $value !=
'') {
7616 $this->errors[] = $langs->trans(
"ExtraFieldHasWrongValue", $attributeLabel);
7618 } elseif ($value ===
'') {
7619 $new_array_options[$key] =
null;
7623 if ($value ===
'' || $value ===
false || $value ===
null) {
7624 $new_array_options[$key] =
null;
7630 if (!is_numeric($value) && $value !=
'') {
7631 dol_syslog($langs->trans(
"ExtraFieldHasWrongValue").
" for ".$attributeLabel.
"(".$value.
"is not '".$attributeType.
"')", LOG_DEBUG);
7632 $this->errors[] = $langs->trans(
"ExtraFieldHasWrongValue", $attributeLabel);
7634 } elseif ($value ==
'') {
7638 $new_array_options[$key] = $value;
7648 if ($this->array_options[$key] !=
'' && is_array($extrafields->attributes[$this->table_element][
'param'][$attributeKey][
'options'])) {
7650 $tmparrays = array_keys($extrafields->attributes[$this->table_element][
'param'][$attributeKey][
'options']);
7651 $algo = reset($tmparrays);
7656 if (is_object($this->oldcopy)) {
7658 if (isset($this->oldcopy->array_options[$key]) && $this->array_options[$key] == $this->oldcopy->array_options[$key]) {
7660 if ($algo ==
'dolcrypt') {
7661 if (!preg_match(
'/^dolcrypt:/', $this->array_options[$key])) {
7662 $new_array_options[$key] =
dolEncrypt($this->array_options[$key]);
7664 $new_array_options[$key] = $this->array_options[$key];
7667 $new_array_options[$key] = $this->array_options[$key];
7671 if ($algo ==
'dolcrypt') {
7672 if (!preg_match(
'/^dolcrypt:/', $this->array_options[$key])) {
7673 $new_array_options[$key] =
dolEncrypt($this->array_options[$key]);
7675 $new_array_options[$key] = $this->array_options[$key];
7678 $new_array_options[$key] =
dol_hash($this->array_options[$key], $algo);
7684 if ($algo ==
'dolcrypt' && !preg_match(
'/^dolcrypt:/', $this->array_options[$key])) {
7685 $new_array_options[$key] =
dolEncrypt($this->array_options[$key]);
7687 $new_array_options[$key] = $this->array_options[$key];
7692 $new_array_options[$key] = $this->array_options[$key];
7695 $new_array_options[$key] = $this->array_options[$key];
7701 if (!is_numeric($this->array_options[$key]) || $this->array_options[$key] != intval($this->array_options[$key])) {
7702 $this->array_options[$key] = strtotime($this->array_options[$key]);
7704 $new_array_options[$key] = $this->db->idate($this->array_options[$key]);
7708 if (!is_numeric($this->array_options[$key]) || $this->array_options[$key] != intval($this->array_options[$key])) {
7709 $this->array_options[$key] = strtotime($this->array_options[$key]);
7711 $new_array_options[$key] = $this->db->idate($this->array_options[$key],
'gmt');
7714 $param_list = array_keys($attributeParam[
'options']);
7717 $InfoFieldList = explode(
":", $param_list[0]);
7719 if ($InfoFieldList[0] && class_exists($InfoFieldList[0])) {
7720 if ($value ==
'-1') {
7721 $new_array_options[$key] =
'';
7723 $object =
new $InfoFieldList[0]($this->db);
7724 '@phan-var-force CommonObject $object';
7728 $sqlFetchObject =
"SELECT rowid FROM ".$this->db->prefix().$object->table_element;
7729 if (is_numeric($value)) {
7730 $sqlFetchObject .=
" WHERE rowid = " . (int) $value;
7732 $sqlFetchObject .=
" WHERE ref = '" . $this->db->escape($value) .
"'";
7735 $obj = $this->db->getRow($sqlFetchObject);
7741 if (is_object($obj)) {
7742 $objectId = $obj->rowid;
7749 $new_array_options[$key] = $objectId;
7751 $this->error =
"Id/Ref '".$value.
"' for object '".
$object->element.
"' not found";
7756 dol_syslog(
'Error bad setup of extrafield', LOG_WARNING);
7761 if (is_array($this->array_options[$key])) {
7762 $new_array_options[$key] = implode(
',', $this->array_options[$key]);
7764 $new_array_options[$key] = $this->array_options[$key];
7771 $sqlColumnValues = [
'fk_object' => (int) $this->
id];
7773 foreach ($new_array_options as $key => $newValue) {
7774 $attributeKey = substr($key, 8);
7775 $attributeType = $extrafields->attributes[$this->table_element][
'type'][$attributeKey];
7776 if ($attributeType ===
'separate') {
7780 $geoDataType = ExtraFields::$geoDataTypes[$attributeType] ??
null;
7782 if (! $geoDataType) {
7784 if ($newValue !=
'') {
7785 $sqlColumnValues[$attributeKey] =
"'".$this->db->escape($newValue).
"'";
7787 $sqlColumnValues[$attributeKey] =
'null';
7791 if (empty($newValue)) {
7792 $sqlColumnValues[$attributeKey] =
'null';
7795 if (preg_match(
'/error/i', $newValue)) {
7796 dol_syslog(
'Bad syntax string for '.$geoDataType[
'shortname'].
' '.$newValue.
' to generate SQL request', LOG_WARNING);
7797 $sqlColumnValues[$attributeKey] =
'null';
7806 $sqlColumnValues[$attributeKey] = $geoDataType[
'ST_Function'].
"('".$this->db->escape($newValue).
"')";
7811 $table_element = $this->table_element;
7812 if ($table_element ==
'categorie') {
7813 $table_element =
'categories';
7815 $extrafieldsTable = $this->db->prefix() . $table_element .
'_extrafields';
7817 dol_syslog(get_class($this).
"::insertExtraFields update or insert record line", LOG_DEBUG);
7819 $linealreadyfound = 0;
7820 $sql =
"SELECT COUNT(rowid) as nb FROM ".$this->db->prefix().$table_element.
"_extrafields WHERE fk_object = ".((int) $this->
id);
7821 $resql = $this->db->query($sql);
7823 $tmpobj = $this->db->fetch_object($resql);
7825 $linealreadyfound = $tmpobj->nb;
7830 if ($linealreadyfound) {
7831 array_shift($sqlColumnValues);
7832 if (empty($sqlColumnValues)) {
7838 $this->db->commit();
7841 $sqlColumnValueString = implode(
7847 array_map(
function ($key) use ($sqlColumnValues) {
7848 return "{$key} = {$sqlColumnValues[$key]}";
7849 }, array_keys($sqlColumnValues))
7851 $sql =
"UPDATE {$extrafieldsTable} SET {$sqlColumnValueString} WHERE fk_object = ".((int) $this->
id);
7854 $extrafieldsRequiredOnOtherEntities = $extrafields->attributes[$this->table_element][
'mandatoryfieldsofotherentities'] ?? array();
7855 foreach ($extrafieldsRequiredOnOtherEntities as $key => $extrafieldType) {
7856 if (isset($sqlColumnValues[$key])) {
7861 $sqlColumnValues[$key] =
"''";
7862 if (in_array($extrafieldType, array(
'int',
'double',
'price'))) {
7863 $sqlColumnValues[$key] = 0;
7866 $sqlColumns = implode(
',', array_keys($sqlColumnValues));
7867 $sqlValues = implode(
',', array_values($sqlColumnValues));
7868 $sql =
"INSERT INTO {$extrafieldsTable} ({$sqlColumns}) VALUES ({$sqlValues})";
7871 $resql = $this->db->query($sql);
7873 $this->error = $this->db->lasterror();
7878 if (!$error && !empty($this->fields[
'fk_user_modif'])) {
7879 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
7880 $sql .=
" SET fk_user_modif = ".(int) $userused->id;
7881 $sql .=
" WHERE ".(empty($this->table_rowid) ?
'rowid' : $this->db->sanitize($this->table_rowid)).
" = ".((
int)
$this->id);
7882 $this->db->query($sql);
7885 if (!$error && $trigger) {
7887 $this->context = array(
'extrafieldaddupdate' => 1);
7888 $result = $this->call_trigger($trigger, $userused);
7896 $this->db->rollback();
7899 $this->db->commit();
7917 global $langs, $user;
7919 if (empty($userused)) {
7929 if (is_array($this->array_languages)) {
7930 $new_array_languages = $this->array_languages;
7932 foreach ($new_array_languages as $key => $value) {
7933 $attributeKey = $key;
7934 $attributeType = $this->fields[$attributeKey][
'type'];
7935 $attributeLabel = $this->fields[$attributeKey][
'label'];
7940 switch ($attributeType) {
7942 if (is_array($value) || (!is_numeric($value) && $value !=
'')) {
7943 $this->errors[] = $langs->trans(
"ExtraLanguageHasWrongValue", $attributeLabel);
7945 } elseif ($value ==
'') {
7946 $new_array_languages[$key] =
null;
7951 if (!is_numeric($value) && $value !=
'') {
7952 dol_syslog($langs->trans(
"ExtraLanguageHasWrongValue").
" on ".$attributeLabel.
"(".$value.
"is not '".$attributeType.
"')", LOG_DEBUG);
7953 $this->errors[] = $langs->trans(
"ExtraLanguageHasWrongValue", $attributeLabel);
7955 } elseif ($value ==
'') {
7956 $new_array_languages[$key] =
null;
7958 $new_array_languages[$key] = $value;
7972 $table_element = $this->table_element;
7973 if ($table_element ==
'categorie') {
7974 $table_element =
'categories';
7977 dol_syslog(get_class($this).
"::insertExtraLanguages delete then insert", LOG_DEBUG);
7979 foreach ($new_array_languages as $key => $langcodearray) {
7980 foreach ($langcodearray as $langcode => $value) {
7981 $sql_del =
"DELETE FROM ".$this->db->prefix().
"object_lang";
7982 $sql_del .=
" WHERE fk_object = ".((int) $this->
id).
" AND property = '".$this->db->escape($key).
"' AND type_object = '".$this->db->escape($table_element).
"'";
7983 $sql_del .=
" AND lang = '".$this->db->escape($langcode).
"'";
7984 $this->db->query($sql_del);
7986 if ($value !==
'') {
7987 $sql =
"INSERT INTO ".$this->db->prefix().
"object_lang (fk_object, property, type_object, lang, value";
7988 $sql .=
") VALUES (".((int) $this->
id).
", '".$this->db->escape($key).
"', '".$this->db->escape($table_element).
"', '".$this->db->escape($langcode).
"', '".$this->db->escape($value).
"'";
7991 $resql = $this->db->query($sql);
7993 $this->error = $this->db->lasterror();
8001 if (!$error && $trigger) {
8003 $this->context = array(
'extralanguagesaddupdate' => 1);
8004 $result = $this->call_trigger($trigger, $userused);
8012 $this->db->rollback();
8015 $this->db->commit();
8035 global $langs, $user, $extrafields, $hookmanager;
8041 if (empty($userused)) {
8047 if (!empty($this->array_options) && isset($this->array_options[
"options_".$key])) {
8049 $langs->load(
'admin');
8050 if (!isset($extrafields) || !is_object($extrafields)) {
8051 require_once DOL_DOCUMENT_ROOT.
'/core/class/extrafields.class.php';
8054 $extrafields->fetch_name_optionals_label($this->table_element);
8055 if (!isset($extrafields->attributes[$this->table_element][
'type'][$key])) {
8059 $value = $this->array_options[
"options_".$key];
8061 $attributeKey = $key;
8062 $attributeType = $extrafields->attributes[$this->table_element][
'type'][$attributeKey];
8063 $attributeLabel = $extrafields->attributes[$this->table_element][
'label'][$attributeKey];
8064 $attributeParam = $extrafields->attributes[$this->table_element][
'param'][$attributeKey];
8065 $attributeRequired = $extrafields->attributes[$this->table_element][
'required'][$attributeKey];
8066 $attributeUnique = $extrafields->attributes[$this->table_element][
'unique'][$attributeKey];
8067 $attrfieldcomputed = $extrafields->attributes[$this->table_element][
'computed'][$attributeKey];
8071 if ($attributeRequired) {
8072 $mandatorypb =
false;
8073 if ($attributeType ==
'link' && $this->array_options[
"options_".$key] ==
'-1') {
8074 $mandatorypb =
true;
8076 if ($this->array_options[
"options_".$key] ===
'') {
8077 $mandatorypb =
true;
8080 $langs->load(
"errors");
8081 dol_syslog(
"Mandatory field 'options_".$key.
"' is empty during update and set to required into definition of extrafields");
8082 $this->errors[] = $langs->trans(
'ErrorFieldRequired', $attributeLabel);
8088 $new_array_options = $this->array_options;
8092 if (!empty($attrfieldcomputed)) {
8094 global $objectoffield;
8095 $objectoffield = $this;
8096 $value =
dol_eval((
string) $attrfieldcomputed, 1, 0,
'2');
8097 dol_syslog($langs->trans(
"Extrafieldcomputed").
" on ".$attributeLabel.
"(".$value.
")", LOG_DEBUG);
8099 $new_array_options[
"options_".$key] = $value;
8101 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
8103 $new_array_options[
"options_".$key] =
null;
8105 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
8109 switch ($attributeType) {
8111 if (!is_numeric($value) && $value !=
'') {
8112 $this->errors[] = $langs->trans(
"ExtraFieldHasWrongValue", $attributeLabel);
8114 } elseif ($value ===
'') {
8115 $new_array_options[
"options_".$key] =
null;
8117 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
8123 if (!is_numeric($value) && $value !=
'') {
8124 dol_syslog($langs->trans(
"ExtraFieldHasWrongValue").
" on ".$attributeLabel.
"(".$value.
"is not '".$attributeType.
"')", LOG_DEBUG);
8125 $this->errors[] = $langs->trans(
"ExtraFieldHasWrongValue", $attributeLabel);
8127 } elseif ($value ===
'') {
8131 $new_array_options[
"options_".$key] = $value;
8133 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
8145 if ($this->array_options[
"options_".$key] !=
'' && is_array($extrafields->attributes[$this->table_element][
'param'][$attributeKey][
'options'])) {
8147 $tmparrays = array_keys($extrafields->attributes[$this->table_element][
'param'][$attributeKey][
'options']);
8148 $algo = reset($tmparrays);
8154 if (is_object($this->oldcopy)) {
8156 if (isset($this->oldcopy->array_options[
"options_".$key]) && $this->array_options[
"options_".$key] == $this->oldcopy->array_options[
"options_".$key]) {
8157 if ($algo ==
'dolcrypt') {
8158 if (!preg_match(
'/^dolcrypt:/', $this->array_options[
"options_".$key])) {
8159 $new_array_options[
"options_".$key] =
dolEncrypt($this->array_options[
"options_".$key]);
8161 $new_array_options[
"options_".$key] = $this->array_options[
"options_".$key];
8164 $new_array_options[
"options_".$key] = $this->array_options[
"options_".$key];
8167 if ($algo ==
'dolcrypt') {
8168 if (!preg_match(
'/^dolcrypt:/', $this->array_options[
"options_".$key])) {
8169 $new_array_options[
"options_".$key] =
dolEncrypt($this->array_options[
"options_".$key]);
8171 $new_array_options[
"options_".$key] = $this->array_options[
"options_".$key];
8174 $new_array_options[
"options_".$key] =
dol_hash($this->array_options[
"options_".$key], $algo);
8178 if ($algo ==
'dolcrypt' && !preg_match(
'/^dolcrypt:/', $this->array_options[
"options_".$key])) {
8179 $new_array_options[
"options_".$key] =
dolEncrypt($this->array_options[
"options_".$key]);
8181 $new_array_options[
"options_".$key] = $this->array_options[
"options_".$key];
8186 $new_array_options[
"options_".$key] = $this->array_options[
"options_".$key];
8189 $new_array_options[
"options_".$key] = $this->array_options[
"options_".$key];
8192 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
8196 if (empty($this->array_options[
"options_".$key])) {
8197 $new_array_options[
"options_".$key] =
null;
8199 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
8201 $new_array_options[
"options_".$key] = $this->db->idate($this->array_options[
"options_".$key]);
8205 if (empty($this->array_options[
"options_".$key])) {
8206 $new_array_options[
"options_".$key] =
null;
8208 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
8210 $new_array_options[
"options_".$key] = $this->db->idate($this->array_options[
"options_".$key],
'gmt');
8214 if (empty($this->array_options[
"options_".$key])) {
8215 $new_array_options[
"options_".$key] =
null;
8217 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
8221 if ($this->array_options[
"options_".$key] ===
'') {
8222 $new_array_options[
"options_".$key] =
null;
8224 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
8258 $new_array_options = array();
8259 if (is_array($this->array_options[
"options_".$key])) {
8260 $new_array_options[
"options_".$key] = implode(
',', $this->array_options[
"options_".$key]);
8262 $new_array_options[
"options_".$key] = $this->array_options[
"options_".$key];
8265 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
8271 $linealreadyfound = 0;
8274 $table_element = $this->table_element;
8275 if ($table_element ==
'categorie') {
8276 $table_element =
'categories';
8279 $sql =
"SELECT COUNT(rowid) as nb FROM ".$this->db->prefix().$table_element.
"_extrafields WHERE fk_object = ".((int) $this->
id);
8280 $resql = $this->db->query($sql);
8282 $tmpobj = $this->db->fetch_object($resql);
8284 $linealreadyfound = $tmpobj->nb;
8289 if ($linealreadyfound) {
8290 $sanitizedGeoDataType = ExtraFields::$geoDataTypes[$attributeType] ??
null;
8291 if ($this->array_options[
"options_".$key] ===
null) {
8292 $sql =
"UPDATE ".$this->db->prefix().$this->db->sanitize($table_element).
"_extrafields";
8293 $sql .=
" SET ".$this->db->sanitize($key).
" = null";
8294 } elseif (!empty($sanitizedGeoDataType[
'ST_Function'])) {
8295 $sql =
"UPDATE ".$this->db->prefix().$this->db->sanitize($table_element).
"_extrafields";
8296 $sql .=
" SET ".$this->db->sanitize($key).
" = ".$this->db->sanitize($sanitizedGeoDataType[
'ST_Function']).
"('".$this->db->escape($this->array_options[
"options_".$key]).
"')";
8299 $sql =
"UPDATE ".$this->db->prefix().$this->db->sanitize($table_element).
"_extrafields";
8300 $sql .=
" SET ".$this->db->sanitize($key).
" = '".$this->db->escape($new_array_options[
"options_".$key]).
"'";
8302 $sql .=
" WHERE fk_object = ".((int) $this->
id);
8304 $resql = $this->db->query($sql);
8307 $this->error = $this->db->lasterror();
8310 $result = $this->insertExtraFields(
'', $user);
8317 if (!$error && !empty($this->fields[
'fk_user_modif'])) {
8318 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
8319 $sql .=
" SET fk_user_modif = ".(int) $userused->id;
8320 $sql .=
" WHERE ".(empty($this->table_rowid) ?
'rowid' : $this->db->sanitize($this->table_rowid)).
" = ".((
int)
$this->id);
8321 $this->db->query($sql);
8325 $parameters = array(
'key' => $key);
8327 $reshook = $hookmanager->executeHooks(
'updateExtraFieldBeforeCommit', $parameters, $this, $action);
8329 setEventMessages($hookmanager->error, $hookmanager->errors,
'errors');
8333 if (!$error && $trigger) {
8335 $this->context = array(
'extrafieldupdate' => 1);
8336 $result = $this->call_trigger($trigger, $userused);
8344 dol_syslog(__METHOD__.$this->error, LOG_ERR);
8345 $this->db->rollback();
8348 $this->db->commit();
8364 return $this->array_options[
'options_'.$key] ??
null;
8376 $this->array_options[
'options_'.$key] = $value;
8393 if (empty($userused)) {
8421 public function showInputField($val, $key, $value, $moreparam =
'', $keysuffix =
'', $keyprefix =
'', $morecss = 0, $nonewbutton = 0)
8423 global
$conf, $langs, $form;
8428 if (!is_object($form)) {
8429 require_once DOL_DOCUMENT_ROOT.
'/core/class/html.form.class.php';
8430 $form =
new Form($this->db);
8433 if (!empty($this->fields)) {
8434 $val = $this->fields[$key];
8438 $fieldValidationErrorMsg =
'';
8439 $validationClass =
'';
8440 $fieldValidationErrorMsg = $this->getFieldError($key);
8441 if (!empty($fieldValidationErrorMsg)) {
8442 $validationClass =
' --error';
8444 $validationClass =
' --success';
8452 $param[
'options'] = array();
8455 $size = !empty($this->fields[$key][
'size']) ? $this->fields[$key][
'size'] : 0;
8457 if (preg_match(
'/^(integer|link):(.*):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
8458 $param[
'options'] = array($reg[2].
':'.$reg[3].
':'.$reg[4].
':'.$reg[5] =>
'N');
8460 } elseif (preg_match(
'/^(integer|link):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
8461 $param[
'options'] = array($reg[2].
':'.$reg[3].
':'.$reg[4] =>
'N');
8463 } elseif (preg_match(
'/^(integer|link):(.*):(.*)/i', $val[
'type'], $reg)) {
8464 $param[
'options'] = array($reg[2].
':'.$reg[3] =>
'N');
8466 } elseif (preg_match(
'/^(sellist):(.*):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
8467 $param[
'options'] = array($reg[2].
':'.$reg[3].
':'.$reg[4].
':'.$reg[5] =>
'N');
8469 } elseif (preg_match(
'/^(sellist):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
8470 $param[
'options'] = array($reg[2].
':'.$reg[3].
':'.$reg[4] =>
'N');
8472 } elseif (preg_match(
'/^(sellist):(.*):(.*)/i', $val[
'type'], $reg)) {
8473 $param[
'options'] = array($reg[2].
':'.$reg[3] =>
'N');
8475 } elseif (preg_match(
'/^chkbxlst:(.*)/i', $val[
'type'], $reg)) {
8476 $param[
'options'] = array($reg[1] =>
'N');
8478 } elseif (preg_match(
'/varchar\((\d+)\)/', $val[
'type'], $reg)) {
8479 $param[
'options'] = array();
8482 } elseif (preg_match(
'/varchar/', $val[
'type'])) {
8483 $param[
'options'] = array();
8485 } elseif (preg_match(
'/stars\((\d+)\)/', $val[
'type'], $reg)) {
8486 $param[
'options'] = array();
8490 $param[
'options'] = array();
8491 $type = $this->fields[$key][
'type'];
8496 if (!empty($this->fields[$key][
'arrayofkeyval']) && is_array($this->fields[$key][
'arrayofkeyval'])) {
8497 $param[
'options'] = $this->fields[$key][
'arrayofkeyval'];
8499 if (empty($this->fields[$key][
'multiinput'])) {
8500 $type = (($this->fields[$key][
'type'] ==
'checkbox') ? $this->fields[$key][
'type'] :
'select');
8504 $label = $this->fields[$key][
'label'];
8507 $default = (!empty($this->fields[$key][
'default']) ? $this->fields[$key][
'default'] :
'');
8509 $computed = (!empty($this->fields[$key][
'computed']) ? $this->fields[$key][
'computed'] :
'');
8511 $unique = (!empty($this->fields[$key][
'unique']) ? $this->fields[$key][
'unique'] : 0);
8513 $required = (!empty($this->fields[$key][
'required']) ? $this->fields[$key][
'required'] : 0);
8515 $autofocusoncreate = (!empty($this->fields[$key][
'autofocusoncreate']) ? $this->fields[$key][
'autofocusoncreate'] : 0);
8517 $placeholder = (!empty($this->fields[$key][
'placeholder']) ? $this->fields[$key][
'placeholder'] : 0);
8520 $langfile = (!empty($this->fields[$key][
'langfile']) ? $this->fields[$key][
'langfile'] :
'');
8522 $list = (!empty($this->fields[$key][
'list']) ? $this->fields[$key][
'list'] : 0);
8523 $hidden = (in_array(abs($this->fields[$key][
'visible']), array(0, 2)) ? 1 : 0);
8528 if (!preg_match(
'/^search_/', $keyprefix)) {
8529 return '<span class="opacitymedium">'.$langs->trans(
"AutomaticallyCalculated").
'</span>';
8536 if (empty($morecss) && !empty($val[
'css'])) {
8537 $morecss = $val[
'css'];
8538 } elseif (empty($morecss)) {
8539 if ($type ==
'date') {
8540 $morecss =
'minwidth100imp';
8541 } elseif ($type ==
'datetime' || $type ==
'link') {
8542 $morecss =
'minwidth200imp';
8543 } elseif (in_array($type, array(
'int',
'integer',
'price')) || preg_match(
'/^double(\([0-9],[0-9]\)){0,1}/', (
string) $type)) {
8544 $morecss =
'maxwidth75';
8545 } elseif ($type ==
'url') {
8546 $morecss =
'minwidth400';
8547 } elseif ($type ==
'boolean') {
8550 if (is_numeric($size) && round((
float) $size) < 12) {
8551 $morecss =
'minwidth100';
8552 } elseif (is_numeric($size) && round((
float) $size) <= 48) {
8553 $morecss =
'minwidth200';
8555 $morecss =
'minwidth400';
8561 if (!empty($validationClass)) {
8562 $morecss .= $validationClass;
8565 if (in_array($type, array(
'date'))) {
8566 $tmp = explode(
',', $size);
8571 if (!$required && $value ==
'') {
8576 $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required,
'', 1, (($keyprefix !=
'search_' && $keyprefix !=
'search_options_') ? 1 : 0), 0, 1);
8577 } elseif (in_array($type, array(
'datetime'))) {
8578 $tmp = explode(
',', $size);
8583 if (!$required && $value ==
'') {
8588 $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required,
'', 1, (($keyprefix !=
'search_' && $keyprefix !=
'search_options_') ? 1 : 0), 0, 1,
'',
'',
'', 1,
'',
'',
'tzuserrel');
8589 } elseif (in_array($type, array(
'duration'))) {
8590 $out = $form->select_duration($keyprefix.$key.$keysuffix, $value, 0,
'text', 0, 1);
8591 } elseif (in_array($type, array(
'int',
'integer'))) {
8592 $tmp = explode(
',', $size);
8594 $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' :
'').
'>';
8595 } elseif (in_array($type, array(
'real'))) {
8596 $out =
'<input type="text" class="flat '.$morecss.
'" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.
dol_escape_htmltag($value).
'"'.($moreparam ? $moreparam :
'').($autofocusoncreate ?
' autofocus' :
'').
'>';
8597 } elseif (preg_match(
'/varchar/', (
string) $type)) {
8598 $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' :
'').
'>';
8599 } elseif ($type ==
'phone' && !preg_match(
'/search_/', $keyprefix)) {
8600 $out = $form->showPhoneInput($value, $keyprefix.$key.$keysuffix, !empty($this->country_id) ? $this->country_id : 0);
8601 } elseif (in_array($type, array(
'email',
'mail',
'url',
'ip'))) {
8602 $out =
'<input type="text" class="flat '.$morecss.
'" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.
dol_escape_htmltag($value).
'" '.($moreparam ? $moreparam :
'').($autofocusoncreate ?
' autofocus' :
'').
'>';
8603 } elseif (preg_match(
'/^text/', (
string) $type)) {
8604 if (!preg_match(
'/search_/', $keyprefix)) {
8605 if (!empty($param[
'options'])) {
8608 $out .= $form->selectarray($keyprefix.$key.$keysuffix.
"_multiinput", $param[
'options'],
'', 1, 0, 0,
"flat maxwidthonphone".$morecss);
8609 $out .=
'<input id="'.$keyprefix.$key.$keysuffix.
'_multiinputadd" type="button" class="button" value="'.$langs->trans(
"Add").
'">';
8612 function handlemultiinputdisabling(htmlname){
8613 console.log("We handle the disabling of used options for "+htmlname+"_multiinput");
8614 multiinput = $("#"+htmlname+"_multiinput");
8615 multiinput.find("option").each(function(){
8616 tmpval = $("#"+htmlname).val();
8617 tmpvalarray = tmpval.split("\n");
8618 valtotest = $(this).val();
8619 if(tmpvalarray.includes(valtotest)){
8620 $(this).prop("disabled",true);
8622 if($(this).prop("disabled") == true){
8623 console.log(valtotest)
8624 $(this).prop("disabled", false);
8630 $(document).ready(function () {
8631 $("#'.$keyprefix.$key.$keysuffix.
'_multiinputadd").on("click",function() {
8632 tmpval = $("#'.$keyprefix.$key.$keysuffix.
'").val();
8633 tmpvalarray = tmpval.split(",");
8634 valtotest = $("#'.$keyprefix.$key.$keysuffix.
'_multiinput").val();
8635 if(valtotest != -1 && !tmpvalarray.includes(valtotest)){
8636 console.log("We add the selected value to the text area '.$keyprefix.$key.$keysuffix.
'");
8640 tmpval = tmpval + "\n" + valtotest;
8642 $("#'.$keyprefix.$key.$keysuffix.
'").val(tmpval);
8643 handlemultiinputdisabling("'.$keyprefix.$key.$keysuffix.
'");
8644 $("#'.$keyprefix.$key.$keysuffix.
'_multiinput").val(-1);
8646 console.log("We add nothing the text area '.$keyprefix.$key.$keysuffix.
'");
8649 $("#'.$keyprefix.$key.$keysuffix.
'").on("change",function(){
8650 handlemultiinputdisabling("'.$keyprefix.$key.$keysuffix.
'");
8652 handlemultiinputdisabling("'.$keyprefix.$key.$keysuffix.
'");
8654 $out .=
"</script>";
8655 $value = str_replace(
',',
"\n", $value);
8657 require_once DOL_DOCUMENT_ROOT.
'/core/class/doleditor.class.php';
8658 $doleditor =
new DolEditor($keyprefix.$key.$keysuffix, $value,
'', 200,
'dolibarr_notes',
'In',
false,
false,
false, ROWS_5,
'90%');
8659 $out .= (string) $doleditor->Create(1,
'',
true,
'',
'',
'', $morecss);
8661 $out =
'<input type="text" class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.
dol_escape_htmltag($value).
'" '.($moreparam ? $moreparam :
'').
'>';
8663 } elseif (preg_match(
'/^html/', (
string) $type)) {
8664 if (!preg_match(
'/search_/', $keyprefix)) {
8665 require_once DOL_DOCUMENT_ROOT.
'/core/class/doleditor.class.php';
8666 $doleditor =
new DolEditor($keyprefix.$key.$keysuffix, $value,
'', 200,
'dolibarr_notes',
'In',
false,
false,
isModEnabled(
'fckeditor') &&
getDolGlobalInt(
'FCKEDITOR_ENABLE_SOCIETE'), ROWS_5,
'90%');
8667 $out = (string) $doleditor->Create(1,
'',
true,
'',
'', $moreparam, $morecss);
8669 $out =
'<input type="text" class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.
dol_escape_htmltag($value).
'" '.($moreparam ? $moreparam :
'').
'>';
8671 } elseif ($type ==
'boolean') {
8673 if (!empty($value)) {
8674 $checked =
' checked value="1" ';
8676 $checked =
' value="1" ';
8678 $out =
'<input type="checkbox" class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" '.$checked.
' '.($moreparam ? $moreparam :
'').
'>';
8679 } elseif ($type ==
'price') {
8680 if (!empty($value)) {
8681 $value =
price($value);
8683 $out =
'<input type="text" class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.$value.
'" '.($moreparam ? $moreparam :
'').
'> <span class="opacitymedium">'.$langs->getCurrencySymbol(
$conf->currency).
'</span>';
8684 } elseif ($type ==
'stars') {
8685 $out =
'<input type="hidden" class="flat '.$morecss.
'" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.
dol_escape_htmltag($value).
'"'.($moreparam ? $moreparam :
'').($autofocusoncreate ?
' autofocus' :
'').
'>';
8686 $out .=
'<div class="star-selection" id="'.$keyprefix.$key.$keysuffix.
'_selection">';
8688 while ($i <= $size) {
8689 $out .=
'<span class="star" data-value="'.$i.
'">'.img_picto(
'',
'fontawesome_star_fas').
'</span>';
8694 jQuery(function($) { /* commonobject.class.php 1 */
8695 let container = $("#'.$keyprefix.$key.$keysuffix.
'_selection");
8696 let selectedStars = parseInt($("#'.$keyprefix.$key.$keysuffix.
'").val()) || 0;
8697 container.find(".star").each(function() {
8698 $(this).toggleClass("active", $(this).data("value") <= selectedStars);
8700 container.find(".star").on("mouseover", function() {
8701 let selectedStar = $(this).data("value");
8702 container.find(".star").each(function() {
8703 $(this).toggleClass("active", $(this).data("value") <= selectedStar);
8706 container.on("mouseout", function() {
8707 container.find(".star").each(function() {
8708 $(this).toggleClass("active", $(this).data("value") <= selectedStars);
8711 container.find(".star").off("click").on("click", function() {
8712 selectedStars = $(this).data("value");
8713 if (selectedStars === 1 && $("#'.$keyprefix.$key.$keysuffix.
'").val() == 1) {
8716 $("#'.$keyprefix.$key.$keysuffix.
'").val(selectedStars);
8717 container.find(".star").each(function() {
8718 $(this).toggleClass("active", $(this).data("value") <= selectedStars);
8723 } elseif (preg_match(
'/^double(\([0-9],[0-9]\)){0,1}/', (
string) $type)) {
8724 if (!empty($value)) {
8725 $value =
price($value);
8727 $out =
'<input type="text" class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.$value.
'" '.($moreparam ? $moreparam :
'').
'> ';
8728 } elseif ($type ==
'select') {
8731 include_once DOL_DOCUMENT_ROOT.
'/core/lib/ajax.lib.php';
8732 $out .=
ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
8738 foreach ($param[
'options'] as $keyb => $valb) {
8739 if ((
string) $keyb ==
'') {
8742 if (strpos($valb,
"|") !==
false) {
8743 list($valb, $parent) = explode(
'|', $valb);
8746 $tmpselect .=
'<option value="'.$keyb.
'"';
8747 $tmpselect .= (((string) $value == (
string) $keyb) ?
' selected' :
'');
8748 if (!empty($parent)) {
8751 $tmpselect .= (!empty($parent) ?
' parent="'.$parent.
'"' :
'');
8752 $tmpselect .=
'>'.$langs->trans($valb).
'</option>';
8755 $out .=
'<select class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" '.($moreparam ? $moreparam :
'').
'>';
8756 if ((!isset($this->fields[$key][
'default'])) || empty($this->fields[$key][
'notnull']) || ($this->fields[$key][
'notnull'] != 1) || $nbchoice >= 2) {
8757 $out .=
'<option value="0"> </option>';
8760 $out .=
'</select>';
8761 } elseif ($type ==
'sellist') {
8764 include_once DOL_DOCUMENT_ROOT.
'/core/lib/ajax.lib.php';
8765 $out .=
ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
8768 $out .=
'<select class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" '.($moreparam ? $moreparam :
'').
'>';
8769 if (is_array($param[
'options'])) {
8770 $tmpparamoptions = array_keys($param[
'options']);
8771 $paramoptions = preg_split(
'/[\r\n]+/', $tmpparamoptions[0]);
8773 $InfoFieldList = explode(
":", $paramoptions[0], 5);
8785 if (! empty($InfoFieldList[4])) {
8787 $parenthesisopen = 0;
8788 while (substr($InfoFieldList[4], $pos, 1) !==
'' && ($parenthesisopen || $pos == 0 || substr($InfoFieldList[4], $pos, 1) !=
':')) {
8789 if (substr($InfoFieldList[4], $pos, 1) ==
'(') {
8792 if (substr($InfoFieldList[4], $pos, 1) ==
')') {
8797 $tmpbefore = substr($InfoFieldList[4], 0, $pos);
8798 $tmpafter = substr($InfoFieldList[4], $pos + 1);
8800 $InfoFieldList[4] = $tmpbefore;
8801 if ($tmpafter !==
'') {
8802 $InfoFieldList = array_merge($InfoFieldList, explode(
':', $tmpafter));
8808 if (preg_match(
'/^\(?([a-z0-9]+)([=<>]+)(\d+)\)?$/i', $InfoFieldList[4], $reg)) {
8809 $InfoFieldList[4] =
'('.$reg[1].
':'.$reg[2].
':'.$reg[3].
')';
8820 $keyList = (empty($InfoFieldList[2]) ?
'rowid' : $InfoFieldList[2].
' as rowid');
8822 if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
8823 if (strpos($InfoFieldList[4],
'extra.') !==
false) {
8824 $keyList =
'main.'.$InfoFieldList[2].
' as rowid';
8826 $keyList = $InfoFieldList[2].
' as rowid';
8829 if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
8830 list($parentName, $parentField) = explode(
'|', $InfoFieldList[3]);
8831 if (!empty($InfoFieldList[4]) && strpos($InfoFieldList[4],
'extra.') !==
false) {
8832 $keyList .=
', main.'.$parentField;
8834 $keyList .=
', '.$parentField;
8838 $filter_categorie =
false;
8839 if (count($InfoFieldList) > 5) {
8840 if ($InfoFieldList[0] ==
'categorie') {
8841 $filter_categorie =
true;
8845 if (!$filter_categorie) {
8846 $fields_label = isset($InfoFieldList[1]) ? explode(
'|', $InfoFieldList[1]) : array();
8847 if (!empty($fields_label)) {
8849 $keyList .= implode(
', ', $fields_label);
8853 $sql =
"SELECT " . $this->db->sanitize($keyList, 0, 0, 1);
8854 $sql .=
" FROM " . $this->db->prefix() . $this->db->sanitize($InfoFieldList[0]);
8856 if (!empty($InfoFieldList[4])) {
8858 if (strpos($InfoFieldList[4],
'$SEL$') !==
false) {
8859 $InfoFieldList[4] = str_replace(
'$SEL$',
'SELECT', $InfoFieldList[4]);
8863 if (strpos($InfoFieldList[4],
'$ID$') !==
false && !empty($objectid)) {
8864 $InfoFieldList[4] = str_replace(
'$ID$', (
string) $objectid, $InfoFieldList[4]);
8866 $InfoFieldList[4] = str_replace(
'$ID$',
'0', $InfoFieldList[4]);
8871 if (strpos($InfoFieldList[4],
'extra') !==
false) {
8872 $sql .=
" as main, " . $this->db->sanitize($this->db->prefix() . $InfoFieldList[0]) .
"_extrafields as extra";
8873 $sqlwhere .=
" WHERE extra.fk_object = main." . $this->db->sanitize($InfoFieldList[2]);
8879 $sqlwhere .=
' WHERE 1=1';
8896 if (in_array($InfoFieldList[0], array(
'tablewithentity'))) {
8897 $sqlwhere .=
" AND entity = " . ((int)
$conf->entity);
8902 if (isset($InfoFieldList[7]) && preg_match(
'/^[a-z0-9_\-,]+$/i', $InfoFieldList[7])) {
8903 $sql .=
" ORDER BY ".$this->db->sanitize($InfoFieldList[7]);
8905 $sql .=
" ORDER BY ".$this->db->sanitize(implode(
', ', $fields_label));
8907 $sql .=
' LIMIT ' .
getDolGlobalInt(
'MAIN_EXTRAFIELDS_LIMIT_SELLIST_SQL', 1000);
8910 dol_syslog(get_class($this) .
'::showInputField type=sellist', LOG_DEBUG);
8911 $resql = $this->db->query($sql);
8913 $out .=
'<option value="0"> </option>';
8914 $num = $this->db->num_rows($resql);
8918 $obj = $this->db->fetch_object($resql);
8922 $fields_label = explode(
'|', $InfoFieldList[1]);
8923 if (count($fields_label) > 1) {
8925 foreach ($fields_label as $field_toshow) {
8926 $labeltoshow .= $obj->$field_toshow .
' ';
8929 $labeltoshow = $obj->{$InfoFieldList[1]};
8931 $labeltoshow =
dol_trunc($labeltoshow, 45);
8933 if ($value == $obj->rowid) {
8934 foreach ($fields_label as $field_toshow) {
8935 $translabel = $langs->trans($obj->$field_toshow);
8936 if ($translabel != $obj->$field_toshow) {
8937 $labeltoshow =
dol_trunc($translabel) .
' ';
8939 $labeltoshow =
dol_trunc($obj->$field_toshow) .
' ';
8942 $out .=
'<option value="' . $obj->rowid .
'" selected>' . $labeltoshow .
'</option>';
8945 $translabel = $langs->trans($obj->{$InfoFieldList[1]});
8946 if ($translabel != $obj->{$InfoFieldList[1]}) {
8947 $labeltoshow =
dol_trunc($translabel, 18);
8949 $labeltoshow =
dol_trunc($obj->{$InfoFieldList[1]});
8952 if (empty($labeltoshow)) {
8953 $labeltoshow =
'(not defined)';
8955 if ($value == $obj->rowid) {
8956 $out .=
'<option value="' . $obj->rowid .
'" selected>' . $labeltoshow .
'</option>';
8959 if (!empty($InfoFieldList[3]) && $parentField) {
8960 $parent = $parentName .
':' . $obj->{$parentField};
8964 $out .=
'<option value="' . $obj->rowid .
'"';
8965 $out .= ($value == $obj->rowid ?
' selected' :
'');
8966 $out .= (!empty($parent) ?
' parent="' . $parent .
'"' :
'');
8967 $out .=
'>' . $labeltoshow .
'</option>';
8972 $this->db->free($resql);
8974 print
'Error in request ' . $sql .
' ' . $this->db->lasterror() .
'. Check setup of extra parameters.<br>';
8977 require_once DOL_DOCUMENT_ROOT.
'/categories/class/categorie.class.php';
8978 $categcode = $InfoFieldList[5];
8979 if (is_numeric($categcode)) {
8980 $tmpcategory =
new Categorie($this->db);
8981 $MAP_ID_TO_CODE = array_flip($tmpcategory->MAP_ID);
8982 $categcode = $MAP_ID_TO_CODE[(int) $categcode];
8985 $data = $form->select_all_categories($categcode,
'',
'parent', 64, $InfoFieldList[6], 1, 1);
8986 $out .=
'<option value="0"> </option>';
8987 foreach ($data as $data_key => $data_value) {
8988 $out .=
'<option value="' . $data_key .
'"';
8989 $out .= ($value == $data_key ?
' selected' :
'');
8990 $out .=
'>' . $data_value .
'</option>';
8994 $out .=
'</select>';
8995 } elseif ($type ==
'checkbox') {
8996 $value_arr = explode(
',', $value);
8997 $out = $form->multiselectarray($keyprefix.$key.$keysuffix, (empty($param[
'options']) ?
null : $param[
'options']), $value_arr, 0, 0, $morecss, 0,
'100%');
8998 } elseif ($type ==
'radio') {
9000 foreach ($param[
'options'] as $keyopt => $valopt) {
9001 $out .=
'<input class="flat '.$morecss.
'" type="radio" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" '.($moreparam ? $moreparam :
'');
9002 $out .=
' value="'.$keyopt.
'"';
9003 $out .=
' id="'.$keyprefix.$key.$keysuffix.
'_'.$keyopt.
'"';
9004 $out .= ($value == $keyopt ?
'checked' :
'');
9005 $out .=
'/><label for="'.$keyprefix.$key.$keysuffix.
'_'.$keyopt.
'">'.$valopt.
'</label><br>';
9007 } elseif ($type ==
'chkbxlst') {
9008 if (is_array($value)) {
9009 $value_arr = $value;
9011 $value_arr = explode(
',', $value);
9014 if (is_array($param[
'options'])) {
9015 $tmpparamoptions = array_keys($param[
'options']);
9016 $paramoptions = preg_split(
'/[\r\n]+/', $tmpparamoptions[0]);
9018 $InfoFieldList = explode(
":", $paramoptions[0], 5);
9030 if (! empty($InfoFieldList[4])) {
9032 $parenthesisopen = 0;
9033 while (substr($InfoFieldList[4], $pos, 1) !==
'' && ($parenthesisopen || $pos == 0 || substr($InfoFieldList[4], $pos, 1) !=
':')) {
9034 if (substr($InfoFieldList[4], $pos, 1) ==
'(') {
9037 if (substr($InfoFieldList[4], $pos, 1) ==
')') {
9042 $tmpbefore = substr($InfoFieldList[4], 0, $pos);
9043 $tmpafter = substr($InfoFieldList[4], $pos + 1);
9045 $InfoFieldList[4] = $tmpbefore;
9046 if ($tmpafter !==
'') {
9047 $InfoFieldList = array_merge($InfoFieldList, explode(
':', $tmpafter));
9052 if (preg_match(
'/^\(?([a-z0-9]+)([=<>]+)(\d+)\)?$/i', $InfoFieldList[4], $reg)) {
9053 $InfoFieldList[4] =
'('.$reg[1].
':'.$reg[2].
':'.$reg[3].
')';
9061 '@phan-var-force array{0:string,1:string,2:string,3:string,3:string,5:string,6:string} $InfoFieldList';
9066 $keyList = (empty($InfoFieldList[2]) ?
'rowid' : $InfoFieldList[2].
' as rowid');
9068 if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
9069 if (strpos($InfoFieldList[4],
'extra.') !==
false) {
9070 $keyList =
'main.'.$InfoFieldList[2].
' as rowid';
9072 $keyList = $InfoFieldList[2].
' as rowid';
9075 if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
9076 list($parentName, $parentField) = explode(
'|', $InfoFieldList[3]);
9077 if (!empty($InfoFieldList[4]) && strpos($InfoFieldList[4],
'extra.') !==
false) {
9078 $keyList .=
', main.'.$parentField;
9080 $keyList .=
', '.$parentField;
9084 $filter_categorie =
false;
9085 if (count($InfoFieldList) > 5) {
9086 if ($InfoFieldList[0] ==
'categorie') {
9087 $filter_categorie =
true;
9092 if (!$filter_categorie) {
9093 $fields_label = explode(
'|', $InfoFieldList[1]);
9094 if (is_array($fields_label)) {
9096 $keyList .= implode(
', ', $fields_label);
9100 $sql =
"SELECT " . $this->db->sanitize($keyList, 0, 0, 1);
9101 $sql .=
' FROM ' . $this->db->prefix() . $this->db->sanitize($InfoFieldList[0]);
9103 if (!empty($InfoFieldList[4])) {
9105 if (strpos($InfoFieldList[4],
'$SEL$') !==
false) {
9106 $InfoFieldList[4] = str_replace(
'$SEL$',
'SELECT', $InfoFieldList[4]);
9110 if (strpos($InfoFieldList[4],
'$ID$') !==
false && !empty($objectid)) {
9111 $InfoFieldList[4] = str_replace(
'$ID$', (
string) $objectid, $InfoFieldList[4]);
9113 $InfoFieldList[4] = str_replace(
'$ID$',
'0', $InfoFieldList[4]);
9118 if (strpos($InfoFieldList[4],
'extra') !==
false) {
9119 $sql .=
' as main, ' . $this->db->sanitize($this->db->prefix() . $InfoFieldList[0]) .
'_extrafields as extra';
9120 $sqlwhere .=
" WHERE extra.fk_object = main." . $this->db->sanitize($InfoFieldList[2]);
9126 $sqlwhere .=
' WHERE 1=1';
9143 if (in_array($InfoFieldList[0], array(
'tablewithentity'))) {
9144 $sqlwhere .=
" AND entity = " . ((int)
$conf->entity);
9151 dol_syslog(get_class($this) .
'::showInputField type=chkbxlst', LOG_DEBUG);
9153 $resql = $this->db->query($sql);
9155 $num = $this->db->num_rows($resql);
9162 $obj = $this->db->fetch_object($resql);
9166 $fields_label = explode(
'|', $InfoFieldList[1]);
9167 if (count($fields_label) > 1) {
9169 foreach ($fields_label as $field_toshow) {
9170 $labeltoshow .= $obj->$field_toshow .
' ';
9173 $labeltoshow = $obj->{$InfoFieldList[1]};
9175 $labeltoshow =
dol_trunc($labeltoshow, 45);
9177 if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
9178 foreach ($fields_label as $field_toshow) {
9179 $translabel = $langs->trans($obj->$field_toshow);
9180 if ($translabel != $obj->$field_toshow) {
9181 $labeltoshow =
dol_trunc($translabel, 18) .
' ';
9183 $labeltoshow =
dol_trunc($obj->$field_toshow, 18) .
' ';
9187 $data[$obj->rowid] = $labeltoshow;
9190 $translabel = $langs->trans($obj->{$InfoFieldList[1]});
9191 if ($translabel != $obj->{$InfoFieldList[1]}) {
9192 $labeltoshow =
dol_trunc($translabel, 18);
9194 $labeltoshow =
dol_trunc($obj->{$InfoFieldList[1]}, 18);
9197 if (empty($labeltoshow)) {
9198 $labeltoshow =
'(not defined)';
9201 if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
9202 $data[$obj->rowid] = $labeltoshow;
9205 if (!empty($InfoFieldList[3]) && $parentField) {
9206 $parent = $parentName .
':' . $obj->{$parentField};
9210 $data[$obj->rowid] = $labeltoshow;
9215 $this->db->free($resql);
9217 $out = $form->multiselectarray($keyprefix . $key . $keysuffix, $data, $value_arr, 0, 0, $morecss, 0,
'100%');
9219 print
'Error in request ' . $sql .
' ' . $this->db->lasterror() .
'. Check setup of extra parameters.<br>';
9222 require_once DOL_DOCUMENT_ROOT.
'/categories/class/categorie.class.php';
9223 $categcode = $InfoFieldList[5];
9224 if (is_numeric($categcode)) {
9225 $tmpcategory =
new Categorie($this->db);
9226 $MAP_ID_TO_CODE = array_flip($tmpcategory->MAP_ID);
9227 $categcode = $MAP_ID_TO_CODE[(int) $categcode];
9230 $data = $form->select_all_categories($categcode,
'',
'parent', 64, $InfoFieldList[6], 1, 1);
9231 $out = $form->multiselectarray($keyprefix . $key . $keysuffix, $data, $value_arr, 0, 0, $morecss, 0,
'100%');
9234 } elseif ($type ==
'link') {
9237 $param_list = array_keys($param[
'options']);
9238 $param_list_array = explode(
':', $param_list[0], 4);
9240 $showempty = (($required && $default !=
'') ? 0 : 1);
9242 if (!preg_match(
'/search_/', $keyprefix)) {
9243 if (!empty($param_list_array[2])) {
9245 if (!empty($this->fields[$key][
'picto'])) {
9246 $morecss .=
' widthcentpercentminusxx';
9248 $morecss .=
' widthcentpercentminusx';
9252 if (!empty($this->fields[$key][
'picto'])) {
9253 $morecss .=
' widthcentpercentminusx';
9262 $objectfield = $val;
9265 $out = $form->selectForForms($param_list_array[0], $keyprefix.$key.$keysuffix, (
int) $value, $showempty,
'',
'', $morecss, $moreparam, 0, (empty($val[
'disabled']) ? 0 : 1),
'', $objectfield);
9267 if (!empty($param_list_array[2])) {
9268 if ((!
GETPOSTISSET(
'backtopage') || strpos(
GETPOST(
'backtopage'), $_SERVER[
'PHP_SELF']) === 0)
9269 && empty($val[
'disabled']) && empty($nonewbutton)) {
9270 list($class, $classfile) = explode(
':', $param_list[0]);
9271 if (file_exists(
dol_buildpath(dirname(dirname($classfile)).
'/card.php'))) {
9272 $url_path =
dol_buildpath(dirname(dirname($classfile)).
'/card.php', 1);
9274 $url_path =
dol_buildpath(dirname(dirname($classfile)).
'/'.strtolower($class).
'_card.php', 1);
9276 $paramforthenewlink =
'';
9277 $paramforthenewlink .= (
GETPOSTISSET(
'action') ?
'&action='.GETPOST(
'action',
'aZ09') :
'');
9278 $paramforthenewlink .= (
GETPOSTISSET(
'id') ?
'&id='.GETPOSTINT(
'id') :
'');
9279 $paramforthenewlink .= (
GETPOSTISSET(
'origin') ?
'&origin='.GETPOST(
'origin',
'aZ09') :
'');
9280 $paramforthenewlink .= (
GETPOSTISSET(
'originid') ?
'&originid='.GETPOSTINT(
'originid') :
'');
9281 $paramforthenewlink .=
'&fk_'.strtolower($class).
'=--IDFORBACKTOPAGE--';
9283 $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>';
9286 } elseif ($type ==
'password') {
9288 if ($keyprefix.$key.$keysuffix ==
'pass_crypted') {
9289 $out =
'<input type="'.($keyprefix ==
'search_' ?
'text' :
'password').
'" class="flat '.$morecss.
'" name="pass" id="pass" value="" '.($moreparam ? $moreparam :
'').
'>';
9290 $out .=
'<input type="hidden" name="pass_crypted" id="pass_crypted" value="'.$value.
'" '.($moreparam ? $moreparam :
'').
'>';
9292 $out =
'<input type="'.($keyprefix ==
'search_' ?
'text' :
'password').
'" class="flat '.$morecss.
'" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.$value.
'" '.($moreparam ? $moreparam :
'').
'>';
9294 } elseif ($type ==
'array') {
9296 $newval[
'type'] =
'varchar(256)';
9299 if (!empty($value)) {
9300 foreach ($value as $option) {
9301 $out .=
'<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).
'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
9302 $out .= $this->showInputField($newval, $keyprefix.$key.$keysuffix.
'[]', $option, $moreparam,
'',
'', $morecss).
'<br></span>';
9305 $out .=
'<a id="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).
'_add" href="javascript:;"><span class="fa fa-plus-circle valignmiddle"></span></a>';
9307 $newInput =
'<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).
'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
9308 $newInput .= $this->showInputField($newval, $keyprefix.$key.$keysuffix.
'[]',
'', $moreparam,
'',
'', $morecss).
'<br></span>';
9310 if (!empty(
$conf->use_javascript_ajax)) {
9312 <script nonce="'.getNonce().
'">
9313 $(document).ready(function() {
9314 $(\'a#'.
dol_escape_js($keyprefix.$key.$keysuffix).
'_add\').click(function() {
9318 $(document).on(
"click", \
'a.'.
dol_escape_js($keyprefix.$key.$keysuffix).
'_del\', function() {
9319 $(this).parent().remove();
9325 if (!empty($hidden)) {
9326 $out =
'<input type="hidden" value="'.$value.
'" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'"/>';
9329 if ($isDependList == 1) {
9330 $out .= $this->getJSListDependancies(
'_common');
9338 if (!empty($fieldValidationErrorMsg) && function_exists(
'getFieldErrorIcon')) {
9339 $out .=
' '.getFieldErrorIcon($fieldValidationErrorMsg);
9358 public function showOutputField($val, $key, $value, $moreparam =
'', $keysuffix =
'', $keyprefix =
'', $morecss =
'')
9360 global
$conf, $langs, $form;
9364 if (!is_object($form)) {
9365 require_once DOL_DOCUMENT_ROOT.
'/core/class/html.form.class.php';
9366 $form =
new Form($this->db);
9370 $type = empty($val[
'type']) ?
'' : $val[
'type'];
9371 $size = empty($val[
'css']) ?
'' : $val[
'css'];
9376 if (preg_match(
'/varchar\((\d+)\)/', $type, $reg)) {
9379 } elseif (preg_match(
'/varchar/', $type)) {
9381 } elseif (preg_match(
'/^double\(/', $type)) {
9384 if (!empty($val[
'arrayofkeyval']) && is_array($val[
'arrayofkeyval'])) {
9386 if (empty($this->fields[$key][
'multiinput'])) {
9387 $type = (($this->fields[$key][
'type'] ==
'checkbox') ? $this->fields[$key][
'type'] :
'select');
9390 if (isset($val[
'type']) && preg_match(
'/^integer:(.*):(.*)/i', $val[
'type'], $reg)) {
9394 $default = empty($val[
'default']) ?
'' : $val[
'default'];
9395 $computed = empty($val[
'computed']) ?
'' : $val[
'computed'];
9396 $unique = empty($val[
'unique']) ?
'' : $val[
'unique'];
9397 $required = empty($val[
'required']) ?
'' : $val[
'required'];
9399 $param[
'options'] = array();
9401 if (!empty($val[
'arrayofkeyval']) && is_array($val[
'arrayofkeyval'])) {
9402 $param[
'options'] = $val[
'arrayofkeyval'];
9404 if (isset($val[
'type']) && preg_match(
'/^integer:([^:]*):([^:]*)/i', $val[
'type'], $reg)) {
9406 $stringforoptions = $reg[1].
':'.$reg[2];
9408 if ($reg[1] ==
'User') {
9409 $stringforoptions .=
':#getnomurlparam1=-1';
9411 $param[
'options'] = array($stringforoptions => $stringforoptions);
9412 } elseif (isset($val[
'type']) && preg_match(
'/^sellist:(.*):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
9413 $param[
'options'] = array($reg[1].
':'.$reg[2].
':'.$reg[3].
':'.$reg[4] =>
'N');
9415 } elseif (isset($val[
'type']) && preg_match(
'/^sellist:(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
9416 $param[
'options'] = array($reg[1].
':'.$reg[2].
':'.$reg[3] =>
'N');
9418 } elseif (isset($val[
'type']) && preg_match(
'/^sellist:(.*):(.*)/i', $val[
'type'], $reg)) {
9419 $param[
'options'] = array($reg[1].
':'.$reg[2] =>
'N');
9421 } elseif (isset($val[
'type']) && preg_match(
'/^chkbxlst:(.*)/i', $val[
'type'], $reg)) {
9422 $param[
'options'] = array($reg[1] =>
'N');
9424 } elseif (isset($val[
'type']) && preg_match(
'/stars\((\d+)\)/', $val[
'type'], $reg)) {
9425 $param[
'options'] = array();
9430 $langfile = empty($val[
'langfile']) ?
'' : $val[
'langfile'];
9431 $list = (empty($val[
'list']) ?
'' : $val[
'list']);
9432 $help = (empty($val[
'help']) ?
'' : $val[
'help']);
9433 $hidden = (($val[
'visible'] == 0) ? 1 : 0);
9443 $value =
dol_eval((
string) $computed, 1, 0,
'2');
9446 if (empty($morecss)) {
9447 if ($type ==
'date') {
9448 $morecss =
'minwidth100imp';
9449 } elseif ($type ==
'datetime' || $type ==
'timestamp') {
9450 $morecss =
'minwidth200imp';
9451 } elseif (in_array($type, array(
'int',
'double',
'price'))) {
9452 $morecss =
'maxwidth75';
9453 } elseif ($type ==
'url') {
9454 $morecss =
'minwidth400';
9455 } elseif ($type ==
'boolean') {
9458 if (is_numeric($size) && round((
float) $size) < 12) {
9459 $morecss =
'minwidth100';
9460 } elseif (is_numeric($size) && round((
float) $size) <= 48) {
9461 $morecss =
'minwidth200';
9463 $morecss =
'minwidth400';
9469 if (in_array($key, array(
'rowid',
'ref')) && method_exists($this,
'getNomUrl')) {
9471 if ($key !=
'rowid' || empty($this->fields[
'ref'])) {
9472 $value = $this->getNomUrl(1,
'', 0,
'', 1);
9474 } elseif ($key ==
'status' && method_exists($this,
'getLibStatut')) {
9475 $value = $this->getLibStatut(3);
9476 } elseif ($type ==
'date') {
9477 if (!empty($value)) {
9482 } elseif ($type ==
'datetime' || $type ==
'timestamp') {
9483 if (!empty($value)) {
9488 } elseif ($type ==
'duration') {
9489 include_once DOL_DOCUMENT_ROOT.
'/core/lib/date.lib.php';
9490 if (!is_null($value) && $value !==
'') {
9493 } elseif ($type ==
'double' || $type ==
'real') {
9494 if (!is_null($value) && $value !==
'') {
9495 $value =
price($value);
9497 } elseif ($type ==
'boolean') {
9499 if (!empty($value)) {
9500 $checked =
' checked ';
9503 $value =
'<input type="checkbox" '.$checked.
' '.($moreparam ? $moreparam :
'').
' readonly disabled>';
9505 $value = yn($value ? 1 : 0);
9507 } elseif ($type ==
'mail' || $type ==
'email') {
9509 } elseif ($type ==
'url') {
9511 } elseif ($type ==
'phone') {
9512 $value =
dol_print_phone((
string) $value,
'', 0, 0,
'',
' ',
'phone');
9513 } elseif ($type ==
'ip') {
9515 } elseif ($type ==
'stars') {
9516 $value =
'<input type="hidden" class="flat '.$morecss.
'" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.$this->id.
'" value="'.
dol_escape_htmltag((
string) $value).
'"'.($moreparam ? $moreparam :
'').
'>';
9517 $value .=
'<div class="star-selection" id="'.$keyprefix.$key.$keysuffix.$this->id.
'_selection">';
9519 while ($i <= $size) {
9520 $value .=
'<span class="star" data-value="'.$i.
'">'.img_picto(
'',
'fontawesome_star_fas').
'</span>';
9525 $(document).ready(function() { /* commonobject.class.php 2 */
9526 let container = $("#'.$keyprefix.$key.$keysuffix.$this->id.
'_selection");
9527 let selectedStars = parseInt($("#'.$keyprefix.$key.$keysuffix.$this->id.
'").val()) || 0;
9528 container.find(".star").each(function() {
9529 $(this).toggleClass("active", $(this).data("value") <= selectedStars);
9531 container.find(".star").on("mouseover", function() {
9532 let selectedStar = $(this).data("value");
9533 container.find(".star").each(function() {
9534 $(this).toggleClass("active", $(this).data("value") <= selectedStar);
9537 container.on("mouseout", function() {
9538 container.find(".star").each(function() {
9539 $(this).toggleClass("active", $(this).data("value") <= selectedStars);
9542 container.find(".star").off("click").on("click", function() {
9543 selectedStars = $(this).data("value");
9544 if (selectedStars == 1 && $("#'.$keyprefix.$key.$keysuffix.$this->id.
'").val() == 1) {
9547 container.find("#'.$keyprefix.$key.$keysuffix.$this->id.
'").val(selectedStars);
9548 container.find(".star").each(function() {
9549 $(this).toggleClass("active", $(this).data("value") <= selectedStars);
9552 url: "ajax/'.$this->element.
'.php",
9555 objectId: "'.$this->
id.
'",
9556 field: "'.$keyprefix.$key.$keysuffix.
'",
9557 value: selectedStars,
9560 success: function(response) {
9561 var res = JSON.parse(response);
9562 console[res.status === "success" ? "log" : "error"](res.message);
9564 error: function(xhr, status, error) {
9565 console.log("Ajax request failed while updating '.$keyprefix.$key.$keysuffix.
':", error);
9571 } elseif ($type ==
'price') {
9572 if (!is_null($value) && $value !==
'') {
9573 $value =
price($value, 0, $langs, 0, 0, -1,
$conf->currency);
9575 } elseif ($type ==
'select') {
9576 $value = isset($param[
'options'][(
string) $value]) ? $param[
'options'][(string) $value] :
'';
9577 if (strpos($value,
"|") !==
false) {
9578 $value = $langs->trans(explode(
'|', $value)[0]);
9579 } elseif (! is_numeric($value)) {
9580 $value = $langs->trans($value);
9582 } elseif ($type ==
'sellist') {
9583 $param_list = array_keys($param[
'options']);
9584 $InfoFieldList = explode(
":", $param_list[0]);
9586 $selectkey =
"rowid";
9589 if (count($InfoFieldList) > 2 && !empty($InfoFieldList[2])) {
9590 $selectkey = $InfoFieldList[2];
9591 $keyList = $InfoFieldList[2].
' as rowid';
9594 $fields_label = explode(
'|', $InfoFieldList[1]);
9595 if (is_array($fields_label)) {
9597 $keyList .= implode(
', ', $fields_label);
9600 $filter_categorie =
false;
9601 if (count($InfoFieldList) > 5) {
9602 if ($InfoFieldList[0] ==
'categorie') {
9603 $filter_categorie =
true;
9607 $sql =
"SELECT ".$this->db->sanitize($keyList, 0, 0, 1);
9608 $sql .=
' FROM '.$this->db->prefix().$this->db->sanitize($InfoFieldList[0]);
9609 if (isset($InfoFieldList[4]) && strpos($InfoFieldList[4],
'extra') !==
false) {
9612 if ($selectkey ==
'rowid' && empty($value)) {
9613 $sql .=
" WHERE ".$this->db->sanitize($selectkey).
" = 0";
9614 } elseif ($selectkey ==
'rowid') {
9615 $sql .=
" WHERE ".$this->db->sanitize($selectkey).
" = ".((int) $value);
9617 $sql .=
" WHERE ".$this->db->sanitize($selectkey).
" = '".$this->db->escape((
string) $value).
"'";
9622 dol_syslog(get_class($this).
':showOutputField:$type=sellist', LOG_DEBUG);
9623 $resql = $this->db->query($sql);
9625 if (!$filter_categorie) {
9627 $numrows = $this->db->num_rows($resql);
9629 $obj = $this->db->fetch_object($resql);
9632 $fields_label = explode(
'|', $InfoFieldList[1]);
9634 if (is_array($fields_label) && count($fields_label) > 1) {
9635 foreach ($fields_label as $field_toshow) {
9637 if (!empty($obj->$field_toshow)) {
9638 $translabel = $langs->trans($obj->$field_toshow);
9640 if ($translabel != $field_toshow) {
9641 $value .=
dol_trunc($translabel, 18) .
' ';
9643 $value .= $obj->$field_toshow .
' ';
9648 if (!empty($obj->{$InfoFieldList[1]})) {
9649 $translabel = $langs->trans($obj->{$InfoFieldList[1]});
9651 if ($translabel != $obj->{$InfoFieldList[1]}) {
9654 $value = $obj->{$InfoFieldList[1]};
9659 require_once DOL_DOCUMENT_ROOT .
'/categories/class/categorie.class.php';
9662 $obj = $this->db->fetch_object($resql);
9664 $c->fetch($obj->rowid);
9665 $ways =
$c->print_all_ways();
9666 foreach ($ways as $way) {
9667 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories"' . (
$c->color ?
' style="background: #' .
$c->color .
';"' :
' style="background: #aaa"') .
'>' . img_object(
'',
'category') .
' ' . $way .
'</li>';
9669 $value =
'<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(
' ', $toprint).
'</ul></div>';
9672 dol_syslog(get_class($this).
'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
9674 } elseif ($type ==
'radio') {
9675 $value = $param[
'options'][(string) $value];
9676 } elseif ($type ==
'checkbox') {
9677 $value_arr = explode(
',', (
string) $value);
9679 if (is_array($value_arr) && count($value_arr) > 0) {
9681 foreach ($value_arr as $keyval => $valueval) {
9682 if (!empty($valueval)) {
9683 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' . $param[
'options'][$valueval] .
'</li>';
9686 if (!empty($toprint)) {
9687 $value =
'<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">' . implode(
' ', $toprint) .
'</ul></div>';
9690 } elseif ($type ==
'chkbxlst') {
9691 $value_arr = (isset($value) ? explode(
',', $value) : array());
9693 $param_list = array_keys($param[
'options']);
9694 $InfoFieldList = explode(
":", $param_list[0]);
9696 $selectkey =
"rowid";
9699 if (count($InfoFieldList) >= 3) {
9700 $selectkey = $InfoFieldList[2];
9701 $keyList = $InfoFieldList[2].
' as rowid';
9704 $fields_label = explode(
'|', $InfoFieldList[1]);
9705 if (is_array($fields_label)) {
9707 $keyList .= implode(
', ', $fields_label);
9710 $filter_categorie =
false;
9711 if (count($InfoFieldList) > 5) {
9712 if ($InfoFieldList[0] ==
'categorie') {
9713 $filter_categorie =
true;
9717 $sql =
"SELECT ".$this->db->sanitize($keyList, 0, 0, 1);
9718 $sql .=
' FROM '.$this->db->prefix().$this->db->sanitize($InfoFieldList[0]);
9719 if (isset($InfoFieldList[4]) && strpos($InfoFieldList[4],
'extra') !==
false) {
9725 dol_syslog(get_class($this).
':showOutputField:$type=chkbxlst', LOG_DEBUG);
9726 $resql = $this->db->query($sql);
9728 if (!$filter_categorie) {
9731 while ($obj = $this->db->fetch_object($resql)) {
9733 $fields_label = explode(
'|', $InfoFieldList[1]);
9734 if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
9735 if (is_array($fields_label) && count($fields_label) > 1) {
9736 foreach ($fields_label as $field_toshow) {
9738 if (!empty($obj->$field_toshow)) {
9739 $translabel = $langs->trans($obj->$field_toshow);
9741 if ($translabel != $field_toshow) {
9742 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' .
dol_trunc($translabel, 18) .
'</li>';
9744 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' . $obj->$field_toshow .
'</li>';
9749 if (!empty($obj->{$InfoFieldList[1]})) {
9750 $translabel = $langs->trans($obj->{$InfoFieldList[1]});
9752 if ($translabel != $obj->{$InfoFieldList[1]}) {
9753 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' .
dol_trunc($translabel, 18) .
'</li>';
9755 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' . $obj->{$InfoFieldList[1]} .
'</li>';
9761 require_once DOL_DOCUMENT_ROOT .
'/categories/class/categorie.class.php';
9764 while ($obj = $this->db->fetch_object($resql)) {
9765 if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
9767 $c->fetch($obj->rowid);
9768 $ways =
$c->print_all_ways();
9769 foreach ($ways as $way) {
9770 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories"' . (
$c->color ?
' style="background: #' .
$c->color .
';"' :
' style="background: #aaa"') .
'>' . img_object(
'',
'category') .
' ' . $way .
'</li>';
9775 $value =
'<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(
' ', $toprint).
'</ul></div>';
9777 dol_syslog(get_class($this).
'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
9779 } elseif ($type ==
'link') {
9784 $param_list = array_keys($param[
'options']);
9788 $InfoFieldList = explode(
":", $param_list[0]);
9790 $classname = $InfoFieldList[0];
9791 $classpath = $InfoFieldList[1];
9794 $getnomurlparam = 3;
9795 $getnomurlparam2 =
'';
9797 if (preg_match(
'/#getnomurlparam1=([^#]*)/', $param_list[0], $regtmp)) {
9798 $getnomurlparam = $regtmp[1];
9800 if (preg_match(
'/#getnomurlparam2=([^#]*)/', $param_list[0], $regtmp)) {
9801 $getnomurlparam2 = $regtmp[1];
9804 if (!empty($classpath)) {
9807 if ($classname && !class_exists($classname)) {
9811 if ($element_prop) {
9812 $classname = $element_prop[
'classname'];
9817 if ($classname && class_exists($classname)) {
9818 $object =
new $classname($this->db);
9819 '@phan-var-force CommonObject $object';
9820 if (
$object->element ===
'product') {
9821 '@phan-var-force Product $object';
9822 $result =
$object->fetch((
int) $value,
'',
'',
'', 0, 1, 1);
9824 $result =
$object->fetch($value);
9827 if (
$object->element ===
'product') {
9828 '@phan-var-force Product $object';
9829 $get_name_url_param_arr = array($getnomurlparam, $getnomurlparam2, 0, -1, 0,
'', 0);
9830 if (isset($val[
'get_name_url_params'])) {
9831 $get_name_url_params = explode(
':', $val[
'get_name_url_params']);
9832 if (!empty($get_name_url_params)) {
9833 $param_num_max = count($get_name_url_param_arr) - 1;
9834 foreach ($get_name_url_params as $param_num => $param_value) {
9835 if ($param_num > $param_num_max) {
9838 $get_name_url_param_arr[$param_num] = $param_value;
9846 $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]);
9848 $value =
$object->getNomUrl($getnomurlparam, $getnomurlparam2);
9855 dol_syslog(
'Error bad setup of extrafield', LOG_WARNING);
9856 return 'Error bad setup of extrafield';
9861 } elseif ($type ==
'password') {
9862 $value =
'<span class="opacitymedium">'.$langs->trans(
"Encrypted").
'</span>';
9864 } elseif ($type ==
'array') {
9865 if (is_array($value)) {
9866 $value = implode(
'<br>', $value);
9868 dol_syslog(__METHOD__.
' Expected array from dol_eval, but got '.gettype($value), LOG_ERR);
9869 return 'Error unexpected result from code evaluation';
9872 if (!empty($value) && preg_match(
'/^text/', (
string) $type) && !preg_match(
'/search_/', $keyprefix) && !empty($param[
'options'])) {
9873 $value = str_replace(
',',
"\n", $value);
9881 return is_null($out) ?
'' : $out;
9893 unset($this->validateFieldsErrors[$fieldKey]);
9907 $msg = $langs->trans(
"UnknownError");
9910 $this->error = $this->validateFieldsErrors[$fieldKey] = $msg;
9921 if (!empty($this->validateFieldsErrors[$fieldKey])) {
9922 return $this->validateFieldsErrors[$fieldKey];
9939 if (!class_exists(
'Validate')) {
9940 require_once DOL_DOCUMENT_ROOT .
'/core/class/validate.class.php';
9943 $this->clearFieldError($fieldKey);
9945 if (!array_key_exists($fieldKey, $fields) || !is_array($fields[$fieldKey])) {
9946 $this->setFieldError($fieldKey, $langs->trans(
'FieldNotFoundInObject'));
9950 $val = $fields[$fieldKey];
9953 $param[
'options'] = array();
9954 $type = $val[
'type'];
9957 if (isset($val[
'notnull']) && $val[
'notnull'] === 1) {
9971 if (preg_match(
'/varchar\((\d+)\)/', $type, $reg)) {
9973 $maxSize = (int) $reg[1];
9974 } elseif (preg_match(
'/varchar/', $type)) {
9976 } elseif (preg_match(
'/^double\(/', $type)) {
9980 if (!empty($val[
'arrayofkeyval']) && is_array($val[
'arrayofkeyval'])) {
9984 if (!empty($val[
'type']) && preg_match(
'/^integer:(.*):(.*)/i', $val[
'type'], $reg)) {
9988 if (!empty($val[
'arrayofkeyval']) && is_array($val[
'arrayofkeyval'])) {
9989 $param[
'options'] = $val[
'arrayofkeyval'];
9992 if (preg_match(
'/^integer:(.*):(.*)/i', $val[
'type'], $reg)) {
9994 $param[
'options'] = array($reg[1].
':'.$reg[2] => $reg[1].
':'.$reg[2]);
9995 } elseif (preg_match(
'/^sellist:(.*):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
9996 $param[
'options'] = array($reg[1].
':'.$reg[2].
':'.$reg[3].
':'.$reg[4] =>
'N');
9998 } elseif (preg_match(
'/^sellist:(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
9999 $param[
'options'] = array($reg[1].
':'.$reg[2].
':'.$reg[3] =>
'N');
10001 } elseif (preg_match(
'/^sellist:(.*):(.*)/i', $val[
'type'], $reg)) {
10002 $param[
'options'] = array($reg[1].
':'.$reg[2] =>
'N');
10011 $validate =
new Validate($this->db, $langs);
10021 if ($required && !$validate->isNotEmptyString($fieldValue)) {
10022 $this->setFieldError($fieldKey, $validate->error);
10024 } elseif (!$required && !$validate->isNotEmptyString($fieldValue)) {
10030 if (!empty($maxSize) && !$validate->isMaxLength($fieldValue, $maxSize)) {
10031 $this->setFieldError($fieldKey, $validate->error);
10036 if (!empty($minSize) && !$validate->isMinLength($fieldValue, $minSize)) {
10037 $this->setFieldError($fieldKey, $validate->error);
10045 if (in_array($type, array(
'date',
'datetime',
'timestamp'))) {
10046 if (!$validate->isTimestamp($fieldValue)) {
10047 $this->setFieldError($fieldKey, $validate->error);
10052 } elseif ($type ==
'duration') {
10053 if (!$validate->isDuration($fieldValue)) {
10054 $this->setFieldError($fieldKey, $validate->error);
10059 } elseif (in_array($type, array(
'double',
'real',
'price'))) {
10061 if (!$validate->isNumeric($fieldValue)) {
10062 $this->setFieldError($fieldKey, $validate->error);
10067 } elseif ($type ==
'boolean') {
10068 if (!$validate->isBool($fieldValue)) {
10069 $this->setFieldError($fieldKey, $validate->error);
10074 } elseif ($type ==
'mail' || $type ==
'email') {
10075 if (!$validate->isEmail($fieldValue)) {
10076 $this->setFieldError($fieldKey, $validate->error);
10079 } elseif ($type ==
'url') {
10080 if (!$validate->isUrl($fieldValue)) {
10081 $this->setFieldError($fieldKey, $validate->error);
10086 } elseif ($type ==
'phone') {
10087 if (!$validate->isPhone($fieldValue)) {
10088 $this->setFieldError($fieldKey, $validate->error);
10093 } elseif ($type ==
'select' || $type ==
'radio') {
10094 if (!isset($param[
'options'][$fieldValue])) {
10095 $this->error = $langs->trans(
'RequireValidValue');
10100 } elseif ($type ==
'sellist' || $type ==
'chkbxlst') {
10101 $param_list = array_keys($param[
'options']);
10102 $InfoFieldList = explode(
":", $param_list[0]);
10103 $value_arr = explode(
',', $fieldValue);
10105 $selectkey =
"rowid";
10106 if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
10107 $selectkey = $InfoFieldList[2];
10110 if (!$validate->isInDb($value_arr, $InfoFieldList[0], $selectkey)) {
10111 $this->setFieldError($fieldKey, $validate->error);
10116 } elseif ($type ==
'link') {
10117 $param_list = array_keys($param[
'options']);
10118 $InfoFieldList = explode(
":", $param_list[0]);
10119 $classname = $InfoFieldList[0];
10120 $classpath = $InfoFieldList[1];
10121 if (!$validate->isFetchable((
int) $fieldValue, $classname, $classpath)) {
10122 $lastIsFetchableError = $validate->error;
10125 if ($validate->isFetchableElement((
int) $fieldValue, $classname)) {
10129 $this->setFieldError($fieldKey, $lastIsFetchableError);
10153 public function showOptionals($extrafields, $mode =
'view', $params =
null, $keysuffix =
'', $keyprefix =
'', $onetrtd =
'', $display_type =
'card')
10155 global $db,
$conf, $langs, $action, $form, $hookmanager;
10156 global $objectoffield;
10158 if (!is_object($form)) {
10159 $form =
new Form($db);
10161 if (!is_object($extrafields)) {
10162 dol_syslog(
'Bad parameter extrafields for showOptionals', LOG_ERR);
10163 return 'Bad parameter extrafields for showOptionals';
10165 if (!is_array($extrafields->attributes[$this->table_element])) {
10166 dol_syslog(
"extrafields->attributes was not loaded with extrafields->fetch_name_optionals_label(table_element);", LOG_WARNING);
10170 $objectoffield = $this;
10174 $parameters = array(
'mode' => $mode,
'params' => $params,
'keysuffix' => $keysuffix,
'keyprefix' => $keyprefix,
'display_type' => $display_type);
10175 $reshook = $hookmanager->executeHooks(
'showOptionals', $parameters, $this, $action);
10176 $hookResPrint = $hookmanager->resPrint;
10178 if (empty($reshook)) {
10179 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) {
10181 $out .=
'<!-- commonobject:showOptionals --> ';
10184 $nbofextrafieldsshown = 0;
10187 $lastseparatorkeyfound =
'';
10188 $extrafields_collapse_num =
'';
10189 $extrafields_collapse_num_old =
'';
10192 foreach ($extrafields->attributes[$this->table_element][
'label'] as $key => $label) {
10196 if (is_array($params) && array_key_exists(
'onlykey', $params) && $key != $params[
'onlykey']) {
10202 if ($enabled && isset($extrafields->attributes[$this->table_element][
'enabled'][$key])) {
10203 $enabled = (int)
dol_eval((
string) $extrafields->attributes[$this->table_element][
'enabled'][$key], 1, 1,
'2');
10205 if (empty($enabled)) {
10210 if (isset($extrafields->attributes[$this->table_element][
'list'][$key])) {
10211 $visibility = (int)
dol_eval((
string) $extrafields->attributes[$this->table_element][
'list'][$key], 1, 1,
'2');
10215 if ($perms && isset($extrafields->attributes[$this->table_element][
'perms'][$key])) {
10216 $perms = (int)
dol_eval((
string) $extrafields->attributes[$this->table_element][
'perms'][$key], 1, 1,
'2');
10219 if (($mode ==
'create') && !in_array(abs($visibility), array(1, 3))) {
10221 } elseif (($mode ==
'edit') && !in_array(abs($visibility), array(1, 3, 4))) {
10225 $ef_name =
'options_' . $key;
10226 $ef_value = $this->array_options[$ef_name] ??
'';
10227 $out .=
'<input type="hidden" name="' . $ef_name .
'" id="' . $ef_name .
'" value="' . dolPrintHTMLForAttribute($ef_value) .
'" />' .
"\n";
10229 } elseif ($mode ==
'view' && empty($visibility)) {
10232 if (empty($perms)) {
10237 if (!empty($extrafields->attributes[$this->table_element][
'langfile'][$key])) {
10238 $langs->load($extrafields->attributes[$this->table_element][
'langfile'][$key]);
10243 if (is_array($params) && count($params) > 0 && $display_type ==
'card') {
10244 if (array_key_exists(
'cols', $params)) {
10245 $colspan = $params[
'cols'];
10246 } elseif (array_key_exists(
'colspan', $params)) {
10248 if (preg_match(
'/colspan="(\d+)"/', $params[
'colspan'], $reg)) {
10249 $colspan = $reg[1];
10251 $colspan = $params[
'colspan'];
10255 $colspan = intval($colspan);
10259 $value = ((!empty($this->array_options) && array_key_exists(
"options_".$key.$keysuffix, $this->array_options)) ? $this->array_options[
"options_".$key.$keysuffix] :
null);
10265 $check =
'alphanohtml';
10266 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'html',
'text'))) {
10267 $check =
'restricthtml';
10269 $getposttemp =
GETPOST($keyprefix.
'options_'.$key.$keysuffix, $check, 3);
10271 if (is_array($getposttemp) || $getposttemp !=
'' ||
GETPOSTISSET($keyprefix.
'options_'.$key.$keysuffix)) {
10272 if (is_array($getposttemp)) {
10274 $value = implode(
",", $getposttemp);
10276 $value = $getposttemp;
10278 } elseif (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'int'))) {
10279 $value = (!empty($this->array_options[
"options_".$key]) || (isset($this->array_options[
"options_".$key]) && $this->array_options[
"options_".$key] ===
'0')) ? $this->array_options[
"options_".$key] :
'';
10280 } elseif (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'varchar',
'char'))) {
10281 $value = (isset($this->array_options[
"options_".$key]) && $this->array_options[
"options_".$key] !==
'') ? $this->array_options[
"options_".$key] :
'';
10283 $value = (!empty($this->array_options[
"options_".$key]) ? $this->array_options[
"options_".$key] :
'');
10289 $nbofextrafieldsshown++;
10292 if ($extrafields->attributes[$this->table_element][
'type'][$key] ==
'separate') {
10293 $extrafields_collapse_num = $key;
10311 $out .= $extrafields->showSeparator($key, $this, ($colspan ? $colspan + 1 : 2), $display_type, $mode);
10313 $lastseparatorkeyfound = $key;
10315 $collapse_group = $extrafields_collapse_num.(!empty($this->
id) ?
'_'.$this->id :
'');
10317 $class = (!empty($extrafields->attributes[$this->table_element][
'hidden'][$key]) ?
'hideobject ' :
'');
10319 if (is_array($params) && count($params) > 0) {
10320 if (array_key_exists(
'class', $params)) {
10321 $class .= $params[
'class'].
' ';
10323 if (array_key_exists(
'style', $params)) {
10324 $csstyle = $params[
'style'];
10329 $domData =
' data-element="extrafield"';
10330 $domData .=
' data-targetelement="'.$this->element.
'"';
10331 $domData .=
' data-targetid="'.$this->id.
'"';
10333 $html_id = (empty($this->
id) ?
'' :
'extrarow-'.$this->element.
'_'.$key.
'_'.
$this->id);
10334 if ($display_type ==
'card') {
10339 if ($action ==
'selectlines') {
10346 $force_values_on_change_company = (
10347 ($this->element ==
'facture' &&
getDolGlobalInt(
'THIRDPARTY_PROPAGATE_EXTRAFIELDS_TO_INVOICE'))
10348 || ($this->element ==
'commande' &&
getDolGlobalInt(
'THIRDPARTY_PROPAGATE_EXTRAFIELDS_TO_ORDER'))
10349 || ($this->element ==
'order_supplier' &&
getDolGlobalInt(
'THIRDPARTY_PROPAGATE_EXTRAFIELDS_TO_SUPPLIER_ORDER'))
10351 if ($force_values_on_change_company &&
GETPOSTINT(
'changecompany')) {
10352 $value = $this->array_options[
'options_'.$key] ?? $value;
10356 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'date'))) {
10357 $datenotinstring =
null;
10358 if (array_key_exists(
'options_'.$key, $this->array_options)) {
10359 $datenotinstring = $this->array_options[
'options_'.$key];
10360 if (!is_numeric($this->array_options[
'options_'.$key])) {
10361 $datenotinstring = $this->db->jdate($datenotinstring);
10364 $datekey = $keyprefix.
'options_'.$key.$keysuffix;
10367 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'datetime'))) {
10368 $datenotinstring =
null;
10369 if (array_key_exists(
'options_'.$key, $this->array_options)) {
10370 $datenotinstring = $this->array_options[
'options_'.$key];
10371 if (!is_numeric($this->array_options[
'options_'.$key])) {
10372 $datenotinstring = $this->db->jdate($datenotinstring);
10375 $timekey = $keyprefix.
'options_'.$key.$keysuffix;
10376 $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;
10379 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'price',
'double'))) {
10380 if (
GETPOSTISSET($keyprefix.
'options_'.$key.$keysuffix) || $value) {
10382 } elseif (isset($this->array_options[
'options_'.$key])) {
10383 $value = $this->array_options[
'options_'.$key];
10388 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'html',
'text',
'varchar',
'select',
'radio',
'int',
'boolean'))) {
10389 if ($action ==
'create' || $mode ==
'create') {
10390 $value = (
GETPOSTISSET($keyprefix.
'options_'.$key.$keysuffix) || $value) ? $value : $extrafields->attributes[$this->table_element][
'default'][$key];
10394 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'checkbox'))) {
10395 if ($action ==
'create') {
10396 $value = (
GETPOSTISSET($keyprefix.
'options_'.$key.$keysuffix) || $value) ? $value : explode(
',', $extrafields->attributes[$this->table_element][
'default'][$key]);
10401 $labeltoshow = $langs->trans($label);
10402 $helptoshow = $langs->trans($extrafields->attributes[$this->table_element][
'help'][$key]);
10403 if ($display_type ==
'card') {
10404 $out .=
'<tr '.($html_id ?
'id="'.$html_id.
'" ' :
'').$csstyle.
' class="field_options_'.$key.
' '.$class.$this->element.
'_extras_'.$key.
' trextrafields'.($extrafields_collapse_num ?
' trextrafieldsgroup' :
'').
' trextrafields_collapse'.$collapse_group.
'" '.$domData.
' >';
10405 if (
getDolGlobalString(
'MAIN_VIEW_LINE_NUMBER') && ($action ==
'view' || $action ==
'valid' || $action ==
'editline' || $action ==
'confirm_valid' || $action ==
'confirm_cancel')) {
10406 $out .=
'<td></td>';
10408 $out .=
'<td class="'.(empty($params[
'tdclass']) ?
'titlefieldmax45' : $params[
'tdclass']).
' wordbreak';
10409 if ($extrafields->attributes[$this->table_element][
'type'][$key] ==
'text') {
10412 } elseif ($display_type ==
'line') {
10413 $out .=
'<div '.($html_id ?
'id="'.$html_id.
'" ' :
'').$csstyle.
' class="fieldline_options_'.$key.
' '.$class.$this->element.
'_extras_'.$key.
' trextrafields_collapse'.$collapse_group.
'" '.$domData.
' >';
10414 $out .=
'<div style="display: inline-block; padding-right:4px" class="wordbreak';
10419 $tpl_context = isset($params[
"tpl_context"]) ? $params[
"tpl_context"] :
"none";
10420 if ($tpl_context !=
"public") {
10421 if ($mode !=
'view' && !empty($extrafields->attributes[$this->table_element][
'required'][$key])) {
10422 $out .=
' fieldrequired';
10426 if ($tpl_context ==
"public") {
10427 if (!empty($extrafields->attributes[$this->table_element][
'help'][$key])) {
10428 $out .= $form->textwithpicto($labeltoshow, $helptoshow);
10430 $out .= $labeltoshow;
10432 if ($mode !=
'view' && !empty($extrafields->attributes[$this->table_element][
'required'][$key])) {
10433 $out .=
' <span style="color: red">*</span>';
10436 if (!empty($extrafields->attributes[$this->table_element][
'help'][$key])) {
10437 $out .= $form->textwithpicto($labeltoshow, $helptoshow);
10439 $out .= $labeltoshow;
10443 $out .= ($display_type ==
'card' ?
'</td>' :
'</div>');
10446 $html_id = !empty($this->
id) ? $this->element.
'_extras_'.$key.
'_'.$this->id :
'';
10447 if ($display_type ==
'card') {
10449 $out .=
'<td '.($html_id ?
'id="'.$html_id.
'" ' :
'').
' class="valuefieldcreate '.$this->element.
'_extras_'.$key;
10450 $out .=
'" '.($colspan ?
' colspan="'.$colspan.
'"' :
'');
10452 } elseif ($display_type ==
'line') {
10453 $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].
'">';
10458 $out .= $extrafields->showOutputField($key, $value,
'', $this->table_element);
10461 $listoftypestoshowpicto = explode(
',',
getDolGlobalString(
'MAIN_TYPES_TO_SHOW_PICTO',
'email,ip,password'));
10462 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], $listoftypestoshowpicto)) {
10463 $out .=
getPictoForType($extrafields->attributes[$this->table_element][
'type'][$key], ($extrafields->attributes[$this->table_element][
'type'][$key] ==
'text' ?
'tdtop' :
''));
10466 $out .= $extrafields->showInputField($key, $value,
'', $keysuffix,
'',
'', $this, $this->table_element);
10469 $listoftypestoshowpicto = explode(
',',
getDolGlobalString(
'MAIN_TYPES_TO_SHOW_PICTO',
'email,phone,ip,password'));
10470 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], $listoftypestoshowpicto)) {
10471 $out .=
getPictoForType($extrafields->attributes[$this->table_element][
'type'][$key], ($extrafields->attributes[$this->table_element][
'type'][$key] ==
'text' ?
'tdtop' :
''));
10473 $out .= $extrafields->showInputField($key, $value,
'', $keysuffix,
'',
'', $this, $this->table_element);
10477 $out .= ($display_type ==
'card' ?
'</td>' :
'</div>');
10478 $out .= ($display_type ==
'card' ?
'</tr>'.
"\n" :
'</div>');
10484 if (!empty(
$conf->use_javascript_ajax)) {
10485 $out .= $this->getJSListDependancies();
10488 $out .=
'<!-- commonobject:showOptionals end --> '.
"\n";
10490 if (empty($nbofextrafieldsshown)) {
10496 $out .= $hookResPrint;
10508 <script nonce="'.getNonce().
'">
10509 jQuery(document).ready(function() {
10510 function showOptions'.$type.
'(child_list, parent_list, orig_select)
10512 var val = $("select[name=\""+parent_list+"\"]").val();
10513 var parentVal = parent_list + ":" + val;
10514 if(typeof val == "string"){
10516 var options = orig_select.find("option[parent=\""+parentVal+"\"]").clone();
10517 $("select[name=\""+child_list+"\"] option[parent]").remove();
10518 $("select[name=\""+child_list+"\"]").append(options);
10520 var options = orig_select.find("option[parent]").clone();
10521 $("select[name=\""+child_list+"\"] option[parent]").remove();
10522 $("select[name=\""+child_list+"\"]").append(options);
10524 } else if(val > 0) {
10525 var options = orig_select.find("option[parent=\""+parentVal+"\"]").clone();
10526 $("select[name=\""+child_list+"\"] option[parent]").remove();
10527 $("select[name=\""+child_list+"\"]").append(options);
10529 var options = orig_select.find("option[parent]").clone();
10530 $("select[name=\""+child_list+"\"] option[parent]").remove();
10531 $("select[name=\""+child_list+"\"]").append(options);
10534 function setListDependencies'.$type.
'() {
10535 jQuery("select option[parent]").parent().each(function() {
10536 var orig_select = {};
10537 var child_list = $(this).attr("name");
10538 orig_select[child_list] = $(this).clone();
10539 var parent = $(this).find("option[parent]:first").attr("parent");
10540 var infos = parent.split(":");
10541 var parent_list = infos[0];
10543 //Hide daughters lists
10544 if ($("#"+child_list).val() == 0 && $("#"+parent_list).val() == 0){
10545 $("#"+child_list).hide();
10546 //Show mother lists
10547 } else if ($("#"+parent_list).val() != 0){
10548 $("#"+parent_list).show();
10550 //Show the child list if the parent list value is selected
10551 $("select[name=\""+parent_list+"\"]").click(function() {
10552 if ($(this).val() != 0){
10553 $("#"+child_list).show()
10557 //When we change parent list
10558 $("select[name=\""+parent_list+"\"]").change(function() {
10559 showOptions'.$type.
'(child_list, parent_list, orig_select[child_list]);
10560 //Select the value 0 on child list after a change on the parent list
10561 $("#"+child_list).val(0).trigger("change");
10562 //Hide child lists if the parent value is set to 0
10563 if ($(this).val() == 0){
10564 $("#"+child_list).hide();
10570 setListDependencies'.$type.
'();
10585 return $this->getRightsForUser($user);
10598 $element = $this->element;
10602 $rights = $user->hasRight(
$module, $element);
10605 if (!is_object($rights) || isset($rights->read) || isset($rights->write) || isset($rights->delete) || isset($rights->lire) || isset($rights->creer) || isset($rights->supprimer)) {
10610 return isset($user->rights->$element) ? $user->rights->$element :
null;
10625 $rights = $this->getRightsForUser($user);
10626 if (is_int($rights)) {
10628 return $rights === 1;
10630 if (!is_object($rights)) {
10634 if ($mode ==
'read') {
10635 return !empty($rights->lire) || !empty($rights->read);
10637 if ($mode ==
'create' || $mode ==
'write') {
10638 return !empty($rights->creer) || !empty($rights->write);
10640 if ($mode ==
'delete') {
10641 return !empty($rights->supprimer) || !empty($rights->delete);
10658 return $this->hasUserPermissionOnField($user, $field,
'write');
10673 if (empty($field)) {
10677 return $this->hasUserPermission($user, $mode);
10702 if (!$byPassUserPermission && !$this->hasUserPermissionOnField($user, $field,
'write')) {
10707 if (!$this->isFieldDefined($field)) {
10712 if ($this->isFieldDisabled($field)) {
10717 if (!$this->isFieldEnabled($field)) {
10722 if ($this->isFieldMarkedNotEditable($field)) {
10727 if ($this->isFieldBlockedByObjectState($field)) {
10751 if (!$this->isFieldDefined($field) || empty($this->fields[$field][
'uieditable'])) {
10755 if ($field ==
'note_private' && !empty($user->socid)) {
10759 return $this->isFieldEditAllowed($user, $field);
10777 if (!$this->isFieldDefined($field) || !$this->isFieldEnabled($field)) {
10781 if (preg_match(
'/^password/', (
string) $this->fields[$field][
'type'])) {
10785 if ($field ==
'note_private' && !empty($user->socid)) {
10789 if (!empty($this->fields[$field][
'uieditable'])) {
10793 $visible = isset($this->fields[$field][
'visible']) ? $this->fields[$field][
'visible'] : 0;
10794 if (!is_numeric($visible)) {
10795 $visible =
dol_eval((
string) $visible);
10798 return in_array(abs((
int) $visible), array(1, 3, 4, 5));
10810 return !empty($this->fields)
10811 && is_array($this->fields)
10812 && isset($this->fields[$field]);
10823 return !empty($this->fields[$field][
'disabled']);
10834 return !empty($this->fields[$field][
'validate']);
10848 return !isset($this->fields[$field][
'enabled']) || (bool) (
int)
dol_eval((
string) $this->fields[$field][
'enabled']);
10859 return !empty($this->fields[$field][
'noteditable']);
10878 if (!empty($this->fields[$field][
'alwayseditable'])) {
10882 if (!defined(static::class.
'::STATUS_DRAFT')) {
10886 $draftStatus = (int) constant(static::class.
'::STATUS_DRAFT');
10888 return (isset($this->
status) && (int) $this->
status !== $draftStatus)
10889 || (isset($this->statut) && (int) $this->statut !== $draftStatus);
10906 global $hookmanager;
10908 $parameters = array(
10909 'origin_id' => $origin_id,
10910 'dest_id' => $dest_id,
10911 'tables' => $tables,
10913 $reshook = $hookmanager->executeHooks(
'commonReplaceThirdparty', $parameters);
10916 } elseif ($reshook < 0) {
10917 return $ignoreerrors === 1;
10920 foreach ($tables as $table) {
10921 $sql =
'UPDATE '.$dbs->prefix().$table.
' SET fk_soc = '.((int) $dest_id).
' WHERE fk_soc = '.((int) $origin_id);
10923 if (!$dbs->
query($sql)) {
10924 if ($ignoreerrors) {
10949 foreach ($tables as $table) {
10950 $sql =
'UPDATE '.MAIN_DB_PREFIX.$table.
' SET fk_product = '.((int) $dest_id).
' WHERE fk_product = '.((int) $origin_id);
10952 if (!$dbs->
query($sql)) {
10953 if ($ignoreerrors) {
10980 global $hookmanager;
10984 if (!preg_match(
'/^[a-z0-9_]+$/', $fieldname)) {
10985 dol_syslog(__METHOD__.
' Refused an invalid column name: '.$fieldname, LOG_ERR);
10989 $parameters = array(
10990 'origin_id' => $origin_id,
10991 'dest_id' => $dest_id,
10992 'tables' => $tables,
10993 'fieldname' => $fieldname,
10995 $reshook = $hookmanager->executeHooks(
'commonReplaceContact', $parameters);
10996 if ($reshook > 0) {
10998 } elseif ($reshook < 0) {
10999 return $ignoreerrors === 1;
11002 foreach ($tables as $table) {
11003 if (!preg_match(
'/^[a-z0-9_]+$/', $table)) {
11004 dol_syslog(__METHOD__.
' Refused an invalid table name: '.$table, LOG_ERR);
11008 $sanitizedtable = $dbs->
sanitize($table);
11009 $sanitizedfieldname = $dbs->
sanitize($fieldname);
11011 $sql =
"UPDATE ".$dbs->prefix().$sanitizedtable;
11012 $sql .=
" SET ".$sanitizedfieldname.
" = ".((int) $dest_id);
11013 $sql .=
" WHERE ".$sanitizedfieldname.
" = ".((int) $origin_id);
11015 if (!$dbs->
query($sql)) {
11016 if ($ignoreerrors) {
11039 public function defineBuyPrice($unitPrice = 0.0, $discountPercent = 0.0, $fk_product = 0, $qty = 0)
11045 if (($unitPrice > 0) && (isset(
$conf->global->ForceBuyingPriceIfNull) &&
getDolGlobalInt(
'ForceBuyingPriceIfNull') > 0)) {
11047 $buyPrice = $unitPrice * (1 - $discountPercent / 100);
11050 if (!empty($fk_product) && $fk_product > 0) {
11053 require_once DOL_DOCUMENT_ROOT.
'/product/class/product.class.php';
11054 $product =
new Product($this->db);
11055 $result = $product->fetch($fk_product);
11056 if ($result <= 0) {
11057 $this->errors[] =
'ErrorProductIdDoesNotExists';
11060 if ($product->cost_price > 0) {
11061 $buyPrice = $product->cost_price;
11062 } elseif ($product->pmp > 0) {
11063 $buyPrice = $product->pmp;
11066 require_once DOL_DOCUMENT_ROOT.
'/product/class/product.class.php';
11067 $product =
new Product($this->db);
11068 $result = $product->fetch($fk_product);
11069 if ($result <= 0) {
11070 $this->errors[] =
'ErrorProductIdDoesNotExists';
11073 if ($product->pmp > 0) {
11074 $buyPrice = $product->pmp;
11078 if (empty($buyPrice) && in_array(
getDolGlobalString(
'MARGIN_TYPE'), array(
'1',
'pmp',
'costprice'))) {
11079 require_once DOL_DOCUMENT_ROOT.
'/fourn/class/fournisseur.product.class.php';
11081 $result = $productFournisseur->find_min_price_product_fournisseur($fk_product, $qty);
11082 if ($result == 0 && $qty > 0) {
11084 $result = $productFournisseur->find_min_price_product_fournisseur($fk_product);
11087 $buyPrice = $productFournisseur->fourn_unitprice;
11088 } elseif ($result < 0) {
11089 $this->errors[] = $productFournisseur->error;
11096 return (
float) $buyPrice;
11112 $documents = array();
11114 if (!
getDolGlobalString(
'MARGIN_CAN_UPDATE_BUYINGPRICE_ON_LINKED_DOCUMENTS') || !$user->hasRight(
'margins',
'creer')) {
11118 $sql =
"SELECT fk_product, ".($this->element ==
'order_supplier' ?
"subprice * (1 - remise_percent / 100)" :
"buy_price_ht").
" as buy_price_ht FROM ".$this->db->prefix().$this->table_element_line;
11119 $sql .=
" WHERE rowid = ".((int) $lineid).
" AND ".$this->db->sanitize($this->fk_element).
" = ".((int) $this->
id);
11120 $resql = $this->db->query($sql);
11121 $line = ($resql ? $this->db->fetch_object($resql) :
null);
11122 if (!$line || $line->fk_product <= 0 || $line->buy_price_ht <= 0 || (isset($oldbuyprice) &&
price2num($oldbuyprice,
'MU') ==
price2num($line->buy_price_ht,
'MU'))) {
11127 $this->fetchObjectLinked(
null,
'',
null,
'',
'OR', 1,
'sourcetype', 0);
11129 if ($this->element ==
'order_supplier') {
11131 $orderids = array((
int) $this->
id);
11132 $sql =
"SELECT fk_source, sourcetype, fk_target, targettype FROM ".$this->db->prefix().
"element_element WHERE 1 = 0";
11133 foreach (array(
'propal',
'commande',
'facture') as $element) {
11134 $linkedids = array_map(
'intval', $this->linkedObjectsIds[$element] ?? array());
11136 $sql .=
" OR (sourcetype = '".$this->db->escape($element).
"' AND fk_source IN (".$this->db->sanitize(implode(
',', $linkedids)).
") AND targettype = 'order_supplier')";
11137 $sql .=
" OR (targettype = '".$this->db->escape($element).
"' AND fk_target IN (".$this->db->sanitize(implode(
',', $linkedids)).
") AND sourcetype = 'order_supplier')";
11140 $resql = $this->db->query($sql);
11141 while ($resql && $obj = $this->db->fetch_object($resql)) {
11142 $orderids[] = (int) ($obj->targettype ==
'order_supplier' ? $obj->fk_target : $obj->fk_source);
11146 $sql =
"SELECT SUM(d.qty * d.subprice * (1 - d.remise_percent / 100)) / SUM(d.qty) as cost";
11147 $sql .=
" FROM ".$this->db->prefix().$this->table_element.
" as t, ".$this->db->prefix().$this->table_element_line.
" as d";
11148 $sql .=
" WHERE d.".$this->db->sanitize($this->fk_element).
" = t.rowid AND t.entity IN (".
getEntity($this->table_element).
")";
11149 $sql .=
" AND t.rowid IN (".$this->db->sanitize(implode(
',', $orderids)).
")";
11150 $sql .=
" AND (t.rowid = ".((int) $this->
id).
" OR t.fk_statut BETWEEN 3 AND 5)";
11151 $sql .=
" AND d.fk_product = ".((int) $line->fk_product).
" AND d.qty > 0";
11152 $resql = $this->db->query($sql);
11153 $obj = ($resql ? $this->db->fetch_object($resql) :
null);
11154 if ($obj && $obj->cost > 0) {
11155 $line->buy_price_ht = $obj->cost;
11159 foreach (array(
'propal',
'commande',
'facture') as $element) {
11161 foreach ($this->linkedObjectsIds[$element] ?? array() as
$id) {
11162 if (
restrictedArea($user, $element,
$id,
'',
'',
'fk_soc',
'rowid', 0, 1,
'write')) {
11163 $ids[] = (int)
$id;
11169 $sql =
"SELECT d.rowid, d.buy_price_ht, t.ref FROM ".$this->db->prefix().$element.
" as t, ".$this->db->prefix().$element.
"det as d";
11170 $sql .=
" WHERE d.fk_".$this->db->sanitize($element).
" = t.rowid AND t.entity IN (".
getEntity($element).
")";
11171 $sql .=
" AND t.rowid IN (".$this->db->sanitize(implode(
',', $ids)).
")";
11172 $sql .=
" AND d.fk_product = ".((int) $line->fk_product);
11173 $resql = $this->db->query($sql);
11174 while ($resql && $obj = $this->db->fetch_object($resql)) {
11176 $documents[$element][
'refs'][$obj->ref] = $obj->ref;
11177 $documents[$element][
'lineids'][] = (int) $obj->rowid;
11178 $documents[$element][
'buyprice'] = (float) $line->buy_price_ht;
11198 $this->db->begin();
11199 foreach ($this->getLinkedBuyPriceDocuments($user, $lineid) as $element => $document) {
11200 if (empty($elements[$element])) {
11203 $sql =
"UPDATE ".$this->db->prefix().$element.
"det SET buy_price_ht = ".((float) $document[
'buyprice']);
11204 $sql .=
" WHERE rowid IN (".$this->db->sanitize(implode(
',', $document[
'lineids'])).
")";
11205 if (!$this->db->query($sql)) {
11206 $this->error = $this->db->lasterror();
11207 $this->db->rollback();
11210 $nbupdated += count($document[
'lineids']);
11212 $this->db->commit();
11227 return array(
'dir' =>
'',
'file' =>
'',
'originalfile' =>
'',
'altfile' =>
'',
'email' =>
'',
'capture' =>
'');
11251 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')
11254 global $user, $langs;
11256 include_once DOL_DOCUMENT_ROOT.
'/core/lib/files.lib.php';
11257 include_once DOL_DOCUMENT_ROOT.
'/core/lib/images.lib.php';
11258 include_once DOL_DOCUMENT_ROOT.
'/core/class/link.class.php';
11260 $sortfield =
'position_name';
11261 $sortorder =
'asc';
11266 $dir .=
get_exdir(0, 0, 0, 0, $this, $modulepart);
11267 $pdir .=
get_exdir(0, 0, 0, 0, $this, $modulepart);
11270 if ($modulepart ==
'product') {
11272 $dir = $sdir.
'/'.
get_exdir($this->
id, 2, 0, 0, $this, $modulepart).$this->id.
"/photos/";
11273 $pdir =
'/'.get_exdir($this->
id, 2, 0, 0, $this, $modulepart).$this->id.
"/photos/";
11276 if ($modulepart ==
'category') {
11277 $dir = $sdir.
'/'.
get_exdir($this->
id, 2, 0, 0, $this, $modulepart).$this->id.
"/photos/";
11278 $pdir =
'/'.get_exdir($this->
id, 2, 0, 0, $this, $modulepart).$this->id.
"/photos/";
11284 $relativedir = preg_replace(
'/^'.preg_quote(DOL_DATA_ROOT,
'/').
'/',
'', $dir);
11285 $relativedir = preg_replace(
'/^[\\/]/',
'', $relativedir);
11286 $relativedir = preg_replace(
'/[\\/]$/',
'', $relativedir);
11289 $dirthumb = $dir.
'thumbs/';
11290 $pdirthumb = $pdir.
'thumbs/';
11292 $return =
'<!-- Photo -->'.
"\n";
11295 $filearray =
dol_dir_list($dir,
"files", 0,
'',
'(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) ==
'desc' ? SORT_DESC : SORT_ASC), 1);
11304 '@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';
11306 $useLinkPathPhoto =
false;
11309 $link =
new Link($this->db);
11311 $link->fetchAll($links,
'product', $this->
id);
11313 if (count($links) > 0) {
11314 $useLinkPathPhoto =
true;
11317 if ($useLinkPathPhoto) {
11319 if ($nbbyrow > 0) {
11320 $return .=
'<table class="valigntop center centpercent" style="border:0; padding:2px; border-spacing:2px; border-collapse: separate;">';
11324 foreach ($links as $link) {
11325 if (!empty($link->url) && preg_match(
'/\.(jpg|jpeg|png|gif|webp)$/i', $link->url)) {
11330 if ($nbbyrow > 0 && ($i % $nbbyrow == 1)) {
11331 $return .=
'<tr class="center valignmiddle">';
11334 if ($nbbyrow > 0) {
11335 $return .=
'<td style="width:'.ceil(100 / $nbbyrow).
'%" class="photo">';
11337 $return .=
'<div class="inline-block">';
11340 $return .=
'<img class="photo photowithmargin'.($addphotorefcss ?
' '.$addphotorefcss :
'').
'"'.($maxHeight ?
' height="'.$maxHeight.
'"' :
'').
' src="'.$url.
'" title="External image">';
11342 if ($nbbyrow > 0) {
11343 $return .=
'</td>';
11344 if ($i % $nbbyrow == 0) {
11345 $return .=
'</tr>';
11348 $return .=
'</div>';
11351 if ($nbmax && $nbphoto >= $nbmax) {
11357 if ($nbbyrow > 0) {
11358 while ($i % $nbbyrow) {
11359 $return .=
'<td style="width:'.ceil(100 / $nbbyrow).
'%"> </td>';
11363 $return .=
'</table>';
11369 if (count($filearray)) {
11370 if ($sortfield && $sortorder) {
11371 $filearray =
dol_sort_array($filearray, $sortfield, $sortorder);
11374 foreach ($filearray as $key => $val) {
11376 $file = $val[
'name'];
11382 $viewfilename = $file;
11384 if ($size == 1 || $size ==
'small') {
11390 $pdirthumb = $pdir;
11391 $photo_vignette = basename($file);
11397 if ($nbbyrow > 0) {
11398 if ($nbphoto == 1) {
11399 $return .=
'<table class="valigntop center centpercent" style="border: 0; padding: 2px; border-spacing: 2px; border-collapse: separate;">';
11402 if ($nbphoto % $nbbyrow == 1) {
11403 $return .=
'<tr class="center valignmiddle" style="border: 1px">';
11405 $return .=
'<td style="width: '.ceil(100 / $nbbyrow).
'%" class="photo">'.
"\n";
11406 } elseif ($nbbyrow < 0) {
11407 $return .=
'<div class="inline-block">'.
"\n";
11410 $relativefile = preg_replace(
'/^\//',
'', $pdir.$photo);
11411 if (empty($nolink)) {
11413 if ($urladvanced) {
11414 $return .=
'<a href="'.$urladvanced.
'">';
11416 $return .=
'<a href="'.DOL_URL_ROOT.
'/viewimage.php?modulepart='.$modulepart.
'&entity='.$this->entity.
'&file='.urlencode($pdir.$photo).
'" class="aphoto" target="_blank" rel="noopener noreferrer">';
11422 $alt = $langs->transnoentitiesnoconv(
'File').
': '.$relativefile;
11423 $alt .=
' - '.$langs->transnoentitiesnoconv(
'Size').
': '.$imgarray[
'width'].
'x'.$imgarray[
'height'];
11424 if ($overwritetitle) {
11425 if (is_numeric($overwritetitle)) {
11428 $alt = $overwritetitle;
11431 if (empty($cache) && !empty($val[
'label'])) {
11434 $cache = $val[
'label'];
11436 if ($usesharelink) {
11437 if (array_key_exists(
'share', $val) && $val[
'share']) {
11438 if (empty($maxHeight) || ($photo_vignette && $imgarray[
'height'] > $maxHeight)) {
11439 $return .=
'<!-- Show original file (thumb not yet available with shared links) -->';
11440 $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).
'">';
11442 $return .=
'<!-- Show original file -->';
11443 $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).
'">';
11446 $return .=
'<!-- Show nophoto file (because file is not shared) -->';
11447 $return .=
'<img class="photo photowithmargin'.($addphotorefcss ?
' '.$addphotorefcss :
'').
'" height="'.$maxHeight.
'" src="'.DOL_URL_ROOT.
'/public/theme/common/nophoto.png" title="'.
dol_escape_htmltag($alt).
'">';
11450 if (empty($maxHeight) || ($photo_vignette && $imgarray[
'height'] > $maxHeight)) {
11451 $return .=
'<!-- Show thumb -->';
11452 $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).
'">';
11454 $return .=
'<!-- Show original file -->';
11455 $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).
'">';
11459 if (empty($nolink)) {
11463 if ($showfilename) {
11464 $return .=
'<br>'.$viewfilename;
11469 if ($photo_vignette && (
image_format_supported($photo) > 0) && ((isset($imgarray[
'width']) && $imgarray[
'width'] > $maxWidth) || (isset($imgarray[
'width']) && $imgarray[
'width'] > $maxHeight))) {
11470 $return .=
'<a href="'.$_SERVER[
"PHP_SELF"].
'?id='.$this->
id.
'&action=addthumb&token='.
newToken().
'&file='.urlencode($pdir.$viewfilename).
'">'.img_picto($langs->trans(
'GenerateThumb'),
'refresh').
' </a>';
11473 if ($modulepart ==
'product' && ($user->hasRight(
'produit',
'creer') || $user->hasRight(
'service',
'creer'))) {
11475 $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> ';
11478 $return .=
'<a href="'.$_SERVER[
"PHP_SELF"].
'?id='.$this->
id.
'&action=delete&token='.
newToken().
'&file='.urlencode($pdir.$viewfilename).
'">';
11479 $return .= img_delete().
'</a>';
11484 if ($nbbyrow > 0) {
11485 $return .=
'</td>';
11486 if (($nbphoto % $nbbyrow) == 0) {
11487 $return .=
'</tr>';
11489 } elseif ($nbbyrow < 0) {
11490 $return .=
'</div>'.
"\n";
11494 if (empty($size)) {
11495 $return .=
'<img class="photo photowithmargin" src="'.DOL_URL_ROOT.
'/viewimage.php?modulepart='.$modulepart.
'&entity='.$this->entity.
'&file='.urlencode($pdir.$photo).
'">';
11497 if ($showfilename) {
11498 $return .=
'<br>'.$viewfilename;
11502 if ($modulepart ==
'product' && ($user->hasRight(
'produit',
'creer') || $user->hasRight(
'service',
'creer'))) {
11504 $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> ';
11507 $return .=
'<a href="'.$_SERVER[
"PHP_SELF"].
'?id='.$this->
id.
'&action=delete&token='.
newToken().
'&file='.urlencode($pdir.$viewfilename).
'">';
11508 $return .= img_delete().
'</a>';
11514 if ($nbmax && $nbphoto >= $nbmax) {
11520 if ($size == 1 || $size ==
'small') {
11521 if ($nbbyrow > 0) {
11523 while ($nbphoto % $nbbyrow) {
11524 $return .=
'<td style="width: '.ceil(100 / $nbbyrow).
'%"> </td>';
11529 $return .=
'</table>';
11535 $this->nbphoto = $nbphoto;
11549 if (is_array($info)) {
11550 if (isset($info[
'type']) && $info[
'type'] ==
'array') {
11567 if (isset($info[
'type']) && ($info[
'type'] ==
'date' || $info[
'type'] ==
'datetime' || $info[
'type'] ==
'timestamp')) {
11581 if (is_array($info)) {
11582 if (isset($info[
'type']) && ($info[
'type'] ==
'duration')) {
11600 if (is_array($info)) {
11601 if (isset($info[
'type']) && (preg_match(
'/^(?:tiny|small|medium|big)?int|int$/i', $info[
'type']))) {
11619 if (is_array($info)) {
11620 if (isset($info[
'type']) && (preg_match(
'/^(double|real|price)/i', $info[
'type']))) {
11637 if (is_array($info)) {
11638 if (isset($info[
'type']) && $info[
'type'] ==
'text') {
11655 if (is_array($info)) {
11656 if (array_key_exists(
'notnull', $info) && $info[
'notnull'] !=
'1') {
11673 if (is_array($info)) {
11674 if (array_key_exists(
'notnull', $info) && $info[
'notnull'] ==
'-1') {
11691 if (is_array($info)) {
11692 if (array_key_exists(
'index', $info) && $info[
'index'] ==
true) {
11715 $queryarray = array();
11716 foreach ($this->fields as $field => $info) {
11718 if ($this->isDate($info)) {
11719 if (empty($this->{$field})) {
11720 $queryarray[$field] =
null;
11722 $queryarray[$field] = $this->db->idate($this->{$field});
11724 } elseif ($this->isDuration($info)) {
11726 if ((isset($this->{$field}) && $this->{$field} !=
'') || !empty($info[
'notnull'])) {
11727 if (!isset($this->{$field})) {
11728 if (!empty($info[
'default'])) {
11729 $queryarray[$field] = $info[
'default'];
11731 $queryarray[$field] = 0;
11734 $queryarray[$field] = (int) $this->{$field};
11737 $queryarray[$field] =
null;
11739 } elseif ($this->isInt($info) || $this->isFloat($info)) {
11740 if ($field ==
'entity' && is_null($this->{$field})) {
11741 $queryarray[$field] = ((int)
$conf->entity);
11744 if ((isset($this->{$field}) && ((
string) $this->{$field}) !=
'') || !empty($info[
'notnull'])) {
11745 if (!isset($this->{$field})) {
11746 $queryarray[$field] = 0;
11747 } elseif ($this->isInt($info)) {
11748 $queryarray[$field] = (int) $this->{$field};
11749 } elseif ($this->isFloat($info)) {
11750 $queryarray[$field] = (float) $this->{$field};
11753 $queryarray[$field] =
null;
11759 $queryarray[$field] = $this->{$field};
11762 if (is_array($info) && array_key_exists(
'type', $info) && !empty($info[
'type']) && $info[
'type'] ==
'timestamp' && empty($queryarray[$field])) {
11763 unset($queryarray[$field]);
11765 if (!empty($info[
'notnull']) && $info[
'notnull'] == -1 && empty($queryarray[$field])) {
11766 $queryarray[$field] =
null;
11770 return $queryarray;
11783 foreach ($this->fields as $field => $info) {
11784 if ($this->isDate($info)) {
11785 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') {
11786 $this->$field =
'';
11788 $this->$field = $db->jdate($obj->$field);
11790 } elseif ($this->isInt($info)) {
11791 if ($field ==
'rowid') {
11792 $this->
id = (int) $obj->$field;
11794 if ($this->isForcedToNullIfZero($info)) {
11795 if (empty($obj->$field)) {
11796 $this->$field =
null;
11798 $this->$field = (int) $obj->$field;
11801 if (isset($obj->$field) && (!is_null($obj->$field) || (array_key_exists(
'notnull', $info) && $info[
'notnull'] == 1))) {
11802 $this->$field = (int) $obj->$field;
11804 $this->$field =
null;
11808 } elseif ($this->isFloat($info)) {
11809 if ($this->isForcedToNullIfZero($info)) {
11810 if (empty($obj->$field)) {
11811 $this->$field =
null;
11813 $this->$field = (float) $obj->$field;
11816 if (isset($obj->$field) && (!is_null($obj->$field) || (array_key_exists(
'notnull', $info) && $info[
'notnull'] == 1))) {
11817 $this->$field = (float) $obj->$field;
11819 $this->$field =
null;
11823 $this->$field = isset($obj->$field) ? $obj->$field :
null;
11828 if (!isset($this->fields[
'ref']) && isset($this->
id)) {
11829 $this->
ref = (string) $this->
id;
11839 foreach ($this->fields as $field => $arr) {
11840 $this->$field =
null;
11853 $keys = array_keys($this->fields);
11854 if (!empty($alias)) {
11855 $keys_with_alias = array();
11856 foreach ($keys as $fieldname) {
11857 if (!empty($excludefields)) {
11858 if (in_array($fieldname, $excludefields)) {
11862 $keys_with_alias[] = $this->db->sanitize($alias .
'.' . $fieldname);
11864 return implode(
', ', $keys_with_alias);
11866 return implode(
', ', $keys);
11877 protected function quote($value, $fieldsentry)
11879 if (is_null($value)) {
11881 } elseif (preg_match(
'/^(int|double|real|price)/i', $fieldsentry[
'type'])) {
11883 } elseif (preg_match(
'/int$/i', $fieldsentry[
'type'])) {
11884 return (
int) $value;
11885 } elseif ($fieldsentry[
'type'] ==
'boolean') {
11892 return "'".$this->db->escape($value).
"'";
11909 dol_syslog(get_class($this).
"::createCommon create", LOG_DEBUG);
11915 $fieldvalues = $this->setSaveQuery();
11919 if (array_key_exists(
'date_creation', $fieldvalues) && empty($fieldvalues[
'date_creation'])) {
11920 $fieldvalues[
'date_creation'] = $this->db->idate($now);
11921 $this->date_creation = $this->db->idate($now);
11924 if (array_key_exists(
'fk_user_creat', $fieldvalues) && !($fieldvalues[
'fk_user_creat'] > 0)) {
11925 $fieldvalues[
'fk_user_creat'] = $user->id;
11926 $this->fk_user_creat = $user->id;
11928 if (array_key_exists(
'user_creation_id', $fieldvalues) && !($fieldvalues[
'user_creation_id'] > 0)) {
11929 $fieldvalues[
'user_creation_id'] = $user->id;
11930 $this->user_creation_id = $user->id;
11932 if (array_key_exists(
'pass_crypted', $fieldvalues) && property_exists($this,
'pass')) {
11934 $tmparray =
dol_hash($this->pass,
'0', 0, 1);
11935 $fieldvalues[
'pass_crypted'] = $tmparray[
'pass_encrypted'];
11936 if (array_key_exists(
'pass_encoding', $fieldvalues) && property_exists($this,
'pass_encoding')) {
11937 $fieldvalues[
'pass_encoding'] = $tmparray[
'pass_encoding'];
11940 if (array_key_exists(
'ref', $fieldvalues)) {
11943 if (
getDolGlobalString(
'MAIN_DISABLE_AUTO_UPDATE_OF_TMS_FIELDS') && array_key_exists(
'tms', $fieldvalues)) {
11944 $fieldvalues[
'tms'] = $this->db->idate($now);
11947 unset($fieldvalues[
'rowid']);
11949 $sanitized_keys = array();
11950 $sanitized_values = array();
11951 foreach ($fieldvalues as $k => $v) {
11952 $sanitized_keys[$k] = $k;
11953 $value = $this->fields[$k];
11955 $sanitized_values[$k] = $this->quote($v, $value);
11959 foreach ($sanitized_keys as $key) {
11960 if (!isset($this->fields[$key])) {
11963 $key_fields = $this->fields[$key];
11966 if (preg_match(
'/^integer:/i', $key_fields[
'type']) && $sanitized_values[$key] ==
'-1') {
11967 $sanitized_values[$key] =
'';
11969 if (!empty($key_fields[
'foreignkey']) && $sanitized_values[$key] ==
'-1') {
11970 $sanitized_values[$key] =
'';
11973 if (isset($key_fields[
'notnull']) && $key_fields[
'notnull'] == 1 && (!isset($sanitized_values[$key]) || $sanitized_values[$key] ===
'NULL') && (!isset($key_fields[
'default']) || is_null($key_fields[
'default']))) {
11976 if (empty($langs)) {
11977 require_once DOL_DOCUMENT_ROOT.
'/core/class/translate.class.php';
11979 $langs->setDefaultLang();
11980 $langs->load(
"errors");
11982 dol_syslog(
"Mandatory field '".$key.
"' is empty and required into ->fields definition of class");
11983 $this->errors[] = $langs->trans(
"ErrorFieldRequired", isset($key_fields[
'label']) ? $key_fields[
'label'] : $key);
11987 if (isset($key_fields[
'notnull']) && $key_fields[
'notnull'] == 1 && (!isset($sanitized_values[$key]) || $sanitized_values[$key] ===
'NULL') && array_key_exists(
'default', $key_fields) && !is_null($key_fields[
'default'])) {
11988 $sanitized_values[$key] = $this->quote($key_fields[
'default'], $key_fields);
11992 if (isset($key_fields[
'type']) && preg_match(
'/^integer:/i', $key_fields[
'type']) && empty($sanitized_values[$key])) {
11993 if (isset($key_fields[
'default'])) {
11994 $sanitized_values[$key] = ((int) $key_fields[
'default']);
11996 $sanitized_values[$key] =
'null';
11999 if (!empty($key_fields[
'foreignkey']) && empty($sanitized_values[$key])) {
12000 $sanitized_values[$key] =
'null';
12008 $this->db->begin();
12011 $sql =
"INSERT INTO ".$this->db->prefix().$this->db->sanitize($this->table_element);
12012 $sql .=
" (".implode(
", ", $sanitized_keys).
')';
12013 $sql .=
" VALUES (".implode(
", ", $sanitized_values).
")";
12015 $res = $this->db->query($sql);
12018 if ($this->db->lasterrno() ==
'DB_ERROR_RECORD_ALREADY_EXISTS') {
12019 $this->errors[] =
"ErrorRefAlreadyExists";
12021 $this->errors[] = $this->db->lasterror();
12027 $this->
id = $this->db->last_insert_id($this->db->prefix().$this->table_element);
12033 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)') {
12034 $sql =
"UPDATE ".$this->db->prefix().$this->db->sanitize($this->table_element);
12035 $sql .=
" SET ref = '(PROV".((int) $this->
id).
")' WHERE (ref = '(PROV)' OR ref = '') AND rowid = ".((int) $this->
id);
12036 $resqlupdate = $this->db->query($sql);
12038 if ($resqlupdate ===
false) {
12040 $this->errors[] = $this->db->lasterror();
12042 $this->
ref =
'(PROV'.$this->id.
')';
12049 $result = $this->insertExtraFields();
12056 if (!empty($this->table_element_line) && !empty($this->fk_element) && !empty($this->lines)) {
12057 foreach ($this->lines as $line) {
12058 $keyforparent = $this->fk_element;
12063 if (!is_object($line)) {
12064 $line = (object) $line;
12068 if (method_exists($line,
'insert')) {
12069 $result = $line->insert($user, 1);
12070 } elseif (method_exists($line,
'create')) {
12071 $result = $line->create($user, 1);
12074 $this->error = $line->error;
12075 $this->db->rollback();
12082 if (!$error && !$notrigger) {
12084 $triggerPrefix = (empty($this->TRIGGER_PREFIX) ? strtoupper(get_class($this)) : $this->TRIGGER_PREFIX);
12085 $result = $this->call_trigger($triggerPrefix.
'_CREATE', $user);
12094 $this->db->rollback();
12097 $this->db->commit();
12114 if (empty(
$id) && empty($ref) && empty($morewhere)) {
12118 $fieldlist = $this->getFieldList(
't');
12119 if (empty($fieldlist)) {
12123 $sql =
"SELECT ".$this->db->sanitize($fieldlist, 0, 0, 1);
12124 $sql .=
" FROM ".$this->db->prefix().$this->table_element.
' as t';
12127 $sql .=
' WHERE t.rowid = '.((int)
$id);
12128 } elseif (!empty($ref)) {
12129 $sql .=
" WHERE t.ref = '".$this->db->escape($ref).
"'";
12131 $sql .=
' WHERE 1 = 1';
12133 if (empty(
$id) && isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
12134 $sql .=
' AND t.entity IN ('.getEntity($this->element).
')';
12137 $sql .= $morewhere;
12139 $sql .=
' LIMIT 1';
12141 $res = $this->db->query($sql);
12143 $obj = $this->db->fetch_object($res);
12145 $this->setVarsFromFetchObj($obj);
12149 if (empty($noextrafields)) {
12150 $result = $this->fetch_optionals();
12152 $this->error = $this->db->lasterror();
12153 $this->errors[] = $this->error;
12163 $this->error = $this->db->lasterror();
12164 $this->errors[] = $this->error;
12178 $objectlineclassname = get_class($this).
'Line';
12179 if (!class_exists($objectlineclassname)) {
12180 $this->error =
'Error, class '.$objectlineclassname.
' not found during call of fetchLinesCommon';
12184 $objectline =
new $objectlineclassname($this->db);
12185 '@phan-var-force CommonObjectLine $objectline';
12187 $sql =
"SELECT ".$objectline->getFieldList(
'l');
12188 $sql .=
" FROM ".$this->db->prefix().$this->db->sanitize($objectline->table_element).
" as l";
12189 $sql .=
" WHERE l.fk_".$this->db->sanitize($this->element).
" = ".((int) $this->
id);
12191 $sql .= $morewhere;
12193 if (isset($objectline->fields[
'position'])) {
12194 $sql .= $this->db->order(
'position',
'ASC');
12197 $resql = $this->db->query($sql);
12199 $num_rows = $this->db->num_rows($resql);
12201 $this->lines = array();
12202 while ($i < $num_rows) {
12203 $obj = $this->db->fetch_object($resql);
12205 $newline =
new $objectlineclassname($this->db);
12206 '@phan-var-force CommonObjectLine $newline';
12207 $newline->setVarsFromFetchObj($obj);
12210 if (empty($noextrafields)) {
12211 $newline->fetch_optionals();
12214 $this->lines[] = $newline;
12221 $this->error = $this->db->lasterror();
12222 $this->errors[] = $this->error;
12236 dol_syslog(get_class($this).
"::updateCommon update", LOG_DEBUG);
12248 $fieldvalues = $this->setSaveQuery();
12252 if (array_key_exists(
'date_modification', $fieldvalues)) {
12253 $fieldvalues[
'date_modification'] = $this->db->idate($now);
12255 if (
getDolGlobalString(
'MAIN_DISABLE_AUTO_UPDATE_OF_TMS_FIELDS') && array_key_exists(
'tms', $fieldvalues)) {
12256 $fieldvalues[
'tms'] = $this->db->idate($now);
12258 if (array_key_exists(
'fk_user_modif', $fieldvalues)) {
12259 $fieldvalues[
'fk_user_modif'] = $user->id;
12261 if (array_key_exists(
'user_modification_id', $fieldvalues)) {
12262 $fieldvalues[
'user_modification_id'] = $user->id;
12265 if (array_key_exists(
'pass_crypted', $fieldvalues) && property_exists($this,
'pass') && !empty($this->pass)) {
12267 $tmparray =
dol_hash($this->pass,
'0', 0, 1);
12268 $fieldvalues[
'pass_crypted'] = $tmparray[
'pass_encrypted'];
12269 if (array_key_exists(
'pass_encoding', $fieldvalues) && property_exists($this,
'pass_encoding')) {
12270 $fieldvalues[
'pass_encoding'] = $tmparray[
'pass_encoding'];
12273 if (array_key_exists(
'ref', $fieldvalues)) {
12277 unset($fieldvalues[
'rowid']);
12282 $sanitized_tmp = array();
12283 foreach ($fieldvalues as $k => $v) {
12285 $value = $this->fields[$k];
12287 $values[$k] = $this->quote($v, $value);
12288 if ((!empty($value[
"type"]) && $value[
"type"] ==
"text") && !empty($value[
'arrayofkeyval']) && is_array($value[
'arrayofkeyval'])) {
12290 $v = preg_replace(
'/\s/',
',', $v);
12291 $v = preg_replace(
'/,+/',
',', $v);
12294 $sanitized_tmp[] = $this->db->sanitize($k).
'='.$this->quote($v, $this->fields[$k]);
12298 foreach ($keys as $key) {
12299 if (!empty($this->fields[$key][
'type']) && preg_match(
'/^integer:/i', $this->fields[$key][
'type']) && $values[$key] ==
'-1') {
12300 $values[$key] =
'';
12302 if (!empty($this->fields[$key][
'foreignkey']) && $values[$key] ==
'-1') {
12303 $values[$key] =
'';
12315 $sql =
"UPDATE ".$this->db->prefix().$this->db->sanitize($this->table_element);
12316 $sql .=
" SET ".implode(
', ', $sanitized_tmp);
12317 $sql .=
" WHERE rowid = ".((int) $this->
id);
12319 $this->db->begin();
12322 $res = $this->db->query($sql);
12325 $this->errors[] = $this->db->lasterror();
12331 $result = $this->insertExtraFields();
12338 if (!$error && !$notrigger) {
12340 $triggerPrefix = (empty($this->TRIGGER_PREFIX) ? strtoupper(get_class($this)) : $this->TRIGGER_PREFIX);
12341 $result = $this->call_trigger($triggerPrefix.
'_MODIFY', $user);
12350 $this->db->rollback();
12353 $this->db->commit();
12368 dol_syslog(get_class($this).
"::deleteCommon delete", LOG_DEBUG);
12372 $this->db->begin();
12374 if ($forcechilddeletion) {
12375 foreach ($this->childtables as $table) {
12376 $sql =
"DELETE FROM ".$this->db->prefix().$this->db->sanitize($table);
12377 $sql .=
" WHERE ".$this->db->sanitize($this->fk_element).
" = ".((int) $this->
id);
12378 $resql = $this->db->query($sql);
12380 $this->error = $this->db->lasterror();
12381 $this->errors[] = $this->error;
12382 $this->db->rollback();
12386 } elseif (!empty($this->childtables)) {
12387 $objectisused = $this->isObjectUsed($this->
id);
12388 if (!empty($objectisused)) {
12389 dol_syslog(get_class($this).
"::deleteCommon Can't delete record as it has some child", LOG_WARNING);
12390 $this->error =
'ErrorRecordHasChildren';
12391 $this->errors[] = $this->error;
12392 $this->db->rollback();
12398 if (is_array($this->childtablesoncascade) && !empty($this->childtablesoncascade)) {
12399 foreach ($this->childtablesoncascade as $tabletodelete) {
12400 $deleteFromObject = explode(
':', $tabletodelete, 4);
12401 if (count($deleteFromObject) >= 2) {
12402 $className = str_replace(
'@',
'', $deleteFromObject[0]);
12403 $filePath = $deleteFromObject[1];
12404 $columnName = $deleteFromObject[2];
12406 if (!empty($deleteFromObject[3])) {
12407 $filter = $deleteFromObject[3];
12411 $childObject =
new $className($this->db);
12412 if (method_exists($childObject,
'deleteByParentField')) {
12413 '@phan-var-force CommonObject $childObject';
12414 $result = $childObject->deleteByParentField($this->
id, $columnName, $filter);
12417 $this->errors[] = $childObject->error;
12422 $this->errors[] =
"You defined a cascade delete on an object $className/$this->id but there is no method deleteByParentField for it";
12427 $this->errors[] =
'Cannot include child class file '.$filePath;
12432 $sql =
"DELETE FROM ".$this->db->prefix().$this->db->sanitize($tabletodelete).
" WHERE ".$this->db->sanitize($this->fk_element).
" = ".((int) $this->
id);
12434 $resql = $this->db->query($sql);
12437 $this->error = $this->db->lasterror();
12438 $this->errors[] = $this->error;
12448 $triggerPrefix = (empty($this->TRIGGER_PREFIX) ? strtoupper(get_class($this)) : $this->TRIGGER_PREFIX);
12449 $result = $this->call_trigger($triggerPrefix.
'_DELETE', $user);
12459 $res = $this->deleteEcmFiles(1);
12468 require_once DOL_DOCUMENT_ROOT .
'/core/lib/files.lib.php';
12471 $this->errors[] =
'ErrorFailToDeleteDir';
12477 $res = $this->deleteObjectLinked();
12482 if (!$error && !empty($this->isextrafieldmanaged)) {
12483 $result = $this->deleteExtraFields();
12490 $sql =
"DELETE FROM ".$this->db->prefix().$this->db->sanitize($this->table_element);
12491 $sql .=
" WHERE rowid = ".((int) $this->
id);
12493 $resql = $this->db->query($sql);
12496 $this->errors[] = $this->db->lasterror();
12502 $this->db->rollback();
12505 $this->db->commit();
12530 if (!empty($parentId) && !empty($parentField)) {
12531 if (empty($this->table_element)) {
12532 $this->error =
'Property table_element for object is not defined';
12533 $this->errors[] = $this->error;
12537 if (!method_exists($this,
'fetch')) {
12538 $this->error =
'Method fetch for object is not defined';
12539 $this->errors[] = $this->error;
12543 if (!method_exists($this,
'delete')) {
12544 $this->error =
'Method delete for object is not defined';
12545 $this->errors[] = $this->error;
12550 $this->db->begin();
12552 $sql =
"SELECT rowid FROM ".$this->db->prefix().$this->db->sanitize($this->table_element);
12553 $sql .=
" WHERE ".$this->db->sanitize($parentField).
" = ".(int) $parentId;
12556 $errormessage =
'';
12558 if ($errormessage) {
12559 $this->errors[] = $errormessage;
12560 dol_syslog(__METHOD__.
' '.implode(
',', $this->errors), LOG_ERR);
12564 $resql = $this->db->query($sql);
12566 $this->errors[] = $this->db->lasterror();
12569 while ($obj = $this->db->fetch_object($resql)) {
12570 $result = $this->fetch($obj->rowid);
12573 $this->errors[] = $this->error;
12575 $result = $this->
delete($user);
12578 $this->errors[] = $this->error;
12586 if (empty($error)) {
12587 $this->db->commit();
12590 $this->error = implode(
', ', $this->errors);
12591 $this->db->rollback();
12592 return $error * -1;
12608 if (!($this->
id > 0) || empty($this->table_element_line) || empty($this->fk_element)) {
12612 $sql =
"SELECT rowid FROM ".$this->db->prefix().$this->db->sanitize($this->table_element_line);
12613 $sql .=
" WHERE rowid = ".((int) $lineid).
" AND ".$this->db->sanitize($this->fk_element).
" = ".((int) $this->
id);
12614 $resql = $this->db->query($sql);
12616 return ($resql && $this->db->num_rows($resql) > 0);
12631 $tmpforobjectclass = get_class($this);
12632 $tmpforobjectlineclass = ucfirst($tmpforobjectclass).
'Line';
12634 if ($this->
id > 0 && !empty($this->fk_element)) {
12636 $sql =
"SELECT rowid FROM ".$this->db->prefix().$this->table_element_line;
12637 $sql .=
" WHERE rowid = ".((int) $idline).
" AND ".$this->db->sanitize($this->fk_element).
" = ".((int) $this->
id);
12638 $resql = $this->db->query($sql);
12639 if (!$resql || !$this->db->num_rows($resql)) {
12640 $this->error =
'ErrorLineIDDoesNotMatchWithObjectID';
12645 $this->db->begin();
12648 $result = $this->call_trigger(
'LINE'.strtoupper($tmpforobjectclass).
'_DELETE', $user);
12654 if (empty($error)) {
12655 $sql =
"DELETE FROM ".$this->db->prefix().$this->db->sanitize($this->table_element_line);
12656 $sql .=
" WHERE rowid = ".((int) $idline);
12658 $resql = $this->db->query($sql);
12660 $this->error =
"Error ".$this->db->lasterror();
12665 if (empty($error)) {
12667 $tmpobjectline =
new $tmpforobjectlineclass($this->db);
12668 '@phan-var-force CommonObjectLine $tmpobjectline';
12669 if (!isset($tmpobjectline->isextrafieldmanaged) || !empty($tmpobjectline->isextrafieldmanaged)) {
12670 $tmpobjectline->id = $idline;
12671 $result = $tmpobjectline->deleteExtraFields();
12674 $this->error =
"Error ".get_class($this).
"::deleteLineCommon deleteExtraFields error -4 ".$tmpobjectline->error;
12679 if (empty($error)) {
12680 $this->db->commit();
12683 dol_syslog(get_class($this).
"::deleteLineCommon ERROR:".$this->error, LOG_ERR);
12684 $this->db->rollback();
12704 $this->db->begin();
12706 $statusfield =
'status';
12707 if (in_array($this->element, array(
'don',
'donation',
'shipping',
'project_task'))) {
12708 $statusfield =
'fk_statut';
12711 $sql =
"UPDATE ".$this->db->prefix().$this->db->sanitize($this->table_element);
12712 $sql .=
" SET ".$this->db->sanitize($statusfield).
" = ".((int) $status);
12713 $sql .=
" WHERE rowid = ".((int) $this->
id);
12715 if ($this->db->query($sql)) {
12717 $this->oldcopy = clone $this;
12720 if (!$error && !$notrigger) {
12722 $result = $this->call_trigger($triggercode, $user);
12729 $this->
status = $status;
12730 if (property_exists($this,
'statut')) {
12731 $this->statut = $status;
12733 $this->db->commit();
12736 $this->db->rollback();
12740 $this->error = $this->db->error();
12741 $this->db->rollback();
12757 $this->specimen = 1;
12759 'label' =>
'This is label',
12760 'ref' =>
'ABCD1234',
12761 'description' =>
'This is a description',
12763 'note_public' =>
'Public note',
12764 'note_private' =>
'Private note',
12765 'date_creation' => (
dol_now() - 3600 * 48),
12766 'date_modification' => (
dol_now() - 3600 * 24),
12767 'fk_user_creat' => $user->id,
12768 'fk_user_modif' => $user->id,
12771 foreach ($fields as $key => $value) {
12772 if (array_key_exists($key, $this->fields)) {
12773 $this->{$key} = $value;
12778 if (property_exists($this,
'fields')) {
12779 foreach ($this->fields as $key => $value) {
12781 if (array_key_exists($key, $fields)) {
12785 if (!empty($value[
'default'])) {
12786 $this->$key = $value[
'default'];
12804 require_once DOL_DOCUMENT_ROOT.
'/core/class/comment.class.php';
12806 $comment =
new Comment($this->db);
12807 $result = $comment->fetchAllFor($this->element, $this->
id);
12809 $this->setErrorsFromObject($comment);
12812 $this->comments = $comment->comments;
12814 return count($this->comments);
12824 return count($this->comments);
12835 if (!is_array($parameters)) {
12838 foreach ($parameters as $parameter) {
12839 if (isset($this->$parameter)) {
12840 $this->$parameter = trim($this->$parameter);
12859 require_once DOL_DOCUMENT_ROOT.
'/categories/class/categorie.class.php';
12863 $existing =
$c->containing($this->
id, $type_categ,
'id');
12883 if (!is_array($categories)) {
12884 $categories = array($categories);
12887 dol_syslog(get_class($this).
"::setCategoriesCommon Object Id:".$this->
id.
' type_categ:'.$type_categ.
' nb tag add:'.count($categories), LOG_DEBUG);
12889 require_once DOL_DOCUMENT_ROOT.
'/categories/class/categorie.class.php';
12891 if (empty($type_categ)) {
12892 dol_syslog(__METHOD__.
': Type '.$type_categ.
'is an unknown category type. Done nothing.', LOG_ERR);
12898 $existing =
$c->containing($this->
id, $type_categ,
'id');
12901 if (!is_array($existing)) {
12902 $existing = array();
12904 if ($remove_existing) {
12906 $to_del = array_diff($existing, $categories);
12907 $to_add = array_diff($categories, $existing);
12910 $to_add = array_diff($categories, $existing);
12917 foreach ($to_del as $del) {
12918 if (
$c->fetch($del) > 0) {
12919 $result =
$c->del_type($this, $type_categ);
12922 $this->error =
$c->error;
12923 $this->errors =
$c->errors;
12930 foreach ($to_add as $add) {
12931 if (
$c->fetch($add) > 0) {
12932 $result =
$c->add_type($this, $type_categ);
12935 $this->error =
$c->error;
12936 $this->errors =
$c->errors;
12944 return $error ? (-1 * $error) : $ok;
12957 $this->db->begin();
12959 if (empty($type)) {
12960 $type = $this->table_element;
12963 require_once DOL_DOCUMENT_ROOT.
'/categories/class/categorie.class.php';
12964 $categorystatic =
new Categorie($this->db);
12966 $tablename = $this->db->prefix().
"categorie_".(empty($categorystatic->MAP_CAT_TABLE[$type]) ? $type : $categorystatic->MAP_CAT_TABLE[$type]);
12967 $fkname =
'fk_' . (empty($categorystatic->MAP_CAT_FK[$type]) ? $type : $categorystatic->MAP_CAT_FK[$type]);
12969 $sql =
"INSERT INTO ".$this->db->sanitize($tablename).
" (fk_categorie, ".$this->db->sanitize($fkname).
")";
12970 $sql .=
" SELECT fk_categorie, ".((int) $toId).
" FROM ".$this->db->sanitize($tablename);
12971 $sql .=
" WHERE ".$this->db->sanitize($fkname).
" = ".((int) $fromId);
12973 if (!$this->db->query($sql)) {
12974 $this->error = $this->db->lasterror();
12975 $this->db->rollback();
12979 $this->db->commit();
12993 $this->db->begin();
12997 switch ($this->element) {
12999 $element =
'propale';
13002 $element =
'produit';
13004 case 'order_supplier':
13005 $element =
'fournisseur/commande';
13007 case 'invoice_supplier':
13010 $element =
'fournisseur/facture/'.get_exdir($this->
id, 2, 0, 1, $this,
'invoice_supplier');
13013 $element =
'expedition/sending';
13016 case 'project_task':
13017 require_once DOL_DOCUMENT_ROOT.
'/projet/class/task.class.php';
13019 $project_result = $this->fetchProject();
13020 if ($project_result >= 0) {
13021 $element =
'projet/'.dol_sanitizeFileName($this->project->ref).
'/';
13025 $element =
'contract';
13028 $element = $this->element;
13030 '@phan-var-force string $element';
13033 $sql =
"DELETE FROM ".$this->db->prefix().
"ecm_files_extrafields WHERE fk_object IN (";
13034 $sql .=
" SELECT rowid FROM ".$this->db->prefix().
"ecm_files WHERE filename LIKE '".$this->db->escape($this->
ref).
"%'";
13035 $sql .=
" AND filepath = '".$this->db->escape($element.
"/".$this->ref).
"' AND entity = ".((int)
$conf->entity);
13038 if (!$this->db->query($sql)) {
13039 $this->error = $this->db->lasterror();
13040 $this->db->rollback();
13045 $sql =
"DELETE FROM ".$this->db->prefix().
"ecm_files";
13046 $sql .=
" WHERE filename LIKE '".$this->db->escape($this->
ref).
"%'";
13047 $sql .=
" AND filepath = '".$this->db->escape($element.
"/".$this->ref).
"' AND entity = ".((int)
$conf->entity);
13049 if (!$this->db->query($sql)) {
13050 $this->error = $this->db->lasterror();
13051 $this->db->rollback();
13058 $sql =
'DELETE FROM '.$this->db->prefix().
"ecm_files_extrafields";
13059 $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).
")";
13060 $resql = $this->db->query($sql);
13062 $this->error = $this->db->lasterror();
13063 $this->db->rollback();
13067 $sql =
'DELETE FROM '.$this->db->prefix().
"ecm_files";
13068 $sql .=
" WHERE src_object_type = '".$this->db->escape($this->table_element.(empty($this->module) ?
"" :
"@".$this->module)).
"' AND src_object_id = ".((int) $this->
id);
13069 $resql = $this->db->query($sql);
13071 $this->error = $this->db->lasterror();
13072 $this->db->rollback();
13077 $this->db->commit();
13094 include_once DOL_DOCUMENT_ROOT.
'/product/class/product.class.php';
13097 $tmpproduct =
new Product($this->db);
13098 foreach ($this->lines as $line) {
13099 if ($line->fk_product > 0) {
13100 $tmpproduct->fetch($line->fk_product);
13101 $statustotest = ($status ==
'onsale' ?
'status' :
'status_buy');
13102 if (!$tmpproduct->$statustotest) {
13103 $langs->load(
'products');
13104 $statuskey4lang = ($status ==
'onsale' ?
'ProductStatusNotOnSell' :
'ProductStatusNotOnBuy');
13106 $this->errors[] = $langs->trans(
'ProductRef').
' '.$tmpproduct->ref.
' '.$langs->trans($statuskey4lang);
13112 $this->error =
'ErrorOneLineContainsADisactivatedProduct';
13128 $this->error = $message;
13129 $this->errors[] = $message;
13141 global $dolibarr_main_document_root;
13143 $this->setErrorWithoutLog($message);
13144 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
13145 $file = str_replace($dolibarr_main_document_root,
'', $trace[0][
'file'] ??
'file unknown');
13146 $line = $trace[0][
'line'] ??
'line unknown';
13147 $syslogMessage = sprintf(
'%s:%s %s', $file, $line, $message);
13161 global
$conf, $formfile, $langs;
13163 require_once DOL_DOCUMENT_ROOT .
'/core/lib/functions.lib.php';
13166 if (empty($rootdir)) {
13167 $element = $this->element;
13168 $rootdir =
$conf->$element->multidir_output[$this->entity];
13170 if (!empty($rootdir)) {
13171 $rootdir = rtrim($rootdir,
'/') .
'/';
13173 if (empty($rootdir) || !file_exists($rootdir) || !
dol_is_dir($rootdir)) {
13178 if (empty($relativepath)) {
13181 if (!empty($relativepath)) {
13182 $relativepath = rtrim($relativepath,
'/') .
'/';
13186 $filedir = $rootdir . $relativepath;
13187 if (!empty($filedir)) {
13188 $filedir = rtrim($filedir,
'/') .
'/';
13190 if (empty($filedir) || !file_exists($filedir) || !
dol_is_dir($filedir)) {
13196 $relativefilepath =
'';
13200 $filename = basename($this->last_main_doc);
13201 $filepath = $filedir . $filename;
13202 if (file_exists($filepath) &&
dol_is_file($filepath)) {
13203 $relativefilepath = $relativepath . $filename;
13211 if (is_array($filelist) && !empty($filelist)) {
13215 $relativedir = preg_replace(
'/^' . preg_quote(DOL_DATA_ROOT,
'/') .
'/',
'', $filedir);
13216 $relativedir = preg_replace(
'/^[\\/]/',
'', $relativedir);
13219 if ($relativedir) {
13221 '@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}> $filelist';
13224 if (!empty($sortfield) && !empty($sortorder)) {
13228 $filename = $filelist[0][
'name'];
13229 $filepath = $filedir . $filename;
13231 $file = $filelist[0];
13232 $relativefilepath = $relativepath . $filename;
13240 if (!is_object($formfile)) {
13241 require_once DOL_DOCUMENT_ROOT .
'/core/class/html.formfile.class.php';
13242 $formfile =
new FormFile($this->db);
13244 return $formfile->showPreview($file, $this->element, $relativefilepath, 0,
'entity=' . $this->entity);
$id
Support class for third parties, contacts, members, users or resources.
if(! $sortfield) if(! $sortorder) $object
global $dolibarr_main_url_root
$propal type
'integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter[:Sortfield]]]',...
ajax_combobox($htmlname, $events=array(), $minLengthToAutocomplete=0, $forcefocus=0, $widthTypeOfAutocomplete='resolve', $idforemptyvalue='-1', $morecss='', $placeholder='')
Convert a html select field into an ajax combobox.
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
Class to manage members of a foundation.
Class to manage categories.
Class to manage customers 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...
fetchWarehouse($force_warehouse_id=0)
Load the warehouse of object, from id $this->warehouse_id or $this->fk_warehouse, into this->warehous...
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.
updateFieldFromUi(User $user, $field, $value)
Update a field from the user interface (ajax edition of cards...) and save it into database.
line_order($renum=false, $rowidorder='ASC', $fk_parent_line=true)
Save a new position (field rang) for details lines.
onFieldValueChanged($fieldKey, $value)
Hook called by setFieldValue() after a field has been successfully assigned.
deleteLineCommon(User $user, $idline, $notrigger=0)
Delete a line of object in database.
getRightsForUser(User $user)
Returns the rights used for this class for a specific user.
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.
hasUserPermission(User $user, $mode='write')
Check if user has a permission on this type of object.
deleteEcmFiles($mode=0)
Delete related files of object in database.
isFieldReadableFromUi(User $user, $field)
Check whether the value of a field can be read from the user interface with generic tools (ajax refre...
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
setFieldValue(User $user, $fieldKey, $value, $byPassUserPermission=false)
Set a value for a dynamic field on the current object.
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
setStatut($status, $elementId=null, $elementType='', $trigkey='', $fieldstatus='')
Set status of an object.
add_object_linked($origin=null, $origin_id=null, $f_user=null, $notrigger=0)
Add an object link into llx_element_element.
updateObjectLinked($sourceid=null, $sourcetype='', $targetid=null, $targettype='', $f_user=null, $notrigger=0)
Update object linked of a current object.
setErrorWithoutLog($message)
Set the error message for the object without logging it.
roundQtyToPackaging($qty, $packaging)
Round a quantity up to the next multiple of a packaging quantity (options PRODUCT_USE_CUSTOMER_PACKAG...
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.
showLastFilePreview($rootdir='', $relativepath='')
Show preview link of the element (last generate or *<ref>*.pdf) if found and authorized to show the p...
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.
getObjectLineHtml($lineid, $action='')
Return the HTML of a line as printed in the card by printObjectLines(), hooks printObjectLine and pri...
setFieldError($fieldKey, $msg='')
set validation error message a field
validateField($fields, $fieldKey, $fieldValue)
Return validation test result for a field.
printObjectLineWithHooks($action, $line, $num, $i, $dateSelector, $seller, $buyer, $selected, $extrafields, $defaulttpldir)
Print a line of the lines table: hooks printObjectLine or printObjectSubLine, then printObjectLine() ...
getDataToShowPhoto($modulepart, $imagesize)
Function used to get the logos or photos of an object.
setMulticurrencyCode($code)
Change the multicurrency code.
emtpyObjectVars()
Sets all object fields to null.
isFieldDefined($field)
Check if the field is defined in the object's field metadata.
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.
delete_resource($rowid, $element='', $notrigger=0)
Delete a link to resource line.
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)
isLineOfObject($lineid)
Check that a line belongs to this object, using $this->table_element_line and $this->fk_element.
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.
isFieldValidationRequired($field)
Check if the field requires validation.
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.
add_element_resource($resource_id, $resource_type, $busy=0, $mandatory=0, $notrigger=0)
Add resources to the current object : add entry into llx_element_resources Need $this->element & $thi...
hasUserPermissionOnField(User $user, $field, $mode='write')
Check if user has a permission on a field of this object.
checkActiveProductInLines($status='onsale')
Check if all products have the right status (on sale, on buy) called during validation of propal,...
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.
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.
persistFieldValue(User $user, $field)
Save into database the current value of one field, called by updateFieldFromUi().
updateExtraLanguages($key, $trigger=null, $userused=null)
Update an extra language value for the current object.
isFieldMarkedNotEditable($field)
Check if the field is explicitly marked as not editable.
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) Used for ex...
insertExtraLanguages($trigger='', $userused=null)
Add/Update all extra languages 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).
getLinkedBuyPriceDocuments($user, $lineid, $oldbuyprice=null)
Return the linked proposals, orders and invoices having, for the product of a line of this object,...
delete_contact($rowid, $notrigger=0)
Delete a link to contact line.
initObjectLinesDisplay()
Init the display of the lines: set the global variables used by the line templates (objectline_xxx....
updateLineUp($rowid, $rang)
Update position of line up (rang)
updateLinkedBuyPrice($user, $lineid, $elements)
Apply the cost price of a line of this object to the lines of the same product of some linked documen...
fetch_user($userid)
Load the user with id $userid into this->user.
ajaxOutputField($field)
Return the output html of a field for the user interface (ajax edition of fields).
errorsToString()
Method to output saved errors.
isFieldDisabled($field)
Check if the field is explicitly marked as disabled.
ajaxInputField($field)
Return the input html of a field for the user interface (ajax edition of fields).
getFieldPropertyName($field)
Return the name of the property of the object holding the value of a field of $fields.
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.
hasUserWritePermissionOnField(User $user, $field)
Check if user has write permission on a field of this object.
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.
isFieldBlockedByObjectState($field)
Check if the field is blocked by the current object state.
fetchComments()
Load comments linked with current task.
isFieldEditAllowed(User $user, $field, $byPassUserPermission=false)
Check whether a given field is allowed to be edited on the current object.
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.
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.
isFieldEditableFromUi(User $user, $field)
Check whether a field can be edited from the user interface with generic tools (ajax edition of cards...
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...
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.
isFieldEnabled($field)
Check if the field is enabled.
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 ...
getFieldValueFromAjaxPost($field)
Return the value of a field posted by the user interface (ajax edition of fields).
fetch_origin()
Read linked origin object.
prepareObjectLinesDisplay()
Prepare the display of the lines: global $usemargins and line extrafields used by the line templates ...
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.
getObjectLinesDisplayContext()
Return the display context of the lines, as defined by the card of the object before printObjectLines...
getFormatedCustomerRef($objref)
Return customer ref for screen output.
getTooltipContentArray($params)
Return array of data to show into a tooltip.
defineBuyPrice($unitPrice=0.0, $discountPercent=0.0, $fk_product=0, $qty=0)
Get buy price to use for margin calculation.
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.
setErrorWithLog($message, $loglevel=LOG_ERR)
Set the error message for the object and logs it, including the file name and line number.
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.
getRights()
Returns the rights used for this class.
static commonReplaceContact(DoliDB $dbs, $origin_id, $dest_id, array $tables, $fieldname='fk_socpeople', $ignoreerrors=0)
Function used to replace a contact id with another one.
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...
getFieldUiValue($field)
Return the value of a field of $fields, read in the property holding it (see getFieldPropertyName()).
Class to manage absolute discounts.
Class to manage a WYSIWYG editor.
Class to manage Dolibarr database access.
sanitize($stringtosanitize, $allowsimplequote=0, $allowsequals=0, $allowsspace=0, $allowschars=1)
Sanitize a string for SQL forging.
Class to manage donations.
Class to manage ECM files.
Class to manage warehouses.
Class to manage invoices.
const TYPE_CREDIT_NOTE
Credit note invoice.
Class to manage invoice templates.
Parent class of subscription templates.
Parent class to manage intervention document templates.
static getIdAndTxFromCode($dbs, $code, $date_document=0)
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 proposals.
Class to manage third parties objects (customers, suppliers, prospects...)
Class to manage price ask supplier.
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...
if(! $sortfield) if(! $sortorder) $module
$context
@method int call_trigger(string $triggerName, ?User $user)
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_delete_dir_recursive($dir, $count=0, $nophperrors=0, $onlysub=0, &$countdeleted=0, $indexdatabase=1, $nolog=0, $level=0)
Remove a directory $dir and its subdirectories (or only files and subdirectories)
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_is_dir($folder)
Test if filename is a directory.
dol_delete_preview($object)
Delete all preview files linked to object instance.
$date_start
Variables from include:
dol_html_entity_decode($a, $b, $c='UTF-8', $keepsomeentities=0)
Replace html_entity_decode functions to manage errors.
dol_now($mode='gmt')
Return date for now.
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...
dol_print_email($email, $contactid=0, $socid=0, $addlink=0, $max=0, $showinvalid=2, $withpicto=0, $morecss='paddingrightonly')
Show EMail link formatted for HTML output.
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.
price2num($amount, $rounding='', $option=0, $currencycode='')
Function that return a number with universal decimal format (decimal separator is '.
GETPOSTDATE($prefix, $hourTime='', $gm='auto', $saverestore='')
Helper function that combines values of a dolibarr DatePicker (such as Form\selectDate) for year,...
dol_print_ip($ip, $mode=0, $showname=0)
Return an IP formatted to be shown on screen.
dol_print_phone($phone, $countrycode='', $contactid=0, $socid=0, $addlink='', $separ=" ", $withpicto='', $titlealt='', $adddivfloat=0, $morecss='paddingright')
Format phone numbers according to country.
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_osencode($str)
Return a string encoded into OS filesystem encoding.
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.
dol_print_url($url, $target='_blank', $max=32, $withpicto=0, $morecss='')
Show Url link.
dol_sanitizePathName($str, $newstr='_', $unaccent=0, $allowdash=0)
Clean a string to use it as a path name.
dol_sanitizeFileName($str, $newstr='_', $unaccent=1, $includequotes=0, $allowdash=0)
Clean a string to use it as a file name.
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.
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_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.
getMultidirOutput($object, $module='', $forobject=0, $mode='output')
Return the full path of the directory where a module (or an object of a module) stores its files.
newToken()
Return the value of token currently saved into session with name 'newtoken'.
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0, $nodefault=0)
Return value of a param into GET or POST supervariable.
forgeSQLFromUniversalSearchCriteria($filter, &$errorstr='', $noand=0, $nopar=0, $noerror=0, $forbiddenfields=array())
forgeSQLFromUniversalSearchCriteria
getImageFileNameForSize($file, $extName, $extImgTarget='')
Return the filename of file to get the thumbs.
get_date_range($date_start, $date_end, $format='', $outputlangs=null, $withparenthesis=1)
Format output for start and end date.
GETPOSTINT($paramname, $method=0, $nodefault=0)
Return the value of a $_GET or $_POST supervariable, converted into integer.
dolIsAllowedForPreview($file)
Return if a file is qualified for preview.
if(!function_exists( 'utf8_encode')) if(!function_exists('utf8_decode')) if(!function_exists( 'str_starts_with')) if(!function_exists('str_ends_with')) if(!function_exists( 'str_contains')) formatLogObject($data)
Return a string serialized to be output on log with dol_syslog() An option allow to output log in one...
dol_buildpath($path, $type=0, $returnemptyifnotfound=0)
Return path of url or filesystem.
dol_clone($srcobject, $native=2)
Create a clone of instance of object (new instance with same value for each properties) With native =...
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false, $decorate=0)
Output date in a string format according to outputlangs (or langs if not defined).
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.
GETPOSTISSET($paramname)
Return true if we are in a context of submitting the parameter $paramname from a POST of a form.
dol_htmlentitiesbr($stringtoencode, $nl2brmode=0, $pagecodefrom='UTF-8', $removelasteolbr=1)
This function is called to encode a string into a HTML string but differs from htmlentities because a...
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
isModEnabled($module)
Is Dolibarr module enabled.
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.
getPictoForType($key, $morecss='')
Return the picto for a data type.
getAdvancedPreviewUrl($modulepart, $relativepath, $alldata=0, $param='')
Return URL we can use for advanced preview links.
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $noescapetags='', $escapeonlyhtmltags=0, $cleanalsojavascript=0)
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.
calcul_price_total($qty, $pu, $remise_percent_ligne, $txtva, $uselocaltax1_rate, $uselocaltax2_rate, $notused, $price_base_type, $info_bits, $type, $seller=null, $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.
getRandomPassword($generic=false, $replaceambiguouschars=null, $length=32)
Return a generated password using default module.
restrictedArea(User $user, $features, $object=0, $tableandshare='', $feature2='', $dbt_keyfield='fk_soc', $dbt_select='rowid', $isdraft=0, $nodie=0, $mode='')
Check permissions of a user to show a page and an object.
dol_hash($chain, $type='0', $nosalt=0, $mode=0)
Returns a hash (non reversible encryption) of a string.
dolDecrypt($chain, $key='', $patterntotest='')
Decode a string with a symmetric encryption.
dolEncrypt($chain, $key='', $ciphering='', $forceseed='', $obfuscationmode='dolcrypt')
Encode a string with a symmetric encryption.