46require_once DOL_DOCUMENT_ROOT.
'/core/class/doldeprecationhandler.class.php';
47require_once DOL_DOCUMENT_ROOT.
'/core/class/commontrigger.class.php';
56 use DolDeprecationHandler;
93 public $errors = array();
104 public $warnings = array();
109 private $validateFieldsErrors = array();
127 public $element_for_permission;
132 public $table_element;
142 public $table_element_line =
'';
148 public $ismultientitymanaged;
158 public $array_options = array();
239 public $fields = array();
246 public $array_languages =
null;
251 public $contacts_ids;
256 public $contacts_ids_internal;
261 public $linked_objects;
266 public $linkedObjectsIds;
271 public $linkedObjects;
276 private $linkedObjectsFullLoaded = array();
291 protected $table_ref_field =
'';
296 public $restrictiononfksoc = 0;
305 public $context = array();
416 private $commandeFournisseur;
432 public $ref_previous;
478 public $country_code;
521 public $barcode_type;
527 public $barcode_type_code;
533 public $barcode_type_label;
539 public $barcode_type_coder;
545 public $mode_reglement_id;
551 public $cond_reglement_id;
556 public $demand_reason_id;
562 public $transport_mode_id;
571 private $cond_reglement;
575 protected $depr_cond_reglement;
582 public $fk_delivery_address;
588 public $shipping_method_id;
594 public $shipping_method;
600 public $fk_multicurrency;
606 public $multicurrency_code;
612 public $multicurrency_tx;
617 public $multicurrency_total_ht;
622 public $multicurrency_total_tva;
627 public $multicurrency_total_localtax1;
632 public $multicurrency_total_localtax2;
637 public $multicurrency_total_ttc;
650 public $last_main_doc;
675 public $note_private;
700 public $total_localtax1;
706 public $total_localtax2;
723 public $actiontypecode;
729 public $comments = array();
755 public $civility_code;
761 public $date_creation;
766 public $date_validation;
771 public $date_modification;
785 private $date_update;
790 public $date_cloture;
795 public $user_creation_id;
800 public $user_validation_id;
805 public $user_closing_id;
810 public $user_modification_id;
816 public $fk_user_creat;
822 public $fk_user_modif;
828 public $next_prev_filter;
833 public $specimen = 0;
857 public $totalpaid_multicurrency;
863 public $labelStatus = array();
868 public $labelStatusShort = array();
879 public $showphoto_on_popup;
884 public $nb = array();
899 public $extraparams = array();
904 protected $childtables = array();
911 protected $childtablesoncascade = array();
916 public $cond_reglement_supplier_id;
923 public $deposit_percent;
929 public $warehouse_id;
934 public $isextrafieldmanaged = 0;
944 public $attachedfiles;
958 'alreadypaid' =>
'totalpaid',
959 'cond_reglement' =>
'depr_cond_reglement',
961 'commandeFournisseur' =>
'origin_object',
962 'expedition' =>
'origin_object',
963 'fk_project' =>
'fk_project',
964 'livraison' =>
'origin_object',
965 'projet' =>
'project',
966 'statut' =>
'status',
985 $sql =
"SELECT rowid";
986 $sql .=
" FROM ".$db->prefix().$element;
987 $sql .=
" WHERE entity IN (".getEntity($element).
")";
990 $sql .=
" AND rowid = ".((int) $id);
992 $sql .=
" AND ref = '".$db->escape($ref).
"'";
993 } elseif ($ref_ext) {
994 $sql .=
" AND ref_ext = '".$db->escape($ref_ext).
"'";
996 $error =
'ErrorWrongParameters';
997 dol_syslog(get_class().
"::isExistingObject ".$error, LOG_ERR);
1000 if ($ref || $ref_ext) {
1001 $sql .=
" AND entity = ".((int)
$conf->entity);
1004 dol_syslog(get_class().
"::isExistingObject", LOG_DEBUG);
1005 $resql =
$db->query($sql);
1007 $num =
$db->num_rows($resql);
1025 return (empty($this->
id));
1037 $this->error =
$object->error;
1039 if (!empty(
$object->errors)) {
1040 $this->errors = array_merge($this->errors,
$object->errors);
1065 global $action, $extrafields, $langs, $hookmanager;
1068 $MAX_EXTRAFIELDS_TO_SHOW_IN_TOOLTIP =
getDolGlobalInt(
'MAX_EXTRAFIELDS_TO_SHOW_IN_TOOLTIP', 3);
1074 if (!empty($extrafields->attributes[$this->table_element][
'label'])) {
1075 $data[
'opendivextra'] =
'<div class="centpercent wordbreak divtooltipextra">';
1076 foreach ($extrafields->attributes[$this->table_element][
'label'] as $key => $val) {
1077 if ($extrafields->attributes[$this->table_element][
'type'][$key] ==
'separate') {
1081 if (empty($extrafields->attributes[$this->table_element][
'showintooltip'][$key])) {
1086 if ($count >= abs($MAX_EXTRAFIELDS_TO_SHOW_IN_TOOLTIP)) {
1087 $data[
'more_extrafields'] =
'<br>...';
1091 if ($enabled && isset($extrafields->attributes[$this->table_element][
'enabled'][$key])) {
1092 $enabled = (int)
dol_eval((
string) $extrafields->attributes[$this->table_element][
'enabled'][$key], 1, 1,
'2');
1094 if ($enabled && isset($extrafields->attributes[$this->table_element][
'list'][$key])) {
1095 $enabled = (int)
dol_eval((
string) $extrafields->attributes[$this->table_element][
'list'][$key], 1, 1,
'2');
1098 if ($perms && isset($extrafields->attributes[$this->table_element][
'perms'][$key])) {
1099 $perms = (int)
dol_eval((
string) $extrafields->attributes[$this->table_element][
'perms'][$key], 1, 1,
'2');
1101 if (empty($enabled)) {
1104 if (abs($enabled) != 1 && abs($enabled) != 3 && abs($enabled) != 5 && abs($enabled) != 4) {
1107 if (empty($perms)) {
1110 if (!empty($extrafields->attributes[$this->table_element][
'langfile'][$key])) {
1111 $langs->load($extrafields->attributes[$this->table_element][
'langfile'][$key]);
1113 $labelextra = $langs->trans((
string) $extrafields->attributes[$this->table_element][
'label'][$key]);
1114 if ($extrafields->attributes[$this->table_element][
'type'][$key] ==
'separate') {
1115 $data[$key] =
'<br><b><u>'. $labelextra .
'</u></b>';
1117 $value = (empty($this->array_options[
'options_' . $key]) ?
'' : $this->array_options[
'options_' . $key]);
1118 $data[$key] =
'<br><b>'. $labelextra .
':</b> ' . $extrafields->showOutputField($key, $value,
'', $this->table_element);
1122 $data[
'closedivextra'] =
'</div>';
1125 $hookmanager->initHooks(array($this->element .
'dao'));
1126 $parameters = array(
1127 'tooltipcontentarray' => &$data,
1128 'params' => $params,
1131 $hookmanager->executeHooks(
'getTooltipContent', $parameters, $this, $action);
1134 $label = implode($data);
1147 return $this->error.(is_array($this->errors) ? (($this->error !=
'' ?
', ' :
'').implode(
', ', $this->errors)) :
'');
1159 global $hookmanager;
1161 $parameters = array(
'objref' => $objref);
1163 $reshook = $hookmanager->executeHooks(
'getFormatedCustomerRef', $parameters, $this, $action);
1165 return $hookmanager->resArray[
'objref'];
1167 return $objref.(isset($hookmanager->resArray[
'objref']) ? $hookmanager->resArray[
'objref'] :
'');
1178 global $hookmanager;
1180 $parameters = array(
'objref' => $objref);
1182 $reshook = $hookmanager->executeHooks(
'getFormatedSupplierRef', $parameters, $this, $action);
1184 return $hookmanager->resArray[
'objref'];
1186 return $objref.(isset($hookmanager->resArray[
'objref']) ? $hookmanager->resArray[
'objref'] :
'');
1198 public function getFullAddress($withcountry = 0, $sep =
"\n", $withregion = 0, $extralangcode =
'')
1200 if ($withcountry && $this->country_id && (empty($this->country_code) || empty($this->country))) {
1201 require_once DOL_DOCUMENT_ROOT.
'/core/lib/company.lib.php';
1202 $tmparray =
getCountry($this->country_id,
'all');
1203 $this->country_code = $tmparray[
'code'];
1204 $this->country = $tmparray[
'label'];
1207 if ($withregion && $this->state_id && (empty($this->state_code) || empty($this->state) || empty($this->region) || empty($this->region_code))) {
1208 require_once DOL_DOCUMENT_ROOT.
'/core/lib/company.lib.php';
1209 $tmparray =
getState($this->state_id,
'all',
null, 1);
1210 $this->state_code = $tmparray[
'code'];
1211 $this->state = $tmparray[
'label'];
1212 $this->region_code = $tmparray[
'region_code'];
1213 $this->region = $tmparray[
'region'];
1232 if (empty($this->last_main_doc)) {
1236 include_once DOL_DOCUMENT_ROOT.
'/ecm/class/ecmfiles.class.php';
1237 $ecmfile =
new EcmFiles($this->db);
1238 $result = $ecmfile->fetch(0,
'', $this->last_main_doc);
1240 $this->error = $ecmfile->error;
1241 $this->errors = $ecmfile->errors;
1245 if (empty($ecmfile->id)) {
1247 if ($initsharekey) {
1248 require_once DOL_DOCUMENT_ROOT.
'/core/lib/security2.lib.php';
1270 } elseif (empty($ecmfile->share)) {
1272 if ($initsharekey) {
1273 require_once DOL_DOCUMENT_ROOT.
'/core/lib/security2.lib.php';
1275 $ecmfile->update($user);
1281 $urlwithouturlroot = preg_replace(
'/'.preg_quote(DOL_URL_ROOT,
'/').
'$/i',
'', trim(
$dolibarr_main_url_root));
1285 $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT;
1294 if (!empty($ecmfile->share)) {
1295 $paramlink .= ($paramlink ?
'&' :
'').
'hashp='.$ecmfile->share;
1297 if ($forcedownload) {
1298 $paramlink .= ($paramlink ?
'&' :
'').
'attachment=1';
1301 if ($relativelink) {
1302 $linktoreturn =
'document.php'.($paramlink ?
'?'.$paramlink :
'');
1304 $linktoreturn = $urlwithroot.
'/document.php'.($paramlink ?
'?'.$paramlink :
'');
1308 return $linktoreturn;
1322 public function add_contact($fk_socpeople, $type_contact, $source =
'external', $notrigger = 0)
1325 global $user, $langs;
1327 dol_syslog(get_class($this).
"::add_contact $fk_socpeople, $type_contact, $source, $notrigger");
1330 if ($fk_socpeople <= 0) {
1331 $langs->load(
"errors");
1332 $this->error = $langs->trans(
"ErrorWrongValueForParameterX",
"1");
1333 dol_syslog(get_class($this).
"::add_contact ".$this->error, LOG_ERR);
1338 $sql_check =
"SELECT rowid FROM ".$this->db->prefix().($source ==
'internal' ?
"user" :
"socpeople").
" WHERE rowid = ".((
int) $fk_socpeople);
1339 $resql_check = $this->db->query($sql_check);
1341 if (!$this->db->num_rows($resql_check)) {
1342 $langs->load(
"errors");
1343 $this->error = $langs->trans(
"ErrorRecordNotFound");
1344 dol_syslog(get_class($this).
"::add_contact Contact/user id ".$fk_socpeople.
" does not exist", LOG_ERR);
1348 $this->error = $this->db->lasterror();
1352 if (!$type_contact) {
1353 $langs->load(
"errors");
1354 $this->error = $langs->trans(
"ErrorWrongValueForParameterX",
"2");
1355 dol_syslog(get_class($this).
"::add_contact ".$this->error, LOG_ERR);
1359 if ($this->restrictiononfksoc && property_exists($this,
'socid') && !empty($this->socid) && $user->id > 0 && !$user->hasRight(
'societe',
'client',
'voir')) {
1360 $sql_allowed_contacts =
'SELECT COUNT(*) as cnt FROM '.$this->db->prefix().
'societe_commerciaux as sc';
1361 $sql_allowed_contacts .=
' WHERE sc.fk_soc = '.(int) $this->socid;
1362 $sql_allowed_contacts .=
' AND sc.fk_user = '.(int) $user->id;
1364 $resql_allowed_contacts = $this->db->query($sql_allowed_contacts);
1366 if (!$resql_allowed_contacts) {
1367 $this->errors[] = $this->db->lasterror();
1369 } elseif ($obj = $this->db->fetch_object($resql_allowed_contacts)) {
1370 if ($obj->cnt == 0) {
1371 $langs->load(
"companies");
1372 $this->error = $langs->trans(
"ErrorCommercialNotAllowedForThirdparty", $user->id);
1373 dol_syslog(get_class($this).
"::add_contact ".$this->error, LOG_ERR);
1379 $id_type_contact = 0;
1380 if (is_numeric($type_contact)) {
1381 $id_type_contact = $type_contact;
1384 $sql =
"SELECT tc.rowid";
1385 $sql .=
" FROM ".$this->db->prefix().
"c_type_contact as tc";
1386 $sql .=
" WHERE tc.element='".$this->db->escape($this->element).
"'";
1387 $sql .=
" AND tc.source='".$this->db->escape($source).
"'";
1388 $sql .=
" AND tc.code='".$this->db->escape($type_contact).
"' AND tc.active=1";
1390 $resql = $this->db->query($sql);
1392 $obj = $this->db->fetch_object($resql);
1394 $id_type_contact = $obj->rowid;
1398 if ($id_type_contact == 0) {
1399 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");
1407 $already_added =
false;
1408 if (is_array($TListeContacts) && !empty($TListeContacts)) {
1409 foreach ($TListeContacts as $array_contact) {
1410 if ($array_contact[
'status'] == 4 && $array_contact[
'id'] == $fk_socpeople && $array_contact[
'fk_c_type_contact'] == $id_type_contact) {
1411 $already_added =
true;
1417 if (!$already_added) {
1421 $sql =
"INSERT INTO ".$this->db->prefix().
"element_contact";
1422 $sql .=
" (element_id, fk_socpeople, datecreate, statut, fk_c_type_contact) ";
1423 $sql .=
" VALUES (".((int) $this->
id).
", ".((int) $fk_socpeople).
" , ";
1424 $sql .=
"'".$this->db->idate($datecreate).
"'";
1425 $sql .=
", 4, ".((int) $id_type_contact);
1428 $resql = $this->db->query($sql);
1431 $triggerPrefix = (empty($this->TRIGGER_PREFIX) ? strtoupper($this->element) : $this->TRIGGER_PREFIX);
1432 $result = $this->call_trigger($triggerPrefix.
'_ADD_CONTACT', $user);
1434 $this->db->rollback();
1439 $this->db->commit();
1442 if ($this->db->errno() ==
'DB_ERROR_RECORD_ALREADY_EXISTS') {
1443 $this->error = $this->db->errno();
1444 $this->db->rollback();
1447 $this->error = $this->db->lasterror();
1448 $this->db->rollback();
1468 $contacts = $objFrom->liste_contact(-1, $source);
1469 foreach ($contacts as $contact) {
1470 if ($this->
add_contact($contact[
'id'], $contact[
'fk_c_type_contact'], $contact[
'source']) < 0) {
1487 public function update_contact($rowid, $statut, $type_contact_id = 0, $fk_socpeople = 0)
1491 $sql =
"UPDATE ".$this->db->prefix().
"element_contact set";
1492 $sql .=
" statut = ".((int) $statut);
1493 if ($type_contact_id) {
1494 $sql .=
", fk_c_type_contact = ".((int) $type_contact_id);
1496 if ($fk_socpeople) {
1497 $sql .=
", fk_socpeople = ".((int) $fk_socpeople);
1499 $sql .=
" where rowid = ".((int) $rowid);
1501 $resql = $this->db->query($sql);
1505 $this->error = $this->db->lasterror();
1526 if ($this->
id > 0) {
1527 $sql =
"SELECT ec.rowid FROM ".$this->db->prefix().
"element_contact as ec, ".$this->db->prefix().
"c_type_contact as tc";
1528 $sql .=
" WHERE ec.rowid = ".((int) $rowid).
" AND ec.element_id = ".((int) $this->
id);
1529 $sql .=
" AND ec.fk_c_type_contact = tc.rowid AND tc.element = '".$this->db->escape($this->element).
"'";
1530 $resql = $this->db->query($sql);
1531 if (!$resql || !$this->db->num_rows($resql)) {
1532 $this->error =
'ErrorRecordNotFound';
1539 if (!$error && empty($notrigger)) {
1541 $this->context[
'contact_id'] = ((int) $rowid);
1542 $triggerPrefix = (empty($this->TRIGGER_PREFIX) ? strtoupper($this->element) : $this->TRIGGER_PREFIX);
1543 $result = $this->call_trigger($triggerPrefix.
'_DELETE_CONTACT', $user);
1551 dol_syslog(get_class($this).
"::delete_contact", LOG_DEBUG);
1553 $sql =
"DELETE FROM ".MAIN_DB_PREFIX.
"element_contact";
1554 $sql .=
" WHERE rowid = ".((int) $rowid);
1556 $result = $this->db->query($sql);
1559 $this->errors[] = $this->db->lasterror();
1564 $this->db->commit();
1567 $this->error = $this->db->lasterror();
1568 $this->db->rollback();
1588 if (!empty($typeContact)) {
1589 foreach ($typeContact as $key => $value) {
1590 array_push($temp, $key);
1592 $listId = implode(
",", $temp);
1597 if (empty($listId)) {
1601 $sql =
"DELETE FROM ".$this->db->prefix().
"element_contact";
1602 $sql .=
" WHERE element_id = ".((int) $this->
id);
1603 $sql .=
" AND fk_c_type_contact IN (".$this->db->sanitize($listId).
")";
1605 dol_syslog(get_class($this).
"::delete_linked_contact", LOG_DEBUG);
1606 if ($this->db->query($sql)) {
1609 $this->error = $this->db->lasterror();
1626 public function liste_contact($statusoflink = -1, $source =
'external', $list = 0, $code =
'', $status = -1, $arrayoftcids = array())
1633 $sql =
"SELECT ec.rowid, ec.statut as statuslink, ec.fk_socpeople as id, ec.fk_c_type_contact";
1634 if ($source ==
'internal') {
1635 $sql .=
", '-1' as socid, t.statut as statuscontact, t.login, t.photo, t.gender, t.fk_country as country_id";
1637 if ($source ==
'external' || $source ==
'thirdparty') {
1638 $sql .=
", t.fk_soc as socid, t.statut as statuscontact, t.fk_pays as country_id";
1640 $sql .=
", t.civility as civility, t.lastname as lastname, t.firstname, t.email, t.address, t.zip, t.town";
1641 if (empty($arrayoftcids)) {
1642 $sql .=
", tc.source, tc.element, tc.code, tc.libelle as type_label, co.label as country";
1645 if (empty($arrayoftcids)) {
1646 $sql .=
" ".$this->db->prefix().
"c_type_contact as tc,";
1648 $sql .=
" ".$this->db->prefix().
"element_contact as ec";
1649 if ($source ==
'internal') {
1650 $sql .=
" LEFT JOIN ".$this->db->prefix().
"user as t on ec.fk_socpeople = t.rowid";
1651 $sql .=
" LEFT JOIN ".$this->db->prefix().
"c_country as co ON co.rowid = t.fk_country";
1653 if ($source ==
'external' || $source ==
'thirdparty') {
1654 $sql .=
" LEFT JOIN ".$this->db->prefix().
"socpeople as t on ec.fk_socpeople = t.rowid";
1655 $sql .=
" LEFT JOIN ".$this->db->prefix().
"c_country as co ON co.rowid = t.fk_pays";
1657 $sql .=
" WHERE ec.element_id = ".((int) $this->
id);
1658 if (empty($arrayoftcids)) {
1659 $sql .=
" AND ec.fk_c_type_contact = tc.rowid";
1660 $sql .=
" AND tc.element = '".$this->db->escape($this->element).
"'";
1662 $sql .=
" AND tc.code = '".$this->db->escape($code).
"'";
1664 if ($source ==
'internal') {
1665 $sql .=
" AND tc.source = 'internal'";
1667 if ($source ==
'external' || $source ==
'thirdparty') {
1668 $sql .=
" AND tc.source = 'external'";
1670 $sql .=
" AND tc.active = 1";
1672 $sql .=
" AND ec.fk_c_type_contact IN (".$this->db->sanitize(implode(
',', $arrayoftcids)).
")";
1675 $sql .=
" AND t.statut = ".((int) $status);
1677 if ($statusoflink >= 0) {
1678 $sql .=
" AND ec.statut = ".((int) $statusoflink);
1680 $sql .=
" ORDER BY t.lastname ASC";
1682 dol_syslog(get_class($this).
"::liste_contact", LOG_DEBUG);
1683 $resql = $this->db->query($sql);
1685 $num = $this->db->num_rows($resql);
1688 $obj = $this->db->fetch_object($resql);
1691 $transkey =
"TypeContact_".$obj->element.
"_".$obj->source.
"_".$obj->code;
1692 $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->type_label);
1694 'parentId' => $this->
id,
1695 'source' => $obj->source,
1696 'socid' => $obj->socid,
1698 'nom' => $obj->lastname,
1699 'civility' => $obj->civility,
1700 'lastname' => $obj->lastname,
1701 'firstname' => $obj->firstname,
1702 'email' => $obj->email,
1703 'address' => $obj->address,
1705 'town' => $obj->town,
1706 'country_id' => $obj->country_id,
1707 'country' => $obj->country,
1708 'login' => (empty($obj->login) ?
'' : $obj->login),
1709 'photo' => (empty($obj->photo) ?
'' : $obj->photo),
1710 'gender' => (empty($obj->gender) ?
'' : $obj->gender),
1711 'statuscontact' => $obj->statuscontact,
1712 'rowid' => $obj->rowid,
1713 'code' => $obj->code,
1714 'libelle' => $libelle_type,
1715 'status' => (
int) $obj->statuslink,
1716 'fk_c_type_contact' => $obj->fk_c_type_contact
1719 $tab[$i] = $obj->id;
1727 $this->error = $this->db->lasterror();
1742 $sql =
"SELECT ec.datecreate, ec.statut, ec.fk_socpeople, ec.fk_c_type_contact,";
1743 $sql .=
" tc.code, tc.libelle as type_label";
1744 $sql .=
" FROM (".$this->db->prefix().
"element_contact as ec, ".$this->db->prefix().
"c_type_contact as tc)";
1745 $sql .=
" WHERE ec.rowid =".((int) $rowid);
1746 $sql .=
" AND ec.fk_c_type_contact = tc.rowid";
1747 $sql .=
" AND tc.element = '".$this->db->escape($this->element).
"'";
1749 dol_syslog(get_class($this).
"::swapContactStatus", LOG_DEBUG);
1750 $resql = $this->db->query($sql);
1752 $obj = $this->db->fetch_object($resql);
1753 $newstatut = ($obj->statut == 4) ? 5 : 4;
1755 $this->db->free($resql);
1758 $this->error = $this->db->error();
1775 public function liste_type_contact($source =
'internal', $order =
'position', $option = 0, $activeonly = 0, $code =
'')
1780 $sanitized_order = $order;
1782 if (empty($sanitized_order)) {
1783 $sanitized_order =
'position';
1785 if ($sanitized_order ==
'position') {
1786 $sanitized_order .=
',code';
1791 $sql =
"SELECT DISTINCT tc.rowid, tc.code, tc.libelle as type_label, tc.position";
1792 $sql .=
" FROM ".$this->db->prefix().
"c_type_contact as tc";
1793 $sql .=
" WHERE tc.element = '".$this->db->escape($this->element).
"'";
1794 if ($activeonly == 1) {
1795 $sql .=
" AND tc.active = 1";
1797 if (!empty($source) && $source !=
'all') {
1798 $sql .=
" AND tc.source = '".$this->db->escape($source).
"'";
1800 if (!empty($code)) {
1801 $sql .=
" AND tc.code = '".$this->db->escape($code).
"'";
1803 $sql .= $this->db->order($sanitized_order,
'ASC');
1806 $resql = $this->db->query($sql);
1808 $this->error = $this->db->lasterror();
1813 $num = $this->db->num_rows($resql);
1816 $obj = $this->db->fetch_object($resql);
1818 $transkey =
"TypeContact_".$this->element.
"_".$source.
"_".$obj->code;
1819 $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $langs->trans($obj->type_label));
1820 if (empty($option)) {
1821 $tab[$obj->rowid] = $libelle_type;
1822 } elseif ($option == 1) {
1823 $tab[$obj->code] = $libelle_type;
1825 $tab[$obj->rowid] = array(
'id' => $obj->rowid,
'code' => $obj->code,
'label' => $libelle_type);
1844 public function listeTypeContacts($source =
'internal', $option = 0, $activeonly = 0, $code =
'', $element =
'', $excludeelement =
'')
1848 $langs->loadLangs(array(
'bills',
'contracts',
'interventions',
'orders',
'projects',
'propal',
'ticket',
'agenda'));
1852 $sql =
"SELECT DISTINCT tc.rowid, tc.code, tc.libelle as type_label, tc.position, tc.element, tc.module";
1853 $sql .=
" FROM ".$this->db->prefix().
"c_type_contact as tc";
1855 $sqlWhere = array();
1856 if (!empty($element)) {
1857 $sqlWhere[] =
" tc.element='".$this->db->escape($element).
"'";
1859 if (!empty($excludeelement)) {
1860 $sqlWhere[] =
" tc.element <> '".$this->db->escape($excludeelement).
"'";
1863 if ($activeonly == 1) {
1864 $sqlWhere[] =
" tc.active=1";
1867 if (!empty($source) && $source !=
'all') {
1868 $sqlWhere[] =
" tc.source='".$this->db->escape($source).
"'";
1871 if (!empty($code)) {
1872 $sqlWhere[] =
" tc.code='".$this->db->escape($code).
"'";
1875 if (count($sqlWhere) > 0) {
1876 $sql .=
" WHERE ".implode(
' AND ', $sqlWhere);
1879 $sql .= $this->db->order(
'tc.element, tc.position',
'ASC');
1882 $resql = $this->db->query($sql);
1884 $num = $this->db->num_rows($resql);
1886 $langs->loadLangs(array(
"propal",
"orders",
"bills",
"suppliers",
"contracts",
"supplier_proposal"));
1888 while ($obj = $this->db->fetch_object($resql)) {
1889 $modulename = $obj->module ?? $obj->element;
1890 if (strpos($obj->element,
'project') !==
false) {
1891 $modulename =
'projet';
1892 } elseif ($obj->element ==
'contrat') {
1893 $element =
'contract';
1894 } elseif ($obj->element ==
'action') {
1895 $modulename =
'agenda';
1896 } elseif (strpos($obj->element,
'supplier') !==
false && $obj->element !=
'supplier_proposal') {
1897 $modulename =
'fournisseur';
1900 $libelle_element = $langs->trans(
'ContactDefault_'.$obj->element);
1901 $tmpelement = $obj->element;
1902 $transkey =
"TypeContact_".$tmpelement.
"_".$source.
"_".$obj->code;
1903 $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->type_label);
1904 $tab[$obj->rowid] = $libelle_element.
' - '.$libelle_type;
1910 $this->error = $this->db->lasterror();
1931 if (!
getDolGlobalInt(
'SHIPPING_USE_ITS_OWN_CONTACTS') && $this->element ==
'shipping' && $this->origin_id != 0) {
1932 $id = $this->origin_id;
1933 $element =
'commande';
1934 } elseif ($this->element ==
'reception' && $this->origin_id != 0) {
1935 $id = $this->origin_id;
1936 $element =
'order_supplier';
1939 $element = $this->element;
1942 $sql =
"SELECT ec.fk_socpeople";
1943 $sql .=
" FROM ".$this->db->prefix().
"element_contact as ec,";
1944 if ($source ==
'internal') {
1945 $sql .=
" ".$this->db->prefix().
"user as c,";
1947 if ($source ==
'external') {
1948 $sql .=
" ".$this->db->prefix().
"socpeople as c,";
1950 $sql .=
" ".$this->db->prefix().
"c_type_contact as tc";
1951 $sql .=
" WHERE ec.element_id = ".((int) $id);
1952 $sql .=
" AND ec.fk_socpeople = c.rowid";
1953 if ($source ==
'internal') {
1954 $sql .=
" AND c.entity IN (".getEntity(
'user').
")";
1956 if ($source ==
'external') {
1957 $sql .=
" AND c.entity IN (".getEntity(
'societe').
")";
1959 $sql .=
" AND ec.fk_c_type_contact = tc.rowid";
1960 $sql .=
" AND tc.element = '".$this->db->escape($element).
"'";
1961 $sql .=
" AND tc.source = '".$this->db->escape($source).
"'";
1963 $sql .=
" AND tc.code = '".$this->db->escape($code).
"'";
1965 $sql .=
" AND tc.active = 1";
1967 $sql .=
" AND ec.statut = ".((int) $status);
1970 dol_syslog(get_class($this).
"::getIdContact", LOG_DEBUG);
1971 $resql = $this->db->query($sql);
1973 while ($obj = $this->db->fetch_object($resql)) {
1974 $result[$i] = $obj->fk_socpeople;
1978 $this->error = $this->db->error();
1995 if (empty($contactid)) {
1996 $contactid = $this->contact_id;
1999 if (empty($contactid)) {
2003 require_once DOL_DOCUMENT_ROOT.
'/contact/class/contact.class.php';
2004 $contact =
new Contact($this->db);
2005 $result = $contact->fetch($contactid);
2006 $this->contact = $contact;
2021 if (empty($this->socid) && empty($this->fk_soc) && empty($force_thirdparty_id)) {
2025 require_once DOL_DOCUMENT_ROOT.
'/societe/class/societe.class.php';
2027 $idtofetch = isset($this->socid) ? $this->socid : (isset($this->fk_soc) ? $this->fk_soc : 0);
2028 if ($force_thirdparty_id) {
2029 $idtofetch = $force_thirdparty_id;
2033 $thirdparty =
new Societe($this->db);
2034 $result = $thirdparty->fetch($idtofetch);
2036 $this->errors = array_merge($this->errors, $thirdparty->errors);
2038 $this->thirdparty = $thirdparty;
2042 $this->thirdparty->price_level = 1;
2061 if (!$this->table_ref_field) {
2065 $sql =
"SELECT rowid FROM ".$this->db->prefix().$this->table_element;
2066 $sql .=
" WHERE ".$this->db->sanitize($this->table_ref_field).
" LIKE '".$this->db->escape($ref).
"'";
2069 $query = $this->db->query($sql);
2071 if (!$this->db->num_rows($query)) {
2075 $result = $this->db->fetch_object($query);
2077 if (method_exists($this,
'fetch')) {
2078 return $this->fetch($result->rowid);
2080 $this->error =
'Fetch method not implemented on '.get_class($this);
2081 dol_syslog(get_class($this).
'::fetchOneLike Error='.$this->error, LOG_ERR);
2082 array_push($this->errors, $this->error);
2111 dol_syslog(get_class($this).
'::fetchBarCode this->element='.$this->element.
' this->barcode_type='.$this->barcode_type);
2113 $idtype = $this->barcode_type;
2114 if (empty($idtype) && $idtype !=
'0') {
2115 if ($this->element ==
'product' &&
getDolGlobalString(
'PRODUIT_DEFAULT_BARCODE_TYPE')) {
2117 } elseif ($this->element ==
'societe') {
2120 dol_syslog(
'Call fetchBarCode with barcode_type not defined and cannot be guessed', LOG_WARNING);
2125 if (empty($this->barcode_type) || empty($this->barcode_type_code) || empty($this->barcode_type_label) || empty($this->barcode_type_coder)) {
2126 $sql =
"SELECT rowid, code, libelle as label, coder";
2127 $sql .=
" FROM ".$this->db->prefix().
"c_barcode_type";
2128 $sql .=
" WHERE rowid = ".((int) $idtype);
2130 $resql = $this->db->query($sql);
2132 $obj = $this->db->fetch_object($resql);
2134 $this->barcode_type = $obj->rowid;
2135 $this->barcode_type_code = $obj->code;
2136 $this->barcode_type_label = $obj->label;
2137 $this->barcode_type_coder = $obj->coder;
2155 include_once DOL_DOCUMENT_ROOT.
'/projet/class/project.class.php';
2157 if (empty($this->fk_project) && !empty($this->fk_projet)) {
2158 $this->fk_project = $this->fk_projet;
2160 if (empty($this->fk_project)) {
2164 $project =
new Project($this->db);
2165 $result = $project->fetch($this->fk_project);
2167 $this->project = $project;
2209 include_once DOL_DOCUMENT_ROOT.
'/product/class/product.class.php';
2212 if (empty($this->fk_product)) {
2216 $product =
new Product($this->db);
2218 $result = $product->fetch($this->fk_product);
2220 $this->product = $product;
2234 $user =
new User($this->db);
2235 $result = $user->fetch($userid);
2236 $this->
user = $user;
2250 $tmpclassname = $this->origin ? $this->origin : $this->origin_type;
2253 if ($tmpclassname ==
'shipping') {
2254 $tmpclassname =
'Expedition';
2256 if ($tmpclassname ==
'delivery') {
2257 $tmpclassname =
'Livraison';
2259 if ($tmpclassname ==
'order_supplier' || $tmpclassname ==
'supplier_order') {
2260 $tmpclassname =
'CommandeFournisseur';
2263 $classname = ucfirst($tmpclassname);
2265 $this->origin_object =
new $classname($this->db);
2267 $this->origin_object->fetch($this->origin_id);
2285 $sql =
"SELECT rowid FROM ".$this->db->prefix().$table;
2286 $sql .=
" WHERE ".$this->db->sanitize($field).
" = '".$this->db->escape($key).
"'";
2287 if (!empty($element)) {
2288 $sql .=
" AND entity IN (".getEntity($element).
")";
2290 $sql .=
" AND entity = ".((int)
$conf->entity);
2293 dol_syslog(get_class($this).
'::fetchObjectFrom', LOG_DEBUG);
2294 $resql = $this->db->query($sql);
2296 $obj = $this->db->fetch_object($resql);
2299 if (method_exists($this,
'fetch')) {
2300 $result = $this->fetch($obj->rowid);
2302 $this->error =
'fetch() method not implemented on '.get_class($this);
2303 dol_syslog(get_class($this).
'::fetchOneLike Error='.$this->error, LOG_ERR);
2304 array_push($this->errors, $this->error);
2324 if (!empty($id) && !empty($field) && !empty($table)) {
2325 if (!preg_match(
'/^[a-zA-Z_][a-zA-Z0-9_]*$/', $table)) {
2326 dol_syslog(get_class($this).
'::getValueFrom Bad table name: '.$table, LOG_WARNING);
2329 if (!preg_match(
'/^[a-zA-Z_][a-zA-Z0-9_.]*$/', $field)) {
2330 dol_syslog(get_class($this).
'::getValueFrom Bad field name: '.$field, LOG_WARNING);
2334 $sql =
"SELECT ".$this->db->sanitize($field).
" FROM ".$this->db->prefix().$this->db->sanitize($table);
2335 $sql .=
" WHERE rowid = ".((int) $id);
2337 dol_syslog(get_class($this).
'::getValueFrom', LOG_DEBUG);
2338 $resql = $this->db->query($sql);
2340 $row = $this->db->fetch_row($resql);
2363 public function setValueFrom($field, $value, $table =
'', $id =
null, $format =
'', $id_field =
'', $fuser =
null, $trigkey =
'', $fk_user_field =
'fk_user_modif')
2367 if (empty($table)) {
2368 $table = $this->table_element;
2373 if (empty($format)) {
2376 if (empty($id_field)) {
2377 $id_field =
'rowid';
2380 $propfield = $field;
2383 if ($table ==
'product') {
2384 if ($field ==
'note_private') {
2386 $propfield =
'note_private';
2387 } elseif ($field ==
'status') {
2389 $propfield =
'status';
2390 } elseif ($field ==
'status_buy') {
2392 $propfield =
'status_buy';
2393 } elseif ($field ==
'status_batch') {
2395 $propfield =
'status_batch';
2399 if (in_array($table, array(
'actioncomm',
'adherent',
'advtargetemailing',
'cronjob',
'establishment'))) {
2400 $fk_user_field =
'fk_user_mod';
2402 if (in_array($table, array(
'prelevement_bons'))) {
2403 $fk_user_field =
'';
2406 if (!preg_match(
'/^[a-zA-Z_][a-zA-Z0-9_]*$/', $table)) {
2407 dol_syslog(get_class($this).
'::getValueFrom Bad table name: '.$table, LOG_WARNING);
2410 if (!preg_match(
'/^[a-zA-Z_][a-zA-Z0-9_.]*$/', $field)) {
2411 dol_syslog(get_class($this).
'::getValueFrom Bad field name: '.$field, LOG_WARNING);
2417 $sql =
"SELECT " . $this->db->sanitize($field);
2418 $sql .=
" FROM " . MAIN_DB_PREFIX . $this->db->sanitize($table);
2419 $sql .=
" WHERE " . $this->db->sanitize($id_field) .
" = " . ((int) $id);
2421 $resql = $this->db->query($sql);
2423 if ($obj = $this->db->fetch_object($resql)) {
2424 if ($format ==
'date') {
2425 $oldvalue = $this->db->jdate($obj->$field);
2427 $oldvalue = $obj->$field;
2431 $this->error = $this->db->lasterror();
2442 $sql =
"UPDATE ".$this->db->prefix().$table.
" SET ";
2444 if ($format ==
'text') {
2445 $sql .= $this->db->sanitize($field).
" = '".$this->db->escape($value).
"'";
2446 } elseif ($format ==
'int') {
2447 $sql .= $this->db->sanitize($field).
" = ".((int) $value);
2448 } elseif ($format ==
'date') {
2449 $sql .= $this->db->sanitize($field).
" = ".($value ?
"'".$this->db->idate($value).
"'" :
"null");
2450 } elseif ($format ==
'dategmt') {
2451 $sql .= $this->db->sanitize($field).
" = ".($value ?
"'".$this->db->idate($value,
'gmt').
"'" :
"null");
2454 if ($fk_user_field) {
2455 if (!empty($fuser) && is_object($fuser)) {
2456 $sql .=
", ".$this->db->sanitize($fk_user_field).
" = ".((int) $fuser->id);
2457 } elseif (empty($fuser) || $fuser !=
'none') {
2458 $sql .=
", ".$this->db->sanitize($fk_user_field).
" = ".((int) $user->id);
2462 $sql .=
" WHERE ".$this->db->sanitize($id_field).
" = ".((int) $id);
2464 $resql = $this->db->query($sql);
2468 if (method_exists($this,
'fetch')) {
2469 $result = $this->fetch(
$id);
2474 $this->oldcopy = clone $this;
2475 if (property_exists($this->oldcopy, $field)) {
2476 $this->oldcopy->$field = $oldvalue;
2478 if ($propfield != $field && property_exists($this->oldcopy, $propfield)) {
2479 $this->oldcopy->$propfield = $oldvalue;
2482 if (empty($this->context[
'actionmsgmore'])) {
2483 $this->context[
'actionmsgmore'] =
'Trigger called by setValueFrom';
2487 $result = $this->call_trigger($trigkey, (!empty($fuser) && is_object($fuser)) ? $fuser : $user);
2493 if (property_exists($this, $field)) {
2494 $this->$field = $value;
2496 if ($propfield != $field && property_exists($this, $propfield)) {
2497 $this->$propfield = $value;
2502 $this->db->commit();
2505 if (property_exists($this, $field)) {
2506 $this->$field = $oldvalue;
2508 if ($propfield != $field && property_exists($this, $propfield)) {
2509 $this->$propfield = $oldvalue;
2511 $this->db->rollback();
2515 if ($this->db->lasterrno() ==
'DB_ERROR_RECORD_ALREADY_EXISTS') {
2516 $this->error =
'DB_ERROR_RECORD_ALREADY_EXISTS';
2518 $this->error = $this->db->lasterror();
2520 $this->db->rollback();
2539 global
$conf, $user;
2541 if (!$this->table_element) {
2542 dol_print_error(
null, get_class($this).
"::load_previous_next_ref was called on object with property table_element not defined");
2545 if ($fieldid ==
'none') {
2550 if (in_array($this->table_element, array(
'facture_rec',
'facture_fourn_rec')) && $fieldid ==
'title') {
2556 if ($user->socid > 0) {
2557 $socid = $user->socid;
2562 $aliastablesociete =
's';
2563 if ($this->element ==
'societe') {
2564 $aliastablesociete =
'te';
2566 $restrictiononfksoc = empty($this->restrictiononfksoc) ? 0 : $this->restrictiononfksoc;
2567 $sql =
"SELECT MAX(te.".$this->db->sanitize($fieldid).
")";
2568 $sql .=
" FROM ".(empty($nodbprefix) ? $this->db->prefix() :
'').$this->table_element.
" as te";
2569 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2570 $tmparray = explode(
'@', $this->ismultientitymanaged);
2571 $sql .=
", ".$this->db->prefix().$this->db->sanitize($tmparray[1]).
" as ".($tmparray[1] ==
'societe' ?
's' :
'parenttable');
2572 } elseif ($restrictiononfksoc == 1 && $this->element !=
'societe' && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2573 $sql .=
", ".$this->db->prefix().
"societe as s";
2574 } elseif ($restrictiononfksoc == 2 && $this->element !=
'societe' && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2575 $sql .=
" LEFT JOIN ".$this->db->prefix().
"societe as s ON te.fk_soc = s.rowid";
2577 if ($restrictiononfksoc && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2578 $sql .=
" LEFT JOIN ".$this->db->prefix().
"societe_commerciaux as sc ON ".$aliastablesociete.
".rowid = sc.fk_soc";
2580 if ($fieldid ==
'rowid') {
2581 $sql .=
" WHERE te.".$this->db->sanitize($fieldid).
" < ".((int) $this->
id);
2582 } elseif ($fieldid ==
'label') {
2583 $sql .=
" WHERE te.".$this->db->sanitize($fieldid).
" < '".$this->db->escape((
string) $this->label).
"'";
2585 $sql .=
" WHERE te.".$this->db->sanitize($fieldid).
" < '".$this->db->escape((
string) $this->
ref).
"'";
2587 if ($restrictiononfksoc == 1 && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2588 $sql .=
" AND sc.fk_user = ".((int) $user->id);
2590 if ($restrictiononfksoc == 2 && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2591 $sql .=
" AND (sc.fk_user = ".((int) $user->id).
' OR te.fk_soc IS NULL)';
2594 $filtermax = $filter;
2599 if ($errormessage) {
2600 if (!preg_match(
'/^\s*AND/i', $filtermax)) {
2608 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2609 $tmparray = explode(
'@', $this->ismultientitymanaged);
2610 $sql .=
" AND te.".$this->db->sanitize($tmparray[0]).
" = ".($tmparray[1] ==
"societe" ?
"s" :
"parenttable").
".rowid";
2611 } elseif ($restrictiononfksoc == 1 && $this->element !=
'societe' && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2612 $sql .=
' AND te.fk_soc = s.rowid';
2614 if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
2615 if ($this->element ==
'user' &&
getDolGlobalInt(
'MULTICOMPANY_TRANSVERSE_MODE')) {
2616 if (!empty($user->admin) && empty($user->entity) &&
$conf->entity == 1) {
2617 $sql .=
" AND te.entity IS NOT NULL";
2619 $sql .=
" AND te.rowid IN (SELECT ug.fk_user FROM ".$this->db->prefix().
"usergroup_user as ug WHERE ug.entity IN (".
getEntity(
'usergroup').
"))";
2622 $sql .=
' AND te.entity IN ('.getEntity($this->element).
')';
2625 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged) && $this->element !=
'societe') {
2626 $tmparray = explode(
'@', $this->ismultientitymanaged);
2627 $sql .=
' AND parenttable.entity IN ('.getEntity($tmparray[1]).
')';
2629 if ($restrictiononfksoc == 1 && $socid && $this->element !=
'societe') {
2630 $sql .=
' AND te.fk_soc = '.((int) $socid);
2632 if ($restrictiononfksoc == 2 && $socid && $this->element !=
'societe') {
2633 $sql .=
' AND (te.fk_soc = '.((int) $socid).
' OR te.fk_soc IS NULL)';
2635 if ($restrictiononfksoc && $socid && $this->element ==
'societe') {
2636 $sql .=
' AND te.rowid = '.((int) $socid);
2640 $result = $this->db->query($sql);
2642 $this->error = $this->db->lasterror();
2645 $row = $this->db->fetch_row($result);
2646 $this->ref_previous = $row[0];
2648 $sql =
"SELECT MIN(te.".$this->db->sanitize($fieldid).
")";
2649 $sql .=
" FROM ".(empty($nodbprefix) ? $this->db->prefix() :
'').$this->table_element.
" as te";
2650 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2651 $tmparray = explode(
'@', $this->ismultientitymanaged);
2652 $sql .=
", ".$this->db->prefix().$this->db->sanitize($tmparray[1]).
" as ".($tmparray[1] ==
'societe' ?
's' :
'parenttable');
2653 } elseif ($restrictiononfksoc == 1 && $this->element !=
'societe' && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2654 $sql .=
", ".$this->db->prefix().
"societe as s";
2655 } elseif ($restrictiononfksoc == 2 && $this->element !=
'societe' && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2656 $sql .=
" LEFT JOIN ".$this->db->prefix().
"societe as s ON te.fk_soc = s.rowid";
2658 if ($restrictiononfksoc && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2659 $sql .=
" LEFT JOIN ".$this->db->prefix().
"societe_commerciaux as sc ON ".$aliastablesociete.
".rowid = sc.fk_soc";
2661 if ($fieldid ==
'rowid') {
2662 $sql .=
" WHERE te.".$this->db->sanitize($fieldid).
" > ".((int) $this->
id);
2663 } elseif ($fieldid ==
'label') {
2664 $sql .=
" WHERE te.".$this->db->sanitize($fieldid).
" > '".$this->db->escape((
string) $this->label).
"'";
2666 $sql .=
" WHERE te.".$this->db->sanitize($fieldid).
" > '".$this->db->escape((
string) $this->
ref).
"'";
2668 if ($restrictiononfksoc == 1 && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2669 $sql .=
" AND (sc.fk_user = ".((int) $user->id);
2671 $userschilds = $user->getAllChildIds();
2672 $sql .=
" OR sc.fk_user IN (".$this->db->sanitize(implode(
',', $userschilds)).
")";
2676 if ($restrictiononfksoc == 2 && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2677 $sql .=
" AND (sc.fk_user = ".((int) $user->id).
' OR te.fk_soc IS NULL)';
2680 $filtermin = $filter;
2685 if ($errormessage) {
2686 if (!preg_match(
'/^\s*AND/i', $filtermin)) {
2696 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2697 $tmparray = explode(
'@', $this->ismultientitymanaged);
2698 $sql .=
" AND te.".$this->db->sanitize($tmparray[0]).
" = ".($tmparray[1] ==
"societe" ?
"s" :
"parenttable").
".rowid";
2699 } elseif ($restrictiononfksoc == 1 && $this->element !=
'societe' && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2700 $sql .=
' AND te.fk_soc = s.rowid';
2702 if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
2703 if ($this->element ==
'user' &&
getDolGlobalInt(
'MULTICOMPANY_TRANSVERSE_MODE')) {
2704 if (!empty($user->admin) && empty($user->entity) &&
$conf->entity == 1) {
2705 $sql .=
" AND te.entity IS NOT NULL";
2707 $sql .=
" AND te.rowid IN (SELECT ug.fk_user FROM ".$this->db->prefix().
"usergroup_user as ug WHERE ug.entity IN (".
getEntity(
'usergroup').
"))";
2710 $sql .=
' AND te.entity IN ('.getEntity($this->element).
')';
2713 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged) && $this->element !=
'societe') {
2714 $tmparray = explode(
'@', $this->ismultientitymanaged);
2715 $sql .=
' AND parenttable.entity IN ('.getEntity($tmparray[1]).
')';
2717 if ($restrictiononfksoc == 1 && $socid && $this->element !=
'societe') {
2718 $sql .=
' AND te.fk_soc = '.((int) $socid);
2720 if ($restrictiononfksoc == 2 && $socid && $this->element !=
'societe') {
2721 $sql .=
' AND (te.fk_soc = '.((int) $socid).
' OR te.fk_soc IS NULL)';
2723 if ($restrictiononfksoc && $socid && $this->element ==
'societe') {
2724 $sql .=
' AND te.rowid = '.((int) $socid);
2729 $result = $this->db->query($sql);
2731 $this->error = $this->db->lasterror();
2734 $row = $this->db->fetch_row($result);
2735 $this->ref_next = $row[0];
2750 $contactAlreadySelected = array();
2755 if ($source ==
'thirdparty') {
2756 $contactAlreadySelected[$i] = $tab[$i][
'socid'];
2758 $contactAlreadySelected[$i] = $tab[$i][
'id'];
2762 return $contactAlreadySelected;
2778 if (!$this->table_element) {
2779 dol_syslog(get_class($this).
"::setProject was called on object with property table_element not defined", LOG_ERR);
2783 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
2784 if ($this->table_element ==
'actioncomm') {
2786 $sql .=
" SET fk_project = ".((int) $projectid);
2788 $sql .=
" SET fk_project = NULL";
2790 $sql .=
' WHERE id = '.((int) $this->
id);
2792 } elseif (!empty($this->fields[
'fk_project'])) {
2794 $sql .=
" SET fk_project = ".((int) $projectid);
2796 $sql .=
" SET fk_project = NULL";
2798 $sql .=
' WHERE rowid = '.((int) $this->
id);
2801 $sql .=
' SET fk_projet = '.((int) $projectid);
2803 $sql .=
' SET fk_projet = NULL';
2805 $sql .=
" WHERE rowid = ".((int) $this->
id);
2810 dol_syslog(get_class($this).
"::setProject", LOG_DEBUG);
2811 if ($this->db->query($sql)) {
2812 $this->fk_project = ((int) $projectid);
2819 if (!$error && !$notrigger) {
2821 $result = $this->call_trigger(strtoupper($this->element) .
'_MODIFY', $user);
2830 $this->db->rollback();
2833 $this->db->commit();
2851 dol_syslog(get_class($this).
'::setPaymentMethods('.$id.
')');
2853 if ($this->
status >= 0 || $this->element ==
'societe') {
2857 $fieldname =
'fk_mode_reglement';
2858 $triggerName = (empty($this->TRIGGER_PREFIX) ? strtoupper(get_class($this)) : $this->TRIGGER_PREFIX);
2859 if ($this->element ==
'societe') {
2860 $fieldname =
'mode_reglement';
2861 $triggerName =
'COMPANY';
2863 if (get_class($this) ==
'Facture') {
2864 $triggerName =
'BILL';
2866 if (get_class($this) ==
'Fournisseur') {
2867 $fieldname =
'mode_reglement_supplier';
2868 $triggerName =
'BILL_SUPPLIER';
2870 if (get_class($this) ==
'Tva') {
2871 $fieldname =
'fk_typepayment';
2872 $triggerName =
'VAT';
2874 if (get_class($this) ==
'Salary') {
2875 $fieldname =
'fk_typepayment';
2878 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
2879 $sql .=
" SET ".$this->db->sanitize($fieldname).
" = ".(($id > 0 || $id ==
'0') ? ((
int) $id) :
'NULL');
2880 $sql .=
' WHERE rowid = '.((int) $this->
id);
2882 if ($this->db->query($sql)) {
2883 $this->mode_reglement_id = $id;
2885 if (get_class($this) ==
'Fournisseur') {
2886 $this->mode_reglement_supplier_id = $id;
2890 if (!$error && !$notrigger) {
2892 $result = $this->call_trigger($triggerName.
'_MODIFY', $user);
2900 dol_syslog(get_class($this).
'::setPaymentMethods Error '.$this->db->error());
2901 $this->error = $this->db->error();
2905 dol_syslog(get_class($this).
'::setPaymentMethods, status of the object is incompatible');
2906 $this->error =
'Status of the object is incompatible '.$this->status;
2919 dol_syslog(get_class($this).
'::setMulticurrencyCode('.$code.
')');
2920 if ($this->
status >= 0 || $this->element ==
'societe') {
2921 $sql =
'UPDATE '.$this->db->prefix().$this->table_element;
2922 $sql .=
" SET multicurrency_code = '".$this->db->escape($code).
"'";
2923 $sql .=
' WHERE rowid='.((int) $this->
id);
2925 if ($this->db->query($sql)) {
2926 $this->multicurrency_code = $code;
2930 $this->setMulticurrencyRate($rate, 2);
2935 dol_syslog(get_class($this).
'::setMulticurrencyCode Error '.$sql.
' - '.$this->db->error());
2936 $this->error = $this->db->error();
2940 dol_syslog(get_class($this).
'::setMulticurrencyCode, status of the object is incompatible');
2941 $this->error =
'Status of the object is incompatible '.$this->status;
2953 public function setMulticurrencyRate($rate, $mode = 1)
2955 dol_syslog(get_class($this).
'::setMulticurrencyRate('.$rate.
', '.$mode.
')');
2956 if ($this->
status >= 0 || $this->element ==
'societe') {
2957 $sql =
'UPDATE '.$this->db->prefix().$this->table_element;
2958 $sql .=
" SET multicurrency_tx = ".((float) $rate);
2959 $sql .=
' WHERE rowid='.((int) $this->
id);
2961 if ($this->db->query($sql)) {
2962 $this->multicurrency_tx = $rate;
2965 if (!empty($this->lines)) {
2966 foreach ($this->lines as &$line) {
2969 if (!empty($line->fk_remise_except)) {
2975 $line->subprice = 0;
2980 $line->multicurrency_subprice = 0;
2983 switch ($this->element) {
2987 '@phan-var-force Propal $this';
2988 '@phan-var-force PropaleLigne $line';
2993 $line->remise_percent,
2995 $line->localtax1_tx,
2996 $line->localtax2_tx,
2997 ($line->description ? $line->description : $line->desc),
3000 $line->special_code,
3001 $line->fk_parent_line,
3002 $line->skip_update_total,
3003 $line->fk_fournprice,
3006 $line->product_type,
3009 $line->array_options,
3011 $line->multicurrency_subprice
3017 '@phan-var-force Commande $this';
3018 '@phan-var-force OrderLine $line';
3021 ($line->description ? $line->description : $line->desc),
3024 $line->remise_percent,
3026 $line->localtax1_tx,
3027 $line->localtax2_tx,
3032 $line->product_type,
3033 $line->fk_parent_line,
3034 $line->skip_update_total,
3035 $line->fk_fournprice,
3038 $line->special_code,
3039 $line->array_options,
3041 $line->multicurrency_subprice
3047 '@phan-var-force Facture $this';
3048 '@phan-var-force FactureLigne $line';
3051 ($line->description ? $line->description : $line->desc),
3054 $line->remise_percent,
3058 $line->localtax1_tx,
3059 $line->localtax2_tx,
3062 $line->product_type,
3063 $line->fk_parent_line,
3064 $line->skip_update_total,
3065 $line->fk_fournprice,
3068 $line->special_code,
3069 $line->array_options,
3070 $line->situation_percent,
3072 $line->multicurrency_subprice
3078 '@phan-var-force FactureRec $this';
3079 '@phan-var-force FactureLigneRec $line';
3082 ($line->description ? $line->description : $line->desc),
3086 $line->localtax1_tx,
3087 $line->localtax2_tx,
3089 $line->remise_percent,
3094 $line->product_type,
3096 $line->special_code,
3099 $line->multicurrency_subprice,
3103 $line->fk_fournprice,
3105 $line->fk_parent_line
3108 case 'supplier_proposal':
3111 '@phan-var-force SupplierProposal $this';
3112 '@phan-var-force SupplierProposalLine $line';
3117 $line->remise_percent,
3119 $line->localtax1_tx,
3120 $line->localtax2_tx,
3121 ($line->description ? $line->description : $line->desc),
3124 $line->special_code,
3125 $line->fk_parent_line,
3126 $line->skip_update_total,
3127 $line->fk_fournprice,
3130 $line->product_type,
3131 $line->array_options,
3133 (int) $line->fk_unit,
3134 $line->multicurrency_subprice
3137 case 'order_supplier':
3140 '@phan-var-force CommandeFournisseur $this';
3141 '@phan-var-force CommandeFournisseurLigne $line';
3144 ($line->description ? $line->description : $line->desc),
3147 $line->remise_percent,
3149 $line->localtax1_tx,
3150 $line->localtax2_tx,
3153 $line->product_type,
3157 $line->array_options,
3159 $line->multicurrency_subprice,
3163 case 'invoice_supplier':
3166 '@phan-var-force FactureFournisseur $this';
3167 '@phan-var-force SupplierInvoiceLIne $line';
3170 ($line->description ? $line->description : $line->desc),
3173 $line->localtax1_tx,
3174 $line->localtax2_tx,
3179 $line->product_type,
3180 $line->remise_percent,
3184 $line->array_options,
3186 $line->multicurrency_subprice,
3191 dol_syslog(get_class($this).
'::setMulticurrencyRate no updateline defined', LOG_DEBUG);
3199 dol_syslog(get_class($this).
'::setMulticurrencyRate Error '.$sql.
' - '.$this->db->error());
3200 $this->error = $this->db->error();
3204 dol_syslog(get_class($this).
'::setMulticurrencyRate, status of the object is incompatible');
3205 $this->error =
'Status of the object is incompatible '.$this->status;
3220 if ($this->
status >= 0 || $this->element ==
'societe') {
3222 $fieldname =
'fk_cond_reglement';
3223 if ($this->element ==
'societe') {
3224 $fieldname =
'cond_reglement';
3226 if (get_class($this) ==
'Fournisseur') {
3227 $fieldname =
'cond_reglement_supplier';
3230 if (empty($deposit_percent) || $deposit_percent < 0) {
3231 $deposit_percent = (float)
getDictionaryValue(
'c_payment_term',
'deposit_percent', $id);
3234 if ($deposit_percent > 100) {
3235 $deposit_percent = 100;
3238 $sql =
'UPDATE '.$this->db->prefix().$this->table_element;
3239 $sql .=
" SET ".$this->db->sanitize($fieldname).
" = ".(($id > 0 || $id ==
'0') ? ((
int) $id) :
'NULL');
3240 if (in_array($this->table_element, array(
'propal',
'commande',
'supplier_proposal',
'commande_fournisseur',
'societe'))) {
3241 $sql .=
" , deposit_percent = " . (empty($deposit_percent) ?
'NULL' :
"'".$this->db->escape((
string) $deposit_percent).
"'");
3243 $sql .=
' WHERE rowid = '.((int) $this->
id);
3245 if ($this->db->query($sql)) {
3246 $this->cond_reglement_id = $id;
3248 if (get_class($this) ==
'Fournisseur') {
3249 $this->cond_reglement_supplier_id = $id;
3251 $this->deposit_percent = $deposit_percent;
3254 dol_syslog(get_class($this).
'::setPaymentTerms Error '.$sql.
' - '.$this->db->error());
3255 $this->error = $this->db->error();
3259 dol_syslog(get_class($this).
'::setPaymentTerms, status of the object is incompatible');
3260 $this->error =
'Status of the object is incompatible '.$this->status;
3273 dol_syslog(get_class($this).
'::setTransportMode('.$id.
')');
3274 if ($this->
status >= 0 || $this->element ==
'societe') {
3275 $fieldname =
'fk_transport_mode';
3276 if ($this->element ==
'societe') {
3277 $fieldname =
'transport_mode';
3279 if (get_class($this) ==
'Fournisseur') {
3280 $fieldname =
'transport_mode_supplier';
3283 $sql =
'UPDATE '.$this->db->prefix().$this->table_element;
3284 $sql .=
" SET ".$this->db->sanitize($fieldname).
" = ".(($id > 0 || $id ==
'0') ? ((
int) $id) :
'NULL');
3285 $sql .=
' WHERE rowid='.((int) $this->
id);
3287 if ($this->db->query($sql)) {
3288 $this->transport_mode_id = $id;
3290 if (get_class($this) ==
'Fournisseur') {
3291 $this->transport_mode_supplier_id = $id;
3295 dol_syslog(get_class($this).
'::setTransportMode Error '.$sql.
' - '.$this->db->error());
3296 $this->error = $this->db->error();
3300 dol_syslog(get_class($this).
'::setTransportMode, status of the object is incompatible');
3301 $this->error =
'Status of the object is incompatible '.$this->status;
3315 $fieldname =
'fk_delivery_address';
3316 if ($this->element ==
'delivery' || $this->element ==
'shipping') {
3317 $fieldname =
'fk_address';
3320 $sql =
"UPDATE ".$this->db->prefix().$this->table_element.
" SET ".$this->db->sanitize($fieldname).
" = ".((int) $id);
3321 $sql .=
" WHERE rowid = ".((int) $this->
id).
" AND fk_statut = 0";
3323 if ($this->db->query($sql)) {
3324 $this->fk_delivery_address =
$id;
3327 $this->error = $this->db->error();
3328 dol_syslog(get_class($this).
'::setDeliveryAddress Error '.$this->error);
3346 if (empty($userused)) {
3352 if (!$this->table_element) {
3353 dol_syslog(get_class($this).
"::setShippingMethod was called on object with property table_element not defined", LOG_ERR);
3359 if ($shipping_method_id < 0) {
3360 $shipping_method_id =
'NULL';
3362 dol_syslog(get_class($this).
'::setShippingMethod('.$shipping_method_id.
')');
3364 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
3365 $sql .=
" SET fk_shipping_method = ".((int) $shipping_method_id);
3366 $sql .=
" WHERE rowid=".((int) $this->
id);
3367 $resql = $this->db->query($sql);
3369 dol_syslog(get_class($this).
'::setShippingMethod Error ', LOG_DEBUG);
3370 $this->error = $this->db->lasterror();
3375 $this->context = array(
'shippingmethodupdate' => 1);
3376 $triggerPrefix = (empty($this->TRIGGER_PREFIX) ? strtoupper(get_class($this)) : $this->TRIGGER_PREFIX);
3377 $result = $this->call_trigger($triggerPrefix.
'_MODIFY', $userused);
3385 $this->db->rollback();
3388 $this->shipping_method_id = ($shipping_method_id ==
'NULL') ?
null : $shipping_method_id;
3389 $this->db->commit();
3403 if (!$this->table_element) {
3404 dol_syslog(get_class($this).
"::setWarehouse was called on object with property table_element not defined", LOG_ERR);
3407 if ($warehouse_id < 0) {
3408 $warehouse_id =
'NULL';
3410 dol_syslog(get_class($this).
'::setWarehouse('.$warehouse_id.
')');
3412 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
3413 $sql .=
" SET fk_warehouse = ".((int) $warehouse_id);
3414 $sql .=
" WHERE rowid=".((int) $this->
id);
3416 if ($this->db->query($sql)) {
3417 $this->warehouse_id = ($warehouse_id ==
'NULL') ?
null : $warehouse_id;
3420 dol_syslog(get_class($this).
'::setWarehouse Error ', LOG_DEBUG);
3421 $this->error = $this->db->error();
3436 if (!$this->table_element) {
3437 dol_syslog(get_class($this).
"::setDocModel was called on object with property table_element not defined", LOG_ERR);
3441 $newmodelpdf =
dol_trunc($modelpdf, 255);
3443 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
3444 $sql .=
" SET model_pdf = '".$this->db->escape($newmodelpdf).
"'";
3445 $sql .=
" WHERE rowid = ".((int) $this->
id);
3447 dol_syslog(get_class($this).
"::setDocModel", LOG_DEBUG);
3448 $resql = $this->db->query($sql);
3450 $this->model_pdf = $modelpdf;
3471 if (empty($userused)) {
3477 if (!$this->table_element) {
3478 dol_syslog(get_class($this).
"::setBankAccount was called on object with property table_element not defined", LOG_ERR);
3483 if ($fk_account < 0) {
3484 $fk_account =
'NULL';
3486 dol_syslog(get_class($this).
'::setBankAccount('.$fk_account.
')');
3488 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
3489 $sql .=
" SET fk_account = ".((int) $fk_account);
3490 $sql .=
" WHERE rowid=".((int) $this->
id);
3492 $resql = $this->db->query($sql);
3494 dol_syslog(get_class($this).
'::setBankAccount Error '.$sql.
' - '.$this->db->error());
3495 $this->error = $this->db->lasterror();
3500 $this->context[
'bankaccountupdate'] = 1;
3502 $triggerName = (empty($this->TRIGGER_PREFIX) ? strtoupper(get_class($this)) : $this->TRIGGER_PREFIX);
3503 $result = $this->call_trigger($triggerName .
'_MODIFY', $userused);
3511 $this->db->rollback();
3514 $this->fk_account = ($fk_account ==
'NULL') ?
null : $fk_account;
3515 $this->db->commit();
3533 public function line_order($renum =
false, $rowidorder =
'ASC', $fk_parent_line =
true)
3536 if (!$this->table_element_line) {
3537 dol_syslog(get_class($this).
"::line_order was called on object with property table_element_line not defined", LOG_ERR);
3540 if (!$this->fk_element) {
3541 dol_syslog(get_class($this).
"::line_order was called on object with property fk_element not defined", LOG_ERR);
3545 $fieldposition =
'rang';
3546 if (in_array($this->table_element_line, array(
'bom_bomline',
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3547 $fieldposition =
'position';
3552 $sql =
"SELECT count(rowid) FROM ".$this->db->prefix().$this->db->sanitize($this->table_element_line);
3553 $sql .=
" WHERE ".$this->db->sanitize($this->fk_element).
" = ".((int) $this->
id);
3555 $sql .=
" AND " . $this->db->sanitize($fieldposition) .
" = 0";
3558 $sql .=
" AND " . $this->db->sanitize($fieldposition) .
" <> 0";
3561 dol_syslog(get_class($this).
"::line_order", LOG_DEBUG);
3562 $resql = $this->db->query($sql);
3564 $row = $this->db->fetch_row($resql);
3574 $sql =
"SELECT rowid FROM ".$this->db->prefix().$this->db->sanitize($this->table_element_line);
3575 $sql .=
" WHERE ".$this->db->sanitize($this->fk_element).
" = ".((int) $this->
id);
3576 if ($fk_parent_line) {
3577 $sql .=
' AND fk_parent_line IS NULL';
3579 $sql .=
" ORDER BY " . $this->db->sanitize($fieldposition) .
" ASC, rowid " . $this->db->sanitize($rowidorder);
3581 dol_syslog(get_class($this).
"::line_order search all parent lines", LOG_DEBUG);
3582 $resql = $this->db->query($sql);
3585 $num = $this->db->num_rows($resql);
3588 $row = $this->db->fetch_row($resql);
3590 if ($fk_parent_line) {
3593 if (!empty($children)) {
3594 foreach ($children as $child) {
3595 array_push($rows, $child);
3602 if (!empty($rows)) {
3603 foreach ($rows as $key => $row) {
3623 $fieldposition =
'rang';
3624 if (in_array($this->table_element_line, array(
'bom_bomline',
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3625 $fieldposition =
'position';
3630 $sql =
"SELECT rowid FROM ".$this->db->prefix().$this->db->sanitize($this->table_element_line);
3631 $sql .=
" WHERE ".$this->db->sanitize($this->fk_element).
" = ".((int) $this->
id);
3632 $sql .=
' AND fk_parent_line = '.((int) $id);
3633 $sql .=
" ORDER BY " . $this->db->sanitize($fieldposition) .
" ASC";
3635 dol_syslog(get_class($this).
"::getChildrenOfLine search children lines for line ".$id, LOG_DEBUG);
3637 $resql = $this->db->query($sql);
3638 if (!$resql || $this->db->num_rows($resql) <= 0) {
3642 while ($row = $this->db->fetch_row($resql)) {
3644 if (!empty($includealltree) && $includealltree <= 1000) {
3645 $rows = array_merge($rows, $this->
getChildrenOfLine($row[0], $includealltree + 1));
3659 public function line_up($rowid, $fk_parent_line =
true)
3662 $this->
line_order(
false,
'ASC', $fk_parent_line);
3682 $this->
line_order(
false,
'ASC', $fk_parent_line);
3703 global $hookmanager;
3704 $fieldposition =
'rang';
3705 if (in_array($this->table_element_line, array(
'bom_bomline',
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3706 $fieldposition =
'position';
3709 $sql =
"UPDATE ".$this->db->prefix().$this->table_element_line.
" SET ".$this->db->sanitize($fieldposition).
" = ".((int) $rang);
3710 $sql .=
' WHERE rowid = '.((int) $rowid);
3711 if ($this->
id > 0 && !empty($this->fk_element)) {
3713 $sql .=
" AND ".$this->db->sanitize($this->fk_element).
" = ".((int) $this->
id);
3716 dol_syslog(get_class($this).
"::updateRangOfLine", LOG_DEBUG);
3717 if (!$this->db->query($sql)) {
3722 $parameters = array(
'rowid' => $rowid,
'rang' => $rang,
'fieldposition' => $fieldposition);
3724 $reshook = $hookmanager->executeHooks(
'afterRankOfLineUpdate', $parameters, $this, $action);
3738 $num = count($rows);
3739 for ($i = 0; $i < $num; $i++) {
3757 $fieldposition =
'rang';
3758 if (in_array($this->table_element_line, array(
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3759 $fieldposition =
'position';
3762 $sql =
"UPDATE ".$this->db->prefix().$this->db->sanitize($this->table_element_line).
" SET ".$this->db->sanitize($fieldposition).
" = ".((int) $rang);
3763 $sql .=
" WHERE ".$this->db->sanitize($this->fk_element).
" = ".((int) $this->
id);
3764 $sql .=
" AND " . $this->db->sanitize($fieldposition) .
" = " . ((int) ($rang - 1));
3765 if (!$this->db->query($sql)) {
3766 $this->error = $this->db->lasterror();
3770 $sql =
"UPDATE ".$this->db->prefix().$this->table_element_line.
" SET ".$this->db->sanitize($fieldposition).
" = ".((int) ($rang - 1));
3771 $sql .=
' WHERE rowid = '.((int) $rowid);
3772 if (!$this->db->query($sql)) {
3773 $this->error = $this->db->lasterror();
3790 if ($rang >= $max) {
3794 $fieldposition =
'rang';
3795 if (in_array($this->table_element_line, array(
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3796 $fieldposition =
'position';
3799 $sql =
"UPDATE ".$this->db->prefix().$this->db->sanitize($this->table_element_line).
" SET ".$this->db->sanitize($fieldposition).
" = ".((int) $rang);
3800 $sql .=
" WHERE ".$this->db->sanitize($this->fk_element).
" = ".((int) $this->
id);
3801 $sql .=
" AND " . $this->db->sanitize($fieldposition) .
" = " . ((int) ($rang + 1));
3802 if (!$this->db->query($sql)) {
3803 $this->error = $this->db->lasterror();
3807 $sql =
"UPDATE ".$this->db->prefix().$this->table_element_line.
" SET ".$this->db->sanitize($fieldposition).
" = ".((int) ($rang + 1));
3808 $sql .=
' WHERE rowid = '.((int) $rowid);
3809 if (!$this->db->query($sql)) {
3810 $this->error = $this->db->lasterror();
3825 $fieldposition =
'rang';
3826 if (in_array($this->table_element_line, array(
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3827 $fieldposition =
'position';
3830 $sql =
"SELECT " . $this->db->sanitize($fieldposition) .
" FROM ".$this->db->prefix().$this->db->sanitize($this->table_element_line);
3831 $sql .=
" WHERE rowid = ".((int) $rowid);
3833 dol_syslog(get_class($this).
"::getRangOfLine", LOG_DEBUG);
3834 $resql = $this->db->query($sql);
3839 $row = $this->db->fetch_row($resql);
3851 $fieldposition =
'rang';
3852 if (in_array($this->table_element_line, array(
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3853 $fieldposition =
'position';
3856 $sql =
"SELECT rowid FROM ".$this->db->prefix().$this->db->sanitize($this->table_element_line);
3857 $sql .=
" WHERE ".$this->db->sanitize($this->fk_element).
" = ".((int) $this->
id);
3858 $sql .=
" AND " . $this->db->sanitize($fieldposition) .
" = ".((int) $rang);
3859 $resql = $this->db->query($sql);
3864 $row = $this->db->fetch_row($resql);
3879 if (empty($packaging) || !is_numeric($packaging) || (
float) $packaging <= 0) {
3882 $sign = ((float) $qty < 0 ? -1 : 1);
3883 $absqty = abs((
float) $qty);
3884 if ($absqty < (
float) $packaging) {
3885 return $sign * (float) $packaging;
3887 if ((
float)
price2num(fmod($absqty, (
float) $packaging),
'MS')) {
3888 $coeff = intval($absqty / (
float) $packaging) + 1;
3889 return $sign * (float)
price2num((
float) $packaging * $coeff,
'MS');
3904 $positionfield =
'rang';
3905 if (in_array($this->table_element, array(
'bom_bom',
'product_attribute'))) {
3906 $positionfield =
'position';
3909 $sql =
"SELECT max(".$this->db->sanitize($positionfield).
") FROM ".$this->db->prefix().$this->db->sanitize($this->table_element_line);
3910 $sql .=
" WHERE ".$this->db->sanitize($this->fk_element).
" = ".((int) $this->
id);
3913 if ($fk_parent_line) {
3914 $sql .=
" AND fk_parent_line = ".((int) $fk_parent_line);
3917 dol_syslog(get_class($this).
"::line_max", LOG_DEBUG);
3918 $resql = $this->db->query($sql);
3920 $row = $this->db->fetch_row($resql);
3922 if ($fk_parent_line) {
3923 if (!empty($row[0])) {
3946 if (!$this->table_element) {
3947 dol_syslog(get_class($this).
"::update_ref_ext was called on object with property table_element not defined", LOG_ERR);
3951 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
3952 $sql .=
" SET ref_ext = '".$this->db->escape($ref_ext).
"'";
3954 $sql .=
" WHERE ".(isset($this->table_rowid) ? $this->table_rowid :
'rowid').
" = ".((
int) $this->id);
3956 dol_syslog(get_class($this).
"::update_ref_ext", LOG_DEBUG);
3957 if ($this->db->query($sql)) {
3958 $this->ref_ext = $ref_ext;
3961 $this->error = $this->db->error();
3980 if (!$this->table_element) {
3981 $this->error =
'update_note was called on object with property table_element not defined';
3982 dol_syslog(get_class($this).
"::update_note was called on object with property table_element not defined", LOG_ERR);
3985 if (!in_array($suffix, array(
'',
'_public',
'_private'))) {
3986 $this->error =
'update_note Parameter suffix must be empty, \'_private\' or \'_public\'';
3987 dol_syslog(get_class($this).
"::update_note Parameter suffix must be empty, '_private' or '_public'", LOG_ERR);
3991 $newsuffix = $suffix;
3994 if ($this->table_element ==
'product' && $newsuffix ==
'_private') {
3997 if (in_array($this->table_element, array(
'actioncomm',
'adherent',
'advtargetemailing',
'cronjob',
'establishment'))) {
3998 $fieldusermod =
"fk_user_mod";
3999 } elseif ($this->table_element ==
'ecm_files') {
4000 $fieldusermod =
"fk_user_m";
4002 $fieldusermod =
"fk_user_modif";
4004 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
4005 $sql .=
" SET note".$this->db->sanitize($newsuffix).
" = ".(!empty($note) ? (
"'".$this->db->escape($note).
"'") :
"NULL");
4006 $sql .=
", ".$this->db->sanitize($fieldusermod).
" = ".((int) $user->id);
4007 $sql .=
" WHERE rowid = ".((int) $this->
id);
4009 dol_syslog(get_class($this).
"::update_note", LOG_DEBUG);
4010 if ($this->db->query($sql)) {
4011 if ($suffix ==
'_public') {
4012 $this->note_public = $note;
4013 } elseif ($suffix ==
'_private') {
4014 $this->note_private = $note;
4016 $this->note = $note;
4017 $this->note_private = $note;
4019 if (empty($notrigger)) {
4021 switch ($this->element) {
4023 $triggerName =
'COMPANY_MODIFY';
4026 $triggerName =
'BILL_MODIFY';
4028 case 'invoice_supplier':
4029 $triggerName =
'BILL_SUPPLIER_MODIFY';
4032 $triggerName =
'BILLREC_MODIFIY';
4034 case 'expensereport':
4035 $triggerName =
'EXPENSE_REPORT_MODIFY';
4038 $triggerName = (!empty($this->TRIGGER_PREFIX) ? $this->TRIGGER_PREFIX : strtoupper($this->element)) .
'_MODIFY';
4040 $ret = $this->call_trigger($triggerName, $user);
4047 $this->error = $this->db->lasterror();
4078 public function update_price($exclspec = 0, $roundingadjust =
'auto', $nodatabaseupdate = 0, $seller =
null)
4081 global
$conf, $hookmanager, $action;
4083 $parameters = array(
'exclspec' => $exclspec,
'roundingadjust' => $roundingadjust,
'nodatabaseupdate' => $nodatabaseupdate,
'seller' => $seller);
4084 $reshook = $hookmanager->executeHooks(
'updateTotalPrice', $parameters, $this, $action);
4087 } elseif ($reshook < 0) {
4092 $isElementForSupplier =
false;
4093 $roundTotalConstName =
'MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND';
4095 if ($this->element ==
'propal') {
4096 $MODULE =
"MODULE_DISALLOW_UPDATE_PRICE_PROPOSAL";
4097 } elseif ($this->element ==
'commande' || $this->element ==
'order') {
4098 $MODULE =
"MODULE_DISALLOW_UPDATE_PRICE_ORDER";
4099 } elseif ($this->element ==
'facture' || $this->element ==
'invoice') {
4100 $MODULE =
"MODULE_DISALLOW_UPDATE_PRICE_INVOICE";
4101 } elseif ($this->element ==
'facture_fourn' || $this->element ==
'supplier_invoice' || $this->element ==
'invoice_supplier' || $this->element ==
'invoice_supplier_rec') {
4102 $isElementForSupplier =
true;
4103 $MODULE =
"MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_INVOICE";
4104 } elseif ($this->element ==
'order_supplier' || $this->element ==
'supplier_order') {
4105 $isElementForSupplier =
true;
4106 $MODULE =
"MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_ORDER";
4107 } elseif ($this->element ==
'supplier_proposal') {
4108 $isElementForSupplier =
true;
4109 $MODULE =
"MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_PROPOSAL";
4111 if ($isElementForSupplier) {
4112 $roundTotalConstName =
'MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND_SUPPLIER';
4115 if (!empty($MODULE)) {
4118 foreach ($modsactivated as $mod) {
4126 include_once DOL_DOCUMENT_ROOT.
'/core/lib/price.lib.php';
4128 $forcedroundingmode = $roundingadjust;
4129 if ($forcedroundingmode ==
'auto' && isset(
$conf->global->{$roundTotalConstName})) {
4131 } elseif ($forcedroundingmode ==
'auto') {
4132 $forcedroundingmode =
'0';
4137 $multicurrency_tx = !empty($this->multicurrency_tx) ? $this->multicurrency_tx : 1;
4140 $fieldtva =
'total_tva';
4141 $fieldlocaltax1 =
'total_localtax1';
4142 $fieldlocaltax2 =
'total_localtax2';
4143 $fieldup =
'subprice';
4144 $base_price_type =
'HT';
4145 if ($this->element ==
'facture_fourn' || $this->element ==
'invoice_supplier') {
4149 if ($this->element ==
'invoice_supplier_rec') {
4152 if ($this->element ==
'expensereport') {
4156 $forcedroundingmode =
'0';
4157 $fieldup =
'value_unit';
4158 $base_price_type =
'TTC';
4161 $sql =
"SELECT rowid, qty, ".$this->db->sanitize($fieldup).
" as up, remise_percent,";
4162 $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,";
4163 $sql .=
' tva_tx as vatrate, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type,';
4164 $sql .=
' info_bits, product_type,';
4165 if ($this->element ==
'expensereport') {
4166 $sql .=
' comments as description';
4168 $sql .=
' description';
4170 if ($this->table_element_line ==
'facturedet') {
4171 $sql .=
', situation_percent';
4173 $sql .=
', multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc';
4174 $sql .=
" FROM ".$this->db->prefix().$this->db->sanitize($this->table_element_line);
4175 $sql .=
" WHERE ".$this->db->sanitize($this->fk_element).
" = ".((int) $this->
id);
4177 $product_field =
'product_type';
4178 if ($this->table_element_line ==
'contratdet') {
4179 $product_field =
'';
4181 if ($product_field) {
4182 $sql .=
" AND ".$this->db->sanitize($product_field).
" <> 9";
4185 $sql .=
' ORDER by rowid';
4187 dol_syslog(get_class($this).
"::update_price", LOG_DEBUG);
4189 $resql = $this->db->query($sql);
4191 $this->total_ht = 0;
4192 $this->total_tva = 0;
4193 $this->total_localtax1 = 0;
4194 $this->total_localtax2 = 0;
4195 $this->total_ttc = 0;
4196 $total_ht_by_vats = array();
4197 $total_tva_by_vats = array();
4198 $total_ttc_by_vats = array();
4199 $this->multicurrency_total_ht = 0;
4200 $this->multicurrency_total_tva = 0;
4201 $this->multicurrency_total_ttc = 0;
4205 $num = $this->db->num_rows($resql);
4208 $obj = $this->db->fetch_object($resql);
4211 $parameters = array(
'fk_element' => $obj->rowid);
4212 $reshook = $hookmanager->executeHooks(
'changeRoundingMode', $parameters, $this, $action);
4214 if (empty($reshook) && $forcedroundingmode ==
'0') {
4216 $localtax_array = array($obj->localtax1_type, $obj->localtax1_tx, $obj->localtax2_type, $obj->localtax2_tx);
4217 $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);
4219 $diff_when_using_price_ht =
price2num((
float) $tmpcal[1] - $obj->total_tva,
'MT', 1);
4220 $diff_on_current_total =
price2num($obj->total_ttc - $obj->total_ht - $obj->total_tva - $obj->total_localtax1 - $obj->total_localtax2,
'MT', 1);
4224 if ($diff_on_current_total) {
4226 $sqlfix =
"UPDATE ".$this->db->prefix().$this->table_element_line;
4227 $sqlfix .=
" SET ".$this->db->sanitize($fieldtva).
" = ".
price2num((
float) $tmpcal[1]).
", total_ttc = ".
price2num((
float) $tmpcal[2]);
4228 $sqlfix .=
", multicurrency_total_tva = ".price2num((
float) $tmpcal[17]).
", multicurrency_total_ttc = ".
price2num((
float) $tmpcal[18]);
4229 $sqlfix .=
" WHERE rowid = ".((int) $obj->rowid);
4230 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);
4231 $resqlfix = $this->db->query($sqlfix);
4235 $obj->total_tva = $tmpcal[1];
4236 $obj->total_ttc = $tmpcal[2];
4237 $obj->multicurrency_total_tva = $tmpcal[17];
4238 $obj->multicurrency_total_ttc = $tmpcal[18];
4239 } elseif ($diff_when_using_price_ht) {
4243 if ((
float) $tmpcal[0] == (
float) $obj->total_ht) {
4246 if ($obj->description !=
'(DEPOSIT)' && !
getDolGlobalInt(
'MAIN_DISABLE_AUTOFIX_CORRUPTED_LINES_WHEN_TOTAL_DOES_NOT_MATCH_RECALCULATION_FROM_UP')) {
4250 $sqlfix =
"UPDATE ".$this->db->prefix().$this->table_element_line;
4251 $sqlfix .=
" SET ".$this->db->sanitize($fieldtva).
" = ".
price2num((
float) $tmpcal[1]).
", total_ttc = ".
price2num((
float) $tmpcal[2]);
4252 $sqlfix .=
", multicurrency_total_tva = ".price2num((
float) $tmpcal[17]).
", multicurrency_total_ttc = ".
price2num((
float) $tmpcal[18]);
4253 $sqlfix .=
" WHERE rowid = ".((int) $obj->rowid);
4255 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);
4257 $resqlfix = $this->db->query($sqlfix);
4261 $obj->total_tva = $tmpcal[1];
4262 $obj->total_ttc = $tmpcal[2];
4263 $obj->multicurrency_total_tva = $tmpcal[17];
4264 $obj->multicurrency_total_ttc = $tmpcal[18];
4270 $this->total_ht += $obj->total_ht;
4271 $this->total_tva += $obj->total_tva;
4272 $this->total_localtax1 += $obj->total_localtax1;
4273 $this->total_localtax2 += $obj->total_localtax2;
4274 $this->total_ttc += $obj->total_ttc;
4275 $this->multicurrency_total_ht += $obj->multicurrency_total_ht;
4276 $this->multicurrency_total_tva += $obj->multicurrency_total_tva;
4277 $this->multicurrency_total_ttc += $obj->multicurrency_total_ttc;
4279 if (!isset($total_ht_by_vats[$obj->vatrate])) {
4280 $total_ht_by_vats[$obj->vatrate] = 0;
4282 if (!isset($total_tva_by_vats[$obj->vatrate])) {
4283 $total_tva_by_vats[$obj->vatrate] = 0;
4285 if (!isset($total_ttc_by_vats[$obj->vatrate])) {
4286 $total_ttc_by_vats[$obj->vatrate] = 0;
4288 $total_ht_by_vats[$obj->vatrate] += $obj->total_ht;
4289 $total_tva_by_vats[$obj->vatrate] += $obj->total_tva;
4290 $total_ttc_by_vats[$obj->vatrate] += $obj->total_ttc;
4292 if ($forcedroundingmode ==
'1') {
4293 if ($base_price_type ==
'TTC') {
4294 $tmpvat =
price2num($total_ttc_by_vats[$obj->vatrate] * $obj->vatrate / (100 + $obj->vatrate),
'MT', 1);
4296 $tmpvat =
price2num($total_ht_by_vats[$obj->vatrate] * $obj->vatrate / 100,
'MT', 1);
4298 $diff =
price2num($total_tva_by_vats[$obj->vatrate] - (
float) $tmpvat,
'MT', 1);
4301 $maxdiff = (10 * pow(10, -1 *
getDolGlobalInt(
'MAIN_MAX_DECIMALS_TOT', 0)));
4302 if (abs((
float) $diff) > $maxdiff) {
4304 $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.';
4306 $this->error = $errmsg;
4311 if ($base_price_type ==
'TTC') {
4312 $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);
4313 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);
4315 $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);
4316 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);
4319 $resqlfix = $this->db->query($sqlfix);
4325 $this->total_tva = (float)
price2num($this->total_tva - (
float) $diff,
'', 1);
4326 $total_tva_by_vats[$obj->vatrate] = (float)
price2num($total_tva_by_vats[$obj->vatrate] - (
float) $diff,
'', 1);
4327 if ($base_price_type ==
'TTC') {
4328 $this->total_ht = (float)
price2num($this->total_ht + (
float) $diff,
'', 1);
4329 $total_ht_by_vats[$obj->vatrate] = (float)
price2num($total_ht_by_vats[$obj->vatrate] + (
float) $diff,
'', 1);
4331 $this->total_ttc = (float)
price2num($this->total_ttc - (
float) $diff,
'', 1);
4332 $total_ttc_by_vats[$obj->vatrate] = (float)
price2num($total_ttc_by_vats[$obj->vatrate] - (
float) $diff,
'', 1);
4342 $this->total_ttc += isset($this->revenuestamp) ? $this->revenuestamp : 0;
4344 $this->multicurrency_total_ttc += isset($this->revenuestamp) ? ($this->revenuestamp * $multicurrency_tx) : 0;
4347 if (!empty($this->situation_cycle_ref) && !empty($this->situation_counter) && $this->situation_counter > 1 && method_exists($this,
'get_prev_sits')) {
4348 '@phan-var-force Facture $this';
4349 include_once DOL_DOCUMENT_ROOT.
'/compta/facture/class/facture.class.php';
4352 $prev_sits = $this->get_prev_sits();
4354 foreach ($prev_sits as $sit) {
4355 $this->total_ht -= $sit->total_ht;
4356 $this->total_tva -= $sit->total_tva;
4357 $this->total_localtax1 -= $sit->total_localtax1;
4358 $this->total_localtax2 -= $sit->total_localtax2;
4359 $this->total_ttc -= $sit->total_ttc;
4360 $this->multicurrency_total_ht -= $sit->multicurrency_total_ht;
4361 $this->multicurrency_total_tva -= $sit->multicurrency_total_tva;
4362 $this->multicurrency_total_ttc -= $sit->multicurrency_total_ttc;
4369 $this->total_ht = (float)
price2num($this->total_ht);
4370 $this->total_tva = (float)
price2num($this->total_tva);
4371 $this->total_localtax1 = (float)
price2num($this->total_localtax1);
4372 $this->total_localtax2 = (float)
price2num($this->total_localtax2);
4373 $this->total_ttc = (float)
price2num($this->total_ttc);
4375 $this->db->free($resql);
4378 $fieldht =
'total_ht';
4380 $fieldlocaltax1 =
'localtax1';
4381 $fieldlocaltax2 =
'localtax2';
4382 $fieldttc =
'total_ttc';
4384 if (in_array($this->element, array(
'propal',
'commande',
'facture',
'facturerec',
'supplier_proposal',
'order_supplier',
'facture_fourn',
'invoice_supplier',
'invoice_supplier_rec',
'expensereport'))) {
4385 $fieldtva =
'total_tva';
4388 if (!$error && empty($nodatabaseupdate)) {
4389 $sql =
"UPDATE ".$this->db->prefix().$this->table_element.
' SET';
4390 $sql .=
" ".$this->db->sanitize($fieldht).
" = ".((float)
price2num($this->total_ht,
'MT', 1)).
",";
4391 $sql .=
" ".$this->db->sanitize($fieldtva).
" = ".((float)
price2num($this->total_tva,
'MT', 1)).
",";
4392 $sql .=
" ".$this->db->sanitize($fieldlocaltax1).
" = ".((float)
price2num($this->total_localtax1,
'MT', 1)).
",";
4393 $sql .=
" ".$this->db->sanitize($fieldlocaltax2).
" = ".((float)
price2num($this->total_localtax2,
'MT', 1)).
",";
4394 $sql .=
" ".$this->db->sanitize($fieldttc).
" = ".((float)
price2num($this->total_ttc,
'MT', 1));
4395 $sql .=
", multicurrency_total_ht = ".((float)
price2num($this->multicurrency_total_ht,
'MT', 1));
4396 $sql .=
", multicurrency_total_tva = ".((float)
price2num($this->multicurrency_total_tva,
'MT', 1));
4397 $sql .=
", multicurrency_total_ttc = ".((float)
price2num($this->multicurrency_total_ttc,
'MT', 1));
4398 $sql .=
" WHERE rowid = ".((int) $this->
id);
4400 dol_syslog(get_class($this).
"::update_price", LOG_DEBUG);
4401 $resql = $this->db->query($sql);
4405 $this->error = $this->db->lasterror();
4406 $this->errors[] = $this->db->lasterror();
4411 $this->db->commit();
4414 $this->db->rollback();
4434 public function add_object_linked($origin =
null, $origin_id =
null, $f_user =
null, $notrigger = 0)
4437 global $user, $hookmanager, $action;
4440 if (empty($this->origin_type) && !empty($this->origin)) {
4441 $this->origin_type = $this->origin;
4443 $origin = (!empty($origin) ? $origin : $this->origin_type);
4444 $origin_id = (!empty($origin_id) ? $origin_id : $this->origin_id);
4445 $f_user = isset($f_user) ? $f_user : $user;
4448 if ($origin ==
'order') {
4449 $origin =
'commande';
4451 if ($origin ==
'invoice') {
4452 $origin =
'facture';
4454 if ($origin ==
'invoice_template') {
4455 $origin =
'facturerec';
4457 if ($origin ==
'supplierorder') {
4458 $origin =
'order_supplier';
4462 $targettype = $this->getElementType();
4464 $parameters = array(
'targettype' => $targettype);
4466 $reshook = $hookmanager->executeHooks(
'setLinkedObjectSourceTargetType', $parameters, $this, $action);
4468 if (!empty($hookmanager->resArray[
'targettype'])) {
4469 $targettype = $hookmanager->resArray[
'targettype'];
4476 $sql =
"INSERT INTO " . $this->db->prefix() .
"element_element (";
4477 $sql .=
"fk_source";
4478 $sql .=
", sourcetype";
4479 $sql .=
", fk_target";
4480 $sql .=
", targettype";
4481 $sql .=
") VALUES (";
4482 $sql .= ((int) $origin_id);
4483 $sql .=
", '" . $this->db->escape($origin) .
"'";
4484 $sql .=
", " . ((int) $this->
id);
4485 $sql .=
", '" . $this->db->escape($targettype) .
"'";
4488 dol_syslog(get_class($this) .
"::add_object_linked", LOG_DEBUG);
4489 if ($this->db->query($sql)) {
4493 if ($origin ===
'order_supplier' && $targettype ===
'invoice_supplier' && $this->element ===
'invoice_supplier' && (
int) $origin_id > 0 && (
int) $this->
id > 0) {
4494 $sourceinvoices = array();
4496 $sqlsources =
"SELECT DISTINCT rc.fk_invoice_supplier_source as rowid";
4497 $sqlsources .=
" FROM ".$this->db->prefix().
"societe_remise_except as rc";
4498 $sqlsources .=
" WHERE rc.fk_invoice_supplier = ".((int) $this->
id);
4499 $sqlsources .=
" AND rc.fk_invoice_supplier_source IS NOT NULL";
4501 $resqlsources = $this->db->query($sqlsources);
4502 if ($resqlsources) {
4503 while ($objsrc = $this->db->fetch_object($resqlsources)) {
4504 $srcid = (int) $objsrc->rowid;
4505 if ($srcid > 0 && $srcid !== (
int) $this->
id) {
4506 $sourceinvoices[$srcid] = $srcid;
4510 dol_syslog(get_class($this).
"::add_object_linked Failed to read supplier invoice discounts sources", LOG_WARNING);
4513 if (!empty($sourceinvoices)) {
4514 $existing = array();
4515 $sourcelist = implode(
',', $sourceinvoices);
4517 $sqlexists =
"SELECT fk_target";
4518 $sqlexists .=
" FROM ".$this->db->prefix().
"element_element";
4519 $sqlexists .=
" WHERE fk_source = ".((int) $origin_id);
4520 $sqlexists .=
" AND sourcetype = '".$this->db->escape($origin).
"'";
4521 $sqlexists .=
" AND targettype = '".$this->db->escape($targettype).
"'";
4522 $sqlexists .=
" AND fk_target IN (".$this->db->sanitize($sourcelist).
")";
4524 $resqlexists = $this->db->query($sqlexists);
4526 while ($objexist = $this->db->fetch_object($resqlexists)) {
4527 $existing[(int) $objexist->fk_target] = 1;
4530 dol_syslog(get_class($this).
"::add_object_linked Failed to read existing linked supplier invoices", LOG_WARNING);
4533 foreach ($sourceinvoices as $srcid) {
4534 if (!empty($existing[(
int) $srcid])) {
4538 $sqladd =
"INSERT INTO " . $this->db->prefix() .
"element_element (fk_source, sourcetype, fk_target, targettype)";
4539 $sqladd .=
" VALUES (".((int) $origin_id).
", '".$this->db->escape($origin).
"', ".((int) $srcid).
", '".$this->db->escape($targettype).
"')";
4540 $this->db->query($sqladd);
4547 $this->context[
'link_origin'] = $origin;
4548 $this->context[
'link_origin_id'] = $origin_id;
4550 $result = $this->call_trigger(
'OBJECT_LINK_INSERT', $f_user);
4557 $this->error = $this->db->lasterror();
4562 $this->db->commit();
4565 $this->db->rollback();
4579 $coreModule = array(
'knowledgemanagement',
'partnership',
'workstation',
'ticket',
'recruitment',
'eventorganization',
'asset');
4581 return ((!empty($this->module) && !in_array($this->module, $coreModule)) ? $this->module.
'_' :
'').$this->element;
4607 public function fetchObjectLinked($sourceid =
null, $sourcetype =
'', $targetid =
null, $targettype =
'', $clause =
'OR', $alsosametype = 1, $orderby =
'sourcetype', $loadalsoobjects = 1)
4609 global $hookmanager, $action;
4614 if ($this->
id > 0 && !empty($this->linkedObjectsFullLoaded[$this->
id])) {
4618 $this->linkedObjectsIds = array();
4619 $this->linkedObjects = array();
4622 $parameters = array(
4623 'sourceid' => $sourceid,
4624 'sourcetype' => $sourcetype,
4625 'targetid' => $targetid,
4626 'targettype' => $targettype,
4627 'clause' => $clause,
4628 'alsosametype' => $alsosametype,
4629 'orderby' => $orderby,
4630 'loadalsoobjects' => $loadalsoobjects
4632 $reshook = $hookmanager->executeHooks(
'fetchObjectLinked', $parameters, $this, $action);
4637 $justsource =
false;
4638 $justtarget =
false;
4639 $withtargettype =
false;
4640 $withsourcetype =
false;
4643 if (is_object($hookmanager)) {
4644 $parameters = array(
'sourcetype' => $sourcetype,
'sourceid' => $sourceid,
'targettype' => $targettype,
'targetid' => $targetid);
4645 $reshook = $hookmanager->executeHooks(
'setLinkedObjectSourceTargetType', $parameters, $this, $action);
4647 if (!empty($hookmanager->resArray[
'sourcetype'])) {
4648 $sourcetype = $hookmanager->resArray[
'sourcetype'];
4650 if (!empty($hookmanager->resArray[
'sourceid'])) {
4651 $sourceid = $hookmanager->resArray[
'sourceid'];
4653 if (!empty($hookmanager->resArray[
'targettype'])) {
4654 $targettype = $hookmanager->resArray[
'targettype'];
4656 if (!empty($hookmanager->resArray[
'targetid'])) {
4657 $targetid = $hookmanager->resArray[
'targetid'];
4662 if (!empty($sourceid) && !empty($sourcetype) && empty($targetid)) {
4664 if (!empty($targettype)) {
4665 $withtargettype =
true;
4668 if (!empty($targetid) && !empty($targettype) && empty($sourceid)) {
4670 if (!empty($sourcetype)) {
4671 $withsourcetype =
true;
4675 $sourceid = (!empty($sourceid) ? $sourceid :
$this->id);
4676 $targetid = (!empty($targetid) ? $targetid :
$this->id);
4677 $sourcetype = (!empty($sourcetype) ? $sourcetype : $this->getElementType());
4678 $targettype = (!empty($targettype) ? $targettype : $this->getElementType());
4687 $sql =
"SELECT rowid, fk_source, sourcetype, fk_target, targettype";
4688 $sql .=
" FROM ".$this->db->prefix().
"element_element";
4690 if ($justsource || $justtarget) {
4692 $sql .=
"fk_source = ".((int) $sourceid).
" AND sourcetype = '".$this->db->escape($sourcetype).
"'";
4693 if ($withtargettype) {
4694 $sql .=
" AND targettype = '".$this->db->escape($targettype).
"'";
4696 } elseif ($justtarget) {
4697 $sql .=
"fk_target = ".((int) $targetid).
" AND targettype = '".$this->db->escape($targettype).
"'";
4698 if ($withsourcetype) {
4699 $sql .=
" AND sourcetype = '".$this->db->escape($sourcetype).
"'";
4703 $sql .=
"(fk_source = ".((int) $sourceid).
" AND sourcetype = '".$this->db->escape($sourcetype).
"')";
4704 $sql .=
" ".$this->db->sanitize($clause).
" (fk_target = ".((int) $targetid).
" AND targettype = '".$this->db->escape($targettype).
"')";
4705 if ($loadalsoobjects && $this->
id > 0 && $sourceid == $this->
id && $sourcetype == $this->element && $targetid == $this->
id && $targettype == $this->element && $clause ==
'OR') {
4706 $this->linkedObjectsFullLoaded[
$this->id] =
true;
4709 $sql .= $this->db->order($orderby);
4711 dol_syslog(get_class($this).
"::fetchObjectLink", LOG_DEBUG);
4713 $resql = $this->db->query($sql);
4715 $num = $this->db->num_rows($resql);
4718 $obj = $this->db->fetch_object($resql);
4719 if ($justsource || $justtarget) {
4721 $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
4722 } elseif ($justtarget) {
4723 $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
4726 if ($obj->fk_source == $sourceid && $obj->sourcetype == $sourcetype) {
4727 $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
4729 if ($obj->fk_target == $targetid && $obj->targettype == $targettype) {
4730 $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
4736 if (!empty($this->linkedObjectsIds)) {
4737 $tmparray = $this->linkedObjectsIds;
4738 foreach ($tmparray as $objecttype => $objectids) {
4740 $element = $element_properties[
'element'];
4741 $classPath = $element_properties[
'classpath'];
4742 $classFile = $element_properties[
'classfile'];
4743 $className = $element_properties[
'classname'];
4744 $module = $element_properties[
'module'];
4747 if (
isModEnabled($module) && (($element != $this->element) || $alsosametype)) {
4748 if ($loadalsoobjects && (is_numeric($loadalsoobjects) || ($loadalsoobjects === $objecttype))) {
4750 if (class_exists($className)) {
4751 foreach ($objectids as $i => $objectid) {
4752 $object =
new $className($this->db);
4753 '@phan-var-force CommonObject $object';
4754 $ret =
$object->fetch($objectid);
4756 $this->linkedObjects[$objecttype][$i] =
$object;
4762 unset($this->linkedObjectsIds[$objecttype]);
4781 if ($this->
id > 0 && !empty($this->linkedObjectsFullLoaded[$this->
id])) {
4782 unset($this->linkedObjectsFullLoaded[$this->
id]);
4800 public function updateObjectLinked($sourceid =
null, $sourcetype =
'', $targetid =
null, $targettype =
'', $f_user =
null, $notrigger = 0)
4803 $updatesource =
false;
4804 $updatetarget =
false;
4805 $f_user = isset($f_user) ? $f_user : $user;
4808 if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) {
4809 $updatesource =
true;
4810 } elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) {
4811 $updatetarget =
true;
4817 $sql =
"UPDATE " . $this->db->prefix() .
"element_element SET ";
4818 if ($updatesource) {
4819 $sql .=
"fk_source = " . ((int) $sourceid);
4820 $sql .=
", sourcetype = '" . $this->db->escape($sourcetype) .
"'";
4821 $sql .=
" WHERE fk_target = " . ((int) $this->
id);
4822 $sql .=
" AND targettype = '" . $this->db->escape($this->element) .
"'";
4823 } elseif ($updatetarget) {
4824 $sql .=
"fk_target = " . ((int) $targetid);
4825 $sql .=
", targettype = '" . $this->db->escape($targettype) .
"'";
4826 $sql .=
" WHERE fk_source = " . ((int) $this->
id);
4827 $sql .=
" AND sourcetype = '" . $this->db->escape($this->element) .
"'";
4830 dol_syslog(get_class($this) .
"::updateObjectLinked", LOG_DEBUG);
4831 if ($this->db->query($sql)) {
4834 $this->context[
'link_source_id'] = $sourceid;
4835 $this->context[
'link_source_type'] = $sourcetype;
4836 $this->context[
'link_target_id'] = $targetid;
4837 $this->context[
'link_target_type'] = $targettype;
4839 $result = $this->call_trigger(
'OBJECT_LINK_MODIFY', $f_user);
4846 $this->error = $this->db->lasterror();
4851 $this->db->commit();
4854 $this->db->rollback();
4872 public function deleteObjectLinked($sourceid =
null, $sourcetype =
'', $targetid =
null, $targettype =
'', $rowid = 0, $f_user =
null, $notrigger = 0)
4875 $deletesource =
false;
4876 $deletetarget =
false;
4877 $f_user = isset($f_user) ? $f_user : $user;
4879 if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) {
4880 $deletesource =
true;
4881 } elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) {
4882 $deletetarget =
true;
4885 $element = $this->getElementType();
4886 $sourceid = (!empty($sourceid) ? $sourceid :
$this->id);
4887 $sourcetype = (!empty($sourcetype) ? $sourcetype : $element);
4888 $targetid = (!empty($targetid) ? $targetid :
$this->id);
4889 $targettype = (!empty($targettype) ? $targettype : $element);
4895 $this->context[
'link_id'] = $rowid;
4896 $this->context[
'link_source_id'] = $sourceid;
4897 $this->context[
'link_source_type'] = $sourcetype;
4898 $this->context[
'link_target_id'] = $targetid;
4899 $this->context[
'link_target_type'] = $targettype;
4901 $result = $this->call_trigger(
'OBJECT_LINK_DELETE', $f_user);
4909 $sql =
"DELETE FROM " . $this->db->prefix() .
"element_element";
4912 $sql .=
" rowid = " . ((int) $rowid);
4914 if ($deletesource) {
4915 $sql .=
" fk_source = " . ((int) $sourceid) .
" AND sourcetype = '" . $this->db->escape($sourcetype) .
"'";
4916 $sql .=
" AND fk_target = " . ((int) $this->
id) .
" AND targettype = '" . $this->db->escape($element) .
"'";
4917 } elseif ($deletetarget) {
4918 $sql .=
" fk_target = " . ((int) $targetid) .
" AND targettype = '" . $this->db->escape($targettype) .
"'";
4919 $sql .=
" AND fk_source = " . ((int) $this->
id) .
" AND sourcetype = '" . $this->db->escape($element) .
"'";
4921 $sql .=
" (fk_source = " . ((int) $this->
id) .
" AND sourcetype = '" . $this->db->escape($element) .
"')";
4923 $sql .=
" (fk_target = " . ((int) $this->
id) .
" AND targettype = '" . $this->db->escape($element) .
"')";
4927 dol_syslog(get_class($this) .
"::deleteObjectLinked", LOG_DEBUG);
4928 if (!$this->db->query($sql)) {
4929 $this->error = $this->db->lasterror();
4930 $this->errors[] = $this->error;
4936 $this->db->commit();
4939 $this->db->rollback();
4955 if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
4958 if (!preg_match(
'/^[_a-zA-Z0-9]+$/', $field_select)) {
4959 dol_syslog(
'Invalid value $field_select for parameter '.$field_select.
' in call to getAllItemsLinkedByObjectID(). Must be a single field name.', LOG_ERR);
4964 $sql =
"SELECT ".$db->sanitize($field_select).
" FROM ".
$db->prefix().$db->sanitize($table_element).
" WHERE ".
$db->sanitize($field_where).
" = ".((int) $fk_object_where);
4965 $resql =
$db->query($sql);
4968 if (!empty($resql)) {
4969 while ($res =
$db->fetch_object($resql)) {
4970 $TRes[] = $res->{$field_select};
4987 if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
4993 $sql =
"SELECT COUNT(*) as nb FROM ".$db->prefix().$db->sanitize($table_element).
" WHERE ".
$db->sanitize($field_where).
" = ".((int) $fk_object_where);
4994 $resql =
$db->query($sql);
4997 $res =
$db->fetch_object($resql);
5016 if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
5022 $sql =
"DELETE FROM ".$db->prefix().$table_element.
" WHERE ".
$db->sanitize($field_where).
" = ".((int) $fk_object_where);
5023 $resql =
$db->query($sql);
5025 if (empty($resql)) {
5043 public function setStatut($status, $elementId =
null, $elementType =
'', $trigkey =
'', $fieldstatus =
'')
5047 $savElementId = $elementId;
5049 $elementId = (!empty($elementId) ? $elementId :
$this->id);
5050 $elementTable = (!empty($elementType) ? $elementType : $this->table_element);
5054 if (empty($fieldstatus)) {
5055 if ($elementTable ==
'facture_rec') {
5056 $fieldstatus =
"suspended";
5058 if ($elementTable ==
'mailing') {
5059 $fieldstatus =
"statut";
5061 if ($elementTable ==
'cronjob') {
5062 $fieldstatus =
"status";
5064 if ($elementTable ==
'user') {
5065 $fieldstatus =
"statut";
5067 if ($elementTable ==
'expensereport') {
5068 $fieldstatus =
"fk_statut";
5070 if ($elementTable ==
'receptiondet_batch') {
5071 $fieldstatus =
"status";
5073 if ($elementTable ==
'prelevement_bons') {
5074 $fieldstatus =
"statut";
5076 if ($elementTable ==
'bank_account') {
5077 $fieldstatus =
"clos";
5079 if (isset($this->fields) && is_array($this->fields) && array_key_exists(
'status', $this->fields)) {
5080 $fieldstatus =
'status';
5083 if (empty($fieldstatus)) {
5084 $fieldstatus =
'fk_statut';
5088 $sql =
"UPDATE ".$this->db->prefix().$this->db->sanitize($elementTable);
5089 $sql .=
" SET ".$this->db->sanitize($fieldstatus).
" = ".((int) $status);
5092 if ($status == 1 && in_array($elementTable, array(
'expensereport',
'inventory'))) {
5093 $sql .=
", fk_user_valid = ".((int) $user->id);
5095 if ($status == 1 && in_array($elementTable, array(
'expensereport'))) {
5096 $sql .=
", date_valid = '".$this->db->idate(
dol_now()).
"'";
5098 if ($status == 1 && in_array($elementTable, array(
'inventory'))) {
5099 $sql .=
", date_validation = '".$this->db->idate(
dol_now()).
"'";
5101 $sql .=
" WHERE rowid = ".((int) $elementId);
5102 $sql .=
" AND ".$this->db->sanitize($fieldstatus).
" <> ".((int) $status);
5104 dol_syslog(get_class($this).
"::setStatut", LOG_DEBUG);
5105 $resql = $this->db->query($sql);
5109 $nb_rows_affected = $this->db->affected_rows($resql);
5111 if ($nb_rows_affected > 0) {
5112 if (empty($trigkey)) {
5114 if ($this->element ==
'supplier_proposal' && $status == 2) {
5115 $trigkey =
'SUPPLIER_PROPOSAL_SIGN';
5117 if ($this->element ==
'supplier_proposal' && $status == 3) {
5118 $trigkey =
'SUPPLIER_PROPOSAL_REFUSE';
5120 if ($this->element ==
'supplier_proposal' && $status == 4) {
5121 $trigkey =
'SUPPLIER_PROPOSAL_CLOSE';
5123 if ($this->element ==
'fichinter' && $status == 3) {
5124 $trigkey =
'FICHINTER_CLASSIFY_DONE';
5126 if ($this->element ==
'fichinter' && $status == 2) {
5127 $trigkey =
'FICHINTER_CLASSIFY_BILLED';
5129 if ($this->element ==
'fichinter' && $status == 1) {
5130 $trigkey =
'FICHINTER_CLASSIFY_UNBILLED';
5134 $this->context = array_merge($this->context, array(
'newstatus' => $status));
5136 if ($trigkey && $trigkey !=
'none') {
5140 $result = $this->call_trigger($trigkey, $user);
5151 $this->db->commit();
5153 if (empty($savElementId)) {
5155 if ($fieldstatus ==
'dispute_status') {
5156 $this->dispute_status = $status;
5157 } elseif ($fieldstatus ==
'tosell') {
5159 } elseif ($fieldstatus ==
'tobuy') {
5160 $this->status_buy = $status;
5161 } elseif ($fieldstatus ==
'tobatch') {
5162 $this->status_batch = $status;
5170 $this->db->rollback();
5171 dol_syslog(get_class($this).
"::setStatut ".$this->error, LOG_ERR);
5175 $this->error = $this->db->lasterror();
5176 $this->db->rollback();
5191 if (empty(
$id) && empty($ref)) {
5201 $sql =
"SELECT rowid, canvas";
5202 $sql .=
" FROM ".$this->db->prefix().$this->table_element;
5203 $sql .=
" WHERE entity IN (".getEntity($this->element).
")";
5205 $sql .=
" AND rowid = ".((int)
$id);
5208 $sql .=
" AND ref = '".$this->db->escape($ref).
"'";
5211 $resql = $this->db->query($sql);
5213 $obj = $this->db->fetch_object($resql);
5215 $this->canvas = $obj->canvas;
5235 $sql =
"SELECT special_code FROM ".$this->db->prefix().$this->db->sanitize($this->table_element_line);
5236 $sql .=
" WHERE rowid = ".((int) $lineid);
5237 $resql = $this->db->query($sql);
5239 $row = $this->db->fetch_row($resql);
5240 return (!empty($row[0]) ? $row[0] : 0);
5263 if (!isset($this->childtables) || !is_array($this->childtables) || count($this->childtables) == 0) {
5264 dol_print_error(
null,
'Called isObjectUsed on a class with property this->childtables not defined');
5268 $arraytoscan = $this->childtables;
5270 $tmparray = array_keys($this->childtables);
5271 if (is_numeric($tmparray[0])) {
5272 $arraytoscan = array_flip($this->childtables);
5277 foreach ($arraytoscan as $table => $element) {
5281 if (isset($element[
'enabled']) && !empty($element[
'enabled'])) {
5282 $enabled = (int)
dol_eval((
string) $element[
'enabled'], 1);
5283 if (empty($enabled)) {
5289 $sql =
"SELECT COUNT(*) as nb";
5290 $sql .=
" FROM ".$this->db->prefix().$this->db->sanitize($table).
" as c";
5291 if (!empty($element[
'parent']) && !empty($element[
'parentkey'])) {
5292 $sql .=
", ".$this->db->prefix().$this->db->sanitize($element[
'parent']).
" as p";
5294 if (!empty($element[
'fk_element'])) {
5295 $sql .=
" WHERE c.".$this->db->sanitize($element[
'fk_element']).
" = ".((int)
$id);
5297 $sql .=
" WHERE c.".$this->db->sanitize($this->fk_element).
" = ".((int)
$id);
5299 if (!empty($element[
'parent']) && !empty($element[
'parentkey'])) {
5300 $sql .=
" AND c.".$this->db->sanitize($element[
'parentkey']).
" = p.rowid";
5302 if (!empty($element[
'parent']) && !empty($element[
'parenttypefield']) && !empty($element[
'parenttypevalue'])) {
5303 $sql .=
" AND c.".$this->db->sanitize($element[
'parenttypefield']).
" = '".$this->db->escape($element[
'parenttypevalue']).
"'";
5305 if (!empty($entity)) {
5306 if (!empty($element[
'parent']) && !empty($element[
'parentkey'])) {
5307 $sql .=
" AND p.entity = ".((int) $entity);
5309 $sql .=
" AND c.entity = ".((int) $entity);
5314 $resql = $this->db->query($sql);
5316 $obj = $this->db->fetch_object($resql);
5318 $langs->load(
"errors");
5320 $haschild += (int) $obj->nb;
5321 if (is_numeric($element)) {
5322 $this->errors[] = $langs->transnoentitiesnoconv(
"ErrorRecordHasAtLeastOneChildOfType", method_exists($this,
'getNomUrl') ? $this->getNomUrl() : $this->ref, $table);
5323 } elseif (is_string($element)) {
5324 $this->errors[] = $langs->transnoentitiesnoconv(
"ErrorRecordHasAtLeastOneChildOfType", method_exists($this,
'getNomUrl') ? $this->getNomUrl() : $this->ref, $langs->transnoentitiesnoconv($element));
5326 $this->errors[] = $langs->transnoentitiesnoconv(
"ErrorRecordHasAtLeastOneChildOfType", method_exists($this,
'getNomUrl') ? $this->getNomUrl() : $this->ref, $langs->transnoentitiesnoconv($element[
'name']));
5331 $this->errors[] = $this->db->lasterror();
5336 if ($haschild > 0) {
5337 $this->errors[] =
"ErrorRecordHasChildren";
5354 foreach ($this->lines as $key => $val) {
5356 if ($predefined == -1) {
5359 if ($predefined == 1 && $val->fk_product > 0) {
5362 if ($predefined == 0 && $val->fk_product <= 0) {
5365 if ($predefined == 2 && $val->fk_product > 0 && $val->product_type == 0) {
5368 if ($predefined == 3 && $val->fk_product > 0 && $val->product_type == 1) {
5375 dol_syslog(get_class($this).
'::hasProductsOrServices we found '.$nb.
' qualified lines of products/servcies');
5386 if (!empty($this->table_element_line) && ($this->table_element_line !=
'expeditiondet')) {
5387 $total_discount = 0.00;
5389 $sql =
"SELECT subprice as pu_ht, qty, remise_percent, total_ht";
5390 $sql .=
" FROM ".$this->db->prefix().$this->table_element_line;
5391 $sql .=
" WHERE ".$this->db->sanitize($this->fk_element).
" = ".((int) $this->
id);
5393 dol_syslog(get_class($this).
'::getTotalDiscount', LOG_DEBUG);
5394 $resql = $this->db->query($sql);
5396 $num = $this->db->num_rows($resql);
5399 $obj = $this->db->fetch_object($resql);
5401 $pu_ht = $obj->pu_ht;
5403 $total_ht = $obj->total_ht;
5405 $total_discount_line = (float)
price2num(($pu_ht * $qty) - $total_ht,
'MT');
5406 $total_discount += $total_discount_line;
5413 return (
float)
price2num($total_discount);
5435 if (empty($this->lines)) {
5436 return array(
'weight' => $totalWeight,
'volume' => $totalVolume,
'ordered' => $totalOrdered,
'toship' => $totalToShip);
5439 foreach ($this->lines as $line) {
5440 if (isset($line->qty_asked)) {
5441 $totalOrdered += $line->qty_asked;
5443 if (isset($line->qty_shipped)) {
5444 $totalToShip += $line->qty_shipped;
5445 } elseif ($line->element ==
'commandefournisseurdispatch' && isset($line->qty)) {
5446 if (empty($totalToShip)) {
5449 $totalToShip += $line->qty;
5453 if ($this->element ==
'shipping') {
5455 $qty = $line->qty_shipped ? $line->qty_shipped : 0;
5457 $qty = $line->qty ? $line->qty : 0;
5460 $weight = !empty($line->weight) ? $line->weight : 0;
5461 ($weight == 0 && !empty($line->product->weight)) ? $weight = $line->product->weight : 0;
5462 $volume = !empty($line->volume) ? $line->volume : 0;
5463 ($volume == 0 && !empty($line->product->volume)) ? $volume = $line->product->volume : 0;
5465 $weight_units = !empty($line->weight_units) ? $line->weight_units : 0;
5466 ($weight_units == 0 && !empty($line->product->weight_units)) ? $weight_units = $line->product->weight_units : 0;
5467 $volume_units = !empty($line->volume_units) ? $line->volume_units : 0;
5468 ($volume_units == 0 && !empty($line->product->volume_units)) ? $volume_units = $line->product->volume_units : 0;
5472 if (!empty($weight_units)) {
5473 $weightUnit = $weight_units;
5475 if (!empty($volume_units)) {
5476 $volumeUnit = $volume_units;
5479 if (empty($totalWeight)) {
5482 if (empty($totalVolume)) {
5487 if ($weight_units < 50) {
5488 $trueWeightUnit = pow(10, $weightUnit);
5489 $totalWeight += $weight * $qty * $trueWeightUnit;
5491 if ($weight_units == 99) {
5493 $trueWeightUnit = 0.45359237;
5494 $totalWeight += $weight * $qty * $trueWeightUnit;
5495 } elseif ($weight_units == 98) {
5497 $trueWeightUnit = 0.0283495;
5498 $totalWeight += $weight * $qty * $trueWeightUnit;
5500 $totalWeight += $weight * $qty;
5503 if ($volume_units < 50) {
5505 $trueVolumeUnit = pow(10, $volumeUnit);
5507 $totalVolume += $volume * $qty * $trueVolumeUnit;
5509 $totalVolume += $volume * $qty;
5513 return array(
'weight' => $totalWeight,
'volume' => $totalVolume,
'ordered' => $totalOrdered,
'toship' => $totalToShip);
5526 $extraparams = (!empty($this->extraparams) ? json_encode($this->extraparams) :
null);
5527 $extraparams =
dol_trunc($extraparams, 250);
5529 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
5530 $sql .=
" SET extraparams = ".(!empty($extraparams) ?
"'".$this->db->escape($extraparams).
"'" :
"null");
5531 $sql .=
" WHERE rowid = ".((int) $this->
id);
5533 dol_syslog(get_class($this).
"::setExtraParameters", LOG_DEBUG);
5534 $resql = $this->db->query($sql);
5536 $this->error = $this->db->lasterror();
5537 $this->db->rollback();
5540 $this->db->commit();
5563 global
$conf, $user, $langs,
$object, $hookmanager, $extrafields, $form;
5566 if (!is_object($extrafields)) {
5567 require_once DOL_DOCUMENT_ROOT.
'/core/class/extrafields.class.php';
5570 $extrafields->fetch_name_optionals_label($this->table_element_line);
5575 $dirtpls = array_merge(
$conf->modules_parts[
'tpl'], array($defaulttpldir));
5576 foreach ($dirtpls as $module => $reldir) {
5577 if (!empty($module)) {
5580 $tpl = DOL_DOCUMENT_ROOT.$reldir.
'/objectline_create.tpl.php';
5583 if (empty(
$conf->file->strict_mode)) {
5584 $res = @include $tpl;
5586 $res = include $tpl;
5613 public function printObjectLines($action, $seller, $buyer, $selected = 0, $dateSelector = 0, $defaulttpldir =
'/core/tpl')
5615 global
$conf, $hookmanager, $langs, $user, $form, $extrafields,
$object;
5617 global $inputalsopricewithtax, $usemargins, $disableedit, $disablemove, $disableremove, $outputalsopricetotalwithtax;
5621 if (
isModEnabled(
'margin') && !empty($this->element) && in_array($this->element, array(
'facture',
'facturerec',
'propal',
'commande'))) {
5625 $num = count($this->lines);
5628 if (!is_object($extrafields)) {
5629 require_once DOL_DOCUMENT_ROOT.
'/core/class/extrafields.class.php';
5632 $extrafields->fetch_name_optionals_label($this->table_element_line);
5634 if (method_exists($this,
'loadExpeditions')) {
5636 $this->loadExpeditions();
5639 $parameters = array();
5640 $reshook = $hookmanager->executeHooks(
'printObjectLinesBlock', $parameters, $this, $action);
5641 if (empty($reshook)) {
5642 $parameters = array(
'num' => $num,
'dateSelector' => $dateSelector,
'seller' => $seller,
'buyer' => $buyer,
'selected' => $selected,
'table_element_line' => $this->table_element_line);
5643 $reshook = $hookmanager->executeHooks(
'printObjectLineTitle', $parameters, $this, $action);
5644 if (empty($reshook)) {
5648 $dirtpls = array_merge(
$conf->modules_parts[
'tpl'], array($defaulttpldir));
5649 foreach ($dirtpls as $module => $reldir) {
5651 if (!empty($module)) {
5654 $tpl = DOL_DOCUMENT_ROOT.$reldir.
'/objectline_title.tpl.php';
5656 if (file_exists($tpl)) {
5657 if (empty(
$conf->file->strict_mode)) {
5658 $res = @include $tpl;
5660 $res = include $tpl;
5671 print
"<!-- begin printObjectLines() -->\n";
5672 foreach ($this->lines as $line) {
5676 if (is_object($hookmanager)) {
5677 if (empty($line->fk_parent_line)) {
5678 $parameters = array(
'line' => $line,
'num' => $num,
'i' => $i,
'dateSelector' => $dateSelector,
'seller' => $seller,
'buyer' => $buyer,
'selected' => $selected,
'table_element_line' => $line->table_element,
'defaulttpldir' => $defaulttpldir);
5679 $reshook = $hookmanager->executeHooks(
'printObjectLine', $parameters, $this, $action);
5681 $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);
5682 $reshook = $hookmanager->executeHooks(
'printObjectSubLine', $parameters, $this, $action);
5685 if (empty($reshook)) {
5686 $this->printObjectLine($action, $line,
'', $num, $i, $dateSelector, $seller, $buyer, $selected, $extrafields, $defaulttpldir);
5691 print
"<!-- end printObjectLines() -->\n";
5712 public function printObjectLine($action, $line, $var, $num, $i, $dateSelector, $seller, $buyer, $selected = 0, $extrafields =
null, $defaulttpldir =
'/core/tpl')
5716 global $disableedit, $disablemove, $disableremove;
5723 if ($action !=
'editline' || $selected != $line->id) {
5725 if (!empty($line->fk_product) && $line->fk_product > 0) {
5726 $product_static =
new Product($this->db);
5727 $product_static->fetch($line->fk_product);
5729 $product_static->ref = (
string) $line->ref;
5730 $product_static->label = !empty($line->label) ? $line->label :
"";
5732 $text = $product_static->getNomUrl(1);
5737 if (property_exists($this,
'socid') && !empty($this->socid) && !is_object($this->thirdparty)) {
5738 dol_print_error(
null,
'Error: Method printObjectLine was called on an object and object->fetch_thirdparty was not done before');
5743 $prod->fetch($line->fk_product);
5745 $outputlangs = $langs;
5747 if (empty($newlang) &&
GETPOST(
'lang_id',
'aZ09')) {
5748 $newlang =
GETPOST(
'lang_id',
'aZ09');
5750 if (
getDolGlobalString(
'PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE') && empty($newlang) && is_object($this->thirdparty)) {
5751 $newlang = $this->thirdparty->default_lang;
5753 if (!empty($newlang)) {
5755 $outputlangs->setDefaultLang($newlang);
5758 $label = (!empty(
$prod->multilangs[$outputlangs->defaultlang][
"label"])) ?
$prod->multilangs[$outputlangs->defaultlang][
"label"] : $line->product_label;
5760 $label = $line->product_label;
5763 $text .=
' - '.(!empty($line->label) ? $line->label : $label);
5764 $description .= (
getDolGlobalInt(
'PRODUIT_DESC_IN_FORM_ACCORDING_TO_DEVICE') ?
'' : (!empty($line->description) ?
dol_htmlentitiesbr($line->description) :
''));
5768 if (empty((
float) $line->subprice_ttc) && $line->qty) {
5771 if ($line->remise_percent != 100) {
5772 $line->subprice_ttc = (float)
price2num($line->total_ttc * ($line->situation_percent ? 100 / $line->situation_percent : 1) / $line->qty / (1 - $line->remise_percent / 100),
'MU');
5775 $line->subprice_ttc = (float)
price2num((!empty($line->subprice) ? $line->subprice : 0) * (1 + ((!empty($line->tva_tx) ? $line->tva_tx : 0) / 100)),
'MU');
5778 $line->pu_ttc = $line->subprice_ttc;
5785 if (isset($this->expeditions[$line->id])) {
5786 $qty_shipped = $this->expeditions[$line->id];
5788 $disableedit = ($qty_shipped > 0) && ($qty_shipped >= $line->qty);
5790 $dirtpls = array_merge(
$conf->modules_parts[
'tpl'], array($defaulttpldir));
5791 foreach ($dirtpls as $module => $reldir) {
5793 if (!empty($module)) {
5796 $tpl = DOL_DOCUMENT_ROOT.$reldir.
'/objectline_view.tpl.php';
5799 if (file_exists($tpl)) {
5800 if (empty(
$conf->file->strict_mode)) {
5801 $res = @include $tpl;
5803 $res = include $tpl;
5813 if ($this->
status == 0 && $action ==
'editline' && $selected == $line->id) {
5814 $label = (!empty($line->label) ? $line->label : (($line->fk_product > 0) ? $line->product_label :
''));
5816 $line->subprice_ttc = (float)
price2num($line->subprice * (1 + ($line->tva_tx / 100)),
'MU');
5817 $line->pu_ttc = $line->subprice_ttc;
5822 $dirtpls = array_merge(
$conf->modules_parts[
'tpl'], array($defaulttpldir));
5823 foreach ($dirtpls as $module => $reldir) {
5824 if (!empty($module)) {
5827 $tpl = DOL_DOCUMENT_ROOT.$reldir.
'/objectline_edit.tpl.php';
5830 if (empty(
$conf->file->strict_mode)) {
5831 $res = @include $tpl;
5833 $res = include $tpl;
5858 global $langs, $hookmanager, $form, $action;
5860 print
'<!-- printOriginLinesList '.get_class($this).
' -->'.
"\n";
5861 print
'<tr class="liste_titre">';
5862 print
'<td class="linecolref">'.$langs->trans(
'Ref').
'</td>';
5863 print
'<td class="linecoldescription">'.$langs->trans(
'Description').
'</td>';
5864 print
'<td class="linecolvat right">'.$langs->trans(
'VATRate').
'</td>';
5865 print
'<td class="linecoluht right">'.$langs->trans(
'PriceUHT').
'</td>';
5867 print
'<td class="linecoluht_currency right">'.$langs->trans(
'PriceUHTCurrency').
'</td>';
5869 print
'<td class="linecolqty right">'.$langs->trans(
'Qty').
'</td>';
5871 print
'<td class="linecoluseunit left">'.$langs->trans(
'Unit').
'</td>';
5873 print
'<td class="linecoldiscount right">'.$langs->trans(
'ReductionShort').
'</td>';
5874 print
'<td class="linecolht right">'.$langs->trans(
'TotalHT').
'</td>';
5875 print
'<td class="center">';
5876 print $form->showCheckAddButtons(
'checkforselect', 1);
5881 if (!empty($this->lines)) {
5882 foreach ($this->lines as $line) {
5885 if (is_object($hookmanager)) {
5886 $parameters = array(
'line' => $line,
'i' => $i,
'restrictlist' => $restrictlist,
'selectedLines' => $selectedLines);
5887 if (!empty($line->fk_parent_line)) {
5888 $parameters[
'fk_parent_line'] = $line->fk_parent_line;
5890 $reshook = $hookmanager->executeHooks(
'printOriginObjectLine', $parameters, $this, $action);
5892 if (empty($reshook)) {
5893 $this->printOriginLine($line,
'', $restrictlist,
'/core/tpl', $selectedLines);
5914 public function printOriginLine($line, $var, $restrictlist =
'', $defaulttpldir =
'/core/tpl', $selectedLines = array())
5916 global $langs,
$conf;
5919 if (!empty($line->date_start)) {
5924 if ($line->date_debut_reel) {
5928 if (!empty($line->date_end)) {
5930 $date_end = $line->date_end;
5932 $date_end = $line->date_fin_prevue;
5933 if ($line->date_fin_reel) {
5934 $date_end = $line->date_fin_reel;
5939 $this->tpl[
'id'] = $line->id;
5941 $this->tpl[
'label'] =
'';
5942 if (!empty($line->fk_parent_line)) {
5943 $this->tpl[
'label'] .=
img_picto(
'',
'rightarrow.png');
5946 if (((
int) $line->info_bits & 2) == 2) {
5948 if (property_exists($this,
'socid')) {
5949 $discount->fk_soc = $this->socid;
5950 $discount->socid = $this->socid;
5952 $this->tpl[
'label'] .= $discount->getNomUrl(0,
'discount');
5953 } elseif (!empty($line->fk_product)) {
5954 $productstatic =
new Product($this->db);
5955 $productstatic->id = $line->fk_product;
5956 $productstatic->ref = (
string) $line->ref;
5957 $productstatic->type = $line->fk_product_type;
5958 if (empty($productstatic->ref)) {
5959 $line->fetch_product();
5960 $productstatic = $line->product;
5963 $this->tpl[
'label'] .= $productstatic->getNomUrl(1);
5964 $this->tpl[
'label'] .=
' - '.(!empty($line->label) ? $line->label : $line->product_label);
5966 if ($line->product_type == 1 && (
$date_start || $date_end)) {
5970 $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"')));
5971 if (!empty($line->desc)) {
5972 $this->tpl[
'label'] .= $line->desc;
5974 $this->tpl[
'label'] .= ($line->label ?
' '.$line->label :
'');
5978 if ($line->product_type == 1 && (
$date_start || $date_end)) {
5983 if (!empty($line->desc)) {
5984 '@phan-var-force OrderLine|FactureLigne|ContratLigne|FactureFournisseurLigneRec|SupplierInvoiceLine|SupplierProposalLine $line';
5985 if ($line->desc ==
'(CREDIT_NOTE)') {
5987 $discount->fetch($line->fk_remise_except);
5988 $this->tpl[
'description'] = $langs->transnoentities(
"DiscountFromCreditNote", $discount->getNomUrl(0));
5989 } elseif ($line->desc ==
'(DEPOSIT)') {
5991 $discount->fetch($line->fk_remise_except);
5992 $this->tpl[
'description'] = $langs->transnoentities(
"DiscountFromDeposit", $discount->getNomUrl(0));
5993 } elseif ($line->desc ==
'(EXCESS RECEIVED)') {
5995 $discount->fetch($line->fk_remise_except);
5996 $this->tpl[
'description'] = $langs->transnoentities(
"DiscountFromExcessReceived", $discount->getNomUrl(0));
5997 } elseif ($line->desc ==
'(EXCESS PAID)') {
5999 $discount->fetch($line->fk_remise_except);
6000 $this->tpl[
'description'] = $langs->transnoentities(
"DiscountFromExcessPaid", $discount->getNomUrl(0));
6002 $this->tpl[
'description'] =
dol_trunc($line->desc, 60);
6005 $this->tpl[
'description'] =
' ';
6009 $this->tpl[
'vat_rate'] =
vatrate($line->tva_tx,
true);
6010 $this->tpl[
'vat_rate'] .= (((int) $line->info_bits & 1) == 1) ?
'*' :
'';
6011 if (!empty($line->vat_src_code) && !preg_match(
'/\(/', $this->tpl[
'vat_rate'])) {
6012 $this->tpl[
'vat_rate'] .=
' ('.$line->vat_src_code.
')';
6015 $this->tpl[
'price'] =
price($line->subprice);
6016 $this->tpl[
'total_ht'] =
price($line->total_ht);
6017 $this->tpl[
'multicurrency_price'] =
price($line->multicurrency_subprice);
6018 $this->tpl[
'qty'] = (((int) $line->info_bits & 2) != 2) ? $line->qty :
' ';
6020 $this->tpl[
'unit'] = $line->getLabelOfUnit(
'long', $langs);
6021 $this->tpl[
'unit_short'] = $line->getLabelOfUnit(
'short', $langs);
6024 $this->tpl[
'remise_percent'] = (((int) $line->info_bits & 2) != 2) ?
vatrate((
string) $line->remise_percent,
true) :
' ';
6027 $this->tpl[
'strike'] = 0;
6029 $this->tpl[
'strike'] = 1;
6030 } elseif (defined(
'SUBTOTALS_SPECIAL_CODE') && $line->special_code == SUBTOTALS_SPECIAL_CODE) {
6035 $this->tpl[
'strike'] = 1;
6040 $dirtpls = array_merge(
$conf->modules_parts[
'tpl'], array($defaulttpldir));
6041 foreach ($dirtpls as $module => $reldir) {
6042 if (!empty($module)) {
6045 $tpl = DOL_DOCUMENT_ROOT.$reldir.
'/originproductline.tpl.php';
6048 if (empty(
$conf->file->strict_mode)) {
6049 $res = @include $tpl;
6051 $res = include $tpl;
6078 $sql =
"INSERT INTO ".$this->db->prefix().
"element_resources (";
6079 $sql .=
"resource_id";
6080 $sql .=
", resource_type";
6081 $sql .=
", element_id";
6082 $sql .=
", element_type";
6084 $sql .=
", mandatory";
6085 $sql .=
") VALUES (";
6086 $sql .= ((int) $resource_id);
6087 $sql .=
", '".$this->db->escape($resource_type).
"'";
6088 $sql .=
", '".$this->db->escape((
string) $this->
id).
"'";
6089 $sql .=
", '".$this->db->escape($this->element).
"'";
6090 $sql .=
", '".$this->db->escape((
string) $busy).
"'";
6091 $sql .=
", '".$this->db->escape((
string) $mandatory).
"'";
6094 dol_syslog(get_class($this).
"::add_element_resource", LOG_DEBUG);
6095 if ($this->db->query($sql)) {
6097 $result = $this->call_trigger(strtoupper($this->TRIGGER_PREFIX).
'_ADD_RESOURCE', $user);
6099 $this->db->rollback();
6103 $this->db->commit();
6106 $this->error = $this->db->lasterror();
6107 $this->db->rollback();
6128 $sql =
"DELETE FROM ".$this->db->prefix().
"element_resources";
6129 $sql .=
" WHERE rowid = ".((int) $rowid);
6131 dol_syslog(get_class($this).
"::delete_resource", LOG_DEBUG);
6133 $resql = $this->db->query($sql);
6135 $this->error = $this->db->lasterror();
6136 $this->db->rollback();
6140 $result = $this->call_trigger(strtoupper($this->TRIGGER_PREFIX).
'_DELETE_RESOURCE', $user);
6142 $this->db->rollback();
6146 $this->db->commit();
6160 if (isset($this->lines) && is_array($this->lines)) {
6161 $nboflines = count($this->lines);
6162 for ($i = 0; $i < $nboflines; $i++) {
6163 if (is_object($this->lines[$i])) {
6164 $this->lines[$i] = clone $this->lines[$i];
6183 protected function commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams =
null)
6185 global
$conf, $langs, $hookmanager, $action;
6187 $srctemplatepath =
'';
6189 $parameters = array(
'modelspath' => $modelspath,
'modele' => $modele,
'outputlangs' => $outputlangs,
'hidedetails' => $hidedetails,
'hidedesc' => $hidedesc,
'hideref' => $hideref,
'moreparams' => $moreparams);
6190 $reshook = $hookmanager->executeHooks(
'commonGenerateDocument', $parameters, $this, $action);
6192 if (!empty($reshook)) {
6196 dol_syslog(
"commonGenerateDocument modele=".$modele.
" outputlangs->defaultlang=".(is_object($outputlangs) ? $outputlangs->defaultlang :
'null'));
6198 if (empty($modele)) {
6199 $this->error =
'BadValueForParameterModele';
6204 $err = error_reporting();
6206 @set_time_limit(120);
6207 error_reporting($err);
6210 $tmp = explode(
':', $modele, 2);
6211 $saved_model = $modele;
6212 if (!empty($tmp[1])) {
6214 $srctemplatepath = $tmp[1];
6216 if (!preg_match(
'/^'.preg_quote(DOL_DATA_ROOT,
'/').
'\/(ecm|doctemplates)/', $srctemplatepath)) {
6217 $this->error =
'BadDirForTemplateFile';
6226 $dirmodels = array(
'/');
6227 if (is_array(
$conf->modules_parts[
'models'])) {
6228 $dirmodels = array_merge($dirmodels,
$conf->modules_parts[
'models']);
6230 foreach ($dirmodels as $reldir) {
6231 foreach (array(
'doc',
'pdf') as $prefix) {
6232 if (in_array(get_class($this), array(
'Adherent'))) {
6234 $file = $prefix.
"_".$modele.
".class.php";
6237 $file = $prefix.
"_".$modele.
".modules.php";
6244 if (file_exists($file)) {
6246 $classname = $prefix.
'_'.$modele;
6255 if ($filefound ===
'' || $classname ===
'') {
6256 $this->error = $langs->trans(
"Error").
' Failed to load doc generator with modelpaths='.$modelspath.
' - modele='.$modele;
6257 $this->errors[] = $this->error;
6268 require_once $filefound;
6270 $obj =
new $classname($this->db);
6282 '@phan-var-force ModelePDFMember $obj';
6286 if ($obj->type ==
'odt' && empty($srctemplatepath)) {
6287 $varfortemplatedir = $obj->scandir;
6291 $listoffiles = array();
6294 $listofdir = explode(
',', $dirtoscan);
6295 foreach ($listofdir as $key => $tmpdir) {
6296 $tmpdir = trim($tmpdir);
6297 $tmpdir = preg_replace(
'/DOL_DATA_ROOT/', DOL_DATA_ROOT, $tmpdir);
6299 unset($listofdir[$key]);
6302 if (is_dir($tmpdir)) {
6303 $tmpfiles =
dol_dir_list($tmpdir,
'files', 0,
'\.od(s|t)$',
'',
'name', SORT_ASC, 0);
6304 if (count($tmpfiles)) {
6305 $listoffiles = array_merge($listoffiles, $tmpfiles);
6310 if (count($listoffiles)) {
6311 foreach ($listoffiles as $record) {
6312 $srctemplatepath = $record[
'fullname'];
6318 if (empty($srctemplatepath)) {
6319 $this->error =
'ErrorGenerationAskedForOdtTemplateWithSrcFileNotDefined';
6324 if ($obj->type ==
'odt' && !empty($srctemplatepath)) {
6326 dol_syslog(
"Failed to locate template file ".$srctemplatepath, LOG_WARNING);
6327 $this->error =
'ErrorGenerationAskedForOdtTemplateWithSrcFileNotFound';
6334 $sav_charset_output = empty($outputlangs->charset_output) ?
'' : $outputlangs->charset_output;
6337 $this->model_pdf = $saved_model;
6342 $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath,
'member', 1,
'tmp_cards');
6344 $resultwritefile = -1;
6345 dol_syslog(
"Error generating document - Provided ".get_class($this).
" to ".get_class($obj).
"::write_file()", LOG_ERR);
6349 if ($this instanceof
Don) {
6350 $resultwritefile = $obj->write_file($this, $outputlangs );
6352 $resultwritefile = -1;
6353 dol_syslog(
"Error generating document - Provided ".get_class($this).
" to Don::write_file()", LOG_ERR);
6357 '@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';
6358 $this->context[
'moreparams'] = $moreparams;
6359 $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, $hidedetails, $hidedesc, $hideref);
6361 }
catch (\Throwable $e) {
6362 $resultwritefile = -1;
6363 $this->error = $e->getMessage();
6364 dol_syslog(
"Exception in write_file() for ".get_class($this).
": ".$e->getMessage(), LOG_ERR);
6369 if ($resultwritefile > 0) {
6370 $outputlangs->charset_output = $sav_charset_output;
6373 require_once DOL_DOCUMENT_ROOT.
'/core/lib/files.lib.php';
6377 if (!empty($obj->result[
'fullpath'])) {
6378 $destfull = $obj->result[
'fullpath'];
6381 $update_main_doc_field = 0;
6382 if (!empty($obj->update_main_doc_field)) {
6383 $update_main_doc_field = 1;
6389 $this->indexFile($destfull, $update_main_doc_field);
6392 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);
6398 $this->warnings = $obj->warnings;
6402 $outputlangs->charset_output = $sav_charset_output;
6403 if (empty($this->error)) {
6404 $this->error = $obj->error;
6406 if (empty($this->errors)) {
6407 $this->errors = $obj->errors;
6409 $this->warnings = $obj->warnings;
6410 dol_syslog(
"Error generating document for ".__CLASS__.
". Error: ".$this->error, LOG_ERR);
6424 public function indexFile($destfull, $update_main_doc_field)
6426 global
$conf, $user;
6428 $upload_dir = dirname($destfull);
6429 $destfile = basename($destfull);
6430 $rel_dir = preg_replace(
'/^'.preg_quote(DOL_DATA_ROOT,
'/').
'/',
'', $upload_dir);
6432 if (!preg_match(
'/[\\/]temp[\\/]|[\\/]thumbs|\.meta$/', $rel_dir)) {
6433 $filename = basename($destfile);
6434 $rel_dir = preg_replace(
'/[\\/]$/',
'', $rel_dir);
6435 $rel_dir = preg_replace(
'/^[\\/]/',
'', $rel_dir);
6437 include_once DOL_DOCUMENT_ROOT.
'/ecm/class/ecmfiles.class.php';
6438 $ecmfile =
new EcmFiles($this->db);
6439 $result = $ecmfile->fetch(0,
'', ($rel_dir ? $rel_dir.
'/' :
'').$filename);
6442 $setsharekey =
false;
6444 !empty($this->TRIGGER_PREFIX)
6447 $setsharekey =
true;
6450 if ($this->element ==
'propal' || $this->element ==
'proposal') {
6452 $setsharekey =
true;
6455 $setsharekey =
true;
6458 if ($this->element ==
'facture' &&
getDolGlobalInt(
"INVOICE_ALLOW_EXTERNAL_DOWNLOAD")) {
6459 $setsharekey =
true;
6461 if ($this->element ==
'bank_account' &&
getDolGlobalInt(
"BANK_ACCOUNT_ALLOW_EXTERNAL_DOWNLOAD")) {
6462 $setsharekey =
true;
6464 if ($this->element ==
'contrat' &&
getDolGlobalInt(
"CONTRACT_ALLOW_EXTERNAL_DOWNLOAD")) {
6465 $setsharekey =
true;
6467 if ($this->element ==
'supplier_proposal' &&
getDolGlobalInt(
"SUPPLIER_PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD")) {
6468 $setsharekey =
true;
6470 if ($this->element ==
'order_supplier' &&
getDolGlobalInt(
"SUPPLIER_ORDER_ALLOW_EXTERNAL_DOWNLOAD")) {
6471 $setsharekey =
true;
6473 if ($this->element ==
'invoice_supplier' &&
getDolGlobalInt(
"SUPPLIER_INVOICE_ALLOW_EXTERNAL_DOWNLOAD")) {
6474 $setsharekey =
true;
6476 if ($this->element ==
'societe_rib' &&
getDolGlobalInt(
"SOCIETE_RIB_ALLOW_ONLINESIGN")) {
6477 $setsharekey =
true;
6481 if (empty($ecmfile->share)) {
6482 require_once DOL_DOCUMENT_ROOT.
'/core/lib/security2.lib.php';
6489 $ecmfile->fullpath_orig =
'';
6490 $ecmfile->gen_or_uploaded =
'generated';
6491 $ecmfile->description =
'';
6492 $ecmfile->keywords =
'';
6493 $ecmfile->src_object_type = $this->table_element;
6495 $result = $ecmfile->update($user);
6501 $ecmfile->entity =
$conf->entity;
6502 $ecmfile->filepath = $rel_dir;
6503 $ecmfile->filename = $filename;
6505 $ecmfile->fullpath_orig =
'';
6506 $ecmfile->gen_or_uploaded =
'generated';
6507 $ecmfile->description =
'';
6508 $ecmfile->keywords =
'';
6509 $ecmfile->src_object_type = $this->table_element;
6512 $result = $ecmfile->create($user);
6524 if ($update_main_doc_field && !empty($this->table_element)) {
6525 $sql =
"UPDATE ".$this->db->prefix().$this->table_element.
" SET last_main_doc = '".$this->db->escape($ecmfile->filepath.
"/".$ecmfile->filename).
"'";
6526 $sql .=
" WHERE rowid = ".((int) $this->
id);
6528 $resql = $this->db->query($sql);
6533 $this->last_main_doc = $ecmfile->filepath.
'/'.$ecmfile->filename;
6553 if (file_exists($file_osencoded)) {
6554 require_once DOL_DOCUMENT_ROOT.
'/core/lib/images.lib.php';
6557 $maxwidthsmall = $tmparraysize[
'maxwidthsmall'];
6558 $maxheightsmall = $tmparraysize[
'maxheightsmall'];
6559 $maxwidthmini = $tmparraysize[
'maxwidthmini'];
6560 $maxheightmini = $tmparraysize[
'maxheightmini'];
6565 vignette($file_osencoded, $maxwidthsmall, $maxheightsmall,
'_small', $quality);
6569 vignette($file_osencoded, $maxwidthmini, $maxheightmini,
'_mini', $quality);
6617 return GETPOST($fieldname, $type, 3);
6620 if (isset($alternatevalue)) {
6621 return $alternatevalue;
6624 $newelement = $this->element;
6625 if ($newelement ==
'facture') {
6626 $newelement =
'invoice';
6628 if ($newelement ==
'commande') {
6629 $newelement =
'order';
6631 if (empty($newelement)) {
6632 dol_syslog(
"Ask a default value using common method getDefaultCreateValueForField on an object with no property ->element defined. Return empty string.", LOG_WARNING);
6636 $keyforfieldname = strtoupper($newelement.
'_DEFAULT_'.$fieldname);
6663 if (!$this->element) {
6666 if (!($this->
id > 0)) {
6669 if (is_array($this->array_languages)) {
6673 $this->array_languages = array();
6675 $element = $this->element;
6676 if ($element ==
'categorie') {
6677 $element =
'categories';
6681 $sql =
"SELECT rowid, property, lang , value";
6682 $sql .=
" FROM ".$this->db->prefix().
"object_lang";
6683 $sql .=
" WHERE type_object = '".$this->db->escape($element).
"'";
6684 $sql .=
" AND fk_object = ".((int) $this->
id);
6686 $resql = $this->db->query($sql);
6688 $numrows = $this->db->num_rows($resql);
6691 while ($i < $numrows) {
6692 $obj = $this->db->fetch_object($resql);
6693 $key = $obj->property;
6694 $value = $obj->value;
6695 $codelang = $obj->lang;
6696 $type = $this->fields[$key][
'type'];
6699 if (preg_match(
'/date/', $type)) {
6700 $this->array_languages[$key][$codelang] = $this->db->jdate($value);
6702 $this->array_languages[$key][$codelang] = $value;
6709 $this->db->free($resql);
6732 foreach ($_POST as $postfieldkey => $postfieldvalue) {
6733 $tmparray = explode(
'-', $postfieldkey);
6734 if ($tmparray[0] !=
'field') {
6738 $element = $tmparray[1];
6739 $key = $tmparray[2];
6740 $codelang = $tmparray[3];
6743 if (!empty($onlykey) && $key != $onlykey) {
6746 if ($element != $this->element) {
6750 $key_type = $this->fields[$key][
'type'];
6753 if (isset($this->fields[$key][
'enabled'])) {
6754 $enabled = (int)
dol_eval((
string) $this->fields[$key][
'enabled'], 1, 1,
'1');
6761 if (empty($enabled)) {
6766 if (in_array($key_type, array(
'date'))) {
6770 } elseif (in_array($key_type, array(
'datetime'))) {
6774 } elseif (in_array($key_type, array(
'checkbox',
'chkbxlst'))) {
6775 $value_arr =
GETPOST($postfieldkey,
'array');
6776 if (!empty($value_arr)) {
6777 $value_key = implode(
',', $value_arr);
6781 } elseif (in_array($key_type, array(
'price',
'double'))) {
6782 $value_arr =
GETPOST($postfieldkey,
'alpha');
6785 $value_key =
GETPOST($postfieldkey);
6786 if (in_array($key_type, array(
'link')) && $value_key ==
'-1') {
6791 $this->array_languages[$key][$codelang] = $value_key;
6816 $savDisableCompute =
$conf->disable_compute;
6817 $conf->disable_compute = 1;
6819 $ret = $this->fetch(
$id);
6821 $conf->disable_compute = $savDisableCompute;
6839 global
$conf, $extrafields;
6841 if (empty($rowid)) {
6844 if (empty($rowid) && isset($this->rowid)) {
6845 $rowid = $this->rowid;
6849 if (!$this->table_element) {
6852 $this->array_options = array();
6854 if (!is_array($optionsArray)) {
6856 if (!isset($extrafields) || !is_object($extrafields)) {
6857 require_once DOL_DOCUMENT_ROOT.
'/core/class/extrafields.class.php';
6862 if (empty($extrafields->attributes[$this->table_element][
'loaded'])) {
6863 $extrafields->fetch_name_optionals_label($this->table_element);
6865 $optionsArray = (!empty($extrafields->attributes[$this->table_element][
'label']) ? $extrafields->attributes[$this->table_element][
'label'] :
null);
6867 global $extrafields;
6868 dol_syslog(
"Warning: fetch_optionals was called with param optionsArray defined when you should pass null now", LOG_WARNING);
6871 $table_element = $this->table_element;
6872 if ($table_element ==
'categorie') {
6873 $table_element =
'categories';
6877 if (is_array($optionsArray) && count($optionsArray) > 0) {
6878 $sql =
"SELECT rowid";
6879 foreach ($optionsArray as $name => $label) {
6880 if (empty($extrafields->attributes[$this->table_element][
'type'][$name]) || (!in_array($extrafields->attributes[$this->table_element][
'type'][$name], [
'separate',
'point',
'multipts',
'linestrg',
'polygon']))) {
6881 $sql .=
", ".$this->db->sanitize($name);
6884 if (!empty($extrafields->attributes[$this->table_element][
'type'][$name]) && in_array($extrafields->attributes[$this->table_element][
'type'][$name], array(
'point',
'multipts',
'linestrg',
'polygon'))) {
6886 $sql .=
", ST_AsWKT(".$this->db->sanitize($name).
") as ".$this->db->sanitize($name);
6889 $sql .=
" FROM ".$this->db->prefix().$table_element.
"_extrafields";
6890 $sql .=
" WHERE fk_object = ".((int) $rowid);
6893 $resql = $this->db->query($sql);
6895 $numrows = $this->db->num_rows($resql);
6897 $tab = $this->db->fetch_array($resql);
6898 foreach ($tab as $key => $value) {
6900 if ($key !=
'rowid' && $key !=
'tms' && $key !=
'fk_member' && !is_int($key)) {
6902 if (!empty($extrafields->attributes[$this->table_element]) && in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'date',
'datetime'))) {
6904 $this->array_options[
"options_".$key] = $this->db->jdate($value);
6906 $this->array_options[
"options_".$key] = $value;
6911 if (!empty($extrafields->attributes[$this->table_element][
'type'][$key]) && $extrafields->attributes[$this->table_element][
'type'][$key] ==
'password') {
6912 if (!empty($value) && preg_match(
'/^dolcrypt:/', $value)) {
6913 $this->array_options[
"options_".$key] =
dolDecrypt($value);
6922 if (is_array($extrafields->attributes[$this->table_element][
'label'])) {
6923 foreach ($extrafields->attributes[$this->table_element][
'label'] as $key => $val) {
6924 $this->array_options[
'options_' . $key] =
null;
6931 if (is_array($extrafields->attributes[$this->table_element][
'label'])) {
6932 foreach ($extrafields->attributes[$this->table_element][
'label'] as $key => $val) {
6933 if (!empty($extrafields->attributes[$this->table_element]) && !empty($extrafields->attributes[$this->table_element][
'computed'][$key])) {
6935 if (empty(
$conf->disable_compute)) {
6937 global $objectoffield;
6939 $this->array_options[
'options_' . $key] =
dol_eval((
string) $extrafields->attributes[$this->table_element][
'computed'][$key], 1, 0,
'2');
6945 $this->db->free($resql);
6953 $this->errors[] = $this->db->lasterror();
6974 $table_element = $this->table_element;
6975 if ($table_element ==
'categorie') {
6976 $table_element =
'categories';
6979 dol_syslog(get_class($this).
"::deleteExtraFields delete", LOG_DEBUG);
6981 $sql_del =
"DELETE FROM ".$this->db->prefix().$table_element.
"_extrafields WHERE fk_object = ".((int) $this->
id);
6983 $resql = $this->db->query($sql_del);
6985 $this->error = $this->db->lasterror();
6986 $this->db->rollback();
6989 $this->db->commit();
7006 global $langs, $extrafields, $user;
7008 if (
getDolGlobalString(
'MAIN_EXTRAFIELDS_DISABLED') || empty($this->array_options)) {
7012 if (empty($userused)) {
7019 $langs->load(
'admin');
7020 if (!isset($extrafields) || !is_object($extrafields)) {
7021 require_once DOL_DOCUMENT_ROOT.
'/core/class/extrafields.class.php';
7024 $target_extrafields = $extrafields->fetch_name_optionals_label($this->table_element);
7027 $new_array_options = array();
7028 foreach ($this->array_options as $key => $value) {
7029 if (in_array(substr($key, 8), array_keys($target_extrafields))) {
7030 $new_array_options[$key] = $value;
7031 } elseif (in_array($key, array_keys($target_extrafields))) {
7032 $new_array_options[
'options_'.$key] = $value;
7036 foreach ($new_array_options as $key => $value) {
7037 $attributeKey = substr($key, 8);
7038 $attributeType = $extrafields->attributes[$this->table_element][
'type'][$attributeKey];
7039 $attributeLabel = $langs->transnoentities($extrafields->attributes[$this->table_element][
'label'][$attributeKey]);
7040 $attributeParam = $extrafields->attributes[$this->table_element][
'param'][$attributeKey];
7041 $attributeRequired = $extrafields->attributes[$this->table_element][
'required'][$attributeKey];
7042 $attributeUnique = $extrafields->attributes[$this->table_element][
'unique'][$attributeKey];
7043 $attrfieldcomputed = $extrafields->attributes[$this->table_element][
'computed'][$attributeKey];
7044 $attributeEmptyOnClone = $extrafields->attributes[$this->table_element][
'emptyonclone'][$attributeKey];
7056 if (!empty($this->context[
'createfromclone']) && $this->context[
'createfromclone'] ==
'createfromclone' && (!empty($attributeUnique) || !empty($attributeEmptyOnClone))) {
7057 $new_array_options[$key] =
null;
7063 if (!empty($this->context[
'createproductcombination']) && $this->context[
'createproductcombination'] ==
'createproductcombination' && !empty($attributeUnique)) {
7064 $new_array_options[$key] =
null;
7069 if ($attributeRequired) {
7070 $v = $this->array_options[$key];
7072 $langs->load(
"errors");
7073 dol_syslog(
"Mandatory field '".$key.
"' is empty during create and set to required into definition of extrafields");
7074 $this->errors[] = $langs->trans(
'ErrorFieldRequired', $attributeLabel);
7079 if (!empty($attrfieldcomputed)) {
7081 global $objectoffield;
7082 $objectoffield = $this;
7083 $value =
dol_eval((
string) $attrfieldcomputed, 1, 0,
'2');
7084 dol_syslog($langs->trans(
"Extrafieldcomputed").
" on ".$attributeLabel.
"(".$value.
")", LOG_DEBUG);
7085 $new_array_options[$key] = $value;
7087 $new_array_options[$key] =
null;
7092 switch ($attributeType) {
7096 if (!is_numeric($value) && $value !=
'') {
7097 $this->errors[] = $langs->trans(
"ExtraFieldHasWrongValue", $attributeLabel);
7099 } elseif ($value ===
'') {
7100 $new_array_options[$key] =
null;
7104 if ($value ===
'' || $value ===
false || $value ===
null) {
7105 $new_array_options[$key] =
null;
7111 if (!is_numeric($value) && $value !=
'') {
7112 dol_syslog($langs->trans(
"ExtraFieldHasWrongValue").
" for ".$attributeLabel.
"(".$value.
"is not '".$attributeType.
"')", LOG_DEBUG);
7113 $this->errors[] = $langs->trans(
"ExtraFieldHasWrongValue", $attributeLabel);
7115 } elseif ($value ==
'') {
7119 $new_array_options[$key] = $value;
7129 if ($this->array_options[$key] !=
'' && is_array($extrafields->attributes[$this->table_element][
'param'][$attributeKey][
'options'])) {
7131 $tmparrays = array_keys($extrafields->attributes[$this->table_element][
'param'][$attributeKey][
'options']);
7132 $algo = reset($tmparrays);
7137 if (is_object($this->oldcopy)) {
7139 if (isset($this->oldcopy->array_options[$key]) && $this->array_options[$key] == $this->oldcopy->array_options[$key]) {
7141 if ($algo ==
'dolcrypt') {
7142 if (!preg_match(
'/^dolcrypt:/', $this->array_options[$key])) {
7143 $new_array_options[$key] =
dolEncrypt($this->array_options[$key]);
7145 $new_array_options[$key] = $this->array_options[$key];
7148 $new_array_options[$key] = $this->array_options[$key];
7152 if ($algo ==
'dolcrypt') {
7153 if (!preg_match(
'/^dolcrypt:/', $this->array_options[$key])) {
7154 $new_array_options[$key] =
dolEncrypt($this->array_options[$key]);
7156 $new_array_options[$key] = $this->array_options[$key];
7159 $new_array_options[$key] =
dol_hash($this->array_options[$key], $algo);
7165 if ($algo ==
'dolcrypt' && !preg_match(
'/^dolcrypt:/', $this->array_options[$key])) {
7166 $new_array_options[$key] =
dolEncrypt($this->array_options[$key]);
7168 $new_array_options[$key] = $this->array_options[$key];
7173 $new_array_options[$key] = $this->array_options[$key];
7176 $new_array_options[$key] = $this->array_options[$key];
7182 if (!is_numeric($this->array_options[$key]) || $this->array_options[$key] != intval($this->array_options[$key])) {
7183 $this->array_options[$key] = strtotime($this->array_options[$key]);
7185 $new_array_options[$key] = $this->db->idate($this->array_options[$key]);
7189 if (!is_numeric($this->array_options[$key]) || $this->array_options[$key] != intval($this->array_options[$key])) {
7190 $this->array_options[$key] = strtotime($this->array_options[$key]);
7192 $new_array_options[$key] = $this->db->idate($this->array_options[$key],
'gmt');
7195 $param_list = array_keys($attributeParam[
'options']);
7198 $InfoFieldList = explode(
":", $param_list[0]);
7200 if ($InfoFieldList[0] && class_exists($InfoFieldList[0])) {
7201 if ($value ==
'-1') {
7202 $new_array_options[$key] =
'';
7205 '@phan-var-force CommonObject $object';
7209 $sqlFetchObject =
"SELECT rowid FROM ".$this->db->prefix().$object->table_element;
7210 if (is_numeric($value)) {
7211 $sqlFetchObject .=
" WHERE rowid = " . (int) $value;
7213 $sqlFetchObject .=
" WHERE ref = '" . $this->db->escape($value) .
"'";
7216 $obj = $this->db->getRow($sqlFetchObject);
7222 if (is_object($obj)) {
7223 $objectId = $obj->rowid;
7230 $new_array_options[$key] = $objectId;
7232 $this->error =
"Id/Ref '".$value.
"' for object '".
$object->element.
"' not found";
7237 dol_syslog(
'Error bad setup of extrafield', LOG_WARNING);
7242 if (is_array($this->array_options[$key])) {
7243 $new_array_options[$key] = implode(
',', $this->array_options[$key]);
7245 $new_array_options[$key] = $this->array_options[$key];
7252 $sqlColumnValues = [
'fk_object' => (int) $this->
id];
7254 foreach ($new_array_options as $key => $newValue) {
7255 $attributeKey = substr($key, 8);
7256 $attributeType = $extrafields->attributes[$this->table_element][
'type'][$attributeKey];
7257 if ($attributeType ===
'separate') {
7261 $geoDataType = ExtraFields::$geoDataTypes[$attributeType] ??
null;
7263 if (! $geoDataType) {
7265 if ($newValue !=
'') {
7266 $sqlColumnValues[$attributeKey] =
"'".$this->db->escape($newValue).
"'";
7268 $sqlColumnValues[$attributeKey] =
'null';
7272 if (empty($newValue)) {
7273 $sqlColumnValues[$attributeKey] =
'null';
7276 if (preg_match(
'/error/i', $newValue)) {
7277 dol_syslog(
'Bad syntax string for '.$geoDataType[
'shortname'].
' '.$newValue.
' to generate SQL request', LOG_WARNING);
7278 $sqlColumnValues[$attributeKey] =
'null';
7287 $sqlColumnValues[$attributeKey] = $geoDataType[
'ST_Function'].
"('".$this->db->escape($newValue).
"')";
7292 $table_element = $this->table_element;
7293 if ($table_element ==
'categorie') {
7294 $table_element =
'categories';
7296 $extrafieldsTable = $this->db->prefix() . $table_element .
'_extrafields';
7298 dol_syslog(get_class($this).
"::insertExtraFields update or insert record line", LOG_DEBUG);
7300 $linealreadyfound = 0;
7301 $sql =
"SELECT COUNT(rowid) as nb FROM ".$this->db->prefix().$table_element.
"_extrafields WHERE fk_object = ".((int) $this->
id);
7302 $resql = $this->db->query($sql);
7304 $tmpobj = $this->db->fetch_object($resql);
7306 $linealreadyfound = $tmpobj->nb;
7311 if ($linealreadyfound) {
7312 array_shift($sqlColumnValues);
7313 if (empty($sqlColumnValues)) {
7319 $this->db->commit();
7322 $sqlColumnValueString = implode(
7328 array_map(
function ($key) use ($sqlColumnValues) {
7329 return "{$key} = {$sqlColumnValues[$key]}";
7330 }, array_keys($sqlColumnValues))
7332 $sql =
"UPDATE {$extrafieldsTable} SET {$sqlColumnValueString} WHERE fk_object = ".((int) $this->
id);
7335 $extrafieldsRequiredOnOtherEntities = $extrafields->attributes[$this->table_element][
'mandatoryfieldsofotherentities'] ?? array();
7336 foreach ($extrafieldsRequiredOnOtherEntities as $key => $extrafieldType) {
7337 if (isset($sqlColumnValues[$key])) {
7342 $sqlColumnValues[$key] =
"''";
7343 if (in_array($extrafieldType, array(
'int',
'double',
'price'))) {
7344 $sqlColumnValues[$key] = 0;
7347 $sqlColumns = implode(
',', array_keys($sqlColumnValues));
7348 $sqlValues = implode(
',', array_values($sqlColumnValues));
7349 $sql =
"INSERT INTO {$extrafieldsTable} ({$sqlColumns}) VALUES ({$sqlValues})";
7352 $resql = $this->db->query($sql);
7354 $this->error = $this->db->lasterror();
7359 if (!$error && !empty($this->fields[
'fk_user_modif'])) {
7360 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
7361 $sql .=
" SET fk_user_modif = ".(int) $userused->id;
7362 $sql .=
" WHERE ".(empty($this->table_rowid) ?
'rowid' : $this->db->sanitize($this->table_rowid)).
" = ".((
int)
$this->id);
7363 $this->db->query($sql);
7366 if (!$error && $trigger) {
7368 $this->context = array(
'extrafieldaddupdate' => 1);
7369 $result = $this->call_trigger($trigger, $userused);
7377 $this->db->rollback();
7380 $this->db->commit();
7398 global $langs, $user;
7400 if (empty($userused)) {
7410 if (is_array($this->array_languages)) {
7411 $new_array_languages = $this->array_languages;
7413 foreach ($new_array_languages as $key => $value) {
7414 $attributeKey = $key;
7415 $attributeType = $this->fields[$attributeKey][
'type'];
7416 $attributeLabel = $this->fields[$attributeKey][
'label'];
7421 switch ($attributeType) {
7423 if (is_array($value) || (!is_numeric($value) && $value !=
'')) {
7424 $this->errors[] = $langs->trans(
"ExtraLanguageHasWrongValue", $attributeLabel);
7426 } elseif ($value ==
'') {
7427 $new_array_languages[$key] =
null;
7432 if (!is_numeric($value) && $value !=
'') {
7433 dol_syslog($langs->trans(
"ExtraLanguageHasWrongValue").
" on ".$attributeLabel.
"(".$value.
"is not '".$attributeType.
"')", LOG_DEBUG);
7434 $this->errors[] = $langs->trans(
"ExtraLanguageHasWrongValue", $attributeLabel);
7436 } elseif ($value ==
'') {
7437 $new_array_languages[$key] =
null;
7439 $new_array_languages[$key] = $value;
7453 $table_element = $this->table_element;
7454 if ($table_element ==
'categorie') {
7455 $table_element =
'categories';
7458 dol_syslog(get_class($this).
"::insertExtraLanguages delete then insert", LOG_DEBUG);
7460 foreach ($new_array_languages as $key => $langcodearray) {
7461 foreach ($langcodearray as $langcode => $value) {
7462 $sql_del =
"DELETE FROM ".$this->db->prefix().
"object_lang";
7463 $sql_del .=
" WHERE fk_object = ".((int) $this->
id).
" AND property = '".$this->db->escape($key).
"' AND type_object = '".$this->db->escape($table_element).
"'";
7464 $sql_del .=
" AND lang = '".$this->db->escape($langcode).
"'";
7465 $this->db->query($sql_del);
7467 if ($value !==
'') {
7468 $sql =
"INSERT INTO ".$this->db->prefix().
"object_lang (fk_object, property, type_object, lang, value";
7469 $sql .=
") VALUES (".((int) $this->
id).
", '".$this->db->escape($key).
"', '".$this->db->escape($table_element).
"', '".$this->db->escape($langcode).
"', '".$this->db->escape($value).
"'";
7472 $resql = $this->db->query($sql);
7474 $this->error = $this->db->lasterror();
7482 if (!$error && $trigger) {
7484 $this->context = array(
'extralanguagesaddupdate' => 1);
7485 $result = $this->call_trigger($trigger, $userused);
7493 $this->db->rollback();
7496 $this->db->commit();
7516 global $langs, $user, $extrafields, $hookmanager;
7522 if (empty($userused)) {
7528 if (!empty($this->array_options) && isset($this->array_options[
"options_".$key])) {
7530 $langs->load(
'admin');
7531 if (!isset($extrafields) || !is_object($extrafields)) {
7532 require_once DOL_DOCUMENT_ROOT.
'/core/class/extrafields.class.php';
7535 $extrafields->fetch_name_optionals_label($this->table_element);
7536 if (!isset($extrafields->attributes[$this->table_element][
'type'][$key])) {
7540 $value = $this->array_options[
"options_".$key];
7542 $attributeKey = $key;
7543 $attributeType = $extrafields->attributes[$this->table_element][
'type'][$attributeKey];
7544 $attributeLabel = $extrafields->attributes[$this->table_element][
'label'][$attributeKey];
7545 $attributeParam = $extrafields->attributes[$this->table_element][
'param'][$attributeKey];
7546 $attributeRequired = $extrafields->attributes[$this->table_element][
'required'][$attributeKey];
7547 $attributeUnique = $extrafields->attributes[$this->table_element][
'unique'][$attributeKey];
7548 $attrfieldcomputed = $extrafields->attributes[$this->table_element][
'computed'][$attributeKey];
7552 if ($attributeRequired) {
7553 $mandatorypb =
false;
7554 if ($attributeType ==
'link' && $this->array_options[
"options_".$key] ==
'-1') {
7555 $mandatorypb =
true;
7557 if ($this->array_options[
"options_".$key] ===
'') {
7558 $mandatorypb =
true;
7561 $langs->load(
"errors");
7562 dol_syslog(
"Mandatory field 'options_".$key.
"' is empty during update and set to required into definition of extrafields");
7563 $this->errors[] = $langs->trans(
'ErrorFieldRequired', $attributeLabel);
7569 $new_array_options = $this->array_options;
7573 if (!empty($attrfieldcomputed)) {
7575 global $objectoffield;
7576 $objectoffield = $this;
7577 $value =
dol_eval((
string) $attrfieldcomputed, 1, 0,
'2');
7578 dol_syslog($langs->trans(
"Extrafieldcomputed").
" on ".$attributeLabel.
"(".$value.
")", LOG_DEBUG);
7580 $new_array_options[
"options_".$key] = $value;
7582 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7584 $new_array_options[
"options_".$key] =
null;
7586 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7590 switch ($attributeType) {
7592 if (!is_numeric($value) && $value !=
'') {
7593 $this->errors[] = $langs->trans(
"ExtraFieldHasWrongValue", $attributeLabel);
7595 } elseif ($value ===
'') {
7596 $new_array_options[
"options_".$key] =
null;
7598 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7604 if (!is_numeric($value) && $value !=
'') {
7605 dol_syslog($langs->trans(
"ExtraFieldHasWrongValue").
" on ".$attributeLabel.
"(".$value.
"is not '".$attributeType.
"')", LOG_DEBUG);
7606 $this->errors[] = $langs->trans(
"ExtraFieldHasWrongValue", $attributeLabel);
7608 } elseif ($value ===
'') {
7612 $new_array_options[
"options_".$key] = $value;
7614 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7626 if ($this->array_options[
"options_".$key] !=
'' && is_array($extrafields->attributes[$this->table_element][
'param'][$attributeKey][
'options'])) {
7628 $tmparrays = array_keys($extrafields->attributes[$this->table_element][
'param'][$attributeKey][
'options']);
7629 $algo = reset($tmparrays);
7635 if (is_object($this->oldcopy)) {
7637 if (isset($this->oldcopy->array_options[
"options_".$key]) && $this->array_options[
"options_".$key] == $this->oldcopy->array_options[
"options_".$key]) {
7638 if ($algo ==
'dolcrypt') {
7639 if (!preg_match(
'/^dolcrypt:/', $this->array_options[
"options_".$key])) {
7640 $new_array_options[
"options_".$key] =
dolEncrypt($this->array_options[
"options_".$key]);
7642 $new_array_options[
"options_".$key] = $this->array_options[
"options_".$key];
7645 $new_array_options[
"options_".$key] = $this->array_options[
"options_".$key];
7648 if ($algo ==
'dolcrypt') {
7649 if (!preg_match(
'/^dolcrypt:/', $this->array_options[
"options_".$key])) {
7650 $new_array_options[
"options_".$key] =
dolEncrypt($this->array_options[
"options_".$key]);
7652 $new_array_options[
"options_".$key] = $this->array_options[
"options_".$key];
7655 $new_array_options[
"options_".$key] =
dol_hash($this->array_options[
"options_".$key], $algo);
7659 if ($algo ==
'dolcrypt' && !preg_match(
'/^dolcrypt:/', $this->array_options[
"options_".$key])) {
7660 $new_array_options[
"options_".$key] =
dolEncrypt($this->array_options[
"options_".$key]);
7662 $new_array_options[
"options_".$key] = $this->array_options[
"options_".$key];
7667 $new_array_options[
"options_".$key] = $this->array_options[
"options_".$key];
7670 $new_array_options[
"options_".$key] = $this->array_options[
"options_".$key];
7673 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7677 if (empty($this->array_options[
"options_".$key])) {
7678 $new_array_options[
"options_".$key] =
null;
7680 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7682 $new_array_options[
"options_".$key] = $this->db->idate($this->array_options[
"options_".$key]);
7686 if (empty($this->array_options[
"options_".$key])) {
7687 $new_array_options[
"options_".$key] =
null;
7689 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7691 $new_array_options[
"options_".$key] = $this->db->idate($this->array_options[
"options_".$key],
'gmt');
7695 if (empty($this->array_options[
"options_".$key])) {
7696 $new_array_options[
"options_".$key] =
null;
7698 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7702 if ($this->array_options[
"options_".$key] ===
'') {
7703 $new_array_options[
"options_".$key] =
null;
7705 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7739 $new_array_options = array();
7740 if (is_array($this->array_options[
"options_".$key])) {
7741 $new_array_options[
"options_".$key] = implode(
',', $this->array_options[
"options_".$key]);
7743 $new_array_options[
"options_".$key] = $this->array_options[
"options_".$key];
7746 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7752 $linealreadyfound = 0;
7755 $table_element = $this->table_element;
7756 if ($table_element ==
'categorie') {
7757 $table_element =
'categories';
7760 $sql =
"SELECT COUNT(rowid) as nb FROM ".$this->db->prefix().$table_element.
"_extrafields WHERE fk_object = ".((int) $this->
id);
7761 $resql = $this->db->query($sql);
7763 $tmpobj = $this->db->fetch_object($resql);
7765 $linealreadyfound = $tmpobj->nb;
7770 if ($linealreadyfound) {
7771 $sanitizedGeoDataType = ExtraFields::$geoDataTypes[$attributeType] ??
null;
7772 if ($this->array_options[
"options_".$key] ===
null) {
7773 $sql =
"UPDATE ".$this->db->prefix().$this->db->sanitize($table_element).
"_extrafields";
7774 $sql .=
" SET ".$this->db->sanitize($key).
" = null";
7775 } elseif (!empty($sanitizedGeoDataType[
'ST_Function'])) {
7776 $sql =
"UPDATE ".$this->db->prefix().$this->db->sanitize($table_element).
"_extrafields";
7777 $sql .=
" SET ".$this->db->sanitize($key).
" = ".$this->db->sanitize($sanitizedGeoDataType[
'ST_Function']).
"('".$this->db->escape($this->array_options[
"options_".$key]).
"')";
7780 $sql =
"UPDATE ".$this->db->prefix().$this->db->sanitize($table_element).
"_extrafields";
7781 $sql .=
" SET ".$this->db->sanitize($key).
" = '".$this->db->escape($new_array_options[
"options_".$key]).
"'";
7783 $sql .=
" WHERE fk_object = ".((int) $this->
id);
7785 $resql = $this->db->query($sql);
7788 $this->error = $this->db->lasterror();
7791 $result = $this->insertExtraFields(
'', $user);
7798 if (!$error && !empty($this->fields[
'fk_user_modif'])) {
7799 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
7800 $sql .=
" SET fk_user_modif = ".(int) $userused->id;
7801 $sql .=
" WHERE ".(empty($this->table_rowid) ?
'rowid' : $this->db->sanitize($this->table_rowid)).
" = ".((
int)
$this->id);
7802 $this->db->query($sql);
7806 $parameters = array(
'key' => $key);
7808 $reshook = $hookmanager->executeHooks(
'updateExtraFieldBeforeCommit', $parameters, $this, $action);
7814 if (!$error && $trigger) {
7816 $this->context = array(
'extrafieldupdate' => 1);
7817 $result = $this->call_trigger($trigger, $userused);
7825 dol_syslog(__METHOD__.$this->error, LOG_ERR);
7826 $this->db->rollback();
7829 $this->db->commit();
7845 return $this->array_options[
'options_'.$key] ??
null;
7857 $this->array_options[
'options_'.$key] = $value;
7874 if (empty($userused)) {
7902 public function showInputField($val, $key, $value, $moreparam =
'', $keysuffix =
'', $keyprefix =
'', $morecss = 0, $nonewbutton = 0)
7904 global
$conf, $langs, $form;
7909 if (!is_object($form)) {
7910 require_once DOL_DOCUMENT_ROOT.
'/core/class/html.form.class.php';
7911 $form =
new Form($this->db);
7914 if (!empty($this->fields)) {
7915 $val = $this->fields[$key];
7919 $fieldValidationErrorMsg =
'';
7920 $validationClass =
'';
7921 $fieldValidationErrorMsg = $this->getFieldError($key);
7922 if (!empty($fieldValidationErrorMsg)) {
7923 $validationClass =
' --error';
7925 $validationClass =
' --success';
7933 $param[
'options'] = array();
7936 $size = !empty($this->fields[$key][
'size']) ? $this->fields[$key][
'size'] : 0;
7938 if (preg_match(
'/^(integer|link):(.*):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
7939 $param[
'options'] = array($reg[2].
':'.$reg[3].
':'.$reg[4].
':'.$reg[5] =>
'N');
7941 } elseif (preg_match(
'/^(integer|link):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
7942 $param[
'options'] = array($reg[2].
':'.$reg[3].
':'.$reg[4] =>
'N');
7944 } elseif (preg_match(
'/^(integer|link):(.*):(.*)/i', $val[
'type'], $reg)) {
7945 $param[
'options'] = array($reg[2].
':'.$reg[3] =>
'N');
7947 } elseif (preg_match(
'/^(sellist):(.*):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
7948 $param[
'options'] = array($reg[2].
':'.$reg[3].
':'.$reg[4].
':'.$reg[5] =>
'N');
7950 } elseif (preg_match(
'/^(sellist):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
7951 $param[
'options'] = array($reg[2].
':'.$reg[3].
':'.$reg[4] =>
'N');
7953 } elseif (preg_match(
'/^(sellist):(.*):(.*)/i', $val[
'type'], $reg)) {
7954 $param[
'options'] = array($reg[2].
':'.$reg[3] =>
'N');
7956 } elseif (preg_match(
'/^chkbxlst:(.*)/i', $val[
'type'], $reg)) {
7957 $param[
'options'] = array($reg[1] =>
'N');
7959 } elseif (preg_match(
'/varchar\((\d+)\)/', $val[
'type'], $reg)) {
7960 $param[
'options'] = array();
7963 } elseif (preg_match(
'/varchar/', $val[
'type'])) {
7964 $param[
'options'] = array();
7966 } elseif (preg_match(
'/stars\((\d+)\)/', $val[
'type'], $reg)) {
7967 $param[
'options'] = array();
7971 $param[
'options'] = array();
7972 $type = $this->fields[$key][
'type'];
7977 if (!empty($this->fields[$key][
'arrayofkeyval']) && is_array($this->fields[$key][
'arrayofkeyval'])) {
7978 $param[
'options'] = $this->fields[$key][
'arrayofkeyval'];
7980 if (empty($this->fields[$key][
'multiinput'])) {
7981 $type = (($this->fields[$key][
'type'] ==
'checkbox') ? $this->fields[$key][
'type'] :
'select');
7985 $label = $this->fields[$key][
'label'];
7988 $default = (!empty($this->fields[$key][
'default']) ? $this->fields[$key][
'default'] :
'');
7990 $computed = (!empty($this->fields[$key][
'computed']) ? $this->fields[$key][
'computed'] :
'');
7992 $unique = (!empty($this->fields[$key][
'unique']) ? $this->fields[$key][
'unique'] : 0);
7994 $required = (!empty($this->fields[$key][
'required']) ? $this->fields[$key][
'required'] : 0);
7996 $autofocusoncreate = (!empty($this->fields[$key][
'autofocusoncreate']) ? $this->fields[$key][
'autofocusoncreate'] : 0);
7998 $placeholder = (!empty($this->fields[$key][
'placeholder']) ? $this->fields[$key][
'placeholder'] : 0);
8001 $langfile = (!empty($this->fields[$key][
'langfile']) ? $this->fields[$key][
'langfile'] :
'');
8003 $list = (!empty($this->fields[$key][
'list']) ? $this->fields[$key][
'list'] : 0);
8004 $hidden = (in_array(abs($this->fields[$key][
'visible']), array(0, 2)) ? 1 : 0);
8009 if (!preg_match(
'/^search_/', $keyprefix)) {
8010 return '<span class="opacitymedium">'.$langs->trans(
"AutomaticallyCalculated").
'</span>';
8017 if (empty($morecss) && !empty($val[
'css'])) {
8018 $morecss = $val[
'css'];
8019 } elseif (empty($morecss)) {
8020 if ($type ==
'date') {
8021 $morecss =
'minwidth100imp';
8022 } elseif ($type ==
'datetime' || $type ==
'link') {
8023 $morecss =
'minwidth200imp';
8024 } elseif (in_array($type, array(
'int',
'integer',
'price')) || preg_match(
'/^double(\([0-9],[0-9]\)){0,1}/', (
string) $type)) {
8025 $morecss =
'maxwidth75';
8026 } elseif ($type ==
'url') {
8027 $morecss =
'minwidth400';
8028 } elseif ($type ==
'boolean') {
8031 if (is_numeric($size) && round((
float) $size) < 12) {
8032 $morecss =
'minwidth100';
8033 } elseif (is_numeric($size) && round((
float) $size) <= 48) {
8034 $morecss =
'minwidth200';
8036 $morecss =
'minwidth400';
8042 if (!empty($validationClass)) {
8043 $morecss .= $validationClass;
8046 if (in_array($type, array(
'date'))) {
8047 $tmp = explode(
',', $size);
8052 if (!$required && $value ==
'') {
8057 $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required,
'', 1, (($keyprefix !=
'search_' && $keyprefix !=
'search_options_') ? 1 : 0), 0, 1);
8058 } elseif (in_array($type, array(
'datetime'))) {
8059 $tmp = explode(
',', $size);
8064 if (!$required && $value ==
'') {
8069 $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required,
'', 1, (($keyprefix !=
'search_' && $keyprefix !=
'search_options_') ? 1 : 0), 0, 1,
'',
'',
'', 1,
'',
'',
'tzuserrel');
8070 } elseif (in_array($type, array(
'duration'))) {
8071 $out = $form->select_duration($keyprefix.$key.$keysuffix, $value, 0,
'text', 0, 1);
8072 } elseif (in_array($type, array(
'int',
'integer'))) {
8073 $tmp = explode(
',', $size);
8075 $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' :
'').
'>';
8076 } elseif (in_array($type, array(
'real'))) {
8077 $out =
'<input type="text" class="flat '.$morecss.
'" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.
dol_escape_htmltag($value).
'"'.($moreparam ? $moreparam :
'').($autofocusoncreate ?
' autofocus' :
'').
'>';
8078 } elseif (preg_match(
'/varchar/', (
string) $type)) {
8079 $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' :
'').
'>';
8080 } elseif (in_array($type, array(
'email',
'mail',
'phone',
'url',
'ip'))) {
8081 $out =
'<input type="text" class="flat '.$morecss.
'" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.
dol_escape_htmltag($value).
'" '.($moreparam ? $moreparam :
'').($autofocusoncreate ?
' autofocus' :
'').
'>';
8082 } elseif (preg_match(
'/^text/', (
string) $type)) {
8083 if (!preg_match(
'/search_/', $keyprefix)) {
8084 if (!empty($param[
'options'])) {
8087 $out .= $form->selectarray($keyprefix.$key.$keysuffix.
"_multiinput", $param[
'options'],
'', 1, 0, 0,
"flat maxwidthonphone".$morecss);
8088 $out .=
'<input id="'.$keyprefix.$key.$keysuffix.
'_multiinputadd" type="button" class="button" value="'.$langs->trans(
"Add").
'">';
8091 function handlemultiinputdisabling(htmlname){
8092 console.log("We handle the disabling of used options for "+htmlname+"_multiinput");
8093 multiinput = $("#"+htmlname+"_multiinput");
8094 multiinput.find("option").each(function(){
8095 tmpval = $("#"+htmlname).val();
8096 tmpvalarray = tmpval.split("\n");
8097 valtotest = $(this).val();
8098 if(tmpvalarray.includes(valtotest)){
8099 $(this).prop("disabled",true);
8101 if($(this).prop("disabled") == true){
8102 console.log(valtotest)
8103 $(this).prop("disabled", false);
8109 $(document).ready(function () {
8110 $("#'.$keyprefix.$key.$keysuffix.
'_multiinputadd").on("click",function() {
8111 tmpval = $("#'.$keyprefix.$key.$keysuffix.
'").val();
8112 tmpvalarray = tmpval.split(",");
8113 valtotest = $("#'.$keyprefix.$key.$keysuffix.
'_multiinput").val();
8114 if(valtotest != -1 && !tmpvalarray.includes(valtotest)){
8115 console.log("We add the selected value to the text area '.$keyprefix.$key.$keysuffix.
'");
8119 tmpval = tmpval + "\n" + valtotest;
8121 $("#'.$keyprefix.$key.$keysuffix.
'").val(tmpval);
8122 handlemultiinputdisabling("'.$keyprefix.$key.$keysuffix.
'");
8123 $("#'.$keyprefix.$key.$keysuffix.
'_multiinput").val(-1);
8125 console.log("We add nothing the text area '.$keyprefix.$key.$keysuffix.
'");
8128 $("#'.$keyprefix.$key.$keysuffix.
'").on("change",function(){
8129 handlemultiinputdisabling("'.$keyprefix.$key.$keysuffix.
'");
8131 handlemultiinputdisabling("'.$keyprefix.$key.$keysuffix.
'");
8133 $out .=
"</script>";
8134 $value = str_replace(
',',
"\n", $value);
8136 require_once DOL_DOCUMENT_ROOT.
'/core/class/doleditor.class.php';
8137 $doleditor =
new DolEditor($keyprefix.$key.$keysuffix, $value,
'', 200,
'dolibarr_notes',
'In',
false,
false,
false, ROWS_5,
'90%');
8138 $out .= (
string) $doleditor->Create(1,
'',
true,
'',
'',
'', $morecss);
8140 $out =
'<input type="text" class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.
dol_escape_htmltag($value).
'" '.($moreparam ? $moreparam :
'').
'>';
8142 } elseif (preg_match(
'/^html/', (
string) $type)) {
8143 if (!preg_match(
'/search_/', $keyprefix)) {
8144 require_once DOL_DOCUMENT_ROOT.
'/core/class/doleditor.class.php';
8145 $doleditor =
new DolEditor($keyprefix.$key.$keysuffix, $value,
'', 200,
'dolibarr_notes',
'In',
false,
false,
isModEnabled(
'fckeditor') &&
getDolGlobalInt(
'FCKEDITOR_ENABLE_SOCIETE'), ROWS_5,
'90%');
8146 $out = (
string) $doleditor->Create(1,
'',
true,
'',
'', $moreparam, $morecss);
8148 $out =
'<input type="text" class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.
dol_escape_htmltag($value).
'" '.($moreparam ? $moreparam :
'').
'>';
8150 } elseif ($type ==
'boolean') {
8152 if (!empty($value)) {
8153 $checked =
' checked value="1" ';
8155 $checked =
' value="1" ';
8157 $out =
'<input type="checkbox" class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" '.$checked.
' '.($moreparam ? $moreparam :
'').
'>';
8158 } elseif ($type ==
'price') {
8159 if (!empty($value)) {
8160 $value =
price($value);
8162 $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>';
8163 } elseif ($type ==
'stars') {
8164 $out =
'<input type="hidden" class="flat '.$morecss.
'" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.
dol_escape_htmltag($value).
'"'.($moreparam ? $moreparam :
'').($autofocusoncreate ?
' autofocus' :
'').
'>';
8165 $out .=
'<div class="star-selection" id="'.$keyprefix.$key.$keysuffix.
'_selection">';
8167 while ($i <= $size) {
8168 $out .=
'<span class="star" data-value="'.$i.
'">'.
img_picto(
'',
'fontawesome_star_fas').
'</span>';
8173 jQuery(function($) { /* commonobject.class.php 1 */
8174 let container = $("#'.$keyprefix.$key.$keysuffix.
'_selection");
8175 let selectedStars = parseInt($("#'.$keyprefix.$key.$keysuffix.
'").val()) || 0;
8176 container.find(".star").each(function() {
8177 $(this).toggleClass("active", $(this).data("value") <= selectedStars);
8179 container.find(".star").on("mouseover", function() {
8180 let selectedStar = $(this).data("value");
8181 container.find(".star").each(function() {
8182 $(this).toggleClass("active", $(this).data("value") <= selectedStar);
8185 container.on("mouseout", function() {
8186 container.find(".star").each(function() {
8187 $(this).toggleClass("active", $(this).data("value") <= selectedStars);
8190 container.find(".star").off("click").on("click", function() {
8191 selectedStars = $(this).data("value");
8192 if (selectedStars === 1 && $("#'.$keyprefix.$key.$keysuffix.
'").val() == 1) {
8195 $("#'.$keyprefix.$key.$keysuffix.
'").val(selectedStars);
8196 container.find(".star").each(function() {
8197 $(this).toggleClass("active", $(this).data("value") <= selectedStars);
8202 } elseif (preg_match(
'/^double(\([0-9],[0-9]\)){0,1}/', (
string) $type)) {
8203 if (!empty($value)) {
8204 $value =
price($value);
8206 $out =
'<input type="text" class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.$value.
'" '.($moreparam ? $moreparam :
'').
'> ';
8207 } elseif ($type ==
'select') {
8210 include_once DOL_DOCUMENT_ROOT.
'/core/lib/ajax.lib.php';
8211 $out .=
ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
8217 foreach ($param[
'options'] as $keyb => $valb) {
8218 if ((
string) $keyb ==
'') {
8221 if (strpos($valb,
"|") !==
false) {
8222 list($valb, $parent) = explode(
'|', $valb);
8225 $tmpselect .=
'<option value="'.$keyb.
'"';
8226 $tmpselect .= (((
string) $value == (
string) $keyb) ?
' selected' :
'');
8227 if (!empty($parent)) {
8230 $tmpselect .= (!empty($parent) ?
' parent="'.$parent.
'"' :
'');
8231 $tmpselect .=
'>'.$langs->trans($valb).
'</option>';
8234 $out .=
'<select class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" '.($moreparam ? $moreparam :
'').
'>';
8235 if ((!isset($this->fields[$key][
'default'])) || empty($this->fields[$key][
'notnull']) || ($this->fields[$key][
'notnull'] != 1) || $nbchoice >= 2) {
8236 $out .=
'<option value="0"> </option>';
8239 $out .=
'</select>';
8240 } elseif ($type ==
'sellist') {
8243 include_once DOL_DOCUMENT_ROOT.
'/core/lib/ajax.lib.php';
8244 $out .=
ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
8247 $out .=
'<select class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" '.($moreparam ? $moreparam :
'').
'>';
8248 if (is_array($param[
'options'])) {
8249 $tmpparamoptions = array_keys($param[
'options']);
8250 $paramoptions = preg_split(
'/[\r\n]+/', $tmpparamoptions[0]);
8252 $InfoFieldList = explode(
":", $paramoptions[0], 5);
8264 if (! empty($InfoFieldList[4])) {
8266 $parenthesisopen = 0;
8267 while (substr($InfoFieldList[4], $pos, 1) !==
'' && ($parenthesisopen || $pos == 0 || substr($InfoFieldList[4], $pos, 1) !=
':')) {
8268 if (substr($InfoFieldList[4], $pos, 1) ==
'(') {
8271 if (substr($InfoFieldList[4], $pos, 1) ==
')') {
8276 $tmpbefore = substr($InfoFieldList[4], 0, $pos);
8277 $tmpafter = substr($InfoFieldList[4], $pos + 1);
8279 $InfoFieldList[4] = $tmpbefore;
8280 if ($tmpafter !==
'') {
8281 $InfoFieldList = array_merge($InfoFieldList, explode(
':', $tmpafter));
8287 if (preg_match(
'/^\(?([a-z0-9]+)([=<>]+)(\d+)\)?$/i', $InfoFieldList[4], $reg)) {
8288 $InfoFieldList[4] =
'('.$reg[1].
':'.$reg[2].
':'.$reg[3].
')';
8299 $keyList = (empty($InfoFieldList[2]) ?
'rowid' : $InfoFieldList[2].
' as rowid');
8301 if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
8302 if (strpos($InfoFieldList[4],
'extra.') !==
false) {
8303 $keyList =
'main.'.$InfoFieldList[2].
' as rowid';
8305 $keyList = $InfoFieldList[2].
' as rowid';
8308 if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
8309 list($parentName, $parentField) = explode(
'|', $InfoFieldList[3]);
8310 if (!empty($InfoFieldList[4]) && strpos($InfoFieldList[4],
'extra.') !==
false) {
8311 $keyList .=
', main.'.$parentField;
8313 $keyList .=
', '.$parentField;
8317 $filter_categorie =
false;
8318 if (count($InfoFieldList) > 5) {
8319 if ($InfoFieldList[0] ==
'categorie') {
8320 $filter_categorie =
true;
8324 if (!$filter_categorie) {
8325 $fields_label = isset($InfoFieldList[1]) ? explode(
'|', $InfoFieldList[1]) : array();
8326 if (!empty($fields_label)) {
8328 $keyList .= implode(
', ', $fields_label);
8332 $sql =
"SELECT " . $this->db->sanitize($keyList, 0, 0, 1);
8333 $sql .=
" FROM " . $this->db->prefix() . $this->db->sanitize($InfoFieldList[0]);
8335 if (!empty($InfoFieldList[4])) {
8337 if (strpos($InfoFieldList[4],
'$SEL$') !==
false) {
8338 $InfoFieldList[4] = str_replace(
'$SEL$',
'SELECT', $InfoFieldList[4]);
8342 if (strpos($InfoFieldList[4],
'$ID$') !==
false && !empty($objectid)) {
8343 $InfoFieldList[4] = str_replace(
'$ID$', (
string) $objectid, $InfoFieldList[4]);
8345 $InfoFieldList[4] = str_replace(
'$ID$',
'0', $InfoFieldList[4]);
8350 if (strpos($InfoFieldList[4],
'extra') !==
false) {
8351 $sql .=
" as main, " . $this->db->sanitize($this->db->prefix() . $InfoFieldList[0]) .
"_extrafields as extra";
8352 $sqlwhere .=
" WHERE extra.fk_object = main." . $this->db->sanitize($InfoFieldList[2]);
8358 $sqlwhere .=
' WHERE 1=1';
8375 if (in_array($InfoFieldList[0], array(
'tablewithentity'))) {
8376 $sqlwhere .=
" AND entity = " . ((int)
$conf->entity);
8381 if (isset($InfoFieldList[7]) && preg_match(
'/^[a-z0-9_\-,]+$/i', $InfoFieldList[7])) {
8382 $sql .=
" ORDER BY ".$this->db->sanitize($InfoFieldList[7]);
8384 $sql .=
" ORDER BY ".$this->db->sanitize(implode(
', ', $fields_label));
8386 $sql .=
' LIMIT ' .
getDolGlobalInt(
'MAIN_EXTRAFIELDS_LIMIT_SELLIST_SQL', 1000);
8389 dol_syslog(get_class($this) .
'::showInputField type=sellist', LOG_DEBUG);
8390 $resql = $this->db->query($sql);
8392 $out .=
'<option value="0"> </option>';
8393 $num = $this->db->num_rows($resql);
8397 $obj = $this->db->fetch_object($resql);
8401 $fields_label = explode(
'|', $InfoFieldList[1]);
8402 if (count($fields_label) > 1) {
8404 foreach ($fields_label as $field_toshow) {
8405 $labeltoshow .= $obj->$field_toshow .
' ';
8408 $labeltoshow = $obj->{$InfoFieldList[1]};
8410 $labeltoshow =
dol_trunc($labeltoshow, 45);
8412 if ($value == $obj->rowid) {
8413 foreach ($fields_label as $field_toshow) {
8414 $translabel = $langs->trans($obj->$field_toshow);
8415 if ($translabel != $obj->$field_toshow) {
8416 $labeltoshow =
dol_trunc($translabel) .
' ';
8418 $labeltoshow =
dol_trunc($obj->$field_toshow) .
' ';
8421 $out .=
'<option value="' . $obj->rowid .
'" selected>' . $labeltoshow .
'</option>';
8424 $translabel = $langs->trans($obj->{$InfoFieldList[1]});
8425 if ($translabel != $obj->{$InfoFieldList[1]}) {
8426 $labeltoshow =
dol_trunc($translabel, 18);
8428 $labeltoshow =
dol_trunc($obj->{$InfoFieldList[1]});
8431 if (empty($labeltoshow)) {
8432 $labeltoshow =
'(not defined)';
8434 if ($value == $obj->rowid) {
8435 $out .=
'<option value="' . $obj->rowid .
'" selected>' . $labeltoshow .
'</option>';
8438 if (!empty($InfoFieldList[3]) && $parentField) {
8439 $parent = $parentName .
':' . $obj->{$parentField};
8443 $out .=
'<option value="' . $obj->rowid .
'"';
8444 $out .= ($value == $obj->rowid ?
' selected' :
'');
8445 $out .= (!empty($parent) ?
' parent="' . $parent .
'"' :
'');
8446 $out .=
'>' . $labeltoshow .
'</option>';
8451 $this->db->free($resql);
8453 print
'Error in request ' . $sql .
' ' . $this->db->lasterror() .
'. Check setup of extra parameters.<br>';
8456 require_once DOL_DOCUMENT_ROOT.
'/categories/class/categorie.class.php';
8457 $categcode = $InfoFieldList[5];
8458 if (is_numeric($categcode)) {
8459 $tmpcategory =
new Categorie($this->db);
8460 $MAP_ID_TO_CODE = array_flip($tmpcategory->MAP_ID);
8461 $categcode = $MAP_ID_TO_CODE[(int) $categcode];
8464 $data = $form->select_all_categories($categcode,
'',
'parent', 64, $InfoFieldList[6], 1, 1);
8465 $out .=
'<option value="0"> </option>';
8466 foreach ($data as $data_key => $data_value) {
8467 $out .=
'<option value="' . $data_key .
'"';
8468 $out .= ($value == $data_key ?
' selected' :
'');
8469 $out .=
'>' . $data_value .
'</option>';
8473 $out .=
'</select>';
8474 } elseif ($type ==
'checkbox') {
8475 $value_arr = explode(
',', $value);
8476 $out = $form->multiselectarray($keyprefix.$key.$keysuffix, (empty($param[
'options']) ?
null : $param[
'options']), $value_arr, 0, 0, $morecss, 0,
'100%');
8477 } elseif ($type ==
'radio') {
8479 foreach ($param[
'options'] as $keyopt => $valopt) {
8480 $out .=
'<input class="flat '.$morecss.
'" type="radio" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" '.($moreparam ? $moreparam :
'');
8481 $out .=
' value="'.$keyopt.
'"';
8482 $out .=
' id="'.$keyprefix.$key.$keysuffix.
'_'.$keyopt.
'"';
8483 $out .= ($value == $keyopt ?
'checked' :
'');
8484 $out .=
'/><label for="'.$keyprefix.$key.$keysuffix.
'_'.$keyopt.
'">'.$valopt.
'</label><br>';
8486 } elseif ($type ==
'chkbxlst') {
8487 if (is_array($value)) {
8488 $value_arr = $value;
8490 $value_arr = explode(
',', $value);
8493 if (is_array($param[
'options'])) {
8494 $tmpparamoptions = array_keys($param[
'options']);
8495 $paramoptions = preg_split(
'/[\r\n]+/', $tmpparamoptions[0]);
8497 $InfoFieldList = explode(
":", $paramoptions[0], 5);
8509 if (! empty($InfoFieldList[4])) {
8511 $parenthesisopen = 0;
8512 while (substr($InfoFieldList[4], $pos, 1) !==
'' && ($parenthesisopen || $pos == 0 || substr($InfoFieldList[4], $pos, 1) !=
':')) {
8513 if (substr($InfoFieldList[4], $pos, 1) ==
'(') {
8516 if (substr($InfoFieldList[4], $pos, 1) ==
')') {
8521 $tmpbefore = substr($InfoFieldList[4], 0, $pos);
8522 $tmpafter = substr($InfoFieldList[4], $pos + 1);
8524 $InfoFieldList[4] = $tmpbefore;
8525 if ($tmpafter !==
'') {
8526 $InfoFieldList = array_merge($InfoFieldList, explode(
':', $tmpafter));
8531 if (preg_match(
'/^\(?([a-z0-9]+)([=<>]+)(\d+)\)?$/i', $InfoFieldList[4], $reg)) {
8532 $InfoFieldList[4] =
'('.$reg[1].
':'.$reg[2].
':'.$reg[3].
')';
8540 '@phan-var-force array{0:string,1:string,2:string,3:string,3:string,5:string,6:string} $InfoFieldList';
8545 $keyList = (empty($InfoFieldList[2]) ?
'rowid' : $InfoFieldList[2].
' as rowid');
8547 if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
8548 if (strpos($InfoFieldList[4],
'extra.') !==
false) {
8549 $keyList =
'main.'.$InfoFieldList[2].
' as rowid';
8551 $keyList = $InfoFieldList[2].
' as rowid';
8554 if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
8555 list($parentName, $parentField) = explode(
'|', $InfoFieldList[3]);
8556 if (!empty($InfoFieldList[4]) && strpos($InfoFieldList[4],
'extra.') !==
false) {
8557 $keyList .=
', main.'.$parentField;
8559 $keyList .=
', '.$parentField;
8563 $filter_categorie =
false;
8564 if (count($InfoFieldList) > 5) {
8565 if ($InfoFieldList[0] ==
'categorie') {
8566 $filter_categorie =
true;
8571 if (!$filter_categorie) {
8572 $fields_label = explode(
'|', $InfoFieldList[1]);
8573 if (is_array($fields_label)) {
8575 $keyList .= implode(
', ', $fields_label);
8579 $sql =
"SELECT " . $this->db->sanitize($keyList, 0, 0, 1);
8580 $sql .=
' FROM ' . $this->db->prefix() . $this->db->sanitize($InfoFieldList[0]);
8582 if (!empty($InfoFieldList[4])) {
8584 if (strpos($InfoFieldList[4],
'$SEL$') !==
false) {
8585 $InfoFieldList[4] = str_replace(
'$SEL$',
'SELECT', $InfoFieldList[4]);
8589 if (strpos($InfoFieldList[4],
'$ID$') !==
false && !empty($objectid)) {
8590 $InfoFieldList[4] = str_replace(
'$ID$', (
string) $objectid, $InfoFieldList[4]);
8592 $InfoFieldList[4] = str_replace(
'$ID$',
'0', $InfoFieldList[4]);
8597 if (strpos($InfoFieldList[4],
'extra') !==
false) {
8598 $sql .=
' as main, ' . $this->db->sanitize($this->db->prefix() . $InfoFieldList[0]) .
'_extrafields as extra';
8599 $sqlwhere .=
" WHERE extra.fk_object = main." . $this->db->sanitize($InfoFieldList[2]);
8605 $sqlwhere .=
' WHERE 1=1';
8622 if (in_array($InfoFieldList[0], array(
'tablewithentity'))) {
8623 $sqlwhere .=
" AND entity = " . ((int)
$conf->entity);
8630 dol_syslog(get_class($this) .
'::showInputField type=chkbxlst', LOG_DEBUG);
8632 $resql = $this->db->query($sql);
8634 $num = $this->db->num_rows($resql);
8641 $obj = $this->db->fetch_object($resql);
8645 $fields_label = explode(
'|', $InfoFieldList[1]);
8646 if (count($fields_label) > 1) {
8648 foreach ($fields_label as $field_toshow) {
8649 $labeltoshow .= $obj->$field_toshow .
' ';
8652 $labeltoshow = $obj->{$InfoFieldList[1]};
8654 $labeltoshow =
dol_trunc($labeltoshow, 45);
8656 if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
8657 foreach ($fields_label as $field_toshow) {
8658 $translabel = $langs->trans($obj->$field_toshow);
8659 if ($translabel != $obj->$field_toshow) {
8660 $labeltoshow =
dol_trunc($translabel, 18) .
' ';
8662 $labeltoshow =
dol_trunc($obj->$field_toshow, 18) .
' ';
8666 $data[$obj->rowid] = $labeltoshow;
8669 $translabel = $langs->trans($obj->{$InfoFieldList[1]});
8670 if ($translabel != $obj->{$InfoFieldList[1]}) {
8671 $labeltoshow =
dol_trunc($translabel, 18);
8673 $labeltoshow =
dol_trunc($obj->{$InfoFieldList[1]}, 18);
8676 if (empty($labeltoshow)) {
8677 $labeltoshow =
'(not defined)';
8680 if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
8681 $data[$obj->rowid] = $labeltoshow;
8684 if (!empty($InfoFieldList[3]) && $parentField) {
8685 $parent = $parentName .
':' . $obj->{$parentField};
8689 $data[$obj->rowid] = $labeltoshow;
8694 $this->db->free($resql);
8696 $out = $form->multiselectarray($keyprefix . $key . $keysuffix, $data, $value_arr, 0, 0, $morecss, 0,
'100%');
8698 print
'Error in request ' . $sql .
' ' . $this->db->lasterror() .
'. Check setup of extra parameters.<br>';
8701 require_once DOL_DOCUMENT_ROOT.
'/categories/class/categorie.class.php';
8702 $categcode = $InfoFieldList[5];
8703 if (is_numeric($categcode)) {
8704 $tmpcategory =
new Categorie($this->db);
8705 $MAP_ID_TO_CODE = array_flip($tmpcategory->MAP_ID);
8706 $categcode = $MAP_ID_TO_CODE[(int) $categcode];
8709 $data = $form->select_all_categories($categcode,
'',
'parent', 64, $InfoFieldList[6], 1, 1);
8710 $out = $form->multiselectarray($keyprefix . $key . $keysuffix, $data, $value_arr, 0, 0, $morecss, 0,
'100%');
8713 } elseif ($type ==
'link') {
8716 $param_list = array_keys($param[
'options']);
8717 $param_list_array = explode(
':', $param_list[0], 4);
8719 $showempty = (($required && $default !=
'') ? 0 : 1);
8721 if (!preg_match(
'/search_/', $keyprefix)) {
8722 if (!empty($param_list_array[2])) {
8724 if (!empty($this->fields[$key][
'picto'])) {
8725 $morecss .=
' widthcentpercentminusxx';
8727 $morecss .=
' widthcentpercentminusx';
8731 if (!empty($this->fields[$key][
'picto'])) {
8732 $morecss .=
' widthcentpercentminusx';
8741 $objectfield = $val;
8744 $out = $form->selectForForms($param_list_array[0], $keyprefix.$key.$keysuffix, (
int) $value, $showempty,
'',
'', $morecss, $moreparam, 0, (empty($val[
'disabled']) ? 0 : 1),
'', $objectfield);
8746 if (!empty($param_list_array[2])) {
8747 if ((!
GETPOSTISSET(
'backtopage') || strpos(
GETPOST(
'backtopage'), $_SERVER[
'PHP_SELF']) === 0)
8748 && empty($val[
'disabled']) && empty($nonewbutton)) {
8749 list($class, $classfile) = explode(
':', $param_list[0]);
8750 if (file_exists(
dol_buildpath(dirname(dirname($classfile)).
'/card.php'))) {
8751 $url_path =
dol_buildpath(dirname(dirname($classfile)).
'/card.php', 1);
8753 $url_path =
dol_buildpath(dirname(dirname($classfile)).
'/'.strtolower($class).
'_card.php', 1);
8755 $paramforthenewlink =
'';
8756 $paramforthenewlink .= (
GETPOSTISSET(
'action') ?
'&action='.GETPOST(
'action',
'aZ09') :
'');
8757 $paramforthenewlink .= (
GETPOSTISSET(
'id') ?
'&id='.GETPOSTINT(
'id') :
'');
8758 $paramforthenewlink .= (
GETPOSTISSET(
'origin') ?
'&origin='.GETPOST(
'origin',
'aZ09') :
'');
8759 $paramforthenewlink .= (
GETPOSTISSET(
'originid') ?
'&originid='.GETPOSTINT(
'originid') :
'');
8760 $paramforthenewlink .=
'&fk_'.strtolower($class).
'=--IDFORBACKTOPAGE--';
8762 $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>';
8765 } elseif ($type ==
'password') {
8767 if ($keyprefix.$key.$keysuffix ==
'pass_crypted') {
8768 $out =
'<input type="'.($keyprefix ==
'search_' ?
'text' :
'password').
'" class="flat '.$morecss.
'" name="pass" id="pass" value="" '.($moreparam ? $moreparam :
'').
'>';
8769 $out .=
'<input type="hidden" name="pass_crypted" id="pass_crypted" value="'.$value.
'" '.($moreparam ? $moreparam :
'').
'>';
8771 $out =
'<input type="'.($keyprefix ==
'search_' ?
'text' :
'password').
'" class="flat '.$morecss.
'" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.$value.
'" '.($moreparam ? $moreparam :
'').
'>';
8773 } elseif ($type ==
'array') {
8775 $newval[
'type'] =
'varchar(256)';
8778 if (!empty($value)) {
8779 foreach ($value as $option) {
8780 $out .=
'<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).
'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
8781 $out .= $this->showInputField($newval, $keyprefix.$key.$keysuffix.
'[]', $option, $moreparam,
'',
'', $morecss).
'<br></span>';
8784 $out .=
'<a id="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).
'_add" href="javascript:;"><span class="fa fa-plus-circle valignmiddle"></span></a>';
8786 $newInput =
'<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).
'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
8787 $newInput .= $this->showInputField($newval, $keyprefix.$key.$keysuffix.
'[]',
'', $moreparam,
'',
'', $morecss).
'<br></span>';
8789 if (!empty(
$conf->use_javascript_ajax)) {
8791 <script nonce="'.getNonce().
'">
8792 $(document).ready(function() {
8793 $("a#'.
dol_escape_js($keyprefix.$key.$keysuffix).
'_add").click(function() {
8797 $(document).on("click", "a.'.
dol_escape_js($keyprefix.$key.$keysuffix).
'_del", function() {
8798 $(this).parent().remove();
8804 if (!empty($hidden)) {
8805 $out =
'<input type="hidden" value="'.$value.
'" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'"/>';
8808 if ($isDependList == 1) {
8809 $out .= $this->getJSListDependancies(
'_common');
8817 if (!empty($fieldValidationErrorMsg) && function_exists(
'getFieldErrorIcon')) {
8818 $out .=
' '.getFieldErrorIcon($fieldValidationErrorMsg);
8837 public function showOutputField($val, $key, $value, $moreparam =
'', $keysuffix =
'', $keyprefix =
'', $morecss =
'')
8839 global
$conf, $langs, $form;
8843 if (!is_object($form)) {
8844 require_once DOL_DOCUMENT_ROOT.
'/core/class/html.form.class.php';
8845 $form =
new Form($this->db);
8849 $type = empty($val[
'type']) ?
'' : $val[
'type'];
8850 $size = empty($val[
'css']) ?
'' : $val[
'css'];
8855 if (preg_match(
'/varchar\((\d+)\)/', $type, $reg)) {
8858 } elseif (preg_match(
'/varchar/', $type)) {
8861 if (!empty($val[
'arrayofkeyval']) && is_array($val[
'arrayofkeyval'])) {
8863 if (empty($this->fields[$key][
'multiinput'])) {
8864 $type = (($this->fields[$key][
'type'] ==
'checkbox') ? $this->fields[$key][
'type'] :
'select');
8867 if (isset($val[
'type']) && preg_match(
'/^integer:(.*):(.*)/i', $val[
'type'], $reg)) {
8871 $default = empty($val[
'default']) ?
'' : $val[
'default'];
8872 $computed = empty($val[
'computed']) ?
'' : $val[
'computed'];
8873 $unique = empty($val[
'unique']) ?
'' : $val[
'unique'];
8874 $required = empty($val[
'required']) ?
'' : $val[
'required'];
8876 $param[
'options'] = array();
8878 if (!empty($val[
'arrayofkeyval']) && is_array($val[
'arrayofkeyval'])) {
8879 $param[
'options'] = $val[
'arrayofkeyval'];
8881 if (isset($val[
'type']) && preg_match(
'/^integer:([^:]*):([^:]*)/i', $val[
'type'], $reg)) {
8883 $stringforoptions = $reg[1].
':'.$reg[2];
8885 if ($reg[1] ==
'User') {
8886 $stringforoptions .=
':#getnomurlparam1=-1';
8888 $param[
'options'] = array($stringforoptions => $stringforoptions);
8889 } elseif (isset($val[
'type']) && preg_match(
'/^sellist:(.*):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
8890 $param[
'options'] = array($reg[1].
':'.$reg[2].
':'.$reg[3].
':'.$reg[4] =>
'N');
8892 } elseif (isset($val[
'type']) && preg_match(
'/^sellist:(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
8893 $param[
'options'] = array($reg[1].
':'.$reg[2].
':'.$reg[3] =>
'N');
8895 } elseif (isset($val[
'type']) && preg_match(
'/^sellist:(.*):(.*)/i', $val[
'type'], $reg)) {
8896 $param[
'options'] = array($reg[1].
':'.$reg[2] =>
'N');
8898 } elseif (isset($val[
'type']) && preg_match(
'/^chkbxlst:(.*)/i', $val[
'type'], $reg)) {
8899 $param[
'options'] = array($reg[1] =>
'N');
8901 } elseif (isset($val[
'type']) && preg_match(
'/stars\((\d+)\)/', $val[
'type'], $reg)) {
8902 $param[
'options'] = array();
8907 $langfile = empty($val[
'langfile']) ?
'' : $val[
'langfile'];
8908 $list = (empty($val[
'list']) ?
'' : $val[
'list']);
8909 $help = (empty($val[
'help']) ?
'' : $val[
'help']);
8910 $hidden = (($val[
'visible'] == 0) ? 1 : 0);
8920 $value =
dol_eval((
string) $computed, 1, 0,
'2');
8923 if (empty($morecss)) {
8924 if ($type ==
'date') {
8925 $morecss =
'minwidth100imp';
8926 } elseif ($type ==
'datetime' || $type ==
'timestamp') {
8927 $morecss =
'minwidth200imp';
8928 } elseif (in_array($type, array(
'int',
'double',
'price'))) {
8929 $morecss =
'maxwidth75';
8930 } elseif ($type ==
'url') {
8931 $morecss =
'minwidth400';
8932 } elseif ($type ==
'boolean') {
8935 if (is_numeric($size) && round((
float) $size) < 12) {
8936 $morecss =
'minwidth100';
8937 } elseif (is_numeric($size) && round((
float) $size) <= 48) {
8938 $morecss =
'minwidth200';
8940 $morecss =
'minwidth400';
8946 if (in_array($key, array(
'rowid',
'ref')) && method_exists($this,
'getNomUrl')) {
8948 if ($key !=
'rowid' || empty($this->fields[
'ref'])) {
8949 $value = $this->getNomUrl(1,
'', 0,
'', 1);
8951 } elseif ($key ==
'status' && method_exists($this,
'getLibStatut')) {
8952 $value = $this->getLibStatut(3);
8953 } elseif ($type ==
'date') {
8954 if (!empty($value)) {
8959 } elseif ($type ==
'datetime' || $type ==
'timestamp') {
8960 if (!empty($value)) {
8965 } elseif ($type ==
'duration') {
8966 include_once DOL_DOCUMENT_ROOT.
'/core/lib/date.lib.php';
8967 if (!is_null($value) && $value !==
'') {
8970 } elseif ($type ==
'double' || $type ==
'real') {
8971 if (!is_null($value) && $value !==
'') {
8972 $value =
price($value);
8974 } elseif ($type ==
'boolean') {
8976 if (!empty($value)) {
8977 $checked =
' checked ';
8980 $value =
'<input type="checkbox" '.$checked.
' '.($moreparam ? $moreparam :
'').
' readonly disabled>';
8982 $value =
yn($value ? 1 : 0);
8984 } elseif ($type ==
'mail' || $type ==
'email') {
8986 } elseif ($type ==
'url') {
8988 } elseif ($type ==
'phone') {
8989 $value =
dol_print_phone((
string) $value,
'', 0, 0,
'',
' ',
'phone');
8990 } elseif ($type ==
'ip') {
8992 } elseif ($type ==
'stars') {
8993 $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 :
'').
'>';
8994 $value .=
'<div class="star-selection" id="'.$keyprefix.$key.$keysuffix.$this->id.
'_selection">';
8996 while ($i <= $size) {
8997 $value .=
'<span class="star" data-value="'.$i.
'">'.
img_picto(
'',
'fontawesome_star_fas').
'</span>';
9002 $(document).ready(function() { /* commonobject.class.php 2 */
9003 let container = $("#'.$keyprefix.$key.$keysuffix.$this->id.
'_selection");
9004 let selectedStars = parseInt($("#'.$keyprefix.$key.$keysuffix.$this->id.
'").val()) || 0;
9005 container.find(".star").each(function() {
9006 $(this).toggleClass("active", $(this).data("value") <= selectedStars);
9008 container.find(".star").on("mouseover", function() {
9009 let selectedStar = $(this).data("value");
9010 container.find(".star").each(function() {
9011 $(this).toggleClass("active", $(this).data("value") <= selectedStar);
9014 container.on("mouseout", function() {
9015 container.find(".star").each(function() {
9016 $(this).toggleClass("active", $(this).data("value") <= selectedStars);
9019 container.find(".star").off("click").on("click", function() {
9020 selectedStars = $(this).data("value");
9021 if (selectedStars == 1 && $("#'.$keyprefix.$key.$keysuffix.$this->id.
'").val() == 1) {
9024 container.find("#'.$keyprefix.$key.$keysuffix.$this->id.
'").val(selectedStars);
9025 container.find(".star").each(function() {
9026 $(this).toggleClass("active", $(this).data("value") <= selectedStars);
9029 url: "ajax/'.$this->element.
'.php",
9032 objectId: "'.$this->
id.
'",
9033 field: "'.$keyprefix.$key.$keysuffix.
'",
9034 value: selectedStars,
9037 success: function(response) {
9038 var res = JSON.parse(response);
9039 console[res.status === "success" ? "log" : "error"](res.message);
9041 error: function(xhr, status, error) {
9042 console.log("Ajax request failed while updating '.$keyprefix.$key.$keysuffix.
':", error);
9048 } elseif ($type ==
'price') {
9049 if (!is_null($value) && $value !==
'') {
9050 $value =
price($value, 0, $langs, 0, 0, -1,
$conf->currency);
9052 } elseif ($type ==
'select') {
9053 $value = isset($param[
'options'][(
string) $value]) ? $param[
'options'][(
string) $value] :
'';
9054 if (strpos($value,
"|") !==
false) {
9055 $value = $langs->trans(explode(
'|', $value)[0]);
9056 } elseif (! is_numeric($value)) {
9057 $value = $langs->trans($value);
9059 } elseif ($type ==
'sellist') {
9060 $param_list = array_keys($param[
'options']);
9061 $InfoFieldList = explode(
":", $param_list[0]);
9063 $selectkey =
"rowid";
9066 if (count($InfoFieldList) > 2 && !empty($InfoFieldList[2])) {
9067 $selectkey = $InfoFieldList[2];
9068 $keyList = $InfoFieldList[2].
' as rowid';
9071 $fields_label = explode(
'|', $InfoFieldList[1]);
9072 if (is_array($fields_label)) {
9074 $keyList .= implode(
', ', $fields_label);
9077 $filter_categorie =
false;
9078 if (count($InfoFieldList) > 5) {
9079 if ($InfoFieldList[0] ==
'categorie') {
9080 $filter_categorie =
true;
9084 $sql =
"SELECT ".$this->db->sanitize($keyList, 0, 0, 1);
9085 $sql .=
' FROM '.$this->db->prefix().$this->db->sanitize($InfoFieldList[0]);
9086 if (isset($InfoFieldList[4]) && strpos($InfoFieldList[4],
'extra') !==
false) {
9089 if ($selectkey ==
'rowid' && empty($value)) {
9090 $sql .=
" WHERE ".$this->db->sanitize($selectkey).
" = 0";
9091 } elseif ($selectkey ==
'rowid') {
9092 $sql .=
" WHERE ".$this->db->sanitize($selectkey).
" = ".((int) $value);
9094 $sql .=
" WHERE ".$this->db->sanitize($selectkey).
" = '".$this->db->escape((
string) $value).
"'";
9099 dol_syslog(get_class($this).
':showOutputField:$type=sellist', LOG_DEBUG);
9100 $resql = $this->db->query($sql);
9102 if (!$filter_categorie) {
9104 $numrows = $this->db->num_rows($resql);
9106 $obj = $this->db->fetch_object($resql);
9109 $fields_label = explode(
'|', $InfoFieldList[1]);
9111 if (is_array($fields_label) && count($fields_label) > 1) {
9112 foreach ($fields_label as $field_toshow) {
9114 if (!empty($obj->$field_toshow)) {
9115 $translabel = $langs->trans($obj->$field_toshow);
9117 if ($translabel != $field_toshow) {
9118 $value .=
dol_trunc($translabel, 18) .
' ';
9120 $value .= $obj->$field_toshow .
' ';
9125 if (!empty($obj->{$InfoFieldList[1]})) {
9126 $translabel = $langs->trans($obj->{$InfoFieldList[1]});
9128 if ($translabel != $obj->{$InfoFieldList[1]}) {
9131 $value = $obj->{$InfoFieldList[1]};
9136 require_once DOL_DOCUMENT_ROOT .
'/categories/class/categorie.class.php';
9139 $obj = $this->db->fetch_object($resql);
9141 $c->fetch($obj->rowid);
9142 $ways =
$c->print_all_ways();
9143 foreach ($ways as $way) {
9144 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories"' . (
$c->color ?
' style="background: #' .
$c->color .
';"' :
' style="background: #aaa"') .
'>' .
img_object(
'',
'category') .
' ' . $way .
'</li>';
9146 $value =
'<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(
' ', $toprint).
'</ul></div>';
9149 dol_syslog(get_class($this).
'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
9151 } elseif ($type ==
'radio') {
9152 $value = $param[
'options'][(
string) $value];
9153 } elseif ($type ==
'checkbox') {
9154 $value_arr = explode(
',', (
string) $value);
9156 if (is_array($value_arr) && count($value_arr) > 0) {
9158 foreach ($value_arr as $keyval => $valueval) {
9159 if (!empty($valueval)) {
9160 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' . $param[
'options'][$valueval] .
'</li>';
9163 if (!empty($toprint)) {
9164 $value =
'<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">' . implode(
' ', $toprint) .
'</ul></div>';
9167 } elseif ($type ==
'chkbxlst') {
9168 $value_arr = (isset($value) ? explode(
',', $value) : array());
9170 $param_list = array_keys($param[
'options']);
9171 $InfoFieldList = explode(
":", $param_list[0]);
9173 $selectkey =
"rowid";
9176 if (count($InfoFieldList) >= 3) {
9177 $selectkey = $InfoFieldList[2];
9178 $keyList = $InfoFieldList[2].
' as rowid';
9181 $fields_label = explode(
'|', $InfoFieldList[1]);
9182 if (is_array($fields_label)) {
9184 $keyList .= implode(
', ', $fields_label);
9187 $filter_categorie =
false;
9188 if (count($InfoFieldList) > 5) {
9189 if ($InfoFieldList[0] ==
'categorie') {
9190 $filter_categorie =
true;
9194 $sql =
"SELECT ".$this->db->sanitize($keyList, 0, 0, 1);
9195 $sql .=
' FROM '.$this->db->prefix().$this->db->sanitize($InfoFieldList[0]);
9196 if (isset($InfoFieldList[4]) && strpos($InfoFieldList[4],
'extra') !==
false) {
9202 dol_syslog(get_class($this).
':showOutputField:$type=chkbxlst', LOG_DEBUG);
9203 $resql = $this->db->query($sql);
9205 if (!$filter_categorie) {
9208 while ($obj = $this->db->fetch_object($resql)) {
9210 $fields_label = explode(
'|', $InfoFieldList[1]);
9211 if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
9212 if (is_array($fields_label) && count($fields_label) > 1) {
9213 foreach ($fields_label as $field_toshow) {
9215 if (!empty($obj->$field_toshow)) {
9216 $translabel = $langs->trans($obj->$field_toshow);
9218 if ($translabel != $field_toshow) {
9219 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' .
dol_trunc($translabel, 18) .
'</li>';
9221 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' . $obj->$field_toshow .
'</li>';
9226 if (!empty($obj->{$InfoFieldList[1]})) {
9227 $translabel = $langs->trans($obj->{$InfoFieldList[1]});
9229 if ($translabel != $obj->{$InfoFieldList[1]}) {
9230 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' .
dol_trunc($translabel, 18) .
'</li>';
9232 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' . $obj->{$InfoFieldList[1]} .
'</li>';
9238 require_once DOL_DOCUMENT_ROOT .
'/categories/class/categorie.class.php';
9241 while ($obj = $this->db->fetch_object($resql)) {
9242 if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
9244 $c->fetch($obj->rowid);
9245 $ways =
$c->print_all_ways();
9246 foreach ($ways as $way) {
9247 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories"' . (
$c->color ?
' style="background: #' .
$c->color .
';"' :
' style="background: #aaa"') .
'>' .
img_object(
'',
'category') .
' ' . $way .
'</li>';
9252 $value =
'<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(
' ', $toprint).
'</ul></div>';
9254 dol_syslog(get_class($this).
'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
9256 } elseif ($type ==
'link') {
9261 $param_list = array_keys($param[
'options']);
9265 $InfoFieldList = explode(
":", $param_list[0]);
9267 $classname = $InfoFieldList[0];
9268 $classpath = $InfoFieldList[1];
9271 $getnomurlparam = 3;
9272 $getnomurlparam2 =
'';
9274 if (preg_match(
'/#getnomurlparam1=([^#]*)/', $param_list[0], $regtmp)) {
9275 $getnomurlparam = $regtmp[1];
9277 if (preg_match(
'/#getnomurlparam2=([^#]*)/', $param_list[0], $regtmp)) {
9278 $getnomurlparam2 = $regtmp[1];
9281 if (!empty($classpath)) {
9284 if ($classname && !class_exists($classname)) {
9288 if ($element_prop) {
9289 $classname = $element_prop[
'classname'];
9294 if ($classname && class_exists($classname)) {
9295 $object =
new $classname($this->db);
9296 '@phan-var-force CommonObject $object';
9297 if (
$object->element ===
'product') {
9298 '@phan-var-force Product $object';
9299 $result =
$object->fetch((
int) $value,
'',
'',
'', 0, 1, 1);
9301 $result =
$object->fetch($value);
9304 if (
$object->element ===
'product') {
9305 '@phan-var-force Product $object';
9306 $get_name_url_param_arr = array($getnomurlparam, $getnomurlparam2, 0, -1, 0,
'', 0);
9307 if (isset($val[
'get_name_url_params'])) {
9308 $get_name_url_params = explode(
':', $val[
'get_name_url_params']);
9309 if (!empty($get_name_url_params)) {
9310 $param_num_max = count($get_name_url_param_arr) - 1;
9311 foreach ($get_name_url_params as $param_num => $param_value) {
9312 if ($param_num > $param_num_max) {
9315 $get_name_url_param_arr[$param_num] = $param_value;
9323 $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]);
9325 $value =
$object->getNomUrl($getnomurlparam, $getnomurlparam2);
9332 dol_syslog(
'Error bad setup of extrafield', LOG_WARNING);
9333 return 'Error bad setup of extrafield';
9338 } elseif ($type ==
'password') {
9339 $value =
'<span class="opacitymedium">'.$langs->trans(
"Encrypted").
'</span>';
9341 } elseif ($type ==
'array') {
9342 if (is_array($value)) {
9343 $value = implode(
'<br>', $value);
9345 dol_syslog(__METHOD__.
' Expected array from dol_eval, but got '.gettype($value), LOG_ERR);
9346 return 'Error unexpected result from code evaluation';
9349 if (!empty($value) && preg_match(
'/^text/', (
string) $type) && !preg_match(
'/search_/', $keyprefix) && !empty($param[
'options'])) {
9350 $value = str_replace(
',',
"\n", $value);
9358 return is_null($out) ?
'' : $out;
9370 unset($this->validateFieldsErrors[$fieldKey]);
9384 $msg = $langs->trans(
"UnknownError");
9387 $this->error = $this->validateFieldsErrors[$fieldKey] = $msg;
9398 if (!empty($this->validateFieldsErrors[$fieldKey])) {
9399 return $this->validateFieldsErrors[$fieldKey];
9416 if (!class_exists(
'Validate')) {
9417 require_once DOL_DOCUMENT_ROOT .
'/core/class/validate.class.php';
9420 $this->clearFieldError($fieldKey);
9422 if (!array_key_exists($fieldKey, $fields) || !is_array($fields[$fieldKey])) {
9423 $this->setFieldError($fieldKey, $langs->trans(
'FieldNotFoundInObject'));
9427 $val = $fields[$fieldKey];
9430 $param[
'options'] = array();
9431 $type = $val[
'type'];
9434 if (isset($val[
'notnull']) && $val[
'notnull'] === 1) {
9448 if (preg_match(
'/varchar\((\d+)\)/', $type, $reg)) {
9450 $maxSize = (int) $reg[1];
9451 } elseif (preg_match(
'/varchar/', $type)) {
9455 if (!empty($val[
'arrayofkeyval']) && is_array($val[
'arrayofkeyval'])) {
9459 if (!empty($val[
'type']) && preg_match(
'/^integer:(.*):(.*)/i', $val[
'type'], $reg)) {
9463 if (!empty($val[
'arrayofkeyval']) && is_array($val[
'arrayofkeyval'])) {
9464 $param[
'options'] = $val[
'arrayofkeyval'];
9467 if (preg_match(
'/^integer:(.*):(.*)/i', $val[
'type'], $reg)) {
9469 $param[
'options'] = array($reg[1].
':'.$reg[2] => $reg[1].
':'.$reg[2]);
9470 } elseif (preg_match(
'/^sellist:(.*):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
9471 $param[
'options'] = array($reg[1].
':'.$reg[2].
':'.$reg[3].
':'.$reg[4] =>
'N');
9473 } elseif (preg_match(
'/^sellist:(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
9474 $param[
'options'] = array($reg[1].
':'.$reg[2].
':'.$reg[3] =>
'N');
9476 } elseif (preg_match(
'/^sellist:(.*):(.*)/i', $val[
'type'], $reg)) {
9477 $param[
'options'] = array($reg[1].
':'.$reg[2] =>
'N');
9486 $validate =
new Validate($this->db, $langs);
9496 if ($required && !$validate->isNotEmptyString($fieldValue)) {
9497 $this->setFieldError($fieldKey, $validate->error);
9499 } elseif (!$required && !$validate->isNotEmptyString($fieldValue)) {
9505 if (!empty($maxSize) && !$validate->isMaxLength($fieldValue, $maxSize)) {
9506 $this->setFieldError($fieldKey, $validate->error);
9511 if (!empty($minSize) && !$validate->isMinLength($fieldValue, $minSize)) {
9512 $this->setFieldError($fieldKey, $validate->error);
9520 if (in_array($type, array(
'date',
'datetime',
'timestamp'))) {
9521 if (!$validate->isTimestamp($fieldValue)) {
9522 $this->setFieldError($fieldKey, $validate->error);
9527 } elseif ($type ==
'duration') {
9528 if (!$validate->isDuration($fieldValue)) {
9529 $this->setFieldError($fieldKey, $validate->error);
9534 } elseif (in_array($type, array(
'double',
'real',
'price'))) {
9536 if (!$validate->isNumeric($fieldValue)) {
9537 $this->setFieldError($fieldKey, $validate->error);
9542 } elseif ($type ==
'boolean') {
9543 if (!$validate->isBool($fieldValue)) {
9544 $this->setFieldError($fieldKey, $validate->error);
9549 } elseif ($type ==
'mail' || $type ==
'email') {
9550 if (!$validate->isEmail($fieldValue)) {
9551 $this->setFieldError($fieldKey, $validate->error);
9554 } elseif ($type ==
'url') {
9555 if (!$validate->isUrl($fieldValue)) {
9556 $this->setFieldError($fieldKey, $validate->error);
9561 } elseif ($type ==
'phone') {
9562 if (!$validate->isPhone($fieldValue)) {
9563 $this->setFieldError($fieldKey, $validate->error);
9568 } elseif ($type ==
'select' || $type ==
'radio') {
9569 if (!isset($param[
'options'][$fieldValue])) {
9570 $this->error = $langs->trans(
'RequireValidValue');
9575 } elseif ($type ==
'sellist' || $type ==
'chkbxlst') {
9576 $param_list = array_keys($param[
'options']);
9577 $InfoFieldList = explode(
":", $param_list[0]);
9578 $value_arr = explode(
',', $fieldValue);
9580 $selectkey =
"rowid";
9581 if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
9582 $selectkey = $InfoFieldList[2];
9585 if (!$validate->isInDb($value_arr, $InfoFieldList[0], $selectkey)) {
9586 $this->setFieldError($fieldKey, $validate->error);
9591 } elseif ($type ==
'link') {
9592 $param_list = array_keys($param[
'options']);
9593 $InfoFieldList = explode(
":", $param_list[0]);
9594 $classname = $InfoFieldList[0];
9595 $classpath = $InfoFieldList[1];
9596 if (!$validate->isFetchable((
int) $fieldValue, $classname, $classpath)) {
9597 $lastIsFetchableError = $validate->error;
9600 if ($validate->isFetchableElement((
int) $fieldValue, $classname)) {
9604 $this->setFieldError($fieldKey, $lastIsFetchableError);
9628 public function showOptionals($extrafields, $mode =
'view', $params =
null, $keysuffix =
'', $keyprefix =
'', $onetrtd =
'', $display_type =
'card')
9630 global
$db,
$conf, $langs, $action, $form, $hookmanager;
9631 global $objectoffield;
9633 if (!is_object($form)) {
9636 if (!is_object($extrafields)) {
9637 dol_syslog(
'Bad parameter extrafields for showOptionals', LOG_ERR);
9638 return 'Bad parameter extrafields for showOptionals';
9640 if (!is_array($extrafields->attributes[$this->table_element])) {
9641 dol_syslog(
"extrafields->attributes was not loaded with extrafields->fetch_name_optionals_label(table_element);", LOG_WARNING);
9645 $objectoffield = $this;
9649 $parameters = array(
'mode' => $mode,
'params' => $params,
'keysuffix' => $keysuffix,
'keyprefix' => $keyprefix,
'display_type' => $display_type);
9650 $reshook = $hookmanager->executeHooks(
'showOptionals', $parameters, $this, $action);
9651 $hookResPrint = $hookmanager->resPrint;
9653 if (empty($reshook)) {
9654 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) {
9656 $out .=
'<!-- commonobject:showOptionals --> ';
9659 $nbofextrafieldsshown = 0;
9662 $lastseparatorkeyfound =
'';
9663 $extrafields_collapse_num =
'';
9664 $extrafields_collapse_num_old =
'';
9667 foreach ($extrafields->attributes[$this->table_element][
'label'] as $key => $label) {
9671 if (is_array($params) && array_key_exists(
'onlykey', $params) && $key != $params[
'onlykey']) {
9677 if ($enabled && isset($extrafields->attributes[$this->table_element][
'enabled'][$key])) {
9678 $enabled = (int)
dol_eval((
string) $extrafields->attributes[$this->table_element][
'enabled'][$key], 1, 1,
'2');
9680 if (empty($enabled)) {
9685 if (isset($extrafields->attributes[$this->table_element][
'list'][$key])) {
9686 $visibility = (int)
dol_eval((
string) $extrafields->attributes[$this->table_element][
'list'][$key], 1, 1,
'2');
9690 if ($perms && isset($extrafields->attributes[$this->table_element][
'perms'][$key])) {
9691 $perms = (int)
dol_eval((
string) $extrafields->attributes[$this->table_element][
'perms'][$key], 1, 1,
'2');
9694 if (($mode ==
'create') && !in_array(abs($visibility), array(1, 3))) {
9696 } elseif (($mode ==
'edit') && !in_array(abs($visibility), array(1, 3, 4))) {
9700 $ef_name =
'options_' . $key;
9701 $ef_value = $this->array_options[$ef_name] ??
'';
9702 $out .=
'<input type="hidden" name="' . $ef_name .
'" id="' . $ef_name .
'" value="' .
dolPrintHTMLForAttribute($ef_value) .
'" />' .
"\n";
9704 } elseif ($mode ==
'view' && empty($visibility)) {
9707 if (empty($perms)) {
9712 if (!empty($extrafields->attributes[$this->table_element][
'langfile'][$key])) {
9713 $langs->load($extrafields->attributes[$this->table_element][
'langfile'][$key]);
9718 if (is_array($params) && count($params) > 0 && $display_type ==
'card') {
9719 if (array_key_exists(
'cols', $params)) {
9720 $colspan = $params[
'cols'];
9721 } elseif (array_key_exists(
'colspan', $params)) {
9723 if (preg_match(
'/colspan="(\d+)"/', $params[
'colspan'], $reg)) {
9726 $colspan = $params[
'colspan'];
9730 $colspan = intval($colspan);
9734 $value = ((!empty($this->array_options) && array_key_exists(
"options_".$key.$keysuffix, $this->array_options)) ? $this->array_options[
"options_".$key.$keysuffix] :
null);
9740 $check =
'alphanohtml';
9741 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'html',
'text'))) {
9742 $check =
'restricthtml';
9744 $getposttemp =
GETPOST($keyprefix.
'options_'.$key.$keysuffix, $check, 3);
9746 if (is_array($getposttemp) || $getposttemp !=
'' ||
GETPOSTISSET($keyprefix.
'options_'.$key.$keysuffix)) {
9747 if (is_array($getposttemp)) {
9749 $value = implode(
",", $getposttemp);
9751 $value = $getposttemp;
9753 } elseif (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'int'))) {
9754 $value = (!empty($this->array_options[
"options_".$key]) || (isset($this->array_options[
"options_".$key]) && $this->array_options[
"options_".$key] ===
'0')) ? $this->array_options[
"options_".$key] :
'';
9755 } elseif (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'varchar',
'char'))) {
9756 $value = (isset($this->array_options[
"options_".$key]) && $this->array_options[
"options_".$key] !==
'') ? $this->array_options[
"options_".$key] :
'';
9758 $value = (!empty($this->array_options[
"options_".$key]) ? $this->array_options[
"options_".$key] :
'');
9764 $nbofextrafieldsshown++;
9767 if ($extrafields->attributes[$this->table_element][
'type'][$key] ==
'separate') {
9768 $extrafields_collapse_num = $key;
9786 $out .= $extrafields->showSeparator($key, $this, ($colspan ? $colspan + 1 : 2), $display_type, $mode);
9788 $lastseparatorkeyfound = $key;
9790 $collapse_group = $extrafields_collapse_num.(!empty($this->
id) ?
'_'.$this->id :
'');
9792 $class = (!empty($extrafields->attributes[$this->table_element][
'hidden'][$key]) ?
'hideobject ' :
'');
9794 if (is_array($params) && count($params) > 0) {
9795 if (array_key_exists(
'class', $params)) {
9796 $class .= $params[
'class'].
' ';
9798 if (array_key_exists(
'style', $params)) {
9799 $csstyle = $params[
'style'];
9804 $domData =
' data-element="extrafield"';
9805 $domData .=
' data-targetelement="'.$this->element.
'"';
9806 $domData .=
' data-targetid="'.$this->id.
'"';
9808 $html_id = (empty($this->
id) ?
'' :
'extrarow-'.$this->element.
'_'.$key.
'_'.
$this->id);
9809 if ($display_type ==
'card') {
9814 if ($action ==
'selectlines') {
9821 $force_values_on_change_company = (
9822 ($this->element ==
'facture' &&
getDolGlobalInt(
'THIRDPARTY_PROPAGATE_EXTRAFIELDS_TO_INVOICE'))
9823 || ($this->element ==
'commande' &&
getDolGlobalInt(
'THIRDPARTY_PROPAGATE_EXTRAFIELDS_TO_ORDER'))
9824 || ($this->element ==
'order_supplier' &&
getDolGlobalInt(
'THIRDPARTY_PROPAGATE_EXTRAFIELDS_TO_SUPPLIER_ORDER'))
9826 if ($force_values_on_change_company &&
GETPOSTINT(
'changecompany')) {
9827 $value = $this->array_options[
'options_'.$key] ?? $value;
9831 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'date'))) {
9832 $datenotinstring =
null;
9833 if (array_key_exists(
'options_'.$key, $this->array_options)) {
9834 $datenotinstring = $this->array_options[
'options_'.$key];
9835 if (!is_numeric($this->array_options[
'options_'.$key])) {
9836 $datenotinstring = $this->db->jdate($datenotinstring);
9839 $datekey = $keyprefix.
'options_'.$key.$keysuffix;
9842 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'datetime'))) {
9843 $datenotinstring =
null;
9844 if (array_key_exists(
'options_'.$key, $this->array_options)) {
9845 $datenotinstring = $this->array_options[
'options_'.$key];
9846 if (!is_numeric($this->array_options[
'options_'.$key])) {
9847 $datenotinstring = $this->db->jdate($datenotinstring);
9850 $timekey = $keyprefix.
'options_'.$key.$keysuffix;
9851 $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;
9854 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'price',
'double'))) {
9855 if (
GETPOSTISSET($keyprefix.
'options_'.$key.$keysuffix) || $value) {
9857 } elseif (isset($this->array_options[
'options_'.$key])) {
9858 $value = $this->array_options[
'options_'.$key];
9863 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'html',
'text',
'varchar',
'select',
'radio',
'int',
'boolean'))) {
9864 if ($action ==
'create' || $mode ==
'create') {
9865 $value = (
GETPOSTISSET($keyprefix.
'options_'.$key.$keysuffix) || $value) ? $value : $extrafields->attributes[$this->table_element][
'default'][$key];
9869 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'checkbox'))) {
9870 if ($action ==
'create') {
9871 $value = (
GETPOSTISSET($keyprefix.
'options_'.$key.$keysuffix) || $value) ? $value : explode(
',', $extrafields->attributes[$this->table_element][
'default'][$key]);
9876 $labeltoshow = $langs->trans($label);
9877 $helptoshow = $langs->trans($extrafields->attributes[$this->table_element][
'help'][$key]);
9878 if ($display_type ==
'card') {
9879 $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.
' >';
9880 if (
getDolGlobalString(
'MAIN_VIEW_LINE_NUMBER') && ($action ==
'view' || $action ==
'valid' || $action ==
'editline' || $action ==
'confirm_valid' || $action ==
'confirm_cancel')) {
9881 $out .=
'<td></td>';
9883 $out .=
'<td class="'.(empty($params[
'tdclass']) ?
'titlefieldmax45' : $params[
'tdclass']).
' wordbreak';
9884 if ($extrafields->attributes[$this->table_element][
'type'][$key] ==
'text') {
9887 } elseif ($display_type ==
'line') {
9888 $out .=
'<div '.($html_id ?
'id="'.$html_id.
'" ' :
'').$csstyle.
' class="fieldline_options_'.$key.
' '.$class.$this->element.
'_extras_'.$key.
' trextrafields_collapse'.$collapse_group.
'" '.$domData.
' >';
9889 $out .=
'<div style="display: inline-block; padding-right:4px" class="wordbreak';
9894 $tpl_context = isset($params[
"tpl_context"]) ? $params[
"tpl_context"] :
"none";
9895 if ($tpl_context !=
"public") {
9896 if ($mode !=
'view' && !empty($extrafields->attributes[$this->table_element][
'required'][$key])) {
9897 $out .=
' fieldrequired';
9901 if ($tpl_context ==
"public") {
9902 if (!empty($extrafields->attributes[$this->table_element][
'help'][$key])) {
9903 $out .= $form->textwithpicto($labeltoshow, $helptoshow);
9905 $out .= $labeltoshow;
9907 if ($mode !=
'view' && !empty($extrafields->attributes[$this->table_element][
'required'][$key])) {
9908 $out .=
' <span style="color: red">*</span>';
9911 if (!empty($extrafields->attributes[$this->table_element][
'help'][$key])) {
9912 $out .= $form->textwithpicto($labeltoshow, $helptoshow);
9914 $out .= $labeltoshow;
9918 $out .= ($display_type ==
'card' ?
'</td>' :
'</div>');
9921 $html_id = !empty($this->
id) ? $this->element.
'_extras_'.$key.
'_'.$this->id :
'';
9922 if ($display_type ==
'card') {
9924 $out .=
'<td '.($html_id ?
'id="'.$html_id.
'" ' :
'').
' class="valuefieldcreate '.$this->element.
'_extras_'.$key;
9925 $out .=
'" '.($colspan ?
' colspan="'.$colspan.
'"' :
'');
9927 } elseif ($display_type ==
'line') {
9928 $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].
'">';
9933 $out .= $extrafields->showOutputField($key, $value,
'', $this->table_element);
9936 $listoftypestoshowpicto = explode(
',',
getDolGlobalString(
'MAIN_TYPES_TO_SHOW_PICTO',
'email,phone,ip,password'));
9937 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], $listoftypestoshowpicto)) {
9938 $out .=
getPictoForType($extrafields->attributes[$this->table_element][
'type'][$key], ($extrafields->attributes[$this->table_element][
'type'][$key] ==
'text' ?
'tdtop' :
''));
9941 $out .= $extrafields->showInputField($key, $value,
'', $keysuffix,
'',
'', $this, $this->table_element);
9944 $listoftypestoshowpicto = explode(
',',
getDolGlobalString(
'MAIN_TYPES_TO_SHOW_PICTO',
'email,phone,ip,password'));
9945 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], $listoftypestoshowpicto)) {
9946 $out .=
getPictoForType($extrafields->attributes[$this->table_element][
'type'][$key], ($extrafields->attributes[$this->table_element][
'type'][$key] ==
'text' ?
'tdtop' :
''));
9948 $out .= $extrafields->showInputField($key, $value,
'', $keysuffix,
'',
'', $this, $this->table_element);
9952 $out .= ($display_type ==
'card' ?
'</td>' :
'</div>');
9953 $out .= ($display_type ==
'card' ?
'</tr>'.
"\n" :
'</div>');
9959 if (!empty(
$conf->use_javascript_ajax)) {
9960 $out .= $this->getJSListDependancies();
9963 $out .=
'<!-- commonobject:showOptionals end --> '.
"\n";
9965 if (empty($nbofextrafieldsshown)) {
9971 $out .= $hookResPrint;
9983 <script nonce="'.getNonce().
'">
9984 jQuery(document).ready(function() {
9985 function showOptions'.$type.
'(child_list, parent_list, orig_select)
9987 var val = $("select[name=\""+parent_list+"\"]").val();
9988 var parentVal = parent_list + ":" + val;
9989 if(typeof val == "string"){
9991 var options = orig_select.find("option[parent=\""+parentVal+"\"]").clone();
9992 $("select[name=\""+child_list+"\"] option[parent]").remove();
9993 $("select[name=\""+child_list+"\"]").append(options);
9995 var options = orig_select.find("option[parent]").clone();
9996 $("select[name=\""+child_list+"\"] option[parent]").remove();
9997 $("select[name=\""+child_list+"\"]").append(options);
9999 } else if(val > 0) {
10000 var options = orig_select.find("option[parent=\""+parentVal+"\"]").clone();
10001 $("select[name=\""+child_list+"\"] option[parent]").remove();
10002 $("select[name=\""+child_list+"\"]").append(options);
10004 var options = orig_select.find("option[parent]").clone();
10005 $("select[name=\""+child_list+"\"] option[parent]").remove();
10006 $("select[name=\""+child_list+"\"]").append(options);
10009 function setListDependencies'.$type.
'() {
10010 jQuery("select option[parent]").parent().each(function() {
10011 var orig_select = {};
10012 var child_list = $(this).attr("name");
10013 orig_select[child_list] = $(this).clone();
10014 var parent = $(this).find("option[parent]:first").attr("parent");
10015 var infos = parent.split(":");
10016 var parent_list = infos[0];
10018 //Hide daughters lists
10019 if ($("#"+child_list).val() == 0 && $("#"+parent_list).val() == 0){
10020 $("#"+child_list).hide();
10021 //Show mother lists
10022 } else if ($("#"+parent_list).val() != 0){
10023 $("#"+parent_list).show();
10025 //Show the child list if the parent list value is selected
10026 $("select[name=\""+parent_list+"\"]").click(function() {
10027 if ($(this).val() != 0){
10028 $("#"+child_list).show()
10032 //When we change parent list
10033 $("select[name=\""+parent_list+"\"]").change(function() {
10034 showOptions'.$type.
'(child_list, parent_list, orig_select[child_list]);
10035 //Select the value 0 on child list after a change on the parent list
10036 $("#"+child_list).val(0).trigger("change");
10037 //Hide child lists if the parent value is set to 0
10038 if ($(this).val() == 0){
10039 $("#"+child_list).hide();
10045 setListDependencies'.$type.
'();
10060 $module = empty($this->module) ?
'' : $this->module;
10061 $element = $this->element;
10063 if ($element ==
'facturerec') {
10064 $element =
'facture';
10065 } elseif ($element ==
'invoice_supplier_rec') {
10066 return !$user->hasRight(
'fournisseur',
'facture') ? null : $user->hasRight(
'fournisseur',
'facture');
10067 } elseif ($module && $user->hasRight($module, $element)) {
10069 return $user->hasRight($module, $element);
10072 return isset($user->rights->$element) ? $user->rights->$element :
null;
10089 global $hookmanager;
10091 $parameters = array(
10092 'origin_id' => $origin_id,
10093 'dest_id' => $dest_id,
10094 'tables' => $tables,
10096 $reshook = $hookmanager->executeHooks(
'commonReplaceThirdparty', $parameters);
10099 } elseif ($reshook < 0) {
10100 return $ignoreerrors === 1;
10103 foreach ($tables as $table) {
10104 $sql =
'UPDATE '.$dbs->prefix().$table.
' SET fk_soc = '.((int) $dest_id).
' WHERE fk_soc = '.((int) $origin_id);
10106 if (!$dbs->
query($sql)) {
10107 if ($ignoreerrors) {
10132 foreach ($tables as $table) {
10133 $sql =
'UPDATE '.MAIN_DB_PREFIX.$table.
' SET fk_product = '.((int) $dest_id).
' WHERE fk_product = '.((int) $origin_id);
10135 if (!$dbs->
query($sql)) {
10136 if ($ignoreerrors) {
10160 public function defineBuyPrice($unitPrice = 0.0, $discountPercent = 0.0, $fk_product = 0, $qty = 0)
10166 if (($unitPrice > 0) && (isset(
$conf->global->ForceBuyingPriceIfNull) &&
getDolGlobalInt(
'ForceBuyingPriceIfNull') > 0)) {
10168 $buyPrice = $unitPrice * (1 - $discountPercent / 100);
10171 if (!empty($fk_product) && $fk_product > 0) {
10174 require_once DOL_DOCUMENT_ROOT.
'/product/class/product.class.php';
10175 $product =
new Product($this->db);
10176 $result = $product->fetch($fk_product);
10177 if ($result <= 0) {
10178 $this->errors[] =
'ErrorProductIdDoesNotExists';
10181 if ($product->cost_price > 0) {
10182 $buyPrice = $product->cost_price;
10183 } elseif ($product->pmp > 0) {
10184 $buyPrice = $product->pmp;
10187 require_once DOL_DOCUMENT_ROOT.
'/product/class/product.class.php';
10188 $product =
new Product($this->db);
10189 $result = $product->fetch($fk_product);
10190 if ($result <= 0) {
10191 $this->errors[] =
'ErrorProductIdDoesNotExists';
10194 if ($product->pmp > 0) {
10195 $buyPrice = $product->pmp;
10199 if (empty($buyPrice) && in_array(
getDolGlobalString(
'MARGIN_TYPE'), array(
'1',
'pmp',
'costprice'))) {
10200 require_once DOL_DOCUMENT_ROOT.
'/fourn/class/fournisseur.product.class.php';
10202 $result = $productFournisseur->find_min_price_product_fournisseur($fk_product, $qty);
10203 if ($result == 0 && $qty > 0) {
10205 $result = $productFournisseur->find_min_price_product_fournisseur($fk_product);
10208 $buyPrice = $productFournisseur->fourn_unitprice;
10209 } elseif ($result < 0) {
10210 $this->errors[] = $productFournisseur->error;
10217 return (
float) $buyPrice;
10230 return array(
'dir' =>
'',
'file' =>
'',
'originalfile' =>
'',
'altfile' =>
'',
'email' =>
'',
'capture' =>
'');
10254 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')
10257 global $user, $langs;
10259 include_once DOL_DOCUMENT_ROOT.
'/core/lib/files.lib.php';
10260 include_once DOL_DOCUMENT_ROOT.
'/core/lib/images.lib.php';
10261 include_once DOL_DOCUMENT_ROOT.
'/core/class/link.class.php';
10263 $sortfield =
'position_name';
10264 $sortorder =
'asc';
10269 $dir .=
get_exdir(0, 0, 0, 0, $this, $modulepart);
10270 $pdir .=
get_exdir(0, 0, 0, 0, $this, $modulepart);
10273 if ($modulepart ==
'product') {
10275 $dir = $sdir.
'/'.
get_exdir($this->
id, 2, 0, 0, $this, $modulepart).$this->id.
"/photos/";
10276 $pdir =
'/'.get_exdir($this->
id, 2, 0, 0, $this, $modulepart).$this->id.
"/photos/";
10279 if ($modulepart ==
'category') {
10280 $dir = $sdir.
'/'.
get_exdir($this->
id, 2, 0, 0, $this, $modulepart).$this->id.
"/photos/";
10281 $pdir =
'/'.get_exdir($this->
id, 2, 0, 0, $this, $modulepart).$this->id.
"/photos/";
10287 $relativedir = preg_replace(
'/^'.preg_quote(DOL_DATA_ROOT,
'/').
'/',
'', $dir);
10288 $relativedir = preg_replace(
'/^[\\/]/',
'', $relativedir);
10289 $relativedir = preg_replace(
'/[\\/]$/',
'', $relativedir);
10292 $dirthumb = $dir.
'thumbs/';
10293 $pdirthumb = $pdir.
'thumbs/';
10295 $return =
'<!-- Photo -->'.
"\n";
10298 $filearray =
dol_dir_list($dir,
"files", 0,
'',
'(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) ==
'desc' ? SORT_DESC : SORT_ASC), 1);
10307 '@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';
10309 $useLinkPathPhoto =
false;
10312 $link =
new Link($this->db);
10314 $link->fetchAll($links,
'product', $this->
id);
10316 if (count($links) > 0) {
10317 $useLinkPathPhoto =
true;
10320 if ($useLinkPathPhoto) {
10322 if ($nbbyrow > 0) {
10323 $return .=
'<table class="valigntop center centpercent" style="border:0; padding:2px; border-spacing:2px; border-collapse: separate;">';
10327 foreach ($links as $link) {
10328 if (!empty($link->url) && preg_match(
'/\.(jpg|jpeg|png|gif|webp)$/i', $link->url)) {
10333 if ($nbbyrow > 0 && ($i % $nbbyrow == 1)) {
10334 $return .=
'<tr class="center valignmiddle">';
10337 if ($nbbyrow > 0) {
10338 $return .=
'<td style="width:'.ceil(100 / $nbbyrow).
'%" class="photo">';
10340 $return .=
'<div class="inline-block">';
10343 $return .=
'<img class="photo photowithmargin'.($addphotorefcss ?
' '.$addphotorefcss :
'').
'"'.($maxHeight ?
' height="'.$maxHeight.
'"' :
'').
' src="'.$url.
'" title="External image">';
10345 if ($nbbyrow > 0) {
10346 $return .=
'</td>';
10347 if ($i % $nbbyrow == 0) {
10348 $return .=
'</tr>';
10351 $return .=
'</div>';
10354 if ($nbmax && $nbphoto >= $nbmax) {
10360 if ($nbbyrow > 0) {
10361 while ($i % $nbbyrow) {
10362 $return .=
'<td style="width:'.ceil(100 / $nbbyrow).
'%"> </td>';
10366 $return .=
'</table>';
10372 if (count($filearray)) {
10373 if ($sortfield && $sortorder) {
10374 $filearray =
dol_sort_array($filearray, $sortfield, $sortorder);
10377 foreach ($filearray as $key => $val) {
10379 $file = $val[
'name'];
10385 $viewfilename = $file;
10387 if ($size == 1 || $size ==
'small') {
10393 $pdirthumb = $pdir;
10394 $photo_vignette = basename($file);
10400 if ($nbbyrow > 0) {
10401 if ($nbphoto == 1) {
10402 $return .=
'<table class="valigntop center centpercent" style="border: 0; padding: 2px; border-spacing: 2px; border-collapse: separate;">';
10405 if ($nbphoto % $nbbyrow == 1) {
10406 $return .=
'<tr class="center valignmiddle" style="border: 1px">';
10408 $return .=
'<td style="width: '.ceil(100 / $nbbyrow).
'%" class="photo">'.
"\n";
10409 } elseif ($nbbyrow < 0) {
10410 $return .=
'<div class="inline-block">'.
"\n";
10413 $relativefile = preg_replace(
'/^\//',
'', $pdir.$photo);
10414 if (empty($nolink)) {
10416 if ($urladvanced) {
10417 $return .=
'<a href="'.$urladvanced.
'">';
10419 $return .=
'<a href="'.DOL_URL_ROOT.
'/viewimage.php?modulepart='.$modulepart.
'&entity='.$this->entity.
'&file='.urlencode($pdir.$photo).
'" class="aphoto" target="_blank" rel="noopener noreferrer">';
10425 $alt = $langs->transnoentitiesnoconv(
'File').
': '.$relativefile;
10426 $alt .=
' - '.$langs->transnoentitiesnoconv(
'Size').
': '.$imgarray[
'width'].
'x'.$imgarray[
'height'];
10427 if ($overwritetitle) {
10428 if (is_numeric($overwritetitle)) {
10431 $alt = $overwritetitle;
10434 if (empty($cache) && !empty($val[
'label'])) {
10437 $cache = $val[
'label'];
10439 if ($usesharelink) {
10440 if (array_key_exists(
'share', $val) && $val[
'share']) {
10441 if (empty($maxHeight) || ($photo_vignette && $imgarray[
'height'] > $maxHeight)) {
10442 $return .=
'<!-- Show original file (thumb not yet available with shared links) -->';
10443 $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).
'">';
10445 $return .=
'<!-- Show original file -->';
10446 $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).
'">';
10449 $return .=
'<!-- Show nophoto file (because file is not shared) -->';
10450 $return .=
'<img class="photo photowithmargin'.($addphotorefcss ?
' '.$addphotorefcss :
'').
'" height="'.$maxHeight.
'" src="'.DOL_URL_ROOT.
'/public/theme/common/nophoto.png" title="'.
dol_escape_htmltag($alt).
'">';
10453 if (empty($maxHeight) || ($photo_vignette && $imgarray[
'height'] > $maxHeight)) {
10454 $return .=
'<!-- Show thumb -->';
10455 $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).
'">';
10457 $return .=
'<!-- Show original file -->';
10458 $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).
'">';
10462 if (empty($nolink)) {
10466 if ($showfilename) {
10467 $return .=
'<br>'.$viewfilename;
10472 if ($photo_vignette && (
image_format_supported($photo) > 0) && ((isset($imgarray[
'width']) && $imgarray[
'width'] > $maxWidth) || (isset($imgarray[
'width']) && $imgarray[
'width'] > $maxHeight))) {
10473 $return .=
'<a href="'.$_SERVER[
"PHP_SELF"].
'?id='.$this->
id.
'&action=addthumb&token='.
newToken().
'&file='.urlencode($pdir.$viewfilename).
'">'.
img_picto($langs->trans(
'GenerateThumb'),
'refresh').
' </a>';
10476 if ($modulepart ==
'product' && ($user->hasRight(
'produit',
'creer') || $user->hasRight(
'service',
'creer'))) {
10478 $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> ';
10481 $return .=
'<a href="'.$_SERVER[
"PHP_SELF"].
'?id='.$this->
id.
'&action=delete&token='.
newToken().
'&file='.urlencode($pdir.$viewfilename).
'">';
10487 if ($nbbyrow > 0) {
10488 $return .=
'</td>';
10489 if (($nbphoto % $nbbyrow) == 0) {
10490 $return .=
'</tr>';
10492 } elseif ($nbbyrow < 0) {
10493 $return .=
'</div>'.
"\n";
10497 if (empty($size)) {
10498 $return .=
'<img class="photo photowithmargin" src="'.DOL_URL_ROOT.
'/viewimage.php?modulepart='.$modulepart.
'&entity='.$this->entity.
'&file='.urlencode($pdir.$photo).
'">';
10500 if ($showfilename) {
10501 $return .=
'<br>'.$viewfilename;
10505 if ($modulepart ==
'product' && ($user->hasRight(
'produit',
'creer') || $user->hasRight(
'service',
'creer'))) {
10507 $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> ';
10510 $return .=
'<a href="'.$_SERVER[
"PHP_SELF"].
'?id='.$this->
id.
'&action=delete&token='.
newToken().
'&file='.urlencode($pdir.$viewfilename).
'">';
10517 if ($nbmax && $nbphoto >= $nbmax) {
10523 if ($size == 1 || $size ==
'small') {
10524 if ($nbbyrow > 0) {
10526 while ($nbphoto % $nbbyrow) {
10527 $return .=
'<td style="width: '.ceil(100 / $nbbyrow).
'%"> </td>';
10532 $return .=
'</table>';
10538 $this->nbphoto = $nbphoto;
10552 if (is_array($info)) {
10553 if (isset($info[
'type']) && $info[
'type'] ==
'array') {
10570 if (isset($info[
'type']) && ($info[
'type'] ==
'date' || $info[
'type'] ==
'datetime' || $info[
'type'] ==
'timestamp')) {
10584 if (is_array($info)) {
10585 if (isset($info[
'type']) && ($info[
'type'] ==
'duration')) {
10603 if (is_array($info)) {
10604 if (isset($info[
'type']) && (preg_match(
'/^(?:tiny|small|medium|big)?int|int$/i', $info[
'type']))) {
10622 if (is_array($info)) {
10623 if (isset($info[
'type']) && (preg_match(
'/^(double|real|price)/i', $info[
'type']))) {
10640 if (is_array($info)) {
10641 if (isset($info[
'type']) && $info[
'type'] ==
'text') {
10658 if (is_array($info)) {
10659 if (array_key_exists(
'notnull', $info) && $info[
'notnull'] !=
'1') {
10676 if (is_array($info)) {
10677 if (array_key_exists(
'notnull', $info) && $info[
'notnull'] ==
'-1') {
10694 if (is_array($info)) {
10695 if (array_key_exists(
'index', $info) && $info[
'index'] ==
true) {
10718 $queryarray = array();
10719 foreach ($this->fields as $field => $info) {
10721 if ($this->isDate($info)) {
10722 if (empty($this->{$field})) {
10723 $queryarray[$field] =
null;
10725 $queryarray[$field] = $this->db->idate($this->{$field});
10727 } elseif ($this->isDuration($info)) {
10729 if ((isset($this->{$field}) && $this->{$field} !=
'') || !empty($info[
'notnull'])) {
10730 if (!isset($this->{$field})) {
10731 if (!empty($info[
'default'])) {
10732 $queryarray[$field] = $info[
'default'];
10734 $queryarray[$field] = 0;
10737 $queryarray[$field] = (int) $this->{$field};
10740 $queryarray[$field] =
null;
10742 } elseif ($this->isInt($info) || $this->isFloat($info)) {
10743 if ($field ==
'entity' && is_null($this->{$field})) {
10744 $queryarray[$field] = ((int)
$conf->entity);
10747 if ((isset($this->{$field}) && ((
string) $this->{$field}) !=
'') || !empty($info[
'notnull'])) {
10748 if (!isset($this->{$field})) {
10749 $queryarray[$field] = 0;
10750 } elseif ($this->isInt($info)) {
10751 $queryarray[$field] = (int) $this->{$field};
10752 } elseif ($this->isFloat($info)) {
10753 $queryarray[$field] = (float) $this->{$field};
10756 $queryarray[$field] =
null;
10762 $queryarray[$field] = $this->{$field};
10765 if (is_array($info) && array_key_exists(
'type', $info) && !empty($info[
'type']) && $info[
'type'] ==
'timestamp' && empty($queryarray[$field])) {
10766 unset($queryarray[$field]);
10768 if (!empty($info[
'notnull']) && $info[
'notnull'] == -1 && empty($queryarray[$field])) {
10769 $queryarray[$field] =
null;
10773 return $queryarray;
10786 foreach ($this->fields as $field => $info) {
10787 if ($this->isDate($info)) {
10788 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') {
10789 $this->$field =
'';
10791 $this->$field =
$db->jdate($obj->$field);
10793 } elseif ($this->isInt($info)) {
10794 if ($field ==
'rowid') {
10795 $this->
id = (int) $obj->$field;
10797 if ($this->isForcedToNullIfZero($info)) {
10798 if (empty($obj->$field)) {
10799 $this->$field =
null;
10801 $this->$field = (int) $obj->$field;
10804 if (isset($obj->$field) && (!is_null($obj->$field) || (array_key_exists(
'notnull', $info) && $info[
'notnull'] == 1))) {
10805 $this->$field = (int) $obj->$field;
10807 $this->$field =
null;
10811 } elseif ($this->isFloat($info)) {
10812 if ($this->isForcedToNullIfZero($info)) {
10813 if (empty($obj->$field)) {
10814 $this->$field =
null;
10816 $this->$field = (float) $obj->$field;
10819 if (isset($obj->$field) && (!is_null($obj->$field) || (array_key_exists(
'notnull', $info) && $info[
'notnull'] == 1))) {
10820 $this->$field = (float) $obj->$field;
10822 $this->$field =
null;
10826 $this->$field = isset($obj->$field) ? $obj->$field :
null;
10831 if (!isset($this->fields[
'ref']) && isset($this->
id)) {
10842 foreach ($this->fields as $field => $arr) {
10843 $this->$field =
null;
10856 $keys = array_keys($this->fields);
10857 if (!empty($alias)) {
10858 $keys_with_alias = array();
10859 foreach ($keys as $fieldname) {
10860 if (!empty($excludefields)) {
10861 if (in_array($fieldname, $excludefields)) {
10865 $keys_with_alias[] = $this->db->sanitize($alias .
'.' . $fieldname);
10867 return implode(
', ', $keys_with_alias);
10869 return implode(
', ', $keys);
10880 protected function quote($value, $fieldsentry)
10882 if (is_null($value)) {
10884 } elseif (preg_match(
'/^(int|double|real|price)/i', $fieldsentry[
'type'])) {
10886 } elseif (preg_match(
'/int$/i', $fieldsentry[
'type'])) {
10887 return (
int) $value;
10888 } elseif ($fieldsentry[
'type'] ==
'boolean') {
10895 return "'".$this->db->escape($value).
"'";
10912 dol_syslog(get_class($this).
"::createCommon create", LOG_DEBUG);
10918 $fieldvalues = $this->setSaveQuery();
10922 if (array_key_exists(
'date_creation', $fieldvalues) && empty($fieldvalues[
'date_creation'])) {
10923 $fieldvalues[
'date_creation'] = $this->db->idate($now);
10924 $this->date_creation = $this->db->idate($now);
10927 if (array_key_exists(
'fk_user_creat', $fieldvalues) && !($fieldvalues[
'fk_user_creat'] > 0)) {
10928 $fieldvalues[
'fk_user_creat'] = $user->id;
10929 $this->fk_user_creat = $user->id;
10931 if (array_key_exists(
'user_creation_id', $fieldvalues) && !($fieldvalues[
'user_creation_id'] > 0)) {
10932 $fieldvalues[
'user_creation_id'] = $user->id;
10933 $this->user_creation_id = $user->id;
10935 if (array_key_exists(
'pass_crypted', $fieldvalues) && property_exists($this,
'pass')) {
10937 $tmparray =
dol_hash($this->pass,
'0', 0, 1);
10938 $fieldvalues[
'pass_crypted'] = $tmparray[
'pass_encrypted'];
10939 if (array_key_exists(
'pass_encoding', $fieldvalues) && property_exists($this,
'pass_encoding')) {
10940 $fieldvalues[
'pass_encoding'] = $tmparray[
'pass_encoding'];
10943 if (array_key_exists(
'ref', $fieldvalues)) {
10946 if (
getDolGlobalString(
'MAIN_DISABLE_AUTO_UPDATE_OF_TMS_FIELDS') && array_key_exists(
'tms', $fieldvalues)) {
10947 $fieldvalues[
'tms'] = $this->db->idate($now);
10950 unset($fieldvalues[
'rowid']);
10952 $sanitized_keys = array();
10953 $sanitized_values = array();
10954 foreach ($fieldvalues as $k => $v) {
10955 $sanitized_keys[$k] = $k;
10956 $value = $this->fields[$k];
10958 $sanitized_values[$k] = $this->quote($v, $value);
10962 foreach ($sanitized_keys as $key) {
10963 if (!isset($this->fields[$key])) {
10966 $key_fields = $this->fields[$key];
10969 if (preg_match(
'/^integer:/i', $key_fields[
'type']) && $sanitized_values[$key] ==
'-1') {
10970 $sanitized_values[$key] =
'';
10972 if (!empty($key_fields[
'foreignkey']) && $sanitized_values[$key] ==
'-1') {
10973 $sanitized_values[$key] =
'';
10976 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']))) {
10979 if (empty($langs)) {
10980 require_once DOL_DOCUMENT_ROOT.
'/core/class/translate.class.php';
10982 $langs->setDefaultLang();
10983 $langs->load(
"errors");
10985 dol_syslog(
"Mandatory field '".$key.
"' is empty and required into ->fields definition of class");
10986 $this->errors[] = $langs->trans(
"ErrorFieldRequired", isset($key_fields[
'label']) ? $key_fields[
'label'] : $key);
10990 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'])) {
10991 $sanitized_values[$key] = $this->quote($key_fields[
'default'], $key_fields);
10995 if (isset($key_fields[
'type']) && preg_match(
'/^integer:/i', $key_fields[
'type']) && empty($sanitized_values[$key])) {
10996 if (isset($key_fields[
'default'])) {
10997 $sanitized_values[$key] = ((int) $key_fields[
'default']);
10999 $sanitized_values[$key] =
'null';
11002 if (!empty($key_fields[
'foreignkey']) && empty($sanitized_values[$key])) {
11003 $sanitized_values[$key] =
'null';
11011 $this->db->begin();
11014 $sql =
"INSERT INTO ".$this->db->prefix().$this->db->sanitize($this->table_element);
11015 $sql .=
" (".implode(
", ", $sanitized_keys).
')';
11016 $sql .=
" VALUES (".implode(
", ", $sanitized_values).
")";
11018 $res = $this->db->query($sql);
11021 if ($this->db->lasterrno() ==
'DB_ERROR_RECORD_ALREADY_EXISTS') {
11022 $this->errors[] =
"ErrorRefAlreadyExists";
11024 $this->errors[] = $this->db->lasterror();
11030 $this->
id = $this->db->last_insert_id($this->db->prefix().$this->table_element);
11036 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)') {
11037 $sql =
"UPDATE ".$this->db->prefix().$this->db->sanitize($this->table_element);
11038 $sql .=
" SET ref = '(PROV".((int) $this->
id).
")' WHERE (ref = '(PROV)' OR ref = '') AND rowid = ".((int) $this->
id);
11039 $resqlupdate = $this->db->query($sql);
11041 if ($resqlupdate ===
false) {
11043 $this->errors[] = $this->db->lasterror();
11045 $this->
ref =
'(PROV'.$this->id.
')';
11052 $result = $this->insertExtraFields();
11059 if (!empty($this->table_element_line) && !empty($this->fk_element) && !empty($this->lines)) {
11060 foreach ($this->lines as $line) {
11061 $keyforparent = $this->fk_element;
11066 if (!is_object($line)) {
11067 $line = (object) $line;
11071 if (method_exists($line,
'insert')) {
11072 $result = $line->insert($user, 1);
11073 } elseif (method_exists($line,
'create')) {
11074 $result = $line->create($user, 1);
11077 $this->error = $line->error;
11078 $this->db->rollback();
11085 if (!$error && !$notrigger) {
11087 $result = $this->call_trigger(strtoupper(get_class($this)).
'_CREATE', $user);
11096 $this->db->rollback();
11099 $this->db->commit();
11116 if (empty(
$id) && empty($ref) && empty($morewhere)) {
11120 $fieldlist = $this->getFieldList(
't');
11121 if (empty($fieldlist)) {
11125 $sql =
"SELECT ".$this->db->sanitize($fieldlist, 0, 0, 1);
11126 $sql .=
" FROM ".$this->db->prefix().$this->table_element.
' as t';
11129 $sql .=
' WHERE t.rowid = '.((int)
$id);
11130 } elseif (!empty($ref)) {
11131 $sql .=
" WHERE t.ref = '".$this->db->escape($ref).
"'";
11133 $sql .=
' WHERE 1 = 1';
11135 if (empty(
$id) && isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
11136 $sql .=
' AND t.entity IN ('.getEntity($this->element).
')';
11139 $sql .= $morewhere;
11141 $sql .=
' LIMIT 1';
11143 $res = $this->db->query($sql);
11145 $obj = $this->db->fetch_object($res);
11147 $this->setVarsFromFetchObj($obj);
11151 if (empty($noextrafields)) {
11152 $result = $this->fetch_optionals();
11154 $this->error = $this->db->lasterror();
11155 $this->errors[] = $this->error;
11165 $this->error = $this->db->lasterror();
11166 $this->errors[] = $this->error;
11180 $objectlineclassname = get_class($this).
'Line';
11181 if (!class_exists($objectlineclassname)) {
11182 $this->error =
'Error, class '.$objectlineclassname.
' not found during call of fetchLinesCommon';
11186 $objectline =
new $objectlineclassname($this->db);
11187 '@phan-var-force CommonObjectLine $objectline';
11189 $sql =
"SELECT ".$objectline->getFieldList(
'l');
11190 $sql .=
" FROM ".$this->db->prefix().$this->db->sanitize($objectline->table_element).
" as l";
11191 $sql .=
" WHERE l.fk_".$this->db->sanitize($this->element).
" = ".((int) $this->
id);
11193 $sql .= $morewhere;
11195 if (isset($objectline->fields[
'position'])) {
11196 $sql .= $this->db->order(
'position',
'ASC');
11199 $resql = $this->db->query($sql);
11201 $num_rows = $this->db->num_rows($resql);
11203 $this->lines = array();
11204 while ($i < $num_rows) {
11205 $obj = $this->db->fetch_object($resql);
11207 $newline =
new $objectlineclassname($this->db);
11208 '@phan-var-force CommonObjectLine $newline';
11209 $newline->setVarsFromFetchObj($obj);
11212 if (empty($noextrafields)) {
11213 $newline->fetch_optionals();
11216 $this->lines[] = $newline;
11223 $this->error = $this->db->lasterror();
11224 $this->errors[] = $this->error;
11238 dol_syslog(get_class($this).
"::updateCommon update", LOG_DEBUG);
11250 $fieldvalues = $this->setSaveQuery();
11254 if (array_key_exists(
'date_modification', $fieldvalues)) {
11255 $fieldvalues[
'date_modification'] = $this->db->idate($now);
11257 if (
getDolGlobalString(
'MAIN_DISABLE_AUTO_UPDATE_OF_TMS_FIELDS') && array_key_exists(
'tms', $fieldvalues)) {
11258 $fieldvalues[
'tms'] = $this->db->idate($now);
11260 if (array_key_exists(
'fk_user_modif', $fieldvalues)) {
11261 $fieldvalues[
'fk_user_modif'] = $user->id;
11263 if (array_key_exists(
'user_modification_id', $fieldvalues)) {
11264 $fieldvalues[
'user_modification_id'] = $user->id;
11267 if (array_key_exists(
'pass_crypted', $fieldvalues) && property_exists($this,
'pass') && !empty($this->pass)) {
11269 $tmparray =
dol_hash($this->pass,
'0', 0, 1);
11270 $fieldvalues[
'pass_crypted'] = $tmparray[
'pass_encrypted'];
11271 if (array_key_exists(
'pass_encoding', $fieldvalues) && property_exists($this,
'pass_encoding')) {
11272 $fieldvalues[
'pass_encoding'] = $tmparray[
'pass_encoding'];
11275 if (array_key_exists(
'ref', $fieldvalues)) {
11279 unset($fieldvalues[
'rowid']);
11284 $sanitized_tmp = array();
11285 foreach ($fieldvalues as $k => $v) {
11287 $value = $this->fields[$k];
11289 $values[$k] = $this->quote($v, $value);
11290 if ((!empty($value[
"type"]) && $value[
"type"] ==
"text") && !empty($value[
'arrayofkeyval']) && is_array($value[
'arrayofkeyval'])) {
11292 $v = preg_replace(
'/\s/',
',', $v);
11293 $v = preg_replace(
'/,+/',
',', $v);
11296 $sanitized_tmp[] = $this->db->sanitize($k).
'='.$this->quote($v, $this->fields[$k]);
11300 foreach ($keys as $key) {
11301 if (!empty($this->fields[$key][
'type']) && preg_match(
'/^integer:/i', $this->fields[$key][
'type']) && $values[$key] ==
'-1') {
11302 $values[$key] =
'';
11304 if (!empty($this->fields[$key][
'foreignkey']) && $values[$key] ==
'-1') {
11305 $values[$key] =
'';
11317 $sql =
"UPDATE ".$this->db->prefix().$this->db->sanitize($this->table_element);
11318 $sql.=
" SET ".implode(
', ', $sanitized_tmp);
11319 $sql.=
" WHERE rowid = ".((int) $this->
id);
11321 $this->db->begin();
11324 $res = $this->db->query($sql);
11327 $this->errors[] = $this->db->lasterror();
11333 $result = $this->insertExtraFields();
11340 if (!$error && !$notrigger) {
11342 $result = $this->call_trigger(strtoupper(get_class($this)).
'_MODIFY', $user);
11351 $this->db->rollback();
11354 $this->db->commit();
11369 dol_syslog(get_class($this).
"::deleteCommon delete", LOG_DEBUG);
11373 $this->db->begin();
11375 if ($forcechilddeletion) {
11376 foreach ($this->childtables as $table) {
11377 $sql =
"DELETE FROM ".$this->db->prefix().$this->db->sanitize($table);
11378 $sql .=
" WHERE ".$this->db->sanitize($this->fk_element).
" = ".((int) $this->
id);
11379 $resql = $this->db->query($sql);
11381 $this->error = $this->db->lasterror();
11382 $this->errors[] = $this->error;
11383 $this->db->rollback();
11387 } elseif (!empty($this->childtables)) {
11388 $objectisused = $this->isObjectUsed($this->
id);
11389 if (!empty($objectisused)) {
11390 dol_syslog(get_class($this).
"::deleteCommon Can't delete record as it has some child", LOG_WARNING);
11391 $this->error =
'ErrorRecordHasChildren';
11392 $this->errors[] = $this->error;
11393 $this->db->rollback();
11399 if (is_array($this->childtablesoncascade) && !empty($this->childtablesoncascade)) {
11400 foreach ($this->childtablesoncascade as $tabletodelete) {
11401 $deleteFromObject = explode(
':', $tabletodelete, 4);
11402 if (count($deleteFromObject) >= 2) {
11403 $className = str_replace(
'@',
'', $deleteFromObject[0]);
11404 $filePath = $deleteFromObject[1];
11405 $columnName = $deleteFromObject[2];
11407 if (!empty($deleteFromObject[3])) {
11408 $filter = $deleteFromObject[3];
11412 $childObject =
new $className($this->db);
11413 if (method_exists($childObject,
'deleteByParentField')) {
11414 '@phan-var-force CommonObject $childObject';
11415 $result = $childObject->deleteByParentField($this->
id, $columnName, $filter);
11418 $this->errors[] = $childObject->error;
11423 $this->errors[] =
"You defined a cascade delete on an object $className/$this->id but there is no method deleteByParentField for it";
11428 $this->errors[] =
'Cannot include child class file '.$filePath;
11433 $sql =
"DELETE FROM ".$this->db->prefix().$this->db->sanitize($tabletodelete).
" WHERE ".$this->db->sanitize($this->fk_element).
" = ".((int) $this->
id);
11435 $resql = $this->db->query($sql);
11438 $this->error = $this->db->lasterror();
11439 $this->errors[] = $this->error;
11449 $result = $this->call_trigger(strtoupper(get_class($this)).
'_DELETE', $user);
11459 $res = $this->deleteEcmFiles(1);
11468 require_once DOL_DOCUMENT_ROOT .
'/core/lib/files.lib.php';
11471 $this->errors[] =
'ErrorFailToDeleteDir';
11477 $res = $this->deleteObjectLinked();
11482 if (!$error && !empty($this->isextrafieldmanaged)) {
11483 $result = $this->deleteExtraFields();
11490 $sql =
"DELETE FROM ".$this->db->prefix().$this->db->sanitize($this->table_element);
11491 $sql .=
" WHERE rowid = ".((int) $this->
id);
11493 $resql = $this->db->query($sql);
11496 $this->errors[] = $this->db->lasterror();
11502 $this->db->rollback();
11505 $this->db->commit();
11530 if (!empty($parentId) && !empty($parentField)) {
11531 if (empty($this->table_element)) {
11532 $this->error =
'Property table_element for object is not defined';
11533 $this->errors[] = $this->error;
11537 if (!method_exists($this,
'fetch')) {
11538 $this->error =
'Method fetch for object is not defined';
11539 $this->errors[] = $this->error;
11543 if (!method_exists($this,
'delete')) {
11544 $this->error =
'Method delete for object is not defined';
11545 $this->errors[] = $this->error;
11550 $this->db->begin();
11552 $sql =
"SELECT rowid FROM ".$this->db->prefix().$this->db->sanitize($this->table_element);
11553 $sql .=
" WHERE ".$this->db->sanitize($parentField).
" = ".(int) $parentId;
11556 $errormessage =
'';
11558 if ($errormessage) {
11559 $this->errors[] = $errormessage;
11560 dol_syslog(__METHOD__.
' '.implode(
',', $this->errors), LOG_ERR);
11564 $resql = $this->db->query($sql);
11566 $this->errors[] = $this->db->lasterror();
11569 while ($obj = $this->db->fetch_object($resql)) {
11570 $result = $this->fetch($obj->rowid);
11573 $this->errors[] = $this->error;
11575 $result = $this->
delete($user);
11578 $this->errors[] = $this->error;
11586 if (empty($error)) {
11587 $this->db->commit();
11590 $this->error = implode(
', ', $this->errors);
11591 $this->db->rollback();
11592 return $error * -1;
11608 if (!($this->
id > 0) || empty($this->table_element_line) || empty($this->fk_element)) {
11612 $sql =
"SELECT rowid FROM ".$this->db->prefix().$this->db->sanitize($this->table_element_line);
11613 $sql .=
" WHERE rowid = ".((int) $lineid).
" AND ".$this->db->sanitize($this->fk_element).
" = ".((int) $this->
id);
11614 $resql = $this->db->query($sql);
11616 return ($resql && $this->db->num_rows($resql) > 0);
11631 $tmpforobjectclass = get_class($this);
11632 $tmpforobjectlineclass = ucfirst($tmpforobjectclass).
'Line';
11634 if ($this->
id > 0 && !empty($this->fk_element)) {
11636 $sql =
"SELECT rowid FROM ".$this->db->prefix().$this->table_element_line;
11637 $sql .=
" WHERE rowid = ".((int) $idline).
" AND ".$this->db->sanitize($this->fk_element).
" = ".((int) $this->
id);
11638 $resql = $this->db->query($sql);
11639 if (!$resql || !$this->db->num_rows($resql)) {
11640 $this->error =
'ErrorLineIDDoesNotMatchWithObjectID';
11645 $this->db->begin();
11648 $result = $this->call_trigger(
'LINE'.strtoupper($tmpforobjectclass).
'_DELETE', $user);
11654 if (empty($error)) {
11655 $sql =
"DELETE FROM ".$this->db->prefix().$this->db->sanitize($this->table_element_line);
11656 $sql .=
" WHERE rowid = ".((int) $idline);
11658 $resql = $this->db->query($sql);
11660 $this->error =
"Error ".$this->db->lasterror();
11665 if (empty($error)) {
11667 $tmpobjectline =
new $tmpforobjectlineclass($this->db);
11668 '@phan-var-force CommonObjectLine $tmpobjectline';
11669 if (!isset($tmpobjectline->isextrafieldmanaged) || !empty($tmpobjectline->isextrafieldmanaged)) {
11670 $tmpobjectline->id = $idline;
11671 $result = $tmpobjectline->deleteExtraFields();
11674 $this->error =
"Error ".get_class($this).
"::deleteLineCommon deleteExtraFields error -4 ".$tmpobjectline->error;
11679 if (empty($error)) {
11680 $this->db->commit();
11683 dol_syslog(get_class($this).
"::deleteLineCommon ERROR:".$this->error, LOG_ERR);
11684 $this->db->rollback();
11704 $this->db->begin();
11706 $statusfield =
'status';
11707 if (in_array($this->element, array(
'don',
'donation',
'shipping',
'project_task'))) {
11708 $statusfield =
'fk_statut';
11711 $sql =
"UPDATE ".$this->db->prefix().$this->db->sanitize($this->table_element);
11712 $sql .=
" SET ".$this->db->sanitize($statusfield).
" = ".((int) $status);
11713 $sql .=
" WHERE rowid = ".((int) $this->
id);
11715 if ($this->db->query($sql)) {
11717 $this->oldcopy = clone $this;
11720 if (!$error && !$notrigger) {
11722 $result = $this->call_trigger($triggercode, $user);
11729 $this->
status = $status;
11730 if (property_exists($this,
'statut')) {
11731 $this->statut = $status;
11733 $this->db->commit();
11736 $this->db->rollback();
11740 $this->error = $this->db->error();
11741 $this->db->rollback();
11757 $this->specimen = 1;
11759 'label' =>
'This is label',
11760 'ref' =>
'ABCD1234',
11761 'description' =>
'This is a description',
11763 'note_public' =>
'Public note',
11764 'note_private' =>
'Private note',
11765 'date_creation' => (
dol_now() - 3600 * 48),
11766 'date_modification' => (
dol_now() - 3600 * 24),
11767 'fk_user_creat' => $user->id,
11768 'fk_user_modif' => $user->id,
11771 foreach ($fields as $key => $value) {
11772 if (array_key_exists($key, $this->fields)) {
11773 $this->{$key} = $value;
11778 if (property_exists($this,
'fields')) {
11779 foreach ($this->fields as $key => $value) {
11781 if (array_key_exists($key, $fields)) {
11785 if (!empty($value[
'default'])) {
11786 $this->$key = $value[
'default'];
11804 require_once DOL_DOCUMENT_ROOT.
'/core/class/comment.class.php';
11806 $comment =
new Comment($this->db);
11807 $result = $comment->fetchAllFor($this->element, $this->
id);
11809 $this->setErrorsFromObject($comment);
11812 $this->comments = $comment->comments;
11814 return count($this->comments);
11824 return count($this->comments);
11835 if (!is_array($parameters)) {
11838 foreach ($parameters as $parameter) {
11839 if (isset($this->$parameter)) {
11840 $this->$parameter = trim($this->$parameter);
11859 require_once DOL_DOCUMENT_ROOT.
'/categories/class/categorie.class.php';
11863 $existing =
$c->containing($this->
id, $type_categ,
'id');
11883 if (!is_array($categories)) {
11884 $categories = array($categories);
11887 dol_syslog(get_class($this).
"::setCategoriesCommon Object Id:".$this->
id.
' type_categ:'.$type_categ.
' nb tag add:'.count($categories), LOG_DEBUG);
11889 require_once DOL_DOCUMENT_ROOT.
'/categories/class/categorie.class.php';
11891 if (empty($type_categ)) {
11892 dol_syslog(__METHOD__.
': Type '.$type_categ.
'is an unknown category type. Done nothing.', LOG_ERR);
11898 $existing =
$c->containing($this->
id, $type_categ,
'id');
11901 if (!is_array($existing)) {
11902 $existing = array();
11904 if ($remove_existing) {
11906 $to_del = array_diff($existing, $categories);
11907 $to_add = array_diff($categories, $existing);
11910 $to_add = array_diff($categories, $existing);
11917 foreach ($to_del as $del) {
11918 if (
$c->fetch($del) > 0) {
11919 $result =
$c->del_type($this, $type_categ);
11922 $this->error =
$c->error;
11923 $this->errors =
$c->errors;
11930 foreach ($to_add as $add) {
11931 if (
$c->fetch($add) > 0) {
11932 $result =
$c->add_type($this, $type_categ);
11935 $this->error =
$c->error;
11936 $this->errors =
$c->errors;
11944 return $error ? (-1 * $error) : $ok;
11957 $this->db->begin();
11959 if (empty($type)) {
11960 $type = $this->table_element;
11963 require_once DOL_DOCUMENT_ROOT.
'/categories/class/categorie.class.php';
11964 $categorystatic =
new Categorie($this->db);
11966 $tablename = $this->db->prefix().
"categorie_".(empty($categorystatic->MAP_CAT_TABLE[$type]) ? $type : $categorystatic->MAP_CAT_TABLE[$type]);
11967 $fkname =
'fk_' . (empty($categorystatic->MAP_CAT_FK[$type]) ? $type : $categorystatic->MAP_CAT_FK[$type]);
11969 $sql =
"INSERT INTO ".$this->db->sanitize($tablename).
" (fk_categorie, ".$this->db->sanitize($fkname).
")";
11970 $sql .=
" SELECT fk_categorie, ".((int) $toId).
" FROM ".$this->db->sanitize($tablename);
11971 $sql .=
" WHERE ".$this->db->sanitize($fkname).
" = ".((int) $fromId);
11973 if (!$this->db->query($sql)) {
11974 $this->error = $this->db->lasterror();
11975 $this->db->rollback();
11979 $this->db->commit();
11993 $this->db->begin();
11997 switch ($this->element) {
11999 $element =
'propale';
12002 $element =
'produit';
12004 case 'order_supplier':
12005 $element =
'fournisseur/commande';
12007 case 'invoice_supplier':
12010 $element =
'fournisseur/facture/'.get_exdir($this->
id, 2, 0, 1, $this,
'invoice_supplier');
12013 $element =
'expedition/sending';
12016 case 'project_task':
12017 require_once DOL_DOCUMENT_ROOT.
'/projet/class/task.class.php';
12019 $project_result = $this->fetchProject();
12020 if ($project_result >= 0) {
12021 $element =
'projet/'.dol_sanitizeFileName($this->project->ref).
'/';
12025 $element =
'contract';
12028 $element = $this->element;
12030 '@phan-var-force string $element';
12033 $sql =
"DELETE FROM ".$this->db->prefix().
"ecm_files_extrafields WHERE fk_object IN (";
12034 $sql .=
" SELECT rowid FROM ".$this->db->prefix().
"ecm_files WHERE filename LIKE '".$this->db->escape($this->
ref).
"%'";
12035 $sql .=
" AND filepath = '".$this->db->escape($element.
"/".$this->ref).
"' AND entity = ".((int)
$conf->entity);
12038 if (!$this->db->query($sql)) {
12039 $this->error = $this->db->lasterror();
12040 $this->db->rollback();
12045 $sql =
"DELETE FROM ".$this->db->prefix().
"ecm_files";
12046 $sql .=
" WHERE filename LIKE '".$this->db->escape($this->
ref).
"%'";
12047 $sql .=
" AND filepath = '".$this->db->escape($element.
"/".$this->ref).
"' AND entity = ".((int)
$conf->entity);
12049 if (!$this->db->query($sql)) {
12050 $this->error = $this->db->lasterror();
12051 $this->db->rollback();
12058 $sql =
'DELETE FROM '.$this->db->prefix().
"ecm_files_extrafields";
12059 $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).
")";
12060 $resql = $this->db->query($sql);
12062 $this->error = $this->db->lasterror();
12063 $this->db->rollback();
12067 $sql =
'DELETE FROM '.$this->db->prefix().
"ecm_files";
12068 $sql .=
" WHERE src_object_type = '".$this->db->escape($this->table_element.(empty($this->module) ?
"" :
"@".$this->module)).
"' AND src_object_id = ".((int) $this->
id);
12069 $resql = $this->db->query($sql);
12071 $this->error = $this->db->lasterror();
12072 $this->db->rollback();
12077 $this->db->commit();
12094 include_once DOL_DOCUMENT_ROOT.
'/product/class/product.class.php';
12097 $tmpproduct =
new Product($this->db);
12098 foreach ($this->lines as $line) {
12099 if ($line->fk_product > 0) {
12100 $tmpproduct->fetch($line->fk_product);
12101 $statustotest = ($status ==
'onsale' ?
'status' :
'status_buy');
12102 if (!$tmpproduct->$statustotest) {
12103 $langs->load(
'products');
12104 $statuskey4lang = ($status ==
'onsale' ?
'ProductStatusNotOnSell' :
'ProductStatusNotOnBuy');
12106 $this->errors[] = $langs->trans(
'ProductRef').
' '.$tmpproduct->ref.
' '.$langs->trans($statuskey4lang);
12112 $this->error =
'ErrorOneLineContainsADisactivatedProduct';
12128 $this->error = $message;
12129 $this->errors[] = $message;
12141 global $dolibarr_main_document_root;
12143 $this->setErrorWithoutLog($message);
12144 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
12145 $file = str_replace($dolibarr_main_document_root,
'', $trace[0][
'file'] ??
'file unknown');
12146 $line = $trace[0][
'line'] ??
'line unknown';
12147 $syslogMessage = sprintf(
'%s:%s %s', $file, $line, $message);
$id
Support class for third parties, contacts, members, users or resources.
if(! $sortfield) if(! $sortorder) $object
global $dolibarr_main_url_root
ajax_combobox($htmlname, $events=array(), $minLengthToAutocomplete=0, $forcefocus=0, $widthTypeOfAutocomplete='resolve', $idforemptyvalue='-1', $morecss='')
Convert a html select field into an ajax combobox.
Class to manage members of a foundation.
Class to manage categories.
Parent class of all other business classes (invoices, contracts, proposals, orders,...
fetch_optionals($rowid=null, $optionsArray=null)
Function to get extra fields of an object into $this->array_options This method is in most cases call...
getCategoriesCommon($type_categ)
Sets object to given categories.
indexFile($destfull, $update_main_doc_field)
Index a file into the ECM database.
getFormatedSupplierRef($objref)
Return supplier ref for screen output.
line_order($renum=false, $rowidorder='ASC', $fk_parent_line=true)
Save a new position (field rang) for details lines.
deleteLineCommon(User $user, $idline, $notrigger=0)
Delete a line of object in database.
isEmpty()
isEmpty We consider CommonObject isEmpty if this->id is empty
clearFieldError($fieldKey)
clear validation message result for a field
static getCountOfItemsLinkedByObjectID($fk_object_where, $field_where, $table_element)
Count items linked to an object id in association table.
deleteEcmFiles($mode=0)
Delete related files of object in database.
getLastMainDocLink($modulepart, $initsharekey=0, $relativelink=0)
Return the link of last main doc file for direct public download.
liste_type_contact($source='internal', $order='position', $option=0, $activeonly=0, $code='')
Return array with list of possible values for type of contacts.
getTooltipContent($params)
getTooltipContent
update_price($exclspec=0, $roundingadjust='auto', $nodatabaseupdate=0, $seller=null)
Update total_ht, total_ttc, total_vat, total_localtax1, total_localtax2 for an object (sum of lines).
swapContactStatus($rowid)
Update status of a contact linked to object.
getFieldError($fieldKey)
get field error message
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.
addThumbs($file, $quality=50)
Build thumb.
add_contact($fk_socpeople, $type_contact, $source='external', $notrigger=0)
Add a link between element $this->element and a contact.
cloneCategories($fromId, $toId, $type='')
Copy related categories to another object.
fetch_barcode()
Load data for barcode into properties ->barcode_type* Properties ->barcode_type that is id of barcode...
Class to manage absolute discounts.
Class to manage a WYSIWYG editor.
Class to manage Dolibarr database access.
Class to manage donations.
Class to manage ECM files.
const TYPE_CREDIT_NOTE
Credit note invoice.
Parent class of subscription templates.
Parent class to manage intervention document templates.
static getIdAndTxFromCode($dbs, $code, $date_document=0)
Get id and rate of currency from code.
Class to manage predefined suppliers products.
Class to manage products or services.
const TYPE_SERVICE
Service.
Class to manage projects.
Class to manage third parties objects (customers, suppliers, prospects...)
Class to manage translations.
Class to manage Dolibarr users.
Class toolbox to validate values.
print $langs trans("Ref").' m titre as m m statut as status
Or an array listing all the potential status of the object: array: int of the status => translated la...
getCountry($searchkey, $withcode='', $dbtouse=null, $outputlangs=null, $entconv=1, $searchlabel='')
Return country label, code or id from an id, code or label.
getState($id, $withcode='0', $dbtouse=null, $withregion=0, $outputlangs=null, $entconv=1)
Return state translated from an id.
convertSecondToTime($iSecond, $format='all', $lengthOfDay=86400, $lengthOfWeek=7)
Return, in clear text, value of a number of seconds in days, hours and minutes.
dol_meta_create($object)
Create a meta file with document file into same directory.
completeFileArrayWithDatabaseInfo(&$filearray, $relativedir, $object=null)
Complete $filearray with data from database.
dol_delete_file($file, $disableglob=0, $nophperrors=0, $nohook=0, $object=null, $allowdotdot=false, $indexdatabase=1, $nolog=0)
Remove a file or several files with a mask.
dol_delete_dir_recursive($dir, $count=0, $nophperrors=0, $onlysub=0, &$countdeleted=0, $indexdatabase=1, $nolog=0, $level=0)
Remove a directory $dir and its subdirectories (or only files and subdirectories)
dol_is_file($pathoffile)
Return if path is a file.
dol_dir_list($utf8_path, $types="all", $recursive=0, $filter="", $excludefilter=null, $sortcriteria="name", $sortorder=SORT_ASC, $mode=0, $nohook=0, $relativename="", $donotfollowsymlinks=0, $nbsecondsold=0)
Scan a directory and return a list of files/directories.
dol_is_dir($folder)
Test if filename is a directory.
dol_delete_preview($object)
Delete all preview files linked to object instance.
$date_start
Variables from include:
dol_now($mode='gmt')
Return date for now.
dol_mktime($hour, $minute, $second, $month, $day, $year, $gm='auto', $check=1)
Return a timestamp date built from detailed information (by default a local PHP server timestamp) Rep...
dol_print_email($email, $contactid=0, $socid=0, $addlink=0, $max=0, $showinvalid=2, $withpicto=0, $morecss='paddingrightonly')
Show EMail link formatted for HTML output.
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='', $noduplicate=0, $attop=0)
Set event messages in dol_events session object.
vatrate($rate, $addpercent=false, $info_bits=0, $usestarfornpr=0, $html=0)
Return a string with VAT rate label formatted for view output Used into pdf and HTML pages.
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.
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2, $allowothertags=array())
Show picto whatever it's its name (generic function)
img_delete($titlealt='default', $other='class="pictodelete"', $morecss='')
Show delete logo.
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.
img_object($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $allowothertags=array())
Show a picto called object_picto (generic function)
dol_print_url($url, $target='_blank', $max=32, $withpicto=0, $morecss='')
Show Url link.
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.
getPictoForType($key, $morecss='')
Return the picto for a data type.
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.
dolPrintHTMLForAttribute($s, $escapeonlyhtmltags=0, $allowothertags=array())
Return a string ready to be output into an HTML attribute (alt, title, data-html, ....
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.
yn($yesno, $format=1, $color=0)
Return yes or no in current language.
get_date_range($date_start, $date_end, $format='', $outputlangs=null, $withparenthesis=1)
Format output for start and end date.
getAdvancedPreviewUrl($modulepart, $relativepath, $alldata=0, $param='')
Return URL we can use for advanced preview links.
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_print_error($db=null, $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
dol_trunc($string, $size=40, $trunc='right', $stringencoding='UTF-8', $nodot=0, $display=0)
Truncate a string to a particular length adding '...' if string larger than length.
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.
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $noescapetags='', $escapeonlyhtmltags=0, $cleanalsojavascript=0)
Returns text escaped for inclusion in HTML alt or title or value tags, or into values of HTML input f...
vignette($file, $maxWidth=160, $maxHeight=120, $extName='_small', $quality=50, $outdir='thumbs', $targetformat=0)
Create a thumbnail from an image file (Supported extensions are gif, jpg, png and bmp).
if(!defined( 'IMAGETYPE_WEBP')) getDefaultImageSizes()
Return default values for image sizes.
dol_getImageSize($file, $url=false)
Return size of image file on disk (Supported extensions are gif, jpg, png, bmp and webp)
image_format_supported($file, $acceptsvg=0)
Return if a filename is file name of a supported image format.
query($query, $usesavepoint=0, $type='auto', $result_mode=0)
Execute a SQL request and return the resultset.
print $langs trans("Show") . '< td style="' . $timeColor . '" align="center"> s</td > badge status0 badge status4 badge status3 Error badge status8< td align="center">< span class="badge ' . $badge . '"></span ></td >< td align="center">< a href="#" class="button button-small" onclick="openLogModal(this)" data-req="' . dol_escape_htmltag($reqSafe) . '" data-res="' . dol_escape_htmltag($resSafe) . '" data-err="' . dol_escape_htmltag($errSafe) . '">< span class="fa fa-search-plus"></span ></a ></td ></tr >< tr >< td colspan="' . $colspan . '" class="opacitymedium"></td ></tr ></table ></div ></form > logModal none logModal none s a JSON string
buildzip.php
calcul_price_total($qty, $pu, $remise_percent_ligne, $txtva, $uselocaltax1_rate, $uselocaltax2_rate, $notused, $price_base_type, $info_bits, $type, $seller=null, $localtaxes_array=[], $progress=100, $multicurrency_tx=1, $pu_devise=0, $multicurrency_code='')
Calculate totals (net, vat, ...) of a line.
$conf db user
Active Directory does not allow anonymous connections.
if(preg_match('/(crypted|dolcrypt):/i', $dolibarr_main_db_pass)||!empty($dolibarr_main_db_encrypted_pass)) $conf db type
'integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter[:Sortfield]]]',...
getRandomPassword($generic=false, $replaceambiguouschars=null, $length=32)
Return a generated password using default module.
dol_hash($chain, $type='0', $nosalt=0, $mode=0)
Returns a hash (non reversible encryption) of a string.
dolDecrypt($chain, $key='', $patterntotest='')
Decode a string with a symmetric encryption.
dolEncrypt($chain, $key='', $ciphering='', $forceseed='', $obfuscationmode='dolcrypt')
Encode a string with a symmetric encryption.