44require_once DOL_DOCUMENT_ROOT.
'/core/class/doldeprecationhandler.class.php';
53 use DolDeprecationHandler;
55 const TRIGGER_PREFIX =
'';
91 public $errors = array();
96 private $validateFieldsErrors = array();
114 public $element_for_permission;
119 public $table_element;
124 public $table_element_line =
'';
130 public $ismultientitymanaged;
140 public $array_options = array();
146 public $fields = array();
153 public $array_languages =
null;
158 public $contacts_ids;
163 public $contacts_ids_internal;
168 public $linked_objects;
173 public $linkedObjectsIds;
178 public $linkedObjects;
183 private $linkedObjectsFullLoaded = array();
198 protected $table_ref_field =
'';
203 public $restrictiononfksoc = 0;
212 public $context = array();
324 private $commandeFournisseur;
340 public $ref_previous;
386 public $country_code;
429 public $barcode_type;
435 public $barcode_type_code;
441 public $barcode_type_label;
447 public $barcode_type_coder;
453 public $mode_reglement_id;
459 public $cond_reglement_id;
464 public $demand_reason_id;
470 public $transport_mode_id;
479 private $cond_reglement;
483 protected $depr_cond_reglement;
490 public $fk_delivery_address;
496 public $shipping_method_id;
502 public $shipping_method;
508 public $fk_multicurrency;
514 public $multicurrency_code;
520 public $multicurrency_tx;
525 public $multicurrency_total_ht;
530 public $multicurrency_total_tva;
535 public $multicurrency_total_localtax1;
540 public $multicurrency_total_localtax2;
545 public $multicurrency_total_ttc;
558 public $last_main_doc;
583 public $note_private;
608 public $total_localtax1;
614 public $total_localtax2;
631 public $actiontypecode;
637 public $comments = array();
663 public $civility_code;
669 public $date_creation;
674 public $date_validation;
679 public $date_modification;
693 private $date_update;
698 public $date_cloture;
710 public $user_creation;
715 public $user_creation_id;
727 public $user_validation;
732 public $user_validation_id;
737 public $user_closing_id;
743 public $user_modification;
748 public $user_modification_id;
754 public $fk_user_creat;
760 public $fk_user_modif;
766 public $next_prev_filter;
771 public $specimen = 0;
793 public $labelStatus = array();
798 public $labelStatusShort = array();
809 public $showphoto_on_popup;
814 public $nb = array();
829 public $extraparams = array();
834 protected $childtables = array();
841 protected $childtablesoncascade = array();
851 public $cond_reglement_supplier_id;
858 public $deposit_percent;
864 public $retained_warranty_fk_cond_reglement;
869 public $warehouse_id;
874 public $isextrafieldmanaged = 0;
887 'alreadypaid' =>
'totalpaid',
888 'cond_reglement' =>
'depr_cond_reglement',
890 'commandeFournisseur' =>
'origin_object',
891 'expedition' =>
'origin_object',
892 'fk_project' =>
'fk_project',
893 'livraison' =>
'origin_object',
894 'projet' =>
'project',
895 'statut' =>
'status',
914 $sql =
"SELECT rowid";
915 $sql .=
" FROM ".$db->prefix().$element;
916 $sql .=
" WHERE entity IN (".getEntity($element).
")";
919 $sql .=
" AND rowid = ".((int) $id);
921 $sql .=
" AND ref = '".$db->escape($ref).
"'";
922 } elseif ($ref_ext) {
923 $sql .=
" AND ref_ext = '".$db->escape($ref_ext).
"'";
925 $error =
'ErrorWrongParameters';
926 dol_syslog(get_class().
"::isExistingObject ".$error, LOG_ERR);
929 if ($ref || $ref_ext) {
930 $sql .=
" AND entity = ".((int)
$conf->entity);
933 dol_syslog(get_class().
"::isExistingObject", LOG_DEBUG);
934 $resql = $db->query($sql);
936 $num = $db->num_rows($resql);
953 return (empty($this->
id));
968 $this->errors = array_merge($this->errors,
$object->errors);
993 global $action, $extrafields, $langs, $hookmanager;
996 $MAX_EXTRAFIELDS_TO_SHOW_IN_TOOLTIP =
getDolGlobalInt(
'MAX_EXTRAFIELDS_TO_SHOW_IN_TOOLTIP', 3);
1002 if (!empty($extrafields->attributes[$this->table_element][
'label'])) {
1003 $data[
'opendivextra'] =
'<div class="centpercent wordbreak divtooltipextra">';
1004 foreach ($extrafields->attributes[$this->table_element][
'label'] as $key => $val) {
1005 if ($extrafields->attributes[$this->table_element][
'type'][$key] ==
'separate') {
1008 if ($count >= abs($MAX_EXTRAFIELDS_TO_SHOW_IN_TOOLTIP)) {
1009 $data[
'more_extrafields'] =
'<br>...';
1013 if ($enabled && isset($extrafields->attributes[$this->table_element][
'enabled'][$key])) {
1014 $enabled = (int)
dol_eval((
string) $extrafields->attributes[$this->table_element][
'enabled'][$key], 1, 1,
'2');
1016 if ($enabled && isset($extrafields->attributes[$this->table_element][
'list'][$key])) {
1017 $enabled = (int)
dol_eval((
string) $extrafields->attributes[$this->table_element][
'list'][$key], 1, 1,
'2');
1020 if ($perms && isset($extrafields->attributes[$this->table_element][
'perms'][$key])) {
1021 $perms = (int)
dol_eval((
string) $extrafields->attributes[$this->table_element][
'perms'][$key], 1, 1,
'2');
1023 if (empty($enabled)) {
1026 if (abs($enabled) != 1 && abs($enabled) != 3 && abs($enabled) != 5 && abs($enabled) != 4) {
1029 if (empty($perms)) {
1032 if (!empty($extrafields->attributes[$this->table_element][
'langfile'][$key])) {
1033 $langs->load($extrafields->attributes[$this->table_element][
'langfile'][$key]);
1035 $labelextra = $langs->trans((
string) $extrafields->attributes[$this->table_element][
'label'][$key]);
1036 if ($extrafields->attributes[$this->table_element][
'type'][$key] ==
'separate') {
1037 $data[$key] =
'<br><b><u>'. $labelextra .
'</u></b>';
1039 $value = (empty($this->array_options[
'options_' . $key]) ?
'' : $this->array_options[
'options_' . $key]);
1040 $data[$key] =
'<br><b>'. $labelextra .
':</b> ' . $extrafields->showOutputField($key, $value,
'', $this->table_element);
1044 $data[
'closedivextra'] =
'</div>';
1047 $hookmanager->initHooks(array($this->element .
'dao'));
1048 $parameters = array(
1049 'tooltipcontentarray' => &$data,
1050 'params' => $params,
1053 $hookmanager->executeHooks(
'getTooltipContent', $parameters, $this, $action);
1056 $label = implode($data);
1069 return $this->error.(is_array($this->errors) ? (($this->error !=
'' ?
', ' :
'').implode(
', ', $this->errors)) :
'');
1081 global $hookmanager;
1083 $parameters = array(
'objref' => $objref);
1085 $reshook = $hookmanager->executeHooks(
'getFormatedCustomerRef', $parameters, $this, $action);
1087 return $hookmanager->resArray[
'objref'];
1089 return $objref.(isset($hookmanager->resArray[
'objref']) ? $hookmanager->resArray[
'objref'] :
'');
1100 global $hookmanager;
1102 $parameters = array(
'objref' => $objref);
1104 $reshook = $hookmanager->executeHooks(
'getFormatedSupplierRef', $parameters, $this, $action);
1106 return $hookmanager->resArray[
'objref'];
1108 return $objref.(isset($hookmanager->resArray[
'objref']) ? $hookmanager->resArray[
'objref'] :
'');
1120 public function getFullAddress($withcountry = 0, $sep =
"\n", $withregion = 0, $extralangcode =
'')
1122 if ($withcountry && $this->country_id && (empty($this->country_code) || empty($this->country))) {
1123 require_once DOL_DOCUMENT_ROOT.
'/core/lib/company.lib.php';
1124 $tmparray =
getCountry($this->country_id,
'all');
1125 $this->country_code = $tmparray[
'code'];
1126 $this->country = $tmparray[
'label'];
1129 if ($withregion && $this->state_id && (empty($this->state_code) || empty($this->state) || empty($this->region) || empty($this->region_code))) {
1130 require_once DOL_DOCUMENT_ROOT.
'/core/lib/company.lib.php';
1131 $tmparray =
getState($this->state_id,
'all',
null, 1);
1132 $this->state_code = $tmparray[
'code'];
1133 $this->state = $tmparray[
'label'];
1134 $this->region_code = $tmparray[
'region_code'];
1135 $this->region = $tmparray[
'region'];
1154 if (empty($this->last_main_doc)) {
1158 include_once DOL_DOCUMENT_ROOT.
'/ecm/class/ecmfiles.class.php';
1159 $ecmfile =
new EcmFiles($this->db);
1160 $result = $ecmfile->fetch(0,
'', $this->last_main_doc);
1162 $this->error = $ecmfile->error;
1163 $this->errors = $ecmfile->errors;
1167 if (empty($ecmfile->id)) {
1169 if ($initsharekey) {
1170 require_once DOL_DOCUMENT_ROOT.
'/core/lib/security2.lib.php';
1192 } elseif (empty($ecmfile->share)) {
1194 if ($initsharekey) {
1195 require_once DOL_DOCUMENT_ROOT.
'/core/lib/security2.lib.php';
1197 $ecmfile->update($user);
1203 $urlwithouturlroot = preg_replace(
'/'.preg_quote(DOL_URL_ROOT,
'/').
'$/i',
'', trim(
$dolibarr_main_url_root));
1207 $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT;
1216 if (!empty($ecmfile->share)) {
1217 $paramlink .= ($paramlink ?
'&' :
'').
'hashp='.$ecmfile->share;
1219 if ($forcedownload) {
1220 $paramlink .= ($paramlink ?
'&' :
'').
'attachment=1';
1223 if ($relativelink) {
1224 $linktoreturn =
'document.php'.($paramlink ?
'?'.$paramlink :
'');
1226 $linktoreturn = $urlwithroot.
'/document.php'.($paramlink ?
'?'.$paramlink :
'');
1230 return $linktoreturn;
1244 public function add_contact($fk_socpeople, $type_contact, $source =
'external', $notrigger = 0)
1247 global $user, $langs;
1249 dol_syslog(get_class($this).
"::add_contact $fk_socpeople, $type_contact, $source, $notrigger");
1252 if ($fk_socpeople <= 0) {
1253 $langs->load(
"errors");
1254 $this->error = $langs->trans(
"ErrorWrongValueForParameterX",
"1");
1255 dol_syslog(get_class($this).
"::add_contact ".$this->error, LOG_ERR);
1258 if (!$type_contact) {
1259 $langs->load(
"errors");
1260 $this->error = $langs->trans(
"ErrorWrongValueForParameterX",
"2");
1261 dol_syslog(get_class($this).
"::add_contact ".$this->error, LOG_ERR);
1265 if ($this->restrictiononfksoc && property_exists($this,
'socid') && !empty($this->socid) && !$user->hasRight(
'societe',
'client',
'voir')) {
1266 $sql_allowed_contacts =
'SELECT COUNT(*) as cnt FROM '.$this->db->prefix().
'societe_commerciaux as sc';
1267 $sql_allowed_contacts.=
' WHERE sc.fk_soc = '.(int) $this->socid;
1268 $sql_allowed_contacts.=
' AND sc.fk_user = '.(int) $user->id;
1270 $resql_allowed_contacts = $this->db->query($sql_allowed_contacts);
1272 if (!$resql_allowed_contacts) {
1273 $this->errors[] = $this->db->lasterror();
1275 } elseif ($obj = $this->db->fetch_object($resql_allowed_contacts)) {
1276 if ($obj->cnt == 0) {
1277 $langs->load(
"companies");
1278 $this->error = $langs->trans(
"ErrorCommercialNotAllowedForThirdparty", $user->id);
1279 dol_syslog(get_class($this).
"::add_contact ".$this->error, LOG_ERR);
1285 $id_type_contact = 0;
1286 if (is_numeric($type_contact)) {
1287 $id_type_contact = $type_contact;
1290 $sql =
"SELECT tc.rowid";
1291 $sql .=
" FROM ".$this->db->prefix().
"c_type_contact as tc";
1292 $sql .=
" WHERE tc.element='".$this->db->escape($this->element).
"'";
1293 $sql .=
" AND tc.source='".$this->db->escape($source).
"'";
1294 $sql .=
" AND tc.code='".$this->db->escape($type_contact).
"' AND tc.active=1";
1296 $resql = $this->db->query($sql);
1298 $obj = $this->db->fetch_object($resql);
1300 $id_type_contact = $obj->rowid;
1304 if ($id_type_contact == 0) {
1305 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");
1313 $already_added =
false;
1314 if (is_array($TListeContacts) && !empty($TListeContacts)) {
1315 foreach ($TListeContacts as $array_contact) {
1316 if ($array_contact[
'status'] == 4 && $array_contact[
'id'] == $fk_socpeople && $array_contact[
'fk_c_type_contact'] == $id_type_contact) {
1317 $already_added =
true;
1323 if (!$already_added) {
1327 $sql =
"INSERT INTO ".$this->db->prefix().
"element_contact";
1328 $sql .=
" (element_id, fk_socpeople, datecreate, statut, fk_c_type_contact) ";
1329 $sql .=
" VALUES (".$this->id.
", ".((int) $fk_socpeople).
" , ";
1330 $sql .=
"'".$this->db->idate($datecreate).
"'";
1331 $sql .=
", 4, ".((int) $id_type_contact);
1334 $resql = $this->db->query($sql);
1337 $result = $this->
call_trigger(strtoupper($this->element).
'_ADD_CONTACT', $user);
1339 $this->db->rollback();
1344 $this->db->commit();
1347 if ($this->db->errno() ==
'DB_ERROR_RECORD_ALREADY_EXISTS') {
1348 $this->error = $this->db->errno();
1349 $this->db->rollback();
1352 $this->error = $this->db->lasterror();
1353 $this->db->rollback();
1373 $contacts = $objFrom->liste_contact(-1, $source);
1374 foreach ($contacts as $contact) {
1375 if ($this->
add_contact($contact[
'id'], $contact[
'fk_c_type_contact'], $contact[
'source']) < 0) {
1392 public function update_contact($rowid, $statut, $type_contact_id = 0, $fk_socpeople = 0)
1396 $sql =
"UPDATE ".$this->db->prefix().
"element_contact set";
1397 $sql .=
" statut = ".((int) $statut);
1398 if ($type_contact_id) {
1399 $sql .=
", fk_c_type_contact = ".((int) $type_contact_id);
1401 if ($fk_socpeople) {
1402 $sql .=
", fk_socpeople = ".((int) $fk_socpeople);
1404 $sql .=
" where rowid = ".((int) $rowid);
1406 $resql = $this->db->query($sql);
1410 $this->error = $this->db->lasterror();
1431 if ($this->
id > 0) {
1432 $sql =
"SELECT ec.rowid FROM ".$this->db->prefix().
"element_contact as ec, ".$this->db->prefix().
"c_type_contact as tc";
1433 $sql .=
" WHERE ec.rowid = ".((int) $rowid).
" AND ec.element_id = ".((int) $this->
id);
1434 $sql .=
" AND ec.fk_c_type_contact = tc.rowid AND tc.element = '".$this->db->escape($this->element).
"'";
1435 $resql = $this->db->query($sql);
1436 if (!$resql || !$this->db->num_rows($resql)) {
1437 $this->error =
'ErrorRecordNotFound';
1444 if (!$error && empty($notrigger)) {
1446 $this->context[
'contact_id'] = ((int) $rowid);
1447 $result = $this->
call_trigger(strtoupper($this->element).
'_DELETE_CONTACT', $user);
1455 dol_syslog(get_class($this).
"::delete_contact", LOG_DEBUG);
1457 $sql =
"DELETE FROM ".MAIN_DB_PREFIX.
"element_contact";
1458 $sql .=
" WHERE rowid = ".((int) $rowid);
1460 $result = $this->db->query($sql);
1463 $this->errors[] = $this->db->lasterror();
1468 $this->db->commit();
1471 $this->error = $this->db->lasterror();
1472 $this->db->rollback();
1492 if (!empty($typeContact)) {
1493 foreach ($typeContact as $key => $value) {
1494 array_push($temp, $key);
1496 $listId = implode(
",", $temp);
1501 if (empty($listId)) {
1505 $sql =
"DELETE FROM ".$this->db->prefix().
"element_contact";
1506 $sql .=
" WHERE element_id = ".((int) $this->
id);
1507 $sql .=
" AND fk_c_type_contact IN (".$this->db->sanitize($listId).
")";
1509 dol_syslog(get_class($this).
"::delete_linked_contact", LOG_DEBUG);
1510 if ($this->db->query($sql)) {
1513 $this->error = $this->db->lasterror();
1530 public function liste_contact($statusoflink = -1, $source =
'external', $list = 0, $code =
'', $status = -1, $arrayoftcids = array())
1537 $sql =
"SELECT ec.rowid, ec.statut as statuslink, ec.fk_socpeople as id, ec.fk_c_type_contact";
1538 if ($source ==
'internal') {
1539 $sql .=
", '-1' as socid, t.statut as statuscontact, t.login, t.photo, t.gender, t.fk_country as country_id";
1541 if ($source ==
'external' || $source ==
'thirdparty') {
1542 $sql .=
", t.fk_soc as socid, t.statut as statuscontact, t.fk_pays as country_id";
1544 $sql .=
", t.civility as civility, t.lastname as lastname, t.firstname, t.email, t.address, t.zip, t.town";
1545 if (empty($arrayoftcids)) {
1546 $sql .=
", tc.source, tc.element, tc.code, tc.libelle as type_label, co.label as country";
1549 if (empty($arrayoftcids)) {
1550 $sql .=
" ".$this->db->prefix().
"c_type_contact as tc,";
1552 $sql .=
" ".$this->db->prefix().
"element_contact as ec";
1553 if ($source ==
'internal') {
1554 $sql .=
" LEFT JOIN ".$this->db->prefix().
"user as t on ec.fk_socpeople = t.rowid";
1555 $sql .=
" LEFT JOIN ".$this->db->prefix().
"c_country as co ON co.rowid = t.fk_country";
1557 if ($source ==
'external' || $source ==
'thirdparty') {
1558 $sql .=
" LEFT JOIN ".$this->db->prefix().
"socpeople as t on ec.fk_socpeople = t.rowid";
1559 $sql .=
" LEFT JOIN ".$this->db->prefix().
"c_country as co ON co.rowid = t.fk_pays";
1561 $sql .=
" WHERE ec.element_id = ".((int) $this->
id);
1562 if (empty($arrayoftcids)) {
1563 $sql .=
" AND ec.fk_c_type_contact = tc.rowid";
1564 $sql .=
" AND tc.element = '".$this->db->escape($this->element).
"'";
1566 $sql .=
" AND tc.code = '".$this->db->escape($code).
"'";
1568 if ($source ==
'internal') {
1569 $sql .=
" AND tc.source = 'internal'";
1571 if ($source ==
'external' || $source ==
'thirdparty') {
1572 $sql .=
" AND tc.source = 'external'";
1574 $sql .=
" AND tc.active = 1";
1576 $sql .=
" AND ec.fk_c_type_contact IN (".$this->db->sanitize(implode(
',', $arrayoftcids)).
")";
1579 $sql .=
" AND t.statut = ".((int) $status);
1581 if ($statusoflink >= 0) {
1582 $sql .=
" AND ec.statut = ".((int) $statusoflink);
1584 $sql .=
" ORDER BY t.lastname ASC";
1586 dol_syslog(get_class($this).
"::liste_contact", LOG_DEBUG);
1587 $resql = $this->db->query($sql);
1589 $num = $this->db->num_rows($resql);
1592 $obj = $this->db->fetch_object($resql);
1595 $transkey =
"TypeContact_".$obj->element.
"_".$obj->source.
"_".$obj->code;
1596 $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->type_label);
1598 'parentId' => $this->
id,
1599 'source' => $obj->source,
1600 'socid' => $obj->socid,
1602 'nom' => $obj->lastname,
1603 'civility' => $obj->civility,
1604 'lastname' => $obj->lastname,
1605 'firstname' => $obj->firstname,
1606 'email' => $obj->email,
1607 'address' => $obj->address,
1609 'town' => $obj->town,
1610 'country_id' => $obj->country_id,
1611 'country' => $obj->country,
1612 'login' => (empty($obj->login) ?
'' : $obj->login),
1613 'photo' => (empty($obj->photo) ?
'' : $obj->photo),
1614 'gender' => (empty($obj->gender) ?
'' : $obj->gender),
1615 'statuscontact' => $obj->statuscontact,
1616 'rowid' => $obj->rowid,
1617 'code' => $obj->code,
1618 'libelle' => $libelle_type,
1619 'status' => (
int) $obj->statuslink,
1620 'fk_c_type_contact' => $obj->fk_c_type_contact
1623 $tab[$i] = $obj->id;
1631 $this->error = $this->db->lasterror();
1646 $sql =
"SELECT ec.datecreate, ec.statut, ec.fk_socpeople, ec.fk_c_type_contact,";
1647 $sql .=
" tc.code, tc.libelle as type_label";
1648 $sql .=
" FROM (".$this->db->prefix().
"element_contact as ec, ".$this->db->prefix().
"c_type_contact as tc)";
1649 $sql .=
" WHERE ec.rowid =".((int) $rowid);
1650 $sql .=
" AND ec.fk_c_type_contact = tc.rowid";
1651 $sql .=
" AND tc.element = '".$this->db->escape($this->element).
"'";
1653 dol_syslog(get_class($this).
"::swapContactStatus", LOG_DEBUG);
1654 $resql = $this->db->query($sql);
1656 $obj = $this->db->fetch_object($resql);
1657 $newstatut = ($obj->statut == 4) ? 5 : 4;
1659 $this->db->free($resql);
1662 $this->error = $this->db->error();
1679 public function liste_type_contact($source =
'internal', $order =
'position', $option = 0, $activeonly = 0, $code =
'')
1684 if (empty($order)) {
1685 $order =
'position';
1687 if ($order ==
'position') {
1693 $sql =
"SELECT DISTINCT tc.rowid, tc.code, tc.libelle as type_label, tc.position";
1694 $sql .=
" FROM ".$this->db->prefix().
"c_type_contact as tc";
1695 $sql .=
" WHERE tc.element = '".$this->db->escape($this->element).
"'";
1696 if ($activeonly == 1) {
1697 $sql .=
" AND tc.active = 1";
1699 if (!empty($source) && $source !=
'all') {
1700 $sql .=
" AND tc.source = '".$this->db->escape($source).
"'";
1702 if (!empty($code)) {
1703 $sql .=
" AND tc.code = '".$this->db->escape($code).
"'";
1705 $sql .= $this->db->order($order,
'ASC');
1708 $resql = $this->db->query($sql);
1710 $this->error = $this->db->lasterror();
1715 $num = $this->db->num_rows($resql);
1718 $obj = $this->db->fetch_object($resql);
1720 $transkey =
"TypeContact_".$this->element.
"_".$source.
"_".$obj->code;
1721 $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $langs->trans($obj->type_label));
1722 if (empty($option)) {
1723 $tab[$obj->rowid] = $libelle_type;
1724 } elseif ($option == 1) {
1725 $tab[$obj->code] = $libelle_type;
1727 $tab[$obj->rowid] = array(
'id' => $obj->rowid,
'code' => $obj->code,
'label' => $libelle_type);
1746 public function listeTypeContacts($source =
'internal', $option = 0, $activeonly = 0, $code =
'', $element =
'', $excludeelement =
'')
1750 $langs->loadLangs(array(
'bills',
'contracts',
'interventions',
'orders',
'projects',
'propal',
'ticket',
'agenda'));
1754 $sql =
"SELECT DISTINCT tc.rowid, tc.code, tc.libelle as type_label, tc.position, tc.element, tc.module";
1755 $sql .=
" FROM ".$this->db->prefix().
"c_type_contact as tc";
1757 $sqlWhere = array();
1758 if (!empty($element)) {
1759 $sqlWhere[] =
" tc.element='".$this->db->escape($element).
"'";
1761 if (!empty($excludeelement)) {
1762 $sqlWhere[] =
" tc.element <> '".$this->db->escape($excludeelement).
"'";
1765 if ($activeonly == 1) {
1766 $sqlWhere[] =
" tc.active=1";
1769 if (!empty($source) && $source !=
'all') {
1770 $sqlWhere[] =
" tc.source='".$this->db->escape($source).
"'";
1773 if (!empty($code)) {
1774 $sqlWhere[] =
" tc.code='".$this->db->escape($code).
"'";
1777 if (count($sqlWhere) > 0) {
1778 $sql .=
" WHERE ".implode(
' AND ', $sqlWhere);
1781 $sql .= $this->db->order(
'tc.element, tc.position',
'ASC');
1784 $resql = $this->db->query($sql);
1786 $num = $this->db->num_rows($resql);
1788 $langs->loadLangs(array(
"propal",
"orders",
"bills",
"suppliers",
"contracts",
"supplier_proposal"));
1790 while ($obj = $this->db->fetch_object($resql)) {
1791 $modulename = $obj->module ?? $obj->element;
1792 if (strpos($obj->element,
'project') !==
false) {
1793 $modulename =
'projet';
1794 } elseif ($obj->element ==
'contrat') {
1795 $element =
'contract';
1796 } elseif ($obj->element ==
'action') {
1797 $modulename =
'agenda';
1798 } elseif (strpos($obj->element,
'supplier') !==
false && $obj->element !=
'supplier_proposal') {
1799 $modulename =
'fournisseur';
1801 if (isModEnabled($modulename)) {
1802 $libelle_element = $langs->trans(
'ContactDefault_'.$obj->element);
1803 $tmpelement = $obj->element;
1804 $transkey =
"TypeContact_".$tmpelement.
"_".$source.
"_".$obj->code;
1805 $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->type_label);
1806 $tab[$obj->rowid] = $libelle_element.
' - '.$libelle_type;
1812 $this->error = $this->db->lasterror();
1833 if (!
getDolGlobalInt(
'SHIPPING_USE_ITS_OWN_CONTACTS') && $this->element ==
'shipping' && $this->origin_id != 0) {
1834 $id = $this->origin_id;
1835 $element =
'commande';
1836 } elseif ($this->element ==
'reception' && $this->origin_id != 0) {
1837 $id = $this->origin_id;
1838 $element =
'order_supplier';
1841 $element = $this->element;
1844 $sql =
"SELECT ec.fk_socpeople";
1845 $sql .=
" FROM ".$this->db->prefix().
"element_contact as ec,";
1846 if ($source ==
'internal') {
1847 $sql .=
" ".$this->db->prefix().
"user as c,";
1849 if ($source ==
'external') {
1850 $sql .=
" ".$this->db->prefix().
"socpeople as c,";
1852 $sql .=
" ".$this->db->prefix().
"c_type_contact as tc";
1853 $sql .=
" WHERE ec.element_id = ".((int) $id);
1854 $sql .=
" AND ec.fk_socpeople = c.rowid";
1855 if ($source ==
'internal') {
1856 $sql .=
" AND c.entity IN (".getEntity(
'user').
")";
1858 if ($source ==
'external') {
1859 $sql .=
" AND c.entity IN (".getEntity(
'societe').
")";
1861 $sql .=
" AND ec.fk_c_type_contact = tc.rowid";
1862 $sql .=
" AND tc.element = '".$this->db->escape($element).
"'";
1863 $sql .=
" AND tc.source = '".$this->db->escape($source).
"'";
1865 $sql .=
" AND tc.code = '".$this->db->escape($code).
"'";
1867 $sql .=
" AND tc.active = 1";
1869 $sql .=
" AND ec.statut = ".((int) $status);
1872 dol_syslog(get_class($this).
"::getIdContact", LOG_DEBUG);
1873 $resql = $this->db->query($sql);
1875 while ($obj = $this->db->fetch_object($resql)) {
1876 $result[$i] = $obj->fk_socpeople;
1880 $this->error = $this->db->error();
1897 if (empty($contactid)) {
1898 $contactid = $this->contact_id;
1901 if (empty($contactid)) {
1905 require_once DOL_DOCUMENT_ROOT.
'/contact/class/contact.class.php';
1906 $contact =
new Contact($this->db);
1907 $result = $contact->fetch($contactid);
1908 $this->contact = $contact;
1923 if (empty($this->socid) && empty($this->fk_soc) && empty($force_thirdparty_id)) {
1927 require_once DOL_DOCUMENT_ROOT.
'/societe/class/societe.class.php';
1929 $idtofetch = isset($this->socid) ? $this->socid : (isset($this->fk_soc) ? $this->fk_soc : 0);
1930 if ($force_thirdparty_id) {
1931 $idtofetch = $force_thirdparty_id;
1935 $thirdparty =
new Societe($this->db);
1936 $result = $thirdparty->fetch($idtofetch);
1938 $this->errors = array_merge($this->errors, $thirdparty->errors);
1940 $this->thirdparty = $thirdparty;
1944 $this->thirdparty->price_level = 1;
1963 if (!$this->table_ref_field) {
1967 $sql =
"SELECT rowid FROM ".$this->db->prefix().$this->table_element;
1968 $sql .=
" WHERE ".$this->table_ref_field.
" LIKE '".$this->db->escape($ref).
"'";
1971 $query = $this->db->query($sql);
1973 if (!$this->db->num_rows($query)) {
1977 $result = $this->db->fetch_object($query);
1979 if (method_exists($this,
'fetch')) {
1980 return $this->fetch($result->rowid);
1982 $this->error =
'Fetch method not implemented on '.get_class($this);
1983 dol_syslog(get_class($this).
'::fetchOneLike Error='.$this->error, LOG_ERR);
1984 array_push($this->errors, $this->error);
2013 dol_syslog(get_class($this).
'::fetchBarCode this->element='.$this->element.
' this->barcode_type='.$this->barcode_type);
2015 $idtype = $this->barcode_type;
2016 if (empty($idtype) && $idtype !=
'0') {
2017 if ($this->element ==
'product' &&
getDolGlobalString(
'PRODUIT_DEFAULT_BARCODE_TYPE')) {
2019 } elseif ($this->element ==
'societe') {
2022 dol_syslog(
'Call fetchBarCode with barcode_type not defined and cannot be guessed', LOG_WARNING);
2027 if (empty($this->barcode_type) || empty($this->barcode_type_code) || empty($this->barcode_type_label) || empty($this->barcode_type_coder)) {
2028 $sql =
"SELECT rowid, code, libelle as label, coder";
2029 $sql .=
" FROM ".$this->db->prefix().
"c_barcode_type";
2030 $sql .=
" WHERE rowid = ".((int) $idtype);
2032 $resql = $this->db->query($sql);
2034 $obj = $this->db->fetch_object($resql);
2036 $this->barcode_type = $obj->rowid;
2037 $this->barcode_type_code = $obj->code;
2038 $this->barcode_type_label = $obj->label;
2039 $this->barcode_type_coder = $obj->coder;
2057 include_once DOL_DOCUMENT_ROOT.
'/projet/class/project.class.php';
2059 if (empty($this->fk_project) && !empty($this->fk_projet)) {
2060 $this->fk_project = $this->fk_projet;
2062 if (empty($this->fk_project)) {
2066 $project =
new Project($this->db);
2067 $result = $project->fetch($this->fk_project);
2069 $this->projet = $project;
2070 $this->project = $project;
2112 include_once DOL_DOCUMENT_ROOT.
'/product/class/product.class.php';
2115 if (empty($this->fk_product)) {
2119 $product =
new Product($this->db);
2121 $result = $product->fetch($this->fk_product);
2123 $this->product = $product;
2137 $user =
new User($this->db);
2138 $result = $user->fetch($userid);
2139 $this->
user = $user;
2153 $origin = $this->origin ? $this->origin : $this->origin_type;
2156 if ($origin ==
'shipping') {
2157 $origin =
'expedition';
2159 if ($origin ==
'delivery') {
2160 $origin =
'livraison';
2162 if ($origin ==
'order_supplier' || $origin ==
'supplier_order') {
2163 $origin =
'commandeFournisseur';
2166 $classname = ucfirst($origin);
2167 $this->origin_object =
new $classname($this->db);
2169 $this->origin_object->fetch($this->origin_id);
2187 $sql =
"SELECT rowid FROM ".$this->db->prefix().$table;
2188 $sql .=
" WHERE ".$field.
" = '".$this->db->escape($key).
"'";
2189 if (!empty($element)) {
2190 $sql .=
" AND entity IN (".getEntity($element).
")";
2192 $sql .=
" AND entity = ".((int)
$conf->entity);
2195 dol_syslog(get_class($this).
'::fetchObjectFrom', LOG_DEBUG);
2196 $resql = $this->db->query($sql);
2198 $obj = $this->db->fetch_object($resql);
2201 if (method_exists($this,
'fetch')) {
2202 $result = $this->fetch($obj->rowid);
2204 $this->error =
'fetch() method not implemented on '.get_class($this);
2205 dol_syslog(get_class($this).
'::fetchOneLike Error='.$this->error, LOG_ERR);
2206 array_push($this->errors, $this->error);
2226 if (!empty($id) && !empty($field) && !empty($table)) {
2227 $sql =
"SELECT ".$field.
" FROM ".$this->db->prefix().$table;
2228 $sql .=
" WHERE rowid = ".((int) $id);
2230 dol_syslog(get_class($this).
'::getValueFrom', LOG_DEBUG);
2231 $resql = $this->db->query($sql);
2233 $row = $this->db->fetch_row($resql);
2256 public function setValueFrom($field, $value, $table =
'', $id =
null, $format =
'', $id_field =
'', $fuser =
null, $trigkey =
'', $fk_user_field =
'fk_user_modif')
2260 if (empty($table)) {
2261 $table = $this->table_element;
2266 if (empty($format)) {
2269 if (empty($id_field)) {
2270 $id_field =
'rowid';
2274 if ($table ==
'product' && $field ==
'note_private') {
2278 if (in_array($table, array(
'actioncomm',
'adherent',
'advtargetemailing',
'cronjob',
'establishment'))) {
2279 $fk_user_field =
'fk_user_mod';
2281 if (in_array($table, array(
'prelevement_bons'))) {
2282 $fk_user_field =
'';
2287 $sql =
"SELECT " . $field;
2288 $sql .=
" FROM " . MAIN_DB_PREFIX . $table;
2289 $sql .=
" WHERE " . $id_field .
" = " . ((int) $id);
2291 $resql = $this->db->query($sql);
2293 if ($obj = $this->db->fetch_object($resql)) {
2294 if ($format ==
'date') {
2295 $oldvalue = $this->db->jdate($obj->$field);
2297 $oldvalue = $obj->$field;
2301 $this->error = $this->db->lasterror();
2312 $sql =
"UPDATE ".$this->db->prefix().$table.
" SET ";
2314 if ($format ==
'text') {
2315 $sql .= $field.
" = '".$this->db->escape($value).
"'";
2316 } elseif ($format ==
'int') {
2317 $sql .= $field.
" = ".((int) $value);
2318 } elseif ($format ==
'date') {
2319 $sql .= $field.
" = ".($value ?
"'".$this->db->idate($value).
"'" :
"null");
2320 } elseif ($format ==
'dategmt') {
2321 $sql .= $field.
" = ".($value ?
"'".$this->db->idate($value,
'gmt').
"'" :
"null");
2324 if ($fk_user_field) {
2325 if (!empty($fuser) && is_object($fuser)) {
2326 $sql .=
", ".$this->db->sanitize($fk_user_field).
" = ".((int) $fuser->id);
2327 } elseif (empty($fuser) || $fuser !=
'none') {
2328 $sql .=
", ".$this->db->sanitize($fk_user_field).
" = ".((int) $user->id);
2332 $sql .=
" WHERE ".$id_field.
" = ".((int) $id);
2334 $resql = $this->db->query($sql);
2338 if (method_exists($this,
'fetch')) {
2339 $result = $this->fetch($id);
2343 $this->oldcopy = clone $this;
2344 if (property_exists($this->oldcopy, $field)) {
2345 $this->oldcopy->$field = $oldvalue;
2349 $result = $this->
call_trigger($trigkey, (!empty($fuser) && is_object($fuser)) ? $fuser : $user);
2357 if (property_exists($this, $field)) {
2358 $this->$field = $value;
2360 $this->db->commit();
2363 $this->db->rollback();
2367 if ($this->db->lasterrno() ==
'DB_ERROR_RECORD_ALREADY_EXISTS') {
2368 $this->error =
'DB_ERROR_RECORD_ALREADY_EXISTS';
2370 $this->error = $this->db->lasterror();
2372 $this->db->rollback();
2391 global
$conf, $user;
2393 if (!$this->table_element) {
2394 dol_print_error(
null, get_class($this).
"::load_previous_next_ref was called on object with property table_element not defined");
2397 if ($fieldid ==
'none') {
2402 if (in_array($this->table_element, array(
'facture_rec',
'facture_fourn_rec')) && $fieldid ==
'title') {
2408 if ($user->socid > 0) {
2409 $socid = $user->socid;
2414 $aliastablesociete =
's';
2415 if ($this->element ==
'societe') {
2416 $aliastablesociete =
'te';
2418 $restrictiononfksoc = empty($this->restrictiononfksoc) ? 0 : $this->restrictiononfksoc;
2419 $sql =
"SELECT MAX(te.".$fieldid.
")";
2420 $sql .=
" FROM ".(empty($nodbprefix) ? $this->db->prefix() :
'').$this->table_element.
" as te";
2421 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2422 $tmparray = explode(
'@', $this->ismultientitymanaged);
2423 $sql .=
", ".$this->db->prefix().$tmparray[1].
" as ".($tmparray[1] ==
'societe' ?
's' :
'parenttable');
2424 } elseif ($restrictiononfksoc == 1 && $this->element !=
'societe' && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2425 $sql .=
", ".$this->db->prefix().
"societe as s";
2426 } elseif ($restrictiononfksoc == 2 && $this->element !=
'societe' && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2427 $sql .=
" LEFT JOIN ".$this->db->prefix().
"societe as s ON te.fk_soc = s.rowid";
2429 if ($restrictiononfksoc && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2430 $sql .=
" LEFT JOIN ".$this->db->prefix().
"societe_commerciaux as sc ON ".$aliastablesociete.
".rowid = sc.fk_soc";
2432 if ($fieldid ==
'rowid') {
2433 $sql .=
" WHERE te.".$fieldid.
" < ".((int) $this->
id);
2435 $sql .=
" WHERE te.".$fieldid.
" < '".$this->db->escape($this->
ref).
"'";
2437 if ($restrictiononfksoc == 1 && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2438 $sql .=
" AND sc.fk_user = ".((int) $user->id);
2440 if ($restrictiononfksoc == 2 && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2441 $sql .=
" AND (sc.fk_user = ".((int) $user->id).
' OR te.fk_soc IS NULL)';
2444 $filtermax = $filter;
2449 if ($errormessage) {
2450 if (!preg_match(
'/^\s*AND/i', $filtermax)) {
2458 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2459 $tmparray = explode(
'@', $this->ismultientitymanaged);
2460 $sql .=
" AND te.".$tmparray[0].
" = ".($tmparray[1] ==
"societe" ?
"s" :
"parenttable").
".rowid";
2461 } elseif ($restrictiononfksoc == 1 && $this->element !=
'societe' && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2462 $sql .=
' AND te.fk_soc = s.rowid';
2464 if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
2465 if ($this->element ==
'user' &&
getDolGlobalInt(
'MULTICOMPANY_TRANSVERSE_MODE')) {
2466 if (!empty($user->admin) && empty($user->entity) &&
$conf->entity == 1) {
2467 $sql .=
" AND te.entity IS NOT NULL";
2469 $sql .=
" AND te.rowid IN (SELECT ug.fk_user FROM ".$this->db->prefix().
"usergroup_user as ug WHERE ug.entity IN (".
getEntity(
'usergroup').
"))";
2472 $sql .=
' AND te.entity IN ('.getEntity($this->element).
')';
2475 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged) && $this->element !=
'societe') {
2476 $tmparray = explode(
'@', $this->ismultientitymanaged);
2477 $sql .=
' AND parenttable.entity IN ('.getEntity($tmparray[1]).
')';
2479 if ($restrictiononfksoc == 1 && $socid && $this->element !=
'societe') {
2480 $sql .=
' AND te.fk_soc = '.((int) $socid);
2482 if ($restrictiononfksoc == 2 && $socid && $this->element !=
'societe') {
2483 $sql .=
' AND (te.fk_soc = '.((int) $socid).
' OR te.fk_soc IS NULL)';
2485 if ($restrictiononfksoc && $socid && $this->element ==
'societe') {
2486 $sql .=
' AND te.rowid = '.((int) $socid);
2490 $result = $this->db->query($sql);
2492 $this->error = $this->db->lasterror();
2495 $row = $this->db->fetch_row($result);
2496 $this->ref_previous = $row[0];
2498 $sql =
"SELECT MIN(te.".$fieldid.
")";
2499 $sql .=
" FROM ".(empty($nodbprefix) ? $this->db->prefix() :
'').$this->table_element.
" as te";
2500 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2501 $tmparray = explode(
'@', $this->ismultientitymanaged);
2502 $sql .=
", ".$this->db->prefix().$tmparray[1].
" as ".($tmparray[1] ==
'societe' ?
's' :
'parenttable');
2503 } elseif ($restrictiononfksoc == 1 && $this->element !=
'societe' && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2504 $sql .=
", ".$this->db->prefix().
"societe as s";
2505 } elseif ($restrictiononfksoc == 2 && $this->element !=
'societe' && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2506 $sql .=
" LEFT JOIN ".$this->db->prefix().
"societe as s ON te.fk_soc = s.rowid";
2508 if ($restrictiononfksoc && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2509 $sql .=
" LEFT JOIN ".$this->db->prefix().
"societe_commerciaux as sc ON ".$aliastablesociete.
".rowid = sc.fk_soc";
2511 if ($fieldid ==
'rowid') {
2512 $sql .=
" WHERE te.".$fieldid.
" > ".((int) $this->
id);
2514 $sql .=
" WHERE te.".$fieldid.
" > '".$this->db->escape($this->
ref).
"'";
2516 if ($restrictiononfksoc == 1 && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2517 $sql .=
" AND (sc.fk_user = ".((int) $user->id);
2519 $userschilds = $user->getAllChildIds();
2520 $sql .=
" OR sc.fk_user IN (".$this->db->sanitize(implode(
',', $userschilds)).
")";
2524 if ($restrictiononfksoc == 2 && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2525 $sql .=
" AND (sc.fk_user = ".((int) $user->id).
' OR te.fk_soc IS NULL)';
2528 $filtermin = $filter;
2533 if ($errormessage) {
2534 if (!preg_match(
'/^\s*AND/i', $filtermin)) {
2544 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2545 $tmparray = explode(
'@', $this->ismultientitymanaged);
2546 $sql .=
" AND te.".$tmparray[0].
" = ".($tmparray[1] ==
"societe" ?
"s" :
"parenttable").
".rowid";
2547 } elseif ($restrictiononfksoc == 1 && $this->element !=
'societe' && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2548 $sql .=
' AND te.fk_soc = s.rowid';
2550 if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
2551 if ($this->element ==
'user' &&
getDolGlobalInt(
'MULTICOMPANY_TRANSVERSE_MODE')) {
2552 if (!empty($user->admin) && empty($user->entity) &&
$conf->entity == 1) {
2553 $sql .=
" AND te.entity IS NOT NULL";
2555 $sql .=
" AND te.rowid IN (SELECT ug.fk_user FROM ".$this->db->prefix().
"usergroup_user as ug WHERE ug.entity IN (".
getEntity(
'usergroup').
"))";
2558 $sql .=
' AND te.entity IN ('.getEntity($this->element).
')';
2561 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged) && $this->element !=
'societe') {
2562 $tmparray = explode(
'@', $this->ismultientitymanaged);
2563 $sql .=
' AND parenttable.entity IN ('.getEntity($tmparray[1]).
')';
2565 if ($restrictiononfksoc == 1 && $socid && $this->element !=
'societe') {
2566 $sql .=
' AND te.fk_soc = '.((int) $socid);
2568 if ($restrictiononfksoc == 2 && $socid && $this->element !=
'societe') {
2569 $sql .=
' AND (te.fk_soc = '.((int) $socid).
' OR te.fk_soc IS NULL)';
2571 if ($restrictiononfksoc && $socid && $this->element ==
'societe') {
2572 $sql .=
' AND te.rowid = '.((int) $socid);
2577 $result = $this->db->query($sql);
2579 $this->error = $this->db->lasterror();
2582 $row = $this->db->fetch_row($result);
2583 $this->ref_next = $row[0];
2598 $contactAlreadySelected = array();
2603 if ($source ==
'thirdparty') {
2604 $contactAlreadySelected[$i] = $tab[$i][
'socid'];
2606 $contactAlreadySelected[$i] = $tab[$i][
'id'];
2610 return $contactAlreadySelected;
2626 if (!$this->table_element) {
2627 dol_syslog(get_class($this).
"::setProject was called on object with property table_element not defined", LOG_ERR);
2631 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
2633 if (!empty($this->fields[
'fk_project'])) {
2635 $sql .=
" SET fk_project = ".((int) $projectid);
2637 $sql .=
" SET fk_project = NULL";
2639 $sql .=
' WHERE rowid = '.((int) $this->
id);
2640 } elseif ($this->table_element ==
'actioncomm') {
2642 $sql .=
" SET fk_project = ".((int) $projectid);
2644 $sql .=
" SET fk_project = NULL";
2646 $sql .=
' WHERE id = '.((int) $this->
id);
2649 $sql .=
' SET fk_projet = '.((int) $projectid);
2651 $sql .=
' SET fk_projet = NULL';
2653 $sql .=
" WHERE rowid = ".((int) $this->
id);
2658 dol_syslog(get_class($this).
"::setProject", LOG_DEBUG);
2659 if ($this->db->query($sql)) {
2660 $this->fk_project = ((int) $projectid);
2667 if (!$error && !$notrigger) {
2669 $result = $this->
call_trigger(strtoupper($this->element) .
'_MODIFY', $user);
2678 $this->db->rollback();
2681 $this->db->commit();
2699 dol_syslog(get_class($this).
'::setPaymentMethods('.$id.
')');
2701 if ($this->
status >= 0 || $this->element ==
'societe') {
2703 $fieldname =
'fk_mode_reglement';
2704 if ($this->element ==
'societe') {
2705 $fieldname =
'mode_reglement';
2707 if (get_class($this) ==
'Fournisseur') {
2708 $fieldname =
'mode_reglement_supplier';
2710 if (get_class($this) ==
'Tva') {
2711 $fieldname =
'fk_typepayment';
2713 if (get_class($this) ==
'Salary') {
2714 $fieldname =
'fk_typepayment';
2717 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
2718 $sql .=
" SET ".$fieldname.
" = ".(($id > 0 || $id ==
'0') ? ((
int) $id) :
'NULL');
2719 $sql .=
' WHERE rowid='.((int) $this->
id);
2721 if ($this->db->query($sql)) {
2722 $this->mode_reglement_id = $id;
2724 if (get_class($this) ==
'Fournisseur') {
2725 $this->mode_reglement_supplier_id = $id;
2728 if (!$error && !$notrigger) {
2730 if (get_class($this) ==
'Commande') {
2733 $result = $this->
call_trigger(strtoupper(get_class($this)).
'_MODIFY', $user);
2742 dol_syslog(get_class($this).
'::setPaymentMethods Error '.$this->db->error());
2743 $this->error = $this->db->error();
2747 dol_syslog(get_class($this).
'::setPaymentMethods, status of the object is incompatible');
2748 $this->error =
'Status of the object is incompatible '.$this->status;
2761 dol_syslog(get_class($this).
'::setMulticurrencyCode('.$code.
')');
2762 if ($this->
status >= 0 || $this->element ==
'societe') {
2763 $fieldname =
'multicurrency_code';
2765 $sql =
'UPDATE '.$this->db->prefix().$this->table_element;
2766 $sql .=
" SET ".$fieldname.
" = '".$this->db->escape($code).
"'";
2767 $sql .=
' WHERE rowid='.((int) $this->
id);
2769 if ($this->db->query($sql)) {
2770 $this->multicurrency_code = $code;
2774 $this->setMulticurrencyRate($rate, 2);
2779 dol_syslog(get_class($this).
'::setMulticurrencyCode Error '.$sql.
' - '.$this->db->error());
2780 $this->error = $this->db->error();
2784 dol_syslog(get_class($this).
'::setMulticurrencyCode, status of the object is incompatible');
2785 $this->error =
'Status of the object is incompatible '.$this->status;
2797 public function setMulticurrencyRate($rate, $mode = 1)
2799 dol_syslog(get_class($this).
'::setMulticurrencyRate('.$rate.
', '.$mode.
')');
2800 if ($this->
status >= 0 || $this->element ==
'societe') {
2801 $fieldname =
'multicurrency_tx';
2803 $sql =
'UPDATE '.$this->db->prefix().$this->table_element;
2804 $sql .=
" SET ".$this->db->sanitize($fieldname).
" = ".((float) $rate);
2805 $sql .=
' WHERE rowid='.((int) $this->
id);
2807 if ($this->db->query($sql)) {
2808 $this->multicurrency_tx = $rate;
2811 if (!empty($this->lines)) {
2812 foreach ($this->lines as &$line) {
2815 $line->subprice = 0;
2820 $line->multicurrency_subprice = 0;
2823 switch ($this->element) {
2827 '@phan-var-force Propal $this';
2828 '@phan-var-force PropaleLigne $line';
2833 $line->remise_percent,
2835 $line->localtax1_tx,
2836 $line->localtax2_tx,
2837 ($line->description ? $line->description : $line->desc),
2840 $line->special_code,
2841 $line->fk_parent_line,
2842 $line->skip_update_total,
2843 $line->fk_fournprice,
2846 $line->product_type,
2849 $line->array_options,
2851 $line->multicurrency_subprice
2857 '@phan-var-force Commande $this';
2858 '@phan-var-force OrderLine $line';
2861 ($line->description ? $line->description : $line->desc),
2864 $line->remise_percent,
2866 $line->localtax1_tx,
2867 $line->localtax2_tx,
2872 $line->product_type,
2873 $line->fk_parent_line,
2874 $line->skip_update_total,
2875 $line->fk_fournprice,
2878 $line->special_code,
2879 $line->array_options,
2881 $line->multicurrency_subprice
2887 '@phan-var-force Facture $this';
2888 '@phan-var-force FactureLigne $line';
2891 ($line->description ? $line->description : $line->desc),
2894 $line->remise_percent,
2898 $line->localtax1_tx,
2899 $line->localtax2_tx,
2902 $line->product_type,
2903 $line->fk_parent_line,
2904 $line->skip_update_total,
2905 $line->fk_fournprice,
2908 $line->special_code,
2909 $line->array_options,
2910 $line->situation_percent,
2912 $line->multicurrency_subprice
2918 '@phan-var-force FactureRec $this';
2919 '@phan-var-force FactureLigneRec $line';
2922 ($line->description ? $line->description : $line->desc),
2926 $line->localtax1_tx,
2927 $line->localtax2_tx,
2929 $line->remise_percent,
2934 $line->product_type,
2936 $line->special_code,
2939 $line->multicurrency_subprice,
2943 $line->fk_fournprice,
2945 $line->fk_parent_line
2948 case 'supplier_proposal':
2951 '@phan-var-force SupplierProposal $this';
2952 '@phan-var-force SupplierProposalLine $line';
2957 $line->remise_percent,
2959 $line->localtax1_tx,
2960 $line->localtax2_tx,
2961 ($line->description ? $line->description : $line->desc),
2964 $line->special_code,
2965 $line->fk_parent_line,
2966 $line->skip_update_total,
2967 $line->fk_fournprice,
2970 $line->product_type,
2971 $line->array_options,
2973 (int) $line->fk_unit,
2974 $line->multicurrency_subprice
2977 case 'order_supplier':
2980 '@phan-var-force CommandeFournisseur $this';
2981 '@phan-var-force CommandeFournisseurLigne $line';
2984 ($line->description ? $line->description : $line->desc),
2987 $line->remise_percent,
2989 $line->localtax1_tx,
2990 $line->localtax2_tx,
2993 $line->product_type,
2997 $line->array_options,
2999 $line->multicurrency_subprice,
3003 case 'invoice_supplier':
3006 '@phan-var-force FactureFournisseur $this';
3007 '@phan-var-force SupplierInvoiceLIne $line';
3010 ($line->description ? $line->description : $line->desc),
3013 $line->localtax1_tx,
3014 $line->localtax2_tx,
3019 $line->product_type,
3020 $line->remise_percent,
3024 $line->array_options,
3026 $line->multicurrency_subprice,
3031 dol_syslog(get_class($this).
'::setMulticurrencyRate no updateline defined', LOG_DEBUG);
3039 dol_syslog(get_class($this).
'::setMulticurrencyRate Error '.$sql.
' - '.$this->db->error());
3040 $this->error = $this->db->error();
3044 dol_syslog(get_class($this).
'::setMulticurrencyRate, status of the object is incompatible');
3045 $this->error =
'Status of the object is incompatible '.$this->status;
3059 dol_syslog(get_class($this).
'::setPaymentTerms('.$id.
', '.var_export($deposit_percent,
true).
')');
3060 if ($this->
status >= 0 || $this->element ==
'societe') {
3062 $fieldname =
'fk_cond_reglement';
3063 if ($this->element ==
'societe') {
3064 $fieldname =
'cond_reglement';
3066 if (get_class($this) ==
'Fournisseur') {
3067 $fieldname =
'cond_reglement_supplier';
3070 if (empty($deposit_percent) || $deposit_percent < 0) {
3071 $deposit_percent = (float)
getDictionaryValue(
'c_payment_term',
'deposit_percent', $id);
3074 if ($deposit_percent > 100) {
3075 $deposit_percent = 100;
3078 $sql =
'UPDATE '.$this->db->prefix().$this->table_element;
3079 $sql .=
" SET ".$fieldname.
" = ".(($id > 0 || $id ==
'0') ? ((
int) $id) :
'NULL');
3080 if (in_array($this->table_element, array(
'propal',
'commande',
'societe'))) {
3081 $sql .=
" , deposit_percent = " . (empty($deposit_percent) ?
'NULL' :
"'".$this->db->escape((
string) $deposit_percent).
"'");
3083 $sql .=
' WHERE rowid='.((int) $this->
id);
3085 if ($this->db->query($sql)) {
3086 $this->cond_reglement_id = $id;
3088 if (get_class($this) ==
'Fournisseur') {
3089 $this->cond_reglement_supplier_id = $id;
3091 $this->deposit_percent = $deposit_percent;
3094 dol_syslog(get_class($this).
'::setPaymentTerms Error '.$sql.
' - '.$this->db->error());
3095 $this->error = $this->db->error();
3099 dol_syslog(get_class($this).
'::setPaymentTerms, status of the object is incompatible');
3100 $this->error =
'Status of the object is incompatible '.$this->status;
3113 dol_syslog(get_class($this).
'::setTransportMode('.$id.
')');
3114 if ($this->
status >= 0 || $this->element ==
'societe') {
3115 $fieldname =
'fk_transport_mode';
3116 if ($this->element ==
'societe') {
3117 $fieldname =
'transport_mode';
3119 if (get_class($this) ==
'Fournisseur') {
3120 $fieldname =
'transport_mode_supplier';
3123 $sql =
'UPDATE '.$this->db->prefix().$this->table_element;
3124 $sql .=
" SET ".$fieldname.
" = ".(($id > 0 || $id ==
'0') ? ((
int) $id) :
'NULL');
3125 $sql .=
' WHERE rowid='.((int) $this->
id);
3127 if ($this->db->query($sql)) {
3128 $this->transport_mode_id = $id;
3130 if (get_class($this) ==
'Fournisseur') {
3131 $this->transport_mode_supplier_id = $id;
3135 dol_syslog(get_class($this).
'::setTransportMode Error '.$sql.
' - '.$this->db->error());
3136 $this->error = $this->db->error();
3140 dol_syslog(get_class($this).
'::setTransportMode, status of the object is incompatible');
3141 $this->error =
'Status of the object is incompatible '.$this->status;
3154 dol_syslog(get_class($this).
'::setRetainedWarrantyPaymentTerms('.$id.
')');
3155 if ($this->
status >= 0 || $this->element ==
'societe') {
3156 $fieldname =
'retained_warranty_fk_cond_reglement';
3158 $sql =
'UPDATE '.$this->db->prefix().$this->table_element;
3159 $sql .=
" SET ".$fieldname.
" = ".((int) $id);
3160 $sql .=
' WHERE rowid='.((int) $this->
id);
3162 if ($this->db->query($sql)) {
3163 $this->retained_warranty_fk_cond_reglement = $id;
3166 dol_syslog(get_class($this).
'::setRetainedWarrantyPaymentTerms Error '.$sql.
' - '.$this->db->error());
3167 $this->error = $this->db->error();
3171 dol_syslog(get_class($this).
'::setRetainedWarrantyPaymentTerms, status of the object is incompatible');
3172 $this->error =
'Status of the object is incompatible '.$this->status;
3186 $fieldname =
'fk_delivery_address';
3187 if ($this->element ==
'delivery' || $this->element ==
'shipping') {
3188 $fieldname =
'fk_address';
3191 $sql =
"UPDATE ".$this->db->prefix().$this->table_element.
" SET ".$fieldname.
" = ".((int) $id);
3192 $sql .=
" WHERE rowid = ".((int) $this->
id).
" AND fk_statut = 0";
3194 if ($this->db->query($sql)) {
3195 $this->fk_delivery_address = $id;
3198 $this->error = $this->db->error();
3199 dol_syslog(get_class($this).
'::setDeliveryAddress Error '.$this->error);
3217 if (empty($userused)) {
3223 if (!$this->table_element) {
3224 dol_syslog(get_class($this).
"::setShippingMethod was called on object with property table_element not defined", LOG_ERR);
3230 if ($shipping_method_id < 0) {
3231 $shipping_method_id =
'NULL';
3233 dol_syslog(get_class($this).
'::setShippingMethod('.$shipping_method_id.
')');
3235 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
3236 $sql .=
" SET fk_shipping_method = ".((int) $shipping_method_id);
3237 $sql .=
" WHERE rowid=".((int) $this->
id);
3238 $resql = $this->db->query($sql);
3240 dol_syslog(get_class($this).
'::setShippingMethod Error ', LOG_DEBUG);
3241 $this->error = $this->db->lasterror();
3246 $this->context = array(
'shippingmethodupdate' => 1);
3247 $result = $this->
call_trigger(strtoupper(get_class($this)).
'_MODIFY', $userused);
3255 $this->db->rollback();
3258 $this->shipping_method_id = ($shipping_method_id ==
'NULL') ?
null : $shipping_method_id;
3259 $this->db->commit();
3273 if (!$this->table_element) {
3274 dol_syslog(get_class($this).
"::setWarehouse was called on object with property table_element not defined", LOG_ERR);
3277 if ($warehouse_id < 0) {
3278 $warehouse_id =
'NULL';
3280 dol_syslog(get_class($this).
'::setWarehouse('.$warehouse_id.
')');
3282 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
3283 $sql .=
" SET fk_warehouse = ".((int) $warehouse_id);
3284 $sql .=
" WHERE rowid=".((int) $this->
id);
3286 if ($this->db->query($sql)) {
3287 $this->warehouse_id = ($warehouse_id ==
'NULL') ?
null : $warehouse_id;
3290 dol_syslog(get_class($this).
'::setWarehouse Error ', LOG_DEBUG);
3291 $this->error = $this->db->error();
3306 if (!$this->table_element) {
3307 dol_syslog(get_class($this).
"::setDocModel was called on object with property table_element not defined", LOG_ERR);
3311 $newmodelpdf =
dol_trunc($modelpdf, 255);
3313 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
3314 $sql .=
" SET model_pdf = '".$this->db->escape($newmodelpdf).
"'";
3315 $sql .=
" WHERE rowid = ".((int) $this->
id);
3317 dol_syslog(get_class($this).
"::setDocModel", LOG_DEBUG);
3318 $resql = $this->db->query($sql);
3320 $this->model_pdf = $modelpdf;
3341 if (empty($userused)) {
3347 if (!$this->table_element) {
3348 dol_syslog(get_class($this).
"::setBankAccount was called on object with property table_element not defined", LOG_ERR);
3353 if ($fk_account < 0) {
3354 $fk_account =
'NULL';
3356 dol_syslog(get_class($this).
'::setBankAccount('.$fk_account.
')');
3358 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
3359 $sql .=
" SET fk_account = ".((int) $fk_account);
3360 $sql .=
" WHERE rowid=".((int) $this->
id);
3362 $resql = $this->db->query($sql);
3364 dol_syslog(get_class($this).
'::setBankAccount Error '.$sql.
' - '.$this->db->error());
3365 $this->error = $this->db->lasterror();
3370 $this->context[
'bankaccountupdate'] = 1;
3371 $triggerName = strtoupper(get_class($this)).
'_MODIFY';
3373 if ($triggerName ==
'FACTUREREC_MODIFY') {
3374 $triggerName =
'BILLREC_MODIFY';
3376 $result = $this->
call_trigger($triggerName, $userused);
3384 $this->db->rollback();
3387 $this->fk_account = ($fk_account ==
'NULL') ?
null : $fk_account;
3388 $this->db->commit();
3406 public function line_order($renum =
false, $rowidorder =
'ASC', $fk_parent_line =
true)
3409 if (!$this->table_element_line) {
3410 dol_syslog(get_class($this).
"::line_order was called on object with property table_element_line not defined", LOG_ERR);
3413 if (!$this->fk_element) {
3414 dol_syslog(get_class($this).
"::line_order was called on object with property fk_element not defined", LOG_ERR);
3418 $fieldposition =
'rang';
3419 if (in_array($this->table_element_line, array(
'bom_bomline',
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3420 $fieldposition =
'position';
3425 $sql =
"SELECT count(rowid) FROM ".$this->db->prefix().$this->table_element_line;
3426 $sql .=
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
3428 $sql .=
" AND " . $fieldposition .
" = 0";
3431 $sql .=
" AND " . $fieldposition .
" <> 0";
3434 dol_syslog(get_class($this).
"::line_order", LOG_DEBUG);
3435 $resql = $this->db->query($sql);
3437 $row = $this->db->fetch_row($resql);
3447 $sql =
"SELECT rowid FROM ".$this->db->prefix().$this->table_element_line;
3448 $sql .=
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
3449 if ($fk_parent_line) {
3450 $sql .=
' AND fk_parent_line IS NULL';
3452 $sql .=
" ORDER BY " . $fieldposition .
" ASC, rowid " . $rowidorder;
3454 dol_syslog(get_class($this).
"::line_order search all parent lines", LOG_DEBUG);
3455 $resql = $this->db->query($sql);
3458 $num = $this->db->num_rows($resql);
3461 $row = $this->db->fetch_row($resql);
3463 if ($fk_parent_line) {
3466 if (!empty($children)) {
3467 foreach ($children as $child) {
3468 array_push($rows, $child);
3475 if (!empty($rows)) {
3476 foreach ($rows as $key => $row) {
3496 $fieldposition =
'rang';
3497 if (in_array($this->table_element_line, array(
'bom_bomline',
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3498 $fieldposition =
'position';
3503 $sql =
"SELECT rowid FROM ".$this->db->prefix().$this->table_element_line;
3504 $sql .=
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
3505 $sql .=
' AND fk_parent_line = '.((int) $id);
3506 $sql .=
" ORDER BY " . $fieldposition .
" ASC";
3508 dol_syslog(get_class($this).
"::getChildrenOfLine search children lines for line ".$id, LOG_DEBUG);
3510 $resql = $this->db->query($sql);
3511 if (!$resql || $this->db->num_rows($resql) <= 0) {
3515 while ($row = $this->db->fetch_row($resql)) {
3517 if (!empty($includealltree) && $includealltree <= 1000) {
3518 $rows = array_merge($rows, $this->
getChildrenOfLine($row[0], $includealltree + 1));
3532 public function line_up($rowid, $fk_parent_line =
true)
3535 $this->
line_order(
false,
'ASC', $fk_parent_line);
3555 $this->
line_order(
false,
'ASC', $fk_parent_line);
3576 global $hookmanager;
3577 $fieldposition =
'rang';
3578 if (in_array($this->table_element_line, array(
'bom_bomline',
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3579 $fieldposition =
'position';
3582 $sql =
"UPDATE ".$this->db->prefix().$this->table_element_line.
" SET ".$fieldposition.
" = ".((int) $rang);
3583 $sql .=
' WHERE rowid = '.((int) $rowid);
3584 if ($this->
id > 0 && !empty($this->fk_element)) {
3586 $sql .=
" AND ".$this->db->sanitize($this->fk_element).
" = ".((int) $this->
id);
3589 dol_syslog(get_class($this).
"::updateRangOfLine", LOG_DEBUG);
3590 if (!$this->db->query($sql)) {
3595 $parameters = array(
'rowid' => $rowid,
'rang' => $rang,
'fieldposition' => $fieldposition);
3597 $reshook = $hookmanager->executeHooks(
'afterRankOfLineUpdate', $parameters, $this, $action);
3611 $num = count($rows);
3612 for ($i = 0; $i < $num; $i++) {
3630 $fieldposition =
'rang';
3631 if (in_array($this->table_element_line, array(
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3632 $fieldposition =
'position';
3635 $sql =
"UPDATE ".$this->db->prefix().$this->table_element_line.
" SET ".$fieldposition.
" = ".((int) $rang);
3636 $sql .=
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
3637 $sql .=
" AND " . $fieldposition .
" = " . ((int) ($rang - 1));
3638 if (!$this->db->query($sql)) {
3639 $this->error = $this->db->lasterror();
3643 $sql =
"UPDATE ".$this->db->prefix().$this->table_element_line.
" SET ".$fieldposition.
" = ".((int) ($rang - 1));
3644 $sql .=
' WHERE rowid = '.((int) $rowid);
3645 if (!$this->db->query($sql)) {
3646 $this->error = $this->db->lasterror();
3663 if ($rang >= $max) {
3667 $fieldposition =
'rang';
3668 if (in_array($this->table_element_line, array(
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3669 $fieldposition =
'position';
3672 $sql =
"UPDATE ".$this->db->prefix().$this->table_element_line.
" SET ".$fieldposition.
" = ".((int) $rang);
3673 $sql .=
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
3674 $sql .=
" AND " . $fieldposition .
" = " . ((int) ($rang + 1));
3675 if (!$this->db->query($sql)) {
3676 $this->error = $this->db->lasterror();
3680 $sql =
"UPDATE ".$this->db->prefix().$this->table_element_line.
" SET ".$fieldposition.
" = ".((int) ($rang + 1));
3681 $sql .=
' WHERE rowid = '.((int) $rowid);
3682 if (!$this->db->query($sql)) {
3683 $this->error = $this->db->lasterror();
3698 $fieldposition =
'rang';
3699 if (in_array($this->table_element_line, array(
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3700 $fieldposition =
'position';
3703 $sql =
"SELECT " . $fieldposition .
" FROM ".$this->db->prefix().$this->table_element_line;
3704 $sql .=
" WHERE rowid = ".((int) $rowid);
3706 dol_syslog(get_class($this).
"::getRangOfLine", LOG_DEBUG);
3707 $resql = $this->db->query($sql);
3712 $row = $this->db->fetch_row($resql);
3724 $fieldposition =
'rang';
3725 if (in_array($this->table_element_line, array(
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3726 $fieldposition =
'position';
3729 $sql =
"SELECT rowid FROM ".$this->db->prefix().$this->table_element_line;
3730 $sql .=
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
3731 $sql .=
" AND " . $fieldposition .
" = ".((int) $rang);
3732 $resql = $this->db->query($sql);
3737 $row = $this->db->fetch_row($resql);
3751 $positionfield =
'rang';
3752 if (in_array($this->table_element, array(
'bom_bom',
'product_attribute'))) {
3753 $positionfield =
'position';
3756 $sql =
"SELECT max(".$positionfield.
") FROM ".$this->db->prefix().$this->table_element_line;
3757 $sql .=
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
3760 if ($fk_parent_line) {
3761 $sql .=
" AND fk_parent_line = ".((int) $fk_parent_line);
3764 dol_syslog(get_class($this).
"::line_max", LOG_DEBUG);
3765 $resql = $this->db->query($sql);
3767 $row = $this->db->fetch_row($resql);
3769 if ($fk_parent_line) {
3770 if (!empty($row[0])) {
3793 if (!$this->table_element) {
3794 dol_syslog(get_class($this).
"::update_ref_ext was called on object with property table_element not defined", LOG_ERR);
3798 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
3799 $sql .=
" SET ref_ext = '".$this->db->escape($ref_ext).
"'";
3801 $sql .=
" WHERE ".(isset($this->table_rowid) ? $this->table_rowid :
'rowid').
" = ".((
int) $this->id);
3803 dol_syslog(get_class($this).
"::update_ref_ext", LOG_DEBUG);
3804 if ($this->db->query($sql)) {
3805 $this->ref_ext = $ref_ext;
3808 $this->error = $this->db->error();
3827 if (!$this->table_element) {
3828 $this->error =
'update_note was called on object with property table_element not defined';
3829 dol_syslog(get_class($this).
"::update_note was called on object with property table_element not defined", LOG_ERR);
3832 if (!in_array($suffix, array(
'',
'_public',
'_private'))) {
3833 $this->error =
'update_note Parameter suffix must be empty, \'_private\' or \'_public\'';
3834 dol_syslog(get_class($this).
"::update_note Parameter suffix must be empty, '_private' or '_public'", LOG_ERR);
3838 $newsuffix = $suffix;
3841 if ($this->table_element ==
'product' && $newsuffix ==
'_private') {
3844 if (in_array($this->table_element, array(
'actioncomm',
'adherent',
'advtargetemailing',
'cronjob',
'establishment'))) {
3845 $fieldusermod =
"fk_user_mod";
3846 } elseif ($this->table_element ==
'ecm_files') {
3847 $fieldusermod =
"fk_user_m";
3849 $fieldusermod =
"fk_user_modif";
3851 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
3852 $sql .=
" SET note".$this->db->sanitize($newsuffix).
" = ".(!empty($note) ? (
"'".$this->db->escape($note).
"'") :
"NULL");
3853 $sql .=
", ".$this->db->sanitize($fieldusermod).
" = ".((int) $user->id);
3854 $sql .=
" WHERE rowid = ".((int) $this->
id);
3856 dol_syslog(get_class($this).
"::update_note", LOG_DEBUG);
3857 if ($this->db->query($sql)) {
3858 if ($suffix ==
'_public') {
3859 $this->note_public = $note;
3860 } elseif ($suffix ==
'_private') {
3861 $this->note_private = $note;
3863 $this->note = $note;
3864 $this->note_private = $note;
3866 if (empty($notrigger)) {
3867 switch ($this->element) {
3869 $trigger_name =
'COMPANY_MODIFY';
3872 $trigger_name =
'ORDER_MODIFY';
3875 $trigger_name =
'BILL_MODIFY';
3877 case 'invoice_supplier':
3878 $trigger_name =
'BILL_SUPPLIER_MODIFY';
3881 $trigger_name =
'BILLREC_MODIFIY';
3883 case 'expensereport':
3884 $trigger_name =
'EXPENSE_REPORT_MODIFY';
3887 $trigger_name = strtoupper($this->element) .
'_MODIFY';
3896 $this->error = $this->db->lasterror();
3927 public function update_price($exclspec = 0, $roundingadjust =
'auto', $nodatabaseupdate = 0, $seller =
null)
3930 global
$conf, $hookmanager, $action;
3932 $parameters = array(
'exclspec' => $exclspec,
'roundingadjust' => $roundingadjust,
'nodatabaseupdate' => $nodatabaseupdate,
'seller' => $seller);
3933 $reshook = $hookmanager->executeHooks(
'updateTotalPrice', $parameters, $this, $action);
3936 } elseif ($reshook < 0) {
3941 $isElementForSupplier =
false;
3942 $roundTotalConstName =
'MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND';
3944 if ($this->element ==
'propal') {
3945 $MODULE =
"MODULE_DISALLOW_UPDATE_PRICE_PROPOSAL";
3946 } elseif ($this->element ==
'commande' || $this->element ==
'order') {
3947 $MODULE =
"MODULE_DISALLOW_UPDATE_PRICE_ORDER";
3948 } elseif ($this->element ==
'facture' || $this->element ==
'invoice') {
3949 $MODULE =
"MODULE_DISALLOW_UPDATE_PRICE_INVOICE";
3950 } elseif ($this->element ==
'facture_fourn' || $this->element ==
'supplier_invoice' || $this->element ==
'invoice_supplier' || $this->element ==
'invoice_supplier_rec') {
3951 $isElementForSupplier =
true;
3952 $MODULE =
"MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_INVOICE";
3953 } elseif ($this->element ==
'order_supplier' || $this->element ==
'supplier_order') {
3954 $isElementForSupplier =
true;
3955 $MODULE =
"MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_ORDER";
3956 } elseif ($this->element ==
'supplier_proposal') {
3957 $isElementForSupplier =
true;
3958 $MODULE =
"MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_PROPOSAL";
3960 if ($isElementForSupplier) {
3961 $roundTotalConstName =
'MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND_SUPPLIER';
3964 if (!empty($MODULE)) {
3967 foreach ($modsactivated as $mod) {
3968 if (isModEnabled($mod)) {
3975 include_once DOL_DOCUMENT_ROOT.
'/core/lib/price.lib.php';
3977 $forcedroundingmode = $roundingadjust;
3978 if ($forcedroundingmode ==
'auto' && isset(
$conf->global->{$roundTotalConstName})) {
3980 } elseif ($forcedroundingmode ==
'auto') {
3981 $forcedroundingmode =
'0';
3986 $multicurrency_tx = !empty($this->multicurrency_tx) ? $this->multicurrency_tx : 1;
3989 $fieldtva =
'total_tva';
3990 $fieldlocaltax1 =
'total_localtax1';
3991 $fieldlocaltax2 =
'total_localtax2';
3992 $fieldup =
'subprice';
3993 $base_price_type =
'HT';
3994 if ($this->element ==
'facture_fourn' || $this->element ==
'invoice_supplier') {
3998 if ($this->element ==
'invoice_supplier_rec') {
4001 if ($this->element ==
'expensereport') {
4005 $forcedroundingmode =
'0';
4006 $fieldup =
'value_unit';
4007 $base_price_type =
'TTC';
4010 $sql =
"SELECT rowid, qty, ".$this->db->sanitize($fieldup).
" as up, remise_percent, 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,";
4011 $sql .=
' tva_tx as vatrate, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type, info_bits, product_type';
4012 if ($this->table_element_line ==
'facturedet') {
4013 $sql .=
', situation_percent';
4015 $sql .=
', multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc';
4016 $sql .=
" FROM ".$this->db->prefix().$this->table_element_line;
4017 $sql .=
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
4019 $product_field =
'product_type';
4020 if ($this->table_element_line ==
'contratdet') {
4021 $product_field =
'';
4023 if ($product_field) {
4024 $sql .=
" AND ".$product_field.
" <> 9";
4027 $sql .=
' ORDER by rowid';
4029 dol_syslog(get_class($this).
"::update_price", LOG_DEBUG);
4031 $resql = $this->db->query($sql);
4033 $this->total_ht = 0;
4034 $this->total_tva = 0;
4035 $this->total_localtax1 = 0;
4036 $this->total_localtax2 = 0;
4037 $this->total_ttc = 0;
4038 $total_ht_by_vats = array();
4039 $total_tva_by_vats = array();
4040 $total_ttc_by_vats = array();
4041 $this->multicurrency_total_ht = 0;
4042 $this->multicurrency_total_tva = 0;
4043 $this->multicurrency_total_ttc = 0;
4047 $num = $this->db->num_rows($resql);
4050 $obj = $this->db->fetch_object($resql);
4053 $parameters = array(
'fk_element' => $obj->rowid);
4054 $reshook = $hookmanager->executeHooks(
'changeRoundingMode', $parameters, $this, $action);
4056 if (empty($reshook) && $forcedroundingmode ==
'0') {
4058 $localtax_array = array($obj->localtax1_type, $obj->localtax1_tx, $obj->localtax2_type, $obj->localtax2_tx);
4059 $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);
4061 $diff_when_using_price_ht =
price2num((
float) $tmpcal[1] - $obj->total_tva,
'MT', 1);
4062 $diff_on_current_total =
price2num($obj->total_ttc - $obj->total_ht - $obj->total_tva - $obj->total_localtax1 - $obj->total_localtax2,
'MT', 1);
4066 if ($diff_on_current_total) {
4068 $sqlfix =
"UPDATE ".$this->db->prefix().$this->table_element_line;
4069 $sqlfix .=
" SET ".$this->db->sanitize($fieldtva).
" = ".
price2num((
float) $tmpcal[1]).
", total_ttc = ".
price2num((
float) $tmpcal[2]);
4070 $sqlfix .=
", multicurrency_total_tva = ".price2num((
float) $tmpcal[17]).
", multicurrency_total_ttc = ".
price2num((
float) $tmpcal[18]);
4071 $sqlfix .=
" WHERE rowid = ".((int) $obj->rowid);
4072 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);
4073 $resqlfix = $this->db->query($sqlfix);
4077 $obj->total_tva = $tmpcal[1];
4078 $obj->total_ttc = $tmpcal[2];
4079 $obj->multicurrency_total_tva = $tmpcal[17];
4080 $obj->multicurrency_total_ttc = $tmpcal[18];
4081 } elseif ($diff_when_using_price_ht) {
4084 if ((
float) $tmpcal[0] == (
float) $obj->total_ht) {
4089 $sqlfix =
"UPDATE ".$this->db->prefix().$this->table_element_line;
4090 $sqlfix .=
" SET ".$this->db->sanitize($fieldtva).
" = ".
price2num((
float) $tmpcal[1]).
", total_ttc = ".
price2num((
float) $tmpcal[2]);
4091 $sqlfix .=
", multicurrency_total_tva = ".price2num((
float) $tmpcal[17]).
", multicurrency_total_ttc = ".
price2num((
float) $tmpcal[18]);
4092 $sqlfix .=
" WHERE rowid = ".((int) $obj->rowid);
4093 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);
4094 $resqlfix = $this->db->query($sqlfix);
4098 $obj->total_tva = $tmpcal[1];
4099 $obj->total_ttc = $tmpcal[2];
4100 $obj->multicurrency_total_tva = $tmpcal[17];
4101 $obj->multicurrency_total_ttc = $tmpcal[18];
4106 $this->total_ht += $obj->total_ht;
4107 $this->total_tva += $obj->total_tva;
4108 $this->total_localtax1 += $obj->total_localtax1;
4109 $this->total_localtax2 += $obj->total_localtax2;
4110 $this->total_ttc += $obj->total_ttc;
4111 $this->multicurrency_total_ht += $obj->multicurrency_total_ht;
4112 $this->multicurrency_total_tva += $obj->multicurrency_total_tva;
4113 $this->multicurrency_total_ttc += $obj->multicurrency_total_ttc;
4115 if (!isset($total_ht_by_vats[$obj->vatrate])) {
4116 $total_ht_by_vats[$obj->vatrate] = 0;
4118 if (!isset($total_tva_by_vats[$obj->vatrate])) {
4119 $total_tva_by_vats[$obj->vatrate] = 0;
4121 if (!isset($total_ttc_by_vats[$obj->vatrate])) {
4122 $total_ttc_by_vats[$obj->vatrate] = 0;
4124 $total_ht_by_vats[$obj->vatrate] += $obj->total_ht;
4125 $total_tva_by_vats[$obj->vatrate] += $obj->total_tva;
4126 $total_ttc_by_vats[$obj->vatrate] += $obj->total_ttc;
4128 if ($forcedroundingmode ==
'1') {
4129 if ($base_price_type ==
'TTC') {
4130 $tmpvat =
price2num($total_ttc_by_vats[$obj->vatrate] * $obj->vatrate / (100 + $obj->vatrate),
'MT', 1);
4132 $tmpvat =
price2num($total_ht_by_vats[$obj->vatrate] * $obj->vatrate / 100,
'MT', 1);
4134 $diff =
price2num($total_tva_by_vats[$obj->vatrate] - (
float) $tmpvat,
'MT', 1);
4137 $maxdiff = (10 * pow(10, -1 *
getDolGlobalInt(
'MAIN_MAX_DECIMALS_TOT', 0)));
4138 if (abs((
float) $diff) > $maxdiff) {
4140 $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.';
4142 $this->error = $errmsg;
4147 if ($base_price_type ==
'TTC') {
4148 $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);
4149 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);
4151 $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);
4152 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);
4155 $resqlfix = $this->db->query($sqlfix);
4161 $this->total_tva = (float)
price2num($this->total_tva - (
float) $diff,
'', 1);
4162 $total_tva_by_vats[$obj->vatrate] = (float)
price2num($total_tva_by_vats[$obj->vatrate] - (
float) $diff,
'', 1);
4163 if ($base_price_type ==
'TTC') {
4164 $this->total_ht = (float)
price2num($this->total_ht + (
float) $diff,
'', 1);
4165 $total_ht_by_vats[$obj->vatrate] = (float)
price2num($total_ht_by_vats[$obj->vatrate] + (
float) $diff,
'', 1);
4167 $this->total_ttc = (float)
price2num($this->total_ttc - (
float) $diff,
'', 1);
4168 $total_ttc_by_vats[$obj->vatrate] = (float)
price2num($total_ttc_by_vats[$obj->vatrate] - (
float) $diff,
'', 1);
4178 $this->total_ttc += isset($this->revenuestamp) ? $this->revenuestamp : 0;
4180 $this->multicurrency_total_ttc += isset($this->revenuestamp) ? ($this->revenuestamp * $multicurrency_tx) : 0;
4183 if (!empty($this->situation_cycle_ref) && !empty($this->situation_counter) && $this->situation_counter > 1 && method_exists($this,
'get_prev_sits')) {
4184 '@phan-var-force Facture $this';
4185 include_once DOL_DOCUMENT_ROOT.
'/compta/facture/class/facture.class.php';
4188 $prev_sits = $this->get_prev_sits();
4190 foreach ($prev_sits as $sit) {
4191 $this->total_ht -= $sit->total_ht;
4192 $this->total_tva -= $sit->total_tva;
4193 $this->total_localtax1 -= $sit->total_localtax1;
4194 $this->total_localtax2 -= $sit->total_localtax2;
4195 $this->total_ttc -= $sit->total_ttc;
4196 $this->multicurrency_total_ht -= $sit->multicurrency_total_ht;
4197 $this->multicurrency_total_tva -= $sit->multicurrency_total_tva;
4198 $this->multicurrency_total_ttc -= $sit->multicurrency_total_ttc;
4205 $this->total_ht = (float)
price2num($this->total_ht);
4206 $this->total_tva = (float)
price2num($this->total_tva);
4207 $this->total_localtax1 = (float)
price2num($this->total_localtax1);
4208 $this->total_localtax2 = (float)
price2num($this->total_localtax2);
4209 $this->total_ttc = (float)
price2num($this->total_ttc);
4211 $this->db->free($resql);
4214 $fieldht =
'total_ht';
4216 $fieldlocaltax1 =
'localtax1';
4217 $fieldlocaltax2 =
'localtax2';
4218 $fieldttc =
'total_ttc';
4220 if (in_array($this->element, array(
'propal',
'commande',
'facture',
'facturerec',
'supplier_proposal',
'order_supplier',
'facture_fourn',
'invoice_supplier',
'invoice_supplier_rec',
'expensereport'))) {
4221 $fieldtva =
'total_tva';
4224 if (!$error && empty($nodatabaseupdate)) {
4225 $sql =
"UPDATE ".$this->db->prefix().$this->table_element.
' SET';
4226 $sql .=
" ".$this->db->sanitize($fieldht).
" = ".((float)
price2num($this->total_ht,
'MT', 1)).
",";
4227 $sql .=
" ".$this->db->sanitize($fieldtva).
" = ".((float)
price2num($this->total_tva,
'MT', 1)).
",";
4228 $sql .=
" ".$this->db->sanitize($fieldlocaltax1).
" = ".((float)
price2num($this->total_localtax1,
'MT', 1)).
",";
4229 $sql .=
" ".$this->db->sanitize($fieldlocaltax2).
" = ".((float)
price2num($this->total_localtax2,
'MT', 1)).
",";
4230 $sql .=
" ".$this->db->sanitize($fieldttc).
" = ".((float)
price2num($this->total_ttc,
'MT', 1));
4231 $sql .=
", multicurrency_total_ht = ".((float)
price2num($this->multicurrency_total_ht,
'MT', 1));
4232 $sql .=
", multicurrency_total_tva = ".((float)
price2num($this->multicurrency_total_tva,
'MT', 1));
4233 $sql .=
", multicurrency_total_ttc = ".((float)
price2num($this->multicurrency_total_ttc,
'MT', 1));
4234 $sql .=
" WHERE rowid = ".((int) $this->
id);
4236 dol_syslog(get_class($this).
"::update_price", LOG_DEBUG);
4237 $resql = $this->db->query($sql);
4241 $this->error = $this->db->lasterror();
4242 $this->errors[] = $this->db->lasterror();
4247 $this->db->commit();
4250 $this->db->rollback();
4270 public function add_object_linked($origin =
null, $origin_id =
null, $f_user =
null, $notrigger = 0)
4273 global $user, $hookmanager, $action;
4275 if (empty($this->origin_type) && !empty($this->origin)) {
4276 $this->origin_type = $this->origin;
4278 $origin = (!empty($origin) ? $origin : $this->origin_type);
4279 $origin_id = (!empty($origin_id) ? $origin_id : $this->origin_id);
4280 $f_user = isset($f_user) ? $f_user : $user;
4283 if ($origin ==
'order') {
4284 $origin =
'commande';
4286 if ($origin ==
'invoice') {
4287 $origin =
'facture';
4289 if ($origin ==
'invoice_template') {
4290 $origin =
'facturerec';
4292 if ($origin ==
'supplierorder') {
4293 $origin =
'order_supplier';
4297 $targettype = $this->getElementType();
4299 $parameters = array(
'targettype' => $targettype);
4301 $reshook = $hookmanager->executeHooks(
'setLinkedObjectSourceTargetType', $parameters, $this, $action);
4303 if (!empty($hookmanager->resArray[
'targettype'])) {
4304 $targettype = $hookmanager->resArray[
'targettype'];
4311 $sql =
"INSERT INTO " . $this->db->prefix() .
"element_element (";
4312 $sql .=
"fk_source";
4313 $sql .=
", sourcetype";
4314 $sql .=
", fk_target";
4315 $sql .=
", targettype";
4316 $sql .=
") VALUES (";
4317 $sql .= ((int) $origin_id);
4318 $sql .=
", '" . $this->db->escape($origin) .
"'";
4319 $sql .=
", " . ((int) $this->
id);
4320 $sql .=
", '" . $this->db->escape($targettype) .
"'";
4323 dol_syslog(get_class($this) .
"::add_object_linked", LOG_DEBUG);
4324 if ($this->db->query($sql)) {
4327 $this->context[
'link_origin'] = $origin;
4328 $this->context[
'link_origin_id'] = $origin_id;
4329 $result = $this->call_trigger(
'OBJECT_LINK_INSERT', $f_user);
4336 $this->error = $this->db->lasterror();
4341 $this->db->commit();
4344 $this->db->rollback();
4358 $coreModule = array(
'knowledgemanagement',
'partnership',
'workstation',
'ticket',
'recruitment',
'eventorganization',
'asset');
4360 return ((!empty($this->module) && !in_array($this->module, $coreModule)) ? $this->module.
'_' :
'').$this->element;
4386 public function fetchObjectLinked($sourceid =
null, $sourcetype =
'', $targetid =
null, $targettype =
'', $clause =
'OR', $alsosametype = 1, $orderby =
'sourcetype', $loadalsoobjects = 1)
4388 global $hookmanager, $action;
4393 if ($this->
id > 0 && !empty($this->linkedObjectsFullLoaded[$this->
id])) {
4397 $this->linkedObjectsIds = array();
4398 $this->linkedObjects = array();
4400 $justsource =
false;
4401 $justtarget =
false;
4402 $withtargettype =
false;
4403 $withsourcetype =
false;
4406 if (is_object($hookmanager)) {
4407 $parameters = array(
'sourcetype' => $sourcetype,
'sourceid' => $sourceid,
'targettype' => $targettype,
'targetid' => $targetid);
4408 $reshook = $hookmanager->executeHooks(
'setLinkedObjectSourceTargetType', $parameters, $this, $action);
4410 if (!empty($hookmanager->resArray[
'sourcetype'])) {
4411 $sourcetype = $hookmanager->resArray[
'sourcetype'];
4413 if (!empty($hookmanager->resArray[
'sourceid'])) {
4414 $sourceid = $hookmanager->resArray[
'sourceid'];
4416 if (!empty($hookmanager->resArray[
'targettype'])) {
4417 $targettype = $hookmanager->resArray[
'targettype'];
4419 if (!empty($hookmanager->resArray[
'targetid'])) {
4420 $targetid = $hookmanager->resArray[
'targetid'];
4425 if (!empty($sourceid) && !empty($sourcetype) && empty($targetid)) {
4427 if (!empty($targettype)) {
4428 $withtargettype =
true;
4431 if (!empty($targetid) && !empty($targettype) && empty($sourceid)) {
4433 if (!empty($sourcetype)) {
4434 $withsourcetype =
true;
4438 $sourceid = (!empty($sourceid) ? $sourceid :
$this->id);
4439 $targetid = (!empty($targetid) ? $targetid :
$this->id);
4440 $sourcetype = (!empty($sourcetype) ? $sourcetype : $this->getElementType());
4441 $targettype = (!empty($targettype) ? $targettype : $this->getElementType());
4450 $sql =
"SELECT rowid, fk_source, sourcetype, fk_target, targettype";
4451 $sql .=
" FROM ".$this->db->prefix().
"element_element";
4453 if ($justsource || $justtarget) {
4455 $sql .=
"fk_source = ".((int) $sourceid).
" AND sourcetype = '".$this->db->escape($sourcetype).
"'";
4456 if ($withtargettype) {
4457 $sql .=
" AND targettype = '".$this->db->escape($targettype).
"'";
4459 } elseif ($justtarget) {
4460 $sql .=
"fk_target = ".((int) $targetid).
" AND targettype = '".$this->db->escape($targettype).
"'";
4461 if ($withsourcetype) {
4462 $sql .=
" AND sourcetype = '".$this->db->escape($sourcetype).
"'";
4466 $sql .=
"(fk_source = ".((int) $sourceid).
" AND sourcetype = '".$this->db->escape($sourcetype).
"')";
4467 $sql .=
" ".$this->db->sanitize($clause).
" (fk_target = ".((int) $targetid).
" AND targettype = '".$this->db->escape($targettype).
"')";
4468 if ($loadalsoobjects && $this->
id > 0 && $sourceid == $this->
id && $sourcetype == $this->element && $targetid == $this->
id && $targettype == $this->element && $clause ==
'OR') {
4469 $this->linkedObjectsFullLoaded[
$this->id] =
true;
4472 $sql .=
" ORDER BY ".$orderby;
4474 dol_syslog(get_class($this).
"::fetchObjectLink", LOG_DEBUG);
4475 $resql = $this->db->query($sql);
4477 $num = $this->db->num_rows($resql);
4480 $obj = $this->db->fetch_object($resql);
4481 if ($justsource || $justtarget) {
4483 $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
4484 } elseif ($justtarget) {
4485 $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
4488 if ($obj->fk_source == $sourceid && $obj->sourcetype == $sourcetype) {
4489 $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
4491 if ($obj->fk_target == $targetid && $obj->targettype == $targettype) {
4492 $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
4498 if (!empty($this->linkedObjectsIds)) {
4499 $tmparray = $this->linkedObjectsIds;
4500 foreach ($tmparray as $objecttype => $objectids) {
4502 $element = $element_properties[
'element'];
4503 $classPath = $element_properties[
'classpath'];
4504 $classFile = $element_properties[
'classfile'];
4505 $className = $element_properties[
'classname'];
4506 $module = $element_properties[
'module'];
4509 if (isModEnabled($module) && (($element != $this->element) || $alsosametype)) {
4510 if ($loadalsoobjects && (is_numeric($loadalsoobjects) || ($loadalsoobjects === $objecttype))) {
4512 if (class_exists($className)) {
4513 foreach ($objectids as $i => $objectid) {
4514 $object =
new $className($this->db);
4515 '@phan-var-force CommonObject $object';
4516 $ret =
$object->fetch($objectid);
4518 $this->linkedObjects[$objecttype][$i] =
$object;
4524 unset($this->linkedObjectsIds[$objecttype]);
4543 if ($this->
id > 0 && !empty($this->linkedObjectsFullLoaded[$this->
id])) {
4544 unset($this->linkedObjectsFullLoaded[$this->
id]);
4562 public function updateObjectLinked($sourceid =
null, $sourcetype =
'', $targetid =
null, $targettype =
'', $f_user =
null, $notrigger = 0)
4565 $updatesource =
false;
4566 $updatetarget =
false;
4567 $f_user = isset($f_user) ? $f_user : $user;
4569 if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) {
4570 $updatesource =
true;
4571 } elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) {
4572 $updatetarget =
true;
4578 $sql =
"UPDATE " . $this->db->prefix() .
"element_element SET ";
4579 if ($updatesource) {
4580 $sql .=
"fk_source = " . ((int) $sourceid);
4581 $sql .=
", sourcetype = '" . $this->db->escape($sourcetype) .
"'";
4582 $sql .=
" WHERE fk_target = " . ((int) $this->
id);
4583 $sql .=
" AND targettype = '" . $this->db->escape($this->element) .
"'";
4584 } elseif ($updatetarget) {
4585 $sql .=
"fk_target = " . ((int) $targetid);
4586 $sql .=
", targettype = '" . $this->db->escape($targettype) .
"'";
4587 $sql .=
" WHERE fk_source = " . ((int) $this->
id);
4588 $sql .=
" AND sourcetype = '" . $this->db->escape($this->element) .
"'";
4591 dol_syslog(get_class($this) .
"::updateObjectLinked", LOG_DEBUG);
4592 if ($this->db->query($sql)) {
4595 $this->context[
'link_source_id'] = $sourceid;
4596 $this->context[
'link_source_type'] = $sourcetype;
4597 $this->context[
'link_target_id'] = $targetid;
4598 $this->context[
'link_target_type'] = $targettype;
4599 $result = $this->call_trigger(
'OBJECT_LINK_MODIFY', $f_user);
4606 $this->error = $this->db->lasterror();
4611 $this->db->commit();
4614 $this->db->rollback();
4632 public function deleteObjectLinked($sourceid =
null, $sourcetype =
'', $targetid =
null, $targettype =
'', $rowid = 0, $f_user =
null, $notrigger = 0)
4635 $deletesource =
false;
4636 $deletetarget =
false;
4637 $f_user = isset($f_user) ? $f_user : $user;
4639 if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) {
4640 $deletesource =
true;
4641 } elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) {
4642 $deletetarget =
true;
4645 $element = $this->getElementType();
4646 $sourceid = (!empty($sourceid) ? $sourceid :
$this->id);
4647 $sourcetype = (!empty($sourcetype) ? $sourcetype : $element);
4648 $targetid = (!empty($targetid) ? $targetid :
$this->id);
4649 $targettype = (!empty($targettype) ? $targettype : $element);
4655 $this->context[
'link_id'] = $rowid;
4656 $this->context[
'link_source_id'] = $sourceid;
4657 $this->context[
'link_source_type'] = $sourcetype;
4658 $this->context[
'link_target_id'] = $targetid;
4659 $this->context[
'link_target_type'] = $targettype;
4660 $result = $this->call_trigger(
'OBJECT_LINK_DELETE', $f_user);
4668 $sql =
"DELETE FROM " . $this->db->prefix() .
"element_element";
4671 $sql .=
" rowid = " . ((int) $rowid);
4673 if ($deletesource) {
4674 $sql .=
" fk_source = " . ((int) $sourceid) .
" AND sourcetype = '" . $this->db->escape($sourcetype) .
"'";
4675 $sql .=
" AND fk_target = " . ((int) $this->
id) .
" AND targettype = '" . $this->db->escape($element) .
"'";
4676 } elseif ($deletetarget) {
4677 $sql .=
" fk_target = " . ((int) $targetid) .
" AND targettype = '" . $this->db->escape($targettype) .
"'";
4678 $sql .=
" AND fk_source = " . ((int) $this->
id) .
" AND sourcetype = '" . $this->db->escape($element) .
"'";
4680 $sql .=
" (fk_source = " . ((int) $this->
id) .
" AND sourcetype = '" . $this->db->escape($element) .
"')";
4682 $sql .=
" (fk_target = " . ((int) $this->
id) .
" AND targettype = '" . $this->db->escape($element) .
"')";
4686 dol_syslog(get_class($this) .
"::deleteObjectLinked", LOG_DEBUG);
4687 if (!$this->db->query($sql)) {
4688 $this->error = $this->db->lasterror();
4689 $this->errors[] = $this->error;
4695 $this->db->commit();
4698 $this->db->rollback();
4714 if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
4717 if (!preg_match(
'/^[_a-zA-Z0-9]+$/', $field_select)) {
4718 dol_syslog(
'Invalid value $field_select for parameter '.$field_select.
' in call to getAllItemsLinkedByObjectID(). Must be a single field name.', LOG_ERR);
4723 $sql =
"SELECT ".$field_select.
" FROM ".$db->prefix().$table_element.
" WHERE ".$field_where.
" = ".((int) $fk_object_where);
4724 $resql = $db->query($sql);
4727 if (!empty($resql)) {
4728 while ($res = $db->fetch_object($resql)) {
4729 $TRes[] = $res->{$field_select};
4746 if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
4752 $sql =
"SELECT COUNT(*) as nb FROM ".$db->prefix().$table_element.
" WHERE ".$field_where.
" = ".((int) $fk_object_where);
4753 $resql = $db->query($sql);
4756 $res = $db->fetch_object($resql);
4775 if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
4781 $sql =
"DELETE FROM ".$db->prefix().$table_element.
" WHERE ".$field_where.
" = ".((int) $fk_object_where);
4782 $resql = $db->query($sql);
4784 if (empty($resql)) {
4801 public function setStatut($status, $elementId =
null, $elementType =
'', $trigkey =
'', $fieldstatus =
'fk_statut')
4805 $savElementId = $elementId;
4807 $elementId = (!empty($elementId) ? $elementId :
$this->id);
4808 $elementTable = (!empty($elementType) ? $elementType : $this->table_element);
4812 if ($elementTable ==
'facture_rec') {
4813 $fieldstatus =
"suspended";
4815 if ($elementTable ==
'mailing') {
4816 $fieldstatus =
"statut";
4818 if ($elementTable ==
'cronjob') {
4819 $fieldstatus =
"status";
4821 if ($elementTable ==
'user') {
4822 $fieldstatus =
"statut";
4824 if ($elementTable ==
'expensereport') {
4825 $fieldstatus =
"fk_statut";
4827 if ($elementTable ==
'receptiondet_batch') {
4828 $fieldstatus =
"status";
4830 if ($elementTable ==
'prelevement_bons') {
4831 $fieldstatus =
"statut";
4833 if (isset($this->fields) && is_array($this->fields) && array_key_exists(
'status', $this->fields)) {
4834 $fieldstatus =
'status';
4837 $sql =
"UPDATE ".$this->db->prefix().$this->db->sanitize($elementTable);
4838 $sql .=
" SET ".$this->db->sanitize($fieldstatus).
" = ".((int) $status);
4841 if ($status == 1 && in_array($elementTable, array(
'expensereport',
'inventory'))) {
4842 $sql .=
", fk_user_valid = ".((int) $user->id);
4844 if ($status == 1 && in_array($elementTable, array(
'expensereport'))) {
4845 $sql .=
", date_valid = '".$this->db->idate(
dol_now()).
"'";
4847 if ($status == 1 && in_array($elementTable, array(
'inventory'))) {
4848 $sql .=
", date_validation = '".$this->db->idate(
dol_now()).
"'";
4850 $sql .=
" WHERE rowid = ".((int) $elementId);
4851 $sql .=
" AND ".$fieldstatus.
" <> ".((int) $status);
4853 dol_syslog(get_class($this).
"::setStatut", LOG_DEBUG);
4854 $resql = $this->db->query($sql);
4858 $nb_rows_affected = $this->db->affected_rows($resql);
4860 if ($nb_rows_affected > 0) {
4861 if (empty($trigkey)) {
4863 if ($this->element ==
'supplier_proposal' && $status == 2) {
4864 $trigkey =
'SUPPLIER_PROPOSAL_SIGN';
4866 if ($this->element ==
'supplier_proposal' && $status == 3) {
4867 $trigkey =
'SUPPLIER_PROPOSAL_REFUSE';
4869 if ($this->element ==
'supplier_proposal' && $status == 4) {
4870 $trigkey =
'SUPPLIER_PROPOSAL_CLOSE';
4872 if ($this->element ==
'fichinter' && $status == 3) {
4873 $trigkey =
'FICHINTER_CLASSIFY_DONE';
4875 if ($this->element ==
'fichinter' && $status == 2) {
4876 $trigkey =
'FICHINTER_CLASSIFY_BILLED';
4878 if ($this->element ==
'fichinter' && $status == 1) {
4879 $trigkey =
'FICHINTER_CLASSIFY_UNBILLED';
4883 $this->context = array_merge($this->context, array(
'newstatus' => $status));
4889 $result = $this->call_trigger($trigkey, $user);
4900 $this->db->commit();
4902 if (empty($savElementId)) {
4904 if ($fieldstatus ==
'tosell') {
4906 } elseif ($fieldstatus ==
'tobuy') {
4907 $this->status_buy = $status;
4908 } elseif ($fieldstatus ==
'tobatch') {
4909 $this->status_batch = $status;
4917 $this->db->rollback();
4918 dol_syslog(get_class($this).
"::setStatut ".$this->error, LOG_ERR);
4922 $this->error = $this->db->lasterror();
4923 $this->db->rollback();
4938 if (empty(
$id) && empty($ref)) {
4948 $sql =
"SELECT rowid, canvas";
4949 $sql .=
" FROM ".$this->db->prefix().$this->table_element;
4950 $sql .=
" WHERE entity IN (".getEntity($this->element).
")";
4952 $sql .=
" AND rowid = ".((int)
$id);
4955 $sql .=
" AND ref = '".$this->db->escape($ref).
"'";
4958 $resql = $this->db->query($sql);
4960 $obj = $this->db->fetch_object($resql);
4962 $this->canvas = $obj->canvas;
4982 $sql =
"SELECT special_code FROM ".$this->db->prefix().$this->table_element_line;
4983 $sql .=
" WHERE rowid = ".((int) $lineid);
4984 $resql = $this->db->query($sql);
4986 $row = $this->db->fetch_row($resql);
4987 return (!empty($row[0]) ? $row[0] : 0);
5010 if (!isset($this->childtables) || !is_array($this->childtables) || count($this->childtables) == 0) {
5011 dol_print_error(
null,
'Called isObjectUsed on a class with property this->childtables not defined');
5015 $arraytoscan = $this->childtables;
5017 $tmparray = array_keys($this->childtables);
5018 if (is_numeric($tmparray[0])) {
5019 $arraytoscan = array_flip($this->childtables);
5024 foreach ($arraytoscan as $table => $element) {
5028 if (isset($element[
'enabled']) && !empty($element[
'enabled'])) {
5029 $enabled = (int)
dol_eval((
string) $element[
'enabled'], 1);
5030 if (empty($enabled)) {
5036 $sql =
"SELECT COUNT(*) as nb";
5037 $sql .=
" FROM ".$this->db->prefix().$table.
" as c";
5038 if (!empty($element[
'parent']) && !empty($element[
'parentkey'])) {
5039 $sql .=
", ".$this->db->prefix().$element[
'parent'].
" as p";
5041 if (!empty($element[
'fk_element'])) {
5042 $sql .=
" WHERE c.".$element[
'fk_element'].
" = ".((int)
$id);
5044 $sql .=
" WHERE c.".$this->fk_element.
" = ".((int)
$id);
5046 if (!empty($element[
'parent']) && !empty($element[
'parentkey'])) {
5047 $sql .=
" AND c.".$element[
'parentkey'].
" = p.rowid";
5049 if (!empty($element[
'parent']) && !empty($element[
'parenttypefield']) && !empty($element[
'parenttypevalue'])) {
5050 $sql .=
" AND c.".$element[
'parenttypefield'].
" = '".$this->db->escape($element[
'parenttypevalue']).
"'";
5052 if (!empty($entity)) {
5053 if (!empty($element[
'parent']) && !empty($element[
'parentkey'])) {
5054 $sql .=
" AND p.entity = ".((int) $entity);
5056 $sql .=
" AND c.entity = ".((int) $entity);
5060 $resql = $this->db->query($sql);
5062 $obj = $this->db->fetch_object($resql);
5064 $langs->load(
"errors");
5066 $haschild += $obj->nb;
5067 if (is_numeric($element)) {
5068 $this->errors[] = $langs->transnoentitiesnoconv(
"ErrorRecordHasAtLeastOneChildOfType", method_exists($this,
'getNomUrl') ? $this->getNomUrl() : $this->ref, $table);
5069 } elseif (is_string($element)) {
5070 $this->errors[] = $langs->transnoentitiesnoconv(
"ErrorRecordHasAtLeastOneChildOfType", method_exists($this,
'getNomUrl') ? $this->getNomUrl() : $this->ref, $langs->transnoentitiesnoconv($element));
5072 $this->errors[] = $langs->transnoentitiesnoconv(
"ErrorRecordHasAtLeastOneChildOfType", method_exists($this,
'getNomUrl') ? $this->getNomUrl() : $this->ref, $langs->transnoentitiesnoconv($element[
'name']));
5077 $this->errors[] = $this->db->lasterror();
5081 if ($haschild > 0) {
5082 $this->errors[] =
"ErrorRecordHasChildren";
5099 foreach ($this->lines as $key => $val) {
5101 if ($predefined == -1) {
5104 if ($predefined == 1 && $val->fk_product > 0) {
5107 if ($predefined == 0 && $val->fk_product <= 0) {
5110 if ($predefined == 2 && $val->fk_product > 0 && $val->product_type == 0) {
5113 if ($predefined == 3 && $val->fk_product > 0 && $val->product_type == 1) {
5120 dol_syslog(get_class($this).
'::hasProductsOrServices we found '.$nb.
' qualified lines of products/servcies');
5131 if (!empty($this->table_element_line) && ($this->table_element_line !=
'expeditiondet')) {
5132 $total_discount = 0.00;
5134 $sql =
"SELECT subprice as pu_ht, qty, remise_percent, total_ht";
5135 $sql .=
" FROM ".$this->db->prefix().$this->table_element_line;
5136 $sql .=
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
5138 dol_syslog(get_class($this).
'::getTotalDiscount', LOG_DEBUG);
5139 $resql = $this->db->query($sql);
5141 $num = $this->db->num_rows($resql);
5144 $obj = $this->db->fetch_object($resql);
5146 $pu_ht = $obj->pu_ht;
5148 $total_ht = $obj->total_ht;
5150 $total_discount_line = (float)
price2num(($pu_ht * $qty) - $total_ht,
'MT');
5151 $total_discount += $total_discount_line;
5158 return (
float)
price2num($total_discount);
5180 if (empty($this->lines)) {
5181 return array(
'weight' => $totalWeight,
'volume' => $totalVolume,
'ordered' => $totalOrdered,
'toship' => $totalToShip);
5184 foreach ($this->lines as $line) {
5185 if (isset($line->qty_asked)) {
5186 $totalOrdered += $line->qty_asked;
5188 if (isset($line->qty_shipped)) {
5189 $totalToShip += $line->qty_shipped;
5190 } elseif ($line->element ==
'commandefournisseurdispatch' && isset($line->qty)) {
5191 if (empty($totalToShip)) {
5194 $totalToShip += $line->qty;
5198 if ($this->element ==
'shipping') {
5200 $qty = $line->qty_shipped ? $line->qty_shipped : 0;
5202 $qty = $line->qty ? $line->qty : 0;
5205 $weight = !empty($line->weight) ? $line->weight : 0;
5206 ($weight == 0 && !empty($line->product->weight)) ? $weight = $line->product->weight : 0;
5207 $volume = !empty($line->volume) ? $line->volume : 0;
5208 ($volume == 0 && !empty($line->product->volume)) ? $volume = $line->product->volume : 0;
5210 $weight_units = !empty($line->weight_units) ? $line->weight_units : 0;
5211 ($weight_units == 0 && !empty($line->product->weight_units)) ? $weight_units = $line->product->weight_units : 0;
5212 $volume_units = !empty($line->volume_units) ? $line->volume_units : 0;
5213 ($volume_units == 0 && !empty($line->product->volume_units)) ? $volume_units = $line->product->volume_units : 0;
5217 if (!empty($weight_units)) {
5218 $weightUnit = $weight_units;
5220 if (!empty($volume_units)) {
5221 $volumeUnit = $volume_units;
5224 if (empty($totalWeight)) {
5227 if (empty($totalVolume)) {
5232 if ($weight_units < 50) {
5233 $trueWeightUnit = pow(10, $weightUnit);
5234 $totalWeight += $weight * $qty * $trueWeightUnit;
5236 if ($weight_units == 99) {
5238 $trueWeightUnit = 0.45359237;
5239 $totalWeight += $weight * $qty * $trueWeightUnit;
5240 } elseif ($weight_units == 98) {
5242 $trueWeightUnit = 0.0283495;
5243 $totalWeight += $weight * $qty * $trueWeightUnit;
5245 $totalWeight += $weight * $qty;
5248 if ($volume_units < 50) {
5250 $trueVolumeUnit = pow(10, $volumeUnit);
5252 $totalVolume += $volume * $qty * $trueVolumeUnit;
5254 $totalVolume += $volume * $qty;
5258 return array(
'weight' => $totalWeight,
'volume' => $totalVolume,
'ordered' => $totalOrdered,
'toship' => $totalToShip);
5271 $extraparams = (!empty($this->extraparams) ? json_encode($this->extraparams) :
null);
5272 $extraparams =
dol_trunc($extraparams, 250);
5274 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
5275 $sql .=
" SET extraparams = ".(!empty($extraparams) ?
"'".$this->db->escape($extraparams).
"'" :
"null");
5276 $sql .=
" WHERE rowid = ".((int) $this->
id);
5278 dol_syslog(get_class($this).
"::setExtraParameters", LOG_DEBUG);
5279 $resql = $this->db->query($sql);
5281 $this->error = $this->db->lasterror();
5282 $this->db->rollback();
5285 $this->db->commit();
5308 global
$conf, $user, $langs,
$object, $hookmanager, $extrafields, $form;
5311 if (!is_object($extrafields)) {
5312 require_once DOL_DOCUMENT_ROOT.
'/core/class/extrafields.class.php';
5315 $extrafields->fetch_name_optionals_label($this->table_element_line);
5320 $dirtpls = array_merge(
$conf->modules_parts[
'tpl'], array($defaulttpldir));
5321 foreach ($dirtpls as $module => $reldir) {
5322 if (!empty($module)) {
5325 $tpl = DOL_DOCUMENT_ROOT.$reldir.
'/objectline_create.tpl.php';
5328 if (empty(
$conf->file->strict_mode)) {
5329 $res = @include $tpl;
5331 $res = include $tpl;
5358 public function printObjectLines($action, $seller, $buyer, $selected = 0, $dateSelector = 0, $defaulttpldir =
'/core/tpl')
5360 global
$conf, $hookmanager, $langs, $user, $form, $extrafields,
$object;
5362 global $inputalsopricewithtax, $usemargins, $disableedit, $disablemove, $disableremove, $outputalsopricetotalwithtax;
5366 if (isModEnabled(
'margin') && !empty($this->element) && in_array($this->element, array(
'facture',
'facturerec',
'propal',
'commande'))) {
5370 $num = count($this->lines);
5373 if (!is_object($extrafields)) {
5374 require_once DOL_DOCUMENT_ROOT.
'/core/class/extrafields.class.php';
5377 $extrafields->fetch_name_optionals_label($this->table_element_line);
5379 if (method_exists($this,
'loadExpeditions')) {
5381 $this->loadExpeditions();
5384 $parameters = array();
5385 $reshook = $hookmanager->executeHooks(
'printObjectLinesBlock', $parameters, $this, $action);
5386 if (empty($reshook)) {
5387 $parameters = array(
'num' => $num,
'dateSelector' => $dateSelector,
'seller' => $seller,
'buyer' => $buyer,
'selected' => $selected,
'table_element_line' => $this->table_element_line);
5388 $reshook = $hookmanager->executeHooks(
'printObjectLineTitle', $parameters, $this, $action);
5389 if (empty($reshook)) {
5393 $dirtpls = array_merge(
$conf->modules_parts[
'tpl'], array($defaulttpldir));
5394 foreach ($dirtpls as $module => $reldir) {
5396 if (!empty($module)) {
5399 $tpl = DOL_DOCUMENT_ROOT.$reldir.
'/objectline_title.tpl.php';
5401 if (file_exists($tpl)) {
5402 if (empty(
$conf->file->strict_mode)) {
5403 $res = @include $tpl;
5405 $res = include $tpl;
5416 print
"<!-- begin printObjectLines() -->\n";
5417 foreach ($this->lines as $line) {
5421 if (is_object($hookmanager)) {
5422 if (empty($line->fk_parent_line)) {
5423 $parameters = array(
'line' => $line,
'num' => $num,
'i' => $i,
'dateSelector' => $dateSelector,
'seller' => $seller,
'buyer' => $buyer,
'selected' => $selected,
'table_element_line' => $line->table_element,
'defaulttpldir' => $defaulttpldir);
5424 $reshook = $hookmanager->executeHooks(
'printObjectLine', $parameters, $this, $action);
5426 $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);
5427 $reshook = $hookmanager->executeHooks(
'printObjectSubLine', $parameters, $this, $action);
5430 if (empty($reshook)) {
5431 $this->printObjectLine($action, $line,
'', $num, $i, $dateSelector, $seller, $buyer, $selected, $extrafields, $defaulttpldir);
5436 print
"<!-- end printObjectLines() -->\n";
5457 public function printObjectLine($action, $line, $var, $num, $i, $dateSelector, $seller, $buyer, $selected = 0, $extrafields =
null, $defaulttpldir =
'/core/tpl')
5461 global $disableedit, $disablemove, $disableremove;
5468 if ($action !=
'editline' || $selected != $line->id) {
5470 if (!empty($line->fk_product) && $line->fk_product > 0) {
5471 $product_static =
new Product($this->db);
5472 $product_static->fetch($line->fk_product);
5474 $product_static->ref = $line->ref;
5475 $product_static->label = !empty($line->label) ? $line->label :
"";
5477 $text = $product_static->getNomUrl(1);
5482 if (property_exists($this,
'socid') && !empty($this->socid) && !is_object($this->thirdparty)) {
5483 dol_print_error(
null,
'Error: Method printObjectLine was called on an object and object->fetch_thirdparty was not done before');
5487 $prod =
new Product($this->db);
5488 $prod->fetch($line->fk_product);
5490 $outputlangs = $langs;
5492 if (empty($newlang) &&
GETPOST(
'lang_id',
'aZ09')) {
5493 $newlang =
GETPOST(
'lang_id',
'aZ09');
5495 if (
getDolGlobalString(
'PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE') && empty($newlang) && is_object($this->thirdparty)) {
5496 $newlang = $this->thirdparty->default_lang;
5498 if (!empty($newlang)) {
5500 $outputlangs->setDefaultLang($newlang);
5503 $label = (!empty($prod->multilangs[$outputlangs->defaultlang][
"label"])) ? $prod->multilangs[$outputlangs->defaultlang][
"label"] : $line->product_label;
5505 $label = $line->product_label;
5508 $text .=
' - '.(!empty($line->label) ? $line->label : $label);
5509 $description .= (
getDolGlobalInt(
'PRODUIT_DESC_IN_FORM_ACCORDING_TO_DEVICE') ?
'' : (!empty($line->description) ?
dol_htmlentitiesbr($line->description) :
''));
5512 $line->pu_ttc =
price2num((!empty($line->subprice) ? $line->subprice : 0) * (1 + ((!empty($line->tva_tx) ? $line->tva_tx : 0) / 100)),
'MU');
5519 if (isset($this->expeditions[$line->id])) {
5520 $qty_shipped = $this->expeditions[$line->id];
5522 $disableedit = ($qty_shipped > 0) && ($qty_shipped >= $line->qty);
5524 $dirtpls = array_merge(
$conf->modules_parts[
'tpl'], array($defaulttpldir));
5525 foreach ($dirtpls as $module => $reldir) {
5527 if (!empty($module)) {
5530 $tpl = DOL_DOCUMENT_ROOT.$reldir.
'/objectline_view.tpl.php';
5533 if (file_exists($tpl)) {
5534 if (empty(
$conf->file->strict_mode)) {
5535 $res = @include $tpl;
5537 $res = include $tpl;
5547 if ($this->
status == 0 && $action ==
'editline' && $selected == $line->id) {
5548 $label = (!empty($line->label) ? $line->label : (($line->fk_product > 0) ? $line->product_label :
''));
5550 $line->pu_ttc =
price2num($line->subprice * (1 + ($line->tva_tx / 100)),
'MU');
5555 $dirtpls = array_merge(
$conf->modules_parts[
'tpl'], array($defaulttpldir));
5556 foreach ($dirtpls as $module => $reldir) {
5557 if (!empty($module)) {
5560 $tpl = DOL_DOCUMENT_ROOT.$reldir.
'/objectline_edit.tpl.php';
5563 if (empty(
$conf->file->strict_mode)) {
5564 $res = @include $tpl;
5566 $res = include $tpl;
5591 global $langs, $hookmanager, $form, $action;
5593 print
'<!-- printOriginLinesList '.get_class($this).
' -->'.
"\n";
5594 print
'<tr class="liste_titre">';
5595 print
'<td class="linecolref">'.$langs->trans(
'Ref').
'</td>';
5596 print
'<td class="linecoldescription">'.$langs->trans(
'Description').
'</td>';
5597 print
'<td class="linecolvat right">'.$langs->trans(
'VATRate').
'</td>';
5598 print
'<td class="linecoluht right">'.$langs->trans(
'PriceUHT').
'</td>';
5599 if (isModEnabled(
"multicurrency")) {
5600 print
'<td class="linecoluht_currency right">'.$langs->trans(
'PriceUHTCurrency').
'</td>';
5602 print
'<td class="linecolqty right">'.$langs->trans(
'Qty').
'</td>';
5604 print
'<td class="linecoluseunit left">'.$langs->trans(
'Unit').
'</td>';
5606 print
'<td class="linecoldiscount right">'.$langs->trans(
'ReductionShort').
'</td>';
5607 print
'<td class="linecolht right">'.$langs->trans(
'TotalHT').
'</td>';
5608 print
'<td class="center">';
5609 print $form->showCheckAddButtons(
'checkforselect', 1);
5614 if (!empty($this->lines)) {
5615 foreach ($this->lines as $line) {
5618 if (is_object($hookmanager)) {
5619 $parameters = array(
'line' => $line,
'i' => $i,
'restrictlist' => $restrictlist,
'selectedLines' => $selectedLines);
5620 if (!empty($line->fk_parent_line)) {
5621 $parameters[
'fk_parent_line'] = $line->fk_parent_line;
5623 $reshook = $hookmanager->executeHooks(
'printOriginObjectLine', $parameters, $this, $action);
5625 if (empty($reshook)) {
5626 $this->printOriginLine($line,
'', $restrictlist,
'/core/tpl', $selectedLines);
5647 public function printOriginLine($line, $var, $restrictlist =
'', $defaulttpldir =
'/core/tpl', $selectedLines = array())
5649 global $langs,
$conf;
5652 if (!empty($line->date_start)) {
5654 $date_start = $line->date_start;
5656 $date_start = $line->date_debut_prevue;
5657 if ($line->date_debut_reel) {
5658 $date_start = $line->date_debut_reel;
5661 if (!empty($line->date_end)) {
5663 $date_end = $line->date_end;
5665 $date_end = $line->date_fin_prevue;
5666 if ($line->date_fin_reel) {
5667 $date_end = $line->date_fin_reel;
5672 $this->tpl[
'id'] = $line->id;
5674 $this->tpl[
'label'] =
'';
5675 if (!empty($line->fk_parent_line)) {
5676 $this->tpl[
'label'] .=
img_picto(
'',
'rightarrow');
5679 if (($line->info_bits & 2) == 2) {
5681 if (property_exists($this,
'socid')) {
5682 $discount->fk_soc = $this->socid;
5683 $discount->socid = $this->socid;
5685 $this->tpl[
'label'] .= $discount->getNomUrl(0,
'discount');
5686 } elseif (!empty($line->fk_product)) {
5687 $productstatic =
new Product($this->db);
5688 $productstatic->id = $line->fk_product;
5689 $productstatic->ref = $line->ref;
5690 $productstatic->type = $line->fk_product_type;
5691 if (empty($productstatic->ref)) {
5692 $line->fetch_product();
5693 $productstatic = $line->product;
5696 $this->tpl[
'label'] .= $productstatic->getNomUrl(1);
5697 $this->tpl[
'label'] .=
' - '.(!empty($line->label) ? $line->label : $line->product_label);
5699 if ($line->product_type == 1 && ($date_start || $date_end)) {
5703 $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"')));
5704 if (!empty($line->desc)) {
5705 $this->tpl[
'label'] .= $line->desc;
5707 $this->tpl[
'label'] .= ($line->label ?
' '.$line->label :
'');
5711 if ($line->product_type == 1 && ($date_start || $date_end)) {
5716 if (!empty($line->desc)) {
5717 '@phan-var-force OrderLine|FactureLigne|ContratLigne|FactureFournisseurLigneRec|SupplierInvoiceLine|SupplierProposalLine $line';
5718 if ($line->desc ==
'(CREDIT_NOTE)') {
5720 $discount->fetch($line->fk_remise_except);
5721 $this->tpl[
'description'] = $langs->transnoentities(
"DiscountFromCreditNote", $discount->getNomUrl(0));
5722 } elseif ($line->desc ==
'(DEPOSIT)') {
5724 $discount->fetch($line->fk_remise_except);
5725 $this->tpl[
'description'] = $langs->transnoentities(
"DiscountFromDeposit", $discount->getNomUrl(0));
5726 } elseif ($line->desc ==
'(EXCESS RECEIVED)') {
5728 $discount->fetch($line->fk_remise_except);
5729 $this->tpl[
'description'] = $langs->transnoentities(
"DiscountFromExcessReceived", $discount->getNomUrl(0));
5730 } elseif ($line->desc ==
'(EXCESS PAID)') {
5732 $discount->fetch($line->fk_remise_except);
5733 $this->tpl[
'description'] = $langs->transnoentities(
"DiscountFromExcessPaid", $discount->getNomUrl(0));
5735 $this->tpl[
'description'] =
dol_trunc($line->desc, 60);
5738 $this->tpl[
'description'] =
' ';
5742 $this->tpl[
'vat_rate'] =
vatrate($line->tva_tx,
true);
5743 $this->tpl[
'vat_rate'] .= (($line->info_bits & 1) == 1) ?
'*' :
'';
5744 if (!empty($line->vat_src_code) && !preg_match(
'/\(/', $this->tpl[
'vat_rate'])) {
5745 $this->tpl[
'vat_rate'] .=
' ('.$line->vat_src_code.
')';
5748 $this->tpl[
'price'] =
price($line->subprice);
5749 $this->tpl[
'total_ht'] =
price($line->total_ht);
5750 $this->tpl[
'multicurrency_price'] =
price($line->multicurrency_subprice);
5751 $this->tpl[
'qty'] = (($line->info_bits & 2) != 2) ? $line->qty :
' ';
5753 $this->tpl[
'unit'] = $line->getLabelOfUnit(
'long', $langs);
5754 $this->tpl[
'unit_short'] = $line->getLabelOfUnit(
'short', $langs);
5757 $this->tpl[
'remise_percent'] = (($line->info_bits & 2) != 2) ?
vatrate((
string) $line->remise_percent,
true) :
' ';
5760 $this->tpl[
'strike'] = 0;
5762 $this->tpl[
'strike'] = 1;
5763 } elseif ($line->special_code == SUBTOTALS_SPECIAL_CODE) {
5764 $this->tpl[
'strike'] = 1;
5769 $dirtpls = array_merge(
$conf->modules_parts[
'tpl'], array($defaulttpldir));
5770 foreach ($dirtpls as $module => $reldir) {
5771 if (!empty($module)) {
5774 $tpl = DOL_DOCUMENT_ROOT.$reldir.
'/originproductline.tpl.php';
5777 if (empty(
$conf->file->strict_mode)) {
5778 $res = @include $tpl;
5780 $res = include $tpl;
5805 $sql =
"INSERT INTO ".$this->db->prefix().
"element_resources (";
5806 $sql .=
"resource_id";
5807 $sql .=
", resource_type";
5808 $sql .=
", element_id";
5809 $sql .=
", element_type";
5811 $sql .=
", mandatory";
5812 $sql .=
") VALUES (";
5813 $sql .= ((int) $resource_id);
5814 $sql .=
", '".$this->db->escape($resource_type).
"'";
5815 $sql .=
", '".$this->db->escape((
string) $this->
id).
"'";
5816 $sql .=
", '".$this->db->escape($this->element).
"'";
5817 $sql .=
", '".$this->db->escape((
string) $busy).
"'";
5818 $sql .=
", '".$this->db->escape((
string) $mandatory).
"'";
5821 dol_syslog(get_class($this).
"::add_element_resource", LOG_DEBUG);
5822 if ($this->db->query($sql)) {
5823 $this->db->commit();
5826 $this->error = $this->db->lasterror();
5827 $this->db->rollback();
5848 $sql =
"DELETE FROM ".$this->db->prefix().
"element_resources";
5849 $sql .=
" WHERE rowid = ".((int) $rowid);
5851 dol_syslog(get_class($this).
"::delete_resource", LOG_DEBUG);
5853 $resql = $this->db->query($sql);
5855 $this->error = $this->db->lasterror();
5856 $this->db->rollback();
5860 $result = $this->call_trigger(strtoupper($element).
'_DELETE_RESOURCE', $user);
5862 $this->db->rollback();
5866 $this->db->commit();
5880 if (isset($this->lines) && is_array($this->lines)) {
5881 $nboflines = count($this->lines);
5882 for ($i = 0; $i < $nboflines; $i++) {
5883 if (is_object($this->lines[$i])) {
5884 $this->lines[$i] = clone $this->lines[$i];
5903 protected function commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams =
null)
5905 global
$conf, $langs, $hookmanager, $action;
5907 $srctemplatepath =
'';
5909 $parameters = array(
'modelspath' => $modelspath,
'modele' => $modele,
'outputlangs' => $outputlangs,
'hidedetails' => $hidedetails,
'hidedesc' => $hidedesc,
'hideref' => $hideref,
'moreparams' => $moreparams);
5910 $reshook = $hookmanager->executeHooks(
'commonGenerateDocument', $parameters, $this, $action);
5912 if (!empty($reshook)) {
5916 dol_syslog(
"commonGenerateDocument modele=".$modele.
" outputlangs->defaultlang=".(is_object($outputlangs) ? $outputlangs->defaultlang :
'null'));
5918 if (empty($modele)) {
5919 $this->error =
'BadValueForParameterModele';
5924 $err = error_reporting();
5926 @set_time_limit(120);
5927 error_reporting($err);
5930 $tmp = explode(
':', $modele, 2);
5931 $saved_model = $modele;
5932 if (!empty($tmp[1])) {
5934 $srctemplatepath = $tmp[1];
5941 $dirmodels = array(
'/');
5942 if (is_array(
$conf->modules_parts[
'models'])) {
5943 $dirmodels = array_merge($dirmodels,
$conf->modules_parts[
'models']);
5945 foreach ($dirmodels as $reldir) {
5946 foreach (array(
'doc',
'pdf') as $prefix) {
5947 if (in_array(get_class($this), array(
'Adherent'))) {
5949 $file = $prefix.
"_".$modele.
".class.php";
5952 $file = $prefix.
"_".$modele.
".modules.php";
5959 if (file_exists($file)) {
5961 $classname = $prefix.
'_'.$modele;
5970 if ($filefound ===
'' || $classname ===
'') {
5971 $this->error = $langs->trans(
"Error").
' Failed to load doc generator with modelpaths='.$modelspath.
' - modele='.$modele;
5972 $this->errors[] = $this->error;
5983 require_once $filefound;
5985 $obj =
new $classname($this->db);
5997 '@phan-var-force ModelePDFMember $obj';
6001 if ($obj->type ==
'odt' && empty($srctemplatepath)) {
6002 $varfortemplatedir = $obj->scandir;
6006 $listoffiles = array();
6009 $listofdir = explode(
',', $dirtoscan);
6010 foreach ($listofdir as $key => $tmpdir) {
6011 $tmpdir = trim($tmpdir);
6012 $tmpdir = preg_replace(
'/DOL_DATA_ROOT/', DOL_DATA_ROOT, $tmpdir);
6014 unset($listofdir[$key]);
6017 if (is_dir($tmpdir)) {
6018 $tmpfiles =
dol_dir_list($tmpdir,
'files', 0,
'\.od(s|t)$',
'',
'name', SORT_ASC, 0);
6019 if (count($tmpfiles)) {
6020 $listoffiles = array_merge($listoffiles, $tmpfiles);
6025 if (count($listoffiles)) {
6026 foreach ($listoffiles as $record) {
6027 $srctemplatepath = $record[
'fullname'];
6033 if (empty($srctemplatepath)) {
6034 $this->error =
'ErrorGenerationAskedForOdtTemplateWithSrcFileNotDefined';
6039 if ($obj->type ==
'odt' && !empty($srctemplatepath)) {
6041 dol_syslog(
"Failed to locate template file ".$srctemplatepath, LOG_WARNING);
6042 $this->error =
'ErrorGenerationAskedForOdtTemplateWithSrcFileNotFound';
6049 $sav_charset_output = empty($outputlangs->charset_output) ?
'' : $outputlangs->charset_output;
6052 $this->model_pdf = $saved_model;
6056 $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath,
'member', 1,
'tmp_cards');
6058 $resultwritefile = -1;
6059 dol_syslog(
"Error generating document - Provided ".get_class($this).
" to ".get_class($obj).
"::write_file()", LOG_ERR);
6063 if ($this instanceof
Don) {
6064 $resultwritefile = $obj->write_file($this, $outputlangs );
6066 $resultwritefile = -1;
6067 dol_syslog(
"Error generating document - Provided ".get_class($this).
" to Don::write_file()", LOG_ERR);
6071 '@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';
6072 $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, $hidedetails, $hidedesc, $hideref, $moreparams);
6076 if ($resultwritefile > 0) {
6077 $outputlangs->charset_output = $sav_charset_output;
6080 require_once DOL_DOCUMENT_ROOT.
'/core/lib/files.lib.php';
6084 if (!empty($obj->result[
'fullpath'])) {
6085 $destfull = $obj->result[
'fullpath'];
6088 $update_main_doc_field = 0;
6089 if (!empty($obj->update_main_doc_field)) {
6090 $update_main_doc_field = 1;
6096 $this->indexFile($destfull, $update_main_doc_field);
6099 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);
6107 $outputlangs->charset_output = $sav_charset_output;
6108 $this->error = $obj->error;
6109 $this->errors = $obj->errors;
6110 dol_syslog(
"Error generating document for ".__CLASS__.
". Error: ".$obj->error, LOG_ERR);
6124 public function indexFile($destfull, $update_main_doc_field)
6126 global
$conf, $user;
6128 $upload_dir = dirname($destfull);
6129 $destfile = basename($destfull);
6130 $rel_dir = preg_replace(
'/^'.preg_quote(DOL_DATA_ROOT,
'/').
'/',
'', $upload_dir);
6132 if (!preg_match(
'/[\\/]temp[\\/]|[\\/]thumbs|\.meta$/', $rel_dir)) {
6133 $filename = basename($destfile);
6134 $rel_dir = preg_replace(
'/[\\/]$/',
'', $rel_dir);
6135 $rel_dir = preg_replace(
'/^[\\/]/',
'', $rel_dir);
6137 include_once DOL_DOCUMENT_ROOT.
'/ecm/class/ecmfiles.class.php';
6138 $ecmfile =
new EcmFiles($this->db);
6139 $result = $ecmfile->fetch(0,
'', ($rel_dir ? $rel_dir.
'/' :
'').$filename);
6142 $setsharekey =
false;
6143 if ($this->element ==
'propal' || $this->element ==
'proposal') {
6145 $setsharekey =
true;
6148 $setsharekey =
true;
6151 if ($this->element ==
'commande' &&
getDolGlobalInt(
"ORDER_ALLOW_EXTERNAL_DOWNLOAD")) {
6152 $setsharekey =
true;
6154 if ($this->element ==
'facture' &&
getDolGlobalInt(
"INVOICE_ALLOW_EXTERNAL_DOWNLOAD")) {
6155 $setsharekey =
true;
6157 if ($this->element ==
'bank_account' &&
getDolGlobalInt(
"BANK_ACCOUNT_ALLOW_EXTERNAL_DOWNLOAD")) {
6158 $setsharekey =
true;
6160 if ($this->element ==
'product' &&
getDolGlobalInt(
"PRODUCT_ALLOW_EXTERNAL_DOWNLOAD")) {
6161 $setsharekey =
true;
6163 if ($this->element ==
'contrat' &&
getDolGlobalInt(
"CONTRACT_ALLOW_EXTERNAL_DOWNLOAD")) {
6164 $setsharekey =
true;
6166 if ($this->element ==
'fichinter' &&
getDolGlobalInt(
"FICHINTER_ALLOW_EXTERNAL_DOWNLOAD")) {
6167 $setsharekey =
true;
6169 if ($this->element ==
'supplier_proposal' &&
getDolGlobalInt(
"SUPPLIER_PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD")) {
6170 $setsharekey =
true;
6172 if ($this->element ==
'societe_rib' &&
getDolGlobalInt(
"SOCIETE_RIB_ALLOW_ONLINESIGN")) {
6173 $setsharekey =
true;
6177 if (empty($ecmfile->share)) {
6178 require_once DOL_DOCUMENT_ROOT.
'/core/lib/security2.lib.php';
6185 $ecmfile->fullpath_orig =
'';
6186 $ecmfile->gen_or_uploaded =
'generated';
6187 $ecmfile->description =
'';
6188 $ecmfile->keywords =
'';
6189 $ecmfile->src_object_type = $this->table_element;
6191 $result = $ecmfile->update($user);
6197 $ecmfile->entity =
$conf->entity;
6198 $ecmfile->filepath = $rel_dir;
6199 $ecmfile->filename = $filename;
6201 $ecmfile->fullpath_orig =
'';
6202 $ecmfile->gen_or_uploaded =
'generated';
6203 $ecmfile->description =
'';
6204 $ecmfile->keywords =
'';
6205 $ecmfile->src_object_type = $this->table_element;
6208 $result = $ecmfile->create($user);
6220 if ($update_main_doc_field && !empty($this->table_element)) {
6221 $sql =
"UPDATE ".$this->db->prefix().$this->table_element.
" SET last_main_doc = '".$this->db->escape($ecmfile->filepath.
"/".$ecmfile->filename).
"'";
6222 $sql .=
" WHERE rowid = ".((int) $this->
id);
6224 $resql = $this->db->query($sql);
6229 $this->last_main_doc = $ecmfile->filepath.
'/'.$ecmfile->filename;
6249 if (file_exists($file_osencoded)) {
6250 require_once DOL_DOCUMENT_ROOT.
'/core/lib/images.lib.php';
6253 $maxwidthsmall = $tmparraysize[
'maxwidthsmall'];
6254 $maxheightsmall = $tmparraysize[
'maxheightsmall'];
6255 $maxwidthmini = $tmparraysize[
'maxwidthmini'];
6256 $maxheightmini = $tmparraysize[
'maxheightmini'];
6261 vignette($file_osencoded, $maxwidthsmall, $maxheightsmall,
'_small', $quality);
6265 vignette($file_osencoded, $maxwidthmini, $maxheightmini,
'_mini', $quality);
6305 if (GETPOSTISSET($fieldname)) {
6306 return GETPOST($fieldname, $type, 3);
6309 if (isset($alternatevalue)) {
6310 return $alternatevalue;
6313 $newelement = $this->element;
6314 if ($newelement ==
'facture') {
6315 $newelement =
'invoice';
6317 if ($newelement ==
'commande') {
6318 $newelement =
'order';
6320 if (empty($newelement)) {
6321 dol_syslog(
"Ask a default value using common method getDefaultCreateValueForField on an object with no property ->element defined. Return empty string.", LOG_WARNING);
6325 $keyforfieldname = strtoupper($newelement.
'_DEFAULT_'.$fieldname);
6355 global $langs,
$conf;
6357 if (!empty(self::TRIGGER_PREFIX) && strpos($triggerName, self::TRIGGER_PREFIX .
'_') !== 0) {
6358 dol_print_error(
null,
'The trigger "' . $triggerName .
'" does not start with "' . self::TRIGGER_PREFIX .
'_" as required.');
6361 if (!is_object($langs)) {
6363 include_once DOL_DOCUMENT_ROOT.
'/core/class/translate.class.php';
6365 $langs->load(
"main");
6368 include_once DOL_DOCUMENT_ROOT.
'/core/class/interfaces.class.php';
6370 $result = $interface->run_triggers($triggerName, $this, $user, $langs,
$conf);
6373 if (!empty($this->errors)) {
6374 $this->errors = array_unique(array_merge($this->errors, $interface->errors));
6376 $this->errors = $interface->errors;
6397 if (!$this->element) {
6400 if (!($this->
id > 0)) {
6403 if (is_array($this->array_languages)) {
6407 $this->array_languages = array();
6409 $element = $this->element;
6410 if ($element ==
'categorie') {
6411 $element =
'categories';
6415 $sql =
"SELECT rowid, property, lang , value";
6416 $sql .=
" FROM ".$this->db->prefix().
"object_lang";
6417 $sql .=
" WHERE type_object = '".$this->db->escape($element).
"'";
6418 $sql .=
" AND fk_object = ".((int) $this->
id);
6420 $resql = $this->db->query($sql);
6422 $numrows = $this->db->num_rows($resql);
6425 while ($i < $numrows) {
6426 $obj = $this->db->fetch_object($resql);
6427 $key = $obj->property;
6428 $value = $obj->value;
6429 $codelang = $obj->lang;
6430 $type = $this->fields[$key][
'type'];
6433 if (preg_match(
'/date/', $type)) {
6434 $this->array_languages[$key][$codelang] = $this->db->jdate($value);
6436 $this->array_languages[$key][$codelang] = $value;
6443 $this->db->free($resql);
6466 foreach ($_POST as $postfieldkey => $postfieldvalue) {
6467 $tmparray = explode(
'-', $postfieldkey);
6468 if ($tmparray[0] !=
'field') {
6472 $element = $tmparray[1];
6473 $key = $tmparray[2];
6474 $codelang = $tmparray[3];
6477 if (!empty($onlykey) && $key != $onlykey) {
6480 if ($element != $this->element) {
6484 $key_type = $this->fields[$key][
'type'];
6487 if (isset($this->fields[$key][
'enabled'])) {
6488 $enabled = (int)
dol_eval((
string) $this->fields[$key][
'enabled'], 1, 1,
'1');
6495 if (empty($enabled)) {
6500 if (in_array($key_type, array(
'date'))) {
6504 } elseif (in_array($key_type, array(
'datetime'))) {
6508 } elseif (in_array($key_type, array(
'checkbox',
'chkbxlst'))) {
6509 $value_arr =
GETPOST($postfieldkey,
'array');
6510 if (!empty($value_arr)) {
6511 $value_key = implode(
',', $value_arr);
6515 } elseif (in_array($key_type, array(
'price',
'double'))) {
6516 $value_arr =
GETPOST($postfieldkey,
'alpha');
6519 $value_key =
GETPOST($postfieldkey);
6520 if (in_array($key_type, array(
'link')) && $value_key ==
'-1') {
6525 $this->array_languages[$key][$codelang] = $value_key;
6550 $savDisableCompute =
$conf->disable_compute;
6551 $conf->disable_compute = 1;
6553 $ret = $this->fetch(
$id);
6555 $conf->disable_compute = $savDisableCompute;
6573 global
$conf, $extrafields;
6575 if (empty($rowid)) {
6578 if (empty($rowid) && isset($this->rowid)) {
6579 $rowid = $this->rowid;
6583 if (!$this->table_element) {
6587 $this->array_options = array();
6589 if (!is_array($optionsArray)) {
6591 if (!isset($extrafields) || !is_object($extrafields)) {
6592 require_once DOL_DOCUMENT_ROOT.
'/core/class/extrafields.class.php';
6597 if (empty($extrafields->attributes[$this->table_element][
'loaded'])) {
6598 $extrafields->fetch_name_optionals_label($this->table_element);
6600 $optionsArray = (!empty($extrafields->attributes[$this->table_element][
'label']) ? $extrafields->attributes[$this->table_element][
'label'] :
null);
6602 global $extrafields;
6603 dol_syslog(
"Warning: fetch_optionals was called with param optionsArray defined when you should pass null now", LOG_WARNING);
6606 $table_element = $this->table_element;
6607 if ($table_element ==
'categorie') {
6608 $table_element =
'categories';
6612 if (is_array($optionsArray) && count($optionsArray) > 0) {
6613 $sql =
"SELECT rowid";
6614 foreach ($optionsArray as $name => $label) {
6615 if (empty($extrafields->attributes[$this->table_element][
'type'][$name]) || (!in_array($extrafields->attributes[$this->table_element][
'type'][$name], [
'separate',
'point',
'multipts',
'linestrg',
'polygon']))) {
6616 $sql .=
", ".$this->db->sanitize($name);
6619 if (empty($extrafields->attributes[$this->table_element][
'type'][$name]) || in_array($extrafields->attributes[$this->table_element][
'type'][$name], array(
'point',
'multipts',
'linestrg',
'polygon'))) {
6621 $sql .=
", ST_AsWKT(".$name.
") as ".$this->db->sanitize($name);
6624 $sql .=
" FROM ".$this->db->prefix().$table_element.
"_extrafields";
6625 $sql .=
" WHERE fk_object = ".((int) $rowid);
6628 $resql = $this->db->query($sql);
6630 $numrows = $this->db->num_rows($resql);
6632 $tab = $this->db->fetch_array($resql);
6634 foreach ($tab as $key => $value) {
6636 if ($key !=
'rowid' && $key !=
'tms' && $key !=
'fk_member' && !is_int($key)) {
6638 if (!empty($extrafields->attributes[$this->table_element]) && in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'date',
'datetime'))) {
6640 $this->array_options[
"options_".$key] = $this->db->jdate($value);
6642 $this->array_options[
"options_".$key] = $value;
6647 if (!empty($extrafields->attributes[$this->table_element][
'type'][$key]) && $extrafields->attributes[$this->table_element][
'type'][$key] ==
'password') {
6648 if (!empty($value) && preg_match(
'/^dolcrypt:/', $value)) {
6649 $this->array_options[
"options_".$key] =
dolDecrypt($value);
6658 if (is_array($extrafields->attributes[$this->table_element][
'label'])) {
6659 foreach ($extrafields->attributes[$this->table_element][
'label'] as $key => $val) {
6660 $this->array_options[
'options_' . $key] =
null;
6667 if (is_array($extrafields->attributes[$this->table_element][
'label'])) {
6668 foreach ($extrafields->attributes[$this->table_element][
'label'] as $key => $val) {
6669 if (!empty($extrafields->attributes[$this->table_element]) && !empty($extrafields->attributes[$this->table_element][
'computed'][$key])) {
6671 if (empty(
$conf->disable_compute)) {
6672 global $objectoffield;
6673 $objectoffield = $this;
6674 $this->array_options[
'options_' . $key] =
dol_eval((
string) $extrafields->attributes[$this->table_element][
'computed'][$key], 1, 0,
'2');
6680 $this->db->free($resql);
6688 $this->errors[] = $this->db->lasterror;
6709 $table_element = $this->table_element;
6710 if ($table_element ==
'categorie') {
6711 $table_element =
'categories';
6714 dol_syslog(get_class($this).
"::deleteExtraFields delete", LOG_DEBUG);
6716 $sql_del =
"DELETE FROM ".$this->db->prefix().$table_element.
"_extrafields WHERE fk_object = ".((int) $this->
id);
6718 $resql = $this->db->query($sql_del);
6720 $this->error = $this->db->lasterror();
6721 $this->db->rollback();
6724 $this->db->commit();
6741 global $langs, $user;
6743 if (
getDolGlobalString(
'MAIN_EXTRAFIELDS_DISABLED') || empty($this->array_options)) {
6747 if (empty($userused)) {
6754 $langs->load(
'admin');
6755 require_once DOL_DOCUMENT_ROOT.
'/core/class/extrafields.class.php';
6757 $target_extrafields = $extrafields->fetch_name_optionals_label($this->table_element);
6760 $new_array_options = array();
6761 foreach ($this->array_options as $key => $value) {
6762 if (in_array(substr($key, 8), array_keys($target_extrafields))) {
6763 $new_array_options[$key] = $value;
6764 } elseif (in_array($key, array_keys($target_extrafields))) {
6765 $new_array_options[
'options_'.$key] = $value;
6769 foreach ($new_array_options as $key => $value) {
6770 $attributeKey = substr($key, 8);
6771 $attributeType = $extrafields->attributes[$this->table_element][
'type'][$attributeKey];
6772 $attributeLabel = $langs->transnoentities($extrafields->attributes[$this->table_element][
'label'][$attributeKey]);
6773 $attributeParam = $extrafields->attributes[$this->table_element][
'param'][$attributeKey];
6774 $attributeRequired = $extrafields->attributes[$this->table_element][
'required'][$attributeKey];
6775 $attributeUnique = $extrafields->attributes[$this->table_element][
'unique'][$attributeKey];
6776 $attrfieldcomputed = $extrafields->attributes[$this->table_element][
'computed'][$attributeKey];
6780 if (!empty($this->context[
'createfromclone']) && $this->context[
'createfromclone'] ==
'createfromclone' && !empty($attributeUnique)) {
6781 $new_array_options[$key] =
null;
6786 if (!empty($this->context[
'createproductcombination']) && $this->context[
'createproductcombination'] ==
'createproductcombination' && !empty($attributeUnique)) {
6787 $new_array_options[$key] =
null;
6791 if ($attributeRequired) {
6792 $v = $this->array_options[$key];
6794 $langs->load(
"errors");
6795 dol_syslog(
"Mandatory field '".$key.
"' is empty during create and set to required into definition of extrafields");
6796 $this->errors[] = $langs->trans(
'ErrorFieldRequired', $attributeLabel);
6801 if (!empty($attrfieldcomputed)) {
6803 $value =
dol_eval((
string) $attrfieldcomputed, 1, 0,
'2');
6804 dol_syslog($langs->trans(
"Extrafieldcomputed").
" on ".$attributeLabel.
"(".$value.
")", LOG_DEBUG);
6805 $new_array_options[$key] = $value;
6807 $new_array_options[$key] =
null;
6811 switch ($attributeType) {
6815 if (!is_numeric($value) && $value !=
'') {
6816 $this->errors[] = $langs->trans(
"ExtraFieldHasWrongValue", $attributeLabel);
6818 } elseif ($value ===
'') {
6819 $new_array_options[$key] =
null;
6823 if ($value ===
'' || $value ===
false || $value ===
null) {
6824 $new_array_options[$key] =
null;
6830 if (!is_numeric($value) && $value !=
'') {
6831 dol_syslog($langs->trans(
"ExtraFieldHasWrongValue").
" for ".$attributeLabel.
"(".$value.
"is not '".$attributeType.
"')", LOG_DEBUG);
6832 $this->errors[] = $langs->trans(
"ExtraFieldHasWrongValue", $attributeLabel);
6834 } elseif ($value ==
'') {
6838 $new_array_options[$key] = $value;
6848 if ($this->array_options[$key] !=
'' && is_array($extrafields->attributes[$this->table_element][
'param'][$attributeKey][
'options'])) {
6850 $tmparrays = array_keys($extrafields->attributes[$this->table_element][
'param'][$attributeKey][
'options']);
6851 $algo = reset($tmparrays);
6856 if (is_object($this->oldcopy)) {
6858 if (isset($this->oldcopy->array_options[$key]) && $this->array_options[$key] == $this->oldcopy->array_options[$key]) {
6860 if ($algo ==
'dolcrypt') {
6861 if (!preg_match(
'/^dolcrypt:/', $this->array_options[$key])) {
6862 $new_array_options[$key] =
dolEncrypt($this->array_options[$key]);
6864 $new_array_options[$key] = $this->array_options[$key];
6867 $new_array_options[$key] = $this->array_options[$key];
6871 if ($algo ==
'dolcrypt') {
6872 if (!preg_match(
'/^dolcrypt:/', $this->array_options[$key])) {
6873 $new_array_options[$key] =
dolEncrypt($this->array_options[$key]);
6875 $new_array_options[$key] = $this->array_options[$key];
6878 $new_array_options[$key] =
dol_hash($this->array_options[$key], $algo);
6884 if ($algo ==
'dolcrypt' && !preg_match(
'/^dolcrypt:/', $this->array_options[$key])) {
6885 $new_array_options[$key] =
dolEncrypt($this->array_options[$key]);
6887 $new_array_options[$key] = $this->array_options[$key];
6892 $new_array_options[$key] = $this->array_options[$key];
6895 $new_array_options[$key] = $this->array_options[$key];
6901 if (!is_numeric($this->array_options[$key]) || $this->array_options[$key] != intval($this->array_options[$key])) {
6902 $this->array_options[$key] = strtotime($this->array_options[$key]);
6904 $new_array_options[$key] = $this->db->idate($this->array_options[$key]);
6908 if (!is_numeric($this->array_options[$key]) || $this->array_options[$key] != intval($this->array_options[$key])) {
6909 $this->array_options[$key] = strtotime($this->array_options[$key]);
6911 $new_array_options[$key] = $this->db->idate($this->array_options[$key],
'gmt');
6914 $param_list = array_keys($attributeParam[
'options']);
6917 $InfoFieldList = explode(
":", $param_list[0]);
6919 if ($InfoFieldList[0] && class_exists($InfoFieldList[0])) {
6920 if ($value ==
'-1') {
6921 $new_array_options[$key] =
'';
6923 $object =
new $InfoFieldList[0]($this->db);
6924 '@phan-var-force CommonObject $object';
6928 $sqlFetchObject =
"SELECT rowid FROM ".$this->db->prefix().$object->table_element;
6929 if (is_numeric($value)) {
6930 $sqlFetchObject .=
" WHERE rowid = " . (int) $value;
6932 $sqlFetchObject .=
" WHERE ref = '" . $this->db->escape($value) .
"'";
6935 $obj = $this->db->getRow($sqlFetchObject);
6941 if (is_object($obj)) {
6942 $objectId = $obj->rowid;
6949 $new_array_options[$key] = $objectId;
6951 $this->error =
"Id/Ref '".$value.
"' for object '".
$object->element.
"' not found";
6956 dol_syslog(
'Error bad setup of extrafield', LOG_WARNING);
6961 if (is_array($this->array_options[$key])) {
6962 $new_array_options[$key] = implode(
',', $this->array_options[$key]);
6964 $new_array_options[$key] = $this->array_options[$key];
6970 $sqlColumnValues = [
'fk_object' => (int) $this->
id];
6972 foreach ($new_array_options as $key => $newValue) {
6973 $attributeKey = substr($key, 8);
6974 $attributeType = $extrafields->attributes[$this->table_element][
'type'][$attributeKey];
6975 if ($attributeType ===
'separate') {
6979 $geoDataType = ExtraFields::$geoDataTypes[$attributeType] ??
null;
6981 if (! $geoDataType) {
6983 if ($newValue !=
'') {
6984 $sqlColumnValues[$attributeKey] =
"'".$this->db->escape($newValue).
"'";
6986 $sqlColumnValues[$attributeKey] =
'null';
6990 if (empty($newValue)) {
6991 $sqlColumnValues[$attributeKey] =
'null';
6994 if (preg_match(
'/error/i', $newValue)) {
6996 'Bad syntax string for '.$geoDataType[
'shortname'].
' '.$newValue.
' to generate SQL request',
6999 $sqlColumnValues[$attributeKey] =
'null';
7008 $sqlColumnValues[$key] = $geoDataType[
'ST_Function'].
"('".$this->db->escape($newValue).
"')";
7013 $table_element = $this->table_element;
7014 if ($table_element ==
'categorie') {
7015 $table_element =
'categories';
7017 $extrafieldsTable = $this->db->prefix() . $table_element .
'_extrafields';
7019 dol_syslog(get_class($this).
"::insertExtraFields delete then insert", LOG_DEBUG);
7022 if ($this->db->getRow(
"SELECT 1 FROM {$extrafieldsTable} WHERE fk_object = ".((int) $this->id))) {
7023 array_shift($sqlColumnValues);
7024 if (empty($sqlColumnValues)) {
7030 $this->db->commit();
7033 $sqlColumnValueString = implode(
7039 array_map(
function ($key) use ($sqlColumnValues) {
7040 return "{$key} = {$sqlColumnValues[$key]}";
7041 }, array_keys($sqlColumnValues))
7043 $sql =
"UPDATE {$extrafieldsTable} SET {$sqlColumnValueString} WHERE fk_object = ".((int) $this->
id);
7046 $extrafieldsRequiredOnOtherEntities = $extrafields->attributes[$this->table_element][
'mandatoryfieldsofotherentities'] ?? array();
7047 foreach ($extrafieldsRequiredOnOtherEntities as $key => $extrafieldType) {
7048 if (isset($sqlColumnValues[$key])) {
7053 $sqlColumnValues[$key] =
"''";
7054 if (in_array($extrafieldType, array(
'int',
'double',
'price'))) {
7055 $sqlColumnValues[$key] = 0;
7058 $sqlColumns = implode(
',', array_keys($sqlColumnValues));
7059 $sqlValues = implode(
',', array_values($sqlColumnValues));
7060 $sql =
"INSERT INTO {$extrafieldsTable} ({$sqlColumns}) VALUES ({$sqlValues})";
7063 $resql = $this->db->query($sql);
7065 $this->error = $this->db->lasterror();
7069 if (!$error && $trigger) {
7071 $this->context = array(
'extrafieldaddupdate' => 1);
7072 $result = $this->call_trigger($trigger, $userused);
7080 $this->db->rollback();
7083 $this->db->commit();
7101 global $langs, $user;
7103 if (empty($userused)) {
7113 if (is_array($this->array_languages)) {
7114 $new_array_languages = $this->array_languages;
7116 foreach ($new_array_languages as $key => $value) {
7117 $attributeKey = $key;
7118 $attributeType = $this->fields[$attributeKey][
'type'];
7119 $attributeLabel = $this->fields[$attributeKey][
'label'];
7124 switch ($attributeType) {
7126 if (is_array($value) || (!is_numeric($value) && $value !=
'')) {
7127 $this->errors[] = $langs->trans(
"ExtraLanguageHasWrongValue", $attributeLabel);
7129 } elseif ($value ==
'') {
7130 $new_array_languages[$key] =
null;
7135 if (!is_numeric($value) && $value !=
'') {
7136 dol_syslog($langs->trans(
"ExtraLanguageHasWrongValue").
" on ".$attributeLabel.
"(".$value.
"is not '".$attributeType.
"')", LOG_DEBUG);
7137 $this->errors[] = $langs->trans(
"ExtraLanguageHasWrongValue", $attributeLabel);
7139 } elseif ($value ==
'') {
7140 $new_array_languages[$key] =
null;
7142 $new_array_languages[$key] = $value;
7156 $table_element = $this->table_element;
7157 if ($table_element ==
'categorie') {
7158 $table_element =
'categories';
7161 dol_syslog(get_class($this).
"::insertExtraLanguages delete then insert", LOG_DEBUG);
7163 foreach ($new_array_languages as $key => $langcodearray) {
7164 foreach ($langcodearray as $langcode => $value) {
7165 $sql_del =
"DELETE FROM ".$this->db->prefix().
"object_lang";
7166 $sql_del .=
" WHERE fk_object = ".((int) $this->
id).
" AND property = '".$this->db->escape($key).
"' AND type_object = '".$this->db->escape($table_element).
"'";
7167 $sql_del .=
" AND lang = '".$this->db->escape($langcode).
"'";
7168 $this->db->query($sql_del);
7170 if ($value !==
'') {
7171 $sql =
"INSERT INTO ".$this->db->prefix().
"object_lang (fk_object, property, type_object, lang, value";
7172 $sql .=
") VALUES (".$this->id.
", '".$this->db->escape($key).
"', '".$this->db->escape($table_element).
"', '".$this->db->escape($langcode).
"', '".$this->db->escape($value).
"'";
7175 $resql = $this->db->query($sql);
7177 $this->error = $this->db->lasterror();
7185 if (!$error && $trigger) {
7187 $this->context = array(
'extralanguagesaddupdate' => 1);
7188 $result = $this->call_trigger($trigger, $userused);
7196 $this->db->rollback();
7199 $this->db->commit();
7219 global $langs, $user, $hookmanager;
7225 if (empty($userused)) {
7231 if (!empty($this->array_options) && isset($this->array_options[
"options_".$key])) {
7233 $langs->load(
'admin');
7234 require_once DOL_DOCUMENT_ROOT.
'/core/class/extrafields.class.php';
7236 $extrafields->fetch_name_optionals_label($this->table_element);
7237 if (!isset($extrafields->attributes[$this->table_element][
'type'][$key])) {
7241 $value = $this->array_options[
"options_".$key];
7243 $attributeKey = $key;
7244 $attributeType = $extrafields->attributes[$this->table_element][
'type'][$key];
7245 $attributeLabel = $extrafields->attributes[$this->table_element][
'label'][$key];
7246 $attributeParam = $extrafields->attributes[$this->table_element][
'param'][$key];
7247 $attributeRequired = $extrafields->attributes[$this->table_element][
'required'][$key];
7248 $attributeUnique = $extrafields->attributes[$this->table_element][
'unique'][$attributeKey];
7249 $attrfieldcomputed = $extrafields->attributes[$this->table_element][
'computed'][$key];
7252 if ($attributeRequired) {
7253 $mandatorypb =
false;
7254 if ($attributeType ==
'link' && $this->array_options[
"options_".$key] ==
'-1') {
7255 $mandatorypb =
true;
7257 if ($this->array_options[
"options_".$key] ===
'') {
7258 $mandatorypb =
true;
7261 $langs->load(
"errors");
7262 dol_syslog(
"Mandatory field 'options_".$key.
"' is empty during update and set to required into definition of extrafields");
7263 $this->errors[] = $langs->trans(
'ErrorFieldRequired', $attributeLabel);
7269 $new_array_options = $this->array_options;
7273 if (!empty($attrfieldcomputed)) {
7275 $value =
dol_eval((
string) $attrfieldcomputed, 1, 0,
'2');
7276 dol_syslog($langs->trans(
"Extrafieldcomputed").
" on ".$attributeLabel.
"(".$value.
")", LOG_DEBUG);
7278 $new_array_options[
"options_".$key] = $value;
7280 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7282 $new_array_options[
"options_".$key] =
null;
7284 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7288 switch ($attributeType) {
7290 if (!is_numeric($value) && $value !=
'') {
7291 $this->errors[] = $langs->trans(
"ExtraFieldHasWrongValue", $attributeLabel);
7293 } elseif ($value ===
'') {
7294 $new_array_options[
"options_".$key] =
null;
7296 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7302 if (!is_numeric($value) && $value !=
'') {
7303 dol_syslog($langs->trans(
"ExtraFieldHasWrongValue").
" on ".$attributeLabel.
"(".$value.
"is not '".$attributeType.
"')", LOG_DEBUG);
7304 $this->errors[] = $langs->trans(
"ExtraFieldHasWrongValue", $attributeLabel);
7306 } elseif ($value ===
'') {
7310 $new_array_options[
"options_".$key] = $value;
7312 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7324 if ($this->array_options[
"options_".$key] !=
'' && is_array($extrafields->attributes[$this->table_element][
'param'][$attributeKey][
'options'])) {
7326 $tmparrays = array_keys($extrafields->attributes[$this->table_element][
'param'][$attributeKey][
'options']);
7327 $algo = reset($tmparrays);
7333 if (is_object($this->oldcopy)) {
7335 if (isset($this->oldcopy->array_options[
"options_".$key]) && $this->array_options[
"options_".$key] == $this->oldcopy->array_options[
"options_".$key]) {
7336 if ($algo ==
'dolcrypt') {
7337 if (!preg_match(
'/^dolcrypt:/', $this->array_options[
"options_".$key])) {
7338 $new_array_options[
"options_".$key] =
dolEncrypt($this->array_options[
"options_".$key]);
7340 $new_array_options[
"options_".$key] = $this->array_options[
"options_".$key];
7343 $new_array_options[
"options_".$key] = $this->array_options[
"options_".$key];
7346 if ($algo ==
'dolcrypt') {
7347 if (!preg_match(
'/^dolcrypt:/', $this->array_options[
"options_".$key])) {
7348 $new_array_options[
"options_".$key] =
dolEncrypt($this->array_options[
"options_".$key]);
7350 $new_array_options[
"options_".$key] = $this->array_options[
"options_".$key];
7353 $new_array_options[
"options_".$key] =
dol_hash($this->array_options[
"options_".$key], $algo);
7357 if ($algo ==
'dolcrypt' && !preg_match(
'/^dolcrypt:/', $this->array_options[
"options_".$key])) {
7358 $new_array_options[
"options_".$key] =
dolEncrypt($this->array_options[
"options_".$key]);
7360 $new_array_options[
"options_".$key] = $this->array_options[
"options_".$key];
7365 $new_array_options[
"options_".$key] = $this->array_options[
"options_".$key];
7368 $new_array_options[
"options_".$key] = $this->array_options[
"options_".$key];
7371 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7375 if (empty($this->array_options[
"options_".$key])) {
7376 $new_array_options[
"options_".$key] =
null;
7378 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7380 $new_array_options[
"options_".$key] = $this->db->idate($this->array_options[
"options_".$key]);
7384 if (empty($this->array_options[
"options_".$key])) {
7385 $new_array_options[
"options_".$key] =
null;
7387 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7389 $new_array_options[
"options_".$key] = $this->db->idate($this->array_options[
"options_".$key],
'gmt');
7393 if (empty($this->array_options[
"options_".$key])) {
7394 $new_array_options[
"options_".$key] =
null;
7396 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7400 if ($this->array_options[
"options_".$key] ===
'') {
7401 $new_array_options[
"options_".$key] =
null;
7403 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7437 $new_array_options = array();
7438 if (is_array($this->array_options[
"options_".$key])) {
7439 $new_array_options[
"options_".$key] = implode(
',', $this->array_options[
"options_".$key]);
7441 $new_array_options[
"options_".$key] = $this->array_options[
"options_".$key];
7444 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7450 $linealreadyfound = 0;
7453 $table_element = $this->table_element;
7454 if ($table_element ==
'categorie') {
7455 $table_element =
'categories';
7458 $sql =
"SELECT COUNT(rowid) as nb FROM ".$this->db->prefix().$table_element.
"_extrafields WHERE fk_object = ".((int) $this->
id);
7459 $resql = $this->db->query($sql);
7461 $tmpobj = $this->db->fetch_object($resql);
7463 $linealreadyfound = $tmpobj->nb;
7468 if ($linealreadyfound) {
7469 if ($this->array_options[
"options_".$key] ===
null) {
7470 $sql =
"UPDATE ".$this->db->prefix().$table_element.
"_extrafields SET ".$key.
" = null";
7472 $sql =
"UPDATE ".$this->db->prefix().$table_element.
"_extrafields SET ".$key.
" = '".$this->db->escape($new_array_options[
"options_".$key]).
"'";
7474 $sql .=
" WHERE fk_object = ".((int) $this->
id);
7476 $resql = $this->db->query($sql);
7479 $this->error = $this->db->lasterror();
7482 $result = $this->insertExtraFields(
'', $user);
7489 $parameters = array(
'key' => $key);
7491 $reshook = $hookmanager->executeHooks(
'updateExtraFieldBeforeCommit', $parameters, $this, $action);
7497 if (!$error && $trigger) {
7499 $this->context = array(
'extrafieldupdate' => 1);
7500 $result = $this->call_trigger($trigger, $userused);
7508 dol_syslog(__METHOD__.$this->error, LOG_ERR);
7509 $this->db->rollback();
7512 $this->db->commit();
7528 return $this->array_options[
'options_'.$key] ??
null;
7540 $this->array_options[
'options_'.$key] = $value;
7557 if (empty($userused)) {
7585 public function showInputField($val, $key, $value, $moreparam =
'', $keysuffix =
'', $keyprefix =
'', $morecss = 0, $nonewbutton = 0)
7587 global
$conf, $langs, $form;
7592 if (!is_object($form)) {
7593 require_once DOL_DOCUMENT_ROOT.
'/core/class/html.form.class.php';
7594 $form =
new Form($this->db);
7597 if (!empty($this->fields)) {
7598 $val = $this->fields[$key];
7602 $fieldValidationErrorMsg =
'';
7603 $validationClass =
'';
7604 $fieldValidationErrorMsg = $this->getFieldError($key);
7605 if (!empty($fieldValidationErrorMsg)) {
7606 $validationClass =
' --error';
7608 $validationClass =
' --success';
7616 $param[
'options'] = array();
7619 $size = !empty($this->fields[$key][
'size']) ? $this->fields[$key][
'size'] : 0;
7621 if (preg_match(
'/^(integer|link):(.*):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
7622 $param[
'options'] = array($reg[2].
':'.$reg[3].
':'.$reg[4].
':'.$reg[5] =>
'N');
7624 } elseif (preg_match(
'/^(integer|link):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
7625 $param[
'options'] = array($reg[2].
':'.$reg[3].
':'.$reg[4] =>
'N');
7627 } elseif (preg_match(
'/^(integer|link):(.*):(.*)/i', $val[
'type'], $reg)) {
7628 $param[
'options'] = array($reg[2].
':'.$reg[3] =>
'N');
7630 } elseif (preg_match(
'/^(sellist):(.*):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
7631 $param[
'options'] = array($reg[2].
':'.$reg[3].
':'.$reg[4].
':'.$reg[5] =>
'N');
7633 } elseif (preg_match(
'/^(sellist):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
7634 $param[
'options'] = array($reg[2].
':'.$reg[3].
':'.$reg[4] =>
'N');
7636 } elseif (preg_match(
'/^(sellist):(.*):(.*)/i', $val[
'type'], $reg)) {
7637 $param[
'options'] = array($reg[2].
':'.$reg[3] =>
'N');
7639 } elseif (preg_match(
'/^chkbxlst:(.*)/i', $val[
'type'], $reg)) {
7640 $param[
'options'] = array($reg[1] =>
'N');
7642 } elseif (preg_match(
'/varchar\((\d+)\)/', $val[
'type'], $reg)) {
7643 $param[
'options'] = array();
7646 } elseif (preg_match(
'/varchar/', $val[
'type'])) {
7647 $param[
'options'] = array();
7649 } elseif (preg_match(
'/stars\((\d+)\)/', $val[
'type'], $reg)) {
7650 $param[
'options'] = array();
7654 $param[
'options'] = array();
7655 $type = $this->fields[$key][
'type'];
7660 if (!empty($this->fields[$key][
'arrayofkeyval']) && is_array($this->fields[$key][
'arrayofkeyval'])) {
7661 $param[
'options'] = $this->fields[$key][
'arrayofkeyval'];
7663 if (empty($this->fields[$key][
'multiinput'])) {
7664 $type = (($this->fields[$key][
'type'] ==
'checkbox') ? $this->fields[$key][
'type'] :
'select');
7668 $label = $this->fields[$key][
'label'];
7671 $default = (!empty($this->fields[$key][
'default']) ? $this->fields[$key][
'default'] :
'');
7673 $computed = (!empty($this->fields[$key][
'computed']) ? $this->fields[$key][
'computed'] :
'');
7675 $unique = (!empty($this->fields[$key][
'unique']) ? $this->fields[$key][
'unique'] : 0);
7677 $required = (!empty($this->fields[$key][
'required']) ? $this->fields[$key][
'required'] : 0);
7679 $autofocusoncreate = (!empty($this->fields[$key][
'autofocusoncreate']) ? $this->fields[$key][
'autofocusoncreate'] : 0);
7681 $placeholder = (!empty($this->fields[$key][
'placeholder']) ? $this->fields[$key][
'placeholder'] : 0);
7684 $langfile = (!empty($this->fields[$key][
'langfile']) ? $this->fields[$key][
'langfile'] :
'');
7686 $list = (!empty($this->fields[$key][
'list']) ? $this->fields[$key][
'list'] : 0);
7687 $hidden = (in_array(abs($this->fields[$key][
'visible']), array(0, 2)) ? 1 : 0);
7692 if (!preg_match(
'/^search_/', $keyprefix)) {
7693 return '<span class="opacitymedium">'.$langs->trans(
"AutomaticallyCalculated").
'</span>';
7700 if (empty($morecss) && !empty($val[
'css'])) {
7701 $morecss = $val[
'css'];
7702 } elseif (empty($morecss)) {
7703 if ($type ==
'date') {
7704 $morecss =
'minwidth100imp';
7705 } elseif ($type ==
'datetime' || $type ==
'link') {
7706 $morecss =
'minwidth200imp';
7707 } elseif (in_array($type, array(
'int',
'integer',
'price')) || preg_match(
'/^double(\([0-9],[0-9]\)){0,1}/', (
string) $type)) {
7708 $morecss =
'maxwidth75';
7709 } elseif ($type ==
'url') {
7710 $morecss =
'minwidth400';
7711 } elseif ($type ==
'boolean') {
7714 if (is_numeric($size) && round((
float) $size) < 12) {
7715 $morecss =
'minwidth100';
7716 } elseif (is_numeric($size) && round((
float) $size) <= 48) {
7717 $morecss =
'minwidth200';
7719 $morecss =
'minwidth400';
7725 if (!empty($validationClass)) {
7726 $morecss .= $validationClass;
7729 if (in_array($type, array(
'date'))) {
7730 $tmp = explode(
',', $size);
7735 if (!$required && $value ==
'') {
7740 $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required,
'', 1, (($keyprefix !=
'search_' && $keyprefix !=
'search_options_') ? 1 : 0), 0, 1);
7741 } elseif (in_array($type, array(
'datetime'))) {
7742 $tmp = explode(
',', $size);
7747 if (!$required && $value ==
'') {
7752 $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required,
'', 1, (($keyprefix !=
'search_' && $keyprefix !=
'search_options_') ? 1 : 0), 0, 1,
'',
'',
'', 1,
'',
'',
'tzuserrel');
7753 } elseif (in_array($type, array(
'duration'))) {
7754 $out = $form->select_duration($keyprefix.$key.$keysuffix, $value, 0,
'text', 0, 1);
7755 } elseif (in_array($type, array(
'int',
'integer'))) {
7756 $tmp = explode(
',', $size);
7758 $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' :
'').
'>';
7759 } elseif (in_array($type, array(
'real'))) {
7760 $out =
'<input type="text" class="flat '.$morecss.
'" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.
dol_escape_htmltag($value).
'"'.($moreparam ? $moreparam :
'').($autofocusoncreate ?
' autofocus' :
'').
'>';
7761 } elseif (preg_match(
'/varchar/', (
string) $type)) {
7762 $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' :
'').
'>';
7763 } elseif (in_array($type, array(
'email',
'mail',
'phone',
'url',
'ip'))) {
7764 $out =
'<input type="text" class="flat '.$morecss.
'" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.
dol_escape_htmltag($value).
'" '.($moreparam ? $moreparam :
'').($autofocusoncreate ?
' autofocus' :
'').
'>';
7765 } elseif (preg_match(
'/^text/', (
string) $type)) {
7766 if (!preg_match(
'/search_/', $keyprefix)) {
7767 if (!empty($param[
'options'])) {
7770 $out .= $form->selectarray($keyprefix.$key.$keysuffix.
"_multiinput", $param[
'options'],
'', 1, 0, 0,
"flat maxwidthonphone".$morecss);
7771 $out .=
'<input id="'.$keyprefix.$key.$keysuffix.
'_multiinputadd" type="button" class="button" value="'.$langs->trans(
"Add").
'">';
7774 function handlemultiinputdisabling(htmlname){
7775 console.log("We handle the disabling of used options for "+htmlname+"_multiinput");
7776 multiinput = $("#"+htmlname+"_multiinput");
7777 multiinput.find("option").each(function(){
7778 tmpval = $("#"+htmlname).val();
7779 tmpvalarray = tmpval.split("\n");
7780 valtotest = $(this).val();
7781 if(tmpvalarray.includes(valtotest)){
7782 $(this).prop("disabled",true);
7784 if($(this).prop("disabled") == true){
7785 console.log(valtotest)
7786 $(this).prop("disabled", false);
7792 $(document).ready(function () {
7793 $("#'.$keyprefix.$key.$keysuffix.
'_multiinputadd").on("click",function() {
7794 tmpval = $("#'.$keyprefix.$key.$keysuffix.
'").val();
7795 tmpvalarray = tmpval.split(",");
7796 valtotest = $("#'.$keyprefix.$key.$keysuffix.
'_multiinput").val();
7797 if(valtotest != -1 && !tmpvalarray.includes(valtotest)){
7798 console.log("We add the selected value to the text area '.$keyprefix.$key.$keysuffix.
'");
7802 tmpval = tmpval + "\n" + valtotest;
7804 $("#'.$keyprefix.$key.$keysuffix.
'").val(tmpval);
7805 handlemultiinputdisabling("'.$keyprefix.$key.$keysuffix.
'");
7806 $("#'.$keyprefix.$key.$keysuffix.
'_multiinput").val(-1);
7808 console.log("We add nothing the text area '.$keyprefix.$key.$keysuffix.
'");
7811 $("#'.$keyprefix.$key.$keysuffix.
'").on("change",function(){
7812 handlemultiinputdisabling("'.$keyprefix.$key.$keysuffix.
'");
7814 handlemultiinputdisabling("'.$keyprefix.$key.$keysuffix.
'");
7816 $out .=
"</script>";
7817 $value = str_replace(
',',
"\n", $value);
7819 require_once DOL_DOCUMENT_ROOT.
'/core/class/doleditor.class.php';
7820 $doleditor =
new DolEditor($keyprefix.$key.$keysuffix, $value,
'', 200,
'dolibarr_notes',
'In',
false,
false,
false, ROWS_5,
'90%');
7821 $out .= (string) $doleditor->Create(1,
'',
true,
'',
'',
'', $morecss);
7823 $out =
'<input type="text" class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.
dol_escape_htmltag($value).
'" '.($moreparam ? $moreparam :
'').
'>';
7825 } elseif (preg_match(
'/^html/', (
string) $type)) {
7826 if (!preg_match(
'/search_/', $keyprefix)) {
7827 require_once DOL_DOCUMENT_ROOT.
'/core/class/doleditor.class.php';
7828 $doleditor =
new DolEditor($keyprefix.$key.$keysuffix, $value,
'', 200,
'dolibarr_notes',
'In',
false,
false, isModEnabled(
'fckeditor') &&
getDolGlobalInt(
'FCKEDITOR_ENABLE_SOCIETE'), ROWS_5,
'90%');
7829 $out = (string) $doleditor->Create(1,
'',
true,
'',
'', $moreparam, $morecss);
7831 $out =
'<input type="text" class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.
dol_escape_htmltag($value).
'" '.($moreparam ? $moreparam :
'').
'>';
7833 } elseif ($type ==
'boolean') {
7835 if (!empty($value)) {
7836 $checked =
' checked value="1" ';
7838 $checked =
' value="1" ';
7840 $out =
'<input type="checkbox" class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" '.$checked.
' '.($moreparam ? $moreparam :
'').
'>';
7841 } elseif ($type ==
'price') {
7842 if (!empty($value)) {
7843 $value =
price($value);
7845 $out =
'<input type="text" class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.$value.
'" '.($moreparam ? $moreparam :
'').
'> '.$langs->getCurrencySymbol(
$conf->currency);
7846 } elseif ($type ==
'stars') {
7847 $out =
'<input type="hidden" class="flat '.$morecss.
'" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.
dol_escape_htmltag($value).
'"'.($moreparam ? $moreparam :
'').($autofocusoncreate ?
' autofocus' :
'').
'>';
7848 $out .=
'<div class="star-selection" id="'.$keyprefix.$key.$keysuffix.
'_selection">';
7850 while ($i <= $size) {
7851 $out .=
'<span class="star" data-value="'.$i.
'">'.
img_picto(
'',
'fontawesome_star_fas').
'</span>';
7856 jQuery(function($) { /* commonobject.class.php 1 */
7857 let container = $("#'.$keyprefix.$key.$keysuffix.
'_selection");
7858 let selectedStars = parseInt($("#'.$keyprefix.$key.$keysuffix.
'").val()) || 0;
7859 container.find(".star").each(function() {
7860 $(this).toggleClass("active", $(this).data("value") <= selectedStars);
7862 container.find(".star").on("mouseover", function() {
7863 let selectedStar = $(this).data("value");
7864 container.find(".star").each(function() {
7865 $(this).toggleClass("active", $(this).data("value") <= selectedStar);
7868 container.on("mouseout", function() {
7869 container.find(".star").each(function() {
7870 $(this).toggleClass("active", $(this).data("value") <= selectedStars);
7873 container.find(".star").off("click").on("click", function() {
7874 selectedStars = $(this).data("value");
7875 if (selectedStars === 1 && $("#'.$keyprefix.$key.$keysuffix.
'").val() == 1) {
7878 $("#'.$keyprefix.$key.$keysuffix.
'").val(selectedStars);
7879 container.find(".star").each(function() {
7880 $(this).toggleClass("active", $(this).data("value") <= selectedStars);
7885 } elseif (preg_match(
'/^double(\([0-9],[0-9]\)){0,1}/', (
string) $type)) {
7886 if (!empty($value)) {
7887 $value =
price($value);
7889 $out =
'<input type="text" class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.$value.
'" '.($moreparam ? $moreparam :
'').
'> ';
7890 } elseif ($type ==
'select') {
7893 include_once DOL_DOCUMENT_ROOT.
'/core/lib/ajax.lib.php';
7894 $out .=
ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
7900 foreach ($param[
'options'] as $keyb => $valb) {
7901 if ((
string) $keyb ==
'') {
7904 if (strpos($valb,
"|") !==
false) {
7905 list($valb, $parent) = explode(
'|', $valb);
7908 $tmpselect .=
'<option value="'.$keyb.
'"';
7909 $tmpselect .= (((string) $value == (
string) $keyb) ?
' selected' :
'');
7910 if (!empty($parent)) {
7913 $tmpselect .= (!empty($parent) ?
' parent="'.$parent.
'"' :
'');
7914 $tmpselect .=
'>'.$langs->trans($valb).
'</option>';
7917 $out .=
'<select class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" '.($moreparam ? $moreparam :
'').
'>';
7918 if ((!isset($this->fields[$key][
'default'])) || empty($this->fields[$key][
'notnull']) || ($this->fields[$key][
'notnull'] != 1) || $nbchoice >= 2) {
7919 $out .=
'<option value="0"> </option>';
7922 $out .=
'</select>';
7923 } elseif ($type ==
'sellist') {
7926 include_once DOL_DOCUMENT_ROOT.
'/core/lib/ajax.lib.php';
7927 $out .=
ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
7930 $out .=
'<select class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" '.($moreparam ? $moreparam :
'').
'>';
7931 if (is_array($param[
'options'])) {
7932 $tmpparamoptions = array_keys($param[
'options']);
7933 $paramoptions = preg_split(
'/[\r\n]+/', $tmpparamoptions[0]);
7935 $InfoFieldList = explode(
":", $paramoptions[0], 5);
7947 if (! empty($InfoFieldList[4])) {
7949 $parenthesisopen = 0;
7950 while (substr($InfoFieldList[4], $pos, 1) !==
'' && ($parenthesisopen || $pos == 0 || substr($InfoFieldList[4], $pos, 1) !=
':')) {
7951 if (substr($InfoFieldList[4], $pos, 1) ==
'(') {
7954 if (substr($InfoFieldList[4], $pos, 1) ==
')') {
7959 $tmpbefore = substr($InfoFieldList[4], 0, $pos);
7960 $tmpafter = substr($InfoFieldList[4], $pos + 1);
7962 $InfoFieldList[4] = $tmpbefore;
7963 if ($tmpafter !==
'') {
7964 $InfoFieldList = array_merge($InfoFieldList, explode(
':', $tmpafter));
7970 if (preg_match(
'/^\(?([a-z0-9]+)([=<>]+)(\d+)\)?$/i', $InfoFieldList[4], $reg)) {
7971 $InfoFieldList[4] =
'('.$reg[1].
':'.$reg[2].
':'.$reg[3].
')';
7982 $keyList = (empty($InfoFieldList[2]) ?
'rowid' : $InfoFieldList[2].
' as rowid');
7984 if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
7985 if (strpos($InfoFieldList[4],
'extra.') !==
false) {
7986 $keyList =
'main.'.$InfoFieldList[2].
' as rowid';
7988 $keyList = $InfoFieldList[2].
' as rowid';
7991 if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
7992 list($parentName, $parentField) = explode(
'|', $InfoFieldList[3]);
7993 if (!empty($InfoFieldList[4]) && strpos($InfoFieldList[4],
'extra.') !==
false) {
7994 $keyList .=
', main.'.$parentField;
7996 $keyList .=
', '.$parentField;
8000 $filter_categorie =
false;
8001 if (count($InfoFieldList) > 5) {
8002 if ($InfoFieldList[0] ==
'categorie') {
8003 $filter_categorie =
true;
8007 if (!$filter_categorie) {
8008 $fields_label = explode(
'|', $InfoFieldList[1]);
8009 if (is_array($fields_label)) {
8011 $keyList .= implode(
', ', $fields_label);
8015 $sql =
"SELECT " . $keyList;
8016 $sql .=
" FROM " . $this->db->prefix() . $InfoFieldList[0];
8018 if (!empty($InfoFieldList[4])) {
8020 if (strpos($InfoFieldList[4],
'$SEL$') !==
false) {
8021 $InfoFieldList[4] = str_replace(
'$SEL$',
'SELECT', $InfoFieldList[4]);
8025 if (strpos($InfoFieldList[4],
'$ID$') !==
false && !empty($objectid)) {
8026 $InfoFieldList[4] = str_replace(
'$ID$', (
string) $objectid, $InfoFieldList[4]);
8028 $InfoFieldList[4] = str_replace(
'$ID$',
'0', $InfoFieldList[4]);
8033 if (strpos($InfoFieldList[4],
'extra') !==
false) {
8034 $sql .=
" as main, " . $this->db->sanitize($this->db->prefix() . $InfoFieldList[0]) .
"_extrafields as extra";
8035 $sqlwhere .=
" WHERE extra.fk_object = main." . $this->db->sanitize($InfoFieldList[2]);
8041 $sqlwhere .=
' WHERE 1=1';
8058 if (in_array($InfoFieldList[0], array(
'tablewithentity'))) {
8059 $sqlwhere .=
" AND entity = " . ((int)
$conf->entity);
8064 if (isset($InfoFieldList[7]) && preg_match(
'/^[a-z0-9_\-,]+$/i', $InfoFieldList[7])) {
8065 $sql .=
" ORDER BY ".$this->db->escape($InfoFieldList[7]);
8067 $sql .=
" ORDER BY ".$this->db->sanitize(implode(
', ', $fields_label));
8069 $sql .=
' LIMIT ' .
getDolGlobalInt(
'MAIN_EXTRAFIELDS_LIMIT_SELLIST_SQL', 1000);
8072 dol_syslog(get_class($this) .
'::showInputField type=sellist', LOG_DEBUG);
8073 $resql = $this->db->query($sql);
8075 $out .=
'<option value="0"> </option>';
8076 $num = $this->db->num_rows($resql);
8080 $obj = $this->db->fetch_object($resql);
8084 $fields_label = explode(
'|', $InfoFieldList[1]);
8085 if (count($fields_label) > 1) {
8087 foreach ($fields_label as $field_toshow) {
8088 $labeltoshow .= $obj->$field_toshow .
' ';
8091 $labeltoshow = $obj->{$InfoFieldList[1]};
8093 $labeltoshow =
dol_trunc($labeltoshow, 45);
8095 if ($value == $obj->rowid) {
8096 foreach ($fields_label as $field_toshow) {
8097 $translabel = $langs->trans($obj->$field_toshow);
8098 if ($translabel != $obj->$field_toshow) {
8099 $labeltoshow =
dol_trunc($translabel) .
' ';
8101 $labeltoshow =
dol_trunc($obj->$field_toshow) .
' ';
8104 $out .=
'<option value="' . $obj->rowid .
'" selected>' . $labeltoshow .
'</option>';
8107 $translabel = $langs->trans($obj->{$InfoFieldList[1]});
8108 if ($translabel != $obj->{$InfoFieldList[1]}) {
8109 $labeltoshow =
dol_trunc($translabel, 18);
8111 $labeltoshow =
dol_trunc($obj->{$InfoFieldList[1]});
8114 if (empty($labeltoshow)) {
8115 $labeltoshow =
'(not defined)';
8117 if ($value == $obj->rowid) {
8118 $out .=
'<option value="' . $obj->rowid .
'" selected>' . $labeltoshow .
'</option>';
8121 if (!empty($InfoFieldList[3]) && $parentField) {
8122 $parent = $parentName .
':' . $obj->{$parentField};
8126 $out .=
'<option value="' . $obj->rowid .
'"';
8127 $out .= ($value == $obj->rowid ?
' selected' :
'');
8128 $out .= (!empty($parent) ?
' parent="' . $parent .
'"' :
'');
8129 $out .=
'>' . $labeltoshow .
'</option>';
8134 $this->db->free($resql);
8136 print
'Error in request ' . $sql .
' ' . $this->db->lasterror() .
'. Check setup of extra parameters.<br>';
8139 require_once DOL_DOCUMENT_ROOT.
'/categories/class/categorie.class.php';
8140 $categcode = $InfoFieldList[5];
8141 if (is_numeric($categcode)) {
8142 $categcode = Categorie::$MAP_ID_TO_CODE[(int) $InfoFieldList[5]];
8144 $data = $form->select_all_categories($categcode,
'',
'parent', 64, $InfoFieldList[6], 1, 1);
8145 $out .=
'<option value="0"> </option>';
8146 foreach ($data as $data_key => $data_value) {
8147 $out .=
'<option value="' . $data_key .
'"';
8148 $out .= ($value == $data_key ?
' selected' :
'');
8149 $out .=
'>' . $data_value .
'</option>';
8153 $out .=
'</select>';
8154 } elseif ($type ==
'checkbox') {
8155 $value_arr = explode(
',', $value);
8156 $out = $form->multiselectarray($keyprefix.$key.$keysuffix, (empty($param[
'options']) ?
null : $param[
'options']), $value_arr, 0, 0, $morecss, 0,
'100%');
8157 } elseif ($type ==
'radio') {
8159 foreach ($param[
'options'] as $keyopt => $valopt) {
8160 $out .=
'<input class="flat '.$morecss.
'" type="radio" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" '.($moreparam ? $moreparam :
'');
8161 $out .=
' value="'.$keyopt.
'"';
8162 $out .=
' id="'.$keyprefix.$key.$keysuffix.
'_'.$keyopt.
'"';
8163 $out .= ($value == $keyopt ?
'checked' :
'');
8164 $out .=
'/><label for="'.$keyprefix.$key.$keysuffix.
'_'.$keyopt.
'">'.$valopt.
'</label><br>';
8166 } elseif ($type ==
'chkbxlst') {
8167 if (is_array($value)) {
8168 $value_arr = $value;
8170 $value_arr = explode(
',', $value);
8173 if (is_array($param[
'options'])) {
8174 $tmpparamoptions = array_keys($param[
'options']);
8175 $paramoptions = preg_split(
'/[\r\n]+/', $tmpparamoptions[0]);
8177 $InfoFieldList = explode(
":", $paramoptions[0], 5);
8189 if (! empty($InfoFieldList[4])) {
8191 $parenthesisopen = 0;
8192 while (substr($InfoFieldList[4], $pos, 1) !==
'' && ($parenthesisopen || $pos == 0 || substr($InfoFieldList[4], $pos, 1) !=
':')) {
8193 if (substr($InfoFieldList[4], $pos, 1) ==
'(') {
8196 if (substr($InfoFieldList[4], $pos, 1) ==
')') {
8201 $tmpbefore = substr($InfoFieldList[4], 0, $pos);
8202 $tmpafter = substr($InfoFieldList[4], $pos + 1);
8204 $InfoFieldList[4] = $tmpbefore;
8205 if ($tmpafter !==
'') {
8206 $InfoFieldList = array_merge($InfoFieldList, explode(
':', $tmpafter));
8211 if (preg_match(
'/^\(?([a-z0-9]+)([=<>]+)(\d+)\)?$/i', $InfoFieldList[4], $reg)) {
8212 $InfoFieldList[4] =
'('.$reg[1].
':'.$reg[2].
':'.$reg[3].
')';
8220 '@phan-var-force array{0:string,1:string,2:string,3:string,3:string,5:string,6:string} $InfoFieldList';
8225 $keyList = (empty($InfoFieldList[2]) ?
'rowid' : $InfoFieldList[2].
' as rowid');
8227 if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
8228 if (strpos($InfoFieldList[4],
'extra.') !==
false) {
8229 $keyList =
'main.'.$InfoFieldList[2].
' as rowid';
8231 $keyList = $InfoFieldList[2].
' as rowid';
8234 if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
8235 list($parentName, $parentField) = explode(
'|', $InfoFieldList[3]);
8236 if (!empty($InfoFieldList[4]) && strpos($InfoFieldList[4],
'extra.') !==
false) {
8237 $keyList .=
', main.'.$parentField;
8239 $keyList .=
', '.$parentField;
8243 $filter_categorie =
false;
8244 if (count($InfoFieldList) > 5) {
8245 if ($InfoFieldList[0] ==
'categorie') {
8246 $filter_categorie =
true;
8251 if (!$filter_categorie) {
8252 $fields_label = explode(
'|', $InfoFieldList[1]);
8253 if (is_array($fields_label)) {
8255 $keyList .= implode(
', ', $fields_label);
8259 $sql =
"SELECT " . $keyList;
8260 $sql .=
' FROM ' . $this->db->prefix() . $InfoFieldList[0];
8262 if (!empty($InfoFieldList[4])) {
8264 if (strpos($InfoFieldList[4],
'$SEL$') !==
false) {
8265 $InfoFieldList[4] = str_replace(
'$SEL$',
'SELECT', $InfoFieldList[4]);
8269 if (strpos($InfoFieldList[4],
'$ID$') !==
false && !empty($objectid)) {
8270 $InfoFieldList[4] = str_replace(
'$ID$', (
string) $objectid, $InfoFieldList[4]);
8272 $InfoFieldList[4] = str_replace(
'$ID$',
'0', $InfoFieldList[4]);
8277 if (strpos($InfoFieldList[4],
'extra') !==
false) {
8278 $sql .=
' as main, ' . $this->db->sanitize($this->db->prefix() . $InfoFieldList[0]) .
'_extrafields as extra';
8279 $sqlwhere .=
" WHERE extra.fk_object = main." . $this->db->sanitize($InfoFieldList[2]);
8285 $sqlwhere .=
' WHERE 1=1';
8302 if (in_array($InfoFieldList[0], array(
'tablewithentity'))) {
8303 $sqlwhere .=
" AND entity = " . ((int)
$conf->entity);
8310 dol_syslog(get_class($this) .
'::showInputField type=chkbxlst', LOG_DEBUG);
8312 $resql = $this->db->query($sql);
8314 $num = $this->db->num_rows($resql);
8321 $obj = $this->db->fetch_object($resql);
8325 $fields_label = explode(
'|', $InfoFieldList[1]);
8326 if (count($fields_label) > 1) {
8328 foreach ($fields_label as $field_toshow) {
8329 $labeltoshow .= $obj->$field_toshow .
' ';
8332 $labeltoshow = $obj->{$InfoFieldList[1]};
8334 $labeltoshow =
dol_trunc($labeltoshow, 45);
8336 if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
8337 foreach ($fields_label as $field_toshow) {
8338 $translabel = $langs->trans($obj->$field_toshow);
8339 if ($translabel != $obj->$field_toshow) {
8340 $labeltoshow =
dol_trunc($translabel, 18) .
' ';
8342 $labeltoshow =
dol_trunc($obj->$field_toshow, 18) .
' ';
8346 $data[$obj->rowid] = $labeltoshow;
8349 $translabel = $langs->trans($obj->{$InfoFieldList[1]});
8350 if ($translabel != $obj->{$InfoFieldList[1]}) {
8351 $labeltoshow =
dol_trunc($translabel, 18);
8353 $labeltoshow =
dol_trunc($obj->{$InfoFieldList[1]}, 18);
8356 if (empty($labeltoshow)) {
8357 $labeltoshow =
'(not defined)';
8360 if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
8361 $data[$obj->rowid] = $labeltoshow;
8364 if (!empty($InfoFieldList[3]) && $parentField) {
8365 $parent = $parentName .
':' . $obj->{$parentField};
8369 $data[$obj->rowid] = $labeltoshow;
8374 $this->db->free($resql);
8376 $out = $form->multiselectarray($keyprefix . $key . $keysuffix, $data, $value_arr, 0, 0, $morecss, 0,
'100%');
8378 print
'Error in request ' . $sql .
' ' . $this->db->lasterror() .
'. Check setup of extra parameters.<br>';
8381 require_once DOL_DOCUMENT_ROOT.
'/categories/class/categorie.class.php';
8382 $categcode = $InfoFieldList[5];
8383 if (is_numeric($categcode)) {
8384 $categcode = Categorie::$MAP_ID_TO_CODE[(int) $InfoFieldList[5]];
8386 $data = $form->select_all_categories($categcode,
'',
'parent', 64, $InfoFieldList[6], 1, 1);
8387 $out = $form->multiselectarray($keyprefix . $key . $keysuffix, $data, $value_arr, 0, 0, $morecss, 0,
'100%');
8390 } elseif ($type ==
'link') {
8393 $param_list = array_keys($param[
'options']);
8394 $param_list_array = explode(
':', $param_list[0], 4);
8396 $showempty = (($required && $default !=
'') ? 0 : 1);
8398 if (!preg_match(
'/search_/', $keyprefix)) {
8399 if (!empty($param_list_array[2])) {
8401 if (!empty($this->fields[$key][
'picto'])) {
8402 $morecss .=
' widthcentpercentminusxx';
8404 $morecss .=
' widthcentpercentminusx';
8408 if (!empty($this->fields[$key][
'picto'])) {
8409 $morecss .=
' widthcentpercentminusx';
8422 $objectfield = $val;
8425 $out = $form->selectForForms($param_list_array[0], $keyprefix.$key.$keysuffix, (
int) $value, $showempty,
'',
'', $morecss, $moreparam, 0, (empty($val[
'disabled']) ? 0 : 1),
'', $objectfield);
8427 if (!empty($param_list_array[2])) {
8428 if ((!GETPOSTISSET(
'backtopage') || strpos(
GETPOST(
'backtopage'), $_SERVER[
'PHP_SELF']) === 0)
8429 && empty($val[
'disabled']) && empty($nonewbutton)) {
8430 list($class, $classfile) = explode(
':', $param_list[0]);
8431 if (file_exists(
dol_buildpath(dirname(dirname($classfile)).
'/card.php'))) {
8432 $url_path =
dol_buildpath(dirname(dirname($classfile)).
'/card.php', 1);
8434 $url_path =
dol_buildpath(dirname(dirname($classfile)).
'/'.strtolower($class).
'_card.php', 1);
8436 $paramforthenewlink =
'';
8437 $paramforthenewlink .= (GETPOSTISSET(
'action') ?
'&action='.GETPOST(
'action',
'aZ09') :
'');
8438 $paramforthenewlink .= (GETPOSTISSET(
'id') ?
'&id='.GETPOSTINT(
'id') :
'');
8439 $paramforthenewlink .= (GETPOSTISSET(
'origin') ?
'&origin='.GETPOST(
'origin',
'aZ09') :
'');
8440 $paramforthenewlink .= (GETPOSTISSET(
'originid') ?
'&originid='.GETPOSTINT(
'originid') :
'');
8441 $paramforthenewlink .=
'&fk_'.strtolower($class).
'=--IDFORBACKTOPAGE--';
8443 $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>';
8446 } elseif ($type ==
'password') {
8448 if ($keyprefix.$key.$keysuffix ==
'pass_crypted') {
8449 $out =
'<input type="'.($keyprefix ==
'search_' ?
'text' :
'password').
'" class="flat '.$morecss.
'" name="pass" id="pass" value="" '.($moreparam ? $moreparam :
'').
'>';
8450 $out .=
'<input type="hidden" name="pass_crypted" id="pass_crypted" value="'.$value.
'" '.($moreparam ? $moreparam :
'').
'>';
8452 $out =
'<input type="'.($keyprefix ==
'search_' ?
'text' :
'password').
'" class="flat '.$morecss.
'" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.$value.
'" '.($moreparam ? $moreparam :
'').
'>';
8454 } elseif ($type ==
'array') {
8456 $newval[
'type'] =
'varchar(256)';
8459 if (!empty($value)) {
8460 foreach ($value as $option) {
8461 $out .=
'<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).
'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
8462 $out .= $this->showInputField($newval, $keyprefix.$key.$keysuffix.
'[]', $option, $moreparam,
'',
'', $morecss).
'<br></span>';
8465 $out .=
'<a id="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).
'_add" href="javascript:;"><span class="fa fa-plus-circle valignmiddle"></span></a>';
8467 $newInput =
'<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).
'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
8468 $newInput .= $this->showInputField($newval, $keyprefix.$key.$keysuffix.
'[]',
'', $moreparam,
'',
'', $morecss).
'<br></span>';
8470 if (!empty(
$conf->use_javascript_ajax)) {
8472 <script nonce="'.getNonce().
'">
8473 $(document).ready(function() {
8474 $("a#'.
dol_escape_js($keyprefix.$key.$keysuffix).
'_add").click(function() {
8478 $(document).on("click", "a.'.
dol_escape_js($keyprefix.$key.$keysuffix).
'_del", function() {
8479 $(this).parent().remove();
8485 if (!empty($hidden)) {
8486 $out =
'<input type="hidden" value="'.$value.
'" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'"/>';
8489 if ($isDependList == 1) {
8490 $out .= $this->getJSListDependancies(
'_common');
8498 if (!empty($fieldValidationErrorMsg) && function_exists(
'getFieldErrorIcon')) {
8499 $out .=
' '.getFieldErrorIcon($fieldValidationErrorMsg);
8518 public function showOutputField($val, $key, $value, $moreparam =
'', $keysuffix =
'', $keyprefix =
'', $morecss =
'')
8520 global
$conf, $langs, $form;
8524 if (!is_object($form)) {
8525 require_once DOL_DOCUMENT_ROOT.
'/core/class/html.form.class.php';
8526 $form =
new Form($this->db);
8530 $type = empty($val[
'type']) ?
'' : $val[
'type'];
8531 $size = empty($val[
'css']) ?
'' : $val[
'css'];
8535 if (preg_match(
'/varchar\((\d+)\)/', $type, $reg)) {
8538 } elseif (preg_match(
'/varchar/', $type)) {
8541 if (!empty($val[
'arrayofkeyval']) && is_array($val[
'arrayofkeyval'])) {
8543 if (empty($this->fields[$key][
'multiinput'])) {
8544 $type = (($this->fields[$key][
'type'] ==
'checkbox') ? $this->fields[$key][
'type'] :
'select');
8547 if (isset($val[
'type']) && preg_match(
'/^integer:(.*):(.*)/i', $val[
'type'], $reg)) {
8551 $default = empty($val[
'default']) ?
'' : $val[
'default'];
8552 $computed = empty($val[
'computed']) ?
'' : $val[
'computed'];
8553 $unique = empty($val[
'unique']) ?
'' : $val[
'unique'];
8554 $required = empty($val[
'required']) ?
'' : $val[
'required'];
8556 $param[
'options'] = array();
8558 if (!empty($val[
'arrayofkeyval']) && is_array($val[
'arrayofkeyval'])) {
8559 $param[
'options'] = $val[
'arrayofkeyval'];
8561 if (isset($val[
'type']) && preg_match(
'/^integer:([^:]*):([^:]*)/i', $val[
'type'], $reg)) {
8563 $stringforoptions = $reg[1].
':'.$reg[2];
8565 if ($reg[1] ==
'User') {
8566 $stringforoptions .=
':#getnomurlparam1=-1';
8568 $param[
'options'] = array($stringforoptions => $stringforoptions);
8569 } elseif (isset($val[
'type']) && preg_match(
'/^sellist:(.*):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
8570 $param[
'options'] = array($reg[1].
':'.$reg[2].
':'.$reg[3].
':'.$reg[4] =>
'N');
8572 } elseif (isset($val[
'type']) && preg_match(
'/^sellist:(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
8573 $param[
'options'] = array($reg[1].
':'.$reg[2].
':'.$reg[3] =>
'N');
8575 } elseif (isset($val[
'type']) && preg_match(
'/^sellist:(.*):(.*)/i', $val[
'type'], $reg)) {
8576 $param[
'options'] = array($reg[1].
':'.$reg[2] =>
'N');
8578 } elseif (isset($val[
'type']) && preg_match(
'/^chkbxlst:(.*)/i', $val[
'type'], $reg)) {
8579 $param[
'options'] = array($reg[1] =>
'N');
8581 } elseif (isset($val[
'type']) && preg_match(
'/stars\((\d+)\)/', $val[
'type'], $reg)) {
8582 $param[
'options'] = array();
8587 $langfile = empty($val[
'langfile']) ?
'' : $val[
'langfile'];
8588 $list = (empty($val[
'list']) ?
'' : $val[
'list']);
8589 $help = (empty($val[
'help']) ?
'' : $val[
'help']);
8590 $hidden = (($val[
'visible'] == 0) ? 1 : 0);
8600 $value =
dol_eval((
string) $computed, 1, 0,
'2');
8603 if (empty($morecss)) {
8604 if ($type ==
'date') {
8605 $morecss =
'minwidth100imp';
8606 } elseif ($type ==
'datetime' || $type ==
'timestamp') {
8607 $morecss =
'minwidth200imp';
8608 } elseif (in_array($type, array(
'int',
'double',
'price'))) {
8609 $morecss =
'maxwidth75';
8610 } elseif ($type ==
'url') {
8611 $morecss =
'minwidth400';
8612 } elseif ($type ==
'boolean') {
8615 if (is_numeric($size) && round((
float) $size) < 12) {
8616 $morecss =
'minwidth100';
8617 } elseif (is_numeric($size) && round((
float) $size) <= 48) {
8618 $morecss =
'minwidth200';
8620 $morecss =
'minwidth400';
8626 if (in_array($key, array(
'rowid',
'ref')) && method_exists($this,
'getNomUrl')) {
8628 if ($key !=
'rowid' || empty($this->fields[
'ref'])) {
8629 $value = $this->getNomUrl(1,
'', 0,
'', 1);
8631 } elseif ($key ==
'status' && method_exists($this,
'getLibStatut')) {
8632 $value = $this->getLibStatut(3);
8633 } elseif ($type ==
'date') {
8634 if (!empty($value)) {
8639 } elseif ($type ==
'datetime' || $type ==
'timestamp') {
8640 if (!empty($value)) {
8645 } elseif ($type ==
'duration') {
8646 include_once DOL_DOCUMENT_ROOT.
'/core/lib/date.lib.php';
8647 if (!is_null($value) && $value !==
'') {
8650 } elseif ($type ==
'double' || $type ==
'real') {
8651 if (!is_null($value) && $value !==
'') {
8652 $value =
price($value);
8654 } elseif ($type ==
'boolean') {
8656 if (!empty($value)) {
8657 $checked =
' checked ';
8660 $value =
'<input type="checkbox" '.$checked.
' '.($moreparam ? $moreparam :
'').
' readonly disabled>';
8662 $value =
yn($value ? 1 : 0);
8664 } elseif ($type ==
'mail' || $type ==
'email') {
8666 } elseif ($type ==
'url') {
8668 } elseif ($type ==
'phone') {
8669 $value =
dol_print_phone((
string) $value,
'', 0, 0,
'',
' ',
'phone');
8670 } elseif ($type ==
'ip') {
8672 } elseif ($type ==
'stars') {
8673 $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 :
'').
'>';
8674 $value .=
'<div class="star-selection" id="'.$keyprefix.$key.$keysuffix.$this->id.
'_selection">';
8676 while ($i <= $size) {
8677 $value .=
'<span class="star" data-value="'.$i.
'">'.
img_picto(
'',
'fontawesome_star_fas').
'</span>';
8682 $(document).ready(function() { /* commonobject.class.php 2 */
8683 let container = $("#'.$keyprefix.$key.$keysuffix.$this->id.
'_selection");
8684 let selectedStars = parseInt($("#'.$keyprefix.$key.$keysuffix.$this->id.
'").val()) || 0;
8685 container.find(".star").each(function() {
8686 $(this).toggleClass("active", $(this).data("value") <= selectedStars);
8688 container.find(".star").on("mouseover", function() {
8689 let selectedStar = $(this).data("value");
8690 container.find(".star").each(function() {
8691 $(this).toggleClass("active", $(this).data("value") <= selectedStar);
8694 container.on("mouseout", function() {
8695 container.find(".star").each(function() {
8696 $(this).toggleClass("active", $(this).data("value") <= selectedStars);
8699 container.find(".star").off("click").on("click", function() {
8700 selectedStars = $(this).data("value");
8701 if (selectedStars == 1 && $("#'.$keyprefix.$key.$keysuffix.$this->id.
'").val() == 1) {
8704 container.find("#'.$keyprefix.$key.$keysuffix.$this->id.
'").val(selectedStars);
8705 container.find(".star").each(function() {
8706 $(this).toggleClass("active", $(this).data("value") <= selectedStars);
8709 url: "ajax/'.$this->element.
'.php",
8712 objectId: "'.$this->
id.
'",
8713 field: "'.$keyprefix.$key.$keysuffix.
'",
8714 value: selectedStars,
8717 success: function(response) {
8718 var res = JSON.parse(response);
8719 console[res.status === "success" ? "log" : "error"](res.message);
8721 error: function(xhr, status, error) {
8722 console.log("Ajax request failed while updating '.$keyprefix.$key.$keysuffix.
':", error);
8728 } elseif ($type ==
'price') {
8729 if (!is_null($value) && $value !==
'') {
8730 $value =
price($value, 0, $langs, 0, 0, -1,
$conf->currency);
8732 } elseif ($type ==
'select') {
8733 $value = isset($param[
'options'][(
string) $value]) ? $param[
'options'][(string) $value] :
'';
8734 if (strpos($value,
"|") !==
false) {
8735 $value = $langs->trans(explode(
'|', $value)[0]);
8736 } elseif (! is_numeric($value)) {
8737 $value = $langs->trans($value);
8739 } elseif ($type ==
'sellist') {
8740 $param_list = array_keys($param[
'options']);
8741 $InfoFieldList = explode(
":", $param_list[0]);
8743 $selectkey =
"rowid";
8746 if (count($InfoFieldList) > 2 && !empty($InfoFieldList[2])) {
8747 $selectkey = $InfoFieldList[2];
8748 $keyList = $InfoFieldList[2].
' as rowid';
8751 $fields_label = explode(
'|', $InfoFieldList[1]);
8752 if (is_array($fields_label)) {
8754 $keyList .= implode(
', ', $fields_label);
8757 $filter_categorie =
false;
8758 if (count($InfoFieldList) > 5) {
8759 if ($InfoFieldList[0] ==
'categorie') {
8760 $filter_categorie =
true;
8764 $sql =
"SELECT ".$keyList;
8765 $sql .=
' FROM '.$this->db->prefix().$InfoFieldList[0];
8766 if (isset($InfoFieldList[4]) && strpos($InfoFieldList[4],
'extra') !==
false) {
8769 if ($selectkey ==
'rowid' && empty($value)) {
8770 $sql .=
" WHERE ".$selectkey.
" = 0";
8771 } elseif ($selectkey ==
'rowid') {
8772 $sql .=
" WHERE ".$selectkey.
" = ".((int) $value);
8774 $sql .=
" WHERE ".$selectkey.
" = '".$this->db->escape((
string) $value).
"'";
8779 dol_syslog(get_class($this).
':showOutputField:$type=sellist', LOG_DEBUG);
8780 $resql = $this->db->query($sql);
8782 if (!$filter_categorie) {
8784 $numrows = $this->db->num_rows($resql);
8786 $obj = $this->db->fetch_object($resql);
8789 $fields_label = explode(
'|', $InfoFieldList[1]);
8791 if (is_array($fields_label) && count($fields_label) > 1) {
8792 foreach ($fields_label as $field_toshow) {
8794 if (!empty($obj->$field_toshow)) {
8795 $translabel = $langs->trans($obj->$field_toshow);
8797 if ($translabel != $field_toshow) {
8798 $value .=
dol_trunc($translabel, 18) .
' ';
8800 $value .= $obj->$field_toshow .
' ';
8805 if (!empty($obj->{$InfoFieldList[1]})) {
8806 $translabel = $langs->trans($obj->{$InfoFieldList[1]});
8808 if ($translabel != $obj->{$InfoFieldList[1]}) {
8811 $value = $obj->{$InfoFieldList[1]};
8816 require_once DOL_DOCUMENT_ROOT .
'/categories/class/categorie.class.php';
8819 $obj = $this->db->fetch_object($resql);
8821 $c->fetch($obj->rowid);
8822 $ways =
$c->print_all_ways();
8823 foreach ($ways as $way) {
8824 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories"' . (
$c->color ?
' style="background: #' .
$c->color .
';"' :
' style="background: #aaa"') .
'>' .
img_object(
'',
'category') .
' ' . $way .
'</li>';
8826 $value =
'<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(
' ', $toprint).
'</ul></div>';
8829 dol_syslog(get_class($this).
'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
8831 } elseif ($type ==
'radio') {
8832 $value = $param[
'options'][(string) $value];
8833 } elseif ($type ==
'checkbox') {
8834 $value_arr = explode(
',', (
string) $value);
8836 if (is_array($value_arr) && count($value_arr) > 0) {
8838 foreach ($value_arr as $keyval => $valueval) {
8839 if (!empty($valueval)) {
8840 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' . $param[
'options'][$valueval] .
'</li>';
8843 if (!empty($toprint)) {
8844 $value =
'<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">' . implode(
' ', $toprint) .
'</ul></div>';
8847 } elseif ($type ==
'chkbxlst') {
8848 $value_arr = (isset($value) ? explode(
',', $value) : array());
8850 $param_list = array_keys($param[
'options']);
8851 $InfoFieldList = explode(
":", $param_list[0]);
8853 $selectkey =
"rowid";
8856 if (count($InfoFieldList) >= 3) {
8857 $selectkey = $InfoFieldList[2];
8858 $keyList = $InfoFieldList[2].
' as rowid';
8861 $fields_label = explode(
'|', $InfoFieldList[1]);
8862 if (is_array($fields_label)) {
8864 $keyList .= implode(
', ', $fields_label);
8867 $filter_categorie =
false;
8868 if (count($InfoFieldList) > 5) {
8869 if ($InfoFieldList[0] ==
'categorie') {
8870 $filter_categorie =
true;
8874 $sql =
"SELECT ".$keyList;
8875 $sql .=
' FROM '.$this->db->prefix().$InfoFieldList[0];
8876 if (isset($InfoFieldList[4]) && strpos($InfoFieldList[4],
'extra') !==
false) {
8882 dol_syslog(get_class($this).
':showOutputField:$type=chkbxlst', LOG_DEBUG);
8883 $resql = $this->db->query($sql);
8885 if (!$filter_categorie) {
8888 while ($obj = $this->db->fetch_object($resql)) {
8890 $fields_label = explode(
'|', $InfoFieldList[1]);
8891 if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
8892 if (is_array($fields_label) && count($fields_label) > 1) {
8893 foreach ($fields_label as $field_toshow) {
8895 if (!empty($obj->$field_toshow)) {
8896 $translabel = $langs->trans($obj->$field_toshow);
8898 if ($translabel != $field_toshow) {
8899 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' .
dol_trunc($translabel, 18) .
'</li>';
8901 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' . $obj->$field_toshow .
'</li>';
8906 if (!empty($obj->{$InfoFieldList[1]})) {
8907 $translabel = $langs->trans($obj->{$InfoFieldList[1]});
8909 if ($translabel != $obj->{$InfoFieldList[1]}) {
8910 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' .
dol_trunc($translabel, 18) .
'</li>';
8912 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' . $obj->{$InfoFieldList[1]} .
'</li>';
8918 require_once DOL_DOCUMENT_ROOT .
'/categories/class/categorie.class.php';
8921 while ($obj = $this->db->fetch_object($resql)) {
8922 if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
8924 $c->fetch($obj->rowid);
8925 $ways =
$c->print_all_ways();
8926 foreach ($ways as $way) {
8927 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories"' . (
$c->color ?
' style="background: #' .
$c->color .
';"' :
' style="background: #aaa"') .
'>' .
img_object(
'',
'category') .
' ' . $way .
'</li>';
8932 $value =
'<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(
' ', $toprint).
'</ul></div>';
8934 dol_syslog(get_class($this).
'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
8936 } elseif ($type ==
'link') {
8941 $param_list = array_keys($param[
'options']);
8945 $InfoFieldList = explode(
":", $param_list[0]);
8947 $classname = $InfoFieldList[0];
8948 $classpath = $InfoFieldList[1];
8951 $getnomurlparam = 3;
8952 $getnomurlparam2 =
'';
8954 if (preg_match(
'/#getnomurlparam1=([^#]*)/', $param_list[0], $regtmp)) {
8955 $getnomurlparam = $regtmp[1];
8957 if (preg_match(
'/#getnomurlparam2=([^#]*)/', $param_list[0], $regtmp)) {
8958 $getnomurlparam2 = $regtmp[1];
8961 if (!empty($classpath)) {
8964 if ($classname && !class_exists($classname)) {
8968 if ($element_prop) {
8969 $classname = $element_prop[
'classname'];
8974 if ($classname && class_exists($classname)) {
8975 $object =
new $classname($this->db);
8976 '@phan-var-force CommonObject $object';
8977 if (
$object->element ===
'product') {
8978 '@phan-var-force Product $object';
8979 $result =
$object->fetch((
int) $value,
'',
'',
'', 0, 1, 1);
8981 $result =
$object->fetch($value);
8984 if (
$object->element ===
'product') {
8985 '@phan-var-force Product $object';
8986 $get_name_url_param_arr = array($getnomurlparam, $getnomurlparam2, 0, -1, 0,
'', 0);
8987 if (isset($val[
'get_name_url_params'])) {
8988 $get_name_url_params = explode(
':', $val[
'get_name_url_params']);
8989 if (!empty($get_name_url_params)) {
8990 $param_num_max = count($get_name_url_param_arr) - 1;
8991 foreach ($get_name_url_params as $param_num => $param_value) {
8992 if ($param_num > $param_num_max) {
8995 $get_name_url_param_arr[$param_num] = $param_value;
9003 $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]);
9005 $value =
$object->getNomUrl($getnomurlparam, $getnomurlparam2);
9012 dol_syslog(
'Error bad setup of extrafield', LOG_WARNING);
9013 return 'Error bad setup of extrafield';
9018 } elseif ($type ==
'password') {
9019 $value =
'<span class="opacitymedium">'.$langs->trans(
"Encrypted").
'</span>';
9021 } elseif ($type ==
'array') {
9022 if (is_array($value)) {
9023 $value = implode(
'<br>', $value);
9025 dol_syslog(__METHOD__.
' Expected array from dol_eval, but got '.gettype($value), LOG_ERR);
9026 return 'Error unexpected result from code evaluation';
9029 if (!empty($value) && preg_match(
'/^text/', (
string) $type) && !preg_match(
'/search_/', $keyprefix) && !empty($param[
'options'])) {
9030 $value = str_replace(
',',
"\n", $value);
9038 return is_null($out) ?
'' : $out;
9050 unset($this->validateFieldsErrors[$fieldKey]);
9064 $msg = $langs->trans(
"UnknownError");
9067 $this->error = $this->validateFieldsErrors[$fieldKey] = $msg;
9078 if (!empty($this->validateFieldsErrors[$fieldKey])) {
9079 return $this->validateFieldsErrors[$fieldKey];
9096 if (!class_exists(
'Validate')) {
9097 require_once DOL_DOCUMENT_ROOT .
'/core/class/validate.class.php';
9100 $this->clearFieldError($fieldKey);
9102 if (!array_key_exists($fieldKey, $fields) || !is_array($fields[$fieldKey])) {
9103 $this->setFieldError($fieldKey, $langs->trans(
'FieldNotFoundInObject'));
9107 $val = $fields[$fieldKey];
9110 $param[
'options'] = array();
9111 $type = $val[
'type'];
9114 if (isset($val[
'notnull']) && $val[
'notnull'] === 1) {
9128 if (preg_match(
'/varchar\((\d+)\)/', $type, $reg)) {
9130 $maxSize = (int) $reg[1];
9131 } elseif (preg_match(
'/varchar/', $type)) {
9135 if (!empty($val[
'arrayofkeyval']) && is_array($val[
'arrayofkeyval'])) {
9139 if (!empty($val[
'type']) && preg_match(
'/^integer:(.*):(.*)/i', $val[
'type'], $reg)) {
9143 if (!empty($val[
'arrayofkeyval']) && is_array($val[
'arrayofkeyval'])) {
9144 $param[
'options'] = $val[
'arrayofkeyval'];
9147 if (preg_match(
'/^integer:(.*):(.*)/i', $val[
'type'], $reg)) {
9149 $param[
'options'] = array($reg[1].
':'.$reg[2] => $reg[1].
':'.$reg[2]);
9150 } elseif (preg_match(
'/^sellist:(.*):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
9151 $param[
'options'] = array($reg[1].
':'.$reg[2].
':'.$reg[3].
':'.$reg[4] =>
'N');
9153 } elseif (preg_match(
'/^sellist:(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
9154 $param[
'options'] = array($reg[1].
':'.$reg[2].
':'.$reg[3] =>
'N');
9156 } elseif (preg_match(
'/^sellist:(.*):(.*)/i', $val[
'type'], $reg)) {
9157 $param[
'options'] = array($reg[1].
':'.$reg[2] =>
'N');
9166 $validate =
new Validate($this->db, $langs);
9176 if ($required && !$validate->isNotEmptyString($fieldValue)) {
9177 $this->setFieldError($fieldKey, $validate->error);
9179 } elseif (!$required && !$validate->isNotEmptyString($fieldValue)) {
9185 if (!empty($maxSize) && !$validate->isMaxLength($fieldValue, $maxSize)) {
9186 $this->setFieldError($fieldKey, $validate->error);
9191 if (!empty($minSize) && !$validate->isMinLength($fieldValue, $minSize)) {
9192 $this->setFieldError($fieldKey, $validate->error);
9200 if (in_array($type, array(
'date',
'datetime',
'timestamp'))) {
9201 if (!$validate->isTimestamp($fieldValue)) {
9202 $this->setFieldError($fieldKey, $validate->error);
9207 } elseif ($type ==
'duration') {
9208 if (!$validate->isDuration($fieldValue)) {
9209 $this->setFieldError($fieldKey, $validate->error);
9214 } elseif (in_array($type, array(
'double',
'real',
'price'))) {
9216 if (!$validate->isNumeric($fieldValue)) {
9217 $this->setFieldError($fieldKey, $validate->error);
9222 } elseif ($type ==
'boolean') {
9223 if (!$validate->isBool($fieldValue)) {
9224 $this->setFieldError($fieldKey, $validate->error);
9229 } elseif ($type ==
'mail' || $type ==
'email') {
9230 if (!$validate->isEmail($fieldValue)) {
9231 $this->setFieldError($fieldKey, $validate->error);
9234 } elseif ($type ==
'url') {
9235 if (!$validate->isUrl($fieldValue)) {
9236 $this->setFieldError($fieldKey, $validate->error);
9241 } elseif ($type ==
'phone') {
9242 if (!$validate->isPhone($fieldValue)) {
9243 $this->setFieldError($fieldKey, $validate->error);
9248 } elseif ($type ==
'select' || $type ==
'radio') {
9249 if (!isset($param[
'options'][$fieldValue])) {
9250 $this->error = $langs->trans(
'RequireValidValue');
9255 } elseif ($type ==
'sellist' || $type ==
'chkbxlst') {
9256 $param_list = array_keys($param[
'options']);
9257 $InfoFieldList = explode(
":", $param_list[0]);
9258 $value_arr = explode(
',', $fieldValue);
9259 $value_arr = array_map(array($this->db,
'escape'), $value_arr);
9261 $selectkey =
"rowid";
9262 if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
9263 $selectkey = $InfoFieldList[2];
9266 if (!$validate->isInDb($value_arr, $InfoFieldList[0], $selectkey)) {
9267 $this->setFieldError($fieldKey, $validate->error);
9272 } elseif ($type ==
'link') {
9273 $param_list = array_keys($param[
'options']);
9274 $InfoFieldList = explode(
":", $param_list[0]);
9275 $classname = $InfoFieldList[0];
9276 $classpath = $InfoFieldList[1];
9277 if (!$validate->isFetchable((
int) $fieldValue, $classname, $classpath)) {
9278 $lastIsFetchableError = $validate->error;
9281 if ($validate->isFetchableElement((
int) $fieldValue, $classname)) {
9285 $this->setFieldError($fieldKey, $lastIsFetchableError);
9309 public function showOptionals($extrafields, $mode =
'view', $params =
null, $keysuffix =
'', $keyprefix =
'', $onetrtd =
'', $display_type =
'card')
9311 global $db,
$conf, $langs, $action, $form, $hookmanager;
9313 if (!is_object($form)) {
9314 $form =
new Form($db);
9316 if (!is_object($extrafields)) {
9317 dol_syslog(
'Bad parameter extrafields for showOptionals', LOG_ERR);
9318 return 'Bad parameter extrafields for showOptionals';
9320 if (!is_array($extrafields->attributes[$this->table_element])) {
9321 dol_syslog(
"extrafields->attributes was not loaded with extrafields->fetch_name_optionals_label(table_element);", LOG_WARNING);
9326 $parameters = array(
'mode' => $mode,
'params' => $params,
'keysuffix' => $keysuffix,
'keyprefix' => $keyprefix,
'display_type' => $display_type);
9327 $reshook = $hookmanager->executeHooks(
'showOptionals', $parameters, $this, $action);
9329 if (empty($reshook)) {
9330 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) {
9332 $out .=
'<!-- commonobject:showOptionals --> ';
9335 $nbofextrafieldsshown = 0;
9338 $lastseparatorkeyfound =
'';
9339 $extrafields_collapse_num =
'';
9340 $extrafields_collapse_num_old =
'';
9343 foreach ($extrafields->attributes[$this->table_element][
'label'] as $key => $label) {
9347 if (is_array($params) && array_key_exists(
'onlykey', $params) && $key != $params[
'onlykey']) {
9353 if ($enabled && isset($extrafields->attributes[$this->table_element][
'enabled'][$key])) {
9354 $enabled = (int)
dol_eval((
string) $extrafields->attributes[$this->table_element][
'enabled'][$key], 1, 1,
'2');
9356 if (empty($enabled)) {
9361 if (isset($extrafields->attributes[$this->table_element][
'list'][$key])) {
9362 $visibility = (int)
dol_eval((
string) $extrafields->attributes[$this->table_element][
'list'][$key], 1, 1,
'2');
9366 if ($perms && isset($extrafields->attributes[$this->table_element][
'perms'][$key])) {
9367 $perms = (int)
dol_eval((
string) $extrafields->attributes[$this->table_element][
'perms'][$key], 1, 1,
'2');
9370 if (($mode ==
'create') && !in_array(abs($visibility), array(1, 3))) {
9372 } elseif (($mode ==
'edit') && !in_array(abs($visibility), array(1, 3, 4))) {
9376 $ef_name =
'options_' . $key;
9377 $ef_value = isset($this->array_options[$ef_name]) ? $this->array_options[$ef_name] :
'';
9378 $out .=
'<input type="hidden" name="' . $ef_name .
'" id="' . $ef_name .
'" value="' .
dolPrintHTMLForAttribute($ef_value) .
'" />' .
"\n";
9380 } elseif ($mode ==
'view' && empty($visibility)) {
9383 if (empty($perms)) {
9388 if (!empty($extrafields->attributes[$this->table_element][
'langfile'][$key])) {
9389 $langs->load($extrafields->attributes[$this->table_element][
'langfile'][$key]);
9394 if (is_array($params) && count($params) > 0 && $display_type ==
'card') {
9395 if (array_key_exists(
'cols', $params)) {
9396 $colspan = $params[
'cols'];
9397 } elseif (array_key_exists(
'colspan', $params)) {
9399 if (preg_match(
'/colspan="(\d+)"/', $params[
'colspan'], $reg)) {
9402 $colspan = $params[
'colspan'];
9406 $colspan = intval($colspan);
9410 $value = ((!empty($this->array_options) && array_key_exists(
"options_".$key.$keysuffix, $this->array_options)) ? $this->array_options[
"options_".$key.$keysuffix] :
null);
9416 $check =
'alphanohtml';
9417 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'html',
'text'))) {
9418 $check =
'restricthtml';
9420 $getposttemp =
GETPOST($keyprefix.
'options_'.$key.$keysuffix, $check, 3);
9422 if (is_array($getposttemp) || $getposttemp !=
'' || GETPOSTISSET($keyprefix.
'options_'.$key.$keysuffix)) {
9423 if (is_array($getposttemp)) {
9425 $value = implode(
",", $getposttemp);
9427 $value = $getposttemp;
9429 } elseif (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'int'))) {
9430 $value = (!empty($this->array_options[
"options_".$key]) || (isset($this->array_options[
"options_".$key]) && $this->array_options[
"options_".$key] ===
'0')) ? $this->array_options[
"options_".$key] :
'';
9432 $value = (!empty($this->array_options[
"options_".$key]) ? $this->array_options[
"options_".$key] :
'');
9438 $nbofextrafieldsshown++;
9441 if ($extrafields->attributes[$this->table_element][
'type'][$key] ==
'separate') {
9442 $extrafields_collapse_num = $key;
9460 $out .= $extrafields->showSeparator($key, $this, ($colspan ? $colspan + 1 : 2), $display_type, $mode);
9462 $lastseparatorkeyfound = $key;
9464 $collapse_group = $extrafields_collapse_num.(!empty($this->
id) ?
'_'.$this->id :
'');
9466 $class = (!empty($extrafields->attributes[$this->table_element][
'hidden'][$key]) ?
'hideobject ' :
'');
9468 if (is_array($params) && count($params) > 0) {
9469 if (array_key_exists(
'class', $params)) {
9470 $class .= $params[
'class'].
' ';
9472 if (array_key_exists(
'style', $params)) {
9473 $csstyle = $params[
'style'];
9478 $domData =
' data-element="extrafield"';
9479 $domData .=
' data-targetelement="'.$this->element.
'"';
9480 $domData .=
' data-targetid="'.$this->id.
'"';
9482 $html_id = (empty($this->
id) ?
'' :
'extrarow-'.$this->element.
'_'.$key.
'_'.
$this->id);
9483 if ($display_type ==
'card') {
9488 if ($action ==
'selectlines') {
9495 $force_values_on_change_company = (
9496 ($this->element ==
'facture' &&
getDolGlobalInt(
'THIRDPARTY_PROPAGATE_EXTRAFIELDS_TO_INVOICE'))
9497 || ($this->element ==
'commande' &&
getDolGlobalInt(
'THIRDPARTY_PROPAGATE_EXTRAFIELDS_TO_ORDER'))
9498 || ($this->element ==
'order_supplier' &&
getDolGlobalInt(
'THIRDPARTY_PROPAGATE_EXTRAFIELDS_TO_SUPPLIER_ORDER'))
9500 if ($force_values_on_change_company &&
GETPOSTINT(
'changecompany')) {
9501 $value = $this->array_options[
'options_'.$key] ?? $value;
9505 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'date'))) {
9506 $datenotinstring =
null;
9507 if (array_key_exists(
'options_'.$key, $this->array_options)) {
9508 $datenotinstring = $this->array_options[
'options_'.$key];
9509 if (!is_numeric($this->array_options[
'options_'.$key])) {
9510 $datenotinstring = $this->db->jdate($datenotinstring);
9513 $datekey = $keyprefix.
'options_'.$key.$keysuffix;
9516 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'datetime'))) {
9517 $datenotinstring =
null;
9518 if (array_key_exists(
'options_'.$key, $this->array_options)) {
9519 $datenotinstring = $this->array_options[
'options_'.$key];
9520 if (!is_numeric($this->array_options[
'options_'.$key])) {
9521 $datenotinstring = $this->db->jdate($datenotinstring);
9524 $timekey = $keyprefix.
'options_'.$key.$keysuffix;
9525 $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;
9528 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'price',
'double'))) {
9529 if (GETPOSTISSET($keyprefix.
'options_'.$key.$keysuffix) || $value) {
9531 } elseif (isset($this->array_options[
'options_'.$key])) {
9532 $value = $this->array_options[
'options_'.$key];
9537 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'html',
'text',
'varchar',
'select',
'radio',
'int',
'boolean'))) {
9538 if ($action ==
'create' || $mode ==
'create') {
9539 $value = (GETPOSTISSET($keyprefix.
'options_'.$key.$keysuffix) || $value) ? $value : $extrafields->attributes[$this->table_element][
'default'][$key];
9543 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'checkbox'))) {
9544 if ($action ==
'create') {
9545 $value = (GETPOSTISSET($keyprefix.
'options_'.$key.$keysuffix) || $value) ? $value : explode(
',', $extrafields->attributes[$this->table_element][
'default'][$key]);
9550 $labeltoshow = $langs->trans($label);
9551 $helptoshow = $langs->trans($extrafields->attributes[$this->table_element][
'help'][$key]);
9552 if ($display_type ==
'card') {
9553 $out .=
'<tr '.($html_id ?
'id="'.$html_id.
'" ' :
'').$csstyle.
' class="field_options_'.$key.
' '.$class.$this->element.
'_extras_'.$key.
' trextrafields_collapse'.$collapse_group.
'" '.$domData.
' >';
9554 if (
getDolGlobalString(
'MAIN_VIEW_LINE_NUMBER') && ($action ==
'view' || $action ==
'valid' || $action ==
'editline' || $action ==
'confirm_valid' || $action ==
'confirm_cancel')) {
9555 $out .=
'<td></td>';
9557 $out .=
'<td class="'.(empty($params[
'tdclass']) ?
'titlefieldmax45' : $params[
'tdclass']).
' wordbreak';
9558 if ($extrafields->attributes[$this->table_element][
'type'][$key] ==
'text') {
9561 } elseif ($display_type ==
'line') {
9562 $out .=
'<div '.($html_id ?
'id="'.$html_id.
'" ' :
'').$csstyle.
' class="fieldline_options_'.$key.
' '.$class.$this->element.
'_extras_'.$key.
' trextrafields_collapse'.$collapse_group.
'" '.$domData.
' >';
9563 $out .=
'<div style="display: inline-block; padding-right:4px" class="wordbreak';
9568 $tpl_context = isset($params[
"tpl_context"]) ? $params[
"tpl_context"] :
"none";
9569 if ($tpl_context !=
"public") {
9570 if ($mode !=
'view' && !empty($extrafields->attributes[$this->table_element][
'required'][$key])) {
9571 $out .=
' fieldrequired';
9575 if ($tpl_context ==
"public") {
9576 if (!empty($extrafields->attributes[$this->table_element][
'help'][$key])) {
9577 $out .= $form->textwithpicto($labeltoshow, $helptoshow);
9579 $out .= $labeltoshow;
9581 if ($mode !=
'view' && !empty($extrafields->attributes[$this->table_element][
'required'][$key])) {
9582 $out .=
' <span style="color: red">*</span>';
9585 if (!empty($extrafields->attributes[$this->table_element][
'help'][$key])) {
9586 $out .= $form->textwithpicto($labeltoshow, $helptoshow);
9588 $out .= $labeltoshow;
9592 $out .= ($display_type ==
'card' ?
'</td>' :
'</div>');
9595 $html_id = !empty($this->
id) ? $this->element.
'_extras_'.$key.
'_'.$this->id :
'';
9596 if ($display_type ==
'card') {
9598 $out .=
'<td '.($html_id ?
'id="'.$html_id.
'" ' :
'').
' class="valuefieldcreate '.$this->element.
'_extras_'.$key;
9599 $out .=
'" '.($colspan ?
' colspan="'.$colspan.
'"' :
'');
9601 } elseif ($display_type ==
'line') {
9602 $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].
'">';
9607 $out .= $extrafields->showOutputField($key, $value,
'', $this->table_element);
9610 $listoftypestoshowpicto = explode(
',',
getDolGlobalString(
'MAIN_TYPES_TO_SHOW_PICTO',
'email,phone,ip,password'));
9611 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], $listoftypestoshowpicto)) {
9612 $out .=
getPictoForType($extrafields->attributes[$this->table_element][
'type'][$key], ($extrafields->attributes[$this->table_element][
'type'][$key] ==
'text' ?
'tdtop' :
''));
9615 $out .= $extrafields->showInputField($key, $value,
'', $keysuffix,
'',
'', $this, $this->table_element);
9618 $listoftypestoshowpicto = explode(
',',
getDolGlobalString(
'MAIN_TYPES_TO_SHOW_PICTO',
'email,phone,ip,password'));
9619 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], $listoftypestoshowpicto)) {
9620 $out .=
getPictoForType($extrafields->attributes[$this->table_element][
'type'][$key], ($extrafields->attributes[$this->table_element][
'type'][$key] ==
'text' ?
'tdtop' :
''));
9622 $out .= $extrafields->showInputField($key, $value,
'', $keysuffix,
'',
'', $this, $this->table_element);
9626 $out .= ($display_type ==
'card' ?
'</td>' :
'</div>');
9627 $out .= ($display_type ==
'card' ?
'</tr>'.
"\n" :
'</div>');
9633 if (!empty(
$conf->use_javascript_ajax)) {
9634 $out .= $this->getJSListDependancies();
9637 $out .=
'<!-- commonobject:showOptionals end --> '.
"\n";
9639 if (empty($nbofextrafieldsshown)) {
9645 $out .= $hookmanager->resPrint;
9657 <script nonce="'.getNonce().
'">
9658 jQuery(document).ready(function() {
9659 function showOptions'.$type.
'(child_list, parent_list, orig_select)
9661 var val = $("select[name=\""+parent_list+"\"]").val();
9662 var parentVal = parent_list + ":" + val;
9663 if(typeof val == "string"){
9665 var options = orig_select.find("option[parent=\""+parentVal+"\"]").clone();
9666 $("select[name=\""+child_list+"\"] option[parent]").remove();
9667 $("select[name=\""+child_list+"\"]").append(options);
9669 var options = orig_select.find("option[parent]").clone();
9670 $("select[name=\""+child_list+"\"] option[parent]").remove();
9671 $("select[name=\""+child_list+"\"]").append(options);
9673 } else if(val > 0) {
9674 var options = orig_select.find("option[parent=\""+parentVal+"\"]").clone();
9675 $("select[name=\""+child_list+"\"] option[parent]").remove();
9676 $("select[name=\""+child_list+"\"]").append(options);
9678 var options = orig_select.find("option[parent]").clone();
9679 $("select[name=\""+child_list+"\"] option[parent]").remove();
9680 $("select[name=\""+child_list+"\"]").append(options);
9683 function setListDependencies'.$type.
'() {
9684 jQuery("select option[parent]").parent().each(function() {
9685 var orig_select = {};
9686 var child_list = $(this).attr("name");
9687 orig_select[child_list] = $(this).clone();
9688 var parent = $(this).find("option[parent]:first").attr("parent");
9689 var infos = parent.split(":");
9690 var parent_list = infos[0];
9692 //Hide daughters lists
9693 if ($("#"+child_list).val() == 0 && $("#"+parent_list).val() == 0){
9694 $("#"+child_list).hide();
9696 } else if ($("#"+parent_list).val() != 0){
9697 $("#"+parent_list).show();
9699 //Show the child list if the parent list value is selected
9700 $("select[name=\""+parent_list+"\"]").click(function() {
9701 if ($(this).val() != 0){
9702 $("#"+child_list).show()
9706 //When we change parent list
9707 $("select[name=\""+parent_list+"\"]").change(function() {
9708 showOptions'.$type.
'(child_list, parent_list, orig_select[child_list]);
9709 //Select the value 0 on child list after a change on the parent list
9710 $("#"+child_list).val(0).trigger("change");
9711 //Hide child lists if the parent value is set to 0
9712 if ($(this).val() == 0){
9713 $("#"+child_list).hide();
9719 setListDependencies'.$type.
'();
9734 $module = empty($this->module) ?
'' : $this->module;
9735 $element = $this->element;
9737 if ($element ==
'facturerec') {
9738 $element =
'facture';
9739 } elseif ($element ==
'invoice_supplier_rec') {
9740 return !$user->hasRight(
'fournisseur',
'facture') ? null : $user->hasRight(
'fournisseur',
'facture');
9741 } elseif ($module && $user->hasRight($module, $element)) {
9743 return $user->hasRight($module, $element);
9746 return isset($user->rights->$element) ? $user->rights->$element :
null;
9763 global $hookmanager;
9765 $parameters = array(
9766 'origin_id' => $origin_id,
9767 'dest_id' => $dest_id,
9768 'tables' => $tables,
9770 $reshook = $hookmanager->executeHooks(
'commonReplaceThirdparty', $parameters);
9773 } elseif ($reshook < 0) {
9774 return $ignoreerrors === 1;
9777 foreach ($tables as $table) {
9778 $sql =
'UPDATE '.$dbs->prefix().$table.
' SET fk_soc = '.((int) $dest_id).
' WHERE fk_soc = '.((int) $origin_id);
9780 if (!$dbs->
query($sql)) {
9781 if ($ignoreerrors) {
9806 foreach ($tables as $table) {
9807 $sql =
'UPDATE '.MAIN_DB_PREFIX.$table.
' SET fk_product = '.((int) $dest_id).
' WHERE fk_product = '.((int) $origin_id);
9809 if (!$dbs->
query($sql)) {
9810 if ($ignoreerrors) {
9833 public function defineBuyPrice($unitPrice = 0.0, $discountPercent = 0.0, $fk_product = 0)
9839 if (($unitPrice > 0) && (isset(
$conf->global->ForceBuyingPriceIfNull) &&
getDolGlobalInt(
'ForceBuyingPriceIfNull') > 0)) {
9841 $buyPrice = $unitPrice * (1 - $discountPercent / 100);
9844 if (!empty($fk_product) && $fk_product > 0) {
9847 require_once DOL_DOCUMENT_ROOT.
'/product/class/product.class.php';
9848 $product =
new Product($this->db);
9849 $result = $product->fetch($fk_product);
9851 $this->errors[] =
'ErrorProductIdDoesNotExists';
9854 if ($product->cost_price > 0) {
9855 $buyPrice = $product->cost_price;
9856 } elseif ($product->pmp > 0) {
9857 $buyPrice = $product->pmp;
9860 require_once DOL_DOCUMENT_ROOT.
'/product/class/product.class.php';
9861 $product =
new Product($this->db);
9862 $result = $product->fetch($fk_product);
9864 $this->errors[] =
'ErrorProductIdDoesNotExists';
9867 if ($product->pmp > 0) {
9868 $buyPrice = $product->pmp;
9872 if (empty($buyPrice) && isset(
$conf->global->MARGIN_TYPE) && in_array(
$conf->global->MARGIN_TYPE, array(
'1',
'pmp',
'costprice'))) {
9873 require_once DOL_DOCUMENT_ROOT.
'/fourn/class/fournisseur.product.class.php';
9875 if (($result = $productFournisseur->find_min_price_product_fournisseur($fk_product)) > 0) {
9876 $buyPrice = $productFournisseur->fourn_unitprice;
9877 } elseif ($result < 0) {
9878 $this->errors[] = $productFournisseur->error;
9885 return (
float) $buyPrice;
9898 return array(
'dir' =>
'',
'file' =>
'',
'originalfile' =>
'',
'altfile' =>
'',
'email' =>
'',
'capture' =>
'');
9922 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')
9925 global $user, $langs;
9927 include_once DOL_DOCUMENT_ROOT.
'/core/lib/files.lib.php';
9928 include_once DOL_DOCUMENT_ROOT.
'/core/lib/images.lib.php';
9930 $sortfield =
'position_name';
9936 $dir .=
get_exdir(0, 0, 0, 0, $this, $modulepart);
9937 $pdir .=
get_exdir(0, 0, 0, 0, $this, $modulepart);
9940 if ($modulepart ==
'product') {
9942 $dir = $sdir.
'/'.
get_exdir($this->
id, 2, 0, 0, $this, $modulepart).$this->id.
"/photos/";
9943 $pdir =
'/'.get_exdir($this->
id, 2, 0, 0, $this, $modulepart).$this->id.
"/photos/";
9946 if ($modulepart ==
'category') {
9947 $dir = $sdir.
'/'.
get_exdir($this->
id, 2, 0, 0, $this, $modulepart).$this->id.
"/photos/";
9948 $pdir =
'/'.get_exdir($this->
id, 2, 0, 0, $this, $modulepart).$this->id.
"/photos/";
9954 $relativedir = preg_replace(
'/^'.preg_quote(DOL_DATA_ROOT,
'/').
'/',
'', $dir);
9955 $relativedir = preg_replace(
'/^[\\/]/',
'', $relativedir);
9956 $relativedir = preg_replace(
'/[\\/]$/',
'', $relativedir);
9959 $dirthumb = $dir.
'thumbs/';
9960 $pdirthumb = $pdir.
'thumbs/';
9962 $return =
'<!-- Photo -->'.
"\n";
9965 $filearray =
dol_dir_list($dir,
"files", 0,
'',
'(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) ==
'desc' ? SORT_DESC : SORT_ASC), 1);
9974 '@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';
9976 if (count($filearray)) {
9977 if ($sortfield && $sortorder) {
9981 foreach ($filearray as $key => $val) {
9983 $file = $val[
'name'];
9989 $viewfilename = $file;
9991 if ($size == 1 || $size ==
'small') {
9998 $photo_vignette = basename($file);
10004 if ($nbbyrow > 0) {
10005 if ($nbphoto == 1) {
10006 $return .=
'<table class="valigntop center centpercent" style="border: 0; padding: 2px; border-spacing: 2px; border-collapse: separate;">';
10009 if ($nbphoto % $nbbyrow == 1) {
10010 $return .=
'<tr class="center valignmiddle" style="border: 1px">';
10012 $return .=
'<td style="width: '.ceil(100 / $nbbyrow).
'%" class="photo">'.
"\n";
10013 } elseif ($nbbyrow < 0) {
10014 $return .=
'<div class="inline-block">'.
"\n";
10017 $relativefile = preg_replace(
'/^\//',
'', $pdir.$photo);
10018 if (empty($nolink)) {
10020 if ($urladvanced) {
10021 $return .=
'<a href="'.$urladvanced.
'">';
10023 $return .=
'<a href="'.DOL_URL_ROOT.
'/viewimage.php?modulepart='.$modulepart.
'&entity='.$this->entity.
'&file='.urlencode($pdir.$photo).
'" class="aphoto" target="_blank" rel="noopener noreferrer">';
10029 $alt = $langs->transnoentitiesnoconv(
'File').
': '.$relativefile;
10030 $alt .=
' - '.$langs->transnoentitiesnoconv(
'Size').
': '.$imgarray[
'width'].
'x'.$imgarray[
'height'];
10031 if ($overwritetitle) {
10032 if (is_numeric($overwritetitle)) {
10035 $alt = $overwritetitle;
10038 if (empty($cache) && !empty($val[
'label'])) {
10041 $cache = $val[
'label'];
10043 if ($usesharelink) {
10044 if (array_key_exists(
'share', $val) && $val[
'share']) {
10045 if (empty($maxHeight) || ($photo_vignette && $imgarray[
'height'] > $maxHeight)) {
10046 $return .=
'<!-- Show original file (thumb not yet available with shared links) -->';
10047 $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).
'">';
10049 $return .=
'<!-- Show original file -->';
10050 $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).
'">';
10053 $return .=
'<!-- Show nophoto file (because file is not shared) -->';
10054 $return .=
'<img class="photo photowithmargin'.($addphotorefcss ?
' '.$addphotorefcss :
'').
'" height="'.$maxHeight.
'" src="'.DOL_URL_ROOT.
'/public/theme/common/nophoto.png" title="'.
dol_escape_htmltag($alt).
'">';
10057 if (empty($maxHeight) || ($photo_vignette && $imgarray[
'height'] > $maxHeight)) {
10058 $return .=
'<!-- Show thumb -->';
10059 $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).
'">';
10061 $return .=
'<!-- Show original file -->';
10062 $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).
'">';
10066 if (empty($nolink)) {
10070 if ($showfilename) {
10071 $return .=
'<br>'.$viewfilename;
10076 if ($photo_vignette && (
image_format_supported($photo) > 0) && ((isset($imgarray[
'width']) && $imgarray[
'width'] > $maxWidth) || (isset($imgarray[
'width']) && $imgarray[
'width'] > $maxHeight))) {
10077 $return .=
'<a href="'.$_SERVER[
"PHP_SELF"].
'?id='.$this->
id.
'&action=addthumb&token='.
newToken().
'&file='.urlencode($pdir.$viewfilename).
'">'.
img_picto($langs->trans(
'GenerateThumb'),
'refresh').
' </a>';
10080 if ($modulepart ==
'product' && ($user->hasRight(
'produit',
'creer') || $user->hasRight(
'service',
'creer'))) {
10082 $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> ';
10085 $return .=
'<a href="'.$_SERVER[
"PHP_SELF"].
'?id='.$this->
id.
'&action=delete&token='.
newToken().
'&file='.urlencode($pdir.$viewfilename).
'">';
10091 if ($nbbyrow > 0) {
10092 $return .=
'</td>';
10093 if (($nbphoto % $nbbyrow) == 0) {
10094 $return .=
'</tr>';
10096 } elseif ($nbbyrow < 0) {
10097 $return .=
'</div>'.
"\n";
10101 if (empty($size)) {
10102 $return .=
'<img class="photo photowithmargin" src="'.DOL_URL_ROOT.
'/viewimage.php?modulepart='.$modulepart.
'&entity='.$this->entity.
'&file='.urlencode($pdir.$photo).
'">';
10104 if ($showfilename) {
10105 $return .=
'<br>'.$viewfilename;
10109 if ($modulepart ==
'product' && ($user->hasRight(
'produit',
'creer') || $user->hasRight(
'service',
'creer'))) {
10111 $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> ';
10114 $return .=
'<a href="'.$_SERVER[
"PHP_SELF"].
'?id='.$this->
id.
'&action=delete&token='.
newToken().
'&file='.urlencode($pdir.$viewfilename).
'">';
10121 if ($nbmax && $nbphoto >= $nbmax) {
10127 if ($size == 1 || $size ==
'small') {
10128 if ($nbbyrow > 0) {
10130 while ($nbphoto % $nbbyrow) {
10131 $return .=
'<td style="width: '.ceil(100 / $nbbyrow).
'%"> </td>';
10136 $return .=
'</table>';
10142 $this->nbphoto = $nbphoto;
10156 if (is_array($info)) {
10157 if (isset($info[
'type']) && $info[
'type'] ==
'array') {
10174 if (isset($info[
'type']) && ($info[
'type'] ==
'date' || $info[
'type'] ==
'datetime' || $info[
'type'] ==
'timestamp')) {
10188 if (is_array($info)) {
10189 if (isset($info[
'type']) && ($info[
'type'] ==
'duration')) {
10207 if (is_array($info)) {
10208 if (isset($info[
'type']) && (preg_match(
'/^(?:tiny|small|medium|big)?int|int$/i', $info[
'type']))) {
10226 if (is_array($info)) {
10227 if (isset($info[
'type']) && (preg_match(
'/^(double|real|price)/i', $info[
'type']))) {
10244 if (is_array($info)) {
10245 if (isset($info[
'type']) && $info[
'type'] ==
'text') {
10262 if (is_array($info)) {
10263 if (array_key_exists(
'notnull', $info) && $info[
'notnull'] !=
'1') {
10280 if (is_array($info)) {
10281 if (array_key_exists(
'notnull', $info) && $info[
'notnull'] ==
'-1') {
10298 if (is_array($info)) {
10299 if (array_key_exists(
'index', $info) && $info[
'index'] ==
true) {
10321 $queryarray = array();
10322 foreach ($this->fields as $field => $info) {
10324 if ($this->isDate($info)) {
10325 if (empty($this->{$field})) {
10326 $queryarray[$field] =
null;
10328 $queryarray[$field] = $this->db->idate($this->{$field});
10330 } elseif ($this->isDuration($info)) {
10332 if ((isset($this->{$field}) && $this->{$field} !=
'') || !empty($info[
'notnull'])) {
10333 if (!isset($this->{$field})) {
10334 if (!empty($info[
'default'])) {
10335 $queryarray[$field] = $info[
'default'];
10337 $queryarray[$field] = 0;
10340 $queryarray[$field] = (int) $this->{$field};
10343 $queryarray[$field] =
null;
10345 } elseif ($this->isInt($info) || $this->isFloat($info)) {
10346 if ($field ==
'entity' && is_null($this->{$field})) {
10347 $queryarray[$field] = ((int)
$conf->entity);
10350 if ((isset($this->{$field}) && ((
string) $this->{$field}) !=
'') || !empty($info[
'notnull'])) {
10351 if (!isset($this->{$field})) {
10352 $queryarray[$field] = 0;
10353 } elseif ($this->isInt($info)) {
10354 $queryarray[$field] = (int) $this->{$field};
10355 } elseif ($this->isFloat($info)) {
10356 $queryarray[$field] = (float) $this->{$field};
10359 $queryarray[$field] =
null;
10365 $queryarray[$field] = $this->{$field};
10368 if (array_key_exists(
'type', $info) && $info[
'type'] ==
'timestamp' && empty($queryarray[$field])) {
10369 unset($queryarray[$field]);
10371 if (!empty($info[
'notnull']) && $info[
'notnull'] == -1 && empty($queryarray[$field])) {
10372 $queryarray[$field] =
null;
10376 return $queryarray;
10389 foreach ($this->fields as $field => $info) {
10390 if ($this->isDate($info)) {
10391 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') {
10392 $this->$field =
'';
10394 $this->$field = $db->jdate($obj->$field);
10396 } elseif ($this->isInt($info)) {
10397 if ($field ==
'rowid') {
10398 $this->
id = (int) $obj->$field;
10400 if ($this->isForcedToNullIfZero($info)) {
10401 if (empty($obj->$field)) {
10402 $this->$field =
null;
10404 $this->$field = (int) $obj->$field;
10407 if (isset($obj->$field) && (!is_null($obj->$field) || (array_key_exists(
'notnull', $info) && $info[
'notnull'] == 1))) {
10408 $this->$field = (int) $obj->$field;
10410 $this->$field =
null;
10414 } elseif ($this->isFloat($info)) {
10415 if ($this->isForcedToNullIfZero($info)) {
10416 if (empty($obj->$field)) {
10417 $this->$field =
null;
10419 $this->$field = (float) $obj->$field;
10422 if (isset($obj->$field) && (!is_null($obj->$field) || (array_key_exists(
'notnull', $info) && $info[
'notnull'] == 1))) {
10423 $this->$field = (float) $obj->$field;
10425 $this->$field =
null;
10429 $this->$field = isset($obj->$field) ? $obj->$field :
null;
10434 if (!isset($this->fields[
'ref']) && isset($this->
id)) {
10435 $this->
ref = (string) $this->
id;
10445 foreach ($this->fields as $field => $arr) {
10446 $this->$field =
null;
10459 $keys = array_keys($this->fields);
10460 if (!empty($alias)) {
10461 $keys_with_alias = array();
10462 foreach ($keys as $fieldname) {
10463 if (!empty($excludefields)) {
10464 if (in_array($fieldname, $excludefields)) {
10468 $keys_with_alias[] = $alias .
'.' . $fieldname;
10470 return implode(
', ', $keys_with_alias);
10472 return implode(
', ', $keys);
10483 protected function quote($value, $fieldsentry)
10485 if (is_null($value)) {
10487 } elseif (preg_match(
'/^(int|double|real|price)/i', $fieldsentry[
'type'])) {
10489 } elseif (preg_match(
'/int$/i', $fieldsentry[
'type'])) {
10490 return (
int) $value;
10491 } elseif ($fieldsentry[
'type'] ==
'boolean') {
10498 return "'".$this->db->escape($value).
"'";
10514 dol_syslog(get_class($this).
"::createCommon create", LOG_DEBUG);
10520 $fieldvalues = $this->setSaveQuery();
10524 if (array_key_exists(
'date_creation', $fieldvalues) && empty($fieldvalues[
'date_creation'])) {
10525 $fieldvalues[
'date_creation'] = $this->db->idate($now);
10526 $this->date_creation = $this->db->idate($now);
10529 if (array_key_exists(
'fk_user_creat', $fieldvalues) && !($fieldvalues[
'fk_user_creat'] > 0)) {
10530 $fieldvalues[
'fk_user_creat'] = $user->id;
10531 $this->fk_user_creat = $user->id;
10533 if (array_key_exists(
'user_creation_id', $fieldvalues) && !($fieldvalues[
'user_creation_id'] > 0)) {
10534 $fieldvalues[
'user_creation_id'] = $user->id;
10535 $this->user_creation_id = $user->id;
10537 if (array_key_exists(
'pass_crypted', $fieldvalues) && property_exists($this,
'pass')) {
10539 $tmparray =
dol_hash($this->pass,
'0', 0, 1);
10540 $fieldvalues[
'pass_crypted'] = $tmparray[
'pass_encrypted'];
10541 if (array_key_exists(
'pass_encoding', $fieldvalues) && property_exists($this,
'pass_encoding')) {
10542 $fieldvalues[
'pass_encoding'] = $tmparray[
'pass_encoding'];
10545 if (array_key_exists(
'ref', $fieldvalues)) {
10549 unset($fieldvalues[
'rowid']);
10553 foreach ($fieldvalues as $k => $v) {
10555 $value = $this->fields[$k];
10557 $values[$k] = $this->quote($v, $value);
10561 foreach ($keys as $key) {
10562 if (!isset($this->fields[$key])) {
10565 $key_fields = $this->fields[$key];
10568 if (preg_match(
'/^integer:/i', $key_fields[
'type']) && $values[$key] ==
'-1') {
10569 $values[$key] =
'';
10571 if (!empty($key_fields[
'foreignkey']) && $values[$key] ==
'-1') {
10572 $values[$key] =
'';
10575 if (isset($key_fields[
'notnull']) && $key_fields[
'notnull'] == 1 && (!isset($values[$key]) || $values[$key] ===
'NULL') && (!isset($key_fields[
'default']) || is_null($key_fields[
'default']))) {
10577 $langs->load(
"errors");
10578 dol_syslog(
"Mandatory field '".$key.
"' is empty and required into ->fields definition of class");
10579 $this->errors[] = $langs->trans(
"ErrorFieldRequired", isset($key_fields[
'label']) ? $key_fields[
'label'] : $key);
10583 if (isset($key_fields[
'notnull']) && $key_fields[
'notnull'] == 1 && (!isset($values[$key]) || $values[$key] ===
'NULL') && !is_null($key_fields[
'default'])) {
10584 $values[$key] = $this->quote($key_fields[
'default'], $key_fields);
10588 if (isset($key_fields[
'type']) && preg_match(
'/^integer:/i', $key_fields[
'type']) && empty($values[$key])) {
10589 if (isset($key_fields[
'default'])) {
10590 $values[$key] = ((int) $key_fields[
'default']);
10592 $values[$key] =
'null';
10595 if (!empty($key_fields[
'foreignkey']) && empty($values[$key])) {
10596 $values[$key] =
'null';
10604 $this->db->begin();
10607 $sql =
"INSERT INTO ".$this->db->prefix().$this->table_element;
10608 $sql .=
" (".implode(
", ", $keys).
')';
10609 $sql .=
" VALUES (".implode(
", ", $values).
")";
10611 $res = $this->db->query($sql);
10614 if ($this->db->lasterrno() ==
'DB_ERROR_RECORD_ALREADY_EXISTS') {
10615 $this->errors[] =
"ErrorRefAlreadyExists";
10617 $this->errors[] = $this->db->lasterror();
10623 $this->
id = $this->db->last_insert_id($this->db->prefix().$this->table_element);
10629 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)') {
10630 $sql =
"UPDATE ".$this->db->prefix().$this->table_element.
" SET ref = '(PROV".((int) $this->
id).
")' WHERE (ref = '(PROV)' OR ref = '') AND rowid = ".((int) $this->
id);
10631 $resqlupdate = $this->db->query($sql);
10633 if ($resqlupdate ===
false) {
10635 $this->errors[] = $this->db->lasterror();
10637 $this->
ref =
'(PROV'.$this->id.
')';
10644 $result = $this->insertExtraFields();
10651 if (!empty($this->table_element_line) && !empty($this->fk_element) && !empty($this->lines)) {
10652 foreach ($this->lines as $line) {
10653 $keyforparent = $this->fk_element;
10658 if (!is_object($line)) {
10659 $line = (object) $line;
10663 if (method_exists($line,
'insert')) {
10664 $result = $line->insert($user, 1);
10665 } elseif (method_exists($line,
'create')) {
10666 $result = $line->create($user, 1);
10669 $this->error = $line->error;
10670 $this->db->rollback();
10677 if (!$error && !$notrigger) {
10679 $result = $this->call_trigger(strtoupper(get_class($this)).
'_CREATE', $user);
10688 $this->db->rollback();
10691 $this->db->commit();
10708 if (empty(
$id) && empty($ref) && empty($morewhere)) {
10712 $fieldlist = $this->getFieldList(
't');
10713 if (empty($fieldlist)) {
10717 $sql =
"SELECT ".$fieldlist;
10718 $sql .=
" FROM ".$this->db->prefix().$this->table_element.
' as t';
10721 $sql .=
' WHERE t.rowid = '.((int)
$id);
10722 } elseif (!empty($ref)) {
10723 $sql .=
" WHERE t.ref = '".$this->db->escape($ref).
"'";
10725 $sql .=
' WHERE 1 = 1';
10727 if (empty(
$id) && isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
10728 $sql .=
' AND t.entity IN ('.getEntity($this->element).
')';
10731 $sql .= $morewhere;
10733 $sql .=
' LIMIT 1';
10735 $res = $this->db->query($sql);
10737 $obj = $this->db->fetch_object($res);
10739 $this->setVarsFromFetchObj($obj);
10743 if (empty($noextrafields)) {
10744 $result = $this->fetch_optionals();
10746 $this->error = $this->db->lasterror();
10747 $this->errors[] = $this->error;
10757 $this->error = $this->db->lasterror();
10758 $this->errors[] = $this->error;
10772 $objectlineclassname = get_class($this).
'Line';
10773 if (!class_exists($objectlineclassname)) {
10774 $this->error =
'Error, class '.$objectlineclassname.
' not found during call of fetchLinesCommon';
10778 $objectline =
new $objectlineclassname($this->db);
10779 '@phan-var-force CommonObjectLine $objectline';
10781 $sql =
"SELECT ".$objectline->getFieldList(
'l');
10782 $sql .=
" FROM ".$this->db->prefix().$objectline->table_element.
" as l";
10783 $sql .=
" WHERE l.fk_".$this->db->escape($this->element).
" = ".((int) $this->
id);
10785 $sql .= $morewhere;
10787 if (isset($objectline->fields[
'position'])) {
10788 $sql .= $this->db->order(
'position',
'ASC');
10791 $resql = $this->db->query($sql);
10793 $num_rows = $this->db->num_rows($resql);
10795 $this->lines = array();
10796 while ($i < $num_rows) {
10797 $obj = $this->db->fetch_object($resql);
10799 $newline =
new $objectlineclassname($this->db);
10800 '@phan-var-force CommonObjectLine $newline';
10801 $newline->setVarsFromFetchObj($obj);
10804 if (empty($noextrafields)) {
10805 $newline->fetch_optionals();
10808 $this->lines[] = $newline;
10815 $this->error = $this->db->lasterror();
10816 $this->errors[] = $this->error;
10830 dol_syslog(get_class($this).
"::updateCommon update", LOG_DEBUG);
10842 $fieldvalues = $this->setSaveQuery();
10846 if (array_key_exists(
'date_modification', $fieldvalues) && empty($fieldvalues[
'date_modification'])) {
10847 $fieldvalues[
'date_modification'] = $this->db->idate($now);
10849 if (array_key_exists(
'fk_user_modif', $fieldvalues) && !($fieldvalues[
'fk_user_modif'] > 0)) {
10850 $fieldvalues[
'fk_user_modif'] = $user->id;
10852 if (array_key_exists(
'user_modification_id', $fieldvalues) && !($fieldvalues[
'user_modification_id'] > 0)) {
10853 $fieldvalues[
'user_modification_id'] = $user->id;
10856 if (array_key_exists(
'pass_crypted', $fieldvalues) && property_exists($this,
'pass') && !empty($this->pass)) {
10858 $tmparray =
dol_hash($this->pass,
'0', 0, 1);
10859 $fieldvalues[
'pass_crypted'] = $tmparray[
'pass_encrypted'];
10860 if (array_key_exists(
'pass_encoding', $fieldvalues) && property_exists($this,
'pass_encoding')) {
10861 $fieldvalues[
'pass_encoding'] = $tmparray[
'pass_encoding'];
10864 if (array_key_exists(
'ref', $fieldvalues)) {
10868 unset($fieldvalues[
'rowid']);
10874 foreach ($fieldvalues as $k => $v) {
10876 $value = $this->fields[$k];
10878 $values[$k] = $this->quote($v, $value);
10879 if (($value[
"type"] ==
"text") && !empty($value[
'arrayofkeyval']) && is_array($value[
'arrayofkeyval'])) {
10881 $v = preg_replace(
'/\s/',
',', $v);
10882 $v = preg_replace(
'/,+/',
',', $v);
10885 $tmp[] = $k.
'='.$this->quote($v, $this->fields[$k]);
10889 foreach ($keys as $key) {
10890 if (preg_match(
'/^integer:/i', $this->fields[$key][
'type']) && $values[$key] ==
'-1') {
10891 $values[$key] =
'';
10893 if (!empty($this->fields[$key][
'foreignkey']) && $values[$key] ==
'-1') {
10894 $values[$key] =
'';
10906 $sql =
'UPDATE '.$this->db->prefix().$this->table_element.
' SET '.implode(
', ', $tmp).
' WHERE rowid='.((int) $this->
id);
10908 $this->db->begin();
10911 $res = $this->db->query($sql);
10914 $this->errors[] = $this->db->lasterror();
10920 $result = $this->insertExtraFields();
10927 if (!$error && !$notrigger) {
10929 $result = $this->call_trigger(strtoupper(get_class($this)).
'_MODIFY', $user);
10938 $this->db->rollback();
10941 $this->db->commit();
10956 dol_syslog(get_class($this).
"::deleteCommon delete", LOG_DEBUG);
10960 $this->db->begin();
10962 if ($forcechilddeletion) {
10963 foreach ($this->childtables as $table) {
10964 $sql =
"DELETE FROM ".$this->db->prefix().$table.
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
10965 $resql = $this->db->query($sql);
10967 $this->error = $this->db->lasterror();
10968 $this->errors[] = $this->error;
10969 $this->db->rollback();
10973 } elseif (!empty($this->childtables)) {
10974 $objectisused = $this->isObjectUsed($this->
id);
10975 if (!empty($objectisused)) {
10976 dol_syslog(get_class($this).
"::deleteCommon Can't delete record as it has some child", LOG_WARNING);
10977 $this->error =
'ErrorRecordHasChildren';
10978 $this->errors[] = $this->error;
10979 $this->db->rollback();
10985 if (is_array($this->childtablesoncascade) && !empty($this->childtablesoncascade)) {
10986 foreach ($this->childtablesoncascade as $tabletodelete) {
10987 $deleteFromObject = explode(
':', $tabletodelete, 4);
10988 if (count($deleteFromObject) >= 2) {
10989 $className = str_replace(
'@',
'', $deleteFromObject[0]);
10990 $filePath = $deleteFromObject[1];
10991 $columnName = $deleteFromObject[2];
10993 if (!empty($deleteFromObject[3])) {
10994 $filter = $deleteFromObject[3];
10998 $childObject =
new $className($this->db);
10999 if (method_exists($childObject,
'deleteByParentField')) {
11000 '@phan-var-force CommonObject $childObject';
11001 $result = $childObject->deleteByParentField($this->
id, $columnName, $filter);
11004 $this->errors[] = $childObject->error;
11009 $this->errors[] =
"You defined a cascade delete on an object $className/$this->id but there is no method deleteByParentField for it";
11014 $this->errors[] =
'Cannot include child class file '.$filePath;
11019 $sql =
"DELETE FROM ".$this->db->prefix().$tabletodelete.
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
11021 $resql = $this->db->query($sql);
11024 $this->error = $this->db->lasterror();
11025 $this->errors[] = $this->error;
11035 $result = $this->call_trigger(strtoupper(get_class($this)).
'_DELETE', $user);
11045 $res = $this->deleteEcmFiles(1);
11052 $res = $this->deleteObjectLinked();
11057 if (!$error && !empty($this->isextrafieldmanaged)) {
11058 $result = $this->deleteExtraFields();
11065 $sql =
'DELETE FROM '.$this->db->prefix().$this->table_element.
' WHERE rowid='.((int) $this->
id);
11067 $resql = $this->db->query($sql);
11070 $this->errors[] = $this->db->lasterror();
11076 $this->db->rollback();
11079 $this->db->commit();
11104 if (!empty($parentId) && !empty($parentField)) {
11105 if (empty($this->table_element)) {
11106 $this->error =
'Property table_element for object is not defined';
11107 $this->errors[] = $this->error;
11111 if (!method_exists($this,
'fetch')) {
11112 $this->error =
'Method fetch for object is not defined';
11113 $this->errors[] = $this->error;
11117 if (!method_exists($this,
'delete')) {
11118 $this->error =
'Method delete for object is not defined';
11119 $this->errors[] = $this->error;
11124 $this->db->begin();
11126 $sql =
"SELECT rowid FROM ".$this->db->prefix().$this->table_element;
11127 $sql .=
" WHERE ".$this->db->sanitize($parentField).
" = ".(int) $parentId;
11130 $errormessage =
'';
11132 if ($errormessage) {
11133 $this->errors[] = $errormessage;
11134 dol_syslog(__METHOD__.
' '.implode(
',', $this->errors), LOG_ERR);
11138 $resql = $this->db->query($sql);
11140 $this->errors[] = $this->db->lasterror();
11143 while ($obj = $this->db->fetch_object($resql)) {
11144 $result = $this->fetch($obj->rowid);
11147 $this->errors[] = $this->error;
11149 $result = $this->
delete($user);
11152 $this->errors[] = $this->error;
11160 if (empty($error)) {
11161 $this->db->commit();
11164 $this->error = implode(
', ', $this->errors);
11165 $this->db->rollback();
11166 return $error * -1;
11185 $tmpforobjectclass = get_class($this);
11186 $tmpforobjectlineclass = ucfirst($tmpforobjectclass).
'Line';
11188 if ($this->
id > 0 && !empty($this->fk_element)) {
11190 $sql =
"SELECT rowid FROM ".$this->db->prefix().$this->table_element_line;
11191 $sql .=
" WHERE rowid = ".((int) $idline).
" AND ".$this->db->sanitize($this->fk_element).
" = ".((int) $this->
id);
11192 $resql = $this->db->query($sql);
11193 if (!$resql || !$this->db->num_rows($resql)) {
11194 $this->error =
'ErrorLineIDDoesNotMatchWithObjectID';
11199 $this->db->begin();
11202 $result = $this->call_trigger(
'LINE'.strtoupper($tmpforobjectclass).
'_DELETE', $user);
11208 if (empty($error)) {
11209 $sql =
"DELETE FROM ".$this->db->prefix().$this->table_element_line;
11210 $sql .=
" WHERE rowid = ".((int) $idline);
11212 $resql = $this->db->query($sql);
11214 $this->error =
"Error ".$this->db->lasterror();
11219 if (empty($error)) {
11221 $tmpobjectline =
new $tmpforobjectlineclass($this->db);
11222 '@phan-var-force CommonObjectLine $tmpobjectline';
11223 if (!isset($tmpobjectline->isextrafieldmanaged) || !empty($tmpobjectline->isextrafieldmanaged)) {
11224 $tmpobjectline->id = $idline;
11225 $result = $tmpobjectline->deleteExtraFields();
11228 $this->error =
"Error ".get_class($this).
"::deleteLineCommon deleteExtraFields error -4 ".$tmpobjectline->error;
11233 if (empty($error)) {
11234 $this->db->commit();
11237 dol_syslog(get_class($this).
"::deleteLineCommon ERROR:".$this->error, LOG_ERR);
11238 $this->db->rollback();
11257 $this->db->begin();
11259 $statusfield =
'status';
11260 if (in_array($this->element, array(
'don',
'donation',
'shipping',
'project_task'))) {
11261 $statusfield =
'fk_statut';
11264 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
11265 $sql .=
" SET ".$statusfield.
" = ".((int) $status);
11266 $sql .=
" WHERE rowid = ".((int) $this->
id);
11268 if ($this->db->query($sql)) {
11270 $this->oldcopy = clone $this;
11273 if (!$error && !$notrigger) {
11275 $result = $this->call_trigger($triggercode, $user);
11282 $this->
status = $status;
11283 if (property_exists($this,
'statut')) {
11284 $this->statut = $status;
11286 $this->db->commit();
11289 $this->db->rollback();
11293 $this->error = $this->db->error();
11294 $this->db->rollback();
11310 $this->specimen = 1;
11312 'label' =>
'This is label',
11313 'ref' =>
'ABCD1234',
11314 'description' =>
'This is a description',
11316 'note_public' =>
'Public note',
11317 'note_private' =>
'Private note',
11318 'date_creation' => (
dol_now() - 3600 * 48),
11319 'date_modification' => (
dol_now() - 3600 * 24),
11320 'fk_user_creat' => $user->id,
11321 'fk_user_modif' => $user->id,
11324 foreach ($fields as $key => $value) {
11325 if (array_key_exists($key, $this->fields)) {
11326 $this->{$key} = $value;
11331 if (property_exists($this,
'fields')) {
11332 foreach ($this->fields as $key => $value) {
11334 if (array_key_exists($key, $fields)) {
11338 if (!empty($value[
'default'])) {
11339 $this->$key = $value[
'default'];
11357 require_once DOL_DOCUMENT_ROOT.
'/core/class/comment.class.php';
11359 $comment =
new Comment($this->db);
11360 $result = $comment->fetchAllFor($this->element, $this->
id);
11362 $this->errors = array_merge($this->errors, $comment->errors);
11365 $this->comments = $comment->comments;
11367 return count($this->comments);
11377 return count($this->comments);
11388 if (!is_array($parameters)) {
11391 foreach ($parameters as $parameter) {
11392 if (isset($this->$parameter)) {
11393 $this->$parameter = trim($this->$parameter);
11412 require_once DOL_DOCUMENT_ROOT.
'/categories/class/categorie.class.php';
11416 $existing =
$c->containing($this->
id, $type_categ,
'id');
11436 if (!is_array($categories)) {
11437 $categories = array($categories);
11440 dol_syslog(get_class($this).
"::setCategoriesCommon Object Id:".$this->
id.
' type_categ:'.$type_categ.
' nb tag add:'.count($categories), LOG_DEBUG);
11442 require_once DOL_DOCUMENT_ROOT.
'/categories/class/categorie.class.php';
11444 if (empty($type_categ)) {
11445 dol_syslog(__METHOD__.
': Type '.$type_categ.
'is an unknown category type. Done nothing.', LOG_ERR);
11451 $existing =
$c->containing($this->
id, $type_categ,
'id');
11452 if ($remove_existing) {
11454 if (is_array($existing)) {
11455 $to_del = array_diff($existing, $categories);
11456 $to_add = array_diff($categories, $existing);
11459 $to_add = $categories;
11463 $to_add = array_diff($categories, $existing);
11470 foreach ($to_del as $del) {
11471 if (
$c->fetch($del) > 0) {
11472 $result =
$c->del_type($this, $type_categ);
11475 $this->error =
$c->error;
11476 $this->errors =
$c->errors;
11483 foreach ($to_add as $add) {
11484 if (
$c->fetch($add) > 0) {
11485 $result =
$c->add_type($this, $type_categ);
11488 $this->error =
$c->error;
11489 $this->errors =
$c->errors;
11497 return $error ? (-1 * $error) : $ok;
11510 $this->db->begin();
11512 if (empty($type)) {
11513 $type = $this->table_element;
11516 require_once DOL_DOCUMENT_ROOT.
'/categories/class/categorie.class.php';
11517 $categorystatic =
new Categorie($this->db);
11519 $sql =
"INSERT INTO ".$this->db->prefix().
"categorie_".(empty($categorystatic->MAP_CAT_TABLE[$type]) ? $type : $categorystatic->MAP_CAT_TABLE[$type]).
" (fk_categorie, fk_product)";
11520 $sql .=
" SELECT fk_categorie, $toId FROM ".$this->db->prefix().
"categorie_".(empty($categorystatic->MAP_CAT_TABLE[$type]) ? $type : $categorystatic->MAP_CAT_TABLE[$type]);
11521 $sql .=
" WHERE fk_product = ".((int) $fromId);
11523 if (!$this->db->query($sql)) {
11524 $this->error = $this->db->lasterror();
11525 $this->db->rollback();
11529 $this->db->commit();
11543 $this->db->begin();
11547 switch ($this->element) {
11549 $element =
'propale';
11552 $element =
'produit';
11554 case 'order_supplier':
11555 $element =
'fournisseur/commande';
11557 case 'invoice_supplier':
11560 $element =
'fournisseur/facture/'.get_exdir($this->
id, 2, 0, 1, $this,
'invoice_supplier');
11563 $element =
'expedition/sending';
11566 case 'project_task':
11567 require_once DOL_DOCUMENT_ROOT.
'/projet/class/task.class.php';
11569 $project_result = $this->fetchProject();
11570 if ($project_result >= 0) {
11571 $element =
'projet/'.dol_sanitizeFileName($this->project->ref).
'/';
11575 $element =
'contract';
11578 $element = $this->element;
11580 '@phan-var-force string $element';
11583 $sql =
"DELETE FROM ".$this->db->prefix().
"ecm_files_extrafields WHERE fk_object IN (";
11584 $sql .=
" SELECT rowid FROM ".$this->db->prefix().
"ecm_files WHERE filename LIKE '".$this->db->escape($this->
ref).
"%'";
11585 $sql .=
" AND filepath = '".$this->db->escape($element).
"/".$this->db->escape($this->
ref).
"' AND entity = ".((int)
$conf->entity);
11588 if (!$this->db->query($sql)) {
11589 $this->error = $this->db->lasterror();
11590 $this->db->rollback();
11595 $sql =
"DELETE FROM ".$this->db->prefix().
"ecm_files";
11596 $sql .=
" WHERE filename LIKE '".$this->db->escape($this->
ref).
"%'";
11597 $sql .=
" AND filepath = '".$this->db->escape($element).
"/".$this->db->escape($this->
ref).
"' AND entity = ".((int)
$conf->entity);
11599 if (!$this->db->query($sql)) {
11600 $this->error = $this->db->lasterror();
11601 $this->db->rollback();
11608 $sql =
'DELETE FROM '.$this->db->prefix().
"ecm_files_extrafields";
11609 $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).
")";
11610 $resql = $this->db->query($sql);
11612 $this->error = $this->db->lasterror();
11613 $this->db->rollback();
11617 $sql =
'DELETE FROM '.$this->db->prefix().
"ecm_files";
11618 $sql .=
" WHERE src_object_type = '".$this->db->escape($this->table_element.(empty($this->module) ?
"" :
"@".$this->module)).
"' AND src_object_id = ".((int) $this->
id);
11619 $resql = $this->db->query($sql);
11621 $this->error = $this->db->lasterror();
11622 $this->db->rollback();
11627 $this->db->commit();
$id
Support class for third parties, contacts, members, users or resources.
if( $user->socid > 0) if(! $user->hasRight('accounting', 'chartofaccount')) $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
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.
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.
add_element_resource($resource_id, $resource_type, $busy=0, $mandatory=0)
Add resources to the current object : add entry into llx_element_resources Need $this->element & $thi...
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.
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.
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.
setStatut($status, $elementId=null, $elementType='', $trigkey='', $fieldstatus='fk_statut')
Set status of an object.
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...
delete_resource($rowid, $element, $notrigger=0)
Delete a link to resource line.
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.
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.
call_trigger($triggerName, $user)
Call trigger based on this instance.
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.
Class to manage triggers.
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_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_delete_preview($object)
Delete all preview files linked to object instance.
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.
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_print_phone($phone, $countrycode='', $cid=0, $socid=0, $addlink='', $separ=" ", $withpicto='', $titlealt='', $adddivfloat=0, $morecss='paddingright')
Format phone numbers according to country.
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 '.
getCallerInfoString()
Get caller info as a string that can be appended to a log message.
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.
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
dol_now($mode='auto')
Return date for now.
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_print_date($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false)
Output date in a string format according to outputlangs (or langs if not defined).
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, $cid=0, $socid=0, $addlink=0, $max=64, $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.
dol_buildpath($path, $type=0, $returnemptyifnotfound=0)
Return path of url or filesystem.
dol_clone($object, $native=2)
Create a clone of instance of object (new instance with same value for each properties) With native =...
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...
dol_sanitizeFileName($str, $newstr='_', $unaccent=1, $includequotes=0)
Clean a string to use it as a file name.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
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_sanitizePathName($str, $newstr='_', $unaccent=1)
Clean a string to use it as a path name.
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.
global $conf
The following vars must be defined: $type2label $form $conf, $lang, The following vars may also be de...
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
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.