49require_once DOL_DOCUMENT_ROOT.
'/core/class/doldeprecationhandler.class.php';
50require_once DOL_DOCUMENT_ROOT.
'/core/class/commontrigger.class.php';
61 use DolDeprecationHandler;
98 public $errors = array();
109 public $warnings = array();
114 private $validateFieldsErrors = array();
132 public $element_for_permission;
137 public $table_element;
147 public $table_element_line =
'';
153 public $ismultientitymanaged;
163 public $array_options = array();
244 public $fields = array();
251 public $array_languages =
null;
256 public $contacts_ids;
261 public $contacts_ids_internal;
266 public $linked_objects;
271 public $other_linked_objects;
276 public $linkedObjectsIds;
281 public $linkedObjects;
286 private $linkedObjectsFullLoaded = array();
301 protected $table_ref_field =
'';
306 public $restrictiononfksoc = 0;
315 public $context = array();
432 private $commandeFournisseur;
448 public $ref_previous;
494 public $country_code;
537 public $barcode_type;
543 public $barcode_type_code;
549 public $barcode_type_label;
555 public $barcode_type_coder;
561 public $mode_reglement_id;
567 public $cond_reglement_id;
572 public $demand_reason_id;
578 public $transport_mode_id;
590 protected $depr_cond_reglement;
597 public $fk_delivery_address;
603 public $shipping_method_id;
609 public $shipping_method;
615 public $fk_multicurrency;
621 public $multicurrency_code;
627 public $multicurrency_tx;
632 public $multicurrency_total_ht;
637 public $multicurrency_total_tva;
642 public $multicurrency_total_localtax1;
647 public $multicurrency_total_localtax2;
652 public $multicurrency_total_ttc;
665 public $last_main_doc;
690 public $note_private;
715 public $total_localtax1;
721 public $total_localtax2;
738 public $actiontypecode;
744 public $comments = array();
770 public $civility_code;
776 public $date_creation;
781 public $date_validation;
786 public $date_modification;
800 private $date_update;
805 public $date_cloture;
810 public $user_creation_id;
815 public $user_validation_id;
820 public $user_closing_id;
825 public $user_modification_id;
831 public $fk_user_creat;
837 public $fk_user_modif;
843 public $next_prev_filter;
848 public $specimen = 0;
872 public $totalpaid_multicurrency;
878 public $labelStatus = array();
883 public $labelStatusShort = array();
894 public $showphoto_on_popup;
899 public $nb = array();
914 public $extraparams = array();
919 protected $childtables = array();
926 protected $childtablesoncascade = array();
931 public $cond_reglement_supplier_id;
938 public $deposit_percent;
944 public $warehouse_id;
949 public $isextrafieldmanaged = 0;
959 public $attachedfiles;
973 'alreadypaid' =>
'totalpaid',
974 'cond_reglement' =>
'depr_cond_reglement',
976 'commandeFournisseur' =>
'origin_object',
977 'expedition' =>
'origin_object',
978 'fk_project' =>
'fk_project',
979 'livraison' =>
'origin_object',
980 'projet' =>
'project',
981 'statut' =>
'status',
1000 $sql =
"SELECT rowid";
1001 $sql .=
" FROM ".$db->prefix().$element;
1002 $sql .=
" WHERE entity IN (".getEntity($element).
")";
1005 $sql .=
" AND rowid = ".((int) $id);
1007 $sql .=
" AND ref = '".$db->escape($ref).
"'";
1008 } elseif ($ref_ext) {
1009 $sql .=
" AND ref_ext = '".$db->escape($ref_ext).
"'";
1011 $error =
'ErrorWrongParameters';
1012 dol_syslog(get_class().
"::isExistingObject ".$error, LOG_ERR);
1015 if ($ref || $ref_ext) {
1016 $sql .=
" AND entity = ".((int)
$conf->entity);
1019 dol_syslog(get_class().
"::isExistingObject", LOG_DEBUG);
1020 $resql = $db->query($sql);
1022 $num = $db->num_rows($resql);
1041 $this->error =
$object->error;
1043 if (!empty(
$object->errors)) {
1044 $this->errors = array_merge($this->errors,
$object->errors);
1069 global $action, $extrafields, $langs, $hookmanager;
1072 $MAX_EXTRAFIELDS_TO_SHOW_IN_TOOLTIP =
getDolGlobalInt(
'MAX_EXTRAFIELDS_TO_SHOW_IN_TOOLTIP', 3);
1078 if (!empty($extrafields->attributes[$this->table_element][
'label'])) {
1079 $data[
'opendivextra'] =
'<div class="centpercent wordbreak divtooltipextra">';
1080 foreach ($extrafields->attributes[$this->table_element][
'label'] as $key => $val) {
1081 if ($extrafields->attributes[$this->table_element][
'type'][$key] ==
'separate') {
1085 if (empty($extrafields->attributes[$this->table_element][
'showintooltip'][$key])) {
1090 if ($count >= abs($MAX_EXTRAFIELDS_TO_SHOW_IN_TOOLTIP)) {
1091 $data[
'more_extrafields'] =
'<br>...';
1095 if ($enabled && isset($extrafields->attributes[$this->table_element][
'enabled'][$key])) {
1096 $enabled = (int)
dol_eval((
string) $extrafields->attributes[$this->table_element][
'enabled'][$key], 1, 1,
'2');
1098 if ($enabled && isset($extrafields->attributes[$this->table_element][
'list'][$key])) {
1099 $enabled = (int)
dol_eval((
string) $extrafields->attributes[$this->table_element][
'list'][$key], 1, 1,
'2');
1102 if ($perms && isset($extrafields->attributes[$this->table_element][
'perms'][$key])) {
1103 $perms = (int)
dol_eval((
string) $extrafields->attributes[$this->table_element][
'perms'][$key], 1, 1,
'2');
1105 if (empty($enabled)) {
1108 if (abs($enabled) != 1 && abs($enabled) != 3 && abs($enabled) != 5 && abs($enabled) != 4) {
1111 if (empty($perms)) {
1114 if (!empty($extrafields->attributes[$this->table_element][
'langfile'][$key])) {
1115 $langs->load($extrafields->attributes[$this->table_element][
'langfile'][$key]);
1117 $labelextra = $langs->trans((
string) $extrafields->attributes[$this->table_element][
'label'][$key]);
1118 if ($extrafields->attributes[$this->table_element][
'type'][$key] ==
'separate') {
1119 $data[$key] =
'<br><b><u>'. $labelextra .
'</u></b>';
1121 $value = (empty($this->array_options[
'options_' . $key]) ?
'' : $this->array_options[
'options_' . $key]);
1122 $data[$key] =
'<br><b>'. $labelextra .
':</b> ' . $extrafields->showOutputField($key, $value,
'', $this->table_element);
1126 $data[
'closedivextra'] =
'</div>';
1129 $hookmanager->initHooks(array($this->element .
'dao'));
1130 $parameters = array(
1131 'tooltipcontentarray' => &$data,
1132 'params' => $params,
1135 $hookmanager->executeHooks(
'getTooltipContent', $parameters, $this, $action);
1138 $label = implode($data);
1151 return $this->error.(is_array($this->errors) && count($this->errors) > 0 ? (($this->error !=
'' ?
', ' :
'').implode(
', ', $this->errors)) :
'');
1163 global $hookmanager;
1165 $parameters = array(
'objref' => $objref);
1167 $reshook = $hookmanager->executeHooks(
'getFormatedCustomerRef', $parameters, $this, $action);
1169 return $hookmanager->resArray[
'objref'];
1171 return $objref.(isset($hookmanager->resArray[
'objref']) ? $hookmanager->resArray[
'objref'] :
'');
1182 global $hookmanager;
1184 $parameters = array(
'objref' => $objref);
1186 $reshook = $hookmanager->executeHooks(
'getFormatedSupplierRef', $parameters, $this, $action);
1188 return $hookmanager->resArray[
'objref'];
1190 return $objref.(isset($hookmanager->resArray[
'objref']) ? $hookmanager->resArray[
'objref'] :
'');
1202 public function getFullAddress($withcountry = 0, $sep =
"\n", $withregion = 0, $extralangcode =
'')
1204 if ($withcountry && $this->country_id && (empty($this->country_code) || empty($this->country))) {
1205 require_once DOL_DOCUMENT_ROOT.
'/core/lib/company.lib.php';
1206 $tmparray =
getCountry($this->country_id,
'all');
1207 $this->country_code = $tmparray[
'code'];
1208 $this->country = $tmparray[
'label'];
1211 if ($withregion && $this->state_id && (empty($this->state_code) || empty($this->state) || empty($this->region) || empty($this->region_code))) {
1212 require_once DOL_DOCUMENT_ROOT.
'/core/lib/company.lib.php';
1213 $tmparray =
getState($this->state_id,
'all',
null, 1);
1214 $this->state_code = $tmparray[
'code'];
1215 $this->state = $tmparray[
'label'];
1216 $this->region_code = $tmparray[
'region_code'];
1217 $this->region = $tmparray[
'region'];
1236 if (empty($this->last_main_doc)) {
1240 include_once DOL_DOCUMENT_ROOT.
'/ecm/class/ecmfiles.class.php';
1241 $ecmfile =
new EcmFiles($this->db);
1242 $result = $ecmfile->fetch(0,
'', $this->last_main_doc);
1244 $this->error = $ecmfile->error;
1245 $this->errors = $ecmfile->errors;
1249 if (empty($ecmfile->id)) {
1251 if ($initsharekey) {
1252 require_once DOL_DOCUMENT_ROOT.
'/core/lib/security2.lib.php';
1274 } elseif (empty($ecmfile->share)) {
1276 if ($initsharekey) {
1277 require_once DOL_DOCUMENT_ROOT.
'/core/lib/security2.lib.php';
1279 $ecmfile->update($user);
1285 $urlwithouturlroot = preg_replace(
'/'.preg_quote(DOL_URL_ROOT,
'/').
'$/i',
'', trim(
$dolibarr_main_url_root));
1289 $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT;
1298 if (!empty($ecmfile->share)) {
1299 $paramlink .= ($paramlink ?
'&' :
'').
'hashp='.$ecmfile->share;
1301 if ($forcedownload) {
1302 $paramlink .= ($paramlink ?
'&' :
'').
'attachment=1';
1305 if ($relativelink) {
1306 $linktoreturn =
'document.php'.($paramlink ?
'?'.$paramlink :
'');
1308 $linktoreturn = $urlwithroot.
'/document.php'.($paramlink ?
'?'.$paramlink :
'');
1312 return $linktoreturn;
1326 public function add_contact($fk_socpeople, $type_contact, $source =
'external', $notrigger = 0)
1329 global $user, $langs;
1331 dol_syslog(get_class($this).
"::add_contact $fk_socpeople, $type_contact, $source, $notrigger");
1334 if ($fk_socpeople <= 0) {
1335 $langs->load(
"errors");
1336 $this->error = $langs->trans(
"ErrorWrongValueForParameterX",
"1");
1337 dol_syslog(get_class($this).
"::add_contact ".$this->error, LOG_ERR);
1342 $sql_check =
"SELECT rowid FROM ".$this->db->prefix().($source ==
'internal' ?
"user" :
"socpeople").
" WHERE rowid = ".((
int) $fk_socpeople);
1343 $resql_check = $this->db->query($sql_check);
1345 if (!$this->db->num_rows($resql_check)) {
1346 $langs->load(
"errors");
1347 $this->error = $langs->trans(
"ErrorRecordNotFound");
1348 dol_syslog(get_class($this).
"::add_contact Contact/user id ".$fk_socpeople.
" does not exist", LOG_ERR);
1352 $this->error = $this->db->lasterror();
1356 if (!$type_contact) {
1357 $langs->load(
"errors");
1358 $this->error = $langs->trans(
"ErrorWrongValueForParameterX",
"2");
1359 dol_syslog(get_class($this).
"::add_contact ".$this->error, LOG_ERR);
1364 if ($this->restrictiononfksoc && property_exists($this,
'socid') && !empty($this->socid) && $user->id > 0 && !$user->hasRight(
'societe',
'client',
'voir')) {
1365 $sql_allowed_contacts =
'SELECT COUNT(*) as cnt FROM '.$this->db->prefix().
'societe_commerciaux as sc';
1367 $sql_allowed_contacts .=
' WHERE sc.fk_soc = '.(int) $this->socid;
1368 $sql_allowed_contacts .=
' AND sc.fk_user = '.(int) $user->id;
1370 $resql_allowed_contacts = $this->db->query($sql_allowed_contacts);
1372 if (!$resql_allowed_contacts) {
1373 $this->errors[] = $this->db->lasterror();
1375 } elseif ($obj = $this->db->fetch_object($resql_allowed_contacts)) {
1376 if ($obj->cnt == 0) {
1377 $langs->load(
"companies");
1378 $this->error = $langs->trans(
"ErrorCommercialNotAllowedForThirdparty", $user->id);
1379 dol_syslog(get_class($this).
"::add_contact ".$this->error, LOG_ERR);
1385 $id_type_contact = 0;
1386 if (is_numeric($type_contact)) {
1387 $id_type_contact = $type_contact;
1390 $sql =
"SELECT tc.rowid";
1391 $sql .=
" FROM ".$this->db->prefix().
"c_type_contact as tc";
1392 $sql .=
" WHERE tc.element='".$this->db->escape($this->element).
"'";
1393 $sql .=
" AND tc.source='".$this->db->escape($source).
"'";
1394 $sql .=
" AND tc.code='".$this->db->escape($type_contact).
"' AND tc.active=1";
1396 $resql = $this->db->query($sql);
1398 $obj = $this->db->fetch_object($resql);
1400 $id_type_contact = $obj->rowid;
1404 if ($id_type_contact == 0) {
1405 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");
1413 $already_added =
false;
1414 if (is_array($TListeContacts) && !empty($TListeContacts)) {
1415 foreach ($TListeContacts as $array_contact) {
1416 if ($array_contact[
'status'] == 4 && $array_contact[
'id'] == $fk_socpeople && $array_contact[
'fk_c_type_contact'] == $id_type_contact) {
1417 $already_added =
true;
1423 if (!$already_added) {
1427 $sql =
"INSERT INTO ".$this->db->prefix().
"element_contact";
1428 $sql .=
" (element_id, fk_socpeople, datecreate, statut, fk_c_type_contact) ";
1429 $sql .=
" VALUES (".((int) $this->
id).
", ".((int) $fk_socpeople).
" , ";
1430 $sql .=
"'".$this->db->idate($datecreate).
"'";
1431 $sql .=
", 4, ".((int) $id_type_contact);
1434 $resql = $this->db->query($sql);
1437 $triggerPrefix = (empty($this->TRIGGER_PREFIX) ? strtoupper($this->element) : $this->TRIGGER_PREFIX);
1438 $result = $this->call_trigger($triggerPrefix.
'_ADD_CONTACT', $user);
1440 $this->db->rollback();
1445 $this->db->commit();
1448 if ($this->db->errno() ==
'DB_ERROR_RECORD_ALREADY_EXISTS') {
1449 $this->error = $this->db->errno();
1450 $this->db->rollback();
1453 $this->error = $this->db->lasterror();
1454 $this->db->rollback();
1474 $contacts = $objFrom->liste_contact(-1, $source);
1475 foreach ($contacts as $contact) {
1476 if ($this->
add_contact($contact[
'id'], $contact[
'fk_c_type_contact'], $contact[
'source']) < 0) {
1493 public function update_contact($rowid, $statut, $type_contact_id = 0, $fk_socpeople = 0)
1497 $sql =
"UPDATE ".$this->db->prefix().
"element_contact set";
1498 $sql .=
" statut = ".((int) $statut);
1499 if ($type_contact_id) {
1500 $sql .=
", fk_c_type_contact = ".((int) $type_contact_id);
1502 if ($fk_socpeople) {
1503 $sql .=
", fk_socpeople = ".((int) $fk_socpeople);
1505 $sql .=
" where rowid = ".((int) $rowid);
1507 $resql = $this->db->query($sql);
1511 $this->error = $this->db->lasterror();
1532 if ($this->
id > 0) {
1533 $sql =
"SELECT ec.rowid FROM ".$this->db->prefix().
"element_contact as ec, ".$this->db->prefix().
"c_type_contact as tc";
1534 $sql .=
" WHERE ec.rowid = ".((int) $rowid).
" AND ec.element_id = ".((int) $this->
id);
1535 $sql .=
" AND ec.fk_c_type_contact = tc.rowid AND tc.element = '".$this->db->escape($this->element).
"'";
1536 $resql = $this->db->query($sql);
1537 if (!$resql || !$this->db->num_rows($resql)) {
1538 $this->error =
'ErrorRecordNotFound';
1545 if (!$error && empty($notrigger)) {
1547 $this->context[
'contact_id'] = ((int) $rowid);
1548 $triggerPrefix = (empty($this->TRIGGER_PREFIX) ? strtoupper($this->element) : $this->TRIGGER_PREFIX);
1549 $result = $this->call_trigger($triggerPrefix.
'_DELETE_CONTACT', $user);
1557 dol_syslog(get_class($this).
"::delete_contact", LOG_DEBUG);
1559 $sql =
"DELETE FROM ".MAIN_DB_PREFIX.
"element_contact";
1560 $sql .=
" WHERE rowid = ".((int) $rowid);
1562 $result = $this->db->query($sql);
1565 $this->errors[] = $this->db->lasterror();
1570 $this->db->commit();
1573 $this->error = $this->db->lasterror();
1574 $this->db->rollback();
1594 if (!empty($typeContact)) {
1595 foreach ($typeContact as $key => $value) {
1596 array_push($temp, $key);
1598 $listId = implode(
",", $temp);
1603 if (empty($listId)) {
1607 $sql =
"DELETE FROM ".$this->db->prefix().
"element_contact";
1608 $sql .=
" WHERE element_id = ".((int) $this->
id);
1609 $sql .=
" AND fk_c_type_contact IN (".$this->db->sanitize($listId).
")";
1611 dol_syslog(get_class($this).
"::delete_linked_contact", LOG_DEBUG);
1612 if ($this->db->query($sql)) {
1615 $this->error = $this->db->lasterror();
1632 public function liste_contact($statusoflink = -1, $source =
'external', $list = 0, $code =
'', $status = -1, $arrayoftcids = array())
1639 $sql =
"SELECT ec.rowid, ec.statut as statuslink, ec.fk_socpeople as id, ec.fk_c_type_contact";
1640 if ($source ==
'internal') {
1641 $sql .=
", '-1' as socid, t.statut as statuscontact, t.login, t.photo, t.gender, t.fk_country as country_id";
1643 if ($source ==
'external' || $source ==
'thirdparty') {
1644 $sql .=
", t.fk_soc as socid, t.statut as statuscontact, t.fk_pays as country_id";
1646 $sql .=
", t.civility as civility, t.lastname as lastname, t.firstname, t.email, t.address, t.zip, t.town";
1647 if (empty($arrayoftcids)) {
1648 $sql .=
", tc.source, tc.element, tc.code, tc.libelle as type_label, co.label as country";
1651 if (empty($arrayoftcids)) {
1652 $sql .=
" ".$this->db->prefix().
"c_type_contact as tc,";
1654 $sql .=
" ".$this->db->prefix().
"element_contact as ec";
1655 if ($source ==
'internal') {
1656 $sql .=
" LEFT JOIN ".$this->db->prefix().
"user as t on ec.fk_socpeople = t.rowid";
1657 $sql .=
" LEFT JOIN ".$this->db->prefix().
"c_country as co ON co.rowid = t.fk_country";
1659 if ($source ==
'external' || $source ==
'thirdparty') {
1660 $sql .=
" LEFT JOIN ".$this->db->prefix().
"socpeople as t on ec.fk_socpeople = t.rowid";
1661 $sql .=
" LEFT JOIN ".$this->db->prefix().
"c_country as co ON co.rowid = t.fk_pays";
1663 $sql .=
" WHERE ec.element_id = ".((int) $this->
id);
1664 if (empty($arrayoftcids)) {
1665 $sql .=
" AND ec.fk_c_type_contact = tc.rowid";
1666 $sql .=
" AND tc.element = '".$this->db->escape($this->element).
"'";
1668 $sql .=
" AND tc.code = '".$this->db->escape($code).
"'";
1670 if ($source ==
'internal') {
1671 $sql .=
" AND tc.source = 'internal'";
1673 if ($source ==
'external' || $source ==
'thirdparty') {
1674 $sql .=
" AND tc.source = 'external'";
1676 $sql .=
" AND tc.active = 1";
1678 $sql .=
" AND ec.fk_c_type_contact IN (".$this->db->sanitize(implode(
',', $arrayoftcids)).
")";
1681 $sql .=
" AND t.statut = ".((int) $status);
1683 if ($statusoflink >= 0) {
1684 $sql .=
" AND ec.statut = ".((int) $statusoflink);
1686 $sql .=
" ORDER BY t.lastname ASC";
1688 dol_syslog(get_class($this).
"::liste_contact", LOG_DEBUG);
1689 $resql = $this->db->query($sql);
1691 $num = $this->db->num_rows($resql);
1694 $obj = $this->db->fetch_object($resql);
1697 $transkey =
"TypeContact_".$obj->element.
"_".$obj->source.
"_".$obj->code;
1698 $label_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->type_label);
1700 'parentId' => $this->
id,
1701 'source' => $obj->source,
1702 'socid' => $obj->socid,
1704 'nom' => $obj->lastname,
1705 'civility' => $obj->civility,
1706 'lastname' => $obj->lastname,
1707 'firstname' => $obj->firstname,
1708 'email' => $obj->email,
1709 'address' => $obj->address,
1711 'town' => $obj->town,
1712 'country_id' => $obj->country_id,
1713 'country' => $obj->country,
1714 'login' => (empty($obj->login) ?
'' : $obj->login),
1715 'photo' => (empty($obj->photo) ?
'' : $obj->photo),
1716 'gender' => (empty($obj->gender) ?
'' : $obj->gender),
1717 'statuscontact' => $obj->statuscontact,
1718 'rowid' => $obj->rowid,
1719 'code' => $obj->code,
1720 'libelle' => $label_type,
1721 'status' => (
int) $obj->statuslink,
1722 'fk_c_type_contact' => $obj->fk_c_type_contact
1725 $tab[$i] = $obj->id;
1733 $this->error = $this->db->lasterror();
1734 dol_print_error($this->db);
1748 $sql =
"SELECT ec.datecreate, ec.statut, ec.fk_socpeople, ec.fk_c_type_contact,";
1749 $sql .=
" tc.code, tc.libelle as type_label";
1750 $sql .=
" FROM (".$this->db->prefix().
"element_contact as ec, ".$this->db->prefix().
"c_type_contact as tc)";
1751 $sql .=
" WHERE ec.rowid =".((int) $rowid);
1752 $sql .=
" AND ec.fk_c_type_contact = tc.rowid";
1753 $sql .=
" AND tc.element = '".$this->db->escape($this->element).
"'";
1755 dol_syslog(get_class($this).
"::swapContactStatus", LOG_DEBUG);
1756 $resql = $this->db->query($sql);
1758 $obj = $this->db->fetch_object($resql);
1759 $newstatut = ($obj->statut == 4) ? 5 : 4;
1761 $this->db->free($resql);
1764 $this->error = $this->db->error();
1765 dol_print_error($this->db);
1781 public function liste_type_contact($source =
'internal', $order =
'position', $option = 0, $activeonly = 0, $code =
'')
1786 $sanitized_order = $order;
1788 if (empty($sanitized_order)) {
1789 $sanitized_order =
'position';
1791 if ($sanitized_order ==
'position') {
1792 $sanitized_order .=
',code';
1797 $sql =
"SELECT DISTINCT tc.rowid, tc.code, tc.libelle as type_label, tc.position";
1798 $sql .=
" FROM ".$this->db->prefix().
"c_type_contact as tc";
1799 $sql .=
" WHERE tc.element = '".$this->db->escape($this->element).
"'";
1800 if ($activeonly == 1) {
1801 $sql .=
" AND tc.active = 1";
1803 if (!empty($source) && $source !=
'all') {
1804 $sql .=
" AND tc.source = '".$this->db->escape($source).
"'";
1806 if (!empty($code)) {
1807 $sql .=
" AND tc.code = '".$this->db->escape($code).
"'";
1809 $sql .= $this->db->order($sanitized_order,
'ASC');
1812 $resql = $this->db->query($sql);
1814 $this->error = $this->db->lasterror();
1819 $num = $this->db->num_rows($resql);
1822 $obj = $this->db->fetch_object($resql);
1824 $transkey =
"TypeContact_".$this->element.
"_".$source.
"_".$obj->code;
1825 $label_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $langs->trans($obj->type_label));
1826 if (empty($option)) {
1827 $tab[$obj->rowid] = $label_type;
1828 } elseif ($option == 1) {
1829 $tab[$obj->code] = $label_type;
1831 $tab[$obj->rowid] = array(
'id' => $obj->rowid,
'code' => $obj->code,
'label' => $label_type);
1850 public function listeTypeContacts($source =
'internal', $option = 0, $activeonly = 0, $code =
'', $element =
'', $excludeelement =
'')
1854 $langs->loadLangs(array(
'bills',
'contracts',
'interventions',
'orders',
'projects',
'propal',
'ticket',
'agenda'));
1858 $sql =
"SELECT DISTINCT tc.rowid, tc.code, tc.libelle as type_label, tc.position, tc.element, tc.module";
1859 $sql .=
" FROM ".$this->db->prefix().
"c_type_contact as tc";
1861 $sqlWhere = array();
1862 if (!empty($element)) {
1863 $sqlWhere[] =
" tc.element='".$this->db->escape($element).
"'";
1865 if (!empty($excludeelement)) {
1866 $sqlWhere[] =
" tc.element <> '".$this->db->escape($excludeelement).
"'";
1869 if ($activeonly == 1) {
1870 $sqlWhere[] =
" tc.active=1";
1873 if (!empty($source) && $source !=
'all') {
1874 $sqlWhere[] =
" tc.source='".$this->db->escape($source).
"'";
1877 if (!empty($code)) {
1878 $sqlWhere[] =
" tc.code='".$this->db->escape($code).
"'";
1881 if (count($sqlWhere) > 0) {
1882 $sql .=
" WHERE ".implode(
' AND ', $sqlWhere);
1885 $sql .= $this->db->order(
'tc.element, tc.position',
'ASC');
1888 $resql = $this->db->query($sql);
1890 $num = $this->db->num_rows($resql);
1892 $langs->loadLangs(array(
"propal",
"orders",
"bills",
"suppliers",
"contracts",
"supplier_proposal"));
1894 while ($obj = $this->db->fetch_object($resql)) {
1895 $modulename = $obj->module ?? $obj->element;
1896 if (strpos($obj->element,
'project') !==
false) {
1897 $modulename =
'projet';
1898 } elseif ($obj->element ==
'contrat') {
1899 $element =
'contract';
1900 } elseif ($obj->element ==
'action') {
1901 $modulename =
'agenda';
1902 } elseif (strpos($obj->element,
'supplier') !==
false && $obj->element !=
'supplier_proposal') {
1903 $modulename =
'fournisseur';
1906 $label_element = $langs->trans(
'ContactDefault_'.$obj->element);
1907 $tmpelement = $obj->element;
1908 $transkey =
"TypeContact_".$tmpelement.
"_".$source.
"_".$obj->code;
1909 $label_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->type_label);
1910 $tab[$obj->rowid] = $label_element.
' - '.$label_type;
1916 $this->error = $this->db->lasterror();
1937 if (!
getDolGlobalInt(
'SHIPPING_USE_ITS_OWN_CONTACTS') && $this->element ==
'shipping' && $this->origin_id != 0) {
1938 $id = $this->origin_id;
1939 $element =
'commande';
1940 } elseif ($this->element ==
'reception' && $this->origin_id != 0) {
1941 $id = $this->origin_id;
1942 $element =
'order_supplier';
1945 $element = $this->element;
1948 $sql =
"SELECT ec.fk_socpeople";
1949 $sql .=
" FROM ".$this->db->prefix().
"element_contact as ec,";
1950 if ($source ==
'internal') {
1951 $sql .=
" ".$this->db->prefix().
"user as c,";
1953 if ($source ==
'external') {
1954 $sql .=
" ".$this->db->prefix().
"socpeople as c,";
1956 $sql .=
" ".$this->db->prefix().
"c_type_contact as tc";
1957 $sql .=
" WHERE ec.element_id = ".((int) $id);
1958 $sql .=
" AND ec.fk_socpeople = c.rowid";
1959 if ($source ==
'internal') {
1960 $sql .=
" AND c.entity IN (".getEntity(
'user').
")";
1962 if ($source ==
'external') {
1963 $sql .=
" AND c.entity IN (".getEntity(
'societe').
")";
1965 $sql .=
" AND ec.fk_c_type_contact = tc.rowid";
1966 $sql .=
" AND tc.element = '".$this->db->escape($element).
"'";
1967 $sql .=
" AND tc.source = '".$this->db->escape($source).
"'";
1969 $sql .=
" AND tc.code = '".$this->db->escape($code).
"'";
1971 $sql .=
" AND tc.active = 1";
1973 $sql .=
" AND ec.statut = ".((int) $status);
1976 dol_syslog(get_class($this).
"::getIdContact", LOG_DEBUG);
1977 $resql = $this->db->query($sql);
1979 while ($obj = $this->db->fetch_object($resql)) {
1980 $result[$i] = $obj->fk_socpeople;
1984 $this->error = $this->db->error();
2001 if (empty($contactid)) {
2002 $contactid = $this->contact_id;
2005 if (empty($contactid)) {
2009 require_once DOL_DOCUMENT_ROOT.
'/contact/class/contact.class.php';
2010 $contact =
new Contact($this->db);
2011 $result = $contact->fetch($contactid);
2012 $this->contact = $contact;
2027 if (empty($this->socid) && empty($this->fk_soc) && empty($force_thirdparty_id)) {
2031 require_once DOL_DOCUMENT_ROOT.
'/societe/class/societe.class.php';
2033 $idtofetch = isset($this->socid) ? $this->socid : (isset($this->fk_soc) ? $this->fk_soc : 0);
2034 if ($force_thirdparty_id) {
2035 $idtofetch = $force_thirdparty_id;
2039 $thirdparty =
new Societe($this->db);
2040 $result = $thirdparty->fetch($idtofetch);
2042 $this->errors = array_merge($this->errors, $thirdparty->errors);
2044 $this->thirdparty = $thirdparty;
2048 $this->thirdparty->price_level = 1;
2067 if (!$this->table_ref_field) {
2071 $sql =
"SELECT rowid FROM ".$this->db->prefix().$this->table_element;
2072 $sql .=
" WHERE ".$this->db->sanitize($this->table_ref_field).
" LIKE '".$this->db->escape($ref).
"'";
2075 $query = $this->db->query($sql);
2077 if (!$this->db->num_rows($query)) {
2081 $result = $this->db->fetch_object($query);
2083 if (method_exists($this,
'fetch')) {
2084 return $this->fetch($result->rowid);
2086 $this->error =
'Fetch method not implemented on '.get_class($this);
2087 dol_syslog(get_class($this).
'::fetchOneLike Error='.$this->error, LOG_ERR);
2088 array_push($this->errors, $this->error);
2117 dol_syslog(get_class($this).
'::fetchBarCode this->element='.$this->element.
' this->barcode_type='.$this->barcode_type);
2119 $idtype = $this->barcode_type;
2120 if (empty($idtype) && $idtype !=
'0') {
2121 if ($this->element ==
'product' &&
getDolGlobalString(
'PRODUIT_DEFAULT_BARCODE_TYPE')) {
2123 } elseif ($this->element ==
'societe') {
2126 dol_syslog(
'Call fetchBarCode with barcode_type not defined and cannot be guessed', LOG_WARNING);
2131 if (empty($this->barcode_type) || empty($this->barcode_type_code) || empty($this->barcode_type_label) || empty($this->barcode_type_coder)) {
2132 $sql =
"SELECT rowid, code, libelle as label, coder";
2133 $sql .=
" FROM ".$this->db->prefix().
"c_barcode_type";
2134 $sql .=
" WHERE rowid = ".((int) $idtype);
2136 $resql = $this->db->query($sql);
2138 $obj = $this->db->fetch_object($resql);
2140 $this->barcode_type = $obj->rowid;
2141 $this->barcode_type_code = $obj->code;
2142 $this->barcode_type_label = $obj->label;
2143 $this->barcode_type_coder = $obj->coder;
2146 dol_print_error($this->db);
2161 include_once DOL_DOCUMENT_ROOT.
'/projet/class/project.class.php';
2168 if (empty($this->fk_project)) {
2172 $project =
new Project($this->db);
2173 $result = $project->fetch($this->fk_project);
2175 $this->project = $project;
2217 include_once DOL_DOCUMENT_ROOT.
'/product/class/product.class.php';
2220 if (empty($this->fk_product)) {
2224 $product =
new Product($this->db);
2226 $result = $product->fetch($this->fk_product);
2228 $this->product = $product;
2241 if (empty($this->warehouse_id) && empty($this->fk_warehouse) && empty($force_warehouse_id)) {
2245 include_once DOL_DOCUMENT_ROOT.
'/product/stock/class/entrepot.class.php';
2248 $idtofetch = isset($this->warehouse_id) ? $this->warehouse_id : (isset($this->fk_warehouse) ? $this->fk_warehouse : 0);
2249 if (!empty($force_warehouse_id)) {
2250 $idtofetch = $force_warehouse_id;
2254 $warehouse =
new Entrepot($this->db);
2255 $result = $warehouse->fetch($idtofetch);
2257 $this->errors = array_merge($this->errors, $warehouse->errors);
2259 $this->warehouse = $warehouse;
2277 $user =
new User($this->db);
2278 $result = $user->fetch($userid);
2279 $this->
user = $user;
2293 $tmpclassname = $this->origin ? $this->origin : $this->origin_type;
2296 if ($tmpclassname ==
'shipping') {
2297 $tmpclassname =
'Expedition';
2299 if ($tmpclassname ==
'delivery') {
2300 $tmpclassname =
'Livraison';
2302 if ($tmpclassname ==
'order_supplier' || $tmpclassname ==
'supplier_order') {
2303 $tmpclassname =
'CommandeFournisseur';
2306 $classname = ucfirst($tmpclassname);
2308 $this->origin_object =
new $classname($this->db);
2310 $this->origin_object->fetch($this->origin_id);
2328 $sql =
"SELECT rowid FROM ".$this->db->prefix().$table;
2329 $sql .=
" WHERE ".$this->db->sanitize($field).
" = '".$this->db->escape($key).
"'";
2330 if (!empty($element)) {
2331 $sql .=
" AND entity IN (".getEntity($element).
")";
2333 $sql .=
" AND entity = ".((int)
$conf->entity);
2336 dol_syslog(get_class($this).
'::fetchObjectFrom', LOG_DEBUG);
2337 $resql = $this->db->query($sql);
2339 $obj = $this->db->fetch_object($resql);
2342 if (method_exists($this,
'fetch')) {
2343 $result = $this->fetch($obj->rowid);
2345 $this->error =
'fetch() method not implemented on '.get_class($this);
2346 dol_syslog(get_class($this).
'::fetchOneLike Error='.$this->error, LOG_ERR);
2347 array_push($this->errors, $this->error);
2367 if (!empty($id) && !empty($field) && !empty($table)) {
2368 if (!preg_match(
'/^[a-zA-Z_][a-zA-Z0-9_]*$/', $table)) {
2369 dol_syslog(get_class($this).
'::getValueFrom Bad table name: '.$table, LOG_WARNING);
2372 if (!preg_match(
'/^[a-zA-Z_][a-zA-Z0-9_.]*$/', $field)) {
2373 dol_syslog(get_class($this).
'::getValueFrom Bad field name: '.$field, LOG_WARNING);
2377 $sql =
"SELECT ".$this->db->sanitize($field).
" FROM ".$this->db->prefix().$this->db->sanitize($table);
2378 $sql .=
" WHERE rowid = ".((int) $id);
2380 dol_syslog(get_class($this).
'::getValueFrom', LOG_DEBUG);
2381 $resql = $this->db->query($sql);
2383 $row = $this->db->fetch_row($resql);
2406 public function setValueFrom($field, $value, $table =
'', $id =
null, $format =
'', $id_field =
'', $fuser =
null, $trigkey =
'', $fk_user_field =
'fk_user_modif')
2410 if (empty($table)) {
2411 $table = $this->table_element;
2416 if (empty($format)) {
2419 if (empty($id_field)) {
2420 $id_field =
'rowid';
2423 $propfield = $field;
2426 if ($table ==
'product') {
2427 if ($field ==
'note_private') {
2429 $propfield =
'note_private';
2430 } elseif ($field ==
'status') {
2432 $propfield =
'status';
2433 } elseif ($field ==
'status_buy') {
2435 $propfield =
'status_buy';
2436 } elseif ($field ==
'status_batch') {
2438 $propfield =
'status_batch';
2442 if (in_array($table, array(
'actioncomm',
'adherent',
'advtargetemailing',
'cronjob',
'establishment'))) {
2443 $fk_user_field =
'fk_user_mod';
2445 if (in_array($table, array(
'prelevement_bons'))) {
2446 $fk_user_field =
'';
2449 if (!preg_match(
'/^[a-zA-Z_][a-zA-Z0-9_]*$/', $table)) {
2450 dol_syslog(get_class($this).
'::getValueFrom Bad table name: '.$table, LOG_WARNING);
2453 if (!preg_match(
'/^[a-zA-Z_][a-zA-Z0-9_.]*$/', $field)) {
2454 dol_syslog(get_class($this).
'::getValueFrom Bad field name: '.$field, LOG_WARNING);
2460 $sql =
"SELECT " . $this->db->sanitize($field);
2461 $sql .=
" FROM " . MAIN_DB_PREFIX . $this->db->sanitize($table);
2462 $sql .=
" WHERE " . $this->db->sanitize($id_field) .
" = " . ((int) $id);
2464 $resql = $this->db->query($sql);
2466 if ($obj = $this->db->fetch_object($resql)) {
2467 if ($format ==
'date') {
2468 $oldvalue = $this->db->jdate($obj->$field);
2470 $oldvalue = $obj->$field;
2474 $this->error = $this->db->lasterror();
2485 $sql =
"UPDATE ".$this->db->prefix().$table.
" SET ";
2487 if ($format ==
'text') {
2488 $sql .= $this->db->sanitize($field).
" = '".$this->db->escape($value).
"'";
2489 } elseif ($format ==
'int') {
2490 $sql .= $this->db->sanitize($field).
" = ".((int) $value);
2491 } elseif ($format ==
'date') {
2492 $sql .= $this->db->sanitize($field).
" = ".($value ?
"'".$this->db->idate($value).
"'" :
"null");
2493 } elseif ($format ==
'dategmt') {
2494 $sql .= $this->db->sanitize($field).
" = ".($value ?
"'".$this->db->idate($value,
'gmt').
"'" :
"null");
2497 if ($fk_user_field) {
2498 if (!empty($fuser) && is_object($fuser)) {
2499 $sql .=
", ".$this->db->sanitize($fk_user_field).
" = ".((int) $fuser->id);
2500 } elseif (empty($fuser) || $fuser !=
'none') {
2501 $sql .=
", ".$this->db->sanitize($fk_user_field).
" = ".((int) $user->id);
2505 $sql .=
" WHERE ".$this->db->sanitize($id_field).
" = ".((int) $id);
2507 $resql = $this->db->query($sql);
2511 if (method_exists($this,
'fetch')) {
2512 $result = $this->fetch(
$id);
2517 $this->oldcopy = clone $this;
2518 if (property_exists($this->oldcopy, $field)) {
2519 $this->oldcopy->$field = $oldvalue;
2521 if ($propfield != $field && property_exists($this->oldcopy, $propfield)) {
2522 $this->oldcopy->$propfield = $oldvalue;
2525 if (empty($this->context[
'actionmsgmore'])) {
2526 $this->context[
'actionmsgmore'] =
'Trigger called by setValueFrom';
2530 $result = $this->call_trigger($trigkey, (!empty($fuser) && is_object($fuser)) ? $fuser : $user);
2536 if (property_exists($this, $field)) {
2537 $this->$field = $value;
2539 if ($propfield != $field && property_exists($this, $propfield)) {
2540 $this->$propfield = $value;
2545 $this->db->commit();
2548 if (property_exists($this, $field)) {
2549 $this->$field = $oldvalue;
2551 if ($propfield != $field && property_exists($this, $propfield)) {
2552 $this->$propfield = $oldvalue;
2554 $this->db->rollback();
2558 if ($this->db->lasterrno() ==
'DB_ERROR_RECORD_ALREADY_EXISTS') {
2559 $this->error =
'DB_ERROR_RECORD_ALREADY_EXISTS';
2561 $this->error = $this->db->lasterror();
2563 $this->db->rollback();
2582 global
$conf, $user;
2584 if (!$this->table_element) {
2585 dol_print_error(
null, get_class($this).
"::load_previous_next_ref was called on object with property table_element not defined");
2588 if ($fieldid ==
'none') {
2593 if (in_array($this->table_element, array(
'facture_rec',
'facture_fourn_rec')) && $fieldid ==
'title') {
2599 if ($user->socid > 0) {
2600 $socid = $user->socid;
2605 $aliastablesociete =
's';
2606 if ($this->element ==
'societe') {
2607 $aliastablesociete =
'te';
2609 $restrictiononfksoc = empty($this->restrictiononfksoc) ? 0 : $this->restrictiononfksoc;
2610 $sql =
"SELECT MAX(te.".$this->db->sanitize($fieldid).
")";
2611 $sql .=
" FROM ".(empty($nodbprefix) ? $this->db->prefix() :
'').$this->table_element.
" as te";
2612 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2613 $tmparray = explode(
'@', $this->ismultientitymanaged);
2614 $sql .=
", ".$this->db->prefix().$this->db->sanitize($tmparray[1]).
" as ".($tmparray[1] ==
'societe' ?
's' :
'parenttable');
2615 } elseif ($restrictiononfksoc == 1 && $this->element !=
'societe' && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2616 $sql .=
", ".$this->db->prefix().
"societe as s";
2617 } elseif ($restrictiononfksoc == 2 && $this->element !=
'societe' && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2618 $sql .=
" LEFT JOIN ".$this->db->prefix().
"societe as s ON te.fk_soc = s.rowid";
2620 if ($restrictiononfksoc && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2621 $sql .=
" LEFT JOIN ".$this->db->prefix().
"societe_commerciaux as sc ON ".$aliastablesociete.
".rowid = sc.fk_soc";
2623 if ($fieldid ==
'rowid') {
2624 $sql .=
" WHERE te.".$this->db->sanitize($fieldid).
" < ".((int) $this->
id);
2625 } elseif ($fieldid ==
'label') {
2627 $sql .=
" WHERE te.".$this->db->sanitize($fieldid).
" < '".$this->db->escape((
string) $this->label).
"'";
2629 $sql .=
" WHERE te.".$this->db->sanitize($fieldid).
" < '".$this->db->escape((
string) $this->
ref).
"'";
2631 if ($restrictiononfksoc == 1 && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2632 $sql .=
" AND sc.fk_user = ".((int) $user->id);
2634 if ($restrictiononfksoc == 2 && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2635 $sql .=
" AND (sc.fk_user = ".((int) $user->id).
' OR te.fk_soc IS NULL)';
2638 $filtermax = $filter;
2643 if ($errormessage) {
2644 if (!preg_match(
'/^\s*AND/i', $filtermax)) {
2652 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2653 $tmparray = explode(
'@', $this->ismultientitymanaged);
2654 $sql .=
" AND te.".$this->db->sanitize($tmparray[0]).
" = ".($tmparray[1] ==
"societe" ?
"s" :
"parenttable").
".rowid";
2655 } elseif ($restrictiononfksoc == 1 && $this->element !=
'societe' && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2656 $sql .=
' AND te.fk_soc = s.rowid';
2658 if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
2659 if ($this->element ==
'user' &&
getDolGlobalInt(
'MULTICOMPANY_TRANSVERSE_MODE')) {
2660 if (!empty($user->admin) && empty($user->entity) &&
$conf->entity == 1) {
2661 $sql .=
" AND te.entity IS NOT NULL";
2663 $sql .=
" AND te.rowid IN (SELECT ug.fk_user FROM ".$this->db->prefix().
"usergroup_user as ug WHERE ug.entity IN (".
getEntity(
'usergroup').
"))";
2666 $sql .=
' AND te.entity IN ('.getEntity($this->element).
')';
2669 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged) && $this->element !=
'societe') {
2670 $tmparray = explode(
'@', $this->ismultientitymanaged);
2671 $sql .=
' AND parenttable.entity IN ('.getEntity($tmparray[1]).
')';
2673 if ($restrictiononfksoc == 1 && $socid && $this->element !=
'societe') {
2674 $sql .=
' AND te.fk_soc = '.((int) $socid);
2676 if ($restrictiononfksoc == 2 && $socid && $this->element !=
'societe') {
2677 $sql .=
' AND (te.fk_soc = '.((int) $socid).
' OR te.fk_soc IS NULL)';
2679 if ($restrictiononfksoc && $socid && $this->element ==
'societe') {
2680 $sql .=
' AND te.rowid = '.((int) $socid);
2684 $result = $this->db->query($sql);
2686 $this->error = $this->db->lasterror();
2689 $row = $this->db->fetch_row($result);
2690 $this->ref_previous = $row[0];
2692 $sql =
"SELECT MIN(te.".$this->db->sanitize($fieldid).
")";
2693 $sql .=
" FROM ".(empty($nodbprefix) ? $this->db->prefix() :
'').$this->table_element.
" as te";
2694 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2695 $tmparray = explode(
'@', $this->ismultientitymanaged);
2696 $sql .=
", ".$this->db->prefix().$this->db->sanitize($tmparray[1]).
" as ".($tmparray[1] ==
'societe' ?
's' :
'parenttable');
2697 } elseif ($restrictiononfksoc == 1 && $this->element !=
'societe' && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2698 $sql .=
", ".$this->db->prefix().
"societe as s";
2699 } elseif ($restrictiononfksoc == 2 && $this->element !=
'societe' && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2700 $sql .=
" LEFT JOIN ".$this->db->prefix().
"societe as s ON te.fk_soc = s.rowid";
2702 if ($restrictiononfksoc && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2703 $sql .=
" LEFT JOIN ".$this->db->prefix().
"societe_commerciaux as sc ON ".$aliastablesociete.
".rowid = sc.fk_soc";
2705 if ($fieldid ==
'rowid') {
2706 $sql .=
" WHERE te.".$this->db->sanitize($fieldid).
" > ".((int) $this->
id);
2707 } elseif ($fieldid ==
'label') {
2709 $sql .=
" WHERE te.".$this->db->sanitize($fieldid).
" > '".$this->db->escape((
string) $this->label).
"'";
2711 $sql .=
" WHERE te.".$this->db->sanitize($fieldid).
" > '".$this->db->escape((
string) $this->
ref).
"'";
2713 if ($restrictiononfksoc == 1 && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2714 $sql .=
" AND (sc.fk_user = ".((int) $user->id);
2716 $userschilds = $user->getAllChildIds();
2717 $sql .=
" OR sc.fk_user IN (".$this->db->sanitize(implode(
',', $userschilds)).
")";
2721 if ($restrictiononfksoc == 2 && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2722 $sql .=
" AND (sc.fk_user = ".((int) $user->id).
' OR te.fk_soc IS NULL)';
2725 $filtermin = $filter;
2730 if ($errormessage) {
2731 if (!preg_match(
'/^\s*AND/i', $filtermin)) {
2741 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2742 $tmparray = explode(
'@', $this->ismultientitymanaged);
2743 $sql .=
" AND te.".$this->db->sanitize($tmparray[0]).
" = ".($tmparray[1] ==
"societe" ?
"s" :
"parenttable").
".rowid";
2744 } elseif ($restrictiononfksoc == 1 && $this->element !=
'societe' && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2745 $sql .=
' AND te.fk_soc = s.rowid';
2747 if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
2748 if ($this->element ==
'user' &&
getDolGlobalInt(
'MULTICOMPANY_TRANSVERSE_MODE')) {
2749 if (!empty($user->admin) && empty($user->entity) &&
$conf->entity == 1) {
2750 $sql .=
" AND te.entity IS NOT NULL";
2752 $sql .=
" AND te.rowid IN (SELECT ug.fk_user FROM ".$this->db->prefix().
"usergroup_user as ug WHERE ug.entity IN (".
getEntity(
'usergroup').
"))";
2755 $sql .=
' AND te.entity IN ('.getEntity($this->element).
')';
2758 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged) && $this->element !=
'societe') {
2759 $tmparray = explode(
'@', $this->ismultientitymanaged);
2760 $sql .=
' AND parenttable.entity IN ('.getEntity($tmparray[1]).
')';
2762 if ($restrictiononfksoc == 1 && $socid && $this->element !=
'societe') {
2763 $sql .=
' AND te.fk_soc = '.((int) $socid);
2765 if ($restrictiononfksoc == 2 && $socid && $this->element !=
'societe') {
2766 $sql .=
' AND (te.fk_soc = '.((int) $socid).
' OR te.fk_soc IS NULL)';
2768 if ($restrictiononfksoc && $socid && $this->element ==
'societe') {
2769 $sql .=
' AND te.rowid = '.((int) $socid);
2774 $result = $this->db->query($sql);
2776 $this->error = $this->db->lasterror();
2779 $row = $this->db->fetch_row($result);
2780 $this->ref_next = $row[0];
2795 $contactAlreadySelected = array();
2800 if ($source ==
'thirdparty') {
2801 $contactAlreadySelected[$i] = $tab[$i][
'socid'];
2803 $contactAlreadySelected[$i] = $tab[$i][
'id'];
2807 return $contactAlreadySelected;
2823 if (!$this->table_element) {
2824 dol_syslog(get_class($this).
"::setProject was called on object with property table_element not defined", LOG_ERR);
2828 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
2829 if ($this->table_element ==
'actioncomm') {
2831 $sql .=
" SET fk_project = ".((int) $projectid);
2833 $sql .=
" SET fk_project = NULL";
2835 $sql .=
' WHERE id = '.((int) $this->
id);
2837 } elseif (!empty($this->fields[
'fk_project'])) {
2839 $sql .=
" SET fk_project = ".((int) $projectid);
2841 $sql .=
" SET fk_project = NULL";
2843 $sql .=
' WHERE rowid = '.((int) $this->
id);
2846 $sql .=
' SET fk_projet = '.((int) $projectid);
2848 $sql .=
' SET fk_projet = NULL';
2850 $sql .=
" WHERE rowid = ".((int) $this->
id);
2855 dol_syslog(get_class($this).
"::setProject", LOG_DEBUG);
2856 if ($this->db->query($sql)) {
2857 $this->fk_project = ((int) $projectid);
2859 dol_print_error($this->db);
2864 if (!$error && !$notrigger) {
2866 $result = $this->call_trigger(strtoupper($this->element) .
'_MODIFY', $user);
2875 $this->db->rollback();
2878 $this->db->commit();
2897 dol_syslog(get_class($this).
'::setPaymentMethods('.$id.
')');
2899 if ($this->
status >= 0 || $this->element ==
'societe') {
2903 $fieldname =
'fk_mode_reglement';
2904 $triggerName = (empty($this->TRIGGER_PREFIX) ? strtoupper(get_class($this)) : $this->TRIGGER_PREFIX);
2905 if ($this->element ==
'societe') {
2906 $fieldname =
'mode_reglement';
2907 $triggerName =
'COMPANY';
2909 if (get_class($this) ==
'Facture') {
2910 $triggerName =
'BILL';
2912 if (get_class($this) ==
'Fournisseur') {
2913 $fieldname =
'mode_reglement_supplier';
2914 $triggerName =
'BILL_SUPPLIER';
2916 if (get_class($this) ==
'Tva') {
2917 $fieldname =
'fk_typepayment';
2918 $triggerName =
'VAT';
2920 if (get_class($this) ==
'Salary') {
2921 $fieldname =
'fk_typepayment';
2924 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
2925 $sql .=
" SET ".$this->db->sanitize($fieldname).
" = ".(($id > 0 || $id ==
'0') ? ((
int) $id) :
'NULL');
2926 $sql .=
' WHERE rowid = '.((int) $this->
id);
2928 if ($this->db->query($sql)) {
2929 $this->mode_reglement_id = $id;
2931 if (get_class($this) ==
'Fournisseur') {
2932 $this->mode_reglement_supplier_id = $id;
2936 if (!$error && !$notrigger) {
2938 $result = $this->call_trigger($triggerName.
'_MODIFY', $user);
2946 dol_syslog(get_class($this).
'::setPaymentMethods Error '.$this->db->error());
2947 $this->error = $this->db->error();
2951 dol_syslog(get_class($this).
'::setPaymentMethods, status of the object is incompatible');
2952 $this->error =
'Status of the object is incompatible '.$this->status;
2965 dol_syslog(get_class($this).
'::setMulticurrencyCode('.$code.
')');
2966 if ($this->
status >= 0 || $this->element ==
'societe') {
2967 $sql =
'UPDATE '.$this->db->prefix().$this->table_element;
2968 $sql .=
" SET multicurrency_code = '".$this->db->escape($code).
"'";
2969 $sql .=
' WHERE rowid='.((int) $this->
id);
2971 if ($this->db->query($sql)) {
2972 $this->multicurrency_code = $code;
2976 $this->setMulticurrencyRate($rate, 2);
2981 dol_syslog(get_class($this).
'::setMulticurrencyCode Error '.$sql.
' - '.$this->db->error());
2982 $this->error = $this->db->error();
2986 dol_syslog(get_class($this).
'::setMulticurrencyCode, status of the object is incompatible');
2987 $this->error =
'Status of the object is incompatible '.$this->status;
2999 public function setMulticurrencyRate($rate, $mode = 1)
3001 dol_syslog(get_class($this).
'::setMulticurrencyRate('.$rate.
', '.$mode.
')');
3002 if ($this->
status >= 0 || $this->element ==
'societe') {
3003 $sql =
'UPDATE '.$this->db->prefix().$this->table_element;
3004 $sql .=
" SET multicurrency_tx = ".((float) $rate);
3005 $sql .=
' WHERE rowid='.((int) $this->
id);
3007 if ($this->db->query($sql)) {
3008 $this->multicurrency_tx = $rate;
3011 if (!empty($this->lines)) {
3012 foreach ($this->lines as &$line) {
3015 if (!empty($line->fk_remise_except)) {
3021 $line->subprice = 0;
3026 $line->multicurrency_subprice = 0;
3029 switch ($this->element) {
3033 '@phan-var-force Propal $this';
3034 '@phan-var-force PropaleLigne $line';
3039 $line->remise_percent,
3041 $line->localtax1_tx,
3042 $line->localtax2_tx,
3043 ($line->description ? $line->description : $line->desc),
3046 $line->special_code,
3047 $line->fk_parent_line,
3048 $line->skip_update_total,
3049 $line->fk_fournprice,
3052 $line->product_type,
3055 $line->array_options,
3057 $line->multicurrency_subprice
3063 '@phan-var-force Commande $this';
3064 '@phan-var-force OrderLine $line';
3067 ($line->description ? $line->description : $line->desc),
3070 $line->remise_percent,
3072 $line->localtax1_tx,
3073 $line->localtax2_tx,
3078 $line->product_type,
3079 $line->fk_parent_line,
3080 $line->skip_update_total,
3081 $line->fk_fournprice,
3084 $line->special_code,
3085 $line->array_options,
3087 $line->multicurrency_subprice
3093 '@phan-var-force Facture $this';
3094 '@phan-var-force FactureLigne $line';
3097 ($line->description ? $line->description : $line->desc),
3100 $line->remise_percent,
3104 $line->localtax1_tx,
3105 $line->localtax2_tx,
3108 $line->product_type,
3109 $line->fk_parent_line,
3110 $line->skip_update_total,
3111 $line->fk_fournprice,
3114 $line->special_code,
3115 $line->array_options,
3116 $line->situation_percent,
3118 $line->multicurrency_subprice
3124 '@phan-var-force FactureRec $this';
3125 '@phan-var-force FactureLigneRec $line';
3128 ($line->description ? $line->description : $line->desc),
3132 $line->localtax1_tx,
3133 $line->localtax2_tx,
3135 $line->remise_percent,
3140 $line->product_type,
3142 $line->special_code,
3145 $line->multicurrency_subprice,
3149 $line->fk_fournprice,
3151 $line->fk_parent_line
3154 case 'supplier_proposal':
3157 '@phan-var-force SupplierProposal $this';
3158 '@phan-var-force SupplierProposalLine $line';
3163 $line->remise_percent,
3165 $line->localtax1_tx,
3166 $line->localtax2_tx,
3167 ($line->description ? $line->description : $line->desc),
3170 $line->special_code,
3171 $line->fk_parent_line,
3172 $line->skip_update_total,
3173 $line->fk_fournprice,
3176 $line->product_type,
3177 $line->array_options,
3179 (int) $line->fk_unit,
3180 $line->multicurrency_subprice
3183 case 'order_supplier':
3186 '@phan-var-force CommandeFournisseur $this';
3187 '@phan-var-force CommandeFournisseurLigne $line';
3190 ($line->description ? $line->description : $line->desc),
3193 $line->remise_percent,
3195 $line->localtax1_tx,
3196 $line->localtax2_tx,
3199 $line->product_type,
3203 $line->array_options,
3205 $line->multicurrency_subprice,
3209 case 'invoice_supplier':
3212 '@phan-var-force FactureFournisseur $this';
3213 '@phan-var-force SupplierInvoiceLIne $line';
3216 ($line->description ? $line->description : $line->desc),
3219 $line->localtax1_tx,
3220 $line->localtax2_tx,
3225 $line->product_type,
3226 $line->remise_percent,
3230 $line->array_options,
3232 $line->multicurrency_subprice,
3237 dol_syslog(get_class($this).
'::setMulticurrencyRate no updateline defined', LOG_DEBUG);
3245 dol_syslog(get_class($this).
'::setMulticurrencyRate Error '.$sql.
' - '.$this->db->error());
3246 $this->error = $this->db->error();
3250 dol_syslog(get_class($this).
'::setMulticurrencyRate, status of the object is incompatible');
3251 $this->error =
'Status of the object is incompatible '.$this->status;
3266 if ($this->
status >= 0 || $this->element ==
'societe') {
3268 $fieldname =
'fk_cond_reglement';
3269 if ($this->element ==
'societe') {
3270 $fieldname =
'cond_reglement';
3272 if (get_class($this) ==
'Fournisseur') {
3273 $fieldname =
'cond_reglement_supplier';
3276 if (empty($deposit_percent) || $deposit_percent < 0) {
3277 $deposit_percent = (float)
getDictionaryValue(
'c_payment_term',
'deposit_percent', $id);
3280 if ($deposit_percent > 100) {
3281 $deposit_percent = 100;
3284 $sql =
'UPDATE '.$this->db->prefix().$this->table_element;
3285 $sql .=
" SET ".$this->db->sanitize($fieldname).
" = ".(($id > 0 || $id ==
'0') ? ((
int) $id) :
'NULL');
3286 if (in_array($this->table_element, array(
'propal',
'commande',
'supplier_proposal',
'commande_fournisseur',
'societe'))) {
3287 $sql .=
" , deposit_percent = " . (empty($deposit_percent) ?
'NULL' :
"'".$this->db->escape((
string) $deposit_percent).
"'");
3289 $sql .=
' WHERE rowid = '.((int) $this->
id);
3291 if ($this->db->query($sql)) {
3292 $this->cond_reglement_id = $id;
3294 if (get_class($this) ==
'Fournisseur') {
3295 $this->cond_reglement_supplier_id = $id;
3297 $this->deposit_percent = $deposit_percent;
3300 dol_syslog(get_class($this).
'::setPaymentTerms Error '.$sql.
' - '.$this->db->error());
3301 $this->error = $this->db->error();
3305 dol_syslog(get_class($this).
'::setPaymentTerms, status of the object is incompatible');
3306 $this->error =
'Status of the object is incompatible '.$this->status;
3319 dol_syslog(get_class($this).
'::setTransportMode('.$id.
')');
3320 if ($this->
status >= 0 || $this->element ==
'societe') {
3321 $fieldname =
'fk_transport_mode';
3322 if ($this->element ==
'societe') {
3323 $fieldname =
'transport_mode';
3325 if (get_class($this) ==
'Fournisseur') {
3326 $fieldname =
'transport_mode_supplier';
3329 $sql =
'UPDATE '.$this->db->prefix().$this->table_element;
3330 $sql .=
" SET ".$this->db->sanitize($fieldname).
" = ".(($id > 0 || $id ==
'0') ? ((
int) $id) :
'NULL');
3331 $sql .=
' WHERE rowid='.((int) $this->
id);
3333 if ($this->db->query($sql)) {
3334 $this->transport_mode_id = $id;
3336 if (get_class($this) ==
'Fournisseur') {
3337 $this->transport_mode_supplier_id = $id;
3341 dol_syslog(get_class($this).
'::setTransportMode Error '.$sql.
' - '.$this->db->error());
3342 $this->error = $this->db->error();
3346 dol_syslog(get_class($this).
'::setTransportMode, status of the object is incompatible');
3347 $this->error =
'Status of the object is incompatible '.$this->status;
3361 $fieldname =
'fk_delivery_address';
3362 if ($this->element ==
'delivery' || $this->element ==
'shipping') {
3363 $fieldname =
'fk_address';
3366 $sql =
"UPDATE ".$this->db->prefix().$this->table_element.
" SET ".$this->db->sanitize($fieldname).
" = ".((int) $id);
3367 $sql .=
" WHERE rowid = ".((int) $this->
id).
" AND fk_statut = 0";
3369 if ($this->db->query($sql)) {
3370 $this->fk_delivery_address =
$id;
3373 $this->error = $this->db->error();
3374 dol_syslog(get_class($this).
'::setDeliveryAddress Error '.$this->error);
3392 if (empty($userused)) {
3398 if (!$this->table_element) {
3399 dol_syslog(get_class($this).
"::setShippingMethod was called on object with property table_element not defined", LOG_ERR);
3405 if ($shipping_method_id < 0) {
3406 $shipping_method_id =
'NULL';
3408 dol_syslog(get_class($this).
'::setShippingMethod('.$shipping_method_id.
')');
3410 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
3411 $sql .=
" SET fk_shipping_method = ".((int) $shipping_method_id);
3412 $sql .=
" WHERE rowid=".((int) $this->
id);
3413 $resql = $this->db->query($sql);
3415 dol_syslog(get_class($this).
'::setShippingMethod Error ', LOG_DEBUG);
3416 $this->error = $this->db->lasterror();
3421 $this->context = array(
'shippingmethodupdate' => 1);
3422 $triggerPrefix = (empty($this->TRIGGER_PREFIX) ? strtoupper(get_class($this)) : $this->TRIGGER_PREFIX);
3423 $result = $this->call_trigger($triggerPrefix.
'_MODIFY', $userused);
3431 $this->db->rollback();
3434 $this->shipping_method_id = ($shipping_method_id ==
'NULL') ?
null : $shipping_method_id;
3435 $this->db->commit();
3449 if (!$this->table_element) {
3450 dol_syslog(get_class($this).
"::setWarehouse was called on object with property table_element not defined", LOG_ERR);
3453 if ($warehouse_id < 0) {
3454 $warehouse_id =
'NULL';
3456 dol_syslog(get_class($this).
'::setWarehouse('.$warehouse_id.
')');
3458 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
3459 $sql .=
" SET fk_warehouse = ".((int) $warehouse_id);
3460 $sql .=
" WHERE rowid=".((int) $this->
id);
3462 if ($this->db->query($sql)) {
3463 $this->warehouse_id = ($warehouse_id ==
'NULL') ?
null : $warehouse_id;
3466 dol_syslog(get_class($this).
'::setWarehouse Error ', LOG_DEBUG);
3467 $this->error = $this->db->error();
3482 if (!$this->table_element) {
3483 dol_syslog(get_class($this).
"::setDocModel was called on object with property table_element not defined", LOG_ERR);
3487 $newmodelpdf =
dol_trunc($modelpdf, 255);
3489 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
3490 $sql .=
" SET model_pdf = '".$this->db->escape($newmodelpdf).
"'";
3491 $sql .=
" WHERE rowid = ".((int) $this->
id);
3493 dol_syslog(get_class($this).
"::setDocModel", LOG_DEBUG);
3494 $resql = $this->db->query($sql);
3496 $this->model_pdf = $modelpdf;
3499 dol_print_error($this->db);
3517 if (empty($userused)) {
3523 if (!$this->table_element) {
3524 dol_syslog(get_class($this).
"::setBankAccount was called on object with property table_element not defined", LOG_ERR);
3529 if ($fk_account < 0) {
3530 $fk_account =
'NULL';
3532 dol_syslog(get_class($this).
'::setBankAccount('.$fk_account.
')');
3534 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
3535 $sql .=
" SET fk_account = ".((int) $fk_account);
3536 $sql .=
" WHERE rowid=".((int) $this->
id);
3538 $resql = $this->db->query($sql);
3540 dol_syslog(get_class($this).
'::setBankAccount Error '.$sql.
' - '.$this->db->error());
3541 $this->error = $this->db->lasterror();
3546 $this->context[
'bankaccountupdate'] = 1;
3548 $triggerName = (empty($this->TRIGGER_PREFIX) ? strtoupper(get_class($this)) : $this->TRIGGER_PREFIX);
3549 $result = $this->call_trigger($triggerName .
'_MODIFY', $userused);
3557 $this->db->rollback();
3560 $this->fk_account = ($fk_account ==
'NULL') ?
null : $fk_account;
3561 $this->db->commit();
3579 public function line_order($renum =
false, $rowidorder =
'ASC', $fk_parent_line =
true)
3582 if (!$this->table_element_line) {
3583 dol_syslog(get_class($this).
"::line_order was called on object with property table_element_line not defined", LOG_ERR);
3586 if (!$this->fk_element) {
3587 dol_syslog(get_class($this).
"::line_order was called on object with property fk_element not defined", LOG_ERR);
3591 $fieldposition =
'rang';
3592 if (in_array($this->table_element_line, array(
'bom_bomline',
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3593 $fieldposition =
'position';
3598 $sql =
"SELECT count(rowid) FROM ".$this->db->prefix().$this->db->sanitize($this->table_element_line);
3599 $sql .=
" WHERE ".$this->db->sanitize($this->fk_element).
" = ".((int) $this->
id);
3601 $sql .=
" AND " . $this->db->sanitize($fieldposition) .
" = 0";
3604 $sql .=
" AND " . $this->db->sanitize($fieldposition) .
" <> 0";
3607 dol_syslog(get_class($this).
"::line_order", LOG_DEBUG);
3608 $resql = $this->db->query($sql);
3610 $row = $this->db->fetch_row($resql);
3613 dol_print_error($this->db);
3620 $sql =
"SELECT rowid FROM ".$this->db->prefix().$this->db->sanitize($this->table_element_line);
3621 $sql .=
" WHERE ".$this->db->sanitize($this->fk_element).
" = ".((int) $this->
id);
3622 if ($fk_parent_line) {
3623 $sql .=
' AND fk_parent_line IS NULL';
3625 $sql .=
" ORDER BY " . $this->db->sanitize($fieldposition) .
" ASC, rowid " . $this->db->sanitize($rowidorder);
3627 dol_syslog(get_class($this).
"::line_order search all parent lines", LOG_DEBUG);
3628 $resql = $this->db->query($sql);
3631 $num = $this->db->num_rows($resql);
3634 $row = $this->db->fetch_row($resql);
3636 if ($fk_parent_line) {
3639 if (!empty($children)) {
3640 foreach ($children as $child) {
3641 array_push($rows, $child);
3648 if (!empty($rows)) {
3649 foreach ($rows as $key => $row) {
3654 dol_print_error($this->db);
3669 $fieldposition =
'rang';
3670 if (in_array($this->table_element_line, array(
'bom_bomline',
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3671 $fieldposition =
'position';
3676 $sql =
"SELECT rowid FROM ".$this->db->prefix().$this->db->sanitize($this->table_element_line);
3677 $sql .=
" WHERE ".$this->db->sanitize($this->fk_element).
" = ".((int) $this->
id);
3678 $sql .=
' AND fk_parent_line = '.((int) $id);
3679 $sql .=
" ORDER BY " . $this->db->sanitize($fieldposition) .
" ASC";
3681 dol_syslog(get_class($this).
"::getChildrenOfLine search children lines for line ".$id, LOG_DEBUG);
3683 $resql = $this->db->query($sql);
3684 if (!$resql || $this->db->num_rows($resql) <= 0) {
3688 while ($row = $this->db->fetch_row($resql)) {
3690 if (!empty($includealltree) && $includealltree <= 1000) {
3691 $rows = array_merge($rows, $this->
getChildrenOfLine($row[0], $includealltree + 1));
3705 public function line_up($rowid, $fk_parent_line =
true)
3708 $this->
line_order(
false,
'ASC', $fk_parent_line);
3728 $this->
line_order(
false,
'ASC', $fk_parent_line);
3749 global $hookmanager;
3750 $fieldposition =
'rang';
3751 if (in_array($this->table_element_line, array(
'bom_bomline',
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3752 $fieldposition =
'position';
3755 $sql =
"UPDATE ".$this->db->prefix().$this->table_element_line.
" SET ".$this->db->sanitize($fieldposition).
" = ".((int) $rang);
3756 $sql .=
' WHERE rowid = '.((int) $rowid);
3757 if ($this->
id > 0 && !empty($this->fk_element)) {
3759 $sql .=
" AND ".$this->db->sanitize($this->fk_element).
" = ".((int) $this->
id);
3762 dol_syslog(get_class($this).
"::updateRangOfLine", LOG_DEBUG);
3763 if (!$this->db->query($sql)) {
3764 dol_print_error($this->db);
3768 $parameters = array(
'rowid' => $rowid,
'rang' => $rang,
'fieldposition' => $fieldposition);
3770 $reshook = $hookmanager->executeHooks(
'afterRankOfLineUpdate', $parameters, $this, $action);
3784 $num = count($rows);
3785 for ($i = 0; $i < $num; $i++) {
3803 $fieldposition =
'rang';
3804 if (in_array($this->table_element_line, array(
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3805 $fieldposition =
'position';
3808 $sql =
"UPDATE ".$this->db->prefix().$this->db->sanitize($this->table_element_line).
" SET ".$this->db->sanitize($fieldposition).
" = ".((int) $rang);
3809 $sql .=
" WHERE ".$this->db->sanitize($this->fk_element).
" = ".((int) $this->
id);
3810 $sql .=
" AND " . $this->db->sanitize($fieldposition) .
" = " . ((int) ($rang - 1));
3811 if (!$this->db->query($sql)) {
3812 $this->error = $this->db->lasterror();
3816 $sql =
"UPDATE ".$this->db->prefix().$this->table_element_line.
" SET ".$this->db->sanitize($fieldposition).
" = ".((int) ($rang - 1));
3817 $sql .=
' WHERE rowid = '.((int) $rowid);
3818 if (!$this->db->query($sql)) {
3819 $this->error = $this->db->lasterror();
3836 if ($rang >= $max) {
3840 $fieldposition =
'rang';
3841 if (in_array($this->table_element_line, array(
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3842 $fieldposition =
'position';
3845 $sql =
"UPDATE ".$this->db->prefix().$this->db->sanitize($this->table_element_line).
" SET ".$this->db->sanitize($fieldposition).
" = ".((int) $rang);
3846 $sql .=
" WHERE ".$this->db->sanitize($this->fk_element).
" = ".((int) $this->
id);
3847 $sql .=
" AND " . $this->db->sanitize($fieldposition) .
" = " . ((int) ($rang + 1));
3848 if (!$this->db->query($sql)) {
3849 $this->error = $this->db->lasterror();
3853 $sql =
"UPDATE ".$this->db->prefix().$this->table_element_line.
" SET ".$this->db->sanitize($fieldposition).
" = ".((int) ($rang + 1));
3854 $sql .=
' WHERE rowid = '.((int) $rowid);
3855 if (!$this->db->query($sql)) {
3856 $this->error = $this->db->lasterror();
3871 $fieldposition =
'rang';
3872 if (in_array($this->table_element_line, array(
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3873 $fieldposition =
'position';
3876 $sql =
"SELECT " . $this->db->sanitize($fieldposition) .
" FROM ".$this->db->prefix().$this->db->sanitize($this->table_element_line);
3877 $sql .=
" WHERE rowid = ".((int) $rowid);
3879 dol_syslog(get_class($this).
"::getRangOfLine", LOG_DEBUG);
3880 $resql = $this->db->query($sql);
3885 $row = $this->db->fetch_row($resql);
3897 $fieldposition =
'rang';
3898 if (in_array($this->table_element_line, array(
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3899 $fieldposition =
'position';
3902 $sql =
"SELECT rowid FROM ".$this->db->prefix().$this->db->sanitize($this->table_element_line);
3903 $sql .=
" WHERE ".$this->db->sanitize($this->fk_element).
" = ".((int) $this->
id);
3904 $sql .=
" AND " . $this->db->sanitize($fieldposition) .
" = ".((int) $rang);
3905 $resql = $this->db->query($sql);
3910 $row = $this->db->fetch_row($resql);
3925 if (empty($packaging) || !is_numeric($packaging) || (
float) $packaging <= 0) {
3928 $sign = ((float) $qty < 0 ? -1 : 1);
3929 $absqty = abs((
float) $qty);
3930 if ($absqty < (
float) $packaging) {
3931 return $sign * (float) $packaging;
3933 if ((
float)
price2num(fmod($absqty, (
float) $packaging),
'MS')) {
3934 $coeff = intval($absqty / (
float) $packaging) + 1;
3935 return $sign * (float)
price2num((
float) $packaging * $coeff,
'MS');
3950 $positionfield =
'rang';
3951 if (in_array($this->table_element, array(
'bom_bom',
'product_attribute'))) {
3952 $positionfield =
'position';
3955 $sql =
"SELECT max(".$this->db->sanitize($positionfield).
") FROM ".$this->db->prefix().$this->db->sanitize($this->table_element_line);
3956 $sql .=
" WHERE ".$this->db->sanitize($this->fk_element).
" = ".((int) $this->
id);
3959 if ($fk_parent_line) {
3960 $sql .=
" AND fk_parent_line = ".((int) $fk_parent_line);
3963 dol_syslog(get_class($this).
"::line_max", LOG_DEBUG);
3964 $resql = $this->db->query($sql);
3966 $row = $this->db->fetch_row($resql);
3968 if ($fk_parent_line) {
3969 if (!empty($row[0])) {
3992 if (!$this->table_element) {
3993 dol_syslog(get_class($this).
"::update_ref_ext was called on object with property table_element not defined", LOG_ERR);
3997 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
3998 $sql .=
" SET ref_ext = '".$this->db->escape($ref_ext).
"'";
4000 $sql .=
" WHERE ".(isset($this->table_rowid) ? $this->table_rowid :
'rowid').
" = ".((
int) $this->id);
4002 dol_syslog(get_class($this).
"::update_ref_ext", LOG_DEBUG);
4003 if ($this->db->query($sql)) {
4004 $this->ref_ext = $ref_ext;
4007 $this->error = $this->db->error();
4026 if (!$this->table_element) {
4027 $this->error =
'update_note was called on object with property table_element not defined';
4028 dol_syslog(get_class($this).
"::update_note was called on object with property table_element not defined", LOG_ERR);
4031 if (!in_array($suffix, array(
'',
'_public',
'_private'))) {
4032 $this->error =
'update_note Parameter suffix must be empty, \'_private\' or \'_public\'';
4033 dol_syslog(get_class($this).
"::update_note Parameter suffix must be empty, '_private' or '_public'", LOG_ERR);
4037 $newsuffix = $suffix;
4040 if ($this->table_element ==
'product' && $newsuffix ==
'_private') {
4043 if (in_array($this->table_element, array(
'actioncomm',
'adherent',
'advtargetemailing',
'cronjob',
'establishment'))) {
4044 $fieldusermod =
"fk_user_mod";
4045 } elseif ($this->table_element ==
'ecm_files') {
4046 $fieldusermod =
"fk_user_m";
4048 $fieldusermod =
"fk_user_modif";
4050 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
4051 $sql .=
" SET note".$this->db->sanitize($newsuffix).
" = ".(!empty($note) ? (
"'".$this->db->escape($note).
"'") :
"NULL");
4052 $sql .=
", ".$this->db->sanitize($fieldusermod).
" = ".((int) $user->id);
4053 $sql .=
" WHERE rowid = ".((int) $this->
id);
4055 dol_syslog(get_class($this).
"::update_note", LOG_DEBUG);
4056 if ($this->db->query($sql)) {
4057 if ($suffix ==
'_public') {
4058 $this->note_public = $note;
4059 } elseif ($suffix ==
'_private') {
4060 $this->note_private = $note;
4062 $this->note = $note;
4063 $this->note_private = $note;
4065 if (empty($notrigger)) {
4067 switch ($this->element) {
4069 $triggerName =
'COMPANY_MODIFY';
4072 $triggerName =
'BILL_MODIFY';
4074 case 'invoice_supplier':
4075 $triggerName =
'BILL_SUPPLIER_MODIFY';
4078 $triggerName =
'BILLREC_MODIFIY';
4080 case 'expensereport':
4081 $triggerName =
'EXPENSE_REPORT_MODIFY';
4084 $triggerName = (!empty($this->TRIGGER_PREFIX) ? $this->TRIGGER_PREFIX : strtoupper($this->element)) .
'_MODIFY';
4086 $ret = $this->call_trigger($triggerName, $user);
4093 $this->error = $this->db->lasterror();
4124 public function update_price($exclspec = 0, $roundingadjust =
'auto', $nodatabaseupdate = 0, $seller =
null)
4127 global
$conf, $hookmanager, $action;
4129 $parameters = array(
'exclspec' => $exclspec,
'roundingadjust' => $roundingadjust,
'nodatabaseupdate' => $nodatabaseupdate,
'seller' => $seller);
4130 $reshook = $hookmanager->executeHooks(
'updateTotalPrice', $parameters, $this, $action);
4133 } elseif ($reshook < 0) {
4138 $isElementForSupplier =
false;
4139 $roundTotalConstName =
'MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND';
4141 if ($this->element ==
'propal') {
4142 $MODULE =
"MODULE_DISALLOW_UPDATE_PRICE_PROPOSAL";
4143 } elseif ($this->element ==
'commande' || $this->element ==
'order') {
4144 $MODULE =
"MODULE_DISALLOW_UPDATE_PRICE_ORDER";
4145 } elseif ($this->element ==
'facture' || $this->element ==
'invoice') {
4146 $MODULE =
"MODULE_DISALLOW_UPDATE_PRICE_INVOICE";
4147 } elseif ($this->element ==
'facture_fourn' || $this->element ==
'supplier_invoice' || $this->element ==
'invoice_supplier' || $this->element ==
'invoice_supplier_rec') {
4148 $isElementForSupplier =
true;
4149 $MODULE =
"MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_INVOICE";
4150 } elseif ($this->element ==
'order_supplier' || $this->element ==
'supplier_order') {
4151 $isElementForSupplier =
true;
4152 $MODULE =
"MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_ORDER";
4153 } elseif ($this->element ==
'supplier_proposal') {
4154 $isElementForSupplier =
true;
4155 $MODULE =
"MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_PROPOSAL";
4157 if ($isElementForSupplier) {
4158 $roundTotalConstName =
'MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND_SUPPLIER';
4161 if (!empty($MODULE)) {
4164 foreach ($modsactivated as $mod) {
4172 include_once DOL_DOCUMENT_ROOT.
'/core/lib/price.lib.php';
4174 $forcedroundingmode = $roundingadjust;
4175 if ($forcedroundingmode ==
'auto' && isset(
$conf->global->{$roundTotalConstName})) {
4177 } elseif ($forcedroundingmode ==
'auto') {
4178 $forcedroundingmode =
'0';
4183 $multicurrency_tx = !empty($this->multicurrency_tx) ? $this->multicurrency_tx : 1;
4186 $fieldtva =
'total_tva';
4187 $fieldlocaltax1 =
'total_localtax1';
4188 $fieldlocaltax2 =
'total_localtax2';
4189 $fieldup =
'subprice';
4190 $base_price_type =
'HT';
4191 if ($this->element ==
'facture_fourn' || $this->element ==
'invoice_supplier') {
4195 if ($this->element ==
'invoice_supplier_rec') {
4198 if ($this->element ==
'expensereport') {
4202 $forcedroundingmode =
'0';
4203 $fieldup =
'value_unit';
4204 $base_price_type =
'TTC';
4207 $sql =
"SELECT rowid, qty, ".$this->db->sanitize($fieldup).
" as up, remise_percent,";
4208 $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,";
4209 $sql .=
' tva_tx as vatrate, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type,';
4210 $sql .=
' info_bits, product_type,';
4211 if ($this->element ==
'expensereport') {
4212 $sql .=
' comments as description';
4214 $sql .=
' description';
4216 if ($this->table_element_line ==
'facturedet') {
4217 $sql .=
', situation_percent';
4219 $sql .=
', multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc';
4220 $sql .=
" FROM ".$this->db->prefix().$this->db->sanitize($this->table_element_line);
4221 $sql .=
" WHERE ".$this->db->sanitize($this->fk_element).
" = ".((int) $this->
id);
4223 $product_field =
'product_type';
4224 if ($this->table_element_line ==
'contratdet') {
4225 $product_field =
'';
4227 if ($product_field) {
4228 $sql .=
" AND ".$this->db->sanitize($product_field).
" <> 9";
4231 $sql .=
' ORDER by rowid';
4233 dol_syslog(get_class($this).
"::update_price", LOG_DEBUG);
4235 $resql = $this->db->query($sql);
4237 $this->total_ht = 0;
4238 $this->total_tva = 0;
4239 $this->total_localtax1 = 0;
4240 $this->total_localtax2 = 0;
4241 $this->total_ttc = 0;
4242 $total_ht_by_vats = array();
4243 $total_tva_by_vats = array();
4244 $total_ttc_by_vats = array();
4245 $this->multicurrency_total_ht = 0;
4246 $this->multicurrency_total_tva = 0;
4247 $this->multicurrency_total_ttc = 0;
4251 $num = $this->db->num_rows($resql);
4254 $obj = $this->db->fetch_object($resql);
4257 $parameters = array(
'fk_element' => $obj->rowid);
4258 $reshook = $hookmanager->executeHooks(
'changeRoundingMode', $parameters, $this, $action);
4260 if (empty($reshook) && $forcedroundingmode ==
'0') {
4262 $localtax_array = array($obj->localtax1_type, $obj->localtax1_tx, $obj->localtax2_type, $obj->localtax2_tx);
4263 $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);
4265 $diff_when_using_price_ht =
price2num((
float) $tmpcal[1] - $obj->total_tva,
'MT', 1);
4266 $diff_on_current_total =
price2num($obj->total_ttc - $obj->total_ht - $obj->total_tva - $obj->total_localtax1 - $obj->total_localtax2,
'MT', 1);
4270 if ($diff_on_current_total) {
4272 $sqlfix =
"UPDATE ".$this->db->prefix().$this->table_element_line;
4273 $sqlfix .=
" SET ".$this->db->sanitize($fieldtva).
" = ".
price2num((
float) $tmpcal[1]).
", total_ttc = ".
price2num((
float) $tmpcal[2]);
4274 $sqlfix .=
", multicurrency_total_tva = ".price2num((
float) $tmpcal[17]).
", multicurrency_total_ttc = ".
price2num((
float) $tmpcal[18]);
4275 $sqlfix .=
" WHERE rowid = ".((int) $obj->rowid);
4276 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);
4277 $resqlfix = $this->db->query($sqlfix);
4279 dol_print_error($this->db,
'Failed to update line');
4281 $obj->total_tva = $tmpcal[1];
4282 $obj->total_ttc = $tmpcal[2];
4283 $obj->multicurrency_total_tva = $tmpcal[17];
4284 $obj->multicurrency_total_ttc = $tmpcal[18];
4285 } elseif ($diff_when_using_price_ht) {
4289 if ((
float) $tmpcal[0] == (
float) $obj->total_ht) {
4292 if ($obj->description !=
'(DEPOSIT)' && !
getDolGlobalInt(
'MAIN_DISABLE_AUTOFIX_CORRUPTED_LINES_WHEN_TOTAL_DOES_NOT_MATCH_RECALCULATION_FROM_UP')) {
4296 $sqlfix =
"UPDATE ".$this->db->prefix().$this->table_element_line;
4297 $sqlfix .=
" SET ".$this->db->sanitize($fieldtva).
" = ".
price2num((
float) $tmpcal[1]).
", total_ttc = ".
price2num((
float) $tmpcal[2]);
4298 $sqlfix .=
", multicurrency_total_tva = ".price2num((
float) $tmpcal[17]).
", multicurrency_total_ttc = ".
price2num((
float) $tmpcal[18]);
4299 $sqlfix .=
" WHERE rowid = ".((int) $obj->rowid);
4301 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);
4303 $resqlfix = $this->db->query($sqlfix);
4305 dol_print_error($this->db,
'Failed to update line');
4307 $obj->total_tva = $tmpcal[1];
4308 $obj->total_ttc = $tmpcal[2];
4309 $obj->multicurrency_total_tva = $tmpcal[17];
4310 $obj->multicurrency_total_ttc = $tmpcal[18];
4316 $this->total_ht += $obj->total_ht;
4317 $this->total_tva += $obj->total_tva;
4318 $this->total_localtax1 += $obj->total_localtax1;
4319 $this->total_localtax2 += $obj->total_localtax2;
4320 $this->total_ttc += $obj->total_ttc;
4321 $this->multicurrency_total_ht += $obj->multicurrency_total_ht;
4322 $this->multicurrency_total_tva += $obj->multicurrency_total_tva;
4323 $this->multicurrency_total_ttc += $obj->multicurrency_total_ttc;
4325 if (!isset($total_ht_by_vats[$obj->vatrate])) {
4326 $total_ht_by_vats[$obj->vatrate] = 0;
4328 if (!isset($total_tva_by_vats[$obj->vatrate])) {
4329 $total_tva_by_vats[$obj->vatrate] = 0;
4331 if (!isset($total_ttc_by_vats[$obj->vatrate])) {
4332 $total_ttc_by_vats[$obj->vatrate] = 0;
4334 $total_ht_by_vats[$obj->vatrate] += $obj->total_ht;
4335 $total_tva_by_vats[$obj->vatrate] += $obj->total_tva;
4336 $total_ttc_by_vats[$obj->vatrate] += $obj->total_ttc;
4338 if ($forcedroundingmode ==
'1') {
4339 if ($base_price_type ==
'TTC') {
4340 $tmpvat =
price2num($total_ttc_by_vats[$obj->vatrate] * $obj->vatrate / (100 + $obj->vatrate),
'MT', 1);
4342 $tmpvat =
price2num($total_ht_by_vats[$obj->vatrate] * $obj->vatrate / 100,
'MT', 1);
4344 $diff =
price2num($total_tva_by_vats[$obj->vatrate] - (
float) $tmpvat,
'MT', 1);
4347 $maxdiff = (10 * pow(10, -1 *
getDolGlobalInt(
'MAIN_MAX_DECIMALS_TOT', 0)));
4348 if (abs((
float) $diff) > $maxdiff) {
4350 $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.';
4352 $this->error = $errmsg;
4357 if ($base_price_type ==
'TTC') {
4358 $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);
4359 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);
4361 $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);
4362 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);
4365 $resqlfix = $this->db->query($sqlfix);
4368 dol_print_error($this->db,
'Failed to update line');
4371 $this->total_tva = (float)
price2num($this->total_tva - (
float) $diff,
'', 1);
4372 $total_tva_by_vats[$obj->vatrate] = (float)
price2num($total_tva_by_vats[$obj->vatrate] - (
float) $diff,
'', 1);
4373 if ($base_price_type ==
'TTC') {
4374 $this->total_ht = (float)
price2num($this->total_ht + (
float) $diff,
'', 1);
4375 $total_ht_by_vats[$obj->vatrate] = (float)
price2num($total_ht_by_vats[$obj->vatrate] + (
float) $diff,
'', 1);
4377 $this->total_ttc = (float)
price2num($this->total_ttc - (
float) $diff,
'', 1);
4378 $total_ttc_by_vats[$obj->vatrate] = (float)
price2num($total_ttc_by_vats[$obj->vatrate] - (
float) $diff,
'', 1);
4388 $this->total_ttc += isset($this->revenuestamp) ? $this->revenuestamp : 0;
4390 $this->multicurrency_total_ttc += isset($this->revenuestamp) ? ($this->revenuestamp * $multicurrency_tx) : 0;
4393 if (!empty($this->situation_cycle_ref) && !empty($this->situation_counter) && $this->situation_counter > 1 && method_exists($this,
'get_prev_sits')) {
4394 '@phan-var-force Facture $this';
4395 include_once DOL_DOCUMENT_ROOT.
'/compta/facture/class/facture.class.php';
4398 $prev_sits = $this->get_prev_sits();
4400 foreach ($prev_sits as $sit) {
4401 $this->total_ht -= $sit->total_ht;
4402 $this->total_tva -= $sit->total_tva;
4403 $this->total_localtax1 -= $sit->total_localtax1;
4404 $this->total_localtax2 -= $sit->total_localtax2;
4405 $this->total_ttc -= $sit->total_ttc;
4406 $this->multicurrency_total_ht -= $sit->multicurrency_total_ht;
4407 $this->multicurrency_total_tva -= $sit->multicurrency_total_tva;
4408 $this->multicurrency_total_ttc -= $sit->multicurrency_total_ttc;
4415 $this->total_ht = (float)
price2num($this->total_ht);
4416 $this->total_tva = (float)
price2num($this->total_tva);
4417 $this->total_localtax1 = (float)
price2num($this->total_localtax1);
4418 $this->total_localtax2 = (float)
price2num($this->total_localtax2);
4419 $this->total_ttc = (float)
price2num($this->total_ttc);
4421 $this->db->free($resql);
4424 $fieldht =
'total_ht';
4426 $fieldlocaltax1 =
'localtax1';
4427 $fieldlocaltax2 =
'localtax2';
4428 $fieldttc =
'total_ttc';
4430 if (in_array($this->element, array(
'propal',
'commande',
'facture',
'facturerec',
'supplier_proposal',
'order_supplier',
'facture_fourn',
'invoice_supplier',
'invoice_supplier_rec',
'expensereport'))) {
4431 $fieldtva =
'total_tva';
4434 if (!$error && empty($nodatabaseupdate)) {
4435 $sql =
"UPDATE ".$this->db->prefix().$this->table_element.
' SET';
4436 $sql .=
" ".$this->db->sanitize($fieldht).
" = ".((float)
price2num($this->total_ht,
'MT', 1)).
",";
4437 $sql .=
" ".$this->db->sanitize($fieldtva).
" = ".((float)
price2num($this->total_tva,
'MT', 1)).
",";
4438 $sql .=
" ".$this->db->sanitize($fieldlocaltax1).
" = ".((float)
price2num($this->total_localtax1,
'MT', 1)).
",";
4439 $sql .=
" ".$this->db->sanitize($fieldlocaltax2).
" = ".((float)
price2num($this->total_localtax2,
'MT', 1)).
",";
4440 $sql .=
" ".$this->db->sanitize($fieldttc).
" = ".((float)
price2num($this->total_ttc,
'MT', 1));
4441 $sql .=
", multicurrency_total_ht = ".((float)
price2num($this->multicurrency_total_ht,
'MT', 1));
4442 $sql .=
", multicurrency_total_tva = ".((float)
price2num($this->multicurrency_total_tva,
'MT', 1));
4443 $sql .=
", multicurrency_total_ttc = ".((float)
price2num($this->multicurrency_total_ttc,
'MT', 1));
4444 $sql .=
" WHERE rowid = ".((int) $this->
id);
4446 dol_syslog(get_class($this).
"::update_price", LOG_DEBUG);
4447 $resql = $this->db->query($sql);
4451 $this->error = $this->db->lasterror();
4452 $this->errors[] = $this->db->lasterror();
4457 $this->db->commit();
4460 $this->db->rollback();
4464 dol_print_error($this->db,
'Bad request in update_price');
4480 public function add_object_linked($origin =
null, $origin_id =
null, $f_user =
null, $notrigger = 0)
4483 global $user, $hookmanager, $action;
4486 if (empty($this->origin_type) && !empty($this->origin)) {
4487 $this->origin_type = $this->origin;
4489 $origin = (!empty($origin) ? $origin : $this->origin_type);
4490 $origin_id = (!empty($origin_id) ? $origin_id : $this->origin_id);
4491 $f_user = isset($f_user) ? $f_user : $user;
4494 if ($origin ==
'order') {
4495 $origin =
'commande';
4497 if ($origin ==
'invoice') {
4498 $origin =
'facture';
4500 if ($origin ==
'invoice_template') {
4501 $origin =
'facturerec';
4503 if ($origin ==
'supplierorder') {
4504 $origin =
'order_supplier';
4508 $targettype = $this->getElementType();
4510 $parameters = array(
'targettype' => $targettype);
4512 $reshook = $hookmanager->executeHooks(
'setLinkedObjectSourceTargetType', $parameters, $this, $action);
4514 if (!empty($hookmanager->resArray[
'targettype'])) {
4515 $targettype = $hookmanager->resArray[
'targettype'];
4522 $sql =
"INSERT INTO " . $this->db->prefix() .
"element_element (";
4523 $sql .=
"fk_source";
4524 $sql .=
", sourcetype";
4525 $sql .=
", fk_target";
4526 $sql .=
", targettype";
4527 $sql .=
") VALUES (";
4528 $sql .= ((int) $origin_id);
4529 $sql .=
", '" . $this->db->escape($origin) .
"'";
4530 $sql .=
", " . ((int) $this->
id);
4531 $sql .=
", '" . $this->db->escape($targettype) .
"'";
4534 dol_syslog(get_class($this) .
"::add_object_linked", LOG_DEBUG);
4535 if ($this->db->query($sql)) {
4539 if ($origin ===
'order_supplier' && $targettype ===
'invoice_supplier' && $this->element ===
'invoice_supplier' && (
int) $origin_id > 0 && (
int) $this->
id > 0) {
4540 $sourceinvoices = array();
4542 $sqlsources =
"SELECT DISTINCT rc.fk_invoice_supplier_source as rowid";
4543 $sqlsources .=
" FROM ".$this->db->prefix().
"societe_remise_except as rc";
4544 $sqlsources .=
" WHERE rc.fk_invoice_supplier = ".((int) $this->
id);
4545 $sqlsources .=
" AND rc.fk_invoice_supplier_source IS NOT NULL";
4547 $resqlsources = $this->db->query($sqlsources);
4548 if ($resqlsources) {
4549 while ($objsrc = $this->db->fetch_object($resqlsources)) {
4550 $srcid = (int) $objsrc->rowid;
4551 if ($srcid > 0 && $srcid !== (
int) $this->
id) {
4552 $sourceinvoices[$srcid] = $srcid;
4556 dol_syslog(get_class($this).
"::add_object_linked Failed to read supplier invoice discounts sources", LOG_WARNING);
4559 if (!empty($sourceinvoices)) {
4560 $existing = array();
4561 $sourcelist = implode(
',', $sourceinvoices);
4563 $sqlexists =
"SELECT fk_target";
4564 $sqlexists .=
" FROM ".$this->db->prefix().
"element_element";
4565 $sqlexists .=
" WHERE fk_source = ".((int) $origin_id);
4566 $sqlexists .=
" AND sourcetype = '".$this->db->escape($origin).
"'";
4567 $sqlexists .=
" AND targettype = '".$this->db->escape($targettype).
"'";
4568 $sqlexists .=
" AND fk_target IN (".$this->db->sanitize($sourcelist).
")";
4570 $resqlexists = $this->db->query($sqlexists);
4572 while ($objexist = $this->db->fetch_object($resqlexists)) {
4573 $existing[(int) $objexist->fk_target] = 1;
4576 dol_syslog(get_class($this).
"::add_object_linked Failed to read existing linked supplier invoices", LOG_WARNING);
4579 foreach ($sourceinvoices as $srcid) {
4580 if (!empty($existing[(
int) $srcid])) {
4584 $sqladd =
"INSERT INTO " . $this->db->prefix() .
"element_element (fk_source, sourcetype, fk_target, targettype)";
4585 $sqladd .=
" VALUES (".((int) $origin_id).
", '".$this->db->escape($origin).
"', ".((int) $srcid).
", '".$this->db->escape($targettype).
"')";
4586 $this->db->query($sqladd);
4593 $this->context[
'link_origin'] = $origin;
4594 $this->context[
'link_origin_id'] = $origin_id;
4596 $result = $this->call_trigger(
'OBJECT_LINK_INSERT', $f_user);
4603 $this->error = $this->db->lasterror();
4608 $this->db->commit();
4611 $this->db->rollback();
4625 $coreModule = array(
'knowledgemanagement',
'partnership',
'workstation',
'ticket',
'recruitment',
'eventorganization',
'asset');
4627 return ((!empty($this->module) && !in_array($this->module, $coreModule)) ? $this->module.
'_' :
'').$this->element;
4653 public function fetchObjectLinked($sourceid =
null, $sourcetype =
'', $targetid =
null, $targettype =
'', $clause =
'OR', $alsosametype = 1, $orderby =
'sourcetype', $loadalsoobjects = 1)
4655 global $hookmanager, $action;
4660 if ($this->
id > 0 && !empty($this->linkedObjectsFullLoaded[$this->
id])) {
4664 $this->linkedObjectsIds = array();
4665 $this->linkedObjects = array();
4668 $parameters = array(
4669 'sourceid' => $sourceid,
4670 'sourcetype' => $sourcetype,
4671 'targetid' => $targetid,
4672 'targettype' => $targettype,
4673 'clause' => $clause,
4674 'alsosametype' => $alsosametype,
4675 'orderby' => $orderby,
4676 'loadalsoobjects' => $loadalsoobjects
4678 $reshook = $hookmanager->executeHooks(
'fetchObjectLinked', $parameters, $this, $action);
4683 $justsource =
false;
4684 $justtarget =
false;
4685 $withtargettype =
false;
4686 $withsourcetype =
false;
4689 if (is_object($hookmanager)) {
4690 $parameters = array(
'sourcetype' => $sourcetype,
'sourceid' => $sourceid,
'targettype' => $targettype,
'targetid' => $targetid);
4691 $reshook = $hookmanager->executeHooks(
'setLinkedObjectSourceTargetType', $parameters, $this, $action);
4693 if (!empty($hookmanager->resArray[
'sourcetype'])) {
4694 $sourcetype = $hookmanager->resArray[
'sourcetype'];
4696 if (!empty($hookmanager->resArray[
'sourceid'])) {
4697 $sourceid = $hookmanager->resArray[
'sourceid'];
4699 if (!empty($hookmanager->resArray[
'targettype'])) {
4700 $targettype = $hookmanager->resArray[
'targettype'];
4702 if (!empty($hookmanager->resArray[
'targetid'])) {
4703 $targetid = $hookmanager->resArray[
'targetid'];
4708 if (!empty($sourceid) && !empty($sourcetype) && empty($targetid)) {
4710 if (!empty($targettype)) {
4711 $withtargettype =
true;
4714 if (!empty($targetid) && !empty($targettype) && empty($sourceid)) {
4716 if (!empty($sourcetype)) {
4717 $withsourcetype =
true;
4721 $sourceid = (!empty($sourceid) ? $sourceid :
$this->id);
4722 $targetid = (!empty($targetid) ? $targetid :
$this->id);
4723 $sourcetype = (!empty($sourcetype) ? $sourcetype : $this->getElementType());
4724 $targettype = (!empty($targettype) ? $targettype : $this->getElementType());
4733 $sql =
"SELECT rowid, fk_source, sourcetype, fk_target, targettype";
4734 $sql .=
" FROM ".$this->db->prefix().
"element_element";
4736 if ($justsource || $justtarget) {
4738 $sql .=
"fk_source = ".((int) $sourceid).
" AND sourcetype = '".$this->db->escape($sourcetype).
"'";
4739 if ($withtargettype) {
4740 $sql .=
" AND targettype = '".$this->db->escape($targettype).
"'";
4742 } elseif ($justtarget) {
4743 $sql .=
"fk_target = ".((int) $targetid).
" AND targettype = '".$this->db->escape($targettype).
"'";
4744 if ($withsourcetype) {
4745 $sql .=
" AND sourcetype = '".$this->db->escape($sourcetype).
"'";
4749 $sql .=
"(fk_source = ".((int) $sourceid).
" AND sourcetype = '".$this->db->escape($sourcetype).
"')";
4750 $sql .=
" ".$this->db->sanitize($clause).
" (fk_target = ".((int) $targetid).
" AND targettype = '".$this->db->escape($targettype).
"')";
4751 if ($loadalsoobjects && $this->
id > 0 && $sourceid == $this->
id && $sourcetype == $this->element && $targetid == $this->
id && $targettype == $this->element && $clause ==
'OR') {
4752 $this->linkedObjectsFullLoaded[
$this->id] =
true;
4755 $sql .= $this->db->order($orderby);
4757 dol_syslog(get_class($this).
"::fetchObjectLink", LOG_DEBUG);
4759 $resql = $this->db->query($sql);
4761 $num = $this->db->num_rows($resql);
4764 $obj = $this->db->fetch_object($resql);
4765 if ($justsource || $justtarget) {
4767 $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
4768 } elseif ($justtarget) {
4769 $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
4772 if ($obj->fk_source == $sourceid && $obj->sourcetype == $sourcetype) {
4773 $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
4775 if ($obj->fk_target == $targetid && $obj->targettype == $targettype) {
4776 $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
4782 if (!empty($this->linkedObjectsIds)) {
4783 $tmparray = $this->linkedObjectsIds;
4784 foreach ($tmparray as $objecttype => $objectids) {
4786 $element = $element_properties[
'element'];
4787 $classPath = $element_properties[
'classpath'];
4788 $classFile = $element_properties[
'classfile'];
4789 $className = $element_properties[
'classname'];
4790 $module = $element_properties[
'module'];
4794 if ($loadalsoobjects && (is_numeric($loadalsoobjects) || ($loadalsoobjects === $objecttype))) {
4796 if (class_exists($className)) {
4797 foreach ($objectids as $i => $objectid) {
4798 $object =
new $className($this->db);
4799 '@phan-var-force CommonObject $object';
4800 $ret =
$object->fetch($objectid);
4802 $this->linkedObjects[$objecttype][$i] =
$object;
4808 unset($this->linkedObjectsIds[$objecttype]);
4814 dol_print_error($this->db);
4827 if ($this->
id > 0 && !empty($this->linkedObjectsFullLoaded[$this->
id])) {
4828 unset($this->linkedObjectsFullLoaded[$this->
id]);
4846 public function updateObjectLinked($sourceid =
null, $sourcetype =
'', $targetid =
null, $targettype =
'', $f_user =
null, $notrigger = 0)
4849 $updatesource =
false;
4850 $updatetarget =
false;
4851 $f_user = isset($f_user) ? $f_user : $user;
4854 if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) {
4855 $updatesource =
true;
4856 } elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) {
4857 $updatetarget =
true;
4863 $sql =
"UPDATE " . $this->db->prefix() .
"element_element SET ";
4864 if ($updatesource) {
4865 $sql .=
"fk_source = " . ((int) $sourceid);
4866 $sql .=
", sourcetype = '" . $this->db->escape($sourcetype) .
"'";
4867 $sql .=
" WHERE fk_target = " . ((int) $this->
id);
4868 $sql .=
" AND targettype = '" . $this->db->escape($this->element) .
"'";
4869 } elseif ($updatetarget) {
4870 $sql .=
"fk_target = " . ((int) $targetid);
4871 $sql .=
", targettype = '" . $this->db->escape($targettype) .
"'";
4872 $sql .=
" WHERE fk_source = " . ((int) $this->
id);
4873 $sql .=
" AND sourcetype = '" . $this->db->escape($this->element) .
"'";
4876 dol_syslog(get_class($this) .
"::updateObjectLinked", LOG_DEBUG);
4877 if ($this->db->query($sql)) {
4880 $this->context[
'link_source_id'] = $sourceid;
4881 $this->context[
'link_source_type'] = $sourcetype;
4882 $this->context[
'link_target_id'] = $targetid;
4883 $this->context[
'link_target_type'] = $targettype;
4885 $result = $this->call_trigger(
'OBJECT_LINK_MODIFY', $f_user);
4892 $this->error = $this->db->lasterror();
4897 $this->db->commit();
4900 $this->db->rollback();
4918 public function deleteObjectLinked($sourceid =
null, $sourcetype =
'', $targetid =
null, $targettype =
'', $rowid = 0, $f_user =
null, $notrigger = 0)
4921 $deletesource =
false;
4922 $deletetarget =
false;
4923 $f_user = isset($f_user) ? $f_user : $user;
4925 if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) {
4926 $deletesource =
true;
4927 } elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) {
4928 $deletetarget =
true;
4931 $element = $this->getElementType();
4932 $sourceid = (!empty($sourceid) ? $sourceid :
$this->id);
4933 $sourcetype = (!empty($sourcetype) ? $sourcetype : $element);
4934 $targetid = (!empty($targetid) ? $targetid :
$this->id);
4935 $targettype = (!empty($targettype) ? $targettype : $element);
4941 $this->context[
'link_id'] = $rowid;
4942 $this->context[
'link_source_id'] = $sourceid;
4943 $this->context[
'link_source_type'] = $sourcetype;
4944 $this->context[
'link_target_id'] = $targetid;
4945 $this->context[
'link_target_type'] = $targettype;
4947 $result = $this->call_trigger(
'OBJECT_LINK_DELETE', $f_user);
4955 $sql =
"DELETE FROM " . $this->db->prefix() .
"element_element";
4958 $sql .=
" rowid = " . ((int) $rowid);
4960 if ($deletesource) {
4961 $sql .=
" fk_source = " . ((int) $sourceid) .
" AND sourcetype = '" . $this->db->escape($sourcetype) .
"'";
4962 $sql .=
" AND fk_target = " . ((int) $this->
id) .
" AND targettype = '" . $this->db->escape($element) .
"'";
4963 } elseif ($deletetarget) {
4964 $sql .=
" fk_target = " . ((int) $targetid) .
" AND targettype = '" . $this->db->escape($targettype) .
"'";
4965 $sql .=
" AND fk_source = " . ((int) $this->
id) .
" AND sourcetype = '" . $this->db->escape($element) .
"'";
4967 $sql .=
" (fk_source = " . ((int) $this->
id) .
" AND sourcetype = '" . $this->db->escape($element) .
"')";
4969 $sql .=
" (fk_target = " . ((int) $this->
id) .
" AND targettype = '" . $this->db->escape($element) .
"')";
4973 dol_syslog(get_class($this) .
"::deleteObjectLinked", LOG_DEBUG);
4974 if (!$this->db->query($sql)) {
4975 $this->error = $this->db->lasterror();
4976 $this->errors[] = $this->error;
4982 $this->db->commit();
4985 $this->db->rollback();
5001 if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
5004 if (!preg_match(
'/^[_a-zA-Z0-9]+$/', $field_select)) {
5005 dol_syslog(
'Invalid value $field_select for parameter '.$field_select.
' in call to getAllItemsLinkedByObjectID(). Must be a single field name.', LOG_ERR);
5010 $sql =
"SELECT ".$db->sanitize($field_select).
" FROM ".$db->prefix().$db->sanitize($table_element).
" WHERE ".$db->sanitize($field_where).
" = ".((int) $fk_object_where);
5011 $resql = $db->query($sql);
5014 if (!empty($resql)) {
5015 while ($res = $db->fetch_object($resql)) {
5016 $TRes[] = $res->{$field_select};
5033 if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
5039 $sql =
"SELECT COUNT(*) as nb FROM ".$db->prefix().$db->sanitize($table_element).
" WHERE ".$db->sanitize($field_where).
" = ".((int) $fk_object_where);
5040 $resql = $db->query($sql);
5043 $res = $db->fetch_object($resql);
5062 if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
5068 $sql =
"DELETE FROM ".$db->prefix().$table_element.
" WHERE ".$db->sanitize($field_where).
" = ".((int) $fk_object_where);
5069 $resql = $db->query($sql);
5071 if (empty($resql)) {
5089 public function setStatut($status, $elementId =
null, $elementType =
'', $trigkey =
'', $fieldstatus =
'')
5093 $savElementId = $elementId;
5095 $elementId = (!empty($elementId) ? $elementId :
$this->id);
5096 $elementTable = (!empty($elementType) ? $elementType : $this->table_element);
5100 if (empty($fieldstatus)) {
5101 if ($elementTable ==
'facture_rec') {
5102 $fieldstatus =
"suspended";
5104 if ($elementTable ==
'mailing') {
5105 $fieldstatus =
"statut";
5107 if ($elementTable ==
'cronjob') {
5108 $fieldstatus =
"status";
5110 if ($elementTable ==
'user') {
5111 $fieldstatus =
"statut";
5113 if ($elementTable ==
'expensereport') {
5114 $fieldstatus =
"fk_statut";
5116 if ($elementTable ==
'receptiondet_batch') {
5117 $fieldstatus =
"status";
5119 if ($elementTable ==
'prelevement_bons') {
5120 $fieldstatus =
"statut";
5122 if ($elementTable ==
'bank_account') {
5123 $fieldstatus =
"clos";
5125 if (isset($this->fields) && is_array($this->fields) && array_key_exists(
'status', $this->fields)) {
5126 $fieldstatus =
'status';
5129 if (empty($fieldstatus)) {
5130 $fieldstatus =
'fk_statut';
5134 $sql =
"UPDATE ".$this->db->prefix().$this->db->sanitize($elementTable);
5135 $sql .=
" SET ".$this->db->sanitize($fieldstatus).
" = ".((int) $status);
5138 if ($status == 1 && in_array($elementTable, array(
'expensereport',
'inventory'))) {
5139 $sql .=
", fk_user_valid = ".((int) $user->id);
5141 if ($status == 1 && in_array($elementTable, array(
'expensereport'))) {
5142 $sql .=
", date_valid = '".$this->db->idate(
dol_now()).
"'";
5144 if ($status == 1 && in_array($elementTable, array(
'inventory'))) {
5145 $sql .=
", date_validation = '".$this->db->idate(
dol_now()).
"'";
5147 $sql .=
" WHERE rowid = ".((int) $elementId);
5148 $sql .=
" AND ".$this->db->sanitize($fieldstatus).
" <> ".((int) $status);
5150 dol_syslog(get_class($this).
"::setStatut", LOG_DEBUG);
5151 $resql = $this->db->query($sql);
5155 $nb_rows_affected = $this->db->affected_rows($resql);
5157 if ($nb_rows_affected > 0) {
5158 if (empty($trigkey)) {
5160 if ($this->element ==
'supplier_proposal' && $status == 2) {
5161 $trigkey =
'SUPPLIER_PROPOSAL_SIGN';
5163 if ($this->element ==
'supplier_proposal' && $status == 3) {
5164 $trigkey =
'SUPPLIER_PROPOSAL_REFUSE';
5166 if ($this->element ==
'supplier_proposal' && $status == 4) {
5167 $trigkey =
'SUPPLIER_PROPOSAL_CLOSE';
5169 if ($this->element ==
'fichinter' && $status == 3) {
5170 $trigkey =
'FICHINTER_CLASSIFY_DONE';
5172 if ($this->element ==
'fichinter' && $status == 2) {
5173 $trigkey =
'FICHINTER_CLASSIFY_BILLED';
5175 if ($this->element ==
'fichinter' && $status == 1) {
5176 $trigkey =
'FICHINTER_CLASSIFY_UNBILLED';
5180 $this->context = array_merge($this->context, array(
'newstatus' => $status));
5182 if ($trigkey && $trigkey !=
'none') {
5186 $result = $this->call_trigger($trigkey, $user);
5197 $this->db->commit();
5199 if (empty($savElementId)) {
5201 if ($fieldstatus ==
'dispute_status') {
5202 $this->dispute_status = $status;
5203 } elseif ($fieldstatus ==
'tosell') {
5205 } elseif ($fieldstatus ==
'tobuy') {
5206 $this->status_buy = $status;
5207 } elseif ($fieldstatus ==
'tobatch') {
5208 $this->status_batch = $status;
5216 $this->db->rollback();
5217 dol_syslog(get_class($this).
"::setStatut ".$this->error, LOG_ERR);
5221 $this->error = $this->db->lasterror();
5222 $this->db->rollback();
5237 if (empty(
$id) && empty($ref)) {
5247 $sql =
"SELECT rowid, canvas";
5248 $sql .=
" FROM ".$this->db->prefix().$this->table_element;
5249 $sql .=
" WHERE entity IN (".getEntity($this->element).
")";
5251 $sql .=
" AND rowid = ".((int)
$id);
5254 $sql .=
" AND ref = '".$this->db->escape($ref).
"'";
5257 $resql = $this->db->query($sql);
5259 $obj = $this->db->fetch_object($resql);
5261 $this->canvas = $obj->canvas;
5267 dol_print_error($this->db);
5281 $sql =
"SELECT special_code FROM ".$this->db->prefix().$this->db->sanitize($this->table_element_line);
5282 $sql .=
" WHERE rowid = ".((int) $lineid);
5283 $resql = $this->db->query($sql);
5285 $row = $this->db->fetch_row($resql);
5286 return (!empty($row[0]) ? $row[0] : 0);
5309 if (!isset($this->childtables) || !is_array($this->childtables) || count($this->childtables) == 0) {
5310 dol_print_error(
null,
'Called isObjectUsed on a class with property this->childtables not defined');
5314 $arraytoscan = $this->childtables;
5316 $tmparray = array_keys($this->childtables);
5317 if (is_numeric($tmparray[0])) {
5318 $arraytoscan = array_flip($this->childtables);
5323 foreach ($arraytoscan as $table => $element) {
5327 if (isset($element[
'enabled']) && !empty($element[
'enabled'])) {
5328 $enabled = (int)
dol_eval((
string) $element[
'enabled'], 1);
5329 if (empty($enabled)) {
5335 $sql =
"SELECT COUNT(*) as nb";
5336 $sql .=
" FROM ".$this->db->prefix().$this->db->sanitize($table).
" as c";
5337 if (!empty($element[
'parent']) && !empty($element[
'parentkey'])) {
5338 $sql .=
", ".$this->db->prefix().$this->db->sanitize($element[
'parent']).
" as p";
5340 if (!empty($element[
'fk_element'])) {
5341 $sql .=
" WHERE c.".$this->db->sanitize($element[
'fk_element']).
" = ".((int)
$id);
5343 $sql .=
" WHERE c.".$this->db->sanitize($this->fk_element).
" = ".((int)
$id);
5345 if (!empty($element[
'parent']) && !empty($element[
'parentkey'])) {
5346 $sql .=
" AND c.".$this->db->sanitize($element[
'parentkey']).
" = p.rowid";
5348 if (!empty($element[
'parent']) && !empty($element[
'parenttypefield']) && !empty($element[
'parenttypevalue'])) {
5349 $sql .=
" AND c.".$this->db->sanitize($element[
'parenttypefield']).
" = '".$this->db->escape($element[
'parenttypevalue']).
"'";
5351 if (!empty($entity)) {
5352 if (!empty($element[
'parent']) && !empty($element[
'parentkey'])) {
5353 $sql .=
" AND p.entity = ".((int) $entity);
5355 $sql .=
" AND c.entity = ".((int) $entity);
5360 $resql = $this->db->query($sql);
5362 $obj = $this->db->fetch_object($resql);
5364 $langs->load(
"errors");
5366 $haschild += (int) $obj->nb;
5367 if (is_numeric($element)) {
5368 $this->errors[] = $langs->transnoentitiesnoconv(
"ErrorRecordHasAtLeastOneChildOfType", method_exists($this,
'getNomUrl') ? $this->getNomUrl() : $this->ref, $table);
5369 } elseif (is_string($element)) {
5370 $this->errors[] = $langs->transnoentitiesnoconv(
"ErrorRecordHasAtLeastOneChildOfType", method_exists($this,
'getNomUrl') ? $this->getNomUrl() : $this->ref, $langs->transnoentitiesnoconv($element));
5372 $this->errors[] = $langs->transnoentitiesnoconv(
"ErrorRecordHasAtLeastOneChildOfType", method_exists($this,
'getNomUrl') ? $this->getNomUrl() : $this->ref, $langs->transnoentitiesnoconv($element[
'name']));
5377 $this->errors[] = $this->db->lasterror();
5382 if ($haschild > 0) {
5383 $this->errors[] =
"ErrorRecordHasChildren";
5400 foreach ($this->lines as $key => $val) {
5402 if ($predefined == -1) {
5405 if ($predefined == 1 && $val->fk_product > 0) {
5408 if ($predefined == 0 && $val->fk_product <= 0) {
5411 if ($predefined == 2 && $val->fk_product > 0 && $val->product_type == 0) {
5414 if ($predefined == 3 && $val->fk_product > 0 && $val->product_type == 1) {
5421 dol_syslog(get_class($this).
'::hasProductsOrServices we found '.$nb.
' qualified lines of products/servcies');
5432 if (!empty($this->table_element_line) && ($this->table_element_line !=
'expeditiondet')) {
5433 $total_discount = 0.00;
5435 $sql =
"SELECT subprice as pu_ht, qty, remise_percent, total_ht";
5436 $sql .=
" FROM ".$this->db->prefix().$this->table_element_line;
5437 $sql .=
" WHERE ".$this->db->sanitize($this->fk_element).
" = ".((int) $this->
id);
5439 dol_syslog(get_class($this).
'::getTotalDiscount', LOG_DEBUG);
5440 $resql = $this->db->query($sql);
5442 $num = $this->db->num_rows($resql);
5445 $obj = $this->db->fetch_object($resql);
5447 $pu_ht = $obj->pu_ht;
5449 $total_ht = $obj->total_ht;
5451 $total_discount_line = (float)
price2num(($pu_ht * $qty) - $total_ht,
'MT');
5452 $total_discount += $total_discount_line;
5459 return (
float)
price2num($total_discount);
5481 if (empty($this->lines)) {
5482 return array(
'weight' => $totalWeight,
'volume' => $totalVolume,
'ordered' => $totalOrdered,
'toship' => $totalToShip);
5485 foreach ($this->lines as $line) {
5486 if (isset($line->qty_asked)) {
5487 $totalOrdered += $line->qty_asked;
5489 if (isset($line->qty_shipped)) {
5490 $totalToShip += $line->qty_shipped;
5491 } elseif ($line->element ==
'commandefournisseurdispatch' && isset($line->qty)) {
5492 if (empty($totalToShip)) {
5495 $totalToShip += $line->qty;
5499 if ($this->element ==
'shipping') {
5501 $qty = $line->qty_shipped ? $line->qty_shipped : 0;
5503 $qty = $line->qty ? $line->qty : 0;
5506 $weight = !empty($line->weight) ? $line->weight : 0;
5507 ($weight == 0 && !empty($line->product->weight)) ? $weight = $line->product->weight : 0;
5508 $volume = !empty($line->volume) ? $line->volume : 0;
5509 ($volume == 0 && !empty($line->product->volume)) ? $volume = $line->product->volume : 0;
5511 $weight_units = !empty($line->weight_units) ? $line->weight_units : 0;
5512 ($weight_units == 0 && !empty($line->product->weight_units)) ? $weight_units = $line->product->weight_units : 0;
5513 $volume_units = !empty($line->volume_units) ? $line->volume_units : 0;
5514 ($volume_units == 0 && !empty($line->product->volume_units)) ? $volume_units = $line->product->volume_units : 0;
5518 if (!empty($weight_units)) {
5519 $weightUnit = $weight_units;
5521 if (!empty($volume_units)) {
5522 $volumeUnit = $volume_units;
5525 if (empty($totalWeight)) {
5528 if (empty($totalVolume)) {
5533 if ($weight_units < 50) {
5534 $trueWeightUnit = pow(10, $weightUnit);
5535 $totalWeight += $weight * $qty * $trueWeightUnit;
5537 if ($weight_units == 99) {
5539 $trueWeightUnit = 0.45359237;
5540 $totalWeight += $weight * $qty * $trueWeightUnit;
5541 } elseif ($weight_units == 98) {
5543 $trueWeightUnit = 0.0283495;
5544 $totalWeight += $weight * $qty * $trueWeightUnit;
5546 $totalWeight += $weight * $qty;
5549 if ($volume_units < 50) {
5551 $trueVolumeUnit = pow(10, $volumeUnit);
5553 $totalVolume += $volume * $qty * $trueVolumeUnit;
5555 $totalVolume += $volume * $qty;
5559 return array(
'weight' => $totalWeight,
'volume' => $totalVolume,
'ordered' => $totalOrdered,
'toship' => $totalToShip);
5572 $extraparams = (!empty($this->extraparams) ? json_encode($this->extraparams) :
null);
5573 $extraparams =
dol_trunc($extraparams, 250);
5575 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
5576 $sql .=
" SET extraparams = ".(!empty($extraparams) ?
"'".$this->db->escape($extraparams).
"'" :
"null");
5577 $sql .=
" WHERE rowid = ".((int) $this->
id);
5579 dol_syslog(get_class($this).
"::setExtraParameters", LOG_DEBUG);
5580 $resql = $this->db->query($sql);
5582 $this->error = $this->db->lasterror();
5583 $this->db->rollback();
5586 $this->db->commit();
5609 global
$conf, $user, $langs,
$object, $hookmanager, $extrafields, $form;
5612 if (!is_object($extrafields)) {
5613 require_once DOL_DOCUMENT_ROOT.
'/core/class/extrafields.class.php';
5616 $extrafields->fetch_name_optionals_label($this->table_element_line);
5621 $dirtpls = array_merge(
$conf->modules_parts[
'tpl'], array($defaulttpldir));
5622 foreach ($dirtpls as
$module => $reldir) {
5626 $tpl = DOL_DOCUMENT_ROOT.$reldir.
'/objectline_create.tpl.php';
5629 if (empty(
$conf->file->strict_mode)) {
5630 $res = @include $tpl;
5632 $res = include $tpl;
5659 public function printObjectLines($action, $seller, $buyer, $selected = 0, $dateSelector = 0, $defaulttpldir =
'/core/tpl')
5661 global
$conf, $hookmanager, $langs, $user, $form, $extrafields,
$object;
5663 global $inputalsopricewithtax, $usemargins, $disableedit, $disablemove, $disableremove, $outputalsopricetotalwithtax;
5667 if (
isModEnabled(
'margin') && !empty($this->element) && in_array($this->element, array(
'facture',
'facturerec',
'propal',
'commande'))) {
5671 $num = count($this->lines);
5674 if (!is_object($extrafields)) {
5675 require_once DOL_DOCUMENT_ROOT.
'/core/class/extrafields.class.php';
5678 $extrafields->fetch_name_optionals_label($this->table_element_line);
5680 if (method_exists($this,
'loadExpeditions')) {
5682 $this->loadExpeditions();
5685 $parameters = array();
5686 $reshook = $hookmanager->executeHooks(
'printObjectLinesBlock', $parameters, $this, $action);
5687 if (empty($reshook)) {
5688 $parameters = array(
'num' => $num,
'dateSelector' => $dateSelector,
'seller' => $seller,
'buyer' => $buyer,
'selected' => $selected,
'table_element_line' => $this->table_element_line);
5689 $reshook = $hookmanager->executeHooks(
'printObjectLineTitle', $parameters, $this, $action);
5690 if (empty($reshook)) {
5694 $dirtpls = array_merge(
$conf->modules_parts[
'tpl'], array($defaulttpldir));
5695 foreach ($dirtpls as
$module => $reldir) {
5700 $tpl = DOL_DOCUMENT_ROOT.$reldir.
'/objectline_title.tpl.php';
5702 if (file_exists($tpl)) {
5703 if (empty(
$conf->file->strict_mode)) {
5704 $res = @include $tpl;
5706 $res = include $tpl;
5717 print
"<!-- begin printObjectLines() -->\n";
5718 foreach ($this->lines as $line) {
5722 if (is_object($hookmanager)) {
5723 if (empty($line->fk_parent_line)) {
5724 $parameters = array(
'line' => $line,
'num' => $num,
'i' => $i,
'dateSelector' => $dateSelector,
'seller' => $seller,
'buyer' => $buyer,
'selected' => $selected,
'table_element_line' => $line->table_element,
'defaulttpldir' => $defaulttpldir);
5725 $reshook = $hookmanager->executeHooks(
'printObjectLine', $parameters, $this, $action);
5727 $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);
5728 $reshook = $hookmanager->executeHooks(
'printObjectSubLine', $parameters, $this, $action);
5731 if (empty($reshook)) {
5732 $this->printObjectLine($action, $line,
'', $num, $i, $dateSelector, $seller, $buyer, $selected, $extrafields, $defaulttpldir);
5737 print
"<!-- end printObjectLines() -->\n";
5758 public function printObjectLine($action, $line, $var, $num, $i, $dateSelector, $seller, $buyer, $selected = 0, $extrafields =
null, $defaulttpldir =
'/core/tpl')
5762 global $disableedit, $disablemove, $disableremove;
5769 if ($action !=
'editline' || $selected != $line->id) {
5771 if (!empty($line->fk_product) && $line->fk_product > 0) {
5772 $product_static =
new Product($this->db);
5773 $product_static->fetch($line->fk_product);
5775 $product_static->ref = (string) $line->ref;
5777 $product_static->label = !empty($line->label) ? $line->label :
"";
5779 $text = $product_static->getNomUrl(1);
5784 if (property_exists($this,
'socid') && !empty($this->socid) && !is_object($this->thirdparty)) {
5785 dol_print_error(
null,
'Error: Method printObjectLine was called on an object and object->fetch_thirdparty was not done before');
5790 $prod->fetch($line->fk_product);
5792 $outputlangs = $langs;
5794 if (
GETPOST(
'lang_id',
'aZ09')) {
5795 $newlang =
GETPOST(
'lang_id',
'aZ09');
5797 if (
getDolGlobalString(
'PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE') && empty($newlang) && is_object($this->thirdparty)) {
5798 $newlang = $this->thirdparty->default_lang;
5800 if (!empty($newlang)) {
5802 $outputlangs->setDefaultLang($newlang);
5805 $label = (!empty(
$prod->multilangs[$outputlangs->defaultlang][
"label"])) ?
$prod->multilangs[$outputlangs->defaultlang][
"label"] : $line->product_label;
5807 $label = $line->product_label;
5811 $text .=
' - '.(!empty($line->label) ? $line->label : $label);
5812 $description .= (
getDolGlobalInt(
'PRODUIT_DESC_IN_FORM_ACCORDING_TO_DEVICE') ?
'' : (!empty($line->description) ?
dol_htmlentitiesbr($line->description) :
''));
5816 if (empty((
float) $line->subprice_ttc) && $line->qty) {
5819 if ($line->remise_percent != 100) {
5821 $line->subprice_ttc = (float)
price2num($line->total_ttc * ($line->situation_percent ? 100 / $line->situation_percent : 1) / $line->qty / (1 - $line->remise_percent / 100),
'MU');
5824 $line->subprice_ttc = (float)
price2num((!empty($line->subprice) ? $line->subprice : 0) * (1 + ((!empty($line->tva_tx) ? $line->tva_tx : 0) / 100)),
'MU');
5827 $line->pu_ttc = $line->subprice_ttc;
5834 if (isset($this->expeditions[$line->id])) {
5836 $qty_shipped = $this->expeditions[$line->id];
5838 $disableedit = ($qty_shipped > 0) && ($qty_shipped >= $line->qty);
5840 $dirtpls = array_merge(
$conf->modules_parts[
'tpl'], array($defaulttpldir));
5841 foreach ($dirtpls as
$module => $reldir) {
5846 $tpl = DOL_DOCUMENT_ROOT.$reldir.
'/objectline_view.tpl.php';
5849 if (file_exists($tpl)) {
5850 if (empty(
$conf->file->strict_mode)) {
5851 $res = @include $tpl;
5853 $res = include $tpl;
5863 if ($this->
status == 0 && $action ==
'editline' && $selected == $line->id) {
5865 $label = (!empty($line->label) ? $line->label : (($line->fk_product > 0) ? $line->product_label :
''));
5867 $line->subprice_ttc = (float)
price2num($line->subprice * (1 + ($line->tva_tx / 100)),
'MU');
5868 $line->pu_ttc = $line->subprice_ttc;
5873 $dirtpls = array_merge(
$conf->modules_parts[
'tpl'], array($defaulttpldir));
5874 foreach ($dirtpls as
$module => $reldir) {
5878 $tpl = DOL_DOCUMENT_ROOT.$reldir.
'/objectline_edit.tpl.php';
5881 if (empty(
$conf->file->strict_mode)) {
5882 $res = @include $tpl;
5884 $res = include $tpl;
5909 global $langs, $hookmanager, $form, $action;
5911 print
'<!-- printOriginLinesList '.get_class($this).
' -->'.
"\n";
5912 print
'<tr class="liste_titre">';
5913 print
'<td class="linecolref">'.$langs->trans(
'Ref').
'</td>';
5914 print
'<td class="linecoldescription">'.$langs->trans(
'Description').
'</td>';
5915 print
'<td class="linecolvat right">'.$langs->trans(
'VATRate').
'</td>';
5916 print
'<td class="linecoluht right">'.$langs->trans(
'PriceUHT').
'</td>';
5918 print
'<td class="linecoluht_currency right">'.$langs->trans(
'PriceUHTCurrency').
'</td>';
5920 print
'<td class="linecolqty right">'.$langs->trans(
'Qty').
'</td>';
5922 print
'<td class="linecoluseunit left">'.$langs->trans(
'Unit').
'</td>';
5924 print
'<td class="linecoldiscount right">'.$langs->trans(
'ReductionShort').
'</td>';
5925 print
'<td class="linecolht right">'.$langs->trans(
'TotalHT').
'</td>';
5926 print
'<td class="center">';
5927 print $form->showCheckAddButtons(
'checkforselect', 1);
5932 if (!empty($this->lines)) {
5933 foreach ($this->lines as $line) {
5936 if (is_object($hookmanager)) {
5937 $parameters = array(
'line' => $line,
'i' => $i,
'restrictlist' => $restrictlist,
'selectedLines' => $selectedLines);
5938 if (!empty($line->fk_parent_line)) {
5939 $parameters[
'fk_parent_line'] = $line->fk_parent_line;
5941 $reshook = $hookmanager->executeHooks(
'printOriginObjectLine', $parameters, $this, $action);
5943 if (empty($reshook)) {
5944 $this->printOriginLine($line,
'', $restrictlist,
'/core/tpl', $selectedLines);
5965 public function printOriginLine($line, $var, $restrictlist =
'', $defaulttpldir =
'/core/tpl', $selectedLines = array())
5967 global $langs,
$conf;
5970 if (!empty($line->date_start)) {
5975 if ($line->date_debut_reel) {
5979 if (!empty($line->date_end)) {
5981 $date_end = $line->date_end;
5983 $date_end = $line->date_fin_prevue;
5984 if ($line->date_fin_reel) {
5985 $date_end = $line->date_fin_reel;
5990 $this->tpl[
'id'] = $line->id;
5992 $this->tpl[
'label'] =
'';
5993 if (!empty($line->fk_parent_line)) {
5994 $this->tpl[
'label'] .= img_picto(
'',
'rightarrow.png');
5997 if (((
int) $line->info_bits & 2) == 2) {
5999 if (property_exists($this,
'socid')) {
6001 $discount->fk_soc = $this->socid;
6003 $discount->socid = $this->socid;
6005 $this->tpl[
'label'] .= $discount->getNomUrl(0,
'discount');
6006 } elseif (!empty($line->fk_product)) {
6007 $productstatic =
new Product($this->db);
6008 $productstatic->id = $line->fk_product;
6009 $productstatic->ref = (string) $line->ref;
6010 $productstatic->type = $line->fk_product_type;
6011 if (empty($productstatic->ref)) {
6012 $line->fetch_product();
6013 $productstatic = $line->product;
6016 $this->tpl[
'label'] .= $productstatic->getNomUrl(1);
6018 $this->tpl[
'label'] .=
' - '.(!empty($line->label) ? $line->label : $line->product_label);
6020 if ($line->product_type == 1 && (
$date_start || $date_end)) {
6024 $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"')));
6025 if (!empty($line->desc)) {
6026 $this->tpl[
'label'] .= $line->desc;
6029 $this->tpl[
'label'] .= ($line->label ?
' '.$line->label :
'');
6033 if ($line->product_type == 1 && (
$date_start || $date_end)) {
6038 if (!empty($line->desc)) {
6039 '@phan-var-force OrderLine|FactureLigne|ContratLigne|FactureFournisseurLigneRec|SupplierInvoiceLine|SupplierProposalLine $line';
6040 if ($line->desc ==
'(CREDIT_NOTE)') {
6042 $discount->fetch($line->fk_remise_except);
6043 $this->tpl[
'description'] = $langs->transnoentities(
"DiscountFromCreditNote", $discount->getNomUrl(0));
6044 } elseif ($line->desc ==
'(DEPOSIT)') {
6046 $discount->fetch($line->fk_remise_except);
6047 $this->tpl[
'description'] = $langs->transnoentities(
"DiscountFromDeposit", $discount->getNomUrl(0));
6048 } elseif ($line->desc ==
'(EXCESS RECEIVED)') {
6050 $discount->fetch($line->fk_remise_except);
6051 $this->tpl[
'description'] = $langs->transnoentities(
"DiscountFromExcessReceived", $discount->getNomUrl(0));
6052 } elseif ($line->desc ==
'(EXCESS PAID)') {
6054 $discount->fetch($line->fk_remise_except);
6055 $this->tpl[
'description'] = $langs->transnoentities(
"DiscountFromExcessPaid", $discount->getNomUrl(0));
6057 $this->tpl[
'description'] =
dol_trunc($line->desc, 60);
6060 $this->tpl[
'description'] =
' ';
6064 $this->tpl[
'vat_rate'] =
vatrate($line->tva_tx,
true);
6065 $this->tpl[
'vat_rate'] .= (((int) $line->info_bits & 1) == 1) ?
'*' :
'';
6066 if (!empty($line->vat_src_code) && !preg_match(
'/\(/', $this->tpl[
'vat_rate'])) {
6067 $this->tpl[
'vat_rate'] .=
' ('.$line->vat_src_code.
')';
6070 $this->tpl[
'price'] =
price($line->subprice);
6071 $this->tpl[
'total_ht'] =
price($line->total_ht);
6072 $this->tpl[
'multicurrency_price'] =
price($line->multicurrency_subprice);
6073 $this->tpl[
'qty'] = (((int) $line->info_bits & 2) != 2) ? $line->qty :
' ';
6075 $this->tpl[
'unit'] = $line->getLabelOfUnit(
'long', $langs);
6076 $this->tpl[
'unit_short'] = $line->getLabelOfUnit(
'short', $langs);
6079 $this->tpl[
'remise_percent'] = (((int) $line->info_bits & 2) != 2) ?
vatrate((
string) $line->remise_percent,
true) :
' ';
6082 $this->tpl[
'strike'] = 0;
6084 $this->tpl[
'strike'] = 1;
6085 } elseif (defined(
'SUBTOTALS_SPECIAL_CODE') && $line->special_code == SUBTOTALS_SPECIAL_CODE) {
6090 $this->tpl[
'strike'] = 1;
6095 $dirtpls = array_merge(
$conf->modules_parts[
'tpl'], array($defaulttpldir));
6096 foreach ($dirtpls as
$module => $reldir) {
6100 $tpl = DOL_DOCUMENT_ROOT.$reldir.
'/originproductline.tpl.php';
6103 if (empty(
$conf->file->strict_mode)) {
6104 $res = @include $tpl;
6106 $res = include $tpl;
6133 $sql =
"INSERT INTO ".$this->db->prefix().
"element_resources (";
6134 $sql .=
"resource_id";
6135 $sql .=
", resource_type";
6136 $sql .=
", element_id";
6137 $sql .=
", element_type";
6139 $sql .=
", mandatory";
6140 $sql .=
") VALUES (";
6141 $sql .= ((int) $resource_id);
6142 $sql .=
", '".$this->db->escape($resource_type).
"'";
6143 $sql .=
", '".$this->db->escape((
string) $this->
id).
"'";
6144 $sql .=
", '".$this->db->escape($this->element).
"'";
6145 $sql .=
", '".$this->db->escape((
string) $busy).
"'";
6146 $sql .=
", '".$this->db->escape((
string) $mandatory).
"'";
6149 dol_syslog(get_class($this).
"::add_element_resource", LOG_DEBUG);
6150 if ($this->db->query($sql)) {
6152 $result = $this->call_trigger(strtoupper($this->TRIGGER_PREFIX).
'_ADD_RESOURCE', $user);
6154 $this->db->rollback();
6158 $this->db->commit();
6161 $this->error = $this->db->lasterror();
6162 $this->db->rollback();
6183 $sql =
"DELETE FROM ".$this->db->prefix().
"element_resources";
6184 $sql .=
" WHERE rowid = ".((int) $rowid);
6186 dol_syslog(get_class($this).
"::delete_resource", LOG_DEBUG);
6188 $resql = $this->db->query($sql);
6190 $this->error = $this->db->lasterror();
6191 $this->db->rollback();
6195 $result = $this->call_trigger(strtoupper($this->TRIGGER_PREFIX).
'_DELETE_RESOURCE', $user);
6197 $this->db->rollback();
6201 $this->db->commit();
6215 if (isset($this->lines) && is_array($this->lines)) {
6216 $nboflines = count($this->lines);
6217 for ($i = 0; $i < $nboflines; $i++) {
6218 if (is_object($this->lines[$i])) {
6219 $this->lines[$i] = clone $this->lines[$i];
6238 protected function commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams =
null)
6240 global
$conf, $langs, $hookmanager, $action;
6242 $srctemplatepath =
'';
6244 $parameters = array(
'modelspath' => $modelspath,
'modele' => $modele,
'outputlangs' => $outputlangs,
'hidedetails' => $hidedetails,
'hidedesc' => $hidedesc,
'hideref' => $hideref,
'moreparams' => $moreparams);
6245 $reshook = $hookmanager->executeHooks(
'commonGenerateDocument', $parameters, $this, $action);
6247 if (!empty($reshook)) {
6251 dol_syslog(
"commonGenerateDocument modele=".$modele.
" outputlangs->defaultlang=".(is_object($outputlangs) ? $outputlangs->defaultlang :
'null'));
6253 if (empty($modele)) {
6254 $this->error =
'BadValueForParameterModele';
6259 $err = error_reporting();
6261 @set_time_limit(120);
6262 error_reporting($err);
6265 $tmp = explode(
':', $modele, 2);
6266 $saved_model = $modele;
6267 if (!empty($tmp[1])) {
6269 $srctemplatepath = $tmp[1];
6271 if (!preg_match(
'/^'.preg_quote(DOL_DATA_ROOT,
'/').
'\/(ecm|doctemplates)/', $srctemplatepath)) {
6272 $this->error =
'BadDirForTemplateFile';
6281 $dirmodels = array(
'/');
6282 if (is_array(
$conf->modules_parts[
'models'])) {
6283 $dirmodels = array_merge($dirmodels,
$conf->modules_parts[
'models']);
6285 foreach ($dirmodels as $reldir) {
6286 foreach (array(
'doc',
'pdf') as $prefix) {
6287 if (in_array(get_class($this), array(
'Adherent'))) {
6289 $file = $prefix.
"_".$modele.
".class.php";
6292 $file = $prefix.
"_".$modele.
".modules.php";
6299 if (file_exists($file)) {
6301 $classname = $prefix.
'_'.$modele;
6310 if ($filefound ===
'' || $classname ===
'') {
6311 $this->error = $langs->trans(
"Error").
' Failed to load doc generator with modelpaths='.$modelspath.
' - modele='.$modele;
6312 $this->errors[] = $this->error;
6323 require_once $filefound;
6325 $obj =
new $classname($this->db);
6337 '@phan-var-force ModelePDFMember $obj';
6341 if ($obj->type ==
'odt' && empty($srctemplatepath)) {
6342 $varfortemplatedir = $obj->scandir;
6346 $listoffiles = array();
6349 $listofdir = explode(
',', $dirtoscan);
6350 foreach ($listofdir as $key => $tmpdir) {
6351 $tmpdir = trim($tmpdir);
6352 $tmpdir = preg_replace(
'/DOL_DATA_ROOT/', DOL_DATA_ROOT, $tmpdir);
6354 unset($listofdir[$key]);
6357 if (is_dir($tmpdir)) {
6358 $tmpfiles =
dol_dir_list($tmpdir,
'files', 0,
'\.od(s|t)$',
'',
'name', SORT_ASC, 0);
6359 if (count($tmpfiles)) {
6360 $listoffiles = array_merge($listoffiles, $tmpfiles);
6365 if (count($listoffiles)) {
6366 foreach ($listoffiles as $record) {
6367 $srctemplatepath = $record[
'fullname'];
6373 if (empty($srctemplatepath)) {
6374 $this->error =
'ErrorGenerationAskedForOdtTemplateWithSrcFileNotDefined';
6379 if ($obj->type ==
'odt' && !empty($srctemplatepath)) {
6381 dol_syslog(
"Failed to locate template file ".$srctemplatepath, LOG_WARNING);
6382 $this->error =
'ErrorGenerationAskedForOdtTemplateWithSrcFileNotFound';
6389 $sav_charset_output = empty($outputlangs->charset_output) ?
'' : $outputlangs->charset_output;
6392 $this->model_pdf = $saved_model;
6397 $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath,
'member', 1,
'tmp_cards');
6399 $resultwritefile = -1;
6400 dol_syslog(
"Error generating document - Provided ".get_class($this).
" to ".get_class($obj).
"::write_file()", LOG_ERR);
6404 if ($this instanceof
Don) {
6405 $resultwritefile = $obj->write_file($this, $outputlangs );
6407 $resultwritefile = -1;
6408 dol_syslog(
"Error generating document - Provided ".get_class($this).
" to Don::write_file()", LOG_ERR);
6412 '@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';
6413 $this->context[
'moreparams'] = $moreparams;
6414 $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, $hidedetails, $hidedesc, $hideref);
6416 }
catch (\Throwable $e) {
6417 $resultwritefile = -1;
6418 $this->error = $e->getMessage();
6419 dol_syslog(
"Exception in write_file() for ".get_class($this).
": ".$e->getMessage(), LOG_ERR);
6424 if ($resultwritefile > 0) {
6425 $outputlangs->charset_output = $sav_charset_output;
6428 require_once DOL_DOCUMENT_ROOT.
'/core/lib/files.lib.php';
6432 if (!empty($obj->result[
'fullpath'])) {
6433 $destfull = $obj->result[
'fullpath'];
6436 $update_main_doc_field = 0;
6437 if (!empty($obj->update_main_doc_field)) {
6438 $update_main_doc_field = 1;
6444 $this->indexFile($destfull, $update_main_doc_field);
6447 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);
6453 $this->warnings = $obj->warnings;
6457 $outputlangs->charset_output = $sav_charset_output;
6458 if (empty($this->error)) {
6459 $this->error = $obj->error;
6461 if (empty($this->errors)) {
6462 $this->errors = $obj->errors;
6464 $this->warnings = $obj->warnings;
6465 dol_syslog(
"Error generating document for ".__CLASS__.
". Error: ".$this->error, LOG_ERR);
6479 public function indexFile($destfull, $update_main_doc_field)
6481 global
$conf, $user;
6483 $upload_dir = dirname($destfull);
6484 $destfile = basename($destfull);
6485 $rel_dir = preg_replace(
'/^'.preg_quote(DOL_DATA_ROOT,
'/').
'/',
'', $upload_dir);
6487 if (!preg_match(
'/[\\/]temp[\\/]|[\\/]thumbs|\.meta$/', $rel_dir)) {
6488 $filename = basename($destfile);
6489 $rel_dir = preg_replace(
'/[\\/]$/',
'', $rel_dir);
6490 $rel_dir = preg_replace(
'/^[\\/]/',
'', $rel_dir);
6492 include_once DOL_DOCUMENT_ROOT.
'/ecm/class/ecmfiles.class.php';
6493 $ecmfile =
new EcmFiles($this->db);
6494 $result = $ecmfile->fetch(0,
'', ($rel_dir ? $rel_dir.
'/' :
'').$filename);
6497 $setsharekey =
false;
6499 !empty($this->TRIGGER_PREFIX)
6502 $setsharekey =
true;
6505 if ($this->element ==
'propal' || $this->element ==
'proposal') {
6507 $setsharekey =
true;
6510 $setsharekey =
true;
6513 if ($this->element ==
'facture' &&
getDolGlobalInt(
"INVOICE_ALLOW_EXTERNAL_DOWNLOAD")) {
6514 $setsharekey =
true;
6516 if ($this->element ==
'bank_account' &&
getDolGlobalInt(
"BANK_ACCOUNT_ALLOW_EXTERNAL_DOWNLOAD")) {
6517 $setsharekey =
true;
6519 if ($this->element ==
'contrat' &&
getDolGlobalInt(
"CONTRACT_ALLOW_EXTERNAL_DOWNLOAD")) {
6520 $setsharekey =
true;
6522 if ($this->element ==
'supplier_proposal' &&
getDolGlobalInt(
"SUPPLIER_PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD")) {
6523 $setsharekey =
true;
6525 if ($this->element ==
'order_supplier' &&
getDolGlobalInt(
"SUPPLIER_ORDER_ALLOW_EXTERNAL_DOWNLOAD")) {
6526 $setsharekey =
true;
6528 if ($this->element ==
'invoice_supplier' &&
getDolGlobalInt(
"SUPPLIER_INVOICE_ALLOW_EXTERNAL_DOWNLOAD")) {
6529 $setsharekey =
true;
6531 if ($this->element ==
'societe_rib' &&
getDolGlobalInt(
"SOCIETE_RIB_ALLOW_ONLINESIGN")) {
6532 $setsharekey =
true;
6536 if (empty($ecmfile->share)) {
6537 require_once DOL_DOCUMENT_ROOT.
'/core/lib/security2.lib.php';
6544 $ecmfile->fullpath_orig =
'';
6545 $ecmfile->gen_or_uploaded =
'generated';
6546 $ecmfile->description =
'';
6547 $ecmfile->keywords =
'';
6548 $ecmfile->src_object_type = $this->table_element;
6550 $result = $ecmfile->update($user);
6552 setEventMessages($ecmfile->error, $ecmfile->errors,
'warnings');
6556 $ecmfile->entity =
$conf->entity;
6557 $ecmfile->filepath = $rel_dir;
6558 $ecmfile->filename = $filename;
6560 $ecmfile->fullpath_orig =
'';
6561 $ecmfile->gen_or_uploaded =
'generated';
6562 $ecmfile->description =
'';
6563 $ecmfile->keywords =
'';
6564 $ecmfile->src_object_type = $this->table_element;
6567 $result = $ecmfile->create($user);
6569 setEventMessages($ecmfile->error, $ecmfile->errors,
'warnings');
6579 if ($update_main_doc_field && !empty($this->table_element)) {
6580 $sql =
"UPDATE ".$this->db->prefix().$this->table_element.
" SET last_main_doc = '".$this->db->escape($ecmfile->filepath.
"/".$ecmfile->filename).
"'";
6581 $sql .=
" WHERE rowid = ".((int) $this->
id);
6583 $resql = $this->db->query($sql);
6585 dol_print_error($this->db);
6588 $this->last_main_doc = $ecmfile->filepath.
'/'.$ecmfile->filename;
6608 if (file_exists($file_osencoded)) {
6609 require_once DOL_DOCUMENT_ROOT.
'/core/lib/images.lib.php';
6612 $maxwidthsmall = $tmparraysize[
'maxwidthsmall'];
6613 $maxheightsmall = $tmparraysize[
'maxheightsmall'];
6614 $maxwidthmini = $tmparraysize[
'maxwidthmini'];
6615 $maxheightmini = $tmparraysize[
'maxheightmini'];
6620 vignette($file_osencoded, $maxwidthsmall, $maxheightsmall,
'_small', $quality);
6624 vignette($file_osencoded, $maxwidthmini, $maxheightmini,
'_mini', $quality);
6672 return GETPOST($fieldname, $type, 3);
6675 if (isset($alternatevalue)) {
6676 return $alternatevalue;
6679 $newelement = $this->element;
6680 if ($newelement ==
'facture') {
6681 $newelement =
'invoice';
6683 if ($newelement ==
'commande') {
6684 $newelement =
'order';
6686 if (empty($newelement)) {
6687 dol_syslog(
"Ask a default value using common method getDefaultCreateValueForField on an object with no property ->element defined. Return empty string.", LOG_WARNING);
6691 $keyforfieldname = strtoupper($newelement.
'_DEFAULT_'.$fieldname);
6718 if (!$this->element) {
6721 if (!($this->
id > 0)) {
6724 if (is_array($this->array_languages)) {
6728 $this->array_languages = array();
6730 $element = $this->element;
6731 if ($element ==
'categorie') {
6732 $element =
'categories';
6736 $sql =
"SELECT rowid, property, lang , value";
6737 $sql .=
" FROM ".$this->db->prefix().
"object_lang";
6738 $sql .=
" WHERE type_object = '".$this->db->escape($element).
"'";
6739 $sql .=
" AND fk_object = ".((int) $this->
id);
6741 $resql = $this->db->query($sql);
6743 $numrows = $this->db->num_rows($resql);
6746 while ($i < $numrows) {
6747 $obj = $this->db->fetch_object($resql);
6748 $key = $obj->property;
6749 $value = $obj->value;
6750 $codelang = $obj->lang;
6751 $type = $this->fields[$key][
'type'];
6754 if (preg_match(
'/date/', $type)) {
6755 $this->array_languages[$key][$codelang] = $this->db->jdate($value);
6757 $this->array_languages[$key][$codelang] = $value;
6764 $this->db->free($resql);
6772 dol_print_error($this->db);
6787 foreach ($_POST as $postfieldkey => $postfieldvalue) {
6788 $tmparray = explode(
'-', $postfieldkey);
6789 if ($tmparray[0] !=
'field') {
6793 $element = $tmparray[1];
6794 $key = $tmparray[2];
6795 $codelang = $tmparray[3];
6798 if (!empty($onlykey) && $key != $onlykey) {
6801 if ($element != $this->element) {
6805 $key_type = $this->fields[$key][
'type'];
6808 if (isset($this->fields[$key][
'enabled'])) {
6809 $enabled = (int)
dol_eval((
string) $this->fields[$key][
'enabled'], 1, 1,
'1');
6816 if (empty($enabled)) {
6821 if (in_array($key_type, array(
'date'))) {
6825 } elseif (in_array($key_type, array(
'datetime'))) {
6829 } elseif (in_array($key_type, array(
'checkbox',
'chkbxlst'))) {
6830 $value_arr =
GETPOST($postfieldkey,
'array');
6831 if (!empty($value_arr)) {
6832 $value_key = implode(
',', $value_arr);
6836 } elseif (in_array($key_type, array(
'price',
'double'))) {
6837 $value_arr =
GETPOST($postfieldkey,
'alpha');
6840 $value_key =
GETPOST($postfieldkey);
6841 if (in_array($key_type, array(
'link')) && $value_key ==
'-1') {
6846 $this->array_languages[$key][$codelang] = $value_key;
6871 $savDisableCompute =
$conf->disable_compute;
6872 $conf->disable_compute = 1;
6874 $ret = $this->fetch(
$id);
6876 $conf->disable_compute = $savDisableCompute;
6894 global
$conf, $extrafields;
6896 if (empty($rowid)) {
6899 if (empty($rowid) && isset($this->rowid)) {
6900 $rowid = $this->rowid;
6904 if (!$this->table_element) {
6907 $this->array_options = array();
6909 if (!is_array($optionsArray)) {
6911 if (!isset($extrafields) || !is_object($extrafields)) {
6912 require_once DOL_DOCUMENT_ROOT.
'/core/class/extrafields.class.php';
6917 if (empty($extrafields->attributes[$this->table_element][
'loaded'])) {
6918 $extrafields->fetch_name_optionals_label($this->table_element);
6920 $optionsArray = (!empty($extrafields->attributes[$this->table_element][
'label']) ? $extrafields->attributes[$this->table_element][
'label'] :
null);
6922 global $extrafields;
6923 dol_syslog(
"Warning: fetch_optionals was called with param optionsArray defined when you should pass null now", LOG_WARNING);
6926 $table_element = $this->table_element;
6927 if ($table_element ==
'categorie') {
6928 $table_element =
'categories';
6932 if (is_array($optionsArray) && count($optionsArray) > 0) {
6933 $sql =
"SELECT rowid";
6934 foreach ($optionsArray as $name => $label) {
6935 if (empty($extrafields->attributes[$this->table_element][
'type'][$name]) || (!in_array($extrafields->attributes[$this->table_element][
'type'][$name], [
'separate',
'point',
'multipts',
'linestrg',
'polygon']))) {
6936 $sql .=
", ".$this->db->sanitize($name);
6939 if (!empty($extrafields->attributes[$this->table_element][
'type'][$name]) && in_array($extrafields->attributes[$this->table_element][
'type'][$name], array(
'point',
'multipts',
'linestrg',
'polygon'))) {
6941 $sql .=
", ST_AsWKT(".$this->db->sanitize($name).
") as ".$this->db->sanitize($name);
6944 $sql .=
" FROM ".$this->db->prefix().$table_element.
"_extrafields";
6945 $sql .=
" WHERE fk_object = ".((int) $rowid);
6948 $resql = $this->db->query($sql);
6950 $numrows = $this->db->num_rows($resql);
6952 $tab = $this->db->fetch_array($resql);
6953 foreach ($tab as $key => $value) {
6955 if ($key !=
'rowid' && $key !=
'tms' && $key !=
'fk_member' && !is_int($key)) {
6957 if (!empty($extrafields->attributes[$this->table_element]) && in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'date',
'datetime'))) {
6959 $this->array_options[
"options_".$key] = $this->db->jdate($value);
6961 $this->array_options[
"options_".$key] = $value;
6966 if (!empty($extrafields->attributes[$this->table_element][
'type'][$key]) && $extrafields->attributes[$this->table_element][
'type'][$key] ==
'password') {
6967 if (!empty($value) && preg_match(
'/^dolcrypt:/', $value)) {
6968 $this->array_options[
"options_".$key] =
dolDecrypt($value);
6977 if (is_array($extrafields->attributes[$this->table_element][
'label'])) {
6978 foreach ($extrafields->attributes[$this->table_element][
'label'] as $key => $val) {
6979 $this->array_options[
'options_' . $key] =
null;
6986 if (is_array($extrafields->attributes[$this->table_element][
'label'])) {
6987 foreach ($extrafields->attributes[$this->table_element][
'label'] as $key => $val) {
6988 if (!empty($extrafields->attributes[$this->table_element]) && !empty($extrafields->attributes[$this->table_element][
'computed'][$key])) {
6990 if (empty(
$conf->disable_compute)) {
6992 global $objectoffield;
6994 $this->array_options[
'options_' . $key] =
dol_eval((
string) $extrafields->attributes[$this->table_element][
'computed'][$key], 1, 0,
'2');
7000 $this->db->free($resql);
7008 $this->errors[] = $this->db->lasterror();
7029 $table_element = $this->table_element;
7030 if ($table_element ==
'categorie') {
7031 $table_element =
'categories';
7034 dol_syslog(get_class($this).
"::deleteExtraFields delete", LOG_DEBUG);
7036 $sql_del =
"DELETE FROM ".$this->db->prefix().$table_element.
"_extrafields WHERE fk_object = ".((int) $this->
id);
7038 $resql = $this->db->query($sql_del);
7040 $this->error = $this->db->lasterror();
7041 $this->db->rollback();
7044 $this->db->commit();
7061 global $langs, $extrafields, $user;
7063 if (
getDolGlobalString(
'MAIN_EXTRAFIELDS_DISABLED') || empty($this->array_options)) {
7067 if (empty($userused)) {
7074 $langs->load(
'admin');
7075 if (!isset($extrafields) || !is_object($extrafields)) {
7076 require_once DOL_DOCUMENT_ROOT.
'/core/class/extrafields.class.php';
7079 $target_extrafields = $extrafields->fetch_name_optionals_label($this->table_element);
7082 $new_array_options = array();
7083 foreach ($this->array_options as $key => $value) {
7084 if (in_array(substr($key, 8), array_keys($target_extrafields))) {
7085 $new_array_options[$key] = $value;
7086 } elseif (in_array($key, array_keys($target_extrafields))) {
7087 $new_array_options[
'options_'.$key] = $value;
7091 foreach ($new_array_options as $key => $value) {
7092 $attributeKey = substr($key, 8);
7093 $attributeType = $extrafields->attributes[$this->table_element][
'type'][$attributeKey];
7094 $attributeLabel = $langs->transnoentities($extrafields->attributes[$this->table_element][
'label'][$attributeKey]);
7095 $attributeParam = $extrafields->attributes[$this->table_element][
'param'][$attributeKey];
7096 $attributeRequired = $extrafields->attributes[$this->table_element][
'required'][$attributeKey];
7097 $attributeUnique = $extrafields->attributes[$this->table_element][
'unique'][$attributeKey];
7098 $attrfieldcomputed = $extrafields->attributes[$this->table_element][
'computed'][$attributeKey];
7099 $attributeEmptyOnClone = $extrafields->attributes[$this->table_element][
'emptyonclone'][$attributeKey];
7111 if (!empty($this->context[
'createfromclone']) && $this->context[
'createfromclone'] ==
'createfromclone' && (!empty($attributeUnique) || !empty($attributeEmptyOnClone))) {
7112 $new_array_options[$key] =
null;
7118 if (!empty($this->context[
'createproductcombination']) && $this->context[
'createproductcombination'] ==
'createproductcombination' && !empty($attributeUnique)) {
7119 $new_array_options[$key] =
null;
7124 if ($attributeRequired) {
7125 $v = $this->array_options[$key];
7127 $langs->load(
"errors");
7128 dol_syslog(
"Mandatory field '".$key.
"' is empty during create and set to required into definition of extrafields");
7129 $this->errors[] = $langs->trans(
'ErrorFieldRequired', $attributeLabel);
7134 if (!empty($attrfieldcomputed)) {
7136 global $objectoffield;
7137 $objectoffield = $this;
7138 $value =
dol_eval((
string) $attrfieldcomputed, 1, 0,
'2');
7139 dol_syslog($langs->trans(
"Extrafieldcomputed").
" on ".$attributeLabel.
"(".$value.
")", LOG_DEBUG);
7140 $new_array_options[$key] = $value;
7142 $new_array_options[$key] =
null;
7147 switch ($attributeType) {
7151 if (!is_numeric($value) && $value !=
'') {
7152 $this->errors[] = $langs->trans(
"ExtraFieldHasWrongValue", $attributeLabel);
7154 } elseif ($value ===
'') {
7155 $new_array_options[$key] =
null;
7159 if ($value ===
'' || $value ===
false || $value ===
null) {
7160 $new_array_options[$key] =
null;
7166 if (!is_numeric($value) && $value !=
'') {
7167 dol_syslog($langs->trans(
"ExtraFieldHasWrongValue").
" for ".$attributeLabel.
"(".$value.
"is not '".$attributeType.
"')", LOG_DEBUG);
7168 $this->errors[] = $langs->trans(
"ExtraFieldHasWrongValue", $attributeLabel);
7170 } elseif ($value ==
'') {
7174 $new_array_options[$key] = $value;
7184 if ($this->array_options[$key] !=
'' && is_array($extrafields->attributes[$this->table_element][
'param'][$attributeKey][
'options'])) {
7186 $tmparrays = array_keys($extrafields->attributes[$this->table_element][
'param'][$attributeKey][
'options']);
7187 $algo = reset($tmparrays);
7192 if (is_object($this->oldcopy)) {
7194 if (isset($this->oldcopy->array_options[$key]) && $this->array_options[$key] == $this->oldcopy->array_options[$key]) {
7196 if ($algo ==
'dolcrypt') {
7197 if (!preg_match(
'/^dolcrypt:/', $this->array_options[$key])) {
7198 $new_array_options[$key] =
dolEncrypt($this->array_options[$key]);
7200 $new_array_options[$key] = $this->array_options[$key];
7203 $new_array_options[$key] = $this->array_options[$key];
7207 if ($algo ==
'dolcrypt') {
7208 if (!preg_match(
'/^dolcrypt:/', $this->array_options[$key])) {
7209 $new_array_options[$key] =
dolEncrypt($this->array_options[$key]);
7211 $new_array_options[$key] = $this->array_options[$key];
7214 $new_array_options[$key] =
dol_hash($this->array_options[$key], $algo);
7220 if ($algo ==
'dolcrypt' && !preg_match(
'/^dolcrypt:/', $this->array_options[$key])) {
7221 $new_array_options[$key] =
dolEncrypt($this->array_options[$key]);
7223 $new_array_options[$key] = $this->array_options[$key];
7228 $new_array_options[$key] = $this->array_options[$key];
7231 $new_array_options[$key] = $this->array_options[$key];
7237 if (!is_numeric($this->array_options[$key]) || $this->array_options[$key] != intval($this->array_options[$key])) {
7238 $this->array_options[$key] = strtotime($this->array_options[$key]);
7240 $new_array_options[$key] = $this->db->idate($this->array_options[$key]);
7244 if (!is_numeric($this->array_options[$key]) || $this->array_options[$key] != intval($this->array_options[$key])) {
7245 $this->array_options[$key] = strtotime($this->array_options[$key]);
7247 $new_array_options[$key] = $this->db->idate($this->array_options[$key],
'gmt');
7250 $param_list = array_keys($attributeParam[
'options']);
7253 $InfoFieldList = explode(
":", $param_list[0]);
7255 if ($InfoFieldList[0] && class_exists($InfoFieldList[0])) {
7256 if ($value ==
'-1') {
7257 $new_array_options[$key] =
'';
7259 $object =
new $InfoFieldList[0]($this->db);
7260 '@phan-var-force CommonObject $object';
7264 $sqlFetchObject =
"SELECT rowid FROM ".$this->db->prefix().$object->table_element;
7265 if (is_numeric($value)) {
7266 $sqlFetchObject .=
" WHERE rowid = " . (int) $value;
7268 $sqlFetchObject .=
" WHERE ref = '" . $this->db->escape($value) .
"'";
7271 $obj = $this->db->getRow($sqlFetchObject);
7277 if (is_object($obj)) {
7278 $objectId = $obj->rowid;
7285 $new_array_options[$key] = $objectId;
7287 $this->error =
"Id/Ref '".$value.
"' for object '".
$object->element.
"' not found";
7292 dol_syslog(
'Error bad setup of extrafield', LOG_WARNING);
7297 if (is_array($this->array_options[$key])) {
7298 $new_array_options[$key] = implode(
',', $this->array_options[$key]);
7300 $new_array_options[$key] = $this->array_options[$key];
7307 $sqlColumnValues = [
'fk_object' => (int) $this->
id];
7309 foreach ($new_array_options as $key => $newValue) {
7310 $attributeKey = substr($key, 8);
7311 $attributeType = $extrafields->attributes[$this->table_element][
'type'][$attributeKey];
7312 if ($attributeType ===
'separate') {
7316 $geoDataType = ExtraFields::$geoDataTypes[$attributeType] ??
null;
7318 if (! $geoDataType) {
7320 if ($newValue !=
'') {
7321 $sqlColumnValues[$attributeKey] =
"'".$this->db->escape($newValue).
"'";
7323 $sqlColumnValues[$attributeKey] =
'null';
7327 if (empty($newValue)) {
7328 $sqlColumnValues[$attributeKey] =
'null';
7331 if (preg_match(
'/error/i', $newValue)) {
7332 dol_syslog(
'Bad syntax string for '.$geoDataType[
'shortname'].
' '.$newValue.
' to generate SQL request', LOG_WARNING);
7333 $sqlColumnValues[$attributeKey] =
'null';
7342 $sqlColumnValues[$attributeKey] = $geoDataType[
'ST_Function'].
"('".$this->db->escape($newValue).
"')";
7347 $table_element = $this->table_element;
7348 if ($table_element ==
'categorie') {
7349 $table_element =
'categories';
7351 $extrafieldsTable = $this->db->prefix() . $table_element .
'_extrafields';
7353 dol_syslog(get_class($this).
"::insertExtraFields update or insert record line", LOG_DEBUG);
7355 $linealreadyfound = 0;
7356 $sql =
"SELECT COUNT(rowid) as nb FROM ".$this->db->prefix().$table_element.
"_extrafields WHERE fk_object = ".((int) $this->
id);
7357 $resql = $this->db->query($sql);
7359 $tmpobj = $this->db->fetch_object($resql);
7361 $linealreadyfound = $tmpobj->nb;
7366 if ($linealreadyfound) {
7367 array_shift($sqlColumnValues);
7368 if (empty($sqlColumnValues)) {
7374 $this->db->commit();
7377 $sqlColumnValueString = implode(
7383 array_map(
function ($key) use ($sqlColumnValues) {
7384 return "{$key} = {$sqlColumnValues[$key]}";
7385 }, array_keys($sqlColumnValues))
7387 $sql =
"UPDATE {$extrafieldsTable} SET {$sqlColumnValueString} WHERE fk_object = ".((int) $this->
id);
7390 $extrafieldsRequiredOnOtherEntities = $extrafields->attributes[$this->table_element][
'mandatoryfieldsofotherentities'] ?? array();
7391 foreach ($extrafieldsRequiredOnOtherEntities as $key => $extrafieldType) {
7392 if (isset($sqlColumnValues[$key])) {
7397 $sqlColumnValues[$key] =
"''";
7398 if (in_array($extrafieldType, array(
'int',
'double',
'price'))) {
7399 $sqlColumnValues[$key] = 0;
7402 $sqlColumns = implode(
',', array_keys($sqlColumnValues));
7403 $sqlValues = implode(
',', array_values($sqlColumnValues));
7404 $sql =
"INSERT INTO {$extrafieldsTable} ({$sqlColumns}) VALUES ({$sqlValues})";
7407 $resql = $this->db->query($sql);
7409 $this->error = $this->db->lasterror();
7414 if (!$error && !empty($this->fields[
'fk_user_modif'])) {
7415 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
7416 $sql .=
" SET fk_user_modif = ".(int) $userused->id;
7417 $sql .=
" WHERE ".(empty($this->table_rowid) ?
'rowid' : $this->db->sanitize($this->table_rowid)).
" = ".((
int)
$this->id);
7418 $this->db->query($sql);
7421 if (!$error && $trigger) {
7423 $this->context = array(
'extrafieldaddupdate' => 1);
7424 $result = $this->call_trigger($trigger, $userused);
7432 $this->db->rollback();
7435 $this->db->commit();
7453 global $langs, $user;
7455 if (empty($userused)) {
7465 if (is_array($this->array_languages)) {
7466 $new_array_languages = $this->array_languages;
7468 foreach ($new_array_languages as $key => $value) {
7469 $attributeKey = $key;
7470 $attributeType = $this->fields[$attributeKey][
'type'];
7471 $attributeLabel = $this->fields[$attributeKey][
'label'];
7476 switch ($attributeType) {
7478 if (is_array($value) || (!is_numeric($value) && $value !=
'')) {
7479 $this->errors[] = $langs->trans(
"ExtraLanguageHasWrongValue", $attributeLabel);
7481 } elseif ($value ==
'') {
7482 $new_array_languages[$key] =
null;
7487 if (!is_numeric($value) && $value !=
'') {
7488 dol_syslog($langs->trans(
"ExtraLanguageHasWrongValue").
" on ".$attributeLabel.
"(".$value.
"is not '".$attributeType.
"')", LOG_DEBUG);
7489 $this->errors[] = $langs->trans(
"ExtraLanguageHasWrongValue", $attributeLabel);
7491 } elseif ($value ==
'') {
7492 $new_array_languages[$key] =
null;
7494 $new_array_languages[$key] = $value;
7508 $table_element = $this->table_element;
7509 if ($table_element ==
'categorie') {
7510 $table_element =
'categories';
7513 dol_syslog(get_class($this).
"::insertExtraLanguages delete then insert", LOG_DEBUG);
7515 foreach ($new_array_languages as $key => $langcodearray) {
7516 foreach ($langcodearray as $langcode => $value) {
7517 $sql_del =
"DELETE FROM ".$this->db->prefix().
"object_lang";
7518 $sql_del .=
" WHERE fk_object = ".((int) $this->
id).
" AND property = '".$this->db->escape($key).
"' AND type_object = '".$this->db->escape($table_element).
"'";
7519 $sql_del .=
" AND lang = '".$this->db->escape($langcode).
"'";
7520 $this->db->query($sql_del);
7522 if ($value !==
'') {
7523 $sql =
"INSERT INTO ".$this->db->prefix().
"object_lang (fk_object, property, type_object, lang, value";
7524 $sql .=
") VALUES (".((int) $this->
id).
", '".$this->db->escape($key).
"', '".$this->db->escape($table_element).
"', '".$this->db->escape($langcode).
"', '".$this->db->escape($value).
"'";
7527 $resql = $this->db->query($sql);
7529 $this->error = $this->db->lasterror();
7537 if (!$error && $trigger) {
7539 $this->context = array(
'extralanguagesaddupdate' => 1);
7540 $result = $this->call_trigger($trigger, $userused);
7548 $this->db->rollback();
7551 $this->db->commit();
7571 global $langs, $user, $extrafields, $hookmanager;
7577 if (empty($userused)) {
7583 if (!empty($this->array_options) && isset($this->array_options[
"options_".$key])) {
7585 $langs->load(
'admin');
7586 if (!isset($extrafields) || !is_object($extrafields)) {
7587 require_once DOL_DOCUMENT_ROOT.
'/core/class/extrafields.class.php';
7590 $extrafields->fetch_name_optionals_label($this->table_element);
7591 if (!isset($extrafields->attributes[$this->table_element][
'type'][$key])) {
7595 $value = $this->array_options[
"options_".$key];
7597 $attributeKey = $key;
7598 $attributeType = $extrafields->attributes[$this->table_element][
'type'][$attributeKey];
7599 $attributeLabel = $extrafields->attributes[$this->table_element][
'label'][$attributeKey];
7600 $attributeParam = $extrafields->attributes[$this->table_element][
'param'][$attributeKey];
7601 $attributeRequired = $extrafields->attributes[$this->table_element][
'required'][$attributeKey];
7602 $attributeUnique = $extrafields->attributes[$this->table_element][
'unique'][$attributeKey];
7603 $attrfieldcomputed = $extrafields->attributes[$this->table_element][
'computed'][$attributeKey];
7607 if ($attributeRequired) {
7608 $mandatorypb =
false;
7609 if ($attributeType ==
'link' && $this->array_options[
"options_".$key] ==
'-1') {
7610 $mandatorypb =
true;
7612 if ($this->array_options[
"options_".$key] ===
'') {
7613 $mandatorypb =
true;
7616 $langs->load(
"errors");
7617 dol_syslog(
"Mandatory field 'options_".$key.
"' is empty during update and set to required into definition of extrafields");
7618 $this->errors[] = $langs->trans(
'ErrorFieldRequired', $attributeLabel);
7624 $new_array_options = $this->array_options;
7628 if (!empty($attrfieldcomputed)) {
7630 global $objectoffield;
7631 $objectoffield = $this;
7632 $value =
dol_eval((
string) $attrfieldcomputed, 1, 0,
'2');
7633 dol_syslog($langs->trans(
"Extrafieldcomputed").
" on ".$attributeLabel.
"(".$value.
")", LOG_DEBUG);
7635 $new_array_options[
"options_".$key] = $value;
7637 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7639 $new_array_options[
"options_".$key] =
null;
7641 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7645 switch ($attributeType) {
7647 if (!is_numeric($value) && $value !=
'') {
7648 $this->errors[] = $langs->trans(
"ExtraFieldHasWrongValue", $attributeLabel);
7650 } elseif ($value ===
'') {
7651 $new_array_options[
"options_".$key] =
null;
7653 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7659 if (!is_numeric($value) && $value !=
'') {
7660 dol_syslog($langs->trans(
"ExtraFieldHasWrongValue").
" on ".$attributeLabel.
"(".$value.
"is not '".$attributeType.
"')", LOG_DEBUG);
7661 $this->errors[] = $langs->trans(
"ExtraFieldHasWrongValue", $attributeLabel);
7663 } elseif ($value ===
'') {
7667 $new_array_options[
"options_".$key] = $value;
7669 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7681 if ($this->array_options[
"options_".$key] !=
'' && is_array($extrafields->attributes[$this->table_element][
'param'][$attributeKey][
'options'])) {
7683 $tmparrays = array_keys($extrafields->attributes[$this->table_element][
'param'][$attributeKey][
'options']);
7684 $algo = reset($tmparrays);
7690 if (is_object($this->oldcopy)) {
7692 if (isset($this->oldcopy->array_options[
"options_".$key]) && $this->array_options[
"options_".$key] == $this->oldcopy->array_options[
"options_".$key]) {
7693 if ($algo ==
'dolcrypt') {
7694 if (!preg_match(
'/^dolcrypt:/', $this->array_options[
"options_".$key])) {
7695 $new_array_options[
"options_".$key] =
dolEncrypt($this->array_options[
"options_".$key]);
7697 $new_array_options[
"options_".$key] = $this->array_options[
"options_".$key];
7700 $new_array_options[
"options_".$key] = $this->array_options[
"options_".$key];
7703 if ($algo ==
'dolcrypt') {
7704 if (!preg_match(
'/^dolcrypt:/', $this->array_options[
"options_".$key])) {
7705 $new_array_options[
"options_".$key] =
dolEncrypt($this->array_options[
"options_".$key]);
7707 $new_array_options[
"options_".$key] = $this->array_options[
"options_".$key];
7710 $new_array_options[
"options_".$key] =
dol_hash($this->array_options[
"options_".$key], $algo);
7714 if ($algo ==
'dolcrypt' && !preg_match(
'/^dolcrypt:/', $this->array_options[
"options_".$key])) {
7715 $new_array_options[
"options_".$key] =
dolEncrypt($this->array_options[
"options_".$key]);
7717 $new_array_options[
"options_".$key] = $this->array_options[
"options_".$key];
7722 $new_array_options[
"options_".$key] = $this->array_options[
"options_".$key];
7725 $new_array_options[
"options_".$key] = $this->array_options[
"options_".$key];
7728 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7732 if (empty($this->array_options[
"options_".$key])) {
7733 $new_array_options[
"options_".$key] =
null;
7735 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7737 $new_array_options[
"options_".$key] = $this->db->idate($this->array_options[
"options_".$key]);
7741 if (empty($this->array_options[
"options_".$key])) {
7742 $new_array_options[
"options_".$key] =
null;
7744 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7746 $new_array_options[
"options_".$key] = $this->db->idate($this->array_options[
"options_".$key],
'gmt');
7750 if (empty($this->array_options[
"options_".$key])) {
7751 $new_array_options[
"options_".$key] =
null;
7753 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7757 if ($this->array_options[
"options_".$key] ===
'') {
7758 $new_array_options[
"options_".$key] =
null;
7760 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7794 $new_array_options = array();
7795 if (is_array($this->array_options[
"options_".$key])) {
7796 $new_array_options[
"options_".$key] = implode(
',', $this->array_options[
"options_".$key]);
7798 $new_array_options[
"options_".$key] = $this->array_options[
"options_".$key];
7801 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7807 $linealreadyfound = 0;
7810 $table_element = $this->table_element;
7811 if ($table_element ==
'categorie') {
7812 $table_element =
'categories';
7815 $sql =
"SELECT COUNT(rowid) as nb FROM ".$this->db->prefix().$table_element.
"_extrafields WHERE fk_object = ".((int) $this->
id);
7816 $resql = $this->db->query($sql);
7818 $tmpobj = $this->db->fetch_object($resql);
7820 $linealreadyfound = $tmpobj->nb;
7825 if ($linealreadyfound) {
7826 $sanitizedGeoDataType = ExtraFields::$geoDataTypes[$attributeType] ??
null;
7827 if ($this->array_options[
"options_".$key] ===
null) {
7828 $sql =
"UPDATE ".$this->db->prefix().$this->db->sanitize($table_element).
"_extrafields";
7829 $sql .=
" SET ".$this->db->sanitize($key).
" = null";
7830 } elseif (!empty($sanitizedGeoDataType[
'ST_Function'])) {
7831 $sql =
"UPDATE ".$this->db->prefix().$this->db->sanitize($table_element).
"_extrafields";
7832 $sql .=
" SET ".$this->db->sanitize($key).
" = ".$this->db->sanitize($sanitizedGeoDataType[
'ST_Function']).
"('".$this->db->escape($this->array_options[
"options_".$key]).
"')";
7835 $sql =
"UPDATE ".$this->db->prefix().$this->db->sanitize($table_element).
"_extrafields";
7836 $sql .=
" SET ".$this->db->sanitize($key).
" = '".$this->db->escape($new_array_options[
"options_".$key]).
"'";
7838 $sql .=
" WHERE fk_object = ".((int) $this->
id);
7840 $resql = $this->db->query($sql);
7843 $this->error = $this->db->lasterror();
7846 $result = $this->insertExtraFields(
'', $user);
7853 if (!$error && !empty($this->fields[
'fk_user_modif'])) {
7854 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
7855 $sql .=
" SET fk_user_modif = ".(int) $userused->id;
7856 $sql .=
" WHERE ".(empty($this->table_rowid) ?
'rowid' : $this->db->sanitize($this->table_rowid)).
" = ".((
int)
$this->id);
7857 $this->db->query($sql);
7861 $parameters = array(
'key' => $key);
7863 $reshook = $hookmanager->executeHooks(
'updateExtraFieldBeforeCommit', $parameters, $this, $action);
7865 setEventMessages($hookmanager->error, $hookmanager->errors,
'errors');
7869 if (!$error && $trigger) {
7871 $this->context = array(
'extrafieldupdate' => 1);
7872 $result = $this->call_trigger($trigger, $userused);
7880 dol_syslog(__METHOD__.$this->error, LOG_ERR);
7881 $this->db->rollback();
7884 $this->db->commit();
7900 return $this->array_options[
'options_'.$key] ??
null;
7912 $this->array_options[
'options_'.$key] = $value;
7929 if (empty($userused)) {
7957 public function showInputField($val, $key, $value, $moreparam =
'', $keysuffix =
'', $keyprefix =
'', $morecss = 0, $nonewbutton = 0)
7959 global
$conf, $langs, $form;
7964 if (!is_object($form)) {
7965 require_once DOL_DOCUMENT_ROOT.
'/core/class/html.form.class.php';
7966 $form =
new Form($this->db);
7969 if (!empty($this->fields)) {
7970 $val = $this->fields[$key];
7974 $fieldValidationErrorMsg =
'';
7975 $validationClass =
'';
7976 $fieldValidationErrorMsg = $this->getFieldError($key);
7977 if (!empty($fieldValidationErrorMsg)) {
7978 $validationClass =
' --error';
7980 $validationClass =
' --success';
7988 $param[
'options'] = array();
7991 $size = !empty($this->fields[$key][
'size']) ? $this->fields[$key][
'size'] : 0;
7993 if (preg_match(
'/^(integer|link):(.*):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
7994 $param[
'options'] = array($reg[2].
':'.$reg[3].
':'.$reg[4].
':'.$reg[5] =>
'N');
7996 } elseif (preg_match(
'/^(integer|link):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
7997 $param[
'options'] = array($reg[2].
':'.$reg[3].
':'.$reg[4] =>
'N');
7999 } elseif (preg_match(
'/^(integer|link):(.*):(.*)/i', $val[
'type'], $reg)) {
8000 $param[
'options'] = array($reg[2].
':'.$reg[3] =>
'N');
8002 } elseif (preg_match(
'/^(sellist):(.*):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
8003 $param[
'options'] = array($reg[2].
':'.$reg[3].
':'.$reg[4].
':'.$reg[5] =>
'N');
8005 } elseif (preg_match(
'/^(sellist):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
8006 $param[
'options'] = array($reg[2].
':'.$reg[3].
':'.$reg[4] =>
'N');
8008 } elseif (preg_match(
'/^(sellist):(.*):(.*)/i', $val[
'type'], $reg)) {
8009 $param[
'options'] = array($reg[2].
':'.$reg[3] =>
'N');
8011 } elseif (preg_match(
'/^chkbxlst:(.*)/i', $val[
'type'], $reg)) {
8012 $param[
'options'] = array($reg[1] =>
'N');
8014 } elseif (preg_match(
'/varchar\((\d+)\)/', $val[
'type'], $reg)) {
8015 $param[
'options'] = array();
8018 } elseif (preg_match(
'/varchar/', $val[
'type'])) {
8019 $param[
'options'] = array();
8021 } elseif (preg_match(
'/stars\((\d+)\)/', $val[
'type'], $reg)) {
8022 $param[
'options'] = array();
8026 $param[
'options'] = array();
8027 $type = $this->fields[$key][
'type'];
8032 if (!empty($this->fields[$key][
'arrayofkeyval']) && is_array($this->fields[$key][
'arrayofkeyval'])) {
8033 $param[
'options'] = $this->fields[$key][
'arrayofkeyval'];
8035 if (empty($this->fields[$key][
'multiinput'])) {
8036 $type = (($this->fields[$key][
'type'] ==
'checkbox') ? $this->fields[$key][
'type'] :
'select');
8040 $label = $this->fields[$key][
'label'];
8043 $default = (!empty($this->fields[$key][
'default']) ? $this->fields[$key][
'default'] :
'');
8045 $computed = (!empty($this->fields[$key][
'computed']) ? $this->fields[$key][
'computed'] :
'');
8047 $unique = (!empty($this->fields[$key][
'unique']) ? $this->fields[$key][
'unique'] : 0);
8049 $required = (!empty($this->fields[$key][
'required']) ? $this->fields[$key][
'required'] : 0);
8051 $autofocusoncreate = (!empty($this->fields[$key][
'autofocusoncreate']) ? $this->fields[$key][
'autofocusoncreate'] : 0);
8053 $placeholder = (!empty($this->fields[$key][
'placeholder']) ? $this->fields[$key][
'placeholder'] : 0);
8056 $langfile = (!empty($this->fields[$key][
'langfile']) ? $this->fields[$key][
'langfile'] :
'');
8058 $list = (!empty($this->fields[$key][
'list']) ? $this->fields[$key][
'list'] : 0);
8059 $hidden = (in_array(abs($this->fields[$key][
'visible']), array(0, 2)) ? 1 : 0);
8064 if (!preg_match(
'/^search_/', $keyprefix)) {
8065 return '<span class="opacitymedium">'.$langs->trans(
"AutomaticallyCalculated").
'</span>';
8072 if (empty($morecss) && !empty($val[
'css'])) {
8073 $morecss = $val[
'css'];
8074 } elseif (empty($morecss)) {
8075 if ($type ==
'date') {
8076 $morecss =
'minwidth100imp';
8077 } elseif ($type ==
'datetime' || $type ==
'link') {
8078 $morecss =
'minwidth200imp';
8079 } elseif (in_array($type, array(
'int',
'integer',
'price')) || preg_match(
'/^double(\([0-9],[0-9]\)){0,1}/', (
string) $type)) {
8080 $morecss =
'maxwidth75';
8081 } elseif ($type ==
'url') {
8082 $morecss =
'minwidth400';
8083 } elseif ($type ==
'boolean') {
8086 if (is_numeric($size) && round((
float) $size) < 12) {
8087 $morecss =
'minwidth100';
8088 } elseif (is_numeric($size) && round((
float) $size) <= 48) {
8089 $morecss =
'minwidth200';
8091 $morecss =
'minwidth400';
8097 if (!empty($validationClass)) {
8098 $morecss .= $validationClass;
8101 if (in_array($type, array(
'date'))) {
8102 $tmp = explode(
',', $size);
8107 if (!$required && $value ==
'') {
8112 $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required,
'', 1, (($keyprefix !=
'search_' && $keyprefix !=
'search_options_') ? 1 : 0), 0, 1);
8113 } elseif (in_array($type, array(
'datetime'))) {
8114 $tmp = explode(
',', $size);
8119 if (!$required && $value ==
'') {
8124 $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required,
'', 1, (($keyprefix !=
'search_' && $keyprefix !=
'search_options_') ? 1 : 0), 0, 1,
'',
'',
'', 1,
'',
'',
'tzuserrel');
8125 } elseif (in_array($type, array(
'duration'))) {
8126 $out = $form->select_duration($keyprefix.$key.$keysuffix, $value, 0,
'text', 0, 1);
8127 } elseif (in_array($type, array(
'int',
'integer'))) {
8128 $tmp = explode(
',', $size);
8130 $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' :
'').
'>';
8131 } elseif (in_array($type, array(
'real'))) {
8132 $out =
'<input type="text" class="flat '.$morecss.
'" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.
dol_escape_htmltag($value).
'"'.($moreparam ? $moreparam :
'').($autofocusoncreate ?
' autofocus' :
'').
'>';
8133 } elseif (preg_match(
'/varchar/', (
string) $type)) {
8134 $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' :
'').
'>';
8135 } elseif ($type ==
'phone' && !preg_match(
'/search_/', $keyprefix)) {
8136 $out = $form->showPhoneInput($value, $keyprefix.$key.$keysuffix, !empty($this->country_id) ? $this->country_id : 0);
8137 } elseif (in_array($type, array(
'email',
'mail',
'url',
'ip'))) {
8138 $out =
'<input type="text" class="flat '.$morecss.
'" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.
dol_escape_htmltag($value).
'" '.($moreparam ? $moreparam :
'').($autofocusoncreate ?
' autofocus' :
'').
'>';
8139 } elseif (preg_match(
'/^text/', (
string) $type)) {
8140 if (!preg_match(
'/search_/', $keyprefix)) {
8141 if (!empty($param[
'options'])) {
8144 $out .= $form->selectarray($keyprefix.$key.$keysuffix.
"_multiinput", $param[
'options'],
'', 1, 0, 0,
"flat maxwidthonphone".$morecss);
8145 $out .=
'<input id="'.$keyprefix.$key.$keysuffix.
'_multiinputadd" type="button" class="button" value="'.$langs->trans(
"Add").
'">';
8148 function handlemultiinputdisabling(htmlname){
8149 console.log("We handle the disabling of used options for "+htmlname+"_multiinput");
8150 multiinput = $("#"+htmlname+"_multiinput");
8151 multiinput.find("option").each(function(){
8152 tmpval = $("#"+htmlname).val();
8153 tmpvalarray = tmpval.split("\n");
8154 valtotest = $(this).val();
8155 if(tmpvalarray.includes(valtotest)){
8156 $(this).prop("disabled",true);
8158 if($(this).prop("disabled") == true){
8159 console.log(valtotest)
8160 $(this).prop("disabled", false);
8166 $(document).ready(function () {
8167 $("#'.$keyprefix.$key.$keysuffix.
'_multiinputadd").on("click",function() {
8168 tmpval = $("#'.$keyprefix.$key.$keysuffix.
'").val();
8169 tmpvalarray = tmpval.split(",");
8170 valtotest = $("#'.$keyprefix.$key.$keysuffix.
'_multiinput").val();
8171 if(valtotest != -1 && !tmpvalarray.includes(valtotest)){
8172 console.log("We add the selected value to the text area '.$keyprefix.$key.$keysuffix.
'");
8176 tmpval = tmpval + "\n" + valtotest;
8178 $("#'.$keyprefix.$key.$keysuffix.
'").val(tmpval);
8179 handlemultiinputdisabling("'.$keyprefix.$key.$keysuffix.
'");
8180 $("#'.$keyprefix.$key.$keysuffix.
'_multiinput").val(-1);
8182 console.log("We add nothing the text area '.$keyprefix.$key.$keysuffix.
'");
8185 $("#'.$keyprefix.$key.$keysuffix.
'").on("change",function(){
8186 handlemultiinputdisabling("'.$keyprefix.$key.$keysuffix.
'");
8188 handlemultiinputdisabling("'.$keyprefix.$key.$keysuffix.
'");
8190 $out .=
"</script>";
8191 $value = str_replace(
',',
"\n", $value);
8193 require_once DOL_DOCUMENT_ROOT.
'/core/class/doleditor.class.php';
8194 $doleditor =
new DolEditor($keyprefix.$key.$keysuffix, $value,
'', 200,
'dolibarr_notes',
'In',
false,
false,
false, ROWS_5,
'90%');
8195 $out .= (string) $doleditor->Create(1,
'',
true,
'',
'',
'', $morecss);
8197 $out =
'<input type="text" class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.
dol_escape_htmltag($value).
'" '.($moreparam ? $moreparam :
'').
'>';
8199 } elseif (preg_match(
'/^html/', (
string) $type)) {
8200 if (!preg_match(
'/search_/', $keyprefix)) {
8201 require_once DOL_DOCUMENT_ROOT.
'/core/class/doleditor.class.php';
8202 $doleditor =
new DolEditor($keyprefix.$key.$keysuffix, $value,
'', 200,
'dolibarr_notes',
'In',
false,
false,
isModEnabled(
'fckeditor') &&
getDolGlobalInt(
'FCKEDITOR_ENABLE_SOCIETE'), ROWS_5,
'90%');
8203 $out = (string) $doleditor->Create(1,
'',
true,
'',
'', $moreparam, $morecss);
8205 $out =
'<input type="text" class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.
dol_escape_htmltag($value).
'" '.($moreparam ? $moreparam :
'').
'>';
8207 } elseif ($type ==
'boolean') {
8209 if (!empty($value)) {
8210 $checked =
' checked value="1" ';
8212 $checked =
' value="1" ';
8214 $out =
'<input type="checkbox" class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" '.$checked.
' '.($moreparam ? $moreparam :
'').
'>';
8215 } elseif ($type ==
'price') {
8216 if (!empty($value)) {
8217 $value =
price($value);
8219 $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>';
8220 } elseif ($type ==
'stars') {
8221 $out =
'<input type="hidden" class="flat '.$morecss.
'" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.
dol_escape_htmltag($value).
'"'.($moreparam ? $moreparam :
'').($autofocusoncreate ?
' autofocus' :
'').
'>';
8222 $out .=
'<div class="star-selection" id="'.$keyprefix.$key.$keysuffix.
'_selection">';
8224 while ($i <= $size) {
8225 $out .=
'<span class="star" data-value="'.$i.
'">'.img_picto(
'',
'fontawesome_star_fas').
'</span>';
8230 jQuery(function($) { /* commonobject.class.php 1 */
8231 let container = $("#'.$keyprefix.$key.$keysuffix.
'_selection");
8232 let selectedStars = parseInt($("#'.$keyprefix.$key.$keysuffix.
'").val()) || 0;
8233 container.find(".star").each(function() {
8234 $(this).toggleClass("active", $(this).data("value") <= selectedStars);
8236 container.find(".star").on("mouseover", function() {
8237 let selectedStar = $(this).data("value");
8238 container.find(".star").each(function() {
8239 $(this).toggleClass("active", $(this).data("value") <= selectedStar);
8242 container.on("mouseout", function() {
8243 container.find(".star").each(function() {
8244 $(this).toggleClass("active", $(this).data("value") <= selectedStars);
8247 container.find(".star").off("click").on("click", function() {
8248 selectedStars = $(this).data("value");
8249 if (selectedStars === 1 && $("#'.$keyprefix.$key.$keysuffix.
'").val() == 1) {
8252 $("#'.$keyprefix.$key.$keysuffix.
'").val(selectedStars);
8253 container.find(".star").each(function() {
8254 $(this).toggleClass("active", $(this).data("value") <= selectedStars);
8259 } elseif (preg_match(
'/^double(\([0-9],[0-9]\)){0,1}/', (
string) $type)) {
8260 if (!empty($value)) {
8261 $value =
price($value);
8263 $out =
'<input type="text" class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.$value.
'" '.($moreparam ? $moreparam :
'').
'> ';
8264 } elseif ($type ==
'select') {
8267 include_once DOL_DOCUMENT_ROOT.
'/core/lib/ajax.lib.php';
8268 $out .=
ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
8274 foreach ($param[
'options'] as $keyb => $valb) {
8275 if ((
string) $keyb ==
'') {
8278 if (strpos($valb,
"|") !==
false) {
8279 list($valb, $parent) = explode(
'|', $valb);
8282 $tmpselect .=
'<option value="'.$keyb.
'"';
8283 $tmpselect .= (((string) $value == (
string) $keyb) ?
' selected' :
'');
8284 if (!empty($parent)) {
8287 $tmpselect .= (!empty($parent) ?
' parent="'.$parent.
'"' :
'');
8288 $tmpselect .=
'>'.$langs->trans($valb).
'</option>';
8291 $out .=
'<select class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" '.($moreparam ? $moreparam :
'').
'>';
8292 if ((!isset($this->fields[$key][
'default'])) || empty($this->fields[$key][
'notnull']) || ($this->fields[$key][
'notnull'] != 1) || $nbchoice >= 2) {
8293 $out .=
'<option value="0"> </option>';
8296 $out .=
'</select>';
8297 } elseif ($type ==
'sellist') {
8300 include_once DOL_DOCUMENT_ROOT.
'/core/lib/ajax.lib.php';
8301 $out .=
ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
8304 $out .=
'<select class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" '.($moreparam ? $moreparam :
'').
'>';
8305 if (is_array($param[
'options'])) {
8306 $tmpparamoptions = array_keys($param[
'options']);
8307 $paramoptions = preg_split(
'/[\r\n]+/', $tmpparamoptions[0]);
8309 $InfoFieldList = explode(
":", $paramoptions[0], 5);
8321 if (! empty($InfoFieldList[4])) {
8323 $parenthesisopen = 0;
8324 while (substr($InfoFieldList[4], $pos, 1) !==
'' && ($parenthesisopen || $pos == 0 || substr($InfoFieldList[4], $pos, 1) !=
':')) {
8325 if (substr($InfoFieldList[4], $pos, 1) ==
'(') {
8328 if (substr($InfoFieldList[4], $pos, 1) ==
')') {
8333 $tmpbefore = substr($InfoFieldList[4], 0, $pos);
8334 $tmpafter = substr($InfoFieldList[4], $pos + 1);
8336 $InfoFieldList[4] = $tmpbefore;
8337 if ($tmpafter !==
'') {
8338 $InfoFieldList = array_merge($InfoFieldList, explode(
':', $tmpafter));
8344 if (preg_match(
'/^\(?([a-z0-9]+)([=<>]+)(\d+)\)?$/i', $InfoFieldList[4], $reg)) {
8345 $InfoFieldList[4] =
'('.$reg[1].
':'.$reg[2].
':'.$reg[3].
')';
8356 $keyList = (empty($InfoFieldList[2]) ?
'rowid' : $InfoFieldList[2].
' as rowid');
8358 if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
8359 if (strpos($InfoFieldList[4],
'extra.') !==
false) {
8360 $keyList =
'main.'.$InfoFieldList[2].
' as rowid';
8362 $keyList = $InfoFieldList[2].
' as rowid';
8365 if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
8366 list($parentName, $parentField) = explode(
'|', $InfoFieldList[3]);
8367 if (!empty($InfoFieldList[4]) && strpos($InfoFieldList[4],
'extra.') !==
false) {
8368 $keyList .=
', main.'.$parentField;
8370 $keyList .=
', '.$parentField;
8374 $filter_categorie =
false;
8375 if (count($InfoFieldList) > 5) {
8376 if ($InfoFieldList[0] ==
'categorie') {
8377 $filter_categorie =
true;
8381 if (!$filter_categorie) {
8382 $fields_label = isset($InfoFieldList[1]) ? explode(
'|', $InfoFieldList[1]) : array();
8383 if (!empty($fields_label)) {
8385 $keyList .= implode(
', ', $fields_label);
8389 $sql =
"SELECT " . $this->db->sanitize($keyList, 0, 0, 1);
8390 $sql .=
" FROM " . $this->db->prefix() . $this->db->sanitize($InfoFieldList[0]);
8392 if (!empty($InfoFieldList[4])) {
8394 if (strpos($InfoFieldList[4],
'$SEL$') !==
false) {
8395 $InfoFieldList[4] = str_replace(
'$SEL$',
'SELECT', $InfoFieldList[4]);
8399 if (strpos($InfoFieldList[4],
'$ID$') !==
false && !empty($objectid)) {
8400 $InfoFieldList[4] = str_replace(
'$ID$', (
string) $objectid, $InfoFieldList[4]);
8402 $InfoFieldList[4] = str_replace(
'$ID$',
'0', $InfoFieldList[4]);
8407 if (strpos($InfoFieldList[4],
'extra') !==
false) {
8408 $sql .=
" as main, " . $this->db->sanitize($this->db->prefix() . $InfoFieldList[0]) .
"_extrafields as extra";
8409 $sqlwhere .=
" WHERE extra.fk_object = main." . $this->db->sanitize($InfoFieldList[2]);
8415 $sqlwhere .=
' WHERE 1=1';
8432 if (in_array($InfoFieldList[0], array(
'tablewithentity'))) {
8433 $sqlwhere .=
" AND entity = " . ((int)
$conf->entity);
8438 if (isset($InfoFieldList[7]) && preg_match(
'/^[a-z0-9_\-,]+$/i', $InfoFieldList[7])) {
8439 $sql .=
" ORDER BY ".$this->db->sanitize($InfoFieldList[7]);
8441 $sql .=
" ORDER BY ".$this->db->sanitize(implode(
', ', $fields_label));
8443 $sql .=
' LIMIT ' .
getDolGlobalInt(
'MAIN_EXTRAFIELDS_LIMIT_SELLIST_SQL', 1000);
8446 dol_syslog(get_class($this) .
'::showInputField type=sellist', LOG_DEBUG);
8447 $resql = $this->db->query($sql);
8449 $out .=
'<option value="0"> </option>';
8450 $num = $this->db->num_rows($resql);
8454 $obj = $this->db->fetch_object($resql);
8458 $fields_label = explode(
'|', $InfoFieldList[1]);
8459 if (count($fields_label) > 1) {
8461 foreach ($fields_label as $field_toshow) {
8462 $labeltoshow .= $obj->$field_toshow .
' ';
8465 $labeltoshow = $obj->{$InfoFieldList[1]};
8467 $labeltoshow =
dol_trunc($labeltoshow, 45);
8469 if ($value == $obj->rowid) {
8470 foreach ($fields_label as $field_toshow) {
8471 $translabel = $langs->trans($obj->$field_toshow);
8472 if ($translabel != $obj->$field_toshow) {
8473 $labeltoshow =
dol_trunc($translabel) .
' ';
8475 $labeltoshow =
dol_trunc($obj->$field_toshow) .
' ';
8478 $out .=
'<option value="' . $obj->rowid .
'" selected>' . $labeltoshow .
'</option>';
8481 $translabel = $langs->trans($obj->{$InfoFieldList[1]});
8482 if ($translabel != $obj->{$InfoFieldList[1]}) {
8483 $labeltoshow =
dol_trunc($translabel, 18);
8485 $labeltoshow =
dol_trunc($obj->{$InfoFieldList[1]});
8488 if (empty($labeltoshow)) {
8489 $labeltoshow =
'(not defined)';
8491 if ($value == $obj->rowid) {
8492 $out .=
'<option value="' . $obj->rowid .
'" selected>' . $labeltoshow .
'</option>';
8495 if (!empty($InfoFieldList[3]) && $parentField) {
8496 $parent = $parentName .
':' . $obj->{$parentField};
8500 $out .=
'<option value="' . $obj->rowid .
'"';
8501 $out .= ($value == $obj->rowid ?
' selected' :
'');
8502 $out .= (!empty($parent) ?
' parent="' . $parent .
'"' :
'');
8503 $out .=
'>' . $labeltoshow .
'</option>';
8508 $this->db->free($resql);
8510 print
'Error in request ' . $sql .
' ' . $this->db->lasterror() .
'. Check setup of extra parameters.<br>';
8513 require_once DOL_DOCUMENT_ROOT.
'/categories/class/categorie.class.php';
8514 $categcode = $InfoFieldList[5];
8515 if (is_numeric($categcode)) {
8516 $tmpcategory =
new Categorie($this->db);
8517 $MAP_ID_TO_CODE = array_flip($tmpcategory->MAP_ID);
8518 $categcode = $MAP_ID_TO_CODE[(int) $categcode];
8521 $data = $form->select_all_categories($categcode,
'',
'parent', 64, $InfoFieldList[6], 1, 1);
8522 $out .=
'<option value="0"> </option>';
8523 foreach ($data as $data_key => $data_value) {
8524 $out .=
'<option value="' . $data_key .
'"';
8525 $out .= ($value == $data_key ?
' selected' :
'');
8526 $out .=
'>' . $data_value .
'</option>';
8530 $out .=
'</select>';
8531 } elseif ($type ==
'checkbox') {
8532 $value_arr = explode(
',', $value);
8533 $out = $form->multiselectarray($keyprefix.$key.$keysuffix, (empty($param[
'options']) ?
null : $param[
'options']), $value_arr, 0, 0, $morecss, 0,
'100%');
8534 } elseif ($type ==
'radio') {
8536 foreach ($param[
'options'] as $keyopt => $valopt) {
8537 $out .=
'<input class="flat '.$morecss.
'" type="radio" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" '.($moreparam ? $moreparam :
'');
8538 $out .=
' value="'.$keyopt.
'"';
8539 $out .=
' id="'.$keyprefix.$key.$keysuffix.
'_'.$keyopt.
'"';
8540 $out .= ($value == $keyopt ?
'checked' :
'');
8541 $out .=
'/><label for="'.$keyprefix.$key.$keysuffix.
'_'.$keyopt.
'">'.$valopt.
'</label><br>';
8543 } elseif ($type ==
'chkbxlst') {
8544 if (is_array($value)) {
8545 $value_arr = $value;
8547 $value_arr = explode(
',', $value);
8550 if (is_array($param[
'options'])) {
8551 $tmpparamoptions = array_keys($param[
'options']);
8552 $paramoptions = preg_split(
'/[\r\n]+/', $tmpparamoptions[0]);
8554 $InfoFieldList = explode(
":", $paramoptions[0], 5);
8566 if (! empty($InfoFieldList[4])) {
8568 $parenthesisopen = 0;
8569 while (substr($InfoFieldList[4], $pos, 1) !==
'' && ($parenthesisopen || $pos == 0 || substr($InfoFieldList[4], $pos, 1) !=
':')) {
8570 if (substr($InfoFieldList[4], $pos, 1) ==
'(') {
8573 if (substr($InfoFieldList[4], $pos, 1) ==
')') {
8578 $tmpbefore = substr($InfoFieldList[4], 0, $pos);
8579 $tmpafter = substr($InfoFieldList[4], $pos + 1);
8581 $InfoFieldList[4] = $tmpbefore;
8582 if ($tmpafter !==
'') {
8583 $InfoFieldList = array_merge($InfoFieldList, explode(
':', $tmpafter));
8588 if (preg_match(
'/^\(?([a-z0-9]+)([=<>]+)(\d+)\)?$/i', $InfoFieldList[4], $reg)) {
8589 $InfoFieldList[4] =
'('.$reg[1].
':'.$reg[2].
':'.$reg[3].
')';
8597 '@phan-var-force array{0:string,1:string,2:string,3:string,3:string,5:string,6:string} $InfoFieldList';
8602 $keyList = (empty($InfoFieldList[2]) ?
'rowid' : $InfoFieldList[2].
' as rowid');
8604 if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
8605 if (strpos($InfoFieldList[4],
'extra.') !==
false) {
8606 $keyList =
'main.'.$InfoFieldList[2].
' as rowid';
8608 $keyList = $InfoFieldList[2].
' as rowid';
8611 if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
8612 list($parentName, $parentField) = explode(
'|', $InfoFieldList[3]);
8613 if (!empty($InfoFieldList[4]) && strpos($InfoFieldList[4],
'extra.') !==
false) {
8614 $keyList .=
', main.'.$parentField;
8616 $keyList .=
', '.$parentField;
8620 $filter_categorie =
false;
8621 if (count($InfoFieldList) > 5) {
8622 if ($InfoFieldList[0] ==
'categorie') {
8623 $filter_categorie =
true;
8628 if (!$filter_categorie) {
8629 $fields_label = explode(
'|', $InfoFieldList[1]);
8630 if (is_array($fields_label)) {
8632 $keyList .= implode(
', ', $fields_label);
8636 $sql =
"SELECT " . $this->db->sanitize($keyList, 0, 0, 1);
8637 $sql .=
' FROM ' . $this->db->prefix() . $this->db->sanitize($InfoFieldList[0]);
8639 if (!empty($InfoFieldList[4])) {
8641 if (strpos($InfoFieldList[4],
'$SEL$') !==
false) {
8642 $InfoFieldList[4] = str_replace(
'$SEL$',
'SELECT', $InfoFieldList[4]);
8646 if (strpos($InfoFieldList[4],
'$ID$') !==
false && !empty($objectid)) {
8647 $InfoFieldList[4] = str_replace(
'$ID$', (
string) $objectid, $InfoFieldList[4]);
8649 $InfoFieldList[4] = str_replace(
'$ID$',
'0', $InfoFieldList[4]);
8654 if (strpos($InfoFieldList[4],
'extra') !==
false) {
8655 $sql .=
' as main, ' . $this->db->sanitize($this->db->prefix() . $InfoFieldList[0]) .
'_extrafields as extra';
8656 $sqlwhere .=
" WHERE extra.fk_object = main." . $this->db->sanitize($InfoFieldList[2]);
8662 $sqlwhere .=
' WHERE 1=1';
8679 if (in_array($InfoFieldList[0], array(
'tablewithentity'))) {
8680 $sqlwhere .=
" AND entity = " . ((int)
$conf->entity);
8687 dol_syslog(get_class($this) .
'::showInputField type=chkbxlst', LOG_DEBUG);
8689 $resql = $this->db->query($sql);
8691 $num = $this->db->num_rows($resql);
8698 $obj = $this->db->fetch_object($resql);
8702 $fields_label = explode(
'|', $InfoFieldList[1]);
8703 if (count($fields_label) > 1) {
8705 foreach ($fields_label as $field_toshow) {
8706 $labeltoshow .= $obj->$field_toshow .
' ';
8709 $labeltoshow = $obj->{$InfoFieldList[1]};
8711 $labeltoshow =
dol_trunc($labeltoshow, 45);
8713 if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
8714 foreach ($fields_label as $field_toshow) {
8715 $translabel = $langs->trans($obj->$field_toshow);
8716 if ($translabel != $obj->$field_toshow) {
8717 $labeltoshow =
dol_trunc($translabel, 18) .
' ';
8719 $labeltoshow =
dol_trunc($obj->$field_toshow, 18) .
' ';
8723 $data[$obj->rowid] = $labeltoshow;
8726 $translabel = $langs->trans($obj->{$InfoFieldList[1]});
8727 if ($translabel != $obj->{$InfoFieldList[1]}) {
8728 $labeltoshow =
dol_trunc($translabel, 18);
8730 $labeltoshow =
dol_trunc($obj->{$InfoFieldList[1]}, 18);
8733 if (empty($labeltoshow)) {
8734 $labeltoshow =
'(not defined)';
8737 if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
8738 $data[$obj->rowid] = $labeltoshow;
8741 if (!empty($InfoFieldList[3]) && $parentField) {
8742 $parent = $parentName .
':' . $obj->{$parentField};
8746 $data[$obj->rowid] = $labeltoshow;
8751 $this->db->free($resql);
8753 $out = $form->multiselectarray($keyprefix . $key . $keysuffix, $data, $value_arr, 0, 0, $morecss, 0,
'100%');
8755 print
'Error in request ' . $sql .
' ' . $this->db->lasterror() .
'. Check setup of extra parameters.<br>';
8758 require_once DOL_DOCUMENT_ROOT.
'/categories/class/categorie.class.php';
8759 $categcode = $InfoFieldList[5];
8760 if (is_numeric($categcode)) {
8761 $tmpcategory =
new Categorie($this->db);
8762 $MAP_ID_TO_CODE = array_flip($tmpcategory->MAP_ID);
8763 $categcode = $MAP_ID_TO_CODE[(int) $categcode];
8766 $data = $form->select_all_categories($categcode,
'',
'parent', 64, $InfoFieldList[6], 1, 1);
8767 $out = $form->multiselectarray($keyprefix . $key . $keysuffix, $data, $value_arr, 0, 0, $morecss, 0,
'100%');
8770 } elseif ($type ==
'link') {
8773 $param_list = array_keys($param[
'options']);
8774 $param_list_array = explode(
':', $param_list[0], 4);
8776 $showempty = (($required && $default !=
'') ? 0 : 1);
8778 if (!preg_match(
'/search_/', $keyprefix)) {
8779 if (!empty($param_list_array[2])) {
8781 if (!empty($this->fields[$key][
'picto'])) {
8782 $morecss .=
' widthcentpercentminusxx';
8784 $morecss .=
' widthcentpercentminusx';
8788 if (!empty($this->fields[$key][
'picto'])) {
8789 $morecss .=
' widthcentpercentminusx';
8798 $objectfield = $val;
8801 $out = $form->selectForForms($param_list_array[0], $keyprefix.$key.$keysuffix, (
int) $value, $showempty,
'',
'', $morecss, $moreparam, 0, (empty($val[
'disabled']) ? 0 : 1),
'', $objectfield);
8803 if (!empty($param_list_array[2])) {
8804 if ((!
GETPOSTISSET(
'backtopage') || strpos(
GETPOST(
'backtopage'), $_SERVER[
'PHP_SELF']) === 0)
8805 && empty($val[
'disabled']) && empty($nonewbutton)) {
8806 list($class, $classfile) = explode(
':', $param_list[0]);
8807 if (file_exists(
dol_buildpath(dirname(dirname($classfile)).
'/card.php'))) {
8808 $url_path =
dol_buildpath(dirname(dirname($classfile)).
'/card.php', 1);
8810 $url_path =
dol_buildpath(dirname(dirname($classfile)).
'/'.strtolower($class).
'_card.php', 1);
8812 $paramforthenewlink =
'';
8813 $paramforthenewlink .= (
GETPOSTISSET(
'action') ?
'&action='.GETPOST(
'action',
'aZ09') :
'');
8814 $paramforthenewlink .= (
GETPOSTISSET(
'id') ?
'&id='.GETPOSTINT(
'id') :
'');
8815 $paramforthenewlink .= (
GETPOSTISSET(
'origin') ?
'&origin='.GETPOST(
'origin',
'aZ09') :
'');
8816 $paramforthenewlink .= (
GETPOSTISSET(
'originid') ?
'&originid='.GETPOSTINT(
'originid') :
'');
8817 $paramforthenewlink .=
'&fk_'.strtolower($class).
'=--IDFORBACKTOPAGE--';
8819 $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>';
8822 } elseif ($type ==
'password') {
8824 if ($keyprefix.$key.$keysuffix ==
'pass_crypted') {
8825 $out =
'<input type="'.($keyprefix ==
'search_' ?
'text' :
'password').
'" class="flat '.$morecss.
'" name="pass" id="pass" value="" '.($moreparam ? $moreparam :
'').
'>';
8826 $out .=
'<input type="hidden" name="pass_crypted" id="pass_crypted" value="'.$value.
'" '.($moreparam ? $moreparam :
'').
'>';
8828 $out =
'<input type="'.($keyprefix ==
'search_' ?
'text' :
'password').
'" class="flat '.$morecss.
'" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.$value.
'" '.($moreparam ? $moreparam :
'').
'>';
8830 } elseif ($type ==
'array') {
8832 $newval[
'type'] =
'varchar(256)';
8835 if (!empty($value)) {
8836 foreach ($value as $option) {
8837 $out .=
'<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).
'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
8838 $out .= $this->showInputField($newval, $keyprefix.$key.$keysuffix.
'[]', $option, $moreparam,
'',
'', $morecss).
'<br></span>';
8841 $out .=
'<a id="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).
'_add" href="javascript:;"><span class="fa fa-plus-circle valignmiddle"></span></a>';
8843 $newInput =
'<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).
'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
8844 $newInput .= $this->showInputField($newval, $keyprefix.$key.$keysuffix.
'[]',
'', $moreparam,
'',
'', $morecss).
'<br></span>';
8846 if (!empty(
$conf->use_javascript_ajax)) {
8848 <script nonce="'.getNonce().
'">
8849 $(document).ready(function() {
8850 $(\'a#'.
dol_escape_js($keyprefix.$key.$keysuffix).
'_add\').click(function() {
8854 $(document).on(
"click", \
'a.'.
dol_escape_js($keyprefix.$key.$keysuffix).
'_del\', function() {
8855 $(this).parent().remove();
8861 if (!empty($hidden)) {
8862 $out =
'<input type="hidden" value="'.$value.
'" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'"/>';
8865 if ($isDependList == 1) {
8866 $out .= $this->getJSListDependancies(
'_common');
8874 if (!empty($fieldValidationErrorMsg) && function_exists(
'getFieldErrorIcon')) {
8875 $out .=
' '.getFieldErrorIcon($fieldValidationErrorMsg);
8894 public function showOutputField($val, $key, $value, $moreparam =
'', $keysuffix =
'', $keyprefix =
'', $morecss =
'')
8896 global
$conf, $langs, $form;
8900 if (!is_object($form)) {
8901 require_once DOL_DOCUMENT_ROOT.
'/core/class/html.form.class.php';
8902 $form =
new Form($this->db);
8906 $type = empty($val[
'type']) ?
'' : $val[
'type'];
8907 $size = empty($val[
'css']) ?
'' : $val[
'css'];
8912 if (preg_match(
'/varchar\((\d+)\)/', $type, $reg)) {
8915 } elseif (preg_match(
'/varchar/', $type)) {
8918 if (!empty($val[
'arrayofkeyval']) && is_array($val[
'arrayofkeyval'])) {
8920 if (empty($this->fields[$key][
'multiinput'])) {
8921 $type = (($this->fields[$key][
'type'] ==
'checkbox') ? $this->fields[$key][
'type'] :
'select');
8924 if (isset($val[
'type']) && preg_match(
'/^integer:(.*):(.*)/i', $val[
'type'], $reg)) {
8928 $default = empty($val[
'default']) ?
'' : $val[
'default'];
8929 $computed = empty($val[
'computed']) ?
'' : $val[
'computed'];
8930 $unique = empty($val[
'unique']) ?
'' : $val[
'unique'];
8931 $required = empty($val[
'required']) ?
'' : $val[
'required'];
8933 $param[
'options'] = array();
8935 if (!empty($val[
'arrayofkeyval']) && is_array($val[
'arrayofkeyval'])) {
8936 $param[
'options'] = $val[
'arrayofkeyval'];
8938 if (isset($val[
'type']) && preg_match(
'/^integer:([^:]*):([^:]*)/i', $val[
'type'], $reg)) {
8940 $stringforoptions = $reg[1].
':'.$reg[2];
8942 if ($reg[1] ==
'User') {
8943 $stringforoptions .=
':#getnomurlparam1=-1';
8945 $param[
'options'] = array($stringforoptions => $stringforoptions);
8946 } elseif (isset($val[
'type']) && preg_match(
'/^sellist:(.*):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
8947 $param[
'options'] = array($reg[1].
':'.$reg[2].
':'.$reg[3].
':'.$reg[4] =>
'N');
8949 } elseif (isset($val[
'type']) && preg_match(
'/^sellist:(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
8950 $param[
'options'] = array($reg[1].
':'.$reg[2].
':'.$reg[3] =>
'N');
8952 } elseif (isset($val[
'type']) && preg_match(
'/^sellist:(.*):(.*)/i', $val[
'type'], $reg)) {
8953 $param[
'options'] = array($reg[1].
':'.$reg[2] =>
'N');
8955 } elseif (isset($val[
'type']) && preg_match(
'/^chkbxlst:(.*)/i', $val[
'type'], $reg)) {
8956 $param[
'options'] = array($reg[1] =>
'N');
8958 } elseif (isset($val[
'type']) && preg_match(
'/stars\((\d+)\)/', $val[
'type'], $reg)) {
8959 $param[
'options'] = array();
8964 $langfile = empty($val[
'langfile']) ?
'' : $val[
'langfile'];
8965 $list = (empty($val[
'list']) ?
'' : $val[
'list']);
8966 $help = (empty($val[
'help']) ?
'' : $val[
'help']);
8967 $hidden = (($val[
'visible'] == 0) ? 1 : 0);
8977 $value =
dol_eval((
string) $computed, 1, 0,
'2');
8980 if (empty($morecss)) {
8981 if ($type ==
'date') {
8982 $morecss =
'minwidth100imp';
8983 } elseif ($type ==
'datetime' || $type ==
'timestamp') {
8984 $morecss =
'minwidth200imp';
8985 } elseif (in_array($type, array(
'int',
'double',
'price'))) {
8986 $morecss =
'maxwidth75';
8987 } elseif ($type ==
'url') {
8988 $morecss =
'minwidth400';
8989 } elseif ($type ==
'boolean') {
8992 if (is_numeric($size) && round((
float) $size) < 12) {
8993 $morecss =
'minwidth100';
8994 } elseif (is_numeric($size) && round((
float) $size) <= 48) {
8995 $morecss =
'minwidth200';
8997 $morecss =
'minwidth400';
9003 if (in_array($key, array(
'rowid',
'ref')) && method_exists($this,
'getNomUrl')) {
9005 if ($key !=
'rowid' || empty($this->fields[
'ref'])) {
9006 $value = $this->getNomUrl(1,
'', 0,
'', 1);
9008 } elseif ($key ==
'status' && method_exists($this,
'getLibStatut')) {
9009 $value = $this->getLibStatut(3);
9010 } elseif ($type ==
'date') {
9011 if (!empty($value)) {
9016 } elseif ($type ==
'datetime' || $type ==
'timestamp') {
9017 if (!empty($value)) {
9022 } elseif ($type ==
'duration') {
9023 include_once DOL_DOCUMENT_ROOT.
'/core/lib/date.lib.php';
9024 if (!is_null($value) && $value !==
'') {
9027 } elseif ($type ==
'double' || $type ==
'real') {
9028 if (!is_null($value) && $value !==
'') {
9029 $value =
price($value);
9031 } elseif ($type ==
'boolean') {
9033 if (!empty($value)) {
9034 $checked =
' checked ';
9037 $value =
'<input type="checkbox" '.$checked.
' '.($moreparam ? $moreparam :
'').
' readonly disabled>';
9039 $value = yn($value ? 1 : 0);
9041 } elseif ($type ==
'mail' || $type ==
'email') {
9043 } elseif ($type ==
'url') {
9045 } elseif ($type ==
'phone') {
9046 $value =
dol_print_phone((
string) $value,
'', 0, 0,
'',
' ',
'phone');
9047 } elseif ($type ==
'ip') {
9049 } elseif ($type ==
'stars') {
9050 $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 :
'').
'>';
9051 $value .=
'<div class="star-selection" id="'.$keyprefix.$key.$keysuffix.$this->id.
'_selection">';
9053 while ($i <= $size) {
9054 $value .=
'<span class="star" data-value="'.$i.
'">'.img_picto(
'',
'fontawesome_star_fas').
'</span>';
9059 $(document).ready(function() { /* commonobject.class.php 2 */
9060 let container = $("#'.$keyprefix.$key.$keysuffix.$this->id.
'_selection");
9061 let selectedStars = parseInt($("#'.$keyprefix.$key.$keysuffix.$this->id.
'").val()) || 0;
9062 container.find(".star").each(function() {
9063 $(this).toggleClass("active", $(this).data("value") <= selectedStars);
9065 container.find(".star").on("mouseover", function() {
9066 let selectedStar = $(this).data("value");
9067 container.find(".star").each(function() {
9068 $(this).toggleClass("active", $(this).data("value") <= selectedStar);
9071 container.on("mouseout", function() {
9072 container.find(".star").each(function() {
9073 $(this).toggleClass("active", $(this).data("value") <= selectedStars);
9076 container.find(".star").off("click").on("click", function() {
9077 selectedStars = $(this).data("value");
9078 if (selectedStars == 1 && $("#'.$keyprefix.$key.$keysuffix.$this->id.
'").val() == 1) {
9081 container.find("#'.$keyprefix.$key.$keysuffix.$this->id.
'").val(selectedStars);
9082 container.find(".star").each(function() {
9083 $(this).toggleClass("active", $(this).data("value") <= selectedStars);
9086 url: "ajax/'.$this->element.
'.php",
9089 objectId: "'.$this->
id.
'",
9090 field: "'.$keyprefix.$key.$keysuffix.
'",
9091 value: selectedStars,
9094 success: function(response) {
9095 var res = JSON.parse(response);
9096 console[res.status === "success" ? "log" : "error"](res.message);
9098 error: function(xhr, status, error) {
9099 console.log("Ajax request failed while updating '.$keyprefix.$key.$keysuffix.
':", error);
9105 } elseif ($type ==
'price') {
9106 if (!is_null($value) && $value !==
'') {
9107 $value =
price($value, 0, $langs, 0, 0, -1,
$conf->currency);
9109 } elseif ($type ==
'select') {
9110 $value = isset($param[
'options'][(
string) $value]) ? $param[
'options'][(string) $value] :
'';
9111 if (strpos($value,
"|") !==
false) {
9112 $value = $langs->trans(explode(
'|', $value)[0]);
9113 } elseif (! is_numeric($value)) {
9114 $value = $langs->trans($value);
9116 } elseif ($type ==
'sellist') {
9117 $param_list = array_keys($param[
'options']);
9118 $InfoFieldList = explode(
":", $param_list[0]);
9120 $selectkey =
"rowid";
9123 if (count($InfoFieldList) > 2 && !empty($InfoFieldList[2])) {
9124 $selectkey = $InfoFieldList[2];
9125 $keyList = $InfoFieldList[2].
' as rowid';
9128 $fields_label = explode(
'|', $InfoFieldList[1]);
9129 if (is_array($fields_label)) {
9131 $keyList .= implode(
', ', $fields_label);
9134 $filter_categorie =
false;
9135 if (count($InfoFieldList) > 5) {
9136 if ($InfoFieldList[0] ==
'categorie') {
9137 $filter_categorie =
true;
9141 $sql =
"SELECT ".$this->db->sanitize($keyList, 0, 0, 1);
9142 $sql .=
' FROM '.$this->db->prefix().$this->db->sanitize($InfoFieldList[0]);
9143 if (isset($InfoFieldList[4]) && strpos($InfoFieldList[4],
'extra') !==
false) {
9146 if ($selectkey ==
'rowid' && empty($value)) {
9147 $sql .=
" WHERE ".$this->db->sanitize($selectkey).
" = 0";
9148 } elseif ($selectkey ==
'rowid') {
9149 $sql .=
" WHERE ".$this->db->sanitize($selectkey).
" = ".((int) $value);
9151 $sql .=
" WHERE ".$this->db->sanitize($selectkey).
" = '".$this->db->escape((
string) $value).
"'";
9156 dol_syslog(get_class($this).
':showOutputField:$type=sellist', LOG_DEBUG);
9157 $resql = $this->db->query($sql);
9159 if (!$filter_categorie) {
9161 $numrows = $this->db->num_rows($resql);
9163 $obj = $this->db->fetch_object($resql);
9166 $fields_label = explode(
'|', $InfoFieldList[1]);
9168 if (is_array($fields_label) && count($fields_label) > 1) {
9169 foreach ($fields_label as $field_toshow) {
9171 if (!empty($obj->$field_toshow)) {
9172 $translabel = $langs->trans($obj->$field_toshow);
9174 if ($translabel != $field_toshow) {
9175 $value .=
dol_trunc($translabel, 18) .
' ';
9177 $value .= $obj->$field_toshow .
' ';
9182 if (!empty($obj->{$InfoFieldList[1]})) {
9183 $translabel = $langs->trans($obj->{$InfoFieldList[1]});
9185 if ($translabel != $obj->{$InfoFieldList[1]}) {
9188 $value = $obj->{$InfoFieldList[1]};
9193 require_once DOL_DOCUMENT_ROOT .
'/categories/class/categorie.class.php';
9196 $obj = $this->db->fetch_object($resql);
9198 $c->fetch($obj->rowid);
9199 $ways =
$c->print_all_ways();
9200 foreach ($ways as $way) {
9201 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories"' . (
$c->color ?
' style="background: #' .
$c->color .
';"' :
' style="background: #aaa"') .
'>' . img_object(
'',
'category') .
' ' . $way .
'</li>';
9203 $value =
'<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(
' ', $toprint).
'</ul></div>';
9206 dol_syslog(get_class($this).
'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
9208 } elseif ($type ==
'radio') {
9209 $value = $param[
'options'][(string) $value];
9210 } elseif ($type ==
'checkbox') {
9211 $value_arr = explode(
',', (
string) $value);
9213 if (is_array($value_arr) && count($value_arr) > 0) {
9215 foreach ($value_arr as $keyval => $valueval) {
9216 if (!empty($valueval)) {
9217 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' . $param[
'options'][$valueval] .
'</li>';
9220 if (!empty($toprint)) {
9221 $value =
'<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">' . implode(
' ', $toprint) .
'</ul></div>';
9224 } elseif ($type ==
'chkbxlst') {
9225 $value_arr = (isset($value) ? explode(
',', $value) : array());
9227 $param_list = array_keys($param[
'options']);
9228 $InfoFieldList = explode(
":", $param_list[0]);
9230 $selectkey =
"rowid";
9233 if (count($InfoFieldList) >= 3) {
9234 $selectkey = $InfoFieldList[2];
9235 $keyList = $InfoFieldList[2].
' as rowid';
9238 $fields_label = explode(
'|', $InfoFieldList[1]);
9239 if (is_array($fields_label)) {
9241 $keyList .= implode(
', ', $fields_label);
9244 $filter_categorie =
false;
9245 if (count($InfoFieldList) > 5) {
9246 if ($InfoFieldList[0] ==
'categorie') {
9247 $filter_categorie =
true;
9251 $sql =
"SELECT ".$this->db->sanitize($keyList, 0, 0, 1);
9252 $sql .=
' FROM '.$this->db->prefix().$this->db->sanitize($InfoFieldList[0]);
9253 if (isset($InfoFieldList[4]) && strpos($InfoFieldList[4],
'extra') !==
false) {
9259 dol_syslog(get_class($this).
':showOutputField:$type=chkbxlst', LOG_DEBUG);
9260 $resql = $this->db->query($sql);
9262 if (!$filter_categorie) {
9265 while ($obj = $this->db->fetch_object($resql)) {
9267 $fields_label = explode(
'|', $InfoFieldList[1]);
9268 if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
9269 if (is_array($fields_label) && count($fields_label) > 1) {
9270 foreach ($fields_label as $field_toshow) {
9272 if (!empty($obj->$field_toshow)) {
9273 $translabel = $langs->trans($obj->$field_toshow);
9275 if ($translabel != $field_toshow) {
9276 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' .
dol_trunc($translabel, 18) .
'</li>';
9278 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' . $obj->$field_toshow .
'</li>';
9283 if (!empty($obj->{$InfoFieldList[1]})) {
9284 $translabel = $langs->trans($obj->{$InfoFieldList[1]});
9286 if ($translabel != $obj->{$InfoFieldList[1]}) {
9287 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' .
dol_trunc($translabel, 18) .
'</li>';
9289 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' . $obj->{$InfoFieldList[1]} .
'</li>';
9295 require_once DOL_DOCUMENT_ROOT .
'/categories/class/categorie.class.php';
9298 while ($obj = $this->db->fetch_object($resql)) {
9299 if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
9301 $c->fetch($obj->rowid);
9302 $ways =
$c->print_all_ways();
9303 foreach ($ways as $way) {
9304 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories"' . (
$c->color ?
' style="background: #' .
$c->color .
';"' :
' style="background: #aaa"') .
'>' . img_object(
'',
'category') .
' ' . $way .
'</li>';
9309 $value =
'<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(
' ', $toprint).
'</ul></div>';
9311 dol_syslog(get_class($this).
'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
9313 } elseif ($type ==
'link') {
9318 $param_list = array_keys($param[
'options']);
9322 $InfoFieldList = explode(
":", $param_list[0]);
9324 $classname = $InfoFieldList[0];
9325 $classpath = $InfoFieldList[1];
9328 $getnomurlparam = 3;
9329 $getnomurlparam2 =
'';
9331 if (preg_match(
'/#getnomurlparam1=([^#]*)/', $param_list[0], $regtmp)) {
9332 $getnomurlparam = $regtmp[1];
9334 if (preg_match(
'/#getnomurlparam2=([^#]*)/', $param_list[0], $regtmp)) {
9335 $getnomurlparam2 = $regtmp[1];
9338 if (!empty($classpath)) {
9341 if ($classname && !class_exists($classname)) {
9345 if ($element_prop) {
9346 $classname = $element_prop[
'classname'];
9351 if ($classname && class_exists($classname)) {
9352 $object =
new $classname($this->db);
9353 '@phan-var-force CommonObject $object';
9354 if (
$object->element ===
'product') {
9355 '@phan-var-force Product $object';
9356 $result =
$object->fetch((
int) $value,
'',
'',
'', 0, 1, 1);
9358 $result =
$object->fetch($value);
9361 if (
$object->element ===
'product') {
9362 '@phan-var-force Product $object';
9363 $get_name_url_param_arr = array($getnomurlparam, $getnomurlparam2, 0, -1, 0,
'', 0);
9364 if (isset($val[
'get_name_url_params'])) {
9365 $get_name_url_params = explode(
':', $val[
'get_name_url_params']);
9366 if (!empty($get_name_url_params)) {
9367 $param_num_max = count($get_name_url_param_arr) - 1;
9368 foreach ($get_name_url_params as $param_num => $param_value) {
9369 if ($param_num > $param_num_max) {
9372 $get_name_url_param_arr[$param_num] = $param_value;
9380 $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]);
9382 $value =
$object->getNomUrl($getnomurlparam, $getnomurlparam2);
9389 dol_syslog(
'Error bad setup of extrafield', LOG_WARNING);
9390 return 'Error bad setup of extrafield';
9395 } elseif ($type ==
'password') {
9396 $value =
'<span class="opacitymedium">'.$langs->trans(
"Encrypted").
'</span>';
9398 } elseif ($type ==
'array') {
9399 if (is_array($value)) {
9400 $value = implode(
'<br>', $value);
9402 dol_syslog(__METHOD__.
' Expected array from dol_eval, but got '.gettype($value), LOG_ERR);
9403 return 'Error unexpected result from code evaluation';
9406 if (!empty($value) && preg_match(
'/^text/', (
string) $type) && !preg_match(
'/search_/', $keyprefix) && !empty($param[
'options'])) {
9407 $value = str_replace(
',',
"\n", $value);
9415 return is_null($out) ?
'' : $out;
9427 unset($this->validateFieldsErrors[$fieldKey]);
9441 $msg = $langs->trans(
"UnknownError");
9444 $this->error = $this->validateFieldsErrors[$fieldKey] = $msg;
9455 if (!empty($this->validateFieldsErrors[$fieldKey])) {
9456 return $this->validateFieldsErrors[$fieldKey];
9473 if (!class_exists(
'Validate')) {
9474 require_once DOL_DOCUMENT_ROOT .
'/core/class/validate.class.php';
9477 $this->clearFieldError($fieldKey);
9479 if (!array_key_exists($fieldKey, $fields) || !is_array($fields[$fieldKey])) {
9480 $this->setFieldError($fieldKey, $langs->trans(
'FieldNotFoundInObject'));
9484 $val = $fields[$fieldKey];
9487 $param[
'options'] = array();
9488 $type = $val[
'type'];
9491 if (isset($val[
'notnull']) && $val[
'notnull'] === 1) {
9505 if (preg_match(
'/varchar\((\d+)\)/', $type, $reg)) {
9507 $maxSize = (int) $reg[1];
9508 } elseif (preg_match(
'/varchar/', $type)) {
9512 if (!empty($val[
'arrayofkeyval']) && is_array($val[
'arrayofkeyval'])) {
9516 if (!empty($val[
'type']) && preg_match(
'/^integer:(.*):(.*)/i', $val[
'type'], $reg)) {
9520 if (!empty($val[
'arrayofkeyval']) && is_array($val[
'arrayofkeyval'])) {
9521 $param[
'options'] = $val[
'arrayofkeyval'];
9524 if (preg_match(
'/^integer:(.*):(.*)/i', $val[
'type'], $reg)) {
9526 $param[
'options'] = array($reg[1].
':'.$reg[2] => $reg[1].
':'.$reg[2]);
9527 } elseif (preg_match(
'/^sellist:(.*):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
9528 $param[
'options'] = array($reg[1].
':'.$reg[2].
':'.$reg[3].
':'.$reg[4] =>
'N');
9530 } elseif (preg_match(
'/^sellist:(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
9531 $param[
'options'] = array($reg[1].
':'.$reg[2].
':'.$reg[3] =>
'N');
9533 } elseif (preg_match(
'/^sellist:(.*):(.*)/i', $val[
'type'], $reg)) {
9534 $param[
'options'] = array($reg[1].
':'.$reg[2] =>
'N');
9543 $validate =
new Validate($this->db, $langs);
9553 if ($required && !$validate->isNotEmptyString($fieldValue)) {
9554 $this->setFieldError($fieldKey, $validate->error);
9556 } elseif (!$required && !$validate->isNotEmptyString($fieldValue)) {
9562 if (!empty($maxSize) && !$validate->isMaxLength($fieldValue, $maxSize)) {
9563 $this->setFieldError($fieldKey, $validate->error);
9568 if (!empty($minSize) && !$validate->isMinLength($fieldValue, $minSize)) {
9569 $this->setFieldError($fieldKey, $validate->error);
9577 if (in_array($type, array(
'date',
'datetime',
'timestamp'))) {
9578 if (!$validate->isTimestamp($fieldValue)) {
9579 $this->setFieldError($fieldKey, $validate->error);
9584 } elseif ($type ==
'duration') {
9585 if (!$validate->isDuration($fieldValue)) {
9586 $this->setFieldError($fieldKey, $validate->error);
9591 } elseif (in_array($type, array(
'double',
'real',
'price'))) {
9593 if (!$validate->isNumeric($fieldValue)) {
9594 $this->setFieldError($fieldKey, $validate->error);
9599 } elseif ($type ==
'boolean') {
9600 if (!$validate->isBool($fieldValue)) {
9601 $this->setFieldError($fieldKey, $validate->error);
9606 } elseif ($type ==
'mail' || $type ==
'email') {
9607 if (!$validate->isEmail($fieldValue)) {
9608 $this->setFieldError($fieldKey, $validate->error);
9611 } elseif ($type ==
'url') {
9612 if (!$validate->isUrl($fieldValue)) {
9613 $this->setFieldError($fieldKey, $validate->error);
9618 } elseif ($type ==
'phone') {
9619 if (!$validate->isPhone($fieldValue)) {
9620 $this->setFieldError($fieldKey, $validate->error);
9625 } elseif ($type ==
'select' || $type ==
'radio') {
9626 if (!isset($param[
'options'][$fieldValue])) {
9627 $this->error = $langs->trans(
'RequireValidValue');
9632 } elseif ($type ==
'sellist' || $type ==
'chkbxlst') {
9633 $param_list = array_keys($param[
'options']);
9634 $InfoFieldList = explode(
":", $param_list[0]);
9635 $value_arr = explode(
',', $fieldValue);
9637 $selectkey =
"rowid";
9638 if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
9639 $selectkey = $InfoFieldList[2];
9642 if (!$validate->isInDb($value_arr, $InfoFieldList[0], $selectkey)) {
9643 $this->setFieldError($fieldKey, $validate->error);
9648 } elseif ($type ==
'link') {
9649 $param_list = array_keys($param[
'options']);
9650 $InfoFieldList = explode(
":", $param_list[0]);
9651 $classname = $InfoFieldList[0];
9652 $classpath = $InfoFieldList[1];
9653 if (!$validate->isFetchable((
int) $fieldValue, $classname, $classpath)) {
9654 $lastIsFetchableError = $validate->error;
9657 if ($validate->isFetchableElement((
int) $fieldValue, $classname)) {
9661 $this->setFieldError($fieldKey, $lastIsFetchableError);
9685 public function showOptionals($extrafields, $mode =
'view', $params =
null, $keysuffix =
'', $keyprefix =
'', $onetrtd =
'', $display_type =
'card')
9687 global $db,
$conf, $langs, $action, $form, $hookmanager;
9688 global $objectoffield;
9690 if (!is_object($form)) {
9691 $form =
new Form($db);
9693 if (!is_object($extrafields)) {
9694 dol_syslog(
'Bad parameter extrafields for showOptionals', LOG_ERR);
9695 return 'Bad parameter extrafields for showOptionals';
9697 if (!is_array($extrafields->attributes[$this->table_element])) {
9698 dol_syslog(
"extrafields->attributes was not loaded with extrafields->fetch_name_optionals_label(table_element);", LOG_WARNING);
9702 $objectoffield = $this;
9706 $parameters = array(
'mode' => $mode,
'params' => $params,
'keysuffix' => $keysuffix,
'keyprefix' => $keyprefix,
'display_type' => $display_type);
9707 $reshook = $hookmanager->executeHooks(
'showOptionals', $parameters, $this, $action);
9708 $hookResPrint = $hookmanager->resPrint;
9710 if (empty($reshook)) {
9711 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) {
9713 $out .=
'<!-- commonobject:showOptionals --> ';
9716 $nbofextrafieldsshown = 0;
9719 $lastseparatorkeyfound =
'';
9720 $extrafields_collapse_num =
'';
9721 $extrafields_collapse_num_old =
'';
9724 foreach ($extrafields->attributes[$this->table_element][
'label'] as $key => $label) {
9728 if (is_array($params) && array_key_exists(
'onlykey', $params) && $key != $params[
'onlykey']) {
9734 if ($enabled && isset($extrafields->attributes[$this->table_element][
'enabled'][$key])) {
9735 $enabled = (int)
dol_eval((
string) $extrafields->attributes[$this->table_element][
'enabled'][$key], 1, 1,
'2');
9737 if (empty($enabled)) {
9742 if (isset($extrafields->attributes[$this->table_element][
'list'][$key])) {
9743 $visibility = (int)
dol_eval((
string) $extrafields->attributes[$this->table_element][
'list'][$key], 1, 1,
'2');
9747 if ($perms && isset($extrafields->attributes[$this->table_element][
'perms'][$key])) {
9748 $perms = (int)
dol_eval((
string) $extrafields->attributes[$this->table_element][
'perms'][$key], 1, 1,
'2');
9751 if (($mode ==
'create') && !in_array(abs($visibility), array(1, 3))) {
9753 } elseif (($mode ==
'edit') && !in_array(abs($visibility), array(1, 3, 4))) {
9757 $ef_name =
'options_' . $key;
9758 $ef_value = $this->array_options[$ef_name] ??
'';
9759 $out .=
'<input type="hidden" name="' . $ef_name .
'" id="' . $ef_name .
'" value="' . dolPrintHTMLForAttribute($ef_value) .
'" />' .
"\n";
9761 } elseif ($mode ==
'view' && empty($visibility)) {
9764 if (empty($perms)) {
9769 if (!empty($extrafields->attributes[$this->table_element][
'langfile'][$key])) {
9770 $langs->load($extrafields->attributes[$this->table_element][
'langfile'][$key]);
9775 if (is_array($params) && count($params) > 0 && $display_type ==
'card') {
9776 if (array_key_exists(
'cols', $params)) {
9777 $colspan = $params[
'cols'];
9778 } elseif (array_key_exists(
'colspan', $params)) {
9780 if (preg_match(
'/colspan="(\d+)"/', $params[
'colspan'], $reg)) {
9783 $colspan = $params[
'colspan'];
9787 $colspan = intval($colspan);
9791 $value = ((!empty($this->array_options) && array_key_exists(
"options_".$key.$keysuffix, $this->array_options)) ? $this->array_options[
"options_".$key.$keysuffix] :
null);
9797 $check =
'alphanohtml';
9798 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'html',
'text'))) {
9799 $check =
'restricthtml';
9801 $getposttemp =
GETPOST($keyprefix.
'options_'.$key.$keysuffix, $check, 3);
9803 if (is_array($getposttemp) || $getposttemp !=
'' ||
GETPOSTISSET($keyprefix.
'options_'.$key.$keysuffix)) {
9804 if (is_array($getposttemp)) {
9806 $value = implode(
",", $getposttemp);
9808 $value = $getposttemp;
9810 } elseif (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'int'))) {
9811 $value = (!empty($this->array_options[
"options_".$key]) || (isset($this->array_options[
"options_".$key]) && $this->array_options[
"options_".$key] ===
'0')) ? $this->array_options[
"options_".$key] :
'';
9812 } elseif (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'varchar',
'char'))) {
9813 $value = (isset($this->array_options[
"options_".$key]) && $this->array_options[
"options_".$key] !==
'') ? $this->array_options[
"options_".$key] :
'';
9815 $value = (!empty($this->array_options[
"options_".$key]) ? $this->array_options[
"options_".$key] :
'');
9821 $nbofextrafieldsshown++;
9824 if ($extrafields->attributes[$this->table_element][
'type'][$key] ==
'separate') {
9825 $extrafields_collapse_num = $key;
9843 $out .= $extrafields->showSeparator($key, $this, ($colspan ? $colspan + 1 : 2), $display_type, $mode);
9845 $lastseparatorkeyfound = $key;
9847 $collapse_group = $extrafields_collapse_num.(!empty($this->
id) ?
'_'.$this->id :
'');
9849 $class = (!empty($extrafields->attributes[$this->table_element][
'hidden'][$key]) ?
'hideobject ' :
'');
9851 if (is_array($params) && count($params) > 0) {
9852 if (array_key_exists(
'class', $params)) {
9853 $class .= $params[
'class'].
' ';
9855 if (array_key_exists(
'style', $params)) {
9856 $csstyle = $params[
'style'];
9861 $domData =
' data-element="extrafield"';
9862 $domData .=
' data-targetelement="'.$this->element.
'"';
9863 $domData .=
' data-targetid="'.$this->id.
'"';
9865 $html_id = (empty($this->
id) ?
'' :
'extrarow-'.$this->element.
'_'.$key.
'_'.
$this->id);
9866 if ($display_type ==
'card') {
9871 if ($action ==
'selectlines') {
9878 $force_values_on_change_company = (
9879 ($this->element ==
'facture' &&
getDolGlobalInt(
'THIRDPARTY_PROPAGATE_EXTRAFIELDS_TO_INVOICE'))
9880 || ($this->element ==
'commande' &&
getDolGlobalInt(
'THIRDPARTY_PROPAGATE_EXTRAFIELDS_TO_ORDER'))
9881 || ($this->element ==
'order_supplier' &&
getDolGlobalInt(
'THIRDPARTY_PROPAGATE_EXTRAFIELDS_TO_SUPPLIER_ORDER'))
9883 if ($force_values_on_change_company &&
GETPOSTINT(
'changecompany')) {
9884 $value = $this->array_options[
'options_'.$key] ?? $value;
9888 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'date'))) {
9889 $datenotinstring =
null;
9890 if (array_key_exists(
'options_'.$key, $this->array_options)) {
9891 $datenotinstring = $this->array_options[
'options_'.$key];
9892 if (!is_numeric($this->array_options[
'options_'.$key])) {
9893 $datenotinstring = $this->db->jdate($datenotinstring);
9896 $datekey = $keyprefix.
'options_'.$key.$keysuffix;
9899 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'datetime'))) {
9900 $datenotinstring =
null;
9901 if (array_key_exists(
'options_'.$key, $this->array_options)) {
9902 $datenotinstring = $this->array_options[
'options_'.$key];
9903 if (!is_numeric($this->array_options[
'options_'.$key])) {
9904 $datenotinstring = $this->db->jdate($datenotinstring);
9907 $timekey = $keyprefix.
'options_'.$key.$keysuffix;
9908 $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;
9911 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'price',
'double'))) {
9912 if (
GETPOSTISSET($keyprefix.
'options_'.$key.$keysuffix) || $value) {
9914 } elseif (isset($this->array_options[
'options_'.$key])) {
9915 $value = $this->array_options[
'options_'.$key];
9920 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'html',
'text',
'varchar',
'select',
'radio',
'int',
'boolean'))) {
9921 if ($action ==
'create' || $mode ==
'create') {
9922 $value = (
GETPOSTISSET($keyprefix.
'options_'.$key.$keysuffix) || $value) ? $value : $extrafields->attributes[$this->table_element][
'default'][$key];
9926 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'checkbox'))) {
9927 if ($action ==
'create') {
9928 $value = (
GETPOSTISSET($keyprefix.
'options_'.$key.$keysuffix) || $value) ? $value : explode(
',', $extrafields->attributes[$this->table_element][
'default'][$key]);
9933 $labeltoshow = $langs->trans($label);
9934 $helptoshow = $langs->trans($extrafields->attributes[$this->table_element][
'help'][$key]);
9935 if ($display_type ==
'card') {
9936 $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.
' >';
9937 if (
getDolGlobalString(
'MAIN_VIEW_LINE_NUMBER') && ($action ==
'view' || $action ==
'valid' || $action ==
'editline' || $action ==
'confirm_valid' || $action ==
'confirm_cancel')) {
9938 $out .=
'<td></td>';
9940 $out .=
'<td class="'.(empty($params[
'tdclass']) ?
'titlefieldmax45' : $params[
'tdclass']).
' wordbreak';
9941 if ($extrafields->attributes[$this->table_element][
'type'][$key] ==
'text') {
9944 } elseif ($display_type ==
'line') {
9945 $out .=
'<div '.($html_id ?
'id="'.$html_id.
'" ' :
'').$csstyle.
' class="fieldline_options_'.$key.
' '.$class.$this->element.
'_extras_'.$key.
' trextrafields_collapse'.$collapse_group.
'" '.$domData.
' >';
9946 $out .=
'<div style="display: inline-block; padding-right:4px" class="wordbreak';
9951 $tpl_context = isset($params[
"tpl_context"]) ? $params[
"tpl_context"] :
"none";
9952 if ($tpl_context !=
"public") {
9953 if ($mode !=
'view' && !empty($extrafields->attributes[$this->table_element][
'required'][$key])) {
9954 $out .=
' fieldrequired';
9958 if ($tpl_context ==
"public") {
9959 if (!empty($extrafields->attributes[$this->table_element][
'help'][$key])) {
9960 $out .= $form->textwithpicto($labeltoshow, $helptoshow);
9962 $out .= $labeltoshow;
9964 if ($mode !=
'view' && !empty($extrafields->attributes[$this->table_element][
'required'][$key])) {
9965 $out .=
' <span style="color: red">*</span>';
9968 if (!empty($extrafields->attributes[$this->table_element][
'help'][$key])) {
9969 $out .= $form->textwithpicto($labeltoshow, $helptoshow);
9971 $out .= $labeltoshow;
9975 $out .= ($display_type ==
'card' ?
'</td>' :
'</div>');
9978 $html_id = !empty($this->
id) ? $this->element.
'_extras_'.$key.
'_'.$this->id :
'';
9979 if ($display_type ==
'card') {
9981 $out .=
'<td '.($html_id ?
'id="'.$html_id.
'" ' :
'').
' class="valuefieldcreate '.$this->element.
'_extras_'.$key;
9982 $out .=
'" '.($colspan ?
' colspan="'.$colspan.
'"' :
'');
9984 } elseif ($display_type ==
'line') {
9985 $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].
'">';
9990 $out .= $extrafields->showOutputField($key, $value,
'', $this->table_element);
9993 $listoftypestoshowpicto = explode(
',',
getDolGlobalString(
'MAIN_TYPES_TO_SHOW_PICTO',
'email,ip,password'));
9994 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], $listoftypestoshowpicto)) {
9995 $out .=
getPictoForType($extrafields->attributes[$this->table_element][
'type'][$key], ($extrafields->attributes[$this->table_element][
'type'][$key] ==
'text' ?
'tdtop' :
''));
9998 $out .= $extrafields->showInputField($key, $value,
'', $keysuffix,
'',
'', $this, $this->table_element);
10001 $listoftypestoshowpicto = explode(
',',
getDolGlobalString(
'MAIN_TYPES_TO_SHOW_PICTO',
'email,phone,ip,password'));
10002 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], $listoftypestoshowpicto)) {
10003 $out .=
getPictoForType($extrafields->attributes[$this->table_element][
'type'][$key], ($extrafields->attributes[$this->table_element][
'type'][$key] ==
'text' ?
'tdtop' :
''));
10005 $out .= $extrafields->showInputField($key, $value,
'', $keysuffix,
'',
'', $this, $this->table_element);
10009 $out .= ($display_type ==
'card' ?
'</td>' :
'</div>');
10010 $out .= ($display_type ==
'card' ?
'</tr>'.
"\n" :
'</div>');
10016 if (!empty(
$conf->use_javascript_ajax)) {
10017 $out .= $this->getJSListDependancies();
10020 $out .=
'<!-- commonobject:showOptionals end --> '.
"\n";
10022 if (empty($nbofextrafieldsshown)) {
10028 $out .= $hookResPrint;
10040 <script nonce="'.getNonce().
'">
10041 jQuery(document).ready(function() {
10042 function showOptions'.$type.
'(child_list, parent_list, orig_select)
10044 var val = $("select[name=\""+parent_list+"\"]").val();
10045 var parentVal = parent_list + ":" + val;
10046 if(typeof val == "string"){
10048 var options = orig_select.find("option[parent=\""+parentVal+"\"]").clone();
10049 $("select[name=\""+child_list+"\"] option[parent]").remove();
10050 $("select[name=\""+child_list+"\"]").append(options);
10052 var options = orig_select.find("option[parent]").clone();
10053 $("select[name=\""+child_list+"\"] option[parent]").remove();
10054 $("select[name=\""+child_list+"\"]").append(options);
10056 } else if(val > 0) {
10057 var options = orig_select.find("option[parent=\""+parentVal+"\"]").clone();
10058 $("select[name=\""+child_list+"\"] option[parent]").remove();
10059 $("select[name=\""+child_list+"\"]").append(options);
10061 var options = orig_select.find("option[parent]").clone();
10062 $("select[name=\""+child_list+"\"] option[parent]").remove();
10063 $("select[name=\""+child_list+"\"]").append(options);
10066 function setListDependencies'.$type.
'() {
10067 jQuery("select option[parent]").parent().each(function() {
10068 var orig_select = {};
10069 var child_list = $(this).attr("name");
10070 orig_select[child_list] = $(this).clone();
10071 var parent = $(this).find("option[parent]:first").attr("parent");
10072 var infos = parent.split(":");
10073 var parent_list = infos[0];
10075 //Hide daughters lists
10076 if ($("#"+child_list).val() == 0 && $("#"+parent_list).val() == 0){
10077 $("#"+child_list).hide();
10078 //Show mother lists
10079 } else if ($("#"+parent_list).val() != 0){
10080 $("#"+parent_list).show();
10082 //Show the child list if the parent list value is selected
10083 $("select[name=\""+parent_list+"\"]").click(function() {
10084 if ($(this).val() != 0){
10085 $("#"+child_list).show()
10089 //When we change parent list
10090 $("select[name=\""+parent_list+"\"]").change(function() {
10091 showOptions'.$type.
'(child_list, parent_list, orig_select[child_list]);
10092 //Select the value 0 on child list after a change on the parent list
10093 $("#"+child_list).val(0).trigger("change");
10094 //Hide child lists if the parent value is set to 0
10095 if ($(this).val() == 0){
10096 $("#"+child_list).hide();
10102 setListDependencies'.$type.
'();
10118 $element = $this->element;
10120 if ($element ==
'facturerec') {
10121 $element =
'facture';
10122 } elseif ($element ==
'invoice_supplier_rec') {
10123 return !$user->hasRight(
'fournisseur',
'facture') ? null : $user->hasRight(
'fournisseur',
'facture');
10126 return $user->hasRight(
$module, $element);
10129 return isset($user->rights->$element) ? $user->rights->$element :
null;
10146 global $hookmanager;
10148 $parameters = array(
10149 'origin_id' => $origin_id,
10150 'dest_id' => $dest_id,
10151 'tables' => $tables,
10153 $reshook = $hookmanager->executeHooks(
'commonReplaceThirdparty', $parameters);
10156 } elseif ($reshook < 0) {
10157 return $ignoreerrors === 1;
10160 foreach ($tables as $table) {
10161 $sql =
'UPDATE '.$dbs->prefix().$table.
' SET fk_soc = '.((int) $dest_id).
' WHERE fk_soc = '.((int) $origin_id);
10163 if (!$dbs->
query($sql)) {
10164 if ($ignoreerrors) {
10189 foreach ($tables as $table) {
10190 $sql =
'UPDATE '.MAIN_DB_PREFIX.$table.
' SET fk_product = '.((int) $dest_id).
' WHERE fk_product = '.((int) $origin_id);
10192 if (!$dbs->
query($sql)) {
10193 if ($ignoreerrors) {
10220 global $hookmanager;
10224 if (!preg_match(
'/^[a-z0-9_]+$/', $fieldname)) {
10225 dol_syslog(__METHOD__.
' Refused an invalid column name: '.$fieldname, LOG_ERR);
10229 $parameters = array(
10230 'origin_id' => $origin_id,
10231 'dest_id' => $dest_id,
10232 'tables' => $tables,
10233 'fieldname' => $fieldname,
10235 $reshook = $hookmanager->executeHooks(
'commonReplaceContact', $parameters);
10236 if ($reshook > 0) {
10238 } elseif ($reshook < 0) {
10239 return $ignoreerrors === 1;
10242 foreach ($tables as $table) {
10243 if (!preg_match(
'/^[a-z0-9_]+$/', $table)) {
10244 dol_syslog(__METHOD__.
' Refused an invalid table name: '.$table, LOG_ERR);
10248 $sanitizedtable = $dbs->
sanitize($table);
10249 $sanitizedfieldname = $dbs->
sanitize($fieldname);
10251 $sql =
"UPDATE ".$dbs->prefix().$sanitizedtable;
10252 $sql .=
" SET ".$sanitizedfieldname.
" = ".((int) $dest_id);
10253 $sql .=
" WHERE ".$sanitizedfieldname.
" = ".((int) $origin_id);
10255 if (!$dbs->
query($sql)) {
10256 if ($ignoreerrors) {
10279 public function defineBuyPrice($unitPrice = 0.0, $discountPercent = 0.0, $fk_product = 0, $qty = 0)
10285 if (($unitPrice > 0) && (isset(
$conf->global->ForceBuyingPriceIfNull) &&
getDolGlobalInt(
'ForceBuyingPriceIfNull') > 0)) {
10287 $buyPrice = $unitPrice * (1 - $discountPercent / 100);
10290 if (!empty($fk_product) && $fk_product > 0) {
10293 require_once DOL_DOCUMENT_ROOT.
'/product/class/product.class.php';
10294 $product =
new Product($this->db);
10295 $result = $product->fetch($fk_product);
10296 if ($result <= 0) {
10297 $this->errors[] =
'ErrorProductIdDoesNotExists';
10300 if ($product->cost_price > 0) {
10301 $buyPrice = $product->cost_price;
10302 } elseif ($product->pmp > 0) {
10303 $buyPrice = $product->pmp;
10306 require_once DOL_DOCUMENT_ROOT.
'/product/class/product.class.php';
10307 $product =
new Product($this->db);
10308 $result = $product->fetch($fk_product);
10309 if ($result <= 0) {
10310 $this->errors[] =
'ErrorProductIdDoesNotExists';
10313 if ($product->pmp > 0) {
10314 $buyPrice = $product->pmp;
10318 if (empty($buyPrice) && in_array(
getDolGlobalString(
'MARGIN_TYPE'), array(
'1',
'pmp',
'costprice'))) {
10319 require_once DOL_DOCUMENT_ROOT.
'/fourn/class/fournisseur.product.class.php';
10321 $result = $productFournisseur->find_min_price_product_fournisseur($fk_product, $qty);
10322 if ($result == 0 && $qty > 0) {
10324 $result = $productFournisseur->find_min_price_product_fournisseur($fk_product);
10327 $buyPrice = $productFournisseur->fourn_unitprice;
10328 } elseif ($result < 0) {
10329 $this->errors[] = $productFournisseur->error;
10336 return (
float) $buyPrice;
10349 return array(
'dir' =>
'',
'file' =>
'',
'originalfile' =>
'',
'altfile' =>
'',
'email' =>
'',
'capture' =>
'');
10373 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')
10376 global $user, $langs;
10378 include_once DOL_DOCUMENT_ROOT.
'/core/lib/files.lib.php';
10379 include_once DOL_DOCUMENT_ROOT.
'/core/lib/images.lib.php';
10380 include_once DOL_DOCUMENT_ROOT.
'/core/class/link.class.php';
10382 $sortfield =
'position_name';
10383 $sortorder =
'asc';
10388 $dir .=
get_exdir(0, 0, 0, 0, $this, $modulepart);
10389 $pdir .=
get_exdir(0, 0, 0, 0, $this, $modulepart);
10392 if ($modulepart ==
'product') {
10394 $dir = $sdir.
'/'.
get_exdir($this->
id, 2, 0, 0, $this, $modulepart).$this->id.
"/photos/";
10395 $pdir =
'/'.get_exdir($this->
id, 2, 0, 0, $this, $modulepart).$this->id.
"/photos/";
10398 if ($modulepart ==
'category') {
10399 $dir = $sdir.
'/'.
get_exdir($this->
id, 2, 0, 0, $this, $modulepart).$this->id.
"/photos/";
10400 $pdir =
'/'.get_exdir($this->
id, 2, 0, 0, $this, $modulepart).$this->id.
"/photos/";
10406 $relativedir = preg_replace(
'/^'.preg_quote(DOL_DATA_ROOT,
'/').
'/',
'', $dir);
10407 $relativedir = preg_replace(
'/^[\\/]/',
'', $relativedir);
10408 $relativedir = preg_replace(
'/[\\/]$/',
'', $relativedir);
10411 $dirthumb = $dir.
'thumbs/';
10412 $pdirthumb = $pdir.
'thumbs/';
10414 $return =
'<!-- Photo -->'.
"\n";
10417 $filearray =
dol_dir_list($dir,
"files", 0,
'',
'(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) ==
'desc' ? SORT_DESC : SORT_ASC), 1);
10426 '@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';
10428 $useLinkPathPhoto =
false;
10431 $link =
new Link($this->db);
10433 $link->fetchAll($links,
'product', $this->
id);
10435 if (count($links) > 0) {
10436 $useLinkPathPhoto =
true;
10439 if ($useLinkPathPhoto) {
10441 if ($nbbyrow > 0) {
10442 $return .=
'<table class="valigntop center centpercent" style="border:0; padding:2px; border-spacing:2px; border-collapse: separate;">';
10446 foreach ($links as $link) {
10447 if (!empty($link->url) && preg_match(
'/\.(jpg|jpeg|png|gif|webp)$/i', $link->url)) {
10452 if ($nbbyrow > 0 && ($i % $nbbyrow == 1)) {
10453 $return .=
'<tr class="center valignmiddle">';
10456 if ($nbbyrow > 0) {
10457 $return .=
'<td style="width:'.ceil(100 / $nbbyrow).
'%" class="photo">';
10459 $return .=
'<div class="inline-block">';
10462 $return .=
'<img class="photo photowithmargin'.($addphotorefcss ?
' '.$addphotorefcss :
'').
'"'.($maxHeight ?
' height="'.$maxHeight.
'"' :
'').
' src="'.$url.
'" title="External image">';
10464 if ($nbbyrow > 0) {
10465 $return .=
'</td>';
10466 if ($i % $nbbyrow == 0) {
10467 $return .=
'</tr>';
10470 $return .=
'</div>';
10473 if ($nbmax && $nbphoto >= $nbmax) {
10479 if ($nbbyrow > 0) {
10480 while ($i % $nbbyrow) {
10481 $return .=
'<td style="width:'.ceil(100 / $nbbyrow).
'%"> </td>';
10485 $return .=
'</table>';
10491 if (count($filearray)) {
10492 if ($sortfield && $sortorder) {
10493 $filearray =
dol_sort_array($filearray, $sortfield, $sortorder);
10496 foreach ($filearray as $key => $val) {
10498 $file = $val[
'name'];
10504 $viewfilename = $file;
10506 if ($size == 1 || $size ==
'small') {
10512 $pdirthumb = $pdir;
10513 $photo_vignette = basename($file);
10519 if ($nbbyrow > 0) {
10520 if ($nbphoto == 1) {
10521 $return .=
'<table class="valigntop center centpercent" style="border: 0; padding: 2px; border-spacing: 2px; border-collapse: separate;">';
10524 if ($nbphoto % $nbbyrow == 1) {
10525 $return .=
'<tr class="center valignmiddle" style="border: 1px">';
10527 $return .=
'<td style="width: '.ceil(100 / $nbbyrow).
'%" class="photo">'.
"\n";
10528 } elseif ($nbbyrow < 0) {
10529 $return .=
'<div class="inline-block">'.
"\n";
10532 $relativefile = preg_replace(
'/^\//',
'', $pdir.$photo);
10533 if (empty($nolink)) {
10535 if ($urladvanced) {
10536 $return .=
'<a href="'.$urladvanced.
'">';
10538 $return .=
'<a href="'.DOL_URL_ROOT.
'/viewimage.php?modulepart='.$modulepart.
'&entity='.$this->entity.
'&file='.urlencode($pdir.$photo).
'" class="aphoto" target="_blank" rel="noopener noreferrer">';
10544 $alt = $langs->transnoentitiesnoconv(
'File').
': '.$relativefile;
10545 $alt .=
' - '.$langs->transnoentitiesnoconv(
'Size').
': '.$imgarray[
'width'].
'x'.$imgarray[
'height'];
10546 if ($overwritetitle) {
10547 if (is_numeric($overwritetitle)) {
10550 $alt = $overwritetitle;
10553 if (empty($cache) && !empty($val[
'label'])) {
10556 $cache = $val[
'label'];
10558 if ($usesharelink) {
10559 if (array_key_exists(
'share', $val) && $val[
'share']) {
10560 if (empty($maxHeight) || ($photo_vignette && $imgarray[
'height'] > $maxHeight)) {
10561 $return .=
'<!-- Show original file (thumb not yet available with shared links) -->';
10562 $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).
'">';
10564 $return .=
'<!-- Show original file -->';
10565 $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).
'">';
10568 $return .=
'<!-- Show nophoto file (because file is not shared) -->';
10569 $return .=
'<img class="photo photowithmargin'.($addphotorefcss ?
' '.$addphotorefcss :
'').
'" height="'.$maxHeight.
'" src="'.DOL_URL_ROOT.
'/public/theme/common/nophoto.png" title="'.
dol_escape_htmltag($alt).
'">';
10572 if (empty($maxHeight) || ($photo_vignette && $imgarray[
'height'] > $maxHeight)) {
10573 $return .=
'<!-- Show thumb -->';
10574 $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).
'">';
10576 $return .=
'<!-- Show original file -->';
10577 $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).
'">';
10581 if (empty($nolink)) {
10585 if ($showfilename) {
10586 $return .=
'<br>'.$viewfilename;
10591 if ($photo_vignette && (
image_format_supported($photo) > 0) && ((isset($imgarray[
'width']) && $imgarray[
'width'] > $maxWidth) || (isset($imgarray[
'width']) && $imgarray[
'width'] > $maxHeight))) {
10592 $return .=
'<a href="'.$_SERVER[
"PHP_SELF"].
'?id='.$this->
id.
'&action=addthumb&token='.
newToken().
'&file='.urlencode($pdir.$viewfilename).
'">'.img_picto($langs->trans(
'GenerateThumb'),
'refresh').
' </a>';
10595 if ($modulepart ==
'product' && ($user->hasRight(
'produit',
'creer') || $user->hasRight(
'service',
'creer'))) {
10597 $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> ';
10600 $return .=
'<a href="'.$_SERVER[
"PHP_SELF"].
'?id='.$this->
id.
'&action=delete&token='.
newToken().
'&file='.urlencode($pdir.$viewfilename).
'">';
10601 $return .= img_delete().
'</a>';
10606 if ($nbbyrow > 0) {
10607 $return .=
'</td>';
10608 if (($nbphoto % $nbbyrow) == 0) {
10609 $return .=
'</tr>';
10611 } elseif ($nbbyrow < 0) {
10612 $return .=
'</div>'.
"\n";
10616 if (empty($size)) {
10617 $return .=
'<img class="photo photowithmargin" src="'.DOL_URL_ROOT.
'/viewimage.php?modulepart='.$modulepart.
'&entity='.$this->entity.
'&file='.urlencode($pdir.$photo).
'">';
10619 if ($showfilename) {
10620 $return .=
'<br>'.$viewfilename;
10624 if ($modulepart ==
'product' && ($user->hasRight(
'produit',
'creer') || $user->hasRight(
'service',
'creer'))) {
10626 $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> ';
10629 $return .=
'<a href="'.$_SERVER[
"PHP_SELF"].
'?id='.$this->
id.
'&action=delete&token='.
newToken().
'&file='.urlencode($pdir.$viewfilename).
'">';
10630 $return .= img_delete().
'</a>';
10636 if ($nbmax && $nbphoto >= $nbmax) {
10642 if ($size == 1 || $size ==
'small') {
10643 if ($nbbyrow > 0) {
10645 while ($nbphoto % $nbbyrow) {
10646 $return .=
'<td style="width: '.ceil(100 / $nbbyrow).
'%"> </td>';
10651 $return .=
'</table>';
10657 $this->nbphoto = $nbphoto;
10671 if (is_array($info)) {
10672 if (isset($info[
'type']) && $info[
'type'] ==
'array') {
10689 if (isset($info[
'type']) && ($info[
'type'] ==
'date' || $info[
'type'] ==
'datetime' || $info[
'type'] ==
'timestamp')) {
10703 if (is_array($info)) {
10704 if (isset($info[
'type']) && ($info[
'type'] ==
'duration')) {
10722 if (is_array($info)) {
10723 if (isset($info[
'type']) && (preg_match(
'/^(?:tiny|small|medium|big)?int|int$/i', $info[
'type']))) {
10741 if (is_array($info)) {
10742 if (isset($info[
'type']) && (preg_match(
'/^(double|real|price)/i', $info[
'type']))) {
10759 if (is_array($info)) {
10760 if (isset($info[
'type']) && $info[
'type'] ==
'text') {
10777 if (is_array($info)) {
10778 if (array_key_exists(
'notnull', $info) && $info[
'notnull'] !=
'1') {
10795 if (is_array($info)) {
10796 if (array_key_exists(
'notnull', $info) && $info[
'notnull'] ==
'-1') {
10813 if (is_array($info)) {
10814 if (array_key_exists(
'index', $info) && $info[
'index'] ==
true) {
10837 $queryarray = array();
10838 foreach ($this->fields as $field => $info) {
10840 if ($this->isDate($info)) {
10841 if (empty($this->{$field})) {
10842 $queryarray[$field] =
null;
10844 $queryarray[$field] = $this->db->idate($this->{$field});
10846 } elseif ($this->isDuration($info)) {
10848 if ((isset($this->{$field}) && $this->{$field} !=
'') || !empty($info[
'notnull'])) {
10849 if (!isset($this->{$field})) {
10850 if (!empty($info[
'default'])) {
10851 $queryarray[$field] = $info[
'default'];
10853 $queryarray[$field] = 0;
10856 $queryarray[$field] = (int) $this->{$field};
10859 $queryarray[$field] =
null;
10861 } elseif ($this->isInt($info) || $this->isFloat($info)) {
10862 if ($field ==
'entity' && is_null($this->{$field})) {
10863 $queryarray[$field] = ((int)
$conf->entity);
10866 if ((isset($this->{$field}) && ((
string) $this->{$field}) !=
'') || !empty($info[
'notnull'])) {
10867 if (!isset($this->{$field})) {
10868 $queryarray[$field] = 0;
10869 } elseif ($this->isInt($info)) {
10870 $queryarray[$field] = (int) $this->{$field};
10871 } elseif ($this->isFloat($info)) {
10872 $queryarray[$field] = (float) $this->{$field};
10875 $queryarray[$field] =
null;
10881 $queryarray[$field] = $this->{$field};
10884 if (is_array($info) && array_key_exists(
'type', $info) && !empty($info[
'type']) && $info[
'type'] ==
'timestamp' && empty($queryarray[$field])) {
10885 unset($queryarray[$field]);
10887 if (!empty($info[
'notnull']) && $info[
'notnull'] == -1 && empty($queryarray[$field])) {
10888 $queryarray[$field] =
null;
10892 return $queryarray;
10905 foreach ($this->fields as $field => $info) {
10906 if ($this->isDate($info)) {
10907 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') {
10908 $this->$field =
'';
10910 $this->$field = $db->jdate($obj->$field);
10912 } elseif ($this->isInt($info)) {
10913 if ($field ==
'rowid') {
10914 $this->
id = (int) $obj->$field;
10916 if ($this->isForcedToNullIfZero($info)) {
10917 if (empty($obj->$field)) {
10918 $this->$field =
null;
10920 $this->$field = (int) $obj->$field;
10923 if (isset($obj->$field) && (!is_null($obj->$field) || (array_key_exists(
'notnull', $info) && $info[
'notnull'] == 1))) {
10924 $this->$field = (int) $obj->$field;
10926 $this->$field =
null;
10930 } elseif ($this->isFloat($info)) {
10931 if ($this->isForcedToNullIfZero($info)) {
10932 if (empty($obj->$field)) {
10933 $this->$field =
null;
10935 $this->$field = (float) $obj->$field;
10938 if (isset($obj->$field) && (!is_null($obj->$field) || (array_key_exists(
'notnull', $info) && $info[
'notnull'] == 1))) {
10939 $this->$field = (float) $obj->$field;
10941 $this->$field =
null;
10945 $this->$field = isset($obj->$field) ? $obj->$field :
null;
10950 if (!isset($this->fields[
'ref']) && isset($this->
id)) {
10951 $this->
ref = (string) $this->
id;
10961 foreach ($this->fields as $field => $arr) {
10962 $this->$field =
null;
10975 $keys = array_keys($this->fields);
10976 if (!empty($alias)) {
10977 $keys_with_alias = array();
10978 foreach ($keys as $fieldname) {
10979 if (!empty($excludefields)) {
10980 if (in_array($fieldname, $excludefields)) {
10984 $keys_with_alias[] = $this->db->sanitize($alias .
'.' . $fieldname);
10986 return implode(
', ', $keys_with_alias);
10988 return implode(
', ', $keys);
10999 protected function quote($value, $fieldsentry)
11001 if (is_null($value)) {
11003 } elseif (preg_match(
'/^(int|double|real|price)/i', $fieldsentry[
'type'])) {
11005 } elseif (preg_match(
'/int$/i', $fieldsentry[
'type'])) {
11006 return (
int) $value;
11007 } elseif ($fieldsentry[
'type'] ==
'boolean') {
11014 return "'".$this->db->escape($value).
"'";
11031 dol_syslog(get_class($this).
"::createCommon create", LOG_DEBUG);
11037 $fieldvalues = $this->setSaveQuery();
11041 if (array_key_exists(
'date_creation', $fieldvalues) && empty($fieldvalues[
'date_creation'])) {
11042 $fieldvalues[
'date_creation'] = $this->db->idate($now);
11043 $this->date_creation = $this->db->idate($now);
11046 if (array_key_exists(
'fk_user_creat', $fieldvalues) && !($fieldvalues[
'fk_user_creat'] > 0)) {
11047 $fieldvalues[
'fk_user_creat'] = $user->id;
11048 $this->fk_user_creat = $user->id;
11050 if (array_key_exists(
'user_creation_id', $fieldvalues) && !($fieldvalues[
'user_creation_id'] > 0)) {
11051 $fieldvalues[
'user_creation_id'] = $user->id;
11052 $this->user_creation_id = $user->id;
11054 if (array_key_exists(
'pass_crypted', $fieldvalues) && property_exists($this,
'pass')) {
11056 $tmparray =
dol_hash($this->pass,
'0', 0, 1);
11057 $fieldvalues[
'pass_crypted'] = $tmparray[
'pass_encrypted'];
11058 if (array_key_exists(
'pass_encoding', $fieldvalues) && property_exists($this,
'pass_encoding')) {
11059 $fieldvalues[
'pass_encoding'] = $tmparray[
'pass_encoding'];
11062 if (array_key_exists(
'ref', $fieldvalues)) {
11065 if (
getDolGlobalString(
'MAIN_DISABLE_AUTO_UPDATE_OF_TMS_FIELDS') && array_key_exists(
'tms', $fieldvalues)) {
11066 $fieldvalues[
'tms'] = $this->db->idate($now);
11069 unset($fieldvalues[
'rowid']);
11071 $sanitized_keys = array();
11072 $sanitized_values = array();
11073 foreach ($fieldvalues as $k => $v) {
11074 $sanitized_keys[$k] = $k;
11075 $value = $this->fields[$k];
11077 $sanitized_values[$k] = $this->quote($v, $value);
11081 foreach ($sanitized_keys as $key) {
11082 if (!isset($this->fields[$key])) {
11085 $key_fields = $this->fields[$key];
11088 if (preg_match(
'/^integer:/i', $key_fields[
'type']) && $sanitized_values[$key] ==
'-1') {
11089 $sanitized_values[$key] =
'';
11091 if (!empty($key_fields[
'foreignkey']) && $sanitized_values[$key] ==
'-1') {
11092 $sanitized_values[$key] =
'';
11095 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']))) {
11098 if (empty($langs)) {
11099 require_once DOL_DOCUMENT_ROOT.
'/core/class/translate.class.php';
11101 $langs->setDefaultLang();
11102 $langs->load(
"errors");
11104 dol_syslog(
"Mandatory field '".$key.
"' is empty and required into ->fields definition of class");
11105 $this->errors[] = $langs->trans(
"ErrorFieldRequired", isset($key_fields[
'label']) ? $key_fields[
'label'] : $key);
11109 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'])) {
11110 $sanitized_values[$key] = $this->quote($key_fields[
'default'], $key_fields);
11114 if (isset($key_fields[
'type']) && preg_match(
'/^integer:/i', $key_fields[
'type']) && empty($sanitized_values[$key])) {
11115 if (isset($key_fields[
'default'])) {
11116 $sanitized_values[$key] = ((int) $key_fields[
'default']);
11118 $sanitized_values[$key] =
'null';
11121 if (!empty($key_fields[
'foreignkey']) && empty($sanitized_values[$key])) {
11122 $sanitized_values[$key] =
'null';
11130 $this->db->begin();
11133 $sql =
"INSERT INTO ".$this->db->prefix().$this->db->sanitize($this->table_element);
11134 $sql .=
" (".implode(
", ", $sanitized_keys).
')';
11135 $sql .=
" VALUES (".implode(
", ", $sanitized_values).
")";
11137 $res = $this->db->query($sql);
11140 if ($this->db->lasterrno() ==
'DB_ERROR_RECORD_ALREADY_EXISTS') {
11141 $this->errors[] =
"ErrorRefAlreadyExists";
11143 $this->errors[] = $this->db->lasterror();
11149 $this->
id = $this->db->last_insert_id($this->db->prefix().$this->table_element);
11155 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)') {
11156 $sql =
"UPDATE ".$this->db->prefix().$this->db->sanitize($this->table_element);
11157 $sql .=
" SET ref = '(PROV".((int) $this->
id).
")' WHERE (ref = '(PROV)' OR ref = '') AND rowid = ".((int) $this->
id);
11158 $resqlupdate = $this->db->query($sql);
11160 if ($resqlupdate ===
false) {
11162 $this->errors[] = $this->db->lasterror();
11164 $this->
ref =
'(PROV'.$this->id.
')';
11171 $result = $this->insertExtraFields();
11178 if (!empty($this->table_element_line) && !empty($this->fk_element) && !empty($this->lines)) {
11179 foreach ($this->lines as $line) {
11180 $keyforparent = $this->fk_element;
11185 if (!is_object($line)) {
11186 $line = (object) $line;
11190 if (method_exists($line,
'insert')) {
11191 $result = $line->insert($user, 1);
11192 } elseif (method_exists($line,
'create')) {
11193 $result = $line->create($user, 1);
11196 $this->error = $line->error;
11197 $this->db->rollback();
11204 if (!$error && !$notrigger) {
11206 $triggerPrefix = (empty($this->TRIGGER_PREFIX) ? strtoupper(get_class($this)) : $this->TRIGGER_PREFIX);
11207 $result = $this->call_trigger($triggerPrefix.
'_CREATE', $user);
11216 $this->db->rollback();
11219 $this->db->commit();
11236 if (empty(
$id) && empty($ref) && empty($morewhere)) {
11240 $fieldlist = $this->getFieldList(
't');
11241 if (empty($fieldlist)) {
11245 $sql =
"SELECT ".$this->db->sanitize($fieldlist, 0, 0, 1);
11246 $sql .=
" FROM ".$this->db->prefix().$this->table_element.
' as t';
11249 $sql .=
' WHERE t.rowid = '.((int)
$id);
11250 } elseif (!empty($ref)) {
11251 $sql .=
" WHERE t.ref = '".$this->db->escape($ref).
"'";
11253 $sql .=
' WHERE 1 = 1';
11255 if (empty(
$id) && isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
11256 $sql .=
' AND t.entity IN ('.getEntity($this->element).
')';
11259 $sql .= $morewhere;
11261 $sql .=
' LIMIT 1';
11263 $res = $this->db->query($sql);
11265 $obj = $this->db->fetch_object($res);
11267 $this->setVarsFromFetchObj($obj);
11271 if (empty($noextrafields)) {
11272 $result = $this->fetch_optionals();
11274 $this->error = $this->db->lasterror();
11275 $this->errors[] = $this->error;
11285 $this->error = $this->db->lasterror();
11286 $this->errors[] = $this->error;
11300 $objectlineclassname = get_class($this).
'Line';
11301 if (!class_exists($objectlineclassname)) {
11302 $this->error =
'Error, class '.$objectlineclassname.
' not found during call of fetchLinesCommon';
11306 $objectline =
new $objectlineclassname($this->db);
11307 '@phan-var-force CommonObjectLine $objectline';
11309 $sql =
"SELECT ".$objectline->getFieldList(
'l');
11310 $sql .=
" FROM ".$this->db->prefix().$this->db->sanitize($objectline->table_element).
" as l";
11311 $sql .=
" WHERE l.fk_".$this->db->sanitize($this->element).
" = ".((int) $this->
id);
11313 $sql .= $morewhere;
11315 if (isset($objectline->fields[
'position'])) {
11316 $sql .= $this->db->order(
'position',
'ASC');
11319 $resql = $this->db->query($sql);
11321 $num_rows = $this->db->num_rows($resql);
11323 $this->lines = array();
11324 while ($i < $num_rows) {
11325 $obj = $this->db->fetch_object($resql);
11327 $newline =
new $objectlineclassname($this->db);
11328 '@phan-var-force CommonObjectLine $newline';
11329 $newline->setVarsFromFetchObj($obj);
11332 if (empty($noextrafields)) {
11333 $newline->fetch_optionals();
11336 $this->lines[] = $newline;
11343 $this->error = $this->db->lasterror();
11344 $this->errors[] = $this->error;
11358 dol_syslog(get_class($this).
"::updateCommon update", LOG_DEBUG);
11370 $fieldvalues = $this->setSaveQuery();
11374 if (array_key_exists(
'date_modification', $fieldvalues)) {
11375 $fieldvalues[
'date_modification'] = $this->db->idate($now);
11377 if (
getDolGlobalString(
'MAIN_DISABLE_AUTO_UPDATE_OF_TMS_FIELDS') && array_key_exists(
'tms', $fieldvalues)) {
11378 $fieldvalues[
'tms'] = $this->db->idate($now);
11380 if (array_key_exists(
'fk_user_modif', $fieldvalues)) {
11381 $fieldvalues[
'fk_user_modif'] = $user->id;
11383 if (array_key_exists(
'user_modification_id', $fieldvalues)) {
11384 $fieldvalues[
'user_modification_id'] = $user->id;
11387 if (array_key_exists(
'pass_crypted', $fieldvalues) && property_exists($this,
'pass') && !empty($this->pass)) {
11389 $tmparray =
dol_hash($this->pass,
'0', 0, 1);
11390 $fieldvalues[
'pass_crypted'] = $tmparray[
'pass_encrypted'];
11391 if (array_key_exists(
'pass_encoding', $fieldvalues) && property_exists($this,
'pass_encoding')) {
11392 $fieldvalues[
'pass_encoding'] = $tmparray[
'pass_encoding'];
11395 if (array_key_exists(
'ref', $fieldvalues)) {
11399 unset($fieldvalues[
'rowid']);
11404 $sanitized_tmp = array();
11405 foreach ($fieldvalues as $k => $v) {
11407 $value = $this->fields[$k];
11409 $values[$k] = $this->quote($v, $value);
11410 if ((!empty($value[
"type"]) && $value[
"type"] ==
"text") && !empty($value[
'arrayofkeyval']) && is_array($value[
'arrayofkeyval'])) {
11412 $v = preg_replace(
'/\s/',
',', $v);
11413 $v = preg_replace(
'/,+/',
',', $v);
11416 $sanitized_tmp[] = $this->db->sanitize($k).
'='.$this->quote($v, $this->fields[$k]);
11420 foreach ($keys as $key) {
11421 if (!empty($this->fields[$key][
'type']) && preg_match(
'/^integer:/i', $this->fields[$key][
'type']) && $values[$key] ==
'-1') {
11422 $values[$key] =
'';
11424 if (!empty($this->fields[$key][
'foreignkey']) && $values[$key] ==
'-1') {
11425 $values[$key] =
'';
11437 $sql =
"UPDATE ".$this->db->prefix().$this->db->sanitize($this->table_element);
11438 $sql .=
" SET ".implode(
', ', $sanitized_tmp);
11439 $sql .=
" WHERE rowid = ".((int) $this->
id);
11441 $this->db->begin();
11444 $res = $this->db->query($sql);
11447 $this->errors[] = $this->db->lasterror();
11453 $result = $this->insertExtraFields();
11460 if (!$error && !$notrigger) {
11462 $triggerPrefix = (empty($this->TRIGGER_PREFIX) ? strtoupper(get_class($this)) : $this->TRIGGER_PREFIX);
11463 $result = $this->call_trigger($triggerPrefix.
'_MODIFY', $user);
11472 $this->db->rollback();
11475 $this->db->commit();
11490 dol_syslog(get_class($this).
"::deleteCommon delete", LOG_DEBUG);
11494 $this->db->begin();
11496 if ($forcechilddeletion) {
11497 foreach ($this->childtables as $table) {
11498 $sql =
"DELETE FROM ".$this->db->prefix().$this->db->sanitize($table);
11499 $sql .=
" WHERE ".$this->db->sanitize($this->fk_element).
" = ".((int) $this->
id);
11500 $resql = $this->db->query($sql);
11502 $this->error = $this->db->lasterror();
11503 $this->errors[] = $this->error;
11504 $this->db->rollback();
11508 } elseif (!empty($this->childtables)) {
11509 $objectisused = $this->isObjectUsed($this->
id);
11510 if (!empty($objectisused)) {
11511 dol_syslog(get_class($this).
"::deleteCommon Can't delete record as it has some child", LOG_WARNING);
11512 $this->error =
'ErrorRecordHasChildren';
11513 $this->errors[] = $this->error;
11514 $this->db->rollback();
11520 if (is_array($this->childtablesoncascade) && !empty($this->childtablesoncascade)) {
11521 foreach ($this->childtablesoncascade as $tabletodelete) {
11522 $deleteFromObject = explode(
':', $tabletodelete, 4);
11523 if (count($deleteFromObject) >= 2) {
11524 $className = str_replace(
'@',
'', $deleteFromObject[0]);
11525 $filePath = $deleteFromObject[1];
11526 $columnName = $deleteFromObject[2];
11528 if (!empty($deleteFromObject[3])) {
11529 $filter = $deleteFromObject[3];
11533 $childObject =
new $className($this->db);
11534 if (method_exists($childObject,
'deleteByParentField')) {
11535 '@phan-var-force CommonObject $childObject';
11536 $result = $childObject->deleteByParentField($this->
id, $columnName, $filter);
11539 $this->errors[] = $childObject->error;
11544 $this->errors[] =
"You defined a cascade delete on an object $className/$this->id but there is no method deleteByParentField for it";
11549 $this->errors[] =
'Cannot include child class file '.$filePath;
11554 $sql =
"DELETE FROM ".$this->db->prefix().$this->db->sanitize($tabletodelete).
" WHERE ".$this->db->sanitize($this->fk_element).
" = ".((int) $this->
id);
11556 $resql = $this->db->query($sql);
11559 $this->error = $this->db->lasterror();
11560 $this->errors[] = $this->error;
11570 $triggerPrefix = (empty($this->TRIGGER_PREFIX) ? strtoupper(get_class($this)) : $this->TRIGGER_PREFIX);
11571 $result = $this->call_trigger($triggerPrefix.
'_DELETE', $user);
11581 $res = $this->deleteEcmFiles(1);
11590 require_once DOL_DOCUMENT_ROOT .
'/core/lib/files.lib.php';
11593 $this->errors[] =
'ErrorFailToDeleteDir';
11599 $res = $this->deleteObjectLinked();
11604 if (!$error && !empty($this->isextrafieldmanaged)) {
11605 $result = $this->deleteExtraFields();
11612 $sql =
"DELETE FROM ".$this->db->prefix().$this->db->sanitize($this->table_element);
11613 $sql .=
" WHERE rowid = ".((int) $this->
id);
11615 $resql = $this->db->query($sql);
11618 $this->errors[] = $this->db->lasterror();
11624 $this->db->rollback();
11627 $this->db->commit();
11652 if (!empty($parentId) && !empty($parentField)) {
11653 if (empty($this->table_element)) {
11654 $this->error =
'Property table_element for object is not defined';
11655 $this->errors[] = $this->error;
11659 if (!method_exists($this,
'fetch')) {
11660 $this->error =
'Method fetch for object is not defined';
11661 $this->errors[] = $this->error;
11665 if (!method_exists($this,
'delete')) {
11666 $this->error =
'Method delete for object is not defined';
11667 $this->errors[] = $this->error;
11672 $this->db->begin();
11674 $sql =
"SELECT rowid FROM ".$this->db->prefix().$this->db->sanitize($this->table_element);
11675 $sql .=
" WHERE ".$this->db->sanitize($parentField).
" = ".(int) $parentId;
11678 $errormessage =
'';
11680 if ($errormessage) {
11681 $this->errors[] = $errormessage;
11682 dol_syslog(__METHOD__.
' '.implode(
',', $this->errors), LOG_ERR);
11686 $resql = $this->db->query($sql);
11688 $this->errors[] = $this->db->lasterror();
11691 while ($obj = $this->db->fetch_object($resql)) {
11692 $result = $this->fetch($obj->rowid);
11695 $this->errors[] = $this->error;
11697 $result = $this->
delete($user);
11700 $this->errors[] = $this->error;
11708 if (empty($error)) {
11709 $this->db->commit();
11712 $this->error = implode(
', ', $this->errors);
11713 $this->db->rollback();
11714 return $error * -1;
11730 if (!($this->
id > 0) || empty($this->table_element_line) || empty($this->fk_element)) {
11734 $sql =
"SELECT rowid FROM ".$this->db->prefix().$this->db->sanitize($this->table_element_line);
11735 $sql .=
" WHERE rowid = ".((int) $lineid).
" AND ".$this->db->sanitize($this->fk_element).
" = ".((int) $this->
id);
11736 $resql = $this->db->query($sql);
11738 return ($resql && $this->db->num_rows($resql) > 0);
11753 $tmpforobjectclass = get_class($this);
11754 $tmpforobjectlineclass = ucfirst($tmpforobjectclass).
'Line';
11756 if ($this->
id > 0 && !empty($this->fk_element)) {
11758 $sql =
"SELECT rowid FROM ".$this->db->prefix().$this->table_element_line;
11759 $sql .=
" WHERE rowid = ".((int) $idline).
" AND ".$this->db->sanitize($this->fk_element).
" = ".((int) $this->
id);
11760 $resql = $this->db->query($sql);
11761 if (!$resql || !$this->db->num_rows($resql)) {
11762 $this->error =
'ErrorLineIDDoesNotMatchWithObjectID';
11767 $this->db->begin();
11770 $result = $this->call_trigger(
'LINE'.strtoupper($tmpforobjectclass).
'_DELETE', $user);
11776 if (empty($error)) {
11777 $sql =
"DELETE FROM ".$this->db->prefix().$this->db->sanitize($this->table_element_line);
11778 $sql .=
" WHERE rowid = ".((int) $idline);
11780 $resql = $this->db->query($sql);
11782 $this->error =
"Error ".$this->db->lasterror();
11787 if (empty($error)) {
11789 $tmpobjectline =
new $tmpforobjectlineclass($this->db);
11790 '@phan-var-force CommonObjectLine $tmpobjectline';
11791 if (!isset($tmpobjectline->isextrafieldmanaged) || !empty($tmpobjectline->isextrafieldmanaged)) {
11792 $tmpobjectline->id = $idline;
11793 $result = $tmpobjectline->deleteExtraFields();
11796 $this->error =
"Error ".get_class($this).
"::deleteLineCommon deleteExtraFields error -4 ".$tmpobjectline->error;
11801 if (empty($error)) {
11802 $this->db->commit();
11805 dol_syslog(get_class($this).
"::deleteLineCommon ERROR:".$this->error, LOG_ERR);
11806 $this->db->rollback();
11826 $this->db->begin();
11828 $statusfield =
'status';
11829 if (in_array($this->element, array(
'don',
'donation',
'shipping',
'project_task'))) {
11830 $statusfield =
'fk_statut';
11833 $sql =
"UPDATE ".$this->db->prefix().$this->db->sanitize($this->table_element);
11834 $sql .=
" SET ".$this->db->sanitize($statusfield).
" = ".((int) $status);
11835 $sql .=
" WHERE rowid = ".((int) $this->
id);
11837 if ($this->db->query($sql)) {
11839 $this->oldcopy = clone $this;
11842 if (!$error && !$notrigger) {
11844 $result = $this->call_trigger($triggercode, $user);
11851 $this->
status = $status;
11852 if (property_exists($this,
'statut')) {
11853 $this->statut = $status;
11855 $this->db->commit();
11858 $this->db->rollback();
11862 $this->error = $this->db->error();
11863 $this->db->rollback();
11879 $this->specimen = 1;
11881 'label' =>
'This is label',
11882 'ref' =>
'ABCD1234',
11883 'description' =>
'This is a description',
11885 'note_public' =>
'Public note',
11886 'note_private' =>
'Private note',
11887 'date_creation' => (
dol_now() - 3600 * 48),
11888 'date_modification' => (
dol_now() - 3600 * 24),
11889 'fk_user_creat' => $user->id,
11890 'fk_user_modif' => $user->id,
11893 foreach ($fields as $key => $value) {
11894 if (array_key_exists($key, $this->fields)) {
11895 $this->{$key} = $value;
11900 if (property_exists($this,
'fields')) {
11901 foreach ($this->fields as $key => $value) {
11903 if (array_key_exists($key, $fields)) {
11907 if (!empty($value[
'default'])) {
11908 $this->$key = $value[
'default'];
11926 require_once DOL_DOCUMENT_ROOT.
'/core/class/comment.class.php';
11928 $comment =
new Comment($this->db);
11929 $result = $comment->fetchAllFor($this->element, $this->
id);
11931 $this->setErrorsFromObject($comment);
11934 $this->comments = $comment->comments;
11936 return count($this->comments);
11946 return count($this->comments);
11957 if (!is_array($parameters)) {
11960 foreach ($parameters as $parameter) {
11961 if (isset($this->$parameter)) {
11962 $this->$parameter = trim($this->$parameter);
11981 require_once DOL_DOCUMENT_ROOT.
'/categories/class/categorie.class.php';
11985 $existing =
$c->containing($this->
id, $type_categ,
'id');
12005 if (!is_array($categories)) {
12006 $categories = array($categories);
12009 dol_syslog(get_class($this).
"::setCategoriesCommon Object Id:".$this->
id.
' type_categ:'.$type_categ.
' nb tag add:'.count($categories), LOG_DEBUG);
12011 require_once DOL_DOCUMENT_ROOT.
'/categories/class/categorie.class.php';
12013 if (empty($type_categ)) {
12014 dol_syslog(__METHOD__.
': Type '.$type_categ.
'is an unknown category type. Done nothing.', LOG_ERR);
12020 $existing =
$c->containing($this->
id, $type_categ,
'id');
12023 if (!is_array($existing)) {
12024 $existing = array();
12026 if ($remove_existing) {
12028 $to_del = array_diff($existing, $categories);
12029 $to_add = array_diff($categories, $existing);
12032 $to_add = array_diff($categories, $existing);
12039 foreach ($to_del as $del) {
12040 if (
$c->fetch($del) > 0) {
12041 $result =
$c->del_type($this, $type_categ);
12044 $this->error =
$c->error;
12045 $this->errors =
$c->errors;
12052 foreach ($to_add as $add) {
12053 if (
$c->fetch($add) > 0) {
12054 $result =
$c->add_type($this, $type_categ);
12057 $this->error =
$c->error;
12058 $this->errors =
$c->errors;
12066 return $error ? (-1 * $error) : $ok;
12079 $this->db->begin();
12081 if (empty($type)) {
12082 $type = $this->table_element;
12085 require_once DOL_DOCUMENT_ROOT.
'/categories/class/categorie.class.php';
12086 $categorystatic =
new Categorie($this->db);
12088 $tablename = $this->db->prefix().
"categorie_".(empty($categorystatic->MAP_CAT_TABLE[$type]) ? $type : $categorystatic->MAP_CAT_TABLE[$type]);
12089 $fkname =
'fk_' . (empty($categorystatic->MAP_CAT_FK[$type]) ? $type : $categorystatic->MAP_CAT_FK[$type]);
12091 $sql =
"INSERT INTO ".$this->db->sanitize($tablename).
" (fk_categorie, ".$this->db->sanitize($fkname).
")";
12092 $sql .=
" SELECT fk_categorie, ".((int) $toId).
" FROM ".$this->db->sanitize($tablename);
12093 $sql .=
" WHERE ".$this->db->sanitize($fkname).
" = ".((int) $fromId);
12095 if (!$this->db->query($sql)) {
12096 $this->error = $this->db->lasterror();
12097 $this->db->rollback();
12101 $this->db->commit();
12115 $this->db->begin();
12119 switch ($this->element) {
12121 $element =
'propale';
12124 $element =
'produit';
12126 case 'order_supplier':
12127 $element =
'fournisseur/commande';
12129 case 'invoice_supplier':
12132 $element =
'fournisseur/facture/'.get_exdir($this->
id, 2, 0, 1, $this,
'invoice_supplier');
12135 $element =
'expedition/sending';
12138 case 'project_task':
12139 require_once DOL_DOCUMENT_ROOT.
'/projet/class/task.class.php';
12141 $project_result = $this->fetchProject();
12142 if ($project_result >= 0) {
12143 $element =
'projet/'.dol_sanitizeFileName($this->project->ref).
'/';
12147 $element =
'contract';
12150 $element = $this->element;
12152 '@phan-var-force string $element';
12155 $sql =
"DELETE FROM ".$this->db->prefix().
"ecm_files_extrafields WHERE fk_object IN (";
12156 $sql .=
" SELECT rowid FROM ".$this->db->prefix().
"ecm_files WHERE filename LIKE '".$this->db->escape($this->
ref).
"%'";
12157 $sql .=
" AND filepath = '".$this->db->escape($element.
"/".$this->ref).
"' AND entity = ".((int)
$conf->entity);
12160 if (!$this->db->query($sql)) {
12161 $this->error = $this->db->lasterror();
12162 $this->db->rollback();
12167 $sql =
"DELETE FROM ".$this->db->prefix().
"ecm_files";
12168 $sql .=
" WHERE filename LIKE '".$this->db->escape($this->
ref).
"%'";
12169 $sql .=
" AND filepath = '".$this->db->escape($element.
"/".$this->ref).
"' AND entity = ".((int)
$conf->entity);
12171 if (!$this->db->query($sql)) {
12172 $this->error = $this->db->lasterror();
12173 $this->db->rollback();
12180 $sql =
'DELETE FROM '.$this->db->prefix().
"ecm_files_extrafields";
12181 $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).
")";
12182 $resql = $this->db->query($sql);
12184 $this->error = $this->db->lasterror();
12185 $this->db->rollback();
12189 $sql =
'DELETE FROM '.$this->db->prefix().
"ecm_files";
12190 $sql .=
" WHERE src_object_type = '".$this->db->escape($this->table_element.(empty($this->module) ?
"" :
"@".$this->module)).
"' AND src_object_id = ".((int) $this->
id);
12191 $resql = $this->db->query($sql);
12193 $this->error = $this->db->lasterror();
12194 $this->db->rollback();
12199 $this->db->commit();
12216 include_once DOL_DOCUMENT_ROOT.
'/product/class/product.class.php';
12219 $tmpproduct =
new Product($this->db);
12220 foreach ($this->lines as $line) {
12221 if ($line->fk_product > 0) {
12222 $tmpproduct->fetch($line->fk_product);
12223 $statustotest = ($status ==
'onsale' ?
'status' :
'status_buy');
12224 if (!$tmpproduct->$statustotest) {
12225 $langs->load(
'products');
12226 $statuskey4lang = ($status ==
'onsale' ?
'ProductStatusNotOnSell' :
'ProductStatusNotOnBuy');
12228 $this->errors[] = $langs->trans(
'ProductRef').
' '.$tmpproduct->ref.
' '.$langs->trans($statuskey4lang);
12234 $this->error =
'ErrorOneLineContainsADisactivatedProduct';
12250 $this->error = $message;
12251 $this->errors[] = $message;
12263 global $dolibarr_main_document_root;
12265 $this->setErrorWithoutLog($message);
12266 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
12267 $file = str_replace($dolibarr_main_document_root,
'', $trace[0][
'file'] ??
'file unknown');
12268 $line = $trace[0][
'line'] ??
'line unknown';
12269 $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
$propal type
'integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter[:Sortfield]]]',...
ajax_combobox($htmlname, $events=array(), $minLengthToAutocomplete=0, $forcefocus=0, $widthTypeOfAutocomplete='resolve', $idforemptyvalue='-1', $morecss='', $placeholder='')
Convert a html select field into an ajax combobox.
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.
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.
roundQtyToPackaging($qty, $packaging)
Round a quantity up to the next multiple of a packaging quantity (options PRODUCT_USE_CUSTOMER_PACKAG...
commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams=null)
Common function for all objects extending CommonObject for generating documents.
liste_contact($statusoflink=-1, $source='external', $list=0, $code='', $status=-1, $arrayoftcids=array())
Get array of all contacts for an object.
fetchObjectFrom($table, $field, $key, $element=null)
Load object from specific field.
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)
isLineOfObject($lineid)
Check that a line belongs to this object, using $this->table_element_line and $this->fk_element.
getSpecialCode($lineid)
Get special code of a line.
clearObjectLinkedCache()
Clear the cache saying that all linked object were already loaded.
update_ref_ext($ref_ext)
Update external ref of element.
fetchOneLike($ref)
Looks for an object with ref matching the wildcard provided It does only work when $this->table_ref_f...
hasProductsOrServices($predefined=-1)
Function to say how many lines object contains.
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.
defineBuyPrice($unitPrice=0.0, $discountPercent=0.0, $fk_product=0, $qty=0)
Get buy price to use for margin calculation.
isText($info)
Function test if type is text.
isDate($info)
Function test if type is date.
printOriginLine($line, $var, $restrictlist='', $defaulttpldir='/core/tpl', $selectedLines=array())
Return HTML with a line of table array of source object lines TODO Move this and previous function in...
showOptionals($extrafields, $mode='view', $params=null, $keysuffix='', $keyprefix='', $onetrtd='', $display_type='card')
Function to show lines of extrafields with output data.
getCanvas($id=0, $ref='')
Load type of canvas of an object if it exists.
line_up($rowid, $fk_parent_line=true)
Update a line to have a lower rank.
isDuration($info)
Function test if type is duration.
setErrorWithLog($message, $loglevel=LOG_ERR)
Set the error message for the object and logs it, including the file name and line number.
canBeNull($info)
Function test if field can be null.
listeTypeContacts($source='internal', $option=0, $activeonly=0, $code='', $element='', $excludeelement='')
Return array with list of possible values for type of contacts.
getRights()
Returns the rights used for this class.
static commonReplaceContact(DoliDB $dbs, $origin_id, $dest_id, array $tables, $fieldname='fk_socpeople', $ignoreerrors=0)
Function used to replace a contact id with another one.
addThumbs($file, $quality=50)
Build thumb.
add_contact($fk_socpeople, $type_contact, $source='external', $notrigger=0)
Add a link between element $this->element and a contact.
cloneCategories($fromId, $toId, $type='')
Copy related categories to another object.
fetch_barcode()
Load data for barcode into properties ->barcode_type* Properties ->barcode_type that is id of barcode...
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...
if(! $sortfield) if(! $sortorder) $module
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.
GETPOSTISSET($paramname)
Return true if we are in a context of submitting the parameter $paramname from a POST of a form.
dol_htmlentitiesbr($stringtoencode, $nl2brmode=0, $pagecodefrom='UTF-8', $removelasteolbr=1)
This function is called to encode a string into a HTML string but differs from htmlentities because a...
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
isModEnabled($module)
Is Dolibarr module enabled.
getDictionaryValue($tablename, $field, $id, $checkentity=false, $rowidfield='rowid')
Return the value of a filed into a dictionary for the record $id.
get_exdir($num, $level, $alpha, $withoutslash, $object, $modulepart='')
Return a path to have a the directory according to object where files are stored.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
getEntity($element, $shared=1, $currentobject=null)
Get list of entity id to use.
getPictoForType($key, $morecss='')
Return the picto for a data type.
getAdvancedPreviewUrl($modulepart, $relativepath, $alldata=0, $param='')
Return URL we can use for advanced preview links.
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $noescapetags='', $escapeonlyhtmltags=0, $cleanalsojavascript=0)
vignette($file, $maxWidth=160, $maxHeight=120, $extName='_small', $quality=50, $outdir='thumbs', $targetformat=0)
Create a thumbnail from an image file (Supported extensions are gif, jpg, png and bmp).
if(!defined( 'IMAGETYPE_WEBP')) getDefaultImageSizes()
Return default values for image sizes.
dol_getImageSize($file, $url=false)
Return size of image file on disk (Supported extensions are gif, jpg, png, bmp and webp)
image_format_supported($file, $acceptsvg=0)
Return if a filename is file name of a supported image format.
query($query, $usesavepoint=0, $type='auto', $result_mode=0)
Execute a SQL request and return the resultset.
calcul_price_total($qty, $pu, $remise_percent_ligne, $txtva, $uselocaltax1_rate, $uselocaltax2_rate, $notused, $price_base_type, $info_bits, $type, $seller=null, $localtaxes_array=[], $progress=100, $multicurrency_tx=1, $pu_devise=0, $multicurrency_code='')
Calculate totals (net, vat, ...) of a line.
$conf db user
Active Directory does not allow anonymous connections.
getRandomPassword($generic=false, $replaceambiguouschars=null, $length=32)
Return a generated password using default module.
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.