48require_once DOL_DOCUMENT_ROOT.
'/core/class/doldeprecationhandler.class.php';
49require_once DOL_DOCUMENT_ROOT.
'/core/class/commontrigger.class.php';
60 use DolDeprecationHandler;
97 public $errors = array();
108 public $warnings = array();
113 private $validateFieldsErrors = array();
131 public $element_for_permission;
136 public $table_element;
146 public $table_element_line =
'';
152 public $ismultientitymanaged;
162 public $array_options = array();
243 public $fields = array();
250 public $array_languages =
null;
255 public $contacts_ids;
260 public $contacts_ids_internal;
265 public $linked_objects;
270 public $linkedObjectsIds;
275 public $linkedObjects;
280 private $linkedObjectsFullLoaded = array();
295 protected $table_ref_field =
'';
300 public $restrictiononfksoc = 0;
309 public $context = array();
426 private $commandeFournisseur;
442 public $ref_previous;
488 public $country_code;
531 public $barcode_type;
537 public $barcode_type_code;
543 public $barcode_type_label;
549 public $barcode_type_coder;
555 public $mode_reglement_id;
561 public $cond_reglement_id;
566 public $demand_reason_id;
572 public $transport_mode_id;
584 protected $depr_cond_reglement;
591 public $fk_delivery_address;
597 public $shipping_method_id;
603 public $shipping_method;
609 public $fk_multicurrency;
615 public $multicurrency_code;
621 public $multicurrency_tx;
626 public $multicurrency_total_ht;
631 public $multicurrency_total_tva;
636 public $multicurrency_total_localtax1;
641 public $multicurrency_total_localtax2;
646 public $multicurrency_total_ttc;
659 public $last_main_doc;
684 public $note_private;
709 public $total_localtax1;
715 public $total_localtax2;
732 public $actiontypecode;
738 public $comments = array();
764 public $civility_code;
770 public $date_creation;
775 public $date_validation;
780 public $date_modification;
794 private $date_update;
799 public $date_cloture;
804 public $user_creation_id;
809 public $user_validation_id;
814 public $user_closing_id;
819 public $user_modification_id;
825 public $fk_user_creat;
831 public $fk_user_modif;
837 public $next_prev_filter;
842 public $specimen = 0;
866 public $totalpaid_multicurrency;
872 public $labelStatus = array();
877 public $labelStatusShort = array();
888 public $showphoto_on_popup;
893 public $nb = array();
908 public $extraparams = array();
913 protected $childtables = array();
920 protected $childtablesoncascade = array();
925 public $cond_reglement_supplier_id;
932 public $deposit_percent;
938 public $warehouse_id;
943 public $isextrafieldmanaged = 0;
956 'alreadypaid' =>
'totalpaid',
957 'cond_reglement' =>
'depr_cond_reglement',
959 'commandeFournisseur' =>
'origin_object',
960 'expedition' =>
'origin_object',
961 'fk_project' =>
'fk_project',
962 'livraison' =>
'origin_object',
963 'projet' =>
'project',
964 'statut' =>
'status',
983 $sql =
"SELECT rowid";
984 $sql .=
" FROM ".$db->prefix().$element;
985 $sql .=
" WHERE entity IN (".getEntity($element).
")";
988 $sql .=
" AND rowid = ".((int) $id);
990 $sql .=
" AND ref = '".$db->escape($ref).
"'";
991 } elseif ($ref_ext) {
992 $sql .=
" AND ref_ext = '".$db->escape($ref_ext).
"'";
994 $error =
'ErrorWrongParameters';
995 dol_syslog(get_class().
"::isExistingObject ".$error, LOG_ERR);
998 if ($ref || $ref_ext) {
999 $sql .=
" AND entity = ".((int)
$conf->entity);
1002 dol_syslog(get_class().
"::isExistingObject", LOG_DEBUG);
1003 $resql =
$db->query($sql);
1005 $num =
$db->num_rows($resql);
1022 return (empty($this->
id));
1034 $this->error =
$object->error;
1036 if (!empty(
$object->errors)) {
1037 $this->errors = array_merge($this->errors,
$object->errors);
1062 global $action, $extrafields, $langs, $hookmanager;
1065 $MAX_EXTRAFIELDS_TO_SHOW_IN_TOOLTIP =
getDolGlobalInt(
'MAX_EXTRAFIELDS_TO_SHOW_IN_TOOLTIP', 3);
1071 if (!empty($extrafields->attributes[$this->table_element][
'label'])) {
1072 $data[
'opendivextra'] =
'<div class="centpercent wordbreak divtooltipextra">';
1073 foreach ($extrafields->attributes[$this->table_element][
'label'] as $key => $val) {
1074 if ($extrafields->attributes[$this->table_element][
'type'][$key] ==
'separate') {
1078 if (empty($extrafields->attributes[$this->table_element][
'showintooltip'][$key])) {
1083 if ($count >= abs($MAX_EXTRAFIELDS_TO_SHOW_IN_TOOLTIP)) {
1084 $data[
'more_extrafields'] =
'<br>...';
1088 if ($enabled && isset($extrafields->attributes[$this->table_element][
'enabled'][$key])) {
1089 $enabled = (int)
dol_eval((
string) $extrafields->attributes[$this->table_element][
'enabled'][$key], 1, 1,
'2');
1091 if ($enabled && isset($extrafields->attributes[$this->table_element][
'list'][$key])) {
1092 $enabled = (int)
dol_eval((
string) $extrafields->attributes[$this->table_element][
'list'][$key], 1, 1,
'2');
1095 if ($perms && isset($extrafields->attributes[$this->table_element][
'perms'][$key])) {
1096 $perms = (int)
dol_eval((
string) $extrafields->attributes[$this->table_element][
'perms'][$key], 1, 1,
'2');
1098 if (empty($enabled)) {
1101 if (abs($enabled) != 1 && abs($enabled) != 3 && abs($enabled) != 5 && abs($enabled) != 4) {
1104 if (empty($perms)) {
1107 if (!empty($extrafields->attributes[$this->table_element][
'langfile'][$key])) {
1108 $langs->load($extrafields->attributes[$this->table_element][
'langfile'][$key]);
1110 $labelextra = $langs->trans((
string) $extrafields->attributes[$this->table_element][
'label'][$key]);
1111 if ($extrafields->attributes[$this->table_element][
'type'][$key] ==
'separate') {
1112 $data[$key] =
'<br><b><u>'. $labelextra .
'</u></b>';
1114 $value = (empty($this->array_options[
'options_' . $key]) ?
'' : $this->array_options[
'options_' . $key]);
1115 $data[$key] =
'<br><b>'. $labelextra .
':</b> ' . $extrafields->showOutputField($key, $value,
'', $this->table_element);
1119 $data[
'closedivextra'] =
'</div>';
1122 $hookmanager->initHooks(array($this->element .
'dao'));
1123 $parameters = array(
1124 'tooltipcontentarray' => &$data,
1125 'params' => $params,
1128 $hookmanager->executeHooks(
'getTooltipContent', $parameters, $this, $action);
1131 $label = implode($data);
1144 return $this->error.(is_array($this->errors) ? (($this->error !=
'' ?
', ' :
'').implode(
', ', $this->errors)) :
'');
1156 global $hookmanager;
1158 $parameters = array(
'objref' => $objref);
1160 $reshook = $hookmanager->executeHooks(
'getFormatedCustomerRef', $parameters, $this, $action);
1162 return $hookmanager->resArray[
'objref'];
1164 return $objref.(isset($hookmanager->resArray[
'objref']) ? $hookmanager->resArray[
'objref'] :
'');
1175 global $hookmanager;
1177 $parameters = array(
'objref' => $objref);
1179 $reshook = $hookmanager->executeHooks(
'getFormatedSupplierRef', $parameters, $this, $action);
1181 return $hookmanager->resArray[
'objref'];
1183 return $objref.(isset($hookmanager->resArray[
'objref']) ? $hookmanager->resArray[
'objref'] :
'');
1195 public function getFullAddress($withcountry = 0, $sep =
"\n", $withregion = 0, $extralangcode =
'')
1197 if ($withcountry && $this->country_id && (empty($this->country_code) || empty($this->country))) {
1198 require_once DOL_DOCUMENT_ROOT.
'/core/lib/company.lib.php';
1199 $tmparray =
getCountry($this->country_id,
'all');
1200 $this->country_code = $tmparray[
'code'];
1201 $this->country = $tmparray[
'label'];
1204 if ($withregion && $this->state_id && (empty($this->state_code) || empty($this->state) || empty($this->region) || empty($this->region_code))) {
1205 require_once DOL_DOCUMENT_ROOT.
'/core/lib/company.lib.php';
1206 $tmparray =
getState($this->state_id,
'all',
null, 1);
1207 $this->state_code = $tmparray[
'code'];
1208 $this->state = $tmparray[
'label'];
1209 $this->region_code = $tmparray[
'region_code'];
1210 $this->region = $tmparray[
'region'];
1229 if (empty($this->last_main_doc)) {
1233 include_once DOL_DOCUMENT_ROOT.
'/ecm/class/ecmfiles.class.php';
1234 $ecmfile =
new EcmFiles($this->db);
1235 $result = $ecmfile->fetch(0,
'', $this->last_main_doc);
1237 $this->error = $ecmfile->error;
1238 $this->errors = $ecmfile->errors;
1242 if (empty($ecmfile->id)) {
1244 if ($initsharekey) {
1245 require_once DOL_DOCUMENT_ROOT.
'/core/lib/security2.lib.php';
1267 } elseif (empty($ecmfile->share)) {
1269 if ($initsharekey) {
1270 require_once DOL_DOCUMENT_ROOT.
'/core/lib/security2.lib.php';
1272 $ecmfile->update($user);
1278 $urlwithouturlroot = preg_replace(
'/'.preg_quote(DOL_URL_ROOT,
'/').
'$/i',
'', trim(
$dolibarr_main_url_root));
1282 $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT;
1291 if (!empty($ecmfile->share)) {
1292 $paramlink .= ($paramlink ?
'&' :
'').
'hashp='.$ecmfile->share;
1294 if ($forcedownload) {
1295 $paramlink .= ($paramlink ?
'&' :
'').
'attachment=1';
1298 if ($relativelink) {
1299 $linktoreturn =
'document.php'.($paramlink ?
'?'.$paramlink :
'');
1301 $linktoreturn = $urlwithroot.
'/document.php'.($paramlink ?
'?'.$paramlink :
'');
1305 return $linktoreturn;
1319 public function add_contact($fk_socpeople, $type_contact, $source =
'external', $notrigger = 0)
1322 global $user, $langs;
1324 dol_syslog(get_class($this).
"::add_contact $fk_socpeople, $type_contact, $source, $notrigger");
1327 if ($fk_socpeople <= 0) {
1328 $langs->load(
"errors");
1329 $this->error = $langs->trans(
"ErrorWrongValueForParameterX",
"1");
1330 dol_syslog(get_class($this).
"::add_contact ".$this->error, LOG_ERR);
1335 $sql_check =
"SELECT rowid FROM ".$this->db->prefix().($source ==
'internal' ?
"user" :
"socpeople").
" WHERE rowid = ".((
int) $fk_socpeople);
1336 $resql_check = $this->db->query($sql_check);
1338 if (!$this->db->num_rows($resql_check)) {
1339 $langs->load(
"errors");
1340 $this->error = $langs->trans(
"ErrorRecordNotFound");
1341 dol_syslog(get_class($this).
"::add_contact Contact/user id ".$fk_socpeople.
" does not exist", LOG_ERR);
1345 $this->error = $this->db->lasterror();
1349 if (!$type_contact) {
1350 $langs->load(
"errors");
1351 $this->error = $langs->trans(
"ErrorWrongValueForParameterX",
"2");
1352 dol_syslog(get_class($this).
"::add_contact ".$this->error, LOG_ERR);
1357 if ($this->restrictiononfksoc && property_exists($this,
'socid') && !empty($this->socid) && $user->id > 0 && !$user->hasRight(
'societe',
'client',
'voir')) {
1358 $sql_allowed_contacts =
'SELECT COUNT(*) as cnt FROM '.$this->db->prefix().
'societe_commerciaux as sc';
1360 $sql_allowed_contacts .=
' WHERE sc.fk_soc = '.(int) $this->socid;
1361 $sql_allowed_contacts .=
' AND sc.fk_user = '.(int) $user->id;
1363 $resql_allowed_contacts = $this->db->query($sql_allowed_contacts);
1365 if (!$resql_allowed_contacts) {
1366 $this->errors[] = $this->db->lasterror();
1368 } elseif ($obj = $this->db->fetch_object($resql_allowed_contacts)) {
1369 if ($obj->cnt == 0) {
1370 $langs->load(
"companies");
1371 $this->error = $langs->trans(
"ErrorCommercialNotAllowedForThirdparty", $user->id);
1372 dol_syslog(get_class($this).
"::add_contact ".$this->error, LOG_ERR);
1378 $id_type_contact = 0;
1379 if (is_numeric($type_contact)) {
1380 $id_type_contact = $type_contact;
1383 $sql =
"SELECT tc.rowid";
1384 $sql .=
" FROM ".$this->db->prefix().
"c_type_contact as tc";
1385 $sql .=
" WHERE tc.element='".$this->db->escape($this->element).
"'";
1386 $sql .=
" AND tc.source='".$this->db->escape($source).
"'";
1387 $sql .=
" AND tc.code='".$this->db->escape($type_contact).
"' AND tc.active=1";
1389 $resql = $this->db->query($sql);
1391 $obj = $this->db->fetch_object($resql);
1393 $id_type_contact = $obj->rowid;
1397 if ($id_type_contact == 0) {
1398 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");
1406 $already_added =
false;
1407 if (is_array($TListeContacts) && !empty($TListeContacts)) {
1408 foreach ($TListeContacts as $array_contact) {
1409 if ($array_contact[
'status'] == 4 && $array_contact[
'id'] == $fk_socpeople && $array_contact[
'fk_c_type_contact'] == $id_type_contact) {
1410 $already_added =
true;
1416 if (!$already_added) {
1420 $sql =
"INSERT INTO ".$this->db->prefix().
"element_contact";
1421 $sql .=
" (element_id, fk_socpeople, datecreate, statut, fk_c_type_contact) ";
1422 $sql .=
" VALUES (".((int) $this->
id).
", ".((int) $fk_socpeople).
" , ";
1423 $sql .=
"'".$this->db->idate($datecreate).
"'";
1424 $sql .=
", 4, ".((int) $id_type_contact);
1427 $resql = $this->db->query($sql);
1430 $triggerPrefix = (empty($this->TRIGGER_PREFIX) ? strtoupper($this->element) : $this->TRIGGER_PREFIX);
1431 $result = $this->call_trigger($triggerPrefix.
'_ADD_CONTACT', $user);
1433 $this->db->rollback();
1438 $this->db->commit();
1441 if ($this->db->errno() ==
'DB_ERROR_RECORD_ALREADY_EXISTS') {
1442 $this->error = $this->db->errno();
1443 $this->db->rollback();
1446 $this->error = $this->db->lasterror();
1447 $this->db->rollback();
1467 $contacts = $objFrom->liste_contact(-1, $source);
1468 foreach ($contacts as $contact) {
1469 if ($this->
add_contact($contact[
'id'], $contact[
'fk_c_type_contact'], $contact[
'source']) < 0) {
1486 public function update_contact($rowid, $statut, $type_contact_id = 0, $fk_socpeople = 0)
1490 $sql =
"UPDATE ".$this->db->prefix().
"element_contact set";
1491 $sql .=
" statut = ".((int) $statut);
1492 if ($type_contact_id) {
1493 $sql .=
", fk_c_type_contact = ".((int) $type_contact_id);
1495 if ($fk_socpeople) {
1496 $sql .=
", fk_socpeople = ".((int) $fk_socpeople);
1498 $sql .=
" where rowid = ".((int) $rowid);
1500 $resql = $this->db->query($sql);
1504 $this->error = $this->db->lasterror();
1526 if (!$error && empty($notrigger)) {
1528 $this->context[
'contact_id'] = ((int) $rowid);
1529 $triggerPrefix = (empty($this->TRIGGER_PREFIX) ? strtoupper($this->element) : $this->TRIGGER_PREFIX);
1530 $result = $this->call_trigger($triggerPrefix.
'_DELETE_CONTACT', $user);
1538 dol_syslog(get_class($this).
"::delete_contact", LOG_DEBUG);
1540 $sql =
"DELETE FROM ".MAIN_DB_PREFIX.
"element_contact";
1541 $sql .=
" WHERE rowid = ".((int) $rowid);
1543 $result = $this->db->query($sql);
1546 $this->errors[] = $this->db->lasterror();
1551 $this->db->commit();
1554 $this->error = $this->db->lasterror();
1555 $this->db->rollback();
1575 if (!empty($typeContact)) {
1576 foreach ($typeContact as $key => $value) {
1577 array_push($temp, $key);
1579 $listId = implode(
",", $temp);
1584 if (empty($listId)) {
1588 $sql =
"DELETE FROM ".$this->db->prefix().
"element_contact";
1589 $sql .=
" WHERE element_id = ".((int) $this->
id);
1590 $sql .=
" AND fk_c_type_contact IN (".$this->db->sanitize($listId).
")";
1592 dol_syslog(get_class($this).
"::delete_linked_contact", LOG_DEBUG);
1593 if ($this->db->query($sql)) {
1596 $this->error = $this->db->lasterror();
1613 public function liste_contact($statusoflink = -1, $source =
'external', $list = 0, $code =
'', $status = -1, $arrayoftcids = array())
1620 $sql =
"SELECT ec.rowid, ec.statut as statuslink, ec.fk_socpeople as id, ec.fk_c_type_contact";
1621 if ($source ==
'internal') {
1622 $sql .=
", '-1' as socid, t.statut as statuscontact, t.login, t.photo, t.gender, t.fk_country as country_id";
1624 if ($source ==
'external' || $source ==
'thirdparty') {
1625 $sql .=
", t.fk_soc as socid, t.statut as statuscontact, t.fk_pays as country_id";
1627 $sql .=
", t.civility as civility, t.lastname as lastname, t.firstname, t.email, t.address, t.zip, t.town";
1628 if (empty($arrayoftcids)) {
1629 $sql .=
", tc.source, tc.element, tc.code, tc.libelle as type_label, co.label as country";
1632 if (empty($arrayoftcids)) {
1633 $sql .=
" ".$this->db->prefix().
"c_type_contact as tc,";
1635 $sql .=
" ".$this->db->prefix().
"element_contact as ec";
1636 if ($source ==
'internal') {
1637 $sql .=
" LEFT JOIN ".$this->db->prefix().
"user as t on ec.fk_socpeople = t.rowid";
1638 $sql .=
" LEFT JOIN ".$this->db->prefix().
"c_country as co ON co.rowid = t.fk_country";
1640 if ($source ==
'external' || $source ==
'thirdparty') {
1641 $sql .=
" LEFT JOIN ".$this->db->prefix().
"socpeople as t on ec.fk_socpeople = t.rowid";
1642 $sql .=
" LEFT JOIN ".$this->db->prefix().
"c_country as co ON co.rowid = t.fk_pays";
1644 $sql .=
" WHERE ec.element_id = ".((int) $this->
id);
1645 if (empty($arrayoftcids)) {
1646 $sql .=
" AND ec.fk_c_type_contact = tc.rowid";
1647 $sql .=
" AND tc.element = '".$this->db->escape($this->element).
"'";
1649 $sql .=
" AND tc.code = '".$this->db->escape($code).
"'";
1651 if ($source ==
'internal') {
1652 $sql .=
" AND tc.source = 'internal'";
1654 if ($source ==
'external' || $source ==
'thirdparty') {
1655 $sql .=
" AND tc.source = 'external'";
1657 $sql .=
" AND tc.active = 1";
1659 $sql .=
" AND ec.fk_c_type_contact IN (".$this->db->sanitize(implode(
',', $arrayoftcids)).
")";
1662 $sql .=
" AND t.statut = ".((int) $status);
1664 if ($statusoflink >= 0) {
1665 $sql .=
" AND ec.statut = ".((int) $statusoflink);
1667 $sql .=
" ORDER BY t.lastname ASC";
1669 dol_syslog(get_class($this).
"::liste_contact", LOG_DEBUG);
1670 $resql = $this->db->query($sql);
1672 $num = $this->db->num_rows($resql);
1675 $obj = $this->db->fetch_object($resql);
1678 $transkey =
"TypeContact_".$obj->element.
"_".$obj->source.
"_".$obj->code;
1679 $label_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->type_label);
1681 'parentId' => $this->
id,
1682 'source' => $obj->source,
1683 'socid' => $obj->socid,
1685 'nom' => $obj->lastname,
1686 'civility' => $obj->civility,
1687 'lastname' => $obj->lastname,
1688 'firstname' => $obj->firstname,
1689 'email' => $obj->email,
1690 'address' => $obj->address,
1692 'town' => $obj->town,
1693 'country_id' => $obj->country_id,
1694 'country' => $obj->country,
1695 'login' => (empty($obj->login) ?
'' : $obj->login),
1696 'photo' => (empty($obj->photo) ?
'' : $obj->photo),
1697 'gender' => (empty($obj->gender) ?
'' : $obj->gender),
1698 'statuscontact' => $obj->statuscontact,
1699 'rowid' => $obj->rowid,
1700 'code' => $obj->code,
1701 'libelle' => $label_type,
1702 'status' => (
int) $obj->statuslink,
1703 'fk_c_type_contact' => $obj->fk_c_type_contact
1706 $tab[$i] = $obj->id;
1714 $this->error = $this->db->lasterror();
1729 $sql =
"SELECT ec.datecreate, ec.statut, ec.fk_socpeople, ec.fk_c_type_contact,";
1730 $sql .=
" tc.code, tc.libelle as type_label";
1731 $sql .=
" FROM (".$this->db->prefix().
"element_contact as ec, ".$this->db->prefix().
"c_type_contact as tc)";
1732 $sql .=
" WHERE ec.rowid =".((int) $rowid);
1733 $sql .=
" AND ec.fk_c_type_contact = tc.rowid";
1734 $sql .=
" AND tc.element = '".$this->db->escape($this->element).
"'";
1736 dol_syslog(get_class($this).
"::swapContactStatus", LOG_DEBUG);
1737 $resql = $this->db->query($sql);
1739 $obj = $this->db->fetch_object($resql);
1740 $newstatut = ($obj->statut == 4) ? 5 : 4;
1742 $this->db->free($resql);
1745 $this->error = $this->db->error();
1762 public function liste_type_contact($source =
'internal', $order =
'position', $option = 0, $activeonly = 0, $code =
'')
1767 $sanitized_order = $order;
1769 if (empty($sanitized_order)) {
1770 $sanitized_order =
'position';
1772 if ($sanitized_order ==
'position') {
1773 $sanitized_order .=
',code';
1778 $sql =
"SELECT DISTINCT tc.rowid, tc.code, tc.libelle as type_label, tc.position";
1779 $sql .=
" FROM ".$this->db->prefix().
"c_type_contact as tc";
1780 $sql .=
" WHERE tc.element = '".$this->db->escape($this->element).
"'";
1781 if ($activeonly == 1) {
1782 $sql .=
" AND tc.active = 1";
1784 if (!empty($source) && $source !=
'all') {
1785 $sql .=
" AND tc.source = '".$this->db->escape($source).
"'";
1787 if (!empty($code)) {
1788 $sql .=
" AND tc.code = '".$this->db->escape($code).
"'";
1790 $sql .= $this->db->order($sanitized_order,
'ASC');
1793 $resql = $this->db->query($sql);
1795 $this->error = $this->db->lasterror();
1800 $num = $this->db->num_rows($resql);
1803 $obj = $this->db->fetch_object($resql);
1805 $transkey =
"TypeContact_".$this->element.
"_".$source.
"_".$obj->code;
1806 $label_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $langs->trans($obj->type_label));
1807 if (empty($option)) {
1808 $tab[$obj->rowid] = $label_type;
1809 } elseif ($option == 1) {
1810 $tab[$obj->code] = $label_type;
1812 $tab[$obj->rowid] = array(
'id' => $obj->rowid,
'code' => $obj->code,
'label' => $label_type);
1831 public function listeTypeContacts($source =
'internal', $option = 0, $activeonly = 0, $code =
'', $element =
'', $excludeelement =
'')
1835 $langs->loadLangs(array(
'bills',
'contracts',
'interventions',
'orders',
'projects',
'propal',
'ticket',
'agenda'));
1839 $sql =
"SELECT DISTINCT tc.rowid, tc.code, tc.libelle as type_label, tc.position, tc.element, tc.module";
1840 $sql .=
" FROM ".$this->db->prefix().
"c_type_contact as tc";
1842 $sqlWhere = array();
1843 if (!empty($element)) {
1844 $sqlWhere[] =
" tc.element='".$this->db->escape($element).
"'";
1846 if (!empty($excludeelement)) {
1847 $sqlWhere[] =
" tc.element <> '".$this->db->escape($excludeelement).
"'";
1850 if ($activeonly == 1) {
1851 $sqlWhere[] =
" tc.active=1";
1854 if (!empty($source) && $source !=
'all') {
1855 $sqlWhere[] =
" tc.source='".$this->db->escape($source).
"'";
1858 if (!empty($code)) {
1859 $sqlWhere[] =
" tc.code='".$this->db->escape($code).
"'";
1862 if (count($sqlWhere) > 0) {
1863 $sql .=
" WHERE ".implode(
' AND ', $sqlWhere);
1866 $sql .= $this->db->order(
'tc.element, tc.position',
'ASC');
1869 $resql = $this->db->query($sql);
1871 $num = $this->db->num_rows($resql);
1873 $langs->loadLangs(array(
"propal",
"orders",
"bills",
"suppliers",
"contracts",
"supplier_proposal"));
1875 while ($obj = $this->db->fetch_object($resql)) {
1876 $modulename = $obj->module ?? $obj->element;
1877 if (strpos($obj->element,
'project') !==
false) {
1878 $modulename =
'projet';
1879 } elseif ($obj->element ==
'contrat') {
1880 $element =
'contract';
1881 } elseif ($obj->element ==
'action') {
1882 $modulename =
'agenda';
1883 } elseif (strpos($obj->element,
'supplier') !==
false && $obj->element !=
'supplier_proposal') {
1884 $modulename =
'fournisseur';
1887 $label_element = $langs->trans(
'ContactDefault_'.$obj->element);
1888 $tmpelement = $obj->element;
1889 $transkey =
"TypeContact_".$tmpelement.
"_".$source.
"_".$obj->code;
1890 $label_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->type_label);
1891 $tab[$obj->rowid] = $label_element.
' - '.$label_type;
1897 $this->error = $this->db->lasterror();
1918 if (!
getDolGlobalInt(
'SHIPPING_USE_ITS_OWN_CONTACTS') && $this->element ==
'shipping' && $this->origin_id != 0) {
1919 $id = $this->origin_id;
1920 $element =
'commande';
1921 } elseif ($this->element ==
'reception' && $this->origin_id != 0) {
1922 $id = $this->origin_id;
1923 $element =
'order_supplier';
1926 $element = $this->element;
1929 $sql =
"SELECT ec.fk_socpeople";
1930 $sql .=
" FROM ".$this->db->prefix().
"element_contact as ec,";
1931 if ($source ==
'internal') {
1932 $sql .=
" ".$this->db->prefix().
"user as c,";
1934 if ($source ==
'external') {
1935 $sql .=
" ".$this->db->prefix().
"socpeople as c,";
1937 $sql .=
" ".$this->db->prefix().
"c_type_contact as tc";
1938 $sql .=
" WHERE ec.element_id = ".((int) $id);
1939 $sql .=
" AND ec.fk_socpeople = c.rowid";
1940 if ($source ==
'internal') {
1941 $sql .=
" AND c.entity IN (".getEntity(
'user').
")";
1943 if ($source ==
'external') {
1944 $sql .=
" AND c.entity IN (".getEntity(
'societe').
")";
1946 $sql .=
" AND ec.fk_c_type_contact = tc.rowid";
1947 $sql .=
" AND tc.element = '".$this->db->escape($element).
"'";
1948 $sql .=
" AND tc.source = '".$this->db->escape($source).
"'";
1950 $sql .=
" AND tc.code = '".$this->db->escape($code).
"'";
1952 $sql .=
" AND tc.active = 1";
1954 $sql .=
" AND ec.statut = ".((int) $status);
1957 dol_syslog(get_class($this).
"::getIdContact", LOG_DEBUG);
1958 $resql = $this->db->query($sql);
1960 while ($obj = $this->db->fetch_object($resql)) {
1961 $result[$i] = $obj->fk_socpeople;
1965 $this->error = $this->db->error();
1982 if (empty($contactid)) {
1983 $contactid = $this->contact_id;
1986 if (empty($contactid)) {
1990 require_once DOL_DOCUMENT_ROOT.
'/contact/class/contact.class.php';
1991 $contact =
new Contact($this->db);
1992 $result = $contact->fetch($contactid);
1993 $this->contact = $contact;
2008 if (empty($this->socid) && empty($this->fk_soc) && empty($force_thirdparty_id)) {
2012 require_once DOL_DOCUMENT_ROOT.
'/societe/class/societe.class.php';
2014 $idtofetch = isset($this->socid) ? $this->socid : (isset($this->fk_soc) ? $this->fk_soc : 0);
2015 if ($force_thirdparty_id) {
2016 $idtofetch = $force_thirdparty_id;
2020 $thirdparty =
new Societe($this->db);
2021 $result = $thirdparty->fetch($idtofetch);
2023 $this->errors = array_merge($this->errors, $thirdparty->errors);
2025 $this->thirdparty = $thirdparty;
2029 $this->thirdparty->price_level = 1;
2048 if (!$this->table_ref_field) {
2052 $sql =
"SELECT rowid FROM ".$this->db->prefix().$this->table_element;
2053 $sql .=
" WHERE ".$this->db->sanitize($this->table_ref_field).
" LIKE '".$this->db->escape($ref).
"'";
2056 $query = $this->db->query($sql);
2058 if (!$this->db->num_rows($query)) {
2062 $result = $this->db->fetch_object($query);
2064 if (method_exists($this,
'fetch')) {
2065 return $this->fetch($result->rowid);
2067 $this->error =
'Fetch method not implemented on '.get_class($this);
2068 dol_syslog(get_class($this).
'::fetchOneLike Error='.$this->error, LOG_ERR);
2069 array_push($this->errors, $this->error);
2098 dol_syslog(get_class($this).
'::fetchBarCode this->element='.$this->element.
' this->barcode_type='.$this->barcode_type);
2100 $idtype = $this->barcode_type;
2101 if (empty($idtype) && $idtype !=
'0') {
2102 if ($this->element ==
'product' &&
getDolGlobalString(
'PRODUIT_DEFAULT_BARCODE_TYPE')) {
2104 } elseif ($this->element ==
'societe') {
2107 dol_syslog(
'Call fetchBarCode with barcode_type not defined and cannot be guessed', LOG_WARNING);
2112 if (empty($this->barcode_type) || empty($this->barcode_type_code) || empty($this->barcode_type_label) || empty($this->barcode_type_coder)) {
2113 $sql =
"SELECT rowid, code, libelle as label, coder";
2114 $sql .=
" FROM ".$this->db->prefix().
"c_barcode_type";
2115 $sql .=
" WHERE rowid = ".((int) $idtype);
2117 $resql = $this->db->query($sql);
2119 $obj = $this->db->fetch_object($resql);
2121 $this->barcode_type = $obj->rowid;
2122 $this->barcode_type_code = $obj->code;
2123 $this->barcode_type_label = $obj->label;
2124 $this->barcode_type_coder = $obj->coder;
2142 include_once DOL_DOCUMENT_ROOT.
'/projet/class/project.class.php';
2144 if (empty($this->fk_project) && !empty($this->fk_projet)) {
2145 $this->fk_project = $this->fk_projet;
2147 if (empty($this->fk_project)) {
2151 $project =
new Project($this->db);
2152 $result = $project->fetch($this->fk_project);
2154 $this->project = $project;
2196 include_once DOL_DOCUMENT_ROOT.
'/product/class/product.class.php';
2199 if (empty($this->fk_product)) {
2203 $product =
new Product($this->db);
2205 $result = $product->fetch($this->fk_product);
2207 $this->product = $product;
2220 if (empty($this->warehouse_id) && empty($this->fk_warehouse) && empty($force_warehouse_id)) {
2224 include_once DOL_DOCUMENT_ROOT.
'/product/stock/class/entrepot.class.php';
2227 $idtofetch = isset($this->warehouse_id) ? $this->warehouse_id : (isset($this->fk_warehouse) ? $this->fk_warehouse : 0);
2228 if (!empty($force_warehouse_id)) {
2229 $idtofetch = $force_warehouse_id;
2233 $warehouse =
new Entrepot($this->db);
2234 $result = $warehouse->fetch($idtofetch);
2236 $this->errors = array_merge($this->errors, $warehouse->errors);
2238 $this->warehouse = $warehouse;
2256 $user =
new User($this->db);
2257 $result = $user->fetch($userid);
2258 $this->
user = $user;
2272 $tmpclassname = $this->origin ? $this->origin : $this->origin_type;
2275 if ($tmpclassname ==
'shipping') {
2276 $tmpclassname =
'Expedition';
2278 if ($tmpclassname ==
'delivery') {
2279 $tmpclassname =
'Livraison';
2281 if ($tmpclassname ==
'order_supplier' || $tmpclassname ==
'supplier_order') {
2282 $tmpclassname =
'CommandeFournisseur';
2285 $classname = ucfirst($tmpclassname);
2287 $this->origin_object =
new $classname($this->db);
2289 $this->origin_object->fetch($this->origin_id);
2307 $sql =
"SELECT rowid FROM ".$this->db->prefix().$table;
2308 $sql .=
" WHERE ".$this->db->sanitize($field).
" = '".$this->db->escape($key).
"'";
2309 if (!empty($element)) {
2310 $sql .=
" AND entity IN (".getEntity($element).
")";
2312 $sql .=
" AND entity = ".((int)
$conf->entity);
2315 dol_syslog(get_class($this).
'::fetchObjectFrom', LOG_DEBUG);
2316 $resql = $this->db->query($sql);
2318 $obj = $this->db->fetch_object($resql);
2321 if (method_exists($this,
'fetch')) {
2322 $result = $this->fetch($obj->rowid);
2324 $this->error =
'fetch() method not implemented on '.get_class($this);
2325 dol_syslog(get_class($this).
'::fetchOneLike Error='.$this->error, LOG_ERR);
2326 array_push($this->errors, $this->error);
2346 if (!empty($id) && !empty($field) && !empty($table)) {
2347 if (!preg_match(
'/^[a-zA-Z_][a-zA-Z0-9_]*$/', $table)) {
2348 dol_syslog(get_class($this).
'::getValueFrom Bad table name: '.$table, LOG_WARNING);
2351 if (!preg_match(
'/^[a-zA-Z_][a-zA-Z0-9_.]*$/', $field)) {
2352 dol_syslog(get_class($this).
'::getValueFrom Bad field name: '.$field, LOG_WARNING);
2356 $sql =
"SELECT ".$this->db->sanitize($field).
" FROM ".$this->db->prefix().$this->db->sanitize($table);
2357 $sql .=
" WHERE rowid = ".((int) $id);
2359 dol_syslog(get_class($this).
'::getValueFrom', LOG_DEBUG);
2360 $resql = $this->db->query($sql);
2362 $row = $this->db->fetch_row($resql);
2385 public function setValueFrom($field, $value, $table =
'', $id =
null, $format =
'', $id_field =
'', $fuser =
null, $trigkey =
'', $fk_user_field =
'fk_user_modif')
2389 if (empty($table)) {
2390 $table = $this->table_element;
2395 if (empty($format)) {
2398 if (empty($id_field)) {
2399 $id_field =
'rowid';
2402 $propfield = $field;
2405 if ($table ==
'product') {
2406 if ($field ==
'note_private') {
2408 $propfield =
'note_private';
2409 } elseif ($field ==
'status') {
2411 $propfield =
'status';
2412 } elseif ($field ==
'status_buy') {
2414 $propfield =
'status_buy';
2415 } elseif ($field ==
'status_batch') {
2417 $propfield =
'status_batch';
2421 if (in_array($table, array(
'actioncomm',
'adherent',
'advtargetemailing',
'cronjob',
'establishment'))) {
2422 $fk_user_field =
'fk_user_mod';
2424 if (in_array($table, array(
'prelevement_bons'))) {
2425 $fk_user_field =
'';
2428 if (!preg_match(
'/^[a-zA-Z_][a-zA-Z0-9_]*$/', $table)) {
2429 dol_syslog(get_class($this).
'::getValueFrom Bad table name: '.$table, LOG_WARNING);
2432 if (!preg_match(
'/^[a-zA-Z_][a-zA-Z0-9_.]*$/', $field)) {
2433 dol_syslog(get_class($this).
'::getValueFrom Bad field name: '.$field, LOG_WARNING);
2439 $sql =
"SELECT " . $this->db->sanitize($field);
2440 $sql .=
" FROM " . MAIN_DB_PREFIX . $this->db->sanitize($table);
2441 $sql .=
" WHERE " . $this->db->sanitize($id_field) .
" = " . ((int) $id);
2443 $resql = $this->db->query($sql);
2445 if ($obj = $this->db->fetch_object($resql)) {
2446 if ($format ==
'date') {
2447 $oldvalue = $this->db->jdate($obj->$field);
2449 $oldvalue = $obj->$field;
2453 $this->error = $this->db->lasterror();
2464 $sql =
"UPDATE ".$this->db->prefix().$table.
" SET ";
2466 if ($format ==
'text') {
2467 $sql .= $this->db->sanitize($field).
" = '".$this->db->escape($value).
"'";
2468 } elseif ($format ==
'int') {
2469 $sql .= $this->db->sanitize($field).
" = ".((int) $value);
2470 } elseif ($format ==
'date') {
2471 $sql .= $this->db->sanitize($field).
" = ".($value ?
"'".$this->db->idate($value).
"'" :
"null");
2472 } elseif ($format ==
'dategmt') {
2473 $sql .= $this->db->sanitize($field).
" = ".($value ?
"'".$this->db->idate($value,
'gmt').
"'" :
"null");
2476 if ($fk_user_field) {
2477 if (!empty($fuser) && is_object($fuser)) {
2478 $sql .=
", ".$this->db->sanitize($fk_user_field).
" = ".((int) $fuser->id);
2479 } elseif (empty($fuser) || $fuser !=
'none') {
2480 $sql .=
", ".$this->db->sanitize($fk_user_field).
" = ".((int) $user->id);
2484 $sql .=
" WHERE ".$this->db->sanitize($id_field).
" = ".((int) $id);
2486 $resql = $this->db->query($sql);
2490 if (method_exists($this,
'fetch')) {
2491 $result = $this->fetch(
$id);
2496 $this->oldcopy = clone $this;
2497 if (property_exists($this->oldcopy, $field)) {
2498 $this->oldcopy->$field = $oldvalue;
2500 if ($propfield != $field && property_exists($this->oldcopy, $propfield)) {
2501 $this->oldcopy->$propfield = $oldvalue;
2504 if (empty($this->context[
'actionmsgmore'])) {
2505 $this->context[
'actionmsgmore'] =
'Trigger called by setValueFrom';
2509 $result = $this->call_trigger($trigkey, (!empty($fuser) && is_object($fuser)) ? $fuser : $user);
2515 if (property_exists($this, $field)) {
2516 $this->$field = $value;
2518 if ($propfield != $field && property_exists($this, $propfield)) {
2519 $this->$propfield = $value;
2524 $this->db->commit();
2527 if (property_exists($this, $field)) {
2528 $this->$field = $oldvalue;
2530 if ($propfield != $field && property_exists($this, $propfield)) {
2531 $this->$propfield = $oldvalue;
2533 $this->db->rollback();
2537 if ($this->db->lasterrno() ==
'DB_ERROR_RECORD_ALREADY_EXISTS') {
2538 $this->error =
'DB_ERROR_RECORD_ALREADY_EXISTS';
2540 $this->error = $this->db->lasterror();
2542 $this->db->rollback();
2561 global
$conf, $user;
2563 if (!$this->table_element) {
2564 dol_print_error(
null, get_class($this).
"::load_previous_next_ref was called on object with property table_element not defined");
2567 if ($fieldid ==
'none') {
2572 if (in_array($this->table_element, array(
'facture_rec',
'facture_fourn_rec')) && $fieldid ==
'title') {
2578 if ($user->socid > 0) {
2579 $socid = $user->socid;
2584 $aliastablesociete =
's';
2585 if ($this->element ==
'societe') {
2586 $aliastablesociete =
'te';
2588 $restrictiononfksoc = empty($this->restrictiononfksoc) ? 0 : $this->restrictiononfksoc;
2589 $sql =
"SELECT MAX(te.".$this->db->sanitize($fieldid).
")";
2590 $sql .=
" FROM ".(empty($nodbprefix) ? $this->db->prefix() :
'').$this->table_element.
" as te";
2591 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2592 $tmparray = explode(
'@', $this->ismultientitymanaged);
2593 $sql .=
", ".$this->db->prefix().$this->db->sanitize($tmparray[1]).
" as ".($tmparray[1] ==
'societe' ?
's' :
'parenttable');
2594 } elseif ($restrictiononfksoc == 1 && $this->element !=
'societe' && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2595 $sql .=
", ".$this->db->prefix().
"societe as s";
2596 } elseif ($restrictiononfksoc == 2 && $this->element !=
'societe' && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2597 $sql .=
" LEFT JOIN ".$this->db->prefix().
"societe as s ON te.fk_soc = s.rowid";
2599 if ($restrictiononfksoc && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2600 $sql .=
" LEFT JOIN ".$this->db->prefix().
"societe_commerciaux as sc ON ".$aliastablesociete.
".rowid = sc.fk_soc";
2602 if ($fieldid ==
'rowid') {
2603 $sql .=
" WHERE te.".$this->db->sanitize($fieldid).
" < ".((int) $this->
id);
2604 } elseif ($fieldid ==
'label') {
2606 $sql .=
" WHERE te.".$this->db->sanitize($fieldid).
" < '".$this->db->escape((
string) $this->label).
"'";
2608 $sql .=
" WHERE te.".$this->db->sanitize($fieldid).
" < '".$this->db->escape((
string) $this->
ref).
"'";
2610 if ($restrictiononfksoc == 1 && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2611 $sql .=
" AND sc.fk_user = ".((int) $user->id);
2613 if ($restrictiononfksoc == 2 && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2614 $sql .=
" AND (sc.fk_user = ".((int) $user->id).
' OR te.fk_soc IS NULL)';
2617 $filtermax = $filter;
2622 if ($errormessage) {
2623 if (!preg_match(
'/^\s*AND/i', $filtermax)) {
2631 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2632 $tmparray = explode(
'@', $this->ismultientitymanaged);
2633 $sql .=
" AND te.".$this->db->sanitize($tmparray[0]).
" = ".($tmparray[1] ==
"societe" ?
"s" :
"parenttable").
".rowid";
2634 } elseif ($restrictiononfksoc == 1 && $this->element !=
'societe' && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2635 $sql .=
' AND te.fk_soc = s.rowid';
2637 if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
2638 if ($this->element ==
'user' &&
getDolGlobalInt(
'MULTICOMPANY_TRANSVERSE_MODE')) {
2639 if (!empty($user->admin) && empty($user->entity) &&
$conf->entity == 1) {
2640 $sql .=
" AND te.entity IS NOT NULL";
2642 $sql .=
" AND te.rowid IN (SELECT ug.fk_user FROM ".$this->db->prefix().
"usergroup_user as ug WHERE ug.entity IN (".
getEntity(
'usergroup').
"))";
2645 $sql .=
' AND te.entity IN ('.getEntity($this->element).
')';
2648 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged) && $this->element !=
'societe') {
2649 $tmparray = explode(
'@', $this->ismultientitymanaged);
2650 $sql .=
' AND parenttable.entity IN ('.getEntity($tmparray[1]).
')';
2652 if ($restrictiononfksoc == 1 && $socid && $this->element !=
'societe') {
2653 $sql .=
' AND te.fk_soc = '.((int) $socid);
2655 if ($restrictiononfksoc == 2 && $socid && $this->element !=
'societe') {
2656 $sql .=
' AND (te.fk_soc = '.((int) $socid).
' OR te.fk_soc IS NULL)';
2658 if ($restrictiononfksoc && $socid && $this->element ==
'societe') {
2659 $sql .=
' AND te.rowid = '.((int) $socid);
2663 $result = $this->db->query($sql);
2665 $this->error = $this->db->lasterror();
2668 $row = $this->db->fetch_row($result);
2669 $this->ref_previous = $row[0];
2671 $sql =
"SELECT MIN(te.".$this->db->sanitize($fieldid).
")";
2672 $sql .=
" FROM ".(empty($nodbprefix) ? $this->db->prefix() :
'').$this->table_element.
" as te";
2673 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2674 $tmparray = explode(
'@', $this->ismultientitymanaged);
2675 $sql .=
", ".$this->db->prefix().$this->db->sanitize($tmparray[1]).
" as ".($tmparray[1] ==
'societe' ?
's' :
'parenttable');
2676 } elseif ($restrictiononfksoc == 1 && $this->element !=
'societe' && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2677 $sql .=
", ".$this->db->prefix().
"societe as s";
2678 } elseif ($restrictiononfksoc == 2 && $this->element !=
'societe' && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2679 $sql .=
" LEFT JOIN ".$this->db->prefix().
"societe as s ON te.fk_soc = s.rowid";
2681 if ($restrictiononfksoc && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2682 $sql .=
" LEFT JOIN ".$this->db->prefix().
"societe_commerciaux as sc ON ".$aliastablesociete.
".rowid = sc.fk_soc";
2684 if ($fieldid ==
'rowid') {
2685 $sql .=
" WHERE te.".$this->db->sanitize($fieldid).
" > ".((int) $this->
id);
2686 } elseif ($fieldid ==
'label') {
2688 $sql .=
" WHERE te.".$this->db->sanitize($fieldid).
" > '".$this->db->escape((
string) $this->label).
"'";
2690 $sql .=
" WHERE te.".$this->db->sanitize($fieldid).
" > '".$this->db->escape((
string) $this->
ref).
"'";
2692 if ($restrictiononfksoc == 1 && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2693 $sql .=
" AND (sc.fk_user = ".((int) $user->id);
2695 $userschilds = $user->getAllChildIds();
2696 $sql .=
" OR sc.fk_user IN (".$this->db->sanitize(implode(
',', $userschilds)).
")";
2700 if ($restrictiononfksoc == 2 && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2701 $sql .=
" AND (sc.fk_user = ".((int) $user->id).
' OR te.fk_soc IS NULL)';
2704 $filtermin = $filter;
2709 if ($errormessage) {
2710 if (!preg_match(
'/^\s*AND/i', $filtermin)) {
2720 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2721 $tmparray = explode(
'@', $this->ismultientitymanaged);
2722 $sql .=
" AND te.".$this->db->sanitize($tmparray[0]).
" = ".($tmparray[1] ==
"societe" ?
"s" :
"parenttable").
".rowid";
2723 } elseif ($restrictiononfksoc == 1 && $this->element !=
'societe' && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2724 $sql .=
' AND te.fk_soc = s.rowid';
2726 if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
2727 if ($this->element ==
'user' &&
getDolGlobalInt(
'MULTICOMPANY_TRANSVERSE_MODE')) {
2728 if (!empty($user->admin) && empty($user->entity) &&
$conf->entity == 1) {
2729 $sql .=
" AND te.entity IS NOT NULL";
2731 $sql .=
" AND te.rowid IN (SELECT ug.fk_user FROM ".$this->db->prefix().
"usergroup_user as ug WHERE ug.entity IN (".
getEntity(
'usergroup').
"))";
2734 $sql .=
' AND te.entity IN ('.getEntity($this->element).
')';
2737 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged) && $this->element !=
'societe') {
2738 $tmparray = explode(
'@', $this->ismultientitymanaged);
2739 $sql .=
' AND parenttable.entity IN ('.getEntity($tmparray[1]).
')';
2741 if ($restrictiononfksoc == 1 && $socid && $this->element !=
'societe') {
2742 $sql .=
' AND te.fk_soc = '.((int) $socid);
2744 if ($restrictiononfksoc == 2 && $socid && $this->element !=
'societe') {
2745 $sql .=
' AND (te.fk_soc = '.((int) $socid).
' OR te.fk_soc IS NULL)';
2747 if ($restrictiononfksoc && $socid && $this->element ==
'societe') {
2748 $sql .=
' AND te.rowid = '.((int) $socid);
2753 $result = $this->db->query($sql);
2755 $this->error = $this->db->lasterror();
2758 $row = $this->db->fetch_row($result);
2759 $this->ref_next = $row[0];
2774 $contactAlreadySelected = array();
2779 if ($source ==
'thirdparty') {
2780 $contactAlreadySelected[$i] = $tab[$i][
'socid'];
2782 $contactAlreadySelected[$i] = $tab[$i][
'id'];
2786 return $contactAlreadySelected;
2802 if (!$this->table_element) {
2803 dol_syslog(get_class($this).
"::setProject was called on object with property table_element not defined", LOG_ERR);
2807 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
2808 if ($this->table_element ==
'actioncomm') {
2810 $sql .=
" SET fk_project = ".((int) $projectid);
2812 $sql .=
" SET fk_project = NULL";
2814 $sql .=
' WHERE id = '.((int) $this->
id);
2816 } elseif (!empty($this->fields[
'fk_project'])) {
2818 $sql .=
" SET fk_project = ".((int) $projectid);
2820 $sql .=
" SET fk_project = NULL";
2822 $sql .=
' WHERE rowid = '.((int) $this->
id);
2825 $sql .=
' SET fk_projet = '.((int) $projectid);
2827 $sql .=
' SET fk_projet = NULL';
2829 $sql .=
" WHERE rowid = ".((int) $this->
id);
2834 dol_syslog(get_class($this).
"::setProject", LOG_DEBUG);
2835 if ($this->db->query($sql)) {
2836 $this->fk_project = ((int) $projectid);
2843 if (!$error && !$notrigger) {
2845 $result = $this->call_trigger(strtoupper($this->element) .
'_MODIFY', $user);
2854 $this->db->rollback();
2857 $this->db->commit();
2875 dol_syslog(get_class($this).
'::setPaymentMethods('.$id.
')');
2877 if ($this->
status >= 0 || $this->element ==
'societe') {
2881 $fieldname =
'fk_mode_reglement';
2882 $triggerName = (empty($this->TRIGGER_PREFIX) ? strtoupper(get_class($this)) : $this->TRIGGER_PREFIX);
2883 if ($this->element ==
'societe') {
2884 $fieldname =
'mode_reglement';
2885 $triggerName =
'COMPANY';
2887 if (get_class($this) ==
'Facture') {
2888 $triggerName =
'BILL';
2890 if (get_class($this) ==
'Fournisseur') {
2891 $fieldname =
'mode_reglement_supplier';
2892 $triggerName =
'BILL_SUPPLIER';
2894 if (get_class($this) ==
'Tva') {
2895 $fieldname =
'fk_typepayment';
2896 $triggerName =
'VAT';
2898 if (get_class($this) ==
'Salary') {
2899 $fieldname =
'fk_typepayment';
2902 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
2903 $sql .=
" SET ".$this->db->sanitize($fieldname).
" = ".(($id > 0 || $id ==
'0') ? ((
int) $id) :
'NULL');
2904 $sql .=
' WHERE rowid = '.((int) $this->
id);
2906 if ($this->db->query($sql)) {
2907 $this->mode_reglement_id = $id;
2909 if (get_class($this) ==
'Fournisseur') {
2910 $this->mode_reglement_supplier_id = $id;
2914 if (!$error && !$notrigger) {
2916 $result = $this->call_trigger($triggerName.
'_MODIFY', $user);
2924 dol_syslog(get_class($this).
'::setPaymentMethods Error '.$this->db->error());
2925 $this->error = $this->db->error();
2929 dol_syslog(get_class($this).
'::setPaymentMethods, status of the object is incompatible');
2930 $this->error =
'Status of the object is incompatible '.$this->status;
2943 dol_syslog(get_class($this).
'::setMulticurrencyCode('.$code.
')');
2944 if ($this->
status >= 0 || $this->element ==
'societe') {
2945 $sql =
'UPDATE '.$this->db->prefix().$this->table_element;
2946 $sql .=
" SET multicurrency_code = '".$this->db->escape($code).
"'";
2947 $sql .=
' WHERE rowid='.((int) $this->
id);
2949 if ($this->db->query($sql)) {
2950 $this->multicurrency_code = $code;
2954 $this->setMulticurrencyRate($rate, 2);
2959 dol_syslog(get_class($this).
'::setMulticurrencyCode Error '.$sql.
' - '.$this->db->error());
2960 $this->error = $this->db->error();
2964 dol_syslog(get_class($this).
'::setMulticurrencyCode, status of the object is incompatible');
2965 $this->error =
'Status of the object is incompatible '.$this->status;
2977 public function setMulticurrencyRate($rate, $mode = 1)
2979 dol_syslog(get_class($this).
'::setMulticurrencyRate('.$rate.
', '.$mode.
')');
2980 if ($this->
status >= 0 || $this->element ==
'societe') {
2981 $sql =
'UPDATE '.$this->db->prefix().$this->table_element;
2982 $sql .=
" SET multicurrency_tx = ".((float) $rate);
2983 $sql .=
' WHERE rowid='.((int) $this->
id);
2985 if ($this->db->query($sql)) {
2986 $this->multicurrency_tx = $rate;
2989 if (!empty($this->lines)) {
2990 foreach ($this->lines as &$line) {
2993 $line->subprice = 0;
2998 $line->multicurrency_subprice = 0;
3001 switch ($this->element) {
3005 '@phan-var-force Propal $this';
3006 '@phan-var-force PropaleLigne $line';
3011 $line->remise_percent,
3013 $line->localtax1_tx,
3014 $line->localtax2_tx,
3015 ($line->description ? $line->description : $line->desc),
3018 $line->special_code,
3019 $line->fk_parent_line,
3020 $line->skip_update_total,
3021 $line->fk_fournprice,
3024 $line->product_type,
3027 $line->array_options,
3029 $line->multicurrency_subprice
3035 '@phan-var-force Commande $this';
3036 '@phan-var-force OrderLine $line';
3039 ($line->description ? $line->description : $line->desc),
3042 $line->remise_percent,
3044 $line->localtax1_tx,
3045 $line->localtax2_tx,
3050 $line->product_type,
3051 $line->fk_parent_line,
3052 $line->skip_update_total,
3053 $line->fk_fournprice,
3056 $line->special_code,
3057 $line->array_options,
3059 $line->multicurrency_subprice
3065 '@phan-var-force Facture $this';
3066 '@phan-var-force FactureLigne $line';
3069 ($line->description ? $line->description : $line->desc),
3072 $line->remise_percent,
3076 $line->localtax1_tx,
3077 $line->localtax2_tx,
3080 $line->product_type,
3081 $line->fk_parent_line,
3082 $line->skip_update_total,
3083 $line->fk_fournprice,
3086 $line->special_code,
3087 $line->array_options,
3088 $line->situation_percent,
3090 $line->multicurrency_subprice
3096 '@phan-var-force FactureRec $this';
3097 '@phan-var-force FactureLigneRec $line';
3100 ($line->description ? $line->description : $line->desc),
3104 $line->localtax1_tx,
3105 $line->localtax2_tx,
3107 $line->remise_percent,
3112 $line->product_type,
3114 $line->special_code,
3117 $line->multicurrency_subprice,
3121 $line->fk_fournprice,
3123 $line->fk_parent_line
3126 case 'supplier_proposal':
3129 '@phan-var-force SupplierProposal $this';
3130 '@phan-var-force SupplierProposalLine $line';
3135 $line->remise_percent,
3137 $line->localtax1_tx,
3138 $line->localtax2_tx,
3139 ($line->description ? $line->description : $line->desc),
3142 $line->special_code,
3143 $line->fk_parent_line,
3144 $line->skip_update_total,
3145 $line->fk_fournprice,
3148 $line->product_type,
3149 $line->array_options,
3151 (int) $line->fk_unit,
3152 $line->multicurrency_subprice
3155 case 'order_supplier':
3158 '@phan-var-force CommandeFournisseur $this';
3159 '@phan-var-force CommandeFournisseurLigne $line';
3162 ($line->description ? $line->description : $line->desc),
3165 $line->remise_percent,
3167 $line->localtax1_tx,
3168 $line->localtax2_tx,
3171 $line->product_type,
3175 $line->array_options,
3177 $line->multicurrency_subprice,
3181 case 'invoice_supplier':
3184 '@phan-var-force FactureFournisseur $this';
3185 '@phan-var-force SupplierInvoiceLIne $line';
3188 ($line->description ? $line->description : $line->desc),
3191 $line->localtax1_tx,
3192 $line->localtax2_tx,
3197 $line->product_type,
3198 $line->remise_percent,
3202 $line->array_options,
3204 $line->multicurrency_subprice,
3209 dol_syslog(get_class($this).
'::setMulticurrencyRate no updateline defined', LOG_DEBUG);
3217 dol_syslog(get_class($this).
'::setMulticurrencyRate Error '.$sql.
' - '.$this->db->error());
3218 $this->error = $this->db->error();
3222 dol_syslog(get_class($this).
'::setMulticurrencyRate, status of the object is incompatible');
3223 $this->error =
'Status of the object is incompatible '.$this->status;
3238 if ($this->
status >= 0 || $this->element ==
'societe') {
3240 $fieldname =
'fk_cond_reglement';
3241 if ($this->element ==
'societe') {
3242 $fieldname =
'cond_reglement';
3244 if (get_class($this) ==
'Fournisseur') {
3245 $fieldname =
'cond_reglement_supplier';
3248 if (empty($deposit_percent) || $deposit_percent < 0) {
3249 $deposit_percent = (float)
getDictionaryValue(
'c_payment_term',
'deposit_percent', $id);
3252 if ($deposit_percent > 100) {
3253 $deposit_percent = 100;
3256 $sql =
'UPDATE '.$this->db->prefix().$this->table_element;
3257 $sql .=
" SET ".$this->db->sanitize($fieldname).
" = ".(($id > 0 || $id ==
'0') ? ((
int) $id) :
'NULL');
3258 if (in_array($this->table_element, array(
'propal',
'commande',
'supplier_proposal',
'commande_fournisseur',
'societe'))) {
3259 $sql .=
" , deposit_percent = " . (empty($deposit_percent) ?
'NULL' :
"'".$this->db->escape((
string) $deposit_percent).
"'");
3261 $sql .=
' WHERE rowid = '.((int) $this->
id);
3263 if ($this->db->query($sql)) {
3264 $this->cond_reglement_id = $id;
3266 if (get_class($this) ==
'Fournisseur') {
3267 $this->cond_reglement_supplier_id = $id;
3269 $this->deposit_percent = $deposit_percent;
3272 dol_syslog(get_class($this).
'::setPaymentTerms Error '.$sql.
' - '.$this->db->error());
3273 $this->error = $this->db->error();
3277 dol_syslog(get_class($this).
'::setPaymentTerms, status of the object is incompatible');
3278 $this->error =
'Status of the object is incompatible '.$this->status;
3291 dol_syslog(get_class($this).
'::setTransportMode('.$id.
')');
3292 if ($this->
status >= 0 || $this->element ==
'societe') {
3293 $fieldname =
'fk_transport_mode';
3294 if ($this->element ==
'societe') {
3295 $fieldname =
'transport_mode';
3297 if (get_class($this) ==
'Fournisseur') {
3298 $fieldname =
'transport_mode_supplier';
3301 $sql =
'UPDATE '.$this->db->prefix().$this->table_element;
3302 $sql .=
" SET ".$this->db->sanitize($fieldname).
" = ".(($id > 0 || $id ==
'0') ? ((
int) $id) :
'NULL');
3303 $sql .=
' WHERE rowid='.((int) $this->
id);
3305 if ($this->db->query($sql)) {
3306 $this->transport_mode_id = $id;
3308 if (get_class($this) ==
'Fournisseur') {
3309 $this->transport_mode_supplier_id = $id;
3313 dol_syslog(get_class($this).
'::setTransportMode Error '.$sql.
' - '.$this->db->error());
3314 $this->error = $this->db->error();
3318 dol_syslog(get_class($this).
'::setTransportMode, status of the object is incompatible');
3319 $this->error =
'Status of the object is incompatible '.$this->status;
3333 $fieldname =
'fk_delivery_address';
3334 if ($this->element ==
'delivery' || $this->element ==
'shipping') {
3335 $fieldname =
'fk_address';
3338 $sql =
"UPDATE ".$this->db->prefix().$this->table_element.
" SET ".$this->db->sanitize($fieldname).
" = ".((int) $id);
3339 $sql .=
" WHERE rowid = ".((int) $this->
id).
" AND fk_statut = 0";
3341 if ($this->db->query($sql)) {
3342 $this->fk_delivery_address =
$id;
3345 $this->error = $this->db->error();
3346 dol_syslog(get_class($this).
'::setDeliveryAddress Error '.$this->error);
3364 if (empty($userused)) {
3370 if (!$this->table_element) {
3371 dol_syslog(get_class($this).
"::setShippingMethod was called on object with property table_element not defined", LOG_ERR);
3377 if ($shipping_method_id < 0) {
3378 $shipping_method_id =
'NULL';
3380 dol_syslog(get_class($this).
'::setShippingMethod('.$shipping_method_id.
')');
3382 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
3383 $sql .=
" SET fk_shipping_method = ".((int) $shipping_method_id);
3384 $sql .=
" WHERE rowid=".((int) $this->
id);
3385 $resql = $this->db->query($sql);
3387 dol_syslog(get_class($this).
'::setShippingMethod Error ', LOG_DEBUG);
3388 $this->error = $this->db->lasterror();
3393 $this->context = array(
'shippingmethodupdate' => 1);
3394 $triggerPrefix = (empty($this->TRIGGER_PREFIX) ? strtoupper(get_class($this)) : $this->TRIGGER_PREFIX);
3395 $result = $this->call_trigger($triggerPrefix.
'_MODIFY', $userused);
3403 $this->db->rollback();
3406 $this->shipping_method_id = ($shipping_method_id ==
'NULL') ?
null : $shipping_method_id;
3407 $this->db->commit();
3421 if (!$this->table_element) {
3422 dol_syslog(get_class($this).
"::setWarehouse was called on object with property table_element not defined", LOG_ERR);
3425 if ($warehouse_id < 0) {
3426 $warehouse_id =
'NULL';
3428 dol_syslog(get_class($this).
'::setWarehouse('.$warehouse_id.
')');
3430 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
3431 $sql .=
" SET fk_warehouse = ".((int) $warehouse_id);
3432 $sql .=
" WHERE rowid=".((int) $this->
id);
3434 if ($this->db->query($sql)) {
3435 $this->warehouse_id = ($warehouse_id ==
'NULL') ?
null : $warehouse_id;
3438 dol_syslog(get_class($this).
'::setWarehouse Error ', LOG_DEBUG);
3439 $this->error = $this->db->error();
3454 if (!$this->table_element) {
3455 dol_syslog(get_class($this).
"::setDocModel was called on object with property table_element not defined", LOG_ERR);
3459 $newmodelpdf =
dol_trunc($modelpdf, 255);
3461 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
3462 $sql .=
" SET model_pdf = '".$this->db->escape($newmodelpdf).
"'";
3463 $sql .=
" WHERE rowid = ".((int) $this->
id);
3465 dol_syslog(get_class($this).
"::setDocModel", LOG_DEBUG);
3466 $resql = $this->db->query($sql);
3468 $this->model_pdf = $modelpdf;
3489 if (empty($userused)) {
3495 if (!$this->table_element) {
3496 dol_syslog(get_class($this).
"::setBankAccount was called on object with property table_element not defined", LOG_ERR);
3501 if ($fk_account < 0) {
3502 $fk_account =
'NULL';
3504 dol_syslog(get_class($this).
'::setBankAccount('.$fk_account.
')');
3506 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
3507 $sql .=
" SET fk_account = ".((int) $fk_account);
3508 $sql .=
" WHERE rowid=".((int) $this->
id);
3510 $resql = $this->db->query($sql);
3512 dol_syslog(get_class($this).
'::setBankAccount Error '.$sql.
' - '.$this->db->error());
3513 $this->error = $this->db->lasterror();
3518 $this->context[
'bankaccountupdate'] = 1;
3520 $triggerName = (empty($this->TRIGGER_PREFIX) ? strtoupper(get_class($this)) : $this->TRIGGER_PREFIX);
3521 $result = $this->call_trigger($triggerName .
'_MODIFY', $userused);
3529 $this->db->rollback();
3532 $this->fk_account = ($fk_account ==
'NULL') ?
null : $fk_account;
3533 $this->db->commit();
3551 public function line_order($renum =
false, $rowidorder =
'ASC', $fk_parent_line =
true)
3554 if (!$this->table_element_line) {
3555 dol_syslog(get_class($this).
"::line_order was called on object with property table_element_line not defined", LOG_ERR);
3558 if (!$this->fk_element) {
3559 dol_syslog(get_class($this).
"::line_order was called on object with property fk_element not defined", LOG_ERR);
3563 $fieldposition =
'rang';
3564 if (in_array($this->table_element_line, array(
'bom_bomline',
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3565 $fieldposition =
'position';
3570 $sql =
"SELECT count(rowid) FROM ".$this->db->prefix().$this->db->sanitize($this->table_element_line);
3571 $sql .=
" WHERE ".$this->db->sanitize($this->fk_element).
" = ".((int) $this->
id);
3573 $sql .=
" AND " . $this->db->sanitize($fieldposition) .
" = 0";
3576 $sql .=
" AND " . $this->db->sanitize($fieldposition) .
" <> 0";
3579 dol_syslog(get_class($this).
"::line_order", LOG_DEBUG);
3580 $resql = $this->db->query($sql);
3582 $row = $this->db->fetch_row($resql);
3592 $sql =
"SELECT rowid FROM ".$this->db->prefix().$this->db->sanitize($this->table_element_line);
3593 $sql .=
" WHERE ".$this->db->sanitize($this->fk_element).
" = ".((int) $this->
id);
3594 if ($fk_parent_line) {
3595 $sql .=
' AND fk_parent_line IS NULL';
3597 $sql .=
" ORDER BY " . $this->db->sanitize($fieldposition) .
" ASC, rowid " . $this->db->sanitize($rowidorder);
3599 dol_syslog(get_class($this).
"::line_order search all parent lines", LOG_DEBUG);
3600 $resql = $this->db->query($sql);
3603 $num = $this->db->num_rows($resql);
3606 $row = $this->db->fetch_row($resql);
3608 if ($fk_parent_line) {
3611 if (!empty($children)) {
3612 foreach ($children as $child) {
3613 array_push($rows, $child);
3620 if (!empty($rows)) {
3621 foreach ($rows as $key => $row) {
3641 $fieldposition =
'rang';
3642 if (in_array($this->table_element_line, array(
'bom_bomline',
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3643 $fieldposition =
'position';
3648 $sql =
"SELECT rowid FROM ".$this->db->prefix().$this->db->sanitize($this->table_element_line);
3649 $sql .=
" WHERE ".$this->db->sanitize($this->fk_element).
" = ".((int) $this->
id);
3650 $sql .=
' AND fk_parent_line = '.((int) $id);
3651 $sql .=
" ORDER BY " . $this->db->sanitize($fieldposition) .
" ASC";
3653 dol_syslog(get_class($this).
"::getChildrenOfLine search children lines for line ".$id, LOG_DEBUG);
3655 $resql = $this->db->query($sql);
3656 if (!$resql || $this->db->num_rows($resql) <= 0) {
3660 while ($row = $this->db->fetch_row($resql)) {
3662 if (!empty($includealltree) && $includealltree <= 1000) {
3663 $rows = array_merge($rows, $this->
getChildrenOfLine($row[0], $includealltree + 1));
3677 public function line_up($rowid, $fk_parent_line =
true)
3680 $this->
line_order(
false,
'ASC', $fk_parent_line);
3700 $this->
line_order(
false,
'ASC', $fk_parent_line);
3721 global $hookmanager;
3722 $fieldposition =
'rang';
3723 if (in_array($this->table_element_line, array(
'bom_bomline',
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3724 $fieldposition =
'position';
3727 $sql =
"UPDATE ".$this->db->prefix().$this->table_element_line.
" SET ".$this->db->sanitize($fieldposition).
" = ".((int) $rang);
3728 $sql .=
' WHERE rowid = '.((int) $rowid);
3730 dol_syslog(get_class($this).
"::updateRangOfLine", LOG_DEBUG);
3731 if (!$this->db->query($sql)) {
3736 $parameters = array(
'rowid' => $rowid,
'rang' => $rang,
'fieldposition' => $fieldposition);
3738 $reshook = $hookmanager->executeHooks(
'afterRankOfLineUpdate', $parameters, $this, $action);
3752 $num = count($rows);
3753 for ($i = 0; $i < $num; $i++) {
3771 $fieldposition =
'rang';
3772 if (in_array($this->table_element_line, array(
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3773 $fieldposition =
'position';
3776 $sql =
"UPDATE ".$this->db->prefix().$this->db->sanitize($this->table_element_line).
" SET ".$this->db->sanitize($fieldposition).
" = ".((int) $rang);
3777 $sql .=
" WHERE ".$this->db->sanitize($this->fk_element).
" = ".((int) $this->
id);
3778 $sql .=
" AND " . $this->db->sanitize($fieldposition) .
" = " . ((int) ($rang - 1));
3779 if (!$this->db->query($sql)) {
3780 $this->error = $this->db->lasterror();
3784 $sql =
"UPDATE ".$this->db->prefix().$this->table_element_line.
" SET ".$this->db->sanitize($fieldposition).
" = ".((int) ($rang - 1));
3785 $sql .=
' WHERE rowid = '.((int) $rowid);
3786 if (!$this->db->query($sql)) {
3787 $this->error = $this->db->lasterror();
3804 if ($rang >= $max) {
3808 $fieldposition =
'rang';
3809 if (in_array($this->table_element_line, array(
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3810 $fieldposition =
'position';
3813 $sql =
"UPDATE ".$this->db->prefix().$this->db->sanitize($this->table_element_line).
" SET ".$this->db->sanitize($fieldposition).
" = ".((int) $rang);
3814 $sql .=
" WHERE ".$this->db->sanitize($this->fk_element).
" = ".((int) $this->
id);
3815 $sql .=
" AND " . $this->db->sanitize($fieldposition) .
" = " . ((int) ($rang + 1));
3816 if (!$this->db->query($sql)) {
3817 $this->error = $this->db->lasterror();
3821 $sql =
"UPDATE ".$this->db->prefix().$this->table_element_line.
" SET ".$this->db->sanitize($fieldposition).
" = ".((int) ($rang + 1));
3822 $sql .=
' WHERE rowid = '.((int) $rowid);
3823 if (!$this->db->query($sql)) {
3824 $this->error = $this->db->lasterror();
3839 $fieldposition =
'rang';
3840 if (in_array($this->table_element_line, array(
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3841 $fieldposition =
'position';
3844 $sql =
"SELECT " . $this->db->sanitize($fieldposition) .
" FROM ".$this->db->prefix().$this->db->sanitize($this->table_element_line);
3845 $sql .=
" WHERE rowid = ".((int) $rowid);
3847 dol_syslog(get_class($this).
"::getRangOfLine", LOG_DEBUG);
3848 $resql = $this->db->query($sql);
3853 $row = $this->db->fetch_row($resql);
3865 $fieldposition =
'rang';
3866 if (in_array($this->table_element_line, array(
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3867 $fieldposition =
'position';
3870 $sql =
"SELECT rowid FROM ".$this->db->prefix().$this->db->sanitize($this->table_element_line);
3871 $sql .=
" WHERE ".$this->db->sanitize($this->fk_element).
" = ".((int) $this->
id);
3872 $sql .=
" AND " . $this->db->sanitize($fieldposition) .
" = ".((int) $rang);
3873 $resql = $this->db->query($sql);
3878 $row = $this->db->fetch_row($resql);
3892 $positionfield =
'rang';
3893 if (in_array($this->table_element, array(
'bom_bom',
'product_attribute'))) {
3894 $positionfield =
'position';
3897 $sql =
"SELECT max(".$this->db->sanitize($positionfield).
") FROM ".$this->db->prefix().$this->db->sanitize($this->table_element_line);
3898 $sql .=
" WHERE ".$this->db->sanitize($this->fk_element).
" = ".((int) $this->
id);
3901 if ($fk_parent_line) {
3902 $sql .=
" AND fk_parent_line = ".((int) $fk_parent_line);
3905 dol_syslog(get_class($this).
"::line_max", LOG_DEBUG);
3906 $resql = $this->db->query($sql);
3908 $row = $this->db->fetch_row($resql);
3910 if ($fk_parent_line) {
3911 if (!empty($row[0])) {
3934 if (!$this->table_element) {
3935 dol_syslog(get_class($this).
"::update_ref_ext was called on object with property table_element not defined", LOG_ERR);
3939 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
3940 $sql .=
" SET ref_ext = '".$this->db->escape($ref_ext).
"'";
3942 $sql .=
" WHERE ".(isset($this->table_rowid) ? $this->table_rowid :
'rowid').
" = ".((
int) $this->id);
3944 dol_syslog(get_class($this).
"::update_ref_ext", LOG_DEBUG);
3945 if ($this->db->query($sql)) {
3946 $this->ref_ext = $ref_ext;
3949 $this->error = $this->db->error();
3968 if (!$this->table_element) {
3969 $this->error =
'update_note was called on object with property table_element not defined';
3970 dol_syslog(get_class($this).
"::update_note was called on object with property table_element not defined", LOG_ERR);
3973 if (!in_array($suffix, array(
'',
'_public',
'_private'))) {
3974 $this->error =
'update_note Parameter suffix must be empty, \'_private\' or \'_public\'';
3975 dol_syslog(get_class($this).
"::update_note Parameter suffix must be empty, '_private' or '_public'", LOG_ERR);
3979 $newsuffix = $suffix;
3982 if ($this->table_element ==
'product' && $newsuffix ==
'_private') {
3985 if (in_array($this->table_element, array(
'actioncomm',
'adherent',
'advtargetemailing',
'cronjob',
'establishment'))) {
3986 $fieldusermod =
"fk_user_mod";
3987 } elseif ($this->table_element ==
'ecm_files') {
3988 $fieldusermod =
"fk_user_m";
3990 $fieldusermod =
"fk_user_modif";
3992 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
3993 $sql .=
" SET note".$this->db->sanitize($newsuffix).
" = ".(!empty($note) ? (
"'".$this->db->escape($note).
"'") :
"NULL");
3994 $sql .=
", ".$this->db->sanitize($fieldusermod).
" = ".((int) $user->id);
3995 $sql .=
" WHERE rowid = ".((int) $this->
id);
3997 dol_syslog(get_class($this).
"::update_note", LOG_DEBUG);
3998 if ($this->db->query($sql)) {
3999 if ($suffix ==
'_public') {
4000 $this->note_public = $note;
4001 } elseif ($suffix ==
'_private') {
4002 $this->note_private = $note;
4004 $this->note = $note;
4005 $this->note_private = $note;
4007 if (empty($notrigger)) {
4009 switch ($this->element) {
4011 $triggerName =
'COMPANY_MODIFY';
4014 $triggerName =
'BILL_MODIFY';
4016 case 'invoice_supplier':
4017 $triggerName =
'BILL_SUPPLIER_MODIFY';
4020 $triggerName =
'BILLREC_MODIFIY';
4022 case 'expensereport':
4023 $triggerName =
'EXPENSE_REPORT_MODIFY';
4026 $triggerName = (!empty($this->TRIGGER_PREFIX) ? $this->TRIGGER_PREFIX : strtoupper($this->element)) .
'_MODIFY';
4028 $ret = $this->call_trigger($triggerName, $user);
4035 $this->error = $this->db->lasterror();
4066 public function update_price($exclspec = 0, $roundingadjust =
'auto', $nodatabaseupdate = 0, $seller =
null)
4069 global
$conf, $hookmanager, $action;
4071 $parameters = array(
'exclspec' => $exclspec,
'roundingadjust' => $roundingadjust,
'nodatabaseupdate' => $nodatabaseupdate,
'seller' => $seller);
4072 $reshook = $hookmanager->executeHooks(
'updateTotalPrice', $parameters, $this, $action);
4075 } elseif ($reshook < 0) {
4080 $isElementForSupplier =
false;
4081 $roundTotalConstName =
'MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND';
4083 if ($this->element ==
'propal') {
4084 $MODULE =
"MODULE_DISALLOW_UPDATE_PRICE_PROPOSAL";
4085 } elseif ($this->element ==
'commande' || $this->element ==
'order') {
4086 $MODULE =
"MODULE_DISALLOW_UPDATE_PRICE_ORDER";
4087 } elseif ($this->element ==
'facture' || $this->element ==
'invoice') {
4088 $MODULE =
"MODULE_DISALLOW_UPDATE_PRICE_INVOICE";
4089 } elseif ($this->element ==
'facture_fourn' || $this->element ==
'supplier_invoice' || $this->element ==
'invoice_supplier' || $this->element ==
'invoice_supplier_rec') {
4090 $isElementForSupplier =
true;
4091 $MODULE =
"MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_INVOICE";
4092 } elseif ($this->element ==
'order_supplier' || $this->element ==
'supplier_order') {
4093 $isElementForSupplier =
true;
4094 $MODULE =
"MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_ORDER";
4095 } elseif ($this->element ==
'supplier_proposal') {
4096 $isElementForSupplier =
true;
4097 $MODULE =
"MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_PROPOSAL";
4099 if ($isElementForSupplier) {
4100 $roundTotalConstName =
'MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND_SUPPLIER';
4103 if (!empty($MODULE)) {
4106 foreach ($modsactivated as $mod) {
4114 include_once DOL_DOCUMENT_ROOT.
'/core/lib/price.lib.php';
4116 $forcedroundingmode = $roundingadjust;
4117 if ($forcedroundingmode ==
'auto' && isset(
$conf->global->{$roundTotalConstName})) {
4119 } elseif ($forcedroundingmode ==
'auto') {
4120 $forcedroundingmode =
'0';
4125 $multicurrency_tx = !empty($this->multicurrency_tx) ? $this->multicurrency_tx : 1;
4128 $fieldtva =
'total_tva';
4129 $fieldlocaltax1 =
'total_localtax1';
4130 $fieldlocaltax2 =
'total_localtax2';
4131 $fieldup =
'subprice';
4132 $base_price_type =
'HT';
4133 if ($this->element ==
'facture_fourn' || $this->element ==
'invoice_supplier') {
4137 if ($this->element ==
'invoice_supplier_rec') {
4140 if ($this->element ==
'expensereport') {
4144 $forcedroundingmode =
'0';
4145 $fieldup =
'value_unit';
4146 $base_price_type =
'TTC';
4149 $sql =
"SELECT rowid, qty, ".$this->db->sanitize($fieldup).
" as up, remise_percent,";
4150 $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,";
4151 $sql .=
' tva_tx as vatrate, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type,';
4152 $sql .=
' info_bits, product_type,';
4153 if ($this->element ==
'expensereport') {
4154 $sql .=
' comments as description';
4156 $sql .=
' description';
4158 if ($this->table_element_line ==
'facturedet') {
4159 $sql .=
', situation_percent';
4161 $sql .=
', multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc';
4162 $sql .=
" FROM ".$this->db->prefix().$this->db->sanitize($this->table_element_line);
4163 $sql .=
" WHERE ".$this->db->sanitize($this->fk_element).
" = ".((int) $this->
id);
4165 $product_field =
'product_type';
4166 if ($this->table_element_line ==
'contratdet') {
4167 $product_field =
'';
4169 if ($product_field) {
4170 $sql .=
" AND ".$this->db->sanitize($product_field).
" <> 9";
4173 $sql .=
' ORDER by rowid';
4175 dol_syslog(get_class($this).
"::update_price", LOG_DEBUG);
4177 $resql = $this->db->query($sql);
4179 $this->total_ht = 0;
4180 $this->total_tva = 0;
4181 $this->total_localtax1 = 0;
4182 $this->total_localtax2 = 0;
4183 $this->total_ttc = 0;
4184 $total_ht_by_vats = array();
4185 $total_tva_by_vats = array();
4186 $total_ttc_by_vats = array();
4187 $this->multicurrency_total_ht = 0;
4188 $this->multicurrency_total_tva = 0;
4189 $this->multicurrency_total_ttc = 0;
4193 $num = $this->db->num_rows($resql);
4196 $obj = $this->db->fetch_object($resql);
4199 $parameters = array(
'fk_element' => $obj->rowid);
4200 $reshook = $hookmanager->executeHooks(
'changeRoundingMode', $parameters, $this, $action);
4202 if (empty($reshook) && $forcedroundingmode ==
'0') {
4204 $localtax_array = array($obj->localtax1_type, $obj->localtax1_tx, $obj->localtax2_type, $obj->localtax2_tx);
4205 $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);
4207 $diff_when_using_price_ht =
price2num((
float) $tmpcal[1] - $obj->total_tva,
'MT', 1);
4208 $diff_on_current_total =
price2num($obj->total_ttc - $obj->total_ht - $obj->total_tva - $obj->total_localtax1 - $obj->total_localtax2,
'MT', 1);
4212 if ($diff_on_current_total) {
4214 $sqlfix =
"UPDATE ".$this->db->prefix().$this->table_element_line;
4215 $sqlfix .=
" SET ".$this->db->sanitize($fieldtva).
" = ".
price2num((
float) $tmpcal[1]).
", total_ttc = ".
price2num((
float) $tmpcal[2]);
4216 $sqlfix .=
", multicurrency_total_tva = ".price2num((
float) $tmpcal[17]).
", multicurrency_total_ttc = ".
price2num((
float) $tmpcal[18]);
4217 $sqlfix .=
" WHERE rowid = ".((int) $obj->rowid);
4218 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);
4219 $resqlfix = $this->db->query($sqlfix);
4223 $obj->total_tva = $tmpcal[1];
4224 $obj->total_ttc = $tmpcal[2];
4225 $obj->multicurrency_total_tva = $tmpcal[17];
4226 $obj->multicurrency_total_ttc = $tmpcal[18];
4227 } elseif ($diff_when_using_price_ht) {
4231 if ((
float) $tmpcal[0] == (
float) $obj->total_ht) {
4234 if ($obj->description !=
'(DEPOSIT)' && !
getDolGlobalInt(
'MAIN_DISABLE_AUTOFIX_CORRUPTED_LINES_WHEN_TOTAL_DOES_NOT_MATCH_RECALCULATION_FROM_UP')) {
4238 $sqlfix =
"UPDATE ".$this->db->prefix().$this->table_element_line;
4239 $sqlfix .=
" SET ".$this->db->sanitize($fieldtva).
" = ".
price2num((
float) $tmpcal[1]).
", total_ttc = ".
price2num((
float) $tmpcal[2]);
4240 $sqlfix .=
", multicurrency_total_tva = ".price2num((
float) $tmpcal[17]).
", multicurrency_total_ttc = ".
price2num((
float) $tmpcal[18]);
4241 $sqlfix .=
" WHERE rowid = ".((int) $obj->rowid);
4243 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);
4245 $resqlfix = $this->db->query($sqlfix);
4249 $obj->total_tva = $tmpcal[1];
4250 $obj->total_ttc = $tmpcal[2];
4251 $obj->multicurrency_total_tva = $tmpcal[17];
4252 $obj->multicurrency_total_ttc = $tmpcal[18];
4258 $this->total_ht += $obj->total_ht;
4259 $this->total_tva += $obj->total_tva;
4260 $this->total_localtax1 += $obj->total_localtax1;
4261 $this->total_localtax2 += $obj->total_localtax2;
4262 $this->total_ttc += $obj->total_ttc;
4263 $this->multicurrency_total_ht += $obj->multicurrency_total_ht;
4264 $this->multicurrency_total_tva += $obj->multicurrency_total_tva;
4265 $this->multicurrency_total_ttc += $obj->multicurrency_total_ttc;
4267 if (!isset($total_ht_by_vats[$obj->vatrate])) {
4268 $total_ht_by_vats[$obj->vatrate] = 0;
4270 if (!isset($total_tva_by_vats[$obj->vatrate])) {
4271 $total_tva_by_vats[$obj->vatrate] = 0;
4273 if (!isset($total_ttc_by_vats[$obj->vatrate])) {
4274 $total_ttc_by_vats[$obj->vatrate] = 0;
4276 $total_ht_by_vats[$obj->vatrate] += $obj->total_ht;
4277 $total_tva_by_vats[$obj->vatrate] += $obj->total_tva;
4278 $total_ttc_by_vats[$obj->vatrate] += $obj->total_ttc;
4280 if ($forcedroundingmode ==
'1') {
4281 if ($base_price_type ==
'TTC') {
4282 $tmpvat =
price2num($total_ttc_by_vats[$obj->vatrate] * $obj->vatrate / (100 + $obj->vatrate),
'MT', 1);
4284 $tmpvat =
price2num($total_ht_by_vats[$obj->vatrate] * $obj->vatrate / 100,
'MT', 1);
4286 $diff =
price2num($total_tva_by_vats[$obj->vatrate] - (
float) $tmpvat,
'MT', 1);
4289 $maxdiff = (10 * pow(10, -1 *
getDolGlobalInt(
'MAIN_MAX_DECIMALS_TOT', 0)));
4290 if (abs((
float) $diff) > $maxdiff) {
4292 $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.';
4294 $this->error = $errmsg;
4299 if ($base_price_type ==
'TTC') {
4300 $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);
4301 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);
4303 $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);
4304 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);
4307 $resqlfix = $this->db->query($sqlfix);
4313 $this->total_tva = (float)
price2num($this->total_tva - (
float) $diff,
'', 1);
4314 $total_tva_by_vats[$obj->vatrate] = (float)
price2num($total_tva_by_vats[$obj->vatrate] - (
float) $diff,
'', 1);
4315 if ($base_price_type ==
'TTC') {
4316 $this->total_ht = (float)
price2num($this->total_ht + (
float) $diff,
'', 1);
4317 $total_ht_by_vats[$obj->vatrate] = (float)
price2num($total_ht_by_vats[$obj->vatrate] + (
float) $diff,
'', 1);
4319 $this->total_ttc = (float)
price2num($this->total_ttc - (
float) $diff,
'', 1);
4320 $total_ttc_by_vats[$obj->vatrate] = (float)
price2num($total_ttc_by_vats[$obj->vatrate] - (
float) $diff,
'', 1);
4330 $this->total_ttc += isset($this->revenuestamp) ? $this->revenuestamp : 0;
4332 $this->multicurrency_total_ttc += isset($this->revenuestamp) ? ($this->revenuestamp * $multicurrency_tx) : 0;
4335 if (!empty($this->situation_cycle_ref) && !empty($this->situation_counter) && $this->situation_counter > 1 && method_exists($this,
'get_prev_sits')) {
4336 '@phan-var-force Facture $this';
4337 include_once DOL_DOCUMENT_ROOT.
'/compta/facture/class/facture.class.php';
4340 $prev_sits = $this->get_prev_sits();
4342 foreach ($prev_sits as $sit) {
4343 $this->total_ht -= $sit->total_ht;
4344 $this->total_tva -= $sit->total_tva;
4345 $this->total_localtax1 -= $sit->total_localtax1;
4346 $this->total_localtax2 -= $sit->total_localtax2;
4347 $this->total_ttc -= $sit->total_ttc;
4348 $this->multicurrency_total_ht -= $sit->multicurrency_total_ht;
4349 $this->multicurrency_total_tva -= $sit->multicurrency_total_tva;
4350 $this->multicurrency_total_ttc -= $sit->multicurrency_total_ttc;
4357 $this->total_ht = (float)
price2num($this->total_ht);
4358 $this->total_tva = (float)
price2num($this->total_tva);
4359 $this->total_localtax1 = (float)
price2num($this->total_localtax1);
4360 $this->total_localtax2 = (float)
price2num($this->total_localtax2);
4361 $this->total_ttc = (float)
price2num($this->total_ttc);
4363 $this->db->free($resql);
4366 $fieldht =
'total_ht';
4368 $fieldlocaltax1 =
'localtax1';
4369 $fieldlocaltax2 =
'localtax2';
4370 $fieldttc =
'total_ttc';
4372 if (in_array($this->element, array(
'propal',
'commande',
'facture',
'facturerec',
'supplier_proposal',
'order_supplier',
'facture_fourn',
'invoice_supplier',
'invoice_supplier_rec',
'expensereport'))) {
4373 $fieldtva =
'total_tva';
4376 if (!$error && empty($nodatabaseupdate)) {
4377 $sql =
"UPDATE ".$this->db->prefix().$this->table_element.
' SET';
4378 $sql .=
" ".$this->db->sanitize($fieldht).
" = ".((float)
price2num($this->total_ht,
'MT', 1)).
",";
4379 $sql .=
" ".$this->db->sanitize($fieldtva).
" = ".((float)
price2num($this->total_tva,
'MT', 1)).
",";
4380 $sql .=
" ".$this->db->sanitize($fieldlocaltax1).
" = ".((float)
price2num($this->total_localtax1,
'MT', 1)).
",";
4381 $sql .=
" ".$this->db->sanitize($fieldlocaltax2).
" = ".((float)
price2num($this->total_localtax2,
'MT', 1)).
",";
4382 $sql .=
" ".$this->db->sanitize($fieldttc).
" = ".((float)
price2num($this->total_ttc,
'MT', 1));
4383 $sql .=
", multicurrency_total_ht = ".((float)
price2num($this->multicurrency_total_ht,
'MT', 1));
4384 $sql .=
", multicurrency_total_tva = ".((float)
price2num($this->multicurrency_total_tva,
'MT', 1));
4385 $sql .=
", multicurrency_total_ttc = ".((float)
price2num($this->multicurrency_total_ttc,
'MT', 1));
4386 $sql .=
" WHERE rowid = ".((int) $this->
id);
4388 dol_syslog(get_class($this).
"::update_price", LOG_DEBUG);
4389 $resql = $this->db->query($sql);
4393 $this->error = $this->db->lasterror();
4394 $this->errors[] = $this->db->lasterror();
4399 $this->db->commit();
4402 $this->db->rollback();
4422 public function add_object_linked($origin =
null, $origin_id =
null, $f_user =
null, $notrigger = 0)
4425 global $user, $hookmanager, $action;
4428 if (empty($this->origin_type) && !empty($this->origin)) {
4429 $this->origin_type = $this->origin;
4431 $origin = (!empty($origin) ? $origin : $this->origin_type);
4432 $origin_id = (!empty($origin_id) ? $origin_id : $this->origin_id);
4433 $f_user = isset($f_user) ? $f_user : $user;
4436 if ($origin ==
'order') {
4437 $origin =
'commande';
4439 if ($origin ==
'invoice') {
4440 $origin =
'facture';
4442 if ($origin ==
'invoice_template') {
4443 $origin =
'facturerec';
4445 if ($origin ==
'supplierorder') {
4446 $origin =
'order_supplier';
4450 $targettype = $this->getElementType();
4452 $parameters = array(
'targettype' => $targettype);
4454 $reshook = $hookmanager->executeHooks(
'setLinkedObjectSourceTargetType', $parameters, $this, $action);
4456 if (!empty($hookmanager->resArray[
'targettype'])) {
4457 $targettype = $hookmanager->resArray[
'targettype'];
4464 $sql =
"INSERT INTO " . $this->db->prefix() .
"element_element (";
4465 $sql .=
"fk_source";
4466 $sql .=
", sourcetype";
4467 $sql .=
", fk_target";
4468 $sql .=
", targettype";
4469 $sql .=
") VALUES (";
4470 $sql .= ((int) $origin_id);
4471 $sql .=
", '" . $this->db->escape($origin) .
"'";
4472 $sql .=
", " . ((int) $this->
id);
4473 $sql .=
", '" . $this->db->escape($targettype) .
"'";
4476 dol_syslog(get_class($this) .
"::add_object_linked", LOG_DEBUG);
4477 if ($this->db->query($sql)) {
4481 if ($origin ===
'order_supplier' && $targettype ===
'invoice_supplier' && $this->element ===
'invoice_supplier' && (
int) $origin_id > 0 && (
int) $this->
id > 0) {
4482 $sourceinvoices = array();
4484 $sqlsources =
"SELECT DISTINCT rc.fk_invoice_supplier_source as rowid";
4485 $sqlsources .=
" FROM ".$this->db->prefix().
"societe_remise_except as rc";
4486 $sqlsources .=
" WHERE rc.fk_invoice_supplier = ".((int) $this->
id);
4487 $sqlsources .=
" AND rc.fk_invoice_supplier_source IS NOT NULL";
4489 $resqlsources = $this->db->query($sqlsources);
4490 if ($resqlsources) {
4491 while ($objsrc = $this->db->fetch_object($resqlsources)) {
4492 $srcid = (int) $objsrc->rowid;
4493 if ($srcid > 0 && $srcid !== (
int) $this->
id) {
4494 $sourceinvoices[$srcid] = $srcid;
4498 dol_syslog(get_class($this).
"::add_object_linked Failed to read supplier invoice discounts sources", LOG_WARNING);
4501 if (!empty($sourceinvoices)) {
4502 $existing = array();
4503 $sourcelist = implode(
',', $sourceinvoices);
4505 $sqlexists =
"SELECT fk_target";
4506 $sqlexists .=
" FROM ".$this->db->prefix().
"element_element";
4507 $sqlexists .=
" WHERE fk_source = ".((int) $origin_id);
4508 $sqlexists .=
" AND sourcetype = '".$this->db->escape($origin).
"'";
4509 $sqlexists .=
" AND targettype = '".$this->db->escape($targettype).
"'";
4510 $sqlexists .=
" AND fk_target IN (".$this->db->sanitize($sourcelist).
")";
4512 $resqlexists = $this->db->query($sqlexists);
4514 while ($objexist = $this->db->fetch_object($resqlexists)) {
4515 $existing[(int) $objexist->fk_target] = 1;
4518 dol_syslog(get_class($this).
"::add_object_linked Failed to read existing linked supplier invoices", LOG_WARNING);
4521 foreach ($sourceinvoices as $srcid) {
4522 if (!empty($existing[(
int) $srcid])) {
4526 $sqladd =
"INSERT INTO " . $this->db->prefix() .
"element_element (fk_source, sourcetype, fk_target, targettype)";
4527 $sqladd .=
" VALUES (".((int) $origin_id).
", '".$this->db->escape($origin).
"', ".((int) $srcid).
", '".$this->db->escape($targettype).
"')";
4528 $this->db->query($sqladd);
4535 $this->context[
'link_origin'] = $origin;
4536 $this->context[
'link_origin_id'] = $origin_id;
4538 $result = $this->call_trigger(
'OBJECT_LINK_INSERT', $f_user);
4545 $this->error = $this->db->lasterror();
4550 $this->db->commit();
4553 $this->db->rollback();
4567 $coreModule = array(
'knowledgemanagement',
'partnership',
'workstation',
'ticket',
'recruitment',
'eventorganization',
'asset');
4569 return ((!empty($this->module) && !in_array($this->module, $coreModule)) ? $this->module.
'_' :
'').$this->element;
4595 public function fetchObjectLinked($sourceid =
null, $sourcetype =
'', $targetid =
null, $targettype =
'', $clause =
'OR', $alsosametype = 1, $orderby =
'sourcetype', $loadalsoobjects = 1)
4597 global $hookmanager, $action;
4602 if ($this->
id > 0 && !empty($this->linkedObjectsFullLoaded[$this->
id])) {
4606 $this->linkedObjectsIds = array();
4607 $this->linkedObjects = array();
4610 $parameters = array(
4611 'sourceid' => $sourceid,
4612 'sourcetype' => $sourcetype,
4613 'targetid' => $targetid,
4614 'targettype' => $targettype,
4615 'clause' => $clause,
4616 'alsosametype' => $alsosametype,
4617 'orderby' => $orderby,
4618 'loadalsoobjects' => $loadalsoobjects
4620 $reshook = $hookmanager->executeHooks(
'fetchObjectLinked', $parameters, $this, $action);
4625 $justsource =
false;
4626 $justtarget =
false;
4627 $withtargettype =
false;
4628 $withsourcetype =
false;
4631 if (is_object($hookmanager)) {
4632 $parameters = array(
'sourcetype' => $sourcetype,
'sourceid' => $sourceid,
'targettype' => $targettype,
'targetid' => $targetid);
4633 $reshook = $hookmanager->executeHooks(
'setLinkedObjectSourceTargetType', $parameters, $this, $action);
4635 if (!empty($hookmanager->resArray[
'sourcetype'])) {
4636 $sourcetype = $hookmanager->resArray[
'sourcetype'];
4638 if (!empty($hookmanager->resArray[
'sourceid'])) {
4639 $sourceid = $hookmanager->resArray[
'sourceid'];
4641 if (!empty($hookmanager->resArray[
'targettype'])) {
4642 $targettype = $hookmanager->resArray[
'targettype'];
4644 if (!empty($hookmanager->resArray[
'targetid'])) {
4645 $targetid = $hookmanager->resArray[
'targetid'];
4650 if (!empty($sourceid) && !empty($sourcetype) && empty($targetid)) {
4652 if (!empty($targettype)) {
4653 $withtargettype =
true;
4656 if (!empty($targetid) && !empty($targettype) && empty($sourceid)) {
4658 if (!empty($sourcetype)) {
4659 $withsourcetype =
true;
4663 $sourceid = (!empty($sourceid) ? $sourceid :
$this->id);
4664 $targetid = (!empty($targetid) ? $targetid :
$this->id);
4665 $sourcetype = (!empty($sourcetype) ? $sourcetype : $this->getElementType());
4666 $targettype = (!empty($targettype) ? $targettype : $this->getElementType());
4675 $sql =
"SELECT rowid, fk_source, sourcetype, fk_target, targettype";
4676 $sql .=
" FROM ".$this->db->prefix().
"element_element";
4678 if ($justsource || $justtarget) {
4680 $sql .=
"fk_source = ".((int) $sourceid).
" AND sourcetype = '".$this->db->escape($sourcetype).
"'";
4681 if ($withtargettype) {
4682 $sql .=
" AND targettype = '".$this->db->escape($targettype).
"'";
4684 } elseif ($justtarget) {
4685 $sql .=
"fk_target = ".((int) $targetid).
" AND targettype = '".$this->db->escape($targettype).
"'";
4686 if ($withsourcetype) {
4687 $sql .=
" AND sourcetype = '".$this->db->escape($sourcetype).
"'";
4691 $sql .=
"(fk_source = ".((int) $sourceid).
" AND sourcetype = '".$this->db->escape($sourcetype).
"')";
4692 $sql .=
" ".$this->db->sanitize($clause).
" (fk_target = ".((int) $targetid).
" AND targettype = '".$this->db->escape($targettype).
"')";
4693 if ($loadalsoobjects && $this->
id > 0 && $sourceid == $this->
id && $sourcetype == $this->element && $targetid == $this->
id && $targettype == $this->element && $clause ==
'OR') {
4694 $this->linkedObjectsFullLoaded[
$this->id] =
true;
4697 $sql .= $this->db->order($orderby);
4699 dol_syslog(get_class($this).
"::fetchObjectLink", LOG_DEBUG);
4701 $resql = $this->db->query($sql);
4703 $num = $this->db->num_rows($resql);
4706 $obj = $this->db->fetch_object($resql);
4707 if ($justsource || $justtarget) {
4709 $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
4710 } elseif ($justtarget) {
4711 $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
4714 if ($obj->fk_source == $sourceid && $obj->sourcetype == $sourcetype) {
4715 $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
4717 if ($obj->fk_target == $targetid && $obj->targettype == $targettype) {
4718 $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
4724 if (!empty($this->linkedObjectsIds)) {
4725 $tmparray = $this->linkedObjectsIds;
4726 foreach ($tmparray as $objecttype => $objectids) {
4728 $element = $element_properties[
'element'];
4729 $classPath = $element_properties[
'classpath'];
4730 $classFile = $element_properties[
'classfile'];
4731 $className = $element_properties[
'classname'];
4732 $module = $element_properties[
'module'];
4735 if (
isModEnabled($module) && (($element != $this->element) || $alsosametype)) {
4736 if ($loadalsoobjects && (is_numeric($loadalsoobjects) || ($loadalsoobjects === $objecttype))) {
4738 if (class_exists($className)) {
4739 foreach ($objectids as $i => $objectid) {
4740 $object =
new $className($this->db);
4741 '@phan-var-force CommonObject $object';
4742 $ret =
$object->fetch($objectid);
4744 $this->linkedObjects[$objecttype][$i] =
$object;
4750 unset($this->linkedObjectsIds[$objecttype]);
4769 if ($this->
id > 0 && !empty($this->linkedObjectsFullLoaded[$this->
id])) {
4770 unset($this->linkedObjectsFullLoaded[$this->
id]);
4788 public function updateObjectLinked($sourceid =
null, $sourcetype =
'', $targetid =
null, $targettype =
'', $f_user =
null, $notrigger = 0)
4791 $updatesource =
false;
4792 $updatetarget =
false;
4793 $f_user = isset($f_user) ? $f_user : $user;
4796 if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) {
4797 $updatesource =
true;
4798 } elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) {
4799 $updatetarget =
true;
4805 $sql =
"UPDATE " . $this->db->prefix() .
"element_element SET ";
4806 if ($updatesource) {
4807 $sql .=
"fk_source = " . ((int) $sourceid);
4808 $sql .=
", sourcetype = '" . $this->db->escape($sourcetype) .
"'";
4809 $sql .=
" WHERE fk_target = " . ((int) $this->
id);
4810 $sql .=
" AND targettype = '" . $this->db->escape($this->element) .
"'";
4811 } elseif ($updatetarget) {
4812 $sql .=
"fk_target = " . ((int) $targetid);
4813 $sql .=
", targettype = '" . $this->db->escape($targettype) .
"'";
4814 $sql .=
" WHERE fk_source = " . ((int) $this->
id);
4815 $sql .=
" AND sourcetype = '" . $this->db->escape($this->element) .
"'";
4818 dol_syslog(get_class($this) .
"::updateObjectLinked", LOG_DEBUG);
4819 if ($this->db->query($sql)) {
4822 $this->context[
'link_source_id'] = $sourceid;
4823 $this->context[
'link_source_type'] = $sourcetype;
4824 $this->context[
'link_target_id'] = $targetid;
4825 $this->context[
'link_target_type'] = $targettype;
4827 $result = $this->call_trigger(
'OBJECT_LINK_MODIFY', $f_user);
4834 $this->error = $this->db->lasterror();
4839 $this->db->commit();
4842 $this->db->rollback();
4860 public function deleteObjectLinked($sourceid =
null, $sourcetype =
'', $targetid =
null, $targettype =
'', $rowid = 0, $f_user =
null, $notrigger = 0)
4863 $deletesource =
false;
4864 $deletetarget =
false;
4865 $f_user = isset($f_user) ? $f_user : $user;
4867 if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) {
4868 $deletesource =
true;
4869 } elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) {
4870 $deletetarget =
true;
4873 $element = $this->getElementType();
4874 $sourceid = (!empty($sourceid) ? $sourceid :
$this->id);
4875 $sourcetype = (!empty($sourcetype) ? $sourcetype : $element);
4876 $targetid = (!empty($targetid) ? $targetid :
$this->id);
4877 $targettype = (!empty($targettype) ? $targettype : $element);
4883 $this->context[
'link_id'] = $rowid;
4884 $this->context[
'link_source_id'] = $sourceid;
4885 $this->context[
'link_source_type'] = $sourcetype;
4886 $this->context[
'link_target_id'] = $targetid;
4887 $this->context[
'link_target_type'] = $targettype;
4889 $result = $this->call_trigger(
'OBJECT_LINK_DELETE', $f_user);
4897 $sql =
"DELETE FROM " . $this->db->prefix() .
"element_element";
4900 $sql .=
" rowid = " . ((int) $rowid);
4902 if ($deletesource) {
4903 $sql .=
" fk_source = " . ((int) $sourceid) .
" AND sourcetype = '" . $this->db->escape($sourcetype) .
"'";
4904 $sql .=
" AND fk_target = " . ((int) $this->
id) .
" AND targettype = '" . $this->db->escape($element) .
"'";
4905 } elseif ($deletetarget) {
4906 $sql .=
" fk_target = " . ((int) $targetid) .
" AND targettype = '" . $this->db->escape($targettype) .
"'";
4907 $sql .=
" AND fk_source = " . ((int) $this->
id) .
" AND sourcetype = '" . $this->db->escape($element) .
"'";
4909 $sql .=
" (fk_source = " . ((int) $this->
id) .
" AND sourcetype = '" . $this->db->escape($element) .
"')";
4911 $sql .=
" (fk_target = " . ((int) $this->
id) .
" AND targettype = '" . $this->db->escape($element) .
"')";
4915 dol_syslog(get_class($this) .
"::deleteObjectLinked", LOG_DEBUG);
4916 if (!$this->db->query($sql)) {
4917 $this->error = $this->db->lasterror();
4918 $this->errors[] = $this->error;
4924 $this->db->commit();
4927 $this->db->rollback();
4943 if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
4946 if (!preg_match(
'/^[_a-zA-Z0-9]+$/', $field_select)) {
4947 dol_syslog(
'Invalid value $field_select for parameter '.$field_select.
' in call to getAllItemsLinkedByObjectID(). Must be a single field name.', LOG_ERR);
4952 $sql =
"SELECT ".$db->sanitize($field_select).
" FROM ".
$db->prefix().$db->sanitize($table_element).
" WHERE ".
$db->sanitize($field_where).
" = ".((int) $fk_object_where);
4953 $resql =
$db->query($sql);
4956 if (!empty($resql)) {
4957 while ($res =
$db->fetch_object($resql)) {
4958 $TRes[] = $res->{$field_select};
4975 if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
4981 $sql =
"SELECT COUNT(*) as nb FROM ".$db->prefix().$db->sanitize($table_element).
" WHERE ".
$db->sanitize($field_where).
" = ".((int) $fk_object_where);
4982 $resql =
$db->query($sql);
4985 $res =
$db->fetch_object($resql);
5004 if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
5010 $sql =
"DELETE FROM ".$db->prefix().$table_element.
" WHERE ".
$db->sanitize($field_where).
" = ".((int) $fk_object_where);
5011 $resql =
$db->query($sql);
5013 if (empty($resql)) {
5031 public function setStatut($status, $elementId =
null, $elementType =
'', $trigkey =
'', $fieldstatus =
'')
5035 $savElementId = $elementId;
5037 $elementId = (!empty($elementId) ? $elementId :
$this->id);
5038 $elementTable = (!empty($elementType) ? $elementType : $this->table_element);
5042 if (empty($fieldstatus)) {
5043 if ($elementTable ==
'facture_rec') {
5044 $fieldstatus =
"suspended";
5046 if ($elementTable ==
'mailing') {
5047 $fieldstatus =
"statut";
5049 if ($elementTable ==
'cronjob') {
5050 $fieldstatus =
"status";
5052 if ($elementTable ==
'user') {
5053 $fieldstatus =
"statut";
5055 if ($elementTable ==
'expensereport') {
5056 $fieldstatus =
"fk_statut";
5058 if ($elementTable ==
'receptiondet_batch') {
5059 $fieldstatus =
"status";
5061 if ($elementTable ==
'prelevement_bons') {
5062 $fieldstatus =
"statut";
5064 if ($elementTable ==
'bank_account') {
5065 $fieldstatus =
"clos";
5067 if (isset($this->fields) && is_array($this->fields) && array_key_exists(
'status', $this->fields)) {
5068 $fieldstatus =
'status';
5071 if (empty($fieldstatus)) {
5072 $fieldstatus =
'fk_statut';
5076 $sql =
"UPDATE ".$this->db->prefix().$this->db->sanitize($elementTable);
5077 $sql .=
" SET ".$this->db->sanitize($fieldstatus).
" = ".((int) $status);
5080 if ($status == 1 && in_array($elementTable, array(
'expensereport',
'inventory'))) {
5081 $sql .=
", fk_user_valid = ".((int) $user->id);
5083 if ($status == 1 && in_array($elementTable, array(
'expensereport'))) {
5084 $sql .=
", date_valid = '".$this->db->idate(
dol_now()).
"'";
5086 if ($status == 1 && in_array($elementTable, array(
'inventory'))) {
5087 $sql .=
", date_validation = '".$this->db->idate(
dol_now()).
"'";
5089 $sql .=
" WHERE rowid = ".((int) $elementId);
5090 $sql .=
" AND ".$this->db->sanitize($fieldstatus).
" <> ".((int) $status);
5092 dol_syslog(get_class($this).
"::setStatut", LOG_DEBUG);
5093 $resql = $this->db->query($sql);
5097 $nb_rows_affected = $this->db->affected_rows($resql);
5099 if ($nb_rows_affected > 0) {
5100 if (empty($trigkey)) {
5102 if ($this->element ==
'supplier_proposal' && $status == 2) {
5103 $trigkey =
'SUPPLIER_PROPOSAL_SIGN';
5105 if ($this->element ==
'supplier_proposal' && $status == 3) {
5106 $trigkey =
'SUPPLIER_PROPOSAL_REFUSE';
5108 if ($this->element ==
'supplier_proposal' && $status == 4) {
5109 $trigkey =
'SUPPLIER_PROPOSAL_CLOSE';
5111 if ($this->element ==
'fichinter' && $status == 3) {
5112 $trigkey =
'FICHINTER_CLASSIFY_DONE';
5114 if ($this->element ==
'fichinter' && $status == 2) {
5115 $trigkey =
'FICHINTER_CLASSIFY_BILLED';
5117 if ($this->element ==
'fichinter' && $status == 1) {
5118 $trigkey =
'FICHINTER_CLASSIFY_UNBILLED';
5122 $this->context = array_merge($this->context, array(
'newstatus' => $status));
5124 if ($trigkey && $trigkey !=
'none') {
5128 $result = $this->call_trigger($trigkey, $user);
5139 $this->db->commit();
5141 if (empty($savElementId)) {
5143 if ($fieldstatus ==
'dispute_status') {
5144 $this->dispute_status = $status;
5145 } elseif ($fieldstatus ==
'tosell') {
5147 } elseif ($fieldstatus ==
'tobuy') {
5148 $this->status_buy = $status;
5149 } elseif ($fieldstatus ==
'tobatch') {
5150 $this->status_batch = $status;
5158 $this->db->rollback();
5159 dol_syslog(get_class($this).
"::setStatut ".$this->error, LOG_ERR);
5163 $this->error = $this->db->lasterror();
5164 $this->db->rollback();
5179 if (empty(
$id) && empty($ref)) {
5189 $sql =
"SELECT rowid, canvas";
5190 $sql .=
" FROM ".$this->db->prefix().$this->table_element;
5191 $sql .=
" WHERE entity IN (".getEntity($this->element).
")";
5193 $sql .=
" AND rowid = ".((int)
$id);
5196 $sql .=
" AND ref = '".$this->db->escape($ref).
"'";
5199 $resql = $this->db->query($sql);
5201 $obj = $this->db->fetch_object($resql);
5203 $this->canvas = $obj->canvas;
5223 $sql =
"SELECT special_code FROM ".$this->db->prefix().$this->db->sanitize($this->table_element_line);
5224 $sql .=
" WHERE rowid = ".((int) $lineid);
5225 $resql = $this->db->query($sql);
5227 $row = $this->db->fetch_row($resql);
5228 return (!empty($row[0]) ? $row[0] : 0);
5251 if (!isset($this->childtables) || !is_array($this->childtables) || count($this->childtables) == 0) {
5252 dol_print_error(
null,
'Called isObjectUsed on a class with property this->childtables not defined');
5256 $arraytoscan = $this->childtables;
5258 $tmparray = array_keys($this->childtables);
5259 if (is_numeric($tmparray[0])) {
5260 $arraytoscan = array_flip($this->childtables);
5265 foreach ($arraytoscan as $table => $element) {
5269 if (isset($element[
'enabled']) && !empty($element[
'enabled'])) {
5270 $enabled = (int)
dol_eval((
string) $element[
'enabled'], 1);
5271 if (empty($enabled)) {
5277 $sql =
"SELECT COUNT(*) as nb";
5278 $sql .=
" FROM ".$this->db->prefix().$this->db->sanitize($table).
" as c";
5279 if (!empty($element[
'parent']) && !empty($element[
'parentkey'])) {
5280 $sql .=
", ".$this->db->prefix().$this->db->sanitize($element[
'parent']).
" as p";
5282 if (!empty($element[
'fk_element'])) {
5283 $sql .=
" WHERE c.".$this->db->sanitize($element[
'fk_element']).
" = ".((int)
$id);
5285 $sql .=
" WHERE c.".$this->db->sanitize($this->fk_element).
" = ".((int)
$id);
5287 if (!empty($element[
'parent']) && !empty($element[
'parentkey'])) {
5288 $sql .=
" AND c.".$this->db->sanitize($element[
'parentkey']).
" = p.rowid";
5290 if (!empty($element[
'parent']) && !empty($element[
'parenttypefield']) && !empty($element[
'parenttypevalue'])) {
5291 $sql .=
" AND c.".$this->db->sanitize($element[
'parenttypefield']).
" = '".$this->db->escape($element[
'parenttypevalue']).
"'";
5293 if (!empty($entity)) {
5294 if (!empty($element[
'parent']) && !empty($element[
'parentkey'])) {
5295 $sql .=
" AND p.entity = ".((int) $entity);
5297 $sql .=
" AND c.entity = ".((int) $entity);
5302 $resql = $this->db->query($sql);
5304 $obj = $this->db->fetch_object($resql);
5306 $langs->load(
"errors");
5308 $haschild += (int) $obj->nb;
5309 if (is_numeric($element)) {
5310 $this->errors[] = $langs->transnoentitiesnoconv(
"ErrorRecordHasAtLeastOneChildOfType", method_exists($this,
'getNomUrl') ? $this->getNomUrl() : $this->ref, $table);
5311 } elseif (is_string($element)) {
5312 $this->errors[] = $langs->transnoentitiesnoconv(
"ErrorRecordHasAtLeastOneChildOfType", method_exists($this,
'getNomUrl') ? $this->getNomUrl() : $this->ref, $langs->transnoentitiesnoconv($element));
5314 $this->errors[] = $langs->transnoentitiesnoconv(
"ErrorRecordHasAtLeastOneChildOfType", method_exists($this,
'getNomUrl') ? $this->getNomUrl() : $this->ref, $langs->transnoentitiesnoconv($element[
'name']));
5319 $this->errors[] = $this->db->lasterror();
5324 if ($haschild > 0) {
5325 $this->errors[] =
"ErrorRecordHasChildren";
5342 foreach ($this->lines as $key => $val) {
5344 if ($predefined == -1) {
5347 if ($predefined == 1 && $val->fk_product > 0) {
5350 if ($predefined == 0 && $val->fk_product <= 0) {
5353 if ($predefined == 2 && $val->fk_product > 0 && $val->product_type == 0) {
5356 if ($predefined == 3 && $val->fk_product > 0 && $val->product_type == 1) {
5363 dol_syslog(get_class($this).
'::hasProductsOrServices we found '.$nb.
' qualified lines of products/servcies');
5374 if (!empty($this->table_element_line) && ($this->table_element_line !=
'expeditiondet')) {
5375 $total_discount = 0.00;
5377 $sql =
"SELECT subprice as pu_ht, qty, remise_percent, total_ht";
5378 $sql .=
" FROM ".$this->db->prefix().$this->table_element_line;
5379 $sql .=
" WHERE ".$this->db->sanitize($this->fk_element).
" = ".((int) $this->
id);
5381 dol_syslog(get_class($this).
'::getTotalDiscount', LOG_DEBUG);
5382 $resql = $this->db->query($sql);
5384 $num = $this->db->num_rows($resql);
5387 $obj = $this->db->fetch_object($resql);
5389 $pu_ht = $obj->pu_ht;
5391 $total_ht = $obj->total_ht;
5393 $total_discount_line = (float)
price2num(($pu_ht * $qty) - $total_ht,
'MT');
5394 $total_discount += $total_discount_line;
5401 return (
float)
price2num($total_discount);
5423 if (empty($this->lines)) {
5424 return array(
'weight' => $totalWeight,
'volume' => $totalVolume,
'ordered' => $totalOrdered,
'toship' => $totalToShip);
5427 foreach ($this->lines as $line) {
5428 if (isset($line->qty_asked)) {
5429 $totalOrdered += $line->qty_asked;
5431 if (isset($line->qty_shipped)) {
5432 $totalToShip += $line->qty_shipped;
5433 } elseif ($line->element ==
'commandefournisseurdispatch' && isset($line->qty)) {
5434 if (empty($totalToShip)) {
5437 $totalToShip += $line->qty;
5441 if ($this->element ==
'shipping') {
5443 $qty = $line->qty_shipped ? $line->qty_shipped : 0;
5445 $qty = $line->qty ? $line->qty : 0;
5448 $weight = !empty($line->weight) ? $line->weight : 0;
5449 ($weight == 0 && !empty($line->product->weight)) ? $weight = $line->product->weight : 0;
5450 $volume = !empty($line->volume) ? $line->volume : 0;
5451 ($volume == 0 && !empty($line->product->volume)) ? $volume = $line->product->volume : 0;
5453 $weight_units = !empty($line->weight_units) ? $line->weight_units : 0;
5454 ($weight_units == 0 && !empty($line->product->weight_units)) ? $weight_units = $line->product->weight_units : 0;
5455 $volume_units = !empty($line->volume_units) ? $line->volume_units : 0;
5456 ($volume_units == 0 && !empty($line->product->volume_units)) ? $volume_units = $line->product->volume_units : 0;
5460 if (!empty($weight_units)) {
5461 $weightUnit = $weight_units;
5463 if (!empty($volume_units)) {
5464 $volumeUnit = $volume_units;
5467 if (empty($totalWeight)) {
5470 if (empty($totalVolume)) {
5475 if ($weight_units < 50) {
5476 $trueWeightUnit = pow(10, $weightUnit);
5477 $totalWeight += $weight * $qty * $trueWeightUnit;
5479 if ($weight_units == 99) {
5481 $trueWeightUnit = 0.45359237;
5482 $totalWeight += $weight * $qty * $trueWeightUnit;
5483 } elseif ($weight_units == 98) {
5485 $trueWeightUnit = 0.0283495;
5486 $totalWeight += $weight * $qty * $trueWeightUnit;
5488 $totalWeight += $weight * $qty;
5491 if ($volume_units < 50) {
5493 $trueVolumeUnit = pow(10, $volumeUnit);
5495 $totalVolume += $volume * $qty * $trueVolumeUnit;
5497 $totalVolume += $volume * $qty;
5501 return array(
'weight' => $totalWeight,
'volume' => $totalVolume,
'ordered' => $totalOrdered,
'toship' => $totalToShip);
5514 $extraparams = (!empty($this->extraparams) ? json_encode($this->extraparams) :
null);
5515 $extraparams =
dol_trunc($extraparams, 250);
5517 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
5518 $sql .=
" SET extraparams = ".(!empty($extraparams) ?
"'".$this->db->escape($extraparams).
"'" :
"null");
5519 $sql .=
" WHERE rowid = ".((int) $this->
id);
5521 dol_syslog(get_class($this).
"::setExtraParameters", LOG_DEBUG);
5522 $resql = $this->db->query($sql);
5524 $this->error = $this->db->lasterror();
5525 $this->db->rollback();
5528 $this->db->commit();
5551 global
$conf, $user, $langs,
$object, $hookmanager, $extrafields, $form;
5554 if (!is_object($extrafields)) {
5555 require_once DOL_DOCUMENT_ROOT.
'/core/class/extrafields.class.php';
5558 $extrafields->fetch_name_optionals_label($this->table_element_line);
5563 $dirtpls = array_merge(
$conf->modules_parts[
'tpl'], array($defaulttpldir));
5564 foreach ($dirtpls as $module => $reldir) {
5565 if (!empty($module)) {
5568 $tpl = DOL_DOCUMENT_ROOT.$reldir.
'/objectline_create.tpl.php';
5571 if (empty(
$conf->file->strict_mode)) {
5572 $res = @include $tpl;
5574 $res = include $tpl;
5601 public function printObjectLines($action, $seller, $buyer, $selected = 0, $dateSelector = 0, $defaulttpldir =
'/core/tpl')
5603 global
$conf, $hookmanager, $langs, $user, $form, $extrafields,
$object;
5605 global $inputalsopricewithtax, $usemargins, $disableedit, $disablemove, $disableremove, $outputalsopricetotalwithtax;
5609 if (
isModEnabled(
'margin') && !empty($this->element) && in_array($this->element, array(
'facture',
'facturerec',
'propal',
'commande'))) {
5613 $num = count($this->lines);
5616 if (!is_object($extrafields)) {
5617 require_once DOL_DOCUMENT_ROOT.
'/core/class/extrafields.class.php';
5620 $extrafields->fetch_name_optionals_label($this->table_element_line);
5622 if (method_exists($this,
'loadExpeditions')) {
5624 $this->loadExpeditions();
5627 $parameters = array();
5628 $reshook = $hookmanager->executeHooks(
'printObjectLinesBlock', $parameters, $this, $action);
5629 if (empty($reshook)) {
5630 $parameters = array(
'num' => $num,
'dateSelector' => $dateSelector,
'seller' => $seller,
'buyer' => $buyer,
'selected' => $selected,
'table_element_line' => $this->table_element_line);
5631 $reshook = $hookmanager->executeHooks(
'printObjectLineTitle', $parameters, $this, $action);
5632 if (empty($reshook)) {
5636 $dirtpls = array_merge(
$conf->modules_parts[
'tpl'], array($defaulttpldir));
5637 foreach ($dirtpls as $module => $reldir) {
5639 if (!empty($module)) {
5642 $tpl = DOL_DOCUMENT_ROOT.$reldir.
'/objectline_title.tpl.php';
5644 if (file_exists($tpl)) {
5645 if (empty(
$conf->file->strict_mode)) {
5646 $res = @include $tpl;
5648 $res = include $tpl;
5659 print
"<!-- begin printObjectLines() -->\n";
5660 foreach ($this->lines as $line) {
5664 if (is_object($hookmanager)) {
5665 if (empty($line->fk_parent_line)) {
5666 $parameters = array(
'line' => $line,
'num' => $num,
'i' => $i,
'dateSelector' => $dateSelector,
'seller' => $seller,
'buyer' => $buyer,
'selected' => $selected,
'table_element_line' => $line->table_element,
'defaulttpldir' => $defaulttpldir);
5667 $reshook = $hookmanager->executeHooks(
'printObjectLine', $parameters, $this, $action);
5669 $parameters = array(
'line' => $line,
'num' => $num,
'i' => $i,
'dateSelector' => $dateSelector,
'seller' => $seller,
'buyer' => $buyer,
'selected' => $selected,
'table_element_line' => $line->table_element,
'fk_parent_line' => $line->fk_parent_line,
'defaulttpldir' => $defaulttpldir);
5670 $reshook = $hookmanager->executeHooks(
'printObjectSubLine', $parameters, $this, $action);
5673 if (empty($reshook)) {
5674 $this->printObjectLine($action, $line,
'', $num, $i, $dateSelector, $seller, $buyer, $selected, $extrafields, $defaulttpldir);
5679 print
"<!-- end printObjectLines() -->\n";
5700 public function printObjectLine($action, $line, $var, $num, $i, $dateSelector, $seller, $buyer, $selected = 0, $extrafields =
null, $defaulttpldir =
'/core/tpl')
5704 global $disableedit, $disablemove, $disableremove;
5711 if ($action !=
'editline' || $selected != $line->id) {
5713 if (!empty($line->fk_product) && $line->fk_product > 0) {
5714 $product_static =
new Product($this->db);
5715 $product_static->fetch($line->fk_product);
5717 $product_static->ref = (
string) $line->ref;
5719 $product_static->label = !empty($line->label) ? $line->label :
"";
5721 $text = $product_static->getNomUrl(1);
5726 if (property_exists($this,
'socid') && !empty($this->socid) && !is_object($this->thirdparty)) {
5727 dol_print_error(
null,
'Error: Method printObjectLine was called on an object and object->fetch_thirdparty was not done before');
5732 $prod->fetch($line->fk_product);
5734 $outputlangs = $langs;
5736 if (empty($newlang) &&
GETPOST(
'lang_id',
'aZ09')) {
5737 $newlang =
GETPOST(
'lang_id',
'aZ09');
5739 if (
getDolGlobalString(
'PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE') && empty($newlang) && is_object($this->thirdparty)) {
5740 $newlang = $this->thirdparty->default_lang;
5742 if (!empty($newlang)) {
5744 $outputlangs->setDefaultLang($newlang);
5747 $label = (!empty(
$prod->multilangs[$outputlangs->defaultlang][
"label"])) ?
$prod->multilangs[$outputlangs->defaultlang][
"label"] : $line->product_label;
5749 $label = $line->product_label;
5753 $text .=
' - '.(!empty($line->label) ? $line->label : $label);
5754 $description .= (
getDolGlobalInt(
'PRODUIT_DESC_IN_FORM_ACCORDING_TO_DEVICE') ?
'' : (!empty($line->description) ?
dol_htmlentitiesbr($line->description) :
''));
5758 if (empty((
float) $line->subprice_ttc) && $line->qty) {
5761 if ($line->remise_percent != 100) {
5763 $line->subprice_ttc = (float)
price2num($line->total_ttc * ($line->situation_percent ? 100 / $line->situation_percent : 1) / $line->qty / (1 - $line->remise_percent / 100),
'MU');
5766 $line->subprice_ttc = (float)
price2num((!empty($line->subprice) ? $line->subprice : 0) * (1 + ((!empty($line->tva_tx) ? $line->tva_tx : 0) / 100)),
'MU');
5769 $line->pu_ttc = $line->subprice_ttc;
5776 if (isset($this->expeditions[$line->id])) {
5778 $qty_shipped = $this->expeditions[$line->id];
5780 $disableedit = ($qty_shipped > 0) && ($qty_shipped >= $line->qty);
5782 $dirtpls = array_merge(
$conf->modules_parts[
'tpl'], array($defaulttpldir));
5783 foreach ($dirtpls as $module => $reldir) {
5785 if (!empty($module)) {
5788 $tpl = DOL_DOCUMENT_ROOT.$reldir.
'/objectline_view.tpl.php';
5791 if (file_exists($tpl)) {
5792 if (empty(
$conf->file->strict_mode)) {
5793 $res = @include $tpl;
5795 $res = include $tpl;
5805 if ($this->
status == 0 && $action ==
'editline' && $selected == $line->id) {
5807 $label = (!empty($line->label) ? $line->label : (($line->fk_product > 0) ? $line->product_label :
''));
5809 $line->subprice_ttc = (float)
price2num($line->subprice * (1 + ($line->tva_tx / 100)),
'MU');
5810 $line->pu_ttc = $line->subprice_ttc;
5815 $dirtpls = array_merge(
$conf->modules_parts[
'tpl'], array($defaulttpldir));
5816 foreach ($dirtpls as $module => $reldir) {
5817 if (!empty($module)) {
5820 $tpl = DOL_DOCUMENT_ROOT.$reldir.
'/objectline_edit.tpl.php';
5823 if (empty(
$conf->file->strict_mode)) {
5824 $res = @include $tpl;
5826 $res = include $tpl;
5851 global $langs, $hookmanager, $form, $action;
5853 print
'<!-- printOriginLinesList '.get_class($this).
' -->'.
"\n";
5854 print
'<tr class="liste_titre">';
5855 print
'<td class="linecolref">'.$langs->trans(
'Ref').
'</td>';
5856 print
'<td class="linecoldescription">'.$langs->trans(
'Description').
'</td>';
5857 print
'<td class="linecolvat right">'.$langs->trans(
'VATRate').
'</td>';
5858 print
'<td class="linecoluht right">'.$langs->trans(
'PriceUHT').
'</td>';
5860 print
'<td class="linecoluht_currency right">'.$langs->trans(
'PriceUHTCurrency').
'</td>';
5862 print
'<td class="linecolqty right">'.$langs->trans(
'Qty').
'</td>';
5864 print
'<td class="linecoluseunit left">'.$langs->trans(
'Unit').
'</td>';
5866 print
'<td class="linecoldiscount right">'.$langs->trans(
'ReductionShort').
'</td>';
5867 print
'<td class="linecolht right">'.$langs->trans(
'TotalHT').
'</td>';
5868 print
'<td class="center">';
5869 print $form->showCheckAddButtons(
'checkforselect', 1);
5874 if (!empty($this->lines)) {
5875 foreach ($this->lines as $line) {
5878 if (is_object($hookmanager)) {
5879 $parameters = array(
'line' => $line,
'i' => $i,
'restrictlist' => $restrictlist,
'selectedLines' => $selectedLines);
5880 if (!empty($line->fk_parent_line)) {
5881 $parameters[
'fk_parent_line'] = $line->fk_parent_line;
5883 $reshook = $hookmanager->executeHooks(
'printOriginObjectLine', $parameters, $this, $action);
5885 if (empty($reshook)) {
5886 $this->printOriginLine($line,
'', $restrictlist,
'/core/tpl', $selectedLines);
5907 public function printOriginLine($line, $var, $restrictlist =
'', $defaulttpldir =
'/core/tpl', $selectedLines = array())
5909 global $langs,
$conf;
5912 if (!empty($line->date_start)) {
5917 if ($line->date_debut_reel) {
5921 if (!empty($line->date_end)) {
5923 $date_end = $line->date_end;
5925 $date_end = $line->date_fin_prevue;
5926 if ($line->date_fin_reel) {
5927 $date_end = $line->date_fin_reel;
5932 $this->tpl[
'id'] = $line->id;
5934 $this->tpl[
'label'] =
'';
5935 if (!empty($line->fk_parent_line)) {
5936 $this->tpl[
'label'] .=
img_picto(
'',
'rightarrow.png');
5939 if (((
int) $line->info_bits & 2) == 2) {
5941 if (property_exists($this,
'socid')) {
5943 $discount->fk_soc = $this->socid;
5945 $discount->socid = $this->socid;
5947 $this->tpl[
'label'] .= $discount->getNomUrl(0,
'discount');
5948 } elseif (!empty($line->fk_product)) {
5949 $productstatic =
new Product($this->db);
5950 $productstatic->id = $line->fk_product;
5951 $productstatic->ref = (
string) $line->ref;
5952 $productstatic->type = $line->fk_product_type;
5953 if (empty($productstatic->ref)) {
5954 $line->fetch_product();
5955 $productstatic = $line->product;
5958 $this->tpl[
'label'] .= $productstatic->getNomUrl(1);
5960 $this->tpl[
'label'] .=
' - '.(!empty($line->label) ? $line->label : $line->product_label);
5962 if ($line->product_type == 1 && (
$date_start || $date_end)) {
5966 $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"')));
5967 if (!empty($line->desc)) {
5968 $this->tpl[
'label'] .= $line->desc;
5971 $this->tpl[
'label'] .= ($line->label ?
' '.$line->label :
'');
5975 if ($line->product_type == 1 && (
$date_start || $date_end)) {
5980 if (!empty($line->desc)) {
5981 '@phan-var-force OrderLine|FactureLigne|ContratLigne|FactureFournisseurLigneRec|SupplierInvoiceLine|SupplierProposalLine $line';
5982 if ($line->desc ==
'(CREDIT_NOTE)') {
5984 $discount->fetch($line->fk_remise_except);
5985 $this->tpl[
'description'] = $langs->transnoentities(
"DiscountFromCreditNote", $discount->getNomUrl(0));
5986 } elseif ($line->desc ==
'(DEPOSIT)') {
5988 $discount->fetch($line->fk_remise_except);
5989 $this->tpl[
'description'] = $langs->transnoentities(
"DiscountFromDeposit", $discount->getNomUrl(0));
5990 } elseif ($line->desc ==
'(EXCESS RECEIVED)') {
5992 $discount->fetch($line->fk_remise_except);
5993 $this->tpl[
'description'] = $langs->transnoentities(
"DiscountFromExcessReceived", $discount->getNomUrl(0));
5994 } elseif ($line->desc ==
'(EXCESS PAID)') {
5996 $discount->fetch($line->fk_remise_except);
5997 $this->tpl[
'description'] = $langs->transnoentities(
"DiscountFromExcessPaid", $discount->getNomUrl(0));
5999 $this->tpl[
'description'] =
dol_trunc($line->desc, 60);
6002 $this->tpl[
'description'] =
' ';
6006 $this->tpl[
'vat_rate'] =
vatrate($line->tva_tx,
true);
6007 $this->tpl[
'vat_rate'] .= (((int) $line->info_bits & 1) == 1) ?
'*' :
'';
6008 if (!empty($line->vat_src_code) && !preg_match(
'/\(/', $this->tpl[
'vat_rate'])) {
6009 $this->tpl[
'vat_rate'] .=
' ('.$line->vat_src_code.
')';
6012 $this->tpl[
'price'] =
price($line->subprice);
6013 $this->tpl[
'total_ht'] =
price($line->total_ht);
6014 $this->tpl[
'multicurrency_price'] =
price($line->multicurrency_subprice);
6015 $this->tpl[
'qty'] = (((int) $line->info_bits & 2) != 2) ? $line->qty :
' ';
6017 $this->tpl[
'unit'] = $line->getLabelOfUnit(
'long', $langs);
6018 $this->tpl[
'unit_short'] = $line->getLabelOfUnit(
'short', $langs);
6021 $this->tpl[
'remise_percent'] = (((int) $line->info_bits & 2) != 2) ?
vatrate((
string) $line->remise_percent,
true) :
' ';
6024 $this->tpl[
'strike'] = 0;
6026 $this->tpl[
'strike'] = 1;
6027 } elseif (defined(
'SUBTOTALS_SPECIAL_CODE') && $line->special_code == SUBTOTALS_SPECIAL_CODE) {
6032 $this->tpl[
'strike'] = 1;
6037 $dirtpls = array_merge(
$conf->modules_parts[
'tpl'], array($defaulttpldir));
6038 foreach ($dirtpls as $module => $reldir) {
6039 if (!empty($module)) {
6042 $tpl = DOL_DOCUMENT_ROOT.$reldir.
'/originproductline.tpl.php';
6045 if (empty(
$conf->file->strict_mode)) {
6046 $res = @include $tpl;
6048 $res = include $tpl;
6075 $sql =
"INSERT INTO ".$this->db->prefix().
"element_resources (";
6076 $sql .=
"resource_id";
6077 $sql .=
", resource_type";
6078 $sql .=
", element_id";
6079 $sql .=
", element_type";
6081 $sql .=
", mandatory";
6082 $sql .=
") VALUES (";
6083 $sql .= ((int) $resource_id);
6084 $sql .=
", '".$this->db->escape($resource_type).
"'";
6085 $sql .=
", '".$this->db->escape((
string) $this->
id).
"'";
6086 $sql .=
", '".$this->db->escape($this->element).
"'";
6087 $sql .=
", '".$this->db->escape((
string) $busy).
"'";
6088 $sql .=
", '".$this->db->escape((
string) $mandatory).
"'";
6091 dol_syslog(get_class($this).
"::add_element_resource", LOG_DEBUG);
6092 if ($this->db->query($sql)) {
6094 $result = $this->call_trigger(strtoupper($this->TRIGGER_PREFIX).
'_ADD_RESOURCE', $user);
6096 $this->db->rollback();
6100 $this->db->commit();
6103 $this->error = $this->db->lasterror();
6104 $this->db->rollback();
6125 $sql =
"DELETE FROM ".$this->db->prefix().
"element_resources";
6126 $sql .=
" WHERE rowid = ".((int) $rowid);
6128 dol_syslog(get_class($this).
"::delete_resource", LOG_DEBUG);
6130 $resql = $this->db->query($sql);
6132 $this->error = $this->db->lasterror();
6133 $this->db->rollback();
6137 $result = $this->call_trigger(strtoupper($this->TRIGGER_PREFIX).
'_DELETE_RESOURCE', $user);
6139 $this->db->rollback();
6143 $this->db->commit();
6157 if (isset($this->lines) && is_array($this->lines)) {
6158 $nboflines = count($this->lines);
6159 for ($i = 0; $i < $nboflines; $i++) {
6160 if (is_object($this->lines[$i])) {
6161 $this->lines[$i] = clone $this->lines[$i];
6180 protected function commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams =
null)
6182 global
$conf, $langs, $hookmanager, $action;
6184 $srctemplatepath =
'';
6186 $parameters = array(
'modelspath' => $modelspath,
'modele' => $modele,
'outputlangs' => $outputlangs,
'hidedetails' => $hidedetails,
'hidedesc' => $hidedesc,
'hideref' => $hideref,
'moreparams' => $moreparams);
6187 $reshook = $hookmanager->executeHooks(
'commonGenerateDocument', $parameters, $this, $action);
6189 if (!empty($reshook)) {
6193 dol_syslog(
"commonGenerateDocument modele=".$modele.
" outputlangs->defaultlang=".(is_object($outputlangs) ? $outputlangs->defaultlang :
'null'));
6195 if (empty($modele)) {
6196 $this->error =
'BadValueForParameterModele';
6201 $err = error_reporting();
6203 @set_time_limit(120);
6204 error_reporting($err);
6207 $tmp = explode(
':', $modele, 2);
6208 $saved_model = $modele;
6209 if (!empty($tmp[1])) {
6211 $srctemplatepath = $tmp[1];
6213 if (!preg_match(
'/^'.preg_quote(DOL_DATA_ROOT,
'/').
'\/(ecm|doctemplates)/', $srctemplatepath)) {
6214 $this->error =
'BadDirForTemplateFile';
6223 $dirmodels = array(
'/');
6224 if (is_array(
$conf->modules_parts[
'models'])) {
6225 $dirmodels = array_merge($dirmodels,
$conf->modules_parts[
'models']);
6227 foreach ($dirmodels as $reldir) {
6228 foreach (array(
'doc',
'pdf') as $prefix) {
6229 if (in_array(get_class($this), array(
'Adherent'))) {
6231 $file = $prefix.
"_".$modele.
".class.php";
6234 $file = $prefix.
"_".$modele.
".modules.php";
6241 if (file_exists($file)) {
6243 $classname = $prefix.
'_'.$modele;
6252 if ($filefound ===
'' || $classname ===
'') {
6253 $this->error = $langs->trans(
"Error").
' Failed to load doc generator with modelpaths='.$modelspath.
' - modele='.$modele;
6254 $this->errors[] = $this->error;
6265 require_once $filefound;
6267 $obj =
new $classname($this->db);
6279 '@phan-var-force ModelePDFMember $obj';
6283 if ($obj->type ==
'odt' && empty($srctemplatepath)) {
6284 $varfortemplatedir = $obj->scandir;
6288 $listoffiles = array();
6291 $listofdir = explode(
',', $dirtoscan);
6292 foreach ($listofdir as $key => $tmpdir) {
6293 $tmpdir = trim($tmpdir);
6294 $tmpdir = preg_replace(
'/DOL_DATA_ROOT/', DOL_DATA_ROOT, $tmpdir);
6296 unset($listofdir[$key]);
6299 if (is_dir($tmpdir)) {
6300 $tmpfiles =
dol_dir_list($tmpdir,
'files', 0,
'\.od(s|t)$',
'',
'name', SORT_ASC, 0);
6301 if (count($tmpfiles)) {
6302 $listoffiles = array_merge($listoffiles, $tmpfiles);
6307 if (count($listoffiles)) {
6308 foreach ($listoffiles as $record) {
6309 $srctemplatepath = $record[
'fullname'];
6315 if (empty($srctemplatepath)) {
6316 $this->error =
'ErrorGenerationAskedForOdtTemplateWithSrcFileNotDefined';
6321 if ($obj->type ==
'odt' && !empty($srctemplatepath)) {
6323 dol_syslog(
"Failed to locate template file ".$srctemplatepath, LOG_WARNING);
6324 $this->error =
'ErrorGenerationAskedForOdtTemplateWithSrcFileNotFound';
6331 $sav_charset_output = empty($outputlangs->charset_output) ?
'' : $outputlangs->charset_output;
6334 $this->model_pdf = $saved_model;
6339 $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath,
'member', 1,
'tmp_cards');
6341 $resultwritefile = -1;
6342 dol_syslog(
"Error generating document - Provided ".get_class($this).
" to ".get_class($obj).
"::write_file()", LOG_ERR);
6346 if ($this instanceof
Don) {
6347 $resultwritefile = $obj->write_file($this, $outputlangs );
6349 $resultwritefile = -1;
6350 dol_syslog(
"Error generating document - Provided ".get_class($this).
" to Don::write_file()", LOG_ERR);
6354 '@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';
6355 $this->context[
'moreparams'] = $moreparams;
6356 $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, $hidedetails, $hidedesc, $hideref);
6358 }
catch (\Throwable $e) {
6359 $resultwritefile = -1;
6360 $this->error = $e->getMessage();
6361 dol_syslog(
"Exception in write_file() for ".get_class($this).
": ".$e->getMessage(), LOG_ERR);
6366 if ($resultwritefile > 0) {
6367 $outputlangs->charset_output = $sav_charset_output;
6370 require_once DOL_DOCUMENT_ROOT.
'/core/lib/files.lib.php';
6374 if (!empty($obj->result[
'fullpath'])) {
6375 $destfull = $obj->result[
'fullpath'];
6378 $update_main_doc_field = 0;
6379 if (!empty($obj->update_main_doc_field)) {
6380 $update_main_doc_field = 1;
6386 $this->indexFile($destfull, $update_main_doc_field);
6389 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);
6395 $this->warnings = $obj->warnings;
6399 $outputlangs->charset_output = $sav_charset_output;
6400 if (empty($this->error)) {
6401 $this->error = $obj->error;
6403 if (empty($this->errors)) {
6404 $this->errors = $obj->errors;
6406 $this->warnings = $obj->warnings;
6407 dol_syslog(
"Error generating document for ".__CLASS__.
". Error: ".$this->error, LOG_ERR);
6421 public function indexFile($destfull, $update_main_doc_field)
6423 global
$conf, $user;
6425 $upload_dir = dirname($destfull);
6426 $destfile = basename($destfull);
6427 $rel_dir = preg_replace(
'/^'.preg_quote(DOL_DATA_ROOT,
'/').
'/',
'', $upload_dir);
6429 if (!preg_match(
'/[\\/]temp[\\/]|[\\/]thumbs|\.meta$/', $rel_dir)) {
6430 $filename = basename($destfile);
6431 $rel_dir = preg_replace(
'/[\\/]$/',
'', $rel_dir);
6432 $rel_dir = preg_replace(
'/^[\\/]/',
'', $rel_dir);
6434 include_once DOL_DOCUMENT_ROOT.
'/ecm/class/ecmfiles.class.php';
6435 $ecmfile =
new EcmFiles($this->db);
6436 $result = $ecmfile->fetch(0,
'', ($rel_dir ? $rel_dir.
'/' :
'').$filename);
6439 $setsharekey =
false;
6441 !empty($this->TRIGGER_PREFIX)
6444 $setsharekey =
true;
6447 if ($this->element ==
'propal' || $this->element ==
'proposal') {
6449 $setsharekey =
true;
6452 $setsharekey =
true;
6455 if ($this->element ==
'facture' &&
getDolGlobalInt(
"INVOICE_ALLOW_EXTERNAL_DOWNLOAD")) {
6456 $setsharekey =
true;
6458 if ($this->element ==
'bank_account' &&
getDolGlobalInt(
"BANK_ACCOUNT_ALLOW_EXTERNAL_DOWNLOAD")) {
6459 $setsharekey =
true;
6461 if ($this->element ==
'contrat' &&
getDolGlobalInt(
"CONTRACT_ALLOW_EXTERNAL_DOWNLOAD")) {
6462 $setsharekey =
true;
6464 if ($this->element ==
'supplier_proposal' &&
getDolGlobalInt(
"SUPPLIER_PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD")) {
6465 $setsharekey =
true;
6467 if ($this->element ==
'order_supplier' &&
getDolGlobalInt(
"SUPPLIER_ORDER_ALLOW_EXTERNAL_DOWNLOAD")) {
6468 $setsharekey =
true;
6470 if ($this->element ==
'invoice_supplier' &&
getDolGlobalInt(
"SUPPLIER_INVOICE_ALLOW_EXTERNAL_DOWNLOAD")) {
6471 $setsharekey =
true;
6473 if ($this->element ==
'societe_rib' &&
getDolGlobalInt(
"SOCIETE_RIB_ALLOW_ONLINESIGN")) {
6474 $setsharekey =
true;
6478 if (empty($ecmfile->share)) {
6479 require_once DOL_DOCUMENT_ROOT.
'/core/lib/security2.lib.php';
6486 $ecmfile->fullpath_orig =
'';
6487 $ecmfile->gen_or_uploaded =
'generated';
6488 $ecmfile->description =
'';
6489 $ecmfile->keywords =
'';
6490 $ecmfile->src_object_type = $this->table_element;
6492 $result = $ecmfile->update($user);
6498 $ecmfile->entity =
$conf->entity;
6499 $ecmfile->filepath = $rel_dir;
6500 $ecmfile->filename = $filename;
6502 $ecmfile->fullpath_orig =
'';
6503 $ecmfile->gen_or_uploaded =
'generated';
6504 $ecmfile->description =
'';
6505 $ecmfile->keywords =
'';
6506 $ecmfile->src_object_type = $this->table_element;
6509 $result = $ecmfile->create($user);
6521 if ($update_main_doc_field && !empty($this->table_element)) {
6522 $sql =
"UPDATE ".$this->db->prefix().$this->table_element.
" SET last_main_doc = '".$this->db->escape($ecmfile->filepath.
"/".$ecmfile->filename).
"'";
6523 $sql .=
" WHERE rowid = ".((int) $this->
id);
6525 $resql = $this->db->query($sql);
6530 $this->last_main_doc = $ecmfile->filepath.
'/'.$ecmfile->filename;
6550 if (file_exists($file_osencoded)) {
6551 require_once DOL_DOCUMENT_ROOT.
'/core/lib/images.lib.php';
6554 $maxwidthsmall = $tmparraysize[
'maxwidthsmall'];
6555 $maxheightsmall = $tmparraysize[
'maxheightsmall'];
6556 $maxwidthmini = $tmparraysize[
'maxwidthmini'];
6557 $maxheightmini = $tmparraysize[
'maxheightmini'];
6562 vignette($file_osencoded, $maxwidthsmall, $maxheightsmall,
'_small', $quality);
6566 vignette($file_osencoded, $maxwidthmini, $maxheightmini,
'_mini', $quality);
6613 if (GETPOSTISSET($fieldname)) {
6614 return GETPOST($fieldname, $type, 3);
6617 if (isset($alternatevalue)) {
6618 return $alternatevalue;
6621 $newelement = $this->element;
6622 if ($newelement ==
'facture') {
6623 $newelement =
'invoice';
6625 if ($newelement ==
'commande') {
6626 $newelement =
'order';
6628 if (empty($newelement)) {
6629 dol_syslog(
"Ask a default value using common method getDefaultCreateValueForField on an object with no property ->element defined. Return empty string.", LOG_WARNING);
6633 $keyforfieldname = strtoupper($newelement.
'_DEFAULT_'.$fieldname);
6660 if (!$this->element) {
6663 if (!($this->
id > 0)) {
6666 if (is_array($this->array_languages)) {
6670 $this->array_languages = array();
6672 $element = $this->element;
6673 if ($element ==
'categorie') {
6674 $element =
'categories';
6678 $sql =
"SELECT rowid, property, lang , value";
6679 $sql .=
" FROM ".$this->db->prefix().
"object_lang";
6680 $sql .=
" WHERE type_object = '".$this->db->escape($element).
"'";
6681 $sql .=
" AND fk_object = ".((int) $this->
id);
6683 $resql = $this->db->query($sql);
6685 $numrows = $this->db->num_rows($resql);
6688 while ($i < $numrows) {
6689 $obj = $this->db->fetch_object($resql);
6690 $key = $obj->property;
6691 $value = $obj->value;
6692 $codelang = $obj->lang;
6693 $type = $this->fields[$key][
'type'];
6696 if (preg_match(
'/date/', $type)) {
6697 $this->array_languages[$key][$codelang] = $this->db->jdate($value);
6699 $this->array_languages[$key][$codelang] = $value;
6706 $this->db->free($resql);
6729 foreach ($_POST as $postfieldkey => $postfieldvalue) {
6730 $tmparray = explode(
'-', $postfieldkey);
6731 if ($tmparray[0] !=
'field') {
6735 $element = $tmparray[1];
6736 $key = $tmparray[2];
6737 $codelang = $tmparray[3];
6740 if (!empty($onlykey) && $key != $onlykey) {
6743 if ($element != $this->element) {
6747 $key_type = $this->fields[$key][
'type'];
6750 if (isset($this->fields[$key][
'enabled'])) {
6751 $enabled = (int)
dol_eval((
string) $this->fields[$key][
'enabled'], 1, 1,
'1');
6758 if (empty($enabled)) {
6763 if (in_array($key_type, array(
'date'))) {
6767 } elseif (in_array($key_type, array(
'datetime'))) {
6771 } elseif (in_array($key_type, array(
'checkbox',
'chkbxlst'))) {
6772 $value_arr =
GETPOST($postfieldkey,
'array');
6773 if (!empty($value_arr)) {
6774 $value_key = implode(
',', $value_arr);
6778 } elseif (in_array($key_type, array(
'price',
'double'))) {
6779 $value_arr =
GETPOST($postfieldkey,
'alpha');
6782 $value_key =
GETPOST($postfieldkey);
6783 if (in_array($key_type, array(
'link')) && $value_key ==
'-1') {
6788 $this->array_languages[$key][$codelang] = $value_key;
6813 $savDisableCompute =
$conf->disable_compute;
6814 $conf->disable_compute = 1;
6816 $ret = $this->fetch(
$id);
6818 $conf->disable_compute = $savDisableCompute;
6836 global
$conf, $extrafields;
6838 if (empty($rowid)) {
6841 if (empty($rowid) && isset($this->rowid)) {
6842 $rowid = $this->rowid;
6846 if (!$this->table_element) {
6849 $this->array_options = array();
6851 if (!is_array($optionsArray)) {
6853 if (!isset($extrafields) || !is_object($extrafields)) {
6854 require_once DOL_DOCUMENT_ROOT.
'/core/class/extrafields.class.php';
6859 if (empty($extrafields->attributes[$this->table_element][
'loaded'])) {
6860 $extrafields->fetch_name_optionals_label($this->table_element);
6862 $optionsArray = (!empty($extrafields->attributes[$this->table_element][
'label']) ? $extrafields->attributes[$this->table_element][
'label'] :
null);
6864 global $extrafields;
6865 dol_syslog(
"Warning: fetch_optionals was called with param optionsArray defined when you should pass null now", LOG_WARNING);
6868 $table_element = $this->table_element;
6869 if ($table_element ==
'categorie') {
6870 $table_element =
'categories';
6874 if (is_array($optionsArray) && count($optionsArray) > 0) {
6875 $sql =
"SELECT rowid";
6876 foreach ($optionsArray as $name => $label) {
6877 if (empty($extrafields->attributes[$this->table_element][
'type'][$name]) || (!in_array($extrafields->attributes[$this->table_element][
'type'][$name], [
'separate',
'point',
'multipts',
'linestrg',
'polygon']))) {
6878 $sql .=
", ".$this->db->sanitize($name);
6881 if (!empty($extrafields->attributes[$this->table_element][
'type'][$name]) && in_array($extrafields->attributes[$this->table_element][
'type'][$name], array(
'point',
'multipts',
'linestrg',
'polygon'))) {
6883 $sql .=
", ST_AsWKT(".$this->db->sanitize($name).
") as ".$this->db->sanitize($name);
6886 $sql .=
" FROM ".$this->db->prefix().$table_element.
"_extrafields";
6887 $sql .=
" WHERE fk_object = ".((int) $rowid);
6890 $resql = $this->db->query($sql);
6892 $numrows = $this->db->num_rows($resql);
6894 $tab = $this->db->fetch_array($resql);
6895 foreach ($tab as $key => $value) {
6897 if ($key !=
'rowid' && $key !=
'tms' && $key !=
'fk_member' && !is_int($key)) {
6899 if (!empty($extrafields->attributes[$this->table_element]) && in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'date',
'datetime'))) {
6901 $this->array_options[
"options_".$key] = $this->db->jdate($value);
6903 $this->array_options[
"options_".$key] = $value;
6908 if (!empty($extrafields->attributes[$this->table_element][
'type'][$key]) && $extrafields->attributes[$this->table_element][
'type'][$key] ==
'password') {
6909 if (!empty($value) && preg_match(
'/^dolcrypt:/', $value)) {
6910 $this->array_options[
"options_".$key] =
dolDecrypt($value);
6919 if (is_array($extrafields->attributes[$this->table_element][
'label'])) {
6920 foreach ($extrafields->attributes[$this->table_element][
'label'] as $key => $val) {
6921 $this->array_options[
'options_' . $key] =
null;
6928 if (is_array($extrafields->attributes[$this->table_element][
'label'])) {
6929 foreach ($extrafields->attributes[$this->table_element][
'label'] as $key => $val) {
6930 if (!empty($extrafields->attributes[$this->table_element]) && !empty($extrafields->attributes[$this->table_element][
'computed'][$key])) {
6932 if (empty(
$conf->disable_compute)) {
6935 global $objectoffield;
6936 $this->array_options[
'options_' . $key] =
dol_eval((
string) $extrafields->attributes[$this->table_element][
'computed'][$key], 1, 0,
'2');
6942 $this->db->free($resql);
6950 $this->errors[] = $this->db->lasterror();
6971 $table_element = $this->table_element;
6972 if ($table_element ==
'categorie') {
6973 $table_element =
'categories';
6976 dol_syslog(get_class($this).
"::deleteExtraFields delete", LOG_DEBUG);
6978 $sql_del =
"DELETE FROM ".$this->db->prefix().$table_element.
"_extrafields WHERE fk_object = ".((int) $this->
id);
6980 $resql = $this->db->query($sql_del);
6982 $this->error = $this->db->lasterror();
6983 $this->db->rollback();
6986 $this->db->commit();
7003 global $langs, $extrafields, $user;
7005 if (
getDolGlobalString(
'MAIN_EXTRAFIELDS_DISABLED') || empty($this->array_options)) {
7009 if (empty($userused)) {
7016 $langs->load(
'admin');
7017 if (!isset($extrafields) || !is_object($extrafields)) {
7018 require_once DOL_DOCUMENT_ROOT.
'/core/class/extrafields.class.php';
7021 $target_extrafields = $extrafields->fetch_name_optionals_label($this->table_element);
7024 $new_array_options = array();
7025 foreach ($this->array_options as $key => $value) {
7026 if (in_array(substr($key, 8), array_keys($target_extrafields))) {
7027 $new_array_options[$key] = $value;
7028 } elseif (in_array($key, array_keys($target_extrafields))) {
7029 $new_array_options[
'options_'.$key] = $value;
7033 foreach ($new_array_options as $key => $value) {
7034 $attributeKey = substr($key, 8);
7035 $attributeType = $extrafields->attributes[$this->table_element][
'type'][$attributeKey];
7036 $attributeLabel = $langs->transnoentities($extrafields->attributes[$this->table_element][
'label'][$attributeKey]);
7037 $attributeParam = $extrafields->attributes[$this->table_element][
'param'][$attributeKey];
7038 $attributeRequired = $extrafields->attributes[$this->table_element][
'required'][$attributeKey];
7039 $attributeUnique = $extrafields->attributes[$this->table_element][
'unique'][$attributeKey];
7040 $attrfieldcomputed = $extrafields->attributes[$this->table_element][
'computed'][$attributeKey];
7041 $attributeEmptyOnClone = $extrafields->attributes[$this->table_element][
'emptyonclone'][$attributeKey];
7053 if (!empty($this->context[
'createfromclone']) && $this->context[
'createfromclone'] ==
'createfromclone' && (!empty($attributeUnique) || !empty($attributeEmptyOnClone))) {
7054 $new_array_options[$key] =
null;
7060 if (!empty($this->context[
'createproductcombination']) && $this->context[
'createproductcombination'] ==
'createproductcombination' && !empty($attributeUnique)) {
7061 $new_array_options[$key] =
null;
7066 if ($attributeRequired) {
7067 $v = $this->array_options[$key];
7069 $langs->load(
"errors");
7070 dol_syslog(
"Mandatory field '".$key.
"' is empty during create and set to required into definition of extrafields");
7071 $this->errors[] = $langs->trans(
'ErrorFieldRequired', $attributeLabel);
7076 if (!empty($attrfieldcomputed)) {
7078 global $objectoffield;
7079 $objectoffield = $this;
7080 $value =
dol_eval((
string) $attrfieldcomputed, 1, 0,
'2');
7081 dol_syslog($langs->trans(
"Extrafieldcomputed").
" on ".$attributeLabel.
"(".$value.
")", LOG_DEBUG);
7082 $new_array_options[$key] = $value;
7084 $new_array_options[$key] =
null;
7089 switch ($attributeType) {
7093 if (!is_numeric($value) && $value !=
'') {
7094 $this->errors[] = $langs->trans(
"ExtraFieldHasWrongValue", $attributeLabel);
7096 } elseif ($value ===
'') {
7097 $new_array_options[$key] =
null;
7101 if ($value ===
'' || $value ===
false || $value ===
null) {
7102 $new_array_options[$key] =
null;
7108 if (!is_numeric($value) && $value !=
'') {
7109 dol_syslog($langs->trans(
"ExtraFieldHasWrongValue").
" for ".$attributeLabel.
"(".$value.
"is not '".$attributeType.
"')", LOG_DEBUG);
7110 $this->errors[] = $langs->trans(
"ExtraFieldHasWrongValue", $attributeLabel);
7112 } elseif ($value ==
'') {
7116 $new_array_options[$key] = $value;
7126 if ($this->array_options[$key] !=
'' && is_array($extrafields->attributes[$this->table_element][
'param'][$attributeKey][
'options'])) {
7128 $tmparrays = array_keys($extrafields->attributes[$this->table_element][
'param'][$attributeKey][
'options']);
7129 $algo = reset($tmparrays);
7134 if (is_object($this->oldcopy)) {
7136 if (isset($this->oldcopy->array_options[$key]) && $this->array_options[$key] == $this->oldcopy->array_options[$key]) {
7138 if ($algo ==
'dolcrypt') {
7139 if (!preg_match(
'/^dolcrypt:/', $this->array_options[$key])) {
7140 $new_array_options[$key] =
dolEncrypt($this->array_options[$key]);
7142 $new_array_options[$key] = $this->array_options[$key];
7145 $new_array_options[$key] = $this->array_options[$key];
7149 if ($algo ==
'dolcrypt') {
7150 if (!preg_match(
'/^dolcrypt:/', $this->array_options[$key])) {
7151 $new_array_options[$key] =
dolEncrypt($this->array_options[$key]);
7153 $new_array_options[$key] = $this->array_options[$key];
7156 $new_array_options[$key] =
dol_hash($this->array_options[$key], $algo);
7162 if ($algo ==
'dolcrypt' && !preg_match(
'/^dolcrypt:/', $this->array_options[$key])) {
7163 $new_array_options[$key] =
dolEncrypt($this->array_options[$key]);
7165 $new_array_options[$key] = $this->array_options[$key];
7170 $new_array_options[$key] = $this->array_options[$key];
7173 $new_array_options[$key] = $this->array_options[$key];
7179 if (!is_numeric($this->array_options[$key]) || $this->array_options[$key] != intval($this->array_options[$key])) {
7180 $this->array_options[$key] = strtotime($this->array_options[$key]);
7182 $new_array_options[$key] = $this->db->idate($this->array_options[$key]);
7186 if (!is_numeric($this->array_options[$key]) || $this->array_options[$key] != intval($this->array_options[$key])) {
7187 $this->array_options[$key] = strtotime($this->array_options[$key]);
7189 $new_array_options[$key] = $this->db->idate($this->array_options[$key],
'gmt');
7192 $param_list = array_keys($attributeParam[
'options']);
7195 $InfoFieldList = explode(
":", $param_list[0]);
7197 if ($InfoFieldList[0] && class_exists($InfoFieldList[0])) {
7198 if ($value ==
'-1') {
7199 $new_array_options[$key] =
'';
7202 '@phan-var-force CommonObject $object';
7206 $sqlFetchObject =
"SELECT rowid FROM ".$this->db->prefix().$object->table_element;
7207 if (is_numeric($value)) {
7208 $sqlFetchObject .=
" WHERE rowid = " . (int) $value;
7210 $sqlFetchObject .=
" WHERE ref = '" . $this->db->escape($value) .
"'";
7213 $obj = $this->db->getRow($sqlFetchObject);
7215 if ($obj !==
false) {
7216 $objectId = $obj->rowid;
7223 $new_array_options[$key] = $objectId;
7225 $this->error =
"Id/Ref '".$value.
"' for object '".
$object->element.
"' not found";
7230 dol_syslog(
'Error bad setup of extrafield', LOG_WARNING);
7235 if (is_array($this->array_options[$key])) {
7236 $new_array_options[$key] = implode(
',', $this->array_options[$key]);
7238 $new_array_options[$key] = $this->array_options[$key];
7245 $sqlColumnValues = [
'fk_object' => (int) $this->
id];
7247 foreach ($new_array_options as $key => $newValue) {
7248 $attributeKey = substr($key, 8);
7249 $attributeType = $extrafields->attributes[$this->table_element][
'type'][$attributeKey];
7250 if ($attributeType ===
'separate') {
7254 $geoDataType = ExtraFields::$geoDataTypes[$attributeType] ??
null;
7256 if (! $geoDataType) {
7258 if ($newValue !=
'') {
7259 $sqlColumnValues[$attributeKey] =
"'".$this->db->escape($newValue).
"'";
7261 $sqlColumnValues[$attributeKey] =
'null';
7265 if (empty($newValue)) {
7266 $sqlColumnValues[$attributeKey] =
'null';
7269 if (preg_match(
'/error/i', $newValue)) {
7270 dol_syslog(
'Bad syntax string for '.$geoDataType[
'shortname'].
' '.$newValue.
' to generate SQL request', LOG_WARNING);
7271 $sqlColumnValues[$attributeKey] =
'null';
7280 $sqlColumnValues[$attributeKey] = $geoDataType[
'ST_Function'].
"('".$this->db->escape($newValue).
"')";
7285 $table_element = $this->table_element;
7286 if ($table_element ==
'categorie') {
7287 $table_element =
'categories';
7289 $extrafieldsTable = $this->db->prefix() . $table_element .
'_extrafields';
7291 dol_syslog(get_class($this).
"::insertExtraFields update or insert record line", LOG_DEBUG);
7293 $linealreadyfound = 0;
7294 $sql =
"SELECT COUNT(rowid) as nb FROM ".$this->db->prefix().$table_element.
"_extrafields WHERE fk_object = ".((int) $this->
id);
7295 $resql = $this->db->query($sql);
7297 $tmpobj = $this->db->fetch_object($resql);
7299 $linealreadyfound = $tmpobj->nb;
7304 if ($linealreadyfound) {
7305 array_shift($sqlColumnValues);
7306 if (empty($sqlColumnValues)) {
7312 $this->db->commit();
7315 $sqlColumnValueString = implode(
7321 array_map(
function ($key) use ($sqlColumnValues) {
7322 return "{$key} = {$sqlColumnValues[$key]}";
7323 }, array_keys($sqlColumnValues))
7325 $sql =
"UPDATE {$extrafieldsTable} SET {$sqlColumnValueString} WHERE fk_object = ".((int) $this->
id);
7328 $extrafieldsRequiredOnOtherEntities = $extrafields->attributes[$this->table_element][
'mandatoryfieldsofotherentities'] ?? array();
7329 foreach ($extrafieldsRequiredOnOtherEntities as $key => $extrafieldType) {
7330 if (isset($sqlColumnValues[$key])) {
7335 $sqlColumnValues[$key] =
"''";
7336 if (in_array($extrafieldType, array(
'int',
'double',
'price'))) {
7337 $sqlColumnValues[$key] = 0;
7340 $sqlColumns = implode(
',', array_keys($sqlColumnValues));
7341 $sqlValues = implode(
',', array_values($sqlColumnValues));
7342 $sql =
"INSERT INTO {$extrafieldsTable} ({$sqlColumns}) VALUES ({$sqlValues})";
7345 $resql = $this->db->query($sql);
7347 $this->error = $this->db->lasterror();
7352 if (!$error && !empty($this->fields[
'fk_user_modif'])) {
7353 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
7354 $sql .=
" SET fk_user_modif = ".(int) $userused->id;
7355 $sql .=
" WHERE ".(empty($this->table_rowid) ?
'rowid' : $this->db->sanitize($this->table_rowid)).
" = ".((
int)
$this->id);
7356 $this->db->query($sql);
7359 if (!$error && $trigger) {
7361 $this->context = array(
'extrafieldaddupdate' => 1);
7362 $result = $this->call_trigger($trigger, $userused);
7370 $this->db->rollback();
7373 $this->db->commit();
7391 global $langs, $user;
7393 if (empty($userused)) {
7403 if (is_array($this->array_languages)) {
7404 $new_array_languages = $this->array_languages;
7406 foreach ($new_array_languages as $key => $value) {
7407 $attributeKey = $key;
7408 $attributeType = $this->fields[$attributeKey][
'type'];
7409 $attributeLabel = $this->fields[$attributeKey][
'label'];
7414 switch ($attributeType) {
7416 if (is_array($value) || (!is_numeric($value) && $value !=
'')) {
7417 $this->errors[] = $langs->trans(
"ExtraLanguageHasWrongValue", $attributeLabel);
7419 } elseif ($value ==
'') {
7420 $new_array_languages[$key] =
null;
7425 if (!is_numeric($value) && $value !=
'') {
7426 dol_syslog($langs->trans(
"ExtraLanguageHasWrongValue").
" on ".$attributeLabel.
"(".$value.
"is not '".$attributeType.
"')", LOG_DEBUG);
7427 $this->errors[] = $langs->trans(
"ExtraLanguageHasWrongValue", $attributeLabel);
7429 } elseif ($value ==
'') {
7430 $new_array_languages[$key] =
null;
7432 $new_array_languages[$key] = $value;
7446 $table_element = $this->table_element;
7447 if ($table_element ==
'categorie') {
7448 $table_element =
'categories';
7451 dol_syslog(get_class($this).
"::insertExtraLanguages delete then insert", LOG_DEBUG);
7453 foreach ($new_array_languages as $key => $langcodearray) {
7454 foreach ($langcodearray as $langcode => $value) {
7455 $sql_del =
"DELETE FROM ".$this->db->prefix().
"object_lang";
7456 $sql_del .=
" WHERE fk_object = ".((int) $this->
id).
" AND property = '".$this->db->escape($key).
"' AND type_object = '".$this->db->escape($table_element).
"'";
7457 $sql_del .=
" AND lang = '".$this->db->escape($langcode).
"'";
7458 $this->db->query($sql_del);
7460 if ($value !==
'') {
7461 $sql =
"INSERT INTO ".$this->db->prefix().
"object_lang (fk_object, property, type_object, lang, value";
7462 $sql .=
") VALUES (".((int) $this->
id).
", '".$this->db->escape($key).
"', '".$this->db->escape($table_element).
"', '".$this->db->escape($langcode).
"', '".$this->db->escape($value).
"'";
7465 $resql = $this->db->query($sql);
7467 $this->error = $this->db->lasterror();
7475 if (!$error && $trigger) {
7477 $this->context = array(
'extralanguagesaddupdate' => 1);
7478 $result = $this->call_trigger($trigger, $userused);
7486 $this->db->rollback();
7489 $this->db->commit();
7509 global $langs, $user, $extrafields, $hookmanager;
7515 if (empty($userused)) {
7521 if (!empty($this->array_options) && isset($this->array_options[
"options_".$key])) {
7523 $langs->load(
'admin');
7524 if (!isset($extrafields) || !is_object($extrafields)) {
7525 require_once DOL_DOCUMENT_ROOT.
'/core/class/extrafields.class.php';
7528 $extrafields->fetch_name_optionals_label($this->table_element);
7529 if (!isset($extrafields->attributes[$this->table_element][
'type'][$key])) {
7533 $value = $this->array_options[
"options_".$key];
7535 $attributeKey = $key;
7536 $attributeType = $extrafields->attributes[$this->table_element][
'type'][$attributeKey];
7537 $attributeLabel = $extrafields->attributes[$this->table_element][
'label'][$attributeKey];
7538 $attributeParam = $extrafields->attributes[$this->table_element][
'param'][$attributeKey];
7539 $attributeRequired = $extrafields->attributes[$this->table_element][
'required'][$attributeKey];
7540 $attributeUnique = $extrafields->attributes[$this->table_element][
'unique'][$attributeKey];
7541 $attrfieldcomputed = $extrafields->attributes[$this->table_element][
'computed'][$attributeKey];
7545 if ($attributeRequired) {
7546 $mandatorypb =
false;
7547 if ($attributeType ==
'link' && $this->array_options[
"options_".$key] ==
'-1') {
7548 $mandatorypb =
true;
7550 if ($this->array_options[
"options_".$key] ===
'') {
7551 $mandatorypb =
true;
7554 $langs->load(
"errors");
7555 dol_syslog(
"Mandatory field 'options_".$key.
"' is empty during update and set to required into definition of extrafields");
7556 $this->errors[] = $langs->trans(
'ErrorFieldRequired', $attributeLabel);
7562 $new_array_options = $this->array_options;
7566 if (!empty($attrfieldcomputed)) {
7568 global $objectoffield;
7569 $objectoffield = $this;
7570 $value =
dol_eval((
string) $attrfieldcomputed, 1, 0,
'2');
7571 dol_syslog($langs->trans(
"Extrafieldcomputed").
" on ".$attributeLabel.
"(".$value.
")", LOG_DEBUG);
7573 $new_array_options[
"options_".$key] = $value;
7575 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7577 $new_array_options[
"options_".$key] =
null;
7579 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7583 switch ($attributeType) {
7585 if (!is_numeric($value) && $value !=
'') {
7586 $this->errors[] = $langs->trans(
"ExtraFieldHasWrongValue", $attributeLabel);
7588 } elseif ($value ===
'') {
7589 $new_array_options[
"options_".$key] =
null;
7591 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7597 if (!is_numeric($value) && $value !=
'') {
7598 dol_syslog($langs->trans(
"ExtraFieldHasWrongValue").
" on ".$attributeLabel.
"(".$value.
"is not '".$attributeType.
"')", LOG_DEBUG);
7599 $this->errors[] = $langs->trans(
"ExtraFieldHasWrongValue", $attributeLabel);
7601 } elseif ($value ===
'') {
7605 $new_array_options[
"options_".$key] = $value;
7607 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7619 if ($this->array_options[
"options_".$key] !=
'' && is_array($extrafields->attributes[$this->table_element][
'param'][$attributeKey][
'options'])) {
7621 $tmparrays = array_keys($extrafields->attributes[$this->table_element][
'param'][$attributeKey][
'options']);
7622 $algo = reset($tmparrays);
7628 if (is_object($this->oldcopy)) {
7630 if (isset($this->oldcopy->array_options[
"options_".$key]) && $this->array_options[
"options_".$key] == $this->oldcopy->array_options[
"options_".$key]) {
7631 if ($algo ==
'dolcrypt') {
7632 if (!preg_match(
'/^dolcrypt:/', $this->array_options[
"options_".$key])) {
7633 $new_array_options[
"options_".$key] =
dolEncrypt($this->array_options[
"options_".$key]);
7635 $new_array_options[
"options_".$key] = $this->array_options[
"options_".$key];
7638 $new_array_options[
"options_".$key] = $this->array_options[
"options_".$key];
7641 if ($algo ==
'dolcrypt') {
7642 if (!preg_match(
'/^dolcrypt:/', $this->array_options[
"options_".$key])) {
7643 $new_array_options[
"options_".$key] =
dolEncrypt($this->array_options[
"options_".$key]);
7645 $new_array_options[
"options_".$key] = $this->array_options[
"options_".$key];
7648 $new_array_options[
"options_".$key] =
dol_hash($this->array_options[
"options_".$key], $algo);
7652 if ($algo ==
'dolcrypt' && !preg_match(
'/^dolcrypt:/', $this->array_options[
"options_".$key])) {
7653 $new_array_options[
"options_".$key] =
dolEncrypt($this->array_options[
"options_".$key]);
7655 $new_array_options[
"options_".$key] = $this->array_options[
"options_".$key];
7660 $new_array_options[
"options_".$key] = $this->array_options[
"options_".$key];
7663 $new_array_options[
"options_".$key] = $this->array_options[
"options_".$key];
7666 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7670 if (empty($this->array_options[
"options_".$key])) {
7671 $new_array_options[
"options_".$key] =
null;
7673 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7675 $new_array_options[
"options_".$key] = $this->db->idate($this->array_options[
"options_".$key]);
7679 if (empty($this->array_options[
"options_".$key])) {
7680 $new_array_options[
"options_".$key] =
null;
7682 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7684 $new_array_options[
"options_".$key] = $this->db->idate($this->array_options[
"options_".$key],
'gmt');
7688 if (empty($this->array_options[
"options_".$key])) {
7689 $new_array_options[
"options_".$key] =
null;
7691 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7695 if ($this->array_options[
"options_".$key] ===
'') {
7696 $new_array_options[
"options_".$key] =
null;
7698 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7732 $new_array_options = array();
7733 if (is_array($this->array_options[
"options_".$key])) {
7734 $new_array_options[
"options_".$key] = implode(
',', $this->array_options[
"options_".$key]);
7736 $new_array_options[
"options_".$key] = $this->array_options[
"options_".$key];
7739 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7745 $linealreadyfound = 0;
7748 $table_element = $this->table_element;
7749 if ($table_element ==
'categorie') {
7750 $table_element =
'categories';
7753 $sql =
"SELECT COUNT(rowid) as nb FROM ".$this->db->prefix().$table_element.
"_extrafields WHERE fk_object = ".((int) $this->
id);
7754 $resql = $this->db->query($sql);
7756 $tmpobj = $this->db->fetch_object($resql);
7758 $linealreadyfound = $tmpobj->nb;
7763 if ($linealreadyfound) {
7764 $sanitizedGeoDataType = ExtraFields::$geoDataTypes[$attributeType] ??
null;
7765 if ($this->array_options[
"options_".$key] ===
null) {
7766 $sql =
"UPDATE ".$this->db->prefix().$this->db->sanitize($table_element).
"_extrafields";
7767 $sql .=
" SET ".$this->db->sanitize($key).
" = null";
7768 } elseif (!empty($sanitizedGeoDataType[
'ST_Function'])) {
7769 $sql =
"UPDATE ".$this->db->prefix().$this->db->sanitize($table_element).
"_extrafields";
7770 $sql .=
" SET ".$this->db->sanitize($key).
" = ".$this->db->sanitize($sanitizedGeoDataType[
'ST_Function']).
"('".$this->db->escape($this->array_options[
"options_".$key]).
"')";
7773 $sql =
"UPDATE ".$this->db->prefix().$this->db->sanitize($table_element).
"_extrafields";
7774 $sql .=
" SET ".$this->db->sanitize($key).
" = '".$this->db->escape($new_array_options[
"options_".$key]).
"'";
7776 $sql .=
" WHERE fk_object = ".((int) $this->
id);
7778 $resql = $this->db->query($sql);
7781 $this->error = $this->db->lasterror();
7784 $result = $this->insertExtraFields(
'', $user);
7791 if (!$error && !empty($this->fields[
'fk_user_modif'])) {
7792 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
7793 $sql .=
" SET fk_user_modif = ".(int) $userused->id;
7794 $sql .=
" WHERE ".(empty($this->table_rowid) ?
'rowid' : $this->db->sanitize($this->table_rowid)).
" = ".((
int)
$this->id);
7795 $this->db->query($sql);
7799 $parameters = array(
'key' => $key);
7801 $reshook = $hookmanager->executeHooks(
'updateExtraFieldBeforeCommit', $parameters, $this, $action);
7807 if (!$error && $trigger) {
7809 $this->context = array(
'extrafieldupdate' => 1);
7810 $result = $this->call_trigger($trigger, $userused);
7818 dol_syslog(__METHOD__.$this->error, LOG_ERR);
7819 $this->db->rollback();
7822 $this->db->commit();
7838 return $this->array_options[
'options_'.$key] ??
null;
7850 $this->array_options[
'options_'.$key] = $value;
7867 if (empty($userused)) {
7895 public function showInputField($val, $key, $value, $moreparam =
'', $keysuffix =
'', $keyprefix =
'', $morecss = 0, $nonewbutton = 0)
7897 global
$conf, $langs, $form;
7902 if (!is_object($form)) {
7903 require_once DOL_DOCUMENT_ROOT.
'/core/class/html.form.class.php';
7904 $form =
new Form($this->db);
7907 if (!empty($this->fields)) {
7908 $val = $this->fields[$key];
7912 $fieldValidationErrorMsg =
'';
7913 $validationClass =
'';
7914 $fieldValidationErrorMsg = $this->getFieldError($key);
7915 if (!empty($fieldValidationErrorMsg)) {
7916 $validationClass =
' --error';
7918 $validationClass =
' --success';
7926 $param[
'options'] = array();
7929 $size = !empty($this->fields[$key][
'size']) ? $this->fields[$key][
'size'] : 0;
7931 if (preg_match(
'/^(integer|link):(.*):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
7932 $param[
'options'] = array($reg[2].
':'.$reg[3].
':'.$reg[4].
':'.$reg[5] =>
'N');
7934 } elseif (preg_match(
'/^(integer|link):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
7935 $param[
'options'] = array($reg[2].
':'.$reg[3].
':'.$reg[4] =>
'N');
7937 } elseif (preg_match(
'/^(integer|link):(.*):(.*)/i', $val[
'type'], $reg)) {
7938 $param[
'options'] = array($reg[2].
':'.$reg[3] =>
'N');
7940 } elseif (preg_match(
'/^(sellist):(.*):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
7941 $param[
'options'] = array($reg[2].
':'.$reg[3].
':'.$reg[4].
':'.$reg[5] =>
'N');
7943 } elseif (preg_match(
'/^(sellist):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
7944 $param[
'options'] = array($reg[2].
':'.$reg[3].
':'.$reg[4] =>
'N');
7946 } elseif (preg_match(
'/^(sellist):(.*):(.*)/i', $val[
'type'], $reg)) {
7947 $param[
'options'] = array($reg[2].
':'.$reg[3] =>
'N');
7949 } elseif (preg_match(
'/^chkbxlst:(.*)/i', $val[
'type'], $reg)) {
7950 $param[
'options'] = array($reg[1] =>
'N');
7952 } elseif (preg_match(
'/varchar\((\d+)\)/', $val[
'type'], $reg)) {
7953 $param[
'options'] = array();
7956 } elseif (preg_match(
'/varchar/', $val[
'type'])) {
7957 $param[
'options'] = array();
7959 } elseif (preg_match(
'/stars\((\d+)\)/', $val[
'type'], $reg)) {
7960 $param[
'options'] = array();
7964 $param[
'options'] = array();
7965 $type = $this->fields[$key][
'type'];
7970 if (!empty($this->fields[$key][
'arrayofkeyval']) && is_array($this->fields[$key][
'arrayofkeyval'])) {
7971 $param[
'options'] = $this->fields[$key][
'arrayofkeyval'];
7973 if (empty($this->fields[$key][
'multiinput'])) {
7974 $type = (($this->fields[$key][
'type'] ==
'checkbox') ? $this->fields[$key][
'type'] :
'select');
7978 $label = $this->fields[$key][
'label'];
7981 $default = (!empty($this->fields[$key][
'default']) ? $this->fields[$key][
'default'] :
'');
7983 $computed = (!empty($this->fields[$key][
'computed']) ? $this->fields[$key][
'computed'] :
'');
7985 $unique = (!empty($this->fields[$key][
'unique']) ? $this->fields[$key][
'unique'] : 0);
7987 $required = (!empty($this->fields[$key][
'required']) ? $this->fields[$key][
'required'] : 0);
7989 $autofocusoncreate = (!empty($this->fields[$key][
'autofocusoncreate']) ? $this->fields[$key][
'autofocusoncreate'] : 0);
7991 $placeholder = (!empty($this->fields[$key][
'placeholder']) ? $this->fields[$key][
'placeholder'] : 0);
7994 $langfile = (!empty($this->fields[$key][
'langfile']) ? $this->fields[$key][
'langfile'] :
'');
7996 $list = (!empty($this->fields[$key][
'list']) ? $this->fields[$key][
'list'] : 0);
7997 $hidden = (in_array(abs($this->fields[$key][
'visible']), array(0, 2)) ? 1 : 0);
8002 if (!preg_match(
'/^search_/', $keyprefix)) {
8003 return '<span class="opacitymedium">'.$langs->trans(
"AutomaticallyCalculated").
'</span>';
8010 if (empty($morecss) && !empty($val[
'css'])) {
8011 $morecss = $val[
'css'];
8012 } elseif (empty($morecss)) {
8013 if ($type ==
'date') {
8014 $morecss =
'minwidth100imp';
8015 } elseif ($type ==
'datetime' || $type ==
'link') {
8016 $morecss =
'minwidth200imp';
8017 } elseif (in_array($type, array(
'int',
'integer',
'price')) || preg_match(
'/^double(\([0-9],[0-9]\)){0,1}/', (
string) $type)) {
8018 $morecss =
'maxwidth75';
8019 } elseif ($type ==
'url') {
8020 $morecss =
'minwidth400';
8021 } elseif ($type ==
'boolean') {
8024 if (is_numeric($size) && round((
float) $size) < 12) {
8025 $morecss =
'minwidth100';
8026 } elseif (is_numeric($size) && round((
float) $size) <= 48) {
8027 $morecss =
'minwidth200';
8029 $morecss =
'minwidth400';
8035 if (!empty($validationClass)) {
8036 $morecss .= $validationClass;
8039 if (in_array($type, array(
'date'))) {
8040 $tmp = explode(
',', $size);
8045 if (!$required && $value ==
'') {
8050 $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required,
'', 1, (($keyprefix !=
'search_' && $keyprefix !=
'search_options_') ? 1 : 0), 0, 1);
8051 } elseif (in_array($type, array(
'datetime'))) {
8052 $tmp = explode(
',', $size);
8057 if (!$required && $value ==
'') {
8062 $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required,
'', 1, (($keyprefix !=
'search_' && $keyprefix !=
'search_options_') ? 1 : 0), 0, 1,
'',
'',
'', 1,
'',
'',
'tzuserrel');
8063 } elseif (in_array($type, array(
'duration'))) {
8064 $out = $form->select_duration($keyprefix.$key.$keysuffix, $value, 0,
'text', 0, 1);
8065 } elseif (in_array($type, array(
'int',
'integer'))) {
8066 $tmp = explode(
',', $size);
8068 $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' :
'').
'>';
8069 } elseif (in_array($type, array(
'real'))) {
8070 $out =
'<input type="text" class="flat '.$morecss.
'" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.
dol_escape_htmltag($value).
'"'.($moreparam ? $moreparam :
'').($autofocusoncreate ?
' autofocus' :
'').
'>';
8071 } elseif (preg_match(
'/varchar/', (
string) $type)) {
8072 $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' :
'').
'>';
8073 } elseif (in_array($type, array(
'email',
'mail',
'phone',
'url',
'ip'))) {
8074 $out =
'<input type="text" class="flat '.$morecss.
'" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.
dol_escape_htmltag($value).
'" '.($moreparam ? $moreparam :
'').($autofocusoncreate ?
' autofocus' :
'').
'>';
8075 } elseif (preg_match(
'/^text/', (
string) $type)) {
8076 if (!preg_match(
'/search_/', $keyprefix)) {
8077 if (!empty($param[
'options'])) {
8080 $out .= $form->selectarray($keyprefix.$key.$keysuffix.
"_multiinput", $param[
'options'],
'', 1, 0, 0,
"flat maxwidthonphone".$morecss);
8081 $out .=
'<input id="'.$keyprefix.$key.$keysuffix.
'_multiinputadd" type="button" class="button" value="'.$langs->trans(
"Add").
'">';
8084 function handlemultiinputdisabling(htmlname){
8085 console.log("We handle the disabling of used options for "+htmlname+"_multiinput");
8086 multiinput = $("#"+htmlname+"_multiinput");
8087 multiinput.find("option").each(function(){
8088 tmpval = $("#"+htmlname).val();
8089 tmpvalarray = tmpval.split("\n");
8090 valtotest = $(this).val();
8091 if(tmpvalarray.includes(valtotest)){
8092 $(this).prop("disabled",true);
8094 if($(this).prop("disabled") == true){
8095 console.log(valtotest)
8096 $(this).prop("disabled", false);
8102 $(document).ready(function () {
8103 $("#'.$keyprefix.$key.$keysuffix.
'_multiinputadd").on("click",function() {
8104 tmpval = $("#'.$keyprefix.$key.$keysuffix.
'").val();
8105 tmpvalarray = tmpval.split(",");
8106 valtotest = $("#'.$keyprefix.$key.$keysuffix.
'_multiinput").val();
8107 if(valtotest != -1 && !tmpvalarray.includes(valtotest)){
8108 console.log("We add the selected value to the text area '.$keyprefix.$key.$keysuffix.
'");
8112 tmpval = tmpval + "\n" + valtotest;
8114 $("#'.$keyprefix.$key.$keysuffix.
'").val(tmpval);
8115 handlemultiinputdisabling("'.$keyprefix.$key.$keysuffix.
'");
8116 $("#'.$keyprefix.$key.$keysuffix.
'_multiinput").val(-1);
8118 console.log("We add nothing the text area '.$keyprefix.$key.$keysuffix.
'");
8121 $("#'.$keyprefix.$key.$keysuffix.
'").on("change",function(){
8122 handlemultiinputdisabling("'.$keyprefix.$key.$keysuffix.
'");
8124 handlemultiinputdisabling("'.$keyprefix.$key.$keysuffix.
'");
8126 $out .=
"</script>";
8127 $value = str_replace(
',',
"\n", $value);
8129 require_once DOL_DOCUMENT_ROOT.
'/core/class/doleditor.class.php';
8130 $doleditor =
new DolEditor($keyprefix.$key.$keysuffix, $value,
'', 200,
'dolibarr_notes',
'In',
false,
false,
false, ROWS_5,
'90%');
8131 $out .= (
string) $doleditor->Create(1,
'',
true,
'',
'',
'', $morecss);
8133 $out =
'<input type="text" class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.
dol_escape_htmltag($value).
'" '.($moreparam ? $moreparam :
'').
'>';
8135 } elseif (preg_match(
'/^html/', (
string) $type)) {
8136 if (!preg_match(
'/search_/', $keyprefix)) {
8137 require_once DOL_DOCUMENT_ROOT.
'/core/class/doleditor.class.php';
8138 $doleditor =
new DolEditor($keyprefix.$key.$keysuffix, $value,
'', 200,
'dolibarr_notes',
'In',
false,
false,
isModEnabled(
'fckeditor') &&
getDolGlobalInt(
'FCKEDITOR_ENABLE_SOCIETE'), ROWS_5,
'90%');
8139 $out = (
string) $doleditor->Create(1,
'',
true,
'',
'', $moreparam, $morecss);
8141 $out =
'<input type="text" class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.
dol_escape_htmltag($value).
'" '.($moreparam ? $moreparam :
'').
'>';
8143 } elseif ($type ==
'boolean') {
8145 if (!empty($value)) {
8146 $checked =
' checked value="1" ';
8148 $checked =
' value="1" ';
8150 $out =
'<input type="checkbox" class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" '.$checked.
' '.($moreparam ? $moreparam :
'').
'>';
8151 } elseif ($type ==
'price') {
8152 if (!empty($value)) {
8153 $value =
price($value);
8155 $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>';
8156 } elseif ($type ==
'stars') {
8157 $out =
'<input type="hidden" class="flat '.$morecss.
'" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.
dol_escape_htmltag($value).
'"'.($moreparam ? $moreparam :
'').($autofocusoncreate ?
' autofocus' :
'').
'>';
8158 $out .=
'<div class="star-selection" id="'.$keyprefix.$key.$keysuffix.
'_selection">';
8160 while ($i <= $size) {
8161 $out .=
'<span class="star" data-value="'.$i.
'">'.
img_picto(
'',
'fontawesome_star_fas').
'</span>';
8166 jQuery(function($) { /* commonobject.class.php 1 */
8167 let container = $("#'.$keyprefix.$key.$keysuffix.
'_selection");
8168 let selectedStars = parseInt($("#'.$keyprefix.$key.$keysuffix.
'").val()) || 0;
8169 container.find(".star").each(function() {
8170 $(this).toggleClass("active", $(this).data("value") <= selectedStars);
8172 container.find(".star").on("mouseover", function() {
8173 let selectedStar = $(this).data("value");
8174 container.find(".star").each(function() {
8175 $(this).toggleClass("active", $(this).data("value") <= selectedStar);
8178 container.on("mouseout", function() {
8179 container.find(".star").each(function() {
8180 $(this).toggleClass("active", $(this).data("value") <= selectedStars);
8183 container.find(".star").off("click").on("click", function() {
8184 selectedStars = $(this).data("value");
8185 if (selectedStars === 1 && $("#'.$keyprefix.$key.$keysuffix.
'").val() == 1) {
8188 $("#'.$keyprefix.$key.$keysuffix.
'").val(selectedStars);
8189 container.find(".star").each(function() {
8190 $(this).toggleClass("active", $(this).data("value") <= selectedStars);
8195 } elseif (preg_match(
'/^double(\([0-9],[0-9]\)){0,1}/', (
string) $type)) {
8196 if (!empty($value)) {
8197 $value =
price($value);
8199 $out =
'<input type="text" class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.$value.
'" '.($moreparam ? $moreparam :
'').
'> ';
8200 } elseif ($type ==
'select') {
8203 include_once DOL_DOCUMENT_ROOT.
'/core/lib/ajax.lib.php';
8204 $out .=
ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
8210 foreach ($param[
'options'] as $keyb => $valb) {
8211 if ((
string) $keyb ==
'') {
8214 if (strpos($valb,
"|") !==
false) {
8215 list($valb, $parent) = explode(
'|', $valb);
8218 $tmpselect .=
'<option value="'.$keyb.
'"';
8219 $tmpselect .= (((
string) $value == (
string) $keyb) ?
' selected' :
'');
8220 if (!empty($parent)) {
8223 $tmpselect .= (!empty($parent) ?
' parent="'.$parent.
'"' :
'');
8224 $tmpselect .=
'>'.$langs->trans($valb).
'</option>';
8227 $out .=
'<select class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" '.($moreparam ? $moreparam :
'').
'>';
8228 if ((!isset($this->fields[$key][
'default'])) || empty($this->fields[$key][
'notnull']) || ($this->fields[$key][
'notnull'] != 1) || $nbchoice >= 2) {
8229 $out .=
'<option value="0"> </option>';
8232 $out .=
'</select>';
8233 } elseif ($type ==
'sellist') {
8236 include_once DOL_DOCUMENT_ROOT.
'/core/lib/ajax.lib.php';
8237 $out .=
ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
8240 $out .=
'<select class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" '.($moreparam ? $moreparam :
'').
'>';
8241 if (is_array($param[
'options'])) {
8242 $tmpparamoptions = array_keys($param[
'options']);
8243 $paramoptions = preg_split(
'/[\r\n]+/', $tmpparamoptions[0]);
8245 $InfoFieldList = explode(
":", $paramoptions[0], 5);
8257 if (! empty($InfoFieldList[4])) {
8259 $parenthesisopen = 0;
8260 while (substr($InfoFieldList[4], $pos, 1) !==
'' && ($parenthesisopen || $pos == 0 || substr($InfoFieldList[4], $pos, 1) !=
':')) {
8261 if (substr($InfoFieldList[4], $pos, 1) ==
'(') {
8264 if (substr($InfoFieldList[4], $pos, 1) ==
')') {
8269 $tmpbefore = substr($InfoFieldList[4], 0, $pos);
8270 $tmpafter = substr($InfoFieldList[4], $pos + 1);
8272 $InfoFieldList[4] = $tmpbefore;
8273 if ($tmpafter !==
'') {
8274 $InfoFieldList = array_merge($InfoFieldList, explode(
':', $tmpafter));
8280 if (preg_match(
'/^\(?([a-z0-9]+)([=<>]+)(\d+)\)?$/i', $InfoFieldList[4], $reg)) {
8281 $InfoFieldList[4] =
'('.$reg[1].
':'.$reg[2].
':'.$reg[3].
')';
8292 $keyList = (empty($InfoFieldList[2]) ?
'rowid' : $InfoFieldList[2].
' as rowid');
8294 if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
8295 if (strpos($InfoFieldList[4],
'extra.') !==
false) {
8296 $keyList =
'main.'.$InfoFieldList[2].
' as rowid';
8298 $keyList = $InfoFieldList[2].
' as rowid';
8301 if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
8302 list($parentName, $parentField) = explode(
'|', $InfoFieldList[3]);
8303 if (!empty($InfoFieldList[4]) && strpos($InfoFieldList[4],
'extra.') !==
false) {
8304 $keyList .=
', main.'.$parentField;
8306 $keyList .=
', '.$parentField;
8310 $filter_categorie =
false;
8311 if (count($InfoFieldList) > 5) {
8312 if ($InfoFieldList[0] ==
'categorie') {
8313 $filter_categorie =
true;
8317 if (!$filter_categorie) {
8318 $fields_label = isset($InfoFieldList[1]) ? explode(
'|', $InfoFieldList[1]) : array();
8319 if (!empty($fields_label)) {
8321 $keyList .= implode(
', ', $fields_label);
8325 $sql =
"SELECT " . $this->db->sanitize($keyList, 0, 0, 1);
8326 $sql .=
" FROM " . $this->db->prefix() . $this->db->sanitize($InfoFieldList[0]);
8328 if (!empty($InfoFieldList[4])) {
8330 if (strpos($InfoFieldList[4],
'$SEL$') !==
false) {
8331 $InfoFieldList[4] = str_replace(
'$SEL$',
'SELECT', $InfoFieldList[4]);
8335 if (strpos($InfoFieldList[4],
'$ID$') !==
false && !empty($objectid)) {
8336 $InfoFieldList[4] = str_replace(
'$ID$', (
string) $objectid, $InfoFieldList[4]);
8338 $InfoFieldList[4] = str_replace(
'$ID$',
'0', $InfoFieldList[4]);
8343 if (strpos($InfoFieldList[4],
'extra') !==
false) {
8344 $sql .=
" as main, " . $this->db->sanitize($this->db->prefix() . $InfoFieldList[0]) .
"_extrafields as extra";
8345 $sqlwhere .=
" WHERE extra.fk_object = main." . $this->db->sanitize($InfoFieldList[2]);
8351 $sqlwhere .=
' WHERE 1=1';
8368 if (in_array($InfoFieldList[0], array(
'tablewithentity'))) {
8369 $sqlwhere .=
" AND entity = " . ((int)
$conf->entity);
8374 if (isset($InfoFieldList[7]) && preg_match(
'/^[a-z0-9_\-,]+$/i', $InfoFieldList[7])) {
8375 $sql .=
" ORDER BY ".$this->db->sanitize($InfoFieldList[7]);
8377 $sql .=
" ORDER BY ".$this->db->sanitize(implode(
', ', $fields_label));
8379 $sql .=
' LIMIT ' .
getDolGlobalInt(
'MAIN_EXTRAFIELDS_LIMIT_SELLIST_SQL', 1000);
8382 dol_syslog(get_class($this) .
'::showInputField type=sellist', LOG_DEBUG);
8383 $resql = $this->db->query($sql);
8385 $out .=
'<option value="0"> </option>';
8386 $num = $this->db->num_rows($resql);
8390 $obj = $this->db->fetch_object($resql);
8394 $fields_label = explode(
'|', $InfoFieldList[1]);
8395 if (count($fields_label) > 1) {
8397 foreach ($fields_label as $field_toshow) {
8398 $labeltoshow .= $obj->$field_toshow .
' ';
8401 $labeltoshow = $obj->{$InfoFieldList[1]};
8403 $labeltoshow =
dol_trunc($labeltoshow, 45);
8405 if ($value == $obj->rowid) {
8406 foreach ($fields_label as $field_toshow) {
8407 $translabel = $langs->trans($obj->$field_toshow);
8408 if ($translabel != $obj->$field_toshow) {
8409 $labeltoshow =
dol_trunc($translabel) .
' ';
8411 $labeltoshow =
dol_trunc($obj->$field_toshow) .
' ';
8414 $out .=
'<option value="' . $obj->rowid .
'" selected>' . $labeltoshow .
'</option>';
8417 $translabel = $langs->trans($obj->{$InfoFieldList[1]});
8418 if ($translabel != $obj->{$InfoFieldList[1]}) {
8419 $labeltoshow =
dol_trunc($translabel, 18);
8421 $labeltoshow =
dol_trunc($obj->{$InfoFieldList[1]});
8424 if (empty($labeltoshow)) {
8425 $labeltoshow =
'(not defined)';
8427 if ($value == $obj->rowid) {
8428 $out .=
'<option value="' . $obj->rowid .
'" selected>' . $labeltoshow .
'</option>';
8431 if (!empty($InfoFieldList[3]) && $parentField) {
8432 $parent = $parentName .
':' . $obj->{$parentField};
8436 $out .=
'<option value="' . $obj->rowid .
'"';
8437 $out .= ($value == $obj->rowid ?
' selected' :
'');
8438 $out .= (!empty($parent) ?
' parent="' . $parent .
'"' :
'');
8439 $out .=
'>' . $labeltoshow .
'</option>';
8444 $this->db->free($resql);
8446 print
'Error in request ' . $sql .
' ' . $this->db->lasterror() .
'. Check setup of extra parameters.<br>';
8449 require_once DOL_DOCUMENT_ROOT.
'/categories/class/categorie.class.php';
8450 $categcode = $InfoFieldList[5];
8451 if (is_numeric($categcode)) {
8452 $tmpcategory =
new Categorie($this->db);
8453 $MAP_ID_TO_CODE = array_flip($tmpcategory->MAP_ID);
8454 $categcode = $MAP_ID_TO_CODE[(int) $categcode];
8457 $data = $form->select_all_categories($categcode,
'',
'parent', 64, $InfoFieldList[6], 1, 1);
8458 $out .=
'<option value="0"> </option>';
8459 foreach ($data as $data_key => $data_value) {
8460 $out .=
'<option value="' . $data_key .
'"';
8461 $out .= ($value == $data_key ?
' selected' :
'');
8462 $out .=
'>' . $data_value .
'</option>';
8466 $out .=
'</select>';
8467 } elseif ($type ==
'checkbox') {
8468 $value_arr = explode(
',', $value);
8469 $out = $form->multiselectarray($keyprefix.$key.$keysuffix, (empty($param[
'options']) ?
null : $param[
'options']), $value_arr, 0, 0, $morecss, 0,
'100%');
8470 } elseif ($type ==
'radio') {
8472 foreach ($param[
'options'] as $keyopt => $valopt) {
8473 $out .=
'<input class="flat '.$morecss.
'" type="radio" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" '.($moreparam ? $moreparam :
'');
8474 $out .=
' value="'.$keyopt.
'"';
8475 $out .=
' id="'.$keyprefix.$key.$keysuffix.
'_'.$keyopt.
'"';
8476 $out .= ($value == $keyopt ?
'checked' :
'');
8477 $out .=
'/><label for="'.$keyprefix.$key.$keysuffix.
'_'.$keyopt.
'">'.$valopt.
'</label><br>';
8479 } elseif ($type ==
'chkbxlst') {
8480 if (is_array($value)) {
8481 $value_arr = $value;
8483 $value_arr = explode(
',', $value);
8486 if (is_array($param[
'options'])) {
8487 $tmpparamoptions = array_keys($param[
'options']);
8488 $paramoptions = preg_split(
'/[\r\n]+/', $tmpparamoptions[0]);
8490 $InfoFieldList = explode(
":", $paramoptions[0], 5);
8502 if (! empty($InfoFieldList[4])) {
8504 $parenthesisopen = 0;
8505 while (substr($InfoFieldList[4], $pos, 1) !==
'' && ($parenthesisopen || $pos == 0 || substr($InfoFieldList[4], $pos, 1) !=
':')) {
8506 if (substr($InfoFieldList[4], $pos, 1) ==
'(') {
8509 if (substr($InfoFieldList[4], $pos, 1) ==
')') {
8514 $tmpbefore = substr($InfoFieldList[4], 0, $pos);
8515 $tmpafter = substr($InfoFieldList[4], $pos + 1);
8517 $InfoFieldList[4] = $tmpbefore;
8518 if ($tmpafter !==
'') {
8519 $InfoFieldList = array_merge($InfoFieldList, explode(
':', $tmpafter));
8524 if (preg_match(
'/^\(?([a-z0-9]+)([=<>]+)(\d+)\)?$/i', $InfoFieldList[4], $reg)) {
8525 $InfoFieldList[4] =
'('.$reg[1].
':'.$reg[2].
':'.$reg[3].
')';
8533 '@phan-var-force array{0:string,1:string,2:string,3:string,3:string,5:string,6:string} $InfoFieldList';
8538 $keyList = (empty($InfoFieldList[2]) ?
'rowid' : $InfoFieldList[2].
' as rowid');
8540 if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
8541 if (strpos($InfoFieldList[4],
'extra.') !==
false) {
8542 $keyList =
'main.'.$InfoFieldList[2].
' as rowid';
8544 $keyList = $InfoFieldList[2].
' as rowid';
8547 if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
8548 list($parentName, $parentField) = explode(
'|', $InfoFieldList[3]);
8549 if (!empty($InfoFieldList[4]) && strpos($InfoFieldList[4],
'extra.') !==
false) {
8550 $keyList .=
', main.'.$parentField;
8552 $keyList .=
', '.$parentField;
8556 $filter_categorie =
false;
8557 if (count($InfoFieldList) > 5) {
8558 if ($InfoFieldList[0] ==
'categorie') {
8559 $filter_categorie =
true;
8564 if (!$filter_categorie) {
8565 $fields_label = explode(
'|', $InfoFieldList[1]);
8566 if (is_array($fields_label)) {
8568 $keyList .= implode(
', ', $fields_label);
8572 $sql =
"SELECT " . $this->db->sanitize($keyList, 0, 0, 1);
8573 $sql .=
' FROM ' . $this->db->prefix() . $this->db->sanitize($InfoFieldList[0]);
8575 if (!empty($InfoFieldList[4])) {
8577 if (strpos($InfoFieldList[4],
'$SEL$') !==
false) {
8578 $InfoFieldList[4] = str_replace(
'$SEL$',
'SELECT', $InfoFieldList[4]);
8582 if (strpos($InfoFieldList[4],
'$ID$') !==
false && !empty($objectid)) {
8583 $InfoFieldList[4] = str_replace(
'$ID$', (
string) $objectid, $InfoFieldList[4]);
8585 $InfoFieldList[4] = str_replace(
'$ID$',
'0', $InfoFieldList[4]);
8590 if (strpos($InfoFieldList[4],
'extra') !==
false) {
8591 $sql .=
' as main, ' . $this->db->sanitize($this->db->prefix() . $InfoFieldList[0]) .
'_extrafields as extra';
8592 $sqlwhere .=
" WHERE extra.fk_object = main." . $this->db->sanitize($InfoFieldList[2]);
8598 $sqlwhere .=
' WHERE 1=1';
8615 if (in_array($InfoFieldList[0], array(
'tablewithentity'))) {
8616 $sqlwhere .=
" AND entity = " . ((int)
$conf->entity);
8623 dol_syslog(get_class($this) .
'::showInputField type=chkbxlst', LOG_DEBUG);
8625 $resql = $this->db->query($sql);
8627 $num = $this->db->num_rows($resql);
8634 $obj = $this->db->fetch_object($resql);
8638 $fields_label = explode(
'|', $InfoFieldList[1]);
8639 if (count($fields_label) > 1) {
8641 foreach ($fields_label as $field_toshow) {
8642 $labeltoshow .= $obj->$field_toshow .
' ';
8645 $labeltoshow = $obj->{$InfoFieldList[1]};
8647 $labeltoshow =
dol_trunc($labeltoshow, 45);
8649 if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
8650 foreach ($fields_label as $field_toshow) {
8651 $translabel = $langs->trans($obj->$field_toshow);
8652 if ($translabel != $obj->$field_toshow) {
8653 $labeltoshow =
dol_trunc($translabel, 18) .
' ';
8655 $labeltoshow =
dol_trunc($obj->$field_toshow, 18) .
' ';
8659 $data[$obj->rowid] = $labeltoshow;
8662 $translabel = $langs->trans($obj->{$InfoFieldList[1]});
8663 if ($translabel != $obj->{$InfoFieldList[1]}) {
8664 $labeltoshow =
dol_trunc($translabel, 18);
8666 $labeltoshow =
dol_trunc($obj->{$InfoFieldList[1]}, 18);
8669 if (empty($labeltoshow)) {
8670 $labeltoshow =
'(not defined)';
8673 if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
8674 $data[$obj->rowid] = $labeltoshow;
8677 if (!empty($InfoFieldList[3]) && $parentField) {
8678 $parent = $parentName .
':' . $obj->{$parentField};
8682 $data[$obj->rowid] = $labeltoshow;
8687 $this->db->free($resql);
8689 $out = $form->multiselectarray($keyprefix . $key . $keysuffix, $data, $value_arr, 0, 0, $morecss, 0,
'100%');
8691 print
'Error in request ' . $sql .
' ' . $this->db->lasterror() .
'. Check setup of extra parameters.<br>';
8694 require_once DOL_DOCUMENT_ROOT.
'/categories/class/categorie.class.php';
8695 $categcode = $InfoFieldList[5];
8696 if (is_numeric($categcode)) {
8697 $tmpcategory =
new Categorie($this->db);
8698 $MAP_ID_TO_CODE = array_flip($tmpcategory->MAP_ID);
8699 $categcode = $MAP_ID_TO_CODE[(int) $categcode];
8702 $data = $form->select_all_categories($categcode,
'',
'parent', 64, $InfoFieldList[6], 1, 1);
8703 $out = $form->multiselectarray($keyprefix . $key . $keysuffix, $data, $value_arr, 0, 0, $morecss, 0,
'100%');
8706 } elseif ($type ==
'link') {
8709 $param_list = array_keys($param[
'options']);
8710 $param_list_array = explode(
':', $param_list[0], 4);
8712 $showempty = (($required && $default !=
'') ? 0 : 1);
8714 if (!preg_match(
'/search_/', $keyprefix)) {
8715 if (!empty($param_list_array[2])) {
8717 if (!empty($this->fields[$key][
'picto'])) {
8718 $morecss .=
' widthcentpercentminusxx';
8720 $morecss .=
' widthcentpercentminusx';
8724 if (!empty($this->fields[$key][
'picto'])) {
8725 $morecss .=
' widthcentpercentminusx';
8734 $objectfield = $val;
8737 $out = $form->selectForForms($param_list_array[0], $keyprefix.$key.$keysuffix, (
int) $value, $showempty,
'',
'', $morecss, $moreparam, 0, (empty($val[
'disabled']) ? 0 : 1),
'', $objectfield);
8739 if (!empty($param_list_array[2])) {
8740 if ((!GETPOSTISSET(
'backtopage') || strpos(
GETPOST(
'backtopage'), $_SERVER[
'PHP_SELF']) === 0)
8741 && empty($val[
'disabled']) && empty($nonewbutton)) {
8742 list($class, $classfile) = explode(
':', $param_list[0]);
8743 if (file_exists(
dol_buildpath(dirname(dirname($classfile)).
'/card.php'))) {
8744 $url_path =
dol_buildpath(dirname(dirname($classfile)).
'/card.php', 1);
8746 $url_path =
dol_buildpath(dirname(dirname($classfile)).
'/'.strtolower($class).
'_card.php', 1);
8748 $paramforthenewlink =
'';
8749 $paramforthenewlink .= (GETPOSTISSET(
'action') ?
'&action='.GETPOST(
'action',
'aZ09') :
'');
8750 $paramforthenewlink .= (GETPOSTISSET(
'id') ?
'&id='.GETPOSTINT(
'id') :
'');
8751 $paramforthenewlink .= (GETPOSTISSET(
'origin') ?
'&origin='.GETPOST(
'origin',
'aZ09') :
'');
8752 $paramforthenewlink .= (GETPOSTISSET(
'originid') ?
'&originid='.GETPOSTINT(
'originid') :
'');
8753 $paramforthenewlink .=
'&fk_'.strtolower($class).
'=--IDFORBACKTOPAGE--';
8755 $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>';
8758 } elseif ($type ==
'password') {
8760 if ($keyprefix.$key.$keysuffix ==
'pass_crypted') {
8761 $out =
'<input type="'.($keyprefix ==
'search_' ?
'text' :
'password').
'" class="flat '.$morecss.
'" name="pass" id="pass" value="" '.($moreparam ? $moreparam :
'').
'>';
8762 $out .=
'<input type="hidden" name="pass_crypted" id="pass_crypted" value="'.$value.
'" '.($moreparam ? $moreparam :
'').
'>';
8764 $out =
'<input type="'.($keyprefix ==
'search_' ?
'text' :
'password').
'" class="flat '.$morecss.
'" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.$value.
'" '.($moreparam ? $moreparam :
'').
'>';
8766 } elseif ($type ==
'array') {
8768 $newval[
'type'] =
'varchar(256)';
8771 if (!empty($value)) {
8772 foreach ($value as $option) {
8773 $out .=
'<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).
'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
8774 $out .= $this->showInputField($newval, $keyprefix.$key.$keysuffix.
'[]', $option, $moreparam,
'',
'', $morecss).
'<br></span>';
8777 $out .=
'<a id="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).
'_add" href="javascript:;"><span class="fa fa-plus-circle valignmiddle"></span></a>';
8779 $newInput =
'<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).
'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
8780 $newInput .= $this->showInputField($newval, $keyprefix.$key.$keysuffix.
'[]',
'', $moreparam,
'',
'', $morecss).
'<br></span>';
8782 if (!empty(
$conf->use_javascript_ajax)) {
8784 <script nonce="'.getNonce().
'">
8785 $(document).ready(function() {
8786 $("a#'.
dol_escape_js($keyprefix.$key.$keysuffix).
'_add").click(function() {
8790 $(document).on("click", "a.'.
dol_escape_js($keyprefix.$key.$keysuffix).
'_del", function() {
8791 $(this).parent().remove();
8797 if (!empty($hidden)) {
8798 $out =
'<input type="hidden" value="'.$value.
'" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'"/>';
8801 if ($isDependList == 1) {
8802 $out .= $this->getJSListDependancies(
'_common');
8810 if (!empty($fieldValidationErrorMsg) && function_exists(
'getFieldErrorIcon')) {
8811 $out .=
' '.getFieldErrorIcon($fieldValidationErrorMsg);
8830 public function showOutputField($val, $key, $value, $moreparam =
'', $keysuffix =
'', $keyprefix =
'', $morecss =
'')
8832 global
$conf, $langs, $form;
8836 if (!is_object($form)) {
8837 require_once DOL_DOCUMENT_ROOT.
'/core/class/html.form.class.php';
8838 $form =
new Form($this->db);
8842 $type = empty($val[
'type']) ?
'' : $val[
'type'];
8843 $size = empty($val[
'css']) ?
'' : $val[
'css'];
8848 if (preg_match(
'/varchar\((\d+)\)/', $type, $reg)) {
8851 } elseif (preg_match(
'/varchar/', $type)) {
8854 if (!empty($val[
'arrayofkeyval']) && is_array($val[
'arrayofkeyval'])) {
8856 if (empty($this->fields[$key][
'multiinput'])) {
8857 $type = (($this->fields[$key][
'type'] ==
'checkbox') ? $this->fields[$key][
'type'] :
'select');
8860 if (isset($val[
'type']) && preg_match(
'/^integer:(.*):(.*)/i', $val[
'type'], $reg)) {
8864 $default = empty($val[
'default']) ?
'' : $val[
'default'];
8865 $computed = empty($val[
'computed']) ?
'' : $val[
'computed'];
8866 $unique = empty($val[
'unique']) ?
'' : $val[
'unique'];
8867 $required = empty($val[
'required']) ?
'' : $val[
'required'];
8869 $param[
'options'] = array();
8871 if (!empty($val[
'arrayofkeyval']) && is_array($val[
'arrayofkeyval'])) {
8872 $param[
'options'] = $val[
'arrayofkeyval'];
8874 if (isset($val[
'type']) && preg_match(
'/^integer:([^:]*):([^:]*)/i', $val[
'type'], $reg)) {
8876 $stringforoptions = $reg[1].
':'.$reg[2];
8878 if ($reg[1] ==
'User') {
8879 $stringforoptions .=
':#getnomurlparam1=-1';
8881 $param[
'options'] = array($stringforoptions => $stringforoptions);
8882 } elseif (isset($val[
'type']) && preg_match(
'/^sellist:(.*):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
8883 $param[
'options'] = array($reg[1].
':'.$reg[2].
':'.$reg[3].
':'.$reg[4] =>
'N');
8885 } elseif (isset($val[
'type']) && preg_match(
'/^sellist:(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
8886 $param[
'options'] = array($reg[1].
':'.$reg[2].
':'.$reg[3] =>
'N');
8888 } elseif (isset($val[
'type']) && preg_match(
'/^sellist:(.*):(.*)/i', $val[
'type'], $reg)) {
8889 $param[
'options'] = array($reg[1].
':'.$reg[2] =>
'N');
8891 } elseif (isset($val[
'type']) && preg_match(
'/^chkbxlst:(.*)/i', $val[
'type'], $reg)) {
8892 $param[
'options'] = array($reg[1] =>
'N');
8894 } elseif (isset($val[
'type']) && preg_match(
'/stars\((\d+)\)/', $val[
'type'], $reg)) {
8895 $param[
'options'] = array();
8900 $langfile = empty($val[
'langfile']) ?
'' : $val[
'langfile'];
8901 $list = (empty($val[
'list']) ?
'' : $val[
'list']);
8902 $help = (empty($val[
'help']) ?
'' : $val[
'help']);
8903 $hidden = (($val[
'visible'] == 0) ? 1 : 0);
8913 $value =
dol_eval((
string) $computed, 1, 0,
'2');
8916 if (empty($morecss)) {
8917 if ($type ==
'date') {
8918 $morecss =
'minwidth100imp';
8919 } elseif ($type ==
'datetime' || $type ==
'timestamp') {
8920 $morecss =
'minwidth200imp';
8921 } elseif (in_array($type, array(
'int',
'double',
'price'))) {
8922 $morecss =
'maxwidth75';
8923 } elseif ($type ==
'url') {
8924 $morecss =
'minwidth400';
8925 } elseif ($type ==
'boolean') {
8928 if (is_numeric($size) && round((
float) $size) < 12) {
8929 $morecss =
'minwidth100';
8930 } elseif (is_numeric($size) && round((
float) $size) <= 48) {
8931 $morecss =
'minwidth200';
8933 $morecss =
'minwidth400';
8939 if (in_array($key, array(
'rowid',
'ref')) && method_exists($this,
'getNomUrl')) {
8941 if ($key !=
'rowid' || empty($this->fields[
'ref'])) {
8942 $value = $this->getNomUrl(1,
'', 0,
'', 1);
8944 } elseif ($key ==
'status' && method_exists($this,
'getLibStatut')) {
8945 $value = $this->getLibStatut(3);
8946 } elseif ($type ==
'date') {
8947 if (!empty($value)) {
8952 } elseif ($type ==
'datetime' || $type ==
'timestamp') {
8953 if (!empty($value)) {
8958 } elseif ($type ==
'duration') {
8959 include_once DOL_DOCUMENT_ROOT.
'/core/lib/date.lib.php';
8960 if (!is_null($value) && $value !==
'') {
8963 } elseif ($type ==
'double' || $type ==
'real') {
8964 if (!is_null($value) && $value !==
'') {
8965 $value =
price($value);
8967 } elseif ($type ==
'boolean') {
8969 if (!empty($value)) {
8970 $checked =
' checked ';
8973 $value =
'<input type="checkbox" '.$checked.
' '.($moreparam ? $moreparam :
'').
' readonly disabled>';
8975 $value =
yn($value ? 1 : 0);
8977 } elseif ($type ==
'mail' || $type ==
'email') {
8979 } elseif ($type ==
'url') {
8981 } elseif ($type ==
'phone') {
8982 $value =
dol_print_phone((
string) $value,
'', 0, 0,
'',
' ',
'phone');
8983 } elseif ($type ==
'ip') {
8985 } elseif ($type ==
'stars') {
8986 $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 :
'').
'>';
8987 $value .=
'<div class="star-selection" id="'.$keyprefix.$key.$keysuffix.$this->id.
'_selection">';
8989 while ($i <= $size) {
8990 $value .=
'<span class="star" data-value="'.$i.
'">'.
img_picto(
'',
'fontawesome_star_fas').
'</span>';
8995 $(document).ready(function() { /* commonobject.class.php 2 */
8996 let container = $("#'.$keyprefix.$key.$keysuffix.$this->id.
'_selection");
8997 let selectedStars = parseInt($("#'.$keyprefix.$key.$keysuffix.$this->id.
'").val()) || 0;
8998 container.find(".star").each(function() {
8999 $(this).toggleClass("active", $(this).data("value") <= selectedStars);
9001 container.find(".star").on("mouseover", function() {
9002 let selectedStar = $(this).data("value");
9003 container.find(".star").each(function() {
9004 $(this).toggleClass("active", $(this).data("value") <= selectedStar);
9007 container.on("mouseout", function() {
9008 container.find(".star").each(function() {
9009 $(this).toggleClass("active", $(this).data("value") <= selectedStars);
9012 container.find(".star").off("click").on("click", function() {
9013 selectedStars = $(this).data("value");
9014 if (selectedStars == 1 && $("#'.$keyprefix.$key.$keysuffix.$this->id.
'").val() == 1) {
9017 container.find("#'.$keyprefix.$key.$keysuffix.$this->id.
'").val(selectedStars);
9018 container.find(".star").each(function() {
9019 $(this).toggleClass("active", $(this).data("value") <= selectedStars);
9022 url: "ajax/'.$this->element.
'.php",
9025 objectId: "'.$this->
id.
'",
9026 field: "'.$keyprefix.$key.$keysuffix.
'",
9027 value: selectedStars,
9030 success: function(response) {
9031 var res = JSON.parse(response);
9032 console[res.status === "success" ? "log" : "error"](res.message);
9034 error: function(xhr, status, error) {
9035 console.log("Ajax request failed while updating '.$keyprefix.$key.$keysuffix.
':", error);
9041 } elseif ($type ==
'price') {
9042 if (!is_null($value) && $value !==
'') {
9043 $value =
price($value, 0, $langs, 0, 0, -1,
$conf->currency);
9045 } elseif ($type ==
'select') {
9046 $value = isset($param[
'options'][(
string) $value]) ? $param[
'options'][(
string) $value] :
'';
9047 if (strpos($value,
"|") !==
false) {
9048 $value = $langs->trans(explode(
'|', $value)[0]);
9049 } elseif (! is_numeric($value)) {
9050 $value = $langs->trans($value);
9052 } elseif ($type ==
'sellist') {
9053 $param_list = array_keys($param[
'options']);
9054 $InfoFieldList = explode(
":", $param_list[0]);
9056 $selectkey =
"rowid";
9059 if (count($InfoFieldList) > 2 && !empty($InfoFieldList[2])) {
9060 $selectkey = $InfoFieldList[2];
9061 $keyList = $InfoFieldList[2].
' as rowid';
9064 $fields_label = explode(
'|', $InfoFieldList[1]);
9065 if (is_array($fields_label)) {
9067 $keyList .= implode(
', ', $fields_label);
9070 $filter_categorie =
false;
9071 if (count($InfoFieldList) > 5) {
9072 if ($InfoFieldList[0] ==
'categorie') {
9073 $filter_categorie =
true;
9077 $sql =
"SELECT ".$this->db->sanitize($keyList, 0, 0, 1);
9078 $sql .=
' FROM '.$this->db->prefix().$this->db->sanitize($InfoFieldList[0]);
9079 if (isset($InfoFieldList[4]) && strpos($InfoFieldList[4],
'extra') !==
false) {
9082 if ($selectkey ==
'rowid' && empty($value)) {
9083 $sql .=
" WHERE ".$this->db->sanitize($selectkey).
" = 0";
9084 } elseif ($selectkey ==
'rowid') {
9085 $sql .=
" WHERE ".$this->db->sanitize($selectkey).
" = ".((int) $value);
9087 $sql .=
" WHERE ".$this->db->sanitize($selectkey).
" = '".$this->db->escape((
string) $value).
"'";
9092 dol_syslog(get_class($this).
':showOutputField:$type=sellist', LOG_DEBUG);
9093 $resql = $this->db->query($sql);
9095 if (!$filter_categorie) {
9097 $numrows = $this->db->num_rows($resql);
9099 $obj = $this->db->fetch_object($resql);
9102 $fields_label = explode(
'|', $InfoFieldList[1]);
9104 if (is_array($fields_label) && count($fields_label) > 1) {
9105 foreach ($fields_label as $field_toshow) {
9107 if (!empty($obj->$field_toshow)) {
9108 $translabel = $langs->trans($obj->$field_toshow);
9110 if ($translabel != $field_toshow) {
9111 $value .=
dol_trunc($translabel, 18) .
' ';
9113 $value .= $obj->$field_toshow .
' ';
9118 if (!empty($obj->{$InfoFieldList[1]})) {
9119 $translabel = $langs->trans($obj->{$InfoFieldList[1]});
9121 if ($translabel != $obj->{$InfoFieldList[1]}) {
9124 $value = $obj->{$InfoFieldList[1]};
9129 require_once DOL_DOCUMENT_ROOT .
'/categories/class/categorie.class.php';
9132 $obj = $this->db->fetch_object($resql);
9134 $c->fetch($obj->rowid);
9135 $ways =
$c->print_all_ways();
9136 foreach ($ways as $way) {
9137 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories"' . (
$c->color ?
' style="background: #' .
$c->color .
';"' :
' style="background: #aaa"') .
'>' .
img_object(
'',
'category') .
' ' . $way .
'</li>';
9139 $value =
'<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(
' ', $toprint).
'</ul></div>';
9142 dol_syslog(get_class($this).
'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
9144 } elseif ($type ==
'radio') {
9145 $value = $param[
'options'][(
string) $value];
9146 } elseif ($type ==
'checkbox') {
9147 $value_arr = explode(
',', (
string) $value);
9149 if (is_array($value_arr) && count($value_arr) > 0) {
9151 foreach ($value_arr as $keyval => $valueval) {
9152 if (!empty($valueval)) {
9153 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' . $param[
'options'][$valueval] .
'</li>';
9156 if (!empty($toprint)) {
9157 $value =
'<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">' . implode(
' ', $toprint) .
'</ul></div>';
9160 } elseif ($type ==
'chkbxlst') {
9161 $value_arr = (isset($value) ? explode(
',', $value) : array());
9163 $param_list = array_keys($param[
'options']);
9164 $InfoFieldList = explode(
":", $param_list[0]);
9166 $selectkey =
"rowid";
9169 if (count($InfoFieldList) >= 3) {
9170 $selectkey = $InfoFieldList[2];
9171 $keyList = $InfoFieldList[2].
' as rowid';
9174 $fields_label = explode(
'|', $InfoFieldList[1]);
9175 if (is_array($fields_label)) {
9177 $keyList .= implode(
', ', $fields_label);
9180 $filter_categorie =
false;
9181 if (count($InfoFieldList) > 5) {
9182 if ($InfoFieldList[0] ==
'categorie') {
9183 $filter_categorie =
true;
9187 $sql =
"SELECT ".$this->db->sanitize($keyList, 0, 0, 1);
9188 $sql .=
' FROM '.$this->db->prefix().$this->db->sanitize($InfoFieldList[0]);
9189 if (isset($InfoFieldList[4]) && strpos($InfoFieldList[4],
'extra') !==
false) {
9195 dol_syslog(get_class($this).
':showOutputField:$type=chkbxlst', LOG_DEBUG);
9196 $resql = $this->db->query($sql);
9198 if (!$filter_categorie) {
9201 while ($obj = $this->db->fetch_object($resql)) {
9203 $fields_label = explode(
'|', $InfoFieldList[1]);
9204 if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
9205 if (is_array($fields_label) && count($fields_label) > 1) {
9206 foreach ($fields_label as $field_toshow) {
9208 if (!empty($obj->$field_toshow)) {
9209 $translabel = $langs->trans($obj->$field_toshow);
9211 if ($translabel != $field_toshow) {
9212 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' .
dol_trunc($translabel, 18) .
'</li>';
9214 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' . $obj->$field_toshow .
'</li>';
9219 if (!empty($obj->{$InfoFieldList[1]})) {
9220 $translabel = $langs->trans($obj->{$InfoFieldList[1]});
9222 if ($translabel != $obj->{$InfoFieldList[1]}) {
9223 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' .
dol_trunc($translabel, 18) .
'</li>';
9225 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' . $obj->{$InfoFieldList[1]} .
'</li>';
9231 require_once DOL_DOCUMENT_ROOT .
'/categories/class/categorie.class.php';
9234 while ($obj = $this->db->fetch_object($resql)) {
9235 if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
9237 $c->fetch($obj->rowid);
9238 $ways =
$c->print_all_ways();
9239 foreach ($ways as $way) {
9240 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories"' . (
$c->color ?
' style="background: #' .
$c->color .
';"' :
' style="background: #aaa"') .
'>' .
img_object(
'',
'category') .
' ' . $way .
'</li>';
9245 $value =
'<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(
' ', $toprint).
'</ul></div>';
9247 dol_syslog(get_class($this).
'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
9249 } elseif ($type ==
'link') {
9254 $param_list = array_keys($param[
'options']);
9258 $InfoFieldList = explode(
":", $param_list[0]);
9260 $classname = $InfoFieldList[0];
9261 $classpath = $InfoFieldList[1];
9264 $getnomurlparam = 3;
9265 $getnomurlparam2 =
'';
9267 if (preg_match(
'/#getnomurlparam1=([^#]*)/', $param_list[0], $regtmp)) {
9268 $getnomurlparam = $regtmp[1];
9270 if (preg_match(
'/#getnomurlparam2=([^#]*)/', $param_list[0], $regtmp)) {
9271 $getnomurlparam2 = $regtmp[1];
9274 if (!empty($classpath)) {
9277 if ($classname && !class_exists($classname)) {
9281 if ($element_prop) {
9282 $classname = $element_prop[
'classname'];
9287 if ($classname && class_exists($classname)) {
9288 $object =
new $classname($this->db);
9289 '@phan-var-force CommonObject $object';
9290 if (
$object->element ===
'product') {
9291 '@phan-var-force Product $object';
9292 $result =
$object->fetch((
int) $value,
'',
'',
'', 0, 1, 1);
9294 $result =
$object->fetch($value);
9297 if (
$object->element ===
'product') {
9298 '@phan-var-force Product $object';
9299 $get_name_url_param_arr = array($getnomurlparam, $getnomurlparam2, 0, -1, 0,
'', 0);
9300 if (isset($val[
'get_name_url_params'])) {
9301 $get_name_url_params = explode(
':', $val[
'get_name_url_params']);
9302 if (!empty($get_name_url_params)) {
9303 $param_num_max = count($get_name_url_param_arr) - 1;
9304 foreach ($get_name_url_params as $param_num => $param_value) {
9305 if ($param_num > $param_num_max) {
9308 $get_name_url_param_arr[$param_num] = $param_value;
9316 $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]);
9318 $value =
$object->getNomUrl($getnomurlparam, $getnomurlparam2);
9325 dol_syslog(
'Error bad setup of extrafield', LOG_WARNING);
9326 return 'Error bad setup of extrafield';
9331 } elseif ($type ==
'password') {
9332 $value =
'<span class="opacitymedium">'.$langs->trans(
"Encrypted").
'</span>';
9334 } elseif ($type ==
'array') {
9335 if (is_array($value)) {
9336 $value = implode(
'<br>', $value);
9338 dol_syslog(__METHOD__.
' Expected array from dol_eval, but got '.gettype($value), LOG_ERR);
9339 return 'Error unexpected result from code evaluation';
9342 if (!empty($value) && preg_match(
'/^text/', (
string) $type) && !preg_match(
'/search_/', $keyprefix) && !empty($param[
'options'])) {
9343 $value = str_replace(
',',
"\n", $value);
9351 return is_null($out) ?
'' : $out;
9363 unset($this->validateFieldsErrors[$fieldKey]);
9377 $msg = $langs->trans(
"UnknownError");
9380 $this->error = $this->validateFieldsErrors[$fieldKey] = $msg;
9391 if (!empty($this->validateFieldsErrors[$fieldKey])) {
9392 return $this->validateFieldsErrors[$fieldKey];
9409 if (!class_exists(
'Validate')) {
9410 require_once DOL_DOCUMENT_ROOT .
'/core/class/validate.class.php';
9413 $this->clearFieldError($fieldKey);
9415 if (!array_key_exists($fieldKey, $fields) || !is_array($fields[$fieldKey])) {
9416 $this->setFieldError($fieldKey, $langs->trans(
'FieldNotFoundInObject'));
9420 $val = $fields[$fieldKey];
9423 $param[
'options'] = array();
9424 $type = $val[
'type'];
9427 if (isset($val[
'notnull']) && $val[
'notnull'] === 1) {
9441 if (preg_match(
'/varchar\((\d+)\)/', $type, $reg)) {
9443 $maxSize = (int) $reg[1];
9444 } elseif (preg_match(
'/varchar/', $type)) {
9448 if (!empty($val[
'arrayofkeyval']) && is_array($val[
'arrayofkeyval'])) {
9452 if (!empty($val[
'type']) && preg_match(
'/^integer:(.*):(.*)/i', $val[
'type'], $reg)) {
9456 if (!empty($val[
'arrayofkeyval']) && is_array($val[
'arrayofkeyval'])) {
9457 $param[
'options'] = $val[
'arrayofkeyval'];
9460 if (preg_match(
'/^integer:(.*):(.*)/i', $val[
'type'], $reg)) {
9462 $param[
'options'] = array($reg[1].
':'.$reg[2] => $reg[1].
':'.$reg[2]);
9463 } elseif (preg_match(
'/^sellist:(.*):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
9464 $param[
'options'] = array($reg[1].
':'.$reg[2].
':'.$reg[3].
':'.$reg[4] =>
'N');
9466 } elseif (preg_match(
'/^sellist:(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
9467 $param[
'options'] = array($reg[1].
':'.$reg[2].
':'.$reg[3] =>
'N');
9469 } elseif (preg_match(
'/^sellist:(.*):(.*)/i', $val[
'type'], $reg)) {
9470 $param[
'options'] = array($reg[1].
':'.$reg[2] =>
'N');
9479 $validate =
new Validate($this->db, $langs);
9489 if ($required && !$validate->isNotEmptyString($fieldValue)) {
9490 $this->setFieldError($fieldKey, $validate->error);
9492 } elseif (!$required && !$validate->isNotEmptyString($fieldValue)) {
9498 if (!empty($maxSize) && !$validate->isMaxLength($fieldValue, $maxSize)) {
9499 $this->setFieldError($fieldKey, $validate->error);
9504 if (!empty($minSize) && !$validate->isMinLength($fieldValue, $minSize)) {
9505 $this->setFieldError($fieldKey, $validate->error);
9513 if (in_array($type, array(
'date',
'datetime',
'timestamp'))) {
9514 if (!$validate->isTimestamp($fieldValue)) {
9515 $this->setFieldError($fieldKey, $validate->error);
9520 } elseif ($type ==
'duration') {
9521 if (!$validate->isDuration($fieldValue)) {
9522 $this->setFieldError($fieldKey, $validate->error);
9527 } elseif (in_array($type, array(
'double',
'real',
'price'))) {
9529 if (!$validate->isNumeric($fieldValue)) {
9530 $this->setFieldError($fieldKey, $validate->error);
9535 } elseif ($type ==
'boolean') {
9536 if (!$validate->isBool($fieldValue)) {
9537 $this->setFieldError($fieldKey, $validate->error);
9542 } elseif ($type ==
'mail' || $type ==
'email') {
9543 if (!$validate->isEmail($fieldValue)) {
9544 $this->setFieldError($fieldKey, $validate->error);
9547 } elseif ($type ==
'url') {
9548 if (!$validate->isUrl($fieldValue)) {
9549 $this->setFieldError($fieldKey, $validate->error);
9554 } elseif ($type ==
'phone') {
9555 if (!$validate->isPhone($fieldValue)) {
9556 $this->setFieldError($fieldKey, $validate->error);
9561 } elseif ($type ==
'select' || $type ==
'radio') {
9562 if (!isset($param[
'options'][$fieldValue])) {
9563 $this->error = $langs->trans(
'RequireValidValue');
9568 } elseif ($type ==
'sellist' || $type ==
'chkbxlst') {
9569 $param_list = array_keys($param[
'options']);
9570 $InfoFieldList = explode(
":", $param_list[0]);
9571 $value_arr = explode(
',', $fieldValue);
9573 $selectkey =
"rowid";
9574 if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
9575 $selectkey = $InfoFieldList[2];
9578 if (!$validate->isInDb($value_arr, $InfoFieldList[0], $selectkey)) {
9579 $this->setFieldError($fieldKey, $validate->error);
9584 } elseif ($type ==
'link') {
9585 $param_list = array_keys($param[
'options']);
9586 $InfoFieldList = explode(
":", $param_list[0]);
9587 $classname = $InfoFieldList[0];
9588 $classpath = $InfoFieldList[1];
9589 if (!$validate->isFetchable((
int) $fieldValue, $classname, $classpath)) {
9590 $lastIsFetchableError = $validate->error;
9593 if ($validate->isFetchableElement((
int) $fieldValue, $classname)) {
9597 $this->setFieldError($fieldKey, $lastIsFetchableError);
9621 public function showOptionals($extrafields, $mode =
'view', $params =
null, $keysuffix =
'', $keyprefix =
'', $onetrtd =
'', $display_type =
'card')
9623 global
$db,
$conf, $langs, $action, $form, $hookmanager;
9624 global $objectoffield;
9626 if (!is_object($form)) {
9629 if (!is_object($extrafields)) {
9630 dol_syslog(
'Bad parameter extrafields for showOptionals', LOG_ERR);
9631 return 'Bad parameter extrafields for showOptionals';
9633 if (!is_array($extrafields->attributes[$this->table_element])) {
9634 dol_syslog(
"extrafields->attributes was not loaded with extrafields->fetch_name_optionals_label(table_element);", LOG_WARNING);
9638 $objectoffield = $this;
9642 $parameters = array(
'mode' => $mode,
'params' => $params,
'keysuffix' => $keysuffix,
'keyprefix' => $keyprefix,
'display_type' => $display_type);
9643 $reshook = $hookmanager->executeHooks(
'showOptionals', $parameters, $this, $action);
9644 $hookResPrint = $hookmanager->resPrint;
9646 if (empty($reshook)) {
9647 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) {
9649 $out .=
'<!-- commonobject:showOptionals --> ';
9652 $nbofextrafieldsshown = 0;
9655 $lastseparatorkeyfound =
'';
9656 $extrafields_collapse_num =
'';
9657 $extrafields_collapse_num_old =
'';
9660 foreach ($extrafields->attributes[$this->table_element][
'label'] as $key => $label) {
9664 if (is_array($params) && array_key_exists(
'onlykey', $params) && $key != $params[
'onlykey']) {
9670 if ($enabled && isset($extrafields->attributes[$this->table_element][
'enabled'][$key])) {
9671 $enabled = (int)
dol_eval((
string) $extrafields->attributes[$this->table_element][
'enabled'][$key], 1, 1,
'2');
9673 if (empty($enabled)) {
9678 if (isset($extrafields->attributes[$this->table_element][
'list'][$key])) {
9679 $visibility = (int)
dol_eval((
string) $extrafields->attributes[$this->table_element][
'list'][$key], 1, 1,
'2');
9683 if ($perms && isset($extrafields->attributes[$this->table_element][
'perms'][$key])) {
9684 $perms = (int)
dol_eval((
string) $extrafields->attributes[$this->table_element][
'perms'][$key], 1, 1,
'2');
9687 if (($mode ==
'create') && !in_array(abs($visibility), array(1, 3))) {
9689 } elseif (($mode ==
'edit') && !in_array(abs($visibility), array(1, 3, 4))) {
9693 $ef_name =
'options_' . $key;
9694 $ef_value = $this->array_options[$ef_name] ??
'';
9695 $out .=
'<input type="hidden" name="' . $ef_name .
'" id="' . $ef_name .
'" value="' .
dolPrintHTMLForAttribute($ef_value) .
'" />' .
"\n";
9697 } elseif ($mode ==
'view' && empty($visibility)) {
9700 if (empty($perms)) {
9705 if (!empty($extrafields->attributes[$this->table_element][
'langfile'][$key])) {
9706 $langs->load($extrafields->attributes[$this->table_element][
'langfile'][$key]);
9711 if (is_array($params) && count($params) > 0 && $display_type ==
'card') {
9712 if (array_key_exists(
'cols', $params)) {
9713 $colspan = $params[
'cols'];
9714 } elseif (array_key_exists(
'colspan', $params)) {
9716 if (preg_match(
'/colspan="(\d+)"/', $params[
'colspan'], $reg)) {
9719 $colspan = $params[
'colspan'];
9723 $colspan = intval($colspan);
9727 $value = ((!empty($this->array_options) && array_key_exists(
"options_".$key.$keysuffix, $this->array_options)) ? $this->array_options[
"options_".$key.$keysuffix] :
null);
9733 $check =
'alphanohtml';
9734 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'html',
'text'))) {
9735 $check =
'restricthtml';
9737 $getposttemp =
GETPOST($keyprefix.
'options_'.$key.$keysuffix, $check, 3);
9739 if (is_array($getposttemp) || $getposttemp !=
'' || GETPOSTISSET($keyprefix.
'options_'.$key.$keysuffix)) {
9740 if (is_array($getposttemp)) {
9742 $value = implode(
",", $getposttemp);
9744 $value = $getposttemp;
9746 } elseif (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'int'))) {
9747 $value = (!empty($this->array_options[
"options_".$key]) || (isset($this->array_options[
"options_".$key]) && $this->array_options[
"options_".$key] ===
'0')) ? $this->array_options[
"options_".$key] :
'';
9748 } elseif (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'varchar',
'char'))) {
9749 $value = (isset($this->array_options[
"options_".$key]) && $this->array_options[
"options_".$key] !==
'') ? $this->array_options[
"options_".$key] :
'';
9751 $value = (!empty($this->array_options[
"options_".$key]) ? $this->array_options[
"options_".$key] :
'');
9757 $nbofextrafieldsshown++;
9760 if ($extrafields->attributes[$this->table_element][
'type'][$key] ==
'separate') {
9761 $extrafields_collapse_num = $key;
9779 $out .= $extrafields->showSeparator($key, $this, ($colspan ? $colspan + 1 : 2), $display_type, $mode);
9781 $lastseparatorkeyfound = $key;
9783 $collapse_group = $extrafields_collapse_num.(!empty($this->
id) ?
'_'.$this->id :
'');
9785 $class = (!empty($extrafields->attributes[$this->table_element][
'hidden'][$key]) ?
'hideobject ' :
'');
9787 if (is_array($params) && count($params) > 0) {
9788 if (array_key_exists(
'class', $params)) {
9789 $class .= $params[
'class'].
' ';
9791 if (array_key_exists(
'style', $params)) {
9792 $csstyle = $params[
'style'];
9797 $domData =
' data-element="extrafield"';
9798 $domData .=
' data-targetelement="'.$this->element.
'"';
9799 $domData .=
' data-targetid="'.$this->id.
'"';
9801 $html_id = (empty($this->
id) ?
'' :
'extrarow-'.$this->element.
'_'.$key.
'_'.
$this->id);
9802 if ($display_type ==
'card') {
9807 if ($action ==
'selectlines') {
9814 $force_values_on_change_company = (
9815 ($this->element ==
'facture' &&
getDolGlobalInt(
'THIRDPARTY_PROPAGATE_EXTRAFIELDS_TO_INVOICE'))
9816 || ($this->element ==
'commande' &&
getDolGlobalInt(
'THIRDPARTY_PROPAGATE_EXTRAFIELDS_TO_ORDER'))
9817 || ($this->element ==
'order_supplier' &&
getDolGlobalInt(
'THIRDPARTY_PROPAGATE_EXTRAFIELDS_TO_SUPPLIER_ORDER'))
9819 if ($force_values_on_change_company &&
GETPOSTINT(
'changecompany')) {
9820 $value = $this->array_options[
'options_'.$key] ?? $value;
9824 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'date'))) {
9825 $datenotinstring =
null;
9826 if (array_key_exists(
'options_'.$key, $this->array_options)) {
9827 $datenotinstring = $this->array_options[
'options_'.$key];
9828 if (!is_numeric($this->array_options[
'options_'.$key])) {
9829 $datenotinstring = $this->db->jdate($datenotinstring);
9832 $datekey = $keyprefix.
'options_'.$key.$keysuffix;
9835 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'datetime'))) {
9836 $datenotinstring =
null;
9837 if (array_key_exists(
'options_'.$key, $this->array_options)) {
9838 $datenotinstring = $this->array_options[
'options_'.$key];
9839 if (!is_numeric($this->array_options[
'options_'.$key])) {
9840 $datenotinstring = $this->db->jdate($datenotinstring);
9843 $timekey = $keyprefix.
'options_'.$key.$keysuffix;
9844 $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;
9847 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'price',
'double'))) {
9848 if (GETPOSTISSET($keyprefix.
'options_'.$key.$keysuffix) || $value) {
9850 } elseif (isset($this->array_options[
'options_'.$key])) {
9851 $value = $this->array_options[
'options_'.$key];
9856 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'html',
'text',
'varchar',
'select',
'radio',
'int',
'boolean'))) {
9857 if ($action ==
'create' || $mode ==
'create') {
9858 $value = (GETPOSTISSET($keyprefix.
'options_'.$key.$keysuffix) || $value) ? $value : $extrafields->attributes[$this->table_element][
'default'][$key];
9862 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'checkbox'))) {
9863 if ($action ==
'create') {
9864 $value = (GETPOSTISSET($keyprefix.
'options_'.$key.$keysuffix) || $value) ? $value : explode(
',', $extrafields->attributes[$this->table_element][
'default'][$key]);
9869 $labeltoshow = $langs->trans($label);
9870 $helptoshow = $langs->trans($extrafields->attributes[$this->table_element][
'help'][$key]);
9871 if ($display_type ==
'card') {
9872 $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.
' >';
9873 if (
getDolGlobalString(
'MAIN_VIEW_LINE_NUMBER') && ($action ==
'view' || $action ==
'valid' || $action ==
'editline' || $action ==
'confirm_valid' || $action ==
'confirm_cancel')) {
9874 $out .=
'<td></td>';
9876 $out .=
'<td class="'.(empty($params[
'tdclass']) ?
'titlefieldmax45' : $params[
'tdclass']).
' wordbreak';
9877 if ($extrafields->attributes[$this->table_element][
'type'][$key] ==
'text') {
9880 } elseif ($display_type ==
'line') {
9881 $out .=
'<div '.($html_id ?
'id="'.$html_id.
'" ' :
'').$csstyle.
' class="fieldline_options_'.$key.
' '.$class.$this->element.
'_extras_'.$key.
' trextrafields_collapse'.$collapse_group.
'" '.$domData.
' >';
9882 $out .=
'<div style="display: inline-block; padding-right:4px" class="wordbreak';
9887 $tpl_context = isset($params[
"tpl_context"]) ? $params[
"tpl_context"] :
"none";
9888 if ($tpl_context !=
"public") {
9889 if ($mode !=
'view' && !empty($extrafields->attributes[$this->table_element][
'required'][$key])) {
9890 $out .=
' fieldrequired';
9894 if ($tpl_context ==
"public") {
9895 if (!empty($extrafields->attributes[$this->table_element][
'help'][$key])) {
9896 $out .= $form->textwithpicto($labeltoshow, $helptoshow);
9898 $out .= $labeltoshow;
9900 if ($mode !=
'view' && !empty($extrafields->attributes[$this->table_element][
'required'][$key])) {
9901 $out .=
' <span style="color: red">*</span>';
9904 if (!empty($extrafields->attributes[$this->table_element][
'help'][$key])) {
9905 $out .= $form->textwithpicto($labeltoshow, $helptoshow);
9907 $out .= $labeltoshow;
9911 $out .= ($display_type ==
'card' ?
'</td>' :
'</div>');
9914 $html_id = !empty($this->
id) ? $this->element.
'_extras_'.$key.
'_'.$this->id :
'';
9915 if ($display_type ==
'card') {
9917 $out .=
'<td '.($html_id ?
'id="'.$html_id.
'" ' :
'').
' class="valuefieldcreate '.$this->element.
'_extras_'.$key;
9918 $out .=
'" '.($colspan ?
' colspan="'.$colspan.
'"' :
'');
9920 } elseif ($display_type ==
'line') {
9921 $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].
'">';
9926 $out .= $extrafields->showOutputField($key, $value,
'', $this->table_element);
9929 $listoftypestoshowpicto = explode(
',',
getDolGlobalString(
'MAIN_TYPES_TO_SHOW_PICTO',
'email,phone,ip,password'));
9930 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], $listoftypestoshowpicto)) {
9931 $out .=
getPictoForType($extrafields->attributes[$this->table_element][
'type'][$key], ($extrafields->attributes[$this->table_element][
'type'][$key] ==
'text' ?
'tdtop' :
''));
9934 $out .= $extrafields->showInputField($key, $value,
'', $keysuffix,
'',
'', $this, $this->table_element);
9937 $listoftypestoshowpicto = explode(
',',
getDolGlobalString(
'MAIN_TYPES_TO_SHOW_PICTO',
'email,phone,ip,password'));
9938 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], $listoftypestoshowpicto)) {
9939 $out .=
getPictoForType($extrafields->attributes[$this->table_element][
'type'][$key], ($extrafields->attributes[$this->table_element][
'type'][$key] ==
'text' ?
'tdtop' :
''));
9941 $out .= $extrafields->showInputField($key, $value,
'', $keysuffix,
'',
'', $this, $this->table_element);
9945 $out .= ($display_type ==
'card' ?
'</td>' :
'</div>');
9946 $out .= ($display_type ==
'card' ?
'</tr>'.
"\n" :
'</div>');
9952 if (!empty(
$conf->use_javascript_ajax)) {
9953 $out .= $this->getJSListDependancies();
9956 $out .=
'<!-- commonobject:showOptionals end --> '.
"\n";
9958 if (empty($nbofextrafieldsshown)) {
9964 $out .= $hookResPrint;
9976 <script nonce="'.getNonce().
'">
9977 jQuery(document).ready(function() {
9978 function showOptions'.$type.
'(child_list, parent_list, orig_select)
9980 var val = $("select[name=\""+parent_list+"\"]").val();
9981 var parentVal = parent_list + ":" + val;
9982 if(typeof val == "string"){
9984 var options = orig_select.find("option[parent=\""+parentVal+"\"]").clone();
9985 $("select[name=\""+child_list+"\"] option[parent]").remove();
9986 $("select[name=\""+child_list+"\"]").append(options);
9988 var options = orig_select.find("option[parent]").clone();
9989 $("select[name=\""+child_list+"\"] option[parent]").remove();
9990 $("select[name=\""+child_list+"\"]").append(options);
9992 } else if(val > 0) {
9993 var options = orig_select.find("option[parent=\""+parentVal+"\"]").clone();
9994 $("select[name=\""+child_list+"\"] option[parent]").remove();
9995 $("select[name=\""+child_list+"\"]").append(options);
9997 var options = orig_select.find("option[parent]").clone();
9998 $("select[name=\""+child_list+"\"] option[parent]").remove();
9999 $("select[name=\""+child_list+"\"]").append(options);
10002 function setListDependencies'.$type.
'() {
10003 jQuery("select option[parent]").parent().each(function() {
10004 var orig_select = {};
10005 var child_list = $(this).attr("name");
10006 orig_select[child_list] = $(this).clone();
10007 var parent = $(this).find("option[parent]:first").attr("parent");
10008 var infos = parent.split(":");
10009 var parent_list = infos[0];
10011 //Hide daughters lists
10012 if ($("#"+child_list).val() == 0 && $("#"+parent_list).val() == 0){
10013 $("#"+child_list).hide();
10014 //Show mother lists
10015 } else if ($("#"+parent_list).val() != 0){
10016 $("#"+parent_list).show();
10018 //Show the child list if the parent list value is selected
10019 $("select[name=\""+parent_list+"\"]").click(function() {
10020 if ($(this).val() != 0){
10021 $("#"+child_list).show()
10025 //When we change parent list
10026 $("select[name=\""+parent_list+"\"]").change(function() {
10027 showOptions'.$type.
'(child_list, parent_list, orig_select[child_list]);
10028 //Select the value 0 on child list after a change on the parent list
10029 $("#"+child_list).val(0).trigger("change");
10030 //Hide child lists if the parent value is set to 0
10031 if ($(this).val() == 0){
10032 $("#"+child_list).hide();
10038 setListDependencies'.$type.
'();
10053 $module = empty($this->module) ?
'' : $this->module;
10054 $element = $this->element;
10056 if ($element ==
'facturerec') {
10057 $element =
'facture';
10058 } elseif ($element ==
'invoice_supplier_rec') {
10059 return !$user->hasRight(
'fournisseur',
'facture') ? null : $user->hasRight(
'fournisseur',
'facture');
10060 } elseif ($module && $user->hasRight($module, $element)) {
10062 return $user->hasRight($module, $element);
10065 return isset($user->rights->$element) ? $user->rights->$element :
null;
10082 global $hookmanager;
10084 $parameters = array(
10085 'origin_id' => $origin_id,
10086 'dest_id' => $dest_id,
10087 'tables' => $tables,
10089 $reshook = $hookmanager->executeHooks(
'commonReplaceThirdparty', $parameters);
10092 } elseif ($reshook < 0) {
10093 return $ignoreerrors === 1;
10096 foreach ($tables as $table) {
10097 $sql =
'UPDATE '.$dbs->prefix().$table.
' SET fk_soc = '.((int) $dest_id).
' WHERE fk_soc = '.((int) $origin_id);
10099 if (!$dbs->
query($sql)) {
10100 if ($ignoreerrors) {
10125 foreach ($tables as $table) {
10126 $sql =
'UPDATE '.MAIN_DB_PREFIX.$table.
' SET fk_product = '.((int) $dest_id).
' WHERE fk_product = '.((int) $origin_id);
10128 if (!$dbs->
query($sql)) {
10129 if ($ignoreerrors) {
10156 global $hookmanager;
10160 if (!preg_match(
'/^[a-z0-9_]+$/', $fieldname)) {
10161 dol_syslog(__METHOD__.
' Refused an invalid column name: '.$fieldname, LOG_ERR);
10165 $parameters = array(
10166 'origin_id' => $origin_id,
10167 'dest_id' => $dest_id,
10168 'tables' => $tables,
10169 'fieldname' => $fieldname,
10171 $reshook = $hookmanager->executeHooks(
'commonReplaceContact', $parameters);
10172 if ($reshook > 0) {
10174 } elseif ($reshook < 0) {
10175 return $ignoreerrors === 1;
10178 foreach ($tables as $table) {
10179 if (!preg_match(
'/^[a-z0-9_]+$/', $table)) {
10180 dol_syslog(__METHOD__.
' Refused an invalid table name: '.$table, LOG_ERR);
10184 $sanitizedtable = $dbs->
sanitize($table);
10185 $sanitizedfieldname = $dbs->
sanitize($fieldname);
10187 $sql =
"UPDATE ".$dbs->prefix().$sanitizedtable;
10188 $sql .=
" SET ".$sanitizedfieldname.
" = ".((int) $dest_id);
10189 $sql .=
" WHERE ".$sanitizedfieldname.
" = ".((int) $origin_id);
10191 if (!$dbs->
query($sql)) {
10192 if ($ignoreerrors) {
10214 public function defineBuyPrice($unitPrice = 0.0, $discountPercent = 0.0, $fk_product = 0)
10220 if (($unitPrice > 0) && (isset(
$conf->global->ForceBuyingPriceIfNull) &&
getDolGlobalInt(
'ForceBuyingPriceIfNull') > 0)) {
10222 $buyPrice = $unitPrice * (1 - $discountPercent / 100);
10225 if (!empty($fk_product) && $fk_product > 0) {
10228 require_once DOL_DOCUMENT_ROOT.
'/product/class/product.class.php';
10229 $product =
new Product($this->db);
10230 $result = $product->fetch($fk_product);
10231 if ($result <= 0) {
10232 $this->errors[] =
'ErrorProductIdDoesNotExists';
10235 if ($product->cost_price > 0) {
10236 $buyPrice = $product->cost_price;
10237 } elseif ($product->pmp > 0) {
10238 $buyPrice = $product->pmp;
10241 require_once DOL_DOCUMENT_ROOT.
'/product/class/product.class.php';
10242 $product =
new Product($this->db);
10243 $result = $product->fetch($fk_product);
10244 if ($result <= 0) {
10245 $this->errors[] =
'ErrorProductIdDoesNotExists';
10248 if ($product->pmp > 0) {
10249 $buyPrice = $product->pmp;
10253 if (empty($buyPrice) && in_array(
getDolGlobalString(
'MARGIN_TYPE'), array(
'1',
'pmp',
'costprice'))) {
10254 require_once DOL_DOCUMENT_ROOT.
'/fourn/class/fournisseur.product.class.php';
10256 if (($result = $productFournisseur->find_min_price_product_fournisseur($fk_product)) > 0) {
10257 $buyPrice = $productFournisseur->fourn_unitprice;
10258 } elseif ($result < 0) {
10259 $this->errors[] = $productFournisseur->error;
10266 return (
float) $buyPrice;
10279 return array(
'dir' =>
'',
'file' =>
'',
'originalfile' =>
'',
'altfile' =>
'',
'email' =>
'',
'capture' =>
'');
10303 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')
10306 global $user, $langs;
10308 include_once DOL_DOCUMENT_ROOT.
'/core/lib/files.lib.php';
10309 include_once DOL_DOCUMENT_ROOT.
'/core/lib/images.lib.php';
10310 include_once DOL_DOCUMENT_ROOT.
'/core/class/link.class.php';
10312 $sortfield =
'position_name';
10313 $sortorder =
'asc';
10318 $dir .=
get_exdir(0, 0, 0, 0, $this, $modulepart);
10319 $pdir .=
get_exdir(0, 0, 0, 0, $this, $modulepart);
10322 if ($modulepart ==
'product') {
10324 $dir = $sdir.
'/'.
get_exdir($this->
id, 2, 0, 0, $this, $modulepart).$this->id.
"/photos/";
10325 $pdir =
'/'.get_exdir($this->
id, 2, 0, 0, $this, $modulepart).$this->id.
"/photos/";
10328 if ($modulepart ==
'category') {
10329 $dir = $sdir.
'/'.
get_exdir($this->
id, 2, 0, 0, $this, $modulepart).$this->id.
"/photos/";
10330 $pdir =
'/'.get_exdir($this->
id, 2, 0, 0, $this, $modulepart).$this->id.
"/photos/";
10336 $relativedir = preg_replace(
'/^'.preg_quote(DOL_DATA_ROOT,
'/').
'/',
'', $dir);
10337 $relativedir = preg_replace(
'/^[\\/]/',
'', $relativedir);
10338 $relativedir = preg_replace(
'/[\\/]$/',
'', $relativedir);
10341 $dirthumb = $dir.
'thumbs/';
10342 $pdirthumb = $pdir.
'thumbs/';
10344 $return =
'<!-- Photo -->'.
"\n";
10347 $filearray =
dol_dir_list($dir,
"files", 0,
'',
'(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) ==
'desc' ? SORT_DESC : SORT_ASC), 1);
10356 '@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';
10358 $useLinkPathPhoto =
false;
10361 $link =
new Link($this->db);
10363 $link->fetchAll($links,
'product', $this->
id);
10365 if (count($links) > 0) {
10366 $useLinkPathPhoto =
true;
10369 if ($useLinkPathPhoto) {
10371 if ($nbbyrow > 0) {
10372 $return .=
'<table class="valigntop center centpercent" style="border:0; padding:2px; border-spacing:2px; border-collapse: separate;">';
10376 foreach ($links as $link) {
10377 if (!empty($link->url) && preg_match(
'/\.(jpg|jpeg|png|gif|webp)$/i', $link->url)) {
10382 if ($nbbyrow > 0 && ($i % $nbbyrow == 1)) {
10383 $return .=
'<tr class="center valignmiddle">';
10386 if ($nbbyrow > 0) {
10387 $return .=
'<td style="width:'.ceil(100 / $nbbyrow).
'%" class="photo">';
10389 $return .=
'<div class="inline-block">';
10392 $return .=
'<img class="photo photowithmargin'.($addphotorefcss ?
' '.$addphotorefcss :
'').
'"'.($maxHeight ?
' height="'.$maxHeight.
'"' :
'').
' src="'.$url.
'" title="External image">';
10394 if ($nbbyrow > 0) {
10395 $return .=
'</td>';
10396 if ($i % $nbbyrow == 0) {
10397 $return .=
'</tr>';
10400 $return .=
'</div>';
10403 if ($nbmax && $nbphoto >= $nbmax) {
10409 if ($nbbyrow > 0) {
10410 while ($i % $nbbyrow) {
10411 $return .=
'<td style="width:'.ceil(100 / $nbbyrow).
'%"> </td>';
10415 $return .=
'</table>';
10421 if (count($filearray)) {
10422 if ($sortfield && $sortorder) {
10423 $filearray =
dol_sort_array($filearray, $sortfield, $sortorder);
10426 foreach ($filearray as $key => $val) {
10428 $file = $val[
'name'];
10434 $viewfilename = $file;
10436 if ($size == 1 || $size ==
'small') {
10442 $pdirthumb = $pdir;
10443 $photo_vignette = basename($file);
10449 if ($nbbyrow > 0) {
10450 if ($nbphoto == 1) {
10451 $return .=
'<table class="valigntop center centpercent" style="border: 0; padding: 2px; border-spacing: 2px; border-collapse: separate;">';
10454 if ($nbphoto % $nbbyrow == 1) {
10455 $return .=
'<tr class="center valignmiddle" style="border: 1px">';
10457 $return .=
'<td style="width: '.ceil(100 / $nbbyrow).
'%" class="photo">'.
"\n";
10458 } elseif ($nbbyrow < 0) {
10459 $return .=
'<div class="inline-block">'.
"\n";
10462 $relativefile = preg_replace(
'/^\//',
'', $pdir.$photo);
10463 if (empty($nolink)) {
10465 if ($urladvanced) {
10466 $return .=
'<a href="'.$urladvanced.
'">';
10468 $return .=
'<a href="'.DOL_URL_ROOT.
'/viewimage.php?modulepart='.$modulepart.
'&entity='.$this->entity.
'&file='.urlencode($pdir.$photo).
'" class="aphoto" target="_blank" rel="noopener noreferrer">';
10474 $alt = $langs->transnoentitiesnoconv(
'File').
': '.$relativefile;
10475 $alt .=
' - '.$langs->transnoentitiesnoconv(
'Size').
': '.$imgarray[
'width'].
'x'.$imgarray[
'height'];
10476 if ($overwritetitle) {
10477 if (is_numeric($overwritetitle)) {
10480 $alt = $overwritetitle;
10483 if (empty($cache) && !empty($val[
'label'])) {
10486 $cache = $val[
'label'];
10488 if ($usesharelink) {
10489 if (array_key_exists(
'share', $val) && $val[
'share']) {
10490 if (empty($maxHeight) || ($photo_vignette && $imgarray[
'height'] > $maxHeight)) {
10491 $return .=
'<!-- Show original file (thumb not yet available with shared links) -->';
10492 $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).
'">';
10494 $return .=
'<!-- Show original file -->';
10495 $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).
'">';
10498 $return .=
'<!-- Show nophoto file (because file is not shared) -->';
10499 $return .=
'<img class="photo photowithmargin'.($addphotorefcss ?
' '.$addphotorefcss :
'').
'" height="'.$maxHeight.
'" src="'.DOL_URL_ROOT.
'/public/theme/common/nophoto.png" title="'.
dol_escape_htmltag($alt).
'">';
10502 if (empty($maxHeight) || ($photo_vignette && $imgarray[
'height'] > $maxHeight)) {
10503 $return .=
'<!-- Show thumb -->';
10504 $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).
'">';
10506 $return .=
'<!-- Show original file -->';
10507 $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).
'">';
10511 if (empty($nolink)) {
10515 if ($showfilename) {
10516 $return .=
'<br>'.$viewfilename;
10521 if ($photo_vignette && (
image_format_supported($photo) > 0) && ((isset($imgarray[
'width']) && $imgarray[
'width'] > $maxWidth) || (isset($imgarray[
'width']) && $imgarray[
'width'] > $maxHeight))) {
10522 $return .=
'<a href="'.$_SERVER[
"PHP_SELF"].
'?id='.$this->
id.
'&action=addthumb&token='.
newToken().
'&file='.urlencode($pdir.$viewfilename).
'">'.
img_picto($langs->trans(
'GenerateThumb'),
'refresh').
' </a>';
10525 if ($modulepart ==
'product' && ($user->hasRight(
'produit',
'creer') || $user->hasRight(
'service',
'creer'))) {
10527 $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> ';
10530 $return .=
'<a href="'.$_SERVER[
"PHP_SELF"].
'?id='.$this->
id.
'&action=delete&token='.
newToken().
'&file='.urlencode($pdir.$viewfilename).
'">';
10536 if ($nbbyrow > 0) {
10537 $return .=
'</td>';
10538 if (($nbphoto % $nbbyrow) == 0) {
10539 $return .=
'</tr>';
10541 } elseif ($nbbyrow < 0) {
10542 $return .=
'</div>'.
"\n";
10546 if (empty($size)) {
10547 $return .=
'<img class="photo photowithmargin" src="'.DOL_URL_ROOT.
'/viewimage.php?modulepart='.$modulepart.
'&entity='.$this->entity.
'&file='.urlencode($pdir.$photo).
'">';
10549 if ($showfilename) {
10550 $return .=
'<br>'.$viewfilename;
10554 if ($modulepart ==
'product' && ($user->hasRight(
'produit',
'creer') || $user->hasRight(
'service',
'creer'))) {
10556 $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> ';
10559 $return .=
'<a href="'.$_SERVER[
"PHP_SELF"].
'?id='.$this->
id.
'&action=delete&token='.
newToken().
'&file='.urlencode($pdir.$viewfilename).
'">';
10566 if ($nbmax && $nbphoto >= $nbmax) {
10572 if ($size == 1 || $size ==
'small') {
10573 if ($nbbyrow > 0) {
10575 while ($nbphoto % $nbbyrow) {
10576 $return .=
'<td style="width: '.ceil(100 / $nbbyrow).
'%"> </td>';
10581 $return .=
'</table>';
10587 $this->nbphoto = $nbphoto;
10601 if (is_array($info)) {
10602 if (isset($info[
'type']) && $info[
'type'] ==
'array') {
10619 if (isset($info[
'type']) && ($info[
'type'] ==
'date' || $info[
'type'] ==
'datetime' || $info[
'type'] ==
'timestamp')) {
10633 if (is_array($info)) {
10634 if (isset($info[
'type']) && ($info[
'type'] ==
'duration')) {
10652 if (is_array($info)) {
10653 if (isset($info[
'type']) && (preg_match(
'/^(?:tiny|small|medium|big)?int|int$/i', $info[
'type']))) {
10671 if (is_array($info)) {
10672 if (isset($info[
'type']) && (preg_match(
'/^(double|real|price)/i', $info[
'type']))) {
10689 if (is_array($info)) {
10690 if (isset($info[
'type']) && $info[
'type'] ==
'text') {
10707 if (is_array($info)) {
10708 if (array_key_exists(
'notnull', $info) && $info[
'notnull'] !=
'1') {
10725 if (is_array($info)) {
10726 if (array_key_exists(
'notnull', $info) && $info[
'notnull'] ==
'-1') {
10743 if (is_array($info)) {
10744 if (array_key_exists(
'index', $info) && $info[
'index'] ==
true) {
10767 $queryarray = array();
10768 foreach ($this->fields as $field => $info) {
10770 if ($this->isDate($info)) {
10771 if (empty($this->{$field})) {
10772 $queryarray[$field] =
null;
10774 $queryarray[$field] = $this->db->idate($this->{$field});
10776 } elseif ($this->isDuration($info)) {
10778 if ((isset($this->{$field}) && $this->{$field} !=
'') || !empty($info[
'notnull'])) {
10779 if (!isset($this->{$field})) {
10780 if (!empty($info[
'default'])) {
10781 $queryarray[$field] = $info[
'default'];
10783 $queryarray[$field] = 0;
10786 $queryarray[$field] = (int) $this->{$field};
10789 $queryarray[$field] =
null;
10791 } elseif ($this->isInt($info) || $this->isFloat($info)) {
10792 if ($field ==
'entity' && is_null($this->{$field})) {
10793 $queryarray[$field] = ((int)
$conf->entity);
10796 if ((isset($this->{$field}) && ((
string) $this->{$field}) !=
'') || !empty($info[
'notnull'])) {
10797 if (!isset($this->{$field})) {
10798 $queryarray[$field] = 0;
10799 } elseif ($this->isInt($info)) {
10800 $queryarray[$field] = (int) $this->{$field};
10801 } elseif ($this->isFloat($info)) {
10802 $queryarray[$field] = (float) $this->{$field};
10805 $queryarray[$field] =
null;
10811 $queryarray[$field] = $this->{$field};
10814 if (is_array($info) && array_key_exists(
'type', $info) && !empty($info[
'type']) && $info[
'type'] ==
'timestamp' && empty($queryarray[$field])) {
10815 unset($queryarray[$field]);
10817 if (!empty($info[
'notnull']) && $info[
'notnull'] == -1 && empty($queryarray[$field])) {
10818 $queryarray[$field] =
null;
10822 return $queryarray;
10835 foreach ($this->fields as $field => $info) {
10836 if ($this->isDate($info)) {
10837 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') {
10838 $this->$field =
'';
10840 $this->$field =
$db->jdate($obj->$field);
10842 } elseif ($this->isInt($info)) {
10843 if ($field ==
'rowid') {
10844 $this->
id = (int) $obj->$field;
10846 if ($this->isForcedToNullIfZero($info)) {
10847 if (empty($obj->$field)) {
10848 $this->$field =
null;
10850 $this->$field = (int) $obj->$field;
10853 if (isset($obj->$field) && (!is_null($obj->$field) || (array_key_exists(
'notnull', $info) && $info[
'notnull'] == 1))) {
10854 $this->$field = (int) $obj->$field;
10856 $this->$field =
null;
10860 } elseif ($this->isFloat($info)) {
10861 if ($this->isForcedToNullIfZero($info)) {
10862 if (empty($obj->$field)) {
10863 $this->$field =
null;
10865 $this->$field = (float) $obj->$field;
10868 if (isset($obj->$field) && (!is_null($obj->$field) || (array_key_exists(
'notnull', $info) && $info[
'notnull'] == 1))) {
10869 $this->$field = (float) $obj->$field;
10871 $this->$field =
null;
10875 $this->$field = isset($obj->$field) ? $obj->$field :
null;
10880 if (!isset($this->fields[
'ref']) && isset($this->
id)) {
10891 foreach ($this->fields as $field => $arr) {
10892 $this->$field =
null;
10905 $keys = array_keys($this->fields);
10906 if (!empty($alias)) {
10907 $keys_with_alias = array();
10908 foreach ($keys as $fieldname) {
10909 if (!empty($excludefields)) {
10910 if (in_array($fieldname, $excludefields)) {
10914 $keys_with_alias[] = $this->db->sanitize($alias .
'.' . $fieldname);
10916 return implode(
', ', $keys_with_alias);
10918 return implode(
', ', $keys);
10929 protected function quote($value, $fieldsentry)
10931 if (is_null($value)) {
10933 } elseif (preg_match(
'/^(int|double|real|price)/i', $fieldsentry[
'type'])) {
10935 } elseif (preg_match(
'/int$/i', $fieldsentry[
'type'])) {
10936 return (
int) $value;
10937 } elseif ($fieldsentry[
'type'] ==
'boolean') {
10944 return "'".$this->db->escape($value).
"'";
10961 dol_syslog(get_class($this).
"::createCommon create", LOG_DEBUG);
10967 $fieldvalues = $this->setSaveQuery();
10971 if (array_key_exists(
'date_creation', $fieldvalues) && empty($fieldvalues[
'date_creation'])) {
10972 $fieldvalues[
'date_creation'] = $this->db->idate($now);
10973 $this->date_creation = $this->db->idate($now);
10976 if (array_key_exists(
'fk_user_creat', $fieldvalues) && !($fieldvalues[
'fk_user_creat'] > 0)) {
10977 $fieldvalues[
'fk_user_creat'] = $user->id;
10978 $this->fk_user_creat = $user->id;
10980 if (array_key_exists(
'user_creation_id', $fieldvalues) && !($fieldvalues[
'user_creation_id'] > 0)) {
10981 $fieldvalues[
'user_creation_id'] = $user->id;
10982 $this->user_creation_id = $user->id;
10984 if (array_key_exists(
'pass_crypted', $fieldvalues) && property_exists($this,
'pass')) {
10986 $tmparray =
dol_hash($this->pass,
'0', 0, 1);
10987 $fieldvalues[
'pass_crypted'] = $tmparray[
'pass_encrypted'];
10988 if (array_key_exists(
'pass_encoding', $fieldvalues) && property_exists($this,
'pass_encoding')) {
10989 $fieldvalues[
'pass_encoding'] = $tmparray[
'pass_encoding'];
10992 if (array_key_exists(
'ref', $fieldvalues)) {
10995 if (
getDolGlobalString(
'MAIN_DISABLE_AUTO_UPDATE_OF_TMS_FIELDS') && array_key_exists(
'tms', $fieldvalues)) {
10996 $fieldvalues[
'tms'] = $this->db->idate($now);
10999 unset($fieldvalues[
'rowid']);
11001 $sanitized_keys = array();
11002 $sanitized_values = array();
11003 foreach ($fieldvalues as $k => $v) {
11004 $sanitized_keys[$k] = $k;
11005 $value = $this->fields[$k];
11007 $sanitized_values[$k] = $this->quote($v, $value);
11011 foreach ($sanitized_keys as $key) {
11012 if (!isset($this->fields[$key])) {
11015 $key_fields = $this->fields[$key];
11018 if (preg_match(
'/^integer:/i', $key_fields[
'type']) && $sanitized_values[$key] ==
'-1') {
11019 $sanitized_values[$key] =
'';
11021 if (!empty($key_fields[
'foreignkey']) && $sanitized_values[$key] ==
'-1') {
11022 $sanitized_values[$key] =
'';
11025 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']))) {
11028 if (empty($langs)) {
11029 require_once DOL_DOCUMENT_ROOT.
'/core/class/translate.class.php';
11031 $langs->setDefaultLang();
11032 $langs->load(
"errors");
11034 dol_syslog(
"Mandatory field '".$key.
"' is empty and required into ->fields definition of class");
11035 $this->errors[] = $langs->trans(
"ErrorFieldRequired", isset($key_fields[
'label']) ? $key_fields[
'label'] : $key);
11039 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'])) {
11040 $sanitized_values[$key] = $this->quote($key_fields[
'default'], $key_fields);
11044 if (isset($key_fields[
'type']) && preg_match(
'/^integer:/i', $key_fields[
'type']) && empty($sanitized_values[$key])) {
11045 if (isset($key_fields[
'default'])) {
11046 $sanitized_values[$key] = ((int) $key_fields[
'default']);
11048 $sanitized_values[$key] =
'null';
11051 if (!empty($key_fields[
'foreignkey']) && empty($sanitized_values[$key])) {
11052 $sanitized_values[$key] =
'null';
11060 $this->db->begin();
11063 $sql =
"INSERT INTO ".$this->db->prefix().$this->db->sanitize($this->table_element);
11064 $sql .=
" (".implode(
", ", $sanitized_keys).
')';
11065 $sql .=
" VALUES (".implode(
", ", $sanitized_values).
")";
11067 $res = $this->db->query($sql);
11070 if ($this->db->lasterrno() ==
'DB_ERROR_RECORD_ALREADY_EXISTS') {
11071 $this->errors[] =
"ErrorRefAlreadyExists";
11073 $this->errors[] = $this->db->lasterror();
11079 $this->
id = $this->db->last_insert_id($this->db->prefix().$this->table_element);
11085 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)') {
11086 $sql =
"UPDATE ".$this->db->prefix().$this->db->sanitize($this->table_element);
11087 $sql .=
" SET ref = '(PROV".((int) $this->
id).
")' WHERE (ref = '(PROV)' OR ref = '') AND rowid = ".((int) $this->
id);
11088 $resqlupdate = $this->db->query($sql);
11090 if ($resqlupdate ===
false) {
11092 $this->errors[] = $this->db->lasterror();
11094 $this->
ref =
'(PROV'.$this->id.
')';
11101 $result = $this->insertExtraFields();
11108 if (!empty($this->table_element_line) && !empty($this->fk_element) && !empty($this->lines)) {
11109 foreach ($this->lines as $line) {
11110 $keyforparent = $this->fk_element;
11115 if (!is_object($line)) {
11116 $line = (object) $line;
11120 if (method_exists($line,
'insert')) {
11121 $result = $line->insert($user, 1);
11122 } elseif (method_exists($line,
'create')) {
11123 $result = $line->create($user, 1);
11126 $this->error = $line->error;
11127 $this->db->rollback();
11134 if (!$error && !$notrigger) {
11136 $result = $this->call_trigger(strtoupper(get_class($this)).
'_CREATE', $user);
11145 $this->db->rollback();
11148 $this->db->commit();
11165 if (empty(
$id) && empty($ref) && empty($morewhere)) {
11169 $fieldlist = $this->getFieldList(
't');
11170 if (empty($fieldlist)) {
11174 $sql =
"SELECT ".$this->db->sanitize($fieldlist, 0, 0, 1);
11175 $sql .=
" FROM ".$this->db->prefix().$this->table_element.
' as t';
11178 $sql .=
' WHERE t.rowid = '.((int)
$id);
11179 } elseif (!empty($ref)) {
11180 $sql .=
" WHERE t.ref = '".$this->db->escape($ref).
"'";
11182 $sql .=
' WHERE 1 = 1';
11184 if (empty(
$id) && isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
11185 $sql .=
' AND t.entity IN ('.getEntity($this->element).
')';
11188 $sql .= $morewhere;
11190 $sql .=
' LIMIT 1';
11192 $res = $this->db->query($sql);
11194 $obj = $this->db->fetch_object($res);
11196 $this->setVarsFromFetchObj($obj);
11200 if (empty($noextrafields)) {
11201 $result = $this->fetch_optionals();
11203 $this->error = $this->db->lasterror();
11204 $this->errors[] = $this->error;
11214 $this->error = $this->db->lasterror();
11215 $this->errors[] = $this->error;
11229 $objectlineclassname = get_class($this).
'Line';
11230 if (!class_exists($objectlineclassname)) {
11231 $this->error =
'Error, class '.$objectlineclassname.
' not found during call of fetchLinesCommon';
11235 $objectline =
new $objectlineclassname($this->db);
11236 '@phan-var-force CommonObjectLine $objectline';
11238 $sql =
"SELECT ".$objectline->getFieldList(
'l');
11239 $sql .=
" FROM ".$this->db->prefix().$this->db->sanitize($objectline->table_element).
" as l";
11240 $sql .=
" WHERE l.fk_".$this->db->sanitize($this->element).
" = ".((int) $this->
id);
11242 $sql .= $morewhere;
11244 if (isset($objectline->fields[
'position'])) {
11245 $sql .= $this->db->order(
'position',
'ASC');
11248 $resql = $this->db->query($sql);
11250 $num_rows = $this->db->num_rows($resql);
11252 $this->lines = array();
11253 while ($i < $num_rows) {
11254 $obj = $this->db->fetch_object($resql);
11256 $newline =
new $objectlineclassname($this->db);
11257 '@phan-var-force CommonObjectLine $newline';
11258 $newline->setVarsFromFetchObj($obj);
11261 if (empty($noextrafields)) {
11262 $newline->fetch_optionals();
11265 $this->lines[] = $newline;
11272 $this->error = $this->db->lasterror();
11273 $this->errors[] = $this->error;
11287 dol_syslog(get_class($this).
"::updateCommon update", LOG_DEBUG);
11299 $fieldvalues = $this->setSaveQuery();
11303 if (array_key_exists(
'date_modification', $fieldvalues)) {
11304 $fieldvalues[
'date_modification'] = $this->db->idate($now);
11306 if (
getDolGlobalString(
'MAIN_DISABLE_AUTO_UPDATE_OF_TMS_FIELDS') && array_key_exists(
'tms', $fieldvalues)) {
11307 $fieldvalues[
'tms'] = $this->db->idate($now);
11309 if (array_key_exists(
'fk_user_modif', $fieldvalues)) {
11310 $fieldvalues[
'fk_user_modif'] = $user->id;
11312 if (array_key_exists(
'user_modification_id', $fieldvalues)) {
11313 $fieldvalues[
'user_modification_id'] = $user->id;
11316 if (array_key_exists(
'pass_crypted', $fieldvalues) && property_exists($this,
'pass') && !empty($this->pass)) {
11318 $tmparray =
dol_hash($this->pass,
'0', 0, 1);
11319 $fieldvalues[
'pass_crypted'] = $tmparray[
'pass_encrypted'];
11320 if (array_key_exists(
'pass_encoding', $fieldvalues) && property_exists($this,
'pass_encoding')) {
11321 $fieldvalues[
'pass_encoding'] = $tmparray[
'pass_encoding'];
11324 if (array_key_exists(
'ref', $fieldvalues)) {
11328 unset($fieldvalues[
'rowid']);
11333 $sanitized_tmp = array();
11334 foreach ($fieldvalues as $k => $v) {
11336 $value = $this->fields[$k];
11338 $values[$k] = $this->quote($v, $value);
11339 if ((!empty($value[
"type"]) && $value[
"type"] ==
"text") && !empty($value[
'arrayofkeyval']) && is_array($value[
'arrayofkeyval'])) {
11341 $v = preg_replace(
'/\s/',
',', $v);
11342 $v = preg_replace(
'/,+/',
',', $v);
11345 $sanitized_tmp[] = $this->db->sanitize($k).
'='.$this->quote($v, $this->fields[$k]);
11349 foreach ($keys as $key) {
11350 if (!empty($this->fields[$key][
'type']) && preg_match(
'/^integer:/i', $this->fields[$key][
'type']) && $values[$key] ==
'-1') {
11351 $values[$key] =
'';
11353 if (!empty($this->fields[$key][
'foreignkey']) && $values[$key] ==
'-1') {
11354 $values[$key] =
'';
11366 $sql =
"UPDATE ".$this->db->prefix().$this->db->sanitize($this->table_element);
11367 $sql.=
" SET ".implode(
', ', $sanitized_tmp);
11368 $sql.=
" WHERE rowid = ".((int) $this->
id);
11370 $this->db->begin();
11373 $res = $this->db->query($sql);
11376 $this->errors[] = $this->db->lasterror();
11382 $result = $this->insertExtraFields();
11389 if (!$error && !$notrigger) {
11391 $result = $this->call_trigger(strtoupper(get_class($this)).
'_MODIFY', $user);
11400 $this->db->rollback();
11403 $this->db->commit();
11418 dol_syslog(get_class($this).
"::deleteCommon delete", LOG_DEBUG);
11422 $this->db->begin();
11424 if ($forcechilddeletion) {
11425 foreach ($this->childtables as $table) {
11426 $sql =
"DELETE FROM ".$this->db->prefix().$this->db->sanitize($table);
11427 $sql .=
" WHERE ".$this->db->sanitize($this->fk_element).
" = ".((int) $this->
id);
11428 $resql = $this->db->query($sql);
11430 $this->error = $this->db->lasterror();
11431 $this->errors[] = $this->error;
11432 $this->db->rollback();
11436 } elseif (!empty($this->childtables)) {
11437 $objectisused = $this->isObjectUsed($this->
id);
11438 if (!empty($objectisused)) {
11439 dol_syslog(get_class($this).
"::deleteCommon Can't delete record as it has some child", LOG_WARNING);
11440 $this->error =
'ErrorRecordHasChildren';
11441 $this->errors[] = $this->error;
11442 $this->db->rollback();
11448 if (is_array($this->childtablesoncascade) && !empty($this->childtablesoncascade)) {
11449 foreach ($this->childtablesoncascade as $tabletodelete) {
11450 $deleteFromObject = explode(
':', $tabletodelete, 4);
11451 if (count($deleteFromObject) >= 2) {
11452 $className = str_replace(
'@',
'', $deleteFromObject[0]);
11453 $filePath = $deleteFromObject[1];
11454 $columnName = $deleteFromObject[2];
11456 if (!empty($deleteFromObject[3])) {
11457 $filter = $deleteFromObject[3];
11461 $childObject =
new $className($this->db);
11462 if (method_exists($childObject,
'deleteByParentField')) {
11463 '@phan-var-force CommonObject $childObject';
11464 $result = $childObject->deleteByParentField($this->
id, $columnName, $filter);
11467 $this->errors[] = $childObject->error;
11472 $this->errors[] =
"You defined a cascade delete on an object $className/$this->id but there is no method deleteByParentField for it";
11477 $this->errors[] =
'Cannot include child class file '.$filePath;
11482 $sql =
"DELETE FROM ".$this->db->prefix().$this->db->sanitize($tabletodelete).
" WHERE ".$this->db->sanitize($this->fk_element).
" = ".((int) $this->
id);
11484 $resql = $this->db->query($sql);
11487 $this->error = $this->db->lasterror();
11488 $this->errors[] = $this->error;
11498 $result = $this->call_trigger(strtoupper(get_class($this)).
'_DELETE', $user);
11508 $res = $this->deleteEcmFiles(1);
11517 require_once DOL_DOCUMENT_ROOT .
'/core/lib/files.lib.php';
11520 $this->errors[] =
'ErrorFailToDeleteDir';
11526 $res = $this->deleteObjectLinked();
11531 if (!$error && !empty($this->isextrafieldmanaged)) {
11532 $result = $this->deleteExtraFields();
11539 $sql =
"DELETE FROM ".$this->db->prefix().$this->db->sanitize($this->table_element);
11540 $sql .=
" WHERE rowid = ".((int) $this->
id);
11542 $resql = $this->db->query($sql);
11545 $this->errors[] = $this->db->lasterror();
11551 $this->db->rollback();
11554 $this->db->commit();
11579 if (!empty($parentId) && !empty($parentField)) {
11580 if (empty($this->table_element)) {
11581 $this->error =
'Property table_element for object is not defined';
11582 $this->errors[] = $this->error;
11586 if (!method_exists($this,
'fetch')) {
11587 $this->error =
'Method fetch for object is not defined';
11588 $this->errors[] = $this->error;
11592 if (!method_exists($this,
'delete')) {
11593 $this->error =
'Method delete for object is not defined';
11594 $this->errors[] = $this->error;
11599 $this->db->begin();
11601 $sql =
"SELECT rowid FROM ".$this->db->prefix().$this->db->sanitize($this->table_element);
11602 $sql .=
" WHERE ".$this->db->sanitize($parentField).
" = ".(int) $parentId;
11605 $errormessage =
'';
11607 if ($errormessage) {
11608 $this->errors[] = $errormessage;
11609 dol_syslog(__METHOD__.
' '.implode(
',', $this->errors), LOG_ERR);
11613 $resql = $this->db->query($sql);
11615 $this->errors[] = $this->db->lasterror();
11618 while ($obj = $this->db->fetch_object($resql)) {
11619 $result = $this->fetch($obj->rowid);
11622 $this->errors[] = $this->error;
11624 $result = $this->
delete($user);
11627 $this->errors[] = $this->error;
11635 if (empty($error)) {
11636 $this->db->commit();
11639 $this->error = implode(
', ', $this->errors);
11640 $this->db->rollback();
11641 return $error * -1;
11660 $tmpforobjectclass = get_class($this);
11661 $tmpforobjectlineclass = ucfirst($tmpforobjectclass).
'Line';
11663 $this->db->begin();
11666 $result = $this->call_trigger(
'LINE'.strtoupper($tmpforobjectclass).
'_DELETE', $user);
11672 if (empty($error)) {
11673 $sql =
"DELETE FROM ".$this->db->prefix().$this->db->sanitize($this->table_element_line);
11674 $sql .=
" WHERE rowid = ".((int) $idline);
11676 $resql = $this->db->query($sql);
11678 $this->error =
"Error ".$this->db->lasterror();
11683 if (empty($error)) {
11685 $tmpobjectline =
new $tmpforobjectlineclass($this->db);
11686 '@phan-var-force CommonObjectLine $tmpobjectline';
11687 if (!isset($tmpobjectline->isextrafieldmanaged) || !empty($tmpobjectline->isextrafieldmanaged)) {
11688 $tmpobjectline->id = $idline;
11689 $result = $tmpobjectline->deleteExtraFields();
11692 $this->error =
"Error ".get_class($this).
"::deleteLineCommon deleteExtraFields error -4 ".$tmpobjectline->error;
11697 if (empty($error)) {
11698 $this->db->commit();
11701 dol_syslog(get_class($this).
"::deleteLineCommon ERROR:".$this->error, LOG_ERR);
11702 $this->db->rollback();
11722 $this->db->begin();
11724 $statusfield =
'status';
11725 if (in_array($this->element, array(
'don',
'donation',
'shipping',
'project_task'))) {
11726 $statusfield =
'fk_statut';
11729 $sql =
"UPDATE ".$this->db->prefix().$this->db->sanitize($this->table_element);
11730 $sql .=
" SET ".$this->db->sanitize($statusfield).
" = ".((int) $status);
11731 $sql .=
" WHERE rowid = ".((int) $this->
id);
11733 if ($this->db->query($sql)) {
11735 $this->oldcopy = clone $this;
11738 if (!$error && !$notrigger) {
11740 $result = $this->call_trigger($triggercode, $user);
11747 $this->
status = $status;
11748 if (property_exists($this,
'statut')) {
11749 $this->statut = $status;
11751 $this->db->commit();
11754 $this->db->rollback();
11758 $this->error = $this->db->error();
11759 $this->db->rollback();
11775 $this->specimen = 1;
11777 'label' =>
'This is label',
11778 'ref' =>
'ABCD1234',
11779 'description' =>
'This is a description',
11781 'note_public' =>
'Public note',
11782 'note_private' =>
'Private note',
11783 'date_creation' => (
dol_now() - 3600 * 48),
11784 'date_modification' => (
dol_now() - 3600 * 24),
11785 'fk_user_creat' => $user->id,
11786 'fk_user_modif' => $user->id,
11789 foreach ($fields as $key => $value) {
11790 if (array_key_exists($key, $this->fields)) {
11791 $this->{$key} = $value;
11796 if (property_exists($this,
'fields')) {
11797 foreach ($this->fields as $key => $value) {
11799 if (array_key_exists($key, $fields)) {
11803 if (!empty($value[
'default'])) {
11804 $this->$key = $value[
'default'];
11822 require_once DOL_DOCUMENT_ROOT.
'/core/class/comment.class.php';
11824 $comment =
new Comment($this->db);
11825 $result = $comment->fetchAllFor($this->element, $this->
id);
11827 $this->setErrorsFromObject($comment);
11830 $this->comments = $comment->comments;
11832 return count($this->comments);
11842 return count($this->comments);
11853 if (!is_array($parameters)) {
11856 foreach ($parameters as $parameter) {
11857 if (isset($this->$parameter)) {
11858 $this->$parameter = trim($this->$parameter);
11877 require_once DOL_DOCUMENT_ROOT.
'/categories/class/categorie.class.php';
11881 $existing =
$c->containing($this->
id, $type_categ,
'id');
11901 if (!is_array($categories)) {
11902 $categories = array($categories);
11905 dol_syslog(get_class($this).
"::setCategoriesCommon Object Id:".$this->
id.
' type_categ:'.$type_categ.
' nb tag add:'.count($categories), LOG_DEBUG);
11907 require_once DOL_DOCUMENT_ROOT.
'/categories/class/categorie.class.php';
11909 if (empty($type_categ)) {
11910 dol_syslog(__METHOD__.
': Type '.$type_categ.
'is an unknown category type. Done nothing.', LOG_ERR);
11916 $existing =
$c->containing($this->
id, $type_categ,
'id');
11919 if (!is_array($existing)) {
11920 $existing = array();
11922 if ($remove_existing) {
11924 $to_del = array_diff($existing, $categories);
11925 $to_add = array_diff($categories, $existing);
11928 $to_add = array_diff($categories, $existing);
11935 foreach ($to_del as $del) {
11936 if (
$c->fetch($del) > 0) {
11937 $result =
$c->del_type($this, $type_categ);
11940 $this->error =
$c->error;
11941 $this->errors =
$c->errors;
11948 foreach ($to_add as $add) {
11949 if (
$c->fetch($add) > 0) {
11950 $result =
$c->add_type($this, $type_categ);
11953 $this->error =
$c->error;
11954 $this->errors =
$c->errors;
11962 return $error ? (-1 * $error) : $ok;
11975 $this->db->begin();
11977 if (empty($type)) {
11978 $type = $this->table_element;
11981 require_once DOL_DOCUMENT_ROOT.
'/categories/class/categorie.class.php';
11982 $categorystatic =
new Categorie($this->db);
11984 $tablename = $this->db->prefix().
"categorie_".(empty($categorystatic->MAP_CAT_TABLE[$type]) ? $type : $categorystatic->MAP_CAT_TABLE[$type]);
11985 $fkname =
'fk_' . (empty($categorystatic->MAP_CAT_FK[$type]) ? $type : $categorystatic->MAP_CAT_FK[$type]);
11987 $sql =
"INSERT INTO ".$this->db->sanitize($tablename).
" (fk_categorie, ".$this->db->sanitize($fkname).
")";
11988 $sql .=
" SELECT fk_categorie, ".((int) $toId).
" FROM ".$this->db->sanitize($tablename);
11989 $sql .=
" WHERE ".$this->db->sanitize($fkname).
" = ".((int) $fromId);
11991 if (!$this->db->query($sql)) {
11992 $this->error = $this->db->lasterror();
11993 $this->db->rollback();
11997 $this->db->commit();
12011 $this->db->begin();
12015 switch ($this->element) {
12017 $element =
'propale';
12020 $element =
'produit';
12022 case 'order_supplier':
12023 $element =
'fournisseur/commande';
12025 case 'invoice_supplier':
12028 $element =
'fournisseur/facture/'.get_exdir($this->
id, 2, 0, 1, $this,
'invoice_supplier');
12031 $element =
'expedition/sending';
12034 case 'project_task':
12035 require_once DOL_DOCUMENT_ROOT.
'/projet/class/task.class.php';
12037 $project_result = $this->fetchProject();
12038 if ($project_result >= 0) {
12039 $element =
'projet/'.dol_sanitizeFileName($this->project->ref).
'/';
12043 $element =
'contract';
12046 $element = $this->element;
12048 '@phan-var-force string $element';
12051 $sql =
"DELETE FROM ".$this->db->prefix().
"ecm_files_extrafields WHERE fk_object IN (";
12052 $sql .=
" SELECT rowid FROM ".$this->db->prefix().
"ecm_files WHERE filename LIKE '".$this->db->escape($this->
ref).
"%'";
12053 $sql .=
" AND filepath = '".$this->db->escape($element.
"/".$this->ref).
"' AND entity = ".((int)
$conf->entity);
12056 if (!$this->db->query($sql)) {
12057 $this->error = $this->db->lasterror();
12058 $this->db->rollback();
12063 $sql =
"DELETE FROM ".$this->db->prefix().
"ecm_files";
12064 $sql .=
" WHERE filename LIKE '".$this->db->escape($this->
ref).
"%'";
12065 $sql .=
" AND filepath = '".$this->db->escape($element.
"/".$this->ref).
"' AND entity = ".((int)
$conf->entity);
12067 if (!$this->db->query($sql)) {
12068 $this->error = $this->db->lasterror();
12069 $this->db->rollback();
12076 $sql =
'DELETE FROM '.$this->db->prefix().
"ecm_files_extrafields";
12077 $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).
")";
12078 $resql = $this->db->query($sql);
12080 $this->error = $this->db->lasterror();
12081 $this->db->rollback();
12085 $sql =
'DELETE FROM '.$this->db->prefix().
"ecm_files";
12086 $sql .=
" WHERE src_object_type = '".$this->db->escape($this->table_element.(empty($this->module) ?
"" :
"@".$this->module)).
"' AND src_object_id = ".((int) $this->
id);
12087 $resql = $this->db->query($sql);
12089 $this->error = $this->db->lasterror();
12090 $this->db->rollback();
12095 $this->db->commit();
12112 include_once DOL_DOCUMENT_ROOT.
'/product/class/product.class.php';
12115 $tmpproduct =
new Product($this->db);
12116 foreach ($this->lines as $line) {
12117 if ($line->fk_product > 0) {
12118 $tmpproduct->fetch($line->fk_product);
12119 $statustotest = ($status ==
'onsale' ?
'status' :
'status_buy');
12120 if (!$tmpproduct->$statustotest) {
12121 $langs->load(
'products');
12122 $statuskey4lang = ($status ==
'onsale' ?
'ProductStatusNotOnSell' :
'ProductStatusNotOnBuy');
12124 $this->errors[] = $langs->trans(
'ProductRef').
' '.$tmpproduct->ref.
' '.$langs->trans($statuskey4lang);
12130 $this->error =
'ErrorOneLineContainsADisactivatedProduct';
12146 $this->error = $message;
12147 $this->errors[] = $message;
12159 global $dolibarr_main_document_root;
12161 $this->setErrorWithoutLog($message);
12162 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
12163 $file = str_replace($dolibarr_main_document_root,
'', $trace[0][
'file'] ??
'file unknown');
12164 $line = $trace[0][
'line'] ??
'line unknown';
12165 $syslogMessage = sprintf(
'%s:%s %s', $file, $line, $message);
$id
Support class for third parties, contacts, members, users or resources.
if(! $sortfield) if(! $sortorder) $object
global $dolibarr_main_url_root
ajax_combobox($htmlname, $events=array(), $minLengthToAutocomplete=0, $forcefocus=0, $widthTypeOfAutocomplete='resolve', $idforemptyvalue='-1', $morecss='')
Convert a html select field into an ajax combobox.
Class to manage members of a foundation.
Class to manage categories.
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.
line_order($renum=false, $rowidorder='ASC', $fk_parent_line=true)
Save a new position (field rang) for details lines.
deleteLineCommon(User $user, $idline, $notrigger=0)
Delete a line of object in database.
isEmpty()
isEmpty We consider CommonObject isEmpty if this->id is empty
clearFieldError($fieldKey)
clear validation message result for a field
static getCountOfItemsLinkedByObjectID($fk_object_where, $field_where, $table_element)
Count items linked to an object id in association table.
deleteEcmFiles($mode=0)
Delete related files of object in database.
getLastMainDocLink($modulepart, $initsharekey=0, $relativelink=0)
Return the link of last main doc file for direct public download.
liste_type_contact($source='internal', $order='position', $option=0, $activeonly=0, $code='')
Return array with list of possible values for type of contacts.
getTooltipContent($params)
getTooltipContent
update_price($exclspec=0, $roundingadjust='auto', $nodatabaseupdate=0, $seller=null)
Update total_ht, total_ttc, total_vat, total_localtax1, total_localtax2 for an object (sum of lines).
swapContactStatus($rowid)
Update status of a contact linked to object.
getFieldError($fieldKey)
get field error message
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.
defineBuyPrice($unitPrice=0.0, $discountPercent=0.0, $fk_product=0)
Get buy price to use for margin calculation.
commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams=null)
Common function for all objects extending CommonObject for generating documents.
liste_contact($statusoflink=-1, $source='external', $list=0, $code='', $status=-1, $arrayoftcids=array())
Get array of all contacts for an object.
fetchObjectFrom($table, $field, $key, $element=null)
Load object from specific field.
fetchProject()
Load the project with id $this->fk_project into this->project.
fetch_thirdparty($force_thirdparty_id=0)
Load the third party of object, from id $this->socid or $this->fk_soc, into this->thirdparty.
static deleteAllItemsLinkedByObjectID($fk_object_where, $field_where, $table_element)
Function used to remove all items linked to an object id in association table.
setFieldError($fieldKey, $msg='')
set validation error message a field
validateField($fields, $fieldKey, $fieldValue)
Return validation test result for a field.
getDataToShowPhoto($modulepart, $imagesize)
Function used to get the logos or photos of an object.
setMulticurrencyCode($code)
Change the multicurrency code.
emtpyObjectVars()
Sets all object fields to null.
fetch_projet()
Load the project with id $this->fk_project into this->project.
getIdContact($source, $code, $status=0)
Return id of contacts for a source and a contact code.
setExtraField($key, $value)
Convenience method for setting the value of an extrafield without actually updating it in the databas...
setDocModel($user, $modelpdf)
Set last model used by doc generator.
deleteObjectLinked($sourceid=null, $sourcetype='', $targetid=null, $targettype='', $rowid=0, $f_user=null, $notrigger=0)
Delete all links between an object $this.
getExtraField($key)
Convenience method for retrieving the value of an extrafield without actually fetching it from the da...
updateExtraField($key, $trigger=null, $userused=null)
Update 1 extra field value for the current object.
setPaymentTerms($id, $deposit_percent=null)
Change the payments terms.
isFloat($info)
Function test if type is float.
setBankAccount($fk_account, $notrigger=0, $userused=null)
Change the bank account.
setExtraParameters()
Set extra parameters.
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)
getSpecialCode($lineid)
Get special code of a line.
clearObjectLinkedCache()
Clear the cache saying that all linked object were already loaded.
update_ref_ext($ref_ext)
Update external ref of element.
fetchOneLike($ref)
Looks for an object with ref matching the wildcard provided It does only work when $this->table_ref_f...
hasProductsOrServices($predefined=-1)
Function to say how many lines object contains.
static isExistingObject($element, $id, $ref='', $ref_ext='')
Check if an object id or ref exists If you don't need or want to instantiate the object and just need...
isObjectUsed($id=0, $entity=0)
Function to check if an object is used by others (by children).
updateRangOfLine($rowid, $rang)
Update position of line (rang)
getDefaultCreateValueFor($fieldname, $alternatevalue=null, $type='alphanohtml')
Return the default value to use for a field when showing the create form of object.
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...
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.
updateExtraLanguages($key, $trigger=null, $userused=null)
Update an extra language value for the current object.
deleteExtraFields()
Delete all extra fields values for the current object.
setStatusCommon($user, $status, $notrigger=0, $triggercode='')
Set to a status.
deprecatedProperties()
Provide list of deprecated properties and replacements.
setSaveQuery()
Function to return the array of data key-value from the ->fields and all the ->properties of an objec...
setValuesForExtraLanguages($onlykey='')
Fill array_options property of object by extrafields value (using for data sent by forms) 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).
delete_contact($rowid, $notrigger=0)
Delete a link to contact line.
updateLineUp($rowid, $rang)
Update position of line up (rang)
fetch_user($userid)
Load the user with id $userid into this->user.
errorsToString()
Method to output saved errors.
getListContactId($source='external')
Return list of id of contacts of object.
setWarehouse($warehouse_id)
Change the warehouse.
setDeliveryAddress($id)
Define delivery address.
fetchBarCode()
Load data for barcode into properties ->barcode_type* Properties ->barcode_type that is id of barcode...
getTotalDiscount()
Function that returns the total amount HT of discounts applied for all lines.
initAsSpecimenCommon()
Initialise object with example values Id must be 0 if object instance is a specimen.
printObjectLine($action, $line, $var, $num, $i, $dateSelector, $seller, $buyer, $selected=0, $extrafields=null, $defaulttpldir='/core/tpl')
Return HTML content of a detail line TODO Move this into an output class file (htmlline....
copy_linked_contact($objFrom, $source='internal')
Copy contact from one element to current.
static commonReplaceThirdparty(DoliDB $dbs, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
Function used to replace a thirdparty id with another one.
getValueFrom($table, $id, $field)
Getter generic.
trimParameters($parameters)
Trim object parameters.
fetch_product()
Load the product with id $this->fk_product into this->product.
isIndex($info)
Function test if is indexed.
quote($value, $fieldsentry)
Add quote to field value if necessary.
formAddObjectLine($dateSelector, $seller, $buyer, $defaulttpldir='/core/tpl')
Show add free and predefined products/services form.
fetchComments()
Load comments linked with current task.
line_down($rowid, $fk_parent_line=true)
Update a line to have a higher rank.
setValueFrom($field, $value, $table='', $id=null, $format='', $id_field='', $fuser=null, $trigkey='', $fk_user_field='fk_user_modif')
Setter generic.
fetch_contact($contactid=null)
Load object contact with id=$this->contact_id into $this->contact.
delThumbs($file)
Delete thumbs.
show_photos($modulepart, $sdir, $size=0, $nbmax=0, $nbbyrow=5, $showfilename=0, $showaction=0, $maxHeight=120, $maxWidth=160, $nolink=0, $overwritetitle=0, $usesharelink=0, $cache='', $addphotorefcss='photoref')
Show photos of an object (nbmax maximum), into several columns.
fetchLinesCommon($morewhere='', $noextrafields=0)
Load object in memory from the database.
static commonReplaceProduct(DoliDB $dbs, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
Function used to replace a product id with another one.
getRangOfLine($rowid)
Get position of line (rang)
showInputField($val, $key, $value, $moreparam='', $keysuffix='', $keyprefix='', $morecss=0, $nonewbutton=0)
Return HTML string to put an input field into a page Code very similar with showInputField of extra f...
update_contact($rowid, $statut, $type_contact_id=0, $fk_socpeople=0)
Update a link to contact line.
getElementType()
Return an element type string formatted like element_element target_type and source_type.
load_previous_next_ref($filter, $fieldid, $nodbprefix=0)
Load properties id_previous and id_next by comparing $fieldid with $this->ref.
setCategoriesCommon($categories, $type_categ='', $remove_existing=true)
Sets object to given categories.
fetchValuesForExtraLanguages()
Function to get alternative languages of a data into $this->array_languages This method is NOT called...
fetchNoCompute($id)
Function to make a fetch but set environment to avoid to load computed values before.
line_max($fk_parent_line=0)
Get max value used for position of line (rang)
getJSListDependancies($type='_extra')
setProject($projectid, $notrigger=0)
Link element with a project.
isForcedToNullIfZero($info)
Function test if field is forced to null if zero or empty.
line_ajaxorder($rows)
Update position of line with ajax (rang)
printOriginLinesList($restrictlist='', $selectedLines=array())
Return HTML table table of source object lines TODO Move this and previous function into output html ...
fetch_origin()
Read linked origin object.
getIdOfLine($rang)
Get rowid of the line relative to its position.
insertExtraFields($trigger='', $userused=null)
Add/Update all extra fields values for the current object.
deleteByParentField($parentId=0, $parentField='', $filter='', $filtermode="AND")
Delete all child object from a parent ID.
static getAllItemsLinkedByObjectID($fk_object_where, $field_select, $field_where, $table_element)
Function used to get an array with all items linked to an object id in association table.
__clone()
Overwrite magic function to solve problem of cloning object that are kept as references.
setPaymentMethods($id)
Change the payments methods.
updateLineDown($rowid, $rang, $max)
Update position of line down (rang)
delete_linked_contact($source='', $code='')
Delete all links between an object $this and all its contacts in llx_element_contact.
fetchCommon($id, $ref=null, $morewhere='', $noextrafields=0)
Load object in memory from the database.
deleteCommon(User $user, $notrigger=0, $forcechilddeletion=0)
Delete object in database.
getFormatedCustomerRef($objref)
Return customer ref for screen output.
getTooltipContentArray($params)
Return array of data to show into a tooltip.
isText($info)
Function test if type is text.
isDate($info)
Function test if type is date.
printOriginLine($line, $var, $restrictlist='', $defaulttpldir='/core/tpl', $selectedLines=array())
Return HTML with a line of table array of source object lines TODO Move this and previous function in...
showOptionals($extrafields, $mode='view', $params=null, $keysuffix='', $keyprefix='', $onetrtd='', $display_type='card')
Function to show lines of extrafields with output data.
getCanvas($id=0, $ref='')
Load type of canvas of an object if it exists.
line_up($rowid, $fk_parent_line=true)
Update a line to have a lower rank.
isDuration($info)
Function test if type is duration.
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...
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.
const TYPE_CREDIT_NOTE
Credit note invoice.
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 third parties objects (customers, suppliers, prospects...)
Class to manage translations.
Class to manage Dolibarr users.
Class toolbox to validate values.
print $langs trans("Ref").' m titre as m m statut as status
Or an array listing all the potential status of the object: array: int of the status => translated la...
getCountry($searchkey, $withcode='', $dbtouse=null, $outputlangs=null, $entconv=1, $searchlabel='')
Return country label, code or id from an id, code or label.
getState($id, $withcode='0', $dbtouse=null, $withregion=0, $outputlangs=null, $entconv=1)
Return state translated from an id.
convertSecondToTime($iSecond, $format='all', $lengthOfDay=86400, $lengthOfWeek=7)
Return, in clear text, value of a number of seconds in days, hours and minutes.
dol_meta_create($object)
Create a meta file with document file into same directory.
completeFileArrayWithDatabaseInfo(&$filearray, $relativedir, $object=null)
Complete $filearray with data from database.
dol_delete_file($file, $disableglob=0, $nophperrors=0, $nohook=0, $object=null, $allowdotdot=false, $indexdatabase=1, $nolog=0)
Remove a file or several files with a mask.
dol_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_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.
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.
price2num($amount, $rounding='', $option=0)
Function that return a number with universal decimal format (decimal separator is '.
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.
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.
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.
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='', $noduplicate=0, $attop=0)
Set event messages in dol_events session object.
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2, $allowothertags=array())
Show picto whatever it's its name (generic function)
img_delete($titlealt='default', $other='class="pictodelete"', $morecss='')
Show delete logo.
img_object($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $allowothertags=array())
Show a picto called object_picto (generic function)
getPictoForType($key, $morecss='')
Return the picto for a data type.
dolPrintHTMLForAttribute($s, $escapeonlyhtmltags=0, $allowothertags=array())
Return a string ready to be output into an HTML attribute (alt, title, data-html, ....
yn($yesno, $format=1, $color=0)
Return yes or no in current language.
getAdvancedPreviewUrl($modulepart, $relativepath, $alldata=0, $param='')
Return URL we can use for advanced preview links.
dol_print_error($db=null, $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $noescapetags='', $escapeonlyhtmltags=0, $cleanalsojavascript=0)
Returns text escaped for inclusion in HTML alt or title or value tags, or into values of HTML input f...
vignette($file, $maxWidth=160, $maxHeight=120, $extName='_small', $quality=50, $outdir='thumbs', $targetformat=0)
Create a thumbnail from an image file (Supported extensions are gif, jpg, png and bmp).
if(!defined( 'IMAGETYPE_WEBP')) getDefaultImageSizes()
Return default values for image sizes.
dol_getImageSize($file, $url=false)
Return size of image file on disk (Supported extensions are gif, jpg, png, bmp and webp)
image_format_supported($file, $acceptsvg=0)
Return if a filename is file name of a supported image format.
query($query, $usesavepoint=0, $type='auto', $result_mode=0)
Execute a SQL request and return the resultset.
print $langs trans("Show") . '< td style="' . $timeColor . '" align="center"> s</td > badge status0 badge status4 badge status3 Error badge status8< td align="center">< span class="badge ' . $badge . '"></span ></td >< td align="center">< a href="#" class="button button-small" onclick="openLogModal(this)" data-req="' . dol_escape_htmltag($reqSafe) . '" data-res="' . dol_escape_htmltag($resSafe) . '" data-err="' . dol_escape_htmltag($errSafe) . '">< span class="fa fa-search-plus"></span ></a ></td ></tr >< tr >< td colspan="' . $colspan . '" class="opacitymedium"></td ></tr ></table ></div ></form > logModal none logModal none s a JSON string
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.
if(preg_match('/(crypted|dolcrypt):/i', $dolibarr_main_db_pass)||!empty($dolibarr_main_db_encrypted_pass)) $conf db type
'integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter[:Sortfield]]]',...
getRandomPassword($generic=false, $replaceambiguouschars=null, $length=32)
Return a generated password using default module.
dol_hash($chain, $type='0', $nosalt=0, $mode=0)
Returns a hash (non reversible encryption) of a string.
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.