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();
1457 if (!$error && empty($notrigger)) {
1459 $this->context[
'contact_id'] = ((int) $rowid);
1460 $triggerPrefix = (empty($this->TRIGGER_PREFIX) ? strtoupper($this->element) : $this->TRIGGER_PREFIX);
1461 $result = $this->call_trigger($triggerPrefix.
'_DELETE_CONTACT', $user);
1469 dol_syslog(get_class($this).
"::delete_contact", LOG_DEBUG);
1471 $sql =
"DELETE FROM ".MAIN_DB_PREFIX.
"element_contact";
1472 $sql .=
" WHERE rowid = ".((int) $rowid);
1474 $result = $this->db->query($sql);
1477 $this->errors[] = $this->db->lasterror();
1482 $this->db->commit();
1485 $this->error = $this->db->lasterror();
1486 $this->db->rollback();
1506 if (!empty($typeContact)) {
1507 foreach ($typeContact as $key => $value) {
1508 array_push($temp, $key);
1510 $listId = implode(
",", $temp);
1515 if (empty($listId)) {
1519 $sql =
"DELETE FROM ".$this->db->prefix().
"element_contact";
1520 $sql .=
" WHERE element_id = ".((int) $this->
id);
1521 $sql .=
" AND fk_c_type_contact IN (".$this->db->sanitize($listId).
")";
1523 dol_syslog(get_class($this).
"::delete_linked_contact", LOG_DEBUG);
1524 if ($this->db->query($sql)) {
1527 $this->error = $this->db->lasterror();
1544 public function liste_contact($statusoflink = -1, $source =
'external', $list = 0, $code =
'', $status = -1, $arrayoftcids = array())
1551 $sql =
"SELECT ec.rowid, ec.statut as statuslink, ec.fk_socpeople as id, ec.fk_c_type_contact";
1552 if ($source ==
'internal') {
1553 $sql .=
", '-1' as socid, t.statut as statuscontact, t.login, t.photo, t.gender, t.fk_country as country_id";
1555 if ($source ==
'external' || $source ==
'thirdparty') {
1556 $sql .=
", t.fk_soc as socid, t.statut as statuscontact, t.fk_pays as country_id";
1558 $sql .=
", t.civility as civility, t.lastname as lastname, t.firstname, t.email, t.address, t.zip, t.town";
1559 if (empty($arrayoftcids)) {
1560 $sql .=
", tc.source, tc.element, tc.code, tc.libelle as type_label, co.label as country";
1563 if (empty($arrayoftcids)) {
1564 $sql .=
" ".$this->db->prefix().
"c_type_contact as tc,";
1566 $sql .=
" ".$this->db->prefix().
"element_contact as ec";
1567 if ($source ==
'internal') {
1568 $sql .=
" LEFT JOIN ".$this->db->prefix().
"user as t on ec.fk_socpeople = t.rowid";
1569 $sql .=
" LEFT JOIN ".$this->db->prefix().
"c_country as co ON co.rowid = t.fk_country";
1571 if ($source ==
'external' || $source ==
'thirdparty') {
1572 $sql .=
" LEFT JOIN ".$this->db->prefix().
"socpeople as t on ec.fk_socpeople = t.rowid";
1573 $sql .=
" LEFT JOIN ".$this->db->prefix().
"c_country as co ON co.rowid = t.fk_pays";
1575 $sql .=
" WHERE ec.element_id = ".((int) $this->
id);
1576 if (empty($arrayoftcids)) {
1577 $sql .=
" AND ec.fk_c_type_contact = tc.rowid";
1578 $sql .=
" AND tc.element = '".$this->db->escape($this->element).
"'";
1580 $sql .=
" AND tc.code = '".$this->db->escape($code).
"'";
1582 if ($source ==
'internal') {
1583 $sql .=
" AND tc.source = 'internal'";
1585 if ($source ==
'external' || $source ==
'thirdparty') {
1586 $sql .=
" AND tc.source = 'external'";
1588 $sql .=
" AND tc.active = 1";
1590 $sql .=
" AND ec.fk_c_type_contact IN (".$this->db->sanitize(implode(
',', $arrayoftcids)).
")";
1593 $sql .=
" AND t.statut = ".((int) $status);
1595 if ($statusoflink >= 0) {
1596 $sql .=
" AND ec.statut = ".((int) $statusoflink);
1598 $sql .=
" ORDER BY t.lastname ASC";
1600 dol_syslog(get_class($this).
"::liste_contact", LOG_DEBUG);
1601 $resql = $this->db->query($sql);
1603 $num = $this->db->num_rows($resql);
1606 $obj = $this->db->fetch_object($resql);
1609 $transkey =
"TypeContact_".$obj->element.
"_".$obj->source.
"_".$obj->code;
1610 $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->type_label);
1612 'parentId' => $this->
id,
1613 'source' => $obj->source,
1614 'socid' => $obj->socid,
1616 'nom' => $obj->lastname,
1617 'civility' => $obj->civility,
1618 'lastname' => $obj->lastname,
1619 'firstname' => $obj->firstname,
1620 'email' => $obj->email,
1621 'address' => $obj->address,
1623 'town' => $obj->town,
1624 'country_id' => $obj->country_id,
1625 'country' => $obj->country,
1626 'login' => (empty($obj->login) ?
'' : $obj->login),
1627 'photo' => (empty($obj->photo) ?
'' : $obj->photo),
1628 'gender' => (empty($obj->gender) ?
'' : $obj->gender),
1629 'statuscontact' => $obj->statuscontact,
1630 'rowid' => $obj->rowid,
1631 'code' => $obj->code,
1632 'libelle' => $libelle_type,
1633 'status' => (
int) $obj->statuslink,
1634 'fk_c_type_contact' => $obj->fk_c_type_contact
1637 $tab[$i] = $obj->id;
1645 $this->error = $this->db->lasterror();
1660 $sql =
"SELECT ec.datecreate, ec.statut, ec.fk_socpeople, ec.fk_c_type_contact,";
1661 $sql .=
" tc.code, tc.libelle as type_label";
1662 $sql .=
" FROM (".$this->db->prefix().
"element_contact as ec, ".$this->db->prefix().
"c_type_contact as tc)";
1663 $sql .=
" WHERE ec.rowid =".((int) $rowid);
1664 $sql .=
" AND ec.fk_c_type_contact = tc.rowid";
1665 $sql .=
" AND tc.element = '".$this->db->escape($this->element).
"'";
1667 dol_syslog(get_class($this).
"::swapContactStatus", LOG_DEBUG);
1668 $resql = $this->db->query($sql);
1670 $obj = $this->db->fetch_object($resql);
1671 $newstatut = ($obj->statut == 4) ? 5 : 4;
1673 $this->db->free($resql);
1676 $this->error = $this->db->error();
1693 public function liste_type_contact($source =
'internal', $order =
'position', $option = 0, $activeonly = 0, $code =
'')
1698 if (empty($order)) {
1699 $order =
'position';
1701 if ($order ==
'position') {
1707 $sql =
"SELECT DISTINCT tc.rowid, tc.code, tc.libelle as type_label, tc.position";
1708 $sql .=
" FROM ".$this->db->prefix().
"c_type_contact as tc";
1709 $sql .=
" WHERE tc.element = '".$this->db->escape($this->element).
"'";
1710 if ($activeonly == 1) {
1711 $sql .=
" AND tc.active = 1";
1713 if (!empty($source) && $source !=
'all') {
1714 $sql .=
" AND tc.source = '".$this->db->escape($source).
"'";
1716 if (!empty($code)) {
1717 $sql .=
" AND tc.code = '".$this->db->escape($code).
"'";
1719 $sql .= $this->db->order($order,
'ASC');
1722 $resql = $this->db->query($sql);
1724 $this->error = $this->db->lasterror();
1729 $num = $this->db->num_rows($resql);
1732 $obj = $this->db->fetch_object($resql);
1734 $transkey =
"TypeContact_".$this->element.
"_".$source.
"_".$obj->code;
1735 $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $langs->trans($obj->type_label));
1736 if (empty($option)) {
1737 $tab[$obj->rowid] = $libelle_type;
1738 } elseif ($option == 1) {
1739 $tab[$obj->code] = $libelle_type;
1741 $tab[$obj->rowid] = array(
'id' => $obj->rowid,
'code' => $obj->code,
'label' => $libelle_type);
1760 public function listeTypeContacts($source =
'internal', $option = 0, $activeonly = 0, $code =
'', $element =
'', $excludeelement =
'')
1764 $langs->loadLangs(array(
'bills',
'contracts',
'interventions',
'orders',
'projects',
'propal',
'ticket',
'agenda'));
1768 $sql =
"SELECT DISTINCT tc.rowid, tc.code, tc.libelle as type_label, tc.position, tc.element, tc.module";
1769 $sql .=
" FROM ".$this->db->prefix().
"c_type_contact as tc";
1771 $sqlWhere = array();
1772 if (!empty($element)) {
1773 $sqlWhere[] =
" tc.element='".$this->db->escape($element).
"'";
1775 if (!empty($excludeelement)) {
1776 $sqlWhere[] =
" tc.element <> '".$this->db->escape($excludeelement).
"'";
1779 if ($activeonly == 1) {
1780 $sqlWhere[] =
" tc.active=1";
1783 if (!empty($source) && $source !=
'all') {
1784 $sqlWhere[] =
" tc.source='".$this->db->escape($source).
"'";
1787 if (!empty($code)) {
1788 $sqlWhere[] =
" tc.code='".$this->db->escape($code).
"'";
1791 if (count($sqlWhere) > 0) {
1792 $sql .=
" WHERE ".implode(
' AND ', $sqlWhere);
1795 $sql .= $this->db->order(
'tc.element, tc.position',
'ASC');
1798 $resql = $this->db->query($sql);
1800 $num = $this->db->num_rows($resql);
1802 $langs->loadLangs(array(
"propal",
"orders",
"bills",
"suppliers",
"contracts",
"supplier_proposal"));
1804 while ($obj = $this->db->fetch_object($resql)) {
1805 $modulename = $obj->module ?? $obj->element;
1806 if (strpos($obj->element,
'project') !==
false) {
1807 $modulename =
'projet';
1808 } elseif ($obj->element ==
'contrat') {
1809 $element =
'contract';
1810 } elseif ($obj->element ==
'action') {
1811 $modulename =
'agenda';
1812 } elseif (strpos($obj->element,
'supplier') !==
false && $obj->element !=
'supplier_proposal') {
1813 $modulename =
'fournisseur';
1816 $libelle_element = $langs->trans(
'ContactDefault_'.$obj->element);
1817 $tmpelement = $obj->element;
1818 $transkey =
"TypeContact_".$tmpelement.
"_".$source.
"_".$obj->code;
1819 $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->type_label);
1820 $tab[$obj->rowid] = $libelle_element.
' - '.$libelle_type;
1826 $this->error = $this->db->lasterror();
1847 if (!
getDolGlobalInt(
'SHIPPING_USE_ITS_OWN_CONTACTS') && $this->element ==
'shipping' && $this->origin_id != 0) {
1848 $id = $this->origin_id;
1849 $element =
'commande';
1850 } elseif ($this->element ==
'reception' && $this->origin_id != 0) {
1851 $id = $this->origin_id;
1852 $element =
'order_supplier';
1855 $element = $this->element;
1858 $sql =
"SELECT ec.fk_socpeople";
1859 $sql .=
" FROM ".$this->db->prefix().
"element_contact as ec,";
1860 if ($source ==
'internal') {
1861 $sql .=
" ".$this->db->prefix().
"user as c,";
1863 if ($source ==
'external') {
1864 $sql .=
" ".$this->db->prefix().
"socpeople as c,";
1866 $sql .=
" ".$this->db->prefix().
"c_type_contact as tc";
1867 $sql .=
" WHERE ec.element_id = ".((int) $id);
1868 $sql .=
" AND ec.fk_socpeople = c.rowid";
1869 if ($source ==
'internal') {
1870 $sql .=
" AND c.entity IN (".getEntity(
'user').
")";
1872 if ($source ==
'external') {
1873 $sql .=
" AND c.entity IN (".getEntity(
'societe').
")";
1875 $sql .=
" AND ec.fk_c_type_contact = tc.rowid";
1876 $sql .=
" AND tc.element = '".$this->db->escape($element).
"'";
1877 $sql .=
" AND tc.source = '".$this->db->escape($source).
"'";
1879 $sql .=
" AND tc.code = '".$this->db->escape($code).
"'";
1881 $sql .=
" AND tc.active = 1";
1883 $sql .=
" AND ec.statut = ".((int) $status);
1886 dol_syslog(get_class($this).
"::getIdContact", LOG_DEBUG);
1887 $resql = $this->db->query($sql);
1889 while ($obj = $this->db->fetch_object($resql)) {
1890 $result[$i] = $obj->fk_socpeople;
1894 $this->error = $this->db->error();
1911 if (empty($contactid)) {
1912 $contactid = $this->contact_id;
1915 if (empty($contactid)) {
1919 require_once DOL_DOCUMENT_ROOT.
'/contact/class/contact.class.php';
1920 $contact =
new Contact($this->db);
1921 $result = $contact->fetch($contactid);
1922 $this->contact = $contact;
1937 if (empty($this->socid) && empty($this->fk_soc) && empty($force_thirdparty_id)) {
1941 require_once DOL_DOCUMENT_ROOT.
'/societe/class/societe.class.php';
1943 $idtofetch = isset($this->socid) ? $this->socid : (isset($this->fk_soc) ? $this->fk_soc : 0);
1944 if ($force_thirdparty_id) {
1945 $idtofetch = $force_thirdparty_id;
1949 $thirdparty =
new Societe($this->db);
1950 $result = $thirdparty->fetch($idtofetch);
1952 $this->errors = array_merge($this->errors, $thirdparty->errors);
1954 $this->thirdparty = $thirdparty;
1958 $this->thirdparty->price_level = 1;
1977 if (!$this->table_ref_field) {
1981 $sql =
"SELECT rowid FROM ".$this->db->prefix().$this->table_element;
1982 $sql .=
" WHERE ".$this->table_ref_field.
" LIKE '".$this->db->escape($ref).
"'";
1985 $query = $this->db->query($sql);
1987 if (!$this->db->num_rows($query)) {
1991 $result = $this->db->fetch_object($query);
1993 if (method_exists($this,
'fetch')) {
1994 return $this->fetch($result->rowid);
1996 $this->error =
'Fetch method not implemented on '.get_class($this);
1997 dol_syslog(get_class($this).
'::fetchOneLike Error='.$this->error, LOG_ERR);
1998 array_push($this->errors, $this->error);
2027 dol_syslog(get_class($this).
'::fetchBarCode this->element='.$this->element.
' this->barcode_type='.$this->barcode_type);
2029 $idtype = $this->barcode_type;
2030 if (empty($idtype) && $idtype !=
'0') {
2031 if ($this->element ==
'product' &&
getDolGlobalString(
'PRODUIT_DEFAULT_BARCODE_TYPE')) {
2033 } elseif ($this->element ==
'societe') {
2036 dol_syslog(
'Call fetchBarCode with barcode_type not defined and cannot be guessed', LOG_WARNING);
2041 if (empty($this->barcode_type) || empty($this->barcode_type_code) || empty($this->barcode_type_label) || empty($this->barcode_type_coder)) {
2042 $sql =
"SELECT rowid, code, libelle as label, coder";
2043 $sql .=
" FROM ".$this->db->prefix().
"c_barcode_type";
2044 $sql .=
" WHERE rowid = ".((int) $idtype);
2046 $resql = $this->db->query($sql);
2048 $obj = $this->db->fetch_object($resql);
2050 $this->barcode_type = $obj->rowid;
2051 $this->barcode_type_code = $obj->code;
2052 $this->barcode_type_label = $obj->label;
2053 $this->barcode_type_coder = $obj->coder;
2071 include_once DOL_DOCUMENT_ROOT.
'/projet/class/project.class.php';
2073 if (empty($this->fk_project) && !empty($this->fk_projet)) {
2074 $this->fk_project = $this->fk_projet;
2076 if (empty($this->fk_project)) {
2080 $project =
new Project($this->db);
2081 $result = $project->fetch($this->fk_project);
2083 $this->project = $project;
2125 include_once DOL_DOCUMENT_ROOT.
'/product/class/product.class.php';
2128 if (empty($this->fk_product)) {
2132 $product =
new Product($this->db);
2134 $result = $product->fetch($this->fk_product);
2136 $this->product = $product;
2150 $user =
new User($this->db);
2151 $result = $user->fetch($userid);
2152 $this->
user = $user;
2166 $tmpclassname = $this->origin ? $this->origin : $this->origin_type;
2169 if ($tmpclassname ==
'shipping') {
2170 $tmpclassname =
'Expedition';
2172 if ($tmpclassname ==
'delivery') {
2173 $tmpclassname =
'Livraison';
2175 if ($tmpclassname ==
'order_supplier' || $tmpclassname ==
'supplier_order') {
2176 $tmpclassname =
'CommandeFournisseur';
2179 $classname = ucfirst($tmpclassname);
2181 $this->origin_object =
new $classname($this->db);
2183 $this->origin_object->fetch($this->origin_id);
2201 $sql =
"SELECT rowid FROM ".$this->db->prefix().$table;
2202 $sql .=
" WHERE ".$field.
" = '".$this->db->escape($key).
"'";
2203 if (!empty($element)) {
2204 $sql .=
" AND entity IN (".getEntity($element).
")";
2206 $sql .=
" AND entity = ".((int) $conf->entity);
2209 dol_syslog(get_class($this).
'::fetchObjectFrom', LOG_DEBUG);
2210 $resql = $this->db->query($sql);
2212 $obj = $this->db->fetch_object($resql);
2215 if (method_exists($this,
'fetch')) {
2216 $result = $this->fetch($obj->rowid);
2218 $this->error =
'fetch() method not implemented on '.get_class($this);
2219 dol_syslog(get_class($this).
'::fetchOneLike Error='.$this->error, LOG_ERR);
2220 array_push($this->errors, $this->error);
2240 if (!empty($id) && !empty($field) && !empty($table)) {
2241 if (!preg_match(
'/^[a-zA-Z_][a-zA-Z0-9_]*$/', $table)) {
2242 dol_syslog(get_class($this).
'::getValueFrom Bad table name: '.$table, LOG_WARNING);
2245 if (!preg_match(
'/^[a-zA-Z_][a-zA-Z0-9_.]*$/', $field)) {
2246 dol_syslog(get_class($this).
'::getValueFrom Bad field name: '.$field, LOG_WARNING);
2250 $sql =
"SELECT ".$this->db->sanitize($field).
" FROM ".$this->db->prefix().$this->db->sanitize($table);
2251 $sql .=
" WHERE rowid = ".((int) $id);
2253 dol_syslog(get_class($this).
'::getValueFrom', LOG_DEBUG);
2254 $resql = $this->db->query($sql);
2256 $row = $this->db->fetch_row($resql);
2279 public function setValueFrom($field, $value, $table =
'', $id =
null, $format =
'', $id_field =
'', $fuser =
null, $trigkey =
'', $fk_user_field =
'fk_user_modif')
2283 if (empty($table)) {
2284 $table = $this->table_element;
2289 if (empty($format)) {
2292 if (empty($id_field)) {
2293 $id_field =
'rowid';
2296 $propfield = $field;
2299 if ($table ==
'product') {
2300 if ($field ==
'note_private') {
2302 $propfield =
'note_private';
2303 } elseif ($field ==
'status') {
2305 $propfield =
'status';
2306 } elseif ($field ==
'status_buy') {
2308 $propfield =
'status_buy';
2309 } elseif ($field ==
'status_batch') {
2311 $propfield =
'status_batch';
2315 if (in_array($table, array(
'actioncomm',
'adherent',
'advtargetemailing',
'cronjob',
'establishment'))) {
2316 $fk_user_field =
'fk_user_mod';
2318 if (in_array($table, array(
'prelevement_bons'))) {
2319 $fk_user_field =
'';
2322 if (!preg_match(
'/^[a-zA-Z_][a-zA-Z0-9_]*$/', $table)) {
2323 dol_syslog(get_class($this).
'::getValueFrom Bad table name: '.$table, LOG_WARNING);
2326 if (!preg_match(
'/^[a-zA-Z_][a-zA-Z0-9_.]*$/', $field)) {
2327 dol_syslog(get_class($this).
'::getValueFrom Bad field name: '.$field, LOG_WARNING);
2333 $sql =
"SELECT " . $this->db->sanitize($field);
2334 $sql .=
" FROM " . MAIN_DB_PREFIX . $this->db->sanitize($table);
2335 $sql .=
" WHERE " . $this->db->sanitize($id_field) .
" = " . ((int) $id);
2337 $resql = $this->db->query($sql);
2339 if ($obj = $this->db->fetch_object($resql)) {
2340 if ($format ==
'date') {
2341 $oldvalue = $this->db->jdate($obj->$field);
2343 $oldvalue = $obj->$field;
2347 $this->error = $this->db->lasterror();
2358 $sql =
"UPDATE ".$this->db->prefix().$table.
" SET ";
2360 if ($format ==
'text') {
2361 $sql .= $this->db->sanitize($field).
" = '".$this->db->escape($value).
"'";
2362 } elseif ($format ==
'int') {
2363 $sql .= $this->db->sanitize($field).
" = ".((int) $value);
2364 } elseif ($format ==
'date') {
2365 $sql .= $this->db->sanitize($field).
" = ".($value ?
"'".$this->db->idate($value).
"'" :
"null");
2366 } elseif ($format ==
'dategmt') {
2367 $sql .= $this->db->sanitize($field).
" = ".($value ?
"'".$this->db->idate($value,
'gmt').
"'" :
"null");
2370 if ($fk_user_field) {
2371 if (!empty($fuser) && is_object($fuser)) {
2372 $sql .=
", ".$this->db->sanitize($fk_user_field).
" = ".((int) $fuser->id);
2373 } elseif (empty($fuser) || $fuser !=
'none') {
2374 $sql .=
", ".$this->db->sanitize($fk_user_field).
" = ".((int) $user->id);
2378 $sql .=
" WHERE ".$this->db->sanitize($id_field).
" = ".((int) $id);
2380 $resql = $this->db->query($sql);
2384 if (method_exists($this,
'fetch')) {
2385 $result = $this->fetch(
$id);
2390 $this->oldcopy = clone $this;
2391 if (property_exists($this->oldcopy, $field)) {
2392 $this->oldcopy->$field = $oldvalue;
2394 if ($propfield != $field && property_exists($this->oldcopy, $propfield)) {
2395 $this->oldcopy->$propfield = $oldvalue;
2398 if (empty($this->context[
'actionmsgmore'])) {
2399 $this->context[
'actionmsgmore'] =
'Trigger called by setValueFrom';
2403 $result = $this->call_trigger($trigkey, (!empty($fuser) && is_object($fuser)) ? $fuser : $user);
2409 if (property_exists($this, $field)) {
2410 $this->$field = $value;
2412 if ($propfield != $field && property_exists($this, $propfield)) {
2413 $this->$propfield = $value;
2418 $this->db->commit();
2421 if (property_exists($this, $field)) {
2422 $this->$field = $oldvalue;
2424 if ($propfield != $field && property_exists($this, $propfield)) {
2425 $this->$propfield = $oldvalue;
2427 $this->db->rollback();
2431 if ($this->db->lasterrno() ==
'DB_ERROR_RECORD_ALREADY_EXISTS') {
2432 $this->error =
'DB_ERROR_RECORD_ALREADY_EXISTS';
2434 $this->error = $this->db->lasterror();
2436 $this->db->rollback();
2455 global $conf, $user;
2457 if (!$this->table_element) {
2458 dol_print_error(
null, get_class($this).
"::load_previous_next_ref was called on object with property table_element not defined");
2461 if ($fieldid ==
'none') {
2466 if (in_array($this->table_element, array(
'facture_rec',
'facture_fourn_rec')) && $fieldid ==
'title') {
2472 if ($user->socid > 0) {
2473 $socid = $user->socid;
2478 $aliastablesociete =
's';
2479 if ($this->element ==
'societe') {
2480 $aliastablesociete =
'te';
2482 $restrictiononfksoc = empty($this->restrictiononfksoc) ? 0 : $this->restrictiononfksoc;
2483 $sql =
"SELECT MAX(te.".$fieldid.
")";
2484 $sql .=
" FROM ".(empty($nodbprefix) ? $this->db->prefix() :
'').$this->table_element.
" as te";
2485 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2486 $tmparray = explode(
'@', $this->ismultientitymanaged);
2487 $sql .=
", ".$this->db->prefix().$tmparray[1].
" as ".($tmparray[1] ==
'societe' ?
's' :
'parenttable');
2488 } elseif ($restrictiononfksoc == 1 && $this->element !=
'societe' && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2489 $sql .=
", ".$this->db->prefix().
"societe as s";
2490 } elseif ($restrictiononfksoc == 2 && $this->element !=
'societe' && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2491 $sql .=
" LEFT JOIN ".$this->db->prefix().
"societe as s ON te.fk_soc = s.rowid";
2493 if ($restrictiononfksoc && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2494 $sql .=
" LEFT JOIN ".$this->db->prefix().
"societe_commerciaux as sc ON ".$aliastablesociete.
".rowid = sc.fk_soc";
2496 if ($fieldid ==
'rowid') {
2497 $sql .=
" WHERE te.".$fieldid.
" < ".((int) $this->
id);
2498 } elseif ($fieldid ==
'label') {
2499 $sql .=
" WHERE te.".$fieldid.
" < '".$this->db->escape((
string) $this->label).
"'";
2501 $sql .=
" WHERE te.".$fieldid.
" < '".$this->db->escape((
string) $this->
ref).
"'";
2503 if ($restrictiononfksoc == 1 && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2504 $sql .=
" AND sc.fk_user = ".((int) $user->id);
2506 if ($restrictiononfksoc == 2 && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2507 $sql .=
" AND (sc.fk_user = ".((int) $user->id).
' OR te.fk_soc IS NULL)';
2510 $filtermax = $filter;
2515 if ($errormessage) {
2516 if (!preg_match(
'/^\s*AND/i', $filtermax)) {
2524 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2525 $tmparray = explode(
'@', $this->ismultientitymanaged);
2526 $sql .=
" AND te.".$tmparray[0].
" = ".($tmparray[1] ==
"societe" ?
"s" :
"parenttable").
".rowid";
2527 } elseif ($restrictiononfksoc == 1 && $this->element !=
'societe' && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2528 $sql .=
' AND te.fk_soc = s.rowid';
2530 if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
2531 if ($this->element ==
'user' &&
getDolGlobalInt(
'MULTICOMPANY_TRANSVERSE_MODE')) {
2532 if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
2533 $sql .=
" AND te.entity IS NOT NULL";
2535 $sql .=
" AND te.rowid IN (SELECT ug.fk_user FROM ".$this->db->prefix().
"usergroup_user as ug WHERE ug.entity IN (".
getEntity(
'usergroup').
"))";
2538 $sql .=
' AND te.entity IN ('.getEntity($this->element).
')';
2541 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged) && $this->element !=
'societe') {
2542 $tmparray = explode(
'@', $this->ismultientitymanaged);
2543 $sql .=
' AND parenttable.entity IN ('.getEntity($tmparray[1]).
')';
2545 if ($restrictiononfksoc == 1 && $socid && $this->element !=
'societe') {
2546 $sql .=
' AND te.fk_soc = '.((int) $socid);
2548 if ($restrictiononfksoc == 2 && $socid && $this->element !=
'societe') {
2549 $sql .=
' AND (te.fk_soc = '.((int) $socid).
' OR te.fk_soc IS NULL)';
2551 if ($restrictiononfksoc && $socid && $this->element ==
'societe') {
2552 $sql .=
' AND te.rowid = '.((int) $socid);
2556 $result = $this->db->query($sql);
2558 $this->error = $this->db->lasterror();
2561 $row = $this->db->fetch_row($result);
2562 $this->ref_previous = $row[0];
2564 $sql =
"SELECT MIN(te.".$fieldid.
")";
2565 $sql .=
" FROM ".(empty($nodbprefix) ? $this->db->prefix() :
'').$this->table_element.
" as te";
2566 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2567 $tmparray = explode(
'@', $this->ismultientitymanaged);
2568 $sql .=
", ".$this->db->prefix().$tmparray[1].
" as ".($tmparray[1] ==
'societe' ?
's' :
'parenttable');
2569 } elseif ($restrictiononfksoc == 1 && $this->element !=
'societe' && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2570 $sql .=
", ".$this->db->prefix().
"societe as s";
2571 } elseif ($restrictiononfksoc == 2 && $this->element !=
'societe' && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2572 $sql .=
" LEFT JOIN ".$this->db->prefix().
"societe as s ON te.fk_soc = s.rowid";
2574 if ($restrictiononfksoc && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2575 $sql .=
" LEFT JOIN ".$this->db->prefix().
"societe_commerciaux as sc ON ".$aliastablesociete.
".rowid = sc.fk_soc";
2577 if ($fieldid ==
'rowid') {
2578 $sql .=
" WHERE te.".$fieldid.
" > ".((int) $this->
id);
2579 } elseif ($fieldid ==
'label') {
2580 $sql .=
" WHERE te.".$fieldid.
" > '".$this->db->escape((
string) $this->label).
"'";
2582 $sql .=
" WHERE te.".$fieldid.
" > '".$this->db->escape((
string) $this->
ref).
"'";
2584 if ($restrictiononfksoc == 1 && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2585 $sql .=
" AND (sc.fk_user = ".((int) $user->id);
2587 $userschilds = $user->getAllChildIds();
2588 $sql .=
" OR sc.fk_user IN (".$this->db->sanitize(implode(
',', $userschilds)).
")";
2592 if ($restrictiononfksoc == 2 && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2593 $sql .=
" AND (sc.fk_user = ".((int) $user->id).
' OR te.fk_soc IS NULL)';
2596 $filtermin = $filter;
2601 if ($errormessage) {
2602 if (!preg_match(
'/^\s*AND/i', $filtermin)) {
2612 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2613 $tmparray = explode(
'@', $this->ismultientitymanaged);
2614 $sql .=
" AND te.".$tmparray[0].
" = ".($tmparray[1] ==
"societe" ?
"s" :
"parenttable").
".rowid";
2615 } elseif ($restrictiononfksoc == 1 && $this->element !=
'societe' && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2616 $sql .=
' AND te.fk_soc = s.rowid';
2618 if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
2619 if ($this->element ==
'user' &&
getDolGlobalInt(
'MULTICOMPANY_TRANSVERSE_MODE')) {
2620 if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
2621 $sql .=
" AND te.entity IS NOT NULL";
2623 $sql .=
" AND te.rowid IN (SELECT ug.fk_user FROM ".$this->db->prefix().
"usergroup_user as ug WHERE ug.entity IN (".
getEntity(
'usergroup').
"))";
2626 $sql .=
' AND te.entity IN ('.getEntity($this->element).
')';
2629 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged) && $this->element !=
'societe') {
2630 $tmparray = explode(
'@', $this->ismultientitymanaged);
2631 $sql .=
' AND parenttable.entity IN ('.getEntity($tmparray[1]).
')';
2633 if ($restrictiononfksoc == 1 && $socid && $this->element !=
'societe') {
2634 $sql .=
' AND te.fk_soc = '.((int) $socid);
2636 if ($restrictiononfksoc == 2 && $socid && $this->element !=
'societe') {
2637 $sql .=
' AND (te.fk_soc = '.((int) $socid).
' OR te.fk_soc IS NULL)';
2639 if ($restrictiononfksoc && $socid && $this->element ==
'societe') {
2640 $sql .=
' AND te.rowid = '.((int) $socid);
2645 $result = $this->db->query($sql);
2647 $this->error = $this->db->lasterror();
2650 $row = $this->db->fetch_row($result);
2651 $this->ref_next = $row[0];
2666 $contactAlreadySelected = array();
2671 if ($source ==
'thirdparty') {
2672 $contactAlreadySelected[$i] = $tab[$i][
'socid'];
2674 $contactAlreadySelected[$i] = $tab[$i][
'id'];
2678 return $contactAlreadySelected;
2694 if (!$this->table_element) {
2695 dol_syslog(get_class($this).
"::setProject was called on object with property table_element not defined", LOG_ERR);
2699 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
2700 if ($this->table_element ==
'actioncomm') {
2702 $sql .=
" SET fk_project = ".((int) $projectid);
2704 $sql .=
" SET fk_project = NULL";
2706 $sql .=
' WHERE id = '.((int) $this->
id);
2708 } elseif (!empty($this->fields[
'fk_project'])) {
2710 $sql .=
" SET fk_project = ".((int) $projectid);
2712 $sql .=
" SET fk_project = NULL";
2714 $sql .=
' WHERE rowid = '.((int) $this->
id);
2717 $sql .=
' SET fk_projet = '.((int) $projectid);
2719 $sql .=
' SET fk_projet = NULL';
2721 $sql .=
" WHERE rowid = ".((int) $this->
id);
2726 dol_syslog(get_class($this).
"::setProject", LOG_DEBUG);
2727 if ($this->db->query($sql)) {
2728 $this->fk_project = ((int) $projectid);
2735 if (!$error && !$notrigger) {
2737 $result = $this->call_trigger(strtoupper($this->element) .
'_MODIFY', $user);
2746 $this->db->rollback();
2749 $this->db->commit();
2767 dol_syslog(get_class($this).
'::setPaymentMethods('.$id.
')');
2769 if ($this->
status >= 0 || $this->element ==
'societe') {
2771 $fieldname =
'fk_mode_reglement';
2772 if ($this->element ==
'societe') {
2773 $fieldname =
'mode_reglement';
2775 if (get_class($this) ==
'Fournisseur') {
2776 $fieldname =
'mode_reglement_supplier';
2778 if (get_class($this) ==
'Tva') {
2779 $fieldname =
'fk_typepayment';
2781 if (get_class($this) ==
'Salary') {
2782 $fieldname =
'fk_typepayment';
2785 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
2786 $sql .=
" SET ".$this->db->sanitize($fieldname).
" = ".(($id > 0 || $id ==
'0') ? ((
int) $id) :
'NULL');
2787 $sql .=
' WHERE rowid = '.((int) $this->
id);
2789 if ($this->db->query($sql)) {
2790 $this->mode_reglement_id = $id;
2792 if (get_class($this) ==
'Fournisseur') {
2793 $this->mode_reglement_supplier_id = $id;
2796 if (!$error && !$notrigger) {
2798 $triggerName = (empty($this->TRIGGER_PREFIX) ? strtoupper(get_class($this)) : $this->TRIGGER_PREFIX);
2799 $result = $this->call_trigger($triggerName.
'_MODIFY', $user);
2807 dol_syslog(get_class($this).
'::setPaymentMethods Error '.$this->db->error());
2808 $this->error = $this->db->error();
2812 dol_syslog(get_class($this).
'::setPaymentMethods, status of the object is incompatible');
2813 $this->error =
'Status of the object is incompatible '.$this->status;
2826 dol_syslog(get_class($this).
'::setMulticurrencyCode('.$code.
')');
2827 if ($this->
status >= 0 || $this->element ==
'societe') {
2828 $fieldname =
'multicurrency_code';
2830 $sql =
'UPDATE '.$this->db->prefix().$this->table_element;
2831 $sql .=
" SET ".$fieldname.
" = '".$this->db->escape($code).
"'";
2832 $sql .=
' WHERE rowid='.((int) $this->
id);
2834 if ($this->db->query($sql)) {
2835 $this->multicurrency_code = $code;
2839 $this->setMulticurrencyRate($rate, 2);
2844 dol_syslog(get_class($this).
'::setMulticurrencyCode Error '.$sql.
' - '.$this->db->error());
2845 $this->error = $this->db->error();
2849 dol_syslog(get_class($this).
'::setMulticurrencyCode, status of the object is incompatible');
2850 $this->error =
'Status of the object is incompatible '.$this->status;
2862 public function setMulticurrencyRate($rate, $mode = 1)
2864 dol_syslog(get_class($this).
'::setMulticurrencyRate('.$rate.
', '.$mode.
')');
2865 if ($this->
status >= 0 || $this->element ==
'societe') {
2866 $fieldname =
'multicurrency_tx';
2868 $sql =
'UPDATE '.$this->db->prefix().$this->table_element;
2869 $sql .=
" SET ".$this->db->sanitize($fieldname).
" = ".((float) $rate);
2870 $sql .=
' WHERE rowid='.((int) $this->
id);
2872 if ($this->db->query($sql)) {
2873 $this->multicurrency_tx = $rate;
2876 if (!empty($this->lines)) {
2877 foreach ($this->lines as &$line) {
2880 $line->subprice = 0;
2885 $line->multicurrency_subprice = 0;
2888 switch ($this->element) {
2892 '@phan-var-force Propal $this';
2893 '@phan-var-force PropaleLigne $line';
2898 $line->remise_percent,
2900 $line->localtax1_tx,
2901 $line->localtax2_tx,
2902 ($line->description ? $line->description : $line->desc),
2905 $line->special_code,
2906 $line->fk_parent_line,
2907 $line->skip_update_total,
2908 $line->fk_fournprice,
2911 $line->product_type,
2914 $line->array_options,
2916 $line->multicurrency_subprice
2922 '@phan-var-force Commande $this';
2923 '@phan-var-force OrderLine $line';
2926 ($line->description ? $line->description : $line->desc),
2929 $line->remise_percent,
2931 $line->localtax1_tx,
2932 $line->localtax2_tx,
2937 $line->product_type,
2938 $line->fk_parent_line,
2939 $line->skip_update_total,
2940 $line->fk_fournprice,
2943 $line->special_code,
2944 $line->array_options,
2946 $line->multicurrency_subprice
2952 '@phan-var-force Facture $this';
2953 '@phan-var-force FactureLigne $line';
2956 ($line->description ? $line->description : $line->desc),
2959 $line->remise_percent,
2963 $line->localtax1_tx,
2964 $line->localtax2_tx,
2967 $line->product_type,
2968 $line->fk_parent_line,
2969 $line->skip_update_total,
2970 $line->fk_fournprice,
2973 $line->special_code,
2974 $line->array_options,
2975 $line->situation_percent,
2977 $line->multicurrency_subprice
2983 '@phan-var-force FactureRec $this';
2984 '@phan-var-force FactureLigneRec $line';
2987 ($line->description ? $line->description : $line->desc),
2991 $line->localtax1_tx,
2992 $line->localtax2_tx,
2994 $line->remise_percent,
2999 $line->product_type,
3001 $line->special_code,
3004 $line->multicurrency_subprice,
3008 $line->fk_fournprice,
3010 $line->fk_parent_line
3013 case 'supplier_proposal':
3016 '@phan-var-force SupplierProposal $this';
3017 '@phan-var-force SupplierProposalLine $line';
3022 $line->remise_percent,
3024 $line->localtax1_tx,
3025 $line->localtax2_tx,
3026 ($line->description ? $line->description : $line->desc),
3029 $line->special_code,
3030 $line->fk_parent_line,
3031 $line->skip_update_total,
3032 $line->fk_fournprice,
3035 $line->product_type,
3036 $line->array_options,
3038 (int) $line->fk_unit,
3039 $line->multicurrency_subprice
3042 case 'order_supplier':
3045 '@phan-var-force CommandeFournisseur $this';
3046 '@phan-var-force CommandeFournisseurLigne $line';
3049 ($line->description ? $line->description : $line->desc),
3052 $line->remise_percent,
3054 $line->localtax1_tx,
3055 $line->localtax2_tx,
3058 $line->product_type,
3062 $line->array_options,
3064 $line->multicurrency_subprice,
3068 case 'invoice_supplier':
3071 '@phan-var-force FactureFournisseur $this';
3072 '@phan-var-force SupplierInvoiceLIne $line';
3075 ($line->description ? $line->description : $line->desc),
3078 $line->localtax1_tx,
3079 $line->localtax2_tx,
3084 $line->product_type,
3085 $line->remise_percent,
3089 $line->array_options,
3091 $line->multicurrency_subprice,
3096 dol_syslog(get_class($this).
'::setMulticurrencyRate no updateline defined', LOG_DEBUG);
3104 dol_syslog(get_class($this).
'::setMulticurrencyRate Error '.$sql.
' - '.$this->db->error());
3105 $this->error = $this->db->error();
3109 dol_syslog(get_class($this).
'::setMulticurrencyRate, status of the object is incompatible');
3110 $this->error =
'Status of the object is incompatible '.$this->status;
3124 dol_syslog(get_class($this).
'::setPaymentTerms('.$id.
', '.var_export($deposit_percent,
true).
')');
3125 if ($this->
status >= 0 || $this->element ==
'societe') {
3127 $fieldname =
'fk_cond_reglement';
3128 if ($this->element ==
'societe') {
3129 $fieldname =
'cond_reglement';
3131 if (get_class($this) ==
'Fournisseur') {
3132 $fieldname =
'cond_reglement_supplier';
3135 if (empty($deposit_percent) || $deposit_percent < 0) {
3136 $deposit_percent = (float)
getDictionaryValue(
'c_payment_term',
'deposit_percent', $id);
3139 if ($deposit_percent > 100) {
3140 $deposit_percent = 100;
3143 $sql =
'UPDATE '.$this->db->prefix().$this->table_element;
3144 $sql .=
" SET ".$fieldname.
" = ".(($id > 0 || $id ==
'0') ? ((
int) $id) :
'NULL');
3145 if (in_array($this->table_element, array(
'propal',
'commande',
'supplier_proposal',
'commande_fournisseur',
'societe'))) {
3146 $sql .=
" , deposit_percent = " . (empty($deposit_percent) ?
'NULL' :
"'".$this->db->escape((
string) $deposit_percent).
"'");
3148 $sql .=
' WHERE rowid='.((int) $this->
id);
3150 if ($this->db->query($sql)) {
3151 $this->cond_reglement_id = $id;
3153 if (get_class($this) ==
'Fournisseur') {
3154 $this->cond_reglement_supplier_id = $id;
3156 $this->deposit_percent = $deposit_percent;
3159 dol_syslog(get_class($this).
'::setPaymentTerms Error '.$sql.
' - '.$this->db->error());
3160 $this->error = $this->db->error();
3164 dol_syslog(get_class($this).
'::setPaymentTerms, status of the object is incompatible');
3165 $this->error =
'Status of the object is incompatible '.$this->status;
3178 dol_syslog(get_class($this).
'::setTransportMode('.$id.
')');
3179 if ($this->
status >= 0 || $this->element ==
'societe') {
3180 $fieldname =
'fk_transport_mode';
3181 if ($this->element ==
'societe') {
3182 $fieldname =
'transport_mode';
3184 if (get_class($this) ==
'Fournisseur') {
3185 $fieldname =
'transport_mode_supplier';
3188 $sql =
'UPDATE '.$this->db->prefix().$this->table_element;
3189 $sql .=
" SET ".$fieldname.
" = ".(($id > 0 || $id ==
'0') ? ((
int) $id) :
'NULL');
3190 $sql .=
' WHERE rowid='.((int) $this->
id);
3192 if ($this->db->query($sql)) {
3193 $this->transport_mode_id = $id;
3195 if (get_class($this) ==
'Fournisseur') {
3196 $this->transport_mode_supplier_id = $id;
3200 dol_syslog(get_class($this).
'::setTransportMode Error '.$sql.
' - '.$this->db->error());
3201 $this->error = $this->db->error();
3205 dol_syslog(get_class($this).
'::setTransportMode, status of the object is incompatible');
3206 $this->error =
'Status of the object is incompatible '.$this->status;
3219 dol_syslog(get_class($this).
'::setRetainedWarrantyPaymentTerms('.$id.
')');
3220 if ($this->
status >= 0 || $this->element ==
'societe') {
3221 $fieldname =
'retained_warranty_fk_cond_reglement';
3223 $sql =
'UPDATE '.$this->db->prefix().$this->table_element;
3224 $sql .=
" SET ".$fieldname.
" = ".((int) $id);
3225 $sql .=
' WHERE rowid='.((int) $this->
id);
3227 if ($this->db->query($sql)) {
3228 $this->retained_warranty_fk_cond_reglement = $id;
3231 dol_syslog(get_class($this).
'::setRetainedWarrantyPaymentTerms Error '.$sql.
' - '.$this->db->error());
3232 $this->error = $this->db->error();
3236 dol_syslog(get_class($this).
'::setRetainedWarrantyPaymentTerms, status of the object is incompatible');
3237 $this->error =
'Status of the object is incompatible '.$this->status;
3251 $fieldname =
'fk_delivery_address';
3252 if ($this->element ==
'delivery' || $this->element ==
'shipping') {
3253 $fieldname =
'fk_address';
3256 $sql =
"UPDATE ".$this->db->prefix().$this->table_element.
" SET ".$fieldname.
" = ".((int) $id);
3257 $sql .=
" WHERE rowid = ".((int) $this->
id).
" AND fk_statut = 0";
3259 if ($this->db->query($sql)) {
3260 $this->fk_delivery_address = $id;
3263 $this->error = $this->db->error();
3264 dol_syslog(get_class($this).
'::setDeliveryAddress Error '.$this->error);
3282 if (empty($userused)) {
3288 if (!$this->table_element) {
3289 dol_syslog(get_class($this).
"::setShippingMethod was called on object with property table_element not defined", LOG_ERR);
3295 if ($shipping_method_id < 0) {
3296 $shipping_method_id =
'NULL';
3298 dol_syslog(get_class($this).
'::setShippingMethod('.$shipping_method_id.
')');
3300 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
3301 $sql .=
" SET fk_shipping_method = ".((int) $shipping_method_id);
3302 $sql .=
" WHERE rowid=".((int) $this->
id);
3303 $resql = $this->db->query($sql);
3305 dol_syslog(get_class($this).
'::setShippingMethod Error ', LOG_DEBUG);
3306 $this->error = $this->db->lasterror();
3311 $this->context = array(
'shippingmethodupdate' => 1);
3312 $triggerPrefix = (empty($this->TRIGGER_PREFIX) ? strtoupper(get_class($this)) : $this->TRIGGER_PREFIX);
3313 $result = $this->call_trigger($triggerPrefix.
'_MODIFY', $userused);
3321 $this->db->rollback();
3324 $this->shipping_method_id = ($shipping_method_id ==
'NULL') ?
null : $shipping_method_id;
3325 $this->db->commit();
3339 if (!$this->table_element) {
3340 dol_syslog(get_class($this).
"::setWarehouse was called on object with property table_element not defined", LOG_ERR);
3343 if ($warehouse_id < 0) {
3344 $warehouse_id =
'NULL';
3346 dol_syslog(get_class($this).
'::setWarehouse('.$warehouse_id.
')');
3348 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
3349 $sql .=
" SET fk_warehouse = ".((int) $warehouse_id);
3350 $sql .=
" WHERE rowid=".((int) $this->
id);
3352 if ($this->db->query($sql)) {
3353 $this->warehouse_id = ($warehouse_id ==
'NULL') ?
null : $warehouse_id;
3356 dol_syslog(get_class($this).
'::setWarehouse Error ', LOG_DEBUG);
3357 $this->error = $this->db->error();
3372 if (!$this->table_element) {
3373 dol_syslog(get_class($this).
"::setDocModel was called on object with property table_element not defined", LOG_ERR);
3377 $newmodelpdf =
dol_trunc($modelpdf, 255);
3379 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
3380 $sql .=
" SET model_pdf = '".$this->db->escape($newmodelpdf).
"'";
3381 $sql .=
" WHERE rowid = ".((int) $this->
id);
3383 dol_syslog(get_class($this).
"::setDocModel", LOG_DEBUG);
3384 $resql = $this->db->query($sql);
3386 $this->model_pdf = $modelpdf;
3407 if (empty($userused)) {
3413 if (!$this->table_element) {
3414 dol_syslog(get_class($this).
"::setBankAccount was called on object with property table_element not defined", LOG_ERR);
3419 if ($fk_account < 0) {
3420 $fk_account =
'NULL';
3422 dol_syslog(get_class($this).
'::setBankAccount('.$fk_account.
')');
3424 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
3425 $sql .=
" SET fk_account = ".((int) $fk_account);
3426 $sql .=
" WHERE rowid=".((int) $this->
id);
3428 $resql = $this->db->query($sql);
3430 dol_syslog(get_class($this).
'::setBankAccount Error '.$sql.
' - '.$this->db->error());
3431 $this->error = $this->db->lasterror();
3436 $this->context[
'bankaccountupdate'] = 1;
3438 $triggerName = (empty($this->TRIGGER_PREFIX) ? strtoupper(get_class($this)) : $this->TRIGGER_PREFIX);
3439 $result = $this->call_trigger($triggerName .
'_MODIFY', $userused);
3447 $this->db->rollback();
3450 $this->fk_account = ($fk_account ==
'NULL') ?
null : $fk_account;
3451 $this->db->commit();
3469 public function line_order($renum =
false, $rowidorder =
'ASC', $fk_parent_line =
true)
3472 if (!$this->table_element_line) {
3473 dol_syslog(get_class($this).
"::line_order was called on object with property table_element_line not defined", LOG_ERR);
3476 if (!$this->fk_element) {
3477 dol_syslog(get_class($this).
"::line_order was called on object with property fk_element not defined", LOG_ERR);
3481 $fieldposition =
'rang';
3482 if (in_array($this->table_element_line, array(
'bom_bomline',
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3483 $fieldposition =
'position';
3488 $sql =
"SELECT count(rowid) FROM ".$this->db->prefix().$this->table_element_line;
3489 $sql .=
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
3491 $sql .=
" AND " . $fieldposition .
" = 0";
3494 $sql .=
" AND " . $fieldposition .
" <> 0";
3497 dol_syslog(get_class($this).
"::line_order", LOG_DEBUG);
3498 $resql = $this->db->query($sql);
3500 $row = $this->db->fetch_row($resql);
3510 $sql =
"SELECT rowid FROM ".$this->db->prefix().$this->table_element_line;
3511 $sql .=
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
3512 if ($fk_parent_line) {
3513 $sql .=
' AND fk_parent_line IS NULL';
3515 $sql .=
" ORDER BY " . $fieldposition .
" ASC, rowid " . $rowidorder;
3517 dol_syslog(get_class($this).
"::line_order search all parent lines", LOG_DEBUG);
3518 $resql = $this->db->query($sql);
3521 $num = $this->db->num_rows($resql);
3524 $row = $this->db->fetch_row($resql);
3526 if ($fk_parent_line) {
3529 if (!empty($children)) {
3530 foreach ($children as $child) {
3531 array_push($rows, $child);
3538 if (!empty($rows)) {
3539 foreach ($rows as $key => $row) {
3559 $fieldposition =
'rang';
3560 if (in_array($this->table_element_line, array(
'bom_bomline',
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3561 $fieldposition =
'position';
3566 $sql =
"SELECT rowid FROM ".$this->db->prefix().$this->table_element_line;
3567 $sql .=
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
3568 $sql .=
' AND fk_parent_line = '.((int) $id);
3569 $sql .=
" ORDER BY " . $fieldposition .
" ASC";
3571 dol_syslog(get_class($this).
"::getChildrenOfLine search children lines for line ".$id, LOG_DEBUG);
3573 $resql = $this->db->query($sql);
3574 if (!$resql || $this->db->num_rows($resql) <= 0) {
3578 while ($row = $this->db->fetch_row($resql)) {
3580 if (!empty($includealltree) && $includealltree <= 1000) {
3581 $rows = array_merge($rows, $this->
getChildrenOfLine($row[0], $includealltree + 1));
3595 public function line_up($rowid, $fk_parent_line =
true)
3598 $this->
line_order(
false,
'ASC', $fk_parent_line);
3618 $this->
line_order(
false,
'ASC', $fk_parent_line);
3639 global $hookmanager;
3640 $fieldposition =
'rang';
3641 if (in_array($this->table_element_line, array(
'bom_bomline',
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3642 $fieldposition =
'position';
3645 $sql =
"UPDATE ".$this->db->prefix().$this->table_element_line.
" SET ".$fieldposition.
" = ".((int) $rang);
3646 $sql .=
' WHERE rowid = '.((int) $rowid);
3648 dol_syslog(get_class($this).
"::updateRangOfLine", LOG_DEBUG);
3649 if (!$this->db->query($sql)) {
3654 $parameters = array(
'rowid' => $rowid,
'rang' => $rang,
'fieldposition' => $fieldposition);
3656 $reshook = $hookmanager->executeHooks(
'afterRankOfLineUpdate', $parameters, $this, $action);
3670 $num = count($rows);
3671 for ($i = 0; $i < $num; $i++) {
3689 $fieldposition =
'rang';
3690 if (in_array($this->table_element_line, array(
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3691 $fieldposition =
'position';
3694 $sql =
"UPDATE ".$this->db->prefix().$this->table_element_line.
" SET ".$fieldposition.
" = ".((int) $rang);
3695 $sql .=
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
3696 $sql .=
" AND " . $fieldposition .
" = " . ((int) ($rang - 1));
3697 if (!$this->db->query($sql)) {
3698 $this->error = $this->db->lasterror();
3702 $sql =
"UPDATE ".$this->db->prefix().$this->table_element_line.
" SET ".$fieldposition.
" = ".((int) ($rang - 1));
3703 $sql .=
' WHERE rowid = '.((int) $rowid);
3704 if (!$this->db->query($sql)) {
3705 $this->error = $this->db->lasterror();
3722 if ($rang >= $max) {
3726 $fieldposition =
'rang';
3727 if (in_array($this->table_element_line, array(
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3728 $fieldposition =
'position';
3731 $sql =
"UPDATE ".$this->db->prefix().$this->table_element_line.
" SET ".$fieldposition.
" = ".((int) $rang);
3732 $sql .=
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
3733 $sql .=
" AND " . $fieldposition .
" = " . ((int) ($rang + 1));
3734 if (!$this->db->query($sql)) {
3735 $this->error = $this->db->lasterror();
3739 $sql =
"UPDATE ".$this->db->prefix().$this->table_element_line.
" SET ".$fieldposition.
" = ".((int) ($rang + 1));
3740 $sql .=
' WHERE rowid = '.((int) $rowid);
3741 if (!$this->db->query($sql)) {
3742 $this->error = $this->db->lasterror();
3757 $fieldposition =
'rang';
3758 if (in_array($this->table_element_line, array(
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3759 $fieldposition =
'position';
3762 $sql =
"SELECT " . $fieldposition .
" FROM ".$this->db->prefix().$this->table_element_line;
3763 $sql .=
" WHERE rowid = ".((int) $rowid);
3765 dol_syslog(get_class($this).
"::getRangOfLine", LOG_DEBUG);
3766 $resql = $this->db->query($sql);
3771 $row = $this->db->fetch_row($resql);
3783 $fieldposition =
'rang';
3784 if (in_array($this->table_element_line, array(
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3785 $fieldposition =
'position';
3788 $sql =
"SELECT rowid FROM ".$this->db->prefix().$this->table_element_line;
3789 $sql .=
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
3790 $sql .=
" AND " . $fieldposition .
" = ".((int) $rang);
3791 $resql = $this->db->query($sql);
3796 $row = $this->db->fetch_row($resql);
3810 $positionfield =
'rang';
3811 if (in_array($this->table_element, array(
'bom_bom',
'product_attribute'))) {
3812 $positionfield =
'position';
3815 $sql =
"SELECT max(".$positionfield.
") FROM ".$this->db->prefix().$this->table_element_line;
3816 $sql .=
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
3819 if ($fk_parent_line) {
3820 $sql .=
" AND fk_parent_line = ".((int) $fk_parent_line);
3823 dol_syslog(get_class($this).
"::line_max", LOG_DEBUG);
3824 $resql = $this->db->query($sql);
3826 $row = $this->db->fetch_row($resql);
3828 if ($fk_parent_line) {
3829 if (!empty($row[0])) {
3852 if (!$this->table_element) {
3853 dol_syslog(get_class($this).
"::update_ref_ext was called on object with property table_element not defined", LOG_ERR);
3857 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
3858 $sql .=
" SET ref_ext = '".$this->db->escape($ref_ext).
"'";
3860 $sql .=
" WHERE ".(isset($this->table_rowid) ? $this->table_rowid :
'rowid').
" = ".((
int) $this->id);
3862 dol_syslog(get_class($this).
"::update_ref_ext", LOG_DEBUG);
3863 if ($this->db->query($sql)) {
3864 $this->ref_ext = $ref_ext;
3867 $this->error = $this->db->error();
3886 if (!$this->table_element) {
3887 $this->error =
'update_note was called on object with property table_element not defined';
3888 dol_syslog(get_class($this).
"::update_note was called on object with property table_element not defined", LOG_ERR);
3891 if (!in_array($suffix, array(
'',
'_public',
'_private'))) {
3892 $this->error =
'update_note Parameter suffix must be empty, \'_private\' or \'_public\'';
3893 dol_syslog(get_class($this).
"::update_note Parameter suffix must be empty, '_private' or '_public'", LOG_ERR);
3897 $newsuffix = $suffix;
3900 if ($this->table_element ==
'product' && $newsuffix ==
'_private') {
3903 if (in_array($this->table_element, array(
'actioncomm',
'adherent',
'advtargetemailing',
'cronjob',
'establishment'))) {
3904 $fieldusermod =
"fk_user_mod";
3905 } elseif ($this->table_element ==
'ecm_files') {
3906 $fieldusermod =
"fk_user_m";
3908 $fieldusermod =
"fk_user_modif";
3910 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
3911 $sql .=
" SET note".$this->db->sanitize($newsuffix).
" = ".(!empty($note) ? (
"'".$this->db->escape($note).
"'") :
"NULL");
3912 $sql .=
", ".$this->db->sanitize($fieldusermod).
" = ".((int) $user->id);
3913 $sql .=
" WHERE rowid = ".((int) $this->
id);
3915 dol_syslog(get_class($this).
"::update_note", LOG_DEBUG);
3916 if ($this->db->query($sql)) {
3917 if ($suffix ==
'_public') {
3918 $this->note_public = $note;
3919 } elseif ($suffix ==
'_private') {
3920 $this->note_private = $note;
3922 $this->note = $note;
3923 $this->note_private = $note;
3925 if (empty($notrigger)) {
3927 switch ($this->element) {
3929 $triggerName =
'COMPANY_MODIFY';
3932 $triggerName =
'BILL_MODIFY';
3934 case 'invoice_supplier':
3935 $triggerName =
'BILL_SUPPLIER_MODIFY';
3938 $triggerName =
'BILLREC_MODIFIY';
3940 case 'expensereport':
3941 $triggerName =
'EXPENSE_REPORT_MODIFY';
3944 $triggerName = (!empty($this->TRIGGER_PREFIX) ? $this->TRIGGER_PREFIX : strtoupper($this->element)) .
'_MODIFY';
3946 $ret = $this->call_trigger($triggerName, $user);
3953 $this->error = $this->db->lasterror();
3984 public function update_price($exclspec = 0, $roundingadjust =
'auto', $nodatabaseupdate = 0, $seller =
null)
3987 global $conf, $hookmanager, $action;
3989 $parameters = array(
'exclspec' => $exclspec,
'roundingadjust' => $roundingadjust,
'nodatabaseupdate' => $nodatabaseupdate,
'seller' => $seller);
3990 $reshook = $hookmanager->executeHooks(
'updateTotalPrice', $parameters, $this, $action);
3993 } elseif ($reshook < 0) {
3998 $isElementForSupplier =
false;
3999 $roundTotalConstName =
'MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND';
4001 if ($this->element ==
'propal') {
4002 $MODULE =
"MODULE_DISALLOW_UPDATE_PRICE_PROPOSAL";
4003 } elseif ($this->element ==
'commande' || $this->element ==
'order') {
4004 $MODULE =
"MODULE_DISALLOW_UPDATE_PRICE_ORDER";
4005 } elseif ($this->element ==
'facture' || $this->element ==
'invoice') {
4006 $MODULE =
"MODULE_DISALLOW_UPDATE_PRICE_INVOICE";
4007 } elseif ($this->element ==
'facture_fourn' || $this->element ==
'supplier_invoice' || $this->element ==
'invoice_supplier' || $this->element ==
'invoice_supplier_rec') {
4008 $isElementForSupplier =
true;
4009 $MODULE =
"MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_INVOICE";
4010 } elseif ($this->element ==
'order_supplier' || $this->element ==
'supplier_order') {
4011 $isElementForSupplier =
true;
4012 $MODULE =
"MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_ORDER";
4013 } elseif ($this->element ==
'supplier_proposal') {
4014 $isElementForSupplier =
true;
4015 $MODULE =
"MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_PROPOSAL";
4017 if ($isElementForSupplier) {
4018 $roundTotalConstName =
'MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND_SUPPLIER';
4021 if (!empty($MODULE)) {
4024 foreach ($modsactivated as $mod) {
4032 include_once DOL_DOCUMENT_ROOT.
'/core/lib/price.lib.php';
4034 $forcedroundingmode = $roundingadjust;
4035 if ($forcedroundingmode ==
'auto' && isset($conf->global->{$roundTotalConstName})) {
4037 } elseif ($forcedroundingmode ==
'auto') {
4038 $forcedroundingmode =
'0';
4043 $multicurrency_tx = !empty($this->multicurrency_tx) ? $this->multicurrency_tx : 1;
4046 $fieldtva =
'total_tva';
4047 $fieldlocaltax1 =
'total_localtax1';
4048 $fieldlocaltax2 =
'total_localtax2';
4049 $fieldup =
'subprice';
4050 $base_price_type =
'HT';
4051 if ($this->element ==
'facture_fourn' || $this->element ==
'invoice_supplier') {
4055 if ($this->element ==
'invoice_supplier_rec') {
4058 if ($this->element ==
'expensereport') {
4062 $forcedroundingmode =
'0';
4063 $fieldup =
'value_unit';
4064 $base_price_type =
'TTC';
4067 $sql =
"SELECT rowid, qty, ".$this->db->sanitize($fieldup).
" as up, remise_percent,";
4068 $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,";
4069 $sql .=
' tva_tx as vatrate, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type,';
4070 $sql .=
' info_bits, product_type,';
4071 if ($this->element ==
'expensereport') {
4072 $sql .=
' comments as description';
4074 $sql .=
' description';
4076 if ($this->table_element_line ==
'facturedet') {
4077 $sql .=
', situation_percent';
4079 $sql .=
', multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc';
4080 $sql .=
" FROM ".$this->db->prefix().$this->table_element_line;
4081 $sql .=
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
4083 $product_field =
'product_type';
4084 if ($this->table_element_line ==
'contratdet') {
4085 $product_field =
'';
4087 if ($product_field) {
4088 $sql .=
" AND ".$product_field.
" <> 9";
4091 $sql .=
' ORDER by rowid';
4093 dol_syslog(get_class($this).
"::update_price", LOG_DEBUG);
4095 $resql = $this->db->query($sql);
4097 $this->total_ht = 0;
4098 $this->total_tva = 0;
4099 $this->total_localtax1 = 0;
4100 $this->total_localtax2 = 0;
4101 $this->total_ttc = 0;
4102 $total_ht_by_vats = array();
4103 $total_tva_by_vats = array();
4104 $total_ttc_by_vats = array();
4105 $this->multicurrency_total_ht = 0;
4106 $this->multicurrency_total_tva = 0;
4107 $this->multicurrency_total_ttc = 0;
4111 $num = $this->db->num_rows($resql);
4114 $obj = $this->db->fetch_object($resql);
4117 $parameters = array(
'fk_element' => $obj->rowid);
4118 $reshook = $hookmanager->executeHooks(
'changeRoundingMode', $parameters, $this, $action);
4120 if (empty($reshook) && $forcedroundingmode ==
'0') {
4122 $localtax_array = array($obj->localtax1_type, $obj->localtax1_tx, $obj->localtax2_type, $obj->localtax2_tx);
4123 $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);
4125 $diff_when_using_price_ht =
price2num((
float) $tmpcal[1] - $obj->total_tva,
'MT', 1);
4126 $diff_on_current_total =
price2num($obj->total_ttc - $obj->total_ht - $obj->total_tva - $obj->total_localtax1 - $obj->total_localtax2,
'MT', 1);
4130 if ($diff_on_current_total) {
4132 $sqlfix =
"UPDATE ".$this->db->prefix().$this->table_element_line;
4133 $sqlfix .=
" SET ".$this->db->sanitize($fieldtva).
" = ".
price2num((
float) $tmpcal[1]).
", total_ttc = ".
price2num((
float) $tmpcal[2]);
4134 $sqlfix .=
", multicurrency_total_tva = ".price2num((
float) $tmpcal[17]).
", multicurrency_total_ttc = ".
price2num((
float) $tmpcal[18]);
4135 $sqlfix .=
" WHERE rowid = ".((int) $obj->rowid);
4136 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);
4137 $resqlfix = $this->db->query($sqlfix);
4141 $obj->total_tva = $tmpcal[1];
4142 $obj->total_ttc = $tmpcal[2];
4143 $obj->multicurrency_total_tva = $tmpcal[17];
4144 $obj->multicurrency_total_ttc = $tmpcal[18];
4145 } elseif ($diff_when_using_price_ht) {
4149 if ((
float) $tmpcal[0] == (
float) $obj->total_ht) {
4152 if ($obj->description !=
'(DEPOSIT)' && !
getDolGlobalInt(
'MAIN_DISABLE_AUTOFIX_CORRUPTED_LINES_WHEN_TOTAL_DOES_NOT_MATCH_RECALCULATION_FROM_UP')) {
4156 $sqlfix =
"UPDATE ".$this->db->prefix().$this->table_element_line;
4157 $sqlfix .=
" SET ".$this->db->sanitize($fieldtva).
" = ".
price2num((
float) $tmpcal[1]).
", total_ttc = ".
price2num((
float) $tmpcal[2]);
4158 $sqlfix .=
", multicurrency_total_tva = ".price2num((
float) $tmpcal[17]).
", multicurrency_total_ttc = ".
price2num((
float) $tmpcal[18]);
4159 $sqlfix .=
" WHERE rowid = ".((int) $obj->rowid);
4161 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);
4163 $resqlfix = $this->db->query($sqlfix);
4167 $obj->total_tva = $tmpcal[1];
4168 $obj->total_ttc = $tmpcal[2];
4169 $obj->multicurrency_total_tva = $tmpcal[17];
4170 $obj->multicurrency_total_ttc = $tmpcal[18];
4176 $this->total_ht += $obj->total_ht;
4177 $this->total_tva += $obj->total_tva;
4178 $this->total_localtax1 += $obj->total_localtax1;
4179 $this->total_localtax2 += $obj->total_localtax2;
4180 $this->total_ttc += $obj->total_ttc;
4181 $this->multicurrency_total_ht += $obj->multicurrency_total_ht;
4182 $this->multicurrency_total_tva += $obj->multicurrency_total_tva;
4183 $this->multicurrency_total_ttc += $obj->multicurrency_total_ttc;
4185 if (!isset($total_ht_by_vats[$obj->vatrate])) {
4186 $total_ht_by_vats[$obj->vatrate] = 0;
4188 if (!isset($total_tva_by_vats[$obj->vatrate])) {
4189 $total_tva_by_vats[$obj->vatrate] = 0;
4191 if (!isset($total_ttc_by_vats[$obj->vatrate])) {
4192 $total_ttc_by_vats[$obj->vatrate] = 0;
4194 $total_ht_by_vats[$obj->vatrate] += $obj->total_ht;
4195 $total_tva_by_vats[$obj->vatrate] += $obj->total_tva;
4196 $total_ttc_by_vats[$obj->vatrate] += $obj->total_ttc;
4198 if ($forcedroundingmode ==
'1') {
4199 if ($base_price_type ==
'TTC') {
4200 $tmpvat =
price2num($total_ttc_by_vats[$obj->vatrate] * $obj->vatrate / (100 + $obj->vatrate),
'MT', 1);
4202 $tmpvat =
price2num($total_ht_by_vats[$obj->vatrate] * $obj->vatrate / 100,
'MT', 1);
4204 $diff =
price2num($total_tva_by_vats[$obj->vatrate] - (
float) $tmpvat,
'MT', 1);
4207 $maxdiff = (10 * pow(10, -1 *
getDolGlobalInt(
'MAIN_MAX_DECIMALS_TOT', 0)));
4208 if (abs((
float) $diff) > $maxdiff) {
4210 $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.';
4212 $this->error = $errmsg;
4217 if ($base_price_type ==
'TTC') {
4218 $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);
4219 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);
4221 $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);
4222 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);
4225 $resqlfix = $this->db->query($sqlfix);
4231 $this->total_tva = (float)
price2num($this->total_tva - (
float) $diff,
'', 1);
4232 $total_tva_by_vats[$obj->vatrate] = (float)
price2num($total_tva_by_vats[$obj->vatrate] - (
float) $diff,
'', 1);
4233 if ($base_price_type ==
'TTC') {
4234 $this->total_ht = (float)
price2num($this->total_ht + (
float) $diff,
'', 1);
4235 $total_ht_by_vats[$obj->vatrate] = (float)
price2num($total_ht_by_vats[$obj->vatrate] + (
float) $diff,
'', 1);
4237 $this->total_ttc = (float)
price2num($this->total_ttc - (
float) $diff,
'', 1);
4238 $total_ttc_by_vats[$obj->vatrate] = (float)
price2num($total_ttc_by_vats[$obj->vatrate] - (
float) $diff,
'', 1);
4248 $this->total_ttc += isset($this->revenuestamp) ? $this->revenuestamp : 0;
4250 $this->multicurrency_total_ttc += isset($this->revenuestamp) ? ($this->revenuestamp * $multicurrency_tx) : 0;
4253 if (!empty($this->situation_cycle_ref) && !empty($this->situation_counter) && $this->situation_counter > 1 && method_exists($this,
'get_prev_sits')) {
4254 '@phan-var-force Facture $this';
4255 include_once DOL_DOCUMENT_ROOT.
'/compta/facture/class/facture.class.php';
4258 $prev_sits = $this->get_prev_sits();
4260 foreach ($prev_sits as $sit) {
4261 $this->total_ht -= $sit->total_ht;
4262 $this->total_tva -= $sit->total_tva;
4263 $this->total_localtax1 -= $sit->total_localtax1;
4264 $this->total_localtax2 -= $sit->total_localtax2;
4265 $this->total_ttc -= $sit->total_ttc;
4266 $this->multicurrency_total_ht -= $sit->multicurrency_total_ht;
4267 $this->multicurrency_total_tva -= $sit->multicurrency_total_tva;
4268 $this->multicurrency_total_ttc -= $sit->multicurrency_total_ttc;
4275 $this->total_ht = (float)
price2num($this->total_ht);
4276 $this->total_tva = (float)
price2num($this->total_tva);
4277 $this->total_localtax1 = (float)
price2num($this->total_localtax1);
4278 $this->total_localtax2 = (float)
price2num($this->total_localtax2);
4279 $this->total_ttc = (float)
price2num($this->total_ttc);
4281 $this->db->free($resql);
4284 $fieldht =
'total_ht';
4286 $fieldlocaltax1 =
'localtax1';
4287 $fieldlocaltax2 =
'localtax2';
4288 $fieldttc =
'total_ttc';
4290 if (in_array($this->element, array(
'propal',
'commande',
'facture',
'facturerec',
'supplier_proposal',
'order_supplier',
'facture_fourn',
'invoice_supplier',
'invoice_supplier_rec',
'expensereport'))) {
4291 $fieldtva =
'total_tva';
4294 if (!$error && empty($nodatabaseupdate)) {
4295 $sql =
"UPDATE ".$this->db->prefix().$this->table_element.
' SET';
4296 $sql .=
" ".$this->db->sanitize($fieldht).
" = ".((float)
price2num($this->total_ht,
'MT', 1)).
",";
4297 $sql .=
" ".$this->db->sanitize($fieldtva).
" = ".((float)
price2num($this->total_tva,
'MT', 1)).
",";
4298 $sql .=
" ".$this->db->sanitize($fieldlocaltax1).
" = ".((float)
price2num($this->total_localtax1,
'MT', 1)).
",";
4299 $sql .=
" ".$this->db->sanitize($fieldlocaltax2).
" = ".((float)
price2num($this->total_localtax2,
'MT', 1)).
",";
4300 $sql .=
" ".$this->db->sanitize($fieldttc).
" = ".((float)
price2num($this->total_ttc,
'MT', 1));
4301 $sql .=
", multicurrency_total_ht = ".((float)
price2num($this->multicurrency_total_ht,
'MT', 1));
4302 $sql .=
", multicurrency_total_tva = ".((float)
price2num($this->multicurrency_total_tva,
'MT', 1));
4303 $sql .=
", multicurrency_total_ttc = ".((float)
price2num($this->multicurrency_total_ttc,
'MT', 1));
4304 $sql .=
" WHERE rowid = ".((int) $this->
id);
4306 dol_syslog(get_class($this).
"::update_price", LOG_DEBUG);
4307 $resql = $this->db->query($sql);
4311 $this->error = $this->db->lasterror();
4312 $this->errors[] = $this->db->lasterror();
4317 $this->db->commit();
4320 $this->db->rollback();
4340 public function add_object_linked($origin =
null, $origin_id =
null, $f_user =
null, $notrigger = 0)
4343 global $user, $hookmanager, $action;
4345 if (empty($this->origin_type) && !empty($this->origin)) {
4346 $this->origin_type = $this->origin;
4348 $origin = (!empty($origin) ? $origin : $this->origin_type);
4349 $origin_id = (!empty($origin_id) ? $origin_id : $this->origin_id);
4350 $f_user = isset($f_user) ? $f_user : $user;
4353 if ($origin ==
'order') {
4354 $origin =
'commande';
4356 if ($origin ==
'invoice') {
4357 $origin =
'facture';
4359 if ($origin ==
'invoice_template') {
4360 $origin =
'facturerec';
4362 if ($origin ==
'supplierorder') {
4363 $origin =
'order_supplier';
4367 $targettype = $this->getElementType();
4369 $parameters = array(
'targettype' => $targettype);
4371 $reshook = $hookmanager->executeHooks(
'setLinkedObjectSourceTargetType', $parameters, $this, $action);
4373 if (!empty($hookmanager->resArray[
'targettype'])) {
4374 $targettype = $hookmanager->resArray[
'targettype'];
4381 $sql =
"INSERT INTO " . $this->db->prefix() .
"element_element (";
4382 $sql .=
"fk_source";
4383 $sql .=
", sourcetype";
4384 $sql .=
", fk_target";
4385 $sql .=
", targettype";
4386 $sql .=
") VALUES (";
4387 $sql .= ((int) $origin_id);
4388 $sql .=
", '" . $this->db->escape($origin) .
"'";
4389 $sql .=
", " . ((int) $this->
id);
4390 $sql .=
", '" . $this->db->escape($targettype) .
"'";
4393 dol_syslog(get_class($this) .
"::add_object_linked", LOG_DEBUG);
4394 if ($this->db->query($sql)) {
4397 $this->context[
'link_origin'] = $origin;
4398 $this->context[
'link_origin_id'] = $origin_id;
4400 $result = $this->call_trigger(
'OBJECT_LINK_INSERT', $f_user);
4407 $this->error = $this->db->lasterror();
4412 $this->db->commit();
4415 $this->db->rollback();
4429 $coreModule = array(
'knowledgemanagement',
'partnership',
'workstation',
'ticket',
'recruitment',
'eventorganization',
'asset');
4431 return ((!empty($this->module) && !in_array($this->module, $coreModule)) ? $this->module.
'_' :
'').$this->element;
4457 public function fetchObjectLinked($sourceid =
null, $sourcetype =
'', $targetid =
null, $targettype =
'', $clause =
'OR', $alsosametype = 1, $orderby =
'sourcetype', $loadalsoobjects = 1)
4459 global $hookmanager, $action;
4464 if ($this->
id > 0 && !empty($this->linkedObjectsFullLoaded[$this->
id])) {
4468 $this->linkedObjectsIds = array();
4469 $this->linkedObjects = array();
4472 $parameters = array(
4473 'sourceid' => $sourceid,
4474 'sourcetype' => $sourcetype,
4475 'targetid' => $targetid,
4476 'targettype' => $targettype,
4477 'clause' => $clause,
4478 'alsosametype' => $alsosametype,
4479 'orderby' => $orderby,
4480 'loadalsoobjects' => $loadalsoobjects
4482 $reshook = $hookmanager->executeHooks(
'fetchObjectLinked', $parameters, $this, $action);
4487 $justsource =
false;
4488 $justtarget =
false;
4489 $withtargettype =
false;
4490 $withsourcetype =
false;
4493 if (is_object($hookmanager)) {
4494 $parameters = array(
'sourcetype' => $sourcetype,
'sourceid' => $sourceid,
'targettype' => $targettype,
'targetid' => $targetid);
4495 $reshook = $hookmanager->executeHooks(
'setLinkedObjectSourceTargetType', $parameters, $this, $action);
4497 if (!empty($hookmanager->resArray[
'sourcetype'])) {
4498 $sourcetype = $hookmanager->resArray[
'sourcetype'];
4500 if (!empty($hookmanager->resArray[
'sourceid'])) {
4501 $sourceid = $hookmanager->resArray[
'sourceid'];
4503 if (!empty($hookmanager->resArray[
'targettype'])) {
4504 $targettype = $hookmanager->resArray[
'targettype'];
4506 if (!empty($hookmanager->resArray[
'targetid'])) {
4507 $targetid = $hookmanager->resArray[
'targetid'];
4512 if (!empty($sourceid) && !empty($sourcetype) && empty($targetid)) {
4514 if (!empty($targettype)) {
4515 $withtargettype =
true;
4518 if (!empty($targetid) && !empty($targettype) && empty($sourceid)) {
4520 if (!empty($sourcetype)) {
4521 $withsourcetype =
true;
4525 $sourceid = (!empty($sourceid) ? $sourceid :
$this->id);
4526 $targetid = (!empty($targetid) ? $targetid :
$this->id);
4527 $sourcetype = (!empty($sourcetype) ? $sourcetype : $this->getElementType());
4528 $targettype = (!empty($targettype) ? $targettype : $this->getElementType());
4537 $sql =
"SELECT rowid, fk_source, sourcetype, fk_target, targettype";
4538 $sql .=
" FROM ".$this->db->prefix().
"element_element";
4540 if ($justsource || $justtarget) {
4542 $sql .=
"fk_source = ".((int) $sourceid).
" AND sourcetype = '".$this->db->escape($sourcetype).
"'";
4543 if ($withtargettype) {
4544 $sql .=
" AND targettype = '".$this->db->escape($targettype).
"'";
4546 } elseif ($justtarget) {
4547 $sql .=
"fk_target = ".((int) $targetid).
" AND targettype = '".$this->db->escape($targettype).
"'";
4548 if ($withsourcetype) {
4549 $sql .=
" AND sourcetype = '".$this->db->escape($sourcetype).
"'";
4553 $sql .=
"(fk_source = ".((int) $sourceid).
" AND sourcetype = '".$this->db->escape($sourcetype).
"')";
4554 $sql .=
" ".$this->db->sanitize($clause).
" (fk_target = ".((int) $targetid).
" AND targettype = '".$this->db->escape($targettype).
"')";
4555 if ($loadalsoobjects && $this->
id > 0 && $sourceid == $this->
id && $sourcetype == $this->element && $targetid == $this->
id && $targettype == $this->element && $clause ==
'OR') {
4556 $this->linkedObjectsFullLoaded[
$this->id] =
true;
4559 $sql .=
" ORDER BY ".$orderby;
4561 dol_syslog(get_class($this).
"::fetchObjectLink", LOG_DEBUG);
4562 $resql = $this->db->query($sql);
4564 $num = $this->db->num_rows($resql);
4567 $obj = $this->db->fetch_object($resql);
4568 if ($justsource || $justtarget) {
4570 $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
4571 } elseif ($justtarget) {
4572 $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
4575 if ($obj->fk_source == $sourceid && $obj->sourcetype == $sourcetype) {
4576 $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
4578 if ($obj->fk_target == $targetid && $obj->targettype == $targettype) {
4579 $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
4585 if (!empty($this->linkedObjectsIds)) {
4586 $tmparray = $this->linkedObjectsIds;
4587 foreach ($tmparray as $objecttype => $objectids) {
4589 $element = $element_properties[
'element'];
4590 $classPath = $element_properties[
'classpath'];
4591 $classFile = $element_properties[
'classfile'];
4592 $className = $element_properties[
'classname'];
4593 $module = $element_properties[
'module'];
4596 if (
isModEnabled($module) && (($element != $this->element) || $alsosametype)) {
4597 if ($loadalsoobjects && (is_numeric($loadalsoobjects) || ($loadalsoobjects === $objecttype))) {
4599 if (class_exists($className)) {
4600 foreach ($objectids as $i => $objectid) {
4601 $object =
new $className($this->db);
4602 '@phan-var-force CommonObject $object';
4603 $ret =
$object->fetch($objectid);
4605 $this->linkedObjects[$objecttype][$i] =
$object;
4611 unset($this->linkedObjectsIds[$objecttype]);
4630 if ($this->
id > 0 && !empty($this->linkedObjectsFullLoaded[$this->
id])) {
4631 unset($this->linkedObjectsFullLoaded[$this->
id]);
4649 public function updateObjectLinked($sourceid =
null, $sourcetype =
'', $targetid =
null, $targettype =
'', $f_user =
null, $notrigger = 0)
4652 $updatesource =
false;
4653 $updatetarget =
false;
4654 $f_user = isset($f_user) ? $f_user : $user;
4656 if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) {
4657 $updatesource =
true;
4658 } elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) {
4659 $updatetarget =
true;
4665 $sql =
"UPDATE " . $this->db->prefix() .
"element_element SET ";
4666 if ($updatesource) {
4667 $sql .=
"fk_source = " . ((int) $sourceid);
4668 $sql .=
", sourcetype = '" . $this->db->escape($sourcetype) .
"'";
4669 $sql .=
" WHERE fk_target = " . ((int) $this->
id);
4670 $sql .=
" AND targettype = '" . $this->db->escape($this->element) .
"'";
4671 } elseif ($updatetarget) {
4672 $sql .=
"fk_target = " . ((int) $targetid);
4673 $sql .=
", targettype = '" . $this->db->escape($targettype) .
"'";
4674 $sql .=
" WHERE fk_source = " . ((int) $this->
id);
4675 $sql .=
" AND sourcetype = '" . $this->db->escape($this->element) .
"'";
4678 dol_syslog(get_class($this) .
"::updateObjectLinked", LOG_DEBUG);
4679 if ($this->db->query($sql)) {
4682 $this->context[
'link_source_id'] = $sourceid;
4683 $this->context[
'link_source_type'] = $sourcetype;
4684 $this->context[
'link_target_id'] = $targetid;
4685 $this->context[
'link_target_type'] = $targettype;
4687 $result = $this->call_trigger(
'OBJECT_LINK_MODIFY', $f_user);
4694 $this->error = $this->db->lasterror();
4699 $this->db->commit();
4702 $this->db->rollback();
4720 public function deleteObjectLinked($sourceid =
null, $sourcetype =
'', $targetid =
null, $targettype =
'', $rowid = 0, $f_user =
null, $notrigger = 0)
4723 $deletesource =
false;
4724 $deletetarget =
false;
4725 $f_user = isset($f_user) ? $f_user : $user;
4727 if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) {
4728 $deletesource =
true;
4729 } elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) {
4730 $deletetarget =
true;
4733 $element = $this->getElementType();
4734 $sourceid = (!empty($sourceid) ? $sourceid :
$this->id);
4735 $sourcetype = (!empty($sourcetype) ? $sourcetype : $element);
4736 $targetid = (!empty($targetid) ? $targetid :
$this->id);
4737 $targettype = (!empty($targettype) ? $targettype : $element);
4743 $this->context[
'link_id'] = $rowid;
4744 $this->context[
'link_source_id'] = $sourceid;
4745 $this->context[
'link_source_type'] = $sourcetype;
4746 $this->context[
'link_target_id'] = $targetid;
4747 $this->context[
'link_target_type'] = $targettype;
4749 $result = $this->call_trigger(
'OBJECT_LINK_DELETE', $f_user);
4757 $sql =
"DELETE FROM " . $this->db->prefix() .
"element_element";
4760 $sql .=
" rowid = " . ((int) $rowid);
4762 if ($deletesource) {
4763 $sql .=
" fk_source = " . ((int) $sourceid) .
" AND sourcetype = '" . $this->db->escape($sourcetype) .
"'";
4764 $sql .=
" AND fk_target = " . ((int) $this->
id) .
" AND targettype = '" . $this->db->escape($element) .
"'";
4765 } elseif ($deletetarget) {
4766 $sql .=
" fk_target = " . ((int) $targetid) .
" AND targettype = '" . $this->db->escape($targettype) .
"'";
4767 $sql .=
" AND fk_source = " . ((int) $this->
id) .
" AND sourcetype = '" . $this->db->escape($element) .
"'";
4769 $sql .=
" (fk_source = " . ((int) $this->
id) .
" AND sourcetype = '" . $this->db->escape($element) .
"')";
4771 $sql .=
" (fk_target = " . ((int) $this->
id) .
" AND targettype = '" . $this->db->escape($element) .
"')";
4775 dol_syslog(get_class($this) .
"::deleteObjectLinked", LOG_DEBUG);
4776 if (!$this->db->query($sql)) {
4777 $this->error = $this->db->lasterror();
4778 $this->errors[] = $this->error;
4784 $this->db->commit();
4787 $this->db->rollback();
4803 if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
4806 if (!preg_match(
'/^[_a-zA-Z0-9]+$/', $field_select)) {
4807 dol_syslog(
'Invalid value $field_select for parameter '.$field_select.
' in call to getAllItemsLinkedByObjectID(). Must be a single field name.', LOG_ERR);
4812 $sql =
"SELECT ".$field_select.
" FROM ".$db->prefix().$table_element.
" WHERE ".$field_where.
" = ".((int) $fk_object_where);
4813 $resql = $db->query($sql);
4816 if (!empty($resql)) {
4817 while ($res = $db->fetch_object($resql)) {
4818 $TRes[] = $res->{$field_select};
4835 if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
4841 $sql =
"SELECT COUNT(*) as nb FROM ".$db->prefix().$table_element.
" WHERE ".$field_where.
" = ".((int) $fk_object_where);
4842 $resql = $db->query($sql);
4845 $res = $db->fetch_object($resql);
4864 if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
4870 $sql =
"DELETE FROM ".$db->prefix().$table_element.
" WHERE ".$field_where.
" = ".((int) $fk_object_where);
4871 $resql = $db->query($sql);
4873 if (empty($resql)) {
4891 public function setStatut($status, $elementId =
null, $elementType =
'', $trigkey =
'', $fieldstatus =
'')
4895 $savElementId = $elementId;
4897 $elementId = (!empty($elementId) ? $elementId :
$this->id);
4898 $elementTable = (!empty($elementType) ? $elementType : $this->table_element);
4902 if (empty($fieldstatus)) {
4903 if ($elementTable ==
'facture_rec') {
4904 $fieldstatus =
"suspended";
4906 if ($elementTable ==
'mailing') {
4907 $fieldstatus =
"statut";
4909 if ($elementTable ==
'cronjob') {
4910 $fieldstatus =
"status";
4912 if ($elementTable ==
'user') {
4913 $fieldstatus =
"statut";
4915 if ($elementTable ==
'expensereport') {
4916 $fieldstatus =
"fk_statut";
4918 if ($elementTable ==
'receptiondet_batch') {
4919 $fieldstatus =
"status";
4921 if ($elementTable ==
'prelevement_bons') {
4922 $fieldstatus =
"statut";
4924 if (isset($this->fields) && is_array($this->fields) && array_key_exists(
'status', $this->fields)) {
4925 $fieldstatus =
'status';
4928 if (empty($fieldstatus)) {
4929 $fieldstatus =
'fk_statut';
4933 $sql =
"UPDATE ".$this->db->prefix().$this->db->sanitize($elementTable);
4934 $sql .=
" SET ".$this->db->sanitize($fieldstatus).
" = ".((int) $status);
4937 if ($status == 1 && in_array($elementTable, array(
'expensereport',
'inventory'))) {
4938 $sql .=
", fk_user_valid = ".((int) $user->id);
4940 if ($status == 1 && in_array($elementTable, array(
'expensereport'))) {
4941 $sql .=
", date_valid = '".$this->db->idate(
dol_now()).
"'";
4943 if ($status == 1 && in_array($elementTable, array(
'inventory'))) {
4944 $sql .=
", date_validation = '".$this->db->idate(
dol_now()).
"'";
4946 $sql .=
" WHERE rowid = ".((int) $elementId);
4947 $sql .=
" AND ".$this->db->sanitize($fieldstatus).
" <> ".((int) $status);
4949 dol_syslog(get_class($this).
"::setStatut", LOG_DEBUG);
4950 $resql = $this->db->query($sql);
4954 $nb_rows_affected = $this->db->affected_rows($resql);
4956 if ($nb_rows_affected > 0) {
4957 if (empty($trigkey)) {
4959 if ($this->element ==
'supplier_proposal' && $status == 2) {
4960 $trigkey =
'SUPPLIER_PROPOSAL_SIGN';
4962 if ($this->element ==
'supplier_proposal' && $status == 3) {
4963 $trigkey =
'SUPPLIER_PROPOSAL_REFUSE';
4965 if ($this->element ==
'supplier_proposal' && $status == 4) {
4966 $trigkey =
'SUPPLIER_PROPOSAL_CLOSE';
4968 if ($this->element ==
'fichinter' && $status == 3) {
4969 $trigkey =
'FICHINTER_CLASSIFY_DONE';
4971 if ($this->element ==
'fichinter' && $status == 2) {
4972 $trigkey =
'FICHINTER_CLASSIFY_BILLED';
4974 if ($this->element ==
'fichinter' && $status == 1) {
4975 $trigkey =
'FICHINTER_CLASSIFY_UNBILLED';
4979 $this->context = array_merge($this->context, array(
'newstatus' => $status));
4981 if ($trigkey && $trigkey !=
'none') {
4985 $result = $this->call_trigger($trigkey, $user);
4996 $this->db->commit();
4998 if (empty($savElementId)) {
5000 if ($fieldstatus ==
'dispute_status') {
5001 $this->dispute_status = $status;
5002 } elseif ($fieldstatus ==
'tosell') {
5004 } elseif ($fieldstatus ==
'tobuy') {
5005 $this->status_buy = $status;
5006 } elseif ($fieldstatus ==
'tobatch') {
5007 $this->status_batch = $status;
5015 $this->db->rollback();
5016 dol_syslog(get_class($this).
"::setStatut ".$this->error, LOG_ERR);
5020 $this->error = $this->db->lasterror();
5021 $this->db->rollback();
5036 if (empty(
$id) && empty($ref)) {
5046 $sql =
"SELECT rowid, canvas";
5047 $sql .=
" FROM ".$this->db->prefix().$this->table_element;
5048 $sql .=
" WHERE entity IN (".getEntity($this->element).
")";
5050 $sql .=
" AND rowid = ".((int)
$id);
5053 $sql .=
" AND ref = '".$this->db->escape($ref).
"'";
5056 $resql = $this->db->query($sql);
5058 $obj = $this->db->fetch_object($resql);
5060 $this->canvas = $obj->canvas;
5080 $sql =
"SELECT special_code FROM ".$this->db->prefix().$this->table_element_line;
5081 $sql .=
" WHERE rowid = ".((int) $lineid);
5082 $resql = $this->db->query($sql);
5084 $row = $this->db->fetch_row($resql);
5085 return (!empty($row[0]) ? $row[0] : 0);
5108 if (!isset($this->childtables) || !is_array($this->childtables) || count($this->childtables) == 0) {
5109 dol_print_error(
null,
'Called isObjectUsed on a class with property this->childtables not defined');
5113 $arraytoscan = $this->childtables;
5115 $tmparray = array_keys($this->childtables);
5116 if (is_numeric($tmparray[0])) {
5117 $arraytoscan = array_flip($this->childtables);
5122 foreach ($arraytoscan as $table => $element) {
5126 if (isset($element[
'enabled']) && !empty($element[
'enabled'])) {
5127 $enabled = (int)
dol_eval((
string) $element[
'enabled'], 1);
5128 if (empty($enabled)) {
5134 $sql =
"SELECT COUNT(*) as nb";
5135 $sql .=
" FROM ".$this->db->prefix().$table.
" as c";
5136 if (!empty($element[
'parent']) && !empty($element[
'parentkey'])) {
5137 $sql .=
", ".$this->db->prefix().$element[
'parent'].
" as p";
5139 if (!empty($element[
'fk_element'])) {
5140 $sql .=
" WHERE c.".$element[
'fk_element'].
" = ".((int)
$id);
5142 $sql .=
" WHERE c.".$this->fk_element.
" = ".((int)
$id);
5144 if (!empty($element[
'parent']) && !empty($element[
'parentkey'])) {
5145 $sql .=
" AND c.".$element[
'parentkey'].
" = p.rowid";
5147 if (!empty($element[
'parent']) && !empty($element[
'parenttypefield']) && !empty($element[
'parenttypevalue'])) {
5148 $sql .=
" AND c.".$element[
'parenttypefield'].
" = '".$this->db->escape($element[
'parenttypevalue']).
"'";
5150 if (!empty($entity)) {
5151 if (!empty($element[
'parent']) && !empty($element[
'parentkey'])) {
5152 $sql .=
" AND p.entity = ".((int) $entity);
5154 $sql .=
" AND c.entity = ".((int) $entity);
5158 $resql = $this->db->query($sql);
5160 $obj = $this->db->fetch_object($resql);
5162 $langs->load(
"errors");
5164 $haschild += $obj->nb;
5165 if (is_numeric($element)) {
5166 $this->errors[] = $langs->transnoentitiesnoconv(
"ErrorRecordHasAtLeastOneChildOfType", method_exists($this,
'getNomUrl') ? $this->getNomUrl() : $this->ref, $table);
5167 } elseif (is_string($element)) {
5168 $this->errors[] = $langs->transnoentitiesnoconv(
"ErrorRecordHasAtLeastOneChildOfType", method_exists($this,
'getNomUrl') ? $this->getNomUrl() : $this->ref, $langs->transnoentitiesnoconv($element));
5170 $this->errors[] = $langs->transnoentitiesnoconv(
"ErrorRecordHasAtLeastOneChildOfType", method_exists($this,
'getNomUrl') ? $this->getNomUrl() : $this->ref, $langs->transnoentitiesnoconv($element[
'name']));
5175 $this->errors[] = $this->db->lasterror();
5179 if ($haschild > 0) {
5180 $this->errors[] =
"ErrorRecordHasChildren";
5197 foreach ($this->lines as $key => $val) {
5199 if ($predefined == -1) {
5202 if ($predefined == 1 && $val->fk_product > 0) {
5205 if ($predefined == 0 && $val->fk_product <= 0) {
5208 if ($predefined == 2 && $val->fk_product > 0 && $val->product_type == 0) {
5211 if ($predefined == 3 && $val->fk_product > 0 && $val->product_type == 1) {
5218 dol_syslog(get_class($this).
'::hasProductsOrServices we found '.$nb.
' qualified lines of products/servcies');
5229 if (!empty($this->table_element_line) && ($this->table_element_line !=
'expeditiondet')) {
5230 $total_discount = 0.00;
5232 $sql =
"SELECT subprice as pu_ht, qty, remise_percent, total_ht";
5233 $sql .=
" FROM ".$this->db->prefix().$this->table_element_line;
5234 $sql .=
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
5236 dol_syslog(get_class($this).
'::getTotalDiscount', LOG_DEBUG);
5237 $resql = $this->db->query($sql);
5239 $num = $this->db->num_rows($resql);
5242 $obj = $this->db->fetch_object($resql);
5244 $pu_ht = $obj->pu_ht;
5246 $total_ht = $obj->total_ht;
5248 $total_discount_line = (float)
price2num(($pu_ht * $qty) - $total_ht,
'MT');
5249 $total_discount += $total_discount_line;
5256 return (
float)
price2num($total_discount);
5278 if (empty($this->lines)) {
5279 return array(
'weight' => $totalWeight,
'volume' => $totalVolume,
'ordered' => $totalOrdered,
'toship' => $totalToShip);
5282 foreach ($this->lines as $line) {
5283 if (isset($line->qty_asked)) {
5284 $totalOrdered += $line->qty_asked;
5286 if (isset($line->qty_shipped)) {
5287 $totalToShip += $line->qty_shipped;
5288 } elseif ($line->element ==
'commandefournisseurdispatch' && isset($line->qty)) {
5289 if (empty($totalToShip)) {
5292 $totalToShip += $line->qty;
5296 if ($this->element ==
'shipping') {
5298 $qty = $line->qty_shipped ? $line->qty_shipped : 0;
5300 $qty = $line->qty ? $line->qty : 0;
5303 $weight = !empty($line->weight) ? $line->weight : 0;
5304 ($weight == 0 && !empty($line->product->weight)) ? $weight = $line->product->weight : 0;
5305 $volume = !empty($line->volume) ? $line->volume : 0;
5306 ($volume == 0 && !empty($line->product->volume)) ? $volume = $line->product->volume : 0;
5308 $weight_units = !empty($line->weight_units) ? $line->weight_units : 0;
5309 ($weight_units == 0 && !empty($line->product->weight_units)) ? $weight_units = $line->product->weight_units : 0;
5310 $volume_units = !empty($line->volume_units) ? $line->volume_units : 0;
5311 ($volume_units == 0 && !empty($line->product->volume_units)) ? $volume_units = $line->product->volume_units : 0;
5315 if (!empty($weight_units)) {
5316 $weightUnit = $weight_units;
5318 if (!empty($volume_units)) {
5319 $volumeUnit = $volume_units;
5322 if (empty($totalWeight)) {
5325 if (empty($totalVolume)) {
5330 if ($weight_units < 50) {
5331 $trueWeightUnit = pow(10, $weightUnit);
5332 $totalWeight += $weight * $qty * $trueWeightUnit;
5334 if ($weight_units == 99) {
5336 $trueWeightUnit = 0.45359237;
5337 $totalWeight += $weight * $qty * $trueWeightUnit;
5338 } elseif ($weight_units == 98) {
5340 $trueWeightUnit = 0.0283495;
5341 $totalWeight += $weight * $qty * $trueWeightUnit;
5343 $totalWeight += $weight * $qty;
5346 if ($volume_units < 50) {
5348 $trueVolumeUnit = pow(10, $volumeUnit);
5350 $totalVolume += $volume * $qty * $trueVolumeUnit;
5352 $totalVolume += $volume * $qty;
5356 return array(
'weight' => $totalWeight,
'volume' => $totalVolume,
'ordered' => $totalOrdered,
'toship' => $totalToShip);
5369 $extraparams = (!empty($this->extraparams) ? json_encode($this->extraparams) :
null);
5370 $extraparams =
dol_trunc($extraparams, 250);
5372 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
5373 $sql .=
" SET extraparams = ".(!empty($extraparams) ?
"'".$this->db->escape($extraparams).
"'" :
"null");
5374 $sql .=
" WHERE rowid = ".((int) $this->
id);
5376 dol_syslog(get_class($this).
"::setExtraParameters", LOG_DEBUG);
5377 $resql = $this->db->query($sql);
5379 $this->error = $this->db->lasterror();
5380 $this->db->rollback();
5383 $this->db->commit();
5406 global $conf, $user, $langs,
$object, $hookmanager, $extrafields, $form;
5409 if (!is_object($extrafields)) {
5410 require_once DOL_DOCUMENT_ROOT.
'/core/class/extrafields.class.php';
5413 $extrafields->fetch_name_optionals_label($this->table_element_line);
5418 $dirtpls = array_merge($conf->modules_parts[
'tpl'], array($defaulttpldir));
5419 foreach ($dirtpls as $module => $reldir) {
5420 if (!empty($module)) {
5423 $tpl = DOL_DOCUMENT_ROOT.$reldir.
'/objectline_create.tpl.php';
5426 if (empty($conf->file->strict_mode)) {
5427 $res = @include $tpl;
5429 $res = include $tpl;
5456 public function printObjectLines($action, $seller, $buyer, $selected = 0, $dateSelector = 0, $defaulttpldir =
'/core/tpl')
5458 global $conf, $hookmanager, $langs, $user, $form, $extrafields,
$object;
5460 global $inputalsopricewithtax, $usemargins, $disableedit, $disablemove, $disableremove, $outputalsopricetotalwithtax;
5464 if (
isModEnabled(
'margin') && !empty($this->element) && in_array($this->element, array(
'facture',
'facturerec',
'propal',
'commande'))) {
5468 $num = count($this->lines);
5471 if (!is_object($extrafields)) {
5472 require_once DOL_DOCUMENT_ROOT.
'/core/class/extrafields.class.php';
5475 $extrafields->fetch_name_optionals_label($this->table_element_line);
5477 if (method_exists($this,
'loadExpeditions')) {
5479 $this->loadExpeditions();
5482 $parameters = array();
5483 $reshook = $hookmanager->executeHooks(
'printObjectLinesBlock', $parameters, $this, $action);
5484 if (empty($reshook)) {
5485 $parameters = array(
'num' => $num,
'dateSelector' => $dateSelector,
'seller' => $seller,
'buyer' => $buyer,
'selected' => $selected,
'table_element_line' => $this->table_element_line);
5486 $reshook = $hookmanager->executeHooks(
'printObjectLineTitle', $parameters, $this, $action);
5487 if (empty($reshook)) {
5491 $dirtpls = array_merge($conf->modules_parts[
'tpl'], array($defaulttpldir));
5492 foreach ($dirtpls as $module => $reldir) {
5494 if (!empty($module)) {
5497 $tpl = DOL_DOCUMENT_ROOT.$reldir.
'/objectline_title.tpl.php';
5499 if (file_exists($tpl)) {
5500 if (empty($conf->file->strict_mode)) {
5501 $res = @include $tpl;
5503 $res = include $tpl;
5514 print
"<!-- begin printObjectLines() -->\n";
5515 foreach ($this->lines as $line) {
5519 if (is_object($hookmanager)) {
5520 if (empty($line->fk_parent_line)) {
5521 $parameters = array(
'line' => $line,
'num' => $num,
'i' => $i,
'dateSelector' => $dateSelector,
'seller' => $seller,
'buyer' => $buyer,
'selected' => $selected,
'table_element_line' => $line->table_element,
'defaulttpldir' => $defaulttpldir);
5522 $reshook = $hookmanager->executeHooks(
'printObjectLine', $parameters, $this, $action);
5524 $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);
5525 $reshook = $hookmanager->executeHooks(
'printObjectSubLine', $parameters, $this, $action);
5528 if (empty($reshook)) {
5529 $this->printObjectLine($action, $line,
'', $num, $i, $dateSelector, $seller, $buyer, $selected, $extrafields, $defaulttpldir);
5534 print
"<!-- end printObjectLines() -->\n";
5555 public function printObjectLine($action, $line, $var, $num, $i, $dateSelector, $seller, $buyer, $selected = 0, $extrafields =
null, $defaulttpldir =
'/core/tpl')
5557 global $conf, $langs, $user,
$object, $hookmanager;
5559 global $disableedit, $disablemove, $disableremove;
5566 if ($action !=
'editline' || $selected != $line->id) {
5568 if (!empty($line->fk_product) && $line->fk_product > 0) {
5569 $product_static =
new Product($this->db);
5570 $product_static->fetch($line->fk_product);
5572 $product_static->ref = $line->ref;
5573 $product_static->label = !empty($line->label) ? $line->label :
"";
5575 $text = $product_static->getNomUrl(1);
5580 if (property_exists($this,
'socid') && !empty($this->socid) && !is_object($this->thirdparty)) {
5581 dol_print_error(
null,
'Error: Method printObjectLine was called on an object and object->fetch_thirdparty was not done before');
5585 $prod =
new Product($this->db);
5586 $prod->fetch($line->fk_product);
5588 $outputlangs = $langs;
5590 if (empty($newlang) &&
GETPOST(
'lang_id',
'aZ09')) {
5591 $newlang =
GETPOST(
'lang_id',
'aZ09');
5593 if (
getDolGlobalString(
'PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE') && empty($newlang) && is_object($this->thirdparty)) {
5594 $newlang = $this->thirdparty->default_lang;
5596 if (!empty($newlang)) {
5597 $outputlangs =
new Translate(
"", $conf);
5598 $outputlangs->setDefaultLang($newlang);
5601 $label = (!empty($prod->multilangs[$outputlangs->defaultlang][
"label"])) ? $prod->multilangs[$outputlangs->defaultlang][
"label"] : $line->product_label;
5603 $label = $line->product_label;
5606 $text .=
' - '.(!empty($line->label) ? $line->label : $label);
5607 $description .= (
getDolGlobalInt(
'PRODUIT_DESC_IN_FORM_ACCORDING_TO_DEVICE') ?
'' : (!empty($line->description) ?
dol_htmlentitiesbr($line->description) :
''));
5611 if (empty((
float) $line->subprice_ttc) && $line->qty) {
5613 if ($line->remise_percent != 100) {
5614 $line->subprice_ttc = (float)
price2num($line->total_ttc / $line->qty / (1 - $line->remise_percent / 100),
'MU');
5617 $line->subprice_ttc = (float)
price2num((!empty($line->subprice) ? $line->subprice : 0) * (1 + ((!empty($line->tva_tx) ? $line->tva_tx : 0) / 100)),
'MU');
5620 $line->pu_ttc = $line->subprice_ttc;
5627 if (isset($this->expeditions[$line->id])) {
5628 $qty_shipped = $this->expeditions[$line->id];
5630 $disableedit = ($qty_shipped > 0) && ($qty_shipped >= $line->qty);
5632 $dirtpls = array_merge($conf->modules_parts[
'tpl'], array($defaulttpldir));
5633 foreach ($dirtpls as $module => $reldir) {
5635 if (!empty($module)) {
5638 $tpl = DOL_DOCUMENT_ROOT.$reldir.
'/objectline_view.tpl.php';
5641 if (file_exists($tpl)) {
5642 if (empty($conf->file->strict_mode)) {
5643 $res = @include $tpl;
5645 $res = include $tpl;
5655 if ($this->
status == 0 && $action ==
'editline' && $selected == $line->id) {
5656 $label = (!empty($line->label) ? $line->label : (($line->fk_product > 0) ? $line->product_label :
''));
5658 $line->subprice_ttc = (float)
price2num($line->subprice * (1 + ($line->tva_tx / 100)),
'MU');
5659 $line->pu_ttc = $line->subprice_ttc;
5664 $dirtpls = array_merge($conf->modules_parts[
'tpl'], array($defaulttpldir));
5665 foreach ($dirtpls as $module => $reldir) {
5666 if (!empty($module)) {
5669 $tpl = DOL_DOCUMENT_ROOT.$reldir.
'/objectline_edit.tpl.php';
5672 if (empty($conf->file->strict_mode)) {
5673 $res = @include $tpl;
5675 $res = include $tpl;
5700 global $langs, $hookmanager, $form, $action;
5702 print
'<!-- printOriginLinesList '.get_class($this).
' -->'.
"\n";
5703 print
'<tr class="liste_titre">';
5704 print
'<td class="linecolref">'.$langs->trans(
'Ref').
'</td>';
5705 print
'<td class="linecoldescription">'.$langs->trans(
'Description').
'</td>';
5706 print
'<td class="linecolvat right">'.$langs->trans(
'VATRate').
'</td>';
5707 print
'<td class="linecoluht right">'.$langs->trans(
'PriceUHT').
'</td>';
5709 print
'<td class="linecoluht_currency right">'.$langs->trans(
'PriceUHTCurrency').
'</td>';
5711 print
'<td class="linecolqty right">'.$langs->trans(
'Qty').
'</td>';
5713 print
'<td class="linecoluseunit left">'.$langs->trans(
'Unit').
'</td>';
5715 print
'<td class="linecoldiscount right">'.$langs->trans(
'ReductionShort').
'</td>';
5716 print
'<td class="linecolht right">'.$langs->trans(
'TotalHT').
'</td>';
5717 print
'<td class="center">';
5718 print $form->showCheckAddButtons(
'checkforselect', 1);
5723 if (!empty($this->lines)) {
5724 foreach ($this->lines as $line) {
5727 if (is_object($hookmanager)) {
5728 $parameters = array(
'line' => $line,
'i' => $i,
'restrictlist' => $restrictlist,
'selectedLines' => $selectedLines);
5729 if (!empty($line->fk_parent_line)) {
5730 $parameters[
'fk_parent_line'] = $line->fk_parent_line;
5732 $reshook = $hookmanager->executeHooks(
'printOriginObjectLine', $parameters, $this, $action);
5734 if (empty($reshook)) {
5735 $this->printOriginLine($line,
'', $restrictlist,
'/core/tpl', $selectedLines);
5756 public function printOriginLine($line, $var, $restrictlist =
'', $defaulttpldir =
'/core/tpl', $selectedLines = array())
5758 global $langs, $conf;
5761 if (!empty($line->date_start)) {
5763 $date_start = $line->date_start;
5765 $date_start = $line->date_debut_prevue;
5766 if ($line->date_debut_reel) {
5767 $date_start = $line->date_debut_reel;
5770 if (!empty($line->date_end)) {
5772 $date_end = $line->date_end;
5774 $date_end = $line->date_fin_prevue;
5775 if ($line->date_fin_reel) {
5776 $date_end = $line->date_fin_reel;
5781 $this->tpl[
'id'] = $line->id;
5783 $this->tpl[
'label'] =
'';
5784 if (!empty($line->fk_parent_line)) {
5785 $this->tpl[
'label'] .=
img_picto(
'',
'rightarrow.png');
5788 if (((
int) $line->info_bits & 2) == 2) {
5790 if (property_exists($this,
'socid')) {
5791 $discount->fk_soc = $this->socid;
5792 $discount->socid = $this->socid;
5794 $this->tpl[
'label'] .= $discount->getNomUrl(0,
'discount');
5795 } elseif (!empty($line->fk_product)) {
5796 $productstatic =
new Product($this->db);
5797 $productstatic->id = $line->fk_product;
5798 $productstatic->ref = $line->ref;
5799 $productstatic->type = $line->fk_product_type;
5800 if (empty($productstatic->ref)) {
5801 $line->fetch_product();
5802 $productstatic = $line->product;
5805 $this->tpl[
'label'] .= $productstatic->getNomUrl(1);
5806 $this->tpl[
'label'] .=
' - '.(!empty($line->label) ? $line->label : $line->product_label);
5808 if ($line->product_type == 1 && ($date_start || $date_end)) {
5812 $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"')));
5813 if (!empty($line->desc)) {
5814 $this->tpl[
'label'] .= $line->desc;
5816 $this->tpl[
'label'] .= ($line->label ?
' '.$line->label :
'');
5820 if ($line->product_type == 1 && ($date_start || $date_end)) {
5825 if (!empty($line->desc)) {
5826 '@phan-var-force OrderLine|FactureLigne|ContratLigne|FactureFournisseurLigneRec|SupplierInvoiceLine|SupplierProposalLine $line';
5827 if ($line->desc ==
'(CREDIT_NOTE)') {
5829 $discount->fetch($line->fk_remise_except);
5830 $this->tpl[
'description'] = $langs->transnoentities(
"DiscountFromCreditNote", $discount->getNomUrl(0));
5831 } elseif ($line->desc ==
'(DEPOSIT)') {
5833 $discount->fetch($line->fk_remise_except);
5834 $this->tpl[
'description'] = $langs->transnoentities(
"DiscountFromDeposit", $discount->getNomUrl(0));
5835 } elseif ($line->desc ==
'(EXCESS RECEIVED)') {
5837 $discount->fetch($line->fk_remise_except);
5838 $this->tpl[
'description'] = $langs->transnoentities(
"DiscountFromExcessReceived", $discount->getNomUrl(0));
5839 } elseif ($line->desc ==
'(EXCESS PAID)') {
5841 $discount->fetch($line->fk_remise_except);
5842 $this->tpl[
'description'] = $langs->transnoentities(
"DiscountFromExcessPaid", $discount->getNomUrl(0));
5844 $this->tpl[
'description'] =
dol_trunc($line->desc, 60);
5847 $this->tpl[
'description'] =
' ';
5851 $this->tpl[
'vat_rate'] =
vatrate($line->tva_tx,
true);
5852 $this->tpl[
'vat_rate'] .= (((int) $line->info_bits & 1) == 1) ?
'*' :
'';
5853 if (!empty($line->vat_src_code) && !preg_match(
'/\(/', $this->tpl[
'vat_rate'])) {
5854 $this->tpl[
'vat_rate'] .=
' ('.$line->vat_src_code.
')';
5857 $this->tpl[
'price'] =
price($line->subprice);
5858 $this->tpl[
'total_ht'] =
price($line->total_ht);
5859 $this->tpl[
'multicurrency_price'] =
price($line->multicurrency_subprice);
5860 $this->tpl[
'qty'] = (((int) $line->info_bits & 2) != 2) ? $line->qty :
' ';
5862 $this->tpl[
'unit'] = $line->getLabelOfUnit(
'long', $langs);
5863 $this->tpl[
'unit_short'] = $line->getLabelOfUnit(
'short', $langs);
5866 $this->tpl[
'remise_percent'] = (((int) $line->info_bits & 2) != 2) ?
vatrate((
string) $line->remise_percent,
true) :
' ';
5869 $this->tpl[
'strike'] = 0;
5871 $this->tpl[
'strike'] = 1;
5872 } elseif ($line->special_code == SUBTOTALS_SPECIAL_CODE) {
5873 $this->tpl[
'strike'] = 1;
5878 $dirtpls = array_merge($conf->modules_parts[
'tpl'], array($defaulttpldir));
5879 foreach ($dirtpls as $module => $reldir) {
5880 if (!empty($module)) {
5883 $tpl = DOL_DOCUMENT_ROOT.$reldir.
'/originproductline.tpl.php';
5886 if (empty($conf->file->strict_mode)) {
5887 $res = @include $tpl;
5889 $res = include $tpl;
5916 $sql =
"INSERT INTO ".$this->db->prefix().
"element_resources (";
5917 $sql .=
"resource_id";
5918 $sql .=
", resource_type";
5919 $sql .=
", element_id";
5920 $sql .=
", element_type";
5922 $sql .=
", mandatory";
5923 $sql .=
") VALUES (";
5924 $sql .= ((int) $resource_id);
5925 $sql .=
", '".$this->db->escape($resource_type).
"'";
5926 $sql .=
", '".$this->db->escape((
string) $this->
id).
"'";
5927 $sql .=
", '".$this->db->escape($this->element).
"'";
5928 $sql .=
", '".$this->db->escape((
string) $busy).
"'";
5929 $sql .=
", '".$this->db->escape((
string) $mandatory).
"'";
5932 dol_syslog(get_class($this).
"::add_element_resource", LOG_DEBUG);
5933 if ($this->db->query($sql)) {
5935 $result = $this->call_trigger(strtoupper($this->TRIGGER_PREFIX).
'_ADD_RESOURCE', $user);
5937 $this->db->rollback();
5941 $this->db->commit();
5944 $this->error = $this->db->lasterror();
5945 $this->db->rollback();
5966 $sql =
"DELETE FROM ".$this->db->prefix().
"element_resources";
5967 $sql .=
" WHERE rowid = ".((int) $rowid);
5969 dol_syslog(get_class($this).
"::delete_resource", LOG_DEBUG);
5971 $resql = $this->db->query($sql);
5973 $this->error = $this->db->lasterror();
5974 $this->db->rollback();
5978 $result = $this->call_trigger(strtoupper($this->TRIGGER_PREFIX).
'_DELETE_RESOURCE', $user);
5980 $this->db->rollback();
5984 $this->db->commit();
5998 if (isset($this->lines) && is_array($this->lines)) {
5999 $nboflines = count($this->lines);
6000 for ($i = 0; $i < $nboflines; $i++) {
6001 if (is_object($this->lines[$i])) {
6002 $this->lines[$i] = clone $this->lines[$i];
6021 protected function commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams =
null)
6023 global $conf, $langs, $hookmanager, $action;
6025 $srctemplatepath =
'';
6027 $parameters = array(
'modelspath' => $modelspath,
'modele' => $modele,
'outputlangs' => $outputlangs,
'hidedetails' => $hidedetails,
'hidedesc' => $hidedesc,
'hideref' => $hideref,
'moreparams' => $moreparams);
6028 $reshook = $hookmanager->executeHooks(
'commonGenerateDocument', $parameters, $this, $action);
6030 if (!empty($reshook)) {
6034 dol_syslog(
"commonGenerateDocument modele=".$modele.
" outputlangs->defaultlang=".(is_object($outputlangs) ? $outputlangs->defaultlang :
'null'));
6036 if (empty($modele)) {
6037 $this->error =
'BadValueForParameterModele';
6042 $err = error_reporting();
6044 @set_time_limit(120);
6045 error_reporting($err);
6048 $tmp = explode(
':', $modele, 2);
6049 $saved_model = $modele;
6050 if (!empty($tmp[1])) {
6052 $srctemplatepath = $tmp[1];
6059 $dirmodels = array(
'/');
6060 if (is_array($conf->modules_parts[
'models'])) {
6061 $dirmodels = array_merge($dirmodels, $conf->modules_parts[
'models']);
6063 foreach ($dirmodels as $reldir) {
6064 foreach (array(
'doc',
'pdf') as $prefix) {
6065 if (in_array(get_class($this), array(
'Adherent'))) {
6067 $file = $prefix.
"_".$modele.
".class.php";
6070 $file = $prefix.
"_".$modele.
".modules.php";
6077 if (file_exists($file)) {
6079 $classname = $prefix.
'_'.$modele;
6088 if ($filefound ===
'' || $classname ===
'') {
6089 $this->error = $langs->trans(
"Error").
' Failed to load doc generator with modelpaths='.$modelspath.
' - modele='.$modele;
6090 $this->errors[] = $this->error;
6101 require_once $filefound;
6103 $obj =
new $classname($this->db);
6115 '@phan-var-force ModelePDFMember $obj';
6119 if ($obj->type ==
'odt' && empty($srctemplatepath)) {
6120 $varfortemplatedir = $obj->scandir;
6124 $listoffiles = array();
6127 $listofdir = explode(
',', $dirtoscan);
6128 foreach ($listofdir as $key => $tmpdir) {
6129 $tmpdir = trim($tmpdir);
6130 $tmpdir = preg_replace(
'/DOL_DATA_ROOT/', DOL_DATA_ROOT, $tmpdir);
6132 unset($listofdir[$key]);
6135 if (is_dir($tmpdir)) {
6136 $tmpfiles =
dol_dir_list($tmpdir,
'files', 0,
'\.od(s|t)$',
'',
'name', SORT_ASC, 0);
6137 if (count($tmpfiles)) {
6138 $listoffiles = array_merge($listoffiles, $tmpfiles);
6143 if (count($listoffiles)) {
6144 foreach ($listoffiles as $record) {
6145 $srctemplatepath = $record[
'fullname'];
6151 if (empty($srctemplatepath)) {
6152 $this->error =
'ErrorGenerationAskedForOdtTemplateWithSrcFileNotDefined';
6157 if ($obj->type ==
'odt' && !empty($srctemplatepath)) {
6159 dol_syslog(
"Failed to locate template file ".$srctemplatepath, LOG_WARNING);
6160 $this->error =
'ErrorGenerationAskedForOdtTemplateWithSrcFileNotFound';
6167 $sav_charset_output = empty($outputlangs->charset_output) ?
'' : $outputlangs->charset_output;
6170 $this->model_pdf = $saved_model;
6174 $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath,
'member', 1,
'tmp_cards');
6176 $resultwritefile = -1;
6177 dol_syslog(
"Error generating document - Provided ".get_class($this).
" to ".get_class($obj).
"::write_file()", LOG_ERR);
6181 if ($this instanceof
Don) {
6182 $resultwritefile = $obj->write_file($this, $outputlangs );
6184 $resultwritefile = -1;
6185 dol_syslog(
"Error generating document - Provided ".get_class($this).
" to Don::write_file()", LOG_ERR);
6189 '@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';
6190 $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, $hidedetails, $hidedesc, $hideref, $moreparams);
6195 if ($resultwritefile > 0) {
6196 $outputlangs->charset_output = $sav_charset_output;
6199 require_once DOL_DOCUMENT_ROOT.
'/core/lib/files.lib.php';
6203 if (!empty($obj->result[
'fullpath'])) {
6204 $destfull = $obj->result[
'fullpath'];
6207 $update_main_doc_field = 0;
6208 if (!empty($obj->update_main_doc_field)) {
6209 $update_main_doc_field = 1;
6215 $this->indexFile($destfull, $update_main_doc_field);
6218 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);
6224 $this->warnings = $obj->warnings;
6228 $outputlangs->charset_output = $sav_charset_output;
6229 $this->error = $obj->error;
6230 $this->errors = $obj->errors;
6231 $this->warnings = $obj->warnings;
6232 dol_syslog(
"Error generating document for ".__CLASS__.
". Error: ".$obj->error, LOG_ERR);
6246 public function indexFile($destfull, $update_main_doc_field)
6248 global $conf, $user;
6250 $upload_dir = dirname($destfull);
6251 $destfile = basename($destfull);
6252 $rel_dir = preg_replace(
'/^'.preg_quote(DOL_DATA_ROOT,
'/').
'/',
'', $upload_dir);
6254 if (!preg_match(
'/[\\/]temp[\\/]|[\\/]thumbs|\.meta$/', $rel_dir)) {
6255 $filename = basename($destfile);
6256 $rel_dir = preg_replace(
'/[\\/]$/',
'', $rel_dir);
6257 $rel_dir = preg_replace(
'/^[\\/]/',
'', $rel_dir);
6259 include_once DOL_DOCUMENT_ROOT.
'/ecm/class/ecmfiles.class.php';
6260 $ecmfile =
new EcmFiles($this->db);
6261 $result = $ecmfile->fetch(0,
'', ($rel_dir ? $rel_dir.
'/' :
'').$filename);
6264 $setsharekey =
false;
6266 !empty($this->TRIGGER_PREFIX)
6269 $setsharekey =
true;
6272 if ($this->element ==
'propal' || $this->element ==
'proposal') {
6274 $setsharekey =
true;
6277 $setsharekey =
true;
6280 if ($this->element ==
'facture' &&
getDolGlobalInt(
"INVOICE_ALLOW_EXTERNAL_DOWNLOAD")) {
6281 $setsharekey =
true;
6283 if ($this->element ==
'bank_account' &&
getDolGlobalInt(
"BANK_ACCOUNT_ALLOW_EXTERNAL_DOWNLOAD")) {
6284 $setsharekey =
true;
6286 if ($this->element ==
'contrat' &&
getDolGlobalInt(
"CONTRACT_ALLOW_EXTERNAL_DOWNLOAD")) {
6287 $setsharekey =
true;
6289 if ($this->element ==
'supplier_proposal' &&
getDolGlobalInt(
"SUPPLIER_PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD")) {
6290 $setsharekey =
true;
6292 if ($this->element ==
'societe_rib' &&
getDolGlobalInt(
"SOCIETE_RIB_ALLOW_ONLINESIGN")) {
6293 $setsharekey =
true;
6297 if (empty($ecmfile->share)) {
6298 require_once DOL_DOCUMENT_ROOT.
'/core/lib/security2.lib.php';
6305 $ecmfile->fullpath_orig =
'';
6306 $ecmfile->gen_or_uploaded =
'generated';
6307 $ecmfile->description =
'';
6308 $ecmfile->keywords =
'';
6309 $ecmfile->src_object_type = $this->table_element;
6311 $result = $ecmfile->update($user);
6317 $ecmfile->entity = $conf->entity;
6318 $ecmfile->filepath = $rel_dir;
6319 $ecmfile->filename = $filename;
6321 $ecmfile->fullpath_orig =
'';
6322 $ecmfile->gen_or_uploaded =
'generated';
6323 $ecmfile->description =
'';
6324 $ecmfile->keywords =
'';
6325 $ecmfile->src_object_type = $this->table_element;
6328 $result = $ecmfile->create($user);
6340 if ($update_main_doc_field && !empty($this->table_element)) {
6341 $sql =
"UPDATE ".$this->db->prefix().$this->table_element.
" SET last_main_doc = '".$this->db->escape($ecmfile->filepath.
"/".$ecmfile->filename).
"'";
6342 $sql .=
" WHERE rowid = ".((int) $this->
id);
6344 $resql = $this->db->query($sql);
6349 $this->last_main_doc = $ecmfile->filepath.
'/'.$ecmfile->filename;
6369 if (file_exists($file_osencoded)) {
6370 require_once DOL_DOCUMENT_ROOT.
'/core/lib/images.lib.php';
6373 $maxwidthsmall = $tmparraysize[
'maxwidthsmall'];
6374 $maxheightsmall = $tmparraysize[
'maxheightsmall'];
6375 $maxwidthmini = $tmparraysize[
'maxwidthmini'];
6376 $maxheightmini = $tmparraysize[
'maxheightmini'];
6381 vignette($file_osencoded, $maxwidthsmall, $maxheightsmall,
'_small', $quality);
6385 vignette($file_osencoded, $maxwidthmini, $maxheightmini,
'_mini', $quality);
6432 if (GETPOSTISSET($fieldname)) {
6433 return GETPOST($fieldname, $type, 3);
6436 if (isset($alternatevalue)) {
6437 return $alternatevalue;
6440 $newelement = $this->element;
6441 if ($newelement ==
'facture') {
6442 $newelement =
'invoice';
6444 if ($newelement ==
'commande') {
6445 $newelement =
'order';
6447 if (empty($newelement)) {
6448 dol_syslog(
"Ask a default value using common method getDefaultCreateValueForField on an object with no property ->element defined. Return empty string.", LOG_WARNING);
6452 $keyforfieldname = strtoupper($newelement.
'_DEFAULT_'.$fieldname);
6479 if (!$this->element) {
6482 if (!($this->
id > 0)) {
6485 if (is_array($this->array_languages)) {
6489 $this->array_languages = array();
6491 $element = $this->element;
6492 if ($element ==
'categorie') {
6493 $element =
'categories';
6497 $sql =
"SELECT rowid, property, lang , value";
6498 $sql .=
" FROM ".$this->db->prefix().
"object_lang";
6499 $sql .=
" WHERE type_object = '".$this->db->escape($element).
"'";
6500 $sql .=
" AND fk_object = ".((int) $this->
id);
6502 $resql = $this->db->query($sql);
6504 $numrows = $this->db->num_rows($resql);
6507 while ($i < $numrows) {
6508 $obj = $this->db->fetch_object($resql);
6509 $key = $obj->property;
6510 $value = $obj->value;
6511 $codelang = $obj->lang;
6512 $type = $this->fields[$key][
'type'];
6515 if (preg_match(
'/date/', $type)) {
6516 $this->array_languages[$key][$codelang] = $this->db->jdate($value);
6518 $this->array_languages[$key][$codelang] = $value;
6525 $this->db->free($resql);
6548 foreach ($_POST as $postfieldkey => $postfieldvalue) {
6549 $tmparray = explode(
'-', $postfieldkey);
6550 if ($tmparray[0] !=
'field') {
6554 $element = $tmparray[1];
6555 $key = $tmparray[2];
6556 $codelang = $tmparray[3];
6559 if (!empty($onlykey) && $key != $onlykey) {
6562 if ($element != $this->element) {
6566 $key_type = $this->fields[$key][
'type'];
6569 if (isset($this->fields[$key][
'enabled'])) {
6570 $enabled = (int)
dol_eval((
string) $this->fields[$key][
'enabled'], 1, 1,
'1');
6577 if (empty($enabled)) {
6582 if (in_array($key_type, array(
'date'))) {
6586 } elseif (in_array($key_type, array(
'datetime'))) {
6590 } elseif (in_array($key_type, array(
'checkbox',
'chkbxlst'))) {
6591 $value_arr =
GETPOST($postfieldkey,
'array');
6592 if (!empty($value_arr)) {
6593 $value_key = implode(
',', $value_arr);
6597 } elseif (in_array($key_type, array(
'price',
'double'))) {
6598 $value_arr =
GETPOST($postfieldkey,
'alpha');
6601 $value_key =
GETPOST($postfieldkey);
6602 if (in_array($key_type, array(
'link')) && $value_key ==
'-1') {
6607 $this->array_languages[$key][$codelang] = $value_key;
6632 $savDisableCompute = $conf->disable_compute;
6633 $conf->disable_compute = 1;
6635 $ret = $this->fetch(
$id);
6637 $conf->disable_compute = $savDisableCompute;
6655 global $conf, $extrafields;
6657 if (empty($rowid)) {
6660 if (empty($rowid) && isset($this->rowid)) {
6661 $rowid = $this->rowid;
6665 if (!$this->table_element) {
6669 $this->array_options = array();
6671 if (!is_array($optionsArray)) {
6673 if (!isset($extrafields) || !is_object($extrafields)) {
6674 require_once DOL_DOCUMENT_ROOT.
'/core/class/extrafields.class.php';
6679 if (empty($extrafields->attributes[$this->table_element][
'loaded'])) {
6680 $extrafields->fetch_name_optionals_label($this->table_element);
6682 $optionsArray = (!empty($extrafields->attributes[$this->table_element][
'label']) ? $extrafields->attributes[$this->table_element][
'label'] :
null);
6684 global $extrafields;
6685 dol_syslog(
"Warning: fetch_optionals was called with param optionsArray defined when you should pass null now", LOG_WARNING);
6688 $table_element = $this->table_element;
6689 if ($table_element ==
'categorie') {
6690 $table_element =
'categories';
6694 if (is_array($optionsArray) && count($optionsArray) > 0) {
6695 $sql =
"SELECT rowid";
6696 foreach ($optionsArray as $name => $label) {
6697 if (empty($extrafields->attributes[$this->table_element][
'type'][$name]) || (!in_array($extrafields->attributes[$this->table_element][
'type'][$name], [
'separate',
'point',
'multipts',
'linestrg',
'polygon']))) {
6698 $sql .=
", ".$this->db->sanitize($name);
6701 if (!empty($extrafields->attributes[$this->table_element][
'type'][$name]) && in_array($extrafields->attributes[$this->table_element][
'type'][$name], array(
'point',
'multipts',
'linestrg',
'polygon'))) {
6703 $sql .=
", ST_AsWKT(".$name.
") as ".$this->db->sanitize($name);
6706 $sql .=
" FROM ".$this->db->prefix().$table_element.
"_extrafields";
6707 $sql .=
" WHERE fk_object = ".((int) $rowid);
6710 $resql = $this->db->query($sql);
6712 $numrows = $this->db->num_rows($resql);
6714 $tab = $this->db->fetch_array($resql);
6716 foreach ($tab as $key => $value) {
6718 if ($key !=
'rowid' && $key !=
'tms' && $key !=
'fk_member' && !is_int($key)) {
6720 if (!empty($extrafields->attributes[$this->table_element]) && in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'date',
'datetime'))) {
6722 $this->array_options[
"options_".$key] = $this->db->jdate($value);
6724 $this->array_options[
"options_".$key] = $value;
6729 if (!empty($extrafields->attributes[$this->table_element][
'type'][$key]) && $extrafields->attributes[$this->table_element][
'type'][$key] ==
'password') {
6730 if (!empty($value) && preg_match(
'/^dolcrypt:/', $value)) {
6731 $this->array_options[
"options_".$key] =
dolDecrypt($value);
6740 if (is_array($extrafields->attributes[$this->table_element][
'label'])) {
6741 foreach ($extrafields->attributes[$this->table_element][
'label'] as $key => $val) {
6742 $this->array_options[
'options_' . $key] =
null;
6749 if (is_array($extrafields->attributes[$this->table_element][
'label'])) {
6750 foreach ($extrafields->attributes[$this->table_element][
'label'] as $key => $val) {
6751 if (!empty($extrafields->attributes[$this->table_element]) && !empty($extrafields->attributes[$this->table_element][
'computed'][$key])) {
6753 if (empty($conf->disable_compute)) {
6754 global $objectoffield;
6755 $objectoffield = $this;
6756 $this->array_options[
'options_' . $key] =
dol_eval((
string) $extrafields->attributes[$this->table_element][
'computed'][$key], 1, 0,
'2');
6762 $this->db->free($resql);
6770 $this->errors[] = $this->db->lasterror;
6791 $table_element = $this->table_element;
6792 if ($table_element ==
'categorie') {
6793 $table_element =
'categories';
6796 dol_syslog(get_class($this).
"::deleteExtraFields delete", LOG_DEBUG);
6798 $sql_del =
"DELETE FROM ".$this->db->prefix().$table_element.
"_extrafields WHERE fk_object = ".((int) $this->
id);
6800 $resql = $this->db->query($sql_del);
6802 $this->error = $this->db->lasterror();
6803 $this->db->rollback();
6806 $this->db->commit();
6823 global $langs, $user;
6825 if (
getDolGlobalString(
'MAIN_EXTRAFIELDS_DISABLED') || empty($this->array_options)) {
6829 if (empty($userused)) {
6836 $langs->load(
'admin');
6837 require_once DOL_DOCUMENT_ROOT.
'/core/class/extrafields.class.php';
6839 $target_extrafields = $extrafields->fetch_name_optionals_label($this->table_element);
6842 $new_array_options = array();
6843 foreach ($this->array_options as $key => $value) {
6844 if (in_array(substr($key, 8), array_keys($target_extrafields))) {
6845 $new_array_options[$key] = $value;
6846 } elseif (in_array($key, array_keys($target_extrafields))) {
6847 $new_array_options[
'options_'.$key] = $value;
6851 foreach ($new_array_options as $key => $value) {
6852 $attributeKey = substr($key, 8);
6853 $attributeType = $extrafields->attributes[$this->table_element][
'type'][$attributeKey];
6854 $attributeLabel = $langs->transnoentities($extrafields->attributes[$this->table_element][
'label'][$attributeKey]);
6855 $attributeParam = $extrafields->attributes[$this->table_element][
'param'][$attributeKey];
6856 $attributeRequired = $extrafields->attributes[$this->table_element][
'required'][$attributeKey];
6857 $attributeUnique = $extrafields->attributes[$this->table_element][
'unique'][$attributeKey];
6858 $attrfieldcomputed = $extrafields->attributes[$this->table_element][
'computed'][$attributeKey];
6859 $attributeEmptyOnClone = $extrafields->attributes[$this->table_element][
'emptyonclone'][$attributeKey];
6864 if (!empty($this->context[
'createfromclone']) && $this->context[
'createfromclone'] ==
'createfromclone' && (!empty($attributeUnique) || !empty($attributeEmptyOnClone))) {
6865 $new_array_options[$key] =
null;
6871 if (!empty($this->context[
'createproductcombination']) && $this->context[
'createproductcombination'] ==
'createproductcombination' && !empty($attributeUnique)) {
6872 $new_array_options[$key] =
null;
6877 if ($attributeRequired) {
6878 $v = $this->array_options[$key];
6880 $langs->load(
"errors");
6881 dol_syslog(
"Mandatory field '".$key.
"' is empty during create and set to required into definition of extrafields");
6882 $this->errors[] = $langs->trans(
'ErrorFieldRequired', $attributeLabel);
6887 if (!empty($attrfieldcomputed)) {
6889 $value =
dol_eval((
string) $attrfieldcomputed, 1, 0,
'2');
6890 dol_syslog($langs->trans(
"Extrafieldcomputed").
" on ".$attributeLabel.
"(".$value.
")", LOG_DEBUG);
6891 $new_array_options[$key] = $value;
6893 $new_array_options[$key] =
null;
6898 switch ($attributeType) {
6902 if (!is_numeric($value) && $value !=
'') {
6903 $this->errors[] = $langs->trans(
"ExtraFieldHasWrongValue", $attributeLabel);
6905 } elseif ($value ===
'') {
6906 $new_array_options[$key] =
null;
6910 if ($value ===
'' || $value ===
false || $value ===
null) {
6911 $new_array_options[$key] =
null;
6917 if (!is_numeric($value) && $value !=
'') {
6918 dol_syslog($langs->trans(
"ExtraFieldHasWrongValue").
" for ".$attributeLabel.
"(".$value.
"is not '".$attributeType.
"')", LOG_DEBUG);
6919 $this->errors[] = $langs->trans(
"ExtraFieldHasWrongValue", $attributeLabel);
6921 } elseif ($value ==
'') {
6925 $new_array_options[$key] = $value;
6935 if ($this->array_options[$key] !=
'' && is_array($extrafields->attributes[$this->table_element][
'param'][$attributeKey][
'options'])) {
6937 $tmparrays = array_keys($extrafields->attributes[$this->table_element][
'param'][$attributeKey][
'options']);
6938 $algo = reset($tmparrays);
6943 if (is_object($this->oldcopy)) {
6945 if (isset($this->oldcopy->array_options[$key]) && $this->array_options[$key] == $this->oldcopy->array_options[$key]) {
6947 if ($algo ==
'dolcrypt') {
6948 if (!preg_match(
'/^dolcrypt:/', $this->array_options[$key])) {
6949 $new_array_options[$key] =
dolEncrypt($this->array_options[$key]);
6951 $new_array_options[$key] = $this->array_options[$key];
6954 $new_array_options[$key] = $this->array_options[$key];
6958 if ($algo ==
'dolcrypt') {
6959 if (!preg_match(
'/^dolcrypt:/', $this->array_options[$key])) {
6960 $new_array_options[$key] =
dolEncrypt($this->array_options[$key]);
6962 $new_array_options[$key] = $this->array_options[$key];
6965 $new_array_options[$key] =
dol_hash($this->array_options[$key], $algo);
6971 if ($algo ==
'dolcrypt' && !preg_match(
'/^dolcrypt:/', $this->array_options[$key])) {
6972 $new_array_options[$key] =
dolEncrypt($this->array_options[$key]);
6974 $new_array_options[$key] = $this->array_options[$key];
6979 $new_array_options[$key] = $this->array_options[$key];
6982 $new_array_options[$key] = $this->array_options[$key];
6988 if (!is_numeric($this->array_options[$key]) || $this->array_options[$key] != intval($this->array_options[$key])) {
6989 $this->array_options[$key] = strtotime($this->array_options[$key]);
6991 $new_array_options[$key] = $this->db->idate($this->array_options[$key]);
6995 if (!is_numeric($this->array_options[$key]) || $this->array_options[$key] != intval($this->array_options[$key])) {
6996 $this->array_options[$key] = strtotime($this->array_options[$key]);
6998 $new_array_options[$key] = $this->db->idate($this->array_options[$key],
'gmt');
7001 $param_list = array_keys($attributeParam[
'options']);
7004 $InfoFieldList = explode(
":", $param_list[0]);
7006 if ($InfoFieldList[0] && class_exists($InfoFieldList[0])) {
7007 if ($value ==
'-1') {
7008 $new_array_options[$key] =
'';
7010 $object =
new $InfoFieldList[0]($this->db);
7011 '@phan-var-force CommonObject $object';
7015 $sqlFetchObject =
"SELECT rowid FROM ".$this->db->prefix().$object->table_element;
7016 if (is_numeric($value)) {
7017 $sqlFetchObject .=
" WHERE rowid = " . (int) $value;
7019 $sqlFetchObject .=
" WHERE ref = '" . $this->db->escape($value) .
"'";
7022 $obj = $this->db->getRow($sqlFetchObject);
7024 if ($obj !==
false) {
7025 $objectId = $obj->rowid;
7032 $new_array_options[$key] = $objectId;
7034 $this->error =
"Id/Ref '".$value.
"' for object '".
$object->element.
"' not found";
7039 dol_syslog(
'Error bad setup of extrafield', LOG_WARNING);
7044 if (is_array($this->array_options[$key])) {
7045 $new_array_options[$key] = implode(
',', $this->array_options[$key]);
7047 $new_array_options[$key] = $this->array_options[$key];
7054 $sqlColumnValues = [
'fk_object' => (int) $this->
id];
7056 foreach ($new_array_options as $key => $newValue) {
7057 $attributeKey = substr($key, 8);
7058 $attributeType = $extrafields->attributes[$this->table_element][
'type'][$attributeKey];
7059 if ($attributeType ===
'separate') {
7063 $geoDataType = ExtraFields::$geoDataTypes[$attributeType] ??
null;
7065 if (! $geoDataType) {
7067 if ($newValue !=
'') {
7068 $sqlColumnValues[$attributeKey] =
"'".$this->db->escape($newValue).
"'";
7070 $sqlColumnValues[$attributeKey] =
'null';
7074 if (empty($newValue)) {
7075 $sqlColumnValues[$attributeKey] =
'null';
7078 if (preg_match(
'/error/i', $newValue)) {
7079 dol_syslog(
'Bad syntax string for '.$geoDataType[
'shortname'].
' '.$newValue.
' to generate SQL request', LOG_WARNING);
7080 $sqlColumnValues[$attributeKey] =
'null';
7089 $sqlColumnValues[$key] = $geoDataType[
'ST_Function'].
"('".$this->db->escape($newValue).
"')";
7094 $table_element = $this->table_element;
7095 if ($table_element ==
'categorie') {
7096 $table_element =
'categories';
7098 $extrafieldsTable = $this->db->prefix() . $table_element .
'_extrafields';
7100 dol_syslog(get_class($this).
"::insertExtraFields update or insert record line", LOG_DEBUG);
7102 $linealreadyfound = 0;
7103 $sql =
"SELECT COUNT(rowid) as nb FROM ".$this->db->prefix().$table_element.
"_extrafields WHERE fk_object = ".((int) $this->
id);
7104 $resql = $this->db->query($sql);
7106 $tmpobj = $this->db->fetch_object($resql);
7108 $linealreadyfound = $tmpobj->nb;
7113 if ($linealreadyfound) {
7114 array_shift($sqlColumnValues);
7115 $sqlColumnValueString = implode(
7121 array_map(
function ($key) use ($sqlColumnValues) {
7122 return "{$key} = {$sqlColumnValues[$key]}";
7123 }, array_keys($sqlColumnValues))
7125 $sql =
"UPDATE {$extrafieldsTable} SET {$sqlColumnValueString} WHERE fk_object = ".((int) $this->
id);
7128 $extrafieldsRequiredOnOtherEntities = $extrafields->attributes[$this->table_element][
'mandatoryfieldsofotherentities'] ?? array();
7129 foreach ($extrafieldsRequiredOnOtherEntities as $key => $extrafieldType) {
7130 if (isset($sqlColumnValues[$key])) {
7135 $sqlColumnValues[$key] =
"''";
7136 if (in_array($extrafieldType, array(
'int',
'double',
'price'))) {
7137 $sqlColumnValues[$key] = 0;
7140 $sqlColumns = implode(
',', array_keys($sqlColumnValues));
7141 $sqlValues = implode(
',', array_values($sqlColumnValues));
7142 $sql =
"INSERT INTO {$extrafieldsTable} ({$sqlColumns}) VALUES ({$sqlValues})";
7145 $resql = $this->db->query($sql);
7147 $this->error = $this->db->lasterror();
7152 if (!$error && !empty($this->fields[
'fk_user_modif'])) {
7153 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
7154 $sql .=
" SET fk_user_modif = ".(int) $user->id;
7155 $sql .=
" WHERE ".(empty($this->table_rowid) ?
'rowid' : $this->db->sanitize($this->table_rowid)).
" = ".((
int)
$this->id);
7156 $this->db->query($sql);
7159 if (!$error && $trigger) {
7161 $this->context = array(
'extrafieldaddupdate' => 1);
7162 $result = $this->call_trigger($trigger, $userused);
7170 $this->db->rollback();
7173 $this->db->commit();
7191 global $langs, $user;
7193 if (empty($userused)) {
7203 if (is_array($this->array_languages)) {
7204 $new_array_languages = $this->array_languages;
7206 foreach ($new_array_languages as $key => $value) {
7207 $attributeKey = $key;
7208 $attributeType = $this->fields[$attributeKey][
'type'];
7209 $attributeLabel = $this->fields[$attributeKey][
'label'];
7214 switch ($attributeType) {
7216 if (is_array($value) || (!is_numeric($value) && $value !=
'')) {
7217 $this->errors[] = $langs->trans(
"ExtraLanguageHasWrongValue", $attributeLabel);
7219 } elseif ($value ==
'') {
7220 $new_array_languages[$key] =
null;
7225 if (!is_numeric($value) && $value !=
'') {
7226 dol_syslog($langs->trans(
"ExtraLanguageHasWrongValue").
" on ".$attributeLabel.
"(".$value.
"is not '".$attributeType.
"')", LOG_DEBUG);
7227 $this->errors[] = $langs->trans(
"ExtraLanguageHasWrongValue", $attributeLabel);
7229 } elseif ($value ==
'') {
7230 $new_array_languages[$key] =
null;
7232 $new_array_languages[$key] = $value;
7246 $table_element = $this->table_element;
7247 if ($table_element ==
'categorie') {
7248 $table_element =
'categories';
7251 dol_syslog(get_class($this).
"::insertExtraLanguages delete then insert", LOG_DEBUG);
7253 foreach ($new_array_languages as $key => $langcodearray) {
7254 foreach ($langcodearray as $langcode => $value) {
7255 $sql_del =
"DELETE FROM ".$this->db->prefix().
"object_lang";
7256 $sql_del .=
" WHERE fk_object = ".((int) $this->
id).
" AND property = '".$this->db->escape($key).
"' AND type_object = '".$this->db->escape($table_element).
"'";
7257 $sql_del .=
" AND lang = '".$this->db->escape($langcode).
"'";
7258 $this->db->query($sql_del);
7260 if ($value !==
'') {
7261 $sql =
"INSERT INTO ".$this->db->prefix().
"object_lang (fk_object, property, type_object, lang, value";
7262 $sql .=
") VALUES (".$this->id.
", '".$this->db->escape($key).
"', '".$this->db->escape($table_element).
"', '".$this->db->escape($langcode).
"', '".$this->db->escape($value).
"'";
7265 $resql = $this->db->query($sql);
7267 $this->error = $this->db->lasterror();
7275 if (!$error && $trigger) {
7277 $this->context = array(
'extralanguagesaddupdate' => 1);
7278 $result = $this->call_trigger($trigger, $userused);
7286 $this->db->rollback();
7289 $this->db->commit();
7309 global $langs, $user, $hookmanager;
7315 if (empty($userused)) {
7321 if (!empty($this->array_options) && isset($this->array_options[
"options_".$key])) {
7323 $langs->load(
'admin');
7324 require_once DOL_DOCUMENT_ROOT.
'/core/class/extrafields.class.php';
7326 $extrafields->fetch_name_optionals_label($this->table_element);
7328 $value = $this->array_options[
"options_".$key];
7330 $attributeKey = $key;
7331 $attributeType = $extrafields->attributes[$this->table_element][
'type'][$key];
7332 $attributeLabel = $extrafields->attributes[$this->table_element][
'label'][$key];
7333 $attributeParam = $extrafields->attributes[$this->table_element][
'param'][$key];
7334 $attributeRequired = $extrafields->attributes[$this->table_element][
'required'][$key];
7335 $attributeUnique = $extrafields->attributes[$this->table_element][
'unique'][$attributeKey];
7336 $attrfieldcomputed = $extrafields->attributes[$this->table_element][
'computed'][$key];
7339 if ($attributeRequired) {
7340 $mandatorypb =
false;
7341 if ($attributeType ==
'link' && $this->array_options[
"options_".$key] ==
'-1') {
7342 $mandatorypb =
true;
7344 if ($this->array_options[
"options_".$key] ===
'') {
7345 $mandatorypb =
true;
7348 $langs->load(
"errors");
7349 dol_syslog(
"Mandatory field 'options_".$key.
"' is empty during update and set to required into definition of extrafields");
7350 $this->errors[] = $langs->trans(
'ErrorFieldRequired', $attributeLabel);
7356 $new_array_options = $this->array_options;
7360 if (!empty($attrfieldcomputed)) {
7362 $value =
dol_eval((
string) $attrfieldcomputed, 1, 0,
'2');
7363 dol_syslog($langs->trans(
"Extrafieldcomputed").
" on ".$attributeLabel.
"(".$value.
")", LOG_DEBUG);
7365 $new_array_options[
"options_".$key] = $value;
7367 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7369 $new_array_options[
"options_".$key] =
null;
7371 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7375 switch ($attributeType) {
7377 if (!is_numeric($value) && $value !=
'') {
7378 $this->errors[] = $langs->trans(
"ExtraFieldHasWrongValue", $attributeLabel);
7380 } elseif ($value ===
'') {
7381 $new_array_options[
"options_".$key] =
null;
7383 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7389 if (!is_numeric($value) && $value !=
'') {
7390 dol_syslog($langs->trans(
"ExtraFieldHasWrongValue").
" on ".$attributeLabel.
"(".$value.
"is not '".$attributeType.
"')", LOG_DEBUG);
7391 $this->errors[] = $langs->trans(
"ExtraFieldHasWrongValue", $attributeLabel);
7393 } elseif ($value ===
'') {
7397 $new_array_options[
"options_".$key] = $value;
7399 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7411 if ($this->array_options[
"options_".$key] !=
'' && is_array($extrafields->attributes[$this->table_element][
'param'][$attributeKey][
'options'])) {
7413 $tmparrays = array_keys($extrafields->attributes[$this->table_element][
'param'][$attributeKey][
'options']);
7414 $algo = reset($tmparrays);
7420 if (is_object($this->oldcopy)) {
7422 if (isset($this->oldcopy->array_options[
"options_".$key]) && $this->array_options[
"options_".$key] == $this->oldcopy->array_options[
"options_".$key]) {
7423 if ($algo ==
'dolcrypt') {
7424 if (!preg_match(
'/^dolcrypt:/', $this->array_options[
"options_".$key])) {
7425 $new_array_options[
"options_".$key] =
dolEncrypt($this->array_options[
"options_".$key]);
7427 $new_array_options[
"options_".$key] = $this->array_options[
"options_".$key];
7430 $new_array_options[
"options_".$key] = $this->array_options[
"options_".$key];
7433 if ($algo ==
'dolcrypt') {
7434 if (!preg_match(
'/^dolcrypt:/', $this->array_options[
"options_".$key])) {
7435 $new_array_options[
"options_".$key] =
dolEncrypt($this->array_options[
"options_".$key]);
7437 $new_array_options[
"options_".$key] = $this->array_options[
"options_".$key];
7440 $new_array_options[
"options_".$key] =
dol_hash($this->array_options[
"options_".$key], $algo);
7444 if ($algo ==
'dolcrypt' && !preg_match(
'/^dolcrypt:/', $this->array_options[
"options_".$key])) {
7445 $new_array_options[
"options_".$key] =
dolEncrypt($this->array_options[
"options_".$key]);
7447 $new_array_options[
"options_".$key] = $this->array_options[
"options_".$key];
7452 $new_array_options[
"options_".$key] = $this->array_options[
"options_".$key];
7455 $new_array_options[
"options_".$key] = $this->array_options[
"options_".$key];
7458 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7462 if (empty($this->array_options[
"options_".$key])) {
7463 $new_array_options[
"options_".$key] =
null;
7465 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7467 $new_array_options[
"options_".$key] = $this->db->idate($this->array_options[
"options_".$key]);
7471 if (empty($this->array_options[
"options_".$key])) {
7472 $new_array_options[
"options_".$key] =
null;
7474 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7476 $new_array_options[
"options_".$key] = $this->db->idate($this->array_options[
"options_".$key],
'gmt');
7480 if (empty($this->array_options[
"options_".$key])) {
7481 $new_array_options[
"options_".$key] =
null;
7483 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7487 if ($this->array_options[
"options_".$key] ===
'') {
7488 $new_array_options[
"options_".$key] =
null;
7490 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7524 $new_array_options = array();
7525 if (is_array($this->array_options[
"options_".$key])) {
7526 $new_array_options[
"options_".$key] = implode(
',', $this->array_options[
"options_".$key]);
7528 $new_array_options[
"options_".$key] = $this->array_options[
"options_".$key];
7531 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7537 $linealreadyfound = 0;
7540 $table_element = $this->table_element;
7541 if ($table_element ==
'categorie') {
7542 $table_element =
'categories';
7545 $sql =
"SELECT COUNT(rowid) as nb FROM ".$this->db->prefix().$table_element.
"_extrafields WHERE fk_object = ".((int) $this->
id);
7546 $resql = $this->db->query($sql);
7548 $tmpobj = $this->db->fetch_object($resql);
7550 $linealreadyfound = $tmpobj->nb;
7555 if ($linealreadyfound) {
7556 if ($this->array_options[
"options_".$key] ===
null) {
7557 $sql =
"UPDATE ".$this->db->prefix().$table_element.
"_extrafields SET ".$key.
" = null";
7560 $sql =
"UPDATE ".$this->db->prefix().$table_element.
"_extrafields SET ".$key.
" = '".$this->db->escape($new_array_options[
"options_".$key]).
"'";
7562 $sql .=
" WHERE fk_object = ".((int) $this->
id);
7564 $resql = $this->db->query($sql);
7567 $this->error = $this->db->lasterror();
7570 $result = $this->insertExtraFields(
'', $user);
7577 if (!$error && !empty($this->fields[
'fk_user_modif'])) {
7578 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
7579 $sql .=
" SET fk_user_modif = ".(int) $user->id;
7580 $sql .=
" WHERE ".(empty($this->table_rowid) ?
'rowid' : $this->db->sanitize($this->table_rowid)).
" = ".((
int)
$this->id);
7581 $this->db->query($sql);
7585 $parameters = array(
'key' => $key);
7587 $reshook = $hookmanager->executeHooks(
'updateExtraFieldBeforeCommit', $parameters, $this, $action);
7593 if (!$error && $trigger) {
7595 $this->context = array(
'extrafieldupdate' => 1);
7596 $result = $this->call_trigger($trigger, $userused);
7604 dol_syslog(__METHOD__.$this->error, LOG_ERR);
7605 $this->db->rollback();
7608 $this->db->commit();
7624 return $this->array_options[
'options_'.$key] ??
null;
7636 $this->array_options[
'options_'.$key] = $value;
7653 if (empty($userused)) {
7681 public function showInputField($val, $key, $value, $moreparam =
'', $keysuffix =
'', $keyprefix =
'', $morecss = 0, $nonewbutton = 0)
7683 global $conf, $langs, $form;
7688 if (!is_object($form)) {
7689 require_once DOL_DOCUMENT_ROOT.
'/core/class/html.form.class.php';
7690 $form =
new Form($this->db);
7693 if (!empty($this->fields)) {
7694 $val = $this->fields[$key];
7698 $fieldValidationErrorMsg =
'';
7699 $validationClass =
'';
7700 $fieldValidationErrorMsg = $this->getFieldError($key);
7701 if (!empty($fieldValidationErrorMsg)) {
7702 $validationClass =
' --error';
7704 $validationClass =
' --success';
7712 $param[
'options'] = array();
7715 $size = !empty($this->fields[$key][
'size']) ? $this->fields[$key][
'size'] : 0;
7717 if (preg_match(
'/^(integer|link):(.*):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
7718 $param[
'options'] = array($reg[2].
':'.$reg[3].
':'.$reg[4].
':'.$reg[5] =>
'N');
7720 } elseif (preg_match(
'/^(integer|link):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
7721 $param[
'options'] = array($reg[2].
':'.$reg[3].
':'.$reg[4] =>
'N');
7723 } elseif (preg_match(
'/^(integer|link):(.*):(.*)/i', $val[
'type'], $reg)) {
7724 $param[
'options'] = array($reg[2].
':'.$reg[3] =>
'N');
7726 } elseif (preg_match(
'/^(sellist):(.*):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
7727 $param[
'options'] = array($reg[2].
':'.$reg[3].
':'.$reg[4].
':'.$reg[5] =>
'N');
7729 } elseif (preg_match(
'/^(sellist):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
7730 $param[
'options'] = array($reg[2].
':'.$reg[3].
':'.$reg[4] =>
'N');
7732 } elseif (preg_match(
'/^(sellist):(.*):(.*)/i', $val[
'type'], $reg)) {
7733 $param[
'options'] = array($reg[2].
':'.$reg[3] =>
'N');
7735 } elseif (preg_match(
'/^chkbxlst:(.*)/i', $val[
'type'], $reg)) {
7736 $param[
'options'] = array($reg[1] =>
'N');
7738 } elseif (preg_match(
'/varchar\((\d+)\)/', $val[
'type'], $reg)) {
7739 $param[
'options'] = array();
7742 } elseif (preg_match(
'/varchar/', $val[
'type'])) {
7743 $param[
'options'] = array();
7745 } elseif (preg_match(
'/stars\((\d+)\)/', $val[
'type'], $reg)) {
7746 $param[
'options'] = array();
7750 $param[
'options'] = array();
7751 $type = $this->fields[$key][
'type'];
7756 if (!empty($this->fields[$key][
'arrayofkeyval']) && is_array($this->fields[$key][
'arrayofkeyval'])) {
7757 $param[
'options'] = $this->fields[$key][
'arrayofkeyval'];
7759 if (empty($this->fields[$key][
'multiinput'])) {
7760 $type = (($this->fields[$key][
'type'] ==
'checkbox') ? $this->fields[$key][
'type'] :
'select');
7764 $label = $this->fields[$key][
'label'];
7767 $default = (!empty($this->fields[$key][
'default']) ? $this->fields[$key][
'default'] :
'');
7769 $computed = (!empty($this->fields[$key][
'computed']) ? $this->fields[$key][
'computed'] :
'');
7771 $unique = (!empty($this->fields[$key][
'unique']) ? $this->fields[$key][
'unique'] : 0);
7773 $required = (!empty($this->fields[$key][
'required']) ? $this->fields[$key][
'required'] : 0);
7775 $autofocusoncreate = (!empty($this->fields[$key][
'autofocusoncreate']) ? $this->fields[$key][
'autofocusoncreate'] : 0);
7777 $placeholder = (!empty($this->fields[$key][
'placeholder']) ? $this->fields[$key][
'placeholder'] : 0);
7780 $langfile = (!empty($this->fields[$key][
'langfile']) ? $this->fields[$key][
'langfile'] :
'');
7782 $list = (!empty($this->fields[$key][
'list']) ? $this->fields[$key][
'list'] : 0);
7783 $hidden = (in_array(abs($this->fields[$key][
'visible']), array(0, 2)) ? 1 : 0);
7788 if (!preg_match(
'/^search_/', $keyprefix)) {
7789 return '<span class="opacitymedium">'.$langs->trans(
"AutomaticallyCalculated").
'</span>';
7796 if (empty($morecss) && !empty($val[
'css'])) {
7797 $morecss = $val[
'css'];
7798 } elseif (empty($morecss)) {
7799 if ($type ==
'date') {
7800 $morecss =
'minwidth100imp';
7801 } elseif ($type ==
'datetime' || $type ==
'link') {
7802 $morecss =
'minwidth200imp';
7803 } elseif (in_array($type, array(
'int',
'integer',
'price')) || preg_match(
'/^double(\([0-9],[0-9]\)){0,1}/', (
string) $type)) {
7804 $morecss =
'maxwidth75';
7805 } elseif ($type ==
'url') {
7806 $morecss =
'minwidth400';
7807 } elseif ($type ==
'boolean') {
7810 if (is_numeric($size) && round((
float) $size) < 12) {
7811 $morecss =
'minwidth100';
7812 } elseif (is_numeric($size) && round((
float) $size) <= 48) {
7813 $morecss =
'minwidth200';
7815 $morecss =
'minwidth400';
7821 if (!empty($validationClass)) {
7822 $morecss .= $validationClass;
7825 if (in_array($type, array(
'date'))) {
7826 $tmp = explode(
',', $size);
7831 if (!$required && $value ==
'') {
7836 $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required,
'', 1, (($keyprefix !=
'search_' && $keyprefix !=
'search_options_') ? 1 : 0), 0, 1);
7837 } elseif (in_array($type, array(
'datetime'))) {
7838 $tmp = explode(
',', $size);
7843 if (!$required && $value ==
'') {
7848 $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required,
'', 1, (($keyprefix !=
'search_' && $keyprefix !=
'search_options_') ? 1 : 0), 0, 1,
'',
'',
'', 1,
'',
'',
'tzuserrel');
7849 } elseif (in_array($type, array(
'duration'))) {
7850 $out = $form->select_duration($keyprefix.$key.$keysuffix, $value, 0,
'text', 0, 1);
7851 } elseif (in_array($type, array(
'int',
'integer'))) {
7852 $tmp = explode(
',', $size);
7854 $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' :
'').
'>';
7855 } elseif (in_array($type, array(
'real'))) {
7856 $out =
'<input type="text" class="flat '.$morecss.
'" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.
dol_escape_htmltag($value).
'"'.($moreparam ? $moreparam :
'').($autofocusoncreate ?
' autofocus' :
'').
'>';
7857 } elseif (preg_match(
'/varchar/', (
string) $type)) {
7858 $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' :
'').
'>';
7859 } elseif (in_array($type, array(
'email',
'mail',
'phone',
'url',
'ip'))) {
7860 $out =
'<input type="text" class="flat '.$morecss.
'" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.
dol_escape_htmltag($value).
'" '.($moreparam ? $moreparam :
'').($autofocusoncreate ?
' autofocus' :
'').
'>';
7861 } elseif (preg_match(
'/^text/', (
string) $type)) {
7862 if (!preg_match(
'/search_/', $keyprefix)) {
7863 if (!empty($param[
'options'])) {
7866 $out .= $form->selectarray($keyprefix.$key.$keysuffix.
"_multiinput", $param[
'options'],
'', 1, 0, 0,
"flat maxwidthonphone".$morecss);
7867 $out .=
'<input id="'.$keyprefix.$key.$keysuffix.
'_multiinputadd" type="button" class="button" value="'.$langs->trans(
"Add").
'">';
7870 function handlemultiinputdisabling(htmlname){
7871 console.log("We handle the disabling of used options for "+htmlname+"_multiinput");
7872 multiinput = $("#"+htmlname+"_multiinput");
7873 multiinput.find("option").each(function(){
7874 tmpval = $("#"+htmlname).val();
7875 tmpvalarray = tmpval.split("\n");
7876 valtotest = $(this).val();
7877 if(tmpvalarray.includes(valtotest)){
7878 $(this).prop("disabled",true);
7880 if($(this).prop("disabled") == true){
7881 console.log(valtotest)
7882 $(this).prop("disabled", false);
7888 $(document).ready(function () {
7889 $("#'.$keyprefix.$key.$keysuffix.
'_multiinputadd").on("click",function() {
7890 tmpval = $("#'.$keyprefix.$key.$keysuffix.
'").val();
7891 tmpvalarray = tmpval.split(",");
7892 valtotest = $("#'.$keyprefix.$key.$keysuffix.
'_multiinput").val();
7893 if(valtotest != -1 && !tmpvalarray.includes(valtotest)){
7894 console.log("We add the selected value to the text area '.$keyprefix.$key.$keysuffix.
'");
7898 tmpval = tmpval + "\n" + valtotest;
7900 $("#'.$keyprefix.$key.$keysuffix.
'").val(tmpval);
7901 handlemultiinputdisabling("'.$keyprefix.$key.$keysuffix.
'");
7902 $("#'.$keyprefix.$key.$keysuffix.
'_multiinput").val(-1);
7904 console.log("We add nothing the text area '.$keyprefix.$key.$keysuffix.
'");
7907 $("#'.$keyprefix.$key.$keysuffix.
'").on("change",function(){
7908 handlemultiinputdisabling("'.$keyprefix.$key.$keysuffix.
'");
7910 handlemultiinputdisabling("'.$keyprefix.$key.$keysuffix.
'");
7912 $out .=
"</script>";
7913 $value = str_replace(
',',
"\n", $value);
7915 require_once DOL_DOCUMENT_ROOT.
'/core/class/doleditor.class.php';
7916 $doleditor =
new DolEditor($keyprefix.$key.$keysuffix, $value,
'', 200,
'dolibarr_notes',
'In',
false,
false,
false, ROWS_5,
'90%');
7917 $out .= (string) $doleditor->Create(1,
'',
true,
'',
'',
'', $morecss);
7919 $out =
'<input type="text" class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.
dol_escape_htmltag($value).
'" '.($moreparam ? $moreparam :
'').
'>';
7921 } elseif (preg_match(
'/^html/', (
string) $type)) {
7922 if (!preg_match(
'/search_/', $keyprefix)) {
7923 require_once DOL_DOCUMENT_ROOT.
'/core/class/doleditor.class.php';
7924 $doleditor =
new DolEditor($keyprefix.$key.$keysuffix, $value,
'', 200,
'dolibarr_notes',
'In',
false,
false,
isModEnabled(
'fckeditor') &&
getDolGlobalInt(
'FCKEDITOR_ENABLE_SOCIETE'), ROWS_5,
'90%');
7925 $out = (string) $doleditor->Create(1,
'',
true,
'',
'', $moreparam, $morecss);
7927 $out =
'<input type="text" class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.
dol_escape_htmltag($value).
'" '.($moreparam ? $moreparam :
'').
'>';
7929 } elseif ($type ==
'boolean') {
7931 if (!empty($value)) {
7932 $checked =
' checked value="1" ';
7934 $checked =
' value="1" ';
7936 $out =
'<input type="checkbox" class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" '.$checked.
' '.($moreparam ? $moreparam :
'').
'>';
7937 } elseif ($type ==
'price') {
7938 if (!empty($value)) {
7939 $value =
price($value);
7941 $out =
'<input type="text" class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.$value.
'" '.($moreparam ? $moreparam :
'').
'> '.$langs->getCurrencySymbol($conf->currency);
7942 } elseif ($type ==
'stars') {
7943 $out =
'<input type="hidden" class="flat '.$morecss.
'" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.
dol_escape_htmltag($value).
'"'.($moreparam ? $moreparam :
'').($autofocusoncreate ?
' autofocus' :
'').
'>';
7944 $out .=
'<div class="star-selection" id="'.$keyprefix.$key.$keysuffix.
'_selection">';
7946 while ($i <= $size) {
7947 $out .=
'<span class="star" data-value="'.$i.
'">'.
img_picto(
'',
'fontawesome_star_fas').
'</span>';
7952 jQuery(function($) { /* commonobject.class.php 1 */
7953 let container = $("#'.$keyprefix.$key.$keysuffix.
'_selection");
7954 let selectedStars = parseInt($("#'.$keyprefix.$key.$keysuffix.
'").val()) || 0;
7955 container.find(".star").each(function() {
7956 $(this).toggleClass("active", $(this).data("value") <= selectedStars);
7958 container.find(".star").on("mouseover", function() {
7959 let selectedStar = $(this).data("value");
7960 container.find(".star").each(function() {
7961 $(this).toggleClass("active", $(this).data("value") <= selectedStar);
7964 container.on("mouseout", function() {
7965 container.find(".star").each(function() {
7966 $(this).toggleClass("active", $(this).data("value") <= selectedStars);
7969 container.find(".star").off("click").on("click", function() {
7970 selectedStars = $(this).data("value");
7971 if (selectedStars === 1 && $("#'.$keyprefix.$key.$keysuffix.
'").val() == 1) {
7974 $("#'.$keyprefix.$key.$keysuffix.
'").val(selectedStars);
7975 container.find(".star").each(function() {
7976 $(this).toggleClass("active", $(this).data("value") <= selectedStars);
7981 } elseif (preg_match(
'/^double(\([0-9],[0-9]\)){0,1}/', (
string) $type)) {
7982 if (!empty($value)) {
7983 $value =
price($value);
7985 $out =
'<input type="text" class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.$value.
'" '.($moreparam ? $moreparam :
'').
'> ';
7986 } elseif ($type ==
'select') {
7988 if (!empty($conf->use_javascript_ajax) && !
getDolGlobalString(
'MAIN_EXTRAFIELDS_DISABLE_SELECT2')) {
7989 include_once DOL_DOCUMENT_ROOT.
'/core/lib/ajax.lib.php';
7990 $out .=
ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
7996 foreach ($param[
'options'] as $keyb => $valb) {
7997 if ((
string) $keyb ==
'') {
8000 if (strpos($valb,
"|") !==
false) {
8001 list($valb, $parent) = explode(
'|', $valb);
8004 $tmpselect .=
'<option value="'.$keyb.
'"';
8005 $tmpselect .= (((string) $value == (
string) $keyb) ?
' selected' :
'');
8006 if (!empty($parent)) {
8009 $tmpselect .= (!empty($parent) ?
' parent="'.$parent.
'"' :
'');
8010 $tmpselect .=
'>'.$langs->trans($valb).
'</option>';
8013 $out .=
'<select class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" '.($moreparam ? $moreparam :
'').
'>';
8014 if ((!isset($this->fields[$key][
'default'])) || empty($this->fields[$key][
'notnull']) || ($this->fields[$key][
'notnull'] != 1) || $nbchoice >= 2) {
8015 $out .=
'<option value="0"> </option>';
8018 $out .=
'</select>';
8019 } elseif ($type ==
'sellist') {
8021 if (!empty($conf->use_javascript_ajax) && !
getDolGlobalString(
'MAIN_EXTRAFIELDS_DISABLE_SELECT2')) {
8022 include_once DOL_DOCUMENT_ROOT.
'/core/lib/ajax.lib.php';
8023 $out .=
ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
8026 $out .=
'<select class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" '.($moreparam ? $moreparam :
'').
'>';
8027 if (is_array($param[
'options'])) {
8028 $tmpparamoptions = array_keys($param[
'options']);
8029 $paramoptions = preg_split(
'/[\r\n]+/', $tmpparamoptions[0]);
8031 $InfoFieldList = explode(
":", $paramoptions[0], 5);
8043 if (! empty($InfoFieldList[4])) {
8045 $parenthesisopen = 0;
8046 while (substr($InfoFieldList[4], $pos, 1) !==
'' && ($parenthesisopen || $pos == 0 || substr($InfoFieldList[4], $pos, 1) !=
':')) {
8047 if (substr($InfoFieldList[4], $pos, 1) ==
'(') {
8050 if (substr($InfoFieldList[4], $pos, 1) ==
')') {
8055 $tmpbefore = substr($InfoFieldList[4], 0, $pos);
8056 $tmpafter = substr($InfoFieldList[4], $pos + 1);
8058 $InfoFieldList[4] = $tmpbefore;
8059 if ($tmpafter !==
'') {
8060 $InfoFieldList = array_merge($InfoFieldList, explode(
':', $tmpafter));
8066 if (preg_match(
'/^\(?([a-z0-9]+)([=<>]+)(\d+)\)?$/i', $InfoFieldList[4], $reg)) {
8067 $InfoFieldList[4] =
'('.$reg[1].
':'.$reg[2].
':'.$reg[3].
')';
8078 $keyList = (empty($InfoFieldList[2]) ?
'rowid' : $InfoFieldList[2].
' as rowid');
8080 if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
8081 if (strpos($InfoFieldList[4],
'extra.') !==
false) {
8082 $keyList =
'main.'.$InfoFieldList[2].
' as rowid';
8084 $keyList = $InfoFieldList[2].
' as rowid';
8087 if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
8088 list($parentName, $parentField) = explode(
'|', $InfoFieldList[3]);
8089 if (!empty($InfoFieldList[4]) && strpos($InfoFieldList[4],
'extra.') !==
false) {
8090 $keyList .=
', main.'.$parentField;
8092 $keyList .=
', '.$parentField;
8096 $filter_categorie =
false;
8097 if (count($InfoFieldList) > 5) {
8098 if ($InfoFieldList[0] ==
'categorie') {
8099 $filter_categorie =
true;
8103 if (!$filter_categorie) {
8104 $fields_label = isset($InfoFieldList[1]) ? explode(
'|', $InfoFieldList[1]) : array();
8105 if (!empty($fields_label)) {
8107 $keyList .= implode(
', ', $fields_label);
8111 $sql =
"SELECT " . $keyList;
8112 $sql .=
" FROM " . $this->db->prefix() . $InfoFieldList[0];
8114 if (!empty($InfoFieldList[4])) {
8116 if (strpos($InfoFieldList[4],
'$SEL$') !==
false) {
8117 $InfoFieldList[4] = str_replace(
'$SEL$',
'SELECT', $InfoFieldList[4]);
8121 if (strpos($InfoFieldList[4],
'$ID$') !==
false && !empty($objectid)) {
8122 $InfoFieldList[4] = str_replace(
'$ID$', (
string) $objectid, $InfoFieldList[4]);
8124 $InfoFieldList[4] = str_replace(
'$ID$',
'0', $InfoFieldList[4]);
8129 if (strpos($InfoFieldList[4],
'extra') !==
false) {
8130 $sql .=
" as main, " . $this->db->sanitize($this->db->prefix() . $InfoFieldList[0]) .
"_extrafields as extra";
8131 $sqlwhere .=
" WHERE extra.fk_object = main." . $this->db->sanitize($InfoFieldList[2]);
8137 $sqlwhere .=
' WHERE 1=1';
8154 if (in_array($InfoFieldList[0], array(
'tablewithentity'))) {
8155 $sqlwhere .=
" AND entity = " . ((int) $conf->entity);
8160 if (isset($InfoFieldList[7]) && preg_match(
'/^[a-z0-9_\-,]+$/i', $InfoFieldList[7])) {
8161 $sql .=
" ORDER BY ".$this->db->escape($InfoFieldList[7]);
8163 $sql .=
" ORDER BY ".$this->db->sanitize(implode(
', ', $fields_label));
8165 $sql .=
' LIMIT ' .
getDolGlobalInt(
'MAIN_EXTRAFIELDS_LIMIT_SELLIST_SQL', 1000);
8168 dol_syslog(get_class($this) .
'::showInputField type=sellist', LOG_DEBUG);
8169 $resql = $this->db->query($sql);
8171 $out .=
'<option value="0"> </option>';
8172 $num = $this->db->num_rows($resql);
8176 $obj = $this->db->fetch_object($resql);
8180 $fields_label = explode(
'|', $InfoFieldList[1]);
8181 if (count($fields_label) > 1) {
8183 foreach ($fields_label as $field_toshow) {
8184 $labeltoshow .= $obj->$field_toshow .
' ';
8187 $labeltoshow = $obj->{$InfoFieldList[1]};
8189 $labeltoshow =
dol_trunc($labeltoshow, 45);
8191 if ($value == $obj->rowid) {
8192 foreach ($fields_label as $field_toshow) {
8193 $translabel = $langs->trans($obj->$field_toshow);
8194 if ($translabel != $obj->$field_toshow) {
8195 $labeltoshow =
dol_trunc($translabel) .
' ';
8197 $labeltoshow =
dol_trunc($obj->$field_toshow) .
' ';
8200 $out .=
'<option value="' . $obj->rowid .
'" selected>' . $labeltoshow .
'</option>';
8203 $translabel = $langs->trans($obj->{$InfoFieldList[1]});
8204 if ($translabel != $obj->{$InfoFieldList[1]}) {
8205 $labeltoshow =
dol_trunc($translabel, 18);
8207 $labeltoshow =
dol_trunc($obj->{$InfoFieldList[1]});
8210 if (empty($labeltoshow)) {
8211 $labeltoshow =
'(not defined)';
8213 if ($value == $obj->rowid) {
8214 $out .=
'<option value="' . $obj->rowid .
'" selected>' . $labeltoshow .
'</option>';
8217 if (!empty($InfoFieldList[3]) && $parentField) {
8218 $parent = $parentName .
':' . $obj->{$parentField};
8222 $out .=
'<option value="' . $obj->rowid .
'"';
8223 $out .= ($value == $obj->rowid ?
' selected' :
'');
8224 $out .= (!empty($parent) ?
' parent="' . $parent .
'"' :
'');
8225 $out .=
'>' . $labeltoshow .
'</option>';
8230 $this->db->free($resql);
8232 print
'Error in request ' . $sql .
' ' . $this->db->lasterror() .
'. Check setup of extra parameters.<br>';
8235 require_once DOL_DOCUMENT_ROOT.
'/categories/class/categorie.class.php';
8236 $categcode = $InfoFieldList[5];
8237 if (is_numeric($categcode)) {
8238 $tmpcategory =
new Categorie($this->db);
8239 $MAP_ID_TO_CODE = array_flip($tmpcategory->MAP_ID);
8240 $categcode = $MAP_ID_TO_CODE[(int) $categcode];
8243 $data = $form->select_all_categories($categcode,
'',
'parent', 64, $InfoFieldList[6], 1, 1);
8244 $out .=
'<option value="0"> </option>';
8245 foreach ($data as $data_key => $data_value) {
8246 $out .=
'<option value="' . $data_key .
'"';
8247 $out .= ($value == $data_key ?
' selected' :
'');
8248 $out .=
'>' . $data_value .
'</option>';
8252 $out .=
'</select>';
8253 } elseif ($type ==
'checkbox') {
8254 $value_arr = explode(
',', $value);
8255 $out = $form->multiselectarray($keyprefix.$key.$keysuffix, (empty($param[
'options']) ?
null : $param[
'options']), $value_arr, 0, 0, $morecss, 0,
'100%');
8256 } elseif ($type ==
'radio') {
8258 foreach ($param[
'options'] as $keyopt => $valopt) {
8259 $out .=
'<input class="flat '.$morecss.
'" type="radio" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" '.($moreparam ? $moreparam :
'');
8260 $out .=
' value="'.$keyopt.
'"';
8261 $out .=
' id="'.$keyprefix.$key.$keysuffix.
'_'.$keyopt.
'"';
8262 $out .= ($value == $keyopt ?
'checked' :
'');
8263 $out .=
'/><label for="'.$keyprefix.$key.$keysuffix.
'_'.$keyopt.
'">'.$valopt.
'</label><br>';
8265 } elseif ($type ==
'chkbxlst') {
8266 if (is_array($value)) {
8267 $value_arr = $value;
8269 $value_arr = explode(
',', $value);
8272 if (is_array($param[
'options'])) {
8273 $tmpparamoptions = array_keys($param[
'options']);
8274 $paramoptions = preg_split(
'/[\r\n]+/', $tmpparamoptions[0]);
8276 $InfoFieldList = explode(
":", $paramoptions[0], 5);
8288 if (! empty($InfoFieldList[4])) {
8290 $parenthesisopen = 0;
8291 while (substr($InfoFieldList[4], $pos, 1) !==
'' && ($parenthesisopen || $pos == 0 || substr($InfoFieldList[4], $pos, 1) !=
':')) {
8292 if (substr($InfoFieldList[4], $pos, 1) ==
'(') {
8295 if (substr($InfoFieldList[4], $pos, 1) ==
')') {
8300 $tmpbefore = substr($InfoFieldList[4], 0, $pos);
8301 $tmpafter = substr($InfoFieldList[4], $pos + 1);
8303 $InfoFieldList[4] = $tmpbefore;
8304 if ($tmpafter !==
'') {
8305 $InfoFieldList = array_merge($InfoFieldList, explode(
':', $tmpafter));
8310 if (preg_match(
'/^\(?([a-z0-9]+)([=<>]+)(\d+)\)?$/i', $InfoFieldList[4], $reg)) {
8311 $InfoFieldList[4] =
'('.$reg[1].
':'.$reg[2].
':'.$reg[3].
')';
8319 '@phan-var-force array{0:string,1:string,2:string,3:string,3:string,5:string,6:string} $InfoFieldList';
8324 $keyList = (empty($InfoFieldList[2]) ?
'rowid' : $InfoFieldList[2].
' as rowid');
8326 if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
8327 if (strpos($InfoFieldList[4],
'extra.') !==
false) {
8328 $keyList =
'main.'.$InfoFieldList[2].
' as rowid';
8330 $keyList = $InfoFieldList[2].
' as rowid';
8333 if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
8334 list($parentName, $parentField) = explode(
'|', $InfoFieldList[3]);
8335 if (!empty($InfoFieldList[4]) && strpos($InfoFieldList[4],
'extra.') !==
false) {
8336 $keyList .=
', main.'.$parentField;
8338 $keyList .=
', '.$parentField;
8342 $filter_categorie =
false;
8343 if (count($InfoFieldList) > 5) {
8344 if ($InfoFieldList[0] ==
'categorie') {
8345 $filter_categorie =
true;
8350 if (!$filter_categorie) {
8351 $fields_label = explode(
'|', $InfoFieldList[1]);
8352 if (is_array($fields_label)) {
8354 $keyList .= implode(
', ', $fields_label);
8358 $sql =
"SELECT " . $keyList;
8359 $sql .=
' FROM ' . $this->db->prefix() . $InfoFieldList[0];
8361 if (!empty($InfoFieldList[4])) {
8363 if (strpos($InfoFieldList[4],
'$SEL$') !==
false) {
8364 $InfoFieldList[4] = str_replace(
'$SEL$',
'SELECT', $InfoFieldList[4]);
8368 if (strpos($InfoFieldList[4],
'$ID$') !==
false && !empty($objectid)) {
8369 $InfoFieldList[4] = str_replace(
'$ID$', (
string) $objectid, $InfoFieldList[4]);
8371 $InfoFieldList[4] = str_replace(
'$ID$',
'0', $InfoFieldList[4]);
8376 if (strpos($InfoFieldList[4],
'extra') !==
false) {
8377 $sql .=
' as main, ' . $this->db->sanitize($this->db->prefix() . $InfoFieldList[0]) .
'_extrafields as extra';
8378 $sqlwhere .=
" WHERE extra.fk_object = main." . $this->db->sanitize($InfoFieldList[2]);
8384 $sqlwhere .=
' WHERE 1=1';
8401 if (in_array($InfoFieldList[0], array(
'tablewithentity'))) {
8402 $sqlwhere .=
" AND entity = " . ((int) $conf->entity);
8409 dol_syslog(get_class($this) .
'::showInputField type=chkbxlst', LOG_DEBUG);
8411 $resql = $this->db->query($sql);
8413 $num = $this->db->num_rows($resql);
8420 $obj = $this->db->fetch_object($resql);
8424 $fields_label = explode(
'|', $InfoFieldList[1]);
8425 if (count($fields_label) > 1) {
8427 foreach ($fields_label as $field_toshow) {
8428 $labeltoshow .= $obj->$field_toshow .
' ';
8431 $labeltoshow = $obj->{$InfoFieldList[1]};
8433 $labeltoshow =
dol_trunc($labeltoshow, 45);
8435 if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
8436 foreach ($fields_label as $field_toshow) {
8437 $translabel = $langs->trans($obj->$field_toshow);
8438 if ($translabel != $obj->$field_toshow) {
8439 $labeltoshow =
dol_trunc($translabel, 18) .
' ';
8441 $labeltoshow =
dol_trunc($obj->$field_toshow, 18) .
' ';
8445 $data[$obj->rowid] = $labeltoshow;
8448 $translabel = $langs->trans($obj->{$InfoFieldList[1]});
8449 if ($translabel != $obj->{$InfoFieldList[1]}) {
8450 $labeltoshow =
dol_trunc($translabel, 18);
8452 $labeltoshow =
dol_trunc($obj->{$InfoFieldList[1]}, 18);
8455 if (empty($labeltoshow)) {
8456 $labeltoshow =
'(not defined)';
8459 if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
8460 $data[$obj->rowid] = $labeltoshow;
8463 if (!empty($InfoFieldList[3]) && $parentField) {
8464 $parent = $parentName .
':' . $obj->{$parentField};
8468 $data[$obj->rowid] = $labeltoshow;
8473 $this->db->free($resql);
8475 $out = $form->multiselectarray($keyprefix . $key . $keysuffix, $data, $value_arr, 0, 0, $morecss, 0,
'100%');
8477 print
'Error in request ' . $sql .
' ' . $this->db->lasterror() .
'. Check setup of extra parameters.<br>';
8480 require_once DOL_DOCUMENT_ROOT.
'/categories/class/categorie.class.php';
8481 $categcode = $InfoFieldList[5];
8482 if (is_numeric($categcode)) {
8483 $tmpcategory =
new Categorie($this->db);
8484 $MAP_ID_TO_CODE = array_flip($tmpcategory->MAP_ID);
8485 $categcode = $MAP_ID_TO_CODE[(int) $categcode];
8488 $data = $form->select_all_categories($categcode,
'',
'parent', 64, $InfoFieldList[6], 1, 1);
8489 $out = $form->multiselectarray($keyprefix . $key . $keysuffix, $data, $value_arr, 0, 0, $morecss, 0,
'100%');
8492 } elseif ($type ==
'link') {
8495 $param_list = array_keys($param[
'options']);
8496 $param_list_array = explode(
':', $param_list[0], 4);
8498 $showempty = (($required && $default !=
'') ? 0 : 1);
8500 if (!preg_match(
'/search_/', $keyprefix)) {
8501 if (!empty($param_list_array[2])) {
8503 if (!empty($this->fields[$key][
'picto'])) {
8504 $morecss .=
' widthcentpercentminusxx';
8506 $morecss .=
' widthcentpercentminusx';
8510 if (!empty($this->fields[$key][
'picto'])) {
8511 $morecss .=
' widthcentpercentminusx';
8520 $objectfield = $val;
8523 $out = $form->selectForForms($param_list_array[0], $keyprefix.$key.$keysuffix, (
int) $value, $showempty,
'',
'', $morecss, $moreparam, 0, (empty($val[
'disabled']) ? 0 : 1),
'', $objectfield);
8525 if (!empty($param_list_array[2])) {
8526 if ((!GETPOSTISSET(
'backtopage') || strpos(
GETPOST(
'backtopage'), $_SERVER[
'PHP_SELF']) === 0)
8527 && empty($val[
'disabled']) && empty($nonewbutton)) {
8528 list($class, $classfile) = explode(
':', $param_list[0]);
8529 if (file_exists(
dol_buildpath(dirname(dirname($classfile)).
'/card.php'))) {
8530 $url_path =
dol_buildpath(dirname(dirname($classfile)).
'/card.php', 1);
8532 $url_path =
dol_buildpath(dirname(dirname($classfile)).
'/'.strtolower($class).
'_card.php', 1);
8534 $paramforthenewlink =
'';
8535 $paramforthenewlink .= (GETPOSTISSET(
'action') ?
'&action='.GETPOST(
'action',
'aZ09') :
'');
8536 $paramforthenewlink .= (GETPOSTISSET(
'id') ?
'&id='.GETPOSTINT(
'id') :
'');
8537 $paramforthenewlink .= (GETPOSTISSET(
'origin') ?
'&origin='.GETPOST(
'origin',
'aZ09') :
'');
8538 $paramforthenewlink .= (GETPOSTISSET(
'originid') ?
'&originid='.GETPOSTINT(
'originid') :
'');
8539 $paramforthenewlink .=
'&fk_'.strtolower($class).
'=--IDFORBACKTOPAGE--';
8541 $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>';
8544 } elseif ($type ==
'password') {
8546 if ($keyprefix.$key.$keysuffix ==
'pass_crypted') {
8547 $out =
'<input type="'.($keyprefix ==
'search_' ?
'text' :
'password').
'" class="flat '.$morecss.
'" name="pass" id="pass" value="" '.($moreparam ? $moreparam :
'').
'>';
8548 $out .=
'<input type="hidden" name="pass_crypted" id="pass_crypted" value="'.$value.
'" '.($moreparam ? $moreparam :
'').
'>';
8550 $out =
'<input type="'.($keyprefix ==
'search_' ?
'text' :
'password').
'" class="flat '.$morecss.
'" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.$value.
'" '.($moreparam ? $moreparam :
'').
'>';
8552 } elseif ($type ==
'array') {
8554 $newval[
'type'] =
'varchar(256)';
8557 if (!empty($value)) {
8558 foreach ($value as $option) {
8559 $out .=
'<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).
'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
8560 $out .= $this->showInputField($newval, $keyprefix.$key.$keysuffix.
'[]', $option, $moreparam,
'',
'', $morecss).
'<br></span>';
8563 $out .=
'<a id="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).
'_add" href="javascript:;"><span class="fa fa-plus-circle valignmiddle"></span></a>';
8565 $newInput =
'<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).
'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
8566 $newInput .= $this->showInputField($newval, $keyprefix.$key.$keysuffix.
'[]',
'', $moreparam,
'',
'', $morecss).
'<br></span>';
8568 if (!empty($conf->use_javascript_ajax)) {
8570 <script nonce="'.getNonce().
'">
8571 $(document).ready(function() {
8572 $("a#'.
dol_escape_js($keyprefix.$key.$keysuffix).
'_add").click(function() {
8576 $(document).on("click", "a.'.
dol_escape_js($keyprefix.$key.$keysuffix).
'_del", function() {
8577 $(this).parent().remove();
8583 if (!empty($hidden)) {
8584 $out =
'<input type="hidden" value="'.$value.
'" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'"/>';
8587 if ($isDependList == 1) {
8588 $out .= $this->getJSListDependancies(
'_common');
8596 if (!empty($fieldValidationErrorMsg) && function_exists(
'getFieldErrorIcon')) {
8597 $out .=
' '.getFieldErrorIcon($fieldValidationErrorMsg);
8616 public function showOutputField($val, $key, $value, $moreparam =
'', $keysuffix =
'', $keyprefix =
'', $morecss =
'')
8618 global $conf, $langs, $form;
8622 if (!is_object($form)) {
8623 require_once DOL_DOCUMENT_ROOT.
'/core/class/html.form.class.php';
8624 $form =
new Form($this->db);
8628 $type = empty($val[
'type']) ?
'' : $val[
'type'];
8629 $size = empty($val[
'css']) ?
'' : $val[
'css'];
8633 if (preg_match(
'/varchar\((\d+)\)/', $type, $reg)) {
8636 } elseif (preg_match(
'/varchar/', $type)) {
8639 if (!empty($val[
'arrayofkeyval']) && is_array($val[
'arrayofkeyval'])) {
8641 if (empty($this->fields[$key][
'multiinput'])) {
8642 $type = (($this->fields[$key][
'type'] ==
'checkbox') ? $this->fields[$key][
'type'] :
'select');
8645 if (isset($val[
'type']) && preg_match(
'/^integer:(.*):(.*)/i', $val[
'type'], $reg)) {
8649 $default = empty($val[
'default']) ?
'' : $val[
'default'];
8650 $computed = empty($val[
'computed']) ?
'' : $val[
'computed'];
8651 $unique = empty($val[
'unique']) ?
'' : $val[
'unique'];
8652 $required = empty($val[
'required']) ?
'' : $val[
'required'];
8654 $param[
'options'] = array();
8656 if (!empty($val[
'arrayofkeyval']) && is_array($val[
'arrayofkeyval'])) {
8657 $param[
'options'] = $val[
'arrayofkeyval'];
8659 if (isset($val[
'type']) && preg_match(
'/^integer:([^:]*):([^:]*)/i', $val[
'type'], $reg)) {
8661 $stringforoptions = $reg[1].
':'.$reg[2];
8663 if ($reg[1] ==
'User') {
8664 $stringforoptions .=
':#getnomurlparam1=-1';
8666 $param[
'options'] = array($stringforoptions => $stringforoptions);
8667 } elseif (isset($val[
'type']) && preg_match(
'/^sellist:(.*):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
8668 $param[
'options'] = array($reg[1].
':'.$reg[2].
':'.$reg[3].
':'.$reg[4] =>
'N');
8670 } elseif (isset($val[
'type']) && preg_match(
'/^sellist:(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
8671 $param[
'options'] = array($reg[1].
':'.$reg[2].
':'.$reg[3] =>
'N');
8673 } elseif (isset($val[
'type']) && preg_match(
'/^sellist:(.*):(.*)/i', $val[
'type'], $reg)) {
8674 $param[
'options'] = array($reg[1].
':'.$reg[2] =>
'N');
8676 } elseif (isset($val[
'type']) && preg_match(
'/^chkbxlst:(.*)/i', $val[
'type'], $reg)) {
8677 $param[
'options'] = array($reg[1] =>
'N');
8679 } elseif (isset($val[
'type']) && preg_match(
'/stars\((\d+)\)/', $val[
'type'], $reg)) {
8680 $param[
'options'] = array();
8685 $langfile = empty($val[
'langfile']) ?
'' : $val[
'langfile'];
8686 $list = (empty($val[
'list']) ?
'' : $val[
'list']);
8687 $help = (empty($val[
'help']) ?
'' : $val[
'help']);
8688 $hidden = (($val[
'visible'] == 0) ? 1 : 0);
8698 $value =
dol_eval((
string) $computed, 1, 0,
'2');
8701 if (empty($morecss)) {
8702 if ($type ==
'date') {
8703 $morecss =
'minwidth100imp';
8704 } elseif ($type ==
'datetime' || $type ==
'timestamp') {
8705 $morecss =
'minwidth200imp';
8706 } elseif (in_array($type, array(
'int',
'double',
'price'))) {
8707 $morecss =
'maxwidth75';
8708 } elseif ($type ==
'url') {
8709 $morecss =
'minwidth400';
8710 } elseif ($type ==
'boolean') {
8713 if (is_numeric($size) && round((
float) $size) < 12) {
8714 $morecss =
'minwidth100';
8715 } elseif (is_numeric($size) && round((
float) $size) <= 48) {
8716 $morecss =
'minwidth200';
8718 $morecss =
'minwidth400';
8724 if (in_array($key, array(
'rowid',
'ref')) && method_exists($this,
'getNomUrl')) {
8726 if ($key !=
'rowid' || empty($this->fields[
'ref'])) {
8727 $value = $this->getNomUrl(1,
'', 0,
'', 1);
8729 } elseif ($key ==
'status' && method_exists($this,
'getLibStatut')) {
8730 $value = $this->getLibStatut(3);
8731 } elseif ($type ==
'date') {
8732 if (!empty($value)) {
8737 } elseif ($type ==
'datetime' || $type ==
'timestamp') {
8738 if (!empty($value)) {
8743 } elseif ($type ==
'duration') {
8744 include_once DOL_DOCUMENT_ROOT.
'/core/lib/date.lib.php';
8745 if (!is_null($value) && $value !==
'') {
8748 } elseif ($type ==
'double' || $type ==
'real') {
8749 if (!is_null($value) && $value !==
'') {
8750 $value =
price($value);
8752 } elseif ($type ==
'boolean') {
8754 if (!empty($value)) {
8755 $checked =
' checked ';
8758 $value =
'<input type="checkbox" '.$checked.
' '.($moreparam ? $moreparam :
'').
' readonly disabled>';
8760 $value =
yn($value ? 1 : 0);
8762 } elseif ($type ==
'mail' || $type ==
'email') {
8764 } elseif ($type ==
'url') {
8766 } elseif ($type ==
'phone') {
8767 $value =
dol_print_phone((
string) $value,
'', 0, 0,
'',
' ',
'phone');
8768 } elseif ($type ==
'ip') {
8770 } elseif ($type ==
'stars') {
8771 $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 :
'').
'>';
8772 $value .=
'<div class="star-selection" id="'.$keyprefix.$key.$keysuffix.$this->id.
'_selection">';
8774 while ($i <= $size) {
8775 $value .=
'<span class="star" data-value="'.$i.
'">'.
img_picto(
'',
'fontawesome_star_fas').
'</span>';
8780 $(document).ready(function() { /* commonobject.class.php 2 */
8781 let container = $("#'.$keyprefix.$key.$keysuffix.$this->id.
'_selection");
8782 let selectedStars = parseInt($("#'.$keyprefix.$key.$keysuffix.$this->id.
'").val()) || 0;
8783 container.find(".star").each(function() {
8784 $(this).toggleClass("active", $(this).data("value") <= selectedStars);
8786 container.find(".star").on("mouseover", function() {
8787 let selectedStar = $(this).data("value");
8788 container.find(".star").each(function() {
8789 $(this).toggleClass("active", $(this).data("value") <= selectedStar);
8792 container.on("mouseout", function() {
8793 container.find(".star").each(function() {
8794 $(this).toggleClass("active", $(this).data("value") <= selectedStars);
8797 container.find(".star").off("click").on("click", function() {
8798 selectedStars = $(this).data("value");
8799 if (selectedStars == 1 && $("#'.$keyprefix.$key.$keysuffix.$this->id.
'").val() == 1) {
8802 container.find("#'.$keyprefix.$key.$keysuffix.$this->id.
'").val(selectedStars);
8803 container.find(".star").each(function() {
8804 $(this).toggleClass("active", $(this).data("value") <= selectedStars);
8807 url: "ajax/'.$this->element.
'.php",
8810 objectId: "'.$this->
id.
'",
8811 field: "'.$keyprefix.$key.$keysuffix.
'",
8812 value: selectedStars,
8815 success: function(response) {
8816 var res = JSON.parse(response);
8817 console[res.status === "success" ? "log" : "error"](res.message);
8819 error: function(xhr, status, error) {
8820 console.log("Ajax request failed while updating '.$keyprefix.$key.$keysuffix.
':", error);
8826 } elseif ($type ==
'price') {
8827 if (!is_null($value) && $value !==
'') {
8828 $value =
price($value, 0, $langs, 0, 0, -1, $conf->currency);
8830 } elseif ($type ==
'select') {
8831 $value = isset($param[
'options'][(
string) $value]) ? $param[
'options'][(string) $value] :
'';
8832 if (strpos($value,
"|") !==
false) {
8833 $value = $langs->trans(explode(
'|', $value)[0]);
8834 } elseif (! is_numeric($value)) {
8835 $value = $langs->trans($value);
8837 } elseif ($type ==
'sellist') {
8838 $param_list = array_keys($param[
'options']);
8839 $InfoFieldList = explode(
":", $param_list[0]);
8841 $selectkey =
"rowid";
8844 if (count($InfoFieldList) > 2 && !empty($InfoFieldList[2])) {
8845 $selectkey = $InfoFieldList[2];
8846 $keyList = $InfoFieldList[2].
' as rowid';
8849 $fields_label = explode(
'|', $InfoFieldList[1]);
8850 if (is_array($fields_label)) {
8852 $keyList .= implode(
', ', $fields_label);
8855 $filter_categorie =
false;
8856 if (count($InfoFieldList) > 5) {
8857 if ($InfoFieldList[0] ==
'categorie') {
8858 $filter_categorie =
true;
8862 $sql =
"SELECT ".$keyList;
8863 $sql .=
' FROM '.$this->db->prefix().$InfoFieldList[0];
8864 if (isset($InfoFieldList[4]) && strpos($InfoFieldList[4],
'extra') !==
false) {
8867 if ($selectkey ==
'rowid' && empty($value)) {
8868 $sql .=
" WHERE ".$selectkey.
" = 0";
8869 } elseif ($selectkey ==
'rowid') {
8870 $sql .=
" WHERE ".$selectkey.
" = ".((int) $value);
8872 $sql .=
" WHERE ".$selectkey.
" = '".$this->db->escape((
string) $value).
"'";
8877 dol_syslog(get_class($this).
':showOutputField:$type=sellist', LOG_DEBUG);
8878 $resql = $this->db->query($sql);
8880 if (!$filter_categorie) {
8882 $numrows = $this->db->num_rows($resql);
8884 $obj = $this->db->fetch_object($resql);
8887 $fields_label = explode(
'|', $InfoFieldList[1]);
8889 if (is_array($fields_label) && count($fields_label) > 1) {
8890 foreach ($fields_label as $field_toshow) {
8892 if (!empty($obj->$field_toshow)) {
8893 $translabel = $langs->trans($obj->$field_toshow);
8895 if ($translabel != $field_toshow) {
8896 $value .=
dol_trunc($translabel, 18) .
' ';
8898 $value .= $obj->$field_toshow .
' ';
8903 if (!empty($obj->{$InfoFieldList[1]})) {
8904 $translabel = $langs->trans($obj->{$InfoFieldList[1]});
8906 if ($translabel != $obj->{$InfoFieldList[1]}) {
8909 $value = $obj->{$InfoFieldList[1]};
8914 require_once DOL_DOCUMENT_ROOT .
'/categories/class/categorie.class.php';
8917 $obj = $this->db->fetch_object($resql);
8919 $c->fetch($obj->rowid);
8920 $ways =
$c->print_all_ways();
8921 foreach ($ways as $way) {
8922 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories"' . (
$c->color ?
' style="background: #' .
$c->color .
';"' :
' style="background: #aaa"') .
'>' .
img_object(
'',
'category') .
' ' . $way .
'</li>';
8924 $value =
'<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(
' ', $toprint).
'</ul></div>';
8927 dol_syslog(get_class($this).
'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
8929 } elseif ($type ==
'radio') {
8930 $value = $param[
'options'][(string) $value];
8931 } elseif ($type ==
'checkbox') {
8932 $value_arr = explode(
',', (
string) $value);
8934 if (is_array($value_arr) && count($value_arr) > 0) {
8936 foreach ($value_arr as $keyval => $valueval) {
8937 if (!empty($valueval)) {
8938 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' . $param[
'options'][$valueval] .
'</li>';
8941 if (!empty($toprint)) {
8942 $value =
'<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">' . implode(
' ', $toprint) .
'</ul></div>';
8945 } elseif ($type ==
'chkbxlst') {
8946 $value_arr = (isset($value) ? explode(
',', $value) : array());
8948 $param_list = array_keys($param[
'options']);
8949 $InfoFieldList = explode(
":", $param_list[0]);
8951 $selectkey =
"rowid";
8954 if (count($InfoFieldList) >= 3) {
8955 $selectkey = $InfoFieldList[2];
8956 $keyList = $InfoFieldList[2].
' as rowid';
8959 $fields_label = explode(
'|', $InfoFieldList[1]);
8960 if (is_array($fields_label)) {
8962 $keyList .= implode(
', ', $fields_label);
8965 $filter_categorie =
false;
8966 if (count($InfoFieldList) > 5) {
8967 if ($InfoFieldList[0] ==
'categorie') {
8968 $filter_categorie =
true;
8972 $sql =
"SELECT ".$keyList;
8973 $sql .=
' FROM '.$this->db->prefix().$InfoFieldList[0];
8974 if (isset($InfoFieldList[4]) && strpos($InfoFieldList[4],
'extra') !==
false) {
8980 dol_syslog(get_class($this).
':showOutputField:$type=chkbxlst', LOG_DEBUG);
8981 $resql = $this->db->query($sql);
8983 if (!$filter_categorie) {
8986 while ($obj = $this->db->fetch_object($resql)) {
8988 $fields_label = explode(
'|', $InfoFieldList[1]);
8989 if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
8990 if (is_array($fields_label) && count($fields_label) > 1) {
8991 foreach ($fields_label as $field_toshow) {
8993 if (!empty($obj->$field_toshow)) {
8994 $translabel = $langs->trans($obj->$field_toshow);
8996 if ($translabel != $field_toshow) {
8997 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' .
dol_trunc($translabel, 18) .
'</li>';
8999 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' . $obj->$field_toshow .
'</li>';
9004 if (!empty($obj->{$InfoFieldList[1]})) {
9005 $translabel = $langs->trans($obj->{$InfoFieldList[1]});
9007 if ($translabel != $obj->{$InfoFieldList[1]}) {
9008 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' .
dol_trunc($translabel, 18) .
'</li>';
9010 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' . $obj->{$InfoFieldList[1]} .
'</li>';
9016 require_once DOL_DOCUMENT_ROOT .
'/categories/class/categorie.class.php';
9019 while ($obj = $this->db->fetch_object($resql)) {
9020 if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
9022 $c->fetch($obj->rowid);
9023 $ways =
$c->print_all_ways();
9024 foreach ($ways as $way) {
9025 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories"' . (
$c->color ?
' style="background: #' .
$c->color .
';"' :
' style="background: #aaa"') .
'>' .
img_object(
'',
'category') .
' ' . $way .
'</li>';
9030 $value =
'<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(
' ', $toprint).
'</ul></div>';
9032 dol_syslog(get_class($this).
'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
9034 } elseif ($type ==
'link') {
9039 $param_list = array_keys($param[
'options']);
9043 $InfoFieldList = explode(
":", $param_list[0]);
9045 $classname = $InfoFieldList[0];
9046 $classpath = $InfoFieldList[1];
9049 $getnomurlparam = 3;
9050 $getnomurlparam2 =
'';
9052 if (preg_match(
'/#getnomurlparam1=([^#]*)/', $param_list[0], $regtmp)) {
9053 $getnomurlparam = $regtmp[1];
9055 if (preg_match(
'/#getnomurlparam2=([^#]*)/', $param_list[0], $regtmp)) {
9056 $getnomurlparam2 = $regtmp[1];
9059 if (!empty($classpath)) {
9062 if ($classname && !class_exists($classname)) {
9066 if ($element_prop) {
9067 $classname = $element_prop[
'classname'];
9072 if ($classname && class_exists($classname)) {
9073 $object =
new $classname($this->db);
9074 '@phan-var-force CommonObject $object';
9075 if (
$object->element ===
'product') {
9076 '@phan-var-force Product $object';
9077 $result =
$object->fetch((
int) $value,
'',
'',
'', 0, 1, 1);
9079 $result =
$object->fetch($value);
9082 if (
$object->element ===
'product') {
9083 '@phan-var-force Product $object';
9084 $get_name_url_param_arr = array($getnomurlparam, $getnomurlparam2, 0, -1, 0,
'', 0);
9085 if (isset($val[
'get_name_url_params'])) {
9086 $get_name_url_params = explode(
':', $val[
'get_name_url_params']);
9087 if (!empty($get_name_url_params)) {
9088 $param_num_max = count($get_name_url_param_arr) - 1;
9089 foreach ($get_name_url_params as $param_num => $param_value) {
9090 if ($param_num > $param_num_max) {
9093 $get_name_url_param_arr[$param_num] = $param_value;
9101 $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]);
9103 $value =
$object->getNomUrl($getnomurlparam, $getnomurlparam2);
9110 dol_syslog(
'Error bad setup of extrafield', LOG_WARNING);
9111 return 'Error bad setup of extrafield';
9116 } elseif ($type ==
'password') {
9117 $value =
'<span class="opacitymedium">'.$langs->trans(
"Encrypted").
'</span>';
9119 } elseif ($type ==
'array') {
9120 if (is_array($value)) {
9121 $value = implode(
'<br>', $value);
9123 dol_syslog(__METHOD__.
' Expected array from dol_eval, but got '.gettype($value), LOG_ERR);
9124 return 'Error unexpected result from code evaluation';
9127 if (!empty($value) && preg_match(
'/^text/', (
string) $type) && !preg_match(
'/search_/', $keyprefix) && !empty($param[
'options'])) {
9128 $value = str_replace(
',',
"\n", $value);
9136 return is_null($out) ?
'' : $out;
9148 unset($this->validateFieldsErrors[$fieldKey]);
9162 $msg = $langs->trans(
"UnknownError");
9165 $this->error = $this->validateFieldsErrors[$fieldKey] = $msg;
9176 if (!empty($this->validateFieldsErrors[$fieldKey])) {
9177 return $this->validateFieldsErrors[$fieldKey];
9194 if (!class_exists(
'Validate')) {
9195 require_once DOL_DOCUMENT_ROOT .
'/core/class/validate.class.php';
9198 $this->clearFieldError($fieldKey);
9200 if (!array_key_exists($fieldKey, $fields) || !is_array($fields[$fieldKey])) {
9201 $this->setFieldError($fieldKey, $langs->trans(
'FieldNotFoundInObject'));
9205 $val = $fields[$fieldKey];
9208 $param[
'options'] = array();
9209 $type = $val[
'type'];
9212 if (isset($val[
'notnull']) && $val[
'notnull'] === 1) {
9226 if (preg_match(
'/varchar\((\d+)\)/', $type, $reg)) {
9228 $maxSize = (int) $reg[1];
9229 } elseif (preg_match(
'/varchar/', $type)) {
9233 if (!empty($val[
'arrayofkeyval']) && is_array($val[
'arrayofkeyval'])) {
9237 if (!empty($val[
'type']) && preg_match(
'/^integer:(.*):(.*)/i', $val[
'type'], $reg)) {
9241 if (!empty($val[
'arrayofkeyval']) && is_array($val[
'arrayofkeyval'])) {
9242 $param[
'options'] = $val[
'arrayofkeyval'];
9245 if (preg_match(
'/^integer:(.*):(.*)/i', $val[
'type'], $reg)) {
9247 $param[
'options'] = array($reg[1].
':'.$reg[2] => $reg[1].
':'.$reg[2]);
9248 } elseif (preg_match(
'/^sellist:(.*):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
9249 $param[
'options'] = array($reg[1].
':'.$reg[2].
':'.$reg[3].
':'.$reg[4] =>
'N');
9251 } elseif (preg_match(
'/^sellist:(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
9252 $param[
'options'] = array($reg[1].
':'.$reg[2].
':'.$reg[3] =>
'N');
9254 } elseif (preg_match(
'/^sellist:(.*):(.*)/i', $val[
'type'], $reg)) {
9255 $param[
'options'] = array($reg[1].
':'.$reg[2] =>
'N');
9264 $validate =
new Validate($this->db, $langs);
9274 if ($required && !$validate->isNotEmptyString($fieldValue)) {
9275 $this->setFieldError($fieldKey, $validate->error);
9277 } elseif (!$required && !$validate->isNotEmptyString($fieldValue)) {
9283 if (!empty($maxSize) && !$validate->isMaxLength($fieldValue, $maxSize)) {
9284 $this->setFieldError($fieldKey, $validate->error);
9289 if (!empty($minSize) && !$validate->isMinLength($fieldValue, $minSize)) {
9290 $this->setFieldError($fieldKey, $validate->error);
9298 if (in_array($type, array(
'date',
'datetime',
'timestamp'))) {
9299 if (!$validate->isTimestamp($fieldValue)) {
9300 $this->setFieldError($fieldKey, $validate->error);
9305 } elseif ($type ==
'duration') {
9306 if (!$validate->isDuration($fieldValue)) {
9307 $this->setFieldError($fieldKey, $validate->error);
9312 } elseif (in_array($type, array(
'double',
'real',
'price'))) {
9314 if (!$validate->isNumeric($fieldValue)) {
9315 $this->setFieldError($fieldKey, $validate->error);
9320 } elseif ($type ==
'boolean') {
9321 if (!$validate->isBool($fieldValue)) {
9322 $this->setFieldError($fieldKey, $validate->error);
9327 } elseif ($type ==
'mail' || $type ==
'email') {
9328 if (!$validate->isEmail($fieldValue)) {
9329 $this->setFieldError($fieldKey, $validate->error);
9332 } elseif ($type ==
'url') {
9333 if (!$validate->isUrl($fieldValue)) {
9334 $this->setFieldError($fieldKey, $validate->error);
9339 } elseif ($type ==
'phone') {
9340 if (!$validate->isPhone($fieldValue)) {
9341 $this->setFieldError($fieldKey, $validate->error);
9346 } elseif ($type ==
'select' || $type ==
'radio') {
9347 if (!isset($param[
'options'][$fieldValue])) {
9348 $this->error = $langs->trans(
'RequireValidValue');
9353 } elseif ($type ==
'sellist' || $type ==
'chkbxlst') {
9354 $param_list = array_keys($param[
'options']);
9355 $InfoFieldList = explode(
":", $param_list[0]);
9356 $value_arr = explode(
',', $fieldValue);
9357 $value_arr = array_map(array($this->db,
'escape'), $value_arr);
9359 $selectkey =
"rowid";
9360 if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
9361 $selectkey = $InfoFieldList[2];
9364 if (!$validate->isInDb($value_arr, $InfoFieldList[0], $selectkey)) {
9365 $this->setFieldError($fieldKey, $validate->error);
9370 } elseif ($type ==
'link') {
9371 $param_list = array_keys($param[
'options']);
9372 $InfoFieldList = explode(
":", $param_list[0]);
9373 $classname = $InfoFieldList[0];
9374 $classpath = $InfoFieldList[1];
9375 if (!$validate->isFetchable((
int) $fieldValue, $classname, $classpath)) {
9376 $lastIsFetchableError = $validate->error;
9379 if ($validate->isFetchableElement((
int) $fieldValue, $classname)) {
9383 $this->setFieldError($fieldKey, $lastIsFetchableError);
9407 public function showOptionals($extrafields, $mode =
'view', $params =
null, $keysuffix =
'', $keyprefix =
'', $onetrtd =
'', $display_type =
'card')
9409 global $db, $conf, $langs, $action, $form, $hookmanager;
9411 if (!is_object($form)) {
9412 $form =
new Form($db);
9414 if (!is_object($extrafields)) {
9415 dol_syslog(
'Bad parameter extrafields for showOptionals', LOG_ERR);
9416 return 'Bad parameter extrafields for showOptionals';
9418 if (!is_array($extrafields->attributes[$this->table_element])) {
9419 dol_syslog(
"extrafields->attributes was not loaded with extrafields->fetch_name_optionals_label(table_element);", LOG_WARNING);
9424 $parameters = array(
'mode' => $mode,
'params' => $params,
'keysuffix' => $keysuffix,
'keyprefix' => $keyprefix,
'display_type' => $display_type);
9425 $reshook = $hookmanager->executeHooks(
'showOptionals', $parameters, $this, $action);
9426 $hookResPrint = $hookmanager->resPrint;
9428 if (empty($reshook)) {
9429 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) {
9431 $out .=
'<!-- commonobject:showOptionals --> ';
9434 $nbofextrafieldsshown = 0;
9437 $lastseparatorkeyfound =
'';
9438 $extrafields_collapse_num =
'';
9439 $extrafields_collapse_num_old =
'';
9442 foreach ($extrafields->attributes[$this->table_element][
'label'] as $key => $label) {
9446 if (is_array($params) && array_key_exists(
'onlykey', $params) && $key != $params[
'onlykey']) {
9452 if ($enabled && isset($extrafields->attributes[$this->table_element][
'enabled'][$key])) {
9453 $enabled = (int)
dol_eval((
string) $extrafields->attributes[$this->table_element][
'enabled'][$key], 1, 1,
'2');
9455 if (empty($enabled)) {
9460 if (isset($extrafields->attributes[$this->table_element][
'list'][$key])) {
9461 $visibility = (int)
dol_eval((
string) $extrafields->attributes[$this->table_element][
'list'][$key], 1, 1,
'2');
9465 if ($perms && isset($extrafields->attributes[$this->table_element][
'perms'][$key])) {
9466 $perms = (int)
dol_eval((
string) $extrafields->attributes[$this->table_element][
'perms'][$key], 1, 1,
'2');
9469 if (($mode ==
'create') && !in_array(abs($visibility), array(1, 3))) {
9471 } elseif (($mode ==
'edit') && !in_array(abs($visibility), array(1, 3, 4))) {
9473 $ef_name =
'options_' . $key;
9474 $ef_value = $this->array_options[$ef_name]??
'';
9475 $out .=
'<input type="hidden" name="' . $ef_name .
'" id="' . $ef_name .
'" value="' . $ef_value .
'" />' .
"\n";
9477 } elseif ($mode ==
'view' && empty($visibility)) {
9480 if (empty($perms)) {
9485 if (!empty($extrafields->attributes[$this->table_element][
'langfile'][$key])) {
9486 $langs->load($extrafields->attributes[$this->table_element][
'langfile'][$key]);
9491 if (is_array($params) && count($params) > 0 && $display_type ==
'card') {
9492 if (array_key_exists(
'cols', $params)) {
9493 $colspan = $params[
'cols'];
9494 } elseif (array_key_exists(
'colspan', $params)) {
9496 if (preg_match(
'/colspan="(\d+)"/', $params[
'colspan'], $reg)) {
9499 $colspan = $params[
'colspan'];
9503 $colspan = intval($colspan);
9507 $value = ((!empty($this->array_options) && array_key_exists(
"options_".$key.$keysuffix, $this->array_options)) ? $this->array_options[
"options_".$key.$keysuffix] :
null);
9513 $check =
'alphanohtml';
9514 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'html',
'text'))) {
9515 $check =
'restricthtml';
9517 $getposttemp =
GETPOST($keyprefix.
'options_'.$key.$keysuffix, $check, 3);
9519 if (is_array($getposttemp) || $getposttemp !=
'' || GETPOSTISSET($keyprefix.
'options_'.$key.$keysuffix)) {
9520 if (is_array($getposttemp)) {
9522 $value = implode(
",", $getposttemp);
9524 $value = $getposttemp;
9526 } elseif (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'int'))) {
9527 $value = (!empty($this->array_options[
"options_".$key]) || (isset($this->array_options[
"options_".$key]) && $this->array_options[
"options_".$key] ===
'0')) ? $this->array_options[
"options_".$key] :
'';
9529 $value = (!empty($this->array_options[
"options_".$key]) ? $this->array_options[
"options_".$key] :
'');
9535 $nbofextrafieldsshown++;
9538 if ($extrafields->attributes[$this->table_element][
'type'][$key] ==
'separate') {
9539 $extrafields_collapse_num = $key;
9557 $out .= $extrafields->showSeparator($key, $this, ($colspan ? $colspan + 1 : 2), $display_type, $mode);
9559 $lastseparatorkeyfound = $key;
9561 $collapse_group = $extrafields_collapse_num.(!empty($this->
id) ?
'_'.$this->id :
'');
9563 $class = (!empty($extrafields->attributes[$this->table_element][
'hidden'][$key]) ?
'hideobject ' :
'');
9565 if (is_array($params) && count($params) > 0) {
9566 if (array_key_exists(
'class', $params)) {
9567 $class .= $params[
'class'].
' ';
9569 if (array_key_exists(
'style', $params)) {
9570 $csstyle = $params[
'style'];
9575 $domData =
' data-element="extrafield"';
9576 $domData .=
' data-targetelement="'.$this->element.
'"';
9577 $domData .=
' data-targetid="'.$this->id.
'"';
9579 $html_id = (empty($this->
id) ?
'' :
'extrarow-'.$this->element.
'_'.$key.
'_'.
$this->id);
9580 if ($display_type ==
'card') {
9585 if ($action ==
'selectlines') {
9592 $force_values_on_change_company = (
9593 ($this->element ==
'facture' &&
getDolGlobalInt(
'THIRDPARTY_PROPAGATE_EXTRAFIELDS_TO_INVOICE'))
9594 || ($this->element ==
'commande' &&
getDolGlobalInt(
'THIRDPARTY_PROPAGATE_EXTRAFIELDS_TO_ORDER'))
9595 || ($this->element ==
'order_supplier' &&
getDolGlobalInt(
'THIRDPARTY_PROPAGATE_EXTRAFIELDS_TO_SUPPLIER_ORDER'))
9597 if ($force_values_on_change_company &&
GETPOSTINT(
'changecompany')) {
9598 $value = $this->array_options[
'options_'.$key] ?? $value;
9602 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'date'))) {
9603 $datenotinstring =
null;
9604 if (array_key_exists(
'options_'.$key, $this->array_options)) {
9605 $datenotinstring = $this->array_options[
'options_'.$key];
9606 if (!is_numeric($this->array_options[
'options_'.$key])) {
9607 $datenotinstring = $this->db->jdate($datenotinstring);
9610 $datekey = $keyprefix.
'options_'.$key.$keysuffix;
9613 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'datetime'))) {
9614 $datenotinstring =
null;
9615 if (array_key_exists(
'options_'.$key, $this->array_options)) {
9616 $datenotinstring = $this->array_options[
'options_'.$key];
9617 if (!is_numeric($this->array_options[
'options_'.$key])) {
9618 $datenotinstring = $this->db->jdate($datenotinstring);
9621 $timekey = $keyprefix.
'options_'.$key.$keysuffix;
9622 $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;
9625 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'price',
'double'))) {
9626 if (GETPOSTISSET($keyprefix.
'options_'.$key.$keysuffix) || $value) {
9628 } elseif (isset($this->array_options[
'options_'.$key])) {
9629 $value = $this->array_options[
'options_'.$key];
9634 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'html',
'text',
'varchar',
'select',
'radio',
'int',
'boolean'))) {
9635 if ($action ==
'create' || $mode ==
'create') {
9636 $value = (GETPOSTISSET($keyprefix.
'options_'.$key.$keysuffix) || $value) ? $value : $extrafields->attributes[$this->table_element][
'default'][$key];
9640 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'checkbox'))) {
9641 if ($action ==
'create') {
9642 $value = (GETPOSTISSET($keyprefix.
'options_'.$key.$keysuffix) || $value) ? $value : explode(
',', $extrafields->attributes[$this->table_element][
'default'][$key]);
9647 $labeltoshow = $langs->trans($label);
9648 $helptoshow = $langs->trans($extrafields->attributes[$this->table_element][
'help'][$key]);
9649 if ($display_type ==
'card') {
9650 $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.
' >';
9651 if (
getDolGlobalString(
'MAIN_VIEW_LINE_NUMBER') && ($action ==
'view' || $action ==
'valid' || $action ==
'editline' || $action ==
'confirm_valid' || $action ==
'confirm_cancel')) {
9652 $out .=
'<td></td>';
9654 $out .=
'<td class="'.(empty($params[
'tdclass']) ?
'titlefieldmax45' : $params[
'tdclass']).
' wordbreak';
9655 if ($extrafields->attributes[$this->table_element][
'type'][$key] ==
'text') {
9658 } elseif ($display_type ==
'line') {
9659 $out .=
'<div '.($html_id ?
'id="'.$html_id.
'" ' :
'').$csstyle.
' class="fieldline_options_'.$key.
' '.$class.$this->element.
'_extras_'.$key.
' trextrafields_collapse'.$collapse_group.
'" '.$domData.
' >';
9660 $out .=
'<div style="display: inline-block; padding-right:4px" class="wordbreak';
9665 $tpl_context = isset($params[
"tpl_context"]) ? $params[
"tpl_context"] :
"none";
9666 if ($tpl_context !=
"public") {
9667 if ($mode !=
'view' && !empty($extrafields->attributes[$this->table_element][
'required'][$key])) {
9668 $out .=
' fieldrequired';
9672 if ($tpl_context ==
"public") {
9673 if (!empty($extrafields->attributes[$this->table_element][
'help'][$key])) {
9674 $out .= $form->textwithpicto($labeltoshow, $helptoshow);
9676 $out .= $labeltoshow;
9678 if ($mode !=
'view' && !empty($extrafields->attributes[$this->table_element][
'required'][$key])) {
9679 $out .=
' <span style="color: red">*</span>';
9682 if (!empty($extrafields->attributes[$this->table_element][
'help'][$key])) {
9683 $out .= $form->textwithpicto($labeltoshow, $helptoshow);
9685 $out .= $labeltoshow;
9689 $out .= ($display_type ==
'card' ?
'</td>' :
'</div>');
9692 $html_id = !empty($this->
id) ? $this->element.
'_extras_'.$key.
'_'.$this->id :
'';
9693 if ($display_type ==
'card') {
9695 $out .=
'<td '.($html_id ?
'id="'.$html_id.
'" ' :
'').
' class="valuefieldcreate '.$this->element.
'_extras_'.$key;
9696 $out .=
'" '.($colspan ?
' colspan="'.$colspan.
'"' :
'');
9698 } elseif ($display_type ==
'line') {
9699 $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].
'">';
9704 $out .= $extrafields->showOutputField($key, $value,
'', $this->table_element);
9707 $listoftypestoshowpicto = explode(
',',
getDolGlobalString(
'MAIN_TYPES_TO_SHOW_PICTO',
'email,phone,ip,password'));
9708 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], $listoftypestoshowpicto)) {
9709 $out .=
getPictoForType($extrafields->attributes[$this->table_element][
'type'][$key], ($extrafields->attributes[$this->table_element][
'type'][$key] ==
'text' ?
'tdtop' :
''));
9712 $out .= $extrafields->showInputField($key, $value,
'', $keysuffix,
'',
'', $this, $this->table_element);
9715 $listoftypestoshowpicto = explode(
',',
getDolGlobalString(
'MAIN_TYPES_TO_SHOW_PICTO',
'email,phone,ip,password'));
9716 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], $listoftypestoshowpicto)) {
9717 $out .=
getPictoForType($extrafields->attributes[$this->table_element][
'type'][$key], ($extrafields->attributes[$this->table_element][
'type'][$key] ==
'text' ?
'tdtop' :
''));
9719 $out .= $extrafields->showInputField($key, $value,
'', $keysuffix,
'',
'', $this, $this->table_element);
9723 $out .= ($display_type ==
'card' ?
'</td>' :
'</div>');
9724 $out .= ($display_type ==
'card' ?
'</tr>'.
"\n" :
'</div>');
9730 if (!empty($conf->use_javascript_ajax)) {
9731 $out .= $this->getJSListDependancies();
9734 $out .=
'<!-- commonobject:showOptionals end --> '.
"\n";
9736 if (empty($nbofextrafieldsshown)) {
9742 $out .= $hookResPrint;
9754 <script nonce="'.getNonce().
'">
9755 jQuery(document).ready(function() {
9756 function showOptions'.$type.
'(child_list, parent_list, orig_select)
9758 var val = $("select[name=\""+parent_list+"\"]").val();
9759 var parentVal = parent_list + ":" + val;
9760 if(typeof val == "string"){
9762 var options = orig_select.find("option[parent=\""+parentVal+"\"]").clone();
9763 $("select[name=\""+child_list+"\"] option[parent]").remove();
9764 $("select[name=\""+child_list+"\"]").append(options);
9766 var options = orig_select.find("option[parent]").clone();
9767 $("select[name=\""+child_list+"\"] option[parent]").remove();
9768 $("select[name=\""+child_list+"\"]").append(options);
9770 } else if(val > 0) {
9771 var options = orig_select.find("option[parent=\""+parentVal+"\"]").clone();
9772 $("select[name=\""+child_list+"\"] option[parent]").remove();
9773 $("select[name=\""+child_list+"\"]").append(options);
9775 var options = orig_select.find("option[parent]").clone();
9776 $("select[name=\""+child_list+"\"] option[parent]").remove();
9777 $("select[name=\""+child_list+"\"]").append(options);
9780 function setListDependencies'.$type.
'() {
9781 jQuery("select option[parent]").parent().each(function() {
9782 var orig_select = {};
9783 var child_list = $(this).attr("name");
9784 orig_select[child_list] = $(this).clone();
9785 var parent = $(this).find("option[parent]:first").attr("parent");
9786 var infos = parent.split(":");
9787 var parent_list = infos[0];
9789 //Hide daughters lists
9790 if ($("#"+child_list).val() == 0 && $("#"+parent_list).val() == 0){
9791 $("#"+child_list).hide();
9793 } else if ($("#"+parent_list).val() != 0){
9794 $("#"+parent_list).show();
9796 //Show the child list if the parent list value is selected
9797 $("select[name=\""+parent_list+"\"]").click(function() {
9798 if ($(this).val() != 0){
9799 $("#"+child_list).show()
9803 //When we change parent list
9804 $("select[name=\""+parent_list+"\"]").change(function() {
9805 showOptions'.$type.
'(child_list, parent_list, orig_select[child_list]);
9806 //Select the value 0 on child list after a change on the parent list
9807 $("#"+child_list).val(0).trigger("change");
9808 //Hide child lists if the parent value is set to 0
9809 if ($(this).val() == 0){
9810 $("#"+child_list).hide();
9816 setListDependencies'.$type.
'();
9831 $module = empty($this->module) ?
'' : $this->module;
9832 $element = $this->element;
9834 if ($element ==
'facturerec') {
9835 $element =
'facture';
9836 } elseif ($element ==
'invoice_supplier_rec') {
9837 return !$user->hasRight(
'fournisseur',
'facture') ? null : $user->hasRight(
'fournisseur',
'facture');
9838 } elseif ($module && $user->hasRight($module, $element)) {
9840 return $user->hasRight($module, $element);
9843 return $user->rights->$element;
9860 global $hookmanager;
9862 $parameters = array(
9863 'origin_id' => $origin_id,
9864 'dest_id' => $dest_id,
9865 'tables' => $tables,
9867 $reshook = $hookmanager->executeHooks(
'commonReplaceThirdparty', $parameters);
9870 } elseif ($reshook < 0) {
9871 return $ignoreerrors === 1;
9874 foreach ($tables as $table) {
9875 $sql =
'UPDATE '.$dbs->prefix().$table.
' SET fk_soc = '.((int) $dest_id).
' WHERE fk_soc = '.((int) $origin_id);
9877 if (!$dbs->
query($sql)) {
9878 if ($ignoreerrors) {
9903 foreach ($tables as $table) {
9904 $sql =
'UPDATE '.MAIN_DB_PREFIX.$table.
' SET fk_product = '.((int) $dest_id).
' WHERE fk_product = '.((int) $origin_id);
9906 if (!$dbs->
query($sql)) {
9907 if ($ignoreerrors) {
9930 public function defineBuyPrice($unitPrice = 0.0, $discountPercent = 0.0, $fk_product = 0)
9936 if (($unitPrice > 0) && (isset($conf->global->ForceBuyingPriceIfNull) &&
getDolGlobalInt(
'ForceBuyingPriceIfNull') > 0)) {
9938 $buyPrice = $unitPrice * (1 - $discountPercent / 100);
9941 if (!empty($fk_product) && $fk_product > 0) {
9944 require_once DOL_DOCUMENT_ROOT.
'/product/class/product.class.php';
9945 $product =
new Product($this->db);
9946 $result = $product->fetch($fk_product);
9948 $this->errors[] =
'ErrorProductIdDoesNotExists';
9951 if ($product->cost_price > 0) {
9952 $buyPrice = $product->cost_price;
9953 } elseif ($product->pmp > 0) {
9954 $buyPrice = $product->pmp;
9957 require_once DOL_DOCUMENT_ROOT.
'/product/class/product.class.php';
9958 $product =
new Product($this->db);
9959 $result = $product->fetch($fk_product);
9961 $this->errors[] =
'ErrorProductIdDoesNotExists';
9964 if ($product->pmp > 0) {
9965 $buyPrice = $product->pmp;
9969 if (empty($buyPrice) && in_array(
getDolGlobalString(
'MARGIN_TYPE'), array(
'1',
'pmp',
'costprice'))) {
9970 require_once DOL_DOCUMENT_ROOT.
'/fourn/class/fournisseur.product.class.php';
9972 if (($result = $productFournisseur->find_min_price_product_fournisseur($fk_product)) > 0) {
9973 $buyPrice = $productFournisseur->fourn_unitprice;
9974 } elseif ($result < 0) {
9975 $this->errors[] = $productFournisseur->error;
9982 return (
float) $buyPrice;
9995 return array(
'dir' =>
'',
'file' =>
'',
'originalfile' =>
'',
'altfile' =>
'',
'email' =>
'',
'capture' =>
'');
10019 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')
10022 global $user, $langs;
10024 include_once DOL_DOCUMENT_ROOT.
'/core/lib/files.lib.php';
10025 include_once DOL_DOCUMENT_ROOT.
'/core/lib/images.lib.php';
10027 $sortfield =
'position_name';
10028 $sortorder =
'asc';
10033 $dir .=
get_exdir(0, 0, 0, 0, $this, $modulepart);
10034 $pdir .=
get_exdir(0, 0, 0, 0, $this, $modulepart);
10037 if ($modulepart ==
'product') {
10039 $dir = $sdir.
'/'.
get_exdir($this->
id, 2, 0, 0, $this, $modulepart).$this->id.
"/photos/";
10040 $pdir =
'/'.get_exdir($this->
id, 2, 0, 0, $this, $modulepart).$this->id.
"/photos/";
10043 if ($modulepart ==
'category') {
10044 $dir = $sdir.
'/'.
get_exdir($this->
id, 2, 0, 0, $this, $modulepart).$this->id.
"/photos/";
10045 $pdir =
'/'.get_exdir($this->
id, 2, 0, 0, $this, $modulepart).$this->id.
"/photos/";
10051 $relativedir = preg_replace(
'/^'.preg_quote(DOL_DATA_ROOT,
'/').
'/',
'', $dir);
10052 $relativedir = preg_replace(
'/^[\\/]/',
'', $relativedir);
10053 $relativedir = preg_replace(
'/[\\/]$/',
'', $relativedir);
10056 $dirthumb = $dir.
'thumbs/';
10057 $pdirthumb = $pdir.
'thumbs/';
10059 $return =
'<!-- Photo -->'.
"\n";
10062 $filearray =
dol_dir_list($dir,
"files", 0,
'',
'(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) ==
'desc' ? SORT_DESC : SORT_ASC), 1);
10071 '@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';
10073 if (count($filearray)) {
10074 if ($sortfield && $sortorder) {
10075 $filearray =
dol_sort_array($filearray, $sortfield, $sortorder);
10078 foreach ($filearray as $key => $val) {
10080 $file = $val[
'name'];
10086 $viewfilename = $file;
10088 if ($size == 1 || $size ==
'small') {
10094 $pdirthumb = $pdir;
10095 $photo_vignette = basename($file);
10101 if ($nbbyrow > 0) {
10102 if ($nbphoto == 1) {
10103 $return .=
'<table class="valigntop center centpercent" style="border: 0; padding: 2px; border-spacing: 2px; border-collapse: separate;">';
10106 if ($nbphoto % $nbbyrow == 1) {
10107 $return .=
'<tr class="center valignmiddle" style="border: 1px">';
10109 $return .=
'<td style="width: '.ceil(100 / $nbbyrow).
'%" class="photo">'.
"\n";
10110 } elseif ($nbbyrow < 0) {
10111 $return .=
'<div class="inline-block">'.
"\n";
10114 $relativefile = preg_replace(
'/^\//',
'', $pdir.$photo);
10115 if (empty($nolink)) {
10117 if ($urladvanced) {
10118 $return .=
'<a href="'.$urladvanced.
'">';
10120 $return .=
'<a href="'.DOL_URL_ROOT.
'/viewimage.php?modulepart='.$modulepart.
'&entity='.$this->entity.
'&file='.urlencode($pdir.$photo).
'" class="aphoto" target="_blank" rel="noopener noreferrer">';
10126 $alt = $langs->transnoentitiesnoconv(
'File').
': '.$relativefile;
10127 $alt .=
' - '.$langs->transnoentitiesnoconv(
'Size').
': '.$imgarray[
'width'].
'x'.$imgarray[
'height'];
10128 if ($overwritetitle) {
10129 if (is_numeric($overwritetitle)) {
10132 $alt = $overwritetitle;
10135 if (empty($cache) && !empty($val[
'label'])) {
10138 $cache = $val[
'label'];
10140 if ($usesharelink) {
10141 if (array_key_exists(
'share', $val) && $val[
'share']) {
10142 if (empty($maxHeight) || ($photo_vignette && $imgarray[
'height'] > $maxHeight)) {
10143 $return .=
'<!-- Show original file (thumb not yet available with shared links) -->';
10144 $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).
'">';
10146 $return .=
'<!-- Show original file -->';
10147 $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).
'">';
10150 $return .=
'<!-- Show nophoto file (because file is not shared) -->';
10151 $return .=
'<img class="photo photowithmargin'.($addphotorefcss ?
' '.$addphotorefcss :
'').
'" height="'.$maxHeight.
'" src="'.DOL_URL_ROOT.
'/public/theme/common/nophoto.png" title="'.
dol_escape_htmltag($alt).
'">';
10154 if (empty($maxHeight) || ($photo_vignette && $imgarray[
'height'] > $maxHeight)) {
10155 $return .=
'<!-- Show thumb -->';
10156 $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).
'">';
10158 $return .=
'<!-- Show original file -->';
10159 $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).
'">';
10163 if (empty($nolink)) {
10167 if ($showfilename) {
10168 $return .=
'<br>'.$viewfilename;
10173 if ($photo_vignette && (
image_format_supported($photo) > 0) && ((isset($imgarray[
'width']) && $imgarray[
'width'] > $maxWidth) || (isset($imgarray[
'width']) && $imgarray[
'width'] > $maxHeight))) {
10174 $return .=
'<a href="'.$_SERVER[
"PHP_SELF"].
'?id='.$this->
id.
'&action=addthumb&token='.
newToken().
'&file='.urlencode($pdir.$viewfilename).
'">'.
img_picto($langs->trans(
'GenerateThumb'),
'refresh').
' </a>';
10177 if ($modulepart ==
'product' && ($user->hasRight(
'produit',
'creer') || $user->hasRight(
'service',
'creer'))) {
10179 $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> ';
10182 $return .=
'<a href="'.$_SERVER[
"PHP_SELF"].
'?id='.$this->
id.
'&action=delete&token='.
newToken().
'&file='.urlencode($pdir.$viewfilename).
'">';
10188 if ($nbbyrow > 0) {
10189 $return .=
'</td>';
10190 if (($nbphoto % $nbbyrow) == 0) {
10191 $return .=
'</tr>';
10193 } elseif ($nbbyrow < 0) {
10194 $return .=
'</div>'.
"\n";
10198 if (empty($size)) {
10199 $return .=
'<img class="photo photowithmargin" src="'.DOL_URL_ROOT.
'/viewimage.php?modulepart='.$modulepart.
'&entity='.$this->entity.
'&file='.urlencode($pdir.$photo).
'">';
10201 if ($showfilename) {
10202 $return .=
'<br>'.$viewfilename;
10206 if ($modulepart ==
'product' && ($user->hasRight(
'produit',
'creer') || $user->hasRight(
'service',
'creer'))) {
10208 $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> ';
10211 $return .=
'<a href="'.$_SERVER[
"PHP_SELF"].
'?id='.$this->
id.
'&action=delete&token='.
newToken().
'&file='.urlencode($pdir.$viewfilename).
'">';
10218 if ($nbmax && $nbphoto >= $nbmax) {
10224 if ($size == 1 || $size ==
'small') {
10225 if ($nbbyrow > 0) {
10227 while ($nbphoto % $nbbyrow) {
10228 $return .=
'<td style="width: '.ceil(100 / $nbbyrow).
'%"> </td>';
10233 $return .=
'</table>';
10239 $this->nbphoto = $nbphoto;
10253 if (is_array($info)) {
10254 if (isset($info[
'type']) && $info[
'type'] ==
'array') {
10271 if (isset($info[
'type']) && ($info[
'type'] ==
'date' || $info[
'type'] ==
'datetime' || $info[
'type'] ==
'timestamp')) {
10285 if (is_array($info)) {
10286 if (isset($info[
'type']) && ($info[
'type'] ==
'duration')) {
10304 if (is_array($info)) {
10305 if (isset($info[
'type']) && (preg_match(
'/(^int|int$)/i', $info[
'type']))) {
10323 if (is_array($info)) {
10324 if (isset($info[
'type']) && (preg_match(
'/^(double|real|price)/i', $info[
'type']))) {
10341 if (is_array($info)) {
10342 if (isset($info[
'type']) && $info[
'type'] ==
'text') {
10359 if (is_array($info)) {
10360 if (array_key_exists(
'notnull', $info) && $info[
'notnull'] !=
'1') {
10377 if (is_array($info)) {
10378 if (array_key_exists(
'notnull', $info) && $info[
'notnull'] ==
'-1') {
10395 if (is_array($info)) {
10396 if (array_key_exists(
'index', $info) && $info[
'index'] ==
true) {
10418 $queryarray = array();
10419 foreach ($this->fields as $field => $info) {
10421 if ($this->isDate($info)) {
10422 if (empty($this->{$field})) {
10423 $queryarray[$field] =
null;
10425 $queryarray[$field] = $this->db->idate($this->{$field});
10427 } elseif ($this->isDuration($info)) {
10429 if ((isset($this->{$field}) && $this->{$field} !=
'') || !empty($info[
'notnull'])) {
10430 if (!isset($this->{$field})) {
10431 if (!empty($info[
'default'])) {
10432 $queryarray[$field] = $info[
'default'];
10434 $queryarray[$field] = 0;
10437 $queryarray[$field] = (int) $this->{$field};
10440 $queryarray[$field] =
null;
10442 } elseif ($this->isInt($info) || $this->isFloat($info)) {
10443 if ($field ==
'entity' && is_null($this->{$field})) {
10444 $queryarray[$field] = ((int) $conf->entity);
10447 if ((isset($this->{$field}) && ((
string) $this->{$field}) !=
'') || !empty($info[
'notnull'])) {
10448 if (!isset($this->{$field})) {
10449 $queryarray[$field] = 0;
10450 } elseif ($this->isInt($info)) {
10451 $queryarray[$field] = (int) $this->{$field};
10452 } elseif ($this->isFloat($info)) {
10453 $queryarray[$field] = (float) $this->{$field};
10456 $queryarray[$field] =
null;
10462 $queryarray[$field] = $this->{$field};
10465 if (array_key_exists(
'type', $info) && $info[
'type'] ==
'timestamp' && empty($queryarray[$field])) {
10466 unset($queryarray[$field]);
10468 if (!empty($info[
'notnull']) && $info[
'notnull'] == -1 && empty($queryarray[$field])) {
10469 $queryarray[$field] =
null;
10473 return $queryarray;
10486 foreach ($this->fields as $field => $info) {
10487 if ($this->isDate($info)) {
10488 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') {
10489 $this->$field =
'';
10491 $this->$field = $db->jdate($obj->$field);
10493 } elseif ($this->isInt($info)) {
10494 if ($field ==
'rowid') {
10495 $this->
id = (int) $obj->$field;
10497 if ($this->isForcedToNullIfZero($info)) {
10498 if (empty($obj->$field)) {
10499 $this->$field =
null;
10501 $this->$field = (int) $obj->$field;
10504 if (isset($obj->$field) && (!is_null($obj->$field) || (array_key_exists(
'notnull', $info) && $info[
'notnull'] == 1))) {
10505 $this->$field = (int) $obj->$field;
10507 $this->$field =
null;
10511 } elseif ($this->isFloat($info)) {
10512 if ($this->isForcedToNullIfZero($info)) {
10513 if (empty($obj->$field)) {
10514 $this->$field =
null;
10516 $this->$field = (float) $obj->$field;
10519 if (isset($obj->$field) && (!is_null($obj->$field) || (array_key_exists(
'notnull', $info) && $info[
'notnull'] == 1))) {
10520 $this->$field = (float) $obj->$field;
10522 $this->$field =
null;
10526 $this->$field = isset($obj->$field) ? $obj->$field :
null;
10531 if (!isset($this->fields[
'ref']) && isset($this->
id)) {
10532 $this->
ref = (string) $this->
id;
10542 foreach ($this->fields as $field => $arr) {
10543 $this->$field =
null;
10556 $keys = array_keys($this->fields);
10557 if (!empty($alias)) {
10558 $keys_with_alias = array();
10559 foreach ($keys as $fieldname) {
10560 if (!empty($excludefields)) {
10561 if (in_array($fieldname, $excludefields)) {
10565 $keys_with_alias[] = $alias .
'.' . $fieldname;
10567 return implode(
', ', $keys_with_alias);
10569 return implode(
', ', $keys);
10580 protected function quote($value, $fieldsentry)
10582 if (is_null($value)) {
10584 } elseif (preg_match(
'/^(int|double|real|price)/i', $fieldsentry[
'type'])) {
10586 } elseif (preg_match(
'/int$/i', $fieldsentry[
'type'])) {
10587 return (
int) $value;
10588 } elseif ($fieldsentry[
'type'] ==
'boolean') {
10595 return "'".$this->db->escape($value).
"'";
10612 dol_syslog(get_class($this).
"::createCommon create", LOG_DEBUG);
10618 $fieldvalues = $this->setSaveQuery();
10622 if (array_key_exists(
'date_creation', $fieldvalues) && empty($fieldvalues[
'date_creation'])) {
10623 $fieldvalues[
'date_creation'] = $this->db->idate($now);
10624 $this->date_creation = $this->db->idate($now);
10627 if (array_key_exists(
'fk_user_creat', $fieldvalues) && !($fieldvalues[
'fk_user_creat'] > 0)) {
10628 $fieldvalues[
'fk_user_creat'] = $user->id;
10629 $this->fk_user_creat = $user->id;
10631 if (array_key_exists(
'user_creation_id', $fieldvalues) && !($fieldvalues[
'user_creation_id'] > 0)) {
10632 $fieldvalues[
'user_creation_id'] = $user->id;
10633 $this->user_creation_id = $user->id;
10635 if (array_key_exists(
'pass_crypted', $fieldvalues) && property_exists($this,
'pass')) {
10637 $tmparray =
dol_hash($this->pass,
'0', 0, 1);
10638 $fieldvalues[
'pass_crypted'] = $tmparray[
'pass_encrypted'];
10639 if (array_key_exists(
'pass_encoding', $fieldvalues) && property_exists($this,
'pass_encoding')) {
10640 $fieldvalues[
'pass_encoding'] = $tmparray[
'pass_encoding'];
10643 if (array_key_exists(
'ref', $fieldvalues)) {
10646 if (
getDolGlobalString(
'MAIN_DISABLE_AUTO_UPDATE_OF_TMS_FIELDS') && array_key_exists(
'tms', $fieldvalues)) {
10647 $fieldvalues[
'tms'] = $this->db->idate($now);
10650 unset($fieldvalues[
'rowid']);
10654 foreach ($fieldvalues as $k => $v) {
10656 $value = $this->fields[$k];
10658 $values[$k] = $this->quote($v, $value);
10662 foreach ($keys as $key) {
10663 if (!isset($this->fields[$key])) {
10666 $key_fields = $this->fields[$key];
10669 if (preg_match(
'/^integer:/i', $key_fields[
'type']) && $values[$key] ==
'-1') {
10670 $values[$key] =
'';
10672 if (!empty($key_fields[
'foreignkey']) && $values[$key] ==
'-1') {
10673 $values[$key] =
'';
10676 if (isset($key_fields[
'notnull']) && $key_fields[
'notnull'] == 1 && (!isset($values[$key]) || $values[$key] ===
'NULL') && (!isset($key_fields[
'default']) || is_null($key_fields[
'default']))) {
10679 if (empty($langs)) {
10680 require_once DOL_DOCUMENT_ROOT.
'/core/class/translate.class.php';
10682 $langs->setDefaultLang();
10683 $langs->load(
"errors");
10685 dol_syslog(
"Mandatory field '".$key.
"' is empty and required into ->fields definition of class");
10686 $this->errors[] = $langs->trans(
"ErrorFieldRequired", isset($key_fields[
'label']) ? $key_fields[
'label'] : $key);
10690 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'])) {
10691 $values[$key] = $this->quote($key_fields[
'default'], $key_fields);
10695 if (isset($key_fields[
'type']) && preg_match(
'/^integer:/i', $key_fields[
'type']) && empty($values[$key])) {
10696 if (isset($key_fields[
'default'])) {
10697 $values[$key] = ((int) $key_fields[
'default']);
10699 $values[$key] =
'null';
10702 if (!empty($key_fields[
'foreignkey']) && empty($values[$key])) {
10703 $values[$key] =
'null';
10711 $this->db->begin();
10714 $sql =
"INSERT INTO ".$this->db->prefix().$this->table_element;
10715 $sql .=
" (".implode(
", ", $keys).
')';
10716 $sql .=
" VALUES (".implode(
", ", $values).
")";
10718 $res = $this->db->query($sql);
10721 if ($this->db->lasterrno() ==
'DB_ERROR_RECORD_ALREADY_EXISTS') {
10722 $this->errors[] =
"ErrorRefAlreadyExists";
10724 $this->errors[] = $this->db->lasterror();
10730 $this->
id = $this->db->last_insert_id($this->db->prefix().$this->table_element);
10736 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)') {
10737 $sql =
"UPDATE ".$this->db->prefix().$this->table_element.
" SET ref = '(PROV".((int) $this->
id).
")' WHERE (ref = '(PROV)' OR ref = '') AND rowid = ".((int) $this->
id);
10738 $resqlupdate = $this->db->query($sql);
10740 if ($resqlupdate ===
false) {
10742 $this->errors[] = $this->db->lasterror();
10744 $this->
ref =
'(PROV'.$this->id.
')';
10751 $result = $this->insertExtraFields();
10758 if (!empty($this->table_element_line) && !empty($this->fk_element) && !empty($this->lines)) {
10759 foreach ($this->lines as $line) {
10760 $keyforparent = $this->fk_element;
10765 if (!is_object($line)) {
10766 $line = (object) $line;
10770 if (method_exists($line,
'insert')) {
10771 $result = $line->insert($user, 1);
10772 } elseif (method_exists($line,
'create')) {
10773 $result = $line->create($user, 1);
10776 $this->error = $line->error;
10777 $this->db->rollback();
10784 if (!$error && !$notrigger) {
10786 $result = $this->call_trigger(strtoupper(get_class($this)).
'_CREATE', $user);
10795 $this->db->rollback();
10798 $this->db->commit();
10815 if (empty(
$id) && empty($ref) && empty($morewhere)) {
10819 $fieldlist = $this->getFieldList(
't');
10820 if (empty($fieldlist)) {
10824 $sql =
"SELECT ".$fieldlist;
10825 $sql .=
" FROM ".$this->db->prefix().$this->table_element.
' as t';
10828 $sql .=
' WHERE t.rowid = '.((int)
$id);
10829 } elseif (!empty($ref)) {
10830 $sql .=
" WHERE t.ref = '".$this->db->escape($ref).
"'";
10832 $sql .=
' WHERE 1 = 1';
10834 if (empty(
$id) && isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
10835 $sql .=
' AND t.entity IN ('.getEntity($this->element).
')';
10838 $sql .= $morewhere;
10840 $sql .=
' LIMIT 1';
10842 $res = $this->db->query($sql);
10844 $obj = $this->db->fetch_object($res);
10846 $this->setVarsFromFetchObj($obj);
10850 if (empty($noextrafields)) {
10851 $result = $this->fetch_optionals();
10853 $this->error = $this->db->lasterror();
10854 $this->errors[] = $this->error;
10864 $this->error = $this->db->lasterror();
10865 $this->errors[] = $this->error;
10879 $objectlineclassname = get_class($this).
'Line';
10880 if (!class_exists($objectlineclassname)) {
10881 $this->error =
'Error, class '.$objectlineclassname.
' not found during call of fetchLinesCommon';
10885 $objectline =
new $objectlineclassname($this->db);
10886 '@phan-var-force CommonObjectLine $objectline';
10888 $sql =
"SELECT ".$objectline->getFieldList(
'l');
10889 $sql .=
" FROM ".$this->db->prefix().$objectline->table_element.
" as l";
10890 $sql .=
" WHERE l.fk_".$this->db->escape($this->element).
" = ".((int) $this->
id);
10892 $sql .= $morewhere;
10894 if (isset($objectline->fields[
'position'])) {
10895 $sql .= $this->db->order(
'position',
'ASC');
10898 $resql = $this->db->query($sql);
10900 $num_rows = $this->db->num_rows($resql);
10902 $this->lines = array();
10903 while ($i < $num_rows) {
10904 $obj = $this->db->fetch_object($resql);
10906 $newline =
new $objectlineclassname($this->db);
10907 '@phan-var-force CommonObjectLine $newline';
10908 $newline->setVarsFromFetchObj($obj);
10911 if (empty($noextrafields)) {
10912 $newline->fetch_optionals();
10915 $this->lines[] = $newline;
10922 $this->error = $this->db->lasterror();
10923 $this->errors[] = $this->error;
10937 dol_syslog(get_class($this).
"::updateCommon update", LOG_DEBUG);
10949 $fieldvalues = $this->setSaveQuery();
10953 if (array_key_exists(
'date_modification', $fieldvalues)) {
10954 $fieldvalues[
'date_modification'] = $this->db->idate($now);
10956 if (
getDolGlobalString(
'MAIN_DISABLE_AUTO_UPDATE_OF_TMS_FIELDS') && array_key_exists(
'tms', $fieldvalues)) {
10957 $fieldvalues[
'tms'] = $this->db->idate($now);
10959 if (array_key_exists(
'fk_user_modif', $fieldvalues)) {
10960 $fieldvalues[
'fk_user_modif'] = $user->id;
10962 if (array_key_exists(
'user_modification_id', $fieldvalues)) {
10963 $fieldvalues[
'user_modification_id'] = $user->id;
10966 if (array_key_exists(
'pass_crypted', $fieldvalues) && property_exists($this,
'pass') && !empty($this->pass)) {
10968 $tmparray =
dol_hash($this->pass,
'0', 0, 1);
10969 $fieldvalues[
'pass_crypted'] = $tmparray[
'pass_encrypted'];
10970 if (array_key_exists(
'pass_encoding', $fieldvalues) && property_exists($this,
'pass_encoding')) {
10971 $fieldvalues[
'pass_encoding'] = $tmparray[
'pass_encoding'];
10974 if (array_key_exists(
'ref', $fieldvalues)) {
10978 unset($fieldvalues[
'rowid']);
10984 foreach ($fieldvalues as $k => $v) {
10986 $value = $this->fields[$k];
10988 $values[$k] = $this->quote($v, $value);
10989 if (($value[
"type"] ==
"text") && !empty($value[
'arrayofkeyval']) && is_array($value[
'arrayofkeyval'])) {
10991 $v = preg_replace(
'/\s/',
',', $v);
10992 $v = preg_replace(
'/,+/',
',', $v);
10995 $tmp[] = $k.
'='.$this->quote($v, $this->fields[$k]);
10999 foreach ($keys as $key) {
11000 if (preg_match(
'/^integer:/i', $this->fields[$key][
'type']) && $values[$key] ==
'-1') {
11001 $values[$key] =
'';
11003 if (!empty($this->fields[$key][
'foreignkey']) && $values[$key] ==
'-1') {
11004 $values[$key] =
'';
11016 $sql =
'UPDATE '.$this->db->prefix().$this->table_element.
' SET '.implode(
', ', $tmp).
' WHERE rowid='.((int) $this->
id);
11018 $this->db->begin();
11021 $res = $this->db->query($sql);
11024 $this->errors[] = $this->db->lasterror();
11030 $result = $this->insertExtraFields();
11037 if (!$error && !$notrigger) {
11039 $result = $this->call_trigger(strtoupper(get_class($this)).
'_MODIFY', $user);
11048 $this->db->rollback();
11051 $this->db->commit();
11066 dol_syslog(get_class($this).
"::deleteCommon delete", LOG_DEBUG);
11070 $this->db->begin();
11072 if ($forcechilddeletion) {
11073 foreach ($this->childtables as $table) {
11074 $sql =
"DELETE FROM ".$this->db->prefix().$table.
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
11075 $resql = $this->db->query($sql);
11077 $this->error = $this->db->lasterror();
11078 $this->errors[] = $this->error;
11079 $this->db->rollback();
11083 } elseif (!empty($this->childtables)) {
11084 $objectisused = $this->isObjectUsed($this->
id);
11085 if (!empty($objectisused)) {
11086 dol_syslog(get_class($this).
"::deleteCommon Can't delete record as it has some child", LOG_WARNING);
11087 $this->error =
'ErrorRecordHasChildren';
11088 $this->errors[] = $this->error;
11089 $this->db->rollback();
11095 if (is_array($this->childtablesoncascade) && !empty($this->childtablesoncascade)) {
11096 foreach ($this->childtablesoncascade as $tabletodelete) {
11097 $deleteFromObject = explode(
':', $tabletodelete, 4);
11098 if (count($deleteFromObject) >= 2) {
11099 $className = str_replace(
'@',
'', $deleteFromObject[0]);
11100 $filePath = $deleteFromObject[1];
11101 $columnName = $deleteFromObject[2];
11103 if (!empty($deleteFromObject[3])) {
11104 $filter = $deleteFromObject[3];
11108 $childObject =
new $className($this->db);
11109 if (method_exists($childObject,
'deleteByParentField')) {
11110 '@phan-var-force CommonObject $childObject';
11111 $result = $childObject->deleteByParentField($this->
id, $columnName, $filter);
11114 $this->errors[] = $childObject->error;
11119 $this->errors[] =
"You defined a cascade delete on an object $className/$this->id but there is no method deleteByParentField for it";
11124 $this->errors[] =
'Cannot include child class file '.$filePath;
11129 $sql =
"DELETE FROM ".$this->db->prefix().$tabletodelete.
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
11131 $resql = $this->db->query($sql);
11134 $this->error = $this->db->lasterror();
11135 $this->errors[] = $this->error;
11145 $result = $this->call_trigger(strtoupper(get_class($this)).
'_DELETE', $user);
11155 $res = $this->deleteEcmFiles(1);
11164 require_once DOL_DOCUMENT_ROOT .
'/core/lib/files.lib.php';
11167 $this->errors[] =
'ErrorFailToDeleteDir';
11173 $res = $this->deleteObjectLinked();
11178 if (!$error && !empty($this->isextrafieldmanaged)) {
11179 $result = $this->deleteExtraFields();
11186 $sql =
'DELETE FROM '.$this->db->prefix().$this->table_element.
' WHERE rowid='.((int) $this->
id);
11188 $resql = $this->db->query($sql);
11191 $this->errors[] = $this->db->lasterror();
11197 $this->db->rollback();
11200 $this->db->commit();
11225 if (!empty($parentId) && !empty($parentField)) {
11226 if (empty($this->table_element)) {
11227 $this->error =
'Property table_element for object is not defined';
11228 $this->errors[] = $this->error;
11232 if (!method_exists($this,
'fetch')) {
11233 $this->error =
'Method fetch for object is not defined';
11234 $this->errors[] = $this->error;
11238 if (!method_exists($this,
'delete')) {
11239 $this->error =
'Method delete for object is not defined';
11240 $this->errors[] = $this->error;
11245 $this->db->begin();
11247 $sql =
"SELECT rowid FROM ".$this->db->prefix().$this->table_element;
11248 $sql .=
" WHERE ".$this->db->sanitize($parentField).
" = ".(int) $parentId;
11251 $errormessage =
'';
11253 if ($errormessage) {
11254 $this->errors[] = $errormessage;
11255 dol_syslog(__METHOD__.
' '.implode(
',', $this->errors), LOG_ERR);
11259 $resql = $this->db->query($sql);
11261 $this->errors[] = $this->db->lasterror();
11264 while ($obj = $this->db->fetch_object($resql)) {
11265 $result = $this->fetch($obj->rowid);
11268 $this->errors[] = $this->error;
11270 $result = $this->
delete($user);
11273 $this->errors[] = $this->error;
11281 if (empty($error)) {
11282 $this->db->commit();
11285 $this->error = implode(
', ', $this->errors);
11286 $this->db->rollback();
11287 return $error * -1;
11306 $tmpforobjectclass = get_class($this);
11307 $tmpforobjectlineclass = ucfirst($tmpforobjectclass).
'Line';
11309 $this->db->begin();
11312 $result = $this->call_trigger(
'LINE'.strtoupper($tmpforobjectclass).
'_DELETE', $user);
11318 if (empty($error)) {
11319 $sql =
"DELETE FROM ".$this->db->prefix().$this->table_element_line;
11320 $sql .=
" WHERE rowid = ".((int) $idline);
11322 $resql = $this->db->query($sql);
11324 $this->error =
"Error ".$this->db->lasterror();
11329 if (empty($error)) {
11331 $tmpobjectline =
new $tmpforobjectlineclass($this->db);
11332 '@phan-var-force CommonObjectLine $tmpobjectline';
11333 if (!isset($tmpobjectline->isextrafieldmanaged) || !empty($tmpobjectline->isextrafieldmanaged)) {
11334 $tmpobjectline->id = $idline;
11335 $result = $tmpobjectline->deleteExtraFields();
11338 $this->error =
"Error ".get_class($this).
"::deleteLineCommon deleteExtraFields error -4 ".$tmpobjectline->error;
11343 if (empty($error)) {
11344 $this->db->commit();
11347 dol_syslog(get_class($this).
"::deleteLineCommon ERROR:".$this->error, LOG_ERR);
11348 $this->db->rollback();
11368 $this->db->begin();
11370 $statusfield =
'status';
11371 if (in_array($this->element, array(
'don',
'donation',
'shipping',
'project_task'))) {
11372 $statusfield =
'fk_statut';
11375 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
11376 $sql .=
" SET ".$statusfield.
" = ".((int) $status);
11377 $sql .=
" WHERE rowid = ".((int) $this->
id);
11379 if ($this->db->query($sql)) {
11381 $this->oldcopy = clone $this;
11384 if (!$error && !$notrigger) {
11386 $result = $this->call_trigger($triggercode, $user);
11393 $this->
status = $status;
11394 if (property_exists($this,
'statut')) {
11395 $this->statut = $status;
11397 $this->db->commit();
11400 $this->db->rollback();
11404 $this->error = $this->db->error();
11405 $this->db->rollback();
11421 $this->specimen = 1;
11423 'label' =>
'This is label',
11424 'ref' =>
'ABCD1234',
11425 'description' =>
'This is a description',
11427 'note_public' =>
'Public note',
11428 'note_private' =>
'Private note',
11429 'date_creation' => (
dol_now() - 3600 * 48),
11430 'date_modification' => (
dol_now() - 3600 * 24),
11431 'fk_user_creat' => $user->id,
11432 'fk_user_modif' => $user->id,
11435 foreach ($fields as $key => $value) {
11436 if (array_key_exists($key, $this->fields)) {
11437 $this->{$key} = $value;
11442 if (property_exists($this,
'fields')) {
11443 foreach ($this->fields as $key => $value) {
11445 if (array_key_exists($key, $fields)) {
11449 if (!empty($value[
'default'])) {
11450 $this->$key = $value[
'default'];
11468 require_once DOL_DOCUMENT_ROOT.
'/core/class/comment.class.php';
11470 $comment =
new Comment($this->db);
11471 $result = $comment->fetchAllFor($this->element, $this->
id);
11473 $this->setErrorsFromObject($comment);
11476 $this->comments = $comment->comments;
11478 return count($this->comments);
11488 return count($this->comments);
11499 if (!is_array($parameters)) {
11502 foreach ($parameters as $parameter) {
11503 if (isset($this->$parameter)) {
11504 $this->$parameter = trim($this->$parameter);
11523 require_once DOL_DOCUMENT_ROOT.
'/categories/class/categorie.class.php';
11527 $existing =
$c->containing($this->
id, $type_categ,
'id');
11547 if (!is_array($categories)) {
11548 $categories = array($categories);
11551 dol_syslog(get_class($this).
"::setCategoriesCommon Object Id:".$this->
id.
' type_categ:'.$type_categ.
' nb tag add:'.count($categories), LOG_DEBUG);
11553 require_once DOL_DOCUMENT_ROOT.
'/categories/class/categorie.class.php';
11555 if (empty($type_categ)) {
11556 dol_syslog(__METHOD__.
': Type '.$type_categ.
'is an unknown category type. Done nothing.', LOG_ERR);
11562 $existing =
$c->containing($this->
id, $type_categ,
'id');
11565 if (!is_array($existing)) {
11566 $existing = array();
11568 if ($remove_existing) {
11570 $to_del = array_diff($existing, $categories);
11571 $to_add = array_diff($categories, $existing);
11574 $to_add = array_diff($categories, $existing);
11581 foreach ($to_del as $del) {
11582 if (
$c->fetch($del) > 0) {
11583 $result =
$c->del_type($this, $type_categ);
11586 $this->error =
$c->error;
11587 $this->errors =
$c->errors;
11594 foreach ($to_add as $add) {
11595 if (
$c->fetch($add) > 0) {
11596 $result =
$c->add_type($this, $type_categ);
11599 $this->error =
$c->error;
11600 $this->errors =
$c->errors;
11608 return $error ? (-1 * $error) : $ok;
11621 $this->db->begin();
11623 if (empty($type)) {
11624 $type = $this->table_element;
11627 require_once DOL_DOCUMENT_ROOT.
'/categories/class/categorie.class.php';
11628 $categorystatic =
new Categorie($this->db);
11630 $tablename = $this->db->prefix().
"categorie_".(empty($categorystatic->MAP_CAT_TABLE[$type]) ? $type : $categorystatic->MAP_CAT_TABLE[$type]);
11631 $fkname =
'fk_' . (empty($categorystatic->MAP_CAT_FK[$type]) ? $type : $categorystatic->MAP_CAT_FK[$type]);
11633 $sql =
"INSERT INTO ".$tablename.
" (fk_categorie, ".$fkname.
")";
11634 $sql .=
" SELECT fk_categorie, $toId FROM ".$tablename;
11635 $sql .=
" WHERE ".$fkname.
" = ".((int) $fromId);
11637 if (!$this->db->query($sql)) {
11638 $this->error = $this->db->lasterror();
11639 $this->db->rollback();
11643 $this->db->commit();
11657 $this->db->begin();
11661 switch ($this->element) {
11663 $element =
'propale';
11666 $element =
'produit';
11668 case 'order_supplier':
11669 $element =
'fournisseur/commande';
11671 case 'invoice_supplier':
11674 $element =
'fournisseur/facture/'.get_exdir($this->
id, 2, 0, 1, $this,
'invoice_supplier');
11677 $element =
'expedition/sending';
11680 case 'project_task':
11681 require_once DOL_DOCUMENT_ROOT.
'/projet/class/task.class.php';
11683 $project_result = $this->fetchProject();
11684 if ($project_result >= 0) {
11685 $element =
'projet/'.dol_sanitizeFileName($this->project->ref).
'/';
11689 $element =
'contract';
11692 $element = $this->element;
11694 '@phan-var-force string $element';
11697 $sql =
"DELETE FROM ".$this->db->prefix().
"ecm_files_extrafields WHERE fk_object IN (";
11698 $sql .=
" SELECT rowid FROM ".$this->db->prefix().
"ecm_files WHERE filename LIKE '".$this->db->escape($this->
ref).
"%'";
11699 $sql .=
" AND filepath = '".$this->db->escape($element).
"/".$this->db->escape($this->
ref).
"' AND entity = ".((int) $conf->entity);
11702 if (!$this->db->query($sql)) {
11703 $this->error = $this->db->lasterror();
11704 $this->db->rollback();
11709 $sql =
"DELETE FROM ".$this->db->prefix().
"ecm_files";
11710 $sql .=
" WHERE filename LIKE '".$this->db->escape($this->
ref).
"%'";
11711 $sql .=
" AND filepath = '".$this->db->escape($element).
"/".$this->db->escape($this->
ref).
"' AND entity = ".((int) $conf->entity);
11713 if (!$this->db->query($sql)) {
11714 $this->error = $this->db->lasterror();
11715 $this->db->rollback();
11722 $sql =
'DELETE FROM '.$this->db->prefix().
"ecm_files_extrafields";
11723 $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).
")";
11724 $resql = $this->db->query($sql);
11726 $this->error = $this->db->lasterror();
11727 $this->db->rollback();
11731 $sql =
'DELETE FROM '.$this->db->prefix().
"ecm_files";
11732 $sql .=
" WHERE src_object_type = '".$this->db->escape($this->table_element.(empty($this->module) ?
"" :
"@".$this->module)).
"' AND src_object_id = ".((int) $this->
id);
11733 $resql = $this->db->query($sql);
11735 $this->error = $this->db->lasterror();
11736 $this->db->rollback();
11741 $this->db->commit();
11758 include_once DOL_DOCUMENT_ROOT.
'/product/class/product.class.php';
11761 $tmpproduct =
new Product($this->db);
11762 foreach ($this->lines as $line) {
11763 if ($line->fk_product > 0) {
11764 $tmpproduct->fetch($line->fk_product);
11765 $statustotest = ($status ==
'onsale' ?
'status' :
'status_buy');
11766 if (!$tmpproduct->$statustotest) {
11767 $langs->load(
'products');
11768 $statuskey4lang = ($status ==
'onsale' ?
'ProductStatusNotOnSell' :
'ProductStatusNotOnBuy');
11770 $this->errors[] = $langs->trans(
'ProductRef').
' '.$tmpproduct->ref.
' '.$langs->trans($statuskey4lang);
11776 $this->error =
'ErrorOneLineContainsADisactivatedProduct';
11792 $this->error = $message;
11793 $this->errors[] = $message;
11805 $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.
commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams=null)
Common function for all objects extending CommonObject for generating documents.
liste_contact($statusoflink=-1, $source='external', $list=0, $code='', $status=-1, $arrayoftcids=array())
Get array of all contacts for an object.
fetchObjectFrom($table, $field, $key, $element=null)
Load object from specific field.
fetchProject()
Load the project with id $this->fk_project into this->project.
fetch_thirdparty($force_thirdparty_id=0)
Load the third party of object, from id $this->socid or $this->fk_soc, into this->thirdparty.
static deleteAllItemsLinkedByObjectID($fk_object_where, $field_where, $table_element)
Function used to remove all items linked to an object id in association table.
setFieldError($fieldKey, $msg='')
set validation error message a field
validateField($fields, $fieldKey, $fieldValue)
Return validation test result for a field.
getDataToShowPhoto($modulepart, $imagesize)
Function used to get the logos or photos of an object.
setMulticurrencyCode($code)
Change the multicurrency code.
emtpyObjectVars()
Sets all object fields to null.
fetch_projet()
Load the project with id $this->fk_project into this->project.
getIdContact($source, $code, $status=0)
Return id of contacts for a source and a contact code.
setExtraField($key, $value)
Convenience method for setting the value of an extrafield without actually updating it in the databas...
setDocModel($user, $modelpdf)
Set last model used by doc generator.
deleteObjectLinked($sourceid=null, $sourcetype='', $targetid=null, $targettype='', $rowid=0, $f_user=null, $notrigger=0)
Delete all links between an object $this.
getExtraField($key)
Convenience method for retrieving the value of an extrafield without actually fetching it from the da...
updateExtraField($key, $trigger=null, $userused=null)
Update 1 extra field value for the current object.
setPaymentTerms($id, $deposit_percent=null)
Change the payments terms.
isFloat($info)
Function test if type is float.
setBankAccount($fk_account, $notrigger=0, $userused=null)
Change the bank account.
setExtraParameters()
Set extra parameters.
delete_resource($rowid, $element='', $notrigger=0)
Delete a link to resource line.
setErrorsFromObject($object)
setErrorsFromObject
setShippingMethod($shipping_method_id, $notrigger=0, $userused=null)
Change the shipping method.
update_note_public($note)
Update public note (kept for backward compatibility)
getSpecialCode($lineid)
Get special code of a line.
clearObjectLinkedCache()
Clear the cache saying that all linked object were already loaded.
update_ref_ext($ref_ext)
Update external ref of element.
fetchOneLike($ref)
Looks for an object with ref matching the wildcard provided It does only work when $this->table_ref_f...
hasProductsOrServices($predefined=-1)
Function to say how many lines object contains.
static isExistingObject($element, $id, $ref='', $ref_ext='')
Check if an object id or ref exists If you don't need or want to instantiate the object and just need...
isObjectUsed($id=0, $entity=0)
Function to check if an object is used by others (by children).
updateRangOfLine($rowid, $rang)
Update position of line (rang)
getDefaultCreateValueFor($fieldname, $alternatevalue=null, $type='alphanohtml')
Return the default value to use for a field when showing the create form of object.
add_element_resource($resource_id, $resource_type, $busy=0, $mandatory=0, $notrigger=0)
Add resources to the current object : add entry into llx_element_resources Need $this->element & $thi...
checkActiveProductInLines($status='onsale')
Check if all products have the right status (on sale, on buy) called during validation of propal,...
createCommon(User $user, $notrigger=0)
Create object in the database.
getTotalWeightVolume()
Return into unit=0, the calculated total of weight and volume of all lines * qty Calculate by adding ...
update_note($note, $suffix='', $notrigger=0)
Update note of element.
getFullAddress($withcountry=0, $sep="\n", $withregion=0, $extralangcode='')
Return full address of contact.
fetch_project()
Load the project with id $this->fk_project into this->project.
getFieldList($alias='', $excludefields=array())
Function to concat keys of fields.
getNbComments()
Return nb comments already posted.
setVarsFromFetchObj(&$obj)
Function to load data from a SQL pointer into properties of current object $this.
printObjectLines($action, $seller, $buyer, $selected=0, $dateSelector=0, $defaulttpldir='/core/tpl')
Return HTML table for object lines TODO Move this into an output class file (htmlline....
getChildrenOfLine($id, $includealltree=0)
Get children of line.
updateCommon(User $user, $notrigger=0)
Update object into database.
updateExtraLanguages($key, $trigger=null, $userused=null)
Update an extra language value for the current object.
deleteExtraFields()
Delete all extra fields values for the current object.
setStatusCommon($user, $status, $notrigger=0, $triggercode='')
Set to a status.
deprecatedProperties()
Provide list of deprecated properties and replacements.
setSaveQuery()
Function to return the array of data key-value from the ->fields and all the ->properties of an objec...
setValuesForExtraLanguages($onlykey='')
Fill array_options property of object by extrafields value (using for data sent by forms) Used for ex...
insertExtraLanguages($trigger='', $userused=null)
Add/Update all extra languages values for the current object.
setTransportMode($id)
Change the transport mode methods.
isArray($info)
Function test if type is array.
isInt($info)
Function test if type is integer.
fetchObjectLinked($sourceid=null, $sourcetype='', $targetid=null, $targettype='', $clause='OR', $alsosametype=1, $orderby='sourcetype', $loadalsoobjects=1)
Fetch array of objects linked to current object (object of enabled modules only).
delete_contact($rowid, $notrigger=0)
Delete a link to contact line.
updateLineUp($rowid, $rang)
Update position of line up (rang)
fetch_user($userid)
Load the user with id $userid into this->user.
errorsToString()
Method to output saved errors.
getListContactId($source='external')
Return list of id of contacts of object.
setWarehouse($warehouse_id)
Change the warehouse.
setDeliveryAddress($id)
Define delivery address.
fetchBarCode()
Load data for barcode into properties ->barcode_type* Properties ->barcode_type that is id of barcode...
getTotalDiscount()
Function that returns the total amount HT of discounts applied for all lines.
initAsSpecimenCommon()
Initialise object with example values Id must be 0 if object instance is a specimen.
printObjectLine($action, $line, $var, $num, $i, $dateSelector, $seller, $buyer, $selected=0, $extrafields=null, $defaulttpldir='/core/tpl')
Return HTML content of a detail line TODO Move this into an output class file (htmlline....
copy_linked_contact($objFrom, $source='internal')
Copy contact from one element to current.
static commonReplaceThirdparty(DoliDB $dbs, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
Function used to replace a thirdparty id with another one.
getValueFrom($table, $id, $field)
Getter generic.
trimParameters($parameters)
Trim object parameters.
fetch_product()
Load the product with id $this->fk_product into this->product.
isIndex($info)
Function test if is indexed.
quote($value, $fieldsentry)
Add quote to field value if necessary.
formAddObjectLine($dateSelector, $seller, $buyer, $defaulttpldir='/core/tpl')
Show add free and predefined products/services form.
fetchComments()
Load comments linked with current task.
line_down($rowid, $fk_parent_line=true)
Update a line to have a higher rank.
setValueFrom($field, $value, $table='', $id=null, $format='', $id_field='', $fuser=null, $trigkey='', $fk_user_field='fk_user_modif')
Setter generic.
fetch_contact($contactid=null)
Load object contact with id=$this->contact_id into $this->contact.
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...
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, ....
dol_print_email($email, $contactid=0, $socid=0, $addlink=0, $max=0, $showinvalid=1, $withpicto=0, $morecss='paddingrightonly')
Show EMail link formatted for HTML output.
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.