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 = ".$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);
1380 $resql = $this->db->query($sql);
1384 $this->error = $this->db->lasterror();
1406 if (!$error && empty($notrigger)) {
1408 $this->context[
'contact_id'] = ((int) $rowid);
1409 $result = $this->
call_trigger(strtoupper($this->element).
'_DELETE_CONTACT', $user);
1417 dol_syslog(get_class($this).
"::delete_contact", LOG_DEBUG);
1419 $sql =
"DELETE FROM ".MAIN_DB_PREFIX.
"element_contact";
1420 $sql .=
" WHERE rowid = ".((int) $rowid);
1422 $result = $this->db->query($sql);
1425 $this->errors[] = $this->db->lasterror();
1430 $this->db->commit();
1433 $this->error = $this->db->lasterror();
1434 $this->db->rollback();
1454 if (!empty($typeContact)) {
1455 foreach ($typeContact as $key => $value) {
1456 array_push($temp, $key);
1458 $listId = implode(
",", $temp);
1463 if (empty($listId)) {
1467 $sql =
"DELETE FROM ".$this->db->prefix().
"element_contact";
1468 $sql .=
" WHERE element_id = ".((int) $this->
id);
1469 $sql .=
" AND fk_c_type_contact IN (".$this->db->sanitize($listId).
")";
1471 dol_syslog(get_class($this).
"::delete_linked_contact", LOG_DEBUG);
1472 if ($this->db->query($sql)) {
1475 $this->error = $this->db->lasterror();
1492 public function liste_contact($statusoflink = -1, $source =
'external', $list = 0, $code =
'', $status = -1, $arrayoftcids = array())
1499 $sql =
"SELECT ec.rowid, ec.statut as statuslink, ec.fk_socpeople as id, ec.fk_c_type_contact";
1500 if ($source ==
'internal') {
1501 $sql .=
", '-1' as socid, t.statut as statuscontact, t.login, t.photo, t.gender";
1503 if ($source ==
'external' || $source ==
'thirdparty') {
1504 $sql .=
", t.fk_soc as socid, t.statut as statuscontact";
1506 $sql .=
", t.civility as civility, t.lastname as lastname, t.firstname, t.email";
1507 if (empty($arrayoftcids)) {
1508 $sql .=
", tc.source, tc.element, tc.code, tc.libelle as type_label";
1511 if (empty($arrayoftcids)) {
1512 $sql .=
" ".$this->db->prefix().
"c_type_contact as tc,";
1514 $sql .=
" ".$this->db->prefix().
"element_contact as ec";
1515 if ($source ==
'internal') {
1516 $sql .=
" LEFT JOIN ".$this->db->prefix().
"user as t on ec.fk_socpeople = t.rowid";
1518 if ($source ==
'external' || $source ==
'thirdparty') {
1519 $sql .=
" LEFT JOIN ".$this->db->prefix().
"socpeople as t on ec.fk_socpeople = t.rowid";
1521 $sql .=
" WHERE ec.element_id = ".((int) $this->
id);
1522 if (empty($arrayoftcids)) {
1523 $sql .=
" AND ec.fk_c_type_contact = tc.rowid";
1524 $sql .=
" AND tc.element = '".$this->db->escape($this->element).
"'";
1526 $sql .=
" AND tc.code = '".$this->db->escape($code).
"'";
1528 if ($source ==
'internal') {
1529 $sql .=
" AND tc.source = 'internal'";
1531 if ($source ==
'external' || $source ==
'thirdparty') {
1532 $sql .=
" AND tc.source = 'external'";
1534 $sql .=
" AND tc.active = 1";
1536 $sql .=
" AND ec.fk_c_type_contact IN (".$this->db->sanitize(implode(
',', $arrayoftcids)).
")";
1539 $sql .=
" AND t.statut = ".((int) $status);
1541 if ($statusoflink >= 0) {
1542 $sql .=
" AND ec.statut = ".((int) $statusoflink);
1544 $sql .=
" ORDER BY t.lastname ASC";
1546 dol_syslog(get_class($this).
"::liste_contact", LOG_DEBUG);
1547 $resql = $this->db->query($sql);
1549 $num = $this->db->num_rows($resql);
1552 $obj = $this->db->fetch_object($resql);
1555 $transkey =
"TypeContact_".$obj->element.
"_".$obj->source.
"_".$obj->code;
1556 $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->type_label);
1558 'parentId' => $this->
id,
1559 'source' => $obj->source,
1560 'socid' => $obj->socid,
1562 'nom' => $obj->lastname,
1563 'civility' => $obj->civility,
1564 'lastname' => $obj->lastname,
1565 'firstname' => $obj->firstname,
1566 'email' => $obj->email,
1567 'login' => (empty($obj->login) ?
'' : $obj->login),
1568 'photo' => (empty($obj->photo) ?
'' : $obj->photo),
1569 'gender' => (empty($obj->gender) ?
'' : $obj->gender),
1570 'statuscontact' => $obj->statuscontact,
1571 'rowid' => $obj->rowid,
1572 'code' => $obj->code,
1573 'libelle' => $libelle_type,
1574 'status' => $obj->statuslink,
1575 'fk_c_type_contact' => $obj->fk_c_type_contact
1578 $tab[$i] = $obj->id;
1586 $this->error = $this->db->lasterror();
1601 $sql =
"SELECT ec.datecreate, ec.statut, ec.fk_socpeople, ec.fk_c_type_contact,";
1602 $sql .=
" tc.code, tc.libelle as type_label";
1603 $sql .=
" FROM (".$this->db->prefix().
"element_contact as ec, ".$this->db->prefix().
"c_type_contact as tc)";
1604 $sql .=
" WHERE ec.rowid =".((int) $rowid);
1605 $sql .=
" AND ec.fk_c_type_contact = tc.rowid";
1606 $sql .=
" AND tc.element = '".$this->db->escape($this->element).
"'";
1608 dol_syslog(get_class($this).
"::swapContactStatus", LOG_DEBUG);
1609 $resql = $this->db->query($sql);
1611 $obj = $this->db->fetch_object($resql);
1612 $newstatut = ($obj->statut == 4) ? 5 : 4;
1614 $this->db->free($resql);
1617 $this->error = $this->db->error();
1634 public function liste_type_contact($source =
'internal', $order =
'position', $option = 0, $activeonly = 0, $code =
'')
1639 if (empty($order)) {
1640 $order =
'position';
1642 if ($order ==
'position') {
1647 $sql =
"SELECT DISTINCT tc.rowid, tc.code, tc.libelle as type_label, tc.position";
1648 $sql .=
" FROM ".$this->db->prefix().
"c_type_contact as tc";
1649 $sql .=
" WHERE tc.element='".$this->db->escape($this->element).
"'";
1650 if ($activeonly == 1) {
1651 $sql .=
" AND tc.active=1";
1653 if (!empty($source) && $source !=
'all') {
1654 $sql .=
" AND tc.source='".$this->db->escape($source).
"'";
1656 if (!empty($code)) {
1657 $sql .=
" AND tc.code='".$this->db->escape($code).
"'";
1659 $sql .= $this->db->order($order,
'ASC');
1662 $resql = $this->db->query($sql);
1664 $num = $this->db->num_rows($resql);
1667 $obj = $this->db->fetch_object($resql);
1669 $transkey =
"TypeContact_".$this->element.
"_".$source.
"_".$obj->code;
1670 $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->type_label);
1671 if (empty($option)) {
1672 $tab[$obj->rowid] = $libelle_type;
1674 $tab[$obj->code] = $libelle_type;
1680 $this->error = $this->db->lasterror();
1697 public function listeTypeContacts($source =
'internal', $option = 0, $activeonly = 0, $code =
'', $element =
'', $excludeelement =
'')
1699 global $langs, $conf;
1701 $langs->loadLangs(array(
'bills',
'contracts',
'interventions',
'orders',
'projects',
'propal',
'ticket',
'agenda'));
1705 $sql =
"SELECT DISTINCT tc.rowid, tc.code, tc.libelle as type_label, tc.position, tc.element";
1706 $sql .=
" FROM ".$this->db->prefix().
"c_type_contact as tc";
1708 $sqlWhere = array();
1709 if (!empty($element)) {
1710 $sqlWhere[] =
" tc.element='".$this->db->escape($element).
"'";
1712 if (!empty($excludeelement)) {
1713 $sqlWhere[] =
" tc.element <> '".$this->db->escape($excludeelement).
"'";
1716 if ($activeonly == 1) {
1717 $sqlWhere[] =
" tc.active=1";
1720 if (!empty($source) && $source !=
'all') {
1721 $sqlWhere[] =
" tc.source='".$this->db->escape($source).
"'";
1724 if (!empty($code)) {
1725 $sqlWhere[] =
" tc.code='".$this->db->escape($code).
"'";
1728 if (count($sqlWhere) > 0) {
1729 $sql .=
" WHERE ".implode(
' AND ', $sqlWhere);
1732 $sql .= $this->db->order(
'tc.element, tc.position',
'ASC');
1735 $resql = $this->db->query($sql);
1737 $num = $this->db->num_rows($resql);
1739 $langs->loadLangs(array(
"propal",
"orders",
"bills",
"suppliers",
"contracts",
"supplier_proposal"));
1741 while ($obj = $this->db->fetch_object($resql)) {
1742 $modulename = $obj->element;
1743 if (strpos($obj->element,
'project') !==
false) {
1744 $modulename =
'projet';
1745 } elseif ($obj->element ==
'contrat') {
1746 $element =
'contract';
1747 } elseif ($obj->element ==
'action') {
1748 $modulename =
'agenda';
1749 } elseif (strpos($obj->element,
'supplier') !==
false && $obj->element !=
'supplier_proposal') {
1750 $modulename =
'fournisseur';
1752 if (!empty($conf->{$modulename}->enabled)) {
1753 $libelle_element = $langs->trans(
'ContactDefault_'.$obj->element);
1754 $tmpelement = $obj->element;
1755 $transkey =
"TypeContact_".$tmpelement.
"_".$source.
"_".$obj->code;
1756 $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->type_label);
1757 $tab[$obj->rowid] = $libelle_element.
' - '.$libelle_type;
1763 $this->error = $this->db->lasterror();
1786 if ($this->element ==
'shipping' && $this->origin_id != 0) {
1787 $id = $this->origin_id;
1788 $element =
'commande';
1789 } elseif ($this->element ==
'reception' && $this->origin_id != 0) {
1790 $id = $this->origin_id;
1791 $element =
'order_supplier';
1794 $element = $this->element;
1797 $sql =
"SELECT ec.fk_socpeople";
1798 $sql .=
" FROM ".$this->db->prefix().
"element_contact as ec,";
1799 if ($source ==
'internal') {
1800 $sql .=
" ".$this->db->prefix().
"user as c,";
1802 if ($source ==
'external') {
1803 $sql .=
" ".$this->db->prefix().
"socpeople as c,";
1805 $sql .=
" ".$this->db->prefix().
"c_type_contact as tc";
1806 $sql .=
" WHERE ec.element_id = ".((int)
$id);
1807 $sql .=
" AND ec.fk_socpeople = c.rowid";
1808 if ($source ==
'internal') {
1809 $sql .=
" AND c.entity IN (".getEntity(
'user').
")";
1811 if ($source ==
'external') {
1812 $sql .=
" AND c.entity IN (".getEntity(
'societe').
")";
1814 $sql .=
" AND ec.fk_c_type_contact = tc.rowid";
1815 $sql .=
" AND tc.element = '".$this->db->escape($element).
"'";
1816 $sql .=
" AND tc.source = '".$this->db->escape($source).
"'";
1818 $sql .=
" AND tc.code = '".$this->db->escape($code).
"'";
1820 $sql .=
" AND tc.active = 1";
1822 $sql .=
" AND ec.statut = ".((int) $status);
1825 dol_syslog(get_class($this).
"::getIdContact", LOG_DEBUG);
1826 $resql = $this->db->query($sql);
1828 while ($obj = $this->db->fetch_object($resql)) {
1829 $result[$i] = $obj->fk_socpeople;
1833 $this->error = $this->db->error();
1850 if (empty($contactid)) {
1851 $contactid = $this->contact_id;
1854 if (empty($contactid)) {
1858 require_once DOL_DOCUMENT_ROOT.
'/contact/class/contact.class.php';
1859 $contact =
new Contact($this->db);
1860 $result = $contact->fetch($contactid);
1861 $this->contact = $contact;
1876 if (empty($this->socid) && empty($this->fk_soc) && empty($force_thirdparty_id)) {
1880 require_once DOL_DOCUMENT_ROOT.
'/societe/class/societe.class.php';
1882 $idtofetch = isset($this->socid) ? $this->socid : (isset($this->fk_soc) ? $this->fk_soc : 0);
1883 if ($force_thirdparty_id) {
1884 $idtofetch = $force_thirdparty_id;
1888 $thirdparty =
new Societe($this->db);
1889 $result = $thirdparty->fetch($idtofetch);
1891 $this->errors = array_merge($this->errors, $thirdparty->errors);
1893 $this->thirdparty = $thirdparty;
1897 $this->thirdparty->price_level = 1;
1916 if (!$this->table_ref_field) {
1920 $sql =
"SELECT rowid FROM ".$this->db->prefix().$this->table_element;
1921 $sql .=
" WHERE ".$this->table_ref_field.
" LIKE '".$this->db->escape($ref).
"'";
1924 $query = $this->db->query($sql);
1926 if (!$this->db->num_rows($query)) {
1930 $result = $this->db->fetch_object($query);
1932 if (method_exists($this,
'fetch')) {
1933 return $this->fetch($result->rowid);
1935 $this->error =
'Fetch method not implemented on '.get_class($this);
1936 dol_syslog(get_class($this).
'::fetchOneLike Error='.$this->error, LOG_ERR);
1937 array_push($this->errors, $this->error);
1955 dol_syslog(get_class($this).
'::fetch_barcode this->element='.$this->element.
' this->barcode_type='.$this->barcode_type);
1957 $idtype = $this->barcode_type;
1958 if (empty($idtype) && $idtype !=
'0') {
1959 if ($this->element ==
'product' &&
getDolGlobalString(
'PRODUIT_DEFAULT_BARCODE_TYPE')) {
1961 } elseif ($this->element ==
'societe') {
1964 dol_syslog(
'Call fetch_barcode with barcode_type not defined and cannot be guessed', LOG_WARNING);
1969 if (empty($this->barcode_type) || empty($this->barcode_type_code) || empty($this->barcode_type_label) || empty($this->barcode_type_coder)) {
1970 $sql =
"SELECT rowid, code, libelle as label, coder";
1971 $sql .=
" FROM ".$this->db->prefix().
"c_barcode_type";
1972 $sql .=
" WHERE rowid = ".((int) $idtype);
1973 dol_syslog(get_class($this).
'::fetch_barcode', LOG_DEBUG);
1974 $resql = $this->db->query($sql);
1976 $obj = $this->db->fetch_object($resql);
1977 $this->barcode_type = $obj->rowid;
1978 $this->barcode_type_code = $obj->code;
1979 $this->barcode_type_label = $obj->label;
1980 $this->barcode_type_coder = $obj->coder;
2000 return $this->fetch_projet();
2012 include_once DOL_DOCUMENT_ROOT.
'/projet/class/project.class.php';
2014 if (empty($this->fk_project) && !empty($this->fk_projet)) {
2015 $this->fk_project = $this->fk_projet;
2017 if (empty($this->fk_project)) {
2021 $project =
new Project($this->db);
2022 $result = $project->fetch($this->fk_project);
2024 $this->projet = $project;
2025 $this->project = $project;
2038 include_once DOL_DOCUMENT_ROOT.
'/product/class/product.class.php';
2041 if (empty($this->fk_product)) {
2045 $product =
new Product($this->db);
2047 $result = $product->fetch($this->fk_product);
2049 $this->product = $product;
2063 $user =
new User($this->db);
2064 $result = $user->fetch($userid);
2065 $this->
user = $user;
2079 $origin = $this->origin ? $this->origin : $this->origin_type;
2082 if ($origin ==
'shipping') {
2083 $origin =
'expedition';
2085 if ($origin ==
'delivery') {
2086 $origin =
'livraison';
2088 if ($origin ==
'order_supplier' || $origin ==
'supplier_order') {
2089 $origin =
'commandeFournisseur';
2092 $classname = ucfirst($origin);
2093 $this->origin_object =
new $classname($this->db);
2095 $this->origin_object->fetch($this->origin_id);
2113 $sql =
"SELECT rowid FROM ".$this->db->prefix().$table;
2114 $sql .=
" WHERE ".$field.
" = '".$this->db->escape($key).
"'";
2115 if (!empty($element)) {
2116 $sql .=
" AND entity IN (".getEntity($element).
")";
2118 $sql .=
" AND entity = ".((int) $conf->entity);
2121 dol_syslog(get_class($this).
'::fetchObjectFrom', LOG_DEBUG);
2122 $resql = $this->db->query($sql);
2124 $obj = $this->db->fetch_object($resql);
2127 if (method_exists($this,
'fetch')) {
2128 $result = $this->fetch($obj->rowid);
2130 $this->error =
'fetch() method not implemented on '.get_class($this);
2131 dol_syslog(get_class($this).
'::fetchOneLike Error='.$this->error, LOG_ERR);
2132 array_push($this->errors, $this->error);
2152 if (!empty(
$id) && !empty($field) && !empty($table)) {
2153 $sql =
"SELECT ".$field.
" FROM ".$this->db->prefix().$table;
2154 $sql .=
" WHERE rowid = ".((int)
$id);
2156 dol_syslog(get_class($this).
'::getValueFrom', LOG_DEBUG);
2157 $resql = $this->db->query($sql);
2159 $row = $this->db->fetch_row($resql);
2182 public function setValueFrom($field, $value, $table =
'',
$id =
null, $format =
'', $id_field =
'', $fuser =
null, $trigkey =
'', $fk_user_field =
'fk_user_modif')
2186 if (empty($table)) {
2187 $table = $this->table_element;
2192 if (empty($format)) {
2195 if (empty($id_field)) {
2196 $id_field =
'rowid';
2200 if ($table ==
'product' && $field ==
'note_private') {
2204 if (in_array($table, array(
'actioncomm',
'adherent',
'advtargetemailing',
'cronjob',
'establishment'))) {
2205 $fk_user_field =
'fk_user_mod';
2207 if (in_array($table, array(
'prelevement_bons'))) {
2208 $fk_user_field =
'';
2213 $sql =
"SELECT " . $field;
2214 $sql .=
" FROM " . MAIN_DB_PREFIX . $table;
2215 $sql .=
" WHERE " . $id_field .
" = " . ((int)
$id);
2217 $resql = $this->db->query($sql);
2219 if ($obj = $this->db->fetch_object($resql)) {
2220 if ($format ==
'date') {
2221 $oldvalue = $this->db->jdate($obj->$field);
2223 $oldvalue = $obj->$field;
2227 $this->error = $this->db->lasterror();
2238 $sql =
"UPDATE ".$this->db->prefix().$table.
" SET ";
2240 if ($format ==
'text') {
2241 $sql .= $field.
" = '".$this->db->escape($value).
"'";
2242 } elseif ($format ==
'int') {
2243 $sql .= $field.
" = ".((int) $value);
2244 } elseif ($format ==
'date') {
2245 $sql .= $field.
" = ".($value ?
"'".$this->db->idate($value).
"'" :
"null");
2246 } elseif ($format ==
'dategmt') {
2247 $sql .= $field.
" = ".($value ?
"'".$this->db->idate($value,
'gmt').
"'" :
"null");
2250 if ($fk_user_field) {
2251 if (!empty($fuser) && is_object($fuser)) {
2252 $sql .=
", ".$fk_user_field.
" = ".((int) $fuser->id);
2253 } elseif (empty($fuser) || $fuser !=
'none') {
2254 $sql .=
", ".$fk_user_field.
" = ".((int) $user->id);
2258 $sql .=
" WHERE ".$id_field.
" = ".((int)
$id);
2260 $resql = $this->db->query($sql);
2264 if (method_exists($this,
'fetch')) {
2265 $result = $this->fetch(
$id);
2267 $result = $this->fetchCommon(
$id);
2269 $this->oldcopy = clone $this;
2270 if (property_exists($this->oldcopy, $field)) {
2271 $this->oldcopy->$field = $oldvalue;
2275 $result = $this->call_trigger($trigkey, (!empty($fuser) && is_object($fuser)) ? $fuser : $user);
2283 if (property_exists($this, $field)) {
2284 $this->$field = $value;
2286 $this->db->commit();
2289 $this->db->rollback();
2293 if ($this->db->lasterrno() ==
'DB_ERROR_RECORD_ALREADY_EXISTS') {
2294 $this->error =
'DB_ERROR_RECORD_ALREADY_EXISTS';
2296 $this->error = $this->db->lasterror();
2298 $this->db->rollback();
2317 global $conf, $user;
2319 if (!$this->table_element) {
2320 dol_print_error(
null, get_class($this).
"::load_previous_next_ref was called on object with property table_element not defined");
2323 if ($fieldid ==
'none') {
2328 if (in_array($this->table_element, array(
'facture_rec',
'facture_fourn_rec')) && $fieldid ==
'title') {
2334 if ($user->socid > 0) {
2335 $socid = $user->socid;
2340 $aliastablesociete =
's';
2341 if ($this->element ==
'societe') {
2342 $aliastablesociete =
'te';
2344 $restrictiononfksoc = empty($this->restrictiononfksoc) ? 0 : $this->restrictiononfksoc;
2345 $sql =
"SELECT MAX(te.".$fieldid.
")";
2346 $sql .=
" FROM ".(empty($nodbprefix) ? $this->db->prefix() :
'').$this->table_element.
" as te";
2347 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2348 $tmparray = explode(
'@', $this->ismultientitymanaged);
2349 $sql .=
", ".$this->db->prefix().$tmparray[1].
" as ".($tmparray[1] ==
'societe' ?
's' :
'parenttable');
2350 } elseif ($restrictiononfksoc == 1 && $this->element !=
'societe' && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2351 $sql .=
", ".$this->db->prefix().
"societe as s";
2352 } elseif ($restrictiononfksoc == 2 && $this->element !=
'societe' && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2353 $sql .=
" LEFT JOIN ".$this->db->prefix().
"societe as s ON te.fk_soc = s.rowid";
2355 if ($restrictiononfksoc && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2356 $sql .=
" LEFT JOIN ".$this->db->prefix().
"societe_commerciaux as sc ON ".$aliastablesociete.
".rowid = sc.fk_soc";
2358 if ($fieldid ==
'rowid') {
2359 $sql .=
" WHERE te.".$fieldid.
" < ".((int) $this->
id);
2361 $sql .=
" WHERE te.".$fieldid.
" < '".$this->db->escape($this->
ref).
"'";
2363 if ($restrictiononfksoc == 1 && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2364 $sql .=
" AND sc.fk_user = ".((int) $user->id);
2366 if ($restrictiononfksoc == 2 && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2367 $sql .=
" AND (sc.fk_user = ".((int) $user->id).
' OR te.fk_soc IS NULL)';
2370 $filtermax = $filter;
2375 if ($errormessage) {
2376 if (!preg_match(
'/^\s*AND/i', $filtermax)) {
2384 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2385 $tmparray = explode(
'@', $this->ismultientitymanaged);
2386 $sql .=
" AND te.".$tmparray[0].
" = ".($tmparray[1] ==
"societe" ?
"s" :
"parenttable").
".rowid";
2387 } elseif ($restrictiononfksoc == 1 && $this->element !=
'societe' && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2388 $sql .=
' AND te.fk_soc = s.rowid';
2390 if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
2391 if ($this->element ==
'user' &&
getDolGlobalInt(
'MULTICOMPANY_TRANSVERSE_MODE')) {
2392 if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
2393 $sql .=
" AND te.entity IS NOT NULL";
2395 $sql .=
" AND te.rowid IN (SELECT ug.fk_user FROM ".$this->db->prefix().
"usergroup_user as ug WHERE ug.entity IN (".
getEntity(
'usergroup').
"))";
2398 $sql .=
' AND te.entity IN ('.getEntity($this->element).
')';
2401 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged) && $this->element !=
'societe') {
2402 $tmparray = explode(
'@', $this->ismultientitymanaged);
2403 $sql .=
' AND parenttable.entity IN ('.getEntity($tmparray[1]).
')';
2405 if ($restrictiononfksoc == 1 && $socid && $this->element !=
'societe') {
2406 $sql .=
' AND te.fk_soc = '.((int) $socid);
2408 if ($restrictiononfksoc == 2 && $socid && $this->element !=
'societe') {
2409 $sql .=
' AND (te.fk_soc = '.((int) $socid).
' OR te.fk_soc IS NULL)';
2411 if ($restrictiononfksoc && $socid && $this->element ==
'societe') {
2412 $sql .=
' AND te.rowid = '.((int) $socid);
2416 $result = $this->db->query($sql);
2418 $this->error = $this->db->lasterror();
2421 $row = $this->db->fetch_row($result);
2422 $this->ref_previous = $row[0];
2424 $sql =
"SELECT MIN(te.".$fieldid.
")";
2425 $sql .=
" FROM ".(empty($nodbprefix) ? $this->db->prefix() :
'').$this->table_element.
" as te";
2426 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2427 $tmparray = explode(
'@', $this->ismultientitymanaged);
2428 $sql .=
", ".$this->db->prefix().$tmparray[1].
" as ".($tmparray[1] ==
'societe' ?
's' :
'parenttable');
2429 } elseif ($restrictiononfksoc == 1 && $this->element !=
'societe' && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2430 $sql .=
", ".$this->db->prefix().
"societe as s";
2431 } elseif ($restrictiononfksoc == 2 && $this->element !=
'societe' && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2432 $sql .=
" LEFT JOIN ".$this->db->prefix().
"societe as s ON te.fk_soc = s.rowid";
2434 if ($restrictiononfksoc && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2435 $sql .=
" LEFT JOIN ".$this->db->prefix().
"societe_commerciaux as sc ON ".$aliastablesociete.
".rowid = sc.fk_soc";
2437 if ($fieldid ==
'rowid') {
2438 $sql .=
" WHERE te.".$fieldid.
" > ".((int) $this->
id);
2440 $sql .=
" WHERE te.".$fieldid.
" > '".$this->db->escape($this->
ref).
"'";
2442 if ($restrictiononfksoc == 1 && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2443 $sql .=
" AND (sc.fk_user = ".((int) $user->id);
2445 $userschilds = $user->getAllChildIds();
2446 $sql .=
" OR sc.fk_user IN (".$this->db->sanitize(implode(
',', $userschilds)).
")";
2450 if ($restrictiononfksoc == 2 && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2451 $sql .=
" AND (sc.fk_user = ".((int) $user->id).
' OR te.fk_soc IS NULL)';
2454 $filtermin = $filter;
2459 if ($errormessage) {
2460 if (!preg_match(
'/^\s*AND/i', $filtermin)) {
2470 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2471 $tmparray = explode(
'@', $this->ismultientitymanaged);
2472 $sql .=
" AND te.".$tmparray[0].
" = ".($tmparray[1] ==
"societe" ?
"s" :
"parenttable").
".rowid";
2473 } elseif ($restrictiononfksoc == 1 && $this->element !=
'societe' && !$user->hasRight(
'societe',
'client',
'voir') && !$socid) {
2474 $sql .=
' AND te.fk_soc = s.rowid';
2476 if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
2477 if ($this->element ==
'user' &&
getDolGlobalInt(
'MULTICOMPANY_TRANSVERSE_MODE')) {
2478 if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
2479 $sql .=
" AND te.entity IS NOT NULL";
2481 $sql .=
" AND te.rowid IN (SELECT ug.fk_user FROM ".$this->db->prefix().
"usergroup_user as ug WHERE ug.entity IN (".
getEntity(
'usergroup').
"))";
2484 $sql .=
' AND te.entity IN ('.getEntity($this->element).
')';
2487 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged) && $this->element !=
'societe') {
2488 $tmparray = explode(
'@', $this->ismultientitymanaged);
2489 $sql .=
' AND parenttable.entity IN ('.getEntity($tmparray[1]).
')';
2491 if ($restrictiononfksoc == 1 && $socid && $this->element !=
'societe') {
2492 $sql .=
' AND te.fk_soc = '.((int) $socid);
2494 if ($restrictiononfksoc == 2 && $socid && $this->element !=
'societe') {
2495 $sql .=
' AND (te.fk_soc = '.((int) $socid).
' OR te.fk_soc IS NULL)';
2497 if ($restrictiononfksoc && $socid && $this->element ==
'societe') {
2498 $sql .=
' AND te.rowid = '.((int) $socid);
2503 $result = $this->db->query($sql);
2505 $this->error = $this->db->lasterror();
2508 $row = $this->db->fetch_row($result);
2509 $this->ref_next = $row[0];
2524 $contactAlreadySelected = array();
2525 $tab = $this->liste_contact(-1, $source);
2529 if ($source ==
'thirdparty') {
2530 $contactAlreadySelected[$i] = $tab[$i][
'socid'];
2532 $contactAlreadySelected[$i] = $tab[$i][
'id'];
2536 return $contactAlreadySelected;
2552 if (!$this->table_element) {
2553 dol_syslog(get_class($this).
"::setProject was called on object with property table_element not defined", LOG_ERR);
2557 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
2559 if (!empty($this->fields[
'fk_project'])) {
2561 $sql .=
" SET fk_project = ".((int) $projectid);
2563 $sql .=
" SET fk_project = NULL";
2565 $sql .=
' WHERE rowid = '.((int) $this->
id);
2566 } elseif ($this->table_element ==
'actioncomm') {
2568 $sql .=
" SET fk_project = ".((int) $projectid);
2570 $sql .=
" SET fk_project = NULL";
2572 $sql .=
' WHERE id = '.((int) $this->
id);
2575 $sql .=
' SET fk_projet = '.((int) $projectid);
2577 $sql .=
' SET fk_projet = NULL';
2579 $sql .=
" WHERE rowid = ".((int) $this->
id);
2584 dol_syslog(get_class($this).
"::setProject", LOG_DEBUG);
2585 if ($this->db->query($sql)) {
2586 $this->fk_project = ((int) $projectid);
2593 if (!$error && !$notrigger) {
2595 $result = $this->call_trigger(strtoupper($this->element) .
'_MODIFY', $user);
2604 $this->db->rollback();
2607 $this->db->commit();
2625 dol_syslog(get_class($this).
'::setPaymentMethods('.
$id.
')');
2627 if ($this->
status >= 0 || $this->element ==
'societe') {
2629 $fieldname =
'fk_mode_reglement';
2630 if ($this->element ==
'societe') {
2631 $fieldname =
'mode_reglement';
2633 if (get_class($this) ==
'Fournisseur') {
2634 $fieldname =
'mode_reglement_supplier';
2636 if (get_class($this) ==
'Tva') {
2637 $fieldname =
'fk_typepayment';
2639 if (get_class($this) ==
'Salary') {
2640 $fieldname =
'fk_typepayment';
2643 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
2644 $sql .=
" SET ".$fieldname.
" = ".((
$id > 0 ||
$id ==
'0') ? ((
int)
$id) :
'NULL');
2645 $sql .=
' WHERE rowid='.((int) $this->
id);
2647 if ($this->db->query($sql)) {
2648 $this->mode_reglement_id =
$id;
2650 if (get_class($this) ==
'Fournisseur') {
2651 $this->mode_reglement_supplier_id =
$id;
2654 if (!$error && !$notrigger) {
2656 if (get_class($this) ==
'Commande') {
2657 $result = $this->call_trigger(
'ORDER_MODIFY', $user);
2659 $result = $this->call_trigger(strtoupper(get_class($this)).
'_MODIFY', $user);
2668 dol_syslog(get_class($this).
'::setPaymentMethods Error '.$this->db->error());
2669 $this->error = $this->db->error();
2673 dol_syslog(get_class($this).
'::setPaymentMethods, status of the object is incompatible');
2674 $this->error =
'Status of the object is incompatible '.$this->status;
2687 dol_syslog(get_class($this).
'::setMulticurrencyCode('.$code.
')');
2688 if ($this->
status >= 0 || $this->element ==
'societe') {
2689 $fieldname =
'multicurrency_code';
2691 $sql =
'UPDATE '.$this->db->prefix().$this->table_element;
2692 $sql .=
" SET ".$fieldname.
" = '".$this->db->escape($code).
"'";
2693 $sql .=
' WHERE rowid='.((int) $this->
id);
2695 if ($this->db->query($sql)) {
2696 $this->multicurrency_code = $code;
2700 $this->setMulticurrencyRate($rate, 2);
2705 dol_syslog(get_class($this).
'::setMulticurrencyCode Error '.$sql.
' - '.$this->db->error());
2706 $this->error = $this->db->error();
2710 dol_syslog(get_class($this).
'::setMulticurrencyCode, status of the object is incompatible');
2711 $this->error =
'Status of the object is incompatible '.$this->status;
2723 public function setMulticurrencyRate($rate, $mode = 1)
2725 dol_syslog(get_class($this).
'::setMulticurrencyRate('.$rate.
', '.$mode.
')');
2726 if ($this->
status >= 0 || $this->element ==
'societe') {
2727 $fieldname =
'multicurrency_tx';
2729 $sql =
'UPDATE '.$this->db->prefix().$this->table_element;
2730 $sql .=
" SET ".$fieldname.
" = ".((float) $rate);
2731 $sql .=
' WHERE rowid='.((int) $this->
id);
2733 if ($this->db->query($sql)) {
2734 $this->multicurrency_tx = $rate;
2737 if (!empty($this->lines)) {
2738 foreach ($this->lines as &$line) {
2741 $line->subprice = 0;
2746 $line->multicurrency_subprice = 0;
2749 switch ($this->element) {
2753 '@phan-var-force Propal $this';
2754 '@phan-var-force PropaleLigne $line';
2759 $line->remise_percent,
2761 $line->localtax1_tx,
2762 $line->localtax2_tx,
2763 ($line->description ? $line->description : $line->desc),
2766 $line->special_code,
2767 $line->fk_parent_line,
2768 $line->skip_update_total,
2769 $line->fk_fournprice,
2772 $line->product_type,
2775 $line->array_options,
2777 $line->multicurrency_subprice
2783 '@phan-var-force Commande $this';
2784 '@phan-var-force OrderLine $line';
2787 ($line->description ? $line->description : $line->desc),
2790 $line->remise_percent,
2792 $line->localtax1_tx,
2793 $line->localtax2_tx,
2798 $line->product_type,
2799 $line->fk_parent_line,
2800 $line->skip_update_total,
2801 $line->fk_fournprice,
2804 $line->special_code,
2805 $line->array_options,
2807 $line->multicurrency_subprice
2813 '@phan-var-force Facture $this';
2814 '@phan-var-force FactureLigne $line';
2817 ($line->description ? $line->description : $line->desc),
2820 $line->remise_percent,
2824 $line->localtax1_tx,
2825 $line->localtax2_tx,
2828 $line->product_type,
2829 $line->fk_parent_line,
2830 $line->skip_update_total,
2831 $line->fk_fournprice,
2834 $line->special_code,
2835 $line->array_options,
2836 $line->situation_percent,
2838 $line->multicurrency_subprice
2841 case 'supplier_proposal':
2844 '@phan-var-force SupplierProposal $this';
2845 '@phan-var-force SupplierProposalLine $line';
2850 $line->remise_percent,
2852 $line->localtax1_tx,
2853 $line->localtax2_tx,
2854 ($line->description ? $line->description : $line->desc),
2857 $line->special_code,
2858 $line->fk_parent_line,
2859 $line->skip_update_total,
2860 $line->fk_fournprice,
2863 $line->product_type,
2864 $line->array_options,
2866 $line->multicurrency_subprice
2869 case 'order_supplier':
2872 '@phan-var-force CommandeFournisseur $this';
2873 '@phan-var-force CommandeFournisseurLigne $line';
2876 ($line->description ? $line->description : $line->desc),
2879 $line->remise_percent,
2881 $line->localtax1_tx,
2882 $line->localtax2_tx,
2885 $line->product_type,
2889 $line->array_options,
2891 $line->multicurrency_subprice,
2895 case 'invoice_supplier':
2898 '@phan-var-force FactureFournisseur $this';
2899 '@phan-var-force SupplierInvoiceLIne $line';
2902 ($line->description ? $line->description : $line->desc),
2905 $line->localtax1_tx,
2906 $line->localtax2_tx,
2911 $line->product_type,
2912 $line->remise_percent,
2916 $line->array_options,
2918 $line->multicurrency_subprice,
2923 dol_syslog(get_class($this).
'::setMulticurrencyRate no updateline defined', LOG_DEBUG);
2931 dol_syslog(get_class($this).
'::setMulticurrencyRate Error '.$sql.
' - '.$this->db->error());
2932 $this->error = $this->db->error();
2936 dol_syslog(get_class($this).
'::setMulticurrencyRate, status of the object is incompatible');
2937 $this->error =
'Status of the object is incompatible '.$this->status;
2951 dol_syslog(get_class($this).
'::setPaymentTerms('.
$id.
', '.var_export($deposit_percent,
true).
')');
2952 if ($this->
status >= 0 || $this->element ==
'societe') {
2954 $fieldname =
'fk_cond_reglement';
2955 if ($this->element ==
'societe') {
2956 $fieldname =
'cond_reglement';
2958 if (get_class($this) ==
'Fournisseur') {
2959 $fieldname =
'cond_reglement_supplier';
2962 if (empty($deposit_percent) || $deposit_percent < 0) {
2966 if ($deposit_percent > 100) {
2967 $deposit_percent = 100;
2970 $sql =
'UPDATE '.$this->db->prefix().$this->table_element;
2971 $sql .=
" SET ".$fieldname.
" = ".((
$id > 0 ||
$id ==
'0') ? ((
int)
$id) :
'NULL');
2972 if (in_array($this->table_element, array(
'propal',
'commande',
'societe'))) {
2973 $sql .=
" , deposit_percent = " . (empty($deposit_percent) ?
'NULL' :
"'".$this->db->escape($deposit_percent).
"'");
2975 $sql .=
' WHERE rowid='.((int) $this->
id);
2977 if ($this->db->query($sql)) {
2978 $this->cond_reglement_id =
$id;
2980 if (get_class($this) ==
'Fournisseur') {
2981 $this->cond_reglement_supplier_id =
$id;
2983 $this->cond_reglement =
$id;
2984 $this->deposit_percent = $deposit_percent;
2987 dol_syslog(get_class($this).
'::setPaymentTerms Error '.$sql.
' - '.$this->db->error());
2988 $this->error = $this->db->error();
2992 dol_syslog(get_class($this).
'::setPaymentTerms, status of the object is incompatible');
2993 $this->error =
'Status of the object is incompatible '.$this->status;
3007 if ($this->
status >= 0 || $this->element ==
'societe') {
3008 $fieldname =
'fk_transport_mode';
3009 if ($this->element ==
'societe') {
3010 $fieldname =
'transport_mode';
3012 if (get_class($this) ==
'Fournisseur') {
3013 $fieldname =
'transport_mode_supplier';
3016 $sql =
'UPDATE '.$this->db->prefix().$this->table_element;
3017 $sql .=
" SET ".$fieldname.
" = ".((
$id > 0 ||
$id ==
'0') ? ((
int)
$id) :
'NULL');
3018 $sql .=
' WHERE rowid='.((int) $this->
id);
3020 if ($this->db->query($sql)) {
3021 $this->transport_mode_id =
$id;
3023 if (get_class($this) ==
'Fournisseur') {
3024 $this->transport_mode_supplier_id =
$id;
3028 dol_syslog(get_class($this).
'::setTransportMode Error '.$sql.
' - '.$this->db->error());
3029 $this->error = $this->db->error();
3033 dol_syslog(get_class($this).
'::setTransportMode, status of the object is incompatible');
3034 $this->error =
'Status of the object is incompatible '.$this->status;
3047 dol_syslog(get_class($this).
'::setRetainedWarrantyPaymentTerms('.
$id.
')');
3048 if ($this->
status >= 0 || $this->element ==
'societe') {
3049 $fieldname =
'retained_warranty_fk_cond_reglement';
3051 $sql =
'UPDATE '.$this->db->prefix().$this->table_element;
3052 $sql .=
" SET ".$fieldname.
" = ".((int)
$id);
3053 $sql .=
' WHERE rowid='.((int) $this->
id);
3055 if ($this->db->query($sql)) {
3056 $this->retained_warranty_fk_cond_reglement =
$id;
3059 dol_syslog(get_class($this).
'::setRetainedWarrantyPaymentTerms Error '.$sql.
' - '.$this->db->error());
3060 $this->error = $this->db->error();
3064 dol_syslog(get_class($this).
'::setRetainedWarrantyPaymentTerms, status of the object is incompatible');
3065 $this->error =
'Status of the object is incompatible '.$this->status;
3079 $fieldname =
'fk_delivery_address';
3080 if ($this->element ==
'delivery' || $this->element ==
'shipping') {
3081 $fieldname =
'fk_address';
3084 $sql =
"UPDATE ".$this->db->prefix().$this->table_element.
" SET ".$fieldname.
" = ".((int)
$id);
3085 $sql .=
" WHERE rowid = ".((int) $this->
id).
" AND fk_statut = 0";
3087 if ($this->db->query($sql)) {
3088 $this->fk_delivery_address =
$id;
3091 $this->error = $this->db->error();
3092 dol_syslog(get_class($this).
'::setDeliveryAddress Error '.$this->error);
3110 if (empty($userused)) {
3116 if (!$this->table_element) {
3117 dol_syslog(get_class($this).
"::setShippingMethod was called on object with property table_element not defined", LOG_ERR);
3123 if ($shipping_method_id < 0) {
3124 $shipping_method_id =
'NULL';
3126 dol_syslog(get_class($this).
'::setShippingMethod('.$shipping_method_id.
')');
3128 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
3129 $sql .=
" SET fk_shipping_method = ".((int) $shipping_method_id);
3130 $sql .=
" WHERE rowid=".((int) $this->
id);
3131 $resql = $this->db->query($sql);
3133 dol_syslog(get_class($this).
'::setShippingMethod Error ', LOG_DEBUG);
3134 $this->error = $this->db->lasterror();
3139 $this->context = array(
'shippingmethodupdate' => 1);
3140 $result = $this->call_trigger(strtoupper(get_class($this)).
'_MODIFY', $userused);
3148 $this->db->rollback();
3151 $this->shipping_method_id = ($shipping_method_id ==
'NULL') ?
null : $shipping_method_id;
3152 $this->db->commit();
3166 if (!$this->table_element) {
3167 dol_syslog(get_class($this).
"::setWarehouse was called on object with property table_element not defined", LOG_ERR);
3170 if ($warehouse_id < 0) {
3171 $warehouse_id =
'NULL';
3173 dol_syslog(get_class($this).
'::setWarehouse('.$warehouse_id.
')');
3175 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
3176 $sql .=
" SET fk_warehouse = ".((int) $warehouse_id);
3177 $sql .=
" WHERE rowid=".((int) $this->
id);
3179 if ($this->db->query($sql)) {
3180 $this->warehouse_id = ($warehouse_id ==
'NULL') ?
null : $warehouse_id;
3183 dol_syslog(get_class($this).
'::setWarehouse Error ', LOG_DEBUG);
3184 $this->error = $this->db->error();
3199 if (!$this->table_element) {
3200 dol_syslog(get_class($this).
"::setDocModel was called on object with property table_element not defined", LOG_ERR);
3204 $newmodelpdf =
dol_trunc($modelpdf, 255);
3206 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
3207 $sql .=
" SET model_pdf = '".$this->db->escape($newmodelpdf).
"'";
3208 $sql .=
" WHERE rowid = ".((int) $this->
id);
3210 dol_syslog(get_class($this).
"::setDocModel", LOG_DEBUG);
3211 $resql = $this->db->query($sql);
3213 $this->model_pdf = $modelpdf;
3234 if (empty($userused)) {
3240 if (!$this->table_element) {
3241 dol_syslog(get_class($this).
"::setBankAccount was called on object with property table_element not defined", LOG_ERR);
3246 if ($fk_account < 0) {
3247 $fk_account =
'NULL';
3249 dol_syslog(get_class($this).
'::setBankAccount('.$fk_account.
')');
3251 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
3252 $sql .=
" SET fk_account = ".((int) $fk_account);
3253 $sql .=
" WHERE rowid=".((int) $this->
id);
3255 $resql = $this->db->query($sql);
3257 dol_syslog(get_class($this).
'::setBankAccount Error '.$sql.
' - '.$this->db->error());
3258 $this->error = $this->db->lasterror();
3263 $this->context[
'bankaccountupdate'] = 1;
3264 $triggerName = strtoupper(get_class($this)).
'_MODIFY';
3266 if ($triggerName ==
'FACTUREREC_MODIFY') {
3267 $triggerName =
'BILLREC_MODIFY';
3269 $result = $this->call_trigger($triggerName, $userused);
3277 $this->db->rollback();
3280 $this->fk_account = ($fk_account ==
'NULL') ?
null : $fk_account;
3281 $this->db->commit();
3299 public function line_order($renum =
false, $rowidorder =
'ASC', $fk_parent_line =
true)
3302 if (!$this->table_element_line) {
3303 dol_syslog(get_class($this).
"::line_order was called on object with property table_element_line not defined", LOG_ERR);
3306 if (!$this->fk_element) {
3307 dol_syslog(get_class($this).
"::line_order was called on object with property fk_element not defined", LOG_ERR);
3311 $fieldposition =
'rang';
3312 if (in_array($this->table_element_line, array(
'bom_bomline',
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3313 $fieldposition =
'position';
3318 $sql =
"SELECT count(rowid) FROM ".$this->db->prefix().$this->table_element_line;
3319 $sql .=
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
3321 $sql .=
" AND " . $fieldposition .
" = 0";
3324 $sql .=
" AND " . $fieldposition .
" <> 0";
3327 dol_syslog(get_class($this).
"::line_order", LOG_DEBUG);
3328 $resql = $this->db->query($sql);
3330 $row = $this->db->fetch_row($resql);
3340 $sql =
"SELECT rowid FROM ".$this->db->prefix().$this->table_element_line;
3341 $sql .=
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
3342 if ($fk_parent_line) {
3343 $sql .=
' AND fk_parent_line IS NULL';
3345 $sql .=
" ORDER BY " . $fieldposition .
" ASC, rowid " . $rowidorder;
3347 dol_syslog(get_class($this).
"::line_order search all parent lines", LOG_DEBUG);
3348 $resql = $this->db->query($sql);
3351 $num = $this->db->num_rows($resql);
3353 $row = $this->db->fetch_row($resql);
3355 $children = $this->getChildrenOfLine($row[0]);
3356 if (!empty($children)) {
3357 foreach ($children as $child) {
3358 array_push($rows, $child);
3365 if (!empty($rows)) {
3366 foreach ($rows as $key => $row) {
3367 $this->updateRangOfLine($row, ($key + 1));
3386 $fieldposition =
'rang';
3387 if (in_array($this->table_element_line, array(
'bom_bomline',
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3388 $fieldposition =
'position';
3393 $sql =
"SELECT rowid FROM ".$this->db->prefix().$this->table_element_line;
3394 $sql .=
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
3395 $sql .=
' AND fk_parent_line = '.((int)
$id);
3396 $sql .=
" ORDER BY " . $fieldposition .
" ASC";
3398 dol_syslog(get_class($this).
"::getChildrenOfLine search children lines for line ".
$id, LOG_DEBUG);
3400 $resql = $this->db->query($sql);
3402 if ($this->db->num_rows($resql) > 0) {
3403 while ($row = $this->db->fetch_row($resql)) {
3405 if (!empty($includealltree) && $includealltree <= 1000) {
3406 $rows = array_merge($rows, $this->getChildrenOfLine($row[0], $includealltree + 1));
3422 public function line_up($rowid, $fk_parent_line =
true)
3425 $this->line_order(
false,
'ASC', $fk_parent_line);
3428 $rang = $this->getRangOfLine($rowid);
3431 $this->updateLineUp($rowid, $rang);
3445 $this->line_order(
false,
'ASC', $fk_parent_line);
3448 $rang = $this->getRangOfLine($rowid);
3451 $max = $this->line_max();
3454 $this->updateLineDown($rowid, $rang, $max);
3466 global $hookmanager;
3467 $fieldposition =
'rang';
3468 if (in_array($this->table_element_line, array(
'bom_bomline',
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3469 $fieldposition =
'position';
3472 $sql =
"UPDATE ".$this->db->prefix().$this->table_element_line.
" SET ".$fieldposition.
" = ".((int) $rang);
3473 $sql .=
' WHERE rowid = '.((int) $rowid);
3475 dol_syslog(get_class($this).
"::updateRangOfLine", LOG_DEBUG);
3476 if (!$this->db->query($sql)) {
3480 $parameters = array(
'rowid' => $rowid,
'rang' => $rang,
'fieldposition' => $fieldposition);
3482 $reshook = $hookmanager->executeHooks(
'afterRankOfLineUpdate', $parameters, $this, $action);
3497 $num = count($rows);
3498 for ($i = 0; $i < $num; $i++) {
3499 $this->updateRangOfLine($rows[$i], ($i + 1));
3513 $fieldposition =
'rang';
3514 if (in_array($this->table_element_line, array(
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3515 $fieldposition =
'position';
3518 $sql =
"UPDATE ".$this->db->prefix().$this->table_element_line.
" SET ".$fieldposition.
" = ".((int) $rang);
3519 $sql .=
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
3520 $sql .=
" AND " . $fieldposition .
" = " . ((int) ($rang - 1));
3521 if ($this->db->query($sql)) {
3522 $sql =
"UPDATE ".$this->db->prefix().$this->table_element_line.
" SET ".$fieldposition.
" = ".((int) ($rang - 1));
3523 $sql .=
' WHERE rowid = '.((int) $rowid);
3524 if (!$this->db->query($sql)) {
3544 $fieldposition =
'rang';
3545 if (in_array($this->table_element_line, array(
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3546 $fieldposition =
'position';
3549 $sql =
"UPDATE ".$this->db->prefix().$this->table_element_line.
" SET ".$fieldposition.
" = ".((int) $rang);
3550 $sql .=
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
3551 $sql .=
" AND " . $fieldposition .
" = " . ((int) ($rang + 1));
3552 if ($this->db->query($sql)) {
3553 $sql =
"UPDATE ".$this->db->prefix().$this->table_element_line.
" SET ".$fieldposition.
" = ".((int) ($rang + 1));
3554 $sql .=
' WHERE rowid = '.((int) $rowid);
3555 if (!$this->db->query($sql)) {
3572 $fieldposition =
'rang';
3573 if (in_array($this->table_element_line, array(
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3574 $fieldposition =
'position';
3577 $sql =
"SELECT " . $fieldposition .
" FROM ".$this->db->prefix().$this->table_element_line;
3578 $sql .=
" WHERE rowid = ".((int) $rowid);
3580 dol_syslog(get_class($this).
"::getRangOfLine", LOG_DEBUG);
3581 $resql = $this->db->query($sql);
3583 $row = $this->db->fetch_row($resql);
3598 $fieldposition =
'rang';
3599 if (in_array($this->table_element_line, array(
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3600 $fieldposition =
'position';
3603 $sql =
"SELECT rowid FROM ".$this->db->prefix().$this->table_element_line;
3604 $sql .=
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
3605 $sql .=
" AND " . $fieldposition .
" = ".((int) $rang);
3606 $resql = $this->db->query($sql);
3608 $row = $this->db->fetch_row($resql);
3625 $positionfield =
'rang';
3626 if (in_array($this->table_element, array(
'bom_bom',
'product_attribute'))) {
3627 $positionfield =
'position';
3631 if ($fk_parent_line) {
3632 $sql =
"SELECT max(".$positionfield.
") FROM ".$this->db->prefix().$this->table_element_line;
3633 $sql .=
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
3634 $sql .=
" AND fk_parent_line = ".((int) $fk_parent_line);
3636 dol_syslog(get_class($this).
"::line_max", LOG_DEBUG);
3637 $resql = $this->db->query($sql);
3639 $row = $this->db->fetch_row($resql);
3640 if (!empty($row[0])) {
3643 return $this->getRangOfLine($fk_parent_line);
3648 $sql =
"SELECT max(".$positionfield.
") FROM ".$this->db->prefix().$this->table_element_line;
3649 $sql .=
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
3651 dol_syslog(get_class($this).
"::line_max", LOG_DEBUG);
3652 $resql = $this->db->query($sql);
3654 $row = $this->db->fetch_row($resql);
3672 if (!$this->table_element) {
3673 dol_syslog(get_class($this).
"::update_ref_ext was called on object with property table_element not defined", LOG_ERR);
3677 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
3678 $sql .=
" SET ref_ext = '".$this->db->escape($ref_ext).
"'";
3680 $sql .=
" WHERE ".(isset($this->table_rowid) ? $this->table_rowid :
'rowid').
" = ".((
int)
$this->id);
3682 dol_syslog(get_class($this).
"::update_ref_ext", LOG_DEBUG);
3683 if ($this->db->query($sql)) {
3684 $this->ref_ext = $ref_ext;
3687 $this->error = $this->db->error();
3706 if (!$this->table_element) {
3707 $this->error =
'update_note was called on object with property table_element not defined';
3708 dol_syslog(get_class($this).
"::update_note was called on object with property table_element not defined", LOG_ERR);
3711 if (!in_array($suffix, array(
'',
'_public',
'_private'))) {
3712 $this->error =
'update_note Parameter suffix must be empty, \'_private\' or \'_public\'';
3713 dol_syslog(get_class($this).
"::update_note Parameter suffix must be empty, '_private' or '_public'", LOG_ERR);
3717 $newsuffix = $suffix;
3720 if ($this->table_element ==
'product' && $newsuffix ==
'_private') {
3723 if (in_array($this->table_element, array(
'actioncomm',
'adherent',
'advtargetemailing',
'cronjob',
'establishment'))) {
3724 $fieldusermod =
"fk_user_mod";
3725 } elseif ($this->table_element ==
'ecm_files') {
3726 $fieldusermod =
"fk_user_m";
3728 $fieldusermod =
"fk_user_modif";
3730 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
3731 $sql .=
" SET note".$newsuffix.
" = ".(!empty($note) ? (
"'".$this->db->escape($note).
"'") :
"NULL");
3732 $sql .=
", ".$fieldusermod.
" = ".((int) $user->id);
3733 $sql .=
" WHERE rowid = ".((int) $this->
id);
3735 dol_syslog(get_class($this).
"::update_note", LOG_DEBUG);
3736 if ($this->db->query($sql)) {
3737 if ($suffix ==
'_public') {
3738 $this->note_public = $note;
3739 } elseif ($suffix ==
'_private') {
3740 $this->note_private = $note;
3742 $this->note = $note;
3743 $this->note_private = $note;
3745 if (empty($notrigger)) {
3746 switch ($this->element) {
3748 $trigger_name =
'COMPANY_MODIFY';
3751 $trigger_name =
'ORDER_MODIFY';
3754 $trigger_name =
'BILL_MODIFY';
3756 case 'invoice_supplier':
3757 $trigger_name =
'BILL_SUPPLIER_MODIFY';
3760 $trigger_name =
'BILLREC_MODIFIY';
3762 case 'expensereport':
3763 $trigger_name =
'EXPENSE_REPORT_MODIFY';
3766 $trigger_name = strtoupper($this->element) .
'_MODIFY';
3768 $ret = $this->call_trigger($trigger_name, $user);
3775 $this->error = $this->db->lasterror();
3792 return $this->update_note($note,
'_public');
3806 public function update_price($exclspec = 0, $roundingadjust =
'auto', $nodatabaseupdate = 0, $seller =
null)
3809 global $conf, $hookmanager, $action;
3811 $parameters = array(
'exclspec' => $exclspec,
'roundingadjust' => $roundingadjust,
'nodatabaseupdate' => $nodatabaseupdate,
'seller' => $seller);
3812 $reshook = $hookmanager->executeHooks(
'updateTotalPrice', $parameters, $this, $action);
3815 } elseif ($reshook < 0) {
3820 $isElementForSupplier =
false;
3821 $roundTotalConstName =
'MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND';
3823 if ($this->element ==
'propal') {
3824 $MODULE =
"MODULE_DISALLOW_UPDATE_PRICE_PROPOSAL";
3825 } elseif ($this->element ==
'commande' || $this->element ==
'order') {
3826 $MODULE =
"MODULE_DISALLOW_UPDATE_PRICE_ORDER";
3827 } elseif ($this->element ==
'facture' || $this->element ==
'invoice') {
3828 $MODULE =
"MODULE_DISALLOW_UPDATE_PRICE_INVOICE";
3829 } elseif ($this->element ==
'facture_fourn' || $this->element ==
'supplier_invoice' || $this->element ==
'invoice_supplier' || $this->element ==
'invoice_supplier_rec') {
3830 $isElementForSupplier =
true;
3831 $MODULE =
"MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_INVOICE";
3832 } elseif ($this->element ==
'order_supplier' || $this->element ==
'supplier_order') {
3833 $isElementForSupplier =
true;
3834 $MODULE =
"MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_ORDER";
3835 } elseif ($this->element ==
'supplier_proposal') {
3836 $isElementForSupplier =
true;
3837 $MODULE =
"MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_PROPOSAL";
3839 if ($isElementForSupplier) {
3840 $roundTotalConstName =
'MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND_SUPPLIER';
3843 if (!empty($MODULE)) {
3846 foreach ($modsactivated as $mod) {
3847 if (isModEnabled($mod)) {
3854 include_once DOL_DOCUMENT_ROOT.
'/core/lib/price.lib.php';
3856 $forcedroundingmode = $roundingadjust;
3857 if ($forcedroundingmode ==
'auto' && isset($conf->global->{$roundTotalConstName})) {
3859 } elseif ($forcedroundingmode ==
'auto') {
3860 $forcedroundingmode =
'0';
3865 $multicurrency_tx = !empty($this->multicurrency_tx) ? $this->multicurrency_tx : 1;
3868 $fieldtva =
'total_tva';
3869 $fieldlocaltax1 =
'total_localtax1';
3870 $fieldlocaltax2 =
'total_localtax2';
3871 $fieldup =
'subprice';
3872 $base_price_type =
'HT';
3873 if ($this->element ==
'facture_fourn' || $this->element ==
'invoice_supplier') {
3877 if ($this->element ==
'invoice_supplier_rec') {
3880 if ($this->element ==
'expensereport') {
3884 $forcedroundingmode =
'0';
3885 $fieldup =
'value_unit';
3886 $base_price_type =
'TTC';
3889 $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,";
3890 $sql .=
' tva_tx as vatrate, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type, info_bits, product_type';
3891 if ($this->table_element_line ==
'facturedet') {
3892 $sql .=
', situation_percent';
3894 $sql .=
', multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc';
3895 $sql .=
" FROM ".$this->db->prefix().$this->table_element_line;
3896 $sql .=
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
3898 $product_field =
'product_type';
3899 if ($this->table_element_line ==
'contratdet') {
3900 $product_field =
'';
3902 if ($product_field) {
3903 $sql .=
" AND ".$product_field.
" <> 9";
3906 $sql .=
' ORDER by rowid';
3908 dol_syslog(get_class($this).
"::update_price", LOG_DEBUG);
3910 $resql = $this->db->query($sql);
3912 $this->total_ht = 0;
3913 $this->total_tva = 0;
3914 $this->total_localtax1 = 0;
3915 $this->total_localtax2 = 0;
3916 $this->total_ttc = 0;
3917 $total_ht_by_vats = array();
3918 $total_tva_by_vats = array();
3919 $total_ttc_by_vats = array();
3920 $this->multicurrency_total_ht = 0;
3921 $this->multicurrency_total_tva = 0;
3922 $this->multicurrency_total_ttc = 0;
3926 $num = $this->db->num_rows($resql);
3929 $obj = $this->db->fetch_object($resql);
3932 $parameters = array(
'fk_element' => $obj->rowid);
3933 $reshook = $hookmanager->executeHooks(
'changeRoundingMode', $parameters, $this, $action);
3935 if (empty($reshook) && $forcedroundingmode ==
'0') {
3937 $localtax_array = array($obj->localtax1_type, $obj->localtax1_tx, $obj->localtax2_type, $obj->localtax2_tx);
3938 $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);
3940 $diff_when_using_price_ht =
price2num($tmpcal[1] - $obj->total_tva,
'MT', 1);
3941 $diff_on_current_total =
price2num($obj->total_ttc - $obj->total_ht - $obj->total_tva - $obj->total_localtax1 - $obj->total_localtax2,
'MT', 1);
3945 if ($diff_on_current_total) {
3947 $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);
3948 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);
3949 $resqlfix = $this->db->query($sqlfix);
3953 $obj->total_tva = $tmpcal[1];
3954 $obj->total_ttc = $tmpcal[2];
3955 } elseif ($diff_when_using_price_ht) {
3958 $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);
3959 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);
3960 $resqlfix = $this->db->query($sqlfix);
3964 $obj->total_tva = $tmpcal[1];
3965 $obj->total_ttc = $tmpcal[2];
3969 $this->total_ht += $obj->total_ht;
3970 $this->total_tva += $obj->total_tva;
3971 $this->total_localtax1 += $obj->total_localtax1;
3972 $this->total_localtax2 += $obj->total_localtax2;
3973 $this->total_ttc += $obj->total_ttc;
3974 $this->multicurrency_total_ht += $obj->multicurrency_total_ht;
3975 $this->multicurrency_total_tva += $obj->multicurrency_total_tva;
3976 $this->multicurrency_total_ttc += $obj->multicurrency_total_ttc;
3978 if (!isset($total_ht_by_vats[$obj->vatrate])) {
3979 $total_ht_by_vats[$obj->vatrate] = 0;
3981 if (!isset($total_tva_by_vats[$obj->vatrate])) {
3982 $total_tva_by_vats[$obj->vatrate] = 0;
3984 if (!isset($total_ttc_by_vats[$obj->vatrate])) {
3985 $total_ttc_by_vats[$obj->vatrate] = 0;
3987 $total_ht_by_vats[$obj->vatrate] += $obj->total_ht;
3988 $total_tva_by_vats[$obj->vatrate] += $obj->total_tva;
3989 $total_ttc_by_vats[$obj->vatrate] += $obj->total_ttc;
3991 if ($forcedroundingmode ==
'1') {
3992 if ($base_price_type ==
'TTC') {
3993 $tmpvat =
price2num($total_ttc_by_vats[$obj->vatrate] * $obj->vatrate / (100 + $obj->vatrate),
'MT', 1);
3995 $tmpvat =
price2num($total_ht_by_vats[$obj->vatrate] * $obj->vatrate / 100,
'MT', 1);
3997 $diff =
price2num($total_tva_by_vats[$obj->vatrate] - (
float) $tmpvat,
'MT', 1);
4000 $maxdiff = (10 * pow(10, -1 *
getDolGlobalInt(
'MAIN_MAX_DECIMALS_TOT', 0)));
4001 if (abs((
float) $diff) > $maxdiff) {
4003 $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.';
4005 $this->error = $errmsg;
4010 if ($base_price_type ==
'TTC') {
4011 $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);
4012 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);
4014 $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);
4015 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);
4018 $resqlfix = $this->db->query($sqlfix);
4024 $this->total_tva = (float)
price2num($this->total_tva - (
float) $diff,
'', 1);
4025 $total_tva_by_vats[$obj->vatrate] = (float)
price2num($total_tva_by_vats[$obj->vatrate] - (
float) $diff,
'', 1);
4026 if ($base_price_type ==
'TTC') {
4027 $this->total_ht = (float)
price2num($this->total_ht + (
float) $diff,
'', 1);
4028 $total_ht_by_vats[$obj->vatrate] = (float)
price2num($total_ht_by_vats[$obj->vatrate] + (
float) $diff,
'', 1);
4030 $this->total_ttc = (float)
price2num($this->total_ttc - (
float) $diff,
'', 1);
4031 $total_ttc_by_vats[$obj->vatrate] = (float)
price2num($total_ttc_by_vats[$obj->vatrate] - (
float) $diff,
'', 1);
4041 $this->total_ttc += isset($this->revenuestamp) ? $this->revenuestamp : 0;
4043 $this->multicurrency_total_ttc += isset($this->revenuestamp) ? ($this->revenuestamp * $multicurrency_tx) : 0;
4046 if (!empty($this->situation_cycle_ref) && !empty($this->situation_counter) && $this->situation_counter > 1 && method_exists($this,
'get_prev_sits')) {
4047 '@phan-var-force Facture $this';
4048 include_once DOL_DOCUMENT_ROOT.
'/compta/facture/class/facture.class.php';
4051 $prev_sits = $this->get_prev_sits();
4053 foreach ($prev_sits as $sit) {
4054 $this->total_ht -= $sit->total_ht;
4055 $this->total_tva -= $sit->total_tva;
4056 $this->total_localtax1 -= $sit->total_localtax1;
4057 $this->total_localtax2 -= $sit->total_localtax2;
4058 $this->total_ttc -= $sit->total_ttc;
4059 $this->multicurrency_total_ht -= $sit->multicurrency_total_ht;
4060 $this->multicurrency_total_tva -= $sit->multicurrency_total_tva;
4061 $this->multicurrency_total_ttc -= $sit->multicurrency_total_ttc;
4068 $this->total_ht = (float)
price2num($this->total_ht);
4069 $this->total_tva = (float)
price2num($this->total_tva);
4070 $this->total_localtax1 = (float)
price2num($this->total_localtax1);
4071 $this->total_localtax2 = (float)
price2num($this->total_localtax2);
4072 $this->total_ttc = (float)
price2num($this->total_ttc);
4074 $this->db->free($resql);
4077 $fieldht =
'total_ht';
4079 $fieldlocaltax1 =
'localtax1';
4080 $fieldlocaltax2 =
'localtax2';
4081 $fieldttc =
'total_ttc';
4083 if (in_array($this->element, array(
'propal',
'commande',
'facture',
'facturerec',
'supplier_proposal',
'order_supplier',
'facture_fourn',
'invoice_supplier',
'invoice_supplier_rec',
'expensereport'))) {
4084 $fieldtva =
'total_tva';
4087 if (!$error && empty($nodatabaseupdate)) {
4088 $sql =
"UPDATE ".$this->db->prefix().$this->table_element.
' SET';
4089 $sql .=
" ".$fieldht.
" = ".((float)
price2num($this->total_ht,
'MT', 1)).
",";
4090 $sql .=
" ".$fieldtva.
" = ".((float)
price2num($this->total_tva,
'MT', 1)).
",";
4091 $sql .=
" ".$fieldlocaltax1.
" = ".((float)
price2num($this->total_localtax1,
'MT', 1)).
",";
4092 $sql .=
" ".$fieldlocaltax2.
" = ".((float)
price2num($this->total_localtax2,
'MT', 1)).
",";
4093 $sql .=
" ".$fieldttc.
" = ".((float)
price2num($this->total_ttc,
'MT', 1));
4094 $sql .=
", multicurrency_total_ht = ".((float)
price2num($this->multicurrency_total_ht,
'MT', 1));
4095 $sql .=
", multicurrency_total_tva = ".((float)
price2num($this->multicurrency_total_tva,
'MT', 1));
4096 $sql .=
", multicurrency_total_ttc = ".((float)
price2num($this->multicurrency_total_ttc,
'MT', 1));
4097 $sql .=
" WHERE rowid = ".((int) $this->
id);
4099 dol_syslog(get_class($this).
"::update_price", LOG_DEBUG);
4100 $resql = $this->db->query($sql);
4104 $this->error = $this->db->lasterror();
4105 $this->errors[] = $this->db->lasterror();
4110 $this->db->commit();
4113 $this->db->rollback();
4133 public function add_object_linked($origin =
null, $origin_id =
null, $f_user =
null, $notrigger = 0)
4136 global $user, $hookmanager, $action;
4137 $origin = (!empty($origin) ? $origin : $this->origin);
4138 $origin_id = (!empty($origin_id) ? $origin_id : $this->origin_id);
4139 $f_user = isset($f_user) ? $f_user : $user;
4142 if ($origin ==
'order') {
4143 $origin =
'commande';
4145 if ($origin ==
'invoice') {
4146 $origin =
'facture';
4148 if ($origin ==
'invoice_template') {
4149 $origin =
'facturerec';
4151 if ($origin ==
'supplierorder') {
4152 $origin =
'order_supplier';
4156 $targettype = $this->getElementType();
4158 $parameters = array(
'targettype' => $targettype);
4160 $reshook = $hookmanager->executeHooks(
'setLinkedObjectSourceTargetType', $parameters, $this, $action);
4162 if (!empty($hookmanager->resArray[
'targettype'])) {
4163 $targettype = $hookmanager->resArray[
'targettype'];
4170 $sql =
"INSERT INTO " . $this->db->prefix() .
"element_element (";
4171 $sql .=
"fk_source";
4172 $sql .=
", sourcetype";
4173 $sql .=
", fk_target";
4174 $sql .=
", targettype";
4175 $sql .=
") VALUES (";
4176 $sql .= ((int) $origin_id);
4177 $sql .=
", '" . $this->db->escape($origin) .
"'";
4178 $sql .=
", " . ((int) $this->
id);
4179 $sql .=
", '" . $this->db->escape($targettype) .
"'";
4182 dol_syslog(get_class($this) .
"::add_object_linked", LOG_DEBUG);
4183 if ($this->db->query($sql)) {
4186 $this->context[
'link_origin'] = $origin;
4187 $this->context[
'link_origin_id'] = $origin_id;
4188 $result = $this->call_trigger(
'OBJECT_LINK_INSERT', $f_user);
4195 $this->error = $this->db->lasterror();
4200 $this->db->commit();
4203 $this->db->rollback();
4217 $coreModule = array(
'knowledgemanagement',
'partnership',
'workstation',
'ticket',
'recruitment',
'eventorganization',
'asset');
4219 return ((!empty($this->module) && !in_array($this->module, $coreModule)) ? $this->module.
'_' :
'').$this->element;
4245 public function fetchObjectLinked($sourceid =
null, $sourcetype =
'', $targetid =
null, $targettype =
'', $clause =
'OR', $alsosametype = 1, $orderby =
'sourcetype', $loadalsoobjects = 1)
4247 global $conf, $hookmanager, $action;
4252 if ($this->
id > 0 && !empty($this->linkedObjectsFullLoaded[$this->
id])) {
4256 $this->linkedObjectsIds = array();
4257 $this->linkedObjects = array();
4259 $justsource =
false;
4260 $justtarget =
false;
4261 $withtargettype =
false;
4262 $withsourcetype =
false;
4264 $parameters = array(
'sourcetype' => $sourcetype,
'sourceid' => $sourceid,
'targettype' => $targettype,
'targetid' => $targetid);
4266 $reshook = $hookmanager->executeHooks(
'setLinkedObjectSourceTargetType', $parameters, $this, $action);
4268 if (!empty($hookmanager->resArray[
'sourcetype'])) {
4269 $sourcetype = $hookmanager->resArray[
'sourcetype'];
4271 if (!empty($hookmanager->resArray[
'sourceid'])) {
4272 $sourceid = $hookmanager->resArray[
'sourceid'];
4274 if (!empty($hookmanager->resArray[
'targettype'])) {
4275 $targettype = $hookmanager->resArray[
'targettype'];
4277 if (!empty($hookmanager->resArray[
'targetid'])) {
4278 $targetid = $hookmanager->resArray[
'targetid'];
4282 if (!empty($sourceid) && !empty($sourcetype) && empty($targetid)) {
4284 if (!empty($targettype)) {
4285 $withtargettype =
true;
4288 if (!empty($targetid) && !empty($targettype) && empty($sourceid)) {
4290 if (!empty($sourcetype)) {
4291 $withsourcetype =
true;
4295 $sourceid = (!empty($sourceid) ? $sourceid :
$this->id);
4296 $targetid = (!empty($targetid) ? $targetid :
$this->id);
4297 $sourcetype = (!empty($sourcetype) ? $sourcetype : $this->element);
4298 $targettype = (!empty($targettype) ? $targettype : $this->element);
4307 $sql =
"SELECT rowid, fk_source, sourcetype, fk_target, targettype";
4308 $sql .=
" FROM ".$this->db->prefix().
"element_element";
4310 if ($justsource || $justtarget) {
4312 $sql .=
"fk_source = ".((int) $sourceid).
" AND sourcetype = '".$this->db->escape($sourcetype).
"'";
4313 if ($withtargettype) {
4314 $sql .=
" AND targettype = '".$this->db->escape($targettype).
"'";
4316 } elseif ($justtarget) {
4317 $sql .=
"fk_target = ".((int) $targetid).
" AND targettype = '".$this->db->escape($targettype).
"'";
4318 if ($withsourcetype) {
4319 $sql .=
" AND sourcetype = '".$this->db->escape($sourcetype).
"'";
4323 $sql .=
"(fk_source = ".((int) $sourceid).
" AND sourcetype = '".$this->db->escape($sourcetype).
"')";
4324 $sql .=
" ".$clause.
" (fk_target = ".((int) $targetid).
" AND targettype = '".$this->db->escape($targettype).
"')";
4325 if ($loadalsoobjects && $this->
id > 0 && $sourceid == $this->
id && $sourcetype == $this->element && $targetid == $this->
id && $targettype == $this->element && $clause ==
'OR') {
4326 $this->linkedObjectsFullLoaded[
$this->id] =
true;
4329 $sql .=
" ORDER BY ".$orderby;
4331 dol_syslog(get_class($this).
"::fetchObjectLink", LOG_DEBUG);
4332 $resql = $this->db->query($sql);
4334 $num = $this->db->num_rows($resql);
4337 $obj = $this->db->fetch_object($resql);
4338 if ($justsource || $justtarget) {
4340 $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
4341 } elseif ($justtarget) {
4342 $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
4345 if ($obj->fk_source == $sourceid && $obj->sourcetype == $sourcetype) {
4346 $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
4348 if ($obj->fk_target == $targetid && $obj->targettype == $targettype) {
4349 $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
4355 if (!empty($this->linkedObjectsIds)) {
4356 $tmparray = $this->linkedObjectsIds;
4357 foreach ($tmparray as $objecttype => $objectids) {
4359 $element = $element_properties[
'element'];
4360 $classPath = $element_properties[
'classpath'];
4361 $classFile = $element_properties[
'classfile'];
4362 $className = $element_properties[
'classname'];
4363 $module = $element_properties[
'module'];
4366 if (isModEnabled($module) && (($element != $this->element) || $alsosametype)) {
4367 if ($loadalsoobjects && (is_numeric($loadalsoobjects) || ($loadalsoobjects === $objecttype))) {
4369 if (class_exists($className)) {
4370 foreach ($objectids as $i => $objectid) {
4371 $object =
new $className($this->db);
4372 '@phan-var-force CommonObject $object';
4373 $ret =
$object->fetch($objectid);
4375 $this->linkedObjects[$objecttype][$i] =
$object;
4381 unset($this->linkedObjectsIds[$objecttype]);
4400 if ($this->
id > 0 && !empty($this->linkedObjectsFullLoaded[$this->
id])) {
4401 unset($this->linkedObjectsFullLoaded[$this->
id]);
4419 public function updateObjectLinked($sourceid =
null, $sourcetype =
'', $targetid =
null, $targettype =
'', $f_user =
null, $notrigger = 0)
4422 $updatesource =
false;
4423 $updatetarget =
false;
4424 $f_user = isset($f_user) ? $f_user : $user;
4426 if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) {
4427 $updatesource =
true;
4428 } elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) {
4429 $updatetarget =
true;
4435 $sql =
"UPDATE " . $this->db->prefix() .
"element_element SET ";
4436 if ($updatesource) {
4437 $sql .=
"fk_source = " . ((int) $sourceid);
4438 $sql .=
", sourcetype = '" . $this->db->escape($sourcetype) .
"'";
4439 $sql .=
" WHERE fk_target = " . ((int) $this->
id);
4440 $sql .=
" AND targettype = '" . $this->db->escape($this->element) .
"'";
4441 } elseif ($updatetarget) {
4442 $sql .=
"fk_target = " . ((int) $targetid);
4443 $sql .=
", targettype = '" . $this->db->escape($targettype) .
"'";
4444 $sql .=
" WHERE fk_source = " . ((int) $this->
id);
4445 $sql .=
" AND sourcetype = '" . $this->db->escape($this->element) .
"'";
4448 dol_syslog(get_class($this) .
"::updateObjectLinked", LOG_DEBUG);
4449 if ($this->db->query($sql)) {
4452 $this->context[
'link_source_id'] = $sourceid;
4453 $this->context[
'link_source_type'] = $sourcetype;
4454 $this->context[
'link_target_id'] = $targetid;
4455 $this->context[
'link_target_type'] = $targettype;
4456 $result = $this->call_trigger(
'OBJECT_LINK_MODIFY', $f_user);
4463 $this->error = $this->db->lasterror();
4468 $this->db->commit();
4471 $this->db->rollback();
4489 public function deleteObjectLinked($sourceid =
null, $sourcetype =
'', $targetid =
null, $targettype =
'', $rowid = 0, $f_user =
null, $notrigger = 0)
4492 $deletesource =
false;
4493 $deletetarget =
false;
4494 $f_user = isset($f_user) ? $f_user : $user;
4496 if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) {
4497 $deletesource =
true;
4498 } elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) {
4499 $deletetarget =
true;
4502 $sourceid = (!empty($sourceid) ? $sourceid :
$this->id);
4503 $sourcetype = (!empty($sourcetype) ? $sourcetype : $this->element);
4504 $targetid = (!empty($targetid) ? $targetid :
$this->id);
4505 $targettype = (!empty($targettype) ? $targettype : $this->element);
4511 $this->context[
'link_id'] = $rowid;
4512 $this->context[
'link_source_id'] = $sourceid;
4513 $this->context[
'link_source_type'] = $sourcetype;
4514 $this->context[
'link_target_id'] = $targetid;
4515 $this->context[
'link_target_type'] = $targettype;
4516 $result = $this->call_trigger(
'OBJECT_LINK_DELETE', $f_user);
4524 $sql =
"DELETE FROM " . $this->db->prefix() .
"element_element";
4527 $sql .=
" rowid = " . ((int) $rowid);
4529 if ($deletesource) {
4530 $sql .=
" fk_source = " . ((int) $sourceid) .
" AND sourcetype = '" . $this->db->escape($sourcetype) .
"'";
4531 $sql .=
" AND fk_target = " . ((int) $this->
id) .
" AND targettype = '" . $this->db->escape($this->element) .
"'";
4532 } elseif ($deletetarget) {
4533 $sql .=
" fk_target = " . ((int) $targetid) .
" AND targettype = '" . $this->db->escape($targettype) .
"'";
4534 $sql .=
" AND fk_source = " . ((int) $this->
id) .
" AND sourcetype = '" . $this->db->escape($this->element) .
"'";
4536 $sql .=
" (fk_source = " . ((int) $this->
id) .
" AND sourcetype = '" . $this->db->escape($this->element) .
"')";
4538 $sql .=
" (fk_target = " . ((int) $this->
id) .
" AND targettype = '" . $this->db->escape($this->element) .
"')";
4542 dol_syslog(get_class($this) .
"::deleteObjectLinked", LOG_DEBUG);
4543 if (!$this->db->query($sql)) {
4544 $this->error = $this->db->lasterror();
4545 $this->errors[] = $this->error;
4551 $this->db->commit();
4554 $this->db->rollback();
4570 if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
4573 if (!preg_match(
'/^[_a-zA-Z0-9]+$/', $field_select)) {
4574 dol_syslog(
'Invalid value $field_select for parameter '.$field_select.
' in call to getAllItemsLinkedByObjectID(). Must be a single field name.', LOG_ERR);
4579 $sql =
"SELECT ".$field_select.
" FROM ".$db->prefix().$table_element.
" WHERE ".$field_where.
" = ".((int) $fk_object_where);
4580 $resql = $db->query($sql);
4583 if (!empty($resql)) {
4584 while ($res = $db->fetch_object($resql)) {
4585 $TRes[] = $res->{$field_select};
4602 if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
4608 $sql =
"SELECT COUNT(*) as nb FROM ".$db->prefix().$table_element.
" WHERE ".$field_where.
" = ".((int) $fk_object_where);
4609 $resql = $db->query($sql);
4612 $res = $db->fetch_object($resql);
4631 if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
4637 $sql =
"DELETE FROM ".$db->prefix().$table_element.
" WHERE ".$field_where.
" = ".((int) $fk_object_where);
4638 $resql = $db->query($sql);
4640 if (empty($resql)) {
4657 public function setStatut($status, $elementId =
null, $elementType =
'', $trigkey =
'', $fieldstatus =
'fk_statut')
4661 $savElementId = $elementId;
4663 $elementId = (!empty($elementId) ? $elementId :
$this->id);
4664 $elementTable = (!empty($elementType) ? $elementType : $this->table_element);
4668 if ($elementTable ==
'facture_rec') {
4669 $fieldstatus =
"suspended";
4671 if ($elementTable ==
'mailing') {
4672 $fieldstatus =
"statut";
4674 if ($elementTable ==
'cronjob') {
4675 $fieldstatus =
"status";
4677 if ($elementTable ==
'user') {
4678 $fieldstatus =
"statut";
4680 if ($elementTable ==
'expensereport') {
4681 $fieldstatus =
"fk_statut";
4683 if ($elementTable ==
'receptiondet_batch') {
4684 $fieldstatus =
"status";
4686 if ($elementTable ==
'prelevement_bons') {
4687 $fieldstatus =
"statut";
4689 if (isset($this->fields) && is_array($this->fields) && array_key_exists(
'status', $this->fields)) {
4690 $fieldstatus =
'status';
4693 $sql =
"UPDATE ".$this->db->prefix().$this->db->sanitize($elementTable);
4694 $sql .=
" SET ".$this->db->sanitize($fieldstatus).
" = ".((int) $status);
4697 if ($status == 1 && in_array($elementTable, array(
'expensereport',
'inventory'))) {
4698 $sql .=
", fk_user_valid = ".((int) $user->id);
4700 if ($status == 1 && in_array($elementTable, array(
'expensereport'))) {
4701 $sql .=
", date_valid = '".$this->db->idate(
dol_now()).
"'";
4703 if ($status == 1 && in_array($elementTable, array(
'inventory'))) {
4704 $sql .=
", date_validation = '".$this->db->idate(
dol_now()).
"'";
4706 $sql .=
" WHERE rowid = ".((int) $elementId);
4707 $sql .=
" AND ".$fieldstatus.
" <> ".((int) $status);
4709 dol_syslog(get_class($this).
"::setStatut", LOG_DEBUG);
4710 $resql = $this->db->query($sql);
4714 $nb_rows_affected = $this->db->affected_rows($resql);
4716 if ($nb_rows_affected > 0) {
4717 if (empty($trigkey)) {
4719 if ($this->element ==
'supplier_proposal' && $status == 2) {
4720 $trigkey =
'SUPPLIER_PROPOSAL_SIGN';
4722 if ($this->element ==
'supplier_proposal' && $status == 3) {
4723 $trigkey =
'SUPPLIER_PROPOSAL_REFUSE';
4725 if ($this->element ==
'supplier_proposal' && $status == 4) {
4726 $trigkey =
'SUPPLIER_PROPOSAL_CLOSE';
4728 if ($this->element ==
'fichinter' && $status == 3) {
4729 $trigkey =
'FICHINTER_CLASSIFY_DONE';
4731 if ($this->element ==
'fichinter' && $status == 2) {
4732 $trigkey =
'FICHINTER_CLASSIFY_BILLED';
4734 if ($this->element ==
'fichinter' && $status == 1) {
4735 $trigkey =
'FICHINTER_CLASSIFY_UNBILLED';
4739 $this->context = array_merge($this->context, array(
'newstatus' => $status));
4743 $result = $this->call_trigger($trigkey, $user);
4754 $this->db->commit();
4756 if (empty($savElementId)) {
4758 if ($fieldstatus ==
'tosell') {
4760 } elseif ($fieldstatus ==
'tobuy') {
4761 $this->status_buy = $status;
4769 $this->db->rollback();
4770 dol_syslog(get_class($this).
"::setStatut ".$this->error, LOG_ERR);
4774 $this->error = $this->db->lasterror();
4775 $this->db->rollback();
4792 if (empty(
$id) && empty($ref)) {
4802 $sql =
"SELECT rowid, canvas";
4803 $sql .=
" FROM ".$this->db->prefix().$this->table_element;
4804 $sql .=
" WHERE entity IN (".getEntity($this->element).
")";
4806 $sql .=
" AND rowid = ".((int)
$id);
4809 $sql .=
" AND ref = '".$this->db->escape($ref).
"'";
4812 $resql = $this->db->query($sql);
4814 $obj = $this->db->fetch_object($resql);
4816 $this->canvas = $obj->canvas;
4836 $sql =
"SELECT special_code FROM ".$this->db->prefix().$this->table_element_line;
4837 $sql .=
" WHERE rowid = ".((int) $lineid);
4838 $resql = $this->db->query($sql);
4840 $row = $this->db->fetch_row($resql);
4841 return (!empty($row[0]) ? $row[0] : 0);
4864 if (!isset($this->childtables) || !is_array($this->childtables) || count($this->childtables) == 0) {
4865 dol_print_error(
null,
'Called isObjectUsed on a class with property this->childtables not defined');
4869 $arraytoscan = $this->childtables;
4871 $tmparray = array_keys($this->childtables);
4872 if (is_numeric($tmparray[0])) {
4873 $arraytoscan = array_flip($this->childtables);
4878 foreach ($arraytoscan as $table => $element) {
4881 $sql =
"SELECT COUNT(*) as nb";
4882 $sql .=
" FROM ".$this->db->prefix().$table.
" as c";
4883 if (!empty($element[
'parent']) && !empty($element[
'parentkey'])) {
4884 $sql .=
", ".$this->db->prefix().$element[
'parent'].
" as p";
4886 if (!empty($element[
'fk_element'])) {
4887 $sql .=
" WHERE c.".$element[
'fk_element'].
" = ".((int)
$id);
4889 $sql .=
" WHERE c.".$this->fk_element.
" = ".((int)
$id);
4891 if (!empty($element[
'parent']) && !empty($element[
'parentkey'])) {
4892 $sql .=
" AND c.".$element[
'parentkey'].
" = p.rowid";
4894 if (!empty($element[
'parent']) && !empty($element[
'parenttypefield']) && !empty($element[
'parenttypevalue'])) {
4895 $sql .=
" AND c.".$element[
'parenttypefield'].
" = '".$this->db->escape($element[
'parenttypevalue']).
"'";
4897 if (!empty($entity)) {
4898 if (!empty($element[
'parent']) && !empty($element[
'parentkey'])) {
4899 $sql .=
" AND p.entity = ".((int) $entity);
4901 $sql .=
" AND c.entity = ".((int) $entity);
4905 $resql = $this->db->query($sql);
4907 $obj = $this->db->fetch_object($resql);
4909 $langs->load(
"errors");
4911 $haschild += $obj->nb;
4912 if (is_numeric($element)) {
4913 $this->errors[] = $langs->transnoentitiesnoconv(
"ErrorRecordHasAtLeastOneChildOfType", method_exists($this,
'getNomUrl') ? $this->getNomUrl() : $this->ref, $table);
4914 } elseif (is_string($element)) {
4915 $this->errors[] = $langs->transnoentitiesnoconv(
"ErrorRecordHasAtLeastOneChildOfType", method_exists($this,
'getNomUrl') ? $this->getNomUrl() : $this->ref, $langs->transnoentitiesnoconv($element));
4917 $this->errors[] = $langs->transnoentitiesnoconv(
"ErrorRecordHasAtLeastOneChildOfType", method_exists($this,
'getNomUrl') ? $this->getNomUrl() : $this->ref, $langs->transnoentitiesnoconv($element[
'name']));
4922 $this->errors[] = $this->db->lasterror();
4926 if ($haschild > 0) {
4927 $this->errors[] =
"ErrorRecordHasChildren";
4944 foreach ($this->lines as $key => $val) {
4946 if ($predefined == -1) {
4949 if ($predefined == 1 && $val->fk_product > 0) {
4952 if ($predefined == 0 && $val->fk_product <= 0) {
4955 if ($predefined == 2 && $val->fk_product > 0 && $val->product_type == 0) {
4958 if ($predefined == 3 && $val->fk_product > 0 && $val->product_type == 1) {
4965 dol_syslog(get_class($this).
'::hasProductsOrServices we found '.$nb.
' qualified lines of products/servcies');
4976 if (!empty($this->table_element_line)) {
4977 $total_discount = 0.00;
4979 $sql =
"SELECT subprice as pu_ht, qty, remise_percent, total_ht";
4980 $sql .=
" FROM ".$this->db->prefix().$this->table_element_line;
4981 $sql .=
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
4983 dol_syslog(get_class($this).
'::getTotalDiscount', LOG_DEBUG);
4984 $resql = $this->db->query($sql);
4986 $num = $this->db->num_rows($resql);
4989 $obj = $this->db->fetch_object($resql);
4991 $pu_ht = $obj->pu_ht;
4993 $total_ht = $obj->total_ht;
4995 $total_discount_line = (float)
price2num(($pu_ht * $qty) - $total_ht,
'MT');
4996 $total_discount += $total_discount_line;
5003 return (
float)
price2num($total_discount);
5025 if (empty($this->lines)) {
5026 return array(
'weight' => $totalWeight,
'volume' => $totalVolume,
'ordered' => $totalOrdered,
'toship' => $totalToShip);
5029 foreach ($this->lines as $line) {
5030 if (isset($line->qty_asked)) {
5031 $totalOrdered += $line->qty_asked;
5033 if (isset($line->qty_shipped)) {
5034 $totalToShip += $line->qty_shipped;
5035 } elseif ($line->element ==
'commandefournisseurdispatch' && isset($line->qty)) {
5036 if (empty($totalToShip)) {
5039 $totalToShip += $line->qty;
5043 if ($this->element ==
'shipping') {
5045 $qty = $line->qty_shipped ? $line->qty_shipped : 0;
5047 $qty = $line->qty ? $line->qty : 0;
5050 $weight = !empty($line->weight) ? $line->weight : 0;
5051 ($weight == 0 && !empty($line->product->weight)) ? $weight = $line->product->weight : 0;
5052 $volume = !empty($line->volume) ? $line->volume : 0;
5053 ($volume == 0 && !empty($line->product->volume)) ? $volume = $line->product->volume : 0;
5055 $weight_units = !empty($line->weight_units) ? $line->weight_units : 0;
5056 ($weight_units == 0 && !empty($line->product->weight_units)) ? $weight_units = $line->product->weight_units : 0;
5057 $volume_units = !empty($line->volume_units) ? $line->volume_units : 0;
5058 ($volume_units == 0 && !empty($line->product->volume_units)) ? $volume_units = $line->product->volume_units : 0;
5062 if (!empty($weight_units)) {
5063 $weightUnit = $weight_units;
5065 if (!empty($volume_units)) {
5066 $volumeUnit = $volume_units;
5069 if (empty($totalWeight)) {
5072 if (empty($totalVolume)) {
5077 if ($weight_units < 50) {
5078 $trueWeightUnit = pow(10, $weightUnit);
5079 $totalWeight += $weight * $qty * $trueWeightUnit;
5081 if ($weight_units == 99) {
5083 $trueWeightUnit = 0.45359237;
5084 $totalWeight += $weight * $qty * $trueWeightUnit;
5085 } elseif ($weight_units == 98) {
5087 $trueWeightUnit = 0.0283495;
5088 $totalWeight += $weight * $qty * $trueWeightUnit;
5090 $totalWeight += $weight * $qty;
5093 if ($volume_units < 50) {
5095 $trueVolumeUnit = pow(10, $volumeUnit);
5097 $totalVolume += $volume * $qty * $trueVolumeUnit;
5099 $totalVolume += $volume * $qty;
5103 return array(
'weight' => $totalWeight,
'volume' => $totalVolume,
'ordered' => $totalOrdered,
'toship' => $totalToShip);
5116 $extraparams = (!empty($this->extraparams) ? json_encode($this->extraparams) :
null);
5118 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
5119 $sql .=
" SET extraparams = ".(!empty($extraparams) ?
"'".$this->db->escape($extraparams).
"'" :
"null");
5120 $sql .=
" WHERE rowid = ".((int) $this->
id);
5122 dol_syslog(get_class($this).
"::setExtraParameters", LOG_DEBUG);
5123 $resql = $this->db->query($sql);
5125 $this->error = $this->db->lasterror();
5126 $this->db->rollback();
5129 $this->db->commit();
5152 global $conf, $user, $langs,
$object, $hookmanager, $extrafields, $form;
5155 if (!is_object($extrafields)) {
5156 require_once DOL_DOCUMENT_ROOT.
'/core/class/extrafields.class.php';
5159 $extrafields->fetch_name_optionals_label($this->table_element_line);
5164 $dirtpls = array_merge($conf->modules_parts[
'tpl'], array($defaulttpldir));
5165 foreach ($dirtpls as $module => $reldir) {
5166 if (!empty($module)) {
5169 $tpl = DOL_DOCUMENT_ROOT.$reldir.
'/objectline_create.tpl.php';
5172 if (empty($conf->file->strict_mode)) {
5173 $res = @include $tpl;
5175 $res = include $tpl;
5202 public function printObjectLines($action, $seller, $buyer, $selected = 0, $dateSelector = 0, $defaulttpldir =
'/core/tpl')
5204 global $conf, $hookmanager, $langs, $user, $form, $extrafields,
$object;
5206 global $inputalsopricewithtax, $usemargins, $disableedit, $disablemove, $disableremove, $outputalsopricetotalwithtax;
5210 if (isModEnabled(
'margin') && !empty($this->element) && in_array($this->element, array(
'facture',
'facturerec',
'propal',
'commande'))) {
5214 $num = count($this->lines);
5217 if (!is_object($extrafields)) {
5218 require_once DOL_DOCUMENT_ROOT.
'/core/class/extrafields.class.php';
5221 $extrafields->fetch_name_optionals_label($this->table_element_line);
5223 $parameters = array(
'num' => $num,
'dateSelector' => $dateSelector,
'seller' => $seller,
'buyer' => $buyer,
'selected' => $selected,
'table_element_line' => $this->table_element_line);
5224 $reshook = $hookmanager->executeHooks(
'printObjectLineTitle', $parameters, $this, $action);
5225 if (empty($reshook)) {
5229 $dirtpls = array_merge($conf->modules_parts[
'tpl'], array($defaulttpldir));
5230 foreach ($dirtpls as $module => $reldir) {
5232 if (!empty($module)) {
5235 $tpl = DOL_DOCUMENT_ROOT.$reldir.
'/objectline_title.tpl.php';
5237 if (file_exists($tpl)) {
5238 if (empty($conf->file->strict_mode)) {
5239 $res = @include $tpl;
5241 $res = include $tpl;
5252 print
"<!-- begin printObjectLines() --><tbody>\n";
5253 foreach ($this->lines as $line) {
5255 $line->fetch_optionals();
5258 if (is_object($hookmanager)) {
5259 if (empty($line->fk_parent_line)) {
5260 $parameters = array(
'line' => $line,
'num' => $num,
'i' => $i,
'dateSelector' => $dateSelector,
'seller' => $seller,
'buyer' => $buyer,
'selected' => $selected,
'table_element_line' => $line->table_element,
'defaulttpldir' => $defaulttpldir);
5261 $reshook = $hookmanager->executeHooks(
'printObjectLine', $parameters, $this, $action);
5263 $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);
5264 $reshook = $hookmanager->executeHooks(
'printObjectSubLine', $parameters, $this, $action);
5267 if (empty($reshook)) {
5268 $this->printObjectLine($action, $line,
'', $num, $i, $dateSelector, $seller, $buyer, $selected, $extrafields, $defaulttpldir);
5273 print
"</tbody><!-- end printObjectLines() -->\n";
5293 public function printObjectLine($action, $line, $var, $num, $i, $dateSelector, $seller, $buyer, $selected = 0, $extrafields =
null, $defaulttpldir =
'/core/tpl')
5295 global $conf, $langs, $user,
$object, $hookmanager;
5297 global $disableedit, $disablemove, $disableremove;
5304 if ($action !=
'editline' || $selected != $line->id) {
5306 if (!empty($line->fk_product) && $line->fk_product > 0) {
5307 $product_static =
new Product($this->db);
5308 $product_static->fetch($line->fk_product);
5310 $product_static->ref = $line->ref;
5311 $product_static->label = !empty($line->label) ? $line->label :
"";
5313 $text = $product_static->getNomUrl(1);
5317 if (property_exists($this,
'socid') && !is_object($this->thirdparty)) {
5318 dol_print_error(
null,
'Error: Method printObjectLine was called on an object and object->fetch_thirdparty was not done before');
5322 $prod =
new Product($this->db);
5323 $prod->fetch($line->fk_product);
5325 $outputlangs = $langs;
5327 if (empty($newlang) &&
GETPOST(
'lang_id',
'aZ09')) {
5328 $newlang =
GETPOST(
'lang_id',
'aZ09');
5330 if (
getDolGlobalString(
'PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE') && empty($newlang) && is_object($this->thirdparty)) {
5331 $newlang = $this->thirdparty->default_lang;
5333 if (!empty($newlang)) {
5334 $outputlangs =
new Translate(
"", $conf);
5335 $outputlangs->setDefaultLang($newlang);
5338 $label = (!empty($prod->multilangs[$outputlangs->defaultlang][
"label"])) ? $prod->multilangs[$outputlangs->defaultlang][
"label"] : $line->product_label;
5340 $label = $line->product_label;
5343 $text .=
' - '.(!empty($line->label) ? $line->label : $label);
5344 $description .= (
getDolGlobalInt(
'PRODUIT_DESC_IN_FORM_ACCORDING_TO_DEVICE') ?
'' : (!empty($line->description) ?
dol_htmlentitiesbr($line->description) :
''));
5347 $line->pu_ttc =
price2num((!empty($line->subprice) ? $line->subprice : 0) * (1 + ((!empty($line->tva_tx) ? $line->tva_tx : 0) / 100)),
'MU');
5352 $dirtpls = array_merge($conf->modules_parts[
'tpl'], array($defaulttpldir));
5353 foreach ($dirtpls as $module => $reldir) {
5355 if (!empty($module)) {
5358 $tpl = DOL_DOCUMENT_ROOT.$reldir.
'/objectline_view.tpl.php';
5361 if (file_exists($tpl)) {
5362 if (empty($conf->file->strict_mode)) {
5363 $res = @include $tpl;
5365 $res = include $tpl;
5375 if ($this->
status == 0 && $action ==
'editline' && $selected == $line->id) {
5376 $label = (!empty($line->label) ? $line->label : (($line->fk_product > 0) ? $line->product_label :
''));
5378 $line->pu_ttc =
price2num($line->subprice * (1 + ($line->tva_tx / 100)),
'MU');
5383 $dirtpls = array_merge($conf->modules_parts[
'tpl'], array($defaulttpldir));
5384 foreach ($dirtpls as $module => $reldir) {
5385 if (!empty($module)) {
5388 $tpl = DOL_DOCUMENT_ROOT.$reldir.
'/objectline_edit.tpl.php';
5391 if (empty($conf->file->strict_mode)) {
5392 $res = @include $tpl;
5394 $res = include $tpl;
5419 global $langs, $hookmanager, $form, $action;
5421 print
'<tr class="liste_titre">';
5422 print
'<td class="linecolref">'.$langs->trans(
'Ref').
'</td>';
5423 print
'<td class="linecoldescription">'.$langs->trans(
'Description').
'</td>';
5424 print
'<td class="linecolvat right">'.$langs->trans(
'VATRate').
'</td>';
5425 print
'<td class="linecoluht right">'.$langs->trans(
'PriceUHT').
'</td>';
5426 if (isModEnabled(
"multicurrency")) {
5427 print
'<td class="linecoluht_currency right">'.$langs->trans(
'PriceUHTCurrency').
'</td>';
5429 print
'<td class="linecolqty right">'.$langs->trans(
'Qty').
'</td>';
5431 print
'<td class="linecoluseunit left">'.$langs->trans(
'Unit').
'</td>';
5433 print
'<td class="linecoldiscount right">'.$langs->trans(
'ReductionShort').
'</td>';
5434 print
'<td class="linecolht right">'.$langs->trans(
'TotalHT').
'</td>';
5435 print
'<td class="center">'.$form->showCheckAddButtons(
'checkforselect', 1).
'</td>';
5439 if (!empty($this->lines)) {
5440 foreach ($this->lines as $line) {
5443 if (is_object($hookmanager)) {
5444 $parameters = array(
'line' => $line,
'i' => $i,
'restrictlist' => $restrictlist,
'selectedLines' => $selectedLines);
5445 if (!empty($line->fk_parent_line)) {
5446 $parameters[
'fk_parent_line'] = $line->fk_parent_line;
5448 $reshook = $hookmanager->executeHooks(
'printOriginObjectLine', $parameters, $this, $action);
5450 if (empty($reshook)) {
5451 $this->printOriginLine($line,
'', $restrictlist,
'/core/tpl', $selectedLines);
5472 public function printOriginLine($line, $var, $restrictlist =
'', $defaulttpldir =
'/core/tpl', $selectedLines = array())
5474 global $langs, $conf;
5477 if (!empty($line->date_start)) {
5479 $date_start = $line->date_start;
5481 $date_start = $line->date_debut_prevue;
5482 if ($line->date_debut_reel) {
5483 $date_start = $line->date_debut_reel;
5486 if (!empty($line->date_end)) {
5488 $date_end = $line->date_end;
5490 $date_end = $line->date_fin_prevue;
5491 if ($line->date_fin_reel) {
5492 $date_end = $line->date_fin_reel;
5496 $this->tpl[
'id'] = $line->id;
5498 $this->tpl[
'label'] =
'';
5499 if (!empty($line->fk_parent_line)) {
5500 $this->tpl[
'label'] .=
img_picto(
'',
'rightarrow');
5503 if (($line->info_bits & 2) == 2) {
5505 if (property_exists($this,
'socid')) {
5506 $discount->fk_soc = $this->socid;
5507 $discount->socid = $this->socid;
5509 $this->tpl[
'label'] .= $discount->getNomUrl(0,
'discount');
5510 } elseif (!empty($line->fk_product)) {
5511 $productstatic =
new Product($this->db);
5512 $productstatic->id = $line->fk_product;
5513 $productstatic->ref = $line->ref;
5514 $productstatic->type = $line->fk_product_type;
5515 if (empty($productstatic->ref)) {
5516 $line->fetch_product();
5517 $productstatic = $line->product;
5520 $this->tpl[
'label'] .= $productstatic->getNomUrl(1);
5521 $this->tpl[
'label'] .=
' - '.(!empty($line->label) ? $line->label : $line->product_label);
5523 if ($line->product_type == 1 && ($date_start || $date_end)) {
5527 $this->tpl[
'label'] .= ($line->product_type == -1 ?
' ' : ($line->product_type == 1 ?
img_object($langs->trans(
''),
'service') :
img_object($langs->trans(
''),
'product')));
5528 if (!empty($line->desc)) {
5529 $this->tpl[
'label'] .= $line->desc;
5531 $this->tpl[
'label'] .= ($line->label ?
' '.$line->label :
'');
5535 if ($line->product_type == 1 && ($date_start || $date_end)) {
5540 if (!empty($line->desc)) {
5541 '@phan-var-force OrderLine|FactureLigne|ContratLigne|FactureFournisseurLigneRec|SupplierInvoiceLine|SupplierProposalLine $line';
5542 if ($line->desc ==
'(CREDIT_NOTE)') {
5544 $discount->fetch($line->fk_remise_except);
5545 $this->tpl[
'description'] = $langs->transnoentities(
"DiscountFromCreditNote", $discount->getNomUrl(0));
5546 } elseif ($line->desc ==
'(DEPOSIT)') {
5548 $discount->fetch($line->fk_remise_except);
5549 $this->tpl[
'description'] = $langs->transnoentities(
"DiscountFromDeposit", $discount->getNomUrl(0));
5550 } elseif ($line->desc ==
'(EXCESS RECEIVED)') {
5552 $discount->fetch($line->fk_remise_except);
5553 $this->tpl[
'description'] = $langs->transnoentities(
"DiscountFromExcessReceived", $discount->getNomUrl(0));
5554 } elseif ($line->desc ==
'(EXCESS PAID)') {
5556 $discount->fetch($line->fk_remise_except);
5557 $this->tpl[
'description'] = $langs->transnoentities(
"DiscountFromExcessPaid", $discount->getNomUrl(0));
5559 $this->tpl[
'description'] =
dol_trunc($line->desc, 60);
5562 $this->tpl[
'description'] =
' ';
5566 $this->tpl[
'vat_rate'] =
vatrate($line->tva_tx,
true);
5567 $this->tpl[
'vat_rate'] .= (($line->info_bits & 1) == 1) ?
'*' :
'';
5568 if (!empty($line->vat_src_code) && !preg_match(
'/\(/', $this->tpl[
'vat_rate'])) {
5569 $this->tpl[
'vat_rate'] .=
' ('.$line->vat_src_code.
')';
5572 $this->tpl[
'price'] =
price($line->subprice);
5573 $this->tpl[
'total_ht'] =
price($line->total_ht);
5574 $this->tpl[
'multicurrency_price'] =
price($line->multicurrency_subprice);
5575 $this->tpl[
'qty'] = (($line->info_bits & 2) != 2) ? $line->qty :
' ';
5577 $this->tpl[
'unit'] = $langs->transnoentities($line->getLabelOfUnit(
'long'));
5579 $this->tpl[
'remise_percent'] = (($line->info_bits & 2) != 2) ?
vatrate($line->remise_percent,
true) :
' ';
5582 $this->tpl[
'strike'] = 0;
5584 $this->tpl[
'strike'] = 1;
5589 $dirtpls = array_merge($conf->modules_parts[
'tpl'], array($defaulttpldir));
5590 foreach ($dirtpls as $module => $reldir) {
5591 if (!empty($module)) {
5594 $tpl = DOL_DOCUMENT_ROOT.$reldir.
'/originproductline.tpl.php';
5597 if (empty($conf->file->strict_mode)) {
5598 $res = @include $tpl;
5600 $res = include $tpl;
5625 $sql =
"INSERT INTO ".$this->db->prefix().
"element_resources (";
5626 $sql .=
"resource_id";
5627 $sql .=
", resource_type";
5628 $sql .=
", element_id";
5629 $sql .=
", element_type";
5631 $sql .=
", mandatory";
5632 $sql .=
") VALUES (";
5633 $sql .= ((int) $resource_id);
5634 $sql .=
", '".$this->db->escape($resource_type).
"'";
5635 $sql .=
", '".$this->db->escape($this->
id).
"'";
5636 $sql .=
", '".$this->db->escape($this->element).
"'";
5637 $sql .=
", '".$this->db->escape($busy).
"'";
5638 $sql .=
", '".$this->db->escape($mandatory).
"'";
5641 dol_syslog(get_class($this).
"::add_element_resource", LOG_DEBUG);
5642 if ($this->db->query($sql)) {
5643 $this->db->commit();
5646 $this->error = $this->db->lasterror();
5647 $this->db->rollback();
5668 $sql =
"DELETE FROM ".$this->db->prefix().
"element_resources";
5669 $sql .=
" WHERE rowid = ".((int) $rowid);
5671 dol_syslog(get_class($this).
"::delete_resource", LOG_DEBUG);
5673 $resql = $this->db->query($sql);
5675 $this->error = $this->db->lasterror();
5676 $this->db->rollback();
5680 $result = $this->call_trigger(strtoupper($element).
'_DELETE_RESOURCE', $user);
5682 $this->db->rollback();
5686 $this->db->commit();
5700 if (isset($this->lines) && is_array($this->lines)) {
5701 $nboflines = count($this->lines);
5702 for ($i = 0; $i < $nboflines; $i++) {
5703 if (is_object($this->lines[$i])) {
5704 $this->lines[$i] = clone $this->lines[$i];
5723 protected function commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams =
null)
5725 global $conf, $langs, $user, $hookmanager, $action;
5727 $srctemplatepath =
'';
5729 $parameters = array(
'modelspath' => $modelspath,
'modele' => $modele,
'outputlangs' => $outputlangs,
'hidedetails' => $hidedetails,
'hidedesc' => $hidedesc,
'hideref' => $hideref,
'moreparams' => $moreparams);
5730 $reshook = $hookmanager->executeHooks(
'commonGenerateDocument', $parameters, $this, $action);
5732 if (!empty($reshook)) {
5736 dol_syslog(
"commonGenerateDocument modele=".$modele.
" outputlangs->defaultlang=".(is_object($outputlangs) ? $outputlangs->defaultlang :
'null'));
5738 if (empty($modele)) {
5739 $this->error =
'BadValueForParameterModele';
5744 $err = error_reporting();
5746 @set_time_limit(120);
5747 error_reporting($err);
5750 $tmp = explode(
':', $modele, 2);
5751 $saved_model = $modele;
5752 if (!empty($tmp[1])) {
5754 $srctemplatepath = $tmp[1];
5761 $dirmodels = array(
'/');
5762 if (is_array($conf->modules_parts[
'models'])) {
5763 $dirmodels = array_merge($dirmodels, $conf->modules_parts[
'models']);
5765 foreach ($dirmodels as $reldir) {
5766 foreach (array(
'doc',
'pdf') as $prefix) {
5767 if (in_array(get_class($this), array(
'Adherent'))) {
5769 $file = $prefix.
"_".$modele.
".class.php";
5772 $file = $prefix.
"_".$modele.
".modules.php";
5779 if (file_exists($file)) {
5781 $classname = $prefix.
'_'.$modele;
5790 if ($filefound ===
'' || $classname ===
'') {
5791 $this->error = $langs->trans(
"Error").
' Failed to load doc generator with modelpaths='.$modelspath.
' - modele='.$modele;
5792 $this->errors[] = $this->error;
5803 require_once $filefound;
5805 $obj =
new $classname($this->db);
5817 '@phan-var-force ModelePDFMember $obj';
5821 if ($obj->type ==
'odt' && empty($srctemplatepath)) {
5822 $varfortemplatedir = $obj->scandir;
5826 $listoffiles = array();
5829 $listofdir = explode(
',', $dirtoscan);
5830 foreach ($listofdir as $key => $tmpdir) {
5831 $tmpdir = trim($tmpdir);
5832 $tmpdir = preg_replace(
'/DOL_DATA_ROOT/', DOL_DATA_ROOT, $tmpdir);
5834 unset($listofdir[$key]);
5837 if (is_dir($tmpdir)) {
5838 $tmpfiles =
dol_dir_list($tmpdir,
'files', 0,
'\.od(s|t)$',
'',
'name', SORT_ASC, 0);
5839 if (count($tmpfiles)) {
5840 $listoffiles = array_merge($listoffiles, $tmpfiles);
5845 if (count($listoffiles)) {
5846 foreach ($listoffiles as $record) {
5847 $srctemplatepath = $record[
'fullname'];
5853 if (empty($srctemplatepath)) {
5854 $this->error =
'ErrorGenerationAskedForOdtTemplateWithSrcFileNotDefined';
5859 if ($obj->type ==
'odt' && !empty($srctemplatepath)) {
5861 dol_syslog(
"Failed to locate template file ".$srctemplatepath, LOG_WARNING);
5862 $this->error =
'ErrorGenerationAskedForOdtTemplateWithSrcFileNotFound';
5869 $sav_charset_output = empty($outputlangs->charset_output) ?
'' : $outputlangs->charset_output;
5872 $this->model_pdf = $saved_model;
5875 $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath,
'member', 1,
'tmp_cards');
5878 '@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';
5879 $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, $hidedetails, $hidedesc, $hideref, $moreparams);
5883 if ($resultwritefile > 0) {
5884 $outputlangs->charset_output = $sav_charset_output;
5887 require_once DOL_DOCUMENT_ROOT.
'/core/lib/files.lib.php';
5891 if (!empty($obj->result[
'fullpath'])) {
5892 $destfull = $obj->result[
'fullpath'];
5895 $update_main_doc_field = 0;
5896 if (!empty($obj->update_main_doc_field)) {
5897 $update_main_doc_field = 1;
5903 $this->indexFile($destfull, $update_main_doc_field);
5906 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);
5914 $outputlangs->charset_output = $sav_charset_output;
5915 $this->error = $obj->error;
5916 $this->errors = $obj->errors;
5917 dol_syslog(
"Error generating document for ".__CLASS__.
". Error: ".$obj->error, LOG_ERR);
5931 public function indexFile($destfull, $update_main_doc_field)
5933 global $conf, $user;
5935 $upload_dir = dirname($destfull);
5936 $destfile = basename($destfull);
5937 $rel_dir = preg_replace(
'/^'.preg_quote(DOL_DATA_ROOT,
'/').
'/',
'', $upload_dir);
5939 if (!preg_match(
'/[\\/]temp[\\/]|[\\/]thumbs|\.meta$/', $rel_dir)) {
5940 $filename = basename($destfile);
5941 $rel_dir = preg_replace(
'/[\\/]$/',
'', $rel_dir);
5942 $rel_dir = preg_replace(
'/^[\\/]/',
'', $rel_dir);
5944 include_once DOL_DOCUMENT_ROOT.
'/ecm/class/ecmfiles.class.php';
5945 $ecmfile =
new EcmFiles($this->db);
5946 $result = $ecmfile->fetch(0,
'', ($rel_dir ? $rel_dir.
'/' :
'').$filename);
5949 $setsharekey =
false;
5950 if ($this->element ==
'propal' || $this->element ==
'proposal') {
5952 $setsharekey =
true;
5955 $setsharekey =
true;
5958 if ($this->element ==
'commande' &&
getDolGlobalInt(
"ORDER_ALLOW_EXTERNAL_DOWNLOAD")) {
5959 $setsharekey =
true;
5961 if ($this->element ==
'facture' &&
getDolGlobalInt(
"INVOICE_ALLOW_EXTERNAL_DOWNLOAD")) {
5962 $setsharekey =
true;
5964 if ($this->element ==
'bank_account' &&
getDolGlobalInt(
"BANK_ACCOUNT_ALLOW_EXTERNAL_DOWNLOAD")) {
5965 $setsharekey =
true;
5967 if ($this->element ==
'product' &&
getDolGlobalInt(
"PRODUCT_ALLOW_EXTERNAL_DOWNLOAD")) {
5968 $setsharekey =
true;
5970 if ($this->element ==
'contrat' &&
getDolGlobalInt(
"CONTRACT_ALLOW_EXTERNAL_DOWNLOAD")) {
5971 $setsharekey =
true;
5973 if ($this->element ==
'fichinter' &&
getDolGlobalInt(
"FICHINTER_ALLOW_EXTERNAL_DOWNLOAD")) {
5974 $setsharekey =
true;
5976 if ($this->element ==
'supplier_proposal' &&
getDolGlobalInt(
"SUPPLIER_PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD")) {
5977 $setsharekey =
true;
5979 if ($this->element ==
'societe_rib' &&
getDolGlobalInt(
"SOCIETE_RIB_ALLOW_ONLINESIGN")) {
5980 $setsharekey =
true;
5984 if (empty($ecmfile->share)) {
5985 require_once DOL_DOCUMENT_ROOT.
'/core/lib/security2.lib.php';
5992 $ecmfile->fullpath_orig =
'';
5993 $ecmfile->gen_or_uploaded =
'generated';
5994 $ecmfile->description =
'';
5995 $ecmfile->keywords =
'';
5996 $ecmfile->src_object_type = $this->table_element;
5998 $result = $ecmfile->update($user);
6004 $ecmfile->entity = $conf->entity;
6005 $ecmfile->filepath = $rel_dir;
6006 $ecmfile->filename = $filename;
6008 $ecmfile->fullpath_orig =
'';
6009 $ecmfile->gen_or_uploaded =
'generated';
6010 $ecmfile->description =
'';
6011 $ecmfile->keywords =
'';
6012 $ecmfile->src_object_type = $this->table_element;
6015 $result = $ecmfile->create($user);
6027 if ($update_main_doc_field && !empty($this->table_element)) {
6028 $sql =
"UPDATE ".$this->db->prefix().$this->table_element.
" SET last_main_doc = '".$this->db->escape($ecmfile->filepath.
"/".$ecmfile->filename).
"'";
6029 $sql .=
" WHERE rowid = ".((int) $this->
id);
6031 $resql = $this->db->query($sql);
6036 $this->last_main_doc = $ecmfile->filepath.
'/'.$ecmfile->filename;
6055 if (file_exists($file_osencoded)) {
6056 require_once DOL_DOCUMENT_ROOT.
'/core/lib/images.lib.php';
6059 $maxwidthsmall = $tmparraysize[
'maxwidthsmall'];
6060 $maxheightsmall = $tmparraysize[
'maxheightsmall'];
6061 $maxwidthmini = $tmparraysize[
'maxwidthmini'];
6062 $maxheightmini = $tmparraysize[
'maxheightmini'];
6068 vignette($file_osencoded, $maxwidthsmall, $maxheightsmall,
'_small', $quality);
6072 vignette($file_osencoded, $maxwidthmini, $maxheightmini,
'_mini', $quality);
6112 if (GETPOSTISSET($fieldname)) {
6113 return GETPOST($fieldname, $type, 3);
6116 if (isset($alternatevalue)) {
6117 return $alternatevalue;
6120 $newelement = $this->element;
6121 if ($newelement ==
'facture') {
6122 $newelement =
'invoice';
6124 if ($newelement ==
'commande') {
6125 $newelement =
'order';
6127 if (empty($newelement)) {
6128 dol_syslog(
"Ask a default value using common method getDefaultCreateValueForField on an object with no property ->element defined. Return empty string.", LOG_WARNING);
6132 $keyforfieldname = strtoupper($newelement.
'_DEFAULT_'.$fieldname);
6162 global $langs, $conf;
6164 if (!empty(self::TRIGGER_PREFIX) && strpos($triggerName, self::TRIGGER_PREFIX .
'_') !== 0) {
6165 dol_print_error(
null,
'The trigger "' . $triggerName .
'" does not start with "' . self::TRIGGER_PREFIX .
'_" as required.');
6168 if (!is_object($langs)) {
6169 include_once DOL_DOCUMENT_ROOT.
'/core/class/translate.class.php';
6173 include_once DOL_DOCUMENT_ROOT.
'/core/class/interfaces.class.php';
6175 $result = $interface->run_triggers($triggerName, $this, $user, $langs, $conf);
6178 if (!empty($this->errors)) {
6179 $this->errors = array_unique(array_merge($this->errors, $interface->errors));
6181 $this->errors = $interface->errors;
6201 if (!$this->element) {
6204 if (!($this->
id > 0)) {
6207 if (is_array($this->array_languages)) {
6211 $this->array_languages = array();
6213 $element = $this->element;
6214 if ($element ==
'categorie') {
6215 $element =
'categories';
6219 $sql =
"SELECT rowid, property, lang , value";
6220 $sql .=
" FROM ".$this->db->prefix().
"object_lang";
6221 $sql .=
" WHERE type_object = '".$this->db->escape($element).
"'";
6222 $sql .=
" AND fk_object = ".((int) $this->
id);
6225 $resql = $this->db->query($sql);
6227 $numrows = $this->db->num_rows($resql);
6230 while ($i < $numrows) {
6231 $obj = $this->db->fetch_object($resql);
6232 $key = $obj->property;
6233 $value = $obj->value;
6234 $codelang = $obj->lang;
6235 $type = $this->fields[$key][
'type'];
6238 if (preg_match(
'/date/', $type)) {
6239 $this->array_languages[$key][$codelang] = $this->db->jdate($value);
6241 $this->array_languages[$key][$codelang] = $value;
6248 $this->db->free($resql);
6270 foreach ($_POST as $postfieldkey => $postfieldvalue) {
6271 $tmparray = explode(
'-', $postfieldkey);
6272 if ($tmparray[0] !=
'field') {
6276 $element = $tmparray[1];
6277 $key = $tmparray[2];
6278 $codelang = $tmparray[3];
6281 if (!empty($onlykey) && $key != $onlykey) {
6284 if ($element != $this->element) {
6288 $key_type = $this->fields[$key][
'type'];
6291 if (isset($this->fields[$key][
'enabled'])) {
6292 $enabled = (int)
dol_eval($this->fields[$key][
'enabled'], 1, 1,
'1');
6299 if (empty($enabled)) {
6304 if (in_array($key_type, array(
'date'))) {
6308 } elseif (in_array($key_type, array(
'datetime'))) {
6312 } elseif (in_array($key_type, array(
'checkbox',
'chkbxlst'))) {
6313 $value_arr =
GETPOST($postfieldkey,
'array');
6314 if (!empty($value_arr)) {
6315 $value_key = implode(
',', $value_arr);
6319 } elseif (in_array($key_type, array(
'price',
'double'))) {
6320 $value_arr =
GETPOST($postfieldkey,
'alpha');
6323 $value_key =
GETPOST($postfieldkey);
6324 if (in_array($key_type, array(
'link')) && $value_key ==
'-1') {
6329 $this->array_languages[$key][$codelang] = $value_key;
6354 $savDisableCompute = $conf->disable_compute;
6355 $conf->disable_compute = 1;
6357 $ret = $this->fetch(
$id);
6359 $conf->disable_compute = $savDisableCompute;
6377 global $conf, $extrafields;
6379 if (empty($rowid)) {
6382 if (empty($rowid) && isset($this->
rowid)) {
6383 $rowid = $this->rowid;
6387 if (!$this->table_element) {
6391 $this->array_options = array();
6393 if (!is_array($optionsArray)) {
6395 if (!isset($extrafields) || !is_object($extrafields)) {
6396 require_once DOL_DOCUMENT_ROOT.
'/core/class/extrafields.class.php';
6401 if (empty($extrafields->attributes[$this->table_element][
'loaded'])) {
6402 $extrafields->fetch_name_optionals_label($this->table_element);
6404 $optionsArray = (!empty($extrafields->attributes[$this->table_element][
'label']) ? $extrafields->attributes[$this->table_element][
'label'] :
null);
6406 global $extrafields;
6407 dol_syslog(
"Warning: fetch_optionals was called with param optionsArray defined when you should pass null now", LOG_WARNING);
6410 $table_element = $this->table_element;
6411 if ($table_element ==
'categorie') {
6412 $table_element =
'categories';
6416 if (is_array($optionsArray) && count($optionsArray) > 0) {
6417 $sql =
"SELECT rowid";
6418 foreach ($optionsArray as $name => $label) {
6419 if (empty($extrafields->attributes[$this->table_element][
'type'][$name]) || (!in_array($extrafields->attributes[$this->table_element][
'type'][$name], [
'separate',
'point',
'multipts',
'linestrg',
'polygon']))) {
6423 if (empty($extrafields->attributes[$this->table_element][
'type'][$name]) || $extrafields->attributes[$this->table_element][
'type'][$name] ==
'point') {
6424 $sql .=
", ST_AsWKT(".$name.
") as ".$name;
6426 if (empty($extrafields->attributes[$this->table_element][
'type'][$name]) || $extrafields->attributes[$this->table_element][
'type'][$name] ==
'multipts') {
6427 $sql .=
", ST_AsWKT(".$name.
") as ".$name;
6429 if (empty($extrafields->attributes[$this->table_element][
'type'][$name]) || $extrafields->attributes[$this->table_element][
'type'][$name] ==
'linestrg') {
6430 $sql .=
", ST_AsWKT(".$name.
") as ".$name;
6432 if (empty($extrafields->attributes[$this->table_element][
'type'][$name]) || $extrafields->attributes[$this->table_element][
'type'][$name] ==
'polygon') {
6433 $sql .=
", ST_AsWKT(".$name.
") as ".$name;
6436 $sql .=
" FROM ".$this->db->prefix().$table_element.
"_extrafields";
6437 $sql .=
" WHERE fk_object = ".((int) $rowid);
6440 $resql = $this->db->query($sql);
6442 $numrows = $this->db->num_rows($resql);
6444 $tab = $this->db->fetch_array($resql);
6446 foreach ($tab as $key => $value) {
6448 if ($key !=
'rowid' && $key !=
'tms' && $key !=
'fk_member' && !is_int($key)) {
6450 if (!empty($extrafields->attributes[$this->table_element]) && in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'date',
'datetime'))) {
6452 $this->array_options[
"options_".$key] = $this->db->jdate($value);
6454 $this->array_options[
"options_".$key] = $value;
6459 if (!empty($extrafields->attributes[$this->table_element][
'type'][$key]) && $extrafields->attributes[$this->table_element][
'type'][$key] ==
'password') {
6460 if (!empty($value) && preg_match(
'/^dolcrypt:/', $value)) {
6461 $this->array_options[
"options_".$key] =
dolDecrypt($value);
6470 if (is_array($extrafields->attributes[$this->table_element][
'label'])) {
6471 foreach ($extrafields->attributes[$this->table_element][
'label'] as $key => $val) {
6472 $this->array_options[
'options_' . $key] =
null;
6479 if (is_array($extrafields->attributes[$this->table_element][
'label'])) {
6480 foreach ($extrafields->attributes[$this->table_element][
'label'] as $key => $val) {
6481 if (!empty($extrafields->attributes[$this->table_element]) && !empty($extrafields->attributes[$this->table_element][
'computed'][$key])) {
6483 if (empty($conf->disable_compute)) {
6484 global $objectoffield;
6485 $objectoffield = $this;
6486 $this->array_options[
'options_' . $key] =
dol_eval($extrafields->attributes[$this->table_element][
'computed'][$key], 1, 0,
'2');
6492 $this->db->free($resql);
6500 $this->errors[] = $this->db->lasterror;
6523 $table_element = $this->table_element;
6524 if ($table_element ==
'categorie') {
6525 $table_element =
'categories';
6528 dol_syslog(get_class($this).
"::deleteExtraFields delete", LOG_DEBUG);
6530 $sql_del =
"DELETE FROM ".$this->db->prefix().$table_element.
"_extrafields WHERE fk_object = ".((int) $this->
id);
6532 $resql = $this->db->query($sql_del);
6534 $this->error = $this->db->lasterror();
6535 $this->db->rollback();
6538 $this->db->commit();
6555 global $conf, $langs, $user;
6561 if (empty($userused)) {
6567 if (!empty($this->array_options)) {
6569 $langs->load(
'admin');
6570 require_once DOL_DOCUMENT_ROOT.
'/core/class/extrafields.class.php';
6572 $target_extrafields = $extrafields->fetch_name_optionals_label($this->table_element);
6575 $new_array_options = array();
6576 foreach ($this->array_options as $key => $value) {
6577 if (in_array(substr($key, 8), array_keys($target_extrafields))) {
6578 $new_array_options[$key] = $value;
6579 } elseif (in_array($key, array_keys($target_extrafields))) {
6580 $new_array_options[
'options_'.$key] = $value;
6584 foreach ($new_array_options as $key => $value) {
6585 $attributeKey = substr($key, 8);
6586 $attributeType = $extrafields->attributes[$this->table_element][
'type'][$attributeKey];
6587 $attributeLabel = $langs->transnoentities($extrafields->attributes[$this->table_element][
'label'][$attributeKey]);
6588 $attributeParam = $extrafields->attributes[$this->table_element][
'param'][$attributeKey];
6589 $attributeRequired = $extrafields->attributes[$this->table_element][
'required'][$attributeKey];
6590 $attributeUnique = $extrafields->attributes[$this->table_element][
'unique'][$attributeKey];
6591 $attrfieldcomputed = $extrafields->attributes[$this->table_element][
'computed'][$attributeKey];
6595 if (!empty($this->context[
'createfromclone']) && $this->context[
'createfromclone'] ==
'createfromclone' && !empty($attributeUnique)) {
6596 $new_array_options[$key] =
null;
6600 if ($attributeRequired) {
6601 $v = $this->array_options[$key];
6603 $langs->load(
"errors");
6604 dol_syslog(
"Mandatory field '".$key.
"' is empty during create and set to required into definition of extrafields");
6605 $this->errors[] = $langs->trans(
'ErrorFieldRequired', $attributeLabel);
6613 if (!empty($attrfieldcomputed)) {
6615 $value =
dol_eval($attrfieldcomputed, 1, 0,
'2');
6616 dol_syslog($langs->trans(
"Extrafieldcomputed").
" on ".$attributeLabel.
"(".$value.
")", LOG_DEBUG);
6617 $new_array_options[$key] = $value;
6619 $new_array_options[$key] =
null;
6623 switch ($attributeType) {
6625 if (!is_numeric($value) && $value !=
'') {
6626 $this->errors[] = $langs->trans(
"ExtraFieldHasWrongValue", $attributeLabel);
6628 } elseif ($value ==
'') {
6629 $new_array_options[$key] =
null;
6635 if (!is_numeric($value) && $value !=
'') {
6636 dol_syslog($langs->trans(
"ExtraFieldHasWrongValue").
" for ".$attributeLabel.
"(".$value.
"is not '".$attributeType.
"')", LOG_DEBUG);
6637 $this->errors[] = $langs->trans(
"ExtraFieldHasWrongValue", $attributeLabel);
6639 } elseif ($value ==
'') {
6643 $new_array_options[$key] = $value;
6653 if ($this->array_options[$key] !=
'' && is_array($extrafields->attributes[$this->table_element][
'param'][$attributeKey][
'options'])) {
6655 $tmparrays = array_keys($extrafields->attributes[$this->table_element][
'param'][$attributeKey][
'options']);
6656 $algo = reset($tmparrays);
6661 if (is_object($this->oldcopy)) {
6663 if (isset($this->oldcopy->array_options[$key]) && $this->array_options[$key] == $this->oldcopy->array_options[$key]) {
6665 if ($algo ==
'dolcrypt') {
6666 if (!preg_match(
'/^dolcrypt:/', $this->array_options[$key])) {
6667 $new_array_options[$key] =
dolEncrypt($this->array_options[$key]);
6669 $new_array_options[$key] = $this->array_options[$key];
6672 $new_array_options[$key] = $this->array_options[$key];
6676 if ($algo ==
'dolcrypt') {
6677 if (!preg_match(
'/^dolcrypt:/', $this->array_options[$key])) {
6678 $new_array_options[$key] =
dolEncrypt($this->array_options[$key]);
6680 $new_array_options[$key] = $this->array_options[$key];
6683 $new_array_options[$key] =
dol_hash($this->array_options[$key], $algo);
6689 if ($algo ==
'dolcrypt' && !preg_match(
'/^dolcrypt:/', $this->array_options[$key])) {
6690 $new_array_options[$key] =
dolEncrypt($this->array_options[$key]);
6692 $new_array_options[$key] = $this->array_options[$key];
6697 $new_array_options[$key] = $this->array_options[$key];
6700 $new_array_options[$key] = $this->array_options[$key];
6706 if (!is_numeric($this->array_options[$key]) || $this->array_options[$key] != intval($this->array_options[$key])) {
6707 $this->array_options[$key] = strtotime($this->array_options[$key]);
6709 $new_array_options[$key] = $this->db->idate($this->array_options[$key]);
6713 if (!is_numeric($this->array_options[$key]) || $this->array_options[$key] != intval($this->array_options[$key])) {
6714 $this->array_options[$key] = strtotime($this->array_options[$key]);
6716 $new_array_options[$key] = $this->db->idate($this->array_options[$key],
'gmt');
6719 $param_list = array_keys($attributeParam[
'options']);
6722 $InfoFieldList = explode(
":", $param_list[0]);
6724 if ($InfoFieldList[0] && class_exists($InfoFieldList[0])) {
6725 if ($value ==
'-1') {
6726 $new_array_options[$key] =
'';
6728 $object =
new $InfoFieldList[0]($this->db);
6729 '@phan-var-force CommonObject $object';
6730 if (is_numeric($value)) {
6731 $res =
$object->fetch($value);
6733 $res =
$object->fetch(0, $value);
6737 $new_array_options[$key] =
$object->id;
6739 $this->error =
"Id/Ref '".$value.
"' for object '".
$object->element.
"' not found";
6744 dol_syslog(
'Error bad setup of extrafield', LOG_WARNING);
6749 if (is_array($this->array_options[$key])) {
6750 $new_array_options[$key] = implode(
',', $this->array_options[$key]);
6752 $new_array_options[$key] = $this->array_options[$key];
6760 $table_element = $this->table_element;
6761 if ($table_element ==
'categorie') {
6762 $table_element =
'categories';
6765 dol_syslog(get_class($this).
"::insertExtraFields delete then insert", LOG_DEBUG);
6767 $sql_del =
"DELETE FROM ".$this->db->prefix().$table_element.
"_extrafields WHERE fk_object = ".((int) $this->
id);
6768 $this->db->query($sql_del);
6770 $sql =
"INSERT INTO ".$this->db->prefix().$table_element.
"_extrafields (fk_object";
6771 foreach ($new_array_options as $key => $value) {
6772 $attributeKey = substr($key, 8);
6774 if ($extrafields->attributes[$this->table_element][
'type'][$attributeKey] !=
'separate') {
6775 $sql .=
",".$attributeKey;
6779 if (!empty($extrafields->attributes[$this->table_element][
'mandatoryfieldsofotherentities']) && is_array($extrafields->attributes[$this->table_element][
'mandatoryfieldsofotherentities'])) {
6780 foreach ($extrafields->attributes[$this->table_element][
'mandatoryfieldsofotherentities'] as $tmpkey => $tmpval) {
6781 if (!isset($extrafields->attributes[$this->table_element][
'type'][$tmpkey])) {
6782 $sql .=
",".$tmpkey;
6786 $sql .=
") VALUES (".$this->id;
6788 foreach ($new_array_options as $key => $value) {
6789 $attributeKey = substr($key, 8);
6791 if (!in_array($extrafields->attributes[$this->table_element][
'type'][$attributeKey], [
'separate',
'point',
'multipts',
'linestrg',
'polygon'])) {
6792 if ($new_array_options[$key] !=
'' || $new_array_options[$key] ==
'0') {
6793 $sql .=
",'".$this->db->escape($new_array_options[$key]).
"'";
6798 if ($extrafields->attributes[$this->table_element][
'type'][$attributeKey] ==
'point') {
6799 if (!empty($new_array_options[$key])) {
6800 $sql .=
",ST_PointFromText('".$this->db->escape($new_array_options[$key]).
"')";
6805 if ($extrafields->attributes[$this->table_element][
'type'][$attributeKey] ==
'multipts') {
6806 if (!empty($new_array_options[$key])) {
6807 $sql .=
",ST_MultiPointFromText('".$this->db->escape($new_array_options[$key]).
"')";
6812 if ($extrafields->attributes[$this->table_element][
'type'][$attributeKey] ==
'linestrg') {
6813 if (!empty($new_array_options[$key])) {
6814 $sql .=
",ST_LineFromText('".$this->db->escape($new_array_options[$key]).
"')";
6819 if ($extrafields->attributes[$this->table_element][
'type'][$attributeKey] ==
'polygon') {
6820 if (!empty($new_array_options[$key])) {
6821 $sql .=
",ST_PolyFromText('".$this->db->escape($new_array_options[$key]).
"')";
6828 if (!empty($extrafields->attributes[$this->table_element][
'mandatoryfieldsofotherentities']) && is_array($extrafields->attributes[$this->table_element][
'mandatoryfieldsofotherentities'])) {
6829 foreach ($extrafields->attributes[$this->table_element][
'mandatoryfieldsofotherentities'] as $tmpkey => $tmpval) {
6830 if (!isset($extrafields->attributes[$this->table_element][
'type'][$tmpkey])) {
6831 if (in_array($tmpval, array(
'int',
'double',
'price'))) {
6842 $resql = $this->db->query($sql);
6844 $this->error = $this->db->lasterror();
6848 if (!$error && $trigger) {
6850 $this->context = array(
'extrafieldaddupdate' => 1);
6851 $result = $this->call_trigger($trigger, $userused);
6859 $this->db->rollback();
6862 $this->db->commit();
6882 global $conf, $langs, $user;
6884 if (empty($userused)) {
6894 if (is_array($this->array_languages)) {
6895 $new_array_languages = $this->array_languages;
6897 foreach ($new_array_languages as $key => $value) {
6898 $attributeKey = $key;
6899 $attributeType = $this->fields[$attributeKey][
'type'];
6900 $attributeLabel = $this->fields[$attributeKey][
'label'];
6905 switch ($attributeType) {
6907 if (is_array($value) || (!is_numeric($value) && $value !=
'')) {
6908 $this->errors[] = $langs->trans(
"ExtraLanguageHasWrongValue", $attributeLabel);
6910 } elseif ($value ==
'') {
6911 $new_array_languages[$key] =
null;
6916 if (!is_numeric($value) && $value !=
'') {
6917 dol_syslog($langs->trans(
"ExtraLanguageHasWrongValue").
" on ".$attributeLabel.
"(".$value.
"is not '".$attributeType.
"')", LOG_DEBUG);
6918 $this->errors[] = $langs->trans(
"ExtraLanguageHasWrongValue", $attributeLabel);
6920 } elseif ($value ==
'') {
6921 $new_array_languages[$key] =
null;
6923 $new_array_languages[$key] = $value;
6937 $table_element = $this->table_element;
6938 if ($table_element ==
'categorie') {
6939 $table_element =
'categories';
6942 dol_syslog(get_class($this).
"::insertExtraLanguages delete then insert", LOG_DEBUG);
6944 foreach ($new_array_languages as $key => $langcodearray) {
6945 foreach ($langcodearray as $langcode => $value) {
6946 $sql_del =
"DELETE FROM ".$this->db->prefix().
"object_lang";
6947 $sql_del .=
" WHERE fk_object = ".((int) $this->
id).
" AND property = '".$this->db->escape($key).
"' AND type_object = '".$this->db->escape($table_element).
"'";
6948 $sql_del .=
" AND lang = '".$this->db->escape($langcode).
"'";
6949 $this->db->query($sql_del);
6951 if ($value !==
'') {
6952 $sql =
"INSERT INTO ".$this->db->prefix().
"object_lang (fk_object, property, type_object, lang, value";
6953 $sql .=
") VALUES (".$this->id.
", '".$this->db->escape($key).
"', '".$this->db->escape($table_element).
"', '".$this->db->escape($langcode).
"', '".$this->db->escape($value).
"'";
6956 $resql = $this->db->query($sql);
6958 $this->error = $this->db->lasterror();
6966 if (!$error && $trigger) {
6968 $this->context = array(
'extralanguagesaddupdate' => 1);
6969 $result = $this->call_trigger($trigger, $userused);
6977 $this->db->rollback();
6980 $this->db->commit();
7000 global $conf, $langs, $user, $hookmanager;
7006 if (empty($userused)) {
7012 if (!empty($this->array_options) && isset($this->array_options[
"options_".$key])) {
7014 $langs->load(
'admin');
7015 require_once DOL_DOCUMENT_ROOT.
'/core/class/extrafields.class.php';
7017 $extrafields->fetch_name_optionals_label($this->table_element);
7019 $value = $this->array_options[
"options_".$key];
7021 $attributeKey = $key;
7022 $attributeType = $extrafields->attributes[$this->table_element][
'type'][$key];
7023 $attributeLabel = $extrafields->attributes[$this->table_element][
'label'][$key];
7024 $attributeParam = $extrafields->attributes[$this->table_element][
'param'][$key];
7025 $attributeRequired = $extrafields->attributes[$this->table_element][
'required'][$key];
7026 $attributeUnique = $extrafields->attributes[$this->table_element][
'unique'][$attributeKey];
7027 $attrfieldcomputed = $extrafields->attributes[$this->table_element][
'computed'][$key];
7030 if ($attributeRequired) {
7031 $mandatorypb =
false;
7032 if ($attributeType ==
'link' && $this->array_options[
"options_".$key] ==
'-1') {
7033 $mandatorypb =
true;
7035 if ($this->array_options[
"options_".$key] ===
'') {
7036 $mandatorypb =
true;
7039 $langs->load(
"errors");
7040 dol_syslog(
"Mandatory field 'options_".$key.
"' is empty during update and set to required into definition of extrafields");
7041 $this->errors[] = $langs->trans(
'ErrorFieldRequired', $attributeLabel);
7047 $new_array_options = $this->array_options;
7051 if (!empty($attrfieldcomputed)) {
7053 $value =
dol_eval($attrfieldcomputed, 1, 0,
'2');
7054 dol_syslog($langs->trans(
"Extrafieldcomputed").
" on ".$attributeLabel.
"(".$value.
")", LOG_DEBUG);
7056 $new_array_options[
"options_".$key] = $value;
7058 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7060 $new_array_options[
"options_".$key] =
null;
7062 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7066 switch ($attributeType) {
7068 if (!is_numeric($value) && $value !=
'') {
7069 $this->errors[] = $langs->trans(
"ExtraFieldHasWrongValue", $attributeLabel);
7071 } elseif ($value ===
'') {
7072 $new_array_options[
"options_".$key] =
null;
7074 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7080 if (!is_numeric($value) && $value !=
'') {
7081 dol_syslog($langs->trans(
"ExtraFieldHasWrongValue").
" on ".$attributeLabel.
"(".$value.
"is not '".$attributeType.
"')", LOG_DEBUG);
7082 $this->errors[] = $langs->trans(
"ExtraFieldHasWrongValue", $attributeLabel);
7084 } elseif ($value ===
'') {
7088 $new_array_options[
"options_".$key] = $value;
7090 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7102 if ($this->array_options[
"options_".$key] !=
'' && is_array($extrafields->attributes[$this->table_element][
'param'][$attributeKey][
'options'])) {
7104 $tmparrays = array_keys($extrafields->attributes[$this->table_element][
'param'][$attributeKey][
'options']);
7105 $algo = reset($tmparrays);
7111 if (is_object($this->oldcopy)) {
7113 if (isset($this->oldcopy->array_options[
"options_".$key]) && $this->array_options[
"options_".$key] == $this->oldcopy->array_options[
"options_".$key]) {
7114 if ($algo ==
'dolcrypt') {
7115 if (!preg_match(
'/^dolcrypt:/', $this->array_options[
"options_".$key])) {
7116 $new_array_options[
"options_".$key] =
dolEncrypt($this->array_options[
"options_".$key]);
7118 $new_array_options[
"options_".$key] = $this->array_options[
"options_".$key];
7121 $new_array_options[
"options_".$key] = $this->array_options[
"options_".$key];
7124 if ($algo ==
'dolcrypt') {
7125 if (!preg_match(
'/^dolcrypt:/', $this->array_options[
"options_".$key])) {
7126 $new_array_options[
"options_".$key] =
dolEncrypt($this->array_options[
"options_".$key]);
7128 $new_array_options[
"options_".$key] = $this->array_options[
"options_".$key];
7131 $new_array_options[
"options_".$key] =
dol_hash($this->array_options[
"options_".$key], $algo);
7135 if ($algo ==
'dolcrypt' && !preg_match(
'/^dolcrypt:/', $this->array_options[
"options_".$key])) {
7136 $new_array_options[
"options_".$key] =
dolEncrypt($this->array_options[
"options_".$key]);
7138 $new_array_options[
"options_".$key] = $this->array_options[
"options_".$key];
7143 $new_array_options[
"options_".$key] = $this->array_options[
"options_".$key];
7146 $new_array_options[
"options_".$key] = $this->array_options[
"options_".$key];
7149 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7153 if (empty($this->array_options[
"options_".$key])) {
7154 $new_array_options[
"options_".$key] =
null;
7156 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7158 $new_array_options[
"options_".$key] = $this->db->idate($this->array_options[
"options_".$key]);
7162 if (empty($this->array_options[
"options_".$key])) {
7163 $new_array_options[
"options_".$key] =
null;
7165 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7167 $new_array_options[
"options_".$key] = $this->db->idate($this->array_options[
"options_".$key],
'gmt');
7171 if (empty($this->array_options[
"options_".$key])) {
7172 $new_array_options[
"options_".$key] =
null;
7174 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7178 if ($this->array_options[
"options_".$key] ===
'') {
7179 $new_array_options[
"options_".$key] =
null;
7181 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7215 $new_array_options = array();
7216 if (is_array($this->array_options[
"options_".$key])) {
7217 $new_array_options[
"options_".$key] = implode(
',', $this->array_options[
"options_".$key]);
7219 $new_array_options[
"options_".$key] = $this->array_options[
"options_".$key];
7222 $this->array_options[
"options_".$key] = $new_array_options[
"options_".$key];
7228 $linealreadyfound = 0;
7231 $table_element = $this->table_element;
7232 if ($table_element ==
'categorie') {
7233 $table_element =
'categories';
7236 $sql =
"SELECT COUNT(rowid) as nb FROM ".$this->db->prefix().$table_element.
"_extrafields WHERE fk_object = ".((int) $this->
id);
7237 $resql = $this->db->query($sql);
7239 $tmpobj = $this->db->fetch_object($resql);
7241 $linealreadyfound = $tmpobj->nb;
7246 if ($linealreadyfound) {
7247 if ($this->array_options[
"options_".$key] ===
null) {
7248 $sql =
"UPDATE ".$this->db->prefix().$table_element.
"_extrafields SET ".$key.
" = null";
7250 $sql =
"UPDATE ".$this->db->prefix().$table_element.
"_extrafields SET ".$key.
" = '".$this->db->escape($new_array_options[
"options_".$key]).
"'";
7252 $sql .=
" WHERE fk_object = ".((int) $this->
id);
7254 $resql = $this->db->query($sql);
7257 $this->error = $this->db->lasterror();
7260 $result = $this->insertExtraFields(
'', $user);
7267 $parameters = array(
'key' => $key);
7269 $reshook = $hookmanager->executeHooks(
'updateExtraFieldBeforeCommit', $parameters, $this, $action);
7275 if (!$error && $trigger) {
7277 $this->context = array(
'extrafieldupdate' => 1);
7278 $result = $this->call_trigger($trigger, $userused);
7286 dol_syslog(__METHOD__.$this->error, LOG_ERR);
7287 $this->db->rollback();
7290 $this->db->commit();
7306 return $this->array_options[
'options_'.$key] ??
null;
7318 $this->array_options[
'options_'.$key] = $value;
7333 global $conf, $langs, $user;
7335 if (empty($userused)) {
7364 public function showInputField($val, $key, $value, $moreparam =
'', $keysuffix =
'', $keyprefix =
'', $morecss = 0, $nonewbutton = 0)
7366 global $conf, $langs, $form;
7368 if (!is_object($form)) {
7369 require_once DOL_DOCUMENT_ROOT.
'/core/class/html.form.class.php';
7370 $form =
new Form($this->db);
7373 if (!empty($this->fields)) {
7374 $val = $this->fields[$key];
7378 $fieldValidationErrorMsg =
'';
7379 $validationClass =
'';
7380 $fieldValidationErrorMsg = $this->getFieldError($key);
7381 if (!empty($fieldValidationErrorMsg)) {
7382 $validationClass =
' --error';
7384 $validationClass =
' --success';
7387 $valuemultiselectinput = array();
7392 $param[
'options'] = array();
7395 $size = !empty($this->fields[$key][
'size']) ? $this->fields[$key][
'size'] : 0;
7397 if (preg_match(
'/^(integer|link):(.*):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
7398 $param[
'options'] = array($reg[2].
':'.$reg[3].
':'.$reg[4].
':'.$reg[5] =>
'N');
7400 } elseif (preg_match(
'/^(integer|link):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
7401 $param[
'options'] = array($reg[2].
':'.$reg[3].
':'.$reg[4] =>
'N');
7403 } elseif (preg_match(
'/^(integer|link):(.*):(.*)/i', $val[
'type'], $reg)) {
7404 $param[
'options'] = array($reg[2].
':'.$reg[3] =>
'N');
7406 } elseif (preg_match(
'/^(sellist):(.*):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
7407 $param[
'options'] = array($reg[2].
':'.$reg[3].
':'.$reg[4].
':'.$reg[5] =>
'N');
7409 } elseif (preg_match(
'/^(sellist):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
7410 $param[
'options'] = array($reg[2].
':'.$reg[3].
':'.$reg[4] =>
'N');
7412 } elseif (preg_match(
'/^(sellist):(.*):(.*)/i', $val[
'type'], $reg)) {
7413 $param[
'options'] = array($reg[2].
':'.$reg[3] =>
'N');
7415 } elseif (preg_match(
'/^chkbxlst:(.*)/i', $val[
'type'], $reg)) {
7416 $param[
'options'] = array($reg[1] =>
'N');
7418 } elseif (preg_match(
'/varchar\((\d+)\)/', $val[
'type'], $reg)) {
7419 $param[
'options'] = array();
7422 } elseif (preg_match(
'/varchar/', $val[
'type'])) {
7423 $param[
'options'] = array();
7426 $param[
'options'] = array();
7427 $type = $this->fields[$key][
'type'];
7432 if (!empty($this->fields[$key][
'arrayofkeyval']) && is_array($this->fields[$key][
'arrayofkeyval'])) {
7433 $param[
'options'] = $this->fields[$key][
'arrayofkeyval'];
7435 if (empty($this->fields[$key][
'multiinput'])) {
7436 $type = (($this->fields[$key][
'type'] ==
'checkbox') ? $this->fields[$key][
'type'] :
'select');
7440 $label = $this->fields[$key][
'label'];
7443 $default = (!empty($this->fields[$key][
'default']) ? $this->fields[$key][
'default'] :
'');
7445 $computed = (!empty($this->fields[$key][
'computed']) ? $this->fields[$key][
'computed'] :
'');
7447 $unique = (!empty($this->fields[$key][
'unique']) ? $this->fields[$key][
'unique'] : 0);
7449 $required = (!empty($this->fields[$key][
'required']) ? $this->fields[$key][
'required'] : 0);
7451 $autofocusoncreate = (!empty($this->fields[$key][
'autofocusoncreate']) ? $this->fields[$key][
'autofocusoncreate'] : 0);
7454 $langfile = (!empty($this->fields[$key][
'langfile']) ? $this->fields[$key][
'langfile'] :
'');
7456 $list = (!empty($this->fields[$key][
'list']) ? $this->fields[$key][
'list'] : 0);
7457 $hidden = (in_array(abs($this->fields[$key][
'visible']), array(0, 2)) ? 1 : 0);
7462 if (!preg_match(
'/^search_/', $keyprefix)) {
7463 return '<span class="opacitymedium">'.$langs->trans(
"AutomaticallyCalculated").
'</span>';
7470 if (empty($morecss) && !empty($val[
'css'])) {
7471 $morecss = $val[
'css'];
7472 } elseif (empty($morecss)) {
7473 if ($type ==
'date') {
7474 $morecss =
'minwidth100imp';
7475 } elseif ($type ==
'datetime' || $type ==
'link') {
7476 $morecss =
'minwidth200imp';
7477 } elseif (in_array($type, array(
'int',
'integer',
'price')) || preg_match(
'/^double(\([0-9],[0-9]\)){0,1}/', (
string) $type)) {
7478 $morecss =
'maxwidth75';
7479 } elseif ($type ==
'url') {
7480 $morecss =
'minwidth400';
7481 } elseif ($type ==
'boolean') {
7484 if (is_numeric($size) && round((
float) $size) < 12) {
7485 $morecss =
'minwidth100';
7486 } elseif (is_numeric($size) && round((
float) $size) <= 48) {
7487 $morecss =
'minwidth200';
7489 $morecss =
'minwidth400';
7495 if (!empty($validationClass)) {
7496 $morecss .= $validationClass;
7499 if (in_array($type, array(
'date'))) {
7500 $tmp = explode(
',', $size);
7505 if (!$required && $value ==
'') {
7510 $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required,
'', 1, (($keyprefix !=
'search_' && $keyprefix !=
'search_options_') ? 1 : 0), 0, 1);
7511 } elseif (in_array($type, array(
'datetime'))) {
7512 $tmp = explode(
',', $size);
7517 if (!$required && $value ==
'') {
7522 $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required,
'', 1, (($keyprefix !=
'search_' && $keyprefix !=
'search_options_') ? 1 : 0), 0, 1,
'',
'',
'', 1,
'',
'',
'tzuserrel');
7523 } elseif (in_array($type, array(
'duration'))) {
7524 $out = $form->select_duration($keyprefix.$key.$keysuffix, $value, 0,
'text', 0, 1);
7525 } elseif (in_array($type, array(
'int',
'integer'))) {
7526 $tmp = explode(
',', $size);
7528 $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' :
'').
'>';
7529 } elseif (in_array($type, array(
'real'))) {
7530 $out =
'<input type="text" class="flat '.$morecss.
'" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.
dol_escape_htmltag($value).
'"'.($moreparam ? $moreparam :
'').($autofocusoncreate ?
' autofocus' :
'').
'>';
7531 } elseif (preg_match(
'/varchar/', (
string) $type)) {
7532 $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' :
'').
'>';
7533 } elseif (in_array($type, array(
'email',
'mail',
'phone',
'url',
'ip'))) {
7534 $out =
'<input type="text" class="flat '.$morecss.
'" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.
dol_escape_htmltag($value).
'" '.($moreparam ? $moreparam :
'').($autofocusoncreate ?
' autofocus' :
'').
'>';
7535 } elseif (preg_match(
'/^text/', (
string) $type)) {
7536 if (!preg_match(
'/search_/', $keyprefix)) {
7537 if (!empty($param[
'options'])) {
7540 $out .= $form->selectarray($keyprefix.$key.$keysuffix.
"_multiinput", $param[
'options'],
'', 1, 0, 0,
"flat maxwidthonphone".$morecss);
7541 $out .=
'<input id="'.$keyprefix.$key.$keysuffix.
'_multiinputadd" type="button" class="button" value="'.$langs->trans(
"Add").
'">';
7544 function handlemultiinputdisabling(htmlname){
7545 console.log("We handle the disabling of used options for "+htmlname+"_multiinput");
7546 multiinput = $("#"+htmlname+"_multiinput");
7547 multiinput.find("option").each(function(){
7548 tmpval = $("#"+htmlname).val();
7549 tmpvalarray = tmpval.split("\n");
7550 valtotest = $(this).val();
7551 if(tmpvalarray.includes(valtotest)){
7552 $(this).prop("disabled",true);
7554 if($(this).prop("disabled") == true){
7555 console.log(valtotest)
7556 $(this).prop("disabled", false);
7562 $(document).ready(function () {
7563 $("#'.$keyprefix.$key.$keysuffix.
'_multiinputadd").on("click",function() {
7564 tmpval = $("#'.$keyprefix.$key.$keysuffix.
'").val();
7565 tmpvalarray = tmpval.split(",");
7566 valtotest = $("#'.$keyprefix.$key.$keysuffix.
'_multiinput").val();
7567 if(valtotest != -1 && !tmpvalarray.includes(valtotest)){
7568 console.log("We add the selected value to the text area '.$keyprefix.$key.$keysuffix.
'");
7572 tmpval = tmpval + "\n" + valtotest;
7574 $("#'.$keyprefix.$key.$keysuffix.
'").val(tmpval);
7575 handlemultiinputdisabling("'.$keyprefix.$key.$keysuffix.
'");
7576 $("#'.$keyprefix.$key.$keysuffix.
'_multiinput").val(-1);
7578 console.log("We add nothing the text area '.$keyprefix.$key.$keysuffix.
'");
7581 $("#'.$keyprefix.$key.$keysuffix.
'").on("change",function(){
7582 handlemultiinputdisabling("'.$keyprefix.$key.$keysuffix.
'");
7584 handlemultiinputdisabling("'.$keyprefix.$key.$keysuffix.
'");
7586 $out .=
"</script>";
7587 $value = str_replace(
',',
"\n", $value);
7589 require_once DOL_DOCUMENT_ROOT.
'/core/class/doleditor.class.php';
7590 $doleditor =
new DolEditor($keyprefix.$key.$keysuffix, $value,
'', 200,
'dolibarr_notes',
'In',
false,
false,
false, ROWS_5,
'90%');
7591 $out .= (string) $doleditor->Create(1,
'',
true,
'',
'',
'', $morecss);
7593 $out =
'<input type="text" class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.
dol_escape_htmltag($value).
'" '.($moreparam ? $moreparam :
'').
'>';
7595 } elseif (preg_match(
'/^html/', (
string) $type)) {
7596 if (!preg_match(
'/search_/', $keyprefix)) {
7597 require_once DOL_DOCUMENT_ROOT.
'/core/class/doleditor.class.php';
7598 $doleditor =
new DolEditor($keyprefix.$key.$keysuffix, $value,
'', 200,
'dolibarr_notes',
'In',
false,
false, isModEnabled(
'fckeditor') &&
getDolGlobalInt(
'FCKEDITOR_ENABLE_SOCIETE'), ROWS_5,
'90%');
7599 $out = (string) $doleditor->Create(1,
'',
true,
'',
'', $moreparam, $morecss);
7601 $out =
'<input type="text" class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.
dol_escape_htmltag($value).
'" '.($moreparam ? $moreparam :
'').
'>';
7603 } elseif ($type ==
'boolean') {
7605 if (!empty($value)) {
7606 $checked =
' checked value="1" ';
7608 $checked =
' value="1" ';
7610 $out =
'<input type="checkbox" class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" '.$checked.
' '.($moreparam ? $moreparam :
'').
'>';
7611 } elseif ($type ==
'price') {
7612 if (!empty($value)) {
7613 $value =
price($value);
7615 $out =
'<input type="text" class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.$value.
'" '.($moreparam ? $moreparam :
'').
'> '.$langs->getCurrencySymbol($conf->currency);
7616 } elseif (preg_match(
'/^double(\([0-9],[0-9]\)){0,1}/', (
string) $type)) {
7617 if (!empty($value)) {
7618 $value =
price($value);
7620 $out =
'<input type="text" class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.$value.
'" '.($moreparam ? $moreparam :
'').
'> ';
7621 } elseif ($type ==
'select') {
7623 if (!empty($conf->use_javascript_ajax) && !
getDolGlobalString(
'MAIN_EXTRAFIELDS_DISABLE_SELECT2')) {
7624 include_once DOL_DOCUMENT_ROOT.
'/core/lib/ajax.lib.php';
7625 $out .=
ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
7630 foreach ($param[
'options'] as $keyb => $valb) {
7631 if ((
string) $keyb ==
'') {
7634 if (strpos($valb,
"|") !==
false) {
7635 list($valb, $parent) = explode(
'|', $valb);
7638 $tmpselect .=
'<option value="'.$keyb.
'"';
7639 $tmpselect .= (((string) $value == (
string) $keyb) ?
' selected' :
'');
7640 if (!empty($parent)) {
7643 $tmpselect .= (!empty($parent) ?
' parent="'.$parent.
'"' :
'');
7644 $tmpselect .=
'>'.$langs->trans($valb).
'</option>';
7647 $out .=
'<select class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" '.($moreparam ? $moreparam :
'').
'>';
7648 if ((!isset($this->fields[$key][
'default'])) || ($this->fields[$key][
'notnull'] != 1) || $nbchoice >= 2) {
7649 $out .=
'<option value="0"> </option>';
7652 $out .=
'</select>';
7653 } elseif ($type ==
'sellist') {
7655 if (!empty($conf->use_javascript_ajax) && !
getDolGlobalString(
'MAIN_EXTRAFIELDS_DISABLE_SELECT2')) {
7656 include_once DOL_DOCUMENT_ROOT.
'/core/lib/ajax.lib.php';
7657 $out .=
ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
7660 $out .=
'<select class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" '.($moreparam ? $moreparam :
'').
'>';
7661 if (is_array($param[
'options'])) {
7662 $tmpparamoptions = array_keys($param[
'options']);
7663 $paramoptions = preg_split(
'/[\r\n]+/', $tmpparamoptions[0]);
7665 $InfoFieldList = explode(
":", $paramoptions[0], 5);
7677 if (! empty($InfoFieldList[4])) {
7679 $parenthesisopen = 0;
7680 while (substr($InfoFieldList[4], $pos, 1) !==
'' && ($parenthesisopen || $pos == 0 || substr($InfoFieldList[4], $pos, 1) !=
':')) {
7681 if (substr($InfoFieldList[4], $pos, 1) ==
'(') {
7684 if (substr($InfoFieldList[4], $pos, 1) ==
')') {
7689 $tmpbefore = substr($InfoFieldList[4], 0, $pos);
7690 $tmpafter = substr($InfoFieldList[4], $pos + 1);
7692 $InfoFieldList[4] = $tmpbefore;
7693 if ($tmpafter !==
'') {
7694 $InfoFieldList = array_merge($InfoFieldList, explode(
':', $tmpafter));
7700 if (preg_match(
'/^\(?([a-z0-9]+)([=<>]+)(\d+)\)?$/i', $InfoFieldList[4], $reg)) {
7701 $InfoFieldList[4] =
'('.$reg[1].
':'.$reg[2].
':'.$reg[3].
')';
7712 $keyList = (empty($InfoFieldList[2]) ?
'rowid' : $InfoFieldList[2].
' as rowid');
7714 if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
7715 if (strpos($InfoFieldList[4],
'extra.') !==
false) {
7716 $keyList =
'main.'.$InfoFieldList[2].
' as rowid';
7718 $keyList = $InfoFieldList[2].
' as rowid';
7721 if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
7722 list($parentName, $parentField) = explode(
'|', $InfoFieldList[3]);
7723 $keyList .=
', '.$parentField;
7726 $filter_categorie =
false;
7727 if (count($InfoFieldList) > 5) {
7728 if ($InfoFieldList[0] ==
'categorie') {
7729 $filter_categorie =
true;
7733 if (!$filter_categorie) {
7734 $fields_label = explode(
'|', $InfoFieldList[1]);
7735 if (is_array($fields_label)) {
7737 $keyList .= implode(
', ', $fields_label);
7741 $sql =
"SELECT " . $keyList;
7742 $sql .=
" FROM " . $this->db->prefix() . $InfoFieldList[0];
7744 if (!empty($InfoFieldList[4])) {
7746 if (strpos($InfoFieldList[4],
'$SEL$') !==
false) {
7747 $InfoFieldList[4] = str_replace(
'$SEL$',
'SELECT', $InfoFieldList[4]);
7751 if (strpos($InfoFieldList[4],
'$ID$') !==
false && !empty($objectid)) {
7752 $InfoFieldList[4] = str_replace(
'$ID$', (
string) $objectid, $InfoFieldList[4]);
7754 $InfoFieldList[4] = str_replace(
'$ID$',
'0', $InfoFieldList[4]);
7759 if (strpos($InfoFieldList[4],
'extra') !==
false) {
7760 $sql .=
" as main, " . $this->db->sanitize($this->db->prefix() . $InfoFieldList[0]) .
"_extrafields as extra";
7761 $sqlwhere .=
" WHERE extra.fk_object = main." . $this->db->sanitize($InfoFieldList[2]);
7767 $sqlwhere .=
' WHERE 1=1';
7784 if (in_array($InfoFieldList[0], array(
'tablewithentity'))) {
7785 $sqlwhere .=
" AND entity = " . ((int) $conf->entity);
7791 if (isset($InfoFieldList[7]) && preg_match(
'/^[a-z0-9_\-,]+$/i', $InfoFieldList[7])) {
7792 $sql .=
" ORDER BY ".$this->db->escape($InfoFieldList[7]);
7794 $sql .=
" ORDER BY ".$this->db->sanitize(implode(
', ', $fields_label));
7797 dol_syslog(get_class($this) .
'::showInputField type=sellist', LOG_DEBUG);
7798 $resql = $this->db->query($sql);
7800 $out .=
'<option value="0"> </option>';
7801 $num = $this->db->num_rows($resql);
7805 $obj = $this->db->fetch_object($resql);
7809 $fields_label = explode(
'|', $InfoFieldList[1]);
7810 if (count($fields_label) > 1) {
7812 foreach ($fields_label as $field_toshow) {
7813 $labeltoshow .= $obj->$field_toshow .
' ';
7816 $labeltoshow = $obj->{$InfoFieldList[1]};
7818 $labeltoshow =
dol_trunc($labeltoshow, 45);
7820 if ($value == $obj->rowid) {
7821 foreach ($fields_label as $field_toshow) {
7822 $translabel = $langs->trans($obj->$field_toshow);
7823 if ($translabel != $obj->$field_toshow) {
7824 $labeltoshow =
dol_trunc($translabel) .
' ';
7826 $labeltoshow =
dol_trunc($obj->$field_toshow) .
' ';
7829 $out .=
'<option value="' . $obj->rowid .
'" selected>' . $labeltoshow .
'</option>';
7832 $translabel = $langs->trans($obj->{$InfoFieldList[1]});
7833 if ($translabel != $obj->{$InfoFieldList[1]}) {
7834 $labeltoshow =
dol_trunc($translabel, 18);
7836 $labeltoshow =
dol_trunc($obj->{$InfoFieldList[1]});
7839 if (empty($labeltoshow)) {
7840 $labeltoshow =
'(not defined)';
7842 if ($value == $obj->rowid) {
7843 $out .=
'<option value="' . $obj->rowid .
'" selected>' . $labeltoshow .
'</option>';
7846 if (!empty($InfoFieldList[3]) && $parentField) {
7847 $parent = $parentName .
':' . $obj->{$parentField};
7851 $out .=
'<option value="' . $obj->rowid .
'"';
7852 $out .= ($value == $obj->rowid ?
' selected' :
'');
7853 $out .= (!empty($parent) ?
' parent="' . $parent .
'"' :
'');
7854 $out .=
'>' . $labeltoshow .
'</option>';
7859 $this->db->free($resql);
7861 print
'Error in request ' . $sql .
' ' . $this->db->lasterror() .
'. Check setup of extra parameters.<br>';
7864 require_once DOL_DOCUMENT_ROOT.
'/categories/class/categorie.class.php';
7865 $data = $form->select_all_categories(Categorie::$MAP_ID_TO_CODE[$InfoFieldList[5]],
'',
'parent', 64, $InfoFieldList[6], 1, 1);
7866 $out .=
'<option value="0"> </option>';
7867 foreach ($data as $data_key => $data_value) {
7868 $out .=
'<option value="' . $data_key .
'"';
7869 $out .= ($value == $data_key ?
' selected' :
'');
7870 $out .=
'>' . $data_value .
'</option>';
7874 $out .=
'</select>';
7875 } elseif ($type ==
'checkbox') {
7876 $value_arr = explode(
',', $value);
7877 $out = $form->multiselectarray($keyprefix.$key.$keysuffix, (empty($param[
'options']) ?
null : $param[
'options']), $value_arr, 0, 0, $morecss, 0,
'100%');
7878 } elseif ($type ==
'radio') {
7880 foreach ($param[
'options'] as $keyopt => $valopt) {
7881 $out .=
'<input class="flat '.$morecss.
'" type="radio" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" '.($moreparam ? $moreparam :
'');
7882 $out .=
' value="'.$keyopt.
'"';
7883 $out .=
' id="'.$keyprefix.$key.$keysuffix.
'_'.$keyopt.
'"';
7884 $out .= ($value == $keyopt ?
'checked' :
'');
7885 $out .=
'/><label for="'.$keyprefix.$key.$keysuffix.
'_'.$keyopt.
'">'.$valopt.
'</label><br>';
7887 } elseif ($type ==
'chkbxlst') {
7888 if (is_array($value)) {
7889 $value_arr = $value;
7891 $value_arr = explode(
',', $value);
7894 if (is_array($param[
'options'])) {
7895 $tmpparamoptions = array_keys($param[
'options']);
7896 $paramoptions = preg_split(
'/[\r\n]+/', $tmpparamoptions[0]);
7898 $InfoFieldList = explode(
":", $paramoptions[0], 5);
7910 if (! empty($InfoFieldList[4])) {
7912 $parenthesisopen = 0;
7913 while (substr($InfoFieldList[4], $pos, 1) !==
'' && ($parenthesisopen || $pos == 0 || substr($InfoFieldList[4], $pos, 1) !=
':')) {
7914 if (substr($InfoFieldList[4], $pos, 1) ==
'(') {
7917 if (substr($InfoFieldList[4], $pos, 1) ==
')') {
7922 $tmpbefore = substr($InfoFieldList[4], 0, $pos);
7923 $tmpafter = substr($InfoFieldList[4], $pos + 1);
7925 $InfoFieldList[4] = $tmpbefore;
7926 if ($tmpafter !==
'') {
7927 $InfoFieldList = array_merge($InfoFieldList, explode(
':', $tmpafter));
7932 if (preg_match(
'/^\(?([a-z0-9]+)([=<>]+)(\d+)\)?$/i', $InfoFieldList[4], $reg)) {
7933 $InfoFieldList[4] =
'('.$reg[1].
':'.$reg[2].
':'.$reg[3].
')';
7941 '@phan-var-force array{0:string,1:string,2:string,3:string,3:string,5:string,6:string} $InfoFieldList';
7946 $keyList = (empty($InfoFieldList[2]) ?
'rowid' : $InfoFieldList[2].
' as rowid');
7948 if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
7949 list($parentName, $parentField) = explode(
'|', $InfoFieldList[3]);
7950 $keyList .=
', '.$parentField;
7952 if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
7953 if (strpos($InfoFieldList[4],
'extra.') !==
false) {
7954 $keyList =
'main.'.$InfoFieldList[2].
' as rowid';
7956 $keyList = $InfoFieldList[2].
' as rowid';
7960 $filter_categorie =
false;
7961 if (count($InfoFieldList) > 5) {
7962 if ($InfoFieldList[0] ==
'categorie') {
7963 $filter_categorie =
true;
7968 if (!$filter_categorie) {
7969 $fields_label = explode(
'|', $InfoFieldList[1]);
7970 if (is_array($fields_label)) {
7972 $keyList .= implode(
', ', $fields_label);
7976 $sql =
"SELECT " . $keyList;
7977 $sql .=
' FROM ' . $this->db->prefix() . $InfoFieldList[0];
7979 if (!empty($InfoFieldList[4])) {
7981 if (strpos($InfoFieldList[4],
'$SEL$') !==
false) {
7982 $InfoFieldList[4] = str_replace(
'$SEL$',
'SELECT', $InfoFieldList[4]);
7986 if (strpos($InfoFieldList[4],
'$ID$') !==
false && !empty($objectid)) {
7987 $InfoFieldList[4] = str_replace(
'$ID$', (
string) $objectid, $InfoFieldList[4]);
7989 $InfoFieldList[4] = str_replace(
'$ID$',
'0', $InfoFieldList[4]);
7994 if (strpos($InfoFieldList[4],
'extra') !==
false) {
7995 $sql .=
' as main, ' . $this->db->sanitize($this->db->prefix() . $InfoFieldList[0]) .
'_extrafields as extra';
7996 $sqlwhere .=
" WHERE extra.fk_object = main." . $this->db->sanitize($InfoFieldList[2]);
7997 $sqlwhere .=
" AND " . $InfoFieldList[4];
7999 $sqlwhere .=
" WHERE " . $InfoFieldList[4];
8002 $sqlwhere .=
' WHERE 1=1';
8019 if (in_array($InfoFieldList[0], array(
'tablewithentity'))) {
8020 $sqlwhere .=
" AND entity = " . ((int) $conf->entity);
8027 dol_syslog(get_class($this) .
'::showInputField type=chkbxlst', LOG_DEBUG);
8029 $resql = $this->db->query($sql);
8031 $num = $this->db->num_rows($resql);
8038 $obj = $this->db->fetch_object($resql);
8042 $fields_label = explode(
'|', $InfoFieldList[1]);
8043 if (count($fields_label) > 1) {
8045 foreach ($fields_label as $field_toshow) {
8046 $labeltoshow .= $obj->$field_toshow .
' ';
8049 $labeltoshow = $obj->{$InfoFieldList[1]};
8051 $labeltoshow =
dol_trunc($labeltoshow, 45);
8053 if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
8054 foreach ($fields_label as $field_toshow) {
8055 $translabel = $langs->trans($obj->$field_toshow);
8056 if ($translabel != $obj->$field_toshow) {
8057 $labeltoshow =
dol_trunc($translabel, 18) .
' ';
8059 $labeltoshow =
dol_trunc($obj->$field_toshow, 18) .
' ';
8063 $data[$obj->rowid] = $labeltoshow;
8066 $translabel = $langs->trans($obj->{$InfoFieldList[1]});
8067 if ($translabel != $obj->{$InfoFieldList[1]}) {
8068 $labeltoshow =
dol_trunc($translabel, 18);
8070 $labeltoshow =
dol_trunc($obj->{$InfoFieldList[1]}, 18);
8073 if (empty($labeltoshow)) {
8074 $labeltoshow =
'(not defined)';
8077 if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
8078 $data[$obj->rowid] = $labeltoshow;
8081 if (!empty($InfoFieldList[3]) && $parentField) {
8082 $parent = $parentName .
':' . $obj->{$parentField};
8086 $data[(int) $obj->rowid] = $labeltoshow;
8091 $this->db->free($resql);
8093 $out = $form->multiselectarray($keyprefix . $key . $keysuffix, $data, $value_arr, 0, 0, $morecss, 0,
'100%');
8095 print
'Error in request ' . $sql .
' ' . $this->db->lasterror() .
'. Check setup of extra parameters.<br>';
8098 require_once DOL_DOCUMENT_ROOT.
'/categories/class/categorie.class.php';
8099 $data = $form->select_all_categories(Categorie::$MAP_ID_TO_CODE[(
int) $InfoFieldList[5]],
'',
'parent', 64, $InfoFieldList[6], 1, 1);
8100 $out = $form->multiselectarray($keyprefix . $key . $keysuffix, $data, $value_arr, 0, 0, $morecss, 0,
'100%');
8103 } elseif ($type ==
'link') {
8106 $param_list = array_keys($param[
'options']);
8107 $param_list_array = explode(
':', $param_list[0], 4);
8109 $showempty = (($required && $default !=
'') ? 0 : 1);
8111 if (!preg_match(
'/search_/', $keyprefix)) {
8112 if (!empty($param_list_array[2])) {
8114 if (!empty($this->fields[$key][
'picto'])) {
8115 $morecss .=
' widthcentpercentminusxx';
8117 $morecss .=
' widthcentpercentminusx';
8121 if (!empty($this->fields[$key][
'picto'])) {
8122 $morecss .=
' widthcentpercentminusx';
8126 $objectfield = $this->element.($this->module ?
'@'.$this->module :
'').
':'.$key.$keysuffix;
8127 $out = $form->selectForForms($param_list_array[0], $keyprefix.$key.$keysuffix, $value, $showempty,
'',
'', $morecss, $moreparam, 0, (empty($val[
'disabled']) ? 0 : 1),
'', $objectfield);
8129 if (!empty($param_list_array[2])) {
8130 if ((!GETPOSTISSET(
'backtopage') || strpos(
GETPOST(
'backtopage'), $_SERVER[
'PHP_SELF']) === 0)
8131 && empty($val[
'disabled']) && empty($nonewbutton)) {
8132 list($class, $classfile) = explode(
':', $param_list[0]);
8133 if (file_exists(
dol_buildpath(dirname(dirname($classfile)).
'/card.php'))) {
8134 $url_path =
dol_buildpath(dirname(dirname($classfile)).
'/card.php', 1);
8136 $url_path =
dol_buildpath(dirname(dirname($classfile)).
'/'.strtolower($class).
'_card.php', 1);
8138 $paramforthenewlink =
'';
8139 $paramforthenewlink .= (GETPOSTISSET(
'action') ?
'&action='.GETPOST(
'action',
'aZ09') :
'');
8140 $paramforthenewlink .= (GETPOSTISSET(
'id') ?
'&id='.GETPOSTINT(
'id') :
'');
8141 $paramforthenewlink .= (GETPOSTISSET(
'origin') ?
'&origin='.GETPOST(
'origin',
'aZ09') :
'');
8142 $paramforthenewlink .= (GETPOSTISSET(
'originid') ?
'&originid='.GETPOSTINT(
'originid') :
'');
8143 $paramforthenewlink .=
'&fk_'.strtolower($class).
'=--IDFORBACKTOPAGE--';
8145 $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>';
8148 } elseif ($type ==
'password') {
8150 if ($keyprefix.$key.$keysuffix ==
'pass_crypted') {
8151 $out =
'<input type="'.($keyprefix ==
'search_' ?
'text' :
'password').
'" class="flat '.$morecss.
'" name="pass" id="pass" value="" '.($moreparam ? $moreparam :
'').
'>';
8152 $out .=
'<input type="hidden" name="pass_crypted" id="pass_crypted" value="'.$value.
'" '.($moreparam ? $moreparam :
'').
'>';
8154 $out =
'<input type="'.($keyprefix ==
'search_' ?
'text' :
'password').
'" class="flat '.$morecss.
'" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.$value.
'" '.($moreparam ? $moreparam :
'').
'>';
8156 } elseif ($type ==
'array') {
8158 $newval[
'type'] =
'varchar(256)';
8161 if (!empty($value)) {
8162 foreach ($value as $option) {
8163 $out .=
'<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).
'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
8164 $out .= $this->showInputField($newval, $keyprefix.$key.$keysuffix.
'[]', $option, $moreparam,
'',
'', $morecss).
'<br></span>';
8167 $out .=
'<a id="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).
'_add" href="javascript:;"><span class="fa fa-plus-circle valignmiddle"></span></a>';
8169 $newInput =
'<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).
'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
8170 $newInput .= $this->showInputField($newval, $keyprefix.$key.$keysuffix.
'[]',
'', $moreparam,
'',
'', $morecss).
'<br></span>';
8172 if (!empty($conf->use_javascript_ajax)) {
8174 <script nonce="'.getNonce().
'">
8175 $(document).ready(function() {
8176 $("a#'.
dol_escape_js($keyprefix.$key.$keysuffix).
'_add").click(function() {
8180 $(document).on("click", "a.'.
dol_escape_js($keyprefix.$key.$keysuffix).
'_del", function() {
8181 $(this).parent().remove();
8187 if (!empty($hidden)) {
8188 $out =
'<input type="hidden" value="'.$value.
'" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'"/>';
8191 if ($isDependList == 1) {
8192 $out .= $this->getJSListDependancies(
'_common');
8200 if (!empty($fieldValidationErrorMsg) && function_exists(
'getFieldErrorIcon')) {
8201 $out .=
' '.getFieldErrorIcon($fieldValidationErrorMsg);
8220 public function showOutputField($val, $key, $value, $moreparam =
'', $keysuffix =
'', $keyprefix =
'', $morecss =
'')
8222 global $conf, $langs, $form;
8224 if (!is_object($form)) {
8225 require_once DOL_DOCUMENT_ROOT.
'/core/class/html.form.class.php';
8226 $form =
new Form($this->db);
8230 $type = empty($val[
'type']) ?
'' : $val[
'type'];
8231 $size = empty($val[
'css']) ?
'' : $val[
'css'];
8235 if (preg_match(
'/varchar\((\d+)\)/', $type, $reg)) {
8238 } elseif (preg_match(
'/varchar/', $type)) {
8241 if (!empty($val[
'arrayofkeyval']) && is_array($val[
'arrayofkeyval'])) {
8243 if (empty($this->fields[$key][
'multiinput'])) {
8244 $type = (($this->fields[$key][
'type'] ==
'checkbox') ? $this->fields[$key][
'type'] :
'select');
8247 if (preg_match(
'/^integer:(.*):(.*)/i', $val[
'type'], $reg)) {
8251 $default = empty($val[
'default']) ?
'' : $val[
'default'];
8252 $computed = empty($val[
'computed']) ?
'' : $val[
'computed'];
8253 $unique = empty($val[
'unique']) ?
'' : $val[
'unique'];
8254 $required = empty($val[
'required']) ?
'' : $val[
'required'];
8256 $param[
'options'] = array();
8258 if (!empty($val[
'arrayofkeyval']) && is_array($val[
'arrayofkeyval'])) {
8259 $param[
'options'] = $val[
'arrayofkeyval'];
8261 if (preg_match(
'/^integer:([^:]*):([^:]*)/i', $val[
'type'], $reg)) {
8263 $stringforoptions = $reg[1].
':'.$reg[2];
8265 if ($reg[1] ==
'User') {
8266 $stringforoptions .=
':#getnomurlparam1=-1';
8268 $param[
'options'] = array($stringforoptions => $stringforoptions);
8269 } elseif (preg_match(
'/^sellist:(.*):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
8270 $param[
'options'] = array($reg[1].
':'.$reg[2].
':'.$reg[3].
':'.$reg[4] =>
'N');
8272 } elseif (preg_match(
'/^sellist:(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
8273 $param[
'options'] = array($reg[1].
':'.$reg[2].
':'.$reg[3] =>
'N');
8275 } elseif (preg_match(
'/^sellist:(.*):(.*)/i', $val[
'type'], $reg)) {
8276 $param[
'options'] = array($reg[1].
':'.$reg[2] =>
'N');
8278 } elseif (preg_match(
'/^chkbxlst:(.*)/i', $val[
'type'], $reg)) {
8279 $param[
'options'] = array($reg[1] =>
'N');
8283 $langfile = empty($val[
'langfile']) ?
'' : $val[
'langfile'];
8284 $list = (empty($val[
'list']) ?
'' : $val[
'list']);
8285 $help = (empty($val[
'help']) ?
'' : $val[
'help']);
8286 $hidden = (($val[
'visible'] == 0) ? 1 : 0);
8296 $value =
dol_eval($computed, 1, 0,
'2');
8299 if (empty($morecss)) {
8300 if ($type ==
'date') {
8301 $morecss =
'minwidth100imp';
8302 } elseif ($type ==
'datetime' || $type ==
'timestamp') {
8303 $morecss =
'minwidth200imp';
8304 } elseif (in_array($type, array(
'int',
'double',
'price'))) {
8305 $morecss =
'maxwidth75';
8306 } elseif ($type ==
'url') {
8307 $morecss =
'minwidth400';
8308 } elseif ($type ==
'boolean') {
8311 if (is_numeric($size) && round((
float) $size) < 12) {
8312 $morecss =
'minwidth100';
8313 } elseif (is_numeric($size) && round((
float) $size) <= 48) {
8314 $morecss =
'minwidth200';
8316 $morecss =
'minwidth400';
8322 if (in_array($key, array(
'rowid',
'ref')) && method_exists($this,
'getNomUrl')) {
8324 if ($key !=
'rowid' || empty($this->fields[
'ref'])) {
8325 $value = $this->getNomUrl(1,
'', 0,
'', 1);
8327 } elseif ($key ==
'status' && method_exists($this,
'getLibStatut')) {
8328 $value = $this->getLibStatut(3);
8329 } elseif ($type ==
'date') {
8330 if (!empty($value)) {
8335 } elseif ($type ==
'datetime' || $type ==
'timestamp') {
8336 if (!empty($value)) {
8341 } elseif ($type ==
'duration') {
8342 include_once DOL_DOCUMENT_ROOT.
'/core/lib/date.lib.php';
8343 if (!is_null($value) && $value !==
'') {
8346 } elseif ($type ==
'double' || $type ==
'real') {
8347 if (!is_null($value) && $value !==
'') {
8348 $value =
price($value);
8350 } elseif ($type ==
'boolean') {
8352 if (!empty($value)) {
8353 $checked =
' checked ';
8356 $value =
'<input type="checkbox" '.$checked.
' '.($moreparam ? $moreparam :
'').
' readonly disabled>';
8358 $value =
yn($value ? 1 : 0);
8360 } elseif ($type ==
'mail' || $type ==
'email') {
8362 } elseif ($type ==
'url') {
8364 } elseif ($type ==
'phone') {
8366 } elseif ($type ==
'ip') {
8368 } elseif ($type ==
'price') {
8369 if (!is_null($value) && $value !==
'') {
8370 $value =
price($value, 0, $langs, 0, 0, -1, $conf->currency);
8372 } elseif ($type ==
'select') {
8373 $value = isset($param[
'options'][(
string) $value]) ? $param[
'options'][(string) $value] :
'';
8374 if (strpos($value,
"|") !==
false) {
8375 $value = $langs->trans(explode(
'|', $value)[0]);
8376 } elseif (! is_numeric($value)) {
8377 $value = $langs->trans($value);
8379 } elseif ($type ==
'sellist') {
8380 $param_list = array_keys($param[
'options']);
8381 $InfoFieldList = explode(
":", $param_list[0]);
8383 $selectkey =
"rowid";
8386 if (count($InfoFieldList) > 2 && !empty($InfoFieldList[2])) {
8387 $selectkey = $InfoFieldList[2];
8388 $keyList = $InfoFieldList[2].
' as rowid';
8391 $fields_label = explode(
'|', $InfoFieldList[1]);
8392 if (is_array($fields_label)) {
8394 $keyList .= implode(
', ', $fields_label);
8397 $filter_categorie =
false;
8398 if (count($InfoFieldList) > 5) {
8399 if ($InfoFieldList[0] ==
'categorie') {
8400 $filter_categorie =
true;
8404 $sql =
"SELECT ".$keyList;
8405 $sql .=
' FROM '.$this->db->prefix().$InfoFieldList[0];
8406 if (isset($InfoFieldList[4]) && strpos($InfoFieldList[4],
'extra') !==
false) {
8409 if ($selectkey ==
'rowid' && empty($value)) {
8410 $sql .=
" WHERE ".$selectkey.
" = 0";
8411 } elseif ($selectkey ==
'rowid') {
8412 $sql .=
" WHERE ".$selectkey.
" = ".((int) $value);
8414 $sql .=
" WHERE ".$selectkey.
" = '".$this->db->escape($value).
"'";
8419 dol_syslog(get_class($this).
':showOutputField:$type=sellist', LOG_DEBUG);
8420 $resql = $this->db->query($sql);
8422 if (!$filter_categorie) {
8424 $numrows = $this->db->num_rows($resql);
8426 $obj = $this->db->fetch_object($resql);
8429 $fields_label = explode(
'|', $InfoFieldList[1]);
8431 if (is_array($fields_label) && count($fields_label) > 1) {
8432 foreach ($fields_label as $field_toshow) {
8434 if (!empty($obj->$field_toshow)) {
8435 $translabel = $langs->trans($obj->$field_toshow);
8437 if ($translabel != $field_toshow) {
8438 $value .=
dol_trunc($translabel, 18) .
' ';
8440 $value .= $obj->$field_toshow .
' ';
8445 if (!empty($obj->{$InfoFieldList[1]})) {
8446 $translabel = $langs->trans($obj->{$InfoFieldList[1]});
8448 if ($translabel != $obj->{$InfoFieldList[1]}) {
8451 $value = $obj->{$InfoFieldList[1]};
8456 require_once DOL_DOCUMENT_ROOT .
'/categories/class/categorie.class.php';
8459 $obj = $this->db->fetch_object($resql);
8461 $c->fetch($obj->rowid);
8462 $ways = $c->print_all_ways();
8463 foreach ($ways as $way) {
8464 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories"' . ($c->color ?
' style="background: #' . $c->color .
';"' :
' style="background: #aaa"') .
'>' .
img_object(
'',
'category') .
' ' . $way .
'</li>';
8466 $value =
'<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(
' ', $toprint).
'</ul></div>';
8469 dol_syslog(get_class($this).
'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
8471 } elseif ($type ==
'radio') {
8472 $value = $param[
'options'][(string) $value];
8473 } elseif ($type ==
'checkbox') {
8474 $value_arr = explode(
',', (
string) $value);
8476 if (is_array($value_arr) && count($value_arr) > 0) {
8478 foreach ($value_arr as $keyval => $valueval) {
8479 if (!empty($valueval)) {
8480 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' . $param[
'options'][$valueval] .
'</li>';
8483 if (!empty($toprint)) {
8484 $value =
'<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">' . implode(
' ', $toprint) .
'</ul></div>';
8487 } elseif ($type ==
'chkbxlst') {
8488 $value_arr = (isset($value) ? explode(
',', $value) : array());
8490 $param_list = array_keys($param[
'options']);
8491 $InfoFieldList = explode(
":", $param_list[0]);
8493 $selectkey =
"rowid";
8496 if (count($InfoFieldList) >= 3) {
8497 $selectkey = $InfoFieldList[2];
8498 $keyList = $InfoFieldList[2].
' as rowid';
8501 $fields_label = explode(
'|', $InfoFieldList[1]);
8502 if (is_array($fields_label)) {
8504 $keyList .= implode(
', ', $fields_label);
8507 $filter_categorie =
false;
8508 if (count($InfoFieldList) > 5) {
8509 if ($InfoFieldList[0] ==
'categorie') {
8510 $filter_categorie =
true;
8514 $sql =
"SELECT ".$keyList;
8515 $sql .=
' FROM '.$this->db->prefix().$InfoFieldList[0];
8516 if (strpos($InfoFieldList[4],
'extra') !==
false) {
8522 dol_syslog(get_class($this).
':showOutputField:$type=chkbxlst', LOG_DEBUG);
8523 $resql = $this->db->query($sql);
8525 if (!$filter_categorie) {
8528 while ($obj = $this->db->fetch_object($resql)) {
8530 $fields_label = explode(
'|', $InfoFieldList[1]);
8531 if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
8532 if (is_array($fields_label) && count($fields_label) > 1) {
8533 foreach ($fields_label as $field_toshow) {
8535 if (!empty($obj->$field_toshow)) {
8536 $translabel = $langs->trans($obj->$field_toshow);
8538 if ($translabel != $field_toshow) {
8539 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' .
dol_trunc($translabel, 18) .
'</li>';
8541 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' . $obj->$field_toshow .
'</li>';
8546 if (!empty($obj->{$InfoFieldList[1]})) {
8547 $translabel = $langs->trans($obj->{$InfoFieldList[1]});
8549 if ($translabel != $obj->{$InfoFieldList[1]}) {
8550 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' .
dol_trunc($translabel, 18) .
'</li>';
8552 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' . $obj->{$InfoFieldList[1]} .
'</li>';
8558 require_once DOL_DOCUMENT_ROOT .
'/categories/class/categorie.class.php';
8561 while ($obj = $this->db->fetch_object($resql)) {
8562 if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
8564 $c->fetch($obj->rowid);
8565 $ways = $c->print_all_ways();
8566 foreach ($ways as $way) {
8567 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories"' . ($c->color ?
' style="background: #' . $c->color .
';"' :
' style="background: #aaa"') .
'>' .
img_object(
'',
'category') .
' ' . $way .
'</li>';
8572 $value =
'<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(
' ', $toprint).
'</ul></div>';
8574 dol_syslog(get_class($this).
'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
8576 } elseif ($type ==
'link') {
8581 $param_list = array_keys($param[
'options']);
8585 $InfoFieldList = explode(
":", $param_list[0]);
8587 $classname = $InfoFieldList[0];
8588 $classpath = $InfoFieldList[1];
8591 $getnomurlparam = 3;
8592 $getnomurlparam2 =
'';
8594 if (preg_match(
'/#getnomurlparam1=([^#]*)/', $param_list[0], $regtmp)) {
8595 $getnomurlparam = $regtmp[1];
8597 if (preg_match(
'/#getnomurlparam2=([^#]*)/', $param_list[0], $regtmp)) {
8598 $getnomurlparam2 = $regtmp[1];
8601 if (!empty($classpath)) {
8604 if ($classname && !class_exists($classname)) {
8608 if ($element_prop) {
8609 $classname = $element_prop[
'classname'];
8614 if ($classname && class_exists($classname)) {
8615 $object =
new $classname($this->db);
8616 '@phan-var-force CommonObject $object';
8617 if (
$object->element ===
'product') {
8618 '@phan-var-force Product $object';
8619 $result =
$object->fetch($value,
'',
'',
'', 0, 1, 1);
8621 $result =
$object->fetch($value);
8624 if (
$object->element ===
'product') {
8625 '@phan-var-force Product $object';
8626 $get_name_url_param_arr = array($getnomurlparam, $getnomurlparam2, 0, -1, 0,
'', 0);
8627 if (isset($val[
'get_name_url_params'])) {
8628 $get_name_url_params = explode(
':', $val[
'get_name_url_params']);
8629 if (!empty($get_name_url_params)) {
8630 $param_num_max = count($get_name_url_param_arr) - 1;
8631 foreach ($get_name_url_params as $param_num => $param_value) {
8632 if ($param_num > $param_num_max) {
8635 $get_name_url_param_arr[$param_num] = $param_value;
8643 $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]);
8645 $value =
$object->getNomUrl($getnomurlparam, $getnomurlparam2);
8652 dol_syslog(
'Error bad setup of extrafield', LOG_WARNING);
8653 return 'Error bad setup of extrafield';
8658 } elseif ($type ==
'password') {
8659 $value =
'<span class="opacitymedium">'.$langs->trans(
"Encrypted").
'</span>';
8661 } elseif ($type ==
'array') {
8662 if (is_array($value)) {
8663 $value = implode(
'<br>', $value);
8665 dol_syslog(__METHOD__.
' Expected array from dol_eval, but got '.gettype($value), LOG_ERR);
8666 return 'Error unexpected result from code evaluation';
8669 if (!empty($value) && preg_match(
'/^text/', (
string) $type) && !preg_match(
'/search_/', $keyprefix) && !empty($param[
'options'])) {
8670 $value = str_replace(
',',
"\n", $value);
8678 return is_null($out) ?
'' : $out;
8690 unset($this->validateFieldsErrors[$fieldKey]);
8704 $msg = $langs->trans(
"UnknownError");
8707 $this->error = $this->validateFieldsErrors[$fieldKey] = $msg;
8718 if (!empty($this->validateFieldsErrors[$fieldKey])) {
8719 return $this->validateFieldsErrors[$fieldKey];
8736 if (!class_exists(
'Validate')) {
8737 require_once DOL_DOCUMENT_ROOT .
'/core/class/validate.class.php';
8740 $this->clearFieldError($fieldKey);
8742 if (!array_key_exists($fieldKey, $fields) || !is_array($fields[$fieldKey])) {
8743 $this->setFieldError($fieldKey, $langs->trans(
'FieldNotFoundInObject'));
8747 $val = $fields[$fieldKey];
8750 $param[
'options'] = array();
8751 $type = $val[
'type'];
8754 if (isset($val[
'notnull']) && $val[
'notnull'] === 1) {
8768 if (preg_match(
'/varchar\((\d+)\)/', $type, $reg)) {
8771 } elseif (preg_match(
'/varchar/', $type)) {
8775 if (!empty($val[
'arrayofkeyval']) && is_array($val[
'arrayofkeyval'])) {
8779 if (!empty($val[
'type']) && preg_match(
'/^integer:(.*):(.*)/i', $val[
'type'], $reg)) {
8783 if (!empty($val[
'arrayofkeyval']) && is_array($val[
'arrayofkeyval'])) {
8784 $param[
'options'] = $val[
'arrayofkeyval'];
8787 if (preg_match(
'/^integer:(.*):(.*)/i', $val[
'type'], $reg)) {
8789 $param[
'options'] = array($reg[1].
':'.$reg[2] => $reg[1].
':'.$reg[2]);
8790 } elseif (preg_match(
'/^sellist:(.*):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
8791 $param[
'options'] = array($reg[1].
':'.$reg[2].
':'.$reg[3].
':'.$reg[4] =>
'N');
8793 } elseif (preg_match(
'/^sellist:(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
8794 $param[
'options'] = array($reg[1].
':'.$reg[2].
':'.$reg[3] =>
'N');
8796 } elseif (preg_match(
'/^sellist:(.*):(.*)/i', $val[
'type'], $reg)) {
8797 $param[
'options'] = array($reg[1].
':'.$reg[2] =>
'N');
8806 $validate =
new Validate($this->db, $langs);
8816 if ($required && !$validate->isNotEmptyString($fieldValue)) {
8817 $this->setFieldError($fieldKey, $validate->error);
8819 } elseif (!$required && !$validate->isNotEmptyString($fieldValue)) {
8825 if (!empty($maxSize) && !$validate->isMaxLength($fieldValue, $maxSize)) {
8826 $this->setFieldError($fieldKey, $validate->error);
8831 if (!empty($minSize) && !$validate->isMinLength($fieldValue, $minSize)) {
8832 $this->setFieldError($fieldKey, $validate->error);
8840 if (in_array($type, array(
'date',
'datetime',
'timestamp'))) {
8841 if (!$validate->isTimestamp($fieldValue)) {
8842 $this->setFieldError($fieldKey, $validate->error);
8847 } elseif ($type ==
'duration') {
8848 if (!$validate->isDuration($fieldValue)) {
8849 $this->setFieldError($fieldKey, $validate->error);
8854 } elseif (in_array($type, array(
'double',
'real',
'price'))) {
8856 if (!$validate->isNumeric($fieldValue)) {
8857 $this->setFieldError($fieldKey, $validate->error);
8862 } elseif ($type ==
'boolean') {
8863 if (!$validate->isBool($fieldValue)) {
8864 $this->setFieldError($fieldKey, $validate->error);
8869 } elseif ($type ==
'mail') {
8870 if (!$validate->isEmail($fieldValue)) {
8871 $this->setFieldError($fieldKey, $validate->error);
8874 } elseif ($type ==
'url') {
8875 if (!$validate->isUrl($fieldValue)) {
8876 $this->setFieldError($fieldKey, $validate->error);
8881 } elseif ($type ==
'phone') {
8882 if (!$validate->isPhone($fieldValue)) {
8883 $this->setFieldError($fieldKey, $validate->error);
8888 } elseif ($type ==
'select' || $type ==
'radio') {
8889 if (!isset($param[
'options'][$fieldValue])) {
8890 $this->error = $langs->trans(
'RequireValidValue');
8895 } elseif ($type ==
'sellist' || $type ==
'chkbxlst') {
8896 $param_list = array_keys($param[
'options']);
8897 $InfoFieldList = explode(
":", $param_list[0]);
8898 $value_arr = explode(
',', $fieldValue);
8899 $value_arr = array_map(array($this->db,
'escape'), $value_arr);
8901 $selectkey =
"rowid";
8902 if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
8903 $selectkey = $InfoFieldList[2];
8906 if (!$validate->isInDb($value_arr, $InfoFieldList[0], $selectkey)) {
8907 $this->setFieldError($fieldKey, $validate->error);
8912 } elseif ($type ==
'link') {
8913 $param_list = array_keys($param[
'options']);
8914 $InfoFieldList = explode(
":", $param_list[0]);
8915 $classname = $InfoFieldList[0];
8916 $classpath = $InfoFieldList[1];
8917 if (!$validate->isFetchable($fieldValue, $classname, $classpath)) {
8918 $lastIsFetchableError = $validate->error;
8921 if ($validate->isFetchableElement($fieldValue, $classname)) {
8925 $this->setFieldError($fieldKey, $lastIsFetchableError);
8949 public function showOptionals($extrafields, $mode =
'view', $params =
null, $keysuffix =
'', $keyprefix =
'', $onetrtd =
'', $display_type =
'card')
8951 global $db, $conf, $langs, $action, $form, $hookmanager;
8953 if (!is_object($form)) {
8954 $form =
new Form($db);
8956 if (!is_object($extrafields)) {
8957 dol_syslog(
'Bad parameter extrafields for showOptionals', LOG_ERR);
8958 return 'Bad parameter extrafields for showOptionals';
8960 if (!is_array($extrafields->attributes[$this->table_element])) {
8961 dol_syslog(
"extrafields->attributes was not loaded with extrafields->fetch_name_optionals_label(table_element);", LOG_WARNING);
8966 $parameters = array(
'mode' => $mode,
'params' => $params,
'keysuffix' => $keysuffix,
'keyprefix' => $keyprefix,
'display_type' => $display_type);
8967 $reshook = $hookmanager->executeHooks(
'showOptionals', $parameters, $this, $action);
8969 if (empty($reshook)) {
8970 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) {
8972 $out .=
'<!-- commonobject:showOptionals --> ';
8975 $nbofextrafieldsshown = 0;
8978 $lastseparatorkeyfound =
'';
8979 $extrafields_collapse_num =
'';
8980 $extrafields_collapse_num_old =
'';
8983 foreach ($extrafields->attributes[$this->table_element][
'label'] as $key => $label) {
8987 if (is_array($params) && array_key_exists(
'onlykey', $params) && $key != $params[
'onlykey']) {
8993 if ($enabled && isset($extrafields->attributes[$this->table_element][
'enabled'][$key])) {
8994 $enabled = (int)
dol_eval((
string) $extrafields->attributes[$this->table_element][
'enabled'][$key], 1, 1,
'2');
8996 if (empty($enabled)) {
9001 if (isset($extrafields->attributes[$this->table_element][
'list'][$key])) {
9002 $visibility = (int)
dol_eval($extrafields->attributes[$this->table_element][
'list'][$key], 1, 1,
'2');
9006 if ($perms && isset($extrafields->attributes[$this->table_element][
'perms'][$key])) {
9007 $perms = (int)
dol_eval($extrafields->attributes[$this->table_element][
'perms'][$key], 1, 1,
'2');
9010 if (($mode ==
'create') && !in_array(abs($visibility), array(1, 3))) {
9012 } elseif (($mode ==
'edit') && !in_array(abs($visibility), array(1, 3, 4))) {
9014 } elseif ($mode ==
'view' && empty($visibility)) {
9017 if (empty($perms)) {
9022 if (!empty($extrafields->attributes[$this->table_element][
'langfile'][$key])) {
9023 $langs->load($extrafields->attributes[$this->table_element][
'langfile'][$key]);
9028 if (is_array($params) && count($params) > 0 && $display_type ==
'card') {
9029 if (array_key_exists(
'cols', $params)) {
9030 $colspan = $params[
'cols'];
9031 } elseif (array_key_exists(
'colspan', $params)) {
9033 if (preg_match(
'/colspan="(\d+)"/', $params[
'colspan'], $reg)) {
9036 $colspan = $params[
'colspan'];
9040 $colspan = intval($colspan);
9044 $value = ((!empty($this->array_options) && array_key_exists(
"options_".$key.$keysuffix, $this->array_options)) ? $this->array_options[
"options_".$key.$keysuffix] :
null);
9050 $check =
'alphanohtml';
9051 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'html',
'text'))) {
9052 $check =
'restricthtml';
9054 $getposttemp =
GETPOST($keyprefix.
'options_'.$key.$keysuffix, $check, 3);
9056 if (is_array($getposttemp) || $getposttemp !=
'' || GETPOSTISSET($keyprefix.
'options_'.$key.$keysuffix)) {
9057 if (is_array($getposttemp)) {
9059 $value = implode(
",", $getposttemp);
9061 $value = $getposttemp;
9063 } elseif (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'int'))) {
9064 $value = (!empty($this->array_options[
"options_".$key]) || (isset($this->array_options[
"options_".$key]) && $this->array_options[
"options_".$key] ===
'0')) ? $this->array_options[
"options_".$key] :
'';
9066 $value = (!empty($this->array_options[
"options_".$key]) ? $this->array_options[
"options_".$key] :
'');
9072 $nbofextrafieldsshown++;
9075 if ($extrafields->attributes[$this->table_element][
'type'][$key] ==
'separate') {
9076 $extrafields_collapse_num = $key;
9094 $out .= $extrafields->showSeparator($key, $this, ($colspan ? $colspan + 1 : 2), $display_type, $mode);
9096 $lastseparatorkeyfound = $key;
9098 $collapse_group = $extrafields_collapse_num.(!empty($this->
id) ?
'_'.$this->id :
'');
9100 $class = (!empty($extrafields->attributes[$this->table_element][
'hidden'][$key]) ?
'hideobject ' :
'');
9102 if (is_array($params) && count($params) > 0) {
9103 if (array_key_exists(
'class', $params)) {
9104 $class .= $params[
'class'].
' ';
9106 if (array_key_exists(
'style', $params)) {
9107 $csstyle = $params[
'style'];
9112 $domData =
' data-element="extrafield"';
9113 $domData .=
' data-targetelement="'.$this->element.
'"';
9114 $domData .=
' data-targetid="'.$this->id.
'"';
9116 $html_id = (empty($this->
id) ?
'' :
'extrarow-'.$this->element.
'_'.$key.
'_'.
$this->id);
9117 if ($display_type ==
'card') {
9122 if ($action ==
'selectlines') {
9128 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'date'))) {
9129 $datenotinstring =
null;
9130 if (array_key_exists(
'options_'.$key, $this->array_options)) {
9131 $datenotinstring = $this->array_options[
'options_'.$key];
9132 if (!is_numeric($this->array_options[
'options_'.$key])) {
9133 $datenotinstring = $this->db->jdate($datenotinstring);
9136 $datekey = $keyprefix.
'options_'.$key.$keysuffix;
9139 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'datetime'))) {
9140 $datenotinstring =
null;
9141 if (array_key_exists(
'options_'.$key, $this->array_options)) {
9142 $datenotinstring = $this->array_options[
'options_'.$key];
9143 if (!is_numeric($this->array_options[
'options_'.$key])) {
9144 $datenotinstring = $this->db->jdate($datenotinstring);
9147 $timekey = $keyprefix.
'options_'.$key.$keysuffix;
9148 $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;
9151 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'price',
'double'))) {
9152 if (GETPOSTISSET($keyprefix.
'options_'.$key.$keysuffix) || $value) {
9154 } elseif (isset($this->array_options[
'options_'.$key])) {
9155 $value = $this->array_options[
'options_'.$key];
9160 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'html',
'text',
'varchar',
'select',
'radio',
'int',
'boolean'))) {
9161 if ($action ==
'create' || $mode ==
'create') {
9162 $value = (GETPOSTISSET($keyprefix.
'options_'.$key.$keysuffix) || $value) ? $value : $extrafields->attributes[$this->table_element][
'default'][$key];
9166 $labeltoshow = $langs->trans($label);
9167 $helptoshow = $langs->trans($extrafields->attributes[$this->table_element][
'help'][$key]);
9168 if ($display_type ==
'card') {
9169 $out .=
'<tr '.($html_id ?
'id="'.$html_id.
'" ' :
'').$csstyle.
' class="field_options_'.$key.
' '.$class.$this->element.
'_extras_'.$key.
' trextrafields_collapse'.$collapse_group.
'" '.$domData.
' >';
9170 if (
getDolGlobalString(
'MAIN_VIEW_LINE_NUMBER') && ($action ==
'view' || $action ==
'valid' || $action ==
'editline' || $action ==
'confirm_valid' || $action ==
'confirm_cancel')) {
9171 $out .=
'<td></td>';
9173 $out .=
'<td class="'.(empty($params[
'tdclass']) ?
'titlefieldmax45' : $params[
'tdclass']).
' wordbreak';
9174 if ($extrafields->attributes[$this->table_element][
'type'][$key] ==
'text') {
9177 } elseif ($display_type ==
'line') {
9178 $out .=
'<div '.($html_id ?
'id="'.$html_id.
'" ' :
'').$csstyle.
' class="fieldline_options_'.$key.
' '.$class.$this->element.
'_extras_'.$key.
' trextrafields_collapse'.$collapse_group.
'" '.$domData.
' >';
9179 $out .=
'<div style="display: inline-block; padding-right:4px" class="wordbreak';
9184 $tpl_context = isset($params[
"tpl_context"]) ? $params[
"tpl_context"] :
"none";
9185 if ($tpl_context !=
"public") {
9186 if ($mode !=
'view' && !empty($extrafields->attributes[$this->table_element][
'required'][$key])) {
9187 $out .=
' fieldrequired';
9191 if ($tpl_context ==
"public") {
9192 if (!empty($extrafields->attributes[$this->table_element][
'help'][$key])) {
9193 $out .= $form->textwithpicto($labeltoshow, $helptoshow);
9195 $out .= $labeltoshow;
9197 if ($mode !=
'view' && !empty($extrafields->attributes[$this->table_element][
'required'][$key])) {
9198 $out .=
' <span style="color: red">*</span>';
9201 if (!empty($extrafields->attributes[$this->table_element][
'help'][$key])) {
9202 $out .= $form->textwithpicto($labeltoshow, $helptoshow);
9204 $out .= $labeltoshow;
9208 $out .= ($display_type ==
'card' ?
'</td>' :
'</div>');
9211 $html_id = !empty($this->
id) ? $this->element.
'_extras_'.$key.
'_'.$this->id :
'';
9212 if ($display_type ==
'card') {
9214 $out .=
'<td '.($html_id ?
'id="'.$html_id.
'" ' :
'').
' class="valuefieldcreate '.$this->element.
'_extras_'.$key;
9215 $out .=
'" '.($colspan ?
' colspan="'.$colspan.
'"' :
'');
9217 } elseif ($display_type ==
'line') {
9218 $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].
'">';
9223 $out .= $extrafields->showOutputField($key, $value,
'', $this->table_element);
9226 $listoftypestoshowpicto = explode(
',',
getDolGlobalString(
'MAIN_TYPES_TO_SHOW_PICOT',
'email,phone,ip,password'));
9227 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], $listoftypestoshowpicto)) {
9228 $out .=
getPictoForType($extrafields->attributes[$this->table_element][
'type'][$key], ($extrafields->attributes[$this->table_element][
'type'][$key] ==
'text' ?
'tdtop' :
''));
9231 $out .= $extrafields->showInputField($key, $value,
'', $keysuffix,
'', 0, $this->
id, $this->table_element);
9234 $listoftypestoshowpicto = explode(
',',
getDolGlobalString(
'MAIN_TYPES_TO_SHOW_PICOT',
'email,phone,ip,password'));
9235 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], $listoftypestoshowpicto)) {
9236 $out .=
getPictoForType($extrafields->attributes[$this->table_element][
'type'][$key], ($extrafields->attributes[$this->table_element][
'type'][$key] ==
'text' ?
'tdtop' :
''));
9238 $out .= $extrafields->showInputField($key, $value,
'', $keysuffix,
'', 0, $this->
id, $this->table_element);
9242 $out .= ($display_type ==
'card' ?
'</td>' :
'</div>');
9243 $out .= ($display_type ==
'card' ?
'</tr>'.
"\n" :
'</div>');
9249 if (!empty($conf->use_javascript_ajax)) {
9250 $out .= $this->getJSListDependancies();
9253 $out .=
'<!-- commonobject:showOptionals end --> '.
"\n";
9255 if (empty($nbofextrafieldsshown)) {
9261 $out .= $hookmanager->resPrint;
9273 <script nonce="'.getNonce().
'">
9274 jQuery(document).ready(function() {
9275 function showOptions'.$type.
'(child_list, parent_list, orig_select)
9277 var val = $("select[name=\""+parent_list+"\"]").val();
9278 var parentVal = parent_list + ":" + val;
9279 if(typeof val == "string"){
9281 var options = orig_select.find("option[parent=\""+parentVal+"\"]").clone();
9282 $("select[name=\""+child_list+"\"] option[parent]").remove();
9283 $("select[name=\""+child_list+"\"]").append(options);
9285 var options = orig_select.find("option[parent]").clone();
9286 $("select[name=\""+child_list+"\"] option[parent]").remove();
9287 $("select[name=\""+child_list+"\"]").append(options);
9289 } else if(val > 0) {
9290 var options = orig_select.find("option[parent=\""+parentVal+"\"]").clone();
9291 $("select[name=\""+child_list+"\"] option[parent]").remove();
9292 $("select[name=\""+child_list+"\"]").append(options);
9294 var options = orig_select.find("option[parent]").clone();
9295 $("select[name=\""+child_list+"\"] option[parent]").remove();
9296 $("select[name=\""+child_list+"\"]").append(options);
9299 function setListDependencies'.$type.
'() {
9300 jQuery("select option[parent]").parent().each(function() {
9301 var orig_select = {};
9302 var child_list = $(this).attr("name");
9303 orig_select[child_list] = $(this).clone();
9304 var parent = $(this).find("option[parent]:first").attr("parent");
9305 var infos = parent.split(":");
9306 var parent_list = infos[0];
9308 //Hide daughters lists
9309 if ($("#"+child_list).val() == 0 && $("#"+parent_list).val() == 0){
9310 $("#"+child_list).hide();
9312 } else if ($("#"+parent_list).val() != 0){
9313 $("#"+parent_list).show();
9315 //Show the child list if the parent list value is selected
9316 $("select[name=\""+parent_list+"\"]").click(function() {
9317 if ($(this).val() != 0){
9318 $("#"+child_list).show()
9322 //When we change parent list
9323 $("select[name=\""+parent_list+"\"]").change(function() {
9324 showOptions'.$type.
'(child_list, parent_list, orig_select[child_list]);
9325 //Select the value 0 on child list after a change on the parent list
9326 $("#"+child_list).val(0).trigger("change");
9327 //Hide child lists if the parent value is set to 0
9328 if ($(this).val() == 0){
9329 $("#"+child_list).hide();
9335 setListDependencies'.$type.
'();
9350 $module = empty($this->module) ?
'' : $this->module;
9351 $element = $this->element;
9353 if ($element ==
'facturerec') {
9354 $element =
'facture';
9355 } elseif ($element ==
'invoice_supplier_rec') {
9356 return !$user->hasRight(
'fournisseur',
'facture') ? null : $user->hasRight(
'fournisseur',
'facture');
9357 } elseif ($module && $user->hasRight($module, $element)) {
9359 return $user->hasRight($module, $element);
9362 return $user->rights->$element;
9379 global $hookmanager;
9381 $parameters = array(
9382 'origin_id' => $origin_id,
9383 'dest_id' => $dest_id,
9384 'tables' => $tables,
9386 $reshook = $hookmanager->executeHooks(
'commonReplaceThirdparty', $parameters);
9389 } elseif ($reshook < 0) {
9390 return $ignoreerrors === 1;
9393 foreach ($tables as $table) {
9394 $sql =
'UPDATE '.$dbs->prefix().$table.
' SET fk_soc = '.((int) $dest_id).
' WHERE fk_soc = '.((int) $origin_id);
9396 if (!$dbs->
query($sql)) {
9397 if ($ignoreerrors) {
9422 foreach ($tables as $table) {
9423 $sql =
'UPDATE '.MAIN_DB_PREFIX.$table.
' SET fk_product = '.((int) $dest_id).
' WHERE fk_product = '.((int) $origin_id);
9425 if (!$dbs->
query($sql)) {
9426 if ($ignoreerrors) {
9449 public function defineBuyPrice($unitPrice = 0.0, $discountPercent = 0.0, $fk_product = 0)
9455 if (($unitPrice > 0) && (isset($conf->global->ForceBuyingPriceIfNull) &&
getDolGlobalInt(
'ForceBuyingPriceIfNull') > 0)) {
9457 $buyPrice = $unitPrice * (1 - $discountPercent / 100);
9460 if (!empty($fk_product) && $fk_product > 0) {
9463 require_once DOL_DOCUMENT_ROOT.
'/product/class/product.class.php';
9464 $product =
new Product($this->db);
9465 $result = $product->fetch($fk_product);
9467 $this->errors[] =
'ErrorProductIdDoesNotExists';
9470 if ($product->cost_price > 0) {
9471 $buyPrice = $product->cost_price;
9472 } elseif ($product->pmp > 0) {
9473 $buyPrice = $product->pmp;
9476 require_once DOL_DOCUMENT_ROOT.
'/product/class/product.class.php';
9477 $product =
new Product($this->db);
9478 $result = $product->fetch($fk_product);
9480 $this->errors[] =
'ErrorProductIdDoesNotExists';
9483 if ($product->pmp > 0) {
9484 $buyPrice = $product->pmp;
9488 if (empty($buyPrice) && isset($conf->global->MARGIN_TYPE) && in_array($conf->global->MARGIN_TYPE, array(
'1',
'pmp',
'costprice'))) {
9489 require_once DOL_DOCUMENT_ROOT.
'/fourn/class/fournisseur.product.class.php';
9491 if (($result = $productFournisseur->find_min_price_product_fournisseur($fk_product)) > 0) {
9492 $buyPrice = $productFournisseur->fourn_unitprice;
9493 } elseif ($result < 0) {
9494 $this->errors[] = $productFournisseur->error;
9513 return array(
'dir' =>
'',
'file' =>
'',
'originalfile' =>
'',
'altfile' =>
'',
'email' =>
'',
'capture' =>
'');
9537 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')
9540 global $user, $langs;
9542 include_once DOL_DOCUMENT_ROOT.
'/core/lib/files.lib.php';
9543 include_once DOL_DOCUMENT_ROOT.
'/core/lib/images.lib.php';
9545 $sortfield =
'position_name';
9551 $dir .=
get_exdir(0, 0, 0, 0, $this, $modulepart);
9552 $pdir .=
get_exdir(0, 0, 0, 0, $this, $modulepart);
9555 if ($modulepart ==
'product') {
9557 $dir = $sdir.
'/'.
get_exdir($this->
id, 2, 0, 0, $this, $modulepart).$this->id.
"/photos/";
9558 $pdir =
'/'.get_exdir($this->
id, 2, 0, 0, $this, $modulepart).$this->id.
"/photos/";
9561 if ($modulepart ==
'category') {
9562 $dir = $sdir.
'/'.
get_exdir($this->
id, 2, 0, 0, $this, $modulepart).$this->id.
"/photos/";
9563 $pdir =
'/'.get_exdir($this->
id, 2, 0, 0, $this, $modulepart).$this->id.
"/photos/";
9569 $relativedir = preg_replace(
'/^'.preg_quote(DOL_DATA_ROOT,
'/').
'/',
'', $dir);
9570 $relativedir = preg_replace(
'/^[\\/]/',
'', $relativedir);
9571 $relativedir = preg_replace(
'/[\\/]$/',
'', $relativedir);
9574 $dirthumb = $dir.
'thumbs/';
9575 $pdirthumb = $pdir.
'thumbs/';
9577 $return =
'<!-- Photo -->'.
"\n";
9580 $filearray =
dol_dir_list($dir,
"files", 0,
'',
'(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) ==
'desc' ? SORT_DESC : SORT_ASC), 1);
9590 if (count($filearray)) {
9591 if ($sortfield && $sortorder) {
9595 foreach ($filearray as $key => $val) {
9597 $file = $val[
'name'];
9603 $viewfilename = $file;
9605 if ($size == 1 || $size ==
'small') {
9612 $photo_vignette = basename($file);
9619 if ($nbphoto == 1) {
9620 $return .=
'<table class="valigntop center centpercent" style="border: 0; padding: 2px; border-spacing: 2px; border-collapse: separate;">';
9623 if ($nbphoto % $nbbyrow == 1) {
9624 $return .=
'<tr class="center valignmiddle" style="border: 1px">';
9626 $return .=
'<td style="width: '.ceil(100 / $nbbyrow).
'%" class="photo">'.
"\n";
9627 } elseif ($nbbyrow < 0) {
9628 $return .=
'<div class="inline-block">'.
"\n";
9631 $relativefile = preg_replace(
'/^\//',
'', $pdir.$photo);
9632 if (empty($nolink)) {
9635 $return .=
'<a href="'.$urladvanced.
'">';
9637 $return .=
'<a href="'.DOL_URL_ROOT.
'/viewimage.php?modulepart='.$modulepart.
'&entity='.$this->entity.
'&file='.urlencode($pdir.$photo).
'" class="aphoto" target="_blank" rel="noopener noreferrer">';
9643 $alt = $langs->transnoentitiesnoconv(
'File').
': '.$relativefile;
9644 $alt .=
' - '.$langs->transnoentitiesnoconv(
'Size').
': '.$imgarray[
'width'].
'x'.$imgarray[
'height'];
9645 if ($overwritetitle) {
9646 if (is_numeric($overwritetitle)) {
9649 $alt = $overwritetitle;
9652 if (empty($cache) && !empty($val[
'label'])) {
9655 $cache = $val[
'label'];
9657 if ($usesharelink) {
9658 if (array_key_exists(
'share', $val) && $val[
'share']) {
9659 if (empty($maxHeight) || ($photo_vignette && $imgarray[
'height'] > $maxHeight)) {
9660 $return .=
'<!-- Show original file (thumb not yet available with shared links) -->';
9661 $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).
'">';
9663 $return .=
'<!-- Show original file -->';
9664 $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).
'">';
9667 $return .=
'<!-- Show nophoto file (because file is not shared) -->';
9668 $return .=
'<img class="photo photowithmargin'.($addphotorefcss ?
' '.$addphotorefcss :
'').
'" height="'.$maxHeight.
'" src="'.DOL_URL_ROOT.
'/public/theme/common/nophoto.png" title="'.
dol_escape_htmltag($alt).
'">';
9671 if (empty($maxHeight) || ($photo_vignette && $imgarray[
'height'] > $maxHeight)) {
9672 $return .=
'<!-- Show thumb -->';
9673 $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).
'">';
9675 $return .=
'<!-- Show original file -->';
9676 $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).
'">';
9680 if (empty($nolink)) {
9684 if ($showfilename) {
9685 $return .=
'<br>'.$viewfilename;
9690 if ($photo_vignette && (
image_format_supported($photo) > 0) && ((isset($imgarray[
'width']) && $imgarray[
'width'] > $maxWidth) || (isset($imgarray[
'width']) && $imgarray[
'width'] > $maxHeight))) {
9691 $return .=
'<a href="'.$_SERVER[
"PHP_SELF"].
'?id='.$this->
id.
'&action=addthumb&token='.
newToken().
'&file='.urlencode($pdir.$viewfilename).
'">'.
img_picto($langs->trans(
'GenerateThumb'),
'refresh').
' </a>';
9694 if ($modulepart ==
'product' && ($user->hasRight(
'produit',
'creer') || $user->hasRight(
'service',
'creer'))) {
9696 $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> ';
9699 $return .=
'<a href="'.$_SERVER[
"PHP_SELF"].
'?id='.$this->
id.
'&action=delete&token='.
newToken().
'&file='.urlencode($pdir.$viewfilename).
'">';
9707 if (($nbphoto % $nbbyrow) == 0) {
9710 } elseif ($nbbyrow < 0) {
9711 $return .=
'</div>'.
"\n";
9716 $return .=
'<img class="photo photowithmargin" src="'.DOL_URL_ROOT.
'/viewimage.php?modulepart='.$modulepart.
'&entity='.$this->entity.
'&file='.urlencode($pdir.$photo).
'">';
9718 if ($showfilename) {
9719 $return .=
'<br>'.$viewfilename;
9723 if ($modulepart ==
'product' && ($user->hasRight(
'produit',
'creer') || $user->hasRight(
'service',
'creer'))) {
9725 $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> ';
9728 $return .=
'<a href="'.$_SERVER[
"PHP_SELF"].
'?id='.$this->
id.
'&action=delete&token='.
newToken().
'&file='.urlencode($pdir.$viewfilename).
'">';
9735 if ($nbmax && $nbphoto >= $nbmax) {
9741 if ($size == 1 || $size ==
'small') {
9744 while ($nbphoto % $nbbyrow) {
9745 $return .=
'<td style="width: '.ceil(100 / $nbbyrow).
'%"> </td>';
9750 $return .=
'</table>';
9756 $this->nbphoto = $nbphoto;
9770 if (is_array($info)) {
9771 if (isset($info[
'type']) && $info[
'type'] ==
'array') {
9788 if (isset($info[
'type']) && ($info[
'type'] ==
'date' || $info[
'type'] ==
'datetime' || $info[
'type'] ==
'timestamp')) {
9802 if (is_array($info)) {
9803 if (isset($info[
'type']) && ($info[
'type'] ==
'duration')) {
9821 if (is_array($info)) {
9822 if (isset($info[
'type']) && (preg_match(
'/(^int|int$)/i', $info[
'type']))) {
9840 if (is_array($info)) {
9841 if (isset($info[
'type']) && (preg_match(
'/^(double|real|price)/i', $info[
'type']))) {
9858 if (is_array($info)) {
9859 if (isset($info[
'type']) && $info[
'type'] ==
'text') {
9876 if (is_array($info)) {
9877 if (array_key_exists(
'notnull', $info) && $info[
'notnull'] !=
'1') {
9894 if (is_array($info)) {
9895 if (array_key_exists(
'notnull', $info) && $info[
'notnull'] ==
'-1') {
9912 if (is_array($info)) {
9913 if (array_key_exists(
'index', $info) && $info[
'index'] ==
true) {
9935 $queryarray = array();
9936 foreach ($this->fields as $field => $info) {
9938 if ($this->isDate($info)) {
9939 if (empty($this->{$field})) {
9940 $queryarray[$field] =
null;
9942 $queryarray[$field] = $this->db->idate($this->{$field});
9944 } elseif ($this->isDuration($info)) {
9946 if ((isset($this->{$field}) && $this->{$field} !=
'') || !empty($info[
'notnull'])) {
9947 if (!isset($this->{$field})) {
9948 if (!empty($info[
'default'])) {
9949 $queryarray[$field] = $info[
'default'];
9951 $queryarray[$field] = 0;
9954 $queryarray[$field] = (int) $this->{$field};
9957 $queryarray[$field] =
null;
9959 } elseif ($this->isInt($info) || $this->isFloat($info)) {
9960 if ($field ==
'entity' && is_null($this->{$field})) {
9961 $queryarray[$field] = ((int) $conf->entity);
9964 if ((isset($this->{$field}) && ((
string) $this->{$field}) !=
'') || !empty($info[
'notnull'])) {
9965 if (!isset($this->{$field})) {
9966 $queryarray[$field] = 0;
9967 } elseif ($this->isInt($info)) {
9968 $queryarray[$field] = (int) $this->{$field};
9969 } elseif ($this->isFloat($info)) {
9970 $queryarray[$field] = (float) $this->{$field};
9973 $queryarray[$field] =
null;
9979 $queryarray[$field] = $this->{$field};
9982 if (array_key_exists(
'type', $info) && $info[
'type'] ==
'timestamp' && empty($queryarray[$field])) {
9983 unset($queryarray[$field]);
9985 if (!empty($info[
'notnull']) && $info[
'notnull'] == -1 && empty($queryarray[$field])) {
9986 $queryarray[$field] =
null;
10003 foreach ($this->fields as $field => $info) {
10004 if ($this->isDate($info)) {
10005 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') {
10006 $this->$field =
'';
10008 $this->$field = $db->jdate($obj->$field);
10010 } elseif ($this->isInt($info)) {
10011 if ($field ==
'rowid') {
10012 $this->
id = (int) $obj->$field;
10014 if ($this->isForcedToNullIfZero($info)) {
10015 if (empty($obj->$field)) {
10016 $this->$field =
null;
10018 $this->$field = (int) $obj->$field;
10021 if (isset($obj->$field) && (!is_null($obj->$field) || (array_key_exists(
'notnull', $info) && $info[
'notnull'] == 1))) {
10022 $this->$field = (int) $obj->$field;
10024 $this->$field =
null;
10028 } elseif ($this->isFloat($info)) {
10029 if ($this->isForcedToNullIfZero($info)) {
10030 if (empty($obj->$field)) {
10031 $this->$field =
null;
10033 $this->$field = (float) $obj->$field;
10036 if (isset($obj->$field) && (!is_null($obj->$field) || (array_key_exists(
'notnull', $info) && $info[
'notnull'] == 1))) {
10037 $this->$field = (float) $obj->$field;
10039 $this->$field =
null;
10043 $this->$field = isset($obj->$field) ? $obj->$field :
null;
10048 if (!isset($this->fields[
'ref']) && isset($this->
id)) {
10049 $this->
ref = (string) $this->
id;
10059 foreach ($this->fields as $field => $arr) {
10060 $this->$field =
null;
10073 $keys = array_keys($this->fields);
10074 if (!empty($alias)) {
10075 $keys_with_alias = array();
10076 foreach ($keys as $fieldname) {
10077 if (!empty($excludefields)) {
10078 if (in_array($fieldname, $excludefields)) {
10082 $keys_with_alias[] = $alias .
'.' . $fieldname;
10084 return implode(
',', $keys_with_alias);
10086 return implode(
',', $keys);
10097 protected function quote($value, $fieldsentry)
10099 if (is_null($value)) {
10101 } elseif (preg_match(
'/^(int|double|real|price)/i', $fieldsentry[
'type'])) {
10103 } elseif (preg_match(
'/int$/i', $fieldsentry[
'type'])) {
10104 return (
int) $value;
10105 } elseif ($fieldsentry[
'type'] ==
'boolean') {
10112 return "'".$this->db->escape($value).
"'";
10128 dol_syslog(get_class($this).
"::createCommon create", LOG_DEBUG);
10134 $fieldvalues = $this->setSaveQuery();
10138 if (array_key_exists(
'date_creation', $fieldvalues) && empty($fieldvalues[
'date_creation'])) {
10139 $fieldvalues[
'date_creation'] = $this->db->idate($now);
10141 if (array_key_exists(
'fk_user_creat', $fieldvalues) && !($fieldvalues[
'fk_user_creat'] > 0)) {
10142 $fieldvalues[
'fk_user_creat'] = $user->id;
10143 $this->fk_user_creat = $user->id;
10145 if (array_key_exists(
'user_creation_id', $fieldvalues) && !($fieldvalues[
'user_creation_id'] > 0)) {
10146 $fieldvalues[
'user_creation_id'] = $user->id;
10147 $this->user_creation_id = $user->id;
10149 if (array_key_exists(
'pass_crypted', $fieldvalues) && property_exists($this,
'pass')) {
10151 $fieldvalues[
'pass_crypted'] =
dol_hash($this->pass);
10153 if (array_key_exists(
'ref', $fieldvalues)) {
10157 unset($fieldvalues[
'rowid']);
10161 foreach ($fieldvalues as $k => $v) {
10163 $value = $this->fields[$k];
10165 $values[$k] = $this->quote($v, $value);
10169 foreach ($keys as $key) {
10170 if (!isset($this->fields[$key])) {
10173 $key_fields = $this->fields[$key];
10176 if (preg_match(
'/^integer:/i', $key_fields[
'type']) && $values[$key] ==
'-1') {
10177 $values[$key] =
'';
10179 if (!empty($key_fields[
'foreignkey']) && $values[$key] ==
'-1') {
10180 $values[$key] =
'';
10183 if (isset($key_fields[
'notnull']) && $key_fields[
'notnull'] == 1 && (!isset($values[$key]) || $values[$key] ===
'NULL') && (!isset($key_fields[
'default']) || is_null($key_fields[
'default']))) {
10185 $langs->load(
"errors");
10186 dol_syslog(
"Mandatory field '".$key.
"' is empty and required into ->fields definition of class");
10187 $this->errors[] = $langs->trans(
"ErrorFieldRequired", isset($key_fields[
'label']) ? $key_fields[
'label'] : $key);
10191 if (isset($key_fields[
'notnull']) && $key_fields[
'notnull'] == 1 && (!isset($values[$key]) || $values[$key] ===
'NULL') && !is_null($key_fields[
'default'])) {
10192 $values[$key] = $this->quote($key_fields[
'default'], $key_fields);
10196 if (isset($key_fields[
'type']) && preg_match(
'/^integer:/i', $key_fields[
'type']) && empty($values[$key])) {
10197 if (isset($key_fields[
'default'])) {
10198 $values[$key] = ((int) $key_fields[
'default']);
10200 $values[$key] =
'null';
10203 if (!empty($key_fields[
'foreignkey']) && empty($values[$key])) {
10204 $values[$key] =
'null';
10212 $this->db->begin();
10215 $sql =
"INSERT INTO ".$this->db->prefix().$this->table_element;
10216 $sql .=
" (".implode(
", ", $keys).
')';
10217 $sql .=
" VALUES (".implode(
", ", $values).
")";
10219 $res = $this->db->query($sql);
10222 if ($this->db->lasterrno() ==
'DB_ERROR_RECORD_ALREADY_EXISTS') {
10223 $this->errors[] =
"ErrorRefAlreadyExists";
10225 $this->errors[] = $this->db->lasterror();
10231 $this->
id = $this->db->last_insert_id($this->db->prefix().$this->table_element);
10237 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)') {
10238 $sql =
"UPDATE ".$this->db->prefix().$this->table_element.
" SET ref = '(PROV".((int) $this->
id).
")' WHERE (ref = '(PROV)' OR ref = '') AND rowid = ".((int) $this->
id);
10239 $resqlupdate = $this->db->query($sql);
10241 if ($resqlupdate ===
false) {
10243 $this->errors[] = $this->db->lasterror();
10245 $this->
ref =
'(PROV'.$this->id.
')';
10252 $result = $this->insertExtraFields();
10259 if (!empty($this->table_element_line) && !empty($this->fk_element)) {
10260 foreach ($this->lines as $line) {
10261 $keyforparent = $this->fk_element;
10266 if (!is_object($line)) {
10267 $line = (object) $line;
10271 if (method_exists($line,
'insert')) {
10272 $result = $line->insert($user, 1);
10273 } elseif (method_exists($line,
'create')) {
10274 $result = $line->create($user, 1);
10277 $this->error = $line->error;
10278 $this->db->rollback();
10285 if (!$error && !$notrigger) {
10287 $result = $this->call_trigger(strtoupper(get_class($this)).
'_CREATE', $user);
10296 $this->db->rollback();
10299 $this->db->commit();
10316 if (empty(
$id) && empty($ref) && empty($morewhere)) {
10320 $fieldlist = $this->getFieldList(
't');
10321 if (empty($fieldlist)) {
10325 $sql =
"SELECT ".$fieldlist;
10326 $sql .=
" FROM ".$this->db->prefix().$this->table_element.
' as t';
10329 $sql .=
' WHERE t.rowid = '.((int)
$id);
10330 } elseif (!empty($ref)) {
10331 $sql .=
" WHERE t.ref = '".$this->db->escape($ref).
"'";
10333 $sql .=
' WHERE 1 = 1';
10335 if (empty(
$id) && isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
10336 $sql .=
' AND t.entity IN ('.getEntity($this->element).
')';
10339 $sql .= $morewhere;
10341 $sql .=
' LIMIT 1';
10343 $res = $this->db->query($sql);
10345 $obj = $this->db->fetch_object($res);
10347 $this->setVarsFromFetchObj($obj);
10351 if (empty($noextrafields)) {
10352 $result = $this->fetch_optionals();
10354 $this->error = $this->db->lasterror();
10355 $this->errors[] = $this->error;
10365 $this->error = $this->db->lasterror();
10366 $this->errors[] = $this->error;
10380 $objectlineclassname = get_class($this).
'Line';
10381 if (!class_exists($objectlineclassname)) {
10382 $this->error =
'Error, class '.$objectlineclassname.
' not found during call of fetchLinesCommon';
10386 $objectline =
new $objectlineclassname($this->db);
10387 '@phan-var-force CommonObjectLine $objectline';
10389 $sql =
"SELECT ".$objectline->getFieldList(
'l');
10390 $sql .=
" FROM ".$this->db->prefix().$objectline->table_element.
" as l";
10391 $sql .=
" WHERE l.fk_".$this->db->escape($this->element).
" = ".((int) $this->
id);
10393 $sql .= $morewhere;
10395 if (isset($objectline->fields[
'position'])) {
10396 $sql .= $this->db->order(
'position',
'ASC');
10399 $resql = $this->db->query($sql);
10401 $num_rows = $this->db->num_rows($resql);
10403 $this->lines = array();
10404 while ($i < $num_rows) {
10405 $obj = $this->db->fetch_object($resql);
10407 $newline =
new $objectlineclassname($this->db);
10408 '@phan-var-force CommonObjectLine $newline';
10409 $newline->setVarsFromFetchObj($obj);
10417 $this->lines[] = $newline;
10424 $this->error = $this->db->lasterror();
10425 $this->errors[] = $this->error;
10439 dol_syslog(get_class($this).
"::updateCommon update", LOG_DEBUG);
10451 $fieldvalues = $this->setSaveQuery();
10455 if (array_key_exists(
'date_modification', $fieldvalues) && empty($fieldvalues[
'date_modification'])) {
10456 $fieldvalues[
'date_modification'] = $this->db->idate($now);
10458 if (array_key_exists(
'fk_user_modif', $fieldvalues) && !($fieldvalues[
'fk_user_modif'] > 0)) {
10459 $fieldvalues[
'fk_user_modif'] = $user->id;
10461 if (array_key_exists(
'user_modification_id', $fieldvalues) && !($fieldvalues[
'user_modification_id'] > 0)) {
10462 $fieldvalues[
'user_modification_id'] = $user->id;
10464 if (array_key_exists(
'ref', $fieldvalues)) {
10468 unset($fieldvalues[
'rowid']);
10474 foreach ($fieldvalues as $k => $v) {
10476 $value = $this->fields[$k];
10478 $values[$k] = $this->quote($v, $value);
10479 if (($value[
"type"] ==
"text") && !empty($value[
'arrayofkeyval']) && is_array($value[
'arrayofkeyval'])) {
10481 $v = preg_replace(
'/\s/',
',', $v);
10482 $v = preg_replace(
'/,+/',
',', $v);
10485 $tmp[] = $k.
'='.$this->quote($v, $this->fields[$k]);
10489 foreach ($keys as $key) {
10490 if (preg_match(
'/^integer:/i', $this->fields[$key][
'type']) && $values[$key] ==
'-1') {
10491 $values[$key] =
'';
10493 if (!empty($this->fields[$key][
'foreignkey']) && $values[$key] ==
'-1') {
10494 $values[$key] =
'';
10506 $sql =
'UPDATE '.$this->db->prefix().$this->table_element.
' SET '.implode(
', ', $tmp).
' WHERE rowid='.((int) $this->
id);
10508 $this->db->begin();
10511 $res = $this->db->query($sql);
10514 $this->errors[] = $this->db->lasterror();
10520 $result = $this->insertExtraFields();
10527 if (!$error && !$notrigger) {
10529 $result = $this->call_trigger(strtoupper(get_class($this)).
'_MODIFY', $user);
10538 $this->db->rollback();
10541 $this->db->commit();
10556 dol_syslog(get_class($this).
"::deleteCommon delete", LOG_DEBUG);
10560 $this->db->begin();
10562 if ($forcechilddeletion) {
10563 foreach ($this->childtables as $table) {
10564 $sql =
"DELETE FROM ".$this->db->prefix().$table.
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
10565 $resql = $this->db->query($sql);
10567 $this->error = $this->db->lasterror();
10568 $this->errors[] = $this->error;
10569 $this->db->rollback();
10573 } elseif (!empty($this->childtables)) {
10574 $objectisused = $this->isObjectUsed($this->
id);
10575 if (!empty($objectisused)) {
10576 dol_syslog(get_class($this).
"::deleteCommon Can't delete record as it has some child", LOG_WARNING);
10577 $this->error =
'ErrorRecordHasChildren';
10578 $this->errors[] = $this->error;
10579 $this->db->rollback();
10585 if (is_array($this->childtablesoncascade) && !empty($this->childtablesoncascade)) {
10586 foreach ($this->childtablesoncascade as $tabletodelete) {
10587 $deleteFromObject = explode(
':', $tabletodelete, 4);
10588 if (count($deleteFromObject) >= 2) {
10589 $className = str_replace(
'@',
'', $deleteFromObject[0]);
10590 $filePath = $deleteFromObject[1];
10591 $columnName = $deleteFromObject[2];
10593 if (!empty($deleteFromObject[3])) {
10594 $filter = $deleteFromObject[3];
10597 $childObject =
new $className($this->db);
10598 if (method_exists($childObject,
'deleteByParentField')) {
10599 '@phan-var-force CommonObject $childObject';
10600 $result = $childObject->deleteByParentField($this->
id, $columnName, $filter);
10603 $this->errors[] = $childObject->error;
10608 $this->errors[] =
"You defined a cascade delete on an object $className/$this->id but there is no method deleteByParentField for it";
10613 $this->errors[] =
'Cannot include child class file '.$filePath;
10618 $sql =
"DELETE FROM ".$this->db->prefix().$tabletodelete.
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
10620 $resql = $this->db->query($sql);
10623 $this->error = $this->db->lasterror();
10624 $this->errors[] = $this->error;
10634 $result = $this->call_trigger(strtoupper(get_class($this)).
'_DELETE', $user);
10644 $res = $this->deleteEcmFiles(1);
10651 $res = $this->deleteObjectLinked();
10656 if (!$error && !empty($this->isextrafieldmanaged)) {
10657 $result = $this->deleteExtraFields();
10664 $sql =
'DELETE FROM '.$this->db->prefix().$this->table_element.
' WHERE rowid='.((int) $this->
id);
10666 $resql = $this->db->query($sql);
10669 $this->errors[] = $this->db->lasterror();
10675 $this->db->rollback();
10678 $this->db->commit();
10701 if (!empty($parentId) && !empty($parentField)) {
10702 $this->db->begin();
10704 $sql =
"SELECT rowid FROM ".$this->db->prefix().$this->table_element;
10705 $sql .=
" WHERE ".$this->db->sanitize($parentField).
" = ".(int) $parentId;
10708 $errormessage =
'';
10710 if ($errormessage) {
10711 $this->errors[] = $errormessage;
10712 dol_syslog(__METHOD__.
' '.implode(
',', $this->errors), LOG_ERR);
10716 $resql = $this->db->query($sql);
10718 $this->errors[] = $this->db->lasterror();
10721 while ($obj = $this->db->fetch_object($resql)) {
10722 $result = $this->fetch($obj->rowid);
10725 $this->errors[] = $this->error;
10727 $result = $this->
delete($user);
10730 $this->errors[] = $this->error;
10738 if (empty($error)) {
10739 $this->db->commit();
10742 $this->error = implode(
', ', $this->errors);
10743 $this->db->rollback();
10744 return $error * -1;
10763 $tmpforobjectclass = get_class($this);
10764 $tmpforobjectlineclass = ucfirst($tmpforobjectclass).
'Line';
10766 $this->db->begin();
10769 $result = $this->call_trigger(
'LINE'.strtoupper($tmpforobjectclass).
'_DELETE', $user);
10775 if (empty($error)) {
10776 $sql =
"DELETE FROM ".$this->db->prefix().$this->table_element_line;
10777 $sql .=
" WHERE rowid = ".((int) $idline);
10779 $resql = $this->db->query($sql);
10781 $this->error =
"Error ".$this->db->lasterror();
10786 if (empty($error)) {
10788 $tmpobjectline =
new $tmpforobjectlineclass($this->db);
10789 '@phan-var-force CommonObjectLine $tmpobjectline';
10790 if (!isset($tmpobjectline->isextrafieldmanaged) || !empty($tmpobjectline->isextrafieldmanaged)) {
10791 $tmpobjectline->id = $idline;
10792 $result = $tmpobjectline->deleteExtraFields();
10795 $this->error =
"Error ".get_class($this).
"::deleteLineCommon deleteExtraFields error -4 ".$tmpobjectline->error;
10800 if (empty($error)) {
10801 $this->db->commit();
10804 dol_syslog(get_class($this).
"::deleteLineCommon ERROR:".$this->error, LOG_ERR);
10805 $this->db->rollback();
10824 $this->db->begin();
10826 $statusfield =
'status';
10827 if (in_array($this->element, array(
'don',
'donation',
'shipping'))) {
10828 $statusfield =
'fk_statut';
10831 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
10832 $sql .=
" SET ".$statusfield.
" = ".((int) $status);
10833 $sql .=
" WHERE rowid = ".((int) $this->
id);
10835 if ($this->db->query($sql)) {
10837 $this->oldcopy = clone $this;
10840 if (!$error && !$notrigger) {
10842 $result = $this->call_trigger($triggercode, $user);
10849 $this->
status = $status;
10850 if (property_exists($this,
'statut')) {
10851 $this->statut = $status;
10853 $this->db->commit();
10856 $this->db->rollback();
10860 $this->error = $this->db->error();
10861 $this->db->rollback();
10877 $this->specimen = 1;
10879 'label' =>
'This is label',
10880 'ref' =>
'ABCD1234',
10881 'description' =>
'This is a description',
10883 'note_public' =>
'Public note',
10884 'note_private' =>
'Private note',
10885 'date_creation' => (
dol_now() - 3600 * 48),
10886 'date_modification' => (
dol_now() - 3600 * 24),
10887 'fk_user_creat' => $user->id,
10888 'fk_user_modif' => $user->id,
10891 foreach ($fields as $key => $value) {
10892 if (array_key_exists($key, $this->fields)) {
10893 $this->{$key} = $value;
10898 if (property_exists($this,
'fields')) {
10899 foreach ($this->fields as $key => $value) {
10901 if (array_key_exists($key, $fields)) {
10905 if (!empty($value[
'default'])) {
10906 $this->$key = $value[
'default'];
10924 require_once DOL_DOCUMENT_ROOT.
'/core/class/comment.class.php';
10926 $comment =
new Comment($this->db);
10927 $result = $comment->fetchAllFor($this->element, $this->
id);
10929 $this->errors = array_merge($this->errors, $comment->errors);
10932 $this->comments = $comment->comments;
10934 return count($this->comments);
10944 return count($this->comments);
10955 if (!is_array($parameters)) {
10958 foreach ($parameters as $parameter) {
10959 if (isset($this->$parameter)) {
10960 $this->$parameter = trim($this->$parameter);
10979 require_once DOL_DOCUMENT_ROOT.
'/categories/class/categorie.class.php';
10983 $existing = $c->containing($this->
id, $type_categ,
'id');
11003 if (!is_array($categories)) {
11004 $categories = array($categories);
11007 dol_syslog(get_class($this).
"::setCategoriesCommon Object Id:".$this->
id.
' type_categ:'.$type_categ.
' nb tag add:'.count($categories), LOG_DEBUG);
11009 require_once DOL_DOCUMENT_ROOT.
'/categories/class/categorie.class.php';
11011 if (empty($type_categ)) {
11012 dol_syslog(__METHOD__.
': Type '.$type_categ.
'is an unknown category type. Done nothing.', LOG_ERR);
11018 $existing = $c->containing($this->
id, $type_categ,
'id');
11019 if ($remove_existing) {
11021 if (is_array($existing)) {
11022 $to_del = array_diff($existing, $categories);
11023 $to_add = array_diff($categories, $existing);
11026 $to_add = $categories;
11030 $to_add = array_diff($categories, $existing);
11037 foreach ($to_del as $del) {
11038 if ($c->fetch($del) > 0) {
11039 $result = $c->del_type($this, $type_categ);
11042 $this->error = $c->error;
11043 $this->errors = $c->errors;
11050 foreach ($to_add as $add) {
11051 if ($c->fetch($add) > 0) {
11052 $result = $c->add_type($this, $type_categ);
11055 $this->error = $c->error;
11056 $this->errors = $c->errors;
11064 return $error ? (-1 * $error) : $ok;
11077 $this->db->begin();
11079 if (empty($type)) {
11080 $type = $this->table_element;
11083 require_once DOL_DOCUMENT_ROOT.
'/categories/class/categorie.class.php';
11084 $categorystatic =
new Categorie($this->db);
11086 $sql =
"INSERT INTO ".$this->db->prefix().
"categorie_".(empty($categorystatic->MAP_CAT_TABLE[$type]) ? $type : $categorystatic->MAP_CAT_TABLE[$type]).
" (fk_categorie, fk_product)";
11087 $sql .=
" SELECT fk_categorie, $toId FROM ".$this->db->prefix().
"categorie_".(empty($categorystatic->MAP_CAT_TABLE[$type]) ? $type : $categorystatic->MAP_CAT_TABLE[$type]);
11088 $sql .=
" WHERE fk_product = ".((int) $fromId);
11090 if (!$this->db->query($sql)) {
11091 $this->error = $this->db->lasterror();
11092 $this->db->rollback();
11096 $this->db->commit();
11110 $this->db->begin();
11114 switch ($this->element) {
11116 $element =
'propale';
11119 $element =
'produit';
11121 case 'order_supplier':
11122 $element =
'fournisseur/commande';
11124 case 'invoice_supplier':
11127 $element =
'fournisseur/facture/'.get_exdir($this->
id, 2, 0, 1, $this,
'invoice_supplier');
11130 $element =
'expedition/sending';
11133 case 'project_task':
11134 require_once DOL_DOCUMENT_ROOT.
'/projet/class/task.class.php';
11136 $project_result = $this->fetch_projet();
11137 if ($project_result >= 0) {
11138 $element =
'projet/'.dol_sanitizeFileName($this->project->ref).
'/';
11142 $element = $this->element;
11144 '@phan-var-force string $element';
11147 $sql =
"DELETE FROM ".$this->db->prefix().
"ecm_files_extrafields WHERE fk_object IN (";
11148 $sql .=
" SELECT rowid FROM ".$this->db->prefix().
"ecm_files WHERE filename LIKE '".$this->db->escape($this->
ref).
"%'";
11149 $sql .=
" AND filepath = '".$this->db->escape($element).
"/".$this->db->escape($this->
ref).
"' AND entity = ".((int) $conf->entity);
11152 if (!$this->db->query($sql)) {
11153 $this->error = $this->db->lasterror();
11154 $this->db->rollback();
11159 $sql =
"DELETE FROM ".$this->db->prefix().
"ecm_files";
11160 $sql .=
" WHERE filename LIKE '".$this->db->escape($this->
ref).
"%'";
11161 $sql .=
" AND filepath = '".$this->db->escape($element).
"/".$this->db->escape($this->
ref).
"' AND entity = ".((int) $conf->entity);
11163 if (!$this->db->query($sql)) {
11164 $this->error = $this->db->lasterror();
11165 $this->db->rollback();
11172 $sql =
'DELETE FROM '.$this->db->prefix().
"ecm_files_extrafields";
11173 $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).
")";
11174 $resql = $this->db->query($sql);
11176 $this->error = $this->db->lasterror();
11177 $this->db->rollback();
11181 $sql =
'DELETE FROM '.$this->db->prefix().
"ecm_files";
11182 $sql .=
" WHERE src_object_type = '".$this->db->escape($this->table_element.(empty($this->module) ?
"" :
"@".$this->module)).
"' AND src_object_id = ".((int) $this->
id);
11183 $resql = $this->db->query($sql);
11185 $this->error = $this->db->lasterror();
11186 $this->db->rollback();
11191 $this->db->commit();
if( $user->socid > 0) if(! $user->hasRight('accounting', 'chartofaccount')) $object
print $langs trans("AuditedSecurityEvents").'</strong >< span class="opacitymedium"></span >< br > status
Or an array listing all the potential status of the object: array: int of the status => translated la...
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.
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.
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.
yn($yesno, $case=1, $color=0)
Return yes or no in current language.
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.
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='AES-256-CTR', $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.
publicphonebutton2 phonegreen basiclayout basiclayout TotalHT VATCode TotalVAT TotalLT1 TotalLT2 TotalTTC TotalHT clearboth nowraponall TAKEPOS_SHOW_SUBPRICE right right right takeposterminal SELECT e rowid