45require_once DOL_DOCUMENT_ROOT.
'/core/class/doldeprecationhandler.class.php';
46require_once DOL_DOCUMENT_ROOT.
'/core/class/commontrigger.class.php';
55 use DolDeprecationHandler;
92 public $errors = array();
97 public $warnings = array();
102 private $validateFieldsErrors = array();
120 public $element_for_permission;
125 public $table_element;
135 public $table_element_line =
'';
141 public $ismultientitymanaged;
151 public $array_options = array();
198 public $fields = array();
205 public $array_languages =
null;
210 public $contacts_ids;
215 public $contacts_ids_internal;
220 public $linked_objects;
225 public $linkedObjectsIds;
230 public $linkedObjects;
235 private $linkedObjectsFullLoaded = array();
250 protected $table_ref_field =
'';
255 public $restrictiononfksoc = 0;
264 public $context = array();
375 private $commandeFournisseur;
391 public $ref_previous;
437 public $country_code;
480 public $barcode_type;
486 public $barcode_type_code;
492 public $barcode_type_label;
498 public $barcode_type_coder;
504 public $mode_reglement_id;
510 public $cond_reglement_id;
515 public $demand_reason_id;
521 public $transport_mode_id;
530 private $cond_reglement;
534 protected $depr_cond_reglement;
541 public $fk_delivery_address;
547 public $shipping_method_id;
553 public $shipping_method;
559 public $fk_multicurrency;
565 public $multicurrency_code;
571 public $multicurrency_tx;
576 public $multicurrency_total_ht;
581 public $multicurrency_total_tva;
586 public $multicurrency_total_localtax1;
591 public $multicurrency_total_localtax2;
596 public $multicurrency_total_ttc;
609 public $last_main_doc;
634 public $note_private;
659 public $total_localtax1;
665 public $total_localtax2;
682 public $actiontypecode;
688 public $comments = array();
714 public $civility_code;
720 public $date_creation;
725 public $date_validation;
730 public $date_modification;
744 private $date_update;
749 public $date_cloture;
754 public $user_creation_id;
759 public $user_validation_id;
764 public $user_closing_id;
769 public $user_modification_id;
775 public $fk_user_creat;
781 public $fk_user_modif;
787 public $next_prev_filter;
792 public $specimen = 0;
816 public $totalpaid_multicurrency;
822 public $labelStatus = array();
827 public $labelStatusShort = array();
838 public $showphoto_on_popup;
843 public $nb = array();
858 public $extraparams = array();
863 protected $childtables = array();
870 protected $childtablesoncascade = array();
875 public $cond_reglement_supplier_id;
882 public $deposit_percent;
888 public $retained_warranty_fk_cond_reglement;
893 public $warehouse_id;
898 public $isextrafieldmanaged = 0;
911 'alreadypaid' =>
'totalpaid',
912 'cond_reglement' =>
'depr_cond_reglement',
914 'commandeFournisseur' =>
'origin_object',
915 'expedition' =>
'origin_object',
916 'fk_project' =>
'fk_project',
917 'livraison' =>
'origin_object',
918 'projet' =>
'project',
919 'statut' =>
'status',
938 $sql =
"SELECT rowid";
939 $sql .=
" FROM ".$db->prefix().$element;
940 $sql .=
" WHERE entity IN (".getEntity($element).
")";
943 $sql .=
" AND rowid = ".((int) $id);
945 $sql .=
" AND ref = '".$db->escape($ref).
"'";
946 } elseif ($ref_ext) {
947 $sql .=
" AND ref_ext = '".$db->escape($ref_ext).
"'";
949 $error =
'ErrorWrongParameters';
950 dol_syslog(get_class().
"::isExistingObject ".$error, LOG_ERR);
953 if ($ref || $ref_ext) {
954 $sql .=
" AND entity = ".((int) $conf->entity);
957 dol_syslog(get_class().
"::isExistingObject", LOG_DEBUG);
958 $resql = $db->query($sql);
960 $num = $db->num_rows($resql);
977 return (empty($this->
id));
992 $this->errors = array_merge($this->errors,
$object->errors);
1017 global $action, $extrafields, $langs, $hookmanager;
1020 $MAX_EXTRAFIELDS_TO_SHOW_IN_TOOLTIP =
getDolGlobalInt(
'MAX_EXTRAFIELDS_TO_SHOW_IN_TOOLTIP', 3);
1026 if (!empty($extrafields->attributes[$this->table_element][
'label'])) {
1027 $data[
'opendivextra'] =
'<div class="centpercent wordbreak divtooltipextra">';
1028 foreach ($extrafields->attributes[$this->table_element][
'label'] as $key => $val) {
1029 if ($extrafields->attributes[$this->table_element][
'type'][$key] ==
'separate') {
1032 if ($count >= abs($MAX_EXTRAFIELDS_TO_SHOW_IN_TOOLTIP)) {
1033 $data[
'more_extrafields'] =
'<br>...';
1037 if ($enabled && isset($extrafields->attributes[$this->table_element][
'enabled'][$key])) {
1038 $enabled = (int)
dol_eval((
string) $extrafields->attributes[$this->table_element][
'enabled'][$key], 1, 1,
'2');
1040 if ($enabled && isset($extrafields->attributes[$this->table_element][
'list'][$key])) {
1041 $enabled = (int)
dol_eval((
string) $extrafields->attributes[$this->table_element][
'list'][$key], 1, 1,
'2');
1044 if ($perms && isset($extrafields->attributes[$this->table_element][
'perms'][$key])) {
1045 $perms = (int)
dol_eval((
string) $extrafields->attributes[$this->table_element][
'perms'][$key], 1, 1,
'2');
1047 if (empty($enabled)) {
1050 if (abs($enabled) != 1 && abs($enabled) != 3 && abs($enabled) != 5 && abs($enabled) != 4) {
1053 if (empty($perms)) {
1056 if (!empty($extrafields->attributes[$this->table_element][
'langfile'][$key])) {
1057 $langs->load($extrafields->attributes[$this->table_element][
'langfile'][$key]);
1059 $labelextra = $langs->trans((
string) $extrafields->attributes[$this->table_element][
'label'][$key]);
1060 if ($extrafields->attributes[$this->table_element][
'type'][$key] ==
'separate') {
1061 $data[$key] =
'<br><b><u>'. $labelextra .
'</u></b>';
1063 $value = (empty($this->array_options[
'options_' . $key]) ?
'' : $this->array_options[
'options_' . $key]);
1064 $data[$key] =
'<br><b>'. $labelextra .
':</b> ' . $extrafields->showOutputField($key, $value,
'', $this->table_element);
1068 $data[
'closedivextra'] =
'</div>';
1071 $hookmanager->initHooks(array($this->element .
'dao'));
1072 $parameters = array(
1073 'tooltipcontentarray' => &$data,
1074 'params' => $params,
1077 $hookmanager->executeHooks(
'getTooltipContent', $parameters, $this, $action);
1080 $label = implode($data);
1093 return $this->error.(is_array($this->errors) ? (($this->error !=
'' ?
', ' :
'').implode(
', ', $this->errors)) :
'');
1105 global $hookmanager;
1107 $parameters = array(
'objref' => $objref);
1109 $reshook = $hookmanager->executeHooks(
'getFormatedCustomerRef', $parameters, $this, $action);
1111 return $hookmanager->resArray[
'objref'];
1113 return $objref.(isset($hookmanager->resArray[
'objref']) ? $hookmanager->resArray[
'objref'] :
'');
1124 global $hookmanager;
1126 $parameters = array(
'objref' => $objref);
1128 $reshook = $hookmanager->executeHooks(
'getFormatedSupplierRef', $parameters, $this, $action);
1130 return $hookmanager->resArray[
'objref'];
1132 return $objref.(isset($hookmanager->resArray[
'objref']) ? $hookmanager->resArray[
'objref'] :
'');
1144 public function getFullAddress($withcountry = 0, $sep =
"\n", $withregion = 0, $extralangcode =
'')
1146 if ($withcountry && $this->country_id && (empty($this->country_code) || empty($this->country))) {
1147 require_once DOL_DOCUMENT_ROOT.
'/core/lib/company.lib.php';
1148 $tmparray =
getCountry($this->country_id,
'all');
1149 $this->country_code = $tmparray[
'code'];
1150 $this->country = $tmparray[
'label'];
1153 if ($withregion && $this->state_id && (empty($this->state_code) || empty($this->state) || empty($this->region) || empty($this->region_code))) {
1154 require_once DOL_DOCUMENT_ROOT.
'/core/lib/company.lib.php';
1155 $tmparray =
getState($this->state_id,
'all',
null, 1);
1156 $this->state_code = $tmparray[
'code'];
1157 $this->state = $tmparray[
'label'];
1158 $this->region_code = $tmparray[
'region_code'];
1159 $this->region = $tmparray[
'region'];
1178 if (empty($this->last_main_doc)) {
1182 include_once DOL_DOCUMENT_ROOT.
'/ecm/class/ecmfiles.class.php';
1183 $ecmfile =
new EcmFiles($this->db);
1184 $result = $ecmfile->fetch(0,
'', $this->last_main_doc);
1186 $this->error = $ecmfile->error;
1187 $this->errors = $ecmfile->errors;
1191 if (empty($ecmfile->id)) {
1193 if ($initsharekey) {
1194 require_once DOL_DOCUMENT_ROOT.
'/core/lib/security2.lib.php';
1216 } elseif (empty($ecmfile->share)) {
1218 if ($initsharekey) {
1219 require_once DOL_DOCUMENT_ROOT.
'/core/lib/security2.lib.php';
1221 $ecmfile->update($user);
1227 $urlwithouturlroot = preg_replace(
'/'.preg_quote(DOL_URL_ROOT,
'/').
'$/i',
'', trim(
$dolibarr_main_url_root));
1231 $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT;
1240 if (!empty($ecmfile->share)) {
1241 $paramlink .= ($paramlink ?
'&' :
'').
'hashp='.$ecmfile->share;
1243 if ($forcedownload) {
1244 $paramlink .= ($paramlink ?
'&' :
'').
'attachment=1';
1247 if ($relativelink) {
1248 $linktoreturn =
'document.php'.($paramlink ?
'?'.$paramlink :
'');
1250 $linktoreturn = $urlwithroot.
'/document.php'.($paramlink ?
'?'.$paramlink :
'');
1254 return $linktoreturn;
1268 public function add_contact($fk_socpeople, $type_contact, $source =
'external', $notrigger = 0)
1271 global $user, $langs;
1273 dol_syslog(get_class($this).
"::add_contact $fk_socpeople, $type_contact, $source, $notrigger");
1276 if ($fk_socpeople <= 0) {
1277 $langs->load(
"errors");
1278 $this->error = $langs->trans(
"ErrorWrongValueForParameterX",
"1");
1279 dol_syslog(get_class($this).
"::add_contact ".$this->error, LOG_ERR);
1282 if (!$type_contact) {
1283 $langs->load(
"errors");
1284 $this->error = $langs->trans(
"ErrorWrongValueForParameterX",
"2");
1285 dol_syslog(get_class($this).
"::add_contact ".$this->error, LOG_ERR);
1289 if ($this->restrictiononfksoc && property_exists($this,
'socid') && !empty($this->socid) && !$user->hasRight(
'societe',
'client',
'voir')) {
1290 $sql_allowed_contacts =
'SELECT COUNT(*) as cnt FROM '.$this->db->prefix().
'societe_commerciaux as sc';
1291 $sql_allowed_contacts .=
' WHERE sc.fk_soc = '.(int) $this->socid;
1292 $sql_allowed_contacts .=
' AND sc.fk_user = '.(int) $user->id;
1294 $resql_allowed_contacts = $this->db->query($sql_allowed_contacts);
1296 if (!$resql_allowed_contacts) {
1297 $this->errors[] = $this->db->lasterror();
1299 } elseif ($obj = $this->db->fetch_object($resql_allowed_contacts)) {
1300 if ($obj->cnt == 0) {
1301 $langs->load(
"companies");
1302 $this->error = $langs->trans(
"ErrorCommercialNotAllowedForThirdparty", $user->id);
1303 dol_syslog(get_class($this).
"::add_contact ".$this->error, LOG_ERR);
1309 $id_type_contact = 0;
1310 if (is_numeric($type_contact)) {
1311 $id_type_contact = $type_contact;
1314 $sql =
"SELECT tc.rowid";
1315 $sql .=
" FROM ".$this->db->prefix().
"c_type_contact as tc";
1316 $sql .=
" WHERE tc.element='".$this->db->escape($this->element).
"'";
1317 $sql .=
" AND tc.source='".$this->db->escape($source).
"'";
1318 $sql .=
" AND tc.code='".$this->db->escape($type_contact).
"' AND tc.active=1";
1320 $resql = $this->db->query($sql);
1322 $obj = $this->db->fetch_object($resql);
1324 $id_type_contact = $obj->rowid;
1328 if ($id_type_contact == 0) {
1329 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");
1337 $already_added =
false;
1338 if (is_array($TListeContacts) && !empty($TListeContacts)) {
1339 foreach ($TListeContacts as $array_contact) {
1340 if ($array_contact[
'status'] == 4 && $array_contact[
'id'] == $fk_socpeople && $array_contact[
'fk_c_type_contact'] == $id_type_contact) {
1341 $already_added =
true;
1347 if (!$already_added) {
1351 $sql =
"INSERT INTO ".$this->db->prefix().
"element_contact";
1352 $sql .=
" (element_id, fk_socpeople, datecreate, statut, fk_c_type_contact) ";
1353 $sql .=
" VALUES (".$this->id.
", ".((int) $fk_socpeople).
" , ";
1354 $sql .=
"'".$this->db->idate($datecreate).
"'";
1355 $sql .=
", 4, ".((int) $id_type_contact);
1358 $resql = $this->db->query($sql);
1361 $triggerPrefix = (empty($this->TRIGGER_PREFIX) ? strtoupper($this->element) : $this->TRIGGER_PREFIX);
1362 $result = $this->call_trigger($triggerPrefix.
'_ADD_CONTACT', $user);
1364 $this->db->rollback();
1369 $this->db->commit();
1372 if ($this->db->errno() ==
'DB_ERROR_RECORD_ALREADY_EXISTS') {
1373 $this->error = $this->db->errno();
1374 $this->db->rollback();
1377 $this->error = $this->db->lasterror();
1378 $this->db->rollback();
1398 $contacts = $objFrom->liste_contact(-1, $source);
1399 foreach ($contacts as $contact) {
1400 if ($this->
add_contact($contact[
'id'], $contact[
'fk_c_type_contact'], $contact[
'source']) < 0) {
1417 public function update_contact($rowid, $statut, $type_contact_id = 0, $fk_socpeople = 0)
1421 $sql =
"UPDATE ".$this->db->prefix().
"element_contact set";
1422 $sql .=
" statut = ".((int) $statut);
1423 if ($type_contact_id) {
1424 $sql .=
", fk_c_type_contact = ".((int) $type_contact_id);
1426 if ($fk_socpeople) {
1427 $sql .=
", fk_socpeople = ".((int) $fk_socpeople);
1429 $sql .=
" where rowid = ".((int) $rowid);
1431 $resql = $this->db->query($sql);
1435 $this->error = $this->db->lasterror();
1456 if ($this->
id > 0) {
1457 $sql =
"SELECT ec.rowid FROM ".$this->db->prefix().
"element_contact as ec, ".$this->db->prefix().
"c_type_contact as tc";
1458 $sql .=
" WHERE ec.rowid = ".((int) $rowid).
" AND ec.element_id = ".((int) $this->
id);
1459 $sql .=
" AND ec.fk_c_type_contact = tc.rowid AND tc.element = '".$this->db->escape($this->element).
"'";
1460 $resql = $this->db->query($sql);
1461 if (!$resql || !$this->db->num_rows($resql)) {
1462 $this->error =
'ErrorRecordNotFound';
1469 if (!$error && empty($notrigger)) {
1471 $this->context[
'contact_id'] = ((int) $rowid);
1472 $triggerPrefix = (empty($this->TRIGGER_PREFIX) ? strtoupper($this->element) : $this->TRIGGER_PREFIX);
1473 $result = $this->call_trigger($triggerPrefix.
'_DELETE_CONTACT', $user);
1481 dol_syslog(get_class($this).
"::delete_contact", LOG_DEBUG);
1483 $sql =
"DELETE FROM ".MAIN_DB_PREFIX.
"element_contact";
1484 $sql .=
" WHERE rowid = ".((int) $rowid);
1486 $result = $this->db->query($sql);
1489 $this->errors[] = $this->db->lasterror();
1494 $this->db->commit();
1497 $this->error = $this->db->lasterror();
1498 $this->db->rollback();
1518 if (!empty($typeContact)) {
1519 foreach ($typeContact as $key => $value) {
1520 array_push($temp, $key);
1522 $listId = implode(
",", $temp);
1527 if (empty($listId)) {
1531 $sql =
"DELETE FROM ".$this->db->prefix().
"element_contact";
1532 $sql .=
" WHERE element_id = ".((int) $this->
id);
1533 $sql .=
" AND fk_c_type_contact IN (".$this->db->sanitize($listId).
")";
1535 dol_syslog(get_class($this).
"::delete_linked_contact", LOG_DEBUG);
1536 if ($this->db->query($sql)) {
1539 $this->error = $this->db->lasterror();
1556 public function liste_contact($statusoflink = -1, $source =
'external', $list = 0, $code =
'', $status = -1, $arrayoftcids = array())
1563 $sql =
"SELECT ec.rowid, ec.statut as statuslink, ec.fk_socpeople as id, ec.fk_c_type_contact";
1564 if ($source ==
'internal') {
1565 $sql .=
", '-1' as socid, t.statut as statuscontact, t.login, t.photo, t.gender, t.fk_country as country_id";
1567 if ($source ==
'external' || $source ==
'thirdparty') {
1568 $sql .=
", t.fk_soc as socid, t.statut as statuscontact, t.fk_pays as country_id";
1570 $sql .=
", t.civility as civility, t.lastname as lastname, t.firstname, t.email, t.address, t.zip, t.town";
1571 if (empty($arrayoftcids)) {
1572 $sql .=
", tc.source, tc.element, tc.code, tc.libelle as type_label, co.label as country";
1575 if (empty($arrayoftcids)) {
1576 $sql .=
" ".$this->db->prefix().
"c_type_contact as tc,";
1578 $sql .=
" ".$this->db->prefix().
"element_contact as ec";
1579 if ($source ==
'internal') {
1580 $sql .=
" LEFT JOIN ".$this->db->prefix().
"user as t on ec.fk_socpeople = t.rowid";
1581 $sql .=
" LEFT JOIN ".$this->db->prefix().
"c_country as co ON co.rowid = t.fk_country";
1583 if ($source ==
'external' || $source ==
'thirdparty') {
1584 $sql .=
" LEFT JOIN ".$this->db->prefix().
"socpeople as t on ec.fk_socpeople = t.rowid";
1585 $sql .=
" LEFT JOIN ".$this->db->prefix().
"c_country as co ON co.rowid = t.fk_pays";
1587 $sql .=
" WHERE ec.element_id = ".((int) $this->
id);
1588 if (empty($arrayoftcids)) {
1589 $sql .=
" AND ec.fk_c_type_contact = tc.rowid";
1590 $sql .=
" AND tc.element = '".$this->db->escape($this->element).
"'";
1592 $sql .=
" AND tc.code = '".$this->db->escape($code).
"'";
1594 if ($source ==
'internal') {
1595 $sql .=
" AND tc.source = 'internal'";
1597 if ($source ==
'external' || $source ==
'thirdparty') {
1598 $sql .=
" AND tc.source = 'external'";
1600 $sql .=
" AND tc.active = 1";
1602 $sql .=
" AND ec.fk_c_type_contact IN (".$this->db->sanitize(implode(
',', $arrayoftcids)).
")";
1605 $sql .=
" AND t.statut = ".((int) $status);
1607 if ($statusoflink >= 0) {
1608 $sql .=
" AND ec.statut = ".((int) $statusoflink);
1610 $sql .=
" ORDER BY t.lastname ASC";
1612 dol_syslog(get_class($this).
"::liste_contact", LOG_DEBUG);
1613 $resql = $this->db->query($sql);
1615 $num = $this->db->num_rows($resql);
1618 $obj = $this->db->fetch_object($resql);
1621 $transkey =
"TypeContact_".$obj->element.
"_".$obj->source.
"_".$obj->code;
1622 $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->type_label);
1624 'parentId' => $this->
id,
1625 'source' => $obj->source,
1626 'socid' => $obj->socid,
1628 'nom' => $obj->lastname,
1629 'civility' => $obj->civility,
1630 'lastname' => $obj->lastname,
1631 'firstname' => $obj->firstname,
1632 'email' => $obj->email,
1633 'address' => $obj->address,
1635 'town' => $obj->town,
1636 'country_id' => $obj->country_id,
1637 'country' => $obj->country,
1638 'login' => (empty($obj->login) ?
'' : $obj->login),
1639 'photo' => (empty($obj->photo) ?
'' : $obj->photo),
1640 'gender' => (empty($obj->gender) ?
'' : $obj->gender),
1641 'statuscontact' => $obj->statuscontact,
1642 'rowid' => $obj->rowid,
1643 'code' => $obj->code,
1644 'libelle' => $libelle_type,
1645 'status' => (
int) $obj->statuslink,
1646 'fk_c_type_contact' => $obj->fk_c_type_contact
1649 $tab[$i] = $obj->id;
1657 $this->error = $this->db->lasterror();
1672 $sql =
"SELECT ec.datecreate, ec.statut, ec.fk_socpeople, ec.fk_c_type_contact,";
1673 $sql .=
" tc.code, tc.libelle as type_label";
1674 $sql .=
" FROM (".$this->db->prefix().
"element_contact as ec, ".$this->db->prefix().
"c_type_contact as tc)";
1675 $sql .=
" WHERE ec.rowid =".((int) $rowid);
1676 $sql .=
" AND ec.fk_c_type_contact = tc.rowid";
1677 $sql .=
" AND tc.element = '".$this->db->escape($this->element).
"'";
1679 dol_syslog(get_class($this).
"::swapContactStatus", LOG_DEBUG);
1680 $resql = $this->db->query($sql);
1682 $obj = $this->db->fetch_object($resql);
1683 $newstatut = ($obj->statut == 4) ? 5 : 4;
1685 $this->db->free($resql);
1688 $this->error = $this->db->error();
1705 public function liste_type_contact($source =
'internal', $order =
'position', $option = 0, $activeonly = 0, $code =
'')
1710 if (empty($order)) {
1711 $order =
'position';
1713 if ($order ==
'position') {
1719 $sql =
"SELECT DISTINCT tc.rowid, tc.code, tc.libelle as type_label, tc.position";
1720 $sql .=
" FROM ".$this->db->prefix().
"c_type_contact as tc";
1721 $sql .=
" WHERE tc.element = '".$this->db->escape($this->element).
"'";
1722 if ($activeonly == 1) {
1723 $sql .=
" AND tc.active = 1";
1725 if (!empty($source) && $source !=
'all') {
1726 $sql .=
" AND tc.source = '".$this->db->escape($source).
"'";
1728 if (!empty($code)) {
1729 $sql .=
" AND tc.code = '".$this->db->escape($code).
"'";
1731 $sql .= $this->db->order($order,
'ASC');
1734 $resql = $this->db->query($sql);
1736 $this->error = $this->db->lasterror();
1741 $num = $this->db->num_rows($resql);
1744 $obj = $this->db->fetch_object($resql);
1746 $transkey =
"TypeContact_".$this->element.
"_".$source.
"_".$obj->code;
1747 $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $langs->trans($obj->type_label));
1748 if (empty($option)) {
1749 $tab[$obj->rowid] = $libelle_type;
1750 } elseif ($option == 1) {
1751 $tab[$obj->code] = $libelle_type;
1753 $tab[$obj->rowid] = array(
'id' => $obj->rowid,
'code' => $obj->code,
'label' => $libelle_type);
1772 public function listeTypeContacts($source =
'internal', $option = 0, $activeonly = 0, $code =
'', $element =
'', $excludeelement =
'')
1776 $langs->loadLangs(array(
'bills',
'contracts',
'interventions',
'orders',
'projects',
'propal',
'ticket',
'agenda'));
1780 $sql =
"SELECT DISTINCT tc.rowid, tc.code, tc.libelle as type_label, tc.position, tc.element, tc.module";
1781 $sql .=
" FROM ".$this->db->prefix().
"c_type_contact as tc";
1783 $sqlWhere = array();
1784 if (!empty($element)) {
1785 $sqlWhere[] =
" tc.element='".$this->db->escape($element).
"'";
1787 if (!empty($excludeelement)) {
1788 $sqlWhere[] =
" tc.element <> '".$this->db->escape($excludeelement).
"'";
1791 if ($activeonly == 1) {
1792 $sqlWhere[] =
" tc.active=1";
1795 if (!empty($source) && $source !=
'all') {
1796 $sqlWhere[] =
" tc.source='".$this->db->escape($source).
"'";
1799 if (!empty($code)) {
1800 $sqlWhere[] =
" tc.code='".$this->db->escape($code).
"'";
1803 if (count($sqlWhere) > 0) {
1804 $sql .=
" WHERE ".implode(
' AND ', $sqlWhere);
1807 $sql .= $this->db->order(
'tc.element, tc.position',
'ASC');
1810 $resql = $this->db->query($sql);
1812 $num = $this->db->num_rows($resql);
1814 $langs->loadLangs(array(
"propal",
"orders",
"bills",
"suppliers",
"contracts",
"supplier_proposal"));
1816 while ($obj = $this->db->fetch_object($resql)) {
1817 $modulename = $obj->module ?? $obj->element;
1818 if (strpos($obj->element,
'project') !==
false) {
1819 $modulename =
'projet';
1820 } elseif ($obj->element ==
'contrat') {
1821 $element =
'contract';
1822 } elseif ($obj->element ==
'action') {
1823 $modulename =
'agenda';
1824 } elseif (strpos($obj->element,
'supplier') !==
false && $obj->element !=
'supplier_proposal') {
1825 $modulename =
'fournisseur';
1828 $libelle_element = $langs->trans(
'ContactDefault_'.$obj->element);
1829 $tmpelement = $obj->element;
1830 $transkey =
"TypeContact_".$tmpelement.
"_".$source.
"_".$obj->code;
1831 $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->type_label);
1832 $tab[$obj->rowid] = $libelle_element.
' - '.$libelle_type;
1838 $this->error = $this->db->lasterror();
1859 if (!
getDolGlobalInt(
'SHIPPING_USE_ITS_OWN_CONTACTS') && $this->element ==
'shipping' && $this->origin_id != 0) {
1860 $id = $this->origin_id;
1861 $element =
'commande';
1862 } elseif ($this->element ==
'reception' && $this->origin_id != 0) {
1863 $id = $this->origin_id;
1864 $element =
'order_supplier';
1867 $element = $this->element;
1870 $sql =
"SELECT ec.fk_socpeople";
1871 $sql .=
" FROM ".$this->db->prefix().
"element_contact as ec,";
1872 if ($source ==
'internal') {
1873 $sql .=
" ".$this->db->prefix().
"user as c,";
1875 if ($source ==
'external') {
1876 $sql .=
" ".$this->db->prefix().
"socpeople as c,";
1878 $sql .=
" ".$this->db->prefix().
"c_type_contact as tc";
1879 $sql .=
" WHERE ec.element_id = ".((int) $id);
1880 $sql .=
" AND ec.fk_socpeople = c.rowid";
1881 if ($source ==
'internal') {
1882 $sql .=
" AND c.entity IN (".getEntity(
'user').
")";
1884 if ($source ==
'external') {
1885 $sql .=
" AND c.entity IN (".getEntity(
'societe').
")";
1887 $sql .=
" AND ec.fk_c_type_contact = tc.rowid";
1888 $sql .=
" AND tc.element = '".$this->db->escape($element).
"'";
1889 $sql .=
" AND tc.source = '".$this->db->escape($source).
"'";
1891 $sql .=
" AND tc.code = '".$this->db->escape($code).
"'";
1893 $sql .=
" AND tc.active = 1";
1895 $sql .=
" AND ec.statut = ".((int) $status);
1898 dol_syslog(get_class($this).
"::getIdContact", LOG_DEBUG);
1899 $resql = $this->db->query($sql);
1901 while ($obj = $this->db->fetch_object($resql)) {
1902 $result[$i] = $obj->fk_socpeople;
1906 $this->error = $this->db->error();
1923 if (empty($contactid)) {
1924 $contactid = $this->contact_id;
1927 if (empty($contactid)) {
1931 require_once DOL_DOCUMENT_ROOT.
'/contact/class/contact.class.php';
1932 $contact =
new Contact($this->db);
1933 $result = $contact->fetch($contactid);
1934 $this->contact = $contact;
1949 if (empty($this->socid) && empty($this->fk_soc) && empty($force_thirdparty_id)) {
1953 require_once DOL_DOCUMENT_ROOT.
'/societe/class/societe.class.php';
1955 $idtofetch = isset($this->socid) ? $this->socid : (isset($this->fk_soc) ? $this->fk_soc : 0);
1956 if ($force_thirdparty_id) {
1957 $idtofetch = $force_thirdparty_id;
1961 $thirdparty =
new Societe($this->db);
1962 $result = $thirdparty->fetch($idtofetch);
1964 $this->errors = array_merge($this->errors, $thirdparty->errors);
1966 $this->thirdparty = $thirdparty;
1970 $this->thirdparty->price_level = 1;
1989 if (!$this->table_ref_field) {
1993 $sql =
"SELECT rowid FROM ".$this->db->prefix().$this->table_element;
1994 $sql .=
" WHERE ".$this->table_ref_field.
" LIKE '".$this->db->escape($ref).
"'";
1997 $query = $this->db->query($sql);
1999 if (!$this->db->num_rows($query)) {
2003 $result = $this->db->fetch_object($query);
2005 if (method_exists($this,
'fetch')) {
2006 return $this->fetch($result->rowid);
2008 $this->error =
'Fetch method not implemented on '.get_class($this);
2009 dol_syslog(get_class($this).
'::fetchOneLike Error='.$this->error, LOG_ERR);
2010 array_push($this->errors, $this->error);
2039 dol_syslog(get_class($this).
'::fetchBarCode this->element='.$this->element.
' this->barcode_type='.$this->barcode_type);
2041 $idtype = $this->barcode_type;
2042 if (empty($idtype) && $idtype !=
'0') {
2043 if ($this->element ==
'product' &&
getDolGlobalString(
'PRODUIT_DEFAULT_BARCODE_TYPE')) {
2045 } elseif ($this->element ==
'societe') {
2048 dol_syslog(
'Call fetchBarCode with barcode_type not defined and cannot be guessed', LOG_WARNING);
2053 if (empty($this->barcode_type) || empty($this->barcode_type_code) || empty($this->barcode_type_label) || empty($this->barcode_type_coder)) {
2054 $sql =
"SELECT rowid, code, libelle as label, coder";
2055 $sql .=
" FROM ".$this->db->prefix().
"c_barcode_type";
2056 $sql .=
" WHERE rowid = ".((int) $idtype);
2058 $resql = $this->db->query($sql);
2060 $obj = $this->db->fetch_object($resql);
2062 $this->barcode_type = $obj->rowid;
2063 $this->barcode_type_code = $obj->code;
2064 $this->barcode_type_label = $obj->label;
2065 $this->barcode_type_coder = $obj->coder;
2083 include_once DOL_DOCUMENT_ROOT.
'/projet/class/project.class.php';
2085 if (empty($this->fk_project) && !empty($this->fk_projet)) {
2086 $this->fk_project = $this->fk_projet;
2088 if (empty($this->fk_project)) {
2092 $project =
new Project($this->db);
2093 $result = $project->fetch($this->fk_project);
2095 $this->project = $project;
2137 include_once DOL_DOCUMENT_ROOT.
'/product/class/product.class.php';
2140 if (empty($this->fk_product)) {
2144 $product =
new Product($this->db);
2146 $result = $product->fetch($this->fk_product);
2148 $this->product = $product;
2162 $user =
new User($this->db);
2163 $result = $user->fetch($userid);
2164 $this->
user = $user;
2178 $tmpclassname = $this->origin ? $this->origin : $this->origin_type;
2181 if ($tmpclassname ==
'shipping') {
2182 $tmpclassname =
'Expedition';
2184 if ($tmpclassname ==
'delivery') {
2185 $tmpclassname =
'Livraison';
2187 if ($tmpclassname ==
'order_supplier' || $tmpclassname ==
'supplier_order') {
2188 $tmpclassname =
'CommandeFournisseur';
2191 $classname = ucfirst($tmpclassname);
2193 $this->origin_object =
new $classname($this->db);
2195 $this->origin_object->fetch($this->origin_id);
2213 $sql =
"SELECT rowid FROM ".$this->db->prefix().$table;
2214 $sql .=
" WHERE ".$field.
" = '".$this->db->escape($key).
"'";
2215 if (!empty($element)) {
2216 $sql .=
" AND entity IN (".getEntity($element).
")";
2218 $sql .=
" AND entity = ".((int) $conf->entity);
2221 dol_syslog(get_class($this).
'::fetchObjectFrom', LOG_DEBUG);
2222 $resql = $this->db->query($sql);
2224 $obj = $this->db->fetch_object($resql);
2227 if (method_exists($this,
'fetch')) {
2228 $result = $this->fetch($obj->rowid);
2230 $this->error =
'fetch() method not implemented on '.get_class($this);
2231 dol_syslog(get_class($this).
'::fetchOneLike Error='.$this->error, LOG_ERR);
2232 array_push($this->errors, $this->error);
2252 if (!empty($id) && !empty($field) && !empty($table)) {
2253 if (!preg_match(
'/^[a-zA-Z_][a-zA-Z0-9_]*$/', $table)) {
2254 dol_syslog(get_class($this).
'::getValueFrom Bad table name: '.$table, LOG_WARNING);
2257 if (!preg_match(
'/^[a-zA-Z_][a-zA-Z0-9_.]*$/', $field)) {
2258 dol_syslog(get_class($this).
'::getValueFrom Bad field name: '.$field, LOG_WARNING);
2262 $sql =
"SELECT ".$this->db->sanitize($field).
" FROM ".$this->db->prefix().$this->db->sanitize($table);
2263 $sql .=
" WHERE rowid = ".((int) $id);
2265 dol_syslog(get_class($this).
'::getValueFrom', LOG_DEBUG);
2266 $resql = $this->db->query($sql);
2268 $row = $this->db->fetch_row($resql);
2291 public function setValueFrom($field, $value, $table =
'', $id =
null, $format =
'', $id_field =
'', $fuser =
null, $trigkey =
'', $fk_user_field =
'fk_user_modif')
2295 if (empty($table)) {
2296 $table = $this->table_element;
2301 if (empty($format)) {
2304 if (empty($id_field)) {
2305 $id_field =
'rowid';
2308 $propfield = $field;
2311 if ($table ==
'product') {
2312 if ($field ==
'note_private') {
2314 $propfield =
'note_private';
2315 } elseif ($field ==
'status') {
2317 $propfield =
'status';
2318 } elseif ($field ==
'status_buy') {
2320 $propfield =
'status_buy';
2321 } elseif ($field ==
'status_batch') {
2323 $propfield =
'status_batch';
2327 if (in_array($table, array(
'actioncomm',
'adherent',
'advtargetemailing',
'cronjob',
'establishment'))) {
2328 $fk_user_field =
'fk_user_mod';
2330 if (in_array($table, array(
'prelevement_bons'))) {
2331 $fk_user_field =
'';
2334 if (!preg_match(
'/^[a-zA-Z_][a-zA-Z0-9_]*$/', $table)) {
2335 dol_syslog(get_class($this).
'::getValueFrom Bad table name: '.$table, LOG_WARNING);
2338 if (!preg_match(
'/^[a-zA-Z_][a-zA-Z0-9_.]*$/', $field)) {
2339 dol_syslog(get_class($this).
'::getValueFrom Bad field name: '.$field, LOG_WARNING);
2345 $sql =
"SELECT " . $this->db->sanitize($field);
2346 $sql .=
" FROM " . MAIN_DB_PREFIX . $this->db->sanitize($table);
2347 $sql .=
" WHERE " . $this->db->sanitize($id_field) .
" = " . ((int) $id);
2349 $resql = $this->db->query($sql);
2351 if ($obj = $this->db->fetch_object($resql)) {
2352 if ($format ==
'date') {
2353 $oldvalue = $this->db->jdate($obj->$field);
2355 $oldvalue = $obj->$field;
2359 $this->error = $this->db->lasterror();
2370 $sql =
"UPDATE ".$this->db->prefix().$table.
" SET ";
2372 if ($format ==
'text') {
2373 $sql .= $this->db->sanitize($field).
" = '".$this->db->escape($value).
"'";
2374 } elseif ($format ==
'int') {
2375 $sql .= $this->db->sanitize($field).
" = ".((int) $value);
2376 } elseif ($format ==
'date') {
2377 $sql .= $this->db->sanitize($field).
" = ".($value ?
"'".$this->db->idate($value).
"'" :
"null");
2378 } elseif ($format ==
'dategmt') {
2379 $sql .= $this->db->sanitize($field).
" = ".($value ?
"'".$this->db->idate($value,
'gmt').
"'" :
"null");
2382 if ($fk_user_field) {
2383 if (!empty($fuser) && is_object($fuser)) {
2384 $sql .=
", ".$this->db->sanitize($fk_user_field).
" = ".((int) $fuser->id);
2385 } elseif (empty($fuser) || $fuser !=
'none') {
2386 $sql .=
", ".$this->db->sanitize($fk_user_field).
" = ".((int) $user->id);
2390 $sql .=
" WHERE ".$this->db->sanitize($id_field).
" = ".((int) $id);
2392 $resql = $this->db->query($sql);
2396 if (method_exists($this,
'fetch')) {
2397 $result = $this->fetch(
$id);
2402 $this->oldcopy = clone $this;
2403 if (property_exists($this->oldcopy, $field)) {
2404 $this->oldcopy->$field = $oldvalue;
2406 if ($propfield != $field && property_exists($this->oldcopy, $propfield)) {
2407 $this->oldcopy->$propfield = $oldvalue;
2410 if (empty($this->context[
'actionmsgmore'])) {
2411 $this->context[
'actionmsgmore'] =
'Trigger called by setValueFrom';
2415 $result = $this->call_trigger($trigkey, (!empty($fuser) && is_object($fuser)) ? $fuser : $user);
2421 if (property_exists($this, $field)) {
2422 $this->$field = $value;
2424 if ($propfield != $field && property_exists($this, $propfield)) {
2425 $this->$propfield = $value;
2430 $this->db->commit();
2433 if (property_exists($this, $field)) {
2434 $this->$field = $oldvalue;
2436 if ($propfield != $field && property_exists($this, $propfield)) {
2437 $this->$propfield = $oldvalue;
2439 $this->db->rollback();
2443 if ($this->db->lasterrno() ==
'DB_ERROR_RECORD_ALREADY_EXISTS') {
2444 $this->error =
'DB_ERROR_RECORD_ALREADY_EXISTS';
2446 $this->error = $this->db->lasterror();
2448 $this->db->rollback();
2467 global $conf, $user;
2469 if (!$this->table_element) {
2470 dol_print_error(
null, get_class($this).
"::load_previous_next_ref was called on object with property table_element not defined");
2473 if ($fieldid ==
'none') {
2478 if (in_array($this->table_element, array(
'facture_rec',
'facture_fourn_rec')) && $fieldid ==
'title') {
2484 if ($user->socid > 0) {
2485 $socid = $user->socid;
2490 $aliastablesociete =
's';
2491 if ($this->element ==
'societe') {
2492 $aliastablesociete =
'te';
2494 $restrictiononfksoc = empty($this->restrictiononfksoc) ? 0 : $this->restrictiononfksoc;
2495 $sql =
"SELECT MAX(te.".$fieldid.
")";
2496 $sql .=
" FROM ".(empty($nodbprefix) ? $this->db->prefix() :
'').$this->table_element.
" as te";
2497 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2498 $tmparray = explode(
'@', $this->ismultientitymanaged);
2499 $sql .=
", ".$this->db->prefix().$tmparray[1].
" as ".($tmparray[1] ==
'societe' ?
's' :
'parenttable');
2500 } elseif ($restrictiononfksoc == 1 && $this->element !=
'societe' && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2501 $sql .=
", ".$this->db->prefix().
"societe as s";
2502 } elseif ($restrictiononfksoc == 2 && $this->element !=
'societe' && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2503 $sql .=
" LEFT JOIN ".$this->db->prefix().
"societe as s ON te.fk_soc = s.rowid";
2505 if ($restrictiononfksoc && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2506 $sql .=
" LEFT JOIN ".$this->db->prefix().
"societe_commerciaux as sc ON ".$aliastablesociete.
".rowid = sc.fk_soc";
2508 if ($fieldid ==
'rowid') {
2509 $sql .=
" WHERE te.".$fieldid.
" < ".((int) $this->
id);
2510 } elseif ($fieldid ==
'label') {
2511 $sql .=
" WHERE te.".$fieldid.
" < '".$this->db->escape((
string) $this->label).
"'";
2513 $sql .=
" WHERE te.".$fieldid.
" < '".$this->db->escape((
string) $this->
ref).
"'";
2515 if ($restrictiononfksoc == 1 && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2516 $sql .=
" AND sc.fk_user = ".((int) $user->id);
2518 if ($restrictiononfksoc == 2 && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2519 $sql .=
" AND (sc.fk_user = ".((int) $user->id).
' OR te.fk_soc IS NULL)';
2522 $filtermax = $filter;
2527 if ($errormessage) {
2528 if (!preg_match(
'/^\s*AND/i', $filtermax)) {
2536 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2537 $tmparray = explode(
'@', $this->ismultientitymanaged);
2538 $sql .=
" AND te.".$tmparray[0].
" = ".($tmparray[1] ==
"societe" ?
"s" :
"parenttable").
".rowid";
2539 } elseif ($restrictiononfksoc == 1 && $this->element !=
'societe' && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2540 $sql .=
' AND te.fk_soc = s.rowid';
2542 if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
2543 if ($this->element ==
'user' &&
getDolGlobalInt(
'MULTICOMPANY_TRANSVERSE_MODE')) {
2544 if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
2545 $sql .=
" AND te.entity IS NOT NULL";
2547 $sql .=
" AND te.rowid IN (SELECT ug.fk_user FROM ".$this->db->prefix().
"usergroup_user as ug WHERE ug.entity IN (".
getEntity(
'usergroup').
"))";
2550 $sql .=
' AND te.entity IN ('.getEntity($this->element).
')';
2553 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged) && $this->element !=
'societe') {
2554 $tmparray = explode(
'@', $this->ismultientitymanaged);
2555 $sql .=
' AND parenttable.entity IN ('.getEntity($tmparray[1]).
')';
2557 if ($restrictiononfksoc == 1 && $socid && $this->element !=
'societe') {
2558 $sql .=
' AND te.fk_soc = '.((int) $socid);
2560 if ($restrictiononfksoc == 2 && $socid && $this->element !=
'societe') {
2561 $sql .=
' AND (te.fk_soc = '.((int) $socid).
' OR te.fk_soc IS NULL)';
2563 if ($restrictiononfksoc && $socid && $this->element ==
'societe') {
2564 $sql .=
' AND te.rowid = '.((int) $socid);
2568 $result = $this->db->query($sql);
2570 $this->error = $this->db->lasterror();
2573 $row = $this->db->fetch_row($result);
2574 $this->ref_previous = $row[0];
2576 $sql =
"SELECT MIN(te.".$fieldid.
")";
2577 $sql .=
" FROM ".(empty($nodbprefix) ? $this->db->prefix() :
'').$this->table_element.
" as te";
2578 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2579 $tmparray = explode(
'@', $this->ismultientitymanaged);
2580 $sql .=
", ".$this->db->prefix().$tmparray[1].
" as ".($tmparray[1] ==
'societe' ?
's' :
'parenttable');
2581 } elseif ($restrictiononfksoc == 1 && $this->element !=
'societe' && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2582 $sql .=
", ".$this->db->prefix().
"societe as s";
2583 } elseif ($restrictiononfksoc == 2 && $this->element !=
'societe' && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2584 $sql .=
" LEFT JOIN ".$this->db->prefix().
"societe as s ON te.fk_soc = s.rowid";
2586 if ($restrictiononfksoc && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2587 $sql .=
" LEFT JOIN ".$this->db->prefix().
"societe_commerciaux as sc ON ".$aliastablesociete.
".rowid = sc.fk_soc";
2589 if ($fieldid ==
'rowid') {
2590 $sql .=
" WHERE te.".$fieldid.
" > ".((int) $this->
id);
2591 } elseif ($fieldid ==
'label') {
2592 $sql .=
" WHERE te.".$fieldid.
" > '".$this->db->escape((
string) $this->label).
"'";
2594 $sql .=
" WHERE te.".$fieldid.
" > '".$this->db->escape((
string) $this->
ref).
"'";
2596 if ($restrictiononfksoc == 1 && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2597 $sql .=
" AND (sc.fk_user = ".((int) $user->id);
2599 $userschilds = $user->getAllChildIds();
2600 $sql .=
" OR sc.fk_user IN (".$this->db->sanitize(implode(
',', $userschilds)).
")";
2604 if ($restrictiononfksoc == 2 && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2605 $sql .=
" AND (sc.fk_user = ".((int) $user->id).
' OR te.fk_soc IS NULL)';
2608 $filtermin = $filter;
2613 if ($errormessage) {
2614 if (!preg_match(
'/^\s*AND/i', $filtermin)) {
2624 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2625 $tmparray = explode(
'@', $this->ismultientitymanaged);
2626 $sql .=
" AND te.".$tmparray[0].
" = ".($tmparray[1] ==
"societe" ?
"s" :
"parenttable").
".rowid";
2627 } elseif ($restrictiononfksoc == 1 && $this->element !=
'societe' && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2628 $sql .=
' AND te.fk_soc = s.rowid';
2630 if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
2631 if ($this->element ==
'user' &&
getDolGlobalInt(
'MULTICOMPANY_TRANSVERSE_MODE')) {
2632 if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
2633 $sql .=
" AND te.entity IS NOT NULL";
2635 $sql .=
" AND te.rowid IN (SELECT ug.fk_user FROM ".$this->db->prefix().
"usergroup_user as ug WHERE ug.entity IN (".
getEntity(
'usergroup').
"))";
2638 $sql .=
' AND te.entity IN ('.getEntity($this->element).
')';
2641 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged) && $this->element !=
'societe') {
2642 $tmparray = explode(
'@', $this->ismultientitymanaged);
2643 $sql .=
' AND parenttable.entity IN ('.getEntity($tmparray[1]).
')';
2645 if ($restrictiononfksoc == 1 && $socid && $this->element !=
'societe') {
2646 $sql .=
' AND te.fk_soc = '.((int) $socid);
2648 if ($restrictiononfksoc == 2 && $socid && $this->element !=
'societe') {
2649 $sql .=
' AND (te.fk_soc = '.((int) $socid).
' OR te.fk_soc IS NULL)';
2651 if ($restrictiononfksoc && $socid && $this->element ==
'societe') {
2652 $sql .=
' AND te.rowid = '.((int) $socid);
2657 $result = $this->db->query($sql);
2659 $this->error = $this->db->lasterror();
2662 $row = $this->db->fetch_row($result);
2663 $this->ref_next = $row[0];
2678 $contactAlreadySelected = array();
2683 if ($source ==
'thirdparty') {
2684 $contactAlreadySelected[$i] = $tab[$i][
'socid'];
2686 $contactAlreadySelected[$i] = $tab[$i][
'id'];
2690 return $contactAlreadySelected;
2706 if (!$this->table_element) {
2707 dol_syslog(get_class($this).
"::setProject was called on object with property table_element not defined", LOG_ERR);
2711 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
2712 if ($this->table_element ==
'actioncomm') {
2714 $sql .=
" SET fk_project = ".((int) $projectid);
2716 $sql .=
" SET fk_project = NULL";
2718 $sql .=
' WHERE id = '.((int) $this->
id);
2720 } elseif (!empty($this->fields[
'fk_project'])) {
2722 $sql .=
" SET fk_project = ".((int) $projectid);
2724 $sql .=
" SET fk_project = NULL";
2726 $sql .=
' WHERE rowid = '.((int) $this->
id);
2729 $sql .=
' SET fk_projet = '.((int) $projectid);
2731 $sql .=
' SET fk_projet = NULL';
2733 $sql .=
" WHERE rowid = ".((int) $this->
id);
2738 dol_syslog(get_class($this).
"::setProject", LOG_DEBUG);
2739 if ($this->db->query($sql)) {
2740 $this->fk_project = ((int) $projectid);
2747 if (!$error && !$notrigger) {
2749 $result = $this->call_trigger(strtoupper($this->element) .
'_MODIFY', $user);
2758 $this->db->rollback();
2761 $this->db->commit();
2779 dol_syslog(get_class($this).
'::setPaymentMethods('.$id.
')');
2781 if ($this->
status >= 0 || $this->element ==
'societe') {
2783 $fieldname =
'fk_mode_reglement';
2784 if ($this->element ==
'societe') {
2785 $fieldname =
'mode_reglement';
2787 if (get_class($this) ==
'Fournisseur') {
2788 $fieldname =
'mode_reglement_supplier';
2790 if (get_class($this) ==
'Tva') {
2791 $fieldname =
'fk_typepayment';
2793 if (get_class($this) ==
'Salary') {
2794 $fieldname =
'fk_typepayment';
2797 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
2798 $sql .=
" SET ".$this->db->sanitize($fieldname).
" = ".(($id > 0 || $id ==
'0') ? ((
int) $id) :
'NULL');
2799 $sql .=
' WHERE rowid = '.((int) $this->
id);
2801 if ($this->db->query($sql)) {
2802 $this->mode_reglement_id = $id;
2804 if (get_class($this) ==
'Fournisseur') {
2805 $this->mode_reglement_supplier_id = $id;
2808 if (!$error && !$notrigger) {
2810 $triggerName = (empty($this->TRIGGER_PREFIX) ? strtoupper(get_class($this)) : $this->TRIGGER_PREFIX);
2811 $result = $this->call_trigger($triggerName.
'_MODIFY', $user);
2819 dol_syslog(get_class($this).
'::setPaymentMethods Error '.$this->db->error());
2820 $this->error = $this->db->error();
2824 dol_syslog(get_class($this).
'::setPaymentMethods, status of the object is incompatible');
2825 $this->error =
'Status of the object is incompatible '.$this->status;
2838 dol_syslog(get_class($this).
'::setMulticurrencyCode('.$code.
')');
2839 if ($this->
status >= 0 || $this->element ==
'societe') {
2840 $fieldname =
'multicurrency_code';
2842 $sql =
'UPDATE '.$this->db->prefix().$this->table_element;
2843 $sql .=
" SET ".$fieldname.
" = '".$this->db->escape($code).
"'";
2844 $sql .=
' WHERE rowid='.((int) $this->
id);
2846 if ($this->db->query($sql)) {
2847 $this->multicurrency_code = $code;
2851 $this->setMulticurrencyRate($rate, 2);
2856 dol_syslog(get_class($this).
'::setMulticurrencyCode Error '.$sql.
' - '.$this->db->error());
2857 $this->error = $this->db->error();
2861 dol_syslog(get_class($this).
'::setMulticurrencyCode, status of the object is incompatible');
2862 $this->error =
'Status of the object is incompatible '.$this->status;
2874 public function setMulticurrencyRate($rate, $mode = 1)
2876 dol_syslog(get_class($this).
'::setMulticurrencyRate('.$rate.
', '.$mode.
')');
2877 if ($this->
status >= 0 || $this->element ==
'societe') {
2878 $fieldname =
'multicurrency_tx';
2880 $sql =
'UPDATE '.$this->db->prefix().$this->table_element;
2881 $sql .=
" SET ".$this->db->sanitize($fieldname).
" = ".((float) $rate);
2882 $sql .=
' WHERE rowid='.((int) $this->
id);
2884 if ($this->db->query($sql)) {
2885 $this->multicurrency_tx = $rate;
2888 if (!empty($this->lines)) {
2889 foreach ($this->lines as &$line) {
2892 $line->subprice = 0;
2897 $line->multicurrency_subprice = 0;
2900 switch ($this->element) {
2904 '@phan-var-force Propal $this';
2905 '@phan-var-force PropaleLigne $line';
2910 $line->remise_percent,
2912 $line->localtax1_tx,
2913 $line->localtax2_tx,
2914 ($line->description ? $line->description : $line->desc),
2917 $line->special_code,
2918 $line->fk_parent_line,
2919 $line->skip_update_total,
2920 $line->fk_fournprice,
2923 $line->product_type,
2926 $line->array_options,
2928 $line->multicurrency_subprice
2934 '@phan-var-force Commande $this';
2935 '@phan-var-force OrderLine $line';
2938 ($line->description ? $line->description : $line->desc),
2941 $line->remise_percent,
2943 $line->localtax1_tx,
2944 $line->localtax2_tx,
2949 $line->product_type,
2950 $line->fk_parent_line,
2951 $line->skip_update_total,
2952 $line->fk_fournprice,
2955 $line->special_code,
2956 $line->array_options,
2958 $line->multicurrency_subprice
2964 '@phan-var-force Facture $this';
2965 '@phan-var-force FactureLigne $line';
2968 ($line->description ? $line->description : $line->desc),
2971 $line->remise_percent,
2975 $line->localtax1_tx,
2976 $line->localtax2_tx,
2979 $line->product_type,
2980 $line->fk_parent_line,
2981 $line->skip_update_total,
2982 $line->fk_fournprice,
2985 $line->special_code,
2986 $line->array_options,
2987 $line->situation_percent,
2989 $line->multicurrency_subprice
2995 '@phan-var-force FactureRec $this';
2996 '@phan-var-force FactureLigneRec $line';
2999 ($line->description ? $line->description : $line->desc),
3003 $line->localtax1_tx,
3004 $line->localtax2_tx,
3006 $line->remise_percent,
3011 $line->product_type,
3013 $line->special_code,
3016 $line->multicurrency_subprice,
3020 $line->fk_fournprice,
3022 $line->fk_parent_line
3025 case 'supplier_proposal':
3028 '@phan-var-force SupplierProposal $this';
3029 '@phan-var-force SupplierProposalLine $line';
3034 $line->remise_percent,
3036 $line->localtax1_tx,
3037 $line->localtax2_tx,
3038 ($line->description ? $line->description : $line->desc),
3041 $line->special_code,
3042 $line->fk_parent_line,
3043 $line->skip_update_total,
3044 $line->fk_fournprice,
3047 $line->product_type,
3048 $line->array_options,
3050 (int) $line->fk_unit,
3051 $line->multicurrency_subprice
3054 case 'order_supplier':
3057 '@phan-var-force CommandeFournisseur $this';
3058 '@phan-var-force CommandeFournisseurLigne $line';
3061 ($line->description ? $line->description : $line->desc),
3064 $line->remise_percent,
3066 $line->localtax1_tx,
3067 $line->localtax2_tx,
3070 $line->product_type,
3074 $line->array_options,
3076 $line->multicurrency_subprice,
3080 case 'invoice_supplier':
3083 '@phan-var-force FactureFournisseur $this';
3084 '@phan-var-force SupplierInvoiceLIne $line';
3087 ($line->description ? $line->description : $line->desc),
3090 $line->localtax1_tx,
3091 $line->localtax2_tx,
3096 $line->product_type,
3097 $line->remise_percent,
3101 $line->array_options,
3103 $line->multicurrency_subprice,
3108 dol_syslog(get_class($this).
'::setMulticurrencyRate no updateline defined', LOG_DEBUG);
3116 dol_syslog(get_class($this).
'::setMulticurrencyRate Error '.$sql.
' - '.$this->db->error());
3117 $this->error = $this->db->error();
3121 dol_syslog(get_class($this).
'::setMulticurrencyRate, status of the object is incompatible');
3122 $this->error =
'Status of the object is incompatible '.$this->status;
3136 dol_syslog(get_class($this).
'::setPaymentTerms('.$id.
', '.var_export($deposit_percent,
true).
')');
3137 if ($this->
status >= 0 || $this->element ==
'societe') {
3139 $fieldname =
'fk_cond_reglement';
3140 if ($this->element ==
'societe') {
3141 $fieldname =
'cond_reglement';
3143 if (get_class($this) ==
'Fournisseur') {
3144 $fieldname =
'cond_reglement_supplier';
3147 if (empty($deposit_percent) || $deposit_percent < 0) {
3148 $deposit_percent = (float)
getDictionaryValue(
'c_payment_term',
'deposit_percent', $id);
3151 if ($deposit_percent > 100) {
3152 $deposit_percent = 100;
3155 $sql =
'UPDATE '.$this->db->prefix().$this->table_element;
3156 $sql .=
" SET ".$fieldname.
" = ".(($id > 0 || $id ==
'0') ? ((
int) $id) :
'NULL');
3157 if (in_array($this->table_element, array(
'propal',
'commande',
'supplier_proposal',
'commande_fournisseur',
'societe'))) {
3158 $sql .=
" , deposit_percent = " . (empty($deposit_percent) ?
'NULL' :
"'".$this->db->escape((
string) $deposit_percent).
"'");
3160 $sql .=
' WHERE rowid='.((int) $this->
id);
3162 if ($this->db->query($sql)) {
3163 $this->cond_reglement_id = $id;
3165 if (get_class($this) ==
'Fournisseur') {
3166 $this->cond_reglement_supplier_id = $id;
3168 $this->deposit_percent = $deposit_percent;
3171 dol_syslog(get_class($this).
'::setPaymentTerms Error '.$sql.
' - '.$this->db->error());
3172 $this->error = $this->db->error();
3176 dol_syslog(get_class($this).
'::setPaymentTerms, status of the object is incompatible');
3177 $this->error =
'Status of the object is incompatible '.$this->status;
3190 dol_syslog(get_class($this).
'::setTransportMode('.$id.
')');
3191 if ($this->
status >= 0 || $this->element ==
'societe') {
3192 $fieldname =
'fk_transport_mode';
3193 if ($this->element ==
'societe') {
3194 $fieldname =
'transport_mode';
3196 if (get_class($this) ==
'Fournisseur') {
3197 $fieldname =
'transport_mode_supplier';
3200 $sql =
'UPDATE '.$this->db->prefix().$this->table_element;
3201 $sql .=
" SET ".$fieldname.
" = ".(($id > 0 || $id ==
'0') ? ((
int) $id) :
'NULL');
3202 $sql .=
' WHERE rowid='.((int) $this->
id);
3204 if ($this->db->query($sql)) {
3205 $this->transport_mode_id = $id;
3207 if (get_class($this) ==
'Fournisseur') {
3208 $this->transport_mode_supplier_id = $id;
3212 dol_syslog(get_class($this).
'::setTransportMode Error '.$sql.
' - '.$this->db->error());
3213 $this->error = $this->db->error();
3217 dol_syslog(get_class($this).
'::setTransportMode, status of the object is incompatible');
3218 $this->error =
'Status of the object is incompatible '.$this->status;
3231 dol_syslog(get_class($this).
'::setRetainedWarrantyPaymentTerms('.$id.
')');
3232 if ($this->
status >= 0 || $this->element ==
'societe') {
3233 $fieldname =
'retained_warranty_fk_cond_reglement';
3235 $sql =
'UPDATE '.$this->db->prefix().$this->table_element;
3236 $sql .=
" SET ".$fieldname.
" = ".((int) $id);
3237 $sql .=
' WHERE rowid='.((int) $this->
id);
3239 if ($this->db->query($sql)) {
3240 $this->retained_warranty_fk_cond_reglement = $id;
3243 dol_syslog(get_class($this).
'::setRetainedWarrantyPaymentTerms Error '.$sql.
' - '.$this->db->error());
3244 $this->error = $this->db->error();
3248 dol_syslog(get_class($this).
'::setRetainedWarrantyPaymentTerms, status of the object is incompatible');
3249 $this->error =
'Status of the object is incompatible '.$this->status;
3263 $fieldname =
'fk_delivery_address';
3264 if ($this->element ==
'delivery' || $this->element ==
'shipping') {
3265 $fieldname =
'fk_address';
3268 $sql =
"UPDATE ".$this->db->prefix().$this->table_element.
" SET ".$fieldname.
" = ".((int) $id);
3269 $sql .=
" WHERE rowid = ".((int) $this->
id).
" AND fk_statut = 0";
3271 if ($this->db->query($sql)) {
3272 $this->fk_delivery_address = $id;
3275 $this->error = $this->db->error();
3276 dol_syslog(get_class($this).
'::setDeliveryAddress Error '.$this->error);
3294 if (empty($userused)) {
3300 if (!$this->table_element) {
3301 dol_syslog(get_class($this).
"::setShippingMethod was called on object with property table_element not defined", LOG_ERR);
3307 if ($shipping_method_id < 0) {
3308 $shipping_method_id =
'NULL';
3310 dol_syslog(get_class($this).
'::setShippingMethod('.$shipping_method_id.
')');
3312 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
3313 $sql .=
" SET fk_shipping_method = ".((int) $shipping_method_id);
3314 $sql .=
" WHERE rowid=".((int) $this->
id);
3315 $resql = $this->db->query($sql);
3317 dol_syslog(get_class($this).
'::setShippingMethod Error ', LOG_DEBUG);
3318 $this->error = $this->db->lasterror();
3323 $this->context = array(
'shippingmethodupdate' => 1);
3324 $triggerPrefix = (empty($this->TRIGGER_PREFIX) ? strtoupper(get_class($this)) : $this->TRIGGER_PREFIX);
3325 $result = $this->call_trigger($triggerPrefix.
'_MODIFY', $userused);
3333 $this->db->rollback();
3336 $this->shipping_method_id = ($shipping_method_id ==
'NULL') ?
null : $shipping_method_id;
3337 $this->db->commit();
3351 if (!$this->table_element) {
3352 dol_syslog(get_class($this).
"::setWarehouse was called on object with property table_element not defined", LOG_ERR);
3355 if ($warehouse_id < 0) {
3356 $warehouse_id =
'NULL';
3358 dol_syslog(get_class($this).
'::setWarehouse('.$warehouse_id.
')');
3360 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
3361 $sql .=
" SET fk_warehouse = ".((int) $warehouse_id);
3362 $sql .=
" WHERE rowid=".((int) $this->
id);
3364 if ($this->db->query($sql)) {
3365 $this->warehouse_id = ($warehouse_id ==
'NULL') ?
null : $warehouse_id;
3368 dol_syslog(get_class($this).
'::setWarehouse Error ', LOG_DEBUG);
3369 $this->error = $this->db->error();
3384 if (!$this->table_element) {
3385 dol_syslog(get_class($this).
"::setDocModel was called on object with property table_element not defined", LOG_ERR);
3389 $newmodelpdf =
dol_trunc($modelpdf, 255);
3391 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
3392 $sql .=
" SET model_pdf = '".$this->db->escape($newmodelpdf).
"'";
3393 $sql .=
" WHERE rowid = ".((int) $this->
id);
3395 dol_syslog(get_class($this).
"::setDocModel", LOG_DEBUG);
3396 $resql = $this->db->query($sql);
3398 $this->model_pdf = $modelpdf;
3419 if (empty($userused)) {
3425 if (!$this->table_element) {
3426 dol_syslog(get_class($this).
"::setBankAccount was called on object with property table_element not defined", LOG_ERR);
3431 if ($fk_account < 0) {
3432 $fk_account =
'NULL';
3434 dol_syslog(get_class($this).
'::setBankAccount('.$fk_account.
')');
3436 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
3437 $sql .=
" SET fk_account = ".((int) $fk_account);
3438 $sql .=
" WHERE rowid=".((int) $this->
id);
3440 $resql = $this->db->query($sql);
3442 dol_syslog(get_class($this).
'::setBankAccount Error '.$sql.
' - '.$this->db->error());
3443 $this->error = $this->db->lasterror();
3448 $this->context[
'bankaccountupdate'] = 1;
3450 $triggerName = (empty($this->TRIGGER_PREFIX) ? strtoupper(get_class($this)) : $this->TRIGGER_PREFIX);
3451 $result = $this->call_trigger($triggerName .
'_MODIFY', $userused);
3459 $this->db->rollback();
3462 $this->fk_account = ($fk_account ==
'NULL') ?
null : $fk_account;
3463 $this->db->commit();
3481 public function line_order($renum =
false, $rowidorder =
'ASC', $fk_parent_line =
true)
3484 if (!$this->table_element_line) {
3485 dol_syslog(get_class($this).
"::line_order was called on object with property table_element_line not defined", LOG_ERR);
3488 if (!$this->fk_element) {
3489 dol_syslog(get_class($this).
"::line_order was called on object with property fk_element not defined", LOG_ERR);
3493 $fieldposition =
'rang';
3494 if (in_array($this->table_element_line, array(
'bom_bomline',
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3495 $fieldposition =
'position';
3500 $sql =
"SELECT count(rowid) FROM ".$this->db->prefix().$this->table_element_line;
3501 $sql .=
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
3503 $sql .=
" AND " . $fieldposition .
" = 0";
3506 $sql .=
" AND " . $fieldposition .
" <> 0";
3509 dol_syslog(get_class($this).
"::line_order", LOG_DEBUG);
3510 $resql = $this->db->query($sql);
3512 $row = $this->db->fetch_row($resql);
3522 $sql =
"SELECT rowid FROM ".$this->db->prefix().$this->table_element_line;
3523 $sql .=
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
3524 if ($fk_parent_line) {
3525 $sql .=
' AND fk_parent_line IS NULL';
3527 $sql .=
" ORDER BY " . $fieldposition .
" ASC, rowid " . $rowidorder;
3529 dol_syslog(get_class($this).
"::line_order search all parent lines", LOG_DEBUG);
3530 $resql = $this->db->query($sql);
3533 $num = $this->db->num_rows($resql);
3536 $row = $this->db->fetch_row($resql);
3538 if ($fk_parent_line) {
3541 if (!empty($children)) {
3542 foreach ($children as $child) {
3543 array_push($rows, $child);
3550 if (!empty($rows)) {
3551 foreach ($rows as $key => $row) {
3571 $fieldposition =
'rang';
3572 if (in_array($this->table_element_line, array(
'bom_bomline',
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3573 $fieldposition =
'position';
3578 $sql =
"SELECT rowid FROM ".$this->db->prefix().$this->table_element_line;
3579 $sql .=
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
3580 $sql .=
' AND fk_parent_line = '.((int) $id);
3581 $sql .=
" ORDER BY " . $fieldposition .
" ASC";
3583 dol_syslog(get_class($this).
"::getChildrenOfLine search children lines for line ".$id, LOG_DEBUG);
3585 $resql = $this->db->query($sql);
3586 if (!$resql || $this->db->num_rows($resql) <= 0) {
3590 while ($row = $this->db->fetch_row($resql)) {
3592 if (!empty($includealltree) && $includealltree <= 1000) {
3593 $rows = array_merge($rows, $this->
getChildrenOfLine($row[0], $includealltree + 1));
3607 public function line_up($rowid, $fk_parent_line =
true)
3610 $this->
line_order(
false,
'ASC', $fk_parent_line);
3630 $this->
line_order(
false,
'ASC', $fk_parent_line);
3651 global $hookmanager;
3652 $fieldposition =
'rang';
3653 if (in_array($this->table_element_line, array(
'bom_bomline',
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3654 $fieldposition =
'position';
3657 $sql =
"UPDATE ".$this->db->prefix().$this->table_element_line.
" SET ".$fieldposition.
" = ".((int) $rang);
3658 $sql .=
' WHERE rowid = '.((int) $rowid);
3659 if ($this->
id > 0 && !empty($this->fk_element)) {
3661 $sql .=
" AND ".$this->db->sanitize($this->fk_element).
" = ".((int) $this->
id);
3664 dol_syslog(get_class($this).
"::updateRangOfLine", LOG_DEBUG);
3665 if (!$this->db->query($sql)) {
3670 $parameters = array(
'rowid' => $rowid,
'rang' => $rang,
'fieldposition' => $fieldposition);
3672 $reshook = $hookmanager->executeHooks(
'afterRankOfLineUpdate', $parameters, $this, $action);
3686 $num = count($rows);
3687 for ($i = 0; $i < $num; $i++) {
3705 $fieldposition =
'rang';
3706 if (in_array($this->table_element_line, array(
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3707 $fieldposition =
'position';
3710 $sql =
"UPDATE ".$this->db->prefix().$this->table_element_line.
" SET ".$fieldposition.
" = ".((int) $rang);
3711 $sql .=
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
3712 $sql .=
" AND " . $fieldposition .
" = " . ((int) ($rang - 1));
3713 if (!$this->db->query($sql)) {
3714 $this->error = $this->db->lasterror();
3718 $sql =
"UPDATE ".$this->db->prefix().$this->table_element_line.
" SET ".$fieldposition.
" = ".((int) ($rang - 1));
3719 $sql .=
' WHERE rowid = '.((int) $rowid);
3720 if (!$this->db->query($sql)) {
3721 $this->error = $this->db->lasterror();
3738 if ($rang >= $max) {
3742 $fieldposition =
'rang';
3743 if (in_array($this->table_element_line, array(
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3744 $fieldposition =
'position';
3747 $sql =
"UPDATE ".$this->db->prefix().$this->table_element_line.
" SET ".$fieldposition.
" = ".((int) $rang);
3748 $sql .=
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
3749 $sql .=
" AND " . $fieldposition .
" = " . ((int) ($rang + 1));
3750 if (!$this->db->query($sql)) {
3751 $this->error = $this->db->lasterror();
3755 $sql =
"UPDATE ".$this->db->prefix().$this->table_element_line.
" SET ".$fieldposition.
" = ".((int) ($rang + 1));
3756 $sql .=
' WHERE rowid = '.((int) $rowid);
3757 if (!$this->db->query($sql)) {
3758 $this->error = $this->db->lasterror();
3773 $fieldposition =
'rang';
3774 if (in_array($this->table_element_line, array(
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3775 $fieldposition =
'position';
3778 $sql =
"SELECT " . $fieldposition .
" FROM ".$this->db->prefix().$this->table_element_line;
3779 $sql .=
" WHERE rowid = ".((int) $rowid);
3781 dol_syslog(get_class($this).
"::getRangOfLine", LOG_DEBUG);
3782 $resql = $this->db->query($sql);
3787 $row = $this->db->fetch_row($resql);
3799 $fieldposition =
'rang';
3800 if (in_array($this->table_element_line, array(
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3801 $fieldposition =
'position';
3804 $sql =
"SELECT rowid FROM ".$this->db->prefix().$this->table_element_line;
3805 $sql .=
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
3806 $sql .=
" AND " . $fieldposition .
" = ".((int) $rang);
3807 $resql = $this->db->query($sql);
3812 $row = $this->db->fetch_row($resql);
3827 if (empty($packaging) || !is_numeric($packaging) || (
float) $packaging <= 0) {
3830 $sign = ((float) $qty < 0 ? -1 : 1);
3831 $absqty = abs((
float) $qty);
3832 if ($absqty < (
float) $packaging) {
3833 return $sign * (float) $packaging;
3835 if ((
float)
price2num(fmod($absqty, (
float) $packaging),
'MS')) {
3836 $coeff = intval($absqty / (
float) $packaging) + 1;
3837 return $sign * (float)
price2num((
float) $packaging * $coeff,
'MS');
3852 $positionfield =
'rang';
3853 if (in_array($this->table_element, array(
'bom_bom',
'product_attribute'))) {
3854 $positionfield =
'position';
3857 $sql =
"SELECT max(".$positionfield.
") FROM ".$this->db->prefix().$this->table_element_line;
3858 $sql .=
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
3861 if ($fk_parent_line) {
3862 $sql .=
" AND fk_parent_line = ".((int) $fk_parent_line);
3865 dol_syslog(get_class($this).
"::line_max", LOG_DEBUG);
3866 $resql = $this->db->query($sql);
3868 $row = $this->db->fetch_row($resql);
3870 if ($fk_parent_line) {
3871 if (!empty($row[0])) {
3894 if (!$this->table_element) {
3895 dol_syslog(get_class($this).
"::update_ref_ext was called on object with property table_element not defined", LOG_ERR);
3899 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
3900 $sql .=
" SET ref_ext = '".$this->db->escape($ref_ext).
"'";
3902 $sql .=
" WHERE ".(isset($this->table_rowid) ? $this->table_rowid :
'rowid').
" = ".((
int) $this->id);
3904 dol_syslog(get_class($this).
"::update_ref_ext", LOG_DEBUG);
3905 if ($this->db->query($sql)) {
3906 $this->ref_ext = $ref_ext;
3909 $this->error = $this->db->error();
3928 if (!$this->table_element) {
3929 $this->error =
'update_note was called on object with property table_element not defined';
3930 dol_syslog(get_class($this).
"::update_note was called on object with property table_element not defined", LOG_ERR);
3933 if (!in_array($suffix, array(
'',
'_public',
'_private'))) {
3934 $this->error =
'update_note Parameter suffix must be empty, \'_private\' or \'_public\'';
3935 dol_syslog(get_class($this).
"::update_note Parameter suffix must be empty, '_private' or '_public'", LOG_ERR);
3939 $newsuffix = $suffix;
3942 if ($this->table_element ==
'product' && $newsuffix ==
'_private') {
3945 if (in_array($this->table_element, array(
'actioncomm',
'adherent',
'advtargetemailing',
'cronjob',
'establishment'))) {
3946 $fieldusermod =
"fk_user_mod";
3947 } elseif ($this->table_element ==
'ecm_files') {
3948 $fieldusermod =
"fk_user_m";
3950 $fieldusermod =
"fk_user_modif";
3952 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
3953 $sql .=
" SET note".$this->db->sanitize($newsuffix).
" = ".(!empty($note) ? (
"'".$this->db->escape($note).
"'") :
"NULL");
3954 $sql .=
", ".$this->db->sanitize($fieldusermod).
" = ".((int) $user->id);
3955 $sql .=
" WHERE rowid = ".((int) $this->
id);
3957 dol_syslog(get_class($this).
"::update_note", LOG_DEBUG);
3958 if ($this->db->query($sql)) {
3959 if ($suffix ==
'_public') {
3960 $this->note_public = $note;
3961 } elseif ($suffix ==
'_private') {
3962 $this->note_private = $note;
3964 $this->note = $note;
3965 $this->note_private = $note;
3967 if (empty($notrigger)) {
3969 switch ($this->element) {
3971 $triggerName =
'COMPANY_MODIFY';
3974 $triggerName =
'BILL_MODIFY';
3976 case 'invoice_supplier':
3977 $triggerName =
'BILL_SUPPLIER_MODIFY';
3980 $triggerName =
'BILLREC_MODIFIY';
3982 case 'expensereport':
3983 $triggerName =
'EXPENSE_REPORT_MODIFY';
3986 $triggerName = (!empty($this->TRIGGER_PREFIX) ? $this->TRIGGER_PREFIX : strtoupper($this->element)) .
'_MODIFY';
3988 $ret = $this->call_trigger($triggerName, $user);
3995 $this->error = $this->db->lasterror();
4026 public function update_price($exclspec = 0, $roundingadjust =
'auto', $nodatabaseupdate = 0, $seller =
null)
4029 global $conf, $hookmanager, $action;
4031 $parameters = array(
'exclspec' => $exclspec,
'roundingadjust' => $roundingadjust,
'nodatabaseupdate' => $nodatabaseupdate,
'seller' => $seller);
4032 $reshook = $hookmanager->executeHooks(
'updateTotalPrice', $parameters, $this, $action);
4035 } elseif ($reshook < 0) {
4040 $isElementForSupplier =
false;
4041 $roundTotalConstName =
'MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND';
4043 if ($this->element ==
'propal') {
4044 $MODULE =
"MODULE_DISALLOW_UPDATE_PRICE_PROPOSAL";
4045 } elseif ($this->element ==
'commande' || $this->element ==
'order') {
4046 $MODULE =
"MODULE_DISALLOW_UPDATE_PRICE_ORDER";
4047 } elseif ($this->element ==
'facture' || $this->element ==
'invoice') {
4048 $MODULE =
"MODULE_DISALLOW_UPDATE_PRICE_INVOICE";
4049 } elseif ($this->element ==
'facture_fourn' || $this->element ==
'supplier_invoice' || $this->element ==
'invoice_supplier' || $this->element ==
'invoice_supplier_rec') {
4050 $isElementForSupplier =
true;
4051 $MODULE =
"MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_INVOICE";
4052 } elseif ($this->element ==
'order_supplier' || $this->element ==
'supplier_order') {
4053 $isElementForSupplier =
true;
4054 $MODULE =
"MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_ORDER";
4055 } elseif ($this->element ==
'supplier_proposal') {
4056 $isElementForSupplier =
true;
4057 $MODULE =
"MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_PROPOSAL";
4059 if ($isElementForSupplier) {
4060 $roundTotalConstName =
'MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND_SUPPLIER';
4063 if (!empty($MODULE)) {
4066 foreach ($modsactivated as $mod) {
4074 include_once DOL_DOCUMENT_ROOT.
'/core/lib/price.lib.php';
4076 $forcedroundingmode = $roundingadjust;
4077 if ($forcedroundingmode ==
'auto' && isset($conf->global->{$roundTotalConstName})) {
4079 } elseif ($forcedroundingmode ==
'auto') {
4080 $forcedroundingmode =
'0';
4085 $multicurrency_tx = !empty($this->multicurrency_tx) ? $this->multicurrency_tx : 1;
4088 $fieldtva =
'total_tva';
4089 $fieldlocaltax1 =
'total_localtax1';
4090 $fieldlocaltax2 =
'total_localtax2';
4091 $fieldup =
'subprice';
4092 $base_price_type =
'HT';
4093 if ($this->element ==
'facture_fourn' || $this->element ==
'invoice_supplier') {
4097 if ($this->element ==
'invoice_supplier_rec') {
4100 if ($this->element ==
'expensereport') {
4104 $forcedroundingmode =
'0';
4105 $fieldup =
'value_unit';
4106 $base_price_type =
'TTC';
4109 $sql =
"SELECT rowid, qty, ".$this->db->sanitize($fieldup).
" as up, remise_percent,";
4110 $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,";
4111 $sql .=
' tva_tx as vatrate, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type,';
4112 $sql .=
' info_bits, product_type,';
4113 if ($this->element ==
'expensereport') {
4114 $sql .=
' comments as description';
4116 $sql .=
' description';
4118 if ($this->table_element_line ==
'facturedet') {
4119 $sql .=
', situation_percent';
4121 $sql .=
', multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc';
4122 $sql .=
" FROM ".$this->db->prefix().$this->table_element_line;
4123 $sql .=
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
4125 $product_field =
'product_type';
4126 if ($this->table_element_line ==
'contratdet') {
4127 $product_field =
'';
4129 if ($product_field) {
4130 $sql .=
" AND ".$product_field.
" <> 9";
4133 $sql .=
' ORDER by rowid';
4135 dol_syslog(get_class($this).
"::update_price", LOG_DEBUG);
4137 $resql = $this->db->query($sql);
4139 $this->total_ht = 0;
4140 $this->total_tva = 0;
4141 $this->total_localtax1 = 0;
4142 $this->total_localtax2 = 0;
4143 $this->total_ttc = 0;
4144 $total_ht_by_vats = array();
4145 $total_tva_by_vats = array();
4146 $total_ttc_by_vats = array();
4147 $this->multicurrency_total_ht = 0;
4148 $this->multicurrency_total_tva = 0;
4149 $this->multicurrency_total_ttc = 0;
4153 $num = $this->db->num_rows($resql);
4156 $obj = $this->db->fetch_object($resql);
4159 $parameters = array(
'fk_element' => $obj->rowid);
4160 $reshook = $hookmanager->executeHooks(
'changeRoundingMode', $parameters, $this, $action);
4162 if (empty($reshook) && $forcedroundingmode ==
'0') {
4164 $localtax_array = array($obj->localtax1_type, $obj->localtax1_tx, $obj->localtax2_type, $obj->localtax2_tx);
4165 $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);
4167 $diff_when_using_price_ht =
price2num((
float) $tmpcal[1] - $obj->total_tva,
'MT', 1);
4168 $diff_on_current_total =
price2num($obj->total_ttc - $obj->total_ht - $obj->total_tva - $obj->total_localtax1 - $obj->total_localtax2,
'MT', 1);
4172 if ($diff_on_current_total) {
4174 $sqlfix =
"UPDATE ".$this->db->prefix().$this->table_element_line;
4175 $sqlfix .=
" SET ".$this->db->sanitize($fieldtva).
" = ".
price2num((
float) $tmpcal[1]).
", total_ttc = ".
price2num((
float) $tmpcal[2]);
4176 $sqlfix .=
", multicurrency_total_tva = ".price2num((
float) $tmpcal[17]).
", multicurrency_total_ttc = ".
price2num((
float) $tmpcal[18]);
4177 $sqlfix .=
" WHERE rowid = ".((int) $obj->rowid);
4178 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);
4179 $resqlfix = $this->db->query($sqlfix);
4183 $obj->total_tva = $tmpcal[1];
4184 $obj->total_ttc = $tmpcal[2];
4185 $obj->multicurrency_total_tva = $tmpcal[17];
4186 $obj->multicurrency_total_ttc = $tmpcal[18];
4187 } elseif ($diff_when_using_price_ht) {
4191 if ((
float) $tmpcal[0] == (
float) $obj->total_ht) {
4194 if ($obj->description !=
'(DEPOSIT)' && !
getDolGlobalInt(
'MAIN_DISABLE_AUTOFIX_CORRUPTED_LINES_WHEN_TOTAL_DOES_NOT_MATCH_RECALCULATION_FROM_UP')) {
4198 $sqlfix =
"UPDATE ".$this->db->prefix().$this->table_element_line;
4199 $sqlfix .=
" SET ".$this->db->sanitize($fieldtva).
" = ".
price2num((
float) $tmpcal[1]).
", total_ttc = ".
price2num((
float) $tmpcal[2]);
4200 $sqlfix .=
", multicurrency_total_tva = ".price2num((
float) $tmpcal[17]).
", multicurrency_total_ttc = ".
price2num((
float) $tmpcal[18]);
4201 $sqlfix .=
" WHERE rowid = ".((int) $obj->rowid);
4203 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);
4205 $resqlfix = $this->db->query($sqlfix);
4209 $obj->total_tva = $tmpcal[1];
4210 $obj->total_ttc = $tmpcal[2];
4211 $obj->multicurrency_total_tva = $tmpcal[17];
4212 $obj->multicurrency_total_ttc = $tmpcal[18];
4218 $this->total_ht += $obj->total_ht;
4219 $this->total_tva += $obj->total_tva;
4220 $this->total_localtax1 += $obj->total_localtax1;
4221 $this->total_localtax2 += $obj->total_localtax2;
4222 $this->total_ttc += $obj->total_ttc;
4223 $this->multicurrency_total_ht += $obj->multicurrency_total_ht;
4224 $this->multicurrency_total_tva += $obj->multicurrency_total_tva;
4225 $this->multicurrency_total_ttc += $obj->multicurrency_total_ttc;
4227 if (!isset($total_ht_by_vats[$obj->vatrate])) {
4228 $total_ht_by_vats[$obj->vatrate] = 0;
4230 if (!isset($total_tva_by_vats[$obj->vatrate])) {
4231 $total_tva_by_vats[$obj->vatrate] = 0;
4233 if (!isset($total_ttc_by_vats[$obj->vatrate])) {
4234 $total_ttc_by_vats[$obj->vatrate] = 0;
4236 $total_ht_by_vats[$obj->vatrate] += $obj->total_ht;
4237 $total_tva_by_vats[$obj->vatrate] += $obj->total_tva;
4238 $total_ttc_by_vats[$obj->vatrate] += $obj->total_ttc;
4240 if ($forcedroundingmode ==
'1') {
4241 if ($base_price_type ==
'TTC') {
4242 $tmpvat =
price2num($total_ttc_by_vats[$obj->vatrate] * $obj->vatrate / (100 + $obj->vatrate),
'MT', 1);
4244 $tmpvat =
price2num($total_ht_by_vats[$obj->vatrate] * $obj->vatrate / 100,
'MT', 1);
4246 $diff =
price2num($total_tva_by_vats[$obj->vatrate] - (
float) $tmpvat,
'MT', 1);
4249 $maxdiff = (10 * pow(10, -1 *
getDolGlobalInt(
'MAIN_MAX_DECIMALS_TOT', 0)));
4250 if (abs((
float) $diff) > $maxdiff) {
4252 $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.';
4254 $this->error = $errmsg;
4259 if ($base_price_type ==
'TTC') {
4260 $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);
4261 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);
4263 $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);
4264 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);
4267 $resqlfix = $this->db->query($sqlfix);
4273 $this->total_tva = (float)
price2num($this->total_tva - (
float) $diff,
'', 1);
4274 $total_tva_by_vats[$obj->vatrate] = (float)
price2num($total_tva_by_vats[$obj->vatrate] - (
float) $diff,
'', 1);
4275 if ($base_price_type ==
'TTC') {
4276 $this->total_ht = (float)
price2num($this->total_ht + (
float) $diff,
'', 1);
4277 $total_ht_by_vats[$obj->vatrate] = (float)
price2num($total_ht_by_vats[$obj->vatrate] + (
float) $diff,
'', 1);
4279 $this->total_ttc = (float)
price2num($this->total_ttc - (
float) $diff,
'', 1);
4280 $total_ttc_by_vats[$obj->vatrate] = (float)
price2num($total_ttc_by_vats[$obj->vatrate] - (
float) $diff,
'', 1);
4290 $this->total_ttc += isset($this->revenuestamp) ? $this->revenuestamp : 0;
4292 $this->multicurrency_total_ttc += isset($this->revenuestamp) ? ($this->revenuestamp * $multicurrency_tx) : 0;
4295 if (!empty($this->situation_cycle_ref) && !empty($this->situation_counter) && $this->situation_counter > 1 && method_exists($this,
'get_prev_sits')) {
4296 '@phan-var-force Facture $this';
4297 include_once DOL_DOCUMENT_ROOT.
'/compta/facture/class/facture.class.php';
4300 $prev_sits = $this->get_prev_sits();
4302 foreach ($prev_sits as $sit) {
4303 $this->total_ht -= $sit->total_ht;
4304 $this->total_tva -= $sit->total_tva;
4305 $this->total_localtax1 -= $sit->total_localtax1;
4306 $this->total_localtax2 -= $sit->total_localtax2;
4307 $this->total_ttc -= $sit->total_ttc;
4308 $this->multicurrency_total_ht -= $sit->multicurrency_total_ht;
4309 $this->multicurrency_total_tva -= $sit->multicurrency_total_tva;
4310 $this->multicurrency_total_ttc -= $sit->multicurrency_total_ttc;
4317 $this->total_ht = (float)
price2num($this->total_ht);
4318 $this->total_tva = (float)
price2num($this->total_tva);
4319 $this->total_localtax1 = (float)
price2num($this->total_localtax1);
4320 $this->total_localtax2 = (float)
price2num($this->total_localtax2);
4321 $this->total_ttc = (float)
price2num($this->total_ttc);
4323 $this->db->free($resql);
4326 $fieldht =
'total_ht';
4328 $fieldlocaltax1 =
'localtax1';
4329 $fieldlocaltax2 =
'localtax2';
4330 $fieldttc =
'total_ttc';
4332 if (in_array($this->element, array(
'propal',
'commande',
'facture',
'facturerec',
'supplier_proposal',
'order_supplier',
'facture_fourn',
'invoice_supplier',
'invoice_supplier_rec',
'expensereport'))) {
4333 $fieldtva =
'total_tva';
4336 if (!$error && empty($nodatabaseupdate)) {
4337 $sql =
"UPDATE ".$this->db->prefix().$this->table_element.
' SET';
4338 $sql .=
" ".$this->db->sanitize($fieldht).
" = ".((float)
price2num($this->total_ht,
'MT', 1)).
",";
4339 $sql .=
" ".$this->db->sanitize($fieldtva).
" = ".((float)
price2num($this->total_tva,
'MT', 1)).
",";
4340 $sql .=
" ".$this->db->sanitize($fieldlocaltax1).
" = ".((float)
price2num($this->total_localtax1,
'MT', 1)).
",";
4341 $sql .=
" ".$this->db->sanitize($fieldlocaltax2).
" = ".((float)
price2num($this->total_localtax2,
'MT', 1)).
",";
4342 $sql .=
" ".$this->db->sanitize($fieldttc).
" = ".((float)
price2num($this->total_ttc,
'MT', 1));
4343 $sql .=
", multicurrency_total_ht = ".((float)
price2num($this->multicurrency_total_ht,
'MT', 1));
4344 $sql .=
", multicurrency_total_tva = ".((float)
price2num($this->multicurrency_total_tva,
'MT', 1));
4345 $sql .=
", multicurrency_total_ttc = ".((float)
price2num($this->multicurrency_total_ttc,
'MT', 1));
4346 $sql .=
" WHERE rowid = ".((int) $this->
id);
4348 dol_syslog(get_class($this).
"::update_price", LOG_DEBUG);
4349 $resql = $this->db->query($sql);
4353 $this->error = $this->db->lasterror();
4354 $this->errors[] = $this->db->lasterror();
4359 $this->db->commit();
4362 $this->db->rollback();
4382 public function add_object_linked($origin =
null, $origin_id =
null, $f_user =
null, $notrigger = 0)
4385 global $user, $hookmanager, $action;
4387 if (empty($this->origin_type) && !empty($this->origin)) {
4388 $this->origin_type = $this->origin;
4390 $origin = (!empty($origin) ? $origin : $this->origin_type);
4391 $origin_id = (!empty($origin_id) ? $origin_id : $this->origin_id);
4392 $f_user = isset($f_user) ? $f_user : $user;
4395 if ($origin ==
'order') {
4396 $origin =
'commande';
4398 if ($origin ==
'invoice') {
4399 $origin =
'facture';
4401 if ($origin ==
'invoice_template') {
4402 $origin =
'facturerec';
4404 if ($origin ==
'supplierorder') {
4405 $origin =
'order_supplier';
4409 $targettype = $this->getElementType();
4411 $parameters = array(
'targettype' => $targettype);
4413 $reshook = $hookmanager->executeHooks(
'setLinkedObjectSourceTargetType', $parameters, $this, $action);
4415 if (!empty($hookmanager->resArray[
'targettype'])) {
4416 $targettype = $hookmanager->resArray[
'targettype'];
4423 $sql =
"INSERT INTO " . $this->db->prefix() .
"element_element (";
4424 $sql .=
"fk_source";
4425 $sql .=
", sourcetype";
4426 $sql .=
", fk_target";
4427 $sql .=
", targettype";
4428 $sql .=
") VALUES (";
4429 $sql .= ((int) $origin_id);
4430 $sql .=
", '" . $this->db->escape($origin) .
"'";
4431 $sql .=
", " . ((int) $this->
id);
4432 $sql .=
", '" . $this->db->escape($targettype) .
"'";
4435 dol_syslog(get_class($this) .
"::add_object_linked", LOG_DEBUG);
4436 if ($this->db->query($sql)) {
4439 $this->context[
'link_origin'] = $origin;
4440 $this->context[
'link_origin_id'] = $origin_id;
4442 $result = $this->call_trigger(
'OBJECT_LINK_INSERT', $f_user);
4449 $this->error = $this->db->lasterror();
4454 $this->db->commit();
4457 $this->db->rollback();
4471 $coreModule = array(
'knowledgemanagement',
'partnership',
'workstation',
'ticket',
'recruitment',
'eventorganization',
'asset');
4473 return ((!empty($this->module) && !in_array($this->module, $coreModule)) ? $this->module.
'_' :
'').$this->element;
4499 public function fetchObjectLinked($sourceid =
null, $sourcetype =
'', $targetid =
null, $targettype =
'', $clause =
'OR', $alsosametype = 1, $orderby =
'sourcetype', $loadalsoobjects = 1)
4501 global $hookmanager, $action;
4506 if ($this->
id > 0 && !empty($this->linkedObjectsFullLoaded[$this->
id])) {
4510 $this->linkedObjectsIds = array();
4511 $this->linkedObjects = array();
4514 $parameters = array(
4515 'sourceid' => $sourceid,
4516 'sourcetype' => $sourcetype,
4517 'targetid' => $targetid,
4518 'targettype' => $targettype,
4519 'clause' => $clause,
4520 'alsosametype' => $alsosametype,
4521 'orderby' => $orderby,
4522 'loadalsoobjects' => $loadalsoobjects
4524 $reshook = $hookmanager->executeHooks(
'fetchObjectLinked', $parameters, $this, $action);
4529 $justsource =
false;
4530 $justtarget =
false;
4531 $withtargettype =
false;
4532 $withsourcetype =
false;
4535 if (is_object($hookmanager)) {
4536 $parameters = array(
'sourcetype' => $sourcetype,
'sourceid' => $sourceid,
'targettype' => $targettype,
'targetid' => $targetid);
4537 $reshook = $hookmanager->executeHooks(
'setLinkedObjectSourceTargetType', $parameters, $this, $action);
4539 if (!empty($hookmanager->resArray[
'sourcetype'])) {
4540 $sourcetype = $hookmanager->resArray[
'sourcetype'];
4542 if (!empty($hookmanager->resArray[
'sourceid'])) {
4543 $sourceid = $hookmanager->resArray[
'sourceid'];
4545 if (!empty($hookmanager->resArray[
'targettype'])) {
4546 $targettype = $hookmanager->resArray[
'targettype'];
4548 if (!empty($hookmanager->resArray[
'targetid'])) {
4549 $targetid = $hookmanager->resArray[
'targetid'];
4554 if (!empty($sourceid) && !empty($sourcetype) && empty($targetid)) {
4556 if (!empty($targettype)) {
4557 $withtargettype =
true;
4560 if (!empty($targetid) && !empty($targettype) && empty($sourceid)) {
4562 if (!empty($sourcetype)) {
4563 $withsourcetype =
true;
4567 $sourceid = (!empty($sourceid) ? $sourceid :
$this->id);
4568 $targetid = (!empty($targetid) ? $targetid :
$this->id);
4569 $sourcetype = (!empty($sourcetype) ? $sourcetype : $this->getElementType());
4570 $targettype = (!empty($targettype) ? $targettype : $this->getElementType());
4579 $sql =
"SELECT rowid, fk_source, sourcetype, fk_target, targettype";
4580 $sql .=
" FROM ".$this->db->prefix().
"element_element";
4582 if ($justsource || $justtarget) {
4584 $sql .=
"fk_source = ".((int) $sourceid).
" AND sourcetype = '".$this->db->escape($sourcetype).
"'";
4585 if ($withtargettype) {
4586 $sql .=
" AND targettype = '".$this->db->escape($targettype).
"'";
4588 } elseif ($justtarget) {
4589 $sql .=
"fk_target = ".((int) $targetid).
" AND targettype = '".$this->db->escape($targettype).
"'";
4590 if ($withsourcetype) {
4591 $sql .=
" AND sourcetype = '".$this->db->escape($sourcetype).
"'";
4595 $sql .=
"(fk_source = ".((int) $sourceid).
" AND sourcetype = '".$this->db->escape($sourcetype).
"')";
4596 $sql .=
" ".$this->db->sanitize($clause).
" (fk_target = ".((int) $targetid).
" AND targettype = '".$this->db->escape($targettype).
"')";
4597 if ($loadalsoobjects && $this->
id > 0 && $sourceid == $this->
id && $sourcetype == $this->element && $targetid == $this->
id && $targettype == $this->element && $clause ==
'OR') {
4598 $this->linkedObjectsFullLoaded[
$this->id] =
true;
4601 $sql .=
" ORDER BY ".$orderby;
4603 dol_syslog(get_class($this).
"::fetchObjectLink", LOG_DEBUG);
4604 $resql = $this->db->query($sql);
4606 $num = $this->db->num_rows($resql);
4609 $obj = $this->db->fetch_object($resql);
4610 if ($justsource || $justtarget) {
4612 $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
4613 } elseif ($justtarget) {
4614 $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
4617 if ($obj->fk_source == $sourceid && $obj->sourcetype == $sourcetype) {
4618 $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
4620 if ($obj->fk_target == $targetid && $obj->targettype == $targettype) {
4621 $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
4627 if (!empty($this->linkedObjectsIds)) {
4628 $tmparray = $this->linkedObjectsIds;
4629 foreach ($tmparray as $objecttype => $objectids) {
4631 $element = $element_properties[
'element'];
4632 $classPath = $element_properties[
'classpath'];
4633 $classFile = $element_properties[
'classfile'];
4634 $className = $element_properties[
'classname'];
4635 $module = $element_properties[
'module'];
4638 if (
isModEnabled($module) && (($element != $this->element) || $alsosametype)) {
4639 if ($loadalsoobjects && (is_numeric($loadalsoobjects) || ($loadalsoobjects === $objecttype))) {
4641 if (class_exists($className)) {
4642 foreach ($objectids as $i => $objectid) {
4643 $object =
new $className($this->db);
4644 '@phan-var-force CommonObject $object';
4645 $ret =
$object->fetch($objectid);
4647 $this->linkedObjects[$objecttype][$i] =
$object;
4653 unset($this->linkedObjectsIds[$objecttype]);
4672 if ($this->
id > 0 && !empty($this->linkedObjectsFullLoaded[$this->
id])) {
4673 unset($this->linkedObjectsFullLoaded[$this->
id]);
4691 public function updateObjectLinked($sourceid =
null, $sourcetype =
'', $targetid =
null, $targettype =
'', $f_user =
null, $notrigger = 0)
4694 $updatesource =
false;
4695 $updatetarget =
false;
4696 $f_user = isset($f_user) ? $f_user : $user;
4698 if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) {
4699 $updatesource =
true;
4700 } elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) {
4701 $updatetarget =
true;
4707 $sql =
"UPDATE " . $this->db->prefix() .
"element_element SET ";
4708 if ($updatesource) {
4709 $sql .=
"fk_source = " . ((int) $sourceid);
4710 $sql .=
", sourcetype = '" . $this->db->escape($sourcetype) .
"'";
4711 $sql .=
" WHERE fk_target = " . ((int) $this->
id);
4712 $sql .=
" AND targettype = '" . $this->db->escape($this->element) .
"'";
4713 } elseif ($updatetarget) {
4714 $sql .=
"fk_target = " . ((int) $targetid);
4715 $sql .=
", targettype = '" . $this->db->escape($targettype) .
"'";
4716 $sql .=
" WHERE fk_source = " . ((int) $this->
id);
4717 $sql .=
" AND sourcetype = '" . $this->db->escape($this->element) .
"'";
4720 dol_syslog(get_class($this) .
"::updateObjectLinked", LOG_DEBUG);
4721 if ($this->db->query($sql)) {
4724 $this->context[
'link_source_id'] = $sourceid;
4725 $this->context[
'link_source_type'] = $sourcetype;
4726 $this->context[
'link_target_id'] = $targetid;
4727 $this->context[
'link_target_type'] = $targettype;
4729 $result = $this->call_trigger(
'OBJECT_LINK_MODIFY', $f_user);
4736 $this->error = $this->db->lasterror();
4741 $this->db->commit();
4744 $this->db->rollback();
4762 public function deleteObjectLinked($sourceid =
null, $sourcetype =
'', $targetid =
null, $targettype =
'', $rowid = 0, $f_user =
null, $notrigger = 0)
4765 $deletesource =
false;
4766 $deletetarget =
false;
4767 $f_user = isset($f_user) ? $f_user : $user;
4769 if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) {
4770 $deletesource =
true;
4771 } elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) {
4772 $deletetarget =
true;
4775 $element = $this->getElementType();
4776 $sourceid = (!empty($sourceid) ? $sourceid :
$this->id);
4777 $sourcetype = (!empty($sourcetype) ? $sourcetype : $element);
4778 $targetid = (!empty($targetid) ? $targetid :
$this->id);
4779 $targettype = (!empty($targettype) ? $targettype : $element);
4785 $this->context[
'link_id'] = $rowid;
4786 $this->context[
'link_source_id'] = $sourceid;
4787 $this->context[
'link_source_type'] = $sourcetype;
4788 $this->context[
'link_target_id'] = $targetid;
4789 $this->context[
'link_target_type'] = $targettype;
4791 $result = $this->call_trigger(
'OBJECT_LINK_DELETE', $f_user);
4799 $sql =
"DELETE FROM " . $this->db->prefix() .
"element_element";
4802 $sql .=
" rowid = " . ((int) $rowid);
4804 if ($deletesource) {
4805 $sql .=
" fk_source = " . ((int) $sourceid) .
" AND sourcetype = '" . $this->db->escape($sourcetype) .
"'";
4806 $sql .=
" AND fk_target = " . ((int) $this->
id) .
" AND targettype = '" . $this->db->escape($element) .
"'";
4807 } elseif ($deletetarget) {
4808 $sql .=
" fk_target = " . ((int) $targetid) .
" AND targettype = '" . $this->db->escape($targettype) .
"'";
4809 $sql .=
" AND fk_source = " . ((int) $this->
id) .
" AND sourcetype = '" . $this->db->escape($element) .
"'";
4811 $sql .=
" (fk_source = " . ((int) $this->
id) .
" AND sourcetype = '" . $this->db->escape($element) .
"')";
4813 $sql .=
" (fk_target = " . ((int) $this->
id) .
" AND targettype = '" . $this->db->escape($element) .
"')";
4817 dol_syslog(get_class($this) .
"::deleteObjectLinked", LOG_DEBUG);
4818 if (!$this->db->query($sql)) {
4819 $this->error = $this->db->lasterror();
4820 $this->errors[] = $this->error;
4826 $this->db->commit();
4829 $this->db->rollback();
4845 if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
4848 if (!preg_match(
'/^[_a-zA-Z0-9]+$/', $field_select)) {
4849 dol_syslog(
'Invalid value $field_select for parameter '.$field_select.
' in call to getAllItemsLinkedByObjectID(). Must be a single field name.', LOG_ERR);
4854 $sql =
"SELECT ".$field_select.
" FROM ".$db->prefix().$table_element.
" WHERE ".$field_where.
" = ".((int) $fk_object_where);
4855 $resql = $db->query($sql);
4858 if (!empty($resql)) {
4859 while ($res = $db->fetch_object($resql)) {
4860 $TRes[] = $res->{$field_select};
4877 if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
4883 $sql =
"SELECT COUNT(*) as nb FROM ".$db->prefix().$table_element.
" WHERE ".$field_where.
" = ".((int) $fk_object_where);
4884 $resql = $db->query($sql);
4887 $res = $db->fetch_object($resql);
4906 if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
4912 $sql =
"DELETE FROM ".$db->prefix().$table_element.
" WHERE ".$field_where.
" = ".((int) $fk_object_where);
4913 $resql = $db->query($sql);
4915 if (empty($resql)) {
4933 public function setStatut($status, $elementId =
null, $elementType =
'', $trigkey =
'', $fieldstatus =
'')
4937 $savElementId = $elementId;
4939 $elementId = (!empty($elementId) ? $elementId :
$this->id);
4940 $elementTable = (!empty($elementType) ? $elementType : $this->table_element);
4944 if (empty($fieldstatus)) {
4945 if ($elementTable ==
'facture_rec') {
4946 $fieldstatus =
"suspended";
4948 if ($elementTable ==
'mailing') {
4949 $fieldstatus =
"statut";
4951 if ($elementTable ==
'cronjob') {
4952 $fieldstatus =
"status";
4954 if ($elementTable ==
'user') {
4955 $fieldstatus =
"statut";
4957 if ($elementTable ==
'expensereport') {
4958 $fieldstatus =
"fk_statut";
4960 if ($elementTable ==
'receptiondet_batch') {
4961 $fieldstatus =
"status";
4963 if ($elementTable ==
'prelevement_bons') {
4964 $fieldstatus =
"statut";
4966 if (isset($this->fields) && is_array($this->fields) && array_key_exists(
'status', $this->fields)) {
4967 $fieldstatus =
'status';
4970 if (empty($fieldstatus)) {
4971 $fieldstatus =
'fk_statut';
4975 $sql =
"UPDATE ".$this->db->prefix().$this->db->sanitize($elementTable);
4976 $sql .=
" SET ".$this->db->sanitize($fieldstatus).
" = ".((int) $status);
4979 if ($status == 1 && in_array($elementTable, array(
'expensereport',
'inventory'))) {
4980 $sql .=
", fk_user_valid = ".((int) $user->id);
4982 if ($status == 1 && in_array($elementTable, array(
'expensereport'))) {
4983 $sql .=
", date_valid = '".$this->db->idate(
dol_now()).
"'";
4985 if ($status == 1 && in_array($elementTable, array(
'inventory'))) {
4986 $sql .=
", date_validation = '".$this->db->idate(
dol_now()).
"'";
4988 $sql .=
" WHERE rowid = ".((int) $elementId);
4989 $sql .=
" AND ".$this->db->sanitize($fieldstatus).
" <> ".((int) $status);
4991 dol_syslog(get_class($this).
"::setStatut", LOG_DEBUG);
4992 $resql = $this->db->query($sql);
4996 $nb_rows_affected = $this->db->affected_rows($resql);
4998 if ($nb_rows_affected > 0) {
4999 if (empty($trigkey)) {
5001 if ($this->element ==
'supplier_proposal' && $status == 2) {
5002 $trigkey =
'SUPPLIER_PROPOSAL_SIGN';
5004 if ($this->element ==
'supplier_proposal' && $status == 3) {
5005 $trigkey =
'SUPPLIER_PROPOSAL_REFUSE';
5007 if ($this->element ==
'supplier_proposal' && $status == 4) {
5008 $trigkey =
'SUPPLIER_PROPOSAL_CLOSE';
5010 if ($this->element ==
'fichinter' && $status == 3) {
5011 $trigkey =
'FICHINTER_CLASSIFY_DONE';
5013 if ($this->element ==
'fichinter' && $status == 2) {
5014 $trigkey =
'FICHINTER_CLASSIFY_BILLED';
5016 if ($this->element ==
'fichinter' && $status == 1) {
5017 $trigkey =
'FICHINTER_CLASSIFY_UNBILLED';
5021 $this->context = array_merge($this->context, array(
'newstatus' => $status));
5023 if ($trigkey && $trigkey !=
'none') {
5027 $result = $this->call_trigger($trigkey, $user);
5038 $this->db->commit();
5040 if (empty($savElementId)) {
5042 if ($fieldstatus ==
'dispute_status') {
5043 $this->dispute_status = $status;
5044 } elseif ($fieldstatus ==
'tosell') {
5046 } elseif ($fieldstatus ==
'tobuy') {
5047 $this->status_buy = $status;
5048 } elseif ($fieldstatus ==
'tobatch') {
5049 $this->status_batch = $status;
5057 $this->db->rollback();
5058 dol_syslog(get_class($this).
"::setStatut ".$this->error, LOG_ERR);
5062 $this->error = $this->db->lasterror();
5063 $this->db->rollback();
5078 if (empty(
$id) && empty($ref)) {
5088 $sql =
"SELECT rowid, canvas";
5089 $sql .=
" FROM ".$this->db->prefix().$this->table_element;
5090 $sql .=
" WHERE entity IN (".getEntity($this->element).
")";
5092 $sql .=
" AND rowid = ".((int)
$id);
5095 $sql .=
" AND ref = '".$this->db->escape($ref).
"'";
5098 $resql = $this->db->query($sql);
5100 $obj = $this->db->fetch_object($resql);
5102 $this->canvas = $obj->canvas;
5122 $sql =
"SELECT special_code FROM ".$this->db->prefix().$this->table_element_line;
5123 $sql .=
" WHERE rowid = ".((int) $lineid);
5124 $resql = $this->db->query($sql);
5126 $row = $this->db->fetch_row($resql);
5127 return (!empty($row[0]) ? $row[0] : 0);
5150 if (!isset($this->childtables) || !is_array($this->childtables) || count($this->childtables) == 0) {
5151 dol_print_error(
null,
'Called isObjectUsed on a class with property this->childtables not defined');
5155 $arraytoscan = $this->childtables;
5157 $tmparray = array_keys($this->childtables);
5158 if (is_numeric($tmparray[0])) {
5159 $arraytoscan = array_flip($this->childtables);
5164 foreach ($arraytoscan as $table => $element) {
5168 if (isset($element[
'enabled']) && !empty($element[
'enabled'])) {
5169 $enabled = (int)
dol_eval((
string) $element[
'enabled'], 1);
5170 if (empty($enabled)) {
5176 $sql =
"SELECT COUNT(*) as nb";
5177 $sql .=
" FROM ".$this->db->prefix().$table.
" as c";
5178 if (!empty($element[
'parent']) && !empty($element[
'parentkey'])) {
5179 $sql .=
", ".$this->db->prefix().$element[
'parent'].
" as p";
5181 if (!empty($element[
'fk_element'])) {
5182 $sql .=
" WHERE c.".$element[
'fk_element'].
" = ".((int)
$id);
5184 $sql .=
" WHERE c.".$this->fk_element.
" = ".((int)
$id);
5186 if (!empty($element[
'parent']) && !empty($element[
'parentkey'])) {
5187 $sql .=
" AND c.".$element[
'parentkey'].
" = p.rowid";
5189 if (!empty($element[
'parent']) && !empty($element[
'parenttypefield']) && !empty($element[
'parenttypevalue'])) {
5190 $sql .=
" AND c.".$element[
'parenttypefield'].
" = '".$this->db->escape($element[
'parenttypevalue']).
"'";
5192 if (!empty($entity)) {
5193 if (!empty($element[
'parent']) && !empty($element[
'parentkey'])) {
5194 $sql .=
" AND p.entity = ".((int) $entity);
5196 $sql .=
" AND c.entity = ".((int) $entity);
5200 $resql = $this->db->query($sql);
5202 $obj = $this->db->fetch_object($resql);
5204 $langs->load(
"errors");
5206 $haschild += $obj->nb;
5207 if (is_numeric($element)) {
5208 $this->errors[] = $langs->transnoentitiesnoconv(
"ErrorRecordHasAtLeastOneChildOfType", method_exists($this,
'getNomUrl') ? $this->getNomUrl() : $this->ref, $table);
5209 } elseif (is_string($element)) {
5210 $this->errors[] = $langs->transnoentitiesnoconv(
"ErrorRecordHasAtLeastOneChildOfType", method_exists($this,
'getNomUrl') ? $this->getNomUrl() : $this->ref, $langs->transnoentitiesnoconv($element));
5212 $this->errors[] = $langs->transnoentitiesnoconv(
"ErrorRecordHasAtLeastOneChildOfType", method_exists($this,
'getNomUrl') ? $this->getNomUrl() : $this->ref, $langs->transnoentitiesnoconv($element[
'name']));
5217 $this->errors[] = $this->db->lasterror();
5221 if ($haschild > 0) {
5222 $this->errors[] =
"ErrorRecordHasChildren";
5239 foreach ($this->lines as $key => $val) {
5241 if ($predefined == -1) {
5244 if ($predefined == 1 && $val->fk_product > 0) {
5247 if ($predefined == 0 && $val->fk_product <= 0) {
5250 if ($predefined == 2 && $val->fk_product > 0 && $val->product_type == 0) {
5253 if ($predefined == 3 && $val->fk_product > 0 && $val->product_type == 1) {
5260 dol_syslog(get_class($this).
'::hasProductsOrServices we found '.$nb.
' qualified lines of products/servcies');
5271 if (!empty($this->table_element_line) && ($this->table_element_line !=
'expeditiondet')) {
5272 $total_discount = 0.00;
5274 $sql =
"SELECT subprice as pu_ht, qty, remise_percent, total_ht";
5275 $sql .=
" FROM ".$this->db->prefix().$this->table_element_line;
5276 $sql .=
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
5278 dol_syslog(get_class($this).
'::getTotalDiscount', LOG_DEBUG);
5279 $resql = $this->db->query($sql);
5281 $num = $this->db->num_rows($resql);
5284 $obj = $this->db->fetch_object($resql);
5286 $pu_ht = $obj->pu_ht;
5288 $total_ht = $obj->total_ht;
5290 $total_discount_line = (float)
price2num(($pu_ht * $qty) - $total_ht,
'MT');
5291 $total_discount += $total_discount_line;
5298 return (
float)
price2num($total_discount);
5320 if (empty($this->lines)) {
5321 return array(
'weight' => $totalWeight,
'volume' => $totalVolume,
'ordered' => $totalOrdered,
'toship' => $totalToShip);
5324 foreach ($this->lines as $line) {
5325 if (isset($line->qty_asked)) {
5326 $totalOrdered += $line->qty_asked;
5328 if (isset($line->qty_shipped)) {
5329 $totalToShip += $line->qty_shipped;
5330 } elseif ($line->element ==
'commandefournisseurdispatch' && isset($line->qty)) {
5331 if (empty($totalToShip)) {
5334 $totalToShip += $line->qty;
5338 if ($this->element ==
'shipping') {
5340 $qty = $line->qty_shipped ? $line->qty_shipped : 0;
5342 $qty = $line->qty ? $line->qty : 0;
5345 $weight = !empty($line->weight) ? $line->weight : 0;
5346 ($weight == 0 && !empty($line->product->weight)) ? $weight = $line->product->weight : 0;
5347 $volume = !empty($line->volume) ? $line->volume : 0;
5348 ($volume == 0 && !empty($line->product->volume)) ? $volume = $line->product->volume : 0;
5350 $weight_units = !empty($line->weight_units) ? $line->weight_units : 0;
5351 ($weight_units == 0 && !empty($line->product->weight_units)) ? $weight_units = $line->product->weight_units : 0;
5352 $volume_units = !empty($line->volume_units) ? $line->volume_units : 0;
5353 ($volume_units == 0 && !empty($line->product->volume_units)) ? $volume_units = $line->product->volume_units : 0;
5357 if (!empty($weight_units)) {
5358 $weightUnit = $weight_units;
5360 if (!empty($volume_units)) {
5361 $volumeUnit = $volume_units;
5364 if (empty($totalWeight)) {
5367 if (empty($totalVolume)) {
5372 if ($weight_units < 50) {
5373 $trueWeightUnit = pow(10, $weightUnit);
5374 $totalWeight += $weight * $qty * $trueWeightUnit;
5376 if ($weight_units == 99) {
5378 $trueWeightUnit = 0.45359237;
5379 $totalWeight += $weight * $qty * $trueWeightUnit;
5380 } elseif ($weight_units == 98) {
5382 $trueWeightUnit = 0.0283495;
5383 $totalWeight += $weight * $qty * $trueWeightUnit;
5385 $totalWeight += $weight * $qty;
5388 if ($volume_units < 50) {
5390 $trueVolumeUnit = pow(10, $volumeUnit);
5392 $totalVolume += $volume * $qty * $trueVolumeUnit;
5394 $totalVolume += $volume * $qty;
5398 return array(
'weight' => $totalWeight,
'volume' => $totalVolume,
'ordered' => $totalOrdered,
'toship' => $totalToShip);
5411 $extraparams = (!empty($this->extraparams) ? json_encode($this->extraparams) :
null);
5412 $extraparams =
dol_trunc($extraparams, 250);
5414 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
5415 $sql .=
" SET extraparams = ".(!empty($extraparams) ?
"'".$this->db->escape($extraparams).
"'" :
"null");
5416 $sql .=
" WHERE rowid = ".((int) $this->
id);
5418 dol_syslog(get_class($this).
"::setExtraParameters", LOG_DEBUG);
5419 $resql = $this->db->query($sql);
5421 $this->error = $this->db->lasterror();
5422 $this->db->rollback();
5425 $this->db->commit();
5448 global $conf, $user, $langs,
$object, $hookmanager, $extrafields, $form;
5451 if (!is_object($extrafields)) {
5452 require_once DOL_DOCUMENT_ROOT.
'/core/class/extrafields.class.php';
5455 $extrafields->fetch_name_optionals_label($this->table_element_line);
5460 $dirtpls = array_merge($conf->modules_parts[
'tpl'], array($defaulttpldir));
5461 foreach ($dirtpls as $module => $reldir) {
5462 if (!empty($module)) {
5465 $tpl = DOL_DOCUMENT_ROOT.$reldir.
'/objectline_create.tpl.php';
5468 if (empty($conf->file->strict_mode)) {
5469 $res = @include $tpl;
5471 $res = include $tpl;
5498 public function printObjectLines($action, $seller, $buyer, $selected = 0, $dateSelector = 0, $defaulttpldir =
'/core/tpl')
5500 global $conf, $hookmanager, $langs, $user, $form, $extrafields,
$object;
5502 global $inputalsopricewithtax, $usemargins, $disableedit, $disablemove, $disableremove, $outputalsopricetotalwithtax;
5506 if (
isModEnabled(
'margin') && !empty($this->element) && in_array($this->element, array(
'facture',
'facturerec',
'propal',
'commande'))) {
5510 $num = count($this->lines);
5513 if (!is_object($extrafields)) {
5514 require_once DOL_DOCUMENT_ROOT.
'/core/class/extrafields.class.php';
5517 $extrafields->fetch_name_optionals_label($this->table_element_line);
5519 if (method_exists($this,
'loadExpeditions')) {
5521 $this->loadExpeditions();
5524 $parameters = array();
5525 $reshook = $hookmanager->executeHooks(
'printObjectLinesBlock', $parameters, $this, $action);
5526 if (empty($reshook)) {
5527 $parameters = array(
'num' => $num,
'dateSelector' => $dateSelector,
'seller' => $seller,
'buyer' => $buyer,
'selected' => $selected,
'table_element_line' => $this->table_element_line);
5528 $reshook = $hookmanager->executeHooks(
'printObjectLineTitle', $parameters, $this, $action);
5529 if (empty($reshook)) {
5533 $dirtpls = array_merge($conf->modules_parts[
'tpl'], array($defaulttpldir));
5534 foreach ($dirtpls as $module => $reldir) {
5536 if (!empty($module)) {
5539 $tpl = DOL_DOCUMENT_ROOT.$reldir.
'/objectline_title.tpl.php';
5541 if (file_exists($tpl)) {
5542 if (empty($conf->file->strict_mode)) {
5543 $res = @include $tpl;
5545 $res = include $tpl;
5556 print
"<!-- begin printObjectLines() -->\n";
5557 foreach ($this->lines as $line) {
5561 if (is_object($hookmanager)) {
5562 if (empty($line->fk_parent_line)) {
5563 $parameters = array(
'line' => $line,
'num' => $num,
'i' => $i,
'dateSelector' => $dateSelector,
'seller' => $seller,
'buyer' => $buyer,
'selected' => $selected,
'table_element_line' => $line->table_element,
'defaulttpldir' => $defaulttpldir);
5564 $reshook = $hookmanager->executeHooks(
'printObjectLine', $parameters, $this, $action);
5566 $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);
5567 $reshook = $hookmanager->executeHooks(
'printObjectSubLine', $parameters, $this, $action);
5570 if (empty($reshook)) {
5571 $this->printObjectLine($action, $line,
'', $num, $i, $dateSelector, $seller, $buyer, $selected, $extrafields, $defaulttpldir);
5576 print
"<!-- end printObjectLines() -->\n";
5597 public function printObjectLine($action, $line, $var, $num, $i, $dateSelector, $seller, $buyer, $selected = 0, $extrafields =
null, $defaulttpldir =
'/core/tpl')
5599 global $conf, $langs, $user,
$object, $hookmanager;
5601 global $disableedit, $disablemove, $disableremove;
5608 if ($action !=
'editline' || $selected != $line->id) {
5610 if (!empty($line->fk_product) && $line->fk_product > 0) {
5611 $product_static =
new Product($this->db);
5612 $product_static->fetch($line->fk_product);
5614 $product_static->ref = $line->ref;
5615 $product_static->label = !empty($line->label) ? $line->label :
"";
5617 $text = $product_static->getNomUrl(1);
5622 if (property_exists($this,
'socid') && !empty($this->socid) && !is_object($this->thirdparty)) {
5623 dol_print_error(
null,
'Error: Method printObjectLine was called on an object and object->fetch_thirdparty was not done before');
5627 $prod =
new Product($this->db);
5628 $prod->fetch($line->fk_product);
5630 $outputlangs = $langs;
5632 if (empty($newlang) &&
GETPOST(
'lang_id',
'aZ09')) {
5633 $newlang =
GETPOST(
'lang_id',
'aZ09');
5635 if (
getDolGlobalString(
'PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE') && empty($newlang) && is_object($this->thirdparty)) {
5636 $newlang = $this->thirdparty->default_lang;
5638 if (!empty($newlang)) {
5639 $outputlangs =
new Translate(
"", $conf);
5640 $outputlangs->setDefaultLang($newlang);
5643 $label = (!empty($prod->multilangs[$outputlangs->defaultlang][
"label"])) ? $prod->multilangs[$outputlangs->defaultlang][
"label"] : $line->product_label;
5645 $label = $line->product_label;
5648 $text .=
' - '.(!empty($line->label) ? $line->label : $label);
5649 $description .= (
getDolGlobalInt(
'PRODUIT_DESC_IN_FORM_ACCORDING_TO_DEVICE') ?
'' : (!empty($line->description) ?
dol_htmlentitiesbr($line->description) :
''));
5653 if (empty((
float) $line->subprice_ttc) && $line->qty) {
5655 if ($line->remise_percent != 100) {
5656 $line->subprice_ttc = (float)
price2num($line->total_ttc / $line->qty / (1 - $line->remise_percent / 100),
'MU');
5659 $line->subprice_ttc = (float)
price2num((!empty($line->subprice) ? $line->subprice : 0) * (1 + ((!empty($line->tva_tx) ? $line->tva_tx : 0) / 100)),
'MU');
5662 $line->pu_ttc = $line->subprice_ttc;
5669 if (isset($this->expeditions[$line->id])) {
5670 $qty_shipped = $this->expeditions[$line->id];
5672 $disableedit = ($qty_shipped > 0) && ($qty_shipped >= $line->qty);
5674 $dirtpls = array_merge($conf->modules_parts[
'tpl'], array($defaulttpldir));
5675 foreach ($dirtpls as $module => $reldir) {
5677 if (!empty($module)) {
5680 $tpl = DOL_DOCUMENT_ROOT.$reldir.
'/objectline_view.tpl.php';
5683 if (file_exists($tpl)) {
5684 if (empty($conf->file->strict_mode)) {
5685 $res = @include $tpl;
5687 $res = include $tpl;
5697 if ($this->
status == 0 && $action ==
'editline' && $selected == $line->id) {
5698 $label = (!empty($line->label) ? $line->label : (($line->fk_product > 0) ? $line->product_label :
''));
5700 $line->subprice_ttc = (float)
price2num($line->subprice * (1 + ($line->tva_tx / 100)),
'MU');
5701 $line->pu_ttc = $line->subprice_ttc;
5706 $dirtpls = array_merge($conf->modules_parts[
'tpl'], array($defaulttpldir));
5707 foreach ($dirtpls as $module => $reldir) {
5708 if (!empty($module)) {
5711 $tpl = DOL_DOCUMENT_ROOT.$reldir.
'/objectline_edit.tpl.php';
5714 if (empty($conf->file->strict_mode)) {
5715 $res = @include $tpl;
5717 $res = include $tpl;
5742 global $langs, $hookmanager, $form, $action;
5744 print
'<!-- printOriginLinesList '.get_class($this).
' -->'.
"\n";
5745 print
'<tr class="liste_titre">';
5746 print
'<td class="linecolref">'.$langs->trans(
'Ref').
'</td>';
5747 print
'<td class="linecoldescription">'.$langs->trans(
'Description').
'</td>';
5748 print
'<td class="linecolvat right">'.$langs->trans(
'VATRate').
'</td>';
5749 print
'<td class="linecoluht right">'.$langs->trans(
'PriceUHT').
'</td>';
5751 print
'<td class="linecoluht_currency right">'.$langs->trans(
'PriceUHTCurrency').
'</td>';
5753 print
'<td class="linecolqty right">'.$langs->trans(
'Qty').
'</td>';
5755 print
'<td class="linecoluseunit left">'.$langs->trans(
'Unit').
'</td>';
5757 print
'<td class="linecoldiscount right">'.$langs->trans(
'ReductionShort').
'</td>';
5758 print
'<td class="linecolht right">'.$langs->trans(
'TotalHT').
'</td>';
5759 print
'<td class="center">';
5760 print $form->showCheckAddButtons(
'checkforselect', 1);
5765 if (!empty($this->lines)) {
5766 foreach ($this->lines as $line) {
5769 if (is_object($hookmanager)) {
5770 $parameters = array(
'line' => $line,
'i' => $i,
'restrictlist' => $restrictlist,
'selectedLines' => $selectedLines);
5771 if (!empty($line->fk_parent_line)) {
5772 $parameters[
'fk_parent_line'] = $line->fk_parent_line;
5774 $reshook = $hookmanager->executeHooks(
'printOriginObjectLine', $parameters, $this, $action);
5776 if (empty($reshook)) {
5777 $this->printOriginLine($line,
'', $restrictlist,
'/core/tpl', $selectedLines);
5798 public function printOriginLine($line, $var, $restrictlist =
'', $defaulttpldir =
'/core/tpl', $selectedLines = array())
5800 global $langs, $conf;
5803 if (!empty($line->date_start)) {
5805 $date_start = $line->date_start;
5807 $date_start = $line->date_debut_prevue;
5808 if ($line->date_debut_reel) {
5809 $date_start = $line->date_debut_reel;
5812 if (!empty($line->date_end)) {
5814 $date_end = $line->date_end;
5816 $date_end = $line->date_fin_prevue;
5817 if ($line->date_fin_reel) {
5818 $date_end = $line->date_fin_reel;
5823 $this->tpl[
'id'] = $line->id;
5825 $this->tpl[
'label'] =
'';
5826 if (!empty($line->fk_parent_line)) {
5827 $this->tpl[
'label'] .=
img_picto(
'',
'rightarrow.png');
5830 if (((
int) $line->info_bits & 2) == 2) {
5832 if (property_exists($this,
'socid')) {
5833 $discount->fk_soc = $this->socid;
5834 $discount->socid = $this->socid;
5836 $this->tpl[
'label'] .= $discount->getNomUrl(0,
'discount');
5837 } elseif (!empty($line->fk_product)) {
5838 $productstatic =
new Product($this->db);
5839 $productstatic->id = $line->fk_product;
5840 $productstatic->ref = $line->ref;
5841 $productstatic->type = $line->fk_product_type;
5842 if (empty($productstatic->ref)) {
5843 $line->fetch_product();
5844 $productstatic = $line->product;
5847 $this->tpl[
'label'] .= $productstatic->getNomUrl(1);
5848 $this->tpl[
'label'] .=
' - '.(!empty($line->label) ? $line->label : $line->product_label);
5850 if ($line->product_type == 1 && ($date_start || $date_end)) {
5854 $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"')));
5855 if (!empty($line->desc)) {
5856 $this->tpl[
'label'] .= $line->desc;
5858 $this->tpl[
'label'] .= ($line->label ?
' '.$line->label :
'');
5862 if ($line->product_type == 1 && ($date_start || $date_end)) {
5867 if (!empty($line->desc)) {
5868 '@phan-var-force OrderLine|FactureLigne|ContratLigne|FactureFournisseurLigneRec|SupplierInvoiceLine|SupplierProposalLine $line';
5869 if ($line->desc ==
'(CREDIT_NOTE)') {
5871 $discount->fetch($line->fk_remise_except);
5872 $this->tpl[
'description'] = $langs->transnoentities(
"DiscountFromCreditNote", $discount->getNomUrl(0));
5873 } elseif ($line->desc ==
'(DEPOSIT)') {
5875 $discount->fetch($line->fk_remise_except);
5876 $this->tpl[
'description'] = $langs->transnoentities(
"DiscountFromDeposit", $discount->getNomUrl(0));
5877 } elseif ($line->desc ==
'(EXCESS RECEIVED)') {
5879 $discount->fetch($line->fk_remise_except);
5880 $this->tpl[
'description'] = $langs->transnoentities(
"DiscountFromExcessReceived", $discount->getNomUrl(0));
5881 } elseif ($line->desc ==
'(EXCESS PAID)') {
5883 $discount->fetch($line->fk_remise_except);
5884 $this->tpl[
'description'] = $langs->transnoentities(
"DiscountFromExcessPaid", $discount->getNomUrl(0));
5886 $this->tpl[
'description'] =
dol_trunc($line->desc, 60);
5889 $this->tpl[
'description'] =
' ';
5893 $this->tpl[
'vat_rate'] =
vatrate($line->tva_tx,
true);
5894 $this->tpl[
'vat_rate'] .= (((int) $line->info_bits & 1) == 1) ?
'*' :
'';
5895 if (!empty($line->vat_src_code) && !preg_match(
'/\(/', $this->tpl[
'vat_rate'])) {
5896 $this->tpl[
'vat_rate'] .=
' ('.$line->vat_src_code.
')';
5899 $this->tpl[
'price'] =
price($line->subprice);
5900 $this->tpl[
'total_ht'] =
price($line->total_ht);
5901 $this->tpl[
'multicurrency_price'] =
price($line->multicurrency_subprice);
5902 $this->tpl[
'qty'] = (((int) $line->info_bits & 2) != 2) ? $line->qty :
' ';
5904 $this->tpl[
'unit'] = $line->getLabelOfUnit(
'long', $langs);
5905 $this->tpl[
'unit_short'] = $line->getLabelOfUnit(
'short', $langs);
5908 $this->tpl[
'remise_percent'] = (((int) $line->info_bits & 2) != 2) ?
vatrate((
string) $line->remise_percent,
true) :
' ';
5911 $this->tpl[
'strike'] = 0;
5913 $this->tpl[
'strike'] = 1;
5914 } elseif (defined(
'SUBTOTALS_SPECIAL_CODE') && $line->special_code == SUBTOTALS_SPECIAL_CODE) {
5919 $this->tpl[
'strike'] = 1;
5924 $dirtpls = array_merge($conf->modules_parts[
'tpl'], array($defaulttpldir));
5925 foreach ($dirtpls as $module => $reldir) {
5926 if (!empty($module)) {
5929 $tpl = DOL_DOCUMENT_ROOT.$reldir.
'/originproductline.tpl.php';
5932 if (empty($conf->file->strict_mode)) {
5933 $res = @include $tpl;
5935 $res = include $tpl;
5962 $sql =
"INSERT INTO ".$this->db->prefix().
"element_resources (";
5963 $sql .=
"resource_id";
5964 $sql .=
", resource_type";
5965 $sql .=
", element_id";
5966 $sql .=
", element_type";
5968 $sql .=
", mandatory";
5969 $sql .=
") VALUES (";
5970 $sql .= ((int) $resource_id);
5971 $sql .=
", '".$this->db->escape($resource_type).
"'";
5972 $sql .=
", '".$this->db->escape((
string) $this->
id).
"'";
5973 $sql .=
", '".$this->db->escape($this->element).
"'";
5974 $sql .=
", '".$this->db->escape((
string) $busy).
"'";
5975 $sql .=
", '".$this->db->escape((
string) $mandatory).
"'";
5978 dol_syslog(get_class($this).
"::add_element_resource", LOG_DEBUG);
5979 if ($this->db->query($sql)) {
5981 $result = $this->call_trigger(strtoupper($this->TRIGGER_PREFIX).
'_ADD_RESOURCE', $user);
5983 $this->db->rollback();
5987 $this->db->commit();
5990 $this->error = $this->db->lasterror();
5991 $this->db->rollback();
6012 $sql =
"DELETE FROM ".$this->db->prefix().
"element_resources";
6013 $sql .=
" WHERE rowid = ".((int) $rowid);
6015 dol_syslog(get_class($this).
"::delete_resource", LOG_DEBUG);
6017 $resql = $this->db->query($sql);
6019 $this->error = $this->db->lasterror();
6020 $this->db->rollback();
6024 $result = $this->call_trigger(strtoupper($this->TRIGGER_PREFIX).
'_DELETE_RESOURCE', $user);
6026 $this->db->rollback();
6030 $this->db->commit();
6044 if (isset($this->lines) && is_array($this->lines)) {
6045 $nboflines = count($this->lines);
6046 for ($i = 0; $i < $nboflines; $i++) {
6047 if (is_object($this->lines[$i])) {
6048 $this->lines[$i] = clone $this->lines[$i];
6067 protected function commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams =
null)
6069 global $conf, $langs, $hookmanager, $action;
6071 $srctemplatepath =
'';
6073 $parameters = array(
'modelspath' => $modelspath,
'modele' => $modele,
'outputlangs' => $outputlangs,
'hidedetails' => $hidedetails,
'hidedesc' => $hidedesc,
'hideref' => $hideref,
'moreparams' => $moreparams);
6074 $reshook = $hookmanager->executeHooks(
'commonGenerateDocument', $parameters, $this, $action);
6076 if (!empty($reshook)) {
6080 dol_syslog(
"commonGenerateDocument modele=".$modele.
" outputlangs->defaultlang=".(is_object($outputlangs) ? $outputlangs->defaultlang :
'null'));
6082 if (empty($modele)) {
6083 $this->error =
'BadValueForParameterModele';
6088 $err = error_reporting();
6090 @set_time_limit(120);
6091 error_reporting($err);
6094 $tmp = explode(
':', $modele, 2);
6095 $saved_model = $modele;
6096 if (!empty($tmp[1])) {
6098 $srctemplatepath = $tmp[1];
6105 $dirmodels = array(
'/');
6106 if (is_array($conf->modules_parts[
'models'])) {
6107 $dirmodels = array_merge($dirmodels, $conf->modules_parts[
'models']);
6109 foreach ($dirmodels as $reldir) {
6110 foreach (array(
'doc',
'pdf') as $prefix) {
6111 if (in_array(get_class($this), array(
'Adherent'))) {
6113 $file = $prefix.
"_".$modele.
".class.php";
6116 $file = $prefix.
"_".$modele.
".modules.php";
6123 if (file_exists($file)) {
6125 $classname = $prefix.
'_'.$modele;
6134 if ($filefound ===
'' || $classname ===
'') {
6135 $this->error = $langs->trans(
"Error").
' Failed to load doc generator with modelpaths='.$modelspath.
' - modele='.$modele;
6136 $this->errors[] = $this->error;
6147 require_once $filefound;
6149 $obj =
new $classname($this->db);
6161 '@phan-var-force ModelePDFMember $obj';
6165 if ($obj->type ==
'odt' && empty($srctemplatepath)) {
6166 $varfortemplatedir = $obj->scandir;
6170 $listoffiles = array();
6173 $listofdir = explode(
',', $dirtoscan);
6174 foreach ($listofdir as $key => $tmpdir) {
6175 $tmpdir = trim($tmpdir);
6176 $tmpdir = preg_replace(
'/DOL_DATA_ROOT/', DOL_DATA_ROOT, $tmpdir);
6178 unset($listofdir[$key]);
6181 if (is_dir($tmpdir)) {
6182 $tmpfiles =
dol_dir_list($tmpdir,
'files', 0,
'\.od(s|t)$',
'',
'name', SORT_ASC, 0);
6183 if (count($tmpfiles)) {
6184 $listoffiles = array_merge($listoffiles, $tmpfiles);
6189 if (count($listoffiles)) {
6190 foreach ($listoffiles as $record) {
6191 $srctemplatepath = $record[
'fullname'];
6197 if (empty($srctemplatepath)) {
6198 $this->error =
'ErrorGenerationAskedForOdtTemplateWithSrcFileNotDefined';
6203 if ($obj->type ==
'odt' && !empty($srctemplatepath)) {
6205 dol_syslog(
"Failed to locate template file ".$srctemplatepath, LOG_WARNING);
6206 $this->error =
'ErrorGenerationAskedForOdtTemplateWithSrcFileNotFound';
6213 $sav_charset_output = empty($outputlangs->charset_output) ?
'' : $outputlangs->charset_output;
6216 $this->model_pdf = $saved_model;
6220 $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath,
'member', 1,
'tmp_cards');
6222 $resultwritefile = -1;
6223 dol_syslog(
"Error generating document - Provided ".get_class($this).
" to ".get_class($obj).
"::write_file()", LOG_ERR);
6227 if ($this instanceof
Don) {
6228 $resultwritefile = $obj->write_file($this, $outputlangs );
6230 $resultwritefile = -1;
6231 dol_syslog(
"Error generating document - Provided ".get_class($this).
" to Don::write_file()", LOG_ERR);
6235 '@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';
6236 $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, $hidedetails, $hidedesc, $hideref, $moreparams);
6241 if ($resultwritefile > 0) {
6242 $outputlangs->charset_output = $sav_charset_output;
6245 require_once DOL_DOCUMENT_ROOT.
'/core/lib/files.lib.php';
6249 if (!empty($obj->result[
'fullpath'])) {
6250 $destfull = $obj->result[
'fullpath'];
6253 $update_main_doc_field = 0;
6254 if (!empty($obj->update_main_doc_field)) {
6255 $update_main_doc_field = 1;
6261 $this->indexFile($destfull, $update_main_doc_field);
6264 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);
6270 $this->warnings = $obj->warnings;
6274 $outputlangs->charset_output = $sav_charset_output;
6275 $this->error = $obj->error;
6276 $this->errors = $obj->errors;
6277 $this->warnings = $obj->warnings;
6278 dol_syslog(
"Error generating document for ".__CLASS__.
". Error: ".$obj->error, LOG_ERR);
6292 public function indexFile($destfull, $update_main_doc_field)
6294 global $conf, $user;
6296 $upload_dir = dirname($destfull);
6297 $destfile = basename($destfull);
6298 $rel_dir = preg_replace(
'/^'.preg_quote(DOL_DATA_ROOT,
'/').
'/',
'', $upload_dir);
6300 if (!preg_match(
'/[\\/]temp[\\/]|[\\/]thumbs|\.meta$/', $rel_dir)) {
6301 $filename = basename($destfile);
6302 $rel_dir = preg_replace(
'/[\\/]$/',
'', $rel_dir);
6303 $rel_dir = preg_replace(
'/^[\\/]/',
'', $rel_dir);
6305 include_once DOL_DOCUMENT_ROOT.
'/ecm/class/ecmfiles.class.php';
6306 $ecmfile =
new EcmFiles($this->db);
6307 $result = $ecmfile->fetch(0,
'', ($rel_dir ? $rel_dir.
'/' :
'').$filename);
6310 $setsharekey =
false;
6312 !empty($this->TRIGGER_PREFIX)
6315 $setsharekey =
true;
6318 if ($this->element ==
'propal' || $this->element ==
'proposal') {
6320 $setsharekey =
true;
6323 $setsharekey =
true;
6326 if ($this->element ==
'facture' &&
getDolGlobalInt(
"INVOICE_ALLOW_EXTERNAL_DOWNLOAD")) {
6327 $setsharekey =
true;
6329 if ($this->element ==
'bank_account' &&
getDolGlobalInt(
"BANK_ACCOUNT_ALLOW_EXTERNAL_DOWNLOAD")) {
6330 $setsharekey =
true;
6332 if ($this->element ==
'contrat' &&
getDolGlobalInt(
"CONTRACT_ALLOW_EXTERNAL_DOWNLOAD")) {
6333 $setsharekey =
true;
6335 if ($this->element ==
'supplier_proposal' &&
getDolGlobalInt(
"SUPPLIER_PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD")) {
6336 $setsharekey =
true;
6338 if ($this->element ==
'societe_rib' &&
getDolGlobalInt(
"SOCIETE_RIB_ALLOW_ONLINESIGN")) {
6339 $setsharekey =
true;
6343 if (empty($ecmfile->share)) {
6344 require_once DOL_DOCUMENT_ROOT.
'/core/lib/security2.lib.php';
6351 $ecmfile->fullpath_orig =
'';
6352 $ecmfile->gen_or_uploaded =
'generated';
6353 $ecmfile->description =
'';
6354 $ecmfile->keywords =
'';
6355 $ecmfile->src_object_type = $this->table_element;
6357 $result = $ecmfile->update($user);
6363 $ecmfile->entity = $conf->entity;
6364 $ecmfile->filepath = $rel_dir;
6365 $ecmfile->filename = $filename;
6367 $ecmfile->fullpath_orig =
'';
6368 $ecmfile->gen_or_uploaded =
'generated';
6369 $ecmfile->description =
'';
6370 $ecmfile->keywords =
'';
6371 $ecmfile->src_object_type = $this->table_element;
6374 $result = $ecmfile->create($user);
6386 if ($update_main_doc_field && !empty($this->table_element)) {
6387 $sql =
"UPDATE ".$this->db->prefix().$this->table_element.
" SET last_main_doc = '".$this->db->escape($ecmfile->filepath.
"/".$ecmfile->filename).
"'";
6388 $sql .=
" WHERE rowid = ".((int) $this->
id);
6390 $resql = $this->db->query($sql);
6395 $this->last_main_doc = $ecmfile->filepath.
'/'.$ecmfile->filename;
6415 if (file_exists($file_osencoded)) {
6416 require_once DOL_DOCUMENT_ROOT.
'/core/lib/images.lib.php';
6419 $maxwidthsmall = $tmparraysize[
'maxwidthsmall'];
6420 $maxheightsmall = $tmparraysize[
'maxheightsmall'];
6421 $maxwidthmini = $tmparraysize[
'maxwidthmini'];
6422 $maxheightmini = $tmparraysize[
'maxheightmini'];
6427 vignette($file_osencoded, $maxwidthsmall, $maxheightsmall,
'_small', $quality);
6431 vignette($file_osencoded, $maxwidthmini, $maxheightmini,
'_mini', $quality);
6478 if (GETPOSTISSET($fieldname)) {
6479 return GETPOST($fieldname, $type, 3);
6482 if (isset($alternatevalue)) {
6483 return $alternatevalue;
6486 $newelement = $this->element;
6487 if ($newelement ==
'facture') {
6488 $newelement =
'invoice';
6490 if ($newelement ==
'commande') {
6491 $newelement =
'order';
6493 if (empty($newelement)) {
6494 dol_syslog(
"Ask a default value using common method getDefaultCreateValueForField on an object with no property ->element defined. Return empty string.", LOG_WARNING);
6498 $keyforfieldname = strtoupper($newelement.
'_DEFAULT_'.$fieldname);
6525 if (!$this->element) {
6528 if (!($this->
id > 0)) {
6531 if (is_array($this->array_languages)) {
6535 $this->array_languages = array();
6537 $element = $this->element;
6538 if ($element ==
'categorie') {
6539 $element =
'categories';
6543 $sql =
"SELECT rowid, property, lang , value";
6544 $sql .=
" FROM ".$this->db->prefix().
"object_lang";
6545 $sql .=
" WHERE type_object = '".$this->db->escape($element).
"'";
6546 $sql .=
" AND fk_object = ".((int) $this->
id);
6548 $resql = $this->db->query($sql);
6550 $numrows = $this->db->num_rows($resql);
6553 while ($i < $numrows) {
6554 $obj = $this->db->fetch_object($resql);
6555 $key = $obj->property;
6556 $value = $obj->value;
6557 $codelang = $obj->lang;
6558 $type = $this->fields[$key][
'type'];
6561 if (preg_match(
'/date/', $type)) {
6562 $this->array_languages[$key][$codelang] = $this->db->jdate($value);
6564 $this->array_languages[$key][$codelang] = $value;
6571 $this->db->free($resql);
6594 foreach ($_POST as $postfieldkey => $postfieldvalue) {
6595 $tmparray = explode(
'-', $postfieldkey);
6596 if ($tmparray[0] !=
'field') {
6600 $element = $tmparray[1];
6601 $key = $tmparray[2];
6602 $codelang = $tmparray[3];
6605 if (!empty($onlykey) && $key != $onlykey) {
6608 if ($element != $this->element) {
6612 $key_type = $this->fields[$key][
'type'];
6615 if (isset($this->fields[$key][
'enabled'])) {
6616 $enabled = (int)
dol_eval((
string) $this->fields[$key][
'enabled'], 1, 1,
'1');
6623 if (empty($enabled)) {
6628 if (in_array($key_type, array(
'date'))) {
6632 } elseif (in_array($key_type, array(
'datetime'))) {
6636 } elseif (in_array($key_type, array(
'checkbox',
'chkbxlst'))) {
6637 $value_arr =
GETPOST($postfieldkey,
'array');
6638 if (!empty($value_arr)) {
6639 $value_key = implode(
',', $value_arr);
6643 } elseif (in_array($key_type, array(
'price',
'double'))) {
6644 $value_arr =
GETPOST($postfieldkey,
'alpha');
6647 $value_key =
GETPOST($postfieldkey);
6648 if (in_array($key_type, array(
'link')) && $value_key ==
'-1') {
6653 $this->array_languages[$key][$codelang] = $value_key;
6678 $savDisableCompute = $conf->disable_compute;
6679 $conf->disable_compute = 1;
6681 $ret = $this->fetch(
$id);
6683 $conf->disable_compute = $savDisableCompute;
6701 global $conf, $extrafields;
6703 if (empty($rowid)) {
6706 if (empty($rowid) && isset($this->rowid)) {
6707 $rowid = $this->rowid;
6711 if (!$this->table_element) {
6715 $this->array_options = array();
6717 if (!is_array($optionsArray)) {
6719 if (!isset($extrafields) || !is_object($extrafields)) {
6720 require_once DOL_DOCUMENT_ROOT.
'/core/class/extrafields.class.php';
6725 if (empty($extrafields->attributes[$this->table_element][
'loaded'])) {
6726 $extrafields->fetch_name_optionals_label($this->table_element);
6728 $optionsArray = (!empty($extrafields->attributes[$this->table_element][
'label']) ? $extrafields->attributes[$this->table_element][
'label'] :
null);
6730 global $extrafields;
6731 dol_syslog(
"Warning: fetch_optionals was called with param optionsArray defined when you should pass null now", LOG_WARNING);
6734 $table_element = $this->table_element;
6735 if ($table_element ==
'categorie') {
6736 $table_element =
'categories';
6740 if (is_array($optionsArray) && count($optionsArray) > 0) {
6741 $sql =
"SELECT rowid";
6742 foreach ($optionsArray as $name => $label) {
6743 if (empty($extrafields->attributes[$this->table_element][
'type'][$name]) || (!in_array($extrafields->attributes[$this->table_element][
'type'][$name], [
'separate',
'point',
'multipts',
'linestrg',
'polygon']))) {
6744 $sql .=
", ".$this->db->sanitize($name);
6747 if (!empty($extrafields->attributes[$this->table_element][
'type'][$name]) && in_array($extrafields->attributes[$this->table_element][
'type'][$name], array(
'point',
'multipts',
'linestrg',
'polygon'))) {
6749 $sql .=
", ST_AsWKT(".$name.
") as ".$this->db->sanitize($name);
6752 $sql .=
" FROM ".$this->db->prefix().$table_element.
"_extrafields";
6753 $sql .=
" WHERE fk_object = ".((int) $rowid);
6756 $resql = $this->db->query($sql);
6758 $numrows = $this->db->num_rows($resql);
6760 $tab = $this->db->fetch_array($resql);
6762 foreach ($tab as $key => $value) {
6764 if ($key !=
'rowid' && $key !=
'tms' && $key !=
'fk_member' && !is_int($key)) {
6766 if (!empty($extrafields->attributes[$this->table_element]) && in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'date',
'datetime'))) {
6768 $this->array_options[
"options_".$key] = $this->db->jdate($value);
6770 $this->array_options[
"options_".$key] = $value;
6775 if (!empty($extrafields->attributes[$this->table_element][
'type'][$key]) && $extrafields->attributes[$this->table_element][
'type'][$key] ==
'password') {
6776 if (!empty($value) && preg_match(
'/^dolcrypt:/', $value)) {
6777 $this->array_options[
"options_".$key] =
dolDecrypt($value);
6786 if (is_array($extrafields->attributes[$this->table_element][
'label'])) {
6787 foreach ($extrafields->attributes[$this->table_element][
'label'] as $key => $val) {
6788 $this->array_options[
'options_' . $key] =
null;
6795 if (is_array($extrafields->attributes[$this->table_element][
'label'])) {
6796 foreach ($extrafields->attributes[$this->table_element][
'label'] as $key => $val) {
6797 if (!empty($extrafields->attributes[$this->table_element]) && !empty($extrafields->attributes[$this->table_element][
'computed'][$key])) {
6799 if (empty($conf->disable_compute)) {
6800 global $objectoffield;
6801 $objectoffield = $this;
6802 $this->array_options[
'options_' . $key] =
dol_eval((
string) $extrafields->attributes[$this->table_element][
'computed'][$key], 1, 0,
'2');
6808 $this->db->free($resql);
6816 $this->errors[] = $this->db->lasterror;
6837 $table_element = $this->table_element;
6838 if ($table_element ==
'categorie') {
6839 $table_element =
'categories';
6842 dol_syslog(get_class($this).
"::deleteExtraFields delete", LOG_DEBUG);
6844 $sql_del =
"DELETE FROM ".$this->db->prefix().$table_element.
"_extrafields WHERE fk_object = ".((int) $this->
id);
6846 $resql = $this->db->query($sql_del);
6848 $this->error = $this->db->lasterror();
6849 $this->db->rollback();
6852 $this->db->commit();
6869 global $langs, $user;
6871 if (
getDolGlobalString(
'MAIN_EXTRAFIELDS_DISABLED') || empty($this->array_options)) {
6875 if (empty($userused)) {
6882 $langs->load(
'admin');
6883 require_once DOL_DOCUMENT_ROOT.
'/core/class/extrafields.class.php';
6885 $target_extrafields = $extrafields->fetch_name_optionals_label($this->table_element);
6888 $new_array_options = array();
6889 foreach ($this->array_options as $key => $value) {
6890 if (in_array(substr($key, 8), array_keys($target_extrafields))) {
6891 $new_array_options[$key] = $value;
6892 } elseif (in_array($key, array_keys($target_extrafields))) {
6893 $new_array_options[
'options_'.$key] = $value;
6897 foreach ($new_array_options as $key => $value) {
6898 $attributeKey = substr($key, 8);
6899 $attributeType = $extrafields->attributes[$this->table_element][
'type'][$attributeKey];
6900 $attributeLabel = $langs->transnoentities($extrafields->attributes[$this->table_element][
'label'][$attributeKey]);
6901 $attributeParam = $extrafields->attributes[$this->table_element][
'param'][$attributeKey];
6902 $attributeRequired = $extrafields->attributes[$this->table_element][
'required'][$attributeKey];
6903 $attributeUnique = $extrafields->attributes[$this->table_element][
'unique'][$attributeKey];
6904 $attrfieldcomputed = $extrafields->attributes[$this->table_element][
'computed'][$attributeKey];
6905 $attributeEmptyOnClone = $extrafields->attributes[$this->table_element][
'emptyonclone'][$attributeKey];
6910 if (!empty($this->context[
'createfromclone']) && $this->context[
'createfromclone'] ==
'createfromclone' && (!empty($attributeUnique) || !empty($attributeEmptyOnClone))) {
6911 $new_array_options[$key] =
null;
6917 if (!empty($this->context[
'createproductcombination']) && $this->context[
'createproductcombination'] ==
'createproductcombination' && !empty($attributeUnique)) {
6918 $new_array_options[$key] =
null;
6923 if ($attributeRequired) {
6924 $v = $this->array_options[$key];
6926 $langs->load(
"errors");
6927 dol_syslog(
"Mandatory field '".$key.
"' is empty during create and set to required into definition of extrafields");
6928 $this->errors[] = $langs->trans(
'ErrorFieldRequired', $attributeLabel);
6933 if (!empty($attrfieldcomputed)) {
6935 $value =
dol_eval((
string) $attrfieldcomputed, 1, 0,
'2');
6936 dol_syslog($langs->trans(
"Extrafieldcomputed").
" on ".$attributeLabel.
"(".$value.
")", LOG_DEBUG);
6937 $new_array_options[$key] = $value;
6939 $new_array_options[$key] =
null;
6944 switch ($attributeType) {
6948 if (!is_numeric($value) && $value !=
'') {
6949 $this->errors[] = $langs->trans(
"ExtraFieldHasWrongValue", $attributeLabel);
6951 } elseif ($value ===
'') {
6952 $new_array_options[$key] =
null;
6956 if ($value ===
'' || $value ===
false || $value ===
null) {
6957 $new_array_options[$key] =
null;
6963 if (!is_numeric($value) && $value !=
'') {
6964 dol_syslog($langs->trans(
"ExtraFieldHasWrongValue").
" for ".$attributeLabel.
"(".$value.
"is not '".$attributeType.
"')", LOG_DEBUG);
6965 $this->errors[] = $langs->trans(
"ExtraFieldHasWrongValue", $attributeLabel);
6967 } elseif ($value ==
'') {
6971 $new_array_options[$key] = $value;
6981 if ($this->array_options[$key] !=
'' && is_array($extrafields->attributes[$this->table_element][
'param'][$attributeKey][
'options'])) {
6983 $tmparrays = array_keys($extrafields->attributes[$this->table_element][
'param'][$attributeKey][
'options']);
6984 $algo = reset($tmparrays);
6989 if (is_object($this->oldcopy)) {
6991 if (isset($this->oldcopy->array_options[$key]) && $this->array_options[$key] == $this->oldcopy->array_options[$key]) {
6993 if ($algo ==
'dolcrypt') {
6994 if (!preg_match(
'/^dolcrypt:/', $this->array_options[$key])) {
6995 $new_array_options[$key] =
dolEncrypt($this->array_options[$key]);
6997 $new_array_options[$key] = $this->array_options[$key];
7000 $new_array_options[$key] = $this->array_options[$key];
7004 if ($algo ==
'dolcrypt') {
7005 if (!preg_match(
'/^dolcrypt:/', $this->array_options[$key])) {
7006 $new_array_options[$key] =
dolEncrypt($this->array_options[$key]);
7008 $new_array_options[$key] = $this->array_options[$key];
7011 $new_array_options[$key] =
dol_hash($this->array_options[$key], $algo);
7017 if ($algo ==
'dolcrypt' && !preg_match(
'/^dolcrypt:/', $this->array_options[$key])) {
7018 $new_array_options[$key] =
dolEncrypt($this->array_options[$key]);
7020 $new_array_options[$key] = $this->array_options[$key];
7025 $new_array_options[$key] = $this->array_options[$key];
7028 $new_array_options[$key] = $this->array_options[$key];
7034 if (!is_numeric($this->array_options[$key]) || $this->array_options[$key] != intval($this->array_options[$key])) {
7035 $this->array_options[$key] = strtotime($this->array_options[$key]);
7037 $new_array_options[$key] = $this->db->idate($this->array_options[$key]);
7041 if (!is_numeric($this->array_options[$key]) || $this->array_options[$key] != intval($this->array_options[$key])) {
7042 $this->array_options[$key] = strtotime($this->array_options[$key]);
7044 $new_array_options[$key] = $this->db->idate($this->array_options[$key],
'gmt');
7047 $param_list = array_keys($attributeParam[
'options']);
7050 $InfoFieldList = explode(
":", $param_list[0]);
7052 if ($InfoFieldList[0] && class_exists($InfoFieldList[0])) {
7053 if ($value ==
'-1') {
7054 $new_array_options[$key] =
'';
7056 $object =
new $InfoFieldList[0]($this->db);
7057 '@phan-var-force CommonObject $object';
7061 $sqlFetchObject =
"SELECT rowid FROM ".$this->db->prefix().$object->table_element;
7062 if (is_numeric($value)) {
7063 $sqlFetchObject .=
" WHERE rowid = " . (int) $value;
7065 $sqlFetchObject .=
" WHERE ref = '" . $this->db->escape($value) .
"'";
7068 $obj = $this->db->getRow($sqlFetchObject);
7074 if (is_object($obj)) {
7075 $objectId = $obj->rowid;
7082 $new_array_options[$key] = $objectId;
7084 $this->error =
"Id/Ref '".$value.
"' for object '".
$object->element.
"' not found";
7089 dol_syslog(
'Error bad setup of extrafield', LOG_WARNING);
7094 if (is_array($this->array_options[$key])) {
7095 $new_array_options[$key] = implode(
',', $this->array_options[$key]);
7097 $new_array_options[$key] = $this->array_options[$key];
7104 $sqlColumnValues = [
'fk_object' => (int) $this->
id];
7106 foreach ($new_array_options as $key => $newValue) {
7107 $attributeKey = substr($key, 8);
7108 $attributeType = $extrafields->attributes[$this->table_element][
'type'][$attributeKey];
7109 if ($attributeType ===
'separate') {
7113 $geoDataType = ExtraFields::$geoDataTypes[$attributeType] ??
null;
7115 if (! $geoDataType) {
7117 if ($newValue !=
'') {
7118 $sqlColumnValues[$attributeKey] =
"'".$this->db->escape($newValue).
"'";
7120 $sqlColumnValues[$attributeKey] =
'null';
7124 if (empty($newValue)) {
7125 $sqlColumnValues[$attributeKey] =
'null';
7128 if (preg_match(
'/error/i', $newValue)) {
7129 dol_syslog(
'Bad syntax string for '.$geoDataType[
'shortname'].
' '.$newValue.
' to generate SQL request', LOG_WARNING);
7130 $sqlColumnValues[$attributeKey] =
'null';
7139 $sqlColumnValues[$key] = $geoDataType[
'ST_Function'].
"('".$this->db->escape($newValue).
"')";
7144 $table_element = $this->table_element;
7145 if ($table_element ==
'categorie') {
7146 $table_element =
'categories';
7148 $extrafieldsTable = $this->db->prefix() . $table_element .
'_extrafields';
7150 dol_syslog(get_class($this).
"::insertExtraFields update or insert record line", LOG_DEBUG);
7152 $linealreadyfound = 0;
7153 $sql =
"SELECT COUNT(rowid) as nb FROM ".$this->db->prefix().$table_element.
"_extrafields WHERE fk_object = ".((int) $this->
id);
7154 $resql = $this->db->query($sql);
7156 $tmpobj = $this->db->fetch_object($resql);
7158 $linealreadyfound = $tmpobj->nb;
7163 if ($linealreadyfound) {
7164 array_shift($sqlColumnValues);
7165 if (empty($sqlColumnValues)) {
7171 $this->db->commit();
7174 $sqlColumnValueString = implode(
7180 array_map(
function ($key) use ($sqlColumnValues) {
7181 return "{$key} = {$sqlColumnValues[$key]}";
7182 }, array_keys($sqlColumnValues))
7184 $sql =
"UPDATE {$extrafieldsTable} SET {$sqlColumnValueString} WHERE fk_object = ".((int) $this->
id);
7187 $extrafieldsRequiredOnOtherEntities = $extrafields->attributes[$this->table_element][
'mandatoryfieldsofotherentities'] ?? array();
7188 foreach ($extrafieldsRequiredOnOtherEntities as $key => $extrafieldType) {
7189 if (isset($sqlColumnValues[$key])) {
7194 $sqlColumnValues[$key] =
"''";
7195 if (in_array($extrafieldType, array(
'int',
'double',
'price'))) {
7196 $sqlColumnValues[$key] = 0;
7199 $sqlColumns = implode(
',', array_keys($sqlColumnValues));
7200 $sqlValues = implode(
',', array_values($sqlColumnValues));
7201 $sql =
"INSERT INTO {$extrafieldsTable} ({$sqlColumns}) VALUES ({$sqlValues})";
7204 $resql = $this->db->query($sql);
7206 $this->error = $this->db->lasterror();
7211 if (!$error && !empty($this->fields[
'fk_user_modif'])) {
7212 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
7213 $sql .=
" SET fk_user_modif = ".(int) $userused->id;
7214 $sql .=
" WHERE ".(empty($this->table_rowid) ?
'rowid' : $this->db->sanitize($this->table_rowid)).
" = ".((
int)
$this->id);
7215 $this->db->query($sql);
7218 if (!$error && $trigger) {
7220 $this->context = array(
'extrafieldaddupdate' => 1);
7221 $result = $this->call_trigger($trigger, $userused);
7229 $this->db->rollback();
7232 $this->db->commit();
7250 global $langs, $user;
7252 if (empty($userused)) {
7262 if (is_array($this->array_languages)) {
7263 $new_array_languages = $this->array_languages;
7265 foreach ($new_array_languages as $key => $value) {
7266 $attributeKey = $key;
7267 $attributeType = $this->fields[$attributeKey][
'type'];
7268 $attributeLabel = $this->fields[$attributeKey][
'label'];
7273 switch ($attributeType) {
7275 if (is_array($value) || (!is_numeric($value) && $value !=
'')) {
7276 $this->errors[] = $langs->trans(
"ExtraLanguageHasWrongValue", $attributeLabel);
7278 } elseif ($value ==
'') {
7279 $new_array_languages[$key] =
null;
7284 if (!is_numeric($value) && $value !=
'') {
7285 dol_syslog($langs->trans(
"ExtraLanguageHasWrongValue").
" on ".$attributeLabel.
"(".$value.
"is not '".$attributeType.
"')", LOG_DEBUG);
7286 $this->errors[] = $langs->trans(
"ExtraLanguageHasWrongValue", $attributeLabel);
7288 } elseif ($value ==
'') {
7289 $new_array_languages[$key] =
null;
7291 $new_array_languages[$key] = $value;
7305 $table_element = $this->table_element;
7306 if ($table_element ==
'categorie') {
7307 $table_element =
'categories';
7310 dol_syslog(get_class($this).
"::insertExtraLanguages delete then insert", LOG_DEBUG);
7312 foreach ($new_array_languages as $key => $langcodearray) {
7313 foreach ($langcodearray as $langcode => $value) {
7314 $sql_del =
"DELETE FROM ".$this->db->prefix().
"object_lang";
7315 $sql_del .=
" WHERE fk_object = ".((int) $this->
id).
" AND property = '".$this->db->escape($key).
"' AND type_object = '".$this->db->escape($table_element).
"'";
7316 $sql_del .=
" AND lang = '".$this->db->escape($langcode).
"'";
7317 $this->db->query($sql_del);
7319 if ($value !==
'') {
7320 $sql =
"INSERT INTO ".$this->db->prefix().
"object_lang (fk_object, property, type_object, lang, value";
7321 $sql .=
") VALUES (".$this->id.
", '".$this->db->escape($key).
"', '".$this->db->escape($table_element).
"', '".$this->db->escape($langcode).
"', '".$this->db->escape($value).
"'";
7324 $resql = $this->db->query($sql);
7326 $this->error = $this->db->lasterror();
7334 if (!$error && $trigger) {
7336 $this->context = array(
'extralanguagesaddupdate' => 1);
7337 $result = $this->call_trigger($trigger, $userused);
7345 $this->db->rollback();
7348 $this->db->commit();
7368 global $langs, $user, $hookmanager;
7374 if (empty($userused)) {
7380 if (!empty($this->array_options) && isset($this->array_options[
"options_".$key])) {
7382 $langs->load(
'admin');
7383 require_once DOL_DOCUMENT_ROOT.
'/core/class/extrafields.class.php';
7385 $extrafields->fetch_name_optionals_label($this->table_element);
7386 if (!isset($extrafields->attributes[$this->table_element][
'type'][$key])) {
7390 $value = $this->array_options[
"options_".$key];
7392 $attributeKey = $key;
7393 $attributeType = $extrafields->attributes[$this->table_element][
'type'][$key];
7394 $attributeLabel = $extrafields->attributes[$this->table_element][
'label'][$key];
7395 $attributeParam = $extrafields->attributes[$this->table_element][
'param'][$key];
7396 $attributeRequired = $extrafields->attributes[$this->table_element][
'required'][$key];
7397 $attributeUnique = $extrafields->attributes[$this->table_element][
'unique'][$attributeKey];
7398 $attrfieldcomputed = $extrafields->attributes[$this->table_element][
'computed'][$key];
7401 if ($attributeRequired) {
7402 $mandatorypb =
false;
7403 if ($attributeType ==
'link' && $this->array_options[
"options_".$key] ==
'-1') {
7404 $mandatorypb =
true;
7406 if ($this->array_options[
"options_".$key] ===
'') {
7407 $mandatorypb =
true;
7410 $langs->load(
"errors");
7411 dol_syslog(
"Mandatory field 'options_".$key.
"' is empty during update and set to required into definition of extrafields");
7412 $this->errors[] = $langs->trans(
'ErrorFieldRequired', $attributeLabel);
7418 $new_array_options = $this->array_options;
7422 if (!empty($attrfieldcomputed)) {
7424 $value =
dol_eval((
string) $attrfieldcomputed, 1, 0,
'2');
7425 dol_syslog($langs->trans(
"Extrafieldcomputed").
" on ".$attributeLabel.
"(".$value.
")", LOG_DEBUG);
7427 $new_array_options[
"options_".$key] = $value;
7429 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7431 $new_array_options[
"options_".$key] =
null;
7433 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7437 switch ($attributeType) {
7439 if (!is_numeric($value) && $value !=
'') {
7440 $this->errors[] = $langs->trans(
"ExtraFieldHasWrongValue", $attributeLabel);
7442 } elseif ($value ===
'') {
7443 $new_array_options[
"options_".$key] =
null;
7445 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7451 if (!is_numeric($value) && $value !=
'') {
7452 dol_syslog($langs->trans(
"ExtraFieldHasWrongValue").
" on ".$attributeLabel.
"(".$value.
"is not '".$attributeType.
"')", LOG_DEBUG);
7453 $this->errors[] = $langs->trans(
"ExtraFieldHasWrongValue", $attributeLabel);
7455 } elseif ($value ===
'') {
7459 $new_array_options[
"options_".$key] = $value;
7461 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7473 if ($this->array_options[
"options_".$key] !=
'' && is_array($extrafields->attributes[$this->table_element][
'param'][$attributeKey][
'options'])) {
7475 $tmparrays = array_keys($extrafields->attributes[$this->table_element][
'param'][$attributeKey][
'options']);
7476 $algo = reset($tmparrays);
7482 if (is_object($this->oldcopy)) {
7484 if (isset($this->oldcopy->array_options[
"options_".$key]) && $this->array_options[
"options_".$key] == $this->oldcopy->array_options[
"options_".$key]) {
7485 if ($algo ==
'dolcrypt') {
7486 if (!preg_match(
'/^dolcrypt:/', $this->array_options[
"options_".$key])) {
7487 $new_array_options[
"options_".$key] =
dolEncrypt($this->array_options[
"options_".$key]);
7489 $new_array_options[
"options_".$key] = $this->array_options[
"options_".$key];
7492 $new_array_options[
"options_".$key] = $this->array_options[
"options_".$key];
7495 if ($algo ==
'dolcrypt') {
7496 if (!preg_match(
'/^dolcrypt:/', $this->array_options[
"options_".$key])) {
7497 $new_array_options[
"options_".$key] =
dolEncrypt($this->array_options[
"options_".$key]);
7499 $new_array_options[
"options_".$key] = $this->array_options[
"options_".$key];
7502 $new_array_options[
"options_".$key] =
dol_hash($this->array_options[
"options_".$key], $algo);
7506 if ($algo ==
'dolcrypt' && !preg_match(
'/^dolcrypt:/', $this->array_options[
"options_".$key])) {
7507 $new_array_options[
"options_".$key] =
dolEncrypt($this->array_options[
"options_".$key]);
7509 $new_array_options[
"options_".$key] = $this->array_options[
"options_".$key];
7514 $new_array_options[
"options_".$key] = $this->array_options[
"options_".$key];
7517 $new_array_options[
"options_".$key] = $this->array_options[
"options_".$key];
7520 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7524 if (empty($this->array_options[
"options_".$key])) {
7525 $new_array_options[
"options_".$key] =
null;
7527 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7529 $new_array_options[
"options_".$key] = $this->db->idate($this->array_options[
"options_".$key]);
7533 if (empty($this->array_options[
"options_".$key])) {
7534 $new_array_options[
"options_".$key] =
null;
7536 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7538 $new_array_options[
"options_".$key] = $this->db->idate($this->array_options[
"options_".$key],
'gmt');
7542 if (empty($this->array_options[
"options_".$key])) {
7543 $new_array_options[
"options_".$key] =
null;
7545 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7549 if ($this->array_options[
"options_".$key] ===
'') {
7550 $new_array_options[
"options_".$key] =
null;
7552 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7586 $new_array_options = array();
7587 if (is_array($this->array_options[
"options_".$key])) {
7588 $new_array_options[
"options_".$key] = implode(
',', $this->array_options[
"options_".$key]);
7590 $new_array_options[
"options_".$key] = $this->array_options[
"options_".$key];
7593 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7599 $linealreadyfound = 0;
7602 $table_element = $this->table_element;
7603 if ($table_element ==
'categorie') {
7604 $table_element =
'categories';
7607 $sql =
"SELECT COUNT(rowid) as nb FROM ".$this->db->prefix().$table_element.
"_extrafields WHERE fk_object = ".((int) $this->
id);
7608 $resql = $this->db->query($sql);
7610 $tmpobj = $this->db->fetch_object($resql);
7612 $linealreadyfound = $tmpobj->nb;
7617 if ($linealreadyfound) {
7618 if ($this->array_options[
"options_".$key] ===
null) {
7619 $sql =
"UPDATE ".$this->db->prefix().$table_element.
"_extrafields SET ".$key.
" = null";
7622 $sql =
"UPDATE ".$this->db->prefix().$table_element.
"_extrafields SET ".$key.
" = '".$this->db->escape($new_array_options[
"options_".$key]).
"'";
7624 $sql .=
" WHERE fk_object = ".((int) $this->
id);
7626 $resql = $this->db->query($sql);
7629 $this->error = $this->db->lasterror();
7632 $result = $this->insertExtraFields(
'', $user);
7639 if (!$error && !empty($this->fields[
'fk_user_modif'])) {
7640 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
7641 $sql .=
" SET fk_user_modif = ".(int) $userused->id;
7642 $sql .=
" WHERE ".(empty($this->table_rowid) ?
'rowid' : $this->db->sanitize($this->table_rowid)).
" = ".((
int)
$this->id);
7643 $this->db->query($sql);
7647 $parameters = array(
'key' => $key);
7649 $reshook = $hookmanager->executeHooks(
'updateExtraFieldBeforeCommit', $parameters, $this, $action);
7655 if (!$error && $trigger) {
7657 $this->context = array(
'extrafieldupdate' => 1);
7658 $result = $this->call_trigger($trigger, $userused);
7666 dol_syslog(__METHOD__.$this->error, LOG_ERR);
7667 $this->db->rollback();
7670 $this->db->commit();
7686 return $this->array_options[
'options_'.$key] ??
null;
7698 $this->array_options[
'options_'.$key] = $value;
7715 if (empty($userused)) {
7743 public function showInputField($val, $key, $value, $moreparam =
'', $keysuffix =
'', $keyprefix =
'', $morecss = 0, $nonewbutton = 0)
7745 global $conf, $langs, $form;
7750 if (!is_object($form)) {
7751 require_once DOL_DOCUMENT_ROOT.
'/core/class/html.form.class.php';
7752 $form =
new Form($this->db);
7755 if (!empty($this->fields)) {
7756 $val = $this->fields[$key];
7760 $fieldValidationErrorMsg =
'';
7761 $validationClass =
'';
7762 $fieldValidationErrorMsg = $this->getFieldError($key);
7763 if (!empty($fieldValidationErrorMsg)) {
7764 $validationClass =
' --error';
7766 $validationClass =
' --success';
7774 $param[
'options'] = array();
7777 $size = !empty($this->fields[$key][
'size']) ? $this->fields[$key][
'size'] : 0;
7779 if (preg_match(
'/^(integer|link):(.*):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
7780 $param[
'options'] = array($reg[2].
':'.$reg[3].
':'.$reg[4].
':'.$reg[5] =>
'N');
7782 } elseif (preg_match(
'/^(integer|link):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
7783 $param[
'options'] = array($reg[2].
':'.$reg[3].
':'.$reg[4] =>
'N');
7785 } elseif (preg_match(
'/^(integer|link):(.*):(.*)/i', $val[
'type'], $reg)) {
7786 $param[
'options'] = array($reg[2].
':'.$reg[3] =>
'N');
7788 } elseif (preg_match(
'/^(sellist):(.*):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
7789 $param[
'options'] = array($reg[2].
':'.$reg[3].
':'.$reg[4].
':'.$reg[5] =>
'N');
7791 } elseif (preg_match(
'/^(sellist):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
7792 $param[
'options'] = array($reg[2].
':'.$reg[3].
':'.$reg[4] =>
'N');
7794 } elseif (preg_match(
'/^(sellist):(.*):(.*)/i', $val[
'type'], $reg)) {
7795 $param[
'options'] = array($reg[2].
':'.$reg[3] =>
'N');
7797 } elseif (preg_match(
'/^chkbxlst:(.*)/i', $val[
'type'], $reg)) {
7798 $param[
'options'] = array($reg[1] =>
'N');
7800 } elseif (preg_match(
'/varchar\((\d+)\)/', $val[
'type'], $reg)) {
7801 $param[
'options'] = array();
7804 } elseif (preg_match(
'/varchar/', $val[
'type'])) {
7805 $param[
'options'] = array();
7807 } elseif (preg_match(
'/stars\((\d+)\)/', $val[
'type'], $reg)) {
7808 $param[
'options'] = array();
7812 $param[
'options'] = array();
7813 $type = $this->fields[$key][
'type'];
7818 if (!empty($this->fields[$key][
'arrayofkeyval']) && is_array($this->fields[$key][
'arrayofkeyval'])) {
7819 $param[
'options'] = $this->fields[$key][
'arrayofkeyval'];
7821 if (empty($this->fields[$key][
'multiinput'])) {
7822 $type = (($this->fields[$key][
'type'] ==
'checkbox') ? $this->fields[$key][
'type'] :
'select');
7826 $label = $this->fields[$key][
'label'];
7829 $default = (!empty($this->fields[$key][
'default']) ? $this->fields[$key][
'default'] :
'');
7831 $computed = (!empty($this->fields[$key][
'computed']) ? $this->fields[$key][
'computed'] :
'');
7833 $unique = (!empty($this->fields[$key][
'unique']) ? $this->fields[$key][
'unique'] : 0);
7835 $required = (!empty($this->fields[$key][
'required']) ? $this->fields[$key][
'required'] : 0);
7837 $autofocusoncreate = (!empty($this->fields[$key][
'autofocusoncreate']) ? $this->fields[$key][
'autofocusoncreate'] : 0);
7839 $placeholder = (!empty($this->fields[$key][
'placeholder']) ? $this->fields[$key][
'placeholder'] : 0);
7842 $langfile = (!empty($this->fields[$key][
'langfile']) ? $this->fields[$key][
'langfile'] :
'');
7844 $list = (!empty($this->fields[$key][
'list']) ? $this->fields[$key][
'list'] : 0);
7845 $hidden = (in_array(abs($this->fields[$key][
'visible']), array(0, 2)) ? 1 : 0);
7850 if (!preg_match(
'/^search_/', $keyprefix)) {
7851 return '<span class="opacitymedium">'.$langs->trans(
"AutomaticallyCalculated").
'</span>';
7858 if (empty($morecss) && !empty($val[
'css'])) {
7859 $morecss = $val[
'css'];
7860 } elseif (empty($morecss)) {
7861 if ($type ==
'date') {
7862 $morecss =
'minwidth100imp';
7863 } elseif ($type ==
'datetime' || $type ==
'link') {
7864 $morecss =
'minwidth200imp';
7865 } elseif (in_array($type, array(
'int',
'integer',
'price')) || preg_match(
'/^double(\([0-9],[0-9]\)){0,1}/', (
string) $type)) {
7866 $morecss =
'maxwidth75';
7867 } elseif ($type ==
'url') {
7868 $morecss =
'minwidth400';
7869 } elseif ($type ==
'boolean') {
7872 if (is_numeric($size) && round((
float) $size) < 12) {
7873 $morecss =
'minwidth100';
7874 } elseif (is_numeric($size) && round((
float) $size) <= 48) {
7875 $morecss =
'minwidth200';
7877 $morecss =
'minwidth400';
7883 if (!empty($validationClass)) {
7884 $morecss .= $validationClass;
7887 if (in_array($type, array(
'date'))) {
7888 $tmp = explode(
',', $size);
7893 if (!$required && $value ==
'') {
7898 $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required,
'', 1, (($keyprefix !=
'search_' && $keyprefix !=
'search_options_') ? 1 : 0), 0, 1);
7899 } elseif (in_array($type, array(
'datetime'))) {
7900 $tmp = explode(
',', $size);
7905 if (!$required && $value ==
'') {
7910 $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required,
'', 1, (($keyprefix !=
'search_' && $keyprefix !=
'search_options_') ? 1 : 0), 0, 1,
'',
'',
'', 1,
'',
'',
'tzuserrel');
7911 } elseif (in_array($type, array(
'duration'))) {
7912 $out = $form->select_duration($keyprefix.$key.$keysuffix, $value, 0,
'text', 0, 1);
7913 } elseif (in_array($type, array(
'int',
'integer'))) {
7914 $tmp = explode(
',', $size);
7916 $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' :
'').
'>';
7917 } elseif (in_array($type, array(
'real'))) {
7918 $out =
'<input type="text" class="flat '.$morecss.
'" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.
dol_escape_htmltag($value).
'"'.($moreparam ? $moreparam :
'').($autofocusoncreate ?
' autofocus' :
'').
'>';
7919 } elseif (preg_match(
'/varchar/', (
string) $type)) {
7920 $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' :
'').
'>';
7921 } elseif (in_array($type, array(
'email',
'mail',
'phone',
'url',
'ip'))) {
7922 $out =
'<input type="text" class="flat '.$morecss.
'" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.
dol_escape_htmltag($value).
'" '.($moreparam ? $moreparam :
'').($autofocusoncreate ?
' autofocus' :
'').
'>';
7923 } elseif (preg_match(
'/^text/', (
string) $type)) {
7924 if (!preg_match(
'/search_/', $keyprefix)) {
7925 if (!empty($param[
'options'])) {
7928 $out .= $form->selectarray($keyprefix.$key.$keysuffix.
"_multiinput", $param[
'options'],
'', 1, 0, 0,
"flat maxwidthonphone".$morecss);
7929 $out .=
'<input id="'.$keyprefix.$key.$keysuffix.
'_multiinputadd" type="button" class="button" value="'.$langs->trans(
"Add").
'">';
7932 function handlemultiinputdisabling(htmlname){
7933 console.log("We handle the disabling of used options for "+htmlname+"_multiinput");
7934 multiinput = $("#"+htmlname+"_multiinput");
7935 multiinput.find("option").each(function(){
7936 tmpval = $("#"+htmlname).val();
7937 tmpvalarray = tmpval.split("\n");
7938 valtotest = $(this).val();
7939 if(tmpvalarray.includes(valtotest)){
7940 $(this).prop("disabled",true);
7942 if($(this).prop("disabled") == true){
7943 console.log(valtotest)
7944 $(this).prop("disabled", false);
7950 $(document).ready(function () {
7951 $("#'.$keyprefix.$key.$keysuffix.
'_multiinputadd").on("click",function() {
7952 tmpval = $("#'.$keyprefix.$key.$keysuffix.
'").val();
7953 tmpvalarray = tmpval.split(",");
7954 valtotest = $("#'.$keyprefix.$key.$keysuffix.
'_multiinput").val();
7955 if(valtotest != -1 && !tmpvalarray.includes(valtotest)){
7956 console.log("We add the selected value to the text area '.$keyprefix.$key.$keysuffix.
'");
7960 tmpval = tmpval + "\n" + valtotest;
7962 $("#'.$keyprefix.$key.$keysuffix.
'").val(tmpval);
7963 handlemultiinputdisabling("'.$keyprefix.$key.$keysuffix.
'");
7964 $("#'.$keyprefix.$key.$keysuffix.
'_multiinput").val(-1);
7966 console.log("We add nothing the text area '.$keyprefix.$key.$keysuffix.
'");
7969 $("#'.$keyprefix.$key.$keysuffix.
'").on("change",function(){
7970 handlemultiinputdisabling("'.$keyprefix.$key.$keysuffix.
'");
7972 handlemultiinputdisabling("'.$keyprefix.$key.$keysuffix.
'");
7974 $out .=
"</script>";
7975 $value = str_replace(
',',
"\n", $value);
7977 require_once DOL_DOCUMENT_ROOT.
'/core/class/doleditor.class.php';
7978 $doleditor =
new DolEditor($keyprefix.$key.$keysuffix, $value,
'', 200,
'dolibarr_notes',
'In',
false,
false,
false, ROWS_5,
'90%');
7979 $out .= (string) $doleditor->Create(1,
'',
true,
'',
'',
'', $morecss);
7981 $out =
'<input type="text" class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.
dol_escape_htmltag($value).
'" '.($moreparam ? $moreparam :
'').
'>';
7983 } elseif (preg_match(
'/^html/', (
string) $type)) {
7984 if (!preg_match(
'/search_/', $keyprefix)) {
7985 require_once DOL_DOCUMENT_ROOT.
'/core/class/doleditor.class.php';
7986 $doleditor =
new DolEditor($keyprefix.$key.$keysuffix, $value,
'', 200,
'dolibarr_notes',
'In',
false,
false,
isModEnabled(
'fckeditor') &&
getDolGlobalInt(
'FCKEDITOR_ENABLE_SOCIETE'), ROWS_5,
'90%');
7987 $out = (string) $doleditor->Create(1,
'',
true,
'',
'', $moreparam, $morecss);
7989 $out =
'<input type="text" class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.
dol_escape_htmltag($value).
'" '.($moreparam ? $moreparam :
'').
'>';
7991 } elseif ($type ==
'boolean') {
7993 if (!empty($value)) {
7994 $checked =
' checked value="1" ';
7996 $checked =
' value="1" ';
7998 $out =
'<input type="checkbox" class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" '.$checked.
' '.($moreparam ? $moreparam :
'').
'>';
7999 } elseif ($type ==
'price') {
8000 if (!empty($value)) {
8001 $value =
price($value);
8003 $out =
'<input type="text" class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.$value.
'" '.($moreparam ? $moreparam :
'').
'> '.$langs->getCurrencySymbol($conf->currency);
8004 } elseif ($type ==
'stars') {
8005 $out =
'<input type="hidden" class="flat '.$morecss.
'" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.
dol_escape_htmltag($value).
'"'.($moreparam ? $moreparam :
'').($autofocusoncreate ?
' autofocus' :
'').
'>';
8006 $out .=
'<div class="star-selection" id="'.$keyprefix.$key.$keysuffix.
'_selection">';
8008 while ($i <= $size) {
8009 $out .=
'<span class="star" data-value="'.$i.
'">'.
img_picto(
'',
'fontawesome_star_fas').
'</span>';
8014 jQuery(function($) { /* commonobject.class.php 1 */
8015 let container = $("#'.$keyprefix.$key.$keysuffix.
'_selection");
8016 let selectedStars = parseInt($("#'.$keyprefix.$key.$keysuffix.
'").val()) || 0;
8017 container.find(".star").each(function() {
8018 $(this).toggleClass("active", $(this).data("value") <= selectedStars);
8020 container.find(".star").on("mouseover", function() {
8021 let selectedStar = $(this).data("value");
8022 container.find(".star").each(function() {
8023 $(this).toggleClass("active", $(this).data("value") <= selectedStar);
8026 container.on("mouseout", function() {
8027 container.find(".star").each(function() {
8028 $(this).toggleClass("active", $(this).data("value") <= selectedStars);
8031 container.find(".star").off("click").on("click", function() {
8032 selectedStars = $(this).data("value");
8033 if (selectedStars === 1 && $("#'.$keyprefix.$key.$keysuffix.
'").val() == 1) {
8036 $("#'.$keyprefix.$key.$keysuffix.
'").val(selectedStars);
8037 container.find(".star").each(function() {
8038 $(this).toggleClass("active", $(this).data("value") <= selectedStars);
8043 } elseif (preg_match(
'/^double(\([0-9],[0-9]\)){0,1}/', (
string) $type)) {
8044 if (!empty($value)) {
8045 $value =
price($value);
8047 $out =
'<input type="text" class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.$value.
'" '.($moreparam ? $moreparam :
'').
'> ';
8048 } elseif ($type ==
'select') {
8050 if (!empty($conf->use_javascript_ajax) && !
getDolGlobalString(
'MAIN_EXTRAFIELDS_DISABLE_SELECT2')) {
8051 include_once DOL_DOCUMENT_ROOT.
'/core/lib/ajax.lib.php';
8052 $out .=
ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
8058 foreach ($param[
'options'] as $keyb => $valb) {
8059 if ((
string) $keyb ==
'') {
8062 if (strpos($valb,
"|") !==
false) {
8063 list($valb, $parent) = explode(
'|', $valb);
8066 $tmpselect .=
'<option value="'.$keyb.
'"';
8067 $tmpselect .= (((string) $value == (
string) $keyb) ?
' selected' :
'');
8068 if (!empty($parent)) {
8071 $tmpselect .= (!empty($parent) ?
' parent="'.$parent.
'"' :
'');
8072 $tmpselect .=
'>'.$langs->trans($valb).
'</option>';
8075 $out .=
'<select class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" '.($moreparam ? $moreparam :
'').
'>';
8076 if ((!isset($this->fields[$key][
'default'])) || empty($this->fields[$key][
'notnull']) || ($this->fields[$key][
'notnull'] != 1) || $nbchoice >= 2) {
8077 $out .=
'<option value="0"> </option>';
8080 $out .=
'</select>';
8081 } elseif ($type ==
'sellist') {
8083 if (!empty($conf->use_javascript_ajax) && !
getDolGlobalString(
'MAIN_EXTRAFIELDS_DISABLE_SELECT2')) {
8084 include_once DOL_DOCUMENT_ROOT.
'/core/lib/ajax.lib.php';
8085 $out .=
ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
8088 $out .=
'<select class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" '.($moreparam ? $moreparam :
'').
'>';
8089 if (is_array($param[
'options'])) {
8090 $tmpparamoptions = array_keys($param[
'options']);
8091 $paramoptions = preg_split(
'/[\r\n]+/', $tmpparamoptions[0]);
8093 $InfoFieldList = explode(
":", $paramoptions[0], 5);
8105 if (! empty($InfoFieldList[4])) {
8107 $parenthesisopen = 0;
8108 while (substr($InfoFieldList[4], $pos, 1) !==
'' && ($parenthesisopen || $pos == 0 || substr($InfoFieldList[4], $pos, 1) !=
':')) {
8109 if (substr($InfoFieldList[4], $pos, 1) ==
'(') {
8112 if (substr($InfoFieldList[4], $pos, 1) ==
')') {
8117 $tmpbefore = substr($InfoFieldList[4], 0, $pos);
8118 $tmpafter = substr($InfoFieldList[4], $pos + 1);
8120 $InfoFieldList[4] = $tmpbefore;
8121 if ($tmpafter !==
'') {
8122 $InfoFieldList = array_merge($InfoFieldList, explode(
':', $tmpafter));
8128 if (preg_match(
'/^\(?([a-z0-9]+)([=<>]+)(\d+)\)?$/i', $InfoFieldList[4], $reg)) {
8129 $InfoFieldList[4] =
'('.$reg[1].
':'.$reg[2].
':'.$reg[3].
')';
8140 $keyList = (empty($InfoFieldList[2]) ?
'rowid' : $InfoFieldList[2].
' as rowid');
8142 if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
8143 if (strpos($InfoFieldList[4],
'extra.') !==
false) {
8144 $keyList =
'main.'.$InfoFieldList[2].
' as rowid';
8146 $keyList = $InfoFieldList[2].
' as rowid';
8149 if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
8150 list($parentName, $parentField) = explode(
'|', $InfoFieldList[3]);
8151 if (!empty($InfoFieldList[4]) && strpos($InfoFieldList[4],
'extra.') !==
false) {
8152 $keyList .=
', main.'.$parentField;
8154 $keyList .=
', '.$parentField;
8158 $filter_categorie =
false;
8159 if (count($InfoFieldList) > 5) {
8160 if ($InfoFieldList[0] ==
'categorie') {
8161 $filter_categorie =
true;
8165 if (!$filter_categorie) {
8166 $fields_label = isset($InfoFieldList[1]) ? explode(
'|', $InfoFieldList[1]) : array();
8167 if (!empty($fields_label)) {
8169 $keyList .= implode(
', ', $fields_label);
8173 $sql =
"SELECT " . $keyList;
8174 $sql .=
" FROM " . $this->db->prefix() . $InfoFieldList[0];
8176 if (!empty($InfoFieldList[4])) {
8178 if (strpos($InfoFieldList[4],
'$SEL$') !==
false) {
8179 $InfoFieldList[4] = str_replace(
'$SEL$',
'SELECT', $InfoFieldList[4]);
8183 if (strpos($InfoFieldList[4],
'$ID$') !==
false && !empty($objectid)) {
8184 $InfoFieldList[4] = str_replace(
'$ID$', (
string) $objectid, $InfoFieldList[4]);
8186 $InfoFieldList[4] = str_replace(
'$ID$',
'0', $InfoFieldList[4]);
8191 if (strpos($InfoFieldList[4],
'extra') !==
false) {
8192 $sql .=
" as main, " . $this->db->sanitize($this->db->prefix() . $InfoFieldList[0]) .
"_extrafields as extra";
8193 $sqlwhere .=
" WHERE extra.fk_object = main." . $this->db->sanitize($InfoFieldList[2]);
8199 $sqlwhere .=
' WHERE 1=1';
8216 if (in_array($InfoFieldList[0], array(
'tablewithentity'))) {
8217 $sqlwhere .=
" AND entity = " . ((int) $conf->entity);
8222 if (isset($InfoFieldList[7]) && preg_match(
'/^[a-z0-9_\-,]+$/i', $InfoFieldList[7])) {
8223 $sql .=
" ORDER BY ".$this->db->escape($InfoFieldList[7]);
8225 $sql .=
" ORDER BY ".$this->db->sanitize(implode(
', ', $fields_label));
8227 $sql .=
' LIMIT ' .
getDolGlobalInt(
'MAIN_EXTRAFIELDS_LIMIT_SELLIST_SQL', 1000);
8230 dol_syslog(get_class($this) .
'::showInputField type=sellist', LOG_DEBUG);
8231 $resql = $this->db->query($sql);
8233 $out .=
'<option value="0"> </option>';
8234 $num = $this->db->num_rows($resql);
8238 $obj = $this->db->fetch_object($resql);
8242 $fields_label = explode(
'|', $InfoFieldList[1]);
8243 if (count($fields_label) > 1) {
8245 foreach ($fields_label as $field_toshow) {
8246 $labeltoshow .= $obj->$field_toshow .
' ';
8249 $labeltoshow = $obj->{$InfoFieldList[1]};
8251 $labeltoshow =
dol_trunc($labeltoshow, 45);
8253 if ($value == $obj->rowid) {
8254 foreach ($fields_label as $field_toshow) {
8255 $translabel = $langs->trans($obj->$field_toshow);
8256 if ($translabel != $obj->$field_toshow) {
8257 $labeltoshow =
dol_trunc($translabel) .
' ';
8259 $labeltoshow =
dol_trunc($obj->$field_toshow) .
' ';
8262 $out .=
'<option value="' . $obj->rowid .
'" selected>' . $labeltoshow .
'</option>';
8265 $translabel = $langs->trans($obj->{$InfoFieldList[1]});
8266 if ($translabel != $obj->{$InfoFieldList[1]}) {
8267 $labeltoshow =
dol_trunc($translabel, 18);
8269 $labeltoshow =
dol_trunc($obj->{$InfoFieldList[1]});
8272 if (empty($labeltoshow)) {
8273 $labeltoshow =
'(not defined)';
8275 if ($value == $obj->rowid) {
8276 $out .=
'<option value="' . $obj->rowid .
'" selected>' . $labeltoshow .
'</option>';
8279 if (!empty($InfoFieldList[3]) && $parentField) {
8280 $parent = $parentName .
':' . $obj->{$parentField};
8284 $out .=
'<option value="' . $obj->rowid .
'"';
8285 $out .= ($value == $obj->rowid ?
' selected' :
'');
8286 $out .= (!empty($parent) ?
' parent="' . $parent .
'"' :
'');
8287 $out .=
'>' . $labeltoshow .
'</option>';
8292 $this->db->free($resql);
8294 print
'Error in request ' . $sql .
' ' . $this->db->lasterror() .
'. Check setup of extra parameters.<br>';
8297 require_once DOL_DOCUMENT_ROOT.
'/categories/class/categorie.class.php';
8298 $categcode = $InfoFieldList[5];
8299 if (is_numeric($categcode)) {
8300 $tmpcategory =
new Categorie($this->db);
8301 $MAP_ID_TO_CODE = array_flip($tmpcategory->MAP_ID);
8302 $categcode = $MAP_ID_TO_CODE[(int) $categcode];
8305 $data = $form->select_all_categories($categcode,
'',
'parent', 64, $InfoFieldList[6], 1, 1);
8306 $out .=
'<option value="0"> </option>';
8307 foreach ($data as $data_key => $data_value) {
8308 $out .=
'<option value="' . $data_key .
'"';
8309 $out .= ($value == $data_key ?
' selected' :
'');
8310 $out .=
'>' . $data_value .
'</option>';
8314 $out .=
'</select>';
8315 } elseif ($type ==
'checkbox') {
8316 $value_arr = explode(
',', $value);
8317 $out = $form->multiselectarray($keyprefix.$key.$keysuffix, (empty($param[
'options']) ?
null : $param[
'options']), $value_arr, 0, 0, $morecss, 0,
'100%');
8318 } elseif ($type ==
'radio') {
8320 foreach ($param[
'options'] as $keyopt => $valopt) {
8321 $out .=
'<input class="flat '.$morecss.
'" type="radio" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" '.($moreparam ? $moreparam :
'');
8322 $out .=
' value="'.$keyopt.
'"';
8323 $out .=
' id="'.$keyprefix.$key.$keysuffix.
'_'.$keyopt.
'"';
8324 $out .= ($value == $keyopt ?
'checked' :
'');
8325 $out .=
'/><label for="'.$keyprefix.$key.$keysuffix.
'_'.$keyopt.
'">'.$valopt.
'</label><br>';
8327 } elseif ($type ==
'chkbxlst') {
8328 if (is_array($value)) {
8329 $value_arr = $value;
8331 $value_arr = explode(
',', $value);
8334 if (is_array($param[
'options'])) {
8335 $tmpparamoptions = array_keys($param[
'options']);
8336 $paramoptions = preg_split(
'/[\r\n]+/', $tmpparamoptions[0]);
8338 $InfoFieldList = explode(
":", $paramoptions[0], 5);
8350 if (! empty($InfoFieldList[4])) {
8352 $parenthesisopen = 0;
8353 while (substr($InfoFieldList[4], $pos, 1) !==
'' && ($parenthesisopen || $pos == 0 || substr($InfoFieldList[4], $pos, 1) !=
':')) {
8354 if (substr($InfoFieldList[4], $pos, 1) ==
'(') {
8357 if (substr($InfoFieldList[4], $pos, 1) ==
')') {
8362 $tmpbefore = substr($InfoFieldList[4], 0, $pos);
8363 $tmpafter = substr($InfoFieldList[4], $pos + 1);
8365 $InfoFieldList[4] = $tmpbefore;
8366 if ($tmpafter !==
'') {
8367 $InfoFieldList = array_merge($InfoFieldList, explode(
':', $tmpafter));
8372 if (preg_match(
'/^\(?([a-z0-9]+)([=<>]+)(\d+)\)?$/i', $InfoFieldList[4], $reg)) {
8373 $InfoFieldList[4] =
'('.$reg[1].
':'.$reg[2].
':'.$reg[3].
')';
8381 '@phan-var-force array{0:string,1:string,2:string,3:string,3:string,5:string,6:string} $InfoFieldList';
8386 $keyList = (empty($InfoFieldList[2]) ?
'rowid' : $InfoFieldList[2].
' as rowid');
8388 if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
8389 if (strpos($InfoFieldList[4],
'extra.') !==
false) {
8390 $keyList =
'main.'.$InfoFieldList[2].
' as rowid';
8392 $keyList = $InfoFieldList[2].
' as rowid';
8395 if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
8396 list($parentName, $parentField) = explode(
'|', $InfoFieldList[3]);
8397 if (!empty($InfoFieldList[4]) && strpos($InfoFieldList[4],
'extra.') !==
false) {
8398 $keyList .=
', main.'.$parentField;
8400 $keyList .=
', '.$parentField;
8404 $filter_categorie =
false;
8405 if (count($InfoFieldList) > 5) {
8406 if ($InfoFieldList[0] ==
'categorie') {
8407 $filter_categorie =
true;
8412 if (!$filter_categorie) {
8413 $fields_label = explode(
'|', $InfoFieldList[1]);
8414 if (is_array($fields_label)) {
8416 $keyList .= implode(
', ', $fields_label);
8420 $sql =
"SELECT " . $keyList;
8421 $sql .=
' FROM ' . $this->db->prefix() . $InfoFieldList[0];
8423 if (!empty($InfoFieldList[4])) {
8425 if (strpos($InfoFieldList[4],
'$SEL$') !==
false) {
8426 $InfoFieldList[4] = str_replace(
'$SEL$',
'SELECT', $InfoFieldList[4]);
8430 if (strpos($InfoFieldList[4],
'$ID$') !==
false && !empty($objectid)) {
8431 $InfoFieldList[4] = str_replace(
'$ID$', (
string) $objectid, $InfoFieldList[4]);
8433 $InfoFieldList[4] = str_replace(
'$ID$',
'0', $InfoFieldList[4]);
8438 if (strpos($InfoFieldList[4],
'extra') !==
false) {
8439 $sql .=
' as main, ' . $this->db->sanitize($this->db->prefix() . $InfoFieldList[0]) .
'_extrafields as extra';
8440 $sqlwhere .=
" WHERE extra.fk_object = main." . $this->db->sanitize($InfoFieldList[2]);
8446 $sqlwhere .=
' WHERE 1=1';
8463 if (in_array($InfoFieldList[0], array(
'tablewithentity'))) {
8464 $sqlwhere .=
" AND entity = " . ((int) $conf->entity);
8471 dol_syslog(get_class($this) .
'::showInputField type=chkbxlst', LOG_DEBUG);
8473 $resql = $this->db->query($sql);
8475 $num = $this->db->num_rows($resql);
8482 $obj = $this->db->fetch_object($resql);
8486 $fields_label = explode(
'|', $InfoFieldList[1]);
8487 if (count($fields_label) > 1) {
8489 foreach ($fields_label as $field_toshow) {
8490 $labeltoshow .= $obj->$field_toshow .
' ';
8493 $labeltoshow = $obj->{$InfoFieldList[1]};
8495 $labeltoshow =
dol_trunc($labeltoshow, 45);
8497 if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
8498 foreach ($fields_label as $field_toshow) {
8499 $translabel = $langs->trans($obj->$field_toshow);
8500 if ($translabel != $obj->$field_toshow) {
8501 $labeltoshow =
dol_trunc($translabel, 18) .
' ';
8503 $labeltoshow =
dol_trunc($obj->$field_toshow, 18) .
' ';
8507 $data[$obj->rowid] = $labeltoshow;
8510 $translabel = $langs->trans($obj->{$InfoFieldList[1]});
8511 if ($translabel != $obj->{$InfoFieldList[1]}) {
8512 $labeltoshow =
dol_trunc($translabel, 18);
8514 $labeltoshow =
dol_trunc($obj->{$InfoFieldList[1]}, 18);
8517 if (empty($labeltoshow)) {
8518 $labeltoshow =
'(not defined)';
8521 if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
8522 $data[$obj->rowid] = $labeltoshow;
8525 if (!empty($InfoFieldList[3]) && $parentField) {
8526 $parent = $parentName .
':' . $obj->{$parentField};
8530 $data[$obj->rowid] = $labeltoshow;
8535 $this->db->free($resql);
8537 $out = $form->multiselectarray($keyprefix . $key . $keysuffix, $data, $value_arr, 0, 0, $morecss, 0,
'100%');
8539 print
'Error in request ' . $sql .
' ' . $this->db->lasterror() .
'. Check setup of extra parameters.<br>';
8542 require_once DOL_DOCUMENT_ROOT.
'/categories/class/categorie.class.php';
8543 $categcode = $InfoFieldList[5];
8544 if (is_numeric($categcode)) {
8545 $tmpcategory =
new Categorie($this->db);
8546 $MAP_ID_TO_CODE = array_flip($tmpcategory->MAP_ID);
8547 $categcode = $MAP_ID_TO_CODE[(int) $categcode];
8550 $data = $form->select_all_categories($categcode,
'',
'parent', 64, $InfoFieldList[6], 1, 1);
8551 $out = $form->multiselectarray($keyprefix . $key . $keysuffix, $data, $value_arr, 0, 0, $morecss, 0,
'100%');
8554 } elseif ($type ==
'link') {
8557 $param_list = array_keys($param[
'options']);
8558 $param_list_array = explode(
':', $param_list[0], 4);
8560 $showempty = (($required && $default !=
'') ? 0 : 1);
8562 if (!preg_match(
'/search_/', $keyprefix)) {
8563 if (!empty($param_list_array[2])) {
8565 if (!empty($this->fields[$key][
'picto'])) {
8566 $morecss .=
' widthcentpercentminusxx';
8568 $morecss .=
' widthcentpercentminusx';
8572 if (!empty($this->fields[$key][
'picto'])) {
8573 $morecss .=
' widthcentpercentminusx';
8582 $objectfield = $val;
8585 $out = $form->selectForForms($param_list_array[0], $keyprefix.$key.$keysuffix, (
int) $value, $showempty,
'',
'', $morecss, $moreparam, 0, (empty($val[
'disabled']) ? 0 : 1),
'', $objectfield);
8587 if (!empty($param_list_array[2])) {
8588 if ((!GETPOSTISSET(
'backtopage') || strpos(
GETPOST(
'backtopage'), $_SERVER[
'PHP_SELF']) === 0)
8589 && empty($val[
'disabled']) && empty($nonewbutton)) {
8590 list($class, $classfile) = explode(
':', $param_list[0]);
8591 if (file_exists(
dol_buildpath(dirname(dirname($classfile)).
'/card.php'))) {
8592 $url_path =
dol_buildpath(dirname(dirname($classfile)).
'/card.php', 1);
8594 $url_path =
dol_buildpath(dirname(dirname($classfile)).
'/'.strtolower($class).
'_card.php', 1);
8596 $paramforthenewlink =
'';
8597 $paramforthenewlink .= (GETPOSTISSET(
'action') ?
'&action='.GETPOST(
'action',
'aZ09') :
'');
8598 $paramforthenewlink .= (GETPOSTISSET(
'id') ?
'&id='.GETPOSTINT(
'id') :
'');
8599 $paramforthenewlink .= (GETPOSTISSET(
'origin') ?
'&origin='.GETPOST(
'origin',
'aZ09') :
'');
8600 $paramforthenewlink .= (GETPOSTISSET(
'originid') ?
'&originid='.GETPOSTINT(
'originid') :
'');
8601 $paramforthenewlink .=
'&fk_'.strtolower($class).
'=--IDFORBACKTOPAGE--';
8603 $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>';
8606 } elseif ($type ==
'password') {
8608 if ($keyprefix.$key.$keysuffix ==
'pass_crypted') {
8609 $out =
'<input type="'.($keyprefix ==
'search_' ?
'text' :
'password').
'" class="flat '.$morecss.
'" name="pass" id="pass" value="" '.($moreparam ? $moreparam :
'').
'>';
8610 $out .=
'<input type="hidden" name="pass_crypted" id="pass_crypted" value="'.$value.
'" '.($moreparam ? $moreparam :
'').
'>';
8612 $out =
'<input type="'.($keyprefix ==
'search_' ?
'text' :
'password').
'" class="flat '.$morecss.
'" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.$value.
'" '.($moreparam ? $moreparam :
'').
'>';
8614 } elseif ($type ==
'array') {
8616 $newval[
'type'] =
'varchar(256)';
8619 if (!empty($value)) {
8620 foreach ($value as $option) {
8621 $out .=
'<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).
'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
8622 $out .= $this->showInputField($newval, $keyprefix.$key.$keysuffix.
'[]', $option, $moreparam,
'',
'', $morecss).
'<br></span>';
8625 $out .=
'<a id="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).
'_add" href="javascript:;"><span class="fa fa-plus-circle valignmiddle"></span></a>';
8627 $newInput =
'<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).
'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
8628 $newInput .= $this->showInputField($newval, $keyprefix.$key.$keysuffix.
'[]',
'', $moreparam,
'',
'', $morecss).
'<br></span>';
8630 if (!empty($conf->use_javascript_ajax)) {
8632 <script nonce="'.getNonce().
'">
8633 $(document).ready(function() {
8634 $("a#'.
dol_escape_js($keyprefix.$key.$keysuffix).
'_add").click(function() {
8638 $(document).on("click", "a.'.
dol_escape_js($keyprefix.$key.$keysuffix).
'_del", function() {
8639 $(this).parent().remove();
8645 if (!empty($hidden)) {
8646 $out =
'<input type="hidden" value="'.$value.
'" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'"/>';
8649 if ($isDependList == 1) {
8650 $out .= $this->getJSListDependancies(
'_common');
8658 if (!empty($fieldValidationErrorMsg) && function_exists(
'getFieldErrorIcon')) {
8659 $out .=
' '.getFieldErrorIcon($fieldValidationErrorMsg);
8678 public function showOutputField($val, $key, $value, $moreparam =
'', $keysuffix =
'', $keyprefix =
'', $morecss =
'')
8680 global $conf, $langs, $form;
8684 if (!is_object($form)) {
8685 require_once DOL_DOCUMENT_ROOT.
'/core/class/html.form.class.php';
8686 $form =
new Form($this->db);
8690 $type = empty($val[
'type']) ?
'' : $val[
'type'];
8691 $size = empty($val[
'css']) ?
'' : $val[
'css'];
8695 if (preg_match(
'/varchar\((\d+)\)/', $type, $reg)) {
8698 } elseif (preg_match(
'/varchar/', $type)) {
8701 if (!empty($val[
'arrayofkeyval']) && is_array($val[
'arrayofkeyval'])) {
8703 if (empty($this->fields[$key][
'multiinput'])) {
8704 $type = (($this->fields[$key][
'type'] ==
'checkbox') ? $this->fields[$key][
'type'] :
'select');
8707 if (isset($val[
'type']) && preg_match(
'/^integer:(.*):(.*)/i', $val[
'type'], $reg)) {
8711 $default = empty($val[
'default']) ?
'' : $val[
'default'];
8712 $computed = empty($val[
'computed']) ?
'' : $val[
'computed'];
8713 $unique = empty($val[
'unique']) ?
'' : $val[
'unique'];
8714 $required = empty($val[
'required']) ?
'' : $val[
'required'];
8716 $param[
'options'] = array();
8718 if (!empty($val[
'arrayofkeyval']) && is_array($val[
'arrayofkeyval'])) {
8719 $param[
'options'] = $val[
'arrayofkeyval'];
8721 if (isset($val[
'type']) && preg_match(
'/^integer:([^:]*):([^:]*)/i', $val[
'type'], $reg)) {
8723 $stringforoptions = $reg[1].
':'.$reg[2];
8725 if ($reg[1] ==
'User') {
8726 $stringforoptions .=
':#getnomurlparam1=-1';
8728 $param[
'options'] = array($stringforoptions => $stringforoptions);
8729 } elseif (isset($val[
'type']) && preg_match(
'/^sellist:(.*):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
8730 $param[
'options'] = array($reg[1].
':'.$reg[2].
':'.$reg[3].
':'.$reg[4] =>
'N');
8732 } elseif (isset($val[
'type']) && preg_match(
'/^sellist:(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
8733 $param[
'options'] = array($reg[1].
':'.$reg[2].
':'.$reg[3] =>
'N');
8735 } elseif (isset($val[
'type']) && preg_match(
'/^sellist:(.*):(.*)/i', $val[
'type'], $reg)) {
8736 $param[
'options'] = array($reg[1].
':'.$reg[2] =>
'N');
8738 } elseif (isset($val[
'type']) && preg_match(
'/^chkbxlst:(.*)/i', $val[
'type'], $reg)) {
8739 $param[
'options'] = array($reg[1] =>
'N');
8741 } elseif (isset($val[
'type']) && preg_match(
'/stars\((\d+)\)/', $val[
'type'], $reg)) {
8742 $param[
'options'] = array();
8747 $langfile = empty($val[
'langfile']) ?
'' : $val[
'langfile'];
8748 $list = (empty($val[
'list']) ?
'' : $val[
'list']);
8749 $help = (empty($val[
'help']) ?
'' : $val[
'help']);
8750 $hidden = (($val[
'visible'] == 0) ? 1 : 0);
8760 $value =
dol_eval((
string) $computed, 1, 0,
'2');
8763 if (empty($morecss)) {
8764 if ($type ==
'date') {
8765 $morecss =
'minwidth100imp';
8766 } elseif ($type ==
'datetime' || $type ==
'timestamp') {
8767 $morecss =
'minwidth200imp';
8768 } elseif (in_array($type, array(
'int',
'double',
'price'))) {
8769 $morecss =
'maxwidth75';
8770 } elseif ($type ==
'url') {
8771 $morecss =
'minwidth400';
8772 } elseif ($type ==
'boolean') {
8775 if (is_numeric($size) && round((
float) $size) < 12) {
8776 $morecss =
'minwidth100';
8777 } elseif (is_numeric($size) && round((
float) $size) <= 48) {
8778 $morecss =
'minwidth200';
8780 $morecss =
'minwidth400';
8786 if (in_array($key, array(
'rowid',
'ref')) && method_exists($this,
'getNomUrl')) {
8788 if ($key !=
'rowid' || empty($this->fields[
'ref'])) {
8789 $value = $this->getNomUrl(1,
'', 0,
'', 1);
8791 } elseif ($key ==
'status' && method_exists($this,
'getLibStatut')) {
8792 $value = $this->getLibStatut(3);
8793 } elseif ($type ==
'date') {
8794 if (!empty($value)) {
8799 } elseif ($type ==
'datetime' || $type ==
'timestamp') {
8800 if (!empty($value)) {
8805 } elseif ($type ==
'duration') {
8806 include_once DOL_DOCUMENT_ROOT.
'/core/lib/date.lib.php';
8807 if (!is_null($value) && $value !==
'') {
8810 } elseif ($type ==
'double' || $type ==
'real') {
8811 if (!is_null($value) && $value !==
'') {
8812 $value =
price($value);
8814 } elseif ($type ==
'boolean') {
8816 if (!empty($value)) {
8817 $checked =
' checked ';
8820 $value =
'<input type="checkbox" '.$checked.
' '.($moreparam ? $moreparam :
'').
' readonly disabled>';
8822 $value =
yn($value ? 1 : 0);
8824 } elseif ($type ==
'mail' || $type ==
'email') {
8826 } elseif ($type ==
'url') {
8828 } elseif ($type ==
'phone') {
8829 $value =
dol_print_phone((
string) $value,
'', 0, 0,
'',
' ',
'phone');
8830 } elseif ($type ==
'ip') {
8832 } elseif ($type ==
'stars') {
8833 $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 :
'').
'>';
8834 $value .=
'<div class="star-selection" id="'.$keyprefix.$key.$keysuffix.$this->id.
'_selection">';
8836 while ($i <= $size) {
8837 $value .=
'<span class="star" data-value="'.$i.
'">'.
img_picto(
'',
'fontawesome_star_fas').
'</span>';
8842 $(document).ready(function() { /* commonobject.class.php 2 */
8843 let container = $("#'.$keyprefix.$key.$keysuffix.$this->id.
'_selection");
8844 let selectedStars = parseInt($("#'.$keyprefix.$key.$keysuffix.$this->id.
'").val()) || 0;
8845 container.find(".star").each(function() {
8846 $(this).toggleClass("active", $(this).data("value") <= selectedStars);
8848 container.find(".star").on("mouseover", function() {
8849 let selectedStar = $(this).data("value");
8850 container.find(".star").each(function() {
8851 $(this).toggleClass("active", $(this).data("value") <= selectedStar);
8854 container.on("mouseout", function() {
8855 container.find(".star").each(function() {
8856 $(this).toggleClass("active", $(this).data("value") <= selectedStars);
8859 container.find(".star").off("click").on("click", function() {
8860 selectedStars = $(this).data("value");
8861 if (selectedStars == 1 && $("#'.$keyprefix.$key.$keysuffix.$this->id.
'").val() == 1) {
8864 container.find("#'.$keyprefix.$key.$keysuffix.$this->id.
'").val(selectedStars);
8865 container.find(".star").each(function() {
8866 $(this).toggleClass("active", $(this).data("value") <= selectedStars);
8869 url: "ajax/'.$this->element.
'.php",
8872 objectId: "'.$this->
id.
'",
8873 field: "'.$keyprefix.$key.$keysuffix.
'",
8874 value: selectedStars,
8877 success: function(response) {
8878 var res = JSON.parse(response);
8879 console[res.status === "success" ? "log" : "error"](res.message);
8881 error: function(xhr, status, error) {
8882 console.log("Ajax request failed while updating '.$keyprefix.$key.$keysuffix.
':", error);
8888 } elseif ($type ==
'price') {
8889 if (!is_null($value) && $value !==
'') {
8890 $value =
price($value, 0, $langs, 0, 0, -1, $conf->currency);
8892 } elseif ($type ==
'select') {
8893 $value = isset($param[
'options'][(
string) $value]) ? $param[
'options'][(string) $value] :
'';
8894 if (strpos($value,
"|") !==
false) {
8895 $value = $langs->trans(explode(
'|', $value)[0]);
8896 } elseif (! is_numeric($value)) {
8897 $value = $langs->trans($value);
8899 } elseif ($type ==
'sellist') {
8900 $param_list = array_keys($param[
'options']);
8901 $InfoFieldList = explode(
":", $param_list[0]);
8903 $selectkey =
"rowid";
8906 if (count($InfoFieldList) > 2 && !empty($InfoFieldList[2])) {
8907 $selectkey = $InfoFieldList[2];
8908 $keyList = $InfoFieldList[2].
' as rowid';
8911 $fields_label = explode(
'|', $InfoFieldList[1]);
8912 if (is_array($fields_label)) {
8914 $keyList .= implode(
', ', $fields_label);
8917 $filter_categorie =
false;
8918 if (count($InfoFieldList) > 5) {
8919 if ($InfoFieldList[0] ==
'categorie') {
8920 $filter_categorie =
true;
8924 $sql =
"SELECT ".$keyList;
8925 $sql .=
' FROM '.$this->db->prefix().$InfoFieldList[0];
8926 if (isset($InfoFieldList[4]) && strpos($InfoFieldList[4],
'extra') !==
false) {
8929 if ($selectkey ==
'rowid' && empty($value)) {
8930 $sql .=
" WHERE ".$selectkey.
" = 0";
8931 } elseif ($selectkey ==
'rowid') {
8932 $sql .=
" WHERE ".$selectkey.
" = ".((int) $value);
8934 $sql .=
" WHERE ".$selectkey.
" = '".$this->db->escape((
string) $value).
"'";
8939 dol_syslog(get_class($this).
':showOutputField:$type=sellist', LOG_DEBUG);
8940 $resql = $this->db->query($sql);
8942 if (!$filter_categorie) {
8944 $numrows = $this->db->num_rows($resql);
8946 $obj = $this->db->fetch_object($resql);
8949 $fields_label = explode(
'|', $InfoFieldList[1]);
8951 if (is_array($fields_label) && count($fields_label) > 1) {
8952 foreach ($fields_label as $field_toshow) {
8954 if (!empty($obj->$field_toshow)) {
8955 $translabel = $langs->trans($obj->$field_toshow);
8957 if ($translabel != $field_toshow) {
8958 $value .=
dol_trunc($translabel, 18) .
' ';
8960 $value .= $obj->$field_toshow .
' ';
8965 if (!empty($obj->{$InfoFieldList[1]})) {
8966 $translabel = $langs->trans($obj->{$InfoFieldList[1]});
8968 if ($translabel != $obj->{$InfoFieldList[1]}) {
8971 $value = $obj->{$InfoFieldList[1]};
8976 require_once DOL_DOCUMENT_ROOT .
'/categories/class/categorie.class.php';
8979 $obj = $this->db->fetch_object($resql);
8981 $c->fetch($obj->rowid);
8982 $ways =
$c->print_all_ways();
8983 foreach ($ways as $way) {
8984 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories"' . (
$c->color ?
' style="background: #' .
$c->color .
';"' :
' style="background: #aaa"') .
'>' .
img_object(
'',
'category') .
' ' . $way .
'</li>';
8986 $value =
'<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(
' ', $toprint).
'</ul></div>';
8989 dol_syslog(get_class($this).
'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
8991 } elseif ($type ==
'radio') {
8992 $value = $param[
'options'][(string) $value];
8993 } elseif ($type ==
'checkbox') {
8994 $value_arr = explode(
',', (
string) $value);
8996 if (is_array($value_arr) && count($value_arr) > 0) {
8998 foreach ($value_arr as $keyval => $valueval) {
8999 if (!empty($valueval)) {
9000 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' . $param[
'options'][$valueval] .
'</li>';
9003 if (!empty($toprint)) {
9004 $value =
'<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">' . implode(
' ', $toprint) .
'</ul></div>';
9007 } elseif ($type ==
'chkbxlst') {
9008 $value_arr = (isset($value) ? explode(
',', $value) : array());
9010 $param_list = array_keys($param[
'options']);
9011 $InfoFieldList = explode(
":", $param_list[0]);
9013 $selectkey =
"rowid";
9016 if (count($InfoFieldList) >= 3) {
9017 $selectkey = $InfoFieldList[2];
9018 $keyList = $InfoFieldList[2].
' as rowid';
9021 $fields_label = explode(
'|', $InfoFieldList[1]);
9022 if (is_array($fields_label)) {
9024 $keyList .= implode(
', ', $fields_label);
9027 $filter_categorie =
false;
9028 if (count($InfoFieldList) > 5) {
9029 if ($InfoFieldList[0] ==
'categorie') {
9030 $filter_categorie =
true;
9034 $sql =
"SELECT ".$keyList;
9035 $sql .=
' FROM '.$this->db->prefix().$InfoFieldList[0];
9036 if (isset($InfoFieldList[4]) && strpos($InfoFieldList[4],
'extra') !==
false) {
9042 dol_syslog(get_class($this).
':showOutputField:$type=chkbxlst', LOG_DEBUG);
9043 $resql = $this->db->query($sql);
9045 if (!$filter_categorie) {
9048 while ($obj = $this->db->fetch_object($resql)) {
9050 $fields_label = explode(
'|', $InfoFieldList[1]);
9051 if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
9052 if (is_array($fields_label) && count($fields_label) > 1) {
9053 foreach ($fields_label as $field_toshow) {
9055 if (!empty($obj->$field_toshow)) {
9056 $translabel = $langs->trans($obj->$field_toshow);
9058 if ($translabel != $field_toshow) {
9059 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' .
dol_trunc($translabel, 18) .
'</li>';
9061 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' . $obj->$field_toshow .
'</li>';
9066 if (!empty($obj->{$InfoFieldList[1]})) {
9067 $translabel = $langs->trans($obj->{$InfoFieldList[1]});
9069 if ($translabel != $obj->{$InfoFieldList[1]}) {
9070 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' .
dol_trunc($translabel, 18) .
'</li>';
9072 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' . $obj->{$InfoFieldList[1]} .
'</li>';
9078 require_once DOL_DOCUMENT_ROOT .
'/categories/class/categorie.class.php';
9081 while ($obj = $this->db->fetch_object($resql)) {
9082 if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
9084 $c->fetch($obj->rowid);
9085 $ways =
$c->print_all_ways();
9086 foreach ($ways as $way) {
9087 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories"' . (
$c->color ?
' style="background: #' .
$c->color .
';"' :
' style="background: #aaa"') .
'>' .
img_object(
'',
'category') .
' ' . $way .
'</li>';
9092 $value =
'<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(
' ', $toprint).
'</ul></div>';
9094 dol_syslog(get_class($this).
'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
9096 } elseif ($type ==
'link') {
9101 $param_list = array_keys($param[
'options']);
9105 $InfoFieldList = explode(
":", $param_list[0]);
9107 $classname = $InfoFieldList[0];
9108 $classpath = $InfoFieldList[1];
9111 $getnomurlparam = 3;
9112 $getnomurlparam2 =
'';
9114 if (preg_match(
'/#getnomurlparam1=([^#]*)/', $param_list[0], $regtmp)) {
9115 $getnomurlparam = $regtmp[1];
9117 if (preg_match(
'/#getnomurlparam2=([^#]*)/', $param_list[0], $regtmp)) {
9118 $getnomurlparam2 = $regtmp[1];
9121 if (!empty($classpath)) {
9124 if ($classname && !class_exists($classname)) {
9128 if ($element_prop) {
9129 $classname = $element_prop[
'classname'];
9134 if ($classname && class_exists($classname)) {
9135 $object =
new $classname($this->db);
9136 '@phan-var-force CommonObject $object';
9137 if (
$object->element ===
'product') {
9138 '@phan-var-force Product $object';
9139 $result =
$object->fetch((
int) $value,
'',
'',
'', 0, 1, 1);
9141 $result =
$object->fetch($value);
9144 if (
$object->element ===
'product') {
9145 '@phan-var-force Product $object';
9146 $get_name_url_param_arr = array($getnomurlparam, $getnomurlparam2, 0, -1, 0,
'', 0);
9147 if (isset($val[
'get_name_url_params'])) {
9148 $get_name_url_params = explode(
':', $val[
'get_name_url_params']);
9149 if (!empty($get_name_url_params)) {
9150 $param_num_max = count($get_name_url_param_arr) - 1;
9151 foreach ($get_name_url_params as $param_num => $param_value) {
9152 if ($param_num > $param_num_max) {
9155 $get_name_url_param_arr[$param_num] = $param_value;
9163 $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]);
9165 $value =
$object->getNomUrl($getnomurlparam, $getnomurlparam2);
9172 dol_syslog(
'Error bad setup of extrafield', LOG_WARNING);
9173 return 'Error bad setup of extrafield';
9178 } elseif ($type ==
'password') {
9179 $value =
'<span class="opacitymedium">'.$langs->trans(
"Encrypted").
'</span>';
9181 } elseif ($type ==
'array') {
9182 if (is_array($value)) {
9183 $value = implode(
'<br>', $value);
9185 dol_syslog(__METHOD__.
' Expected array from dol_eval, but got '.gettype($value), LOG_ERR);
9186 return 'Error unexpected result from code evaluation';
9189 if (!empty($value) && preg_match(
'/^text/', (
string) $type) && !preg_match(
'/search_/', $keyprefix) && !empty($param[
'options'])) {
9190 $value = str_replace(
',',
"\n", $value);
9198 return is_null($out) ?
'' : $out;
9210 unset($this->validateFieldsErrors[$fieldKey]);
9224 $msg = $langs->trans(
"UnknownError");
9227 $this->error = $this->validateFieldsErrors[$fieldKey] = $msg;
9238 if (!empty($this->validateFieldsErrors[$fieldKey])) {
9239 return $this->validateFieldsErrors[$fieldKey];
9256 if (!class_exists(
'Validate')) {
9257 require_once DOL_DOCUMENT_ROOT .
'/core/class/validate.class.php';
9260 $this->clearFieldError($fieldKey);
9262 if (!array_key_exists($fieldKey, $fields) || !is_array($fields[$fieldKey])) {
9263 $this->setFieldError($fieldKey, $langs->trans(
'FieldNotFoundInObject'));
9267 $val = $fields[$fieldKey];
9270 $param[
'options'] = array();
9271 $type = $val[
'type'];
9274 if (isset($val[
'notnull']) && $val[
'notnull'] === 1) {
9288 if (preg_match(
'/varchar\((\d+)\)/', $type, $reg)) {
9290 $maxSize = (int) $reg[1];
9291 } elseif (preg_match(
'/varchar/', $type)) {
9295 if (!empty($val[
'arrayofkeyval']) && is_array($val[
'arrayofkeyval'])) {
9299 if (!empty($val[
'type']) && preg_match(
'/^integer:(.*):(.*)/i', $val[
'type'], $reg)) {
9303 if (!empty($val[
'arrayofkeyval']) && is_array($val[
'arrayofkeyval'])) {
9304 $param[
'options'] = $val[
'arrayofkeyval'];
9307 if (preg_match(
'/^integer:(.*):(.*)/i', $val[
'type'], $reg)) {
9309 $param[
'options'] = array($reg[1].
':'.$reg[2] => $reg[1].
':'.$reg[2]);
9310 } elseif (preg_match(
'/^sellist:(.*):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
9311 $param[
'options'] = array($reg[1].
':'.$reg[2].
':'.$reg[3].
':'.$reg[4] =>
'N');
9313 } elseif (preg_match(
'/^sellist:(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
9314 $param[
'options'] = array($reg[1].
':'.$reg[2].
':'.$reg[3] =>
'N');
9316 } elseif (preg_match(
'/^sellist:(.*):(.*)/i', $val[
'type'], $reg)) {
9317 $param[
'options'] = array($reg[1].
':'.$reg[2] =>
'N');
9326 $validate =
new Validate($this->db, $langs);
9336 if ($required && !$validate->isNotEmptyString($fieldValue)) {
9337 $this->setFieldError($fieldKey, $validate->error);
9339 } elseif (!$required && !$validate->isNotEmptyString($fieldValue)) {
9345 if (!empty($maxSize) && !$validate->isMaxLength($fieldValue, $maxSize)) {
9346 $this->setFieldError($fieldKey, $validate->error);
9351 if (!empty($minSize) && !$validate->isMinLength($fieldValue, $minSize)) {
9352 $this->setFieldError($fieldKey, $validate->error);
9360 if (in_array($type, array(
'date',
'datetime',
'timestamp'))) {
9361 if (!$validate->isTimestamp($fieldValue)) {
9362 $this->setFieldError($fieldKey, $validate->error);
9367 } elseif ($type ==
'duration') {
9368 if (!$validate->isDuration($fieldValue)) {
9369 $this->setFieldError($fieldKey, $validate->error);
9374 } elseif (in_array($type, array(
'double',
'real',
'price'))) {
9376 if (!$validate->isNumeric($fieldValue)) {
9377 $this->setFieldError($fieldKey, $validate->error);
9382 } elseif ($type ==
'boolean') {
9383 if (!$validate->isBool($fieldValue)) {
9384 $this->setFieldError($fieldKey, $validate->error);
9389 } elseif ($type ==
'mail' || $type ==
'email') {
9390 if (!$validate->isEmail($fieldValue)) {
9391 $this->setFieldError($fieldKey, $validate->error);
9394 } elseif ($type ==
'url') {
9395 if (!$validate->isUrl($fieldValue)) {
9396 $this->setFieldError($fieldKey, $validate->error);
9401 } elseif ($type ==
'phone') {
9402 if (!$validate->isPhone($fieldValue)) {
9403 $this->setFieldError($fieldKey, $validate->error);
9408 } elseif ($type ==
'select' || $type ==
'radio') {
9409 if (!isset($param[
'options'][$fieldValue])) {
9410 $this->error = $langs->trans(
'RequireValidValue');
9415 } elseif ($type ==
'sellist' || $type ==
'chkbxlst') {
9416 $param_list = array_keys($param[
'options']);
9417 $InfoFieldList = explode(
":", $param_list[0]);
9418 $value_arr = explode(
',', $fieldValue);
9419 $value_arr = array_map(array($this->db,
'escape'), $value_arr);
9421 $selectkey =
"rowid";
9422 if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
9423 $selectkey = $InfoFieldList[2];
9426 if (!$validate->isInDb($value_arr, $InfoFieldList[0], $selectkey)) {
9427 $this->setFieldError($fieldKey, $validate->error);
9432 } elseif ($type ==
'link') {
9433 $param_list = array_keys($param[
'options']);
9434 $InfoFieldList = explode(
":", $param_list[0]);
9435 $classname = $InfoFieldList[0];
9436 $classpath = $InfoFieldList[1];
9437 if (!$validate->isFetchable((
int) $fieldValue, $classname, $classpath)) {
9438 $lastIsFetchableError = $validate->error;
9441 if ($validate->isFetchableElement((
int) $fieldValue, $classname)) {
9445 $this->setFieldError($fieldKey, $lastIsFetchableError);
9469 public function showOptionals($extrafields, $mode =
'view', $params =
null, $keysuffix =
'', $keyprefix =
'', $onetrtd =
'', $display_type =
'card')
9471 global $db, $conf, $langs, $action, $form, $hookmanager;
9473 if (!is_object($form)) {
9474 $form =
new Form($db);
9476 if (!is_object($extrafields)) {
9477 dol_syslog(
'Bad parameter extrafields for showOptionals', LOG_ERR);
9478 return 'Bad parameter extrafields for showOptionals';
9480 if (!is_array($extrafields->attributes[$this->table_element])) {
9481 dol_syslog(
"extrafields->attributes was not loaded with extrafields->fetch_name_optionals_label(table_element);", LOG_WARNING);
9486 $parameters = array(
'mode' => $mode,
'params' => $params,
'keysuffix' => $keysuffix,
'keyprefix' => $keyprefix,
'display_type' => $display_type);
9487 $reshook = $hookmanager->executeHooks(
'showOptionals', $parameters, $this, $action);
9488 $hookResPrint = $hookmanager->resPrint;
9490 if (empty($reshook)) {
9491 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) {
9493 $out .=
'<!-- commonobject:showOptionals --> ';
9496 $nbofextrafieldsshown = 0;
9499 $lastseparatorkeyfound =
'';
9500 $extrafields_collapse_num =
'';
9501 $extrafields_collapse_num_old =
'';
9504 foreach ($extrafields->attributes[$this->table_element][
'label'] as $key => $label) {
9508 if (is_array($params) && array_key_exists(
'onlykey', $params) && $key != $params[
'onlykey']) {
9514 if ($enabled && isset($extrafields->attributes[$this->table_element][
'enabled'][$key])) {
9515 $enabled = (int)
dol_eval((
string) $extrafields->attributes[$this->table_element][
'enabled'][$key], 1, 1,
'2');
9517 if (empty($enabled)) {
9522 if (isset($extrafields->attributes[$this->table_element][
'list'][$key])) {
9523 $visibility = (int)
dol_eval((
string) $extrafields->attributes[$this->table_element][
'list'][$key], 1, 1,
'2');
9527 if ($perms && isset($extrafields->attributes[$this->table_element][
'perms'][$key])) {
9528 $perms = (int)
dol_eval((
string) $extrafields->attributes[$this->table_element][
'perms'][$key], 1, 1,
'2');
9531 if (($mode ==
'create') && !in_array(abs($visibility), array(1, 3))) {
9533 } elseif (($mode ==
'edit') && !in_array(abs($visibility), array(1, 3, 4))) {
9537 $ef_name =
'options_' . $key;
9538 $ef_value = $this->array_options[$ef_name] ??
'';
9539 $out .=
'<input type="hidden" name="' . $ef_name .
'" id="' . $ef_name .
'" value="' .
dolPrintHTMLForAttribute($ef_value) .
'" />' .
"\n";
9541 } elseif ($mode ==
'view' && empty($visibility)) {
9544 if (empty($perms)) {
9549 if (!empty($extrafields->attributes[$this->table_element][
'langfile'][$key])) {
9550 $langs->load($extrafields->attributes[$this->table_element][
'langfile'][$key]);
9555 if (is_array($params) && count($params) > 0 && $display_type ==
'card') {
9556 if (array_key_exists(
'cols', $params)) {
9557 $colspan = $params[
'cols'];
9558 } elseif (array_key_exists(
'colspan', $params)) {
9560 if (preg_match(
'/colspan="(\d+)"/', $params[
'colspan'], $reg)) {
9563 $colspan = $params[
'colspan'];
9567 $colspan = intval($colspan);
9571 $value = ((!empty($this->array_options) && array_key_exists(
"options_".$key.$keysuffix, $this->array_options)) ? $this->array_options[
"options_".$key.$keysuffix] :
null);
9577 $check =
'alphanohtml';
9578 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'html',
'text'))) {
9579 $check =
'restricthtml';
9581 $getposttemp =
GETPOST($keyprefix.
'options_'.$key.$keysuffix, $check, 3);
9583 if (is_array($getposttemp) || $getposttemp !=
'' || GETPOSTISSET($keyprefix.
'options_'.$key.$keysuffix)) {
9584 if (is_array($getposttemp)) {
9586 $value = implode(
",", $getposttemp);
9588 $value = $getposttemp;
9590 } elseif (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'int'))) {
9591 $value = (!empty($this->array_options[
"options_".$key]) || (isset($this->array_options[
"options_".$key]) && $this->array_options[
"options_".$key] ===
'0')) ? $this->array_options[
"options_".$key] :
'';
9593 $value = (!empty($this->array_options[
"options_".$key]) ? $this->array_options[
"options_".$key] :
'');
9599 $nbofextrafieldsshown++;
9602 if ($extrafields->attributes[$this->table_element][
'type'][$key] ==
'separate') {
9603 $extrafields_collapse_num = $key;
9621 $out .= $extrafields->showSeparator($key, $this, ($colspan ? $colspan + 1 : 2), $display_type, $mode);
9623 $lastseparatorkeyfound = $key;
9625 $collapse_group = $extrafields_collapse_num.(!empty($this->
id) ?
'_'.$this->id :
'');
9627 $class = (!empty($extrafields->attributes[$this->table_element][
'hidden'][$key]) ?
'hideobject ' :
'');
9629 if (is_array($params) && count($params) > 0) {
9630 if (array_key_exists(
'class', $params)) {
9631 $class .= $params[
'class'].
' ';
9633 if (array_key_exists(
'style', $params)) {
9634 $csstyle = $params[
'style'];
9639 $domData =
' data-element="extrafield"';
9640 $domData .=
' data-targetelement="'.$this->element.
'"';
9641 $domData .=
' data-targetid="'.$this->id.
'"';
9643 $html_id = (empty($this->
id) ?
'' :
'extrarow-'.$this->element.
'_'.$key.
'_'.
$this->id);
9644 if ($display_type ==
'card') {
9649 if ($action ==
'selectlines') {
9656 $force_values_on_change_company = (
9657 ($this->element ==
'facture' &&
getDolGlobalInt(
'THIRDPARTY_PROPAGATE_EXTRAFIELDS_TO_INVOICE'))
9658 || ($this->element ==
'commande' &&
getDolGlobalInt(
'THIRDPARTY_PROPAGATE_EXTRAFIELDS_TO_ORDER'))
9659 || ($this->element ==
'order_supplier' &&
getDolGlobalInt(
'THIRDPARTY_PROPAGATE_EXTRAFIELDS_TO_SUPPLIER_ORDER'))
9661 if ($force_values_on_change_company &&
GETPOSTINT(
'changecompany')) {
9662 $value = $this->array_options[
'options_'.$key] ?? $value;
9666 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'date'))) {
9667 $datenotinstring =
null;
9668 if (array_key_exists(
'options_'.$key, $this->array_options)) {
9669 $datenotinstring = $this->array_options[
'options_'.$key];
9670 if (!is_numeric($this->array_options[
'options_'.$key])) {
9671 $datenotinstring = $this->db->jdate($datenotinstring);
9674 $datekey = $keyprefix.
'options_'.$key.$keysuffix;
9677 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'datetime'))) {
9678 $datenotinstring =
null;
9679 if (array_key_exists(
'options_'.$key, $this->array_options)) {
9680 $datenotinstring = $this->array_options[
'options_'.$key];
9681 if (!is_numeric($this->array_options[
'options_'.$key])) {
9682 $datenotinstring = $this->db->jdate($datenotinstring);
9685 $timekey = $keyprefix.
'options_'.$key.$keysuffix;
9686 $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;
9689 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'price',
'double'))) {
9690 if (GETPOSTISSET($keyprefix.
'options_'.$key.$keysuffix) || $value) {
9692 } elseif (isset($this->array_options[
'options_'.$key])) {
9693 $value = $this->array_options[
'options_'.$key];
9698 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'html',
'text',
'varchar',
'select',
'radio',
'int',
'boolean'))) {
9699 if ($action ==
'create' || $mode ==
'create') {
9700 $value = (GETPOSTISSET($keyprefix.
'options_'.$key.$keysuffix) || $value) ? $value : $extrafields->attributes[$this->table_element][
'default'][$key];
9704 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'checkbox'))) {
9705 if ($action ==
'create') {
9706 $value = (GETPOSTISSET($keyprefix.
'options_'.$key.$keysuffix) || $value) ? $value : explode(
',', $extrafields->attributes[$this->table_element][
'default'][$key]);
9711 $labeltoshow = $langs->trans($label);
9712 $helptoshow = $langs->trans($extrafields->attributes[$this->table_element][
'help'][$key]);
9713 if ($display_type ==
'card') {
9714 $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.
' >';
9715 if (
getDolGlobalString(
'MAIN_VIEW_LINE_NUMBER') && ($action ==
'view' || $action ==
'valid' || $action ==
'editline' || $action ==
'confirm_valid' || $action ==
'confirm_cancel')) {
9716 $out .=
'<td></td>';
9718 $out .=
'<td class="'.(empty($params[
'tdclass']) ?
'titlefieldmax45' : $params[
'tdclass']).
' wordbreak';
9719 if ($extrafields->attributes[$this->table_element][
'type'][$key] ==
'text') {
9722 } elseif ($display_type ==
'line') {
9723 $out .=
'<div '.($html_id ?
'id="'.$html_id.
'" ' :
'').$csstyle.
' class="fieldline_options_'.$key.
' '.$class.$this->element.
'_extras_'.$key.
' trextrafields_collapse'.$collapse_group.
'" '.$domData.
' >';
9724 $out .=
'<div style="display: inline-block; padding-right:4px" class="wordbreak';
9729 $tpl_context = isset($params[
"tpl_context"]) ? $params[
"tpl_context"] :
"none";
9730 if ($tpl_context !=
"public") {
9731 if ($mode !=
'view' && !empty($extrafields->attributes[$this->table_element][
'required'][$key])) {
9732 $out .=
' fieldrequired';
9736 if ($tpl_context ==
"public") {
9737 if (!empty($extrafields->attributes[$this->table_element][
'help'][$key])) {
9738 $out .= $form->textwithpicto($labeltoshow, $helptoshow);
9740 $out .= $labeltoshow;
9742 if ($mode !=
'view' && !empty($extrafields->attributes[$this->table_element][
'required'][$key])) {
9743 $out .=
' <span style="color: red">*</span>';
9746 if (!empty($extrafields->attributes[$this->table_element][
'help'][$key])) {
9747 $out .= $form->textwithpicto($labeltoshow, $helptoshow);
9749 $out .= $labeltoshow;
9753 $out .= ($display_type ==
'card' ?
'</td>' :
'</div>');
9756 $html_id = !empty($this->
id) ? $this->element.
'_extras_'.$key.
'_'.$this->id :
'';
9757 if ($display_type ==
'card') {
9759 $out .=
'<td '.($html_id ?
'id="'.$html_id.
'" ' :
'').
' class="valuefieldcreate '.$this->element.
'_extras_'.$key;
9760 $out .=
'" '.($colspan ?
' colspan="'.$colspan.
'"' :
'');
9762 } elseif ($display_type ==
'line') {
9763 $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].
'">';
9768 $out .= $extrafields->showOutputField($key, $value,
'', $this->table_element);
9771 $listoftypestoshowpicto = explode(
',',
getDolGlobalString(
'MAIN_TYPES_TO_SHOW_PICTO',
'email,phone,ip,password'));
9772 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], $listoftypestoshowpicto)) {
9773 $out .=
getPictoForType($extrafields->attributes[$this->table_element][
'type'][$key], ($extrafields->attributes[$this->table_element][
'type'][$key] ==
'text' ?
'tdtop' :
''));
9776 $out .= $extrafields->showInputField($key, $value,
'', $keysuffix,
'',
'', $this, $this->table_element);
9779 $listoftypestoshowpicto = explode(
',',
getDolGlobalString(
'MAIN_TYPES_TO_SHOW_PICTO',
'email,phone,ip,password'));
9780 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], $listoftypestoshowpicto)) {
9781 $out .=
getPictoForType($extrafields->attributes[$this->table_element][
'type'][$key], ($extrafields->attributes[$this->table_element][
'type'][$key] ==
'text' ?
'tdtop' :
''));
9783 $out .= $extrafields->showInputField($key, $value,
'', $keysuffix,
'',
'', $this, $this->table_element);
9787 $out .= ($display_type ==
'card' ?
'</td>' :
'</div>');
9788 $out .= ($display_type ==
'card' ?
'</tr>'.
"\n" :
'</div>');
9794 if (!empty($conf->use_javascript_ajax)) {
9795 $out .= $this->getJSListDependancies();
9798 $out .=
'<!-- commonobject:showOptionals end --> '.
"\n";
9800 if (empty($nbofextrafieldsshown)) {
9806 $out .= $hookResPrint;
9818 <script nonce="'.getNonce().
'">
9819 jQuery(document).ready(function() {
9820 function showOptions'.$type.
'(child_list, parent_list, orig_select)
9822 var val = $("select[name=\""+parent_list+"\"]").val();
9823 var parentVal = parent_list + ":" + val;
9824 if(typeof val == "string"){
9826 var options = orig_select.find("option[parent=\""+parentVal+"\"]").clone();
9827 $("select[name=\""+child_list+"\"] option[parent]").remove();
9828 $("select[name=\""+child_list+"\"]").append(options);
9830 var options = orig_select.find("option[parent]").clone();
9831 $("select[name=\""+child_list+"\"] option[parent]").remove();
9832 $("select[name=\""+child_list+"\"]").append(options);
9834 } else if(val > 0) {
9835 var options = orig_select.find("option[parent=\""+parentVal+"\"]").clone();
9836 $("select[name=\""+child_list+"\"] option[parent]").remove();
9837 $("select[name=\""+child_list+"\"]").append(options);
9839 var options = orig_select.find("option[parent]").clone();
9840 $("select[name=\""+child_list+"\"] option[parent]").remove();
9841 $("select[name=\""+child_list+"\"]").append(options);
9844 function setListDependencies'.$type.
'() {
9845 jQuery("select option[parent]").parent().each(function() {
9846 var orig_select = {};
9847 var child_list = $(this).attr("name");
9848 orig_select[child_list] = $(this).clone();
9849 var parent = $(this).find("option[parent]:first").attr("parent");
9850 var infos = parent.split(":");
9851 var parent_list = infos[0];
9853 //Hide daughters lists
9854 if ($("#"+child_list).val() == 0 && $("#"+parent_list).val() == 0){
9855 $("#"+child_list).hide();
9857 } else if ($("#"+parent_list).val() != 0){
9858 $("#"+parent_list).show();
9860 //Show the child list if the parent list value is selected
9861 $("select[name=\""+parent_list+"\"]").click(function() {
9862 if ($(this).val() != 0){
9863 $("#"+child_list).show()
9867 //When we change parent list
9868 $("select[name=\""+parent_list+"\"]").change(function() {
9869 showOptions'.$type.
'(child_list, parent_list, orig_select[child_list]);
9870 //Select the value 0 on child list after a change on the parent list
9871 $("#"+child_list).val(0).trigger("change");
9872 //Hide child lists if the parent value is set to 0
9873 if ($(this).val() == 0){
9874 $("#"+child_list).hide();
9880 setListDependencies'.$type.
'();
9895 $module = empty($this->module) ?
'' : $this->module;
9896 $element = $this->element;
9898 if ($element ==
'facturerec') {
9899 $element =
'facture';
9900 } elseif ($element ==
'invoice_supplier_rec') {
9901 return !$user->hasRight(
'fournisseur',
'facture') ? null : $user->hasRight(
'fournisseur',
'facture');
9902 } elseif ($module && $user->hasRight($module, $element)) {
9904 return $user->hasRight($module, $element);
9907 return isset($user->rights->$element) ? $user->rights->$element :
null;
9924 global $hookmanager;
9926 $parameters = array(
9927 'origin_id' => $origin_id,
9928 'dest_id' => $dest_id,
9929 'tables' => $tables,
9931 $reshook = $hookmanager->executeHooks(
'commonReplaceThirdparty', $parameters);
9934 } elseif ($reshook < 0) {
9935 return $ignoreerrors === 1;
9938 foreach ($tables as $table) {
9939 $sql =
'UPDATE '.$dbs->prefix().$table.
' SET fk_soc = '.((int) $dest_id).
' WHERE fk_soc = '.((int) $origin_id);
9941 if (!$dbs->
query($sql)) {
9942 if ($ignoreerrors) {
9967 foreach ($tables as $table) {
9968 $sql =
'UPDATE '.MAIN_DB_PREFIX.$table.
' SET fk_product = '.((int) $dest_id).
' WHERE fk_product = '.((int) $origin_id);
9970 if (!$dbs->
query($sql)) {
9971 if ($ignoreerrors) {
9994 public function defineBuyPrice($unitPrice = 0.0, $discountPercent = 0.0, $fk_product = 0)
10000 if (($unitPrice > 0) && (isset($conf->global->ForceBuyingPriceIfNull) &&
getDolGlobalInt(
'ForceBuyingPriceIfNull') > 0)) {
10002 $buyPrice = $unitPrice * (1 - $discountPercent / 100);
10005 if (!empty($fk_product) && $fk_product > 0) {
10008 require_once DOL_DOCUMENT_ROOT.
'/product/class/product.class.php';
10009 $product =
new Product($this->db);
10010 $result = $product->fetch($fk_product);
10011 if ($result <= 0) {
10012 $this->errors[] =
'ErrorProductIdDoesNotExists';
10015 if ($product->cost_price > 0) {
10016 $buyPrice = $product->cost_price;
10017 } elseif ($product->pmp > 0) {
10018 $buyPrice = $product->pmp;
10021 require_once DOL_DOCUMENT_ROOT.
'/product/class/product.class.php';
10022 $product =
new Product($this->db);
10023 $result = $product->fetch($fk_product);
10024 if ($result <= 0) {
10025 $this->errors[] =
'ErrorProductIdDoesNotExists';
10028 if ($product->pmp > 0) {
10029 $buyPrice = $product->pmp;
10033 if (empty($buyPrice) && in_array(
getDolGlobalString(
'MARGIN_TYPE'), array(
'1',
'pmp',
'costprice'))) {
10034 require_once DOL_DOCUMENT_ROOT.
'/fourn/class/fournisseur.product.class.php';
10036 if (($result = $productFournisseur->find_min_price_product_fournisseur($fk_product)) > 0) {
10037 $buyPrice = $productFournisseur->fourn_unitprice;
10038 } elseif ($result < 0) {
10039 $this->errors[] = $productFournisseur->error;
10046 return (
float) $buyPrice;
10059 return array(
'dir' =>
'',
'file' =>
'',
'originalfile' =>
'',
'altfile' =>
'',
'email' =>
'',
'capture' =>
'');
10083 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')
10086 global $user, $langs;
10088 include_once DOL_DOCUMENT_ROOT.
'/core/lib/files.lib.php';
10089 include_once DOL_DOCUMENT_ROOT.
'/core/lib/images.lib.php';
10091 $sortfield =
'position_name';
10092 $sortorder =
'asc';
10097 $dir .=
get_exdir(0, 0, 0, 0, $this, $modulepart);
10098 $pdir .=
get_exdir(0, 0, 0, 0, $this, $modulepart);
10101 if ($modulepart ==
'product') {
10103 $dir = $sdir.
'/'.
get_exdir($this->
id, 2, 0, 0, $this, $modulepart).$this->id.
"/photos/";
10104 $pdir =
'/'.get_exdir($this->
id, 2, 0, 0, $this, $modulepart).$this->id.
"/photos/";
10107 if ($modulepart ==
'category') {
10108 $dir = $sdir.
'/'.
get_exdir($this->
id, 2, 0, 0, $this, $modulepart).$this->id.
"/photos/";
10109 $pdir =
'/'.get_exdir($this->
id, 2, 0, 0, $this, $modulepart).$this->id.
"/photos/";
10115 $relativedir = preg_replace(
'/^'.preg_quote(DOL_DATA_ROOT,
'/').
'/',
'', $dir);
10116 $relativedir = preg_replace(
'/^[\\/]/',
'', $relativedir);
10117 $relativedir = preg_replace(
'/[\\/]$/',
'', $relativedir);
10120 $dirthumb = $dir.
'thumbs/';
10121 $pdirthumb = $pdir.
'thumbs/';
10123 $return =
'<!-- Photo -->'.
"\n";
10126 $filearray =
dol_dir_list($dir,
"files", 0,
'',
'(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) ==
'desc' ? SORT_DESC : SORT_ASC), 1);
10135 '@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';
10137 if (count($filearray)) {
10138 if ($sortfield && $sortorder) {
10139 $filearray =
dol_sort_array($filearray, $sortfield, $sortorder);
10142 foreach ($filearray as $key => $val) {
10144 $file = $val[
'name'];
10150 $viewfilename = $file;
10152 if ($size == 1 || $size ==
'small') {
10158 $pdirthumb = $pdir;
10159 $photo_vignette = basename($file);
10165 if ($nbbyrow > 0) {
10166 if ($nbphoto == 1) {
10167 $return .=
'<table class="valigntop center centpercent" style="border: 0; padding: 2px; border-spacing: 2px; border-collapse: separate;">';
10170 if ($nbphoto % $nbbyrow == 1) {
10171 $return .=
'<tr class="center valignmiddle" style="border: 1px">';
10173 $return .=
'<td style="width: '.ceil(100 / $nbbyrow).
'%" class="photo">'.
"\n";
10174 } elseif ($nbbyrow < 0) {
10175 $return .=
'<div class="inline-block">'.
"\n";
10178 $relativefile = preg_replace(
'/^\//',
'', $pdir.$photo);
10179 if (empty($nolink)) {
10181 if ($urladvanced) {
10182 $return .=
'<a href="'.$urladvanced.
'">';
10184 $return .=
'<a href="'.DOL_URL_ROOT.
'/viewimage.php?modulepart='.$modulepart.
'&entity='.$this->entity.
'&file='.urlencode($pdir.$photo).
'" class="aphoto" target="_blank" rel="noopener noreferrer">';
10190 $alt = $langs->transnoentitiesnoconv(
'File').
': '.$relativefile;
10191 $alt .=
' - '.$langs->transnoentitiesnoconv(
'Size').
': '.$imgarray[
'width'].
'x'.$imgarray[
'height'];
10192 if ($overwritetitle) {
10193 if (is_numeric($overwritetitle)) {
10196 $alt = $overwritetitle;
10199 if (empty($cache) && !empty($val[
'label'])) {
10202 $cache = $val[
'label'];
10204 if ($usesharelink) {
10205 if (array_key_exists(
'share', $val) && $val[
'share']) {
10206 if (empty($maxHeight) || ($photo_vignette && $imgarray[
'height'] > $maxHeight)) {
10207 $return .=
'<!-- Show original file (thumb not yet available with shared links) -->';
10208 $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).
'">';
10210 $return .=
'<!-- Show original file -->';
10211 $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).
'">';
10214 $return .=
'<!-- Show nophoto file (because file is not shared) -->';
10215 $return .=
'<img class="photo photowithmargin'.($addphotorefcss ?
' '.$addphotorefcss :
'').
'" height="'.$maxHeight.
'" src="'.DOL_URL_ROOT.
'/public/theme/common/nophoto.png" title="'.
dol_escape_htmltag($alt).
'">';
10218 if (empty($maxHeight) || ($photo_vignette && $imgarray[
'height'] > $maxHeight)) {
10219 $return .=
'<!-- Show thumb -->';
10220 $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).
'">';
10222 $return .=
'<!-- Show original file -->';
10223 $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).
'">';
10227 if (empty($nolink)) {
10231 if ($showfilename) {
10232 $return .=
'<br>'.$viewfilename;
10237 if ($photo_vignette && (
image_format_supported($photo) > 0) && ((isset($imgarray[
'width']) && $imgarray[
'width'] > $maxWidth) || (isset($imgarray[
'width']) && $imgarray[
'width'] > $maxHeight))) {
10238 $return .=
'<a href="'.$_SERVER[
"PHP_SELF"].
'?id='.$this->
id.
'&action=addthumb&token='.
newToken().
'&file='.urlencode($pdir.$viewfilename).
'">'.
img_picto($langs->trans(
'GenerateThumb'),
'refresh').
' </a>';
10241 if ($modulepart ==
'product' && ($user->hasRight(
'produit',
'creer') || $user->hasRight(
'service',
'creer'))) {
10243 $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> ';
10246 $return .=
'<a href="'.$_SERVER[
"PHP_SELF"].
'?id='.$this->
id.
'&action=delete&token='.
newToken().
'&file='.urlencode($pdir.$viewfilename).
'">';
10252 if ($nbbyrow > 0) {
10253 $return .=
'</td>';
10254 if (($nbphoto % $nbbyrow) == 0) {
10255 $return .=
'</tr>';
10257 } elseif ($nbbyrow < 0) {
10258 $return .=
'</div>'.
"\n";
10262 if (empty($size)) {
10263 $return .=
'<img class="photo photowithmargin" src="'.DOL_URL_ROOT.
'/viewimage.php?modulepart='.$modulepart.
'&entity='.$this->entity.
'&file='.urlencode($pdir.$photo).
'">';
10265 if ($showfilename) {
10266 $return .=
'<br>'.$viewfilename;
10270 if ($modulepart ==
'product' && ($user->hasRight(
'produit',
'creer') || $user->hasRight(
'service',
'creer'))) {
10272 $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> ';
10275 $return .=
'<a href="'.$_SERVER[
"PHP_SELF"].
'?id='.$this->
id.
'&action=delete&token='.
newToken().
'&file='.urlencode($pdir.$viewfilename).
'">';
10282 if ($nbmax && $nbphoto >= $nbmax) {
10288 if ($size == 1 || $size ==
'small') {
10289 if ($nbbyrow > 0) {
10291 while ($nbphoto % $nbbyrow) {
10292 $return .=
'<td style="width: '.ceil(100 / $nbbyrow).
'%"> </td>';
10297 $return .=
'</table>';
10303 $this->nbphoto = $nbphoto;
10317 if (is_array($info)) {
10318 if (isset($info[
'type']) && $info[
'type'] ==
'array') {
10335 if (isset($info[
'type']) && ($info[
'type'] ==
'date' || $info[
'type'] ==
'datetime' || $info[
'type'] ==
'timestamp')) {
10349 if (is_array($info)) {
10350 if (isset($info[
'type']) && ($info[
'type'] ==
'duration')) {
10368 if (is_array($info)) {
10369 if (isset($info[
'type']) && (preg_match(
'/^(?:tiny|small|medium|big)?int|int$/i', $info[
'type']))) {
10387 if (is_array($info)) {
10388 if (isset($info[
'type']) && (preg_match(
'/^(double|real|price)/i', $info[
'type']))) {
10405 if (is_array($info)) {
10406 if (isset($info[
'type']) && $info[
'type'] ==
'text') {
10423 if (is_array($info)) {
10424 if (array_key_exists(
'notnull', $info) && $info[
'notnull'] !=
'1') {
10441 if (is_array($info)) {
10442 if (array_key_exists(
'notnull', $info) && $info[
'notnull'] ==
'-1') {
10459 if (is_array($info)) {
10460 if (array_key_exists(
'index', $info) && $info[
'index'] ==
true) {
10482 $queryarray = array();
10483 foreach ($this->fields as $field => $info) {
10485 if ($this->isDate($info)) {
10486 if (empty($this->{$field})) {
10487 $queryarray[$field] =
null;
10489 $queryarray[$field] = $this->db->idate($this->{$field});
10491 } elseif ($this->isDuration($info)) {
10493 if ((isset($this->{$field}) && $this->{$field} !=
'') || !empty($info[
'notnull'])) {
10494 if (!isset($this->{$field})) {
10495 if (!empty($info[
'default'])) {
10496 $queryarray[$field] = $info[
'default'];
10498 $queryarray[$field] = 0;
10501 $queryarray[$field] = (int) $this->{$field};
10504 $queryarray[$field] =
null;
10506 } elseif ($this->isInt($info) || $this->isFloat($info)) {
10507 if ($field ==
'entity' && is_null($this->{$field})) {
10508 $queryarray[$field] = ((int) $conf->entity);
10511 if ((isset($this->{$field}) && ((
string) $this->{$field}) !=
'') || !empty($info[
'notnull'])) {
10512 if (!isset($this->{$field})) {
10513 $queryarray[$field] = 0;
10514 } elseif ($this->isInt($info)) {
10515 $queryarray[$field] = (int) $this->{$field};
10516 } elseif ($this->isFloat($info)) {
10517 $queryarray[$field] = (float) $this->{$field};
10520 $queryarray[$field] =
null;
10526 $queryarray[$field] = $this->{$field};
10529 if (array_key_exists(
'type', $info) && $info[
'type'] ==
'timestamp' && empty($queryarray[$field])) {
10530 unset($queryarray[$field]);
10532 if (!empty($info[
'notnull']) && $info[
'notnull'] == -1 && empty($queryarray[$field])) {
10533 $queryarray[$field] =
null;
10537 return $queryarray;
10550 foreach ($this->fields as $field => $info) {
10551 if ($this->isDate($info)) {
10552 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') {
10553 $this->$field =
'';
10555 $this->$field = $db->jdate($obj->$field);
10557 } elseif ($this->isInt($info)) {
10558 if ($field ==
'rowid') {
10559 $this->
id = (int) $obj->$field;
10561 if ($this->isForcedToNullIfZero($info)) {
10562 if (empty($obj->$field)) {
10563 $this->$field =
null;
10565 $this->$field = (int) $obj->$field;
10568 if (isset($obj->$field) && (!is_null($obj->$field) || (array_key_exists(
'notnull', $info) && $info[
'notnull'] == 1))) {
10569 $this->$field = (int) $obj->$field;
10571 $this->$field =
null;
10575 } elseif ($this->isFloat($info)) {
10576 if ($this->isForcedToNullIfZero($info)) {
10577 if (empty($obj->$field)) {
10578 $this->$field =
null;
10580 $this->$field = (float) $obj->$field;
10583 if (isset($obj->$field) && (!is_null($obj->$field) || (array_key_exists(
'notnull', $info) && $info[
'notnull'] == 1))) {
10584 $this->$field = (float) $obj->$field;
10586 $this->$field =
null;
10590 $this->$field = isset($obj->$field) ? $obj->$field :
null;
10595 if (!isset($this->fields[
'ref']) && isset($this->
id)) {
10596 $this->
ref = (string) $this->
id;
10606 foreach ($this->fields as $field => $arr) {
10607 $this->$field =
null;
10620 $keys = array_keys($this->fields);
10621 if (!empty($alias)) {
10622 $keys_with_alias = array();
10623 foreach ($keys as $fieldname) {
10624 if (!empty($excludefields)) {
10625 if (in_array($fieldname, $excludefields)) {
10629 $keys_with_alias[] = $alias .
'.' . $fieldname;
10631 return implode(
', ', $keys_with_alias);
10633 return implode(
', ', $keys);
10644 protected function quote($value, $fieldsentry)
10646 if (is_null($value)) {
10648 } elseif (preg_match(
'/^(int|double|real|price)/i', $fieldsentry[
'type'])) {
10650 } elseif (preg_match(
'/int$/i', $fieldsentry[
'type'])) {
10651 return (
int) $value;
10652 } elseif ($fieldsentry[
'type'] ==
'boolean') {
10659 return "'".$this->db->escape($value).
"'";
10676 dol_syslog(get_class($this).
"::createCommon create", LOG_DEBUG);
10682 $fieldvalues = $this->setSaveQuery();
10686 if (array_key_exists(
'date_creation', $fieldvalues) && empty($fieldvalues[
'date_creation'])) {
10687 $fieldvalues[
'date_creation'] = $this->db->idate($now);
10688 $this->date_creation = $this->db->idate($now);
10691 if (array_key_exists(
'fk_user_creat', $fieldvalues) && !($fieldvalues[
'fk_user_creat'] > 0)) {
10692 $fieldvalues[
'fk_user_creat'] = $user->id;
10693 $this->fk_user_creat = $user->id;
10695 if (array_key_exists(
'user_creation_id', $fieldvalues) && !($fieldvalues[
'user_creation_id'] > 0)) {
10696 $fieldvalues[
'user_creation_id'] = $user->id;
10697 $this->user_creation_id = $user->id;
10699 if (array_key_exists(
'pass_crypted', $fieldvalues) && property_exists($this,
'pass')) {
10701 $tmparray =
dol_hash($this->pass,
'0', 0, 1);
10702 $fieldvalues[
'pass_crypted'] = $tmparray[
'pass_encrypted'];
10703 if (array_key_exists(
'pass_encoding', $fieldvalues) && property_exists($this,
'pass_encoding')) {
10704 $fieldvalues[
'pass_encoding'] = $tmparray[
'pass_encoding'];
10707 if (array_key_exists(
'ref', $fieldvalues)) {
10710 if (
getDolGlobalString(
'MAIN_DISABLE_AUTO_UPDATE_OF_TMS_FIELDS') && array_key_exists(
'tms', $fieldvalues)) {
10711 $fieldvalues[
'tms'] = $this->db->idate($now);
10714 unset($fieldvalues[
'rowid']);
10718 foreach ($fieldvalues as $k => $v) {
10720 $value = $this->fields[$k];
10722 $values[$k] = $this->quote($v, $value);
10726 foreach ($keys as $key) {
10727 if (!isset($this->fields[$key])) {
10730 $key_fields = $this->fields[$key];
10733 if (preg_match(
'/^integer:/i', $key_fields[
'type']) && $values[$key] ==
'-1') {
10734 $values[$key] =
'';
10736 if (!empty($key_fields[
'foreignkey']) && $values[$key] ==
'-1') {
10737 $values[$key] =
'';
10740 if (isset($key_fields[
'notnull']) && $key_fields[
'notnull'] == 1 && (!isset($values[$key]) || $values[$key] ===
'NULL') && (!isset($key_fields[
'default']) || is_null($key_fields[
'default']))) {
10743 if (empty($langs)) {
10744 require_once DOL_DOCUMENT_ROOT.
'/core/class/translate.class.php';
10746 $langs->setDefaultLang();
10747 $langs->load(
"errors");
10749 dol_syslog(
"Mandatory field '".$key.
"' is empty and required into ->fields definition of class");
10750 $this->errors[] = $langs->trans(
"ErrorFieldRequired", isset($key_fields[
'label']) ? $key_fields[
'label'] : $key);
10754 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'])) {
10755 $values[$key] = $this->quote($key_fields[
'default'], $key_fields);
10759 if (isset($key_fields[
'type']) && preg_match(
'/^integer:/i', $key_fields[
'type']) && empty($values[$key])) {
10760 if (isset($key_fields[
'default'])) {
10761 $values[$key] = ((int) $key_fields[
'default']);
10763 $values[$key] =
'null';
10766 if (!empty($key_fields[
'foreignkey']) && empty($values[$key])) {
10767 $values[$key] =
'null';
10775 $this->db->begin();
10778 $sql =
"INSERT INTO ".$this->db->prefix().$this->table_element;
10779 $sql .=
" (".implode(
", ", $keys).
')';
10780 $sql .=
" VALUES (".implode(
", ", $values).
")";
10782 $res = $this->db->query($sql);
10785 if ($this->db->lasterrno() ==
'DB_ERROR_RECORD_ALREADY_EXISTS') {
10786 $this->errors[] =
"ErrorRefAlreadyExists";
10788 $this->errors[] = $this->db->lasterror();
10794 $this->
id = $this->db->last_insert_id($this->db->prefix().$this->table_element);
10800 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)') {
10801 $sql =
"UPDATE ".$this->db->prefix().$this->table_element.
" SET ref = '(PROV".((int) $this->
id).
")' WHERE (ref = '(PROV)' OR ref = '') AND rowid = ".((int) $this->
id);
10802 $resqlupdate = $this->db->query($sql);
10804 if ($resqlupdate ===
false) {
10806 $this->errors[] = $this->db->lasterror();
10808 $this->
ref =
'(PROV'.$this->id.
')';
10815 $result = $this->insertExtraFields();
10822 if (!empty($this->table_element_line) && !empty($this->fk_element) && !empty($this->lines)) {
10823 foreach ($this->lines as $line) {
10824 $keyforparent = $this->fk_element;
10829 if (!is_object($line)) {
10830 $line = (object) $line;
10834 if (method_exists($line,
'insert')) {
10835 $result = $line->insert($user, 1);
10836 } elseif (method_exists($line,
'create')) {
10837 $result = $line->create($user, 1);
10840 $this->error = $line->error;
10841 $this->db->rollback();
10848 if (!$error && !$notrigger) {
10850 $result = $this->call_trigger(strtoupper(get_class($this)).
'_CREATE', $user);
10859 $this->db->rollback();
10862 $this->db->commit();
10879 if (empty(
$id) && empty($ref) && empty($morewhere)) {
10883 $fieldlist = $this->getFieldList(
't');
10884 if (empty($fieldlist)) {
10888 $sql =
"SELECT ".$fieldlist;
10889 $sql .=
" FROM ".$this->db->prefix().$this->table_element.
' as t';
10892 $sql .=
' WHERE t.rowid = '.((int)
$id);
10893 } elseif (!empty($ref)) {
10894 $sql .=
" WHERE t.ref = '".$this->db->escape($ref).
"'";
10896 $sql .=
' WHERE 1 = 1';
10898 if (empty(
$id) && isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
10899 $sql .=
' AND t.entity IN ('.getEntity($this->element).
')';
10902 $sql .= $morewhere;
10904 $sql .=
' LIMIT 1';
10906 $res = $this->db->query($sql);
10908 $obj = $this->db->fetch_object($res);
10910 $this->setVarsFromFetchObj($obj);
10914 if (empty($noextrafields)) {
10915 $result = $this->fetch_optionals();
10917 $this->error = $this->db->lasterror();
10918 $this->errors[] = $this->error;
10928 $this->error = $this->db->lasterror();
10929 $this->errors[] = $this->error;
10943 $objectlineclassname = get_class($this).
'Line';
10944 if (!class_exists($objectlineclassname)) {
10945 $this->error =
'Error, class '.$objectlineclassname.
' not found during call of fetchLinesCommon';
10949 $objectline =
new $objectlineclassname($this->db);
10950 '@phan-var-force CommonObjectLine $objectline';
10952 $sql =
"SELECT ".$objectline->getFieldList(
'l');
10953 $sql .=
" FROM ".$this->db->prefix().$objectline->table_element.
" as l";
10954 $sql .=
" WHERE l.fk_".$this->db->escape($this->element).
" = ".((int) $this->
id);
10956 $sql .= $morewhere;
10958 if (isset($objectline->fields[
'position'])) {
10959 $sql .= $this->db->order(
'position',
'ASC');
10962 $resql = $this->db->query($sql);
10964 $num_rows = $this->db->num_rows($resql);
10966 $this->lines = array();
10967 while ($i < $num_rows) {
10968 $obj = $this->db->fetch_object($resql);
10970 $newline =
new $objectlineclassname($this->db);
10971 '@phan-var-force CommonObjectLine $newline';
10972 $newline->setVarsFromFetchObj($obj);
10975 if (empty($noextrafields)) {
10976 $newline->fetch_optionals();
10979 $this->lines[] = $newline;
10986 $this->error = $this->db->lasterror();
10987 $this->errors[] = $this->error;
11001 dol_syslog(get_class($this).
"::updateCommon update", LOG_DEBUG);
11013 $fieldvalues = $this->setSaveQuery();
11017 if (array_key_exists(
'date_modification', $fieldvalues)) {
11018 $fieldvalues[
'date_modification'] = $this->db->idate($now);
11020 if (
getDolGlobalString(
'MAIN_DISABLE_AUTO_UPDATE_OF_TMS_FIELDS') && array_key_exists(
'tms', $fieldvalues)) {
11021 $fieldvalues[
'tms'] = $this->db->idate($now);
11023 if (array_key_exists(
'fk_user_modif', $fieldvalues)) {
11024 $fieldvalues[
'fk_user_modif'] = $user->id;
11026 if (array_key_exists(
'user_modification_id', $fieldvalues)) {
11027 $fieldvalues[
'user_modification_id'] = $user->id;
11030 if (array_key_exists(
'pass_crypted', $fieldvalues) && property_exists($this,
'pass') && !empty($this->pass)) {
11032 $tmparray =
dol_hash($this->pass,
'0', 0, 1);
11033 $fieldvalues[
'pass_crypted'] = $tmparray[
'pass_encrypted'];
11034 if (array_key_exists(
'pass_encoding', $fieldvalues) && property_exists($this,
'pass_encoding')) {
11035 $fieldvalues[
'pass_encoding'] = $tmparray[
'pass_encoding'];
11038 if (array_key_exists(
'ref', $fieldvalues)) {
11042 unset($fieldvalues[
'rowid']);
11048 foreach ($fieldvalues as $k => $v) {
11050 $value = $this->fields[$k];
11052 $values[$k] = $this->quote($v, $value);
11053 if (($value[
"type"] ==
"text") && !empty($value[
'arrayofkeyval']) && is_array($value[
'arrayofkeyval'])) {
11055 $v = preg_replace(
'/\s/',
',', $v);
11056 $v = preg_replace(
'/,+/',
',', $v);
11059 $tmp[] = $k.
'='.$this->quote($v, $this->fields[$k]);
11063 foreach ($keys as $key) {
11064 if (preg_match(
'/^integer:/i', $this->fields[$key][
'type']) && $values[$key] ==
'-1') {
11065 $values[$key] =
'';
11067 if (!empty($this->fields[$key][
'foreignkey']) && $values[$key] ==
'-1') {
11068 $values[$key] =
'';
11080 $sql =
'UPDATE '.$this->db->prefix().$this->table_element.
' SET '.implode(
', ', $tmp).
' WHERE rowid='.((int) $this->
id);
11082 $this->db->begin();
11085 $res = $this->db->query($sql);
11088 $this->errors[] = $this->db->lasterror();
11094 $result = $this->insertExtraFields();
11101 if (!$error && !$notrigger) {
11103 $result = $this->call_trigger(strtoupper(get_class($this)).
'_MODIFY', $user);
11112 $this->db->rollback();
11115 $this->db->commit();
11130 dol_syslog(get_class($this).
"::deleteCommon delete", LOG_DEBUG);
11134 $this->db->begin();
11136 if ($forcechilddeletion) {
11137 foreach ($this->childtables as $table) {
11138 $sql =
"DELETE FROM ".$this->db->prefix().$table.
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
11139 $resql = $this->db->query($sql);
11141 $this->error = $this->db->lasterror();
11142 $this->errors[] = $this->error;
11143 $this->db->rollback();
11147 } elseif (!empty($this->childtables)) {
11148 $objectisused = $this->isObjectUsed($this->
id);
11149 if (!empty($objectisused)) {
11150 dol_syslog(get_class($this).
"::deleteCommon Can't delete record as it has some child", LOG_WARNING);
11151 $this->error =
'ErrorRecordHasChildren';
11152 $this->errors[] = $this->error;
11153 $this->db->rollback();
11159 if (is_array($this->childtablesoncascade) && !empty($this->childtablesoncascade)) {
11160 foreach ($this->childtablesoncascade as $tabletodelete) {
11161 $deleteFromObject = explode(
':', $tabletodelete, 4);
11162 if (count($deleteFromObject) >= 2) {
11163 $className = str_replace(
'@',
'', $deleteFromObject[0]);
11164 $filePath = $deleteFromObject[1];
11165 $columnName = $deleteFromObject[2];
11167 if (!empty($deleteFromObject[3])) {
11168 $filter = $deleteFromObject[3];
11172 $childObject =
new $className($this->db);
11173 if (method_exists($childObject,
'deleteByParentField')) {
11174 '@phan-var-force CommonObject $childObject';
11175 $result = $childObject->deleteByParentField($this->
id, $columnName, $filter);
11178 $this->errors[] = $childObject->error;
11183 $this->errors[] =
"You defined a cascade delete on an object $className/$this->id but there is no method deleteByParentField for it";
11188 $this->errors[] =
'Cannot include child class file '.$filePath;
11193 $sql =
"DELETE FROM ".$this->db->prefix().$tabletodelete.
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
11195 $resql = $this->db->query($sql);
11198 $this->error = $this->db->lasterror();
11199 $this->errors[] = $this->error;
11209 $result = $this->call_trigger(strtoupper(get_class($this)).
'_DELETE', $user);
11219 $res = $this->deleteEcmFiles(1);
11228 require_once DOL_DOCUMENT_ROOT .
'/core/lib/files.lib.php';
11231 $this->errors[] =
'ErrorFailToDeleteDir';
11237 $res = $this->deleteObjectLinked();
11242 if (!$error && !empty($this->isextrafieldmanaged)) {
11243 $result = $this->deleteExtraFields();
11250 $sql =
'DELETE FROM '.$this->db->prefix().$this->table_element.
' WHERE rowid='.((int) $this->
id);
11252 $resql = $this->db->query($sql);
11255 $this->errors[] = $this->db->lasterror();
11261 $this->db->rollback();
11264 $this->db->commit();
11289 if (!empty($parentId) && !empty($parentField)) {
11290 if (empty($this->table_element)) {
11291 $this->error =
'Property table_element for object is not defined';
11292 $this->errors[] = $this->error;
11296 if (!method_exists($this,
'fetch')) {
11297 $this->error =
'Method fetch for object is not defined';
11298 $this->errors[] = $this->error;
11302 if (!method_exists($this,
'delete')) {
11303 $this->error =
'Method delete for object is not defined';
11304 $this->errors[] = $this->error;
11309 $this->db->begin();
11311 $sql =
"SELECT rowid FROM ".$this->db->prefix().$this->table_element;
11312 $sql .=
" WHERE ".$this->db->sanitize($parentField).
" = ".(int) $parentId;
11315 $errormessage =
'';
11317 if ($errormessage) {
11318 $this->errors[] = $errormessage;
11319 dol_syslog(__METHOD__.
' '.implode(
',', $this->errors), LOG_ERR);
11323 $resql = $this->db->query($sql);
11325 $this->errors[] = $this->db->lasterror();
11328 while ($obj = $this->db->fetch_object($resql)) {
11329 $result = $this->fetch($obj->rowid);
11332 $this->errors[] = $this->error;
11334 $result = $this->
delete($user);
11337 $this->errors[] = $this->error;
11345 if (empty($error)) {
11346 $this->db->commit();
11349 $this->error = implode(
', ', $this->errors);
11350 $this->db->rollback();
11351 return $error * -1;
11367 if (!($this->
id > 0) || empty($this->table_element_line) || empty($this->fk_element)) {
11371 $sql =
"SELECT rowid FROM ".$this->db->prefix().$this->db->sanitize($this->table_element_line);
11372 $sql .=
" WHERE rowid = ".((int) $lineid).
" AND ".$this->db->sanitize($this->fk_element).
" = ".((int) $this->
id);
11373 $resql = $this->db->query($sql);
11375 return ($resql && $this->db->num_rows($resql) > 0);
11390 $tmpforobjectclass = get_class($this);
11391 $tmpforobjectlineclass = ucfirst($tmpforobjectclass).
'Line';
11393 if ($this->
id > 0 && !empty($this->fk_element)) {
11395 $sql =
"SELECT rowid FROM ".$this->db->prefix().$this->table_element_line;
11396 $sql .=
" WHERE rowid = ".((int) $idline).
" AND ".$this->db->sanitize($this->fk_element).
" = ".((int) $this->
id);
11397 $resql = $this->db->query($sql);
11398 if (!$resql || !$this->db->num_rows($resql)) {
11399 $this->error =
'ErrorLineIDDoesNotMatchWithObjectID';
11404 $this->db->begin();
11407 $result = $this->call_trigger(
'LINE'.strtoupper($tmpforobjectclass).
'_DELETE', $user);
11413 if (empty($error)) {
11414 $sql =
"DELETE FROM ".$this->db->prefix().$this->table_element_line;
11415 $sql .=
" WHERE rowid = ".((int) $idline);
11417 $resql = $this->db->query($sql);
11419 $this->error =
"Error ".$this->db->lasterror();
11424 if (empty($error)) {
11426 $tmpobjectline =
new $tmpforobjectlineclass($this->db);
11427 '@phan-var-force CommonObjectLine $tmpobjectline';
11428 if (!isset($tmpobjectline->isextrafieldmanaged) || !empty($tmpobjectline->isextrafieldmanaged)) {
11429 $tmpobjectline->id = $idline;
11430 $result = $tmpobjectline->deleteExtraFields();
11433 $this->error =
"Error ".get_class($this).
"::deleteLineCommon deleteExtraFields error -4 ".$tmpobjectline->error;
11438 if (empty($error)) {
11439 $this->db->commit();
11442 dol_syslog(get_class($this).
"::deleteLineCommon ERROR:".$this->error, LOG_ERR);
11443 $this->db->rollback();
11463 $this->db->begin();
11465 $statusfield =
'status';
11466 if (in_array($this->element, array(
'don',
'donation',
'shipping',
'project_task'))) {
11467 $statusfield =
'fk_statut';
11470 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
11471 $sql .=
" SET ".$statusfield.
" = ".((int) $status);
11472 $sql .=
" WHERE rowid = ".((int) $this->
id);
11474 if ($this->db->query($sql)) {
11476 $this->oldcopy = clone $this;
11479 if (!$error && !$notrigger) {
11481 $result = $this->call_trigger($triggercode, $user);
11488 $this->
status = $status;
11489 if (property_exists($this,
'statut')) {
11490 $this->statut = $status;
11492 $this->db->commit();
11495 $this->db->rollback();
11499 $this->error = $this->db->error();
11500 $this->db->rollback();
11516 $this->specimen = 1;
11518 'label' =>
'This is label',
11519 'ref' =>
'ABCD1234',
11520 'description' =>
'This is a description',
11522 'note_public' =>
'Public note',
11523 'note_private' =>
'Private note',
11524 'date_creation' => (
dol_now() - 3600 * 48),
11525 'date_modification' => (
dol_now() - 3600 * 24),
11526 'fk_user_creat' => $user->id,
11527 'fk_user_modif' => $user->id,
11530 foreach ($fields as $key => $value) {
11531 if (array_key_exists($key, $this->fields)) {
11532 $this->{$key} = $value;
11537 if (property_exists($this,
'fields')) {
11538 foreach ($this->fields as $key => $value) {
11540 if (array_key_exists($key, $fields)) {
11544 if (!empty($value[
'default'])) {
11545 $this->$key = $value[
'default'];
11563 require_once DOL_DOCUMENT_ROOT.
'/core/class/comment.class.php';
11565 $comment =
new Comment($this->db);
11566 $result = $comment->fetchAllFor($this->element, $this->
id);
11568 $this->setErrorsFromObject($comment);
11571 $this->comments = $comment->comments;
11573 return count($this->comments);
11583 return count($this->comments);
11594 if (!is_array($parameters)) {
11597 foreach ($parameters as $parameter) {
11598 if (isset($this->$parameter)) {
11599 $this->$parameter = trim($this->$parameter);
11618 require_once DOL_DOCUMENT_ROOT.
'/categories/class/categorie.class.php';
11622 $existing =
$c->containing($this->
id, $type_categ,
'id');
11642 if (!is_array($categories)) {
11643 $categories = array($categories);
11646 dol_syslog(get_class($this).
"::setCategoriesCommon Object Id:".$this->
id.
' type_categ:'.$type_categ.
' nb tag add:'.count($categories), LOG_DEBUG);
11648 require_once DOL_DOCUMENT_ROOT.
'/categories/class/categorie.class.php';
11650 if (empty($type_categ)) {
11651 dol_syslog(__METHOD__.
': Type '.$type_categ.
'is an unknown category type. Done nothing.', LOG_ERR);
11657 $existing =
$c->containing($this->
id, $type_categ,
'id');
11660 if (!is_array($existing)) {
11661 $existing = array();
11663 if ($remove_existing) {
11665 $to_del = array_diff($existing, $categories);
11666 $to_add = array_diff($categories, $existing);
11669 $to_add = array_diff($categories, $existing);
11676 foreach ($to_del as $del) {
11677 if (
$c->fetch($del) > 0) {
11678 $result =
$c->del_type($this, $type_categ);
11681 $this->error =
$c->error;
11682 $this->errors =
$c->errors;
11689 foreach ($to_add as $add) {
11690 if (
$c->fetch($add) > 0) {
11691 $result =
$c->add_type($this, $type_categ);
11694 $this->error =
$c->error;
11695 $this->errors =
$c->errors;
11703 return $error ? (-1 * $error) : $ok;
11716 $this->db->begin();
11718 if (empty($type)) {
11719 $type = $this->table_element;
11722 require_once DOL_DOCUMENT_ROOT.
'/categories/class/categorie.class.php';
11723 $categorystatic =
new Categorie($this->db);
11725 $tablename = $this->db->prefix().
"categorie_".(empty($categorystatic->MAP_CAT_TABLE[$type]) ? $type : $categorystatic->MAP_CAT_TABLE[$type]);
11726 $fkname =
'fk_' . (empty($categorystatic->MAP_CAT_FK[$type]) ? $type : $categorystatic->MAP_CAT_FK[$type]);
11728 $sql =
"INSERT INTO ".$tablename.
" (fk_categorie, ".$fkname.
")";
11729 $sql .=
" SELECT fk_categorie, $toId FROM ".$tablename;
11730 $sql .=
" WHERE ".$fkname.
" = ".((int) $fromId);
11732 if (!$this->db->query($sql)) {
11733 $this->error = $this->db->lasterror();
11734 $this->db->rollback();
11738 $this->db->commit();
11752 $this->db->begin();
11756 switch ($this->element) {
11758 $element =
'propale';
11761 $element =
'produit';
11763 case 'order_supplier':
11764 $element =
'fournisseur/commande';
11766 case 'invoice_supplier':
11769 $element =
'fournisseur/facture/'.get_exdir($this->
id, 2, 0, 1, $this,
'invoice_supplier');
11772 $element =
'expedition/sending';
11775 case 'project_task':
11776 require_once DOL_DOCUMENT_ROOT.
'/projet/class/task.class.php';
11778 $project_result = $this->fetchProject();
11779 if ($project_result >= 0) {
11780 $element =
'projet/'.dol_sanitizeFileName($this->project->ref).
'/';
11784 $element =
'contract';
11787 $element = $this->element;
11789 '@phan-var-force string $element';
11792 $sql =
"DELETE FROM ".$this->db->prefix().
"ecm_files_extrafields WHERE fk_object IN (";
11793 $sql .=
" SELECT rowid FROM ".$this->db->prefix().
"ecm_files WHERE filename LIKE '".$this->db->escape($this->
ref).
"%'";
11794 $sql .=
" AND filepath = '".$this->db->escape($element).
"/".$this->db->escape($this->
ref).
"' AND entity = ".((int) $conf->entity);
11797 if (!$this->db->query($sql)) {
11798 $this->error = $this->db->lasterror();
11799 $this->db->rollback();
11804 $sql =
"DELETE FROM ".$this->db->prefix().
"ecm_files";
11805 $sql .=
" WHERE filename LIKE '".$this->db->escape($this->
ref).
"%'";
11806 $sql .=
" AND filepath = '".$this->db->escape($element).
"/".$this->db->escape($this->
ref).
"' AND entity = ".((int) $conf->entity);
11808 if (!$this->db->query($sql)) {
11809 $this->error = $this->db->lasterror();
11810 $this->db->rollback();
11817 $sql =
'DELETE FROM '.$this->db->prefix().
"ecm_files_extrafields";
11818 $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).
")";
11819 $resql = $this->db->query($sql);
11821 $this->error = $this->db->lasterror();
11822 $this->db->rollback();
11826 $sql =
'DELETE FROM '.$this->db->prefix().
"ecm_files";
11827 $sql .=
" WHERE src_object_type = '".$this->db->escape($this->table_element.(empty($this->module) ?
"" :
"@".$this->module)).
"' AND src_object_id = ".((int) $this->
id);
11828 $resql = $this->db->query($sql);
11830 $this->error = $this->db->lasterror();
11831 $this->db->rollback();
11836 $this->db->commit();
11853 include_once DOL_DOCUMENT_ROOT.
'/product/class/product.class.php';
11856 $tmpproduct =
new Product($this->db);
11857 foreach ($this->lines as $line) {
11858 if ($line->fk_product > 0) {
11859 $tmpproduct->fetch($line->fk_product);
11860 $statustotest = ($status ==
'onsale' ?
'status' :
'status_buy');
11861 if (!$tmpproduct->$statustotest) {
11862 $langs->load(
'products');
11863 $statuskey4lang = ($status ==
'onsale' ?
'ProductStatusNotOnSell' :
'ProductStatusNotOnBuy');
11865 $this->errors[] = $langs->trans(
'ProductRef').
' '.$tmpproduct->ref.
' '.$langs->trans($statuskey4lang);
11871 $this->error =
'ErrorOneLineContainsADisactivatedProduct';
11887 $this->error = $message;
11888 $this->errors[] = $message;
11900 $this->setErrorWithoutLog($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.
roundQtyToPackaging($qty, $packaging)
Round a quantity up to the next multiple of a packaging quantity (options PRODUCT_USE_CUSTOMER_PACKAG...
commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams=null)
Common function for all objects extending CommonObject for generating documents.
liste_contact($statusoflink=-1, $source='external', $list=0, $code='', $status=-1, $arrayoftcids=array())
Get array of all contacts for an object.
fetchObjectFrom($table, $field, $key, $element=null)
Load object from specific field.
fetchProject()
Load the project with id $this->fk_project into this->project.
fetch_thirdparty($force_thirdparty_id=0)
Load the third party of object, from id $this->socid or $this->fk_soc, into this->thirdparty.
static deleteAllItemsLinkedByObjectID($fk_object_where, $field_where, $table_element)
Function used to remove all items linked to an object id in association table.
setFieldError($fieldKey, $msg='')
set validation error message a field
validateField($fields, $fieldKey, $fieldValue)
Return validation test result for a field.
getDataToShowPhoto($modulepart, $imagesize)
Function used to get the logos or photos of an object.
setMulticurrencyCode($code)
Change the multicurrency code.
emtpyObjectVars()
Sets all object fields to null.
fetch_projet()
Load the project with id $this->fk_project into this->project.
getIdContact($source, $code, $status=0)
Return id of contacts for a source and a contact code.
setExtraField($key, $value)
Convenience method for setting the value of an extrafield without actually updating it in the databas...
setDocModel($user, $modelpdf)
Set last model used by doc generator.
deleteObjectLinked($sourceid=null, $sourcetype='', $targetid=null, $targettype='', $rowid=0, $f_user=null, $notrigger=0)
Delete all links between an object $this.
getExtraField($key)
Convenience method for retrieving the value of an extrafield without actually fetching it from the da...
updateExtraField($key, $trigger=null, $userused=null)
Update 1 extra field value for the current object.
setPaymentTerms($id, $deposit_percent=null)
Change the payments terms.
isFloat($info)
Function test if type is float.
setBankAccount($fk_account, $notrigger=0, $userused=null)
Change the bank account.
setExtraParameters()
Set extra parameters.
delete_resource($rowid, $element='', $notrigger=0)
Delete a link to resource line.
setErrorsFromObject($object)
setErrorsFromObject
setShippingMethod($shipping_method_id, $notrigger=0, $userused=null)
Change the shipping method.
update_note_public($note)
Update public note (kept for backward compatibility)
isLineOfObject($lineid)
Check that a line belongs to this object, using $this->table_element_line and $this->fk_element.
getSpecialCode($lineid)
Get special code of a line.
clearObjectLinkedCache()
Clear the cache saying that all linked object were already loaded.
update_ref_ext($ref_ext)
Update external ref of element.
fetchOneLike($ref)
Looks for an object with ref matching the wildcard provided It does only work when $this->table_ref_f...
hasProductsOrServices($predefined=-1)
Function to say how many lines object contains.
static isExistingObject($element, $id, $ref='', $ref_ext='')
Check if an object id or ref exists If you don't need or want to instantiate the object and just need...
isObjectUsed($id=0, $entity=0)
Function to check if an object is used by others (by children).
updateRangOfLine($rowid, $rang)
Update position of line (rang)
getDefaultCreateValueFor($fieldname, $alternatevalue=null, $type='alphanohtml')
Return the default value to use for a field when showing the create form of object.
add_element_resource($resource_id, $resource_type, $busy=0, $mandatory=0, $notrigger=0)
Add resources to the current object : add entry into llx_element_resources Need $this->element & $thi...
checkActiveProductInLines($status='onsale')
Check if all products have the right status (on sale, on buy) called during validation of propal,...
createCommon(User $user, $notrigger=0)
Create object in the database.
getTotalWeightVolume()
Return into unit=0, the calculated total of weight and volume of all lines * qty Calculate by adding ...
update_note($note, $suffix='', $notrigger=0)
Update note of element.
getFullAddress($withcountry=0, $sep="\n", $withregion=0, $extralangcode='')
Return full address of contact.
fetch_project()
Load the project with id $this->fk_project into this->project.
getFieldList($alias='', $excludefields=array())
Function to concat keys of fields.
getNbComments()
Return nb comments already posted.
setVarsFromFetchObj(&$obj)
Function to load data from a SQL pointer into properties of current object $this.
printObjectLines($action, $seller, $buyer, $selected=0, $dateSelector=0, $defaulttpldir='/core/tpl')
Return HTML table for object lines TODO Move this into an output class file (htmlline....
getChildrenOfLine($id, $includealltree=0)
Get children of line.
updateCommon(User $user, $notrigger=0)
Update object into database.
updateExtraLanguages($key, $trigger=null, $userused=null)
Update an extra language value for the current object.
deleteExtraFields()
Delete all extra fields values for the current object.
setStatusCommon($user, $status, $notrigger=0, $triggercode='')
Set to a status.
deprecatedProperties()
Provide list of deprecated properties and replacements.
setSaveQuery()
Function to return the array of data key-value from the ->fields and all the ->properties of an objec...
setValuesForExtraLanguages($onlykey='')
Fill array_options property of object by extrafields value (using for data sent by forms) Used for ex...
insertExtraLanguages($trigger='', $userused=null)
Add/Update all extra languages values for the current object.
setTransportMode($id)
Change the transport mode methods.
isArray($info)
Function test if type is array.
isInt($info)
Function test if type is integer.
fetchObjectLinked($sourceid=null, $sourcetype='', $targetid=null, $targettype='', $clause='OR', $alsosametype=1, $orderby='sourcetype', $loadalsoobjects=1)
Fetch array of objects linked to current object (object of enabled modules only).
delete_contact($rowid, $notrigger=0)
Delete a link to contact line.
updateLineUp($rowid, $rang)
Update position of line up (rang)
fetch_user($userid)
Load the user with id $userid into this->user.
errorsToString()
Method to output saved errors.
getListContactId($source='external')
Return list of id of contacts of object.
setWarehouse($warehouse_id)
Change the warehouse.
setDeliveryAddress($id)
Define delivery address.
fetchBarCode()
Load data for barcode into properties ->barcode_type* Properties ->barcode_type that is id of barcode...
getTotalDiscount()
Function that returns the total amount HT of discounts applied for all lines.
initAsSpecimenCommon()
Initialise object with example values Id must be 0 if object instance is a specimen.
printObjectLine($action, $line, $var, $num, $i, $dateSelector, $seller, $buyer, $selected=0, $extrafields=null, $defaulttpldir='/core/tpl')
Return HTML content of a detail line TODO Move this into an output class file (htmlline....
copy_linked_contact($objFrom, $source='internal')
Copy contact from one element to current.
static commonReplaceThirdparty(DoliDB $dbs, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
Function used to replace a thirdparty id with another one.
getValueFrom($table, $id, $field)
Getter generic.
trimParameters($parameters)
Trim object parameters.
fetch_product()
Load the product with id $this->fk_product into this->product.
isIndex($info)
Function test if is indexed.
quote($value, $fieldsentry)
Add quote to field value if necessary.
formAddObjectLine($dateSelector, $seller, $buyer, $defaulttpldir='/core/tpl')
Show add free and predefined products/services form.
fetchComments()
Load comments linked with current task.
line_down($rowid, $fk_parent_line=true)
Update a line to have a higher rank.
setValueFrom($field, $value, $table='', $id=null, $format='', $id_field='', $fuser=null, $trigkey='', $fk_user_field='fk_user_modif')
Setter generic.
fetch_contact($contactid=null)
Load object contact with id=$this->contact_id into $this->contact.
setRetainedWarrantyPaymentTerms($id)
Change the retained warranty payments terms.
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 log it.
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.
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.
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')) 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.
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.
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.
dolEncrypt($chain, $key='', $ciphering='', $forceseed='')
Encode a string with a symmetric encryption.
dolDecrypt($chain, $key='')
Decode a string with a symmetric encryption.