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;
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;
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) {
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) {
5970 $this->tpl[
'strike'] = 1;
5975 $dirtpls = array_merge(
$conf->modules_parts[
'tpl'], array($defaulttpldir));
5976 foreach ($dirtpls as $module => $reldir) {
5977 if (!empty($module)) {
5980 $tpl = DOL_DOCUMENT_ROOT.$reldir.
'/originproductline.tpl.php';
5983 if (empty(
$conf->file->strict_mode)) {
5984 $res = @include $tpl;
5986 $res = include $tpl;
6013 $sql =
"INSERT INTO ".$this->db->prefix().
"element_resources (";
6014 $sql .=
"resource_id";
6015 $sql .=
", resource_type";
6016 $sql .=
", element_id";
6017 $sql .=
", element_type";
6019 $sql .=
", mandatory";
6020 $sql .=
") VALUES (";
6021 $sql .= ((int) $resource_id);
6022 $sql .=
", '".$this->db->escape($resource_type).
"'";
6023 $sql .=
", '".$this->db->escape((
string) $this->
id).
"'";
6024 $sql .=
", '".$this->db->escape($this->element).
"'";
6025 $sql .=
", '".$this->db->escape((
string) $busy).
"'";
6026 $sql .=
", '".$this->db->escape((
string) $mandatory).
"'";
6029 dol_syslog(get_class($this).
"::add_element_resource", LOG_DEBUG);
6030 if ($this->db->query($sql)) {
6032 $result = $this->call_trigger(strtoupper($this->TRIGGER_PREFIX).
'_ADD_RESOURCE', $user);
6034 $this->db->rollback();
6038 $this->db->commit();
6041 $this->error = $this->db->lasterror();
6042 $this->db->rollback();
6063 $sql =
"DELETE FROM ".$this->db->prefix().
"element_resources";
6064 $sql .=
" WHERE rowid = ".((int) $rowid);
6066 dol_syslog(get_class($this).
"::delete_resource", LOG_DEBUG);
6068 $resql = $this->db->query($sql);
6070 $this->error = $this->db->lasterror();
6071 $this->db->rollback();
6075 $result = $this->call_trigger(strtoupper($this->TRIGGER_PREFIX).
'_DELETE_RESOURCE', $user);
6077 $this->db->rollback();
6081 $this->db->commit();
6095 if (isset($this->lines) && is_array($this->lines)) {
6096 $nboflines = count($this->lines);
6097 for ($i = 0; $i < $nboflines; $i++) {
6098 if (is_object($this->lines[$i])) {
6099 $this->lines[$i] = clone $this->lines[$i];
6118 protected function commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams =
null)
6120 global
$conf, $langs, $hookmanager, $action;
6122 $srctemplatepath =
'';
6124 $parameters = array(
'modelspath' => $modelspath,
'modele' => $modele,
'outputlangs' => $outputlangs,
'hidedetails' => $hidedetails,
'hidedesc' => $hidedesc,
'hideref' => $hideref,
'moreparams' => $moreparams);
6125 $reshook = $hookmanager->executeHooks(
'commonGenerateDocument', $parameters, $this, $action);
6127 if (!empty($reshook)) {
6131 dol_syslog(
"commonGenerateDocument modele=".$modele.
" outputlangs->defaultlang=".(is_object($outputlangs) ? $outputlangs->defaultlang :
'null'));
6133 if (empty($modele)) {
6134 $this->error =
'BadValueForParameterModele';
6139 $err = error_reporting();
6141 @set_time_limit(120);
6142 error_reporting($err);
6145 $tmp = explode(
':', $modele, 2);
6146 $saved_model = $modele;
6147 if (!empty($tmp[1])) {
6149 $srctemplatepath = $tmp[1];
6156 $dirmodels = array(
'/');
6157 if (is_array(
$conf->modules_parts[
'models'])) {
6158 $dirmodels = array_merge($dirmodels,
$conf->modules_parts[
'models']);
6160 foreach ($dirmodels as $reldir) {
6161 foreach (array(
'doc',
'pdf') as $prefix) {
6162 if (in_array(get_class($this), array(
'Adherent'))) {
6164 $file = $prefix.
"_".$modele.
".class.php";
6167 $file = $prefix.
"_".$modele.
".modules.php";
6174 if (file_exists($file)) {
6176 $classname = $prefix.
'_'.$modele;
6185 if ($filefound ===
'' || $classname ===
'') {
6186 $this->error = $langs->trans(
"Error").
' Failed to load doc generator with modelpaths='.$modelspath.
' - modele='.$modele;
6187 $this->errors[] = $this->error;
6198 require_once $filefound;
6200 $obj =
new $classname($this->db);
6212 '@phan-var-force ModelePDFMember $obj';
6216 if ($obj->type ==
'odt' && empty($srctemplatepath)) {
6217 $varfortemplatedir = $obj->scandir;
6221 $listoffiles = array();
6224 $listofdir = explode(
',', $dirtoscan);
6225 foreach ($listofdir as $key => $tmpdir) {
6226 $tmpdir = trim($tmpdir);
6227 $tmpdir = preg_replace(
'/DOL_DATA_ROOT/', DOL_DATA_ROOT, $tmpdir);
6229 unset($listofdir[$key]);
6232 if (is_dir($tmpdir)) {
6233 $tmpfiles =
dol_dir_list($tmpdir,
'files', 0,
'\.od(s|t)$',
'',
'name', SORT_ASC, 0);
6234 if (count($tmpfiles)) {
6235 $listoffiles = array_merge($listoffiles, $tmpfiles);
6240 if (count($listoffiles)) {
6241 foreach ($listoffiles as $record) {
6242 $srctemplatepath = $record[
'fullname'];
6248 if (empty($srctemplatepath)) {
6249 $this->error =
'ErrorGenerationAskedForOdtTemplateWithSrcFileNotDefined';
6254 if ($obj->type ==
'odt' && !empty($srctemplatepath)) {
6256 dol_syslog(
"Failed to locate template file ".$srctemplatepath, LOG_WARNING);
6257 $this->error =
'ErrorGenerationAskedForOdtTemplateWithSrcFileNotFound';
6264 $sav_charset_output = empty($outputlangs->charset_output) ?
'' : $outputlangs->charset_output;
6267 $this->model_pdf = $saved_model;
6272 $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath,
'member', 1,
'tmp_cards');
6274 $resultwritefile = -1;
6275 dol_syslog(
"Error generating document - Provided ".get_class($this).
" to ".get_class($obj).
"::write_file()", LOG_ERR);
6279 if ($this instanceof
Don) {
6280 $resultwritefile = $obj->write_file($this, $outputlangs );
6282 $resultwritefile = -1;
6283 dol_syslog(
"Error generating document - Provided ".get_class($this).
" to Don::write_file()", LOG_ERR);
6287 '@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';
6288 $this->context[
'moreparams'] = $moreparams;
6289 $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, $hidedetails, $hidedesc, $hideref);
6291 }
catch (\Throwable $e) {
6292 $resultwritefile = -1;
6293 $this->error = $e->getMessage();
6294 dol_syslog(
"Exception in write_file() for ".get_class($this).
": ".$e->getMessage(), LOG_ERR);
6299 if ($resultwritefile > 0) {
6300 $outputlangs->charset_output = $sav_charset_output;
6303 require_once DOL_DOCUMENT_ROOT.
'/core/lib/files.lib.php';
6307 if (!empty($obj->result[
'fullpath'])) {
6308 $destfull = $obj->result[
'fullpath'];
6311 $update_main_doc_field = 0;
6312 if (!empty($obj->update_main_doc_field)) {
6313 $update_main_doc_field = 1;
6319 $this->indexFile($destfull, $update_main_doc_field);
6322 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);
6328 $this->warnings = $obj->warnings;
6332 $outputlangs->charset_output = $sav_charset_output;
6333 if (empty($this->error)) {
6334 $this->error = $obj->error;
6336 if (empty($this->errors)) {
6337 $this->errors = $obj->errors;
6339 $this->warnings = $obj->warnings;
6340 dol_syslog(
"Error generating document for ".__CLASS__.
". Error: ".$this->error, LOG_ERR);
6354 public function indexFile($destfull, $update_main_doc_field)
6356 global
$conf, $user;
6358 $upload_dir = dirname($destfull);
6359 $destfile = basename($destfull);
6360 $rel_dir = preg_replace(
'/^'.preg_quote(DOL_DATA_ROOT,
'/').
'/',
'', $upload_dir);
6362 if (!preg_match(
'/[\\/]temp[\\/]|[\\/]thumbs|\.meta$/', $rel_dir)) {
6363 $filename = basename($destfile);
6364 $rel_dir = preg_replace(
'/[\\/]$/',
'', $rel_dir);
6365 $rel_dir = preg_replace(
'/^[\\/]/',
'', $rel_dir);
6367 include_once DOL_DOCUMENT_ROOT.
'/ecm/class/ecmfiles.class.php';
6368 $ecmfile =
new EcmFiles($this->db);
6369 $result = $ecmfile->fetch(0,
'', ($rel_dir ? $rel_dir.
'/' :
'').$filename);
6372 $setsharekey =
false;
6374 !empty($this->TRIGGER_PREFIX)
6377 $setsharekey =
true;
6380 if ($this->element ==
'propal' || $this->element ==
'proposal') {
6382 $setsharekey =
true;
6385 $setsharekey =
true;
6388 if ($this->element ==
'facture' &&
getDolGlobalInt(
"INVOICE_ALLOW_EXTERNAL_DOWNLOAD")) {
6389 $setsharekey =
true;
6391 if ($this->element ==
'bank_account' &&
getDolGlobalInt(
"BANK_ACCOUNT_ALLOW_EXTERNAL_DOWNLOAD")) {
6392 $setsharekey =
true;
6394 if ($this->element ==
'contrat' &&
getDolGlobalInt(
"CONTRACT_ALLOW_EXTERNAL_DOWNLOAD")) {
6395 $setsharekey =
true;
6397 if ($this->element ==
'supplier_proposal' &&
getDolGlobalInt(
"SUPPLIER_PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD")) {
6398 $setsharekey =
true;
6400 if ($this->element ==
'order_supplier' &&
getDolGlobalInt(
"SUPPLIER_ORDER_ALLOW_EXTERNAL_DOWNLOAD")) {
6401 $setsharekey =
true;
6403 if ($this->element ==
'invoice_supplier' &&
getDolGlobalInt(
"SUPPLIER_INVOICE_ALLOW_EXTERNAL_DOWNLOAD")) {
6404 $setsharekey =
true;
6406 if ($this->element ==
'societe_rib' &&
getDolGlobalInt(
"SOCIETE_RIB_ALLOW_ONLINESIGN")) {
6407 $setsharekey =
true;
6411 if (empty($ecmfile->share)) {
6412 require_once DOL_DOCUMENT_ROOT.
'/core/lib/security2.lib.php';
6419 $ecmfile->fullpath_orig =
'';
6420 $ecmfile->gen_or_uploaded =
'generated';
6421 $ecmfile->description =
'';
6422 $ecmfile->keywords =
'';
6423 $ecmfile->src_object_type = $this->table_element;
6425 $result = $ecmfile->update($user);
6431 $ecmfile->entity =
$conf->entity;
6432 $ecmfile->filepath = $rel_dir;
6433 $ecmfile->filename = $filename;
6435 $ecmfile->fullpath_orig =
'';
6436 $ecmfile->gen_or_uploaded =
'generated';
6437 $ecmfile->description =
'';
6438 $ecmfile->keywords =
'';
6439 $ecmfile->src_object_type = $this->table_element;
6442 $result = $ecmfile->create($user);
6454 if ($update_main_doc_field && !empty($this->table_element)) {
6455 $sql =
"UPDATE ".$this->db->prefix().$this->table_element.
" SET last_main_doc = '".$this->db->escape($ecmfile->filepath.
"/".$ecmfile->filename).
"'";
6456 $sql .=
" WHERE rowid = ".((int) $this->
id);
6458 $resql = $this->db->query($sql);
6463 $this->last_main_doc = $ecmfile->filepath.
'/'.$ecmfile->filename;
6483 if (file_exists($file_osencoded)) {
6484 require_once DOL_DOCUMENT_ROOT.
'/core/lib/images.lib.php';
6487 $maxwidthsmall = $tmparraysize[
'maxwidthsmall'];
6488 $maxheightsmall = $tmparraysize[
'maxheightsmall'];
6489 $maxwidthmini = $tmparraysize[
'maxwidthmini'];
6490 $maxheightmini = $tmparraysize[
'maxheightmini'];
6495 vignette($file_osencoded, $maxwidthsmall, $maxheightsmall,
'_small', $quality);
6499 vignette($file_osencoded, $maxwidthmini, $maxheightmini,
'_mini', $quality);
6546 if (GETPOSTISSET($fieldname)) {
6547 return GETPOST($fieldname, $type, 3);
6550 if (isset($alternatevalue)) {
6551 return $alternatevalue;
6554 $newelement = $this->element;
6555 if ($newelement ==
'facture') {
6556 $newelement =
'invoice';
6558 if ($newelement ==
'commande') {
6559 $newelement =
'order';
6561 if (empty($newelement)) {
6562 dol_syslog(
"Ask a default value using common method getDefaultCreateValueForField on an object with no property ->element defined. Return empty string.", LOG_WARNING);
6566 $keyforfieldname = strtoupper($newelement.
'_DEFAULT_'.$fieldname);
6593 if (!$this->element) {
6596 if (!($this->
id > 0)) {
6599 if (is_array($this->array_languages)) {
6603 $this->array_languages = array();
6605 $element = $this->element;
6606 if ($element ==
'categorie') {
6607 $element =
'categories';
6611 $sql =
"SELECT rowid, property, lang , value";
6612 $sql .=
" FROM ".$this->db->prefix().
"object_lang";
6613 $sql .=
" WHERE type_object = '".$this->db->escape($element).
"'";
6614 $sql .=
" AND fk_object = ".((int) $this->
id);
6616 $resql = $this->db->query($sql);
6618 $numrows = $this->db->num_rows($resql);
6621 while ($i < $numrows) {
6622 $obj = $this->db->fetch_object($resql);
6623 $key = $obj->property;
6624 $value = $obj->value;
6625 $codelang = $obj->lang;
6626 $type = $this->fields[$key][
'type'];
6629 if (preg_match(
'/date/', $type)) {
6630 $this->array_languages[$key][$codelang] = $this->db->jdate($value);
6632 $this->array_languages[$key][$codelang] = $value;
6639 $this->db->free($resql);
6662 foreach ($_POST as $postfieldkey => $postfieldvalue) {
6663 $tmparray = explode(
'-', $postfieldkey);
6664 if ($tmparray[0] !=
'field') {
6668 $element = $tmparray[1];
6669 $key = $tmparray[2];
6670 $codelang = $tmparray[3];
6673 if (!empty($onlykey) && $key != $onlykey) {
6676 if ($element != $this->element) {
6680 $key_type = $this->fields[$key][
'type'];
6683 if (isset($this->fields[$key][
'enabled'])) {
6684 $enabled = (int)
dol_eval((
string) $this->fields[$key][
'enabled'], 1, 1,
'1');
6691 if (empty($enabled)) {
6696 if (in_array($key_type, array(
'date'))) {
6700 } elseif (in_array($key_type, array(
'datetime'))) {
6704 } elseif (in_array($key_type, array(
'checkbox',
'chkbxlst'))) {
6705 $value_arr =
GETPOST($postfieldkey,
'array');
6706 if (!empty($value_arr)) {
6707 $value_key = implode(
',', $value_arr);
6711 } elseif (in_array($key_type, array(
'price',
'double'))) {
6712 $value_arr =
GETPOST($postfieldkey,
'alpha');
6715 $value_key =
GETPOST($postfieldkey);
6716 if (in_array($key_type, array(
'link')) && $value_key ==
'-1') {
6721 $this->array_languages[$key][$codelang] = $value_key;
6746 $savDisableCompute =
$conf->disable_compute;
6747 $conf->disable_compute = 1;
6749 $ret = $this->fetch(
$id);
6751 $conf->disable_compute = $savDisableCompute;
6769 global
$conf, $extrafields;
6771 if (empty($rowid)) {
6774 if (empty($rowid) && isset($this->rowid)) {
6775 $rowid = $this->rowid;
6779 if (!$this->table_element) {
6782 $this->array_options = array();
6784 if (!is_array($optionsArray)) {
6786 if (!isset($extrafields) || !is_object($extrafields)) {
6787 require_once DOL_DOCUMENT_ROOT.
'/core/class/extrafields.class.php';
6792 if (empty($extrafields->attributes[$this->table_element][
'loaded'])) {
6793 $extrafields->fetch_name_optionals_label($this->table_element);
6795 $optionsArray = (!empty($extrafields->attributes[$this->table_element][
'label']) ? $extrafields->attributes[$this->table_element][
'label'] :
null);
6797 global $extrafields;
6798 dol_syslog(
"Warning: fetch_optionals was called with param optionsArray defined when you should pass null now", LOG_WARNING);
6801 $table_element = $this->table_element;
6802 if ($table_element ==
'categorie') {
6803 $table_element =
'categories';
6807 if (is_array($optionsArray) && count($optionsArray) > 0) {
6808 $sql =
"SELECT rowid";
6809 foreach ($optionsArray as $name => $label) {
6810 if (empty($extrafields->attributes[$this->table_element][
'type'][$name]) || (!in_array($extrafields->attributes[$this->table_element][
'type'][$name], [
'separate',
'point',
'multipts',
'linestrg',
'polygon']))) {
6811 $sql .=
", ".$this->db->sanitize($name);
6814 if (!empty($extrafields->attributes[$this->table_element][
'type'][$name]) && in_array($extrafields->attributes[$this->table_element][
'type'][$name], array(
'point',
'multipts',
'linestrg',
'polygon'))) {
6816 $sql .=
", ST_AsWKT(".$name.
") as ".$this->db->sanitize($name);
6819 $sql .=
" FROM ".$this->db->prefix().$table_element.
"_extrafields";
6820 $sql .=
" WHERE fk_object = ".((int) $rowid);
6823 $resql = $this->db->query($sql);
6825 $numrows = $this->db->num_rows($resql);
6827 $tab = $this->db->fetch_array($resql);
6828 foreach ($tab as $key => $value) {
6830 if ($key !=
'rowid' && $key !=
'tms' && $key !=
'fk_member' && !is_int($key)) {
6832 if (!empty($extrafields->attributes[$this->table_element]) && in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'date',
'datetime'))) {
6834 $this->array_options[
"options_".$key] = $this->db->jdate($value);
6836 $this->array_options[
"options_".$key] = $value;
6841 if (!empty($extrafields->attributes[$this->table_element][
'type'][$key]) && $extrafields->attributes[$this->table_element][
'type'][$key] ==
'password') {
6842 if (!empty($value) && preg_match(
'/^dolcrypt:/', $value)) {
6843 $this->array_options[
"options_".$key] =
dolDecrypt($value);
6852 if (is_array($extrafields->attributes[$this->table_element][
'label'])) {
6853 foreach ($extrafields->attributes[$this->table_element][
'label'] as $key => $val) {
6854 $this->array_options[
'options_' . $key] =
null;
6861 if (is_array($extrafields->attributes[$this->table_element][
'label'])) {
6862 foreach ($extrafields->attributes[$this->table_element][
'label'] as $key => $val) {
6863 if (!empty($extrafields->attributes[$this->table_element]) && !empty($extrafields->attributes[$this->table_element][
'computed'][$key])) {
6865 if (empty(
$conf->disable_compute)) {
6868 global $objectoffield;
6869 $this->array_options[
'options_' . $key] =
dol_eval((
string) $extrafields->attributes[$this->table_element][
'computed'][$key], 1, 0,
'2');
6875 $this->db->free($resql);
6883 $this->errors[] = $this->db->lasterror();
6904 $table_element = $this->table_element;
6905 if ($table_element ==
'categorie') {
6906 $table_element =
'categories';
6909 dol_syslog(get_class($this).
"::deleteExtraFields delete", LOG_DEBUG);
6911 $sql_del =
"DELETE FROM ".$this->db->prefix().$table_element.
"_extrafields WHERE fk_object = ".((int) $this->
id);
6913 $resql = $this->db->query($sql_del);
6915 $this->error = $this->db->lasterror();
6916 $this->db->rollback();
6919 $this->db->commit();
6936 global $langs, $extrafields, $user;
6938 if (
getDolGlobalString(
'MAIN_EXTRAFIELDS_DISABLED') || empty($this->array_options)) {
6942 if (empty($userused)) {
6949 $langs->load(
'admin');
6950 if (!isset($extrafields) || !is_object($extrafields)) {
6951 require_once DOL_DOCUMENT_ROOT.
'/core/class/extrafields.class.php';
6954 $target_extrafields = $extrafields->fetch_name_optionals_label($this->table_element);
6957 $new_array_options = array();
6958 foreach ($this->array_options as $key => $value) {
6959 if (in_array(substr($key, 8), array_keys($target_extrafields))) {
6960 $new_array_options[$key] = $value;
6961 } elseif (in_array($key, array_keys($target_extrafields))) {
6962 $new_array_options[
'options_'.$key] = $value;
6966 foreach ($new_array_options as $key => $value) {
6967 $attributeKey = substr($key, 8);
6968 $attributeType = $extrafields->attributes[$this->table_element][
'type'][$attributeKey];
6969 $attributeLabel = $langs->transnoentities($extrafields->attributes[$this->table_element][
'label'][$attributeKey]);
6970 $attributeParam = $extrafields->attributes[$this->table_element][
'param'][$attributeKey];
6971 $attributeRequired = $extrafields->attributes[$this->table_element][
'required'][$attributeKey];
6972 $attributeUnique = $extrafields->attributes[$this->table_element][
'unique'][$attributeKey];
6973 $attrfieldcomputed = $extrafields->attributes[$this->table_element][
'computed'][$attributeKey];
6974 $attributeEmptyOnClone = $extrafields->attributes[$this->table_element][
'emptyonclone'][$attributeKey];
6986 if (!empty($this->context[
'createfromclone']) && $this->context[
'createfromclone'] ==
'createfromclone' && (!empty($attributeUnique) || !empty($attributeEmptyOnClone))) {
6987 $new_array_options[$key] =
null;
6993 if (!empty($this->context[
'createproductcombination']) && $this->context[
'createproductcombination'] ==
'createproductcombination' && !empty($attributeUnique)) {
6994 $new_array_options[$key] =
null;
6999 if ($attributeRequired) {
7000 $v = $this->array_options[$key];
7002 $langs->load(
"errors");
7003 dol_syslog(
"Mandatory field '".$key.
"' is empty during create and set to required into definition of extrafields");
7004 $this->errors[] = $langs->trans(
'ErrorFieldRequired', $attributeLabel);
7009 if (!empty($attrfieldcomputed)) {
7011 $value =
dol_eval((
string) $attrfieldcomputed, 1, 0,
'2');
7012 dol_syslog($langs->trans(
"Extrafieldcomputed").
" on ".$attributeLabel.
"(".$value.
")", LOG_DEBUG);
7013 $new_array_options[$key] = $value;
7015 $new_array_options[$key] =
null;
7020 switch ($attributeType) {
7024 if (!is_numeric($value) && $value !=
'') {
7025 $this->errors[] = $langs->trans(
"ExtraFieldHasWrongValue", $attributeLabel);
7027 } elseif ($value ===
'') {
7028 $new_array_options[$key] =
null;
7032 if ($value ===
'' || $value ===
false || $value ===
null) {
7033 $new_array_options[$key] =
null;
7039 if (!is_numeric($value) && $value !=
'') {
7040 dol_syslog($langs->trans(
"ExtraFieldHasWrongValue").
" for ".$attributeLabel.
"(".$value.
"is not '".$attributeType.
"')", LOG_DEBUG);
7041 $this->errors[] = $langs->trans(
"ExtraFieldHasWrongValue", $attributeLabel);
7043 } elseif ($value ==
'') {
7047 $new_array_options[$key] = $value;
7057 if ($this->array_options[$key] !=
'' && is_array($extrafields->attributes[$this->table_element][
'param'][$attributeKey][
'options'])) {
7059 $tmparrays = array_keys($extrafields->attributes[$this->table_element][
'param'][$attributeKey][
'options']);
7060 $algo = reset($tmparrays);
7065 if (is_object($this->oldcopy)) {
7067 if (isset($this->oldcopy->array_options[$key]) && $this->array_options[$key] == $this->oldcopy->array_options[$key]) {
7069 if ($algo ==
'dolcrypt') {
7070 if (!preg_match(
'/^dolcrypt:/', $this->array_options[$key])) {
7071 $new_array_options[$key] =
dolEncrypt($this->array_options[$key]);
7073 $new_array_options[$key] = $this->array_options[$key];
7076 $new_array_options[$key] = $this->array_options[$key];
7080 if ($algo ==
'dolcrypt') {
7081 if (!preg_match(
'/^dolcrypt:/', $this->array_options[$key])) {
7082 $new_array_options[$key] =
dolEncrypt($this->array_options[$key]);
7084 $new_array_options[$key] = $this->array_options[$key];
7087 $new_array_options[$key] =
dol_hash($this->array_options[$key], $algo);
7093 if ($algo ==
'dolcrypt' && !preg_match(
'/^dolcrypt:/', $this->array_options[$key])) {
7094 $new_array_options[$key] =
dolEncrypt($this->array_options[$key]);
7096 $new_array_options[$key] = $this->array_options[$key];
7101 $new_array_options[$key] = $this->array_options[$key];
7104 $new_array_options[$key] = $this->array_options[$key];
7110 if (!is_numeric($this->array_options[$key]) || $this->array_options[$key] != intval($this->array_options[$key])) {
7111 $this->array_options[$key] = strtotime($this->array_options[$key]);
7113 $new_array_options[$key] = $this->db->idate($this->array_options[$key]);
7117 if (!is_numeric($this->array_options[$key]) || $this->array_options[$key] != intval($this->array_options[$key])) {
7118 $this->array_options[$key] = strtotime($this->array_options[$key]);
7120 $new_array_options[$key] = $this->db->idate($this->array_options[$key],
'gmt');
7123 $param_list = array_keys($attributeParam[
'options']);
7126 $InfoFieldList = explode(
":", $param_list[0]);
7128 if ($InfoFieldList[0] && class_exists($InfoFieldList[0])) {
7129 if ($value ==
'-1') {
7130 $new_array_options[$key] =
'';
7133 '@phan-var-force CommonObject $object';
7137 $sqlFetchObject =
"SELECT rowid FROM ".$this->db->prefix().$object->table_element;
7138 if (is_numeric($value)) {
7139 $sqlFetchObject .=
" WHERE rowid = " . (int) $value;
7141 $sqlFetchObject .=
" WHERE ref = '" . $this->db->escape($value) .
"'";
7144 $obj = $this->db->getRow($sqlFetchObject);
7146 if ($obj !==
false) {
7147 $objectId = $obj->rowid;
7154 $new_array_options[$key] = $objectId;
7156 $this->error =
"Id/Ref '".$value.
"' for object '".
$object->element.
"' not found";
7161 dol_syslog(
'Error bad setup of extrafield', LOG_WARNING);
7166 if (is_array($this->array_options[$key])) {
7167 $new_array_options[$key] = implode(
',', $this->array_options[$key]);
7169 $new_array_options[$key] = $this->array_options[$key];
7176 $sqlColumnValues = [
'fk_object' => (int) $this->
id];
7178 foreach ($new_array_options as $key => $newValue) {
7179 $attributeKey = substr($key, 8);
7180 $attributeType = $extrafields->attributes[$this->table_element][
'type'][$attributeKey];
7181 if ($attributeType ===
'separate') {
7185 $geoDataType = ExtraFields::$geoDataTypes[$attributeType] ??
null;
7187 if (! $geoDataType) {
7189 if ($newValue !=
'') {
7190 $sqlColumnValues[$attributeKey] =
"'".$this->db->escape($newValue).
"'";
7192 $sqlColumnValues[$attributeKey] =
'null';
7196 if (empty($newValue)) {
7197 $sqlColumnValues[$attributeKey] =
'null';
7200 if (preg_match(
'/error/i', $newValue)) {
7201 dol_syslog(
'Bad syntax string for '.$geoDataType[
'shortname'].
' '.$newValue.
' to generate SQL request', LOG_WARNING);
7202 $sqlColumnValues[$attributeKey] =
'null';
7211 $sqlColumnValues[$attributeKey] = $geoDataType[
'ST_Function'].
"('".$this->db->escape($newValue).
"')";
7216 $table_element = $this->table_element;
7217 if ($table_element ==
'categorie') {
7218 $table_element =
'categories';
7220 $extrafieldsTable = $this->db->prefix() . $table_element .
'_extrafields';
7222 dol_syslog(get_class($this).
"::insertExtraFields update or insert record line", LOG_DEBUG);
7224 $linealreadyfound = 0;
7225 $sql =
"SELECT COUNT(rowid) as nb FROM ".$this->db->prefix().$table_element.
"_extrafields WHERE fk_object = ".((int) $this->
id);
7226 $resql = $this->db->query($sql);
7228 $tmpobj = $this->db->fetch_object($resql);
7230 $linealreadyfound = $tmpobj->nb;
7235 if ($linealreadyfound) {
7236 array_shift($sqlColumnValues);
7237 $sqlColumnValueString = implode(
7243 array_map(
function ($key) use ($sqlColumnValues) {
7244 return "{$key} = {$sqlColumnValues[$key]}";
7245 }, array_keys($sqlColumnValues))
7247 $sql =
"UPDATE {$extrafieldsTable} SET {$sqlColumnValueString} WHERE fk_object = ".((int) $this->
id);
7250 $extrafieldsRequiredOnOtherEntities = $extrafields->attributes[$this->table_element][
'mandatoryfieldsofotherentities'] ?? array();
7251 foreach ($extrafieldsRequiredOnOtherEntities as $key => $extrafieldType) {
7252 if (isset($sqlColumnValues[$key])) {
7257 $sqlColumnValues[$key] =
"''";
7258 if (in_array($extrafieldType, array(
'int',
'double',
'price'))) {
7259 $sqlColumnValues[$key] = 0;
7262 $sqlColumns = implode(
',', array_keys($sqlColumnValues));
7263 $sqlValues = implode(
',', array_values($sqlColumnValues));
7264 $sql =
"INSERT INTO {$extrafieldsTable} ({$sqlColumns}) VALUES ({$sqlValues})";
7267 $resql = $this->db->query($sql);
7269 $this->error = $this->db->lasterror();
7274 if (!$error && !empty($this->fields[
'fk_user_modif'])) {
7275 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
7276 $sql .=
" SET fk_user_modif = ".(int) $user->id;
7277 $sql .=
" WHERE ".(empty($this->table_rowid) ?
'rowid' : $this->db->sanitize($this->table_rowid)).
" = ".((
int)
$this->id);
7278 $this->db->query($sql);
7281 if (!$error && $trigger) {
7283 $this->context = array(
'extrafieldaddupdate' => 1);
7284 $result = $this->call_trigger($trigger, $userused);
7292 $this->db->rollback();
7295 $this->db->commit();
7313 global $langs, $user;
7315 if (empty($userused)) {
7325 if (is_array($this->array_languages)) {
7326 $new_array_languages = $this->array_languages;
7328 foreach ($new_array_languages as $key => $value) {
7329 $attributeKey = $key;
7330 $attributeType = $this->fields[$attributeKey][
'type'];
7331 $attributeLabel = $this->fields[$attributeKey][
'label'];
7336 switch ($attributeType) {
7338 if (is_array($value) || (!is_numeric($value) && $value !=
'')) {
7339 $this->errors[] = $langs->trans(
"ExtraLanguageHasWrongValue", $attributeLabel);
7341 } elseif ($value ==
'') {
7342 $new_array_languages[$key] =
null;
7347 if (!is_numeric($value) && $value !=
'') {
7348 dol_syslog($langs->trans(
"ExtraLanguageHasWrongValue").
" on ".$attributeLabel.
"(".$value.
"is not '".$attributeType.
"')", LOG_DEBUG);
7349 $this->errors[] = $langs->trans(
"ExtraLanguageHasWrongValue", $attributeLabel);
7351 } elseif ($value ==
'') {
7352 $new_array_languages[$key] =
null;
7354 $new_array_languages[$key] = $value;
7368 $table_element = $this->table_element;
7369 if ($table_element ==
'categorie') {
7370 $table_element =
'categories';
7373 dol_syslog(get_class($this).
"::insertExtraLanguages delete then insert", LOG_DEBUG);
7375 foreach ($new_array_languages as $key => $langcodearray) {
7376 foreach ($langcodearray as $langcode => $value) {
7377 $sql_del =
"DELETE FROM ".$this->db->prefix().
"object_lang";
7378 $sql_del .=
" WHERE fk_object = ".((int) $this->
id).
" AND property = '".$this->db->escape($key).
"' AND type_object = '".$this->db->escape($table_element).
"'";
7379 $sql_del .=
" AND lang = '".$this->db->escape($langcode).
"'";
7380 $this->db->query($sql_del);
7382 if ($value !==
'') {
7383 $sql =
"INSERT INTO ".$this->db->prefix().
"object_lang (fk_object, property, type_object, lang, value";
7384 $sql .=
") VALUES (".$this->id.
", '".$this->db->escape($key).
"', '".$this->db->escape($table_element).
"', '".$this->db->escape($langcode).
"', '".$this->db->escape($value).
"'";
7387 $resql = $this->db->query($sql);
7389 $this->error = $this->db->lasterror();
7397 if (!$error && $trigger) {
7399 $this->context = array(
'extralanguagesaddupdate' => 1);
7400 $result = $this->call_trigger($trigger, $userused);
7408 $this->db->rollback();
7411 $this->db->commit();
7431 global $langs, $user, $extrafields, $hookmanager;
7437 if (empty($userused)) {
7443 if (!empty($this->array_options) && isset($this->array_options[
"options_".$key])) {
7445 $langs->load(
'admin');
7446 if (!isset($extrafields) || !is_object($extrafields)) {
7447 require_once DOL_DOCUMENT_ROOT.
'/core/class/extrafields.class.php';
7450 $extrafields->fetch_name_optionals_label($this->table_element);
7452 $value = $this->array_options[
"options_".$key];
7454 $attributeKey = $key;
7455 $attributeType = $extrafields->attributes[$this->table_element][
'type'][$attributeKey];
7456 $attributeLabel = $extrafields->attributes[$this->table_element][
'label'][$attributeKey];
7457 $attributeParam = $extrafields->attributes[$this->table_element][
'param'][$attributeKey];
7458 $attributeRequired = $extrafields->attributes[$this->table_element][
'required'][$attributeKey];
7459 $attributeUnique = $extrafields->attributes[$this->table_element][
'unique'][$attributeKey];
7460 $attrfieldcomputed = $extrafields->attributes[$this->table_element][
'computed'][$attributeKey];
7464 if ($attributeRequired) {
7465 $mandatorypb =
false;
7466 if ($attributeType ==
'link' && $this->array_options[
"options_".$key] ==
'-1') {
7467 $mandatorypb =
true;
7469 if ($this->array_options[
"options_".$key] ===
'') {
7470 $mandatorypb =
true;
7473 $langs->load(
"errors");
7474 dol_syslog(
"Mandatory field 'options_".$key.
"' is empty during update and set to required into definition of extrafields");
7475 $this->errors[] = $langs->trans(
'ErrorFieldRequired', $attributeLabel);
7481 $new_array_options = $this->array_options;
7485 if (!empty($attrfieldcomputed)) {
7487 $value =
dol_eval((
string) $attrfieldcomputed, 1, 0,
'2');
7488 dol_syslog($langs->trans(
"Extrafieldcomputed").
" on ".$attributeLabel.
"(".$value.
")", LOG_DEBUG);
7490 $new_array_options[
"options_".$key] = $value;
7492 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7494 $new_array_options[
"options_".$key] =
null;
7496 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7500 switch ($attributeType) {
7502 if (!is_numeric($value) && $value !=
'') {
7503 $this->errors[] = $langs->trans(
"ExtraFieldHasWrongValue", $attributeLabel);
7505 } elseif ($value ===
'') {
7506 $new_array_options[
"options_".$key] =
null;
7508 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7514 if (!is_numeric($value) && $value !=
'') {
7515 dol_syslog($langs->trans(
"ExtraFieldHasWrongValue").
" on ".$attributeLabel.
"(".$value.
"is not '".$attributeType.
"')", LOG_DEBUG);
7516 $this->errors[] = $langs->trans(
"ExtraFieldHasWrongValue", $attributeLabel);
7518 } elseif ($value ===
'') {
7522 $new_array_options[
"options_".$key] = $value;
7524 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7536 if ($this->array_options[
"options_".$key] !=
'' && is_array($extrafields->attributes[$this->table_element][
'param'][$attributeKey][
'options'])) {
7538 $tmparrays = array_keys($extrafields->attributes[$this->table_element][
'param'][$attributeKey][
'options']);
7539 $algo = reset($tmparrays);
7545 if (is_object($this->oldcopy)) {
7547 if (isset($this->oldcopy->array_options[
"options_".$key]) && $this->array_options[
"options_".$key] == $this->oldcopy->array_options[
"options_".$key]) {
7548 if ($algo ==
'dolcrypt') {
7549 if (!preg_match(
'/^dolcrypt:/', $this->array_options[
"options_".$key])) {
7550 $new_array_options[
"options_".$key] =
dolEncrypt($this->array_options[
"options_".$key]);
7552 $new_array_options[
"options_".$key] = $this->array_options[
"options_".$key];
7555 $new_array_options[
"options_".$key] = $this->array_options[
"options_".$key];
7558 if ($algo ==
'dolcrypt') {
7559 if (!preg_match(
'/^dolcrypt:/', $this->array_options[
"options_".$key])) {
7560 $new_array_options[
"options_".$key] =
dolEncrypt($this->array_options[
"options_".$key]);
7562 $new_array_options[
"options_".$key] = $this->array_options[
"options_".$key];
7565 $new_array_options[
"options_".$key] =
dol_hash($this->array_options[
"options_".$key], $algo);
7569 if ($algo ==
'dolcrypt' && !preg_match(
'/^dolcrypt:/', $this->array_options[
"options_".$key])) {
7570 $new_array_options[
"options_".$key] =
dolEncrypt($this->array_options[
"options_".$key]);
7572 $new_array_options[
"options_".$key] = $this->array_options[
"options_".$key];
7577 $new_array_options[
"options_".$key] = $this->array_options[
"options_".$key];
7580 $new_array_options[
"options_".$key] = $this->array_options[
"options_".$key];
7583 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7587 if (empty($this->array_options[
"options_".$key])) {
7588 $new_array_options[
"options_".$key] =
null;
7590 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7592 $new_array_options[
"options_".$key] = $this->db->idate($this->array_options[
"options_".$key]);
7596 if (empty($this->array_options[
"options_".$key])) {
7597 $new_array_options[
"options_".$key] =
null;
7599 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7601 $new_array_options[
"options_".$key] = $this->db->idate($this->array_options[
"options_".$key],
'gmt');
7605 if (empty($this->array_options[
"options_".$key])) {
7606 $new_array_options[
"options_".$key] =
null;
7608 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7612 if ($this->array_options[
"options_".$key] ===
'') {
7613 $new_array_options[
"options_".$key] =
null;
7615 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7649 $new_array_options = array();
7650 if (is_array($this->array_options[
"options_".$key])) {
7651 $new_array_options[
"options_".$key] = implode(
',', $this->array_options[
"options_".$key]);
7653 $new_array_options[
"options_".$key] = $this->array_options[
"options_".$key];
7656 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7662 $linealreadyfound = 0;
7665 $table_element = $this->table_element;
7666 if ($table_element ==
'categorie') {
7667 $table_element =
'categories';
7670 $sql =
"SELECT COUNT(rowid) as nb FROM ".$this->db->prefix().$table_element.
"_extrafields WHERE fk_object = ".((int) $this->
id);
7671 $resql = $this->db->query($sql);
7673 $tmpobj = $this->db->fetch_object($resql);
7675 $linealreadyfound = $tmpobj->nb;
7680 if ($linealreadyfound) {
7681 $sanitizedGeoDataType = ExtraFields::$geoDataTypes[$attributeType] ??
null;
7682 if ($this->array_options[
"options_".$key] ===
null) {
7683 $sql =
"UPDATE ".$this->db->prefix().$this->db->sanitize($table_element).
"_extrafields";
7684 $sql .=
" SET ".$this->db->sanitize($key).
" = null";
7685 } elseif (!empty($sanitizedGeoDataType[
'ST_Function'])) {
7686 $sql =
"UPDATE ".$this->db->prefix().$this->db->sanitize($table_element).
"_extrafields";
7687 $sql .=
" SET ".$this->db->sanitize($key).
" = ".$this->db->sanitize($sanitizedGeoDataType[
'ST_Function']).
"('".$this->db->escape($this->array_options[
"options_".$key]).
"')";
7690 $sql =
"UPDATE ".$this->db->prefix().$this->db->sanitize($table_element).
"_extrafields";
7691 $sql .=
" SET ".$this->db->sanitize($key).
" = '".$this->db->escape($new_array_options[
"options_".$key]).
"'";
7693 $sql .=
" WHERE fk_object = ".((int) $this->
id);
7695 $resql = $this->db->query($sql);
7698 $this->error = $this->db->lasterror();
7701 $result = $this->insertExtraFields(
'', $user);
7708 if (!$error && !empty($this->fields[
'fk_user_modif'])) {
7709 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
7710 $sql .=
" SET fk_user_modif = ".(int) $user->id;
7711 $sql .=
" WHERE ".(empty($this->table_rowid) ?
'rowid' : $this->db->sanitize($this->table_rowid)).
" = ".((
int)
$this->id);
7712 $this->db->query($sql);
7716 $parameters = array(
'key' => $key);
7718 $reshook = $hookmanager->executeHooks(
'updateExtraFieldBeforeCommit', $parameters, $this, $action);
7724 if (!$error && $trigger) {
7726 $this->context = array(
'extrafieldupdate' => 1);
7727 $result = $this->call_trigger($trigger, $userused);
7735 dol_syslog(__METHOD__.$this->error, LOG_ERR);
7736 $this->db->rollback();
7739 $this->db->commit();
7755 return $this->array_options[
'options_'.$key] ??
null;
7767 $this->array_options[
'options_'.$key] = $value;
7784 if (empty($userused)) {
7812 public function showInputField($val, $key, $value, $moreparam =
'', $keysuffix =
'', $keyprefix =
'', $morecss = 0, $nonewbutton = 0)
7814 global
$conf, $langs, $form;
7819 if (!is_object($form)) {
7820 require_once DOL_DOCUMENT_ROOT.
'/core/class/html.form.class.php';
7821 $form =
new Form($this->db);
7824 if (!empty($this->fields)) {
7825 $val = $this->fields[$key];
7829 $fieldValidationErrorMsg =
'';
7830 $validationClass =
'';
7831 $fieldValidationErrorMsg = $this->getFieldError($key);
7832 if (!empty($fieldValidationErrorMsg)) {
7833 $validationClass =
' --error';
7835 $validationClass =
' --success';
7843 $param[
'options'] = array();
7846 $size = !empty($this->fields[$key][
'size']) ? $this->fields[$key][
'size'] : 0;
7848 if (preg_match(
'/^(integer|link):(.*):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
7849 $param[
'options'] = array($reg[2].
':'.$reg[3].
':'.$reg[4].
':'.$reg[5] =>
'N');
7851 } elseif (preg_match(
'/^(integer|link):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
7852 $param[
'options'] = array($reg[2].
':'.$reg[3].
':'.$reg[4] =>
'N');
7854 } elseif (preg_match(
'/^(integer|link):(.*):(.*)/i', $val[
'type'], $reg)) {
7855 $param[
'options'] = array($reg[2].
':'.$reg[3] =>
'N');
7857 } elseif (preg_match(
'/^(sellist):(.*):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
7858 $param[
'options'] = array($reg[2].
':'.$reg[3].
':'.$reg[4].
':'.$reg[5] =>
'N');
7860 } elseif (preg_match(
'/^(sellist):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
7861 $param[
'options'] = array($reg[2].
':'.$reg[3].
':'.$reg[4] =>
'N');
7863 } elseif (preg_match(
'/^(sellist):(.*):(.*)/i', $val[
'type'], $reg)) {
7864 $param[
'options'] = array($reg[2].
':'.$reg[3] =>
'N');
7866 } elseif (preg_match(
'/^chkbxlst:(.*)/i', $val[
'type'], $reg)) {
7867 $param[
'options'] = array($reg[1] =>
'N');
7869 } elseif (preg_match(
'/varchar\((\d+)\)/', $val[
'type'], $reg)) {
7870 $param[
'options'] = array();
7873 } elseif (preg_match(
'/varchar/', $val[
'type'])) {
7874 $param[
'options'] = array();
7876 } elseif (preg_match(
'/stars\((\d+)\)/', $val[
'type'], $reg)) {
7877 $param[
'options'] = array();
7881 $param[
'options'] = array();
7882 $type = $this->fields[$key][
'type'];
7887 if (!empty($this->fields[$key][
'arrayofkeyval']) && is_array($this->fields[$key][
'arrayofkeyval'])) {
7888 $param[
'options'] = $this->fields[$key][
'arrayofkeyval'];
7890 if (empty($this->fields[$key][
'multiinput'])) {
7891 $type = (($this->fields[$key][
'type'] ==
'checkbox') ? $this->fields[$key][
'type'] :
'select');
7895 $label = $this->fields[$key][
'label'];
7898 $default = (!empty($this->fields[$key][
'default']) ? $this->fields[$key][
'default'] :
'');
7900 $computed = (!empty($this->fields[$key][
'computed']) ? $this->fields[$key][
'computed'] :
'');
7902 $unique = (!empty($this->fields[$key][
'unique']) ? $this->fields[$key][
'unique'] : 0);
7904 $required = (!empty($this->fields[$key][
'required']) ? $this->fields[$key][
'required'] : 0);
7906 $autofocusoncreate = (!empty($this->fields[$key][
'autofocusoncreate']) ? $this->fields[$key][
'autofocusoncreate'] : 0);
7908 $placeholder = (!empty($this->fields[$key][
'placeholder']) ? $this->fields[$key][
'placeholder'] : 0);
7911 $langfile = (!empty($this->fields[$key][
'langfile']) ? $this->fields[$key][
'langfile'] :
'');
7913 $list = (!empty($this->fields[$key][
'list']) ? $this->fields[$key][
'list'] : 0);
7914 $hidden = (in_array(abs($this->fields[$key][
'visible']), array(0, 2)) ? 1 : 0);
7919 if (!preg_match(
'/^search_/', $keyprefix)) {
7920 return '<span class="opacitymedium">'.$langs->trans(
"AutomaticallyCalculated").
'</span>';
7927 if (empty($morecss) && !empty($val[
'css'])) {
7928 $morecss = $val[
'css'];
7929 } elseif (empty($morecss)) {
7930 if ($type ==
'date') {
7931 $morecss =
'minwidth100imp';
7932 } elseif ($type ==
'datetime' || $type ==
'link') {
7933 $morecss =
'minwidth200imp';
7934 } elseif (in_array($type, array(
'int',
'integer',
'price')) || preg_match(
'/^double(\([0-9],[0-9]\)){0,1}/', (
string) $type)) {
7935 $morecss =
'maxwidth75';
7936 } elseif ($type ==
'url') {
7937 $morecss =
'minwidth400';
7938 } elseif ($type ==
'boolean') {
7941 if (is_numeric($size) && round((
float) $size) < 12) {
7942 $morecss =
'minwidth100';
7943 } elseif (is_numeric($size) && round((
float) $size) <= 48) {
7944 $morecss =
'minwidth200';
7946 $morecss =
'minwidth400';
7952 if (!empty($validationClass)) {
7953 $morecss .= $validationClass;
7956 if (in_array($type, array(
'date'))) {
7957 $tmp = explode(
',', $size);
7962 if (!$required && $value ==
'') {
7967 $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required,
'', 1, (($keyprefix !=
'search_' && $keyprefix !=
'search_options_') ? 1 : 0), 0, 1);
7968 } elseif (in_array($type, array(
'datetime'))) {
7969 $tmp = explode(
',', $size);
7974 if (!$required && $value ==
'') {
7979 $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required,
'', 1, (($keyprefix !=
'search_' && $keyprefix !=
'search_options_') ? 1 : 0), 0, 1,
'',
'',
'', 1,
'',
'',
'tzuserrel');
7980 } elseif (in_array($type, array(
'duration'))) {
7981 $out = $form->select_duration($keyprefix.$key.$keysuffix, $value, 0,
'text', 0, 1);
7982 } elseif (in_array($type, array(
'int',
'integer'))) {
7983 $tmp = explode(
',', $size);
7985 $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' :
'').
'>';
7986 } elseif (in_array($type, array(
'real'))) {
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(
'/varchar/', (
string) $type)) {
7989 $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' :
'').
'>';
7990 } elseif (in_array($type, array(
'email',
'mail',
'phone',
'url',
'ip'))) {
7991 $out =
'<input type="text" class="flat '.$morecss.
'" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.
dol_escape_htmltag($value).
'" '.($moreparam ? $moreparam :
'').($autofocusoncreate ?
' autofocus' :
'').
'>';
7992 } elseif (preg_match(
'/^text/', (
string) $type)) {
7993 if (!preg_match(
'/search_/', $keyprefix)) {
7994 if (!empty($param[
'options'])) {
7997 $out .= $form->selectarray($keyprefix.$key.$keysuffix.
"_multiinput", $param[
'options'],
'', 1, 0, 0,
"flat maxwidthonphone".$morecss);
7998 $out .=
'<input id="'.$keyprefix.$key.$keysuffix.
'_multiinputadd" type="button" class="button" value="'.$langs->trans(
"Add").
'">';
8001 function handlemultiinputdisabling(htmlname){
8002 console.log("We handle the disabling of used options for "+htmlname+"_multiinput");
8003 multiinput = $("#"+htmlname+"_multiinput");
8004 multiinput.find("option").each(function(){
8005 tmpval = $("#"+htmlname).val();
8006 tmpvalarray = tmpval.split("\n");
8007 valtotest = $(this).val();
8008 if(tmpvalarray.includes(valtotest)){
8009 $(this).prop("disabled",true);
8011 if($(this).prop("disabled") == true){
8012 console.log(valtotest)
8013 $(this).prop("disabled", false);
8019 $(document).ready(function () {
8020 $("#'.$keyprefix.$key.$keysuffix.
'_multiinputadd").on("click",function() {
8021 tmpval = $("#'.$keyprefix.$key.$keysuffix.
'").val();
8022 tmpvalarray = tmpval.split(",");
8023 valtotest = $("#'.$keyprefix.$key.$keysuffix.
'_multiinput").val();
8024 if(valtotest != -1 && !tmpvalarray.includes(valtotest)){
8025 console.log("We add the selected value to the text area '.$keyprefix.$key.$keysuffix.
'");
8029 tmpval = tmpval + "\n" + valtotest;
8031 $("#'.$keyprefix.$key.$keysuffix.
'").val(tmpval);
8032 handlemultiinputdisabling("'.$keyprefix.$key.$keysuffix.
'");
8033 $("#'.$keyprefix.$key.$keysuffix.
'_multiinput").val(-1);
8035 console.log("We add nothing the text area '.$keyprefix.$key.$keysuffix.
'");
8038 $("#'.$keyprefix.$key.$keysuffix.
'").on("change",function(){
8039 handlemultiinputdisabling("'.$keyprefix.$key.$keysuffix.
'");
8041 handlemultiinputdisabling("'.$keyprefix.$key.$keysuffix.
'");
8043 $out .=
"</script>";
8044 $value = str_replace(
',',
"\n", $value);
8046 require_once DOL_DOCUMENT_ROOT.
'/core/class/doleditor.class.php';
8047 $doleditor =
new DolEditor($keyprefix.$key.$keysuffix, $value,
'', 200,
'dolibarr_notes',
'In',
false,
false,
false, ROWS_5,
'90%');
8048 $out .= (
string) $doleditor->Create(1,
'',
true,
'',
'',
'', $morecss);
8050 $out =
'<input type="text" class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.
dol_escape_htmltag($value).
'" '.($moreparam ? $moreparam :
'').
'>';
8052 } elseif (preg_match(
'/^html/', (
string) $type)) {
8053 if (!preg_match(
'/search_/', $keyprefix)) {
8054 require_once DOL_DOCUMENT_ROOT.
'/core/class/doleditor.class.php';
8055 $doleditor =
new DolEditor($keyprefix.$key.$keysuffix, $value,
'', 200,
'dolibarr_notes',
'In',
false,
false,
isModEnabled(
'fckeditor') &&
getDolGlobalInt(
'FCKEDITOR_ENABLE_SOCIETE'), ROWS_5,
'90%');
8056 $out = (
string) $doleditor->Create(1,
'',
true,
'',
'', $moreparam, $morecss);
8058 $out =
'<input type="text" class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.
dol_escape_htmltag($value).
'" '.($moreparam ? $moreparam :
'').
'>';
8060 } elseif ($type ==
'boolean') {
8062 if (!empty($value)) {
8063 $checked =
' checked value="1" ';
8065 $checked =
' value="1" ';
8067 $out =
'<input type="checkbox" class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" '.$checked.
' '.($moreparam ? $moreparam :
'').
'>';
8068 } elseif ($type ==
'price') {
8069 if (!empty($value)) {
8070 $value =
price($value);
8072 $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>';
8073 } elseif ($type ==
'stars') {
8074 $out =
'<input type="hidden" class="flat '.$morecss.
'" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.
dol_escape_htmltag($value).
'"'.($moreparam ? $moreparam :
'').($autofocusoncreate ?
' autofocus' :
'').
'>';
8075 $out .=
'<div class="star-selection" id="'.$keyprefix.$key.$keysuffix.
'_selection">';
8077 while ($i <= $size) {
8078 $out .=
'<span class="star" data-value="'.$i.
'">'.
img_picto(
'',
'fontawesome_star_fas').
'</span>';
8083 jQuery(function($) { /* commonobject.class.php 1 */
8084 let container = $("#'.$keyprefix.$key.$keysuffix.
'_selection");
8085 let selectedStars = parseInt($("#'.$keyprefix.$key.$keysuffix.
'").val()) || 0;
8086 container.find(".star").each(function() {
8087 $(this).toggleClass("active", $(this).data("value") <= selectedStars);
8089 container.find(".star").on("mouseover", function() {
8090 let selectedStar = $(this).data("value");
8091 container.find(".star").each(function() {
8092 $(this).toggleClass("active", $(this).data("value") <= selectedStar);
8095 container.on("mouseout", function() {
8096 container.find(".star").each(function() {
8097 $(this).toggleClass("active", $(this).data("value") <= selectedStars);
8100 container.find(".star").off("click").on("click", function() {
8101 selectedStars = $(this).data("value");
8102 if (selectedStars === 1 && $("#'.$keyprefix.$key.$keysuffix.
'").val() == 1) {
8105 $("#'.$keyprefix.$key.$keysuffix.
'").val(selectedStars);
8106 container.find(".star").each(function() {
8107 $(this).toggleClass("active", $(this).data("value") <= selectedStars);
8112 } elseif (preg_match(
'/^double(\([0-9],[0-9]\)){0,1}/', (
string) $type)) {
8113 if (!empty($value)) {
8114 $value =
price($value);
8116 $out =
'<input type="text" class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.$value.
'" '.($moreparam ? $moreparam :
'').
'> ';
8117 } elseif ($type ==
'select') {
8120 include_once DOL_DOCUMENT_ROOT.
'/core/lib/ajax.lib.php';
8121 $out .=
ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
8127 foreach ($param[
'options'] as $keyb => $valb) {
8128 if ((
string) $keyb ==
'') {
8131 if (strpos($valb,
"|") !==
false) {
8132 list($valb, $parent) = explode(
'|', $valb);
8135 $tmpselect .=
'<option value="'.$keyb.
'"';
8136 $tmpselect .= (((
string) $value == (
string) $keyb) ?
' selected' :
'');
8137 if (!empty($parent)) {
8140 $tmpselect .= (!empty($parent) ?
' parent="'.$parent.
'"' :
'');
8141 $tmpselect .=
'>'.$langs->trans($valb).
'</option>';
8144 $out .=
'<select class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" '.($moreparam ? $moreparam :
'').
'>';
8145 if ((!isset($this->fields[$key][
'default'])) || empty($this->fields[$key][
'notnull']) || ($this->fields[$key][
'notnull'] != 1) || $nbchoice >= 2) {
8146 $out .=
'<option value="0"> </option>';
8149 $out .=
'</select>';
8150 } elseif ($type ==
'sellist') {
8153 include_once DOL_DOCUMENT_ROOT.
'/core/lib/ajax.lib.php';
8154 $out .=
ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
8157 $out .=
'<select class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" '.($moreparam ? $moreparam :
'').
'>';
8158 if (is_array($param[
'options'])) {
8159 $tmpparamoptions = array_keys($param[
'options']);
8160 $paramoptions = preg_split(
'/[\r\n]+/', $tmpparamoptions[0]);
8162 $InfoFieldList = explode(
":", $paramoptions[0], 5);
8174 if (! empty($InfoFieldList[4])) {
8176 $parenthesisopen = 0;
8177 while (substr($InfoFieldList[4], $pos, 1) !==
'' && ($parenthesisopen || $pos == 0 || substr($InfoFieldList[4], $pos, 1) !=
':')) {
8178 if (substr($InfoFieldList[4], $pos, 1) ==
'(') {
8181 if (substr($InfoFieldList[4], $pos, 1) ==
')') {
8186 $tmpbefore = substr($InfoFieldList[4], 0, $pos);
8187 $tmpafter = substr($InfoFieldList[4], $pos + 1);
8189 $InfoFieldList[4] = $tmpbefore;
8190 if ($tmpafter !==
'') {
8191 $InfoFieldList = array_merge($InfoFieldList, explode(
':', $tmpafter));
8197 if (preg_match(
'/^\(?([a-z0-9]+)([=<>]+)(\d+)\)?$/i', $InfoFieldList[4], $reg)) {
8198 $InfoFieldList[4] =
'('.$reg[1].
':'.$reg[2].
':'.$reg[3].
')';
8209 $keyList = (empty($InfoFieldList[2]) ?
'rowid' : $InfoFieldList[2].
' as rowid');
8211 if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
8212 if (strpos($InfoFieldList[4],
'extra.') !==
false) {
8213 $keyList =
'main.'.$InfoFieldList[2].
' as rowid';
8215 $keyList = $InfoFieldList[2].
' as rowid';
8218 if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
8219 list($parentName, $parentField) = explode(
'|', $InfoFieldList[3]);
8220 if (!empty($InfoFieldList[4]) && strpos($InfoFieldList[4],
'extra.') !==
false) {
8221 $keyList .=
', main.'.$parentField;
8223 $keyList .=
', '.$parentField;
8227 $filter_categorie =
false;
8228 if (count($InfoFieldList) > 5) {
8229 if ($InfoFieldList[0] ==
'categorie') {
8230 $filter_categorie =
true;
8234 if (!$filter_categorie) {
8235 $fields_label = isset($InfoFieldList[1]) ? explode(
'|', $InfoFieldList[1]) : array();
8236 if (!empty($fields_label)) {
8238 $keyList .= implode(
', ', $fields_label);
8242 $sql =
"SELECT " . $this->db->sanitize($keyList, 0, 0, 1);
8243 $sql .=
" FROM " . $this->db->prefix() . $this->db->sanitize($InfoFieldList[0]);
8245 if (!empty($InfoFieldList[4])) {
8247 if (strpos($InfoFieldList[4],
'$SEL$') !==
false) {
8248 $InfoFieldList[4] = str_replace(
'$SEL$',
'SELECT', $InfoFieldList[4]);
8252 if (strpos($InfoFieldList[4],
'$ID$') !==
false && !empty($objectid)) {
8253 $InfoFieldList[4] = str_replace(
'$ID$', (
string) $objectid, $InfoFieldList[4]);
8255 $InfoFieldList[4] = str_replace(
'$ID$',
'0', $InfoFieldList[4]);
8260 if (strpos($InfoFieldList[4],
'extra') !==
false) {
8261 $sql .=
" as main, " . $this->db->sanitize($this->db->prefix() . $InfoFieldList[0]) .
"_extrafields as extra";
8262 $sqlwhere .=
" WHERE extra.fk_object = main." . $this->db->sanitize($InfoFieldList[2]);
8268 $sqlwhere .=
' WHERE 1=1';
8285 if (in_array($InfoFieldList[0], array(
'tablewithentity'))) {
8286 $sqlwhere .=
" AND entity = " . ((int)
$conf->entity);
8291 if (isset($InfoFieldList[7]) && preg_match(
'/^[a-z0-9_\-,]+$/i', $InfoFieldList[7])) {
8292 $sql .=
" ORDER BY ".$this->db->escape($InfoFieldList[7]);
8294 $sql .=
" ORDER BY ".$this->db->sanitize(implode(
', ', $fields_label));
8296 $sql .=
' LIMIT ' .
getDolGlobalInt(
'MAIN_EXTRAFIELDS_LIMIT_SELLIST_SQL', 1000);
8299 dol_syslog(get_class($this) .
'::showInputField type=sellist', LOG_DEBUG);
8300 $resql = $this->db->query($sql);
8302 $out .=
'<option value="0"> </option>';
8303 $num = $this->db->num_rows($resql);
8307 $obj = $this->db->fetch_object($resql);
8311 $fields_label = explode(
'|', $InfoFieldList[1]);
8312 if (count($fields_label) > 1) {
8314 foreach ($fields_label as $field_toshow) {
8315 $labeltoshow .= $obj->$field_toshow .
' ';
8318 $labeltoshow = $obj->{$InfoFieldList[1]};
8320 $labeltoshow =
dol_trunc($labeltoshow, 45);
8322 if ($value == $obj->rowid) {
8323 foreach ($fields_label as $field_toshow) {
8324 $translabel = $langs->trans($obj->$field_toshow);
8325 if ($translabel != $obj->$field_toshow) {
8326 $labeltoshow =
dol_trunc($translabel) .
' ';
8328 $labeltoshow =
dol_trunc($obj->$field_toshow) .
' ';
8331 $out .=
'<option value="' . $obj->rowid .
'" selected>' . $labeltoshow .
'</option>';
8334 $translabel = $langs->trans($obj->{$InfoFieldList[1]});
8335 if ($translabel != $obj->{$InfoFieldList[1]}) {
8336 $labeltoshow =
dol_trunc($translabel, 18);
8338 $labeltoshow =
dol_trunc($obj->{$InfoFieldList[1]});
8341 if (empty($labeltoshow)) {
8342 $labeltoshow =
'(not defined)';
8344 if ($value == $obj->rowid) {
8345 $out .=
'<option value="' . $obj->rowid .
'" selected>' . $labeltoshow .
'</option>';
8348 if (!empty($InfoFieldList[3]) && $parentField) {
8349 $parent = $parentName .
':' . $obj->{$parentField};
8353 $out .=
'<option value="' . $obj->rowid .
'"';
8354 $out .= ($value == $obj->rowid ?
' selected' :
'');
8355 $out .= (!empty($parent) ?
' parent="' . $parent .
'"' :
'');
8356 $out .=
'>' . $labeltoshow .
'</option>';
8361 $this->db->free($resql);
8363 print
'Error in request ' . $sql .
' ' . $this->db->lasterror() .
'. Check setup of extra parameters.<br>';
8366 require_once DOL_DOCUMENT_ROOT.
'/categories/class/categorie.class.php';
8367 $categcode = $InfoFieldList[5];
8368 if (is_numeric($categcode)) {
8369 $tmpcategory =
new Categorie($this->db);
8370 $MAP_ID_TO_CODE = array_flip($tmpcategory->MAP_ID);
8371 $categcode = $MAP_ID_TO_CODE[(int) $categcode];
8374 $data = $form->select_all_categories($categcode,
'',
'parent', 64, $InfoFieldList[6], 1, 1);
8375 $out .=
'<option value="0"> </option>';
8376 foreach ($data as $data_key => $data_value) {
8377 $out .=
'<option value="' . $data_key .
'"';
8378 $out .= ($value == $data_key ?
' selected' :
'');
8379 $out .=
'>' . $data_value .
'</option>';
8383 $out .=
'</select>';
8384 } elseif ($type ==
'checkbox') {
8385 $value_arr = explode(
',', $value);
8386 $out = $form->multiselectarray($keyprefix.$key.$keysuffix, (empty($param[
'options']) ?
null : $param[
'options']), $value_arr, 0, 0, $morecss, 0,
'100%');
8387 } elseif ($type ==
'radio') {
8389 foreach ($param[
'options'] as $keyopt => $valopt) {
8390 $out .=
'<input class="flat '.$morecss.
'" type="radio" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" '.($moreparam ? $moreparam :
'');
8391 $out .=
' value="'.$keyopt.
'"';
8392 $out .=
' id="'.$keyprefix.$key.$keysuffix.
'_'.$keyopt.
'"';
8393 $out .= ($value == $keyopt ?
'checked' :
'');
8394 $out .=
'/><label for="'.$keyprefix.$key.$keysuffix.
'_'.$keyopt.
'">'.$valopt.
'</label><br>';
8396 } elseif ($type ==
'chkbxlst') {
8397 if (is_array($value)) {
8398 $value_arr = $value;
8400 $value_arr = explode(
',', $value);
8403 if (is_array($param[
'options'])) {
8404 $tmpparamoptions = array_keys($param[
'options']);
8405 $paramoptions = preg_split(
'/[\r\n]+/', $tmpparamoptions[0]);
8407 $InfoFieldList = explode(
":", $paramoptions[0], 5);
8419 if (! empty($InfoFieldList[4])) {
8421 $parenthesisopen = 0;
8422 while (substr($InfoFieldList[4], $pos, 1) !==
'' && ($parenthesisopen || $pos == 0 || substr($InfoFieldList[4], $pos, 1) !=
':')) {
8423 if (substr($InfoFieldList[4], $pos, 1) ==
'(') {
8426 if (substr($InfoFieldList[4], $pos, 1) ==
')') {
8431 $tmpbefore = substr($InfoFieldList[4], 0, $pos);
8432 $tmpafter = substr($InfoFieldList[4], $pos + 1);
8434 $InfoFieldList[4] = $tmpbefore;
8435 if ($tmpafter !==
'') {
8436 $InfoFieldList = array_merge($InfoFieldList, explode(
':', $tmpafter));
8441 if (preg_match(
'/^\(?([a-z0-9]+)([=<>]+)(\d+)\)?$/i', $InfoFieldList[4], $reg)) {
8442 $InfoFieldList[4] =
'('.$reg[1].
':'.$reg[2].
':'.$reg[3].
')';
8450 '@phan-var-force array{0:string,1:string,2:string,3:string,3:string,5:string,6:string} $InfoFieldList';
8455 $keyList = (empty($InfoFieldList[2]) ?
'rowid' : $InfoFieldList[2].
' as rowid');
8457 if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
8458 if (strpos($InfoFieldList[4],
'extra.') !==
false) {
8459 $keyList =
'main.'.$InfoFieldList[2].
' as rowid';
8461 $keyList = $InfoFieldList[2].
' as rowid';
8464 if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
8465 list($parentName, $parentField) = explode(
'|', $InfoFieldList[3]);
8466 if (!empty($InfoFieldList[4]) && strpos($InfoFieldList[4],
'extra.') !==
false) {
8467 $keyList .=
', main.'.$parentField;
8469 $keyList .=
', '.$parentField;
8473 $filter_categorie =
false;
8474 if (count($InfoFieldList) > 5) {
8475 if ($InfoFieldList[0] ==
'categorie') {
8476 $filter_categorie =
true;
8481 if (!$filter_categorie) {
8482 $fields_label = explode(
'|', $InfoFieldList[1]);
8483 if (is_array($fields_label)) {
8485 $keyList .= implode(
', ', $fields_label);
8489 $sql =
"SELECT " . $this->db->sanitize($keyList, 0, 0, 1);
8490 $sql .=
' FROM ' . $this->db->prefix() . $this->db->sanitize($InfoFieldList[0]);
8492 if (!empty($InfoFieldList[4])) {
8494 if (strpos($InfoFieldList[4],
'$SEL$') !==
false) {
8495 $InfoFieldList[4] = str_replace(
'$SEL$',
'SELECT', $InfoFieldList[4]);
8499 if (strpos($InfoFieldList[4],
'$ID$') !==
false && !empty($objectid)) {
8500 $InfoFieldList[4] = str_replace(
'$ID$', (
string) $objectid, $InfoFieldList[4]);
8502 $InfoFieldList[4] = str_replace(
'$ID$',
'0', $InfoFieldList[4]);
8507 if (strpos($InfoFieldList[4],
'extra') !==
false) {
8508 $sql .=
' as main, ' . $this->db->sanitize($this->db->prefix() . $InfoFieldList[0]) .
'_extrafields as extra';
8509 $sqlwhere .=
" WHERE extra.fk_object = main." . $this->db->sanitize($InfoFieldList[2]);
8515 $sqlwhere .=
' WHERE 1=1';
8532 if (in_array($InfoFieldList[0], array(
'tablewithentity'))) {
8533 $sqlwhere .=
" AND entity = " . ((int)
$conf->entity);
8540 dol_syslog(get_class($this) .
'::showInputField type=chkbxlst', LOG_DEBUG);
8542 $resql = $this->db->query($sql);
8544 $num = $this->db->num_rows($resql);
8551 $obj = $this->db->fetch_object($resql);
8555 $fields_label = explode(
'|', $InfoFieldList[1]);
8556 if (count($fields_label) > 1) {
8558 foreach ($fields_label as $field_toshow) {
8559 $labeltoshow .= $obj->$field_toshow .
' ';
8562 $labeltoshow = $obj->{$InfoFieldList[1]};
8564 $labeltoshow =
dol_trunc($labeltoshow, 45);
8566 if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
8567 foreach ($fields_label as $field_toshow) {
8568 $translabel = $langs->trans($obj->$field_toshow);
8569 if ($translabel != $obj->$field_toshow) {
8570 $labeltoshow =
dol_trunc($translabel, 18) .
' ';
8572 $labeltoshow =
dol_trunc($obj->$field_toshow, 18) .
' ';
8576 $data[$obj->rowid] = $labeltoshow;
8579 $translabel = $langs->trans($obj->{$InfoFieldList[1]});
8580 if ($translabel != $obj->{$InfoFieldList[1]}) {
8581 $labeltoshow =
dol_trunc($translabel, 18);
8583 $labeltoshow =
dol_trunc($obj->{$InfoFieldList[1]}, 18);
8586 if (empty($labeltoshow)) {
8587 $labeltoshow =
'(not defined)';
8590 if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
8591 $data[$obj->rowid] = $labeltoshow;
8594 if (!empty($InfoFieldList[3]) && $parentField) {
8595 $parent = $parentName .
':' . $obj->{$parentField};
8599 $data[$obj->rowid] = $labeltoshow;
8604 $this->db->free($resql);
8606 $out = $form->multiselectarray($keyprefix . $key . $keysuffix, $data, $value_arr, 0, 0, $morecss, 0,
'100%');
8608 print
'Error in request ' . $sql .
' ' . $this->db->lasterror() .
'. Check setup of extra parameters.<br>';
8611 require_once DOL_DOCUMENT_ROOT.
'/categories/class/categorie.class.php';
8612 $categcode = $InfoFieldList[5];
8613 if (is_numeric($categcode)) {
8614 $tmpcategory =
new Categorie($this->db);
8615 $MAP_ID_TO_CODE = array_flip($tmpcategory->MAP_ID);
8616 $categcode = $MAP_ID_TO_CODE[(int) $categcode];
8619 $data = $form->select_all_categories($categcode,
'',
'parent', 64, $InfoFieldList[6], 1, 1);
8620 $out = $form->multiselectarray($keyprefix . $key . $keysuffix, $data, $value_arr, 0, 0, $morecss, 0,
'100%');
8623 } elseif ($type ==
'link') {
8626 $param_list = array_keys($param[
'options']);
8627 $param_list_array = explode(
':', $param_list[0], 4);
8629 $showempty = (($required && $default !=
'') ? 0 : 1);
8631 if (!preg_match(
'/search_/', $keyprefix)) {
8632 if (!empty($param_list_array[2])) {
8634 if (!empty($this->fields[$key][
'picto'])) {
8635 $morecss .=
' widthcentpercentminusxx';
8637 $morecss .=
' widthcentpercentminusx';
8641 if (!empty($this->fields[$key][
'picto'])) {
8642 $morecss .=
' widthcentpercentminusx';
8651 $objectfield = $val;
8654 $out = $form->selectForForms($param_list_array[0], $keyprefix.$key.$keysuffix, (
int) $value, $showempty,
'',
'', $morecss, $moreparam, 0, (empty($val[
'disabled']) ? 0 : 1),
'', $objectfield);
8656 if (!empty($param_list_array[2])) {
8657 if ((!GETPOSTISSET(
'backtopage') || strpos(
GETPOST(
'backtopage'), $_SERVER[
'PHP_SELF']) === 0)
8658 && empty($val[
'disabled']) && empty($nonewbutton)) {
8659 list($class, $classfile) = explode(
':', $param_list[0]);
8660 if (file_exists(
dol_buildpath(dirname(dirname($classfile)).
'/card.php'))) {
8661 $url_path =
dol_buildpath(dirname(dirname($classfile)).
'/card.php', 1);
8663 $url_path =
dol_buildpath(dirname(dirname($classfile)).
'/'.strtolower($class).
'_card.php', 1);
8665 $paramforthenewlink =
'';
8666 $paramforthenewlink .= (GETPOSTISSET(
'action') ?
'&action='.GETPOST(
'action',
'aZ09') :
'');
8667 $paramforthenewlink .= (GETPOSTISSET(
'id') ?
'&id='.GETPOSTINT(
'id') :
'');
8668 $paramforthenewlink .= (GETPOSTISSET(
'origin') ?
'&origin='.GETPOST(
'origin',
'aZ09') :
'');
8669 $paramforthenewlink .= (GETPOSTISSET(
'originid') ?
'&originid='.GETPOSTINT(
'originid') :
'');
8670 $paramforthenewlink .=
'&fk_'.strtolower($class).
'=--IDFORBACKTOPAGE--';
8672 $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>';
8675 } elseif ($type ==
'password') {
8677 if ($keyprefix.$key.$keysuffix ==
'pass_crypted') {
8678 $out =
'<input type="'.($keyprefix ==
'search_' ?
'text' :
'password').
'" class="flat '.$morecss.
'" name="pass" id="pass" value="" '.($moreparam ? $moreparam :
'').
'>';
8679 $out .=
'<input type="hidden" name="pass_crypted" id="pass_crypted" value="'.$value.
'" '.($moreparam ? $moreparam :
'').
'>';
8681 $out =
'<input type="'.($keyprefix ==
'search_' ?
'text' :
'password').
'" class="flat '.$morecss.
'" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.$value.
'" '.($moreparam ? $moreparam :
'').
'>';
8683 } elseif ($type ==
'array') {
8685 $newval[
'type'] =
'varchar(256)';
8688 if (!empty($value)) {
8689 foreach ($value as $option) {
8690 $out .=
'<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).
'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
8691 $out .= $this->showInputField($newval, $keyprefix.$key.$keysuffix.
'[]', $option, $moreparam,
'',
'', $morecss).
'<br></span>';
8694 $out .=
'<a id="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).
'_add" href="javascript:;"><span class="fa fa-plus-circle valignmiddle"></span></a>';
8696 $newInput =
'<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).
'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
8697 $newInput .= $this->showInputField($newval, $keyprefix.$key.$keysuffix.
'[]',
'', $moreparam,
'',
'', $morecss).
'<br></span>';
8699 if (!empty(
$conf->use_javascript_ajax)) {
8701 <script nonce="'.getNonce().
'">
8702 $(document).ready(function() {
8703 $("a#'.
dol_escape_js($keyprefix.$key.$keysuffix).
'_add").click(function() {
8707 $(document).on("click", "a.'.
dol_escape_js($keyprefix.$key.$keysuffix).
'_del", function() {
8708 $(this).parent().remove();
8714 if (!empty($hidden)) {
8715 $out =
'<input type="hidden" value="'.$value.
'" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'"/>';
8718 if ($isDependList == 1) {
8719 $out .= $this->getJSListDependancies(
'_common');
8727 if (!empty($fieldValidationErrorMsg) && function_exists(
'getFieldErrorIcon')) {
8728 $out .=
' '.getFieldErrorIcon($fieldValidationErrorMsg);
8747 public function showOutputField($val, $key, $value, $moreparam =
'', $keysuffix =
'', $keyprefix =
'', $morecss =
'')
8749 global
$conf, $langs, $form;
8753 if (!is_object($form)) {
8754 require_once DOL_DOCUMENT_ROOT.
'/core/class/html.form.class.php';
8755 $form =
new Form($this->db);
8759 $type = empty($val[
'type']) ?
'' : $val[
'type'];
8760 $size = empty($val[
'css']) ?
'' : $val[
'css'];
8765 if (preg_match(
'/varchar\((\d+)\)/', $type, $reg)) {
8768 } elseif (preg_match(
'/varchar/', $type)) {
8771 if (!empty($val[
'arrayofkeyval']) && is_array($val[
'arrayofkeyval'])) {
8773 if (empty($this->fields[$key][
'multiinput'])) {
8774 $type = (($this->fields[$key][
'type'] ==
'checkbox') ? $this->fields[$key][
'type'] :
'select');
8777 if (isset($val[
'type']) && preg_match(
'/^integer:(.*):(.*)/i', $val[
'type'], $reg)) {
8781 $default = empty($val[
'default']) ?
'' : $val[
'default'];
8782 $computed = empty($val[
'computed']) ?
'' : $val[
'computed'];
8783 $unique = empty($val[
'unique']) ?
'' : $val[
'unique'];
8784 $required = empty($val[
'required']) ?
'' : $val[
'required'];
8786 $param[
'options'] = array();
8788 if (!empty($val[
'arrayofkeyval']) && is_array($val[
'arrayofkeyval'])) {
8789 $param[
'options'] = $val[
'arrayofkeyval'];
8791 if (isset($val[
'type']) && preg_match(
'/^integer:([^:]*):([^:]*)/i', $val[
'type'], $reg)) {
8793 $stringforoptions = $reg[1].
':'.$reg[2];
8795 if ($reg[1] ==
'User') {
8796 $stringforoptions .=
':#getnomurlparam1=-1';
8798 $param[
'options'] = array($stringforoptions => $stringforoptions);
8799 } elseif (isset($val[
'type']) && preg_match(
'/^sellist:(.*):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
8800 $param[
'options'] = array($reg[1].
':'.$reg[2].
':'.$reg[3].
':'.$reg[4] =>
'N');
8802 } elseif (isset($val[
'type']) && preg_match(
'/^sellist:(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
8803 $param[
'options'] = array($reg[1].
':'.$reg[2].
':'.$reg[3] =>
'N');
8805 } elseif (isset($val[
'type']) && preg_match(
'/^sellist:(.*):(.*)/i', $val[
'type'], $reg)) {
8806 $param[
'options'] = array($reg[1].
':'.$reg[2] =>
'N');
8808 } elseif (isset($val[
'type']) && preg_match(
'/^chkbxlst:(.*)/i', $val[
'type'], $reg)) {
8809 $param[
'options'] = array($reg[1] =>
'N');
8811 } elseif (isset($val[
'type']) && preg_match(
'/stars\((\d+)\)/', $val[
'type'], $reg)) {
8812 $param[
'options'] = array();
8817 $langfile = empty($val[
'langfile']) ?
'' : $val[
'langfile'];
8818 $list = (empty($val[
'list']) ?
'' : $val[
'list']);
8819 $help = (empty($val[
'help']) ?
'' : $val[
'help']);
8820 $hidden = (($val[
'visible'] == 0) ? 1 : 0);
8830 $value =
dol_eval((
string) $computed, 1, 0,
'2');
8833 if (empty($morecss)) {
8834 if ($type ==
'date') {
8835 $morecss =
'minwidth100imp';
8836 } elseif ($type ==
'datetime' || $type ==
'timestamp') {
8837 $morecss =
'minwidth200imp';
8838 } elseif (in_array($type, array(
'int',
'double',
'price'))) {
8839 $morecss =
'maxwidth75';
8840 } elseif ($type ==
'url') {
8841 $morecss =
'minwidth400';
8842 } elseif ($type ==
'boolean') {
8845 if (is_numeric($size) && round((
float) $size) < 12) {
8846 $morecss =
'minwidth100';
8847 } elseif (is_numeric($size) && round((
float) $size) <= 48) {
8848 $morecss =
'minwidth200';
8850 $morecss =
'minwidth400';
8856 if (in_array($key, array(
'rowid',
'ref')) && method_exists($this,
'getNomUrl')) {
8858 if ($key !=
'rowid' || empty($this->fields[
'ref'])) {
8859 $value = $this->getNomUrl(1,
'', 0,
'', 1);
8861 } elseif ($key ==
'status' && method_exists($this,
'getLibStatut')) {
8862 $value = $this->getLibStatut(3);
8863 } elseif ($type ==
'date') {
8864 if (!empty($value)) {
8869 } elseif ($type ==
'datetime' || $type ==
'timestamp') {
8870 if (!empty($value)) {
8875 } elseif ($type ==
'duration') {
8876 include_once DOL_DOCUMENT_ROOT.
'/core/lib/date.lib.php';
8877 if (!is_null($value) && $value !==
'') {
8880 } elseif ($type ==
'double' || $type ==
'real') {
8881 if (!is_null($value) && $value !==
'') {
8882 $value =
price($value);
8884 } elseif ($type ==
'boolean') {
8886 if (!empty($value)) {
8887 $checked =
' checked ';
8890 $value =
'<input type="checkbox" '.$checked.
' '.($moreparam ? $moreparam :
'').
' readonly disabled>';
8892 $value =
yn($value ? 1 : 0);
8894 } elseif ($type ==
'mail' || $type ==
'email') {
8896 } elseif ($type ==
'url') {
8898 } elseif ($type ==
'phone') {
8899 $value =
dol_print_phone((
string) $value,
'', 0, 0,
'',
' ',
'phone');
8900 } elseif ($type ==
'ip') {
8902 } elseif ($type ==
'stars') {
8903 $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 :
'').
'>';
8904 $value .=
'<div class="star-selection" id="'.$keyprefix.$key.$keysuffix.$this->id.
'_selection">';
8906 while ($i <= $size) {
8907 $value .=
'<span class="star" data-value="'.$i.
'">'.
img_picto(
'',
'fontawesome_star_fas').
'</span>';
8912 $(document).ready(function() { /* commonobject.class.php 2 */
8913 let container = $("#'.$keyprefix.$key.$keysuffix.$this->id.
'_selection");
8914 let selectedStars = parseInt($("#'.$keyprefix.$key.$keysuffix.$this->id.
'").val()) || 0;
8915 container.find(".star").each(function() {
8916 $(this).toggleClass("active", $(this).data("value") <= selectedStars);
8918 container.find(".star").on("mouseover", function() {
8919 let selectedStar = $(this).data("value");
8920 container.find(".star").each(function() {
8921 $(this).toggleClass("active", $(this).data("value") <= selectedStar);
8924 container.on("mouseout", function() {
8925 container.find(".star").each(function() {
8926 $(this).toggleClass("active", $(this).data("value") <= selectedStars);
8929 container.find(".star").off("click").on("click", function() {
8930 selectedStars = $(this).data("value");
8931 if (selectedStars == 1 && $("#'.$keyprefix.$key.$keysuffix.$this->id.
'").val() == 1) {
8934 container.find("#'.$keyprefix.$key.$keysuffix.$this->id.
'").val(selectedStars);
8935 container.find(".star").each(function() {
8936 $(this).toggleClass("active", $(this).data("value") <= selectedStars);
8939 url: "ajax/'.$this->element.
'.php",
8942 objectId: "'.$this->
id.
'",
8943 field: "'.$keyprefix.$key.$keysuffix.
'",
8944 value: selectedStars,
8947 success: function(response) {
8948 var res = JSON.parse(response);
8949 console[res.status === "success" ? "log" : "error"](res.message);
8951 error: function(xhr, status, error) {
8952 console.log("Ajax request failed while updating '.$keyprefix.$key.$keysuffix.
':", error);
8958 } elseif ($type ==
'price') {
8959 if (!is_null($value) && $value !==
'') {
8960 $value =
price($value, 0, $langs, 0, 0, -1,
$conf->currency);
8962 } elseif ($type ==
'select') {
8963 $value = isset($param[
'options'][(
string) $value]) ? $param[
'options'][(
string) $value] :
'';
8964 if (strpos($value,
"|") !==
false) {
8965 $value = $langs->trans(explode(
'|', $value)[0]);
8966 } elseif (! is_numeric($value)) {
8967 $value = $langs->trans($value);
8969 } elseif ($type ==
'sellist') {
8970 $param_list = array_keys($param[
'options']);
8971 $InfoFieldList = explode(
":", $param_list[0]);
8973 $selectkey =
"rowid";
8976 if (count($InfoFieldList) > 2 && !empty($InfoFieldList[2])) {
8977 $selectkey = $InfoFieldList[2];
8978 $keyList = $InfoFieldList[2].
' as rowid';
8981 $fields_label = explode(
'|', $InfoFieldList[1]);
8982 if (is_array($fields_label)) {
8984 $keyList .= implode(
', ', $fields_label);
8987 $filter_categorie =
false;
8988 if (count($InfoFieldList) > 5) {
8989 if ($InfoFieldList[0] ==
'categorie') {
8990 $filter_categorie =
true;
8994 $sql =
"SELECT ".$this->db->sanitize($keyList, 0, 0, 1);
8995 $sql .=
' FROM '.$this->db->prefix().$this->db->sanitize($InfoFieldList[0]);
8996 if (isset($InfoFieldList[4]) && strpos($InfoFieldList[4],
'extra') !==
false) {
8999 if ($selectkey ==
'rowid' && empty($value)) {
9000 $sql .=
" WHERE ".$this->db->sanitize($selectkey).
" = 0";
9001 } elseif ($selectkey ==
'rowid') {
9002 $sql .=
" WHERE ".$this->db->sanitize($selectkey).
" = ".((int) $value);
9004 $sql .=
" WHERE ".$this->db->sanitize($selectkey).
" = '".$this->db->escape((
string) $value).
"'";
9009 dol_syslog(get_class($this).
':showOutputField:$type=sellist', LOG_DEBUG);
9010 $resql = $this->db->query($sql);
9012 if (!$filter_categorie) {
9014 $numrows = $this->db->num_rows($resql);
9016 $obj = $this->db->fetch_object($resql);
9019 $fields_label = explode(
'|', $InfoFieldList[1]);
9021 if (is_array($fields_label) && count($fields_label) > 1) {
9022 foreach ($fields_label as $field_toshow) {
9024 if (!empty($obj->$field_toshow)) {
9025 $translabel = $langs->trans($obj->$field_toshow);
9027 if ($translabel != $field_toshow) {
9028 $value .=
dol_trunc($translabel, 18) .
' ';
9030 $value .= $obj->$field_toshow .
' ';
9035 if (!empty($obj->{$InfoFieldList[1]})) {
9036 $translabel = $langs->trans($obj->{$InfoFieldList[1]});
9038 if ($translabel != $obj->{$InfoFieldList[1]}) {
9041 $value = $obj->{$InfoFieldList[1]};
9046 require_once DOL_DOCUMENT_ROOT .
'/categories/class/categorie.class.php';
9049 $obj = $this->db->fetch_object($resql);
9051 $c->fetch($obj->rowid);
9052 $ways =
$c->print_all_ways();
9053 foreach ($ways as $way) {
9054 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories"' . (
$c->color ?
' style="background: #' .
$c->color .
';"' :
' style="background: #aaa"') .
'>' .
img_object(
'',
'category') .
' ' . $way .
'</li>';
9056 $value =
'<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(
' ', $toprint).
'</ul></div>';
9059 dol_syslog(get_class($this).
'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
9061 } elseif ($type ==
'radio') {
9062 $value = $param[
'options'][(
string) $value];
9063 } elseif ($type ==
'checkbox') {
9064 $value_arr = explode(
',', (
string) $value);
9066 if (is_array($value_arr) && count($value_arr) > 0) {
9068 foreach ($value_arr as $keyval => $valueval) {
9069 if (!empty($valueval)) {
9070 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' . $param[
'options'][$valueval] .
'</li>';
9073 if (!empty($toprint)) {
9074 $value =
'<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">' . implode(
' ', $toprint) .
'</ul></div>';
9077 } elseif ($type ==
'chkbxlst') {
9078 $value_arr = (isset($value) ? explode(
',', $value) : array());
9080 $param_list = array_keys($param[
'options']);
9081 $InfoFieldList = explode(
":", $param_list[0]);
9083 $selectkey =
"rowid";
9086 if (count($InfoFieldList) >= 3) {
9087 $selectkey = $InfoFieldList[2];
9088 $keyList = $InfoFieldList[2].
' as rowid';
9091 $fields_label = explode(
'|', $InfoFieldList[1]);
9092 if (is_array($fields_label)) {
9094 $keyList .= implode(
', ', $fields_label);
9097 $filter_categorie =
false;
9098 if (count($InfoFieldList) > 5) {
9099 if ($InfoFieldList[0] ==
'categorie') {
9100 $filter_categorie =
true;
9104 $sql =
"SELECT ".$this->db->sanitize($keyList, 0, 0, 1);
9105 $sql .=
' FROM '.$this->db->prefix().$this->db->sanitize($InfoFieldList[0]);
9106 if (isset($InfoFieldList[4]) && strpos($InfoFieldList[4],
'extra') !==
false) {
9112 dol_syslog(get_class($this).
':showOutputField:$type=chkbxlst', LOG_DEBUG);
9113 $resql = $this->db->query($sql);
9115 if (!$filter_categorie) {
9118 while ($obj = $this->db->fetch_object($resql)) {
9120 $fields_label = explode(
'|', $InfoFieldList[1]);
9121 if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
9122 if (is_array($fields_label) && count($fields_label) > 1) {
9123 foreach ($fields_label as $field_toshow) {
9125 if (!empty($obj->$field_toshow)) {
9126 $translabel = $langs->trans($obj->$field_toshow);
9128 if ($translabel != $field_toshow) {
9129 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' .
dol_trunc($translabel, 18) .
'</li>';
9131 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' . $obj->$field_toshow .
'</li>';
9136 if (!empty($obj->{$InfoFieldList[1]})) {
9137 $translabel = $langs->trans($obj->{$InfoFieldList[1]});
9139 if ($translabel != $obj->{$InfoFieldList[1]}) {
9140 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' .
dol_trunc($translabel, 18) .
'</li>';
9142 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' . $obj->{$InfoFieldList[1]} .
'</li>';
9148 require_once DOL_DOCUMENT_ROOT .
'/categories/class/categorie.class.php';
9151 while ($obj = $this->db->fetch_object($resql)) {
9152 if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
9154 $c->fetch($obj->rowid);
9155 $ways =
$c->print_all_ways();
9156 foreach ($ways as $way) {
9157 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories"' . (
$c->color ?
' style="background: #' .
$c->color .
';"' :
' style="background: #aaa"') .
'>' .
img_object(
'',
'category') .
' ' . $way .
'</li>';
9162 $value =
'<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(
' ', $toprint).
'</ul></div>';
9164 dol_syslog(get_class($this).
'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
9166 } elseif ($type ==
'link') {
9171 $param_list = array_keys($param[
'options']);
9175 $InfoFieldList = explode(
":", $param_list[0]);
9177 $classname = $InfoFieldList[0];
9178 $classpath = $InfoFieldList[1];
9181 $getnomurlparam = 3;
9182 $getnomurlparam2 =
'';
9184 if (preg_match(
'/#getnomurlparam1=([^#]*)/', $param_list[0], $regtmp)) {
9185 $getnomurlparam = $regtmp[1];
9187 if (preg_match(
'/#getnomurlparam2=([^#]*)/', $param_list[0], $regtmp)) {
9188 $getnomurlparam2 = $regtmp[1];
9191 if (!empty($classpath)) {
9194 if ($classname && !class_exists($classname)) {
9198 if ($element_prop) {
9199 $classname = $element_prop[
'classname'];
9204 if ($classname && class_exists($classname)) {
9205 $object =
new $classname($this->db);
9206 '@phan-var-force CommonObject $object';
9207 if (
$object->element ===
'product') {
9208 '@phan-var-force Product $object';
9209 $result =
$object->fetch((
int) $value,
'',
'',
'', 0, 1, 1);
9211 $result =
$object->fetch($value);
9214 if (
$object->element ===
'product') {
9215 '@phan-var-force Product $object';
9216 $get_name_url_param_arr = array($getnomurlparam, $getnomurlparam2, 0, -1, 0,
'', 0);
9217 if (isset($val[
'get_name_url_params'])) {
9218 $get_name_url_params = explode(
':', $val[
'get_name_url_params']);
9219 if (!empty($get_name_url_params)) {
9220 $param_num_max = count($get_name_url_param_arr) - 1;
9221 foreach ($get_name_url_params as $param_num => $param_value) {
9222 if ($param_num > $param_num_max) {
9225 $get_name_url_param_arr[$param_num] = $param_value;
9233 $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]);
9235 $value =
$object->getNomUrl($getnomurlparam, $getnomurlparam2);
9242 dol_syslog(
'Error bad setup of extrafield', LOG_WARNING);
9243 return 'Error bad setup of extrafield';
9248 } elseif ($type ==
'password') {
9249 $value =
'<span class="opacitymedium">'.$langs->trans(
"Encrypted").
'</span>';
9251 } elseif ($type ==
'array') {
9252 if (is_array($value)) {
9253 $value = implode(
'<br>', $value);
9255 dol_syslog(__METHOD__.
' Expected array from dol_eval, but got '.gettype($value), LOG_ERR);
9256 return 'Error unexpected result from code evaluation';
9259 if (!empty($value) && preg_match(
'/^text/', (
string) $type) && !preg_match(
'/search_/', $keyprefix) && !empty($param[
'options'])) {
9260 $value = str_replace(
',',
"\n", $value);
9268 return is_null($out) ?
'' : $out;
9280 unset($this->validateFieldsErrors[$fieldKey]);
9294 $msg = $langs->trans(
"UnknownError");
9297 $this->error = $this->validateFieldsErrors[$fieldKey] = $msg;
9308 if (!empty($this->validateFieldsErrors[$fieldKey])) {
9309 return $this->validateFieldsErrors[$fieldKey];
9326 if (!class_exists(
'Validate')) {
9327 require_once DOL_DOCUMENT_ROOT .
'/core/class/validate.class.php';
9330 $this->clearFieldError($fieldKey);
9332 if (!array_key_exists($fieldKey, $fields) || !is_array($fields[$fieldKey])) {
9333 $this->setFieldError($fieldKey, $langs->trans(
'FieldNotFoundInObject'));
9337 $val = $fields[$fieldKey];
9340 $param[
'options'] = array();
9341 $type = $val[
'type'];
9344 if (isset($val[
'notnull']) && $val[
'notnull'] === 1) {
9358 if (preg_match(
'/varchar\((\d+)\)/', $type, $reg)) {
9360 $maxSize = (int) $reg[1];
9361 } elseif (preg_match(
'/varchar/', $type)) {
9365 if (!empty($val[
'arrayofkeyval']) && is_array($val[
'arrayofkeyval'])) {
9369 if (!empty($val[
'type']) && preg_match(
'/^integer:(.*):(.*)/i', $val[
'type'], $reg)) {
9373 if (!empty($val[
'arrayofkeyval']) && is_array($val[
'arrayofkeyval'])) {
9374 $param[
'options'] = $val[
'arrayofkeyval'];
9377 if (preg_match(
'/^integer:(.*):(.*)/i', $val[
'type'], $reg)) {
9379 $param[
'options'] = array($reg[1].
':'.$reg[2] => $reg[1].
':'.$reg[2]);
9380 } elseif (preg_match(
'/^sellist:(.*):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
9381 $param[
'options'] = array($reg[1].
':'.$reg[2].
':'.$reg[3].
':'.$reg[4] =>
'N');
9383 } elseif (preg_match(
'/^sellist:(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
9384 $param[
'options'] = array($reg[1].
':'.$reg[2].
':'.$reg[3] =>
'N');
9386 } elseif (preg_match(
'/^sellist:(.*):(.*)/i', $val[
'type'], $reg)) {
9387 $param[
'options'] = array($reg[1].
':'.$reg[2] =>
'N');
9396 $validate =
new Validate($this->db, $langs);
9406 if ($required && !$validate->isNotEmptyString($fieldValue)) {
9407 $this->setFieldError($fieldKey, $validate->error);
9409 } elseif (!$required && !$validate->isNotEmptyString($fieldValue)) {
9415 if (!empty($maxSize) && !$validate->isMaxLength($fieldValue, $maxSize)) {
9416 $this->setFieldError($fieldKey, $validate->error);
9421 if (!empty($minSize) && !$validate->isMinLength($fieldValue, $minSize)) {
9422 $this->setFieldError($fieldKey, $validate->error);
9430 if (in_array($type, array(
'date',
'datetime',
'timestamp'))) {
9431 if (!$validate->isTimestamp($fieldValue)) {
9432 $this->setFieldError($fieldKey, $validate->error);
9437 } elseif ($type ==
'duration') {
9438 if (!$validate->isDuration($fieldValue)) {
9439 $this->setFieldError($fieldKey, $validate->error);
9444 } elseif (in_array($type, array(
'double',
'real',
'price'))) {
9446 if (!$validate->isNumeric($fieldValue)) {
9447 $this->setFieldError($fieldKey, $validate->error);
9452 } elseif ($type ==
'boolean') {
9453 if (!$validate->isBool($fieldValue)) {
9454 $this->setFieldError($fieldKey, $validate->error);
9459 } elseif ($type ==
'mail' || $type ==
'email') {
9460 if (!$validate->isEmail($fieldValue)) {
9461 $this->setFieldError($fieldKey, $validate->error);
9464 } elseif ($type ==
'url') {
9465 if (!$validate->isUrl($fieldValue)) {
9466 $this->setFieldError($fieldKey, $validate->error);
9471 } elseif ($type ==
'phone') {
9472 if (!$validate->isPhone($fieldValue)) {
9473 $this->setFieldError($fieldKey, $validate->error);
9478 } elseif ($type ==
'select' || $type ==
'radio') {
9479 if (!isset($param[
'options'][$fieldValue])) {
9480 $this->error = $langs->trans(
'RequireValidValue');
9485 } elseif ($type ==
'sellist' || $type ==
'chkbxlst') {
9486 $param_list = array_keys($param[
'options']);
9487 $InfoFieldList = explode(
":", $param_list[0]);
9488 $value_arr = explode(
',', $fieldValue);
9490 $selectkey =
"rowid";
9491 if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
9492 $selectkey = $InfoFieldList[2];
9495 if (!$validate->isInDb($value_arr, $InfoFieldList[0], $selectkey)) {
9496 $this->setFieldError($fieldKey, $validate->error);
9501 } elseif ($type ==
'link') {
9502 $param_list = array_keys($param[
'options']);
9503 $InfoFieldList = explode(
":", $param_list[0]);
9504 $classname = $InfoFieldList[0];
9505 $classpath = $InfoFieldList[1];
9506 if (!$validate->isFetchable((
int) $fieldValue, $classname, $classpath)) {
9507 $lastIsFetchableError = $validate->error;
9510 if ($validate->isFetchableElement((
int) $fieldValue, $classname)) {
9514 $this->setFieldError($fieldKey, $lastIsFetchableError);
9538 public function showOptionals($extrafields, $mode =
'view', $params =
null, $keysuffix =
'', $keyprefix =
'', $onetrtd =
'', $display_type =
'card')
9540 global
$db,
$conf, $langs, $action, $form, $hookmanager;
9541 global $objectoffield;
9543 if (!is_object($form)) {
9546 if (!is_object($extrafields)) {
9547 dol_syslog(
'Bad parameter extrafields for showOptionals', LOG_ERR);
9548 return 'Bad parameter extrafields for showOptionals';
9550 if (!is_array($extrafields->attributes[$this->table_element])) {
9551 dol_syslog(
"extrafields->attributes was not loaded with extrafields->fetch_name_optionals_label(table_element);", LOG_WARNING);
9555 $objectoffield = $this;
9559 $parameters = array(
'mode' => $mode,
'params' => $params,
'keysuffix' => $keysuffix,
'keyprefix' => $keyprefix,
'display_type' => $display_type);
9560 $reshook = $hookmanager->executeHooks(
'showOptionals', $parameters, $this, $action);
9561 $hookResPrint = $hookmanager->resPrint;
9563 if (empty($reshook)) {
9564 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) {
9566 $out .=
'<!-- commonobject:showOptionals --> ';
9569 $nbofextrafieldsshown = 0;
9572 $lastseparatorkeyfound =
'';
9573 $extrafields_collapse_num =
'';
9574 $extrafields_collapse_num_old =
'';
9577 foreach ($extrafields->attributes[$this->table_element][
'label'] as $key => $label) {
9581 if (is_array($params) && array_key_exists(
'onlykey', $params) && $key != $params[
'onlykey']) {
9587 if ($enabled && isset($extrafields->attributes[$this->table_element][
'enabled'][$key])) {
9588 $enabled = (int)
dol_eval((
string) $extrafields->attributes[$this->table_element][
'enabled'][$key], 1, 1,
'2');
9590 if (empty($enabled)) {
9595 if (isset($extrafields->attributes[$this->table_element][
'list'][$key])) {
9596 $visibility = (int)
dol_eval((
string) $extrafields->attributes[$this->table_element][
'list'][$key], 1, 1,
'2');
9600 if ($perms && isset($extrafields->attributes[$this->table_element][
'perms'][$key])) {
9601 $perms = (int)
dol_eval((
string) $extrafields->attributes[$this->table_element][
'perms'][$key], 1, 1,
'2');
9604 if (($mode ==
'create') && !in_array(abs($visibility), array(1, 3))) {
9606 } elseif (($mode ==
'edit') && !in_array(abs($visibility), array(1, 3, 4))) {
9608 $ef_name =
'options_' . $key;
9609 $ef_value = $this->array_options[$ef_name] ??
'';
9610 $out .=
'<input type="hidden" name="' . $ef_name .
'" id="' . $ef_name .
'" value="' . $ef_value .
'" />' .
"\n";
9612 } elseif ($mode ==
'view' && empty($visibility)) {
9615 if (empty($perms)) {
9620 if (!empty($extrafields->attributes[$this->table_element][
'langfile'][$key])) {
9621 $langs->load($extrafields->attributes[$this->table_element][
'langfile'][$key]);
9626 if (is_array($params) && count($params) > 0 && $display_type ==
'card') {
9627 if (array_key_exists(
'cols', $params)) {
9628 $colspan = $params[
'cols'];
9629 } elseif (array_key_exists(
'colspan', $params)) {
9631 if (preg_match(
'/colspan="(\d+)"/', $params[
'colspan'], $reg)) {
9634 $colspan = $params[
'colspan'];
9638 $colspan = intval($colspan);
9642 $value = ((!empty($this->array_options) && array_key_exists(
"options_".$key.$keysuffix, $this->array_options)) ? $this->array_options[
"options_".$key.$keysuffix] :
null);
9648 $check =
'alphanohtml';
9649 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'html',
'text'))) {
9650 $check =
'restricthtml';
9652 $getposttemp =
GETPOST($keyprefix.
'options_'.$key.$keysuffix, $check, 3);
9654 if (is_array($getposttemp) || $getposttemp !=
'' || GETPOSTISSET($keyprefix.
'options_'.$key.$keysuffix)) {
9655 if (is_array($getposttemp)) {
9657 $value = implode(
",", $getposttemp);
9659 $value = $getposttemp;
9661 } elseif (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'int'))) {
9662 $value = (!empty($this->array_options[
"options_".$key]) || (isset($this->array_options[
"options_".$key]) && $this->array_options[
"options_".$key] ===
'0')) ? $this->array_options[
"options_".$key] :
'';
9663 } elseif (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'varchar',
'char'))) {
9664 $value = (isset($this->array_options[
"options_".$key]) && $this->array_options[
"options_".$key] !==
'') ? $this->array_options[
"options_".$key] :
'';
9666 $value = (!empty($this->array_options[
"options_".$key]) ? $this->array_options[
"options_".$key] :
'');
9672 $nbofextrafieldsshown++;
9675 if ($extrafields->attributes[$this->table_element][
'type'][$key] ==
'separate') {
9676 $extrafields_collapse_num = $key;
9694 $out .= $extrafields->showSeparator($key, $this, ($colspan ? $colspan + 1 : 2), $display_type, $mode);
9696 $lastseparatorkeyfound = $key;
9698 $collapse_group = $extrafields_collapse_num.(!empty($this->
id) ?
'_'.$this->id :
'');
9700 $class = (!empty($extrafields->attributes[$this->table_element][
'hidden'][$key]) ?
'hideobject ' :
'');
9702 if (is_array($params) && count($params) > 0) {
9703 if (array_key_exists(
'class', $params)) {
9704 $class .= $params[
'class'].
' ';
9706 if (array_key_exists(
'style', $params)) {
9707 $csstyle = $params[
'style'];
9712 $domData =
' data-element="extrafield"';
9713 $domData .=
' data-targetelement="'.$this->element.
'"';
9714 $domData .=
' data-targetid="'.$this->id.
'"';
9716 $html_id = (empty($this->
id) ?
'' :
'extrarow-'.$this->element.
'_'.$key.
'_'.
$this->id);
9717 if ($display_type ==
'card') {
9722 if ($action ==
'selectlines') {
9729 $force_values_on_change_company = (
9730 ($this->element ==
'facture' &&
getDolGlobalInt(
'THIRDPARTY_PROPAGATE_EXTRAFIELDS_TO_INVOICE'))
9731 || ($this->element ==
'commande' &&
getDolGlobalInt(
'THIRDPARTY_PROPAGATE_EXTRAFIELDS_TO_ORDER'))
9732 || ($this->element ==
'order_supplier' &&
getDolGlobalInt(
'THIRDPARTY_PROPAGATE_EXTRAFIELDS_TO_SUPPLIER_ORDER'))
9734 if ($force_values_on_change_company &&
GETPOSTINT(
'changecompany')) {
9735 $value = $this->array_options[
'options_'.$key] ?? $value;
9739 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'date'))) {
9740 $datenotinstring =
null;
9741 if (array_key_exists(
'options_'.$key, $this->array_options)) {
9742 $datenotinstring = $this->array_options[
'options_'.$key];
9743 if (!is_numeric($this->array_options[
'options_'.$key])) {
9744 $datenotinstring = $this->db->jdate($datenotinstring);
9747 $datekey = $keyprefix.
'options_'.$key.$keysuffix;
9750 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'datetime'))) {
9751 $datenotinstring =
null;
9752 if (array_key_exists(
'options_'.$key, $this->array_options)) {
9753 $datenotinstring = $this->array_options[
'options_'.$key];
9754 if (!is_numeric($this->array_options[
'options_'.$key])) {
9755 $datenotinstring = $this->db->jdate($datenotinstring);
9758 $timekey = $keyprefix.
'options_'.$key.$keysuffix;
9759 $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;
9762 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'price',
'double'))) {
9763 if (GETPOSTISSET($keyprefix.
'options_'.$key.$keysuffix) || $value) {
9765 } elseif (isset($this->array_options[
'options_'.$key])) {
9766 $value = $this->array_options[
'options_'.$key];
9771 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'html',
'text',
'varchar',
'select',
'radio',
'int',
'boolean'))) {
9772 if ($action ==
'create' || $mode ==
'create') {
9773 $value = (GETPOSTISSET($keyprefix.
'options_'.$key.$keysuffix) || $value) ? $value : $extrafields->attributes[$this->table_element][
'default'][$key];
9777 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'checkbox'))) {
9778 if ($action ==
'create') {
9779 $value = (GETPOSTISSET($keyprefix.
'options_'.$key.$keysuffix) || $value) ? $value : explode(
',', $extrafields->attributes[$this->table_element][
'default'][$key]);
9784 $labeltoshow = $langs->trans($label);
9785 $helptoshow = $langs->trans($extrafields->attributes[$this->table_element][
'help'][$key]);
9786 if ($display_type ==
'card') {
9787 $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.
' >';
9788 if (
getDolGlobalString(
'MAIN_VIEW_LINE_NUMBER') && ($action ==
'view' || $action ==
'valid' || $action ==
'editline' || $action ==
'confirm_valid' || $action ==
'confirm_cancel')) {
9789 $out .=
'<td></td>';
9791 $out .=
'<td class="'.(empty($params[
'tdclass']) ?
'titlefieldmax45' : $params[
'tdclass']).
' wordbreak';
9792 if ($extrafields->attributes[$this->table_element][
'type'][$key] ==
'text') {
9795 } elseif ($display_type ==
'line') {
9796 $out .=
'<div '.($html_id ?
'id="'.$html_id.
'" ' :
'').$csstyle.
' class="fieldline_options_'.$key.
' '.$class.$this->element.
'_extras_'.$key.
' trextrafields_collapse'.$collapse_group.
'" '.$domData.
' >';
9797 $out .=
'<div style="display: inline-block; padding-right:4px" class="wordbreak';
9802 $tpl_context = isset($params[
"tpl_context"]) ? $params[
"tpl_context"] :
"none";
9803 if ($tpl_context !=
"public") {
9804 if ($mode !=
'view' && !empty($extrafields->attributes[$this->table_element][
'required'][$key])) {
9805 $out .=
' fieldrequired';
9809 if ($tpl_context ==
"public") {
9810 if (!empty($extrafields->attributes[$this->table_element][
'help'][$key])) {
9811 $out .= $form->textwithpicto($labeltoshow, $helptoshow);
9813 $out .= $labeltoshow;
9815 if ($mode !=
'view' && !empty($extrafields->attributes[$this->table_element][
'required'][$key])) {
9816 $out .=
' <span style="color: red">*</span>';
9819 if (!empty($extrafields->attributes[$this->table_element][
'help'][$key])) {
9820 $out .= $form->textwithpicto($labeltoshow, $helptoshow);
9822 $out .= $labeltoshow;
9826 $out .= ($display_type ==
'card' ?
'</td>' :
'</div>');
9829 $html_id = !empty($this->
id) ? $this->element.
'_extras_'.$key.
'_'.$this->id :
'';
9830 if ($display_type ==
'card') {
9832 $out .=
'<td '.($html_id ?
'id="'.$html_id.
'" ' :
'').
' class="valuefieldcreate '.$this->element.
'_extras_'.$key;
9833 $out .=
'" '.($colspan ?
' colspan="'.$colspan.
'"' :
'');
9835 } elseif ($display_type ==
'line') {
9836 $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].
'">';
9841 $out .= $extrafields->showOutputField($key, $value,
'', $this->table_element);
9844 $listoftypestoshowpicto = explode(
',',
getDolGlobalString(
'MAIN_TYPES_TO_SHOW_PICTO',
'email,phone,ip,password'));
9845 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], $listoftypestoshowpicto)) {
9846 $out .=
getPictoForType($extrafields->attributes[$this->table_element][
'type'][$key], ($extrafields->attributes[$this->table_element][
'type'][$key] ==
'text' ?
'tdtop' :
''));
9849 $out .= $extrafields->showInputField($key, $value,
'', $keysuffix,
'',
'', $this, $this->table_element);
9852 $listoftypestoshowpicto = explode(
',',
getDolGlobalString(
'MAIN_TYPES_TO_SHOW_PICTO',
'email,phone,ip,password'));
9853 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], $listoftypestoshowpicto)) {
9854 $out .=
getPictoForType($extrafields->attributes[$this->table_element][
'type'][$key], ($extrafields->attributes[$this->table_element][
'type'][$key] ==
'text' ?
'tdtop' :
''));
9856 $out .= $extrafields->showInputField($key, $value,
'', $keysuffix,
'',
'', $this, $this->table_element);
9860 $out .= ($display_type ==
'card' ?
'</td>' :
'</div>');
9861 $out .= ($display_type ==
'card' ?
'</tr>'.
"\n" :
'</div>');
9867 if (!empty(
$conf->use_javascript_ajax)) {
9868 $out .= $this->getJSListDependancies();
9871 $out .=
'<!-- commonobject:showOptionals end --> '.
"\n";
9873 if (empty($nbofextrafieldsshown)) {
9879 $out .= $hookResPrint;
9891 <script nonce="'.getNonce().
'">
9892 jQuery(document).ready(function() {
9893 function showOptions'.$type.
'(child_list, parent_list, orig_select)
9895 var val = $("select[name=\""+parent_list+"\"]").val();
9896 var parentVal = parent_list + ":" + val;
9897 if(typeof val == "string"){
9899 var options = orig_select.find("option[parent=\""+parentVal+"\"]").clone();
9900 $("select[name=\""+child_list+"\"] option[parent]").remove();
9901 $("select[name=\""+child_list+"\"]").append(options);
9903 var options = orig_select.find("option[parent]").clone();
9904 $("select[name=\""+child_list+"\"] option[parent]").remove();
9905 $("select[name=\""+child_list+"\"]").append(options);
9907 } else if(val > 0) {
9908 var options = orig_select.find("option[parent=\""+parentVal+"\"]").clone();
9909 $("select[name=\""+child_list+"\"] option[parent]").remove();
9910 $("select[name=\""+child_list+"\"]").append(options);
9912 var options = orig_select.find("option[parent]").clone();
9913 $("select[name=\""+child_list+"\"] option[parent]").remove();
9914 $("select[name=\""+child_list+"\"]").append(options);
9917 function setListDependencies'.$type.
'() {
9918 jQuery("select option[parent]").parent().each(function() {
9919 var orig_select = {};
9920 var child_list = $(this).attr("name");
9921 orig_select[child_list] = $(this).clone();
9922 var parent = $(this).find("option[parent]:first").attr("parent");
9923 var infos = parent.split(":");
9924 var parent_list = infos[0];
9926 //Hide daughters lists
9927 if ($("#"+child_list).val() == 0 && $("#"+parent_list).val() == 0){
9928 $("#"+child_list).hide();
9930 } else if ($("#"+parent_list).val() != 0){
9931 $("#"+parent_list).show();
9933 //Show the child list if the parent list value is selected
9934 $("select[name=\""+parent_list+"\"]").click(function() {
9935 if ($(this).val() != 0){
9936 $("#"+child_list).show()
9940 //When we change parent list
9941 $("select[name=\""+parent_list+"\"]").change(function() {
9942 showOptions'.$type.
'(child_list, parent_list, orig_select[child_list]);
9943 //Select the value 0 on child list after a change on the parent list
9944 $("#"+child_list).val(0).trigger("change");
9945 //Hide child lists if the parent value is set to 0
9946 if ($(this).val() == 0){
9947 $("#"+child_list).hide();
9953 setListDependencies'.$type.
'();
9968 $module = empty($this->module) ?
'' : $this->module;
9969 $element = $this->element;
9971 if ($element ==
'facturerec') {
9972 $element =
'facture';
9973 } elseif ($element ==
'invoice_supplier_rec') {
9974 return !$user->hasRight(
'fournisseur',
'facture') ? null : $user->hasRight(
'fournisseur',
'facture');
9975 } elseif ($module && $user->hasRight($module, $element)) {
9977 return $user->hasRight($module, $element);
9980 return $user->rights->$element;
9997 global $hookmanager;
9999 $parameters = array(
10000 'origin_id' => $origin_id,
10001 'dest_id' => $dest_id,
10002 'tables' => $tables,
10004 $reshook = $hookmanager->executeHooks(
'commonReplaceThirdparty', $parameters);
10007 } elseif ($reshook < 0) {
10008 return $ignoreerrors === 1;
10011 foreach ($tables as $table) {
10012 $sql =
'UPDATE '.$dbs->prefix().$table.
' SET fk_soc = '.((int) $dest_id).
' WHERE fk_soc = '.((int) $origin_id);
10014 if (!$dbs->
query($sql)) {
10015 if ($ignoreerrors) {
10040 foreach ($tables as $table) {
10041 $sql =
'UPDATE '.MAIN_DB_PREFIX.$table.
' SET fk_product = '.((int) $dest_id).
' WHERE fk_product = '.((int) $origin_id);
10043 if (!$dbs->
query($sql)) {
10044 if ($ignoreerrors) {
10067 public function defineBuyPrice($unitPrice = 0.0, $discountPercent = 0.0, $fk_product = 0)
10073 if (($unitPrice > 0) && (isset(
$conf->global->ForceBuyingPriceIfNull) &&
getDolGlobalInt(
'ForceBuyingPriceIfNull') > 0)) {
10075 $buyPrice = $unitPrice * (1 - $discountPercent / 100);
10078 if (!empty($fk_product) && $fk_product > 0) {
10081 require_once DOL_DOCUMENT_ROOT.
'/product/class/product.class.php';
10082 $product =
new Product($this->db);
10083 $result = $product->fetch($fk_product);
10084 if ($result <= 0) {
10085 $this->errors[] =
'ErrorProductIdDoesNotExists';
10088 if ($product->cost_price > 0) {
10089 $buyPrice = $product->cost_price;
10090 } elseif ($product->pmp > 0) {
10091 $buyPrice = $product->pmp;
10094 require_once DOL_DOCUMENT_ROOT.
'/product/class/product.class.php';
10095 $product =
new Product($this->db);
10096 $result = $product->fetch($fk_product);
10097 if ($result <= 0) {
10098 $this->errors[] =
'ErrorProductIdDoesNotExists';
10101 if ($product->pmp > 0) {
10102 $buyPrice = $product->pmp;
10106 if (empty($buyPrice) && in_array(
getDolGlobalString(
'MARGIN_TYPE'), array(
'1',
'pmp',
'costprice'))) {
10107 require_once DOL_DOCUMENT_ROOT.
'/fourn/class/fournisseur.product.class.php';
10109 if (($result = $productFournisseur->find_min_price_product_fournisseur($fk_product)) > 0) {
10110 $buyPrice = $productFournisseur->fourn_unitprice;
10111 } elseif ($result < 0) {
10112 $this->errors[] = $productFournisseur->error;
10119 return (
float) $buyPrice;
10132 return array(
'dir' =>
'',
'file' =>
'',
'originalfile' =>
'',
'altfile' =>
'',
'email' =>
'',
'capture' =>
'');
10156 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')
10159 global $user, $langs;
10161 include_once DOL_DOCUMENT_ROOT.
'/core/lib/files.lib.php';
10162 include_once DOL_DOCUMENT_ROOT.
'/core/lib/images.lib.php';
10163 include_once DOL_DOCUMENT_ROOT.
'/core/class/link.class.php';
10165 $sortfield =
'position_name';
10166 $sortorder =
'asc';
10171 $dir .=
get_exdir(0, 0, 0, 0, $this, $modulepart);
10172 $pdir .=
get_exdir(0, 0, 0, 0, $this, $modulepart);
10175 if ($modulepart ==
'product') {
10177 $dir = $sdir.
'/'.
get_exdir($this->
id, 2, 0, 0, $this, $modulepart).$this->id.
"/photos/";
10178 $pdir =
'/'.get_exdir($this->
id, 2, 0, 0, $this, $modulepart).$this->id.
"/photos/";
10181 if ($modulepart ==
'category') {
10182 $dir = $sdir.
'/'.
get_exdir($this->
id, 2, 0, 0, $this, $modulepart).$this->id.
"/photos/";
10183 $pdir =
'/'.get_exdir($this->
id, 2, 0, 0, $this, $modulepart).$this->id.
"/photos/";
10189 $relativedir = preg_replace(
'/^'.preg_quote(DOL_DATA_ROOT,
'/').
'/',
'', $dir);
10190 $relativedir = preg_replace(
'/^[\\/]/',
'', $relativedir);
10191 $relativedir = preg_replace(
'/[\\/]$/',
'', $relativedir);
10194 $dirthumb = $dir.
'thumbs/';
10195 $pdirthumb = $pdir.
'thumbs/';
10197 $return =
'<!-- Photo -->'.
"\n";
10200 $filearray =
dol_dir_list($dir,
"files", 0,
'',
'(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) ==
'desc' ? SORT_DESC : SORT_ASC), 1);
10209 '@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';
10211 $useLinkPathPhoto =
false;
10214 $link =
new Link($this->db);
10216 $link->fetchAll($links,
'product', $this->
id);
10218 if (count($links) > 0) {
10219 $useLinkPathPhoto =
true;
10222 if ($useLinkPathPhoto) {
10224 if ($nbbyrow > 0) {
10225 $return .=
'<table class="valigntop center centpercent" style="border:0; padding:2px; border-spacing:2px; border-collapse: separate;">';
10229 foreach ($links as $link) {
10230 if (!empty($link->url) && preg_match(
'/\.(jpg|jpeg|png|gif|webp)$/i', $link->url)) {
10235 if ($nbbyrow > 0 && ($i % $nbbyrow == 1)) {
10236 $return .=
'<tr class="center valignmiddle">';
10239 if ($nbbyrow > 0) {
10240 $return .=
'<td style="width:'.ceil(100 / $nbbyrow).
'%" class="photo">';
10242 $return .=
'<div class="inline-block">';
10245 $return .=
'<img class="photo photowithmargin'.($addphotorefcss ?
' '.$addphotorefcss :
'').
'"'.($maxHeight ?
' height="'.$maxHeight.
'"' :
'').
' src="'.$url.
'" title="External image">';
10247 if ($nbbyrow > 0) {
10248 $return .=
'</td>';
10249 if ($i % $nbbyrow == 0) {
10250 $return .=
'</tr>';
10253 $return .=
'</div>';
10256 if ($nbmax && $nbphoto >= $nbmax) {
10262 if ($nbbyrow > 0) {
10263 while ($i % $nbbyrow) {
10264 $return .=
'<td style="width:'.ceil(100 / $nbbyrow).
'%"> </td>';
10268 $return .=
'</table>';
10274 if (count($filearray)) {
10275 if ($sortfield && $sortorder) {
10276 $filearray =
dol_sort_array($filearray, $sortfield, $sortorder);
10279 foreach ($filearray as $key => $val) {
10281 $file = $val[
'name'];
10287 $viewfilename = $file;
10289 if ($size == 1 || $size ==
'small') {
10295 $pdirthumb = $pdir;
10296 $photo_vignette = basename($file);
10302 if ($nbbyrow > 0) {
10303 if ($nbphoto == 1) {
10304 $return .=
'<table class="valigntop center centpercent" style="border: 0; padding: 2px; border-spacing: 2px; border-collapse: separate;">';
10307 if ($nbphoto % $nbbyrow == 1) {
10308 $return .=
'<tr class="center valignmiddle" style="border: 1px">';
10310 $return .=
'<td style="width: '.ceil(100 / $nbbyrow).
'%" class="photo">'.
"\n";
10311 } elseif ($nbbyrow < 0) {
10312 $return .=
'<div class="inline-block">'.
"\n";
10315 $relativefile = preg_replace(
'/^\//',
'', $pdir.$photo);
10316 if (empty($nolink)) {
10318 if ($urladvanced) {
10319 $return .=
'<a href="'.$urladvanced.
'">';
10321 $return .=
'<a href="'.DOL_URL_ROOT.
'/viewimage.php?modulepart='.$modulepart.
'&entity='.$this->entity.
'&file='.urlencode($pdir.$photo).
'" class="aphoto" target="_blank" rel="noopener noreferrer">';
10327 $alt = $langs->transnoentitiesnoconv(
'File').
': '.$relativefile;
10328 $alt .=
' - '.$langs->transnoentitiesnoconv(
'Size').
': '.$imgarray[
'width'].
'x'.$imgarray[
'height'];
10329 if ($overwritetitle) {
10330 if (is_numeric($overwritetitle)) {
10333 $alt = $overwritetitle;
10336 if (empty($cache) && !empty($val[
'label'])) {
10339 $cache = $val[
'label'];
10341 if ($usesharelink) {
10342 if (array_key_exists(
'share', $val) && $val[
'share']) {
10343 if (empty($maxHeight) || ($photo_vignette && $imgarray[
'height'] > $maxHeight)) {
10344 $return .=
'<!-- Show original file (thumb not yet available with shared links) -->';
10345 $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).
'">';
10347 $return .=
'<!-- Show original file -->';
10348 $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).
'">';
10351 $return .=
'<!-- Show nophoto file (because file is not shared) -->';
10352 $return .=
'<img class="photo photowithmargin'.($addphotorefcss ?
' '.$addphotorefcss :
'').
'" height="'.$maxHeight.
'" src="'.DOL_URL_ROOT.
'/public/theme/common/nophoto.png" title="'.
dol_escape_htmltag($alt).
'">';
10355 if (empty($maxHeight) || ($photo_vignette && $imgarray[
'height'] > $maxHeight)) {
10356 $return .=
'<!-- Show thumb -->';
10357 $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).
'">';
10359 $return .=
'<!-- Show original file -->';
10360 $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).
'">';
10364 if (empty($nolink)) {
10368 if ($showfilename) {
10369 $return .=
'<br>'.$viewfilename;
10374 if ($photo_vignette && (
image_format_supported($photo) > 0) && ((isset($imgarray[
'width']) && $imgarray[
'width'] > $maxWidth) || (isset($imgarray[
'width']) && $imgarray[
'width'] > $maxHeight))) {
10375 $return .=
'<a href="'.$_SERVER[
"PHP_SELF"].
'?id='.$this->
id.
'&action=addthumb&token='.
newToken().
'&file='.urlencode($pdir.$viewfilename).
'">'.
img_picto($langs->trans(
'GenerateThumb'),
'refresh').
' </a>';
10378 if ($modulepart ==
'product' && ($user->hasRight(
'produit',
'creer') || $user->hasRight(
'service',
'creer'))) {
10380 $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> ';
10383 $return .=
'<a href="'.$_SERVER[
"PHP_SELF"].
'?id='.$this->
id.
'&action=delete&token='.
newToken().
'&file='.urlencode($pdir.$viewfilename).
'">';
10389 if ($nbbyrow > 0) {
10390 $return .=
'</td>';
10391 if (($nbphoto % $nbbyrow) == 0) {
10392 $return .=
'</tr>';
10394 } elseif ($nbbyrow < 0) {
10395 $return .=
'</div>'.
"\n";
10399 if (empty($size)) {
10400 $return .=
'<img class="photo photowithmargin" src="'.DOL_URL_ROOT.
'/viewimage.php?modulepart='.$modulepart.
'&entity='.$this->entity.
'&file='.urlencode($pdir.$photo).
'">';
10402 if ($showfilename) {
10403 $return .=
'<br>'.$viewfilename;
10407 if ($modulepart ==
'product' && ($user->hasRight(
'produit',
'creer') || $user->hasRight(
'service',
'creer'))) {
10409 $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> ';
10412 $return .=
'<a href="'.$_SERVER[
"PHP_SELF"].
'?id='.$this->
id.
'&action=delete&token='.
newToken().
'&file='.urlencode($pdir.$viewfilename).
'">';
10419 if ($nbmax && $nbphoto >= $nbmax) {
10425 if ($size == 1 || $size ==
'small') {
10426 if ($nbbyrow > 0) {
10428 while ($nbphoto % $nbbyrow) {
10429 $return .=
'<td style="width: '.ceil(100 / $nbbyrow).
'%"> </td>';
10434 $return .=
'</table>';
10440 $this->nbphoto = $nbphoto;
10454 if (is_array($info)) {
10455 if (isset($info[
'type']) && $info[
'type'] ==
'array') {
10472 if (isset($info[
'type']) && ($info[
'type'] ==
'date' || $info[
'type'] ==
'datetime' || $info[
'type'] ==
'timestamp')) {
10486 if (is_array($info)) {
10487 if (isset($info[
'type']) && ($info[
'type'] ==
'duration')) {
10505 if (is_array($info)) {
10506 if (isset($info[
'type']) && (preg_match(
'/(^int|int$)/i', $info[
'type']))) {
10524 if (is_array($info)) {
10525 if (isset($info[
'type']) && (preg_match(
'/^(double|real|price)/i', $info[
'type']))) {
10542 if (is_array($info)) {
10543 if (isset($info[
'type']) && $info[
'type'] ==
'text') {
10560 if (is_array($info)) {
10561 if (array_key_exists(
'notnull', $info) && $info[
'notnull'] !=
'1') {
10578 if (is_array($info)) {
10579 if (array_key_exists(
'notnull', $info) && $info[
'notnull'] ==
'-1') {
10596 if (is_array($info)) {
10597 if (array_key_exists(
'index', $info) && $info[
'index'] ==
true) {
10619 $queryarray = array();
10620 foreach ($this->fields as $field => $info) {
10622 if ($this->isDate($info)) {
10623 if (empty($this->{$field})) {
10624 $queryarray[$field] =
null;
10626 $queryarray[$field] = $this->db->idate($this->{$field});
10628 } elseif ($this->isDuration($info)) {
10630 if ((isset($this->{$field}) && $this->{$field} !=
'') || !empty($info[
'notnull'])) {
10631 if (!isset($this->{$field})) {
10632 if (!empty($info[
'default'])) {
10633 $queryarray[$field] = $info[
'default'];
10635 $queryarray[$field] = 0;
10638 $queryarray[$field] = (int) $this->{$field};
10641 $queryarray[$field] =
null;
10643 } elseif ($this->isInt($info) || $this->isFloat($info)) {
10644 if ($field ==
'entity' && is_null($this->{$field})) {
10645 $queryarray[$field] = ((int)
$conf->entity);
10648 if ((isset($this->{$field}) && ((
string) $this->{$field}) !=
'') || !empty($info[
'notnull'])) {
10649 if (!isset($this->{$field})) {
10650 $queryarray[$field] = 0;
10651 } elseif ($this->isInt($info)) {
10652 $queryarray[$field] = (int) $this->{$field};
10653 } elseif ($this->isFloat($info)) {
10654 $queryarray[$field] = (float) $this->{$field};
10657 $queryarray[$field] =
null;
10663 $queryarray[$field] = $this->{$field};
10666 if (array_key_exists(
'type', $info) && $info[
'type'] ==
'timestamp' && empty($queryarray[$field])) {
10667 unset($queryarray[$field]);
10669 if (!empty($info[
'notnull']) && $info[
'notnull'] == -1 && empty($queryarray[$field])) {
10670 $queryarray[$field] =
null;
10674 return $queryarray;
10687 foreach ($this->fields as $field => $info) {
10688 if ($this->isDate($info)) {
10689 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') {
10690 $this->$field =
'';
10692 $this->$field =
$db->jdate($obj->$field);
10694 } elseif ($this->isInt($info)) {
10695 if ($field ==
'rowid') {
10696 $this->
id = (int) $obj->$field;
10698 if ($this->isForcedToNullIfZero($info)) {
10699 if (empty($obj->$field)) {
10700 $this->$field =
null;
10702 $this->$field = (int) $obj->$field;
10705 if (isset($obj->$field) && (!is_null($obj->$field) || (array_key_exists(
'notnull', $info) && $info[
'notnull'] == 1))) {
10706 $this->$field = (int) $obj->$field;
10708 $this->$field =
null;
10712 } elseif ($this->isFloat($info)) {
10713 if ($this->isForcedToNullIfZero($info)) {
10714 if (empty($obj->$field)) {
10715 $this->$field =
null;
10717 $this->$field = (float) $obj->$field;
10720 if (isset($obj->$field) && (!is_null($obj->$field) || (array_key_exists(
'notnull', $info) && $info[
'notnull'] == 1))) {
10721 $this->$field = (float) $obj->$field;
10723 $this->$field =
null;
10727 $this->$field = isset($obj->$field) ? $obj->$field :
null;
10732 if (!isset($this->fields[
'ref']) && isset($this->
id)) {
10743 foreach ($this->fields as $field => $arr) {
10744 $this->$field =
null;
10757 $keys = array_keys($this->fields);
10758 if (!empty($alias)) {
10759 $keys_with_alias = array();
10760 foreach ($keys as $fieldname) {
10761 if (!empty($excludefields)) {
10762 if (in_array($fieldname, $excludefields)) {
10766 $keys_with_alias[] = $this->db->sanitize($alias .
'.' . $fieldname);
10768 return implode(
', ', $keys_with_alias);
10770 return implode(
', ', $keys);
10781 protected function quote($value, $fieldsentry)
10783 if (is_null($value)) {
10785 } elseif (preg_match(
'/^(int|double|real|price)/i', $fieldsentry[
'type'])) {
10787 } elseif (preg_match(
'/int$/i', $fieldsentry[
'type'])) {
10788 return (
int) $value;
10789 } elseif ($fieldsentry[
'type'] ==
'boolean') {
10796 return "'".$this->db->escape($value).
"'";
10813 dol_syslog(get_class($this).
"::createCommon create", LOG_DEBUG);
10819 $fieldvalues = $this->setSaveQuery();
10823 if (array_key_exists(
'date_creation', $fieldvalues) && empty($fieldvalues[
'date_creation'])) {
10824 $fieldvalues[
'date_creation'] = $this->db->idate($now);
10825 $this->date_creation = $this->db->idate($now);
10828 if (array_key_exists(
'fk_user_creat', $fieldvalues) && !($fieldvalues[
'fk_user_creat'] > 0)) {
10829 $fieldvalues[
'fk_user_creat'] = $user->id;
10830 $this->fk_user_creat = $user->id;
10832 if (array_key_exists(
'user_creation_id', $fieldvalues) && !($fieldvalues[
'user_creation_id'] > 0)) {
10833 $fieldvalues[
'user_creation_id'] = $user->id;
10834 $this->user_creation_id = $user->id;
10836 if (array_key_exists(
'pass_crypted', $fieldvalues) && property_exists($this,
'pass')) {
10838 $tmparray =
dol_hash($this->pass,
'0', 0, 1);
10839 $fieldvalues[
'pass_crypted'] = $tmparray[
'pass_encrypted'];
10840 if (array_key_exists(
'pass_encoding', $fieldvalues) && property_exists($this,
'pass_encoding')) {
10841 $fieldvalues[
'pass_encoding'] = $tmparray[
'pass_encoding'];
10844 if (array_key_exists(
'ref', $fieldvalues)) {
10847 if (
getDolGlobalString(
'MAIN_DISABLE_AUTO_UPDATE_OF_TMS_FIELDS') && array_key_exists(
'tms', $fieldvalues)) {
10848 $fieldvalues[
'tms'] = $this->db->idate($now);
10851 unset($fieldvalues[
'rowid']);
10855 foreach ($fieldvalues as $k => $v) {
10857 $value = $this->fields[$k];
10859 $values[$k] = $this->quote($v, $value);
10863 foreach ($keys as $key) {
10864 if (!isset($this->fields[$key])) {
10867 $key_fields = $this->fields[$key];
10870 if (preg_match(
'/^integer:/i', $key_fields[
'type']) && $values[$key] ==
'-1') {
10871 $values[$key] =
'';
10873 if (!empty($key_fields[
'foreignkey']) && $values[$key] ==
'-1') {
10874 $values[$key] =
'';
10877 if (isset($key_fields[
'notnull']) && $key_fields[
'notnull'] == 1 && (!isset($values[$key]) || $values[$key] ===
'NULL') && (!isset($key_fields[
'default']) || is_null($key_fields[
'default']))) {
10880 if (empty($langs)) {
10881 require_once DOL_DOCUMENT_ROOT.
'/core/class/translate.class.php';
10883 $langs->setDefaultLang();
10884 $langs->load(
"errors");
10886 dol_syslog(
"Mandatory field '".$key.
"' is empty and required into ->fields definition of class");
10887 $this->errors[] = $langs->trans(
"ErrorFieldRequired", isset($key_fields[
'label']) ? $key_fields[
'label'] : $key);
10891 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'])) {
10892 $values[$key] = $this->quote($key_fields[
'default'], $key_fields);
10896 if (isset($key_fields[
'type']) && preg_match(
'/^integer:/i', $key_fields[
'type']) && empty($values[$key])) {
10897 if (isset($key_fields[
'default'])) {
10898 $values[$key] = ((int) $key_fields[
'default']);
10900 $values[$key] =
'null';
10903 if (!empty($key_fields[
'foreignkey']) && empty($values[$key])) {
10904 $values[$key] =
'null';
10912 $this->db->begin();
10915 $sql =
"INSERT INTO ".$this->db->prefix().$this->table_element;
10916 $sql .=
" (".implode(
", ", $keys).
')';
10917 $sql .=
" VALUES (".implode(
", ", $values).
")";
10919 $res = $this->db->query($sql);
10922 if ($this->db->lasterrno() ==
'DB_ERROR_RECORD_ALREADY_EXISTS') {
10923 $this->errors[] =
"ErrorRefAlreadyExists";
10925 $this->errors[] = $this->db->lasterror();
10931 $this->
id = $this->db->last_insert_id($this->db->prefix().$this->table_element);
10937 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)') {
10938 $sql =
"UPDATE ".$this->db->prefix().$this->table_element.
" SET ref = '(PROV".((int) $this->
id).
")' WHERE (ref = '(PROV)' OR ref = '') AND rowid = ".((int) $this->
id);
10939 $resqlupdate = $this->db->query($sql);
10941 if ($resqlupdate ===
false) {
10943 $this->errors[] = $this->db->lasterror();
10945 $this->
ref =
'(PROV'.$this->id.
')';
10952 $result = $this->insertExtraFields();
10959 if (!empty($this->table_element_line) && !empty($this->fk_element) && !empty($this->lines)) {
10960 foreach ($this->lines as $line) {
10961 $keyforparent = $this->fk_element;
10966 if (!is_object($line)) {
10967 $line = (object) $line;
10971 if (method_exists($line,
'insert')) {
10972 $result = $line->insert($user, 1);
10973 } elseif (method_exists($line,
'create')) {
10974 $result = $line->create($user, 1);
10977 $this->error = $line->error;
10978 $this->db->rollback();
10985 if (!$error && !$notrigger) {
10987 $result = $this->call_trigger(strtoupper(get_class($this)).
'_CREATE', $user);
10996 $this->db->rollback();
10999 $this->db->commit();
11016 if (empty(
$id) && empty($ref) && empty($morewhere)) {
11020 $fieldlist = $this->getFieldList(
't');
11021 if (empty($fieldlist)) {
11025 $sql =
"SELECT ".$this->db->sanitize($fieldlist, 0, 0, 1);
11026 $sql .=
" FROM ".$this->db->prefix().$this->table_element.
' as t';
11029 $sql .=
' WHERE t.rowid = '.((int)
$id);
11030 } elseif (!empty($ref)) {
11031 $sql .=
" WHERE t.ref = '".$this->db->escape($ref).
"'";
11033 $sql .=
' WHERE 1 = 1';
11035 if (empty(
$id) && isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
11036 $sql .=
' AND t.entity IN ('.getEntity($this->element).
')';
11039 $sql .= $morewhere;
11041 $sql .=
' LIMIT 1';
11043 $res = $this->db->query($sql);
11045 $obj = $this->db->fetch_object($res);
11047 $this->setVarsFromFetchObj($obj);
11051 if (empty($noextrafields)) {
11052 $result = $this->fetch_optionals();
11054 $this->error = $this->db->lasterror();
11055 $this->errors[] = $this->error;
11065 $this->error = $this->db->lasterror();
11066 $this->errors[] = $this->error;
11080 $objectlineclassname = get_class($this).
'Line';
11081 if (!class_exists($objectlineclassname)) {
11082 $this->error =
'Error, class '.$objectlineclassname.
' not found during call of fetchLinesCommon';
11086 $objectline =
new $objectlineclassname($this->db);
11087 '@phan-var-force CommonObjectLine $objectline';
11089 $sql =
"SELECT ".$objectline->getFieldList(
'l');
11090 $sql .=
" FROM ".$this->db->prefix().$objectline->table_element.
" as l";
11091 $sql .=
" WHERE l.fk_".$this->db->escape($this->element).
" = ".((int) $this->
id);
11093 $sql .= $morewhere;
11095 if (isset($objectline->fields[
'position'])) {
11096 $sql .= $this->db->order(
'position',
'ASC');
11099 $resql = $this->db->query($sql);
11101 $num_rows = $this->db->num_rows($resql);
11103 $this->lines = array();
11104 while ($i < $num_rows) {
11105 $obj = $this->db->fetch_object($resql);
11107 $newline =
new $objectlineclassname($this->db);
11108 '@phan-var-force CommonObjectLine $newline';
11109 $newline->setVarsFromFetchObj($obj);
11112 if (empty($noextrafields)) {
11113 $newline->fetch_optionals();
11116 $this->lines[] = $newline;
11123 $this->error = $this->db->lasterror();
11124 $this->errors[] = $this->error;
11138 dol_syslog(get_class($this).
"::updateCommon update", LOG_DEBUG);
11150 $fieldvalues = $this->setSaveQuery();
11154 if (array_key_exists(
'date_modification', $fieldvalues)) {
11155 $fieldvalues[
'date_modification'] = $this->db->idate($now);
11157 if (
getDolGlobalString(
'MAIN_DISABLE_AUTO_UPDATE_OF_TMS_FIELDS') && array_key_exists(
'tms', $fieldvalues)) {
11158 $fieldvalues[
'tms'] = $this->db->idate($now);
11160 if (array_key_exists(
'fk_user_modif', $fieldvalues)) {
11161 $fieldvalues[
'fk_user_modif'] = $user->id;
11163 if (array_key_exists(
'user_modification_id', $fieldvalues)) {
11164 $fieldvalues[
'user_modification_id'] = $user->id;
11167 if (array_key_exists(
'pass_crypted', $fieldvalues) && property_exists($this,
'pass') && !empty($this->pass)) {
11169 $tmparray =
dol_hash($this->pass,
'0', 0, 1);
11170 $fieldvalues[
'pass_crypted'] = $tmparray[
'pass_encrypted'];
11171 if (array_key_exists(
'pass_encoding', $fieldvalues) && property_exists($this,
'pass_encoding')) {
11172 $fieldvalues[
'pass_encoding'] = $tmparray[
'pass_encoding'];
11175 if (array_key_exists(
'ref', $fieldvalues)) {
11179 unset($fieldvalues[
'rowid']);
11185 foreach ($fieldvalues as $k => $v) {
11187 $value = $this->fields[$k];
11189 $values[$k] = $this->quote($v, $value);
11190 if (($value[
"type"] ==
"text") && !empty($value[
'arrayofkeyval']) && is_array($value[
'arrayofkeyval'])) {
11192 $v = preg_replace(
'/\s/',
',', $v);
11193 $v = preg_replace(
'/,+/',
',', $v);
11196 $tmp[] = $k.
'='.$this->quote($v, $this->fields[$k]);
11200 foreach ($keys as $key) {
11201 if (preg_match(
'/^integer:/i', $this->fields[$key][
'type']) && $values[$key] ==
'-1') {
11202 $values[$key] =
'';
11204 if (!empty($this->fields[$key][
'foreignkey']) && $values[$key] ==
'-1') {
11205 $values[$key] =
'';
11217 $sql =
'UPDATE '.$this->db->prefix().$this->table_element.
' SET '.implode(
', ', $tmp).
' WHERE rowid='.((int) $this->
id);
11219 $this->db->begin();
11222 $res = $this->db->query($sql);
11225 $this->errors[] = $this->db->lasterror();
11231 $result = $this->insertExtraFields();
11238 if (!$error && !$notrigger) {
11240 $result = $this->call_trigger(strtoupper(get_class($this)).
'_MODIFY', $user);
11249 $this->db->rollback();
11252 $this->db->commit();
11267 dol_syslog(get_class($this).
"::deleteCommon delete", LOG_DEBUG);
11271 $this->db->begin();
11273 if ($forcechilddeletion) {
11274 foreach ($this->childtables as $table) {
11275 $sql =
"DELETE FROM ".$this->db->prefix().$this->db->sanitize($table).
" WHERE ".$this->db->sanitize($this->fk_element).
" = ".((int) $this->
id);
11276 $resql = $this->db->query($sql);
11278 $this->error = $this->db->lasterror();
11279 $this->errors[] = $this->error;
11280 $this->db->rollback();
11284 } elseif (!empty($this->childtables)) {
11285 $objectisused = $this->isObjectUsed($this->
id);
11286 if (!empty($objectisused)) {
11287 dol_syslog(get_class($this).
"::deleteCommon Can't delete record as it has some child", LOG_WARNING);
11288 $this->error =
'ErrorRecordHasChildren';
11289 $this->errors[] = $this->error;
11290 $this->db->rollback();
11296 if (is_array($this->childtablesoncascade) && !empty($this->childtablesoncascade)) {
11297 foreach ($this->childtablesoncascade as $tabletodelete) {
11298 $deleteFromObject = explode(
':', $tabletodelete, 4);
11299 if (count($deleteFromObject) >= 2) {
11300 $className = str_replace(
'@',
'', $deleteFromObject[0]);
11301 $filePath = $deleteFromObject[1];
11302 $columnName = $deleteFromObject[2];
11304 if (!empty($deleteFromObject[3])) {
11305 $filter = $deleteFromObject[3];
11309 $childObject =
new $className($this->db);
11310 if (method_exists($childObject,
'deleteByParentField')) {
11311 '@phan-var-force CommonObject $childObject';
11312 $result = $childObject->deleteByParentField($this->
id, $columnName, $filter);
11315 $this->errors[] = $childObject->error;
11320 $this->errors[] =
"You defined a cascade delete on an object $className/$this->id but there is no method deleteByParentField for it";
11325 $this->errors[] =
'Cannot include child class file '.$filePath;
11330 $sql =
"DELETE FROM ".$this->db->prefix().$this->db->sanitize($tabletodelete).
" WHERE ".$this->db->sanitize($this->fk_element).
" = ".((int) $this->
id);
11332 $resql = $this->db->query($sql);
11335 $this->error = $this->db->lasterror();
11336 $this->errors[] = $this->error;
11346 $result = $this->call_trigger(strtoupper(get_class($this)).
'_DELETE', $user);
11356 $res = $this->deleteEcmFiles(1);
11365 require_once DOL_DOCUMENT_ROOT .
'/core/lib/files.lib.php';
11368 $this->errors[] =
'ErrorFailToDeleteDir';
11374 $res = $this->deleteObjectLinked();
11379 if (!$error && !empty($this->isextrafieldmanaged)) {
11380 $result = $this->deleteExtraFields();
11387 $sql =
'DELETE FROM '.$this->db->prefix().$this->table_element.
' WHERE rowid='.((int) $this->
id);
11389 $resql = $this->db->query($sql);
11392 $this->errors[] = $this->db->lasterror();
11398 $this->db->rollback();
11401 $this->db->commit();
11426 if (!empty($parentId) && !empty($parentField)) {
11427 if (empty($this->table_element)) {
11428 $this->error =
'Property table_element for object is not defined';
11429 $this->errors[] = $this->error;
11433 if (!method_exists($this,
'fetch')) {
11434 $this->error =
'Method fetch for object is not defined';
11435 $this->errors[] = $this->error;
11439 if (!method_exists($this,
'delete')) {
11440 $this->error =
'Method delete for object is not defined';
11441 $this->errors[] = $this->error;
11446 $this->db->begin();
11448 $sql =
"SELECT rowid FROM ".$this->db->prefix().$this->table_element;
11449 $sql .=
" WHERE ".$this->db->sanitize($parentField).
" = ".(int) $parentId;
11452 $errormessage =
'';
11454 if ($errormessage) {
11455 $this->errors[] = $errormessage;
11456 dol_syslog(__METHOD__.
' '.implode(
',', $this->errors), LOG_ERR);
11460 $resql = $this->db->query($sql);
11462 $this->errors[] = $this->db->lasterror();
11465 while ($obj = $this->db->fetch_object($resql)) {
11466 $result = $this->fetch($obj->rowid);
11469 $this->errors[] = $this->error;
11471 $result = $this->
delete($user);
11474 $this->errors[] = $this->error;
11482 if (empty($error)) {
11483 $this->db->commit();
11486 $this->error = implode(
', ', $this->errors);
11487 $this->db->rollback();
11488 return $error * -1;
11507 $tmpforobjectclass = get_class($this);
11508 $tmpforobjectlineclass = ucfirst($tmpforobjectclass).
'Line';
11510 $this->db->begin();
11513 $result = $this->call_trigger(
'LINE'.strtoupper($tmpforobjectclass).
'_DELETE', $user);
11519 if (empty($error)) {
11520 $sql =
"DELETE FROM ".$this->db->prefix().$this->table_element_line;
11521 $sql .=
" WHERE rowid = ".((int) $idline);
11523 $resql = $this->db->query($sql);
11525 $this->error =
"Error ".$this->db->lasterror();
11530 if (empty($error)) {
11532 $tmpobjectline =
new $tmpforobjectlineclass($this->db);
11533 '@phan-var-force CommonObjectLine $tmpobjectline';
11534 if (!isset($tmpobjectline->isextrafieldmanaged) || !empty($tmpobjectline->isextrafieldmanaged)) {
11535 $tmpobjectline->id = $idline;
11536 $result = $tmpobjectline->deleteExtraFields();
11539 $this->error =
"Error ".get_class($this).
"::deleteLineCommon deleteExtraFields error -4 ".$tmpobjectline->error;
11544 if (empty($error)) {
11545 $this->db->commit();
11548 dol_syslog(get_class($this).
"::deleteLineCommon ERROR:".$this->error, LOG_ERR);
11549 $this->db->rollback();
11569 $this->db->begin();
11571 $statusfield =
'status';
11572 if (in_array($this->element, array(
'don',
'donation',
'shipping',
'project_task'))) {
11573 $statusfield =
'fk_statut';
11576 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
11577 $sql .=
" SET ".$this->db->sanitize($statusfield).
" = ".((int) $status);
11578 $sql .=
" WHERE rowid = ".((int) $this->
id);
11580 if ($this->db->query($sql)) {
11582 $this->oldcopy = clone $this;
11585 if (!$error && !$notrigger) {
11587 $result = $this->call_trigger($triggercode, $user);
11594 $this->
status = $status;
11595 if (property_exists($this,
'statut')) {
11596 $this->statut = $status;
11598 $this->db->commit();
11601 $this->db->rollback();
11605 $this->error = $this->db->error();
11606 $this->db->rollback();
11622 $this->specimen = 1;
11624 'label' =>
'This is label',
11625 'ref' =>
'ABCD1234',
11626 'description' =>
'This is a description',
11628 'note_public' =>
'Public note',
11629 'note_private' =>
'Private note',
11630 'date_creation' => (
dol_now() - 3600 * 48),
11631 'date_modification' => (
dol_now() - 3600 * 24),
11632 'fk_user_creat' => $user->id,
11633 'fk_user_modif' => $user->id,
11636 foreach ($fields as $key => $value) {
11637 if (array_key_exists($key, $this->fields)) {
11638 $this->{$key} = $value;
11643 if (property_exists($this,
'fields')) {
11644 foreach ($this->fields as $key => $value) {
11646 if (array_key_exists($key, $fields)) {
11650 if (!empty($value[
'default'])) {
11651 $this->$key = $value[
'default'];
11669 require_once DOL_DOCUMENT_ROOT.
'/core/class/comment.class.php';
11671 $comment =
new Comment($this->db);
11672 $result = $comment->fetchAllFor($this->element, $this->
id);
11674 $this->setErrorsFromObject($comment);
11677 $this->comments = $comment->comments;
11679 return count($this->comments);
11689 return count($this->comments);
11700 if (!is_array($parameters)) {
11703 foreach ($parameters as $parameter) {
11704 if (isset($this->$parameter)) {
11705 $this->$parameter = trim($this->$parameter);
11724 require_once DOL_DOCUMENT_ROOT.
'/categories/class/categorie.class.php';
11728 $existing =
$c->containing($this->
id, $type_categ,
'id');
11748 if (!is_array($categories)) {
11749 $categories = array($categories);
11752 dol_syslog(get_class($this).
"::setCategoriesCommon Object Id:".$this->
id.
' type_categ:'.$type_categ.
' nb tag add:'.count($categories), LOG_DEBUG);
11754 require_once DOL_DOCUMENT_ROOT.
'/categories/class/categorie.class.php';
11756 if (empty($type_categ)) {
11757 dol_syslog(__METHOD__.
': Type '.$type_categ.
'is an unknown category type. Done nothing.', LOG_ERR);
11763 $existing =
$c->containing($this->
id, $type_categ,
'id');
11766 if (!is_array($existing)) {
11767 $existing = array();
11769 if ($remove_existing) {
11771 $to_del = array_diff($existing, $categories);
11772 $to_add = array_diff($categories, $existing);
11775 $to_add = array_diff($categories, $existing);
11782 foreach ($to_del as $del) {
11783 if (
$c->fetch($del) > 0) {
11784 $result =
$c->del_type($this, $type_categ);
11787 $this->error =
$c->error;
11788 $this->errors =
$c->errors;
11795 foreach ($to_add as $add) {
11796 if (
$c->fetch($add) > 0) {
11797 $result =
$c->add_type($this, $type_categ);
11800 $this->error =
$c->error;
11801 $this->errors =
$c->errors;
11809 return $error ? (-1 * $error) : $ok;
11822 $this->db->begin();
11824 if (empty($type)) {
11825 $type = $this->table_element;
11828 require_once DOL_DOCUMENT_ROOT.
'/categories/class/categorie.class.php';
11829 $categorystatic =
new Categorie($this->db);
11831 $tablename = $this->db->prefix().
"categorie_".(empty($categorystatic->MAP_CAT_TABLE[$type]) ? $type : $categorystatic->MAP_CAT_TABLE[$type]);
11832 $fkname =
'fk_' . (empty($categorystatic->MAP_CAT_FK[$type]) ? $type : $categorystatic->MAP_CAT_FK[$type]);
11834 $sql =
"INSERT INTO ".$this->db->sanitize($tablename).
" (fk_categorie, ".$this->db->sanitize($fkname).
")";
11835 $sql .=
" SELECT fk_categorie, ".((int) $toId).
" FROM ".$this->db->sanitize($tablename);
11836 $sql .=
" WHERE ".$this->db->sanitize($fkname).
" = ".((int) $fromId);
11838 if (!$this->db->query($sql)) {
11839 $this->error = $this->db->lasterror();
11840 $this->db->rollback();
11844 $this->db->commit();
11858 $this->db->begin();
11862 switch ($this->element) {
11864 $element =
'propale';
11867 $element =
'produit';
11869 case 'order_supplier':
11870 $element =
'fournisseur/commande';
11872 case 'invoice_supplier':
11875 $element =
'fournisseur/facture/'.get_exdir($this->
id, 2, 0, 1, $this,
'invoice_supplier');
11878 $element =
'expedition/sending';
11881 case 'project_task':
11882 require_once DOL_DOCUMENT_ROOT.
'/projet/class/task.class.php';
11884 $project_result = $this->fetchProject();
11885 if ($project_result >= 0) {
11886 $element =
'projet/'.dol_sanitizeFileName($this->project->ref).
'/';
11890 $element =
'contract';
11893 $element = $this->element;
11895 '@phan-var-force string $element';
11898 $sql =
"DELETE FROM ".$this->db->prefix().
"ecm_files_extrafields WHERE fk_object IN (";
11899 $sql .=
" SELECT rowid FROM ".$this->db->prefix().
"ecm_files WHERE filename LIKE '".$this->db->escape($this->
ref).
"%'";
11900 $sql .=
" AND filepath = '".$this->db->escape($element).
"/".$this->db->escape($this->
ref).
"' AND entity = ".((int)
$conf->entity);
11903 if (!$this->db->query($sql)) {
11904 $this->error = $this->db->lasterror();
11905 $this->db->rollback();
11910 $sql =
"DELETE FROM ".$this->db->prefix().
"ecm_files";
11911 $sql .=
" WHERE filename LIKE '".$this->db->escape($this->
ref).
"%'";
11912 $sql .=
" AND filepath = '".$this->db->escape($element).
"/".$this->db->escape($this->
ref).
"' AND entity = ".((int)
$conf->entity);
11914 if (!$this->db->query($sql)) {
11915 $this->error = $this->db->lasterror();
11916 $this->db->rollback();
11923 $sql =
'DELETE FROM '.$this->db->prefix().
"ecm_files_extrafields";
11924 $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).
")";
11925 $resql = $this->db->query($sql);
11927 $this->error = $this->db->lasterror();
11928 $this->db->rollback();
11932 $sql =
'DELETE FROM '.$this->db->prefix().
"ecm_files";
11933 $sql .=
" WHERE src_object_type = '".$this->db->escape($this->table_element.(empty($this->module) ?
"" :
"@".$this->module)).
"' AND src_object_id = ".((int) $this->
id);
11934 $resql = $this->db->query($sql);
11936 $this->error = $this->db->lasterror();
11937 $this->db->rollback();
11942 $this->db->commit();
11959 include_once DOL_DOCUMENT_ROOT.
'/product/class/product.class.php';
11962 $tmpproduct =
new Product($this->db);
11963 foreach ($this->lines as $line) {
11964 if ($line->fk_product > 0) {
11965 $tmpproduct->fetch($line->fk_product);
11966 $statustotest = ($status ==
'onsale' ?
'status' :
'status_buy');
11967 if (!$tmpproduct->$statustotest) {
11968 $langs->load(
'products');
11969 $statuskey4lang = ($status ==
'onsale' ?
'ProductStatusNotOnSell' :
'ProductStatusNotOnBuy');
11971 $this->errors[] = $langs->trans(
'ProductRef').
' '.$tmpproduct->ref.
' '.$langs->trans($statuskey4lang);
11977 $this->error =
'ErrorOneLineContainsADisactivatedProduct';
11993 $this->error = $message;
11994 $this->errors[] = $message;
12006 global $dolibarr_main_document_root;
12008 $this->setErrorWithoutLog($message);
12009 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
12010 $file = str_replace($dolibarr_main_document_root,
'', $trace[0][
'file'] ??
'file unknown');
12011 $line = $trace[0][
'line'] ??
'line unknown';
12012 $syslogMessage = sprintf(
'%s:%s %s', $file, $line, $message);
$id
Support class for third parties, contacts, members, users or resources.
if(! $sortfield) if(! $sortorder) $object
global $dolibarr_main_url_root
ajax_combobox($htmlname, $events=array(), $minLengthToAutocomplete=0, $forcefocus=0, $widthTypeOfAutocomplete='resolve', $idforemptyvalue='-1', $morecss='')
Convert a html select field into an ajax combobox.
Class to manage members of a foundation.
Class to manage categories.
Parent class of all other business classes (invoices, contracts, proposals, orders,...
fetch_optionals($rowid=null, $optionsArray=null)
Function to get extra fields of an object into $this->array_options This method is in most cases call...
getCategoriesCommon($type_categ)
Sets object to given categories.
indexFile($destfull, $update_main_doc_field)
Index a file into the ECM database.
getFormatedSupplierRef($objref)
Return supplier ref for screen output.
line_order($renum=false, $rowidorder='ASC', $fk_parent_line=true)
Save a new position (field rang) for details lines.
deleteLineCommon(User $user, $idline, $notrigger=0)
Delete a line of object in database.
isEmpty()
isEmpty We consider CommonObject isEmpty if this->id is empty
clearFieldError($fieldKey)
clear validation message result for a field
static getCountOfItemsLinkedByObjectID($fk_object_where, $field_where, $table_element)
Count items linked to an object id in association table.
deleteEcmFiles($mode=0)
Delete related files of object in database.
getLastMainDocLink($modulepart, $initsharekey=0, $relativelink=0)
Return the link of last main doc file for direct public download.
liste_type_contact($source='internal', $order='position', $option=0, $activeonly=0, $code='')
Return array with list of possible values for type of contacts.
getTooltipContent($params)
getTooltipContent
update_price($exclspec=0, $roundingadjust='auto', $nodatabaseupdate=0, $seller=null)
Update total_ht, total_ttc, total_vat, total_localtax1, total_localtax2 for an object (sum of lines).
swapContactStatus($rowid)
Update status of a contact linked to object.
getFieldError($fieldKey)
get field error message
setStatut($status, $elementId=null, $elementType='', $trigkey='', $fieldstatus='')
Set status of an object.
add_object_linked($origin=null, $origin_id=null, $f_user=null, $notrigger=0)
Add an object link into llx_element_element.
updateObjectLinked($sourceid=null, $sourcetype='', $targetid=null, $targettype='', $f_user=null, $notrigger=0)
Update object linked of a current object.
setErrorWithoutLog($message)
Set the error message for the object without logging it.
defineBuyPrice($unitPrice=0.0, $discountPercent=0.0, $fk_product=0)
Get buy price to use for margin calculation.
commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams=null)
Common function for all objects extending CommonObject for generating documents.
liste_contact($statusoflink=-1, $source='external', $list=0, $code='', $status=-1, $arrayoftcids=array())
Get array of all contacts for an object.
fetchObjectFrom($table, $field, $key, $element=null)
Load object from specific field.
fetchProject()
Load the project with id $this->fk_project into this->project.
fetch_thirdparty($force_thirdparty_id=0)
Load the third party of object, from id $this->socid or $this->fk_soc, into this->thirdparty.
static deleteAllItemsLinkedByObjectID($fk_object_where, $field_where, $table_element)
Function used to remove all items linked to an object id in association table.
setFieldError($fieldKey, $msg='')
set validation error message a field
validateField($fields, $fieldKey, $fieldValue)
Return validation test result for a field.
getDataToShowPhoto($modulepart, $imagesize)
Function used to get the logos or photos of an object.
setMulticurrencyCode($code)
Change the multicurrency code.
emtpyObjectVars()
Sets all object fields to null.
fetch_projet()
Load the project with id $this->fk_project into this->project.
getIdContact($source, $code, $status=0)
Return id of contacts for a source and a contact code.
setExtraField($key, $value)
Convenience method for setting the value of an extrafield without actually updating it in the databas...
setDocModel($user, $modelpdf)
Set last model used by doc generator.
deleteObjectLinked($sourceid=null, $sourcetype='', $targetid=null, $targettype='', $rowid=0, $f_user=null, $notrigger=0)
Delete all links between an object $this.
getExtraField($key)
Convenience method for retrieving the value of an extrafield without actually fetching it from the da...
updateExtraField($key, $trigger=null, $userused=null)
Update 1 extra field value for the current object.
setPaymentTerms($id, $deposit_percent=null)
Change the payments terms.
isFloat($info)
Function test if type is float.
setBankAccount($fk_account, $notrigger=0, $userused=null)
Change the bank account.
setExtraParameters()
Set extra parameters.
delete_resource($rowid, $element='', $notrigger=0)
Delete a link to resource line.
setErrorsFromObject($object)
setErrorsFromObject
setShippingMethod($shipping_method_id, $notrigger=0, $userused=null)
Change the shipping method.
update_note_public($note)
Update public note (kept for backward compatibility)
getSpecialCode($lineid)
Get special code of a line.
clearObjectLinkedCache()
Clear the cache saying that all linked object were already loaded.
update_ref_ext($ref_ext)
Update external ref of element.
fetchOneLike($ref)
Looks for an object with ref matching the wildcard provided It does only work when $this->table_ref_f...
hasProductsOrServices($predefined=-1)
Function to say how many lines object contains.
static isExistingObject($element, $id, $ref='', $ref_ext='')
Check if an object id or ref exists If you don't need or want to instantiate the object and just need...
isObjectUsed($id=0, $entity=0)
Function to check if an object is used by others (by children).
updateRangOfLine($rowid, $rang)
Update position of line (rang)
getDefaultCreateValueFor($fieldname, $alternatevalue=null, $type='alphanohtml')
Return the default value to use for a field when showing the create form of object.
add_element_resource($resource_id, $resource_type, $busy=0, $mandatory=0, $notrigger=0)
Add resources to the current object : add entry into llx_element_resources Need $this->element & $thi...
checkActiveProductInLines($status='onsale')
Check if all products have the right status (on sale, on buy) called during validation of propal,...
createCommon(User $user, $notrigger=0)
Create object in the database.
getTotalWeightVolume()
Return into unit=0, the calculated total of weight and volume of all lines * qty Calculate by adding ...
update_note($note, $suffix='', $notrigger=0)
Update note of element.
getFullAddress($withcountry=0, $sep="\n", $withregion=0, $extralangcode='')
Return full address of contact.
fetch_project()
Load the project with id $this->fk_project into this->project.
getFieldList($alias='', $excludefields=array())
Function to concat keys of fields.
getNbComments()
Return nb comments already posted.
setVarsFromFetchObj(&$obj)
Function to load data from a SQL pointer into properties of current object $this.
printObjectLines($action, $seller, $buyer, $selected=0, $dateSelector=0, $defaulttpldir='/core/tpl')
Return HTML table for object lines TODO Move this into an output class file (htmlline....
getChildrenOfLine($id, $includealltree=0)
Get children of line.
updateCommon(User $user, $notrigger=0)
Update object into database.
updateExtraLanguages($key, $trigger=null, $userused=null)
Update an extra language value for the current object.
deleteExtraFields()
Delete all extra fields values for the current object.
setStatusCommon($user, $status, $notrigger=0, $triggercode='')
Set to a status.
deprecatedProperties()
Provide list of deprecated properties and replacements.
setSaveQuery()
Function to return the array of data key-value from the ->fields and all the ->properties of an objec...
setValuesForExtraLanguages($onlykey='')
Fill array_options property of object by extrafields value (using for data sent by forms) Used for ex...
insertExtraLanguages($trigger='', $userused=null)
Add/Update all extra languages values for the current object.
setTransportMode($id)
Change the transport mode methods.
isArray($info)
Function test if type is array.
isInt($info)
Function test if type is integer.
fetchObjectLinked($sourceid=null, $sourcetype='', $targetid=null, $targettype='', $clause='OR', $alsosametype=1, $orderby='sourcetype', $loadalsoobjects=1)
Fetch array of objects linked to current object (object of enabled modules only).
delete_contact($rowid, $notrigger=0)
Delete a link to contact line.
updateLineUp($rowid, $rang)
Update position of line up (rang)
fetch_user($userid)
Load the user with id $userid into this->user.
errorsToString()
Method to output saved errors.
getListContactId($source='external')
Return list of id of contacts of object.
setWarehouse($warehouse_id)
Change the warehouse.
setDeliveryAddress($id)
Define delivery address.
fetchBarCode()
Load data for barcode into properties ->barcode_type* Properties ->barcode_type that is id of barcode...
getTotalDiscount()
Function that returns the total amount HT of discounts applied for all lines.
initAsSpecimenCommon()
Initialise object with example values Id must be 0 if object instance is a specimen.
printObjectLine($action, $line, $var, $num, $i, $dateSelector, $seller, $buyer, $selected=0, $extrafields=null, $defaulttpldir='/core/tpl')
Return HTML content of a detail line TODO Move this into an output class file (htmlline....
copy_linked_contact($objFrom, $source='internal')
Copy contact from one element to current.
static commonReplaceThirdparty(DoliDB $dbs, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
Function used to replace a thirdparty id with another one.
getValueFrom($table, $id, $field)
Getter generic.
trimParameters($parameters)
Trim object parameters.
fetch_product()
Load the product with id $this->fk_product into this->product.
isIndex($info)
Function test if is indexed.
quote($value, $fieldsentry)
Add quote to field value if necessary.
formAddObjectLine($dateSelector, $seller, $buyer, $defaulttpldir='/core/tpl')
Show add free and predefined products/services form.
fetchComments()
Load comments linked with current task.
line_down($rowid, $fk_parent_line=true)
Update a line to have a higher rank.
setValueFrom($field, $value, $table='', $id=null, $format='', $id_field='', $fuser=null, $trigkey='', $fk_user_field='fk_user_modif')
Setter generic.
fetch_contact($contactid=null)
Load object contact with id=$this->contact_id into $this->contact.
delThumbs($file)
Delete thumbs.
show_photos($modulepart, $sdir, $size=0, $nbmax=0, $nbbyrow=5, $showfilename=0, $showaction=0, $maxHeight=120, $maxWidth=160, $nolink=0, $overwritetitle=0, $usesharelink=0, $cache='', $addphotorefcss='photoref')
Show photos of an object (nbmax maximum), into several columns.
fetchLinesCommon($morewhere='', $noextrafields=0)
Load object in memory from the database.
static commonReplaceProduct(DoliDB $dbs, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
Function used to replace a product id with another one.
getRangOfLine($rowid)
Get position of line (rang)
showInputField($val, $key, $value, $moreparam='', $keysuffix='', $keyprefix='', $morecss=0, $nonewbutton=0)
Return HTML string to put an input field into a page Code very similar with showInputField of extra f...
update_contact($rowid, $statut, $type_contact_id=0, $fk_socpeople=0)
Update a link to contact line.
getElementType()
Return an element type string formatted like element_element target_type and source_type.
load_previous_next_ref($filter, $fieldid, $nodbprefix=0)
Load properties id_previous and id_next by comparing $fieldid with $this->ref.
setCategoriesCommon($categories, $type_categ='', $remove_existing=true)
Sets object to given categories.
fetchValuesForExtraLanguages()
Function to get alternative languages of a data into $this->array_languages This method is NOT called...
fetchNoCompute($id)
Function to make a fetch but set environment to avoid to load computed values before.
line_max($fk_parent_line=0)
Get max value used for position of line (rang)
getJSListDependancies($type='_extra')
setProject($projectid, $notrigger=0)
Link element with a project.
isForcedToNullIfZero($info)
Function test if field is forced to null if zero or empty.
line_ajaxorder($rows)
Update position of line with ajax (rang)
printOriginLinesList($restrictlist='', $selectedLines=array())
Return HTML table table of source object lines TODO Move this and previous function into output html ...
fetch_origin()
Read linked origin object.
getIdOfLine($rang)
Get rowid of the line relative to its position.
insertExtraFields($trigger='', $userused=null)
Add/Update all extra fields values for the current object.
deleteByParentField($parentId=0, $parentField='', $filter='', $filtermode="AND")
Delete all child object from a parent ID.
static getAllItemsLinkedByObjectID($fk_object_where, $field_select, $field_where, $table_element)
Function used to get an array with all items linked to an object id in association table.
__clone()
Overwrite magic function to solve problem of cloning object that are kept as references.
setPaymentMethods($id)
Change the payments methods.
updateLineDown($rowid, $rang, $max)
Update position of line down (rang)
delete_linked_contact($source='', $code='')
Delete all links between an object $this and all its contacts in llx_element_contact.
fetchCommon($id, $ref=null, $morewhere='', $noextrafields=0)
Load object in memory from the database.
deleteCommon(User $user, $notrigger=0, $forcechilddeletion=0)
Delete object in database.
getFormatedCustomerRef($objref)
Return customer ref for screen output.
getTooltipContentArray($params)
Return array of data to show into a tooltip.
isText($info)
Function test if type is text.
isDate($info)
Function test if type is date.
printOriginLine($line, $var, $restrictlist='', $defaulttpldir='/core/tpl', $selectedLines=array())
Return HTML with a line of table array of source object lines TODO Move this and previous function in...
showOptionals($extrafields, $mode='view', $params=null, $keysuffix='', $keyprefix='', $onetrtd='', $display_type='card')
Function to show lines of extrafields with output data.
getCanvas($id=0, $ref='')
Load type of canvas of an object if it exists.
line_up($rowid, $fk_parent_line=true)
Update a line to have a lower rank.
isDuration($info)
Function test if type is duration.
setErrorWithLog($message, $loglevel=LOG_ERR)
Set the error message for the object and logs it, including the file name and line number.
canBeNull($info)
Function test if field can be null.
listeTypeContacts($source='internal', $option=0, $activeonly=0, $code='', $element='', $excludeelement='')
Return array with list of possible values for type of contacts.
getRights()
Returns the rights used for this class.
addThumbs($file, $quality=50)
Build thumb.
add_contact($fk_socpeople, $type_contact, $source='external', $notrigger=0)
Add a link between element $this->element and a contact.
cloneCategories($fromId, $toId, $type='')
Copy related categories to another object.
fetch_barcode()
Load data for barcode into properties ->barcode_type* Properties ->barcode_type that is id of barcode...
Class to manage absolute discounts.
Class to manage a WYSIWYG editor.
Class to manage Dolibarr database access.
Class to manage donations.
Class to manage ECM files.
const TYPE_CREDIT_NOTE
Credit note invoice.
Parent class of subscription templates.
Parent class to manage intervention document templates.
static getIdAndTxFromCode($dbs, $code, $date_document=0)
Get id and rate of currency from code.
Class to manage predefined suppliers products.
Class to manage products or services.
const TYPE_SERVICE
Service.
Class to manage projects.
Class to manage third parties objects (customers, suppliers, prospects...)
Class to manage translations.
Class to manage Dolibarr users.
Class toolbox to validate values.
print $langs trans("Ref").' m titre as m m statut as status
Or an array listing all the potential status of the object: array: int of the status => translated la...
getCountry($searchkey, $withcode='', $dbtouse=null, $outputlangs=null, $entconv=1, $searchlabel='')
Return country label, code or id from an id, code or label.
getState($id, $withcode='0', $dbtouse=null, $withregion=0, $outputlangs=null, $entconv=1)
Return state translated from an id.
convertSecondToTime($iSecond, $format='all', $lengthOfDay=86400, $lengthOfWeek=7)
Return, in clear text, value of a number of seconds in days, hours and minutes.
dol_meta_create($object)
Create a meta file with document file into same directory.
completeFileArrayWithDatabaseInfo(&$filearray, $relativedir, $object=null)
Complete $filearray with data from database.
dol_delete_file($file, $disableglob=0, $nophperrors=0, $nohook=0, $object=null, $allowdotdot=false, $indexdatabase=1, $nolog=0)
Remove a file or several files with a mask.
dol_delete_dir_recursive($dir, $count=0, $nophperrors=0, $onlysub=0, &$countdeleted=0, $indexdatabase=1, $nolog=0, $level=0)
Remove a directory $dir and its subdirectories (or only files and subdirectories)
dol_is_file($pathoffile)
Return if path is a file.
dol_dir_list($utf8_path, $types="all", $recursive=0, $filter="", $excludefilter=null, $sortcriteria="name", $sortorder=SORT_ASC, $mode=0, $nohook=0, $relativename="", $donotfollowsymlinks=0, $nbsecondsold=0)
Scan a directory and return a list of files/directories.
dol_is_dir($folder)
Test if filename is a directory.
dol_delete_preview($object)
Delete all preview files linked to object instance.
$date_start
Variables from include:
dol_now($mode='gmt')
Return date for now.
dol_mktime($hour, $minute, $second, $month, $day, $year, $gm='auto', $check=1)
Return a timestamp date built from detailed information (by default a local PHP server timestamp) Rep...
dol_print_email($email, $contactid=0, $socid=0, $addlink=0, $max=0, $showinvalid=2, $withpicto=0, $morecss='paddingrightonly')
Show EMail link formatted for HTML output.
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='', $noduplicate=0, $attop=0)
Set event messages in dol_events session object.
vatrate($rate, $addpercent=false, $info_bits=0, $usestarfornpr=0, $html=0)
Return a string with VAT rate label formatted for view output Used into pdf and HTML pages.
dol_print_ip($ip, $mode=0, $showname=0)
Return an IP formatted to be shown on screen.
dol_print_phone($phone, $countrycode='', $contactid=0, $socid=0, $addlink='', $separ=" ", $withpicto='', $titlealt='', $adddivfloat=0, $morecss='paddingright')
Format phone numbers according to country.
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2, $allowothertags=array())
Show picto whatever it's its name (generic function)
img_delete($titlealt='default', $other='class="pictodelete"', $morecss='')
Show delete logo.
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.
forgeSQLFromUniversalSearchCriteria($filter, &$errorstr='', $noand=0, $nopar=0, $noerror=0)
forgeSQLFromUniversalSearchCriteria
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
getElementProperties($elementType)
Get an array with properties of an element.
dol_escape_js($stringtoescape, $mode=0, $noescapebackslashn=0)
Returns text escaped for inclusion into JavaScript code.
dol_sort_array(&$array, $index, $order='asc', $natsort=0, $case_sensitive=0, $keepindex=0)
Advanced sort array by the value of a given key, which produces ascending (default) or descending out...
if(!function_exists( 'dol_getprefix')) dol_include_once($relpath, $classname='')
Make an include_once using default root and alternate root if it fails.
getMultidirOutput($object, $module='', $forobject=0, $mode='output')
Return the full path of the directory where a module (or an object of a module) stores its files.
newToken()
Return the value of token currently saved into session with name 'newtoken'.
dolPrintHTMLForAttribute($s, $escapeonlyhtmltags=0, $allowothertags=array())
Return a string ready to be output into an HTML attribute (alt, title, data-html, ....
getImageFileNameForSize($file, $extName, $extImgTarget='')
Return the filename of file to get the thumbs.
yn($yesno, $format=1, $color=0)
Return yes or no in current language.
get_date_range($date_start, $date_end, $format='', $outputlangs=null, $withparenthesis=1)
Format output for start and end date.
getAdvancedPreviewUrl($modulepart, $relativepath, $alldata=0, $param='')
Return URL we can use for advanced preview links.
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.
getDictionaryValue($tablename, $field, $id, $checkentity=false, $rowidfield='rowid')
Return the value of a filed into a dictionary for the record $id.
get_exdir($num, $level, $alpha, $withoutslash, $object, $modulepart='')
Return a path to have a the directory according to object where files are stored.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
getEntity($element, $shared=1, $currentobject=null)
Get list of entity id to use.
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $noescapetags='', $escapeonlyhtmltags=0, $cleanalsojavascript=0)
Returns text escaped for inclusion in HTML alt or title or value tags, or into values of HTML input f...
vignette($file, $maxWidth=160, $maxHeight=120, $extName='_small', $quality=50, $outdir='thumbs', $targetformat=0)
Create a thumbnail from an image file (Supported extensions are gif, jpg, png and bmp).
if(!defined( 'IMAGETYPE_WEBP')) getDefaultImageSizes()
Return default values for image sizes.
dol_getImageSize($file, $url=false)
Return size of image file on disk (Supported extensions are gif, jpg, png, bmp and webp)
image_format_supported($file, $acceptsvg=0)
Return if a filename is file name of a supported image format.
query($query, $usesavepoint=0, $type='auto', $result_mode=0)
Execute a SQL request and return the resultset.
print $langs trans("Show") . '< td style="' . $timeColor . '" align="center"> s</td > badge status0 badge status4 badge status3 Error badge status8< td align="center">< span class="badge ' . $badge . '"></span ></td >< td align="center">< a href="#" class="button button-small" onclick="openLogModal(this)" data-req="' . dol_escape_htmltag($reqSafe) . '" data-res="' . dol_escape_htmltag($resSafe) . '" data-err="' . dol_escape_htmltag($errSafe) . '">< span class="fa fa-search-plus"></span ></a ></td ></tr >< tr >< td colspan="' . $colspan . '" class="opacitymedium"></td ></tr ></table ></div ></form > logModal none logModal none s a JSON string
buildzip.php
calcul_price_total($qty, $pu, $remise_percent_ligne, $txtva, $uselocaltax1_rate, $uselocaltax2_rate, $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.