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) {
1471 if ($this->
add_contact($contact[
'id'], $contact[
'code'], $contact[
'source']) < 0) {
1488 public function update_contact($rowid, $statut, $type_contact_id = 0, $fk_socpeople = 0)
1492 $sql =
"UPDATE ".$this->db->prefix().
"element_contact set";
1493 $sql .=
" statut = ".((int) $statut);
1494 if ($type_contact_id) {
1495 $sql .=
", fk_c_type_contact = ".((int) $type_contact_id);
1497 if ($fk_socpeople) {
1498 $sql .=
", fk_socpeople = ".((int) $fk_socpeople);
1500 $sql .=
" where rowid = ".((int) $rowid);
1502 $resql = $this->db->query($sql);
1506 $this->error = $this->db->lasterror();
1527 if ($this->
id > 0) {
1528 $sql =
"SELECT ec.rowid FROM ".$this->db->prefix().
"element_contact as ec, ".$this->db->prefix().
"c_type_contact as tc";
1529 $sql .=
" WHERE ec.rowid = ".((int) $rowid).
" AND ec.element_id = ".((int) $this->
id);
1530 $sql .=
" AND ec.fk_c_type_contact = tc.rowid AND tc.element = '".$this->db->escape($this->element).
"'";
1531 $resql = $this->db->query($sql);
1532 if (!$resql || !$this->db->num_rows($resql)) {
1533 $this->error =
'ErrorRecordNotFound';
1540 if (!$error && empty($notrigger)) {
1542 $this->context[
'contact_id'] = ((int) $rowid);
1543 $triggerPrefix = (empty($this->TRIGGER_PREFIX) ? strtoupper($this->element) : $this->TRIGGER_PREFIX);
1544 $result = $this->call_trigger($triggerPrefix.
'_DELETE_CONTACT', $user);
1552 dol_syslog(get_class($this).
"::delete_contact", LOG_DEBUG);
1554 $sql =
"DELETE FROM ".MAIN_DB_PREFIX.
"element_contact";
1555 $sql .=
" WHERE rowid = ".((int) $rowid);
1557 $result = $this->db->query($sql);
1560 $this->errors[] = $this->db->lasterror();
1565 $this->db->commit();
1568 $this->error = $this->db->lasterror();
1569 $this->db->rollback();
1589 if (!empty($typeContact)) {
1590 foreach ($typeContact as $key => $value) {
1591 array_push($temp, $key);
1593 $listId = implode(
",", $temp);
1598 if (empty($listId)) {
1602 $sql =
"DELETE FROM ".$this->db->prefix().
"element_contact";
1603 $sql .=
" WHERE element_id = ".((int) $this->
id);
1604 $sql .=
" AND fk_c_type_contact IN (".$this->db->sanitize($listId).
")";
1606 dol_syslog(get_class($this).
"::delete_linked_contact", LOG_DEBUG);
1607 if ($this->db->query($sql)) {
1610 $this->error = $this->db->lasterror();
1627 public function liste_contact($statusoflink = -1, $source =
'external', $list = 0, $code =
'', $status = -1, $arrayoftcids = array())
1634 $sql =
"SELECT ec.rowid, ec.statut as statuslink, ec.fk_socpeople as id, ec.fk_c_type_contact";
1635 if ($source ==
'internal') {
1636 $sql .=
", '-1' as socid, t.statut as statuscontact, t.login, t.photo, t.gender, t.fk_country as country_id";
1638 if ($source ==
'external' || $source ==
'thirdparty') {
1639 $sql .=
", t.fk_soc as socid, t.statut as statuscontact, t.fk_pays as country_id";
1641 $sql .=
", t.civility as civility, t.lastname as lastname, t.firstname, t.email, t.address, t.zip, t.town";
1642 if (empty($arrayoftcids)) {
1643 $sql .=
", tc.source, tc.element, tc.code, tc.libelle as type_label, co.label as country";
1646 if (empty($arrayoftcids)) {
1647 $sql .=
" ".$this->db->prefix().
"c_type_contact as tc,";
1649 $sql .=
" ".$this->db->prefix().
"element_contact as ec";
1650 if ($source ==
'internal') {
1651 $sql .=
" LEFT JOIN ".$this->db->prefix().
"user as t on ec.fk_socpeople = t.rowid";
1652 $sql .=
" LEFT JOIN ".$this->db->prefix().
"c_country as co ON co.rowid = t.fk_country";
1654 if ($source ==
'external' || $source ==
'thirdparty') {
1655 $sql .=
" LEFT JOIN ".$this->db->prefix().
"socpeople as t on ec.fk_socpeople = t.rowid";
1656 $sql .=
" LEFT JOIN ".$this->db->prefix().
"c_country as co ON co.rowid = t.fk_pays";
1658 $sql .=
" WHERE ec.element_id = ".((int) $this->
id);
1659 if (empty($arrayoftcids)) {
1660 $sql .=
" AND ec.fk_c_type_contact = tc.rowid";
1661 $sql .=
" AND tc.element = '".$this->db->escape($this->element).
"'";
1663 $sql .=
" AND tc.code = '".$this->db->escape($code).
"'";
1665 if ($source ==
'internal') {
1666 $sql .=
" AND tc.source = 'internal'";
1668 if ($source ==
'external' || $source ==
'thirdparty') {
1669 $sql .=
" AND tc.source = 'external'";
1671 $sql .=
" AND tc.active = 1";
1673 $sql .=
" AND ec.fk_c_type_contact IN (".$this->db->sanitize(implode(
',', $arrayoftcids)).
")";
1676 $sql .=
" AND t.statut = ".((int) $status);
1678 if ($statusoflink >= 0) {
1679 $sql .=
" AND ec.statut = ".((int) $statusoflink);
1681 $sql .=
" ORDER BY t.lastname ASC";
1683 dol_syslog(get_class($this).
"::liste_contact", LOG_DEBUG);
1684 $resql = $this->db->query($sql);
1686 $num = $this->db->num_rows($resql);
1689 $obj = $this->db->fetch_object($resql);
1692 $transkey =
"TypeContact_".$obj->element.
"_".$obj->source.
"_".$obj->code;
1693 $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->type_label);
1695 'parentId' => $this->
id,
1696 'source' => $obj->source,
1697 'socid' => $obj->socid,
1699 'nom' => $obj->lastname,
1700 'civility' => $obj->civility,
1701 'lastname' => $obj->lastname,
1702 'firstname' => $obj->firstname,
1703 'email' => $obj->email,
1704 'address' => $obj->address,
1706 'town' => $obj->town,
1707 'country_id' => $obj->country_id,
1708 'country' => $obj->country,
1709 'login' => (empty($obj->login) ?
'' : $obj->login),
1710 'photo' => (empty($obj->photo) ?
'' : $obj->photo),
1711 'gender' => (empty($obj->gender) ?
'' : $obj->gender),
1712 'statuscontact' => $obj->statuscontact,
1713 'rowid' => $obj->rowid,
1714 'code' => $obj->code,
1715 'libelle' => $libelle_type,
1716 'status' => (
int) $obj->statuslink,
1717 'fk_c_type_contact' => $obj->fk_c_type_contact
1720 $tab[$i] = $obj->id;
1728 $this->error = $this->db->lasterror();
1743 $sql =
"SELECT ec.datecreate, ec.statut, ec.fk_socpeople, ec.fk_c_type_contact,";
1744 $sql .=
" tc.code, tc.libelle as type_label";
1745 $sql .=
" FROM (".$this->db->prefix().
"element_contact as ec, ".$this->db->prefix().
"c_type_contact as tc)";
1746 $sql .=
" WHERE ec.rowid =".((int) $rowid);
1747 $sql .=
" AND ec.fk_c_type_contact = tc.rowid";
1748 $sql .=
" AND tc.element = '".$this->db->escape($this->element).
"'";
1750 dol_syslog(get_class($this).
"::swapContactStatus", LOG_DEBUG);
1751 $resql = $this->db->query($sql);
1753 $obj = $this->db->fetch_object($resql);
1754 $newstatut = ($obj->statut == 4) ? 5 : 4;
1756 $this->db->free($resql);
1759 $this->error = $this->db->error();
1776 public function liste_type_contact($source =
'internal', $order =
'position', $option = 0, $activeonly = 0, $code =
'')
1781 $sanitized_order = $order;
1783 if (empty($sanitized_order)) {
1784 $sanitized_order =
'position';
1786 if ($sanitized_order ==
'position') {
1787 $sanitized_order .=
',code';
1792 $sql =
"SELECT DISTINCT tc.rowid, tc.code, tc.libelle as type_label, tc.position";
1793 $sql .=
" FROM ".$this->db->prefix().
"c_type_contact as tc";
1794 $sql .=
" WHERE tc.element = '".$this->db->escape($this->element).
"'";
1795 if ($activeonly == 1) {
1796 $sql .=
" AND tc.active = 1";
1798 if (!empty($source) && $source !=
'all') {
1799 $sql .=
" AND tc.source = '".$this->db->escape($source).
"'";
1801 if (!empty($code)) {
1802 $sql .=
" AND tc.code = '".$this->db->escape($code).
"'";
1804 $sql .= $this->db->order($sanitized_order,
'ASC');
1807 $resql = $this->db->query($sql);
1809 $this->error = $this->db->lasterror();
1814 $num = $this->db->num_rows($resql);
1817 $obj = $this->db->fetch_object($resql);
1819 $transkey =
"TypeContact_".$this->element.
"_".$source.
"_".$obj->code;
1820 $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $langs->trans($obj->type_label));
1821 if (empty($option)) {
1822 $tab[$obj->rowid] = $libelle_type;
1823 } elseif ($option == 1) {
1824 $tab[$obj->code] = $libelle_type;
1826 $tab[$obj->rowid] = array(
'id' => $obj->rowid,
'code' => $obj->code,
'label' => $libelle_type);
1845 public function listeTypeContacts($source =
'internal', $option = 0, $activeonly = 0, $code =
'', $element =
'', $excludeelement =
'')
1849 $langs->loadLangs(array(
'bills',
'contracts',
'interventions',
'orders',
'projects',
'propal',
'ticket',
'agenda'));
1853 $sql =
"SELECT DISTINCT tc.rowid, tc.code, tc.libelle as type_label, tc.position, tc.element, tc.module";
1854 $sql .=
" FROM ".$this->db->prefix().
"c_type_contact as tc";
1856 $sqlWhere = array();
1857 if (!empty($element)) {
1858 $sqlWhere[] =
" tc.element='".$this->db->escape($element).
"'";
1860 if (!empty($excludeelement)) {
1861 $sqlWhere[] =
" tc.element <> '".$this->db->escape($excludeelement).
"'";
1864 if ($activeonly == 1) {
1865 $sqlWhere[] =
" tc.active=1";
1868 if (!empty($source) && $source !=
'all') {
1869 $sqlWhere[] =
" tc.source='".$this->db->escape($source).
"'";
1872 if (!empty($code)) {
1873 $sqlWhere[] =
" tc.code='".$this->db->escape($code).
"'";
1876 if (count($sqlWhere) > 0) {
1877 $sql .=
" WHERE ".implode(
' AND ', $sqlWhere);
1880 $sql .= $this->db->order(
'tc.element, tc.position',
'ASC');
1883 $resql = $this->db->query($sql);
1885 $num = $this->db->num_rows($resql);
1887 $langs->loadLangs(array(
"propal",
"orders",
"bills",
"suppliers",
"contracts",
"supplier_proposal"));
1889 while ($obj = $this->db->fetch_object($resql)) {
1890 $modulename = $obj->module ?? $obj->element;
1891 if (strpos($obj->element,
'project') !==
false) {
1892 $modulename =
'projet';
1893 } elseif ($obj->element ==
'contrat') {
1894 $element =
'contract';
1895 } elseif ($obj->element ==
'action') {
1896 $modulename =
'agenda';
1897 } elseif (strpos($obj->element,
'supplier') !==
false && $obj->element !=
'supplier_proposal') {
1898 $modulename =
'fournisseur';
1901 $libelle_element = $langs->trans(
'ContactDefault_'.$obj->element);
1902 $tmpelement = $obj->element;
1903 $transkey =
"TypeContact_".$tmpelement.
"_".$source.
"_".$obj->code;
1904 $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->type_label);
1905 $tab[$obj->rowid] = $libelle_element.
' - '.$libelle_type;
1911 $this->error = $this->db->lasterror();
1932 if (!
getDolGlobalInt(
'SHIPPING_USE_ITS_OWN_CONTACTS') && $this->element ==
'shipping' && $this->origin_id != 0) {
1933 $id = $this->origin_id;
1934 $element =
'commande';
1935 } elseif ($this->element ==
'reception' && $this->origin_id != 0) {
1936 $id = $this->origin_id;
1937 $element =
'order_supplier';
1940 $element = $this->element;
1943 $sql =
"SELECT ec.fk_socpeople";
1944 $sql .=
" FROM ".$this->db->prefix().
"element_contact as ec,";
1945 if ($source ==
'internal') {
1946 $sql .=
" ".$this->db->prefix().
"user as c,";
1948 if ($source ==
'external') {
1949 $sql .=
" ".$this->db->prefix().
"socpeople as c,";
1951 $sql .=
" ".$this->db->prefix().
"c_type_contact as tc";
1952 $sql .=
" WHERE ec.element_id = ".((int) $id);
1953 $sql .=
" AND ec.fk_socpeople = c.rowid";
1954 if ($source ==
'internal') {
1955 $sql .=
" AND c.entity IN (".getEntity(
'user').
")";
1957 if ($source ==
'external') {
1958 $sql .=
" AND c.entity IN (".getEntity(
'societe').
")";
1960 $sql .=
" AND ec.fk_c_type_contact = tc.rowid";
1961 $sql .=
" AND tc.element = '".$this->db->escape($element).
"'";
1962 $sql .=
" AND tc.source = '".$this->db->escape($source).
"'";
1964 $sql .=
" AND tc.code = '".$this->db->escape($code).
"'";
1966 $sql .=
" AND tc.active = 1";
1968 $sql .=
" AND ec.statut = ".((int) $status);
1971 dol_syslog(get_class($this).
"::getIdContact", LOG_DEBUG);
1972 $resql = $this->db->query($sql);
1974 while ($obj = $this->db->fetch_object($resql)) {
1975 $result[$i] = $obj->fk_socpeople;
1979 $this->error = $this->db->error();
1996 if (empty($contactid)) {
1997 $contactid = $this->contact_id;
2000 if (empty($contactid)) {
2004 require_once DOL_DOCUMENT_ROOT.
'/contact/class/contact.class.php';
2005 $contact =
new Contact($this->db);
2006 $result = $contact->fetch($contactid);
2007 $this->contact = $contact;
2022 if (empty($this->socid) && empty($this->fk_soc) && empty($force_thirdparty_id)) {
2026 require_once DOL_DOCUMENT_ROOT.
'/societe/class/societe.class.php';
2028 $idtofetch = isset($this->socid) ? $this->socid : (isset($this->fk_soc) ? $this->fk_soc : 0);
2029 if ($force_thirdparty_id) {
2030 $idtofetch = $force_thirdparty_id;
2034 $thirdparty =
new Societe($this->db);
2035 $result = $thirdparty->fetch($idtofetch);
2037 $this->errors = array_merge($this->errors, $thirdparty->errors);
2039 $this->thirdparty = $thirdparty;
2043 $this->thirdparty->price_level = 1;
2062 if (!$this->table_ref_field) {
2066 $sql =
"SELECT rowid FROM ".$this->db->prefix().$this->table_element;
2067 $sql .=
" WHERE ".$this->db->sanitize($this->table_ref_field).
" LIKE '".$this->db->escape($ref).
"'";
2070 $query = $this->db->query($sql);
2072 if (!$this->db->num_rows($query)) {
2076 $result = $this->db->fetch_object($query);
2078 if (method_exists($this,
'fetch')) {
2079 return $this->fetch($result->rowid);
2081 $this->error =
'Fetch method not implemented on '.get_class($this);
2082 dol_syslog(get_class($this).
'::fetchOneLike Error='.$this->error, LOG_ERR);
2083 array_push($this->errors, $this->error);
2112 dol_syslog(get_class($this).
'::fetchBarCode this->element='.$this->element.
' this->barcode_type='.$this->barcode_type);
2114 $idtype = $this->barcode_type;
2115 if (empty($idtype) && $idtype !=
'0') {
2116 if ($this->element ==
'product' &&
getDolGlobalString(
'PRODUIT_DEFAULT_BARCODE_TYPE')) {
2118 } elseif ($this->element ==
'societe') {
2121 dol_syslog(
'Call fetchBarCode with barcode_type not defined and cannot be guessed', LOG_WARNING);
2126 if (empty($this->barcode_type) || empty($this->barcode_type_code) || empty($this->barcode_type_label) || empty($this->barcode_type_coder)) {
2127 $sql =
"SELECT rowid, code, libelle as label, coder";
2128 $sql .=
" FROM ".$this->db->prefix().
"c_barcode_type";
2129 $sql .=
" WHERE rowid = ".((int) $idtype);
2131 $resql = $this->db->query($sql);
2133 $obj = $this->db->fetch_object($resql);
2135 $this->barcode_type = $obj->rowid;
2136 $this->barcode_type_code = $obj->code;
2137 $this->barcode_type_label = $obj->label;
2138 $this->barcode_type_coder = $obj->coder;
2156 include_once DOL_DOCUMENT_ROOT.
'/projet/class/project.class.php';
2158 if (empty($this->fk_project) && !empty($this->fk_projet)) {
2159 $this->fk_project = $this->fk_projet;
2161 if (empty($this->fk_project)) {
2165 $project =
new Project($this->db);
2166 $result = $project->fetch($this->fk_project);
2168 $this->project = $project;
2210 include_once DOL_DOCUMENT_ROOT.
'/product/class/product.class.php';
2213 if (empty($this->fk_product)) {
2217 $product =
new Product($this->db);
2219 $result = $product->fetch($this->fk_product);
2221 $this->product = $product;
2235 $user =
new User($this->db);
2236 $result = $user->fetch($userid);
2237 $this->
user = $user;
2251 $tmpclassname = $this->origin ? $this->origin : $this->origin_type;
2254 if ($tmpclassname ==
'shipping') {
2255 $tmpclassname =
'Expedition';
2257 if ($tmpclassname ==
'delivery') {
2258 $tmpclassname =
'Livraison';
2260 if ($tmpclassname ==
'order_supplier' || $tmpclassname ==
'supplier_order') {
2261 $tmpclassname =
'CommandeFournisseur';
2264 $classname = ucfirst($tmpclassname);
2266 $this->origin_object =
new $classname($this->db);
2268 $this->origin_object->fetch($this->origin_id);
2286 $sql =
"SELECT rowid FROM ".$this->db->prefix().$table;
2287 $sql .=
" WHERE ".$this->db->sanitize($field).
" = '".$this->db->escape($key).
"'";
2288 if (!empty($element)) {
2289 $sql .=
" AND entity IN (".getEntity($element).
")";
2291 $sql .=
" AND entity = ".((int)
$conf->entity);
2294 dol_syslog(get_class($this).
'::fetchObjectFrom', LOG_DEBUG);
2295 $resql = $this->db->query($sql);
2297 $obj = $this->db->fetch_object($resql);
2300 if (method_exists($this,
'fetch')) {
2301 $result = $this->fetch($obj->rowid);
2303 $this->error =
'fetch() method not implemented on '.get_class($this);
2304 dol_syslog(get_class($this).
'::fetchOneLike Error='.$this->error, LOG_ERR);
2305 array_push($this->errors, $this->error);
2325 if (!empty($id) && !empty($field) && !empty($table)) {
2326 if (!preg_match(
'/^[a-zA-Z_][a-zA-Z0-9_]*$/', $table)) {
2327 dol_syslog(get_class($this).
'::getValueFrom Bad table name: '.$table, LOG_WARNING);
2330 if (!preg_match(
'/^[a-zA-Z_][a-zA-Z0-9_.]*$/', $field)) {
2331 dol_syslog(get_class($this).
'::getValueFrom Bad field name: '.$field, LOG_WARNING);
2335 $sql =
"SELECT ".$this->db->sanitize($field).
" FROM ".$this->db->prefix().$this->db->sanitize($table);
2336 $sql .=
" WHERE rowid = ".((int) $id);
2338 dol_syslog(get_class($this).
'::getValueFrom', LOG_DEBUG);
2339 $resql = $this->db->query($sql);
2341 $row = $this->db->fetch_row($resql);
2364 public function setValueFrom($field, $value, $table =
'', $id =
null, $format =
'', $id_field =
'', $fuser =
null, $trigkey =
'', $fk_user_field =
'fk_user_modif')
2368 if (empty($table)) {
2369 $table = $this->table_element;
2374 if (empty($format)) {
2377 if (empty($id_field)) {
2378 $id_field =
'rowid';
2381 $propfield = $field;
2384 if ($table ==
'product') {
2385 if ($field ==
'note_private') {
2387 $propfield =
'note_private';
2388 } elseif ($field ==
'status') {
2390 $propfield =
'status';
2391 } elseif ($field ==
'status_buy') {
2393 $propfield =
'status_buy';
2394 } elseif ($field ==
'status_batch') {
2396 $propfield =
'status_batch';
2400 if (in_array($table, array(
'actioncomm',
'adherent',
'advtargetemailing',
'cronjob',
'establishment'))) {
2401 $fk_user_field =
'fk_user_mod';
2403 if (in_array($table, array(
'prelevement_bons'))) {
2404 $fk_user_field =
'';
2407 if (!preg_match(
'/^[a-zA-Z_][a-zA-Z0-9_]*$/', $table)) {
2408 dol_syslog(get_class($this).
'::getValueFrom Bad table name: '.$table, LOG_WARNING);
2411 if (!preg_match(
'/^[a-zA-Z_][a-zA-Z0-9_.]*$/', $field)) {
2412 dol_syslog(get_class($this).
'::getValueFrom Bad field name: '.$field, LOG_WARNING);
2418 $sql =
"SELECT " . $this->db->sanitize($field);
2419 $sql .=
" FROM " . MAIN_DB_PREFIX . $this->db->sanitize($table);
2420 $sql .=
" WHERE " . $this->db->sanitize($id_field) .
" = " . ((int) $id);
2422 $resql = $this->db->query($sql);
2424 if ($obj = $this->db->fetch_object($resql)) {
2425 if ($format ==
'date') {
2426 $oldvalue = $this->db->jdate($obj->$field);
2428 $oldvalue = $obj->$field;
2432 $this->error = $this->db->lasterror();
2443 $sql =
"UPDATE ".$this->db->prefix().$table.
" SET ";
2445 if ($format ==
'text') {
2446 $sql .= $this->db->sanitize($field).
" = '".$this->db->escape($value).
"'";
2447 } elseif ($format ==
'int') {
2448 $sql .= $this->db->sanitize($field).
" = ".((int) $value);
2449 } elseif ($format ==
'date') {
2450 $sql .= $this->db->sanitize($field).
" = ".($value ?
"'".$this->db->idate($value).
"'" :
"null");
2451 } elseif ($format ==
'dategmt') {
2452 $sql .= $this->db->sanitize($field).
" = ".($value ?
"'".$this->db->idate($value,
'gmt').
"'" :
"null");
2455 if ($fk_user_field) {
2456 if (!empty($fuser) && is_object($fuser)) {
2457 $sql .=
", ".$this->db->sanitize($fk_user_field).
" = ".((int) $fuser->id);
2458 } elseif (empty($fuser) || $fuser !=
'none') {
2459 $sql .=
", ".$this->db->sanitize($fk_user_field).
" = ".((int) $user->id);
2463 $sql .=
" WHERE ".$this->db->sanitize($id_field).
" = ".((int) $id);
2465 $resql = $this->db->query($sql);
2469 if (method_exists($this,
'fetch')) {
2470 $result = $this->fetch(
$id);
2475 $this->oldcopy = clone $this;
2476 if (property_exists($this->oldcopy, $field)) {
2477 $this->oldcopy->$field = $oldvalue;
2479 if ($propfield != $field && property_exists($this->oldcopy, $propfield)) {
2480 $this->oldcopy->$propfield = $oldvalue;
2483 if (empty($this->context[
'actionmsgmore'])) {
2484 $this->context[
'actionmsgmore'] =
'Trigger called by setValueFrom';
2488 $result = $this->call_trigger($trigkey, (!empty($fuser) && is_object($fuser)) ? $fuser : $user);
2494 if (property_exists($this, $field)) {
2495 $this->$field = $value;
2497 if ($propfield != $field && property_exists($this, $propfield)) {
2498 $this->$propfield = $value;
2503 $this->db->commit();
2506 if (property_exists($this, $field)) {
2507 $this->$field = $oldvalue;
2509 if ($propfield != $field && property_exists($this, $propfield)) {
2510 $this->$propfield = $oldvalue;
2512 $this->db->rollback();
2516 if ($this->db->lasterrno() ==
'DB_ERROR_RECORD_ALREADY_EXISTS') {
2517 $this->error =
'DB_ERROR_RECORD_ALREADY_EXISTS';
2519 $this->error = $this->db->lasterror();
2521 $this->db->rollback();
2540 global
$conf, $user;
2542 if (!$this->table_element) {
2543 dol_print_error(
null, get_class($this).
"::load_previous_next_ref was called on object with property table_element not defined");
2546 if ($fieldid ==
'none') {
2551 if (in_array($this->table_element, array(
'facture_rec',
'facture_fourn_rec')) && $fieldid ==
'title') {
2557 if ($user->socid > 0) {
2558 $socid = $user->socid;
2563 $aliastablesociete =
's';
2564 if ($this->element ==
'societe') {
2565 $aliastablesociete =
'te';
2567 $restrictiononfksoc = empty($this->restrictiononfksoc) ? 0 : $this->restrictiononfksoc;
2568 $sql =
"SELECT MAX(te.".$this->db->sanitize($fieldid).
")";
2569 $sql .=
" FROM ".(empty($nodbprefix) ? $this->db->prefix() :
'').$this->table_element.
" as te";
2570 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2571 $tmparray = explode(
'@', $this->ismultientitymanaged);
2572 $sql .=
", ".$this->db->prefix().$this->db->sanitize($tmparray[1]).
" as ".($tmparray[1] ==
'societe' ?
's' :
'parenttable');
2573 } elseif ($restrictiononfksoc == 1 && $this->element !=
'societe' && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2574 $sql .=
", ".$this->db->prefix().
"societe as s";
2575 } elseif ($restrictiononfksoc == 2 && $this->element !=
'societe' && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2576 $sql .=
" LEFT JOIN ".$this->db->prefix().
"societe as s ON te.fk_soc = s.rowid";
2578 if ($restrictiononfksoc && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2579 $sql .=
" LEFT JOIN ".$this->db->prefix().
"societe_commerciaux as sc ON ".$aliastablesociete.
".rowid = sc.fk_soc";
2581 if ($fieldid ==
'rowid') {
2582 $sql .=
" WHERE te.".$this->db->sanitize($fieldid).
" < ".((int) $this->
id);
2583 } elseif ($fieldid ==
'label') {
2584 $sql .=
" WHERE te.".$this->db->sanitize($fieldid).
" < '".$this->db->escape((
string) $this->label).
"'";
2586 $sql .=
" WHERE te.".$this->db->sanitize($fieldid).
" < '".$this->db->escape((
string) $this->
ref).
"'";
2588 if ($restrictiononfksoc == 1 && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2589 $sql .=
" AND sc.fk_user = ".((int) $user->id);
2591 if ($restrictiononfksoc == 2 && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2592 $sql .=
" AND (sc.fk_user = ".((int) $user->id).
' OR te.fk_soc IS NULL)';
2595 $filtermax = $filter;
2600 if ($errormessage) {
2601 if (!preg_match(
'/^\s*AND/i', $filtermax)) {
2609 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2610 $tmparray = explode(
'@', $this->ismultientitymanaged);
2611 $sql .=
" AND te.".$this->db->sanitize($tmparray[0]).
" = ".($tmparray[1] ==
"societe" ?
"s" :
"parenttable").
".rowid";
2612 } elseif ($restrictiononfksoc == 1 && $this->element !=
'societe' && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2613 $sql .=
' AND te.fk_soc = s.rowid';
2615 if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
2616 if ($this->element ==
'user' &&
getDolGlobalInt(
'MULTICOMPANY_TRANSVERSE_MODE')) {
2617 if (!empty($user->admin) && empty($user->entity) &&
$conf->entity == 1) {
2618 $sql .=
" AND te.entity IS NOT NULL";
2620 $sql .=
" AND te.rowid IN (SELECT ug.fk_user FROM ".$this->db->prefix().
"usergroup_user as ug WHERE ug.entity IN (".
getEntity(
'usergroup').
"))";
2623 $sql .=
' AND te.entity IN ('.getEntity($this->element).
')';
2626 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged) && $this->element !=
'societe') {
2627 $tmparray = explode(
'@', $this->ismultientitymanaged);
2628 $sql .=
' AND parenttable.entity IN ('.getEntity($tmparray[1]).
')';
2630 if ($restrictiononfksoc == 1 && $socid && $this->element !=
'societe') {
2631 $sql .=
' AND te.fk_soc = '.((int) $socid);
2633 if ($restrictiononfksoc == 2 && $socid && $this->element !=
'societe') {
2634 $sql .=
' AND (te.fk_soc = '.((int) $socid).
' OR te.fk_soc IS NULL)';
2636 if ($restrictiononfksoc && $socid && $this->element ==
'societe') {
2637 $sql .=
' AND te.rowid = '.((int) $socid);
2641 $result = $this->db->query($sql);
2643 $this->error = $this->db->lasterror();
2646 $row = $this->db->fetch_row($result);
2647 $this->ref_previous = $row[0];
2649 $sql =
"SELECT MIN(te.".$this->db->sanitize($fieldid).
")";
2650 $sql .=
" FROM ".(empty($nodbprefix) ? $this->db->prefix() :
'').$this->table_element.
" as te";
2651 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2652 $tmparray = explode(
'@', $this->ismultientitymanaged);
2653 $sql .=
", ".$this->db->prefix().$this->db->sanitize($tmparray[1]).
" as ".($tmparray[1] ==
'societe' ?
's' :
'parenttable');
2654 } elseif ($restrictiononfksoc == 1 && $this->element !=
'societe' && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2655 $sql .=
", ".$this->db->prefix().
"societe as s";
2656 } elseif ($restrictiononfksoc == 2 && $this->element !=
'societe' && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2657 $sql .=
" LEFT JOIN ".$this->db->prefix().
"societe as s ON te.fk_soc = s.rowid";
2659 if ($restrictiononfksoc && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2660 $sql .=
" LEFT JOIN ".$this->db->prefix().
"societe_commerciaux as sc ON ".$aliastablesociete.
".rowid = sc.fk_soc";
2662 if ($fieldid ==
'rowid') {
2663 $sql .=
" WHERE te.".$this->db->sanitize($fieldid).
" > ".((int) $this->
id);
2664 } elseif ($fieldid ==
'label') {
2665 $sql .=
" WHERE te.".$this->db->sanitize($fieldid).
" > '".$this->db->escape((
string) $this->label).
"'";
2667 $sql .=
" WHERE te.".$this->db->sanitize($fieldid).
" > '".$this->db->escape((
string) $this->
ref).
"'";
2669 if ($restrictiononfksoc == 1 && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2670 $sql .=
" AND (sc.fk_user = ".((int) $user->id);
2672 $userschilds = $user->getAllChildIds();
2673 $sql .=
" OR sc.fk_user IN (".$this->db->sanitize(implode(
',', $userschilds)).
")";
2677 if ($restrictiononfksoc == 2 && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2678 $sql .=
" AND (sc.fk_user = ".((int) $user->id).
' OR te.fk_soc IS NULL)';
2681 $filtermin = $filter;
2686 if ($errormessage) {
2687 if (!preg_match(
'/^\s*AND/i', $filtermin)) {
2697 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2698 $tmparray = explode(
'@', $this->ismultientitymanaged);
2699 $sql .=
" AND te.".$this->db->sanitize($tmparray[0]).
" = ".($tmparray[1] ==
"societe" ?
"s" :
"parenttable").
".rowid";
2700 } elseif ($restrictiononfksoc == 1 && $this->element !=
'societe' && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2701 $sql .=
' AND te.fk_soc = s.rowid';
2703 if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
2704 if ($this->element ==
'user' &&
getDolGlobalInt(
'MULTICOMPANY_TRANSVERSE_MODE')) {
2705 if (!empty($user->admin) && empty($user->entity) &&
$conf->entity == 1) {
2706 $sql .=
" AND te.entity IS NOT NULL";
2708 $sql .=
" AND te.rowid IN (SELECT ug.fk_user FROM ".$this->db->prefix().
"usergroup_user as ug WHERE ug.entity IN (".
getEntity(
'usergroup').
"))";
2711 $sql .=
' AND te.entity IN ('.getEntity($this->element).
')';
2714 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged) && $this->element !=
'societe') {
2715 $tmparray = explode(
'@', $this->ismultientitymanaged);
2716 $sql .=
' AND parenttable.entity IN ('.getEntity($tmparray[1]).
')';
2718 if ($restrictiononfksoc == 1 && $socid && $this->element !=
'societe') {
2719 $sql .=
' AND te.fk_soc = '.((int) $socid);
2721 if ($restrictiononfksoc == 2 && $socid && $this->element !=
'societe') {
2722 $sql .=
' AND (te.fk_soc = '.((int) $socid).
' OR te.fk_soc IS NULL)';
2724 if ($restrictiononfksoc && $socid && $this->element ==
'societe') {
2725 $sql .=
' AND te.rowid = '.((int) $socid);
2730 $result = $this->db->query($sql);
2732 $this->error = $this->db->lasterror();
2735 $row = $this->db->fetch_row($result);
2736 $this->ref_next = $row[0];
2751 $contactAlreadySelected = array();
2756 if ($source ==
'thirdparty') {
2757 $contactAlreadySelected[$i] = $tab[$i][
'socid'];
2759 $contactAlreadySelected[$i] = $tab[$i][
'id'];
2763 return $contactAlreadySelected;
2779 if (!$this->table_element) {
2780 dol_syslog(get_class($this).
"::setProject was called on object with property table_element not defined", LOG_ERR);
2784 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
2785 if ($this->table_element ==
'actioncomm') {
2787 $sql .=
" SET fk_project = ".((int) $projectid);
2789 $sql .=
" SET fk_project = NULL";
2791 $sql .=
' WHERE id = '.((int) $this->
id);
2793 } elseif (!empty($this->fields[
'fk_project'])) {
2795 $sql .=
" SET fk_project = ".((int) $projectid);
2797 $sql .=
" SET fk_project = NULL";
2799 $sql .=
' WHERE rowid = '.((int) $this->
id);
2802 $sql .=
' SET fk_projet = '.((int) $projectid);
2804 $sql .=
' SET fk_projet = NULL';
2806 $sql .=
" WHERE rowid = ".((int) $this->
id);
2811 dol_syslog(get_class($this).
"::setProject", LOG_DEBUG);
2812 if ($this->db->query($sql)) {
2813 $this->fk_project = ((int) $projectid);
2820 if (!$error && !$notrigger) {
2822 $result = $this->call_trigger(strtoupper($this->element) .
'_MODIFY', $user);
2831 $this->db->rollback();
2834 $this->db->commit();
2852 dol_syslog(get_class($this).
'::setPaymentMethods('.$id.
')');
2854 if ($this->
status >= 0 || $this->element ==
'societe') {
2858 $fieldname =
'fk_mode_reglement';
2859 $triggerName = (empty($this->TRIGGER_PREFIX) ? strtoupper(get_class($this)) : $this->TRIGGER_PREFIX);
2860 if ($this->element ==
'societe') {
2861 $fieldname =
'mode_reglement';
2862 $triggerName =
'COMPANY';
2864 if (get_class($this) ==
'Facture') {
2865 $triggerName =
'BILL';
2867 if (get_class($this) ==
'Fournisseur') {
2868 $fieldname =
'mode_reglement_supplier';
2869 $triggerName =
'BILL_SUPPLIER';
2871 if (get_class($this) ==
'Tva') {
2872 $fieldname =
'fk_typepayment';
2873 $triggerName =
'VAT';
2875 if (get_class($this) ==
'Salary') {
2876 $fieldname =
'fk_typepayment';
2879 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
2880 $sql .=
" SET ".$this->db->sanitize($fieldname).
" = ".(($id > 0 || $id ==
'0') ? ((
int) $id) :
'NULL');
2881 $sql .=
' WHERE rowid = '.((int) $this->
id);
2883 if ($this->db->query($sql)) {
2884 $this->mode_reglement_id = $id;
2886 if (get_class($this) ==
'Fournisseur') {
2887 $this->mode_reglement_supplier_id = $id;
2891 if (!$error && !$notrigger) {
2893 $result = $this->call_trigger($triggerName.
'_MODIFY', $user);
2901 dol_syslog(get_class($this).
'::setPaymentMethods Error '.$this->db->error());
2902 $this->error = $this->db->error();
2906 dol_syslog(get_class($this).
'::setPaymentMethods, status of the object is incompatible');
2907 $this->error =
'Status of the object is incompatible '.$this->status;
2920 dol_syslog(get_class($this).
'::setMulticurrencyCode('.$code.
')');
2921 if ($this->
status >= 0 || $this->element ==
'societe') {
2922 $sql =
'UPDATE '.$this->db->prefix().$this->table_element;
2923 $sql .=
" SET multicurrency_code = '".$this->db->escape($code).
"'";
2924 $sql .=
' WHERE rowid='.((int) $this->
id);
2926 if ($this->db->query($sql)) {
2927 $this->multicurrency_code = $code;
2931 $this->setMulticurrencyRate($rate, 2);
2936 dol_syslog(get_class($this).
'::setMulticurrencyCode Error '.$sql.
' - '.$this->db->error());
2937 $this->error = $this->db->error();
2941 dol_syslog(get_class($this).
'::setMulticurrencyCode, status of the object is incompatible');
2942 $this->error =
'Status of the object is incompatible '.$this->status;
2954 public function setMulticurrencyRate($rate, $mode = 1)
2956 dol_syslog(get_class($this).
'::setMulticurrencyRate('.$rate.
', '.$mode.
')');
2957 if ($this->
status >= 0 || $this->element ==
'societe') {
2958 $sql =
'UPDATE '.$this->db->prefix().$this->table_element;
2959 $sql .=
" SET multicurrency_tx = ".((float) $rate);
2960 $sql .=
' WHERE rowid='.((int) $this->
id);
2962 if ($this->db->query($sql)) {
2963 $this->multicurrency_tx = $rate;
2966 if (!empty($this->lines)) {
2967 foreach ($this->lines as &$line) {
2970 if (!empty($line->fk_remise_except)) {
2976 $line->subprice = 0;
2981 $line->multicurrency_subprice = 0;
2984 switch ($this->element) {
2988 '@phan-var-force Propal $this';
2989 '@phan-var-force PropaleLigne $line';
2994 $line->remise_percent,
2996 $line->localtax1_tx,
2997 $line->localtax2_tx,
2998 ($line->description ? $line->description : $line->desc),
3001 $line->special_code,
3002 $line->fk_parent_line,
3003 $line->skip_update_total,
3004 $line->fk_fournprice,
3007 $line->product_type,
3010 $line->array_options,
3012 $line->multicurrency_subprice
3018 '@phan-var-force Commande $this';
3019 '@phan-var-force OrderLine $line';
3022 ($line->description ? $line->description : $line->desc),
3025 $line->remise_percent,
3027 $line->localtax1_tx,
3028 $line->localtax2_tx,
3033 $line->product_type,
3034 $line->fk_parent_line,
3035 $line->skip_update_total,
3036 $line->fk_fournprice,
3039 $line->special_code,
3040 $line->array_options,
3042 $line->multicurrency_subprice
3048 '@phan-var-force Facture $this';
3049 '@phan-var-force FactureLigne $line';
3052 ($line->description ? $line->description : $line->desc),
3055 $line->remise_percent,
3059 $line->localtax1_tx,
3060 $line->localtax2_tx,
3063 $line->product_type,
3064 $line->fk_parent_line,
3065 $line->skip_update_total,
3066 $line->fk_fournprice,
3069 $line->special_code,
3070 $line->array_options,
3071 $line->situation_percent,
3073 $line->multicurrency_subprice
3079 '@phan-var-force FactureRec $this';
3080 '@phan-var-force FactureLigneRec $line';
3083 ($line->description ? $line->description : $line->desc),
3087 $line->localtax1_tx,
3088 $line->localtax2_tx,
3090 $line->remise_percent,
3095 $line->product_type,
3097 $line->special_code,
3100 $line->multicurrency_subprice,
3104 $line->fk_fournprice,
3106 $line->fk_parent_line
3109 case 'supplier_proposal':
3112 '@phan-var-force SupplierProposal $this';
3113 '@phan-var-force SupplierProposalLine $line';
3118 $line->remise_percent,
3120 $line->localtax1_tx,
3121 $line->localtax2_tx,
3122 ($line->description ? $line->description : $line->desc),
3125 $line->special_code,
3126 $line->fk_parent_line,
3127 $line->skip_update_total,
3128 $line->fk_fournprice,
3131 $line->product_type,
3132 $line->array_options,
3134 (int) $line->fk_unit,
3135 $line->multicurrency_subprice
3138 case 'order_supplier':
3141 '@phan-var-force CommandeFournisseur $this';
3142 '@phan-var-force CommandeFournisseurLigne $line';
3145 ($line->description ? $line->description : $line->desc),
3148 $line->remise_percent,
3150 $line->localtax1_tx,
3151 $line->localtax2_tx,
3154 $line->product_type,
3158 $line->array_options,
3160 $line->multicurrency_subprice,
3164 case 'invoice_supplier':
3167 '@phan-var-force FactureFournisseur $this';
3168 '@phan-var-force SupplierInvoiceLIne $line';
3171 ($line->description ? $line->description : $line->desc),
3174 $line->localtax1_tx,
3175 $line->localtax2_tx,
3180 $line->product_type,
3181 $line->remise_percent,
3185 $line->array_options,
3187 $line->multicurrency_subprice,
3192 dol_syslog(get_class($this).
'::setMulticurrencyRate no updateline defined', LOG_DEBUG);
3200 dol_syslog(get_class($this).
'::setMulticurrencyRate Error '.$sql.
' - '.$this->db->error());
3201 $this->error = $this->db->error();
3205 dol_syslog(get_class($this).
'::setMulticurrencyRate, status of the object is incompatible');
3206 $this->error =
'Status of the object is incompatible '.$this->status;
3221 if ($this->
status >= 0 || $this->element ==
'societe') {
3223 $fieldname =
'fk_cond_reglement';
3224 if ($this->element ==
'societe') {
3225 $fieldname =
'cond_reglement';
3227 if (get_class($this) ==
'Fournisseur') {
3228 $fieldname =
'cond_reglement_supplier';
3231 if (empty($deposit_percent) || $deposit_percent < 0) {
3232 $deposit_percent = (float)
getDictionaryValue(
'c_payment_term',
'deposit_percent', $id);
3235 if ($deposit_percent > 100) {
3236 $deposit_percent = 100;
3239 $sql =
'UPDATE '.$this->db->prefix().$this->table_element;
3240 $sql .=
" SET ".$this->db->sanitize($fieldname).
" = ".(($id > 0 || $id ==
'0') ? ((
int) $id) :
'NULL');
3241 if (in_array($this->table_element, array(
'propal',
'commande',
'supplier_proposal',
'commande_fournisseur',
'societe'))) {
3242 $sql .=
" , deposit_percent = " . (empty($deposit_percent) ?
'NULL' :
"'".$this->db->escape((
string) $deposit_percent).
"'");
3244 $sql .=
' WHERE rowid = '.((int) $this->
id);
3246 if ($this->db->query($sql)) {
3247 $this->cond_reglement_id = $id;
3249 if (get_class($this) ==
'Fournisseur') {
3250 $this->cond_reglement_supplier_id = $id;
3252 $this->deposit_percent = $deposit_percent;
3255 dol_syslog(get_class($this).
'::setPaymentTerms Error '.$sql.
' - '.$this->db->error());
3256 $this->error = $this->db->error();
3260 dol_syslog(get_class($this).
'::setPaymentTerms, status of the object is incompatible');
3261 $this->error =
'Status of the object is incompatible '.$this->status;
3274 dol_syslog(get_class($this).
'::setTransportMode('.$id.
')');
3275 if ($this->
status >= 0 || $this->element ==
'societe') {
3276 $fieldname =
'fk_transport_mode';
3277 if ($this->element ==
'societe') {
3278 $fieldname =
'transport_mode';
3280 if (get_class($this) ==
'Fournisseur') {
3281 $fieldname =
'transport_mode_supplier';
3284 $sql =
'UPDATE '.$this->db->prefix().$this->table_element;
3285 $sql .=
" SET ".$this->db->sanitize($fieldname).
" = ".(($id > 0 || $id ==
'0') ? ((
int) $id) :
'NULL');
3286 $sql .=
' WHERE rowid='.((int) $this->
id);
3288 if ($this->db->query($sql)) {
3289 $this->transport_mode_id = $id;
3291 if (get_class($this) ==
'Fournisseur') {
3292 $this->transport_mode_supplier_id = $id;
3296 dol_syslog(get_class($this).
'::setTransportMode Error '.$sql.
' - '.$this->db->error());
3297 $this->error = $this->db->error();
3301 dol_syslog(get_class($this).
'::setTransportMode, status of the object is incompatible');
3302 $this->error =
'Status of the object is incompatible '.$this->status;
3316 $fieldname =
'fk_delivery_address';
3317 if ($this->element ==
'delivery' || $this->element ==
'shipping') {
3318 $fieldname =
'fk_address';
3321 $sql =
"UPDATE ".$this->db->prefix().$this->table_element.
" SET ".$this->db->sanitize($fieldname).
" = ".((int) $id);
3322 $sql .=
" WHERE rowid = ".((int) $this->
id).
" AND fk_statut = 0";
3324 if ($this->db->query($sql)) {
3325 $this->fk_delivery_address =
$id;
3328 $this->error = $this->db->error();
3329 dol_syslog(get_class($this).
'::setDeliveryAddress Error '.$this->error);
3347 if (empty($userused)) {
3353 if (!$this->table_element) {
3354 dol_syslog(get_class($this).
"::setShippingMethod was called on object with property table_element not defined", LOG_ERR);
3360 if ($shipping_method_id < 0) {
3361 $shipping_method_id =
'NULL';
3363 dol_syslog(get_class($this).
'::setShippingMethod('.$shipping_method_id.
')');
3365 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
3366 $sql .=
" SET fk_shipping_method = ".((int) $shipping_method_id);
3367 $sql .=
" WHERE rowid=".((int) $this->
id);
3368 $resql = $this->db->query($sql);
3370 dol_syslog(get_class($this).
'::setShippingMethod Error ', LOG_DEBUG);
3371 $this->error = $this->db->lasterror();
3376 $this->context = array(
'shippingmethodupdate' => 1);
3377 $triggerPrefix = (empty($this->TRIGGER_PREFIX) ? strtoupper(get_class($this)) : $this->TRIGGER_PREFIX);
3378 $result = $this->call_trigger($triggerPrefix.
'_MODIFY', $userused);
3386 $this->db->rollback();
3389 $this->shipping_method_id = ($shipping_method_id ==
'NULL') ?
null : $shipping_method_id;
3390 $this->db->commit();
3404 if (!$this->table_element) {
3405 dol_syslog(get_class($this).
"::setWarehouse was called on object with property table_element not defined", LOG_ERR);
3408 if ($warehouse_id < 0) {
3409 $warehouse_id =
'NULL';
3411 dol_syslog(get_class($this).
'::setWarehouse('.$warehouse_id.
')');
3413 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
3414 $sql .=
" SET fk_warehouse = ".((int) $warehouse_id);
3415 $sql .=
" WHERE rowid=".((int) $this->
id);
3417 if ($this->db->query($sql)) {
3418 $this->warehouse_id = ($warehouse_id ==
'NULL') ?
null : $warehouse_id;
3421 dol_syslog(get_class($this).
'::setWarehouse Error ', LOG_DEBUG);
3422 $this->error = $this->db->error();
3437 if (!$this->table_element) {
3438 dol_syslog(get_class($this).
"::setDocModel was called on object with property table_element not defined", LOG_ERR);
3442 $newmodelpdf =
dol_trunc($modelpdf, 255);
3444 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
3445 $sql .=
" SET model_pdf = '".$this->db->escape($newmodelpdf).
"'";
3446 $sql .=
" WHERE rowid = ".((int) $this->
id);
3448 dol_syslog(get_class($this).
"::setDocModel", LOG_DEBUG);
3449 $resql = $this->db->query($sql);
3451 $this->model_pdf = $modelpdf;
3472 if (empty($userused)) {
3478 if (!$this->table_element) {
3479 dol_syslog(get_class($this).
"::setBankAccount was called on object with property table_element not defined", LOG_ERR);
3484 if ($fk_account < 0) {
3485 $fk_account =
'NULL';
3487 dol_syslog(get_class($this).
'::setBankAccount('.$fk_account.
')');
3489 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
3490 $sql .=
" SET fk_account = ".((int) $fk_account);
3491 $sql .=
" WHERE rowid=".((int) $this->
id);
3493 $resql = $this->db->query($sql);
3495 dol_syslog(get_class($this).
'::setBankAccount Error '.$sql.
' - '.$this->db->error());
3496 $this->error = $this->db->lasterror();
3501 $this->context[
'bankaccountupdate'] = 1;
3503 $triggerName = (empty($this->TRIGGER_PREFIX) ? strtoupper(get_class($this)) : $this->TRIGGER_PREFIX);
3504 $result = $this->call_trigger($triggerName .
'_MODIFY', $userused);
3512 $this->db->rollback();
3515 $this->fk_account = ($fk_account ==
'NULL') ?
null : $fk_account;
3516 $this->db->commit();
3534 public function line_order($renum =
false, $rowidorder =
'ASC', $fk_parent_line =
true)
3537 if (!$this->table_element_line) {
3538 dol_syslog(get_class($this).
"::line_order was called on object with property table_element_line not defined", LOG_ERR);
3541 if (!$this->fk_element) {
3542 dol_syslog(get_class($this).
"::line_order was called on object with property fk_element not defined", LOG_ERR);
3546 $fieldposition =
'rang';
3547 if (in_array($this->table_element_line, array(
'bom_bomline',
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3548 $fieldposition =
'position';
3553 $sql =
"SELECT count(rowid) FROM ".$this->db->prefix().$this->db->sanitize($this->table_element_line);
3554 $sql .=
" WHERE ".$this->db->sanitize($this->fk_element).
" = ".((int) $this->
id);
3556 $sql .=
" AND " . $this->db->sanitize($fieldposition) .
" = 0";
3559 $sql .=
" AND " . $this->db->sanitize($fieldposition) .
" <> 0";
3562 dol_syslog(get_class($this).
"::line_order", LOG_DEBUG);
3563 $resql = $this->db->query($sql);
3565 $row = $this->db->fetch_row($resql);
3575 $sql =
"SELECT rowid FROM ".$this->db->prefix().$this->db->sanitize($this->table_element_line);
3576 $sql .=
" WHERE ".$this->db->sanitize($this->fk_element).
" = ".((int) $this->
id);
3577 if ($fk_parent_line) {
3578 $sql .=
' AND fk_parent_line IS NULL';
3580 $sql .=
" ORDER BY " . $this->db->sanitize($fieldposition) .
" ASC, rowid " . $this->db->sanitize($rowidorder);
3582 dol_syslog(get_class($this).
"::line_order search all parent lines", LOG_DEBUG);
3583 $resql = $this->db->query($sql);
3586 $num = $this->db->num_rows($resql);
3589 $row = $this->db->fetch_row($resql);
3591 if ($fk_parent_line) {
3594 if (!empty($children)) {
3595 foreach ($children as $child) {
3596 array_push($rows, $child);
3603 if (!empty($rows)) {
3604 foreach ($rows as $key => $row) {
3624 $fieldposition =
'rang';
3625 if (in_array($this->table_element_line, array(
'bom_bomline',
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3626 $fieldposition =
'position';
3631 $sql =
"SELECT rowid FROM ".$this->db->prefix().$this->db->sanitize($this->table_element_line);
3632 $sql .=
" WHERE ".$this->db->sanitize($this->fk_element).
" = ".((int) $this->
id);
3633 $sql .=
' AND fk_parent_line = '.((int) $id);
3634 $sql .=
" ORDER BY " . $this->db->sanitize($fieldposition) .
" ASC";
3636 dol_syslog(get_class($this).
"::getChildrenOfLine search children lines for line ".$id, LOG_DEBUG);
3638 $resql = $this->db->query($sql);
3639 if (!$resql || $this->db->num_rows($resql) <= 0) {
3643 while ($row = $this->db->fetch_row($resql)) {
3645 if (!empty($includealltree) && $includealltree <= 1000) {
3646 $rows = array_merge($rows, $this->
getChildrenOfLine($row[0], $includealltree + 1));
3660 public function line_up($rowid, $fk_parent_line =
true)
3663 $this->
line_order(
false,
'ASC', $fk_parent_line);
3683 $this->
line_order(
false,
'ASC', $fk_parent_line);
3704 global $hookmanager;
3705 $fieldposition =
'rang';
3706 if (in_array($this->table_element_line, array(
'bom_bomline',
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3707 $fieldposition =
'position';
3710 $sql =
"UPDATE ".$this->db->prefix().$this->table_element_line.
" SET ".$this->db->sanitize($fieldposition).
" = ".((int) $rang);
3711 $sql .=
' WHERE rowid = '.((int) $rowid);
3712 if ($this->
id > 0 && !empty($this->fk_element)) {
3714 $sql .=
" AND ".$this->db->sanitize($this->fk_element).
" = ".((int) $this->
id);
3717 dol_syslog(get_class($this).
"::updateRangOfLine", LOG_DEBUG);
3718 if (!$this->db->query($sql)) {
3723 $parameters = array(
'rowid' => $rowid,
'rang' => $rang,
'fieldposition' => $fieldposition);
3725 $reshook = $hookmanager->executeHooks(
'afterRankOfLineUpdate', $parameters, $this, $action);
3739 $num = count($rows);
3740 for ($i = 0; $i < $num; $i++) {
3758 $fieldposition =
'rang';
3759 if (in_array($this->table_element_line, array(
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3760 $fieldposition =
'position';
3763 $sql =
"UPDATE ".$this->db->prefix().$this->db->sanitize($this->table_element_line).
" SET ".$this->db->sanitize($fieldposition).
" = ".((int) $rang);
3764 $sql .=
" WHERE ".$this->db->sanitize($this->fk_element).
" = ".((int) $this->
id);
3765 $sql .=
" AND " . $this->db->sanitize($fieldposition) .
" = " . ((int) ($rang - 1));
3766 if (!$this->db->query($sql)) {
3767 $this->error = $this->db->lasterror();
3771 $sql =
"UPDATE ".$this->db->prefix().$this->table_element_line.
" SET ".$this->db->sanitize($fieldposition).
" = ".((int) ($rang - 1));
3772 $sql .=
' WHERE rowid = '.((int) $rowid);
3773 if (!$this->db->query($sql)) {
3774 $this->error = $this->db->lasterror();
3791 if ($rang >= $max) {
3795 $fieldposition =
'rang';
3796 if (in_array($this->table_element_line, array(
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3797 $fieldposition =
'position';
3800 $sql =
"UPDATE ".$this->db->prefix().$this->db->sanitize($this->table_element_line).
" SET ".$this->db->sanitize($fieldposition).
" = ".((int) $rang);
3801 $sql .=
" WHERE ".$this->db->sanitize($this->fk_element).
" = ".((int) $this->
id);
3802 $sql .=
" AND " . $this->db->sanitize($fieldposition) .
" = " . ((int) ($rang + 1));
3803 if (!$this->db->query($sql)) {
3804 $this->error = $this->db->lasterror();
3808 $sql =
"UPDATE ".$this->db->prefix().$this->table_element_line.
" SET ".$this->db->sanitize($fieldposition).
" = ".((int) ($rang + 1));
3809 $sql .=
' WHERE rowid = '.((int) $rowid);
3810 if (!$this->db->query($sql)) {
3811 $this->error = $this->db->lasterror();
3826 $fieldposition =
'rang';
3827 if (in_array($this->table_element_line, array(
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3828 $fieldposition =
'position';
3831 $sql =
"SELECT " . $this->db->sanitize($fieldposition) .
" FROM ".$this->db->prefix().$this->db->sanitize($this->table_element_line);
3832 $sql .=
" WHERE rowid = ".((int) $rowid);
3834 dol_syslog(get_class($this).
"::getRangOfLine", LOG_DEBUG);
3835 $resql = $this->db->query($sql);
3840 $row = $this->db->fetch_row($resql);
3852 $fieldposition =
'rang';
3853 if (in_array($this->table_element_line, array(
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3854 $fieldposition =
'position';
3857 $sql =
"SELECT rowid FROM ".$this->db->prefix().$this->db->sanitize($this->table_element_line);
3858 $sql .=
" WHERE ".$this->db->sanitize($this->fk_element).
" = ".((int) $this->
id);
3859 $sql .=
" AND " . $this->db->sanitize($fieldposition) .
" = ".((int) $rang);
3860 $resql = $this->db->query($sql);
3865 $row = $this->db->fetch_row($resql);
3880 if (empty($packaging) || !is_numeric($packaging) || (
float) $packaging <= 0) {
3883 $sign = ((float) $qty < 0 ? -1 : 1);
3884 $absqty = abs((
float) $qty);
3885 if ($absqty < (
float) $packaging) {
3886 return $sign * (float) $packaging;
3888 if ((
float)
price2num($absqty - round($absqty / (
float) $packaging) * (
float) $packaging,
'MS') != 0) {
3889 $coeff = intval($absqty / (
float) $packaging) + 1;
3890 return $sign * (float)
price2num((
float) $packaging * $coeff,
'MS');
3905 $positionfield =
'rang';
3906 if (in_array($this->table_element, array(
'bom_bom',
'product_attribute'))) {
3907 $positionfield =
'position';
3910 $sql =
"SELECT max(".$this->db->sanitize($positionfield).
") FROM ".$this->db->prefix().$this->db->sanitize($this->table_element_line);
3911 $sql .=
" WHERE ".$this->db->sanitize($this->fk_element).
" = ".((int) $this->
id);
3914 if ($fk_parent_line) {
3915 $sql .=
" AND fk_parent_line = ".((int) $fk_parent_line);
3918 dol_syslog(get_class($this).
"::line_max", LOG_DEBUG);
3919 $resql = $this->db->query($sql);
3921 $row = $this->db->fetch_row($resql);
3923 if ($fk_parent_line) {
3924 if (!empty($row[0])) {
3947 if (!$this->table_element) {
3948 dol_syslog(get_class($this).
"::update_ref_ext was called on object with property table_element not defined", LOG_ERR);
3952 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
3953 $sql .=
" SET ref_ext = '".$this->db->escape($ref_ext).
"'";
3955 $sql .=
" WHERE ".(isset($this->table_rowid) ? $this->table_rowid :
'rowid').
" = ".((
int) $this->id);
3957 dol_syslog(get_class($this).
"::update_ref_ext", LOG_DEBUG);
3958 if ($this->db->query($sql)) {
3959 $this->ref_ext = $ref_ext;
3962 $this->error = $this->db->error();
3981 if (!$this->table_element) {
3982 $this->error =
'update_note was called on object with property table_element not defined';
3983 dol_syslog(get_class($this).
"::update_note was called on object with property table_element not defined", LOG_ERR);
3986 if (!in_array($suffix, array(
'',
'_public',
'_private'))) {
3987 $this->error =
'update_note Parameter suffix must be empty, \'_private\' or \'_public\'';
3988 dol_syslog(get_class($this).
"::update_note Parameter suffix must be empty, '_private' or '_public'", LOG_ERR);
3992 $newsuffix = $suffix;
3995 if ($this->table_element ==
'product' && $newsuffix ==
'_private') {
3998 if (in_array($this->table_element, array(
'actioncomm',
'adherent',
'advtargetemailing',
'cronjob',
'establishment'))) {
3999 $fieldusermod =
"fk_user_mod";
4000 } elseif ($this->table_element ==
'ecm_files') {
4001 $fieldusermod =
"fk_user_m";
4003 $fieldusermod =
"fk_user_modif";
4005 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
4006 $sql .=
" SET note".$this->db->sanitize($newsuffix).
" = ".(!empty($note) ? (
"'".$this->db->escape($note).
"'") :
"NULL");
4007 $sql .=
", ".$this->db->sanitize($fieldusermod).
" = ".((int) $user->id);
4008 $sql .=
" WHERE rowid = ".((int) $this->
id);
4010 dol_syslog(get_class($this).
"::update_note", LOG_DEBUG);
4011 if ($this->db->query($sql)) {
4012 if ($suffix ==
'_public') {
4013 $this->note_public = $note;
4014 } elseif ($suffix ==
'_private') {
4015 $this->note_private = $note;
4017 $this->note = $note;
4018 $this->note_private = $note;
4020 if (empty($notrigger)) {
4022 switch ($this->element) {
4024 $triggerName =
'COMPANY_MODIFY';
4027 $triggerName =
'BILL_MODIFY';
4029 case 'invoice_supplier':
4030 $triggerName =
'BILL_SUPPLIER_MODIFY';
4033 $triggerName =
'BILLREC_MODIFIY';
4035 case 'expensereport':
4036 $triggerName =
'EXPENSE_REPORT_MODIFY';
4039 $triggerName = (!empty($this->TRIGGER_PREFIX) ? $this->TRIGGER_PREFIX : strtoupper($this->element)) .
'_MODIFY';
4041 $ret = $this->call_trigger($triggerName, $user);
4048 $this->error = $this->db->lasterror();
4079 public function update_price($exclspec = 0, $roundingadjust =
'auto', $nodatabaseupdate = 0, $seller =
null)
4082 global
$conf, $hookmanager, $action;
4084 $parameters = array(
'exclspec' => $exclspec,
'roundingadjust' => $roundingadjust,
'nodatabaseupdate' => $nodatabaseupdate,
'seller' => $seller);
4085 $reshook = $hookmanager->executeHooks(
'updateTotalPrice', $parameters, $this, $action);
4088 } elseif ($reshook < 0) {
4093 $isElementForSupplier =
false;
4094 $roundTotalConstName =
'MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND';
4096 if ($this->element ==
'propal') {
4097 $MODULE =
"MODULE_DISALLOW_UPDATE_PRICE_PROPOSAL";
4098 } elseif ($this->element ==
'commande' || $this->element ==
'order') {
4099 $MODULE =
"MODULE_DISALLOW_UPDATE_PRICE_ORDER";
4100 } elseif ($this->element ==
'facture' || $this->element ==
'invoice') {
4101 $MODULE =
"MODULE_DISALLOW_UPDATE_PRICE_INVOICE";
4102 } elseif ($this->element ==
'facture_fourn' || $this->element ==
'supplier_invoice' || $this->element ==
'invoice_supplier' || $this->element ==
'invoice_supplier_rec') {
4103 $isElementForSupplier =
true;
4104 $MODULE =
"MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_INVOICE";
4105 } elseif ($this->element ==
'order_supplier' || $this->element ==
'supplier_order') {
4106 $isElementForSupplier =
true;
4107 $MODULE =
"MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_ORDER";
4108 } elseif ($this->element ==
'supplier_proposal') {
4109 $isElementForSupplier =
true;
4110 $MODULE =
"MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_PROPOSAL";
4112 if ($isElementForSupplier) {
4113 $roundTotalConstName =
'MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND_SUPPLIER';
4116 if (!empty($MODULE)) {
4119 foreach ($modsactivated as $mod) {
4127 include_once DOL_DOCUMENT_ROOT.
'/core/lib/price.lib.php';
4129 $forcedroundingmode = $roundingadjust;
4130 if ($forcedroundingmode ==
'auto' && isset(
$conf->global->{$roundTotalConstName})) {
4132 } elseif ($forcedroundingmode ==
'auto') {
4133 $forcedroundingmode =
'0';
4138 $multicurrency_tx = !empty($this->multicurrency_tx) ? $this->multicurrency_tx : 1;
4141 $fieldtva =
'total_tva';
4142 $fieldlocaltax1 =
'total_localtax1';
4143 $fieldlocaltax2 =
'total_localtax2';
4144 $fieldup =
'subprice';
4145 $base_price_type =
'HT';
4146 if ($this->element ==
'facture_fourn' || $this->element ==
'invoice_supplier') {
4150 if ($this->element ==
'invoice_supplier_rec') {
4153 if ($this->element ==
'expensereport') {
4157 $forcedroundingmode =
'0';
4158 $fieldup =
'value_unit';
4159 $base_price_type =
'TTC';
4162 $sql =
"SELECT rowid, qty, ".$this->db->sanitize($fieldup).
" as up, remise_percent,";
4163 $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,";
4164 $sql .=
' tva_tx as vatrate, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type,';
4165 $sql .=
' info_bits, product_type,';
4166 if ($this->element ==
'expensereport') {
4167 $sql .=
' comments as description';
4169 $sql .=
' description';
4171 if ($this->table_element_line ==
'facturedet') {
4172 $sql .=
', situation_percent';
4174 $sql .=
', multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc';
4175 $sql .=
" FROM ".$this->db->prefix().$this->db->sanitize($this->table_element_line);
4176 $sql .=
" WHERE ".$this->db->sanitize($this->fk_element).
" = ".((int) $this->
id);
4178 $product_field =
'product_type';
4179 if ($this->table_element_line ==
'contratdet') {
4180 $product_field =
'';
4182 if ($product_field) {
4183 $sql .=
" AND ".$this->db->sanitize($product_field).
" <> 9";
4186 $sql .=
' ORDER by rowid';
4188 dol_syslog(get_class($this).
"::update_price", LOG_DEBUG);
4190 $resql = $this->db->query($sql);
4192 $this->total_ht = 0;
4193 $this->total_tva = 0;
4194 $this->total_localtax1 = 0;
4195 $this->total_localtax2 = 0;
4196 $this->total_ttc = 0;
4197 $total_ht_by_vats = array();
4198 $total_tva_by_vats = array();
4199 $total_ttc_by_vats = array();
4200 $this->multicurrency_total_ht = 0;
4201 $this->multicurrency_total_tva = 0;
4202 $this->multicurrency_total_ttc = 0;
4206 $num = $this->db->num_rows($resql);
4209 $obj = $this->db->fetch_object($resql);
4212 $parameters = array(
'fk_element' => $obj->rowid);
4213 $reshook = $hookmanager->executeHooks(
'changeRoundingMode', $parameters, $this, $action);
4215 if (empty($reshook) && $forcedroundingmode ==
'0') {
4217 $localtax_array = array($obj->localtax1_type, $obj->localtax1_tx, $obj->localtax2_type, $obj->localtax2_tx);
4218 $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);
4220 $diff_when_using_price_ht =
price2num((
float) $tmpcal[1] - $obj->total_tva,
'MT', 1);
4221 $diff_on_current_total =
price2num($obj->total_ttc - $obj->total_ht - $obj->total_tva - $obj->total_localtax1 - $obj->total_localtax2,
'MT', 1);
4225 if ($diff_on_current_total) {
4227 $sqlfix =
"UPDATE ".$this->db->prefix().$this->table_element_line;
4228 $sqlfix .=
" SET ".$this->db->sanitize($fieldtva).
" = ".
price2num((
float) $tmpcal[1]).
", total_ttc = ".
price2num((
float) $tmpcal[2]);
4229 $sqlfix .=
", multicurrency_total_tva = ".price2num((
float) $tmpcal[17]).
", multicurrency_total_ttc = ".
price2num((
float) $tmpcal[18]);
4230 $sqlfix .=
" WHERE rowid = ".((int) $obj->rowid);
4231 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);
4232 $resqlfix = $this->db->query($sqlfix);
4236 $obj->total_tva = $tmpcal[1];
4237 $obj->total_ttc = $tmpcal[2];
4238 $obj->multicurrency_total_tva = $tmpcal[17];
4239 $obj->multicurrency_total_ttc = $tmpcal[18];
4240 } elseif ($diff_when_using_price_ht) {
4244 if ((
float) $tmpcal[0] == (
float) $obj->total_ht) {
4247 if ($obj->description !=
'(DEPOSIT)' && !
getDolGlobalInt(
'MAIN_DISABLE_AUTOFIX_CORRUPTED_LINES_WHEN_TOTAL_DOES_NOT_MATCH_RECALCULATION_FROM_UP')) {
4251 $sqlfix =
"UPDATE ".$this->db->prefix().$this->table_element_line;
4252 $sqlfix .=
" SET ".$this->db->sanitize($fieldtva).
" = ".
price2num((
float) $tmpcal[1]).
", total_ttc = ".
price2num((
float) $tmpcal[2]);
4253 $sqlfix .=
", multicurrency_total_tva = ".price2num((
float) $tmpcal[17]).
", multicurrency_total_ttc = ".
price2num((
float) $tmpcal[18]);
4254 $sqlfix .=
" WHERE rowid = ".((int) $obj->rowid);
4256 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);
4258 $resqlfix = $this->db->query($sqlfix);
4262 $obj->total_tva = $tmpcal[1];
4263 $obj->total_ttc = $tmpcal[2];
4264 $obj->multicurrency_total_tva = $tmpcal[17];
4265 $obj->multicurrency_total_ttc = $tmpcal[18];
4271 $this->total_ht += $obj->total_ht;
4272 $this->total_tva += $obj->total_tva;
4273 $this->total_localtax1 += $obj->total_localtax1;
4274 $this->total_localtax2 += $obj->total_localtax2;
4275 $this->total_ttc += $obj->total_ttc;
4276 $this->multicurrency_total_ht += $obj->multicurrency_total_ht;
4277 $this->multicurrency_total_tva += $obj->multicurrency_total_tva;
4278 $this->multicurrency_total_ttc += $obj->multicurrency_total_ttc;
4280 if (!isset($total_ht_by_vats[$obj->vatrate])) {
4281 $total_ht_by_vats[$obj->vatrate] = 0;
4283 if (!isset($total_tva_by_vats[$obj->vatrate])) {
4284 $total_tva_by_vats[$obj->vatrate] = 0;
4286 if (!isset($total_ttc_by_vats[$obj->vatrate])) {
4287 $total_ttc_by_vats[$obj->vatrate] = 0;
4289 $total_ht_by_vats[$obj->vatrate] += $obj->total_ht;
4290 $total_tva_by_vats[$obj->vatrate] += $obj->total_tva;
4291 $total_ttc_by_vats[$obj->vatrate] += $obj->total_ttc;
4293 if ($forcedroundingmode ==
'1') {
4294 if ($base_price_type ==
'TTC') {
4295 $tmpvat =
price2num($total_ttc_by_vats[$obj->vatrate] * $obj->vatrate / (100 + $obj->vatrate),
'MT', 1);
4297 $tmpvat =
price2num($total_ht_by_vats[$obj->vatrate] * $obj->vatrate / 100,
'MT', 1);
4299 $diff =
price2num($total_tva_by_vats[$obj->vatrate] - (
float) $tmpvat,
'MT', 1);
4302 $maxdiff = (10 * pow(10, -1 *
getDolGlobalInt(
'MAIN_MAX_DECIMALS_TOT', 0)));
4303 if (abs((
float) $diff) > $maxdiff) {
4305 $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.';
4307 $this->error = $errmsg;
4312 if ($base_price_type ==
'TTC') {
4313 $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);
4314 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);
4316 $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);
4317 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);
4320 $resqlfix = $this->db->query($sqlfix);
4326 $this->total_tva = (float)
price2num($this->total_tva - (
float) $diff,
'', 1);
4327 $total_tva_by_vats[$obj->vatrate] = (float)
price2num($total_tva_by_vats[$obj->vatrate] - (
float) $diff,
'', 1);
4328 if ($base_price_type ==
'TTC') {
4329 $this->total_ht = (float)
price2num($this->total_ht + (
float) $diff,
'', 1);
4330 $total_ht_by_vats[$obj->vatrate] = (float)
price2num($total_ht_by_vats[$obj->vatrate] + (
float) $diff,
'', 1);
4332 $this->total_ttc = (float)
price2num($this->total_ttc - (
float) $diff,
'', 1);
4333 $total_ttc_by_vats[$obj->vatrate] = (float)
price2num($total_ttc_by_vats[$obj->vatrate] - (
float) $diff,
'', 1);
4343 $this->total_ttc += isset($this->revenuestamp) ? $this->revenuestamp : 0;
4345 $this->multicurrency_total_ttc += isset($this->revenuestamp) ? ($this->revenuestamp * $multicurrency_tx) : 0;
4348 if (!empty($this->situation_cycle_ref) && !empty($this->situation_counter) && $this->situation_counter > 1 && method_exists($this,
'get_prev_sits')) {
4349 '@phan-var-force Facture $this';
4350 include_once DOL_DOCUMENT_ROOT.
'/compta/facture/class/facture.class.php';
4353 $prev_sits = $this->get_prev_sits();
4355 foreach ($prev_sits as $sit) {
4356 $this->total_ht -= $sit->total_ht;
4357 $this->total_tva -= $sit->total_tva;
4358 $this->total_localtax1 -= $sit->total_localtax1;
4359 $this->total_localtax2 -= $sit->total_localtax2;
4360 $this->total_ttc -= $sit->total_ttc;
4361 $this->multicurrency_total_ht -= $sit->multicurrency_total_ht;
4362 $this->multicurrency_total_tva -= $sit->multicurrency_total_tva;
4363 $this->multicurrency_total_ttc -= $sit->multicurrency_total_ttc;
4370 $this->total_ht = (float)
price2num($this->total_ht);
4371 $this->total_tva = (float)
price2num($this->total_tva);
4372 $this->total_localtax1 = (float)
price2num($this->total_localtax1);
4373 $this->total_localtax2 = (float)
price2num($this->total_localtax2);
4374 $this->total_ttc = (float)
price2num($this->total_ttc);
4376 $this->db->free($resql);
4379 $fieldht =
'total_ht';
4381 $fieldlocaltax1 =
'localtax1';
4382 $fieldlocaltax2 =
'localtax2';
4383 $fieldttc =
'total_ttc';
4385 if (in_array($this->element, array(
'propal',
'commande',
'facture',
'facturerec',
'supplier_proposal',
'order_supplier',
'facture_fourn',
'invoice_supplier',
'invoice_supplier_rec',
'expensereport'))) {
4386 $fieldtva =
'total_tva';
4389 if (!$error && empty($nodatabaseupdate)) {
4390 $sql =
"UPDATE ".$this->db->prefix().$this->table_element.
' SET';
4391 $sql .=
" ".$this->db->sanitize($fieldht).
" = ".((float)
price2num($this->total_ht,
'MT', 1)).
",";
4392 $sql .=
" ".$this->db->sanitize($fieldtva).
" = ".((float)
price2num($this->total_tva,
'MT', 1)).
",";
4393 $sql .=
" ".$this->db->sanitize($fieldlocaltax1).
" = ".((float)
price2num($this->total_localtax1,
'MT', 1)).
",";
4394 $sql .=
" ".$this->db->sanitize($fieldlocaltax2).
" = ".((float)
price2num($this->total_localtax2,
'MT', 1)).
",";
4395 $sql .=
" ".$this->db->sanitize($fieldttc).
" = ".((float)
price2num($this->total_ttc,
'MT', 1));
4396 $sql .=
", multicurrency_total_ht = ".((float)
price2num($this->multicurrency_total_ht,
'MT', 1));
4397 $sql .=
", multicurrency_total_tva = ".((float)
price2num($this->multicurrency_total_tva,
'MT', 1));
4398 $sql .=
", multicurrency_total_ttc = ".((float)
price2num($this->multicurrency_total_ttc,
'MT', 1));
4399 $sql .=
" WHERE rowid = ".((int) $this->
id);
4401 dol_syslog(get_class($this).
"::update_price", LOG_DEBUG);
4402 $resql = $this->db->query($sql);
4406 $this->error = $this->db->lasterror();
4407 $this->errors[] = $this->db->lasterror();
4412 $this->db->commit();
4415 $this->db->rollback();
4435 public function add_object_linked($origin =
null, $origin_id =
null, $f_user =
null, $notrigger = 0)
4438 global $user, $hookmanager, $action;
4441 if (empty($this->origin_type) && !empty($this->origin)) {
4442 $this->origin_type = $this->origin;
4444 $origin = (!empty($origin) ? $origin : $this->origin_type);
4445 $origin_id = (!empty($origin_id) ? $origin_id : $this->origin_id);
4446 $f_user = isset($f_user) ? $f_user : $user;
4449 if ($origin ==
'order') {
4450 $origin =
'commande';
4452 if ($origin ==
'invoice') {
4453 $origin =
'facture';
4455 if ($origin ==
'invoice_template') {
4456 $origin =
'facturerec';
4458 if ($origin ==
'supplierorder') {
4459 $origin =
'order_supplier';
4463 $targettype = $this->getElementType();
4465 $parameters = array(
'targettype' => $targettype);
4467 $reshook = $hookmanager->executeHooks(
'setLinkedObjectSourceTargetType', $parameters, $this, $action);
4469 if (!empty($hookmanager->resArray[
'targettype'])) {
4470 $targettype = $hookmanager->resArray[
'targettype'];
4477 $sql =
"INSERT INTO " . $this->db->prefix() .
"element_element (";
4478 $sql .=
"fk_source";
4479 $sql .=
", sourcetype";
4480 $sql .=
", fk_target";
4481 $sql .=
", targettype";
4482 $sql .=
") VALUES (";
4483 $sql .= ((int) $origin_id);
4484 $sql .=
", '" . $this->db->escape($origin) .
"'";
4485 $sql .=
", " . ((int) $this->
id);
4486 $sql .=
", '" . $this->db->escape($targettype) .
"'";
4489 dol_syslog(get_class($this) .
"::add_object_linked", LOG_DEBUG);
4490 if ($this->db->query($sql)) {
4494 if ($origin ===
'order_supplier' && $targettype ===
'invoice_supplier' && $this->element ===
'invoice_supplier' && (
int) $origin_id > 0 && (
int) $this->
id > 0) {
4495 $sourceinvoices = array();
4497 $sqlsources =
"SELECT DISTINCT rc.fk_invoice_supplier_source as rowid";
4498 $sqlsources .=
" FROM ".$this->db->prefix().
"societe_remise_except as rc";
4499 $sqlsources .=
" WHERE rc.fk_invoice_supplier = ".((int) $this->
id);
4500 $sqlsources .=
" AND rc.fk_invoice_supplier_source IS NOT NULL";
4502 $resqlsources = $this->db->query($sqlsources);
4503 if ($resqlsources) {
4504 while ($objsrc = $this->db->fetch_object($resqlsources)) {
4505 $srcid = (int) $objsrc->rowid;
4506 if ($srcid > 0 && $srcid !== (
int) $this->
id) {
4507 $sourceinvoices[$srcid] = $srcid;
4511 dol_syslog(get_class($this).
"::add_object_linked Failed to read supplier invoice discounts sources", LOG_WARNING);
4514 if (!empty($sourceinvoices)) {
4515 $existing = array();
4516 $sourcelist = implode(
',', $sourceinvoices);
4518 $sqlexists =
"SELECT fk_target";
4519 $sqlexists .=
" FROM ".$this->db->prefix().
"element_element";
4520 $sqlexists .=
" WHERE fk_source = ".((int) $origin_id);
4521 $sqlexists .=
" AND sourcetype = '".$this->db->escape($origin).
"'";
4522 $sqlexists .=
" AND targettype = '".$this->db->escape($targettype).
"'";
4523 $sqlexists .=
" AND fk_target IN (".$this->db->sanitize($sourcelist).
")";
4525 $resqlexists = $this->db->query($sqlexists);
4527 while ($objexist = $this->db->fetch_object($resqlexists)) {
4528 $existing[(int) $objexist->fk_target] = 1;
4531 dol_syslog(get_class($this).
"::add_object_linked Failed to read existing linked supplier invoices", LOG_WARNING);
4534 foreach ($sourceinvoices as $srcid) {
4535 if (!empty($existing[(
int) $srcid])) {
4539 $sqladd =
"INSERT INTO " . $this->db->prefix() .
"element_element (fk_source, sourcetype, fk_target, targettype)";
4540 $sqladd .=
" VALUES (".((int) $origin_id).
", '".$this->db->escape($origin).
"', ".((int) $srcid).
", '".$this->db->escape($targettype).
"')";
4541 $this->db->query($sqladd);
4548 $this->context[
'link_origin'] = $origin;
4549 $this->context[
'link_origin_id'] = $origin_id;
4551 $result = $this->call_trigger(
'OBJECT_LINK_INSERT', $f_user);
4558 $this->error = $this->db->lasterror();
4563 $this->db->commit();
4566 $this->db->rollback();
4580 $coreModule = array(
'knowledgemanagement',
'partnership',
'workstation',
'ticket',
'recruitment',
'eventorganization',
'asset');
4582 return ((!empty($this->module) && !in_array($this->module, $coreModule)) ? $this->module.
'_' :
'').$this->element;
4608 public function fetchObjectLinked($sourceid =
null, $sourcetype =
'', $targetid =
null, $targettype =
'', $clause =
'OR', $alsosametype = 1, $orderby =
'sourcetype', $loadalsoobjects = 1)
4610 global $hookmanager, $action;
4615 if ($this->
id > 0 && !empty($this->linkedObjectsFullLoaded[$this->
id])) {
4619 $this->linkedObjectsIds = array();
4620 $this->linkedObjects = array();
4623 $parameters = array(
4624 'sourceid' => $sourceid,
4625 'sourcetype' => $sourcetype,
4626 'targetid' => $targetid,
4627 'targettype' => $targettype,
4628 'clause' => $clause,
4629 'alsosametype' => $alsosametype,
4630 'orderby' => $orderby,
4631 'loadalsoobjects' => $loadalsoobjects
4633 $reshook = $hookmanager->executeHooks(
'fetchObjectLinked', $parameters, $this, $action);
4638 $justsource =
false;
4639 $justtarget =
false;
4640 $withtargettype =
false;
4641 $withsourcetype =
false;
4644 if (is_object($hookmanager)) {
4645 $parameters = array(
'sourcetype' => $sourcetype,
'sourceid' => $sourceid,
'targettype' => $targettype,
'targetid' => $targetid);
4646 $reshook = $hookmanager->executeHooks(
'setLinkedObjectSourceTargetType', $parameters, $this, $action);
4648 if (!empty($hookmanager->resArray[
'sourcetype'])) {
4649 $sourcetype = $hookmanager->resArray[
'sourcetype'];
4651 if (!empty($hookmanager->resArray[
'sourceid'])) {
4652 $sourceid = $hookmanager->resArray[
'sourceid'];
4654 if (!empty($hookmanager->resArray[
'targettype'])) {
4655 $targettype = $hookmanager->resArray[
'targettype'];
4657 if (!empty($hookmanager->resArray[
'targetid'])) {
4658 $targetid = $hookmanager->resArray[
'targetid'];
4663 if (!empty($sourceid) && !empty($sourcetype) && empty($targetid)) {
4665 if (!empty($targettype)) {
4666 $withtargettype =
true;
4669 if (!empty($targetid) && !empty($targettype) && empty($sourceid)) {
4671 if (!empty($sourcetype)) {
4672 $withsourcetype =
true;
4676 $sourceid = (!empty($sourceid) ? $sourceid :
$this->id);
4677 $targetid = (!empty($targetid) ? $targetid :
$this->id);
4678 $sourcetype = (!empty($sourcetype) ? $sourcetype : $this->getElementType());
4679 $targettype = (!empty($targettype) ? $targettype : $this->getElementType());
4688 $sql =
"SELECT rowid, fk_source, sourcetype, fk_target, targettype";
4689 $sql .=
" FROM ".$this->db->prefix().
"element_element";
4691 if ($justsource || $justtarget) {
4693 $sql .=
"fk_source = ".((int) $sourceid).
" AND sourcetype = '".$this->db->escape($sourcetype).
"'";
4694 if ($withtargettype) {
4695 $sql .=
" AND targettype = '".$this->db->escape($targettype).
"'";
4697 } elseif ($justtarget) {
4698 $sql .=
"fk_target = ".((int) $targetid).
" AND targettype = '".$this->db->escape($targettype).
"'";
4699 if ($withsourcetype) {
4700 $sql .=
" AND sourcetype = '".$this->db->escape($sourcetype).
"'";
4704 $sql .=
"(fk_source = ".((int) $sourceid).
" AND sourcetype = '".$this->db->escape($sourcetype).
"')";
4705 $sql .=
" ".$this->db->sanitize($clause).
" (fk_target = ".((int) $targetid).
" AND targettype = '".$this->db->escape($targettype).
"')";
4706 if ($loadalsoobjects && $this->
id > 0 && $sourceid == $this->
id && $sourcetype == $this->element && $targetid == $this->
id && $targettype == $this->element && $clause ==
'OR') {
4707 $this->linkedObjectsFullLoaded[
$this->id] =
true;
4710 $sql .= $this->db->order($orderby);
4712 dol_syslog(get_class($this).
"::fetchObjectLink", LOG_DEBUG);
4714 $resql = $this->db->query($sql);
4716 $num = $this->db->num_rows($resql);
4719 $obj = $this->db->fetch_object($resql);
4720 if ($justsource || $justtarget) {
4722 $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
4723 } elseif ($justtarget) {
4724 $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
4727 if ($obj->fk_source == $sourceid && $obj->sourcetype == $sourcetype) {
4728 $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
4730 if ($obj->fk_target == $targetid && $obj->targettype == $targettype) {
4731 $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
4737 if (!empty($this->linkedObjectsIds)) {
4738 $tmparray = $this->linkedObjectsIds;
4739 foreach ($tmparray as $objecttype => $objectids) {
4741 $element = $element_properties[
'element'];
4742 $classPath = $element_properties[
'classpath'];
4743 $classFile = $element_properties[
'classfile'];
4744 $className = $element_properties[
'classname'];
4745 $module = $element_properties[
'module'];
4748 if (
isModEnabled($module) && (($element != $this->element) || $alsosametype)) {
4749 if ($loadalsoobjects && (is_numeric($loadalsoobjects) || ($loadalsoobjects === $objecttype))) {
4751 if (class_exists($className)) {
4752 foreach ($objectids as $i => $objectid) {
4753 $object =
new $className($this->db);
4754 '@phan-var-force CommonObject $object';
4755 $ret =
$object->fetch($objectid);
4757 $this->linkedObjects[$objecttype][$i] =
$object;
4763 unset($this->linkedObjectsIds[$objecttype]);
4782 if ($this->
id > 0 && !empty($this->linkedObjectsFullLoaded[$this->
id])) {
4783 unset($this->linkedObjectsFullLoaded[$this->
id]);
4801 public function updateObjectLinked($sourceid =
null, $sourcetype =
'', $targetid =
null, $targettype =
'', $f_user =
null, $notrigger = 0)
4804 $updatesource =
false;
4805 $updatetarget =
false;
4806 $f_user = isset($f_user) ? $f_user : $user;
4809 if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) {
4810 $updatesource =
true;
4811 } elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) {
4812 $updatetarget =
true;
4818 $sql =
"UPDATE " . $this->db->prefix() .
"element_element SET ";
4819 if ($updatesource) {
4820 $sql .=
"fk_source = " . ((int) $sourceid);
4821 $sql .=
", sourcetype = '" . $this->db->escape($sourcetype) .
"'";
4822 $sql .=
" WHERE fk_target = " . ((int) $this->
id);
4823 $sql .=
" AND targettype = '" . $this->db->escape($this->element) .
"'";
4824 } elseif ($updatetarget) {
4825 $sql .=
"fk_target = " . ((int) $targetid);
4826 $sql .=
", targettype = '" . $this->db->escape($targettype) .
"'";
4827 $sql .=
" WHERE fk_source = " . ((int) $this->
id);
4828 $sql .=
" AND sourcetype = '" . $this->db->escape($this->element) .
"'";
4831 dol_syslog(get_class($this) .
"::updateObjectLinked", LOG_DEBUG);
4832 if ($this->db->query($sql)) {
4835 $this->context[
'link_source_id'] = $sourceid;
4836 $this->context[
'link_source_type'] = $sourcetype;
4837 $this->context[
'link_target_id'] = $targetid;
4838 $this->context[
'link_target_type'] = $targettype;
4840 $result = $this->call_trigger(
'OBJECT_LINK_MODIFY', $f_user);
4847 $this->error = $this->db->lasterror();
4852 $this->db->commit();
4855 $this->db->rollback();
4873 public function deleteObjectLinked($sourceid =
null, $sourcetype =
'', $targetid =
null, $targettype =
'', $rowid = 0, $f_user =
null, $notrigger = 0)
4876 $deletesource =
false;
4877 $deletetarget =
false;
4878 $f_user = isset($f_user) ? $f_user : $user;
4880 if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) {
4881 $deletesource =
true;
4882 } elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) {
4883 $deletetarget =
true;
4886 $element = $this->getElementType();
4887 $sourceid = (!empty($sourceid) ? $sourceid :
$this->id);
4888 $sourcetype = (!empty($sourcetype) ? $sourcetype : $element);
4889 $targetid = (!empty($targetid) ? $targetid :
$this->id);
4890 $targettype = (!empty($targettype) ? $targettype : $element);
4896 $this->context[
'link_id'] = $rowid;
4897 $this->context[
'link_source_id'] = $sourceid;
4898 $this->context[
'link_source_type'] = $sourcetype;
4899 $this->context[
'link_target_id'] = $targetid;
4900 $this->context[
'link_target_type'] = $targettype;
4902 $result = $this->call_trigger(
'OBJECT_LINK_DELETE', $f_user);
4910 $sql =
"DELETE FROM " . $this->db->prefix() .
"element_element";
4913 $sql .=
" rowid = " . ((int) $rowid);
4915 if ($deletesource) {
4916 $sql .=
" fk_source = " . ((int) $sourceid) .
" AND sourcetype = '" . $this->db->escape($sourcetype) .
"'";
4917 $sql .=
" AND fk_target = " . ((int) $this->
id) .
" AND targettype = '" . $this->db->escape($element) .
"'";
4918 } elseif ($deletetarget) {
4919 $sql .=
" fk_target = " . ((int) $targetid) .
" AND targettype = '" . $this->db->escape($targettype) .
"'";
4920 $sql .=
" AND fk_source = " . ((int) $this->
id) .
" AND sourcetype = '" . $this->db->escape($element) .
"'";
4922 $sql .=
" (fk_source = " . ((int) $this->
id) .
" AND sourcetype = '" . $this->db->escape($element) .
"')";
4924 $sql .=
" (fk_target = " . ((int) $this->
id) .
" AND targettype = '" . $this->db->escape($element) .
"')";
4928 dol_syslog(get_class($this) .
"::deleteObjectLinked", LOG_DEBUG);
4929 if (!$this->db->query($sql)) {
4930 $this->error = $this->db->lasterror();
4931 $this->errors[] = $this->error;
4937 $this->db->commit();
4940 $this->db->rollback();
4956 if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
4959 if (!preg_match(
'/^[_a-zA-Z0-9]+$/', $field_select)) {
4960 dol_syslog(
'Invalid value $field_select for parameter '.$field_select.
' in call to getAllItemsLinkedByObjectID(). Must be a single field name.', LOG_ERR);
4965 $sql =
"SELECT ".$db->sanitize($field_select).
" FROM ".
$db->prefix().$db->sanitize($table_element).
" WHERE ".
$db->sanitize($field_where).
" = ".((int) $fk_object_where);
4966 $resql =
$db->query($sql);
4969 if (!empty($resql)) {
4970 while ($res =
$db->fetch_object($resql)) {
4971 $TRes[] = $res->{$field_select};
4988 if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
4994 $sql =
"SELECT COUNT(*) as nb FROM ".$db->prefix().$db->sanitize($table_element).
" WHERE ".
$db->sanitize($field_where).
" = ".((int) $fk_object_where);
4995 $resql =
$db->query($sql);
4998 $res =
$db->fetch_object($resql);
5017 if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
5023 $sql =
"DELETE FROM ".$db->prefix().$table_element.
" WHERE ".
$db->sanitize($field_where).
" = ".((int) $fk_object_where);
5024 $resql =
$db->query($sql);
5026 if (empty($resql)) {
5044 public function setStatut($status, $elementId =
null, $elementType =
'', $trigkey =
'', $fieldstatus =
'')
5048 $savElementId = $elementId;
5050 $elementId = (!empty($elementId) ? $elementId :
$this->id);
5051 $elementTable = (!empty($elementType) ? $elementType : $this->table_element);
5055 if (empty($fieldstatus)) {
5056 if ($elementTable ==
'facture_rec') {
5057 $fieldstatus =
"suspended";
5059 if ($elementTable ==
'mailing') {
5060 $fieldstatus =
"statut";
5062 if ($elementTable ==
'cronjob') {
5063 $fieldstatus =
"status";
5065 if ($elementTable ==
'user') {
5066 $fieldstatus =
"statut";
5068 if ($elementTable ==
'expensereport') {
5069 $fieldstatus =
"fk_statut";
5071 if ($elementTable ==
'receptiondet_batch') {
5072 $fieldstatus =
"status";
5074 if ($elementTable ==
'prelevement_bons') {
5075 $fieldstatus =
"statut";
5077 if ($elementTable ==
'bank_account') {
5078 $fieldstatus =
"clos";
5080 if (isset($this->fields) && is_array($this->fields) && array_key_exists(
'status', $this->fields)) {
5081 $fieldstatus =
'status';
5084 if (empty($fieldstatus)) {
5085 $fieldstatus =
'fk_statut';
5089 $sql =
"UPDATE ".$this->db->prefix().$this->db->sanitize($elementTable);
5090 $sql .=
" SET ".$this->db->sanitize($fieldstatus).
" = ".((int) $status);
5093 if ($status == 1 && in_array($elementTable, array(
'expensereport',
'inventory'))) {
5094 $sql .=
", fk_user_valid = ".((int) $user->id);
5096 if ($status == 1 && in_array($elementTable, array(
'expensereport'))) {
5097 $sql .=
", date_valid = '".$this->db->idate(
dol_now()).
"'";
5099 if ($status == 1 && in_array($elementTable, array(
'inventory'))) {
5100 $sql .=
", date_validation = '".$this->db->idate(
dol_now()).
"'";
5102 $sql .=
" WHERE rowid = ".((int) $elementId);
5103 $sql .=
" AND ".$this->db->sanitize($fieldstatus).
" <> ".((int) $status);
5105 dol_syslog(get_class($this).
"::setStatut", LOG_DEBUG);
5106 $resql = $this->db->query($sql);
5110 $nb_rows_affected = $this->db->affected_rows($resql);
5112 if ($nb_rows_affected > 0) {
5113 if (empty($trigkey)) {
5115 if ($this->element ==
'supplier_proposal' && $status == 2) {
5116 $trigkey =
'SUPPLIER_PROPOSAL_SIGN';
5118 if ($this->element ==
'supplier_proposal' && $status == 3) {
5119 $trigkey =
'SUPPLIER_PROPOSAL_REFUSE';
5121 if ($this->element ==
'supplier_proposal' && $status == 4) {
5122 $trigkey =
'SUPPLIER_PROPOSAL_CLOSE';
5124 if ($this->element ==
'fichinter' && $status == 3) {
5125 $trigkey =
'FICHINTER_CLASSIFY_DONE';
5127 if ($this->element ==
'fichinter' && $status == 2) {
5128 $trigkey =
'FICHINTER_CLASSIFY_BILLED';
5130 if ($this->element ==
'fichinter' && $status == 1) {
5131 $trigkey =
'FICHINTER_CLASSIFY_UNBILLED';
5135 $this->context = array_merge($this->context, array(
'newstatus' => $status));
5137 if ($trigkey && $trigkey !=
'none') {
5141 $result = $this->call_trigger($trigkey, $user);
5152 $this->db->commit();
5154 if (empty($savElementId)) {
5156 if ($fieldstatus ==
'dispute_status') {
5157 $this->dispute_status = $status;
5158 } elseif ($fieldstatus ==
'tosell') {
5160 } elseif ($fieldstatus ==
'tobuy') {
5161 $this->status_buy = $status;
5162 } elseif ($fieldstatus ==
'tobatch') {
5163 $this->status_batch = $status;
5171 $this->db->rollback();
5172 dol_syslog(get_class($this).
"::setStatut ".$this->error, LOG_ERR);
5176 $this->error = $this->db->lasterror();
5177 $this->db->rollback();
5192 if (empty(
$id) && empty($ref)) {
5202 $sql =
"SELECT rowid, canvas";
5203 $sql .=
" FROM ".$this->db->prefix().$this->table_element;
5204 $sql .=
" WHERE entity IN (".getEntity($this->element).
")";
5206 $sql .=
" AND rowid = ".((int)
$id);
5209 $sql .=
" AND ref = '".$this->db->escape($ref).
"'";
5212 $resql = $this->db->query($sql);
5214 $obj = $this->db->fetch_object($resql);
5216 $this->canvas = $obj->canvas;
5236 $sql =
"SELECT special_code FROM ".$this->db->prefix().$this->db->sanitize($this->table_element_line);
5237 $sql .=
" WHERE rowid = ".((int) $lineid);
5238 $resql = $this->db->query($sql);
5240 $row = $this->db->fetch_row($resql);
5241 return (!empty($row[0]) ? $row[0] : 0);
5264 if (!isset($this->childtables) || !is_array($this->childtables) || count($this->childtables) == 0) {
5265 dol_print_error(
null,
'Called isObjectUsed on a class with property this->childtables not defined');
5269 $arraytoscan = $this->childtables;
5271 $tmparray = array_keys($this->childtables);
5272 if (is_numeric($tmparray[0])) {
5273 $arraytoscan = array_flip($this->childtables);
5278 foreach ($arraytoscan as $table => $element) {
5282 if (isset($element[
'enabled']) && !empty($element[
'enabled'])) {
5283 $enabled = (int)
dol_eval((
string) $element[
'enabled'], 1);
5284 if (empty($enabled)) {
5290 $sql =
"SELECT COUNT(*) as nb";
5291 $sql .=
" FROM ".$this->db->prefix().$this->db->sanitize($table).
" as c";
5292 if (!empty($element[
'parent']) && !empty($element[
'parentkey'])) {
5293 $sql .=
", ".$this->db->prefix().$this->db->sanitize($element[
'parent']).
" as p";
5295 if (!empty($element[
'fk_element'])) {
5296 $sql .=
" WHERE c.".$this->db->sanitize($element[
'fk_element']).
" = ".((int)
$id);
5298 $sql .=
" WHERE c.".$this->db->sanitize($this->fk_element).
" = ".((int)
$id);
5300 if (!empty($element[
'parent']) && !empty($element[
'parentkey'])) {
5301 $sql .=
" AND c.".$this->db->sanitize($element[
'parentkey']).
" = p.rowid";
5303 if (!empty($element[
'parent']) && !empty($element[
'parenttypefield']) && !empty($element[
'parenttypevalue'])) {
5304 $sql .=
" AND c.".$this->db->sanitize($element[
'parenttypefield']).
" = '".$this->db->escape($element[
'parenttypevalue']).
"'";
5306 if (!empty($entity)) {
5307 if (!empty($element[
'parent']) && !empty($element[
'parentkey'])) {
5308 $sql .=
" AND p.entity = ".((int) $entity);
5310 $sql .=
" AND c.entity = ".((int) $entity);
5315 $resql = $this->db->query($sql);
5317 $obj = $this->db->fetch_object($resql);
5319 $langs->load(
"errors");
5321 $haschild += (int) $obj->nb;
5322 if (is_numeric($element)) {
5323 $this->errors[] = $langs->transnoentitiesnoconv(
"ErrorRecordHasAtLeastOneChildOfType", method_exists($this,
'getNomUrl') ? $this->getNomUrl() : $this->ref, $table);
5324 } elseif (is_string($element)) {
5325 $this->errors[] = $langs->transnoentitiesnoconv(
"ErrorRecordHasAtLeastOneChildOfType", method_exists($this,
'getNomUrl') ? $this->getNomUrl() : $this->ref, $langs->transnoentitiesnoconv($element));
5327 $this->errors[] = $langs->transnoentitiesnoconv(
"ErrorRecordHasAtLeastOneChildOfType", method_exists($this,
'getNomUrl') ? $this->getNomUrl() : $this->ref, $langs->transnoentitiesnoconv($element[
'name']));
5332 $this->errors[] = $this->db->lasterror();
5337 if ($haschild > 0) {
5338 $this->errors[] =
"ErrorRecordHasChildren";
5355 foreach ($this->lines as $key => $val) {
5357 if ($predefined == -1) {
5360 if ($predefined == 1 && $val->fk_product > 0) {
5363 if ($predefined == 0 && $val->fk_product <= 0) {
5366 if ($predefined == 2 && $val->fk_product > 0 && $val->product_type == 0) {
5369 if ($predefined == 3 && $val->fk_product > 0 && $val->product_type == 1) {
5376 dol_syslog(get_class($this).
'::hasProductsOrServices we found '.$nb.
' qualified lines of products/servcies');
5387 if (!empty($this->table_element_line) && ($this->table_element_line !=
'expeditiondet')) {
5388 $total_discount = 0.00;
5390 $sql =
"SELECT subprice as pu_ht, qty, remise_percent, total_ht";
5391 $sql .=
" FROM ".$this->db->prefix().$this->table_element_line;
5392 $sql .=
" WHERE ".$this->db->sanitize($this->fk_element).
" = ".((int) $this->
id);
5394 dol_syslog(get_class($this).
'::getTotalDiscount', LOG_DEBUG);
5395 $resql = $this->db->query($sql);
5397 $num = $this->db->num_rows($resql);
5400 $obj = $this->db->fetch_object($resql);
5402 $pu_ht = $obj->pu_ht;
5404 $total_ht = $obj->total_ht;
5406 $total_discount_line = (float)
price2num(($pu_ht * $qty) - $total_ht,
'MT');
5407 $total_discount += $total_discount_line;
5414 return (
float)
price2num($total_discount);
5436 if (empty($this->lines)) {
5437 return array(
'weight' => $totalWeight,
'volume' => $totalVolume,
'ordered' => $totalOrdered,
'toship' => $totalToShip);
5440 foreach ($this->lines as $line) {
5441 if (isset($line->qty_asked)) {
5442 $totalOrdered += $line->qty_asked;
5444 if (isset($line->qty_shipped)) {
5445 $totalToShip += $line->qty_shipped;
5446 } elseif ($line->element ==
'commandefournisseurdispatch' && isset($line->qty)) {
5447 if (empty($totalToShip)) {
5450 $totalToShip += $line->qty;
5454 if ($this->element ==
'shipping') {
5456 $qty = $line->qty_shipped ? $line->qty_shipped : 0;
5458 $qty = $line->qty ? $line->qty : 0;
5461 $weight = !empty($line->weight) ? $line->weight : 0;
5462 ($weight == 0 && !empty($line->product->weight)) ? $weight = $line->product->weight : 0;
5463 $volume = !empty($line->volume) ? $line->volume : 0;
5464 ($volume == 0 && !empty($line->product->volume)) ? $volume = $line->product->volume : 0;
5466 $weight_units = !empty($line->weight_units) ? $line->weight_units : 0;
5467 ($weight_units == 0 && !empty($line->product->weight_units)) ? $weight_units = $line->product->weight_units : 0;
5468 $volume_units = !empty($line->volume_units) ? $line->volume_units : 0;
5469 ($volume_units == 0 && !empty($line->product->volume_units)) ? $volume_units = $line->product->volume_units : 0;
5473 if (!empty($weight_units)) {
5474 $weightUnit = $weight_units;
5476 if (!empty($volume_units)) {
5477 $volumeUnit = $volume_units;
5480 if (empty($totalWeight)) {
5483 if (empty($totalVolume)) {
5488 if ($weight_units < 50) {
5489 $trueWeightUnit = pow(10, $weightUnit);
5490 $totalWeight += $weight * $qty * $trueWeightUnit;
5492 if ($weight_units == 99) {
5494 $trueWeightUnit = 0.45359237;
5495 $totalWeight += $weight * $qty * $trueWeightUnit;
5496 } elseif ($weight_units == 98) {
5498 $trueWeightUnit = 0.0283495;
5499 $totalWeight += $weight * $qty * $trueWeightUnit;
5501 $totalWeight += $weight * $qty;
5504 if ($volume_units < 50) {
5506 $trueVolumeUnit = pow(10, $volumeUnit);
5508 $totalVolume += $volume * $qty * $trueVolumeUnit;
5510 $totalVolume += $volume * $qty;
5514 return array(
'weight' => $totalWeight,
'volume' => $totalVolume,
'ordered' => $totalOrdered,
'toship' => $totalToShip);
5527 $extraparams = (!empty($this->extraparams) ? json_encode($this->extraparams) :
null);
5528 $extraparams =
dol_trunc($extraparams, 250);
5530 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
5531 $sql .=
" SET extraparams = ".(!empty($extraparams) ?
"'".$this->db->escape($extraparams).
"'" :
"null");
5532 $sql .=
" WHERE rowid = ".((int) $this->
id);
5534 dol_syslog(get_class($this).
"::setExtraParameters", LOG_DEBUG);
5535 $resql = $this->db->query($sql);
5537 $this->error = $this->db->lasterror();
5538 $this->db->rollback();
5541 $this->db->commit();
5564 global
$conf, $user, $langs,
$object, $hookmanager, $extrafields, $form;
5567 if (!is_object($extrafields)) {
5568 require_once DOL_DOCUMENT_ROOT.
'/core/class/extrafields.class.php';
5571 $extrafields->fetch_name_optionals_label($this->table_element_line);
5576 $dirtpls = array_merge(
$conf->modules_parts[
'tpl'], array($defaulttpldir));
5577 foreach ($dirtpls as $module => $reldir) {
5578 if (!empty($module)) {
5581 $tpl = DOL_DOCUMENT_ROOT.$reldir.
'/objectline_create.tpl.php';
5584 if (empty(
$conf->file->strict_mode)) {
5585 $res = @include $tpl;
5587 $res = include $tpl;
5614 public function printObjectLines($action, $seller, $buyer, $selected = 0, $dateSelector = 0, $defaulttpldir =
'/core/tpl')
5616 global
$conf, $hookmanager, $langs, $user, $form, $extrafields,
$object;
5618 global $inputalsopricewithtax, $usemargins, $disableedit, $disablemove, $disableremove, $outputalsopricetotalwithtax;
5622 if (
isModEnabled(
'margin') && !empty($this->element) && in_array($this->element, array(
'facture',
'facturerec',
'propal',
'commande'))) {
5626 $num = count($this->lines);
5629 if (!is_object($extrafields)) {
5630 require_once DOL_DOCUMENT_ROOT.
'/core/class/extrafields.class.php';
5633 $extrafields->fetch_name_optionals_label($this->table_element_line);
5635 if (method_exists($this,
'loadExpeditions')) {
5637 $this->loadExpeditions();
5640 $parameters = array();
5641 $reshook = $hookmanager->executeHooks(
'printObjectLinesBlock', $parameters, $this, $action);
5642 if (empty($reshook)) {
5643 $parameters = array(
'num' => $num,
'dateSelector' => $dateSelector,
'seller' => $seller,
'buyer' => $buyer,
'selected' => $selected,
'table_element_line' => $this->table_element_line);
5644 $reshook = $hookmanager->executeHooks(
'printObjectLineTitle', $parameters, $this, $action);
5645 if (empty($reshook)) {
5649 $dirtpls = array_merge(
$conf->modules_parts[
'tpl'], array($defaulttpldir));
5650 foreach ($dirtpls as $module => $reldir) {
5652 if (!empty($module)) {
5655 $tpl = DOL_DOCUMENT_ROOT.$reldir.
'/objectline_title.tpl.php';
5657 if (file_exists($tpl)) {
5658 if (empty(
$conf->file->strict_mode)) {
5659 $res = @include $tpl;
5661 $res = include $tpl;
5672 print
"<!-- begin printObjectLines() -->\n";
5673 foreach ($this->lines as $line) {
5677 if (is_object($hookmanager)) {
5678 if (empty($line->fk_parent_line)) {
5679 $parameters = array(
'line' => $line,
'num' => $num,
'i' => $i,
'dateSelector' => $dateSelector,
'seller' => $seller,
'buyer' => $buyer,
'selected' => $selected,
'table_element_line' => $line->table_element,
'defaulttpldir' => $defaulttpldir);
5680 $reshook = $hookmanager->executeHooks(
'printObjectLine', $parameters, $this, $action);
5682 $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);
5683 $reshook = $hookmanager->executeHooks(
'printObjectSubLine', $parameters, $this, $action);
5686 if (empty($reshook)) {
5687 $this->printObjectLine($action, $line,
'', $num, $i, $dateSelector, $seller, $buyer, $selected, $extrafields, $defaulttpldir);
5692 print
"<!-- end printObjectLines() -->\n";
5713 public function printObjectLine($action, $line, $var, $num, $i, $dateSelector, $seller, $buyer, $selected = 0, $extrafields =
null, $defaulttpldir =
'/core/tpl')
5717 global $disableedit, $disablemove, $disableremove;
5724 if ($action !=
'editline' || $selected != $line->id) {
5726 if (!empty($line->fk_product) && $line->fk_product > 0) {
5727 $product_static =
new Product($this->db);
5728 $product_static->fetch($line->fk_product);
5730 $product_static->ref = (
string) $line->ref;
5731 $product_static->label = !empty($line->label) ? $line->label :
"";
5733 $text = $product_static->getNomUrl(1);
5738 if (property_exists($this,
'socid') && !empty($this->socid) && !is_object($this->thirdparty)) {
5739 dol_print_error(
null,
'Error: Method printObjectLine was called on an object and object->fetch_thirdparty was not done before');
5744 $prod->fetch($line->fk_product);
5746 $outputlangs = $langs;
5748 if (empty($newlang) &&
GETPOST(
'lang_id',
'aZ09')) {
5749 $newlang =
GETPOST(
'lang_id',
'aZ09');
5751 if (
getDolGlobalString(
'PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE') && empty($newlang) && is_object($this->thirdparty)) {
5752 $newlang = $this->thirdparty->default_lang;
5754 if (!empty($newlang)) {
5756 $outputlangs->setDefaultLang($newlang);
5759 $label = (!empty(
$prod->multilangs[$outputlangs->defaultlang][
"label"])) ?
$prod->multilangs[$outputlangs->defaultlang][
"label"] : $line->product_label;
5761 $label = $line->product_label;
5764 $text .=
' - '.(!empty($line->label) ? $line->label : $label);
5765 $description .= (
getDolGlobalInt(
'PRODUIT_DESC_IN_FORM_ACCORDING_TO_DEVICE') ?
'' : (!empty($line->description) ?
dol_htmlentitiesbr($line->description) :
''));
5769 if (empty((
float) $line->subprice_ttc) && $line->qty) {
5772 if ($line->remise_percent != 100) {
5773 $line->subprice_ttc = (float)
price2num($line->total_ttc * ($line->situation_percent ? 100 / $line->situation_percent : 1) / $line->qty / (1 - $line->remise_percent / 100),
'MU');
5776 $line->subprice_ttc = (float)
price2num((!empty($line->subprice) ? $line->subprice : 0) * (1 + ((!empty($line->tva_tx) ? $line->tva_tx : 0) / 100)),
'MU');
5779 $line->pu_ttc = $line->subprice_ttc;
5786 if (isset($this->expeditions[$line->id])) {
5787 $qty_shipped = $this->expeditions[$line->id];
5789 $disableedit = ($qty_shipped > 0) && ($qty_shipped >= $line->qty);
5791 $dirtpls = array_merge(
$conf->modules_parts[
'tpl'], array($defaulttpldir));
5792 foreach ($dirtpls as $module => $reldir) {
5794 if (!empty($module)) {
5797 $tpl = DOL_DOCUMENT_ROOT.$reldir.
'/objectline_view.tpl.php';
5800 if (file_exists($tpl)) {
5801 if (empty(
$conf->file->strict_mode)) {
5802 $res = @include $tpl;
5804 $res = include $tpl;
5814 if ($this->
status == 0 && $action ==
'editline' && $selected == $line->id) {
5815 $label = (!empty($line->label) ? $line->label : (($line->fk_product > 0) ? $line->product_label :
''));
5817 $line->subprice_ttc = (float)
price2num($line->subprice * (1 + ($line->tva_tx / 100)),
'MU');
5818 $line->pu_ttc = $line->subprice_ttc;
5823 $dirtpls = array_merge(
$conf->modules_parts[
'tpl'], array($defaulttpldir));
5824 foreach ($dirtpls as $module => $reldir) {
5825 if (!empty($module)) {
5828 $tpl = DOL_DOCUMENT_ROOT.$reldir.
'/objectline_edit.tpl.php';
5831 if (empty(
$conf->file->strict_mode)) {
5832 $res = @include $tpl;
5834 $res = include $tpl;
5859 global $langs, $hookmanager, $form, $action;
5861 print
'<!-- printOriginLinesList '.get_class($this).
' -->'.
"\n";
5862 print
'<tr class="liste_titre">';
5863 print
'<td class="linecolref">'.$langs->trans(
'Ref').
'</td>';
5864 print
'<td class="linecoldescription">'.$langs->trans(
'Description').
'</td>';
5865 print
'<td class="linecolvat right">'.$langs->trans(
'VATRate').
'</td>';
5866 print
'<td class="linecoluht right">'.$langs->trans(
'PriceUHT').
'</td>';
5868 print
'<td class="linecoluht_currency right">'.$langs->trans(
'PriceUHTCurrency').
'</td>';
5870 print
'<td class="linecolqty right">'.$langs->trans(
'Qty').
'</td>';
5872 print
'<td class="linecoluseunit left">'.$langs->trans(
'Unit').
'</td>';
5874 print
'<td class="linecoldiscount right">'.$langs->trans(
'ReductionShort').
'</td>';
5875 print
'<td class="linecolht right">'.$langs->trans(
'TotalHT').
'</td>';
5876 print
'<td class="center">';
5877 print $form->showCheckAddButtons(
'checkforselect', 1);
5882 if (!empty($this->lines)) {
5883 foreach ($this->lines as $line) {
5886 if (is_object($hookmanager)) {
5887 $parameters = array(
'line' => $line,
'i' => $i,
'restrictlist' => $restrictlist,
'selectedLines' => $selectedLines);
5888 if (!empty($line->fk_parent_line)) {
5889 $parameters[
'fk_parent_line'] = $line->fk_parent_line;
5891 $reshook = $hookmanager->executeHooks(
'printOriginObjectLine', $parameters, $this, $action);
5893 if (empty($reshook)) {
5894 $this->printOriginLine($line,
'', $restrictlist,
'/core/tpl', $selectedLines);
5915 public function printOriginLine($line, $var, $restrictlist =
'', $defaulttpldir =
'/core/tpl', $selectedLines = array())
5917 global $langs,
$conf;
5920 if (!empty($line->date_start)) {
5925 if ($line->date_debut_reel) {
5929 if (!empty($line->date_end)) {
5931 $date_end = $line->date_end;
5933 $date_end = $line->date_fin_prevue;
5934 if ($line->date_fin_reel) {
5935 $date_end = $line->date_fin_reel;
5940 $this->tpl[
'id'] = $line->id;
5942 $this->tpl[
'label'] =
'';
5943 if (!empty($line->fk_parent_line)) {
5944 $this->tpl[
'label'] .=
img_picto(
'',
'rightarrow.png');
5947 if (((
int) $line->info_bits & 2) == 2) {
5949 if (property_exists($this,
'socid')) {
5950 $discount->fk_soc = $this->socid;
5951 $discount->socid = $this->socid;
5953 $this->tpl[
'label'] .= $discount->getNomUrl(0,
'discount');
5954 } elseif (!empty($line->fk_product)) {
5955 $productstatic =
new Product($this->db);
5956 $productstatic->id = $line->fk_product;
5957 $productstatic->ref = (
string) $line->ref;
5958 $productstatic->type = $line->fk_product_type;
5959 if (empty($productstatic->ref)) {
5960 $line->fetch_product();
5961 $productstatic = $line->product;
5964 $this->tpl[
'label'] .= $productstatic->getNomUrl(1);
5965 $this->tpl[
'label'] .=
' - '.(!empty($line->label) ? $line->label : $line->product_label);
5967 if ($line->product_type == 1 && (
$date_start || $date_end)) {
5971 $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"')));
5972 if (!empty($line->desc)) {
5973 $this->tpl[
'label'] .= $line->desc;
5975 $this->tpl[
'label'] .= ($line->label ?
' '.$line->label :
'');
5979 if ($line->product_type == 1 && (
$date_start || $date_end)) {
5984 if (!empty($line->desc)) {
5985 '@phan-var-force OrderLine|FactureLigne|ContratLigne|FactureFournisseurLigneRec|SupplierInvoiceLine|SupplierProposalLine $line';
5986 if ($line->desc ==
'(CREDIT_NOTE)') {
5988 $discount->fetch($line->fk_remise_except);
5989 $this->tpl[
'description'] = $langs->transnoentities(
"DiscountFromCreditNote", $discount->getNomUrl(0));
5990 } elseif ($line->desc ==
'(DEPOSIT)') {
5992 $discount->fetch($line->fk_remise_except);
5993 $this->tpl[
'description'] = $langs->transnoentities(
"DiscountFromDeposit", $discount->getNomUrl(0));
5994 } elseif ($line->desc ==
'(EXCESS RECEIVED)') {
5996 $discount->fetch($line->fk_remise_except);
5997 $this->tpl[
'description'] = $langs->transnoentities(
"DiscountFromExcessReceived", $discount->getNomUrl(0));
5998 } elseif ($line->desc ==
'(EXCESS PAID)') {
6000 $discount->fetch($line->fk_remise_except);
6001 $this->tpl[
'description'] = $langs->transnoentities(
"DiscountFromExcessPaid", $discount->getNomUrl(0));
6003 $this->tpl[
'description'] =
dol_trunc($line->desc, 60);
6006 $this->tpl[
'description'] =
' ';
6010 $this->tpl[
'vat_rate'] =
vatrate($line->tva_tx,
true);
6011 $this->tpl[
'vat_rate'] .= (((int) $line->info_bits & 1) == 1) ?
'*' :
'';
6012 if (!empty($line->vat_src_code) && !preg_match(
'/\(/', $this->tpl[
'vat_rate'])) {
6013 $this->tpl[
'vat_rate'] .=
' ('.$line->vat_src_code.
')';
6016 $this->tpl[
'price'] =
price($line->subprice);
6017 $this->tpl[
'total_ht'] =
price($line->total_ht);
6018 $this->tpl[
'multicurrency_price'] =
price($line->multicurrency_subprice);
6019 $this->tpl[
'qty'] = (((int) $line->info_bits & 2) != 2) ? $line->qty :
' ';
6021 $this->tpl[
'unit'] = $line->getLabelOfUnit(
'long', $langs);
6022 $this->tpl[
'unit_short'] = $line->getLabelOfUnit(
'short', $langs);
6025 $this->tpl[
'remise_percent'] = (((int) $line->info_bits & 2) != 2) ?
vatrate((
string) $line->remise_percent,
true) :
' ';
6028 $this->tpl[
'strike'] = 0;
6030 $this->tpl[
'strike'] = 1;
6031 } elseif (defined(
'SUBTOTALS_SPECIAL_CODE') && $line->special_code == SUBTOTALS_SPECIAL_CODE) {
6036 $this->tpl[
'strike'] = 1;
6041 $dirtpls = array_merge(
$conf->modules_parts[
'tpl'], array($defaulttpldir));
6042 foreach ($dirtpls as $module => $reldir) {
6043 if (!empty($module)) {
6046 $tpl = DOL_DOCUMENT_ROOT.$reldir.
'/originproductline.tpl.php';
6049 if (empty(
$conf->file->strict_mode)) {
6050 $res = @include $tpl;
6052 $res = include $tpl;
6079 $sql =
"INSERT INTO ".$this->db->prefix().
"element_resources (";
6080 $sql .=
"resource_id";
6081 $sql .=
", resource_type";
6082 $sql .=
", element_id";
6083 $sql .=
", element_type";
6085 $sql .=
", mandatory";
6086 $sql .=
") VALUES (";
6087 $sql .= ((int) $resource_id);
6088 $sql .=
", '".$this->db->escape($resource_type).
"'";
6089 $sql .=
", '".$this->db->escape((
string) $this->
id).
"'";
6090 $sql .=
", '".$this->db->escape($this->element).
"'";
6091 $sql .=
", '".$this->db->escape((
string) $busy).
"'";
6092 $sql .=
", '".$this->db->escape((
string) $mandatory).
"'";
6095 dol_syslog(get_class($this).
"::add_element_resource", LOG_DEBUG);
6096 if ($this->db->query($sql)) {
6098 $result = $this->call_trigger(strtoupper($this->TRIGGER_PREFIX).
'_ADD_RESOURCE', $user);
6100 $this->db->rollback();
6104 $this->db->commit();
6107 $this->error = $this->db->lasterror();
6108 $this->db->rollback();
6129 $sql =
"DELETE FROM ".$this->db->prefix().
"element_resources";
6130 $sql .=
" WHERE rowid = ".((int) $rowid);
6132 dol_syslog(get_class($this).
"::delete_resource", LOG_DEBUG);
6134 $resql = $this->db->query($sql);
6136 $this->error = $this->db->lasterror();
6137 $this->db->rollback();
6141 $result = $this->call_trigger(strtoupper($this->TRIGGER_PREFIX).
'_DELETE_RESOURCE', $user);
6143 $this->db->rollback();
6147 $this->db->commit();
6161 if (isset($this->lines) && is_array($this->lines)) {
6162 $nboflines = count($this->lines);
6163 for ($i = 0; $i < $nboflines; $i++) {
6164 if (is_object($this->lines[$i])) {
6165 $this->lines[$i] = clone $this->lines[$i];
6184 protected function commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams =
null)
6186 global
$conf, $langs, $hookmanager, $action;
6188 $srctemplatepath =
'';
6190 $parameters = array(
'modelspath' => $modelspath,
'modele' => $modele,
'outputlangs' => $outputlangs,
'hidedetails' => $hidedetails,
'hidedesc' => $hidedesc,
'hideref' => $hideref,
'moreparams' => $moreparams);
6191 $reshook = $hookmanager->executeHooks(
'commonGenerateDocument', $parameters, $this, $action);
6193 if (!empty($reshook)) {
6197 dol_syslog(
"commonGenerateDocument modele=".$modele.
" outputlangs->defaultlang=".(is_object($outputlangs) ? $outputlangs->defaultlang :
'null'));
6199 if (empty($modele)) {
6200 $this->error =
'BadValueForParameterModele';
6205 $err = error_reporting();
6207 @set_time_limit(120);
6208 error_reporting($err);
6211 $tmp = explode(
':', $modele, 2);
6212 $saved_model = $modele;
6213 if (!empty($tmp[1])) {
6215 $srctemplatepath = $tmp[1];
6217 if (!preg_match(
'/^'.preg_quote(DOL_DATA_ROOT,
'/').
'\/(ecm|doctemplates)/', $srctemplatepath)) {
6218 $this->error =
'BadDirForTemplateFile';
6227 $dirmodels = array(
'/');
6228 if (is_array(
$conf->modules_parts[
'models'])) {
6229 $dirmodels = array_merge($dirmodels,
$conf->modules_parts[
'models']);
6231 foreach ($dirmodels as $reldir) {
6232 foreach (array(
'doc',
'pdf') as $prefix) {
6233 if (in_array(get_class($this), array(
'Adherent'))) {
6235 $file = $prefix.
"_".$modele.
".class.php";
6238 $file = $prefix.
"_".$modele.
".modules.php";
6245 if (file_exists($file)) {
6247 $classname = $prefix.
'_'.$modele;
6256 if ($filefound ===
'' || $classname ===
'') {
6257 $this->error = $langs->trans(
"Error").
' Failed to load doc generator with modelpaths='.$modelspath.
' - modele='.$modele;
6258 $this->errors[] = $this->error;
6269 require_once $filefound;
6271 $obj =
new $classname($this->db);
6283 '@phan-var-force ModelePDFMember $obj';
6287 if ($obj->type ==
'odt' && empty($srctemplatepath)) {
6288 $varfortemplatedir = $obj->scandir;
6292 $listoffiles = array();
6295 $listofdir = explode(
',', $dirtoscan);
6296 foreach ($listofdir as $key => $tmpdir) {
6297 $tmpdir = trim($tmpdir);
6298 $tmpdir = preg_replace(
'/DOL_DATA_ROOT/', DOL_DATA_ROOT, $tmpdir);
6300 unset($listofdir[$key]);
6303 if (is_dir($tmpdir)) {
6304 $tmpfiles =
dol_dir_list($tmpdir,
'files', 0,
'\.od(s|t)$',
'',
'name', SORT_ASC, 0);
6305 if (count($tmpfiles)) {
6306 $listoffiles = array_merge($listoffiles, $tmpfiles);
6311 if (count($listoffiles)) {
6312 foreach ($listoffiles as $record) {
6313 $srctemplatepath = $record[
'fullname'];
6319 if (empty($srctemplatepath)) {
6320 $this->error =
'ErrorGenerationAskedForOdtTemplateWithSrcFileNotDefined';
6325 if ($obj->type ==
'odt' && !empty($srctemplatepath)) {
6327 dol_syslog(
"Failed to locate template file ".$srctemplatepath, LOG_WARNING);
6328 $this->error =
'ErrorGenerationAskedForOdtTemplateWithSrcFileNotFound';
6335 $sav_charset_output = empty($outputlangs->charset_output) ?
'' : $outputlangs->charset_output;
6338 $this->model_pdf = $saved_model;
6343 $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath,
'member', 1,
'tmp_cards');
6345 $resultwritefile = -1;
6346 dol_syslog(
"Error generating document - Provided ".get_class($this).
" to ".get_class($obj).
"::write_file()", LOG_ERR);
6350 if ($this instanceof
Don) {
6351 $resultwritefile = $obj->write_file($this, $outputlangs );
6353 $resultwritefile = -1;
6354 dol_syslog(
"Error generating document - Provided ".get_class($this).
" to Don::write_file()", LOG_ERR);
6358 '@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';
6359 $this->context[
'moreparams'] = $moreparams;
6360 $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, $hidedetails, $hidedesc, $hideref);
6362 }
catch (\Throwable $e) {
6363 $resultwritefile = -1;
6364 $this->error = $e->getMessage();
6365 dol_syslog(
"Exception in write_file() for ".get_class($this).
": ".$e->getMessage(), LOG_ERR);
6370 if ($resultwritefile > 0) {
6371 $outputlangs->charset_output = $sav_charset_output;
6374 require_once DOL_DOCUMENT_ROOT.
'/core/lib/files.lib.php';
6378 if (!empty($obj->result[
'fullpath'])) {
6379 $destfull = $obj->result[
'fullpath'];
6382 $update_main_doc_field = 0;
6383 if (!empty($obj->update_main_doc_field)) {
6384 $update_main_doc_field = 1;
6390 $this->indexFile($destfull, $update_main_doc_field);
6393 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);
6399 $this->warnings = $obj->warnings;
6403 $outputlangs->charset_output = $sav_charset_output;
6404 if (empty($this->error)) {
6405 $this->error = $obj->error;
6407 if (empty($this->errors)) {
6408 $this->errors = $obj->errors;
6410 $this->warnings = $obj->warnings;
6411 dol_syslog(
"Error generating document for ".__CLASS__.
". Error: ".$this->error, LOG_ERR);
6425 public function indexFile($destfull, $update_main_doc_field)
6427 global
$conf, $user;
6429 $upload_dir = dirname($destfull);
6430 $destfile = basename($destfull);
6431 $rel_dir = preg_replace(
'/^'.preg_quote(DOL_DATA_ROOT,
'/').
'/',
'', $upload_dir);
6433 if (!preg_match(
'/[\\/]temp[\\/]|[\\/]thumbs|\.meta$/', $rel_dir)) {
6434 $filename = basename($destfile);
6435 $rel_dir = preg_replace(
'/[\\/]$/',
'', $rel_dir);
6436 $rel_dir = preg_replace(
'/^[\\/]/',
'', $rel_dir);
6438 include_once DOL_DOCUMENT_ROOT.
'/ecm/class/ecmfiles.class.php';
6439 $ecmfile =
new EcmFiles($this->db);
6440 $result = $ecmfile->fetch(0,
'', ($rel_dir ? $rel_dir.
'/' :
'').$filename);
6443 $setsharekey =
false;
6445 !empty($this->TRIGGER_PREFIX)
6448 $setsharekey =
true;
6451 if ($this->element ==
'propal' || $this->element ==
'proposal') {
6453 $setsharekey =
true;
6456 $setsharekey =
true;
6459 if ($this->element ==
'facture' &&
getDolGlobalInt(
"INVOICE_ALLOW_EXTERNAL_DOWNLOAD")) {
6460 $setsharekey =
true;
6462 if ($this->element ==
'bank_account' &&
getDolGlobalInt(
"BANK_ACCOUNT_ALLOW_EXTERNAL_DOWNLOAD")) {
6463 $setsharekey =
true;
6465 if ($this->element ==
'contrat' &&
getDolGlobalInt(
"CONTRACT_ALLOW_EXTERNAL_DOWNLOAD")) {
6466 $setsharekey =
true;
6468 if ($this->element ==
'supplier_proposal' &&
getDolGlobalInt(
"SUPPLIER_PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD")) {
6469 $setsharekey =
true;
6471 if ($this->element ==
'order_supplier' &&
getDolGlobalInt(
"SUPPLIER_ORDER_ALLOW_EXTERNAL_DOWNLOAD")) {
6472 $setsharekey =
true;
6474 if ($this->element ==
'invoice_supplier' &&
getDolGlobalInt(
"SUPPLIER_INVOICE_ALLOW_EXTERNAL_DOWNLOAD")) {
6475 $setsharekey =
true;
6477 if ($this->element ==
'societe_rib' &&
getDolGlobalInt(
"SOCIETE_RIB_ALLOW_ONLINESIGN")) {
6478 $setsharekey =
true;
6482 if (empty($ecmfile->share)) {
6483 require_once DOL_DOCUMENT_ROOT.
'/core/lib/security2.lib.php';
6490 $ecmfile->fullpath_orig =
'';
6491 $ecmfile->gen_or_uploaded =
'generated';
6492 $ecmfile->description =
'';
6493 $ecmfile->keywords =
'';
6494 $ecmfile->src_object_type = $this->table_element;
6496 $result = $ecmfile->update($user);
6502 $ecmfile->entity =
$conf->entity;
6503 $ecmfile->filepath = $rel_dir;
6504 $ecmfile->filename = $filename;
6506 $ecmfile->fullpath_orig =
'';
6507 $ecmfile->gen_or_uploaded =
'generated';
6508 $ecmfile->description =
'';
6509 $ecmfile->keywords =
'';
6510 $ecmfile->src_object_type = $this->table_element;
6513 $result = $ecmfile->create($user);
6525 if ($update_main_doc_field && !empty($this->table_element)) {
6526 $sql =
"UPDATE ".$this->db->prefix().$this->table_element.
" SET last_main_doc = '".$this->db->escape($ecmfile->filepath.
"/".$ecmfile->filename).
"'";
6527 $sql .=
" WHERE rowid = ".((int) $this->
id);
6529 $resql = $this->db->query($sql);
6534 $this->last_main_doc = $ecmfile->filepath.
'/'.$ecmfile->filename;
6554 if (file_exists($file_osencoded)) {
6555 require_once DOL_DOCUMENT_ROOT.
'/core/lib/images.lib.php';
6558 $maxwidthsmall = $tmparraysize[
'maxwidthsmall'];
6559 $maxheightsmall = $tmparraysize[
'maxheightsmall'];
6560 $maxwidthmini = $tmparraysize[
'maxwidthmini'];
6561 $maxheightmini = $tmparraysize[
'maxheightmini'];
6566 vignette($file_osencoded, $maxwidthsmall, $maxheightsmall,
'_small', $quality);
6570 vignette($file_osencoded, $maxwidthmini, $maxheightmini,
'_mini', $quality);
6618 return GETPOST($fieldname, $type, 3);
6621 if (isset($alternatevalue)) {
6622 return $alternatevalue;
6625 $newelement = $this->element;
6626 if ($newelement ==
'facture') {
6627 $newelement =
'invoice';
6629 if ($newelement ==
'commande') {
6630 $newelement =
'order';
6632 if (empty($newelement)) {
6633 dol_syslog(
"Ask a default value using common method getDefaultCreateValueForField on an object with no property ->element defined. Return empty string.", LOG_WARNING);
6637 $keyforfieldname = strtoupper($newelement.
'_DEFAULT_'.$fieldname);
6664 if (!$this->element) {
6667 if (!($this->
id > 0)) {
6670 if (is_array($this->array_languages)) {
6674 $this->array_languages = array();
6676 $element = $this->element;
6677 if ($element ==
'categorie') {
6678 $element =
'categories';
6682 $sql =
"SELECT rowid, property, lang , value";
6683 $sql .=
" FROM ".$this->db->prefix().
"object_lang";
6684 $sql .=
" WHERE type_object = '".$this->db->escape($element).
"'";
6685 $sql .=
" AND fk_object = ".((int) $this->
id);
6687 $resql = $this->db->query($sql);
6689 $numrows = $this->db->num_rows($resql);
6692 while ($i < $numrows) {
6693 $obj = $this->db->fetch_object($resql);
6694 $key = $obj->property;
6695 $value = $obj->value;
6696 $codelang = $obj->lang;
6697 $type = $this->fields[$key][
'type'];
6700 if (preg_match(
'/date/', $type)) {
6701 $this->array_languages[$key][$codelang] = $this->db->jdate($value);
6703 $this->array_languages[$key][$codelang] = $value;
6710 $this->db->free($resql);
6733 foreach ($_POST as $postfieldkey => $postfieldvalue) {
6734 $tmparray = explode(
'-', $postfieldkey);
6735 if ($tmparray[0] !=
'field') {
6739 $element = $tmparray[1];
6740 $key = $tmparray[2];
6741 $codelang = $tmparray[3];
6744 if (!empty($onlykey) && $key != $onlykey) {
6747 if ($element != $this->element) {
6751 $key_type = $this->fields[$key][
'type'];
6754 if (isset($this->fields[$key][
'enabled'])) {
6755 $enabled = (int)
dol_eval((
string) $this->fields[$key][
'enabled'], 1, 1,
'1');
6762 if (empty($enabled)) {
6767 if (in_array($key_type, array(
'date'))) {
6771 } elseif (in_array($key_type, array(
'datetime'))) {
6775 } elseif (in_array($key_type, array(
'checkbox',
'chkbxlst'))) {
6776 $value_arr =
GETPOST($postfieldkey,
'array');
6777 if (!empty($value_arr)) {
6778 $value_key = implode(
',', $value_arr);
6782 } elseif (in_array($key_type, array(
'price',
'double'))) {
6783 $value_arr =
GETPOST($postfieldkey,
'alpha');
6786 $value_key =
GETPOST($postfieldkey);
6787 if (in_array($key_type, array(
'link')) && $value_key ==
'-1') {
6792 $this->array_languages[$key][$codelang] = $value_key;
6817 $savDisableCompute =
$conf->disable_compute;
6818 $conf->disable_compute = 1;
6820 $ret = $this->fetch(
$id);
6822 $conf->disable_compute = $savDisableCompute;
6840 global
$conf, $extrafields;
6842 if (empty($rowid)) {
6845 if (empty($rowid) && isset($this->rowid)) {
6846 $rowid = $this->rowid;
6850 if (!$this->table_element) {
6853 $this->array_options = array();
6855 if (!is_array($optionsArray)) {
6857 if (!isset($extrafields) || !is_object($extrafields)) {
6858 require_once DOL_DOCUMENT_ROOT.
'/core/class/extrafields.class.php';
6863 if (empty($extrafields->attributes[$this->table_element][
'loaded'])) {
6864 $extrafields->fetch_name_optionals_label($this->table_element);
6866 $optionsArray = (!empty($extrafields->attributes[$this->table_element][
'label']) ? $extrafields->attributes[$this->table_element][
'label'] :
null);
6868 global $extrafields;
6869 dol_syslog(
"Warning: fetch_optionals was called with param optionsArray defined when you should pass null now", LOG_WARNING);
6872 $table_element = $this->table_element;
6873 if ($table_element ==
'categorie') {
6874 $table_element =
'categories';
6878 if (is_array($optionsArray) && count($optionsArray) > 0) {
6879 $sql =
"SELECT rowid";
6880 foreach ($optionsArray as $name => $label) {
6881 if (empty($extrafields->attributes[$this->table_element][
'type'][$name]) || (!in_array($extrafields->attributes[$this->table_element][
'type'][$name], [
'separate',
'point',
'multipts',
'linestrg',
'polygon']))) {
6882 $sql .=
", ".$this->db->sanitize($name);
6885 if (!empty($extrafields->attributes[$this->table_element][
'type'][$name]) && in_array($extrafields->attributes[$this->table_element][
'type'][$name], array(
'point',
'multipts',
'linestrg',
'polygon'))) {
6887 $sql .=
", ST_AsWKT(".$this->db->sanitize($name).
") as ".$this->db->sanitize($name);
6890 $sql .=
" FROM ".$this->db->prefix().$table_element.
"_extrafields";
6891 $sql .=
" WHERE fk_object = ".((int) $rowid);
6894 $resql = $this->db->query($sql);
6896 $numrows = $this->db->num_rows($resql);
6898 $tab = $this->db->fetch_array($resql);
6899 foreach ($tab as $key => $value) {
6901 if ($key !=
'rowid' && $key !=
'tms' && $key !=
'fk_member' && !is_int($key)) {
6903 if (!empty($extrafields->attributes[$this->table_element]) && in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'date',
'datetime'))) {
6905 $this->array_options[
"options_".$key] = $this->db->jdate($value);
6907 $this->array_options[
"options_".$key] = $value;
6912 if (!empty($extrafields->attributes[$this->table_element][
'type'][$key]) && $extrafields->attributes[$this->table_element][
'type'][$key] ==
'password') {
6913 if (!empty($value) && preg_match(
'/^dolcrypt:/', $value)) {
6914 $this->array_options[
"options_".$key] =
dolDecrypt($value);
6923 if (is_array($extrafields->attributes[$this->table_element][
'label'])) {
6924 foreach ($extrafields->attributes[$this->table_element][
'label'] as $key => $val) {
6925 $this->array_options[
'options_' . $key] =
null;
6932 if (is_array($extrafields->attributes[$this->table_element][
'label'])) {
6933 foreach ($extrafields->attributes[$this->table_element][
'label'] as $key => $val) {
6934 if (!empty($extrafields->attributes[$this->table_element]) && !empty($extrafields->attributes[$this->table_element][
'computed'][$key])) {
6936 if (empty(
$conf->disable_compute)) {
6938 global $objectoffield;
6940 $this->array_options[
'options_' . $key] =
dol_eval((
string) $extrafields->attributes[$this->table_element][
'computed'][$key], 1, 0,
'2');
6946 $this->db->free($resql);
6954 $this->errors[] = $this->db->lasterror();
6975 $table_element = $this->table_element;
6976 if ($table_element ==
'categorie') {
6977 $table_element =
'categories';
6980 dol_syslog(get_class($this).
"::deleteExtraFields delete", LOG_DEBUG);
6982 $sql_del =
"DELETE FROM ".$this->db->prefix().$table_element.
"_extrafields WHERE fk_object = ".((int) $this->
id);
6984 $resql = $this->db->query($sql_del);
6986 $this->error = $this->db->lasterror();
6987 $this->db->rollback();
6990 $this->db->commit();
7007 global $langs, $extrafields, $user;
7009 if (
getDolGlobalString(
'MAIN_EXTRAFIELDS_DISABLED') || empty($this->array_options)) {
7013 if (empty($userused)) {
7020 $langs->load(
'admin');
7021 if (!isset($extrafields) || !is_object($extrafields)) {
7022 require_once DOL_DOCUMENT_ROOT.
'/core/class/extrafields.class.php';
7025 $target_extrafields = $extrafields->fetch_name_optionals_label($this->table_element);
7028 $new_array_options = array();
7029 foreach ($this->array_options as $key => $value) {
7030 if (in_array(substr($key, 8), array_keys($target_extrafields))) {
7031 $new_array_options[$key] = $value;
7032 } elseif (in_array($key, array_keys($target_extrafields))) {
7033 $new_array_options[
'options_'.$key] = $value;
7037 foreach ($new_array_options as $key => $value) {
7038 $attributeKey = substr($key, 8);
7039 $attributeType = $extrafields->attributes[$this->table_element][
'type'][$attributeKey];
7040 $attributeLabel = $langs->transnoentities($extrafields->attributes[$this->table_element][
'label'][$attributeKey]);
7041 $attributeParam = $extrafields->attributes[$this->table_element][
'param'][$attributeKey];
7042 $attributeRequired = $extrafields->attributes[$this->table_element][
'required'][$attributeKey];
7043 $attributeUnique = $extrafields->attributes[$this->table_element][
'unique'][$attributeKey];
7044 $attrfieldcomputed = $extrafields->attributes[$this->table_element][
'computed'][$attributeKey];
7045 $attributeEmptyOnClone = $extrafields->attributes[$this->table_element][
'emptyonclone'][$attributeKey];
7057 if (!empty($this->context[
'createfromclone']) && $this->context[
'createfromclone'] ==
'createfromclone' && (!empty($attributeUnique) || !empty($attributeEmptyOnClone))) {
7058 $new_array_options[$key] =
null;
7064 if (!empty($this->context[
'createproductcombination']) && $this->context[
'createproductcombination'] ==
'createproductcombination' && !empty($attributeUnique)) {
7065 $new_array_options[$key] =
null;
7070 if ($attributeRequired) {
7071 $v = $this->array_options[$key];
7073 $langs->load(
"errors");
7074 dol_syslog(
"Mandatory field '".$key.
"' is empty during create and set to required into definition of extrafields");
7075 $this->errors[] = $langs->trans(
'ErrorFieldRequired', $attributeLabel);
7080 if (!empty($attrfieldcomputed)) {
7082 global $objectoffield;
7083 $objectoffield = $this;
7084 $value =
dol_eval((
string) $attrfieldcomputed, 1, 0,
'2');
7085 dol_syslog($langs->trans(
"Extrafieldcomputed").
" on ".$attributeLabel.
"(".$value.
")", LOG_DEBUG);
7086 $new_array_options[$key] = $value;
7088 $new_array_options[$key] =
null;
7093 switch ($attributeType) {
7097 if (!is_numeric($value) && $value !=
'') {
7098 $this->errors[] = $langs->trans(
"ExtraFieldHasWrongValue", $attributeLabel);
7100 } elseif ($value ===
'') {
7101 $new_array_options[$key] =
null;
7105 if ($value ===
'' || $value ===
false || $value ===
null) {
7106 $new_array_options[$key] =
null;
7112 if (!is_numeric($value) && $value !=
'') {
7113 dol_syslog($langs->trans(
"ExtraFieldHasWrongValue").
" for ".$attributeLabel.
"(".$value.
"is not '".$attributeType.
"')", LOG_DEBUG);
7114 $this->errors[] = $langs->trans(
"ExtraFieldHasWrongValue", $attributeLabel);
7116 } elseif ($value ==
'') {
7120 $new_array_options[$key] = $value;
7130 if ($this->array_options[$key] !=
'' && is_array($extrafields->attributes[$this->table_element][
'param'][$attributeKey][
'options'])) {
7132 $tmparrays = array_keys($extrafields->attributes[$this->table_element][
'param'][$attributeKey][
'options']);
7133 $algo = reset($tmparrays);
7138 if (is_object($this->oldcopy)) {
7140 if (isset($this->oldcopy->array_options[$key]) && $this->array_options[$key] == $this->oldcopy->array_options[$key]) {
7142 if ($algo ==
'dolcrypt') {
7143 if (!preg_match(
'/^dolcrypt:/', $this->array_options[$key])) {
7144 $new_array_options[$key] =
dolEncrypt($this->array_options[$key]);
7146 $new_array_options[$key] = $this->array_options[$key];
7149 $new_array_options[$key] = $this->array_options[$key];
7153 if ($algo ==
'dolcrypt') {
7154 if (!preg_match(
'/^dolcrypt:/', $this->array_options[$key])) {
7155 $new_array_options[$key] =
dolEncrypt($this->array_options[$key]);
7157 $new_array_options[$key] = $this->array_options[$key];
7160 $new_array_options[$key] =
dol_hash($this->array_options[$key], $algo);
7166 if ($algo ==
'dolcrypt' && !preg_match(
'/^dolcrypt:/', $this->array_options[$key])) {
7167 $new_array_options[$key] =
dolEncrypt($this->array_options[$key]);
7169 $new_array_options[$key] = $this->array_options[$key];
7174 $new_array_options[$key] = $this->array_options[$key];
7177 $new_array_options[$key] = $this->array_options[$key];
7183 if (!is_numeric($this->array_options[$key]) || $this->array_options[$key] != intval($this->array_options[$key])) {
7184 $this->array_options[$key] = strtotime($this->array_options[$key]);
7186 $new_array_options[$key] = $this->db->idate($this->array_options[$key]);
7190 if (!is_numeric($this->array_options[$key]) || $this->array_options[$key] != intval($this->array_options[$key])) {
7191 $this->array_options[$key] = strtotime($this->array_options[$key]);
7193 $new_array_options[$key] = $this->db->idate($this->array_options[$key],
'gmt');
7196 $param_list = array_keys($attributeParam[
'options']);
7199 $InfoFieldList = explode(
":", $param_list[0]);
7201 if ($InfoFieldList[0] && class_exists($InfoFieldList[0])) {
7202 if ($value ==
'-1') {
7203 $new_array_options[$key] =
'';
7206 '@phan-var-force CommonObject $object';
7210 $sqlFetchObject =
"SELECT rowid FROM ".$this->db->prefix().$object->table_element;
7211 if (is_numeric($value)) {
7212 $sqlFetchObject .=
" WHERE rowid = " . (int) $value;
7214 $sqlFetchObject .=
" WHERE ref = '" . $this->db->escape($value) .
"'";
7217 $obj = $this->db->getRow($sqlFetchObject);
7223 if (is_object($obj)) {
7224 $objectId = $obj->rowid;
7231 $new_array_options[$key] = $objectId;
7233 $this->error =
"Id/Ref '".$value.
"' for object '".
$object->element.
"' not found";
7238 dol_syslog(
'Error bad setup of extrafield', LOG_WARNING);
7243 if (is_array($this->array_options[$key])) {
7244 $new_array_options[$key] = implode(
',', $this->array_options[$key]);
7246 $new_array_options[$key] = $this->array_options[$key];
7253 $sqlColumnValues = [
'fk_object' => (int) $this->
id];
7255 foreach ($new_array_options as $key => $newValue) {
7256 $attributeKey = substr($key, 8);
7257 $attributeType = $extrafields->attributes[$this->table_element][
'type'][$attributeKey];
7258 if ($attributeType ===
'separate') {
7262 $geoDataType = ExtraFields::$geoDataTypes[$attributeType] ??
null;
7264 if (! $geoDataType) {
7266 if ($newValue !=
'') {
7267 $sqlColumnValues[$attributeKey] =
"'".$this->db->escape($newValue).
"'";
7269 $sqlColumnValues[$attributeKey] =
'null';
7273 if (empty($newValue)) {
7274 $sqlColumnValues[$attributeKey] =
'null';
7277 if (preg_match(
'/error/i', $newValue)) {
7278 dol_syslog(
'Bad syntax string for '.$geoDataType[
'shortname'].
' '.$newValue.
' to generate SQL request', LOG_WARNING);
7279 $sqlColumnValues[$attributeKey] =
'null';
7288 $sqlColumnValues[$attributeKey] = $geoDataType[
'ST_Function'].
"('".$this->db->escape($newValue).
"')";
7293 $table_element = $this->table_element;
7294 if ($table_element ==
'categorie') {
7295 $table_element =
'categories';
7297 $extrafieldsTable = $this->db->prefix() . $table_element .
'_extrafields';
7299 dol_syslog(get_class($this).
"::insertExtraFields update or insert record line", LOG_DEBUG);
7301 $linealreadyfound = 0;
7302 $sql =
"SELECT COUNT(rowid) as nb FROM ".$this->db->prefix().$table_element.
"_extrafields WHERE fk_object = ".((int) $this->
id);
7303 $resql = $this->db->query($sql);
7305 $tmpobj = $this->db->fetch_object($resql);
7307 $linealreadyfound = $tmpobj->nb;
7312 if ($linealreadyfound) {
7313 array_shift($sqlColumnValues);
7314 if (empty($sqlColumnValues)) {
7320 $this->db->commit();
7323 $sqlColumnValueString = implode(
7329 array_map(
function ($key) use ($sqlColumnValues) {
7330 return "{$key} = {$sqlColumnValues[$key]}";
7331 }, array_keys($sqlColumnValues))
7333 $sql =
"UPDATE {$extrafieldsTable} SET {$sqlColumnValueString} WHERE fk_object = ".((int) $this->
id);
7336 $extrafieldsRequiredOnOtherEntities = $extrafields->attributes[$this->table_element][
'mandatoryfieldsofotherentities'] ?? array();
7337 foreach ($extrafieldsRequiredOnOtherEntities as $key => $extrafieldType) {
7338 if (isset($sqlColumnValues[$key])) {
7343 $sqlColumnValues[$key] =
"''";
7344 if (in_array($extrafieldType, array(
'int',
'double',
'price'))) {
7345 $sqlColumnValues[$key] = 0;
7348 $sqlColumns = implode(
',', array_keys($sqlColumnValues));
7349 $sqlValues = implode(
',', array_values($sqlColumnValues));
7350 $sql =
"INSERT INTO {$extrafieldsTable} ({$sqlColumns}) VALUES ({$sqlValues})";
7353 $resql = $this->db->query($sql);
7355 $this->error = $this->db->lasterror();
7360 if (!$error && !empty($this->fields[
'fk_user_modif'])) {
7361 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
7362 $sql .=
" SET fk_user_modif = ".(int) $userused->id;
7363 $sql .=
" WHERE ".(empty($this->table_rowid) ?
'rowid' : $this->db->sanitize($this->table_rowid)).
" = ".((
int)
$this->id);
7364 $this->db->query($sql);
7367 if (!$error && $trigger) {
7369 $this->context = array(
'extrafieldaddupdate' => 1);
7370 $result = $this->call_trigger($trigger, $userused);
7378 $this->db->rollback();
7381 $this->db->commit();
7399 global $langs, $user;
7401 if (empty($userused)) {
7411 if (is_array($this->array_languages)) {
7412 $new_array_languages = $this->array_languages;
7414 foreach ($new_array_languages as $key => $value) {
7415 $attributeKey = $key;
7416 $attributeType = $this->fields[$attributeKey][
'type'];
7417 $attributeLabel = $this->fields[$attributeKey][
'label'];
7422 switch ($attributeType) {
7424 if (is_array($value) || (!is_numeric($value) && $value !=
'')) {
7425 $this->errors[] = $langs->trans(
"ExtraLanguageHasWrongValue", $attributeLabel);
7427 } elseif ($value ==
'') {
7428 $new_array_languages[$key] =
null;
7433 if (!is_numeric($value) && $value !=
'') {
7434 dol_syslog($langs->trans(
"ExtraLanguageHasWrongValue").
" on ".$attributeLabel.
"(".$value.
"is not '".$attributeType.
"')", LOG_DEBUG);
7435 $this->errors[] = $langs->trans(
"ExtraLanguageHasWrongValue", $attributeLabel);
7437 } elseif ($value ==
'') {
7438 $new_array_languages[$key] =
null;
7440 $new_array_languages[$key] = $value;
7454 $table_element = $this->table_element;
7455 if ($table_element ==
'categorie') {
7456 $table_element =
'categories';
7459 dol_syslog(get_class($this).
"::insertExtraLanguages delete then insert", LOG_DEBUG);
7461 foreach ($new_array_languages as $key => $langcodearray) {
7462 foreach ($langcodearray as $langcode => $value) {
7463 $sql_del =
"DELETE FROM ".$this->db->prefix().
"object_lang";
7464 $sql_del .=
" WHERE fk_object = ".((int) $this->
id).
" AND property = '".$this->db->escape($key).
"' AND type_object = '".$this->db->escape($table_element).
"'";
7465 $sql_del .=
" AND lang = '".$this->db->escape($langcode).
"'";
7466 $this->db->query($sql_del);
7468 if ($value !==
'') {
7469 $sql =
"INSERT INTO ".$this->db->prefix().
"object_lang (fk_object, property, type_object, lang, value";
7470 $sql .=
") VALUES (".((int) $this->
id).
", '".$this->db->escape($key).
"', '".$this->db->escape($table_element).
"', '".$this->db->escape($langcode).
"', '".$this->db->escape($value).
"'";
7473 $resql = $this->db->query($sql);
7475 $this->error = $this->db->lasterror();
7483 if (!$error && $trigger) {
7485 $this->context = array(
'extralanguagesaddupdate' => 1);
7486 $result = $this->call_trigger($trigger, $userused);
7494 $this->db->rollback();
7497 $this->db->commit();
7517 global $langs, $user, $extrafields, $hookmanager;
7523 if (empty($userused)) {
7529 if (!empty($this->array_options) && isset($this->array_options[
"options_".$key])) {
7531 $langs->load(
'admin');
7532 if (!isset($extrafields) || !is_object($extrafields)) {
7533 require_once DOL_DOCUMENT_ROOT.
'/core/class/extrafields.class.php';
7536 $extrafields->fetch_name_optionals_label($this->table_element);
7537 if (!isset($extrafields->attributes[$this->table_element][
'type'][$key])) {
7541 $value = $this->array_options[
"options_".$key];
7543 $attributeKey = $key;
7544 $attributeType = $extrafields->attributes[$this->table_element][
'type'][$attributeKey];
7545 $attributeLabel = $extrafields->attributes[$this->table_element][
'label'][$attributeKey];
7546 $attributeParam = $extrafields->attributes[$this->table_element][
'param'][$attributeKey];
7547 $attributeRequired = $extrafields->attributes[$this->table_element][
'required'][$attributeKey];
7548 $attributeUnique = $extrafields->attributes[$this->table_element][
'unique'][$attributeKey];
7549 $attrfieldcomputed = $extrafields->attributes[$this->table_element][
'computed'][$attributeKey];
7553 if ($attributeRequired) {
7554 $mandatorypb =
false;
7555 if ($attributeType ==
'link' && $this->array_options[
"options_".$key] ==
'-1') {
7556 $mandatorypb =
true;
7558 if ($this->array_options[
"options_".$key] ===
'') {
7559 $mandatorypb =
true;
7562 $langs->load(
"errors");
7563 dol_syslog(
"Mandatory field 'options_".$key.
"' is empty during update and set to required into definition of extrafields");
7564 $this->errors[] = $langs->trans(
'ErrorFieldRequired', $attributeLabel);
7570 $new_array_options = $this->array_options;
7574 if (!empty($attrfieldcomputed)) {
7576 global $objectoffield;
7577 $objectoffield = $this;
7578 $value =
dol_eval((
string) $attrfieldcomputed, 1, 0,
'2');
7579 dol_syslog($langs->trans(
"Extrafieldcomputed").
" on ".$attributeLabel.
"(".$value.
")", LOG_DEBUG);
7581 $new_array_options[
"options_".$key] = $value;
7583 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7585 $new_array_options[
"options_".$key] =
null;
7587 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7591 switch ($attributeType) {
7593 if (!is_numeric($value) && $value !=
'') {
7594 $this->errors[] = $langs->trans(
"ExtraFieldHasWrongValue", $attributeLabel);
7596 } elseif ($value ===
'') {
7597 $new_array_options[
"options_".$key] =
null;
7599 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7605 if (!is_numeric($value) && $value !=
'') {
7606 dol_syslog($langs->trans(
"ExtraFieldHasWrongValue").
" on ".$attributeLabel.
"(".$value.
"is not '".$attributeType.
"')", LOG_DEBUG);
7607 $this->errors[] = $langs->trans(
"ExtraFieldHasWrongValue", $attributeLabel);
7609 } elseif ($value ===
'') {
7613 $new_array_options[
"options_".$key] = $value;
7615 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7627 if ($this->array_options[
"options_".$key] !=
'' && is_array($extrafields->attributes[$this->table_element][
'param'][$attributeKey][
'options'])) {
7629 $tmparrays = array_keys($extrafields->attributes[$this->table_element][
'param'][$attributeKey][
'options']);
7630 $algo = reset($tmparrays);
7636 if (is_object($this->oldcopy)) {
7638 if (isset($this->oldcopy->array_options[
"options_".$key]) && $this->array_options[
"options_".$key] == $this->oldcopy->array_options[
"options_".$key]) {
7639 if ($algo ==
'dolcrypt') {
7640 if (!preg_match(
'/^dolcrypt:/', $this->array_options[
"options_".$key])) {
7641 $new_array_options[
"options_".$key] =
dolEncrypt($this->array_options[
"options_".$key]);
7643 $new_array_options[
"options_".$key] = $this->array_options[
"options_".$key];
7646 $new_array_options[
"options_".$key] = $this->array_options[
"options_".$key];
7649 if ($algo ==
'dolcrypt') {
7650 if (!preg_match(
'/^dolcrypt:/', $this->array_options[
"options_".$key])) {
7651 $new_array_options[
"options_".$key] =
dolEncrypt($this->array_options[
"options_".$key]);
7653 $new_array_options[
"options_".$key] = $this->array_options[
"options_".$key];
7656 $new_array_options[
"options_".$key] =
dol_hash($this->array_options[
"options_".$key], $algo);
7660 if ($algo ==
'dolcrypt' && !preg_match(
'/^dolcrypt:/', $this->array_options[
"options_".$key])) {
7661 $new_array_options[
"options_".$key] =
dolEncrypt($this->array_options[
"options_".$key]);
7663 $new_array_options[
"options_".$key] = $this->array_options[
"options_".$key];
7668 $new_array_options[
"options_".$key] = $this->array_options[
"options_".$key];
7671 $new_array_options[
"options_".$key] = $this->array_options[
"options_".$key];
7674 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7678 if (empty($this->array_options[
"options_".$key])) {
7679 $new_array_options[
"options_".$key] =
null;
7681 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7683 $new_array_options[
"options_".$key] = $this->db->idate($this->array_options[
"options_".$key]);
7687 if (empty($this->array_options[
"options_".$key])) {
7688 $new_array_options[
"options_".$key] =
null;
7690 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7692 $new_array_options[
"options_".$key] = $this->db->idate($this->array_options[
"options_".$key],
'gmt');
7696 if (empty($this->array_options[
"options_".$key])) {
7697 $new_array_options[
"options_".$key] =
null;
7699 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7703 if ($this->array_options[
"options_".$key] ===
'') {
7704 $new_array_options[
"options_".$key] =
null;
7706 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7740 $new_array_options = array();
7741 if (is_array($this->array_options[
"options_".$key])) {
7742 $new_array_options[
"options_".$key] = implode(
',', $this->array_options[
"options_".$key]);
7744 $new_array_options[
"options_".$key] = $this->array_options[
"options_".$key];
7747 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7753 $linealreadyfound = 0;
7756 $table_element = $this->table_element;
7757 if ($table_element ==
'categorie') {
7758 $table_element =
'categories';
7761 $sql =
"SELECT COUNT(rowid) as nb FROM ".$this->db->prefix().$table_element.
"_extrafields WHERE fk_object = ".((int) $this->
id);
7762 $resql = $this->db->query($sql);
7764 $tmpobj = $this->db->fetch_object($resql);
7766 $linealreadyfound = $tmpobj->nb;
7771 if ($linealreadyfound) {
7772 $sanitizedGeoDataType = ExtraFields::$geoDataTypes[$attributeType] ??
null;
7773 if ($this->array_options[
"options_".$key] ===
null) {
7774 $sql =
"UPDATE ".$this->db->prefix().$this->db->sanitize($table_element).
"_extrafields";
7775 $sql .=
" SET ".$this->db->sanitize($key).
" = null";
7776 } elseif (!empty($sanitizedGeoDataType[
'ST_Function'])) {
7777 $sql =
"UPDATE ".$this->db->prefix().$this->db->sanitize($table_element).
"_extrafields";
7778 $sql .=
" SET ".$this->db->sanitize($key).
" = ".$this->db->sanitize($sanitizedGeoDataType[
'ST_Function']).
"('".$this->db->escape($this->array_options[
"options_".$key]).
"')";
7781 $sql =
"UPDATE ".$this->db->prefix().$this->db->sanitize($table_element).
"_extrafields";
7782 $sql .=
" SET ".$this->db->sanitize($key).
" = '".$this->db->escape($new_array_options[
"options_".$key]).
"'";
7784 $sql .=
" WHERE fk_object = ".((int) $this->
id);
7786 $resql = $this->db->query($sql);
7789 $this->error = $this->db->lasterror();
7792 $result = $this->insertExtraFields(
'', $user);
7799 if (!$error && !empty($this->fields[
'fk_user_modif'])) {
7800 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
7801 $sql .=
" SET fk_user_modif = ".(int) $userused->id;
7802 $sql .=
" WHERE ".(empty($this->table_rowid) ?
'rowid' : $this->db->sanitize($this->table_rowid)).
" = ".((
int)
$this->id);
7803 $this->db->query($sql);
7807 $parameters = array(
'key' => $key);
7809 $reshook = $hookmanager->executeHooks(
'updateExtraFieldBeforeCommit', $parameters, $this, $action);
7815 if (!$error && $trigger) {
7817 $this->context = array(
'extrafieldupdate' => 1);
7818 $result = $this->call_trigger($trigger, $userused);
7826 dol_syslog(__METHOD__.$this->error, LOG_ERR);
7827 $this->db->rollback();
7830 $this->db->commit();
7846 return $this->array_options[
'options_'.$key] ??
null;
7858 $this->array_options[
'options_'.$key] = $value;
7875 if (empty($userused)) {
7903 public function showInputField($val, $key, $value, $moreparam =
'', $keysuffix =
'', $keyprefix =
'', $morecss = 0, $nonewbutton = 0)
7905 global
$conf, $langs, $form;
7910 if (!is_object($form)) {
7911 require_once DOL_DOCUMENT_ROOT.
'/core/class/html.form.class.php';
7912 $form =
new Form($this->db);
7915 if (!empty($this->fields)) {
7916 $val = $this->fields[$key];
7920 $fieldValidationErrorMsg =
'';
7921 $validationClass =
'';
7922 $fieldValidationErrorMsg = $this->getFieldError($key);
7923 if (!empty($fieldValidationErrorMsg)) {
7924 $validationClass =
' --error';
7926 $validationClass =
' --success';
7934 $param[
'options'] = array();
7937 $size = !empty($this->fields[$key][
'size']) ? $this->fields[$key][
'size'] : 0;
7939 if (preg_match(
'/^(integer|link):(.*):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
7940 $param[
'options'] = array($reg[2].
':'.$reg[3].
':'.$reg[4].
':'.$reg[5] =>
'N');
7942 } elseif (preg_match(
'/^(integer|link):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
7943 $param[
'options'] = array($reg[2].
':'.$reg[3].
':'.$reg[4] =>
'N');
7945 } elseif (preg_match(
'/^(integer|link):(.*):(.*)/i', $val[
'type'], $reg)) {
7946 $param[
'options'] = array($reg[2].
':'.$reg[3] =>
'N');
7948 } elseif (preg_match(
'/^(sellist):(.*):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
7949 $param[
'options'] = array($reg[2].
':'.$reg[3].
':'.$reg[4].
':'.$reg[5] =>
'N');
7951 } elseif (preg_match(
'/^(sellist):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
7952 $param[
'options'] = array($reg[2].
':'.$reg[3].
':'.$reg[4] =>
'N');
7954 } elseif (preg_match(
'/^(sellist):(.*):(.*)/i', $val[
'type'], $reg)) {
7955 $param[
'options'] = array($reg[2].
':'.$reg[3] =>
'N');
7957 } elseif (preg_match(
'/^chkbxlst:(.*)/i', $val[
'type'], $reg)) {
7958 $param[
'options'] = array($reg[1] =>
'N');
7960 } elseif (preg_match(
'/varchar\((\d+)\)/', $val[
'type'], $reg)) {
7961 $param[
'options'] = array();
7964 } elseif (preg_match(
'/varchar/', $val[
'type'])) {
7965 $param[
'options'] = array();
7967 } elseif (preg_match(
'/stars\((\d+)\)/', $val[
'type'], $reg)) {
7968 $param[
'options'] = array();
7972 $param[
'options'] = array();
7973 $type = $this->fields[$key][
'type'];
7978 if (!empty($this->fields[$key][
'arrayofkeyval']) && is_array($this->fields[$key][
'arrayofkeyval'])) {
7979 $param[
'options'] = $this->fields[$key][
'arrayofkeyval'];
7981 if (empty($this->fields[$key][
'multiinput'])) {
7982 $type = (($this->fields[$key][
'type'] ==
'checkbox') ? $this->fields[$key][
'type'] :
'select');
7986 $label = $this->fields[$key][
'label'];
7989 $default = (!empty($this->fields[$key][
'default']) ? $this->fields[$key][
'default'] :
'');
7991 $computed = (!empty($this->fields[$key][
'computed']) ? $this->fields[$key][
'computed'] :
'');
7993 $unique = (!empty($this->fields[$key][
'unique']) ? $this->fields[$key][
'unique'] : 0);
7995 $required = (!empty($this->fields[$key][
'required']) ? $this->fields[$key][
'required'] : 0);
7997 $autofocusoncreate = (!empty($this->fields[$key][
'autofocusoncreate']) ? $this->fields[$key][
'autofocusoncreate'] : 0);
7999 $placeholder = (!empty($this->fields[$key][
'placeholder']) ? $this->fields[$key][
'placeholder'] : 0);
8002 $langfile = (!empty($this->fields[$key][
'langfile']) ? $this->fields[$key][
'langfile'] :
'');
8004 $list = (!empty($this->fields[$key][
'list']) ? $this->fields[$key][
'list'] : 0);
8005 $hidden = (in_array(abs($this->fields[$key][
'visible']), array(0, 2)) ? 1 : 0);
8010 if (!preg_match(
'/^search_/', $keyprefix)) {
8011 return '<span class="opacitymedium">'.$langs->trans(
"AutomaticallyCalculated").
'</span>';
8018 if (empty($morecss) && !empty($val[
'css'])) {
8019 $morecss = $val[
'css'];
8020 } elseif (empty($morecss)) {
8021 if ($type ==
'date') {
8022 $morecss =
'minwidth100imp';
8023 } elseif ($type ==
'datetime' || $type ==
'link') {
8024 $morecss =
'minwidth200imp';
8025 } elseif (in_array($type, array(
'int',
'integer',
'price')) || preg_match(
'/^double(\([0-9],[0-9]\)){0,1}/', (
string) $type)) {
8026 $morecss =
'maxwidth75';
8027 } elseif ($type ==
'url') {
8028 $morecss =
'minwidth400';
8029 } elseif ($type ==
'boolean') {
8032 if (is_numeric($size) && round((
float) $size) < 12) {
8033 $morecss =
'minwidth100';
8034 } elseif (is_numeric($size) && round((
float) $size) <= 48) {
8035 $morecss =
'minwidth200';
8037 $morecss =
'minwidth400';
8043 if (!empty($validationClass)) {
8044 $morecss .= $validationClass;
8047 if (in_array($type, array(
'date'))) {
8048 $tmp = explode(
',', $size);
8053 if (!$required && $value ==
'') {
8058 $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required,
'', 1, (($keyprefix !=
'search_' && $keyprefix !=
'search_options_') ? 1 : 0), 0, 1);
8059 } elseif (in_array($type, array(
'datetime'))) {
8060 $tmp = explode(
',', $size);
8065 if (!$required && $value ==
'') {
8070 $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required,
'', 1, (($keyprefix !=
'search_' && $keyprefix !=
'search_options_') ? 1 : 0), 0, 1,
'',
'',
'', 1,
'',
'',
'tzuserrel');
8071 } elseif (in_array($type, array(
'duration'))) {
8072 $out = $form->select_duration($keyprefix.$key.$keysuffix, $value, 0,
'text', 0, 1);
8073 } elseif (in_array($type, array(
'int',
'integer'))) {
8074 $tmp = explode(
',', $size);
8076 $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' :
'').
'>';
8077 } elseif (in_array($type, array(
'real'))) {
8078 $out =
'<input type="text" class="flat '.$morecss.
'" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.
dol_escape_htmltag($value).
'"'.($moreparam ? $moreparam :
'').($autofocusoncreate ?
' autofocus' :
'').
'>';
8079 } elseif (preg_match(
'/varchar/', (
string) $type)) {
8080 $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' :
'').
'>';
8081 } elseif (in_array($type, array(
'email',
'mail',
'phone',
'url',
'ip'))) {
8082 $out =
'<input type="text" class="flat '.$morecss.
'" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.
dol_escape_htmltag($value).
'" '.($moreparam ? $moreparam :
'').($autofocusoncreate ?
' autofocus' :
'').
'>';
8083 } elseif (preg_match(
'/^text/', (
string) $type)) {
8084 if (!preg_match(
'/search_/', $keyprefix)) {
8085 if (!empty($param[
'options'])) {
8088 $out .= $form->selectarray($keyprefix.$key.$keysuffix.
"_multiinput", $param[
'options'],
'', 1, 0, 0,
"flat maxwidthonphone".$morecss);
8089 $out .=
'<input id="'.$keyprefix.$key.$keysuffix.
'_multiinputadd" type="button" class="button" value="'.$langs->trans(
"Add").
'">';
8092 function handlemultiinputdisabling(htmlname){
8093 console.log("We handle the disabling of used options for "+htmlname+"_multiinput");
8094 multiinput = $("#"+htmlname+"_multiinput");
8095 multiinput.find("option").each(function(){
8096 tmpval = $("#"+htmlname).val();
8097 tmpvalarray = tmpval.split("\n");
8098 valtotest = $(this).val();
8099 if(tmpvalarray.includes(valtotest)){
8100 $(this).prop("disabled",true);
8102 if($(this).prop("disabled") == true){
8103 console.log(valtotest)
8104 $(this).prop("disabled", false);
8110 $(document).ready(function () {
8111 $("#'.$keyprefix.$key.$keysuffix.
'_multiinputadd").on("click",function() {
8112 tmpval = $("#'.$keyprefix.$key.$keysuffix.
'").val();
8113 tmpvalarray = tmpval.split(",");
8114 valtotest = $("#'.$keyprefix.$key.$keysuffix.
'_multiinput").val();
8115 if(valtotest != -1 && !tmpvalarray.includes(valtotest)){
8116 console.log("We add the selected value to the text area '.$keyprefix.$key.$keysuffix.
'");
8120 tmpval = tmpval + "\n" + valtotest;
8122 $("#'.$keyprefix.$key.$keysuffix.
'").val(tmpval);
8123 handlemultiinputdisabling("'.$keyprefix.$key.$keysuffix.
'");
8124 $("#'.$keyprefix.$key.$keysuffix.
'_multiinput").val(-1);
8126 console.log("We add nothing the text area '.$keyprefix.$key.$keysuffix.
'");
8129 $("#'.$keyprefix.$key.$keysuffix.
'").on("change",function(){
8130 handlemultiinputdisabling("'.$keyprefix.$key.$keysuffix.
'");
8132 handlemultiinputdisabling("'.$keyprefix.$key.$keysuffix.
'");
8134 $out .=
"</script>";
8135 $value = str_replace(
',',
"\n", $value);
8137 require_once DOL_DOCUMENT_ROOT.
'/core/class/doleditor.class.php';
8138 $doleditor =
new DolEditor($keyprefix.$key.$keysuffix, $value,
'', 200,
'dolibarr_notes',
'In',
false,
false,
false, ROWS_5,
'90%');
8139 $out .= (
string) $doleditor->Create(1,
'',
true,
'',
'',
'', $morecss);
8141 $out =
'<input type="text" class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.
dol_escape_htmltag($value).
'" '.($moreparam ? $moreparam :
'').
'>';
8143 } elseif (preg_match(
'/^html/', (
string) $type)) {
8144 if (!preg_match(
'/search_/', $keyprefix)) {
8145 require_once DOL_DOCUMENT_ROOT.
'/core/class/doleditor.class.php';
8146 $doleditor =
new DolEditor($keyprefix.$key.$keysuffix, $value,
'', 200,
'dolibarr_notes',
'In',
false,
false,
isModEnabled(
'fckeditor') &&
getDolGlobalInt(
'FCKEDITOR_ENABLE_SOCIETE'), ROWS_5,
'90%');
8147 $out = (
string) $doleditor->Create(1,
'',
true,
'',
'', $moreparam, $morecss);
8149 $out =
'<input type="text" class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.
dol_escape_htmltag($value).
'" '.($moreparam ? $moreparam :
'').
'>';
8151 } elseif ($type ==
'boolean') {
8153 if (!empty($value)) {
8154 $checked =
' checked value="1" ';
8156 $checked =
' value="1" ';
8158 $out =
'<input type="checkbox" class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" '.$checked.
' '.($moreparam ? $moreparam :
'').
'>';
8159 } elseif ($type ==
'price') {
8160 if (!empty($value)) {
8161 $value =
price($value);
8163 $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>';
8164 } elseif ($type ==
'stars') {
8165 $out =
'<input type="hidden" class="flat '.$morecss.
'" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.
dol_escape_htmltag($value).
'"'.($moreparam ? $moreparam :
'').($autofocusoncreate ?
' autofocus' :
'').
'>';
8166 $out .=
'<div class="star-selection" id="'.$keyprefix.$key.$keysuffix.
'_selection">';
8168 while ($i <= $size) {
8169 $out .=
'<span class="star" data-value="'.$i.
'">'.
img_picto(
'',
'fontawesome_star_fas').
'</span>';
8174 jQuery(function($) { /* commonobject.class.php 1 */
8175 let container = $("#'.$keyprefix.$key.$keysuffix.
'_selection");
8176 let selectedStars = parseInt($("#'.$keyprefix.$key.$keysuffix.
'").val()) || 0;
8177 container.find(".star").each(function() {
8178 $(this).toggleClass("active", $(this).data("value") <= selectedStars);
8180 container.find(".star").on("mouseover", function() {
8181 let selectedStar = $(this).data("value");
8182 container.find(".star").each(function() {
8183 $(this).toggleClass("active", $(this).data("value") <= selectedStar);
8186 container.on("mouseout", function() {
8187 container.find(".star").each(function() {
8188 $(this).toggleClass("active", $(this).data("value") <= selectedStars);
8191 container.find(".star").off("click").on("click", function() {
8192 selectedStars = $(this).data("value");
8193 if (selectedStars === 1 && $("#'.$keyprefix.$key.$keysuffix.
'").val() == 1) {
8196 $("#'.$keyprefix.$key.$keysuffix.
'").val(selectedStars);
8197 container.find(".star").each(function() {
8198 $(this).toggleClass("active", $(this).data("value") <= selectedStars);
8203 } elseif (preg_match(
'/^double(\([0-9],[0-9]\)){0,1}/', (
string) $type)) {
8204 if (!empty($value)) {
8205 $value =
price($value);
8207 $out =
'<input type="text" class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.$value.
'" '.($moreparam ? $moreparam :
'').
'> ';
8208 } elseif ($type ==
'select') {
8211 include_once DOL_DOCUMENT_ROOT.
'/core/lib/ajax.lib.php';
8212 $out .=
ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
8218 foreach ($param[
'options'] as $keyb => $valb) {
8219 if ((
string) $keyb ==
'') {
8222 if (strpos($valb,
"|") !==
false) {
8223 list($valb, $parent) = explode(
'|', $valb);
8226 $tmpselect .=
'<option value="'.$keyb.
'"';
8227 $tmpselect .= (((
string) $value == (
string) $keyb) ?
' selected' :
'');
8228 if (!empty($parent)) {
8231 $tmpselect .= (!empty($parent) ?
' parent="'.$parent.
'"' :
'');
8232 $tmpselect .=
'>'.$langs->trans($valb).
'</option>';
8235 $out .=
'<select class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" '.($moreparam ? $moreparam :
'').
'>';
8236 if ((!isset($this->fields[$key][
'default'])) || empty($this->fields[$key][
'notnull']) || ($this->fields[$key][
'notnull'] != 1) || $nbchoice >= 2) {
8237 $out .=
'<option value="0"> </option>';
8240 $out .=
'</select>';
8241 } elseif ($type ==
'sellist') {
8244 include_once DOL_DOCUMENT_ROOT.
'/core/lib/ajax.lib.php';
8245 $out .=
ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
8248 $out .=
'<select class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" '.($moreparam ? $moreparam :
'').
'>';
8249 if (is_array($param[
'options'])) {
8250 $tmpparamoptions = array_keys($param[
'options']);
8251 $paramoptions = preg_split(
'/[\r\n]+/', $tmpparamoptions[0]);
8253 $InfoFieldList = explode(
":", $paramoptions[0], 5);
8265 if (! empty($InfoFieldList[4])) {
8267 $parenthesisopen = 0;
8268 while (substr($InfoFieldList[4], $pos, 1) !==
'' && ($parenthesisopen || $pos == 0 || substr($InfoFieldList[4], $pos, 1) !=
':')) {
8269 if (substr($InfoFieldList[4], $pos, 1) ==
'(') {
8272 if (substr($InfoFieldList[4], $pos, 1) ==
')') {
8277 $tmpbefore = substr($InfoFieldList[4], 0, $pos);
8278 $tmpafter = substr($InfoFieldList[4], $pos + 1);
8280 $InfoFieldList[4] = $tmpbefore;
8281 if ($tmpafter !==
'') {
8282 $InfoFieldList = array_merge($InfoFieldList, explode(
':', $tmpafter));
8288 if (preg_match(
'/^\(?([a-z0-9]+)([=<>]+)(\d+)\)?$/i', $InfoFieldList[4], $reg)) {
8289 $InfoFieldList[4] =
'('.$reg[1].
':'.$reg[2].
':'.$reg[3].
')';
8300 $keyList = (empty($InfoFieldList[2]) ?
'rowid' : $InfoFieldList[2].
' as rowid');
8302 if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
8303 if (strpos($InfoFieldList[4],
'extra.') !==
false) {
8304 $keyList =
'main.'.$InfoFieldList[2].
' as rowid';
8306 $keyList = $InfoFieldList[2].
' as rowid';
8309 if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
8310 list($parentName, $parentField) = explode(
'|', $InfoFieldList[3]);
8311 if (!empty($InfoFieldList[4]) && strpos($InfoFieldList[4],
'extra.') !==
false) {
8312 $keyList .=
', main.'.$parentField;
8314 $keyList .=
', '.$parentField;
8318 $filter_categorie =
false;
8319 if (count($InfoFieldList) > 5) {
8320 if ($InfoFieldList[0] ==
'categorie') {
8321 $filter_categorie =
true;
8325 if (!$filter_categorie) {
8326 $fields_label = isset($InfoFieldList[1]) ? explode(
'|', $InfoFieldList[1]) : array();
8327 if (!empty($fields_label)) {
8329 $keyList .= implode(
', ', $fields_label);
8333 $sql =
"SELECT " . $this->db->sanitize($keyList, 0, 0, 1);
8334 $sql .=
" FROM " . $this->db->prefix() . $this->db->sanitize($InfoFieldList[0]);
8336 if (!empty($InfoFieldList[4])) {
8338 if (strpos($InfoFieldList[4],
'$SEL$') !==
false) {
8339 $InfoFieldList[4] = str_replace(
'$SEL$',
'SELECT', $InfoFieldList[4]);
8343 if (strpos($InfoFieldList[4],
'$ID$') !==
false && !empty($objectid)) {
8344 $InfoFieldList[4] = str_replace(
'$ID$', (
string) $objectid, $InfoFieldList[4]);
8346 $InfoFieldList[4] = str_replace(
'$ID$',
'0', $InfoFieldList[4]);
8351 if (strpos($InfoFieldList[4],
'extra') !==
false) {
8352 $sql .=
" as main, " . $this->db->sanitize($this->db->prefix() . $InfoFieldList[0]) .
"_extrafields as extra";
8353 $sqlwhere .=
" WHERE extra.fk_object = main." . $this->db->sanitize($InfoFieldList[2]);
8359 $sqlwhere .=
' WHERE 1=1';
8376 if (in_array($InfoFieldList[0], array(
'tablewithentity'))) {
8377 $sqlwhere .=
" AND entity = " . ((int)
$conf->entity);
8382 if (isset($InfoFieldList[7]) && preg_match(
'/^[a-z0-9_\-,]+$/i', $InfoFieldList[7])) {
8383 $sql .=
" ORDER BY ".$this->db->sanitize($InfoFieldList[7]);
8385 $sql .=
" ORDER BY ".$this->db->sanitize(implode(
', ', $fields_label));
8387 $sql .=
' LIMIT ' .
getDolGlobalInt(
'MAIN_EXTRAFIELDS_LIMIT_SELLIST_SQL', 1000);
8390 dol_syslog(get_class($this) .
'::showInputField type=sellist', LOG_DEBUG);
8391 $resql = $this->db->query($sql);
8393 $out .=
'<option value="0"> </option>';
8394 $num = $this->db->num_rows($resql);
8398 $obj = $this->db->fetch_object($resql);
8402 $fields_label = explode(
'|', $InfoFieldList[1]);
8403 if (count($fields_label) > 1) {
8405 foreach ($fields_label as $field_toshow) {
8406 $labeltoshow .= $obj->$field_toshow .
' ';
8409 $labeltoshow = $obj->{$InfoFieldList[1]};
8411 $labeltoshow =
dol_trunc($labeltoshow, 45);
8413 if ($value == $obj->rowid) {
8414 foreach ($fields_label as $field_toshow) {
8415 $translabel = $langs->trans($obj->$field_toshow);
8416 if ($translabel != $obj->$field_toshow) {
8417 $labeltoshow =
dol_trunc($translabel) .
' ';
8419 $labeltoshow =
dol_trunc($obj->$field_toshow) .
' ';
8422 $out .=
'<option value="' . $obj->rowid .
'" selected>' . $labeltoshow .
'</option>';
8425 $translabel = $langs->trans($obj->{$InfoFieldList[1]});
8426 if ($translabel != $obj->{$InfoFieldList[1]}) {
8427 $labeltoshow =
dol_trunc($translabel, 18);
8429 $labeltoshow =
dol_trunc($obj->{$InfoFieldList[1]});
8432 if (empty($labeltoshow)) {
8433 $labeltoshow =
'(not defined)';
8435 if ($value == $obj->rowid) {
8436 $out .=
'<option value="' . $obj->rowid .
'" selected>' . $labeltoshow .
'</option>';
8439 if (!empty($InfoFieldList[3]) && $parentField) {
8440 $parent = $parentName .
':' . $obj->{$parentField};
8444 $out .=
'<option value="' . $obj->rowid .
'"';
8445 $out .= ($value == $obj->rowid ?
' selected' :
'');
8446 $out .= (!empty($parent) ?
' parent="' . $parent .
'"' :
'');
8447 $out .=
'>' . $labeltoshow .
'</option>';
8452 $this->db->free($resql);
8454 print
'Error in request ' . $sql .
' ' . $this->db->lasterror() .
'. Check setup of extra parameters.<br>';
8457 require_once DOL_DOCUMENT_ROOT.
'/categories/class/categorie.class.php';
8458 $categcode = $InfoFieldList[5];
8459 if (is_numeric($categcode)) {
8460 $tmpcategory =
new Categorie($this->db);
8461 $MAP_ID_TO_CODE = array_flip($tmpcategory->MAP_ID);
8462 $categcode = $MAP_ID_TO_CODE[(int) $categcode];
8465 $data = $form->select_all_categories($categcode,
'',
'parent', 64, $InfoFieldList[6], 1, 1);
8466 $out .=
'<option value="0"> </option>';
8467 foreach ($data as $data_key => $data_value) {
8468 $out .=
'<option value="' . $data_key .
'"';
8469 $out .= ($value == $data_key ?
' selected' :
'');
8470 $out .=
'>' . $data_value .
'</option>';
8474 $out .=
'</select>';
8475 } elseif ($type ==
'checkbox') {
8476 $value_arr = explode(
',', $value);
8477 $out = $form->multiselectarray($keyprefix.$key.$keysuffix, (empty($param[
'options']) ?
null : $param[
'options']), $value_arr, 0, 0, $morecss, 0,
'100%');
8478 } elseif ($type ==
'radio') {
8480 foreach ($param[
'options'] as $keyopt => $valopt) {
8481 $out .=
'<input class="flat '.$morecss.
'" type="radio" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" '.($moreparam ? $moreparam :
'');
8482 $out .=
' value="'.$keyopt.
'"';
8483 $out .=
' id="'.$keyprefix.$key.$keysuffix.
'_'.$keyopt.
'"';
8484 $out .= ($value == $keyopt ?
'checked' :
'');
8485 $out .=
'/><label for="'.$keyprefix.$key.$keysuffix.
'_'.$keyopt.
'">'.$valopt.
'</label><br>';
8487 } elseif ($type ==
'chkbxlst') {
8488 if (is_array($value)) {
8489 $value_arr = $value;
8491 $value_arr = explode(
',', $value);
8494 if (is_array($param[
'options'])) {
8495 $tmpparamoptions = array_keys($param[
'options']);
8496 $paramoptions = preg_split(
'/[\r\n]+/', $tmpparamoptions[0]);
8498 $InfoFieldList = explode(
":", $paramoptions[0], 5);
8510 if (! empty($InfoFieldList[4])) {
8512 $parenthesisopen = 0;
8513 while (substr($InfoFieldList[4], $pos, 1) !==
'' && ($parenthesisopen || $pos == 0 || substr($InfoFieldList[4], $pos, 1) !=
':')) {
8514 if (substr($InfoFieldList[4], $pos, 1) ==
'(') {
8517 if (substr($InfoFieldList[4], $pos, 1) ==
')') {
8522 $tmpbefore = substr($InfoFieldList[4], 0, $pos);
8523 $tmpafter = substr($InfoFieldList[4], $pos + 1);
8525 $InfoFieldList[4] = $tmpbefore;
8526 if ($tmpafter !==
'') {
8527 $InfoFieldList = array_merge($InfoFieldList, explode(
':', $tmpafter));
8532 if (preg_match(
'/^\(?([a-z0-9]+)([=<>]+)(\d+)\)?$/i', $InfoFieldList[4], $reg)) {
8533 $InfoFieldList[4] =
'('.$reg[1].
':'.$reg[2].
':'.$reg[3].
')';
8541 '@phan-var-force array{0:string,1:string,2:string,3:string,3:string,5:string,6:string} $InfoFieldList';
8546 $keyList = (empty($InfoFieldList[2]) ?
'rowid' : $InfoFieldList[2].
' as rowid');
8548 if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
8549 if (strpos($InfoFieldList[4],
'extra.') !==
false) {
8550 $keyList =
'main.'.$InfoFieldList[2].
' as rowid';
8552 $keyList = $InfoFieldList[2].
' as rowid';
8555 if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
8556 list($parentName, $parentField) = explode(
'|', $InfoFieldList[3]);
8557 if (!empty($InfoFieldList[4]) && strpos($InfoFieldList[4],
'extra.') !==
false) {
8558 $keyList .=
', main.'.$parentField;
8560 $keyList .=
', '.$parentField;
8564 $filter_categorie =
false;
8565 if (count($InfoFieldList) > 5) {
8566 if ($InfoFieldList[0] ==
'categorie') {
8567 $filter_categorie =
true;
8572 if (!$filter_categorie) {
8573 $fields_label = explode(
'|', $InfoFieldList[1]);
8574 if (is_array($fields_label)) {
8576 $keyList .= implode(
', ', $fields_label);
8580 $sql =
"SELECT " . $this->db->sanitize($keyList, 0, 0, 1);
8581 $sql .=
' FROM ' . $this->db->prefix() . $this->db->sanitize($InfoFieldList[0]);
8583 if (!empty($InfoFieldList[4])) {
8585 if (strpos($InfoFieldList[4],
'$SEL$') !==
false) {
8586 $InfoFieldList[4] = str_replace(
'$SEL$',
'SELECT', $InfoFieldList[4]);
8590 if (strpos($InfoFieldList[4],
'$ID$') !==
false && !empty($objectid)) {
8591 $InfoFieldList[4] = str_replace(
'$ID$', (
string) $objectid, $InfoFieldList[4]);
8593 $InfoFieldList[4] = str_replace(
'$ID$',
'0', $InfoFieldList[4]);
8598 if (strpos($InfoFieldList[4],
'extra') !==
false) {
8599 $sql .=
' as main, ' . $this->db->sanitize($this->db->prefix() . $InfoFieldList[0]) .
'_extrafields as extra';
8600 $sqlwhere .=
" WHERE extra.fk_object = main." . $this->db->sanitize($InfoFieldList[2]);
8606 $sqlwhere .=
' WHERE 1=1';
8623 if (in_array($InfoFieldList[0], array(
'tablewithentity'))) {
8624 $sqlwhere .=
" AND entity = " . ((int)
$conf->entity);
8631 dol_syslog(get_class($this) .
'::showInputField type=chkbxlst', LOG_DEBUG);
8633 $resql = $this->db->query($sql);
8635 $num = $this->db->num_rows($resql);
8642 $obj = $this->db->fetch_object($resql);
8646 $fields_label = explode(
'|', $InfoFieldList[1]);
8647 if (count($fields_label) > 1) {
8649 foreach ($fields_label as $field_toshow) {
8650 $labeltoshow .= $obj->$field_toshow .
' ';
8653 $labeltoshow = $obj->{$InfoFieldList[1]};
8655 $labeltoshow =
dol_trunc($labeltoshow, 45);
8657 if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
8658 foreach ($fields_label as $field_toshow) {
8659 $translabel = $langs->trans($obj->$field_toshow);
8660 if ($translabel != $obj->$field_toshow) {
8661 $labeltoshow =
dol_trunc($translabel, 18) .
' ';
8663 $labeltoshow =
dol_trunc($obj->$field_toshow, 18) .
' ';
8667 $data[$obj->rowid] = $labeltoshow;
8670 $translabel = $langs->trans($obj->{$InfoFieldList[1]});
8671 if ($translabel != $obj->{$InfoFieldList[1]}) {
8672 $labeltoshow =
dol_trunc($translabel, 18);
8674 $labeltoshow =
dol_trunc($obj->{$InfoFieldList[1]}, 18);
8677 if (empty($labeltoshow)) {
8678 $labeltoshow =
'(not defined)';
8681 if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
8682 $data[$obj->rowid] = $labeltoshow;
8685 if (!empty($InfoFieldList[3]) && $parentField) {
8686 $parent = $parentName .
':' . $obj->{$parentField};
8690 $data[$obj->rowid] = $labeltoshow;
8695 $this->db->free($resql);
8697 $out = $form->multiselectarray($keyprefix . $key . $keysuffix, $data, $value_arr, 0, 0, $morecss, 0,
'100%');
8699 print
'Error in request ' . $sql .
' ' . $this->db->lasterror() .
'. Check setup of extra parameters.<br>';
8702 require_once DOL_DOCUMENT_ROOT.
'/categories/class/categorie.class.php';
8703 $categcode = $InfoFieldList[5];
8704 if (is_numeric($categcode)) {
8705 $tmpcategory =
new Categorie($this->db);
8706 $MAP_ID_TO_CODE = array_flip($tmpcategory->MAP_ID);
8707 $categcode = $MAP_ID_TO_CODE[(int) $categcode];
8710 $data = $form->select_all_categories($categcode,
'',
'parent', 64, $InfoFieldList[6], 1, 1);
8711 $out = $form->multiselectarray($keyprefix . $key . $keysuffix, $data, $value_arr, 0, 0, $morecss, 0,
'100%');
8714 } elseif ($type ==
'link') {
8717 $param_list = array_keys($param[
'options']);
8718 $param_list_array = explode(
':', $param_list[0], 4);
8720 $showempty = (($required && $default !=
'') ? 0 : 1);
8722 if (!preg_match(
'/search_/', $keyprefix)) {
8723 if (!empty($param_list_array[2])) {
8725 if (!empty($this->fields[$key][
'picto'])) {
8726 $morecss .=
' widthcentpercentminusxx';
8728 $morecss .=
' widthcentpercentminusx';
8732 if (!empty($this->fields[$key][
'picto'])) {
8733 $morecss .=
' widthcentpercentminusx';
8742 $objectfield = $val;
8745 $out = $form->selectForForms($param_list_array[0], $keyprefix.$key.$keysuffix, (
int) $value, $showempty,
'',
'', $morecss, $moreparam, 0, (empty($val[
'disabled']) ? 0 : 1),
'', $objectfield);
8747 if (!empty($param_list_array[2])) {
8748 if ((!
GETPOSTISSET(
'backtopage') || strpos(
GETPOST(
'backtopage'), $_SERVER[
'PHP_SELF']) === 0)
8749 && empty($val[
'disabled']) && empty($nonewbutton)) {
8750 list($class, $classfile) = explode(
':', $param_list[0]);
8751 if (file_exists(
dol_buildpath(dirname(dirname($classfile)).
'/card.php'))) {
8752 $url_path =
dol_buildpath(dirname(dirname($classfile)).
'/card.php', 1);
8754 $url_path =
dol_buildpath(dirname(dirname($classfile)).
'/'.strtolower($class).
'_card.php', 1);
8756 $paramforthenewlink =
'';
8757 $paramforthenewlink .= (
GETPOSTISSET(
'action') ?
'&action='.GETPOST(
'action',
'aZ09') :
'');
8758 $paramforthenewlink .= (
GETPOSTISSET(
'id') ?
'&id='.GETPOSTINT(
'id') :
'');
8759 $paramforthenewlink .= (
GETPOSTISSET(
'origin') ?
'&origin='.GETPOST(
'origin',
'aZ09') :
'');
8760 $paramforthenewlink .= (
GETPOSTISSET(
'originid') ?
'&originid='.GETPOSTINT(
'originid') :
'');
8761 $paramforthenewlink .=
'&fk_'.strtolower($class).
'=--IDFORBACKTOPAGE--';
8763 $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>';
8766 } elseif ($type ==
'password') {
8768 if ($keyprefix.$key.$keysuffix ==
'pass_crypted') {
8769 $out =
'<input type="'.($keyprefix ==
'search_' ?
'text' :
'password').
'" class="flat '.$morecss.
'" name="pass" id="pass" value="" '.($moreparam ? $moreparam :
'').
'>';
8770 $out .=
'<input type="hidden" name="pass_crypted" id="pass_crypted" value="'.$value.
'" '.($moreparam ? $moreparam :
'').
'>';
8772 $out =
'<input type="'.($keyprefix ==
'search_' ?
'text' :
'password').
'" class="flat '.$morecss.
'" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.$value.
'" '.($moreparam ? $moreparam :
'').
'>';
8774 } elseif ($type ==
'array') {
8776 $newval[
'type'] =
'varchar(256)';
8779 if (!empty($value)) {
8780 foreach ($value as $option) {
8781 $out .=
'<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).
'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
8782 $out .= $this->showInputField($newval, $keyprefix.$key.$keysuffix.
'[]', $option, $moreparam,
'',
'', $morecss).
'<br></span>';
8785 $out .=
'<a id="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).
'_add" href="javascript:;"><span class="fa fa-plus-circle valignmiddle"></span></a>';
8787 $newInput =
'<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).
'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
8788 $newInput .= $this->showInputField($newval, $keyprefix.$key.$keysuffix.
'[]',
'', $moreparam,
'',
'', $morecss).
'<br></span>';
8790 if (!empty(
$conf->use_javascript_ajax)) {
8792 <script nonce="'.getNonce().
'">
8793 $(document).ready(function() {
8794 $("a#'.
dol_escape_js($keyprefix.$key.$keysuffix).
'_add").click(function() {
8798 $(document).on("click", "a.'.
dol_escape_js($keyprefix.$key.$keysuffix).
'_del", function() {
8799 $(this).parent().remove();
8805 if (!empty($hidden)) {
8806 $out =
'<input type="hidden" value="'.$value.
'" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'"/>';
8809 if ($isDependList == 1) {
8810 $out .= $this->getJSListDependancies(
'_common');
8818 if (!empty($fieldValidationErrorMsg) && function_exists(
'getFieldErrorIcon')) {
8819 $out .=
' '.getFieldErrorIcon($fieldValidationErrorMsg);
8838 public function showOutputField($val, $key, $value, $moreparam =
'', $keysuffix =
'', $keyprefix =
'', $morecss =
'')
8840 global
$conf, $langs, $form;
8844 if (!is_object($form)) {
8845 require_once DOL_DOCUMENT_ROOT.
'/core/class/html.form.class.php';
8846 $form =
new Form($this->db);
8850 $type = empty($val[
'type']) ?
'' : $val[
'type'];
8851 $size = empty($val[
'css']) ?
'' : $val[
'css'];
8856 if (preg_match(
'/varchar\((\d+)\)/', $type, $reg)) {
8859 } elseif (preg_match(
'/varchar/', $type)) {
8862 if (!empty($val[
'arrayofkeyval']) && is_array($val[
'arrayofkeyval'])) {
8864 if (empty($this->fields[$key][
'multiinput'])) {
8865 $type = (($this->fields[$key][
'type'] ==
'checkbox') ? $this->fields[$key][
'type'] :
'select');
8868 if (isset($val[
'type']) && preg_match(
'/^integer:(.*):(.*)/i', $val[
'type'], $reg)) {
8872 $default = empty($val[
'default']) ?
'' : $val[
'default'];
8873 $computed = empty($val[
'computed']) ?
'' : $val[
'computed'];
8874 $unique = empty($val[
'unique']) ?
'' : $val[
'unique'];
8875 $required = empty($val[
'required']) ?
'' : $val[
'required'];
8877 $param[
'options'] = array();
8879 if (!empty($val[
'arrayofkeyval']) && is_array($val[
'arrayofkeyval'])) {
8880 $param[
'options'] = $val[
'arrayofkeyval'];
8882 if (isset($val[
'type']) && preg_match(
'/^integer:([^:]*):([^:]*)/i', $val[
'type'], $reg)) {
8884 $stringforoptions = $reg[1].
':'.$reg[2];
8886 if ($reg[1] ==
'User') {
8887 $stringforoptions .=
':#getnomurlparam1=-1';
8889 $param[
'options'] = array($stringforoptions => $stringforoptions);
8890 } elseif (isset($val[
'type']) && preg_match(
'/^sellist:(.*):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
8891 $param[
'options'] = array($reg[1].
':'.$reg[2].
':'.$reg[3].
':'.$reg[4] =>
'N');
8893 } elseif (isset($val[
'type']) && preg_match(
'/^sellist:(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
8894 $param[
'options'] = array($reg[1].
':'.$reg[2].
':'.$reg[3] =>
'N');
8896 } elseif (isset($val[
'type']) && preg_match(
'/^sellist:(.*):(.*)/i', $val[
'type'], $reg)) {
8897 $param[
'options'] = array($reg[1].
':'.$reg[2] =>
'N');
8899 } elseif (isset($val[
'type']) && preg_match(
'/^chkbxlst:(.*)/i', $val[
'type'], $reg)) {
8900 $param[
'options'] = array($reg[1] =>
'N');
8902 } elseif (isset($val[
'type']) && preg_match(
'/stars\((\d+)\)/', $val[
'type'], $reg)) {
8903 $param[
'options'] = array();
8908 $langfile = empty($val[
'langfile']) ?
'' : $val[
'langfile'];
8909 $list = (empty($val[
'list']) ?
'' : $val[
'list']);
8910 $help = (empty($val[
'help']) ?
'' : $val[
'help']);
8911 $hidden = (($val[
'visible'] == 0) ? 1 : 0);
8921 $value =
dol_eval((
string) $computed, 1, 0,
'2');
8924 if (empty($morecss)) {
8925 if ($type ==
'date') {
8926 $morecss =
'minwidth100imp';
8927 } elseif ($type ==
'datetime' || $type ==
'timestamp') {
8928 $morecss =
'minwidth200imp';
8929 } elseif (in_array($type, array(
'int',
'double',
'price'))) {
8930 $morecss =
'maxwidth75';
8931 } elseif ($type ==
'url') {
8932 $morecss =
'minwidth400';
8933 } elseif ($type ==
'boolean') {
8936 if (is_numeric($size) && round((
float) $size) < 12) {
8937 $morecss =
'minwidth100';
8938 } elseif (is_numeric($size) && round((
float) $size) <= 48) {
8939 $morecss =
'minwidth200';
8941 $morecss =
'minwidth400';
8947 if (in_array($key, array(
'rowid',
'ref')) && method_exists($this,
'getNomUrl')) {
8949 if ($key !=
'rowid' || empty($this->fields[
'ref'])) {
8950 $value = $this->getNomUrl(1,
'', 0,
'', 1);
8952 } elseif ($key ==
'status' && method_exists($this,
'getLibStatut')) {
8953 $value = $this->getLibStatut(3);
8954 } elseif ($type ==
'date') {
8955 if (!empty($value)) {
8960 } elseif ($type ==
'datetime' || $type ==
'timestamp') {
8961 if (!empty($value)) {
8966 } elseif ($type ==
'duration') {
8967 include_once DOL_DOCUMENT_ROOT.
'/core/lib/date.lib.php';
8968 if (!is_null($value) && $value !==
'') {
8971 } elseif ($type ==
'double' || $type ==
'real') {
8972 if (!is_null($value) && $value !==
'') {
8973 $value =
price($value);
8975 } elseif ($type ==
'boolean') {
8977 if (!empty($value)) {
8978 $checked =
' checked ';
8981 $value =
'<input type="checkbox" '.$checked.
' '.($moreparam ? $moreparam :
'').
' readonly disabled>';
8983 $value =
yn($value ? 1 : 0);
8985 } elseif ($type ==
'mail' || $type ==
'email') {
8987 } elseif ($type ==
'url') {
8989 } elseif ($type ==
'phone') {
8990 $value =
dol_print_phone((
string) $value,
'', 0, 0,
'',
' ',
'phone');
8991 } elseif ($type ==
'ip') {
8993 } elseif ($type ==
'stars') {
8994 $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 :
'').
'>';
8995 $value .=
'<div class="star-selection" id="'.$keyprefix.$key.$keysuffix.$this->id.
'_selection">';
8997 while ($i <= $size) {
8998 $value .=
'<span class="star" data-value="'.$i.
'">'.
img_picto(
'',
'fontawesome_star_fas').
'</span>';
9003 $(document).ready(function() { /* commonobject.class.php 2 */
9004 let container = $("#'.$keyprefix.$key.$keysuffix.$this->id.
'_selection");
9005 let selectedStars = parseInt($("#'.$keyprefix.$key.$keysuffix.$this->id.
'").val()) || 0;
9006 container.find(".star").each(function() {
9007 $(this).toggleClass("active", $(this).data("value") <= selectedStars);
9009 container.find(".star").on("mouseover", function() {
9010 let selectedStar = $(this).data("value");
9011 container.find(".star").each(function() {
9012 $(this).toggleClass("active", $(this).data("value") <= selectedStar);
9015 container.on("mouseout", function() {
9016 container.find(".star").each(function() {
9017 $(this).toggleClass("active", $(this).data("value") <= selectedStars);
9020 container.find(".star").off("click").on("click", function() {
9021 selectedStars = $(this).data("value");
9022 if (selectedStars == 1 && $("#'.$keyprefix.$key.$keysuffix.$this->id.
'").val() == 1) {
9025 container.find("#'.$keyprefix.$key.$keysuffix.$this->id.
'").val(selectedStars);
9026 container.find(".star").each(function() {
9027 $(this).toggleClass("active", $(this).data("value") <= selectedStars);
9030 url: "ajax/'.$this->element.
'.php",
9033 objectId: "'.$this->
id.
'",
9034 field: "'.$keyprefix.$key.$keysuffix.
'",
9035 value: selectedStars,
9038 success: function(response) {
9039 var res = JSON.parse(response);
9040 console[res.status === "success" ? "log" : "error"](res.message);
9042 error: function(xhr, status, error) {
9043 console.log("Ajax request failed while updating '.$keyprefix.$key.$keysuffix.
':", error);
9049 } elseif ($type ==
'price') {
9050 if (!is_null($value) && $value !==
'') {
9051 $value =
price($value, 0, $langs, 0, 0, -1,
$conf->currency);
9053 } elseif ($type ==
'select') {
9054 $value = isset($param[
'options'][(
string) $value]) ? $param[
'options'][(
string) $value] :
'';
9055 if (strpos($value,
"|") !==
false) {
9056 $value = $langs->trans(explode(
'|', $value)[0]);
9057 } elseif (! is_numeric($value)) {
9058 $value = $langs->trans($value);
9060 } elseif ($type ==
'sellist') {
9061 $param_list = array_keys($param[
'options']);
9062 $InfoFieldList = explode(
":", $param_list[0]);
9064 $selectkey =
"rowid";
9067 if (count($InfoFieldList) > 2 && !empty($InfoFieldList[2])) {
9068 $selectkey = $InfoFieldList[2];
9069 $keyList = $InfoFieldList[2].
' as rowid';
9072 $fields_label = explode(
'|', $InfoFieldList[1]);
9073 if (is_array($fields_label)) {
9075 $keyList .= implode(
', ', $fields_label);
9078 $filter_categorie =
false;
9079 if (count($InfoFieldList) > 5) {
9080 if ($InfoFieldList[0] ==
'categorie') {
9081 $filter_categorie =
true;
9085 $sql =
"SELECT ".$this->db->sanitize($keyList, 0, 0, 1);
9086 $sql .=
' FROM '.$this->db->prefix().$this->db->sanitize($InfoFieldList[0]);
9087 if (isset($InfoFieldList[4]) && strpos($InfoFieldList[4],
'extra') !==
false) {
9090 if ($selectkey ==
'rowid' && empty($value)) {
9091 $sql .=
" WHERE ".$this->db->sanitize($selectkey).
" = 0";
9092 } elseif ($selectkey ==
'rowid') {
9093 $sql .=
" WHERE ".$this->db->sanitize($selectkey).
" = ".((int) $value);
9095 $sql .=
" WHERE ".$this->db->sanitize($selectkey).
" = '".$this->db->escape((
string) $value).
"'";
9100 dol_syslog(get_class($this).
':showOutputField:$type=sellist', LOG_DEBUG);
9101 $resql = $this->db->query($sql);
9103 if (!$filter_categorie) {
9105 $numrows = $this->db->num_rows($resql);
9107 $obj = $this->db->fetch_object($resql);
9110 $fields_label = explode(
'|', $InfoFieldList[1]);
9112 if (is_array($fields_label) && count($fields_label) > 1) {
9113 foreach ($fields_label as $field_toshow) {
9115 if (!empty($obj->$field_toshow)) {
9116 $translabel = $langs->trans($obj->$field_toshow);
9118 if ($translabel != $field_toshow) {
9119 $value .=
dol_trunc($translabel, 18) .
' ';
9121 $value .= $obj->$field_toshow .
' ';
9126 if (!empty($obj->{$InfoFieldList[1]})) {
9127 $translabel = $langs->trans($obj->{$InfoFieldList[1]});
9129 if ($translabel != $obj->{$InfoFieldList[1]}) {
9132 $value = $obj->{$InfoFieldList[1]};
9137 require_once DOL_DOCUMENT_ROOT .
'/categories/class/categorie.class.php';
9140 $obj = $this->db->fetch_object($resql);
9142 $c->fetch($obj->rowid);
9143 $ways =
$c->print_all_ways();
9144 foreach ($ways as $way) {
9145 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories"' . (
$c->color ?
' style="background: #' .
$c->color .
';"' :
' style="background: #aaa"') .
'>' .
img_object(
'',
'category') .
' ' . $way .
'</li>';
9147 $value =
'<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(
' ', $toprint).
'</ul></div>';
9150 dol_syslog(get_class($this).
'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
9152 } elseif ($type ==
'radio') {
9153 $value = $param[
'options'][(
string) $value];
9154 } elseif ($type ==
'checkbox') {
9155 $value_arr = explode(
',', (
string) $value);
9157 if (is_array($value_arr) && count($value_arr) > 0) {
9159 foreach ($value_arr as $keyval => $valueval) {
9160 if (!empty($valueval)) {
9161 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' . $param[
'options'][$valueval] .
'</li>';
9164 if (!empty($toprint)) {
9165 $value =
'<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">' . implode(
' ', $toprint) .
'</ul></div>';
9168 } elseif ($type ==
'chkbxlst') {
9169 $value_arr = (isset($value) ? explode(
',', $value) : array());
9171 $param_list = array_keys($param[
'options']);
9172 $InfoFieldList = explode(
":", $param_list[0]);
9174 $selectkey =
"rowid";
9177 if (count($InfoFieldList) >= 3) {
9178 $selectkey = $InfoFieldList[2];
9179 $keyList = $InfoFieldList[2].
' as rowid';
9182 $fields_label = explode(
'|', $InfoFieldList[1]);
9183 if (is_array($fields_label)) {
9185 $keyList .= implode(
', ', $fields_label);
9188 $filter_categorie =
false;
9189 if (count($InfoFieldList) > 5) {
9190 if ($InfoFieldList[0] ==
'categorie') {
9191 $filter_categorie =
true;
9195 $sql =
"SELECT ".$this->db->sanitize($keyList, 0, 0, 1);
9196 $sql .=
' FROM '.$this->db->prefix().$this->db->sanitize($InfoFieldList[0]);
9197 if (isset($InfoFieldList[4]) && strpos($InfoFieldList[4],
'extra') !==
false) {
9203 dol_syslog(get_class($this).
':showOutputField:$type=chkbxlst', LOG_DEBUG);
9204 $resql = $this->db->query($sql);
9206 if (!$filter_categorie) {
9209 while ($obj = $this->db->fetch_object($resql)) {
9211 $fields_label = explode(
'|', $InfoFieldList[1]);
9212 if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
9213 if (is_array($fields_label) && count($fields_label) > 1) {
9214 foreach ($fields_label as $field_toshow) {
9216 if (!empty($obj->$field_toshow)) {
9217 $translabel = $langs->trans($obj->$field_toshow);
9219 if ($translabel != $field_toshow) {
9220 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' .
dol_trunc($translabel, 18) .
'</li>';
9222 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' . $obj->$field_toshow .
'</li>';
9227 if (!empty($obj->{$InfoFieldList[1]})) {
9228 $translabel = $langs->trans($obj->{$InfoFieldList[1]});
9230 if ($translabel != $obj->{$InfoFieldList[1]}) {
9231 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' .
dol_trunc($translabel, 18) .
'</li>';
9233 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' . $obj->{$InfoFieldList[1]} .
'</li>';
9239 require_once DOL_DOCUMENT_ROOT .
'/categories/class/categorie.class.php';
9242 while ($obj = $this->db->fetch_object($resql)) {
9243 if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
9245 $c->fetch($obj->rowid);
9246 $ways =
$c->print_all_ways();
9247 foreach ($ways as $way) {
9248 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories"' . (
$c->color ?
' style="background: #' .
$c->color .
';"' :
' style="background: #aaa"') .
'>' .
img_object(
'',
'category') .
' ' . $way .
'</li>';
9253 $value =
'<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(
' ', $toprint).
'</ul></div>';
9255 dol_syslog(get_class($this).
'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
9257 } elseif ($type ==
'link') {
9262 $param_list = array_keys($param[
'options']);
9266 $InfoFieldList = explode(
":", $param_list[0]);
9268 $classname = $InfoFieldList[0];
9269 $classpath = $InfoFieldList[1];
9272 $getnomurlparam = 3;
9273 $getnomurlparam2 =
'';
9275 if (preg_match(
'/#getnomurlparam1=([^#]*)/', $param_list[0], $regtmp)) {
9276 $getnomurlparam = $regtmp[1];
9278 if (preg_match(
'/#getnomurlparam2=([^#]*)/', $param_list[0], $regtmp)) {
9279 $getnomurlparam2 = $regtmp[1];
9282 if (!empty($classpath)) {
9285 if ($classname && !class_exists($classname)) {
9289 if ($element_prop) {
9290 $classname = $element_prop[
'classname'];
9295 if ($classname && class_exists($classname)) {
9296 $object =
new $classname($this->db);
9297 '@phan-var-force CommonObject $object';
9298 if (
$object->element ===
'product') {
9299 '@phan-var-force Product $object';
9300 $result =
$object->fetch((
int) $value,
'',
'',
'', 0, 1, 1);
9302 $result =
$object->fetch($value);
9305 if (
$object->element ===
'product') {
9306 '@phan-var-force Product $object';
9307 $get_name_url_param_arr = array($getnomurlparam, $getnomurlparam2, 0, -1, 0,
'', 0);
9308 if (isset($val[
'get_name_url_params'])) {
9309 $get_name_url_params = explode(
':', $val[
'get_name_url_params']);
9310 if (!empty($get_name_url_params)) {
9311 $param_num_max = count($get_name_url_param_arr) - 1;
9312 foreach ($get_name_url_params as $param_num => $param_value) {
9313 if ($param_num > $param_num_max) {
9316 $get_name_url_param_arr[$param_num] = $param_value;
9324 $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]);
9326 $value =
$object->getNomUrl($getnomurlparam, $getnomurlparam2);
9333 dol_syslog(
'Error bad setup of extrafield', LOG_WARNING);
9334 return 'Error bad setup of extrafield';
9339 } elseif ($type ==
'password') {
9340 $value =
'<span class="opacitymedium">'.$langs->trans(
"Encrypted").
'</span>';
9342 } elseif ($type ==
'array') {
9343 if (is_array($value)) {
9344 $value = implode(
'<br>', $value);
9346 dol_syslog(__METHOD__.
' Expected array from dol_eval, but got '.gettype($value), LOG_ERR);
9347 return 'Error unexpected result from code evaluation';
9350 if (!empty($value) && preg_match(
'/^text/', (
string) $type) && !preg_match(
'/search_/', $keyprefix) && !empty($param[
'options'])) {
9351 $value = str_replace(
',',
"\n", $value);
9359 return is_null($out) ?
'' : $out;
9371 unset($this->validateFieldsErrors[$fieldKey]);
9385 $msg = $langs->trans(
"UnknownError");
9388 $this->error = $this->validateFieldsErrors[$fieldKey] = $msg;
9399 if (!empty($this->validateFieldsErrors[$fieldKey])) {
9400 return $this->validateFieldsErrors[$fieldKey];
9417 if (!class_exists(
'Validate')) {
9418 require_once DOL_DOCUMENT_ROOT .
'/core/class/validate.class.php';
9421 $this->clearFieldError($fieldKey);
9423 if (!array_key_exists($fieldKey, $fields) || !is_array($fields[$fieldKey])) {
9424 $this->setFieldError($fieldKey, $langs->trans(
'FieldNotFoundInObject'));
9428 $val = $fields[$fieldKey];
9431 $param[
'options'] = array();
9432 $type = $val[
'type'];
9435 if (isset($val[
'notnull']) && $val[
'notnull'] === 1) {
9449 if (preg_match(
'/varchar\((\d+)\)/', $type, $reg)) {
9451 $maxSize = (int) $reg[1];
9452 } elseif (preg_match(
'/varchar/', $type)) {
9456 if (!empty($val[
'arrayofkeyval']) && is_array($val[
'arrayofkeyval'])) {
9460 if (!empty($val[
'type']) && preg_match(
'/^integer:(.*):(.*)/i', $val[
'type'], $reg)) {
9464 if (!empty($val[
'arrayofkeyval']) && is_array($val[
'arrayofkeyval'])) {
9465 $param[
'options'] = $val[
'arrayofkeyval'];
9468 if (preg_match(
'/^integer:(.*):(.*)/i', $val[
'type'], $reg)) {
9470 $param[
'options'] = array($reg[1].
':'.$reg[2] => $reg[1].
':'.$reg[2]);
9471 } elseif (preg_match(
'/^sellist:(.*):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
9472 $param[
'options'] = array($reg[1].
':'.$reg[2].
':'.$reg[3].
':'.$reg[4] =>
'N');
9474 } elseif (preg_match(
'/^sellist:(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
9475 $param[
'options'] = array($reg[1].
':'.$reg[2].
':'.$reg[3] =>
'N');
9477 } elseif (preg_match(
'/^sellist:(.*):(.*)/i', $val[
'type'], $reg)) {
9478 $param[
'options'] = array($reg[1].
':'.$reg[2] =>
'N');
9487 $validate =
new Validate($this->db, $langs);
9497 if ($required && !$validate->isNotEmptyString($fieldValue)) {
9498 $this->setFieldError($fieldKey, $validate->error);
9500 } elseif (!$required && !$validate->isNotEmptyString($fieldValue)) {
9506 if (!empty($maxSize) && !$validate->isMaxLength($fieldValue, $maxSize)) {
9507 $this->setFieldError($fieldKey, $validate->error);
9512 if (!empty($minSize) && !$validate->isMinLength($fieldValue, $minSize)) {
9513 $this->setFieldError($fieldKey, $validate->error);
9521 if (in_array($type, array(
'date',
'datetime',
'timestamp'))) {
9522 if (!$validate->isTimestamp($fieldValue)) {
9523 $this->setFieldError($fieldKey, $validate->error);
9528 } elseif ($type ==
'duration') {
9529 if (!$validate->isDuration($fieldValue)) {
9530 $this->setFieldError($fieldKey, $validate->error);
9535 } elseif (in_array($type, array(
'double',
'real',
'price'))) {
9537 if (!$validate->isNumeric($fieldValue)) {
9538 $this->setFieldError($fieldKey, $validate->error);
9543 } elseif ($type ==
'boolean') {
9544 if (!$validate->isBool($fieldValue)) {
9545 $this->setFieldError($fieldKey, $validate->error);
9550 } elseif ($type ==
'mail' || $type ==
'email') {
9551 if (!$validate->isEmail($fieldValue)) {
9552 $this->setFieldError($fieldKey, $validate->error);
9555 } elseif ($type ==
'url') {
9556 if (!$validate->isUrl($fieldValue)) {
9557 $this->setFieldError($fieldKey, $validate->error);
9562 } elseif ($type ==
'phone') {
9563 if (!$validate->isPhone($fieldValue)) {
9564 $this->setFieldError($fieldKey, $validate->error);
9569 } elseif ($type ==
'select' || $type ==
'radio') {
9570 if (!isset($param[
'options'][$fieldValue])) {
9571 $this->error = $langs->trans(
'RequireValidValue');
9576 } elseif ($type ==
'sellist' || $type ==
'chkbxlst') {
9577 $param_list = array_keys($param[
'options']);
9578 $InfoFieldList = explode(
":", $param_list[0]);
9579 $value_arr = explode(
',', $fieldValue);
9581 $selectkey =
"rowid";
9582 if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
9583 $selectkey = $InfoFieldList[2];
9586 if (!$validate->isInDb($value_arr, $InfoFieldList[0], $selectkey)) {
9587 $this->setFieldError($fieldKey, $validate->error);
9592 } elseif ($type ==
'link') {
9593 $param_list = array_keys($param[
'options']);
9594 $InfoFieldList = explode(
":", $param_list[0]);
9595 $classname = $InfoFieldList[0];
9596 $classpath = $InfoFieldList[1];
9597 if (!$validate->isFetchable((
int) $fieldValue, $classname, $classpath)) {
9598 $lastIsFetchableError = $validate->error;
9601 if ($validate->isFetchableElement((
int) $fieldValue, $classname)) {
9605 $this->setFieldError($fieldKey, $lastIsFetchableError);
9629 public function showOptionals($extrafields, $mode =
'view', $params =
null, $keysuffix =
'', $keyprefix =
'', $onetrtd =
'', $display_type =
'card')
9631 global
$db,
$conf, $langs, $action, $form, $hookmanager;
9632 global $objectoffield;
9634 if (!is_object($form)) {
9637 if (!is_object($extrafields)) {
9638 dol_syslog(
'Bad parameter extrafields for showOptionals', LOG_ERR);
9639 return 'Bad parameter extrafields for showOptionals';
9641 if (!is_array($extrafields->attributes[$this->table_element])) {
9642 dol_syslog(
"extrafields->attributes was not loaded with extrafields->fetch_name_optionals_label(table_element);", LOG_WARNING);
9646 $objectoffield = $this;
9650 $parameters = array(
'mode' => $mode,
'params' => $params,
'keysuffix' => $keysuffix,
'keyprefix' => $keyprefix,
'display_type' => $display_type);
9651 $reshook = $hookmanager->executeHooks(
'showOptionals', $parameters, $this, $action);
9652 $hookResPrint = $hookmanager->resPrint;
9654 if (empty($reshook)) {
9655 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) {
9657 $out .=
'<!-- commonobject:showOptionals --> ';
9660 $nbofextrafieldsshown = 0;
9663 $lastseparatorkeyfound =
'';
9664 $extrafields_collapse_num =
'';
9665 $extrafields_collapse_num_old =
'';
9668 foreach ($extrafields->attributes[$this->table_element][
'label'] as $key => $label) {
9672 if (is_array($params) && array_key_exists(
'onlykey', $params) && $key != $params[
'onlykey']) {
9678 if ($enabled && isset($extrafields->attributes[$this->table_element][
'enabled'][$key])) {
9679 $enabled = (int)
dol_eval((
string) $extrafields->attributes[$this->table_element][
'enabled'][$key], 1, 1,
'2');
9681 if (empty($enabled)) {
9686 if (isset($extrafields->attributes[$this->table_element][
'list'][$key])) {
9687 $visibility = (int)
dol_eval((
string) $extrafields->attributes[$this->table_element][
'list'][$key], 1, 1,
'2');
9691 if ($perms && isset($extrafields->attributes[$this->table_element][
'perms'][$key])) {
9692 $perms = (int)
dol_eval((
string) $extrafields->attributes[$this->table_element][
'perms'][$key], 1, 1,
'2');
9695 if (($mode ==
'create') && !in_array(abs($visibility), array(1, 3))) {
9697 } elseif (($mode ==
'edit') && !in_array(abs($visibility), array(1, 3, 4))) {
9701 $ef_name =
'options_' . $key;
9702 $ef_value = $this->array_options[$ef_name] ??
'';
9703 $out .=
'<input type="hidden" name="' . $ef_name .
'" id="' . $ef_name .
'" value="' .
dolPrintHTMLForAttribute($ef_value) .
'" />' .
"\n";
9705 } elseif ($mode ==
'view' && empty($visibility)) {
9708 if (empty($perms)) {
9713 if (!empty($extrafields->attributes[$this->table_element][
'langfile'][$key])) {
9714 $langs->load($extrafields->attributes[$this->table_element][
'langfile'][$key]);
9719 if (is_array($params) && count($params) > 0 && $display_type ==
'card') {
9720 if (array_key_exists(
'cols', $params)) {
9721 $colspan = $params[
'cols'];
9722 } elseif (array_key_exists(
'colspan', $params)) {
9724 if (preg_match(
'/colspan="(\d+)"/', $params[
'colspan'], $reg)) {
9727 $colspan = $params[
'colspan'];
9731 $colspan = intval($colspan);
9735 $value = ((!empty($this->array_options) && array_key_exists(
"options_".$key.$keysuffix, $this->array_options)) ? $this->array_options[
"options_".$key.$keysuffix] :
null);
9741 $check =
'alphanohtml';
9742 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'html',
'text'))) {
9743 $check =
'restricthtml';
9745 $getposttemp =
GETPOST($keyprefix.
'options_'.$key.$keysuffix, $check, 3);
9747 if (is_array($getposttemp) || $getposttemp !=
'' ||
GETPOSTISSET($keyprefix.
'options_'.$key.$keysuffix)) {
9748 if (is_array($getposttemp)) {
9750 $value = implode(
",", $getposttemp);
9752 $value = $getposttemp;
9754 } elseif (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'int'))) {
9755 $value = (!empty($this->array_options[
"options_".$key]) || (isset($this->array_options[
"options_".$key]) && $this->array_options[
"options_".$key] ===
'0')) ? $this->array_options[
"options_".$key] :
'';
9756 } elseif (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'varchar',
'char'))) {
9757 $value = (isset($this->array_options[
"options_".$key]) && $this->array_options[
"options_".$key] !==
'') ? $this->array_options[
"options_".$key] :
'';
9759 $value = (!empty($this->array_options[
"options_".$key]) ? $this->array_options[
"options_".$key] :
'');
9765 $nbofextrafieldsshown++;
9768 if ($extrafields->attributes[$this->table_element][
'type'][$key] ==
'separate') {
9769 $extrafields_collapse_num = $key;
9787 $out .= $extrafields->showSeparator($key, $this, ($colspan ? $colspan + 1 : 2), $display_type, $mode);
9789 $lastseparatorkeyfound = $key;
9791 $collapse_group = $extrafields_collapse_num.(!empty($this->
id) ?
'_'.$this->id :
'');
9793 $class = (!empty($extrafields->attributes[$this->table_element][
'hidden'][$key]) ?
'hideobject ' :
'');
9795 if (is_array($params) && count($params) > 0) {
9796 if (array_key_exists(
'class', $params)) {
9797 $class .= $params[
'class'].
' ';
9799 if (array_key_exists(
'style', $params)) {
9800 $csstyle = $params[
'style'];
9805 $domData =
' data-element="extrafield"';
9806 $domData .=
' data-targetelement="'.$this->element.
'"';
9807 $domData .=
' data-targetid="'.$this->id.
'"';
9809 $html_id = (empty($this->
id) ?
'' :
'extrarow-'.$this->element.
'_'.$key.
'_'.
$this->id);
9810 if ($display_type ==
'card') {
9815 if ($action ==
'selectlines') {
9822 $force_values_on_change_company = (
9823 ($this->element ==
'facture' &&
getDolGlobalInt(
'THIRDPARTY_PROPAGATE_EXTRAFIELDS_TO_INVOICE'))
9824 || ($this->element ==
'commande' &&
getDolGlobalInt(
'THIRDPARTY_PROPAGATE_EXTRAFIELDS_TO_ORDER'))
9825 || ($this->element ==
'order_supplier' &&
getDolGlobalInt(
'THIRDPARTY_PROPAGATE_EXTRAFIELDS_TO_SUPPLIER_ORDER'))
9827 if ($force_values_on_change_company &&
GETPOSTINT(
'changecompany')) {
9828 $value = $this->array_options[
'options_'.$key] ?? $value;
9832 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'date'))) {
9833 $datenotinstring =
null;
9834 if (array_key_exists(
'options_'.$key, $this->array_options)) {
9835 $datenotinstring = $this->array_options[
'options_'.$key];
9836 if (!is_numeric($this->array_options[
'options_'.$key])) {
9837 $datenotinstring = $this->db->jdate($datenotinstring);
9840 $datekey = $keyprefix.
'options_'.$key.$keysuffix;
9843 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'datetime'))) {
9844 $datenotinstring =
null;
9845 if (array_key_exists(
'options_'.$key, $this->array_options)) {
9846 $datenotinstring = $this->array_options[
'options_'.$key];
9847 if (!is_numeric($this->array_options[
'options_'.$key])) {
9848 $datenotinstring = $this->db->jdate($datenotinstring);
9851 $timekey = $keyprefix.
'options_'.$key.$keysuffix;
9852 $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;
9855 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'price',
'double'))) {
9856 if (
GETPOSTISSET($keyprefix.
'options_'.$key.$keysuffix) || $value) {
9858 } elseif (isset($this->array_options[
'options_'.$key])) {
9859 $value = $this->array_options[
'options_'.$key];
9864 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'html',
'text',
'varchar',
'select',
'radio',
'int',
'boolean'))) {
9865 if ($action ==
'create' || $mode ==
'create') {
9866 $value = (
GETPOSTISSET($keyprefix.
'options_'.$key.$keysuffix) || $value) ? $value : $extrafields->attributes[$this->table_element][
'default'][$key];
9870 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'checkbox'))) {
9871 if ($action ==
'create') {
9872 $value = (
GETPOSTISSET($keyprefix.
'options_'.$key.$keysuffix) || $value) ? $value : explode(
',', $extrafields->attributes[$this->table_element][
'default'][$key]);
9877 $labeltoshow = $langs->trans($label);
9878 $helptoshow = $langs->trans($extrafields->attributes[$this->table_element][
'help'][$key]);
9879 if ($display_type ==
'card') {
9880 $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.
' >';
9881 if (
getDolGlobalString(
'MAIN_VIEW_LINE_NUMBER') && ($action ==
'view' || $action ==
'valid' || $action ==
'editline' || $action ==
'confirm_valid' || $action ==
'confirm_cancel')) {
9882 $out .=
'<td></td>';
9884 $out .=
'<td class="'.(empty($params[
'tdclass']) ?
'titlefieldmax45' : $params[
'tdclass']).
' wordbreak';
9885 if ($extrafields->attributes[$this->table_element][
'type'][$key] ==
'text') {
9888 } elseif ($display_type ==
'line') {
9889 $out .=
'<div '.($html_id ?
'id="'.$html_id.
'" ' :
'').$csstyle.
' class="fieldline_options_'.$key.
' '.$class.$this->element.
'_extras_'.$key.
' trextrafields_collapse'.$collapse_group.
'" '.$domData.
' >';
9890 $out .=
'<div style="display: inline-block; padding-right:4px" class="wordbreak';
9895 $tpl_context = isset($params[
"tpl_context"]) ? $params[
"tpl_context"] :
"none";
9896 if ($tpl_context !=
"public") {
9897 if ($mode !=
'view' && !empty($extrafields->attributes[$this->table_element][
'required'][$key])) {
9898 $out .=
' fieldrequired';
9902 if ($tpl_context ==
"public") {
9903 if (!empty($extrafields->attributes[$this->table_element][
'help'][$key])) {
9904 $out .= $form->textwithpicto($labeltoshow, $helptoshow);
9906 $out .= $labeltoshow;
9908 if ($mode !=
'view' && !empty($extrafields->attributes[$this->table_element][
'required'][$key])) {
9909 $out .=
' <span style="color: red">*</span>';
9912 if (!empty($extrafields->attributes[$this->table_element][
'help'][$key])) {
9913 $out .= $form->textwithpicto($labeltoshow, $helptoshow);
9915 $out .= $labeltoshow;
9919 $out .= ($display_type ==
'card' ?
'</td>' :
'</div>');
9922 $html_id = !empty($this->
id) ? $this->element.
'_extras_'.$key.
'_'.$this->id :
'';
9923 if ($display_type ==
'card') {
9925 $out .=
'<td '.($html_id ?
'id="'.$html_id.
'" ' :
'').
' class="valuefieldcreate '.$this->element.
'_extras_'.$key;
9926 $out .=
'" '.($colspan ?
' colspan="'.$colspan.
'"' :
'');
9928 } elseif ($display_type ==
'line') {
9929 $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].
'">';
9934 $out .= $extrafields->showOutputField($key, $value,
'', $this->table_element);
9937 $listoftypestoshowpicto = explode(
',',
getDolGlobalString(
'MAIN_TYPES_TO_SHOW_PICTO',
'email,phone,ip,password'));
9938 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], $listoftypestoshowpicto)) {
9939 $out .=
getPictoForType($extrafields->attributes[$this->table_element][
'type'][$key], ($extrafields->attributes[$this->table_element][
'type'][$key] ==
'text' ?
'tdtop' :
''));
9942 $out .= $extrafields->showInputField($key, $value,
'', $keysuffix,
'',
'', $this, $this->table_element);
9945 $listoftypestoshowpicto = explode(
',',
getDolGlobalString(
'MAIN_TYPES_TO_SHOW_PICTO',
'email,phone,ip,password'));
9946 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], $listoftypestoshowpicto)) {
9947 $out .=
getPictoForType($extrafields->attributes[$this->table_element][
'type'][$key], ($extrafields->attributes[$this->table_element][
'type'][$key] ==
'text' ?
'tdtop' :
''));
9949 $out .= $extrafields->showInputField($key, $value,
'', $keysuffix,
'',
'', $this, $this->table_element);
9953 $out .= ($display_type ==
'card' ?
'</td>' :
'</div>');
9954 $out .= ($display_type ==
'card' ?
'</tr>'.
"\n" :
'</div>');
9960 if (!empty(
$conf->use_javascript_ajax)) {
9961 $out .= $this->getJSListDependancies();
9964 $out .=
'<!-- commonobject:showOptionals end --> '.
"\n";
9966 if (empty($nbofextrafieldsshown)) {
9972 $out .= $hookResPrint;
9984 <script nonce="'.getNonce().
'">
9985 jQuery(document).ready(function() {
9986 function showOptions'.$type.
'(child_list, parent_list, orig_select)
9988 var val = $("select[name=\""+parent_list+"\"]").val();
9989 var parentVal = parent_list + ":" + val;
9990 if(typeof val == "string"){
9992 var options = orig_select.find("option[parent=\""+parentVal+"\"]").clone();
9993 $("select[name=\""+child_list+"\"] option[parent]").remove();
9994 $("select[name=\""+child_list+"\"]").append(options);
9996 var options = orig_select.find("option[parent]").clone();
9997 $("select[name=\""+child_list+"\"] option[parent]").remove();
9998 $("select[name=\""+child_list+"\"]").append(options);
10000 } else if(val > 0) {
10001 var options = orig_select.find("option[parent=\""+parentVal+"\"]").clone();
10002 $("select[name=\""+child_list+"\"] option[parent]").remove();
10003 $("select[name=\""+child_list+"\"]").append(options);
10005 var options = orig_select.find("option[parent]").clone();
10006 $("select[name=\""+child_list+"\"] option[parent]").remove();
10007 $("select[name=\""+child_list+"\"]").append(options);
10010 function setListDependencies'.$type.
'() {
10011 jQuery("select option[parent]").parent().each(function() {
10012 var orig_select = {};
10013 var child_list = $(this).attr("name");
10014 orig_select[child_list] = $(this).clone();
10015 var parent = $(this).find("option[parent]:first").attr("parent");
10016 var infos = parent.split(":");
10017 var parent_list = infos[0];
10019 //Hide daughters lists
10020 if ($("#"+child_list).val() == 0 && $("#"+parent_list).val() == 0){
10021 $("#"+child_list).hide();
10022 //Show mother lists
10023 } else if ($("#"+parent_list).val() != 0){
10024 $("#"+parent_list).show();
10026 //Show the child list if the parent list value is selected
10027 $("select[name=\""+parent_list+"\"]").click(function() {
10028 if ($(this).val() != 0){
10029 $("#"+child_list).show()
10033 //When we change parent list
10034 $("select[name=\""+parent_list+"\"]").change(function() {
10035 showOptions'.$type.
'(child_list, parent_list, orig_select[child_list]);
10036 //Select the value 0 on child list after a change on the parent list
10037 $("#"+child_list).val(0).trigger("change");
10038 //Hide child lists if the parent value is set to 0
10039 if ($(this).val() == 0){
10040 $("#"+child_list).hide();
10046 setListDependencies'.$type.
'();
10061 $module = empty($this->module) ?
'' : $this->module;
10062 $element = $this->element;
10064 if ($element ==
'facturerec') {
10065 $element =
'facture';
10066 } elseif ($element ==
'invoice_supplier_rec') {
10067 return !$user->hasRight(
'fournisseur',
'facture') ? null : $user->hasRight(
'fournisseur',
'facture');
10068 } elseif ($module && $user->hasRight($module, $element)) {
10070 return $user->hasRight($module, $element);
10073 return isset($user->rights->$element) ? $user->rights->$element :
null;
10090 global $hookmanager;
10092 $parameters = array(
10093 'origin_id' => $origin_id,
10094 'dest_id' => $dest_id,
10095 'tables' => $tables,
10097 $reshook = $hookmanager->executeHooks(
'commonReplaceThirdparty', $parameters);
10100 } elseif ($reshook < 0) {
10101 return $ignoreerrors === 1;
10104 foreach ($tables as $table) {
10105 $sql =
'UPDATE '.$dbs->prefix().$table.
' SET fk_soc = '.((int) $dest_id).
' WHERE fk_soc = '.((int) $origin_id);
10107 if (!$dbs->
query($sql)) {
10108 if ($ignoreerrors) {
10133 foreach ($tables as $table) {
10134 $sql =
'UPDATE '.MAIN_DB_PREFIX.$table.
' SET fk_product = '.((int) $dest_id).
' WHERE fk_product = '.((int) $origin_id);
10136 if (!$dbs->
query($sql)) {
10137 if ($ignoreerrors) {
10161 public function defineBuyPrice($unitPrice = 0.0, $discountPercent = 0.0, $fk_product = 0, $qty = 0)
10167 if (($unitPrice > 0) && (isset(
$conf->global->ForceBuyingPriceIfNull) &&
getDolGlobalInt(
'ForceBuyingPriceIfNull') > 0)) {
10169 $buyPrice = $unitPrice * (1 - $discountPercent / 100);
10172 if (!empty($fk_product) && $fk_product > 0) {
10175 require_once DOL_DOCUMENT_ROOT.
'/product/class/product.class.php';
10176 $product =
new Product($this->db);
10177 $result = $product->fetch($fk_product);
10178 if ($result <= 0) {
10179 $this->errors[] =
'ErrorProductIdDoesNotExists';
10182 if ($product->cost_price > 0) {
10183 $buyPrice = $product->cost_price;
10184 } elseif ($product->pmp > 0) {
10185 $buyPrice = $product->pmp;
10188 require_once DOL_DOCUMENT_ROOT.
'/product/class/product.class.php';
10189 $product =
new Product($this->db);
10190 $result = $product->fetch($fk_product);
10191 if ($result <= 0) {
10192 $this->errors[] =
'ErrorProductIdDoesNotExists';
10195 if ($product->pmp > 0) {
10196 $buyPrice = $product->pmp;
10200 if (empty($buyPrice) && in_array(
getDolGlobalString(
'MARGIN_TYPE'), array(
'1',
'pmp',
'costprice'))) {
10201 require_once DOL_DOCUMENT_ROOT.
'/fourn/class/fournisseur.product.class.php';
10203 $result = $productFournisseur->find_min_price_product_fournisseur($fk_product, $qty);
10204 if ($result == 0 && $qty > 0) {
10206 $result = $productFournisseur->find_min_price_product_fournisseur($fk_product);
10209 $buyPrice = $productFournisseur->fourn_unitprice;
10210 } elseif ($result < 0) {
10211 $this->errors[] = $productFournisseur->error;
10218 return (
float) $buyPrice;
10231 return array(
'dir' =>
'',
'file' =>
'',
'originalfile' =>
'',
'altfile' =>
'',
'email' =>
'',
'capture' =>
'');
10255 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')
10258 global $user, $langs;
10260 include_once DOL_DOCUMENT_ROOT.
'/core/lib/files.lib.php';
10261 include_once DOL_DOCUMENT_ROOT.
'/core/lib/images.lib.php';
10262 include_once DOL_DOCUMENT_ROOT.
'/core/class/link.class.php';
10264 $sortfield =
'position_name';
10265 $sortorder =
'asc';
10270 $dir .=
get_exdir(0, 0, 0, 0, $this, $modulepart);
10271 $pdir .=
get_exdir(0, 0, 0, 0, $this, $modulepart);
10274 if ($modulepart ==
'product') {
10276 $dir = $sdir.
'/'.
get_exdir($this->
id, 2, 0, 0, $this, $modulepart).$this->id.
"/photos/";
10277 $pdir =
'/'.get_exdir($this->
id, 2, 0, 0, $this, $modulepart).$this->id.
"/photos/";
10280 if ($modulepart ==
'category') {
10281 $dir = $sdir.
'/'.
get_exdir($this->
id, 2, 0, 0, $this, $modulepart).$this->id.
"/photos/";
10282 $pdir =
'/'.get_exdir($this->
id, 2, 0, 0, $this, $modulepart).$this->id.
"/photos/";
10288 $relativedir = preg_replace(
'/^'.preg_quote(DOL_DATA_ROOT,
'/').
'/',
'', $dir);
10289 $relativedir = preg_replace(
'/^[\\/]/',
'', $relativedir);
10290 $relativedir = preg_replace(
'/[\\/]$/',
'', $relativedir);
10293 $dirthumb = $dir.
'thumbs/';
10294 $pdirthumb = $pdir.
'thumbs/';
10296 $return =
'<!-- Photo -->'.
"\n";
10299 $filearray =
dol_dir_list($dir,
"files", 0,
'',
'(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) ==
'desc' ? SORT_DESC : SORT_ASC), 1);
10308 '@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';
10310 $useLinkPathPhoto =
false;
10313 $link =
new Link($this->db);
10315 $link->fetchAll($links,
'product', $this->
id);
10317 if (count($links) > 0) {
10318 $useLinkPathPhoto =
true;
10321 if ($useLinkPathPhoto) {
10323 if ($nbbyrow > 0) {
10324 $return .=
'<table class="valigntop center centpercent" style="border:0; padding:2px; border-spacing:2px; border-collapse: separate;">';
10328 foreach ($links as $link) {
10329 if (!empty($link->url) && preg_match(
'/\.(jpg|jpeg|png|gif|webp)$/i', $link->url)) {
10334 if ($nbbyrow > 0 && ($i % $nbbyrow == 1)) {
10335 $return .=
'<tr class="center valignmiddle">';
10338 if ($nbbyrow > 0) {
10339 $return .=
'<td style="width:'.ceil(100 / $nbbyrow).
'%" class="photo">';
10341 $return .=
'<div class="inline-block">';
10344 $return .=
'<img class="photo photowithmargin'.($addphotorefcss ?
' '.$addphotorefcss :
'').
'"'.($maxHeight ?
' height="'.$maxHeight.
'"' :
'').
' src="'.$url.
'" title="External image">';
10346 if ($nbbyrow > 0) {
10347 $return .=
'</td>';
10348 if ($i % $nbbyrow == 0) {
10349 $return .=
'</tr>';
10352 $return .=
'</div>';
10355 if ($nbmax && $nbphoto >= $nbmax) {
10361 if ($nbbyrow > 0) {
10362 while ($i % $nbbyrow) {
10363 $return .=
'<td style="width:'.ceil(100 / $nbbyrow).
'%"> </td>';
10367 $return .=
'</table>';
10373 if (count($filearray)) {
10374 if ($sortfield && $sortorder) {
10375 $filearray =
dol_sort_array($filearray, $sortfield, $sortorder);
10378 foreach ($filearray as $key => $val) {
10380 $file = $val[
'name'];
10386 $viewfilename = $file;
10388 if ($size == 1 || $size ==
'small') {
10394 $pdirthumb = $pdir;
10395 $photo_vignette = basename($file);
10401 if ($nbbyrow > 0) {
10402 if ($nbphoto == 1) {
10403 $return .=
'<table class="valigntop center centpercent" style="border: 0; padding: 2px; border-spacing: 2px; border-collapse: separate;">';
10406 if ($nbphoto % $nbbyrow == 1) {
10407 $return .=
'<tr class="center valignmiddle" style="border: 1px">';
10409 $return .=
'<td style="width: '.ceil(100 / $nbbyrow).
'%" class="photo">'.
"\n";
10410 } elseif ($nbbyrow < 0) {
10411 $return .=
'<div class="inline-block">'.
"\n";
10414 $relativefile = preg_replace(
'/^\//',
'', $pdir.$photo);
10415 if (empty($nolink)) {
10417 if ($urladvanced) {
10418 $return .=
'<a href="'.$urladvanced.
'">';
10420 $return .=
'<a href="'.DOL_URL_ROOT.
'/viewimage.php?modulepart='.$modulepart.
'&entity='.$this->entity.
'&file='.urlencode($pdir.$photo).
'" class="aphoto" target="_blank" rel="noopener noreferrer">';
10426 $alt = $langs->transnoentitiesnoconv(
'File').
': '.$relativefile;
10427 $alt .=
' - '.$langs->transnoentitiesnoconv(
'Size').
': '.$imgarray[
'width'].
'x'.$imgarray[
'height'];
10428 if ($overwritetitle) {
10429 if (is_numeric($overwritetitle)) {
10432 $alt = $overwritetitle;
10435 if (empty($cache) && !empty($val[
'label'])) {
10438 $cache = $val[
'label'];
10440 if ($usesharelink) {
10441 if (array_key_exists(
'share', $val) && $val[
'share']) {
10442 if (empty($maxHeight) || ($photo_vignette && $imgarray[
'height'] > $maxHeight)) {
10443 $return .=
'<!-- Show original file (thumb not yet available with shared links) -->';
10444 $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).
'">';
10446 $return .=
'<!-- Show original file -->';
10447 $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).
'">';
10450 $return .=
'<!-- Show nophoto file (because file is not shared) -->';
10451 $return .=
'<img class="photo photowithmargin'.($addphotorefcss ?
' '.$addphotorefcss :
'').
'" height="'.$maxHeight.
'" src="'.DOL_URL_ROOT.
'/public/theme/common/nophoto.png" title="'.
dol_escape_htmltag($alt).
'">';
10454 if (empty($maxHeight) || ($photo_vignette && $imgarray[
'height'] > $maxHeight)) {
10455 $return .=
'<!-- Show thumb -->';
10456 $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).
'">';
10458 $return .=
'<!-- Show original file -->';
10459 $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).
'">';
10463 if (empty($nolink)) {
10467 if ($showfilename) {
10468 $return .=
'<br>'.$viewfilename;
10473 if ($photo_vignette && (
image_format_supported($photo) > 0) && ((isset($imgarray[
'width']) && $imgarray[
'width'] > $maxWidth) || (isset($imgarray[
'width']) && $imgarray[
'width'] > $maxHeight))) {
10474 $return .=
'<a href="'.$_SERVER[
"PHP_SELF"].
'?id='.$this->
id.
'&action=addthumb&token='.
newToken().
'&file='.urlencode($pdir.$viewfilename).
'">'.
img_picto($langs->trans(
'GenerateThumb'),
'refresh').
' </a>';
10477 if ($modulepart ==
'product' && ($user->hasRight(
'produit',
'creer') || $user->hasRight(
'service',
'creer'))) {
10479 $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> ';
10482 $return .=
'<a href="'.$_SERVER[
"PHP_SELF"].
'?id='.$this->
id.
'&action=delete&token='.
newToken().
'&file='.urlencode($pdir.$viewfilename).
'">';
10488 if ($nbbyrow > 0) {
10489 $return .=
'</td>';
10490 if (($nbphoto % $nbbyrow) == 0) {
10491 $return .=
'</tr>';
10493 } elseif ($nbbyrow < 0) {
10494 $return .=
'</div>'.
"\n";
10498 if (empty($size)) {
10499 $return .=
'<img class="photo photowithmargin" src="'.DOL_URL_ROOT.
'/viewimage.php?modulepart='.$modulepart.
'&entity='.$this->entity.
'&file='.urlencode($pdir.$photo).
'">';
10501 if ($showfilename) {
10502 $return .=
'<br>'.$viewfilename;
10506 if ($modulepart ==
'product' && ($user->hasRight(
'produit',
'creer') || $user->hasRight(
'service',
'creer'))) {
10508 $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> ';
10511 $return .=
'<a href="'.$_SERVER[
"PHP_SELF"].
'?id='.$this->
id.
'&action=delete&token='.
newToken().
'&file='.urlencode($pdir.$viewfilename).
'">';
10518 if ($nbmax && $nbphoto >= $nbmax) {
10524 if ($size == 1 || $size ==
'small') {
10525 if ($nbbyrow > 0) {
10527 while ($nbphoto % $nbbyrow) {
10528 $return .=
'<td style="width: '.ceil(100 / $nbbyrow).
'%"> </td>';
10533 $return .=
'</table>';
10539 $this->nbphoto = $nbphoto;
10553 if (is_array($info)) {
10554 if (isset($info[
'type']) && $info[
'type'] ==
'array') {
10571 if (isset($info[
'type']) && ($info[
'type'] ==
'date' || $info[
'type'] ==
'datetime' || $info[
'type'] ==
'timestamp')) {
10585 if (is_array($info)) {
10586 if (isset($info[
'type']) && ($info[
'type'] ==
'duration')) {
10604 if (is_array($info)) {
10605 if (isset($info[
'type']) && (preg_match(
'/^(?:tiny|small|medium|big)?int|int$/i', $info[
'type']))) {
10623 if (is_array($info)) {
10624 if (isset($info[
'type']) && (preg_match(
'/^(double|real|price)/i', $info[
'type']))) {
10641 if (is_array($info)) {
10642 if (isset($info[
'type']) && $info[
'type'] ==
'text') {
10659 if (is_array($info)) {
10660 if (array_key_exists(
'notnull', $info) && $info[
'notnull'] !=
'1') {
10677 if (is_array($info)) {
10678 if (array_key_exists(
'notnull', $info) && $info[
'notnull'] ==
'-1') {
10695 if (is_array($info)) {
10696 if (array_key_exists(
'index', $info) && $info[
'index'] ==
true) {
10719 $queryarray = array();
10720 foreach ($this->fields as $field => $info) {
10722 if ($this->isDate($info)) {
10723 if (empty($this->{$field})) {
10724 $queryarray[$field] =
null;
10726 $queryarray[$field] = $this->db->idate($this->{$field});
10728 } elseif ($this->isDuration($info)) {
10730 if ((isset($this->{$field}) && $this->{$field} !=
'') || !empty($info[
'notnull'])) {
10731 if (!isset($this->{$field})) {
10732 if (!empty($info[
'default'])) {
10733 $queryarray[$field] = $info[
'default'];
10735 $queryarray[$field] = 0;
10738 $queryarray[$field] = (int) $this->{$field};
10741 $queryarray[$field] =
null;
10743 } elseif ($this->isInt($info) || $this->isFloat($info)) {
10744 if ($field ==
'entity' && is_null($this->{$field})) {
10745 $queryarray[$field] = ((int)
$conf->entity);
10748 if ((isset($this->{$field}) && ((
string) $this->{$field}) !=
'') || !empty($info[
'notnull'])) {
10749 if (!isset($this->{$field})) {
10750 $queryarray[$field] = 0;
10751 } elseif ($this->isInt($info)) {
10752 $queryarray[$field] = (int) $this->{$field};
10753 } elseif ($this->isFloat($info)) {
10754 $queryarray[$field] = (float) $this->{$field};
10757 $queryarray[$field] =
null;
10763 $queryarray[$field] = $this->{$field};
10766 if (is_array($info) && array_key_exists(
'type', $info) && !empty($info[
'type']) && $info[
'type'] ==
'timestamp' && empty($queryarray[$field])) {
10767 unset($queryarray[$field]);
10769 if (!empty($info[
'notnull']) && $info[
'notnull'] == -1 && empty($queryarray[$field])) {
10770 $queryarray[$field] =
null;
10774 return $queryarray;
10787 foreach ($this->fields as $field => $info) {
10788 if ($this->isDate($info)) {
10789 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') {
10790 $this->$field =
'';
10792 $this->$field =
$db->jdate($obj->$field);
10794 } elseif ($this->isInt($info)) {
10795 if ($field ==
'rowid') {
10796 $this->
id = (int) $obj->$field;
10798 if ($this->isForcedToNullIfZero($info)) {
10799 if (empty($obj->$field)) {
10800 $this->$field =
null;
10802 $this->$field = (int) $obj->$field;
10805 if (isset($obj->$field) && (!is_null($obj->$field) || (array_key_exists(
'notnull', $info) && $info[
'notnull'] == 1))) {
10806 $this->$field = (int) $obj->$field;
10808 $this->$field =
null;
10812 } elseif ($this->isFloat($info)) {
10813 if ($this->isForcedToNullIfZero($info)) {
10814 if (empty($obj->$field)) {
10815 $this->$field =
null;
10817 $this->$field = (float) $obj->$field;
10820 if (isset($obj->$field) && (!is_null($obj->$field) || (array_key_exists(
'notnull', $info) && $info[
'notnull'] == 1))) {
10821 $this->$field = (float) $obj->$field;
10823 $this->$field =
null;
10827 $this->$field = isset($obj->$field) ? $obj->$field :
null;
10832 if (!isset($this->fields[
'ref']) && isset($this->
id)) {
10843 foreach ($this->fields as $field => $arr) {
10844 $this->$field =
null;
10857 $keys = array_keys($this->fields);
10858 if (!empty($alias)) {
10859 $keys_with_alias = array();
10860 foreach ($keys as $fieldname) {
10861 if (!empty($excludefields)) {
10862 if (in_array($fieldname, $excludefields)) {
10866 $keys_with_alias[] = $this->db->sanitize($alias .
'.' . $fieldname);
10868 return implode(
', ', $keys_with_alias);
10870 return implode(
', ', $keys);
10881 protected function quote($value, $fieldsentry)
10883 if (is_null($value)) {
10885 } elseif (preg_match(
'/^(int|double|real|price)/i', $fieldsentry[
'type'])) {
10887 } elseif (preg_match(
'/int$/i', $fieldsentry[
'type'])) {
10888 return (
int) $value;
10889 } elseif ($fieldsentry[
'type'] ==
'boolean') {
10896 return "'".$this->db->escape($value).
"'";
10913 dol_syslog(get_class($this).
"::createCommon create", LOG_DEBUG);
10919 $fieldvalues = $this->setSaveQuery();
10923 if (array_key_exists(
'date_creation', $fieldvalues) && empty($fieldvalues[
'date_creation'])) {
10924 $fieldvalues[
'date_creation'] = $this->db->idate($now);
10925 $this->date_creation = $now;
10928 if (array_key_exists(
'fk_user_creat', $fieldvalues) && !($fieldvalues[
'fk_user_creat'] > 0)) {
10929 $fieldvalues[
'fk_user_creat'] = $user->id;
10930 $this->fk_user_creat = $user->id;
10932 if (array_key_exists(
'user_creation_id', $fieldvalues) && !($fieldvalues[
'user_creation_id'] > 0)) {
10933 $fieldvalues[
'user_creation_id'] = $user->id;
10934 $this->user_creation_id = $user->id;
10936 if (array_key_exists(
'pass_crypted', $fieldvalues) && property_exists($this,
'pass')) {
10938 $tmparray =
dol_hash($this->pass,
'0', 0, 1);
10939 $fieldvalues[
'pass_crypted'] = $tmparray[
'pass_encrypted'];
10940 if (array_key_exists(
'pass_encoding', $fieldvalues) && property_exists($this,
'pass_encoding')) {
10941 $fieldvalues[
'pass_encoding'] = $tmparray[
'pass_encoding'];
10944 if (array_key_exists(
'ref', $fieldvalues)) {
10947 if (
getDolGlobalString(
'MAIN_DISABLE_AUTO_UPDATE_OF_TMS_FIELDS') && array_key_exists(
'tms', $fieldvalues)) {
10948 $fieldvalues[
'tms'] = $this->db->idate($now);
10951 unset($fieldvalues[
'rowid']);
10953 $sanitized_keys = array();
10954 $sanitized_values = array();
10955 foreach ($fieldvalues as $k => $v) {
10956 $sanitized_keys[$k] = $k;
10957 $value = $this->fields[$k];
10959 $sanitized_values[$k] = $this->quote($v, $value);
10963 foreach ($sanitized_keys as $key) {
10964 if (!isset($this->fields[$key])) {
10967 $key_fields = $this->fields[$key];
10970 if (preg_match(
'/^integer:/i', $key_fields[
'type']) && $sanitized_values[$key] ==
'-1') {
10971 $sanitized_values[$key] =
'';
10973 if (!empty($key_fields[
'foreignkey']) && $sanitized_values[$key] ==
'-1') {
10974 $sanitized_values[$key] =
'';
10977 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']))) {
10980 if (empty($langs)) {
10981 require_once DOL_DOCUMENT_ROOT.
'/core/class/translate.class.php';
10983 $langs->setDefaultLang();
10984 $langs->load(
"errors");
10986 dol_syslog(
"Mandatory field '".$key.
"' is empty and required into ->fields definition of class");
10987 $this->errors[] = $langs->trans(
"ErrorFieldRequired", isset($key_fields[
'label']) ? $key_fields[
'label'] : $key);
10991 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'])) {
10992 $sanitized_values[$key] = $this->quote($key_fields[
'default'], $key_fields);
10996 if (isset($key_fields[
'type']) && preg_match(
'/^integer:/i', $key_fields[
'type']) && empty($sanitized_values[$key])) {
10997 if (isset($key_fields[
'default'])) {
10998 $sanitized_values[$key] = ((int) $key_fields[
'default']);
11000 $sanitized_values[$key] =
'null';
11003 if (!empty($key_fields[
'foreignkey']) && empty($sanitized_values[$key])) {
11004 $sanitized_values[$key] =
'null';
11012 $this->db->begin();
11015 $sql =
"INSERT INTO ".$this->db->prefix().$this->db->sanitize($this->table_element);
11016 $sql .=
" (".implode(
", ", $sanitized_keys).
')';
11017 $sql .=
" VALUES (".implode(
", ", $sanitized_values).
")";
11019 $res = $this->db->query($sql);
11022 if ($this->db->lasterrno() ==
'DB_ERROR_RECORD_ALREADY_EXISTS') {
11023 $this->errors[] =
"ErrorRefAlreadyExists";
11025 $this->errors[] = $this->db->lasterror();
11031 $this->
id = $this->db->last_insert_id($this->db->prefix().$this->table_element);
11037 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)') {
11038 $sql =
"UPDATE ".$this->db->prefix().$this->db->sanitize($this->table_element);
11039 $sql .=
" SET ref = '(PROV".((int) $this->
id).
")' WHERE (ref = '(PROV)' OR ref = '') AND rowid = ".((int) $this->
id);
11040 $resqlupdate = $this->db->query($sql);
11042 if ($resqlupdate ===
false) {
11044 $this->errors[] = $this->db->lasterror();
11046 $this->
ref =
'(PROV'.$this->id.
')';
11053 $result = $this->insertExtraFields();
11060 if (!empty($this->table_element_line) && !empty($this->fk_element) && !empty($this->lines)) {
11061 foreach ($this->lines as $line) {
11062 $keyforparent = $this->fk_element;
11067 if (!is_object($line)) {
11068 $line = (object) $line;
11072 if (method_exists($line,
'insert')) {
11073 $result = $line->insert($user, 1);
11074 } elseif (method_exists($line,
'create')) {
11075 $result = $line->create($user, 1);
11078 $this->error = $line->error;
11079 $this->db->rollback();
11086 if (!$error && !$notrigger) {
11088 $result = $this->call_trigger(strtoupper(get_class($this)).
'_CREATE', $user);
11097 $this->db->rollback();
11100 $this->db->commit();
11117 if (empty(
$id) && empty($ref) && empty($morewhere)) {
11121 $fieldlist = $this->getFieldList(
't');
11122 if (empty($fieldlist)) {
11126 $sql =
"SELECT ".$this->db->sanitize($fieldlist, 0, 0, 1);
11127 $sql .=
" FROM ".$this->db->prefix().$this->table_element.
' as t';
11130 $sql .=
' WHERE t.rowid = '.((int)
$id);
11131 } elseif (!empty($ref)) {
11132 $sql .=
" WHERE t.ref = '".$this->db->escape($ref).
"'";
11134 $sql .=
' WHERE 1 = 1';
11136 if (empty(
$id) && isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
11137 $sql .=
' AND t.entity IN ('.getEntity($this->element).
')';
11140 $sql .= $morewhere;
11142 $sql .=
' LIMIT 1';
11144 $res = $this->db->query($sql);
11146 $obj = $this->db->fetch_object($res);
11148 $this->setVarsFromFetchObj($obj);
11152 if (empty($noextrafields)) {
11153 $result = $this->fetch_optionals();
11155 $this->error = $this->db->lasterror();
11156 $this->errors[] = $this->error;
11166 $this->error = $this->db->lasterror();
11167 $this->errors[] = $this->error;
11181 $objectlineclassname = get_class($this).
'Line';
11182 if (!class_exists($objectlineclassname)) {
11183 $this->error =
'Error, class '.$objectlineclassname.
' not found during call of fetchLinesCommon';
11187 $objectline =
new $objectlineclassname($this->db);
11188 '@phan-var-force CommonObjectLine $objectline';
11190 $sql =
"SELECT ".$objectline->getFieldList(
'l');
11191 $sql .=
" FROM ".$this->db->prefix().$this->db->sanitize($objectline->table_element).
" as l";
11192 $sql .=
" WHERE l.fk_".$this->db->sanitize($this->element).
" = ".((int) $this->
id);
11194 $sql .= $morewhere;
11196 if (isset($objectline->fields[
'position'])) {
11197 $sql .= $this->db->order(
'position',
'ASC');
11200 $resql = $this->db->query($sql);
11202 $num_rows = $this->db->num_rows($resql);
11204 $this->lines = array();
11205 while ($i < $num_rows) {
11206 $obj = $this->db->fetch_object($resql);
11208 $newline =
new $objectlineclassname($this->db);
11209 '@phan-var-force CommonObjectLine $newline';
11210 $newline->setVarsFromFetchObj($obj);
11213 if (empty($noextrafields)) {
11214 $newline->fetch_optionals();
11217 $this->lines[] = $newline;
11224 $this->error = $this->db->lasterror();
11225 $this->errors[] = $this->error;
11239 dol_syslog(get_class($this).
"::updateCommon update", LOG_DEBUG);
11251 $fieldvalues = $this->setSaveQuery();
11255 if (array_key_exists(
'date_modification', $fieldvalues)) {
11256 $fieldvalues[
'date_modification'] = $this->db->idate($now);
11258 if (
getDolGlobalString(
'MAIN_DISABLE_AUTO_UPDATE_OF_TMS_FIELDS') && array_key_exists(
'tms', $fieldvalues)) {
11259 $fieldvalues[
'tms'] = $this->db->idate($now);
11261 if (array_key_exists(
'fk_user_modif', $fieldvalues)) {
11262 $fieldvalues[
'fk_user_modif'] = $user->id;
11264 if (array_key_exists(
'user_modification_id', $fieldvalues)) {
11265 $fieldvalues[
'user_modification_id'] = $user->id;
11268 if (array_key_exists(
'pass_crypted', $fieldvalues) && property_exists($this,
'pass') && !empty($this->pass)) {
11270 $tmparray =
dol_hash($this->pass,
'0', 0, 1);
11271 $fieldvalues[
'pass_crypted'] = $tmparray[
'pass_encrypted'];
11272 if (array_key_exists(
'pass_encoding', $fieldvalues) && property_exists($this,
'pass_encoding')) {
11273 $fieldvalues[
'pass_encoding'] = $tmparray[
'pass_encoding'];
11276 if (array_key_exists(
'ref', $fieldvalues)) {
11280 unset($fieldvalues[
'rowid']);
11285 $sanitized_tmp = array();
11286 foreach ($fieldvalues as $k => $v) {
11288 $value = $this->fields[$k];
11290 $values[$k] = $this->quote($v, $value);
11291 if ((!empty($value[
"type"]) && $value[
"type"] ==
"text") && !empty($value[
'arrayofkeyval']) && is_array($value[
'arrayofkeyval'])) {
11293 $v = preg_replace(
'/\s/',
',', $v);
11294 $v = preg_replace(
'/,+/',
',', $v);
11297 $sanitized_tmp[] = $this->db->sanitize($k).
'='.$this->quote($v, $this->fields[$k]);
11301 foreach ($keys as $key) {
11302 if (!empty($this->fields[$key][
'type']) && preg_match(
'/^integer:/i', $this->fields[$key][
'type']) && $values[$key] ==
'-1') {
11303 $values[$key] =
'';
11305 if (!empty($this->fields[$key][
'foreignkey']) && $values[$key] ==
'-1') {
11306 $values[$key] =
'';
11318 $sql =
"UPDATE ".$this->db->prefix().$this->db->sanitize($this->table_element);
11319 $sql.=
" SET ".implode(
', ', $sanitized_tmp);
11320 $sql.=
" WHERE rowid = ".((int) $this->
id);
11322 $this->db->begin();
11325 $res = $this->db->query($sql);
11328 $this->errors[] = $this->db->lasterror();
11334 $result = $this->insertExtraFields();
11341 if (!$error && !$notrigger) {
11343 $result = $this->call_trigger(strtoupper(get_class($this)).
'_MODIFY', $user);
11352 $this->db->rollback();
11355 $this->db->commit();
11370 dol_syslog(get_class($this).
"::deleteCommon delete", LOG_DEBUG);
11374 $this->db->begin();
11376 if ($forcechilddeletion) {
11377 foreach ($this->childtables as $table) {
11378 $sql =
"DELETE FROM ".$this->db->prefix().$this->db->sanitize($table);
11379 $sql .=
" WHERE ".$this->db->sanitize($this->fk_element).
" = ".((int) $this->
id);
11380 $resql = $this->db->query($sql);
11382 $this->error = $this->db->lasterror();
11383 $this->errors[] = $this->error;
11384 $this->db->rollback();
11388 } elseif (!empty($this->childtables)) {
11389 $objectisused = $this->isObjectUsed($this->
id);
11390 if (!empty($objectisused)) {
11391 dol_syslog(get_class($this).
"::deleteCommon Can't delete record as it has some child", LOG_WARNING);
11392 $this->error =
'ErrorRecordHasChildren';
11393 $this->errors[] = $this->error;
11394 $this->db->rollback();
11400 if (is_array($this->childtablesoncascade) && !empty($this->childtablesoncascade)) {
11401 foreach ($this->childtablesoncascade as $tabletodelete) {
11402 $deleteFromObject = explode(
':', $tabletodelete, 4);
11403 if (count($deleteFromObject) >= 2) {
11404 $className = str_replace(
'@',
'', $deleteFromObject[0]);
11405 $filePath = $deleteFromObject[1];
11406 $columnName = $deleteFromObject[2];
11408 if (!empty($deleteFromObject[3])) {
11409 $filter = $deleteFromObject[3];
11413 $childObject =
new $className($this->db);
11414 if (method_exists($childObject,
'deleteByParentField')) {
11415 '@phan-var-force CommonObject $childObject';
11416 $result = $childObject->deleteByParentField($this->
id, $columnName, $filter);
11419 $this->errors[] = $childObject->error;
11424 $this->errors[] =
"You defined a cascade delete on an object $className/$this->id but there is no method deleteByParentField for it";
11429 $this->errors[] =
'Cannot include child class file '.$filePath;
11434 $sql =
"DELETE FROM ".$this->db->prefix().$this->db->sanitize($tabletodelete).
" WHERE ".$this->db->sanitize($this->fk_element).
" = ".((int) $this->
id);
11436 $resql = $this->db->query($sql);
11439 $this->error = $this->db->lasterror();
11440 $this->errors[] = $this->error;
11450 $result = $this->call_trigger(strtoupper(get_class($this)).
'_DELETE', $user);
11460 $res = $this->deleteEcmFiles(1);
11469 require_once DOL_DOCUMENT_ROOT .
'/core/lib/files.lib.php';
11472 $this->errors[] =
'ErrorFailToDeleteDir';
11478 $res = $this->deleteObjectLinked();
11483 if (!$error && !empty($this->isextrafieldmanaged)) {
11484 $result = $this->deleteExtraFields();
11491 $sql =
"DELETE FROM ".$this->db->prefix().$this->db->sanitize($this->table_element);
11492 $sql .=
" WHERE rowid = ".((int) $this->
id);
11494 $resql = $this->db->query($sql);
11497 $this->errors[] = $this->db->lasterror();
11503 $this->db->rollback();
11506 $this->db->commit();
11531 if (!empty($parentId) && !empty($parentField)) {
11532 if (empty($this->table_element)) {
11533 $this->error =
'Property table_element for object is not defined';
11534 $this->errors[] = $this->error;
11538 if (!method_exists($this,
'fetch')) {
11539 $this->error =
'Method fetch for object is not defined';
11540 $this->errors[] = $this->error;
11544 if (!method_exists($this,
'delete')) {
11545 $this->error =
'Method delete for object is not defined';
11546 $this->errors[] = $this->error;
11551 $this->db->begin();
11553 $sql =
"SELECT rowid FROM ".$this->db->prefix().$this->db->sanitize($this->table_element);
11554 $sql .=
" WHERE ".$this->db->sanitize($parentField).
" = ".(int) $parentId;
11557 $errormessage =
'';
11559 if ($errormessage) {
11560 $this->errors[] = $errormessage;
11561 dol_syslog(__METHOD__.
' '.implode(
',', $this->errors), LOG_ERR);
11565 $resql = $this->db->query($sql);
11567 $this->errors[] = $this->db->lasterror();
11570 while ($obj = $this->db->fetch_object($resql)) {
11571 $result = $this->fetch($obj->rowid);
11574 $this->errors[] = $this->error;
11576 $result = $this->
delete($user);
11579 $this->errors[] = $this->error;
11587 if (empty($error)) {
11588 $this->db->commit();
11591 $this->error = implode(
', ', $this->errors);
11592 $this->db->rollback();
11593 return $error * -1;
11609 if (!($this->
id > 0) || empty($this->table_element_line) || empty($this->fk_element)) {
11613 $sql =
"SELECT rowid FROM ".$this->db->prefix().$this->db->sanitize($this->table_element_line);
11614 $sql .=
" WHERE rowid = ".((int) $lineid).
" AND ".$this->db->sanitize($this->fk_element).
" = ".((int) $this->
id);
11615 $resql = $this->db->query($sql);
11617 return ($resql && $this->db->num_rows($resql) > 0);
11632 $tmpforobjectclass = get_class($this);
11633 $tmpforobjectlineclass = ucfirst($tmpforobjectclass).
'Line';
11635 if ($this->
id > 0 && !empty($this->fk_element)) {
11637 $sql =
"SELECT rowid FROM ".$this->db->prefix().$this->table_element_line;
11638 $sql .=
" WHERE rowid = ".((int) $idline).
" AND ".$this->db->sanitize($this->fk_element).
" = ".((int) $this->
id);
11639 $resql = $this->db->query($sql);
11640 if (!$resql || !$this->db->num_rows($resql)) {
11641 $this->error =
'ErrorLineIDDoesNotMatchWithObjectID';
11646 $this->db->begin();
11649 $result = $this->call_trigger(
'LINE'.strtoupper($tmpforobjectclass).
'_DELETE', $user);
11655 if (empty($error)) {
11656 $sql =
"DELETE FROM ".$this->db->prefix().$this->db->sanitize($this->table_element_line);
11657 $sql .=
" WHERE rowid = ".((int) $idline);
11659 $resql = $this->db->query($sql);
11661 $this->error =
"Error ".$this->db->lasterror();
11666 if (empty($error)) {
11668 $tmpobjectline =
new $tmpforobjectlineclass($this->db);
11669 '@phan-var-force CommonObjectLine $tmpobjectline';
11670 if (!isset($tmpobjectline->isextrafieldmanaged) || !empty($tmpobjectline->isextrafieldmanaged)) {
11671 $tmpobjectline->id = $idline;
11672 $result = $tmpobjectline->deleteExtraFields();
11675 $this->error =
"Error ".get_class($this).
"::deleteLineCommon deleteExtraFields error -4 ".$tmpobjectline->error;
11680 if (empty($error)) {
11681 $this->db->commit();
11684 dol_syslog(get_class($this).
"::deleteLineCommon ERROR:".$this->error, LOG_ERR);
11685 $this->db->rollback();
11705 $this->db->begin();
11707 $statusfield =
'status';
11708 if (in_array($this->element, array(
'don',
'donation',
'shipping',
'project_task'))) {
11709 $statusfield =
'fk_statut';
11712 $sql =
"UPDATE ".$this->db->prefix().$this->db->sanitize($this->table_element);
11713 $sql .=
" SET ".$this->db->sanitize($statusfield).
" = ".((int) $status);
11714 $sql .=
" WHERE rowid = ".((int) $this->
id);
11716 if ($this->db->query($sql)) {
11718 $this->oldcopy = clone $this;
11721 if (!$error && !$notrigger) {
11723 $result = $this->call_trigger($triggercode, $user);
11730 $this->
status = $status;
11731 if (property_exists($this,
'statut')) {
11732 $this->statut = $status;
11734 $this->db->commit();
11737 $this->db->rollback();
11741 $this->error = $this->db->error();
11742 $this->db->rollback();
11758 $this->specimen = 1;
11760 'label' =>
'This is label',
11761 'ref' =>
'ABCD1234',
11762 'description' =>
'This is a description',
11764 'note_public' =>
'Public note',
11765 'note_private' =>
'Private note',
11766 'date_creation' => (
dol_now() - 3600 * 48),
11767 'date_modification' => (
dol_now() - 3600 * 24),
11768 'fk_user_creat' => $user->id,
11769 'fk_user_modif' => $user->id,
11772 foreach ($fields as $key => $value) {
11773 if (array_key_exists($key, $this->fields)) {
11774 $this->{$key} = $value;
11779 if (property_exists($this,
'fields')) {
11780 foreach ($this->fields as $key => $value) {
11782 if (array_key_exists($key, $fields)) {
11786 if (!empty($value[
'default'])) {
11787 $this->$key = $value[
'default'];
11805 require_once DOL_DOCUMENT_ROOT.
'/core/class/comment.class.php';
11807 $comment =
new Comment($this->db);
11808 $result = $comment->fetchAllFor($this->element, $this->
id);
11810 $this->setErrorsFromObject($comment);
11813 $this->comments = $comment->comments;
11815 return count($this->comments);
11825 return count($this->comments);
11836 if (!is_array($parameters)) {
11839 foreach ($parameters as $parameter) {
11840 if (isset($this->$parameter)) {
11841 $this->$parameter = trim($this->$parameter);
11860 require_once DOL_DOCUMENT_ROOT.
'/categories/class/categorie.class.php';
11864 $existing =
$c->containing($this->
id, $type_categ,
'id');
11884 if (!is_array($categories)) {
11885 $categories = array($categories);
11888 dol_syslog(get_class($this).
"::setCategoriesCommon Object Id:".$this->
id.
' type_categ:'.$type_categ.
' nb tag add:'.count($categories), LOG_DEBUG);
11890 require_once DOL_DOCUMENT_ROOT.
'/categories/class/categorie.class.php';
11892 if (empty($type_categ)) {
11893 dol_syslog(__METHOD__.
': Type '.$type_categ.
'is an unknown category type. Done nothing.', LOG_ERR);
11899 $existing =
$c->containing($this->
id, $type_categ,
'id');
11902 if (!is_array($existing)) {
11903 $existing = array();
11905 if ($remove_existing) {
11907 $to_del = array_diff($existing, $categories);
11908 $to_add = array_diff($categories, $existing);
11911 $to_add = array_diff($categories, $existing);
11918 foreach ($to_del as $del) {
11919 if (
$c->fetch($del) > 0) {
11920 $result =
$c->del_type($this, $type_categ);
11923 $this->error =
$c->error;
11924 $this->errors =
$c->errors;
11931 foreach ($to_add as $add) {
11932 if (
$c->fetch($add) > 0) {
11933 $result =
$c->add_type($this, $type_categ);
11936 $this->error =
$c->error;
11937 $this->errors =
$c->errors;
11945 return $error ? (-1 * $error) : $ok;
11958 $this->db->begin();
11960 if (empty($type)) {
11961 $type = $this->table_element;
11964 require_once DOL_DOCUMENT_ROOT.
'/categories/class/categorie.class.php';
11965 $categorystatic =
new Categorie($this->db);
11967 $tablename = $this->db->prefix().
"categorie_".(empty($categorystatic->MAP_CAT_TABLE[$type]) ? $type : $categorystatic->MAP_CAT_TABLE[$type]);
11968 $fkname =
'fk_' . (empty($categorystatic->MAP_CAT_FK[$type]) ? $type : $categorystatic->MAP_CAT_FK[$type]);
11970 $sql =
"INSERT INTO ".$this->db->sanitize($tablename).
" (fk_categorie, ".$this->db->sanitize($fkname).
")";
11971 $sql .=
" SELECT fk_categorie, ".((int) $toId).
" FROM ".$this->db->sanitize($tablename);
11972 $sql .=
" WHERE ".$this->db->sanitize($fkname).
" = ".((int) $fromId);
11974 if (!$this->db->query($sql)) {
11975 $this->error = $this->db->lasterror();
11976 $this->db->rollback();
11980 $this->db->commit();
11994 $this->db->begin();
11998 switch ($this->element) {
12000 $element =
'propale';
12003 $element =
'produit';
12005 case 'order_supplier':
12006 $element =
'fournisseur/commande';
12008 case 'invoice_supplier':
12011 $element =
'fournisseur/facture/'.get_exdir($this->
id, 2, 0, 1, $this,
'invoice_supplier');
12014 $element =
'expedition/sending';
12017 case 'project_task':
12018 require_once DOL_DOCUMENT_ROOT.
'/projet/class/task.class.php';
12020 $project_result = $this->fetchProject();
12021 if ($project_result >= 0) {
12022 $element =
'projet/'.dol_sanitizeFileName($this->project->ref).
'/';
12026 $element =
'contract';
12029 $element = $this->element;
12031 '@phan-var-force string $element';
12034 $sql =
"DELETE FROM ".$this->db->prefix().
"ecm_files_extrafields WHERE fk_object IN (";
12035 $sql .=
" SELECT rowid FROM ".$this->db->prefix().
"ecm_files WHERE filename LIKE '".$this->db->escape($this->
ref).
"%'";
12036 $sql .=
" AND filepath = '".$this->db->escape($element.
"/".$this->ref).
"' AND entity = ".((int)
$conf->entity);
12039 if (!$this->db->query($sql)) {
12040 $this->error = $this->db->lasterror();
12041 $this->db->rollback();
12046 $sql =
"DELETE FROM ".$this->db->prefix().
"ecm_files";
12047 $sql .=
" WHERE filename LIKE '".$this->db->escape($this->
ref).
"%'";
12048 $sql .=
" AND filepath = '".$this->db->escape($element.
"/".$this->ref).
"' AND entity = ".((int)
$conf->entity);
12050 if (!$this->db->query($sql)) {
12051 $this->error = $this->db->lasterror();
12052 $this->db->rollback();
12059 $sql =
'DELETE FROM '.$this->db->prefix().
"ecm_files_extrafields";
12060 $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).
")";
12061 $resql = $this->db->query($sql);
12063 $this->error = $this->db->lasterror();
12064 $this->db->rollback();
12068 $sql =
'DELETE FROM '.$this->db->prefix().
"ecm_files";
12069 $sql .=
" WHERE src_object_type = '".$this->db->escape($this->table_element.(empty($this->module) ?
"" :
"@".$this->module)).
"' AND src_object_id = ".((int) $this->
id);
12070 $resql = $this->db->query($sql);
12072 $this->error = $this->db->lasterror();
12073 $this->db->rollback();
12078 $this->db->commit();
12095 include_once DOL_DOCUMENT_ROOT.
'/product/class/product.class.php';
12098 $tmpproduct =
new Product($this->db);
12099 foreach ($this->lines as $line) {
12100 if ($line->fk_product > 0) {
12101 $tmpproduct->fetch($line->fk_product);
12102 $statustotest = ($status ==
'onsale' ?
'status' :
'status_buy');
12103 if (!$tmpproduct->$statustotest) {
12104 $langs->load(
'products');
12105 $statuskey4lang = ($status ==
'onsale' ?
'ProductStatusNotOnSell' :
'ProductStatusNotOnBuy');
12107 $this->errors[] = $langs->trans(
'ProductRef').
' '.$tmpproduct->ref.
' '.$langs->trans($statuskey4lang);
12113 $this->error =
'ErrorOneLineContainsADisactivatedProduct';
12129 $this->error = $message;
12130 $this->errors[] = $message;
12142 global $dolibarr_main_document_root;
12144 $this->setErrorWithoutLog($message);
12145 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
12146 $file = str_replace($dolibarr_main_document_root,
'', $trace[0][
'file'] ??
'file unknown');
12147 $line = $trace[0][
'line'] ??
'line unknown';
12148 $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.