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->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 (".$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 if (empty($order)) {
1755 $order =
'position';
1757 if ($order ==
'position') {
1763 $sql =
"SELECT DISTINCT tc.rowid, tc.code, tc.libelle as type_label, tc.position";
1764 $sql .=
" FROM ".$this->db->prefix().
"c_type_contact as tc";
1765 $sql .=
" WHERE tc.element = '".$this->db->escape($this->element).
"'";
1766 if ($activeonly == 1) {
1767 $sql .=
" AND tc.active = 1";
1769 if (!empty($source) && $source !=
'all') {
1770 $sql .=
" AND tc.source = '".$this->db->escape($source).
"'";
1772 if (!empty($code)) {
1773 $sql .=
" AND tc.code = '".$this->db->escape($code).
"'";
1775 $sql .= $this->db->order($order,
'ASC');
1778 $resql = $this->db->query($sql);
1780 $this->error = $this->db->lasterror();
1785 $num = $this->db->num_rows($resql);
1788 $obj = $this->db->fetch_object($resql);
1790 $transkey =
"TypeContact_".$this->element.
"_".$source.
"_".$obj->code;
1791 $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $langs->trans($obj->type_label));
1792 if (empty($option)) {
1793 $tab[$obj->rowid] = $libelle_type;
1794 } elseif ($option == 1) {
1795 $tab[$obj->code] = $libelle_type;
1797 $tab[$obj->rowid] = array(
'id' => $obj->rowid,
'code' => $obj->code,
'label' => $libelle_type);
1816 public function listeTypeContacts($source =
'internal', $option = 0, $activeonly = 0, $code =
'', $element =
'', $excludeelement =
'')
1820 $langs->loadLangs(array(
'bills',
'contracts',
'interventions',
'orders',
'projects',
'propal',
'ticket',
'agenda'));
1824 $sql =
"SELECT DISTINCT tc.rowid, tc.code, tc.libelle as type_label, tc.position, tc.element, tc.module";
1825 $sql .=
" FROM ".$this->db->prefix().
"c_type_contact as tc";
1827 $sqlWhere = array();
1828 if (!empty($element)) {
1829 $sqlWhere[] =
" tc.element='".$this->db->escape($element).
"'";
1831 if (!empty($excludeelement)) {
1832 $sqlWhere[] =
" tc.element <> '".$this->db->escape($excludeelement).
"'";
1835 if ($activeonly == 1) {
1836 $sqlWhere[] =
" tc.active=1";
1839 if (!empty($source) && $source !=
'all') {
1840 $sqlWhere[] =
" tc.source='".$this->db->escape($source).
"'";
1843 if (!empty($code)) {
1844 $sqlWhere[] =
" tc.code='".$this->db->escape($code).
"'";
1847 if (count($sqlWhere) > 0) {
1848 $sql .=
" WHERE ".implode(
' AND ', $sqlWhere);
1851 $sql .= $this->db->order(
'tc.element, tc.position',
'ASC');
1854 $resql = $this->db->query($sql);
1856 $num = $this->db->num_rows($resql);
1858 $langs->loadLangs(array(
"propal",
"orders",
"bills",
"suppliers",
"contracts",
"supplier_proposal"));
1860 while ($obj = $this->db->fetch_object($resql)) {
1861 $modulename = $obj->module ?? $obj->element;
1862 if (strpos($obj->element,
'project') !==
false) {
1863 $modulename =
'projet';
1864 } elseif ($obj->element ==
'contrat') {
1865 $element =
'contract';
1866 } elseif ($obj->element ==
'action') {
1867 $modulename =
'agenda';
1868 } elseif (strpos($obj->element,
'supplier') !==
false && $obj->element !=
'supplier_proposal') {
1869 $modulename =
'fournisseur';
1872 $libelle_element = $langs->trans(
'ContactDefault_'.$obj->element);
1873 $tmpelement = $obj->element;
1874 $transkey =
"TypeContact_".$tmpelement.
"_".$source.
"_".$obj->code;
1875 $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->type_label);
1876 $tab[$obj->rowid] = $libelle_element.
' - '.$libelle_type;
1882 $this->error = $this->db->lasterror();
1903 if (!
getDolGlobalInt(
'SHIPPING_USE_ITS_OWN_CONTACTS') && $this->element ==
'shipping' && $this->origin_id != 0) {
1904 $id = $this->origin_id;
1905 $element =
'commande';
1906 } elseif ($this->element ==
'reception' && $this->origin_id != 0) {
1907 $id = $this->origin_id;
1908 $element =
'order_supplier';
1911 $element = $this->element;
1914 $sql =
"SELECT ec.fk_socpeople";
1915 $sql .=
" FROM ".$this->db->prefix().
"element_contact as ec,";
1916 if ($source ==
'internal') {
1917 $sql .=
" ".$this->db->prefix().
"user as c,";
1919 if ($source ==
'external') {
1920 $sql .=
" ".$this->db->prefix().
"socpeople as c,";
1922 $sql .=
" ".$this->db->prefix().
"c_type_contact as tc";
1923 $sql .=
" WHERE ec.element_id = ".((int) $id);
1924 $sql .=
" AND ec.fk_socpeople = c.rowid";
1925 if ($source ==
'internal') {
1926 $sql .=
" AND c.entity IN (".getEntity(
'user').
")";
1928 if ($source ==
'external') {
1929 $sql .=
" AND c.entity IN (".getEntity(
'societe').
")";
1931 $sql .=
" AND ec.fk_c_type_contact = tc.rowid";
1932 $sql .=
" AND tc.element = '".$this->db->escape($element).
"'";
1933 $sql .=
" AND tc.source = '".$this->db->escape($source).
"'";
1935 $sql .=
" AND tc.code = '".$this->db->escape($code).
"'";
1937 $sql .=
" AND tc.active = 1";
1939 $sql .=
" AND ec.statut = ".((int) $status);
1942 dol_syslog(get_class($this).
"::getIdContact", LOG_DEBUG);
1943 $resql = $this->db->query($sql);
1945 while ($obj = $this->db->fetch_object($resql)) {
1946 $result[$i] = $obj->fk_socpeople;
1950 $this->error = $this->db->error();
1967 if (empty($contactid)) {
1968 $contactid = $this->contact_id;
1971 if (empty($contactid)) {
1975 require_once DOL_DOCUMENT_ROOT.
'/contact/class/contact.class.php';
1976 $contact =
new Contact($this->db);
1977 $result = $contact->fetch($contactid);
1978 $this->contact = $contact;
1993 if (empty($this->socid) && empty($this->fk_soc) && empty($force_thirdparty_id)) {
1997 require_once DOL_DOCUMENT_ROOT.
'/societe/class/societe.class.php';
1999 $idtofetch = isset($this->socid) ? $this->socid : (isset($this->fk_soc) ? $this->fk_soc : 0);
2000 if ($force_thirdparty_id) {
2001 $idtofetch = $force_thirdparty_id;
2005 $thirdparty =
new Societe($this->db);
2006 $result = $thirdparty->fetch($idtofetch);
2008 $this->errors = array_merge($this->errors, $thirdparty->errors);
2010 $this->thirdparty = $thirdparty;
2014 $this->thirdparty->price_level = 1;
2033 if (!$this->table_ref_field) {
2037 $sql =
"SELECT rowid FROM ".$this->db->prefix().$this->table_element;
2038 $sql .=
" WHERE ".$this->db->sanitize($this->table_ref_field).
" LIKE '".$this->db->escape($ref).
"'";
2041 $query = $this->db->query($sql);
2043 if (!$this->db->num_rows($query)) {
2047 $result = $this->db->fetch_object($query);
2049 if (method_exists($this,
'fetch')) {
2050 return $this->fetch($result->rowid);
2052 $this->error =
'Fetch method not implemented on '.get_class($this);
2053 dol_syslog(get_class($this).
'::fetchOneLike Error='.$this->error, LOG_ERR);
2054 array_push($this->errors, $this->error);
2083 dol_syslog(get_class($this).
'::fetchBarCode this->element='.$this->element.
' this->barcode_type='.$this->barcode_type);
2085 $idtype = $this->barcode_type;
2086 if (empty($idtype) && $idtype !=
'0') {
2087 if ($this->element ==
'product' &&
getDolGlobalString(
'PRODUIT_DEFAULT_BARCODE_TYPE')) {
2089 } elseif ($this->element ==
'societe') {
2092 dol_syslog(
'Call fetchBarCode with barcode_type not defined and cannot be guessed', LOG_WARNING);
2097 if (empty($this->barcode_type) || empty($this->barcode_type_code) || empty($this->barcode_type_label) || empty($this->barcode_type_coder)) {
2098 $sql =
"SELECT rowid, code, libelle as label, coder";
2099 $sql .=
" FROM ".$this->db->prefix().
"c_barcode_type";
2100 $sql .=
" WHERE rowid = ".((int) $idtype);
2102 $resql = $this->db->query($sql);
2104 $obj = $this->db->fetch_object($resql);
2106 $this->barcode_type = $obj->rowid;
2107 $this->barcode_type_code = $obj->code;
2108 $this->barcode_type_label = $obj->label;
2109 $this->barcode_type_coder = $obj->coder;
2127 include_once DOL_DOCUMENT_ROOT.
'/projet/class/project.class.php';
2129 if (empty($this->fk_project) && !empty($this->fk_projet)) {
2130 $this->fk_project = $this->fk_projet;
2132 if (empty($this->fk_project)) {
2136 $project =
new Project($this->db);
2137 $result = $project->fetch($this->fk_project);
2139 $this->project = $project;
2181 include_once DOL_DOCUMENT_ROOT.
'/product/class/product.class.php';
2184 if (empty($this->fk_product)) {
2188 $product =
new Product($this->db);
2190 $result = $product->fetch($this->fk_product);
2192 $this->product = $product;
2206 $user =
new User($this->db);
2207 $result = $user->fetch($userid);
2208 $this->
user = $user;
2222 $tmpclassname = $this->origin ? $this->origin : $this->origin_type;
2225 if ($tmpclassname ==
'shipping') {
2226 $tmpclassname =
'Expedition';
2228 if ($tmpclassname ==
'delivery') {
2229 $tmpclassname =
'Livraison';
2231 if ($tmpclassname ==
'order_supplier' || $tmpclassname ==
'supplier_order') {
2232 $tmpclassname =
'CommandeFournisseur';
2235 $classname = ucfirst($tmpclassname);
2237 $this->origin_object =
new $classname($this->db);
2239 $this->origin_object->fetch($this->origin_id);
2257 $sql =
"SELECT rowid FROM ".$this->db->prefix().$table;
2258 $sql .=
" WHERE ".$this->db->sanitize($field).
" = '".$this->db->escape($key).
"'";
2259 if (!empty($element)) {
2260 $sql .=
" AND entity IN (".getEntity($element).
")";
2262 $sql .=
" AND entity = ".((int)
$conf->entity);
2265 dol_syslog(get_class($this).
'::fetchObjectFrom', LOG_DEBUG);
2266 $resql = $this->db->query($sql);
2268 $obj = $this->db->fetch_object($resql);
2271 if (method_exists($this,
'fetch')) {
2272 $result = $this->fetch($obj->rowid);
2274 $this->error =
'fetch() method not implemented on '.get_class($this);
2275 dol_syslog(get_class($this).
'::fetchOneLike Error='.$this->error, LOG_ERR);
2276 array_push($this->errors, $this->error);
2296 if (!empty($id) && !empty($field) && !empty($table)) {
2297 if (!preg_match(
'/^[a-zA-Z_][a-zA-Z0-9_]*$/', $table)) {
2298 dol_syslog(get_class($this).
'::getValueFrom Bad table name: '.$table, LOG_WARNING);
2301 if (!preg_match(
'/^[a-zA-Z_][a-zA-Z0-9_.]*$/', $field)) {
2302 dol_syslog(get_class($this).
'::getValueFrom Bad field name: '.$field, LOG_WARNING);
2306 $sql =
"SELECT ".$this->db->sanitize($field).
" FROM ".$this->db->prefix().$this->db->sanitize($table);
2307 $sql .=
" WHERE rowid = ".((int) $id);
2309 dol_syslog(get_class($this).
'::getValueFrom', LOG_DEBUG);
2310 $resql = $this->db->query($sql);
2312 $row = $this->db->fetch_row($resql);
2335 public function setValueFrom($field, $value, $table =
'', $id =
null, $format =
'', $id_field =
'', $fuser =
null, $trigkey =
'', $fk_user_field =
'fk_user_modif')
2339 if (empty($table)) {
2340 $table = $this->table_element;
2345 if (empty($format)) {
2348 if (empty($id_field)) {
2349 $id_field =
'rowid';
2352 $propfield = $field;
2355 if ($table ==
'product') {
2356 if ($field ==
'note_private') {
2358 $propfield =
'note_private';
2359 } elseif ($field ==
'status') {
2361 $propfield =
'status';
2362 } elseif ($field ==
'status_buy') {
2364 $propfield =
'status_buy';
2365 } elseif ($field ==
'status_batch') {
2367 $propfield =
'status_batch';
2371 if (in_array($table, array(
'actioncomm',
'adherent',
'advtargetemailing',
'cronjob',
'establishment'))) {
2372 $fk_user_field =
'fk_user_mod';
2374 if (in_array($table, array(
'prelevement_bons'))) {
2375 $fk_user_field =
'';
2378 if (!preg_match(
'/^[a-zA-Z_][a-zA-Z0-9_]*$/', $table)) {
2379 dol_syslog(get_class($this).
'::getValueFrom Bad table name: '.$table, LOG_WARNING);
2382 if (!preg_match(
'/^[a-zA-Z_][a-zA-Z0-9_.]*$/', $field)) {
2383 dol_syslog(get_class($this).
'::getValueFrom Bad field name: '.$field, LOG_WARNING);
2389 $sql =
"SELECT " . $this->db->sanitize($field);
2390 $sql .=
" FROM " . MAIN_DB_PREFIX . $this->db->sanitize($table);
2391 $sql .=
" WHERE " . $this->db->sanitize($id_field) .
" = " . ((int) $id);
2393 $resql = $this->db->query($sql);
2395 if ($obj = $this->db->fetch_object($resql)) {
2396 if ($format ==
'date') {
2397 $oldvalue = $this->db->jdate($obj->$field);
2399 $oldvalue = $obj->$field;
2403 $this->error = $this->db->lasterror();
2414 $sql =
"UPDATE ".$this->db->prefix().$table.
" SET ";
2416 if ($format ==
'text') {
2417 $sql .= $this->db->sanitize($field).
" = '".$this->db->escape($value).
"'";
2418 } elseif ($format ==
'int') {
2419 $sql .= $this->db->sanitize($field).
" = ".((int) $value);
2420 } elseif ($format ==
'date') {
2421 $sql .= $this->db->sanitize($field).
" = ".($value ?
"'".$this->db->idate($value).
"'" :
"null");
2422 } elseif ($format ==
'dategmt') {
2423 $sql .= $this->db->sanitize($field).
" = ".($value ?
"'".$this->db->idate($value,
'gmt').
"'" :
"null");
2426 if ($fk_user_field) {
2427 if (!empty($fuser) && is_object($fuser)) {
2428 $sql .=
", ".$this->db->sanitize($fk_user_field).
" = ".((int) $fuser->id);
2429 } elseif (empty($fuser) || $fuser !=
'none') {
2430 $sql .=
", ".$this->db->sanitize($fk_user_field).
" = ".((int) $user->id);
2434 $sql .=
" WHERE ".$this->db->sanitize($id_field).
" = ".((int) $id);
2436 $resql = $this->db->query($sql);
2440 if (method_exists($this,
'fetch')) {
2441 $result = $this->fetch(
$id);
2446 $this->oldcopy = clone $this;
2447 if (property_exists($this->oldcopy, $field)) {
2448 $this->oldcopy->$field = $oldvalue;
2450 if ($propfield != $field && property_exists($this->oldcopy, $propfield)) {
2451 $this->oldcopy->$propfield = $oldvalue;
2454 if (empty($this->context[
'actionmsgmore'])) {
2455 $this->context[
'actionmsgmore'] =
'Trigger called by setValueFrom';
2459 $result = $this->call_trigger($trigkey, (!empty($fuser) && is_object($fuser)) ? $fuser : $user);
2465 if (property_exists($this, $field)) {
2466 $this->$field = $value;
2468 if ($propfield != $field && property_exists($this, $propfield)) {
2469 $this->$propfield = $value;
2474 $this->db->commit();
2477 if (property_exists($this, $field)) {
2478 $this->$field = $oldvalue;
2480 if ($propfield != $field && property_exists($this, $propfield)) {
2481 $this->$propfield = $oldvalue;
2483 $this->db->rollback();
2487 if ($this->db->lasterrno() ==
'DB_ERROR_RECORD_ALREADY_EXISTS') {
2488 $this->error =
'DB_ERROR_RECORD_ALREADY_EXISTS';
2490 $this->error = $this->db->lasterror();
2492 $this->db->rollback();
2511 global
$conf, $user;
2513 if (!$this->table_element) {
2514 dol_print_error(
null, get_class($this).
"::load_previous_next_ref was called on object with property table_element not defined");
2517 if ($fieldid ==
'none') {
2522 if (in_array($this->table_element, array(
'facture_rec',
'facture_fourn_rec')) && $fieldid ==
'title') {
2528 if ($user->socid > 0) {
2529 $socid = $user->socid;
2534 $aliastablesociete =
's';
2535 if ($this->element ==
'societe') {
2536 $aliastablesociete =
'te';
2538 $restrictiononfksoc = empty($this->restrictiononfksoc) ? 0 : $this->restrictiononfksoc;
2539 $sql =
"SELECT MAX(te.".$this->db->sanitize($fieldid).
")";
2540 $sql .=
" FROM ".(empty($nodbprefix) ? $this->db->prefix() :
'').$this->table_element.
" as te";
2541 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2542 $tmparray = explode(
'@', $this->ismultientitymanaged);
2543 $sql .=
", ".$this->db->prefix().$this->db->sanitize($tmparray[1]).
" as ".($tmparray[1] ==
'societe' ?
's' :
'parenttable');
2544 } elseif ($restrictiononfksoc == 1 && $this->element !=
'societe' && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2545 $sql .=
", ".$this->db->prefix().
"societe as s";
2546 } elseif ($restrictiononfksoc == 2 && $this->element !=
'societe' && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2547 $sql .=
" LEFT JOIN ".$this->db->prefix().
"societe as s ON te.fk_soc = s.rowid";
2549 if ($restrictiononfksoc && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2550 $sql .=
" LEFT JOIN ".$this->db->prefix().
"societe_commerciaux as sc ON ".$aliastablesociete.
".rowid = sc.fk_soc";
2552 if ($fieldid ==
'rowid') {
2553 $sql .=
" WHERE te.".$this->db->sanitize($fieldid).
" < ".((int) $this->
id);
2554 } elseif ($fieldid ==
'label') {
2555 $sql .=
" WHERE te.".$this->db->sanitize($fieldid).
" < '".$this->db->escape((
string) $this->label).
"'";
2557 $sql .=
" WHERE te.".$this->db->sanitize($fieldid).
" < '".$this->db->escape((
string) $this->
ref).
"'";
2559 if ($restrictiononfksoc == 1 && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2560 $sql .=
" AND sc.fk_user = ".((int) $user->id);
2562 if ($restrictiononfksoc == 2 && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2563 $sql .=
" AND (sc.fk_user = ".((int) $user->id).
' OR te.fk_soc IS NULL)';
2566 $filtermax = $filter;
2570 $tmpsql = forgeSQLFromUniversalSearchCriteria($filtermax, $errormessage);
2571 if ($errormessage) {
2572 if (!preg_match(
'/^\s*AND/i', $filtermax)) {
2580 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2581 $tmparray = explode(
'@', $this->ismultientitymanaged);
2582 $sql .=
" AND te.".$this->db->sanitize($tmparray[0]).
" = ".($tmparray[1] ==
"societe" ?
"s" :
"parenttable").
".rowid";
2583 } elseif ($restrictiononfksoc == 1 && $this->element !=
'societe' && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2584 $sql .=
' AND te.fk_soc = s.rowid';
2586 if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
2587 if ($this->element ==
'user' &&
getDolGlobalInt(
'MULTICOMPANY_TRANSVERSE_MODE')) {
2588 if (!empty($user->admin) && empty($user->entity) &&
$conf->entity == 1) {
2589 $sql .=
" AND te.entity IS NOT NULL";
2591 $sql .=
" AND te.rowid IN (SELECT ug.fk_user FROM ".$this->db->prefix().
"usergroup_user as ug WHERE ug.entity IN (".
getEntity(
'usergroup').
"))";
2594 $sql .=
' AND te.entity IN ('.getEntity($this->element).
')';
2597 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged) && $this->element !=
'societe') {
2598 $tmparray = explode(
'@', $this->ismultientitymanaged);
2599 $sql .=
' AND parenttable.entity IN ('.getEntity($tmparray[1]).
')';
2601 if ($restrictiononfksoc == 1 && $socid && $this->element !=
'societe') {
2602 $sql .=
' AND te.fk_soc = '.((int) $socid);
2604 if ($restrictiononfksoc == 2 && $socid && $this->element !=
'societe') {
2605 $sql .=
' AND (te.fk_soc = '.((int) $socid).
' OR te.fk_soc IS NULL)';
2607 if ($restrictiononfksoc && $socid && $this->element ==
'societe') {
2608 $sql .=
' AND te.rowid = '.((int) $socid);
2612 $result = $this->db->query($sql);
2614 $this->error = $this->db->lasterror();
2617 $row = $this->db->fetch_row($result);
2618 $this->ref_previous = $row[0];
2620 $sql =
"SELECT MIN(te.".$this->db->sanitize($fieldid).
")";
2621 $sql .=
" FROM ".(empty($nodbprefix) ? $this->db->prefix() :
'').$this->table_element.
" as te";
2622 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2623 $tmparray = explode(
'@', $this->ismultientitymanaged);
2624 $sql .=
", ".$this->db->prefix().$tmparray[1].
" as ".($tmparray[1] ==
'societe' ?
's' :
'parenttable');
2625 } elseif ($restrictiononfksoc == 1 && $this->element !=
'societe' && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2626 $sql .=
", ".$this->db->prefix().
"societe as s";
2627 } elseif ($restrictiononfksoc == 2 && $this->element !=
'societe' && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2628 $sql .=
" LEFT JOIN ".$this->db->prefix().
"societe as s ON te.fk_soc = s.rowid";
2630 if ($restrictiononfksoc && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2631 $sql .=
" LEFT JOIN ".$this->db->prefix().
"societe_commerciaux as sc ON ".$aliastablesociete.
".rowid = sc.fk_soc";
2633 if ($fieldid ==
'rowid') {
2634 $sql .=
" WHERE te.".$this->db->sanitize($fieldid).
" > ".((int) $this->
id);
2635 } elseif ($fieldid ==
'label') {
2636 $sql .=
" WHERE te.".$this->db->sanitize($fieldid).
" > '".$this->db->escape((
string) $this->label).
"'";
2638 $sql .=
" WHERE te.".$this->db->sanitize($fieldid).
" > '".$this->db->escape((
string) $this->
ref).
"'";
2640 if ($restrictiononfksoc == 1 && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2641 $sql .=
" AND (sc.fk_user = ".((int) $user->id);
2643 $userschilds = $user->getAllChildIds();
2644 $sql .=
" OR sc.fk_user IN (".$this->db->sanitize(implode(
',', $userschilds)).
")";
2648 if ($restrictiononfksoc == 2 && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2649 $sql .=
" AND (sc.fk_user = ".((int) $user->id).
' OR te.fk_soc IS NULL)';
2652 $filtermin = $filter;
2656 $tmpsql = forgeSQLFromUniversalSearchCriteria($filtermin, $errormessage);
2657 if ($errormessage) {
2658 if (!preg_match(
'/^\s*AND/i', $filtermin)) {
2668 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2669 $tmparray = explode(
'@', $this->ismultientitymanaged);
2670 $sql .=
" AND te.".$this->db->sanitize($tmparray[0]).
" = ".($tmparray[1] ==
"societe" ?
"s" :
"parenttable").
".rowid";
2671 } elseif ($restrictiononfksoc == 1 && $this->element !=
'societe' && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2672 $sql .=
' AND te.fk_soc = s.rowid';
2674 if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
2675 if ($this->element ==
'user' &&
getDolGlobalInt(
'MULTICOMPANY_TRANSVERSE_MODE')) {
2676 if (!empty($user->admin) && empty($user->entity) &&
$conf->entity == 1) {
2677 $sql .=
" AND te.entity IS NOT NULL";
2679 $sql .=
" AND te.rowid IN (SELECT ug.fk_user FROM ".$this->db->prefix().
"usergroup_user as ug WHERE ug.entity IN (".
getEntity(
'usergroup').
"))";
2682 $sql .=
' AND te.entity IN ('.getEntity($this->element).
')';
2685 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged) && $this->element !=
'societe') {
2686 $tmparray = explode(
'@', $this->ismultientitymanaged);
2687 $sql .=
' AND parenttable.entity IN ('.getEntity($tmparray[1]).
')';
2689 if ($restrictiononfksoc == 1 && $socid && $this->element !=
'societe') {
2690 $sql .=
' AND te.fk_soc = '.((int) $socid);
2692 if ($restrictiononfksoc == 2 && $socid && $this->element !=
'societe') {
2693 $sql .=
' AND (te.fk_soc = '.((int) $socid).
' OR te.fk_soc IS NULL)';
2695 if ($restrictiononfksoc && $socid && $this->element ==
'societe') {
2696 $sql .=
' AND te.rowid = '.((int) $socid);
2701 $result = $this->db->query($sql);
2703 $this->error = $this->db->lasterror();
2706 $row = $this->db->fetch_row($result);
2707 $this->ref_next = $row[0];
2722 $contactAlreadySelected = array();
2727 if ($source ==
'thirdparty') {
2728 $contactAlreadySelected[$i] = $tab[$i][
'socid'];
2730 $contactAlreadySelected[$i] = $tab[$i][
'id'];
2734 return $contactAlreadySelected;
2750 if (!$this->table_element) {
2751 dol_syslog(get_class($this).
"::setProject was called on object with property table_element not defined", LOG_ERR);
2755 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
2756 if ($this->table_element ==
'actioncomm') {
2758 $sql .=
" SET fk_project = ".((int) $projectid);
2760 $sql .=
" SET fk_project = NULL";
2762 $sql .=
' WHERE id = '.((int) $this->
id);
2764 } elseif (!empty($this->fields[
'fk_project'])) {
2766 $sql .=
" SET fk_project = ".((int) $projectid);
2768 $sql .=
" SET fk_project = NULL";
2770 $sql .=
' WHERE rowid = '.((int) $this->
id);
2773 $sql .=
' SET fk_projet = '.((int) $projectid);
2775 $sql .=
' SET fk_projet = NULL';
2777 $sql .=
" WHERE rowid = ".((int) $this->
id);
2782 dol_syslog(get_class($this).
"::setProject", LOG_DEBUG);
2783 if ($this->db->query($sql)) {
2784 $this->fk_project = ((int) $projectid);
2791 if (!$error && !$notrigger) {
2793 $result = $this->call_trigger(strtoupper($this->element) .
'_MODIFY', $user);
2802 $this->db->rollback();
2805 $this->db->commit();
2823 dol_syslog(get_class($this).
'::setPaymentMethods('.$id.
')');
2825 if ($this->
status >= 0 || $this->element ==
'societe') {
2829 $fieldname =
'fk_mode_reglement';
2830 $triggerName = (empty($this->TRIGGER_PREFIX) ? strtoupper(get_class($this)) : $this->TRIGGER_PREFIX);
2831 if ($this->element ==
'societe') {
2832 $fieldname =
'mode_reglement';
2833 $triggerName =
'COMPANY';
2835 if (get_class($this) ==
'Facture') {
2836 $triggerName =
'BILL';
2838 if (get_class($this) ==
'Fournisseur') {
2839 $fieldname =
'mode_reglement_supplier';
2840 $triggerName =
'BILL_SUPPLIER';
2842 if (get_class($this) ==
'Tva') {
2843 $fieldname =
'fk_typepayment';
2844 $triggerName =
'VAT';
2846 if (get_class($this) ==
'Salary') {
2847 $fieldname =
'fk_typepayment';
2850 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
2851 $sql .=
" SET ".$this->db->sanitize($fieldname).
" = ".(($id > 0 || $id ==
'0') ? ((
int) $id) :
'NULL');
2852 $sql .=
' WHERE rowid = '.((int) $this->
id);
2854 if ($this->db->query($sql)) {
2855 $this->mode_reglement_id = $id;
2857 if (get_class($this) ==
'Fournisseur') {
2858 $this->mode_reglement_supplier_id = $id;
2862 if (!$error && !$notrigger) {
2864 $result = $this->call_trigger($triggerName.
'_MODIFY', $user);
2872 dol_syslog(get_class($this).
'::setPaymentMethods Error '.$this->db->error());
2873 $this->error = $this->db->error();
2877 dol_syslog(get_class($this).
'::setPaymentMethods, status of the object is incompatible');
2878 $this->error =
'Status of the object is incompatible '.$this->status;
2891 dol_syslog(get_class($this).
'::setMulticurrencyCode('.$code.
')');
2892 if ($this->
status >= 0 || $this->element ==
'societe') {
2893 $sql =
'UPDATE '.$this->db->prefix().$this->table_element;
2894 $sql .=
" SET multicurrency_code = '".$this->db->escape($code).
"'";
2895 $sql .=
' WHERE rowid='.((int) $this->
id);
2897 if ($this->db->query($sql)) {
2898 $this->multicurrency_code = $code;
2902 $this->setMulticurrencyRate($rate, 2);
2907 dol_syslog(get_class($this).
'::setMulticurrencyCode Error '.$sql.
' - '.$this->db->error());
2908 $this->error = $this->db->error();
2912 dol_syslog(get_class($this).
'::setMulticurrencyCode, status of the object is incompatible');
2913 $this->error =
'Status of the object is incompatible '.$this->status;
2925 public function setMulticurrencyRate($rate, $mode = 1)
2927 dol_syslog(get_class($this).
'::setMulticurrencyRate('.$rate.
', '.$mode.
')');
2928 if ($this->
status >= 0 || $this->element ==
'societe') {
2929 $sql =
'UPDATE '.$this->db->prefix().$this->table_element;
2930 $sql .=
" SET multicurrency_tx = ".((float) $rate);
2931 $sql .=
' WHERE rowid='.((int) $this->
id);
2933 if ($this->db->query($sql)) {
2934 $this->multicurrency_tx = $rate;
2937 if (!empty($this->lines)) {
2938 foreach ($this->lines as &$line) {
2941 $line->subprice = 0;
2946 $line->multicurrency_subprice = 0;
2949 switch ($this->element) {
2953 '@phan-var-force Propal $this';
2954 '@phan-var-force PropaleLigne $line';
2959 $line->remise_percent,
2961 $line->localtax1_tx,
2962 $line->localtax2_tx,
2963 ($line->description ? $line->description : $line->desc),
2966 $line->special_code,
2967 $line->fk_parent_line,
2968 $line->skip_update_total,
2969 $line->fk_fournprice,
2972 $line->product_type,
2975 $line->array_options,
2977 $line->multicurrency_subprice
2983 '@phan-var-force Commande $this';
2984 '@phan-var-force OrderLine $line';
2987 ($line->description ? $line->description : $line->desc),
2990 $line->remise_percent,
2992 $line->localtax1_tx,
2993 $line->localtax2_tx,
2998 $line->product_type,
2999 $line->fk_parent_line,
3000 $line->skip_update_total,
3001 $line->fk_fournprice,
3004 $line->special_code,
3005 $line->array_options,
3007 $line->multicurrency_subprice
3013 '@phan-var-force Facture $this';
3014 '@phan-var-force FactureLigne $line';
3017 ($line->description ? $line->description : $line->desc),
3020 $line->remise_percent,
3024 $line->localtax1_tx,
3025 $line->localtax2_tx,
3028 $line->product_type,
3029 $line->fk_parent_line,
3030 $line->skip_update_total,
3031 $line->fk_fournprice,
3034 $line->special_code,
3035 $line->array_options,
3036 $line->situation_percent,
3038 $line->multicurrency_subprice
3044 '@phan-var-force FactureRec $this';
3045 '@phan-var-force FactureLigneRec $line';
3048 ($line->description ? $line->description : $line->desc),
3052 $line->localtax1_tx,
3053 $line->localtax2_tx,
3055 $line->remise_percent,
3060 $line->product_type,
3062 $line->special_code,
3065 $line->multicurrency_subprice,
3069 $line->fk_fournprice,
3071 $line->fk_parent_line
3074 case 'supplier_proposal':
3077 '@phan-var-force SupplierProposal $this';
3078 '@phan-var-force SupplierProposalLine $line';
3083 $line->remise_percent,
3085 $line->localtax1_tx,
3086 $line->localtax2_tx,
3087 ($line->description ? $line->description : $line->desc),
3090 $line->special_code,
3091 $line->fk_parent_line,
3092 $line->skip_update_total,
3093 $line->fk_fournprice,
3096 $line->product_type,
3097 $line->array_options,
3099 (int) $line->fk_unit,
3100 $line->multicurrency_subprice
3103 case 'order_supplier':
3106 '@phan-var-force CommandeFournisseur $this';
3107 '@phan-var-force CommandeFournisseurLigne $line';
3110 ($line->description ? $line->description : $line->desc),
3113 $line->remise_percent,
3115 $line->localtax1_tx,
3116 $line->localtax2_tx,
3119 $line->product_type,
3123 $line->array_options,
3125 $line->multicurrency_subprice,
3129 case 'invoice_supplier':
3132 '@phan-var-force FactureFournisseur $this';
3133 '@phan-var-force SupplierInvoiceLIne $line';
3136 ($line->description ? $line->description : $line->desc),
3139 $line->localtax1_tx,
3140 $line->localtax2_tx,
3145 $line->product_type,
3146 $line->remise_percent,
3150 $line->array_options,
3152 $line->multicurrency_subprice,
3157 dol_syslog(get_class($this).
'::setMulticurrencyRate no updateline defined', LOG_DEBUG);
3165 dol_syslog(get_class($this).
'::setMulticurrencyRate Error '.$sql.
' - '.$this->db->error());
3166 $this->error = $this->db->error();
3170 dol_syslog(get_class($this).
'::setMulticurrencyRate, status of the object is incompatible');
3171 $this->error =
'Status of the object is incompatible '.$this->status;
3186 if ($this->
status >= 0 || $this->element ==
'societe') {
3188 $fieldname =
'fk_cond_reglement';
3189 if ($this->element ==
'societe') {
3190 $fieldname =
'cond_reglement';
3192 if (get_class($this) ==
'Fournisseur') {
3193 $fieldname =
'cond_reglement_supplier';
3196 if (empty($deposit_percent) || $deposit_percent < 0) {
3197 $deposit_percent = (float) getDictionaryValue(
'c_payment_term',
'deposit_percent', $id);
3200 if ($deposit_percent > 100) {
3201 $deposit_percent = 100;
3204 $sql =
'UPDATE '.$this->db->prefix().$this->table_element;
3205 $sql .=
" SET ".$this->db->sanitize($fieldname).
" = ".(($id > 0 || $id ==
'0') ? ((
int) $id) :
'NULL');
3206 if (in_array($this->table_element, array(
'propal',
'commande',
'supplier_proposal',
'commande_fournisseur',
'societe'))) {
3207 $sql .=
" , deposit_percent = " . (empty($deposit_percent) ?
'NULL' :
"'".$this->db->escape((
string) $deposit_percent).
"'");
3209 $sql .=
' WHERE rowid = '.((int) $this->
id);
3211 if ($this->db->query($sql)) {
3212 $this->cond_reglement_id = $id;
3214 if (get_class($this) ==
'Fournisseur') {
3215 $this->cond_reglement_supplier_id = $id;
3217 $this->deposit_percent = $deposit_percent;
3220 dol_syslog(get_class($this).
'::setPaymentTerms Error '.$sql.
' - '.$this->db->error());
3221 $this->error = $this->db->error();
3225 dol_syslog(get_class($this).
'::setPaymentTerms, status of the object is incompatible');
3226 $this->error =
'Status of the object is incompatible '.$this->status;
3239 dol_syslog(get_class($this).
'::setTransportMode('.$id.
')');
3240 if ($this->
status >= 0 || $this->element ==
'societe') {
3241 $fieldname =
'fk_transport_mode';
3242 if ($this->element ==
'societe') {
3243 $fieldname =
'transport_mode';
3245 if (get_class($this) ==
'Fournisseur') {
3246 $fieldname =
'transport_mode_supplier';
3249 $sql =
'UPDATE '.$this->db->prefix().$this->table_element;
3250 $sql .=
" SET ".$this->db->sanitize($fieldname).
" = ".(($id > 0 || $id ==
'0') ? ((
int) $id) :
'NULL');
3251 $sql .=
' WHERE rowid='.((int) $this->
id);
3253 if ($this->db->query($sql)) {
3254 $this->transport_mode_id = $id;
3256 if (get_class($this) ==
'Fournisseur') {
3257 $this->transport_mode_supplier_id = $id;
3261 dol_syslog(get_class($this).
'::setTransportMode Error '.$sql.
' - '.$this->db->error());
3262 $this->error = $this->db->error();
3266 dol_syslog(get_class($this).
'::setTransportMode, status of the object is incompatible');
3267 $this->error =
'Status of the object is incompatible '.$this->status;
3281 $fieldname =
'fk_delivery_address';
3282 if ($this->element ==
'delivery' || $this->element ==
'shipping') {
3283 $fieldname =
'fk_address';
3286 $sql =
"UPDATE ".$this->db->prefix().$this->table_element.
" SET ".$this->db->sanitize($fieldname).
" = ".((int) $id);
3287 $sql .=
" WHERE rowid = ".((int) $this->
id).
" AND fk_statut = 0";
3289 if ($this->db->query($sql)) {
3290 $this->fk_delivery_address =
$id;
3293 $this->error = $this->db->error();
3294 dol_syslog(get_class($this).
'::setDeliveryAddress Error '.$this->error);
3312 if (empty($userused)) {
3318 if (!$this->table_element) {
3319 dol_syslog(get_class($this).
"::setShippingMethod was called on object with property table_element not defined", LOG_ERR);
3325 if ($shipping_method_id < 0) {
3326 $shipping_method_id =
'NULL';
3328 dol_syslog(get_class($this).
'::setShippingMethod('.$shipping_method_id.
')');
3330 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
3331 $sql .=
" SET fk_shipping_method = ".((int) $shipping_method_id);
3332 $sql .=
" WHERE rowid=".((int) $this->
id);
3333 $resql = $this->db->query($sql);
3335 dol_syslog(get_class($this).
'::setShippingMethod Error ', LOG_DEBUG);
3336 $this->error = $this->db->lasterror();
3341 $this->context = array(
'shippingmethodupdate' => 1);
3342 $triggerPrefix = (empty($this->TRIGGER_PREFIX) ? strtoupper(get_class($this)) : $this->TRIGGER_PREFIX);
3343 $result = $this->call_trigger($triggerPrefix.
'_MODIFY', $userused);
3351 $this->db->rollback();
3354 $this->shipping_method_id = ($shipping_method_id ==
'NULL') ?
null : $shipping_method_id;
3355 $this->db->commit();
3369 if (!$this->table_element) {
3370 dol_syslog(get_class($this).
"::setWarehouse was called on object with property table_element not defined", LOG_ERR);
3373 if ($warehouse_id < 0) {
3374 $warehouse_id =
'NULL';
3376 dol_syslog(get_class($this).
'::setWarehouse('.$warehouse_id.
')');
3378 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
3379 $sql .=
" SET fk_warehouse = ".((int) $warehouse_id);
3380 $sql .=
" WHERE rowid=".((int) $this->
id);
3382 if ($this->db->query($sql)) {
3383 $this->warehouse_id = ($warehouse_id ==
'NULL') ?
null : $warehouse_id;
3386 dol_syslog(get_class($this).
'::setWarehouse Error ', LOG_DEBUG);
3387 $this->error = $this->db->error();
3402 if (!$this->table_element) {
3403 dol_syslog(get_class($this).
"::setDocModel was called on object with property table_element not defined", LOG_ERR);
3407 $newmodelpdf =
dol_trunc($modelpdf, 255);
3409 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
3410 $sql .=
" SET model_pdf = '".$this->db->escape($newmodelpdf).
"'";
3411 $sql .=
" WHERE rowid = ".((int) $this->
id);
3413 dol_syslog(get_class($this).
"::setDocModel", LOG_DEBUG);
3414 $resql = $this->db->query($sql);
3416 $this->model_pdf = $modelpdf;
3437 if (empty($userused)) {
3443 if (!$this->table_element) {
3444 dol_syslog(get_class($this).
"::setBankAccount was called on object with property table_element not defined", LOG_ERR);
3449 if ($fk_account < 0) {
3450 $fk_account =
'NULL';
3452 dol_syslog(get_class($this).
'::setBankAccount('.$fk_account.
')');
3454 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
3455 $sql .=
" SET fk_account = ".((int) $fk_account);
3456 $sql .=
" WHERE rowid=".((int) $this->
id);
3458 $resql = $this->db->query($sql);
3460 dol_syslog(get_class($this).
'::setBankAccount Error '.$sql.
' - '.$this->db->error());
3461 $this->error = $this->db->lasterror();
3466 $this->context[
'bankaccountupdate'] = 1;
3468 $triggerName = (empty($this->TRIGGER_PREFIX) ? strtoupper(get_class($this)) : $this->TRIGGER_PREFIX);
3469 $result = $this->call_trigger($triggerName .
'_MODIFY', $userused);
3477 $this->db->rollback();
3480 $this->fk_account = ($fk_account ==
'NULL') ?
null : $fk_account;
3481 $this->db->commit();
3499 public function line_order($renum =
false, $rowidorder =
'ASC', $fk_parent_line =
true)
3502 if (!$this->table_element_line) {
3503 dol_syslog(get_class($this).
"::line_order was called on object with property table_element_line not defined", LOG_ERR);
3506 if (!$this->fk_element) {
3507 dol_syslog(get_class($this).
"::line_order was called on object with property fk_element not defined", LOG_ERR);
3511 $fieldposition =
'rang';
3512 if (in_array($this->table_element_line, array(
'bom_bomline',
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3513 $fieldposition =
'position';
3518 $sql =
"SELECT count(rowid) FROM ".$this->db->prefix().$this->db->sanitize($this->table_element_line);
3519 $sql .=
" WHERE ".$this->db->sanitize($this->fk_element).
" = ".((int) $this->
id);
3521 $sql .=
" AND " . $this->db->sanitize($fieldposition) .
" = 0";
3524 $sql .=
" AND " . $this->db->sanitize($fieldposition) .
" <> 0";
3527 dol_syslog(get_class($this).
"::line_order", LOG_DEBUG);
3528 $resql = $this->db->query($sql);
3530 $row = $this->db->fetch_row($resql);
3540 $sql =
"SELECT rowid FROM ".$this->db->prefix().$this->db->sanitize($this->table_element_line);
3541 $sql .=
" WHERE ".$this->db->sanitize($this->fk_element).
" = ".((int) $this->
id);
3542 if ($fk_parent_line) {
3543 $sql .=
' AND fk_parent_line IS NULL';
3545 $sql .=
" ORDER BY " . $this->db->sanitize($fieldposition) .
" ASC, rowid " . $this->db->sanitize($rowidorder);
3547 dol_syslog(get_class($this).
"::line_order search all parent lines", LOG_DEBUG);
3548 $resql = $this->db->query($sql);
3551 $num = $this->db->num_rows($resql);
3554 $row = $this->db->fetch_row($resql);
3556 if ($fk_parent_line) {
3559 if (!empty($children)) {
3560 foreach ($children as $child) {
3561 array_push($rows, $child);
3568 if (!empty($rows)) {
3569 foreach ($rows as $key => $row) {
3589 $fieldposition =
'rang';
3590 if (in_array($this->table_element_line, array(
'bom_bomline',
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3591 $fieldposition =
'position';
3596 $sql =
"SELECT rowid FROM ".$this->db->prefix().$this->db->sanitize($this->table_element_line);
3597 $sql .=
" WHERE ".$this->db->sanitize($this->fk_element).
" = ".((int) $this->
id);
3598 $sql .=
' AND fk_parent_line = '.((int) $id);
3599 $sql .=
" ORDER BY " . $this->db->sanitize($fieldposition) .
" ASC";
3601 dol_syslog(get_class($this).
"::getChildrenOfLine search children lines for line ".$id, LOG_DEBUG);
3603 $resql = $this->db->query($sql);
3604 if (!$resql || $this->db->num_rows($resql) <= 0) {
3608 while ($row = $this->db->fetch_row($resql)) {
3610 if (!empty($includealltree) && $includealltree <= 1000) {
3611 $rows = array_merge($rows, $this->
getChildrenOfLine($row[0], $includealltree + 1));
3625 public function line_up($rowid, $fk_parent_line =
true)
3628 $this->
line_order(
false,
'ASC', $fk_parent_line);
3648 $this->
line_order(
false,
'ASC', $fk_parent_line);
3669 global $hookmanager;
3670 $fieldposition =
'rang';
3671 if (in_array($this->table_element_line, array(
'bom_bomline',
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3672 $fieldposition =
'position';
3675 $sql =
"UPDATE ".$this->db->prefix().$this->table_element_line.
" SET ".$this->db->sanitize($fieldposition).
" = ".((int) $rang);
3676 $sql .=
' WHERE rowid = '.((int) $rowid);
3678 dol_syslog(get_class($this).
"::updateRangOfLine", LOG_DEBUG);
3679 if (!$this->db->query($sql)) {
3684 $parameters = array(
'rowid' => $rowid,
'rang' => $rang,
'fieldposition' => $fieldposition);
3686 $reshook = $hookmanager->executeHooks(
'afterRankOfLineUpdate', $parameters, $this, $action);
3700 $num = count($rows);
3701 for ($i = 0; $i < $num; $i++) {
3719 $fieldposition =
'rang';
3720 if (in_array($this->table_element_line, array(
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3721 $fieldposition =
'position';
3724 $sql =
"UPDATE ".$this->db->prefix().$this->db->sanitize($this->table_element_line).
" SET ".$this->db->sanitize($fieldposition).
" = ".((int) $rang);
3725 $sql .=
" WHERE ".$this->db->sanitize($this->fk_element).
" = ".((int) $this->
id);
3726 $sql .=
" AND " . $this->db->sanitize($fieldposition) .
" = " . ((int) ($rang - 1));
3727 if (!$this->db->query($sql)) {
3728 $this->error = $this->db->lasterror();
3732 $sql =
"UPDATE ".$this->db->prefix().$this->table_element_line.
" SET ".$this->db->sanitize($fieldposition).
" = ".((int) ($rang - 1));
3733 $sql .=
' WHERE rowid = '.((int) $rowid);
3734 if (!$this->db->query($sql)) {
3735 $this->error = $this->db->lasterror();
3752 if ($rang >= $max) {
3756 $fieldposition =
'rang';
3757 if (in_array($this->table_element_line, array(
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3758 $fieldposition =
'position';
3761 $sql =
"UPDATE ".$this->db->prefix().$this->db->sanitize($this->table_element_line).
" SET ".$this->db->sanitize($fieldposition).
" = ".((int) $rang);
3762 $sql .=
" WHERE ".$this->db->sanitize($this->fk_element).
" = ".((int) $this->
id);
3763 $sql .=
" AND " . $this->db->sanitize($fieldposition) .
" = " . ((int) ($rang + 1));
3764 if (!$this->db->query($sql)) {
3765 $this->error = $this->db->lasterror();
3769 $sql =
"UPDATE ".$this->db->prefix().$this->table_element_line.
" SET ".$this->db->sanitize($fieldposition).
" = ".((int) ($rang + 1));
3770 $sql .=
' WHERE rowid = '.((int) $rowid);
3771 if (!$this->db->query($sql)) {
3772 $this->error = $this->db->lasterror();
3787 $fieldposition =
'rang';
3788 if (in_array($this->table_element_line, array(
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3789 $fieldposition =
'position';
3792 $sql =
"SELECT " . $this->db->sanitize($fieldposition) .
" FROM ".$this->db->prefix().$this->db->sanitize($this->table_element_line);
3793 $sql .=
" WHERE rowid = ".((int) $rowid);
3795 dol_syslog(get_class($this).
"::getRangOfLine", LOG_DEBUG);
3796 $resql = $this->db->query($sql);
3801 $row = $this->db->fetch_row($resql);
3813 $fieldposition =
'rang';
3814 if (in_array($this->table_element_line, array(
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3815 $fieldposition =
'position';
3818 $sql =
"SELECT rowid FROM ".$this->db->prefix().$this->db->sanitize($this->table_element_line);
3819 $sql .=
" WHERE ".$this->db->sanitize($this->fk_element).
" = ".((int) $this->
id);
3820 $sql .=
" AND " . $this->db->sanitize($fieldposition) .
" = ".((int) $rang);
3821 $resql = $this->db->query($sql);
3826 $row = $this->db->fetch_row($resql);
3840 $positionfield =
'rang';
3841 if (in_array($this->table_element, array(
'bom_bom',
'product_attribute'))) {
3842 $positionfield =
'position';
3845 $sql =
"SELECT max(".$this->db->sanitize($positionfield).
") FROM ".$this->db->prefix().$this->db->sanitize($this->table_element_line);
3846 $sql .=
" WHERE ".$this->db->sanitize($this->fk_element).
" = ".((int) $this->
id);
3849 if ($fk_parent_line) {
3850 $sql .=
" AND fk_parent_line = ".((int) $fk_parent_line);
3853 dol_syslog(get_class($this).
"::line_max", LOG_DEBUG);
3854 $resql = $this->db->query($sql);
3856 $row = $this->db->fetch_row($resql);
3858 if ($fk_parent_line) {
3859 if (!empty($row[0])) {
3882 if (!$this->table_element) {
3883 dol_syslog(get_class($this).
"::update_ref_ext was called on object with property table_element not defined", LOG_ERR);
3887 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
3888 $sql .=
" SET ref_ext = '".$this->db->escape($ref_ext).
"'";
3890 $sql .=
" WHERE ".(isset($this->table_rowid) ? $this->table_rowid :
'rowid').
" = ".((
int) $this->id);
3892 dol_syslog(get_class($this).
"::update_ref_ext", LOG_DEBUG);
3893 if ($this->db->query($sql)) {
3894 $this->ref_ext = $ref_ext;
3897 $this->error = $this->db->error();
3916 if (!$this->table_element) {
3917 $this->error =
'update_note was called on object with property table_element not defined';
3918 dol_syslog(get_class($this).
"::update_note was called on object with property table_element not defined", LOG_ERR);
3921 if (!in_array($suffix, array(
'',
'_public',
'_private'))) {
3922 $this->error =
'update_note Parameter suffix must be empty, \'_private\' or \'_public\'';
3923 dol_syslog(get_class($this).
"::update_note Parameter suffix must be empty, '_private' or '_public'", LOG_ERR);
3927 $newsuffix = $suffix;
3930 if ($this->table_element ==
'product' && $newsuffix ==
'_private') {
3933 if (in_array($this->table_element, array(
'actioncomm',
'adherent',
'advtargetemailing',
'cronjob',
'establishment'))) {
3934 $fieldusermod =
"fk_user_mod";
3935 } elseif ($this->table_element ==
'ecm_files') {
3936 $fieldusermod =
"fk_user_m";
3938 $fieldusermod =
"fk_user_modif";
3940 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
3941 $sql .=
" SET note".$this->db->sanitize($newsuffix).
" = ".(!empty($note) ? (
"'".$this->db->escape($note).
"'") :
"NULL");
3942 $sql .=
", ".$this->db->sanitize($fieldusermod).
" = ".((int) $user->id);
3943 $sql .=
" WHERE rowid = ".((int) $this->
id);
3945 dol_syslog(get_class($this).
"::update_note", LOG_DEBUG);
3946 if ($this->db->query($sql)) {
3947 if ($suffix ==
'_public') {
3948 $this->note_public = $note;
3949 } elseif ($suffix ==
'_private') {
3950 $this->note_private = $note;
3952 $this->note = $note;
3953 $this->note_private = $note;
3955 if (empty($notrigger)) {
3957 switch ($this->element) {
3959 $triggerName =
'COMPANY_MODIFY';
3962 $triggerName =
'BILL_MODIFY';
3964 case 'invoice_supplier':
3965 $triggerName =
'BILL_SUPPLIER_MODIFY';
3968 $triggerName =
'BILLREC_MODIFIY';
3970 case 'expensereport':
3971 $triggerName =
'EXPENSE_REPORT_MODIFY';
3974 $triggerName = (!empty($this->TRIGGER_PREFIX) ? $this->TRIGGER_PREFIX : strtoupper($this->element)) .
'_MODIFY';
3976 $ret = $this->call_trigger($triggerName, $user);
3983 $this->error = $this->db->lasterror();
4014 public function update_price($exclspec = 0, $roundingadjust =
'auto', $nodatabaseupdate = 0, $seller =
null)
4017 global
$conf, $hookmanager, $action;
4019 $parameters = array(
'exclspec' => $exclspec,
'roundingadjust' => $roundingadjust,
'nodatabaseupdate' => $nodatabaseupdate,
'seller' => $seller);
4020 $reshook = $hookmanager->executeHooks(
'updateTotalPrice', $parameters, $this, $action);
4023 } elseif ($reshook < 0) {
4028 $isElementForSupplier =
false;
4029 $roundTotalConstName =
'MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND';
4031 if ($this->element ==
'propal') {
4032 $MODULE =
"MODULE_DISALLOW_UPDATE_PRICE_PROPOSAL";
4033 } elseif ($this->element ==
'commande' || $this->element ==
'order') {
4034 $MODULE =
"MODULE_DISALLOW_UPDATE_PRICE_ORDER";
4035 } elseif ($this->element ==
'facture' || $this->element ==
'invoice') {
4036 $MODULE =
"MODULE_DISALLOW_UPDATE_PRICE_INVOICE";
4037 } elseif ($this->element ==
'facture_fourn' || $this->element ==
'supplier_invoice' || $this->element ==
'invoice_supplier' || $this->element ==
'invoice_supplier_rec') {
4038 $isElementForSupplier =
true;
4039 $MODULE =
"MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_INVOICE";
4040 } elseif ($this->element ==
'order_supplier' || $this->element ==
'supplier_order') {
4041 $isElementForSupplier =
true;
4042 $MODULE =
"MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_ORDER";
4043 } elseif ($this->element ==
'supplier_proposal') {
4044 $isElementForSupplier =
true;
4045 $MODULE =
"MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_PROPOSAL";
4047 if ($isElementForSupplier) {
4048 $roundTotalConstName =
'MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND_SUPPLIER';
4051 if (!empty($MODULE)) {
4054 foreach ($modsactivated as $mod) {
4062 include_once DOL_DOCUMENT_ROOT.
'/core/lib/price.lib.php';
4064 $forcedroundingmode = $roundingadjust;
4065 if ($forcedroundingmode ==
'auto' && isset(
$conf->global->{$roundTotalConstName})) {
4067 } elseif ($forcedroundingmode ==
'auto') {
4068 $forcedroundingmode =
'0';
4073 $multicurrency_tx = !empty($this->multicurrency_tx) ? $this->multicurrency_tx : 1;
4076 $fieldtva =
'total_tva';
4077 $fieldlocaltax1 =
'total_localtax1';
4078 $fieldlocaltax2 =
'total_localtax2';
4079 $fieldup =
'subprice';
4080 $base_price_type =
'HT';
4081 if ($this->element ==
'facture_fourn' || $this->element ==
'invoice_supplier') {
4085 if ($this->element ==
'invoice_supplier_rec') {
4088 if ($this->element ==
'expensereport') {
4092 $forcedroundingmode =
'0';
4093 $fieldup =
'value_unit';
4094 $base_price_type =
'TTC';
4097 $sql =
"SELECT rowid, qty, ".$this->db->sanitize($fieldup).
" as up, remise_percent,";
4098 $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,";
4099 $sql .=
' tva_tx as vatrate, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type,';
4100 $sql .=
' info_bits, product_type,';
4101 if ($this->element ==
'expensereport') {
4102 $sql .=
' comments as description';
4104 $sql .=
' description';
4106 if ($this->table_element_line ==
'facturedet') {
4107 $sql .=
', situation_percent';
4109 $sql .=
', multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc';
4110 $sql .=
" FROM ".$this->db->prefix().$this->db->sanitize($this->table_element_line);
4111 $sql .=
" WHERE ".$this->db->sanitize($this->fk_element).
" = ".((int) $this->
id);
4113 $product_field =
'product_type';
4114 if ($this->table_element_line ==
'contratdet') {
4115 $product_field =
'';
4117 if ($product_field) {
4118 $sql .=
" AND ".$this->db->sanitize($product_field).
" <> 9";
4121 $sql .=
' ORDER by rowid';
4123 dol_syslog(get_class($this).
"::update_price", LOG_DEBUG);
4125 $resql = $this->db->query($sql);
4127 $this->total_ht = 0;
4128 $this->total_tva = 0;
4129 $this->total_localtax1 = 0;
4130 $this->total_localtax2 = 0;
4131 $this->total_ttc = 0;
4132 $total_ht_by_vats = array();
4133 $total_tva_by_vats = array();
4134 $total_ttc_by_vats = array();
4135 $this->multicurrency_total_ht = 0;
4136 $this->multicurrency_total_tva = 0;
4137 $this->multicurrency_total_ttc = 0;
4141 $num = $this->db->num_rows($resql);
4144 $obj = $this->db->fetch_object($resql);
4147 $parameters = array(
'fk_element' => $obj->rowid);
4148 $reshook = $hookmanager->executeHooks(
'changeRoundingMode', $parameters, $this, $action);
4150 if (empty($reshook) && $forcedroundingmode ==
'0') {
4152 $localtax_array = array($obj->localtax1_type, $obj->localtax1_tx, $obj->localtax2_type, $obj->localtax2_tx);
4153 $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);
4155 $diff_when_using_price_ht =
price2num((
float) $tmpcal[1] - $obj->total_tva,
'MT', 1);
4156 $diff_on_current_total =
price2num($obj->total_ttc - $obj->total_ht - $obj->total_tva - $obj->total_localtax1 - $obj->total_localtax2,
'MT', 1);
4160 if ($diff_on_current_total) {
4162 $sqlfix =
"UPDATE ".$this->db->prefix().$this->table_element_line;
4163 $sqlfix .=
" SET ".$this->db->sanitize($fieldtva).
" = ".
price2num((
float) $tmpcal[1]).
", total_ttc = ".
price2num((
float) $tmpcal[2]);
4164 $sqlfix .=
", multicurrency_total_tva = ".price2num((
float) $tmpcal[17]).
", multicurrency_total_ttc = ".
price2num((
float) $tmpcal[18]);
4165 $sqlfix .=
" WHERE rowid = ".((int) $obj->rowid);
4166 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);
4167 $resqlfix = $this->db->query($sqlfix);
4171 $obj->total_tva = $tmpcal[1];
4172 $obj->total_ttc = $tmpcal[2];
4173 $obj->multicurrency_total_tva = $tmpcal[17];
4174 $obj->multicurrency_total_ttc = $tmpcal[18];
4175 } elseif ($diff_when_using_price_ht) {
4179 if ((
float) $tmpcal[0] == (
float) $obj->total_ht) {
4182 if ($obj->description !=
'(DEPOSIT)' && !
getDolGlobalInt(
'MAIN_DISABLE_AUTOFIX_CORRUPTED_LINES_WHEN_TOTAL_DOES_NOT_MATCH_RECALCULATION_FROM_UP')) {
4186 $sqlfix =
"UPDATE ".$this->db->prefix().$this->table_element_line;
4187 $sqlfix .=
" SET ".$this->db->sanitize($fieldtva).
" = ".
price2num((
float) $tmpcal[1]).
", total_ttc = ".
price2num((
float) $tmpcal[2]);
4188 $sqlfix .=
", multicurrency_total_tva = ".price2num((
float) $tmpcal[17]).
", multicurrency_total_ttc = ".
price2num((
float) $tmpcal[18]);
4189 $sqlfix .=
" WHERE rowid = ".((int) $obj->rowid);
4191 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);
4193 $resqlfix = $this->db->query($sqlfix);
4197 $obj->total_tva = $tmpcal[1];
4198 $obj->total_ttc = $tmpcal[2];
4199 $obj->multicurrency_total_tva = $tmpcal[17];
4200 $obj->multicurrency_total_ttc = $tmpcal[18];
4206 $this->total_ht += $obj->total_ht;
4207 $this->total_tva += $obj->total_tva;
4208 $this->total_localtax1 += $obj->total_localtax1;
4209 $this->total_localtax2 += $obj->total_localtax2;
4210 $this->total_ttc += $obj->total_ttc;
4211 $this->multicurrency_total_ht += $obj->multicurrency_total_ht;
4212 $this->multicurrency_total_tva += $obj->multicurrency_total_tva;
4213 $this->multicurrency_total_ttc += $obj->multicurrency_total_ttc;
4215 if (!isset($total_ht_by_vats[$obj->vatrate])) {
4216 $total_ht_by_vats[$obj->vatrate] = 0;
4218 if (!isset($total_tva_by_vats[$obj->vatrate])) {
4219 $total_tva_by_vats[$obj->vatrate] = 0;
4221 if (!isset($total_ttc_by_vats[$obj->vatrate])) {
4222 $total_ttc_by_vats[$obj->vatrate] = 0;
4224 $total_ht_by_vats[$obj->vatrate] += $obj->total_ht;
4225 $total_tva_by_vats[$obj->vatrate] += $obj->total_tva;
4226 $total_ttc_by_vats[$obj->vatrate] += $obj->total_ttc;
4228 if ($forcedroundingmode ==
'1') {
4229 if ($base_price_type ==
'TTC') {
4230 $tmpvat =
price2num($total_ttc_by_vats[$obj->vatrate] * $obj->vatrate / (100 + $obj->vatrate),
'MT', 1);
4232 $tmpvat =
price2num($total_ht_by_vats[$obj->vatrate] * $obj->vatrate / 100,
'MT', 1);
4234 $diff =
price2num($total_tva_by_vats[$obj->vatrate] - (
float) $tmpvat,
'MT', 1);
4237 $maxdiff = (10 * pow(10, -1 *
getDolGlobalInt(
'MAIN_MAX_DECIMALS_TOT', 0)));
4238 if (abs((
float) $diff) > $maxdiff) {
4240 $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.';
4242 $this->error = $errmsg;
4247 if ($base_price_type ==
'TTC') {
4248 $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);
4249 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);
4251 $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);
4252 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);
4255 $resqlfix = $this->db->query($sqlfix);
4261 $this->total_tva = (float)
price2num($this->total_tva - (
float) $diff,
'', 1);
4262 $total_tva_by_vats[$obj->vatrate] = (float)
price2num($total_tva_by_vats[$obj->vatrate] - (
float) $diff,
'', 1);
4263 if ($base_price_type ==
'TTC') {
4264 $this->total_ht = (float)
price2num($this->total_ht + (
float) $diff,
'', 1);
4265 $total_ht_by_vats[$obj->vatrate] = (float)
price2num($total_ht_by_vats[$obj->vatrate] + (
float) $diff,
'', 1);
4267 $this->total_ttc = (float)
price2num($this->total_ttc - (
float) $diff,
'', 1);
4268 $total_ttc_by_vats[$obj->vatrate] = (float)
price2num($total_ttc_by_vats[$obj->vatrate] - (
float) $diff,
'', 1);
4278 $this->total_ttc += isset($this->revenuestamp) ? $this->revenuestamp : 0;
4280 $this->multicurrency_total_ttc += isset($this->revenuestamp) ? ($this->revenuestamp * $multicurrency_tx) : 0;
4283 if (!empty($this->situation_cycle_ref) && !empty($this->situation_counter) && $this->situation_counter > 1 && method_exists($this,
'get_prev_sits')) {
4284 '@phan-var-force Facture $this';
4285 include_once DOL_DOCUMENT_ROOT.
'/compta/facture/class/facture.class.php';
4288 $prev_sits = $this->get_prev_sits();
4290 foreach ($prev_sits as $sit) {
4291 $this->total_ht -= $sit->total_ht;
4292 $this->total_tva -= $sit->total_tva;
4293 $this->total_localtax1 -= $sit->total_localtax1;
4294 $this->total_localtax2 -= $sit->total_localtax2;
4295 $this->total_ttc -= $sit->total_ttc;
4296 $this->multicurrency_total_ht -= $sit->multicurrency_total_ht;
4297 $this->multicurrency_total_tva -= $sit->multicurrency_total_tva;
4298 $this->multicurrency_total_ttc -= $sit->multicurrency_total_ttc;
4305 $this->total_ht = (float)
price2num($this->total_ht);
4306 $this->total_tva = (float)
price2num($this->total_tva);
4307 $this->total_localtax1 = (float)
price2num($this->total_localtax1);
4308 $this->total_localtax2 = (float)
price2num($this->total_localtax2);
4309 $this->total_ttc = (float)
price2num($this->total_ttc);
4311 $this->db->free($resql);
4314 $fieldht =
'total_ht';
4316 $fieldlocaltax1 =
'localtax1';
4317 $fieldlocaltax2 =
'localtax2';
4318 $fieldttc =
'total_ttc';
4320 if (in_array($this->element, array(
'propal',
'commande',
'facture',
'facturerec',
'supplier_proposal',
'order_supplier',
'facture_fourn',
'invoice_supplier',
'invoice_supplier_rec',
'expensereport'))) {
4321 $fieldtva =
'total_tva';
4324 if (!$error && empty($nodatabaseupdate)) {
4325 $sql =
"UPDATE ".$this->db->prefix().$this->table_element.
' SET';
4326 $sql .=
" ".$this->db->sanitize($fieldht).
" = ".((float)
price2num($this->total_ht,
'MT', 1)).
",";
4327 $sql .=
" ".$this->db->sanitize($fieldtva).
" = ".((float)
price2num($this->total_tva,
'MT', 1)).
",";
4328 $sql .=
" ".$this->db->sanitize($fieldlocaltax1).
" = ".((float)
price2num($this->total_localtax1,
'MT', 1)).
",";
4329 $sql .=
" ".$this->db->sanitize($fieldlocaltax2).
" = ".((float)
price2num($this->total_localtax2,
'MT', 1)).
",";
4330 $sql .=
" ".$this->db->sanitize($fieldttc).
" = ".((float)
price2num($this->total_ttc,
'MT', 1));
4331 $sql .=
", multicurrency_total_ht = ".((float)
price2num($this->multicurrency_total_ht,
'MT', 1));
4332 $sql .=
", multicurrency_total_tva = ".((float)
price2num($this->multicurrency_total_tva,
'MT', 1));
4333 $sql .=
", multicurrency_total_ttc = ".((float)
price2num($this->multicurrency_total_ttc,
'MT', 1));
4334 $sql .=
" WHERE rowid = ".((int) $this->
id);
4336 dol_syslog(get_class($this).
"::update_price", LOG_DEBUG);
4337 $resql = $this->db->query($sql);
4341 $this->error = $this->db->lasterror();
4342 $this->errors[] = $this->db->lasterror();
4347 $this->db->commit();
4350 $this->db->rollback();
4370 public function add_object_linked($origin =
null, $origin_id =
null, $f_user =
null, $notrigger = 0)
4373 global $user, $hookmanager, $action;
4376 if (empty($this->origin_type) && !empty($this->origin)) {
4377 $this->origin_type = $this->origin;
4379 $origin = (!empty($origin) ? $origin : $this->origin_type);
4380 $origin_id = (!empty($origin_id) ? $origin_id : $this->origin_id);
4381 $f_user = isset($f_user) ? $f_user : $user;
4384 if ($origin ==
'order') {
4385 $origin =
'commande';
4387 if ($origin ==
'invoice') {
4388 $origin =
'facture';
4390 if ($origin ==
'invoice_template') {
4391 $origin =
'facturerec';
4393 if ($origin ==
'supplierorder') {
4394 $origin =
'order_supplier';
4398 $targettype = $this->getElementType();
4400 $parameters = array(
'targettype' => $targettype);
4402 $reshook = $hookmanager->executeHooks(
'setLinkedObjectSourceTargetType', $parameters, $this, $action);
4404 if (!empty($hookmanager->resArray[
'targettype'])) {
4405 $targettype = $hookmanager->resArray[
'targettype'];
4412 $sql =
"INSERT INTO " . $this->db->prefix() .
"element_element (";
4413 $sql .=
"fk_source";
4414 $sql .=
", sourcetype";
4415 $sql .=
", fk_target";
4416 $sql .=
", targettype";
4417 $sql .=
") VALUES (";
4418 $sql .= ((int) $origin_id);
4419 $sql .=
", '" . $this->db->escape($origin) .
"'";
4420 $sql .=
", " . ((int) $this->
id);
4421 $sql .=
", '" . $this->db->escape($targettype) .
"'";
4424 dol_syslog(get_class($this) .
"::add_object_linked", LOG_DEBUG);
4425 if ($this->db->query($sql)) {
4429 if ($origin ===
'order_supplier' && $targettype ===
'invoice_supplier' && $this->element ===
'invoice_supplier' && (
int) $origin_id > 0 && (
int) $this->
id > 0) {
4430 $sourceinvoices = array();
4432 $sqlsources =
"SELECT DISTINCT rc.fk_invoice_supplier_source as rowid";
4433 $sqlsources .=
" FROM ".$this->db->prefix().
"societe_remise_except as rc";
4434 $sqlsources .=
" WHERE rc.fk_invoice_supplier = ".((int) $this->
id);
4435 $sqlsources .=
" AND rc.fk_invoice_supplier_source IS NOT NULL";
4437 $resqlsources = $this->db->query($sqlsources);
4438 if ($resqlsources) {
4439 while ($objsrc = $this->db->fetch_object($resqlsources)) {
4440 $srcid = (int) $objsrc->rowid;
4441 if ($srcid > 0 && $srcid !== (
int) $this->
id) {
4442 $sourceinvoices[$srcid] = $srcid;
4446 dol_syslog(get_class($this).
"::add_object_linked Failed to read supplier invoice discounts sources", LOG_WARNING);
4449 if (!empty($sourceinvoices)) {
4450 $existing = array();
4451 $sourcelist = implode(
',', $sourceinvoices);
4453 $sqlexists =
"SELECT fk_target";
4454 $sqlexists .=
" FROM ".$this->db->prefix().
"element_element";
4455 $sqlexists .=
" WHERE fk_source = ".((int) $origin_id);
4456 $sqlexists .=
" AND sourcetype = '".$this->db->escape($origin).
"'";
4457 $sqlexists .=
" AND targettype = '".$this->db->escape($targettype).
"'";
4458 $sqlexists .=
" AND fk_target IN (".$this->db->sanitize($sourcelist).
")";
4460 $resqlexists = $this->db->query($sqlexists);
4462 while ($objexist = $this->db->fetch_object($resqlexists)) {
4463 $existing[(int) $objexist->fk_target] = 1;
4466 dol_syslog(get_class($this).
"::add_object_linked Failed to read existing linked supplier invoices", LOG_WARNING);
4469 foreach ($sourceinvoices as $srcid) {
4470 if (!empty($existing[(
int) $srcid])) {
4474 $sqladd =
"INSERT INTO " . $this->db->prefix() .
"element_element (fk_source, sourcetype, fk_target, targettype)";
4475 $sqladd .=
" VALUES (".((int) $origin_id).
", '".$this->db->escape($origin).
"', ".((int) $srcid).
", '".$this->db->escape($targettype).
"')";
4476 $this->db->query($sqladd);
4483 $this->context[
'link_origin'] = $origin;
4484 $this->context[
'link_origin_id'] = $origin_id;
4486 $result = $this->call_trigger(
'OBJECT_LINK_INSERT', $f_user);
4493 $this->error = $this->db->lasterror();
4498 $this->db->commit();
4501 $this->db->rollback();
4515 $coreModule = array(
'knowledgemanagement',
'partnership',
'workstation',
'ticket',
'recruitment',
'eventorganization',
'asset');
4517 return ((!empty($this->module) && !in_array($this->module, $coreModule)) ? $this->module.
'_' :
'').$this->element;
4543 public function fetchObjectLinked($sourceid =
null, $sourcetype =
'', $targetid =
null, $targettype =
'', $clause =
'OR', $alsosametype = 1, $orderby =
'sourcetype', $loadalsoobjects = 1)
4545 global $hookmanager, $action;
4550 if ($this->
id > 0 && !empty($this->linkedObjectsFullLoaded[$this->
id])) {
4554 $this->linkedObjectsIds = array();
4555 $this->linkedObjects = array();
4558 $parameters = array(
4559 'sourceid' => $sourceid,
4560 'sourcetype' => $sourcetype,
4561 'targetid' => $targetid,
4562 'targettype' => $targettype,
4563 'clause' => $clause,
4564 'alsosametype' => $alsosametype,
4565 'orderby' => $orderby,
4566 'loadalsoobjects' => $loadalsoobjects
4568 $reshook = $hookmanager->executeHooks(
'fetchObjectLinked', $parameters, $this, $action);
4573 $justsource =
false;
4574 $justtarget =
false;
4575 $withtargettype =
false;
4576 $withsourcetype =
false;
4579 if (is_object($hookmanager)) {
4580 $parameters = array(
'sourcetype' => $sourcetype,
'sourceid' => $sourceid,
'targettype' => $targettype,
'targetid' => $targetid);
4581 $reshook = $hookmanager->executeHooks(
'setLinkedObjectSourceTargetType', $parameters, $this, $action);
4583 if (!empty($hookmanager->resArray[
'sourcetype'])) {
4584 $sourcetype = $hookmanager->resArray[
'sourcetype'];
4586 if (!empty($hookmanager->resArray[
'sourceid'])) {
4587 $sourceid = $hookmanager->resArray[
'sourceid'];
4589 if (!empty($hookmanager->resArray[
'targettype'])) {
4590 $targettype = $hookmanager->resArray[
'targettype'];
4592 if (!empty($hookmanager->resArray[
'targetid'])) {
4593 $targetid = $hookmanager->resArray[
'targetid'];
4598 if (!empty($sourceid) && !empty($sourcetype) && empty($targetid)) {
4600 if (!empty($targettype)) {
4601 $withtargettype =
true;
4604 if (!empty($targetid) && !empty($targettype) && empty($sourceid)) {
4606 if (!empty($sourcetype)) {
4607 $withsourcetype =
true;
4611 $sourceid = (!empty($sourceid) ? $sourceid :
$this->id);
4612 $targetid = (!empty($targetid) ? $targetid :
$this->id);
4613 $sourcetype = (!empty($sourcetype) ? $sourcetype : $this->getElementType());
4614 $targettype = (!empty($targettype) ? $targettype : $this->getElementType());
4623 $sql =
"SELECT rowid, fk_source, sourcetype, fk_target, targettype";
4624 $sql .=
" FROM ".$this->db->prefix().
"element_element";
4626 if ($justsource || $justtarget) {
4628 $sql .=
"fk_source = ".((int) $sourceid).
" AND sourcetype = '".$this->db->escape($sourcetype).
"'";
4629 if ($withtargettype) {
4630 $sql .=
" AND targettype = '".$this->db->escape($targettype).
"'";
4632 } elseif ($justtarget) {
4633 $sql .=
"fk_target = ".((int) $targetid).
" AND targettype = '".$this->db->escape($targettype).
"'";
4634 if ($withsourcetype) {
4635 $sql .=
" AND sourcetype = '".$this->db->escape($sourcetype).
"'";
4639 $sql .=
"(fk_source = ".((int) $sourceid).
" AND sourcetype = '".$this->db->escape($sourcetype).
"')";
4640 $sql .=
" ".$this->db->sanitize($clause).
" (fk_target = ".((int) $targetid).
" AND targettype = '".$this->db->escape($targettype).
"')";
4641 if ($loadalsoobjects && $this->
id > 0 && $sourceid == $this->
id && $sourcetype == $this->element && $targetid == $this->
id && $targettype == $this->element && $clause ==
'OR') {
4642 $this->linkedObjectsFullLoaded[
$this->id] =
true;
4645 $sql .= $this->db->order($orderby);
4647 dol_syslog(get_class($this).
"::fetchObjectLink", LOG_DEBUG);
4649 $resql = $this->db->query($sql);
4651 $num = $this->db->num_rows($resql);
4654 $obj = $this->db->fetch_object($resql);
4655 if ($justsource || $justtarget) {
4657 $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
4658 } elseif ($justtarget) {
4659 $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
4662 if ($obj->fk_source == $sourceid && $obj->sourcetype == $sourcetype) {
4663 $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
4665 if ($obj->fk_target == $targetid && $obj->targettype == $targettype) {
4666 $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
4672 if (!empty($this->linkedObjectsIds)) {
4673 $tmparray = $this->linkedObjectsIds;
4674 foreach ($tmparray as $objecttype => $objectids) {
4675 $element_properties = getElementProperties($objecttype);
4676 $element = $element_properties[
'element'];
4677 $classPath = $element_properties[
'classpath'];
4678 $classFile = $element_properties[
'classfile'];
4679 $className = $element_properties[
'classname'];
4680 $module = $element_properties[
'module'];
4683 if (
isModEnabled($module) && (($element != $this->element) || $alsosametype)) {
4684 if ($loadalsoobjects && (is_numeric($loadalsoobjects) || ($loadalsoobjects === $objecttype))) {
4686 if (class_exists($className)) {
4687 foreach ($objectids as $i => $objectid) {
4688 $object =
new $className($this->db);
4689 '@phan-var-force CommonObject $object';
4690 $ret =
$object->fetch($objectid);
4692 $this->linkedObjects[$objecttype][$i] =
$object;
4698 unset($this->linkedObjectsIds[$objecttype]);
4717 if ($this->
id > 0 && !empty($this->linkedObjectsFullLoaded[$this->
id])) {
4718 unset($this->linkedObjectsFullLoaded[$this->
id]);
4736 public function updateObjectLinked($sourceid =
null, $sourcetype =
'', $targetid =
null, $targettype =
'', $f_user =
null, $notrigger = 0)
4739 $updatesource =
false;
4740 $updatetarget =
false;
4741 $f_user = isset($f_user) ? $f_user : $user;
4744 if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) {
4745 $updatesource =
true;
4746 } elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) {
4747 $updatetarget =
true;
4753 $sql =
"UPDATE " . $this->db->prefix() .
"element_element SET ";
4754 if ($updatesource) {
4755 $sql .=
"fk_source = " . ((int) $sourceid);
4756 $sql .=
", sourcetype = '" . $this->db->escape($sourcetype) .
"'";
4757 $sql .=
" WHERE fk_target = " . ((int) $this->
id);
4758 $sql .=
" AND targettype = '" . $this->db->escape($this->element) .
"'";
4759 } elseif ($updatetarget) {
4760 $sql .=
"fk_target = " . ((int) $targetid);
4761 $sql .=
", targettype = '" . $this->db->escape($targettype) .
"'";
4762 $sql .=
" WHERE fk_source = " . ((int) $this->
id);
4763 $sql .=
" AND sourcetype = '" . $this->db->escape($this->element) .
"'";
4766 dol_syslog(get_class($this) .
"::updateObjectLinked", LOG_DEBUG);
4767 if ($this->db->query($sql)) {
4770 $this->context[
'link_source_id'] = $sourceid;
4771 $this->context[
'link_source_type'] = $sourcetype;
4772 $this->context[
'link_target_id'] = $targetid;
4773 $this->context[
'link_target_type'] = $targettype;
4775 $result = $this->call_trigger(
'OBJECT_LINK_MODIFY', $f_user);
4782 $this->error = $this->db->lasterror();
4787 $this->db->commit();
4790 $this->db->rollback();
4808 public function deleteObjectLinked($sourceid =
null, $sourcetype =
'', $targetid =
null, $targettype =
'', $rowid = 0, $f_user =
null, $notrigger = 0)
4811 $deletesource =
false;
4812 $deletetarget =
false;
4813 $f_user = isset($f_user) ? $f_user : $user;
4815 if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) {
4816 $deletesource =
true;
4817 } elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) {
4818 $deletetarget =
true;
4821 $element = $this->getElementType();
4822 $sourceid = (!empty($sourceid) ? $sourceid :
$this->id);
4823 $sourcetype = (!empty($sourcetype) ? $sourcetype : $element);
4824 $targetid = (!empty($targetid) ? $targetid :
$this->id);
4825 $targettype = (!empty($targettype) ? $targettype : $element);
4831 $this->context[
'link_id'] = $rowid;
4832 $this->context[
'link_source_id'] = $sourceid;
4833 $this->context[
'link_source_type'] = $sourcetype;
4834 $this->context[
'link_target_id'] = $targetid;
4835 $this->context[
'link_target_type'] = $targettype;
4837 $result = $this->call_trigger(
'OBJECT_LINK_DELETE', $f_user);
4845 $sql =
"DELETE FROM " . $this->db->prefix() .
"element_element";
4848 $sql .=
" rowid = " . ((int) $rowid);
4850 if ($deletesource) {
4851 $sql .=
" fk_source = " . ((int) $sourceid) .
" AND sourcetype = '" . $this->db->escape($sourcetype) .
"'";
4852 $sql .=
" AND fk_target = " . ((int) $this->
id) .
" AND targettype = '" . $this->db->escape($element) .
"'";
4853 } elseif ($deletetarget) {
4854 $sql .=
" fk_target = " . ((int) $targetid) .
" AND targettype = '" . $this->db->escape($targettype) .
"'";
4855 $sql .=
" AND fk_source = " . ((int) $this->
id) .
" AND sourcetype = '" . $this->db->escape($element) .
"'";
4857 $sql .=
" (fk_source = " . ((int) $this->
id) .
" AND sourcetype = '" . $this->db->escape($element) .
"')";
4859 $sql .=
" (fk_target = " . ((int) $this->
id) .
" AND targettype = '" . $this->db->escape($element) .
"')";
4863 dol_syslog(get_class($this) .
"::deleteObjectLinked", LOG_DEBUG);
4864 if (!$this->db->query($sql)) {
4865 $this->error = $this->db->lasterror();
4866 $this->errors[] = $this->error;
4872 $this->db->commit();
4875 $this->db->rollback();
4891 if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
4894 if (!preg_match(
'/^[_a-zA-Z0-9]+$/', $field_select)) {
4895 dol_syslog(
'Invalid value $field_select for parameter '.$field_select.
' in call to getAllItemsLinkedByObjectID(). Must be a single field name.', LOG_ERR);
4900 $sql =
"SELECT ".$db->sanitize($field_select).
" FROM ".
$db->prefix().$db->sanitize($table_element).
" WHERE ".
$db->sanitize($field_where).
" = ".((int) $fk_object_where);
4901 $resql =
$db->query($sql);
4904 if (!empty($resql)) {
4905 while ($res =
$db->fetch_object($resql)) {
4906 $TRes[] = $res->{$field_select};
4923 if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
4929 $sql =
"SELECT COUNT(*) as nb FROM ".$db->prefix().$db->sanitize($table_element).
" WHERE ".
$db->sanitize($field_where).
" = ".((int) $fk_object_where);
4930 $resql =
$db->query($sql);
4933 $res =
$db->fetch_object($resql);
4952 if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
4958 $sql =
"DELETE FROM ".$db->prefix().$table_element.
" WHERE ".
$db->sanitize($field_where).
" = ".((int) $fk_object_where);
4959 $resql =
$db->query($sql);
4961 if (empty($resql)) {
4979 public function setStatut($status, $elementId =
null, $elementType =
'', $trigkey =
'', $fieldstatus =
'')
4983 $savElementId = $elementId;
4985 $elementId = (!empty($elementId) ? $elementId :
$this->id);
4986 $elementTable = (!empty($elementType) ? $elementType : $this->table_element);
4990 if (empty($fieldstatus)) {
4991 if ($elementTable ==
'facture_rec') {
4992 $fieldstatus =
"suspended";
4994 if ($elementTable ==
'mailing') {
4995 $fieldstatus =
"statut";
4997 if ($elementTable ==
'cronjob') {
4998 $fieldstatus =
"status";
5000 if ($elementTable ==
'user') {
5001 $fieldstatus =
"statut";
5003 if ($elementTable ==
'expensereport') {
5004 $fieldstatus =
"fk_statut";
5006 if ($elementTable ==
'receptiondet_batch') {
5007 $fieldstatus =
"status";
5009 if ($elementTable ==
'prelevement_bons') {
5010 $fieldstatus =
"statut";
5012 if ($elementTable ==
'bank_account') {
5013 $fieldstatus =
"clos";
5015 if (isset($this->fields) && is_array($this->fields) && array_key_exists(
'status', $this->fields)) {
5016 $fieldstatus =
'status';
5019 if (empty($fieldstatus)) {
5020 $fieldstatus =
'fk_statut';
5024 $sql =
"UPDATE ".$this->db->prefix().$this->db->sanitize($elementTable);
5025 $sql .=
" SET ".$this->db->sanitize($fieldstatus).
" = ".((int) $status);
5028 if ($status == 1 && in_array($elementTable, array(
'expensereport',
'inventory'))) {
5029 $sql .=
", fk_user_valid = ".((int) $user->id);
5031 if ($status == 1 && in_array($elementTable, array(
'expensereport'))) {
5032 $sql .=
", date_valid = '".$this->db->idate(
dol_now()).
"'";
5034 if ($status == 1 && in_array($elementTable, array(
'inventory'))) {
5035 $sql .=
", date_validation = '".$this->db->idate(
dol_now()).
"'";
5037 $sql .=
" WHERE rowid = ".((int) $elementId);
5038 $sql .=
" AND ".$this->db->sanitize($fieldstatus).
" <> ".((int) $status);
5040 dol_syslog(get_class($this).
"::setStatut", LOG_DEBUG);
5041 $resql = $this->db->query($sql);
5045 $nb_rows_affected = $this->db->affected_rows($resql);
5047 if ($nb_rows_affected > 0) {
5048 if (empty($trigkey)) {
5050 if ($this->element ==
'supplier_proposal' && $status == 2) {
5051 $trigkey =
'SUPPLIER_PROPOSAL_SIGN';
5053 if ($this->element ==
'supplier_proposal' && $status == 3) {
5054 $trigkey =
'SUPPLIER_PROPOSAL_REFUSE';
5056 if ($this->element ==
'supplier_proposal' && $status == 4) {
5057 $trigkey =
'SUPPLIER_PROPOSAL_CLOSE';
5059 if ($this->element ==
'fichinter' && $status == 3) {
5060 $trigkey =
'FICHINTER_CLASSIFY_DONE';
5062 if ($this->element ==
'fichinter' && $status == 2) {
5063 $trigkey =
'FICHINTER_CLASSIFY_BILLED';
5065 if ($this->element ==
'fichinter' && $status == 1) {
5066 $trigkey =
'FICHINTER_CLASSIFY_UNBILLED';
5070 $this->context = array_merge($this->context, array(
'newstatus' => $status));
5072 if ($trigkey && $trigkey !=
'none') {
5076 $result = $this->call_trigger($trigkey, $user);
5087 $this->db->commit();
5089 if (empty($savElementId)) {
5091 if ($fieldstatus ==
'dispute_status') {
5092 $this->dispute_status = $status;
5093 } elseif ($fieldstatus ==
'tosell') {
5095 } elseif ($fieldstatus ==
'tobuy') {
5096 $this->status_buy = $status;
5097 } elseif ($fieldstatus ==
'tobatch') {
5098 $this->status_batch = $status;
5106 $this->db->rollback();
5107 dol_syslog(get_class($this).
"::setStatut ".$this->error, LOG_ERR);
5111 $this->error = $this->db->lasterror();
5112 $this->db->rollback();
5127 if (empty(
$id) && empty($ref)) {
5137 $sql =
"SELECT rowid, canvas";
5138 $sql .=
" FROM ".$this->db->prefix().$this->table_element;
5139 $sql .=
" WHERE entity IN (".getEntity($this->element).
")";
5141 $sql .=
" AND rowid = ".((int)
$id);
5144 $sql .=
" AND ref = '".$this->db->escape($ref).
"'";
5147 $resql = $this->db->query($sql);
5149 $obj = $this->db->fetch_object($resql);
5151 $this->canvas = $obj->canvas;
5171 $sql =
"SELECT special_code FROM ".$this->db->prefix().$this->db->sanitize($this->table_element_line);
5172 $sql .=
" WHERE rowid = ".((int) $lineid);
5173 $resql = $this->db->query($sql);
5175 $row = $this->db->fetch_row($resql);
5176 return (!empty($row[0]) ? $row[0] : 0);
5199 if (!isset($this->childtables) || !is_array($this->childtables) || count($this->childtables) == 0) {
5200 dol_print_error(
null,
'Called isObjectUsed on a class with property this->childtables not defined');
5204 $arraytoscan = $this->childtables;
5206 $tmparray = array_keys($this->childtables);
5207 if (is_numeric($tmparray[0])) {
5208 $arraytoscan = array_flip($this->childtables);
5213 foreach ($arraytoscan as $table => $element) {
5217 if (isset($element[
'enabled']) && !empty($element[
'enabled'])) {
5218 $enabled = (int)
dol_eval((
string) $element[
'enabled'], 1);
5219 if (empty($enabled)) {
5225 $sql =
"SELECT COUNT(*) as nb";
5226 $sql .=
" FROM ".$this->db->prefix().$this->db->sanitize($table).
" as c";
5227 if (!empty($element[
'parent']) && !empty($element[
'parentkey'])) {
5228 $sql .=
", ".$this->db->prefix().$this->db->sanitize($element[
'parent']).
" as p";
5230 if (!empty($element[
'fk_element'])) {
5231 $sql .=
" WHERE c.".$this->db->sanitize($element[
'fk_element']).
" = ".((int)
$id);
5233 $sql .=
" WHERE c.".$this->db->sanitize($this->fk_element).
" = ".((int)
$id);
5235 if (!empty($element[
'parent']) && !empty($element[
'parentkey'])) {
5236 $sql .=
" AND c.".$this->db->sanitize($element[
'parentkey']).
" = p.rowid";
5238 if (!empty($element[
'parent']) && !empty($element[
'parenttypefield']) && !empty($element[
'parenttypevalue'])) {
5239 $sql .=
" AND c.".$this->db->sanitize($element[
'parenttypefield']).
" = '".$this->db->escape($element[
'parenttypevalue']).
"'";
5241 if (!empty($entity)) {
5242 if (!empty($element[
'parent']) && !empty($element[
'parentkey'])) {
5243 $sql .=
" AND p.entity = ".((int) $entity);
5245 $sql .=
" AND c.entity = ".((int) $entity);
5250 $resql = $this->db->query($sql);
5252 $obj = $this->db->fetch_object($resql);
5254 $langs->load(
"errors");
5256 $haschild += (int) $obj->nb;
5257 if (is_numeric($element)) {
5258 $this->errors[] = $langs->transnoentitiesnoconv(
"ErrorRecordHasAtLeastOneChildOfType", method_exists($this,
'getNomUrl') ? $this->getNomUrl() : $this->ref, $table);
5259 } elseif (is_string($element)) {
5260 $this->errors[] = $langs->transnoentitiesnoconv(
"ErrorRecordHasAtLeastOneChildOfType", method_exists($this,
'getNomUrl') ? $this->getNomUrl() : $this->ref, $langs->transnoentitiesnoconv($element));
5262 $this->errors[] = $langs->transnoentitiesnoconv(
"ErrorRecordHasAtLeastOneChildOfType", method_exists($this,
'getNomUrl') ? $this->getNomUrl() : $this->ref, $langs->transnoentitiesnoconv($element[
'name']));
5267 $this->errors[] = $this->db->lasterror();
5272 if ($haschild > 0) {
5273 $this->errors[] =
"ErrorRecordHasChildren";
5290 foreach ($this->lines as $key => $val) {
5292 if ($predefined == -1) {
5295 if ($predefined == 1 && $val->fk_product > 0) {
5298 if ($predefined == 0 && $val->fk_product <= 0) {
5301 if ($predefined == 2 && $val->fk_product > 0 && $val->product_type == 0) {
5304 if ($predefined == 3 && $val->fk_product > 0 && $val->product_type == 1) {
5311 dol_syslog(get_class($this).
'::hasProductsOrServices we found '.$nb.
' qualified lines of products/servcies');
5322 if (!empty($this->table_element_line) && ($this->table_element_line !=
'expeditiondet')) {
5323 $total_discount = 0.00;
5325 $sql =
"SELECT subprice as pu_ht, qty, remise_percent, total_ht";
5326 $sql .=
" FROM ".$this->db->prefix().$this->table_element_line;
5327 $sql .=
" WHERE ".$this->db->sanitize($this->fk_element).
" = ".((int) $this->
id);
5329 dol_syslog(get_class($this).
'::getTotalDiscount', LOG_DEBUG);
5330 $resql = $this->db->query($sql);
5332 $num = $this->db->num_rows($resql);
5335 $obj = $this->db->fetch_object($resql);
5337 $pu_ht = $obj->pu_ht;
5339 $total_ht = $obj->total_ht;
5341 $total_discount_line = (float)
price2num(($pu_ht * $qty) - $total_ht,
'MT');
5342 $total_discount += $total_discount_line;
5349 return (
float)
price2num($total_discount);
5371 if (empty($this->lines)) {
5372 return array(
'weight' => $totalWeight,
'volume' => $totalVolume,
'ordered' => $totalOrdered,
'toship' => $totalToShip);
5375 foreach ($this->lines as $line) {
5376 if (isset($line->qty_asked)) {
5377 $totalOrdered += $line->qty_asked;
5379 if (isset($line->qty_shipped)) {
5380 $totalToShip += $line->qty_shipped;
5381 } elseif ($line->element ==
'commandefournisseurdispatch' && isset($line->qty)) {
5382 if (empty($totalToShip)) {
5385 $totalToShip += $line->qty;
5389 if ($this->element ==
'shipping') {
5391 $qty = $line->qty_shipped ? $line->qty_shipped : 0;
5393 $qty = $line->qty ? $line->qty : 0;
5396 $weight = !empty($line->weight) ? $line->weight : 0;
5397 ($weight == 0 && !empty($line->product->weight)) ? $weight = $line->product->weight : 0;
5398 $volume = !empty($line->volume) ? $line->volume : 0;
5399 ($volume == 0 && !empty($line->product->volume)) ? $volume = $line->product->volume : 0;
5401 $weight_units = !empty($line->weight_units) ? $line->weight_units : 0;
5402 ($weight_units == 0 && !empty($line->product->weight_units)) ? $weight_units = $line->product->weight_units : 0;
5403 $volume_units = !empty($line->volume_units) ? $line->volume_units : 0;
5404 ($volume_units == 0 && !empty($line->product->volume_units)) ? $volume_units = $line->product->volume_units : 0;
5408 if (!empty($weight_units)) {
5409 $weightUnit = $weight_units;
5411 if (!empty($volume_units)) {
5412 $volumeUnit = $volume_units;
5415 if (empty($totalWeight)) {
5418 if (empty($totalVolume)) {
5423 if ($weight_units < 50) {
5424 $trueWeightUnit = pow(10, $weightUnit);
5425 $totalWeight += $weight * $qty * $trueWeightUnit;
5427 if ($weight_units == 99) {
5429 $trueWeightUnit = 0.45359237;
5430 $totalWeight += $weight * $qty * $trueWeightUnit;
5431 } elseif ($weight_units == 98) {
5433 $trueWeightUnit = 0.0283495;
5434 $totalWeight += $weight * $qty * $trueWeightUnit;
5436 $totalWeight += $weight * $qty;
5439 if ($volume_units < 50) {
5441 $trueVolumeUnit = pow(10, $volumeUnit);
5443 $totalVolume += $volume * $qty * $trueVolumeUnit;
5445 $totalVolume += $volume * $qty;
5449 return array(
'weight' => $totalWeight,
'volume' => $totalVolume,
'ordered' => $totalOrdered,
'toship' => $totalToShip);
5462 $extraparams = (!empty($this->extraparams) ? json_encode($this->extraparams) :
null);
5463 $extraparams =
dol_trunc($extraparams, 250);
5465 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
5466 $sql .=
" SET extraparams = ".(!empty($extraparams) ?
"'".$this->db->escape($extraparams).
"'" :
"null");
5467 $sql .=
" WHERE rowid = ".((int) $this->
id);
5469 dol_syslog(get_class($this).
"::setExtraParameters", LOG_DEBUG);
5470 $resql = $this->db->query($sql);
5472 $this->error = $this->db->lasterror();
5473 $this->db->rollback();
5476 $this->db->commit();
5499 global
$conf, $user, $langs,
$object, $hookmanager, $extrafields, $form;
5502 if (!is_object($extrafields)) {
5503 require_once DOL_DOCUMENT_ROOT.
'/core/class/extrafields.class.php';
5506 $extrafields->fetch_name_optionals_label($this->table_element_line);
5511 $dirtpls = array_merge(
$conf->modules_parts[
'tpl'], array($defaulttpldir));
5512 foreach ($dirtpls as $module => $reldir) {
5513 if (!empty($module)) {
5516 $tpl = DOL_DOCUMENT_ROOT.$reldir.
'/objectline_create.tpl.php';
5519 if (empty(
$conf->file->strict_mode)) {
5520 $res = @include $tpl;
5522 $res = include $tpl;
5549 public function printObjectLines($action, $seller, $buyer, $selected = 0, $dateSelector = 0, $defaulttpldir =
'/core/tpl')
5551 global
$conf, $hookmanager, $langs, $user, $form, $extrafields,
$object;
5553 global $inputalsopricewithtax, $usemargins, $disableedit, $disablemove, $disableremove, $outputalsopricetotalwithtax;
5557 if (
isModEnabled(
'margin') && !empty($this->element) && in_array($this->element, array(
'facture',
'facturerec',
'propal',
'commande'))) {
5561 $num = count($this->lines);
5564 if (!is_object($extrafields)) {
5565 require_once DOL_DOCUMENT_ROOT.
'/core/class/extrafields.class.php';
5568 $extrafields->fetch_name_optionals_label($this->table_element_line);
5570 if (method_exists($this,
'loadExpeditions')) {
5572 $this->loadExpeditions();
5575 $parameters = array();
5576 $reshook = $hookmanager->executeHooks(
'printObjectLinesBlock', $parameters, $this, $action);
5577 if (empty($reshook)) {
5578 $parameters = array(
'num' => $num,
'dateSelector' => $dateSelector,
'seller' => $seller,
'buyer' => $buyer,
'selected' => $selected,
'table_element_line' => $this->table_element_line);
5579 $reshook = $hookmanager->executeHooks(
'printObjectLineTitle', $parameters, $this, $action);
5580 if (empty($reshook)) {
5584 $dirtpls = array_merge(
$conf->modules_parts[
'tpl'], array($defaulttpldir));
5585 foreach ($dirtpls as $module => $reldir) {
5587 if (!empty($module)) {
5590 $tpl = DOL_DOCUMENT_ROOT.$reldir.
'/objectline_title.tpl.php';
5592 if (file_exists($tpl)) {
5593 if (empty(
$conf->file->strict_mode)) {
5594 $res = @include $tpl;
5596 $res = include $tpl;
5607 print
"<!-- begin printObjectLines() -->\n";
5608 foreach ($this->lines as $line) {
5612 if (is_object($hookmanager)) {
5613 if (empty($line->fk_parent_line)) {
5614 $parameters = array(
'line' => $line,
'num' => $num,
'i' => $i,
'dateSelector' => $dateSelector,
'seller' => $seller,
'buyer' => $buyer,
'selected' => $selected,
'table_element_line' => $line->table_element,
'defaulttpldir' => $defaulttpldir);
5615 $reshook = $hookmanager->executeHooks(
'printObjectLine', $parameters, $this, $action);
5617 $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);
5618 $reshook = $hookmanager->executeHooks(
'printObjectSubLine', $parameters, $this, $action);
5621 if (empty($reshook)) {
5622 $this->printObjectLine($action, $line,
'', $num, $i, $dateSelector, $seller, $buyer, $selected, $extrafields, $defaulttpldir);
5627 print
"<!-- end printObjectLines() -->\n";
5648 public function printObjectLine($action, $line, $var, $num, $i, $dateSelector, $seller, $buyer, $selected = 0, $extrafields =
null, $defaulttpldir =
'/core/tpl')
5652 global $disableedit, $disablemove, $disableremove;
5659 if ($action !=
'editline' || $selected != $line->id) {
5661 if (!empty($line->fk_product) && $line->fk_product > 0) {
5662 $product_static =
new Product($this->db);
5663 $product_static->fetch($line->fk_product);
5665 $product_static->ref = (
string) $line->ref;
5666 $product_static->label = !empty($line->label) ? $line->label :
"";
5668 $text = $product_static->getNomUrl(1);
5673 if (property_exists($this,
'socid') && !empty($this->socid) && !is_object($this->thirdparty)) {
5674 dol_print_error(
null,
'Error: Method printObjectLine was called on an object and object->fetch_thirdparty was not done before');
5679 $prod->fetch($line->fk_product);
5681 $outputlangs = $langs;
5683 if (empty($newlang) &&
GETPOST(
'lang_id',
'aZ09')) {
5684 $newlang =
GETPOST(
'lang_id',
'aZ09');
5686 if (
getDolGlobalString(
'PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE') && empty($newlang) && is_object($this->thirdparty)) {
5687 $newlang = $this->thirdparty->default_lang;
5689 if (!empty($newlang)) {
5691 $outputlangs->setDefaultLang($newlang);
5694 $label = (!empty(
$prod->multilangs[$outputlangs->defaultlang][
"label"])) ?
$prod->multilangs[$outputlangs->defaultlang][
"label"] : $line->product_label;
5696 $label = $line->product_label;
5699 $text .=
' - '.(!empty($line->label) ? $line->label : $label);
5700 $description .= (
getDolGlobalInt(
'PRODUIT_DESC_IN_FORM_ACCORDING_TO_DEVICE') ?
'' : (!empty($line->description) ?
dol_htmlentitiesbr($line->description) :
''));
5704 if (empty((
float) $line->subprice_ttc) && $line->qty) {
5706 if ($line->remise_percent != 100) {
5707 $line->subprice_ttc = (float)
price2num($line->total_ttc / $line->qty / (1 - $line->remise_percent / 100),
'MU');
5710 $line->subprice_ttc = (float)
price2num((!empty($line->subprice) ? $line->subprice : 0) * (1 + ((!empty($line->tva_tx) ? $line->tva_tx : 0) / 100)),
'MU');
5713 $line->pu_ttc = $line->subprice_ttc;
5720 if (isset($this->expeditions[$line->id])) {
5721 $qty_shipped = $this->expeditions[$line->id];
5723 $disableedit = ($qty_shipped > 0) && ($qty_shipped >= $line->qty);
5725 $dirtpls = array_merge(
$conf->modules_parts[
'tpl'], array($defaulttpldir));
5726 foreach ($dirtpls as $module => $reldir) {
5728 if (!empty($module)) {
5731 $tpl = DOL_DOCUMENT_ROOT.$reldir.
'/objectline_view.tpl.php';
5734 if (file_exists($tpl)) {
5735 if (empty(
$conf->file->strict_mode)) {
5736 $res = @include $tpl;
5738 $res = include $tpl;
5748 if ($this->
status == 0 && $action ==
'editline' && $selected == $line->id) {
5749 $label = (!empty($line->label) ? $line->label : (($line->fk_product > 0) ? $line->product_label :
''));
5751 $line->subprice_ttc = (float)
price2num($line->subprice * (1 + ($line->tva_tx / 100)),
'MU');
5752 $line->pu_ttc = $line->subprice_ttc;
5757 $dirtpls = array_merge(
$conf->modules_parts[
'tpl'], array($defaulttpldir));
5758 foreach ($dirtpls as $module => $reldir) {
5759 if (!empty($module)) {
5762 $tpl = DOL_DOCUMENT_ROOT.$reldir.
'/objectline_edit.tpl.php';
5765 if (empty(
$conf->file->strict_mode)) {
5766 $res = @include $tpl;
5768 $res = include $tpl;
5793 global $langs, $hookmanager, $form, $action;
5795 print
'<!-- printOriginLinesList '.get_class($this).
' -->'.
"\n";
5796 print
'<tr class="liste_titre">';
5797 print
'<td class="linecolref">'.$langs->trans(
'Ref').
'</td>';
5798 print
'<td class="linecoldescription">'.$langs->trans(
'Description').
'</td>';
5799 print
'<td class="linecolvat right">'.$langs->trans(
'VATRate').
'</td>';
5800 print
'<td class="linecoluht right">'.$langs->trans(
'PriceUHT').
'</td>';
5802 print
'<td class="linecoluht_currency right">'.$langs->trans(
'PriceUHTCurrency').
'</td>';
5804 print
'<td class="linecolqty right">'.$langs->trans(
'Qty').
'</td>';
5806 print
'<td class="linecoluseunit left">'.$langs->trans(
'Unit').
'</td>';
5808 print
'<td class="linecoldiscount right">'.$langs->trans(
'ReductionShort').
'</td>';
5809 print
'<td class="linecolht right">'.$langs->trans(
'TotalHT').
'</td>';
5810 print
'<td class="center">';
5811 print $form->showCheckAddButtons(
'checkforselect', 1);
5816 if (!empty($this->lines)) {
5817 foreach ($this->lines as $line) {
5820 if (is_object($hookmanager)) {
5821 $parameters = array(
'line' => $line,
'i' => $i,
'restrictlist' => $restrictlist,
'selectedLines' => $selectedLines);
5822 if (!empty($line->fk_parent_line)) {
5823 $parameters[
'fk_parent_line'] = $line->fk_parent_line;
5825 $reshook = $hookmanager->executeHooks(
'printOriginObjectLine', $parameters, $this, $action);
5827 if (empty($reshook)) {
5828 $this->printOriginLine($line,
'', $restrictlist,
'/core/tpl', $selectedLines);
5849 public function printOriginLine($line, $var, $restrictlist =
'', $defaulttpldir =
'/core/tpl', $selectedLines = array())
5851 global $langs,
$conf;
5854 if (!empty($line->date_start)) {
5859 if ($line->date_debut_reel) {
5863 if (!empty($line->date_end)) {
5865 $date_end = $line->date_end;
5867 $date_end = $line->date_fin_prevue;
5868 if ($line->date_fin_reel) {
5869 $date_end = $line->date_fin_reel;
5874 $this->tpl[
'id'] = $line->id;
5876 $this->tpl[
'label'] =
'';
5877 if (!empty($line->fk_parent_line)) {
5878 $this->tpl[
'label'] .=
img_picto(
'',
'rightarrow.png');
5881 if (((
int) $line->info_bits & 2) == 2) {
5883 if (property_exists($this,
'socid')) {
5884 $discount->fk_soc = $this->socid;
5885 $discount->socid = $this->socid;
5887 $this->tpl[
'label'] .= $discount->getNomUrl(0,
'discount');
5888 } elseif (!empty($line->fk_product)) {
5889 $productstatic =
new Product($this->db);
5890 $productstatic->id = $line->fk_product;
5891 $productstatic->ref = (
string) $line->ref;
5892 $productstatic->type = $line->fk_product_type;
5893 if (empty($productstatic->ref)) {
5894 $line->fetch_product();
5895 $productstatic = $line->product;
5898 $this->tpl[
'label'] .= $productstatic->getNomUrl(1);
5899 $this->tpl[
'label'] .=
' - '.(!empty($line->label) ? $line->label : $line->product_label);
5901 if ($line->product_type == 1 && (
$date_start || $date_end)) {
5905 $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"')));
5906 if (!empty($line->desc)) {
5907 $this->tpl[
'label'] .= $line->desc;
5909 $this->tpl[
'label'] .= ($line->label ?
' '.$line->label :
'');
5913 if ($line->product_type == 1 && (
$date_start || $date_end)) {
5918 if (!empty($line->desc)) {
5919 '@phan-var-force OrderLine|FactureLigne|ContratLigne|FactureFournisseurLigneRec|SupplierInvoiceLine|SupplierProposalLine $line';
5920 if ($line->desc ==
'(CREDIT_NOTE)') {
5922 $discount->fetch($line->fk_remise_except);
5923 $this->tpl[
'description'] = $langs->transnoentities(
"DiscountFromCreditNote", $discount->getNomUrl(0));
5924 } elseif ($line->desc ==
'(DEPOSIT)') {
5926 $discount->fetch($line->fk_remise_except);
5927 $this->tpl[
'description'] = $langs->transnoentities(
"DiscountFromDeposit", $discount->getNomUrl(0));
5928 } elseif ($line->desc ==
'(EXCESS RECEIVED)') {
5930 $discount->fetch($line->fk_remise_except);
5931 $this->tpl[
'description'] = $langs->transnoentities(
"DiscountFromExcessReceived", $discount->getNomUrl(0));
5932 } elseif ($line->desc ==
'(EXCESS PAID)') {
5934 $discount->fetch($line->fk_remise_except);
5935 $this->tpl[
'description'] = $langs->transnoentities(
"DiscountFromExcessPaid", $discount->getNomUrl(0));
5937 $this->tpl[
'description'] =
dol_trunc($line->desc, 60);
5940 $this->tpl[
'description'] =
' ';
5944 $this->tpl[
'vat_rate'] =
vatrate($line->tva_tx,
true);
5945 $this->tpl[
'vat_rate'] .= (((int) $line->info_bits & 1) == 1) ?
'*' :
'';
5946 if (!empty($line->vat_src_code) && !preg_match(
'/\(/', $this->tpl[
'vat_rate'])) {
5947 $this->tpl[
'vat_rate'] .=
' ('.$line->vat_src_code.
')';
5950 $this->tpl[
'price'] =
price($line->subprice);
5951 $this->tpl[
'total_ht'] =
price($line->total_ht);
5952 $this->tpl[
'multicurrency_price'] =
price($line->multicurrency_subprice);
5953 $this->tpl[
'qty'] = (((int) $line->info_bits & 2) != 2) ? $line->qty :
' ';
5955 $this->tpl[
'unit'] = $line->getLabelOfUnit(
'long', $langs);
5956 $this->tpl[
'unit_short'] = $line->getLabelOfUnit(
'short', $langs);
5959 $this->tpl[
'remise_percent'] = (((int) $line->info_bits & 2) != 2) ?
vatrate((
string) $line->remise_percent,
true) :
' ';
5962 $this->tpl[
'strike'] = 0;
5964 $this->tpl[
'strike'] = 1;
5965 } elseif (defined(
'SUBTOTALS_SPECIAL_CODE') && $line->special_code == SUBTOTALS_SPECIAL_CODE) {
5966 $this->tpl[
'strike'] = 1;
5971 $dirtpls = array_merge(
$conf->modules_parts[
'tpl'], array($defaulttpldir));
5972 foreach ($dirtpls as $module => $reldir) {
5973 if (!empty($module)) {
5976 $tpl = DOL_DOCUMENT_ROOT.$reldir.
'/originproductline.tpl.php';
5979 if (empty(
$conf->file->strict_mode)) {
5980 $res = @include $tpl;
5982 $res = include $tpl;
6009 $sql =
"INSERT INTO ".$this->db->prefix().
"element_resources (";
6010 $sql .=
"resource_id";
6011 $sql .=
", resource_type";
6012 $sql .=
", element_id";
6013 $sql .=
", element_type";
6015 $sql .=
", mandatory";
6016 $sql .=
") VALUES (";
6017 $sql .= ((int) $resource_id);
6018 $sql .=
", '".$this->db->escape($resource_type).
"'";
6019 $sql .=
", '".$this->db->escape((
string) $this->
id).
"'";
6020 $sql .=
", '".$this->db->escape($this->element).
"'";
6021 $sql .=
", '".$this->db->escape((
string) $busy).
"'";
6022 $sql .=
", '".$this->db->escape((
string) $mandatory).
"'";
6025 dol_syslog(get_class($this).
"::add_element_resource", LOG_DEBUG);
6026 if ($this->db->query($sql)) {
6028 $result = $this->call_trigger(strtoupper($this->TRIGGER_PREFIX).
'_ADD_RESOURCE', $user);
6030 $this->db->rollback();
6034 $this->db->commit();
6037 $this->error = $this->db->lasterror();
6038 $this->db->rollback();
6059 $sql =
"DELETE FROM ".$this->db->prefix().
"element_resources";
6060 $sql .=
" WHERE rowid = ".((int) $rowid);
6062 dol_syslog(get_class($this).
"::delete_resource", LOG_DEBUG);
6064 $resql = $this->db->query($sql);
6066 $this->error = $this->db->lasterror();
6067 $this->db->rollback();
6071 $result = $this->call_trigger(strtoupper($this->TRIGGER_PREFIX).
'_DELETE_RESOURCE', $user);
6073 $this->db->rollback();
6077 $this->db->commit();
6091 if (isset($this->lines) && is_array($this->lines)) {
6092 $nboflines = count($this->lines);
6093 for ($i = 0; $i < $nboflines; $i++) {
6094 if (is_object($this->lines[$i])) {
6095 $this->lines[$i] = clone $this->lines[$i];
6114 protected function commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams =
null)
6116 global
$conf, $langs, $hookmanager, $action;
6118 $srctemplatepath =
'';
6120 $parameters = array(
'modelspath' => $modelspath,
'modele' => $modele,
'outputlangs' => $outputlangs,
'hidedetails' => $hidedetails,
'hidedesc' => $hidedesc,
'hideref' => $hideref,
'moreparams' => $moreparams);
6121 $reshook = $hookmanager->executeHooks(
'commonGenerateDocument', $parameters, $this, $action);
6123 if (!empty($reshook)) {
6127 dol_syslog(
"commonGenerateDocument modele=".$modele.
" outputlangs->defaultlang=".(is_object($outputlangs) ? $outputlangs->defaultlang :
'null'));
6129 if (empty($modele)) {
6130 $this->error =
'BadValueForParameterModele';
6135 $err = error_reporting();
6137 @set_time_limit(120);
6138 error_reporting($err);
6141 $tmp = explode(
':', $modele, 2);
6142 $saved_model = $modele;
6143 if (!empty($tmp[1])) {
6145 $srctemplatepath = $tmp[1];
6152 $dirmodels = array(
'/');
6153 if (is_array(
$conf->modules_parts[
'models'])) {
6154 $dirmodels = array_merge($dirmodels,
$conf->modules_parts[
'models']);
6156 foreach ($dirmodels as $reldir) {
6157 foreach (array(
'doc',
'pdf') as $prefix) {
6158 if (in_array(get_class($this), array(
'Adherent'))) {
6160 $file = $prefix.
"_".$modele.
".class.php";
6163 $file = $prefix.
"_".$modele.
".modules.php";
6170 if (file_exists($file)) {
6172 $classname = $prefix.
'_'.$modele;
6181 if ($filefound ===
'' || $classname ===
'') {
6182 $this->error = $langs->trans(
"Error").
' Failed to load doc generator with modelpaths='.$modelspath.
' - modele='.$modele;
6183 $this->errors[] = $this->error;
6194 require_once $filefound;
6196 $obj =
new $classname($this->db);
6208 '@phan-var-force ModelePDFMember $obj';
6212 if ($obj->type ==
'odt' && empty($srctemplatepath)) {
6213 $varfortemplatedir = $obj->scandir;
6217 $listoffiles = array();
6220 $listofdir = explode(
',', $dirtoscan);
6221 foreach ($listofdir as $key => $tmpdir) {
6222 $tmpdir = trim($tmpdir);
6223 $tmpdir = preg_replace(
'/DOL_DATA_ROOT/', DOL_DATA_ROOT, $tmpdir);
6225 unset($listofdir[$key]);
6228 if (is_dir($tmpdir)) {
6229 $tmpfiles =
dol_dir_list($tmpdir,
'files', 0,
'\.od(s|t)$',
'',
'name', SORT_ASC, 0);
6230 if (count($tmpfiles)) {
6231 $listoffiles = array_merge($listoffiles, $tmpfiles);
6236 if (count($listoffiles)) {
6237 foreach ($listoffiles as $record) {
6238 $srctemplatepath = $record[
'fullname'];
6244 if (empty($srctemplatepath)) {
6245 $this->error =
'ErrorGenerationAskedForOdtTemplateWithSrcFileNotDefined';
6250 if ($obj->type ==
'odt' && !empty($srctemplatepath)) {
6252 dol_syslog(
"Failed to locate template file ".$srctemplatepath, LOG_WARNING);
6253 $this->error =
'ErrorGenerationAskedForOdtTemplateWithSrcFileNotFound';
6260 $sav_charset_output = empty($outputlangs->charset_output) ?
'' : $outputlangs->charset_output;
6263 $this->model_pdf = $saved_model;
6268 $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath,
'member', 1,
'tmp_cards');
6270 $resultwritefile = -1;
6271 dol_syslog(
"Error generating document - Provided ".get_class($this).
" to ".get_class($obj).
"::write_file()", LOG_ERR);
6275 if ($this instanceof
Don) {
6276 $resultwritefile = $obj->write_file($this, $outputlangs );
6278 $resultwritefile = -1;
6279 dol_syslog(
"Error generating document - Provided ".get_class($this).
" to Don::write_file()", LOG_ERR);
6283 '@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';
6284 $this->context[
'moreparams'] = $moreparams;
6285 $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, $hidedetails, $hidedesc, $hideref);
6287 }
catch (\Throwable $e) {
6288 $resultwritefile = -1;
6289 $this->error = $e->getMessage();
6290 dol_syslog(
"Exception in write_file() for ".get_class($this).
": ".$e->getMessage(), LOG_ERR);
6295 if ($resultwritefile > 0) {
6296 $outputlangs->charset_output = $sav_charset_output;
6299 require_once DOL_DOCUMENT_ROOT.
'/core/lib/files.lib.php';
6303 if (!empty($obj->result[
'fullpath'])) {
6304 $destfull = $obj->result[
'fullpath'];
6307 $update_main_doc_field = 0;
6308 if (!empty($obj->update_main_doc_field)) {
6309 $update_main_doc_field = 1;
6315 $this->indexFile($destfull, $update_main_doc_field);
6318 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);
6324 $this->warnings = $obj->warnings;
6328 $outputlangs->charset_output = $sav_charset_output;
6329 if (empty($this->error)) {
6330 $this->error = $obj->error;
6332 if (empty($this->errors)) {
6333 $this->errors = $obj->errors;
6335 $this->warnings = $obj->warnings;
6336 dol_syslog(
"Error generating document for ".__CLASS__.
". Error: ".$this->error, LOG_ERR);
6350 public function indexFile($destfull, $update_main_doc_field)
6352 global
$conf, $user;
6354 $upload_dir = dirname($destfull);
6355 $destfile = basename($destfull);
6356 $rel_dir = preg_replace(
'/^'.preg_quote(DOL_DATA_ROOT,
'/').
'/',
'', $upload_dir);
6358 if (!preg_match(
'/[\\/]temp[\\/]|[\\/]thumbs|\.meta$/', $rel_dir)) {
6359 $filename = basename($destfile);
6360 $rel_dir = preg_replace(
'/[\\/]$/',
'', $rel_dir);
6361 $rel_dir = preg_replace(
'/^[\\/]/',
'', $rel_dir);
6363 include_once DOL_DOCUMENT_ROOT.
'/ecm/class/ecmfiles.class.php';
6364 $ecmfile =
new EcmFiles($this->db);
6365 $result = $ecmfile->fetch(0,
'', ($rel_dir ? $rel_dir.
'/' :
'').$filename);
6368 $setsharekey =
false;
6370 !empty($this->TRIGGER_PREFIX)
6373 $setsharekey =
true;
6376 if ($this->element ==
'propal' || $this->element ==
'proposal') {
6378 $setsharekey =
true;
6381 $setsharekey =
true;
6384 if ($this->element ==
'facture' &&
getDolGlobalInt(
"INVOICE_ALLOW_EXTERNAL_DOWNLOAD")) {
6385 $setsharekey =
true;
6387 if ($this->element ==
'bank_account' &&
getDolGlobalInt(
"BANK_ACCOUNT_ALLOW_EXTERNAL_DOWNLOAD")) {
6388 $setsharekey =
true;
6390 if ($this->element ==
'contrat' &&
getDolGlobalInt(
"CONTRACT_ALLOW_EXTERNAL_DOWNLOAD")) {
6391 $setsharekey =
true;
6393 if ($this->element ==
'supplier_proposal' &&
getDolGlobalInt(
"SUPPLIER_PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD")) {
6394 $setsharekey =
true;
6396 if ($this->element ==
'order_supplier' &&
getDolGlobalInt(
"SUPPLIER_ORDER_ALLOW_EXTERNAL_DOWNLOAD")) {
6397 $setsharekey =
true;
6399 if ($this->element ==
'invoice_supplier' &&
getDolGlobalInt(
"SUPPLIER_INVOICE_ALLOW_EXTERNAL_DOWNLOAD")) {
6400 $setsharekey =
true;
6402 if ($this->element ==
'societe_rib' &&
getDolGlobalInt(
"SOCIETE_RIB_ALLOW_ONLINESIGN")) {
6403 $setsharekey =
true;
6407 if (empty($ecmfile->share)) {
6408 require_once DOL_DOCUMENT_ROOT.
'/core/lib/security2.lib.php';
6415 $ecmfile->fullpath_orig =
'';
6416 $ecmfile->gen_or_uploaded =
'generated';
6417 $ecmfile->description =
'';
6418 $ecmfile->keywords =
'';
6419 $ecmfile->src_object_type = $this->table_element;
6421 $result = $ecmfile->update($user);
6427 $ecmfile->entity =
$conf->entity;
6428 $ecmfile->filepath = $rel_dir;
6429 $ecmfile->filename = $filename;
6431 $ecmfile->fullpath_orig =
'';
6432 $ecmfile->gen_or_uploaded =
'generated';
6433 $ecmfile->description =
'';
6434 $ecmfile->keywords =
'';
6435 $ecmfile->src_object_type = $this->table_element;
6438 $result = $ecmfile->create($user);
6450 if ($update_main_doc_field && !empty($this->table_element)) {
6451 $sql =
"UPDATE ".$this->db->prefix().$this->table_element.
" SET last_main_doc = '".$this->db->escape($ecmfile->filepath.
"/".$ecmfile->filename).
"'";
6452 $sql .=
" WHERE rowid = ".((int) $this->
id);
6454 $resql = $this->db->query($sql);
6459 $this->last_main_doc = $ecmfile->filepath.
'/'.$ecmfile->filename;
6479 if (file_exists($file_osencoded)) {
6480 require_once DOL_DOCUMENT_ROOT.
'/core/lib/images.lib.php';
6483 $maxwidthsmall = $tmparraysize[
'maxwidthsmall'];
6484 $maxheightsmall = $tmparraysize[
'maxheightsmall'];
6485 $maxwidthmini = $tmparraysize[
'maxwidthmini'];
6486 $maxheightmini = $tmparraysize[
'maxheightmini'];
6491 vignette($file_osencoded, $maxwidthsmall, $maxheightsmall,
'_small', $quality);
6495 vignette($file_osencoded, $maxwidthmini, $maxheightmini,
'_mini', $quality);
6508 $imgThumbName = getImageFileNameForSize($file,
'_small');
6510 $imgThumbName = getImageFileNameForSize($file,
'_mini');
6542 if (GETPOSTISSET($fieldname)) {
6543 return GETPOST($fieldname, $type, 3);
6546 if (isset($alternatevalue)) {
6547 return $alternatevalue;
6550 $newelement = $this->element;
6551 if ($newelement ==
'facture') {
6552 $newelement =
'invoice';
6554 if ($newelement ==
'commande') {
6555 $newelement =
'order';
6557 if (empty($newelement)) {
6558 dol_syslog(
"Ask a default value using common method getDefaultCreateValueForField on an object with no property ->element defined. Return empty string.", LOG_WARNING);
6562 $keyforfieldname = strtoupper($newelement.
'_DEFAULT_'.$fieldname);
6589 if (!$this->element) {
6592 if (!($this->
id > 0)) {
6595 if (is_array($this->array_languages)) {
6599 $this->array_languages = array();
6601 $element = $this->element;
6602 if ($element ==
'categorie') {
6603 $element =
'categories';
6607 $sql =
"SELECT rowid, property, lang , value";
6608 $sql .=
" FROM ".$this->db->prefix().
"object_lang";
6609 $sql .=
" WHERE type_object = '".$this->db->escape($element).
"'";
6610 $sql .=
" AND fk_object = ".((int) $this->
id);
6612 $resql = $this->db->query($sql);
6614 $numrows = $this->db->num_rows($resql);
6617 while ($i < $numrows) {
6618 $obj = $this->db->fetch_object($resql);
6619 $key = $obj->property;
6620 $value = $obj->value;
6621 $codelang = $obj->lang;
6622 $type = $this->fields[$key][
'type'];
6625 if (preg_match(
'/date/', $type)) {
6626 $this->array_languages[$key][$codelang] = $this->db->jdate($value);
6628 $this->array_languages[$key][$codelang] = $value;
6635 $this->db->free($resql);
6658 foreach ($_POST as $postfieldkey => $postfieldvalue) {
6659 $tmparray = explode(
'-', $postfieldkey);
6660 if ($tmparray[0] !=
'field') {
6664 $element = $tmparray[1];
6665 $key = $tmparray[2];
6666 $codelang = $tmparray[3];
6669 if (!empty($onlykey) && $key != $onlykey) {
6672 if ($element != $this->element) {
6676 $key_type = $this->fields[$key][
'type'];
6679 if (isset($this->fields[$key][
'enabled'])) {
6680 $enabled = (int)
dol_eval((
string) $this->fields[$key][
'enabled'], 1, 1,
'1');
6687 if (empty($enabled)) {
6692 if (in_array($key_type, array(
'date'))) {
6696 } elseif (in_array($key_type, array(
'datetime'))) {
6700 } elseif (in_array($key_type, array(
'checkbox',
'chkbxlst'))) {
6701 $value_arr =
GETPOST($postfieldkey,
'array');
6702 if (!empty($value_arr)) {
6703 $value_key = implode(
',', $value_arr);
6707 } elseif (in_array($key_type, array(
'price',
'double'))) {
6708 $value_arr =
GETPOST($postfieldkey,
'alpha');
6711 $value_key =
GETPOST($postfieldkey);
6712 if (in_array($key_type, array(
'link')) && $value_key ==
'-1') {
6717 $this->array_languages[$key][$codelang] = $value_key;
6742 $savDisableCompute =
$conf->disable_compute;
6743 $conf->disable_compute = 1;
6745 $ret = $this->fetch(
$id);
6747 $conf->disable_compute = $savDisableCompute;
6765 global
$conf, $extrafields;
6767 if (empty($rowid)) {
6770 if (empty($rowid) && isset($this->rowid)) {
6771 $rowid = $this->rowid;
6775 if (!$this->table_element) {
6778 $this->array_options = array();
6780 if (!is_array($optionsArray)) {
6782 if (!isset($extrafields) || !is_object($extrafields)) {
6783 require_once DOL_DOCUMENT_ROOT.
'/core/class/extrafields.class.php';
6788 if (empty($extrafields->attributes[$this->table_element][
'loaded'])) {
6789 $extrafields->fetch_name_optionals_label($this->table_element);
6791 $optionsArray = (!empty($extrafields->attributes[$this->table_element][
'label']) ? $extrafields->attributes[$this->table_element][
'label'] :
null);
6793 global $extrafields;
6794 dol_syslog(
"Warning: fetch_optionals was called with param optionsArray defined when you should pass null now", LOG_WARNING);
6797 $table_element = $this->table_element;
6798 if ($table_element ==
'categorie') {
6799 $table_element =
'categories';
6803 if (is_array($optionsArray) && count($optionsArray) > 0) {
6804 $sql =
"SELECT rowid";
6805 foreach ($optionsArray as $name => $label) {
6806 if (empty($extrafields->attributes[$this->table_element][
'type'][$name]) || (!in_array($extrafields->attributes[$this->table_element][
'type'][$name], [
'separate',
'point',
'multipts',
'linestrg',
'polygon']))) {
6807 $sql .=
", ".$this->db->sanitize($name);
6810 if (!empty($extrafields->attributes[$this->table_element][
'type'][$name]) && in_array($extrafields->attributes[$this->table_element][
'type'][$name], array(
'point',
'multipts',
'linestrg',
'polygon'))) {
6812 $sql .=
", ST_AsWKT(".$name.
") as ".$this->db->sanitize($name);
6815 $sql .=
" FROM ".$this->db->prefix().$table_element.
"_extrafields";
6816 $sql .=
" WHERE fk_object = ".((int) $rowid);
6819 $resql = $this->db->query($sql);
6821 $numrows = $this->db->num_rows($resql);
6823 $tab = $this->db->fetch_array($resql);
6824 foreach ($tab as $key => $value) {
6826 if ($key !=
'rowid' && $key !=
'tms' && $key !=
'fk_member' && !is_int($key)) {
6828 if (!empty($extrafields->attributes[$this->table_element]) && in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'date',
'datetime'))) {
6830 $this->array_options[
"options_".$key] = $this->db->jdate($value);
6832 $this->array_options[
"options_".$key] = $value;
6837 if (!empty($extrafields->attributes[$this->table_element][
'type'][$key]) && $extrafields->attributes[$this->table_element][
'type'][$key] ==
'password') {
6838 if (!empty($value) && preg_match(
'/^dolcrypt:/', $value)) {
6839 $this->array_options[
"options_".$key] =
dolDecrypt($value);
6848 if (is_array($extrafields->attributes[$this->table_element][
'label'])) {
6849 foreach ($extrafields->attributes[$this->table_element][
'label'] as $key => $val) {
6850 $this->array_options[
'options_' . $key] =
null;
6857 if (is_array($extrafields->attributes[$this->table_element][
'label'])) {
6858 foreach ($extrafields->attributes[$this->table_element][
'label'] as $key => $val) {
6859 if (!empty($extrafields->attributes[$this->table_element]) && !empty($extrafields->attributes[$this->table_element][
'computed'][$key])) {
6861 if (empty(
$conf->disable_compute)) {
6864 global $objectoffield;
6865 $this->array_options[
'options_' . $key] =
dol_eval((
string) $extrafields->attributes[$this->table_element][
'computed'][$key], 1, 0,
'2');
6871 $this->db->free($resql);
6879 $this->errors[] = $this->db->lasterror();
6900 $table_element = $this->table_element;
6901 if ($table_element ==
'categorie') {
6902 $table_element =
'categories';
6905 dol_syslog(get_class($this).
"::deleteExtraFields delete", LOG_DEBUG);
6907 $sql_del =
"DELETE FROM ".$this->db->prefix().$table_element.
"_extrafields WHERE fk_object = ".((int) $this->
id);
6909 $resql = $this->db->query($sql_del);
6911 $this->error = $this->db->lasterror();
6912 $this->db->rollback();
6915 $this->db->commit();
6932 global $langs, $extrafields, $user;
6934 if (
getDolGlobalString(
'MAIN_EXTRAFIELDS_DISABLED') || empty($this->array_options)) {
6938 if (empty($userused)) {
6945 $langs->load(
'admin');
6946 if (!isset($extrafields) || !is_object($extrafields)) {
6947 require_once DOL_DOCUMENT_ROOT.
'/core/class/extrafields.class.php';
6950 $target_extrafields = $extrafields->fetch_name_optionals_label($this->table_element);
6953 $new_array_options = array();
6954 foreach ($this->array_options as $key => $value) {
6955 if (in_array(substr($key, 8), array_keys($target_extrafields))) {
6956 $new_array_options[$key] = $value;
6957 } elseif (in_array($key, array_keys($target_extrafields))) {
6958 $new_array_options[
'options_'.$key] = $value;
6962 foreach ($new_array_options as $key => $value) {
6963 $attributeKey = substr($key, 8);
6964 $attributeType = $extrafields->attributes[$this->table_element][
'type'][$attributeKey];
6965 $attributeLabel = $langs->transnoentities($extrafields->attributes[$this->table_element][
'label'][$attributeKey]);
6966 $attributeParam = $extrafields->attributes[$this->table_element][
'param'][$attributeKey];
6967 $attributeRequired = $extrafields->attributes[$this->table_element][
'required'][$attributeKey];
6968 $attributeUnique = $extrafields->attributes[$this->table_element][
'unique'][$attributeKey];
6969 $attrfieldcomputed = $extrafields->attributes[$this->table_element][
'computed'][$attributeKey];
6970 $attributeEmptyOnClone = $extrafields->attributes[$this->table_element][
'emptyonclone'][$attributeKey];
6982 if (!empty($this->context[
'createfromclone']) && $this->context[
'createfromclone'] ==
'createfromclone' && (!empty($attributeUnique) || !empty($attributeEmptyOnClone))) {
6983 $new_array_options[$key] =
null;
6989 if (!empty($this->context[
'createproductcombination']) && $this->context[
'createproductcombination'] ==
'createproductcombination' && !empty($attributeUnique)) {
6990 $new_array_options[$key] =
null;
6995 if ($attributeRequired) {
6996 $v = $this->array_options[$key];
6998 $langs->load(
"errors");
6999 dol_syslog(
"Mandatory field '".$key.
"' is empty during create and set to required into definition of extrafields");
7000 $this->errors[] = $langs->trans(
'ErrorFieldRequired', $attributeLabel);
7005 if (!empty($attrfieldcomputed)) {
7007 $value =
dol_eval((
string) $attrfieldcomputed, 1, 0,
'2');
7008 dol_syslog($langs->trans(
"Extrafieldcomputed").
" on ".$attributeLabel.
"(".$value.
")", LOG_DEBUG);
7009 $new_array_options[$key] = $value;
7011 $new_array_options[$key] =
null;
7016 switch ($attributeType) {
7020 if (!is_numeric($value) && $value !=
'') {
7021 $this->errors[] = $langs->trans(
"ExtraFieldHasWrongValue", $attributeLabel);
7023 } elseif ($value ===
'') {
7024 $new_array_options[$key] =
null;
7028 if ($value ===
'' || $value ===
false || $value ===
null) {
7029 $new_array_options[$key] =
null;
7035 if (!is_numeric($value) && $value !=
'') {
7036 dol_syslog($langs->trans(
"ExtraFieldHasWrongValue").
" for ".$attributeLabel.
"(".$value.
"is not '".$attributeType.
"')", LOG_DEBUG);
7037 $this->errors[] = $langs->trans(
"ExtraFieldHasWrongValue", $attributeLabel);
7039 } elseif ($value ==
'') {
7043 $new_array_options[$key] = $value;
7053 if ($this->array_options[$key] !=
'' && is_array($extrafields->attributes[$this->table_element][
'param'][$attributeKey][
'options'])) {
7055 $tmparrays = array_keys($extrafields->attributes[$this->table_element][
'param'][$attributeKey][
'options']);
7056 $algo = reset($tmparrays);
7061 if (is_object($this->oldcopy)) {
7063 if (isset($this->oldcopy->array_options[$key]) && $this->array_options[$key] == $this->oldcopy->array_options[$key]) {
7065 if ($algo ==
'dolcrypt') {
7066 if (!preg_match(
'/^dolcrypt:/', $this->array_options[$key])) {
7067 $new_array_options[$key] =
dolEncrypt($this->array_options[$key]);
7069 $new_array_options[$key] = $this->array_options[$key];
7072 $new_array_options[$key] = $this->array_options[$key];
7076 if ($algo ==
'dolcrypt') {
7077 if (!preg_match(
'/^dolcrypt:/', $this->array_options[$key])) {
7078 $new_array_options[$key] =
dolEncrypt($this->array_options[$key]);
7080 $new_array_options[$key] = $this->array_options[$key];
7083 $new_array_options[$key] =
dol_hash($this->array_options[$key], $algo);
7089 if ($algo ==
'dolcrypt' && !preg_match(
'/^dolcrypt:/', $this->array_options[$key])) {
7090 $new_array_options[$key] =
dolEncrypt($this->array_options[$key]);
7092 $new_array_options[$key] = $this->array_options[$key];
7097 $new_array_options[$key] = $this->array_options[$key];
7100 $new_array_options[$key] = $this->array_options[$key];
7106 if (!is_numeric($this->array_options[$key]) || $this->array_options[$key] != intval($this->array_options[$key])) {
7107 $this->array_options[$key] = strtotime($this->array_options[$key]);
7109 $new_array_options[$key] = $this->db->idate($this->array_options[$key]);
7113 if (!is_numeric($this->array_options[$key]) || $this->array_options[$key] != intval($this->array_options[$key])) {
7114 $this->array_options[$key] = strtotime($this->array_options[$key]);
7116 $new_array_options[$key] = $this->db->idate($this->array_options[$key],
'gmt');
7119 $param_list = array_keys($attributeParam[
'options']);
7122 $InfoFieldList = explode(
":", $param_list[0]);
7124 if ($InfoFieldList[0] && class_exists($InfoFieldList[0])) {
7125 if ($value ==
'-1') {
7126 $new_array_options[$key] =
'';
7129 '@phan-var-force CommonObject $object';
7133 $sqlFetchObject =
"SELECT rowid FROM ".$this->db->prefix().$object->table_element;
7134 if (is_numeric($value)) {
7135 $sqlFetchObject .=
" WHERE rowid = " . (int) $value;
7137 $sqlFetchObject .=
" WHERE ref = '" . $this->db->escape($value) .
"'";
7140 $obj = $this->db->getRow($sqlFetchObject);
7142 if ($obj !==
false) {
7143 $objectId = $obj->rowid;
7150 $new_array_options[$key] = $objectId;
7152 $this->error =
"Id/Ref '".$value.
"' for object '".
$object->element.
"' not found";
7157 dol_syslog(
'Error bad setup of extrafield', LOG_WARNING);
7162 if (is_array($this->array_options[$key])) {
7163 $new_array_options[$key] = implode(
',', $this->array_options[$key]);
7165 $new_array_options[$key] = $this->array_options[$key];
7172 $sqlColumnValues = [
'fk_object' => (int) $this->
id];
7174 foreach ($new_array_options as $key => $newValue) {
7175 $attributeKey = substr($key, 8);
7176 $attributeType = $extrafields->attributes[$this->table_element][
'type'][$attributeKey];
7177 if ($attributeType ===
'separate') {
7181 $geoDataType = ExtraFields::$geoDataTypes[$attributeType] ??
null;
7183 if (! $geoDataType) {
7185 if ($newValue !=
'') {
7186 $sqlColumnValues[$attributeKey] =
"'".$this->db->escape($newValue).
"'";
7188 $sqlColumnValues[$attributeKey] =
'null';
7192 if (empty($newValue)) {
7193 $sqlColumnValues[$attributeKey] =
'null';
7196 if (preg_match(
'/error/i', $newValue)) {
7197 dol_syslog(
'Bad syntax string for '.$geoDataType[
'shortname'].
' '.$newValue.
' to generate SQL request', LOG_WARNING);
7198 $sqlColumnValues[$attributeKey] =
'null';
7207 $sqlColumnValues[$attributeKey] = $geoDataType[
'ST_Function'].
"('".$this->db->escape($newValue).
"')";
7212 $table_element = $this->table_element;
7213 if ($table_element ==
'categorie') {
7214 $table_element =
'categories';
7216 $extrafieldsTable = $this->db->prefix() . $table_element .
'_extrafields';
7218 dol_syslog(get_class($this).
"::insertExtraFields update or insert record line", LOG_DEBUG);
7220 $linealreadyfound = 0;
7221 $sql =
"SELECT COUNT(rowid) as nb FROM ".$this->db->prefix().$table_element.
"_extrafields WHERE fk_object = ".((int) $this->
id);
7222 $resql = $this->db->query($sql);
7224 $tmpobj = $this->db->fetch_object($resql);
7226 $linealreadyfound = $tmpobj->nb;
7231 if ($linealreadyfound) {
7232 array_shift($sqlColumnValues);
7233 $sqlColumnValueString = implode(
7239 array_map(
function ($key) use ($sqlColumnValues) {
7240 return "{$key} = {$sqlColumnValues[$key]}";
7241 }, array_keys($sqlColumnValues))
7243 $sql =
"UPDATE {$extrafieldsTable} SET {$sqlColumnValueString} WHERE fk_object = ".((int) $this->
id);
7246 $extrafieldsRequiredOnOtherEntities = $extrafields->attributes[$this->table_element][
'mandatoryfieldsofotherentities'] ?? array();
7247 foreach ($extrafieldsRequiredOnOtherEntities as $key => $extrafieldType) {
7248 if (isset($sqlColumnValues[$key])) {
7253 $sqlColumnValues[$key] =
"''";
7254 if (in_array($extrafieldType, array(
'int',
'double',
'price'))) {
7255 $sqlColumnValues[$key] = 0;
7258 $sqlColumns = implode(
',', array_keys($sqlColumnValues));
7259 $sqlValues = implode(
',', array_values($sqlColumnValues));
7260 $sql =
"INSERT INTO {$extrafieldsTable} ({$sqlColumns}) VALUES ({$sqlValues})";
7263 $resql = $this->db->query($sql);
7265 $this->error = $this->db->lasterror();
7270 if (!$error && !empty($this->fields[
'fk_user_modif'])) {
7271 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
7272 $sql .=
" SET fk_user_modif = ".(int) $user->id;
7273 $sql .=
" WHERE ".(empty($this->table_rowid) ?
'rowid' : $this->db->sanitize($this->table_rowid)).
" = ".((
int)
$this->id);
7274 $this->db->query($sql);
7277 if (!$error && $trigger) {
7279 $this->context = array(
'extrafieldaddupdate' => 1);
7280 $result = $this->call_trigger($trigger, $userused);
7288 $this->db->rollback();
7291 $this->db->commit();
7309 global $langs, $user;
7311 if (empty($userused)) {
7321 if (is_array($this->array_languages)) {
7322 $new_array_languages = $this->array_languages;
7324 foreach ($new_array_languages as $key => $value) {
7325 $attributeKey = $key;
7326 $attributeType = $this->fields[$attributeKey][
'type'];
7327 $attributeLabel = $this->fields[$attributeKey][
'label'];
7332 switch ($attributeType) {
7334 if (is_array($value) || (!is_numeric($value) && $value !=
'')) {
7335 $this->errors[] = $langs->trans(
"ExtraLanguageHasWrongValue", $attributeLabel);
7337 } elseif ($value ==
'') {
7338 $new_array_languages[$key] =
null;
7343 if (!is_numeric($value) && $value !=
'') {
7344 dol_syslog($langs->trans(
"ExtraLanguageHasWrongValue").
" on ".$attributeLabel.
"(".$value.
"is not '".$attributeType.
"')", LOG_DEBUG);
7345 $this->errors[] = $langs->trans(
"ExtraLanguageHasWrongValue", $attributeLabel);
7347 } elseif ($value ==
'') {
7348 $new_array_languages[$key] =
null;
7350 $new_array_languages[$key] = $value;
7364 $table_element = $this->table_element;
7365 if ($table_element ==
'categorie') {
7366 $table_element =
'categories';
7369 dol_syslog(get_class($this).
"::insertExtraLanguages delete then insert", LOG_DEBUG);
7371 foreach ($new_array_languages as $key => $langcodearray) {
7372 foreach ($langcodearray as $langcode => $value) {
7373 $sql_del =
"DELETE FROM ".$this->db->prefix().
"object_lang";
7374 $sql_del .=
" WHERE fk_object = ".((int) $this->
id).
" AND property = '".$this->db->escape($key).
"' AND type_object = '".$this->db->escape($table_element).
"'";
7375 $sql_del .=
" AND lang = '".$this->db->escape($langcode).
"'";
7376 $this->db->query($sql_del);
7378 if ($value !==
'') {
7379 $sql =
"INSERT INTO ".$this->db->prefix().
"object_lang (fk_object, property, type_object, lang, value";
7380 $sql .=
") VALUES (".$this->id.
", '".$this->db->escape($key).
"', '".$this->db->escape($table_element).
"', '".$this->db->escape($langcode).
"', '".$this->db->escape($value).
"'";
7383 $resql = $this->db->query($sql);
7385 $this->error = $this->db->lasterror();
7393 if (!$error && $trigger) {
7395 $this->context = array(
'extralanguagesaddupdate' => 1);
7396 $result = $this->call_trigger($trigger, $userused);
7404 $this->db->rollback();
7407 $this->db->commit();
7427 global $langs, $user, $extrafields, $hookmanager;
7433 if (empty($userused)) {
7439 if (!empty($this->array_options) && isset($this->array_options[
"options_".$key])) {
7441 $langs->load(
'admin');
7442 if (!isset($extrafields) || !is_object($extrafields)) {
7443 require_once DOL_DOCUMENT_ROOT.
'/core/class/extrafields.class.php';
7446 $extrafields->fetch_name_optionals_label($this->table_element);
7448 $value = $this->array_options[
"options_".$key];
7450 $attributeKey = $key;
7451 $attributeType = $extrafields->attributes[$this->table_element][
'type'][$attributeKey];
7452 $attributeLabel = $extrafields->attributes[$this->table_element][
'label'][$attributeKey];
7453 $attributeParam = $extrafields->attributes[$this->table_element][
'param'][$attributeKey];
7454 $attributeRequired = $extrafields->attributes[$this->table_element][
'required'][$attributeKey];
7455 $attributeUnique = $extrafields->attributes[$this->table_element][
'unique'][$attributeKey];
7456 $attrfieldcomputed = $extrafields->attributes[$this->table_element][
'computed'][$attributeKey];
7460 if ($attributeRequired) {
7461 $mandatorypb =
false;
7462 if ($attributeType ==
'link' && $this->array_options[
"options_".$key] ==
'-1') {
7463 $mandatorypb =
true;
7465 if ($this->array_options[
"options_".$key] ===
'') {
7466 $mandatorypb =
true;
7469 $langs->load(
"errors");
7470 dol_syslog(
"Mandatory field 'options_".$key.
"' is empty during update and set to required into definition of extrafields");
7471 $this->errors[] = $langs->trans(
'ErrorFieldRequired', $attributeLabel);
7477 $new_array_options = $this->array_options;
7481 if (!empty($attrfieldcomputed)) {
7483 $value =
dol_eval((
string) $attrfieldcomputed, 1, 0,
'2');
7484 dol_syslog($langs->trans(
"Extrafieldcomputed").
" on ".$attributeLabel.
"(".$value.
")", LOG_DEBUG);
7486 $new_array_options[
"options_".$key] = $value;
7488 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7490 $new_array_options[
"options_".$key] =
null;
7492 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7496 switch ($attributeType) {
7498 if (!is_numeric($value) && $value !=
'') {
7499 $this->errors[] = $langs->trans(
"ExtraFieldHasWrongValue", $attributeLabel);
7501 } elseif ($value ===
'') {
7502 $new_array_options[
"options_".$key] =
null;
7504 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7510 if (!is_numeric($value) && $value !=
'') {
7511 dol_syslog($langs->trans(
"ExtraFieldHasWrongValue").
" on ".$attributeLabel.
"(".$value.
"is not '".$attributeType.
"')", LOG_DEBUG);
7512 $this->errors[] = $langs->trans(
"ExtraFieldHasWrongValue", $attributeLabel);
7514 } elseif ($value ===
'') {
7518 $new_array_options[
"options_".$key] = $value;
7520 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7532 if ($this->array_options[
"options_".$key] !=
'' && is_array($extrafields->attributes[$this->table_element][
'param'][$attributeKey][
'options'])) {
7534 $tmparrays = array_keys($extrafields->attributes[$this->table_element][
'param'][$attributeKey][
'options']);
7535 $algo = reset($tmparrays);
7541 if (is_object($this->oldcopy)) {
7543 if (isset($this->oldcopy->array_options[
"options_".$key]) && $this->array_options[
"options_".$key] == $this->oldcopy->array_options[
"options_".$key]) {
7544 if ($algo ==
'dolcrypt') {
7545 if (!preg_match(
'/^dolcrypt:/', $this->array_options[
"options_".$key])) {
7546 $new_array_options[
"options_".$key] =
dolEncrypt($this->array_options[
"options_".$key]);
7548 $new_array_options[
"options_".$key] = $this->array_options[
"options_".$key];
7551 $new_array_options[
"options_".$key] = $this->array_options[
"options_".$key];
7554 if ($algo ==
'dolcrypt') {
7555 if (!preg_match(
'/^dolcrypt:/', $this->array_options[
"options_".$key])) {
7556 $new_array_options[
"options_".$key] =
dolEncrypt($this->array_options[
"options_".$key]);
7558 $new_array_options[
"options_".$key] = $this->array_options[
"options_".$key];
7561 $new_array_options[
"options_".$key] =
dol_hash($this->array_options[
"options_".$key], $algo);
7565 if ($algo ==
'dolcrypt' && !preg_match(
'/^dolcrypt:/', $this->array_options[
"options_".$key])) {
7566 $new_array_options[
"options_".$key] =
dolEncrypt($this->array_options[
"options_".$key]);
7568 $new_array_options[
"options_".$key] = $this->array_options[
"options_".$key];
7573 $new_array_options[
"options_".$key] = $this->array_options[
"options_".$key];
7576 $new_array_options[
"options_".$key] = $this->array_options[
"options_".$key];
7579 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7583 if (empty($this->array_options[
"options_".$key])) {
7584 $new_array_options[
"options_".$key] =
null;
7586 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7588 $new_array_options[
"options_".$key] = $this->db->idate($this->array_options[
"options_".$key]);
7592 if (empty($this->array_options[
"options_".$key])) {
7593 $new_array_options[
"options_".$key] =
null;
7595 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7597 $new_array_options[
"options_".$key] = $this->db->idate($this->array_options[
"options_".$key],
'gmt');
7601 if (empty($this->array_options[
"options_".$key])) {
7602 $new_array_options[
"options_".$key] =
null;
7604 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7608 if ($this->array_options[
"options_".$key] ===
'') {
7609 $new_array_options[
"options_".$key] =
null;
7611 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7645 $new_array_options = array();
7646 if (is_array($this->array_options[
"options_".$key])) {
7647 $new_array_options[
"options_".$key] = implode(
',', $this->array_options[
"options_".$key]);
7649 $new_array_options[
"options_".$key] = $this->array_options[
"options_".$key];
7652 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7658 $linealreadyfound = 0;
7661 $table_element = $this->table_element;
7662 if ($table_element ==
'categorie') {
7663 $table_element =
'categories';
7666 $sql =
"SELECT COUNT(rowid) as nb FROM ".$this->db->prefix().$table_element.
"_extrafields WHERE fk_object = ".((int) $this->
id);
7667 $resql = $this->db->query($sql);
7669 $tmpobj = $this->db->fetch_object($resql);
7671 $linealreadyfound = $tmpobj->nb;
7676 if ($linealreadyfound) {
7677 $sanitizedGeoDataType = ExtraFields::$geoDataTypes[$attributeType] ??
null;
7678 if ($this->array_options[
"options_".$key] ===
null) {
7679 $sql =
"UPDATE ".$this->db->prefix().$this->db->sanitize($table_element).
"_extrafields";
7680 $sql .=
" SET ".$this->db->sanitize($key).
" = null";
7681 } elseif (!empty($sanitizedGeoDataType[
'ST_Function'])) {
7682 $sql =
"UPDATE ".$this->db->prefix().$this->db->sanitize($table_element).
"_extrafields";
7683 $sql .=
" SET ".$this->db->sanitize($key).
" = ".$this->db->sanitize($sanitizedGeoDataType[
'ST_Function']).
"('".$this->db->escape($this->array_options[
"options_".$key]).
"')";
7686 $sql =
"UPDATE ".$this->db->prefix().$this->db->sanitize($table_element).
"_extrafields";
7687 $sql .=
" SET ".$this->db->sanitize($key).
" = '".$this->db->escape($new_array_options[
"options_".$key]).
"'";
7689 $sql .=
" WHERE fk_object = ".((int) $this->
id);
7691 $resql = $this->db->query($sql);
7694 $this->error = $this->db->lasterror();
7697 $result = $this->insertExtraFields(
'', $user);
7704 if (!$error && !empty($this->fields[
'fk_user_modif'])) {
7705 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
7706 $sql .=
" SET fk_user_modif = ".(int) $user->id;
7707 $sql .=
" WHERE ".(empty($this->table_rowid) ?
'rowid' : $this->db->sanitize($this->table_rowid)).
" = ".((
int)
$this->id);
7708 $this->db->query($sql);
7712 $parameters = array(
'key' => $key);
7714 $reshook = $hookmanager->executeHooks(
'updateExtraFieldBeforeCommit', $parameters, $this, $action);
7720 if (!$error && $trigger) {
7722 $this->context = array(
'extrafieldupdate' => 1);
7723 $result = $this->call_trigger($trigger, $userused);
7731 dol_syslog(__METHOD__.$this->error, LOG_ERR);
7732 $this->db->rollback();
7735 $this->db->commit();
7751 return $this->array_options[
'options_'.$key] ??
null;
7763 $this->array_options[
'options_'.$key] = $value;
7780 if (empty($userused)) {
7808 public function showInputField($val, $key, $value, $moreparam =
'', $keysuffix =
'', $keyprefix =
'', $morecss = 0, $nonewbutton = 0)
7810 global
$conf, $langs, $form;
7815 if (!is_object($form)) {
7816 require_once DOL_DOCUMENT_ROOT.
'/core/class/html.form.class.php';
7817 $form =
new Form($this->db);
7820 if (!empty($this->fields)) {
7821 $val = $this->fields[$key];
7825 $fieldValidationErrorMsg =
'';
7826 $validationClass =
'';
7827 $fieldValidationErrorMsg = $this->getFieldError($key);
7828 if (!empty($fieldValidationErrorMsg)) {
7829 $validationClass =
' --error';
7831 $validationClass =
' --success';
7839 $param[
'options'] = array();
7842 $size = !empty($this->fields[$key][
'size']) ? $this->fields[$key][
'size'] : 0;
7844 if (preg_match(
'/^(integer|link):(.*):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
7845 $param[
'options'] = array($reg[2].
':'.$reg[3].
':'.$reg[4].
':'.$reg[5] =>
'N');
7847 } elseif (preg_match(
'/^(integer|link):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
7848 $param[
'options'] = array($reg[2].
':'.$reg[3].
':'.$reg[4] =>
'N');
7850 } elseif (preg_match(
'/^(integer|link):(.*):(.*)/i', $val[
'type'], $reg)) {
7851 $param[
'options'] = array($reg[2].
':'.$reg[3] =>
'N');
7853 } elseif (preg_match(
'/^(sellist):(.*):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
7854 $param[
'options'] = array($reg[2].
':'.$reg[3].
':'.$reg[4].
':'.$reg[5] =>
'N');
7856 } elseif (preg_match(
'/^(sellist):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
7857 $param[
'options'] = array($reg[2].
':'.$reg[3].
':'.$reg[4] =>
'N');
7859 } elseif (preg_match(
'/^(sellist):(.*):(.*)/i', $val[
'type'], $reg)) {
7860 $param[
'options'] = array($reg[2].
':'.$reg[3] =>
'N');
7862 } elseif (preg_match(
'/^chkbxlst:(.*)/i', $val[
'type'], $reg)) {
7863 $param[
'options'] = array($reg[1] =>
'N');
7865 } elseif (preg_match(
'/varchar\((\d+)\)/', $val[
'type'], $reg)) {
7866 $param[
'options'] = array();
7869 } elseif (preg_match(
'/varchar/', $val[
'type'])) {
7870 $param[
'options'] = array();
7872 } elseif (preg_match(
'/stars\((\d+)\)/', $val[
'type'], $reg)) {
7873 $param[
'options'] = array();
7877 $param[
'options'] = array();
7878 $type = $this->fields[$key][
'type'];
7883 if (!empty($this->fields[$key][
'arrayofkeyval']) && is_array($this->fields[$key][
'arrayofkeyval'])) {
7884 $param[
'options'] = $this->fields[$key][
'arrayofkeyval'];
7886 if (empty($this->fields[$key][
'multiinput'])) {
7887 $type = (($this->fields[$key][
'type'] ==
'checkbox') ? $this->fields[$key][
'type'] :
'select');
7891 $label = $this->fields[$key][
'label'];
7894 $default = (!empty($this->fields[$key][
'default']) ? $this->fields[$key][
'default'] :
'');
7896 $computed = (!empty($this->fields[$key][
'computed']) ? $this->fields[$key][
'computed'] :
'');
7898 $unique = (!empty($this->fields[$key][
'unique']) ? $this->fields[$key][
'unique'] : 0);
7900 $required = (!empty($this->fields[$key][
'required']) ? $this->fields[$key][
'required'] : 0);
7902 $autofocusoncreate = (!empty($this->fields[$key][
'autofocusoncreate']) ? $this->fields[$key][
'autofocusoncreate'] : 0);
7904 $placeholder = (!empty($this->fields[$key][
'placeholder']) ? $this->fields[$key][
'placeholder'] : 0);
7907 $langfile = (!empty($this->fields[$key][
'langfile']) ? $this->fields[$key][
'langfile'] :
'');
7909 $list = (!empty($this->fields[$key][
'list']) ? $this->fields[$key][
'list'] : 0);
7910 $hidden = (in_array(abs($this->fields[$key][
'visible']), array(0, 2)) ? 1 : 0);
7915 if (!preg_match(
'/^search_/', $keyprefix)) {
7916 return '<span class="opacitymedium">'.$langs->trans(
"AutomaticallyCalculated").
'</span>';
7923 if (empty($morecss) && !empty($val[
'css'])) {
7924 $morecss = $val[
'css'];
7925 } elseif (empty($morecss)) {
7926 if ($type ==
'date') {
7927 $morecss =
'minwidth100imp';
7928 } elseif ($type ==
'datetime' || $type ==
'link') {
7929 $morecss =
'minwidth200imp';
7930 } elseif (in_array($type, array(
'int',
'integer',
'price')) || preg_match(
'/^double(\([0-9],[0-9]\)){0,1}/', (
string) $type)) {
7931 $morecss =
'maxwidth75';
7932 } elseif ($type ==
'url') {
7933 $morecss =
'minwidth400';
7934 } elseif ($type ==
'boolean') {
7937 if (is_numeric($size) && round((
float) $size) < 12) {
7938 $morecss =
'minwidth100';
7939 } elseif (is_numeric($size) && round((
float) $size) <= 48) {
7940 $morecss =
'minwidth200';
7942 $morecss =
'minwidth400';
7948 if (!empty($validationClass)) {
7949 $morecss .= $validationClass;
7952 if (in_array($type, array(
'date'))) {
7953 $tmp = explode(
',', $size);
7958 if (!$required && $value ==
'') {
7963 $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required,
'', 1, (($keyprefix !=
'search_' && $keyprefix !=
'search_options_') ? 1 : 0), 0, 1);
7964 } elseif (in_array($type, array(
'datetime'))) {
7965 $tmp = explode(
',', $size);
7970 if (!$required && $value ==
'') {
7975 $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required,
'', 1, (($keyprefix !=
'search_' && $keyprefix !=
'search_options_') ? 1 : 0), 0, 1,
'',
'',
'', 1,
'',
'',
'tzuserrel');
7976 } elseif (in_array($type, array(
'duration'))) {
7977 $out = $form->select_duration($keyprefix.$key.$keysuffix, $value, 0,
'text', 0, 1);
7978 } elseif (in_array($type, array(
'int',
'integer'))) {
7979 $tmp = explode(
',', $size);
7981 $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' :
'').
'>';
7982 } elseif (in_array($type, array(
'real'))) {
7983 $out =
'<input type="text" class="flat '.$morecss.
'" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.
dol_escape_htmltag($value).
'"'.($moreparam ? $moreparam :
'').($autofocusoncreate ?
' autofocus' :
'').
'>';
7984 } elseif (preg_match(
'/varchar/', (
string) $type)) {
7985 $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' :
'').
'>';
7986 } elseif (in_array($type, array(
'email',
'mail',
'phone',
'url',
'ip'))) {
7987 $out =
'<input type="text" class="flat '.$morecss.
'" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.
dol_escape_htmltag($value).
'" '.($moreparam ? $moreparam :
'').($autofocusoncreate ?
' autofocus' :
'').
'>';
7988 } elseif (preg_match(
'/^text/', (
string) $type)) {
7989 if (!preg_match(
'/search_/', $keyprefix)) {
7990 if (!empty($param[
'options'])) {
7993 $out .= $form->selectarray($keyprefix.$key.$keysuffix.
"_multiinput", $param[
'options'],
'', 1, 0, 0,
"flat maxwidthonphone".$morecss);
7994 $out .=
'<input id="'.$keyprefix.$key.$keysuffix.
'_multiinputadd" type="button" class="button" value="'.$langs->trans(
"Add").
'">';
7997 function handlemultiinputdisabling(htmlname){
7998 console.log("We handle the disabling of used options for "+htmlname+"_multiinput");
7999 multiinput = $("#"+htmlname+"_multiinput");
8000 multiinput.find("option").each(function(){
8001 tmpval = $("#"+htmlname).val();
8002 tmpvalarray = tmpval.split("\n");
8003 valtotest = $(this).val();
8004 if(tmpvalarray.includes(valtotest)){
8005 $(this).prop("disabled",true);
8007 if($(this).prop("disabled") == true){
8008 console.log(valtotest)
8009 $(this).prop("disabled", false);
8015 $(document).ready(function () {
8016 $("#'.$keyprefix.$key.$keysuffix.
'_multiinputadd").on("click",function() {
8017 tmpval = $("#'.$keyprefix.$key.$keysuffix.
'").val();
8018 tmpvalarray = tmpval.split(",");
8019 valtotest = $("#'.$keyprefix.$key.$keysuffix.
'_multiinput").val();
8020 if(valtotest != -1 && !tmpvalarray.includes(valtotest)){
8021 console.log("We add the selected value to the text area '.$keyprefix.$key.$keysuffix.
'");
8025 tmpval = tmpval + "\n" + valtotest;
8027 $("#'.$keyprefix.$key.$keysuffix.
'").val(tmpval);
8028 handlemultiinputdisabling("'.$keyprefix.$key.$keysuffix.
'");
8029 $("#'.$keyprefix.$key.$keysuffix.
'_multiinput").val(-1);
8031 console.log("We add nothing the text area '.$keyprefix.$key.$keysuffix.
'");
8034 $("#'.$keyprefix.$key.$keysuffix.
'").on("change",function(){
8035 handlemultiinputdisabling("'.$keyprefix.$key.$keysuffix.
'");
8037 handlemultiinputdisabling("'.$keyprefix.$key.$keysuffix.
'");
8039 $out .=
"</script>";
8040 $value = str_replace(
',',
"\n", $value);
8042 require_once DOL_DOCUMENT_ROOT.
'/core/class/doleditor.class.php';
8043 $doleditor =
new DolEditor($keyprefix.$key.$keysuffix, $value,
'', 200,
'dolibarr_notes',
'In',
false,
false,
false, ROWS_5,
'90%');
8044 $out .= (
string) $doleditor->Create(1,
'',
true,
'',
'',
'', $morecss);
8046 $out =
'<input type="text" class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.
dol_escape_htmltag($value).
'" '.($moreparam ? $moreparam :
'').
'>';
8048 } elseif (preg_match(
'/^html/', (
string) $type)) {
8049 if (!preg_match(
'/search_/', $keyprefix)) {
8050 require_once DOL_DOCUMENT_ROOT.
'/core/class/doleditor.class.php';
8051 $doleditor =
new DolEditor($keyprefix.$key.$keysuffix, $value,
'', 200,
'dolibarr_notes',
'In',
false,
false,
isModEnabled(
'fckeditor') &&
getDolGlobalInt(
'FCKEDITOR_ENABLE_SOCIETE'), ROWS_5,
'90%');
8052 $out = (
string) $doleditor->Create(1,
'',
true,
'',
'', $moreparam, $morecss);
8054 $out =
'<input type="text" class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.
dol_escape_htmltag($value).
'" '.($moreparam ? $moreparam :
'').
'>';
8056 } elseif ($type ==
'boolean') {
8058 if (!empty($value)) {
8059 $checked =
' checked value="1" ';
8061 $checked =
' value="1" ';
8063 $out =
'<input type="checkbox" class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" '.$checked.
' '.($moreparam ? $moreparam :
'').
'>';
8064 } elseif ($type ==
'price') {
8065 if (!empty($value)) {
8066 $value =
price($value);
8068 $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>';
8069 } elseif ($type ==
'stars') {
8070 $out =
'<input type="hidden" class="flat '.$morecss.
'" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.
dol_escape_htmltag($value).
'"'.($moreparam ? $moreparam :
'').($autofocusoncreate ?
' autofocus' :
'').
'>';
8071 $out .=
'<div class="star-selection" id="'.$keyprefix.$key.$keysuffix.
'_selection">';
8073 while ($i <= $size) {
8074 $out .=
'<span class="star" data-value="'.$i.
'">'.
img_picto(
'',
'fontawesome_star_fas').
'</span>';
8079 jQuery(function($) { /* commonobject.class.php 1 */
8080 let container = $("#'.$keyprefix.$key.$keysuffix.
'_selection");
8081 let selectedStars = parseInt($("#'.$keyprefix.$key.$keysuffix.
'").val()) || 0;
8082 container.find(".star").each(function() {
8083 $(this).toggleClass("active", $(this).data("value") <= selectedStars);
8085 container.find(".star").on("mouseover", function() {
8086 let selectedStar = $(this).data("value");
8087 container.find(".star").each(function() {
8088 $(this).toggleClass("active", $(this).data("value") <= selectedStar);
8091 container.on("mouseout", function() {
8092 container.find(".star").each(function() {
8093 $(this).toggleClass("active", $(this).data("value") <= selectedStars);
8096 container.find(".star").off("click").on("click", function() {
8097 selectedStars = $(this).data("value");
8098 if (selectedStars === 1 && $("#'.$keyprefix.$key.$keysuffix.
'").val() == 1) {
8101 $("#'.$keyprefix.$key.$keysuffix.
'").val(selectedStars);
8102 container.find(".star").each(function() {
8103 $(this).toggleClass("active", $(this).data("value") <= selectedStars);
8108 } elseif (preg_match(
'/^double(\([0-9],[0-9]\)){0,1}/', (
string) $type)) {
8109 if (!empty($value)) {
8110 $value =
price($value);
8112 $out =
'<input type="text" class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.$value.
'" '.($moreparam ? $moreparam :
'').
'> ';
8113 } elseif ($type ==
'select') {
8116 include_once DOL_DOCUMENT_ROOT.
'/core/lib/ajax.lib.php';
8117 $out .=
ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
8123 foreach ($param[
'options'] as $keyb => $valb) {
8124 if ((
string) $keyb ==
'') {
8127 if (strpos($valb,
"|") !==
false) {
8128 list($valb, $parent) = explode(
'|', $valb);
8131 $tmpselect .=
'<option value="'.$keyb.
'"';
8132 $tmpselect .= (((
string) $value == (
string) $keyb) ?
' selected' :
'');
8133 if (!empty($parent)) {
8136 $tmpselect .= (!empty($parent) ?
' parent="'.$parent.
'"' :
'');
8137 $tmpselect .=
'>'.$langs->trans($valb).
'</option>';
8140 $out .=
'<select class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" '.($moreparam ? $moreparam :
'').
'>';
8141 if ((!isset($this->fields[$key][
'default'])) || empty($this->fields[$key][
'notnull']) || ($this->fields[$key][
'notnull'] != 1) || $nbchoice >= 2) {
8142 $out .=
'<option value="0"> </option>';
8145 $out .=
'</select>';
8146 } elseif ($type ==
'sellist') {
8149 include_once DOL_DOCUMENT_ROOT.
'/core/lib/ajax.lib.php';
8150 $out .=
ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
8153 $out .=
'<select class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" '.($moreparam ? $moreparam :
'').
'>';
8154 if (is_array($param[
'options'])) {
8155 $tmpparamoptions = array_keys($param[
'options']);
8156 $paramoptions = preg_split(
'/[\r\n]+/', $tmpparamoptions[0]);
8158 $InfoFieldList = explode(
":", $paramoptions[0], 5);
8170 if (! empty($InfoFieldList[4])) {
8172 $parenthesisopen = 0;
8173 while (substr($InfoFieldList[4], $pos, 1) !==
'' && ($parenthesisopen || $pos == 0 || substr($InfoFieldList[4], $pos, 1) !=
':')) {
8174 if (substr($InfoFieldList[4], $pos, 1) ==
'(') {
8177 if (substr($InfoFieldList[4], $pos, 1) ==
')') {
8182 $tmpbefore = substr($InfoFieldList[4], 0, $pos);
8183 $tmpafter = substr($InfoFieldList[4], $pos + 1);
8185 $InfoFieldList[4] = $tmpbefore;
8186 if ($tmpafter !==
'') {
8187 $InfoFieldList = array_merge($InfoFieldList, explode(
':', $tmpafter));
8193 if (preg_match(
'/^\(?([a-z0-9]+)([=<>]+)(\d+)\)?$/i', $InfoFieldList[4], $reg)) {
8194 $InfoFieldList[4] =
'('.$reg[1].
':'.$reg[2].
':'.$reg[3].
')';
8205 $keyList = (empty($InfoFieldList[2]) ?
'rowid' : $InfoFieldList[2].
' as rowid');
8207 if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
8208 if (strpos($InfoFieldList[4],
'extra.') !==
false) {
8209 $keyList =
'main.'.$InfoFieldList[2].
' as rowid';
8211 $keyList = $InfoFieldList[2].
' as rowid';
8214 if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
8215 list($parentName, $parentField) = explode(
'|', $InfoFieldList[3]);
8216 if (!empty($InfoFieldList[4]) && strpos($InfoFieldList[4],
'extra.') !==
false) {
8217 $keyList .=
', main.'.$parentField;
8219 $keyList .=
', '.$parentField;
8223 $filter_categorie =
false;
8224 if (count($InfoFieldList) > 5) {
8225 if ($InfoFieldList[0] ==
'categorie') {
8226 $filter_categorie =
true;
8230 if (!$filter_categorie) {
8231 $fields_label = isset($InfoFieldList[1]) ? explode(
'|', $InfoFieldList[1]) : array();
8232 if (!empty($fields_label)) {
8234 $keyList .= implode(
', ', $fields_label);
8238 $sql =
"SELECT " . $this->db->sanitize($keyList, 0, 0, 1);
8239 $sql .=
" FROM " . $this->db->prefix() . $this->db->sanitize($InfoFieldList[0]);
8241 if (!empty($InfoFieldList[4])) {
8243 if (strpos($InfoFieldList[4],
'$SEL$') !==
false) {
8244 $InfoFieldList[4] = str_replace(
'$SEL$',
'SELECT', $InfoFieldList[4]);
8248 if (strpos($InfoFieldList[4],
'$ID$') !==
false && !empty($objectid)) {
8249 $InfoFieldList[4] = str_replace(
'$ID$', (
string) $objectid, $InfoFieldList[4]);
8251 $InfoFieldList[4] = str_replace(
'$ID$',
'0', $InfoFieldList[4]);
8256 if (strpos($InfoFieldList[4],
'extra') !==
false) {
8257 $sql .=
" as main, " . $this->db->sanitize($this->db->prefix() . $InfoFieldList[0]) .
"_extrafields as extra";
8258 $sqlwhere .=
" WHERE extra.fk_object = main." . $this->db->sanitize($InfoFieldList[2]);
8259 $sqlwhere .=
" AND " . forgeSQLFromUniversalSearchCriteria($InfoFieldList[4], $errstr, 1);
8261 $sqlwhere .=
" WHERE " . forgeSQLFromUniversalSearchCriteria($InfoFieldList[4], $errstr, 1);
8264 $sqlwhere .=
' WHERE 1=1';
8281 if (in_array($InfoFieldList[0], array(
'tablewithentity'))) {
8282 $sqlwhere .=
" AND entity = " . ((int)
$conf->entity);
8287 if (isset($InfoFieldList[7]) && preg_match(
'/^[a-z0-9_\-,]+$/i', $InfoFieldList[7])) {
8288 $sql .=
" ORDER BY ".$this->db->escape($InfoFieldList[7]);
8290 $sql .=
" ORDER BY ".$this->db->sanitize(implode(
', ', $fields_label));
8292 $sql .=
' LIMIT ' .
getDolGlobalInt(
'MAIN_EXTRAFIELDS_LIMIT_SELLIST_SQL', 1000);
8295 dol_syslog(get_class($this) .
'::showInputField type=sellist', LOG_DEBUG);
8296 $resql = $this->db->query($sql);
8298 $out .=
'<option value="0"> </option>';
8299 $num = $this->db->num_rows($resql);
8303 $obj = $this->db->fetch_object($resql);
8307 $fields_label = explode(
'|', $InfoFieldList[1]);
8308 if (count($fields_label) > 1) {
8310 foreach ($fields_label as $field_toshow) {
8311 $labeltoshow .= $obj->$field_toshow .
' ';
8314 $labeltoshow = $obj->{$InfoFieldList[1]};
8316 $labeltoshow =
dol_trunc($labeltoshow, 45);
8318 if ($value == $obj->rowid) {
8319 foreach ($fields_label as $field_toshow) {
8320 $translabel = $langs->trans($obj->$field_toshow);
8321 if ($translabel != $obj->$field_toshow) {
8322 $labeltoshow =
dol_trunc($translabel) .
' ';
8324 $labeltoshow =
dol_trunc($obj->$field_toshow) .
' ';
8327 $out .=
'<option value="' . $obj->rowid .
'" selected>' . $labeltoshow .
'</option>';
8330 $translabel = $langs->trans($obj->{$InfoFieldList[1]});
8331 if ($translabel != $obj->{$InfoFieldList[1]}) {
8332 $labeltoshow =
dol_trunc($translabel, 18);
8334 $labeltoshow =
dol_trunc($obj->{$InfoFieldList[1]});
8337 if (empty($labeltoshow)) {
8338 $labeltoshow =
'(not defined)';
8340 if ($value == $obj->rowid) {
8341 $out .=
'<option value="' . $obj->rowid .
'" selected>' . $labeltoshow .
'</option>';
8344 if (!empty($InfoFieldList[3]) && $parentField) {
8345 $parent = $parentName .
':' . $obj->{$parentField};
8349 $out .=
'<option value="' . $obj->rowid .
'"';
8350 $out .= ($value == $obj->rowid ?
' selected' :
'');
8351 $out .= (!empty($parent) ?
' parent="' . $parent .
'"' :
'');
8352 $out .=
'>' . $labeltoshow .
'</option>';
8357 $this->db->free($resql);
8359 print
'Error in request ' . $sql .
' ' . $this->db->lasterror() .
'. Check setup of extra parameters.<br>';
8362 require_once DOL_DOCUMENT_ROOT.
'/categories/class/categorie.class.php';
8363 $categcode = $InfoFieldList[5];
8364 if (is_numeric($categcode)) {
8365 $tmpcategory =
new Categorie($this->db);
8366 $MAP_ID_TO_CODE = array_flip($tmpcategory->MAP_ID);
8367 $categcode = $MAP_ID_TO_CODE[(int) $categcode];
8370 $data = $form->select_all_categories($categcode,
'',
'parent', 64, $InfoFieldList[6], 1, 1);
8371 $out .=
'<option value="0"> </option>';
8372 foreach ($data as $data_key => $data_value) {
8373 $out .=
'<option value="' . $data_key .
'"';
8374 $out .= ($value == $data_key ?
' selected' :
'');
8375 $out .=
'>' . $data_value .
'</option>';
8379 $out .=
'</select>';
8380 } elseif ($type ==
'checkbox') {
8381 $value_arr = explode(
',', $value);
8382 $out = $form->multiselectarray($keyprefix.$key.$keysuffix, (empty($param[
'options']) ?
null : $param[
'options']), $value_arr, 0, 0, $morecss, 0,
'100%');
8383 } elseif ($type ==
'radio') {
8385 foreach ($param[
'options'] as $keyopt => $valopt) {
8386 $out .=
'<input class="flat '.$morecss.
'" type="radio" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" '.($moreparam ? $moreparam :
'');
8387 $out .=
' value="'.$keyopt.
'"';
8388 $out .=
' id="'.$keyprefix.$key.$keysuffix.
'_'.$keyopt.
'"';
8389 $out .= ($value == $keyopt ?
'checked' :
'');
8390 $out .=
'/><label for="'.$keyprefix.$key.$keysuffix.
'_'.$keyopt.
'">'.$valopt.
'</label><br>';
8392 } elseif ($type ==
'chkbxlst') {
8393 if (is_array($value)) {
8394 $value_arr = $value;
8396 $value_arr = explode(
',', $value);
8399 if (is_array($param[
'options'])) {
8400 $tmpparamoptions = array_keys($param[
'options']);
8401 $paramoptions = preg_split(
'/[\r\n]+/', $tmpparamoptions[0]);
8403 $InfoFieldList = explode(
":", $paramoptions[0], 5);
8415 if (! empty($InfoFieldList[4])) {
8417 $parenthesisopen = 0;
8418 while (substr($InfoFieldList[4], $pos, 1) !==
'' && ($parenthesisopen || $pos == 0 || substr($InfoFieldList[4], $pos, 1) !=
':')) {
8419 if (substr($InfoFieldList[4], $pos, 1) ==
'(') {
8422 if (substr($InfoFieldList[4], $pos, 1) ==
')') {
8427 $tmpbefore = substr($InfoFieldList[4], 0, $pos);
8428 $tmpafter = substr($InfoFieldList[4], $pos + 1);
8430 $InfoFieldList[4] = $tmpbefore;
8431 if ($tmpafter !==
'') {
8432 $InfoFieldList = array_merge($InfoFieldList, explode(
':', $tmpafter));
8437 if (preg_match(
'/^\(?([a-z0-9]+)([=<>]+)(\d+)\)?$/i', $InfoFieldList[4], $reg)) {
8438 $InfoFieldList[4] =
'('.$reg[1].
':'.$reg[2].
':'.$reg[3].
')';
8446 '@phan-var-force array{0:string,1:string,2:string,3:string,3:string,5:string,6:string} $InfoFieldList';
8451 $keyList = (empty($InfoFieldList[2]) ?
'rowid' : $InfoFieldList[2].
' as rowid');
8453 if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
8454 if (strpos($InfoFieldList[4],
'extra.') !==
false) {
8455 $keyList =
'main.'.$InfoFieldList[2].
' as rowid';
8457 $keyList = $InfoFieldList[2].
' as rowid';
8460 if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
8461 list($parentName, $parentField) = explode(
'|', $InfoFieldList[3]);
8462 if (!empty($InfoFieldList[4]) && strpos($InfoFieldList[4],
'extra.') !==
false) {
8463 $keyList .=
', main.'.$parentField;
8465 $keyList .=
', '.$parentField;
8469 $filter_categorie =
false;
8470 if (count($InfoFieldList) > 5) {
8471 if ($InfoFieldList[0] ==
'categorie') {
8472 $filter_categorie =
true;
8477 if (!$filter_categorie) {
8478 $fields_label = explode(
'|', $InfoFieldList[1]);
8479 if (is_array($fields_label)) {
8481 $keyList .= implode(
', ', $fields_label);
8485 $sql =
"SELECT " . $this->db->sanitize($keyList, 0, 0, 1);
8486 $sql .=
' FROM ' . $this->db->prefix() . $this->db->sanitize($InfoFieldList[0]);
8488 if (!empty($InfoFieldList[4])) {
8490 if (strpos($InfoFieldList[4],
'$SEL$') !==
false) {
8491 $InfoFieldList[4] = str_replace(
'$SEL$',
'SELECT', $InfoFieldList[4]);
8495 if (strpos($InfoFieldList[4],
'$ID$') !==
false && !empty($objectid)) {
8496 $InfoFieldList[4] = str_replace(
'$ID$', (
string) $objectid, $InfoFieldList[4]);
8498 $InfoFieldList[4] = str_replace(
'$ID$',
'0', $InfoFieldList[4]);
8503 if (strpos($InfoFieldList[4],
'extra') !==
false) {
8504 $sql .=
' as main, ' . $this->db->sanitize($this->db->prefix() . $InfoFieldList[0]) .
'_extrafields as extra';
8505 $sqlwhere .=
" WHERE extra.fk_object = main." . $this->db->sanitize($InfoFieldList[2]);
8506 $sqlwhere .=
" AND " . forgeSQLFromUniversalSearchCriteria($InfoFieldList[4], $errstr, 1);
8508 $sqlwhere .=
" WHERE " . forgeSQLFromUniversalSearchCriteria($InfoFieldList[4], $errstr, 1);
8511 $sqlwhere .=
' WHERE 1=1';
8528 if (in_array($InfoFieldList[0], array(
'tablewithentity'))) {
8529 $sqlwhere .=
" AND entity = " . ((int)
$conf->entity);
8536 dol_syslog(get_class($this) .
'::showInputField type=chkbxlst', LOG_DEBUG);
8538 $resql = $this->db->query($sql);
8540 $num = $this->db->num_rows($resql);
8547 $obj = $this->db->fetch_object($resql);
8551 $fields_label = explode(
'|', $InfoFieldList[1]);
8552 if (count($fields_label) > 1) {
8554 foreach ($fields_label as $field_toshow) {
8555 $labeltoshow .= $obj->$field_toshow .
' ';
8558 $labeltoshow = $obj->{$InfoFieldList[1]};
8560 $labeltoshow =
dol_trunc($labeltoshow, 45);
8562 if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
8563 foreach ($fields_label as $field_toshow) {
8564 $translabel = $langs->trans($obj->$field_toshow);
8565 if ($translabel != $obj->$field_toshow) {
8566 $labeltoshow =
dol_trunc($translabel, 18) .
' ';
8568 $labeltoshow =
dol_trunc($obj->$field_toshow, 18) .
' ';
8572 $data[$obj->rowid] = $labeltoshow;
8575 $translabel = $langs->trans($obj->{$InfoFieldList[1]});
8576 if ($translabel != $obj->{$InfoFieldList[1]}) {
8577 $labeltoshow =
dol_trunc($translabel, 18);
8579 $labeltoshow =
dol_trunc($obj->{$InfoFieldList[1]}, 18);
8582 if (empty($labeltoshow)) {
8583 $labeltoshow =
'(not defined)';
8586 if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
8587 $data[$obj->rowid] = $labeltoshow;
8590 if (!empty($InfoFieldList[3]) && $parentField) {
8591 $parent = $parentName .
':' . $obj->{$parentField};
8595 $data[$obj->rowid] = $labeltoshow;
8600 $this->db->free($resql);
8602 $out = $form->multiselectarray($keyprefix . $key . $keysuffix, $data, $value_arr, 0, 0, $morecss, 0,
'100%');
8604 print
'Error in request ' . $sql .
' ' . $this->db->lasterror() .
'. Check setup of extra parameters.<br>';
8607 require_once DOL_DOCUMENT_ROOT.
'/categories/class/categorie.class.php';
8608 $categcode = $InfoFieldList[5];
8609 if (is_numeric($categcode)) {
8610 $tmpcategory =
new Categorie($this->db);
8611 $MAP_ID_TO_CODE = array_flip($tmpcategory->MAP_ID);
8612 $categcode = $MAP_ID_TO_CODE[(int) $categcode];
8615 $data = $form->select_all_categories($categcode,
'',
'parent', 64, $InfoFieldList[6], 1, 1);
8616 $out = $form->multiselectarray($keyprefix . $key . $keysuffix, $data, $value_arr, 0, 0, $morecss, 0,
'100%');
8619 } elseif ($type ==
'link') {
8622 $param_list = array_keys($param[
'options']);
8623 $param_list_array = explode(
':', $param_list[0], 4);
8625 $showempty = (($required && $default !=
'') ? 0 : 1);
8627 if (!preg_match(
'/search_/', $keyprefix)) {
8628 if (!empty($param_list_array[2])) {
8630 if (!empty($this->fields[$key][
'picto'])) {
8631 $morecss .=
' widthcentpercentminusxx';
8633 $morecss .=
' widthcentpercentminusx';
8637 if (!empty($this->fields[$key][
'picto'])) {
8638 $morecss .=
' widthcentpercentminusx';
8647 $objectfield = $val;
8650 $out = $form->selectForForms($param_list_array[0], $keyprefix.$key.$keysuffix, (
int) $value, $showempty,
'',
'', $morecss, $moreparam, 0, (empty($val[
'disabled']) ? 0 : 1),
'', $objectfield);
8652 if (!empty($param_list_array[2])) {
8653 if ((!GETPOSTISSET(
'backtopage') || strpos(
GETPOST(
'backtopage'), $_SERVER[
'PHP_SELF']) === 0)
8654 && empty($val[
'disabled']) && empty($nonewbutton)) {
8655 list($class, $classfile) = explode(
':', $param_list[0]);
8656 if (file_exists(
dol_buildpath(dirname(dirname($classfile)).
'/card.php'))) {
8657 $url_path =
dol_buildpath(dirname(dirname($classfile)).
'/card.php', 1);
8659 $url_path =
dol_buildpath(dirname(dirname($classfile)).
'/'.strtolower($class).
'_card.php', 1);
8661 $paramforthenewlink =
'';
8662 $paramforthenewlink .= (GETPOSTISSET(
'action') ?
'&action='.GETPOST(
'action',
'aZ09') :
'');
8663 $paramforthenewlink .= (GETPOSTISSET(
'id') ?
'&id='.GETPOSTINT(
'id') :
'');
8664 $paramforthenewlink .= (GETPOSTISSET(
'origin') ?
'&origin='.GETPOST(
'origin',
'aZ09') :
'');
8665 $paramforthenewlink .= (GETPOSTISSET(
'originid') ?
'&originid='.GETPOSTINT(
'originid') :
'');
8666 $paramforthenewlink .=
'&fk_'.strtolower($class).
'=--IDFORBACKTOPAGE--';
8668 $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>';
8671 } elseif ($type ==
'password') {
8673 if ($keyprefix.$key.$keysuffix ==
'pass_crypted') {
8674 $out =
'<input type="'.($keyprefix ==
'search_' ?
'text' :
'password').
'" class="flat '.$morecss.
'" name="pass" id="pass" value="" '.($moreparam ? $moreparam :
'').
'>';
8675 $out .=
'<input type="hidden" name="pass_crypted" id="pass_crypted" value="'.$value.
'" '.($moreparam ? $moreparam :
'').
'>';
8677 $out =
'<input type="'.($keyprefix ==
'search_' ?
'text' :
'password').
'" class="flat '.$morecss.
'" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.$value.
'" '.($moreparam ? $moreparam :
'').
'>';
8679 } elseif ($type ==
'array') {
8681 $newval[
'type'] =
'varchar(256)';
8684 if (!empty($value)) {
8685 foreach ($value as $option) {
8686 $out .=
'<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).
'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
8687 $out .= $this->showInputField($newval, $keyprefix.$key.$keysuffix.
'[]', $option, $moreparam,
'',
'', $morecss).
'<br></span>';
8690 $out .=
'<a id="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).
'_add" href="javascript:;"><span class="fa fa-plus-circle valignmiddle"></span></a>';
8692 $newInput =
'<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).
'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
8693 $newInput .= $this->showInputField($newval, $keyprefix.$key.$keysuffix.
'[]',
'', $moreparam,
'',
'', $morecss).
'<br></span>';
8695 if (!empty(
$conf->use_javascript_ajax)) {
8697 <script nonce="'.getNonce().
'">
8698 $(document).ready(function() {
8699 $("a#'.
dol_escape_js($keyprefix.$key.$keysuffix).
'_add").click(function() {
8703 $(document).on("click", "a.'.
dol_escape_js($keyprefix.$key.$keysuffix).
'_del", function() {
8704 $(this).parent().remove();
8710 if (!empty($hidden)) {
8711 $out =
'<input type="hidden" value="'.$value.
'" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'"/>';
8714 if ($isDependList == 1) {
8715 $out .= $this->getJSListDependancies(
'_common');
8723 if (!empty($fieldValidationErrorMsg) && function_exists(
'getFieldErrorIcon')) {
8724 $out .=
' '.getFieldErrorIcon($fieldValidationErrorMsg);
8743 public function showOutputField($val, $key, $value, $moreparam =
'', $keysuffix =
'', $keyprefix =
'', $morecss =
'')
8745 global
$conf, $langs, $form;
8749 if (!is_object($form)) {
8750 require_once DOL_DOCUMENT_ROOT.
'/core/class/html.form.class.php';
8751 $form =
new Form($this->db);
8755 $type = empty($val[
'type']) ?
'' : $val[
'type'];
8756 $size = empty($val[
'css']) ?
'' : $val[
'css'];
8761 if (preg_match(
'/varchar\((\d+)\)/', $type, $reg)) {
8764 } elseif (preg_match(
'/varchar/', $type)) {
8767 if (!empty($val[
'arrayofkeyval']) && is_array($val[
'arrayofkeyval'])) {
8769 if (empty($this->fields[$key][
'multiinput'])) {
8770 $type = (($this->fields[$key][
'type'] ==
'checkbox') ? $this->fields[$key][
'type'] :
'select');
8773 if (isset($val[
'type']) && preg_match(
'/^integer:(.*):(.*)/i', $val[
'type'], $reg)) {
8777 $default = empty($val[
'default']) ?
'' : $val[
'default'];
8778 $computed = empty($val[
'computed']) ?
'' : $val[
'computed'];
8779 $unique = empty($val[
'unique']) ?
'' : $val[
'unique'];
8780 $required = empty($val[
'required']) ?
'' : $val[
'required'];
8782 $param[
'options'] = array();
8784 if (!empty($val[
'arrayofkeyval']) && is_array($val[
'arrayofkeyval'])) {
8785 $param[
'options'] = $val[
'arrayofkeyval'];
8787 if (isset($val[
'type']) && preg_match(
'/^integer:([^:]*):([^:]*)/i', $val[
'type'], $reg)) {
8789 $stringforoptions = $reg[1].
':'.$reg[2];
8791 if ($reg[1] ==
'User') {
8792 $stringforoptions .=
':#getnomurlparam1=-1';
8794 $param[
'options'] = array($stringforoptions => $stringforoptions);
8795 } elseif (isset($val[
'type']) && preg_match(
'/^sellist:(.*):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
8796 $param[
'options'] = array($reg[1].
':'.$reg[2].
':'.$reg[3].
':'.$reg[4] =>
'N');
8798 } elseif (isset($val[
'type']) && preg_match(
'/^sellist:(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
8799 $param[
'options'] = array($reg[1].
':'.$reg[2].
':'.$reg[3] =>
'N');
8801 } elseif (isset($val[
'type']) && preg_match(
'/^sellist:(.*):(.*)/i', $val[
'type'], $reg)) {
8802 $param[
'options'] = array($reg[1].
':'.$reg[2] =>
'N');
8804 } elseif (isset($val[
'type']) && preg_match(
'/^chkbxlst:(.*)/i', $val[
'type'], $reg)) {
8805 $param[
'options'] = array($reg[1] =>
'N');
8807 } elseif (isset($val[
'type']) && preg_match(
'/stars\((\d+)\)/', $val[
'type'], $reg)) {
8808 $param[
'options'] = array();
8813 $langfile = empty($val[
'langfile']) ?
'' : $val[
'langfile'];
8814 $list = (empty($val[
'list']) ?
'' : $val[
'list']);
8815 $help = (empty($val[
'help']) ?
'' : $val[
'help']);
8816 $hidden = (($val[
'visible'] == 0) ? 1 : 0);
8826 $value =
dol_eval((
string) $computed, 1, 0,
'2');
8829 if (empty($morecss)) {
8830 if ($type ==
'date') {
8831 $morecss =
'minwidth100imp';
8832 } elseif ($type ==
'datetime' || $type ==
'timestamp') {
8833 $morecss =
'minwidth200imp';
8834 } elseif (in_array($type, array(
'int',
'double',
'price'))) {
8835 $morecss =
'maxwidth75';
8836 } elseif ($type ==
'url') {
8837 $morecss =
'minwidth400';
8838 } elseif ($type ==
'boolean') {
8841 if (is_numeric($size) && round((
float) $size) < 12) {
8842 $morecss =
'minwidth100';
8843 } elseif (is_numeric($size) && round((
float) $size) <= 48) {
8844 $morecss =
'minwidth200';
8846 $morecss =
'minwidth400';
8852 if (in_array($key, array(
'rowid',
'ref')) && method_exists($this,
'getNomUrl')) {
8854 if ($key !=
'rowid' || empty($this->fields[
'ref'])) {
8855 $value = $this->getNomUrl(1,
'', 0,
'', 1);
8857 } elseif ($key ==
'status' && method_exists($this,
'getLibStatut')) {
8858 $value = $this->getLibStatut(3);
8859 } elseif ($type ==
'date') {
8860 if (!empty($value)) {
8865 } elseif ($type ==
'datetime' || $type ==
'timestamp') {
8866 if (!empty($value)) {
8871 } elseif ($type ==
'duration') {
8872 include_once DOL_DOCUMENT_ROOT.
'/core/lib/date.lib.php';
8873 if (!is_null($value) && $value !==
'') {
8876 } elseif ($type ==
'double' || $type ==
'real') {
8877 if (!is_null($value) && $value !==
'') {
8878 $value =
price($value);
8880 } elseif ($type ==
'boolean') {
8882 if (!empty($value)) {
8883 $checked =
' checked ';
8886 $value =
'<input type="checkbox" '.$checked.
' '.($moreparam ? $moreparam :
'').
' readonly disabled>';
8888 $value =
yn($value ? 1 : 0);
8890 } elseif ($type ==
'mail' || $type ==
'email') {
8892 } elseif ($type ==
'url') {
8894 } elseif ($type ==
'phone') {
8895 $value =
dol_print_phone((
string) $value,
'', 0, 0,
'',
' ',
'phone');
8896 } elseif ($type ==
'ip') {
8898 } elseif ($type ==
'stars') {
8899 $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 :
'').
'>';
8900 $value .=
'<div class="star-selection" id="'.$keyprefix.$key.$keysuffix.$this->id.
'_selection">';
8902 while ($i <= $size) {
8903 $value .=
'<span class="star" data-value="'.$i.
'">'.
img_picto(
'',
'fontawesome_star_fas').
'</span>';
8908 $(document).ready(function() { /* commonobject.class.php 2 */
8909 let container = $("#'.$keyprefix.$key.$keysuffix.$this->id.
'_selection");
8910 let selectedStars = parseInt($("#'.$keyprefix.$key.$keysuffix.$this->id.
'").val()) || 0;
8911 container.find(".star").each(function() {
8912 $(this).toggleClass("active", $(this).data("value") <= selectedStars);
8914 container.find(".star").on("mouseover", function() {
8915 let selectedStar = $(this).data("value");
8916 container.find(".star").each(function() {
8917 $(this).toggleClass("active", $(this).data("value") <= selectedStar);
8920 container.on("mouseout", function() {
8921 container.find(".star").each(function() {
8922 $(this).toggleClass("active", $(this).data("value") <= selectedStars);
8925 container.find(".star").off("click").on("click", function() {
8926 selectedStars = $(this).data("value");
8927 if (selectedStars == 1 && $("#'.$keyprefix.$key.$keysuffix.$this->id.
'").val() == 1) {
8930 container.find("#'.$keyprefix.$key.$keysuffix.$this->id.
'").val(selectedStars);
8931 container.find(".star").each(function() {
8932 $(this).toggleClass("active", $(this).data("value") <= selectedStars);
8935 url: "ajax/'.$this->element.
'.php",
8938 objectId: "'.$this->
id.
'",
8939 field: "'.$keyprefix.$key.$keysuffix.
'",
8940 value: selectedStars,
8941 token: "'.newToken().
'"
8943 success: function(response) {
8944 var res = JSON.parse(response);
8945 console[res.status === "success" ? "log" : "error"](res.message);
8947 error: function(xhr, status, error) {
8948 console.log("Ajax request failed while updating '.$keyprefix.$key.$keysuffix.
':", error);
8954 } elseif ($type ==
'price') {
8955 if (!is_null($value) && $value !==
'') {
8956 $value =
price($value, 0, $langs, 0, 0, -1,
$conf->currency);
8958 } elseif ($type ==
'select') {
8959 $value = isset($param[
'options'][(
string) $value]) ? $param[
'options'][(
string) $value] :
'';
8960 if (strpos($value,
"|") !==
false) {
8961 $value = $langs->trans(explode(
'|', $value)[0]);
8962 } elseif (! is_numeric($value)) {
8963 $value = $langs->trans($value);
8965 } elseif ($type ==
'sellist') {
8966 $param_list = array_keys($param[
'options']);
8967 $InfoFieldList = explode(
":", $param_list[0]);
8969 $selectkey =
"rowid";
8972 if (count($InfoFieldList) > 2 && !empty($InfoFieldList[2])) {
8973 $selectkey = $InfoFieldList[2];
8974 $keyList = $InfoFieldList[2].
' as rowid';
8977 $fields_label = explode(
'|', $InfoFieldList[1]);
8978 if (is_array($fields_label)) {
8980 $keyList .= implode(
', ', $fields_label);
8983 $filter_categorie =
false;
8984 if (count($InfoFieldList) > 5) {
8985 if ($InfoFieldList[0] ==
'categorie') {
8986 $filter_categorie =
true;
8990 $sql =
"SELECT ".$this->db->sanitize($keyList, 0, 0, 1);
8991 $sql .=
' FROM '.$this->db->prefix().$this->db->sanitize($InfoFieldList[0]);
8992 if (isset($InfoFieldList[4]) && strpos($InfoFieldList[4],
'extra') !==
false) {
8995 if ($selectkey ==
'rowid' && empty($value)) {
8996 $sql .=
" WHERE ".$this->db->sanitize($selectkey).
" = 0";
8997 } elseif ($selectkey ==
'rowid') {
8998 $sql .=
" WHERE ".$this->db->sanitize($selectkey).
" = ".((int) $value);
9000 $sql .=
" WHERE ".$this->db->sanitize($selectkey).
" = '".$this->db->escape((
string) $value).
"'";
9005 dol_syslog(get_class($this).
':showOutputField:$type=sellist', LOG_DEBUG);
9006 $resql = $this->db->query($sql);
9008 if (!$filter_categorie) {
9010 $numrows = $this->db->num_rows($resql);
9012 $obj = $this->db->fetch_object($resql);
9015 $fields_label = explode(
'|', $InfoFieldList[1]);
9017 if (is_array($fields_label) && count($fields_label) > 1) {
9018 foreach ($fields_label as $field_toshow) {
9020 if (!empty($obj->$field_toshow)) {
9021 $translabel = $langs->trans($obj->$field_toshow);
9023 if ($translabel != $field_toshow) {
9024 $value .=
dol_trunc($translabel, 18) .
' ';
9026 $value .= $obj->$field_toshow .
' ';
9031 if (!empty($obj->{$InfoFieldList[1]})) {
9032 $translabel = $langs->trans($obj->{$InfoFieldList[1]});
9034 if ($translabel != $obj->{$InfoFieldList[1]}) {
9037 $value = $obj->{$InfoFieldList[1]};
9042 require_once DOL_DOCUMENT_ROOT .
'/categories/class/categorie.class.php';
9045 $obj = $this->db->fetch_object($resql);
9047 $c->fetch($obj->rowid);
9048 $ways =
$c->print_all_ways();
9049 foreach ($ways as $way) {
9050 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories"' . (
$c->color ?
' style="background: #' .
$c->color .
';"' :
' style="background: #aaa"') .
'>' .
img_object(
'',
'category') .
' ' . $way .
'</li>';
9052 $value =
'<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(
' ', $toprint).
'</ul></div>';
9055 dol_syslog(get_class($this).
'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
9057 } elseif ($type ==
'radio') {
9058 $value = $param[
'options'][(
string) $value];
9059 } elseif ($type ==
'checkbox') {
9060 $value_arr = explode(
',', (
string) $value);
9062 if (is_array($value_arr) && count($value_arr) > 0) {
9064 foreach ($value_arr as $keyval => $valueval) {
9065 if (!empty($valueval)) {
9066 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' . $param[
'options'][$valueval] .
'</li>';
9069 if (!empty($toprint)) {
9070 $value =
'<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">' . implode(
' ', $toprint) .
'</ul></div>';
9073 } elseif ($type ==
'chkbxlst') {
9074 $value_arr = (isset($value) ? explode(
',', $value) : array());
9076 $param_list = array_keys($param[
'options']);
9077 $InfoFieldList = explode(
":", $param_list[0]);
9079 $selectkey =
"rowid";
9082 if (count($InfoFieldList) >= 3) {
9083 $selectkey = $InfoFieldList[2];
9084 $keyList = $InfoFieldList[2].
' as rowid';
9087 $fields_label = explode(
'|', $InfoFieldList[1]);
9088 if (is_array($fields_label)) {
9090 $keyList .= implode(
', ', $fields_label);
9093 $filter_categorie =
false;
9094 if (count($InfoFieldList) > 5) {
9095 if ($InfoFieldList[0] ==
'categorie') {
9096 $filter_categorie =
true;
9100 $sql =
"SELECT ".$this->db->sanitize($keyList, 0, 0, 1);
9101 $sql .=
' FROM '.$this->db->prefix().$this->db->sanitize($InfoFieldList[0]);
9102 if (isset($InfoFieldList[4]) && strpos($InfoFieldList[4],
'extra') !==
false) {
9108 dol_syslog(get_class($this).
':showOutputField:$type=chkbxlst', LOG_DEBUG);
9109 $resql = $this->db->query($sql);
9111 if (!$filter_categorie) {
9114 while ($obj = $this->db->fetch_object($resql)) {
9116 $fields_label = explode(
'|', $InfoFieldList[1]);
9117 if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
9118 if (is_array($fields_label) && count($fields_label) > 1) {
9119 foreach ($fields_label as $field_toshow) {
9121 if (!empty($obj->$field_toshow)) {
9122 $translabel = $langs->trans($obj->$field_toshow);
9124 if ($translabel != $field_toshow) {
9125 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' .
dol_trunc($translabel, 18) .
'</li>';
9127 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' . $obj->$field_toshow .
'</li>';
9132 if (!empty($obj->{$InfoFieldList[1]})) {
9133 $translabel = $langs->trans($obj->{$InfoFieldList[1]});
9135 if ($translabel != $obj->{$InfoFieldList[1]}) {
9136 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' .
dol_trunc($translabel, 18) .
'</li>';
9138 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' . $obj->{$InfoFieldList[1]} .
'</li>';
9144 require_once DOL_DOCUMENT_ROOT .
'/categories/class/categorie.class.php';
9147 while ($obj = $this->db->fetch_object($resql)) {
9148 if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
9150 $c->fetch($obj->rowid);
9151 $ways =
$c->print_all_ways();
9152 foreach ($ways as $way) {
9153 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories"' . (
$c->color ?
' style="background: #' .
$c->color .
';"' :
' style="background: #aaa"') .
'>' .
img_object(
'',
'category') .
' ' . $way .
'</li>';
9158 $value =
'<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(
' ', $toprint).
'</ul></div>';
9160 dol_syslog(get_class($this).
'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
9162 } elseif ($type ==
'link') {
9167 $param_list = array_keys($param[
'options']);
9171 $InfoFieldList = explode(
":", $param_list[0]);
9173 $classname = $InfoFieldList[0];
9174 $classpath = $InfoFieldList[1];
9177 $getnomurlparam = 3;
9178 $getnomurlparam2 =
'';
9180 if (preg_match(
'/#getnomurlparam1=([^#]*)/', $param_list[0], $regtmp)) {
9181 $getnomurlparam = $regtmp[1];
9183 if (preg_match(
'/#getnomurlparam2=([^#]*)/', $param_list[0], $regtmp)) {
9184 $getnomurlparam2 = $regtmp[1];
9187 if (!empty($classpath)) {
9190 if ($classname && !class_exists($classname)) {
9193 $element_prop = getElementProperties($classname);
9194 if ($element_prop) {
9195 $classname = $element_prop[
'classname'];
9200 if ($classname && class_exists($classname)) {
9201 $object =
new $classname($this->db);
9202 '@phan-var-force CommonObject $object';
9203 if (
$object->element ===
'product') {
9204 '@phan-var-force Product $object';
9205 $result =
$object->fetch((
int) $value,
'',
'',
'', 0, 1, 1);
9207 $result =
$object->fetch($value);
9210 if (
$object->element ===
'product') {
9211 '@phan-var-force Product $object';
9212 $get_name_url_param_arr = array($getnomurlparam, $getnomurlparam2, 0, -1, 0,
'', 0);
9213 if (isset($val[
'get_name_url_params'])) {
9214 $get_name_url_params = explode(
':', $val[
'get_name_url_params']);
9215 if (!empty($get_name_url_params)) {
9216 $param_num_max = count($get_name_url_param_arr) - 1;
9217 foreach ($get_name_url_params as $param_num => $param_value) {
9218 if ($param_num > $param_num_max) {
9221 $get_name_url_param_arr[$param_num] = $param_value;
9229 $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]);
9231 $value =
$object->getNomUrl($getnomurlparam, $getnomurlparam2);
9238 dol_syslog(
'Error bad setup of extrafield', LOG_WARNING);
9239 return 'Error bad setup of extrafield';
9244 } elseif ($type ==
'password') {
9245 $value =
'<span class="opacitymedium">'.$langs->trans(
"Encrypted").
'</span>';
9247 } elseif ($type ==
'array') {
9248 if (is_array($value)) {
9249 $value = implode(
'<br>', $value);
9251 dol_syslog(__METHOD__.
' Expected array from dol_eval, but got '.gettype($value), LOG_ERR);
9252 return 'Error unexpected result from code evaluation';
9255 if (!empty($value) && preg_match(
'/^text/', (
string) $type) && !preg_match(
'/search_/', $keyprefix) && !empty($param[
'options'])) {
9256 $value = str_replace(
',',
"\n", $value);
9264 return is_null($out) ?
'' : $out;
9276 unset($this->validateFieldsErrors[$fieldKey]);
9290 $msg = $langs->trans(
"UnknownError");
9293 $this->error = $this->validateFieldsErrors[$fieldKey] = $msg;
9304 if (!empty($this->validateFieldsErrors[$fieldKey])) {
9305 return $this->validateFieldsErrors[$fieldKey];
9322 if (!class_exists(
'Validate')) {
9323 require_once DOL_DOCUMENT_ROOT .
'/core/class/validate.class.php';
9326 $this->clearFieldError($fieldKey);
9328 if (!array_key_exists($fieldKey, $fields) || !is_array($fields[$fieldKey])) {
9329 $this->setFieldError($fieldKey, $langs->trans(
'FieldNotFoundInObject'));
9333 $val = $fields[$fieldKey];
9336 $param[
'options'] = array();
9337 $type = $val[
'type'];
9340 if (isset($val[
'notnull']) && $val[
'notnull'] === 1) {
9354 if (preg_match(
'/varchar\((\d+)\)/', $type, $reg)) {
9356 $maxSize = (int) $reg[1];
9357 } elseif (preg_match(
'/varchar/', $type)) {
9361 if (!empty($val[
'arrayofkeyval']) && is_array($val[
'arrayofkeyval'])) {
9365 if (!empty($val[
'type']) && preg_match(
'/^integer:(.*):(.*)/i', $val[
'type'], $reg)) {
9369 if (!empty($val[
'arrayofkeyval']) && is_array($val[
'arrayofkeyval'])) {
9370 $param[
'options'] = $val[
'arrayofkeyval'];
9373 if (preg_match(
'/^integer:(.*):(.*)/i', $val[
'type'], $reg)) {
9375 $param[
'options'] = array($reg[1].
':'.$reg[2] => $reg[1].
':'.$reg[2]);
9376 } elseif (preg_match(
'/^sellist:(.*):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
9377 $param[
'options'] = array($reg[1].
':'.$reg[2].
':'.$reg[3].
':'.$reg[4] =>
'N');
9379 } elseif (preg_match(
'/^sellist:(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
9380 $param[
'options'] = array($reg[1].
':'.$reg[2].
':'.$reg[3] =>
'N');
9382 } elseif (preg_match(
'/^sellist:(.*):(.*)/i', $val[
'type'], $reg)) {
9383 $param[
'options'] = array($reg[1].
':'.$reg[2] =>
'N');
9392 $validate =
new Validate($this->db, $langs);
9402 if ($required && !$validate->isNotEmptyString($fieldValue)) {
9403 $this->setFieldError($fieldKey, $validate->error);
9405 } elseif (!$required && !$validate->isNotEmptyString($fieldValue)) {
9411 if (!empty($maxSize) && !$validate->isMaxLength($fieldValue, $maxSize)) {
9412 $this->setFieldError($fieldKey, $validate->error);
9417 if (!empty($minSize) && !$validate->isMinLength($fieldValue, $minSize)) {
9418 $this->setFieldError($fieldKey, $validate->error);
9426 if (in_array($type, array(
'date',
'datetime',
'timestamp'))) {
9427 if (!$validate->isTimestamp($fieldValue)) {
9428 $this->setFieldError($fieldKey, $validate->error);
9433 } elseif ($type ==
'duration') {
9434 if (!$validate->isDuration($fieldValue)) {
9435 $this->setFieldError($fieldKey, $validate->error);
9440 } elseif (in_array($type, array(
'double',
'real',
'price'))) {
9442 if (!$validate->isNumeric($fieldValue)) {
9443 $this->setFieldError($fieldKey, $validate->error);
9448 } elseif ($type ==
'boolean') {
9449 if (!$validate->isBool($fieldValue)) {
9450 $this->setFieldError($fieldKey, $validate->error);
9455 } elseif ($type ==
'mail' || $type ==
'email') {
9456 if (!$validate->isEmail($fieldValue)) {
9457 $this->setFieldError($fieldKey, $validate->error);
9460 } elseif ($type ==
'url') {
9461 if (!$validate->isUrl($fieldValue)) {
9462 $this->setFieldError($fieldKey, $validate->error);
9467 } elseif ($type ==
'phone') {
9468 if (!$validate->isPhone($fieldValue)) {
9469 $this->setFieldError($fieldKey, $validate->error);
9474 } elseif ($type ==
'select' || $type ==
'radio') {
9475 if (!isset($param[
'options'][$fieldValue])) {
9476 $this->error = $langs->trans(
'RequireValidValue');
9481 } elseif ($type ==
'sellist' || $type ==
'chkbxlst') {
9482 $param_list = array_keys($param[
'options']);
9483 $InfoFieldList = explode(
":", $param_list[0]);
9484 $value_arr = explode(
',', $fieldValue);
9486 $selectkey =
"rowid";
9487 if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
9488 $selectkey = $InfoFieldList[2];
9491 if (!$validate->isInDb($value_arr, $InfoFieldList[0], $selectkey)) {
9492 $this->setFieldError($fieldKey, $validate->error);
9497 } elseif ($type ==
'link') {
9498 $param_list = array_keys($param[
'options']);
9499 $InfoFieldList = explode(
":", $param_list[0]);
9500 $classname = $InfoFieldList[0];
9501 $classpath = $InfoFieldList[1];
9502 if (!$validate->isFetchable((
int) $fieldValue, $classname, $classpath)) {
9503 $lastIsFetchableError = $validate->error;
9506 if ($validate->isFetchableElement((
int) $fieldValue, $classname)) {
9510 $this->setFieldError($fieldKey, $lastIsFetchableError);
9534 public function showOptionals($extrafields, $mode =
'view', $params =
null, $keysuffix =
'', $keyprefix =
'', $onetrtd =
'', $display_type =
'card')
9536 global
$db,
$conf, $langs, $action, $form, $hookmanager;
9537 global $objectoffield;
9539 if (!is_object($form)) {
9542 if (!is_object($extrafields)) {
9543 dol_syslog(
'Bad parameter extrafields for showOptionals', LOG_ERR);
9544 return 'Bad parameter extrafields for showOptionals';
9546 if (!is_array($extrafields->attributes[$this->table_element])) {
9547 dol_syslog(
"extrafields->attributes was not loaded with extrafields->fetch_name_optionals_label(table_element);", LOG_WARNING);
9551 $objectoffield = $this;
9555 $parameters = array(
'mode' => $mode,
'params' => $params,
'keysuffix' => $keysuffix,
'keyprefix' => $keyprefix,
'display_type' => $display_type);
9556 $reshook = $hookmanager->executeHooks(
'showOptionals', $parameters, $this, $action);
9557 $hookResPrint = $hookmanager->resPrint;
9559 if (empty($reshook)) {
9560 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) {
9562 $out .=
'<!-- commonobject:showOptionals --> ';
9565 $nbofextrafieldsshown = 0;
9568 $lastseparatorkeyfound =
'';
9569 $extrafields_collapse_num =
'';
9570 $extrafields_collapse_num_old =
'';
9573 foreach ($extrafields->attributes[$this->table_element][
'label'] as $key => $label) {
9577 if (is_array($params) && array_key_exists(
'onlykey', $params) && $key != $params[
'onlykey']) {
9583 if ($enabled && isset($extrafields->attributes[$this->table_element][
'enabled'][$key])) {
9584 $enabled = (int)
dol_eval((
string) $extrafields->attributes[$this->table_element][
'enabled'][$key], 1, 1,
'2');
9586 if (empty($enabled)) {
9591 if (isset($extrafields->attributes[$this->table_element][
'list'][$key])) {
9592 $visibility = (int)
dol_eval((
string) $extrafields->attributes[$this->table_element][
'list'][$key], 1, 1,
'2');
9596 if ($perms && isset($extrafields->attributes[$this->table_element][
'perms'][$key])) {
9597 $perms = (int)
dol_eval((
string) $extrafields->attributes[$this->table_element][
'perms'][$key], 1, 1,
'2');
9600 if (($mode ==
'create') && !in_array(abs($visibility), array(1, 3))) {
9602 } elseif (($mode ==
'edit') && !in_array(abs($visibility), array(1, 3, 4))) {
9604 $ef_name =
'options_' . $key;
9605 $ef_value = $this->array_options[$ef_name] ??
'';
9606 $out .=
'<input type="hidden" name="' . $ef_name .
'" id="' . $ef_name .
'" value="' . $ef_value .
'" />' .
"\n";
9608 } elseif ($mode ==
'view' && empty($visibility)) {
9611 if (empty($perms)) {
9616 if (!empty($extrafields->attributes[$this->table_element][
'langfile'][$key])) {
9617 $langs->load($extrafields->attributes[$this->table_element][
'langfile'][$key]);
9622 if (is_array($params) && count($params) > 0 && $display_type ==
'card') {
9623 if (array_key_exists(
'cols', $params)) {
9624 $colspan = $params[
'cols'];
9625 } elseif (array_key_exists(
'colspan', $params)) {
9627 if (preg_match(
'/colspan="(\d+)"/', $params[
'colspan'], $reg)) {
9630 $colspan = $params[
'colspan'];
9634 $colspan = intval($colspan);
9638 $value = ((!empty($this->array_options) && array_key_exists(
"options_".$key.$keysuffix, $this->array_options)) ? $this->array_options[
"options_".$key.$keysuffix] :
null);
9644 $check =
'alphanohtml';
9645 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'html',
'text'))) {
9646 $check =
'restricthtml';
9648 $getposttemp =
GETPOST($keyprefix.
'options_'.$key.$keysuffix, $check, 3);
9650 if (is_array($getposttemp) || $getposttemp !=
'' || GETPOSTISSET($keyprefix.
'options_'.$key.$keysuffix)) {
9651 if (is_array($getposttemp)) {
9653 $value = implode(
",", $getposttemp);
9655 $value = $getposttemp;
9657 } elseif (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'int'))) {
9658 $value = (!empty($this->array_options[
"options_".$key]) || (isset($this->array_options[
"options_".$key]) && $this->array_options[
"options_".$key] ===
'0')) ? $this->array_options[
"options_".$key] :
'';
9659 } elseif (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'varchar',
'char'))) {
9660 $value = (isset($this->array_options[
"options_".$key]) && $this->array_options[
"options_".$key] !==
'') ? $this->array_options[
"options_".$key] :
'';
9662 $value = (!empty($this->array_options[
"options_".$key]) ? $this->array_options[
"options_".$key] :
'');
9668 $nbofextrafieldsshown++;
9671 if ($extrafields->attributes[$this->table_element][
'type'][$key] ==
'separate') {
9672 $extrafields_collapse_num = $key;
9690 $out .= $extrafields->showSeparator($key, $this, ($colspan ? $colspan + 1 : 2), $display_type, $mode);
9692 $lastseparatorkeyfound = $key;
9694 $collapse_group = $extrafields_collapse_num.(!empty($this->
id) ?
'_'.$this->id :
'');
9696 $class = (!empty($extrafields->attributes[$this->table_element][
'hidden'][$key]) ?
'hideobject ' :
'');
9698 if (is_array($params) && count($params) > 0) {
9699 if (array_key_exists(
'class', $params)) {
9700 $class .= $params[
'class'].
' ';
9702 if (array_key_exists(
'style', $params)) {
9703 $csstyle = $params[
'style'];
9708 $domData =
' data-element="extrafield"';
9709 $domData .=
' data-targetelement="'.$this->element.
'"';
9710 $domData .=
' data-targetid="'.$this->id.
'"';
9712 $html_id = (empty($this->
id) ?
'' :
'extrarow-'.$this->element.
'_'.$key.
'_'.
$this->id);
9713 if ($display_type ==
'card') {
9718 if ($action ==
'selectlines') {
9725 $force_values_on_change_company = (
9726 ($this->element ==
'facture' &&
getDolGlobalInt(
'THIRDPARTY_PROPAGATE_EXTRAFIELDS_TO_INVOICE'))
9727 || ($this->element ==
'commande' &&
getDolGlobalInt(
'THIRDPARTY_PROPAGATE_EXTRAFIELDS_TO_ORDER'))
9728 || ($this->element ==
'order_supplier' &&
getDolGlobalInt(
'THIRDPARTY_PROPAGATE_EXTRAFIELDS_TO_SUPPLIER_ORDER'))
9730 if ($force_values_on_change_company &&
GETPOSTINT(
'changecompany')) {
9731 $value = $this->array_options[
'options_'.$key] ?? $value;
9735 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'date'))) {
9736 $datenotinstring =
null;
9737 if (array_key_exists(
'options_'.$key, $this->array_options)) {
9738 $datenotinstring = $this->array_options[
'options_'.$key];
9739 if (!is_numeric($this->array_options[
'options_'.$key])) {
9740 $datenotinstring = $this->db->jdate($datenotinstring);
9743 $datekey = $keyprefix.
'options_'.$key.$keysuffix;
9746 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'datetime'))) {
9747 $datenotinstring =
null;
9748 if (array_key_exists(
'options_'.$key, $this->array_options)) {
9749 $datenotinstring = $this->array_options[
'options_'.$key];
9750 if (!is_numeric($this->array_options[
'options_'.$key])) {
9751 $datenotinstring = $this->db->jdate($datenotinstring);
9754 $timekey = $keyprefix.
'options_'.$key.$keysuffix;
9755 $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;
9758 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'price',
'double'))) {
9759 if (GETPOSTISSET($keyprefix.
'options_'.$key.$keysuffix) || $value) {
9761 } elseif (isset($this->array_options[
'options_'.$key])) {
9762 $value = $this->array_options[
'options_'.$key];
9767 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'html',
'text',
'varchar',
'select',
'radio',
'int',
'boolean'))) {
9768 if ($action ==
'create' || $mode ==
'create') {
9769 $value = (GETPOSTISSET($keyprefix.
'options_'.$key.$keysuffix) || $value) ? $value : $extrafields->attributes[$this->table_element][
'default'][$key];
9773 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'checkbox'))) {
9774 if ($action ==
'create') {
9775 $value = (GETPOSTISSET($keyprefix.
'options_'.$key.$keysuffix) || $value) ? $value : explode(
',', $extrafields->attributes[$this->table_element][
'default'][$key]);
9780 $labeltoshow = $langs->trans($label);
9781 $helptoshow = $langs->trans($extrafields->attributes[$this->table_element][
'help'][$key]);
9782 if ($display_type ==
'card') {
9783 $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.
' >';
9784 if (
getDolGlobalString(
'MAIN_VIEW_LINE_NUMBER') && ($action ==
'view' || $action ==
'valid' || $action ==
'editline' || $action ==
'confirm_valid' || $action ==
'confirm_cancel')) {
9785 $out .=
'<td></td>';
9787 $out .=
'<td class="'.(empty($params[
'tdclass']) ?
'titlefieldmax45' : $params[
'tdclass']).
' wordbreak';
9788 if ($extrafields->attributes[$this->table_element][
'type'][$key] ==
'text') {
9791 } elseif ($display_type ==
'line') {
9792 $out .=
'<div '.($html_id ?
'id="'.$html_id.
'" ' :
'').$csstyle.
' class="fieldline_options_'.$key.
' '.$class.$this->element.
'_extras_'.$key.
' trextrafields_collapse'.$collapse_group.
'" '.$domData.
' >';
9793 $out .=
'<div style="display: inline-block; padding-right:4px" class="wordbreak';
9798 $tpl_context = isset($params[
"tpl_context"]) ? $params[
"tpl_context"] :
"none";
9799 if ($tpl_context !=
"public") {
9800 if ($mode !=
'view' && !empty($extrafields->attributes[$this->table_element][
'required'][$key])) {
9801 $out .=
' fieldrequired';
9805 if ($tpl_context ==
"public") {
9806 if (!empty($extrafields->attributes[$this->table_element][
'help'][$key])) {
9807 $out .= $form->textwithpicto($labeltoshow, $helptoshow);
9809 $out .= $labeltoshow;
9811 if ($mode !=
'view' && !empty($extrafields->attributes[$this->table_element][
'required'][$key])) {
9812 $out .=
' <span style="color: red">*</span>';
9815 if (!empty($extrafields->attributes[$this->table_element][
'help'][$key])) {
9816 $out .= $form->textwithpicto($labeltoshow, $helptoshow);
9818 $out .= $labeltoshow;
9822 $out .= ($display_type ==
'card' ?
'</td>' :
'</div>');
9825 $html_id = !empty($this->
id) ? $this->element.
'_extras_'.$key.
'_'.$this->id :
'';
9826 if ($display_type ==
'card') {
9828 $out .=
'<td '.($html_id ?
'id="'.$html_id.
'" ' :
'').
' class="valuefieldcreate '.$this->element.
'_extras_'.$key;
9829 $out .=
'" '.($colspan ?
' colspan="'.$colspan.
'"' :
'');
9831 } elseif ($display_type ==
'line') {
9832 $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].
'">';
9837 $out .= $extrafields->showOutputField($key, $value,
'', $this->table_element);
9840 $listoftypestoshowpicto = explode(
',',
getDolGlobalString(
'MAIN_TYPES_TO_SHOW_PICTO',
'email,phone,ip,password'));
9841 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], $listoftypestoshowpicto)) {
9842 $out .=
getPictoForType($extrafields->attributes[$this->table_element][
'type'][$key], ($extrafields->attributes[$this->table_element][
'type'][$key] ==
'text' ?
'tdtop' :
''));
9845 $out .= $extrafields->showInputField($key, $value,
'', $keysuffix,
'',
'', $this, $this->table_element);
9848 $listoftypestoshowpicto = explode(
',',
getDolGlobalString(
'MAIN_TYPES_TO_SHOW_PICTO',
'email,phone,ip,password'));
9849 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], $listoftypestoshowpicto)) {
9850 $out .=
getPictoForType($extrafields->attributes[$this->table_element][
'type'][$key], ($extrafields->attributes[$this->table_element][
'type'][$key] ==
'text' ?
'tdtop' :
''));
9852 $out .= $extrafields->showInputField($key, $value,
'', $keysuffix,
'',
'', $this, $this->table_element);
9856 $out .= ($display_type ==
'card' ?
'</td>' :
'</div>');
9857 $out .= ($display_type ==
'card' ?
'</tr>'.
"\n" :
'</div>');
9863 if (!empty(
$conf->use_javascript_ajax)) {
9864 $out .= $this->getJSListDependancies();
9867 $out .=
'<!-- commonobject:showOptionals end --> '.
"\n";
9869 if (empty($nbofextrafieldsshown)) {
9875 $out .= $hookResPrint;
9887 <script nonce="'.getNonce().
'">
9888 jQuery(document).ready(function() {
9889 function showOptions'.$type.
'(child_list, parent_list, orig_select)
9891 var val = $("select[name=\""+parent_list+"\"]").val();
9892 var parentVal = parent_list + ":" + val;
9893 if(typeof val == "string"){
9895 var options = orig_select.find("option[parent=\""+parentVal+"\"]").clone();
9896 $("select[name=\""+child_list+"\"] option[parent]").remove();
9897 $("select[name=\""+child_list+"\"]").append(options);
9899 var options = orig_select.find("option[parent]").clone();
9900 $("select[name=\""+child_list+"\"] option[parent]").remove();
9901 $("select[name=\""+child_list+"\"]").append(options);
9903 } else if(val > 0) {
9904 var options = orig_select.find("option[parent=\""+parentVal+"\"]").clone();
9905 $("select[name=\""+child_list+"\"] option[parent]").remove();
9906 $("select[name=\""+child_list+"\"]").append(options);
9908 var options = orig_select.find("option[parent]").clone();
9909 $("select[name=\""+child_list+"\"] option[parent]").remove();
9910 $("select[name=\""+child_list+"\"]").append(options);
9913 function setListDependencies'.$type.
'() {
9914 jQuery("select option[parent]").parent().each(function() {
9915 var orig_select = {};
9916 var child_list = $(this).attr("name");
9917 orig_select[child_list] = $(this).clone();
9918 var parent = $(this).find("option[parent]:first").attr("parent");
9919 var infos = parent.split(":");
9920 var parent_list = infos[0];
9922 //Hide daughters lists
9923 if ($("#"+child_list).val() == 0 && $("#"+parent_list).val() == 0){
9924 $("#"+child_list).hide();
9926 } else if ($("#"+parent_list).val() != 0){
9927 $("#"+parent_list).show();
9929 //Show the child list if the parent list value is selected
9930 $("select[name=\""+parent_list+"\"]").click(function() {
9931 if ($(this).val() != 0){
9932 $("#"+child_list).show()
9936 //When we change parent list
9937 $("select[name=\""+parent_list+"\"]").change(function() {
9938 showOptions'.$type.
'(child_list, parent_list, orig_select[child_list]);
9939 //Select the value 0 on child list after a change on the parent list
9940 $("#"+child_list).val(0).trigger("change");
9941 //Hide child lists if the parent value is set to 0
9942 if ($(this).val() == 0){
9943 $("#"+child_list).hide();
9949 setListDependencies'.$type.
'();
9964 $module = empty($this->module) ?
'' : $this->module;
9965 $element = $this->element;
9967 if ($element ==
'facturerec') {
9968 $element =
'facture';
9969 } elseif ($element ==
'invoice_supplier_rec') {
9970 return !$user->hasRight(
'fournisseur',
'facture') ? null : $user->hasRight(
'fournisseur',
'facture');
9971 } elseif ($module && $user->hasRight($module, $element)) {
9973 return $user->hasRight($module, $element);
9976 return $user->rights->$element;
9993 global $hookmanager;
9995 $parameters = array(
9996 'origin_id' => $origin_id,
9997 'dest_id' => $dest_id,
9998 'tables' => $tables,
10000 $reshook = $hookmanager->executeHooks(
'commonReplaceThirdparty', $parameters);
10003 } elseif ($reshook < 0) {
10004 return $ignoreerrors === 1;
10007 foreach ($tables as $table) {
10008 $sql =
'UPDATE '.$dbs->prefix().$table.
' SET fk_soc = '.((int) $dest_id).
' WHERE fk_soc = '.((int) $origin_id);
10010 if (!$dbs->
query($sql)) {
10011 if ($ignoreerrors) {
10036 foreach ($tables as $table) {
10037 $sql =
'UPDATE '.MAIN_DB_PREFIX.$table.
' SET fk_product = '.((int) $dest_id).
' WHERE fk_product = '.((int) $origin_id);
10039 if (!$dbs->
query($sql)) {
10040 if ($ignoreerrors) {
10063 public function defineBuyPrice($unitPrice = 0.0, $discountPercent = 0.0, $fk_product = 0)
10069 if (($unitPrice > 0) && (isset(
$conf->global->ForceBuyingPriceIfNull) &&
getDolGlobalInt(
'ForceBuyingPriceIfNull') > 0)) {
10071 $buyPrice = $unitPrice * (1 - $discountPercent / 100);
10074 if (!empty($fk_product) && $fk_product > 0) {
10077 require_once DOL_DOCUMENT_ROOT.
'/product/class/product.class.php';
10078 $product =
new Product($this->db);
10079 $result = $product->fetch($fk_product);
10080 if ($result <= 0) {
10081 $this->errors[] =
'ErrorProductIdDoesNotExists';
10084 if ($product->cost_price > 0) {
10085 $buyPrice = $product->cost_price;
10086 } elseif ($product->pmp > 0) {
10087 $buyPrice = $product->pmp;
10090 require_once DOL_DOCUMENT_ROOT.
'/product/class/product.class.php';
10091 $product =
new Product($this->db);
10092 $result = $product->fetch($fk_product);
10093 if ($result <= 0) {
10094 $this->errors[] =
'ErrorProductIdDoesNotExists';
10097 if ($product->pmp > 0) {
10098 $buyPrice = $product->pmp;
10102 if (empty($buyPrice) && in_array(
getDolGlobalString(
'MARGIN_TYPE'), array(
'1',
'pmp',
'costprice'))) {
10103 require_once DOL_DOCUMENT_ROOT.
'/fourn/class/fournisseur.product.class.php';
10105 if (($result = $productFournisseur->find_min_price_product_fournisseur($fk_product)) > 0) {
10106 $buyPrice = $productFournisseur->fourn_unitprice;
10107 } elseif ($result < 0) {
10108 $this->errors[] = $productFournisseur->error;
10115 return (
float) $buyPrice;
10128 return array(
'dir' =>
'',
'file' =>
'',
'originalfile' =>
'',
'altfile' =>
'',
'email' =>
'',
'capture' =>
'');
10152 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')
10155 global $user, $langs;
10157 include_once DOL_DOCUMENT_ROOT.
'/core/lib/files.lib.php';
10158 include_once DOL_DOCUMENT_ROOT.
'/core/lib/images.lib.php';
10159 include_once DOL_DOCUMENT_ROOT.
'/core/class/link.class.php';
10161 $sortfield =
'position_name';
10162 $sortorder =
'asc';
10167 $dir .=
get_exdir(0, 0, 0, 0, $this, $modulepart);
10168 $pdir .=
get_exdir(0, 0, 0, 0, $this, $modulepart);
10171 if ($modulepart ==
'product') {
10173 $dir = $sdir.
'/'.
get_exdir($this->
id, 2, 0, 0, $this, $modulepart).$this->id.
"/photos/";
10174 $pdir =
'/'.get_exdir($this->
id, 2, 0, 0, $this, $modulepart).$this->id.
"/photos/";
10177 if ($modulepart ==
'category') {
10178 $dir = $sdir.
'/'.
get_exdir($this->
id, 2, 0, 0, $this, $modulepart).$this->id.
"/photos/";
10179 $pdir =
'/'.get_exdir($this->
id, 2, 0, 0, $this, $modulepart).$this->id.
"/photos/";
10185 $relativedir = preg_replace(
'/^'.preg_quote(DOL_DATA_ROOT,
'/').
'/',
'', $dir);
10186 $relativedir = preg_replace(
'/^[\\/]/',
'', $relativedir);
10187 $relativedir = preg_replace(
'/[\\/]$/',
'', $relativedir);
10190 $dirthumb = $dir.
'thumbs/';
10191 $pdirthumb = $pdir.
'thumbs/';
10193 $return =
'<!-- Photo -->'.
"\n";
10196 $filearray =
dol_dir_list($dir,
"files", 0,
'',
'(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) ==
'desc' ? SORT_DESC : SORT_ASC), 1);
10205 '@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';
10207 $useLinkPathPhoto =
false;
10210 $link =
new Link($this->db);
10212 $link->fetchAll($links,
'product', $this->
id);
10214 if (count($links) > 0) {
10215 $useLinkPathPhoto =
true;
10218 if ($useLinkPathPhoto) {
10220 if ($nbbyrow > 0) {
10221 $return .=
'<table class="valigntop center centpercent" style="border:0; padding:2px; border-spacing:2px; border-collapse: separate;">';
10225 foreach ($links as $link) {
10226 if (!empty($link->url) && preg_match(
'/\.(jpg|jpeg|png|gif|webp)$/i', $link->url)) {
10231 if ($nbbyrow > 0 && ($i % $nbbyrow == 1)) {
10232 $return .=
'<tr class="center valignmiddle">';
10235 if ($nbbyrow > 0) {
10236 $return .=
'<td style="width:'.ceil(100 / $nbbyrow).
'%" class="photo">';
10238 $return .=
'<div class="inline-block">';
10241 $return .=
'<img class="photo photowithmargin'.($addphotorefcss ?
' '.$addphotorefcss :
'').
'"'.($maxHeight ?
' height="'.$maxHeight.
'"' :
'').
' src="'.$url.
'" title="External image">';
10243 if ($nbbyrow > 0) {
10244 $return .=
'</td>';
10245 if ($i % $nbbyrow == 0) {
10246 $return .=
'</tr>';
10249 $return .=
'</div>';
10252 if ($nbmax && $nbphoto >= $nbmax) {
10258 if ($nbbyrow > 0) {
10259 while ($i % $nbbyrow) {
10260 $return .=
'<td style="width:'.ceil(100 / $nbbyrow).
'%"> </td>';
10264 $return .=
'</table>';
10270 if (count($filearray)) {
10271 if ($sortfield && $sortorder) {
10272 $filearray =
dol_sort_array($filearray, $sortfield, $sortorder);
10275 foreach ($filearray as $key => $val) {
10277 $file = $val[
'name'];
10283 $viewfilename = $file;
10285 if ($size == 1 || $size ==
'small') {
10287 $photo_vignette = basename(getImageFileNameForSize($dir.$file,
'_small'));
10291 $pdirthumb = $pdir;
10292 $photo_vignette = basename($file);
10298 if ($nbbyrow > 0) {
10299 if ($nbphoto == 1) {
10300 $return .=
'<table class="valigntop center centpercent" style="border: 0; padding: 2px; border-spacing: 2px; border-collapse: separate;">';
10303 if ($nbphoto % $nbbyrow == 1) {
10304 $return .=
'<tr class="center valignmiddle" style="border: 1px">';
10306 $return .=
'<td style="width: '.ceil(100 / $nbbyrow).
'%" class="photo">'.
"\n";
10307 } elseif ($nbbyrow < 0) {
10308 $return .=
'<div class="inline-block">'.
"\n";
10311 $relativefile = preg_replace(
'/^\//',
'', $pdir.$photo);
10312 if (empty($nolink)) {
10313 $urladvanced = getAdvancedPreviewUrl($modulepart, $relativefile, 0,
'entity='.$this->entity);
10314 if ($urladvanced) {
10315 $return .=
'<a href="'.$urladvanced.
'">';
10317 $return .=
'<a href="'.DOL_URL_ROOT.
'/viewimage.php?modulepart='.$modulepart.
'&entity='.$this->entity.
'&file='.urlencode($pdir.$photo).
'" class="aphoto" target="_blank" rel="noopener noreferrer">';
10323 $alt = $langs->transnoentitiesnoconv(
'File').
': '.$relativefile;
10324 $alt .=
' - '.$langs->transnoentitiesnoconv(
'Size').
': '.$imgarray[
'width'].
'x'.$imgarray[
'height'];
10325 if ($overwritetitle) {
10326 if (is_numeric($overwritetitle)) {
10329 $alt = $overwritetitle;
10332 if (empty($cache) && !empty($val[
'label'])) {
10335 $cache = $val[
'label'];
10337 if ($usesharelink) {
10338 if (array_key_exists(
'share', $val) && $val[
'share']) {
10339 if (empty($maxHeight) || ($photo_vignette && $imgarray[
'height'] > $maxHeight)) {
10340 $return .=
'<!-- Show original file (thumb not yet available with shared links) -->';
10341 $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).
'">';
10343 $return .=
'<!-- Show original file -->';
10344 $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).
'">';
10347 $return .=
'<!-- Show nophoto file (because file is not shared) -->';
10348 $return .=
'<img class="photo photowithmargin'.($addphotorefcss ?
' '.$addphotorefcss :
'').
'" height="'.$maxHeight.
'" src="'.DOL_URL_ROOT.
'/public/theme/common/nophoto.png" title="'.
dol_escape_htmltag($alt).
'">';
10351 if (empty($maxHeight) || ($photo_vignette && $imgarray[
'height'] > $maxHeight)) {
10352 $return .=
'<!-- Show thumb -->';
10353 $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).
'">';
10355 $return .=
'<!-- Show original file -->';
10356 $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).
'">';
10360 if (empty($nolink)) {
10364 if ($showfilename) {
10365 $return .=
'<br>'.$viewfilename;
10370 if ($photo_vignette && (
image_format_supported($photo) > 0) && ((isset($imgarray[
'width']) && $imgarray[
'width'] > $maxWidth) || (isset($imgarray[
'width']) && $imgarray[
'width'] > $maxHeight))) {
10371 $return .=
'<a href="'.$_SERVER[
"PHP_SELF"].
'?id='.$this->
id.
'&action=addthumb&token='.newToken().
'&file='.urlencode($pdir.$viewfilename).
'">'.
img_picto($langs->trans(
'GenerateThumb'),
'refresh').
' </a>';
10374 if ($modulepart ==
'product' && ($user->hasRight(
'produit',
'creer') || $user->hasRight(
'service',
'creer'))) {
10376 $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> ';
10379 $return .=
'<a href="'.$_SERVER[
"PHP_SELF"].
'?id='.$this->
id.
'&action=delete&token='.newToken().
'&file='.urlencode($pdir.$viewfilename).
'">';
10385 if ($nbbyrow > 0) {
10386 $return .=
'</td>';
10387 if (($nbphoto % $nbbyrow) == 0) {
10388 $return .=
'</tr>';
10390 } elseif ($nbbyrow < 0) {
10391 $return .=
'</div>'.
"\n";
10395 if (empty($size)) {
10396 $return .=
'<img class="photo photowithmargin" src="'.DOL_URL_ROOT.
'/viewimage.php?modulepart='.$modulepart.
'&entity='.$this->entity.
'&file='.urlencode($pdir.$photo).
'">';
10398 if ($showfilename) {
10399 $return .=
'<br>'.$viewfilename;
10403 if ($modulepart ==
'product' && ($user->hasRight(
'produit',
'creer') || $user->hasRight(
'service',
'creer'))) {
10405 $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> ';
10408 $return .=
'<a href="'.$_SERVER[
"PHP_SELF"].
'?id='.$this->
id.
'&action=delete&token='.newToken().
'&file='.urlencode($pdir.$viewfilename).
'">';
10415 if ($nbmax && $nbphoto >= $nbmax) {
10421 if ($size == 1 || $size ==
'small') {
10422 if ($nbbyrow > 0) {
10424 while ($nbphoto % $nbbyrow) {
10425 $return .=
'<td style="width: '.ceil(100 / $nbbyrow).
'%"> </td>';
10430 $return .=
'</table>';
10436 $this->nbphoto = $nbphoto;
10450 if (is_array($info)) {
10451 if (isset($info[
'type']) && $info[
'type'] ==
'array') {
10468 if (isset($info[
'type']) && ($info[
'type'] ==
'date' || $info[
'type'] ==
'datetime' || $info[
'type'] ==
'timestamp')) {
10482 if (is_array($info)) {
10483 if (isset($info[
'type']) && ($info[
'type'] ==
'duration')) {
10501 if (is_array($info)) {
10502 if (isset($info[
'type']) && (preg_match(
'/(^int|int$)/i', $info[
'type']))) {
10520 if (is_array($info)) {
10521 if (isset($info[
'type']) && (preg_match(
'/^(double|real|price)/i', $info[
'type']))) {
10538 if (is_array($info)) {
10539 if (isset($info[
'type']) && $info[
'type'] ==
'text') {
10556 if (is_array($info)) {
10557 if (array_key_exists(
'notnull', $info) && $info[
'notnull'] !=
'1') {
10574 if (is_array($info)) {
10575 if (array_key_exists(
'notnull', $info) && $info[
'notnull'] ==
'-1') {
10592 if (is_array($info)) {
10593 if (array_key_exists(
'index', $info) && $info[
'index'] ==
true) {
10615 $queryarray = array();
10616 foreach ($this->fields as $field => $info) {
10618 if ($this->isDate($info)) {
10619 if (empty($this->{$field})) {
10620 $queryarray[$field] =
null;
10622 $queryarray[$field] = $this->db->idate($this->{$field});
10624 } elseif ($this->isDuration($info)) {
10626 if ((isset($this->{$field}) && $this->{$field} !=
'') || !empty($info[
'notnull'])) {
10627 if (!isset($this->{$field})) {
10628 if (!empty($info[
'default'])) {
10629 $queryarray[$field] = $info[
'default'];
10631 $queryarray[$field] = 0;
10634 $queryarray[$field] = (int) $this->{$field};
10637 $queryarray[$field] =
null;
10639 } elseif ($this->isInt($info) || $this->isFloat($info)) {
10640 if ($field ==
'entity' && is_null($this->{$field})) {
10641 $queryarray[$field] = ((int)
$conf->entity);
10644 if ((isset($this->{$field}) && ((
string) $this->{$field}) !=
'') || !empty($info[
'notnull'])) {
10645 if (!isset($this->{$field})) {
10646 $queryarray[$field] = 0;
10647 } elseif ($this->isInt($info)) {
10648 $queryarray[$field] = (int) $this->{$field};
10649 } elseif ($this->isFloat($info)) {
10650 $queryarray[$field] = (float) $this->{$field};
10653 $queryarray[$field] =
null;
10659 $queryarray[$field] = $this->{$field};
10662 if (array_key_exists(
'type', $info) && $info[
'type'] ==
'timestamp' && empty($queryarray[$field])) {
10663 unset($queryarray[$field]);
10665 if (!empty($info[
'notnull']) && $info[
'notnull'] == -1 && empty($queryarray[$field])) {
10666 $queryarray[$field] =
null;
10670 return $queryarray;
10683 foreach ($this->fields as $field => $info) {
10684 if ($this->isDate($info)) {
10685 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') {
10686 $this->$field =
'';
10688 $this->$field =
$db->jdate($obj->$field);
10690 } elseif ($this->isInt($info)) {
10691 if ($field ==
'rowid') {
10692 $this->
id = (int) $obj->$field;
10694 if ($this->isForcedToNullIfZero($info)) {
10695 if (empty($obj->$field)) {
10696 $this->$field =
null;
10698 $this->$field = (int) $obj->$field;
10701 if (isset($obj->$field) && (!is_null($obj->$field) || (array_key_exists(
'notnull', $info) && $info[
'notnull'] == 1))) {
10702 $this->$field = (int) $obj->$field;
10704 $this->$field =
null;
10708 } elseif ($this->isFloat($info)) {
10709 if ($this->isForcedToNullIfZero($info)) {
10710 if (empty($obj->$field)) {
10711 $this->$field =
null;
10713 $this->$field = (float) $obj->$field;
10716 if (isset($obj->$field) && (!is_null($obj->$field) || (array_key_exists(
'notnull', $info) && $info[
'notnull'] == 1))) {
10717 $this->$field = (float) $obj->$field;
10719 $this->$field =
null;
10723 $this->$field = isset($obj->$field) ? $obj->$field :
null;
10728 if (!isset($this->fields[
'ref']) && isset($this->
id)) {
10739 foreach ($this->fields as $field => $arr) {
10740 $this->$field =
null;
10753 $keys = array_keys($this->fields);
10754 if (!empty($alias)) {
10755 $keys_with_alias = array();
10756 foreach ($keys as $fieldname) {
10757 if (!empty($excludefields)) {
10758 if (in_array($fieldname, $excludefields)) {
10762 $keys_with_alias[] = $this->db->sanitize($alias .
'.' . $fieldname);
10764 return implode(
', ', $keys_with_alias);
10766 return implode(
', ', $keys);
10777 protected function quote($value, $fieldsentry)
10779 if (is_null($value)) {
10781 } elseif (preg_match(
'/^(int|double|real|price)/i', $fieldsentry[
'type'])) {
10783 } elseif (preg_match(
'/int$/i', $fieldsentry[
'type'])) {
10784 return (
int) $value;
10785 } elseif ($fieldsentry[
'type'] ==
'boolean') {
10792 return "'".$this->db->escape($value).
"'";
10809 dol_syslog(get_class($this).
"::createCommon create", LOG_DEBUG);
10815 $fieldvalues = $this->setSaveQuery();
10819 if (array_key_exists(
'date_creation', $fieldvalues) && empty($fieldvalues[
'date_creation'])) {
10820 $fieldvalues[
'date_creation'] = $this->db->idate($now);
10821 $this->date_creation = $this->db->idate($now);
10824 if (array_key_exists(
'fk_user_creat', $fieldvalues) && !($fieldvalues[
'fk_user_creat'] > 0)) {
10825 $fieldvalues[
'fk_user_creat'] = $user->id;
10826 $this->fk_user_creat = $user->id;
10828 if (array_key_exists(
'user_creation_id', $fieldvalues) && !($fieldvalues[
'user_creation_id'] > 0)) {
10829 $fieldvalues[
'user_creation_id'] = $user->id;
10830 $this->user_creation_id = $user->id;
10832 if (array_key_exists(
'pass_crypted', $fieldvalues) && property_exists($this,
'pass')) {
10834 $tmparray =
dol_hash($this->pass,
'0', 0, 1);
10835 $fieldvalues[
'pass_crypted'] = $tmparray[
'pass_encrypted'];
10836 if (array_key_exists(
'pass_encoding', $fieldvalues) && property_exists($this,
'pass_encoding')) {
10837 $fieldvalues[
'pass_encoding'] = $tmparray[
'pass_encoding'];
10840 if (array_key_exists(
'ref', $fieldvalues)) {
10843 if (
getDolGlobalString(
'MAIN_DISABLE_AUTO_UPDATE_OF_TMS_FIELDS') && array_key_exists(
'tms', $fieldvalues)) {
10844 $fieldvalues[
'tms'] = $this->db->idate($now);
10847 unset($fieldvalues[
'rowid']);
10851 foreach ($fieldvalues as $k => $v) {
10853 $value = $this->fields[$k];
10855 $values[$k] = $this->quote($v, $value);
10859 foreach ($keys as $key) {
10860 if (!isset($this->fields[$key])) {
10863 $key_fields = $this->fields[$key];
10866 if (preg_match(
'/^integer:/i', $key_fields[
'type']) && $values[$key] ==
'-1') {
10867 $values[$key] =
'';
10869 if (!empty($key_fields[
'foreignkey']) && $values[$key] ==
'-1') {
10870 $values[$key] =
'';
10873 if (isset($key_fields[
'notnull']) && $key_fields[
'notnull'] == 1 && (!isset($values[$key]) || $values[$key] ===
'NULL') && (!isset($key_fields[
'default']) || is_null($key_fields[
'default']))) {
10876 if (empty($langs)) {
10877 require_once DOL_DOCUMENT_ROOT.
'/core/class/translate.class.php';
10879 $langs->setDefaultLang();
10880 $langs->load(
"errors");
10882 dol_syslog(
"Mandatory field '".$key.
"' is empty and required into ->fields definition of class");
10883 $this->errors[] = $langs->trans(
"ErrorFieldRequired", isset($key_fields[
'label']) ? $key_fields[
'label'] : $key);
10887 if (isset($key_fields[
'notnull']) && $key_fields[
'notnull'] == 1 && (!isset($values[$key]) || $values[$key] ===
'NULL') && array_key_exists(
'default', $key_fields) && !is_null($key_fields[
'default'])) {
10888 $values[$key] = $this->quote($key_fields[
'default'], $key_fields);
10892 if (isset($key_fields[
'type']) && preg_match(
'/^integer:/i', $key_fields[
'type']) && empty($values[$key])) {
10893 if (isset($key_fields[
'default'])) {
10894 $values[$key] = ((int) $key_fields[
'default']);
10896 $values[$key] =
'null';
10899 if (!empty($key_fields[
'foreignkey']) && empty($values[$key])) {
10900 $values[$key] =
'null';
10908 $this->db->begin();
10911 $sql =
"INSERT INTO ".$this->db->prefix().$this->table_element;
10912 $sql .=
" (".implode(
", ", $keys).
')';
10913 $sql .=
" VALUES (".implode(
", ", $values).
")";
10915 $res = $this->db->query($sql);
10918 if ($this->db->lasterrno() ==
'DB_ERROR_RECORD_ALREADY_EXISTS') {
10919 $this->errors[] =
"ErrorRefAlreadyExists";
10921 $this->errors[] = $this->db->lasterror();
10927 $this->
id = $this->db->last_insert_id($this->db->prefix().$this->table_element);
10933 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)') {
10934 $sql =
"UPDATE ".$this->db->prefix().$this->table_element.
" SET ref = '(PROV".((int) $this->
id).
")' WHERE (ref = '(PROV)' OR ref = '') AND rowid = ".((int) $this->
id);
10935 $resqlupdate = $this->db->query($sql);
10937 if ($resqlupdate ===
false) {
10939 $this->errors[] = $this->db->lasterror();
10941 $this->
ref =
'(PROV'.$this->id.
')';
10948 $result = $this->insertExtraFields();
10955 if (!empty($this->table_element_line) && !empty($this->fk_element) && !empty($this->lines)) {
10956 foreach ($this->lines as $line) {
10957 $keyforparent = $this->fk_element;
10962 if (!is_object($line)) {
10963 $line = (object) $line;
10967 if (method_exists($line,
'insert')) {
10968 $result = $line->insert($user, 1);
10969 } elseif (method_exists($line,
'create')) {
10970 $result = $line->create($user, 1);
10973 $this->error = $line->error;
10974 $this->db->rollback();
10981 if (!$error && !$notrigger) {
10983 $result = $this->call_trigger(strtoupper(get_class($this)).
'_CREATE', $user);
10992 $this->db->rollback();
10995 $this->db->commit();
11012 if (empty(
$id) && empty($ref) && empty($morewhere)) {
11016 $fieldlist = $this->getFieldList(
't');
11017 if (empty($fieldlist)) {
11021 $sql =
"SELECT ".$this->db->sanitize($fieldlist, 0, 0, 1);
11022 $sql .=
" FROM ".$this->db->prefix().$this->table_element.
' as t';
11025 $sql .=
' WHERE t.rowid = '.((int)
$id);
11026 } elseif (!empty($ref)) {
11027 $sql .=
" WHERE t.ref = '".$this->db->escape($ref).
"'";
11029 $sql .=
' WHERE 1 = 1';
11031 if (empty(
$id) && isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
11032 $sql .=
' AND t.entity IN ('.getEntity($this->element).
')';
11035 $sql .= $morewhere;
11037 $sql .=
' LIMIT 1';
11039 $res = $this->db->query($sql);
11041 $obj = $this->db->fetch_object($res);
11043 $this->setVarsFromFetchObj($obj);
11047 if (empty($noextrafields)) {
11048 $result = $this->fetch_optionals();
11050 $this->error = $this->db->lasterror();
11051 $this->errors[] = $this->error;
11061 $this->error = $this->db->lasterror();
11062 $this->errors[] = $this->error;
11076 $objectlineclassname = get_class($this).
'Line';
11077 if (!class_exists($objectlineclassname)) {
11078 $this->error =
'Error, class '.$objectlineclassname.
' not found during call of fetchLinesCommon';
11082 $objectline =
new $objectlineclassname($this->db);
11083 '@phan-var-force CommonObjectLine $objectline';
11085 $sql =
"SELECT ".$objectline->getFieldList(
'l');
11086 $sql .=
" FROM ".$this->db->prefix().$objectline->table_element.
" as l";
11087 $sql .=
" WHERE l.fk_".$this->db->escape($this->element).
" = ".((int) $this->
id);
11089 $sql .= $morewhere;
11091 if (isset($objectline->fields[
'position'])) {
11092 $sql .= $this->db->order(
'position',
'ASC');
11095 $resql = $this->db->query($sql);
11097 $num_rows = $this->db->num_rows($resql);
11099 $this->lines = array();
11100 while ($i < $num_rows) {
11101 $obj = $this->db->fetch_object($resql);
11103 $newline =
new $objectlineclassname($this->db);
11104 '@phan-var-force CommonObjectLine $newline';
11105 $newline->setVarsFromFetchObj($obj);
11108 if (empty($noextrafields)) {
11109 $newline->fetch_optionals();
11112 $this->lines[] = $newline;
11119 $this->error = $this->db->lasterror();
11120 $this->errors[] = $this->error;
11134 dol_syslog(get_class($this).
"::updateCommon update", LOG_DEBUG);
11146 $fieldvalues = $this->setSaveQuery();
11150 if (array_key_exists(
'date_modification', $fieldvalues)) {
11151 $fieldvalues[
'date_modification'] = $this->db->idate($now);
11153 if (
getDolGlobalString(
'MAIN_DISABLE_AUTO_UPDATE_OF_TMS_FIELDS') && array_key_exists(
'tms', $fieldvalues)) {
11154 $fieldvalues[
'tms'] = $this->db->idate($now);
11156 if (array_key_exists(
'fk_user_modif', $fieldvalues)) {
11157 $fieldvalues[
'fk_user_modif'] = $user->id;
11159 if (array_key_exists(
'user_modification_id', $fieldvalues)) {
11160 $fieldvalues[
'user_modification_id'] = $user->id;
11163 if (array_key_exists(
'pass_crypted', $fieldvalues) && property_exists($this,
'pass') && !empty($this->pass)) {
11165 $tmparray =
dol_hash($this->pass,
'0', 0, 1);
11166 $fieldvalues[
'pass_crypted'] = $tmparray[
'pass_encrypted'];
11167 if (array_key_exists(
'pass_encoding', $fieldvalues) && property_exists($this,
'pass_encoding')) {
11168 $fieldvalues[
'pass_encoding'] = $tmparray[
'pass_encoding'];
11171 if (array_key_exists(
'ref', $fieldvalues)) {
11175 unset($fieldvalues[
'rowid']);
11181 foreach ($fieldvalues as $k => $v) {
11183 $value = $this->fields[$k];
11185 $values[$k] = $this->quote($v, $value);
11186 if (($value[
"type"] ==
"text") && !empty($value[
'arrayofkeyval']) && is_array($value[
'arrayofkeyval'])) {
11188 $v = preg_replace(
'/\s/',
',', $v);
11189 $v = preg_replace(
'/,+/',
',', $v);
11192 $tmp[] = $k.
'='.$this->quote($v, $this->fields[$k]);
11196 foreach ($keys as $key) {
11197 if (preg_match(
'/^integer:/i', $this->fields[$key][
'type']) && $values[$key] ==
'-1') {
11198 $values[$key] =
'';
11200 if (!empty($this->fields[$key][
'foreignkey']) && $values[$key] ==
'-1') {
11201 $values[$key] =
'';
11213 $sql =
'UPDATE '.$this->db->prefix().$this->table_element.
' SET '.implode(
', ', $tmp).
' WHERE rowid='.((int) $this->
id);
11215 $this->db->begin();
11218 $res = $this->db->query($sql);
11221 $this->errors[] = $this->db->lasterror();
11227 $result = $this->insertExtraFields();
11234 if (!$error && !$notrigger) {
11236 $result = $this->call_trigger(strtoupper(get_class($this)).
'_MODIFY', $user);
11245 $this->db->rollback();
11248 $this->db->commit();
11263 dol_syslog(get_class($this).
"::deleteCommon delete", LOG_DEBUG);
11267 $this->db->begin();
11269 if ($forcechilddeletion) {
11270 foreach ($this->childtables as $table) {
11271 $sql =
"DELETE FROM ".$this->db->prefix().$this->db->sanitize($table).
" WHERE ".$this->db->sanitize($this->fk_element).
" = ".((int) $this->
id);
11272 $resql = $this->db->query($sql);
11274 $this->error = $this->db->lasterror();
11275 $this->errors[] = $this->error;
11276 $this->db->rollback();
11280 } elseif (!empty($this->childtables)) {
11281 $objectisused = $this->isObjectUsed($this->
id);
11282 if (!empty($objectisused)) {
11283 dol_syslog(get_class($this).
"::deleteCommon Can't delete record as it has some child", LOG_WARNING);
11284 $this->error =
'ErrorRecordHasChildren';
11285 $this->errors[] = $this->error;
11286 $this->db->rollback();
11292 if (is_array($this->childtablesoncascade) && !empty($this->childtablesoncascade)) {
11293 foreach ($this->childtablesoncascade as $tabletodelete) {
11294 $deleteFromObject = explode(
':', $tabletodelete, 4);
11295 if (count($deleteFromObject) >= 2) {
11296 $className = str_replace(
'@',
'', $deleteFromObject[0]);
11297 $filePath = $deleteFromObject[1];
11298 $columnName = $deleteFromObject[2];
11300 if (!empty($deleteFromObject[3])) {
11301 $filter = $deleteFromObject[3];
11305 $childObject =
new $className($this->db);
11306 if (method_exists($childObject,
'deleteByParentField')) {
11307 '@phan-var-force CommonObject $childObject';
11308 $result = $childObject->deleteByParentField($this->
id, $columnName, $filter);
11311 $this->errors[] = $childObject->error;
11316 $this->errors[] =
"You defined a cascade delete on an object $className/$this->id but there is no method deleteByParentField for it";
11321 $this->errors[] =
'Cannot include child class file '.$filePath;
11326 $sql =
"DELETE FROM ".$this->db->prefix().$this->db->sanitize($tabletodelete).
" WHERE ".$this->db->sanitize($this->fk_element).
" = ".((int) $this->
id);
11328 $resql = $this->db->query($sql);
11331 $this->error = $this->db->lasterror();
11332 $this->errors[] = $this->error;
11342 $result = $this->call_trigger(strtoupper(get_class($this)).
'_DELETE', $user);
11352 $res = $this->deleteEcmFiles(1);
11361 require_once DOL_DOCUMENT_ROOT .
'/core/lib/files.lib.php';
11364 $this->errors[] =
'ErrorFailToDeleteDir';
11370 $res = $this->deleteObjectLinked();
11375 if (!$error && !empty($this->isextrafieldmanaged)) {
11376 $result = $this->deleteExtraFields();
11383 $sql =
'DELETE FROM '.$this->db->prefix().$this->table_element.
' WHERE rowid='.((int) $this->
id);
11385 $resql = $this->db->query($sql);
11388 $this->errors[] = $this->db->lasterror();
11394 $this->db->rollback();
11397 $this->db->commit();
11422 if (!empty($parentId) && !empty($parentField)) {
11423 if (empty($this->table_element)) {
11424 $this->error =
'Property table_element for object is not defined';
11425 $this->errors[] = $this->error;
11429 if (!method_exists($this,
'fetch')) {
11430 $this->error =
'Method fetch for object is not defined';
11431 $this->errors[] = $this->error;
11435 if (!method_exists($this,
'delete')) {
11436 $this->error =
'Method delete for object is not defined';
11437 $this->errors[] = $this->error;
11442 $this->db->begin();
11444 $sql =
"SELECT rowid FROM ".$this->db->prefix().$this->table_element;
11445 $sql .=
" WHERE ".$this->db->sanitize($parentField).
" = ".(int) $parentId;
11448 $errormessage =
'';
11449 $sql .= forgeSQLFromUniversalSearchCriteria($filter, $errormessage);
11450 if ($errormessage) {
11451 $this->errors[] = $errormessage;
11452 dol_syslog(__METHOD__.
' '.implode(
',', $this->errors), LOG_ERR);
11456 $resql = $this->db->query($sql);
11458 $this->errors[] = $this->db->lasterror();
11461 while ($obj = $this->db->fetch_object($resql)) {
11462 $result = $this->fetch($obj->rowid);
11465 $this->errors[] = $this->error;
11467 $result = $this->
delete($user);
11470 $this->errors[] = $this->error;
11478 if (empty($error)) {
11479 $this->db->commit();
11482 $this->error = implode(
', ', $this->errors);
11483 $this->db->rollback();
11484 return $error * -1;
11503 $tmpforobjectclass = get_class($this);
11504 $tmpforobjectlineclass = ucfirst($tmpforobjectclass).
'Line';
11506 $this->db->begin();
11509 $result = $this->call_trigger(
'LINE'.strtoupper($tmpforobjectclass).
'_DELETE', $user);
11515 if (empty($error)) {
11516 $sql =
"DELETE FROM ".$this->db->prefix().$this->table_element_line;
11517 $sql .=
" WHERE rowid = ".((int) $idline);
11519 $resql = $this->db->query($sql);
11521 $this->error =
"Error ".$this->db->lasterror();
11526 if (empty($error)) {
11528 $tmpobjectline =
new $tmpforobjectlineclass($this->db);
11529 '@phan-var-force CommonObjectLine $tmpobjectline';
11530 if (!isset($tmpobjectline->isextrafieldmanaged) || !empty($tmpobjectline->isextrafieldmanaged)) {
11531 $tmpobjectline->id = $idline;
11532 $result = $tmpobjectline->deleteExtraFields();
11535 $this->error =
"Error ".get_class($this).
"::deleteLineCommon deleteExtraFields error -4 ".$tmpobjectline->error;
11540 if (empty($error)) {
11541 $this->db->commit();
11544 dol_syslog(get_class($this).
"::deleteLineCommon ERROR:".$this->error, LOG_ERR);
11545 $this->db->rollback();
11565 $this->db->begin();
11567 $statusfield =
'status';
11568 if (in_array($this->element, array(
'don',
'donation',
'shipping',
'project_task'))) {
11569 $statusfield =
'fk_statut';
11572 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
11573 $sql .=
" SET ".$this->db->sanitize($statusfield).
" = ".((int) $status);
11574 $sql .=
" WHERE rowid = ".((int) $this->
id);
11576 if ($this->db->query($sql)) {
11578 $this->oldcopy = clone $this;
11581 if (!$error && !$notrigger) {
11583 $result = $this->call_trigger($triggercode, $user);
11590 $this->
status = $status;
11591 if (property_exists($this,
'statut')) {
11592 $this->statut = $status;
11594 $this->db->commit();
11597 $this->db->rollback();
11601 $this->error = $this->db->error();
11602 $this->db->rollback();
11618 $this->specimen = 1;
11620 'label' =>
'This is label',
11621 'ref' =>
'ABCD1234',
11622 'description' =>
'This is a description',
11624 'note_public' =>
'Public note',
11625 'note_private' =>
'Private note',
11626 'date_creation' => (
dol_now() - 3600 * 48),
11627 'date_modification' => (
dol_now() - 3600 * 24),
11628 'fk_user_creat' => $user->id,
11629 'fk_user_modif' => $user->id,
11632 foreach ($fields as $key => $value) {
11633 if (array_key_exists($key, $this->fields)) {
11634 $this->{$key} = $value;
11639 if (property_exists($this,
'fields')) {
11640 foreach ($this->fields as $key => $value) {
11642 if (array_key_exists($key, $fields)) {
11646 if (!empty($value[
'default'])) {
11647 $this->$key = $value[
'default'];
11665 require_once DOL_DOCUMENT_ROOT.
'/core/class/comment.class.php';
11667 $comment =
new Comment($this->db);
11668 $result = $comment->fetchAllFor($this->element, $this->
id);
11670 $this->setErrorsFromObject($comment);
11673 $this->comments = $comment->comments;
11675 return count($this->comments);
11685 return count($this->comments);
11696 if (!is_array($parameters)) {
11699 foreach ($parameters as $parameter) {
11700 if (isset($this->$parameter)) {
11701 $this->$parameter = trim($this->$parameter);
11720 require_once DOL_DOCUMENT_ROOT.
'/categories/class/categorie.class.php';
11724 $existing =
$c->containing($this->
id, $type_categ,
'id');
11744 if (!is_array($categories)) {
11745 $categories = array($categories);
11748 dol_syslog(get_class($this).
"::setCategoriesCommon Object Id:".$this->
id.
' type_categ:'.$type_categ.
' nb tag add:'.count($categories), LOG_DEBUG);
11750 require_once DOL_DOCUMENT_ROOT.
'/categories/class/categorie.class.php';
11752 if (empty($type_categ)) {
11753 dol_syslog(__METHOD__.
': Type '.$type_categ.
'is an unknown category type. Done nothing.', LOG_ERR);
11759 $existing =
$c->containing($this->
id, $type_categ,
'id');
11762 if (!is_array($existing)) {
11763 $existing = array();
11765 if ($remove_existing) {
11767 $to_del = array_diff($existing, $categories);
11768 $to_add = array_diff($categories, $existing);
11771 $to_add = array_diff($categories, $existing);
11778 foreach ($to_del as $del) {
11779 if (
$c->fetch($del) > 0) {
11780 $result =
$c->del_type($this, $type_categ);
11783 $this->error =
$c->error;
11784 $this->errors =
$c->errors;
11791 foreach ($to_add as $add) {
11792 if (
$c->fetch($add) > 0) {
11793 $result =
$c->add_type($this, $type_categ);
11796 $this->error =
$c->error;
11797 $this->errors =
$c->errors;
11805 return $error ? (-1 * $error) : $ok;
11818 $this->db->begin();
11820 if (empty($type)) {
11821 $type = $this->table_element;
11824 require_once DOL_DOCUMENT_ROOT.
'/categories/class/categorie.class.php';
11825 $categorystatic =
new Categorie($this->db);
11827 $tablename = $this->db->prefix().
"categorie_".(empty($categorystatic->MAP_CAT_TABLE[$type]) ? $type : $categorystatic->MAP_CAT_TABLE[$type]);
11828 $fkname =
'fk_' . (empty($categorystatic->MAP_CAT_FK[$type]) ? $type : $categorystatic->MAP_CAT_FK[$type]);
11830 $sql =
"INSERT INTO ".$this->db->sanitize($tablename).
" (fk_categorie, ".$this->db->sanitize($fkname).
")";
11831 $sql .=
" SELECT fk_categorie, ".((int) $toId).
" FROM ".$this->db->sanitize($tablename);
11832 $sql .=
" WHERE ".$this->db->sanitize($fkname).
" = ".((int) $fromId);
11834 if (!$this->db->query($sql)) {
11835 $this->error = $this->db->lasterror();
11836 $this->db->rollback();
11840 $this->db->commit();
11854 $this->db->begin();
11858 switch ($this->element) {
11860 $element =
'propale';
11863 $element =
'produit';
11865 case 'order_supplier':
11866 $element =
'fournisseur/commande';
11868 case 'invoice_supplier':
11871 $element =
'fournisseur/facture/'.get_exdir($this->
id, 2, 0, 1, $this,
'invoice_supplier');
11874 $element =
'expedition/sending';
11877 case 'project_task':
11878 require_once DOL_DOCUMENT_ROOT.
'/projet/class/task.class.php';
11880 $project_result = $this->fetchProject();
11881 if ($project_result >= 0) {
11882 $element =
'projet/'.dol_sanitizeFileName($this->project->ref).
'/';
11886 $element =
'contract';
11889 $element = $this->element;
11891 '@phan-var-force string $element';
11894 $sql =
"DELETE FROM ".$this->db->prefix().
"ecm_files_extrafields WHERE fk_object IN (";
11895 $sql .=
" SELECT rowid FROM ".$this->db->prefix().
"ecm_files WHERE filename LIKE '".$this->db->escape($this->
ref).
"%'";
11896 $sql .=
" AND filepath = '".$this->db->escape($element).
"/".$this->db->escape($this->
ref).
"' AND entity = ".((int)
$conf->entity);
11899 if (!$this->db->query($sql)) {
11900 $this->error = $this->db->lasterror();
11901 $this->db->rollback();
11906 $sql =
"DELETE FROM ".$this->db->prefix().
"ecm_files";
11907 $sql .=
" WHERE filename LIKE '".$this->db->escape($this->
ref).
"%'";
11908 $sql .=
" AND filepath = '".$this->db->escape($element).
"/".$this->db->escape($this->
ref).
"' AND entity = ".((int)
$conf->entity);
11910 if (!$this->db->query($sql)) {
11911 $this->error = $this->db->lasterror();
11912 $this->db->rollback();
11919 $sql =
'DELETE FROM '.$this->db->prefix().
"ecm_files_extrafields";
11920 $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).
")";
11921 $resql = $this->db->query($sql);
11923 $this->error = $this->db->lasterror();
11924 $this->db->rollback();
11928 $sql =
'DELETE FROM '.$this->db->prefix().
"ecm_files";
11929 $sql .=
" WHERE src_object_type = '".$this->db->escape($this->table_element.(empty($this->module) ?
"" :
"@".$this->module)).
"' AND src_object_id = ".((int) $this->
id);
11930 $resql = $this->db->query($sql);
11932 $this->error = $this->db->lasterror();
11933 $this->db->rollback();
11938 $this->db->commit();
11955 include_once DOL_DOCUMENT_ROOT.
'/product/class/product.class.php';
11958 $tmpproduct =
new Product($this->db);
11959 foreach ($this->lines as $line) {
11960 if ($line->fk_product > 0) {
11961 $tmpproduct->fetch($line->fk_product);
11962 $statustotest = ($status ==
'onsale' ?
'status' :
'status_buy');
11963 if (!$tmpproduct->$statustotest) {
11964 $langs->load(
'products');
11965 $statuskey4lang = ($status ==
'onsale' ?
'ProductStatusNotOnSell' :
'ProductStatusNotOnBuy');
11967 $this->errors[] = $langs->trans(
'ProductRef').
' '.$tmpproduct->ref.
' '.$langs->trans($statuskey4lang);
11973 $this->error =
'ErrorOneLineContainsADisactivatedProduct';
11989 $this->error = $message;
11990 $this->errors[] = $message;
12002 global $dolibarr_main_document_root;
12004 $this->setErrorWithoutLog($message);
12005 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
12006 $file = str_replace($dolibarr_main_document_root,
'', $trace[0][
'file'] ??
'file unknown');
12007 $line = $trace[0][
'line'] ??
'line unknown';
12008 $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...
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.
GETPOSTINT($paramname, $method=0)
Return the value of a $_GET or $_POST supervariable, converted into integer.
dol_format_address($object, $withcountry=0, $sep="\n", $outputlangs=null, $mode=0, $extralangcode='')
Return a formatted address (part address/zip/town/state) according to country rules.
dol_osencode($str)
Return a string encoded into OS filesystem encoding.
price2num($amount, $rounding='', $option=0)
Function that return a number with universal decimal format (decimal separator is '.
dol_string_nospecial($str, $newstr='_', $badcharstoreplace='', $badcharstoremove='', $keepspaces=0)
Clean a string from all punctuation characters to use it as a ref or login.
dol_eval($s, $returnvalue=1, $hideerrors=1, $onlysimplestring='1')
Replace eval function to add more security.
img_object($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $allowothertags=array())
Show a picto called object_picto (generic function)
dol_print_url($url, $target='_blank', $max=32, $withpicto=0, $morecss='')
Show Url link.
dol_sanitizePathName($str, $newstr='_', $unaccent=0, $allowdash=0)
Clean a string to use it as a path name.
dol_sanitizeFileName($str, $newstr='_', $unaccent=1, $includequotes=0, $allowdash=0)
Clean a string to use it as a file name.
price($amount, $form=0, $outlangs='', $trunc=1, $rounding=-1, $forcerounding=-1, $currency_code='')
Function to format a value into an amount for visual output Function used into PDF and HTML pages.
getPictoForType($key, $morecss='')
Return the picto for a data type.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
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.
dolPrintHTMLForAttribute($s, $escapeonlyhtmltags=0, $allowothertags=array())
Return a string ready to be output into an HTML attribute (alt, title, data-html, ....
dol_print_email($email, $contactid=0, $socid=0, $addlink=0, $max=0, $showinvalid=1, $withpicto=0, $morecss='paddingrightonly')
Show EMail link formatted for HTML output.
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.
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0)
Return value of a param into GET or POST supervariable.
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.
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.
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, $remise_percent_global, $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.