43require_once DOL_DOCUMENT_ROOT.
'/core/class/doldeprecationhandler.class.php';
52 use DolDeprecationHandler;
54 const TRIGGER_PREFIX =
'';
90 public $errors = array();
95 private $validateFieldsErrors = array();
113 public $element_for_permission;
118 public $table_element;
123 public $table_element_line =
'';
129 public $ismultientitymanaged;
139 public $array_options = array();
145 public $fields = array();
152 public $array_languages =
null;
157 public $contacts_ids;
162 public $linked_objects;
167 public $linkedObjectsIds;
172 public $linkedObjects;
177 private $linkedObjectsFullLoaded = array();
192 protected $table_ref_field =
'';
197 public $restrictiononfksoc = 0;
206 public $context = array();
318 private $commandeFournisseur;
334 public $ref_previous;
380 public $country_code;
398 public $fk_departement;
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_ttc;
540 public $multicurrency_total_localtax1;
545 public $multicurrency_total_localtax2;
557 public $last_main_doc;
582 public $note_private;
607 public $total_localtax1;
613 public $total_localtax2;
630 public $actiontypecode;
636 public $comments = array();
662 public $date_creation;
667 public $date_validation;
672 public $date_modification;
686 private $date_update;
691 public $date_cloture;
703 public $user_creation;
708 public $user_creation_id;
720 public $user_validation;
725 public $user_validation_id;
730 public $user_closing_id;
736 public $user_modification;
741 public $user_modification_id;
747 public $fk_user_creat;
753 public $fk_user_modif;
759 public $next_prev_filter;
764 public $specimen = 0;
786 public $labelStatus = array();
791 public $labelStatusShort = array();
802 public $showphoto_on_popup;
807 public $nb = array();
822 public $extraparams = array();
827 protected $childtables = array();
834 protected $childtablesoncascade = array();
844 public $cond_reglement_supplier_id;
851 public $deposit_percent;
857 public $retained_warranty_fk_cond_reglement;
862 public $warehouse_id;
867 public $isextrafieldmanaged = 0;
880 'alreadypaid' =>
'totalpaid',
881 'cond_reglement' =>
'depr_cond_reglement',
883 'commandeFournisseur' =>
'origin_object',
884 'expedition' =>
'origin_object',
885 'fk_project' =>
'fk_project',
886 'livraison' =>
'origin_object',
887 'projet' =>
'project',
888 'statut' =>
'status',
907 $sql =
"SELECT rowid, ref, ref_ext";
908 $sql .=
" FROM ".$db->prefix().$element;
909 $sql .=
" WHERE entity IN (".getEntity($element).
")";
912 $sql .=
" AND rowid = ".((int) $id);
914 $sql .=
" AND ref = '".$db->escape($ref).
"'";
915 } elseif ($ref_ext) {
916 $sql .=
" AND ref_ext = '".$db->escape($ref_ext).
"'";
918 $error =
'ErrorWrongParameters';
919 dol_syslog(get_class().
"::isExistingObject ".$error, LOG_ERR);
922 if ($ref || $ref_ext) {
923 $sql .=
" AND entity = ".((int) $conf->entity);
926 dol_syslog(get_class().
"::isExistingObject", LOG_DEBUG);
927 $resql = $db->query($sql);
929 $num = $db->num_rows($resql);
946 return (empty($this->
id));
961 $this->errors = array_merge($this->errors,
$object->errors);
986 global $action, $extrafields, $langs, $hookmanager;
989 $MAX_EXTRAFIELDS_TO_SHOW_IN_TOOLTIP =
getDolGlobalInt(
'MAX_EXTRAFIELDS_TO_SHOW_IN_TOOLTIP', 3);
995 if (!empty($extrafields->attributes[$this->table_element][
'label'])) {
996 $data[
'opendivextra'] =
'<div class="centpercent wordbreak divtooltipextra">';
997 foreach ($extrafields->attributes[$this->table_element][
'label'] as $key => $val) {
998 if ($extrafields->attributes[$this->table_element][
'type'][$key] ==
'separate') {
1001 if ($count >= abs($MAX_EXTRAFIELDS_TO_SHOW_IN_TOOLTIP)) {
1002 $data[
'more_extrafields'] =
'<br>...';
1006 if ($enabled && isset($extrafields->attributes[$this->table_element][
'enabled'][$key])) {
1007 $enabled = (int)
dol_eval((
string) $extrafields->attributes[$this->table_element][
'enabled'][$key], 1, 1,
'2');
1009 if ($enabled && isset($extrafields->attributes[$this->table_element][
'list'][$key])) {
1010 $enabled = (int)
dol_eval($extrafields->attributes[$this->table_element][
'list'][$key], 1, 1,
'2');
1013 if ($perms && isset($extrafields->attributes[$this->table_element][
'perms'][$key])) {
1014 $perms = (int)
dol_eval($extrafields->attributes[$this->table_element][
'perms'][$key], 1, 1,
'2');
1016 if (empty($enabled)) {
1019 if (abs($enabled) != 1 && abs($enabled) != 3 && abs($enabled) != 5 && abs($enabled) != 4) {
1022 if (empty($perms)) {
1025 if (!empty($extrafields->attributes[$this->table_element][
'langfile'][$key])) {
1026 $langs->load($extrafields->attributes[$this->table_element][
'langfile'][$key]);
1028 $labelextra = $langs->trans((
string) $extrafields->attributes[$this->table_element][
'label'][$key]);
1029 if ($extrafields->attributes[$this->table_element][
'type'][$key] ==
'separate') {
1030 $data[$key] =
'<br><b><u>'. $labelextra .
'</u></b>';
1032 $value = (empty($this->array_options[
'options_' . $key]) ?
'' : $this->array_options[
'options_' . $key]);
1033 $data[$key] =
'<br><b>'. $labelextra .
':</b> ' . $extrafields->showOutputField($key, $value,
'', $this->table_element);
1037 $data[
'closedivextra'] =
'</div>';
1040 $hookmanager->initHooks(array($this->element .
'dao'));
1041 $parameters = array(
1042 'tooltipcontentarray' => &$data,
1043 'params' => $params,
1046 $hookmanager->executeHooks(
'getTooltipContent', $parameters, $this, $action);
1049 $label = implode($data);
1062 return $this->error.(is_array($this->errors) ? (($this->error !=
'' ?
', ' :
'').implode(
', ', $this->errors)) :
'');
1074 global $hookmanager;
1076 $parameters = array(
'objref' => $objref);
1078 $reshook = $hookmanager->executeHooks(
'getFormatedCustomerRef', $parameters, $this, $action);
1080 return $hookmanager->resArray[
'objref'];
1082 return $objref.(isset($hookmanager->resArray[
'objref']) ? $hookmanager->resArray[
'objref'] :
'');
1093 global $hookmanager;
1095 $parameters = array(
'objref' => $objref);
1097 $reshook = $hookmanager->executeHooks(
'getFormatedSupplierRef', $parameters, $this, $action);
1099 return $hookmanager->resArray[
'objref'];
1101 return $objref.(isset($hookmanager->resArray[
'objref']) ? $hookmanager->resArray[
'objref'] :
'');
1113 public function getFullAddress($withcountry = 0, $sep =
"\n", $withregion = 0, $extralangcode =
'')
1115 if ($withcountry && $this->country_id && (empty($this->country_code) || empty($this->country))) {
1116 require_once DOL_DOCUMENT_ROOT.
'/core/lib/company.lib.php';
1117 $tmparray =
getCountry($this->country_id,
'all');
1118 $this->country_code = $tmparray[
'code'];
1119 $this->country = $tmparray[
'label'];
1122 if ($withregion && $this->state_id && (empty($this->state_code) || empty($this->state) || empty($this->region) || empty($this->region_code))) {
1123 require_once DOL_DOCUMENT_ROOT.
'/core/lib/company.lib.php';
1124 $tmparray =
getState($this->state_id,
'all',
null, 1);
1125 $this->state_code = $tmparray[
'code'];
1126 $this->state = $tmparray[
'label'];
1127 $this->region_code = $tmparray[
'region_code'];
1128 $this->region = $tmparray[
'region'];
1145 global $user, $dolibarr_main_url_root;
1147 if (empty($this->last_main_doc)) {
1151 include_once DOL_DOCUMENT_ROOT.
'/ecm/class/ecmfiles.class.php';
1152 $ecmfile =
new EcmFiles($this->db);
1153 $result = $ecmfile->fetch(0,
'', $this->last_main_doc);
1155 $this->error = $ecmfile->error;
1156 $this->errors = $ecmfile->errors;
1160 if (empty($ecmfile->id)) {
1162 if ($initsharekey) {
1163 require_once DOL_DOCUMENT_ROOT.
'/core/lib/security2.lib.php';
1185 } elseif (empty($ecmfile->share)) {
1187 if ($initsharekey) {
1188 require_once DOL_DOCUMENT_ROOT.
'/core/lib/security2.lib.php';
1190 $ecmfile->update($user);
1196 $urlwithouturlroot = preg_replace(
'/'.preg_quote(DOL_URL_ROOT,
'/').
'$/i',
'', trim($dolibarr_main_url_root));
1200 $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT;
1209 if (!empty($ecmfile->share)) {
1210 $paramlink .= ($paramlink ?
'&' :
'').
'hashp='.$ecmfile->share;
1212 if ($forcedownload) {
1213 $paramlink .= ($paramlink ?
'&' :
'').
'attachment=1';
1216 if ($relativelink) {
1217 $linktoreturn =
'document.php'.($paramlink ?
'?'.$paramlink :
'');
1219 $linktoreturn = $urlwithroot.
'/document.php'.($paramlink ?
'?'.$paramlink :
'');
1223 return $linktoreturn;
1237 public function add_contact($fk_socpeople, $type_contact, $source =
'external', $notrigger = 0)
1240 global $user, $langs;
1243 dol_syslog(get_class($this).
"::add_contact $fk_socpeople, $type_contact, $source, $notrigger");
1246 if ($fk_socpeople <= 0) {
1247 $langs->load(
"errors");
1248 $this->error = $langs->trans(
"ErrorWrongValueForParameterX",
"1");
1249 dol_syslog(get_class($this).
"::add_contact ".$this->error, LOG_ERR);
1252 if (!$type_contact) {
1253 $langs->load(
"errors");
1254 $this->error = $langs->trans(
"ErrorWrongValueForParameterX",
"2");
1255 dol_syslog(get_class($this).
"::add_contact ".$this->error, LOG_ERR);
1259 $id_type_contact = 0;
1260 if (is_numeric($type_contact)) {
1261 $id_type_contact = $type_contact;
1264 $sql =
"SELECT tc.rowid";
1265 $sql .=
" FROM ".$this->db->prefix().
"c_type_contact as tc";
1266 $sql .=
" WHERE tc.element='".$this->db->escape($this->element).
"'";
1267 $sql .=
" AND tc.source='".$this->db->escape($source).
"'";
1268 $sql .=
" AND tc.code='".$this->db->escape($type_contact).
"' AND tc.active=1";
1270 $resql = $this->db->query($sql);
1272 $obj = $this->db->fetch_object($resql);
1274 $id_type_contact = $obj->rowid;
1279 if ($id_type_contact == 0) {
1280 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");
1288 $already_added =
false;
1289 if (is_array($TListeContacts) && !empty($TListeContacts)) {
1290 foreach ($TListeContacts as $array_contact) {
1291 if ($array_contact[
'status'] == 4 && $array_contact[
'id'] == $fk_socpeople && $array_contact[
'fk_c_type_contact'] == $id_type_contact) {
1292 $already_added =
true;
1298 if (!$already_added) {
1302 $sql =
"INSERT INTO ".$this->db->prefix().
"element_contact";
1303 $sql .=
" (element_id, fk_socpeople, datecreate, statut, fk_c_type_contact) ";
1304 $sql .=
" VALUES (".$this->id.
", ".((int) $fk_socpeople).
" , ";
1305 $sql .=
"'".$this->db->idate($datecreate).
"'";
1306 $sql .=
", 4, ".((int) $id_type_contact);
1309 $resql = $this->db->query($sql);
1312 $result = $this->
call_trigger(strtoupper($this->element).
'_ADD_CONTACT', $user);
1314 $this->db->rollback();
1319 $this->db->commit();
1322 if ($this->db->errno() ==
'DB_ERROR_RECORD_ALREADY_EXISTS') {
1323 $this->error = $this->db->errno();
1324 $this->db->rollback();
1327 $this->error = $this->db->lasterror();
1328 $this->db->rollback();
1348 $contacts = $objFrom->liste_contact(-1, $source);
1349 foreach ($contacts as $contact) {
1350 if ($this->
add_contact($contact[
'id'], $contact[
'fk_c_type_contact'], $contact[
'source']) < 0) {
1367 public function update_contact($rowid, $statut, $type_contact_id = 0, $fk_socpeople = 0)
1371 $sql =
"UPDATE ".$this->db->prefix().
"element_contact set";
1372 $sql .=
" statut = ".((int) $statut);
1373 if ($type_contact_id) {
1374 $sql .=
", fk_c_type_contact = ".((int) $type_contact_id);
1376 if ($fk_socpeople) {
1377 $sql .=
", fk_socpeople = ".((int) $fk_socpeople);
1379 $sql .=
" where rowid = ".((int) $rowid);
1381 $resql = $this->db->query($sql);
1385 $this->error = $this->db->lasterror();
1407 if (!$error && empty($notrigger)) {
1409 $this->context[
'contact_id'] = ((int) $rowid);
1410 $result = $this->
call_trigger(strtoupper($this->element).
'_DELETE_CONTACT', $user);
1418 dol_syslog(get_class($this).
"::delete_contact", LOG_DEBUG);
1420 $sql =
"DELETE FROM ".MAIN_DB_PREFIX.
"element_contact";
1421 $sql .=
" WHERE rowid = ".((int) $rowid);
1423 $result = $this->db->query($sql);
1426 $this->errors[] = $this->db->lasterror();
1431 $this->db->commit();
1434 $this->error = $this->db->lasterror();
1435 $this->db->rollback();
1455 if (!empty($typeContact)) {
1456 foreach ($typeContact as $key => $value) {
1457 array_push($temp, $key);
1459 $listId = implode(
",", $temp);
1464 if (empty($listId)) {
1468 $sql =
"DELETE FROM ".$this->db->prefix().
"element_contact";
1469 $sql .=
" WHERE element_id = ".((int) $this->
id);
1470 $sql .=
" AND fk_c_type_contact IN (".$this->db->sanitize($listId).
")";
1472 dol_syslog(get_class($this).
"::delete_linked_contact", LOG_DEBUG);
1473 if ($this->db->query($sql)) {
1476 $this->error = $this->db->lasterror();
1493 public function liste_contact($statusoflink = -1, $source =
'external', $list = 0, $code =
'', $status = -1, $arrayoftcids = array())
1500 $sql =
"SELECT ec.rowid, ec.statut as statuslink, ec.fk_socpeople as id, ec.fk_c_type_contact";
1501 if ($source ==
'internal') {
1502 $sql .=
", '-1' as socid, t.statut as statuscontact, t.login, t.photo, t.gender";
1504 if ($source ==
'external' || $source ==
'thirdparty') {
1505 $sql .=
", t.fk_soc as socid, t.statut as statuscontact";
1507 $sql .=
", t.civility as civility, t.lastname as lastname, t.firstname, t.email";
1508 if (empty($arrayoftcids)) {
1509 $sql .=
", tc.source, tc.element, tc.code, tc.libelle as type_label";
1512 if (empty($arrayoftcids)) {
1513 $sql .=
" ".$this->db->prefix().
"c_type_contact as tc,";
1515 $sql .=
" ".$this->db->prefix().
"element_contact as ec";
1516 if ($source ==
'internal') {
1517 $sql .=
" LEFT JOIN ".$this->db->prefix().
"user as t on ec.fk_socpeople = t.rowid";
1519 if ($source ==
'external' || $source ==
'thirdparty') {
1520 $sql .=
" LEFT JOIN ".$this->db->prefix().
"socpeople as t on ec.fk_socpeople = t.rowid";
1522 $sql .=
" WHERE ec.element_id = ".((int) $this->
id);
1523 if (empty($arrayoftcids)) {
1524 $sql .=
" AND ec.fk_c_type_contact = tc.rowid";
1525 $sql .=
" AND tc.element = '".$this->db->escape($this->element).
"'";
1527 $sql .=
" AND tc.code = '".$this->db->escape($code).
"'";
1529 if ($source ==
'internal') {
1530 $sql .=
" AND tc.source = 'internal'";
1532 if ($source ==
'external' || $source ==
'thirdparty') {
1533 $sql .=
" AND tc.source = 'external'";
1535 $sql .=
" AND tc.active = 1";
1537 $sql .=
" AND ec.fk_c_type_contact IN (".$this->db->sanitize(implode(
',', $arrayoftcids)).
")";
1540 $sql .=
" AND t.statut = ".((int) $status);
1542 if ($statusoflink >= 0) {
1543 $sql .=
" AND ec.statut = ".((int) $statusoflink);
1545 $sql .=
" ORDER BY t.lastname ASC";
1547 dol_syslog(get_class($this).
"::liste_contact", LOG_DEBUG);
1548 $resql = $this->db->query($sql);
1550 $num = $this->db->num_rows($resql);
1553 $obj = $this->db->fetch_object($resql);
1556 $transkey =
"TypeContact_".$obj->element.
"_".$obj->source.
"_".$obj->code;
1557 $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->type_label);
1559 'parentId' => $this->
id,
1560 'source' => $obj->source,
1561 'socid' => $obj->socid,
1563 'nom' => $obj->lastname,
1564 'civility' => $obj->civility,
1565 'lastname' => $obj->lastname,
1566 'firstname' => $obj->firstname,
1567 'email' => $obj->email,
1568 'login' => (empty($obj->login) ?
'' : $obj->login),
1569 'photo' => (empty($obj->photo) ?
'' : $obj->photo),
1570 'gender' => (empty($obj->gender) ?
'' : $obj->gender),
1571 'statuscontact' => $obj->statuscontact,
1572 'rowid' => $obj->rowid,
1573 'code' => $obj->code,
1574 'libelle' => $libelle_type,
1575 'status' => $obj->statuslink,
1576 'fk_c_type_contact' => $obj->fk_c_type_contact
1579 $tab[$i] = $obj->id;
1587 $this->error = $this->db->lasterror();
1602 $sql =
"SELECT ec.datecreate, ec.statut, ec.fk_socpeople, ec.fk_c_type_contact,";
1603 $sql .=
" tc.code, tc.libelle as type_label";
1604 $sql .=
" FROM (".$this->db->prefix().
"element_contact as ec, ".$this->db->prefix().
"c_type_contact as tc)";
1605 $sql .=
" WHERE ec.rowid =".((int) $rowid);
1606 $sql .=
" AND ec.fk_c_type_contact = tc.rowid";
1607 $sql .=
" AND tc.element = '".$this->db->escape($this->element).
"'";
1609 dol_syslog(get_class($this).
"::swapContactStatus", LOG_DEBUG);
1610 $resql = $this->db->query($sql);
1612 $obj = $this->db->fetch_object($resql);
1613 $newstatut = ($obj->statut == 4) ? 5 : 4;
1615 $this->db->free($resql);
1618 $this->error = $this->db->error();
1635 public function liste_type_contact($source =
'internal', $order =
'position', $option = 0, $activeonly = 0, $code =
'')
1640 if (empty($order)) {
1641 $order =
'position';
1643 if ($order ==
'position') {
1648 $sql =
"SELECT DISTINCT tc.rowid, tc.code, tc.libelle as type_label, tc.position";
1649 $sql .=
" FROM ".$this->db->prefix().
"c_type_contact as tc";
1650 $sql .=
" WHERE tc.element='".$this->db->escape($this->element).
"'";
1651 if ($activeonly == 1) {
1652 $sql .=
" AND tc.active=1";
1654 if (!empty($source) && $source !=
'all') {
1655 $sql .=
" AND tc.source='".$this->db->escape($source).
"'";
1657 if (!empty($code)) {
1658 $sql .=
" AND tc.code='".$this->db->escape($code).
"'";
1660 $sql .= $this->db->order($order,
'ASC');
1663 $resql = $this->db->query($sql);
1665 $num = $this->db->num_rows($resql);
1668 $obj = $this->db->fetch_object($resql);
1670 $transkey =
"TypeContact_".$this->element.
"_".$source.
"_".$obj->code;
1671 $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->type_label);
1672 if (empty($option)) {
1673 $tab[$obj->rowid] = $libelle_type;
1675 $tab[$obj->code] = $libelle_type;
1681 $this->error = $this->db->lasterror();
1698 public function listeTypeContacts($source =
'internal', $option = 0, $activeonly = 0, $code =
'', $element =
'', $excludeelement =
'')
1700 global $langs, $conf;
1702 $langs->loadLangs(array(
'bills',
'contracts',
'interventions',
'orders',
'projects',
'propal',
'ticket',
'agenda'));
1706 $sql =
"SELECT DISTINCT tc.rowid, tc.code, tc.libelle as type_label, tc.position, tc.element";
1707 $sql .=
" FROM ".$this->db->prefix().
"c_type_contact as tc";
1709 $sqlWhere = array();
1710 if (!empty($element)) {
1711 $sqlWhere[] =
" tc.element='".$this->db->escape($element).
"'";
1713 if (!empty($excludeelement)) {
1714 $sqlWhere[] =
" tc.element <> '".$this->db->escape($excludeelement).
"'";
1717 if ($activeonly == 1) {
1718 $sqlWhere[] =
" tc.active=1";
1721 if (!empty($source) && $source !=
'all') {
1722 $sqlWhere[] =
" tc.source='".$this->db->escape($source).
"'";
1725 if (!empty($code)) {
1726 $sqlWhere[] =
" tc.code='".$this->db->escape($code).
"'";
1729 if (count($sqlWhere) > 0) {
1730 $sql .=
" WHERE ".implode(
' AND ', $sqlWhere);
1733 $sql .= $this->db->order(
'tc.element, tc.position',
'ASC');
1736 $resql = $this->db->query($sql);
1738 $num = $this->db->num_rows($resql);
1740 $langs->loadLangs(array(
"propal",
"orders",
"bills",
"suppliers",
"contracts",
"supplier_proposal"));
1742 while ($obj = $this->db->fetch_object($resql)) {
1743 $modulename = $obj->element;
1744 if (strpos($obj->element,
'project') !==
false) {
1745 $modulename =
'projet';
1746 } elseif ($obj->element ==
'contrat') {
1747 $element =
'contract';
1748 } elseif ($obj->element ==
'action') {
1749 $modulename =
'agenda';
1750 } elseif (strpos($obj->element,
'supplier') !==
false && $obj->element !=
'supplier_proposal') {
1751 $modulename =
'fournisseur';
1753 if (isModEnabled($modulename)) {
1754 $libelle_element = $langs->trans(
'ContactDefault_'.$obj->element);
1755 $tmpelement = $obj->element;
1756 $transkey =
"TypeContact_".$tmpelement.
"_".$source.
"_".$obj->code;
1757 $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->type_label);
1758 $tab[$obj->rowid] = $libelle_element.
' - '.$libelle_type;
1764 $this->error = $this->db->lasterror();
1787 if ($this->element ==
'shipping' && $this->origin_id != 0) {
1788 $id = $this->origin_id;
1789 $element =
'commande';
1790 } elseif ($this->element ==
'reception' && $this->origin_id != 0) {
1791 $id = $this->origin_id;
1792 $element =
'order_supplier';
1795 $element = $this->element;
1798 $sql =
"SELECT ec.fk_socpeople";
1799 $sql .=
" FROM ".$this->db->prefix().
"element_contact as ec,";
1800 if ($source ==
'internal') {
1801 $sql .=
" ".$this->db->prefix().
"user as c,";
1803 if ($source ==
'external') {
1804 $sql .=
" ".$this->db->prefix().
"socpeople as c,";
1806 $sql .=
" ".$this->db->prefix().
"c_type_contact as tc";
1807 $sql .=
" WHERE ec.element_id = ".((int) $id);
1808 $sql .=
" AND ec.fk_socpeople = c.rowid";
1809 if ($source ==
'internal') {
1810 $sql .=
" AND c.entity IN (".getEntity(
'user').
")";
1812 if ($source ==
'external') {
1813 $sql .=
" AND c.entity IN (".getEntity(
'societe').
")";
1815 $sql .=
" AND ec.fk_c_type_contact = tc.rowid";
1816 $sql .=
" AND tc.element = '".$this->db->escape($element).
"'";
1817 $sql .=
" AND tc.source = '".$this->db->escape($source).
"'";
1819 $sql .=
" AND tc.code = '".$this->db->escape($code).
"'";
1821 $sql .=
" AND tc.active = 1";
1823 $sql .=
" AND ec.statut = ".((int) $status);
1826 dol_syslog(get_class($this).
"::getIdContact", LOG_DEBUG);
1827 $resql = $this->db->query($sql);
1829 while ($obj = $this->db->fetch_object($resql)) {
1830 $result[$i] = $obj->fk_socpeople;
1834 $this->error = $this->db->error();
1851 if (empty($contactid)) {
1852 $contactid = $this->contact_id;
1855 if (empty($contactid)) {
1859 require_once DOL_DOCUMENT_ROOT.
'/contact/class/contact.class.php';
1860 $contact =
new Contact($this->db);
1861 $result = $contact->fetch($contactid);
1862 $this->contact = $contact;
1877 if (empty($this->socid) && empty($this->fk_soc) && empty($force_thirdparty_id)) {
1881 require_once DOL_DOCUMENT_ROOT.
'/societe/class/societe.class.php';
1883 $idtofetch = isset($this->socid) ? $this->socid : (isset($this->fk_soc) ? $this->fk_soc : 0);
1884 if ($force_thirdparty_id) {
1885 $idtofetch = $force_thirdparty_id;
1889 $thirdparty =
new Societe($this->db);
1890 $result = $thirdparty->fetch($idtofetch);
1892 $this->errors = array_merge($this->errors, $thirdparty->errors);
1894 $this->thirdparty = $thirdparty;
1898 $this->thirdparty->price_level = 1;
1917 if (!$this->table_ref_field) {
1921 $sql =
"SELECT rowid FROM ".$this->db->prefix().$this->table_element;
1922 $sql .=
" WHERE ".$this->table_ref_field.
" LIKE '".$this->db->escape($ref).
"'";
1925 $query = $this->db->query($sql);
1927 if (!$this->db->num_rows($query)) {
1931 $result = $this->db->fetch_object($query);
1933 if (method_exists($this,
'fetch')) {
1934 return $this->fetch($result->rowid);
1936 $this->error =
'Fetch method not implemented on '.get_class($this);
1937 dol_syslog(get_class($this).
'::fetchOneLike Error='.$this->error, LOG_ERR);
1938 array_push($this->errors, $this->error);
1956 dol_syslog(get_class($this).
'::fetch_barcode this->element='.$this->element.
' this->barcode_type='.$this->barcode_type);
1958 $idtype = $this->barcode_type;
1959 if (empty($idtype) && $idtype !=
'0') {
1960 if ($this->element ==
'product' &&
getDolGlobalString(
'PRODUIT_DEFAULT_BARCODE_TYPE')) {
1962 } elseif ($this->element ==
'societe') {
1965 dol_syslog(
'Call fetch_barcode with barcode_type not defined and cannot be guessed', LOG_WARNING);
1970 if (empty($this->barcode_type) || empty($this->barcode_type_code) || empty($this->barcode_type_label) || empty($this->barcode_type_coder)) {
1971 $sql =
"SELECT rowid, code, libelle as label, coder";
1972 $sql .=
" FROM ".$this->db->prefix().
"c_barcode_type";
1973 $sql .=
" WHERE rowid = ".((int) $idtype);
1974 dol_syslog(get_class($this).
'::fetch_barcode', LOG_DEBUG);
1975 $resql = $this->db->query($sql);
1977 $obj = $this->db->fetch_object($resql);
1978 $this->barcode_type = $obj->rowid;
1979 $this->barcode_type_code = $obj->code;
1980 $this->barcode_type_label = $obj->label;
1981 $this->barcode_type_coder = $obj->coder;
1999 include_once DOL_DOCUMENT_ROOT.
'/projet/class/project.class.php';
2001 if (empty($this->fk_project) && !empty($this->fk_projet)) {
2002 $this->fk_project = $this->fk_projet;
2004 if (empty($this->fk_project)) {
2008 $project =
new Project($this->db);
2009 $result = $project->fetch($this->fk_project);
2011 $this->projet = $project;
2012 $this->project = $project;
2054 include_once DOL_DOCUMENT_ROOT.
'/product/class/product.class.php';
2057 if (empty($this->fk_product)) {
2061 $product =
new Product($this->db);
2063 $result = $product->fetch($this->fk_product);
2065 $this->product = $product;
2079 $user =
new User($this->db);
2080 $result = $user->fetch($userid);
2081 $this->
user = $user;
2095 $origin = $this->origin ? $this->origin : $this->origin_type;
2098 if ($origin ==
'shipping') {
2099 $origin =
'expedition';
2101 if ($origin ==
'delivery') {
2102 $origin =
'livraison';
2104 if ($origin ==
'order_supplier' || $origin ==
'supplier_order') {
2105 $origin =
'commandeFournisseur';
2108 $classname = ucfirst($origin);
2109 $this->origin_object =
new $classname($this->db);
2111 $this->origin_object->fetch($this->origin_id);
2129 $sql =
"SELECT rowid FROM ".$this->db->prefix().$table;
2130 $sql .=
" WHERE ".$field.
" = '".$this->db->escape($key).
"'";
2131 if (!empty($element)) {
2132 $sql .=
" AND entity IN (".getEntity($element).
")";
2134 $sql .=
" AND entity = ".((int) $conf->entity);
2137 dol_syslog(get_class($this).
'::fetchObjectFrom', LOG_DEBUG);
2138 $resql = $this->db->query($sql);
2140 $obj = $this->db->fetch_object($resql);
2143 if (method_exists($this,
'fetch')) {
2144 $result = $this->fetch($obj->rowid);
2146 $this->error =
'fetch() method not implemented on '.get_class($this);
2147 dol_syslog(get_class($this).
'::fetchOneLike Error='.$this->error, LOG_ERR);
2148 array_push($this->errors, $this->error);
2168 if (!empty($id) && !empty($field) && !empty($table)) {
2169 $sql =
"SELECT ".$field.
" FROM ".$this->db->prefix().$table;
2170 $sql .=
" WHERE rowid = ".((int) $id);
2172 dol_syslog(get_class($this).
'::getValueFrom', LOG_DEBUG);
2173 $resql = $this->db->query($sql);
2175 $row = $this->db->fetch_row($resql);
2198 public function setValueFrom($field, $value, $table =
'', $id =
null, $format =
'', $id_field =
'', $fuser =
null, $trigkey =
'', $fk_user_field =
'fk_user_modif')
2202 if (empty($table)) {
2203 $table = $this->table_element;
2208 if (empty($format)) {
2211 if (empty($id_field)) {
2212 $id_field =
'rowid';
2216 if ($table ==
'product' && $field ==
'note_private') {
2220 if (in_array($table, array(
'actioncomm',
'adherent',
'advtargetemailing',
'cronjob',
'establishment'))) {
2221 $fk_user_field =
'fk_user_mod';
2223 if (in_array($table, array(
'prelevement_bons'))) {
2224 $fk_user_field =
'';
2229 $sql =
"SELECT " . $field;
2230 $sql .=
" FROM " . MAIN_DB_PREFIX . $table;
2231 $sql .=
" WHERE " . $id_field .
" = " . ((int) $id);
2233 $resql = $this->db->query($sql);
2235 if ($obj = $this->db->fetch_object($resql)) {
2236 if ($format ==
'date') {
2237 $oldvalue = $this->db->jdate($obj->$field);
2239 $oldvalue = $obj->$field;
2243 $this->error = $this->db->lasterror();
2254 $sql =
"UPDATE ".$this->db->prefix().$table.
" SET ";
2256 if ($format ==
'text') {
2257 $sql .= $field.
" = '".$this->db->escape($value).
"'";
2258 } elseif ($format ==
'int') {
2259 $sql .= $field.
" = ".((int) $value);
2260 } elseif ($format ==
'date') {
2261 $sql .= $field.
" = ".($value ?
"'".$this->db->idate($value).
"'" :
"null");
2262 } elseif ($format ==
'dategmt') {
2263 $sql .= $field.
" = ".($value ?
"'".$this->db->idate($value,
'gmt').
"'" :
"null");
2266 if ($fk_user_field) {
2267 if (!empty($fuser) && is_object($fuser)) {
2268 $sql .=
", ".$fk_user_field.
" = ".((int) $fuser->id);
2269 } elseif (empty($fuser) || $fuser !=
'none') {
2270 $sql .=
", ".$fk_user_field.
" = ".((int) $user->id);
2274 $sql .=
" WHERE ".$id_field.
" = ".((int) $id);
2276 $resql = $this->db->query($sql);
2280 if (method_exists($this,
'fetch')) {
2281 $result = $this->fetch($id);
2285 $this->oldcopy = clone $this;
2286 if (property_exists($this->oldcopy, $field)) {
2287 $this->oldcopy->$field = $oldvalue;
2291 $result = $this->
call_trigger($trigkey, (!empty($fuser) && is_object($fuser)) ? $fuser : $user);
2299 if (property_exists($this, $field)) {
2300 $this->$field = $value;
2302 $this->db->commit();
2305 $this->db->rollback();
2309 if ($this->db->lasterrno() ==
'DB_ERROR_RECORD_ALREADY_EXISTS') {
2310 $this->error =
'DB_ERROR_RECORD_ALREADY_EXISTS';
2312 $this->error = $this->db->lasterror();
2314 $this->db->rollback();
2333 global $conf, $user;
2335 if (!$this->table_element) {
2336 dol_print_error(
null, get_class($this).
"::load_previous_next_ref was called on object with property table_element not defined");
2339 if ($fieldid ==
'none') {
2344 if (in_array($this->table_element, array(
'facture_rec',
'facture_fourn_rec')) && $fieldid ==
'title') {
2350 if ($user->socid > 0) {
2351 $socid = $user->socid;
2356 $aliastablesociete =
's';
2357 if ($this->element ==
'societe') {
2358 $aliastablesociete =
'te';
2360 $restrictiononfksoc = empty($this->restrictiononfksoc) ? 0 : $this->restrictiononfksoc;
2361 $sql =
"SELECT MAX(te.".$fieldid.
")";
2362 $sql .=
" FROM ".(empty($nodbprefix) ? $this->db->prefix() :
'').$this->table_element.
" as te";
2363 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2364 $tmparray = explode(
'@', $this->ismultientitymanaged);
2365 $sql .=
", ".$this->db->prefix().$tmparray[1].
" as ".($tmparray[1] ==
'societe' ?
's' :
'parenttable');
2366 } elseif ($restrictiononfksoc == 1 && $this->element !=
'societe' && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2367 $sql .=
", ".$this->db->prefix().
"societe as s";
2368 } elseif ($restrictiononfksoc == 2 && $this->element !=
'societe' && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2369 $sql .=
" LEFT JOIN ".$this->db->prefix().
"societe as s ON te.fk_soc = s.rowid";
2371 if ($restrictiononfksoc && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2372 $sql .=
" LEFT JOIN ".$this->db->prefix().
"societe_commerciaux as sc ON ".$aliastablesociete.
".rowid = sc.fk_soc";
2374 if ($fieldid ==
'rowid') {
2375 $sql .=
" WHERE te.".$fieldid.
" < ".((int) $this->
id);
2377 $sql .=
" WHERE te.".$fieldid.
" < '".$this->db->escape($this->
ref).
"'";
2379 if ($restrictiononfksoc == 1 && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2380 $sql .=
" AND sc.fk_user = ".((int) $user->id);
2382 if ($restrictiononfksoc == 2 && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2383 $sql .=
" AND (sc.fk_user = ".((int) $user->id).
' OR te.fk_soc IS NULL)';
2386 $filtermax = $filter;
2391 if ($errormessage) {
2392 if (!preg_match(
'/^\s*AND/i', $filtermax)) {
2400 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2401 $tmparray = explode(
'@', $this->ismultientitymanaged);
2402 $sql .=
" AND te.".$tmparray[0].
" = ".($tmparray[1] ==
"societe" ?
"s" :
"parenttable").
".rowid";
2403 } elseif ($restrictiononfksoc == 1 && $this->element !=
'societe' && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2404 $sql .=
' AND te.fk_soc = s.rowid';
2406 if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
2407 if ($this->element ==
'user' &&
getDolGlobalInt(
'MULTICOMPANY_TRANSVERSE_MODE')) {
2408 if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
2409 $sql .=
" AND te.entity IS NOT NULL";
2411 $sql .=
" AND te.rowid IN (SELECT ug.fk_user FROM ".$this->db->prefix().
"usergroup_user as ug WHERE ug.entity IN (".
getEntity(
'usergroup').
"))";
2414 $sql .=
' AND te.entity IN ('.getEntity($this->element).
')';
2417 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged) && $this->element !=
'societe') {
2418 $tmparray = explode(
'@', $this->ismultientitymanaged);
2419 $sql .=
' AND parenttable.entity IN ('.getEntity($tmparray[1]).
')';
2421 if ($restrictiononfksoc == 1 && $socid && $this->element !=
'societe') {
2422 $sql .=
' AND te.fk_soc = '.((int) $socid);
2424 if ($restrictiononfksoc == 2 && $socid && $this->element !=
'societe') {
2425 $sql .=
' AND (te.fk_soc = '.((int) $socid).
' OR te.fk_soc IS NULL)';
2427 if ($restrictiononfksoc && $socid && $this->element ==
'societe') {
2428 $sql .=
' AND te.rowid = '.((int) $socid);
2432 $result = $this->db->query($sql);
2434 $this->error = $this->db->lasterror();
2437 $row = $this->db->fetch_row($result);
2438 $this->ref_previous = $row[0];
2440 $sql =
"SELECT MIN(te.".$fieldid.
")";
2441 $sql .=
" FROM ".(empty($nodbprefix) ? $this->db->prefix() :
'').$this->table_element.
" as te";
2442 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2443 $tmparray = explode(
'@', $this->ismultientitymanaged);
2444 $sql .=
", ".$this->db->prefix().$tmparray[1].
" as ".($tmparray[1] ==
'societe' ?
's' :
'parenttable');
2445 } elseif ($restrictiononfksoc == 1 && $this->element !=
'societe' && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2446 $sql .=
", ".$this->db->prefix().
"societe as s";
2447 } elseif ($restrictiononfksoc == 2 && $this->element !=
'societe' && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2448 $sql .=
" LEFT JOIN ".$this->db->prefix().
"societe as s ON te.fk_soc = s.rowid";
2450 if ($restrictiononfksoc && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2451 $sql .=
" LEFT JOIN ".$this->db->prefix().
"societe_commerciaux as sc ON ".$aliastablesociete.
".rowid = sc.fk_soc";
2453 if ($fieldid ==
'rowid') {
2454 $sql .=
" WHERE te.".$fieldid.
" > ".((int) $this->
id);
2456 $sql .=
" WHERE te.".$fieldid.
" > '".$this->db->escape($this->
ref).
"'";
2458 if ($restrictiononfksoc == 1 && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2459 $sql .=
" AND (sc.fk_user = ".((int) $user->id);
2461 $userschilds = $user->getAllChildIds();
2462 $sql .=
" OR sc.fk_user IN (".$this->db->sanitize(implode(
',', $userschilds)).
")";
2466 if ($restrictiononfksoc == 2 && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2467 $sql .=
" AND (sc.fk_user = ".((int) $user->id).
' OR te.fk_soc IS NULL)';
2470 $filtermin = $filter;
2475 if ($errormessage) {
2476 if (!preg_match(
'/^\s*AND/i', $filtermin)) {
2486 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2487 $tmparray = explode(
'@', $this->ismultientitymanaged);
2488 $sql .=
" AND te.".$tmparray[0].
" = ".($tmparray[1] ==
"societe" ?
"s" :
"parenttable").
".rowid";
2489 } elseif ($restrictiononfksoc == 1 && $this->element !=
'societe' && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2490 $sql .=
' AND te.fk_soc = s.rowid';
2492 if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
2493 if ($this->element ==
'user' &&
getDolGlobalInt(
'MULTICOMPANY_TRANSVERSE_MODE')) {
2494 if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
2495 $sql .=
" AND te.entity IS NOT NULL";
2497 $sql .=
" AND te.rowid IN (SELECT ug.fk_user FROM ".$this->db->prefix().
"usergroup_user as ug WHERE ug.entity IN (".
getEntity(
'usergroup').
"))";
2500 $sql .=
' AND te.entity IN ('.getEntity($this->element).
')';
2503 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged) && $this->element !=
'societe') {
2504 $tmparray = explode(
'@', $this->ismultientitymanaged);
2505 $sql .=
' AND parenttable.entity IN ('.getEntity($tmparray[1]).
')';
2507 if ($restrictiononfksoc == 1 && $socid && $this->element !=
'societe') {
2508 $sql .=
' AND te.fk_soc = '.((int) $socid);
2510 if ($restrictiononfksoc == 2 && $socid && $this->element !=
'societe') {
2511 $sql .=
' AND (te.fk_soc = '.((int) $socid).
' OR te.fk_soc IS NULL)';
2513 if ($restrictiononfksoc && $socid && $this->element ==
'societe') {
2514 $sql .=
' AND te.rowid = '.((int) $socid);
2519 $result = $this->db->query($sql);
2521 $this->error = $this->db->lasterror();
2524 $row = $this->db->fetch_row($result);
2525 $this->ref_next = $row[0];
2540 $contactAlreadySelected = array();
2545 if ($source ==
'thirdparty') {
2546 $contactAlreadySelected[$i] = $tab[$i][
'socid'];
2548 $contactAlreadySelected[$i] = $tab[$i][
'id'];
2552 return $contactAlreadySelected;
2568 if (!$this->table_element) {
2569 dol_syslog(get_class($this).
"::setProject was called on object with property table_element not defined", LOG_ERR);
2573 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
2575 if (!empty($this->fields[
'fk_project'])) {
2577 $sql .=
" SET fk_project = ".((int) $projectid);
2579 $sql .=
" SET fk_project = NULL";
2581 $sql .=
' WHERE rowid = '.((int) $this->
id);
2582 } elseif ($this->table_element ==
'actioncomm') {
2584 $sql .=
" SET fk_project = ".((int) $projectid);
2586 $sql .=
" SET fk_project = NULL";
2588 $sql .=
' WHERE id = '.((int) $this->
id);
2591 $sql .=
' SET fk_projet = '.((int) $projectid);
2593 $sql .=
' SET fk_projet = NULL';
2595 $sql .=
" WHERE rowid = ".((int) $this->
id);
2600 dol_syslog(get_class($this).
"::setProject", LOG_DEBUG);
2601 if ($this->db->query($sql)) {
2602 $this->fk_project = ((int) $projectid);
2609 if (!$error && !$notrigger) {
2611 $result = $this->
call_trigger(strtoupper($this->element) .
'_MODIFY', $user);
2620 $this->db->rollback();
2623 $this->db->commit();
2641 dol_syslog(get_class($this).
'::setPaymentMethods('.$id.
')');
2643 if ($this->
status >= 0 || $this->element ==
'societe') {
2645 $fieldname =
'fk_mode_reglement';
2646 if ($this->element ==
'societe') {
2647 $fieldname =
'mode_reglement';
2649 if (get_class($this) ==
'Fournisseur') {
2650 $fieldname =
'mode_reglement_supplier';
2652 if (get_class($this) ==
'Tva') {
2653 $fieldname =
'fk_typepayment';
2655 if (get_class($this) ==
'Salary') {
2656 $fieldname =
'fk_typepayment';
2659 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
2660 $sql .=
" SET ".$fieldname.
" = ".(($id > 0 || $id ==
'0') ? ((
int) $id) :
'NULL');
2661 $sql .=
' WHERE rowid='.((int) $this->
id);
2663 if ($this->db->query($sql)) {
2664 $this->mode_reglement_id = $id;
2666 if (get_class($this) ==
'Fournisseur') {
2667 $this->mode_reglement_supplier_id = $id;
2670 if (!$error && !$notrigger) {
2672 if (get_class($this) ==
'Commande') {
2675 $result = $this->
call_trigger(strtoupper(get_class($this)).
'_MODIFY', $user);
2684 dol_syslog(get_class($this).
'::setPaymentMethods Error '.$this->db->error());
2685 $this->error = $this->db->error();
2689 dol_syslog(get_class($this).
'::setPaymentMethods, status of the object is incompatible');
2690 $this->error =
'Status of the object is incompatible '.$this->status;
2703 dol_syslog(get_class($this).
'::setMulticurrencyCode('.$code.
')');
2704 if ($this->
status >= 0 || $this->element ==
'societe') {
2705 $fieldname =
'multicurrency_code';
2707 $sql =
'UPDATE '.$this->db->prefix().$this->table_element;
2708 $sql .=
" SET ".$fieldname.
" = '".$this->db->escape($code).
"'";
2709 $sql .=
' WHERE rowid='.((int) $this->
id);
2711 if ($this->db->query($sql)) {
2712 $this->multicurrency_code = $code;
2716 $this->setMulticurrencyRate($rate, 2);
2721 dol_syslog(get_class($this).
'::setMulticurrencyCode Error '.$sql.
' - '.$this->db->error());
2722 $this->error = $this->db->error();
2726 dol_syslog(get_class($this).
'::setMulticurrencyCode, status of the object is incompatible');
2727 $this->error =
'Status of the object is incompatible '.$this->status;
2739 public function setMulticurrencyRate($rate, $mode = 1)
2741 dol_syslog(get_class($this).
'::setMulticurrencyRate('.$rate.
', '.$mode.
')');
2742 if ($this->
status >= 0 || $this->element ==
'societe') {
2743 $fieldname =
'multicurrency_tx';
2745 $sql =
'UPDATE '.$this->db->prefix().$this->table_element;
2746 $sql .=
" SET ".$fieldname.
" = ".((float) $rate);
2747 $sql .=
' WHERE rowid='.((int) $this->
id);
2749 if ($this->db->query($sql)) {
2750 $this->multicurrency_tx = $rate;
2753 if (!empty($this->lines)) {
2754 foreach ($this->lines as &$line) {
2757 $line->subprice = 0;
2762 $line->multicurrency_subprice = 0;
2765 switch ($this->element) {
2769 '@phan-var-force Propal $this';
2770 '@phan-var-force PropaleLigne $line';
2775 $line->remise_percent,
2777 $line->localtax1_tx,
2778 $line->localtax2_tx,
2779 ($line->description ? $line->description : $line->desc),
2782 $line->special_code,
2783 $line->fk_parent_line,
2784 $line->skip_update_total,
2785 $line->fk_fournprice,
2788 $line->product_type,
2791 $line->array_options,
2793 $line->multicurrency_subprice
2799 '@phan-var-force Commande $this';
2800 '@phan-var-force OrderLine $line';
2803 ($line->description ? $line->description : $line->desc),
2806 $line->remise_percent,
2808 $line->localtax1_tx,
2809 $line->localtax2_tx,
2814 $line->product_type,
2815 $line->fk_parent_line,
2816 $line->skip_update_total,
2817 $line->fk_fournprice,
2820 $line->special_code,
2821 $line->array_options,
2823 $line->multicurrency_subprice
2829 '@phan-var-force Facture $this';
2830 '@phan-var-force FactureLigne $line';
2833 ($line->description ? $line->description : $line->desc),
2836 $line->remise_percent,
2840 $line->localtax1_tx,
2841 $line->localtax2_tx,
2844 $line->product_type,
2845 $line->fk_parent_line,
2846 $line->skip_update_total,
2847 $line->fk_fournprice,
2850 $line->special_code,
2851 $line->array_options,
2852 $line->situation_percent,
2854 $line->multicurrency_subprice
2857 case 'supplier_proposal':
2860 '@phan-var-force SupplierProposal $this';
2861 '@phan-var-force SupplierProposalLine $line';
2866 $line->remise_percent,
2868 $line->localtax1_tx,
2869 $line->localtax2_tx,
2870 ($line->description ? $line->description : $line->desc),
2873 $line->special_code,
2874 $line->fk_parent_line,
2875 $line->skip_update_total,
2876 $line->fk_fournprice,
2879 $line->product_type,
2880 $line->array_options,
2882 $line->multicurrency_subprice
2885 case 'order_supplier':
2888 '@phan-var-force CommandeFournisseur $this';
2889 '@phan-var-force CommandeFournisseurLigne $line';
2892 ($line->description ? $line->description : $line->desc),
2895 $line->remise_percent,
2897 $line->localtax1_tx,
2898 $line->localtax2_tx,
2901 $line->product_type,
2905 $line->array_options,
2907 $line->multicurrency_subprice,
2911 case 'invoice_supplier':
2914 '@phan-var-force FactureFournisseur $this';
2915 '@phan-var-force SupplierInvoiceLIne $line';
2918 ($line->description ? $line->description : $line->desc),
2921 $line->localtax1_tx,
2922 $line->localtax2_tx,
2927 $line->product_type,
2928 $line->remise_percent,
2932 $line->array_options,
2934 $line->multicurrency_subprice,
2939 dol_syslog(get_class($this).
'::setMulticurrencyRate no updateline defined', LOG_DEBUG);
2947 dol_syslog(get_class($this).
'::setMulticurrencyRate Error '.$sql.
' - '.$this->db->error());
2948 $this->error = $this->db->error();
2952 dol_syslog(get_class($this).
'::setMulticurrencyRate, status of the object is incompatible');
2953 $this->error =
'Status of the object is incompatible '.$this->status;
2967 dol_syslog(get_class($this).
'::setPaymentTerms('.$id.
', '.var_export($deposit_percent,
true).
')');
2968 if ($this->
status >= 0 || $this->element ==
'societe') {
2970 $fieldname =
'fk_cond_reglement';
2971 if ($this->element ==
'societe') {
2972 $fieldname =
'cond_reglement';
2974 if (get_class($this) ==
'Fournisseur') {
2975 $fieldname =
'cond_reglement_supplier';
2978 if (empty($deposit_percent) || $deposit_percent < 0) {
2979 $deposit_percent = (float)
getDictionaryValue(
'c_payment_term',
'deposit_percent', $id);
2982 if ($deposit_percent > 100) {
2983 $deposit_percent = 100;
2986 $sql =
'UPDATE '.$this->db->prefix().$this->table_element;
2987 $sql .=
" SET ".$fieldname.
" = ".(($id > 0 || $id ==
'0') ? ((
int) $id) :
'NULL');
2988 if (in_array($this->table_element, array(
'propal',
'commande',
'societe'))) {
2989 $sql .=
" , deposit_percent = " . (empty($deposit_percent) ?
'NULL' :
"'".$this->db->escape($deposit_percent).
"'");
2991 $sql .=
' WHERE rowid='.((int) $this->
id);
2993 if ($this->db->query($sql)) {
2994 $this->cond_reglement_id = $id;
2996 if (get_class($this) ==
'Fournisseur') {
2997 $this->cond_reglement_supplier_id = $id;
2999 $this->cond_reglement = $id;
3000 $this->deposit_percent = $deposit_percent;
3003 dol_syslog(get_class($this).
'::setPaymentTerms Error '.$sql.
' - '.$this->db->error());
3004 $this->error = $this->db->error();
3008 dol_syslog(get_class($this).
'::setPaymentTerms, status of the object is incompatible');
3009 $this->error =
'Status of the object is incompatible '.$this->status;
3022 dol_syslog(get_class($this).
'::setTransportMode('.$id.
')');
3023 if ($this->
status >= 0 || $this->element ==
'societe') {
3024 $fieldname =
'fk_transport_mode';
3025 if ($this->element ==
'societe') {
3026 $fieldname =
'transport_mode';
3028 if (get_class($this) ==
'Fournisseur') {
3029 $fieldname =
'transport_mode_supplier';
3032 $sql =
'UPDATE '.$this->db->prefix().$this->table_element;
3033 $sql .=
" SET ".$fieldname.
" = ".(($id > 0 || $id ==
'0') ? ((
int) $id) :
'NULL');
3034 $sql .=
' WHERE rowid='.((int) $this->
id);
3036 if ($this->db->query($sql)) {
3037 $this->transport_mode_id = $id;
3039 if (get_class($this) ==
'Fournisseur') {
3040 $this->transport_mode_supplier_id = $id;
3044 dol_syslog(get_class($this).
'::setTransportMode Error '.$sql.
' - '.$this->db->error());
3045 $this->error = $this->db->error();
3049 dol_syslog(get_class($this).
'::setTransportMode, status of the object is incompatible');
3050 $this->error =
'Status of the object is incompatible '.$this->status;
3063 dol_syslog(get_class($this).
'::setRetainedWarrantyPaymentTerms('.$id.
')');
3064 if ($this->
status >= 0 || $this->element ==
'societe') {
3065 $fieldname =
'retained_warranty_fk_cond_reglement';
3067 $sql =
'UPDATE '.$this->db->prefix().$this->table_element;
3068 $sql .=
" SET ".$fieldname.
" = ".((int) $id);
3069 $sql .=
' WHERE rowid='.((int) $this->
id);
3071 if ($this->db->query($sql)) {
3072 $this->retained_warranty_fk_cond_reglement = $id;
3075 dol_syslog(get_class($this).
'::setRetainedWarrantyPaymentTerms Error '.$sql.
' - '.$this->db->error());
3076 $this->error = $this->db->error();
3080 dol_syslog(get_class($this).
'::setRetainedWarrantyPaymentTerms, status of the object is incompatible');
3081 $this->error =
'Status of the object is incompatible '.$this->status;
3095 $fieldname =
'fk_delivery_address';
3096 if ($this->element ==
'delivery' || $this->element ==
'shipping') {
3097 $fieldname =
'fk_address';
3100 $sql =
"UPDATE ".$this->db->prefix().$this->table_element.
" SET ".$fieldname.
" = ".((int) $id);
3101 $sql .=
" WHERE rowid = ".((int) $this->
id).
" AND fk_statut = 0";
3103 if ($this->db->query($sql)) {
3104 $this->fk_delivery_address = $id;
3107 $this->error = $this->db->error();
3108 dol_syslog(get_class($this).
'::setDeliveryAddress Error '.$this->error);
3126 if (empty($userused)) {
3132 if (!$this->table_element) {
3133 dol_syslog(get_class($this).
"::setShippingMethod was called on object with property table_element not defined", LOG_ERR);
3139 if ($shipping_method_id < 0) {
3140 $shipping_method_id =
'NULL';
3142 dol_syslog(get_class($this).
'::setShippingMethod('.$shipping_method_id.
')');
3144 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
3145 $sql .=
" SET fk_shipping_method = ".((int) $shipping_method_id);
3146 $sql .=
" WHERE rowid=".((int) $this->
id);
3147 $resql = $this->db->query($sql);
3149 dol_syslog(get_class($this).
'::setShippingMethod Error ', LOG_DEBUG);
3150 $this->error = $this->db->lasterror();
3155 $this->context = array(
'shippingmethodupdate' => 1);
3156 $result = $this->
call_trigger(strtoupper(get_class($this)).
'_MODIFY', $userused);
3164 $this->db->rollback();
3167 $this->shipping_method_id = ($shipping_method_id ==
'NULL') ?
null : $shipping_method_id;
3168 $this->db->commit();
3182 if (!$this->table_element) {
3183 dol_syslog(get_class($this).
"::setWarehouse was called on object with property table_element not defined", LOG_ERR);
3186 if ($warehouse_id < 0) {
3187 $warehouse_id =
'NULL';
3189 dol_syslog(get_class($this).
'::setWarehouse('.$warehouse_id.
')');
3191 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
3192 $sql .=
" SET fk_warehouse = ".((int) $warehouse_id);
3193 $sql .=
" WHERE rowid=".((int) $this->
id);
3195 if ($this->db->query($sql)) {
3196 $this->warehouse_id = ($warehouse_id ==
'NULL') ?
null : $warehouse_id;
3199 dol_syslog(get_class($this).
'::setWarehouse Error ', LOG_DEBUG);
3200 $this->error = $this->db->error();
3215 if (!$this->table_element) {
3216 dol_syslog(get_class($this).
"::setDocModel was called on object with property table_element not defined", LOG_ERR);
3220 $newmodelpdf =
dol_trunc($modelpdf, 255);
3222 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
3223 $sql .=
" SET model_pdf = '".$this->db->escape($newmodelpdf).
"'";
3224 $sql .=
" WHERE rowid = ".((int) $this->
id);
3226 dol_syslog(get_class($this).
"::setDocModel", LOG_DEBUG);
3227 $resql = $this->db->query($sql);
3229 $this->model_pdf = $modelpdf;
3250 if (empty($userused)) {
3256 if (!$this->table_element) {
3257 dol_syslog(get_class($this).
"::setBankAccount was called on object with property table_element not defined", LOG_ERR);
3262 if ($fk_account < 0) {
3263 $fk_account =
'NULL';
3265 dol_syslog(get_class($this).
'::setBankAccount('.$fk_account.
')');
3267 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
3268 $sql .=
" SET fk_account = ".((int) $fk_account);
3269 $sql .=
" WHERE rowid=".((int) $this->
id);
3271 $resql = $this->db->query($sql);
3273 dol_syslog(get_class($this).
'::setBankAccount Error '.$sql.
' - '.$this->db->error());
3274 $this->error = $this->db->lasterror();
3279 $this->context[
'bankaccountupdate'] = 1;
3280 $triggerName = strtoupper(get_class($this)).
'_MODIFY';
3282 if ($triggerName ==
'FACTUREREC_MODIFY') {
3283 $triggerName =
'BILLREC_MODIFY';
3285 $result = $this->
call_trigger($triggerName, $userused);
3293 $this->db->rollback();
3296 $this->fk_account = ($fk_account ==
'NULL') ?
null : $fk_account;
3297 $this->db->commit();
3315 public function line_order($renum =
false, $rowidorder =
'ASC', $fk_parent_line =
true)
3318 if (!$this->table_element_line) {
3319 dol_syslog(get_class($this).
"::line_order was called on object with property table_element_line not defined", LOG_ERR);
3322 if (!$this->fk_element) {
3323 dol_syslog(get_class($this).
"::line_order was called on object with property fk_element not defined", LOG_ERR);
3327 $fieldposition =
'rang';
3328 if (in_array($this->table_element_line, array(
'bom_bomline',
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3329 $fieldposition =
'position';
3334 $sql =
"SELECT count(rowid) FROM ".$this->db->prefix().$this->table_element_line;
3335 $sql .=
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
3337 $sql .=
" AND " . $fieldposition .
" = 0";
3340 $sql .=
" AND " . $fieldposition .
" <> 0";
3343 dol_syslog(get_class($this).
"::line_order", LOG_DEBUG);
3344 $resql = $this->db->query($sql);
3346 $row = $this->db->fetch_row($resql);
3356 $sql =
"SELECT rowid FROM ".$this->db->prefix().$this->table_element_line;
3357 $sql .=
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
3358 if ($fk_parent_line) {
3359 $sql .=
' AND fk_parent_line IS NULL';
3361 $sql .=
" ORDER BY " . $fieldposition .
" ASC, rowid " . $rowidorder;
3363 dol_syslog(get_class($this).
"::line_order search all parent lines", LOG_DEBUG);
3364 $resql = $this->db->query($sql);
3367 $num = $this->db->num_rows($resql);
3370 $row = $this->db->fetch_row($resql);
3373 if (!empty($children)) {
3374 foreach ($children as $child) {
3375 array_push($rows, $child);
3382 if (!empty($rows)) {
3383 foreach ($rows as $key => $row) {
3403 $fieldposition =
'rang';
3404 if (in_array($this->table_element_line, array(
'bom_bomline',
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3405 $fieldposition =
'position';
3410 $sql =
"SELECT rowid FROM ".$this->db->prefix().$this->table_element_line;
3411 $sql .=
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
3412 $sql .=
' AND fk_parent_line = '.((int) $id);
3413 $sql .=
" ORDER BY " . $fieldposition .
" ASC";
3415 dol_syslog(get_class($this).
"::getChildrenOfLine search children lines for line ".$id, LOG_DEBUG);
3417 $resql = $this->db->query($sql);
3419 if ($this->db->num_rows($resql) > 0) {
3420 while ($row = $this->db->fetch_row($resql)) {
3422 if (!empty($includealltree) && $includealltree <= 1000) {
3423 $rows = array_merge($rows, $this->
getChildrenOfLine($row[0], $includealltree + 1));
3439 public function line_up($rowid, $fk_parent_line =
true)
3442 $this->
line_order(
false,
'ASC', $fk_parent_line);
3462 $this->
line_order(
false,
'ASC', $fk_parent_line);
3483 global $hookmanager;
3484 $fieldposition =
'rang';
3485 if (in_array($this->table_element_line, array(
'bom_bomline',
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3486 $fieldposition =
'position';
3489 $sql =
"UPDATE ".$this->db->prefix().$this->table_element_line.
" SET ".$fieldposition.
" = ".((int) $rang);
3490 $sql .=
' WHERE rowid = '.((int) $rowid);
3492 dol_syslog(get_class($this).
"::updateRangOfLine", LOG_DEBUG);
3493 if (!$this->db->query($sql)) {
3497 $parameters = array(
'rowid' => $rowid,
'rang' => $rang,
'fieldposition' => $fieldposition);
3499 $reshook = $hookmanager->executeHooks(
'afterRankOfLineUpdate', $parameters, $this, $action);
3514 $num = count($rows);
3515 for ($i = 0; $i < $num; $i++) {
3530 $fieldposition =
'rang';
3531 if (in_array($this->table_element_line, array(
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3532 $fieldposition =
'position';
3535 $sql =
"UPDATE ".$this->db->prefix().$this->table_element_line.
" SET ".$fieldposition.
" = ".((int) $rang);
3536 $sql .=
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
3537 $sql .=
" AND " . $fieldposition .
" = " . ((int) ($rang - 1));
3538 if ($this->db->query($sql)) {
3539 $sql =
"UPDATE ".$this->db->prefix().$this->table_element_line.
" SET ".$fieldposition.
" = ".((int) ($rang - 1));
3540 $sql .=
' WHERE rowid = '.((int) $rowid);
3541 if (!$this->db->query($sql)) {
3561 $fieldposition =
'rang';
3562 if (in_array($this->table_element_line, array(
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3563 $fieldposition =
'position';
3566 $sql =
"UPDATE ".$this->db->prefix().$this->table_element_line.
" SET ".$fieldposition.
" = ".((int) $rang);
3567 $sql .=
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
3568 $sql .=
" AND " . $fieldposition .
" = " . ((int) ($rang + 1));
3569 if ($this->db->query($sql)) {
3570 $sql =
"UPDATE ".$this->db->prefix().$this->table_element_line.
" SET ".$fieldposition.
" = ".((int) ($rang + 1));
3571 $sql .=
' WHERE rowid = '.((int) $rowid);
3572 if (!$this->db->query($sql)) {
3589 $fieldposition =
'rang';
3590 if (in_array($this->table_element_line, array(
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3591 $fieldposition =
'position';
3594 $sql =
"SELECT " . $fieldposition .
" FROM ".$this->db->prefix().$this->table_element_line;
3595 $sql .=
" WHERE rowid = ".((int) $rowid);
3597 dol_syslog(get_class($this).
"::getRangOfLine", LOG_DEBUG);
3598 $resql = $this->db->query($sql);
3600 $row = $this->db->fetch_row($resql);
3615 $fieldposition =
'rang';
3616 if (in_array($this->table_element_line, array(
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3617 $fieldposition =
'position';
3620 $sql =
"SELECT rowid FROM ".$this->db->prefix().$this->table_element_line;
3621 $sql .=
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
3622 $sql .=
" AND " . $fieldposition .
" = ".((int) $rang);
3623 $resql = $this->db->query($sql);
3625 $row = $this->db->fetch_row($resql);
3642 $positionfield =
'rang';
3643 if (in_array($this->table_element, array(
'bom_bom',
'product_attribute'))) {
3644 $positionfield =
'position';
3648 if ($fk_parent_line) {
3649 $sql =
"SELECT max(".$positionfield.
") FROM ".$this->db->prefix().$this->table_element_line;
3650 $sql .=
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
3651 $sql .=
" AND fk_parent_line = ".((int) $fk_parent_line);
3653 dol_syslog(get_class($this).
"::line_max", LOG_DEBUG);
3654 $resql = $this->db->query($sql);
3656 $row = $this->db->fetch_row($resql);
3657 if (!empty($row[0])) {
3665 $sql =
"SELECT max(".$positionfield.
") FROM ".$this->db->prefix().$this->table_element_line;
3666 $sql .=
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
3668 dol_syslog(get_class($this).
"::line_max", LOG_DEBUG);
3669 $resql = $this->db->query($sql);
3671 $row = $this->db->fetch_row($resql);
3689 if (!$this->table_element) {
3690 dol_syslog(get_class($this).
"::update_ref_ext was called on object with property table_element not defined", LOG_ERR);
3694 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
3695 $sql .=
" SET ref_ext = '".$this->db->escape($ref_ext).
"'";
3697 $sql .=
" WHERE ".(isset($this->table_rowid) ? $this->table_rowid :
'rowid').
" = ".((
int) $this->id);
3699 dol_syslog(get_class($this).
"::update_ref_ext", LOG_DEBUG);
3700 if ($this->db->query($sql)) {
3701 $this->ref_ext = $ref_ext;
3704 $this->error = $this->db->error();
3723 if (!$this->table_element) {
3724 $this->error =
'update_note was called on object with property table_element not defined';
3725 dol_syslog(get_class($this).
"::update_note was called on object with property table_element not defined", LOG_ERR);
3728 if (!in_array($suffix, array(
'',
'_public',
'_private'))) {
3729 $this->error =
'update_note Parameter suffix must be empty, \'_private\' or \'_public\'';
3730 dol_syslog(get_class($this).
"::update_note Parameter suffix must be empty, '_private' or '_public'", LOG_ERR);
3734 $newsuffix = $suffix;
3737 if ($this->table_element ==
'product' && $newsuffix ==
'_private') {
3740 if (in_array($this->table_element, array(
'actioncomm',
'adherent',
'advtargetemailing',
'cronjob',
'establishment'))) {
3741 $fieldusermod =
"fk_user_mod";
3742 } elseif ($this->table_element ==
'ecm_files') {
3743 $fieldusermod =
"fk_user_m";
3745 $fieldusermod =
"fk_user_modif";
3747 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
3748 $sql .=
" SET note".$newsuffix.
" = ".(!empty($note) ? (
"'".$this->db->escape($note).
"'") :
"NULL");
3749 $sql .=
", ".$fieldusermod.
" = ".((int) $user->id);
3750 $sql .=
" WHERE rowid = ".((int) $this->
id);
3752 dol_syslog(get_class($this).
"::update_note", LOG_DEBUG);
3753 if ($this->db->query($sql)) {
3754 if ($suffix ==
'_public') {
3755 $this->note_public = $note;
3756 } elseif ($suffix ==
'_private') {
3757 $this->note_private = $note;
3759 $this->note = $note;
3760 $this->note_private = $note;
3762 if (empty($notrigger)) {
3763 switch ($this->element) {
3765 $trigger_name =
'COMPANY_MODIFY';
3768 $trigger_name =
'ORDER_MODIFY';
3771 $trigger_name =
'BILL_MODIFY';
3773 case 'invoice_supplier':
3774 $trigger_name =
'BILL_SUPPLIER_MODIFY';
3777 $trigger_name =
'BILLREC_MODIFIY';
3779 case 'expensereport':
3780 $trigger_name =
'EXPENSE_REPORT_MODIFY';
3783 $trigger_name = strtoupper($this->element) .
'_MODIFY';
3792 $this->error = $this->db->lasterror();
3823 public function update_price($exclspec = 0, $roundingadjust =
'auto', $nodatabaseupdate = 0, $seller =
null)
3826 global $conf, $hookmanager, $action;
3828 $parameters = array(
'exclspec' => $exclspec,
'roundingadjust' => $roundingadjust,
'nodatabaseupdate' => $nodatabaseupdate,
'seller' => $seller);
3829 $reshook = $hookmanager->executeHooks(
'updateTotalPrice', $parameters, $this, $action);
3832 } elseif ($reshook < 0) {
3837 $isElementForSupplier =
false;
3838 $roundTotalConstName =
'MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND';
3840 if ($this->element ==
'propal') {
3841 $MODULE =
"MODULE_DISALLOW_UPDATE_PRICE_PROPOSAL";
3842 } elseif ($this->element ==
'commande' || $this->element ==
'order') {
3843 $MODULE =
"MODULE_DISALLOW_UPDATE_PRICE_ORDER";
3844 } elseif ($this->element ==
'facture' || $this->element ==
'invoice') {
3845 $MODULE =
"MODULE_DISALLOW_UPDATE_PRICE_INVOICE";
3846 } elseif ($this->element ==
'facture_fourn' || $this->element ==
'supplier_invoice' || $this->element ==
'invoice_supplier' || $this->element ==
'invoice_supplier_rec') {
3847 $isElementForSupplier =
true;
3848 $MODULE =
"MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_INVOICE";
3849 } elseif ($this->element ==
'order_supplier' || $this->element ==
'supplier_order') {
3850 $isElementForSupplier =
true;
3851 $MODULE =
"MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_ORDER";
3852 } elseif ($this->element ==
'supplier_proposal') {
3853 $isElementForSupplier =
true;
3854 $MODULE =
"MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_PROPOSAL";
3856 if ($isElementForSupplier) {
3857 $roundTotalConstName =
'MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND_SUPPLIER';
3860 if (!empty($MODULE)) {
3863 foreach ($modsactivated as $mod) {
3864 if (isModEnabled($mod)) {
3871 include_once DOL_DOCUMENT_ROOT.
'/core/lib/price.lib.php';
3873 $forcedroundingmode = $roundingadjust;
3874 if ($forcedroundingmode ==
'auto' && isset($conf->global->{$roundTotalConstName})) {
3876 } elseif ($forcedroundingmode ==
'auto') {
3877 $forcedroundingmode =
'0';
3882 $multicurrency_tx = !empty($this->multicurrency_tx) ? $this->multicurrency_tx : 1;
3885 $fieldtva =
'total_tva';
3886 $fieldlocaltax1 =
'total_localtax1';
3887 $fieldlocaltax2 =
'total_localtax2';
3888 $fieldup =
'subprice';
3889 $base_price_type =
'HT';
3890 if ($this->element ==
'facture_fourn' || $this->element ==
'invoice_supplier') {
3894 if ($this->element ==
'invoice_supplier_rec') {
3897 if ($this->element ==
'expensereport') {
3901 $forcedroundingmode =
'0';
3902 $fieldup =
'value_unit';
3903 $base_price_type =
'TTC';
3906 $sql =
"SELECT rowid, qty, ".$fieldup.
" as up, remise_percent, total_ht, ".$fieldtva.
" as total_tva, total_ttc, ".$fieldlocaltax1.
" as total_localtax1, ".$fieldlocaltax2.
" as total_localtax2,";
3907 $sql .=
' tva_tx as vatrate, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type, info_bits, product_type';
3908 if ($this->table_element_line ==
'facturedet') {
3909 $sql .=
', situation_percent';
3911 $sql .=
', multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc';
3912 $sql .=
" FROM ".$this->db->prefix().$this->table_element_line;
3913 $sql .=
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
3915 $product_field =
'product_type';
3916 if ($this->table_element_line ==
'contratdet') {
3917 $product_field =
'';
3919 if ($product_field) {
3920 $sql .=
" AND ".$product_field.
" <> 9";
3923 $sql .=
' ORDER by rowid';
3925 dol_syslog(get_class($this).
"::update_price", LOG_DEBUG);
3927 $resql = $this->db->query($sql);
3929 $this->total_ht = 0;
3930 $this->total_tva = 0;
3931 $this->total_localtax1 = 0;
3932 $this->total_localtax2 = 0;
3933 $this->total_ttc = 0;
3934 $total_ht_by_vats = array();
3935 $total_tva_by_vats = array();
3936 $total_ttc_by_vats = array();
3937 $this->multicurrency_total_ht = 0;
3938 $this->multicurrency_total_tva = 0;
3939 $this->multicurrency_total_ttc = 0;
3943 $num = $this->db->num_rows($resql);
3946 $obj = $this->db->fetch_object($resql);
3949 $parameters = array(
'fk_element' => $obj->rowid);
3950 $reshook = $hookmanager->executeHooks(
'changeRoundingMode', $parameters, $this, $action);
3952 if (empty($reshook) && $forcedroundingmode ==
'0') {
3954 $localtax_array = array($obj->localtax1_type, $obj->localtax1_tx, $obj->localtax2_type, $obj->localtax2_tx);
3955 $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);
3957 $diff_when_using_price_ht =
price2num($tmpcal[1] - $obj->total_tva,
'MT', 1);
3958 $diff_on_current_total =
price2num($obj->total_ttc - $obj->total_ht - $obj->total_tva - $obj->total_localtax1 - $obj->total_localtax2,
'MT', 1);
3962 if ($diff_on_current_total) {
3964 $sqlfix =
"UPDATE ".$this->db->prefix().$this->table_element_line.
" SET ".$fieldtva.
" = ".
price2num((
float) $tmpcal[1]).
", total_ttc = ".
price2num((
float) $tmpcal[2]).
" WHERE rowid = ".((int) $obj->rowid);
3965 dol_syslog(
'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);
3966 $resqlfix = $this->db->query($sqlfix);
3970 $obj->total_tva = $tmpcal[1];
3971 $obj->total_ttc = $tmpcal[2];
3972 } elseif ($diff_when_using_price_ht) {
3975 $sqlfix =
"UPDATE ".$this->db->prefix().$this->table_element_line.
" SET ".$fieldtva.
" = ".
price2num((
float) $tmpcal[1]).
", total_ttc = ".
price2num((
float) $tmpcal[2]).
" WHERE rowid = ".((int) $obj->rowid);
3976 dol_syslog(
'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);
3977 $resqlfix = $this->db->query($sqlfix);
3981 $obj->total_tva = $tmpcal[1];
3982 $obj->total_ttc = $tmpcal[2];
3986 $this->total_ht += $obj->total_ht;
3987 $this->total_tva += $obj->total_tva;
3988 $this->total_localtax1 += $obj->total_localtax1;
3989 $this->total_localtax2 += $obj->total_localtax2;
3990 $this->total_ttc += $obj->total_ttc;
3991 $this->multicurrency_total_ht += $obj->multicurrency_total_ht;
3992 $this->multicurrency_total_tva += $obj->multicurrency_total_tva;
3993 $this->multicurrency_total_ttc += $obj->multicurrency_total_ttc;
3995 if (!isset($total_ht_by_vats[$obj->vatrate])) {
3996 $total_ht_by_vats[$obj->vatrate] = 0;
3998 if (!isset($total_tva_by_vats[$obj->vatrate])) {
3999 $total_tva_by_vats[$obj->vatrate] = 0;
4001 if (!isset($total_ttc_by_vats[$obj->vatrate])) {
4002 $total_ttc_by_vats[$obj->vatrate] = 0;
4004 $total_ht_by_vats[$obj->vatrate] += $obj->total_ht;
4005 $total_tva_by_vats[$obj->vatrate] += $obj->total_tva;
4006 $total_ttc_by_vats[$obj->vatrate] += $obj->total_ttc;
4008 if ($forcedroundingmode ==
'1') {
4009 if ($base_price_type ==
'TTC') {
4010 $tmpvat =
price2num($total_ttc_by_vats[$obj->vatrate] * $obj->vatrate / (100 + $obj->vatrate),
'MT', 1);
4012 $tmpvat =
price2num($total_ht_by_vats[$obj->vatrate] * $obj->vatrate / 100,
'MT', 1);
4014 $diff =
price2num($total_tva_by_vats[$obj->vatrate] - (
float) $tmpvat,
'MT', 1);
4017 $maxdiff = (10 * pow(10, -1 *
getDolGlobalInt(
'MAIN_MAX_DECIMALS_TOT', 0)));
4018 if (abs((
float) $diff) > $maxdiff) {
4020 $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.';
4022 $this->error = $errmsg;
4027 if ($base_price_type ==
'TTC') {
4028 $sqlfix =
"UPDATE ".$this->db->prefix().$this->table_element_line.
" SET ".$fieldtva.
" = ".
price2num($obj->total_tva - (
float) $diff).
", total_ht = ".
price2num($obj->total_ht + (
float) $diff).
" WHERE rowid = ".((int) $obj->rowid);
4029 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);
4031 $sqlfix =
"UPDATE ".$this->db->prefix().$this->table_element_line.
" SET ".$fieldtva.
" = ".
price2num($obj->total_tva - (
float) $diff).
", total_ttc = ".
price2num($obj->total_ttc - (
float) $diff).
" WHERE rowid = ".((int) $obj->rowid);
4032 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);
4035 $resqlfix = $this->db->query($sqlfix);
4041 $this->total_tva = (float)
price2num($this->total_tva - (
float) $diff,
'', 1);
4042 $total_tva_by_vats[$obj->vatrate] = (float)
price2num($total_tva_by_vats[$obj->vatrate] - (
float) $diff,
'', 1);
4043 if ($base_price_type ==
'TTC') {
4044 $this->total_ht = (float)
price2num($this->total_ht + (
float) $diff,
'', 1);
4045 $total_ht_by_vats[$obj->vatrate] = (float)
price2num($total_ht_by_vats[$obj->vatrate] + (
float) $diff,
'', 1);
4047 $this->total_ttc = (float)
price2num($this->total_ttc - (
float) $diff,
'', 1);
4048 $total_ttc_by_vats[$obj->vatrate] = (float)
price2num($total_ttc_by_vats[$obj->vatrate] - (
float) $diff,
'', 1);
4058 $this->total_ttc += isset($this->revenuestamp) ? $this->revenuestamp : 0;
4060 $this->multicurrency_total_ttc += isset($this->revenuestamp) ? ($this->revenuestamp * $multicurrency_tx) : 0;
4063 if (!empty($this->situation_cycle_ref) && !empty($this->situation_counter) && $this->situation_counter > 1 && method_exists($this,
'get_prev_sits')) {
4064 '@phan-var-force Facture $this';
4065 include_once DOL_DOCUMENT_ROOT.
'/compta/facture/class/facture.class.php';
4068 $prev_sits = $this->get_prev_sits();
4070 foreach ($prev_sits as $sit) {
4071 $this->total_ht -= $sit->total_ht;
4072 $this->total_tva -= $sit->total_tva;
4073 $this->total_localtax1 -= $sit->total_localtax1;
4074 $this->total_localtax2 -= $sit->total_localtax2;
4075 $this->total_ttc -= $sit->total_ttc;
4076 $this->multicurrency_total_ht -= $sit->multicurrency_total_ht;
4077 $this->multicurrency_total_tva -= $sit->multicurrency_total_tva;
4078 $this->multicurrency_total_ttc -= $sit->multicurrency_total_ttc;
4085 $this->total_ht = (float)
price2num($this->total_ht);
4086 $this->total_tva = (float)
price2num($this->total_tva);
4087 $this->total_localtax1 = (float)
price2num($this->total_localtax1);
4088 $this->total_localtax2 = (float)
price2num($this->total_localtax2);
4089 $this->total_ttc = (float)
price2num($this->total_ttc);
4091 $this->db->free($resql);
4094 $fieldht =
'total_ht';
4096 $fieldlocaltax1 =
'localtax1';
4097 $fieldlocaltax2 =
'localtax2';
4098 $fieldttc =
'total_ttc';
4100 if (in_array($this->element, array(
'propal',
'commande',
'facture',
'facturerec',
'supplier_proposal',
'order_supplier',
'facture_fourn',
'invoice_supplier',
'invoice_supplier_rec',
'expensereport'))) {
4101 $fieldtva =
'total_tva';
4104 if (!$error && empty($nodatabaseupdate)) {
4105 $sql =
"UPDATE ".$this->db->prefix().$this->table_element.
' SET';
4106 $sql .=
" ".$this->db->sanitize($fieldht).
" = ".((float)
price2num($this->total_ht,
'MT', 1)).
",";
4107 $sql .=
" ".$this->db->sanitize($fieldtva).
" = ".((float)
price2num($this->total_tva,
'MT', 1)).
",";
4108 $sql .=
" ".$this->db->sanitize($fieldlocaltax1).
" = ".((float)
price2num($this->total_localtax1,
'MT', 1)).
",";
4109 $sql .=
" ".$this->db->sanitize($fieldlocaltax2).
" = ".((float)
price2num($this->total_localtax2,
'MT', 1)).
",";
4110 $sql .=
" ".$this->db->sanitize($fieldttc).
" = ".((float)
price2num($this->total_ttc,
'MT', 1));
4111 $sql .=
", multicurrency_total_ht = ".((float)
price2num($this->multicurrency_total_ht,
'MT', 1));
4112 $sql .=
", multicurrency_total_tva = ".((float)
price2num($this->multicurrency_total_tva,
'MT', 1));
4113 $sql .=
", multicurrency_total_ttc = ".((float)
price2num($this->multicurrency_total_ttc,
'MT', 1));
4114 $sql .=
" WHERE rowid = ".((int) $this->
id);
4116 dol_syslog(get_class($this).
"::update_price", LOG_DEBUG);
4117 $resql = $this->db->query($sql);
4121 $this->error = $this->db->lasterror();
4122 $this->errors[] = $this->db->lasterror();
4127 $this->db->commit();
4130 $this->db->rollback();
4150 public function add_object_linked($origin =
null, $origin_id =
null, $f_user =
null, $notrigger = 0)
4153 global $user, $hookmanager, $action;
4154 $origin = (!empty($origin) ? $origin : $this->origin);
4155 $origin_id = (!empty($origin_id) ? $origin_id : $this->origin_id);
4156 $f_user = isset($f_user) ? $f_user : $user;
4159 if ($origin ==
'order') {
4160 $origin =
'commande';
4162 if ($origin ==
'invoice') {
4163 $origin =
'facture';
4165 if ($origin ==
'invoice_template') {
4166 $origin =
'facturerec';
4168 if ($origin ==
'supplierorder') {
4169 $origin =
'order_supplier';
4173 $targettype = $this->getElementType();
4175 $parameters = array(
'targettype' => $targettype);
4177 $reshook = $hookmanager->executeHooks(
'setLinkedObjectSourceTargetType', $parameters, $this, $action);
4179 if (!empty($hookmanager->resArray[
'targettype'])) {
4180 $targettype = $hookmanager->resArray[
'targettype'];
4187 $sql =
"INSERT INTO " . $this->db->prefix() .
"element_element (";
4188 $sql .=
"fk_source";
4189 $sql .=
", sourcetype";
4190 $sql .=
", fk_target";
4191 $sql .=
", targettype";
4192 $sql .=
") VALUES (";
4193 $sql .= ((int) $origin_id);
4194 $sql .=
", '" . $this->db->escape($origin) .
"'";
4195 $sql .=
", " . ((int) $this->
id);
4196 $sql .=
", '" . $this->db->escape($targettype) .
"'";
4199 dol_syslog(get_class($this) .
"::add_object_linked", LOG_DEBUG);
4200 if ($this->db->query($sql)) {
4203 $this->context[
'link_origin'] = $origin;
4204 $this->context[
'link_origin_id'] = $origin_id;
4205 $result = $this->call_trigger(
'OBJECT_LINK_INSERT', $f_user);
4212 $this->error = $this->db->lasterror();
4217 $this->db->commit();
4220 $this->db->rollback();
4234 $coreModule = array(
'knowledgemanagement',
'partnership',
'workstation',
'ticket',
'recruitment',
'eventorganization',
'asset');
4236 return ((!empty($this->module) && !in_array($this->module, $coreModule)) ? $this->module.
'_' :
'').$this->element;
4262 public function fetchObjectLinked($sourceid =
null, $sourcetype =
'', $targetid =
null, $targettype =
'', $clause =
'OR', $alsosametype = 1, $orderby =
'sourcetype', $loadalsoobjects = 1)
4264 global $conf, $hookmanager, $action;
4269 if ($this->
id > 0 && !empty($this->linkedObjectsFullLoaded[$this->
id])) {
4273 $this->linkedObjectsIds = array();
4274 $this->linkedObjects = array();
4276 $justsource =
false;
4277 $justtarget =
false;
4278 $withtargettype =
false;
4279 $withsourcetype =
false;
4281 $parameters = array(
'sourcetype' => $sourcetype,
'sourceid' => $sourceid,
'targettype' => $targettype,
'targetid' => $targetid);
4283 $reshook = $hookmanager->executeHooks(
'setLinkedObjectSourceTargetType', $parameters, $this, $action);
4285 if (!empty($hookmanager->resArray[
'sourcetype'])) {
4286 $sourcetype = $hookmanager->resArray[
'sourcetype'];
4288 if (!empty($hookmanager->resArray[
'sourceid'])) {
4289 $sourceid = $hookmanager->resArray[
'sourceid'];
4291 if (!empty($hookmanager->resArray[
'targettype'])) {
4292 $targettype = $hookmanager->resArray[
'targettype'];
4294 if (!empty($hookmanager->resArray[
'targetid'])) {
4295 $targetid = $hookmanager->resArray[
'targetid'];
4299 if (!empty($sourceid) && !empty($sourcetype) && empty($targetid)) {
4301 if (!empty($targettype)) {
4302 $withtargettype =
true;
4305 if (!empty($targetid) && !empty($targettype) && empty($sourceid)) {
4307 if (!empty($sourcetype)) {
4308 $withsourcetype =
true;
4312 $sourceid = (!empty($sourceid) ? $sourceid :
$this->id);
4313 $targetid = (!empty($targetid) ? $targetid :
$this->id);
4314 $sourcetype = (!empty($sourcetype) ? $sourcetype : $this->element);
4315 $targettype = (!empty($targettype) ? $targettype : $this->element);
4324 $sql =
"SELECT rowid, fk_source, sourcetype, fk_target, targettype";
4325 $sql .=
" FROM ".$this->db->prefix().
"element_element";
4327 if ($justsource || $justtarget) {
4329 $sql .=
"fk_source = ".((int) $sourceid).
" AND sourcetype = '".$this->db->escape($sourcetype).
"'";
4330 if ($withtargettype) {
4331 $sql .=
" AND targettype = '".$this->db->escape($targettype).
"'";
4333 } elseif ($justtarget) {
4334 $sql .=
"fk_target = ".((int) $targetid).
" AND targettype = '".$this->db->escape($targettype).
"'";
4335 if ($withsourcetype) {
4336 $sql .=
" AND sourcetype = '".$this->db->escape($sourcetype).
"'";
4340 $sql .=
"(fk_source = ".((int) $sourceid).
" AND sourcetype = '".$this->db->escape($sourcetype).
"')";
4341 $sql .=
" ".$clause.
" (fk_target = ".((int) $targetid).
" AND targettype = '".$this->db->escape($targettype).
"')";
4342 if ($loadalsoobjects && $this->
id > 0 && $sourceid == $this->
id && $sourcetype == $this->element && $targetid == $this->
id && $targettype == $this->element && $clause ==
'OR') {
4343 $this->linkedObjectsFullLoaded[
$this->id] =
true;
4346 $sql .=
" ORDER BY ".$orderby;
4348 dol_syslog(get_class($this).
"::fetchObjectLink", LOG_DEBUG);
4349 $resql = $this->db->query($sql);
4351 $num = $this->db->num_rows($resql);
4354 $obj = $this->db->fetch_object($resql);
4355 if ($justsource || $justtarget) {
4357 $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
4358 } elseif ($justtarget) {
4359 $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
4362 if ($obj->fk_source == $sourceid && $obj->sourcetype == $sourcetype) {
4363 $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
4365 if ($obj->fk_target == $targetid && $obj->targettype == $targettype) {
4366 $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
4372 if (!empty($this->linkedObjectsIds)) {
4373 $tmparray = $this->linkedObjectsIds;
4374 foreach ($tmparray as $objecttype => $objectids) {
4376 $element = $element_properties[
'element'];
4377 $classPath = $element_properties[
'classpath'];
4378 $classFile = $element_properties[
'classfile'];
4379 $className = $element_properties[
'classname'];
4380 $module = $element_properties[
'module'];
4383 if (isModEnabled($module) && (($element != $this->element) || $alsosametype)) {
4384 if ($loadalsoobjects && (is_numeric($loadalsoobjects) || ($loadalsoobjects === $objecttype))) {
4386 if (class_exists($className)) {
4387 foreach ($objectids as $i => $objectid) {
4388 $object =
new $className($this->db);
4389 '@phan-var-force CommonObject $object';
4390 $ret =
$object->fetch($objectid);
4392 $this->linkedObjects[$objecttype][$i] =
$object;
4398 unset($this->linkedObjectsIds[$objecttype]);
4417 if ($this->
id > 0 && !empty($this->linkedObjectsFullLoaded[$this->
id])) {
4418 unset($this->linkedObjectsFullLoaded[$this->
id]);
4436 public function updateObjectLinked($sourceid =
null, $sourcetype =
'', $targetid =
null, $targettype =
'', $f_user =
null, $notrigger = 0)
4439 $updatesource =
false;
4440 $updatetarget =
false;
4441 $f_user = isset($f_user) ? $f_user : $user;
4443 if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) {
4444 $updatesource =
true;
4445 } elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) {
4446 $updatetarget =
true;
4452 $sql =
"UPDATE " . $this->db->prefix() .
"element_element SET ";
4453 if ($updatesource) {
4454 $sql .=
"fk_source = " . ((int) $sourceid);
4455 $sql .=
", sourcetype = '" . $this->db->escape($sourcetype) .
"'";
4456 $sql .=
" WHERE fk_target = " . ((int) $this->
id);
4457 $sql .=
" AND targettype = '" . $this->db->escape($this->element) .
"'";
4458 } elseif ($updatetarget) {
4459 $sql .=
"fk_target = " . ((int) $targetid);
4460 $sql .=
", targettype = '" . $this->db->escape($targettype) .
"'";
4461 $sql .=
" WHERE fk_source = " . ((int) $this->
id);
4462 $sql .=
" AND sourcetype = '" . $this->db->escape($this->element) .
"'";
4465 dol_syslog(get_class($this) .
"::updateObjectLinked", LOG_DEBUG);
4466 if ($this->db->query($sql)) {
4469 $this->context[
'link_source_id'] = $sourceid;
4470 $this->context[
'link_source_type'] = $sourcetype;
4471 $this->context[
'link_target_id'] = $targetid;
4472 $this->context[
'link_target_type'] = $targettype;
4473 $result = $this->call_trigger(
'OBJECT_LINK_MODIFY', $f_user);
4480 $this->error = $this->db->lasterror();
4485 $this->db->commit();
4488 $this->db->rollback();
4506 public function deleteObjectLinked($sourceid =
null, $sourcetype =
'', $targetid =
null, $targettype =
'', $rowid = 0, $f_user =
null, $notrigger = 0)
4509 $deletesource =
false;
4510 $deletetarget =
false;
4511 $f_user = isset($f_user) ? $f_user : $user;
4513 if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) {
4514 $deletesource =
true;
4515 } elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) {
4516 $deletetarget =
true;
4519 $sourceid = (!empty($sourceid) ? $sourceid :
$this->id);
4520 $sourcetype = (!empty($sourcetype) ? $sourcetype : $this->element);
4521 $targetid = (!empty($targetid) ? $targetid :
$this->id);
4522 $targettype = (!empty($targettype) ? $targettype : $this->element);
4528 $this->context[
'link_id'] = $rowid;
4529 $this->context[
'link_source_id'] = $sourceid;
4530 $this->context[
'link_source_type'] = $sourcetype;
4531 $this->context[
'link_target_id'] = $targetid;
4532 $this->context[
'link_target_type'] = $targettype;
4533 $result = $this->call_trigger(
'OBJECT_LINK_DELETE', $f_user);
4541 $sql =
"DELETE FROM " . $this->db->prefix() .
"element_element";
4544 $sql .=
" rowid = " . ((int) $rowid);
4546 if ($deletesource) {
4547 $sql .=
" fk_source = " . ((int) $sourceid) .
" AND sourcetype = '" . $this->db->escape($sourcetype) .
"'";
4548 $sql .=
" AND fk_target = " . ((int) $this->
id) .
" AND targettype = '" . $this->db->escape($this->element) .
"'";
4549 } elseif ($deletetarget) {
4550 $sql .=
" fk_target = " . ((int) $targetid) .
" AND targettype = '" . $this->db->escape($targettype) .
"'";
4551 $sql .=
" AND fk_source = " . ((int) $this->
id) .
" AND sourcetype = '" . $this->db->escape($this->element) .
"'";
4553 $sql .=
" (fk_source = " . ((int) $this->
id) .
" AND sourcetype = '" . $this->db->escape($this->element) .
"')";
4555 $sql .=
" (fk_target = " . ((int) $this->
id) .
" AND targettype = '" . $this->db->escape($this->element) .
"')";
4559 dol_syslog(get_class($this) .
"::deleteObjectLinked", LOG_DEBUG);
4560 if (!$this->db->query($sql)) {
4561 $this->error = $this->db->lasterror();
4562 $this->errors[] = $this->error;
4568 $this->db->commit();
4571 $this->db->rollback();
4587 if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
4590 if (!preg_match(
'/^[_a-zA-Z0-9]+$/', $field_select)) {
4591 dol_syslog(
'Invalid value $field_select for parameter '.$field_select.
' in call to getAllItemsLinkedByObjectID(). Must be a single field name.', LOG_ERR);
4596 $sql =
"SELECT ".$field_select.
" FROM ".$db->prefix().$table_element.
" WHERE ".$field_where.
" = ".((int) $fk_object_where);
4597 $resql = $db->query($sql);
4600 if (!empty($resql)) {
4601 while ($res = $db->fetch_object($resql)) {
4602 $TRes[] = $res->{$field_select};
4619 if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
4625 $sql =
"SELECT COUNT(*) as nb FROM ".$db->prefix().$table_element.
" WHERE ".$field_where.
" = ".((int) $fk_object_where);
4626 $resql = $db->query($sql);
4629 $res = $db->fetch_object($resql);
4648 if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
4654 $sql =
"DELETE FROM ".$db->prefix().$table_element.
" WHERE ".$field_where.
" = ".((int) $fk_object_where);
4655 $resql = $db->query($sql);
4657 if (empty($resql)) {
4674 public function setStatut($status, $elementId =
null, $elementType =
'', $trigkey =
'', $fieldstatus =
'fk_statut')
4678 $savElementId = $elementId;
4680 $elementId = (!empty($elementId) ? $elementId :
$this->id);
4681 $elementTable = (!empty($elementType) ? $elementType : $this->table_element);
4685 if ($elementTable ==
'facture_rec') {
4686 $fieldstatus =
"suspended";
4688 if ($elementTable ==
'mailing') {
4689 $fieldstatus =
"statut";
4691 if ($elementTable ==
'cronjob') {
4692 $fieldstatus =
"status";
4694 if ($elementTable ==
'user') {
4695 $fieldstatus =
"statut";
4697 if ($elementTable ==
'expensereport') {
4698 $fieldstatus =
"fk_statut";
4700 if ($elementTable ==
'receptiondet_batch') {
4701 $fieldstatus =
"status";
4703 if ($elementTable ==
'prelevement_bons') {
4704 $fieldstatus =
"statut";
4706 if (isset($this->fields) && is_array($this->fields) && array_key_exists(
'status', $this->fields)) {
4707 $fieldstatus =
'status';
4710 $sql =
"UPDATE ".$this->db->prefix().$this->db->sanitize($elementTable);
4711 $sql .=
" SET ".$this->db->sanitize($fieldstatus).
" = ".((int) $status);
4714 if ($status == 1 && in_array($elementTable, array(
'expensereport',
'inventory'))) {
4715 $sql .=
", fk_user_valid = ".((int) $user->id);
4717 if ($status == 1 && in_array($elementTable, array(
'expensereport'))) {
4718 $sql .=
", date_valid = '".$this->db->idate(
dol_now()).
"'";
4720 if ($status == 1 && in_array($elementTable, array(
'inventory'))) {
4721 $sql .=
", date_validation = '".$this->db->idate(
dol_now()).
"'";
4723 $sql .=
" WHERE rowid = ".((int) $elementId);
4724 $sql .=
" AND ".$fieldstatus.
" <> ".((int) $status);
4726 dol_syslog(get_class($this).
"::setStatut", LOG_DEBUG);
4727 $resql = $this->db->query($sql);
4731 $nb_rows_affected = $this->db->affected_rows($resql);
4733 if ($nb_rows_affected > 0) {
4734 if (empty($trigkey)) {
4736 if ($this->element ==
'supplier_proposal' && $status == 2) {
4737 $trigkey =
'SUPPLIER_PROPOSAL_SIGN';
4739 if ($this->element ==
'supplier_proposal' && $status == 3) {
4740 $trigkey =
'SUPPLIER_PROPOSAL_REFUSE';
4742 if ($this->element ==
'supplier_proposal' && $status == 4) {
4743 $trigkey =
'SUPPLIER_PROPOSAL_CLOSE';
4745 if ($this->element ==
'fichinter' && $status == 3) {
4746 $trigkey =
'FICHINTER_CLASSIFY_DONE';
4748 if ($this->element ==
'fichinter' && $status == 2) {
4749 $trigkey =
'FICHINTER_CLASSIFY_BILLED';
4751 if ($this->element ==
'fichinter' && $status == 1) {
4752 $trigkey =
'FICHINTER_CLASSIFY_UNBILLED';
4756 $this->context = array_merge($this->context, array(
'newstatus' => $status));
4760 $result = $this->call_trigger($trigkey, $user);
4771 $this->db->commit();
4773 if (empty($savElementId)) {
4775 if ($fieldstatus ==
'tosell') {
4777 } elseif ($fieldstatus ==
'tobuy') {
4778 $this->status_buy = $status;
4786 $this->db->rollback();
4787 dol_syslog(get_class($this).
"::setStatut ".$this->error, LOG_ERR);
4791 $this->error = $this->db->lasterror();
4792 $this->db->rollback();
4809 if (empty(
$id) && empty($ref)) {
4819 $sql =
"SELECT rowid, canvas";
4820 $sql .=
" FROM ".$this->db->prefix().$this->table_element;
4821 $sql .=
" WHERE entity IN (".getEntity($this->element).
")";
4823 $sql .=
" AND rowid = ".((int)
$id);
4826 $sql .=
" AND ref = '".$this->db->escape($ref).
"'";
4829 $resql = $this->db->query($sql);
4831 $obj = $this->db->fetch_object($resql);
4833 $this->canvas = $obj->canvas;
4853 $sql =
"SELECT special_code FROM ".$this->db->prefix().$this->table_element_line;
4854 $sql .=
" WHERE rowid = ".((int) $lineid);
4855 $resql = $this->db->query($sql);
4857 $row = $this->db->fetch_row($resql);
4858 return (!empty($row[0]) ? $row[0] : 0);
4881 if (!isset($this->childtables) || !is_array($this->childtables) || count($this->childtables) == 0) {
4882 dol_print_error(
null,
'Called isObjectUsed on a class with property this->childtables not defined');
4886 $arraytoscan = $this->childtables;
4888 $tmparray = array_keys($this->childtables);
4889 if (is_numeric($tmparray[0])) {
4890 $arraytoscan = array_flip($this->childtables);
4895 foreach ($arraytoscan as $table => $element) {
4898 $sql =
"SELECT COUNT(*) as nb";
4899 $sql .=
" FROM ".$this->db->prefix().$table.
" as c";
4900 if (!empty($element[
'parent']) && !empty($element[
'parentkey'])) {
4901 $sql .=
", ".$this->db->prefix().$element[
'parent'].
" as p";
4903 if (!empty($element[
'fk_element'])) {
4904 $sql .=
" WHERE c.".$element[
'fk_element'].
" = ".((int)
$id);
4906 $sql .=
" WHERE c.".$this->fk_element.
" = ".((int)
$id);
4908 if (!empty($element[
'parent']) && !empty($element[
'parentkey'])) {
4909 $sql .=
" AND c.".$element[
'parentkey'].
" = p.rowid";
4911 if (!empty($element[
'parent']) && !empty($element[
'parenttypefield']) && !empty($element[
'parenttypevalue'])) {
4912 $sql .=
" AND c.".$element[
'parenttypefield'].
" = '".$this->db->escape($element[
'parenttypevalue']).
"'";
4914 if (!empty($entity)) {
4915 if (!empty($element[
'parent']) && !empty($element[
'parentkey'])) {
4916 $sql .=
" AND p.entity = ".((int) $entity);
4918 $sql .=
" AND c.entity = ".((int) $entity);
4922 $resql = $this->db->query($sql);
4924 $obj = $this->db->fetch_object($resql);
4926 $langs->load(
"errors");
4928 $haschild += $obj->nb;
4929 if (is_numeric($element)) {
4930 $this->errors[] = $langs->transnoentitiesnoconv(
"ErrorRecordHasAtLeastOneChildOfType", method_exists($this,
'getNomUrl') ? $this->getNomUrl() : $this->ref, $table);
4931 } elseif (is_string($element)) {
4932 $this->errors[] = $langs->transnoentitiesnoconv(
"ErrorRecordHasAtLeastOneChildOfType", method_exists($this,
'getNomUrl') ? $this->getNomUrl() : $this->ref, $langs->transnoentitiesnoconv($element));
4934 $this->errors[] = $langs->transnoentitiesnoconv(
"ErrorRecordHasAtLeastOneChildOfType", method_exists($this,
'getNomUrl') ? $this->getNomUrl() : $this->ref, $langs->transnoentitiesnoconv($element[
'name']));
4939 $this->errors[] = $this->db->lasterror();
4943 if ($haschild > 0) {
4944 $this->errors[] =
"ErrorRecordHasChildren";
4961 foreach ($this->lines as $key => $val) {
4963 if ($predefined == -1) {
4966 if ($predefined == 1 && $val->fk_product > 0) {
4969 if ($predefined == 0 && $val->fk_product <= 0) {
4972 if ($predefined == 2 && $val->fk_product > 0 && $val->product_type == 0) {
4975 if ($predefined == 3 && $val->fk_product > 0 && $val->product_type == 1) {
4982 dol_syslog(get_class($this).
'::hasProductsOrServices we found '.$nb.
' qualified lines of products/servcies');
4993 if (!empty($this->table_element_line)) {
4994 $total_discount = 0.00;
4996 $sql =
"SELECT subprice as pu_ht, qty, remise_percent, total_ht";
4997 $sql .=
" FROM ".$this->db->prefix().$this->table_element_line;
4998 $sql .=
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
5000 dol_syslog(get_class($this).
'::getTotalDiscount', LOG_DEBUG);
5001 $resql = $this->db->query($sql);
5003 $num = $this->db->num_rows($resql);
5006 $obj = $this->db->fetch_object($resql);
5008 $pu_ht = $obj->pu_ht;
5010 $total_ht = $obj->total_ht;
5012 $total_discount_line = (float)
price2num(($pu_ht * $qty) - $total_ht,
'MT');
5013 $total_discount += $total_discount_line;
5020 return (
float)
price2num($total_discount);
5042 if (empty($this->lines)) {
5043 return array(
'weight' => $totalWeight,
'volume' => $totalVolume,
'ordered' => $totalOrdered,
'toship' => $totalToShip);
5046 foreach ($this->lines as $line) {
5047 if (isset($line->qty_asked)) {
5048 $totalOrdered += $line->qty_asked;
5050 if (isset($line->qty_shipped)) {
5051 $totalToShip += $line->qty_shipped;
5052 } elseif ($line->element ==
'commandefournisseurdispatch' && isset($line->qty)) {
5053 if (empty($totalToShip)) {
5056 $totalToShip += $line->qty;
5060 if ($this->element ==
'shipping') {
5062 $qty = $line->qty_shipped ? $line->qty_shipped : 0;
5064 $qty = $line->qty ? $line->qty : 0;
5067 $weight = !empty($line->weight) ? $line->weight : 0;
5068 ($weight == 0 && !empty($line->product->weight)) ? $weight = $line->product->weight : 0;
5069 $volume = !empty($line->volume) ? $line->volume : 0;
5070 ($volume == 0 && !empty($line->product->volume)) ? $volume = $line->product->volume : 0;
5072 $weight_units = !empty($line->weight_units) ? $line->weight_units : 0;
5073 ($weight_units == 0 && !empty($line->product->weight_units)) ? $weight_units = $line->product->weight_units : 0;
5074 $volume_units = !empty($line->volume_units) ? $line->volume_units : 0;
5075 ($volume_units == 0 && !empty($line->product->volume_units)) ? $volume_units = $line->product->volume_units : 0;
5079 if (!empty($weight_units)) {
5080 $weightUnit = $weight_units;
5082 if (!empty($volume_units)) {
5083 $volumeUnit = $volume_units;
5086 if (empty($totalWeight)) {
5089 if (empty($totalVolume)) {
5094 if ($weight_units < 50) {
5095 $trueWeightUnit = pow(10, $weightUnit);
5096 $totalWeight += $weight * $qty * $trueWeightUnit;
5098 if ($weight_units == 99) {
5100 $trueWeightUnit = 0.45359237;
5101 $totalWeight += $weight * $qty * $trueWeightUnit;
5102 } elseif ($weight_units == 98) {
5104 $trueWeightUnit = 0.0283495;
5105 $totalWeight += $weight * $qty * $trueWeightUnit;
5107 $totalWeight += $weight * $qty;
5110 if ($volume_units < 50) {
5112 $trueVolumeUnit = pow(10, $volumeUnit);
5114 $totalVolume += $volume * $qty * $trueVolumeUnit;
5116 $totalVolume += $volume * $qty;
5120 return array(
'weight' => $totalWeight,
'volume' => $totalVolume,
'ordered' => $totalOrdered,
'toship' => $totalToShip);
5133 $extraparams = (!empty($this->extraparams) ? json_encode($this->extraparams) :
null);
5135 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
5136 $sql .=
" SET extraparams = ".(!empty($extraparams) ?
"'".$this->db->escape($extraparams).
"'" :
"null");
5137 $sql .=
" WHERE rowid = ".((int) $this->
id);
5139 dol_syslog(get_class($this).
"::setExtraParameters", LOG_DEBUG);
5140 $resql = $this->db->query($sql);
5142 $this->error = $this->db->lasterror();
5143 $this->db->rollback();
5146 $this->db->commit();
5169 global $conf, $user, $langs,
$object, $hookmanager, $extrafields, $form;
5172 if (!is_object($extrafields)) {
5173 require_once DOL_DOCUMENT_ROOT.
'/core/class/extrafields.class.php';
5176 $extrafields->fetch_name_optionals_label($this->table_element_line);
5181 $dirtpls = array_merge($conf->modules_parts[
'tpl'], array($defaulttpldir));
5182 foreach ($dirtpls as $module => $reldir) {
5183 if (!empty($module)) {
5186 $tpl = DOL_DOCUMENT_ROOT.$reldir.
'/objectline_create.tpl.php';
5189 if (empty($conf->file->strict_mode)) {
5190 $res = @include $tpl;
5192 $res = include $tpl;
5219 public function printObjectLines($action, $seller, $buyer, $selected = 0, $dateSelector = 0, $defaulttpldir =
'/core/tpl')
5221 global $conf, $hookmanager, $langs, $user, $form, $extrafields,
$object;
5223 global $inputalsopricewithtax, $usemargins, $disableedit, $disablemove, $disableremove, $outputalsopricetotalwithtax;
5227 if (isModEnabled(
'margin') && !empty($this->element) && in_array($this->element, array(
'facture',
'facturerec',
'propal',
'commande'))) {
5231 $num = count($this->lines);
5234 if (!is_object($extrafields)) {
5235 require_once DOL_DOCUMENT_ROOT.
'/core/class/extrafields.class.php';
5238 $extrafields->fetch_name_optionals_label($this->table_element_line);
5240 if (method_exists($this,
'loadExpeditions')) {
5241 $this->loadExpeditions();
5244 $parameters = array(
'num' => $num,
'dateSelector' => $dateSelector,
'seller' => $seller,
'buyer' => $buyer,
'selected' => $selected,
'table_element_line' => $this->table_element_line);
5245 $reshook = $hookmanager->executeHooks(
'printObjectLineTitle', $parameters, $this, $action);
5246 if (empty($reshook)) {
5250 $dirtpls = array_merge($conf->modules_parts[
'tpl'], array($defaulttpldir));
5251 foreach ($dirtpls as $module => $reldir) {
5253 if (!empty($module)) {
5256 $tpl = DOL_DOCUMENT_ROOT.$reldir.
'/objectline_title.tpl.php';
5258 if (file_exists($tpl)) {
5259 if (empty($conf->file->strict_mode)) {
5260 $res = @include $tpl;
5262 $res = include $tpl;
5273 print
"<!-- begin printObjectLines() -->\n";
5274 foreach ($this->lines as $line) {
5276 $line->fetch_optionals();
5279 if (is_object($hookmanager)) {
5280 if (empty($line->fk_parent_line)) {
5281 $parameters = array(
'line' => $line,
'num' => $num,
'i' => $i,
'dateSelector' => $dateSelector,
'seller' => $seller,
'buyer' => $buyer,
'selected' => $selected,
'table_element_line' => $line->table_element,
'defaulttpldir' => $defaulttpldir);
5282 $reshook = $hookmanager->executeHooks(
'printObjectLine', $parameters, $this, $action);
5284 $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);
5285 $reshook = $hookmanager->executeHooks(
'printObjectSubLine', $parameters, $this, $action);
5288 if (empty($reshook)) {
5289 $this->printObjectLine($action, $line,
'', $num, $i, $dateSelector, $seller, $buyer, $selected, $extrafields, $defaulttpldir);
5294 print
"<!-- end printObjectLines() -->\n";
5314 public function printObjectLine($action, $line, $var, $num, $i, $dateSelector, $seller, $buyer, $selected = 0, $extrafields =
null, $defaulttpldir =
'/core/tpl')
5316 global $conf, $langs, $user,
$object, $hookmanager;
5318 global $disableedit, $disablemove, $disableremove;
5325 if ($action !=
'editline' || $selected != $line->id) {
5327 if (!empty($line->fk_product) && $line->fk_product > 0) {
5328 $product_static =
new Product($this->db);
5329 $product_static->fetch($line->fk_product);
5331 $product_static->ref = $line->ref;
5332 $product_static->label = !empty($line->label) ? $line->label :
"";
5334 $text = $product_static->getNomUrl(1);
5338 if (property_exists($this,
'socid') && !is_object($this->thirdparty)) {
5339 dol_print_error(
null,
'Error: Method printObjectLine was called on an object and object->fetch_thirdparty was not done before');
5343 $prod =
new Product($this->db);
5344 $prod->fetch($line->fk_product);
5346 $outputlangs = $langs;
5348 if (empty($newlang) &&
GETPOST(
'lang_id',
'aZ09')) {
5349 $newlang =
GETPOST(
'lang_id',
'aZ09');
5351 if (
getDolGlobalString(
'PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE') && empty($newlang) && is_object($this->thirdparty)) {
5352 $newlang = $this->thirdparty->default_lang;
5354 if (!empty($newlang)) {
5355 $outputlangs =
new Translate(
"", $conf);
5356 $outputlangs->setDefaultLang($newlang);
5359 $label = (!empty($prod->multilangs[$outputlangs->defaultlang][
"label"])) ? $prod->multilangs[$outputlangs->defaultlang][
"label"] : $line->product_label;
5361 $label = $line->product_label;
5364 $text .=
' - '.(!empty($line->label) ? $line->label : $label);
5365 $description .= (
getDolGlobalInt(
'PRODUIT_DESC_IN_FORM_ACCORDING_TO_DEVICE') ?
'' : (!empty($line->description) ?
dol_htmlentitiesbr($line->description) :
''));
5368 $line->pu_ttc =
price2num((!empty($line->subprice) ? $line->subprice : 0) * (1 + ((!empty($line->tva_tx) ? $line->tva_tx : 0) / 100)),
'MU');
5375 if (isset($this->expeditions[$line->id])) {
5376 $qty_shipped = $this->expeditions[$line->id];
5378 $disableedit = $qty_shipped >= $line->qty;
5380 $dirtpls = array_merge($conf->modules_parts[
'tpl'], array($defaulttpldir));
5381 foreach ($dirtpls as $module => $reldir) {
5383 if (!empty($module)) {
5386 $tpl = DOL_DOCUMENT_ROOT.$reldir.
'/objectline_view.tpl.php';
5389 if (file_exists($tpl)) {
5390 if (empty($conf->file->strict_mode)) {
5391 $res = @include $tpl;
5393 $res = include $tpl;
5403 if ($this->
status == 0 && $action ==
'editline' && $selected == $line->id) {
5404 $label = (!empty($line->label) ? $line->label : (($line->fk_product > 0) ? $line->product_label :
''));
5406 $line->pu_ttc =
price2num($line->subprice * (1 + ($line->tva_tx / 100)),
'MU');
5411 $dirtpls = array_merge($conf->modules_parts[
'tpl'], array($defaulttpldir));
5412 foreach ($dirtpls as $module => $reldir) {
5413 if (!empty($module)) {
5416 $tpl = DOL_DOCUMENT_ROOT.$reldir.
'/objectline_edit.tpl.php';
5419 if (empty($conf->file->strict_mode)) {
5420 $res = @include $tpl;
5422 $res = include $tpl;
5447 global $langs, $hookmanager, $form, $action;
5449 print
'<tr class="liste_titre">';
5450 print
'<td class="linecolref">'.$langs->trans(
'Ref').
'</td>';
5451 print
'<td class="linecoldescription">'.$langs->trans(
'Description').
'</td>';
5452 print
'<td class="linecolvat right">'.$langs->trans(
'VATRate').
'</td>';
5453 print
'<td class="linecoluht right">'.$langs->trans(
'PriceUHT').
'</td>';
5454 if (isModEnabled(
"multicurrency")) {
5455 print
'<td class="linecoluht_currency right">'.$langs->trans(
'PriceUHTCurrency').
'</td>';
5457 print
'<td class="linecolqty right">'.$langs->trans(
'Qty').
'</td>';
5459 print
'<td class="linecoluseunit left">'.$langs->trans(
'Unit').
'</td>';
5461 print
'<td class="linecoldiscount right">'.$langs->trans(
'ReductionShort').
'</td>';
5462 print
'<td class="linecolht right">'.$langs->trans(
'TotalHT').
'</td>';
5463 print
'<td class="center">'.$form->showCheckAddButtons(
'checkforselect', 1).
'</td>';
5467 if (!empty($this->lines)) {
5468 foreach ($this->lines as $line) {
5471 if (is_object($hookmanager)) {
5472 $parameters = array(
'line' => $line,
'i' => $i,
'restrictlist' => $restrictlist,
'selectedLines' => $selectedLines);
5473 if (!empty($line->fk_parent_line)) {
5474 $parameters[
'fk_parent_line'] = $line->fk_parent_line;
5476 $reshook = $hookmanager->executeHooks(
'printOriginObjectLine', $parameters, $this, $action);
5478 if (empty($reshook)) {
5479 $this->printOriginLine($line,
'', $restrictlist,
'/core/tpl', $selectedLines);
5500 public function printOriginLine($line, $var, $restrictlist =
'', $defaulttpldir =
'/core/tpl', $selectedLines = array())
5502 global $langs, $conf;
5505 if (!empty($line->date_start)) {
5507 $date_start = $line->date_start;
5509 $date_start = $line->date_debut_prevue;
5510 if ($line->date_debut_reel) {
5511 $date_start = $line->date_debut_reel;
5514 if (!empty($line->date_end)) {
5516 $date_end = $line->date_end;
5518 $date_end = $line->date_fin_prevue;
5519 if ($line->date_fin_reel) {
5520 $date_end = $line->date_fin_reel;
5524 $this->tpl[
'id'] = $line->id;
5526 $this->tpl[
'label'] =
'';
5527 if (!empty($line->fk_parent_line)) {
5528 $this->tpl[
'label'] .=
img_picto(
'',
'rightarrow');
5531 if (($line->info_bits & 2) == 2) {
5533 if (property_exists($this,
'socid')) {
5534 $discount->fk_soc = $this->socid;
5535 $discount->socid = $this->socid;
5537 $this->tpl[
'label'] .= $discount->getNomUrl(0,
'discount');
5538 } elseif (!empty($line->fk_product)) {
5539 $productstatic =
new Product($this->db);
5540 $productstatic->id = $line->fk_product;
5541 $productstatic->ref = $line->ref;
5542 $productstatic->type = $line->fk_product_type;
5543 if (empty($productstatic->ref)) {
5544 $line->fetch_product();
5545 $productstatic = $line->product;
5548 $this->tpl[
'label'] .= $productstatic->getNomUrl(1);
5549 $this->tpl[
'label'] .=
' - '.(!empty($line->label) ? $line->label : $line->product_label);
5551 if ($line->product_type == 1 && ($date_start || $date_end)) {
5555 $this->tpl[
'label'] .= ($line->product_type == -1 ?
' ' : ($line->product_type == 1 ?
img_object($langs->trans(
''),
'service') :
img_object($langs->trans(
''),
'product')));
5556 if (!empty($line->desc)) {
5557 $this->tpl[
'label'] .= $line->desc;
5559 $this->tpl[
'label'] .= ($line->label ?
' '.$line->label :
'');
5563 if ($line->product_type == 1 && ($date_start || $date_end)) {
5568 if (!empty($line->desc)) {
5569 '@phan-var-force OrderLine|FactureLigne|ContratLigne|FactureFournisseurLigneRec|SupplierInvoiceLine|SupplierProposalLine $line';
5570 if ($line->desc ==
'(CREDIT_NOTE)') {
5572 $discount->fetch($line->fk_remise_except);
5573 $this->tpl[
'description'] = $langs->transnoentities(
"DiscountFromCreditNote", $discount->getNomUrl(0));
5574 } elseif ($line->desc ==
'(DEPOSIT)') {
5576 $discount->fetch($line->fk_remise_except);
5577 $this->tpl[
'description'] = $langs->transnoentities(
"DiscountFromDeposit", $discount->getNomUrl(0));
5578 } elseif ($line->desc ==
'(EXCESS RECEIVED)') {
5580 $discount->fetch($line->fk_remise_except);
5581 $this->tpl[
'description'] = $langs->transnoentities(
"DiscountFromExcessReceived", $discount->getNomUrl(0));
5582 } elseif ($line->desc ==
'(EXCESS PAID)') {
5584 $discount->fetch($line->fk_remise_except);
5585 $this->tpl[
'description'] = $langs->transnoentities(
"DiscountFromExcessPaid", $discount->getNomUrl(0));
5587 $this->tpl[
'description'] =
dol_trunc($line->desc, 60);
5590 $this->tpl[
'description'] =
' ';
5594 $this->tpl[
'vat_rate'] =
vatrate($line->tva_tx,
true);
5595 $this->tpl[
'vat_rate'] .= (($line->info_bits & 1) == 1) ?
'*' :
'';
5596 if (!empty($line->vat_src_code) && !preg_match(
'/\(/', $this->tpl[
'vat_rate'])) {
5597 $this->tpl[
'vat_rate'] .=
' ('.$line->vat_src_code.
')';
5600 $this->tpl[
'price'] =
price($line->subprice);
5601 $this->tpl[
'total_ht'] =
price($line->total_ht);
5602 $this->tpl[
'multicurrency_price'] =
price($line->multicurrency_subprice);
5603 $this->tpl[
'qty'] = (($line->info_bits & 2) != 2) ? $line->qty :
' ';
5605 $this->tpl[
'unit'] = $langs->transnoentities($line->getLabelOfUnit(
'long'));
5607 $this->tpl[
'remise_percent'] = (($line->info_bits & 2) != 2) ?
vatrate((
string) $line->remise_percent,
true) :
' ';
5610 $this->tpl[
'strike'] = 0;
5612 $this->tpl[
'strike'] = 1;
5617 $dirtpls = array_merge($conf->modules_parts[
'tpl'], array($defaulttpldir));
5618 foreach ($dirtpls as $module => $reldir) {
5619 if (!empty($module)) {
5622 $tpl = DOL_DOCUMENT_ROOT.$reldir.
'/originproductline.tpl.php';
5625 if (empty($conf->file->strict_mode)) {
5626 $res = @include $tpl;
5628 $res = include $tpl;
5653 $sql =
"INSERT INTO ".$this->db->prefix().
"element_resources (";
5654 $sql .=
"resource_id";
5655 $sql .=
", resource_type";
5656 $sql .=
", element_id";
5657 $sql .=
", element_type";
5659 $sql .=
", mandatory";
5660 $sql .=
") VALUES (";
5661 $sql .= ((int) $resource_id);
5662 $sql .=
", '".$this->db->escape($resource_type).
"'";
5663 $sql .=
", '".$this->db->escape($this->
id).
"'";
5664 $sql .=
", '".$this->db->escape($this->element).
"'";
5665 $sql .=
", '".$this->db->escape($busy).
"'";
5666 $sql .=
", '".$this->db->escape($mandatory).
"'";
5669 dol_syslog(get_class($this).
"::add_element_resource", LOG_DEBUG);
5670 if ($this->db->query($sql)) {
5671 $this->db->commit();
5674 $this->error = $this->db->lasterror();
5675 $this->db->rollback();
5696 $sql =
"DELETE FROM ".$this->db->prefix().
"element_resources";
5697 $sql .=
" WHERE rowid = ".((int) $rowid);
5699 dol_syslog(get_class($this).
"::delete_resource", LOG_DEBUG);
5701 $resql = $this->db->query($sql);
5703 $this->error = $this->db->lasterror();
5704 $this->db->rollback();
5708 $result = $this->call_trigger(strtoupper($element).
'_DELETE_RESOURCE', $user);
5710 $this->db->rollback();
5714 $this->db->commit();
5728 if (isset($this->lines) && is_array($this->lines)) {
5729 $nboflines = count($this->lines);
5730 for ($i = 0; $i < $nboflines; $i++) {
5731 if (is_object($this->lines[$i])) {
5732 $this->lines[$i] = clone $this->lines[$i];
5751 protected function commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams =
null)
5753 global $conf, $langs, $user, $hookmanager, $action;
5755 $srctemplatepath =
'';
5757 $parameters = array(
'modelspath' => $modelspath,
'modele' => $modele,
'outputlangs' => $outputlangs,
'hidedetails' => $hidedetails,
'hidedesc' => $hidedesc,
'hideref' => $hideref,
'moreparams' => $moreparams);
5758 $reshook = $hookmanager->executeHooks(
'commonGenerateDocument', $parameters, $this, $action);
5760 if (!empty($reshook)) {
5764 dol_syslog(
"commonGenerateDocument modele=".$modele.
" outputlangs->defaultlang=".(is_object($outputlangs) ? $outputlangs->defaultlang :
'null'));
5766 if (empty($modele)) {
5767 $this->error =
'BadValueForParameterModele';
5772 $err = error_reporting();
5774 @set_time_limit(120);
5775 error_reporting($err);
5778 $tmp = explode(
':', $modele, 2);
5779 $saved_model = $modele;
5780 if (!empty($tmp[1])) {
5782 $srctemplatepath = $tmp[1];
5789 $dirmodels = array(
'/');
5790 if (is_array($conf->modules_parts[
'models'])) {
5791 $dirmodels = array_merge($dirmodels, $conf->modules_parts[
'models']);
5793 foreach ($dirmodels as $reldir) {
5794 foreach (array(
'doc',
'pdf') as $prefix) {
5795 if (in_array(get_class($this), array(
'Adherent'))) {
5797 $file = $prefix.
"_".$modele.
".class.php";
5800 $file = $prefix.
"_".$modele.
".modules.php";
5807 if (file_exists($file)) {
5809 $classname = $prefix.
'_'.$modele;
5818 if ($filefound ===
'' || $classname ===
'') {
5819 $this->error = $langs->trans(
"Error").
' Failed to load doc generator with modelpaths='.$modelspath.
' - modele='.$modele;
5820 $this->errors[] = $this->error;
5831 require_once $filefound;
5833 $obj =
new $classname($this->db);
5845 '@phan-var-force ModelePDFMember $obj';
5849 if ($obj->type ==
'odt' && empty($srctemplatepath)) {
5850 $varfortemplatedir = $obj->scandir;
5854 $listoffiles = array();
5857 $listofdir = explode(
',', $dirtoscan);
5858 foreach ($listofdir as $key => $tmpdir) {
5859 $tmpdir = trim($tmpdir);
5860 $tmpdir = preg_replace(
'/DOL_DATA_ROOT/', DOL_DATA_ROOT, $tmpdir);
5862 unset($listofdir[$key]);
5865 if (is_dir($tmpdir)) {
5866 $tmpfiles =
dol_dir_list($tmpdir,
'files', 0,
'\.od(s|t)$',
'',
'name', SORT_ASC, 0);
5867 if (count($tmpfiles)) {
5868 $listoffiles = array_merge($listoffiles, $tmpfiles);
5873 if (count($listoffiles)) {
5874 foreach ($listoffiles as $record) {
5875 $srctemplatepath = $record[
'fullname'];
5881 if (empty($srctemplatepath)) {
5882 $this->error =
'ErrorGenerationAskedForOdtTemplateWithSrcFileNotDefined';
5887 if ($obj->type ==
'odt' && !empty($srctemplatepath)) {
5889 dol_syslog(
"Failed to locate template file ".$srctemplatepath, LOG_WARNING);
5890 $this->error =
'ErrorGenerationAskedForOdtTemplateWithSrcFileNotFound';
5897 $sav_charset_output = empty($outputlangs->charset_output) ?
'' : $outputlangs->charset_output;
5900 $this->model_pdf = $saved_model;
5903 $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath,
'member', 1,
'tmp_cards');
5906 '@phan-var-force ModeleBarCode|ModeleDon|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';
5907 $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, $hidedetails, $hidedesc, $hideref, $moreparams);
5911 if ($resultwritefile > 0) {
5912 $outputlangs->charset_output = $sav_charset_output;
5915 require_once DOL_DOCUMENT_ROOT.
'/core/lib/files.lib.php';
5919 if (!empty($obj->result[
'fullpath'])) {
5920 $destfull = $obj->result[
'fullpath'];
5923 $update_main_doc_field = 0;
5924 if (!empty($obj->update_main_doc_field)) {
5925 $update_main_doc_field = 1;
5931 $this->indexFile($destfull, $update_main_doc_field);
5934 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);
5942 $outputlangs->charset_output = $sav_charset_output;
5943 $this->error = $obj->error;
5944 $this->errors = $obj->errors;
5945 dol_syslog(
"Error generating document for ".__CLASS__.
". Error: ".$obj->error, LOG_ERR);
5959 public function indexFile($destfull, $update_main_doc_field)
5961 global $conf, $user;
5963 $upload_dir = dirname($destfull);
5964 $destfile = basename($destfull);
5965 $rel_dir = preg_replace(
'/^'.preg_quote(DOL_DATA_ROOT,
'/').
'/',
'', $upload_dir);
5967 if (!preg_match(
'/[\\/]temp[\\/]|[\\/]thumbs|\.meta$/', $rel_dir)) {
5968 $filename = basename($destfile);
5969 $rel_dir = preg_replace(
'/[\\/]$/',
'', $rel_dir);
5970 $rel_dir = preg_replace(
'/^[\\/]/',
'', $rel_dir);
5972 include_once DOL_DOCUMENT_ROOT.
'/ecm/class/ecmfiles.class.php';
5973 $ecmfile =
new EcmFiles($this->db);
5974 $result = $ecmfile->fetch(0,
'', ($rel_dir ? $rel_dir.
'/' :
'').$filename);
5977 $setsharekey =
false;
5978 if ($this->element ==
'propal' || $this->element ==
'proposal') {
5980 $setsharekey =
true;
5983 $setsharekey =
true;
5986 if ($this->element ==
'commande' &&
getDolGlobalInt(
"ORDER_ALLOW_EXTERNAL_DOWNLOAD")) {
5987 $setsharekey =
true;
5989 if ($this->element ==
'facture' &&
getDolGlobalInt(
"INVOICE_ALLOW_EXTERNAL_DOWNLOAD")) {
5990 $setsharekey =
true;
5992 if ($this->element ==
'bank_account' &&
getDolGlobalInt(
"BANK_ACCOUNT_ALLOW_EXTERNAL_DOWNLOAD")) {
5993 $setsharekey =
true;
5995 if ($this->element ==
'product' &&
getDolGlobalInt(
"PRODUCT_ALLOW_EXTERNAL_DOWNLOAD")) {
5996 $setsharekey =
true;
5998 if ($this->element ==
'contrat' &&
getDolGlobalInt(
"CONTRACT_ALLOW_EXTERNAL_DOWNLOAD")) {
5999 $setsharekey =
true;
6001 if ($this->element ==
'fichinter' &&
getDolGlobalInt(
"FICHINTER_ALLOW_EXTERNAL_DOWNLOAD")) {
6002 $setsharekey =
true;
6004 if ($this->element ==
'supplier_proposal' &&
getDolGlobalInt(
"SUPPLIER_PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD")) {
6005 $setsharekey =
true;
6007 if ($this->element ==
'societe_rib' &&
getDolGlobalInt(
"SOCIETE_RIB_ALLOW_ONLINESIGN")) {
6008 $setsharekey =
true;
6012 if (empty($ecmfile->share)) {
6013 require_once DOL_DOCUMENT_ROOT.
'/core/lib/security2.lib.php';
6020 $ecmfile->fullpath_orig =
'';
6021 $ecmfile->gen_or_uploaded =
'generated';
6022 $ecmfile->description =
'';
6023 $ecmfile->keywords =
'';
6024 $ecmfile->src_object_type = $this->table_element;
6026 $result = $ecmfile->update($user);
6032 $ecmfile->entity = $conf->entity;
6033 $ecmfile->filepath = $rel_dir;
6034 $ecmfile->filename = $filename;
6036 $ecmfile->fullpath_orig =
'';
6037 $ecmfile->gen_or_uploaded =
'generated';
6038 $ecmfile->description =
'';
6039 $ecmfile->keywords =
'';
6040 $ecmfile->src_object_type = $this->table_element;
6043 $result = $ecmfile->create($user);
6055 if ($update_main_doc_field && !empty($this->table_element)) {
6056 $sql =
"UPDATE ".$this->db->prefix().$this->table_element.
" SET last_main_doc = '".$this->db->escape($ecmfile->filepath.
"/".$ecmfile->filename).
"'";
6057 $sql .=
" WHERE rowid = ".((int) $this->
id);
6059 $resql = $this->db->query($sql);
6064 $this->last_main_doc = $ecmfile->filepath.
'/'.$ecmfile->filename;
6083 if (file_exists($file_osencoded)) {
6084 require_once DOL_DOCUMENT_ROOT.
'/core/lib/images.lib.php';
6087 $maxwidthsmall = $tmparraysize[
'maxwidthsmall'];
6088 $maxheightsmall = $tmparraysize[
'maxheightsmall'];
6089 $maxwidthmini = $tmparraysize[
'maxwidthmini'];
6090 $maxheightmini = $tmparraysize[
'maxheightmini'];
6096 vignette($file_osencoded, $maxwidthsmall, $maxheightsmall,
'_small', $quality);
6100 vignette($file_osencoded, $maxwidthmini, $maxheightmini,
'_mini', $quality);
6140 if (GETPOSTISSET($fieldname)) {
6141 return GETPOST($fieldname, $type, 3);
6144 if (isset($alternatevalue)) {
6145 return $alternatevalue;
6148 $newelement = $this->element;
6149 if ($newelement ==
'facture') {
6150 $newelement =
'invoice';
6152 if ($newelement ==
'commande') {
6153 $newelement =
'order';
6155 if (empty($newelement)) {
6156 dol_syslog(
"Ask a default value using common method getDefaultCreateValueForField on an object with no property ->element defined. Return empty string.", LOG_WARNING);
6160 $keyforfieldname = strtoupper($newelement.
'_DEFAULT_'.$fieldname);
6190 global $langs, $conf;
6192 if (!empty(self::TRIGGER_PREFIX) && strpos($triggerName, self::TRIGGER_PREFIX .
'_') !== 0) {
6193 dol_print_error(
null,
'The trigger "' . $triggerName .
'" does not start with "' . self::TRIGGER_PREFIX .
'_" as required.');
6196 if (!is_object($langs)) {
6197 include_once DOL_DOCUMENT_ROOT.
'/core/class/translate.class.php';
6201 include_once DOL_DOCUMENT_ROOT.
'/core/class/interfaces.class.php';
6203 $result = $interface->run_triggers($triggerName, $this, $user, $langs, $conf);
6206 if (!empty($this->errors)) {
6207 $this->errors = array_unique(array_merge($this->errors, $interface->errors));
6209 $this->errors = $interface->errors;
6229 if (!$this->element) {
6232 if (!($this->
id > 0)) {
6235 if (is_array($this->array_languages)) {
6239 $this->array_languages = array();
6241 $element = $this->element;
6242 if ($element ==
'categorie') {
6243 $element =
'categories';
6247 $sql =
"SELECT rowid, property, lang , value";
6248 $sql .=
" FROM ".$this->db->prefix().
"object_lang";
6249 $sql .=
" WHERE type_object = '".$this->db->escape($element).
"'";
6250 $sql .=
" AND fk_object = ".((int) $this->
id);
6253 $resql = $this->db->query($sql);
6255 $numrows = $this->db->num_rows($resql);
6258 while ($i < $numrows) {
6259 $obj = $this->db->fetch_object($resql);
6260 $key = $obj->property;
6261 $value = $obj->value;
6262 $codelang = $obj->lang;
6263 $type = $this->fields[$key][
'type'];
6266 if (preg_match(
'/date/', $type)) {
6267 $this->array_languages[$key][$codelang] = $this->db->jdate($value);
6269 $this->array_languages[$key][$codelang] = $value;
6276 $this->db->free($resql);
6298 foreach ($_POST as $postfieldkey => $postfieldvalue) {
6299 $tmparray = explode(
'-', $postfieldkey);
6300 if ($tmparray[0] !=
'field') {
6304 $element = $tmparray[1];
6305 $key = $tmparray[2];
6306 $codelang = $tmparray[3];
6309 if (!empty($onlykey) && $key != $onlykey) {
6312 if ($element != $this->element) {
6316 $key_type = $this->fields[$key][
'type'];
6319 if (isset($this->fields[$key][
'enabled'])) {
6320 $enabled = (int)
dol_eval($this->fields[$key][
'enabled'], 1, 1,
'1');
6327 if (empty($enabled)) {
6332 if (in_array($key_type, array(
'date'))) {
6336 } elseif (in_array($key_type, array(
'datetime'))) {
6340 } elseif (in_array($key_type, array(
'checkbox',
'chkbxlst'))) {
6341 $value_arr =
GETPOST($postfieldkey,
'array');
6342 if (!empty($value_arr)) {
6343 $value_key = implode(
',', $value_arr);
6347 } elseif (in_array($key_type, array(
'price',
'double'))) {
6348 $value_arr =
GETPOST($postfieldkey,
'alpha');
6351 $value_key =
GETPOST($postfieldkey);
6352 if (in_array($key_type, array(
'link')) && $value_key ==
'-1') {
6357 $this->array_languages[$key][$codelang] = $value_key;
6382 $savDisableCompute = $conf->disable_compute;
6383 $conf->disable_compute = 1;
6385 $ret = $this->fetch(
$id);
6387 $conf->disable_compute = $savDisableCompute;
6405 global $conf, $extrafields;
6407 if (empty($rowid)) {
6410 if (empty($rowid) && isset($this->rowid)) {
6411 $rowid = $this->rowid;
6415 if (!$this->table_element) {
6419 $this->array_options = array();
6421 if (!is_array($optionsArray)) {
6423 if (!isset($extrafields) || !is_object($extrafields)) {
6424 require_once DOL_DOCUMENT_ROOT.
'/core/class/extrafields.class.php';
6429 if (empty($extrafields->attributes[$this->table_element][
'loaded'])) {
6430 $extrafields->fetch_name_optionals_label($this->table_element);
6432 $optionsArray = (!empty($extrafields->attributes[$this->table_element][
'label']) ? $extrafields->attributes[$this->table_element][
'label'] :
null);
6434 global $extrafields;
6435 dol_syslog(
"Warning: fetch_optionals was called with param optionsArray defined when you should pass null now", LOG_WARNING);
6438 $table_element = $this->table_element;
6439 if ($table_element ==
'categorie') {
6440 $table_element =
'categories';
6444 if (is_array($optionsArray) && count($optionsArray) > 0) {
6445 $sql =
"SELECT rowid";
6446 foreach ($optionsArray as $name => $label) {
6447 if (empty($extrafields->attributes[$this->table_element][
'type'][$name]) || (!in_array($extrafields->attributes[$this->table_element][
'type'][$name], [
'separate',
'point',
'multipts',
'linestrg',
'polygon']))) {
6451 if (empty($extrafields->attributes[$this->table_element][
'type'][$name]) || $extrafields->attributes[$this->table_element][
'type'][$name] ==
'point') {
6452 $sql .=
", ST_AsWKT(".$name.
") as ".$name;
6454 if (empty($extrafields->attributes[$this->table_element][
'type'][$name]) || $extrafields->attributes[$this->table_element][
'type'][$name] ==
'multipts') {
6455 $sql .=
", ST_AsWKT(".$name.
") as ".$name;
6457 if (empty($extrafields->attributes[$this->table_element][
'type'][$name]) || $extrafields->attributes[$this->table_element][
'type'][$name] ==
'linestrg') {
6458 $sql .=
", ST_AsWKT(".$name.
") as ".$name;
6460 if (empty($extrafields->attributes[$this->table_element][
'type'][$name]) || $extrafields->attributes[$this->table_element][
'type'][$name] ==
'polygon') {
6461 $sql .=
", ST_AsWKT(".$name.
") as ".$name;
6464 $sql .=
" FROM ".$this->db->prefix().$table_element.
"_extrafields";
6465 $sql .=
" WHERE fk_object = ".((int) $rowid);
6468 $resql = $this->db->query($sql);
6470 $numrows = $this->db->num_rows($resql);
6472 $tab = $this->db->fetch_array($resql);
6474 foreach ($tab as $key => $value) {
6476 if ($key !=
'rowid' && $key !=
'tms' && $key !=
'fk_member' && !is_int($key)) {
6478 if (!empty($extrafields->attributes[$this->table_element]) && in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'date',
'datetime'))) {
6480 $this->array_options[
"options_".$key] = $this->db->jdate($value);
6482 $this->array_options[
"options_".$key] = $value;
6487 if (!empty($extrafields->attributes[$this->table_element][
'type'][$key]) && $extrafields->attributes[$this->table_element][
'type'][$key] ==
'password') {
6488 if (!empty($value) && preg_match(
'/^dolcrypt:/', $value)) {
6489 $this->array_options[
"options_".$key] =
dolDecrypt($value);
6498 if (is_array($extrafields->attributes[$this->table_element][
'label'])) {
6499 foreach ($extrafields->attributes[$this->table_element][
'label'] as $key => $val) {
6500 $this->array_options[
'options_' . $key] =
null;
6507 if (is_array($extrafields->attributes[$this->table_element][
'label'])) {
6508 foreach ($extrafields->attributes[$this->table_element][
'label'] as $key => $val) {
6509 if (!empty($extrafields->attributes[$this->table_element]) && !empty($extrafields->attributes[$this->table_element][
'computed'][$key])) {
6511 if (empty($conf->disable_compute)) {
6512 global $objectoffield;
6513 $objectoffield = $this;
6514 $this->array_options[
'options_' . $key] =
dol_eval($extrafields->attributes[$this->table_element][
'computed'][$key], 1, 0,
'2');
6520 $this->db->free($resql);
6528 $this->errors[] = $this->db->lasterror;
6551 $table_element = $this->table_element;
6552 if ($table_element ==
'categorie') {
6553 $table_element =
'categories';
6556 dol_syslog(get_class($this).
"::deleteExtraFields delete", LOG_DEBUG);
6558 $sql_del =
"DELETE FROM ".$this->db->prefix().$table_element.
"_extrafields WHERE fk_object = ".((int) $this->
id);
6560 $resql = $this->db->query($sql_del);
6562 $this->error = $this->db->lasterror();
6563 $this->db->rollback();
6566 $this->db->commit();
6583 global $conf, $langs, $user;
6589 if (empty($userused)) {
6595 if (!empty($this->array_options)) {
6597 $langs->load(
'admin');
6598 require_once DOL_DOCUMENT_ROOT.
'/core/class/extrafields.class.php';
6600 $target_extrafields = $extrafields->fetch_name_optionals_label($this->table_element);
6603 $new_array_options = array();
6604 foreach ($this->array_options as $key => $value) {
6605 if (in_array(substr($key, 8), array_keys($target_extrafields))) {
6606 $new_array_options[$key] = $value;
6607 } elseif (in_array($key, array_keys($target_extrafields))) {
6608 $new_array_options[
'options_'.$key] = $value;
6612 foreach ($new_array_options as $key => $value) {
6613 $attributeKey = substr($key, 8);
6614 $attributeType = $extrafields->attributes[$this->table_element][
'type'][$attributeKey];
6615 $attributeLabel = $langs->transnoentities($extrafields->attributes[$this->table_element][
'label'][$attributeKey]);
6616 $attributeParam = $extrafields->attributes[$this->table_element][
'param'][$attributeKey];
6617 $attributeRequired = $extrafields->attributes[$this->table_element][
'required'][$attributeKey];
6618 $attributeUnique = $extrafields->attributes[$this->table_element][
'unique'][$attributeKey];
6619 $attrfieldcomputed = $extrafields->attributes[$this->table_element][
'computed'][$attributeKey];
6623 if (!empty($this->context[
'createfromclone']) && $this->context[
'createfromclone'] ==
'createfromclone' && !empty($attributeUnique)) {
6624 $new_array_options[$key] =
null;
6628 if ($attributeRequired) {
6629 $v = $this->array_options[$key];
6631 $langs->load(
"errors");
6632 dol_syslog(
"Mandatory field '".$key.
"' is empty during create and set to required into definition of extrafields");
6633 $this->errors[] = $langs->trans(
'ErrorFieldRequired', $attributeLabel);
6641 if (!empty($attrfieldcomputed)) {
6643 $value =
dol_eval($attrfieldcomputed, 1, 0,
'2');
6644 dol_syslog($langs->trans(
"Extrafieldcomputed").
" on ".$attributeLabel.
"(".$value.
")", LOG_DEBUG);
6645 $new_array_options[$key] = $value;
6647 $new_array_options[$key] =
null;
6651 switch ($attributeType) {
6653 if (!is_numeric($value) && $value !=
'') {
6654 $this->errors[] = $langs->trans(
"ExtraFieldHasWrongValue", $attributeLabel);
6656 } elseif ($value ==
'') {
6657 $new_array_options[$key] =
null;
6663 if (!is_numeric($value) && $value !=
'') {
6664 dol_syslog($langs->trans(
"ExtraFieldHasWrongValue").
" for ".$attributeLabel.
"(".$value.
"is not '".$attributeType.
"')", LOG_DEBUG);
6665 $this->errors[] = $langs->trans(
"ExtraFieldHasWrongValue", $attributeLabel);
6667 } elseif ($value ==
'') {
6671 $new_array_options[$key] = $value;
6681 if ($this->array_options[$key] !=
'' && is_array($extrafields->attributes[$this->table_element][
'param'][$attributeKey][
'options'])) {
6683 $tmparrays = array_keys($extrafields->attributes[$this->table_element][
'param'][$attributeKey][
'options']);
6684 $algo = reset($tmparrays);
6689 if (is_object($this->oldcopy)) {
6691 if (isset($this->oldcopy->array_options[$key]) && $this->array_options[$key] == $this->oldcopy->array_options[$key]) {
6693 if ($algo ==
'dolcrypt') {
6694 if (!preg_match(
'/^dolcrypt:/', $this->array_options[$key])) {
6695 $new_array_options[$key] =
dolEncrypt($this->array_options[$key]);
6697 $new_array_options[$key] = $this->array_options[$key];
6700 $new_array_options[$key] = $this->array_options[$key];
6704 if ($algo ==
'dolcrypt') {
6705 if (!preg_match(
'/^dolcrypt:/', $this->array_options[$key])) {
6706 $new_array_options[$key] =
dolEncrypt($this->array_options[$key]);
6708 $new_array_options[$key] = $this->array_options[$key];
6711 $new_array_options[$key] =
dol_hash($this->array_options[$key], $algo);
6717 if ($algo ==
'dolcrypt' && !preg_match(
'/^dolcrypt:/', $this->array_options[$key])) {
6718 $new_array_options[$key] =
dolEncrypt($this->array_options[$key]);
6720 $new_array_options[$key] = $this->array_options[$key];
6725 $new_array_options[$key] = $this->array_options[$key];
6728 $new_array_options[$key] = $this->array_options[$key];
6734 if (!is_numeric($this->array_options[$key]) || $this->array_options[$key] != intval($this->array_options[$key])) {
6735 $this->array_options[$key] = strtotime($this->array_options[$key]);
6737 $new_array_options[$key] = $this->db->idate($this->array_options[$key]);
6741 if (!is_numeric($this->array_options[$key]) || $this->array_options[$key] != intval($this->array_options[$key])) {
6742 $this->array_options[$key] = strtotime($this->array_options[$key]);
6744 $new_array_options[$key] = $this->db->idate($this->array_options[$key],
'gmt');
6747 $param_list = array_keys($attributeParam[
'options']);
6750 $InfoFieldList = explode(
":", $param_list[0]);
6752 if ($InfoFieldList[0] && class_exists($InfoFieldList[0])) {
6753 if ($value ==
'-1') {
6754 $new_array_options[$key] =
'';
6756 $object =
new $InfoFieldList[0]($this->db);
6757 '@phan-var-force CommonObject $object';
6758 if (is_numeric($value)) {
6759 $res =
$object->fetch($value);
6761 $res =
$object->fetch(0, $value);
6765 $new_array_options[$key] =
$object->id;
6767 $this->error =
"Id/Ref '".$value.
"' for object '".
$object->element.
"' not found";
6772 dol_syslog(
'Error bad setup of extrafield', LOG_WARNING);
6777 if (is_array($this->array_options[$key])) {
6778 $new_array_options[$key] = implode(
',', $this->array_options[$key]);
6780 $new_array_options[$key] = $this->array_options[$key];
6788 $table_element = $this->table_element;
6789 if ($table_element ==
'categorie') {
6790 $table_element =
'categories';
6793 dol_syslog(get_class($this).
"::insertExtraFields delete then insert", LOG_DEBUG);
6795 $sql_del =
"DELETE FROM ".$this->db->prefix().$table_element.
"_extrafields WHERE fk_object = ".((int) $this->
id);
6796 $this->db->query($sql_del);
6798 $sql =
"INSERT INTO ".$this->db->prefix().$table_element.
"_extrafields (fk_object";
6799 foreach ($new_array_options as $key => $value) {
6800 $attributeKey = substr($key, 8);
6802 if ($extrafields->attributes[$this->table_element][
'type'][$attributeKey] !=
'separate') {
6803 $sql .=
",".$attributeKey;
6807 if (!empty($extrafields->attributes[$this->table_element][
'mandatoryfieldsofotherentities']) && is_array($extrafields->attributes[$this->table_element][
'mandatoryfieldsofotherentities'])) {
6808 foreach ($extrafields->attributes[$this->table_element][
'mandatoryfieldsofotherentities'] as $tmpkey => $tmpval) {
6809 if (!isset($extrafields->attributes[$this->table_element][
'type'][$tmpkey])) {
6810 $sql .=
",".$tmpkey;
6814 $sql .=
") VALUES (".$this->id;
6816 foreach ($new_array_options as $key => $value) {
6817 $attributeKey = substr($key, 8);
6819 if (!in_array($extrafields->attributes[$this->table_element][
'type'][$attributeKey], [
'separate',
'point',
'multipts',
'linestrg',
'polygon'])) {
6820 if ($new_array_options[$key] !=
'' || $new_array_options[$key] ==
'0') {
6821 $sql .=
",'".$this->db->escape($new_array_options[$key]).
"'";
6826 if ($extrafields->attributes[$this->table_element][
'type'][$attributeKey] ==
'point') {
6827 if (!empty($new_array_options[$key])) {
6828 $sql .=
",ST_PointFromText('".$this->db->escape($new_array_options[$key]).
"')";
6833 if ($extrafields->attributes[$this->table_element][
'type'][$attributeKey] ==
'multipts') {
6834 if (!empty($new_array_options[$key])) {
6835 $sql .=
",ST_MultiPointFromText('".$this->db->escape($new_array_options[$key]).
"')";
6840 if ($extrafields->attributes[$this->table_element][
'type'][$attributeKey] ==
'linestrg') {
6841 if (!empty($new_array_options[$key])) {
6842 $sql .=
",ST_LineFromText('".$this->db->escape($new_array_options[$key]).
"')";
6847 if ($extrafields->attributes[$this->table_element][
'type'][$attributeKey] ==
'polygon') {
6848 if (!empty($new_array_options[$key])) {
6849 $sql .=
",ST_PolyFromText('".$this->db->escape($new_array_options[$key]).
"')";
6856 if (!empty($extrafields->attributes[$this->table_element][
'mandatoryfieldsofotherentities']) && is_array($extrafields->attributes[$this->table_element][
'mandatoryfieldsofotherentities'])) {
6857 foreach ($extrafields->attributes[$this->table_element][
'mandatoryfieldsofotherentities'] as $tmpkey => $tmpval) {
6858 if (!isset($extrafields->attributes[$this->table_element][
'type'][$tmpkey])) {
6859 if (in_array($tmpval, array(
'int',
'double',
'price'))) {
6870 $resql = $this->db->query($sql);
6872 $this->error = $this->db->lasterror();
6876 if (!$error && $trigger) {
6878 $this->context = array(
'extrafieldaddupdate' => 1);
6879 $result = $this->call_trigger($trigger, $userused);
6887 $this->db->rollback();
6890 $this->db->commit();
6910 global $conf, $langs, $user;
6912 if (empty($userused)) {
6922 if (is_array($this->array_languages)) {
6923 $new_array_languages = $this->array_languages;
6925 foreach ($new_array_languages as $key => $value) {
6926 $attributeKey = $key;
6927 $attributeType = $this->fields[$attributeKey][
'type'];
6928 $attributeLabel = $this->fields[$attributeKey][
'label'];
6933 switch ($attributeType) {
6935 if (is_array($value) || (!is_numeric($value) && $value !=
'')) {
6936 $this->errors[] = $langs->trans(
"ExtraLanguageHasWrongValue", $attributeLabel);
6938 } elseif ($value ==
'') {
6939 $new_array_languages[$key] =
null;
6944 if (!is_numeric($value) && $value !=
'') {
6945 dol_syslog($langs->trans(
"ExtraLanguageHasWrongValue").
" on ".$attributeLabel.
"(".$value.
"is not '".$attributeType.
"')", LOG_DEBUG);
6946 $this->errors[] = $langs->trans(
"ExtraLanguageHasWrongValue", $attributeLabel);
6948 } elseif ($value ==
'') {
6949 $new_array_languages[$key] =
null;
6951 $new_array_languages[$key] = $value;
6965 $table_element = $this->table_element;
6966 if ($table_element ==
'categorie') {
6967 $table_element =
'categories';
6970 dol_syslog(get_class($this).
"::insertExtraLanguages delete then insert", LOG_DEBUG);
6972 foreach ($new_array_languages as $key => $langcodearray) {
6973 foreach ($langcodearray as $langcode => $value) {
6974 $sql_del =
"DELETE FROM ".$this->db->prefix().
"object_lang";
6975 $sql_del .=
" WHERE fk_object = ".((int) $this->
id).
" AND property = '".$this->db->escape($key).
"' AND type_object = '".$this->db->escape($table_element).
"'";
6976 $sql_del .=
" AND lang = '".$this->db->escape($langcode).
"'";
6977 $this->db->query($sql_del);
6979 if ($value !==
'') {
6980 $sql =
"INSERT INTO ".$this->db->prefix().
"object_lang (fk_object, property, type_object, lang, value";
6981 $sql .=
") VALUES (".$this->id.
", '".$this->db->escape($key).
"', '".$this->db->escape($table_element).
"', '".$this->db->escape($langcode).
"', '".$this->db->escape($value).
"'";
6984 $resql = $this->db->query($sql);
6986 $this->error = $this->db->lasterror();
6994 if (!$error && $trigger) {
6996 $this->context = array(
'extralanguagesaddupdate' => 1);
6997 $result = $this->call_trigger($trigger, $userused);
7005 $this->db->rollback();
7008 $this->db->commit();
7028 global $conf, $langs, $user, $hookmanager;
7034 if (empty($userused)) {
7040 if (!empty($this->array_options) && isset($this->array_options[
"options_".$key])) {
7042 $langs->load(
'admin');
7043 require_once DOL_DOCUMENT_ROOT.
'/core/class/extrafields.class.php';
7045 $extrafields->fetch_name_optionals_label($this->table_element);
7047 $value = $this->array_options[
"options_".$key];
7049 $attributeKey = $key;
7050 $attributeType = $extrafields->attributes[$this->table_element][
'type'][$key];
7051 $attributeLabel = $extrafields->attributes[$this->table_element][
'label'][$key];
7052 $attributeParam = $extrafields->attributes[$this->table_element][
'param'][$key];
7053 $attributeRequired = $extrafields->attributes[$this->table_element][
'required'][$key];
7054 $attributeUnique = $extrafields->attributes[$this->table_element][
'unique'][$attributeKey];
7055 $attrfieldcomputed = $extrafields->attributes[$this->table_element][
'computed'][$key];
7058 if ($attributeRequired) {
7059 $mandatorypb =
false;
7060 if ($attributeType ==
'link' && $this->array_options[
"options_".$key] ==
'-1') {
7061 $mandatorypb =
true;
7063 if ($this->array_options[
"options_".$key] ===
'') {
7064 $mandatorypb =
true;
7067 $langs->load(
"errors");
7068 dol_syslog(
"Mandatory field 'options_".$key.
"' is empty during update and set to required into definition of extrafields");
7069 $this->errors[] = $langs->trans(
'ErrorFieldRequired', $attributeLabel);
7075 $new_array_options = $this->array_options;
7079 if (!empty($attrfieldcomputed)) {
7081 $value =
dol_eval($attrfieldcomputed, 1, 0,
'2');
7082 dol_syslog($langs->trans(
"Extrafieldcomputed").
" on ".$attributeLabel.
"(".$value.
")", LOG_DEBUG);
7084 $new_array_options[
"options_".$key] = $value;
7086 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7088 $new_array_options[
"options_".$key] =
null;
7090 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7094 switch ($attributeType) {
7096 if (!is_numeric($value) && $value !=
'') {
7097 $this->errors[] = $langs->trans(
"ExtraFieldHasWrongValue", $attributeLabel);
7099 } elseif ($value ===
'') {
7100 $new_array_options[
"options_".$key] =
null;
7102 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7108 if (!is_numeric($value) && $value !=
'') {
7109 dol_syslog($langs->trans(
"ExtraFieldHasWrongValue").
" on ".$attributeLabel.
"(".$value.
"is not '".$attributeType.
"')", LOG_DEBUG);
7110 $this->errors[] = $langs->trans(
"ExtraFieldHasWrongValue", $attributeLabel);
7112 } elseif ($value ===
'') {
7116 $new_array_options[
"options_".$key] = $value;
7118 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7130 if ($this->array_options[
"options_".$key] !=
'' && is_array($extrafields->attributes[$this->table_element][
'param'][$attributeKey][
'options'])) {
7132 $tmparrays = array_keys($extrafields->attributes[$this->table_element][
'param'][$attributeKey][
'options']);
7133 $algo = reset($tmparrays);
7139 if (is_object($this->oldcopy)) {
7141 if (isset($this->oldcopy->array_options[
"options_".$key]) && $this->array_options[
"options_".$key] == $this->oldcopy->array_options[
"options_".$key]) {
7142 if ($algo ==
'dolcrypt') {
7143 if (!preg_match(
'/^dolcrypt:/', $this->array_options[
"options_".$key])) {
7144 $new_array_options[
"options_".$key] =
dolEncrypt($this->array_options[
"options_".$key]);
7146 $new_array_options[
"options_".$key] = $this->array_options[
"options_".$key];
7149 $new_array_options[
"options_".$key] = $this->array_options[
"options_".$key];
7152 if ($algo ==
'dolcrypt') {
7153 if (!preg_match(
'/^dolcrypt:/', $this->array_options[
"options_".$key])) {
7154 $new_array_options[
"options_".$key] =
dolEncrypt($this->array_options[
"options_".$key]);
7156 $new_array_options[
"options_".$key] = $this->array_options[
"options_".$key];
7159 $new_array_options[
"options_".$key] =
dol_hash($this->array_options[
"options_".$key], $algo);
7163 if ($algo ==
'dolcrypt' && !preg_match(
'/^dolcrypt:/', $this->array_options[
"options_".$key])) {
7164 $new_array_options[
"options_".$key] =
dolEncrypt($this->array_options[
"options_".$key]);
7166 $new_array_options[
"options_".$key] = $this->array_options[
"options_".$key];
7171 $new_array_options[
"options_".$key] = $this->array_options[
"options_".$key];
7174 $new_array_options[
"options_".$key] = $this->array_options[
"options_".$key];
7177 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7181 if (empty($this->array_options[
"options_".$key])) {
7182 $new_array_options[
"options_".$key] =
null;
7184 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7186 $new_array_options[
"options_".$key] = $this->db->idate($this->array_options[
"options_".$key]);
7190 if (empty($this->array_options[
"options_".$key])) {
7191 $new_array_options[
"options_".$key] =
null;
7193 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7195 $new_array_options[
"options_".$key] = $this->db->idate($this->array_options[
"options_".$key],
'gmt');
7199 if (empty($this->array_options[
"options_".$key])) {
7200 $new_array_options[
"options_".$key] =
null;
7202 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7206 if ($this->array_options[
"options_".$key] ===
'') {
7207 $new_array_options[
"options_".$key] =
null;
7209 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7243 $new_array_options = array();
7244 if (is_array($this->array_options[
"options_".$key])) {
7245 $new_array_options[
"options_".$key] = implode(
',', $this->array_options[
"options_".$key]);
7247 $new_array_options[
"options_".$key] = $this->array_options[
"options_".$key];
7250 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7256 $linealreadyfound = 0;
7259 $table_element = $this->table_element;
7260 if ($table_element ==
'categorie') {
7261 $table_element =
'categories';
7264 $sql =
"SELECT COUNT(rowid) as nb FROM ".$this->db->prefix().$table_element.
"_extrafields WHERE fk_object = ".((int) $this->
id);
7265 $resql = $this->db->query($sql);
7267 $tmpobj = $this->db->fetch_object($resql);
7269 $linealreadyfound = $tmpobj->nb;
7274 if ($linealreadyfound) {
7275 if ($this->array_options[
"options_".$key] ===
null) {
7276 $sql =
"UPDATE ".$this->db->prefix().$table_element.
"_extrafields SET ".$key.
" = null";
7278 $sql =
"UPDATE ".$this->db->prefix().$table_element.
"_extrafields SET ".$key.
" = '".$this->db->escape($new_array_options[
"options_".$key]).
"'";
7280 $sql .=
" WHERE fk_object = ".((int) $this->
id);
7282 $resql = $this->db->query($sql);
7285 $this->error = $this->db->lasterror();
7288 $result = $this->insertExtraFields(
'', $user);
7295 $parameters = array(
'key' => $key);
7297 $reshook = $hookmanager->executeHooks(
'updateExtraFieldBeforeCommit', $parameters, $this, $action);
7303 if (!$error && $trigger) {
7305 $this->context = array(
'extrafieldupdate' => 1);
7306 $result = $this->call_trigger($trigger, $userused);
7314 dol_syslog(__METHOD__.$this->error, LOG_ERR);
7315 $this->db->rollback();
7318 $this->db->commit();
7334 return $this->array_options[
'options_'.$key] ??
null;
7346 $this->array_options[
'options_'.$key] = $value;
7361 global $conf, $langs, $user;
7363 if (empty($userused)) {
7392 public function showInputField($val, $key, $value, $moreparam =
'', $keysuffix =
'', $keyprefix =
'', $morecss = 0, $nonewbutton = 0)
7394 global $conf, $langs, $form;
7396 if (!is_object($form)) {
7397 require_once DOL_DOCUMENT_ROOT.
'/core/class/html.form.class.php';
7398 $form =
new Form($this->db);
7401 if (!empty($this->fields)) {
7402 $val = $this->fields[$key];
7406 $fieldValidationErrorMsg =
'';
7407 $validationClass =
'';
7408 $fieldValidationErrorMsg = $this->getFieldError($key);
7409 if (!empty($fieldValidationErrorMsg)) {
7410 $validationClass =
' --error';
7412 $validationClass =
' --success';
7415 $valuemultiselectinput = array();
7420 $param[
'options'] = array();
7423 $size = !empty($this->fields[$key][
'size']) ? $this->fields[$key][
'size'] : 0;
7425 if (preg_match(
'/^(integer|link):(.*):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
7426 $param[
'options'] = array($reg[2].
':'.$reg[3].
':'.$reg[4].
':'.$reg[5] =>
'N');
7428 } elseif (preg_match(
'/^(integer|link):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
7429 $param[
'options'] = array($reg[2].
':'.$reg[3].
':'.$reg[4] =>
'N');
7431 } elseif (preg_match(
'/^(integer|link):(.*):(.*)/i', $val[
'type'], $reg)) {
7432 $param[
'options'] = array($reg[2].
':'.$reg[3] =>
'N');
7434 } elseif (preg_match(
'/^(sellist):(.*):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
7435 $param[
'options'] = array($reg[2].
':'.$reg[3].
':'.$reg[4].
':'.$reg[5] =>
'N');
7437 } elseif (preg_match(
'/^(sellist):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
7438 $param[
'options'] = array($reg[2].
':'.$reg[3].
':'.$reg[4] =>
'N');
7440 } elseif (preg_match(
'/^(sellist):(.*):(.*)/i', $val[
'type'], $reg)) {
7441 $param[
'options'] = array($reg[2].
':'.$reg[3] =>
'N');
7443 } elseif (preg_match(
'/^chkbxlst:(.*)/i', $val[
'type'], $reg)) {
7444 $param[
'options'] = array($reg[1] =>
'N');
7446 } elseif (preg_match(
'/varchar\((\d+)\)/', $val[
'type'], $reg)) {
7447 $param[
'options'] = array();
7450 } elseif (preg_match(
'/varchar/', $val[
'type'])) {
7451 $param[
'options'] = array();
7453 } elseif (preg_match(
'/stars\((\d+)\)/', $val[
'type'], $reg)) {
7454 $param[
'options'] = array();
7458 $param[
'options'] = array();
7459 $type = $this->fields[$key][
'type'];
7464 if (!empty($this->fields[$key][
'arrayofkeyval']) && is_array($this->fields[$key][
'arrayofkeyval'])) {
7465 $param[
'options'] = $this->fields[$key][
'arrayofkeyval'];
7467 if (empty($this->fields[$key][
'multiinput'])) {
7468 $type = (($this->fields[$key][
'type'] ==
'checkbox') ? $this->fields[$key][
'type'] :
'select');
7472 $label = $this->fields[$key][
'label'];
7475 $default = (!empty($this->fields[$key][
'default']) ? $this->fields[$key][
'default'] :
'');
7477 $computed = (!empty($this->fields[$key][
'computed']) ? $this->fields[$key][
'computed'] :
'');
7479 $unique = (!empty($this->fields[$key][
'unique']) ? $this->fields[$key][
'unique'] : 0);
7481 $required = (!empty($this->fields[$key][
'required']) ? $this->fields[$key][
'required'] : 0);
7483 $autofocusoncreate = (!empty($this->fields[$key][
'autofocusoncreate']) ? $this->fields[$key][
'autofocusoncreate'] : 0);
7486 $langfile = (!empty($this->fields[$key][
'langfile']) ? $this->fields[$key][
'langfile'] :
'');
7488 $list = (!empty($this->fields[$key][
'list']) ? $this->fields[$key][
'list'] : 0);
7489 $hidden = (in_array(abs($this->fields[$key][
'visible']), array(0, 2)) ? 1 : 0);
7494 if (!preg_match(
'/^search_/', $keyprefix)) {
7495 return '<span class="opacitymedium">'.$langs->trans(
"AutomaticallyCalculated").
'</span>';
7502 if (empty($morecss) && !empty($val[
'css'])) {
7503 $morecss = $val[
'css'];
7504 } elseif (empty($morecss)) {
7505 if ($type ==
'date') {
7506 $morecss =
'minwidth100imp';
7507 } elseif ($type ==
'datetime' || $type ==
'link') {
7508 $morecss =
'minwidth200imp';
7509 } elseif (in_array($type, array(
'int',
'integer',
'price')) || preg_match(
'/^double(\([0-9],[0-9]\)){0,1}/', (
string) $type)) {
7510 $morecss =
'maxwidth75';
7511 } elseif ($type ==
'url') {
7512 $morecss =
'minwidth400';
7513 } elseif ($type ==
'boolean') {
7516 if (is_numeric($size) && round((
float) $size) < 12) {
7517 $morecss =
'minwidth100';
7518 } elseif (is_numeric($size) && round((
float) $size) <= 48) {
7519 $morecss =
'minwidth200';
7521 $morecss =
'minwidth400';
7527 if (!empty($validationClass)) {
7528 $morecss .= $validationClass;
7531 if (in_array($type, array(
'date'))) {
7532 $tmp = explode(
',', $size);
7537 if (!$required && $value ==
'') {
7542 $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required,
'', 1, (($keyprefix !=
'search_' && $keyprefix !=
'search_options_') ? 1 : 0), 0, 1);
7543 } elseif (in_array($type, array(
'datetime'))) {
7544 $tmp = explode(
',', $size);
7549 if (!$required && $value ==
'') {
7554 $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required,
'', 1, (($keyprefix !=
'search_' && $keyprefix !=
'search_options_') ? 1 : 0), 0, 1,
'',
'',
'', 1,
'',
'',
'tzuserrel');
7555 } elseif (in_array($type, array(
'duration'))) {
7556 $out = $form->select_duration($keyprefix.$key.$keysuffix, $value, 0,
'text', 0, 1);
7557 } elseif (in_array($type, array(
'int',
'integer'))) {
7558 $tmp = explode(
',', $size);
7560 $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' :
'').
'>';
7561 } elseif (in_array($type, array(
'real'))) {
7562 $out =
'<input type="text" class="flat '.$morecss.
'" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.
dol_escape_htmltag($value).
'"'.($moreparam ? $moreparam :
'').($autofocusoncreate ?
' autofocus' :
'').
'>';
7563 } elseif (preg_match(
'/varchar/', (
string) $type)) {
7564 $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 :
'').($autofocusoncreate ?
' autofocus' :
'').
'>';
7565 } elseif (in_array($type, array(
'email',
'mail',
'phone',
'url',
'ip'))) {
7566 $out =
'<input type="text" class="flat '.$morecss.
'" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.
dol_escape_htmltag($value).
'" '.($moreparam ? $moreparam :
'').($autofocusoncreate ?
' autofocus' :
'').
'>';
7567 } elseif (preg_match(
'/^text/', (
string) $type)) {
7568 if (!preg_match(
'/search_/', $keyprefix)) {
7569 if (!empty($param[
'options'])) {
7572 $out .= $form->selectarray($keyprefix.$key.$keysuffix.
"_multiinput", $param[
'options'],
'', 1, 0, 0,
"flat maxwidthonphone".$morecss);
7573 $out .=
'<input id="'.$keyprefix.$key.$keysuffix.
'_multiinputadd" type="button" class="button" value="'.$langs->trans(
"Add").
'">';
7576 function handlemultiinputdisabling(htmlname){
7577 console.log("We handle the disabling of used options for "+htmlname+"_multiinput");
7578 multiinput = $("#"+htmlname+"_multiinput");
7579 multiinput.find("option").each(function(){
7580 tmpval = $("#"+htmlname).val();
7581 tmpvalarray = tmpval.split("\n");
7582 valtotest = $(this).val();
7583 if(tmpvalarray.includes(valtotest)){
7584 $(this).prop("disabled",true);
7586 if($(this).prop("disabled") == true){
7587 console.log(valtotest)
7588 $(this).prop("disabled", false);
7594 $(document).ready(function () {
7595 $("#'.$keyprefix.$key.$keysuffix.
'_multiinputadd").on("click",function() {
7596 tmpval = $("#'.$keyprefix.$key.$keysuffix.
'").val();
7597 tmpvalarray = tmpval.split(",");
7598 valtotest = $("#'.$keyprefix.$key.$keysuffix.
'_multiinput").val();
7599 if(valtotest != -1 && !tmpvalarray.includes(valtotest)){
7600 console.log("We add the selected value to the text area '.$keyprefix.$key.$keysuffix.
'");
7604 tmpval = tmpval + "\n" + valtotest;
7606 $("#'.$keyprefix.$key.$keysuffix.
'").val(tmpval);
7607 handlemultiinputdisabling("'.$keyprefix.$key.$keysuffix.
'");
7608 $("#'.$keyprefix.$key.$keysuffix.
'_multiinput").val(-1);
7610 console.log("We add nothing the text area '.$keyprefix.$key.$keysuffix.
'");
7613 $("#'.$keyprefix.$key.$keysuffix.
'").on("change",function(){
7614 handlemultiinputdisabling("'.$keyprefix.$key.$keysuffix.
'");
7616 handlemultiinputdisabling("'.$keyprefix.$key.$keysuffix.
'");
7618 $out .=
"</script>";
7619 $value = str_replace(
',',
"\n", $value);
7621 require_once DOL_DOCUMENT_ROOT.
'/core/class/doleditor.class.php';
7622 $doleditor =
new DolEditor($keyprefix.$key.$keysuffix, $value,
'', 200,
'dolibarr_notes',
'In',
false,
false,
false, ROWS_5,
'90%');
7623 $out .= (string) $doleditor->Create(1,
'',
true,
'',
'',
'', $morecss);
7625 $out =
'<input type="text" class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.
dol_escape_htmltag($value).
'" '.($moreparam ? $moreparam :
'').
'>';
7627 } elseif (preg_match(
'/^html/', (
string) $type)) {
7628 if (!preg_match(
'/search_/', $keyprefix)) {
7629 require_once DOL_DOCUMENT_ROOT.
'/core/class/doleditor.class.php';
7630 $doleditor =
new DolEditor($keyprefix.$key.$keysuffix, $value,
'', 200,
'dolibarr_notes',
'In',
false,
false, isModEnabled(
'fckeditor') &&
getDolGlobalInt(
'FCKEDITOR_ENABLE_SOCIETE'), ROWS_5,
'90%');
7631 $out = (string) $doleditor->Create(1,
'',
true,
'',
'', $moreparam, $morecss);
7633 $out =
'<input type="text" class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.
dol_escape_htmltag($value).
'" '.($moreparam ? $moreparam :
'').
'>';
7635 } elseif ($type ==
'boolean') {
7637 if (!empty($value)) {
7638 $checked =
' checked value="1" ';
7640 $checked =
' value="1" ';
7642 $out =
'<input type="checkbox" class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" '.$checked.
' '.($moreparam ? $moreparam :
'').
'>';
7643 } elseif ($type ==
'price') {
7644 if (!empty($value)) {
7645 $value =
price($value);
7647 $out =
'<input type="text" class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.$value.
'" '.($moreparam ? $moreparam :
'').
'> '.$langs->getCurrencySymbol($conf->currency);
7648 } elseif ($type ==
'stars') {
7649 $out =
'<input type="hidden" class="flat '.$morecss.
'" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.
dol_escape_htmltag($value).
'"'.($moreparam ? $moreparam :
'').($autofocusoncreate ?
' autofocus' :
'').
'>';
7650 $out .=
'<div class="star-selection" id="'.$keyprefix.$key.$keysuffix.
'_selection">';
7652 while ($i <= $size) {
7653 $out .=
'<span class="star" data-value="'.$i.
'">'.
img_picto(
'',
'fontawesome_star_fas').
'</span>';
7658 jQuery(function($) {
7659 let container = $("#'.$keyprefix.$key.$keysuffix.
'_selection");
7660 let selectedStars = parseInt($("#'.$keyprefix.$key.$keysuffix.
'").val()) || 0;
7661 container.find(".star").each(function() {
7662 $(this).toggleClass("active", $(this).data("value") <= selectedStars);
7664 container.find(".star").on("mouseover", function() {
7665 let selectedStar = $(this).data("value");
7666 container.find(".star").each(function() {
7667 $(this).toggleClass("active", $(this).data("value") <= selectedStar);
7670 container.on("mouseout", function() {
7671 container.find(".star").each(function() {
7672 $(this).toggleClass("active", $(this).data("value") <= selectedStars);
7675 container.find(".star").off("click").on("click", function() {
7676 selectedStars = $(this).data("value");
7677 if (selectedStars === 1 && $("#'.$keyprefix.$key.$keysuffix.
'").val() == 1) {
7680 $("#'.$keyprefix.$key.$keysuffix.
'").val(selectedStars);
7681 container.find(".star").each(function() {
7682 $(this).toggleClass("active", $(this).data("value") <= selectedStars);
7687 } elseif (preg_match(
'/^double(\([0-9],[0-9]\)){0,1}/', (
string) $type)) {
7688 if (!empty($value)) {
7689 $value =
price($value);
7691 $out =
'<input type="text" class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.$value.
'" '.($moreparam ? $moreparam :
'').
'> ';
7692 } elseif ($type ==
'select') {
7694 if (!empty($conf->use_javascript_ajax) && !
getDolGlobalString(
'MAIN_EXTRAFIELDS_DISABLE_SELECT2')) {
7695 include_once DOL_DOCUMENT_ROOT.
'/core/lib/ajax.lib.php';
7696 $out .=
ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
7701 foreach ($param[
'options'] as $keyb => $valb) {
7702 if ((
string) $keyb ==
'') {
7705 if (strpos($valb,
"|") !==
false) {
7706 list($valb, $parent) = explode(
'|', $valb);
7709 $tmpselect .=
'<option value="'.$keyb.
'"';
7710 $tmpselect .= (((string) $value == (
string) $keyb) ?
' selected' :
'');
7711 if (!empty($parent)) {
7714 $tmpselect .= (!empty($parent) ?
' parent="'.$parent.
'"' :
'');
7715 $tmpselect .=
'>'.$langs->trans($valb).
'</option>';
7718 $out .=
'<select class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" '.($moreparam ? $moreparam :
'').
'>';
7719 if ((!isset($this->fields[$key][
'default'])) || ($this->fields[$key][
'notnull'] != 1) || $nbchoice >= 2) {
7720 $out .=
'<option value="0"> </option>';
7723 $out .=
'</select>';
7724 } elseif ($type ==
'sellist') {
7726 if (!empty($conf->use_javascript_ajax) && !
getDolGlobalString(
'MAIN_EXTRAFIELDS_DISABLE_SELECT2')) {
7727 include_once DOL_DOCUMENT_ROOT.
'/core/lib/ajax.lib.php';
7728 $out .=
ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
7731 $out .=
'<select class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" '.($moreparam ? $moreparam :
'').
'>';
7732 if (is_array($param[
'options'])) {
7733 $tmpparamoptions = array_keys($param[
'options']);
7734 $paramoptions = preg_split(
'/[\r\n]+/', $tmpparamoptions[0]);
7736 $InfoFieldList = explode(
":", $paramoptions[0], 5);
7748 if (! empty($InfoFieldList[4])) {
7750 $parenthesisopen = 0;
7751 while (substr($InfoFieldList[4], $pos, 1) !==
'' && ($parenthesisopen || $pos == 0 || substr($InfoFieldList[4], $pos, 1) !=
':')) {
7752 if (substr($InfoFieldList[4], $pos, 1) ==
'(') {
7755 if (substr($InfoFieldList[4], $pos, 1) ==
')') {
7760 $tmpbefore = substr($InfoFieldList[4], 0, $pos);
7761 $tmpafter = substr($InfoFieldList[4], $pos + 1);
7763 $InfoFieldList[4] = $tmpbefore;
7764 if ($tmpafter !==
'') {
7765 $InfoFieldList = array_merge($InfoFieldList, explode(
':', $tmpafter));
7771 if (preg_match(
'/^\(?([a-z0-9]+)([=<>]+)(\d+)\)?$/i', $InfoFieldList[4], $reg)) {
7772 $InfoFieldList[4] =
'('.$reg[1].
':'.$reg[2].
':'.$reg[3].
')';
7783 $keyList = (empty($InfoFieldList[2]) ?
'rowid' : $InfoFieldList[2].
' as rowid');
7785 if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
7786 if (strpos($InfoFieldList[4],
'extra.') !==
false) {
7787 $keyList =
'main.'.$InfoFieldList[2].
' as rowid';
7789 $keyList = $InfoFieldList[2].
' as rowid';
7792 if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
7793 list($parentName, $parentField) = explode(
'|', $InfoFieldList[3]);
7794 $keyList .=
', '.$parentField;
7797 $filter_categorie =
false;
7798 if (count($InfoFieldList) > 5) {
7799 if ($InfoFieldList[0] ==
'categorie') {
7800 $filter_categorie =
true;
7804 if (!$filter_categorie) {
7805 $fields_label = explode(
'|', $InfoFieldList[1]);
7806 if (is_array($fields_label)) {
7808 $keyList .= implode(
', ', $fields_label);
7812 $sql =
"SELECT " . $keyList;
7813 $sql .=
" FROM " . $this->db->prefix() . $InfoFieldList[0];
7815 if (!empty($InfoFieldList[4])) {
7817 if (strpos($InfoFieldList[4],
'$SEL$') !==
false) {
7818 $InfoFieldList[4] = str_replace(
'$SEL$',
'SELECT', $InfoFieldList[4]);
7822 if (strpos($InfoFieldList[4],
'$ID$') !==
false && !empty($objectid)) {
7823 $InfoFieldList[4] = str_replace(
'$ID$', (
string) $objectid, $InfoFieldList[4]);
7825 $InfoFieldList[4] = str_replace(
'$ID$',
'0', $InfoFieldList[4]);
7830 if (strpos($InfoFieldList[4],
'extra') !==
false) {
7831 $sql .=
" as main, " . $this->db->sanitize($this->db->prefix() . $InfoFieldList[0]) .
"_extrafields as extra";
7832 $sqlwhere .=
" WHERE extra.fk_object = main." . $this->db->sanitize($InfoFieldList[2]);
7838 $sqlwhere .=
' WHERE 1=1';
7855 if (in_array($InfoFieldList[0], array(
'tablewithentity'))) {
7856 $sqlwhere .=
" AND entity = " . ((int) $conf->entity);
7862 if (isset($InfoFieldList[7]) && preg_match(
'/^[a-z0-9_\-,]+$/i', $InfoFieldList[7])) {
7863 $sql .=
" ORDER BY ".$this->db->escape($InfoFieldList[7]);
7865 $sql .=
" ORDER BY ".$this->db->sanitize(implode(
', ', $fields_label));
7868 dol_syslog(get_class($this) .
'::showInputField type=sellist', LOG_DEBUG);
7869 $resql = $this->db->query($sql);
7871 $out .=
'<option value="0"> </option>';
7872 $num = $this->db->num_rows($resql);
7876 $obj = $this->db->fetch_object($resql);
7880 $fields_label = explode(
'|', $InfoFieldList[1]);
7881 if (count($fields_label) > 1) {
7883 foreach ($fields_label as $field_toshow) {
7884 $labeltoshow .= $obj->$field_toshow .
' ';
7887 $labeltoshow = $obj->{$InfoFieldList[1]};
7889 $labeltoshow =
dol_trunc($labeltoshow, 45);
7891 if ($value == $obj->rowid) {
7892 foreach ($fields_label as $field_toshow) {
7893 $translabel = $langs->trans($obj->$field_toshow);
7894 if ($translabel != $obj->$field_toshow) {
7895 $labeltoshow =
dol_trunc($translabel) .
' ';
7897 $labeltoshow =
dol_trunc($obj->$field_toshow) .
' ';
7900 $out .=
'<option value="' . $obj->rowid .
'" selected>' . $labeltoshow .
'</option>';
7903 $translabel = $langs->trans($obj->{$InfoFieldList[1]});
7904 if ($translabel != $obj->{$InfoFieldList[1]}) {
7905 $labeltoshow =
dol_trunc($translabel, 18);
7907 $labeltoshow =
dol_trunc($obj->{$InfoFieldList[1]});
7910 if (empty($labeltoshow)) {
7911 $labeltoshow =
'(not defined)';
7913 if ($value == $obj->rowid) {
7914 $out .=
'<option value="' . $obj->rowid .
'" selected>' . $labeltoshow .
'</option>';
7917 if (!empty($InfoFieldList[3]) && $parentField) {
7918 $parent = $parentName .
':' . $obj->{$parentField};
7922 $out .=
'<option value="' . $obj->rowid .
'"';
7923 $out .= ($value == $obj->rowid ?
' selected' :
'');
7924 $out .= (!empty($parent) ?
' parent="' . $parent .
'"' :
'');
7925 $out .=
'>' . $labeltoshow .
'</option>';
7930 $this->db->free($resql);
7932 print
'Error in request ' . $sql .
' ' . $this->db->lasterror() .
'. Check setup of extra parameters.<br>';
7935 require_once DOL_DOCUMENT_ROOT.
'/categories/class/categorie.class.php';
7936 $data = $form->select_all_categories(Categorie::$MAP_ID_TO_CODE[$InfoFieldList[5]],
'',
'parent', 64, $InfoFieldList[6], 1, 1);
7937 $out .=
'<option value="0"> </option>';
7938 foreach ($data as $data_key => $data_value) {
7939 $out .=
'<option value="' . $data_key .
'"';
7940 $out .= ($value == $data_key ?
' selected' :
'');
7941 $out .=
'>' . $data_value .
'</option>';
7945 $out .=
'</select>';
7946 } elseif ($type ==
'checkbox') {
7947 $value_arr = explode(
',', $value);
7948 $out = $form->multiselectarray($keyprefix.$key.$keysuffix, (empty($param[
'options']) ?
null : $param[
'options']), $value_arr, 0, 0, $morecss, 0,
'100%');
7949 } elseif ($type ==
'radio') {
7951 foreach ($param[
'options'] as $keyopt => $valopt) {
7952 $out .=
'<input class="flat '.$morecss.
'" type="radio" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" '.($moreparam ? $moreparam :
'');
7953 $out .=
' value="'.$keyopt.
'"';
7954 $out .=
' id="'.$keyprefix.$key.$keysuffix.
'_'.$keyopt.
'"';
7955 $out .= ($value == $keyopt ?
'checked' :
'');
7956 $out .=
'/><label for="'.$keyprefix.$key.$keysuffix.
'_'.$keyopt.
'">'.$valopt.
'</label><br>';
7958 } elseif ($type ==
'chkbxlst') {
7959 if (is_array($value)) {
7960 $value_arr = $value;
7962 $value_arr = explode(
',', $value);
7965 if (is_array($param[
'options'])) {
7966 $tmpparamoptions = array_keys($param[
'options']);
7967 $paramoptions = preg_split(
'/[\r\n]+/', $tmpparamoptions[0]);
7969 $InfoFieldList = explode(
":", $paramoptions[0], 5);
7981 if (! empty($InfoFieldList[4])) {
7983 $parenthesisopen = 0;
7984 while (substr($InfoFieldList[4], $pos, 1) !==
'' && ($parenthesisopen || $pos == 0 || substr($InfoFieldList[4], $pos, 1) !=
':')) {
7985 if (substr($InfoFieldList[4], $pos, 1) ==
'(') {
7988 if (substr($InfoFieldList[4], $pos, 1) ==
')') {
7993 $tmpbefore = substr($InfoFieldList[4], 0, $pos);
7994 $tmpafter = substr($InfoFieldList[4], $pos + 1);
7996 $InfoFieldList[4] = $tmpbefore;
7997 if ($tmpafter !==
'') {
7998 $InfoFieldList = array_merge($InfoFieldList, explode(
':', $tmpafter));
8003 if (preg_match(
'/^\(?([a-z0-9]+)([=<>]+)(\d+)\)?$/i', $InfoFieldList[4], $reg)) {
8004 $InfoFieldList[4] =
'('.$reg[1].
':'.$reg[2].
':'.$reg[3].
')';
8012 '@phan-var-force array{0:string,1:string,2:string,3:string,3:string,5:string,6:string} $InfoFieldList';
8017 $keyList = (empty($InfoFieldList[2]) ?
'rowid' : $InfoFieldList[2].
' as rowid');
8019 if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
8020 list($parentName, $parentField) = explode(
'|', $InfoFieldList[3]);
8021 $keyList .=
', '.$parentField;
8023 if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
8024 if (strpos($InfoFieldList[4],
'extra.') !==
false) {
8025 $keyList =
'main.'.$InfoFieldList[2].
' as rowid';
8027 $keyList = $InfoFieldList[2].
' as rowid';
8031 $filter_categorie =
false;
8032 if (count($InfoFieldList) > 5) {
8033 if ($InfoFieldList[0] ==
'categorie') {
8034 $filter_categorie =
true;
8039 if (!$filter_categorie) {
8040 $fields_label = explode(
'|', $InfoFieldList[1]);
8041 if (is_array($fields_label)) {
8043 $keyList .= implode(
', ', $fields_label);
8047 $sql =
"SELECT " . $keyList;
8048 $sql .=
' FROM ' . $this->db->prefix() . $InfoFieldList[0];
8050 if (!empty($InfoFieldList[4])) {
8052 if (strpos($InfoFieldList[4],
'$SEL$') !==
false) {
8053 $InfoFieldList[4] = str_replace(
'$SEL$',
'SELECT', $InfoFieldList[4]);
8057 if (strpos($InfoFieldList[4],
'$ID$') !==
false && !empty($objectid)) {
8058 $InfoFieldList[4] = str_replace(
'$ID$', (
string) $objectid, $InfoFieldList[4]);
8060 $InfoFieldList[4] = str_replace(
'$ID$',
'0', $InfoFieldList[4]);
8065 if (strpos($InfoFieldList[4],
'extra') !==
false) {
8066 $sql .=
' as main, ' . $this->db->sanitize($this->db->prefix() . $InfoFieldList[0]) .
'_extrafields as extra';
8067 $sqlwhere .=
" WHERE extra.fk_object = main." . $this->db->sanitize($InfoFieldList[2]);
8068 $sqlwhere .=
" AND " . $InfoFieldList[4];
8070 $sqlwhere .=
" WHERE " . $InfoFieldList[4];
8073 $sqlwhere .=
' WHERE 1=1';
8090 if (in_array($InfoFieldList[0], array(
'tablewithentity'))) {
8091 $sqlwhere .=
" AND entity = " . ((int) $conf->entity);
8098 dol_syslog(get_class($this) .
'::showInputField type=chkbxlst', LOG_DEBUG);
8100 $resql = $this->db->query($sql);
8102 $num = $this->db->num_rows($resql);
8109 $obj = $this->db->fetch_object($resql);
8113 $fields_label = explode(
'|', $InfoFieldList[1]);
8114 if (count($fields_label) > 1) {
8116 foreach ($fields_label as $field_toshow) {
8117 $labeltoshow .= $obj->$field_toshow .
' ';
8120 $labeltoshow = $obj->{$InfoFieldList[1]};
8122 $labeltoshow =
dol_trunc($labeltoshow, 45);
8124 if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
8125 foreach ($fields_label as $field_toshow) {
8126 $translabel = $langs->trans($obj->$field_toshow);
8127 if ($translabel != $obj->$field_toshow) {
8128 $labeltoshow =
dol_trunc($translabel, 18) .
' ';
8130 $labeltoshow =
dol_trunc($obj->$field_toshow, 18) .
' ';
8134 $data[$obj->rowid] = $labeltoshow;
8137 $translabel = $langs->trans($obj->{$InfoFieldList[1]});
8138 if ($translabel != $obj->{$InfoFieldList[1]}) {
8139 $labeltoshow =
dol_trunc($translabel, 18);
8141 $labeltoshow =
dol_trunc($obj->{$InfoFieldList[1]}, 18);
8144 if (empty($labeltoshow)) {
8145 $labeltoshow =
'(not defined)';
8148 if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
8149 $data[$obj->rowid] = $labeltoshow;
8152 if (!empty($InfoFieldList[3]) && $parentField) {
8153 $parent = $parentName .
':' . $obj->{$parentField};
8157 $data[(int) $obj->rowid] = $labeltoshow;
8162 $this->db->free($resql);
8164 $out = $form->multiselectarray($keyprefix . $key . $keysuffix, $data, $value_arr, 0, 0, $morecss, 0,
'100%');
8166 print
'Error in request ' . $sql .
' ' . $this->db->lasterror() .
'. Check setup of extra parameters.<br>';
8169 require_once DOL_DOCUMENT_ROOT.
'/categories/class/categorie.class.php';
8170 $data = $form->select_all_categories(Categorie::$MAP_ID_TO_CODE[(
int) $InfoFieldList[5]],
'',
'parent', 64, $InfoFieldList[6], 1, 1);
8171 $out = $form->multiselectarray($keyprefix . $key . $keysuffix, $data, $value_arr, 0, 0, $morecss, 0,
'100%');
8174 } elseif ($type ==
'link') {
8177 $param_list = array_keys($param[
'options']);
8178 $param_list_array = explode(
':', $param_list[0], 4);
8180 $showempty = (($required && $default !=
'') ? 0 : 1);
8182 if (!preg_match(
'/search_/', $keyprefix)) {
8183 if (!empty($param_list_array[2])) {
8185 if (!empty($this->fields[$key][
'picto'])) {
8186 $morecss .=
' widthcentpercentminusxx';
8188 $morecss .=
' widthcentpercentminusx';
8192 if (!empty($this->fields[$key][
'picto'])) {
8193 $morecss .=
' widthcentpercentminusx';
8197 $objectfield = $this->element.($this->module ?
'@'.$this->module :
'').
':'.$key.$keysuffix;
8198 $out = $form->selectForForms($param_list_array[0], $keyprefix.$key.$keysuffix, $value, $showempty,
'',
'', $morecss, $moreparam, 0, (empty($val[
'disabled']) ? 0 : 1),
'', $objectfield);
8200 if (!empty($param_list_array[2])) {
8201 if ((!GETPOSTISSET(
'backtopage') || strpos(
GETPOST(
'backtopage'), $_SERVER[
'PHP_SELF']) === 0)
8202 && empty($val[
'disabled']) && empty($nonewbutton)) {
8203 list($class, $classfile) = explode(
':', $param_list[0]);
8204 if (file_exists(
dol_buildpath(dirname(dirname($classfile)).
'/card.php'))) {
8205 $url_path =
dol_buildpath(dirname(dirname($classfile)).
'/card.php', 1);
8207 $url_path =
dol_buildpath(dirname(dirname($classfile)).
'/'.strtolower($class).
'_card.php', 1);
8209 $paramforthenewlink =
'';
8210 $paramforthenewlink .= (GETPOSTISSET(
'action') ?
'&action='.GETPOST(
'action',
'aZ09') :
'');
8211 $paramforthenewlink .= (GETPOSTISSET(
'id') ?
'&id='.GETPOSTINT(
'id') :
'');
8212 $paramforthenewlink .= (GETPOSTISSET(
'origin') ?
'&origin='.GETPOST(
'origin',
'aZ09') :
'');
8213 $paramforthenewlink .= (GETPOSTISSET(
'originid') ?
'&originid='.GETPOSTINT(
'originid') :
'');
8214 $paramforthenewlink .=
'&fk_'.strtolower($class).
'=--IDFORBACKTOPAGE--';
8216 $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>';
8219 } elseif ($type ==
'password') {
8221 if ($keyprefix.$key.$keysuffix ==
'pass_crypted') {
8222 $out =
'<input type="'.($keyprefix ==
'search_' ?
'text' :
'password').
'" class="flat '.$morecss.
'" name="pass" id="pass" value="" '.($moreparam ? $moreparam :
'').
'>';
8223 $out .=
'<input type="hidden" name="pass_crypted" id="pass_crypted" value="'.$value.
'" '.($moreparam ? $moreparam :
'').
'>';
8225 $out =
'<input type="'.($keyprefix ==
'search_' ?
'text' :
'password').
'" class="flat '.$morecss.
'" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.$value.
'" '.($moreparam ? $moreparam :
'').
'>';
8227 } elseif ($type ==
'array') {
8229 $newval[
'type'] =
'varchar(256)';
8232 if (!empty($value)) {
8233 foreach ($value as $option) {
8234 $out .=
'<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).
'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
8235 $out .= $this->showInputField($newval, $keyprefix.$key.$keysuffix.
'[]', $option, $moreparam,
'',
'', $morecss).
'<br></span>';
8238 $out .=
'<a id="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).
'_add" href="javascript:;"><span class="fa fa-plus-circle valignmiddle"></span></a>';
8240 $newInput =
'<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).
'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
8241 $newInput .= $this->showInputField($newval, $keyprefix.$key.$keysuffix.
'[]',
'', $moreparam,
'',
'', $morecss).
'<br></span>';
8243 if (!empty($conf->use_javascript_ajax)) {
8245 <script nonce="'.getNonce().
'">
8246 $(document).ready(function() {
8247 $("a#'.
dol_escape_js($keyprefix.$key.$keysuffix).
'_add").click(function() {
8251 $(document).on("click", "a.'.
dol_escape_js($keyprefix.$key.$keysuffix).
'_del", function() {
8252 $(this).parent().remove();
8258 if (!empty($hidden)) {
8259 $out =
'<input type="hidden" value="'.$value.
'" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'"/>';
8262 if ($isDependList == 1) {
8263 $out .= $this->getJSListDependancies(
'_common');
8271 if (!empty($fieldValidationErrorMsg) && function_exists(
'getFieldErrorIcon')) {
8272 $out .=
' '.getFieldErrorIcon($fieldValidationErrorMsg);
8291 public function showOutputField($val, $key, $value, $moreparam =
'', $keysuffix =
'', $keyprefix =
'', $morecss =
'')
8293 global $conf, $langs, $form;
8295 if (!is_object($form)) {
8296 require_once DOL_DOCUMENT_ROOT.
'/core/class/html.form.class.php';
8297 $form =
new Form($this->db);
8301 $type = empty($val[
'type']) ?
'' : $val[
'type'];
8302 $size = empty($val[
'css']) ?
'' : $val[
'css'];
8306 if (preg_match(
'/varchar\((\d+)\)/', $type, $reg)) {
8309 } elseif (preg_match(
'/varchar/', $type)) {
8312 if (!empty($val[
'arrayofkeyval']) && is_array($val[
'arrayofkeyval'])) {
8314 if (empty($this->fields[$key][
'multiinput'])) {
8315 $type = (($this->fields[$key][
'type'] ==
'checkbox') ? $this->fields[$key][
'type'] :
'select');
8318 if (preg_match(
'/^integer:(.*):(.*)/i', $val[
'type'], $reg)) {
8322 $default = empty($val[
'default']) ?
'' : $val[
'default'];
8323 $computed = empty($val[
'computed']) ?
'' : $val[
'computed'];
8324 $unique = empty($val[
'unique']) ?
'' : $val[
'unique'];
8325 $required = empty($val[
'required']) ?
'' : $val[
'required'];
8327 $param[
'options'] = array();
8329 if (!empty($val[
'arrayofkeyval']) && is_array($val[
'arrayofkeyval'])) {
8330 $param[
'options'] = $val[
'arrayofkeyval'];
8332 if (preg_match(
'/^integer:([^:]*):([^:]*)/i', $val[
'type'], $reg)) {
8334 $stringforoptions = $reg[1].
':'.$reg[2];
8336 if ($reg[1] ==
'User') {
8337 $stringforoptions .=
':#getnomurlparam1=-1';
8339 $param[
'options'] = array($stringforoptions => $stringforoptions);
8340 } elseif (preg_match(
'/^sellist:(.*):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
8341 $param[
'options'] = array($reg[1].
':'.$reg[2].
':'.$reg[3].
':'.$reg[4] =>
'N');
8343 } elseif (preg_match(
'/^sellist:(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
8344 $param[
'options'] = array($reg[1].
':'.$reg[2].
':'.$reg[3] =>
'N');
8346 } elseif (preg_match(
'/^sellist:(.*):(.*)/i', $val[
'type'], $reg)) {
8347 $param[
'options'] = array($reg[1].
':'.$reg[2] =>
'N');
8349 } elseif (preg_match(
'/^chkbxlst:(.*)/i', $val[
'type'], $reg)) {
8350 $param[
'options'] = array($reg[1] =>
'N');
8352 } elseif (preg_match(
'/stars\((\d+)\)/', $val[
'type'], $reg)) {
8353 $param[
'options'] = array();
8358 $langfile = empty($val[
'langfile']) ?
'' : $val[
'langfile'];
8359 $list = (empty($val[
'list']) ?
'' : $val[
'list']);
8360 $help = (empty($val[
'help']) ?
'' : $val[
'help']);
8361 $hidden = (($val[
'visible'] == 0) ? 1 : 0);
8371 $value =
dol_eval($computed, 1, 0,
'2');
8374 if (empty($morecss)) {
8375 if ($type ==
'date') {
8376 $morecss =
'minwidth100imp';
8377 } elseif ($type ==
'datetime' || $type ==
'timestamp') {
8378 $morecss =
'minwidth200imp';
8379 } elseif (in_array($type, array(
'int',
'double',
'price'))) {
8380 $morecss =
'maxwidth75';
8381 } elseif ($type ==
'url') {
8382 $morecss =
'minwidth400';
8383 } elseif ($type ==
'boolean') {
8386 if (is_numeric($size) && round((
float) $size) < 12) {
8387 $morecss =
'minwidth100';
8388 } elseif (is_numeric($size) && round((
float) $size) <= 48) {
8389 $morecss =
'minwidth200';
8391 $morecss =
'minwidth400';
8397 if (in_array($key, array(
'rowid',
'ref')) && method_exists($this,
'getNomUrl')) {
8399 if ($key !=
'rowid' || empty($this->fields[
'ref'])) {
8400 $value = $this->getNomUrl(1,
'', 0,
'', 1);
8402 } elseif ($key ==
'status' && method_exists($this,
'getLibStatut')) {
8403 $value = $this->getLibStatut(3);
8404 } elseif ($type ==
'date') {
8405 if (!empty($value)) {
8410 } elseif ($type ==
'datetime' || $type ==
'timestamp') {
8411 if (!empty($value)) {
8416 } elseif ($type ==
'duration') {
8417 include_once DOL_DOCUMENT_ROOT.
'/core/lib/date.lib.php';
8418 if (!is_null($value) && $value !==
'') {
8421 } elseif ($type ==
'double' || $type ==
'real') {
8422 if (!is_null($value) && $value !==
'') {
8423 $value =
price($value);
8425 } elseif ($type ==
'boolean') {
8427 if (!empty($value)) {
8428 $checked =
' checked ';
8431 $value =
'<input type="checkbox" '.$checked.
' '.($moreparam ? $moreparam :
'').
' readonly disabled>';
8433 $value =
yn($value ? 1 : 0);
8435 } elseif ($type ==
'mail' || $type ==
'email') {
8437 } elseif ($type ==
'url') {
8439 } elseif ($type ==
'phone') {
8441 } elseif ($type ==
'ip') {
8443 } elseif ($type ==
'stars') {
8444 $value =
'<input type="hidden" class="flat '.$morecss.
'" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.$this->id.
'" value="'.
dol_escape_htmltag($value).
'"'.($moreparam ? $moreparam :
'').
'>';
8445 $value .=
'<div class="star-selection" id="'.$keyprefix.$key.$keysuffix.$this->id.
'_selection">';
8447 while ($i <= $size) {
8448 $value .=
'<span class="star" data-value="'.$i.
'">'.
img_picto(
'',
'fontawesome_star_fas').
'</span>';
8453 $(document).ready(function() {
8454 let container = $("#'.$keyprefix.$key.$keysuffix.$this->id.
'_selection");
8455 let selectedStars = parseInt($("#'.$keyprefix.$key.$keysuffix.$this->id.
'").val()) || 0;
8456 container.find(".star").each(function() {
8457 $(this).toggleClass("active", $(this).data("value") <= selectedStars);
8459 container.find(".star").on("mouseover", function() {
8460 let selectedStar = $(this).data("value");
8461 container.find(".star").each(function() {
8462 $(this).toggleClass("active", $(this).data("value") <= selectedStar);
8465 container.on("mouseout", function() {
8466 container.find(".star").each(function() {
8467 $(this).toggleClass("active", $(this).data("value") <= selectedStars);
8470 container.find(".star").off("click").on("click", function() {
8471 selectedStars = $(this).data("value");
8472 if (selectedStars == 1 && $("#'.$keyprefix.$key.$keysuffix.$this->id.
'").val() == 1) {
8475 container.find("#'.$keyprefix.$key.$keysuffix.$this->id.
'").val(selectedStars);
8476 container.find(".star").each(function() {
8477 $(this).toggleClass("active", $(this).data("value") <= selectedStars);
8480 url: "ajax/'.$this->element.
'.php",
8483 objectId: "'.$this->
id.
'",
8484 field: "'.$keyprefix.$key.$keysuffix.
'",
8485 value: selectedStars,
8488 success: function(response) {
8489 var res = JSON.parse(response);
8490 console[res.status === "success" ? "log" : "error"](res.message);
8492 error: function(xhr, status, error) {
8493 console.log("Ajax request failed while updating '.$keyprefix.$key.$keysuffix.
':", error);
8499 } elseif ($type ==
'price') {
8500 if (!is_null($value) && $value !==
'') {
8501 $value =
price($value, 0, $langs, 0, 0, -1, $conf->currency);
8503 } elseif ($type ==
'select') {
8504 $value = isset($param[
'options'][(
string) $value]) ? $param[
'options'][(string) $value] :
'';
8505 if (strpos($value,
"|") !==
false) {
8506 $value = $langs->trans(explode(
'|', $value)[0]);
8507 } elseif (! is_numeric($value)) {
8508 $value = $langs->trans($value);
8510 } elseif ($type ==
'sellist') {
8511 $param_list = array_keys($param[
'options']);
8512 $InfoFieldList = explode(
":", $param_list[0]);
8514 $selectkey =
"rowid";
8517 if (count($InfoFieldList) > 2 && !empty($InfoFieldList[2])) {
8518 $selectkey = $InfoFieldList[2];
8519 $keyList = $InfoFieldList[2].
' as rowid';
8522 $fields_label = explode(
'|', $InfoFieldList[1]);
8523 if (is_array($fields_label)) {
8525 $keyList .= implode(
', ', $fields_label);
8528 $filter_categorie =
false;
8529 if (count($InfoFieldList) > 5) {
8530 if ($InfoFieldList[0] ==
'categorie') {
8531 $filter_categorie =
true;
8535 $sql =
"SELECT ".$keyList;
8536 $sql .=
' FROM '.$this->db->prefix().$InfoFieldList[0];
8537 if (isset($InfoFieldList[4]) && strpos($InfoFieldList[4],
'extra') !==
false) {
8540 if ($selectkey ==
'rowid' && empty($value)) {
8541 $sql .=
" WHERE ".$selectkey.
" = 0";
8542 } elseif ($selectkey ==
'rowid') {
8543 $sql .=
" WHERE ".$selectkey.
" = ".((int) $value);
8545 $sql .=
" WHERE ".$selectkey.
" = '".$this->db->escape($value).
"'";
8550 dol_syslog(get_class($this).
':showOutputField:$type=sellist', LOG_DEBUG);
8551 $resql = $this->db->query($sql);
8553 if (!$filter_categorie) {
8555 $numrows = $this->db->num_rows($resql);
8557 $obj = $this->db->fetch_object($resql);
8560 $fields_label = explode(
'|', $InfoFieldList[1]);
8562 if (is_array($fields_label) && count($fields_label) > 1) {
8563 foreach ($fields_label as $field_toshow) {
8565 if (!empty($obj->$field_toshow)) {
8566 $translabel = $langs->trans($obj->$field_toshow);
8568 if ($translabel != $field_toshow) {
8569 $value .=
dol_trunc($translabel, 18) .
' ';
8571 $value .= $obj->$field_toshow .
' ';
8576 if (!empty($obj->{$InfoFieldList[1]})) {
8577 $translabel = $langs->trans($obj->{$InfoFieldList[1]});
8579 if ($translabel != $obj->{$InfoFieldList[1]}) {
8582 $value = $obj->{$InfoFieldList[1]};
8587 require_once DOL_DOCUMENT_ROOT .
'/categories/class/categorie.class.php';
8590 $obj = $this->db->fetch_object($resql);
8592 $c->fetch($obj->rowid);
8593 $ways = $c->print_all_ways();
8594 foreach ($ways as $way) {
8595 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories"' . ($c->color ?
' style="background: #' . $c->color .
';"' :
' style="background: #aaa"') .
'>' .
img_object(
'',
'category') .
' ' . $way .
'</li>';
8597 $value =
'<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(
' ', $toprint).
'</ul></div>';
8600 dol_syslog(get_class($this).
'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
8602 } elseif ($type ==
'radio') {
8603 $value = $param[
'options'][(string) $value];
8604 } elseif ($type ==
'checkbox') {
8605 $value_arr = explode(
',', (
string) $value);
8607 if (is_array($value_arr) && count($value_arr) > 0) {
8609 foreach ($value_arr as $keyval => $valueval) {
8610 if (!empty($valueval)) {
8611 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' . $param[
'options'][$valueval] .
'</li>';
8614 if (!empty($toprint)) {
8615 $value =
'<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">' . implode(
' ', $toprint) .
'</ul></div>';
8618 } elseif ($type ==
'chkbxlst') {
8619 $value_arr = (isset($value) ? explode(
',', $value) : array());
8621 $param_list = array_keys($param[
'options']);
8622 $InfoFieldList = explode(
":", $param_list[0]);
8624 $selectkey =
"rowid";
8627 if (count($InfoFieldList) >= 3) {
8628 $selectkey = $InfoFieldList[2];
8629 $keyList = $InfoFieldList[2].
' as rowid';
8632 $fields_label = explode(
'|', $InfoFieldList[1]);
8633 if (is_array($fields_label)) {
8635 $keyList .= implode(
', ', $fields_label);
8638 $filter_categorie =
false;
8639 if (count($InfoFieldList) > 5) {
8640 if ($InfoFieldList[0] ==
'categorie') {
8641 $filter_categorie =
true;
8645 $sql =
"SELECT ".$keyList;
8646 $sql .=
' FROM '.$this->db->prefix().$InfoFieldList[0];
8647 if (strpos($InfoFieldList[4],
'extra') !==
false) {
8653 dol_syslog(get_class($this).
':showOutputField:$type=chkbxlst', LOG_DEBUG);
8654 $resql = $this->db->query($sql);
8656 if (!$filter_categorie) {
8659 while ($obj = $this->db->fetch_object($resql)) {
8661 $fields_label = explode(
'|', $InfoFieldList[1]);
8662 if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
8663 if (is_array($fields_label) && count($fields_label) > 1) {
8664 foreach ($fields_label as $field_toshow) {
8666 if (!empty($obj->$field_toshow)) {
8667 $translabel = $langs->trans($obj->$field_toshow);
8669 if ($translabel != $field_toshow) {
8670 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' .
dol_trunc($translabel, 18) .
'</li>';
8672 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' . $obj->$field_toshow .
'</li>';
8677 if (!empty($obj->{$InfoFieldList[1]})) {
8678 $translabel = $langs->trans($obj->{$InfoFieldList[1]});
8680 if ($translabel != $obj->{$InfoFieldList[1]}) {
8681 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' .
dol_trunc($translabel, 18) .
'</li>';
8683 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' . $obj->{$InfoFieldList[1]} .
'</li>';
8689 require_once DOL_DOCUMENT_ROOT .
'/categories/class/categorie.class.php';
8692 while ($obj = $this->db->fetch_object($resql)) {
8693 if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
8695 $c->fetch($obj->rowid);
8696 $ways = $c->print_all_ways();
8697 foreach ($ways as $way) {
8698 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories"' . ($c->color ?
' style="background: #' . $c->color .
';"' :
' style="background: #aaa"') .
'>' .
img_object(
'',
'category') .
' ' . $way .
'</li>';
8703 $value =
'<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(
' ', $toprint).
'</ul></div>';
8705 dol_syslog(get_class($this).
'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
8707 } elseif ($type ==
'link') {
8712 $param_list = array_keys($param[
'options']);
8716 $InfoFieldList = explode(
":", $param_list[0]);
8718 $classname = $InfoFieldList[0];
8719 $classpath = $InfoFieldList[1];
8722 $getnomurlparam = 3;
8723 $getnomurlparam2 =
'';
8725 if (preg_match(
'/#getnomurlparam1=([^#]*)/', $param_list[0], $regtmp)) {
8726 $getnomurlparam = $regtmp[1];
8728 if (preg_match(
'/#getnomurlparam2=([^#]*)/', $param_list[0], $regtmp)) {
8729 $getnomurlparam2 = $regtmp[1];
8732 if (!empty($classpath)) {
8735 if ($classname && !class_exists($classname)) {
8739 if ($element_prop) {
8740 $classname = $element_prop[
'classname'];
8745 if ($classname && class_exists($classname)) {
8746 $object =
new $classname($this->db);
8747 '@phan-var-force CommonObject $object';
8748 if (
$object->element ===
'product') {
8749 '@phan-var-force Product $object';
8750 $result =
$object->fetch($value,
'',
'',
'', 0, 1, 1);
8752 $result =
$object->fetch($value);
8755 if (
$object->element ===
'product') {
8756 '@phan-var-force Product $object';
8757 $get_name_url_param_arr = array($getnomurlparam, $getnomurlparam2, 0, -1, 0,
'', 0);
8758 if (isset($val[
'get_name_url_params'])) {
8759 $get_name_url_params = explode(
':', $val[
'get_name_url_params']);
8760 if (!empty($get_name_url_params)) {
8761 $param_num_max = count($get_name_url_param_arr) - 1;
8762 foreach ($get_name_url_params as $param_num => $param_value) {
8763 if ($param_num > $param_num_max) {
8766 $get_name_url_param_arr[$param_num] = $param_value;
8774 $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]);
8776 $value =
$object->getNomUrl($getnomurlparam, $getnomurlparam2);
8783 dol_syslog(
'Error bad setup of extrafield', LOG_WARNING);
8784 return 'Error bad setup of extrafield';
8789 } elseif ($type ==
'password') {
8790 $value =
'<span class="opacitymedium">'.$langs->trans(
"Encrypted").
'</span>';
8792 } elseif ($type ==
'array') {
8793 if (is_array($value)) {
8794 $value = implode(
'<br>', $value);
8796 dol_syslog(__METHOD__.
' Expected array from dol_eval, but got '.gettype($value), LOG_ERR);
8797 return 'Error unexpected result from code evaluation';
8800 if (!empty($value) && preg_match(
'/^text/', (
string) $type) && !preg_match(
'/search_/', $keyprefix) && !empty($param[
'options'])) {
8801 $value = str_replace(
',',
"\n", $value);
8809 return is_null($out) ?
'' : $out;
8821 unset($this->validateFieldsErrors[$fieldKey]);
8835 $msg = $langs->trans(
"UnknownError");
8838 $this->error = $this->validateFieldsErrors[$fieldKey] = $msg;
8849 if (!empty($this->validateFieldsErrors[$fieldKey])) {
8850 return $this->validateFieldsErrors[$fieldKey];
8867 if (!class_exists(
'Validate')) {
8868 require_once DOL_DOCUMENT_ROOT .
'/core/class/validate.class.php';
8871 $this->clearFieldError($fieldKey);
8873 if (!array_key_exists($fieldKey, $fields) || !is_array($fields[$fieldKey])) {
8874 $this->setFieldError($fieldKey, $langs->trans(
'FieldNotFoundInObject'));
8878 $val = $fields[$fieldKey];
8881 $param[
'options'] = array();
8882 $type = $val[
'type'];
8885 if (isset($val[
'notnull']) && $val[
'notnull'] === 1) {
8899 if (preg_match(
'/varchar\((\d+)\)/', $type, $reg)) {
8902 } elseif (preg_match(
'/varchar/', $type)) {
8906 if (!empty($val[
'arrayofkeyval']) && is_array($val[
'arrayofkeyval'])) {
8910 if (!empty($val[
'type']) && preg_match(
'/^integer:(.*):(.*)/i', $val[
'type'], $reg)) {
8914 if (!empty($val[
'arrayofkeyval']) && is_array($val[
'arrayofkeyval'])) {
8915 $param[
'options'] = $val[
'arrayofkeyval'];
8918 if (preg_match(
'/^integer:(.*):(.*)/i', $val[
'type'], $reg)) {
8920 $param[
'options'] = array($reg[1].
':'.$reg[2] => $reg[1].
':'.$reg[2]);
8921 } elseif (preg_match(
'/^sellist:(.*):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
8922 $param[
'options'] = array($reg[1].
':'.$reg[2].
':'.$reg[3].
':'.$reg[4] =>
'N');
8924 } elseif (preg_match(
'/^sellist:(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
8925 $param[
'options'] = array($reg[1].
':'.$reg[2].
':'.$reg[3] =>
'N');
8927 } elseif (preg_match(
'/^sellist:(.*):(.*)/i', $val[
'type'], $reg)) {
8928 $param[
'options'] = array($reg[1].
':'.$reg[2] =>
'N');
8937 $validate =
new Validate($this->db, $langs);
8947 if ($required && !$validate->isNotEmptyString($fieldValue)) {
8948 $this->setFieldError($fieldKey, $validate->error);
8950 } elseif (!$required && !$validate->isNotEmptyString($fieldValue)) {
8956 if (!empty($maxSize) && !$validate->isMaxLength($fieldValue, $maxSize)) {
8957 $this->setFieldError($fieldKey, $validate->error);
8962 if (!empty($minSize) && !$validate->isMinLength($fieldValue, $minSize)) {
8963 $this->setFieldError($fieldKey, $validate->error);
8971 if (in_array($type, array(
'date',
'datetime',
'timestamp'))) {
8972 if (!$validate->isTimestamp($fieldValue)) {
8973 $this->setFieldError($fieldKey, $validate->error);
8978 } elseif ($type ==
'duration') {
8979 if (!$validate->isDuration($fieldValue)) {
8980 $this->setFieldError($fieldKey, $validate->error);
8985 } elseif (in_array($type, array(
'double',
'real',
'price'))) {
8987 if (!$validate->isNumeric($fieldValue)) {
8988 $this->setFieldError($fieldKey, $validate->error);
8993 } elseif ($type ==
'boolean') {
8994 if (!$validate->isBool($fieldValue)) {
8995 $this->setFieldError($fieldKey, $validate->error);
9000 } elseif ($type ==
'mail') {
9001 if (!$validate->isEmail($fieldValue)) {
9002 $this->setFieldError($fieldKey, $validate->error);
9005 } elseif ($type ==
'url') {
9006 if (!$validate->isUrl($fieldValue)) {
9007 $this->setFieldError($fieldKey, $validate->error);
9012 } elseif ($type ==
'phone') {
9013 if (!$validate->isPhone($fieldValue)) {
9014 $this->setFieldError($fieldKey, $validate->error);
9019 } elseif ($type ==
'select' || $type ==
'radio') {
9020 if (!isset($param[
'options'][$fieldValue])) {
9021 $this->error = $langs->trans(
'RequireValidValue');
9026 } elseif ($type ==
'sellist' || $type ==
'chkbxlst') {
9027 $param_list = array_keys($param[
'options']);
9028 $InfoFieldList = explode(
":", $param_list[0]);
9029 $value_arr = explode(
',', $fieldValue);
9030 $value_arr = array_map(array($this->db,
'escape'), $value_arr);
9032 $selectkey =
"rowid";
9033 if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
9034 $selectkey = $InfoFieldList[2];
9037 if (!$validate->isInDb($value_arr, $InfoFieldList[0], $selectkey)) {
9038 $this->setFieldError($fieldKey, $validate->error);
9043 } elseif ($type ==
'link') {
9044 $param_list = array_keys($param[
'options']);
9045 $InfoFieldList = explode(
":", $param_list[0]);
9046 $classname = $InfoFieldList[0];
9047 $classpath = $InfoFieldList[1];
9048 if (!$validate->isFetchable($fieldValue, $classname, $classpath)) {
9049 $lastIsFetchableError = $validate->error;
9052 if ($validate->isFetchableElement($fieldValue, $classname)) {
9056 $this->setFieldError($fieldKey, $lastIsFetchableError);
9080 public function showOptionals($extrafields, $mode =
'view', $params =
null, $keysuffix =
'', $keyprefix =
'', $onetrtd =
'', $display_type =
'card')
9082 global $db, $conf, $langs, $action, $form, $hookmanager;
9084 if (!is_object($form)) {
9085 $form =
new Form($db);
9087 if (!is_object($extrafields)) {
9088 dol_syslog(
'Bad parameter extrafields for showOptionals', LOG_ERR);
9089 return 'Bad parameter extrafields for showOptionals';
9091 if (!is_array($extrafields->attributes[$this->table_element])) {
9092 dol_syslog(
"extrafields->attributes was not loaded with extrafields->fetch_name_optionals_label(table_element);", LOG_WARNING);
9097 $parameters = array(
'mode' => $mode,
'params' => $params,
'keysuffix' => $keysuffix,
'keyprefix' => $keyprefix,
'display_type' => $display_type);
9098 $reshook = $hookmanager->executeHooks(
'showOptionals', $parameters, $this, $action);
9100 if (empty($reshook)) {
9101 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) {
9103 $out .=
'<!-- commonobject:showOptionals --> ';
9106 $nbofextrafieldsshown = 0;
9109 $lastseparatorkeyfound =
'';
9110 $extrafields_collapse_num =
'';
9111 $extrafields_collapse_num_old =
'';
9114 foreach ($extrafields->attributes[$this->table_element][
'label'] as $key => $label) {
9118 if (is_array($params) && array_key_exists(
'onlykey', $params) && $key != $params[
'onlykey']) {
9124 if ($enabled && isset($extrafields->attributes[$this->table_element][
'enabled'][$key])) {
9125 $enabled = (int)
dol_eval((
string) $extrafields->attributes[$this->table_element][
'enabled'][$key], 1, 1,
'2');
9127 if (empty($enabled)) {
9132 if (isset($extrafields->attributes[$this->table_element][
'list'][$key])) {
9133 $visibility = (int)
dol_eval($extrafields->attributes[$this->table_element][
'list'][$key], 1, 1,
'2');
9137 if ($perms && isset($extrafields->attributes[$this->table_element][
'perms'][$key])) {
9138 $perms = (int)
dol_eval($extrafields->attributes[$this->table_element][
'perms'][$key], 1, 1,
'2');
9141 if (($mode ==
'create') && !in_array(abs($visibility), array(1, 3))) {
9143 } elseif (($mode ==
'edit') && !in_array(abs($visibility), array(1, 3, 4))) {
9145 } elseif ($mode ==
'view' && empty($visibility)) {
9148 if (empty($perms)) {
9153 if (!empty($extrafields->attributes[$this->table_element][
'langfile'][$key])) {
9154 $langs->load($extrafields->attributes[$this->table_element][
'langfile'][$key]);
9159 if (is_array($params) && count($params) > 0 && $display_type ==
'card') {
9160 if (array_key_exists(
'cols', $params)) {
9161 $colspan = $params[
'cols'];
9162 } elseif (array_key_exists(
'colspan', $params)) {
9164 if (preg_match(
'/colspan="(\d+)"/', $params[
'colspan'], $reg)) {
9167 $colspan = $params[
'colspan'];
9171 $colspan = intval($colspan);
9175 $value = ((!empty($this->array_options) && array_key_exists(
"options_".$key.$keysuffix, $this->array_options)) ? $this->array_options[
"options_".$key.$keysuffix] :
null);
9181 $check =
'alphanohtml';
9182 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'html',
'text'))) {
9183 $check =
'restricthtml';
9185 $getposttemp =
GETPOST($keyprefix.
'options_'.$key.$keysuffix, $check, 3);
9187 if (is_array($getposttemp) || $getposttemp !=
'' || GETPOSTISSET($keyprefix.
'options_'.$key.$keysuffix)) {
9188 if (is_array($getposttemp)) {
9190 $value = implode(
",", $getposttemp);
9192 $value = $getposttemp;
9194 } elseif (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'int'))) {
9195 $value = (!empty($this->array_options[
"options_".$key]) || (isset($this->array_options[
"options_".$key]) && $this->array_options[
"options_".$key] ===
'0')) ? $this->array_options[
"options_".$key] :
'';
9197 $value = (!empty($this->array_options[
"options_".$key]) ? $this->array_options[
"options_".$key] :
'');
9203 $nbofextrafieldsshown++;
9206 if ($extrafields->attributes[$this->table_element][
'type'][$key] ==
'separate') {
9207 $extrafields_collapse_num = $key;
9225 $out .= $extrafields->showSeparator($key, $this, ($colspan ? $colspan + 1 : 2), $display_type, $mode);
9227 $lastseparatorkeyfound = $key;
9229 $collapse_group = $extrafields_collapse_num.(!empty($this->
id) ?
'_'.$this->id :
'');
9231 $class = (!empty($extrafields->attributes[$this->table_element][
'hidden'][$key]) ?
'hideobject ' :
'');
9233 if (is_array($params) && count($params) > 0) {
9234 if (array_key_exists(
'class', $params)) {
9235 $class .= $params[
'class'].
' ';
9237 if (array_key_exists(
'style', $params)) {
9238 $csstyle = $params[
'style'];
9243 $domData =
' data-element="extrafield"';
9244 $domData .=
' data-targetelement="'.$this->element.
'"';
9245 $domData .=
' data-targetid="'.$this->id.
'"';
9247 $html_id = (empty($this->
id) ?
'' :
'extrarow-'.$this->element.
'_'.$key.
'_'.
$this->id);
9248 if ($display_type ==
'card') {
9253 if ($action ==
'selectlines') {
9259 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'date'))) {
9260 $datenotinstring =
null;
9261 if (array_key_exists(
'options_'.$key, $this->array_options)) {
9262 $datenotinstring = $this->array_options[
'options_'.$key];
9263 if (!is_numeric($this->array_options[
'options_'.$key])) {
9264 $datenotinstring = $this->db->jdate($datenotinstring);
9267 $datekey = $keyprefix.
'options_'.$key.$keysuffix;
9270 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'datetime'))) {
9271 $datenotinstring =
null;
9272 if (array_key_exists(
'options_'.$key, $this->array_options)) {
9273 $datenotinstring = $this->array_options[
'options_'.$key];
9274 if (!is_numeric($this->array_options[
'options_'.$key])) {
9275 $datenotinstring = $this->db->jdate($datenotinstring);
9278 $timekey = $keyprefix.
'options_'.$key.$keysuffix;
9279 $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;
9282 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'price',
'double'))) {
9283 if (GETPOSTISSET($keyprefix.
'options_'.$key.$keysuffix) || $value) {
9285 } elseif (isset($this->array_options[
'options_'.$key])) {
9286 $value = $this->array_options[
'options_'.$key];
9291 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'html',
'text',
'varchar',
'select',
'radio',
'int',
'boolean'))) {
9292 if ($action ==
'create' || $mode ==
'create') {
9293 $value = (GETPOSTISSET($keyprefix.
'options_'.$key.$keysuffix) || $value) ? $value : $extrafields->attributes[$this->table_element][
'default'][$key];
9297 $labeltoshow = $langs->trans($label);
9298 $helptoshow = $langs->trans($extrafields->attributes[$this->table_element][
'help'][$key]);
9299 if ($display_type ==
'card') {
9300 $out .=
'<tr '.($html_id ?
'id="'.$html_id.
'" ' :
'').$csstyle.
' class="field_options_'.$key.
' '.$class.$this->element.
'_extras_'.$key.
' trextrafields_collapse'.$collapse_group.
'" '.$domData.
' >';
9301 if (
getDolGlobalString(
'MAIN_VIEW_LINE_NUMBER') && ($action ==
'view' || $action ==
'valid' || $action ==
'editline' || $action ==
'confirm_valid' || $action ==
'confirm_cancel')) {
9302 $out .=
'<td></td>';
9304 $out .=
'<td class="'.(empty($params[
'tdclass']) ?
'titlefieldmax45' : $params[
'tdclass']).
' wordbreak';
9305 if ($extrafields->attributes[$this->table_element][
'type'][$key] ==
'text') {
9308 } elseif ($display_type ==
'line') {
9309 $out .=
'<div '.($html_id ?
'id="'.$html_id.
'" ' :
'').$csstyle.
' class="fieldline_options_'.$key.
' '.$class.$this->element.
'_extras_'.$key.
' trextrafields_collapse'.$collapse_group.
'" '.$domData.
' >';
9310 $out .=
'<div style="display: inline-block; padding-right:4px" class="wordbreak';
9315 $tpl_context = isset($params[
"tpl_context"]) ? $params[
"tpl_context"] :
"none";
9316 if ($tpl_context !=
"public") {
9317 if ($mode !=
'view' && !empty($extrafields->attributes[$this->table_element][
'required'][$key])) {
9318 $out .=
' fieldrequired';
9322 if ($tpl_context ==
"public") {
9323 if (!empty($extrafields->attributes[$this->table_element][
'help'][$key])) {
9324 $out .= $form->textwithpicto($labeltoshow, $helptoshow);
9326 $out .= $labeltoshow;
9328 if ($mode !=
'view' && !empty($extrafields->attributes[$this->table_element][
'required'][$key])) {
9329 $out .=
' <span style="color: red">*</span>';
9332 if (!empty($extrafields->attributes[$this->table_element][
'help'][$key])) {
9333 $out .= $form->textwithpicto($labeltoshow, $helptoshow);
9335 $out .= $labeltoshow;
9339 $out .= ($display_type ==
'card' ?
'</td>' :
'</div>');
9342 $html_id = !empty($this->
id) ? $this->element.
'_extras_'.$key.
'_'.$this->id :
'';
9343 if ($display_type ==
'card') {
9345 $out .=
'<td '.($html_id ?
'id="'.$html_id.
'" ' :
'').
' class="valuefieldcreate '.$this->element.
'_extras_'.$key;
9346 $out .=
'" '.($colspan ?
' colspan="'.$colspan.
'"' :
'');
9348 } elseif ($display_type ==
'line') {
9349 $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].
'">';
9354 $out .= $extrafields->showOutputField($key, $value,
'', $this->table_element);
9357 $listoftypestoshowpicto = explode(
',',
getDolGlobalString(
'MAIN_TYPES_TO_SHOW_PICTO',
'email,phone,ip,password'));
9358 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], $listoftypestoshowpicto)) {
9359 $out .=
getPictoForType($extrafields->attributes[$this->table_element][
'type'][$key], ($extrafields->attributes[$this->table_element][
'type'][$key] ==
'text' ?
'tdtop' :
''));
9362 $out .= $extrafields->showInputField($key, $value,
'', $keysuffix,
'', 0, $this->
id, $this->table_element);
9365 $listoftypestoshowpicto = explode(
',',
getDolGlobalString(
'MAIN_TYPES_TO_SHOW_PICTO',
'email,phone,ip,password'));
9366 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], $listoftypestoshowpicto)) {
9367 $out .=
getPictoForType($extrafields->attributes[$this->table_element][
'type'][$key], ($extrafields->attributes[$this->table_element][
'type'][$key] ==
'text' ?
'tdtop' :
''));
9369 $out .= $extrafields->showInputField($key, $value,
'', $keysuffix,
'', 0, $this->
id, $this->table_element);
9373 $out .= ($display_type ==
'card' ?
'</td>' :
'</div>');
9374 $out .= ($display_type ==
'card' ?
'</tr>'.
"\n" :
'</div>');
9380 if (!empty($conf->use_javascript_ajax)) {
9381 $out .= $this->getJSListDependancies();
9384 $out .=
'<!-- commonobject:showOptionals end --> '.
"\n";
9386 if (empty($nbofextrafieldsshown)) {
9392 $out .= $hookmanager->resPrint;
9404 <script nonce="'.getNonce().
'">
9405 jQuery(document).ready(function() {
9406 function showOptions'.$type.
'(child_list, parent_list, orig_select)
9408 var val = $("select[name=\""+parent_list+"\"]").val();
9409 var parentVal = parent_list + ":" + val;
9410 if(typeof val == "string"){
9412 var options = orig_select.find("option[parent=\""+parentVal+"\"]").clone();
9413 $("select[name=\""+child_list+"\"] option[parent]").remove();
9414 $("select[name=\""+child_list+"\"]").append(options);
9416 var options = orig_select.find("option[parent]").clone();
9417 $("select[name=\""+child_list+"\"] option[parent]").remove();
9418 $("select[name=\""+child_list+"\"]").append(options);
9420 } else if(val > 0) {
9421 var options = orig_select.find("option[parent=\""+parentVal+"\"]").clone();
9422 $("select[name=\""+child_list+"\"] option[parent]").remove();
9423 $("select[name=\""+child_list+"\"]").append(options);
9425 var options = orig_select.find("option[parent]").clone();
9426 $("select[name=\""+child_list+"\"] option[parent]").remove();
9427 $("select[name=\""+child_list+"\"]").append(options);
9430 function setListDependencies'.$type.
'() {
9431 jQuery("select option[parent]").parent().each(function() {
9432 var orig_select = {};
9433 var child_list = $(this).attr("name");
9434 orig_select[child_list] = $(this).clone();
9435 var parent = $(this).find("option[parent]:first").attr("parent");
9436 var infos = parent.split(":");
9437 var parent_list = infos[0];
9439 //Hide daughters lists
9440 if ($("#"+child_list).val() == 0 && $("#"+parent_list).val() == 0){
9441 $("#"+child_list).hide();
9443 } else if ($("#"+parent_list).val() != 0){
9444 $("#"+parent_list).show();
9446 //Show the child list if the parent list value is selected
9447 $("select[name=\""+parent_list+"\"]").click(function() {
9448 if ($(this).val() != 0){
9449 $("#"+child_list).show()
9453 //When we change parent list
9454 $("select[name=\""+parent_list+"\"]").change(function() {
9455 showOptions'.$type.
'(child_list, parent_list, orig_select[child_list]);
9456 //Select the value 0 on child list after a change on the parent list
9457 $("#"+child_list).val(0).trigger("change");
9458 //Hide child lists if the parent value is set to 0
9459 if ($(this).val() == 0){
9460 $("#"+child_list).hide();
9466 setListDependencies'.$type.
'();
9481 $module = empty($this->module) ?
'' : $this->module;
9482 $element = $this->element;
9484 if ($element ==
'facturerec') {
9485 $element =
'facture';
9486 } elseif ($element ==
'invoice_supplier_rec') {
9487 return !$user->hasRight(
'fournisseur',
'facture') ? null : $user->hasRight(
'fournisseur',
'facture');
9488 } elseif ($module && $user->hasRight($module, $element)) {
9490 return $user->hasRight($module, $element);
9493 return $user->rights->$element;
9510 global $hookmanager;
9512 $parameters = array(
9513 'origin_id' => $origin_id,
9514 'dest_id' => $dest_id,
9515 'tables' => $tables,
9517 $reshook = $hookmanager->executeHooks(
'commonReplaceThirdparty', $parameters);
9520 } elseif ($reshook < 0) {
9521 return $ignoreerrors === 1;
9524 foreach ($tables as $table) {
9525 $sql =
'UPDATE '.$dbs->prefix().$table.
' SET fk_soc = '.((int) $dest_id).
' WHERE fk_soc = '.((int) $origin_id);
9527 if (!$dbs->
query($sql)) {
9528 if ($ignoreerrors) {
9553 foreach ($tables as $table) {
9554 $sql =
'UPDATE '.MAIN_DB_PREFIX.$table.
' SET fk_product = '.((int) $dest_id).
' WHERE fk_product = '.((int) $origin_id);
9556 if (!$dbs->
query($sql)) {
9557 if ($ignoreerrors) {
9580 public function defineBuyPrice($unitPrice = 0.0, $discountPercent = 0.0, $fk_product = 0)
9586 if (($unitPrice > 0) && (isset($conf->global->ForceBuyingPriceIfNull) &&
getDolGlobalInt(
'ForceBuyingPriceIfNull') > 0)) {
9588 $buyPrice = $unitPrice * (1 - $discountPercent / 100);
9591 if (!empty($fk_product) && $fk_product > 0) {
9594 require_once DOL_DOCUMENT_ROOT.
'/product/class/product.class.php';
9595 $product =
new Product($this->db);
9596 $result = $product->fetch($fk_product);
9598 $this->errors[] =
'ErrorProductIdDoesNotExists';
9601 if ($product->cost_price > 0) {
9602 $buyPrice = $product->cost_price;
9603 } elseif ($product->pmp > 0) {
9604 $buyPrice = $product->pmp;
9607 require_once DOL_DOCUMENT_ROOT.
'/product/class/product.class.php';
9608 $product =
new Product($this->db);
9609 $result = $product->fetch($fk_product);
9611 $this->errors[] =
'ErrorProductIdDoesNotExists';
9614 if ($product->pmp > 0) {
9615 $buyPrice = $product->pmp;
9619 if (empty($buyPrice) && isset($conf->global->MARGIN_TYPE) && in_array($conf->global->MARGIN_TYPE, array(
'1',
'pmp',
'costprice'))) {
9620 require_once DOL_DOCUMENT_ROOT.
'/fourn/class/fournisseur.product.class.php';
9622 if (($result = $productFournisseur->find_min_price_product_fournisseur($fk_product)) > 0) {
9623 $buyPrice = $productFournisseur->fourn_unitprice;
9624 } elseif ($result < 0) {
9625 $this->errors[] = $productFournisseur->error;
9644 return array(
'dir' =>
'',
'file' =>
'',
'originalfile' =>
'',
'altfile' =>
'',
'email' =>
'',
'capture' =>
'');
9668 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')
9671 global $user, $langs;
9673 include_once DOL_DOCUMENT_ROOT.
'/core/lib/files.lib.php';
9674 include_once DOL_DOCUMENT_ROOT.
'/core/lib/images.lib.php';
9676 $sortfield =
'position_name';
9682 $dir .=
get_exdir(0, 0, 0, 0, $this, $modulepart);
9683 $pdir .=
get_exdir(0, 0, 0, 0, $this, $modulepart);
9686 if ($modulepart ==
'product') {
9688 $dir = $sdir.
'/'.
get_exdir($this->
id, 2, 0, 0, $this, $modulepart).$this->id.
"/photos/";
9689 $pdir =
'/'.get_exdir($this->
id, 2, 0, 0, $this, $modulepart).$this->id.
"/photos/";
9692 if ($modulepart ==
'category') {
9693 $dir = $sdir.
'/'.
get_exdir($this->
id, 2, 0, 0, $this, $modulepart).$this->id.
"/photos/";
9694 $pdir =
'/'.get_exdir($this->
id, 2, 0, 0, $this, $modulepart).$this->id.
"/photos/";
9700 $relativedir = preg_replace(
'/^'.preg_quote(DOL_DATA_ROOT,
'/').
'/',
'', $dir);
9701 $relativedir = preg_replace(
'/^[\\/]/',
'', $relativedir);
9702 $relativedir = preg_replace(
'/[\\/]$/',
'', $relativedir);
9705 $dirthumb = $dir.
'thumbs/';
9706 $pdirthumb = $pdir.
'thumbs/';
9708 $return =
'<!-- Photo -->'.
"\n";
9711 $filearray =
dol_dir_list($dir,
"files", 0,
'',
'(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) ==
'desc' ? SORT_DESC : SORT_ASC), 1);
9721 if (count($filearray)) {
9722 if ($sortfield && $sortorder) {
9726 foreach ($filearray as $key => $val) {
9728 $file = $val[
'name'];
9734 $viewfilename = $file;
9736 if ($size == 1 || $size ==
'small') {
9743 $photo_vignette = basename($file);
9750 if ($nbphoto == 1) {
9751 $return .=
'<table class="valigntop center centpercent" style="border: 0; padding: 2px; border-spacing: 2px; border-collapse: separate;">';
9754 if ($nbphoto % $nbbyrow == 1) {
9755 $return .=
'<tr class="center valignmiddle" style="border: 1px">';
9757 $return .=
'<td style="width: '.ceil(100 / $nbbyrow).
'%" class="photo">'.
"\n";
9758 } elseif ($nbbyrow < 0) {
9759 $return .=
'<div class="inline-block">'.
"\n";
9762 $relativefile = preg_replace(
'/^\//',
'', $pdir.$photo);
9763 if (empty($nolink)) {
9766 $return .=
'<a href="'.$urladvanced.
'">';
9768 $return .=
'<a href="'.DOL_URL_ROOT.
'/viewimage.php?modulepart='.$modulepart.
'&entity='.$this->entity.
'&file='.urlencode($pdir.$photo).
'" class="aphoto" target="_blank" rel="noopener noreferrer">';
9774 $alt = $langs->transnoentitiesnoconv(
'File').
': '.$relativefile;
9775 $alt .=
' - '.$langs->transnoentitiesnoconv(
'Size').
': '.$imgarray[
'width'].
'x'.$imgarray[
'height'];
9776 if ($overwritetitle) {
9777 if (is_numeric($overwritetitle)) {
9780 $alt = $overwritetitle;
9783 if (empty($cache) && !empty($val[
'label'])) {
9786 $cache = $val[
'label'];
9788 if ($usesharelink) {
9789 if (array_key_exists(
'share', $val) && $val[
'share']) {
9790 if (empty($maxHeight) || ($photo_vignette && $imgarray[
'height'] > $maxHeight)) {
9791 $return .=
'<!-- Show original file (thumb not yet available with shared links) -->';
9792 $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).
'">';
9794 $return .=
'<!-- Show original file -->';
9795 $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).
'">';
9798 $return .=
'<!-- Show nophoto file (because file is not shared) -->';
9799 $return .=
'<img class="photo photowithmargin'.($addphotorefcss ?
' '.$addphotorefcss :
'').
'" height="'.$maxHeight.
'" src="'.DOL_URL_ROOT.
'/public/theme/common/nophoto.png" title="'.
dol_escape_htmltag($alt).
'">';
9802 if (empty($maxHeight) || ($photo_vignette && $imgarray[
'height'] > $maxHeight)) {
9803 $return .=
'<!-- Show thumb -->';
9804 $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).
'">';
9806 $return .=
'<!-- Show original file -->';
9807 $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).
'">';
9811 if (empty($nolink)) {
9815 if ($showfilename) {
9816 $return .=
'<br>'.$viewfilename;
9821 if ($photo_vignette && (
image_format_supported($photo) > 0) && ((isset($imgarray[
'width']) && $imgarray[
'width'] > $maxWidth) || (isset($imgarray[
'width']) && $imgarray[
'width'] > $maxHeight))) {
9822 $return .=
'<a href="'.$_SERVER[
"PHP_SELF"].
'?id='.$this->
id.
'&action=addthumb&token='.
newToken().
'&file='.urlencode($pdir.$viewfilename).
'">'.
img_picto($langs->trans(
'GenerateThumb'),
'refresh').
' </a>';
9825 if ($modulepart ==
'product' && ($user->hasRight(
'produit',
'creer') || $user->hasRight(
'service',
'creer'))) {
9827 $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> ';
9830 $return .=
'<a href="'.$_SERVER[
"PHP_SELF"].
'?id='.$this->
id.
'&action=delete&token='.
newToken().
'&file='.urlencode($pdir.$viewfilename).
'">';
9838 if (($nbphoto % $nbbyrow) == 0) {
9841 } elseif ($nbbyrow < 0) {
9842 $return .=
'</div>'.
"\n";
9847 $return .=
'<img class="photo photowithmargin" src="'.DOL_URL_ROOT.
'/viewimage.php?modulepart='.$modulepart.
'&entity='.$this->entity.
'&file='.urlencode($pdir.$photo).
'">';
9849 if ($showfilename) {
9850 $return .=
'<br>'.$viewfilename;
9854 if ($modulepart ==
'product' && ($user->hasRight(
'produit',
'creer') || $user->hasRight(
'service',
'creer'))) {
9856 $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> ';
9859 $return .=
'<a href="'.$_SERVER[
"PHP_SELF"].
'?id='.$this->
id.
'&action=delete&token='.
newToken().
'&file='.urlencode($pdir.$viewfilename).
'">';
9866 if ($nbmax && $nbphoto >= $nbmax) {
9872 if ($size == 1 || $size ==
'small') {
9875 while ($nbphoto % $nbbyrow) {
9876 $return .=
'<td style="width: '.ceil(100 / $nbbyrow).
'%"> </td>';
9881 $return .=
'</table>';
9887 $this->nbphoto = $nbphoto;
9901 if (is_array($info)) {
9902 if (isset($info[
'type']) && $info[
'type'] ==
'array') {
9919 if (isset($info[
'type']) && ($info[
'type'] ==
'date' || $info[
'type'] ==
'datetime' || $info[
'type'] ==
'timestamp')) {
9933 if (is_array($info)) {
9934 if (isset($info[
'type']) && ($info[
'type'] ==
'duration')) {
9952 if (is_array($info)) {
9953 if (isset($info[
'type']) && (preg_match(
'/(^int|int$)/i', $info[
'type']))) {
9971 if (is_array($info)) {
9972 if (isset($info[
'type']) && (preg_match(
'/^(double|real|price)/i', $info[
'type']))) {
9989 if (is_array($info)) {
9990 if (isset($info[
'type']) && $info[
'type'] ==
'text') {
10007 if (is_array($info)) {
10008 if (array_key_exists(
'notnull', $info) && $info[
'notnull'] !=
'1') {
10025 if (is_array($info)) {
10026 if (array_key_exists(
'notnull', $info) && $info[
'notnull'] ==
'-1') {
10043 if (is_array($info)) {
10044 if (array_key_exists(
'index', $info) && $info[
'index'] ==
true) {
10066 $queryarray = array();
10067 foreach ($this->fields as $field => $info) {
10069 if ($this->isDate($info)) {
10070 if (empty($this->{$field})) {
10071 $queryarray[$field] =
null;
10073 $queryarray[$field] = $this->db->idate($this->{$field});
10075 } elseif ($this->isDuration($info)) {
10077 if ((isset($this->{$field}) && $this->{$field} !=
'') || !empty($info[
'notnull'])) {
10078 if (!isset($this->{$field})) {
10079 if (!empty($info[
'default'])) {
10080 $queryarray[$field] = $info[
'default'];
10082 $queryarray[$field] = 0;
10085 $queryarray[$field] = (int) $this->{$field};
10088 $queryarray[$field] =
null;
10090 } elseif ($this->isInt($info) || $this->isFloat($info)) {
10091 if ($field ==
'entity' && is_null($this->{$field})) {
10092 $queryarray[$field] = ((int) $conf->entity);
10095 if ((isset($this->{$field}) && ((
string) $this->{$field}) !=
'') || !empty($info[
'notnull'])) {
10096 if (!isset($this->{$field})) {
10097 $queryarray[$field] = 0;
10098 } elseif ($this->isInt($info)) {
10099 $queryarray[$field] = (int) $this->{$field};
10100 } elseif ($this->isFloat($info)) {
10101 $queryarray[$field] = (float) $this->{$field};
10104 $queryarray[$field] =
null;
10110 $queryarray[$field] = $this->{$field};
10113 if (array_key_exists(
'type', $info) && $info[
'type'] ==
'timestamp' && empty($queryarray[$field])) {
10114 unset($queryarray[$field]);
10116 if (!empty($info[
'notnull']) && $info[
'notnull'] == -1 && empty($queryarray[$field])) {
10117 $queryarray[$field] =
null;
10121 return $queryarray;
10134 foreach ($this->fields as $field => $info) {
10135 if ($this->isDate($info)) {
10136 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') {
10137 $this->$field =
'';
10139 $this->$field = $db->jdate($obj->$field);
10141 } elseif ($this->isInt($info)) {
10142 if ($field ==
'rowid') {
10143 $this->
id = (int) $obj->$field;
10145 if ($this->isForcedToNullIfZero($info)) {
10146 if (empty($obj->$field)) {
10147 $this->$field =
null;
10149 $this->$field = (int) $obj->$field;
10152 if (isset($obj->$field) && (!is_null($obj->$field) || (array_key_exists(
'notnull', $info) && $info[
'notnull'] == 1))) {
10153 $this->$field = (int) $obj->$field;
10155 $this->$field =
null;
10159 } elseif ($this->isFloat($info)) {
10160 if ($this->isForcedToNullIfZero($info)) {
10161 if (empty($obj->$field)) {
10162 $this->$field =
null;
10164 $this->$field = (float) $obj->$field;
10167 if (isset($obj->$field) && (!is_null($obj->$field) || (array_key_exists(
'notnull', $info) && $info[
'notnull'] == 1))) {
10168 $this->$field = (float) $obj->$field;
10170 $this->$field =
null;
10174 $this->$field = isset($obj->$field) ? $obj->$field :
null;
10179 if (!isset($this->fields[
'ref']) && isset($this->
id)) {
10180 $this->
ref = (string) $this->
id;
10190 foreach ($this->fields as $field => $arr) {
10191 $this->$field =
null;
10204 $keys = array_keys($this->fields);
10205 if (!empty($alias)) {
10206 $keys_with_alias = array();
10207 foreach ($keys as $fieldname) {
10208 if (!empty($excludefields)) {
10209 if (in_array($fieldname, $excludefields)) {
10213 $keys_with_alias[] = $alias .
'.' . $fieldname;
10215 return implode(
',', $keys_with_alias);
10217 return implode(
',', $keys);
10228 protected function quote($value, $fieldsentry)
10230 if (is_null($value)) {
10232 } elseif (preg_match(
'/^(int|double|real|price)/i', $fieldsentry[
'type'])) {
10234 } elseif (preg_match(
'/int$/i', $fieldsentry[
'type'])) {
10235 return (
int) $value;
10236 } elseif ($fieldsentry[
'type'] ==
'boolean') {
10243 return "'".$this->db->escape($value).
"'";
10259 dol_syslog(get_class($this).
"::createCommon create", LOG_DEBUG);
10265 $fieldvalues = $this->setSaveQuery();
10269 if (array_key_exists(
'date_creation', $fieldvalues) && empty($fieldvalues[
'date_creation'])) {
10270 $fieldvalues[
'date_creation'] = $this->db->idate($now);
10272 if (array_key_exists(
'fk_user_creat', $fieldvalues) && !($fieldvalues[
'fk_user_creat'] > 0)) {
10273 $fieldvalues[
'fk_user_creat'] = $user->id;
10274 $this->fk_user_creat = $user->id;
10276 if (array_key_exists(
'user_creation_id', $fieldvalues) && !($fieldvalues[
'user_creation_id'] > 0)) {
10277 $fieldvalues[
'user_creation_id'] = $user->id;
10278 $this->user_creation_id = $user->id;
10280 if (array_key_exists(
'pass_crypted', $fieldvalues) && property_exists($this,
'pass')) {
10282 $fieldvalues[
'pass_crypted'] =
dol_hash($this->pass);
10284 if (array_key_exists(
'ref', $fieldvalues)) {
10288 unset($fieldvalues[
'rowid']);
10292 foreach ($fieldvalues as $k => $v) {
10294 $value = $this->fields[$k];
10296 $values[$k] = $this->quote($v, $value);
10300 foreach ($keys as $key) {
10301 if (!isset($this->fields[$key])) {
10304 $key_fields = $this->fields[$key];
10307 if (preg_match(
'/^integer:/i', $key_fields[
'type']) && $values[$key] ==
'-1') {
10308 $values[$key] =
'';
10310 if (!empty($key_fields[
'foreignkey']) && $values[$key] ==
'-1') {
10311 $values[$key] =
'';
10314 if (isset($key_fields[
'notnull']) && $key_fields[
'notnull'] == 1 && (!isset($values[$key]) || $values[$key] ===
'NULL') && (!isset($key_fields[
'default']) || is_null($key_fields[
'default']))) {
10316 $langs->load(
"errors");
10317 dol_syslog(
"Mandatory field '".$key.
"' is empty and required into ->fields definition of class");
10318 $this->errors[] = $langs->trans(
"ErrorFieldRequired", isset($key_fields[
'label']) ? $key_fields[
'label'] : $key);
10322 if (isset($key_fields[
'notnull']) && $key_fields[
'notnull'] == 1 && (!isset($values[$key]) || $values[$key] ===
'NULL') && !is_null($key_fields[
'default'])) {
10323 $values[$key] = $this->quote($key_fields[
'default'], $key_fields);
10327 if (isset($key_fields[
'type']) && preg_match(
'/^integer:/i', $key_fields[
'type']) && empty($values[$key])) {
10328 if (isset($key_fields[
'default'])) {
10329 $values[$key] = ((int) $key_fields[
'default']);
10331 $values[$key] =
'null';
10334 if (!empty($key_fields[
'foreignkey']) && empty($values[$key])) {
10335 $values[$key] =
'null';
10343 $this->db->begin();
10346 $sql =
"INSERT INTO ".$this->db->prefix().$this->table_element;
10347 $sql .=
" (".implode(
", ", $keys).
')';
10348 $sql .=
" VALUES (".implode(
", ", $values).
")";
10350 $res = $this->db->query($sql);
10353 if ($this->db->lasterrno() ==
'DB_ERROR_RECORD_ALREADY_EXISTS') {
10354 $this->errors[] =
"ErrorRefAlreadyExists";
10356 $this->errors[] = $this->db->lasterror();
10362 $this->
id = $this->db->last_insert_id($this->db->prefix().$this->table_element);
10368 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)') {
10369 $sql =
"UPDATE ".$this->db->prefix().$this->table_element.
" SET ref = '(PROV".((int) $this->
id).
")' WHERE (ref = '(PROV)' OR ref = '') AND rowid = ".((int) $this->
id);
10370 $resqlupdate = $this->db->query($sql);
10372 if ($resqlupdate ===
false) {
10374 $this->errors[] = $this->db->lasterror();
10376 $this->
ref =
'(PROV'.$this->id.
')';
10383 $result = $this->insertExtraFields();
10390 if (!empty($this->table_element_line) && !empty($this->fk_element)) {
10391 foreach ($this->lines as $line) {
10392 $keyforparent = $this->fk_element;
10397 if (!is_object($line)) {
10398 $line = (object) $line;
10402 if (method_exists($line,
'insert')) {
10403 $result = $line->insert($user, 1);
10404 } elseif (method_exists($line,
'create')) {
10405 $result = $line->create($user, 1);
10408 $this->error = $line->error;
10409 $this->db->rollback();
10416 if (!$error && !$notrigger) {
10418 $result = $this->call_trigger(strtoupper(get_class($this)).
'_CREATE', $user);
10427 $this->db->rollback();
10430 $this->db->commit();
10447 if (empty(
$id) && empty($ref) && empty($morewhere)) {
10451 $fieldlist = $this->getFieldList(
't');
10452 if (empty($fieldlist)) {
10456 $sql =
"SELECT ".$fieldlist;
10457 $sql .=
" FROM ".$this->db->prefix().$this->table_element.
' as t';
10460 $sql .=
' WHERE t.rowid = '.((int)
$id);
10461 } elseif (!empty($ref)) {
10462 $sql .=
" WHERE t.ref = '".$this->db->escape($ref).
"'";
10464 $sql .=
' WHERE 1 = 1';
10466 if (empty(
$id) && isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
10467 $sql .=
' AND t.entity IN ('.getEntity($this->element).
')';
10470 $sql .= $morewhere;
10472 $sql .=
' LIMIT 1';
10474 $res = $this->db->query($sql);
10476 $obj = $this->db->fetch_object($res);
10478 $this->setVarsFromFetchObj($obj);
10482 if (empty($noextrafields)) {
10483 $result = $this->fetch_optionals();
10485 $this->error = $this->db->lasterror();
10486 $this->errors[] = $this->error;
10496 $this->error = $this->db->lasterror();
10497 $this->errors[] = $this->error;
10511 $objectlineclassname = get_class($this).
'Line';
10512 if (!class_exists($objectlineclassname)) {
10513 $this->error =
'Error, class '.$objectlineclassname.
' not found during call of fetchLinesCommon';
10517 $objectline =
new $objectlineclassname($this->db);
10518 '@phan-var-force CommonObjectLine $objectline';
10520 $sql =
"SELECT ".$objectline->getFieldList(
'l');
10521 $sql .=
" FROM ".$this->db->prefix().$objectline->table_element.
" as l";
10522 $sql .=
" WHERE l.fk_".$this->db->escape($this->element).
" = ".((int) $this->
id);
10524 $sql .= $morewhere;
10526 if (isset($objectline->fields[
'position'])) {
10527 $sql .= $this->db->order(
'position',
'ASC');
10530 $resql = $this->db->query($sql);
10532 $num_rows = $this->db->num_rows($resql);
10534 $this->lines = array();
10535 while ($i < $num_rows) {
10536 $obj = $this->db->fetch_object($resql);
10538 $newline =
new $objectlineclassname($this->db);
10539 '@phan-var-force CommonObjectLine $newline';
10540 $newline->setVarsFromFetchObj($obj);
10548 $this->lines[] = $newline;
10555 $this->error = $this->db->lasterror();
10556 $this->errors[] = $this->error;
10570 dol_syslog(get_class($this).
"::updateCommon update", LOG_DEBUG);
10582 $fieldvalues = $this->setSaveQuery();
10586 if (array_key_exists(
'date_modification', $fieldvalues) && empty($fieldvalues[
'date_modification'])) {
10587 $fieldvalues[
'date_modification'] = $this->db->idate($now);
10589 if (array_key_exists(
'fk_user_modif', $fieldvalues) && !($fieldvalues[
'fk_user_modif'] > 0)) {
10590 $fieldvalues[
'fk_user_modif'] = $user->id;
10592 if (array_key_exists(
'user_modification_id', $fieldvalues) && !($fieldvalues[
'user_modification_id'] > 0)) {
10593 $fieldvalues[
'user_modification_id'] = $user->id;
10595 if (array_key_exists(
'ref', $fieldvalues)) {
10599 unset($fieldvalues[
'rowid']);
10605 foreach ($fieldvalues as $k => $v) {
10607 $value = $this->fields[$k];
10609 $values[$k] = $this->quote($v, $value);
10610 if (($value[
"type"] ==
"text") && !empty($value[
'arrayofkeyval']) && is_array($value[
'arrayofkeyval'])) {
10612 $v = preg_replace(
'/\s/',
',', $v);
10613 $v = preg_replace(
'/,+/',
',', $v);
10616 $tmp[] = $k.
'='.$this->quote($v, $this->fields[$k]);
10620 foreach ($keys as $key) {
10621 if (preg_match(
'/^integer:/i', $this->fields[$key][
'type']) && $values[$key] ==
'-1') {
10622 $values[$key] =
'';
10624 if (!empty($this->fields[$key][
'foreignkey']) && $values[$key] ==
'-1') {
10625 $values[$key] =
'';
10637 $sql =
'UPDATE '.$this->db->prefix().$this->table_element.
' SET '.implode(
', ', $tmp).
' WHERE rowid='.((int) $this->
id);
10639 $this->db->begin();
10642 $res = $this->db->query($sql);
10645 $this->errors[] = $this->db->lasterror();
10651 $result = $this->insertExtraFields();
10658 if (!$error && !$notrigger) {
10660 $result = $this->call_trigger(strtoupper(get_class($this)).
'_MODIFY', $user);
10669 $this->db->rollback();
10672 $this->db->commit();
10687 dol_syslog(get_class($this).
"::deleteCommon delete", LOG_DEBUG);
10691 $this->db->begin();
10693 if ($forcechilddeletion) {
10694 foreach ($this->childtables as $table) {
10695 $sql =
"DELETE FROM ".$this->db->prefix().$table.
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
10696 $resql = $this->db->query($sql);
10698 $this->error = $this->db->lasterror();
10699 $this->errors[] = $this->error;
10700 $this->db->rollback();
10704 } elseif (!empty($this->childtables)) {
10705 $objectisused = $this->isObjectUsed($this->
id);
10706 if (!empty($objectisused)) {
10707 dol_syslog(get_class($this).
"::deleteCommon Can't delete record as it has some child", LOG_WARNING);
10708 $this->error =
'ErrorRecordHasChildren';
10709 $this->errors[] = $this->error;
10710 $this->db->rollback();
10716 if (is_array($this->childtablesoncascade) && !empty($this->childtablesoncascade)) {
10717 foreach ($this->childtablesoncascade as $tabletodelete) {
10718 $deleteFromObject = explode(
':', $tabletodelete, 4);
10719 if (count($deleteFromObject) >= 2) {
10720 $className = str_replace(
'@',
'', $deleteFromObject[0]);
10721 $filePath = $deleteFromObject[1];
10722 $columnName = $deleteFromObject[2];
10724 if (!empty($deleteFromObject[3])) {
10725 $filter = $deleteFromObject[3];
10728 $childObject =
new $className($this->db);
10729 if (method_exists($childObject,
'deleteByParentField')) {
10730 '@phan-var-force CommonObject $childObject';
10731 $result = $childObject->deleteByParentField($this->
id, $columnName, $filter);
10734 $this->errors[] = $childObject->error;
10739 $this->errors[] =
"You defined a cascade delete on an object $className/$this->id but there is no method deleteByParentField for it";
10744 $this->errors[] =
'Cannot include child class file '.$filePath;
10749 $sql =
"DELETE FROM ".$this->db->prefix().$tabletodelete.
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
10751 $resql = $this->db->query($sql);
10754 $this->error = $this->db->lasterror();
10755 $this->errors[] = $this->error;
10765 $result = $this->call_trigger(strtoupper(get_class($this)).
'_DELETE', $user);
10775 $res = $this->deleteEcmFiles(1);
10782 $res = $this->deleteObjectLinked();
10787 if (!$error && !empty($this->isextrafieldmanaged)) {
10788 $result = $this->deleteExtraFields();
10795 $sql =
'DELETE FROM '.$this->db->prefix().$this->table_element.
' WHERE rowid='.((int) $this->
id);
10797 $resql = $this->db->query($sql);
10800 $this->errors[] = $this->db->lasterror();
10806 $this->db->rollback();
10809 $this->db->commit();
10832 if (!empty($parentId) && !empty($parentField)) {
10833 $this->db->begin();
10835 $sql =
"SELECT rowid FROM ".$this->db->prefix().$this->table_element;
10836 $sql .=
" WHERE ".$this->db->sanitize($parentField).
" = ".(int) $parentId;
10839 $errormessage =
'';
10841 if ($errormessage) {
10842 $this->errors[] = $errormessage;
10843 dol_syslog(__METHOD__.
' '.implode(
',', $this->errors), LOG_ERR);
10847 $resql = $this->db->query($sql);
10849 $this->errors[] = $this->db->lasterror();
10852 while ($obj = $this->db->fetch_object($resql)) {
10853 $result = $this->fetch($obj->rowid);
10856 $this->errors[] = $this->error;
10858 $result = $this->
delete($user);
10861 $this->errors[] = $this->error;
10869 if (empty($error)) {
10870 $this->db->commit();
10873 $this->error = implode(
', ', $this->errors);
10874 $this->db->rollback();
10875 return $error * -1;
10894 $tmpforobjectclass = get_class($this);
10895 $tmpforobjectlineclass = ucfirst($tmpforobjectclass).
'Line';
10897 $this->db->begin();
10900 $result = $this->call_trigger(
'LINE'.strtoupper($tmpforobjectclass).
'_DELETE', $user);
10906 if (empty($error)) {
10907 $sql =
"DELETE FROM ".$this->db->prefix().$this->table_element_line;
10908 $sql .=
" WHERE rowid = ".((int) $idline);
10910 $resql = $this->db->query($sql);
10912 $this->error =
"Error ".$this->db->lasterror();
10917 if (empty($error)) {
10919 $tmpobjectline =
new $tmpforobjectlineclass($this->db);
10920 '@phan-var-force CommonObjectLine $tmpobjectline';
10921 if (!isset($tmpobjectline->isextrafieldmanaged) || !empty($tmpobjectline->isextrafieldmanaged)) {
10922 $tmpobjectline->id = $idline;
10923 $result = $tmpobjectline->deleteExtraFields();
10926 $this->error =
"Error ".get_class($this).
"::deleteLineCommon deleteExtraFields error -4 ".$tmpobjectline->error;
10931 if (empty($error)) {
10932 $this->db->commit();
10935 dol_syslog(get_class($this).
"::deleteLineCommon ERROR:".$this->error, LOG_ERR);
10936 $this->db->rollback();
10955 $this->db->begin();
10957 $statusfield =
'status';
10958 if (in_array($this->element, array(
'don',
'donation',
'shipping'))) {
10959 $statusfield =
'fk_statut';
10962 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
10963 $sql .=
" SET ".$statusfield.
" = ".((int) $status);
10964 $sql .=
" WHERE rowid = ".((int) $this->
id);
10966 if ($this->db->query($sql)) {
10968 $this->oldcopy = clone $this;
10971 if (!$error && !$notrigger) {
10973 $result = $this->call_trigger($triggercode, $user);
10980 $this->
status = $status;
10981 if (property_exists($this,
'statut')) {
10982 $this->statut = $status;
10984 $this->db->commit();
10987 $this->db->rollback();
10991 $this->error = $this->db->error();
10992 $this->db->rollback();
11008 $this->specimen = 1;
11010 'label' =>
'This is label',
11011 'ref' =>
'ABCD1234',
11012 'description' =>
'This is a description',
11014 'note_public' =>
'Public note',
11015 'note_private' =>
'Private note',
11016 'date_creation' => (
dol_now() - 3600 * 48),
11017 'date_modification' => (
dol_now() - 3600 * 24),
11018 'fk_user_creat' => $user->id,
11019 'fk_user_modif' => $user->id,
11022 foreach ($fields as $key => $value) {
11023 if (array_key_exists($key, $this->fields)) {
11024 $this->{$key} = $value;
11029 if (property_exists($this,
'fields')) {
11030 foreach ($this->fields as $key => $value) {
11032 if (array_key_exists($key, $fields)) {
11036 if (!empty($value[
'default'])) {
11037 $this->$key = $value[
'default'];
11055 require_once DOL_DOCUMENT_ROOT.
'/core/class/comment.class.php';
11057 $comment =
new Comment($this->db);
11058 $result = $comment->fetchAllFor($this->element, $this->
id);
11060 $this->errors = array_merge($this->errors, $comment->errors);
11063 $this->comments = $comment->comments;
11065 return count($this->comments);
11075 return count($this->comments);
11086 if (!is_array($parameters)) {
11089 foreach ($parameters as $parameter) {
11090 if (isset($this->$parameter)) {
11091 $this->$parameter = trim($this->$parameter);
11110 require_once DOL_DOCUMENT_ROOT.
'/categories/class/categorie.class.php';
11114 $existing = $c->containing($this->
id, $type_categ,
'id');
11134 if (!is_array($categories)) {
11135 $categories = array($categories);
11138 dol_syslog(get_class($this).
"::setCategoriesCommon Object Id:".$this->
id.
' type_categ:'.$type_categ.
' nb tag add:'.count($categories), LOG_DEBUG);
11140 require_once DOL_DOCUMENT_ROOT.
'/categories/class/categorie.class.php';
11142 if (empty($type_categ)) {
11143 dol_syslog(__METHOD__.
': Type '.$type_categ.
'is an unknown category type. Done nothing.', LOG_ERR);
11149 $existing = $c->containing($this->
id, $type_categ,
'id');
11150 if ($remove_existing) {
11152 if (is_array($existing)) {
11153 $to_del = array_diff($existing, $categories);
11154 $to_add = array_diff($categories, $existing);
11157 $to_add = $categories;
11161 $to_add = array_diff($categories, $existing);
11168 foreach ($to_del as $del) {
11169 if ($c->fetch($del) > 0) {
11170 $result = $c->del_type($this, $type_categ);
11173 $this->error = $c->error;
11174 $this->errors = $c->errors;
11181 foreach ($to_add as $add) {
11182 if ($c->fetch($add) > 0) {
11183 $result = $c->add_type($this, $type_categ);
11186 $this->error = $c->error;
11187 $this->errors = $c->errors;
11195 return $error ? (-1 * $error) : $ok;
11208 $this->db->begin();
11210 if (empty($type)) {
11211 $type = $this->table_element;
11214 require_once DOL_DOCUMENT_ROOT.
'/categories/class/categorie.class.php';
11215 $categorystatic =
new Categorie($this->db);
11217 $sql =
"INSERT INTO ".$this->db->prefix().
"categorie_".(empty($categorystatic->MAP_CAT_TABLE[$type]) ? $type : $categorystatic->MAP_CAT_TABLE[$type]).
" (fk_categorie, fk_product)";
11218 $sql .=
" SELECT fk_categorie, $toId FROM ".$this->db->prefix().
"categorie_".(empty($categorystatic->MAP_CAT_TABLE[$type]) ? $type : $categorystatic->MAP_CAT_TABLE[$type]);
11219 $sql .=
" WHERE fk_product = ".((int) $fromId);
11221 if (!$this->db->query($sql)) {
11222 $this->error = $this->db->lasterror();
11223 $this->db->rollback();
11227 $this->db->commit();
11241 $this->db->begin();
11245 switch ($this->element) {
11247 $element =
'propale';
11250 $element =
'produit';
11252 case 'order_supplier':
11253 $element =
'fournisseur/commande';
11255 case 'invoice_supplier':
11258 $element =
'fournisseur/facture/'.get_exdir($this->
id, 2, 0, 1, $this,
'invoice_supplier');
11261 $element =
'expedition/sending';
11264 case 'project_task':
11265 require_once DOL_DOCUMENT_ROOT.
'/projet/class/task.class.php';
11267 $project_result = $this->fetchProject();
11268 if ($project_result >= 0) {
11269 $element =
'projet/'.dol_sanitizeFileName($this->project->ref).
'/';
11273 $element = $this->element;
11275 '@phan-var-force string $element';
11278 $sql =
"DELETE FROM ".$this->db->prefix().
"ecm_files_extrafields WHERE fk_object IN (";
11279 $sql .=
" SELECT rowid FROM ".$this->db->prefix().
"ecm_files WHERE filename LIKE '".$this->db->escape($this->
ref).
"%'";
11280 $sql .=
" AND filepath = '".$this->db->escape($element).
"/".$this->db->escape($this->
ref).
"' AND entity = ".((int) $conf->entity);
11283 if (!$this->db->query($sql)) {
11284 $this->error = $this->db->lasterror();
11285 $this->db->rollback();
11290 $sql =
"DELETE FROM ".$this->db->prefix().
"ecm_files";
11291 $sql .=
" WHERE filename LIKE '".$this->db->escape($this->
ref).
"%'";
11292 $sql .=
" AND filepath = '".$this->db->escape($element).
"/".$this->db->escape($this->
ref).
"' AND entity = ".((int) $conf->entity);
11294 if (!$this->db->query($sql)) {
11295 $this->error = $this->db->lasterror();
11296 $this->db->rollback();
11303 $sql =
'DELETE FROM '.$this->db->prefix().
"ecm_files_extrafields";
11304 $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).
")";
11305 $resql = $this->db->query($sql);
11307 $this->error = $this->db->lasterror();
11308 $this->db->rollback();
11312 $sql =
'DELETE FROM '.$this->db->prefix().
"ecm_files";
11313 $sql .=
" WHERE src_object_type = '".$this->db->escape($this->table_element.(empty($this->module) ?
"" :
"@".$this->module)).
"' AND src_object_id = ".((int) $this->
id);
11314 $resql = $this->db->query($sql);
11316 $this->error = $this->db->lasterror();
11317 $this->db->rollback();
11322 $this->db->commit();
if( $user->socid > 0) if(! $user->hasRight('accounting', 'chartofaccount')) $object
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 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.
addThumbs($file)
Build thumb.
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)
insertExtraLanguages($trigger='', $userused=null)
Add/Update all extra fields 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.
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.
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 ECM files.
const TYPE_CREDIT_NOTE
Credit note invoice.
Class to manage triggers.
Parent class to manage intervention document templates.
static getIdAndTxFromCode($dbs, $code, $date_document='')
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.
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.
completeFileArrayWithDatabaseInfo(&$filearray, $relativedir)
Complete $filearray with data from database.
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...
img_object($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0)
Show a picto called object_picto (generic function)
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)
Return an IP formatted to be shown on screen.
img_delete($titlealt='default', $other='class="pictodelete"', $morecss='')
Show delete logo.
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2)
Show picto whatever it's its name (generic function)
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 '.
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.
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'.
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_sanitizeFileName($str, $newstr='_', $unaccent=1)
Clean a string to use it as a file name.
dol_print_error($db=null, $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
dol_trunc($string, $size=40, $trunc='right', $stringencoding='UTF-8', $nodot=0, $display=0)
Truncate a string to a particular length adding '…' if string larger than length.
dol_htmlentitiesbr($stringtoencode, $nl2brmode=0, $pagecodefrom='UTF-8', $removelasteolbr=1)
This function is called to encode a string into a HTML string but differs from htmlentities because a...
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
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.
calcul_price_total($qty, $pu, $remise_percent_ligne, $txtva, $uselocaltax1_rate, $uselocaltax2_rate, $remise_percent_global, $price_base_type, $info_bits, $type, $seller='', $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:/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.
dolEncrypt($chain, $key='', $ciphering='', $forceseed='')
Encode a string with a symmetric encryption.
dolDecrypt($chain, $key='')
Decode a string with a symmetric encryption.
dol_hash($chain, $type='0', $nosalt=0)
Returns a hash (non reversible encryption) of a string.