47 const TRIGGER_PREFIX =
'';
83 public $errors = array();
88 private $validateFieldsErrors = array();
104 public $element_for_permission;
109 public $table_element;
114 public $table_element_line =
'';
119 public $ismultientitymanaged;
129 public $array_options = array();
134 public $fields = array();
139 public $array_languages =
null;
144 public $contacts_ids;
149 public $linked_objects;
154 public $linkedObjectsIds;
159 public $linkedObjects;
164 private $linkedObjectsFullLoaded = array();
178 protected $table_ref_field =
'';
183 public $restrictiononfksoc = 0;
191 public $context = array();
276 public $ref_previous;
318 public $country_code;
361 public $barcode_type;
367 public $barcode_type_code;
373 public $barcode_type_label;
379 public $barcode_type_coder;
385 public $mode_reglement_id;
391 public $cond_reglement_id;
396 public $demand_reason_id;
402 public $transport_mode_id;
409 public $cond_reglement;
416 public $fk_delivery_address;
422 public $shipping_method_id;
428 public $shipping_method;
433 public $multicurrency_code;
438 public $multicurrency_tx;
457 public $last_main_doc;
487 public $note_private;
511 public $total_localtax1;
517 public $total_localtax2;
534 public $comments = array();
560 public $date_creation;
565 public $date_validation;
581 public $date_cloture;
593 public $user_creation;
598 public $user_creation_id;
610 public $user_validation;
615 public $user_validation_id;
620 public $user_closing_id;
626 public $user_modification;
631 public $user_modification_id;
634 public $next_prev_filter;
639 public $specimen = 0;
653 protected $labelStatusShort;
658 public $showphoto_on_popup;
663 public $nb = array();
673 public $extraparams = array();
678 protected $childtables = array();
685 protected $childtablesoncascade = array();
705 $sql =
"SELECT rowid, ref, ref_ext";
706 $sql .=
" FROM ".$db->prefix().$element;
707 $sql .=
" WHERE entity IN (".getEntity($element).
")";
710 $sql .=
" AND rowid = ".((int) $id);
712 $sql .=
" AND ref = '".$db->escape($ref).
"'";
713 } elseif ($ref_ext) {
714 $sql .=
" AND ref_ext = '".$db->escape($ref_ext).
"'";
716 $error =
'ErrorWrongParameters';
720 if ($ref || $ref_ext) {
721 $sql .=
" AND entity = ".((int) $conf->entity);
724 dol_syslog(get_class().
"::isExistingObject", LOG_DEBUG);
725 $resql = $db->query(
$sql);
727 $num = $db->num_rows($resql);
745 if (!empty($object->error)) {
746 $this->error = $object->error;
748 if (!empty($object->errors)) {
749 $this->errors = array_merge($this->errors, $object->errors);
774 global $action, $extrafields, $langs, $hookmanager;
777 $MAX_EXTRAFIELDS_TO_SHOW_IN_TOOLTIP =
getDolGlobalInt(
'MAX_EXTRAFIELDS_TO_SHOW_IN_TOOLTIP', 3);
783 if (!empty($extrafields->attributes[$this->table_element][
'label'])) {
784 foreach ($extrafields->attributes[$this->table_element][
'label'] as $key => $val) {
785 if ($extrafields->attributes[$this->table_element][
'type'][$key] ==
'separate') {
788 if ($count >= abs($MAX_EXTRAFIELDS_TO_SHOW_IN_TOOLTIP)) {
789 $datas[
'more_extrafields'] =
'<br>...';
793 if ($enabled && isset($extrafields->attributes[$this->table_element][
'enabled'][$key])) {
794 $enabled =
dol_eval($extrafields->attributes[$this->table_element][
'enabled'][$key], 1, 1,
'2');
796 if ($enabled && isset($extrafields->attributes[$this->table_element][
'list'][$key])) {
797 $enabled =
dol_eval($extrafields->attributes[$this->table_element][
'list'][$key], 1, 1,
'2');
800 if ($perms && isset($extrafields->attributes[$this->table_element][
'perms'][$key])) {
801 $perms =
dol_eval($extrafields->attributes[$this->table_element][
'perms'][$key], 1, 1,
'2');
803 if (empty($enabled)) {
806 if (abs($enabled) != 1 && abs($enabled) != 3 && abs($enabled) != 5 && abs($enabled) != 4) {
812 if (!empty($extrafields->attributes[$this->table_element][
'langfile'][$key])) {
813 $langs->load($extrafields->attributes[$this->table_element][
'langfile'][$key]);
815 $labelextra = $langs->trans((
string) $extrafields->attributes[$this->table_element][
'label'][$key]);
816 if ($extrafields->attributes[$this->table_element][
'type'][$key] ==
'separate') {
817 $datas[$key]=
'<br><b><u>'. $labelextra .
'</u></b>';
819 $value = (empty($this->array_options[
'options_' . $key]) ?
'' : $this->array_options[
'options_' . $key]);
820 $datas[$key]=
'<br><b>'. $labelextra .
':</b> ' . $extrafields->showOutputField($key, $value,
'', $this->table_element);
826 $hookmanager->initHooks(array($this->element .
'dao'));
828 'tooltipcontentarray' => &$datas,
832 $hookmanager->executeHooks(
'getTooltipContent', $parameters, $this, $action);
835 $label = implode($datas);
848 return $this->error.(is_array($this->errors) ? (($this->error !=
'' ?
', ' :
'').join(
', ', $this->errors)) :
'');
862 $parameters = array(
'objref'=>$objref);
864 $reshook = $hookmanager->executeHooks(
'getFormatedCustomerRef', $parameters, $this, $action);
866 return $hookmanager->resArray[
'objref'];
868 return $objref.(isset($hookmanager->resArray[
'objref']) ? $hookmanager->resArray[
'objref'] :
'');
881 $parameters = array(
'objref'=>$objref);
883 $reshook = $hookmanager->executeHooks(
'getFormatedSupplierRef', $parameters, $this, $action);
885 return $hookmanager->resArray[
'objref'];
887 return $objref.(isset($hookmanager->resArray[
'objref']) ? $hookmanager->resArray[
'objref'] :
'');
899 public function getFullAddress($withcountry = 0, $sep =
"\n", $withregion = 0, $extralangcode =
'')
901 if ($withcountry && $this->country_id && (empty($this->country_code) || empty($this->country))) {
902 require_once DOL_DOCUMENT_ROOT.
'/core/lib/company.lib.php';
903 $tmparray =
getCountry($this->country_id,
'all');
904 $this->country_code = $tmparray[
'code'];
905 $this->country = $tmparray[
'label'];
908 if ($withregion && $this->state_id && (empty($this->state_code) || empty($this->state) || empty($this->region) || empty($this->region_code))) {
909 require_once DOL_DOCUMENT_ROOT.
'/core/lib/company.lib.php';
910 $tmparray =
getState($this->state_id,
'all', 0, 1);
911 $this->state_code = $tmparray[
'code'];
912 $this->state = $tmparray[
'label'];
913 $this->region_code = $tmparray[
'region_code'];
914 $this->region = $tmparray[
'region'];
931 global $user, $dolibarr_main_url_root;
933 if (empty($this->last_main_doc)) {
937 include_once DOL_DOCUMENT_ROOT.
'/ecm/class/ecmfiles.class.php';
939 $result = $ecmfile->fetch(0,
'', $this->last_main_doc);
941 $this->error = $ecmfile->error;
942 $this->errors = $ecmfile->errors;
946 if (empty($ecmfile->id)) {
949 require_once DOL_DOCUMENT_ROOT.
'/core/lib/security2.lib.php';
971 } elseif (empty($ecmfile->share)) {
974 require_once DOL_DOCUMENT_ROOT.
'/core/lib/security2.lib.php';
976 $ecmfile->update($user);
982 $urlwithouturlroot = preg_replace(
'/'.preg_quote(DOL_URL_ROOT,
'/').
'$/i',
'', trim($dolibarr_main_url_root));
986 $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT;
995 if (!empty($ecmfile->share)) {
996 $paramlink .= ($paramlink ?
'&' :
'').
'hashp='.$ecmfile->share;
998 if ($forcedownload) {
999 $paramlink .= ($paramlink ?
'&' :
'').
'attachment=1';
1002 if ($relativelink) {
1003 $linktoreturn =
'document.php'.($paramlink ?
'?'.$paramlink :
'');
1005 $linktoreturn = $urlwithroot.
'/document.php'.($paramlink ?
'?'.$paramlink :
'');
1009 return $linktoreturn;
1023 public function add_contact($fk_socpeople, $type_contact, $source =
'external', $notrigger = 0)
1026 global $user, $langs;
1029 dol_syslog(get_class($this).
"::add_contact $fk_socpeople, $type_contact, $source, $notrigger");
1032 if ($fk_socpeople <= 0) {
1033 $langs->load(
"errors");
1034 $this->error = $langs->trans(
"ErrorWrongValueForParameterX",
"1");
1035 dol_syslog(get_class($this).
"::add_contact ".$this->error, LOG_ERR);
1038 if (!$type_contact) {
1039 $langs->load(
"errors");
1040 $this->error = $langs->trans(
"ErrorWrongValueForParameterX",
"2");
1041 dol_syslog(get_class($this).
"::add_contact ".$this->error, LOG_ERR);
1045 $id_type_contact = 0;
1046 if (is_numeric($type_contact)) {
1047 $id_type_contact = $type_contact;
1050 $sql =
"SELECT tc.rowid";
1051 $sql .=
" FROM ".$this->db->prefix().
"c_type_contact as tc";
1052 $sql .=
" WHERE tc.element='".$this->db->escape($this->element).
"'";
1053 $sql .=
" AND tc.source='".$this->db->escape($source).
"'";
1054 $sql .=
" AND tc.code='".$this->db->escape($type_contact).
"' AND tc.active=1";
1056 $resql = $this->db->query(
$sql);
1058 $obj = $this->db->fetch_object($resql);
1060 $id_type_contact = $obj->rowid;
1065 if ($id_type_contact == 0) {
1066 $this->error =
'CODE_NOT_VALID_FOR_THIS_ELEMENT';
1067 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");
1075 $already_added =
false;
1076 if (is_array($TListeContacts) && !empty($TListeContacts)) {
1077 foreach ($TListeContacts as $array_contact) {
1078 if ($array_contact[
'status'] == 4 && $array_contact[
'id'] == $fk_socpeople && $array_contact[
'fk_c_type_contact'] == $id_type_contact) {
1079 $already_added =
true;
1085 if (!$already_added) {
1089 $sql =
"INSERT INTO ".$this->db->prefix().
"element_contact";
1090 $sql .=
" (element_id, fk_socpeople, datecreate, statut, fk_c_type_contact) ";
1091 $sql .=
" VALUES (".$this->id.
", ".((int) $fk_socpeople).
" , ";
1092 $sql .=
"'".$this->db->idate($datecreate).
"'";
1093 $sql .=
", 4, ".((int) $id_type_contact);
1096 $resql = $this->db->query(
$sql);
1099 $result = $this->
call_trigger(strtoupper($this->element).
'_ADD_CONTACT', $user);
1101 $this->db->rollback();
1106 $this->db->commit();
1109 if ($this->db->errno() ==
'DB_ERROR_RECORD_ALREADY_EXISTS') {
1110 $this->error = $this->db->errno();
1111 $this->db->rollback();
1114 $this->error = $this->db->lasterror();
1115 $this->db->rollback();
1135 $contacts = $objFrom->liste_contact(-1, $source);
1136 foreach ($contacts as $contact) {
1137 if ($this->
add_contact($contact[
'id'], $contact[
'fk_c_type_contact'], $contact[
'source']) < 0) {
1154 public function update_contact($rowid, $statut, $type_contact_id = 0, $fk_socpeople = 0)
1158 $sql =
"UPDATE ".$this->db->prefix().
"element_contact set";
1159 $sql .=
" statut = ".$statut;
1160 if ($type_contact_id) {
1161 $sql .=
", fk_c_type_contact = ".((int) $type_contact_id);
1163 if ($fk_socpeople) {
1164 $sql .=
", fk_socpeople = ".((int) $fk_socpeople);
1166 $sql .=
" where rowid = ".((int) $rowid);
1167 $resql = $this->db->query(
$sql);
1171 $this->error = $this->db->lasterror();
1192 $sql =
"DELETE FROM ".$this->db->prefix().
"element_contact";
1193 $sql .=
" WHERE rowid = ".((int) $rowid);
1195 dol_syslog(get_class($this).
"::delete_contact", LOG_DEBUG);
1196 if ($this->db->query(
$sql)) {
1198 $result = $this->
call_trigger(strtoupper($this->element).
'_DELETE_CONTACT', $user);
1200 $this->db->rollback();
1205 $this->db->commit();
1208 $this->error = $this->db->lasterror();
1209 $this->db->rollback();
1229 if (!empty($typeContact)) {
1230 foreach ($typeContact as $key => $value) {
1231 array_push($temp, $key);
1233 $listId = implode(
",", $temp);
1238 if (empty($listId)) {
1242 $sql =
"DELETE FROM ".$this->db->prefix().
"element_contact";
1243 $sql .=
" WHERE element_id = ".((int) $this->
id);
1244 $sql .=
" AND fk_c_type_contact IN (".$this->db->sanitize($listId).
")";
1246 dol_syslog(get_class($this).
"::delete_linked_contact", LOG_DEBUG);
1247 if ($this->db->query(
$sql)) {
1250 $this->error = $this->db->lasterror();
1267 public function liste_contact($statusoflink = -1, $source =
'external', $list = 0, $code =
'', $status = -1, $arrayoftcids = array())
1274 $sql =
"SELECT ec.rowid, ec.statut as statuslink, ec.fk_socpeople as id, ec.fk_c_type_contact";
1275 if ($source ==
'internal') {
1276 $sql .=
", '-1' as socid, t.statut as statuscontact, t.login, t.photo";
1278 if ($source ==
'external' || $source ==
'thirdparty') {
1279 $sql .=
", t.fk_soc as socid, t.statut as statuscontact";
1281 $sql .=
", t.civility as civility, t.lastname as lastname, t.firstname, t.email";
1282 $sql .=
", tc.source, tc.element, tc.code, tc.libelle";
1283 $sql .=
" FROM ".$this->db->prefix().
"c_type_contact tc,";
1284 $sql .=
" ".$this->db->prefix().
"element_contact ec";
1285 if ($source ==
'internal') {
1286 $sql .=
" LEFT JOIN ".$this->db->prefix().
"user t on ec.fk_socpeople = t.rowid";
1288 if ($source ==
'external' || $source ==
'thirdparty') {
1289 $sql .=
" LEFT JOIN ".$this->db->prefix().
"socpeople t on ec.fk_socpeople = t.rowid";
1291 $sql .=
" WHERE ec.element_id = ".((int) $this->
id);
1292 $sql .=
" AND ec.fk_c_type_contact = tc.rowid";
1293 $sql .=
" AND tc.element = '".$this->db->escape($this->element).
"'";
1295 $sql .=
" AND tc.code = '".$this->db->escape($code).
"'";
1297 if ($source ==
'internal') {
1298 $sql .=
" AND tc.source = 'internal'";
1300 $sql .=
" AND t.statut = ".((int) $status);
1303 if ($source ==
'external' || $source ==
'thirdparty') {
1304 $sql .=
" AND tc.source = 'external'";
1306 $sql .=
" AND t.statut = ".((int) $status);
1309 $sql .=
" AND tc.active = 1";
1310 if ($statusoflink >= 0) {
1311 $sql .=
" AND ec.statut = ".((int) $statusoflink);
1313 $sql .=
" ORDER BY t.lastname ASC";
1315 dol_syslog(get_class($this).
"::liste_contact", LOG_DEBUG);
1316 $resql = $this->db->query(
$sql);
1318 $num = $this->db->num_rows($resql);
1321 $obj = $this->db->fetch_object($resql);
1324 $transkey =
"TypeContact_".$obj->element.
"_".$obj->source.
"_".$obj->code;
1325 $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle);
1327 'parentId' => $this->
id,
1328 'source' => $obj->source,
1329 'socid' => $obj->socid,
1331 'nom' => $obj->lastname,
1332 'civility' => $obj->civility,
1333 'lastname' => $obj->lastname,
1334 'firstname' => $obj->firstname,
1335 'email'=>$obj->email,
1336 'login'=> (empty($obj->login) ?
'' : $obj->login),
1337 'photo' => (empty($obj->photo) ?
'' : $obj->photo),
1338 'statuscontact' => $obj->statuscontact,
1339 'rowid' => $obj->rowid,
1340 'code' => $obj->code,
1341 'libelle' => $libelle_type,
1342 'status' => $obj->statuslink,
1343 'fk_c_type_contact' => $obj->fk_c_type_contact
1346 $tab[$i] = $obj->id;
1354 $this->error = $this->db->lasterror();
1369 $sql =
"SELECT ec.datecreate, ec.statut, ec.fk_socpeople, ec.fk_c_type_contact,";
1370 $sql .=
" tc.code, tc.libelle";
1371 $sql .=
" FROM (".$this->db->prefix().
"element_contact as ec, ".$this->db->prefix().
"c_type_contact as tc)";
1372 $sql .=
" WHERE ec.rowid =".((int) $rowid);
1373 $sql .=
" AND ec.fk_c_type_contact=tc.rowid";
1374 $sql .=
" AND tc.element = '".$this->db->escape($this->element).
"'";
1376 dol_syslog(get_class($this).
"::swapContactStatus", LOG_DEBUG);
1377 $resql = $this->db->query(
$sql);
1379 $obj = $this->db->fetch_object($resql);
1380 $newstatut = ($obj->statut == 4) ? 5 : 4;
1382 $this->db->free($resql);
1385 $this->error = $this->db->error();
1402 public function liste_type_contact($source =
'internal', $order =
'position', $option = 0, $activeonly = 0, $code =
'')
1407 if (empty($order)) {
1408 $order =
'position';
1410 if ($order ==
'position') {
1415 $sql =
"SELECT DISTINCT tc.rowid, tc.code, tc.libelle, tc.position";
1416 $sql .=
" FROM ".$this->db->prefix().
"c_type_contact as tc";
1417 $sql .=
" WHERE tc.element='".$this->db->escape($this->element).
"'";
1418 if ($activeonly == 1) {
1419 $sql .=
" AND tc.active=1";
1421 if (!empty($source) && $source !=
'all') {
1422 $sql .=
" AND tc.source='".$this->db->escape($source).
"'";
1424 if (!empty($code)) {
1425 $sql .=
" AND tc.code='".$this->db->escape($code).
"'";
1427 $sql .= $this->db->order($order,
'ASC');
1430 $resql = $this->db->query(
$sql);
1432 $num = $this->db->num_rows($resql);
1435 $obj = $this->db->fetch_object($resql);
1437 $transkey =
"TypeContact_".$this->element.
"_".$source.
"_".$obj->code;
1438 $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle);
1439 if (empty($option)) {
1440 $tab[$obj->rowid] = $libelle_type;
1442 $tab[$obj->code] = $libelle_type;
1448 $this->error = $this->db->lasterror();
1465 public function listeTypeContacts($source =
'internal', $option = 0, $activeonly = 0, $code =
'', $element =
'', $excludeelement =
'')
1467 global $langs, $conf;
1469 $langs->loadLangs(array(
'bills',
'contracts',
'interventions',
'orders',
'projects',
'propal',
'ticket',
'agenda'));
1473 $sql =
"SELECT DISTINCT tc.rowid, tc.code, tc.libelle, tc.position, tc.element";
1474 $sql .=
" FROM ".$this->db->prefix().
"c_type_contact as tc";
1476 $sqlWhere = array();
1477 if (!empty($element)) {
1478 $sqlWhere[] =
" tc.element='".$this->db->escape($element).
"'";
1480 if (!empty($excludeelement)) {
1481 $sqlWhere[] =
" tc.element <> '".$this->db->escape($excludeelement).
"'";
1484 if ($activeonly == 1) {
1485 $sqlWhere[] =
" tc.active=1";
1488 if (!empty($source) && $source !=
'all') {
1489 $sqlWhere[] =
" tc.source='".$this->db->escape($source).
"'";
1492 if (!empty($code)) {
1493 $sqlWhere[] =
" tc.code='".$this->db->escape($code).
"'";
1496 if (count($sqlWhere) > 0) {
1497 $sql .=
" WHERE ".implode(
' AND ', $sqlWhere);
1500 $sql .= $this->db->order(
'tc.element, tc.position',
'ASC');
1503 $resql = $this->db->query(
$sql);
1505 $num = $this->db->num_rows($resql);
1507 $langs->loadLangs(array(
"propal",
"orders",
"bills",
"suppliers",
"contracts",
"supplier_proposal"));
1509 while ($obj = $this->db->fetch_object($resql)) {
1510 $modulename = $obj->element;
1511 if (strpos($obj->element,
'project') !==
false) {
1512 $modulename =
'projet';
1513 } elseif ($obj->element ==
'contrat') {
1514 $element =
'contract';
1515 } elseif ($obj->element ==
'action') {
1516 $modulename =
'agenda';
1517 } elseif (strpos($obj->element,
'supplier') !==
false && $obj->element !=
'supplier_proposal') {
1518 $modulename =
'fournisseur';
1519 } elseif (strpos($obj->element,
'supplier') !==
false && $obj->element !=
'supplier_proposal') {
1520 $modulename =
'fournisseur';
1522 if (!empty($conf->{$modulename}->enabled)) {
1523 $libelle_element = $langs->trans(
'ContactDefault_'.$obj->element);
1524 $tmpelement = $obj->element;
1525 $transkey =
"TypeContact_".$tmpelement.
"_".$source.
"_".$obj->code;
1526 $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle);
1527 if (empty($option)) {
1528 $tab[$obj->rowid] = $libelle_element.
' - '.$libelle_type;
1530 $tab[$obj->rowid] = $libelle_element.
' - '.$libelle_type;
1537 $this->error = $this->db->lasterror();
1560 if ($this->element ==
'shipping' && $this->origin_id != 0) {
1561 $id = $this->origin_id;
1562 $element =
'commande';
1563 } elseif ($this->element ==
'reception' && $this->origin_id != 0) {
1564 $id = $this->origin_id;
1565 $element =
'order_supplier';
1568 $element = $this->element;
1571 $sql =
"SELECT ec.fk_socpeople";
1572 $sql .=
" FROM ".$this->db->prefix().
"element_contact as ec,";
1573 if ($source ==
'internal') {
1574 $sql .=
" ".$this->db->prefix().
"user as c,";
1576 if ($source ==
'external') {
1577 $sql .=
" ".$this->db->prefix().
"socpeople as c,";
1579 $sql .=
" ".$this->db->prefix().
"c_type_contact as tc";
1580 $sql .=
" WHERE ec.element_id = ".((int) $id);
1581 $sql .=
" AND ec.fk_socpeople = c.rowid";
1582 if ($source ==
'internal') {
1583 $sql .=
" AND c.entity IN (".getEntity(
'user').
")";
1585 if ($source ==
'external') {
1586 $sql .=
" AND c.entity IN (".getEntity(
'societe').
")";
1588 $sql .=
" AND ec.fk_c_type_contact = tc.rowid";
1589 $sql .=
" AND tc.element = '".$this->db->escape($element).
"'";
1590 $sql .=
" AND tc.source = '".$this->db->escape($source).
"'";
1592 $sql .=
" AND tc.code = '".$this->db->escape($code).
"'";
1594 $sql .=
" AND tc.active = 1";
1596 $sql .=
" AND ec.statut = ".((int) $status);
1599 dol_syslog(get_class($this).
"::getIdContact", LOG_DEBUG);
1600 $resql = $this->db->query(
$sql);
1602 while ($obj = $this->db->fetch_object($resql)) {
1603 $result[$i] = $obj->fk_socpeople;
1607 $this->error = $this->db->error();
1624 if (empty($contactid)) {
1625 $contactid = $this->contact_id;
1628 if (empty($contactid)) {
1632 require_once DOL_DOCUMENT_ROOT.
'/contact/class/contact.class.php';
1633 $contact =
new Contact($this->db);
1634 $result = $contact->fetch($contactid);
1635 $this->contact = $contact;
1651 if (empty($this->socid) && empty($this->fk_soc) && empty($force_thirdparty_id)) {
1655 require_once DOL_DOCUMENT_ROOT.
'/societe/class/societe.class.php';
1657 $idtofetch = isset($this->socid) ? $this->socid : (isset($this->fk_soc) ? $this->fk_soc : 0);
1658 if ($force_thirdparty_id) {
1659 $idtofetch = $force_thirdparty_id;
1663 $thirdparty =
new Societe($this->db);
1664 $result = $thirdparty->fetch($idtofetch);
1666 $this->errors=array_merge($this->errors, $thirdparty->errors);
1668 $this->thirdparty = $thirdparty;
1671 if (!empty($conf->global->PRODUIT_MULTIPRICES) && empty($this->thirdparty->price_level)) {
1672 $this->thirdparty->price_level = 1;
1691 if (!$this->table_ref_field) {
1695 $sql =
"SELECT rowid FROM ".$this->db->prefix().$this->table_element.
" WHERE ".$this->table_ref_field.
" LIKE '".$this->db->escape($ref).
"' LIMIT 1";
1697 $query = $this->db->query(
$sql);
1699 if (!$this->db->num_rows($query)) {
1703 $result = $this->db->fetch_object($query);
1705 return $this->fetch($result->rowid);
1721 dol_syslog(get_class($this).
'::fetch_barcode this->element='.$this->element.
' this->barcode_type='.$this->barcode_type);
1723 $idtype = $this->barcode_type;
1724 if (empty($idtype) && $idtype !=
'0') {
1725 if ($this->element ==
'product' && !empty($conf->global->PRODUIT_DEFAULT_BARCODE_TYPE)) {
1726 $idtype = $conf->global->PRODUIT_DEFAULT_BARCODE_TYPE;
1727 } elseif ($this->element ==
'societe') {
1728 $idtype = $conf->global->GENBARCODE_BARCODETYPE_THIRDPARTY;
1730 dol_syslog(
'Call fetch_barcode with barcode_type not defined and cant be guessed', LOG_WARNING);
1735 if (empty($this->barcode_type) || empty($this->barcode_type_code) || empty($this->barcode_type_label) || empty($this->barcode_type_coder)) {
1736 $sql =
"SELECT rowid, code, libelle as label, coder";
1737 $sql .=
" FROM ".$this->db->prefix().
"c_barcode_type";
1738 $sql .=
" WHERE rowid = ".((int) $idtype);
1739 dol_syslog(get_class($this).
'::fetch_barcode', LOG_DEBUG);
1740 $resql = $this->db->query(
$sql);
1742 $obj = $this->db->fetch_object($resql);
1743 $this->barcode_type = $obj->rowid;
1744 $this->barcode_type_code = $obj->code;
1745 $this->barcode_type_label = $obj->label;
1746 $this->barcode_type_coder = $obj->coder;
1766 return $this->fetch_projet();
1778 include_once DOL_DOCUMENT_ROOT.
'/projet/class/project.class.php';
1780 if (empty($this->fk_project) && !empty($this->fk_projet)) {
1781 $this->fk_project = $this->fk_projet;
1783 if (empty($this->fk_project)) {
1787 $project =
new Project($this->db);
1788 $result = $project->fetch($this->fk_project);
1790 $this->projet = $project;
1791 $this->project = $project;
1804 include_once DOL_DOCUMENT_ROOT.
'/product/class/product.class.php';
1806 if (empty($this->fk_product)) {
1810 $product =
new Product($this->db);
1811 $result = $product->fetch($this->fk_product);
1813 $this->product = $product;
1827 $user =
new User($this->db);
1828 $result = $user->fetch($userid);
1829 $this->
user = $user;
1842 if ($this->origin ==
'shipping') {
1843 $this->origin =
'expedition';
1845 if ($this->origin ==
'delivery') {
1846 $this->origin =
'livraison';
1848 if ($this->origin ==
'order_supplier') {
1849 $this->origin =
'commandeFournisseur';
1852 $origin = $this->origin;
1854 $classname = ucfirst($origin);
1855 $this->$origin =
new $classname($this->db);
1856 $this->$origin->fetch($this->origin_id);
1874 $sql =
"SELECT rowid FROM ".$this->db->prefix().$table;
1875 $sql .=
" WHERE ".$field.
" = '".$this->db->escape($key).
"'";
1876 if (!empty($element)) {
1877 $sql .=
" AND entity IN (".getEntity($element).
")";
1879 $sql .=
" AND entity = ".((int) $conf->entity);
1882 dol_syslog(get_class($this).
'::fetchObjectFrom', LOG_DEBUG);
1883 $resql = $this->db->query(
$sql);
1885 $row = $this->db->fetch_row($resql);
1888 $result = $this->fetch($row[0]);
1906 if (!empty($id) && !empty($field) && !empty($table)) {
1907 $sql =
"SELECT ".$field.
" FROM ".$this->db->prefix().$table;
1908 $sql .=
" WHERE rowid = ".((int) $id);
1910 dol_syslog(get_class($this).
'::getValueFrom', LOG_DEBUG);
1911 $resql = $this->db->query(
$sql);
1913 $row = $this->db->fetch_row($resql);
1936 public function setValueFrom($field, $value, $table =
'', $id =
null, $format =
'', $id_field =
'', $fuser =
null, $trigkey =
'', $fk_user_field =
'fk_user_modif')
1938 global $user, $langs, $conf;
1940 if (empty($table)) {
1941 $table = $this->table_element;
1946 if (empty($format)) {
1949 if (empty($id_field)) {
1950 $id_field =
'rowid';
1954 if ($table ==
'product' && $field ==
'note_private') {
1957 if (in_array($table, array(
'actioncomm',
'adherent',
'advtargetemailing',
'cronjob',
'establishment'))) {
1958 $fk_user_field =
'fk_user_mod';
1964 $sql =
"SELECT " . $field;
1965 $sql .=
" FROM " . MAIN_DB_PREFIX . $table;
1966 $sql .=
" WHERE " . $id_field .
" = " . ((int) $id);
1968 $resql = $this->db->query(
$sql);
1970 if ($obj = $this->db->fetch_object($resql)) {
1971 if ($format ==
'date') {
1972 $oldvalue = $this->db->jdate($obj->$field);
1974 $oldvalue = $obj->$field;
1978 $this->error = $this->db->lasterror();
1989 $sql =
"UPDATE ".$this->db->prefix().$table.
" SET ";
1991 if ($format ==
'text') {
1992 $sql .= $field.
" = '".$this->db->escape($value).
"'";
1993 } elseif ($format ==
'int') {
1994 $sql .= $field.
" = ".((int) $value);
1995 } elseif ($format ==
'date') {
1996 $sql .= $field.
" = ".($value ?
"'".$this->db->idate($value).
"'" :
"null");
1997 } elseif ($format ==
'dategmt') {
1998 $sql .= $field.
" = ".($value ?
"'".$this->db->idate($value,
'gmt').
"'" :
"null");
2001 if ($fk_user_field) {
2002 if (!empty($fuser) && is_object($fuser)) {
2003 $sql .=
", ".$fk_user_field.
" = ".((int) $fuser->id);
2004 } elseif (empty($fuser) || $fuser !=
'none') {
2005 $sql .=
", ".$fk_user_field.
" = ".((int) $user->id);
2009 $sql .=
" WHERE ".$id_field.
" = ".((int) $id);
2011 $resql = $this->db->query(
$sql);
2015 if (method_exists($this,
'fetch')) {
2016 $result = $this->fetch($id);
2018 $result = $this->fetchCommon($id);
2020 $this->oldcopy = clone $this;
2021 if (property_exists($this->oldcopy, $field)) {
2022 $this->oldcopy->$field = $oldvalue;
2026 $result = $this->call_trigger($trigkey, (!empty($fuser) && is_object($fuser)) ? $fuser : $user);
2034 if (property_exists($this, $field)) {
2035 $this->$field = $value;
2037 $this->db->commit();
2040 $this->db->rollback();
2044 if ($this->db->lasterrno() ==
'DB_ERROR_RECORD_ALREADY_EXISTS') {
2045 $this->error =
'DB_ERROR_RECORD_ALREADY_EXISTS';
2047 $this->error = $this->db->lasterror();
2049 $this->db->rollback();
2066 global $conf, $user;
2068 if (!$this->table_element) {
2069 dol_print_error(
'', get_class($this).
"::load_previous_next_ref was called on objet with property table_element not defined");
2072 if ($fieldid ==
'none') {
2077 if ($this->table_element ==
'facture_rec' && $fieldid ==
'title') {
2083 if ($user->socid > 0) {
2084 $socid = $user->socid;
2089 $aliastablesociete =
's';
2090 if ($this->element ==
'societe') {
2091 $aliastablesociete =
'te';
2093 $restrictiononfksoc = empty($this->restrictiononfksoc) ? 0 : $this->restrictiononfksoc;
2094 $sql =
"SELECT MAX(te.".$fieldid.
")";
2095 $sql .=
" FROM ".(empty($nodbprefix) ?$this->db->prefix():
'').$this->table_element.
" as te";
2096 if ($this->element ==
'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
2097 $sql .=
",".$this->db->prefix().
"usergroup_user as ug";
2099 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2100 $tmparray = explode(
'@', $this->ismultientitymanaged);
2101 $sql .=
", ".$this->db->prefix().$tmparray[1].
" as ".($tmparray[1] ==
'societe' ?
's' :
'parenttable');
2102 } elseif ($restrictiononfksoc == 1 && $this->element !=
'societe' && empty($user->rights->societe->client->voir) && !$socid) {
2103 $sql .=
", ".$this->db->prefix().
"societe as s";
2104 } elseif ($restrictiononfksoc == 2 && $this->element !=
'societe' && empty($user->rights->societe->client->voir) && !$socid) {
2105 $sql .=
" LEFT JOIN ".$this->db->prefix().
"societe as s ON te.fk_soc = s.rowid";
2107 if ($restrictiononfksoc && empty($user->rights->societe->client->voir) && !$socid) {
2108 $sql .=
" LEFT JOIN ".$this->db->prefix().
"societe_commerciaux as sc ON ".$aliastablesociete.
".rowid = sc.fk_soc";
2110 if ($fieldid ==
'rowid') {
2111 $sql .=
" WHERE te.".$fieldid.
" < ".((int) $this->
id);
2113 $sql .=
" WHERE te.".$fieldid.
" < '".$this->db->escape($this->
ref).
"'";
2115 if ($restrictiononfksoc == 1 && empty($user->rights->societe->client->voir) && !$socid) {
2116 $sql .=
" AND sc.fk_user = ".((int) $user->id);
2118 if ($restrictiononfksoc == 2 && empty($user->rights->societe->client->voir) && !$socid) {
2119 $sql .=
" AND (sc.fk_user = ".((int) $user->id).
' OR te.fk_soc IS NULL)';
2121 if (!empty($filter)) {
2122 if (!preg_match(
'/^\s*AND/i', $filter)) {
2127 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2128 $tmparray = explode(
'@', $this->ismultientitymanaged);
2129 $sql .=
" AND te.".$tmparray[0].
" = ".($tmparray[1] ==
"societe" ?
"s" :
"parenttable").
".rowid";
2130 } elseif ($restrictiononfksoc == 1 && $this->element !=
'societe' && empty($user->rights->societe->client->voir) && !$socid) {
2131 $sql .=
' AND te.fk_soc = s.rowid';
2133 if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
2134 if ($this->element ==
'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
2135 if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
2136 $sql .=
" AND te.entity IS NOT NULL";
2138 $sql .=
" AND ug.fk_user = te.rowid";
2139 $sql .=
" AND ug.entity IN (".getEntity(
'usergroup').
")";
2142 $sql .=
' AND te.entity IN ('.getEntity($this->element).
')';
2145 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged) && $this->element !=
'societe') {
2146 $tmparray = explode(
'@', $this->ismultientitymanaged);
2147 $sql .=
' AND parenttable.entity IN ('.getEntity($tmparray[1]).
')';
2149 if ($restrictiononfksoc == 1 && $socid && $this->element !=
'societe') {
2150 $sql .=
' AND te.fk_soc = '.((int) $socid);
2152 if ($restrictiononfksoc == 2 && $socid && $this->element !=
'societe') {
2153 $sql .=
' AND (te.fk_soc = '.((int) $socid).
' OR te.fk_soc IS NULL)';
2155 if ($restrictiononfksoc && $socid && $this->element ==
'societe') {
2156 $sql .=
' AND te.rowid = '.((int) $socid);
2160 $result = $this->db->query(
$sql);
2162 $this->error = $this->db->lasterror();
2165 $row = $this->db->fetch_row($result);
2166 $this->ref_previous = $row[0];
2168 $sql =
"SELECT MIN(te.".$fieldid.
")";
2169 $sql .=
" FROM ".(empty($nodbprefix) ?$this->db->prefix():
'').$this->table_element.
" as te";
2170 if ($this->element ==
'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
2171 $sql .=
",".$this->db->prefix().
"usergroup_user as ug";
2173 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2174 $tmparray = explode(
'@', $this->ismultientitymanaged);
2175 $sql .=
", ".$this->db->prefix().$tmparray[1].
" as ".($tmparray[1] ==
'societe' ?
's' :
'parenttable');
2176 } elseif ($restrictiononfksoc == 1 && $this->element !=
'societe' && empty($user->rights->societe->client->voir) && !$socid) {
2177 $sql .=
", ".$this->db->prefix().
"societe as s";
2178 } elseif ($restrictiononfksoc == 2 && $this->element !=
'societe' && empty($user->rights->societe->client->voir) && !$socid) {
2179 $sql .=
" LEFT JOIN ".$this->db->prefix().
"societe as s ON te.fk_soc = s.rowid";
2181 if ($restrictiononfksoc && empty($user->rights->societe->client->voir) && !$socid) {
2182 $sql .=
" LEFT JOIN ".$this->db->prefix().
"societe_commerciaux as sc ON ".$aliastablesociete.
".rowid = sc.fk_soc";
2184 if ($fieldid ==
'rowid') {
2185 $sql .=
" WHERE te.".$fieldid.
" > ".((int) $this->
id);
2187 $sql .=
" WHERE te.".$fieldid.
" > '".$this->db->escape($this->
ref).
"'";
2189 if ($restrictiononfksoc == 1 && empty($user->rights->societe->client->voir) && !$socid) {
2190 $sql .=
" AND sc.fk_user = ".((int) $user->id);
2192 if ($restrictiononfksoc == 2 && empty($user->rights->societe->client->voir) && !$socid) {
2193 $sql .=
" AND (sc.fk_user = ".((int) $user->id).
' OR te.fk_soc IS NULL)';
2195 if (!empty($filter)) {
2196 if (!preg_match(
'/^\s*AND/i', $filter)) {
2201 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2202 $tmparray = explode(
'@', $this->ismultientitymanaged);
2203 $sql .=
" AND te.".$tmparray[0].
" = ".($tmparray[1] ==
"societe" ?
"s" :
"parenttable").
".rowid";
2204 } elseif ($restrictiononfksoc == 1 && $this->element !=
'societe' && empty($user->rights->societe->client->voir) && !$socid) {
2205 $sql .=
' AND te.fk_soc = s.rowid';
2207 if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
2208 if ($this->element ==
'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
2209 if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
2210 $sql .=
" AND te.entity IS NOT NULL";
2212 $sql .=
" AND ug.fk_user = te.rowid";
2213 $sql .=
" AND ug.entity IN (".getEntity(
'usergroup').
")";
2216 $sql .=
' AND te.entity IN ('.getEntity($this->element).
')';
2219 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged) && $this->element !=
'societe') {
2220 $tmparray = explode(
'@', $this->ismultientitymanaged);
2221 $sql .=
' AND parenttable.entity IN ('.getEntity($tmparray[1]).
')';
2223 if ($restrictiononfksoc == 1 && $socid && $this->element !=
'societe') {
2224 $sql .=
' AND te.fk_soc = '.((int) $socid);
2226 if ($restrictiononfksoc == 2 && $socid && $this->element !=
'societe') {
2227 $sql .=
' AND (te.fk_soc = '.((int) $socid).
' OR te.fk_soc IS NULL)';
2229 if ($restrictiononfksoc && $socid && $this->element ==
'societe') {
2230 $sql .=
' AND te.rowid = '.((int) $socid);
2235 $result = $this->db->query(
$sql);
2237 $this->error = $this->db->lasterror();
2240 $row = $this->db->fetch_row($result);
2241 $this->ref_next = $row[0];
2256 $contactAlreadySelected = array();
2257 $tab = $this->liste_contact(-1, $source);
2261 if ($source ==
'thirdparty') {
2262 $contactAlreadySelected[$i] = $tab[$i][
'socid'];
2264 $contactAlreadySelected[$i] = $tab[$i][
'id'];
2268 return $contactAlreadySelected;
2284 if (!$this->table_element) {
2285 dol_syslog(get_class($this).
"::setProject was called on objet with property table_element not defined", LOG_ERR);
2289 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
2290 if (!empty($this->fields[
'fk_project'])) {
2292 $sql .=
" SET fk_project = ".((int) $projectid);
2294 $sql .=
" SET fk_project = NULL";
2296 $sql .=
' WHERE rowid = '.((int) $this->
id);
2297 } elseif ($this->table_element ==
'actioncomm') {
2299 $sql .=
" SET fk_project = ".((int) $projectid);
2301 $sql .=
" SET fk_project = NULL";
2303 $sql .=
' WHERE id = '.((int) $this->
id);
2307 $sql .=
' SET fk_projet = '.((int) $projectid);
2309 $sql .=
' SET fk_projet = NULL';
2311 $sql .=
" WHERE rowid = ".((int) $this->
id);
2316 dol_syslog(get_class($this).
"::setProject", LOG_DEBUG);
2317 if ($this->db->query(
$sql)) {
2318 $this->fk_project = ((int) $projectid);
2325 if (!$error && !$notrigger) {
2327 $result = $this->call_trigger(strtoupper($this->element) .
'_MODIFY', $user);
2336 $this->db->rollback();
2339 $this->db->commit();
2354 $error = 0; $notrigger = 0;
2356 dol_syslog(get_class($this).
'::setPaymentMethods('.$id.
')');
2358 if ($this->statut >= 0 || $this->element ==
'societe') {
2360 $fieldname =
'fk_mode_reglement';
2361 if ($this->element ==
'societe') {
2362 $fieldname =
'mode_reglement';
2364 if (get_class($this) ==
'Fournisseur') {
2365 $fieldname =
'mode_reglement_supplier';
2367 if (get_class($this) ==
'Tva') {
2368 $fieldname =
'fk_typepayment';
2370 if (get_class($this) ==
'Salary') {
2371 $fieldname =
'fk_typepayment';
2374 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
2375 $sql .=
" SET ".$fieldname.
" = ".(($id > 0 || $id ==
'0') ? ((
int) $id) :
'NULL');
2376 $sql .=
' WHERE rowid='.((int) $this->
id);
2378 if ($this->db->query(
$sql)) {
2379 $this->mode_reglement_id = $id;
2381 if (get_class($this) ==
'Fournisseur') {
2382 $this->mode_reglement_supplier_id = $id;
2385 if (!$error && !$notrigger) {
2387 if (get_class($this) ==
'Commande') {
2388 $result = $this->call_trigger(
'ORDER_MODIFY', $user);
2390 $result = $this->call_trigger(strtoupper(get_class($this)).
'_MODIFY', $user);
2399 dol_syslog(get_class($this).
'::setPaymentMethods Error '.$this->db->error());
2400 $this->error = $this->db->error();
2404 dol_syslog(get_class($this).
'::setPaymentMethods, status of the object is incompatible');
2405 $this->error =
'Status of the object is incompatible '.$this->statut;
2418 dol_syslog(get_class($this).
'::setMulticurrencyCode('.$code.
')');
2419 if ($this->statut >= 0 || $this->element ==
'societe') {
2420 $fieldname =
'multicurrency_code';
2422 $sql =
'UPDATE '.$this->db->prefix().$this->table_element;
2423 $sql .=
" SET ".$fieldname.
" = '".$this->db->escape($code).
"'";
2424 $sql .=
' WHERE rowid='.((int) $this->
id);
2426 if ($this->db->query(
$sql)) {
2427 $this->multicurrency_code = $code;
2431 $this->setMulticurrencyRate($rate, 2);
2436 dol_syslog(get_class($this).
'::setMulticurrencyCode Error '.
$sql.
' - '.$this->db->error());
2437 $this->error = $this->db->error();
2441 dol_syslog(get_class($this).
'::setMulticurrencyCode, status of the object is incompatible');
2442 $this->error =
'Status of the object is incompatible '.$this->statut;
2454 public function setMulticurrencyRate($rate, $mode = 1)
2456 dol_syslog(get_class($this).
'::setMulticurrencyRate('.$rate.
','.$mode.
')');
2457 if ($this->statut >= 0 || $this->element ==
'societe') {
2458 $fieldname =
'multicurrency_tx';
2460 $sql =
'UPDATE '.$this->db->prefix().$this->table_element;
2461 $sql .=
" SET ".$fieldname.
" = ".((
float) $rate);
2462 $sql .=
' WHERE rowid='.((int) $this->
id);
2464 if ($this->db->query(
$sql)) {
2465 $this->multicurrency_tx = $rate;
2468 if (!empty($this->lines)) {
2469 foreach ($this->lines as &$line) {
2472 $line->subprice = 0;
2477 $line->multicurrency_subprice = 0;
2480 switch ($this->element) {
2488 $line->remise_percent,
2490 $line->localtax1_tx,
2491 $line->localtax2_tx,
2492 ($line->description ? $line->description : $line->desc),
2495 $line->special_code,
2496 $line->fk_parent_line,
2497 $line->skip_update_total,
2498 $line->fk_fournprice,
2501 $line->product_type,
2504 $line->array_options,
2506 $line->multicurrency_subprice
2514 ($line->description ? $line->description : $line->desc),
2517 $line->remise_percent,
2519 $line->localtax1_tx,
2520 $line->localtax2_tx,
2525 $line->product_type,
2526 $line->fk_parent_line,
2527 $line->skip_update_total,
2528 $line->fk_fournprice,
2531 $line->special_code,
2532 $line->array_options,
2534 $line->multicurrency_subprice
2542 ($line->description ? $line->description : $line->desc),
2545 $line->remise_percent,
2549 $line->localtax1_tx,
2550 $line->localtax2_tx,
2553 $line->product_type,
2554 $line->fk_parent_line,
2555 $line->skip_update_total,
2556 $line->fk_fournprice,
2559 $line->special_code,
2560 $line->array_options,
2561 $line->situation_percent,
2563 $line->multicurrency_subprice
2566 case 'supplier_proposal':
2573 $line->remise_percent,
2575 $line->localtax1_tx,
2576 $line->localtax2_tx,
2577 ($line->description ? $line->description : $line->desc),
2580 $line->special_code,
2581 $line->fk_parent_line,
2582 $line->skip_update_total,
2583 $line->fk_fournprice,
2586 $line->product_type,
2587 $line->array_options,
2589 $line->multicurrency_subprice
2592 case 'order_supplier':
2597 ($line->description ? $line->description : $line->desc),
2600 $line->remise_percent,
2602 $line->localtax1_tx,
2603 $line->localtax2_tx,
2606 $line->product_type,
2610 $line->array_options,
2612 $line->multicurrency_subprice,
2616 case 'invoice_supplier':
2621 ($line->description ? $line->description : $line->desc),
2624 $line->localtax1_tx,
2625 $line->localtax2_tx,
2630 $line->product_type,
2631 $line->remise_percent,
2635 $line->array_options,
2637 $line->multicurrency_subprice,
2642 dol_syslog(get_class($this).
'::setMulticurrencyRate no updateline defined', LOG_DEBUG);
2650 dol_syslog(get_class($this).
'::setMulticurrencyRate Error '.
$sql.
' - '.$this->db->error());
2651 $this->error = $this->db->error();
2655 dol_syslog(get_class($this).
'::setMulticurrencyRate, status of the object is incompatible');
2656 $this->error =
'Status of the object is incompatible '.$this->statut;
2670 dol_syslog(get_class($this).
'::setPaymentTerms('.$id.
', '.var_export($deposit_percent,
true).
')');
2671 if ($this->statut >= 0 || $this->element ==
'societe') {
2673 $fieldname =
'fk_cond_reglement';
2674 if ($this->element ==
'societe') {
2675 $fieldname =
'cond_reglement';
2677 if (get_class($this) ==
'Fournisseur') {
2678 $fieldname =
'cond_reglement_supplier';
2681 if (empty($deposit_percent) || $deposit_percent < 0) {
2685 if ($deposit_percent > 100) {
2686 $deposit_percent = 100;
2689 $sql =
'UPDATE '.$this->db->prefix().$this->table_element;
2690 $sql .=
" SET ".$fieldname.
" = ".(($id > 0 || $id ==
'0') ? ((
int) $id) :
'NULL');
2691 if (in_array($this->table_element, array(
'propal',
'commande',
'societe'))) {
2692 $sql .=
" , deposit_percent = " . (empty($deposit_percent) ?
'NULL' :
"'".$this->db->escape($deposit_percent).
"'");
2694 $sql .=
' WHERE rowid='.((int) $this->
id);
2696 if ($this->db->query(
$sql)) {
2697 $this->cond_reglement_id = $id;
2699 if (get_class($this) ==
'Fournisseur') {
2700 $this->cond_reglement_supplier_id = $id;
2702 $this->cond_reglement = $id;
2703 $this->deposit_percent = $deposit_percent;
2706 dol_syslog(get_class($this).
'::setPaymentTerms Error '.
$sql.
' - '.$this->db->error());
2707 $this->error = $this->db->error();
2711 dol_syslog(get_class($this).
'::setPaymentTerms, status of the object is incompatible');
2712 $this->error =
'Status of the object is incompatible '.$this->statut;
2725 dol_syslog(get_class($this).
'::setTransportMode('.$id.
')');
2726 if ($this->statut >= 0 || $this->element ==
'societe') {
2727 $fieldname =
'fk_transport_mode';
2728 if ($this->element ==
'societe') {
2729 $fieldname =
'transport_mode';
2731 if (get_class($this) ==
'Fournisseur') {
2732 $fieldname =
'transport_mode_supplier';
2735 $sql =
'UPDATE '.$this->db->prefix().$this->table_element;
2736 $sql .=
" SET ".$fieldname.
" = ".(($id > 0 || $id ==
'0') ? ((
int) $id) :
'NULL');
2737 $sql .=
' WHERE rowid='.((int) $this->
id);
2739 if ($this->db->query(
$sql)) {
2740 $this->transport_mode_id = $id;
2742 if (get_class($this) ==
'Fournisseur') {
2743 $this->transport_mode_supplier_id = $id;
2747 dol_syslog(get_class($this).
'::setTransportMode Error '.
$sql.
' - '.$this->db->error());
2748 $this->error = $this->db->error();
2752 dol_syslog(get_class($this).
'::setTransportMode, status of the object is incompatible');
2753 $this->error =
'Status of the object is incompatible '.$this->statut;
2766 dol_syslog(get_class($this).
'::setRetainedWarrantyPaymentTerms('.$id.
')');
2767 if ($this->statut >= 0 || $this->element ==
'societe') {
2768 $fieldname =
'retained_warranty_fk_cond_reglement';
2770 $sql =
'UPDATE '.$this->db->prefix().$this->table_element;
2771 $sql .=
" SET ".$fieldname.
" = ".((int) $id);
2772 $sql .=
' WHERE rowid='.((int) $this->
id);
2774 if ($this->db->query(
$sql)) {
2775 $this->retained_warranty_fk_cond_reglement = $id;
2778 dol_syslog(get_class($this).
'::setRetainedWarrantyPaymentTerms Error '.
$sql.
' - '.$this->db->error());
2779 $this->error = $this->db->error();
2783 dol_syslog(get_class($this).
'::setRetainedWarrantyPaymentTerms, status of the object is incompatible');
2784 $this->error =
'Status of the object is incompatible '.$this->statut;
2798 $fieldname =
'fk_delivery_address';
2799 if ($this->element ==
'delivery' || $this->element ==
'shipping') {
2800 $fieldname =
'fk_address';
2803 $sql =
"UPDATE ".$this->db->prefix().$this->table_element.
" SET ".$fieldname.
" = ".((int) $id);
2804 $sql .=
" WHERE rowid = ".((int) $this->
id).
" AND fk_statut = 0";
2806 if ($this->db->query(
$sql)) {
2807 $this->fk_delivery_address = $id;
2810 $this->error = $this->db->error();
2811 dol_syslog(get_class($this).
'::setDeliveryAddress Error '.$this->error);
2830 if (empty($userused)) {
2836 if (!$this->table_element) {
2837 dol_syslog(get_class($this).
"::setShippingMethod was called on objet with property table_element not defined", LOG_ERR);
2843 if ($shipping_method_id < 0) {
2844 $shipping_method_id =
'NULL';
2846 dol_syslog(get_class($this).
'::setShippingMethod('.$shipping_method_id.
')');
2848 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
2849 $sql .=
" SET fk_shipping_method = ".((int) $shipping_method_id);
2850 $sql .=
" WHERE rowid=".((int) $this->
id);
2851 $resql = $this->db->query(
$sql);
2853 dol_syslog(get_class($this).
'::setShippingMethod Error ', LOG_DEBUG);
2854 $this->error = $this->db->lasterror();
2859 $this->context = array(
'shippingmethodupdate'=>1);
2860 $result = $this->call_trigger(strtoupper(get_class($this)).
'_MODIFY', $userused);
2868 $this->db->rollback();
2871 $this->shipping_method_id = ($shipping_method_id ==
'NULL') ?
null:$shipping_method_id;
2872 $this->db->commit();
2886 if (!$this->table_element) {
2887 dol_syslog(get_class($this).
"::setWarehouse was called on objet with property table_element not defined", LOG_ERR);
2890 if ($warehouse_id < 0) {
2891 $warehouse_id =
'NULL';
2893 dol_syslog(get_class($this).
'::setWarehouse('.$warehouse_id.
')');
2895 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
2896 $sql .=
" SET fk_warehouse = ".((int) $warehouse_id);
2897 $sql .=
" WHERE rowid=".((int) $this->
id);
2899 if ($this->db->query(
$sql)) {
2900 $this->warehouse_id = ($warehouse_id ==
'NULL') ?
null:$warehouse_id;
2903 dol_syslog(get_class($this).
'::setWarehouse Error ', LOG_DEBUG);
2904 $this->error = $this->db->error();
2919 if (!$this->table_element) {
2920 dol_syslog(get_class($this).
"::setDocModel was called on objet with property table_element not defined", LOG_ERR);
2924 $newmodelpdf =
dol_trunc($modelpdf, 255);
2926 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
2927 $sql .=
" SET model_pdf = '".$this->db->escape($newmodelpdf).
"'";
2928 $sql .=
" WHERE rowid = ".((int) $this->
id);
2930 dol_syslog(get_class($this).
"::setDocModel", LOG_DEBUG);
2931 $resql = $this->db->query(
$sql);
2933 $this->model_pdf = $modelpdf;
2934 $this->modelpdf = $modelpdf;
2955 if (empty($userused)) {
2961 if (!$this->table_element) {
2962 dol_syslog(get_class($this).
"::setBankAccount was called on objet with property table_element not defined", LOG_ERR);
2967 if ($fk_account < 0) {
2968 $fk_account =
'NULL';
2970 dol_syslog(get_class($this).
'::setBankAccount('.$fk_account.
')');
2972 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
2973 $sql .=
" SET fk_account = ".((int) $fk_account);
2974 $sql .=
" WHERE rowid=".((int) $this->
id);
2976 $resql = $this->db->query(
$sql);
2978 dol_syslog(get_class($this).
'::setBankAccount Error '.
$sql.
' - '.$this->db->error());
2979 $this->error = $this->db->lasterror();
2984 $this->context = array(
'bankaccountupdate'=>1);
2985 $result = $this->call_trigger(strtoupper(get_class($this)).
'_MODIFY', $userused);
2993 $this->db->rollback();
2996 $this->fk_account = ($fk_account ==
'NULL') ?
null:$fk_account;
2997 $this->db->commit();
3015 public function line_order($renum =
false, $rowidorder =
'ASC', $fk_parent_line =
true)
3018 if (!$this->table_element_line) {
3019 dol_syslog(get_class($this).
"::line_order was called on objet with property table_element_line not defined", LOG_ERR);
3022 if (!$this->fk_element) {
3023 dol_syslog(get_class($this).
"::line_order was called on objet with property fk_element not defined", LOG_ERR);
3027 $fieldposition =
'rang';
3028 if (in_array($this->table_element_line, array(
'bom_bomline',
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3029 $fieldposition =
'position';
3034 $sql =
"SELECT count(rowid) FROM ".$this->db->prefix().$this->table_element_line;
3035 $sql .=
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
3037 $sql .=
" AND " . $fieldposition .
" = 0";
3040 $sql .=
" AND " . $fieldposition .
" <> 0";
3043 dol_syslog(get_class($this).
"::line_order", LOG_DEBUG);
3044 $resql = $this->db->query(
$sql);
3046 $row = $this->db->fetch_row($resql);
3056 $sql =
"SELECT rowid FROM ".$this->db->prefix().$this->table_element_line;
3057 $sql .=
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
3058 if ($fk_parent_line) {
3059 $sql .=
' AND fk_parent_line IS NULL';
3061 $sql .=
" ORDER BY " . $fieldposition .
" ASC, rowid " . $rowidorder;
3063 dol_syslog(get_class($this).
"::line_order search all parent lines", LOG_DEBUG);
3064 $resql = $this->db->query(
$sql);
3067 $num = $this->db->num_rows($resql);
3069 $row = $this->db->fetch_row($resql);
3071 $childrens = $this->getChildrenOfLine($row[0]);
3072 if (!empty($childrens)) {
3073 foreach ($childrens as $child) {
3074 array_push($rows, $child);
3081 if (!empty($rows)) {
3082 foreach ($rows as $key => $row) {
3083 $this->updateRangOfLine($row, ($key + 1));
3102 $fieldposition =
'rang';
3103 if (in_array($this->table_element_line, array(
'bom_bomline',
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3104 $fieldposition =
'position';
3109 $sql =
"SELECT rowid FROM ".$this->db->prefix().$this->table_element_line;
3110 $sql .=
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
3111 $sql .=
' AND fk_parent_line = '.((int) $id);
3112 $sql .=
" ORDER BY " . $fieldposition .
" ASC";
3114 dol_syslog(get_class($this).
"::getChildrenOfLine search children lines for line ".$id, LOG_DEBUG);
3115 $resql = $this->db->query(
$sql);
3117 if ($this->db->num_rows($resql) > 0) {
3118 while ($row = $this->db->fetch_row($resql)) {
3120 if (!empty($includealltree)) {
3121 $rows = array_merge($rows, $this->getChildrenOfLine($row[0]), $includealltree);
3137 public function line_up($rowid, $fk_parent_line =
true)
3140 $this->line_order(
false,
'ASC', $fk_parent_line);
3143 $rang = $this->getRangOfLine($rowid);
3146 $this->updateLineUp($rowid, $rang);
3160 $this->line_order(
false,
'ASC', $fk_parent_line);
3163 $rang = $this->getRangOfLine($rowid);
3166 $max = $this->line_max();
3169 $this->updateLineDown($rowid, $rang, $max);
3181 global $hookmanager;
3182 $fieldposition =
'rang';
3183 if (in_array($this->table_element_line, array(
'bom_bomline',
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3184 $fieldposition =
'position';
3187 $sql =
"UPDATE ".$this->db->prefix().$this->table_element_line.
" SET ".$fieldposition.
" = ".((int) $rang);
3188 $sql .=
' WHERE rowid = '.((int) $rowid);
3190 dol_syslog(get_class($this).
"::updateRangOfLine", LOG_DEBUG);
3191 if (!$this->db->query(
$sql)) {
3195 $parameters=array(
'rowid'=>$rowid,
'rang'=>$rang,
'fieldposition' => $fieldposition);
3197 $reshook = $hookmanager->executeHooks(
'afterRankOfLineUpdate', $parameters, $this, $action);
3212 $num = count($rows);
3213 for ($i = 0; $i < $num; $i++) {
3214 $this->updateRangOfLine($rows[$i], ($i + 1));
3228 $fieldposition =
'rang';
3229 if (in_array($this->table_element_line, array(
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3230 $fieldposition =
'position';
3233 $sql =
"UPDATE ".$this->db->prefix().$this->table_element_line.
" SET ".$fieldposition.
" = ".((int) $rang);
3234 $sql .=
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
3235 $sql .=
" AND " . $fieldposition .
" = " . ((int) ($rang - 1));
3236 if ($this->db->query(
$sql)) {
3237 $sql =
"UPDATE ".$this->db->prefix().$this->table_element_line.
" SET ".$fieldposition.
" = ".((int) ($rang - 1));
3238 $sql .=
' WHERE rowid = '.((int) $rowid);
3239 if (!$this->db->query(
$sql)) {
3259 $fieldposition =
'rang';
3260 if (in_array($this->table_element_line, array(
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3261 $fieldposition =
'position';
3264 $sql =
"UPDATE ".$this->db->prefix().$this->table_element_line.
" SET ".$fieldposition.
" = ".((int) $rang);
3265 $sql .=
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
3266 $sql .=
" AND " . $fieldposition .
" = " . ((int) ($rang + 1));
3267 if ($this->db->query(
$sql)) {
3268 $sql =
"UPDATE ".$this->db->prefix().$this->table_element_line.
" SET ".$fieldposition.
" = ".((int) ($rang + 1));
3269 $sql .=
' WHERE rowid = '.((int) $rowid);
3270 if (!$this->db->query(
$sql)) {
3287 $fieldposition =
'rang';
3288 if (in_array($this->table_element_line, array(
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3289 $fieldposition =
'position';
3292 $sql =
"SELECT " . $fieldposition .
" FROM ".$this->db->prefix().$this->table_element_line;
3293 $sql .=
" WHERE rowid = ".((int) $rowid);
3295 dol_syslog(get_class($this).
"::getRangOfLine", LOG_DEBUG);
3296 $resql = $this->db->query(
$sql);
3298 $row = $this->db->fetch_row($resql);
3313 $fieldposition =
'rang';
3314 if (in_array($this->table_element_line, array(
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3315 $fieldposition =
'position';
3318 $sql =
"SELECT rowid FROM ".$this->db->prefix().$this->table_element_line;
3319 $sql .=
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
3320 $sql .=
" AND " . $fieldposition .
" = ".((int) $rang);
3321 $resql = $this->db->query(
$sql);
3323 $row = $this->db->fetch_row($resql);
3340 $positionfield =
'rang';
3341 if (in_array($this->table_element, array(
'bom_bom',
'product_attribute'))) {
3342 $positionfield =
'position';
3346 if ($fk_parent_line) {
3347 $sql =
"SELECT max(".$positionfield.
") FROM ".$this->db->prefix().$this->table_element_line;
3348 $sql .=
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
3349 $sql .=
" AND fk_parent_line = ".((int) $fk_parent_line);
3351 dol_syslog(get_class($this).
"::line_max", LOG_DEBUG);
3352 $resql = $this->db->query(
$sql);
3354 $row = $this->db->fetch_row($resql);
3355 if (!empty($row[0])) {
3358 return $this->getRangOfLine($fk_parent_line);
3363 $sql =
"SELECT max(".$positionfield.
") FROM ".$this->db->prefix().$this->table_element_line;
3364 $sql .=
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
3366 dol_syslog(get_class($this).
"::line_max", LOG_DEBUG);
3367 $resql = $this->db->query(
$sql);
3369 $row = $this->db->fetch_row($resql);
3387 if (!$this->table_element) {
3388 dol_syslog(get_class($this).
"::update_ref_ext was called on objet with property table_element not defined", LOG_ERR);
3392 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
3393 $sql .=
" SET ref_ext = '".$this->db->escape($ref_ext).
"'";
3394 $sql .=
" WHERE ".(isset($this->table_rowid) ? $this->table_rowid :
'rowid').
" = ".((
int) $this->id);
3396 dol_syslog(get_class($this).
"::update_ref_ext", LOG_DEBUG);
3397 if ($this->db->query(
$sql)) {
3398 $this->ref_ext = $ref_ext;
3401 $this->error = $this->db->error();
3419 if (!$this->table_element) {
3420 $this->error =
'update_note was called on objet with property table_element not defined';
3421 dol_syslog(get_class($this).
"::update_note was called on objet with property table_element not defined", LOG_ERR);
3424 if (!in_array($suffix, array(
'',
'_public',
'_private'))) {
3425 $this->error =
'update_note Parameter suffix must be empty, \'_private\' or \'_public\'';
3426 dol_syslog(get_class($this).
"::update_note Parameter suffix must be empty, '_private' or '_public'", LOG_ERR);
3430 $newsuffix = $suffix;
3433 if ($this->table_element ==
'product' && $newsuffix ==
'_private') {
3436 if (in_array($this->table_element, array(
'actioncomm',
'adherent',
'advtargetemailing',
'cronjob',
'establishment'))) {
3437 $fieldusermod =
"fk_user_mod";
3438 } elseif ($this->table_element ==
'ecm_files') {
3439 $fieldusermod =
"fk_user_m";
3441 $fieldusermod =
"fk_user_modif";
3443 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
3444 $sql .=
" SET note".$newsuffix.
" = ".(!empty($note) ? (
"'".$this->db->escape($note).
"'") :
"NULL");
3445 $sql .=
", ".$fieldusermod.
" = ".((int) $user->id);
3446 $sql .=
" WHERE rowid = ".((int) $this->
id);
3448 dol_syslog(get_class($this).
"::update_note", LOG_DEBUG);
3449 if ($this->db->query(
$sql)) {
3450 if ($suffix ==
'_public') {
3451 $this->note_public = $note;
3452 } elseif ($suffix ==
'_private') {
3453 $this->note_private = $note;
3455 $this->note = $note;
3456 $this->note_private = $note;
3460 $this->error = $this->db->lasterror();
3477 return $this->update_note($note,
'_public');
3491 public function update_price($exclspec = 0, $roundingadjust =
'none', $nodatabaseupdate = 0, $seller =
null)
3494 global $conf, $hookmanager, $action;
3496 $parameters = array(
'exclspec' => $exclspec,
'roundingadjust' => $roundingadjust,
'nodatabaseupdate' => $nodatabaseupdate,
'seller' => $seller);
3497 $reshook = $hookmanager->executeHooks(
'updateTotalPrice', $parameters, $this, $action);
3500 } elseif ($reshook < 0) {
3506 if ($this->element ==
'propal') {
3507 $MODULE =
"MODULE_DISALLOW_UPDATE_PRICE_PROPOSAL";
3508 } elseif ($this->element ==
'commande' || $this->element ==
'order') {
3509 $MODULE =
"MODULE_DISALLOW_UPDATE_PRICE_ORDER";
3510 } elseif ($this->element ==
'facture' || $this->element ==
'invoice') {
3511 $MODULE =
"MODULE_DISALLOW_UPDATE_PRICE_INVOICE";
3512 } elseif ($this->element ==
'facture_fourn' || $this->element ==
'supplier_invoice' || $this->element ==
'invoice_supplier' || $this->element ==
'invoice_supplier_rec') {
3513 $MODULE =
"MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_INVOICE";
3514 } elseif ($this->element ==
'order_supplier' || $this->element ==
'supplier_order') {
3515 $MODULE =
"MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_ORDER";
3516 } elseif ($this->element ==
'supplier_proposal') {
3517 $MODULE =
"MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_PROPOSAL";
3520 if (!empty($MODULE)) {
3521 if (!empty($conf->global->$MODULE)) {
3522 $modsactivated = explode(
',', $conf->global->$MODULE);
3523 foreach ($modsactivated as $mod) {
3531 include_once DOL_DOCUMENT_ROOT.
'/core/lib/price.lib.php';
3533 $forcedroundingmode = $roundingadjust;
3534 if ($forcedroundingmode ==
'auto' && isset($conf->global->MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND)) {
3536 } elseif ($forcedroundingmode ==
'auto') {
3537 $forcedroundingmode =
'0';
3542 $multicurrency_tx = !empty($this->multicurrency_tx) ? $this->multicurrency_tx : 1;
3545 $fieldtva =
'total_tva';
3546 $fieldlocaltax1 =
'total_localtax1';
3547 $fieldlocaltax2 =
'total_localtax2';
3548 $fieldup =
'subprice';
3549 if ($this->element ==
'facture_fourn' || $this->element ==
'invoice_supplier') {
3553 if ($this->element ==
'invoice_supplier_rec') {
3556 if ($this->element ==
'expensereport') {
3557 $fieldup =
'value_unit';
3560 $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,";
3561 $sql .=
' tva_tx as vatrate, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type, info_bits, product_type';
3562 if ($this->table_element_line ==
'facturedet') {
3563 $sql .=
', situation_percent';
3565 $sql .=
', multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc';
3566 $sql .=
" FROM ".$this->db->prefix().$this->table_element_line;
3567 $sql .=
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
3569 $product_field =
'product_type';
3570 if ($this->table_element_line ==
'contratdet') {
3571 $product_field =
'';
3573 if ($product_field) {
3574 $sql .=
" AND ".$product_field.
" <> 9";
3577 $sql .=
' ORDER by rowid';
3579 dol_syslog(get_class($this).
"::update_price", LOG_DEBUG);
3581 $resql = $this->db->query(
$sql);
3583 $this->total_ht = 0;
3584 $this->total_tva = 0;
3585 $this->total_localtax1 = 0;
3586 $this->total_localtax2 = 0;
3587 $this->total_ttc = 0;
3588 $total_ht_by_vats = array();
3589 $total_tva_by_vats = array();
3590 $total_ttc_by_vats = array();
3591 $this->multicurrency_total_ht = 0;
3592 $this->multicurrency_total_tva = 0;
3593 $this->multicurrency_total_ttc = 0;
3597 $num = $this->db->num_rows($resql);
3600 $obj = $this->db->fetch_object($resql);
3603 $parameters = array(
'fk_element' => $obj->rowid);
3604 $reshook = $hookmanager->executeHooks(
'changeRoundingMode', $parameters, $this, $action);
3606 if (empty($reshook) && $forcedroundingmode ==
'0') {
3608 $localtax_array = array($obj->localtax1_type, $obj->localtax1_tx, $obj->localtax2_type, $obj->localtax2_tx);
3609 $tmpcal =
calcul_price_total($obj->qty, $obj->up, $obj->remise_percent, $obj->vatrate, $obj->localtax1_tx, $obj->localtax2_tx, 0,
'HT', $obj->info_bits, $obj->product_type, $seller, $localtax_array, (isset($obj->situation_percent) ? $obj->situation_percent : 100), $multicurrency_tx);
3611 $diff_when_using_price_ht =
price2num($tmpcal[1] - $obj->total_tva,
'MT', 1);
3612 $diff_on_current_total =
price2num($obj->total_ttc - $obj->total_ht - $obj->total_tva - $obj->total_localtax1 - $obj->total_localtax2,
'MT', 1);
3616 if ($diff_on_current_total) {
3618 $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);
3619 dol_syslog(
'We found unconsistent 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);
3620 $resqlfix = $this->db->query($sqlfix);
3624 $obj->total_tva = $tmpcal[1];
3625 $obj->total_ttc = $tmpcal[2];
3626 } elseif ($diff_when_using_price_ht && $roundingadjust ==
'0') {
3629 $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);
3630 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);
3631 $resqlfix = $this->db->query($sqlfix);
3635 $obj->total_tva = $tmpcal[1];
3636 $obj->total_ttc = $tmpcal[2];
3640 $this->total_ht += $obj->total_ht;
3641 $this->total_tva += $obj->total_tva;
3642 $this->total_localtax1 += $obj->total_localtax1;
3643 $this->total_localtax2 += $obj->total_localtax2;
3644 $this->total_ttc += $obj->total_ttc;
3645 $this->multicurrency_total_ht += $obj->multicurrency_total_ht;
3646 $this->multicurrency_total_tva += $obj->multicurrency_total_tva;
3647 $this->multicurrency_total_ttc += $obj->multicurrency_total_ttc;
3649 if (!isset($total_ht_by_vats[$obj->vatrate])) {
3650 $total_ht_by_vats[$obj->vatrate] = 0;
3652 if (!isset($total_tva_by_vats[$obj->vatrate])) {
3653 $total_tva_by_vats[$obj->vatrate] = 0;
3655 if (!isset($total_ttc_by_vats[$obj->vatrate])) {
3656 $total_ttc_by_vats[$obj->vatrate] = 0;
3658 $total_ht_by_vats[$obj->vatrate] += $obj->total_ht;
3659 $total_tva_by_vats[$obj->vatrate] += $obj->total_tva;
3660 $total_ttc_by_vats[$obj->vatrate] += $obj->total_ttc;
3662 if ($forcedroundingmode ==
'1') {
3663 $tmpvat =
price2num($total_ht_by_vats[$obj->vatrate] * $obj->vatrate / 100,
'MT', 1);
3664 $diff =
price2num($total_tva_by_vats[$obj->vatrate] - $tmpvat,
'MT', 1);
3667 if (abs($diff) > (10 * pow(10, -1 *
getDolGlobalInt(
'MAIN_MAX_DECIMALS_TOT', 0)))) {
3669 $errmsg =
'A rounding difference was detected into TOTAL but is too high to be corrected. Some data in your lines may be corrupted. Try to edit each line manually to fix this before restarting.';
3671 $this->error = $errmsg;
3675 $sqlfix =
"UPDATE ".$this->db->prefix().$this->table_element_line.
" SET ".$fieldtva.
" = ".
price2num($obj->total_tva - $diff).
", total_ttc = ".
price2num($obj->total_ttc - $diff).
" WHERE rowid = ".((int) $obj->rowid);
3676 dol_syslog(
'We found a difference of '.$diff.
' for line rowid = '.$obj->rowid.
". We fix the total_vat and total_ttc of line by running sqlfix = ".$sqlfix);
3678 $resqlfix = $this->db->query($sqlfix);
3684 $this->total_tva = (
float)
price2num($this->total_tva - $diff,
'', 1);
3685 $this->total_ttc = (
float)
price2num($this->total_ttc - $diff,
'', 1);
3686 $total_tva_by_vats[$obj->vatrate] = (
float)
price2num($total_tva_by_vats[$obj->vatrate] - $diff,
'', 1);
3687 $total_ttc_by_vats[$obj->vatrate] = (
float)
price2num($total_ttc_by_vats[$obj->vatrate] - $diff,
'', 1);
3695 $this->total_ttc += isset($this->revenuestamp) ? $this->revenuestamp : 0;
3696 $this->multicurrency_total_ttc += isset($this->revenuestamp) ? ($this->revenuestamp * $multicurrency_tx) : 0;
3699 if (!empty($this->situation_cycle_ref) && $this->situation_counter > 1 && method_exists($this,
'get_prev_sits') && $this->
type != $this::TYPE_CREDIT_NOTE) {
3700 $prev_sits = $this->get_prev_sits();
3702 foreach ($prev_sits as $sit) {
3703 $this->total_ht -= $sit->total_ht;
3704 $this->total_tva -= $sit->total_tva;
3705 $this->total_localtax1 -= $sit->total_localtax1;
3706 $this->total_localtax2 -= $sit->total_localtax2;
3707 $this->total_ttc -= $sit->total_ttc;
3708 $this->multicurrency_total_ht -= $sit->multicurrency_total_ht;
3709 $this->multicurrency_total_tva -= $sit->multicurrency_total_tva;
3710 $this->multicurrency_total_ttc -= $sit->multicurrency_total_ttc;
3717 $this->total_localtax1 = (
float)
price2num($this->total_localtax1);
3718 $this->total_localtax2 = (
float)
price2num($this->total_localtax2);
3721 $this->db->free($resql);
3724 $fieldht =
'total_ht';
3726 $fieldlocaltax1 =
'localtax1';
3727 $fieldlocaltax2 =
'localtax2';
3728 $fieldttc =
'total_ttc';
3730 if (in_array($this->element, array(
'propal',
'commande',
'facture',
'facturerec',
'supplier_proposal',
'order_supplier',
'facture_fourn',
'invoice_supplier',
'invoice_supplier_rec',
'expensereport'))) {
3731 $fieldtva =
'total_tva';
3734 if (!$error && empty($nodatabaseupdate)) {
3735 $sql =
"UPDATE ".$this->db->prefix().$this->table_element.
' SET';
3738 $sql .=
" ".$fieldlocaltax1.
" = ".((
float)
price2num($this->total_localtax1,
'MT', 1)).
",";
3739 $sql .=
" ".$fieldlocaltax2.
" = ".((
float)
price2num($this->total_localtax2,
'MT', 1)).
",";
3741 $sql .=
", multicurrency_total_ht = ".((float)
price2num($this->multicurrency_total_ht,
'MT', 1));
3742 $sql .=
", multicurrency_total_tva = ".((float)
price2num($this->multicurrency_total_tva,
'MT', 1));
3743 $sql .=
", multicurrency_total_ttc = ".((float)
price2num($this->multicurrency_total_ttc,
'MT', 1));
3744 $sql .=
" WHERE rowid = ".((int) $this->
id);
3746 dol_syslog(get_class($this).
"::update_price", LOG_DEBUG);
3747 $resql = $this->db->query(
$sql);
3751 $this->error = $this->db->lasterror();
3752 $this->errors[] = $this->db->lasterror();
3757 $this->db->commit();
3760 $this->db->rollback();
3780 public function add_object_linked($origin =
null, $origin_id =
null, $f_user =
null, $notrigger = 0)
3783 global $user, $hookmanager, $action;
3784 $origin = (!empty($origin) ? $origin : $this->origin);
3785 $origin_id = (!empty($origin_id) ? $origin_id : $this->origin_id);
3786 $f_user = isset($f_user) ? $f_user : $user;
3789 if ($origin ==
'order') {
3790 $origin =
'commande';
3792 if ($origin ==
'invoice') {
3793 $origin =
'facture';
3795 if ($origin ==
'invoice_template') {
3796 $origin =
'facturerec';
3798 if ($origin ==
'supplierorder') {
3799 $origin =
'order_supplier';
3804 $coremodule = array(
'knowledgemanagement',
'partnership',
'workstation',
'ticket',
'recruitment',
'eventorganization',
'asset');
3806 $targettype = ((!empty($this->module) && ! in_array($this->module, $coremodule)) ? $this->module.
'_' :
'').$this->element;
3808 $parameters = array(
'targettype'=>$targettype);
3810 $reshook = $hookmanager->executeHooks(
'setLinkedObjectSourceTargetType', $parameters, $this, $action);
3812 if (!empty($hookmanager->resArray[
'targettype'])) $targettype = $hookmanager->resArray[
'targettype'];
3818 $sql =
"INSERT INTO " . $this->db->prefix() .
"element_element (";
3819 $sql .=
"fk_source";
3820 $sql .=
", sourcetype";
3821 $sql .=
", fk_target";
3822 $sql .=
", targettype";
3823 $sql .=
") VALUES (";
3824 $sql .= ((int) $origin_id);
3825 $sql .=
", '" . $this->db->escape($origin) .
"'";
3826 $sql .=
", " . ((int) $this->
id);
3827 $sql .=
", '" . $this->db->escape($targettype) .
"'";
3830 dol_syslog(get_class($this) .
"::add_object_linked", LOG_DEBUG);
3831 if ($this->db->query(
$sql)) {
3834 $this->context[
'link_origin'] = $origin;
3835 $this->context[
'link_origin_id'] = $origin_id;
3836 $result = $this->call_trigger(
'OBJECT_LINK_INSERT', $f_user);
3843 $this->error = $this->db->lasterror();
3848 $this->db->commit();
3851 $this->db->rollback();
3878 public function fetchObjectLinked($sourceid =
null, $sourcetype =
'', $targetid =
null, $targettype =
'', $clause =
'OR', $alsosametype = 1, $orderby =
'sourcetype', $loadalsoobjects = 1)
3880 global $conf, $hookmanager, $action;
3884 if ($this->
id > 0 && !empty($this->linkedObjectsFullLoaded[$this->
id])) {
3888 $this->linkedObjectsIds = array();
3889 $this->linkedObjects = array();
3891 $justsource =
false;
3892 $justtarget =
false;
3893 $withtargettype =
false;
3894 $withsourcetype =
false;
3896 $parameters = array(
'sourcetype'=>$sourcetype,
'sourceid'=>$sourceid,
'targettype'=>$targettype,
'targetid'=>$targetid);
3898 $reshook = $hookmanager->executeHooks(
'setLinkedObjectSourceTargetType', $parameters, $this, $action);
3900 if (!empty($hookmanager->resArray[
'sourcetype'])) $sourcetype = $hookmanager->resArray[
'sourcetype'];
3901 if (!empty($hookmanager->resArray[
'sourceid'])) $sourceid = $hookmanager->resArray[
'sourceid'];
3902 if (!empty($hookmanager->resArray[
'targettype'])) $targettype = $hookmanager->resArray[
'targettype'];
3903 if (!empty($hookmanager->resArray[
'targetid'])) $targetid = $hookmanager->resArray[
'targetid'];
3906 if (!empty($sourceid) && !empty($sourcetype) && empty($targetid)) {
3908 if (!empty($targettype)) {
3909 $withtargettype =
true;
3912 if (!empty($targetid) && !empty($targettype) && empty($sourceid)) {
3914 if (!empty($sourcetype)) {
3915 $withsourcetype =
true;
3919 $sourceid = (!empty($sourceid) ? $sourceid : $this->id);
3920 $targetid = (!empty($targetid) ? $targetid : $this->id);
3921 $sourcetype = (!empty($sourcetype) ? $sourcetype : $this->element);
3922 $targettype = (!empty($targettype) ? $targettype : $this->element);
3931 $sql =
"SELECT rowid, fk_source, sourcetype, fk_target, targettype";
3932 $sql .=
" FROM ".$this->db->prefix().
"element_element";
3934 if ($justsource || $justtarget) {
3936 $sql .=
"fk_source = ".((int) $sourceid).
" AND sourcetype = '".$this->db->escape($sourcetype).
"'";
3937 if ($withtargettype) {
3938 $sql .=
" AND targettype = '".$this->db->escape($targettype).
"'";
3940 } elseif ($justtarget) {
3941 $sql .=
"fk_target = ".((int) $targetid).
" AND targettype = '".$this->db->escape($targettype).
"'";
3942 if ($withsourcetype) {
3943 $sql .=
" AND sourcetype = '".$this->db->escape($sourcetype).
"'";
3947 $sql .=
"(fk_source = ".((int) $sourceid).
" AND sourcetype = '".$this->db->escape($sourcetype).
"')";
3948 $sql .=
" ".$clause.
" (fk_target = ".((int) $targetid).
" AND targettype = '".$this->db->escape($targettype).
"')";
3949 if ($loadalsoobjects && $this->
id > 0 && $sourceid == $this->
id && $sourcetype == $this->element && $targetid == $this->
id && $targettype == $this->element && $clause ==
'OR') {
3950 $this->linkedObjectsFullLoaded[$this->id] =
true;
3953 $sql .=
" ORDER BY ".$orderby;
3955 dol_syslog(get_class($this).
"::fetchObjectLink", LOG_DEBUG);
3956 $resql = $this->db->query(
$sql);
3958 $num = $this->db->num_rows($resql);
3961 $obj = $this->db->fetch_object($resql);
3962 if ($justsource || $justtarget) {
3964 $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
3965 } elseif ($justtarget) {
3966 $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
3969 if ($obj->fk_source == $sourceid && $obj->sourcetype == $sourcetype) {
3970 $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
3972 if ($obj->fk_target == $targetid && $obj->targettype == $targettype) {
3973 $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
3979 if (!empty($this->linkedObjectsIds)) {
3980 $tmparray = $this->linkedObjectsIds;
3981 foreach ($tmparray as $objecttype => $objectids) {
3983 $module = $element = $subelement = $objecttype;
3985 if ($objecttype !=
'supplier_proposal' && $objecttype !=
'order_supplier' && $objecttype !=
'invoice_supplier'
3986 && preg_match(
'/^([^_]+)_([^_]+)/i', $objecttype, $regs)) {
3987 $module = $element = $regs[1];
3988 $subelement = $regs[2];
3991 $classpath = $element.
'/class';
3993 if ($objecttype ==
'facture') {
3994 $classpath =
'compta/facture/class';
3995 } elseif ($objecttype ==
'facturerec') {
3996 $classpath =
'compta/facture/class';
3997 $module =
'facture';
3998 } elseif ($objecttype ==
'propal') {
3999 $classpath =
'comm/propal/class';
4000 } elseif ($objecttype ==
'supplier_proposal') {
4001 $classpath =
'supplier_proposal/class';
4002 } elseif ($objecttype ==
'shipping') {
4003 $classpath =
'expedition/class';
4004 $subelement =
'expedition';
4005 $module =
'expedition';
4006 } elseif ($objecttype ==
'delivery') {
4007 $classpath =
'delivery/class';
4008 $subelement =
'delivery';
4009 $module =
'delivery_note';
4010 } elseif ($objecttype ==
'invoice_supplier' || $objecttype ==
'order_supplier') {
4011 $classpath =
'fourn/class';
4012 $module =
'fournisseur';
4013 } elseif ($objecttype ==
'fichinter') {
4014 $classpath =
'fichinter/class';
4015 $subelement =
'fichinter';
4016 $module =
'ficheinter';
4017 } elseif ($objecttype ==
'subscription') {
4018 $classpath =
'adherents/class';
4019 $module =
'adherent';
4020 } elseif ($objecttype ==
'contact') {
4021 $module =
'societe';
4024 $classfile = strtolower($subelement);
4025 $classname = ucfirst($subelement);
4027 if ($objecttype ==
'order') {
4028 $classfile =
'commande';
4029 $classname =
'Commande';
4030 } elseif ($objecttype ==
'invoice_supplier') {
4031 $classfile =
'fournisseur.facture';
4032 $classname =
'FactureFournisseur';
4033 } elseif ($objecttype ==
'order_supplier') {
4034 $classfile =
'fournisseur.commande';
4035 $classname =
'CommandeFournisseur';
4036 } elseif ($objecttype ==
'supplier_proposal') {
4037 $classfile =
'supplier_proposal';
4038 $classname =
'SupplierProposal';
4039 } elseif ($objecttype ==
'facturerec') {
4040 $classfile =
'facture-rec';
4041 $classname =
'FactureRec';
4042 } elseif ($objecttype ==
'subscription') {
4043 $classfile =
'subscription';
4044 $classname =
'Subscription';
4045 } elseif ($objecttype ==
'project' || $objecttype ==
'projet') {
4046 $classpath =
'projet/class';
4047 $classfile =
'project';
4048 $classname =
'Project';
4049 } elseif ($objecttype ==
'conferenceorboothattendee') {
4050 $classpath =
'eventorganization/class';
4051 $classfile =
'conferenceorboothattendee';
4052 $classname =
'ConferenceOrBoothAttendee';
4053 $module =
'eventorganization';
4054 } elseif ($objecttype ==
'conferenceorbooth') {
4055 $classpath =
'eventorganization/class';
4056 $classfile =
'conferenceorbooth';
4057 $classname =
'ConferenceOrBooth';
4058 $module =
'eventorganization';
4059 } elseif ($objecttype ==
'mo') {
4060 $classpath =
'mrp/class';
4067 if (
isModEnabled($module) && (($element != $this->element) || $alsosametype)) {
4068 if ($loadalsoobjects && (is_numeric($loadalsoobjects) || ($loadalsoobjects === $objecttype))) {
4071 if (class_exists($classname)) {
4072 foreach ($objectids as $i => $objectid) {
4073 $object =
new $classname($this->db);
4074 $ret = $object->fetch($objectid);
4076 $this->linkedObjects[$objecttype][$i] = $object;
4082 unset($this->linkedObjectsIds[$objecttype]);
4101 if ($this->
id > 0 && !empty($this->linkedObjectsFullLoaded[$this->
id])) {
4102 unset($this->linkedObjectsFullLoaded[$this->
id]);
4120 public function updateObjectLinked($sourceid =
null, $sourcetype =
'', $targetid =
null, $targettype =
'', $f_user =
null, $notrigger = 0)
4123 $updatesource =
false;
4124 $updatetarget =
false;
4125 $f_user = isset($f_user) ? $f_user : $user;
4127 if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) {
4128 $updatesource =
true;
4129 } elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) {
4130 $updatetarget =
true;
4136 $sql =
"UPDATE " . $this->db->prefix() .
"element_element SET ";
4137 if ($updatesource) {
4138 $sql .=
"fk_source = " . ((int) $sourceid);
4139 $sql .=
", sourcetype = '" . $this->db->escape($sourcetype) .
"'";
4140 $sql .=
" WHERE fk_target = " . ((int) $this->
id);
4141 $sql .=
" AND targettype = '" . $this->db->escape($this->element) .
"'";
4142 } elseif ($updatetarget) {
4143 $sql .=
"fk_target = " . ((int) $targetid);
4144 $sql .=
", targettype = '" . $this->db->escape($targettype) .
"'";
4145 $sql .=
" WHERE fk_source = " . ((int) $this->
id);
4146 $sql .=
" AND sourcetype = '" . $this->db->escape($this->element) .
"'";
4149 dol_syslog(get_class($this) .
"::updateObjectLinked", LOG_DEBUG);
4150 if ($this->db->query(
$sql)) {
4153 $this->context[
'link_source_id'] = $sourceid;
4154 $this->context[
'link_source_type'] = $sourcetype;
4155 $this->context[
'link_target_id'] = $targetid;
4156 $this->context[
'link_target_type'] = $targettype;
4157 $result = $this->call_trigger(
'OBJECT_LINK_MODIFY', $f_user);
4164 $this->error = $this->db->lasterror();
4169 $this->db->commit();
4172 $this->db->rollback();
4190 public function deleteObjectLinked($sourceid =
null, $sourcetype =
'', $targetid =
null, $targettype =
'', $rowid =
'', $f_user =
null, $notrigger = 0)
4193 $deletesource =
false;
4194 $deletetarget =
false;
4195 $f_user = isset($f_user) ? $f_user : $user;
4197 if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) {
4198 $deletesource =
true;
4199 } elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) {
4200 $deletetarget =
true;
4203 $sourceid = (!empty($sourceid) ? $sourceid : $this->id);
4204 $sourcetype = (!empty($sourcetype) ? $sourcetype : $this->element);
4205 $targetid = (!empty($targetid) ? $targetid : $this->id);
4206 $targettype = (!empty($targettype) ? $targettype : $this->element);
4212 $this->context[
'link_id'] = $rowid;
4213 $this->context[
'link_source_id'] = $sourceid;
4214 $this->context[
'link_source_type'] = $sourcetype;
4215 $this->context[
'link_target_id'] = $targetid;
4216 $this->context[
'link_target_type'] = $targettype;
4217 $result = $this->call_trigger(
'OBJECT_LINK_DELETE', $f_user);
4225 $sql =
"DELETE FROM " . $this->db->prefix() .
"element_element";
4228 $sql .=
" rowid = " . ((int) $rowid);
4230 if ($deletesource) {
4231 $sql .=
" fk_source = " . ((int) $sourceid) .
" AND sourcetype = '" . $this->db->escape($sourcetype) .
"'";
4232 $sql .=
" AND fk_target = " . ((int) $this->
id) .
" AND targettype = '" . $this->db->escape($this->element) .
"'";
4233 } elseif ($deletetarget) {
4234 $sql .=
" fk_target = " . ((int) $targetid) .
" AND targettype = '" . $this->db->escape($targettype) .
"'";
4235 $sql .=
" AND fk_source = " . ((int) $this->
id) .
" AND sourcetype = '" . $this->db->escape($this->element) .
"'";
4237 $sql .=
" (fk_source = " . ((int) $this->
id) .
" AND sourcetype = '" . $this->db->escape($this->element) .
"')";
4239 $sql .=
" (fk_target = " . ((int) $this->
id) .
" AND targettype = '" . $this->db->escape($this->element) .
"')";
4243 dol_syslog(get_class($this) .
"::deleteObjectLinked", LOG_DEBUG);
4244 if (!$this->db->query(
$sql)) {
4245 $this->error = $this->db->lasterror();
4246 $this->errors[] = $this->error;
4252 $this->db->commit();
4255 $this->db->rollback();
4271 if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
4277 $sql =
"SELECT ".$field_select.
" FROM ".$db->prefix().$table_element.
" WHERE ".$field_where.
" = ".((int) $fk_object_where);
4278 $resql = $db->query(
$sql);
4281 if (!empty($resql)) {
4282 while ($res = $db->fetch_object($resql)) {
4283 $TRes[] = $res->{$field_select};
4300 if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
4306 $sql =
"DELETE FROM ".$db->prefix().$table_element.
" WHERE ".$field_where.
" = ".((int) $fk_object_where);
4307 $resql = $db->query(
$sql);
4309 if (empty($resql)) {
4326 public function setStatut($status, $elementId =
null, $elementType =
'', $trigkey =
'', $fieldstatus =
'fk_statut')
4328 global $user, $langs, $conf;
4330 $savElementId = $elementId;
4332 $elementId = (!empty($elementId) ? $elementId : $this->id);
4333 $elementTable = (!empty($elementType) ? $elementType : $this->table_element);
4337 if ($elementTable ==
'facture_rec') {
4338 $fieldstatus =
"suspended";
4340 if ($elementTable ==
'mailing') {
4341 $fieldstatus =
"statut";
4343 if ($elementTable ==
'cronjob') {
4344 $fieldstatus =
"status";
4346 if ($elementTable ==
'user') {
4347 $fieldstatus =
"statut";
4349 if ($elementTable ==
'expensereport') {
4350 $fieldstatus =
"fk_statut";
4352 if ($elementTable ==
'commande_fournisseur_dispatch') {
4353 $fieldstatus =
"status";
4355 if (isset($this->fields) && is_array($this->fields) && array_key_exists(
'status', $this->fields)) {
4356 $fieldstatus =
'status';
4359 $sql =
"UPDATE ".$this->db->prefix().$elementTable;
4360 $sql .=
" SET ".$fieldstatus.
" = ".((int) $status);
4363 if ($status == 1 && in_array($elementTable, array(
'expensereport',
'inventory'))) {
4364 $sql .=
", fk_user_valid = ".((int) $user->id);
4366 if ($status == 1 && in_array($elementTable, array(
'expensereport'))) {
4367 $sql .=
", date_valid = '".$this->db->idate(
dol_now()).
"'";
4369 if ($status == 1 && in_array($elementTable, array(
'inventory'))) {
4370 $sql .=
", date_validation = '".$this->db->idate(
dol_now()).
"'";
4372 $sql .=
" WHERE rowid = ".((int) $elementId);
4373 $sql .=
" AND ".$fieldstatus.
" <> ".((int) $status);
4375 dol_syslog(get_class($this).
"::setStatut", LOG_DEBUG);
4376 $resql = $this->db->query(
$sql);
4380 $nb_rows_affected = $this->db->affected_rows($resql);
4382 if ($nb_rows_affected > 0) {
4383 if (empty($trigkey)) {
4385 if ($this->element ==
'supplier_proposal' && $status == 2) {
4386 $trigkey =
'SUPPLIER_PROPOSAL_SIGN';
4388 if ($this->element ==
'supplier_proposal' && $status == 3) {
4389 $trigkey =
'SUPPLIER_PROPOSAL_REFUSE';
4391 if ($this->element ==
'supplier_proposal' && $status == 4) {
4392 $trigkey =
'SUPPLIER_PROPOSAL_CLOSE';
4394 if ($this->element ==
'fichinter' && $status == 3) {
4395 $trigkey =
'FICHINTER_CLASSIFY_DONE';
4397 if ($this->element ==
'fichinter' && $status == 2) {
4398 $trigkey =
'FICHINTER_CLASSIFY_BILLED';
4400 if ($this->element ==
'fichinter' && $status == 1) {
4401 $trigkey =
'FICHINTER_CLASSIFY_UNBILLED';
4407 $result = $this->call_trigger($trigkey, $user);
4418 $this->db->commit();
4420 if (empty($savElementId)) {
4422 if ($fieldstatus ==
'tosell') {
4423 $this->status = $status;
4424 } elseif ($fieldstatus ==
'tobuy') {
4425 $this->status_buy = $status;
4427 $this->statut = $status;
4428 $this->status = $status;
4434 $this->db->rollback();
4435 dol_syslog(get_class($this).
"::setStatut ".$this->error, LOG_ERR);
4439 $this->error = $this->db->lasterror();
4440 $this->db->rollback();
4457 if (empty($id) && empty($ref)) {
4460 if (!empty($conf->global->MAIN_DISABLE_CANVAS)) {
4467 $sql =
"SELECT rowid, canvas";
4468 $sql .=
" FROM ".$this->db->prefix().$this->table_element;
4469 $sql .=
" WHERE entity IN (".getEntity($this->element).
")";
4471 $sql .=
" AND rowid = ".((int) $id);
4474 $sql .=
" AND ref = '".$this->db->escape($ref).
"'";
4477 $resql = $this->db->query(
$sql);
4479 $obj = $this->db->fetch_object($resql);
4481 $this->canvas = $obj->canvas;
4501 $sql =
"SELECT special_code FROM ".$this->db->prefix().$this->table_element_line;
4502 $sql .=
" WHERE rowid = ".((int) $lineid);
4503 $resql = $this->db->query(
$sql);
4505 $row = $this->db->fetch_row($resql);
4529 if (!isset($this->childtables) || !is_array($this->childtables) || count($this->childtables) == 0) {
4530 dol_print_error(
'Called isObjectUsed on a class with property this->childtables not defined');
4534 $arraytoscan = $this->childtables;
4536 $tmparray = array_keys($this->childtables);
4537 if (is_numeric($tmparray[0])) {
4538 $arraytoscan = array_flip($this->childtables);
4543 foreach ($arraytoscan as $table => $element) {
4546 $sql =
"SELECT COUNT(*) as nb";
4547 $sql.=
" FROM ".$this->db->prefix().$table.
" as c";
4548 if (!empty($element[
'parent']) && !empty($element[
'parentkey'])) {
4549 $sql.=
", ".$this->db->prefix().$element[
'parent'].
" as p";
4551 if (!empty($element[
'fk_element'])) {
4552 $sql.=
" WHERE c.".$element[
'fk_element'].
" = ".((int) $id);
4554 $sql.=
" WHERE c.".$this->fk_element.
" = ".((int) $id);
4556 if (!empty($element[
'parent']) && !empty($element[
'parentkey'])) {
4557 $sql.=
" AND c.".$element[
'parentkey'].
" = p.rowid";
4559 if (!empty($element[
'parent']) && !empty($element[
'parenttypefield']) && !empty($element[
'parenttypevalue'])) {
4560 $sql.=
" AND c.".$element[
'parenttypefield'].
" = '".$this->db->escape($element[
'parenttypevalue']).
"'";
4562 if (!empty($entity)) {
4563 if (!empty($element[
'parent']) && !empty($element[
'parentkey'])) {
4564 $sql.=
" AND p.entity = ".((int) $entity);
4566 $sql.=
" AND c.entity = ".((int) $entity);
4570 $resql = $this->db->query(
$sql);
4572 $obj = $this->db->fetch_object($resql);
4574 $langs->load(
"errors");
4576 $haschild += $obj->nb;
4577 if (is_numeric($element)) {
4578 $this->errors[] = $langs->transnoentitiesnoconv(
"ErrorRecordHasAtLeastOneChildOfType", method_exists($this,
'getNomUrl') ? $this->getNomUrl() : $this->ref, $table);
4579 } elseif (is_string($element)) {
4580 $this->errors[] = $langs->transnoentitiesnoconv(
"ErrorRecordHasAtLeastOneChildOfType", method_exists($this,
'getNomUrl') ? $this->getNomUrl() : $this->
ref, $langs->transnoentitiesnoconv($element));
4582 $this->errors[] = $langs->transnoentitiesnoconv(
"ErrorRecordHasAtLeastOneChildOfType", method_exists($this,
'getNomUrl') ? $this->getNomUrl() : $this->
ref, $langs->transnoentitiesnoconv($element[
'name']));
4587 $this->errors[] = $this->db->lasterror();
4591 if ($haschild > 0) {
4592 $this->errors[] =
"ErrorRecordHasChildren";
4609 foreach ($this->lines as $key => $val) {
4611 if ($predefined == -1) {
4614 if ($predefined == 1 && $val->fk_product > 0) {
4617 if ($predefined == 0 && $val->fk_product <= 0) {
4620 if ($predefined == 2 && $val->fk_product > 0 && $val->product_type == 0) {
4623 if ($predefined == 3 && $val->fk_product > 0 && $val->product_type == 1) {
4630 dol_syslog(get_class($this).
'::hasProductsOrServices we found '.$nb.
' qualified lines of products/servcies');
4641 if (!empty($this->table_element_line) ) {
4642 $total_discount = 0.00;
4644 $sql =
"SELECT subprice as pu_ht, qty, remise_percent, total_ht";
4645 $sql .=
" FROM ".$this->db->prefix().$this->table_element_line;
4646 $sql .=
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
4648 dol_syslog(get_class($this).
'::getTotalDiscount', LOG_DEBUG);
4649 $resql = $this->db->query(
$sql);
4651 $num = $this->db->num_rows($resql);
4654 $obj = $this->db->fetch_object($resql);
4656 $pu_ht = $obj->pu_ht;
4658 $total_ht = $obj->total_ht;
4660 $total_discount_line = floatval(
price2num(($pu_ht * $qty) - $total_ht,
'MT'));
4661 $total_discount += $total_discount_line;
4690 foreach ($this->lines as $line) {
4691 if (isset($line->qty_asked)) {
4692 if (empty($totalOrdered)) {
4695 $totalOrdered += $line->qty_asked;
4697 if (isset($line->qty_shipped)) {
4698 if (empty($totalToShip)) {
4701 $totalToShip += $line->qty_shipped;
4702 } elseif ($line->element ==
'commandefournisseurdispatch' && isset($line->qty)) {
4703 if (empty($totalToShip)) {
4706 $totalToShip += $line->qty;
4710 if ($this->element ==
'shipping') {
4712 $qty = $line->qty_shipped ? $line->qty_shipped : 0;
4714 $qty = $line->qty ? $line->qty : 0;
4717 $weight = !empty($line->weight) ? $line->weight : 0;
4718 ($weight == 0 && !empty($line->product->weight)) ? $weight = $line->product->weight : 0;
4719 $volume = !empty($line->volume) ? $line->volume : 0;
4720 ($volume == 0 && !empty($line->product->volume)) ? $volume = $line->product->volume : 0;
4722 $weight_units = !empty($line->weight_units) ? $line->weight_units : 0;
4723 ($weight_units == 0 && !empty($line->product->weight_units)) ? $weight_units = $line->product->weight_units : 0;
4724 $volume_units = !empty($line->volume_units) ? $line->volume_units : 0;
4725 ($volume_units == 0 && !empty($line->product->volume_units)) ? $volume_units = $line->product->volume_units : 0;
4729 if (!empty($weight_units)) {
4730 $weightUnit = $weight_units;
4732 if (!empty($volume_units)) {
4733 $volumeUnit = $volume_units;
4736 if (empty($totalWeight)) {
4739 if (empty($totalVolume)) {
4744 if ($weight_units < 50) {
4745 $trueWeightUnit = pow(10, $weightUnit);
4746 $totalWeight += $weight * $qty * $trueWeightUnit;
4748 if ($weight_units == 99) {
4750 $trueWeightUnit = 0.45359237;
4751 $totalWeight += $weight * $qty * $trueWeightUnit;
4752 } elseif ($weight_units == 98) {
4754 $trueWeightUnit = 0.0283495;
4755 $totalWeight += $weight * $qty * $trueWeightUnit;
4757 $totalWeight += $weight * $qty;
4760 if ($volume_units < 50) {
4762 $trueVolumeUnit = pow(10, $volumeUnit);
4764 $totalVolume += $volume * $qty * $trueVolumeUnit;
4766 $totalVolume += $volume * $qty;
4770 return array(
'weight'=>$totalWeight,
'volume'=>$totalVolume,
'ordered'=>$totalOrdered,
'toship'=>$totalToShip);
4783 $extraparams = (!empty($this->extraparams) ? json_encode($this->extraparams) :
null);
4785 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
4786 $sql .=
" SET extraparams = ".(!empty($extraparams) ?
"'".$this->db->escape($extraparams).
"'" :
"null");
4787 $sql .=
" WHERE rowid = ".((int) $this->
id);
4789 dol_syslog(get_class($this).
"::setExtraParameters", LOG_DEBUG);
4790 $resql = $this->db->query(
$sql);
4792 $this->error = $this->db->lasterror();
4793 $this->db->rollback();
4796 $this->db->commit();
4819 global $conf, $user, $langs, $object, $hookmanager, $extrafields;
4823 if (!is_object($extrafields)) {
4824 require_once DOL_DOCUMENT_ROOT.
'/core/class/extrafields.class.php';
4827 $extrafields->fetch_name_optionals_label($this->table_element_line);
4832 $dirtpls = array_merge($conf->modules_parts[
'tpl'], array($defaulttpldir));
4833 foreach ($dirtpls as $module => $reldir) {
4834 if (!empty($module)) {
4837 $tpl = DOL_DOCUMENT_ROOT.$reldir.
'/objectline_create.tpl.php';
4840 if (empty($conf->file->strict_mode)) {
4841 $res = @include $tpl;
4843 $res = include $tpl;
4870 public function printObjectLines($action, $seller, $buyer, $selected = 0, $dateSelector = 0, $defaulttpldir =
'/core/tpl')
4872 global $conf, $hookmanager, $langs, $user,
$form, $extrafields, $object;
4874 global $inputalsopricewithtax, $usemargins, $disableedit, $disablemove, $disableremove, $outputalsopricetotalwithtax;
4878 if (
isModEnabled(
'margin') && !empty($this->element) && in_array($this->element, array(
'facture',
'facturerec',
'propal',
'commande'))) {
4882 $num = count($this->lines);
4885 if (!is_object($extrafields)) {
4886 require_once DOL_DOCUMENT_ROOT.
'/core/class/extrafields.class.php';
4889 $extrafields->fetch_name_optionals_label($this->table_element_line);
4891 $parameters = array(
'num'=>$num,
'dateSelector'=>$dateSelector,
'seller'=>$seller,
'buyer'=>$buyer,
'selected'=>$selected,
'table_element_line'=>$this->table_element_line);
4892 $reshook = $hookmanager->executeHooks(
'printObjectLineTitle', $parameters, $this, $action);
4893 if (empty($reshook)) {
4897 $dirtpls = array_merge($conf->modules_parts[
'tpl'], array($defaulttpldir));
4898 foreach ($dirtpls as $module => $reldir) {
4900 if (!empty($module)) {
4903 $tpl = DOL_DOCUMENT_ROOT.$reldir.
'/objectline_title.tpl.php';
4905 if (file_exists($tpl)) {
4906 if (empty($conf->file->strict_mode)) {
4907 $res = @include $tpl;
4909 $res = include $tpl;
4920 print
"<!-- begin printObjectLines() --><tbody>\n";
4921 foreach ($this->lines as $line) {
4923 $line->fetch_optionals();
4926 if (is_object($hookmanager)) {
4927 if (empty($line->fk_parent_line)) {
4928 $parameters = array(
'line'=>$line,
'num'=>$num,
'i'=>$i,
'dateSelector'=>$dateSelector,
'seller'=>$seller,
'buyer'=>$buyer,
'selected'=>$selected,
'table_element_line'=>$line->table_element);
4929 $reshook = $hookmanager->executeHooks(
'printObjectLine', $parameters, $this, $action);
4931 $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);
4932 $reshook = $hookmanager->executeHooks(
'printObjectSubLine', $parameters, $this, $action);
4935 if (empty($reshook)) {
4936 $this->printObjectLine($action, $line,
'', $num, $i, $dateSelector, $seller, $buyer, $selected, $extrafields, $defaulttpldir);
4941 print
"</tbody><!-- end printObjectLines() -->\n";
4961 public function printObjectLine($action, $line, $var, $num, $i, $dateSelector, $seller, $buyer, $selected = 0, $extrafields =
null, $defaulttpldir =
'/core/tpl')
4963 global $conf, $langs, $user, $object, $hookmanager;
4965 global $object_rights, $disableedit, $disablemove, $disableremove;
4967 $object_rights = $this->getRights();
4973 if ($action !=
'editline' || $selected != $line->id) {
4975 if (!empty($line->fk_product) && $line->fk_product > 0) {
4976 $product_static =
new Product($this->db);
4977 $product_static->fetch($line->fk_product);
4979 $product_static->ref = $line->ref;
4980 $product_static->label = !empty($line->label) ? $line->label :
"";
4982 $text = $product_static->getNomUrl(1);
4986 if (property_exists($this,
'socid') && !is_object($this->thirdparty)) {
4987 dol_print_error(
'',
'Error: Method printObjectLine was called on an object and object->fetch_thirdparty was not done before');
4991 $prod =
new Product($this->db);
4992 $prod->fetch($line->fk_product);
4994 $outputlangs = $langs;
4996 if (empty($newlang) &&
GETPOST(
'lang_id',
'aZ09')) {
4997 $newlang =
GETPOST(
'lang_id',
'aZ09');
4999 if (!empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE) && empty($newlang) && is_object($this->thirdparty)) {
5000 $newlang = $this->thirdparty->default_lang;
5002 if (!empty($newlang)) {
5003 $outputlangs =
new Translate(
"", $conf);
5004 $outputlangs->setDefaultLang($newlang);
5007 $label = (!empty($prod->multilangs[$outputlangs->defaultlang][
"label"])) ? $prod->multilangs[$outputlangs->defaultlang][
"label"] : $line->product_label;
5009 $label = $line->product_label;
5012 $text .=
' - '.(!empty($line->label) ? $line->label : $label);
5013 $description .= (
getDolGlobalInt(
'PRODUIT_DESC_IN_FORM_ACCORDING_TO_DEVICE') ?
'' : (!empty($line->description) ?
dol_htmlentitiesbr($line->description) :
''));
5016 $line->pu_ttc =
price2num((!empty($line->subprice) ? $line->subprice : 0) * (1 + ((!empty($line->tva_tx) ? $line->tva_tx : 0) / 100)),
'MU');
5021 $dirtpls = array_merge($conf->modules_parts[
'tpl'], array($defaulttpldir));
5022 foreach ($dirtpls as $module => $reldir) {
5024 if (!empty($module)) {
5027 $tpl = DOL_DOCUMENT_ROOT.$reldir.
'/objectline_view.tpl.php';
5029 if (file_exists($tpl)) {
5030 if (empty($conf->file->strict_mode)) {
5031 $res = @include $tpl;
5033 $res = include $tpl;
5043 if ($this->statut == 0 && $action ==
'editline' && $selected == $line->id) {
5044 $label = (!empty($line->label) ? $line->label : (($line->fk_product > 0) ? $line->product_label :
''));
5046 $line->pu_ttc =
price2num($line->subprice * (1 + ($line->tva_tx / 100)),
'MU');
5051 $dirtpls = array_merge($conf->modules_parts[
'tpl'], array($defaulttpldir));
5052 foreach ($dirtpls as $module => $reldir) {
5053 if (!empty($module)) {
5056 $tpl = DOL_DOCUMENT_ROOT.$reldir.
'/objectline_edit.tpl.php';
5059 if (empty($conf->file->strict_mode)) {
5060 $res = @include $tpl;
5062 $res = include $tpl;
5087 global $langs, $hookmanager, $conf,
$form, $action;
5089 print
'<tr class="liste_titre">';
5090 print
'<td class="linecolref">'.$langs->trans(
'Ref').
'</td>';
5091 print
'<td class="linecoldescription">'.$langs->trans(
'Description').
'</td>';
5092 print
'<td class="linecolvat right">'.$langs->trans(
'VATRate').
'</td>';
5093 print
'<td class="linecoluht right">'.$langs->trans(
'PriceUHT').
'</td>';
5095 print
'<td class="linecoluht_currency right">'.$langs->trans(
'PriceUHTCurrency').
'</td>';
5097 print
'<td class="linecolqty right">'.$langs->trans(
'Qty').
'</td>';
5099 print
'<td class="linecoluseunit left">'.$langs->trans(
'Unit').
'</td>';
5101 print
'<td class="linecoldiscount right">'.$langs->trans(
'ReductionShort').
'</td>';
5102 print
'<td class="linecolht right">'.$langs->trans(
'TotalHT').
'</td>';
5103 print
'<td class="center">'.$form->showCheckAddButtons(
'checkforselect', 1).
'</td>';
5107 if (!empty($this->lines)) {
5108 foreach ($this->lines as $line) {
5111 if (is_object($hookmanager)) {
5112 $parameters = array(
'line'=>$line,
'i'=>$i,
'restrictlist'=>$restrictlist,
'selectedLines'=> $selectedLines);
5113 if (!empty($line->fk_parent_line)) { $parameters[
'fk_parent_line'] = $line->fk_parent_line; }
5114 $reshook = $hookmanager->executeHooks(
'printOriginObjectLine', $parameters, $this, $action);
5116 if (empty($reshook)) {
5117 $this->printOriginLine($line,
'', $restrictlist,
'/core/tpl', $selectedLines);
5138 public function printOriginLine($line, $var, $restrictlist =
'', $defaulttpldir =
'/core/tpl', $selectedLines = array())
5140 global $langs, $conf;
5143 if (!empty($line->date_start)) {
5144 $date_start = $line->date_start;
5146 $date_start = $line->date_debut_prevue;
5147 if ($line->date_debut_reel) {
5148 $date_start = $line->date_debut_reel;
5151 if (!empty($line->date_end)) {
5152 $date_end = $line->date_end;
5154 $date_end = $line->date_fin_prevue;
5155 if ($line->date_fin_reel) {
5156 $date_end = $line->date_fin_reel;
5160 $this->tpl[
'id'] = $line->id;
5162 $this->tpl[
'label'] =
'';
5163 if (!empty($line->fk_parent_line)) {
5164 $this->tpl[
'label'] .=
img_picto(
'',
'rightarrow');
5167 if (($line->info_bits & 2) == 2) {
5169 $discount->fk_soc = $this->socid;
5170 $this->tpl[
'label'] .= $discount->getNomUrl(0,
'discount');
5171 } elseif (!empty($line->fk_product)) {
5172 $productstatic =
new Product($this->db);
5173 $productstatic->id = $line->fk_product;
5174 $productstatic->ref = $line->ref;
5175 $productstatic->type = $line->fk_product_type;
5176 if (empty($productstatic->ref)) {
5177 $line->fetch_product();
5178 $productstatic = $line->product;
5181 $this->tpl[
'label'] .= $productstatic->getNomUrl(1);
5182 $this->tpl[
'label'] .=
' - '.(!empty($line->label) ? $line->label : $line->product_label);
5184 if ($line->product_type == 1 && ($date_start || $date_end)) {
5188 $this->tpl[
'label'] .= ($line->product_type == -1 ?
' ' : ($line->product_type == 1 ?
img_object($langs->trans(
''),
'service') :
img_object($langs->trans(
''),
'product')));
5189 if (!empty($line->desc)) {
5190 $this->tpl[
'label'] .= $line->desc;
5192 $this->tpl[
'label'] .= ($line->label ?
' '.$line->label :
'');
5196 if ($line->product_type == 1 && ($date_start || $date_end)) {
5201 if (!empty($line->desc)) {
5202 if ($line->desc ==
'(CREDIT_NOTE)') {
5204 $discount->fetch($line->fk_remise_except);
5205 $this->tpl[
'description'] = $langs->transnoentities(
"DiscountFromCreditNote", $discount->getNomUrl(0));
5206 } elseif ($line->desc ==
'(DEPOSIT)') {
5208 $discount->fetch($line->fk_remise_except);
5209 $this->tpl[
'description'] = $langs->transnoentities(
"DiscountFromDeposit", $discount->getNomUrl(0));
5210 } elseif ($line->desc ==
'(EXCESS RECEIVED)') {
5212 $discount->fetch($line->fk_remise_except);
5213 $this->tpl[
'description'] = $langs->transnoentities(
"DiscountFromExcessReceived", $discount->getNomUrl(0));
5214 } elseif ($line->desc ==
'(EXCESS PAID)') {
5216 $discount->fetch($line->fk_remise_except);
5217 $this->tpl[
'description'] = $langs->transnoentities(
"DiscountFromExcessPaid", $discount->getNomUrl(0));
5219 $this->tpl[
'description'] =
dol_trunc($line->desc, 60);
5222 $this->tpl[
'description'] =
' ';
5226 $this->tpl[
'vat_rate'] =
vatrate($line->tva_tx,
true);
5227 $this->tpl[
'vat_rate'] .= (($line->info_bits & 1) == 1) ?
'*' :
'';
5228 if (!empty($line->vat_src_code) && !preg_match(
'/\(/', $this->tpl[
'vat_rate'])) {
5229 $this->tpl[
'vat_rate'] .=
' ('.$line->vat_src_code.
')';
5232 $this->tpl[
'price'] =
price($line->subprice);
5233 $this->tpl[
'total_ht'] =
price($line->total_ht);
5234 $this->tpl[
'multicurrency_price'] =
price($line->multicurrency_subprice);
5235 $this->tpl[
'qty'] = (($line->info_bits & 2) != 2) ? $line->qty :
' ';
5237 $this->tpl[
'unit'] = $langs->transnoentities($line->getLabelOfUnit(
'long'));
5239 $this->tpl[
'remise_percent'] = (($line->info_bits & 2) != 2) ?
vatrate($line->remise_percent,
true) :
' ';
5242 $this->tpl[
'strike'] = 0;
5244 $this->tpl[
'strike'] = 1;
5249 $dirtpls = array_merge($conf->modules_parts[
'tpl'], array($defaulttpldir));
5250 foreach ($dirtpls as $module => $reldir) {
5251 if (!empty($module)) {
5254 $tpl = DOL_DOCUMENT_ROOT.$reldir.
'/originproductline.tpl.php';
5257 if (empty($conf->file->strict_mode)) {
5258 $res = @include $tpl;
5260 $res = include $tpl;
5285 $sql =
"INSERT INTO ".$this->db->prefix().
"element_resources (";
5286 $sql .=
"resource_id";
5287 $sql .=
", resource_type";
5288 $sql .=
", element_id";
5289 $sql .=
", element_type";
5291 $sql .=
", mandatory";
5292 $sql .=
") VALUES (";
5293 $sql .= ((int) $resource_id);
5294 $sql .=
", '".$this->db->escape($resource_type).
"'";
5295 $sql .=
", '".$this->db->escape($this->
id).
"'";
5296 $sql .=
", '".$this->db->escape($this->element).
"'";
5297 $sql .=
", '".$this->db->escape($busy).
"'";
5298 $sql .=
", '".$this->db->escape($mandatory).
"'";
5301 dol_syslog(get_class($this).
"::add_element_resource", LOG_DEBUG);
5302 if ($this->db->query(
$sql)) {
5303 $this->db->commit();
5306 $this->error = $this->db->lasterror();
5307 $this->db->rollback();
5328 $sql =
"DELETE FROM ".$this->db->prefix().
"element_resources";
5329 $sql .=
" WHERE rowid = ".((int) $rowid);
5331 dol_syslog(get_class($this).
"::delete_resource", LOG_DEBUG);
5333 $resql = $this->db->query(
$sql);
5335 $this->error = $this->db->lasterror();
5336 $this->db->rollback();
5340 $result = $this->call_trigger(strtoupper($element).
'_DELETE_RESOURCE', $user);
5342 $this->db->rollback();
5346 $this->db->commit();
5360 if (isset($this->lines) && is_array($this->lines)) {
5361 $nboflines = count($this->lines);
5362 for ($i = 0; $i < $nboflines; $i++) {
5363 $this->lines[$i] = clone $this->lines[$i];
5381 protected function commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams =
null)
5383 global $conf, $langs, $user, $hookmanager, $action;
5385 $srctemplatepath =
'';
5387 $parameters = array(
'modelspath'=>$modelspath,
'modele'=>$modele,
'outputlangs'=>$outputlangs,
'hidedetails'=>$hidedetails,
'hidedesc'=>$hidedesc,
'hideref'=>$hideref,
'moreparams'=>$moreparams);
5388 $reshook = $hookmanager->executeHooks(
'commonGenerateDocument', $parameters, $this, $action);
5390 if (!empty($reshook)) {
5394 dol_syslog(
"commonGenerateDocument modele=".$modele.
" outputlangs->defaultlang=".(is_object($outputlangs) ? $outputlangs->defaultlang :
'null'));
5396 if (empty($modele)) {
5397 $this->error =
'BadValueForParameterModele';
5402 $err = error_reporting();
5404 @set_time_limit(120);
5405 error_reporting($err);
5408 $tmp = explode(
':', $modele, 2);
5409 if (!empty($tmp[1])) {
5411 $srctemplatepath = $tmp[1];
5418 $dirmodels = array(
'/');
5419 if (is_array($conf->modules_parts[
'models'])) {
5420 $dirmodels = array_merge($dirmodels, $conf->modules_parts[
'models']);
5422 foreach ($dirmodels as $reldir) {
5423 foreach (array(
'doc',
'pdf') as $prefix) {
5424 if (in_array(get_class($this), array(
'Adherent'))) {
5426 $file = $prefix.
"_".$modele.
".class.php";
5429 $file = $prefix.
"_".$modele.
".modules.php";
5434 if (file_exists($file)) {
5436 $classname = $prefix.
'_'.$modele;
5446 $this->error = $langs->trans(
"Error").
' Failed to load doc generator with modelpaths='.$modelspath.
' - modele='.$modele;
5447 $this->errors[] = $this->error;
5457 $obj =
new $classname($this->db);
5460 if ($obj->type ==
'odt' && empty($srctemplatepath)) {
5461 $varfortemplatedir = $obj->scandir;
5462 if ($varfortemplatedir && !empty($conf->global->$varfortemplatedir)) {
5463 $dirtoscan = $conf->global->$varfortemplatedir;
5465 $listoffiles = array();
5468 $listofdir = explode(
',', $dirtoscan);
5469 foreach ($listofdir as $key => $tmpdir) {
5470 $tmpdir = trim($tmpdir);
5471 $tmpdir = preg_replace(
'/DOL_DATA_ROOT/', DOL_DATA_ROOT, $tmpdir);
5473 unset($listofdir[$key]);
5476 if (is_dir($tmpdir)) {
5477 $tmpfiles =
dol_dir_list($tmpdir,
'files', 0,
'\.od(s|t)$',
'',
'name', SORT_ASC, 0);
5478 if (count($tmpfiles)) {
5479 $listoffiles = array_merge($listoffiles, $tmpfiles);
5484 if (count($listoffiles)) {
5485 foreach ($listoffiles as $record) {
5486 $srctemplatepath = $record[
'fullname'];
5492 if (empty($srctemplatepath)) {
5493 $this->error =
'ErrorGenerationAskedForOdtTemplateWithSrcFileNotDefined';
5498 if ($obj->type ==
'odt' && !empty($srctemplatepath)) {
5500 dol_syslog(
"Failed to locate template file ".$srctemplatepath, LOG_WARNING);
5501 $this->error =
'ErrorGenerationAskedForOdtTemplateWithSrcFileNotFound';
5508 $sav_charset_output = empty($outputlangs->charset_output) ?
'' : $outputlangs->charset_output;
5510 if (in_array(get_class($this), array(
'Adherent'))) {
5511 $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath,
'member', 1,
'tmp_cards', $moreparams);
5513 $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, $hidedetails, $hidedesc, $hideref, $moreparams);
5517 if ($resultwritefile > 0) {
5518 $outputlangs->charset_output = $sav_charset_output;
5521 require_once DOL_DOCUMENT_ROOT.
'/core/lib/files.lib.php';
5525 if (!empty($obj->result[
'fullpath'])) {
5526 $destfull = $obj->result[
'fullpath'];
5529 $update_main_doc_field = 0;
5530 if (!empty($obj->update_main_doc_field)) {
5531 $update_main_doc_field = 1;
5537 $this->indexFile($destfull, $update_main_doc_field);
5540 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);
5548 $outputlangs->charset_output = $sav_charset_output;
5549 $this->error = $obj->error;
5550 $this->errors = $obj->errors;
5551 dol_syslog(
"Error generating document for ".__CLASS__.
". Error: ".$obj->error, LOG_ERR);
5565 public function indexFile($destfull, $update_main_doc_field)
5567 global $conf, $user;
5569 $upload_dir = dirname($destfull);
5570 $destfile = basename($destfull);
5571 $rel_dir = preg_replace(
'/^'.preg_quote(DOL_DATA_ROOT,
'/').
'/',
'', $upload_dir);
5573 if (!preg_match(
'/[\\/]temp[\\/]|[\\/]thumbs|\.meta$/', $rel_dir)) {
5574 $filename = basename($destfile);
5575 $rel_dir = preg_replace(
'/[\\/]$/',
'', $rel_dir);
5576 $rel_dir = preg_replace(
'/^[\\/]/',
'', $rel_dir);
5578 include_once DOL_DOCUMENT_ROOT.
'/ecm/class/ecmfiles.class.php';
5579 $ecmfile =
new EcmFiles($this->db);
5580 $result = $ecmfile->fetch(0,
'', ($rel_dir ? $rel_dir.
'/' :
'').$filename);
5583 $setsharekey =
false;
5584 if ($this->element ==
'propal' || $this->element ==
'proposal') {
5585 if (!isset($conf->global->PROPOSAL_ALLOW_ONLINESIGN) || !empty($conf->global->PROPOSAL_ALLOW_ONLINESIGN)) {
5586 $setsharekey =
true;
5588 if (!empty($conf->global->PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD)) {
5589 $setsharekey =
true;
5592 if ($this->element ==
'commande' && !empty($conf->global->ORDER_ALLOW_EXTERNAL_DOWNLOAD)) {
5593 $setsharekey =
true;
5595 if ($this->element ==
'facture' && !empty($conf->global->INVOICE_ALLOW_EXTERNAL_DOWNLOAD)) {
5596 $setsharekey =
true;
5598 if ($this->element ==
'bank_account' && !empty($conf->global->BANK_ACCOUNT_ALLOW_EXTERNAL_DOWNLOAD)) {
5599 $setsharekey =
true;
5601 if ($this->element ==
'product' && !empty($conf->global->PRODUCT_ALLOW_EXTERNAL_DOWNLOAD)) {
5602 $setsharekey =
true;
5604 if ($this->element ==
'contrat' && !empty($conf->global->CONTRACT_ALLOW_EXTERNAL_DOWNLOAD)) {
5605 $setsharekey =
true;
5607 if ($this->element ==
'fichinter' && !empty($conf->global->FICHINTER_ALLOW_EXTERNAL_DOWNLOAD)) {
5608 $setsharekey =
true;
5610 if ($this->element ==
'supplier_proposal' && !empty($conf->global->SUPPLIER_PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD)) {
5611 $setsharekey =
true;
5615 if (empty($ecmfile->share)) {
5616 require_once DOL_DOCUMENT_ROOT.
'/core/lib/security2.lib.php';
5623 $ecmfile->fullpath_orig =
'';
5624 $ecmfile->gen_or_uploaded =
'generated';
5625 $ecmfile->description =
'';
5626 $ecmfile->keywords =
'';
5627 $result = $ecmfile->update($user);
5633 $ecmfile->entity = $conf->entity;
5634 $ecmfile->filepath = $rel_dir;
5635 $ecmfile->filename = $filename;
5637 $ecmfile->fullpath_orig =
'';
5638 $ecmfile->gen_or_uploaded =
'generated';
5639 $ecmfile->description =
'';
5640 $ecmfile->keywords =
'';
5641 $ecmfile->src_object_type = $this->table_element;
5642 $ecmfile->src_object_id = $this->id;
5644 $result = $ecmfile->create($user);
5656 if ($update_main_doc_field && !empty($this->table_element)) {
5657 $sql =
"UPDATE ".$this->db->prefix().$this->table_element.
" SET last_main_doc = '".$this->db->escape($ecmfile->filepath.
"/".$ecmfile->filename).
"'";
5658 $sql .=
" WHERE rowid = ".((int) $this->
id);
5660 $resql = $this->db->query(
$sql);
5665 $this->last_main_doc = $ecmfile->filepath.
'/'.$ecmfile->filename;
5684 if (file_exists($file_osencoded)) {
5685 require_once DOL_DOCUMENT_ROOT.
'/core/lib/images.lib.php';
5688 $maxwidthsmall = $tmparraysize[
'maxwidthsmall'];
5689 $maxheightsmall = $tmparraysize[
'maxheightsmall'];
5690 $maxwidthmini = $tmparraysize[
'maxwidthmini'];
5691 $maxheightmini = $tmparraysize[
'maxheightmini'];
5697 vignette($file_osencoded, $maxwidthsmall, $maxheightsmall,
'_small', $quality);
5701 vignette($file_osencoded, $maxwidthmini, $maxheightmini,
'_mini', $quality);
5740 global $conf, $_POST;
5744 return GETPOST($fieldname, $type, 3);
5747 if (isset($alternatevalue)) {
5748 return $alternatevalue;
5751 $newelement = $this->element;
5752 if ($newelement ==
'facture') {
5753 $newelement =
'invoice';
5755 if ($newelement ==
'commande') {
5756 $newelement =
'order';
5758 if (empty($newelement)) {
5759 dol_syslog(
"Ask a default value using common method getDefaultCreateValueForField on an object with no property ->element defined. Return empty string.", LOG_WARNING);
5763 $keyforfieldname = strtoupper($newelement.
'_DEFAULT_'.$fieldname);
5765 if (isset($conf->global->$keyforfieldname)) {
5766 return $conf->global->$keyforfieldname;
5793 global $langs, $conf;
5794 if (!empty(self::TRIGGER_PREFIX) && strpos($triggerName, self::TRIGGER_PREFIX .
'_') !== 0) {
5795 dol_print_error(
'',
'The trigger "' . $triggerName .
'" does not start with "' . self::TRIGGER_PREFIX .
'_" as required.');
5798 if (!is_object($langs)) {
5799 include_once DOL_DOCUMENT_ROOT.
'/core/class/translate.class.php';
5803 include_once DOL_DOCUMENT_ROOT.
'/core/class/interfaces.class.php';
5805 $result = $interface->run_triggers($triggerName, $this, $user, $langs, $conf);
5808 if (!empty($this->errors)) {
5809 $this->errors = array_unique(array_merge($this->errors, $interface->errors));
5811 $this->errors = $interface->errors;
5831 if (!$this->element) {
5834 if (!($this->
id > 0)) {
5837 if (is_array($this->array_languages)) {
5841 $this->array_languages = array();
5843 $element = $this->element;
5844 if ($element ==
'categorie') {
5845 $element =
'categories';
5849 $sql =
"SELECT rowid, property, lang , value";
5850 $sql .=
" FROM ".$this->db->prefix().
"object_lang";
5851 $sql .=
" WHERE type_object = '".$this->db->escape($element).
"'";
5852 $sql .=
" AND fk_object = ".((int) $this->
id);
5855 $resql = $this->db->query(
$sql);
5857 $numrows = $this->db->num_rows($resql);
5860 while ($i < $numrows) {
5861 $obj = $this->db->fetch_object($resql);
5862 $key = $obj->property;
5863 $value = $obj->value;
5864 $codelang = $obj->lang;
5865 $type = $this->fields[$key][
'type'];
5868 if (preg_match(
'/date/', $type)) {
5869 $this->array_languages[$key][$codelang] = $this->db->jdate($value);
5871 $this->array_languages[$key][$codelang] = $value;
5878 $this->db->free($resql);
5899 global $_POST, $langs;
5902 foreach ($_POST as $postfieldkey => $postfieldvalue) {
5903 $tmparray = explode(
'-', $postfieldkey);
5904 if ($tmparray[0] !=
'field') {
5908 $element = $tmparray[1];
5909 $key = $tmparray[2];
5910 $codelang = $tmparray[3];
5913 if (!empty($onlykey) && $key != $onlykey) {
5916 if ($element != $this->element) {
5920 $key_type = $this->fields[$key][
'type'];
5923 if (isset($this->fields[$key][
'enabled'])) {
5924 $enabled =
dol_eval($this->fields[$key][
'enabled'], 1, 1,
'1');
5931 if (empty($enabled)) {
5936 if (in_array($key_type, array(
'date'))) {
5940 } elseif (in_array($key_type, array(
'datetime'))) {
5943 $value_key =
dol_mktime(
GETPOST($postfieldkey.
"hour",
'int'),
GETPOST($postfieldkey.
"min",
'int'), 0,
GETPOST($postfieldkey.
"month",
'int'),
GETPOST($postfieldkey.
"day",
'int'),
GETPOST($postfieldkey.
"year",
'int'));
5944 } elseif (in_array($key_type, array(
'checkbox',
'chkbxlst'))) {
5945 $value_arr =
GETPOST($postfieldkey,
'array');
5946 if (!empty($value_arr)) {
5947 $value_key = implode(
',', $value_arr);
5951 } elseif (in_array($key_type, array(
'price',
'double'))) {
5952 $value_arr =
GETPOST($postfieldkey,
'alpha');
5955 $value_key =
GETPOST($postfieldkey);
5956 if (in_array($key_type, array(
'link')) && $value_key ==
'-1') {
5961 $this->array_languages[$key][$codelang] = $value_key;
5986 $savDisableCompute = $conf->disable_compute;
5987 $conf->disable_compute = 1;
5989 $ret = $this->fetch($id);
5991 $conf->disable_compute = $savDisableCompute;
6009 global $conf, $extrafields;
6011 if (empty($rowid)) {
6014 if (empty($rowid) && isset($this->
rowid)) {
6015 $rowid = $this->rowid;
6019 if (!$this->table_element) {
6023 $this->array_options = array();
6025 if (!is_array($optionsArray)) {
6027 if (!isset($extrafields) || !is_object($extrafields)) {
6028 require_once DOL_DOCUMENT_ROOT.
'/core/class/extrafields.class.php';
6033 if (empty($extrafields->attributes[$this->table_element][
'loaded'])) {
6034 $extrafields->fetch_name_optionals_label($this->table_element);
6036 $optionsArray = (!empty($extrafields->attributes[$this->table_element][
'label']) ? $extrafields->attributes[$this->table_element][
'label'] :
null);
6038 global $extrafields;
6039 dol_syslog(
"Warning: fetch_optionals was called with param optionsArray defined when you should pass null now", LOG_WARNING);
6042 $table_element = $this->table_element;
6043 if ($table_element ==
'categorie') {
6044 $table_element =
'categories';
6048 if (is_array($optionsArray) && count($optionsArray) > 0) {
6049 $sql =
"SELECT rowid";
6050 foreach ($optionsArray as $name => $label) {
6051 if (empty($extrafields->attributes[$this->table_element][
'type'][$name]) || $extrafields->attributes[$this->table_element][
'type'][$name] !=
'separate') {
6055 $sql .=
" FROM ".$this->db->prefix().$table_element.
"_extrafields";
6056 $sql .=
" WHERE fk_object = ".((int) $rowid);
6059 $resql = $this->db->query(
$sql);
6061 $numrows = $this->db->num_rows($resql);
6063 $tab = $this->db->fetch_array($resql);
6065 foreach ($tab as $key => $value) {
6067 if ($key !=
'rowid' && $key !=
'tms' && $key !=
'fk_member' && !is_int($key)) {
6069 if (!empty($extrafields->attributes[$this->table_element]) && in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'date',
'datetime'))) {
6071 $this->array_options[
"options_".$key] = $this->db->jdate($value);
6073 $this->array_options[
"options_".$key] = $value;
6083 if (is_array($extrafields->attributes[$this->table_element][
'label'])) {
6084 foreach ($extrafields->attributes[$this->table_element][
'label'] as $key => $val) {
6085 if (!empty($extrafields->attributes[$this->table_element]) && !empty($extrafields->attributes[$this->table_element][
'computed'][$key])) {
6087 if (empty($conf->disable_compute)) {
6088 global $objectoffield;
6089 $objectoffield = $this;
6090 $this->array_options[
'options_' . $key] =
dol_eval($extrafields->attributes[$this->table_element][
'computed'][$key], 1, 0,
'');
6096 $this->db->free($resql);
6104 $this->errors[]=$this->db->lasterror;
6121 if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
6127 $table_element = $this->table_element;
6128 if ($table_element ==
'categorie') {
6129 $table_element =
'categories';
6132 dol_syslog(get_class($this).
"::deleteExtraFields delete", LOG_DEBUG);
6134 $sql_del =
"DELETE FROM ".$this->db->prefix().$table_element.
"_extrafields WHERE fk_object = ".((int) $this->
id);
6136 $resql = $this->db->query($sql_del);
6138 $this->error = $this->db->lasterror();
6139 $this->db->rollback();
6142 $this->db->commit();
6159 global $conf, $langs, $user;
6161 if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
6165 if (empty($userused)) {
6171 if (!empty($this->array_options)) {
6173 $langs->load(
'admin');
6174 require_once DOL_DOCUMENT_ROOT.
'/core/class/extrafields.class.php';
6176 $target_extrafields = $extrafields->fetch_name_optionals_label($this->table_element);
6179 $new_array_options = array();
6180 foreach ($this->array_options as $key => $value) {
6181 if (in_array(substr($key, 8), array_keys($target_extrafields))) {
6182 $new_array_options[$key] = $value;
6183 } elseif (in_array($key, array_keys($target_extrafields))) {
6184 $new_array_options[
'options_'.$key] = $value;
6188 foreach ($new_array_options as $key => $value) {
6189 $attributeKey = substr($key, 8);
6190 $attributeType = $extrafields->attributes[$this->table_element][
'type'][$attributeKey];
6191 $attributeLabel = $extrafields->attributes[$this->table_element][
'label'][$attributeKey];
6192 $attributeParam = $extrafields->attributes[$this->table_element][
'param'][$attributeKey];
6193 $attributeRequired = $extrafields->attributes[$this->table_element][
'required'][$attributeKey];
6194 $attributeUnique = $extrafields->attributes[$this->table_element][
'unique'][$attributeKey];
6195 $attrfieldcomputed = $extrafields->attributes[$this->table_element][
'computed'][$attributeKey];
6199 if (!empty($this->context[
'createfromclone']) && $this->context[
'createfromclone'] ==
'createfromclone' && !empty($attributeUnique)) {
6200 $new_array_options[$key] =
null;
6204 if ($attributeRequired) {
6205 $mandatorypb =
false;
6206 if ($attributeType ==
'link' && $this->array_options[$key] ==
'-1') {
6207 $mandatorypb =
true;
6209 if ($this->array_options[$key] ===
'') {
6210 $mandatorypb =
true;
6212 if ($attributeType ==
'sellist' && $this->array_options[$key] ==
'0') {
6213 $mandatorypb =
true;
6216 $langs->load(
"errors");
6217 dol_syslog(
"Mandatory field '".$key.
"' is empty during create and set to required into definition of extrafields");
6218 $this->errors[] = $langs->trans(
'ErrorFieldRequired', $attributeLabel);
6226 if (!empty($attrfieldcomputed)) {
6227 if (!empty($conf->global->MAIN_STORE_COMPUTED_EXTRAFIELDS)) {
6228 $value =
dol_eval($attrfieldcomputed, 1, 0,
'');
6229 dol_syslog($langs->trans(
"Extrafieldcomputed").
" sur ".$attributeLabel.
"(".$value.
")", LOG_DEBUG);
6230 $new_array_options[$key] = $value;
6232 $new_array_options[$key] =
null;
6236 switch ($attributeType) {
6238 if (!is_numeric($value) && $value !=
'') {
6239 $this->errors[] = $langs->trans(
"ExtraFieldHasWrongValue", $attributeLabel);
6241 } elseif ($value ==
'') {
6242 $new_array_options[$key] =
null;
6248 if (!is_numeric($value) && $value !=
'') {
6249 dol_syslog($langs->trans(
"ExtraFieldHasWrongValue").
" for ".$attributeLabel.
"(".$value.
"is not '".$attributeType.
"')", LOG_DEBUG);
6250 $this->errors[] = $langs->trans(
"ExtraFieldHasWrongValue", $attributeLabel);
6252 } elseif ($value ==
'') {
6256 $new_array_options[$key] = $value;
6266 if ($this->array_options[$key] !=
'' && is_array($extrafields->attributes[$this->table_element][
'param'][$attributeKey][
'options'])) {
6268 $tmparrays = array_keys($extrafields->attributes[$this->table_element][
'param'][$attributeKey][
'options']);
6269 $algo = reset($tmparrays);
6274 if (is_object($this->oldcopy)) {
6276 if (isset($this->oldcopy->array_options[$key]) && $this->array_options[$key] == $this->oldcopy->array_options[$key]) {
6277 $new_array_options[$key] = $this->array_options[$key];
6280 $newvalue =
dol_hash($this->array_options[$key], $algo);
6281 $new_array_options[$key] = $newvalue;
6284 $new_array_options[$key] = $this->array_options[$key];
6289 $new_array_options[$key] = $this->array_options[$key];
6295 if (!is_numeric($this->array_options[$key]) || $this->array_options[$key] != intval($this->array_options[$key])) {
6296 $this->array_options[$key] = strtotime($this->array_options[$key]);
6298 $new_array_options[$key] = $this->db->idate($this->array_options[$key]);
6302 if (!is_numeric($this->array_options[$key]) || $this->array_options[$key] != intval($this->array_options[$key])) {
6303 $this->array_options[$key] = strtotime($this->array_options[$key]);
6305 $new_array_options[$key] = $this->db->idate($this->array_options[$key],
'gmt');
6308 $param_list = array_keys($attributeParam[
'options']);
6311 $InfoFieldList = explode(
":", $param_list[0]);
6313 if ($InfoFieldList[0] && class_exists($InfoFieldList[0])) {
6314 if ($value ==
'-1') {
6315 $new_array_options[$key] =
'';
6317 $object =
new $InfoFieldList[0]($this->db);
6318 if (is_numeric($value)) {
6319 $res = $object->fetch($value);
6321 $res = $object->fetch(
'', $value);
6325 $new_array_options[$key] = $object->id;
6327 $this->error =
"Id/Ref '".$value.
"' for object '".$object->element.
"' not found";
6332 dol_syslog(
'Error bad setup of extrafield', LOG_WARNING);
6337 if (is_array($this->array_options[$key])) {
6338 $new_array_options[$key] = implode(
',', $this->array_options[$key]);
6340 $new_array_options[$key] = $this->array_options[$key];
6348 $table_element = $this->table_element;
6349 if ($table_element ==
'categorie') {
6350 $table_element =
'categories';
6353 dol_syslog(get_class($this).
"::insertExtraFields delete then insert", LOG_DEBUG);
6355 $sql_del =
"DELETE FROM ".$this->db->prefix().$table_element.
"_extrafields WHERE fk_object = ".((int) $this->
id);
6356 $this->db->query($sql_del);
6358 $sql =
"INSERT INTO ".$this->db->prefix().$table_element.
"_extrafields (fk_object";
6359 foreach ($new_array_options as $key => $value) {
6360 $attributeKey = substr($key, 8);
6362 if ($extrafields->attributes[$this->table_element][
'type'][$attributeKey] !=
'separate') {
6363 $sql .=
",".$attributeKey;
6367 if (!empty($extrafields->attributes[$this->table_element][
'mandatoryfieldsofotherentities']) && is_array($extrafields->attributes[$this->table_element][
'mandatoryfieldsofotherentities'])) {
6368 foreach ($extrafields->attributes[$this->table_element][
'mandatoryfieldsofotherentities'] as $tmpkey => $tmpval) {
6369 if (!isset($extrafields->attributes[$this->table_element][
'type'][$tmpkey])) {
6370 $sql .=
",".$tmpkey;
6374 $sql .=
") VALUES (".$this->id;
6376 foreach ($new_array_options as $key => $value) {
6377 $attributeKey = substr($key, 8);
6379 if ($extrafields->attributes[$this->table_element][
'type'][$attributeKey] !=
'separate') {
6380 if ($new_array_options[$key] !=
'' || $new_array_options[$key] ==
'0') {
6381 $sql .=
",'".$this->db->escape($new_array_options[$key]).
"'";
6388 if (!empty($extrafields->attributes[$this->table_element][
'mandatoryfieldsofotherentities']) && is_array($extrafields->attributes[$this->table_element][
'mandatoryfieldsofotherentities'])) {
6389 foreach ($extrafields->attributes[$this->table_element][
'mandatoryfieldsofotherentities'] as $tmpkey => $tmpval) {
6390 if (!isset($extrafields->attributes[$this->table_element][
'type'][$tmpkey])) {
6391 if (in_array($tmpval, array(
'int',
'double',
'price'))) {
6402 $resql = $this->db->query(
$sql);
6404 $this->error = $this->db->lasterror();
6408 if (!$error && $trigger) {
6410 $this->context = array(
'extrafieldaddupdate'=>1);
6411 $result = $this->call_trigger($trigger, $userused);
6419 $this->db->rollback();
6422 $this->db->commit();
6442 global $conf, $langs, $user;
6444 if (empty($userused)) {
6450 if (!empty($conf->global->MAIN_EXTRALANGUAGES_DISABLED)) {
6454 if (is_array($this->array_languages)) {
6455 $new_array_languages = $this->array_languages;
6457 foreach ($new_array_languages as $key => $value) {
6458 $attributeKey = $key;
6459 $attributeType = $this->fields[$attributeKey][
'type'];
6460 $attributeLabel = $this->fields[$attributeKey][
'label'];
6465 switch ($attributeType) {
6467 if (!is_numeric($value) && $value !=
'') {
6468 $this->errors[] = $langs->trans(
"ExtraLanguageHasWrongValue", $attributeLabel);
6470 } elseif ($value ==
'') {
6471 $new_array_languages[$key] =
null;
6476 if (!is_numeric($value) && $value !=
'') {
6477 dol_syslog($langs->trans(
"ExtraLanguageHasWrongValue").
" sur ".$attributeLabel.
"(".$value.
"is not '".$attributeType.
"')", LOG_DEBUG);
6478 $this->errors[] = $langs->trans(
"ExtraLanguageHasWrongValue", $attributeLabel);
6480 } elseif ($value ==
'') {
6481 $new_array_languages[$key] =
null;
6483 $new_array_languages[$key] = $value;
6497 $table_element = $this->table_element;
6498 if ($table_element ==
'categorie') {
6499 $table_element =
'categories';
6502 dol_syslog(get_class($this).
"::insertExtraLanguages delete then insert", LOG_DEBUG);
6504 foreach ($new_array_languages as $key => $langcodearray) {
6505 foreach ($langcodearray as $langcode => $value) {
6506 $sql_del =
"DELETE FROM ".$this->db->prefix().
"object_lang";
6507 $sql_del .=
" WHERE fk_object = ".((int) $this->
id).
" AND property = '".$this->db->escape($key).
"' AND type_object = '".$this->db->escape($table_element).
"'";
6508 $sql_del .=
" AND lang = '".$this->db->escape($langcode).
"'";
6509 $this->db->query($sql_del);
6511 if ($value !==
'') {
6512 $sql =
"INSERT INTO ".$this->db->prefix().
"object_lang (fk_object, property, type_object, lang, value";
6513 $sql .=
") VALUES (".$this->id.
", '".$this->db->escape($key).
"', '".$this->db->escape($table_element).
"', '".$this->db->escape($langcode).
"', '".$this->db->escape($value).
"'";
6516 $resql = $this->db->query(
$sql);
6518 $this->error = $this->db->lasterror();
6526 if (!$error && $trigger) {
6528 $this->context = array(
'extralanguagesaddupdate'=>1);
6529 $result = $this->call_trigger($trigger, $userused);
6537 $this->db->rollback();
6540 $this->db->commit();
6560 global $conf, $langs, $user;
6562 if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
6566 if (empty($userused)) {
6572 if (!empty($this->array_options) && isset($this->array_options[
"options_".$key])) {
6574 $langs->load(
'admin');
6575 require_once DOL_DOCUMENT_ROOT.
'/core/class/extrafields.class.php';
6577 $extrafields->fetch_name_optionals_label($this->table_element);
6579 $value = $this->array_options[
"options_".$key];
6581 $attributeType = $extrafields->attributes[$this->table_element][
'type'][$key];
6582 $attributeLabel = $extrafields->attributes[$this->table_element][
'label'][$key];
6583 $attributeParam = $extrafields->attributes[$this->table_element][
'param'][$key];
6584 $attributeRequired = $extrafields->attributes[$this->table_element][
'required'][$key];
6585 $attrfieldcomputed = $extrafields->attributes[$this->table_element][
'computed'][$key];
6588 if ($attributeRequired) {
6589 $mandatorypb =
false;
6590 if ($attributeType ==
'link' && $this->array_options[
"options_".$key] ==
'-1') {
6591 $mandatorypb =
true;
6593 if ($this->array_options[
"options_".$key] ===
'') {
6594 $mandatorypb =
true;
6597 $langs->load(
"errors");
6598 dol_syslog(
"Mandatory field 'options_".$key.
"' is empty during update and set to required into definition of extrafields");
6599 $this->errors[] = $langs->trans(
'ErrorFieldRequired', $attributeLabel);
6607 if (!empty($attrfieldcomputed)) {
6608 if (!empty($conf->global->MAIN_STORE_COMPUTED_EXTRAFIELDS)) {
6609 $value =
dol_eval($attrfieldcomputed, 1, 0,
'');
6610 dol_syslog($langs->trans(
"Extrafieldcomputed").
" sur ".$attributeLabel.
"(".$value.
")", LOG_DEBUG);
6611 $this->array_options[
"options_".$key] = $value;
6613 $this->array_options[
"options_".$key] =
null;
6617 switch ($attributeType) {
6619 if (!is_numeric($value) && $value !=
'') {
6620 $this->errors[] = $langs->trans(
"ExtraFieldHasWrongValue", $attributeLabel);
6622 } elseif ($value ===
'') {
6623 $this->array_options[
"options_".$key] =
null;
6628 if (!is_numeric($value) && $value !=
'') {
6629 dol_syslog($langs->trans(
"ExtraFieldHasWrongValue").
" sur ".$attributeLabel.
"(".$value.
"is not '".$attributeType.
"')", LOG_DEBUG);
6630 $this->errors[] = $langs->trans(
"ExtraFieldHasWrongValue", $attributeLabel);
6632 } elseif ($value ===
'') {
6636 $this->array_options[
"options_".$key] = $value;
6645 $this->array_options[
"options_".$key] =
price2num($this->array_options[
"options_".$key]);
6649 if (empty($this->array_options[
"options_".$key])) {
6650 $this->array_options[
"options_".$key] =
null;
6652 $this->array_options[
"options_".$key] = $this->db->idate($this->array_options[
"options_".$key]);
6656 if (empty($this->array_options[
"options_".$key])) {
6657 $this->array_options[
"options_".$key] =
null;
6659 $this->array_options[
"options_".$key] = $this->db->idate($this->array_options[
"options_".$key],
'gmt');
6663 if (empty($this->array_options[
"options_".$key])) {
6664 $this->array_options[
"options_".$key] =
null;
6668 if ($this->array_options[
"options_".$key] ===
'') {
6669 $this->array_options[
"options_".$key] =
null;
6703 if (is_array($this->array_options[$key])) {
6704 $new_array_options[$key] = implode(
',', $this->array_options[$key]);
6706 $new_array_options[$key] = $this->array_options[$key];
6713 $linealreadyfound = 0;
6716 $sql =
"SELECT COUNT(rowid) as nb FROM ".$this->db->prefix().$this->table_element.
"_extrafields WHERE fk_object = ".((int) $this->
id);
6717 $resql = $this->db->query(
$sql);
6719 $tmpobj = $this->db->fetch_object($resql);
6721 $linealreadyfound = $tmpobj->nb;
6725 if ($linealreadyfound) {
6726 if ($this->array_options[
"options_".$key] ===
null) {
6727 $sql =
"UPDATE ".$this->db->prefix().$this->table_element.
"_extrafields SET ".$key.
" = null";
6729 $sql =
"UPDATE ".$this->db->prefix().$this->table_element.
"_extrafields SET ".$key.
" = '".$this->db->escape($this->array_options[
"options_".$key]).
"'";
6731 $sql .=
" WHERE fk_object = ".((int) $this->
id);
6733 $result = $this->insertExtraFields(
'', $user);
6739 $resql = $this->db->query(
$sql);
6742 $this->error = $this->db->lasterror();
6744 if (!$error && $trigger) {
6746 $this->context = array(
'extrafieldupdate'=>1);
6747 $result = $this->call_trigger($trigger, $userused);
6755 dol_syslog(__METHOD__.$this->error, LOG_ERR);
6756 $this->db->rollback();
6759 $this->db->commit();
6779 global $conf, $langs, $user;
6781 if (empty($userused)) {
6787 if (!empty($conf->global->MAIN_EXTRALANGUAGES_DISABLED)) {
6809 public function showInputField($val, $key, $value, $moreparam =
'', $keysuffix =
'', $keyprefix =
'', $morecss = 0, $nonewbutton = 0)
6811 global $conf, $langs,
$form;
6813 if (!is_object(
$form)) {
6814 require_once DOL_DOCUMENT_ROOT.
'/core/class/html.form.class.php';
6818 if (!empty($this->fields)) {
6819 $val = $this->fields[$key];
6823 $fieldValidationErrorMsg =
'';
6824 $validationClass =
'';
6825 $fieldValidationErrorMsg = $this->getFieldError($key);
6826 if (!empty($fieldValidationErrorMsg)) {
6827 $validationClass =
' --error';
6829 $validationClass =
' --success';
6836 $param[
'options'] = array();
6838 $size = !empty($this->fields[$key][
'size']) ? $this->fields[$key][
'size'] : 0;
6840 if (preg_match(
'/^(integer|link):(.*):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
6841 $param[
'options'] = array($reg[2].
':'.$reg[3].
':'.$reg[4].
':'.$reg[5] =>
'N');
6843 } elseif (preg_match(
'/^(integer|link):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
6844 $param[
'options'] = array($reg[2].
':'.$reg[3].
':'.$reg[4] =>
'N');
6846 } elseif (preg_match(
'/^(integer|link):(.*):(.*)/i', $val[
'type'], $reg)) {
6847 $param[
'options'] = array($reg[2].
':'.$reg[3] =>
'N');
6849 } elseif (preg_match(
'/^(sellist):(.*):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
6850 $param[
'options'] = array($reg[2].
':'.$reg[3].
':'.$reg[4].
':'.$reg[5] =>
'N');
6852 } elseif (preg_match(
'/^(sellist):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
6853 $param[
'options'] = array($reg[2].
':'.$reg[3].
':'.$reg[4] =>
'N');
6855 } elseif (preg_match(
'/^(sellist):(.*):(.*)/i', $val[
'type'], $reg)) {
6856 $param[
'options'] = array($reg[2].
':'.$reg[3] =>
'N');
6858 } elseif (preg_match(
'/^chkbxlst:(.*)/i', $val[
'type'], $reg)) {
6859 $param[
'options'] = array($reg[1] =>
'N');
6861 } elseif (preg_match(
'/varchar\((\d+)\)/', $val[
'type'], $reg)) {
6862 $param[
'options'] = array();
6865 } elseif (preg_match(
'/varchar/', $val[
'type'])) {
6866 $param[
'options'] = array();
6869 $param[
'options'] = array();
6870 $type = $this->fields[$key][
'type'];
6874 if (!empty($this->fields[$key][
'arrayofkeyval']) && is_array($this->fields[$key][
'arrayofkeyval'])) {
6875 $param[
'options'] = $this->fields[$key][
'arrayofkeyval'];
6879 $label = $this->fields[$key][
'label'];
6881 $default = (!empty($this->fields[$key][
'default']) ? $this->fields[$key][
'default'] :
'');
6882 $computed = (!empty($this->fields[$key][
'computed']) ? $this->fields[$key][
'computed'] :
'');
6883 $unique = (!empty($this->fields[$key][
'unique']) ? $this->fields[$key][
'unique'] : 0);
6884 $required = (!empty($this->fields[$key][
'required']) ? $this->fields[$key][
'required'] : 0);
6885 $autofocusoncreate = (!empty($this->fields[$key][
'autofocusoncreate']) ? $this->fields[$key][
'autofocusoncreate'] : 0);
6887 $langfile = (!empty($this->fields[$key][
'langfile']) ? $this->fields[$key][
'langfile'] :
'');
6888 $list = (!empty($this->fields[$key][
'list']) ? $this->fields[$key][
'list'] : 0);
6889 $hidden = (in_array(abs($this->fields[$key][
'visible']), array(0, 2)) ? 1 : 0);
6891 $objectid = $this->id;
6894 if (!preg_match(
'/^search_/', $keyprefix)) {
6895 return '<span class="opacitymedium">'.$langs->trans(
"AutomaticallyCalculated").
'</span>';
6902 if (empty($morecss) && !empty($val[
'css'])) {
6903 $morecss = $val[
'css'];
6904 } elseif (empty($morecss)) {
6905 if ($type ==
'date') {
6906 $morecss =
'minwidth100imp';
6907 } elseif ($type ==
'datetime' || $type ==
'link') {
6908 $morecss =
'minwidth200imp';
6909 } elseif (in_array($type, array(
'int',
'integer',
'price')) || preg_match(
'/^double(\([0-9],[0-9]\)){0,1}/', $type)) {
6910 $morecss =
'maxwidth75';
6911 } elseif ($type ==
'url') {
6912 $morecss =
'minwidth400';
6913 } elseif ($type ==
'boolean') {
6916 if (round($size) < 12) {
6917 $morecss =
'minwidth100';
6918 } elseif (round($size) <= 48) {
6919 $morecss =
'minwidth200';
6921 $morecss =
'minwidth400';
6927 if (!empty($validationClass)) {
6928 $morecss.= $validationClass;
6931 if (in_array($type, array(
'date'))) {
6932 $tmp = explode(
',', $size);
6937 if (!$required && $value ==
'') {
6942 $out =
$form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required,
'', 1, (($keyprefix !=
'search_' && $keyprefix !=
'search_options_') ? 1 : 0), 0, 1);
6943 } elseif (in_array($type, array(
'datetime'))) {
6944 $tmp = explode(
',', $size);
6949 if (!$required && $value ==
'') $value =
'-1';
6952 $out =
$form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required,
'', 1, (($keyprefix !=
'search_' && $keyprefix !=
'search_options_') ? 1 : 0), 0, 1,
'',
'',
'', 1,
'',
'',
'tzuserrel');
6953 } elseif (in_array($type, array(
'duration'))) {
6954 $out =
$form->select_duration($keyprefix.$key.$keysuffix, $value, 0,
'text', 0, 1);
6955 } elseif (in_array($type, array(
'int',
'integer'))) {
6956 $tmp = explode(
',', $size);
6958 $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' :
'').
'>';
6959 } elseif (in_array($type, array(
'real'))) {
6960 $out =
'<input type="text" class="flat '.$morecss.
'" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.
dol_escape_htmltag($value).
'"'.($moreparam ? $moreparam :
'').($autofocusoncreate ?
' autofocus' :
'').
'>';
6961 } elseif (preg_match(
'/varchar/', $type)) {
6962 $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' :
'').
'>';
6963 } elseif (in_array($type, array(
'email',
'mail',
'phone',
'url',
'ip'))) {
6964 $out =
'<input type="text" class="flat '.$morecss.
'" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.
dol_escape_htmltag($value).
'" '.($moreparam ? $moreparam :
'').($autofocusoncreate ?
' autofocus' :
'').
'>';
6965 } elseif (preg_match(
'/^text/', $type)) {
6966 if (!preg_match(
'/search_/', $keyprefix)) {
6967 require_once DOL_DOCUMENT_ROOT.
'/core/class/doleditor.class.php';
6968 $doleditor =
new DolEditor($keyprefix.$key.$keysuffix, $value,
'', 200,
'dolibarr_notes',
'In',
false,
false,
false, ROWS_5,
'90%');
6969 $out = $doleditor->Create(1);
6971 $out =
'<input type="text" class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.
dol_escape_htmltag($value).
'" '.($moreparam ? $moreparam :
'').
'>';
6973 } elseif (preg_match(
'/^html/', $type)) {
6974 if (!preg_match(
'/search_/', $keyprefix)) {
6975 require_once DOL_DOCUMENT_ROOT.
'/core/class/doleditor.class.php';
6976 $doleditor =
new DolEditor($keyprefix.$key.$keysuffix, $value,
'', 200,
'dolibarr_notes',
'In',
false,
false,
isModEnabled(
'fckeditor') && $conf->global->FCKEDITOR_ENABLE_SOCIETE, ROWS_5,
'90%');
6977 $out = $doleditor->Create(1,
'',
true,
'',
'', $moreparam, $morecss);
6979 $out =
'<input type="text" class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.
dol_escape_htmltag($value).
'" '.($moreparam ? $moreparam :
'').
'>';
6981 } elseif ($type ==
'boolean') {
6983 if (!empty($value)) {
6984 $checked =
' checked value="1" ';
6986 $checked =
' value="1" ';
6988 $out =
'<input type="checkbox" class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" '.$checked.
' '.($moreparam ? $moreparam :
'').
'>';
6989 } elseif ($type ==
'price') {
6990 if (!empty($value)) {
6991 $value =
price($value);
6993 $out =
'<input type="text" class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.$value.
'" '.($moreparam ? $moreparam :
'').
'> '.$langs->getCurrencySymbol($conf->currency);
6994 } elseif (preg_match(
'/^double(\([0-9],[0-9]\)){0,1}/', $type)) {
6995 if (!empty($value)) {
6996 $value =
price($value);
6998 $out =
'<input type="text" class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.$value.
'" '.($moreparam ? $moreparam :
'').
'> ';
6999 } elseif ($type ==
'select') {
7001 if (!empty($conf->use_javascript_ajax) && empty($conf->global->MAIN_EXTRAFIELDS_DISABLE_SELECT2)) {
7002 include_once DOL_DOCUMENT_ROOT.
'/core/lib/ajax.lib.php';
7003 $out .=
ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
7006 $out .=
'<select class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" '.($moreparam ? $moreparam :
'').
'>';
7007 if ((!isset($this->fields[$key][
'default'])) || ($this->fields[$key][
'notnull'] != 1)) {
7008 $out .=
'<option value="0"> </option>';
7010 foreach ($param[
'options'] as $keyb => $valb) {
7011 if ((
string) $keyb ==
'') {
7014 if (strpos($valb,
"|") !==
false) {
7015 list($valb, $parent) = explode(
'|', $valb);
7017 $out .=
'<option value="'.$keyb.
'"';
7018 $out .= (((string) $value == (
string) $keyb) ?
' selected' :
'');
7019 $out .= (!empty($parent) ?
' parent="'.$parent.
'"' :
'');
7020 $out .=
'>'.$valb.
'</option>';
7022 $out .=
'</select>';
7023 } elseif ($type ==
'sellist') {
7025 if (!empty($conf->use_javascript_ajax) && empty($conf->global->MAIN_EXTRAFIELDS_DISABLE_SELECT2)) {
7026 include_once DOL_DOCUMENT_ROOT.
'/core/lib/ajax.lib.php';
7027 $out .=
ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
7030 $out .=
'<select class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" '.($moreparam ? $moreparam :
'').
'>';
7031 if (is_array($param[
'options'])) {
7032 $param_list = array_keys($param[
'options']);
7033 $InfoFieldList = explode(
":", $param_list[0]);
7043 $keyList = (empty($InfoFieldList[2]) ?
'rowid' : $InfoFieldList[2].
' as rowid');
7045 if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
7046 if (strpos($InfoFieldList[4],
'extra.') !==
false) {
7047 $keyList =
'main.'.$InfoFieldList[2].
' as rowid';
7049 $keyList = $InfoFieldList[2].
' as rowid';
7052 if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
7053 list($parentName, $parentField) = explode(
'|', $InfoFieldList[3]);
7054 $keyList .=
', '.$parentField;
7057 $filter_categorie =
false;
7058 if (count($InfoFieldList) > 5) {
7059 if ($InfoFieldList[0] ==
'categorie') {
7060 $filter_categorie =
true;
7064 if ($filter_categorie ===
false) {
7065 $fields_label = explode(
'|', $InfoFieldList[1]);
7066 if (is_array($fields_label)) {
7068 $keyList .= implode(
', ', $fields_label);
7072 $sql =
"SELECT " . $keyList;
7073 $sql .=
" FROM " . $this->db->prefix() . $InfoFieldList[0];
7074 if (!empty($InfoFieldList[4])) {
7076 if (strpos($InfoFieldList[4],
'$SEL$') !==
false) {
7077 $InfoFieldList[4] = str_replace(
'$SEL$',
'SELECT', $InfoFieldList[4]);
7081 if (strpos($InfoFieldList[4],
'$ID$') !==
false && !empty($objectid)) {
7082 $InfoFieldList[4] = str_replace(
'$ID$', $objectid, $InfoFieldList[4]);
7084 $InfoFieldList[4] = str_replace(
'$ID$',
'0', $InfoFieldList[4]);
7088 if (strpos($InfoFieldList[4],
'extra') !==
false) {
7089 $sql .=
" as main, " . $this->db->prefix() . $InfoFieldList[0] .
"_extrafields as extra";
7090 $sqlwhere .=
" WHERE extra.fk_object=main." . $InfoFieldList[2] .
" AND " . $InfoFieldList[4];
7092 $sqlwhere .=
" WHERE " . $InfoFieldList[4];
7095 $sqlwhere .=
' WHERE 1=1';
7098 if (in_array($InfoFieldList[0], array(
'tablewithentity'))) {
7099 $sqlwhere .=
" AND entity = " . ((int) $conf->entity);
7104 $sql .=
' ORDER BY ' . implode(
', ', $fields_label);
7106 dol_syslog(get_class($this) .
'::showInputField type=sellist', LOG_DEBUG);
7107 $resql = $this->db->query(
$sql);
7109 $out .=
'<option value="0"> </option>';
7110 $num = $this->db->num_rows($resql);
7114 $obj = $this->db->fetch_object($resql);
7118 $fields_label = explode(
'|', $InfoFieldList[1]);
7119 if (count($fields_label) > 1) {
7121 foreach ($fields_label as $field_toshow) {
7122 $labeltoshow .= $obj->$field_toshow .
' ';
7125 $labeltoshow = $obj->{$InfoFieldList[1]};
7127 $labeltoshow =
dol_trunc($labeltoshow, 45);
7129 if ($value == $obj->rowid) {
7130 foreach ($fields_label as $field_toshow) {
7131 $translabel = $langs->trans($obj->$field_toshow);
7132 if ($translabel != $obj->$field_toshow) {
7133 $labeltoshow =
dol_trunc($translabel) .
' ';
7135 $labeltoshow =
dol_trunc($obj->$field_toshow) .
' ';
7138 $out .=
'<option value="' . $obj->rowid .
'" selected>' . $labeltoshow .
'</option>';
7141 $translabel = $langs->trans($obj->{$InfoFieldList[1]});
7142 if ($translabel != $obj->{$InfoFieldList[1]}) {
7143 $labeltoshow =
dol_trunc($translabel, 18);
7145 $labeltoshow =
dol_trunc($obj->{$InfoFieldList[1]});
7148 if (empty($labeltoshow)) {
7149 $labeltoshow =
'(not defined)';
7151 if ($value == $obj->rowid) {
7152 $out .=
'<option value="' . $obj->rowid .
'" selected>' . $labeltoshow .
'</option>';
7155 if (!empty($InfoFieldList[3]) && $parentField) {
7156 $parent = $parentName .
':' . $obj->{$parentField};
7160 $out .=
'<option value="' . $obj->rowid .
'"';
7161 $out .= ($value == $obj->rowid ?
' selected' :
'');
7162 $out .= (!empty($parent) ?
' parent="' . $parent .
'"' :
'');
7163 $out .=
'>' . $labeltoshow .
'</option>';
7168 $this->db->free($resql);
7170 print
'Error in request ' .
$sql .
' ' . $this->db->lasterror() .
'. Check setup of extra parameters.<br>';
7173 require_once DOL_DOCUMENT_ROOT.
'/categories/class/categorie.class.php';
7174 $data =
$form->select_all_categories(Categorie::$MAP_ID_TO_CODE[$InfoFieldList[5]],
'',
'parent', 64, $InfoFieldList[6], 1, 1);
7175 $out .=
'<option value="0"> </option>';
7176 foreach ($data as $data_key => $data_value) {
7177 $out .=
'<option value="' . $data_key .
'"';
7178 $out .= ($value == $data_key ?
' selected' :
'');
7179 $out .=
'>' . $data_value .
'</option>';
7183 $out .=
'</select>';
7184 } elseif ($type ==
'checkbox') {
7185 $value_arr = explode(
',', $value);
7186 $out =
$form->multiselectarray($keyprefix.$key.$keysuffix, (empty($param[
'options']) ?
null:$param[
'options']), $value_arr,
'', 0, $morecss, 0,
'100%');
7187 } elseif ($type ==
'radio') {
7189 foreach ($param[
'options'] as $keyopt => $valopt) {
7190 $out .=
'<input class="flat '.$morecss.
'" type="radio" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" '.($moreparam ? $moreparam :
'');
7191 $out .=
' value="'.$keyopt.
'"';
7192 $out .=
' id="'.$keyprefix.$key.$keysuffix.
'_'.$keyopt.
'"';
7193 $out .= ($value == $keyopt ?
'checked' :
'');
7194 $out .=
'/><label for="'.$keyprefix.$key.$keysuffix.
'_'.$keyopt.
'">'.$valopt.
'</label><br>';
7196 } elseif ($type ==
'chkbxlst') {
7197 if (is_array($value)) {
7198 $value_arr = $value;
7200 $value_arr = explode(
',', $value);
7203 if (is_array($param[
'options'])) {
7204 $param_list = array_keys($param[
'options']);
7205 $InfoFieldList = explode(
":", $param_list[0]);
7215 $keyList = (empty($InfoFieldList[2]) ?
'rowid' : $InfoFieldList[2].
' as rowid');
7217 if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
7218 list ($parentName, $parentField) = explode(
'|', $InfoFieldList[3]);
7219 $keyList .=
', '.$parentField;
7221 if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
7222 if (strpos($InfoFieldList[4],
'extra.') !==
false) {
7223 $keyList =
'main.'.$InfoFieldList[2].
' as rowid';
7225 $keyList = $InfoFieldList[2].
' as rowid';
7229 $filter_categorie =
false;
7230 if (count($InfoFieldList) > 5) {
7231 if ($InfoFieldList[0] ==
'categorie') {
7232 $filter_categorie =
true;
7236 if ($filter_categorie ===
false) {
7237 $fields_label = explode(
'|', $InfoFieldList[1]);
7238 if (is_array($fields_label)) {
7240 $keyList .= implode(
', ', $fields_label);
7244 $sql =
"SELECT " . $keyList;
7245 $sql .=
' FROM ' . $this->db->prefix() . $InfoFieldList[0];
7246 if (!empty($InfoFieldList[4])) {
7248 if (strpos($InfoFieldList[4],
'$SEL$') !==
false) {
7249 $InfoFieldList[4] = str_replace(
'$SEL$',
'SELECT', $InfoFieldList[4]);
7253 if (strpos($InfoFieldList[4],
'$ID$') !==
false && !empty($objectid)) {
7254 $InfoFieldList[4] = str_replace(
'$ID$', $objectid, $InfoFieldList[4]);
7256 $InfoFieldList[4] = str_replace(
'$ID$',
'0', $InfoFieldList[4]);
7260 if (strpos($InfoFieldList[4],
'extra') !==
false) {
7261 $sql .=
' as main, ' . $this->db->prefix() . $InfoFieldList[0] .
'_extrafields as extra';
7262 $sqlwhere .=
" WHERE extra.fk_object=main." . $InfoFieldList[2] .
" AND " . $InfoFieldList[4];
7264 $sqlwhere .=
" WHERE " . $InfoFieldList[4];
7267 $sqlwhere .=
' WHERE 1=1';
7270 if (in_array($InfoFieldList[0], array(
'tablewithentity'))) {
7271 $sqlwhere .=
" AND entity = " . ((int) $conf->entity);
7277 dol_syslog(get_class($this) .
'::showInputField type=chkbxlst', LOG_DEBUG);
7278 $resql = $this->db->query(
$sql);
7280 $num = $this->db->num_rows($resql);
7287 $obj = $this->db->fetch_object($resql);
7291 $fields_label = explode(
'|', $InfoFieldList[1]);
7292 if (count($fields_label) > 1) {
7294 foreach ($fields_label as $field_toshow) {
7295 $labeltoshow .= $obj->$field_toshow .
' ';
7298 $labeltoshow = $obj->{$InfoFieldList[1]};
7300 $labeltoshow =
dol_trunc($labeltoshow, 45);
7302 if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
7303 foreach ($fields_label as $field_toshow) {
7304 $translabel = $langs->trans($obj->$field_toshow);
7305 if ($translabel != $obj->$field_toshow) {
7306 $labeltoshow =
dol_trunc($translabel, 18) .
' ';
7308 $labeltoshow =
dol_trunc($obj->$field_toshow, 18) .
' ';
7312 $data[$obj->rowid] = $labeltoshow;
7315 $translabel = $langs->trans($obj->{$InfoFieldList[1]});
7316 if ($translabel != $obj->{$InfoFieldList[1]}) {
7317 $labeltoshow =
dol_trunc($translabel, 18);
7319 $labeltoshow =
dol_trunc($obj->{$InfoFieldList[1]}, 18);
7322 if (empty($labeltoshow)) {
7323 $labeltoshow =
'(not defined)';
7326 if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
7327 $data[$obj->rowid] = $labeltoshow;
7330 if (!empty($InfoFieldList[3]) && $parentField) {
7331 $parent = $parentName .
':' . $obj->{$parentField};
7335 $data[$obj->rowid] = $labeltoshow;
7340 $this->db->free($resql);
7342 $out =
$form->multiselectarray($keyprefix . $key . $keysuffix, $data, $value_arr,
'', 0, $morecss, 0,
'100%');
7344 print
'Error in request ' .
$sql .
' ' . $this->db->lasterror() .
'. Check setup of extra parameters.<br>';
7347 require_once DOL_DOCUMENT_ROOT.
'/categories/class/categorie.class.php';
7348 $data =
$form->select_all_categories(Categorie::$MAP_ID_TO_CODE[$InfoFieldList[5]],
'',
'parent', 64, $InfoFieldList[6], 1, 1);
7349 $out =
$form->multiselectarray($keyprefix . $key . $keysuffix, $data, $value_arr,
'', 0, $morecss, 0,
'100%');
7352 } elseif ($type ==
'link') {
7353 $param_list = array_keys($param[
'options']);
7354 $param_list_array = explode(
':', $param_list[0]);
7355 $showempty = (($required && $default !=
'') ? 0 : 1);
7357 if (!preg_match(
'/search_/', $keyprefix)) {
7358 if (!empty($param_list_array[2])) {
7359 if (!empty($this->fields[$key][
'picto'])) {
7360 $morecss .=
' widthcentpercentminusxx';
7362 $morecss .=
' widthcentpercentminusx';
7365 if (!empty($this->fields[$key][
'picto'])) {
7366 $morecss .=
' widthcentpercentminusx';
7371 $out =
$form->selectForForms($param_list[0], $keyprefix.$key.$keysuffix, $value, $showempty,
'',
'', $morecss, $moreparam, 0, empty($val[
'disabled']) ? 0 : 1);
7373 if (!empty($param_list_array[2])) {
7374 if (!
GETPOSTISSET(
'backtopage') && empty($val[
'disabled']) && empty($nonewbutton)) {
7375 list($class, $classfile) = explode(
':', $param_list[0]);
7376 if (file_exists(
dol_buildpath(dirname(dirname($classfile)).
'/card.php'))) {
7377 $url_path =
dol_buildpath(dirname(dirname($classfile)).
'/card.php', 1);
7379 $url_path =
dol_buildpath(dirname(dirname($classfile)).
'/'.strtolower($class).
'_card.php', 1);
7381 $paramforthenewlink =
'';
7382 $paramforthenewlink .= (
GETPOSTISSET(
'action') ?
'&action='.GETPOST(
'action',
'aZ09') :
'');
7383 $paramforthenewlink .= (
GETPOSTISSET(
'id') ?
'&id='.GETPOST(
'id',
'int') :
'');
7384 $paramforthenewlink .= (
GETPOSTISSET(
'origin') ?
'&origin='.GETPOST(
'origin',
'aZ09') :
'');
7385 $paramforthenewlink .= (
GETPOSTISSET(
'originid') ?
'&originid='.GETPOST(
'originid',
'int') :
'');
7386 $paramforthenewlink .=
'&fk_'.strtolower($class).
'=--IDFORBACKTOPAGE--';
7388 $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>';
7391 } elseif ($type ==
'password') {
7393 $out =
'<input type="'.($keyprefix ==
'search_' ?
'text' :
'password').
'" class="flat '.$morecss.
'" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.$value.
'" '.($moreparam ? $moreparam :
'').
'>';
7394 } elseif ($type ==
'array') {
7396 $newval[
'type'] =
'varchar(256)';
7399 if (!empty($value)) {
7400 foreach ($value as $option) {
7401 $out .=
'<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).
'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
7402 $out .= $this->showInputField($newval, $keyprefix.$key.$keysuffix.
'[]', $option, $moreparam,
'',
'', $morecss).
'<br></span>';
7405 $out .=
'<a id="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).
'_add" href="javascript:;"><span class="fa fa-plus-circle valignmiddle"></span></a>';
7407 $newInput =
'<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).
'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
7408 $newInput .= $this->showInputField($newval, $keyprefix.$key.$keysuffix.
'[]',
'', $moreparam,
'',
'', $morecss).
'<br></span>';
7410 if (!empty($conf->use_javascript_ajax)) {
7412 <script nonce="'.getNonce().
'">
7413 $(document).ready(function() {
7414 $("a#'.
dol_escape_js($keyprefix.$key.$keysuffix).
'_add").click(function() {
7418 $(document).on("click", "a.'.
dol_escape_js($keyprefix.$key.$keysuffix).
'_del", function() {
7419 $(this).parent().remove();
7425 if (!empty($hidden)) {
7426 $out =
'<input type="hidden" value="'.$value.
'" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'"/>';
7429 if ($isDependList==1) {
7430 $out .= $this->getJSListDependancies(
'_common');
7438 if (!empty($fieldValidationErrorMsg) && function_exists(
'getFieldErrorIcon')) {
7439 $out .=
' '.getFieldErrorIcon($fieldValidationErrorMsg);
7458 public function showOutputField($val, $key, $value, $moreparam =
'', $keysuffix =
'', $keyprefix =
'', $morecss =
'')
7460 global $conf, $langs,
$form;
7462 if (!is_object(
$form)) {
7463 require_once DOL_DOCUMENT_ROOT.
'/core/class/html.form.class.php';
7467 $label = empty($val[
'label']) ?
'' : $val[
'label'];
7468 $type = empty($val[
'type']) ?
'' : $val[
'type'];
7469 $size = empty($val[
'css']) ?
'' : $val[
'css'];
7473 if (preg_match(
'/varchar\((\d+)\)/', $type, $reg)) {
7476 } elseif (preg_match(
'/varchar/', $type)) {
7479 if (!empty($val[
'arrayofkeyval']) && is_array($val[
'arrayofkeyval'])) {
7482 if (preg_match(
'/^integer:(.*):(.*)/i', $val[
'type'], $reg)) {
7486 $default = empty($val[
'default']) ?
'' : $val[
'default'];
7487 $computed = empty($val[
'computed']) ?
'' : $val[
'computed'];
7488 $unique = empty($val[
'unique']) ?
'' : $val[
'unique'];
7489 $required = empty($val[
'required']) ?
'' : $val[
'required'];
7491 $param[
'options'] = array();
7493 if (!empty($val[
'arrayofkeyval']) && is_array($val[
'arrayofkeyval'])) {
7494 $param[
'options'] = $val[
'arrayofkeyval'];
7496 if (preg_match(
'/^integer:(.*):(.*)/i', $val[
'type'], $reg)) {
7498 $stringforoptions = $reg[1].
':'.$reg[2];
7499 if ($reg[1] ==
'User') {
7500 $stringforoptions .=
':-1';
7502 $param[
'options'] = array($stringforoptions => $stringforoptions);
7503 } elseif (preg_match(
'/^sellist:(.*):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
7504 $param[
'options'] = array($reg[1].
':'.$reg[2].
':'.$reg[3].
':'.$reg[4] =>
'N');
7506 } elseif (preg_match(
'/^sellist:(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
7507 $param[
'options'] = array($reg[1].
':'.$reg[2].
':'.$reg[3] =>
'N');
7509 } elseif (preg_match(
'/^sellist:(.*):(.*)/i', $val[
'type'], $reg)) {
7510 $param[
'options'] = array($reg[1].
':'.$reg[2] =>
'N');
7512 } elseif (preg_match(
'/^chkbxlst:(.*)/i', $val[
'type'], $reg)) {
7513 $param[
'options'] = array($reg[1] =>
'N');
7517 $langfile = empty($val[
'langfile']) ?
'' : $val[
'langfile'];
7518 $list = (empty($val[
'list']) ?
'' : $val[
'list']);
7519 $help = (empty($val[
'help']) ?
'' : $val[
'help']);
7520 $hidden = (($val[
'visible'] == 0) ? 1 : 0);
7530 $value =
dol_eval($computed, 1, 0,
'');
7533 if (empty($morecss)) {
7534 if ($type ==
'date') {
7535 $morecss =
'minwidth100imp';
7536 } elseif ($type ==
'datetime' || $type ==
'timestamp') {
7537 $morecss =
'minwidth200imp';
7538 } elseif (in_array($type, array(
'int',
'double',
'price'))) {
7539 $morecss =
'maxwidth75';
7540 } elseif ($type ==
'url') {
7541 $morecss =
'minwidth400';
7542 } elseif ($type ==
'boolean') {
7545 if (is_numeric($size) && round($size) < 12) {
7546 $morecss =
'minwidth100';
7547 } elseif (is_numeric($size) && round($size) <= 48) {
7548 $morecss =
'minwidth200';
7550 $morecss =
'minwidth400';
7556 if (in_array($key, array(
'rowid',
'ref')) && method_exists($this,
'getNomUrl')) {
7557 if ($key !=
'rowid' || empty($this->fields[
'ref'])) {
7558 $value = $this->getNomUrl(1,
'', 0,
'', 1);
7560 } elseif ($key ==
'status' && method_exists($this,
'getLibStatut')) {
7561 $value = $this->getLibStatut(3);
7562 } elseif ($type ==
'date') {
7563 if (!empty($value)) {
7568 } elseif ($type ==
'datetime' || $type ==
'timestamp') {
7569 if (!empty($value)) {
7574 } elseif ($type ==
'duration') {
7575 include_once DOL_DOCUMENT_ROOT.
'/core/lib/date.lib.php';
7576 if (!is_null($value) && $value !==
'') {
7579 } elseif ($type ==
'double' || $type ==
'real') {
7580 if (!is_null($value) && $value !==
'') {
7581 $value =
price($value);
7583 } elseif ($type ==
'boolean') {
7585 if (!empty($value)) {
7586 $checked =
' checked ';
7588 $value =
'<input type="checkbox" '.$checked.
' '.($moreparam ? $moreparam :
'').
' readonly disabled>';
7589 } elseif ($type ==
'mail' || $type ==
'email') {
7591 } elseif ($type ==
'url') {
7593 } elseif ($type ==
'phone') {
7595 } elseif ($type ==
'ip') {
7597 } elseif ($type ==
'price') {
7598 if (!is_null($value) && $value !==
'') {
7599 $value =
price($value, 0, $langs, 0, 0, -1, $conf->currency);
7601 } elseif ($type ==
'select') {
7602 $value = isset($param[
'options'][$value])?$param[
'options'][$value]:
'';
7603 } elseif ($type ==
'sellist') {
7604 $param_list = array_keys($param[
'options']);
7605 $InfoFieldList = explode(
":", $param_list[0]);
7607 $selectkey =
"rowid";
7610 if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
7611 $selectkey = $InfoFieldList[2];
7612 $keyList = $InfoFieldList[2].
' as rowid';
7615 $fields_label = explode(
'|', $InfoFieldList[1]);
7616 if (is_array($fields_label)) {
7618 $keyList .= implode(
', ', $fields_label);
7621 $filter_categorie =
false;
7622 if (count($InfoFieldList) > 5) {
7623 if ($InfoFieldList[0] ==
'categorie') {
7624 $filter_categorie =
true;
7628 $sql =
"SELECT ".$keyList;
7629 $sql .=
' FROM '.$this->db->prefix().$InfoFieldList[0];
7630 if (strpos($InfoFieldList[4],
'extra') !==
false) {
7633 if ($selectkey ==
'rowid' && empty($value)) {
7634 $sql .=
" WHERE ".$selectkey.
" = 0";
7635 } elseif ($selectkey ==
'rowid') {
7636 $sql .=
" WHERE ".$selectkey.
" = ".((int) $value);
7638 $sql .=
" WHERE ".$selectkey.
" = '".$this->db->escape($value).
"'";
7643 dol_syslog(get_class($this).
':showOutputField:$type=sellist', LOG_DEBUG);
7644 $resql = $this->db->query(
$sql);
7646 if ($filter_categorie ===
false) {
7648 $numrows = $this->db->num_rows($resql);
7650 $obj = $this->db->fetch_object($resql);
7653 $fields_label = explode(
'|', $InfoFieldList[1]);
7655 if (is_array($fields_label) && count($fields_label) > 1) {
7656 foreach ($fields_label as $field_toshow) {
7658 if (!empty($obj->$field_toshow)) {
7659 $translabel = $langs->trans($obj->$field_toshow);
7661 if ($translabel != $field_toshow) {
7662 $value .=
dol_trunc($translabel, 18) .
' ';
7664 $value .= $obj->$field_toshow .
' ';
7669 if (!empty($obj->{$InfoFieldList[1]})) {
7670 $translabel = $langs->trans($obj->{$InfoFieldList[1]});
7672 if ($translabel != $obj->{$InfoFieldList[1]}) {
7675 $value = $obj->{$InfoFieldList[1]};
7680 require_once DOL_DOCUMENT_ROOT .
'/categories/class/categorie.class.php';
7683 $obj = $this->db->fetch_object($resql);
7685 $c->fetch($obj->rowid);
7686 $ways = $c->print_all_ways();
7687 foreach ($ways as $way) {
7688 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories"' . ($c->color ?
' style="background: #' . $c->color .
';"' :
' style="background: #aaa"') .
'>' .
img_object(
'',
'category') .
' ' . $way .
'</li>';
7690 $value =
'<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(
' ', $toprint).
'</ul></div>';
7693 dol_syslog(get_class($this).
'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
7695 } elseif ($type ==
'radio') {
7696 $value = $param[
'options'][$value];
7697 } elseif ($type ==
'checkbox') {
7698 $value_arr = explode(
',', $value);
7700 if (is_array($value_arr) && count($value_arr) > 0) {
7702 foreach ($value_arr as $keyval => $valueval) {
7703 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">'.$param[
'options'][$valueval].
'</li>';
7705 $value =
'<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(
' ', $toprint).
'</ul></div>';
7707 } elseif ($type ==
'chkbxlst') {
7708 $value_arr = explode(
',', $value);
7710 $param_list = array_keys($param[
'options']);
7711 $InfoFieldList = explode(
":", $param_list[0]);
7713 $selectkey =
"rowid";
7716 if (count($InfoFieldList) >= 3) {
7717 $selectkey = $InfoFieldList[2];
7718 $keyList = $InfoFieldList[2].
' as rowid';
7721 $fields_label = explode(
'|', $InfoFieldList[1]);
7722 if (is_array($fields_label)) {
7724 $keyList .= implode(
', ', $fields_label);
7727 $filter_categorie =
false;
7728 if (count($InfoFieldList) > 5) {
7729 if ($InfoFieldList[0] ==
'categorie') {
7730 $filter_categorie =
true;
7734 $sql =
"SELECT ".$keyList;
7735 $sql .=
' FROM '.$this->db->prefix().$InfoFieldList[0];
7736 if (strpos($InfoFieldList[4],
'extra') !==
false) {
7742 dol_syslog(get_class($this).
':showOutputField:$type=chkbxlst', LOG_DEBUG);
7743 $resql = $this->db->query(
$sql);
7745 if ($filter_categorie ===
false) {
7748 while ($obj = $this->db->fetch_object($resql)) {
7750 $fields_label = explode(
'|', $InfoFieldList[1]);
7751 if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
7752 if (is_array($fields_label) && count($fields_label) > 1) {
7753 foreach ($fields_label as $field_toshow) {
7755 if (!empty($obj->$field_toshow)) {
7756 $translabel = $langs->trans($obj->$field_toshow);
7758 if ($translabel != $field_toshow) {
7759 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' .
dol_trunc($translabel, 18) .
'</li>';
7761 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' . $obj->$field_toshow .
'</li>';
7766 if (!empty($obj->{$InfoFieldList[1]})) {
7767 $translabel = $langs->trans($obj->{$InfoFieldList[1]});
7769 if ($translabel != $obj->{$InfoFieldList[1]}) {
7770 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' .
dol_trunc($translabel, 18) .
'</li>';
7772 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' . $obj->{$InfoFieldList[1]} .
'</li>';
7778 require_once DOL_DOCUMENT_ROOT .
'/categories/class/categorie.class.php';
7781 while ($obj = $this->db->fetch_object($resql)) {
7782 if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
7784 $c->fetch($obj->rowid);
7785 $ways = $c->print_all_ways();
7786 foreach ($ways as $way) {
7787 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories"' . ($c->color ?
' style="background: #' . $c->color .
';"' :
' style="background: #aaa"') .
'>' .
img_object(
'',
'category') .
' ' . $way .
'</li>';
7792 $value =
'<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(
' ', $toprint).
'</ul></div>';
7794 dol_syslog(get_class($this).
'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
7796 } elseif ($type ==
'link') {
7801 $param_list = array_keys($param[
'options']);
7803 $InfoFieldList = explode(
":", $param_list[0]);
7804 $classname = $InfoFieldList[0];
7805 $classpath = $InfoFieldList[1];
7806 $getnomurlparam = (empty($InfoFieldList[2]) ? 3 : $InfoFieldList[2]);
7807 $getnomurlparam2 = (empty($InfoFieldList[4]) ?
'' : $InfoFieldList[4]);
7808 if (!empty($classpath)) {
7810 if ($classname && class_exists($classname)) {
7811 $object =
new $classname($this->db);
7812 if ($object->element ===
'product') {
7813 $result = $object->fetch($value,
'',
'',
'', 0, 1, 1);
7815 $result = $object->fetch($value);
7818 if ($object->element ===
'product') {
7819 $get_name_url_param_arr = array($getnomurlparam, $getnomurlparam2, 0, -1, 0,
'', 0);
7820 if (isset($val[
'get_name_url_params'])) {
7821 $get_name_url_params = explode(
':', $val[
'get_name_url_params']);
7822 if (!empty($get_name_url_params)) {
7823 $param_num_max = count($get_name_url_param_arr) - 1;
7824 foreach ($get_name_url_params as $param_num => $param_value) {
7825 if ($param_num > $param_num_max) {
7828 $get_name_url_param_arr[$param_num] = $param_value;
7836 $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]);
7838 $value = $object->getNomUrl($getnomurlparam, $getnomurlparam2);
7845 dol_syslog(
'Error bad setup of extrafield', LOG_WARNING);
7846 return 'Error bad setup of extrafield';
7851 } elseif ($type ==
'password') {
7852 $value = preg_replace(
'/./i',
'*', $value);
7853 } elseif ($type ==
'array') {
7854 $value = implode(
'<br>', $value);
7874 unset($this->validateFieldsErrors[$fieldKey]);
7888 $msg = $langs->trans(
"UnknowError");
7891 $this->error = $this->validateFieldsErrors[$fieldKey] = $msg;
7902 if (!empty($this->validateFieldsErrors[$fieldKey])) {
7903 return $this->validateFieldsErrors[$fieldKey];
7920 if (!class_exists(
'Validate')) {
7921 require_once DOL_DOCUMENT_ROOT .
'/core/class/validate.class.php';
7924 $this->clearFieldError($fieldKey);
7926 if (!isset($fields[$fieldKey])) {
7927 $this->setFieldError($fieldKey, $langs->trans(
'FieldNotFoundInObject'));
7931 $val = $fields[$fieldKey];
7934 $param[
'options'] = array();
7935 $type = $val[
'type'];
7938 if (isset($val[
'notnull']) && $val[
'notnull'] === 1) {
7952 if (preg_match(
'/varchar\((\d+)\)/', $type, $reg)) {
7955 } elseif (preg_match(
'/varchar/', $type)) {
7959 if (!empty($val[
'arrayofkeyval']) && is_array($val[
'arrayofkeyval'])) {
7963 if (!empty($val[
'type']) && preg_match(
'/^integer:(.*):(.*)/i', $val[
'type'], $reg)) {
7967 if (!empty($val[
'arrayofkeyval']) && is_array($val[
'arrayofkeyval'])) {
7968 $param[
'options'] = $val[
'arrayofkeyval'];
7971 if (preg_match(
'/^integer:(.*):(.*)/i', $val[
'type'], $reg)) {
7973 $param[
'options'] = array($reg[1].
':'.$reg[2]=>$reg[1].
':'.$reg[2]);
7974 } elseif (preg_match(
'/^sellist:(.*):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
7975 $param[
'options'] = array($reg[1].
':'.$reg[2].
':'.$reg[3].
':'.$reg[4] =>
'N');
7977 } elseif (preg_match(
'/^sellist:(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
7978 $param[
'options'] = array($reg[1].
':'.$reg[2].
':'.$reg[3] =>
'N');
7980 } elseif (preg_match(
'/^sellist:(.*):(.*)/i', $val[
'type'], $reg)) {
7981 $param[
'options'] = array($reg[1].
':'.$reg[2] =>
'N');
7990 $validate =
new Validate($this->db, $langs);
8000 if ($required && !$validate->isNotEmptyString($fieldValue)) {
8001 $this->setFieldError($fieldKey, $validate->error);
8003 } elseif (!$required && !$validate->isNotEmptyString($fieldValue)) {
8009 if (!empty($maxSize) && !$validate->isMaxLength($fieldValue, $maxSize)) {
8010 $this->setFieldError($fieldKey, $validate->error);
8015 if (!empty($minSize) && !$validate->isMinLength($fieldValue, $minSize)) {
8016 $this->setFieldError($fieldKey, $validate->error);
8024 if (in_array($type, array(
'date',
'datetime',
'timestamp'))) {
8025 if (!$validate->isTimestamp($fieldValue)) {
8026 $this->setFieldError($fieldKey, $validate->error);
8028 }
else {
return true; }
8029 } elseif ($type ==
'duration') {
8030 if (!$validate->isDuration($fieldValue)) {
8031 $this->setFieldError($fieldKey, $validate->error);
8033 }
else {
return true; }
8034 } elseif (in_array($type, array(
'double',
'real',
'price'))) {
8036 if (!$validate->isNumeric($fieldValue)) {
8037 $this->setFieldError($fieldKey, $validate->error);
8039 }
else {
return true; }
8040 } elseif ($type ==
'boolean') {
8041 if (!$validate->isBool($fieldValue)) {
8042 $this->setFieldError($fieldKey, $validate->error);
8044 }
else {
return true; }
8045 } elseif ($type ==
'mail') {
8046 if (!$validate->isEmail($fieldValue)) {
8047 $this->setFieldError($fieldKey, $validate->error);
8050 } elseif ($type ==
'url') {
8051 if (!$validate->isUrl($fieldValue)) {
8052 $this->setFieldError($fieldKey, $validate->error);
8054 }
else {
return true; }
8055 } elseif ($type ==
'phone') {
8056 if (!$validate->isPhone($fieldValue)) {
8057 $this->setFieldError($fieldKey, $validate->error);
8059 }
else {
return true; }
8060 } elseif ($type ==
'select' || $type ==
'radio') {
8061 if (!isset($param[
'options'][$fieldValue])) {
8062 $this->error = $langs->trans(
'RequireValidValue');
8064 }
else {
return true; }
8065 } elseif ($type ==
'sellist' || $type ==
'chkbxlst') {
8066 $param_list = array_keys($param[
'options']);
8067 $InfoFieldList = explode(
":", $param_list[0]);
8068 $value_arr = explode(
',', $fieldValue);
8069 $value_arr = array_map(array($this->db,
'escape'), $value_arr);
8071 $selectkey =
"rowid";
8072 if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
8073 $selectkey = $InfoFieldList[2];
8076 if (!$validate->isInDb($value_arr, $InfoFieldList[0], $selectkey)) {
8077 $this->setFieldError($fieldKey, $validate->error);
8079 }
else {
return true; }
8080 } elseif ($type ==
'link') {
8081 $param_list = array_keys($param[
'options']);
8082 $InfoFieldList = explode(
":", $param_list[0]);
8083 $classname = $InfoFieldList[0];
8084 $classpath = $InfoFieldList[1];
8085 if (!$validate->isFetchable($fieldValue, $classname, $classpath)) {
8086 $this->setFieldError($fieldKey, $validate->error);
8088 }
else {
return true; }
8108 public function showOptionals($extrafields, $mode =
'view', $params =
null, $keysuffix =
'', $keyprefix =
'', $onetrtd = 0, $display_type =
'card')
8110 global $db, $conf, $langs, $action,
$form, $hookmanager;
8112 if (!is_object(
$form)) {
8115 if (!is_object($extrafields)) {
8116 dol_syslog(
'Bad parameter extrafields for showOptionals', LOG_ERR);
8117 return 'Bad parameter extrafields for showOptionals';
8119 if (!is_array($extrafields->attributes[$this->table_element])) {
8120 dol_syslog(
"extrafields->attributes was not loaded with extrafields->fetch_name_optionals_label(table_element);", LOG_WARNING);
8125 $parameters = array(
'mode'=>$mode,
'params'=>$params,
'keysuffix'=>$keysuffix,
'keyprefix'=>$keyprefix,
'display_type'=>$display_type);
8126 $reshook = $hookmanager->executeHooks(
'showOptionals', $parameters, $this, $action);
8128 if (empty($reshook)) {
8129 if (is_array($extrafields->attributes[$this->table_element]) && key_exists(
'label', $extrafields->attributes[$this->table_element]) && is_array($extrafields->attributes[$this->table_element][
'label']) && count($extrafields->attributes[$this->table_element][
'label']) > 0) {
8131 $out .=
'<!-- commonobject:showOptionals --> ';
8134 $nbofextrafieldsshown = 0;
8137 $lastseparatorkeyfound =
'';
8138 $extrafields_collapse_num =
'';
8139 $extrafields_collapse_num_old =
'';
8142 foreach ($extrafields->attributes[$this->table_element][
'label'] as $key => $label) {
8146 if (is_array($params) && array_key_exists(
'onlykey', $params) && $key != $params[
'onlykey']) {
8152 if ($enabled && isset($extrafields->attributes[$this->table_element][
'enabled'][$key])) {
8153 $enabled =
dol_eval($extrafields->attributes[$this->table_element][
'enabled'][$key], 1, 1,
'2');
8155 if (empty($enabled)) {
8160 if ($visibility && isset($extrafields->attributes[$this->table_element][
'list'][$key])) {
8161 $visibility =
dol_eval($extrafields->attributes[$this->table_element][
'list'][$key], 1, 1,
'2');
8165 if ($perms && isset($extrafields->attributes[$this->table_element][
'perms'][$key])) {
8166 $perms =
dol_eval($extrafields->attributes[$this->table_element][
'perms'][$key], 1, 1,
'2');
8169 if (($mode ==
'create') && abs($visibility) != 1 && abs($visibility) != 3) {
8171 } elseif (($mode ==
'edit') && abs($visibility) != 1 && abs($visibility) != 3 && abs($visibility) != 4) {
8173 } elseif ($mode ==
'view' && empty($visibility)) {
8176 if (empty($perms)) {
8181 if (!empty($extrafields->attributes[$this->table_element][
'langfile'][$key])) {
8182 $langs->load($extrafields->attributes[$this->table_element][
'langfile'][$key]);
8186 if (is_array($params) && count($params) > 0 && $display_type==
'card') {
8187 if (array_key_exists(
'cols', $params)) {
8188 $colspan = $params[
'cols'];
8189 } elseif (array_key_exists(
'colspan', $params)) {
8191 if (preg_match(
'/colspan="(\d+)"/', $params[
'colspan'], $reg)) {
8194 $colspan = $params[
'colspan'];
8198 $colspan = intval($colspan);
8202 $value = ((!empty($this->array_options) && array_key_exists(
"options_".$key.$keysuffix, $this->array_options)) ? $this->array_options[
"options_".$key.$keysuffix] :
null);
8208 $check =
'alphanohtml';
8209 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'html',
'text'))) {
8210 $check =
'restricthtml';
8212 $getposttemp =
GETPOST($keyprefix.
'options_'.$key.$keysuffix, $check, 3);
8214 if (is_array($getposttemp) || $getposttemp !=
'' ||
GETPOSTISSET($keyprefix.
'options_'.$key.$keysuffix)) {
8215 if (is_array($getposttemp)) {
8217 $value = implode(
",", $getposttemp);
8219 $value = $getposttemp;
8222 $value = (!empty($this->array_options[
"options_".$key]) ? $this->array_options[
"options_".$key] :
'');
8228 $nbofextrafieldsshown++;
8231 if ($extrafields->attributes[$this->table_element][
'type'][$key] ==
'separate') {
8232 $extrafields_collapse_num = $key;
8250 $out .= $extrafields->showSeparator($key, $this, ($colspan ? $colspan + 1 : 2), $display_type, $mode);
8252 $lastseparatorkeyfound = $key;
8254 $collapse_group = $extrafields_collapse_num.(!empty($this->
id) ?
'_'.$this->id :
'');
8256 $class = (!empty($extrafields->attributes[$this->table_element][
'hidden'][$key]) ?
'hideobject ' :
'');
8258 if (is_array($params) && count($params) > 0) {
8259 if (array_key_exists(
'class', $params)) {
8260 $class .= $params[
'class'].
' ';
8262 if (array_key_exists(
'style', $params)) {
8263 $csstyle = $params[
'style'];
8268 $domData =
' data-element="extrafield"';
8269 $domData .=
' data-targetelement="'.$this->element.
'"';
8270 $domData .=
' data-targetid="'.$this->id.
'"';
8272 $html_id = (empty($this->
id) ?
'' :
'extrarow-'.$this->element.
'_'.$key.
'_'.$this->id);
8273 if ($display_type==
'card') {
8274 if (!empty($conf->global->MAIN_EXTRAFIELDS_USE_TWO_COLUMS) && ($e % 2) == 0) {
8278 if ($action ==
'selectlines') {
8284 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'date'))) {
8285 $datenotinstring =
null;
8286 if (array_key_exists(
'options_'.$key, $this->array_options)) {
8287 $datenotinstring = $this->array_options[
'options_'.$key];
8288 if (!is_numeric($this->array_options[
'options_'.$key])) {
8289 $datenotinstring = $this->db->jdate($datenotinstring);
8292 $datekey = $keyprefix.
'options_'.$key.$keysuffix;
8293 $value = (
GETPOSTISSET($datekey)) ?
dol_mktime(12, 0, 0,
GETPOST($datekey.
'month',
'int', 3),
GETPOST($datekey.
'day',
'int', 3),
GETPOST($datekey.
'year',
'int', 3)) : $datenotinstring;
8295 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'datetime'))) {
8296 $datenotinstring =
null;
8297 if (array_key_exists(
'options_'.$key, $this->array_options)) {
8298 $datenotinstring = $this->array_options[
'options_'.$key];
8299 if (!is_numeric($this->array_options[
'options_'.$key])) {
8300 $datenotinstring = $this->db->jdate($datenotinstring);
8303 $timekey = $keyprefix.
'options_'.$key.$keysuffix;
8304 $value = (
GETPOSTISSET($timekey)) ?
dol_mktime(
GETPOST($timekey.
'hour',
'int', 3),
GETPOST($timekey.
'min',
'int', 3),
GETPOST($timekey.
'sec',
'int', 3),
GETPOST($timekey.
'month',
'int', 3),
GETPOST($timekey.
'day',
'int', 3),
GETPOST($timekey.
'year',
'int', 3),
'tzuserrel') : $datenotinstring;
8307 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'price',
'double'))) {
8308 if (
GETPOSTISSET($keyprefix.
'options_'.$key.$keysuffix) || $value) {
8310 } elseif (isset($this->array_options[
'options_'.$key])) {
8311 $value = $this->array_options[
'options_'.$key];
8316 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'html',
'text',
'varchar',
'select',
'int',
'boolean'))) {
8317 if ($action ==
'create') {
8318 $value = (
GETPOSTISSET($keyprefix.
'options_'.$key.$keysuffix) || $value) ? $value : $extrafields->attributes[$this->table_element][
'default'][$key];
8322 $labeltoshow = $langs->trans($label);
8323 $helptoshow = $langs->trans($extrafields->attributes[$this->table_element][
'help'][$key]);
8325 if ($display_type ==
'card') {
8326 $out .=
'<tr '.($html_id ?
'id="'.$html_id.
'" ' :
'').$csstyle.
' class="field_options_'.$key.
' '.$class.$this->element.
'_extras_'.$key.
' trextrafields_collapse'.$collapse_group.
'" '.$domData.
' >';
8327 if (!empty($conf->global->MAIN_VIEW_LINE_NUMBER) && ($action ==
'view' || $action ==
'valid' || $action ==
'editline' || $action ==
'confirm_valid' || $action ==
'confirm_cancel')) {
8328 $out .=
'<td></td>';
8330 $out .=
'<td class="'.(empty($params[
'tdclass']) ?
'titlefieldcreate' : $params[
'tdclass']).
' wordbreak';
8331 } elseif ($display_type ==
'line') {
8332 $out .=
'<div '.($html_id ?
'id="'.$html_id.
'" ' :
'').$csstyle.
' class="fieldline_options_'.$key.
' '.$class.$this->element.
'_extras_'.$key.
' trextrafields_collapse'.$collapse_group.
'" '.$domData.
' >';
8333 $out .=
'<div style="display: inline-block; padding-right:4px" class="wordbreak';
8338 $tpl_context = isset($params[
"tpl_context"]) ? $params[
"tpl_context"] :
"none";
8339 if ($tpl_context !=
"public") {
8340 if ($mode !=
'view' && !empty($extrafields->attributes[$this->table_element][
'required'][$key])) {
8341 $out .=
' fieldrequired';
8345 if ($tpl_context ==
"public") {
8346 if (!empty($extrafields->attributes[$this->table_element][
'help'][$key])) {
8347 $out .=
$form->textwithpicto($labeltoshow, $helptoshow);
8349 $out .= $labeltoshow;
8351 if ($mode !=
'view' && !empty($extrafields->attributes[$this->table_element][
'required'][$key])) {
8352 $out .=
' <span style="color: red">*</span>';
8355 if (!empty($extrafields->attributes[$this->table_element][
'help'][$key])) {
8356 $out .=
$form->textwithpicto($labeltoshow, $helptoshow);
8358 $out .= $labeltoshow;
8362 $out .= ($display_type ==
'card' ?
'</td>' :
'</div>');
8364 $html_id = !empty($this->
id) ? $this->element.
'_extras_'.$key.
'_'.$this->id :
'';
8365 if ($display_type ==
'card') {
8367 $out .=
'<td '.($html_id ?
'id="'.$html_id.
'" ' :
'').
' class="valuefieldcreate '.$this->element.
'_extras_'.$key.
'" '.($colspan ?
' colspan="'.$colspan.
'"' :
'').
'>';
8368 } elseif ($display_type ==
'line') {
8369 $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].
'">';
8374 $out .= $extrafields->showOutputField($key, $value,
'', $this->table_element);
8377 $out .= $extrafields->showInputField($key, $value,
'', $keysuffix,
'', 0, $this->
id, $this->table_element);
8380 $out .= $extrafields->showInputField($key, $value,
'', $keysuffix,
'', 0, $this->
id, $this->table_element);
8384 $out .= ($display_type==
'card' ?
'</td>' :
'</div>');
8386 if (!empty($conf->global->MAIN_EXTRAFIELDS_USE_TWO_COLUMS) && (($e % 2) == 1)) {
8387 $out .= ($display_type==
'card' ?
'</tr>' :
'</div>');
8389 $out .= ($display_type==
'card' ?
'</tr>' :
'</div>');
8397 if (!empty($conf->use_javascript_ajax)) {
8398 $out .= $this->getJSListDependancies();
8401 $out .=
'<!-- commonobject:showOptionals end --> '.
"\n";
8403 if (empty($nbofextrafieldsshown)) {
8409 $out .= $hookmanager->resPrint;
8421 <script nonce="'.getNonce().
'">
8422 jQuery(document).ready(function() {
8423 function showOptions'.$type.
'(child_list, parent_list, orig_select)
8425 var val = $("select[name=\""+parent_list+"\"]").val();
8426 var parentVal = parent_list + ":" + val;
8427 if(typeof val == "string"){
8429 var options = orig_select.find("option[parent=\""+parentVal+"\"]").clone();
8430 $("select[name=\""+child_list+"\"] option[parent]").remove();
8431 $("select[name=\""+child_list+"\"]").append(options);
8433 var options = orig_select.find("option[parent]").clone();
8434 $("select[name=\""+child_list+"\"] option[parent]").remove();
8435 $("select[name=\""+child_list+"\"]").append(options);
8437 } else if(val > 0) {
8438 var options = orig_select.find("option[parent=\""+parentVal+"\"]").clone();
8439 $("select[name=\""+child_list+"\"] option[parent]").remove();
8440 $("select[name=\""+child_list+"\"]").append(options);
8442 var options = orig_select.find("option[parent]").clone();
8443 $("select[name=\""+child_list+"\"] option[parent]").remove();
8444 $("select[name=\""+child_list+"\"]").append(options);
8447 function setListDependencies'.$type.
'() {
8448 jQuery("select option[parent]").parent().each(function() {
8449 var orig_select = {};
8450 var child_list = $(this).attr("name");
8451 orig_select[child_list] = $(this).clone();
8452 var parent = $(this).find("option[parent]:first").attr("parent");
8453 var infos = parent.split(":");
8454 var parent_list = infos[0];
8456 //Hide daughters lists
8457 if ($("#"+child_list).val() == 0 && $("#"+parent_list).val() == 0){
8458 $("#"+child_list).hide();
8460 } else if ($("#"+parent_list).val() != 0){
8461 $("#"+parent_list).show();
8463 //Show the child list if the parent list value is selected
8464 $("select[name=\""+parent_list+"\"]").click(function() {
8465 if ($(this).val() != 0){
8466 $("#"+child_list).show()
8470 //When we change parent list
8471 $("select[name=\""+parent_list+"\"]").change(function() {
8472 showOptions'.$type.
'(child_list, parent_list, orig_select[child_list]);
8473 //Select the value 0 on child list after a change on the parent list
8474 $("#"+child_list).val(0).trigger("change");
8475 //Hide child lists if the parent value is set to 0
8476 if ($(this).val() == 0){
8477 $("#"+child_list).hide();
8483 setListDependencies'.$type.
'();
8497 $module = $this->module;
8498 $element = $this->element;
8500 if ($element ==
'facturerec') {
8501 $element =
'facture';
8502 } elseif ($element ==
'invoice_supplier_rec') {
8503 return $user->rights->fournisseur->facture;
8504 } elseif ($module && !empty($user->rights->$module->$element)) {
8506 return $user->rights->$module->$element;
8509 return $user->rights->$element;
8526 foreach ($tables as $table) {
8527 $sql =
'UPDATE '.$dbs->prefix().$table.
' SET fk_soc = '.((int) $dest_id).
' WHERE fk_soc = '.((int) $origin_id);
8530 if ($ignoreerrors) {
8555 foreach ($tables as $table) {
8556 $sql =
'UPDATE '.MAIN_DB_PREFIX.$table.
' SET fk_product = '.((int) $dest_id).
' WHERE fk_product = '.((int) $origin_id);
8559 if ($ignoreerrors) {
8582 public function defineBuyPrice($unitPrice = 0.0, $discountPercent = 0.0, $fk_product = 0)
8588 if (($unitPrice > 0) && (isset($conf->global->ForceBuyingPriceIfNull) && $conf->global->ForceBuyingPriceIfNull > 0)) {
8590 $buyPrice = $unitPrice * (1 - $discountPercent / 100);
8593 if (!empty($fk_product) && $fk_product > 0) {
8594 if (isset($conf->global->MARGIN_TYPE) && $conf->global->MARGIN_TYPE ==
'costprice') {
8595 require_once DOL_DOCUMENT_ROOT.
'/product/class/product.class.php';
8596 $product =
new Product($this->db);
8597 $result = $product->fetch($fk_product);
8599 $this->errors[] =
'ErrorProductIdDoesNotExists';
8602 if ($product->cost_price > 0) {
8603 $buyPrice = $product->cost_price;
8604 } elseif ($product->pmp > 0) {
8605 $buyPrice = $product->pmp;
8607 } elseif (isset($conf->global->MARGIN_TYPE) && $conf->global->MARGIN_TYPE ==
'pmp') {
8608 require_once DOL_DOCUMENT_ROOT.
'/product/class/product.class.php';
8609 $product =
new Product($this->db);
8610 $result = $product->fetch($fk_product);
8612 $this->errors[] =
'ErrorProductIdDoesNotExists';
8615 if ($product->pmp > 0) {
8616 $buyPrice = $product->pmp;
8620 if (empty($buyPrice) && isset($conf->global->MARGIN_TYPE) && in_array($conf->global->MARGIN_TYPE, array(
'1',
'pmp',
'costprice'))) {
8621 require_once DOL_DOCUMENT_ROOT.
'/fourn/class/fournisseur.product.class.php';
8623 if (($result = $productFournisseur->find_min_price_product_fournisseur($fk_product)) > 0) {
8624 $buyPrice = $productFournisseur->fourn_unitprice;
8625 } elseif ($result < 0) {
8626 $this->errors[] = $productFournisseur->error;
8655 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')
8658 global $conf, $user, $langs;
8660 include_once DOL_DOCUMENT_ROOT.
'/core/lib/files.lib.php';
8661 include_once DOL_DOCUMENT_ROOT.
'/core/lib/images.lib.php';
8663 $sortfield =
'position_name';
8669 $dir .=
get_exdir(0, 0, 0, 0, $this, $modulepart);
8670 $pdir .=
get_exdir(0, 0, 0, 0, $this, $modulepart);
8673 if ($modulepart ==
'product') {
8675 $dir = $sdir.
'/'.
get_exdir($this->
id, 2, 0, 0, $this, $modulepart).$this->id.
"/photos/";
8676 $pdir =
'/'.get_exdir($this->
id, 2, 0, 0, $this, $modulepart).$this->id.
"/photos/";
8683 $relativedir = preg_replace(
'/^'.preg_quote(DOL_DATA_ROOT,
'/').
'/',
'', $dir);
8684 $relativedir = preg_replace(
'/^[\\/]/',
'', $relativedir);
8685 $relativedir = preg_replace(
'/[\\/]$/',
'', $relativedir);
8688 $dirthumb = $dir.
'thumbs/';
8689 $pdirthumb = $pdir.
'thumbs/';
8691 $return =
'<!-- Photo -->'.
"\n";
8694 $filearray =
dol_dir_list($dir,
"files", 0,
'',
'(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) ==
'desc' ?SORT_DESC:SORT_ASC), 1);
8704 if (count($filearray)) {
8705 if ($sortfield && $sortorder) {
8709 foreach ($filearray as $key => $val) {
8711 $file = $val[
'name'];
8717 $viewfilename = $file;
8719 if ($size == 1 || $size ==
'small') {
8726 $photo_vignette = basename($file);
8733 if ($nbphoto == 1) {
8734 $return .=
'<table class="valigntop center centpercent" style="border: 0; padding: 2px; border-spacing: 2px; border-collapse: separate;">';
8737 if ($nbphoto % $nbbyrow == 1) {
8738 $return .=
'<tr class="center valignmiddle" style="border: 1px">';
8740 $return .=
'<td style="width: '.ceil(100 / $nbbyrow).
'%" class="photo">'.
"\n";
8741 } elseif ($nbbyrow < 0) {
8742 $return .=
'<div class="inline-block">'.
"\n";
8745 $relativefile = preg_replace(
'/^\//',
'', $pdir.$photo);
8746 if (empty($nolink)) {
8749 $return .=
'<a href="'.$urladvanced.
'">';
8751 $return .=
'<a href="'.DOL_URL_ROOT.
'/viewimage.php?modulepart='.$modulepart.
'&entity='.$this->entity.
'&file='.urlencode($pdir.$photo).
'" class="aphoto" target="_blank" rel="noopener noreferrer">';
8757 $alt = $langs->transnoentitiesnoconv(
'File').
': '.$relativefile;
8758 $alt .=
' - '.$langs->transnoentitiesnoconv(
'Size').
': '.$imgarray[
'width'].
'x'.$imgarray[
'height'];
8759 if ($overwritetitle) {
8760 if (is_numeric($overwritetitle)) {
8763 $alt = $overwritetitle;
8767 if ($usesharelink) {
8768 if ($val[
'share']) {
8769 if (empty($maxHeight) || ($photo_vignette && $imgarray[
'height'] > $maxHeight)) {
8770 $return .=
'<!-- Show original file (thumb not yet available with shared links) -->';
8771 $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).
'">';
8773 $return .=
'<!-- Show original file -->';
8774 $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).
'">';
8777 $return .=
'<!-- Show nophoto file (because file is not shared) -->';
8778 $return .=
'<img class="photo photowithmargin'.($addphotorefcss ?
' '.$addphotorefcss :
'').
'" height="'.$maxHeight.
'" src="'.DOL_URL_ROOT.
'/public/theme/common/nophoto.png" title="'.
dol_escape_htmltag($alt).
'">';
8781 if (empty($maxHeight) || ($photo_vignette && $imgarray[
'height'] > $maxHeight)) {
8782 $return .=
'<!-- Show thumb -->';
8783 $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).
'">';
8785 $return .=
'<!-- Show original file -->';
8786 $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).
'">';
8790 if (empty($nolink)) {
8794 if ($showfilename) {
8795 $return .=
'<br>'.$viewfilename;
8800 if ($photo_vignette && (
image_format_supported($photo) > 0) && ($this->imgWidth > $maxWidth || $this->imgHeight > $maxHeight)) {
8801 $return .=
'<a href="'.$_SERVER[
"PHP_SELF"].
'?id='.$this->
id.
'&action=addthumb&token='.
newToken().
'&file='.urlencode($pdir.$viewfilename).
'">'.
img_picto($langs->trans(
'GenerateThumb'),
'refresh').
' </a>';
8804 if ($modulepart ==
'product' && ($user->hasRight(
'produit',
'creer') || $user->hasRight(
'service',
'creer'))) {
8806 $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> ';
8809 $return .=
'<a href="'.$_SERVER[
"PHP_SELF"].
'?id='.$this->
id.
'&action=delete&token='.
newToken().
'&file='.urlencode($pdir.$viewfilename).
'">';
8817 if (($nbphoto % $nbbyrow) == 0) {
8820 } elseif ($nbbyrow < 0) {
8821 $return .=
'</div>'.
"\n";
8826 $return .=
'<img class="photo photowithmargin" src="'.DOL_URL_ROOT.
'/viewimage.php?modulepart='.$modulepart.
'&entity='.$this->entity.
'&file='.urlencode($pdir.$photo).
'">';
8828 if ($showfilename) {
8829 $return .=
'<br>'.$viewfilename;
8833 if ($modulepart ==
'product' && ($user->hasRight(
'produit',
'creer') || $user->hasRight(
'service',
'creer'))) {
8835 $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> ';
8838 $return .=
'<a href="'.$_SERVER[
"PHP_SELF"].
'?id='.$this->
id.
'&action=delete&token='.
newToken().
'&file='.urlencode($pdir.$viewfilename).
'">';
8845 if ($nbmax && $nbphoto >= $nbmax) {
8851 if ($size == 1 || $size ==
'small') {
8854 while ($nbphoto % $nbbyrow) {
8855 $return .=
'<td style="width: '.ceil(100 / $nbbyrow).
'%"> </td>';
8860 $return .=
'</table>';
8866 $this->nbphoto = $nbphoto;
8880 if (is_array($info)) {
8881 if (isset($info[
'type']) && $info[
'type'] ==
'array') {
8898 if (isset($info[
'type']) && ($info[
'type'] ==
'date' || $info[
'type'] ==
'datetime' || $info[
'type'] ==
'timestamp')) {
8912 if (is_array($info)) {
8913 if (isset($info[
'type']) && ($info[
'type'] ==
'duration')) {
8931 if (is_array($info)) {
8932 if (isset($info[
'type']) && (preg_match(
'/(^int|int$)/i', $info[
'type']))) {
8950 if (is_array($info)) {
8951 if (isset($info[
'type']) && (preg_match(
'/^(double|real|price)/i', $info[
'type']))) {
8968 if (is_array($info)) {
8969 if (isset($info[
'type']) && $info[
'type'] ==
'text') {
8986 if (is_array($info)) {
8987 if (isset($info[
'notnull']) && $info[
'notnull'] !=
'1') {
9004 if (is_array($info)) {
9005 if (isset($info[
'notnull']) && $info[
'notnull'] ==
'-1') {
9022 if (is_array($info)) {
9023 if (isset($info[
'index']) && $info[
'index'] ==
true) {
9045 $queryarray = array();
9046 foreach ($this->fields as $field => $info) {
9048 if ($this->isDate($info)) {
9049 if (empty($this->{$field})) {
9050 $queryarray[$field] =
null;
9052 $queryarray[$field] = $this->db->idate($this->{$field});
9054 } elseif ($this->isDuration($info)) {
9056 if ((isset($this->{$field}) && $this->{$field} !=
'') || !empty($info[
'notnull'])) {
9057 if (!isset($this->{$field})) {
9058 if (!empty($info[
'default'])) {
9059 $queryarray[$field] = $info[
'default'];
9061 $queryarray[$field] = 0;
9064 $queryarray[$field] = (int) $this->{$field};
9067 $queryarray[$field] =
null;
9069 } elseif ($this->isInt($info) || $this->isFloat($info)) {
9070 if ($field ==
'entity' && is_null($this->{$field})) {
9071 $queryarray[$field] = ((int) $conf->entity);
9074 if ((isset($this->{$field}) && $this->{$field} !=
'') || !empty($info[
'notnull'])) {
9075 if (!isset($this->{$field})) {
9076 $queryarray[$field] = 0;
9077 } elseif ($this->isInt($info)) {
9078 $queryarray[$field] = (int) $this->{$field};
9079 } elseif ($this->isFloat($info)) {
9080 $queryarray[$field] = (double) $this->{$field};
9083 $queryarray[$field] =
null;
9089 $queryarray[$field] = $this->{$field};
9092 if ($info[
'type'] ==
'timestamp' && empty($queryarray[$field])) {
9093 unset($queryarray[$field]);
9095 if (!empty($info[
'notnull']) && $info[
'notnull'] == -1 && empty($queryarray[$field])) {
9096 $queryarray[$field] =
null;
9113 foreach ($this->fields as $field => $info) {
9114 if ($this->isDate($info)) {
9115 if (is_null($obj->$field) || $obj->$field ===
'' || $obj->$field ===
'0000-00-00 00:00:00' || $obj->$field ===
'1000-01-01 00:00:00') {
9118 $this->$field = $db->jdate($obj->$field);
9120 } elseif ($this->isInt($info)) {
9121 if ($field ==
'rowid') {
9122 $this->
id = (int) $obj->$field;
9124 if ($this->isForcedToNullIfZero($info)) {
9125 if (empty($obj->$field)) {
9126 $this->$field =
null;
9128 $this->$field = (double) $obj->$field;
9131 if (!is_null($obj->$field) || (isset($info[
'notnull']) && $info[
'notnull'] == 1)) {
9132 $this->$field = (int) $obj->$field;
9134 $this->$field =
null;
9138 } elseif ($this->isFloat($info)) {
9139 if ($this->isForcedToNullIfZero($info)) {
9140 if (empty($obj->$field)) {
9141 $this->$field =
null;
9143 $this->$field = (double) $obj->$field;
9146 if (!is_null($obj->$field) || (isset($info[
'notnull']) && $info[
'notnull'] == 1)) {
9147 $this->$field = (double) $obj->$field;
9149 $this->$field =
null;
9153 $this->$field = isset($obj->$field) ? $obj->$field :
null;
9158 if (!isset($this->fields[
'ref']) && isset($this->
id)) {
9159 $this->
ref = $this->id;
9169 foreach ($this->fields as $field => $arr) {
9170 $this->$field =
null;
9182 $keys = array_keys($this->fields);
9183 if (!empty($alias)) {
9184 $keys_with_alias = array();
9185 foreach ($keys as $fieldname) {
9186 $keys_with_alias[] = $alias .
'.' . $fieldname;
9188 return implode(
',', $keys_with_alias);
9190 return implode(
',', $keys);
9201 protected function quote($value, $fieldsentry)
9203 if (is_null($value)) {
9205 } elseif (preg_match(
'/^(int|double|real|price)/i', $fieldsentry[
'type'])) {
9207 } elseif (preg_match(
'/int$/i', $fieldsentry[
'type'])) {
9208 return (
int) $value;
9209 } elseif ($fieldsentry[
'type'] ==
'boolean') {
9216 return "'".$this->db->escape($value).
"'";
9231 dol_syslog(get_class($this).
"::createCommon create", LOG_DEBUG);
9237 $fieldvalues = $this->setSaveQuery();
9239 if (array_key_exists(
'date_creation', $fieldvalues) && empty($fieldvalues[
'date_creation'])) {
9240 $fieldvalues[
'date_creation'] = $this->db->idate($now);
9242 if (array_key_exists(
'fk_user_creat', $fieldvalues) && !($fieldvalues[
'fk_user_creat'] > 0)) {
9243 $fieldvalues[
'fk_user_creat'] = $user->id;
9245 unset($fieldvalues[
'rowid']);
9246 if (array_key_exists(
'ref', $fieldvalues)) {
9252 foreach ($fieldvalues as $k => $v) {
9254 $value = $this->fields[$k];
9255 $values[$k] = $this->quote($v, $value);
9259 foreach ($keys as $key) {
9261 if (preg_match(
'/^integer:/i', $this->fields[$key][
'type']) && $values[$key] ==
'-1') {
9264 if (!empty($this->fields[$key][
'foreignkey']) && $values[$key] ==
'-1') {
9268 if (isset($this->fields[$key][
'notnull']) && $this->fields[$key][
'notnull'] == 1 && (!isset($values[$key]) || $values[$key] ===
'NULL') && is_null($this->fields[$key][
'default'])) {
9270 $langs->load(
"errors");
9271 dol_syslog(
"Mandatory field '".$key.
"' is empty and required into ->fields definition of class");
9272 $this->errors[] = $langs->trans(
"ErrorFieldRequired", $this->fields[$key][
'label']);
9276 if (isset($this->fields[$key][
'notnull']) && $this->fields[$key][
'notnull'] == 1 && (!isset($values[$key]) || $values[$key] ===
'NULL') && !is_null($this->fields[$key][
'default'])) {
9277 $values[$key] = $this->quote($this->fields[$key][
'default'], $this->fields[$key]);
9281 if (preg_match(
'/^integer:/i', $this->fields[$key][
'type']) && empty($values[$key])) {
9282 if (isset($this->fields[$key][
'default'])) {
9283 $values[$key] = ((int) $this->fields[$key][
'default']);
9285 $values[$key] =
'null';
9288 if (!empty($this->fields[$key][
'foreignkey']) && empty($values[$key])) {
9289 $values[$key] =
'null';
9300 $sql =
"INSERT INTO ".$this->db->prefix().$this->table_element;
9301 $sql .=
" (".implode(
", ", $keys).
')';
9302 $sql .=
" VALUES (".implode(
", ", $values).
")";
9304 $res = $this->db->query(
$sql);
9307 if ($this->db->lasterrno() ==
'DB_ERROR_RECORD_ALREADY_EXISTS') {
9308 $this->errors[] =
"ErrorRefAlreadyExists";
9310 $this->errors[] = $this->db->lasterror();
9316 $this->
id = $this->db->last_insert_id($this->db->prefix().$this->table_element);
9321 if (key_exists(
'ref', $this->fields) && $this->fields[
'ref'][
'notnull'] > 0 && key_exists(
'default', $this->fields[
'ref']) && $this->fields[
'ref'][
'default'] ==
'(PROV)') {
9322 $sql =
"UPDATE ".$this->db->prefix().$this->table_element.
" SET ref = '(PROV".((int) $this->
id).
")' WHERE (ref = '(PROV)' OR ref = '') AND rowid = ".((int) $this->
id);
9323 $resqlupdate = $this->db->query(
$sql);
9325 if ($resqlupdate ===
false) {
9327 $this->errors[] = $this->db->lasterror();
9329 $this->
ref =
'(PROV'.$this->id.
')';
9336 $result = $this->insertExtraFields();
9343 if (!empty($this->table_element_line) && !empty($this->fk_element)) {
9344 $num = (is_array($this->lines) ? count($this->lines) : 0);
9345 for ($i = 0; $i < $num; $i++) {
9346 $line = $this->lines[$i];
9348 $keyforparent = $this->fk_element;
9349 $line->$keyforparent = $this->id;
9353 if (!is_object($line)) {
9354 $line = (object) $line;
9357 $result = $line->create($user, 1);
9359 $this->error = $line->error;
9360 $this->db->rollback();
9367 if (!$error && !$notrigger) {
9369 $result = $this->call_trigger(strtoupper(get_class($this)).
'_CREATE', $user);
9378 $this->db->rollback();
9381 $this->db->commit();
9397 if (empty($id) && empty($ref) && empty($morewhere)) {
9401 $fieldlist = $this->getFieldList(
't');
9402 if (empty($fieldlist)) {
9406 $sql =
"SELECT ".$fieldlist;
9407 $sql .=
" FROM ".$this->db->prefix().$this->table_element.
' as t';
9410 $sql .=
' WHERE t.rowid = '.((int) $id);
9411 } elseif (!empty($ref)) {
9412 $sql .=
" WHERE t.ref = '".$this->db->escape($ref).
"'";
9414 $sql .=
' WHERE 1 = 1';
9416 if (empty($id) && isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
9417 $sql .=
' AND t.entity IN ('.getEntity($this->element).
')';
9424 $res = $this->db->query(
$sql);
9426 $obj = $this->db->fetch_object($res);
9428 $this->setVarsFromFetchObj($obj);
9432 $this->fetch_optionals();
9439 $this->error = $this->db->lasterror();
9440 $this->errors[] = $this->error;
9453 $objectlineclassname = get_class($this).
'Line';
9454 if (!class_exists($objectlineclassname)) {
9455 $this->error =
'Error, class '.$objectlineclassname.
' not found during call of fetchLinesCommon';
9459 $objectline =
new $objectlineclassname($this->db);
9461 $sql =
"SELECT ".$objectline->getFieldList(
'l');
9462 $sql .=
" FROM ".$this->db->prefix().$objectline->table_element.
" as l";
9463 $sql .=
" WHERE l.fk_".$this->db->escape($this->element).
" = ".((int) $this->
id);
9467 if (isset($objectline->fields[
'position'])) {
9468 $sql .= $this->db->order(
'position',
'ASC');
9471 $resql = $this->db->query(
$sql);
9473 $num_rows = $this->db->num_rows($resql);
9475 while ($i < $num_rows) {
9476 $obj = $this->db->fetch_object($resql);
9478 $newline =
new $objectlineclassname($this->db);
9479 $newline->setVarsFromFetchObj($obj);
9481 $this->lines[] = $newline;
9488 $this->error = $this->db->lasterror();
9489 $this->errors[] = $this->error;
9503 global $conf, $langs;
9504 dol_syslog(get_class($this).
"::updateCommon update", LOG_DEBUG);
9515 $fieldvalues = $this->setSaveQuery();
9517 if (array_key_exists(
'date_modification', $fieldvalues) && empty($fieldvalues[
'date_modification'])) {
9518 $fieldvalues[
'date_modification'] = $this->db->idate($now);
9520 if (array_key_exists(
'fk_user_modif', $fieldvalues) && !($fieldvalues[
'fk_user_modif'] > 0)) {
9521 $fieldvalues[
'fk_user_modif'] = $user->id;
9523 unset($fieldvalues[
'rowid']);
9524 if (array_key_exists(
'ref', $fieldvalues)) {
9532 foreach ($fieldvalues as $k => $v) {
9534 $value = $this->fields[$k];
9535 $values[$k] = $this->quote($v, $value);
9536 $tmp[] = $k.
'='.$this->quote($v, $this->fields[$k]);
9540 foreach ($keys as $key) {
9541 if (preg_match(
'/^integer:/i', $this->fields[$key][
'type']) && $values[$key] ==
'-1') {
9544 if (!empty($this->fields[$key][
'foreignkey']) && $values[$key] ==
'-1') {
9557 $sql =
'UPDATE '.$this->db->prefix().$this->table_element.
' SET '.implode(
', ', $tmp).
' WHERE rowid='.((int) $this->
id);
9562 $res = $this->db->query(
$sql);
9565 $this->errors[] = $this->db->lasterror();
9571 $result = $this->insertExtraFields();
9578 if (!$error && !$notrigger) {
9580 $result = $this->call_trigger(strtoupper(get_class($this)).
'_MODIFY', $user);
9589 $this->db->rollback();
9592 $this->db->commit();
9607 dol_syslog(get_class($this).
"::deleteCommon delete", LOG_DEBUG);
9613 if ($forcechilddeletion) {
9614 foreach ($this->childtables as $table) {
9615 $sql =
"DELETE FROM ".$this->db->prefix().$table.
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
9616 $resql = $this->db->query(
$sql);
9618 $this->error = $this->db->lasterror();
9619 $this->errors[] = $this->error;
9620 $this->db->rollback();
9624 } elseif (!empty($this->childtables)) {
9625 $objectisused = $this->isObjectUsed($this->
id);
9626 if (!empty($objectisused)) {
9627 dol_syslog(get_class($this).
"::deleteCommon Can't delete record as it has some child", LOG_WARNING);
9628 $this->error =
'ErrorRecordHasChildren';
9629 $this->errors[] = $this->error;
9630 $this->db->rollback();
9636 if (is_array($this->childtablesoncascade) && !empty($this->childtablesoncascade)) {
9637 foreach ($this->childtablesoncascade as $table) {
9638 $deleteFromObject = explode(
':', $table);
9639 if (count($deleteFromObject) >= 2) {
9640 $className = str_replace(
'@',
'', $deleteFromObject[0]);
9641 $filePath = $deleteFromObject[1];
9642 $columnName = $deleteFromObject[2];
9643 $TMoreSQL = array();
9644 $more_sql = $deleteFromObject[3];
9645 if (!empty($more_sql)) {
9646 $TMoreSQL[
'customsql'] = $more_sql;
9649 $childObject =
new $className($this->db);
9650 if (method_exists($childObject,
'deleteByParentField')) {
9651 $result = $childObject->deleteByParentField($this->
id, $columnName, $TMoreSQL);
9654 $this->errors[] = $childObject->error;
9659 $this->errors[] =
"You defined a cascade delete on an object $childObject but there is no method deleteByParentField for it";
9664 $this->errors[] =
'Cannot include child class file '.$filePath;
9669 $sql =
"DELETE FROM ".$this->db->prefix().$table.
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
9671 $resql = $this->db->query(
$sql);
9674 $this->error = $this->db->lasterror();
9675 $this->errors[] = $this->error;
9685 $result = $this->call_trigger(strtoupper(get_class($this)).
'_DELETE', $user);
9695 $res = $this->deleteEcmFiles(1);
9702 $res = $this->deleteObjectLinked();
9707 if (!$error && !empty($this->isextrafieldmanaged)) {
9708 $result = $this->deleteExtraFields();
9715 $sql =
'DELETE FROM '.$this->db->prefix().$this->table_element.
' WHERE rowid='.((int) $this->
id);
9717 $resql = $this->db->query(
$sql);
9720 $this->errors[] = $this->db->lasterror();
9726 $this->db->rollback();
9729 $this->db->commit();
9751 if (!empty($parentId) && !empty($parentField)) {
9754 $sql =
"SELECT rowid FROM ".$this->db->prefix().$this->table_element;
9755 $sql .=
" WHERE ".$parentField.
" = ".(int) $parentId;
9758 $sqlwhere = array();
9759 if (count($filter) > 0) {
9760 foreach ($filter as $key => $value) {
9761 if ($key ==
'customsql') {
9762 $sqlwhere[] = $value;
9763 } elseif (strpos($value,
'%') ===
false) {
9764 $sqlwhere[] = $key.
" IN (".$this->db->sanitize($this->db->escape($value)).
")";
9766 $sqlwhere[] = $key.
" LIKE '%".$this->db->escape($value).
"%'";
9770 if (count($sqlwhere) > 0) {
9771 $sql .=
" AND (".implode(
" ".$filtermode.
" ", $sqlwhere).
")";
9774 $resql = $this->db->query(
$sql);
9776 $this->errors[] = $this->db->lasterror();
9779 while ($obj = $this->db->fetch_object($resql)) {
9780 $result = $this->fetch($obj->rowid);
9783 $this->errors[] = $this->error;
9785 if (get_class($this) ==
'Contact') {
9786 $result = $this->
delete();
9788 $result = $this->
delete($user);
9792 $this->errors[] = $this->error;
9800 if (empty($error)) {
9801 $this->db->commit();
9804 $this->error = implode(
', ', $this->errors);
9805 $this->db->rollback();
9827 $tmpforobjectclass = get_class($this);
9828 $tmpforobjectlineclass = ucfirst($tmpforobjectclass).
'Line';
9833 $result = $this->call_trigger(
'LINE'.strtoupper($tmpforobjectclass).
'_DELETE', $user);
9839 if (empty($error)) {
9840 $sql =
"DELETE FROM ".$this->db->prefix().$this->table_element_line;
9841 $sql .=
" WHERE rowid = ".((int) $idline);
9843 $resql = $this->db->query(
$sql);
9845 $this->error =
"Error ".$this->db->lasterror();
9850 if (empty($error)) {
9852 $tmpobjectline =
new $tmpforobjectlineclass($this->db);
9853 if (!isset($tmpobjectline->isextrafieldmanaged) || !empty($tmpobjectline->isextrafieldmanaged)) {
9854 $tmpobjectline->id = $idline;
9855 $result = $tmpobjectline->deleteExtraFields();
9858 $this->error =
"Error ".get_class($this).
"::deleteLineCommon deleteExtraFields error -4 ".$tmpobjectline->error;
9863 if (empty($error)) {
9864 $this->db->commit();
9867 dol_syslog(get_class($this).
"::deleteLineCommon ERROR:".$this->error, LOG_ERR);
9868 $this->db->rollback();
9889 $statusfield =
'status';
9890 if (in_array($this->element, array(
'don',
'donation',
'shipping'))) {
9891 $statusfield =
'fk_statut';
9894 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
9895 $sql .=
" SET ".$statusfield.
" = ".((int) $status);
9896 $sql .=
" WHERE rowid = ".((int) $this->
id);
9898 if ($this->db->query(
$sql)) {
9900 $this->oldcopy = clone $this;
9903 if (!$error && !$notrigger) {
9905 $result = $this->call_trigger($triggercode, $user);
9912 $this->status = $status;
9913 $this->db->commit();
9916 $this->db->rollback();
9920 $this->error = $this->db->error();
9921 $this->db->rollback();
9938 $this->specimen = 1;
9940 'label' =>
'This is label',
9941 'ref' =>
'ABCD1234',
9942 'description' =>
'This is a description',
9944 'note_public' =>
'Public note',
9945 'note_private' =>
'Private note',
9946 'date_creation' => (
dol_now() - 3600 * 48),
9947 'date_modification' => (
dol_now() - 3600 * 24),
9948 'fk_user_creat' => $user->id,
9949 'fk_user_modif' => $user->id,
9952 foreach ($fields as $key => $value) {
9953 if (array_key_exists($key, $this->fields)) {
9954 $this->{$key} = $value;
9959 if (property_exists($this,
'fields')) {
9960 foreach ($this->fields as $key => $value) {
9962 if (array_key_exists($key, $fields)) {
9966 if (!empty($value[
'default'])) {
9967 $this->$key = $value[
'default'];
9984 require_once DOL_DOCUMENT_ROOT.
'/core/class/comment.class.php';
9986 $comment =
new Comment($this->db);
9987 $result = $comment->fetchAllFor($this->element, $this->
id);
9989 $this->errors = array_merge($this->errors, $comment->errors);
9992 $this->comments = $comment->comments;
9994 return count($this->comments);
10004 return count($this->comments);
10015 if (!is_array($parameters)) {
10018 foreach ($parameters as $parameter) {
10019 if (isset($this->$parameter)) {
10020 $this->$parameter = trim($this->$parameter);
10039 require_once DOL_DOCUMENT_ROOT.
'/categories/class/categorie.class.php';
10043 $existing = $c->containing($this->
id, $type_categ,
'id');
10063 if (!is_array($categories)) {
10064 $categories = array($categories);
10067 dol_syslog(get_class($this).
"::setCategoriesCommon Oject Id:".$this->
id.
' type_categ:'.$type_categ.
' nb tag add:'.count($categories), LOG_DEBUG);
10069 require_once DOL_DOCUMENT_ROOT.
'/categories/class/categorie.class.php';
10071 if (empty($type_categ)) {
10072 dol_syslog(__METHOD__.
': Type '.$type_categ.
'is an unknown category type. Done nothing.', LOG_ERR);
10078 $existing = $c->containing($this->
id, $type_categ,
'id');
10079 if ($remove_existing) {
10081 if (is_array($existing)) {
10082 $to_del = array_diff($existing, $categories);
10083 $to_add = array_diff($categories, $existing);
10086 $to_add = $categories;
10090 $to_add = array_diff($categories, $existing);
10097 foreach ($to_del as $del) {
10098 if ($c->fetch($del) > 0) {
10099 $result=$c->del_type($this, $type_categ);
10102 $this->error = $c->error;
10103 $this->errors = $c->errors;
10110 foreach ($to_add as $add) {
10111 if ($c->fetch($add) > 0) {
10112 $result = $c->add_type($this, $type_categ);
10115 $this->error = $c->error;
10116 $this->errors = $c->errors;
10124 return $error ? (-1 * $error) : $ok;
10137 $this->db->begin();
10139 if (empty($type)) {
10140 $type = $this->table_element;
10143 require_once DOL_DOCUMENT_ROOT.
'/categories/class/categorie.class.php';
10144 $categorystatic =
new Categorie($this->db);
10146 $sql =
"INSERT INTO ".$this->db->prefix().
"categorie_".(empty($categorystatic->MAP_CAT_TABLE[$type]) ? $type : $categorystatic->MAP_CAT_TABLE[$type]).
" (fk_categorie, fk_product)";
10147 $sql .=
" SELECT fk_categorie, $toId FROM ".$this->db->prefix().
"categorie_".(empty($categorystatic->MAP_CAT_TABLE[$type]) ? $type : $categorystatic->MAP_CAT_TABLE[$type]);
10148 $sql .=
" WHERE fk_product = ".((int) $fromId);
10150 if (!$this->db->query(
$sql)) {
10151 $this->error = $this->db->lasterror();
10152 $this->db->rollback();
10156 $this->db->commit();
10170 $this->db->begin();
10174 switch ($this->element) {
10176 $element =
'propale';
10179 $element =
'produit';
10181 case 'order_supplier':
10182 $element =
'fournisseur/commande';
10184 case 'invoice_supplier':
10185 $element =
'fournisseur/facture/'.get_exdir($this->
id, 2, 0, 1, $this,
'invoice_supplier');
10188 $element =
'expedition/sending';
10191 $element = $this->element;
10195 $sql =
"DELETE FROM ".$this->db->prefix().
"ecm_files_extrafields WHERE fk_object IN (";
10196 $sql .=
" SELECT rowid FROM ".$this->db->prefix().
"ecm_files WHERE filename LIKE '".$this->db->escape($this->
ref).
"%'";
10197 $sql .=
" AND filepath = '".$this->db->escape($element).
"/".$this->db->escape($this->
ref).
"' AND entity = ".((int) $conf->entity);
10200 if (!$this->db->query(
$sql)) {
10201 $this->error = $this->db->lasterror();
10202 $this->db->rollback();
10207 $sql =
"DELETE FROM ".$this->db->prefix().
"ecm_files";
10208 $sql .=
" WHERE filename LIKE '".$this->db->escape($this->
ref).
"%'";
10209 $sql .=
" AND filepath = '".$this->db->escape($element).
"/".$this->db->escape($this->
ref).
"' AND entity = ".((int) $conf->entity);
10211 if (!$this->db->query(
$sql)) {
10212 $this->error = $this->db->lasterror();
10213 $this->db->rollback();
10220 $sql =
'DELETE FROM '.$this->db->prefix().
"ecm_files_extrafields";
10221 $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).
")";
10222 $resql = $this->db->query(
$sql);
10224 $this->error = $this->db->lasterror();
10225 $this->db->rollback();
10229 $sql =
'DELETE FROM '.$this->db->prefix().
"ecm_files";
10230 $sql .=
" WHERE src_object_type = '".$this->db->escape($this->table_element.(empty($this->module) ?
"" :
"@".$this->module)).
"' AND src_object_id = ".((int) $this->
id);
10231 $resql = $this->db->query(
$sql);
10233 $this->error = $this->db->lasterror();
10234 $this->db->rollback();
10239 $this->db->commit();
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.
clearFieldError($fieldKey)
clear validation message result for a field
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
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.
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.
deleteLineCommon(User $user, $idline, $notrigger=false)
Delete a line of object in database.
static deleteAllItemsLinkedByObjectID($fk_object_where, $field_where, $table_element)
Function used to remove all items linked to an object id in association table.
deleteByParentField($parentId=0, $parentField='', $filter=array(), $filtermode="AND")
Delete all child object from a parent ID.
setFieldError($fieldKey, $msg='')
set validation error message a field
getFieldList($alias='')
Function to concat keys of fields.
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.
setDocModel($user, $modelpdf)
Set last model used by doc generator.
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.
setExtraParameters()
Set extra parameters.
setErrorsFromObject($object)
setErrorsFromObject
update_note_public($note)
Update public note (kept for backward compatibility)
getSpecialCode($lineid)
Get special code of a line.
fetchCommon($id, $ref=null, $morewhere='')
Load object in memory from the database.
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...
showOptionals($extrafields, $mode='view', $params=null, $keysuffix='', $keyprefix='', $onetrtd=0, $display_type='card')
Function to show lines of extrafields with output datas.
hasProductsOrServices($predefined=-1)
Function to say how many lines object contains.
static isExistingObject($element, $id, $ref='', $ref_ext='')
Check an object id/ref exists If you don't need/want to instantiate object and just need to know if o...
isObjectUsed($id=0, $entity=0)
Function to check if an object is used by others (by children).
createCommon(User $user, $notrigger=false)
Create object into database.
updateRangOfLine($rowid, $rang)
Update position of line (rang)
deleteObjectLinked($sourceid=null, $sourcetype='', $targetid=null, $targettype='', $rowid='', $f_user=null, $notrigger=0)
Delete all links between an object $this.
getDefaultCreateValueFor($fieldname, $alternatevalue=null, $type='alphanohtml')
Return the default value to use for a field when showing the create form of object.
getTotalWeightVolume()
Return into unit=0, the calculated total of weight and volume of all lines * qty Calculate by adding ...
deleteCommon(User $user, $notrigger=false, $forcechilddeletion=0)
Delete object in database.
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.
update_price($exclspec=0, $roundingadjust='none', $nodatabaseupdate=0, $seller=null)
Update total_ht, total_ttc, total_vat, total_localtax1, total_localtax2 for an object (sum of lines).
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.
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.
addThumbs($file)
Build thumb.
setSaveQuery()
Function to prepare a part of the query for insert by returning an array with all properties of 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.
validateField($fields, $fieldKey, $fieldValue)
Return validation test result for a field.
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.
setBankAccount($fk_account, $notrigger=false, $userused=null)
Change the bank account.
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.
setShippingMethod($shipping_method_id, $notrigger=false, $userused=null)
Change the shipping method.
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.
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).
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.
updateCommon(User $user, $notrigger=false)
Update object into 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.
update_note($note, $suffix='')
Update note of element.
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.
liste_contact($statusoflink=-1, $source='external', $list=0, $code='', $status=-1, $arrayoftcids=array())
Get array of all contacts for an object.
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 ...
fetchLinesCommon($morewhere='')
Load object in memory from the database.
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.
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.
getFormatedCustomerRef($objref)
Return customer ref for screen output.
getTooltipContentArray($params)
Return array of datas 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...
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.
Class to manage triggers.
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=0, $outputlangs='', $entconv=1, $searchlabel='')
Return country label, code or id from an id, code or label.
getState($id, $withcode='', $dbtouse=0, $withregion=0, $outputlangs='', $entconv=1)
Return state translated from an id.
if(isModEnabled('facture') && $user->hasRight('facture', 'lire')) if((isModEnabled('fournisseur') &&empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) && $user->hasRight("fournisseur", "facture", "lire"))||(isModEnabled('supplier_invoice') && $user->hasRight("supplier_invoice", "lire"))) if(isModEnabled('don') && $user->hasRight('don', 'lire')) if(isModEnabled('tax') &&!empty($user->rights->tax->charges->lire)) if(isModEnabled('facture') &&isModEnabled('commande') && $user->hasRight("commande", "lire") &&empty($conf->global->WORKFLOW_DISABLE_CREATE_INVOICE_FROM_ORDER)) $sql
Social contributions to pay.
if($cancel &&! $id) if($action=='add' &&! $cancel) if($action=='delete') if($id) $form
Actions.
convertSecondToTime($iSecond, $format='all', $lengthOfDay=86400, $lengthOfWeek=7)
Return, in clear text, value of a number of seconds in days, hours and minutes.
print *****$script_file(".$version.") pid c cd cd cd description as p label as s rowid
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($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 informations (by default a local PHP server timestamp) Re...
vatrate($rate, $addpercent=false, $info_bits=0, $usestarfornpr=0, $html=0)
Return a string with VAT rate label formated for view output Used into pdf and HTML pages.
dol_print_ip($ip, $mode=0)
Return an IP formated to be shown on screen.
img_delete($titlealt='default', $other='class="pictodelete"', $morecss='')
Show delete logo.
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 '.
get_date_range($date_start, $date_end, $format='', $outputlangs='', $withparenthesis=1)
Format output for start and end date.
dol_print_error($db='', $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
img_object($titlealt, $picto, $moreatt='', $pictoisfullpath=false, $srconly=0, $notitle=0)
Show a picto called object_picto (generic function)
dol_format_address($object, $withcountry=0, $sep="\n", $outputlangs='', $mode=0, $extralangcode='')
Return a formated address (part address/zip/town/state) according to country rules.
dol_string_nospecial($str, $newstr='_', $badcharstoreplace='', $badcharstoremove='', $keepspaces=0)
Clean a string from all punctuation characters to use it as a ref or login.
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.
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs='', $encodetooutput=false)
Output date in a string format according to outputlangs (or langs if not defined).
dol_print_email($email, $cid=0, $socid=0, $addlink=0, $max=64, $showinvalid=1, $withpicto=0)
Show EMail link formatted for HTML output.
if(!function_exists('dol_getprefix')) dol_include_once($relpath, $classname='')
Make an include_once using default root and alternate root if it fails.
dol_print_phone($phone, $countrycode='', $cid=0, $socid=0, $addlink='', $separ=" ", $withpicto='', $titlealt='', $adddivfloat=0)
Format phone numbers according to country.
dol_now($mode='auto')
Return date for now.
getDolGlobalInt($key, $default=0)
Return dolibarr global constant int value.
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=false, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2)
Show picto whatever it's its name (generic function)
dol_escape_js($stringtoescape, $mode=0, $noescapebackslashn=0)
Returns text escaped for inclusion into javascript code.
dol_sort_array(&$array, $index, $order='asc', $natsort=0, $case_sensitive=0, $keepindex=0)
Advanced sort array by second index function, which produces ascending (default) or descending output...
newToken()
Return the value of token currently saved into session with name 'newtoken'.
dol_eval($s, $returnvalue=0, $hideerrors=1, $onlysimplestring='1')
Replace eval function to add more security.
getImageFileNameForSize($file, $extName, $extImgTarget='')
Return the filename of file to get the thumbs.
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.
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='', $noduplicate=0)
Set event messages in dol_events session object.
dol_print_url($url, $target='_blank', $max=32, $withpicto=0, $morecss='float')
Show Url link.
dol_buildpath($path, $type=0, $returnemptyifnotfound=0)
Return path of url or filesystem.
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.
GETPOSTISSET($paramname)
Return true if we are in a context of submitting the parameter $paramname from a POST of a form.
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 dolibarr global constant string value.
isModEnabled($module)
Is Dolibarr module enabled.
getDictionaryValue($tablename, $field, $id, $checkentity=false, $rowidfield='rowid')
Return the value of a filed into a dictionary for the record $id.
get_exdir($num, $level, $alpha, $withoutslash, $object, $modulepart='')
Return a path to have a the directory according to object where files are stored.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
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).
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.
if(!defined( 'CSRFCHECK_WITH_TOKEN'))
div float
Buy price without taxes.
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.
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.
dol_hash($chain, $type='0')
Returns a hash (non reversible encryption) of a string.