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();
237 public $fields = array();
244 public $array_languages =
null;
249 public $contacts_ids;
254 public $contacts_ids_internal;
259 public $linked_objects;
264 public $linkedObjectsIds;
269 public $linkedObjects;
274 private $linkedObjectsFullLoaded = array();
289 protected $table_ref_field =
'';
294 public $restrictiononfksoc = 0;
303 public $context = array();
414 private $commandeFournisseur;
430 public $ref_previous;
476 public $country_code;
519 public $barcode_type;
525 public $barcode_type_code;
531 public $barcode_type_label;
537 public $barcode_type_coder;
543 public $mode_reglement_id;
549 public $cond_reglement_id;
554 public $demand_reason_id;
560 public $transport_mode_id;
569 private $cond_reglement;
573 protected $depr_cond_reglement;
580 public $fk_delivery_address;
586 public $shipping_method_id;
592 public $shipping_method;
598 public $fk_multicurrency;
604 public $multicurrency_code;
610 public $multicurrency_tx;
615 public $multicurrency_total_ht;
620 public $multicurrency_total_tva;
625 public $multicurrency_total_localtax1;
630 public $multicurrency_total_localtax2;
635 public $multicurrency_total_ttc;
648 public $last_main_doc;
673 public $note_private;
698 public $total_localtax1;
704 public $total_localtax2;
721 public $actiontypecode;
727 public $comments = array();
753 public $civility_code;
759 public $date_creation;
764 public $date_validation;
769 public $date_modification;
783 private $date_update;
788 public $date_cloture;
793 public $user_creation_id;
798 public $user_validation_id;
803 public $user_closing_id;
808 public $user_modification_id;
814 public $fk_user_creat;
820 public $fk_user_modif;
826 public $next_prev_filter;
831 public $specimen = 0;
855 public $totalpaid_multicurrency;
861 public $labelStatus = array();
866 public $labelStatusShort = array();
877 public $showphoto_on_popup;
882 public $nb = array();
897 public $extraparams = array();
902 protected $childtables = array();
909 protected $childtablesoncascade = array();
914 public $cond_reglement_supplier_id;
921 public $deposit_percent;
927 public $warehouse_id;
932 public $isextrafieldmanaged = 0;
945 'alreadypaid' =>
'totalpaid',
946 'cond_reglement' =>
'depr_cond_reglement',
948 'commandeFournisseur' =>
'origin_object',
949 'expedition' =>
'origin_object',
950 'fk_project' =>
'fk_project',
951 'livraison' =>
'origin_object',
952 'projet' =>
'project',
953 'statut' =>
'status',
972 $sql =
"SELECT rowid";
973 $sql .=
" FROM ".$db->prefix().$element;
974 $sql .=
" WHERE entity IN (".getEntity($element).
")";
977 $sql .=
" AND rowid = ".((int) $id);
979 $sql .=
" AND ref = '".$db->escape($ref).
"'";
980 } elseif ($ref_ext) {
981 $sql .=
" AND ref_ext = '".$db->escape($ref_ext).
"'";
983 $error =
'ErrorWrongParameters';
984 dol_syslog(get_class().
"::isExistingObject ".$error, LOG_ERR);
987 if ($ref || $ref_ext) {
988 $sql .=
" AND entity = ".((int)
$conf->entity);
991 dol_syslog(get_class().
"::isExistingObject", LOG_DEBUG);
992 $resql =
$db->query($sql);
994 $num =
$db->num_rows($resql);
1011 return (empty($this->
id));
1023 $this->error =
$object->error;
1025 if (!empty(
$object->errors)) {
1026 $this->errors = array_merge($this->errors,
$object->errors);
1051 global $action, $extrafields, $langs, $hookmanager;
1054 $MAX_EXTRAFIELDS_TO_SHOW_IN_TOOLTIP =
getDolGlobalInt(
'MAX_EXTRAFIELDS_TO_SHOW_IN_TOOLTIP', 3);
1060 if (!empty($extrafields->attributes[$this->table_element][
'label'])) {
1061 $data[
'opendivextra'] =
'<div class="centpercent wordbreak divtooltipextra">';
1062 foreach ($extrafields->attributes[$this->table_element][
'label'] as $key => $val) {
1063 if ($extrafields->attributes[$this->table_element][
'type'][$key] ==
'separate') {
1067 if (empty($extrafields->attributes[$this->table_element][
'showintooltip'][$key])) {
1072 if ($count >= abs($MAX_EXTRAFIELDS_TO_SHOW_IN_TOOLTIP)) {
1073 $data[
'more_extrafields'] =
'<br>...';
1077 if ($enabled && isset($extrafields->attributes[$this->table_element][
'enabled'][$key])) {
1078 $enabled = (int)
dol_eval((
string) $extrafields->attributes[$this->table_element][
'enabled'][$key], 1, 1,
'2');
1080 if ($enabled && isset($extrafields->attributes[$this->table_element][
'list'][$key])) {
1081 $enabled = (int)
dol_eval((
string) $extrafields->attributes[$this->table_element][
'list'][$key], 1, 1,
'2');
1084 if ($perms && isset($extrafields->attributes[$this->table_element][
'perms'][$key])) {
1085 $perms = (int)
dol_eval((
string) $extrafields->attributes[$this->table_element][
'perms'][$key], 1, 1,
'2');
1087 if (empty($enabled)) {
1090 if (abs($enabled) != 1 && abs($enabled) != 3 && abs($enabled) != 5 && abs($enabled) != 4) {
1093 if (empty($perms)) {
1096 if (!empty($extrafields->attributes[$this->table_element][
'langfile'][$key])) {
1097 $langs->load($extrafields->attributes[$this->table_element][
'langfile'][$key]);
1099 $labelextra = $langs->trans((
string) $extrafields->attributes[$this->table_element][
'label'][$key]);
1100 if ($extrafields->attributes[$this->table_element][
'type'][$key] ==
'separate') {
1101 $data[$key] =
'<br><b><u>'. $labelextra .
'</u></b>';
1103 $value = (empty($this->array_options[
'options_' . $key]) ?
'' : $this->array_options[
'options_' . $key]);
1104 $data[$key] =
'<br><b>'. $labelextra .
':</b> ' . $extrafields->showOutputField($key, $value,
'', $this->table_element);
1108 $data[
'closedivextra'] =
'</div>';
1111 $hookmanager->initHooks(array($this->element .
'dao'));
1112 $parameters = array(
1113 'tooltipcontentarray' => &$data,
1114 'params' => $params,
1117 $hookmanager->executeHooks(
'getTooltipContent', $parameters, $this, $action);
1120 $label = implode($data);
1133 return $this->error.(is_array($this->errors) ? (($this->error !=
'' ?
', ' :
'').implode(
', ', $this->errors)) :
'');
1145 global $hookmanager;
1147 $parameters = array(
'objref' => $objref);
1149 $reshook = $hookmanager->executeHooks(
'getFormatedCustomerRef', $parameters, $this, $action);
1151 return $hookmanager->resArray[
'objref'];
1153 return $objref.(isset($hookmanager->resArray[
'objref']) ? $hookmanager->resArray[
'objref'] :
'');
1164 global $hookmanager;
1166 $parameters = array(
'objref' => $objref);
1168 $reshook = $hookmanager->executeHooks(
'getFormatedSupplierRef', $parameters, $this, $action);
1170 return $hookmanager->resArray[
'objref'];
1172 return $objref.(isset($hookmanager->resArray[
'objref']) ? $hookmanager->resArray[
'objref'] :
'');
1184 public function getFullAddress($withcountry = 0, $sep =
"\n", $withregion = 0, $extralangcode =
'')
1186 if ($withcountry && $this->country_id && (empty($this->country_code) || empty($this->country))) {
1187 require_once DOL_DOCUMENT_ROOT.
'/core/lib/company.lib.php';
1188 $tmparray =
getCountry($this->country_id,
'all');
1189 $this->country_code = $tmparray[
'code'];
1190 $this->country = $tmparray[
'label'];
1193 if ($withregion && $this->state_id && (empty($this->state_code) || empty($this->state) || empty($this->region) || empty($this->region_code))) {
1194 require_once DOL_DOCUMENT_ROOT.
'/core/lib/company.lib.php';
1195 $tmparray =
getState($this->state_id,
'all',
null, 1);
1196 $this->state_code = $tmparray[
'code'];
1197 $this->state = $tmparray[
'label'];
1198 $this->region_code = $tmparray[
'region_code'];
1199 $this->region = $tmparray[
'region'];
1218 if (empty($this->last_main_doc)) {
1222 include_once DOL_DOCUMENT_ROOT.
'/ecm/class/ecmfiles.class.php';
1223 $ecmfile =
new EcmFiles($this->db);
1224 $result = $ecmfile->fetch(0,
'', $this->last_main_doc);
1226 $this->error = $ecmfile->error;
1227 $this->errors = $ecmfile->errors;
1231 if (empty($ecmfile->id)) {
1233 if ($initsharekey) {
1234 require_once DOL_DOCUMENT_ROOT.
'/core/lib/security2.lib.php';
1256 } elseif (empty($ecmfile->share)) {
1258 if ($initsharekey) {
1259 require_once DOL_DOCUMENT_ROOT.
'/core/lib/security2.lib.php';
1261 $ecmfile->update($user);
1267 $urlwithouturlroot = preg_replace(
'/'.preg_quote(DOL_URL_ROOT,
'/').
'$/i',
'', trim(
$dolibarr_main_url_root));
1271 $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT;
1280 if (!empty($ecmfile->share)) {
1281 $paramlink .= ($paramlink ?
'&' :
'').
'hashp='.$ecmfile->share;
1283 if ($forcedownload) {
1284 $paramlink .= ($paramlink ?
'&' :
'').
'attachment=1';
1287 if ($relativelink) {
1288 $linktoreturn =
'document.php'.($paramlink ?
'?'.$paramlink :
'');
1290 $linktoreturn = $urlwithroot.
'/document.php'.($paramlink ?
'?'.$paramlink :
'');
1294 return $linktoreturn;
1308 public function add_contact($fk_socpeople, $type_contact, $source =
'external', $notrigger = 0)
1311 global $user, $langs;
1313 dol_syslog(get_class($this).
"::add_contact $fk_socpeople, $type_contact, $source, $notrigger");
1316 if ($fk_socpeople <= 0) {
1317 $langs->load(
"errors");
1318 $this->error = $langs->trans(
"ErrorWrongValueForParameterX",
"1");
1319 dol_syslog(get_class($this).
"::add_contact ".$this->error, LOG_ERR);
1324 $sql_check =
"SELECT rowid FROM ".$this->db->prefix().($source ==
'internal' ?
"user" :
"socpeople").
" WHERE rowid = ".((
int) $fk_socpeople);
1325 $resql_check = $this->db->query($sql_check);
1327 if (!$this->db->num_rows($resql_check)) {
1328 $langs->load(
"errors");
1329 $this->error = $langs->trans(
"ErrorRecordNotFound");
1330 dol_syslog(get_class($this).
"::add_contact Contact/user id ".$fk_socpeople.
" does not exist", LOG_ERR);
1334 $this->error = $this->db->lasterror();
1338 if (!$type_contact) {
1339 $langs->load(
"errors");
1340 $this->error = $langs->trans(
"ErrorWrongValueForParameterX",
"2");
1341 dol_syslog(get_class($this).
"::add_contact ".$this->error, LOG_ERR);
1345 if ($this->restrictiononfksoc && property_exists($this,
'socid') && !empty($this->socid) && $user->id > 0 && !$user->hasRight(
'societe',
'client',
'voir')) {
1346 $sql_allowed_contacts =
'SELECT COUNT(*) as cnt FROM '.$this->db->prefix().
'societe_commerciaux as sc';
1347 $sql_allowed_contacts .=
' WHERE sc.fk_soc = '.(int) $this->socid;
1348 $sql_allowed_contacts .=
' AND sc.fk_user = '.(int) $user->id;
1350 $resql_allowed_contacts = $this->db->query($sql_allowed_contacts);
1352 if (!$resql_allowed_contacts) {
1353 $this->errors[] = $this->db->lasterror();
1355 } elseif ($obj = $this->db->fetch_object($resql_allowed_contacts)) {
1356 if ($obj->cnt == 0) {
1357 $langs->load(
"companies");
1358 $this->error = $langs->trans(
"ErrorCommercialNotAllowedForThirdparty", $user->id);
1359 dol_syslog(get_class($this).
"::add_contact ".$this->error, LOG_ERR);
1365 $id_type_contact = 0;
1366 if (is_numeric($type_contact)) {
1367 $id_type_contact = $type_contact;
1370 $sql =
"SELECT tc.rowid";
1371 $sql .=
" FROM ".$this->db->prefix().
"c_type_contact as tc";
1372 $sql .=
" WHERE tc.element='".$this->db->escape($this->element).
"'";
1373 $sql .=
" AND tc.source='".$this->db->escape($source).
"'";
1374 $sql .=
" AND tc.code='".$this->db->escape($type_contact).
"' AND tc.active=1";
1376 $resql = $this->db->query($sql);
1378 $obj = $this->db->fetch_object($resql);
1380 $id_type_contact = $obj->rowid;
1384 if ($id_type_contact == 0) {
1385 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");
1393 $already_added =
false;
1394 if (is_array($TListeContacts) && !empty($TListeContacts)) {
1395 foreach ($TListeContacts as $array_contact) {
1396 if ($array_contact[
'status'] == 4 && $array_contact[
'id'] == $fk_socpeople && $array_contact[
'fk_c_type_contact'] == $id_type_contact) {
1397 $already_added =
true;
1403 if (!$already_added) {
1407 $sql =
"INSERT INTO ".$this->db->prefix().
"element_contact";
1408 $sql .=
" (element_id, fk_socpeople, datecreate, statut, fk_c_type_contact) ";
1409 $sql .=
" VALUES (".((int) $this->
id).
", ".((int) $fk_socpeople).
" , ";
1410 $sql .=
"'".$this->db->idate($datecreate).
"'";
1411 $sql .=
", 4, ".((int) $id_type_contact);
1414 $resql = $this->db->query($sql);
1417 $triggerPrefix = (empty($this->TRIGGER_PREFIX) ? strtoupper($this->element) : $this->TRIGGER_PREFIX);
1418 $result = $this->call_trigger($triggerPrefix.
'_ADD_CONTACT', $user);
1420 $this->db->rollback();
1425 $this->db->commit();
1428 if ($this->db->errno() ==
'DB_ERROR_RECORD_ALREADY_EXISTS') {
1429 $this->error = $this->db->errno();
1430 $this->db->rollback();
1433 $this->error = $this->db->lasterror();
1434 $this->db->rollback();
1454 $contacts = $objFrom->liste_contact(-1, $source);
1455 foreach ($contacts as $contact) {
1456 if ($this->
add_contact($contact[
'id'], $contact[
'fk_c_type_contact'], $contact[
'source']) < 0) {
1473 public function update_contact($rowid, $statut, $type_contact_id = 0, $fk_socpeople = 0)
1477 $sql =
"UPDATE ".$this->db->prefix().
"element_contact set";
1478 $sql .=
" statut = ".((int) $statut);
1479 if ($type_contact_id) {
1480 $sql .=
", fk_c_type_contact = ".((int) $type_contact_id);
1482 if ($fk_socpeople) {
1483 $sql .=
", fk_socpeople = ".((int) $fk_socpeople);
1485 $sql .=
" where rowid = ".((int) $rowid);
1487 $resql = $this->db->query($sql);
1491 $this->error = $this->db->lasterror();
1513 if (!$error && empty($notrigger)) {
1515 $this->context[
'contact_id'] = ((int) $rowid);
1516 $triggerPrefix = (empty($this->TRIGGER_PREFIX) ? strtoupper($this->element) : $this->TRIGGER_PREFIX);
1517 $result = $this->call_trigger($triggerPrefix.
'_DELETE_CONTACT', $user);
1525 dol_syslog(get_class($this).
"::delete_contact", LOG_DEBUG);
1527 $sql =
"DELETE FROM ".MAIN_DB_PREFIX.
"element_contact";
1528 $sql .=
" WHERE rowid = ".((int) $rowid);
1530 $result = $this->db->query($sql);
1533 $this->errors[] = $this->db->lasterror();
1538 $this->db->commit();
1541 $this->error = $this->db->lasterror();
1542 $this->db->rollback();
1562 if (!empty($typeContact)) {
1563 foreach ($typeContact as $key => $value) {
1564 array_push($temp, $key);
1566 $listId = implode(
",", $temp);
1571 if (empty($listId)) {
1575 $sql =
"DELETE FROM ".$this->db->prefix().
"element_contact";
1576 $sql .=
" WHERE element_id = ".((int) $this->
id);
1577 $sql .=
" AND fk_c_type_contact IN (".$this->db->sanitize($listId).
")";
1579 dol_syslog(get_class($this).
"::delete_linked_contact", LOG_DEBUG);
1580 if ($this->db->query($sql)) {
1583 $this->error = $this->db->lasterror();
1600 public function liste_contact($statusoflink = -1, $source =
'external', $list = 0, $code =
'', $status = -1, $arrayoftcids = array())
1607 $sql =
"SELECT ec.rowid, ec.statut as statuslink, ec.fk_socpeople as id, ec.fk_c_type_contact";
1608 if ($source ==
'internal') {
1609 $sql .=
", '-1' as socid, t.statut as statuscontact, t.login, t.photo, t.gender, t.fk_country as country_id";
1611 if ($source ==
'external' || $source ==
'thirdparty') {
1612 $sql .=
", t.fk_soc as socid, t.statut as statuscontact, t.fk_pays as country_id";
1614 $sql .=
", t.civility as civility, t.lastname as lastname, t.firstname, t.email, t.address, t.zip, t.town";
1615 if (empty($arrayoftcids)) {
1616 $sql .=
", tc.source, tc.element, tc.code, tc.libelle as type_label, co.label as country";
1619 if (empty($arrayoftcids)) {
1620 $sql .=
" ".$this->db->prefix().
"c_type_contact as tc,";
1622 $sql .=
" ".$this->db->prefix().
"element_contact as ec";
1623 if ($source ==
'internal') {
1624 $sql .=
" LEFT JOIN ".$this->db->prefix().
"user as t on ec.fk_socpeople = t.rowid";
1625 $sql .=
" LEFT JOIN ".$this->db->prefix().
"c_country as co ON co.rowid = t.fk_country";
1627 if ($source ==
'external' || $source ==
'thirdparty') {
1628 $sql .=
" LEFT JOIN ".$this->db->prefix().
"socpeople as t on ec.fk_socpeople = t.rowid";
1629 $sql .=
" LEFT JOIN ".$this->db->prefix().
"c_country as co ON co.rowid = t.fk_pays";
1631 $sql .=
" WHERE ec.element_id = ".((int) $this->
id);
1632 if (empty($arrayoftcids)) {
1633 $sql .=
" AND ec.fk_c_type_contact = tc.rowid";
1634 $sql .=
" AND tc.element = '".$this->db->escape($this->element).
"'";
1636 $sql .=
" AND tc.code = '".$this->db->escape($code).
"'";
1638 if ($source ==
'internal') {
1639 $sql .=
" AND tc.source = 'internal'";
1641 if ($source ==
'external' || $source ==
'thirdparty') {
1642 $sql .=
" AND tc.source = 'external'";
1644 $sql .=
" AND tc.active = 1";
1646 $sql .=
" AND ec.fk_c_type_contact IN (".$this->db->sanitize(implode(
',', $arrayoftcids)).
")";
1649 $sql .=
" AND t.statut = ".((int) $status);
1651 if ($statusoflink >= 0) {
1652 $sql .=
" AND ec.statut = ".((int) $statusoflink);
1654 $sql .=
" ORDER BY t.lastname ASC";
1656 dol_syslog(get_class($this).
"::liste_contact", LOG_DEBUG);
1657 $resql = $this->db->query($sql);
1659 $num = $this->db->num_rows($resql);
1662 $obj = $this->db->fetch_object($resql);
1665 $transkey =
"TypeContact_".$obj->element.
"_".$obj->source.
"_".$obj->code;
1666 $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->type_label);
1668 'parentId' => $this->
id,
1669 'source' => $obj->source,
1670 'socid' => $obj->socid,
1672 'nom' => $obj->lastname,
1673 'civility' => $obj->civility,
1674 'lastname' => $obj->lastname,
1675 'firstname' => $obj->firstname,
1676 'email' => $obj->email,
1677 'address' => $obj->address,
1679 'town' => $obj->town,
1680 'country_id' => $obj->country_id,
1681 'country' => $obj->country,
1682 'login' => (empty($obj->login) ?
'' : $obj->login),
1683 'photo' => (empty($obj->photo) ?
'' : $obj->photo),
1684 'gender' => (empty($obj->gender) ?
'' : $obj->gender),
1685 'statuscontact' => $obj->statuscontact,
1686 'rowid' => $obj->rowid,
1687 'code' => $obj->code,
1688 'libelle' => $libelle_type,
1689 'status' => (
int) $obj->statuslink,
1690 'fk_c_type_contact' => $obj->fk_c_type_contact
1693 $tab[$i] = $obj->id;
1701 $this->error = $this->db->lasterror();
1716 $sql =
"SELECT ec.datecreate, ec.statut, ec.fk_socpeople, ec.fk_c_type_contact,";
1717 $sql .=
" tc.code, tc.libelle as type_label";
1718 $sql .=
" FROM (".$this->db->prefix().
"element_contact as ec, ".$this->db->prefix().
"c_type_contact as tc)";
1719 $sql .=
" WHERE ec.rowid =".((int) $rowid);
1720 $sql .=
" AND ec.fk_c_type_contact = tc.rowid";
1721 $sql .=
" AND tc.element = '".$this->db->escape($this->element).
"'";
1723 dol_syslog(get_class($this).
"::swapContactStatus", LOG_DEBUG);
1724 $resql = $this->db->query($sql);
1726 $obj = $this->db->fetch_object($resql);
1727 $newstatut = ($obj->statut == 4) ? 5 : 4;
1729 $this->db->free($resql);
1732 $this->error = $this->db->error();
1749 public function liste_type_contact($source =
'internal', $order =
'position', $option = 0, $activeonly = 0, $code =
'')
1754 $sanitized_order = $order;
1756 if (empty($sanitized_order)) {
1757 $sanitized_order =
'position';
1759 if ($sanitized_order ==
'position') {
1760 $sanitized_order .=
',code';
1765 $sql =
"SELECT DISTINCT tc.rowid, tc.code, tc.libelle as type_label, tc.position";
1766 $sql .=
" FROM ".$this->db->prefix().
"c_type_contact as tc";
1767 $sql .=
" WHERE tc.element = '".$this->db->escape($this->element).
"'";
1768 if ($activeonly == 1) {
1769 $sql .=
" AND tc.active = 1";
1771 if (!empty($source) && $source !=
'all') {
1772 $sql .=
" AND tc.source = '".$this->db->escape($source).
"'";
1774 if (!empty($code)) {
1775 $sql .=
" AND tc.code = '".$this->db->escape($code).
"'";
1777 $sql .= $this->db->order($sanitized_order,
'ASC');
1780 $resql = $this->db->query($sql);
1782 $this->error = $this->db->lasterror();
1787 $num = $this->db->num_rows($resql);
1790 $obj = $this->db->fetch_object($resql);
1792 $transkey =
"TypeContact_".$this->element.
"_".$source.
"_".$obj->code;
1793 $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $langs->trans($obj->type_label));
1794 if (empty($option)) {
1795 $tab[$obj->rowid] = $libelle_type;
1796 } elseif ($option == 1) {
1797 $tab[$obj->code] = $libelle_type;
1799 $tab[$obj->rowid] = array(
'id' => $obj->rowid,
'code' => $obj->code,
'label' => $libelle_type);
1818 public function listeTypeContacts($source =
'internal', $option = 0, $activeonly = 0, $code =
'', $element =
'', $excludeelement =
'')
1822 $langs->loadLangs(array(
'bills',
'contracts',
'interventions',
'orders',
'projects',
'propal',
'ticket',
'agenda'));
1826 $sql =
"SELECT DISTINCT tc.rowid, tc.code, tc.libelle as type_label, tc.position, tc.element, tc.module";
1827 $sql .=
" FROM ".$this->db->prefix().
"c_type_contact as tc";
1829 $sqlWhere = array();
1830 if (!empty($element)) {
1831 $sqlWhere[] =
" tc.element='".$this->db->escape($element).
"'";
1833 if (!empty($excludeelement)) {
1834 $sqlWhere[] =
" tc.element <> '".$this->db->escape($excludeelement).
"'";
1837 if ($activeonly == 1) {
1838 $sqlWhere[] =
" tc.active=1";
1841 if (!empty($source) && $source !=
'all') {
1842 $sqlWhere[] =
" tc.source='".$this->db->escape($source).
"'";
1845 if (!empty($code)) {
1846 $sqlWhere[] =
" tc.code='".$this->db->escape($code).
"'";
1849 if (count($sqlWhere) > 0) {
1850 $sql .=
" WHERE ".implode(
' AND ', $sqlWhere);
1853 $sql .= $this->db->order(
'tc.element, tc.position',
'ASC');
1856 $resql = $this->db->query($sql);
1858 $num = $this->db->num_rows($resql);
1860 $langs->loadLangs(array(
"propal",
"orders",
"bills",
"suppliers",
"contracts",
"supplier_proposal"));
1862 while ($obj = $this->db->fetch_object($resql)) {
1863 $modulename = $obj->module ?? $obj->element;
1864 if (strpos($obj->element,
'project') !==
false) {
1865 $modulename =
'projet';
1866 } elseif ($obj->element ==
'contrat') {
1867 $element =
'contract';
1868 } elseif ($obj->element ==
'action') {
1869 $modulename =
'agenda';
1870 } elseif (strpos($obj->element,
'supplier') !==
false && $obj->element !=
'supplier_proposal') {
1871 $modulename =
'fournisseur';
1874 $libelle_element = $langs->trans(
'ContactDefault_'.$obj->element);
1875 $tmpelement = $obj->element;
1876 $transkey =
"TypeContact_".$tmpelement.
"_".$source.
"_".$obj->code;
1877 $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->type_label);
1878 $tab[$obj->rowid] = $libelle_element.
' - '.$libelle_type;
1884 $this->error = $this->db->lasterror();
1905 if (!
getDolGlobalInt(
'SHIPPING_USE_ITS_OWN_CONTACTS') && $this->element ==
'shipping' && $this->origin_id != 0) {
1906 $id = $this->origin_id;
1907 $element =
'commande';
1908 } elseif ($this->element ==
'reception' && $this->origin_id != 0) {
1909 $id = $this->origin_id;
1910 $element =
'order_supplier';
1913 $element = $this->element;
1916 $sql =
"SELECT ec.fk_socpeople";
1917 $sql .=
" FROM ".$this->db->prefix().
"element_contact as ec,";
1918 if ($source ==
'internal') {
1919 $sql .=
" ".$this->db->prefix().
"user as c,";
1921 if ($source ==
'external') {
1922 $sql .=
" ".$this->db->prefix().
"socpeople as c,";
1924 $sql .=
" ".$this->db->prefix().
"c_type_contact as tc";
1925 $sql .=
" WHERE ec.element_id = ".((int) $id);
1926 $sql .=
" AND ec.fk_socpeople = c.rowid";
1927 if ($source ==
'internal') {
1928 $sql .=
" AND c.entity IN (".getEntity(
'user').
")";
1930 if ($source ==
'external') {
1931 $sql .=
" AND c.entity IN (".getEntity(
'societe').
")";
1933 $sql .=
" AND ec.fk_c_type_contact = tc.rowid";
1934 $sql .=
" AND tc.element = '".$this->db->escape($element).
"'";
1935 $sql .=
" AND tc.source = '".$this->db->escape($source).
"'";
1937 $sql .=
" AND tc.code = '".$this->db->escape($code).
"'";
1939 $sql .=
" AND tc.active = 1";
1941 $sql .=
" AND ec.statut = ".((int) $status);
1944 dol_syslog(get_class($this).
"::getIdContact", LOG_DEBUG);
1945 $resql = $this->db->query($sql);
1947 while ($obj = $this->db->fetch_object($resql)) {
1948 $result[$i] = $obj->fk_socpeople;
1952 $this->error = $this->db->error();
1969 if (empty($contactid)) {
1970 $contactid = $this->contact_id;
1973 if (empty($contactid)) {
1977 require_once DOL_DOCUMENT_ROOT.
'/contact/class/contact.class.php';
1978 $contact =
new Contact($this->db);
1979 $result = $contact->fetch($contactid);
1980 $this->contact = $contact;
1995 if (empty($this->socid) && empty($this->fk_soc) && empty($force_thirdparty_id)) {
1999 require_once DOL_DOCUMENT_ROOT.
'/societe/class/societe.class.php';
2001 $idtofetch = isset($this->socid) ? $this->socid : (isset($this->fk_soc) ? $this->fk_soc : 0);
2002 if ($force_thirdparty_id) {
2003 $idtofetch = $force_thirdparty_id;
2007 $thirdparty =
new Societe($this->db);
2008 $result = $thirdparty->fetch($idtofetch);
2010 $this->errors = array_merge($this->errors, $thirdparty->errors);
2012 $this->thirdparty = $thirdparty;
2016 $this->thirdparty->price_level = 1;
2035 if (!$this->table_ref_field) {
2039 $sql =
"SELECT rowid FROM ".$this->db->prefix().$this->table_element;
2040 $sql .=
" WHERE ".$this->db->sanitize($this->table_ref_field).
" LIKE '".$this->db->escape($ref).
"'";
2043 $query = $this->db->query($sql);
2045 if (!$this->db->num_rows($query)) {
2049 $result = $this->db->fetch_object($query);
2051 if (method_exists($this,
'fetch')) {
2052 return $this->fetch($result->rowid);
2054 $this->error =
'Fetch method not implemented on '.get_class($this);
2055 dol_syslog(get_class($this).
'::fetchOneLike Error='.$this->error, LOG_ERR);
2056 array_push($this->errors, $this->error);
2085 dol_syslog(get_class($this).
'::fetchBarCode this->element='.$this->element.
' this->barcode_type='.$this->barcode_type);
2087 $idtype = $this->barcode_type;
2088 if (empty($idtype) && $idtype !=
'0') {
2089 if ($this->element ==
'product' &&
getDolGlobalString(
'PRODUIT_DEFAULT_BARCODE_TYPE')) {
2091 } elseif ($this->element ==
'societe') {
2094 dol_syslog(
'Call fetchBarCode with barcode_type not defined and cannot be guessed', LOG_WARNING);
2099 if (empty($this->barcode_type) || empty($this->barcode_type_code) || empty($this->barcode_type_label) || empty($this->barcode_type_coder)) {
2100 $sql =
"SELECT rowid, code, libelle as label, coder";
2101 $sql .=
" FROM ".$this->db->prefix().
"c_barcode_type";
2102 $sql .=
" WHERE rowid = ".((int) $idtype);
2104 $resql = $this->db->query($sql);
2106 $obj = $this->db->fetch_object($resql);
2108 $this->barcode_type = $obj->rowid;
2109 $this->barcode_type_code = $obj->code;
2110 $this->barcode_type_label = $obj->label;
2111 $this->barcode_type_coder = $obj->coder;
2129 include_once DOL_DOCUMENT_ROOT.
'/projet/class/project.class.php';
2131 if (empty($this->fk_project) && !empty($this->fk_projet)) {
2132 $this->fk_project = $this->fk_projet;
2134 if (empty($this->fk_project)) {
2138 $project =
new Project($this->db);
2139 $result = $project->fetch($this->fk_project);
2141 $this->project = $project;
2183 include_once DOL_DOCUMENT_ROOT.
'/product/class/product.class.php';
2186 if (empty($this->fk_product)) {
2190 $product =
new Product($this->db);
2192 $result = $product->fetch($this->fk_product);
2194 $this->product = $product;
2208 $user =
new User($this->db);
2209 $result = $user->fetch($userid);
2210 $this->
user = $user;
2224 $tmpclassname = $this->origin ? $this->origin : $this->origin_type;
2227 if ($tmpclassname ==
'shipping') {
2228 $tmpclassname =
'Expedition';
2230 if ($tmpclassname ==
'delivery') {
2231 $tmpclassname =
'Livraison';
2233 if ($tmpclassname ==
'order_supplier' || $tmpclassname ==
'supplier_order') {
2234 $tmpclassname =
'CommandeFournisseur';
2237 $classname = ucfirst($tmpclassname);
2239 $this->origin_object =
new $classname($this->db);
2241 $this->origin_object->fetch($this->origin_id);
2259 $sql =
"SELECT rowid FROM ".$this->db->prefix().$table;
2260 $sql .=
" WHERE ".$this->db->sanitize($field).
" = '".$this->db->escape($key).
"'";
2261 if (!empty($element)) {
2262 $sql .=
" AND entity IN (".getEntity($element).
")";
2264 $sql .=
" AND entity = ".((int)
$conf->entity);
2267 dol_syslog(get_class($this).
'::fetchObjectFrom', LOG_DEBUG);
2268 $resql = $this->db->query($sql);
2270 $obj = $this->db->fetch_object($resql);
2273 if (method_exists($this,
'fetch')) {
2274 $result = $this->fetch($obj->rowid);
2276 $this->error =
'fetch() method not implemented on '.get_class($this);
2277 dol_syslog(get_class($this).
'::fetchOneLike Error='.$this->error, LOG_ERR);
2278 array_push($this->errors, $this->error);
2298 if (!empty($id) && !empty($field) && !empty($table)) {
2299 if (!preg_match(
'/^[a-zA-Z_][a-zA-Z0-9_]*$/', $table)) {
2300 dol_syslog(get_class($this).
'::getValueFrom Bad table name: '.$table, LOG_WARNING);
2303 if (!preg_match(
'/^[a-zA-Z_][a-zA-Z0-9_.]*$/', $field)) {
2304 dol_syslog(get_class($this).
'::getValueFrom Bad field name: '.$field, LOG_WARNING);
2308 $sql =
"SELECT ".$this->db->sanitize($field).
" FROM ".$this->db->prefix().$this->db->sanitize($table);
2309 $sql .=
" WHERE rowid = ".((int) $id);
2311 dol_syslog(get_class($this).
'::getValueFrom', LOG_DEBUG);
2312 $resql = $this->db->query($sql);
2314 $row = $this->db->fetch_row($resql);
2337 public function setValueFrom($field, $value, $table =
'', $id =
null, $format =
'', $id_field =
'', $fuser =
null, $trigkey =
'', $fk_user_field =
'fk_user_modif')
2341 if (empty($table)) {
2342 $table = $this->table_element;
2347 if (empty($format)) {
2350 if (empty($id_field)) {
2351 $id_field =
'rowid';
2354 $propfield = $field;
2357 if ($table ==
'product') {
2358 if ($field ==
'note_private') {
2360 $propfield =
'note_private';
2361 } elseif ($field ==
'status') {
2363 $propfield =
'status';
2364 } elseif ($field ==
'status_buy') {
2366 $propfield =
'status_buy';
2367 } elseif ($field ==
'status_batch') {
2369 $propfield =
'status_batch';
2373 if (in_array($table, array(
'actioncomm',
'adherent',
'advtargetemailing',
'cronjob',
'establishment'))) {
2374 $fk_user_field =
'fk_user_mod';
2376 if (in_array($table, array(
'prelevement_bons'))) {
2377 $fk_user_field =
'';
2380 if (!preg_match(
'/^[a-zA-Z_][a-zA-Z0-9_]*$/', $table)) {
2381 dol_syslog(get_class($this).
'::getValueFrom Bad table name: '.$table, LOG_WARNING);
2384 if (!preg_match(
'/^[a-zA-Z_][a-zA-Z0-9_.]*$/', $field)) {
2385 dol_syslog(get_class($this).
'::getValueFrom Bad field name: '.$field, LOG_WARNING);
2391 $sql =
"SELECT " . $this->db->sanitize($field);
2392 $sql .=
" FROM " . MAIN_DB_PREFIX . $this->db->sanitize($table);
2393 $sql .=
" WHERE " . $this->db->sanitize($id_field) .
" = " . ((int) $id);
2395 $resql = $this->db->query($sql);
2397 if ($obj = $this->db->fetch_object($resql)) {
2398 if ($format ==
'date') {
2399 $oldvalue = $this->db->jdate($obj->$field);
2401 $oldvalue = $obj->$field;
2405 $this->error = $this->db->lasterror();
2416 $sql =
"UPDATE ".$this->db->prefix().$table.
" SET ";
2418 if ($format ==
'text') {
2419 $sql .= $this->db->sanitize($field).
" = '".$this->db->escape($value).
"'";
2420 } elseif ($format ==
'int') {
2421 $sql .= $this->db->sanitize($field).
" = ".((int) $value);
2422 } elseif ($format ==
'date') {
2423 $sql .= $this->db->sanitize($field).
" = ".($value ?
"'".$this->db->idate($value).
"'" :
"null");
2424 } elseif ($format ==
'dategmt') {
2425 $sql .= $this->db->sanitize($field).
" = ".($value ?
"'".$this->db->idate($value,
'gmt').
"'" :
"null");
2428 if ($fk_user_field) {
2429 if (!empty($fuser) && is_object($fuser)) {
2430 $sql .=
", ".$this->db->sanitize($fk_user_field).
" = ".((int) $fuser->id);
2431 } elseif (empty($fuser) || $fuser !=
'none') {
2432 $sql .=
", ".$this->db->sanitize($fk_user_field).
" = ".((int) $user->id);
2436 $sql .=
" WHERE ".$this->db->sanitize($id_field).
" = ".((int) $id);
2438 $resql = $this->db->query($sql);
2442 if (method_exists($this,
'fetch')) {
2443 $result = $this->fetch(
$id);
2448 $this->oldcopy = clone $this;
2449 if (property_exists($this->oldcopy, $field)) {
2450 $this->oldcopy->$field = $oldvalue;
2452 if ($propfield != $field && property_exists($this->oldcopy, $propfield)) {
2453 $this->oldcopy->$propfield = $oldvalue;
2456 if (empty($this->context[
'actionmsgmore'])) {
2457 $this->context[
'actionmsgmore'] =
'Trigger called by setValueFrom';
2461 $result = $this->call_trigger($trigkey, (!empty($fuser) && is_object($fuser)) ? $fuser : $user);
2467 if (property_exists($this, $field)) {
2468 $this->$field = $value;
2470 if ($propfield != $field && property_exists($this, $propfield)) {
2471 $this->$propfield = $value;
2476 $this->db->commit();
2479 if (property_exists($this, $field)) {
2480 $this->$field = $oldvalue;
2482 if ($propfield != $field && property_exists($this, $propfield)) {
2483 $this->$propfield = $oldvalue;
2485 $this->db->rollback();
2489 if ($this->db->lasterrno() ==
'DB_ERROR_RECORD_ALREADY_EXISTS') {
2490 $this->error =
'DB_ERROR_RECORD_ALREADY_EXISTS';
2492 $this->error = $this->db->lasterror();
2494 $this->db->rollback();
2513 global
$conf, $user;
2515 if (!$this->table_element) {
2516 dol_print_error(
null, get_class($this).
"::load_previous_next_ref was called on object with property table_element not defined");
2519 if ($fieldid ==
'none') {
2524 if (in_array($this->table_element, array(
'facture_rec',
'facture_fourn_rec')) && $fieldid ==
'title') {
2530 if ($user->socid > 0) {
2531 $socid = $user->socid;
2536 $aliastablesociete =
's';
2537 if ($this->element ==
'societe') {
2538 $aliastablesociete =
'te';
2540 $restrictiononfksoc = empty($this->restrictiononfksoc) ? 0 : $this->restrictiononfksoc;
2541 $sql =
"SELECT MAX(te.".$this->db->sanitize($fieldid).
")";
2542 $sql .=
" FROM ".(empty($nodbprefix) ? $this->db->prefix() :
'').$this->table_element.
" as te";
2543 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2544 $tmparray = explode(
'@', $this->ismultientitymanaged);
2545 $sql .=
", ".$this->db->prefix().$this->db->sanitize($tmparray[1]).
" as ".($tmparray[1] ==
'societe' ?
's' :
'parenttable');
2546 } elseif ($restrictiononfksoc == 1 && $this->element !=
'societe' && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2547 $sql .=
", ".$this->db->prefix().
"societe as s";
2548 } elseif ($restrictiononfksoc == 2 && $this->element !=
'societe' && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2549 $sql .=
" LEFT JOIN ".$this->db->prefix().
"societe as s ON te.fk_soc = s.rowid";
2551 if ($restrictiononfksoc && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2552 $sql .=
" LEFT JOIN ".$this->db->prefix().
"societe_commerciaux as sc ON ".$aliastablesociete.
".rowid = sc.fk_soc";
2554 if ($fieldid ==
'rowid') {
2555 $sql .=
" WHERE te.".$this->db->sanitize($fieldid).
" < ".((int) $this->
id);
2556 } elseif ($fieldid ==
'label') {
2557 $sql .=
" WHERE te.".$this->db->sanitize($fieldid).
" < '".$this->db->escape((
string) $this->label).
"'";
2559 $sql .=
" WHERE te.".$this->db->sanitize($fieldid).
" < '".$this->db->escape((
string) $this->
ref).
"'";
2561 if ($restrictiononfksoc == 1 && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2562 $sql .=
" AND sc.fk_user = ".((int) $user->id);
2564 if ($restrictiononfksoc == 2 && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2565 $sql .=
" AND (sc.fk_user = ".((int) $user->id).
' OR te.fk_soc IS NULL)';
2568 $filtermax = $filter;
2573 if ($errormessage) {
2574 if (!preg_match(
'/^\s*AND/i', $filtermax)) {
2582 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2583 $tmparray = explode(
'@', $this->ismultientitymanaged);
2584 $sql .=
" AND te.".$this->db->sanitize($tmparray[0]).
" = ".($tmparray[1] ==
"societe" ?
"s" :
"parenttable").
".rowid";
2585 } elseif ($restrictiononfksoc == 1 && $this->element !=
'societe' && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2586 $sql .=
' AND te.fk_soc = s.rowid';
2588 if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
2589 if ($this->element ==
'user' &&
getDolGlobalInt(
'MULTICOMPANY_TRANSVERSE_MODE')) {
2590 if (!empty($user->admin) && empty($user->entity) &&
$conf->entity == 1) {
2591 $sql .=
" AND te.entity IS NOT NULL";
2593 $sql .=
" AND te.rowid IN (SELECT ug.fk_user FROM ".$this->db->prefix().
"usergroup_user as ug WHERE ug.entity IN (".
getEntity(
'usergroup').
"))";
2596 $sql .=
' AND te.entity IN ('.getEntity($this->element).
')';
2599 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged) && $this->element !=
'societe') {
2600 $tmparray = explode(
'@', $this->ismultientitymanaged);
2601 $sql .=
' AND parenttable.entity IN ('.getEntity($tmparray[1]).
')';
2603 if ($restrictiononfksoc == 1 && $socid && $this->element !=
'societe') {
2604 $sql .=
' AND te.fk_soc = '.((int) $socid);
2606 if ($restrictiononfksoc == 2 && $socid && $this->element !=
'societe') {
2607 $sql .=
' AND (te.fk_soc = '.((int) $socid).
' OR te.fk_soc IS NULL)';
2609 if ($restrictiononfksoc && $socid && $this->element ==
'societe') {
2610 $sql .=
' AND te.rowid = '.((int) $socid);
2614 $result = $this->db->query($sql);
2616 $this->error = $this->db->lasterror();
2619 $row = $this->db->fetch_row($result);
2620 $this->ref_previous = $row[0];
2622 $sql =
"SELECT MIN(te.".$this->db->sanitize($fieldid).
")";
2623 $sql .=
" FROM ".(empty($nodbprefix) ? $this->db->prefix() :
'').$this->table_element.
" as te";
2624 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2625 $tmparray = explode(
'@', $this->ismultientitymanaged);
2626 $sql .=
", ".$this->db->prefix().$this->db->sanitize($tmparray[1]).
" as ".($tmparray[1] ==
'societe' ?
's' :
'parenttable');
2627 } elseif ($restrictiononfksoc == 1 && $this->element !=
'societe' && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2628 $sql .=
", ".$this->db->prefix().
"societe as s";
2629 } elseif ($restrictiononfksoc == 2 && $this->element !=
'societe' && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2630 $sql .=
" LEFT JOIN ".$this->db->prefix().
"societe as s ON te.fk_soc = s.rowid";
2632 if ($restrictiononfksoc && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2633 $sql .=
" LEFT JOIN ".$this->db->prefix().
"societe_commerciaux as sc ON ".$aliastablesociete.
".rowid = sc.fk_soc";
2635 if ($fieldid ==
'rowid') {
2636 $sql .=
" WHERE te.".$this->db->sanitize($fieldid).
" > ".((int) $this->
id);
2637 } elseif ($fieldid ==
'label') {
2638 $sql .=
" WHERE te.".$this->db->sanitize($fieldid).
" > '".$this->db->escape((
string) $this->label).
"'";
2640 $sql .=
" WHERE te.".$this->db->sanitize($fieldid).
" > '".$this->db->escape((
string) $this->
ref).
"'";
2642 if ($restrictiononfksoc == 1 && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2643 $sql .=
" AND (sc.fk_user = ".((int) $user->id);
2645 $userschilds = $user->getAllChildIds();
2646 $sql .=
" OR sc.fk_user IN (".$this->db->sanitize(implode(
',', $userschilds)).
")";
2650 if ($restrictiononfksoc == 2 && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2651 $sql .=
" AND (sc.fk_user = ".((int) $user->id).
' OR te.fk_soc IS NULL)';
2654 $filtermin = $filter;
2659 if ($errormessage) {
2660 if (!preg_match(
'/^\s*AND/i', $filtermin)) {
2670 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2671 $tmparray = explode(
'@', $this->ismultientitymanaged);
2672 $sql .=
" AND te.".$this->db->sanitize($tmparray[0]).
" = ".($tmparray[1] ==
"societe" ?
"s" :
"parenttable").
".rowid";
2673 } elseif ($restrictiononfksoc == 1 && $this->element !=
'societe' && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2674 $sql .=
' AND te.fk_soc = s.rowid';
2676 if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
2677 if ($this->element ==
'user' &&
getDolGlobalInt(
'MULTICOMPANY_TRANSVERSE_MODE')) {
2678 if (!empty($user->admin) && empty($user->entity) &&
$conf->entity == 1) {
2679 $sql .=
" AND te.entity IS NOT NULL";
2681 $sql .=
" AND te.rowid IN (SELECT ug.fk_user FROM ".$this->db->prefix().
"usergroup_user as ug WHERE ug.entity IN (".
getEntity(
'usergroup').
"))";
2684 $sql .=
' AND te.entity IN ('.getEntity($this->element).
')';
2687 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged) && $this->element !=
'societe') {
2688 $tmparray = explode(
'@', $this->ismultientitymanaged);
2689 $sql .=
' AND parenttable.entity IN ('.getEntity($tmparray[1]).
')';
2691 if ($restrictiononfksoc == 1 && $socid && $this->element !=
'societe') {
2692 $sql .=
' AND te.fk_soc = '.((int) $socid);
2694 if ($restrictiononfksoc == 2 && $socid && $this->element !=
'societe') {
2695 $sql .=
' AND (te.fk_soc = '.((int) $socid).
' OR te.fk_soc IS NULL)';
2697 if ($restrictiononfksoc && $socid && $this->element ==
'societe') {
2698 $sql .=
' AND te.rowid = '.((int) $socid);
2703 $result = $this->db->query($sql);
2705 $this->error = $this->db->lasterror();
2708 $row = $this->db->fetch_row($result);
2709 $this->ref_next = $row[0];
2724 $contactAlreadySelected = array();
2729 if ($source ==
'thirdparty') {
2730 $contactAlreadySelected[$i] = $tab[$i][
'socid'];
2732 $contactAlreadySelected[$i] = $tab[$i][
'id'];
2736 return $contactAlreadySelected;
2752 if (!$this->table_element) {
2753 dol_syslog(get_class($this).
"::setProject was called on object with property table_element not defined", LOG_ERR);
2757 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
2758 if ($this->table_element ==
'actioncomm') {
2760 $sql .=
" SET fk_project = ".((int) $projectid);
2762 $sql .=
" SET fk_project = NULL";
2764 $sql .=
' WHERE id = '.((int) $this->
id);
2766 } elseif (!empty($this->fields[
'fk_project'])) {
2768 $sql .=
" SET fk_project = ".((int) $projectid);
2770 $sql .=
" SET fk_project = NULL";
2772 $sql .=
' WHERE rowid = '.((int) $this->
id);
2775 $sql .=
' SET fk_projet = '.((int) $projectid);
2777 $sql .=
' SET fk_projet = NULL';
2779 $sql .=
" WHERE rowid = ".((int) $this->
id);
2784 dol_syslog(get_class($this).
"::setProject", LOG_DEBUG);
2785 if ($this->db->query($sql)) {
2786 $this->fk_project = ((int) $projectid);
2793 if (!$error && !$notrigger) {
2795 $result = $this->call_trigger(strtoupper($this->element) .
'_MODIFY', $user);
2804 $this->db->rollback();
2807 $this->db->commit();
2825 dol_syslog(get_class($this).
'::setPaymentMethods('.$id.
')');
2827 if ($this->
status >= 0 || $this->element ==
'societe') {
2831 $fieldname =
'fk_mode_reglement';
2832 $triggerName = (empty($this->TRIGGER_PREFIX) ? strtoupper(get_class($this)) : $this->TRIGGER_PREFIX);
2833 if ($this->element ==
'societe') {
2834 $fieldname =
'mode_reglement';
2835 $triggerName =
'COMPANY';
2837 if (get_class($this) ==
'Facture') {
2838 $triggerName =
'BILL';
2840 if (get_class($this) ==
'Fournisseur') {
2841 $fieldname =
'mode_reglement_supplier';
2842 $triggerName =
'BILL_SUPPLIER';
2844 if (get_class($this) ==
'Tva') {
2845 $fieldname =
'fk_typepayment';
2846 $triggerName =
'VAT';
2848 if (get_class($this) ==
'Salary') {
2849 $fieldname =
'fk_typepayment';
2852 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
2853 $sql .=
" SET ".$this->db->sanitize($fieldname).
" = ".(($id > 0 || $id ==
'0') ? ((
int) $id) :
'NULL');
2854 $sql .=
' WHERE rowid = '.((int) $this->
id);
2856 if ($this->db->query($sql)) {
2857 $this->mode_reglement_id = $id;
2859 if (get_class($this) ==
'Fournisseur') {
2860 $this->mode_reglement_supplier_id = $id;
2864 if (!$error && !$notrigger) {
2866 $result = $this->call_trigger($triggerName.
'_MODIFY', $user);
2874 dol_syslog(get_class($this).
'::setPaymentMethods Error '.$this->db->error());
2875 $this->error = $this->db->error();
2879 dol_syslog(get_class($this).
'::setPaymentMethods, status of the object is incompatible');
2880 $this->error =
'Status of the object is incompatible '.$this->status;
2893 dol_syslog(get_class($this).
'::setMulticurrencyCode('.$code.
')');
2894 if ($this->
status >= 0 || $this->element ==
'societe') {
2895 $sql =
'UPDATE '.$this->db->prefix().$this->table_element;
2896 $sql .=
" SET multicurrency_code = '".$this->db->escape($code).
"'";
2897 $sql .=
' WHERE rowid='.((int) $this->
id);
2899 if ($this->db->query($sql)) {
2900 $this->multicurrency_code = $code;
2904 $this->setMulticurrencyRate($rate, 2);
2909 dol_syslog(get_class($this).
'::setMulticurrencyCode Error '.$sql.
' - '.$this->db->error());
2910 $this->error = $this->db->error();
2914 dol_syslog(get_class($this).
'::setMulticurrencyCode, status of the object is incompatible');
2915 $this->error =
'Status of the object is incompatible '.$this->status;
2927 public function setMulticurrencyRate($rate, $mode = 1)
2929 dol_syslog(get_class($this).
'::setMulticurrencyRate('.$rate.
', '.$mode.
')');
2930 if ($this->
status >= 0 || $this->element ==
'societe') {
2931 $sql =
'UPDATE '.$this->db->prefix().$this->table_element;
2932 $sql .=
" SET multicurrency_tx = ".((float) $rate);
2933 $sql .=
' WHERE rowid='.((int) $this->
id);
2935 if ($this->db->query($sql)) {
2936 $this->multicurrency_tx = $rate;
2939 if (!empty($this->lines)) {
2940 foreach ($this->lines as &$line) {
2943 $line->subprice = 0;
2948 $line->multicurrency_subprice = 0;
2951 switch ($this->element) {
2955 '@phan-var-force Propal $this';
2956 '@phan-var-force PropaleLigne $line';
2961 $line->remise_percent,
2963 $line->localtax1_tx,
2964 $line->localtax2_tx,
2965 ($line->description ? $line->description : $line->desc),
2968 $line->special_code,
2969 $line->fk_parent_line,
2970 $line->skip_update_total,
2971 $line->fk_fournprice,
2974 $line->product_type,
2977 $line->array_options,
2979 $line->multicurrency_subprice
2985 '@phan-var-force Commande $this';
2986 '@phan-var-force OrderLine $line';
2989 ($line->description ? $line->description : $line->desc),
2992 $line->remise_percent,
2994 $line->localtax1_tx,
2995 $line->localtax2_tx,
3000 $line->product_type,
3001 $line->fk_parent_line,
3002 $line->skip_update_total,
3003 $line->fk_fournprice,
3006 $line->special_code,
3007 $line->array_options,
3009 $line->multicurrency_subprice
3015 '@phan-var-force Facture $this';
3016 '@phan-var-force FactureLigne $line';
3019 ($line->description ? $line->description : $line->desc),
3022 $line->remise_percent,
3026 $line->localtax1_tx,
3027 $line->localtax2_tx,
3030 $line->product_type,
3031 $line->fk_parent_line,
3032 $line->skip_update_total,
3033 $line->fk_fournprice,
3036 $line->special_code,
3037 $line->array_options,
3038 $line->situation_percent,
3040 $line->multicurrency_subprice
3046 '@phan-var-force FactureRec $this';
3047 '@phan-var-force FactureLigneRec $line';
3050 ($line->description ? $line->description : $line->desc),
3054 $line->localtax1_tx,
3055 $line->localtax2_tx,
3057 $line->remise_percent,
3062 $line->product_type,
3064 $line->special_code,
3067 $line->multicurrency_subprice,
3071 $line->fk_fournprice,
3073 $line->fk_parent_line
3076 case 'supplier_proposal':
3079 '@phan-var-force SupplierProposal $this';
3080 '@phan-var-force SupplierProposalLine $line';
3085 $line->remise_percent,
3087 $line->localtax1_tx,
3088 $line->localtax2_tx,
3089 ($line->description ? $line->description : $line->desc),
3092 $line->special_code,
3093 $line->fk_parent_line,
3094 $line->skip_update_total,
3095 $line->fk_fournprice,
3098 $line->product_type,
3099 $line->array_options,
3101 (int) $line->fk_unit,
3102 $line->multicurrency_subprice
3105 case 'order_supplier':
3108 '@phan-var-force CommandeFournisseur $this';
3109 '@phan-var-force CommandeFournisseurLigne $line';
3112 ($line->description ? $line->description : $line->desc),
3115 $line->remise_percent,
3117 $line->localtax1_tx,
3118 $line->localtax2_tx,
3121 $line->product_type,
3125 $line->array_options,
3127 $line->multicurrency_subprice,
3131 case 'invoice_supplier':
3134 '@phan-var-force FactureFournisseur $this';
3135 '@phan-var-force SupplierInvoiceLIne $line';
3138 ($line->description ? $line->description : $line->desc),
3141 $line->localtax1_tx,
3142 $line->localtax2_tx,
3147 $line->product_type,
3148 $line->remise_percent,
3152 $line->array_options,
3154 $line->multicurrency_subprice,
3159 dol_syslog(get_class($this).
'::setMulticurrencyRate no updateline defined', LOG_DEBUG);
3167 dol_syslog(get_class($this).
'::setMulticurrencyRate Error '.$sql.
' - '.$this->db->error());
3168 $this->error = $this->db->error();
3172 dol_syslog(get_class($this).
'::setMulticurrencyRate, status of the object is incompatible');
3173 $this->error =
'Status of the object is incompatible '.$this->status;
3188 if ($this->
status >= 0 || $this->element ==
'societe') {
3190 $fieldname =
'fk_cond_reglement';
3191 if ($this->element ==
'societe') {
3192 $fieldname =
'cond_reglement';
3194 if (get_class($this) ==
'Fournisseur') {
3195 $fieldname =
'cond_reglement_supplier';
3198 if (empty($deposit_percent) || $deposit_percent < 0) {
3199 $deposit_percent = (float)
getDictionaryValue(
'c_payment_term',
'deposit_percent', $id);
3202 if ($deposit_percent > 100) {
3203 $deposit_percent = 100;
3206 $sql =
'UPDATE '.$this->db->prefix().$this->table_element;
3207 $sql .=
" SET ".$this->db->sanitize($fieldname).
" = ".(($id > 0 || $id ==
'0') ? ((
int) $id) :
'NULL');
3208 if (in_array($this->table_element, array(
'propal',
'commande',
'supplier_proposal',
'commande_fournisseur',
'societe'))) {
3209 $sql .=
" , deposit_percent = " . (empty($deposit_percent) ?
'NULL' :
"'".$this->db->escape((
string) $deposit_percent).
"'");
3211 $sql .=
' WHERE rowid = '.((int) $this->
id);
3213 if ($this->db->query($sql)) {
3214 $this->cond_reglement_id = $id;
3216 if (get_class($this) ==
'Fournisseur') {
3217 $this->cond_reglement_supplier_id = $id;
3219 $this->deposit_percent = $deposit_percent;
3222 dol_syslog(get_class($this).
'::setPaymentTerms Error '.$sql.
' - '.$this->db->error());
3223 $this->error = $this->db->error();
3227 dol_syslog(get_class($this).
'::setPaymentTerms, status of the object is incompatible');
3228 $this->error =
'Status of the object is incompatible '.$this->status;
3241 dol_syslog(get_class($this).
'::setTransportMode('.$id.
')');
3242 if ($this->
status >= 0 || $this->element ==
'societe') {
3243 $fieldname =
'fk_transport_mode';
3244 if ($this->element ==
'societe') {
3245 $fieldname =
'transport_mode';
3247 if (get_class($this) ==
'Fournisseur') {
3248 $fieldname =
'transport_mode_supplier';
3251 $sql =
'UPDATE '.$this->db->prefix().$this->table_element;
3252 $sql .=
" SET ".$this->db->sanitize($fieldname).
" = ".(($id > 0 || $id ==
'0') ? ((
int) $id) :
'NULL');
3253 $sql .=
' WHERE rowid='.((int) $this->
id);
3255 if ($this->db->query($sql)) {
3256 $this->transport_mode_id = $id;
3258 if (get_class($this) ==
'Fournisseur') {
3259 $this->transport_mode_supplier_id = $id;
3263 dol_syslog(get_class($this).
'::setTransportMode Error '.$sql.
' - '.$this->db->error());
3264 $this->error = $this->db->error();
3268 dol_syslog(get_class($this).
'::setTransportMode, status of the object is incompatible');
3269 $this->error =
'Status of the object is incompatible '.$this->status;
3283 $fieldname =
'fk_delivery_address';
3284 if ($this->element ==
'delivery' || $this->element ==
'shipping') {
3285 $fieldname =
'fk_address';
3288 $sql =
"UPDATE ".$this->db->prefix().$this->table_element.
" SET ".$this->db->sanitize($fieldname).
" = ".((int) $id);
3289 $sql .=
" WHERE rowid = ".((int) $this->
id).
" AND fk_statut = 0";
3291 if ($this->db->query($sql)) {
3292 $this->fk_delivery_address =
$id;
3295 $this->error = $this->db->error();
3296 dol_syslog(get_class($this).
'::setDeliveryAddress Error '.$this->error);
3314 if (empty($userused)) {
3320 if (!$this->table_element) {
3321 dol_syslog(get_class($this).
"::setShippingMethod was called on object with property table_element not defined", LOG_ERR);
3327 if ($shipping_method_id < 0) {
3328 $shipping_method_id =
'NULL';
3330 dol_syslog(get_class($this).
'::setShippingMethod('.$shipping_method_id.
')');
3332 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
3333 $sql .=
" SET fk_shipping_method = ".((int) $shipping_method_id);
3334 $sql .=
" WHERE rowid=".((int) $this->
id);
3335 $resql = $this->db->query($sql);
3337 dol_syslog(get_class($this).
'::setShippingMethod Error ', LOG_DEBUG);
3338 $this->error = $this->db->lasterror();
3343 $this->context = array(
'shippingmethodupdate' => 1);
3344 $triggerPrefix = (empty($this->TRIGGER_PREFIX) ? strtoupper(get_class($this)) : $this->TRIGGER_PREFIX);
3345 $result = $this->call_trigger($triggerPrefix.
'_MODIFY', $userused);
3353 $this->db->rollback();
3356 $this->shipping_method_id = ($shipping_method_id ==
'NULL') ?
null : $shipping_method_id;
3357 $this->db->commit();
3371 if (!$this->table_element) {
3372 dol_syslog(get_class($this).
"::setWarehouse was called on object with property table_element not defined", LOG_ERR);
3375 if ($warehouse_id < 0) {
3376 $warehouse_id =
'NULL';
3378 dol_syslog(get_class($this).
'::setWarehouse('.$warehouse_id.
')');
3380 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
3381 $sql .=
" SET fk_warehouse = ".((int) $warehouse_id);
3382 $sql .=
" WHERE rowid=".((int) $this->
id);
3384 if ($this->db->query($sql)) {
3385 $this->warehouse_id = ($warehouse_id ==
'NULL') ?
null : $warehouse_id;
3388 dol_syslog(get_class($this).
'::setWarehouse Error ', LOG_DEBUG);
3389 $this->error = $this->db->error();
3404 if (!$this->table_element) {
3405 dol_syslog(get_class($this).
"::setDocModel was called on object with property table_element not defined", LOG_ERR);
3409 $newmodelpdf =
dol_trunc($modelpdf, 255);
3411 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
3412 $sql .=
" SET model_pdf = '".$this->db->escape($newmodelpdf).
"'";
3413 $sql .=
" WHERE rowid = ".((int) $this->
id);
3415 dol_syslog(get_class($this).
"::setDocModel", LOG_DEBUG);
3416 $resql = $this->db->query($sql);
3418 $this->model_pdf = $modelpdf;
3439 if (empty($userused)) {
3445 if (!$this->table_element) {
3446 dol_syslog(get_class($this).
"::setBankAccount was called on object with property table_element not defined", LOG_ERR);
3451 if ($fk_account < 0) {
3452 $fk_account =
'NULL';
3454 dol_syslog(get_class($this).
'::setBankAccount('.$fk_account.
')');
3456 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
3457 $sql .=
" SET fk_account = ".((int) $fk_account);
3458 $sql .=
" WHERE rowid=".((int) $this->
id);
3460 $resql = $this->db->query($sql);
3462 dol_syslog(get_class($this).
'::setBankAccount Error '.$sql.
' - '.$this->db->error());
3463 $this->error = $this->db->lasterror();
3468 $this->context[
'bankaccountupdate'] = 1;
3470 $triggerName = (empty($this->TRIGGER_PREFIX) ? strtoupper(get_class($this)) : $this->TRIGGER_PREFIX);
3471 $result = $this->call_trigger($triggerName .
'_MODIFY', $userused);
3479 $this->db->rollback();
3482 $this->fk_account = ($fk_account ==
'NULL') ?
null : $fk_account;
3483 $this->db->commit();
3501 public function line_order($renum =
false, $rowidorder =
'ASC', $fk_parent_line =
true)
3504 if (!$this->table_element_line) {
3505 dol_syslog(get_class($this).
"::line_order was called on object with property table_element_line not defined", LOG_ERR);
3508 if (!$this->fk_element) {
3509 dol_syslog(get_class($this).
"::line_order was called on object with property fk_element not defined", LOG_ERR);
3513 $fieldposition =
'rang';
3514 if (in_array($this->table_element_line, array(
'bom_bomline',
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3515 $fieldposition =
'position';
3520 $sql =
"SELECT count(rowid) FROM ".$this->db->prefix().$this->db->sanitize($this->table_element_line);
3521 $sql .=
" WHERE ".$this->db->sanitize($this->fk_element).
" = ".((int) $this->
id);
3523 $sql .=
" AND " . $this->db->sanitize($fieldposition) .
" = 0";
3526 $sql .=
" AND " . $this->db->sanitize($fieldposition) .
" <> 0";
3529 dol_syslog(get_class($this).
"::line_order", LOG_DEBUG);
3530 $resql = $this->db->query($sql);
3532 $row = $this->db->fetch_row($resql);
3542 $sql =
"SELECT rowid FROM ".$this->db->prefix().$this->db->sanitize($this->table_element_line);
3543 $sql .=
" WHERE ".$this->db->sanitize($this->fk_element).
" = ".((int) $this->
id);
3544 if ($fk_parent_line) {
3545 $sql .=
' AND fk_parent_line IS NULL';
3547 $sql .=
" ORDER BY " . $this->db->sanitize($fieldposition) .
" ASC, rowid " . $this->db->sanitize($rowidorder);
3549 dol_syslog(get_class($this).
"::line_order search all parent lines", LOG_DEBUG);
3550 $resql = $this->db->query($sql);
3553 $num = $this->db->num_rows($resql);
3556 $row = $this->db->fetch_row($resql);
3558 if ($fk_parent_line) {
3561 if (!empty($children)) {
3562 foreach ($children as $child) {
3563 array_push($rows, $child);
3570 if (!empty($rows)) {
3571 foreach ($rows as $key => $row) {
3591 $fieldposition =
'rang';
3592 if (in_array($this->table_element_line, array(
'bom_bomline',
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3593 $fieldposition =
'position';
3598 $sql =
"SELECT rowid FROM ".$this->db->prefix().$this->db->sanitize($this->table_element_line);
3599 $sql .=
" WHERE ".$this->db->sanitize($this->fk_element).
" = ".((int) $this->
id);
3600 $sql .=
' AND fk_parent_line = '.((int) $id);
3601 $sql .=
" ORDER BY " . $this->db->sanitize($fieldposition) .
" ASC";
3603 dol_syslog(get_class($this).
"::getChildrenOfLine search children lines for line ".$id, LOG_DEBUG);
3605 $resql = $this->db->query($sql);
3606 if (!$resql || $this->db->num_rows($resql) <= 0) {
3610 while ($row = $this->db->fetch_row($resql)) {
3612 if (!empty($includealltree) && $includealltree <= 1000) {
3613 $rows = array_merge($rows, $this->
getChildrenOfLine($row[0], $includealltree + 1));
3627 public function line_up($rowid, $fk_parent_line =
true)
3630 $this->
line_order(
false,
'ASC', $fk_parent_line);
3650 $this->
line_order(
false,
'ASC', $fk_parent_line);
3671 global $hookmanager;
3672 $fieldposition =
'rang';
3673 if (in_array($this->table_element_line, array(
'bom_bomline',
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3674 $fieldposition =
'position';
3677 $sql =
"UPDATE ".$this->db->prefix().$this->table_element_line.
" SET ".$this->db->sanitize($fieldposition).
" = ".((int) $rang);
3678 $sql .=
' WHERE rowid = '.((int) $rowid);
3680 dol_syslog(get_class($this).
"::updateRangOfLine", LOG_DEBUG);
3681 if (!$this->db->query($sql)) {
3686 $parameters = array(
'rowid' => $rowid,
'rang' => $rang,
'fieldposition' => $fieldposition);
3688 $reshook = $hookmanager->executeHooks(
'afterRankOfLineUpdate', $parameters, $this, $action);
3702 $num = count($rows);
3703 for ($i = 0; $i < $num; $i++) {
3721 $fieldposition =
'rang';
3722 if (in_array($this->table_element_line, array(
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3723 $fieldposition =
'position';
3726 $sql =
"UPDATE ".$this->db->prefix().$this->db->sanitize($this->table_element_line).
" SET ".$this->db->sanitize($fieldposition).
" = ".((int) $rang);
3727 $sql .=
" WHERE ".$this->db->sanitize($this->fk_element).
" = ".((int) $this->
id);
3728 $sql .=
" AND " . $this->db->sanitize($fieldposition) .
" = " . ((int) ($rang - 1));
3729 if (!$this->db->query($sql)) {
3730 $this->error = $this->db->lasterror();
3734 $sql =
"UPDATE ".$this->db->prefix().$this->table_element_line.
" SET ".$this->db->sanitize($fieldposition).
" = ".((int) ($rang - 1));
3735 $sql .=
' WHERE rowid = '.((int) $rowid);
3736 if (!$this->db->query($sql)) {
3737 $this->error = $this->db->lasterror();
3754 if ($rang >= $max) {
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();
3789 $fieldposition =
'rang';
3790 if (in_array($this->table_element_line, array(
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3791 $fieldposition =
'position';
3794 $sql =
"SELECT " . $this->db->sanitize($fieldposition) .
" FROM ".$this->db->prefix().$this->db->sanitize($this->table_element_line);
3795 $sql .=
" WHERE rowid = ".((int) $rowid);
3797 dol_syslog(get_class($this).
"::getRangOfLine", LOG_DEBUG);
3798 $resql = $this->db->query($sql);
3803 $row = $this->db->fetch_row($resql);
3815 $fieldposition =
'rang';
3816 if (in_array($this->table_element_line, array(
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3817 $fieldposition =
'position';
3820 $sql =
"SELECT rowid FROM ".$this->db->prefix().$this->db->sanitize($this->table_element_line);
3821 $sql .=
" WHERE ".$this->db->sanitize($this->fk_element).
" = ".((int) $this->
id);
3822 $sql .=
" AND " . $this->db->sanitize($fieldposition) .
" = ".((int) $rang);
3823 $resql = $this->db->query($sql);
3828 $row = $this->db->fetch_row($resql);
3842 $positionfield =
'rang';
3843 if (in_array($this->table_element, array(
'bom_bom',
'product_attribute'))) {
3844 $positionfield =
'position';
3847 $sql =
"SELECT max(".$this->db->sanitize($positionfield).
") FROM ".$this->db->prefix().$this->db->sanitize($this->table_element_line);
3848 $sql .=
" WHERE ".$this->db->sanitize($this->fk_element).
" = ".((int) $this->
id);
3851 if ($fk_parent_line) {
3852 $sql .=
" AND fk_parent_line = ".((int) $fk_parent_line);
3855 dol_syslog(get_class($this).
"::line_max", LOG_DEBUG);
3856 $resql = $this->db->query($sql);
3858 $row = $this->db->fetch_row($resql);
3860 if ($fk_parent_line) {
3861 if (!empty($row[0])) {
3884 if (!$this->table_element) {
3885 dol_syslog(get_class($this).
"::update_ref_ext was called on object with property table_element not defined", LOG_ERR);
3889 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
3890 $sql .=
" SET ref_ext = '".$this->db->escape($ref_ext).
"'";
3892 $sql .=
" WHERE ".(isset($this->table_rowid) ? $this->table_rowid :
'rowid').
" = ".((
int) $this->id);
3894 dol_syslog(get_class($this).
"::update_ref_ext", LOG_DEBUG);
3895 if ($this->db->query($sql)) {
3896 $this->ref_ext = $ref_ext;
3899 $this->error = $this->db->error();
3918 if (!$this->table_element) {
3919 $this->error =
'update_note was called on object with property table_element not defined';
3920 dol_syslog(get_class($this).
"::update_note was called on object with property table_element not defined", LOG_ERR);
3923 if (!in_array($suffix, array(
'',
'_public',
'_private'))) {
3924 $this->error =
'update_note Parameter suffix must be empty, \'_private\' or \'_public\'';
3925 dol_syslog(get_class($this).
"::update_note Parameter suffix must be empty, '_private' or '_public'", LOG_ERR);
3929 $newsuffix = $suffix;
3932 if ($this->table_element ==
'product' && $newsuffix ==
'_private') {
3935 if (in_array($this->table_element, array(
'actioncomm',
'adherent',
'advtargetemailing',
'cronjob',
'establishment'))) {
3936 $fieldusermod =
"fk_user_mod";
3937 } elseif ($this->table_element ==
'ecm_files') {
3938 $fieldusermod =
"fk_user_m";
3940 $fieldusermod =
"fk_user_modif";
3942 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
3943 $sql .=
" SET note".$this->db->sanitize($newsuffix).
" = ".(!empty($note) ? (
"'".$this->db->escape($note).
"'") :
"NULL");
3944 $sql .=
", ".$this->db->sanitize($fieldusermod).
" = ".((int) $user->id);
3945 $sql .=
" WHERE rowid = ".((int) $this->
id);
3947 dol_syslog(get_class($this).
"::update_note", LOG_DEBUG);
3948 if ($this->db->query($sql)) {
3949 if ($suffix ==
'_public') {
3950 $this->note_public = $note;
3951 } elseif ($suffix ==
'_private') {
3952 $this->note_private = $note;
3954 $this->note = $note;
3955 $this->note_private = $note;
3957 if (empty($notrigger)) {
3959 switch ($this->element) {
3961 $triggerName =
'COMPANY_MODIFY';
3964 $triggerName =
'BILL_MODIFY';
3966 case 'invoice_supplier':
3967 $triggerName =
'BILL_SUPPLIER_MODIFY';
3970 $triggerName =
'BILLREC_MODIFIY';
3972 case 'expensereport':
3973 $triggerName =
'EXPENSE_REPORT_MODIFY';
3976 $triggerName = (!empty($this->TRIGGER_PREFIX) ? $this->TRIGGER_PREFIX : strtoupper($this->element)) .
'_MODIFY';
3978 $ret = $this->call_trigger($triggerName, $user);
3985 $this->error = $this->db->lasterror();
4016 public function update_price($exclspec = 0, $roundingadjust =
'auto', $nodatabaseupdate = 0, $seller =
null)
4019 global
$conf, $hookmanager, $action;
4021 $parameters = array(
'exclspec' => $exclspec,
'roundingadjust' => $roundingadjust,
'nodatabaseupdate' => $nodatabaseupdate,
'seller' => $seller);
4022 $reshook = $hookmanager->executeHooks(
'updateTotalPrice', $parameters, $this, $action);
4025 } elseif ($reshook < 0) {
4030 $isElementForSupplier =
false;
4031 $roundTotalConstName =
'MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND';
4033 if ($this->element ==
'propal') {
4034 $MODULE =
"MODULE_DISALLOW_UPDATE_PRICE_PROPOSAL";
4035 } elseif ($this->element ==
'commande' || $this->element ==
'order') {
4036 $MODULE =
"MODULE_DISALLOW_UPDATE_PRICE_ORDER";
4037 } elseif ($this->element ==
'facture' || $this->element ==
'invoice') {
4038 $MODULE =
"MODULE_DISALLOW_UPDATE_PRICE_INVOICE";
4039 } elseif ($this->element ==
'facture_fourn' || $this->element ==
'supplier_invoice' || $this->element ==
'invoice_supplier' || $this->element ==
'invoice_supplier_rec') {
4040 $isElementForSupplier =
true;
4041 $MODULE =
"MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_INVOICE";
4042 } elseif ($this->element ==
'order_supplier' || $this->element ==
'supplier_order') {
4043 $isElementForSupplier =
true;
4044 $MODULE =
"MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_ORDER";
4045 } elseif ($this->element ==
'supplier_proposal') {
4046 $isElementForSupplier =
true;
4047 $MODULE =
"MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_PROPOSAL";
4049 if ($isElementForSupplier) {
4050 $roundTotalConstName =
'MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND_SUPPLIER';
4053 if (!empty($MODULE)) {
4056 foreach ($modsactivated as $mod) {
4064 include_once DOL_DOCUMENT_ROOT.
'/core/lib/price.lib.php';
4066 $forcedroundingmode = $roundingadjust;
4067 if ($forcedroundingmode ==
'auto' && isset(
$conf->global->{$roundTotalConstName})) {
4069 } elseif ($forcedroundingmode ==
'auto') {
4070 $forcedroundingmode =
'0';
4075 $multicurrency_tx = !empty($this->multicurrency_tx) ? $this->multicurrency_tx : 1;
4078 $fieldtva =
'total_tva';
4079 $fieldlocaltax1 =
'total_localtax1';
4080 $fieldlocaltax2 =
'total_localtax2';
4081 $fieldup =
'subprice';
4082 $base_price_type =
'HT';
4083 if ($this->element ==
'facture_fourn' || $this->element ==
'invoice_supplier') {
4087 if ($this->element ==
'invoice_supplier_rec') {
4090 if ($this->element ==
'expensereport') {
4094 $forcedroundingmode =
'0';
4095 $fieldup =
'value_unit';
4096 $base_price_type =
'TTC';
4099 $sql =
"SELECT rowid, qty, ".$this->db->sanitize($fieldup).
" as up, remise_percent,";
4100 $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,";
4101 $sql .=
' tva_tx as vatrate, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type,';
4102 $sql .=
' info_bits, product_type,';
4103 if ($this->element ==
'expensereport') {
4104 $sql .=
' comments as description';
4106 $sql .=
' description';
4108 if ($this->table_element_line ==
'facturedet') {
4109 $sql .=
', situation_percent';
4111 $sql .=
', multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc';
4112 $sql .=
" FROM ".$this->db->prefix().$this->db->sanitize($this->table_element_line);
4113 $sql .=
" WHERE ".$this->db->sanitize($this->fk_element).
" = ".((int) $this->
id);
4115 $product_field =
'product_type';
4116 if ($this->table_element_line ==
'contratdet') {
4117 $product_field =
'';
4119 if ($product_field) {
4120 $sql .=
" AND ".$this->db->sanitize($product_field).
" <> 9";
4123 $sql .=
' ORDER by rowid';
4125 dol_syslog(get_class($this).
"::update_price", LOG_DEBUG);
4127 $resql = $this->db->query($sql);
4129 $this->total_ht = 0;
4130 $this->total_tva = 0;
4131 $this->total_localtax1 = 0;
4132 $this->total_localtax2 = 0;
4133 $this->total_ttc = 0;
4134 $total_ht_by_vats = array();
4135 $total_tva_by_vats = array();
4136 $total_ttc_by_vats = array();
4137 $this->multicurrency_total_ht = 0;
4138 $this->multicurrency_total_tva = 0;
4139 $this->multicurrency_total_ttc = 0;
4143 $num = $this->db->num_rows($resql);
4146 $obj = $this->db->fetch_object($resql);
4149 $parameters = array(
'fk_element' => $obj->rowid);
4150 $reshook = $hookmanager->executeHooks(
'changeRoundingMode', $parameters, $this, $action);
4152 if (empty($reshook) && $forcedroundingmode ==
'0') {
4154 $localtax_array = array($obj->localtax1_type, $obj->localtax1_tx, $obj->localtax2_type, $obj->localtax2_tx);
4155 $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);
4157 $diff_when_using_price_ht =
price2num((
float) $tmpcal[1] - $obj->total_tva,
'MT', 1);
4158 $diff_on_current_total =
price2num($obj->total_ttc - $obj->total_ht - $obj->total_tva - $obj->total_localtax1 - $obj->total_localtax2,
'MT', 1);
4162 if ($diff_on_current_total) {
4164 $sqlfix =
"UPDATE ".$this->db->prefix().$this->table_element_line;
4165 $sqlfix .=
" SET ".$this->db->sanitize($fieldtva).
" = ".
price2num((
float) $tmpcal[1]).
", total_ttc = ".
price2num((
float) $tmpcal[2]);
4166 $sqlfix .=
", multicurrency_total_tva = ".price2num((
float) $tmpcal[17]).
", multicurrency_total_ttc = ".
price2num((
float) $tmpcal[18]);
4167 $sqlfix .=
" WHERE rowid = ".((int) $obj->rowid);
4168 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);
4169 $resqlfix = $this->db->query($sqlfix);
4173 $obj->total_tva = $tmpcal[1];
4174 $obj->total_ttc = $tmpcal[2];
4175 $obj->multicurrency_total_tva = $tmpcal[17];
4176 $obj->multicurrency_total_ttc = $tmpcal[18];
4177 } elseif ($diff_when_using_price_ht) {
4181 if ((
float) $tmpcal[0] == (
float) $obj->total_ht) {
4184 if ($obj->description !=
'(DEPOSIT)' && !
getDolGlobalInt(
'MAIN_DISABLE_AUTOFIX_CORRUPTED_LINES_WHEN_TOTAL_DOES_NOT_MATCH_RECALCULATION_FROM_UP')) {
4188 $sqlfix =
"UPDATE ".$this->db->prefix().$this->table_element_line;
4189 $sqlfix .=
" SET ".$this->db->sanitize($fieldtva).
" = ".
price2num((
float) $tmpcal[1]).
", total_ttc = ".
price2num((
float) $tmpcal[2]);
4190 $sqlfix .=
", multicurrency_total_tva = ".price2num((
float) $tmpcal[17]).
", multicurrency_total_ttc = ".
price2num((
float) $tmpcal[18]);
4191 $sqlfix .=
" WHERE rowid = ".((int) $obj->rowid);
4193 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);
4195 $resqlfix = $this->db->query($sqlfix);
4199 $obj->total_tva = $tmpcal[1];
4200 $obj->total_ttc = $tmpcal[2];
4201 $obj->multicurrency_total_tva = $tmpcal[17];
4202 $obj->multicurrency_total_ttc = $tmpcal[18];
4208 $this->total_ht += $obj->total_ht;
4209 $this->total_tva += $obj->total_tva;
4210 $this->total_localtax1 += $obj->total_localtax1;
4211 $this->total_localtax2 += $obj->total_localtax2;
4212 $this->total_ttc += $obj->total_ttc;
4213 $this->multicurrency_total_ht += $obj->multicurrency_total_ht;
4214 $this->multicurrency_total_tva += $obj->multicurrency_total_tva;
4215 $this->multicurrency_total_ttc += $obj->multicurrency_total_ttc;
4217 if (!isset($total_ht_by_vats[$obj->vatrate])) {
4218 $total_ht_by_vats[$obj->vatrate] = 0;
4220 if (!isset($total_tva_by_vats[$obj->vatrate])) {
4221 $total_tva_by_vats[$obj->vatrate] = 0;
4223 if (!isset($total_ttc_by_vats[$obj->vatrate])) {
4224 $total_ttc_by_vats[$obj->vatrate] = 0;
4226 $total_ht_by_vats[$obj->vatrate] += $obj->total_ht;
4227 $total_tva_by_vats[$obj->vatrate] += $obj->total_tva;
4228 $total_ttc_by_vats[$obj->vatrate] += $obj->total_ttc;
4230 if ($forcedroundingmode ==
'1') {
4231 if ($base_price_type ==
'TTC') {
4232 $tmpvat =
price2num($total_ttc_by_vats[$obj->vatrate] * $obj->vatrate / (100 + $obj->vatrate),
'MT', 1);
4234 $tmpvat =
price2num($total_ht_by_vats[$obj->vatrate] * $obj->vatrate / 100,
'MT', 1);
4236 $diff =
price2num($total_tva_by_vats[$obj->vatrate] - (
float) $tmpvat,
'MT', 1);
4239 $maxdiff = (10 * pow(10, -1 *
getDolGlobalInt(
'MAIN_MAX_DECIMALS_TOT', 0)));
4240 if (abs((
float) $diff) > $maxdiff) {
4242 $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.';
4244 $this->error = $errmsg;
4249 if ($base_price_type ==
'TTC') {
4250 $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);
4251 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);
4253 $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);
4254 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);
4257 $resqlfix = $this->db->query($sqlfix);
4263 $this->total_tva = (float)
price2num($this->total_tva - (
float) $diff,
'', 1);
4264 $total_tva_by_vats[$obj->vatrate] = (float)
price2num($total_tva_by_vats[$obj->vatrate] - (
float) $diff,
'', 1);
4265 if ($base_price_type ==
'TTC') {
4266 $this->total_ht = (float)
price2num($this->total_ht + (
float) $diff,
'', 1);
4267 $total_ht_by_vats[$obj->vatrate] = (float)
price2num($total_ht_by_vats[$obj->vatrate] + (
float) $diff,
'', 1);
4269 $this->total_ttc = (float)
price2num($this->total_ttc - (
float) $diff,
'', 1);
4270 $total_ttc_by_vats[$obj->vatrate] = (float)
price2num($total_ttc_by_vats[$obj->vatrate] - (
float) $diff,
'', 1);
4280 $this->total_ttc += isset($this->revenuestamp) ? $this->revenuestamp : 0;
4282 $this->multicurrency_total_ttc += isset($this->revenuestamp) ? ($this->revenuestamp * $multicurrency_tx) : 0;
4285 if (!empty($this->situation_cycle_ref) && !empty($this->situation_counter) && $this->situation_counter > 1 && method_exists($this,
'get_prev_sits')) {
4286 '@phan-var-force Facture $this';
4287 include_once DOL_DOCUMENT_ROOT.
'/compta/facture/class/facture.class.php';
4290 $prev_sits = $this->get_prev_sits();
4292 foreach ($prev_sits as $sit) {
4293 $this->total_ht -= $sit->total_ht;
4294 $this->total_tva -= $sit->total_tva;
4295 $this->total_localtax1 -= $sit->total_localtax1;
4296 $this->total_localtax2 -= $sit->total_localtax2;
4297 $this->total_ttc -= $sit->total_ttc;
4298 $this->multicurrency_total_ht -= $sit->multicurrency_total_ht;
4299 $this->multicurrency_total_tva -= $sit->multicurrency_total_tva;
4300 $this->multicurrency_total_ttc -= $sit->multicurrency_total_ttc;
4307 $this->total_ht = (float)
price2num($this->total_ht);
4308 $this->total_tva = (float)
price2num($this->total_tva);
4309 $this->total_localtax1 = (float)
price2num($this->total_localtax1);
4310 $this->total_localtax2 = (float)
price2num($this->total_localtax2);
4311 $this->total_ttc = (float)
price2num($this->total_ttc);
4313 $this->db->free($resql);
4316 $fieldht =
'total_ht';
4318 $fieldlocaltax1 =
'localtax1';
4319 $fieldlocaltax2 =
'localtax2';
4320 $fieldttc =
'total_ttc';
4322 if (in_array($this->element, array(
'propal',
'commande',
'facture',
'facturerec',
'supplier_proposal',
'order_supplier',
'facture_fourn',
'invoice_supplier',
'invoice_supplier_rec',
'expensereport'))) {
4323 $fieldtva =
'total_tva';
4326 if (!$error && empty($nodatabaseupdate)) {
4327 $sql =
"UPDATE ".$this->db->prefix().$this->table_element.
' SET';
4328 $sql .=
" ".$this->db->sanitize($fieldht).
" = ".((float)
price2num($this->total_ht,
'MT', 1)).
",";
4329 $sql .=
" ".$this->db->sanitize($fieldtva).
" = ".((float)
price2num($this->total_tva,
'MT', 1)).
",";
4330 $sql .=
" ".$this->db->sanitize($fieldlocaltax1).
" = ".((float)
price2num($this->total_localtax1,
'MT', 1)).
",";
4331 $sql .=
" ".$this->db->sanitize($fieldlocaltax2).
" = ".((float)
price2num($this->total_localtax2,
'MT', 1)).
",";
4332 $sql .=
" ".$this->db->sanitize($fieldttc).
" = ".((float)
price2num($this->total_ttc,
'MT', 1));
4333 $sql .=
", multicurrency_total_ht = ".((float)
price2num($this->multicurrency_total_ht,
'MT', 1));
4334 $sql .=
", multicurrency_total_tva = ".((float)
price2num($this->multicurrency_total_tva,
'MT', 1));
4335 $sql .=
", multicurrency_total_ttc = ".((float)
price2num($this->multicurrency_total_ttc,
'MT', 1));
4336 $sql .=
" WHERE rowid = ".((int) $this->
id);
4338 dol_syslog(get_class($this).
"::update_price", LOG_DEBUG);
4339 $resql = $this->db->query($sql);
4343 $this->error = $this->db->lasterror();
4344 $this->errors[] = $this->db->lasterror();
4349 $this->db->commit();
4352 $this->db->rollback();
4372 public function add_object_linked($origin =
null, $origin_id =
null, $f_user =
null, $notrigger = 0)
4375 global $user, $hookmanager, $action;
4378 if (empty($this->origin_type) && !empty($this->origin)) {
4379 $this->origin_type = $this->origin;
4381 $origin = (!empty($origin) ? $origin : $this->origin_type);
4382 $origin_id = (!empty($origin_id) ? $origin_id : $this->origin_id);
4383 $f_user = isset($f_user) ? $f_user : $user;
4386 if ($origin ==
'order') {
4387 $origin =
'commande';
4389 if ($origin ==
'invoice') {
4390 $origin =
'facture';
4392 if ($origin ==
'invoice_template') {
4393 $origin =
'facturerec';
4395 if ($origin ==
'supplierorder') {
4396 $origin =
'order_supplier';
4400 $targettype = $this->getElementType();
4402 $parameters = array(
'targettype' => $targettype);
4404 $reshook = $hookmanager->executeHooks(
'setLinkedObjectSourceTargetType', $parameters, $this, $action);
4406 if (!empty($hookmanager->resArray[
'targettype'])) {
4407 $targettype = $hookmanager->resArray[
'targettype'];
4414 $sql =
"INSERT INTO " . $this->db->prefix() .
"element_element (";
4415 $sql .=
"fk_source";
4416 $sql .=
", sourcetype";
4417 $sql .=
", fk_target";
4418 $sql .=
", targettype";
4419 $sql .=
") VALUES (";
4420 $sql .= ((int) $origin_id);
4421 $sql .=
", '" . $this->db->escape($origin) .
"'";
4422 $sql .=
", " . ((int) $this->
id);
4423 $sql .=
", '" . $this->db->escape($targettype) .
"'";
4426 dol_syslog(get_class($this) .
"::add_object_linked", LOG_DEBUG);
4427 if ($this->db->query($sql)) {
4431 if ($origin ===
'order_supplier' && $targettype ===
'invoice_supplier' && $this->element ===
'invoice_supplier' && (
int) $origin_id > 0 && (
int) $this->
id > 0) {
4432 $sourceinvoices = array();
4434 $sqlsources =
"SELECT DISTINCT rc.fk_invoice_supplier_source as rowid";
4435 $sqlsources .=
" FROM ".$this->db->prefix().
"societe_remise_except as rc";
4436 $sqlsources .=
" WHERE rc.fk_invoice_supplier = ".((int) $this->
id);
4437 $sqlsources .=
" AND rc.fk_invoice_supplier_source IS NOT NULL";
4439 $resqlsources = $this->db->query($sqlsources);
4440 if ($resqlsources) {
4441 while ($objsrc = $this->db->fetch_object($resqlsources)) {
4442 $srcid = (int) $objsrc->rowid;
4443 if ($srcid > 0 && $srcid !== (
int) $this->
id) {
4444 $sourceinvoices[$srcid] = $srcid;
4448 dol_syslog(get_class($this).
"::add_object_linked Failed to read supplier invoice discounts sources", LOG_WARNING);
4451 if (!empty($sourceinvoices)) {
4452 $existing = array();
4453 $sourcelist = implode(
',', $sourceinvoices);
4455 $sqlexists =
"SELECT fk_target";
4456 $sqlexists .=
" FROM ".$this->db->prefix().
"element_element";
4457 $sqlexists .=
" WHERE fk_source = ".((int) $origin_id);
4458 $sqlexists .=
" AND sourcetype = '".$this->db->escape($origin).
"'";
4459 $sqlexists .=
" AND targettype = '".$this->db->escape($targettype).
"'";
4460 $sqlexists .=
" AND fk_target IN (".$this->db->sanitize($sourcelist).
")";
4462 $resqlexists = $this->db->query($sqlexists);
4464 while ($objexist = $this->db->fetch_object($resqlexists)) {
4465 $existing[(int) $objexist->fk_target] = 1;
4468 dol_syslog(get_class($this).
"::add_object_linked Failed to read existing linked supplier invoices", LOG_WARNING);
4471 foreach ($sourceinvoices as $srcid) {
4472 if (!empty($existing[(
int) $srcid])) {
4476 $sqladd =
"INSERT INTO " . $this->db->prefix() .
"element_element (fk_source, sourcetype, fk_target, targettype)";
4477 $sqladd .=
" VALUES (".((int) $origin_id).
", '".$this->db->escape($origin).
"', ".((int) $srcid).
", '".$this->db->escape($targettype).
"')";
4478 $this->db->query($sqladd);
4485 $this->context[
'link_origin'] = $origin;
4486 $this->context[
'link_origin_id'] = $origin_id;
4488 $result = $this->call_trigger(
'OBJECT_LINK_INSERT', $f_user);
4495 $this->error = $this->db->lasterror();
4500 $this->db->commit();
4503 $this->db->rollback();
4517 $coreModule = array(
'knowledgemanagement',
'partnership',
'workstation',
'ticket',
'recruitment',
'eventorganization',
'asset');
4519 return ((!empty($this->module) && !in_array($this->module, $coreModule)) ? $this->module.
'_' :
'').$this->element;
4545 public function fetchObjectLinked($sourceid =
null, $sourcetype =
'', $targetid =
null, $targettype =
'', $clause =
'OR', $alsosametype = 1, $orderby =
'sourcetype', $loadalsoobjects = 1)
4547 global $hookmanager, $action;
4552 if ($this->
id > 0 && !empty($this->linkedObjectsFullLoaded[$this->
id])) {
4556 $this->linkedObjectsIds = array();
4557 $this->linkedObjects = array();
4560 $parameters = array(
4561 'sourceid' => $sourceid,
4562 'sourcetype' => $sourcetype,
4563 'targetid' => $targetid,
4564 'targettype' => $targettype,
4565 'clause' => $clause,
4566 'alsosametype' => $alsosametype,
4567 'orderby' => $orderby,
4568 'loadalsoobjects' => $loadalsoobjects
4570 $reshook = $hookmanager->executeHooks(
'fetchObjectLinked', $parameters, $this, $action);
4575 $justsource =
false;
4576 $justtarget =
false;
4577 $withtargettype =
false;
4578 $withsourcetype =
false;
4581 if (is_object($hookmanager)) {
4582 $parameters = array(
'sourcetype' => $sourcetype,
'sourceid' => $sourceid,
'targettype' => $targettype,
'targetid' => $targetid);
4583 $reshook = $hookmanager->executeHooks(
'setLinkedObjectSourceTargetType', $parameters, $this, $action);
4585 if (!empty($hookmanager->resArray[
'sourcetype'])) {
4586 $sourcetype = $hookmanager->resArray[
'sourcetype'];
4588 if (!empty($hookmanager->resArray[
'sourceid'])) {
4589 $sourceid = $hookmanager->resArray[
'sourceid'];
4591 if (!empty($hookmanager->resArray[
'targettype'])) {
4592 $targettype = $hookmanager->resArray[
'targettype'];
4594 if (!empty($hookmanager->resArray[
'targetid'])) {
4595 $targetid = $hookmanager->resArray[
'targetid'];
4600 if (!empty($sourceid) && !empty($sourcetype) && empty($targetid)) {
4602 if (!empty($targettype)) {
4603 $withtargettype =
true;
4606 if (!empty($targetid) && !empty($targettype) && empty($sourceid)) {
4608 if (!empty($sourcetype)) {
4609 $withsourcetype =
true;
4613 $sourceid = (!empty($sourceid) ? $sourceid :
$this->id);
4614 $targetid = (!empty($targetid) ? $targetid :
$this->id);
4615 $sourcetype = (!empty($sourcetype) ? $sourcetype : $this->getElementType());
4616 $targettype = (!empty($targettype) ? $targettype : $this->getElementType());
4625 $sql =
"SELECT rowid, fk_source, sourcetype, fk_target, targettype";
4626 $sql .=
" FROM ".$this->db->prefix().
"element_element";
4628 if ($justsource || $justtarget) {
4630 $sql .=
"fk_source = ".((int) $sourceid).
" AND sourcetype = '".$this->db->escape($sourcetype).
"'";
4631 if ($withtargettype) {
4632 $sql .=
" AND targettype = '".$this->db->escape($targettype).
"'";
4634 } elseif ($justtarget) {
4635 $sql .=
"fk_target = ".((int) $targetid).
" AND targettype = '".$this->db->escape($targettype).
"'";
4636 if ($withsourcetype) {
4637 $sql .=
" AND sourcetype = '".$this->db->escape($sourcetype).
"'";
4641 $sql .=
"(fk_source = ".((int) $sourceid).
" AND sourcetype = '".$this->db->escape($sourcetype).
"')";
4642 $sql .=
" ".$this->db->sanitize($clause).
" (fk_target = ".((int) $targetid).
" AND targettype = '".$this->db->escape($targettype).
"')";
4643 if ($loadalsoobjects && $this->
id > 0 && $sourceid == $this->
id && $sourcetype == $this->element && $targetid == $this->
id && $targettype == $this->element && $clause ==
'OR') {
4644 $this->linkedObjectsFullLoaded[
$this->id] =
true;
4647 $sql .= $this->db->order($orderby);
4649 dol_syslog(get_class($this).
"::fetchObjectLink", LOG_DEBUG);
4651 $resql = $this->db->query($sql);
4653 $num = $this->db->num_rows($resql);
4656 $obj = $this->db->fetch_object($resql);
4657 if ($justsource || $justtarget) {
4659 $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
4660 } elseif ($justtarget) {
4661 $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
4664 if ($obj->fk_source == $sourceid && $obj->sourcetype == $sourcetype) {
4665 $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
4667 if ($obj->fk_target == $targetid && $obj->targettype == $targettype) {
4668 $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
4674 if (!empty($this->linkedObjectsIds)) {
4675 $tmparray = $this->linkedObjectsIds;
4676 foreach ($tmparray as $objecttype => $objectids) {
4678 $element = $element_properties[
'element'];
4679 $classPath = $element_properties[
'classpath'];
4680 $classFile = $element_properties[
'classfile'];
4681 $className = $element_properties[
'classname'];
4682 $module = $element_properties[
'module'];
4685 if (
isModEnabled($module) && (($element != $this->element) || $alsosametype)) {
4686 if ($loadalsoobjects && (is_numeric($loadalsoobjects) || ($loadalsoobjects === $objecttype))) {
4688 if (class_exists($className)) {
4689 foreach ($objectids as $i => $objectid) {
4690 $object =
new $className($this->db);
4691 '@phan-var-force CommonObject $object';
4692 $ret =
$object->fetch($objectid);
4694 $this->linkedObjects[$objecttype][$i] =
$object;
4700 unset($this->linkedObjectsIds[$objecttype]);
4719 if ($this->
id > 0 && !empty($this->linkedObjectsFullLoaded[$this->
id])) {
4720 unset($this->linkedObjectsFullLoaded[$this->
id]);
4738 public function updateObjectLinked($sourceid =
null, $sourcetype =
'', $targetid =
null, $targettype =
'', $f_user =
null, $notrigger = 0)
4741 $updatesource =
false;
4742 $updatetarget =
false;
4743 $f_user = isset($f_user) ? $f_user : $user;
4746 if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) {
4747 $updatesource =
true;
4748 } elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) {
4749 $updatetarget =
true;
4755 $sql =
"UPDATE " . $this->db->prefix() .
"element_element SET ";
4756 if ($updatesource) {
4757 $sql .=
"fk_source = " . ((int) $sourceid);
4758 $sql .=
", sourcetype = '" . $this->db->escape($sourcetype) .
"'";
4759 $sql .=
" WHERE fk_target = " . ((int) $this->
id);
4760 $sql .=
" AND targettype = '" . $this->db->escape($this->element) .
"'";
4761 } elseif ($updatetarget) {
4762 $sql .=
"fk_target = " . ((int) $targetid);
4763 $sql .=
", targettype = '" . $this->db->escape($targettype) .
"'";
4764 $sql .=
" WHERE fk_source = " . ((int) $this->
id);
4765 $sql .=
" AND sourcetype = '" . $this->db->escape($this->element) .
"'";
4768 dol_syslog(get_class($this) .
"::updateObjectLinked", LOG_DEBUG);
4769 if ($this->db->query($sql)) {
4772 $this->context[
'link_source_id'] = $sourceid;
4773 $this->context[
'link_source_type'] = $sourcetype;
4774 $this->context[
'link_target_id'] = $targetid;
4775 $this->context[
'link_target_type'] = $targettype;
4777 $result = $this->call_trigger(
'OBJECT_LINK_MODIFY', $f_user);
4784 $this->error = $this->db->lasterror();
4789 $this->db->commit();
4792 $this->db->rollback();
4810 public function deleteObjectLinked($sourceid =
null, $sourcetype =
'', $targetid =
null, $targettype =
'', $rowid = 0, $f_user =
null, $notrigger = 0)
4813 $deletesource =
false;
4814 $deletetarget =
false;
4815 $f_user = isset($f_user) ? $f_user : $user;
4817 if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) {
4818 $deletesource =
true;
4819 } elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) {
4820 $deletetarget =
true;
4823 $element = $this->getElementType();
4824 $sourceid = (!empty($sourceid) ? $sourceid :
$this->id);
4825 $sourcetype = (!empty($sourcetype) ? $sourcetype : $element);
4826 $targetid = (!empty($targetid) ? $targetid :
$this->id);
4827 $targettype = (!empty($targettype) ? $targettype : $element);
4833 $this->context[
'link_id'] = $rowid;
4834 $this->context[
'link_source_id'] = $sourceid;
4835 $this->context[
'link_source_type'] = $sourcetype;
4836 $this->context[
'link_target_id'] = $targetid;
4837 $this->context[
'link_target_type'] = $targettype;
4839 $result = $this->call_trigger(
'OBJECT_LINK_DELETE', $f_user);
4847 $sql =
"DELETE FROM " . $this->db->prefix() .
"element_element";
4850 $sql .=
" rowid = " . ((int) $rowid);
4852 if ($deletesource) {
4853 $sql .=
" fk_source = " . ((int) $sourceid) .
" AND sourcetype = '" . $this->db->escape($sourcetype) .
"'";
4854 $sql .=
" AND fk_target = " . ((int) $this->
id) .
" AND targettype = '" . $this->db->escape($element) .
"'";
4855 } elseif ($deletetarget) {
4856 $sql .=
" fk_target = " . ((int) $targetid) .
" AND targettype = '" . $this->db->escape($targettype) .
"'";
4857 $sql .=
" AND fk_source = " . ((int) $this->
id) .
" AND sourcetype = '" . $this->db->escape($element) .
"'";
4859 $sql .=
" (fk_source = " . ((int) $this->
id) .
" AND sourcetype = '" . $this->db->escape($element) .
"')";
4861 $sql .=
" (fk_target = " . ((int) $this->
id) .
" AND targettype = '" . $this->db->escape($element) .
"')";
4865 dol_syslog(get_class($this) .
"::deleteObjectLinked", LOG_DEBUG);
4866 if (!$this->db->query($sql)) {
4867 $this->error = $this->db->lasterror();
4868 $this->errors[] = $this->error;
4874 $this->db->commit();
4877 $this->db->rollback();
4893 if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
4896 if (!preg_match(
'/^[_a-zA-Z0-9]+$/', $field_select)) {
4897 dol_syslog(
'Invalid value $field_select for parameter '.$field_select.
' in call to getAllItemsLinkedByObjectID(). Must be a single field name.', LOG_ERR);
4902 $sql =
"SELECT ".$db->sanitize($field_select).
" FROM ".
$db->prefix().$db->sanitize($table_element).
" WHERE ".
$db->sanitize($field_where).
" = ".((int) $fk_object_where);
4903 $resql =
$db->query($sql);
4906 if (!empty($resql)) {
4907 while ($res =
$db->fetch_object($resql)) {
4908 $TRes[] = $res->{$field_select};
4925 if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
4931 $sql =
"SELECT COUNT(*) as nb FROM ".$db->prefix().$db->sanitize($table_element).
" WHERE ".
$db->sanitize($field_where).
" = ".((int) $fk_object_where);
4932 $resql =
$db->query($sql);
4935 $res =
$db->fetch_object($resql);
4954 if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
4960 $sql =
"DELETE FROM ".$db->prefix().$table_element.
" WHERE ".
$db->sanitize($field_where).
" = ".((int) $fk_object_where);
4961 $resql =
$db->query($sql);
4963 if (empty($resql)) {
4981 public function setStatut($status, $elementId =
null, $elementType =
'', $trigkey =
'', $fieldstatus =
'')
4985 $savElementId = $elementId;
4987 $elementId = (!empty($elementId) ? $elementId :
$this->id);
4988 $elementTable = (!empty($elementType) ? $elementType : $this->table_element);
4992 if (empty($fieldstatus)) {
4993 if ($elementTable ==
'facture_rec') {
4994 $fieldstatus =
"suspended";
4996 if ($elementTable ==
'mailing') {
4997 $fieldstatus =
"statut";
4999 if ($elementTable ==
'cronjob') {
5000 $fieldstatus =
"status";
5002 if ($elementTable ==
'user') {
5003 $fieldstatus =
"statut";
5005 if ($elementTable ==
'expensereport') {
5006 $fieldstatus =
"fk_statut";
5008 if ($elementTable ==
'receptiondet_batch') {
5009 $fieldstatus =
"status";
5011 if ($elementTable ==
'prelevement_bons') {
5012 $fieldstatus =
"statut";
5014 if ($elementTable ==
'bank_account') {
5015 $fieldstatus =
"clos";
5017 if (isset($this->fields) && is_array($this->fields) && array_key_exists(
'status', $this->fields)) {
5018 $fieldstatus =
'status';
5021 if (empty($fieldstatus)) {
5022 $fieldstatus =
'fk_statut';
5026 $sql =
"UPDATE ".$this->db->prefix().$this->db->sanitize($elementTable);
5027 $sql .=
" SET ".$this->db->sanitize($fieldstatus).
" = ".((int) $status);
5030 if ($status == 1 && in_array($elementTable, array(
'expensereport',
'inventory'))) {
5031 $sql .=
", fk_user_valid = ".((int) $user->id);
5033 if ($status == 1 && in_array($elementTable, array(
'expensereport'))) {
5034 $sql .=
", date_valid = '".$this->db->idate(
dol_now()).
"'";
5036 if ($status == 1 && in_array($elementTable, array(
'inventory'))) {
5037 $sql .=
", date_validation = '".$this->db->idate(
dol_now()).
"'";
5039 $sql .=
" WHERE rowid = ".((int) $elementId);
5040 $sql .=
" AND ".$this->db->sanitize($fieldstatus).
" <> ".((int) $status);
5042 dol_syslog(get_class($this).
"::setStatut", LOG_DEBUG);
5043 $resql = $this->db->query($sql);
5047 $nb_rows_affected = $this->db->affected_rows($resql);
5049 if ($nb_rows_affected > 0) {
5050 if (empty($trigkey)) {
5052 if ($this->element ==
'supplier_proposal' && $status == 2) {
5053 $trigkey =
'SUPPLIER_PROPOSAL_SIGN';
5055 if ($this->element ==
'supplier_proposal' && $status == 3) {
5056 $trigkey =
'SUPPLIER_PROPOSAL_REFUSE';
5058 if ($this->element ==
'supplier_proposal' && $status == 4) {
5059 $trigkey =
'SUPPLIER_PROPOSAL_CLOSE';
5061 if ($this->element ==
'fichinter' && $status == 3) {
5062 $trigkey =
'FICHINTER_CLASSIFY_DONE';
5064 if ($this->element ==
'fichinter' && $status == 2) {
5065 $trigkey =
'FICHINTER_CLASSIFY_BILLED';
5067 if ($this->element ==
'fichinter' && $status == 1) {
5068 $trigkey =
'FICHINTER_CLASSIFY_UNBILLED';
5072 $this->context = array_merge($this->context, array(
'newstatus' => $status));
5074 if ($trigkey && $trigkey !=
'none') {
5078 $result = $this->call_trigger($trigkey, $user);
5089 $this->db->commit();
5091 if (empty($savElementId)) {
5093 if ($fieldstatus ==
'dispute_status') {
5094 $this->dispute_status = $status;
5095 } elseif ($fieldstatus ==
'tosell') {
5097 } elseif ($fieldstatus ==
'tobuy') {
5098 $this->status_buy = $status;
5099 } elseif ($fieldstatus ==
'tobatch') {
5100 $this->status_batch = $status;
5108 $this->db->rollback();
5109 dol_syslog(get_class($this).
"::setStatut ".$this->error, LOG_ERR);
5113 $this->error = $this->db->lasterror();
5114 $this->db->rollback();
5129 if (empty(
$id) && empty($ref)) {
5139 $sql =
"SELECT rowid, canvas";
5140 $sql .=
" FROM ".$this->db->prefix().$this->table_element;
5141 $sql .=
" WHERE entity IN (".getEntity($this->element).
")";
5143 $sql .=
" AND rowid = ".((int)
$id);
5146 $sql .=
" AND ref = '".$this->db->escape($ref).
"'";
5149 $resql = $this->db->query($sql);
5151 $obj = $this->db->fetch_object($resql);
5153 $this->canvas = $obj->canvas;
5173 $sql =
"SELECT special_code FROM ".$this->db->prefix().$this->db->sanitize($this->table_element_line);
5174 $sql .=
" WHERE rowid = ".((int) $lineid);
5175 $resql = $this->db->query($sql);
5177 $row = $this->db->fetch_row($resql);
5178 return (!empty($row[0]) ? $row[0] : 0);
5201 if (!isset($this->childtables) || !is_array($this->childtables) || count($this->childtables) == 0) {
5202 dol_print_error(
null,
'Called isObjectUsed on a class with property this->childtables not defined');
5206 $arraytoscan = $this->childtables;
5208 $tmparray = array_keys($this->childtables);
5209 if (is_numeric($tmparray[0])) {
5210 $arraytoscan = array_flip($this->childtables);
5215 foreach ($arraytoscan as $table => $element) {
5219 if (isset($element[
'enabled']) && !empty($element[
'enabled'])) {
5220 $enabled = (int)
dol_eval((
string) $element[
'enabled'], 1);
5221 if (empty($enabled)) {
5227 $sql =
"SELECT COUNT(*) as nb";
5228 $sql .=
" FROM ".$this->db->prefix().$this->db->sanitize($table).
" as c";
5229 if (!empty($element[
'parent']) && !empty($element[
'parentkey'])) {
5230 $sql .=
", ".$this->db->prefix().$this->db->sanitize($element[
'parent']).
" as p";
5232 if (!empty($element[
'fk_element'])) {
5233 $sql .=
" WHERE c.".$this->db->sanitize($element[
'fk_element']).
" = ".((int)
$id);
5235 $sql .=
" WHERE c.".$this->db->sanitize($this->fk_element).
" = ".((int)
$id);
5237 if (!empty($element[
'parent']) && !empty($element[
'parentkey'])) {
5238 $sql .=
" AND c.".$this->db->sanitize($element[
'parentkey']).
" = p.rowid";
5240 if (!empty($element[
'parent']) && !empty($element[
'parenttypefield']) && !empty($element[
'parenttypevalue'])) {
5241 $sql .=
" AND c.".$this->db->sanitize($element[
'parenttypefield']).
" = '".$this->db->escape($element[
'parenttypevalue']).
"'";
5243 if (!empty($entity)) {
5244 if (!empty($element[
'parent']) && !empty($element[
'parentkey'])) {
5245 $sql .=
" AND p.entity = ".((int) $entity);
5247 $sql .=
" AND c.entity = ".((int) $entity);
5252 $resql = $this->db->query($sql);
5254 $obj = $this->db->fetch_object($resql);
5256 $langs->load(
"errors");
5258 $haschild += (int) $obj->nb;
5259 if (is_numeric($element)) {
5260 $this->errors[] = $langs->transnoentitiesnoconv(
"ErrorRecordHasAtLeastOneChildOfType", method_exists($this,
'getNomUrl') ? $this->getNomUrl() : $this->ref, $table);
5261 } elseif (is_string($element)) {
5262 $this->errors[] = $langs->transnoentitiesnoconv(
"ErrorRecordHasAtLeastOneChildOfType", method_exists($this,
'getNomUrl') ? $this->getNomUrl() : $this->ref, $langs->transnoentitiesnoconv($element));
5264 $this->errors[] = $langs->transnoentitiesnoconv(
"ErrorRecordHasAtLeastOneChildOfType", method_exists($this,
'getNomUrl') ? $this->getNomUrl() : $this->ref, $langs->transnoentitiesnoconv($element[
'name']));
5269 $this->errors[] = $this->db->lasterror();
5274 if ($haschild > 0) {
5275 $this->errors[] =
"ErrorRecordHasChildren";
5292 foreach ($this->lines as $key => $val) {
5294 if ($predefined == -1) {
5297 if ($predefined == 1 && $val->fk_product > 0) {
5300 if ($predefined == 0 && $val->fk_product <= 0) {
5303 if ($predefined == 2 && $val->fk_product > 0 && $val->product_type == 0) {
5306 if ($predefined == 3 && $val->fk_product > 0 && $val->product_type == 1) {
5313 dol_syslog(get_class($this).
'::hasProductsOrServices we found '.$nb.
' qualified lines of products/servcies');
5324 if (!empty($this->table_element_line) && ($this->table_element_line !=
'expeditiondet')) {
5325 $total_discount = 0.00;
5327 $sql =
"SELECT subprice as pu_ht, qty, remise_percent, total_ht";
5328 $sql .=
" FROM ".$this->db->prefix().$this->table_element_line;
5329 $sql .=
" WHERE ".$this->db->sanitize($this->fk_element).
" = ".((int) $this->
id);
5331 dol_syslog(get_class($this).
'::getTotalDiscount', LOG_DEBUG);
5332 $resql = $this->db->query($sql);
5334 $num = $this->db->num_rows($resql);
5337 $obj = $this->db->fetch_object($resql);
5339 $pu_ht = $obj->pu_ht;
5341 $total_ht = $obj->total_ht;
5343 $total_discount_line = (float)
price2num(($pu_ht * $qty) - $total_ht,
'MT');
5344 $total_discount += $total_discount_line;
5351 return (
float)
price2num($total_discount);
5373 if (empty($this->lines)) {
5374 return array(
'weight' => $totalWeight,
'volume' => $totalVolume,
'ordered' => $totalOrdered,
'toship' => $totalToShip);
5377 foreach ($this->lines as $line) {
5378 if (isset($line->qty_asked)) {
5379 $totalOrdered += $line->qty_asked;
5381 if (isset($line->qty_shipped)) {
5382 $totalToShip += $line->qty_shipped;
5383 } elseif ($line->element ==
'commandefournisseurdispatch' && isset($line->qty)) {
5384 if (empty($totalToShip)) {
5387 $totalToShip += $line->qty;
5391 if ($this->element ==
'shipping') {
5393 $qty = $line->qty_shipped ? $line->qty_shipped : 0;
5395 $qty = $line->qty ? $line->qty : 0;
5398 $weight = !empty($line->weight) ? $line->weight : 0;
5399 ($weight == 0 && !empty($line->product->weight)) ? $weight = $line->product->weight : 0;
5400 $volume = !empty($line->volume) ? $line->volume : 0;
5401 ($volume == 0 && !empty($line->product->volume)) ? $volume = $line->product->volume : 0;
5403 $weight_units = !empty($line->weight_units) ? $line->weight_units : 0;
5404 ($weight_units == 0 && !empty($line->product->weight_units)) ? $weight_units = $line->product->weight_units : 0;
5405 $volume_units = !empty($line->volume_units) ? $line->volume_units : 0;
5406 ($volume_units == 0 && !empty($line->product->volume_units)) ? $volume_units = $line->product->volume_units : 0;
5410 if (!empty($weight_units)) {
5411 $weightUnit = $weight_units;
5413 if (!empty($volume_units)) {
5414 $volumeUnit = $volume_units;
5417 if (empty($totalWeight)) {
5420 if (empty($totalVolume)) {
5425 if ($weight_units < 50) {
5426 $trueWeightUnit = pow(10, $weightUnit);
5427 $totalWeight += $weight * $qty * $trueWeightUnit;
5429 if ($weight_units == 99) {
5431 $trueWeightUnit = 0.45359237;
5432 $totalWeight += $weight * $qty * $trueWeightUnit;
5433 } elseif ($weight_units == 98) {
5435 $trueWeightUnit = 0.0283495;
5436 $totalWeight += $weight * $qty * $trueWeightUnit;
5438 $totalWeight += $weight * $qty;
5441 if ($volume_units < 50) {
5443 $trueVolumeUnit = pow(10, $volumeUnit);
5445 $totalVolume += $volume * $qty * $trueVolumeUnit;
5447 $totalVolume += $volume * $qty;
5451 return array(
'weight' => $totalWeight,
'volume' => $totalVolume,
'ordered' => $totalOrdered,
'toship' => $totalToShip);
5464 $extraparams = (!empty($this->extraparams) ? json_encode($this->extraparams) :
null);
5465 $extraparams =
dol_trunc($extraparams, 250);
5467 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
5468 $sql .=
" SET extraparams = ".(!empty($extraparams) ?
"'".$this->db->escape($extraparams).
"'" :
"null");
5469 $sql .=
" WHERE rowid = ".((int) $this->
id);
5471 dol_syslog(get_class($this).
"::setExtraParameters", LOG_DEBUG);
5472 $resql = $this->db->query($sql);
5474 $this->error = $this->db->lasterror();
5475 $this->db->rollback();
5478 $this->db->commit();
5501 global
$conf, $user, $langs,
$object, $hookmanager, $extrafields, $form;
5504 if (!is_object($extrafields)) {
5505 require_once DOL_DOCUMENT_ROOT.
'/core/class/extrafields.class.php';
5508 $extrafields->fetch_name_optionals_label($this->table_element_line);
5513 $dirtpls = array_merge(
$conf->modules_parts[
'tpl'], array($defaulttpldir));
5514 foreach ($dirtpls as $module => $reldir) {
5515 if (!empty($module)) {
5518 $tpl = DOL_DOCUMENT_ROOT.$reldir.
'/objectline_create.tpl.php';
5521 if (empty(
$conf->file->strict_mode)) {
5522 $res = @include $tpl;
5524 $res = include $tpl;
5551 public function printObjectLines($action, $seller, $buyer, $selected = 0, $dateSelector = 0, $defaulttpldir =
'/core/tpl')
5553 global
$conf, $hookmanager, $langs, $user, $form, $extrafields,
$object;
5555 global $inputalsopricewithtax, $usemargins, $disableedit, $disablemove, $disableremove, $outputalsopricetotalwithtax;
5559 if (
isModEnabled(
'margin') && !empty($this->element) && in_array($this->element, array(
'facture',
'facturerec',
'propal',
'commande'))) {
5563 $num = count($this->lines);
5566 if (!is_object($extrafields)) {
5567 require_once DOL_DOCUMENT_ROOT.
'/core/class/extrafields.class.php';
5570 $extrafields->fetch_name_optionals_label($this->table_element_line);
5572 if (method_exists($this,
'loadExpeditions')) {
5574 $this->loadExpeditions();
5577 $parameters = array();
5578 $reshook = $hookmanager->executeHooks(
'printObjectLinesBlock', $parameters, $this, $action);
5579 if (empty($reshook)) {
5580 $parameters = array(
'num' => $num,
'dateSelector' => $dateSelector,
'seller' => $seller,
'buyer' => $buyer,
'selected' => $selected,
'table_element_line' => $this->table_element_line);
5581 $reshook = $hookmanager->executeHooks(
'printObjectLineTitle', $parameters, $this, $action);
5582 if (empty($reshook)) {
5586 $dirtpls = array_merge(
$conf->modules_parts[
'tpl'], array($defaulttpldir));
5587 foreach ($dirtpls as $module => $reldir) {
5589 if (!empty($module)) {
5592 $tpl = DOL_DOCUMENT_ROOT.$reldir.
'/objectline_title.tpl.php';
5594 if (file_exists($tpl)) {
5595 if (empty(
$conf->file->strict_mode)) {
5596 $res = @include $tpl;
5598 $res = include $tpl;
5609 print
"<!-- begin printObjectLines() -->\n";
5610 foreach ($this->lines as $line) {
5614 if (is_object($hookmanager)) {
5615 if (empty($line->fk_parent_line)) {
5616 $parameters = array(
'line' => $line,
'num' => $num,
'i' => $i,
'dateSelector' => $dateSelector,
'seller' => $seller,
'buyer' => $buyer,
'selected' => $selected,
'table_element_line' => $line->table_element,
'defaulttpldir' => $defaulttpldir);
5617 $reshook = $hookmanager->executeHooks(
'printObjectLine', $parameters, $this, $action);
5619 $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);
5620 $reshook = $hookmanager->executeHooks(
'printObjectSubLine', $parameters, $this, $action);
5623 if (empty($reshook)) {
5624 $this->printObjectLine($action, $line,
'', $num, $i, $dateSelector, $seller, $buyer, $selected, $extrafields, $defaulttpldir);
5629 print
"<!-- end printObjectLines() -->\n";
5650 public function printObjectLine($action, $line, $var, $num, $i, $dateSelector, $seller, $buyer, $selected = 0, $extrafields =
null, $defaulttpldir =
'/core/tpl')
5654 global $disableedit, $disablemove, $disableremove;
5661 if ($action !=
'editline' || $selected != $line->id) {
5663 if (!empty($line->fk_product) && $line->fk_product > 0) {
5664 $product_static =
new Product($this->db);
5665 $product_static->fetch($line->fk_product);
5667 $product_static->ref = (
string) $line->ref;
5668 $product_static->label = !empty($line->label) ? $line->label :
"";
5670 $text = $product_static->getNomUrl(1);
5675 if (property_exists($this,
'socid') && !empty($this->socid) && !is_object($this->thirdparty)) {
5676 dol_print_error(
null,
'Error: Method printObjectLine was called on an object and object->fetch_thirdparty was not done before');
5681 $prod->fetch($line->fk_product);
5683 $outputlangs = $langs;
5685 if (empty($newlang) &&
GETPOST(
'lang_id',
'aZ09')) {
5686 $newlang =
GETPOST(
'lang_id',
'aZ09');
5688 if (
getDolGlobalString(
'PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE') && empty($newlang) && is_object($this->thirdparty)) {
5689 $newlang = $this->thirdparty->default_lang;
5691 if (!empty($newlang)) {
5693 $outputlangs->setDefaultLang($newlang);
5696 $label = (!empty(
$prod->multilangs[$outputlangs->defaultlang][
"label"])) ?
$prod->multilangs[$outputlangs->defaultlang][
"label"] : $line->product_label;
5698 $label = $line->product_label;
5701 $text .=
' - '.(!empty($line->label) ? $line->label : $label);
5702 $description .= (
getDolGlobalInt(
'PRODUIT_DESC_IN_FORM_ACCORDING_TO_DEVICE') ?
'' : (!empty($line->description) ?
dol_htmlentitiesbr($line->description) :
''));
5706 if (empty((
float) $line->subprice_ttc) && $line->qty) {
5709 if ($line->remise_percent != 100) {
5710 $line->subprice_ttc = (float)
price2num($line->total_ttc * ($line->situation_percent ? 100 / $line->situation_percent : 1) / $line->qty / (1 - $line->remise_percent / 100),
'MU');
5713 $line->subprice_ttc = (float)
price2num((!empty($line->subprice) ? $line->subprice : 0) * (1 + ((!empty($line->tva_tx) ? $line->tva_tx : 0) / 100)),
'MU');
5716 $line->pu_ttc = $line->subprice_ttc;
5723 if (isset($this->expeditions[$line->id])) {
5724 $qty_shipped = $this->expeditions[$line->id];
5726 $disableedit = ($qty_shipped > 0) && ($qty_shipped >= $line->qty);
5728 $dirtpls = array_merge(
$conf->modules_parts[
'tpl'], array($defaulttpldir));
5729 foreach ($dirtpls as $module => $reldir) {
5731 if (!empty($module)) {
5734 $tpl = DOL_DOCUMENT_ROOT.$reldir.
'/objectline_view.tpl.php';
5737 if (file_exists($tpl)) {
5738 if (empty(
$conf->file->strict_mode)) {
5739 $res = @include $tpl;
5741 $res = include $tpl;
5751 if ($this->
status == 0 && $action ==
'editline' && $selected == $line->id) {
5752 $label = (!empty($line->label) ? $line->label : (($line->fk_product > 0) ? $line->product_label :
''));
5754 $line->subprice_ttc = (float)
price2num($line->subprice * (1 + ($line->tva_tx / 100)),
'MU');
5755 $line->pu_ttc = $line->subprice_ttc;
5760 $dirtpls = array_merge(
$conf->modules_parts[
'tpl'], array($defaulttpldir));
5761 foreach ($dirtpls as $module => $reldir) {
5762 if (!empty($module)) {
5765 $tpl = DOL_DOCUMENT_ROOT.$reldir.
'/objectline_edit.tpl.php';
5768 if (empty(
$conf->file->strict_mode)) {
5769 $res = @include $tpl;
5771 $res = include $tpl;
5796 global $langs, $hookmanager, $form, $action;
5798 print
'<!-- printOriginLinesList '.get_class($this).
' -->'.
"\n";
5799 print
'<tr class="liste_titre">';
5800 print
'<td class="linecolref">'.$langs->trans(
'Ref').
'</td>';
5801 print
'<td class="linecoldescription">'.$langs->trans(
'Description').
'</td>';
5802 print
'<td class="linecolvat right">'.$langs->trans(
'VATRate').
'</td>';
5803 print
'<td class="linecoluht right">'.$langs->trans(
'PriceUHT').
'</td>';
5805 print
'<td class="linecoluht_currency right">'.$langs->trans(
'PriceUHTCurrency').
'</td>';
5807 print
'<td class="linecolqty right">'.$langs->trans(
'Qty').
'</td>';
5809 print
'<td class="linecoluseunit left">'.$langs->trans(
'Unit').
'</td>';
5811 print
'<td class="linecoldiscount right">'.$langs->trans(
'ReductionShort').
'</td>';
5812 print
'<td class="linecolht right">'.$langs->trans(
'TotalHT').
'</td>';
5813 print
'<td class="center">';
5814 print $form->showCheckAddButtons(
'checkforselect', 1);
5819 if (!empty($this->lines)) {
5820 foreach ($this->lines as $line) {
5823 if (is_object($hookmanager)) {
5824 $parameters = array(
'line' => $line,
'i' => $i,
'restrictlist' => $restrictlist,
'selectedLines' => $selectedLines);
5825 if (!empty($line->fk_parent_line)) {
5826 $parameters[
'fk_parent_line'] = $line->fk_parent_line;
5828 $reshook = $hookmanager->executeHooks(
'printOriginObjectLine', $parameters, $this, $action);
5830 if (empty($reshook)) {
5831 $this->printOriginLine($line,
'', $restrictlist,
'/core/tpl', $selectedLines);
5852 public function printOriginLine($line, $var, $restrictlist =
'', $defaulttpldir =
'/core/tpl', $selectedLines = array())
5854 global $langs,
$conf;
5857 if (!empty($line->date_start)) {
5862 if ($line->date_debut_reel) {
5866 if (!empty($line->date_end)) {
5868 $date_end = $line->date_end;
5870 $date_end = $line->date_fin_prevue;
5871 if ($line->date_fin_reel) {
5872 $date_end = $line->date_fin_reel;
5877 $this->tpl[
'id'] = $line->id;
5879 $this->tpl[
'label'] =
'';
5880 if (!empty($line->fk_parent_line)) {
5881 $this->tpl[
'label'] .=
img_picto(
'',
'rightarrow.png');
5884 if (((
int) $line->info_bits & 2) == 2) {
5886 if (property_exists($this,
'socid')) {
5887 $discount->fk_soc = $this->socid;
5888 $discount->socid = $this->socid;
5890 $this->tpl[
'label'] .= $discount->getNomUrl(0,
'discount');
5891 } elseif (!empty($line->fk_product)) {
5892 $productstatic =
new Product($this->db);
5893 $productstatic->id = $line->fk_product;
5894 $productstatic->ref = (
string) $line->ref;
5895 $productstatic->type = $line->fk_product_type;
5896 if (empty($productstatic->ref)) {
5897 $line->fetch_product();
5898 $productstatic = $line->product;
5901 $this->tpl[
'label'] .= $productstatic->getNomUrl(1);
5902 $this->tpl[
'label'] .=
' - '.(!empty($line->label) ? $line->label : $line->product_label);
5904 if ($line->product_type == 1 && (
$date_start || $date_end)) {
5908 $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"')));
5909 if (!empty($line->desc)) {
5910 $this->tpl[
'label'] .= $line->desc;
5912 $this->tpl[
'label'] .= ($line->label ?
' '.$line->label :
'');
5916 if ($line->product_type == 1 && (
$date_start || $date_end)) {
5921 if (!empty($line->desc)) {
5922 '@phan-var-force OrderLine|FactureLigne|ContratLigne|FactureFournisseurLigneRec|SupplierInvoiceLine|SupplierProposalLine $line';
5923 if ($line->desc ==
'(CREDIT_NOTE)') {
5925 $discount->fetch($line->fk_remise_except);
5926 $this->tpl[
'description'] = $langs->transnoentities(
"DiscountFromCreditNote", $discount->getNomUrl(0));
5927 } elseif ($line->desc ==
'(DEPOSIT)') {
5929 $discount->fetch($line->fk_remise_except);
5930 $this->tpl[
'description'] = $langs->transnoentities(
"DiscountFromDeposit", $discount->getNomUrl(0));
5931 } elseif ($line->desc ==
'(EXCESS RECEIVED)') {
5933 $discount->fetch($line->fk_remise_except);
5934 $this->tpl[
'description'] = $langs->transnoentities(
"DiscountFromExcessReceived", $discount->getNomUrl(0));
5935 } elseif ($line->desc ==
'(EXCESS PAID)') {
5937 $discount->fetch($line->fk_remise_except);
5938 $this->tpl[
'description'] = $langs->transnoentities(
"DiscountFromExcessPaid", $discount->getNomUrl(0));
5940 $this->tpl[
'description'] =
dol_trunc($line->desc, 60);
5943 $this->tpl[
'description'] =
' ';
5947 $this->tpl[
'vat_rate'] =
vatrate($line->tva_tx,
true);
5948 $this->tpl[
'vat_rate'] .= (((int) $line->info_bits & 1) == 1) ?
'*' :
'';
5949 if (!empty($line->vat_src_code) && !preg_match(
'/\(/', $this->tpl[
'vat_rate'])) {
5950 $this->tpl[
'vat_rate'] .=
' ('.$line->vat_src_code.
')';
5953 $this->tpl[
'price'] =
price($line->subprice);
5954 $this->tpl[
'total_ht'] =
price($line->total_ht);
5955 $this->tpl[
'multicurrency_price'] =
price($line->multicurrency_subprice);
5956 $this->tpl[
'qty'] = (((int) $line->info_bits & 2) != 2) ? $line->qty :
' ';
5958 $this->tpl[
'unit'] = $line->getLabelOfUnit(
'long', $langs);
5959 $this->tpl[
'unit_short'] = $line->getLabelOfUnit(
'short', $langs);
5962 $this->tpl[
'remise_percent'] = (((int) $line->info_bits & 2) != 2) ?
vatrate((
string) $line->remise_percent,
true) :
' ';
5965 $this->tpl[
'strike'] = 0;
5967 $this->tpl[
'strike'] = 1;
5968 } elseif (defined(
'SUBTOTALS_SPECIAL_CODE') && $line->special_code == SUBTOTALS_SPECIAL_CODE) {
5973 $this->tpl[
'strike'] = 1;
5978 $dirtpls = array_merge(
$conf->modules_parts[
'tpl'], array($defaulttpldir));
5979 foreach ($dirtpls as $module => $reldir) {
5980 if (!empty($module)) {
5983 $tpl = DOL_DOCUMENT_ROOT.$reldir.
'/originproductline.tpl.php';
5986 if (empty(
$conf->file->strict_mode)) {
5987 $res = @include $tpl;
5989 $res = include $tpl;
6016 $sql =
"INSERT INTO ".$this->db->prefix().
"element_resources (";
6017 $sql .=
"resource_id";
6018 $sql .=
", resource_type";
6019 $sql .=
", element_id";
6020 $sql .=
", element_type";
6022 $sql .=
", mandatory";
6023 $sql .=
") VALUES (";
6024 $sql .= ((int) $resource_id);
6025 $sql .=
", '".$this->db->escape($resource_type).
"'";
6026 $sql .=
", '".$this->db->escape((
string) $this->
id).
"'";
6027 $sql .=
", '".$this->db->escape($this->element).
"'";
6028 $sql .=
", '".$this->db->escape((
string) $busy).
"'";
6029 $sql .=
", '".$this->db->escape((
string) $mandatory).
"'";
6032 dol_syslog(get_class($this).
"::add_element_resource", LOG_DEBUG);
6033 if ($this->db->query($sql)) {
6035 $result = $this->call_trigger(strtoupper($this->TRIGGER_PREFIX).
'_ADD_RESOURCE', $user);
6037 $this->db->rollback();
6041 $this->db->commit();
6044 $this->error = $this->db->lasterror();
6045 $this->db->rollback();
6066 $sql =
"DELETE FROM ".$this->db->prefix().
"element_resources";
6067 $sql .=
" WHERE rowid = ".((int) $rowid);
6069 dol_syslog(get_class($this).
"::delete_resource", LOG_DEBUG);
6071 $resql = $this->db->query($sql);
6073 $this->error = $this->db->lasterror();
6074 $this->db->rollback();
6078 $result = $this->call_trigger(strtoupper($this->TRIGGER_PREFIX).
'_DELETE_RESOURCE', $user);
6080 $this->db->rollback();
6084 $this->db->commit();
6098 if (isset($this->lines) && is_array($this->lines)) {
6099 $nboflines = count($this->lines);
6100 for ($i = 0; $i < $nboflines; $i++) {
6101 if (is_object($this->lines[$i])) {
6102 $this->lines[$i] = clone $this->lines[$i];
6121 protected function commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams =
null)
6123 global
$conf, $langs, $hookmanager, $action;
6125 $srctemplatepath =
'';
6127 $parameters = array(
'modelspath' => $modelspath,
'modele' => $modele,
'outputlangs' => $outputlangs,
'hidedetails' => $hidedetails,
'hidedesc' => $hidedesc,
'hideref' => $hideref,
'moreparams' => $moreparams);
6128 $reshook = $hookmanager->executeHooks(
'commonGenerateDocument', $parameters, $this, $action);
6130 if (!empty($reshook)) {
6134 dol_syslog(
"commonGenerateDocument modele=".$modele.
" outputlangs->defaultlang=".(is_object($outputlangs) ? $outputlangs->defaultlang :
'null'));
6136 if (empty($modele)) {
6137 $this->error =
'BadValueForParameterModele';
6142 $err = error_reporting();
6144 @set_time_limit(120);
6145 error_reporting($err);
6148 $tmp = explode(
':', $modele, 2);
6149 $saved_model = $modele;
6150 if (!empty($tmp[1])) {
6152 $srctemplatepath = $tmp[1];
6159 $dirmodels = array(
'/');
6160 if (is_array(
$conf->modules_parts[
'models'])) {
6161 $dirmodels = array_merge($dirmodels,
$conf->modules_parts[
'models']);
6163 foreach ($dirmodels as $reldir) {
6164 foreach (array(
'doc',
'pdf') as $prefix) {
6165 if (in_array(get_class($this), array(
'Adherent'))) {
6167 $file = $prefix.
"_".$modele.
".class.php";
6170 $file = $prefix.
"_".$modele.
".modules.php";
6177 if (file_exists($file)) {
6179 $classname = $prefix.
'_'.$modele;
6188 if ($filefound ===
'' || $classname ===
'') {
6189 $this->error = $langs->trans(
"Error").
' Failed to load doc generator with modelpaths='.$modelspath.
' - modele='.$modele;
6190 $this->errors[] = $this->error;
6201 require_once $filefound;
6203 $obj =
new $classname($this->db);
6215 '@phan-var-force ModelePDFMember $obj';
6219 if ($obj->type ==
'odt' && empty($srctemplatepath)) {
6220 $varfortemplatedir = $obj->scandir;
6224 $listoffiles = array();
6227 $listofdir = explode(
',', $dirtoscan);
6228 foreach ($listofdir as $key => $tmpdir) {
6229 $tmpdir = trim($tmpdir);
6230 $tmpdir = preg_replace(
'/DOL_DATA_ROOT/', DOL_DATA_ROOT, $tmpdir);
6232 unset($listofdir[$key]);
6235 if (is_dir($tmpdir)) {
6236 $tmpfiles =
dol_dir_list($tmpdir,
'files', 0,
'\.od(s|t)$',
'',
'name', SORT_ASC, 0);
6237 if (count($tmpfiles)) {
6238 $listoffiles = array_merge($listoffiles, $tmpfiles);
6243 if (count($listoffiles)) {
6244 foreach ($listoffiles as $record) {
6245 $srctemplatepath = $record[
'fullname'];
6251 if (empty($srctemplatepath)) {
6252 $this->error =
'ErrorGenerationAskedForOdtTemplateWithSrcFileNotDefined';
6257 if ($obj->type ==
'odt' && !empty($srctemplatepath)) {
6259 dol_syslog(
"Failed to locate template file ".$srctemplatepath, LOG_WARNING);
6260 $this->error =
'ErrorGenerationAskedForOdtTemplateWithSrcFileNotFound';
6267 $sav_charset_output = empty($outputlangs->charset_output) ?
'' : $outputlangs->charset_output;
6270 $this->model_pdf = $saved_model;
6275 $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath,
'member', 1,
'tmp_cards');
6277 $resultwritefile = -1;
6278 dol_syslog(
"Error generating document - Provided ".get_class($this).
" to ".get_class($obj).
"::write_file()", LOG_ERR);
6282 if ($this instanceof
Don) {
6283 $resultwritefile = $obj->write_file($this, $outputlangs );
6285 $resultwritefile = -1;
6286 dol_syslog(
"Error generating document - Provided ".get_class($this).
" to Don::write_file()", LOG_ERR);
6290 '@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';
6291 $this->context[
'moreparams'] = $moreparams;
6292 $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, $hidedetails, $hidedesc, $hideref);
6294 }
catch (\Throwable $e) {
6295 $resultwritefile = -1;
6296 $this->error = $e->getMessage();
6297 dol_syslog(
"Exception in write_file() for ".get_class($this).
": ".$e->getMessage(), LOG_ERR);
6302 if ($resultwritefile > 0) {
6303 $outputlangs->charset_output = $sav_charset_output;
6306 require_once DOL_DOCUMENT_ROOT.
'/core/lib/files.lib.php';
6310 if (!empty($obj->result[
'fullpath'])) {
6311 $destfull = $obj->result[
'fullpath'];
6314 $update_main_doc_field = 0;
6315 if (!empty($obj->update_main_doc_field)) {
6316 $update_main_doc_field = 1;
6322 $this->indexFile($destfull, $update_main_doc_field);
6325 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);
6331 $this->warnings = $obj->warnings;
6335 $outputlangs->charset_output = $sav_charset_output;
6336 if (empty($this->error)) {
6337 $this->error = $obj->error;
6339 if (empty($this->errors)) {
6340 $this->errors = $obj->errors;
6342 $this->warnings = $obj->warnings;
6343 dol_syslog(
"Error generating document for ".__CLASS__.
". Error: ".$this->error, LOG_ERR);
6357 public function indexFile($destfull, $update_main_doc_field)
6359 global
$conf, $user;
6361 $upload_dir = dirname($destfull);
6362 $destfile = basename($destfull);
6363 $rel_dir = preg_replace(
'/^'.preg_quote(DOL_DATA_ROOT,
'/').
'/',
'', $upload_dir);
6365 if (!preg_match(
'/[\\/]temp[\\/]|[\\/]thumbs|\.meta$/', $rel_dir)) {
6366 $filename = basename($destfile);
6367 $rel_dir = preg_replace(
'/[\\/]$/',
'', $rel_dir);
6368 $rel_dir = preg_replace(
'/^[\\/]/',
'', $rel_dir);
6370 include_once DOL_DOCUMENT_ROOT.
'/ecm/class/ecmfiles.class.php';
6371 $ecmfile =
new EcmFiles($this->db);
6372 $result = $ecmfile->fetch(0,
'', ($rel_dir ? $rel_dir.
'/' :
'').$filename);
6375 $setsharekey =
false;
6377 !empty($this->TRIGGER_PREFIX)
6380 $setsharekey =
true;
6383 if ($this->element ==
'propal' || $this->element ==
'proposal') {
6385 $setsharekey =
true;
6388 $setsharekey =
true;
6391 if ($this->element ==
'facture' &&
getDolGlobalInt(
"INVOICE_ALLOW_EXTERNAL_DOWNLOAD")) {
6392 $setsharekey =
true;
6394 if ($this->element ==
'bank_account' &&
getDolGlobalInt(
"BANK_ACCOUNT_ALLOW_EXTERNAL_DOWNLOAD")) {
6395 $setsharekey =
true;
6397 if ($this->element ==
'contrat' &&
getDolGlobalInt(
"CONTRACT_ALLOW_EXTERNAL_DOWNLOAD")) {
6398 $setsharekey =
true;
6400 if ($this->element ==
'supplier_proposal' &&
getDolGlobalInt(
"SUPPLIER_PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD")) {
6401 $setsharekey =
true;
6403 if ($this->element ==
'order_supplier' &&
getDolGlobalInt(
"SUPPLIER_ORDER_ALLOW_EXTERNAL_DOWNLOAD")) {
6404 $setsharekey =
true;
6406 if ($this->element ==
'invoice_supplier' &&
getDolGlobalInt(
"SUPPLIER_INVOICE_ALLOW_EXTERNAL_DOWNLOAD")) {
6407 $setsharekey =
true;
6409 if ($this->element ==
'societe_rib' &&
getDolGlobalInt(
"SOCIETE_RIB_ALLOW_ONLINESIGN")) {
6410 $setsharekey =
true;
6414 if (empty($ecmfile->share)) {
6415 require_once DOL_DOCUMENT_ROOT.
'/core/lib/security2.lib.php';
6422 $ecmfile->fullpath_orig =
'';
6423 $ecmfile->gen_or_uploaded =
'generated';
6424 $ecmfile->description =
'';
6425 $ecmfile->keywords =
'';
6426 $ecmfile->src_object_type = $this->table_element;
6428 $result = $ecmfile->update($user);
6434 $ecmfile->entity =
$conf->entity;
6435 $ecmfile->filepath = $rel_dir;
6436 $ecmfile->filename = $filename;
6438 $ecmfile->fullpath_orig =
'';
6439 $ecmfile->gen_or_uploaded =
'generated';
6440 $ecmfile->description =
'';
6441 $ecmfile->keywords =
'';
6442 $ecmfile->src_object_type = $this->table_element;
6445 $result = $ecmfile->create($user);
6457 if ($update_main_doc_field && !empty($this->table_element)) {
6458 $sql =
"UPDATE ".$this->db->prefix().$this->table_element.
" SET last_main_doc = '".$this->db->escape($ecmfile->filepath.
"/".$ecmfile->filename).
"'";
6459 $sql .=
" WHERE rowid = ".((int) $this->
id);
6461 $resql = $this->db->query($sql);
6466 $this->last_main_doc = $ecmfile->filepath.
'/'.$ecmfile->filename;
6486 if (file_exists($file_osencoded)) {
6487 require_once DOL_DOCUMENT_ROOT.
'/core/lib/images.lib.php';
6490 $maxwidthsmall = $tmparraysize[
'maxwidthsmall'];
6491 $maxheightsmall = $tmparraysize[
'maxheightsmall'];
6492 $maxwidthmini = $tmparraysize[
'maxwidthmini'];
6493 $maxheightmini = $tmparraysize[
'maxheightmini'];
6498 vignette($file_osencoded, $maxwidthsmall, $maxheightsmall,
'_small', $quality);
6502 vignette($file_osencoded, $maxwidthmini, $maxheightmini,
'_mini', $quality);
6550 return GETPOST($fieldname, $type, 3);
6553 if (isset($alternatevalue)) {
6554 return $alternatevalue;
6557 $newelement = $this->element;
6558 if ($newelement ==
'facture') {
6559 $newelement =
'invoice';
6561 if ($newelement ==
'commande') {
6562 $newelement =
'order';
6564 if (empty($newelement)) {
6565 dol_syslog(
"Ask a default value using common method getDefaultCreateValueForField on an object with no property ->element defined. Return empty string.", LOG_WARNING);
6569 $keyforfieldname = strtoupper($newelement.
'_DEFAULT_'.$fieldname);
6596 if (!$this->element) {
6599 if (!($this->
id > 0)) {
6602 if (is_array($this->array_languages)) {
6606 $this->array_languages = array();
6608 $element = $this->element;
6609 if ($element ==
'categorie') {
6610 $element =
'categories';
6614 $sql =
"SELECT rowid, property, lang , value";
6615 $sql .=
" FROM ".$this->db->prefix().
"object_lang";
6616 $sql .=
" WHERE type_object = '".$this->db->escape($element).
"'";
6617 $sql .=
" AND fk_object = ".((int) $this->
id);
6619 $resql = $this->db->query($sql);
6621 $numrows = $this->db->num_rows($resql);
6624 while ($i < $numrows) {
6625 $obj = $this->db->fetch_object($resql);
6626 $key = $obj->property;
6627 $value = $obj->value;
6628 $codelang = $obj->lang;
6629 $type = $this->fields[$key][
'type'];
6632 if (preg_match(
'/date/', $type)) {
6633 $this->array_languages[$key][$codelang] = $this->db->jdate($value);
6635 $this->array_languages[$key][$codelang] = $value;
6642 $this->db->free($resql);
6665 foreach ($_POST as $postfieldkey => $postfieldvalue) {
6666 $tmparray = explode(
'-', $postfieldkey);
6667 if ($tmparray[0] !=
'field') {
6671 $element = $tmparray[1];
6672 $key = $tmparray[2];
6673 $codelang = $tmparray[3];
6676 if (!empty($onlykey) && $key != $onlykey) {
6679 if ($element != $this->element) {
6683 $key_type = $this->fields[$key][
'type'];
6686 if (isset($this->fields[$key][
'enabled'])) {
6687 $enabled = (int)
dol_eval((
string) $this->fields[$key][
'enabled'], 1, 1,
'1');
6694 if (empty($enabled)) {
6699 if (in_array($key_type, array(
'date'))) {
6703 } elseif (in_array($key_type, array(
'datetime'))) {
6707 } elseif (in_array($key_type, array(
'checkbox',
'chkbxlst'))) {
6708 $value_arr =
GETPOST($postfieldkey,
'array');
6709 if (!empty($value_arr)) {
6710 $value_key = implode(
',', $value_arr);
6714 } elseif (in_array($key_type, array(
'price',
'double'))) {
6715 $value_arr =
GETPOST($postfieldkey,
'alpha');
6718 $value_key =
GETPOST($postfieldkey);
6719 if (in_array($key_type, array(
'link')) && $value_key ==
'-1') {
6724 $this->array_languages[$key][$codelang] = $value_key;
6749 $savDisableCompute =
$conf->disable_compute;
6750 $conf->disable_compute = 1;
6752 $ret = $this->fetch(
$id);
6754 $conf->disable_compute = $savDisableCompute;
6772 global
$conf, $extrafields;
6774 if (empty($rowid)) {
6777 if (empty($rowid) && isset($this->rowid)) {
6778 $rowid = $this->rowid;
6782 if (!$this->table_element) {
6785 $this->array_options = array();
6787 if (!is_array($optionsArray)) {
6789 if (!isset($extrafields) || !is_object($extrafields)) {
6790 require_once DOL_DOCUMENT_ROOT.
'/core/class/extrafields.class.php';
6795 if (empty($extrafields->attributes[$this->table_element][
'loaded'])) {
6796 $extrafields->fetch_name_optionals_label($this->table_element);
6798 $optionsArray = (!empty($extrafields->attributes[$this->table_element][
'label']) ? $extrafields->attributes[$this->table_element][
'label'] :
null);
6800 global $extrafields;
6801 dol_syslog(
"Warning: fetch_optionals was called with param optionsArray defined when you should pass null now", LOG_WARNING);
6804 $table_element = $this->table_element;
6805 if ($table_element ==
'categorie') {
6806 $table_element =
'categories';
6810 if (is_array($optionsArray) && count($optionsArray) > 0) {
6811 $sql =
"SELECT rowid";
6812 foreach ($optionsArray as $name => $label) {
6813 if (empty($extrafields->attributes[$this->table_element][
'type'][$name]) || (!in_array($extrafields->attributes[$this->table_element][
'type'][$name], [
'separate',
'point',
'multipts',
'linestrg',
'polygon']))) {
6814 $sql .=
", ".$this->db->sanitize($name);
6817 if (!empty($extrafields->attributes[$this->table_element][
'type'][$name]) && in_array($extrafields->attributes[$this->table_element][
'type'][$name], array(
'point',
'multipts',
'linestrg',
'polygon'))) {
6819 $sql .=
", ST_AsWKT(".$this->db->sanitize($name).
") as ".$this->db->sanitize($name);
6822 $sql .=
" FROM ".$this->db->prefix().$table_element.
"_extrafields";
6823 $sql .=
" WHERE fk_object = ".((int) $rowid);
6826 $resql = $this->db->query($sql);
6828 $numrows = $this->db->num_rows($resql);
6830 $tab = $this->db->fetch_array($resql);
6831 foreach ($tab as $key => $value) {
6833 if ($key !=
'rowid' && $key !=
'tms' && $key !=
'fk_member' && !is_int($key)) {
6835 if (!empty($extrafields->attributes[$this->table_element]) && in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'date',
'datetime'))) {
6837 $this->array_options[
"options_".$key] = $this->db->jdate($value);
6839 $this->array_options[
"options_".$key] = $value;
6844 if (!empty($extrafields->attributes[$this->table_element][
'type'][$key]) && $extrafields->attributes[$this->table_element][
'type'][$key] ==
'password') {
6845 if (!empty($value) && preg_match(
'/^dolcrypt:/', $value)) {
6846 $this->array_options[
"options_".$key] =
dolDecrypt($value);
6855 if (is_array($extrafields->attributes[$this->table_element][
'label'])) {
6856 foreach ($extrafields->attributes[$this->table_element][
'label'] as $key => $val) {
6857 $this->array_options[
'options_' . $key] =
null;
6864 if (is_array($extrafields->attributes[$this->table_element][
'label'])) {
6865 foreach ($extrafields->attributes[$this->table_element][
'label'] as $key => $val) {
6866 if (!empty($extrafields->attributes[$this->table_element]) && !empty($extrafields->attributes[$this->table_element][
'computed'][$key])) {
6868 if (empty(
$conf->disable_compute)) {
6871 global $objectoffield;
6872 $this->array_options[
'options_' . $key] =
dol_eval((
string) $extrafields->attributes[$this->table_element][
'computed'][$key], 1, 0,
'2');
6878 $this->db->free($resql);
6886 $this->errors[] = $this->db->lasterror();
6907 $table_element = $this->table_element;
6908 if ($table_element ==
'categorie') {
6909 $table_element =
'categories';
6912 dol_syslog(get_class($this).
"::deleteExtraFields delete", LOG_DEBUG);
6914 $sql_del =
"DELETE FROM ".$this->db->prefix().$table_element.
"_extrafields WHERE fk_object = ".((int) $this->
id);
6916 $resql = $this->db->query($sql_del);
6918 $this->error = $this->db->lasterror();
6919 $this->db->rollback();
6922 $this->db->commit();
6939 global $langs, $extrafields, $user;
6941 if (
getDolGlobalString(
'MAIN_EXTRAFIELDS_DISABLED') || empty($this->array_options)) {
6945 if (empty($userused)) {
6952 $langs->load(
'admin');
6953 if (!isset($extrafields) || !is_object($extrafields)) {
6954 require_once DOL_DOCUMENT_ROOT.
'/core/class/extrafields.class.php';
6957 $target_extrafields = $extrafields->fetch_name_optionals_label($this->table_element);
6960 $new_array_options = array();
6961 foreach ($this->array_options as $key => $value) {
6962 if (in_array(substr($key, 8), array_keys($target_extrafields))) {
6963 $new_array_options[$key] = $value;
6964 } elseif (in_array($key, array_keys($target_extrafields))) {
6965 $new_array_options[
'options_'.$key] = $value;
6969 foreach ($new_array_options as $key => $value) {
6970 $attributeKey = substr($key, 8);
6971 $attributeType = $extrafields->attributes[$this->table_element][
'type'][$attributeKey];
6972 $attributeLabel = $langs->transnoentities($extrafields->attributes[$this->table_element][
'label'][$attributeKey]);
6973 $attributeParam = $extrafields->attributes[$this->table_element][
'param'][$attributeKey];
6974 $attributeRequired = $extrafields->attributes[$this->table_element][
'required'][$attributeKey];
6975 $attributeUnique = $extrafields->attributes[$this->table_element][
'unique'][$attributeKey];
6976 $attrfieldcomputed = $extrafields->attributes[$this->table_element][
'computed'][$attributeKey];
6977 $attributeEmptyOnClone = $extrafields->attributes[$this->table_element][
'emptyonclone'][$attributeKey];
6989 if (!empty($this->context[
'createfromclone']) && $this->context[
'createfromclone'] ==
'createfromclone' && (!empty($attributeUnique) || !empty($attributeEmptyOnClone))) {
6990 $new_array_options[$key] =
null;
6996 if (!empty($this->context[
'createproductcombination']) && $this->context[
'createproductcombination'] ==
'createproductcombination' && !empty($attributeUnique)) {
6997 $new_array_options[$key] =
null;
7002 if ($attributeRequired) {
7003 $v = $this->array_options[$key];
7005 $langs->load(
"errors");
7006 dol_syslog(
"Mandatory field '".$key.
"' is empty during create and set to required into definition of extrafields");
7007 $this->errors[] = $langs->trans(
'ErrorFieldRequired', $attributeLabel);
7012 if (!empty($attrfieldcomputed)) {
7014 global $objectoffield;
7015 $objectoffield = $this;
7016 $value =
dol_eval((
string) $attrfieldcomputed, 1, 0,
'2');
7017 dol_syslog($langs->trans(
"Extrafieldcomputed").
" on ".$attributeLabel.
"(".$value.
")", LOG_DEBUG);
7018 $new_array_options[$key] = $value;
7020 $new_array_options[$key] =
null;
7025 switch ($attributeType) {
7029 if (!is_numeric($value) && $value !=
'') {
7030 $this->errors[] = $langs->trans(
"ExtraFieldHasWrongValue", $attributeLabel);
7032 } elseif ($value ===
'') {
7033 $new_array_options[$key] =
null;
7037 if ($value ===
'' || $value ===
false || $value ===
null) {
7038 $new_array_options[$key] =
null;
7044 if (!is_numeric($value) && $value !=
'') {
7045 dol_syslog($langs->trans(
"ExtraFieldHasWrongValue").
" for ".$attributeLabel.
"(".$value.
"is not '".$attributeType.
"')", LOG_DEBUG);
7046 $this->errors[] = $langs->trans(
"ExtraFieldHasWrongValue", $attributeLabel);
7048 } elseif ($value ==
'') {
7052 $new_array_options[$key] = $value;
7062 if ($this->array_options[$key] !=
'' && is_array($extrafields->attributes[$this->table_element][
'param'][$attributeKey][
'options'])) {
7064 $tmparrays = array_keys($extrafields->attributes[$this->table_element][
'param'][$attributeKey][
'options']);
7065 $algo = reset($tmparrays);
7070 if (is_object($this->oldcopy)) {
7072 if (isset($this->oldcopy->array_options[$key]) && $this->array_options[$key] == $this->oldcopy->array_options[$key]) {
7074 if ($algo ==
'dolcrypt') {
7075 if (!preg_match(
'/^dolcrypt:/', $this->array_options[$key])) {
7076 $new_array_options[$key] =
dolEncrypt($this->array_options[$key]);
7078 $new_array_options[$key] = $this->array_options[$key];
7081 $new_array_options[$key] = $this->array_options[$key];
7085 if ($algo ==
'dolcrypt') {
7086 if (!preg_match(
'/^dolcrypt:/', $this->array_options[$key])) {
7087 $new_array_options[$key] =
dolEncrypt($this->array_options[$key]);
7089 $new_array_options[$key] = $this->array_options[$key];
7092 $new_array_options[$key] =
dol_hash($this->array_options[$key], $algo);
7098 if ($algo ==
'dolcrypt' && !preg_match(
'/^dolcrypt:/', $this->array_options[$key])) {
7099 $new_array_options[$key] =
dolEncrypt($this->array_options[$key]);
7101 $new_array_options[$key] = $this->array_options[$key];
7106 $new_array_options[$key] = $this->array_options[$key];
7109 $new_array_options[$key] = $this->array_options[$key];
7115 if (!is_numeric($this->array_options[$key]) || $this->array_options[$key] != intval($this->array_options[$key])) {
7116 $this->array_options[$key] = strtotime($this->array_options[$key]);
7118 $new_array_options[$key] = $this->db->idate($this->array_options[$key]);
7122 if (!is_numeric($this->array_options[$key]) || $this->array_options[$key] != intval($this->array_options[$key])) {
7123 $this->array_options[$key] = strtotime($this->array_options[$key]);
7125 $new_array_options[$key] = $this->db->idate($this->array_options[$key],
'gmt');
7128 $param_list = array_keys($attributeParam[
'options']);
7131 $InfoFieldList = explode(
":", $param_list[0]);
7133 if ($InfoFieldList[0] && class_exists($InfoFieldList[0])) {
7134 if ($value ==
'-1') {
7135 $new_array_options[$key] =
'';
7138 '@phan-var-force CommonObject $object';
7142 $sqlFetchObject =
"SELECT rowid FROM ".$this->db->prefix().$object->table_element;
7143 if (is_numeric($value)) {
7144 $sqlFetchObject .=
" WHERE rowid = " . (int) $value;
7146 $sqlFetchObject .=
" WHERE ref = '" . $this->db->escape($value) .
"'";
7149 $obj = $this->db->getRow($sqlFetchObject);
7151 if ($obj !==
false) {
7152 $objectId = $obj->rowid;
7159 $new_array_options[$key] = $objectId;
7161 $this->error =
"Id/Ref '".$value.
"' for object '".
$object->element.
"' not found";
7166 dol_syslog(
'Error bad setup of extrafield', LOG_WARNING);
7171 if (is_array($this->array_options[$key])) {
7172 $new_array_options[$key] = implode(
',', $this->array_options[$key]);
7174 $new_array_options[$key] = $this->array_options[$key];
7181 $sqlColumnValues = [
'fk_object' => (int) $this->
id];
7183 foreach ($new_array_options as $key => $newValue) {
7184 $attributeKey = substr($key, 8);
7185 $attributeType = $extrafields->attributes[$this->table_element][
'type'][$attributeKey];
7186 if ($attributeType ===
'separate') {
7190 $geoDataType = ExtraFields::$geoDataTypes[$attributeType] ??
null;
7192 if (! $geoDataType) {
7194 if ($newValue !=
'') {
7195 $sqlColumnValues[$attributeKey] =
"'".$this->db->escape($newValue).
"'";
7197 $sqlColumnValues[$attributeKey] =
'null';
7201 if (empty($newValue)) {
7202 $sqlColumnValues[$attributeKey] =
'null';
7205 if (preg_match(
'/error/i', $newValue)) {
7206 dol_syslog(
'Bad syntax string for '.$geoDataType[
'shortname'].
' '.$newValue.
' to generate SQL request', LOG_WARNING);
7207 $sqlColumnValues[$attributeKey] =
'null';
7216 $sqlColumnValues[$attributeKey] = $geoDataType[
'ST_Function'].
"('".$this->db->escape($newValue).
"')";
7221 $table_element = $this->table_element;
7222 if ($table_element ==
'categorie') {
7223 $table_element =
'categories';
7225 $extrafieldsTable = $this->db->prefix() . $table_element .
'_extrafields';
7227 dol_syslog(get_class($this).
"::insertExtraFields update or insert record line", LOG_DEBUG);
7229 $linealreadyfound = 0;
7230 $sql =
"SELECT COUNT(rowid) as nb FROM ".$this->db->prefix().$table_element.
"_extrafields WHERE fk_object = ".((int) $this->
id);
7231 $resql = $this->db->query($sql);
7233 $tmpobj = $this->db->fetch_object($resql);
7235 $linealreadyfound = $tmpobj->nb;
7240 if ($linealreadyfound) {
7241 array_shift($sqlColumnValues);
7242 if (empty($sqlColumnValues)) {
7248 $this->db->commit();
7251 $sqlColumnValueString = implode(
7257 array_map(
function ($key) use ($sqlColumnValues) {
7258 return "{$key} = {$sqlColumnValues[$key]}";
7259 }, array_keys($sqlColumnValues))
7261 $sql =
"UPDATE {$extrafieldsTable} SET {$sqlColumnValueString} WHERE fk_object = ".((int) $this->
id);
7264 $extrafieldsRequiredOnOtherEntities = $extrafields->attributes[$this->table_element][
'mandatoryfieldsofotherentities'] ?? array();
7265 foreach ($extrafieldsRequiredOnOtherEntities as $key => $extrafieldType) {
7266 if (isset($sqlColumnValues[$key])) {
7271 $sqlColumnValues[$key] =
"''";
7272 if (in_array($extrafieldType, array(
'int',
'double',
'price'))) {
7273 $sqlColumnValues[$key] = 0;
7276 $sqlColumns = implode(
',', array_keys($sqlColumnValues));
7277 $sqlValues = implode(
',', array_values($sqlColumnValues));
7278 $sql =
"INSERT INTO {$extrafieldsTable} ({$sqlColumns}) VALUES ({$sqlValues})";
7281 $resql = $this->db->query($sql);
7283 $this->error = $this->db->lasterror();
7288 if (!$error && !empty($this->fields[
'fk_user_modif'])) {
7289 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
7290 $sql .=
" SET fk_user_modif = ".(int) $user->id;
7291 $sql .=
" WHERE ".(empty($this->table_rowid) ?
'rowid' : $this->db->sanitize($this->table_rowid)).
" = ".((
int)
$this->id);
7292 $this->db->query($sql);
7295 if (!$error && $trigger) {
7297 $this->context = array(
'extrafieldaddupdate' => 1);
7298 $result = $this->call_trigger($trigger, $userused);
7306 $this->db->rollback();
7309 $this->db->commit();
7327 global $langs, $user;
7329 if (empty($userused)) {
7339 if (is_array($this->array_languages)) {
7340 $new_array_languages = $this->array_languages;
7342 foreach ($new_array_languages as $key => $value) {
7343 $attributeKey = $key;
7344 $attributeType = $this->fields[$attributeKey][
'type'];
7345 $attributeLabel = $this->fields[$attributeKey][
'label'];
7350 switch ($attributeType) {
7352 if (is_array($value) || (!is_numeric($value) && $value !=
'')) {
7353 $this->errors[] = $langs->trans(
"ExtraLanguageHasWrongValue", $attributeLabel);
7355 } elseif ($value ==
'') {
7356 $new_array_languages[$key] =
null;
7361 if (!is_numeric($value) && $value !=
'') {
7362 dol_syslog($langs->trans(
"ExtraLanguageHasWrongValue").
" on ".$attributeLabel.
"(".$value.
"is not '".$attributeType.
"')", LOG_DEBUG);
7363 $this->errors[] = $langs->trans(
"ExtraLanguageHasWrongValue", $attributeLabel);
7365 } elseif ($value ==
'') {
7366 $new_array_languages[$key] =
null;
7368 $new_array_languages[$key] = $value;
7382 $table_element = $this->table_element;
7383 if ($table_element ==
'categorie') {
7384 $table_element =
'categories';
7387 dol_syslog(get_class($this).
"::insertExtraLanguages delete then insert", LOG_DEBUG);
7389 foreach ($new_array_languages as $key => $langcodearray) {
7390 foreach ($langcodearray as $langcode => $value) {
7391 $sql_del =
"DELETE FROM ".$this->db->prefix().
"object_lang";
7392 $sql_del .=
" WHERE fk_object = ".((int) $this->
id).
" AND property = '".$this->db->escape($key).
"' AND type_object = '".$this->db->escape($table_element).
"'";
7393 $sql_del .=
" AND lang = '".$this->db->escape($langcode).
"'";
7394 $this->db->query($sql_del);
7396 if ($value !==
'') {
7397 $sql =
"INSERT INTO ".$this->db->prefix().
"object_lang (fk_object, property, type_object, lang, value";
7398 $sql .=
") VALUES (".((int) $this->
id).
", '".$this->db->escape($key).
"', '".$this->db->escape($table_element).
"', '".$this->db->escape($langcode).
"', '".$this->db->escape($value).
"'";
7401 $resql = $this->db->query($sql);
7403 $this->error = $this->db->lasterror();
7411 if (!$error && $trigger) {
7413 $this->context = array(
'extralanguagesaddupdate' => 1);
7414 $result = $this->call_trigger($trigger, $userused);
7422 $this->db->rollback();
7425 $this->db->commit();
7445 global $langs, $user, $extrafields, $hookmanager;
7451 if (empty($userused)) {
7457 if (!empty($this->array_options) && isset($this->array_options[
"options_".$key])) {
7459 $langs->load(
'admin');
7460 if (!isset($extrafields) || !is_object($extrafields)) {
7461 require_once DOL_DOCUMENT_ROOT.
'/core/class/extrafields.class.php';
7464 $extrafields->fetch_name_optionals_label($this->table_element);
7465 if (!isset($extrafields->attributes[$this->table_element][
'type'][$key])) {
7469 $value = $this->array_options[
"options_".$key];
7471 $attributeKey = $key;
7472 $attributeType = $extrafields->attributes[$this->table_element][
'type'][$attributeKey];
7473 $attributeLabel = $extrafields->attributes[$this->table_element][
'label'][$attributeKey];
7474 $attributeParam = $extrafields->attributes[$this->table_element][
'param'][$attributeKey];
7475 $attributeRequired = $extrafields->attributes[$this->table_element][
'required'][$attributeKey];
7476 $attributeUnique = $extrafields->attributes[$this->table_element][
'unique'][$attributeKey];
7477 $attrfieldcomputed = $extrafields->attributes[$this->table_element][
'computed'][$attributeKey];
7481 if ($attributeRequired) {
7482 $mandatorypb =
false;
7483 if ($attributeType ==
'link' && $this->array_options[
"options_".$key] ==
'-1') {
7484 $mandatorypb =
true;
7486 if ($this->array_options[
"options_".$key] ===
'') {
7487 $mandatorypb =
true;
7490 $langs->load(
"errors");
7491 dol_syslog(
"Mandatory field 'options_".$key.
"' is empty during update and set to required into definition of extrafields");
7492 $this->errors[] = $langs->trans(
'ErrorFieldRequired', $attributeLabel);
7498 $new_array_options = $this->array_options;
7502 if (!empty($attrfieldcomputed)) {
7504 global $objectoffield;
7505 $objectoffield = $this;
7506 $value =
dol_eval((
string) $attrfieldcomputed, 1, 0,
'2');
7507 dol_syslog($langs->trans(
"Extrafieldcomputed").
" on ".$attributeLabel.
"(".$value.
")", LOG_DEBUG);
7509 $new_array_options[
"options_".$key] = $value;
7511 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7513 $new_array_options[
"options_".$key] =
null;
7515 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7519 switch ($attributeType) {
7521 if (!is_numeric($value) && $value !=
'') {
7522 $this->errors[] = $langs->trans(
"ExtraFieldHasWrongValue", $attributeLabel);
7524 } elseif ($value ===
'') {
7525 $new_array_options[
"options_".$key] =
null;
7527 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7533 if (!is_numeric($value) && $value !=
'') {
7534 dol_syslog($langs->trans(
"ExtraFieldHasWrongValue").
" on ".$attributeLabel.
"(".$value.
"is not '".$attributeType.
"')", LOG_DEBUG);
7535 $this->errors[] = $langs->trans(
"ExtraFieldHasWrongValue", $attributeLabel);
7537 } elseif ($value ===
'') {
7541 $new_array_options[
"options_".$key] = $value;
7543 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7555 if ($this->array_options[
"options_".$key] !=
'' && is_array($extrafields->attributes[$this->table_element][
'param'][$attributeKey][
'options'])) {
7557 $tmparrays = array_keys($extrafields->attributes[$this->table_element][
'param'][$attributeKey][
'options']);
7558 $algo = reset($tmparrays);
7564 if (is_object($this->oldcopy)) {
7566 if (isset($this->oldcopy->array_options[
"options_".$key]) && $this->array_options[
"options_".$key] == $this->oldcopy->array_options[
"options_".$key]) {
7567 if ($algo ==
'dolcrypt') {
7568 if (!preg_match(
'/^dolcrypt:/', $this->array_options[
"options_".$key])) {
7569 $new_array_options[
"options_".$key] =
dolEncrypt($this->array_options[
"options_".$key]);
7571 $new_array_options[
"options_".$key] = $this->array_options[
"options_".$key];
7574 $new_array_options[
"options_".$key] = $this->array_options[
"options_".$key];
7577 if ($algo ==
'dolcrypt') {
7578 if (!preg_match(
'/^dolcrypt:/', $this->array_options[
"options_".$key])) {
7579 $new_array_options[
"options_".$key] =
dolEncrypt($this->array_options[
"options_".$key]);
7581 $new_array_options[
"options_".$key] = $this->array_options[
"options_".$key];
7584 $new_array_options[
"options_".$key] =
dol_hash($this->array_options[
"options_".$key], $algo);
7588 if ($algo ==
'dolcrypt' && !preg_match(
'/^dolcrypt:/', $this->array_options[
"options_".$key])) {
7589 $new_array_options[
"options_".$key] =
dolEncrypt($this->array_options[
"options_".$key]);
7591 $new_array_options[
"options_".$key] = $this->array_options[
"options_".$key];
7596 $new_array_options[
"options_".$key] = $this->array_options[
"options_".$key];
7599 $new_array_options[
"options_".$key] = $this->array_options[
"options_".$key];
7602 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7606 if (empty($this->array_options[
"options_".$key])) {
7607 $new_array_options[
"options_".$key] =
null;
7609 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7611 $new_array_options[
"options_".$key] = $this->db->idate($this->array_options[
"options_".$key]);
7615 if (empty($this->array_options[
"options_".$key])) {
7616 $new_array_options[
"options_".$key] =
null;
7618 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7620 $new_array_options[
"options_".$key] = $this->db->idate($this->array_options[
"options_".$key],
'gmt');
7624 if (empty($this->array_options[
"options_".$key])) {
7625 $new_array_options[
"options_".$key] =
null;
7627 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7631 if ($this->array_options[
"options_".$key] ===
'') {
7632 $new_array_options[
"options_".$key] =
null;
7634 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7668 $new_array_options = array();
7669 if (is_array($this->array_options[
"options_".$key])) {
7670 $new_array_options[
"options_".$key] = implode(
',', $this->array_options[
"options_".$key]);
7672 $new_array_options[
"options_".$key] = $this->array_options[
"options_".$key];
7675 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7681 $linealreadyfound = 0;
7684 $table_element = $this->table_element;
7685 if ($table_element ==
'categorie') {
7686 $table_element =
'categories';
7689 $sql =
"SELECT COUNT(rowid) as nb FROM ".$this->db->prefix().$table_element.
"_extrafields WHERE fk_object = ".((int) $this->
id);
7690 $resql = $this->db->query($sql);
7692 $tmpobj = $this->db->fetch_object($resql);
7694 $linealreadyfound = $tmpobj->nb;
7699 if ($linealreadyfound) {
7700 $sanitizedGeoDataType = ExtraFields::$geoDataTypes[$attributeType] ??
null;
7701 if ($this->array_options[
"options_".$key] ===
null) {
7702 $sql =
"UPDATE ".$this->db->prefix().$this->db->sanitize($table_element).
"_extrafields";
7703 $sql .=
" SET ".$this->db->sanitize($key).
" = null";
7704 } elseif (!empty($sanitizedGeoDataType[
'ST_Function'])) {
7705 $sql =
"UPDATE ".$this->db->prefix().$this->db->sanitize($table_element).
"_extrafields";
7706 $sql .=
" SET ".$this->db->sanitize($key).
" = ".$this->db->sanitize($sanitizedGeoDataType[
'ST_Function']).
"('".$this->db->escape($this->array_options[
"options_".$key]).
"')";
7709 $sql =
"UPDATE ".$this->db->prefix().$this->db->sanitize($table_element).
"_extrafields";
7710 $sql .=
" SET ".$this->db->sanitize($key).
" = '".$this->db->escape($new_array_options[
"options_".$key]).
"'";
7712 $sql .=
" WHERE fk_object = ".((int) $this->
id);
7714 $resql = $this->db->query($sql);
7717 $this->error = $this->db->lasterror();
7720 $result = $this->insertExtraFields(
'', $user);
7727 if (!$error && !empty($this->fields[
'fk_user_modif'])) {
7728 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
7729 $sql .=
" SET fk_user_modif = ".(int) $user->id;
7730 $sql .=
" WHERE ".(empty($this->table_rowid) ?
'rowid' : $this->db->sanitize($this->table_rowid)).
" = ".((
int)
$this->id);
7731 $this->db->query($sql);
7735 $parameters = array(
'key' => $key);
7737 $reshook = $hookmanager->executeHooks(
'updateExtraFieldBeforeCommit', $parameters, $this, $action);
7743 if (!$error && $trigger) {
7745 $this->context = array(
'extrafieldupdate' => 1);
7746 $result = $this->call_trigger($trigger, $userused);
7754 dol_syslog(__METHOD__.$this->error, LOG_ERR);
7755 $this->db->rollback();
7758 $this->db->commit();
7774 return $this->array_options[
'options_'.$key] ??
null;
7786 $this->array_options[
'options_'.$key] = $value;
7803 if (empty($userused)) {
7831 public function showInputField($val, $key, $value, $moreparam =
'', $keysuffix =
'', $keyprefix =
'', $morecss = 0, $nonewbutton = 0)
7833 global
$conf, $langs, $form;
7838 if (!is_object($form)) {
7839 require_once DOL_DOCUMENT_ROOT.
'/core/class/html.form.class.php';
7840 $form =
new Form($this->db);
7843 if (!empty($this->fields)) {
7844 $val = $this->fields[$key];
7848 $fieldValidationErrorMsg =
'';
7849 $validationClass =
'';
7850 $fieldValidationErrorMsg = $this->getFieldError($key);
7851 if (!empty($fieldValidationErrorMsg)) {
7852 $validationClass =
' --error';
7854 $validationClass =
' --success';
7862 $param[
'options'] = array();
7865 $size = !empty($this->fields[$key][
'size']) ? $this->fields[$key][
'size'] : 0;
7867 if (preg_match(
'/^(integer|link):(.*):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
7868 $param[
'options'] = array($reg[2].
':'.$reg[3].
':'.$reg[4].
':'.$reg[5] =>
'N');
7870 } elseif (preg_match(
'/^(integer|link):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
7871 $param[
'options'] = array($reg[2].
':'.$reg[3].
':'.$reg[4] =>
'N');
7873 } elseif (preg_match(
'/^(integer|link):(.*):(.*)/i', $val[
'type'], $reg)) {
7874 $param[
'options'] = array($reg[2].
':'.$reg[3] =>
'N');
7876 } elseif (preg_match(
'/^(sellist):(.*):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
7877 $param[
'options'] = array($reg[2].
':'.$reg[3].
':'.$reg[4].
':'.$reg[5] =>
'N');
7879 } elseif (preg_match(
'/^(sellist):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
7880 $param[
'options'] = array($reg[2].
':'.$reg[3].
':'.$reg[4] =>
'N');
7882 } elseif (preg_match(
'/^(sellist):(.*):(.*)/i', $val[
'type'], $reg)) {
7883 $param[
'options'] = array($reg[2].
':'.$reg[3] =>
'N');
7885 } elseif (preg_match(
'/^chkbxlst:(.*)/i', $val[
'type'], $reg)) {
7886 $param[
'options'] = array($reg[1] =>
'N');
7888 } elseif (preg_match(
'/varchar\((\d+)\)/', $val[
'type'], $reg)) {
7889 $param[
'options'] = array();
7892 } elseif (preg_match(
'/varchar/', $val[
'type'])) {
7893 $param[
'options'] = array();
7895 } elseif (preg_match(
'/stars\((\d+)\)/', $val[
'type'], $reg)) {
7896 $param[
'options'] = array();
7900 $param[
'options'] = array();
7901 $type = $this->fields[$key][
'type'];
7906 if (!empty($this->fields[$key][
'arrayofkeyval']) && is_array($this->fields[$key][
'arrayofkeyval'])) {
7907 $param[
'options'] = $this->fields[$key][
'arrayofkeyval'];
7909 if (empty($this->fields[$key][
'multiinput'])) {
7910 $type = (($this->fields[$key][
'type'] ==
'checkbox') ? $this->fields[$key][
'type'] :
'select');
7914 $label = $this->fields[$key][
'label'];
7917 $default = (!empty($this->fields[$key][
'default']) ? $this->fields[$key][
'default'] :
'');
7919 $computed = (!empty($this->fields[$key][
'computed']) ? $this->fields[$key][
'computed'] :
'');
7921 $unique = (!empty($this->fields[$key][
'unique']) ? $this->fields[$key][
'unique'] : 0);
7923 $required = (!empty($this->fields[$key][
'required']) ? $this->fields[$key][
'required'] : 0);
7925 $autofocusoncreate = (!empty($this->fields[$key][
'autofocusoncreate']) ? $this->fields[$key][
'autofocusoncreate'] : 0);
7927 $placeholder = (!empty($this->fields[$key][
'placeholder']) ? $this->fields[$key][
'placeholder'] : 0);
7930 $langfile = (!empty($this->fields[$key][
'langfile']) ? $this->fields[$key][
'langfile'] :
'');
7932 $list = (!empty($this->fields[$key][
'list']) ? $this->fields[$key][
'list'] : 0);
7933 $hidden = (in_array(abs($this->fields[$key][
'visible']), array(0, 2)) ? 1 : 0);
7938 if (!preg_match(
'/^search_/', $keyprefix)) {
7939 return '<span class="opacitymedium">'.$langs->trans(
"AutomaticallyCalculated").
'</span>';
7946 if (empty($morecss) && !empty($val[
'css'])) {
7947 $morecss = $val[
'css'];
7948 } elseif (empty($morecss)) {
7949 if ($type ==
'date') {
7950 $morecss =
'minwidth100imp';
7951 } elseif ($type ==
'datetime' || $type ==
'link') {
7952 $morecss =
'minwidth200imp';
7953 } elseif (in_array($type, array(
'int',
'integer',
'price')) || preg_match(
'/^double(\([0-9],[0-9]\)){0,1}/', (
string) $type)) {
7954 $morecss =
'maxwidth75';
7955 } elseif ($type ==
'url') {
7956 $morecss =
'minwidth400';
7957 } elseif ($type ==
'boolean') {
7960 if (is_numeric($size) && round((
float) $size) < 12) {
7961 $morecss =
'minwidth100';
7962 } elseif (is_numeric($size) && round((
float) $size) <= 48) {
7963 $morecss =
'minwidth200';
7965 $morecss =
'minwidth400';
7971 if (!empty($validationClass)) {
7972 $morecss .= $validationClass;
7975 if (in_array($type, array(
'date'))) {
7976 $tmp = explode(
',', $size);
7981 if (!$required && $value ==
'') {
7986 $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required,
'', 1, (($keyprefix !=
'search_' && $keyprefix !=
'search_options_') ? 1 : 0), 0, 1);
7987 } elseif (in_array($type, array(
'datetime'))) {
7988 $tmp = explode(
',', $size);
7993 if (!$required && $value ==
'') {
7998 $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required,
'', 1, (($keyprefix !=
'search_' && $keyprefix !=
'search_options_') ? 1 : 0), 0, 1,
'',
'',
'', 1,
'',
'',
'tzuserrel');
7999 } elseif (in_array($type, array(
'duration'))) {
8000 $out = $form->select_duration($keyprefix.$key.$keysuffix, $value, 0,
'text', 0, 1);
8001 } elseif (in_array($type, array(
'int',
'integer'))) {
8002 $tmp = explode(
',', $size);
8004 $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' :
'').
'>';
8005 } elseif (in_array($type, array(
'real'))) {
8006 $out =
'<input type="text" class="flat '.$morecss.
'" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.
dol_escape_htmltag($value).
'"'.($moreparam ? $moreparam :
'').($autofocusoncreate ?
' autofocus' :
'').
'>';
8007 } elseif (preg_match(
'/varchar/', (
string) $type)) {
8008 $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' :
'').
'>';
8009 } elseif (in_array($type, array(
'email',
'mail',
'phone',
'url',
'ip'))) {
8010 $out =
'<input type="text" class="flat '.$morecss.
'" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.
dol_escape_htmltag($value).
'" '.($moreparam ? $moreparam :
'').($autofocusoncreate ?
' autofocus' :
'').
'>';
8011 } elseif (preg_match(
'/^text/', (
string) $type)) {
8012 if (!preg_match(
'/search_/', $keyprefix)) {
8013 if (!empty($param[
'options'])) {
8016 $out .= $form->selectarray($keyprefix.$key.$keysuffix.
"_multiinput", $param[
'options'],
'', 1, 0, 0,
"flat maxwidthonphone".$morecss);
8017 $out .=
'<input id="'.$keyprefix.$key.$keysuffix.
'_multiinputadd" type="button" class="button" value="'.$langs->trans(
"Add").
'">';
8020 function handlemultiinputdisabling(htmlname){
8021 console.log("We handle the disabling of used options for "+htmlname+"_multiinput");
8022 multiinput = $("#"+htmlname+"_multiinput");
8023 multiinput.find("option").each(function(){
8024 tmpval = $("#"+htmlname).val();
8025 tmpvalarray = tmpval.split("\n");
8026 valtotest = $(this).val();
8027 if(tmpvalarray.includes(valtotest)){
8028 $(this).prop("disabled",true);
8030 if($(this).prop("disabled") == true){
8031 console.log(valtotest)
8032 $(this).prop("disabled", false);
8038 $(document).ready(function () {
8039 $("#'.$keyprefix.$key.$keysuffix.
'_multiinputadd").on("click",function() {
8040 tmpval = $("#'.$keyprefix.$key.$keysuffix.
'").val();
8041 tmpvalarray = tmpval.split(",");
8042 valtotest = $("#'.$keyprefix.$key.$keysuffix.
'_multiinput").val();
8043 if(valtotest != -1 && !tmpvalarray.includes(valtotest)){
8044 console.log("We add the selected value to the text area '.$keyprefix.$key.$keysuffix.
'");
8048 tmpval = tmpval + "\n" + valtotest;
8050 $("#'.$keyprefix.$key.$keysuffix.
'").val(tmpval);
8051 handlemultiinputdisabling("'.$keyprefix.$key.$keysuffix.
'");
8052 $("#'.$keyprefix.$key.$keysuffix.
'_multiinput").val(-1);
8054 console.log("We add nothing the text area '.$keyprefix.$key.$keysuffix.
'");
8057 $("#'.$keyprefix.$key.$keysuffix.
'").on("change",function(){
8058 handlemultiinputdisabling("'.$keyprefix.$key.$keysuffix.
'");
8060 handlemultiinputdisabling("'.$keyprefix.$key.$keysuffix.
'");
8062 $out .=
"</script>";
8063 $value = str_replace(
',',
"\n", $value);
8065 require_once DOL_DOCUMENT_ROOT.
'/core/class/doleditor.class.php';
8066 $doleditor =
new DolEditor($keyprefix.$key.$keysuffix, $value,
'', 200,
'dolibarr_notes',
'In',
false,
false,
false, ROWS_5,
'90%');
8067 $out .= (
string) $doleditor->Create(1,
'',
true,
'',
'',
'', $morecss);
8069 $out =
'<input type="text" class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.
dol_escape_htmltag($value).
'" '.($moreparam ? $moreparam :
'').
'>';
8071 } elseif (preg_match(
'/^html/', (
string) $type)) {
8072 if (!preg_match(
'/search_/', $keyprefix)) {
8073 require_once DOL_DOCUMENT_ROOT.
'/core/class/doleditor.class.php';
8074 $doleditor =
new DolEditor($keyprefix.$key.$keysuffix, $value,
'', 200,
'dolibarr_notes',
'In',
false,
false,
isModEnabled(
'fckeditor') &&
getDolGlobalInt(
'FCKEDITOR_ENABLE_SOCIETE'), ROWS_5,
'90%');
8075 $out = (
string) $doleditor->Create(1,
'',
true,
'',
'', $moreparam, $morecss);
8077 $out =
'<input type="text" class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.
dol_escape_htmltag($value).
'" '.($moreparam ? $moreparam :
'').
'>';
8079 } elseif ($type ==
'boolean') {
8081 if (!empty($value)) {
8082 $checked =
' checked value="1" ';
8084 $checked =
' value="1" ';
8086 $out =
'<input type="checkbox" class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" '.$checked.
' '.($moreparam ? $moreparam :
'').
'>';
8087 } elseif ($type ==
'price') {
8088 if (!empty($value)) {
8089 $value =
price($value);
8091 $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>';
8092 } elseif ($type ==
'stars') {
8093 $out =
'<input type="hidden" class="flat '.$morecss.
'" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.
dol_escape_htmltag($value).
'"'.($moreparam ? $moreparam :
'').($autofocusoncreate ?
' autofocus' :
'').
'>';
8094 $out .=
'<div class="star-selection" id="'.$keyprefix.$key.$keysuffix.
'_selection">';
8096 while ($i <= $size) {
8097 $out .=
'<span class="star" data-value="'.$i.
'">'.
img_picto(
'',
'fontawesome_star_fas').
'</span>';
8102 jQuery(function($) { /* commonobject.class.php 1 */
8103 let container = $("#'.$keyprefix.$key.$keysuffix.
'_selection");
8104 let selectedStars = parseInt($("#'.$keyprefix.$key.$keysuffix.
'").val()) || 0;
8105 container.find(".star").each(function() {
8106 $(this).toggleClass("active", $(this).data("value") <= selectedStars);
8108 container.find(".star").on("mouseover", function() {
8109 let selectedStar = $(this).data("value");
8110 container.find(".star").each(function() {
8111 $(this).toggleClass("active", $(this).data("value") <= selectedStar);
8114 container.on("mouseout", function() {
8115 container.find(".star").each(function() {
8116 $(this).toggleClass("active", $(this).data("value") <= selectedStars);
8119 container.find(".star").off("click").on("click", function() {
8120 selectedStars = $(this).data("value");
8121 if (selectedStars === 1 && $("#'.$keyprefix.$key.$keysuffix.
'").val() == 1) {
8124 $("#'.$keyprefix.$key.$keysuffix.
'").val(selectedStars);
8125 container.find(".star").each(function() {
8126 $(this).toggleClass("active", $(this).data("value") <= selectedStars);
8131 } elseif (preg_match(
'/^double(\([0-9],[0-9]\)){0,1}/', (
string) $type)) {
8132 if (!empty($value)) {
8133 $value =
price($value);
8135 $out =
'<input type="text" class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.$value.
'" '.($moreparam ? $moreparam :
'').
'> ';
8136 } elseif ($type ==
'select') {
8139 include_once DOL_DOCUMENT_ROOT.
'/core/lib/ajax.lib.php';
8140 $out .=
ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
8146 foreach ($param[
'options'] as $keyb => $valb) {
8147 if ((
string) $keyb ==
'') {
8150 if (strpos($valb,
"|") !==
false) {
8151 list($valb, $parent) = explode(
'|', $valb);
8154 $tmpselect .=
'<option value="'.$keyb.
'"';
8155 $tmpselect .= (((
string) $value == (
string) $keyb) ?
' selected' :
'');
8156 if (!empty($parent)) {
8159 $tmpselect .= (!empty($parent) ?
' parent="'.$parent.
'"' :
'');
8160 $tmpselect .=
'>'.$langs->trans($valb).
'</option>';
8163 $out .=
'<select class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" '.($moreparam ? $moreparam :
'').
'>';
8164 if ((!isset($this->fields[$key][
'default'])) || empty($this->fields[$key][
'notnull']) || ($this->fields[$key][
'notnull'] != 1) || $nbchoice >= 2) {
8165 $out .=
'<option value="0"> </option>';
8168 $out .=
'</select>';
8169 } elseif ($type ==
'sellist') {
8172 include_once DOL_DOCUMENT_ROOT.
'/core/lib/ajax.lib.php';
8173 $out .=
ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
8176 $out .=
'<select class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" '.($moreparam ? $moreparam :
'').
'>';
8177 if (is_array($param[
'options'])) {
8178 $tmpparamoptions = array_keys($param[
'options']);
8179 $paramoptions = preg_split(
'/[\r\n]+/', $tmpparamoptions[0]);
8181 $InfoFieldList = explode(
":", $paramoptions[0], 5);
8193 if (! empty($InfoFieldList[4])) {
8195 $parenthesisopen = 0;
8196 while (substr($InfoFieldList[4], $pos, 1) !==
'' && ($parenthesisopen || $pos == 0 || substr($InfoFieldList[4], $pos, 1) !=
':')) {
8197 if (substr($InfoFieldList[4], $pos, 1) ==
'(') {
8200 if (substr($InfoFieldList[4], $pos, 1) ==
')') {
8205 $tmpbefore = substr($InfoFieldList[4], 0, $pos);
8206 $tmpafter = substr($InfoFieldList[4], $pos + 1);
8208 $InfoFieldList[4] = $tmpbefore;
8209 if ($tmpafter !==
'') {
8210 $InfoFieldList = array_merge($InfoFieldList, explode(
':', $tmpafter));
8216 if (preg_match(
'/^\(?([a-z0-9]+)([=<>]+)(\d+)\)?$/i', $InfoFieldList[4], $reg)) {
8217 $InfoFieldList[4] =
'('.$reg[1].
':'.$reg[2].
':'.$reg[3].
')';
8228 $keyList = (empty($InfoFieldList[2]) ?
'rowid' : $InfoFieldList[2].
' as rowid');
8230 if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
8231 if (strpos($InfoFieldList[4],
'extra.') !==
false) {
8232 $keyList =
'main.'.$InfoFieldList[2].
' as rowid';
8234 $keyList = $InfoFieldList[2].
' as rowid';
8237 if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
8238 list($parentName, $parentField) = explode(
'|', $InfoFieldList[3]);
8239 if (!empty($InfoFieldList[4]) && strpos($InfoFieldList[4],
'extra.') !==
false) {
8240 $keyList .=
', main.'.$parentField;
8242 $keyList .=
', '.$parentField;
8246 $filter_categorie =
false;
8247 if (count($InfoFieldList) > 5) {
8248 if ($InfoFieldList[0] ==
'categorie') {
8249 $filter_categorie =
true;
8253 if (!$filter_categorie) {
8254 $fields_label = isset($InfoFieldList[1]) ? explode(
'|', $InfoFieldList[1]) : array();
8255 if (!empty($fields_label)) {
8257 $keyList .= implode(
', ', $fields_label);
8261 $sql =
"SELECT " . $this->db->sanitize($keyList, 0, 0, 1);
8262 $sql .=
" FROM " . $this->db->prefix() . $this->db->sanitize($InfoFieldList[0]);
8264 if (!empty($InfoFieldList[4])) {
8266 if (strpos($InfoFieldList[4],
'$SEL$') !==
false) {
8267 $InfoFieldList[4] = str_replace(
'$SEL$',
'SELECT', $InfoFieldList[4]);
8271 if (strpos($InfoFieldList[4],
'$ID$') !==
false && !empty($objectid)) {
8272 $InfoFieldList[4] = str_replace(
'$ID$', (
string) $objectid, $InfoFieldList[4]);
8274 $InfoFieldList[4] = str_replace(
'$ID$',
'0', $InfoFieldList[4]);
8279 if (strpos($InfoFieldList[4],
'extra') !==
false) {
8280 $sql .=
" as main, " . $this->db->sanitize($this->db->prefix() . $InfoFieldList[0]) .
"_extrafields as extra";
8281 $sqlwhere .=
" WHERE extra.fk_object = main." . $this->db->sanitize($InfoFieldList[2]);
8287 $sqlwhere .=
' WHERE 1=1';
8304 if (in_array($InfoFieldList[0], array(
'tablewithentity'))) {
8305 $sqlwhere .=
" AND entity = " . ((int)
$conf->entity);
8310 if (isset($InfoFieldList[7]) && preg_match(
'/^[a-z0-9_\-,]+$/i', $InfoFieldList[7])) {
8311 $sql .=
" ORDER BY ".$this->db->sanitize($InfoFieldList[7]);
8313 $sql .=
" ORDER BY ".$this->db->sanitize(implode(
', ', $fields_label));
8315 $sql .=
' LIMIT ' .
getDolGlobalInt(
'MAIN_EXTRAFIELDS_LIMIT_SELLIST_SQL', 1000);
8318 dol_syslog(get_class($this) .
'::showInputField type=sellist', LOG_DEBUG);
8319 $resql = $this->db->query($sql);
8321 $out .=
'<option value="0"> </option>';
8322 $num = $this->db->num_rows($resql);
8326 $obj = $this->db->fetch_object($resql);
8330 $fields_label = explode(
'|', $InfoFieldList[1]);
8331 if (count($fields_label) > 1) {
8333 foreach ($fields_label as $field_toshow) {
8334 $labeltoshow .= $obj->$field_toshow .
' ';
8337 $labeltoshow = $obj->{$InfoFieldList[1]};
8339 $labeltoshow =
dol_trunc($labeltoshow, 45);
8341 if ($value == $obj->rowid) {
8342 foreach ($fields_label as $field_toshow) {
8343 $translabel = $langs->trans($obj->$field_toshow);
8344 if ($translabel != $obj->$field_toshow) {
8345 $labeltoshow =
dol_trunc($translabel) .
' ';
8347 $labeltoshow =
dol_trunc($obj->$field_toshow) .
' ';
8350 $out .=
'<option value="' . $obj->rowid .
'" selected>' . $labeltoshow .
'</option>';
8353 $translabel = $langs->trans($obj->{$InfoFieldList[1]});
8354 if ($translabel != $obj->{$InfoFieldList[1]}) {
8355 $labeltoshow =
dol_trunc($translabel, 18);
8357 $labeltoshow =
dol_trunc($obj->{$InfoFieldList[1]});
8360 if (empty($labeltoshow)) {
8361 $labeltoshow =
'(not defined)';
8363 if ($value == $obj->rowid) {
8364 $out .=
'<option value="' . $obj->rowid .
'" selected>' . $labeltoshow .
'</option>';
8367 if (!empty($InfoFieldList[3]) && $parentField) {
8368 $parent = $parentName .
':' . $obj->{$parentField};
8372 $out .=
'<option value="' . $obj->rowid .
'"';
8373 $out .= ($value == $obj->rowid ?
' selected' :
'');
8374 $out .= (!empty($parent) ?
' parent="' . $parent .
'"' :
'');
8375 $out .=
'>' . $labeltoshow .
'</option>';
8380 $this->db->free($resql);
8382 print
'Error in request ' . $sql .
' ' . $this->db->lasterror() .
'. Check setup of extra parameters.<br>';
8385 require_once DOL_DOCUMENT_ROOT.
'/categories/class/categorie.class.php';
8386 $categcode = $InfoFieldList[5];
8387 if (is_numeric($categcode)) {
8388 $tmpcategory =
new Categorie($this->db);
8389 $MAP_ID_TO_CODE = array_flip($tmpcategory->MAP_ID);
8390 $categcode = $MAP_ID_TO_CODE[(int) $categcode];
8393 $data = $form->select_all_categories($categcode,
'',
'parent', 64, $InfoFieldList[6], 1, 1);
8394 $out .=
'<option value="0"> </option>';
8395 foreach ($data as $data_key => $data_value) {
8396 $out .=
'<option value="' . $data_key .
'"';
8397 $out .= ($value == $data_key ?
' selected' :
'');
8398 $out .=
'>' . $data_value .
'</option>';
8402 $out .=
'</select>';
8403 } elseif ($type ==
'checkbox') {
8404 $value_arr = explode(
',', $value);
8405 $out = $form->multiselectarray($keyprefix.$key.$keysuffix, (empty($param[
'options']) ?
null : $param[
'options']), $value_arr, 0, 0, $morecss, 0,
'100%');
8406 } elseif ($type ==
'radio') {
8408 foreach ($param[
'options'] as $keyopt => $valopt) {
8409 $out .=
'<input class="flat '.$morecss.
'" type="radio" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" '.($moreparam ? $moreparam :
'');
8410 $out .=
' value="'.$keyopt.
'"';
8411 $out .=
' id="'.$keyprefix.$key.$keysuffix.
'_'.$keyopt.
'"';
8412 $out .= ($value == $keyopt ?
'checked' :
'');
8413 $out .=
'/><label for="'.$keyprefix.$key.$keysuffix.
'_'.$keyopt.
'">'.$valopt.
'</label><br>';
8415 } elseif ($type ==
'chkbxlst') {
8416 if (is_array($value)) {
8417 $value_arr = $value;
8419 $value_arr = explode(
',', $value);
8422 if (is_array($param[
'options'])) {
8423 $tmpparamoptions = array_keys($param[
'options']);
8424 $paramoptions = preg_split(
'/[\r\n]+/', $tmpparamoptions[0]);
8426 $InfoFieldList = explode(
":", $paramoptions[0], 5);
8438 if (! empty($InfoFieldList[4])) {
8440 $parenthesisopen = 0;
8441 while (substr($InfoFieldList[4], $pos, 1) !==
'' && ($parenthesisopen || $pos == 0 || substr($InfoFieldList[4], $pos, 1) !=
':')) {
8442 if (substr($InfoFieldList[4], $pos, 1) ==
'(') {
8445 if (substr($InfoFieldList[4], $pos, 1) ==
')') {
8450 $tmpbefore = substr($InfoFieldList[4], 0, $pos);
8451 $tmpafter = substr($InfoFieldList[4], $pos + 1);
8453 $InfoFieldList[4] = $tmpbefore;
8454 if ($tmpafter !==
'') {
8455 $InfoFieldList = array_merge($InfoFieldList, explode(
':', $tmpafter));
8460 if (preg_match(
'/^\(?([a-z0-9]+)([=<>]+)(\d+)\)?$/i', $InfoFieldList[4], $reg)) {
8461 $InfoFieldList[4] =
'('.$reg[1].
':'.$reg[2].
':'.$reg[3].
')';
8469 '@phan-var-force array{0:string,1:string,2:string,3:string,3:string,5:string,6:string} $InfoFieldList';
8474 $keyList = (empty($InfoFieldList[2]) ?
'rowid' : $InfoFieldList[2].
' as rowid');
8476 if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
8477 if (strpos($InfoFieldList[4],
'extra.') !==
false) {
8478 $keyList =
'main.'.$InfoFieldList[2].
' as rowid';
8480 $keyList = $InfoFieldList[2].
' as rowid';
8483 if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
8484 list($parentName, $parentField) = explode(
'|', $InfoFieldList[3]);
8485 if (!empty($InfoFieldList[4]) && strpos($InfoFieldList[4],
'extra.') !==
false) {
8486 $keyList .=
', main.'.$parentField;
8488 $keyList .=
', '.$parentField;
8492 $filter_categorie =
false;
8493 if (count($InfoFieldList) > 5) {
8494 if ($InfoFieldList[0] ==
'categorie') {
8495 $filter_categorie =
true;
8500 if (!$filter_categorie) {
8501 $fields_label = explode(
'|', $InfoFieldList[1]);
8502 if (is_array($fields_label)) {
8504 $keyList .= implode(
', ', $fields_label);
8508 $sql =
"SELECT " . $this->db->sanitize($keyList, 0, 0, 1);
8509 $sql .=
' FROM ' . $this->db->prefix() . $this->db->sanitize($InfoFieldList[0]);
8511 if (!empty($InfoFieldList[4])) {
8513 if (strpos($InfoFieldList[4],
'$SEL$') !==
false) {
8514 $InfoFieldList[4] = str_replace(
'$SEL$',
'SELECT', $InfoFieldList[4]);
8518 if (strpos($InfoFieldList[4],
'$ID$') !==
false && !empty($objectid)) {
8519 $InfoFieldList[4] = str_replace(
'$ID$', (
string) $objectid, $InfoFieldList[4]);
8521 $InfoFieldList[4] = str_replace(
'$ID$',
'0', $InfoFieldList[4]);
8526 if (strpos($InfoFieldList[4],
'extra') !==
false) {
8527 $sql .=
' as main, ' . $this->db->sanitize($this->db->prefix() . $InfoFieldList[0]) .
'_extrafields as extra';
8528 $sqlwhere .=
" WHERE extra.fk_object = main." . $this->db->sanitize($InfoFieldList[2]);
8534 $sqlwhere .=
' WHERE 1=1';
8551 if (in_array($InfoFieldList[0], array(
'tablewithentity'))) {
8552 $sqlwhere .=
" AND entity = " . ((int)
$conf->entity);
8559 dol_syslog(get_class($this) .
'::showInputField type=chkbxlst', LOG_DEBUG);
8561 $resql = $this->db->query($sql);
8563 $num = $this->db->num_rows($resql);
8570 $obj = $this->db->fetch_object($resql);
8574 $fields_label = explode(
'|', $InfoFieldList[1]);
8575 if (count($fields_label) > 1) {
8577 foreach ($fields_label as $field_toshow) {
8578 $labeltoshow .= $obj->$field_toshow .
' ';
8581 $labeltoshow = $obj->{$InfoFieldList[1]};
8583 $labeltoshow =
dol_trunc($labeltoshow, 45);
8585 if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
8586 foreach ($fields_label as $field_toshow) {
8587 $translabel = $langs->trans($obj->$field_toshow);
8588 if ($translabel != $obj->$field_toshow) {
8589 $labeltoshow =
dol_trunc($translabel, 18) .
' ';
8591 $labeltoshow =
dol_trunc($obj->$field_toshow, 18) .
' ';
8595 $data[$obj->rowid] = $labeltoshow;
8598 $translabel = $langs->trans($obj->{$InfoFieldList[1]});
8599 if ($translabel != $obj->{$InfoFieldList[1]}) {
8600 $labeltoshow =
dol_trunc($translabel, 18);
8602 $labeltoshow =
dol_trunc($obj->{$InfoFieldList[1]}, 18);
8605 if (empty($labeltoshow)) {
8606 $labeltoshow =
'(not defined)';
8609 if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
8610 $data[$obj->rowid] = $labeltoshow;
8613 if (!empty($InfoFieldList[3]) && $parentField) {
8614 $parent = $parentName .
':' . $obj->{$parentField};
8618 $data[$obj->rowid] = $labeltoshow;
8623 $this->db->free($resql);
8625 $out = $form->multiselectarray($keyprefix . $key . $keysuffix, $data, $value_arr, 0, 0, $morecss, 0,
'100%');
8627 print
'Error in request ' . $sql .
' ' . $this->db->lasterror() .
'. Check setup of extra parameters.<br>';
8630 require_once DOL_DOCUMENT_ROOT.
'/categories/class/categorie.class.php';
8631 $categcode = $InfoFieldList[5];
8632 if (is_numeric($categcode)) {
8633 $tmpcategory =
new Categorie($this->db);
8634 $MAP_ID_TO_CODE = array_flip($tmpcategory->MAP_ID);
8635 $categcode = $MAP_ID_TO_CODE[(int) $categcode];
8638 $data = $form->select_all_categories($categcode,
'',
'parent', 64, $InfoFieldList[6], 1, 1);
8639 $out = $form->multiselectarray($keyprefix . $key . $keysuffix, $data, $value_arr, 0, 0, $morecss, 0,
'100%');
8642 } elseif ($type ==
'link') {
8645 $param_list = array_keys($param[
'options']);
8646 $param_list_array = explode(
':', $param_list[0], 4);
8648 $showempty = (($required && $default !=
'') ? 0 : 1);
8650 if (!preg_match(
'/search_/', $keyprefix)) {
8651 if (!empty($param_list_array[2])) {
8653 if (!empty($this->fields[$key][
'picto'])) {
8654 $morecss .=
' widthcentpercentminusxx';
8656 $morecss .=
' widthcentpercentminusx';
8660 if (!empty($this->fields[$key][
'picto'])) {
8661 $morecss .=
' widthcentpercentminusx';
8670 $objectfield = $val;
8673 $out = $form->selectForForms($param_list_array[0], $keyprefix.$key.$keysuffix, (
int) $value, $showempty,
'',
'', $morecss, $moreparam, 0, (empty($val[
'disabled']) ? 0 : 1),
'', $objectfield);
8675 if (!empty($param_list_array[2])) {
8676 if ((!
GETPOSTISSET(
'backtopage') || strpos(
GETPOST(
'backtopage'), $_SERVER[
'PHP_SELF']) === 0)
8677 && empty($val[
'disabled']) && empty($nonewbutton)) {
8678 list($class, $classfile) = explode(
':', $param_list[0]);
8679 if (file_exists(
dol_buildpath(dirname(dirname($classfile)).
'/card.php'))) {
8680 $url_path =
dol_buildpath(dirname(dirname($classfile)).
'/card.php', 1);
8682 $url_path =
dol_buildpath(dirname(dirname($classfile)).
'/'.strtolower($class).
'_card.php', 1);
8684 $paramforthenewlink =
'';
8685 $paramforthenewlink .= (
GETPOSTISSET(
'action') ?
'&action='.GETPOST(
'action',
'aZ09') :
'');
8686 $paramforthenewlink .= (
GETPOSTISSET(
'id') ?
'&id='.GETPOSTINT(
'id') :
'');
8687 $paramforthenewlink .= (
GETPOSTISSET(
'origin') ?
'&origin='.GETPOST(
'origin',
'aZ09') :
'');
8688 $paramforthenewlink .= (
GETPOSTISSET(
'originid') ?
'&originid='.GETPOSTINT(
'originid') :
'');
8689 $paramforthenewlink .=
'&fk_'.strtolower($class).
'=--IDFORBACKTOPAGE--';
8691 $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>';
8694 } elseif ($type ==
'password') {
8696 if ($keyprefix.$key.$keysuffix ==
'pass_crypted') {
8697 $out =
'<input type="'.($keyprefix ==
'search_' ?
'text' :
'password').
'" class="flat '.$morecss.
'" name="pass" id="pass" value="" '.($moreparam ? $moreparam :
'').
'>';
8698 $out .=
'<input type="hidden" name="pass_crypted" id="pass_crypted" value="'.$value.
'" '.($moreparam ? $moreparam :
'').
'>';
8700 $out =
'<input type="'.($keyprefix ==
'search_' ?
'text' :
'password').
'" class="flat '.$morecss.
'" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.$value.
'" '.($moreparam ? $moreparam :
'').
'>';
8702 } elseif ($type ==
'array') {
8704 $newval[
'type'] =
'varchar(256)';
8707 if (!empty($value)) {
8708 foreach ($value as $option) {
8709 $out .=
'<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).
'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
8710 $out .= $this->showInputField($newval, $keyprefix.$key.$keysuffix.
'[]', $option, $moreparam,
'',
'', $morecss).
'<br></span>';
8713 $out .=
'<a id="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).
'_add" href="javascript:;"><span class="fa fa-plus-circle valignmiddle"></span></a>';
8715 $newInput =
'<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).
'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
8716 $newInput .= $this->showInputField($newval, $keyprefix.$key.$keysuffix.
'[]',
'', $moreparam,
'',
'', $morecss).
'<br></span>';
8718 if (!empty(
$conf->use_javascript_ajax)) {
8720 <script nonce="'.getNonce().
'">
8721 $(document).ready(function() {
8722 $("a#'.
dol_escape_js($keyprefix.$key.$keysuffix).
'_add").click(function() {
8726 $(document).on("click", "a.'.
dol_escape_js($keyprefix.$key.$keysuffix).
'_del", function() {
8727 $(this).parent().remove();
8733 if (!empty($hidden)) {
8734 $out =
'<input type="hidden" value="'.$value.
'" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'"/>';
8737 if ($isDependList == 1) {
8738 $out .= $this->getJSListDependancies(
'_common');
8746 if (!empty($fieldValidationErrorMsg) && function_exists(
'getFieldErrorIcon')) {
8747 $out .=
' '.getFieldErrorIcon($fieldValidationErrorMsg);
8766 public function showOutputField($val, $key, $value, $moreparam =
'', $keysuffix =
'', $keyprefix =
'', $morecss =
'')
8768 global
$conf, $langs, $form;
8772 if (!is_object($form)) {
8773 require_once DOL_DOCUMENT_ROOT.
'/core/class/html.form.class.php';
8774 $form =
new Form($this->db);
8778 $type = empty($val[
'type']) ?
'' : $val[
'type'];
8779 $size = empty($val[
'css']) ?
'' : $val[
'css'];
8784 if (preg_match(
'/varchar\((\d+)\)/', $type, $reg)) {
8787 } elseif (preg_match(
'/varchar/', $type)) {
8790 if (!empty($val[
'arrayofkeyval']) && is_array($val[
'arrayofkeyval'])) {
8792 if (empty($this->fields[$key][
'multiinput'])) {
8793 $type = (($this->fields[$key][
'type'] ==
'checkbox') ? $this->fields[$key][
'type'] :
'select');
8796 if (isset($val[
'type']) && preg_match(
'/^integer:(.*):(.*)/i', $val[
'type'], $reg)) {
8800 $default = empty($val[
'default']) ?
'' : $val[
'default'];
8801 $computed = empty($val[
'computed']) ?
'' : $val[
'computed'];
8802 $unique = empty($val[
'unique']) ?
'' : $val[
'unique'];
8803 $required = empty($val[
'required']) ?
'' : $val[
'required'];
8805 $param[
'options'] = array();
8807 if (!empty($val[
'arrayofkeyval']) && is_array($val[
'arrayofkeyval'])) {
8808 $param[
'options'] = $val[
'arrayofkeyval'];
8810 if (isset($val[
'type']) && preg_match(
'/^integer:([^:]*):([^:]*)/i', $val[
'type'], $reg)) {
8812 $stringforoptions = $reg[1].
':'.$reg[2];
8814 if ($reg[1] ==
'User') {
8815 $stringforoptions .=
':#getnomurlparam1=-1';
8817 $param[
'options'] = array($stringforoptions => $stringforoptions);
8818 } elseif (isset($val[
'type']) && preg_match(
'/^sellist:(.*):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
8819 $param[
'options'] = array($reg[1].
':'.$reg[2].
':'.$reg[3].
':'.$reg[4] =>
'N');
8821 } elseif (isset($val[
'type']) && preg_match(
'/^sellist:(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
8822 $param[
'options'] = array($reg[1].
':'.$reg[2].
':'.$reg[3] =>
'N');
8824 } elseif (isset($val[
'type']) && preg_match(
'/^sellist:(.*):(.*)/i', $val[
'type'], $reg)) {
8825 $param[
'options'] = array($reg[1].
':'.$reg[2] =>
'N');
8827 } elseif (isset($val[
'type']) && preg_match(
'/^chkbxlst:(.*)/i', $val[
'type'], $reg)) {
8828 $param[
'options'] = array($reg[1] =>
'N');
8830 } elseif (isset($val[
'type']) && preg_match(
'/stars\((\d+)\)/', $val[
'type'], $reg)) {
8831 $param[
'options'] = array();
8836 $langfile = empty($val[
'langfile']) ?
'' : $val[
'langfile'];
8837 $list = (empty($val[
'list']) ?
'' : $val[
'list']);
8838 $help = (empty($val[
'help']) ?
'' : $val[
'help']);
8839 $hidden = (($val[
'visible'] == 0) ? 1 : 0);
8849 $value =
dol_eval((
string) $computed, 1, 0,
'2');
8852 if (empty($morecss)) {
8853 if ($type ==
'date') {
8854 $morecss =
'minwidth100imp';
8855 } elseif ($type ==
'datetime' || $type ==
'timestamp') {
8856 $morecss =
'minwidth200imp';
8857 } elseif (in_array($type, array(
'int',
'double',
'price'))) {
8858 $morecss =
'maxwidth75';
8859 } elseif ($type ==
'url') {
8860 $morecss =
'minwidth400';
8861 } elseif ($type ==
'boolean') {
8864 if (is_numeric($size) && round((
float) $size) < 12) {
8865 $morecss =
'minwidth100';
8866 } elseif (is_numeric($size) && round((
float) $size) <= 48) {
8867 $morecss =
'minwidth200';
8869 $morecss =
'minwidth400';
8875 if (in_array($key, array(
'rowid',
'ref')) && method_exists($this,
'getNomUrl')) {
8877 if ($key !=
'rowid' || empty($this->fields[
'ref'])) {
8878 $value = $this->getNomUrl(1,
'', 0,
'', 1);
8880 } elseif ($key ==
'status' && method_exists($this,
'getLibStatut')) {
8881 $value = $this->getLibStatut(3);
8882 } elseif ($type ==
'date') {
8883 if (!empty($value)) {
8888 } elseif ($type ==
'datetime' || $type ==
'timestamp') {
8889 if (!empty($value)) {
8894 } elseif ($type ==
'duration') {
8895 include_once DOL_DOCUMENT_ROOT.
'/core/lib/date.lib.php';
8896 if (!is_null($value) && $value !==
'') {
8899 } elseif ($type ==
'double' || $type ==
'real') {
8900 if (!is_null($value) && $value !==
'') {
8901 $value =
price($value);
8903 } elseif ($type ==
'boolean') {
8905 if (!empty($value)) {
8906 $checked =
' checked ';
8909 $value =
'<input type="checkbox" '.$checked.
' '.($moreparam ? $moreparam :
'').
' readonly disabled>';
8911 $value =
yn($value ? 1 : 0);
8913 } elseif ($type ==
'mail' || $type ==
'email') {
8915 } elseif ($type ==
'url') {
8917 } elseif ($type ==
'phone') {
8918 $value =
dol_print_phone((
string) $value,
'', 0, 0,
'',
' ',
'phone');
8919 } elseif ($type ==
'ip') {
8921 } elseif ($type ==
'stars') {
8922 $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 :
'').
'>';
8923 $value .=
'<div class="star-selection" id="'.$keyprefix.$key.$keysuffix.$this->id.
'_selection">';
8925 while ($i <= $size) {
8926 $value .=
'<span class="star" data-value="'.$i.
'">'.
img_picto(
'',
'fontawesome_star_fas').
'</span>';
8931 $(document).ready(function() { /* commonobject.class.php 2 */
8932 let container = $("#'.$keyprefix.$key.$keysuffix.$this->id.
'_selection");
8933 let selectedStars = parseInt($("#'.$keyprefix.$key.$keysuffix.$this->id.
'").val()) || 0;
8934 container.find(".star").each(function() {
8935 $(this).toggleClass("active", $(this).data("value") <= selectedStars);
8937 container.find(".star").on("mouseover", function() {
8938 let selectedStar = $(this).data("value");
8939 container.find(".star").each(function() {
8940 $(this).toggleClass("active", $(this).data("value") <= selectedStar);
8943 container.on("mouseout", function() {
8944 container.find(".star").each(function() {
8945 $(this).toggleClass("active", $(this).data("value") <= selectedStars);
8948 container.find(".star").off("click").on("click", function() {
8949 selectedStars = $(this).data("value");
8950 if (selectedStars == 1 && $("#'.$keyprefix.$key.$keysuffix.$this->id.
'").val() == 1) {
8953 container.find("#'.$keyprefix.$key.$keysuffix.$this->id.
'").val(selectedStars);
8954 container.find(".star").each(function() {
8955 $(this).toggleClass("active", $(this).data("value") <= selectedStars);
8958 url: "ajax/'.$this->element.
'.php",
8961 objectId: "'.$this->
id.
'",
8962 field: "'.$keyprefix.$key.$keysuffix.
'",
8963 value: selectedStars,
8966 success: function(response) {
8967 var res = JSON.parse(response);
8968 console[res.status === "success" ? "log" : "error"](res.message);
8970 error: function(xhr, status, error) {
8971 console.log("Ajax request failed while updating '.$keyprefix.$key.$keysuffix.
':", error);
8977 } elseif ($type ==
'price') {
8978 if (!is_null($value) && $value !==
'') {
8979 $value =
price($value, 0, $langs, 0, 0, -1,
$conf->currency);
8981 } elseif ($type ==
'select') {
8982 $value = isset($param[
'options'][(
string) $value]) ? $param[
'options'][(
string) $value] :
'';
8983 if (strpos($value,
"|") !==
false) {
8984 $value = $langs->trans(explode(
'|', $value)[0]);
8985 } elseif (! is_numeric($value)) {
8986 $value = $langs->trans($value);
8988 } elseif ($type ==
'sellist') {
8989 $param_list = array_keys($param[
'options']);
8990 $InfoFieldList = explode(
":", $param_list[0]);
8992 $selectkey =
"rowid";
8995 if (count($InfoFieldList) > 2 && !empty($InfoFieldList[2])) {
8996 $selectkey = $InfoFieldList[2];
8997 $keyList = $InfoFieldList[2].
' as rowid';
9000 $fields_label = explode(
'|', $InfoFieldList[1]);
9001 if (is_array($fields_label)) {
9003 $keyList .= implode(
', ', $fields_label);
9006 $filter_categorie =
false;
9007 if (count($InfoFieldList) > 5) {
9008 if ($InfoFieldList[0] ==
'categorie') {
9009 $filter_categorie =
true;
9013 $sql =
"SELECT ".$this->db->sanitize($keyList, 0, 0, 1);
9014 $sql .=
' FROM '.$this->db->prefix().$this->db->sanitize($InfoFieldList[0]);
9015 if (isset($InfoFieldList[4]) && strpos($InfoFieldList[4],
'extra') !==
false) {
9018 if ($selectkey ==
'rowid' && empty($value)) {
9019 $sql .=
" WHERE ".$this->db->sanitize($selectkey).
" = 0";
9020 } elseif ($selectkey ==
'rowid') {
9021 $sql .=
" WHERE ".$this->db->sanitize($selectkey).
" = ".((int) $value);
9023 $sql .=
" WHERE ".$this->db->sanitize($selectkey).
" = '".$this->db->escape((
string) $value).
"'";
9028 dol_syslog(get_class($this).
':showOutputField:$type=sellist', LOG_DEBUG);
9029 $resql = $this->db->query($sql);
9031 if (!$filter_categorie) {
9033 $numrows = $this->db->num_rows($resql);
9035 $obj = $this->db->fetch_object($resql);
9038 $fields_label = explode(
'|', $InfoFieldList[1]);
9040 if (is_array($fields_label) && count($fields_label) > 1) {
9041 foreach ($fields_label as $field_toshow) {
9043 if (!empty($obj->$field_toshow)) {
9044 $translabel = $langs->trans($obj->$field_toshow);
9046 if ($translabel != $field_toshow) {
9047 $value .=
dol_trunc($translabel, 18) .
' ';
9049 $value .= $obj->$field_toshow .
' ';
9054 if (!empty($obj->{$InfoFieldList[1]})) {
9055 $translabel = $langs->trans($obj->{$InfoFieldList[1]});
9057 if ($translabel != $obj->{$InfoFieldList[1]}) {
9060 $value = $obj->{$InfoFieldList[1]};
9065 require_once DOL_DOCUMENT_ROOT .
'/categories/class/categorie.class.php';
9068 $obj = $this->db->fetch_object($resql);
9070 $c->fetch($obj->rowid);
9071 $ways =
$c->print_all_ways();
9072 foreach ($ways as $way) {
9073 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories"' . (
$c->color ?
' style="background: #' .
$c->color .
';"' :
' style="background: #aaa"') .
'>' .
img_object(
'',
'category') .
' ' . $way .
'</li>';
9075 $value =
'<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(
' ', $toprint).
'</ul></div>';
9078 dol_syslog(get_class($this).
'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
9080 } elseif ($type ==
'radio') {
9081 $value = $param[
'options'][(
string) $value];
9082 } elseif ($type ==
'checkbox') {
9083 $value_arr = explode(
',', (
string) $value);
9085 if (is_array($value_arr) && count($value_arr) > 0) {
9087 foreach ($value_arr as $keyval => $valueval) {
9088 if (!empty($valueval)) {
9089 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' . $param[
'options'][$valueval] .
'</li>';
9092 if (!empty($toprint)) {
9093 $value =
'<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">' . implode(
' ', $toprint) .
'</ul></div>';
9096 } elseif ($type ==
'chkbxlst') {
9097 $value_arr = (isset($value) ? explode(
',', $value) : array());
9099 $param_list = array_keys($param[
'options']);
9100 $InfoFieldList = explode(
":", $param_list[0]);
9102 $selectkey =
"rowid";
9105 if (count($InfoFieldList) >= 3) {
9106 $selectkey = $InfoFieldList[2];
9107 $keyList = $InfoFieldList[2].
' as rowid';
9110 $fields_label = explode(
'|', $InfoFieldList[1]);
9111 if (is_array($fields_label)) {
9113 $keyList .= implode(
', ', $fields_label);
9116 $filter_categorie =
false;
9117 if (count($InfoFieldList) > 5) {
9118 if ($InfoFieldList[0] ==
'categorie') {
9119 $filter_categorie =
true;
9123 $sql =
"SELECT ".$this->db->sanitize($keyList, 0, 0, 1);
9124 $sql .=
' FROM '.$this->db->prefix().$this->db->sanitize($InfoFieldList[0]);
9125 if (isset($InfoFieldList[4]) && strpos($InfoFieldList[4],
'extra') !==
false) {
9131 dol_syslog(get_class($this).
':showOutputField:$type=chkbxlst', LOG_DEBUG);
9132 $resql = $this->db->query($sql);
9134 if (!$filter_categorie) {
9137 while ($obj = $this->db->fetch_object($resql)) {
9139 $fields_label = explode(
'|', $InfoFieldList[1]);
9140 if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
9141 if (is_array($fields_label) && count($fields_label) > 1) {
9142 foreach ($fields_label as $field_toshow) {
9144 if (!empty($obj->$field_toshow)) {
9145 $translabel = $langs->trans($obj->$field_toshow);
9147 if ($translabel != $field_toshow) {
9148 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' .
dol_trunc($translabel, 18) .
'</li>';
9150 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' . $obj->$field_toshow .
'</li>';
9155 if (!empty($obj->{$InfoFieldList[1]})) {
9156 $translabel = $langs->trans($obj->{$InfoFieldList[1]});
9158 if ($translabel != $obj->{$InfoFieldList[1]}) {
9159 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' .
dol_trunc($translabel, 18) .
'</li>';
9161 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' . $obj->{$InfoFieldList[1]} .
'</li>';
9167 require_once DOL_DOCUMENT_ROOT .
'/categories/class/categorie.class.php';
9170 while ($obj = $this->db->fetch_object($resql)) {
9171 if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
9173 $c->fetch($obj->rowid);
9174 $ways =
$c->print_all_ways();
9175 foreach ($ways as $way) {
9176 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories"' . (
$c->color ?
' style="background: #' .
$c->color .
';"' :
' style="background: #aaa"') .
'>' .
img_object(
'',
'category') .
' ' . $way .
'</li>';
9181 $value =
'<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(
' ', $toprint).
'</ul></div>';
9183 dol_syslog(get_class($this).
'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
9185 } elseif ($type ==
'link') {
9190 $param_list = array_keys($param[
'options']);
9194 $InfoFieldList = explode(
":", $param_list[0]);
9196 $classname = $InfoFieldList[0];
9197 $classpath = $InfoFieldList[1];
9200 $getnomurlparam = 3;
9201 $getnomurlparam2 =
'';
9203 if (preg_match(
'/#getnomurlparam1=([^#]*)/', $param_list[0], $regtmp)) {
9204 $getnomurlparam = $regtmp[1];
9206 if (preg_match(
'/#getnomurlparam2=([^#]*)/', $param_list[0], $regtmp)) {
9207 $getnomurlparam2 = $regtmp[1];
9210 if (!empty($classpath)) {
9213 if ($classname && !class_exists($classname)) {
9217 if ($element_prop) {
9218 $classname = $element_prop[
'classname'];
9223 if ($classname && class_exists($classname)) {
9224 $object =
new $classname($this->db);
9225 '@phan-var-force CommonObject $object';
9226 if (
$object->element ===
'product') {
9227 '@phan-var-force Product $object';
9228 $result =
$object->fetch((
int) $value,
'',
'',
'', 0, 1, 1);
9230 $result =
$object->fetch($value);
9233 if (
$object->element ===
'product') {
9234 '@phan-var-force Product $object';
9235 $get_name_url_param_arr = array($getnomurlparam, $getnomurlparam2, 0, -1, 0,
'', 0);
9236 if (isset($val[
'get_name_url_params'])) {
9237 $get_name_url_params = explode(
':', $val[
'get_name_url_params']);
9238 if (!empty($get_name_url_params)) {
9239 $param_num_max = count($get_name_url_param_arr) - 1;
9240 foreach ($get_name_url_params as $param_num => $param_value) {
9241 if ($param_num > $param_num_max) {
9244 $get_name_url_param_arr[$param_num] = $param_value;
9252 $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]);
9254 $value =
$object->getNomUrl($getnomurlparam, $getnomurlparam2);
9261 dol_syslog(
'Error bad setup of extrafield', LOG_WARNING);
9262 return 'Error bad setup of extrafield';
9267 } elseif ($type ==
'password') {
9268 $value =
'<span class="opacitymedium">'.$langs->trans(
"Encrypted").
'</span>';
9270 } elseif ($type ==
'array') {
9271 if (is_array($value)) {
9272 $value = implode(
'<br>', $value);
9274 dol_syslog(__METHOD__.
' Expected array from dol_eval, but got '.gettype($value), LOG_ERR);
9275 return 'Error unexpected result from code evaluation';
9278 if (!empty($value) && preg_match(
'/^text/', (
string) $type) && !preg_match(
'/search_/', $keyprefix) && !empty($param[
'options'])) {
9279 $value = str_replace(
',',
"\n", $value);
9287 return is_null($out) ?
'' : $out;
9299 unset($this->validateFieldsErrors[$fieldKey]);
9313 $msg = $langs->trans(
"UnknownError");
9316 $this->error = $this->validateFieldsErrors[$fieldKey] = $msg;
9327 if (!empty($this->validateFieldsErrors[$fieldKey])) {
9328 return $this->validateFieldsErrors[$fieldKey];
9345 if (!class_exists(
'Validate')) {
9346 require_once DOL_DOCUMENT_ROOT .
'/core/class/validate.class.php';
9349 $this->clearFieldError($fieldKey);
9351 if (!array_key_exists($fieldKey, $fields) || !is_array($fields[$fieldKey])) {
9352 $this->setFieldError($fieldKey, $langs->trans(
'FieldNotFoundInObject'));
9356 $val = $fields[$fieldKey];
9359 $param[
'options'] = array();
9360 $type = $val[
'type'];
9363 if (isset($val[
'notnull']) && $val[
'notnull'] === 1) {
9377 if (preg_match(
'/varchar\((\d+)\)/', $type, $reg)) {
9379 $maxSize = (int) $reg[1];
9380 } elseif (preg_match(
'/varchar/', $type)) {
9384 if (!empty($val[
'arrayofkeyval']) && is_array($val[
'arrayofkeyval'])) {
9388 if (!empty($val[
'type']) && preg_match(
'/^integer:(.*):(.*)/i', $val[
'type'], $reg)) {
9392 if (!empty($val[
'arrayofkeyval']) && is_array($val[
'arrayofkeyval'])) {
9393 $param[
'options'] = $val[
'arrayofkeyval'];
9396 if (preg_match(
'/^integer:(.*):(.*)/i', $val[
'type'], $reg)) {
9398 $param[
'options'] = array($reg[1].
':'.$reg[2] => $reg[1].
':'.$reg[2]);
9399 } elseif (preg_match(
'/^sellist:(.*):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
9400 $param[
'options'] = array($reg[1].
':'.$reg[2].
':'.$reg[3].
':'.$reg[4] =>
'N');
9402 } elseif (preg_match(
'/^sellist:(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
9403 $param[
'options'] = array($reg[1].
':'.$reg[2].
':'.$reg[3] =>
'N');
9405 } elseif (preg_match(
'/^sellist:(.*):(.*)/i', $val[
'type'], $reg)) {
9406 $param[
'options'] = array($reg[1].
':'.$reg[2] =>
'N');
9415 $validate =
new Validate($this->db, $langs);
9425 if ($required && !$validate->isNotEmptyString($fieldValue)) {
9426 $this->setFieldError($fieldKey, $validate->error);
9428 } elseif (!$required && !$validate->isNotEmptyString($fieldValue)) {
9434 if (!empty($maxSize) && !$validate->isMaxLength($fieldValue, $maxSize)) {
9435 $this->setFieldError($fieldKey, $validate->error);
9440 if (!empty($minSize) && !$validate->isMinLength($fieldValue, $minSize)) {
9441 $this->setFieldError($fieldKey, $validate->error);
9449 if (in_array($type, array(
'date',
'datetime',
'timestamp'))) {
9450 if (!$validate->isTimestamp($fieldValue)) {
9451 $this->setFieldError($fieldKey, $validate->error);
9456 } elseif ($type ==
'duration') {
9457 if (!$validate->isDuration($fieldValue)) {
9458 $this->setFieldError($fieldKey, $validate->error);
9463 } elseif (in_array($type, array(
'double',
'real',
'price'))) {
9465 if (!$validate->isNumeric($fieldValue)) {
9466 $this->setFieldError($fieldKey, $validate->error);
9471 } elseif ($type ==
'boolean') {
9472 if (!$validate->isBool($fieldValue)) {
9473 $this->setFieldError($fieldKey, $validate->error);
9478 } elseif ($type ==
'mail' || $type ==
'email') {
9479 if (!$validate->isEmail($fieldValue)) {
9480 $this->setFieldError($fieldKey, $validate->error);
9483 } elseif ($type ==
'url') {
9484 if (!$validate->isUrl($fieldValue)) {
9485 $this->setFieldError($fieldKey, $validate->error);
9490 } elseif ($type ==
'phone') {
9491 if (!$validate->isPhone($fieldValue)) {
9492 $this->setFieldError($fieldKey, $validate->error);
9497 } elseif ($type ==
'select' || $type ==
'radio') {
9498 if (!isset($param[
'options'][$fieldValue])) {
9499 $this->error = $langs->trans(
'RequireValidValue');
9504 } elseif ($type ==
'sellist' || $type ==
'chkbxlst') {
9505 $param_list = array_keys($param[
'options']);
9506 $InfoFieldList = explode(
":", $param_list[0]);
9507 $value_arr = explode(
',', $fieldValue);
9509 $selectkey =
"rowid";
9510 if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
9511 $selectkey = $InfoFieldList[2];
9514 if (!$validate->isInDb($value_arr, $InfoFieldList[0], $selectkey)) {
9515 $this->setFieldError($fieldKey, $validate->error);
9520 } elseif ($type ==
'link') {
9521 $param_list = array_keys($param[
'options']);
9522 $InfoFieldList = explode(
":", $param_list[0]);
9523 $classname = $InfoFieldList[0];
9524 $classpath = $InfoFieldList[1];
9525 if (!$validate->isFetchable((
int) $fieldValue, $classname, $classpath)) {
9526 $lastIsFetchableError = $validate->error;
9529 if ($validate->isFetchableElement((
int) $fieldValue, $classname)) {
9533 $this->setFieldError($fieldKey, $lastIsFetchableError);
9557 public function showOptionals($extrafields, $mode =
'view', $params =
null, $keysuffix =
'', $keyprefix =
'', $onetrtd =
'', $display_type =
'card')
9559 global
$db,
$conf, $langs, $action, $form, $hookmanager;
9560 global $objectoffield;
9562 if (!is_object($form)) {
9565 if (!is_object($extrafields)) {
9566 dol_syslog(
'Bad parameter extrafields for showOptionals', LOG_ERR);
9567 return 'Bad parameter extrafields for showOptionals';
9569 if (!is_array($extrafields->attributes[$this->table_element])) {
9570 dol_syslog(
"extrafields->attributes was not loaded with extrafields->fetch_name_optionals_label(table_element);", LOG_WARNING);
9574 $objectoffield = $this;
9578 $parameters = array(
'mode' => $mode,
'params' => $params,
'keysuffix' => $keysuffix,
'keyprefix' => $keyprefix,
'display_type' => $display_type);
9579 $reshook = $hookmanager->executeHooks(
'showOptionals', $parameters, $this, $action);
9580 $hookResPrint = $hookmanager->resPrint;
9582 if (empty($reshook)) {
9583 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) {
9585 $out .=
'<!-- commonobject:showOptionals --> ';
9588 $nbofextrafieldsshown = 0;
9591 $lastseparatorkeyfound =
'';
9592 $extrafields_collapse_num =
'';
9593 $extrafields_collapse_num_old =
'';
9596 foreach ($extrafields->attributes[$this->table_element][
'label'] as $key => $label) {
9600 if (is_array($params) && array_key_exists(
'onlykey', $params) && $key != $params[
'onlykey']) {
9606 if ($enabled && isset($extrafields->attributes[$this->table_element][
'enabled'][$key])) {
9607 $enabled = (int)
dol_eval((
string) $extrafields->attributes[$this->table_element][
'enabled'][$key], 1, 1,
'2');
9609 if (empty($enabled)) {
9614 if (isset($extrafields->attributes[$this->table_element][
'list'][$key])) {
9615 $visibility = (int)
dol_eval((
string) $extrafields->attributes[$this->table_element][
'list'][$key], 1, 1,
'2');
9619 if ($perms && isset($extrafields->attributes[$this->table_element][
'perms'][$key])) {
9620 $perms = (int)
dol_eval((
string) $extrafields->attributes[$this->table_element][
'perms'][$key], 1, 1,
'2');
9623 if (($mode ==
'create') && !in_array(abs($visibility), array(1, 3))) {
9625 } elseif (($mode ==
'edit') && !in_array(abs($visibility), array(1, 3, 4))) {
9629 $ef_name =
'options_' . $key;
9630 $ef_value = $this->array_options[$ef_name] ??
'';
9631 $out .=
'<input type="hidden" name="' . $ef_name .
'" id="' . $ef_name .
'" value="' .
dol_htmlentities($ef_value) .
'" />' .
"\n";
9633 } elseif ($mode ==
'view' && empty($visibility)) {
9636 if (empty($perms)) {
9641 if (!empty($extrafields->attributes[$this->table_element][
'langfile'][$key])) {
9642 $langs->load($extrafields->attributes[$this->table_element][
'langfile'][$key]);
9647 if (is_array($params) && count($params) > 0 && $display_type ==
'card') {
9648 if (array_key_exists(
'cols', $params)) {
9649 $colspan = $params[
'cols'];
9650 } elseif (array_key_exists(
'colspan', $params)) {
9652 if (preg_match(
'/colspan="(\d+)"/', $params[
'colspan'], $reg)) {
9655 $colspan = $params[
'colspan'];
9659 $colspan = intval($colspan);
9663 $value = ((!empty($this->array_options) && array_key_exists(
"options_".$key.$keysuffix, $this->array_options)) ? $this->array_options[
"options_".$key.$keysuffix] :
null);
9669 $check =
'alphanohtml';
9670 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'html',
'text'))) {
9671 $check =
'restricthtml';
9673 $getposttemp =
GETPOST($keyprefix.
'options_'.$key.$keysuffix, $check, 3);
9675 if (is_array($getposttemp) || $getposttemp !=
'' ||
GETPOSTISSET($keyprefix.
'options_'.$key.$keysuffix)) {
9676 if (is_array($getposttemp)) {
9678 $value = implode(
",", $getposttemp);
9680 $value = $getposttemp;
9682 } elseif (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'int'))) {
9683 $value = (!empty($this->array_options[
"options_".$key]) || (isset($this->array_options[
"options_".$key]) && $this->array_options[
"options_".$key] ===
'0')) ? $this->array_options[
"options_".$key] :
'';
9684 } elseif (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'varchar',
'char'))) {
9685 $value = (isset($this->array_options[
"options_".$key]) && $this->array_options[
"options_".$key] !==
'') ? $this->array_options[
"options_".$key] :
'';
9687 $value = (!empty($this->array_options[
"options_".$key]) ? $this->array_options[
"options_".$key] :
'');
9693 $nbofextrafieldsshown++;
9696 if ($extrafields->attributes[$this->table_element][
'type'][$key] ==
'separate') {
9697 $extrafields_collapse_num = $key;
9715 $out .= $extrafields->showSeparator($key, $this, ($colspan ? $colspan + 1 : 2), $display_type, $mode);
9717 $lastseparatorkeyfound = $key;
9719 $collapse_group = $extrafields_collapse_num.(!empty($this->
id) ?
'_'.$this->id :
'');
9721 $class = (!empty($extrafields->attributes[$this->table_element][
'hidden'][$key]) ?
'hideobject ' :
'');
9723 if (is_array($params) && count($params) > 0) {
9724 if (array_key_exists(
'class', $params)) {
9725 $class .= $params[
'class'].
' ';
9727 if (array_key_exists(
'style', $params)) {
9728 $csstyle = $params[
'style'];
9733 $domData =
' data-element="extrafield"';
9734 $domData .=
' data-targetelement="'.$this->element.
'"';
9735 $domData .=
' data-targetid="'.$this->id.
'"';
9737 $html_id = (empty($this->
id) ?
'' :
'extrarow-'.$this->element.
'_'.$key.
'_'.
$this->id);
9738 if ($display_type ==
'card') {
9743 if ($action ==
'selectlines') {
9750 $force_values_on_change_company = (
9751 ($this->element ==
'facture' &&
getDolGlobalInt(
'THIRDPARTY_PROPAGATE_EXTRAFIELDS_TO_INVOICE'))
9752 || ($this->element ==
'commande' &&
getDolGlobalInt(
'THIRDPARTY_PROPAGATE_EXTRAFIELDS_TO_ORDER'))
9753 || ($this->element ==
'order_supplier' &&
getDolGlobalInt(
'THIRDPARTY_PROPAGATE_EXTRAFIELDS_TO_SUPPLIER_ORDER'))
9755 if ($force_values_on_change_company &&
GETPOSTINT(
'changecompany')) {
9756 $value = $this->array_options[
'options_'.$key] ?? $value;
9760 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'date'))) {
9761 $datenotinstring =
null;
9762 if (array_key_exists(
'options_'.$key, $this->array_options)) {
9763 $datenotinstring = $this->array_options[
'options_'.$key];
9764 if (!is_numeric($this->array_options[
'options_'.$key])) {
9765 $datenotinstring = $this->db->jdate($datenotinstring);
9768 $datekey = $keyprefix.
'options_'.$key.$keysuffix;
9771 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'datetime'))) {
9772 $datenotinstring =
null;
9773 if (array_key_exists(
'options_'.$key, $this->array_options)) {
9774 $datenotinstring = $this->array_options[
'options_'.$key];
9775 if (!is_numeric($this->array_options[
'options_'.$key])) {
9776 $datenotinstring = $this->db->jdate($datenotinstring);
9779 $timekey = $keyprefix.
'options_'.$key.$keysuffix;
9780 $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;
9783 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'price',
'double'))) {
9784 if (
GETPOSTISSET($keyprefix.
'options_'.$key.$keysuffix) || $value) {
9786 } elseif (isset($this->array_options[
'options_'.$key])) {
9787 $value = $this->array_options[
'options_'.$key];
9792 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'html',
'text',
'varchar',
'select',
'radio',
'int',
'boolean'))) {
9793 if ($action ==
'create' || $mode ==
'create') {
9794 $value = (
GETPOSTISSET($keyprefix.
'options_'.$key.$keysuffix) || $value) ? $value : $extrafields->attributes[$this->table_element][
'default'][$key];
9798 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'checkbox'))) {
9799 if ($action ==
'create') {
9800 $value = (
GETPOSTISSET($keyprefix.
'options_'.$key.$keysuffix) || $value) ? $value : explode(
',', $extrafields->attributes[$this->table_element][
'default'][$key]);
9805 $labeltoshow = $langs->trans($label);
9806 $helptoshow = $langs->trans($extrafields->attributes[$this->table_element][
'help'][$key]);
9807 if ($display_type ==
'card') {
9808 $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.
' >';
9809 if (
getDolGlobalString(
'MAIN_VIEW_LINE_NUMBER') && ($action ==
'view' || $action ==
'valid' || $action ==
'editline' || $action ==
'confirm_valid' || $action ==
'confirm_cancel')) {
9810 $out .=
'<td></td>';
9812 $out .=
'<td class="'.(empty($params[
'tdclass']) ?
'titlefieldmax45' : $params[
'tdclass']).
' wordbreak';
9813 if ($extrafields->attributes[$this->table_element][
'type'][$key] ==
'text') {
9816 } elseif ($display_type ==
'line') {
9817 $out .=
'<div '.($html_id ?
'id="'.$html_id.
'" ' :
'').$csstyle.
' class="fieldline_options_'.$key.
' '.$class.$this->element.
'_extras_'.$key.
' trextrafields_collapse'.$collapse_group.
'" '.$domData.
' >';
9818 $out .=
'<div style="display: inline-block; padding-right:4px" class="wordbreak';
9823 $tpl_context = isset($params[
"tpl_context"]) ? $params[
"tpl_context"] :
"none";
9824 if ($tpl_context !=
"public") {
9825 if ($mode !=
'view' && !empty($extrafields->attributes[$this->table_element][
'required'][$key])) {
9826 $out .=
' fieldrequired';
9830 if ($tpl_context ==
"public") {
9831 if (!empty($extrafields->attributes[$this->table_element][
'help'][$key])) {
9832 $out .= $form->textwithpicto($labeltoshow, $helptoshow);
9834 $out .= $labeltoshow;
9836 if ($mode !=
'view' && !empty($extrafields->attributes[$this->table_element][
'required'][$key])) {
9837 $out .=
' <span style="color: red">*</span>';
9840 if (!empty($extrafields->attributes[$this->table_element][
'help'][$key])) {
9841 $out .= $form->textwithpicto($labeltoshow, $helptoshow);
9843 $out .= $labeltoshow;
9847 $out .= ($display_type ==
'card' ?
'</td>' :
'</div>');
9850 $html_id = !empty($this->
id) ? $this->element.
'_extras_'.$key.
'_'.$this->id :
'';
9851 if ($display_type ==
'card') {
9853 $out .=
'<td '.($html_id ?
'id="'.$html_id.
'" ' :
'').
' class="valuefieldcreate '.$this->element.
'_extras_'.$key;
9854 $out .=
'" '.($colspan ?
' colspan="'.$colspan.
'"' :
'');
9856 } elseif ($display_type ==
'line') {
9857 $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].
'">';
9862 $out .= $extrafields->showOutputField($key, $value,
'', $this->table_element);
9865 $listoftypestoshowpicto = explode(
',',
getDolGlobalString(
'MAIN_TYPES_TO_SHOW_PICTO',
'email,phone,ip,password'));
9866 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], $listoftypestoshowpicto)) {
9867 $out .=
getPictoForType($extrafields->attributes[$this->table_element][
'type'][$key], ($extrafields->attributes[$this->table_element][
'type'][$key] ==
'text' ?
'tdtop' :
''));
9870 $out .= $extrafields->showInputField($key, $value,
'', $keysuffix,
'',
'', $this, $this->table_element);
9873 $listoftypestoshowpicto = explode(
',',
getDolGlobalString(
'MAIN_TYPES_TO_SHOW_PICTO',
'email,phone,ip,password'));
9874 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], $listoftypestoshowpicto)) {
9875 $out .=
getPictoForType($extrafields->attributes[$this->table_element][
'type'][$key], ($extrafields->attributes[$this->table_element][
'type'][$key] ==
'text' ?
'tdtop' :
''));
9877 $out .= $extrafields->showInputField($key, $value,
'', $keysuffix,
'',
'', $this, $this->table_element);
9881 $out .= ($display_type ==
'card' ?
'</td>' :
'</div>');
9882 $out .= ($display_type ==
'card' ?
'</tr>'.
"\n" :
'</div>');
9888 if (!empty(
$conf->use_javascript_ajax)) {
9889 $out .= $this->getJSListDependancies();
9892 $out .=
'<!-- commonobject:showOptionals end --> '.
"\n";
9894 if (empty($nbofextrafieldsshown)) {
9900 $out .= $hookResPrint;
9912 <script nonce="'.getNonce().
'">
9913 jQuery(document).ready(function() {
9914 function showOptions'.$type.
'(child_list, parent_list, orig_select)
9916 var val = $("select[name=\""+parent_list+"\"]").val();
9917 var parentVal = parent_list + ":" + val;
9918 if(typeof val == "string"){
9920 var options = orig_select.find("option[parent=\""+parentVal+"\"]").clone();
9921 $("select[name=\""+child_list+"\"] option[parent]").remove();
9922 $("select[name=\""+child_list+"\"]").append(options);
9924 var options = orig_select.find("option[parent]").clone();
9925 $("select[name=\""+child_list+"\"] option[parent]").remove();
9926 $("select[name=\""+child_list+"\"]").append(options);
9928 } else if(val > 0) {
9929 var options = orig_select.find("option[parent=\""+parentVal+"\"]").clone();
9930 $("select[name=\""+child_list+"\"] option[parent]").remove();
9931 $("select[name=\""+child_list+"\"]").append(options);
9933 var options = orig_select.find("option[parent]").clone();
9934 $("select[name=\""+child_list+"\"] option[parent]").remove();
9935 $("select[name=\""+child_list+"\"]").append(options);
9938 function setListDependencies'.$type.
'() {
9939 jQuery("select option[parent]").parent().each(function() {
9940 var orig_select = {};
9941 var child_list = $(this).attr("name");
9942 orig_select[child_list] = $(this).clone();
9943 var parent = $(this).find("option[parent]:first").attr("parent");
9944 var infos = parent.split(":");
9945 var parent_list = infos[0];
9947 //Hide daughters lists
9948 if ($("#"+child_list).val() == 0 && $("#"+parent_list).val() == 0){
9949 $("#"+child_list).hide();
9951 } else if ($("#"+parent_list).val() != 0){
9952 $("#"+parent_list).show();
9954 //Show the child list if the parent list value is selected
9955 $("select[name=\""+parent_list+"\"]").click(function() {
9956 if ($(this).val() != 0){
9957 $("#"+child_list).show()
9961 //When we change parent list
9962 $("select[name=\""+parent_list+"\"]").change(function() {
9963 showOptions'.$type.
'(child_list, parent_list, orig_select[child_list]);
9964 //Select the value 0 on child list after a change on the parent list
9965 $("#"+child_list).val(0).trigger("change");
9966 //Hide child lists if the parent value is set to 0
9967 if ($(this).val() == 0){
9968 $("#"+child_list).hide();
9974 setListDependencies'.$type.
'();
9989 $module = empty($this->module) ?
'' : $this->module;
9990 $element = $this->element;
9992 if ($element ==
'facturerec') {
9993 $element =
'facture';
9994 } elseif ($element ==
'invoice_supplier_rec') {
9995 return !$user->hasRight(
'fournisseur',
'facture') ? null : $user->hasRight(
'fournisseur',
'facture');
9996 } elseif ($module && $user->hasRight($module, $element)) {
9998 return $user->hasRight($module, $element);
10001 return $user->rights->$element;
10018 global $hookmanager;
10020 $parameters = array(
10021 'origin_id' => $origin_id,
10022 'dest_id' => $dest_id,
10023 'tables' => $tables,
10025 $reshook = $hookmanager->executeHooks(
'commonReplaceThirdparty', $parameters);
10028 } elseif ($reshook < 0) {
10029 return $ignoreerrors === 1;
10032 foreach ($tables as $table) {
10033 $sql =
'UPDATE '.$dbs->prefix().$table.
' SET fk_soc = '.((int) $dest_id).
' WHERE fk_soc = '.((int) $origin_id);
10035 if (!$dbs->
query($sql)) {
10036 if ($ignoreerrors) {
10061 foreach ($tables as $table) {
10062 $sql =
'UPDATE '.MAIN_DB_PREFIX.$table.
' SET fk_product = '.((int) $dest_id).
' WHERE fk_product = '.((int) $origin_id);
10064 if (!$dbs->
query($sql)) {
10065 if ($ignoreerrors) {
10088 public function defineBuyPrice($unitPrice = 0.0, $discountPercent = 0.0, $fk_product = 0)
10094 if (($unitPrice > 0) && (isset(
$conf->global->ForceBuyingPriceIfNull) &&
getDolGlobalInt(
'ForceBuyingPriceIfNull') > 0)) {
10096 $buyPrice = $unitPrice * (1 - $discountPercent / 100);
10099 if (!empty($fk_product) && $fk_product > 0) {
10102 require_once DOL_DOCUMENT_ROOT.
'/product/class/product.class.php';
10103 $product =
new Product($this->db);
10104 $result = $product->fetch($fk_product);
10105 if ($result <= 0) {
10106 $this->errors[] =
'ErrorProductIdDoesNotExists';
10109 if ($product->cost_price > 0) {
10110 $buyPrice = $product->cost_price;
10111 } elseif ($product->pmp > 0) {
10112 $buyPrice = $product->pmp;
10115 require_once DOL_DOCUMENT_ROOT.
'/product/class/product.class.php';
10116 $product =
new Product($this->db);
10117 $result = $product->fetch($fk_product);
10118 if ($result <= 0) {
10119 $this->errors[] =
'ErrorProductIdDoesNotExists';
10122 if ($product->pmp > 0) {
10123 $buyPrice = $product->pmp;
10127 if (empty($buyPrice) && in_array(
getDolGlobalString(
'MARGIN_TYPE'), array(
'1',
'pmp',
'costprice'))) {
10128 require_once DOL_DOCUMENT_ROOT.
'/fourn/class/fournisseur.product.class.php';
10130 if (($result = $productFournisseur->find_min_price_product_fournisseur($fk_product)) > 0) {
10131 $buyPrice = $productFournisseur->fourn_unitprice;
10132 } elseif ($result < 0) {
10133 $this->errors[] = $productFournisseur->error;
10140 return (
float) $buyPrice;
10153 return array(
'dir' =>
'',
'file' =>
'',
'originalfile' =>
'',
'altfile' =>
'',
'email' =>
'',
'capture' =>
'');
10177 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')
10180 global $user, $langs;
10182 include_once DOL_DOCUMENT_ROOT.
'/core/lib/files.lib.php';
10183 include_once DOL_DOCUMENT_ROOT.
'/core/lib/images.lib.php';
10184 include_once DOL_DOCUMENT_ROOT.
'/core/class/link.class.php';
10186 $sortfield =
'position_name';
10187 $sortorder =
'asc';
10192 $dir .=
get_exdir(0, 0, 0, 0, $this, $modulepart);
10193 $pdir .=
get_exdir(0, 0, 0, 0, $this, $modulepart);
10196 if ($modulepart ==
'product') {
10198 $dir = $sdir.
'/'.
get_exdir($this->
id, 2, 0, 0, $this, $modulepart).$this->id.
"/photos/";
10199 $pdir =
'/'.get_exdir($this->
id, 2, 0, 0, $this, $modulepart).$this->id.
"/photos/";
10202 if ($modulepart ==
'category') {
10203 $dir = $sdir.
'/'.
get_exdir($this->
id, 2, 0, 0, $this, $modulepart).$this->id.
"/photos/";
10204 $pdir =
'/'.get_exdir($this->
id, 2, 0, 0, $this, $modulepart).$this->id.
"/photos/";
10210 $relativedir = preg_replace(
'/^'.preg_quote(DOL_DATA_ROOT,
'/').
'/',
'', $dir);
10211 $relativedir = preg_replace(
'/^[\\/]/',
'', $relativedir);
10212 $relativedir = preg_replace(
'/[\\/]$/',
'', $relativedir);
10215 $dirthumb = $dir.
'thumbs/';
10216 $pdirthumb = $pdir.
'thumbs/';
10218 $return =
'<!-- Photo -->'.
"\n";
10221 $filearray =
dol_dir_list($dir,
"files", 0,
'',
'(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) ==
'desc' ? SORT_DESC : SORT_ASC), 1);
10230 '@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';
10232 $useLinkPathPhoto =
false;
10235 $link =
new Link($this->db);
10237 $link->fetchAll($links,
'product', $this->
id);
10239 if (count($links) > 0) {
10240 $useLinkPathPhoto =
true;
10243 if ($useLinkPathPhoto) {
10245 if ($nbbyrow > 0) {
10246 $return .=
'<table class="valigntop center centpercent" style="border:0; padding:2px; border-spacing:2px; border-collapse: separate;">';
10250 foreach ($links as $link) {
10251 if (!empty($link->url) && preg_match(
'/\.(jpg|jpeg|png|gif|webp)$/i', $link->url)) {
10256 if ($nbbyrow > 0 && ($i % $nbbyrow == 1)) {
10257 $return .=
'<tr class="center valignmiddle">';
10260 if ($nbbyrow > 0) {
10261 $return .=
'<td style="width:'.ceil(100 / $nbbyrow).
'%" class="photo">';
10263 $return .=
'<div class="inline-block">';
10266 $return .=
'<img class="photo photowithmargin'.($addphotorefcss ?
' '.$addphotorefcss :
'').
'"'.($maxHeight ?
' height="'.$maxHeight.
'"' :
'').
' src="'.$url.
'" title="External image">';
10268 if ($nbbyrow > 0) {
10269 $return .=
'</td>';
10270 if ($i % $nbbyrow == 0) {
10271 $return .=
'</tr>';
10274 $return .=
'</div>';
10277 if ($nbmax && $nbphoto >= $nbmax) {
10283 if ($nbbyrow > 0) {
10284 while ($i % $nbbyrow) {
10285 $return .=
'<td style="width:'.ceil(100 / $nbbyrow).
'%"> </td>';
10289 $return .=
'</table>';
10295 if (count($filearray)) {
10296 if ($sortfield && $sortorder) {
10297 $filearray =
dol_sort_array($filearray, $sortfield, $sortorder);
10300 foreach ($filearray as $key => $val) {
10302 $file = $val[
'name'];
10308 $viewfilename = $file;
10310 if ($size == 1 || $size ==
'small') {
10316 $pdirthumb = $pdir;
10317 $photo_vignette = basename($file);
10323 if ($nbbyrow > 0) {
10324 if ($nbphoto == 1) {
10325 $return .=
'<table class="valigntop center centpercent" style="border: 0; padding: 2px; border-spacing: 2px; border-collapse: separate;">';
10328 if ($nbphoto % $nbbyrow == 1) {
10329 $return .=
'<tr class="center valignmiddle" style="border: 1px">';
10331 $return .=
'<td style="width: '.ceil(100 / $nbbyrow).
'%" class="photo">'.
"\n";
10332 } elseif ($nbbyrow < 0) {
10333 $return .=
'<div class="inline-block">'.
"\n";
10336 $relativefile = preg_replace(
'/^\//',
'', $pdir.$photo);
10337 if (empty($nolink)) {
10339 if ($urladvanced) {
10340 $return .=
'<a href="'.$urladvanced.
'">';
10342 $return .=
'<a href="'.DOL_URL_ROOT.
'/viewimage.php?modulepart='.$modulepart.
'&entity='.$this->entity.
'&file='.urlencode($pdir.$photo).
'" class="aphoto" target="_blank" rel="noopener noreferrer">';
10348 $alt = $langs->transnoentitiesnoconv(
'File').
': '.$relativefile;
10349 $alt .=
' - '.$langs->transnoentitiesnoconv(
'Size').
': '.$imgarray[
'width'].
'x'.$imgarray[
'height'];
10350 if ($overwritetitle) {
10351 if (is_numeric($overwritetitle)) {
10354 $alt = $overwritetitle;
10357 if (empty($cache) && !empty($val[
'label'])) {
10360 $cache = $val[
'label'];
10362 if ($usesharelink) {
10363 if (array_key_exists(
'share', $val) && $val[
'share']) {
10364 if (empty($maxHeight) || ($photo_vignette && $imgarray[
'height'] > $maxHeight)) {
10365 $return .=
'<!-- Show original file (thumb not yet available with shared links) -->';
10366 $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).
'">';
10368 $return .=
'<!-- Show original file -->';
10369 $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).
'">';
10372 $return .=
'<!-- Show nophoto file (because file is not shared) -->';
10373 $return .=
'<img class="photo photowithmargin'.($addphotorefcss ?
' '.$addphotorefcss :
'').
'" height="'.$maxHeight.
'" src="'.DOL_URL_ROOT.
'/public/theme/common/nophoto.png" title="'.
dol_escape_htmltag($alt).
'">';
10376 if (empty($maxHeight) || ($photo_vignette && $imgarray[
'height'] > $maxHeight)) {
10377 $return .=
'<!-- Show thumb -->';
10378 $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).
'">';
10380 $return .=
'<!-- Show original file -->';
10381 $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).
'">';
10385 if (empty($nolink)) {
10389 if ($showfilename) {
10390 $return .=
'<br>'.$viewfilename;
10395 if ($photo_vignette && (
image_format_supported($photo) > 0) && ((isset($imgarray[
'width']) && $imgarray[
'width'] > $maxWidth) || (isset($imgarray[
'width']) && $imgarray[
'width'] > $maxHeight))) {
10396 $return .=
'<a href="'.$_SERVER[
"PHP_SELF"].
'?id='.$this->
id.
'&action=addthumb&token='.
newToken().
'&file='.urlencode($pdir.$viewfilename).
'">'.
img_picto($langs->trans(
'GenerateThumb'),
'refresh').
' </a>';
10399 if ($modulepart ==
'product' && ($user->hasRight(
'produit',
'creer') || $user->hasRight(
'service',
'creer'))) {
10401 $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> ';
10404 $return .=
'<a href="'.$_SERVER[
"PHP_SELF"].
'?id='.$this->
id.
'&action=delete&token='.
newToken().
'&file='.urlencode($pdir.$viewfilename).
'">';
10410 if ($nbbyrow > 0) {
10411 $return .=
'</td>';
10412 if (($nbphoto % $nbbyrow) == 0) {
10413 $return .=
'</tr>';
10415 } elseif ($nbbyrow < 0) {
10416 $return .=
'</div>'.
"\n";
10420 if (empty($size)) {
10421 $return .=
'<img class="photo photowithmargin" src="'.DOL_URL_ROOT.
'/viewimage.php?modulepart='.$modulepart.
'&entity='.$this->entity.
'&file='.urlencode($pdir.$photo).
'">';
10423 if ($showfilename) {
10424 $return .=
'<br>'.$viewfilename;
10428 if ($modulepart ==
'product' && ($user->hasRight(
'produit',
'creer') || $user->hasRight(
'service',
'creer'))) {
10430 $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> ';
10433 $return .=
'<a href="'.$_SERVER[
"PHP_SELF"].
'?id='.$this->
id.
'&action=delete&token='.
newToken().
'&file='.urlencode($pdir.$viewfilename).
'">';
10440 if ($nbmax && $nbphoto >= $nbmax) {
10446 if ($size == 1 || $size ==
'small') {
10447 if ($nbbyrow > 0) {
10449 while ($nbphoto % $nbbyrow) {
10450 $return .=
'<td style="width: '.ceil(100 / $nbbyrow).
'%"> </td>';
10455 $return .=
'</table>';
10461 $this->nbphoto = $nbphoto;
10475 if (is_array($info)) {
10476 if (isset($info[
'type']) && $info[
'type'] ==
'array') {
10493 if (isset($info[
'type']) && ($info[
'type'] ==
'date' || $info[
'type'] ==
'datetime' || $info[
'type'] ==
'timestamp')) {
10507 if (is_array($info)) {
10508 if (isset($info[
'type']) && ($info[
'type'] ==
'duration')) {
10526 if (is_array($info)) {
10527 if (isset($info[
'type']) && (preg_match(
'/^(?:tiny|small|medium|big)?int|int$/i', $info[
'type']))) {
10545 if (is_array($info)) {
10546 if (isset($info[
'type']) && (preg_match(
'/^(double|real|price)/i', $info[
'type']))) {
10563 if (is_array($info)) {
10564 if (isset($info[
'type']) && $info[
'type'] ==
'text') {
10581 if (is_array($info)) {
10582 if (array_key_exists(
'notnull', $info) && $info[
'notnull'] !=
'1') {
10599 if (is_array($info)) {
10600 if (array_key_exists(
'notnull', $info) && $info[
'notnull'] ==
'-1') {
10617 if (is_array($info)) {
10618 if (array_key_exists(
'index', $info) && $info[
'index'] ==
true) {
10640 $queryarray = array();
10641 foreach ($this->fields as $field => $info) {
10643 if ($this->isDate($info)) {
10644 if (empty($this->{$field})) {
10645 $queryarray[$field] =
null;
10647 $queryarray[$field] = $this->db->idate($this->{$field});
10649 } elseif ($this->isDuration($info)) {
10651 if ((isset($this->{$field}) && $this->{$field} !=
'') || !empty($info[
'notnull'])) {
10652 if (!isset($this->{$field})) {
10653 if (!empty($info[
'default'])) {
10654 $queryarray[$field] = $info[
'default'];
10656 $queryarray[$field] = 0;
10659 $queryarray[$field] = (int) $this->{$field};
10662 $queryarray[$field] =
null;
10664 } elseif ($this->isInt($info) || $this->isFloat($info)) {
10665 if ($field ==
'entity' && is_null($this->{$field})) {
10666 $queryarray[$field] = ((int)
$conf->entity);
10669 if ((isset($this->{$field}) && ((
string) $this->{$field}) !=
'') || !empty($info[
'notnull'])) {
10670 if (!isset($this->{$field})) {
10671 $queryarray[$field] = 0;
10672 } elseif ($this->isInt($info)) {
10673 $queryarray[$field] = (int) $this->{$field};
10674 } elseif ($this->isFloat($info)) {
10675 $queryarray[$field] = (float) $this->{$field};
10678 $queryarray[$field] =
null;
10684 $queryarray[$field] = $this->{$field};
10687 if (array_key_exists(
'type', $info) && $info[
'type'] ==
'timestamp' && empty($queryarray[$field])) {
10688 unset($queryarray[$field]);
10690 if (!empty($info[
'notnull']) && $info[
'notnull'] == -1 && empty($queryarray[$field])) {
10691 $queryarray[$field] =
null;
10695 return $queryarray;
10708 foreach ($this->fields as $field => $info) {
10709 if ($this->isDate($info)) {
10710 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') {
10711 $this->$field =
'';
10713 $this->$field =
$db->jdate($obj->$field);
10715 } elseif ($this->isInt($info)) {
10716 if ($field ==
'rowid') {
10717 $this->
id = (int) $obj->$field;
10719 if ($this->isForcedToNullIfZero($info)) {
10720 if (empty($obj->$field)) {
10721 $this->$field =
null;
10723 $this->$field = (int) $obj->$field;
10726 if (isset($obj->$field) && (!is_null($obj->$field) || (array_key_exists(
'notnull', $info) && $info[
'notnull'] == 1))) {
10727 $this->$field = (int) $obj->$field;
10729 $this->$field =
null;
10733 } elseif ($this->isFloat($info)) {
10734 if ($this->isForcedToNullIfZero($info)) {
10735 if (empty($obj->$field)) {
10736 $this->$field =
null;
10738 $this->$field = (float) $obj->$field;
10741 if (isset($obj->$field) && (!is_null($obj->$field) || (array_key_exists(
'notnull', $info) && $info[
'notnull'] == 1))) {
10742 $this->$field = (float) $obj->$field;
10744 $this->$field =
null;
10748 $this->$field = isset($obj->$field) ? $obj->$field :
null;
10753 if (!isset($this->fields[
'ref']) && isset($this->
id)) {
10764 foreach ($this->fields as $field => $arr) {
10765 $this->$field =
null;
10778 $keys = array_keys($this->fields);
10779 if (!empty($alias)) {
10780 $keys_with_alias = array();
10781 foreach ($keys as $fieldname) {
10782 if (!empty($excludefields)) {
10783 if (in_array($fieldname, $excludefields)) {
10787 $keys_with_alias[] = $this->db->sanitize($alias .
'.' . $fieldname);
10789 return implode(
', ', $keys_with_alias);
10791 return implode(
', ', $keys);
10802 protected function quote($value, $fieldsentry)
10804 if (is_null($value)) {
10806 } elseif (preg_match(
'/^(int|double|real|price)/i', $fieldsentry[
'type'])) {
10808 } elseif (preg_match(
'/int$/i', $fieldsentry[
'type'])) {
10809 return (
int) $value;
10810 } elseif ($fieldsentry[
'type'] ==
'boolean') {
10817 return "'".$this->db->escape($value).
"'";
10834 dol_syslog(get_class($this).
"::createCommon create", LOG_DEBUG);
10840 $fieldvalues = $this->setSaveQuery();
10844 if (array_key_exists(
'date_creation', $fieldvalues) && empty($fieldvalues[
'date_creation'])) {
10845 $fieldvalues[
'date_creation'] = $this->db->idate($now);
10846 $this->date_creation = $this->db->idate($now);
10849 if (array_key_exists(
'fk_user_creat', $fieldvalues) && !($fieldvalues[
'fk_user_creat'] > 0)) {
10850 $fieldvalues[
'fk_user_creat'] = $user->id;
10851 $this->fk_user_creat = $user->id;
10853 if (array_key_exists(
'user_creation_id', $fieldvalues) && !($fieldvalues[
'user_creation_id'] > 0)) {
10854 $fieldvalues[
'user_creation_id'] = $user->id;
10855 $this->user_creation_id = $user->id;
10857 if (array_key_exists(
'pass_crypted', $fieldvalues) && property_exists($this,
'pass')) {
10859 $tmparray =
dol_hash($this->pass,
'0', 0, 1);
10860 $fieldvalues[
'pass_crypted'] = $tmparray[
'pass_encrypted'];
10861 if (array_key_exists(
'pass_encoding', $fieldvalues) && property_exists($this,
'pass_encoding')) {
10862 $fieldvalues[
'pass_encoding'] = $tmparray[
'pass_encoding'];
10865 if (array_key_exists(
'ref', $fieldvalues)) {
10868 if (
getDolGlobalString(
'MAIN_DISABLE_AUTO_UPDATE_OF_TMS_FIELDS') && array_key_exists(
'tms', $fieldvalues)) {
10869 $fieldvalues[
'tms'] = $this->db->idate($now);
10872 unset($fieldvalues[
'rowid']);
10874 $sanitized_keys = array();
10875 $sanitized_values = array();
10876 foreach ($fieldvalues as $k => $v) {
10877 $sanitized_keys[$k] = $k;
10878 $value = $this->fields[$k];
10880 $sanitized_values[$k] = $this->quote($v, $value);
10884 foreach ($sanitized_keys as $key) {
10885 if (!isset($this->fields[$key])) {
10888 $key_fields = $this->fields[$key];
10891 if (preg_match(
'/^integer:/i', $key_fields[
'type']) && $sanitized_values[$key] ==
'-1') {
10892 $sanitized_values[$key] =
'';
10894 if (!empty($key_fields[
'foreignkey']) && $sanitized_values[$key] ==
'-1') {
10895 $sanitized_values[$key] =
'';
10898 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']))) {
10901 if (empty($langs)) {
10902 require_once DOL_DOCUMENT_ROOT.
'/core/class/translate.class.php';
10904 $langs->setDefaultLang();
10905 $langs->load(
"errors");
10907 dol_syslog(
"Mandatory field '".$key.
"' is empty and required into ->fields definition of class");
10908 $this->errors[] = $langs->trans(
"ErrorFieldRequired", isset($key_fields[
'label']) ? $key_fields[
'label'] : $key);
10912 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'])) {
10913 $sanitized_values[$key] = $this->quote($key_fields[
'default'], $key_fields);
10917 if (isset($key_fields[
'type']) && preg_match(
'/^integer:/i', $key_fields[
'type']) && empty($sanitized_values[$key])) {
10918 if (isset($key_fields[
'default'])) {
10919 $sanitized_values[$key] = ((int) $key_fields[
'default']);
10921 $sanitized_values[$key] =
'null';
10924 if (!empty($key_fields[
'foreignkey']) && empty($sanitized_values[$key])) {
10925 $sanitized_values[$key] =
'null';
10933 $this->db->begin();
10936 $sql =
"INSERT INTO ".$this->db->prefix().$this->table_element;
10937 $sql .=
" (".implode(
", ", $sanitized_keys).
')';
10938 $sql .=
" VALUES (".implode(
", ", $sanitized_values).
")";
10940 $res = $this->db->query($sql);
10943 if ($this->db->lasterrno() ==
'DB_ERROR_RECORD_ALREADY_EXISTS') {
10944 $this->errors[] =
"ErrorRefAlreadyExists";
10946 $this->errors[] = $this->db->lasterror();
10952 $this->
id = $this->db->last_insert_id($this->db->prefix().$this->table_element);
10958 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)') {
10959 $sql =
"UPDATE ".$this->db->prefix().$this->table_element.
" SET ref = '(PROV".((int) $this->
id).
")' WHERE (ref = '(PROV)' OR ref = '') AND rowid = ".((int) $this->
id);
10960 $resqlupdate = $this->db->query($sql);
10962 if ($resqlupdate ===
false) {
10964 $this->errors[] = $this->db->lasterror();
10966 $this->
ref =
'(PROV'.$this->id.
')';
10973 $result = $this->insertExtraFields();
10980 if (!empty($this->table_element_line) && !empty($this->fk_element) && !empty($this->lines)) {
10981 foreach ($this->lines as $line) {
10982 $keyforparent = $this->fk_element;
10987 if (!is_object($line)) {
10988 $line = (object) $line;
10992 if (method_exists($line,
'insert')) {
10993 $result = $line->insert($user, 1);
10994 } elseif (method_exists($line,
'create')) {
10995 $result = $line->create($user, 1);
10998 $this->error = $line->error;
10999 $this->db->rollback();
11006 if (!$error && !$notrigger) {
11008 $result = $this->call_trigger(strtoupper(get_class($this)).
'_CREATE', $user);
11017 $this->db->rollback();
11020 $this->db->commit();
11037 if (empty(
$id) && empty($ref) && empty($morewhere)) {
11041 $fieldlist = $this->getFieldList(
't');
11042 if (empty($fieldlist)) {
11046 $sql =
"SELECT ".$this->db->sanitize($fieldlist, 0, 0, 1);
11047 $sql .=
" FROM ".$this->db->prefix().$this->table_element.
' as t';
11050 $sql .=
' WHERE t.rowid = '.((int)
$id);
11051 } elseif (!empty($ref)) {
11052 $sql .=
" WHERE t.ref = '".$this->db->escape($ref).
"'";
11054 $sql .=
' WHERE 1 = 1';
11056 if (empty(
$id) && isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
11057 $sql .=
' AND t.entity IN ('.getEntity($this->element).
')';
11060 $sql .= $morewhere;
11062 $sql .=
' LIMIT 1';
11064 $res = $this->db->query($sql);
11066 $obj = $this->db->fetch_object($res);
11068 $this->setVarsFromFetchObj($obj);
11072 if (empty($noextrafields)) {
11073 $result = $this->fetch_optionals();
11075 $this->error = $this->db->lasterror();
11076 $this->errors[] = $this->error;
11086 $this->error = $this->db->lasterror();
11087 $this->errors[] = $this->error;
11101 $objectlineclassname = get_class($this).
'Line';
11102 if (!class_exists($objectlineclassname)) {
11103 $this->error =
'Error, class '.$objectlineclassname.
' not found during call of fetchLinesCommon';
11107 $objectline =
new $objectlineclassname($this->db);
11108 '@phan-var-force CommonObjectLine $objectline';
11110 $sql =
"SELECT ".$objectline->getFieldList(
'l');
11111 $sql .=
" FROM ".$this->db->prefix().$objectline->table_element.
" as l";
11112 $sql .=
" WHERE l.fk_".$this->db->sanitize($this->element).
" = ".((int) $this->
id);
11114 $sql .= $morewhere;
11116 if (isset($objectline->fields[
'position'])) {
11117 $sql .= $this->db->order(
'position',
'ASC');
11120 $resql = $this->db->query($sql);
11122 $num_rows = $this->db->num_rows($resql);
11124 $this->lines = array();
11125 while ($i < $num_rows) {
11126 $obj = $this->db->fetch_object($resql);
11128 $newline =
new $objectlineclassname($this->db);
11129 '@phan-var-force CommonObjectLine $newline';
11130 $newline->setVarsFromFetchObj($obj);
11133 if (empty($noextrafields)) {
11134 $newline->fetch_optionals();
11137 $this->lines[] = $newline;
11144 $this->error = $this->db->lasterror();
11145 $this->errors[] = $this->error;
11159 dol_syslog(get_class($this).
"::updateCommon update", LOG_DEBUG);
11171 $fieldvalues = $this->setSaveQuery();
11175 if (array_key_exists(
'date_modification', $fieldvalues)) {
11176 $fieldvalues[
'date_modification'] = $this->db->idate($now);
11178 if (
getDolGlobalString(
'MAIN_DISABLE_AUTO_UPDATE_OF_TMS_FIELDS') && array_key_exists(
'tms', $fieldvalues)) {
11179 $fieldvalues[
'tms'] = $this->db->idate($now);
11181 if (array_key_exists(
'fk_user_modif', $fieldvalues)) {
11182 $fieldvalues[
'fk_user_modif'] = $user->id;
11184 if (array_key_exists(
'user_modification_id', $fieldvalues)) {
11185 $fieldvalues[
'user_modification_id'] = $user->id;
11188 if (array_key_exists(
'pass_crypted', $fieldvalues) && property_exists($this,
'pass') && !empty($this->pass)) {
11190 $tmparray =
dol_hash($this->pass,
'0', 0, 1);
11191 $fieldvalues[
'pass_crypted'] = $tmparray[
'pass_encrypted'];
11192 if (array_key_exists(
'pass_encoding', $fieldvalues) && property_exists($this,
'pass_encoding')) {
11193 $fieldvalues[
'pass_encoding'] = $tmparray[
'pass_encoding'];
11196 if (array_key_exists(
'ref', $fieldvalues)) {
11200 unset($fieldvalues[
'rowid']);
11205 $sanitized_tmp = array();
11206 foreach ($fieldvalues as $k => $v) {
11208 $value = $this->fields[$k];
11210 $values[$k] = $this->quote($v, $value);
11211 if (($value[
"type"] ==
"text") && !empty($value[
'arrayofkeyval']) && is_array($value[
'arrayofkeyval'])) {
11213 $v = preg_replace(
'/\s/',
',', $v);
11214 $v = preg_replace(
'/,+/',
',', $v);
11217 $sanitized_tmp[] = $k.
'='.$this->quote($v, $this->fields[$k]);
11221 foreach ($keys as $key) {
11222 if (preg_match(
'/^integer:/i', $this->fields[$key][
'type']) && $values[$key] ==
'-1') {
11223 $values[$key] =
'';
11225 if (!empty($this->fields[$key][
'foreignkey']) && $values[$key] ==
'-1') {
11226 $values[$key] =
'';
11238 $sql =
'UPDATE '.$this->db->prefix().$this->table_element.
' SET '.implode(
', ', $sanitized_tmp).
' WHERE rowid='.((int) $this->
id);
11240 $this->db->begin();
11243 $res = $this->db->query($sql);
11246 $this->errors[] = $this->db->lasterror();
11252 $result = $this->insertExtraFields();
11259 if (!$error && !$notrigger) {
11261 $result = $this->call_trigger(strtoupper(get_class($this)).
'_MODIFY', $user);
11270 $this->db->rollback();
11273 $this->db->commit();
11288 dol_syslog(get_class($this).
"::deleteCommon delete", LOG_DEBUG);
11292 $this->db->begin();
11294 if ($forcechilddeletion) {
11295 foreach ($this->childtables as $table) {
11296 $sql =
"DELETE FROM ".$this->db->prefix().$this->db->sanitize($table).
" WHERE ".$this->db->sanitize($this->fk_element).
" = ".((int) $this->
id);
11297 $resql = $this->db->query($sql);
11299 $this->error = $this->db->lasterror();
11300 $this->errors[] = $this->error;
11301 $this->db->rollback();
11305 } elseif (!empty($this->childtables)) {
11306 $objectisused = $this->isObjectUsed($this->
id);
11307 if (!empty($objectisused)) {
11308 dol_syslog(get_class($this).
"::deleteCommon Can't delete record as it has some child", LOG_WARNING);
11309 $this->error =
'ErrorRecordHasChildren';
11310 $this->errors[] = $this->error;
11311 $this->db->rollback();
11317 if (is_array($this->childtablesoncascade) && !empty($this->childtablesoncascade)) {
11318 foreach ($this->childtablesoncascade as $tabletodelete) {
11319 $deleteFromObject = explode(
':', $tabletodelete, 4);
11320 if (count($deleteFromObject) >= 2) {
11321 $className = str_replace(
'@',
'', $deleteFromObject[0]);
11322 $filePath = $deleteFromObject[1];
11323 $columnName = $deleteFromObject[2];
11325 if (!empty($deleteFromObject[3])) {
11326 $filter = $deleteFromObject[3];
11330 $childObject =
new $className($this->db);
11331 if (method_exists($childObject,
'deleteByParentField')) {
11332 '@phan-var-force CommonObject $childObject';
11333 $result = $childObject->deleteByParentField($this->
id, $columnName, $filter);
11336 $this->errors[] = $childObject->error;
11341 $this->errors[] =
"You defined a cascade delete on an object $className/$this->id but there is no method deleteByParentField for it";
11346 $this->errors[] =
'Cannot include child class file '.$filePath;
11351 $sql =
"DELETE FROM ".$this->db->prefix().$this->db->sanitize($tabletodelete).
" WHERE ".$this->db->sanitize($this->fk_element).
" = ".((int) $this->
id);
11353 $resql = $this->db->query($sql);
11356 $this->error = $this->db->lasterror();
11357 $this->errors[] = $this->error;
11367 $result = $this->call_trigger(strtoupper(get_class($this)).
'_DELETE', $user);
11377 $res = $this->deleteEcmFiles(1);
11386 require_once DOL_DOCUMENT_ROOT .
'/core/lib/files.lib.php';
11389 $this->errors[] =
'ErrorFailToDeleteDir';
11395 $res = $this->deleteObjectLinked();
11400 if (!$error && !empty($this->isextrafieldmanaged)) {
11401 $result = $this->deleteExtraFields();
11408 $sql =
'DELETE FROM '.$this->db->prefix().$this->table_element.
' WHERE rowid='.((int) $this->
id);
11410 $resql = $this->db->query($sql);
11413 $this->errors[] = $this->db->lasterror();
11419 $this->db->rollback();
11422 $this->db->commit();
11447 if (!empty($parentId) && !empty($parentField)) {
11448 if (empty($this->table_element)) {
11449 $this->error =
'Property table_element for object is not defined';
11450 $this->errors[] = $this->error;
11454 if (!method_exists($this,
'fetch')) {
11455 $this->error =
'Method fetch for object is not defined';
11456 $this->errors[] = $this->error;
11460 if (!method_exists($this,
'delete')) {
11461 $this->error =
'Method delete for object is not defined';
11462 $this->errors[] = $this->error;
11467 $this->db->begin();
11469 $sql =
"SELECT rowid FROM ".$this->db->prefix().$this->table_element;
11470 $sql .=
" WHERE ".$this->db->sanitize($parentField).
" = ".(int) $parentId;
11473 $errormessage =
'';
11475 if ($errormessage) {
11476 $this->errors[] = $errormessage;
11477 dol_syslog(__METHOD__.
' '.implode(
',', $this->errors), LOG_ERR);
11481 $resql = $this->db->query($sql);
11483 $this->errors[] = $this->db->lasterror();
11486 while ($obj = $this->db->fetch_object($resql)) {
11487 $result = $this->fetch($obj->rowid);
11490 $this->errors[] = $this->error;
11492 $result = $this->
delete($user);
11495 $this->errors[] = $this->error;
11503 if (empty($error)) {
11504 $this->db->commit();
11507 $this->error = implode(
', ', $this->errors);
11508 $this->db->rollback();
11509 return $error * -1;
11528 $tmpforobjectclass = get_class($this);
11529 $tmpforobjectlineclass = ucfirst($tmpforobjectclass).
'Line';
11531 $this->db->begin();
11534 $result = $this->call_trigger(
'LINE'.strtoupper($tmpforobjectclass).
'_DELETE', $user);
11540 if (empty($error)) {
11541 $sql =
"DELETE FROM ".$this->db->prefix().$this->table_element_line;
11542 $sql .=
" WHERE rowid = ".((int) $idline);
11544 $resql = $this->db->query($sql);
11546 $this->error =
"Error ".$this->db->lasterror();
11551 if (empty($error)) {
11553 $tmpobjectline =
new $tmpforobjectlineclass($this->db);
11554 '@phan-var-force CommonObjectLine $tmpobjectline';
11555 if (!isset($tmpobjectline->isextrafieldmanaged) || !empty($tmpobjectline->isextrafieldmanaged)) {
11556 $tmpobjectline->id = $idline;
11557 $result = $tmpobjectline->deleteExtraFields();
11560 $this->error =
"Error ".get_class($this).
"::deleteLineCommon deleteExtraFields error -4 ".$tmpobjectline->error;
11565 if (empty($error)) {
11566 $this->db->commit();
11569 dol_syslog(get_class($this).
"::deleteLineCommon ERROR:".$this->error, LOG_ERR);
11570 $this->db->rollback();
11590 $this->db->begin();
11592 $statusfield =
'status';
11593 if (in_array($this->element, array(
'don',
'donation',
'shipping',
'project_task'))) {
11594 $statusfield =
'fk_statut';
11597 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
11598 $sql .=
" SET ".$this->db->sanitize($statusfield).
" = ".((int) $status);
11599 $sql .=
" WHERE rowid = ".((int) $this->
id);
11601 if ($this->db->query($sql)) {
11603 $this->oldcopy = clone $this;
11606 if (!$error && !$notrigger) {
11608 $result = $this->call_trigger($triggercode, $user);
11615 $this->
status = $status;
11616 if (property_exists($this,
'statut')) {
11617 $this->statut = $status;
11619 $this->db->commit();
11622 $this->db->rollback();
11626 $this->error = $this->db->error();
11627 $this->db->rollback();
11643 $this->specimen = 1;
11645 'label' =>
'This is label',
11646 'ref' =>
'ABCD1234',
11647 'description' =>
'This is a description',
11649 'note_public' =>
'Public note',
11650 'note_private' =>
'Private note',
11651 'date_creation' => (
dol_now() - 3600 * 48),
11652 'date_modification' => (
dol_now() - 3600 * 24),
11653 'fk_user_creat' => $user->id,
11654 'fk_user_modif' => $user->id,
11657 foreach ($fields as $key => $value) {
11658 if (array_key_exists($key, $this->fields)) {
11659 $this->{$key} = $value;
11664 if (property_exists($this,
'fields')) {
11665 foreach ($this->fields as $key => $value) {
11667 if (array_key_exists($key, $fields)) {
11671 if (!empty($value[
'default'])) {
11672 $this->$key = $value[
'default'];
11690 require_once DOL_DOCUMENT_ROOT.
'/core/class/comment.class.php';
11692 $comment =
new Comment($this->db);
11693 $result = $comment->fetchAllFor($this->element, $this->
id);
11695 $this->setErrorsFromObject($comment);
11698 $this->comments = $comment->comments;
11700 return count($this->comments);
11710 return count($this->comments);
11721 if (!is_array($parameters)) {
11724 foreach ($parameters as $parameter) {
11725 if (isset($this->$parameter)) {
11726 $this->$parameter = trim($this->$parameter);
11745 require_once DOL_DOCUMENT_ROOT.
'/categories/class/categorie.class.php';
11749 $existing =
$c->containing($this->
id, $type_categ,
'id');
11769 if (!is_array($categories)) {
11770 $categories = array($categories);
11773 dol_syslog(get_class($this).
"::setCategoriesCommon Object Id:".$this->
id.
' type_categ:'.$type_categ.
' nb tag add:'.count($categories), LOG_DEBUG);
11775 require_once DOL_DOCUMENT_ROOT.
'/categories/class/categorie.class.php';
11777 if (empty($type_categ)) {
11778 dol_syslog(__METHOD__.
': Type '.$type_categ.
'is an unknown category type. Done nothing.', LOG_ERR);
11784 $existing =
$c->containing($this->
id, $type_categ,
'id');
11787 if (!is_array($existing)) {
11788 $existing = array();
11790 if ($remove_existing) {
11792 $to_del = array_diff($existing, $categories);
11793 $to_add = array_diff($categories, $existing);
11796 $to_add = array_diff($categories, $existing);
11803 foreach ($to_del as $del) {
11804 if (
$c->fetch($del) > 0) {
11805 $result =
$c->del_type($this, $type_categ);
11808 $this->error =
$c->error;
11809 $this->errors =
$c->errors;
11816 foreach ($to_add as $add) {
11817 if (
$c->fetch($add) > 0) {
11818 $result =
$c->add_type($this, $type_categ);
11821 $this->error =
$c->error;
11822 $this->errors =
$c->errors;
11830 return $error ? (-1 * $error) : $ok;
11843 $this->db->begin();
11845 if (empty($type)) {
11846 $type = $this->table_element;
11849 require_once DOL_DOCUMENT_ROOT.
'/categories/class/categorie.class.php';
11850 $categorystatic =
new Categorie($this->db);
11852 $tablename = $this->db->prefix().
"categorie_".(empty($categorystatic->MAP_CAT_TABLE[$type]) ? $type : $categorystatic->MAP_CAT_TABLE[$type]);
11853 $fkname =
'fk_' . (empty($categorystatic->MAP_CAT_FK[$type]) ? $type : $categorystatic->MAP_CAT_FK[$type]);
11855 $sql =
"INSERT INTO ".$this->db->sanitize($tablename).
" (fk_categorie, ".$this->db->sanitize($fkname).
")";
11856 $sql .=
" SELECT fk_categorie, ".((int) $toId).
" FROM ".$this->db->sanitize($tablename);
11857 $sql .=
" WHERE ".$this->db->sanitize($fkname).
" = ".((int) $fromId);
11859 if (!$this->db->query($sql)) {
11860 $this->error = $this->db->lasterror();
11861 $this->db->rollback();
11865 $this->db->commit();
11879 $this->db->begin();
11883 switch ($this->element) {
11885 $element =
'propale';
11888 $element =
'produit';
11890 case 'order_supplier':
11891 $element =
'fournisseur/commande';
11893 case 'invoice_supplier':
11896 $element =
'fournisseur/facture/'.get_exdir($this->
id, 2, 0, 1, $this,
'invoice_supplier');
11899 $element =
'expedition/sending';
11902 case 'project_task':
11903 require_once DOL_DOCUMENT_ROOT.
'/projet/class/task.class.php';
11905 $project_result = $this->fetchProject();
11906 if ($project_result >= 0) {
11907 $element =
'projet/'.dol_sanitizeFileName($this->project->ref).
'/';
11911 $element =
'contract';
11914 $element = $this->element;
11916 '@phan-var-force string $element';
11919 $sql =
"DELETE FROM ".$this->db->prefix().
"ecm_files_extrafields WHERE fk_object IN (";
11920 $sql .=
" SELECT rowid FROM ".$this->db->prefix().
"ecm_files WHERE filename LIKE '".$this->db->escape($this->
ref).
"%'";
11921 $sql .=
" AND filepath = '".$this->db->escape($element.
"/".$this->ref).
"' AND entity = ".((int)
$conf->entity);
11924 if (!$this->db->query($sql)) {
11925 $this->error = $this->db->lasterror();
11926 $this->db->rollback();
11931 $sql =
"DELETE FROM ".$this->db->prefix().
"ecm_files";
11932 $sql .=
" WHERE filename LIKE '".$this->db->escape($this->
ref).
"%'";
11933 $sql .=
" AND filepath = '".$this->db->escape($element.
"/".$this->ref).
"' AND entity = ".((int)
$conf->entity);
11935 if (!$this->db->query($sql)) {
11936 $this->error = $this->db->lasterror();
11937 $this->db->rollback();
11944 $sql =
'DELETE FROM '.$this->db->prefix().
"ecm_files_extrafields";
11945 $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).
")";
11946 $resql = $this->db->query($sql);
11948 $this->error = $this->db->lasterror();
11949 $this->db->rollback();
11953 $sql =
'DELETE FROM '.$this->db->prefix().
"ecm_files";
11954 $sql .=
" WHERE src_object_type = '".$this->db->escape($this->table_element.(empty($this->module) ?
"" :
"@".$this->module)).
"' AND src_object_id = ".((int) $this->
id);
11955 $resql = $this->db->query($sql);
11957 $this->error = $this->db->lasterror();
11958 $this->db->rollback();
11963 $this->db->commit();
11980 include_once DOL_DOCUMENT_ROOT.
'/product/class/product.class.php';
11983 $tmpproduct =
new Product($this->db);
11984 foreach ($this->lines as $line) {
11985 if ($line->fk_product > 0) {
11986 $tmpproduct->fetch($line->fk_product);
11987 $statustotest = ($status ==
'onsale' ?
'status' :
'status_buy');
11988 if (!$tmpproduct->$statustotest) {
11989 $langs->load(
'products');
11990 $statuskey4lang = ($status ==
'onsale' ?
'ProductStatusNotOnSell' :
'ProductStatusNotOnBuy');
11992 $this->errors[] = $langs->trans(
'ProductRef').
' '.$tmpproduct->ref.
' '.$langs->trans($statuskey4lang);
11998 $this->error =
'ErrorOneLineContainsADisactivatedProduct';
12014 $this->error = $message;
12015 $this->errors[] = $message;
12027 global $dolibarr_main_document_root;
12029 $this->setErrorWithoutLog($message);
12030 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
12031 $file = str_replace($dolibarr_main_document_root,
'', $trace[0][
'file'] ??
'file unknown');
12032 $line = $trace[0][
'line'] ??
'line unknown';
12033 $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.
defineBuyPrice($unitPrice=0.0, $discountPercent=0.0, $fk_product=0)
Get buy price to use for margin calculation.
commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams=null)
Common function for all objects extending CommonObject for generating documents.
liste_contact($statusoflink=-1, $source='external', $list=0, $code='', $status=-1, $arrayoftcids=array())
Get array of all contacts for an object.
fetchObjectFrom($table, $field, $key, $element=null)
Load object from specific field.
fetchProject()
Load the project with id $this->fk_project into this->project.
fetch_thirdparty($force_thirdparty_id=0)
Load the third party of object, from id $this->socid or $this->fk_soc, into this->thirdparty.
static deleteAllItemsLinkedByObjectID($fk_object_where, $field_where, $table_element)
Function used to remove all items linked to an object id in association table.
setFieldError($fieldKey, $msg='')
set validation error message a field
validateField($fields, $fieldKey, $fieldValue)
Return validation test result for a field.
getDataToShowPhoto($modulepart, $imagesize)
Function used to get the logos or photos of an object.
setMulticurrencyCode($code)
Change the multicurrency code.
emtpyObjectVars()
Sets all object fields to null.
fetch_projet()
Load the project with id $this->fk_project into this->project.
getIdContact($source, $code, $status=0)
Return id of contacts for a source and a contact code.
setExtraField($key, $value)
Convenience method for setting the value of an extrafield without actually updating it in the databas...
setDocModel($user, $modelpdf)
Set last model used by doc generator.
deleteObjectLinked($sourceid=null, $sourcetype='', $targetid=null, $targettype='', $rowid=0, $f_user=null, $notrigger=0)
Delete all links between an object $this.
getExtraField($key)
Convenience method for retrieving the value of an extrafield without actually fetching it from the da...
updateExtraField($key, $trigger=null, $userused=null)
Update 1 extra field value for the current object.
setPaymentTerms($id, $deposit_percent=null)
Change the payments terms.
isFloat($info)
Function test if type is float.
setBankAccount($fk_account, $notrigger=0, $userused=null)
Change the bank account.
setExtraParameters()
Set extra parameters.
delete_resource($rowid, $element='', $notrigger=0)
Delete a link to resource line.
setErrorsFromObject($object)
setErrorsFromObject
setShippingMethod($shipping_method_id, $notrigger=0, $userused=null)
Change the shipping method.
update_note_public($note)
Update public note (kept for backward compatibility)
getSpecialCode($lineid)
Get special code of a line.
clearObjectLinkedCache()
Clear the cache saying that all linked object were already loaded.
update_ref_ext($ref_ext)
Update external ref of element.
fetchOneLike($ref)
Looks for an object with ref matching the wildcard provided It does only work when $this->table_ref_f...
hasProductsOrServices($predefined=-1)
Function to say how many lines object contains.
static isExistingObject($element, $id, $ref='', $ref_ext='')
Check if an object id or ref exists If you don't need or want to instantiate the object and just need...
isObjectUsed($id=0, $entity=0)
Function to check if an object is used by others (by children).
updateRangOfLine($rowid, $rang)
Update position of line (rang)
getDefaultCreateValueFor($fieldname, $alternatevalue=null, $type='alphanohtml')
Return the default value to use for a field when showing the create form of object.
add_element_resource($resource_id, $resource_type, $busy=0, $mandatory=0, $notrigger=0)
Add resources to the current object : add entry into llx_element_resources Need $this->element & $thi...
checkActiveProductInLines($status='onsale')
Check if all products have the right status (on sale, on buy) called during validation of propal,...
createCommon(User $user, $notrigger=0)
Create object in the database.
getTotalWeightVolume()
Return into unit=0, the calculated total of weight and volume of all lines * qty Calculate by adding ...
update_note($note, $suffix='', $notrigger=0)
Update note of element.
getFullAddress($withcountry=0, $sep="\n", $withregion=0, $extralangcode='')
Return full address of contact.
fetch_project()
Load the project with id $this->fk_project into this->project.
getFieldList($alias='', $excludefields=array())
Function to concat keys of fields.
getNbComments()
Return nb comments already posted.
setVarsFromFetchObj(&$obj)
Function to load data from a SQL pointer into properties of current object $this.
printObjectLines($action, $seller, $buyer, $selected=0, $dateSelector=0, $defaulttpldir='/core/tpl')
Return HTML table for object lines TODO Move this into an output class file (htmlline....
getChildrenOfLine($id, $includealltree=0)
Get children of line.
updateCommon(User $user, $notrigger=0)
Update object into database.
updateExtraLanguages($key, $trigger=null, $userused=null)
Update an extra language value for the current object.
deleteExtraFields()
Delete all extra fields values for the current object.
setStatusCommon($user, $status, $notrigger=0, $triggercode='')
Set to a status.
deprecatedProperties()
Provide list of deprecated properties and replacements.
setSaveQuery()
Function to return the array of data key-value from the ->fields and all the ->properties of an objec...
setValuesForExtraLanguages($onlykey='')
Fill array_options property of object by extrafields value (using for data sent by forms) Used for ex...
insertExtraLanguages($trigger='', $userused=null)
Add/Update all extra languages values for the current object.
setTransportMode($id)
Change the transport mode methods.
isArray($info)
Function test if type is array.
isInt($info)
Function test if type is integer.
fetchObjectLinked($sourceid=null, $sourcetype='', $targetid=null, $targettype='', $clause='OR', $alsosametype=1, $orderby='sourcetype', $loadalsoobjects=1)
Fetch array of objects linked to current object (object of enabled modules only).
delete_contact($rowid, $notrigger=0)
Delete a link to contact line.
updateLineUp($rowid, $rang)
Update position of line up (rang)
fetch_user($userid)
Load the user with id $userid into this->user.
errorsToString()
Method to output saved errors.
getListContactId($source='external')
Return list of id of contacts of object.
setWarehouse($warehouse_id)
Change the warehouse.
setDeliveryAddress($id)
Define delivery address.
fetchBarCode()
Load data for barcode into properties ->barcode_type* Properties ->barcode_type that is id of barcode...
getTotalDiscount()
Function that returns the total amount HT of discounts applied for all lines.
initAsSpecimenCommon()
Initialise object with example values Id must be 0 if object instance is a specimen.
printObjectLine($action, $line, $var, $num, $i, $dateSelector, $seller, $buyer, $selected=0, $extrafields=null, $defaulttpldir='/core/tpl')
Return HTML content of a detail line TODO Move this into an output class file (htmlline....
copy_linked_contact($objFrom, $source='internal')
Copy contact from one element to current.
static commonReplaceThirdparty(DoliDB $dbs, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
Function used to replace a thirdparty id with another one.
getValueFrom($table, $id, $field)
Getter generic.
trimParameters($parameters)
Trim object parameters.
fetch_product()
Load the product with id $this->fk_product into this->product.
isIndex($info)
Function test if is indexed.
quote($value, $fieldsentry)
Add quote to field value if necessary.
formAddObjectLine($dateSelector, $seller, $buyer, $defaulttpldir='/core/tpl')
Show add free and predefined products/services form.
fetchComments()
Load comments linked with current task.
line_down($rowid, $fk_parent_line=true)
Update a line to have a higher rank.
setValueFrom($field, $value, $table='', $id=null, $format='', $id_field='', $fuser=null, $trigkey='', $fk_user_field='fk_user_modif')
Setter generic.
fetch_contact($contactid=null)
Load object contact with id=$this->contact_id into $this->contact.
delThumbs($file)
Delete thumbs.
show_photos($modulepart, $sdir, $size=0, $nbmax=0, $nbbyrow=5, $showfilename=0, $showaction=0, $maxHeight=120, $maxWidth=160, $nolink=0, $overwritetitle=0, $usesharelink=0, $cache='', $addphotorefcss='photoref')
Show photos of an object (nbmax maximum), into several columns.
fetchLinesCommon($morewhere='', $noextrafields=0)
Load object in memory from the database.
static commonReplaceProduct(DoliDB $dbs, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
Function used to replace a product id with another one.
getRangOfLine($rowid)
Get position of line (rang)
showInputField($val, $key, $value, $moreparam='', $keysuffix='', $keyprefix='', $morecss=0, $nonewbutton=0)
Return HTML string to put an input field into a page Code very similar with showInputField of extra f...
update_contact($rowid, $statut, $type_contact_id=0, $fk_socpeople=0)
Update a link to contact line.
getElementType()
Return an element type string formatted like element_element target_type and source_type.
load_previous_next_ref($filter, $fieldid, $nodbprefix=0)
Load properties id_previous and id_next by comparing $fieldid with $this->ref.
setCategoriesCommon($categories, $type_categ='', $remove_existing=true)
Sets object to given categories.
fetchValuesForExtraLanguages()
Function to get alternative languages of a data into $this->array_languages This method is NOT called...
fetchNoCompute($id)
Function to make a fetch but set environment to avoid to load computed values before.
line_max($fk_parent_line=0)
Get max value used for position of line (rang)
getJSListDependancies($type='_extra')
setProject($projectid, $notrigger=0)
Link element with a project.
isForcedToNullIfZero($info)
Function test if field is forced to null if zero or empty.
line_ajaxorder($rows)
Update position of line with ajax (rang)
printOriginLinesList($restrictlist='', $selectedLines=array())
Return HTML table table of source object lines TODO Move this and previous function into output html ...
fetch_origin()
Read linked origin object.
getIdOfLine($rang)
Get rowid of the line relative to its position.
insertExtraFields($trigger='', $userused=null)
Add/Update all extra fields values for the current object.
deleteByParentField($parentId=0, $parentField='', $filter='', $filtermode="AND")
Delete all child object from a parent ID.
static getAllItemsLinkedByObjectID($fk_object_where, $field_select, $field_where, $table_element)
Function used to get an array with all items linked to an object id in association table.
__clone()
Overwrite magic function to solve problem of cloning object that are kept as references.
setPaymentMethods($id)
Change the payments methods.
updateLineDown($rowid, $rang, $max)
Update position of line down (rang)
delete_linked_contact($source='', $code='')
Delete all links between an object $this and all its contacts in llx_element_contact.
fetchCommon($id, $ref=null, $morewhere='', $noextrafields=0)
Load object in memory from the database.
deleteCommon(User $user, $notrigger=0, $forcechilddeletion=0)
Delete object in database.
getFormatedCustomerRef($objref)
Return customer ref for screen output.
getTooltipContentArray($params)
Return array of data to show into a tooltip.
isText($info)
Function test if type is text.
isDate($info)
Function test if type is date.
printOriginLine($line, $var, $restrictlist='', $defaulttpldir='/core/tpl', $selectedLines=array())
Return HTML with a line of table array of source object lines TODO Move this and previous function in...
showOptionals($extrafields, $mode='view', $params=null, $keysuffix='', $keyprefix='', $onetrtd='', $display_type='card')
Function to show lines of extrafields with output data.
getCanvas($id=0, $ref='')
Load type of canvas of an object if it exists.
line_up($rowid, $fk_parent_line=true)
Update a line to have a lower rank.
isDuration($info)
Function test if type is duration.
setErrorWithLog($message, $loglevel=LOG_ERR)
Set the error message for the object and logs it, including the file name and line number.
canBeNull($info)
Function test if field can be null.
listeTypeContacts($source='internal', $option=0, $activeonly=0, $code='', $element='', $excludeelement='')
Return array with list of possible values for type of contacts.
getRights()
Returns the rights used for this class.
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.
forgeSQLFromUniversalSearchCriteria($filter, &$errorstr='', $noand=0, $nopar=0, $noerror=0)
forgeSQLFromUniversalSearchCriteria
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.
dol_htmlentities($string, $flags=ENT_QUOTES|ENT_SUBSTITUTE, $encoding='UTF-8', $double_encode=false)
Replace htmlentities functions.
dolPrintHTMLForAttribute($s, $escapeonlyhtmltags=0, $allowothertags=array())
Return a string ready to be output into an HTML attribute (alt, title, data-html, ....
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.