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();
272 public $ref_previous;
313 public $country_code;
356 public $barcode_type;
362 public $barcode_type_code;
368 public $barcode_type_label;
374 public $barcode_type_coder;
380 public $mode_reglement_id;
386 public $cond_reglement_id;
391 public $demand_reason_id;
397 public $transport_mode_id;
404 public $cond_reglement;
411 public $fk_delivery_address;
417 public $shipping_method_id;
423 public $shipping_method;
428 public $multicurrency_code;
433 public $multicurrency_tx;
452 public $last_main_doc;
482 public $note_private;
506 public $total_localtax1;
512 public $total_localtax2;
529 public $comments = array();
555 public $date_creation;
560 public $date_validation;
575 public $date_cloture;
586 public $user_creation;
590 public $user_creation_id;
601 public $user_validation;
605 public $user_validation_id;
609 public $user_closing_id;
615 public $user_modification;
619 public $user_modification_id;
626 public $fk_user_creat;
632 public $fk_user_modif;
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 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");
1074 $already_added =
false;
1075 if (is_array($TListeContacts) && !empty($TListeContacts)) {
1076 foreach ($TListeContacts as $array_contact) {
1077 if ($array_contact[
'status'] == 4 && $array_contact[
'id'] == $fk_socpeople && $array_contact[
'fk_c_type_contact'] == $id_type_contact) {
1078 $already_added =
true;
1084 if (!$already_added) {
1088 $sql =
"INSERT INTO ".$this->db->prefix().
"element_contact";
1089 $sql .=
" (element_id, fk_socpeople, datecreate, statut, fk_c_type_contact) ";
1090 $sql .=
" VALUES (".$this->id.
", ".((int) $fk_socpeople).
" , ";
1091 $sql .=
"'".$this->db->idate($datecreate).
"'";
1092 $sql .=
", 4, ".((int) $id_type_contact);
1095 $resql = $this->db->query($sql);
1098 $result = $this->
call_trigger(strtoupper($this->element).
'_ADD_CONTACT', $user);
1100 $this->db->rollback();
1105 $this->db->commit();
1108 if ($this->db->errno() ==
'DB_ERROR_RECORD_ALREADY_EXISTS') {
1109 $this->error = $this->db->errno();
1110 $this->db->rollback();
1113 $this->error = $this->db->lasterror();
1114 $this->db->rollback();
1134 $contacts = $objFrom->liste_contact(-1, $source);
1135 foreach ($contacts as $contact) {
1136 if ($this->
add_contact($contact[
'id'], $contact[
'fk_c_type_contact'], $contact[
'source']) < 0) {
1153 public function update_contact($rowid, $statut, $type_contact_id = 0, $fk_socpeople = 0)
1157 $sql =
"UPDATE ".$this->db->prefix().
"element_contact set";
1158 $sql .=
" statut = ".$statut;
1159 if ($type_contact_id) {
1160 $sql .=
", fk_c_type_contact = ".((int) $type_contact_id);
1162 if ($fk_socpeople) {
1163 $sql .=
", fk_socpeople = ".((int) $fk_socpeople);
1165 $sql .=
" where rowid = ".((int) $rowid);
1166 $resql = $this->db->query($sql);
1170 $this->error = $this->db->lasterror();
1192 if (!$error && empty($notrigger)) {
1194 $this->context[
'contact_id'] = ((int) $rowid);
1195 $result = $this->
call_trigger(strtoupper($this->element).
'_DELETE_CONTACT', $user);
1203 dol_syslog(get_class($this).
"::delete_contact", LOG_DEBUG);
1205 $sql =
"DELETE FROM ".MAIN_DB_PREFIX.
"element_contact";
1206 $sql .=
" WHERE rowid = ".((int) $rowid);
1208 $result = $this->db->query($sql);
1211 $this->errors[] = $this->db->lasterror();
1216 $this->db->commit();
1219 $this->error = $this->db->lasterror();
1220 $this->db->rollback();
1240 if (!empty($typeContact)) {
1241 foreach ($typeContact as $key => $value) {
1242 array_push($temp, $key);
1244 $listId = implode(
",", $temp);
1249 if (empty($listId)) {
1253 $sql =
"DELETE FROM ".$this->db->prefix().
"element_contact";
1254 $sql .=
" WHERE element_id = ".((int) $this->
id);
1255 $sql .=
" AND fk_c_type_contact IN (".$this->db->sanitize($listId).
")";
1257 dol_syslog(get_class($this).
"::delete_linked_contact", LOG_DEBUG);
1258 if ($this->db->query($sql)) {
1261 $this->error = $this->db->lasterror();
1278 public function liste_contact($statusoflink = -1, $source =
'external', $list = 0, $code =
'', $status = -1, $arrayoftcids = array())
1285 $sql =
"SELECT ec.rowid, ec.statut as statuslink, ec.fk_socpeople as id, ec.fk_c_type_contact";
1286 if ($source ==
'internal') {
1287 $sql .=
", '-1' as socid, t.statut as statuscontact, t.login, t.photo";
1289 if ($source ==
'external' || $source ==
'thirdparty') {
1290 $sql .=
", t.fk_soc as socid, t.statut as statuscontact";
1292 $sql .=
", t.civility as civility, t.lastname as lastname, t.firstname, t.email";
1293 $sql .=
", tc.source, tc.element, tc.code, tc.libelle";
1294 $sql .=
" FROM ".$this->db->prefix().
"c_type_contact tc,";
1295 $sql .=
" ".$this->db->prefix().
"element_contact ec";
1296 if ($source ==
'internal') {
1297 $sql .=
" LEFT JOIN ".$this->db->prefix().
"user t on ec.fk_socpeople = t.rowid";
1299 if ($source ==
'external' || $source ==
'thirdparty') {
1300 $sql .=
" LEFT JOIN ".$this->db->prefix().
"socpeople t on ec.fk_socpeople = t.rowid";
1302 $sql .=
" WHERE ec.element_id = ".((int) $this->
id);
1303 $sql .=
" AND ec.fk_c_type_contact = tc.rowid";
1304 $sql .=
" AND tc.element = '".$this->db->escape($this->element).
"'";
1306 $sql .=
" AND tc.code = '".$this->db->escape($code).
"'";
1308 if ($source ==
'internal') {
1309 $sql .=
" AND tc.source = 'internal'";
1311 $sql .=
" AND t.statut = ".((int) $status);
1314 if ($source ==
'external' || $source ==
'thirdparty') {
1315 $sql .=
" AND tc.source = 'external'";
1317 $sql .=
" AND t.statut = ".((int) $status);
1320 $sql .=
" AND tc.active = 1";
1321 if ($statusoflink >= 0) {
1322 $sql .=
" AND ec.statut = ".((int) $statusoflink);
1324 $sql .=
" ORDER BY t.lastname ASC";
1326 dol_syslog(get_class($this).
"::liste_contact", LOG_DEBUG);
1327 $resql = $this->db->query($sql);
1329 $num = $this->db->num_rows($resql);
1332 $obj = $this->db->fetch_object($resql);
1335 $transkey =
"TypeContact_".$obj->element.
"_".$obj->source.
"_".$obj->code;
1336 $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle);
1338 'parentId' => $this->
id,
1339 'source' => $obj->source,
1340 'socid' => $obj->socid,
1342 'nom' => $obj->lastname,
1343 'civility' => $obj->civility,
1344 'lastname' => $obj->lastname,
1345 'firstname' => $obj->firstname,
1346 'email'=>$obj->email,
1347 'login'=> (empty($obj->login) ?
'' : $obj->login),
1348 'photo' => (empty($obj->photo) ?
'' : $obj->photo),
1349 'statuscontact' => $obj->statuscontact,
1350 'rowid' => $obj->rowid,
1351 'code' => $obj->code,
1352 'libelle' => $libelle_type,
1353 'status' => $obj->statuslink,
1354 'fk_c_type_contact' => $obj->fk_c_type_contact
1357 $tab[$i] = $obj->id;
1365 $this->error = $this->db->lasterror();
1380 $sql =
"SELECT ec.datecreate, ec.statut, ec.fk_socpeople, ec.fk_c_type_contact,";
1381 $sql .=
" tc.code, tc.libelle";
1382 $sql .=
" FROM (".$this->db->prefix().
"element_contact as ec, ".$this->db->prefix().
"c_type_contact as tc)";
1383 $sql .=
" WHERE ec.rowid =".((int) $rowid);
1384 $sql .=
" AND ec.fk_c_type_contact=tc.rowid";
1385 $sql .=
" AND tc.element = '".$this->db->escape($this->element).
"'";
1387 dol_syslog(get_class($this).
"::swapContactStatus", LOG_DEBUG);
1388 $resql = $this->db->query($sql);
1390 $obj = $this->db->fetch_object($resql);
1391 $newstatut = ($obj->statut == 4) ? 5 : 4;
1393 $this->db->free($resql);
1396 $this->error = $this->db->error();
1413 public function liste_type_contact($source =
'internal', $order =
'position', $option = 0, $activeonly = 0, $code =
'')
1418 if (empty($order)) {
1419 $order =
'position';
1421 if ($order ==
'position') {
1426 $sql =
"SELECT DISTINCT tc.rowid, tc.code, tc.libelle, tc.position";
1427 $sql .=
" FROM ".$this->db->prefix().
"c_type_contact as tc";
1428 $sql .=
" WHERE tc.element='".$this->db->escape($this->element).
"'";
1429 if ($activeonly == 1) {
1430 $sql .=
" AND tc.active=1";
1432 if (!empty($source) && $source !=
'all') {
1433 $sql .=
" AND tc.source='".$this->db->escape($source).
"'";
1435 if (!empty($code)) {
1436 $sql .=
" AND tc.code='".$this->db->escape($code).
"'";
1438 $sql .= $this->db->order($order,
'ASC');
1441 $resql = $this->db->query($sql);
1443 $num = $this->db->num_rows($resql);
1446 $obj = $this->db->fetch_object($resql);
1448 $transkey =
"TypeContact_".$this->element.
"_".$source.
"_".$obj->code;
1449 $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle);
1450 if (empty($option)) {
1451 $tab[$obj->rowid] = $libelle_type;
1453 $tab[$obj->code] = $libelle_type;
1459 $this->error = $this->db->lasterror();
1476 public function listeTypeContacts($source =
'internal', $option = 0, $activeonly = 0, $code =
'', $element =
'', $excludeelement =
'')
1478 global $langs, $conf;
1480 $langs->loadLangs(array(
'bills',
'contracts',
'interventions',
'orders',
'projects',
'propal',
'ticket',
'agenda'));
1484 $sql =
"SELECT DISTINCT tc.rowid, tc.code, tc.libelle, tc.position, tc.element";
1485 $sql .=
" FROM ".$this->db->prefix().
"c_type_contact as tc";
1487 $sqlWhere = array();
1488 if (!empty($element)) {
1489 $sqlWhere[] =
" tc.element='".$this->db->escape($element).
"'";
1491 if (!empty($excludeelement)) {
1492 $sqlWhere[] =
" tc.element <> '".$this->db->escape($excludeelement).
"'";
1495 if ($activeonly == 1) {
1496 $sqlWhere[] =
" tc.active=1";
1499 if (!empty($source) && $source !=
'all') {
1500 $sqlWhere[] =
" tc.source='".$this->db->escape($source).
"'";
1503 if (!empty($code)) {
1504 $sqlWhere[] =
" tc.code='".$this->db->escape($code).
"'";
1507 if (count($sqlWhere) > 0) {
1508 $sql .=
" WHERE ".implode(
' AND ', $sqlWhere);
1511 $sql .= $this->db->order(
'tc.element, tc.position',
'ASC');
1514 $resql = $this->db->query($sql);
1516 $num = $this->db->num_rows($resql);
1518 $langs->loadLangs(array(
"propal",
"orders",
"bills",
"suppliers",
"contracts",
"supplier_proposal"));
1520 while ($obj = $this->db->fetch_object($resql)) {
1521 $modulename = $obj->element;
1522 if (strpos($obj->element,
'project') !==
false) {
1523 $modulename =
'projet';
1524 } elseif ($obj->element ==
'contrat') {
1525 $element =
'contract';
1526 } elseif ($obj->element ==
'action') {
1527 $modulename =
'agenda';
1528 } elseif (strpos($obj->element,
'supplier') !==
false && $obj->element !=
'supplier_proposal') {
1529 $modulename =
'fournisseur';
1530 } elseif (strpos($obj->element,
'supplier') !==
false && $obj->element !=
'supplier_proposal') {
1531 $modulename =
'fournisseur';
1533 if (!empty($conf->{$modulename}->enabled)) {
1534 $libelle_element = $langs->trans(
'ContactDefault_'.$obj->element);
1535 $tmpelement = $obj->element;
1536 $transkey =
"TypeContact_".$tmpelement.
"_".$source.
"_".$obj->code;
1537 $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle);
1538 if (empty($option)) {
1539 $tab[$obj->rowid] = $libelle_element.
' - '.$libelle_type;
1541 $tab[$obj->rowid] = $libelle_element.
' - '.$libelle_type;
1548 $this->error = $this->db->lasterror();
1571 if ($this->element ==
'shipping' && $this->origin_id != 0) {
1572 $id = $this->origin_id;
1573 $element =
'commande';
1574 } elseif ($this->element ==
'reception' && $this->origin_id != 0) {
1575 $id = $this->origin_id;
1576 $element =
'order_supplier';
1579 $element = $this->element;
1582 $sql =
"SELECT ec.fk_socpeople";
1583 $sql .=
" FROM ".$this->db->prefix().
"element_contact as ec,";
1584 if ($source ==
'internal') {
1585 $sql .=
" ".$this->db->prefix().
"user as c,";
1587 if ($source ==
'external') {
1588 $sql .=
" ".$this->db->prefix().
"socpeople as c,";
1590 $sql .=
" ".$this->db->prefix().
"c_type_contact as tc";
1591 $sql .=
" WHERE ec.element_id = ".((int) $id);
1592 $sql .=
" AND ec.fk_socpeople = c.rowid";
1593 if ($source ==
'internal') {
1594 $sql .=
" AND c.entity IN (".getEntity(
'user').
")";
1596 if ($source ==
'external') {
1597 $sql .=
" AND c.entity IN (".getEntity(
'societe').
")";
1599 $sql .=
" AND ec.fk_c_type_contact = tc.rowid";
1600 $sql .=
" AND tc.element = '".$this->db->escape($element).
"'";
1601 $sql .=
" AND tc.source = '".$this->db->escape($source).
"'";
1603 $sql .=
" AND tc.code = '".$this->db->escape($code).
"'";
1605 $sql .=
" AND tc.active = 1";
1607 $sql .=
" AND ec.statut = ".((int) $status);
1610 dol_syslog(get_class($this).
"::getIdContact", LOG_DEBUG);
1611 $resql = $this->db->query($sql);
1613 while ($obj = $this->db->fetch_object($resql)) {
1614 $result[$i] = $obj->fk_socpeople;
1618 $this->error = $this->db->error();
1635 if (empty($contactid)) {
1636 $contactid = $this->contact_id;
1639 if (empty($contactid)) {
1643 require_once DOL_DOCUMENT_ROOT.
'/contact/class/contact.class.php';
1644 $contact =
new Contact($this->db);
1645 $result = $contact->fetch($contactid);
1646 $this->contact = $contact;
1662 if (empty($this->socid) && empty($this->fk_soc) && empty($force_thirdparty_id)) {
1666 require_once DOL_DOCUMENT_ROOT.
'/societe/class/societe.class.php';
1668 $idtofetch = isset($this->socid) ? $this->socid : (isset($this->fk_soc) ? $this->fk_soc : 0);
1669 if ($force_thirdparty_id) {
1670 $idtofetch = $force_thirdparty_id;
1674 $thirdparty =
new Societe($this->db);
1675 $result = $thirdparty->fetch($idtofetch);
1677 $this->errors=array_merge($this->errors, $thirdparty->errors);
1679 $this->thirdparty = $thirdparty;
1682 if (!empty($conf->global->PRODUIT_MULTIPRICES) && empty($this->thirdparty->price_level)) {
1683 $this->thirdparty->price_level = 1;
1702 if (!$this->table_ref_field) {
1706 $sql =
"SELECT rowid FROM ".$this->db->prefix().$this->table_element.
" WHERE ".$this->table_ref_field.
" LIKE '".$this->db->escape($ref).
"' LIMIT 1";
1708 $query = $this->db->query($sql);
1710 if (!$this->db->num_rows($query)) {
1714 $result = $this->db->fetch_object($query);
1716 return $this->fetch($result->rowid);
1732 dol_syslog(get_class($this).
'::fetch_barcode this->element='.$this->element.
' this->barcode_type='.$this->barcode_type);
1734 $idtype = $this->barcode_type;
1735 if (empty($idtype) && $idtype !=
'0') {
1736 if ($this->element ==
'product' && !empty($conf->global->PRODUIT_DEFAULT_BARCODE_TYPE)) {
1737 $idtype = $conf->global->PRODUIT_DEFAULT_BARCODE_TYPE;
1738 } elseif ($this->element ==
'societe') {
1739 $idtype = $conf->global->GENBARCODE_BARCODETYPE_THIRDPARTY;
1741 dol_syslog(
'Call fetch_barcode with barcode_type not defined and cant be guessed', LOG_WARNING);
1746 if (empty($this->barcode_type) || empty($this->barcode_type_code) || empty($this->barcode_type_label) || empty($this->barcode_type_coder)) {
1747 $sql =
"SELECT rowid, code, libelle as label, coder";
1748 $sql .=
" FROM ".$this->db->prefix().
"c_barcode_type";
1749 $sql .=
" WHERE rowid = ".((int) $idtype);
1750 dol_syslog(get_class($this).
'::fetch_barcode', LOG_DEBUG);
1751 $resql = $this->db->query($sql);
1753 $obj = $this->db->fetch_object($resql);
1754 $this->barcode_type = $obj->rowid;
1755 $this->barcode_type_code = $obj->code;
1756 $this->barcode_type_label = $obj->label;
1757 $this->barcode_type_coder = $obj->coder;
1777 return $this->fetch_projet();
1789 include_once DOL_DOCUMENT_ROOT.
'/projet/class/project.class.php';
1791 if (empty($this->fk_project) && !empty($this->fk_projet)) {
1792 $this->fk_project = $this->fk_projet;
1794 if (empty($this->fk_project)) {
1798 $project =
new Project($this->db);
1799 $result = $project->fetch($this->fk_project);
1801 $this->projet = $project;
1802 $this->project = $project;
1815 include_once DOL_DOCUMENT_ROOT.
'/product/class/product.class.php';
1817 if (empty($this->fk_product)) {
1821 $product =
new Product($this->db);
1822 $result = $product->fetch($this->fk_product);
1824 $this->product = $product;
1838 $user =
new User($this->db);
1839 $result = $user->fetch($userid);
1840 $this->
user = $user;
1853 if ($this->origin ==
'shipping') {
1854 $this->origin =
'expedition';
1856 if ($this->origin ==
'delivery') {
1857 $this->origin =
'livraison';
1859 if ($this->origin ==
'order_supplier') {
1860 $this->origin =
'commandeFournisseur';
1863 $origin = $this->origin;
1865 $classname = ucfirst($origin);
1866 $this->$origin =
new $classname($this->db);
1867 $this->$origin->fetch($this->origin_id);
1885 $sql =
"SELECT rowid FROM ".$this->db->prefix().$table;
1886 $sql .=
" WHERE ".$field.
" = '".$this->db->escape($key).
"'";
1887 if (!empty($element)) {
1888 $sql .=
" AND entity IN (".getEntity($element).
")";
1890 $sql .=
" AND entity = ".((int) $conf->entity);
1893 dol_syslog(get_class($this).
'::fetchObjectFrom', LOG_DEBUG);
1894 $resql = $this->db->query($sql);
1896 $row = $this->db->fetch_row($resql);
1899 $result = $this->fetch($row[0]);
1917 if (!empty($id) && !empty($field) && !empty($table)) {
1918 $sql =
"SELECT ".$field.
" FROM ".$this->db->prefix().$table;
1919 $sql .=
" WHERE rowid = ".((int) $id);
1921 dol_syslog(get_class($this).
'::getValueFrom', LOG_DEBUG);
1922 $resql = $this->db->query($sql);
1924 $row = $this->db->fetch_row($resql);
1947 public function setValueFrom($field, $value, $table =
'', $id =
null, $format =
'', $id_field =
'', $fuser =
null, $trigkey =
'', $fk_user_field =
'fk_user_modif')
1951 if (empty($table)) {
1952 $table = $this->table_element;
1957 if (empty($format)) {
1960 if (empty($id_field)) {
1961 $id_field =
'rowid';
1965 if ($table ==
'product' && $field ==
'note_private') {
1969 if (in_array($table, array(
'actioncomm',
'adherent',
'advtargetemailing',
'cronjob',
'establishment'))) {
1970 $fk_user_field =
'fk_user_mod';
1972 if (in_array($table, array(
'prelevement_bons'))) {
1973 $fk_user_field =
'';
1979 $sql =
"SELECT " . $field;
1980 $sql .=
" FROM " . MAIN_DB_PREFIX . $table;
1981 $sql .=
" WHERE " . $id_field .
" = " . ((int) $id);
1983 $resql = $this->db->query($sql);
1985 if ($obj = $this->db->fetch_object($resql)) {
1986 if ($format ==
'date') {
1987 $oldvalue = $this->db->jdate($obj->$field);
1989 $oldvalue = $obj->$field;
1993 $this->error = $this->db->lasterror();
2004 $sql =
"UPDATE ".$this->db->prefix().$table.
" SET ";
2006 if ($format ==
'text') {
2007 $sql .= $field.
" = '".$this->db->escape($value).
"'";
2008 } elseif ($format ==
'int') {
2009 $sql .= $field.
" = ".((int) $value);
2010 } elseif ($format ==
'date') {
2011 $sql .= $field.
" = ".($value ?
"'".$this->db->idate($value).
"'" :
"null");
2012 } elseif ($format ==
'dategmt') {
2013 $sql .= $field.
" = ".($value ?
"'".$this->db->idate($value,
'gmt').
"'" :
"null");
2016 if ($fk_user_field) {
2017 if (!empty($fuser) && is_object($fuser)) {
2018 $sql .=
", ".$fk_user_field.
" = ".((int) $fuser->id);
2019 } elseif (empty($fuser) || $fuser !=
'none') {
2020 $sql .=
", ".$fk_user_field.
" = ".((int) $user->id);
2024 $sql .=
" WHERE ".$id_field.
" = ".((int) $id);
2026 $resql = $this->db->query($sql);
2030 if (method_exists($this,
'fetch')) {
2031 $result = $this->fetch($id);
2033 $result = $this->fetchCommon($id);
2035 $this->oldcopy = clone $this;
2036 if (property_exists($this->oldcopy, $field)) {
2037 $this->oldcopy->$field = $oldvalue;
2041 $result = $this->call_trigger($trigkey, (!empty($fuser) && is_object($fuser)) ? $fuser : $user);
2049 if (property_exists($this, $field)) {
2050 $this->$field = $value;
2052 $this->db->commit();
2055 $this->db->rollback();
2059 if ($this->db->lasterrno() ==
'DB_ERROR_RECORD_ALREADY_EXISTS') {
2060 $this->error =
'DB_ERROR_RECORD_ALREADY_EXISTS';
2062 $this->error = $this->db->lasterror();
2064 $this->db->rollback();
2082 global $conf, $user;
2084 if (!$this->table_element) {
2085 dol_print_error(
'', get_class($this).
"::load_previous_next_ref was called on objet with property table_element not defined");
2088 if ($fieldid ==
'none') {
2093 if (in_array($this->table_element, array(
'facture_rec',
'facture_fourn_rec')) && $fieldid ==
'title') {
2099 if ($user->socid > 0) {
2100 $socid = $user->socid;
2105 $aliastablesociete =
's';
2106 if ($this->element ==
'societe') {
2107 $aliastablesociete =
'te';
2109 $restrictiononfksoc = empty($this->restrictiononfksoc) ? 0 : $this->restrictiononfksoc;
2110 $sql =
"SELECT MAX(te.".$fieldid.
")";
2111 $sql .=
" FROM ".(empty($nodbprefix) ?$this->db->prefix():
'').$this->table_element.
" as te";
2112 if ($this->element ==
'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
2113 if (empty($user->admin) || !empty($user->entity) || $conf->entity != 1) {
2114 $sql .=
" INNER JOIN ".MAIN_DB_PREFIX.
"usergroup_user as ug ON ug.fk_user = te.rowid";
2117 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2118 $tmparray = explode(
'@', $this->ismultientitymanaged);
2119 $sql .=
", ".$this->db->prefix().$tmparray[1].
" as ".($tmparray[1] ==
'societe' ?
's' :
'parenttable');
2120 } elseif ($restrictiononfksoc == 1 && $this->element !=
'societe' && empty($user->rights->societe->client->voir) && !$socid) {
2121 $sql .=
", ".$this->db->prefix().
"societe as s";
2122 } elseif ($restrictiononfksoc == 2 && $this->element !=
'societe' && empty($user->rights->societe->client->voir) && !$socid) {
2123 $sql .=
" LEFT JOIN ".$this->db->prefix().
"societe as s ON te.fk_soc = s.rowid";
2125 if ($restrictiononfksoc && empty($user->rights->societe->client->voir) && !$socid) {
2126 $sql .=
" LEFT JOIN ".$this->db->prefix().
"societe_commerciaux as sc ON ".$aliastablesociete.
".rowid = sc.fk_soc";
2128 $sql .=
" WHERE te.".$fieldid.
" < '".$this->db->escape($fieldid ==
'rowid' ? $this->
id : $this->ref).
"'";
2129 if ($restrictiononfksoc == 1 && empty($user->rights->societe->client->voir) && !$socid) {
2130 $sql .=
" AND sc.fk_user = ".((int) $user->id);
2132 if ($restrictiononfksoc == 2 && empty($user->rights->societe->client->voir) && !$socid) {
2133 $sql .=
" AND (sc.fk_user = ".((int) $user->id).
' OR te.fk_soc IS NULL)';
2135 if (!empty($filter)) {
2136 if (!preg_match(
'/^\s*AND/i', $filter)) {
2141 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2142 $tmparray = explode(
'@', $this->ismultientitymanaged);
2143 $sql .=
" AND te.".$tmparray[0].
" = ".($tmparray[1] ==
"societe" ?
"s" :
"parenttable").
".rowid";
2144 } elseif ($restrictiononfksoc == 1 && $this->element !=
'societe' && empty($user->rights->societe->client->voir) && !$socid) {
2145 $sql .=
' AND te.fk_soc = s.rowid';
2147 if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
2148 if ($this->element ==
'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
2149 if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
2150 $sql .=
" AND te.entity IS NOT NULL";
2152 $sql .=
" AND ug.entity IN (".getEntity(
'usergroup').
")";
2155 $sql .=
' AND te.entity IN ('.getEntity($this->element).
')';
2158 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged) && $this->element !=
'societe') {
2159 $tmparray = explode(
'@', $this->ismultientitymanaged);
2160 $sql .=
' AND parenttable.entity IN ('.getEntity($tmparray[1]).
')';
2162 if ($restrictiononfksoc == 1 && $socid && $this->element !=
'societe') {
2163 $sql .=
' AND te.fk_soc = '.((int) $socid);
2165 if ($restrictiononfksoc == 2 && $socid && $this->element !=
'societe') {
2166 $sql .=
' AND (te.fk_soc = '.((int) $socid).
' OR te.fk_soc IS NULL)';
2168 if ($restrictiononfksoc && $socid && $this->element ==
'societe') {
2169 $sql .=
' AND te.rowid = '.((int) $socid);
2173 $result = $this->db->query($sql);
2175 $this->error = $this->db->lasterror();
2178 $row = $this->db->fetch_row($result);
2179 $this->ref_previous = $row[0];
2181 $sql =
"SELECT MIN(te.".$fieldid.
")";
2182 $sql .=
" FROM ".(empty($nodbprefix) ?$this->db->prefix():
'').$this->table_element.
" as te";
2183 if ($this->element ==
'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
2184 if (empty($user->admin) || !empty($user->entity) || $conf->entity != 1) {
2185 $sql .=
" INNER JOIN ".MAIN_DB_PREFIX.
"usergroup_user as ug ON ug.fk_user = te.rowid";
2188 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2189 $tmparray = explode(
'@', $this->ismultientitymanaged);
2190 $sql .=
", ".$this->db->prefix().$tmparray[1].
" as ".($tmparray[1] ==
'societe' ?
's' :
'parenttable');
2191 } elseif ($restrictiononfksoc == 1 && $this->element !=
'societe' && empty($user->rights->societe->client->voir) && !$socid) {
2192 $sql .=
", ".$this->db->prefix().
"societe as s";
2193 } elseif ($restrictiononfksoc == 2 && $this->element !=
'societe' && empty($user->rights->societe->client->voir) && !$socid) {
2194 $sql .=
" LEFT JOIN ".$this->db->prefix().
"societe as s ON te.fk_soc = s.rowid";
2196 if ($restrictiononfksoc && empty($user->rights->societe->client->voir) && !$socid) {
2197 $sql .=
" LEFT JOIN ".$this->db->prefix().
"societe_commerciaux as sc ON ".$aliastablesociete.
".rowid = sc.fk_soc";
2199 $sql .=
" WHERE te.".$fieldid.
" > '".$this->db->escape($fieldid ==
'rowid' ? $this->
id : $this->ref).
"'";
2200 if ($restrictiononfksoc == 1 && empty($user->rights->societe->client->voir) && !$socid) {
2201 $sql .=
" AND sc.fk_user = ".((int) $user->id);
2203 if ($restrictiononfksoc == 2 && empty($user->rights->societe->client->voir) && !$socid) {
2204 $sql .=
" AND (sc.fk_user = ".((int) $user->id).
' OR te.fk_soc IS NULL)';
2206 if (!empty($filter)) {
2207 if (!preg_match(
'/^\s*AND/i', $filter)) {
2212 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2213 $tmparray = explode(
'@', $this->ismultientitymanaged);
2214 $sql .=
" AND te.".$tmparray[0].
" = ".($tmparray[1] ==
"societe" ?
"s" :
"parenttable").
".rowid";
2215 } elseif ($restrictiononfksoc == 1 && $this->element !=
'societe' && empty($user->rights->societe->client->voir) && !$socid) {
2216 $sql .=
' AND te.fk_soc = s.rowid';
2218 if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
2219 if ($this->element ==
'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
2220 if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
2221 $sql .=
" AND te.entity IS NOT NULL";
2223 $sql .=
" AND ug.entity IN (".getEntity(
'usergroup').
")";
2226 $sql .=
' AND te.entity IN ('.getEntity($this->element).
')';
2229 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged) && $this->element !=
'societe') {
2230 $tmparray = explode(
'@', $this->ismultientitymanaged);
2231 $sql .=
' AND parenttable.entity IN ('.getEntity($tmparray[1]).
')';
2233 if ($restrictiononfksoc == 1 && $socid && $this->element !=
'societe') {
2234 $sql .=
' AND te.fk_soc = '.((int) $socid);
2236 if ($restrictiononfksoc == 2 && $socid && $this->element !=
'societe') {
2237 $sql .=
' AND (te.fk_soc = '.((int) $socid).
' OR te.fk_soc IS NULL)';
2239 if ($restrictiononfksoc && $socid && $this->element ==
'societe') {
2240 $sql .=
' AND te.rowid = '.((int) $socid);
2245 $result = $this->db->query($sql);
2247 $this->error = $this->db->lasterror();
2250 $row = $this->db->fetch_row($result);
2251 $this->ref_next = $row[0];
2266 $contactAlreadySelected = array();
2267 $tab = $this->liste_contact(-1, $source);
2271 if ($source ==
'thirdparty') {
2272 $contactAlreadySelected[$i] = $tab[$i][
'socid'];
2274 $contactAlreadySelected[$i] = $tab[$i][
'id'];
2278 return $contactAlreadySelected;
2294 if (!$this->table_element) {
2295 dol_syslog(get_class($this).
"::setProject was called on objet with property table_element not defined", LOG_ERR);
2299 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
2300 if (!empty($this->fields[
'fk_project'])) {
2302 $sql .=
" SET fk_project = ".((int) $projectid);
2304 $sql .=
" SET fk_project = NULL";
2306 $sql .=
' WHERE rowid = '.((int) $this->
id);
2307 } elseif ($this->table_element ==
'actioncomm') {
2309 $sql .=
" SET fk_project = ".((int) $projectid);
2311 $sql .=
" SET fk_project = NULL";
2313 $sql .=
' WHERE id = '.((int) $this->
id);
2317 $sql .=
' SET fk_projet = '.((int) $projectid);
2319 $sql .=
' SET fk_projet = NULL';
2321 $sql .=
" WHERE rowid = ".((int) $this->
id);
2326 dol_syslog(get_class($this).
"::setProject", LOG_DEBUG);
2327 if ($this->db->query($sql)) {
2328 $this->fk_project = ((int) $projectid);
2335 if (!$error && !$notrigger) {
2337 $result = $this->call_trigger(strtoupper($this->element) .
'_MODIFY', $user);
2346 $this->db->rollback();
2349 $this->db->commit();
2364 $error = 0; $notrigger = 0;
2366 dol_syslog(get_class($this).
'::setPaymentMethods('.$id.
')');
2368 if ($this->
statut >= 0 || $this->element ==
'societe') {
2370 $fieldname =
'fk_mode_reglement';
2371 if ($this->element ==
'societe') {
2372 $fieldname =
'mode_reglement';
2374 if (get_class($this) ==
'Fournisseur') {
2375 $fieldname =
'mode_reglement_supplier';
2377 if (get_class($this) ==
'Tva') {
2378 $fieldname =
'fk_typepayment';
2380 if (get_class($this) ==
'Salary') {
2381 $fieldname =
'fk_typepayment';
2384 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
2385 $sql .=
" SET ".$fieldname.
" = ".(($id > 0 || $id ==
'0') ? ((
int) $id) :
'NULL');
2386 $sql .=
' WHERE rowid='.((int) $this->
id);
2388 if ($this->db->query($sql)) {
2389 $this->mode_reglement_id = $id;
2391 if (get_class($this) ==
'Fournisseur') {
2392 $this->mode_reglement_supplier_id = $id;
2395 if (!$error && !$notrigger) {
2397 if (get_class($this) ==
'Commande') {
2398 $result = $this->call_trigger(
'ORDER_MODIFY', $user);
2400 $result = $this->call_trigger(strtoupper(get_class($this)).
'_MODIFY', $user);
2409 dol_syslog(get_class($this).
'::setPaymentMethods Error '.$this->db->error());
2410 $this->error = $this->db->error();
2414 dol_syslog(get_class($this).
'::setPaymentMethods, status of the object is incompatible');
2415 $this->error =
'Status of the object is incompatible '.$this->statut;
2428 dol_syslog(get_class($this).
'::setMulticurrencyCode('.$code.
')');
2429 if ($this->
statut >= 0 || $this->element ==
'societe') {
2430 $fieldname =
'multicurrency_code';
2432 $sql =
'UPDATE '.$this->db->prefix().$this->table_element;
2433 $sql .=
" SET ".$fieldname.
" = '".$this->db->escape($code).
"'";
2434 $sql .=
' WHERE rowid='.((int) $this->
id);
2436 if ($this->db->query($sql)) {
2437 $this->multicurrency_code = $code;
2441 $this->setMulticurrencyRate($rate, 2);
2446 dol_syslog(get_class($this).
'::setMulticurrencyCode Error '.$sql.
' - '.$this->db->error());
2447 $this->error = $this->db->error();
2451 dol_syslog(get_class($this).
'::setMulticurrencyCode, status of the object is incompatible');
2452 $this->error =
'Status of the object is incompatible '.$this->statut;
2464 public function setMulticurrencyRate($rate, $mode = 1)
2466 dol_syslog(get_class($this).
'::setMulticurrencyRate('.$rate.
','.$mode.
')');
2467 if ($this->
statut >= 0 || $this->element ==
'societe') {
2468 $fieldname =
'multicurrency_tx';
2470 $sql =
'UPDATE '.$this->db->prefix().$this->table_element;
2471 $sql .=
" SET ".$fieldname.
" = ".((float) $rate);
2472 $sql .=
' WHERE rowid='.((int) $this->
id);
2474 if ($this->db->query($sql)) {
2475 $this->multicurrency_tx = $rate;
2478 if (!empty($this->lines)) {
2479 foreach ($this->lines as &$line) {
2482 $line->subprice = 0;
2487 $line->multicurrency_subprice = 0;
2490 switch ($this->element) {
2498 $line->remise_percent,
2500 $line->localtax1_tx,
2501 $line->localtax2_tx,
2502 ($line->description ? $line->description : $line->desc),
2505 $line->special_code,
2506 $line->fk_parent_line,
2507 $line->skip_update_total,
2508 $line->fk_fournprice,
2511 $line->product_type,
2514 $line->array_options,
2516 $line->multicurrency_subprice
2524 ($line->description ? $line->description : $line->desc),
2527 $line->remise_percent,
2529 $line->localtax1_tx,
2530 $line->localtax2_tx,
2535 $line->product_type,
2536 $line->fk_parent_line,
2537 $line->skip_update_total,
2538 $line->fk_fournprice,
2541 $line->special_code,
2542 $line->array_options,
2544 $line->multicurrency_subprice
2552 ($line->description ? $line->description : $line->desc),
2555 $line->remise_percent,
2559 $line->localtax1_tx,
2560 $line->localtax2_tx,
2563 $line->product_type,
2564 $line->fk_parent_line,
2565 $line->skip_update_total,
2566 $line->fk_fournprice,
2569 $line->special_code,
2570 $line->array_options,
2571 $line->situation_percent,
2573 $line->multicurrency_subprice
2576 case 'supplier_proposal':
2583 $line->remise_percent,
2585 $line->localtax1_tx,
2586 $line->localtax2_tx,
2587 ($line->description ? $line->description : $line->desc),
2590 $line->special_code,
2591 $line->fk_parent_line,
2592 $line->skip_update_total,
2593 $line->fk_fournprice,
2596 $line->product_type,
2597 $line->array_options,
2599 $line->multicurrency_subprice
2602 case 'order_supplier':
2607 ($line->description ? $line->description : $line->desc),
2610 $line->remise_percent,
2612 $line->localtax1_tx,
2613 $line->localtax2_tx,
2616 $line->product_type,
2620 $line->array_options,
2622 $line->multicurrency_subprice,
2626 case 'invoice_supplier':
2631 ($line->description ? $line->description : $line->desc),
2634 $line->localtax1_tx,
2635 $line->localtax2_tx,
2640 $line->product_type,
2641 $line->remise_percent,
2645 $line->array_options,
2647 $line->multicurrency_subprice,
2652 dol_syslog(get_class($this).
'::setMulticurrencyRate no updateline defined', LOG_DEBUG);
2660 dol_syslog(get_class($this).
'::setMulticurrencyRate Error '.$sql.
' - '.$this->db->error());
2661 $this->error = $this->db->error();
2665 dol_syslog(get_class($this).
'::setMulticurrencyRate, status of the object is incompatible');
2666 $this->error =
'Status of the object is incompatible '.$this->statut;
2680 dol_syslog(get_class($this).
'::setPaymentTerms('.$id.
', '.var_export($deposit_percent,
true).
')');
2681 if ($this->
statut >= 0 || $this->element ==
'societe') {
2683 $fieldname =
'fk_cond_reglement';
2684 if ($this->element ==
'societe') {
2685 $fieldname =
'cond_reglement';
2687 if (get_class($this) ==
'Fournisseur') {
2688 $fieldname =
'cond_reglement_supplier';
2691 if (empty($deposit_percent) || $deposit_percent < 0) {
2695 if ($deposit_percent > 100) {
2696 $deposit_percent = 100;
2699 $sql =
'UPDATE '.$this->db->prefix().$this->table_element;
2700 $sql .=
" SET ".$fieldname.
" = ".(($id > 0 || $id ==
'0') ? ((
int) $id) :
'NULL');
2701 if (in_array($this->table_element, array(
'propal',
'commande',
'societe'))) {
2702 $sql .=
" , deposit_percent = " . (empty($deposit_percent) ?
'NULL' :
"'".$this->db->escape($deposit_percent).
"'");
2704 $sql .=
' WHERE rowid='.((int) $this->
id);
2706 if ($this->db->query($sql)) {
2707 $this->cond_reglement_id = $id;
2709 if (get_class($this) ==
'Fournisseur') {
2710 $this->cond_reglement_supplier_id = $id;
2712 $this->cond_reglement = $id;
2713 $this->deposit_percent = $deposit_percent;
2716 dol_syslog(get_class($this).
'::setPaymentTerms Error '.$sql.
' - '.$this->db->error());
2717 $this->error = $this->db->error();
2721 dol_syslog(get_class($this).
'::setPaymentTerms, status of the object is incompatible');
2722 $this->error =
'Status of the object is incompatible '.$this->statut;
2735 dol_syslog(get_class($this).
'::setTransportMode('.$id.
')');
2736 if ($this->
statut >= 0 || $this->element ==
'societe') {
2737 $fieldname =
'fk_transport_mode';
2738 if ($this->element ==
'societe') {
2739 $fieldname =
'transport_mode';
2741 if (get_class($this) ==
'Fournisseur') {
2742 $fieldname =
'transport_mode_supplier';
2745 $sql =
'UPDATE '.$this->db->prefix().$this->table_element;
2746 $sql .=
" SET ".$fieldname.
" = ".(($id > 0 || $id ==
'0') ? ((
int) $id) :
'NULL');
2747 $sql .=
' WHERE rowid='.((int) $this->
id);
2749 if ($this->db->query($sql)) {
2750 $this->transport_mode_id = $id;
2752 if (get_class($this) ==
'Fournisseur') {
2753 $this->transport_mode_supplier_id = $id;
2757 dol_syslog(get_class($this).
'::setTransportMode Error '.$sql.
' - '.$this->db->error());
2758 $this->error = $this->db->error();
2762 dol_syslog(get_class($this).
'::setTransportMode, status of the object is incompatible');
2763 $this->error =
'Status of the object is incompatible '.$this->statut;
2776 dol_syslog(get_class($this).
'::setRetainedWarrantyPaymentTerms('.$id.
')');
2777 if ($this->
statut >= 0 || $this->element ==
'societe') {
2778 $fieldname =
'retained_warranty_fk_cond_reglement';
2780 $sql =
'UPDATE '.$this->db->prefix().$this->table_element;
2781 $sql .=
" SET ".$fieldname.
" = ".((int) $id);
2782 $sql .=
' WHERE rowid='.((int) $this->
id);
2784 if ($this->db->query($sql)) {
2785 $this->retained_warranty_fk_cond_reglement = $id;
2788 dol_syslog(get_class($this).
'::setRetainedWarrantyPaymentTerms Error '.$sql.
' - '.$this->db->error());
2789 $this->error = $this->db->error();
2793 dol_syslog(get_class($this).
'::setRetainedWarrantyPaymentTerms, status of the object is incompatible');
2794 $this->error =
'Status of the object is incompatible '.$this->statut;
2808 $fieldname =
'fk_delivery_address';
2809 if ($this->element ==
'delivery' || $this->element ==
'shipping') {
2810 $fieldname =
'fk_address';
2813 $sql =
"UPDATE ".$this->db->prefix().$this->table_element.
" SET ".$fieldname.
" = ".((int) $id);
2814 $sql .=
" WHERE rowid = ".((int) $this->
id).
" AND fk_statut = 0";
2816 if ($this->db->query($sql)) {
2817 $this->fk_delivery_address = $id;
2820 $this->error = $this->db->error();
2821 dol_syslog(get_class($this).
'::setDeliveryAddress Error '.$this->error);
2840 if (empty($userused)) {
2846 if (!$this->table_element) {
2847 dol_syslog(get_class($this).
"::setShippingMethod was called on objet with property table_element not defined", LOG_ERR);
2853 if ($shipping_method_id < 0) {
2854 $shipping_method_id =
'NULL';
2856 dol_syslog(get_class($this).
'::setShippingMethod('.$shipping_method_id.
')');
2858 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
2859 $sql .=
" SET fk_shipping_method = ".((int) $shipping_method_id);
2860 $sql .=
" WHERE rowid=".((int) $this->
id);
2861 $resql = $this->db->query($sql);
2863 dol_syslog(get_class($this).
'::setShippingMethod Error ', LOG_DEBUG);
2864 $this->error = $this->db->lasterror();
2869 $this->context = array(
'shippingmethodupdate'=>1);
2870 $result = $this->call_trigger(strtoupper(get_class($this)).
'_MODIFY', $userused);
2878 $this->db->rollback();
2881 $this->shipping_method_id = ($shipping_method_id ==
'NULL') ?
null:$shipping_method_id;
2882 $this->db->commit();
2896 if (!$this->table_element) {
2897 dol_syslog(get_class($this).
"::setWarehouse was called on objet with property table_element not defined", LOG_ERR);
2900 if ($warehouse_id < 0) {
2901 $warehouse_id =
'NULL';
2903 dol_syslog(get_class($this).
'::setWarehouse('.$warehouse_id.
')');
2905 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
2906 $sql .=
" SET fk_warehouse = ".((int) $warehouse_id);
2907 $sql .=
" WHERE rowid=".((int) $this->
id);
2909 if ($this->db->query($sql)) {
2910 $this->warehouse_id = ($warehouse_id ==
'NULL') ?
null:$warehouse_id;
2913 dol_syslog(get_class($this).
'::setWarehouse Error ', LOG_DEBUG);
2914 $this->error = $this->db->error();
2929 if (!$this->table_element) {
2930 dol_syslog(get_class($this).
"::setDocModel was called on objet with property table_element not defined", LOG_ERR);
2934 $newmodelpdf =
dol_trunc($modelpdf, 255);
2936 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
2937 $sql .=
" SET model_pdf = '".$this->db->escape($newmodelpdf).
"'";
2938 $sql .=
" WHERE rowid = ".((int) $this->
id);
2940 dol_syslog(get_class($this).
"::setDocModel", LOG_DEBUG);
2941 $resql = $this->db->query($sql);
2943 $this->model_pdf = $modelpdf;
2944 $this->modelpdf = $modelpdf;
2965 if (empty($userused)) {
2971 if (!$this->table_element) {
2972 dol_syslog(get_class($this).
"::setBankAccount was called on objet with property table_element not defined", LOG_ERR);
2977 if ($fk_account < 0) {
2978 $fk_account =
'NULL';
2980 dol_syslog(get_class($this).
'::setBankAccount('.$fk_account.
')');
2982 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
2983 $sql .=
" SET fk_account = ".((int) $fk_account);
2984 $sql .=
" WHERE rowid=".((int) $this->
id);
2986 $resql = $this->db->query($sql);
2988 dol_syslog(get_class($this).
'::setBankAccount Error '.$sql.
' - '.$this->db->error());
2989 $this->error = $this->db->lasterror();
2994 $this->context = array(
'bankaccountupdate'=>1);
2995 $result = $this->call_trigger(strtoupper(get_class($this)).
'_MODIFY', $userused);
3003 $this->db->rollback();
3006 $this->fk_account = ($fk_account ==
'NULL') ?
null:$fk_account;
3007 $this->db->commit();
3025 public function line_order($renum =
false, $rowidorder =
'ASC', $fk_parent_line =
true)
3028 if (!$this->table_element_line) {
3029 dol_syslog(get_class($this).
"::line_order was called on objet with property table_element_line not defined", LOG_ERR);
3032 if (!$this->fk_element) {
3033 dol_syslog(get_class($this).
"::line_order was called on objet with property fk_element not defined", LOG_ERR);
3037 $fieldposition =
'rang';
3038 if (in_array($this->table_element_line, array(
'bom_bomline',
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3039 $fieldposition =
'position';
3044 $sql =
"SELECT count(rowid) FROM ".$this->db->prefix().$this->table_element_line;
3045 $sql .=
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
3047 $sql .=
" AND " . $fieldposition .
" = 0";
3050 $sql .=
" AND " . $fieldposition .
" <> 0";
3053 dol_syslog(get_class($this).
"::line_order", LOG_DEBUG);
3054 $resql = $this->db->query($sql);
3056 $row = $this->db->fetch_row($resql);
3066 $sql =
"SELECT rowid FROM ".$this->db->prefix().$this->table_element_line;
3067 $sql .=
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
3068 if ($fk_parent_line) {
3069 $sql .=
' AND fk_parent_line IS NULL';
3071 $sql .=
" ORDER BY " . $fieldposition .
" ASC, rowid " . $rowidorder;
3073 dol_syslog(get_class($this).
"::line_order search all parent lines", LOG_DEBUG);
3074 $resql = $this->db->query($sql);
3077 $num = $this->db->num_rows($resql);
3079 $row = $this->db->fetch_row($resql);
3081 $childrens = $this->getChildrenOfLine($row[0]);
3082 if (!empty($childrens)) {
3083 foreach ($childrens as $child) {
3084 array_push($rows, $child);
3091 if (!empty($rows)) {
3092 foreach ($rows as $key => $row) {
3093 $this->updateRangOfLine($row, ($key + 1));
3112 $fieldposition =
'rang';
3113 if (in_array($this->table_element_line, array(
'bom_bomline',
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3114 $fieldposition =
'position';
3119 $sql =
"SELECT rowid FROM ".$this->db->prefix().$this->table_element_line;
3120 $sql .=
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
3121 $sql .=
' AND fk_parent_line = '.((int) $id);
3122 $sql .=
" ORDER BY " . $fieldposition .
" ASC";
3124 dol_syslog(get_class($this).
"::getChildrenOfLine search children lines for line ".$id, LOG_DEBUG);
3125 $resql = $this->db->query($sql);
3127 if ($this->db->num_rows($resql) > 0) {
3128 while ($row = $this->db->fetch_row($resql)) {
3130 if (!empty($includealltree)) {
3131 $rows = array_merge($rows, $this->getChildrenOfLine($row[0], $includealltree));
3147 public function line_up($rowid, $fk_parent_line =
true)
3150 $this->line_order(
false,
'ASC', $fk_parent_line);
3153 $rang = $this->getRangOfLine($rowid);
3156 $this->updateLineUp($rowid, $rang);
3170 $this->line_order(
false,
'ASC', $fk_parent_line);
3173 $rang = $this->getRangOfLine($rowid);
3176 $max = $this->line_max();
3179 $this->updateLineDown($rowid, $rang, $max);
3191 global $hookmanager;
3192 $fieldposition =
'rang';
3193 if (in_array($this->table_element_line, array(
'bom_bomline',
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3194 $fieldposition =
'position';
3197 $sql =
"UPDATE ".$this->db->prefix().$this->table_element_line.
" SET ".$fieldposition.
" = ".((int) $rang);
3198 $sql .=
' WHERE rowid = '.((int) $rowid);
3200 dol_syslog(get_class($this).
"::updateRangOfLine", LOG_DEBUG);
3201 if (!$this->db->query($sql)) {
3205 $parameters=array(
'rowid'=>$rowid,
'rang'=>$rang,
'fieldposition' => $fieldposition);
3207 $reshook = $hookmanager->executeHooks(
'afterRankOfLineUpdate', $parameters, $this, $action);
3222 $num = count($rows);
3223 for ($i = 0; $i < $num; $i++) {
3224 $this->updateRangOfLine($rows[$i], ($i + 1));
3238 $fieldposition =
'rang';
3239 if (in_array($this->table_element_line, array(
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3240 $fieldposition =
'position';
3243 $sql =
"UPDATE ".$this->db->prefix().$this->table_element_line.
" SET ".$fieldposition.
" = ".((int) $rang);
3244 $sql .=
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
3245 $sql .=
" AND " . $fieldposition .
" = " . ((int) ($rang - 1));
3246 if ($this->db->query($sql)) {
3247 $sql =
"UPDATE ".$this->db->prefix().$this->table_element_line.
" SET ".$fieldposition.
" = ".((int) ($rang - 1));
3248 $sql .=
' WHERE rowid = '.((int) $rowid);
3249 if (!$this->db->query($sql)) {
3269 $fieldposition =
'rang';
3270 if (in_array($this->table_element_line, array(
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3271 $fieldposition =
'position';
3274 $sql =
"UPDATE ".$this->db->prefix().$this->table_element_line.
" SET ".$fieldposition.
" = ".((int) $rang);
3275 $sql .=
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
3276 $sql .=
" AND " . $fieldposition .
" = " . ((int) ($rang + 1));
3277 if ($this->db->query($sql)) {
3278 $sql =
"UPDATE ".$this->db->prefix().$this->table_element_line.
" SET ".$fieldposition.
" = ".((int) ($rang + 1));
3279 $sql .=
' WHERE rowid = '.((int) $rowid);
3280 if (!$this->db->query($sql)) {
3297 $fieldposition =
'rang';
3298 if (in_array($this->table_element_line, array(
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3299 $fieldposition =
'position';
3302 $sql =
"SELECT " . $fieldposition .
" FROM ".$this->db->prefix().$this->table_element_line;
3303 $sql .=
" WHERE rowid = ".((int) $rowid);
3305 dol_syslog(get_class($this).
"::getRangOfLine", LOG_DEBUG);
3306 $resql = $this->db->query($sql);
3308 $row = $this->db->fetch_row($resql);
3323 $fieldposition =
'rang';
3324 if (in_array($this->table_element_line, array(
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3325 $fieldposition =
'position';
3328 $sql =
"SELECT rowid FROM ".$this->db->prefix().$this->table_element_line;
3329 $sql .=
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
3330 $sql .=
" AND " . $fieldposition .
" = ".((int) $rang);
3331 $resql = $this->db->query($sql);
3333 $row = $this->db->fetch_row($resql);
3350 $positionfield =
'rang';
3351 if (in_array($this->table_element, array(
'bom_bom',
'product_attribute'))) {
3352 $positionfield =
'position';
3356 if ($fk_parent_line) {
3357 $sql =
"SELECT max(".$positionfield.
") FROM ".$this->db->prefix().$this->table_element_line;
3358 $sql .=
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
3359 $sql .=
" AND fk_parent_line = ".((int) $fk_parent_line);
3361 dol_syslog(get_class($this).
"::line_max", LOG_DEBUG);
3362 $resql = $this->db->query($sql);
3364 $row = $this->db->fetch_row($resql);
3365 if (!empty($row[0])) {
3368 return $this->getRangOfLine($fk_parent_line);
3373 $sql =
"SELECT max(".$positionfield.
") FROM ".$this->db->prefix().$this->table_element_line;
3374 $sql .=
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
3376 dol_syslog(get_class($this).
"::line_max", LOG_DEBUG);
3377 $resql = $this->db->query($sql);
3379 $row = $this->db->fetch_row($resql);
3397 if (!$this->table_element) {
3398 dol_syslog(get_class($this).
"::update_ref_ext was called on objet with property table_element not defined", LOG_ERR);
3402 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
3403 $sql .=
" SET ref_ext = '".$this->db->escape($ref_ext).
"'";
3404 $sql .=
" WHERE ".(isset($this->table_rowid) ? $this->table_rowid :
'rowid').
" = ".((
int) $this->id);
3406 dol_syslog(get_class($this).
"::update_ref_ext", LOG_DEBUG);
3407 if ($this->db->query($sql)) {
3408 $this->ref_ext = $ref_ext;
3411 $this->error = $this->db->error();
3430 if (!$this->table_element) {
3431 $this->error =
'update_note was called on objet with property table_element not defined';
3432 dol_syslog(get_class($this).
"::update_note was called on objet with property table_element not defined", LOG_ERR);
3435 if (!in_array($suffix, array(
'',
'_public',
'_private'))) {
3436 $this->error =
'update_note Parameter suffix must be empty, \'_private\' or \'_public\'';
3437 dol_syslog(get_class($this).
"::update_note Parameter suffix must be empty, '_private' or '_public'", LOG_ERR);
3441 $newsuffix = $suffix;
3444 if ($this->table_element ==
'product' && $newsuffix ==
'_private') {
3447 if (in_array($this->table_element, array(
'actioncomm',
'adherent',
'advtargetemailing',
'cronjob',
'establishment'))) {
3448 $fieldusermod =
"fk_user_mod";
3449 } elseif ($this->table_element ==
'ecm_files') {
3450 $fieldusermod =
"fk_user_m";
3452 $fieldusermod =
"fk_user_modif";
3454 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
3455 $sql .=
" SET note".$newsuffix.
" = ".(!empty($note) ? (
"'".$this->db->escape($note).
"'") :
"NULL");
3456 $sql .=
", ".$fieldusermod.
" = ".((int) $user->id);
3457 $sql .=
" WHERE rowid = ".((int) $this->
id);
3459 dol_syslog(get_class($this).
"::update_note", LOG_DEBUG);
3460 if ($this->db->query($sql)) {
3461 if ($suffix ==
'_public') {
3462 $this->note_public = $note;
3463 } elseif ($suffix ==
'_private') {
3464 $this->note_private = $note;
3466 $this->note = $note;
3467 $this->note_private = $note;
3469 if (empty($notrigger)) {
3470 switch ($this->element) {
3472 $trigger_name =
'COMPANY_MODIFY';
3475 $trigger_name =
'ORDER_MODIFY';
3478 $trigger_name =
'BILL_MODIFY';
3480 case 'invoice_supplier':
3481 $trigger_name =
'BILL_SUPPLIER_MODIFY';
3484 $trigger_name =
'BILLREC_MODIFIY';
3486 case 'expensereport':
3487 $trigger_name =
'EXPENSE_REPORT_MODIFY';
3490 $trigger_name = strtoupper($this->element) .
'_MODIFY';
3492 $ret = $this->call_trigger($trigger_name, $user);
3499 $this->error = $this->db->lasterror();
3516 return $this->update_note($note,
'_public');
3530 public function update_price($exclspec = 0, $roundingadjust =
'none', $nodatabaseupdate = 0, $seller =
null)
3533 global $conf, $hookmanager, $action;
3535 $parameters = array(
'exclspec' => $exclspec,
'roundingadjust' => $roundingadjust,
'nodatabaseupdate' => $nodatabaseupdate,
'seller' => $seller);
3536 $reshook = $hookmanager->executeHooks(
'updateTotalPrice', $parameters, $this, $action);
3539 } elseif ($reshook < 0) {
3545 if ($this->element ==
'propal') {
3546 $MODULE =
"MODULE_DISALLOW_UPDATE_PRICE_PROPOSAL";
3547 } elseif ($this->element ==
'commande' || $this->element ==
'order') {
3548 $MODULE =
"MODULE_DISALLOW_UPDATE_PRICE_ORDER";
3549 } elseif ($this->element ==
'facture' || $this->element ==
'invoice') {
3550 $MODULE =
"MODULE_DISALLOW_UPDATE_PRICE_INVOICE";
3551 } elseif ($this->element ==
'facture_fourn' || $this->element ==
'supplier_invoice' || $this->element ==
'invoice_supplier' || $this->element ==
'invoice_supplier_rec') {
3552 $MODULE =
"MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_INVOICE";
3553 } elseif ($this->element ==
'order_supplier' || $this->element ==
'supplier_order') {
3554 $MODULE =
"MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_ORDER";
3555 } elseif ($this->element ==
'supplier_proposal') {
3556 $MODULE =
"MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_PROPOSAL";
3559 if (!empty($MODULE)) {
3560 if (!empty($conf->global->$MODULE)) {
3561 $modsactivated = explode(
',', $conf->global->$MODULE);
3562 foreach ($modsactivated as $mod) {
3563 if (isModEnabled($mod)) {
3570 include_once DOL_DOCUMENT_ROOT.
'/core/lib/price.lib.php';
3572 $forcedroundingmode = $roundingadjust;
3573 if ($forcedroundingmode ==
'auto' && isset($conf->global->MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND)) {
3575 } elseif ($forcedroundingmode ==
'auto') {
3576 $forcedroundingmode =
'0';
3581 $multicurrency_tx = !empty($this->multicurrency_tx) ? $this->multicurrency_tx : 1;
3584 $fieldtva =
'total_tva';
3585 $fieldlocaltax1 =
'total_localtax1';
3586 $fieldlocaltax2 =
'total_localtax2';
3587 $fieldup =
'subprice';
3588 if ($this->element ==
'facture_fourn' || $this->element ==
'invoice_supplier') {
3592 if ($this->element ==
'invoice_supplier_rec') {
3595 if ($this->element ==
'expensereport') {
3596 $fieldup =
'value_unit';
3599 $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,";
3600 $sql .=
' tva_tx as vatrate, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type, info_bits, product_type';
3601 if ($this->table_element_line ==
'facturedet') {
3602 $sql .=
', situation_percent';
3604 $sql .=
', multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc';
3605 $sql .=
" FROM ".$this->db->prefix().$this->table_element_line;
3606 $sql .=
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
3608 $product_field =
'product_type';
3609 if ($this->table_element_line ==
'contratdet') {
3610 $product_field =
'';
3612 if ($product_field) {
3613 $sql .=
" AND ".$product_field.
" <> 9";
3616 $sql .=
' ORDER by rowid';
3618 dol_syslog(get_class($this).
"::update_price", LOG_DEBUG);
3620 $resql = $this->db->query($sql);
3622 $this->total_ht = 0;
3623 $this->total_tva = 0;
3624 $this->total_localtax1 = 0;
3625 $this->total_localtax2 = 0;
3626 $this->total_ttc = 0;
3627 $total_ht_by_vats = array();
3628 $total_tva_by_vats = array();
3629 $total_ttc_by_vats = array();
3630 $this->multicurrency_total_ht = 0;
3631 $this->multicurrency_total_tva = 0;
3632 $this->multicurrency_total_ttc = 0;
3636 $num = $this->db->num_rows($resql);
3639 $obj = $this->db->fetch_object($resql);
3642 $parameters = array(
'fk_element' => $obj->rowid);
3643 $reshook = $hookmanager->executeHooks(
'changeRoundingMode', $parameters, $this, $action);
3645 if (empty($reshook) && $forcedroundingmode ==
'0') {
3647 $localtax_array = array($obj->localtax1_type, $obj->localtax1_tx, $obj->localtax2_type, $obj->localtax2_tx);
3648 $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);
3650 $diff_when_using_price_ht =
price2num($tmpcal[1] - $obj->total_tva,
'MT', 1);
3651 $diff_on_current_total =
price2num($obj->total_ttc - $obj->total_ht - $obj->total_tva - $obj->total_localtax1 - $obj->total_localtax2,
'MT', 1);
3655 if ($diff_on_current_total) {
3657 $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);
3658 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);
3659 $resqlfix = $this->db->query($sqlfix);
3663 $obj->total_tva = $tmpcal[1];
3664 $obj->total_ttc = $tmpcal[2];
3665 } elseif ($diff_when_using_price_ht && $roundingadjust ==
'0') {
3668 $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);
3669 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);
3670 $resqlfix = $this->db->query($sqlfix);
3674 $obj->total_tva = $tmpcal[1];
3675 $obj->total_ttc = $tmpcal[2];
3679 $this->total_ht += $obj->total_ht;
3680 $this->total_tva += $obj->total_tva;
3681 $this->total_localtax1 += $obj->total_localtax1;
3682 $this->total_localtax2 += $obj->total_localtax2;
3683 $this->total_ttc += $obj->total_ttc;
3684 $this->multicurrency_total_ht += $obj->multicurrency_total_ht;
3685 $this->multicurrency_total_tva += $obj->multicurrency_total_tva;
3686 $this->multicurrency_total_ttc += $obj->multicurrency_total_ttc;
3688 if (!isset($total_ht_by_vats[$obj->vatrate])) {
3689 $total_ht_by_vats[$obj->vatrate] = 0;
3691 if (!isset($total_tva_by_vats[$obj->vatrate])) {
3692 $total_tva_by_vats[$obj->vatrate] = 0;
3694 if (!isset($total_ttc_by_vats[$obj->vatrate])) {
3695 $total_ttc_by_vats[$obj->vatrate] = 0;
3697 $total_ht_by_vats[$obj->vatrate] += $obj->total_ht;
3698 $total_tva_by_vats[$obj->vatrate] += $obj->total_tva;
3699 $total_ttc_by_vats[$obj->vatrate] += $obj->total_ttc;
3701 if ($forcedroundingmode ==
'1') {
3702 $tmpvat =
price2num($total_ht_by_vats[$obj->vatrate] * $obj->vatrate / 100,
'MT', 1);
3703 $diff =
price2num($total_tva_by_vats[$obj->vatrate] - $tmpvat,
'MT', 1);
3706 if (abs($diff) > (10 * pow(10, -1 *
getDolGlobalInt(
'MAIN_MAX_DECIMALS_TOT', 0)))) {
3708 $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.';
3710 $this->error = $errmsg;
3714 $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);
3715 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);
3717 $resqlfix = $this->db->query($sqlfix);
3723 $this->total_tva = (float)
price2num($this->total_tva - $diff,
'', 1);
3724 $this->total_ttc = (float)
price2num($this->total_ttc - $diff,
'', 1);
3725 $total_tva_by_vats[$obj->vatrate] = (float)
price2num($total_tva_by_vats[$obj->vatrate] - $diff,
'', 1);
3726 $total_ttc_by_vats[$obj->vatrate] = (float)
price2num($total_ttc_by_vats[$obj->vatrate] - $diff,
'', 1);
3734 $this->total_ttc += isset($this->revenuestamp) ? $this->revenuestamp : 0;
3735 $this->multicurrency_total_ttc += isset($this->revenuestamp) ? ($this->revenuestamp * $multicurrency_tx) : 0;
3738 if (!empty($this->situation_cycle_ref) && $this->situation_counter > 1 && method_exists($this,
'get_prev_sits') && $this->
type != $this::TYPE_CREDIT_NOTE) {
3739 $prev_sits = $this->get_prev_sits();
3741 foreach ($prev_sits as $sit) {
3742 $this->total_ht -= $sit->total_ht;
3743 $this->total_tva -= $sit->total_tva;
3744 $this->total_localtax1 -= $sit->total_localtax1;
3745 $this->total_localtax2 -= $sit->total_localtax2;
3746 $this->total_ttc -= $sit->total_ttc;
3747 $this->multicurrency_total_ht -= $sit->multicurrency_total_ht;
3748 $this->multicurrency_total_tva -= $sit->multicurrency_total_tva;
3749 $this->multicurrency_total_ttc -= $sit->multicurrency_total_ttc;
3754 $this->total_ht = (float)
price2num($this->total_ht);
3755 $this->total_tva = (float)
price2num($this->total_tva);
3756 $this->total_localtax1 = (float)
price2num($this->total_localtax1);
3757 $this->total_localtax2 = (float)
price2num($this->total_localtax2);
3758 $this->total_ttc = (float)
price2num($this->total_ttc);
3760 $this->db->free($resql);
3763 $fieldht =
'total_ht';
3765 $fieldlocaltax1 =
'localtax1';
3766 $fieldlocaltax2 =
'localtax2';
3767 $fieldttc =
'total_ttc';
3769 if (in_array($this->element, array(
'propal',
'commande',
'facture',
'facturerec',
'supplier_proposal',
'order_supplier',
'facture_fourn',
'invoice_supplier',
'invoice_supplier_rec',
'expensereport'))) {
3770 $fieldtva =
'total_tva';
3773 if (!$error && empty($nodatabaseupdate)) {
3774 $sql =
"UPDATE ".$this->db->prefix().$this->table_element.
' SET';
3775 $sql .=
" ".$fieldht.
" = ".((float)
price2num($this->total_ht,
'MT', 1)).
",";
3776 $sql .=
" ".$fieldtva.
" = ".((float)
price2num($this->total_tva,
'MT', 1)).
",";
3777 $sql .=
" ".$fieldlocaltax1.
" = ".((float)
price2num($this->total_localtax1,
'MT', 1)).
",";
3778 $sql .=
" ".$fieldlocaltax2.
" = ".((float)
price2num($this->total_localtax2,
'MT', 1)).
",";
3779 $sql .=
" ".$fieldttc.
" = ".((float)
price2num($this->total_ttc,
'MT', 1));
3780 $sql .=
", multicurrency_total_ht = ".((float)
price2num($this->multicurrency_total_ht,
'MT', 1));
3781 $sql .=
", multicurrency_total_tva = ".((float)
price2num($this->multicurrency_total_tva,
'MT', 1));
3782 $sql .=
", multicurrency_total_ttc = ".((float)
price2num($this->multicurrency_total_ttc,
'MT', 1));
3783 $sql .=
" WHERE rowid = ".((int) $this->
id);
3785 dol_syslog(get_class($this).
"::update_price", LOG_DEBUG);
3786 $resql = $this->db->query($sql);
3790 $this->error = $this->db->lasterror();
3791 $this->errors[] = $this->db->lasterror();
3796 $this->db->commit();
3799 $this->db->rollback();
3819 public function add_object_linked($origin =
null, $origin_id =
null, $f_user =
null, $notrigger = 0)
3822 global $user, $hookmanager, $action;
3823 $origin = (!empty($origin) ? $origin : $this->origin);
3824 $origin_id = (!empty($origin_id) ? $origin_id : $this->origin_id);
3825 $f_user = isset($f_user) ? $f_user : $user;
3828 if ($origin ==
'order') {
3829 $origin =
'commande';
3831 if ($origin ==
'invoice') {
3832 $origin =
'facture';
3834 if ($origin ==
'invoice_template') {
3835 $origin =
'facturerec';
3837 if ($origin ==
'supplierorder') {
3838 $origin =
'order_supplier';
3843 $coremodule = array(
'knowledgemanagement',
'partnership',
'workstation',
'ticket',
'recruitment',
'eventorganization',
'asset');
3845 $targettype = ((!empty($this->module) && ! in_array($this->module, $coremodule)) ? $this->module.
'_' :
'').$this->element;
3847 $parameters = array(
'targettype'=>$targettype);
3849 $reshook = $hookmanager->executeHooks(
'setLinkedObjectSourceTargetType', $parameters, $this, $action);
3851 if (!empty($hookmanager->resArray[
'targettype'])) $targettype = $hookmanager->resArray[
'targettype'];
3857 $sql =
"INSERT INTO " . $this->db->prefix() .
"element_element (";
3858 $sql .=
"fk_source";
3859 $sql .=
", sourcetype";
3860 $sql .=
", fk_target";
3861 $sql .=
", targettype";
3862 $sql .=
") VALUES (";
3863 $sql .= ((int) $origin_id);
3864 $sql .=
", '" . $this->db->escape($origin) .
"'";
3865 $sql .=
", " . ((int) $this->
id);
3866 $sql .=
", '" . $this->db->escape($targettype) .
"'";
3869 dol_syslog(get_class($this) .
"::add_object_linked", LOG_DEBUG);
3870 if ($this->db->query($sql)) {
3873 $this->context[
'link_origin'] = $origin;
3874 $this->context[
'link_origin_id'] = $origin_id;
3875 $result = $this->call_trigger(
'OBJECT_LINK_INSERT', $f_user);
3882 $this->error = $this->db->lasterror();
3887 $this->db->commit();
3890 $this->db->rollback();
3917 public function fetchObjectLinked($sourceid =
null, $sourcetype =
'', $targetid =
null, $targettype =
'', $clause =
'OR', $alsosametype = 1, $orderby =
'sourcetype', $loadalsoobjects = 1)
3919 global $conf, $hookmanager, $action;
3923 if ($this->
id > 0 && !empty($this->linkedObjectsFullLoaded[$this->
id])) {
3927 $this->linkedObjectsIds = array();
3928 $this->linkedObjects = array();
3930 $justsource =
false;
3931 $justtarget =
false;
3932 $withtargettype =
false;
3933 $withsourcetype =
false;
3935 $parameters = array(
'sourcetype'=>$sourcetype,
'sourceid'=>$sourceid,
'targettype'=>$targettype,
'targetid'=>$targetid);
3937 $reshook = $hookmanager->executeHooks(
'setLinkedObjectSourceTargetType', $parameters, $this, $action);
3939 if (!empty($hookmanager->resArray[
'sourcetype'])) $sourcetype = $hookmanager->resArray[
'sourcetype'];
3940 if (!empty($hookmanager->resArray[
'sourceid'])) $sourceid = $hookmanager->resArray[
'sourceid'];
3941 if (!empty($hookmanager->resArray[
'targettype'])) $targettype = $hookmanager->resArray[
'targettype'];
3942 if (!empty($hookmanager->resArray[
'targetid'])) $targetid = $hookmanager->resArray[
'targetid'];
3945 if (!empty($sourceid) && !empty($sourcetype) && empty($targetid)) {
3947 if (!empty($targettype)) {
3948 $withtargettype =
true;
3951 if (!empty($targetid) && !empty($targettype) && empty($sourceid)) {
3953 if (!empty($sourcetype)) {
3954 $withsourcetype =
true;
3958 $sourceid = (!empty($sourceid) ? $sourceid : $this->id);
3959 $targetid = (!empty($targetid) ? $targetid : $this->id);
3960 $sourcetype = (!empty($sourcetype) ? $sourcetype : $this->element);
3961 $targettype = (!empty($targettype) ? $targettype : $this->element);
3970 $sql =
"SELECT rowid, fk_source, sourcetype, fk_target, targettype";
3971 $sql .=
" FROM ".$this->db->prefix().
"element_element";
3973 if ($justsource || $justtarget) {
3975 $sql .=
"fk_source = ".((int) $sourceid).
" AND sourcetype = '".$this->db->escape($sourcetype).
"'";
3976 if ($withtargettype) {
3977 $sql .=
" AND targettype = '".$this->db->escape($targettype).
"'";
3979 } elseif ($justtarget) {
3980 $sql .=
"fk_target = ".((int) $targetid).
" AND targettype = '".$this->db->escape($targettype).
"'";
3981 if ($withsourcetype) {
3982 $sql .=
" AND sourcetype = '".$this->db->escape($sourcetype).
"'";
3986 $sql .=
"(fk_source = ".((int) $sourceid).
" AND sourcetype = '".$this->db->escape($sourcetype).
"')";
3987 $sql .=
" ".$clause.
" (fk_target = ".((int) $targetid).
" AND targettype = '".$this->db->escape($targettype).
"')";
3988 if ($loadalsoobjects && $this->
id > 0 && $sourceid == $this->
id && $sourcetype == $this->element && $targetid == $this->
id && $targettype == $this->element && $clause ==
'OR') {
3989 $this->linkedObjectsFullLoaded[$this->id] =
true;
3992 $sql .=
" ORDER BY ".$orderby;
3994 dol_syslog(get_class($this).
"::fetchObjectLink", LOG_DEBUG);
3995 $resql = $this->db->query($sql);
3997 $num = $this->db->num_rows($resql);
4000 $obj = $this->db->fetch_object($resql);
4001 if ($justsource || $justtarget) {
4003 $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
4004 } elseif ($justtarget) {
4005 $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
4008 if ($obj->fk_source == $sourceid && $obj->sourcetype == $sourcetype) {
4009 $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
4011 if ($obj->fk_target == $targetid && $obj->targettype == $targettype) {
4012 $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
4018 if (!empty($this->linkedObjectsIds)) {
4019 $tmparray = $this->linkedObjectsIds;
4020 foreach ($tmparray as $objecttype => $objectids) {
4022 $module = $element = $subelement = $objecttype;
4024 if ($objecttype !=
'supplier_proposal' && $objecttype !=
'order_supplier' && $objecttype !=
'invoice_supplier'
4025 && preg_match(
'/^([^_]+)_([^_]+)/i', $objecttype, $regs)) {
4026 $module = $element = $regs[1];
4027 $subelement = $regs[2];
4030 $classpath = $element.
'/class';
4032 if ($objecttype ==
'facture') {
4033 $classpath =
'compta/facture/class';
4034 } elseif ($objecttype ==
'facturerec') {
4035 $classpath =
'compta/facture/class';
4036 $module =
'facture';
4037 } elseif ($objecttype ==
'propal') {
4038 $classpath =
'comm/propal/class';
4039 } elseif ($objecttype ==
'supplier_proposal') {
4040 $classpath =
'supplier_proposal/class';
4041 } elseif ($objecttype ==
'shipping') {
4042 $classpath =
'expedition/class';
4043 $subelement =
'expedition';
4044 $module =
'expedition';
4045 } elseif ($objecttype ==
'delivery') {
4046 $classpath =
'delivery/class';
4047 $subelement =
'delivery';
4048 $module =
'delivery_note';
4049 } elseif ($objecttype ==
'invoice_supplier' || $objecttype ==
'order_supplier') {
4050 $classpath =
'fourn/class';
4051 $module =
'fournisseur';
4052 } elseif ($objecttype ==
'fichinter') {
4053 $classpath =
'fichinter/class';
4054 $subelement =
'fichinter';
4055 $module =
'ficheinter';
4056 } elseif ($objecttype ==
'subscription') {
4057 $classpath =
'adherents/class';
4058 $module =
'adherent';
4059 } elseif ($objecttype ==
'contact') {
4060 $module =
'societe';
4061 } elseif ($objecttype ==
'action') {
4063 $subelement =
'actionComm';
4067 $classfile = strtolower($subelement);
4068 $classname = ucfirst($subelement);
4070 if ($objecttype ==
'order') {
4071 $classfile =
'commande';
4072 $classname =
'Commande';
4073 } elseif ($objecttype ==
'invoice_supplier') {
4074 $classfile =
'fournisseur.facture';
4075 $classname =
'FactureFournisseur';
4076 } elseif ($objecttype ==
'order_supplier') {
4077 $classfile =
'fournisseur.commande';
4078 $classname =
'CommandeFournisseur';
4079 } elseif ($objecttype ==
'supplier_proposal') {
4080 $classfile =
'supplier_proposal';
4081 $classname =
'SupplierProposal';
4082 } elseif ($objecttype ==
'facturerec') {
4083 $classfile =
'facture-rec';
4084 $classname =
'FactureRec';
4085 } elseif ($objecttype ==
'subscription') {
4086 $classfile =
'subscription';
4087 $classname =
'Subscription';
4088 } elseif ($objecttype ==
'project' || $objecttype ==
'projet') {
4089 $classpath =
'projet/class';
4090 $classfile =
'project';
4091 $classname =
'Project';
4092 } elseif ($objecttype ==
'conferenceorboothattendee') {
4093 $classpath =
'eventorganization/class';
4094 $classfile =
'conferenceorboothattendee';
4095 $classname =
'ConferenceOrBoothAttendee';
4096 $module =
'eventorganization';
4097 } elseif ($objecttype ==
'conferenceorbooth') {
4098 $classpath =
'eventorganization/class';
4099 $classfile =
'conferenceorbooth';
4100 $classname =
'ConferenceOrBooth';
4101 $module =
'eventorganization';
4102 } elseif ($objecttype ==
'mo') {
4103 $classpath =
'mrp/class';
4110 if (isModEnabled($module) && (($element != $this->element) || $alsosametype)) {
4111 if ($loadalsoobjects && (is_numeric($loadalsoobjects) || ($loadalsoobjects === $objecttype))) {
4114 if (class_exists($classname)) {
4115 foreach ($objectids as $i => $objectid) {
4116 $object =
new $classname($this->db);
4117 $ret = $object->fetch($objectid);
4119 $this->linkedObjects[$objecttype][$i] = $object;
4125 unset($this->linkedObjectsIds[$objecttype]);
4144 if ($this->
id > 0 && !empty($this->linkedObjectsFullLoaded[$this->
id])) {
4145 unset($this->linkedObjectsFullLoaded[$this->
id]);
4163 public function updateObjectLinked($sourceid =
null, $sourcetype =
'', $targetid =
null, $targettype =
'', $f_user =
null, $notrigger = 0)
4166 $updatesource =
false;
4167 $updatetarget =
false;
4168 $f_user = isset($f_user) ? $f_user : $user;
4170 if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) {
4171 $updatesource =
true;
4172 } elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) {
4173 $updatetarget =
true;
4179 $sql =
"UPDATE " . $this->db->prefix() .
"element_element SET ";
4180 if ($updatesource) {
4181 $sql .=
"fk_source = " . ((int) $sourceid);
4182 $sql .=
", sourcetype = '" . $this->db->escape($sourcetype) .
"'";
4183 $sql .=
" WHERE fk_target = " . ((int) $this->
id);
4184 $sql .=
" AND targettype = '" . $this->db->escape($this->element) .
"'";
4185 } elseif ($updatetarget) {
4186 $sql .=
"fk_target = " . ((int) $targetid);
4187 $sql .=
", targettype = '" . $this->db->escape($targettype) .
"'";
4188 $sql .=
" WHERE fk_source = " . ((int) $this->
id);
4189 $sql .=
" AND sourcetype = '" . $this->db->escape($this->element) .
"'";
4192 dol_syslog(get_class($this) .
"::updateObjectLinked", LOG_DEBUG);
4193 if ($this->db->query($sql)) {
4196 $this->context[
'link_source_id'] = $sourceid;
4197 $this->context[
'link_source_type'] = $sourcetype;
4198 $this->context[
'link_target_id'] = $targetid;
4199 $this->context[
'link_target_type'] = $targettype;
4200 $result = $this->call_trigger(
'OBJECT_LINK_MODIFY', $f_user);
4207 $this->error = $this->db->lasterror();
4212 $this->db->commit();
4215 $this->db->rollback();
4233 public function deleteObjectLinked($sourceid =
null, $sourcetype =
'', $targetid =
null, $targettype =
'', $rowid =
'', $f_user =
null, $notrigger = 0)
4236 $deletesource =
false;
4237 $deletetarget =
false;
4238 $f_user = isset($f_user) ? $f_user : $user;
4240 if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) {
4241 $deletesource =
true;
4242 } elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) {
4243 $deletetarget =
true;
4246 $sourceid = (!empty($sourceid) ? $sourceid : $this->id);
4247 $sourcetype = (!empty($sourcetype) ? $sourcetype : $this->element);
4248 $targetid = (!empty($targetid) ? $targetid : $this->id);
4249 $targettype = (!empty($targettype) ? $targettype : $this->element);
4255 $this->context[
'link_id'] = $rowid;
4256 $this->context[
'link_source_id'] = $sourceid;
4257 $this->context[
'link_source_type'] = $sourcetype;
4258 $this->context[
'link_target_id'] = $targetid;
4259 $this->context[
'link_target_type'] = $targettype;
4260 $result = $this->call_trigger(
'OBJECT_LINK_DELETE', $f_user);
4268 $sql =
"DELETE FROM " . $this->db->prefix() .
"element_element";
4271 $sql .=
" rowid = " . ((int) $rowid);
4273 if ($deletesource) {
4274 $sql .=
" fk_source = " . ((int) $sourceid) .
" AND sourcetype = '" . $this->db->escape($sourcetype) .
"'";
4275 $sql .=
" AND fk_target = " . ((int) $this->
id) .
" AND targettype = '" . $this->db->escape($this->element) .
"'";
4276 } elseif ($deletetarget) {
4277 $sql .=
" fk_target = " . ((int) $targetid) .
" AND targettype = '" . $this->db->escape($targettype) .
"'";
4278 $sql .=
" AND fk_source = " . ((int) $this->
id) .
" AND sourcetype = '" . $this->db->escape($this->element) .
"'";
4280 $sql .=
" (fk_source = " . ((int) $this->
id) .
" AND sourcetype = '" . $this->db->escape($this->element) .
"')";
4282 $sql .=
" (fk_target = " . ((int) $this->
id) .
" AND targettype = '" . $this->db->escape($this->element) .
"')";
4286 dol_syslog(get_class($this) .
"::deleteObjectLinked", LOG_DEBUG);
4287 if (!$this->db->query($sql)) {
4288 $this->error = $this->db->lasterror();
4289 $this->errors[] = $this->error;
4295 $this->db->commit();
4298 $this->db->rollback();
4314 if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
4320 $sql =
"SELECT ".$field_select.
" FROM ".$db->prefix().$table_element.
" WHERE ".$field_where.
" = ".((int) $fk_object_where);
4321 $resql = $db->query($sql);
4324 if (!empty($resql)) {
4325 while ($res = $db->fetch_object($resql)) {
4326 $TRes[] = $res->{$field_select};
4343 if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
4349 $sql =
"DELETE FROM ".$db->prefix().$table_element.
" WHERE ".$field_where.
" = ".((int) $fk_object_where);
4350 $resql = $db->query($sql);
4352 if (empty($resql)) {
4369 public function setStatut($status, $elementId =
null, $elementType =
'', $trigkey =
'', $fieldstatus =
'fk_statut')
4371 global $user, $langs, $conf;
4373 $savElementId = $elementId;
4375 $elementId = (!empty($elementId) ? $elementId : $this->id);
4376 $elementTable = (!empty($elementType) ? $elementType : $this->table_element);
4380 if ($elementTable ==
'facture_rec') {
4381 $fieldstatus =
"suspended";
4383 if ($elementTable ==
'mailing') {
4384 $fieldstatus =
"statut";
4386 if ($elementTable ==
'cronjob') {
4387 $fieldstatus =
"status";
4389 if ($elementTable ==
'user') {
4390 $fieldstatus =
"statut";
4392 if ($elementTable ==
'expensereport') {
4393 $fieldstatus =
"fk_statut";
4395 if ($elementTable ==
'commande_fournisseur_dispatch') {
4396 $fieldstatus =
"status";
4398 if (isset($this->fields) && is_array($this->fields) && array_key_exists(
'status', $this->fields)) {
4399 $fieldstatus =
'status';
4402 $sql =
"UPDATE ".$this->db->prefix().$elementTable;
4403 $sql .=
" SET ".$fieldstatus.
" = ".((int) $status);
4406 if ($status == 1 && in_array($elementTable, array(
'expensereport',
'inventory'))) {
4407 $sql .=
", fk_user_valid = ".((int) $user->id);
4409 if ($status == 1 && in_array($elementTable, array(
'expensereport'))) {
4410 $sql .=
", date_valid = '".$this->db->idate(
dol_now()).
"'";
4412 if ($status == 1 && in_array($elementTable, array(
'inventory'))) {
4413 $sql .=
", date_validation = '".$this->db->idate(
dol_now()).
"'";
4415 $sql .=
" WHERE rowid = ".((int) $elementId);
4416 $sql .=
" AND ".$fieldstatus.
" <> ".((int) $status);
4418 dol_syslog(get_class($this).
"::setStatut", LOG_DEBUG);
4419 $resql = $this->db->query($sql);
4423 $nb_rows_affected = $this->db->affected_rows($resql);
4425 if ($nb_rows_affected > 0) {
4426 if (empty($trigkey)) {
4428 if ($this->element ==
'supplier_proposal' && $status == 2) {
4429 $trigkey =
'SUPPLIER_PROPOSAL_SIGN';
4431 if ($this->element ==
'supplier_proposal' && $status == 3) {
4432 $trigkey =
'SUPPLIER_PROPOSAL_REFUSE';
4434 if ($this->element ==
'supplier_proposal' && $status == 4) {
4435 $trigkey =
'SUPPLIER_PROPOSAL_CLOSE';
4437 if ($this->element ==
'fichinter' && $status == 3) {
4438 $trigkey =
'FICHINTER_CLASSIFY_DONE';
4440 if ($this->element ==
'fichinter' && $status == 2) {
4441 $trigkey =
'FICHINTER_CLASSIFY_BILLED';
4443 if ($this->element ==
'fichinter' && $status == 1) {
4444 $trigkey =
'FICHINTER_CLASSIFY_UNBILLED';
4448 $this->context = array_merge($this->context, array(
'newstatus' => $status));
4454 $result = $this->call_trigger($trigkey, $user);
4465 $this->db->commit();
4467 if (empty($savElementId)) {
4469 if ($fieldstatus ==
'tosell') {
4470 $this->status = $status;
4471 } elseif ($fieldstatus ==
'tobuy') {
4472 $this->status_buy = $status;
4475 $this->status = $status;
4481 $this->db->rollback();
4482 dol_syslog(get_class($this).
"::setStatut ".$this->error, LOG_ERR);
4486 $this->error = $this->db->lasterror();
4487 $this->db->rollback();
4504 if (empty($id) && empty($ref)) {
4507 if (!empty($conf->global->MAIN_DISABLE_CANVAS)) {
4514 $sql =
"SELECT rowid, canvas";
4515 $sql .=
" FROM ".$this->db->prefix().$this->table_element;
4516 $sql .=
" WHERE entity IN (".getEntity($this->element).
")";
4518 $sql .=
" AND rowid = ".((int) $id);
4521 $sql .=
" AND ref = '".$this->db->escape($ref).
"'";
4524 $resql = $this->db->query($sql);
4526 $obj = $this->db->fetch_object($resql);
4528 $this->canvas = $obj->canvas;
4548 $sql =
"SELECT special_code FROM ".$this->db->prefix().$this->table_element_line;
4549 $sql .=
" WHERE rowid = ".((int) $lineid);
4550 $resql = $this->db->query($sql);
4552 $row = $this->db->fetch_row($resql);
4553 return (!empty($row[0]) ? $row[0] : 0);
4576 if (!isset($this->childtables) || !is_array($this->childtables) || count($this->childtables) == 0) {
4577 dol_print_error(
'Called isObjectUsed on a class with property this->childtables not defined');
4581 $arraytoscan = $this->childtables;
4583 $tmparray = array_keys($this->childtables);
4584 if (is_numeric($tmparray[0])) {
4585 $arraytoscan = array_flip($this->childtables);
4590 foreach ($arraytoscan as $table => $element) {
4593 $sql =
"SELECT COUNT(*) as nb";
4594 $sql.=
" FROM ".$this->db->prefix().$table.
" as c";
4595 if (!empty($element[
'parent']) && !empty($element[
'parentkey'])) {
4596 $sql.=
", ".$this->db->prefix().$element[
'parent'].
" as p";
4598 if (!empty($element[
'fk_element'])) {
4599 $sql.=
" WHERE c.".$element[
'fk_element'].
" = ".((int) $id);
4601 $sql.=
" WHERE c.".$this->fk_element.
" = ".((int) $id);
4603 if (!empty($element[
'parent']) && !empty($element[
'parentkey'])) {
4604 $sql.=
" AND c.".$element[
'parentkey'].
" = p.rowid";
4606 if (!empty($element[
'parent']) && !empty($element[
'parenttypefield']) && !empty($element[
'parenttypevalue'])) {
4607 $sql.=
" AND c.".$element[
'parenttypefield'].
" = '".$this->db->escape($element[
'parenttypevalue']).
"'";
4609 if (!empty($entity)) {
4610 if (!empty($element[
'parent']) && !empty($element[
'parentkey'])) {
4611 $sql.=
" AND p.entity = ".((int) $entity);
4613 $sql.=
" AND c.entity = ".((int) $entity);
4617 $resql = $this->db->query($sql);
4619 $obj = $this->db->fetch_object($resql);
4621 $langs->load(
"errors");
4623 $haschild += $obj->nb;
4624 if (is_numeric($element)) {
4625 $this->errors[] = $langs->transnoentitiesnoconv(
"ErrorRecordHasAtLeastOneChildOfType", method_exists($this,
'getNomUrl') ? $this->getNomUrl() : $this->ref, $table);
4626 } elseif (is_string($element)) {
4627 $this->errors[] = $langs->transnoentitiesnoconv(
"ErrorRecordHasAtLeastOneChildOfType", method_exists($this,
'getNomUrl') ? $this->getNomUrl() : $this->ref, $langs->transnoentitiesnoconv($element));
4629 $this->errors[] = $langs->transnoentitiesnoconv(
"ErrorRecordHasAtLeastOneChildOfType", method_exists($this,
'getNomUrl') ? $this->getNomUrl() : $this->ref, $langs->transnoentitiesnoconv($element[
'name']));
4634 $this->errors[] = $this->db->lasterror();
4638 if ($haschild > 0) {
4639 $this->errors[] =
"ErrorRecordHasChildren";
4656 foreach ($this->lines as $key => $val) {
4658 if ($predefined == -1) {
4661 if ($predefined == 1 && $val->fk_product > 0) {
4664 if ($predefined == 0 && $val->fk_product <= 0) {
4667 if ($predefined == 2 && $val->fk_product > 0 && $val->product_type == 0) {
4670 if ($predefined == 3 && $val->fk_product > 0 && $val->product_type == 1) {
4677 dol_syslog(get_class($this).
'::hasProductsOrServices we found '.$nb.
' qualified lines of products/servcies');
4688 if (!empty($this->table_element_line) ) {
4689 $total_discount = 0.00;
4691 $sql =
"SELECT subprice as pu_ht, qty, remise_percent, total_ht";
4692 $sql .=
" FROM ".$this->db->prefix().$this->table_element_line;
4693 $sql .=
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
4695 dol_syslog(get_class($this).
'::getTotalDiscount', LOG_DEBUG);
4696 $resql = $this->db->query($sql);
4698 $num = $this->db->num_rows($resql);
4701 $obj = $this->db->fetch_object($resql);
4703 $pu_ht = $obj->pu_ht;
4705 $total_ht = $obj->total_ht;
4707 $total_discount_line = floatval(
price2num(($pu_ht * $qty) - $total_ht,
'MT'));
4708 $total_discount += $total_discount_line;
4737 foreach ($this->lines as $line) {
4738 if (isset($line->qty_asked)) {
4739 if (empty($totalOrdered)) {
4742 $totalOrdered += $line->qty_asked;
4744 if (isset($line->qty_shipped)) {
4745 if (empty($totalToShip)) {
4748 $totalToShip += $line->qty_shipped;
4749 } elseif ($line->element ==
'commandefournisseurdispatch' && isset($line->qty)) {
4750 if (empty($totalToShip)) {
4753 $totalToShip += $line->qty;
4757 if ($this->element ==
'shipping') {
4759 $qty = $line->qty_shipped ? $line->qty_shipped : 0;
4761 $qty = $line->qty ? $line->qty : 0;
4764 $weight = !empty($line->weight) ? $line->weight : 0;
4765 ($weight == 0 && !empty($line->product->weight)) ? $weight = $line->product->weight : 0;
4766 $volume = !empty($line->volume) ? $line->volume : 0;
4767 ($volume == 0 && !empty($line->product->volume)) ? $volume = $line->product->volume : 0;
4769 $weight_units = !empty($line->weight_units) ? $line->weight_units : 0;
4770 ($weight_units == 0 && !empty($line->product->weight_units)) ? $weight_units = $line->product->weight_units : 0;
4771 $volume_units = !empty($line->volume_units) ? $line->volume_units : 0;
4772 ($volume_units == 0 && !empty($line->product->volume_units)) ? $volume_units = $line->product->volume_units : 0;
4776 if (!empty($weight_units)) {
4777 $weightUnit = $weight_units;
4779 if (!empty($volume_units)) {
4780 $volumeUnit = $volume_units;
4783 if (empty($totalWeight)) {
4786 if (empty($totalVolume)) {
4791 if ($weight_units < 50) {
4792 $trueWeightUnit = pow(10, $weightUnit);
4793 $totalWeight += $weight * $qty * $trueWeightUnit;
4795 if ($weight_units == 99) {
4797 $trueWeightUnit = 0.45359237;
4798 $totalWeight += $weight * $qty * $trueWeightUnit;
4799 } elseif ($weight_units == 98) {
4801 $trueWeightUnit = 0.0283495;
4802 $totalWeight += $weight * $qty * $trueWeightUnit;
4804 $totalWeight += $weight * $qty;
4807 if ($volume_units < 50) {
4809 $trueVolumeUnit = pow(10, $volumeUnit);
4811 $totalVolume += $volume * $qty * $trueVolumeUnit;
4813 $totalVolume += $volume * $qty;
4817 return array(
'weight'=>$totalWeight,
'volume'=>$totalVolume,
'ordered'=>$totalOrdered,
'toship'=>$totalToShip);
4830 $extraparams = (!empty($this->extraparams) ? json_encode($this->extraparams) :
null);
4832 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
4833 $sql .=
" SET extraparams = ".(!empty($extraparams) ?
"'".$this->db->escape($extraparams).
"'" :
"null");
4834 $sql .=
" WHERE rowid = ".((int) $this->
id);
4836 dol_syslog(get_class($this).
"::setExtraParameters", LOG_DEBUG);
4837 $resql = $this->db->query($sql);
4839 $this->error = $this->db->lasterror();
4840 $this->db->rollback();
4843 $this->db->commit();
4866 global $conf, $user, $langs, $object, $hookmanager, $extrafields;
4870 if (!is_object($extrafields)) {
4871 require_once DOL_DOCUMENT_ROOT.
'/core/class/extrafields.class.php';
4874 $extrafields->fetch_name_optionals_label($this->table_element_line);
4879 $dirtpls = array_merge($conf->modules_parts[
'tpl'], array($defaulttpldir));
4880 foreach ($dirtpls as $module => $reldir) {
4881 if (!empty($module)) {
4884 $tpl = DOL_DOCUMENT_ROOT.$reldir.
'/objectline_create.tpl.php';
4887 if (empty($conf->file->strict_mode)) {
4888 $res = @include $tpl;
4890 $res = include $tpl;
4917 public function printObjectLines($action, $seller, $buyer, $selected = 0, $dateSelector = 0, $defaulttpldir =
'/core/tpl')
4919 global $conf, $hookmanager, $langs, $user, $form, $extrafields, $object;
4921 global $inputalsopricewithtax, $usemargins, $disableedit, $disablemove, $disableremove, $outputalsopricetotalwithtax;
4925 if (isModEnabled(
'margin') && !empty($this->element) && in_array($this->element, array(
'facture',
'facturerec',
'propal',
'commande'))) {
4929 $num = count($this->lines);
4932 if (!is_object($extrafields)) {
4933 require_once DOL_DOCUMENT_ROOT.
'/core/class/extrafields.class.php';
4936 $extrafields->fetch_name_optionals_label($this->table_element_line);
4938 $parameters = array(
'num'=>$num,
'dateSelector'=>$dateSelector,
'seller'=>$seller,
'buyer'=>$buyer,
'selected'=>$selected,
'table_element_line'=>$this->table_element_line);
4939 $reshook = $hookmanager->executeHooks(
'printObjectLineTitle', $parameters, $this, $action);
4940 if (empty($reshook)) {
4944 $dirtpls = array_merge($conf->modules_parts[
'tpl'], array($defaulttpldir));
4945 foreach ($dirtpls as $module => $reldir) {
4947 if (!empty($module)) {
4950 $tpl = DOL_DOCUMENT_ROOT.$reldir.
'/objectline_title.tpl.php';
4952 if (file_exists($tpl)) {
4953 if (empty($conf->file->strict_mode)) {
4954 $res = @include $tpl;
4956 $res = include $tpl;
4967 print
"<!-- begin printObjectLines() --><tbody>\n";
4968 foreach ($this->lines as $line) {
4970 $line->fetch_optionals();
4973 if (is_object($hookmanager)) {
4974 if (empty($line->fk_parent_line)) {
4975 $parameters = array(
'line'=>$line,
'num'=>$num,
'i'=>$i,
'dateSelector'=>$dateSelector,
'seller'=>$seller,
'buyer'=>$buyer,
'selected'=>$selected,
'table_element_line'=>$line->table_element,
'defaulttpldir'=>$defaulttpldir);
4976 $reshook = $hookmanager->executeHooks(
'printObjectLine', $parameters, $this, $action);
4978 $parameters = array(
'line'=>$line,
'num'=>$num,
'i'=>$i,
'dateSelector'=>$dateSelector,
'seller'=>$seller,
'buyer'=>$buyer,
'selected'=>$selected,
'table_element_line'=>$line->table_element,
'fk_parent_line'=>$line->fk_parent_line,
'defaulttpldir'=>$defaulttpldir);
4979 $reshook = $hookmanager->executeHooks(
'printObjectSubLine', $parameters, $this, $action);
4982 if (empty($reshook)) {
4983 $this->printObjectLine($action, $line,
'', $num, $i, $dateSelector, $seller, $buyer, $selected, $extrafields, $defaulttpldir);
4988 print
"</tbody><!-- end printObjectLines() -->\n";
5008 public function printObjectLine($action, $line, $var, $num, $i, $dateSelector, $seller, $buyer, $selected = 0, $extrafields =
null, $defaulttpldir =
'/core/tpl')
5010 global $conf, $langs, $user, $object, $hookmanager;
5012 global $object_rights, $disableedit, $disablemove, $disableremove;
5014 $object_rights = $this->getRights();
5020 if ($action !=
'editline' || $selected != $line->id) {
5022 if (!empty($line->fk_product) && $line->fk_product > 0) {
5023 $product_static =
new Product($this->db);
5024 $product_static->fetch($line->fk_product);
5026 $product_static->ref = $line->ref;
5027 $product_static->label = !empty($line->label) ? $line->label :
"";
5029 $text = $product_static->getNomUrl(1);
5033 if (property_exists($this,
'socid') && !is_object($this->thirdparty)) {
5034 dol_print_error(
'',
'Error: Method printObjectLine was called on an object and object->fetch_thirdparty was not done before');
5038 $prod =
new Product($this->db);
5039 $prod->fetch($line->fk_product);
5041 $outputlangs = $langs;
5043 if (empty($newlang) &&
GETPOST(
'lang_id',
'aZ09')) {
5044 $newlang =
GETPOST(
'lang_id',
'aZ09');
5046 if (!empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE) && empty($newlang) && is_object($this->thirdparty)) {
5047 $newlang = $this->thirdparty->default_lang;
5049 if (!empty($newlang)) {
5050 $outputlangs =
new Translate(
"", $conf);
5051 $outputlangs->setDefaultLang($newlang);
5054 $label = (!empty($prod->multilangs[$outputlangs->defaultlang][
"label"])) ? $prod->multilangs[$outputlangs->defaultlang][
"label"] : $line->product_label;
5056 $label = $line->product_label;
5059 $text .=
' - '.(!empty($line->label) ? $line->label : $label);
5060 $description .= (
getDolGlobalInt(
'PRODUIT_DESC_IN_FORM_ACCORDING_TO_DEVICE') ?
'' : (!empty($line->description) ?
dol_htmlentitiesbr($line->description) :
''));
5063 $line->pu_ttc =
price2num((!empty($line->subprice) ? $line->subprice : 0) * (1 + ((!empty($line->tva_tx) ? $line->tva_tx : 0) / 100)),
'MU');
5068 $dirtpls = array_merge($conf->modules_parts[
'tpl'], array($defaulttpldir));
5069 foreach ($dirtpls as $module => $reldir) {
5071 if (!empty($module)) {
5074 $tpl = DOL_DOCUMENT_ROOT.$reldir.
'/objectline_view.tpl.php';
5076 if (file_exists($tpl)) {
5077 if (empty($conf->file->strict_mode)) {
5078 $res = @include $tpl;
5080 $res = include $tpl;
5090 if ($this->
statut == 0 && $action ==
'editline' && $selected == $line->id) {
5091 $label = (!empty($line->label) ? $line->label : (($line->fk_product > 0) ? $line->product_label :
''));
5093 $line->pu_ttc =
price2num($line->subprice * (1 + ($line->tva_tx / 100)),
'MU');
5098 $dirtpls = array_merge($conf->modules_parts[
'tpl'], array($defaulttpldir));
5099 foreach ($dirtpls as $module => $reldir) {
5100 if (!empty($module)) {
5103 $tpl = DOL_DOCUMENT_ROOT.$reldir.
'/objectline_edit.tpl.php';
5106 if (empty($conf->file->strict_mode)) {
5107 $res = @include $tpl;
5109 $res = include $tpl;
5134 global $langs, $hookmanager, $conf, $form, $action;
5136 print
'<tr class="liste_titre">';
5137 print
'<td class="linecolref">'.$langs->trans(
'Ref').
'</td>';
5138 print
'<td class="linecoldescription">'.$langs->trans(
'Description').
'</td>';
5139 print
'<td class="linecolvat right">'.$langs->trans(
'VATRate').
'</td>';
5140 print
'<td class="linecoluht right">'.$langs->trans(
'PriceUHT').
'</td>';
5141 if (isModEnabled(
"multicurrency")) {
5142 print
'<td class="linecoluht_currency right">'.$langs->trans(
'PriceUHTCurrency').
'</td>';
5144 print
'<td class="linecolqty right">'.$langs->trans(
'Qty').
'</td>';
5146 print
'<td class="linecoluseunit left">'.$langs->trans(
'Unit').
'</td>';
5148 print
'<td class="linecoldiscount right">'.$langs->trans(
'ReductionShort').
'</td>';
5149 print
'<td class="linecolht right">'.$langs->trans(
'TotalHT').
'</td>';
5150 print
'<td class="center">'.$form->showCheckAddButtons(
'checkforselect', 1).
'</td>';
5154 if (!empty($this->lines)) {
5155 foreach ($this->lines as $line) {
5158 if (is_object($hookmanager)) {
5159 $parameters = array(
'line'=>$line,
'i'=>$i,
'restrictlist'=>$restrictlist,
'selectedLines'=> $selectedLines);
5160 if (!empty($line->fk_parent_line)) { $parameters[
'fk_parent_line'] = $line->fk_parent_line; }
5161 $reshook = $hookmanager->executeHooks(
'printOriginObjectLine', $parameters, $this, $action);
5163 if (empty($reshook)) {
5164 $this->printOriginLine($line,
'', $restrictlist,
'/core/tpl', $selectedLines);
5185 public function printOriginLine($line, $var, $restrictlist =
'', $defaulttpldir =
'/core/tpl', $selectedLines = array())
5187 global $langs, $conf;
5190 if (!empty($line->date_start)) {
5191 $date_start = $line->date_start;
5193 $date_start = $line->date_debut_prevue;
5194 if ($line->date_debut_reel) {
5195 $date_start = $line->date_debut_reel;
5198 if (!empty($line->date_end)) {
5199 $date_end = $line->date_end;
5201 $date_end = $line->date_fin_prevue;
5202 if ($line->date_fin_reel) {
5203 $date_end = $line->date_fin_reel;
5207 $this->tpl[
'id'] = $line->id;
5209 $this->tpl[
'label'] =
'';
5210 if (!empty($line->fk_parent_line)) {
5211 $this->tpl[
'label'] .=
img_picto(
'',
'rightarrow');
5214 if (($line->info_bits & 2) == 2) {
5216 $discount->fk_soc = $this->socid;
5217 $this->tpl[
'label'] .= $discount->getNomUrl(0,
'discount');
5218 } elseif (!empty($line->fk_product)) {
5219 if (empty($line->product)) {
5220 $line->fetch_product();
5222 $productstatic = $line->product;
5224 $this->tpl[
'label'] .= (is_object($productstatic) ? $productstatic->getNomUrl(1) : $line->ref);
5225 $this->tpl[
'label'] .=
' - '.(!empty($line->label) ? $line->label : $line->product_label);
5227 if ($line->product_type == 1 && ($date_start || $date_end)) {
5231 $this->tpl[
'label'] .= ($line->product_type == -1 ?
' ' : ($line->product_type == 1 ?
img_object($langs->trans(
''),
'service') :
img_object($langs->trans(
''),
'product')));
5232 if (!empty($line->desc)) {
5233 $this->tpl[
'label'] .= $line->desc;
5235 $this->tpl[
'label'] .= ($line->label ?
' '.$line->label :
'');
5239 if ($line->product_type == 1 && ($date_start || $date_end)) {
5244 if (!empty($line->desc)) {
5245 if ($line->desc ==
'(CREDIT_NOTE)') {
5247 $discount->fetch($line->fk_remise_except);
5248 $this->tpl[
'description'] = $langs->transnoentities(
"DiscountFromCreditNote", $discount->getNomUrl(0));
5249 } elseif ($line->desc ==
'(DEPOSIT)') {
5251 $discount->fetch($line->fk_remise_except);
5252 $this->tpl[
'description'] = $langs->transnoentities(
"DiscountFromDeposit", $discount->getNomUrl(0));
5253 } elseif ($line->desc ==
'(EXCESS RECEIVED)') {
5255 $discount->fetch($line->fk_remise_except);
5256 $this->tpl[
'description'] = $langs->transnoentities(
"DiscountFromExcessReceived", $discount->getNomUrl(0));
5257 } elseif ($line->desc ==
'(EXCESS PAID)') {
5259 $discount->fetch($line->fk_remise_except);
5260 $this->tpl[
'description'] = $langs->transnoentities(
"DiscountFromExcessPaid", $discount->getNomUrl(0));
5262 $this->tpl[
'description'] =
dol_trunc($line->desc, 60);
5265 $this->tpl[
'description'] =
' ';
5269 $this->tpl[
'vat_rate'] =
vatrate($line->tva_tx,
true);
5270 $this->tpl[
'vat_rate'] .= (($line->info_bits & 1) == 1) ?
'*' :
'';
5271 if (!empty($line->vat_src_code) && !preg_match(
'/\(/', $this->tpl[
'vat_rate'])) {
5272 $this->tpl[
'vat_rate'] .=
' ('.$line->vat_src_code.
')';
5275 $this->tpl[
'price'] =
price($line->subprice);
5276 $this->tpl[
'total_ht'] =
price($line->total_ht);
5277 $this->tpl[
'multicurrency_price'] =
price($line->multicurrency_subprice);
5278 $this->tpl[
'qty'] = (($line->info_bits & 2) != 2) ? $line->qty :
' ';
5280 $this->tpl[
'unit'] = $langs->transnoentities($line->getLabelOfUnit(
'long'));
5282 $this->tpl[
'remise_percent'] = (($line->info_bits & 2) != 2) ?
vatrate($line->remise_percent,
true) :
' ';
5285 $this->tpl[
'strike'] = 0;
5287 $this->tpl[
'strike'] = 1;
5292 $dirtpls = array_merge($conf->modules_parts[
'tpl'], array($defaulttpldir));
5293 foreach ($dirtpls as $module => $reldir) {
5294 if (!empty($module)) {
5297 $tpl = DOL_DOCUMENT_ROOT.$reldir.
'/originproductline.tpl.php';
5300 if (empty($conf->file->strict_mode)) {
5301 $res = @include $tpl;
5303 $res = include $tpl;
5328 $sql =
"INSERT INTO ".$this->db->prefix().
"element_resources (";
5329 $sql .=
"resource_id";
5330 $sql .=
", resource_type";
5331 $sql .=
", element_id";
5332 $sql .=
", element_type";
5334 $sql .=
", mandatory";
5335 $sql .=
") VALUES (";
5336 $sql .= ((int) $resource_id);
5337 $sql .=
", '".$this->db->escape($resource_type).
"'";
5338 $sql .=
", '".$this->db->escape($this->
id).
"'";
5339 $sql .=
", '".$this->db->escape($this->element).
"'";
5340 $sql .=
", '".$this->db->escape($busy).
"'";
5341 $sql .=
", '".$this->db->escape($mandatory).
"'";
5344 dol_syslog(get_class($this).
"::add_element_resource", LOG_DEBUG);
5345 if ($this->db->query($sql)) {
5346 $this->db->commit();
5349 $this->error = $this->db->lasterror();
5350 $this->db->rollback();
5371 $sql =
"DELETE FROM ".$this->db->prefix().
"element_resources";
5372 $sql .=
" WHERE rowid = ".((int) $rowid);
5374 dol_syslog(get_class($this).
"::delete_resource", LOG_DEBUG);
5376 $resql = $this->db->query($sql);
5378 $this->error = $this->db->lasterror();
5379 $this->db->rollback();
5383 $result = $this->call_trigger(strtoupper($element).
'_DELETE_RESOURCE', $user);
5385 $this->db->rollback();
5389 $this->db->commit();
5403 if (isset($this->lines) && is_array($this->lines)) {
5404 $nboflines = count($this->lines);
5405 for ($i = 0; $i < $nboflines; $i++) {
5406 if (is_object($this->lines[$i])) {
5407 $this->lines[$i] = clone $this->lines[$i];
5426 protected function commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams =
null)
5428 global $conf, $langs, $user, $hookmanager, $action;
5430 $srctemplatepath =
'';
5432 $parameters = array(
'modelspath'=>$modelspath,
'modele'=>$modele,
'outputlangs'=>$outputlangs,
'hidedetails'=>$hidedetails,
'hidedesc'=>$hidedesc,
'hideref'=>$hideref,
'moreparams'=>$moreparams);
5433 $reshook = $hookmanager->executeHooks(
'commonGenerateDocument', $parameters, $this, $action);
5435 if (!empty($reshook)) {
5439 dol_syslog(
"commonGenerateDocument modele=".$modele.
" outputlangs->defaultlang=".(is_object($outputlangs) ? $outputlangs->defaultlang :
'null'));
5441 if (empty($modele)) {
5442 $this->error =
'BadValueForParameterModele';
5447 $err = error_reporting();
5449 @set_time_limit(120);
5450 error_reporting($err);
5453 $tmp = explode(
':', $modele, 2);
5454 if (!empty($tmp[1])) {
5456 $srctemplatepath = $tmp[1];
5463 $dirmodels = array(
'/');
5464 if (is_array($conf->modules_parts[
'models'])) {
5465 $dirmodels = array_merge($dirmodels, $conf->modules_parts[
'models']);
5467 foreach ($dirmodels as $reldir) {
5468 foreach (array(
'doc',
'pdf') as $prefix) {
5469 if (in_array(get_class($this), array(
'Adherent'))) {
5471 $file = $prefix.
"_".$modele.
".class.php";
5474 $file = $prefix.
"_".$modele.
".modules.php";
5479 if (file_exists($file)) {
5481 $classname = $prefix.
'_'.$modele;
5491 $this->error = $langs->trans(
"Error").
' Failed to load doc generator with modelpaths='.$modelspath.
' - modele='.$modele;
5492 $this->errors[] = $this->error;
5502 $obj =
new $classname($this->db);
5505 if ($obj->type ==
'odt' && empty($srctemplatepath)) {
5506 $varfortemplatedir = $obj->scandir;
5507 if ($varfortemplatedir && !empty($conf->global->$varfortemplatedir)) {
5508 $dirtoscan = $conf->global->$varfortemplatedir;
5510 $listoffiles = array();
5513 $listofdir = explode(
',', $dirtoscan);
5514 foreach ($listofdir as $key => $tmpdir) {
5515 $tmpdir = trim($tmpdir);
5516 $tmpdir = preg_replace(
'/DOL_DATA_ROOT/', DOL_DATA_ROOT, $tmpdir);
5518 unset($listofdir[$key]);
5521 if (is_dir($tmpdir)) {
5522 $tmpfiles =
dol_dir_list($tmpdir,
'files', 0,
'\.od(s|t)$',
'',
'name', SORT_ASC, 0);
5523 if (count($tmpfiles)) {
5524 $listoffiles = array_merge($listoffiles, $tmpfiles);
5529 if (count($listoffiles)) {
5530 foreach ($listoffiles as $record) {
5531 $srctemplatepath = $record[
'fullname'];
5537 if (empty($srctemplatepath)) {
5538 $this->error =
'ErrorGenerationAskedForOdtTemplateWithSrcFileNotDefined';
5543 if ($obj->type ==
'odt' && !empty($srctemplatepath)) {
5545 dol_syslog(
"Failed to locate template file ".$srctemplatepath, LOG_WARNING);
5546 $this->error =
'ErrorGenerationAskedForOdtTemplateWithSrcFileNotFound';
5553 $sav_charset_output = empty($outputlangs->charset_output) ?
'' : $outputlangs->charset_output;
5555 if (in_array(get_class($this), array(
'Adherent'))) {
5556 $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath,
'member', 1,
'tmp_cards', $moreparams);
5558 $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, $hidedetails, $hidedesc, $hideref, $moreparams);
5562 if ($resultwritefile > 0) {
5563 $outputlangs->charset_output = $sav_charset_output;
5566 require_once DOL_DOCUMENT_ROOT.
'/core/lib/files.lib.php';
5570 if (!empty($obj->result[
'fullpath'])) {
5571 $destfull = $obj->result[
'fullpath'];
5574 $update_main_doc_field = 0;
5575 if (!empty($obj->update_main_doc_field)) {
5576 $update_main_doc_field = 1;
5582 $this->indexFile($destfull, $update_main_doc_field);
5585 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);
5593 $outputlangs->charset_output = $sav_charset_output;
5594 $this->error = $obj->error;
5595 $this->errors = $obj->errors;
5596 dol_syslog(
"Error generating document for ".__CLASS__.
". Error: ".$obj->error, LOG_ERR);
5610 public function indexFile($destfull, $update_main_doc_field)
5612 global $conf, $user;
5614 $upload_dir = dirname($destfull);
5615 $destfile = basename($destfull);
5616 $rel_dir = preg_replace(
'/^'.preg_quote(DOL_DATA_ROOT,
'/').
'/',
'', $upload_dir);
5618 if (!preg_match(
'/[\\/]temp[\\/]|[\\/]thumbs|\.meta$/', $rel_dir)) {
5619 $filename = basename($destfile);
5620 $rel_dir = preg_replace(
'/[\\/]$/',
'', $rel_dir);
5621 $rel_dir = preg_replace(
'/^[\\/]/',
'', $rel_dir);
5623 include_once DOL_DOCUMENT_ROOT.
'/ecm/class/ecmfiles.class.php';
5624 $ecmfile =
new EcmFiles($this->db);
5625 $result = $ecmfile->fetch(0,
'', ($rel_dir ? $rel_dir.
'/' :
'').$filename);
5628 $setsharekey =
false;
5629 if ($this->element ==
'propal' || $this->element ==
'proposal') {
5630 if (!isset($conf->global->PROPOSAL_ALLOW_ONLINESIGN) || !empty($conf->global->PROPOSAL_ALLOW_ONLINESIGN)) {
5631 $setsharekey =
true;
5633 if (!empty($conf->global->PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD)) {
5634 $setsharekey =
true;
5637 if ($this->element ==
'commande' && !empty($conf->global->ORDER_ALLOW_EXTERNAL_DOWNLOAD)) {
5638 $setsharekey =
true;
5640 if ($this->element ==
'facture' && !empty($conf->global->INVOICE_ALLOW_EXTERNAL_DOWNLOAD)) {
5641 $setsharekey =
true;
5643 if ($this->element ==
'bank_account' && !empty($conf->global->BANK_ACCOUNT_ALLOW_EXTERNAL_DOWNLOAD)) {
5644 $setsharekey =
true;
5646 if ($this->element ==
'product' && !empty($conf->global->PRODUCT_ALLOW_EXTERNAL_DOWNLOAD)) {
5647 $setsharekey =
true;
5649 if ($this->element ==
'contrat' && !empty($conf->global->CONTRACT_ALLOW_EXTERNAL_DOWNLOAD)) {
5650 $setsharekey =
true;
5652 if ($this->element ==
'fichinter' && !empty($conf->global->FICHINTER_ALLOW_EXTERNAL_DOWNLOAD)) {
5653 $setsharekey =
true;
5655 if ($this->element ==
'supplier_proposal' && !empty($conf->global->SUPPLIER_PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD)) {
5656 $setsharekey =
true;
5660 if (empty($ecmfile->share)) {
5661 require_once DOL_DOCUMENT_ROOT.
'/core/lib/security2.lib.php';
5668 $ecmfile->fullpath_orig =
'';
5669 $ecmfile->gen_or_uploaded =
'generated';
5670 $ecmfile->description =
'';
5671 $ecmfile->keywords =
'';
5672 $result = $ecmfile->update($user);
5678 $ecmfile->entity = $conf->entity;
5679 $ecmfile->filepath = $rel_dir;
5680 $ecmfile->filename = $filename;
5682 $ecmfile->fullpath_orig =
'';
5683 $ecmfile->gen_or_uploaded =
'generated';
5684 $ecmfile->description =
'';
5685 $ecmfile->keywords =
'';
5686 $ecmfile->src_object_type = $this->table_element;
5687 $ecmfile->src_object_id = $this->id;
5689 $result = $ecmfile->create($user);
5701 if ($update_main_doc_field && !empty($this->table_element)) {
5702 $sql =
"UPDATE ".$this->db->prefix().$this->table_element.
" SET last_main_doc = '".$this->db->escape($ecmfile->filepath.
"/".$ecmfile->filename).
"'";
5703 $sql .=
" WHERE rowid = ".((int) $this->
id);
5705 $resql = $this->db->query($sql);
5710 $this->last_main_doc = $ecmfile->filepath.
'/'.$ecmfile->filename;
5729 if (file_exists($file_osencoded)) {
5730 require_once DOL_DOCUMENT_ROOT.
'/core/lib/images.lib.php';
5733 $maxwidthsmall = $tmparraysize[
'maxwidthsmall'];
5734 $maxheightsmall = $tmparraysize[
'maxheightsmall'];
5735 $maxwidthmini = $tmparraysize[
'maxwidthmini'];
5736 $maxheightmini = $tmparraysize[
'maxheightmini'];
5742 vignette($file_osencoded, $maxwidthsmall, $maxheightsmall,
'_small', $quality);
5746 vignette($file_osencoded, $maxwidthmini, $maxheightmini,
'_mini', $quality);
5785 global $conf, $_POST;
5788 if (GETPOSTISSET($fieldname)) {
5789 return GETPOST($fieldname, $type, 3);
5792 if (isset($alternatevalue)) {
5793 return $alternatevalue;
5796 $newelement = $this->element;
5797 if ($newelement ==
'facture') {
5798 $newelement =
'invoice';
5800 if ($newelement ==
'commande') {
5801 $newelement =
'order';
5803 if (empty($newelement)) {
5804 dol_syslog(
"Ask a default value using common method getDefaultCreateValueForField on an object with no property ->element defined. Return empty string.", LOG_WARNING);
5808 $keyforfieldname = strtoupper($newelement.
'_DEFAULT_'.$fieldname);
5810 if (isset($conf->global->$keyforfieldname)) {
5811 return $conf->global->$keyforfieldname;
5838 global $langs, $conf;
5839 if (!empty(self::TRIGGER_PREFIX) && strpos($triggerName, self::TRIGGER_PREFIX .
'_') !== 0) {
5840 dol_print_error(
'',
'The trigger "' . $triggerName .
'" does not start with "' . self::TRIGGER_PREFIX .
'_" as required.');
5843 if (!is_object($langs)) {
5844 include_once DOL_DOCUMENT_ROOT.
'/core/class/translate.class.php';
5848 include_once DOL_DOCUMENT_ROOT.
'/core/class/interfaces.class.php';
5850 $result = $interface->run_triggers($triggerName, $this, $user, $langs, $conf);
5853 if (!empty($this->errors)) {
5854 $this->errors = array_unique(array_merge($this->errors, $interface->errors));
5856 $this->errors = $interface->errors;
5876 if (!$this->element) {
5879 if (!($this->
id > 0)) {
5882 if (is_array($this->array_languages)) {
5886 $this->array_languages = array();
5888 $element = $this->element;
5889 if ($element ==
'categorie') {
5890 $element =
'categories';
5894 $sql =
"SELECT rowid, property, lang , value";
5895 $sql .=
" FROM ".$this->db->prefix().
"object_lang";
5896 $sql .=
" WHERE type_object = '".$this->db->escape($element).
"'";
5897 $sql .=
" AND fk_object = ".((int) $this->
id);
5900 $resql = $this->db->query($sql);
5902 $numrows = $this->db->num_rows($resql);
5905 while ($i < $numrows) {
5906 $obj = $this->db->fetch_object($resql);
5907 $key = $obj->property;
5908 $value = $obj->value;
5909 $codelang = $obj->lang;
5910 $type = $this->fields[$key][
'type'];
5913 if (preg_match(
'/date/', $type)) {
5914 $this->array_languages[$key][$codelang] = $this->db->jdate($value);
5916 $this->array_languages[$key][$codelang] = $value;
5923 $this->db->free($resql);
5944 global $_POST, $langs;
5947 foreach ($_POST as $postfieldkey => $postfieldvalue) {
5948 $tmparray = explode(
'-', $postfieldkey);
5949 if ($tmparray[0] !=
'field') {
5953 $element = $tmparray[1];
5954 $key = $tmparray[2];
5955 $codelang = $tmparray[3];
5958 if (!empty($onlykey) && $key != $onlykey) {
5961 if ($element != $this->element) {
5965 $key_type = $this->fields[$key][
'type'];
5968 if (isset($this->fields[$key][
'enabled'])) {
5969 $enabled =
dol_eval($this->fields[$key][
'enabled'], 1, 1,
'1');
5976 if (empty($enabled)) {
5981 if (in_array($key_type, array(
'date'))) {
5985 } elseif (in_array($key_type, array(
'datetime'))) {
5988 $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'));
5989 } elseif (in_array($key_type, array(
'checkbox',
'chkbxlst'))) {
5990 $value_arr =
GETPOST($postfieldkey,
'array');
5991 if (!empty($value_arr)) {
5992 $value_key = implode(
',', $value_arr);
5996 } elseif (in_array($key_type, array(
'price',
'double'))) {
5997 $value_arr =
GETPOST($postfieldkey,
'alpha');
6000 $value_key =
GETPOST($postfieldkey);
6001 if (in_array($key_type, array(
'link')) && $value_key ==
'-1') {
6006 $this->array_languages[$key][$codelang] = $value_key;
6031 $savDisableCompute = $conf->disable_compute;
6032 $conf->disable_compute = 1;
6034 $ret = $this->fetch($id);
6036 $conf->disable_compute = $savDisableCompute;
6054 global $conf, $extrafields;
6056 if (empty($rowid)) {
6059 if (empty($rowid) && isset($this->
rowid)) {
6060 $rowid = $this->rowid;
6064 if (!$this->table_element) {
6068 $this->array_options = array();
6070 if (!is_array($optionsArray)) {
6072 if (!isset($extrafields) || !is_object($extrafields)) {
6073 require_once DOL_DOCUMENT_ROOT.
'/core/class/extrafields.class.php';
6078 if (empty($extrafields->attributes[$this->table_element][
'loaded'])) {
6079 $extrafields->fetch_name_optionals_label($this->table_element);
6081 $optionsArray = (!empty($extrafields->attributes[$this->table_element][
'label']) ? $extrafields->attributes[$this->table_element][
'label'] :
null);
6083 global $extrafields;
6084 dol_syslog(
"Warning: fetch_optionals was called with param optionsArray defined when you should pass null now", LOG_WARNING);
6087 $table_element = $this->table_element;
6088 if ($table_element ==
'categorie') {
6089 $table_element =
'categories';
6093 if (is_array($optionsArray) && count($optionsArray) > 0) {
6094 $sql =
"SELECT rowid";
6095 foreach ($optionsArray as $name => $label) {
6096 if (empty($extrafields->attributes[$this->table_element][
'type'][$name]) || $extrafields->attributes[$this->table_element][
'type'][$name] !=
'separate') {
6100 $sql .=
" FROM ".$this->db->prefix().$table_element.
"_extrafields";
6101 $sql .=
" WHERE fk_object = ".((int) $rowid);
6104 $resql = $this->db->query($sql);
6106 $numrows = $this->db->num_rows($resql);
6108 $tab = $this->db->fetch_array($resql);
6110 foreach ($tab as $key => $value) {
6112 if ($key !=
'rowid' && $key !=
'tms' && $key !=
'fk_member' && !is_int($key)) {
6114 if (!empty($extrafields->attributes[$this->table_element]) && in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'date',
'datetime'))) {
6116 $this->array_options[
"options_".$key] = $this->db->jdate($value);
6118 $this->array_options[
"options_".$key] = $value;
6128 if (is_array($extrafields->attributes[$this->table_element][
'label'])) {
6129 foreach ($extrafields->attributes[$this->table_element][
'label'] as $key => $val) {
6130 if (!empty($extrafields->attributes[$this->table_element]) && !empty($extrafields->attributes[$this->table_element][
'computed'][$key])) {
6132 if (empty($conf->disable_compute)) {
6133 global $objectoffield;
6134 $objectoffield = $this;
6135 $this->array_options[
'options_' . $key] =
dol_eval($extrafields->attributes[$this->table_element][
'computed'][$key], 1, 0,
'');
6141 $this->db->free($resql);
6149 $this->errors[]=$this->db->lasterror;
6166 if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
6172 $table_element = $this->table_element;
6173 if ($table_element ==
'categorie') {
6174 $table_element =
'categories';
6177 dol_syslog(get_class($this).
"::deleteExtraFields delete", LOG_DEBUG);
6179 $sql_del =
"DELETE FROM ".$this->db->prefix().$table_element.
"_extrafields WHERE fk_object = ".((int) $this->
id);
6181 $resql = $this->db->query($sql_del);
6183 $this->error = $this->db->lasterror();
6184 $this->db->rollback();
6187 $this->db->commit();
6204 global $conf, $langs, $user;
6206 if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
6210 if (empty($userused)) {
6216 if (!empty($this->array_options)) {
6218 $langs->load(
'admin');
6219 require_once DOL_DOCUMENT_ROOT.
'/core/class/extrafields.class.php';
6221 $target_extrafields = $extrafields->fetch_name_optionals_label($this->table_element);
6224 $new_array_options = array();
6225 foreach ($this->array_options as $key => $value) {
6226 if (in_array(substr($key, 8), array_keys($target_extrafields))) {
6227 $new_array_options[$key] = $value;
6228 } elseif (in_array($key, array_keys($target_extrafields))) {
6229 $new_array_options[
'options_'.$key] = $value;
6233 foreach ($new_array_options as $key => $value) {
6234 $attributeKey = substr($key, 8);
6235 $attributeType = $extrafields->attributes[$this->table_element][
'type'][$attributeKey];
6236 $attributeLabel = $langs->transnoentities($extrafields->attributes[$this->table_element][
'label'][$attributeKey]);
6237 $attributeParam = $extrafields->attributes[$this->table_element][
'param'][$attributeKey];
6238 $attributeRequired = $extrafields->attributes[$this->table_element][
'required'][$attributeKey];
6239 $attributeUnique = $extrafields->attributes[$this->table_element][
'unique'][$attributeKey];
6240 $attrfieldcomputed = $extrafields->attributes[$this->table_element][
'computed'][$attributeKey];
6244 if (!empty($this->context[
'createfromclone']) && $this->context[
'createfromclone'] ==
'createfromclone' && !empty($attributeUnique)) {
6245 $new_array_options[$key] =
null;
6249 if ($attributeRequired) {
6250 $mandatorypb =
false;
6251 if ($attributeType ==
'link' && $this->array_options[$key] ==
'-1') {
6252 $mandatorypb =
true;
6254 if ($this->array_options[$key] ===
'') {
6255 $mandatorypb =
true;
6257 if ($attributeType ==
'sellist' && $this->array_options[$key] ==
'0') {
6258 $mandatorypb =
true;
6261 $langs->load(
"errors");
6262 dol_syslog(
"Mandatory field '".$key.
"' is empty during create and set to required into definition of extrafields");
6263 $this->errors[] = $langs->trans(
'ErrorFieldRequired', $attributeLabel);
6271 if (!empty($attrfieldcomputed)) {
6272 if (!empty($conf->global->MAIN_STORE_COMPUTED_EXTRAFIELDS)) {
6273 $value =
dol_eval($attrfieldcomputed, 1, 0,
'');
6274 dol_syslog($langs->trans(
"Extrafieldcomputed").
" sur ".$attributeLabel.
"(".$value.
")", LOG_DEBUG);
6275 $new_array_options[$key] = $value;
6277 $new_array_options[$key] =
null;
6281 switch ($attributeType) {
6283 if (!is_numeric($value) && $value !=
'') {
6284 $this->errors[] = $langs->trans(
"ExtraFieldHasWrongValue", $attributeLabel);
6286 } elseif ($value ==
'') {
6287 $new_array_options[$key] =
null;
6293 if (!is_numeric($value) && $value !=
'') {
6294 dol_syslog($langs->trans(
"ExtraFieldHasWrongValue").
" for ".$attributeLabel.
"(".$value.
"is not '".$attributeType.
"')", LOG_DEBUG);
6295 $this->errors[] = $langs->trans(
"ExtraFieldHasWrongValue", $attributeLabel);
6297 } elseif ($value ==
'') {
6301 $new_array_options[$key] = $value;
6311 if ($this->array_options[$key] !=
'' && is_array($extrafields->attributes[$this->table_element][
'param'][$attributeKey][
'options'])) {
6313 $tmparrays = array_keys($extrafields->attributes[$this->table_element][
'param'][$attributeKey][
'options']);
6314 $algo = reset($tmparrays);
6319 if (is_object($this->oldcopy)) {
6321 if (isset($this->oldcopy->array_options[$key]) && $this->array_options[$key] == $this->oldcopy->array_options[$key]) {
6322 $new_array_options[$key] = $this->array_options[$key];
6325 $newvalue =
dol_hash($this->array_options[$key], $algo);
6326 $new_array_options[$key] = $newvalue;
6329 $new_array_options[$key] = $this->array_options[$key];
6334 $new_array_options[$key] = $this->array_options[$key];
6340 if (!is_numeric($this->array_options[$key]) || $this->array_options[$key] != intval($this->array_options[$key])) {
6341 $this->array_options[$key] = strtotime($this->array_options[$key]);
6343 $new_array_options[$key] = $this->db->idate($this->array_options[$key]);
6347 if (!is_numeric($this->array_options[$key]) || $this->array_options[$key] != intval($this->array_options[$key])) {
6348 $this->array_options[$key] = strtotime($this->array_options[$key]);
6350 $new_array_options[$key] = $this->db->idate($this->array_options[$key],
'gmt');
6353 $param_list = array_keys($attributeParam[
'options']);
6356 $InfoFieldList = explode(
":", $param_list[0]);
6358 if ($InfoFieldList[0] && class_exists($InfoFieldList[0])) {
6359 if ($value ==
'-1') {
6360 $new_array_options[$key] =
'';
6362 $object =
new $InfoFieldList[0]($this->db);
6363 if (is_numeric($value)) {
6364 $res = $object->fetch($value);
6366 $res = $object->fetch(
'', $value);
6370 $new_array_options[$key] = $object->id;
6372 $this->error =
"Id/Ref '".$value.
"' for object '".$object->element.
"' not found";
6377 dol_syslog(
'Error bad setup of extrafield', LOG_WARNING);
6382 if (is_array($this->array_options[$key])) {
6383 $new_array_options[$key] = implode(
',', $this->array_options[$key]);
6385 $new_array_options[$key] = $this->array_options[$key];
6393 $table_element = $this->table_element;
6394 if ($table_element ==
'categorie') {
6395 $table_element =
'categories';
6398 dol_syslog(get_class($this).
"::insertExtraFields delete then insert", LOG_DEBUG);
6400 $sql_del =
"DELETE FROM ".$this->db->prefix().$table_element.
"_extrafields WHERE fk_object = ".((int) $this->
id);
6401 $this->db->query($sql_del);
6403 $sql =
"INSERT INTO ".$this->db->prefix().$table_element.
"_extrafields (fk_object";
6404 foreach ($new_array_options as $key => $value) {
6405 $attributeKey = substr($key, 8);
6407 if ($extrafields->attributes[$this->table_element][
'type'][$attributeKey] !=
'separate') {
6408 $sql .=
",".$attributeKey;
6412 if (!empty($extrafields->attributes[$this->table_element][
'mandatoryfieldsofotherentities']) && is_array($extrafields->attributes[$this->table_element][
'mandatoryfieldsofotherentities'])) {
6413 foreach ($extrafields->attributes[$this->table_element][
'mandatoryfieldsofotherentities'] as $tmpkey => $tmpval) {
6414 if (!isset($extrafields->attributes[$this->table_element][
'type'][$tmpkey])) {
6415 $sql .=
",".$tmpkey;
6419 $sql .=
") VALUES (".$this->id;
6421 foreach ($new_array_options as $key => $value) {
6422 $attributeKey = substr($key, 8);
6424 if ($extrafields->attributes[$this->table_element][
'type'][$attributeKey] !=
'separate') {
6425 if ($new_array_options[$key] !=
'' || $new_array_options[$key] ==
'0') {
6426 $sql .=
",'".$this->db->escape($new_array_options[$key]).
"'";
6433 if (!empty($extrafields->attributes[$this->table_element][
'mandatoryfieldsofotherentities']) && is_array($extrafields->attributes[$this->table_element][
'mandatoryfieldsofotherentities'])) {
6434 foreach ($extrafields->attributes[$this->table_element][
'mandatoryfieldsofotherentities'] as $tmpkey => $tmpval) {
6435 if (!isset($extrafields->attributes[$this->table_element][
'type'][$tmpkey])) {
6436 if (in_array($tmpval, array(
'int',
'double',
'price'))) {
6447 $resql = $this->db->query($sql);
6449 $this->error = $this->db->lasterror();
6453 if (!$error && $trigger) {
6455 $this->context = array(
'extrafieldaddupdate'=>1);
6456 $result = $this->call_trigger($trigger, $userused);
6464 $this->db->rollback();
6467 $this->db->commit();
6487 global $conf, $langs, $user;
6489 if (empty($userused)) {
6495 if (!empty($conf->global->MAIN_EXTRALANGUAGES_DISABLED)) {
6499 if (is_array($this->array_languages)) {
6500 $new_array_languages = $this->array_languages;
6502 foreach ($new_array_languages as $key => $value) {
6503 $attributeKey = $key;
6504 $attributeType = $this->fields[$attributeKey][
'type'];
6505 $attributeLabel = $this->fields[$attributeKey][
'label'];
6510 switch ($attributeType) {
6512 if (!is_numeric($value) && $value !=
'') {
6513 $this->errors[] = $langs->trans(
"ExtraLanguageHasWrongValue", $attributeLabel);
6515 } elseif ($value ==
'') {
6516 $new_array_languages[$key] =
null;
6521 if (!is_numeric($value) && $value !=
'') {
6522 dol_syslog($langs->trans(
"ExtraLanguageHasWrongValue").
" sur ".$attributeLabel.
"(".$value.
"is not '".$attributeType.
"')", LOG_DEBUG);
6523 $this->errors[] = $langs->trans(
"ExtraLanguageHasWrongValue", $attributeLabel);
6525 } elseif ($value ==
'') {
6526 $new_array_languages[$key] =
null;
6528 $new_array_languages[$key] = $value;
6542 $table_element = $this->table_element;
6543 if ($table_element ==
'categorie') {
6544 $table_element =
'categories';
6547 dol_syslog(get_class($this).
"::insertExtraLanguages delete then insert", LOG_DEBUG);
6549 foreach ($new_array_languages as $key => $langcodearray) {
6550 foreach ($langcodearray as $langcode => $value) {
6551 $sql_del =
"DELETE FROM ".$this->db->prefix().
"object_lang";
6552 $sql_del .=
" WHERE fk_object = ".((int) $this->
id).
" AND property = '".$this->db->escape($key).
"' AND type_object = '".$this->db->escape($table_element).
"'";
6553 $sql_del .=
" AND lang = '".$this->db->escape($langcode).
"'";
6554 $this->db->query($sql_del);
6556 if ($value !==
'') {
6557 $sql =
"INSERT INTO ".$this->db->prefix().
"object_lang (fk_object, property, type_object, lang, value";
6558 $sql .=
") VALUES (".$this->id.
", '".$this->db->escape($key).
"', '".$this->db->escape($table_element).
"', '".$this->db->escape($langcode).
"', '".$this->db->escape($value).
"'";
6561 $resql = $this->db->query($sql);
6563 $this->error = $this->db->lasterror();
6571 if (!$error && $trigger) {
6573 $this->context = array(
'extralanguagesaddupdate'=>1);
6574 $result = $this->call_trigger($trigger, $userused);
6582 $this->db->rollback();
6585 $this->db->commit();
6605 global $conf, $langs, $user;
6607 if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
6611 if (empty($userused)) {
6617 if (!empty($this->array_options) && isset($this->array_options[
"options_".$key])) {
6619 $langs->load(
'admin');
6620 require_once DOL_DOCUMENT_ROOT.
'/core/class/extrafields.class.php';
6622 $extrafields->fetch_name_optionals_label($this->table_element);
6624 $value = $this->array_options[
"options_".$key];
6626 $attributeType = $extrafields->attributes[$this->table_element][
'type'][$key];
6627 $attributeLabel = $extrafields->attributes[$this->table_element][
'label'][$key];
6628 $attributeParam = $extrafields->attributes[$this->table_element][
'param'][$key];
6629 $attributeRequired = $extrafields->attributes[$this->table_element][
'required'][$key];
6630 $attrfieldcomputed = $extrafields->attributes[$this->table_element][
'computed'][$key];
6633 if ($attributeRequired) {
6634 $mandatorypb =
false;
6635 if ($attributeType ==
'link' && $this->array_options[
"options_".$key] ==
'-1') {
6636 $mandatorypb =
true;
6638 if ($this->array_options[
"options_".$key] ===
'') {
6639 $mandatorypb =
true;
6642 $langs->load(
"errors");
6643 dol_syslog(
"Mandatory field 'options_".$key.
"' is empty during update and set to required into definition of extrafields");
6644 $this->errors[] = $langs->trans(
'ErrorFieldRequired', $attributeLabel);
6652 if (!empty($attrfieldcomputed)) {
6653 if (!empty($conf->global->MAIN_STORE_COMPUTED_EXTRAFIELDS)) {
6654 $value =
dol_eval($attrfieldcomputed, 1, 0,
'');
6655 dol_syslog($langs->trans(
"Extrafieldcomputed").
" sur ".$attributeLabel.
"(".$value.
")", LOG_DEBUG);
6656 $this->array_options[
"options_".$key] = $value;
6658 $this->array_options[
"options_".$key] =
null;
6662 switch ($attributeType) {
6664 if (!is_numeric($value) && $value !=
'') {
6665 $this->errors[] = $langs->trans(
"ExtraFieldHasWrongValue", $attributeLabel);
6667 } elseif ($value ===
'') {
6668 $this->array_options[
"options_".$key] =
null;
6674 if (!is_numeric($value) && $value !=
'') {
6675 dol_syslog($langs->trans(
"ExtraFieldHasWrongValue").
" sur ".$attributeLabel.
"(".$value.
"is not '".$attributeType.
"')", LOG_DEBUG);
6676 $this->errors[] = $langs->trans(
"ExtraFieldHasWrongValue", $attributeLabel);
6678 } elseif ($value ===
'') {
6682 $this->array_options[
"options_".$key] = $value;
6692 if (empty($this->array_options[
"options_".$key])) {
6693 $this->array_options[
"options_".$key] =
null;
6695 $this->array_options[
"options_".$key] = $this->db->idate($this->array_options[
"options_".$key]);
6699 if (empty($this->array_options[
"options_".$key])) {
6700 $this->array_options[
"options_".$key] =
null;
6702 $this->array_options[
"options_".$key] = $this->db->idate($this->array_options[
"options_".$key],
'gmt');
6706 if (empty($this->array_options[
"options_".$key])) {
6707 $this->array_options[
"options_".$key] =
null;
6711 if ($this->array_options[
"options_".$key] ===
'') {
6712 $this->array_options[
"options_".$key] =
null;
6746 if (is_array($this->array_options[$key])) {
6747 $new_array_options[$key] = implode(
',', $this->array_options[$key]);
6749 $new_array_options[$key] = $this->array_options[$key];
6756 $linealreadyfound = 0;
6759 $sql =
"SELECT COUNT(rowid) as nb FROM ".$this->db->prefix().$this->table_element.
"_extrafields WHERE fk_object = ".((int) $this->
id);
6760 $resql = $this->db->query($sql);
6762 $tmpobj = $this->db->fetch_object($resql);
6764 $linealreadyfound = $tmpobj->nb;
6768 if ($linealreadyfound) {
6769 if ($this->array_options[
"options_".$key] ===
null) {
6770 $sql =
"UPDATE ".$this->db->prefix().$this->table_element.
"_extrafields SET ".$key.
" = null";
6772 $sql =
"UPDATE ".$this->db->prefix().$this->table_element.
"_extrafields SET ".$key.
" = '".$this->db->escape($this->array_options[
"options_".$key]).
"'";
6774 $sql .=
" WHERE fk_object = ".((int) $this->
id);
6776 $result = $this->insertExtraFields(
'', $user);
6782 $resql = $this->db->query($sql);
6785 $this->error = $this->db->lasterror();
6787 if (!$error && $trigger) {
6789 $this->context = array(
'extrafieldupdate'=>1);
6790 $result = $this->call_trigger($trigger, $userused);
6798 dol_syslog(__METHOD__.$this->error, LOG_ERR);
6799 $this->db->rollback();
6802 $this->db->commit();
6822 global $conf, $langs, $user;
6824 if (empty($userused)) {
6830 if (!empty($conf->global->MAIN_EXTRALANGUAGES_DISABLED)) {
6852 public function showInputField($val, $key, $value, $moreparam =
'', $keysuffix =
'', $keyprefix =
'', $morecss = 0, $nonewbutton = 0)
6854 global $conf, $langs, $form;
6856 if (!is_object($form)) {
6857 require_once DOL_DOCUMENT_ROOT.
'/core/class/html.form.class.php';
6858 $form =
new Form($this->db);
6861 if (!empty($this->fields)) {
6862 $val = $this->fields[$key];
6866 $fieldValidationErrorMsg =
'';
6867 $validationClass =
'';
6868 $fieldValidationErrorMsg = $this->getFieldError($key);
6869 if (!empty($fieldValidationErrorMsg)) {
6870 $validationClass =
' --error';
6872 $validationClass =
' --success';
6879 $param[
'options'] = array();
6881 $size = !empty($this->fields[$key][
'size']) ? $this->fields[$key][
'size'] : 0;
6883 if (preg_match(
'/^(integer|link):(.*):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
6884 $param[
'options'] = array($reg[2].
':'.$reg[3].
':'.$reg[4].
':'.$reg[5] =>
'N');
6886 } elseif (preg_match(
'/^(integer|link):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
6887 $param[
'options'] = array($reg[2].
':'.$reg[3].
':'.$reg[4] =>
'N');
6889 } elseif (preg_match(
'/^(integer|link):(.*):(.*)/i', $val[
'type'], $reg)) {
6890 $param[
'options'] = array($reg[2].
':'.$reg[3] =>
'N');
6892 } elseif (preg_match(
'/^(sellist):(.*):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
6893 $param[
'options'] = array($reg[2].
':'.$reg[3].
':'.$reg[4].
':'.$reg[5] =>
'N');
6895 } elseif (preg_match(
'/^(sellist):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
6896 $param[
'options'] = array($reg[2].
':'.$reg[3].
':'.$reg[4] =>
'N');
6898 } elseif (preg_match(
'/^(sellist):(.*):(.*)/i', $val[
'type'], $reg)) {
6899 $param[
'options'] = array($reg[2].
':'.$reg[3] =>
'N');
6901 } elseif (preg_match(
'/^chkbxlst:(.*)/i', $val[
'type'], $reg)) {
6902 $param[
'options'] = array($reg[1] =>
'N');
6904 } elseif (preg_match(
'/varchar\((\d+)\)/', $val[
'type'], $reg)) {
6905 $param[
'options'] = array();
6908 } elseif (preg_match(
'/varchar/', $val[
'type'])) {
6909 $param[
'options'] = array();
6912 $param[
'options'] = array();
6913 $type = $this->fields[$key][
'type'];
6917 if (!empty($this->fields[$key][
'arrayofkeyval']) && is_array($this->fields[$key][
'arrayofkeyval'])) {
6918 $param[
'options'] = $this->fields[$key][
'arrayofkeyval'];
6922 $label = $this->fields[$key][
'label'];
6924 $default = (!empty($this->fields[$key][
'default']) ? $this->fields[$key][
'default'] :
'');
6925 $computed = (!empty($this->fields[$key][
'computed']) ? $this->fields[$key][
'computed'] :
'');
6926 $unique = (!empty($this->fields[$key][
'unique']) ? $this->fields[$key][
'unique'] : 0);
6927 $required = (!empty($this->fields[$key][
'required']) ? $this->fields[$key][
'required'] : 0);
6928 $autofocusoncreate = (!empty($this->fields[$key][
'autofocusoncreate']) ? $this->fields[$key][
'autofocusoncreate'] : 0);
6930 $langfile = (!empty($this->fields[$key][
'langfile']) ? $this->fields[$key][
'langfile'] :
'');
6931 $list = (!empty($this->fields[$key][
'list']) ? $this->fields[$key][
'list'] : 0);
6932 $hidden = (in_array(abs($this->fields[$key][
'visible']), array(0, 2)) ? 1 : 0);
6934 $objectid = $this->id;
6937 if (!preg_match(
'/^search_/', $keyprefix)) {
6938 return '<span class="opacitymedium">'.$langs->trans(
"AutomaticallyCalculated").
'</span>';
6945 if (empty($morecss) && !empty($val[
'css'])) {
6946 $morecss = $val[
'css'];
6947 } elseif (empty($morecss)) {
6948 if ($type ==
'date') {
6949 $morecss =
'minwidth100imp';
6950 } elseif ($type ==
'datetime' || $type ==
'link') {
6951 $morecss =
'minwidth200imp';
6952 } elseif (in_array($type, array(
'int',
'integer',
'price')) || preg_match(
'/^double(\([0-9],[0-9]\)){0,1}/', $type)) {
6953 $morecss =
'maxwidth75';
6954 } elseif ($type ==
'url') {
6955 $morecss =
'minwidth400';
6956 } elseif ($type ==
'boolean') {
6959 if (round($size) < 12) {
6960 $morecss =
'minwidth100';
6961 } elseif (round($size) <= 48) {
6962 $morecss =
'minwidth200';
6964 $morecss =
'minwidth400';
6970 if (!empty($validationClass)) {
6971 $morecss.= $validationClass;
6974 if (in_array($type, array(
'date'))) {
6975 $tmp = explode(
',', $size);
6980 if (!$required && $value ==
'') {
6985 $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required,
'', 1, (($keyprefix !=
'search_' && $keyprefix !=
'search_options_') ? 1 : 0), 0, 1);
6986 } elseif (in_array($type, array(
'datetime'))) {
6987 $tmp = explode(
',', $size);
6992 if (!$required && $value ==
'') $value =
'-1';
6995 $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required,
'', 1, (($keyprefix !=
'search_' && $keyprefix !=
'search_options_') ? 1 : 0), 0, 1,
'',
'',
'', 1,
'',
'',
'tzuserrel');
6996 } elseif (in_array($type, array(
'duration'))) {
6997 $out = $form->select_duration($keyprefix.$key.$keysuffix, $value, 0,
'text', 0, 1);
6998 } elseif (in_array($type, array(
'int',
'integer'))) {
6999 $tmp = explode(
',', $size);
7001 $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' :
'').
'>';
7002 } elseif (in_array($type, array(
'real'))) {
7003 $out =
'<input type="text" class="flat '.$morecss.
'" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.
dol_escape_htmltag($value).
'"'.($moreparam ? $moreparam :
'').($autofocusoncreate ?
' autofocus' :
'').
'>';
7004 } elseif (preg_match(
'/varchar/', $type)) {
7005 $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' :
'').
'>';
7006 } elseif (in_array($type, array(
'email',
'mail',
'phone',
'url',
'ip'))) {
7007 $out =
'<input type="text" class="flat '.$morecss.
'" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.
dol_escape_htmltag($value).
'" '.($moreparam ? $moreparam :
'').($autofocusoncreate ?
' autofocus' :
'').
'>';
7008 } elseif (preg_match(
'/^text/', $type)) {
7009 if (!preg_match(
'/search_/', $keyprefix)) {
7010 require_once DOL_DOCUMENT_ROOT.
'/core/class/doleditor.class.php';
7011 $doleditor =
new DolEditor($keyprefix.$key.$keysuffix, $value,
'', 200,
'dolibarr_notes',
'In',
false,
false,
false, ROWS_5,
'90%');
7012 $out = $doleditor->Create(1);
7014 $out =
'<input type="text" class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.
dol_escape_htmltag($value).
'" '.($moreparam ? $moreparam :
'').
'>';
7016 } elseif (preg_match(
'/^html/', $type)) {
7017 if (!preg_match(
'/search_/', $keyprefix)) {
7018 require_once DOL_DOCUMENT_ROOT.
'/core/class/doleditor.class.php';
7019 $doleditor =
new DolEditor($keyprefix.$key.$keysuffix, $value,
'', 200,
'dolibarr_notes',
'In',
false,
false, isModEnabled(
'fckeditor') && $conf->global->FCKEDITOR_ENABLE_SOCIETE, ROWS_5,
'90%');
7020 $out = $doleditor->Create(1,
'',
true,
'',
'', $moreparam, $morecss);
7022 $out =
'<input type="text" class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.
dol_escape_htmltag($value).
'" '.($moreparam ? $moreparam :
'').
'>';
7024 } elseif ($type ==
'boolean') {
7026 if (!empty($value)) {
7027 $checked =
' checked value="1" ';
7029 $checked =
' value="1" ';
7031 $out =
'<input type="checkbox" class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" '.$checked.
' '.($moreparam ? $moreparam :
'').
'>';
7032 } elseif ($type ==
'price') {
7033 if (!empty($value)) {
7034 $value =
price($value);
7036 $out =
'<input type="text" class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.$value.
'" '.($moreparam ? $moreparam :
'').
'> '.$langs->getCurrencySymbol($conf->currency);
7037 } elseif (preg_match(
'/^double(\([0-9],[0-9]\)){0,1}/', $type)) {
7038 if (!empty($value)) {
7039 $value =
price($value);
7041 $out =
'<input type="text" class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.$value.
'" '.($moreparam ? $moreparam :
'').
'> ';
7042 } elseif ($type ==
'select') {
7044 if (!empty($conf->use_javascript_ajax) && empty($conf->global->MAIN_EXTRAFIELDS_DISABLE_SELECT2)) {
7045 include_once DOL_DOCUMENT_ROOT.
'/core/lib/ajax.lib.php';
7046 $out .=
ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
7049 $out .=
'<select class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" '.($moreparam ? $moreparam :
'').
'>';
7050 if ((!isset($this->fields[$key][
'default'])) || empty($this->fields[$key][
'notnull']) || ($this->fields[$key][
'notnull'] != 1)) {
7051 $out .=
'<option value="0"> </option>';
7053 foreach ($param[
'options'] as $keyb => $valb) {
7054 if ((
string) $keyb ==
'') {
7057 if (strpos($valb,
"|") !==
false) {
7058 list($valb, $parent) = explode(
'|', $valb);
7060 $out .=
'<option value="'.$keyb.
'"';
7061 $out .= (((string) $value == (
string) $keyb) ?
' selected' :
'');
7062 $out .= (!empty($parent) ?
' parent="'.$parent.
'"' :
'');
7063 $out .=
'>'.$valb.
'</option>';
7065 $out .=
'</select>';
7066 } elseif ($type ==
'sellist') {
7068 if (!empty($conf->use_javascript_ajax) && empty($conf->global->MAIN_EXTRAFIELDS_DISABLE_SELECT2)) {
7069 include_once DOL_DOCUMENT_ROOT.
'/core/lib/ajax.lib.php';
7070 $out .=
ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
7073 $out .=
'<select class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" '.($moreparam ? $moreparam :
'').
'>';
7074 if (is_array($param[
'options'])) {
7075 $param_list = array_keys($param[
'options']);
7076 $InfoFieldList = explode(
":", $param_list[0]);
7086 $keyList = (empty($InfoFieldList[2]) ?
'rowid' : $InfoFieldList[2].
' as rowid');
7088 if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
7089 if (strpos($InfoFieldList[4],
'extra.') !==
false) {
7090 $keyList =
'main.'.$InfoFieldList[2].
' as rowid';
7092 $keyList = $InfoFieldList[2].
' as rowid';
7095 if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
7096 list($parentName, $parentField) = explode(
'|', $InfoFieldList[3]);
7097 $keyList .=
', '.$parentField;
7100 $filter_categorie =
false;
7101 if (count($InfoFieldList) > 5) {
7102 if ($InfoFieldList[0] ==
'categorie') {
7103 $filter_categorie =
true;
7107 if ($filter_categorie ===
false) {
7108 $fields_label = explode(
'|', $InfoFieldList[1]);
7109 if (is_array($fields_label)) {
7111 $keyList .= implode(
', ', $fields_label);
7115 $sql =
"SELECT " . $keyList;
7116 $sql .=
" FROM " . $this->db->prefix() . $InfoFieldList[0];
7117 if (!empty($InfoFieldList[4])) {
7119 if (strpos($InfoFieldList[4],
'$SEL$') !==
false) {
7120 $InfoFieldList[4] = str_replace(
'$SEL$',
'SELECT', $InfoFieldList[4]);
7124 if (strpos($InfoFieldList[4],
'$ID$') !==
false && !empty($objectid)) {
7125 $InfoFieldList[4] = str_replace(
'$ID$', $objectid, $InfoFieldList[4]);
7127 $InfoFieldList[4] = str_replace(
'$ID$',
'0', $InfoFieldList[4]);
7131 if (strpos($InfoFieldList[4],
'extra') !==
false) {
7132 $sql .=
" as main, " . $this->db->prefix() . $InfoFieldList[0] .
"_extrafields as extra";
7133 $sqlwhere .=
" WHERE extra.fk_object=main." . $InfoFieldList[2] .
" AND " . $InfoFieldList[4];
7135 $sqlwhere .=
" WHERE " . $InfoFieldList[4];
7138 $sqlwhere .=
' WHERE 1=1';
7141 if (in_array($InfoFieldList[0], array(
'tablewithentity'))) {
7142 $sqlwhere .=
" AND entity = " . ((int) $conf->entity);
7147 $sql .=
' ORDER BY ' . implode(
', ', $fields_label);
7149 dol_syslog(get_class($this) .
'::showInputField type=sellist', LOG_DEBUG);
7150 $resql = $this->db->query($sql);
7152 $out .=
'<option value="0"> </option>';
7153 $num = $this->db->num_rows($resql);
7157 $obj = $this->db->fetch_object($resql);
7161 $fields_label = explode(
'|', $InfoFieldList[1]);
7162 if (count($fields_label) > 1) {
7164 foreach ($fields_label as $field_toshow) {
7165 $labeltoshow .= $obj->$field_toshow .
' ';
7168 $labeltoshow = $obj->{$InfoFieldList[1]};
7170 $labeltoshow =
dol_trunc($labeltoshow, 45);
7172 if ($value == $obj->rowid) {
7173 foreach ($fields_label as $field_toshow) {
7174 $translabel = $langs->trans($obj->$field_toshow);
7175 if ($translabel != $obj->$field_toshow) {
7176 $labeltoshow =
dol_trunc($translabel) .
' ';
7178 $labeltoshow =
dol_trunc($obj->$field_toshow) .
' ';
7181 $out .=
'<option value="' . $obj->rowid .
'" selected>' . $labeltoshow .
'</option>';
7184 $translabel = $langs->trans($obj->{$InfoFieldList[1]});
7185 if ($translabel != $obj->{$InfoFieldList[1]}) {
7186 $labeltoshow =
dol_trunc($translabel, 18);
7188 $labeltoshow =
dol_trunc($obj->{$InfoFieldList[1]});
7191 if (empty($labeltoshow)) {
7192 $labeltoshow =
'(not defined)';
7194 if ($value == $obj->rowid) {
7195 $out .=
'<option value="' . $obj->rowid .
'" selected>' . $labeltoshow .
'</option>';
7198 if (!empty($InfoFieldList[3]) && $parentField) {
7199 $parent = $parentName .
':' . $obj->{$parentField};
7203 $out .=
'<option value="' . $obj->rowid .
'"';
7204 $out .= ($value == $obj->rowid ?
' selected' :
'');
7205 $out .= (!empty($parent) ?
' parent="' . $parent .
'"' :
'');
7206 $out .=
'>' . $labeltoshow .
'</option>';
7211 $this->db->free($resql);
7213 print
'Error in request ' . $sql .
' ' . $this->db->lasterror() .
'. Check setup of extra parameters.<br>';
7216 require_once DOL_DOCUMENT_ROOT.
'/categories/class/categorie.class.php';
7217 $data = $form->select_all_categories(Categorie::$MAP_ID_TO_CODE[$InfoFieldList[5]],
'',
'parent', 64, $InfoFieldList[6], 1, 1);
7218 $out .=
'<option value="0"> </option>';
7219 foreach ($data as $data_key => $data_value) {
7220 $out .=
'<option value="' . $data_key .
'"';
7221 $out .= ($value == $data_key ?
' selected' :
'');
7222 $out .=
'>' . $data_value .
'</option>';
7226 $out .=
'</select>';
7227 } elseif ($type ==
'checkbox') {
7228 $value_arr = explode(
',', $value);
7229 $out = $form->multiselectarray($keyprefix.$key.$keysuffix, (empty($param[
'options']) ?
null:$param[
'options']), $value_arr,
'', 0, $morecss, 0,
'100%');
7230 } elseif ($type ==
'radio') {
7232 foreach ($param[
'options'] as $keyopt => $valopt) {
7233 $out .=
'<input class="flat '.$morecss.
'" type="radio" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" '.($moreparam ? $moreparam :
'');
7234 $out .=
' value="'.$keyopt.
'"';
7235 $out .=
' id="'.$keyprefix.$key.$keysuffix.
'_'.$keyopt.
'"';
7236 $out .= ($value == $keyopt ?
'checked' :
'');
7237 $out .=
'/><label for="'.$keyprefix.$key.$keysuffix.
'_'.$keyopt.
'">'.$valopt.
'</label><br>';
7239 } elseif ($type ==
'chkbxlst') {
7240 if (is_array($value)) {
7241 $value_arr = $value;
7243 $value_arr = explode(
',', $value);
7246 if (is_array($param[
'options'])) {
7247 $param_list = array_keys($param[
'options']);
7248 $InfoFieldList = explode(
":", $param_list[0]);
7258 $keyList = (empty($InfoFieldList[2]) ?
'rowid' : $InfoFieldList[2].
' as rowid');
7260 if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
7261 list ($parentName, $parentField) = explode(
'|', $InfoFieldList[3]);
7262 $keyList .=
', '.$parentField;
7264 if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
7265 if (strpos($InfoFieldList[4],
'extra.') !==
false) {
7266 $keyList =
'main.'.$InfoFieldList[2].
' as rowid';
7268 $keyList = $InfoFieldList[2].
' as rowid';
7272 $filter_categorie =
false;
7273 if (count($InfoFieldList) > 5) {
7274 if ($InfoFieldList[0] ==
'categorie') {
7275 $filter_categorie =
true;
7279 if ($filter_categorie ===
false) {
7280 $fields_label = explode(
'|', $InfoFieldList[1]);
7281 if (is_array($fields_label)) {
7283 $keyList .= implode(
', ', $fields_label);
7287 $sql =
"SELECT " . $keyList;
7288 $sql .=
' FROM ' . $this->db->prefix() . $InfoFieldList[0];
7289 if (!empty($InfoFieldList[4])) {
7291 if (strpos($InfoFieldList[4],
'$SEL$') !==
false) {
7292 $InfoFieldList[4] = str_replace(
'$SEL$',
'SELECT', $InfoFieldList[4]);
7296 if (strpos($InfoFieldList[4],
'$ID$') !==
false && !empty($objectid)) {
7297 $InfoFieldList[4] = str_replace(
'$ID$', $objectid, $InfoFieldList[4]);
7299 $InfoFieldList[4] = str_replace(
'$ID$',
'0', $InfoFieldList[4]);
7303 if (strpos($InfoFieldList[4],
'extra') !==
false) {
7304 $sql .=
' as main, ' . $this->db->prefix() . $InfoFieldList[0] .
'_extrafields as extra';
7305 $sqlwhere .=
" WHERE extra.fk_object=main." . $InfoFieldList[2] .
" AND " . $InfoFieldList[4];
7307 $sqlwhere .=
" WHERE " . $InfoFieldList[4];
7310 $sqlwhere .=
' WHERE 1=1';
7313 if (in_array($InfoFieldList[0], array(
'tablewithentity'))) {
7314 $sqlwhere .=
" AND entity = " . ((int) $conf->entity);
7320 dol_syslog(get_class($this) .
'::showInputField type=chkbxlst', LOG_DEBUG);
7321 $resql = $this->db->query($sql);
7323 $num = $this->db->num_rows($resql);
7330 $obj = $this->db->fetch_object($resql);
7334 $fields_label = explode(
'|', $InfoFieldList[1]);
7335 if (count($fields_label) > 1) {
7337 foreach ($fields_label as $field_toshow) {
7338 $labeltoshow .= $obj->$field_toshow .
' ';
7341 $labeltoshow = $obj->{$InfoFieldList[1]};
7343 $labeltoshow =
dol_trunc($labeltoshow, 45);
7345 if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
7346 foreach ($fields_label as $field_toshow) {
7347 $translabel = $langs->trans($obj->$field_toshow);
7348 if ($translabel != $obj->$field_toshow) {
7349 $labeltoshow =
dol_trunc($translabel, 18) .
' ';
7351 $labeltoshow =
dol_trunc($obj->$field_toshow, 18) .
' ';
7355 $data[$obj->rowid] = $labeltoshow;
7358 $translabel = $langs->trans($obj->{$InfoFieldList[1]});
7359 if ($translabel != $obj->{$InfoFieldList[1]}) {
7360 $labeltoshow =
dol_trunc($translabel, 18);
7362 $labeltoshow =
dol_trunc($obj->{$InfoFieldList[1]}, 18);
7365 if (empty($labeltoshow)) {
7366 $labeltoshow =
'(not defined)';
7369 if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
7370 $data[$obj->rowid] = $labeltoshow;
7373 if (!empty($InfoFieldList[3]) && $parentField) {
7374 $parent = $parentName .
':' . $obj->{$parentField};
7378 $data[$obj->rowid] = $labeltoshow;
7383 $this->db->free($resql);
7385 $out = $form->multiselectarray($keyprefix . $key . $keysuffix, $data, $value_arr,
'', 0, $morecss, 0,
'100%');
7387 print
'Error in request ' . $sql .
' ' . $this->db->lasterror() .
'. Check setup of extra parameters.<br>';
7390 require_once DOL_DOCUMENT_ROOT.
'/categories/class/categorie.class.php';
7391 $data = $form->select_all_categories(Categorie::$MAP_ID_TO_CODE[$InfoFieldList[5]],
'',
'parent', 64, $InfoFieldList[6], 1, 1);
7392 $out = $form->multiselectarray($keyprefix . $key . $keysuffix, $data, $value_arr,
'', 0, $morecss, 0,
'100%');
7395 } elseif ($type ==
'link') {
7396 $param_list = array_keys($param[
'options']);
7397 $param_list_array = explode(
':', $param_list[0]);
7398 $showempty = (($required && $default !=
'') ? 0 : 1);
7400 if (!preg_match(
'/search_/', $keyprefix)) {
7401 if (!empty($param_list_array[2])) {
7402 if (!empty($this->fields[$key][
'picto'])) {
7403 $morecss .=
' widthcentpercentminusxx';
7405 $morecss .=
' widthcentpercentminusx';
7408 if (!empty($this->fields[$key][
'picto'])) {
7409 $morecss .=
' widthcentpercentminusx';
7414 $out = $form->selectForForms($param_list[0], $keyprefix.$key.$keysuffix, $value, $showempty,
'',
'', $morecss, $moreparam, 0, empty($val[
'disabled']) ? 0 : 1);
7416 if (!empty($param_list_array[2])) {
7417 if ((!GETPOSTISSET(
'backtopage') || strpos(
GETPOST(
'backtopage'), $_SERVER[
'PHP_SELF']) === 0)
7418 && empty($val[
'disabled']) && empty($nonewbutton)) {
7419 list($class, $classfile) = explode(
':', $param_list[0]);
7420 if (file_exists(
dol_buildpath(dirname(dirname($classfile)).
'/card.php'))) {
7421 $url_path =
dol_buildpath(dirname(dirname($classfile)).
'/card.php', 1);
7423 $url_path =
dol_buildpath(dirname(dirname($classfile)).
'/'.strtolower($class).
'_card.php', 1);
7425 $paramforthenewlink =
'';
7426 $paramforthenewlink .= (GETPOSTISSET(
'action') ?
'&action='.GETPOST(
'action',
'aZ09') :
'');
7427 $paramforthenewlink .= (GETPOSTISSET(
'id') ?
'&id='.GETPOST(
'id',
'int') :
'');
7428 $paramforthenewlink .= (GETPOSTISSET(
'origin') ?
'&origin='.GETPOST(
'origin',
'aZ09') :
'');
7429 $paramforthenewlink .= (GETPOSTISSET(
'originid') ?
'&originid='.GETPOST(
'originid',
'int') :
'');
7430 $paramforthenewlink .=
'&fk_'.strtolower($class).
'=--IDFORBACKTOPAGE--';
7432 $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>';
7435 } elseif ($type ==
'password') {
7437 $out =
'<input type="'.($keyprefix ==
'search_' ?
'text' :
'password').
'" class="flat '.$morecss.
'" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.$value.
'" '.($moreparam ? $moreparam :
'').
'>';
7438 } elseif ($type ==
'array') {
7440 $newval[
'type'] =
'varchar(256)';
7443 if (!empty($value)) {
7444 foreach ($value as $option) {
7445 $out .=
'<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).
'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
7446 $out .= $this->showInputField($newval, $keyprefix.$key.$keysuffix.
'[]', $option, $moreparam,
'',
'', $morecss).
'<br></span>';
7449 $out .=
'<a id="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).
'_add" href="javascript:;"><span class="fa fa-plus-circle valignmiddle"></span></a>';
7451 $newInput =
'<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).
'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
7452 $newInput .= $this->showInputField($newval, $keyprefix.$key.$keysuffix.
'[]',
'', $moreparam,
'',
'', $morecss).
'<br></span>';
7454 if (!empty($conf->use_javascript_ajax)) {
7456 <script nonce="'.getNonce().
'">
7457 $(document).ready(function() {
7458 $("a#'.
dol_escape_js($keyprefix.$key.$keysuffix).
'_add").click(function() {
7462 $(document).on("click", "a.'.
dol_escape_js($keyprefix.$key.$keysuffix).
'_del", function() {
7463 $(this).parent().remove();
7469 if (!empty($hidden)) {
7470 $out =
'<input type="hidden" value="'.$value.
'" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'"/>';
7473 if ($isDependList==1) {
7474 $out .= $this->getJSListDependancies(
'_common');
7482 if (!empty($fieldValidationErrorMsg) && function_exists(
'getFieldErrorIcon')) {
7483 $out .=
' '.getFieldErrorIcon($fieldValidationErrorMsg);
7502 public function showOutputField($val, $key, $value, $moreparam =
'', $keysuffix =
'', $keyprefix =
'', $morecss =
'')
7504 global $conf, $langs, $form;
7506 if (!is_object($form)) {
7507 require_once DOL_DOCUMENT_ROOT.
'/core/class/html.form.class.php';
7508 $form =
new Form($this->db);
7511 $label = empty($val[
'label']) ?
'' : $val[
'label'];
7512 $type = empty($val[
'type']) ?
'' : $val[
'type'];
7513 $size = empty($val[
'css']) ?
'' : $val[
'css'];
7517 if (preg_match(
'/varchar\((\d+)\)/', $type, $reg)) {
7520 } elseif (preg_match(
'/varchar/', $type)) {
7523 if (!empty($val[
'arrayofkeyval']) && is_array($val[
'arrayofkeyval'])) {
7526 if (preg_match(
'/^integer:(.*):(.*)/i', $val[
'type'], $reg)) {
7530 $default = empty($val[
'default']) ?
'' : $val[
'default'];
7531 $computed = empty($val[
'computed']) ?
'' : $val[
'computed'];
7532 $unique = empty($val[
'unique']) ?
'' : $val[
'unique'];
7533 $required = empty($val[
'required']) ?
'' : $val[
'required'];
7535 $param[
'options'] = array();
7537 if (!empty($val[
'arrayofkeyval']) && is_array($val[
'arrayofkeyval'])) {
7538 $param[
'options'] = $val[
'arrayofkeyval'];
7540 if (preg_match(
'/^integer:(.*):(.*)/i', $val[
'type'], $reg)) {
7542 $stringforoptions = $reg[1].
':'.$reg[2];
7543 if ($reg[1] ==
'User') {
7544 $stringforoptions .=
':-1';
7546 $param[
'options'] = array($stringforoptions => $stringforoptions);
7547 } elseif (preg_match(
'/^sellist:(.*):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
7548 $param[
'options'] = array($reg[1].
':'.$reg[2].
':'.$reg[3].
':'.$reg[4] =>
'N');
7550 } elseif (preg_match(
'/^sellist:(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
7551 $param[
'options'] = array($reg[1].
':'.$reg[2].
':'.$reg[3] =>
'N');
7553 } elseif (preg_match(
'/^sellist:(.*):(.*)/i', $val[
'type'], $reg)) {
7554 $param[
'options'] = array($reg[1].
':'.$reg[2] =>
'N');
7556 } elseif (preg_match(
'/^chkbxlst:(.*)/i', $val[
'type'], $reg)) {
7557 $param[
'options'] = array($reg[1] =>
'N');
7561 $langfile = empty($val[
'langfile']) ?
'' : $val[
'langfile'];
7562 $list = (empty($val[
'list']) ?
'' : $val[
'list']);
7563 $help = (empty($val[
'help']) ?
'' : $val[
'help']);
7564 $hidden = (($val[
'visible'] == 0) ? 1 : 0);
7574 $value =
dol_eval($computed, 1, 0,
'');
7577 if (empty($morecss)) {
7578 if ($type ==
'date') {
7579 $morecss =
'minwidth100imp';
7580 } elseif ($type ==
'datetime' || $type ==
'timestamp') {
7581 $morecss =
'minwidth200imp';
7582 } elseif (in_array($type, array(
'int',
'double',
'price'))) {
7583 $morecss =
'maxwidth75';
7584 } elseif ($type ==
'url') {
7585 $morecss =
'minwidth400';
7586 } elseif ($type ==
'boolean') {
7589 if (is_numeric($size) && round($size) < 12) {
7590 $morecss =
'minwidth100';
7591 } elseif (is_numeric($size) && round($size) <= 48) {
7592 $morecss =
'minwidth200';
7594 $morecss =
'minwidth400';
7600 if (in_array($key, array(
'rowid',
'ref')) && method_exists($this,
'getNomUrl')) {
7601 if ($key !=
'rowid' || empty($this->fields[
'ref'])) {
7602 $value = $this->getNomUrl(1,
'', 0,
'', 1);
7604 } elseif ($key ==
'status' && method_exists($this,
'getLibStatut')) {
7605 $value = $this->getLibStatut(3);
7606 } elseif ($type ==
'date') {
7607 if (!empty($value)) {
7612 } elseif ($type ==
'datetime' || $type ==
'timestamp') {
7613 if (!empty($value)) {
7618 } elseif ($type ==
'duration') {
7619 include_once DOL_DOCUMENT_ROOT.
'/core/lib/date.lib.php';
7620 if (!is_null($value) && $value !==
'') {
7623 } elseif ($type ==
'double' || $type ==
'real') {
7624 if (!is_null($value) && $value !==
'') {
7625 $value =
price($value);
7627 } elseif ($type ==
'boolean') {
7629 if (!empty($value)) {
7630 $checked =
' checked ';
7632 $value =
'<input type="checkbox" '.$checked.
' '.($moreparam ? $moreparam :
'').
' readonly disabled>';
7633 } elseif ($type ==
'mail' || $type ==
'email') {
7635 } elseif ($type ==
'url') {
7637 } elseif ($type ==
'phone') {
7639 } elseif ($type ==
'ip') {
7641 } elseif ($type ==
'price') {
7642 if (!is_null($value) && $value !==
'') {
7643 $value =
price($value, 0, $langs, 0, 0, -1, $conf->currency);
7645 } elseif ($type ==
'select') {
7646 $value = isset($param[
'options'][$value])?$param[
'options'][$value]:
'';
7647 } elseif ($type ==
'sellist') {
7648 $param_list = array_keys($param[
'options']);
7649 $InfoFieldList = explode(
":", $param_list[0]);
7651 $selectkey =
"rowid";
7654 if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
7655 $selectkey = $InfoFieldList[2];
7656 $keyList = $InfoFieldList[2].
' as rowid';
7659 $fields_label = explode(
'|', $InfoFieldList[1]);
7660 if (is_array($fields_label)) {
7662 $keyList .= implode(
', ', $fields_label);
7665 $filter_categorie =
false;
7666 if (count($InfoFieldList) > 5) {
7667 if ($InfoFieldList[0] ==
'categorie') {
7668 $filter_categorie =
true;
7672 $sql =
"SELECT ".$keyList;
7673 $sql .=
' FROM '.$this->db->prefix().$InfoFieldList[0];
7674 if (strpos($InfoFieldList[4],
'extra') !==
false) {
7677 if ($selectkey ==
'rowid' && empty($value)) {
7678 $sql .=
" WHERE ".$selectkey.
" = 0";
7679 } elseif ($selectkey ==
'rowid') {
7680 $sql .=
" WHERE ".$selectkey.
" = ".((int) $value);
7682 $sql .=
" WHERE ".$selectkey.
" = '".$this->db->escape($value).
"'";
7687 dol_syslog(get_class($this).
':showOutputField:$type=sellist', LOG_DEBUG);
7688 $resql = $this->db->query($sql);
7690 if ($filter_categorie ===
false) {
7692 $numrows = $this->db->num_rows($resql);
7694 $obj = $this->db->fetch_object($resql);
7697 $fields_label = explode(
'|', $InfoFieldList[1]);
7699 if (is_array($fields_label) && count($fields_label) > 1) {
7700 foreach ($fields_label as $field_toshow) {
7702 if (!empty($obj->$field_toshow)) {
7703 $translabel = $langs->trans($obj->$field_toshow);
7705 if ($translabel != $field_toshow) {
7706 $value .=
dol_trunc($translabel, 18) .
' ';
7708 $value .= $obj->$field_toshow .
' ';
7713 if (!empty($obj->{$InfoFieldList[1]})) {
7714 $translabel = $langs->trans($obj->{$InfoFieldList[1]});
7716 if ($translabel != $obj->{$InfoFieldList[1]}) {
7719 $value = $obj->{$InfoFieldList[1]};
7724 require_once DOL_DOCUMENT_ROOT .
'/categories/class/categorie.class.php';
7727 $obj = $this->db->fetch_object($resql);
7729 $c->fetch($obj->rowid);
7730 $ways = $c->print_all_ways();
7731 foreach ($ways as $way) {
7732 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories"' . ($c->color ?
' style="background: #' . $c->color .
';"' :
' style="background: #aaa"') .
'>' .
img_object(
'',
'category') .
' ' . $way .
'</li>';
7734 $value =
'<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(
' ', $toprint).
'</ul></div>';
7737 dol_syslog(get_class($this).
'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
7739 } elseif ($type ==
'radio') {
7740 $value = $param[
'options'][$value];
7741 } elseif ($type ==
'checkbox') {
7742 $value_arr = explode(
',', $value);
7744 if (is_array($value_arr) && count($value_arr) > 0) {
7746 foreach ($value_arr as $keyval => $valueval) {
7747 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">'.$param[
'options'][$valueval].
'</li>';
7749 $value =
'<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(
' ', $toprint).
'</ul></div>';
7751 } elseif ($type ==
'chkbxlst') {
7752 $value_arr = explode(
',', $value);
7754 $param_list = array_keys($param[
'options']);
7755 $InfoFieldList = explode(
":", $param_list[0]);
7757 $selectkey =
"rowid";
7760 if (count($InfoFieldList) >= 3) {
7761 $selectkey = $InfoFieldList[2];
7762 $keyList = $InfoFieldList[2].
' as rowid';
7765 $fields_label = explode(
'|', $InfoFieldList[1]);
7766 if (is_array($fields_label)) {
7768 $keyList .= implode(
', ', $fields_label);
7771 $filter_categorie =
false;
7772 if (count($InfoFieldList) > 5) {
7773 if ($InfoFieldList[0] ==
'categorie') {
7774 $filter_categorie =
true;
7778 $sql =
"SELECT ".$keyList;
7779 $sql .=
' FROM '.$this->db->prefix().$InfoFieldList[0];
7780 if (strpos($InfoFieldList[4],
'extra') !==
false) {
7786 dol_syslog(get_class($this).
':showOutputField:$type=chkbxlst', LOG_DEBUG);
7787 $resql = $this->db->query($sql);
7789 if ($filter_categorie ===
false) {
7792 while ($obj = $this->db->fetch_object($resql)) {
7794 $fields_label = explode(
'|', $InfoFieldList[1]);
7795 if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
7796 if (is_array($fields_label) && count($fields_label) > 1) {
7797 foreach ($fields_label as $field_toshow) {
7799 if (!empty($obj->$field_toshow)) {
7800 $translabel = $langs->trans($obj->$field_toshow);
7802 if ($translabel != $field_toshow) {
7803 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' .
dol_trunc($translabel, 18) .
'</li>';
7805 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' . $obj->$field_toshow .
'</li>';
7810 if (!empty($obj->{$InfoFieldList[1]})) {
7811 $translabel = $langs->trans($obj->{$InfoFieldList[1]});
7813 if ($translabel != $obj->{$InfoFieldList[1]}) {
7814 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' .
dol_trunc($translabel, 18) .
'</li>';
7816 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' . $obj->{$InfoFieldList[1]} .
'</li>';
7822 require_once DOL_DOCUMENT_ROOT .
'/categories/class/categorie.class.php';
7825 while ($obj = $this->db->fetch_object($resql)) {
7826 if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
7828 $c->fetch($obj->rowid);
7829 $ways = $c->print_all_ways();
7830 foreach ($ways as $way) {
7831 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories"' . ($c->color ?
' style="background: #' . $c->color .
';"' :
' style="background: #aaa"') .
'>' .
img_object(
'',
'category') .
' ' . $way .
'</li>';
7836 $value =
'<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(
' ', $toprint).
'</ul></div>';
7838 dol_syslog(get_class($this).
'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
7840 } elseif ($type ==
'link') {
7845 $param_list = array_keys($param[
'options']);
7847 $InfoFieldList = explode(
":", $param_list[0]);
7848 $classname = $InfoFieldList[0];
7849 $classpath = $InfoFieldList[1];
7850 $getnomurlparam = (empty($InfoFieldList[2]) ? 3 : $InfoFieldList[2]);
7851 $getnomurlparam2 = (empty($InfoFieldList[4]) ?
'' : $InfoFieldList[4]);
7852 if (!empty($classpath)) {
7854 if ($classname && class_exists($classname)) {
7855 $object =
new $classname($this->db);
7856 if ($object->element ===
'product') {
7857 $result = $object->fetch($value,
'',
'',
'', 0, 1, 1);
7859 $result = $object->fetch($value);
7862 if ($object->element ===
'product') {
7863 $get_name_url_param_arr = array($getnomurlparam, $getnomurlparam2, 0, -1, 0,
'', 0);
7864 if (isset($val[
'get_name_url_params'])) {
7865 $get_name_url_params = explode(
':', $val[
'get_name_url_params']);
7866 if (!empty($get_name_url_params)) {
7867 $param_num_max = count($get_name_url_param_arr) - 1;
7868 foreach ($get_name_url_params as $param_num => $param_value) {
7869 if ($param_num > $param_num_max) {
7872 $get_name_url_param_arr[$param_num] = $param_value;
7880 $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]);
7882 $value = $object->getNomUrl($getnomurlparam, $getnomurlparam2);
7889 dol_syslog(
'Error bad setup of extrafield', LOG_WARNING);
7890 return 'Error bad setup of extrafield';
7895 } elseif ($type ==
'password') {
7896 $value = preg_replace(
'/./i',
'*', $value);
7897 } elseif ($type ==
'array') {
7898 $value = implode(
'<br>', $value);
7918 unset($this->validateFieldsErrors[$fieldKey]);
7932 $msg = $langs->trans(
"UnknowError");
7935 $this->error = $this->validateFieldsErrors[$fieldKey] = $msg;
7946 if (!empty($this->validateFieldsErrors[$fieldKey])) {
7947 return $this->validateFieldsErrors[$fieldKey];
7964 if (!class_exists(
'Validate')) {
7965 require_once DOL_DOCUMENT_ROOT .
'/core/class/validate.class.php';
7968 $this->clearFieldError($fieldKey);
7970 if (!isset($fields[$fieldKey])) {
7971 $this->setFieldError($fieldKey, $langs->trans(
'FieldNotFoundInObject'));
7975 $val = $fields[$fieldKey];
7978 $param[
'options'] = array();
7979 $type = $val[
'type'];
7982 if (isset($val[
'notnull']) && $val[
'notnull'] === 1) {
7996 if (preg_match(
'/varchar\((\d+)\)/', $type, $reg)) {
7999 } elseif (preg_match(
'/varchar/', $type)) {
8003 if (!empty($val[
'arrayofkeyval']) && is_array($val[
'arrayofkeyval'])) {
8007 if (!empty($val[
'type']) && preg_match(
'/^integer:(.*):(.*)/i', $val[
'type'], $reg)) {
8011 if (!empty($val[
'arrayofkeyval']) && is_array($val[
'arrayofkeyval'])) {
8012 $param[
'options'] = $val[
'arrayofkeyval'];
8015 if (preg_match(
'/^integer:(.*):(.*)/i', $val[
'type'], $reg)) {
8017 $param[
'options'] = array($reg[1].
':'.$reg[2]=>$reg[1].
':'.$reg[2]);
8018 } elseif (preg_match(
'/^sellist:(.*):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
8019 $param[
'options'] = array($reg[1].
':'.$reg[2].
':'.$reg[3].
':'.$reg[4] =>
'N');
8021 } elseif (preg_match(
'/^sellist:(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
8022 $param[
'options'] = array($reg[1].
':'.$reg[2].
':'.$reg[3] =>
'N');
8024 } elseif (preg_match(
'/^sellist:(.*):(.*)/i', $val[
'type'], $reg)) {
8025 $param[
'options'] = array($reg[1].
':'.$reg[2] =>
'N');
8034 $validate =
new Validate($this->db, $langs);
8044 if ($required && !$validate->isNotEmptyString($fieldValue)) {
8045 $this->setFieldError($fieldKey, $validate->error);
8047 } elseif (!$required && !$validate->isNotEmptyString($fieldValue)) {
8053 if (!empty($maxSize) && !$validate->isMaxLength($fieldValue, $maxSize)) {
8054 $this->setFieldError($fieldKey, $validate->error);
8059 if (!empty($minSize) && !$validate->isMinLength($fieldValue, $minSize)) {
8060 $this->setFieldError($fieldKey, $validate->error);
8068 if (in_array($type, array(
'date',
'datetime',
'timestamp'))) {
8069 if (!$validate->isTimestamp($fieldValue)) {
8070 $this->setFieldError($fieldKey, $validate->error);
8072 }
else {
return true; }
8073 } elseif ($type ==
'duration') {
8074 if (!$validate->isDuration($fieldValue)) {
8075 $this->setFieldError($fieldKey, $validate->error);
8077 }
else {
return true; }
8078 } elseif (in_array($type, array(
'double',
'real',
'price'))) {
8080 if (!$validate->isNumeric($fieldValue)) {
8081 $this->setFieldError($fieldKey, $validate->error);
8083 }
else {
return true; }
8084 } elseif ($type ==
'boolean') {
8085 if (!$validate->isBool($fieldValue)) {
8086 $this->setFieldError($fieldKey, $validate->error);
8088 }
else {
return true; }
8089 } elseif ($type ==
'mail') {
8090 if (!$validate->isEmail($fieldValue)) {
8091 $this->setFieldError($fieldKey, $validate->error);
8094 } elseif ($type ==
'url') {
8095 if (!$validate->isUrl($fieldValue)) {
8096 $this->setFieldError($fieldKey, $validate->error);
8098 }
else {
return true; }
8099 } elseif ($type ==
'phone') {
8100 if (!$validate->isPhone($fieldValue)) {
8101 $this->setFieldError($fieldKey, $validate->error);
8103 }
else {
return true; }
8104 } elseif ($type ==
'select' || $type ==
'radio') {
8105 if (!isset($param[
'options'][$fieldValue])) {
8106 $this->error = $langs->trans(
'RequireValidValue');
8108 }
else {
return true; }
8109 } elseif ($type ==
'sellist' || $type ==
'chkbxlst') {
8110 $param_list = array_keys($param[
'options']);
8111 $InfoFieldList = explode(
":", $param_list[0]);
8112 $value_arr = explode(
',', $fieldValue);
8113 $value_arr = array_map(array($this->db,
'escape'), $value_arr);
8115 $selectkey =
"rowid";
8116 if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
8117 $selectkey = $InfoFieldList[2];
8120 if (!$validate->isInDb($value_arr, $InfoFieldList[0], $selectkey)) {
8121 $this->setFieldError($fieldKey, $validate->error);
8123 }
else {
return true; }
8124 } elseif ($type ==
'link') {
8125 $param_list = array_keys($param[
'options']);
8126 $InfoFieldList = explode(
":", $param_list[0]);
8127 $classname = $InfoFieldList[0];
8128 $classpath = $InfoFieldList[1];
8129 if (!$validate->isFetchable($fieldValue, $classname, $classpath)) {
8130 $this->setFieldError($fieldKey, $validate->error);
8132 }
else {
return true; }
8152 public function showOptionals($extrafields, $mode =
'view', $params =
null, $keysuffix =
'', $keyprefix =
'', $onetrtd = 0, $display_type =
'card')
8154 global $db, $conf, $langs, $action, $form, $hookmanager;
8156 if (!is_object($form)) {
8157 $form =
new Form($db);
8159 if (!is_object($extrafields)) {
8160 dol_syslog(
'Bad parameter extrafields for showOptionals', LOG_ERR);
8161 return 'Bad parameter extrafields for showOptionals';
8163 if (!is_array($extrafields->attributes[$this->table_element])) {
8164 dol_syslog(
"extrafields->attributes was not loaded with extrafields->fetch_name_optionals_label(table_element);", LOG_WARNING);
8169 $parameters = array(
'mode'=>$mode,
'params'=>$params,
'keysuffix'=>$keysuffix,
'keyprefix'=>$keyprefix,
'display_type'=>$display_type);
8170 $reshook = $hookmanager->executeHooks(
'showOptionals', $parameters, $this, $action);
8172 if (empty($reshook)) {
8173 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) {
8175 $out .=
'<!-- commonobject:showOptionals --> ';
8178 $nbofextrafieldsshown = 0;
8181 $lastseparatorkeyfound =
'';
8182 $extrafields_collapse_num =
'';
8183 $extrafields_collapse_num_old =
'';
8186 foreach ($extrafields->attributes[$this->table_element][
'label'] as $key => $label) {
8190 if (is_array($params) && array_key_exists(
'onlykey', $params) && $key != $params[
'onlykey']) {
8196 if ($enabled && isset($extrafields->attributes[$this->table_element][
'enabled'][$key])) {
8197 $enabled =
dol_eval($extrafields->attributes[$this->table_element][
'enabled'][$key], 1, 1,
'2');
8199 if (empty($enabled)) {
8204 if ($visibility && isset($extrafields->attributes[$this->table_element][
'list'][$key])) {
8205 $visibility =
dol_eval($extrafields->attributes[$this->table_element][
'list'][$key], 1, 1,
'2');
8209 if ($perms && isset($extrafields->attributes[$this->table_element][
'perms'][$key])) {
8210 $perms =
dol_eval($extrafields->attributes[$this->table_element][
'perms'][$key], 1, 1,
'2');
8213 if (($mode ==
'create') && abs($visibility) != 1 && abs($visibility) != 3) {
8215 } elseif (($mode ==
'edit') && abs($visibility) != 1 && abs($visibility) != 3 && abs($visibility) != 4) {
8217 $ef_name =
'options_' . $key;
8218 $ef_value = $this->array_options[$ef_name];
8219 $out .=
'<input type="hidden" name="' . $ef_name .
'" id="' . $ef_name .
'" value="' . $ef_value .
'" />' .
"\n";
8221 } elseif ($mode ==
'view' && empty($visibility)) {
8224 if (empty($perms)) {
8229 if (!empty($extrafields->attributes[$this->table_element][
'langfile'][$key])) {
8230 $langs->load($extrafields->attributes[$this->table_element][
'langfile'][$key]);
8234 if (is_array($params) && count($params) > 0 && $display_type==
'card') {
8235 if (array_key_exists(
'cols', $params)) {
8236 $colspan = $params[
'cols'];
8237 } elseif (array_key_exists(
'colspan', $params)) {
8239 if (preg_match(
'/colspan="(\d+)"/', $params[
'colspan'], $reg)) {
8242 $colspan = $params[
'colspan'];
8246 $colspan = intval($colspan);
8250 $value = ((!empty($this->array_options) && array_key_exists(
"options_".$key.$keysuffix, $this->array_options)) ? $this->array_options[
"options_".$key.$keysuffix] :
null);
8256 $check =
'alphanohtml';
8257 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'html',
'text'))) {
8258 $check =
'restricthtml';
8260 $getposttemp =
GETPOST($keyprefix.
'options_'.$key.$keysuffix, $check, 3);
8262 if (is_array($getposttemp) || $getposttemp !=
'' || GETPOSTISSET($keyprefix.
'options_'.$key.$keysuffix)) {
8263 if (is_array($getposttemp)) {
8265 $value = implode(
",", $getposttemp);
8267 $value = $getposttemp;
8270 $value = (!empty($this->array_options[
"options_".$key]) ? $this->array_options[
"options_".$key] :
'');
8276 $nbofextrafieldsshown++;
8279 if ($extrafields->attributes[$this->table_element][
'type'][$key] ==
'separate') {
8280 $extrafields_collapse_num = $key;
8298 $out .= $extrafields->showSeparator($key, $this, ($colspan ? $colspan + 1 : 2), $display_type, $mode);
8300 $lastseparatorkeyfound = $key;
8302 $collapse_group = $extrafields_collapse_num.(!empty($this->
id) ?
'_'.$this->id :
'');
8304 $class = (!empty($extrafields->attributes[$this->table_element][
'hidden'][$key]) ?
'hideobject ' :
'');
8306 if (is_array($params) && count($params) > 0) {
8307 if (array_key_exists(
'class', $params)) {
8308 $class .= $params[
'class'].
' ';
8310 if (array_key_exists(
'style', $params)) {
8311 $csstyle = $params[
'style'];
8316 $domData =
' data-element="extrafield"';
8317 $domData .=
' data-targetelement="'.$this->element.
'"';
8318 $domData .=
' data-targetid="'.$this->id.
'"';
8320 $html_id = (empty($this->
id) ?
'' :
'extrarow-'.$this->element.
'_'.$key.
'_'.$this->id);
8321 if ($display_type==
'card') {
8322 if (!empty($conf->global->MAIN_EXTRAFIELDS_USE_TWO_COLUMS) && ($e % 2) == 0) {
8326 if ($action ==
'selectlines') {
8332 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'date'))) {
8333 $datenotinstring =
null;
8334 if (array_key_exists(
'options_'.$key, $this->array_options)) {
8335 $datenotinstring = $this->array_options[
'options_'.$key];
8336 if (!is_numeric($this->array_options[
'options_'.$key])) {
8337 $datenotinstring = $this->db->jdate($datenotinstring);
8340 $datekey = $keyprefix.
'options_'.$key.$keysuffix;
8341 $value = (GETPOSTISSET($datekey) && $this->
id ==
GETPOST(
'elrowid',
'int')) ?
dol_mktime(12, 0, 0,
GETPOST($datekey.
'month',
'int', 3),
GETPOST($datekey.
'day',
'int', 3),
GETPOST($datekey.
'year',
'int', 3)) : $datenotinstring;
8343 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'datetime'))) {
8344 $datenotinstring =
null;
8345 if (array_key_exists(
'options_'.$key, $this->array_options)) {
8346 $datenotinstring = $this->array_options[
'options_'.$key];
8347 if (!is_numeric($this->array_options[
'options_'.$key])) {
8348 $datenotinstring = $this->db->jdate($datenotinstring);
8351 $timekey = $keyprefix.
'options_'.$key.$keysuffix;
8352 $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;
8355 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'price',
'double'))) {
8356 if (GETPOSTISSET($keyprefix.
'options_'.$key.$keysuffix) || $value) {
8358 } elseif (isset($this->array_options[
'options_'.$key])) {
8359 $value = $this->array_options[
'options_'.$key];
8364 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'html',
'text',
'varchar',
'select',
'radio',
'int',
'boolean'))) {
8365 if ($action ==
'create') {
8366 $value = (GETPOSTISSET($keyprefix.
'options_'.$key.$keysuffix) || $value) ? $value : $extrafields->attributes[$this->table_element][
'default'][$key];
8370 $labeltoshow = $langs->trans($label);
8371 $helptoshow = $langs->trans($extrafields->attributes[$this->table_element][
'help'][$key]);
8373 if ($display_type ==
'card') {
8374 $out .=
'<tr '.($html_id ?
'id="'.$html_id.
'" ' :
'').$csstyle.
' class="field_options_'.$key.
' '.$class.$this->element.
'_extras_'.$key.
' trextrafields_collapse'.$collapse_group.
'" '.$domData.
' >';
8375 if (!empty($conf->global->MAIN_VIEW_LINE_NUMBER) && ($action ==
'view' || $action ==
'valid' || $action ==
'editline' || $action ==
'confirm_valid' || $action ==
'confirm_cancel')) {
8376 $out .=
'<td></td>';
8378 $out .=
'<td class="'.(empty($params[
'tdclass']) ?
'titlefieldcreate' : $params[
'tdclass']).
' wordbreak';
8379 } elseif ($display_type ==
'line') {
8380 $out .=
'<div '.($html_id ?
'id="'.$html_id.
'" ' :
'').$csstyle.
' class="fieldline_options_'.$key.
' '.$class.$this->element.
'_extras_'.$key.
' trextrafields_collapse'.$collapse_group.
'" '.$domData.
' >';
8381 $out .=
'<div style="display: inline-block; padding-right:4px" class="wordbreak';
8386 $tpl_context = isset($params[
"tpl_context"]) ? $params[
"tpl_context"] :
"none";
8387 if ($tpl_context !=
"public") {
8388 if ($mode !=
'view' && !empty($extrafields->attributes[$this->table_element][
'required'][$key])) {
8389 $out .=
' fieldrequired';
8393 if ($tpl_context ==
"public") {
8394 if (!empty($extrafields->attributes[$this->table_element][
'help'][$key])) {
8395 $out .= $form->textwithpicto($labeltoshow, $helptoshow);
8397 $out .= $labeltoshow;
8399 if ($mode !=
'view' && !empty($extrafields->attributes[$this->table_element][
'required'][$key])) {
8400 $out .=
' <span style="color: red">*</span>';
8403 if (!empty($extrafields->attributes[$this->table_element][
'help'][$key])) {
8404 $out .= $form->textwithpicto($labeltoshow, $helptoshow);
8406 $out .= $labeltoshow;
8410 $out .= ($display_type ==
'card' ?
'</td>' :
'</div>');
8412 $html_id = !empty($this->
id) ? $this->element.
'_extras_'.$key.
'_'.$this->id :
'';
8413 if ($display_type ==
'card') {
8415 $out .=
'<td '.($html_id ?
'id="'.$html_id.
'" ' :
'').
' class="valuefieldcreate '.$this->element.
'_extras_'.$key.
'" '.($colspan ?
' colspan="'.$colspan.
'"' :
'').
'>';
8416 } elseif ($display_type ==
'line') {
8417 $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].
'">';
8422 $out .= $extrafields->showOutputField($key, $value,
'', $this->table_element);
8425 $out .= $extrafields->showInputField($key, $value,
'', $keysuffix,
'', 0, $this->
id, $this->table_element);
8428 $out .= $extrafields->showInputField($key, $value,
'', $keysuffix,
'', 0, $this->
id, $this->table_element);
8432 $out .= ($display_type==
'card' ?
'</td>' :
'</div>');
8434 if (!empty($conf->global->MAIN_EXTRAFIELDS_USE_TWO_COLUMS) && (($e % 2) == 1)) {
8435 $out .= ($display_type==
'card' ?
'</tr>' :
'</div>');
8437 $out .= ($display_type==
'card' ?
'</tr>' :
'</div>');
8445 if (!empty($conf->use_javascript_ajax)) {
8446 $out .= $this->getJSListDependancies();
8449 $out .=
'<!-- commonobject:showOptionals end --> '.
"\n";
8451 if (empty($nbofextrafieldsshown)) {
8457 $out .= $hookmanager->resPrint;
8469 <script nonce="'.getNonce().
'">
8470 jQuery(document).ready(function() {
8471 function showOptions'.$type.
'(child_list, parent_list, orig_select)
8473 var val = $("select[name=\""+parent_list+"\"]").val();
8474 var parentVal = parent_list + ":" + val;
8475 if(typeof val == "string"){
8477 var options = orig_select.find("option[parent=\""+parentVal+"\"]").clone();
8478 $("select[name=\""+child_list+"\"] option[parent]").remove();
8479 $("select[name=\""+child_list+"\"]").append(options);
8481 var options = orig_select.find("option[parent]").clone();
8482 $("select[name=\""+child_list+"\"] option[parent]").remove();
8483 $("select[name=\""+child_list+"\"]").append(options);
8485 } else if(val > 0) {
8486 var options = orig_select.find("option[parent=\""+parentVal+"\"]").clone();
8487 $("select[name=\""+child_list+"\"] option[parent]").remove();
8488 $("select[name=\""+child_list+"\"]").append(options);
8490 var options = orig_select.find("option[parent]").clone();
8491 $("select[name=\""+child_list+"\"] option[parent]").remove();
8492 $("select[name=\""+child_list+"\"]").append(options);
8495 function setListDependencies'.$type.
'() {
8496 jQuery("select option[parent]").parent().each(function() {
8497 var orig_select = {};
8498 var child_list = $(this).attr("name");
8499 orig_select[child_list] = $(this).clone();
8500 var parent = $(this).find("option[parent]:first").attr("parent");
8501 var infos = parent.split(":");
8502 var parent_list = infos[0];
8504 //Hide daughters lists
8505 if ($("#"+child_list).val() == 0 && $("#"+parent_list).val() == 0){
8506 $("#"+child_list).hide();
8508 } else if ($("#"+parent_list).val() != 0){
8509 $("#"+parent_list).show();
8511 //Show the child list if the parent list value is selected
8512 $("select[name=\""+parent_list+"\"]").click(function() {
8513 if ($(this).val() != 0){
8514 $("#"+child_list).show()
8518 //When we change parent list
8519 $("select[name=\""+parent_list+"\"]").change(function() {
8520 showOptions'.$type.
'(child_list, parent_list, orig_select[child_list]);
8521 //Select the value 0 on child list after a change on the parent list
8522 $("#"+child_list).val(0).trigger("change");
8523 //Hide child lists if the parent value is set to 0
8524 if ($(this).val() == 0){
8525 $("#"+child_list).hide();
8531 setListDependencies'.$type.
'();
8546 $module = empty($this->module) ?
'' : $this->module;
8547 $element = $this->element;
8549 if ($element ==
'facturerec') {
8550 $element =
'facture';
8551 } elseif ($element ==
'invoice_supplier_rec') {
8552 return empty($user->rights->fournisseur->facture) ? null : $user->rights->fournisseur->facture;
8553 } elseif ($module && !empty($user->rights->$module->$element)) {
8555 return $user->rights->$module->$element;
8558 return $user->rights->$element;
8575 foreach ($tables as $table) {
8576 $sql =
'UPDATE '.$dbs->prefix().$table.
' SET fk_soc = '.((int) $dest_id).
' WHERE fk_soc = '.((int) $origin_id);
8578 if (!$dbs->
query($sql)) {
8579 if ($ignoreerrors) {
8604 foreach ($tables as $table) {
8605 $sql =
'UPDATE '.MAIN_DB_PREFIX.$table.
' SET fk_product = '.((int) $dest_id).
' WHERE fk_product = '.((int) $origin_id);
8607 if (!$dbs->
query($sql)) {
8608 if ($ignoreerrors) {
8631 public function defineBuyPrice($unitPrice = 0.0, $discountPercent = 0.0, $fk_product = 0)
8637 if (($unitPrice > 0) && (isset($conf->global->ForceBuyingPriceIfNull) && $conf->global->ForceBuyingPriceIfNull > 0)) {
8639 $buyPrice = $unitPrice * (1 - $discountPercent / 100);
8642 if (!empty($fk_product) && $fk_product > 0) {
8643 if (isset($conf->global->MARGIN_TYPE) && $conf->global->MARGIN_TYPE ==
'costprice') {
8644 require_once DOL_DOCUMENT_ROOT.
'/product/class/product.class.php';
8645 $product =
new Product($this->db);
8646 $result = $product->fetch($fk_product);
8648 $this->errors[] =
'ErrorProductIdDoesNotExists';
8651 if ($product->cost_price > 0) {
8652 $buyPrice = $product->cost_price;
8653 } elseif ($product->pmp > 0) {
8654 $buyPrice = $product->pmp;
8656 } elseif (isset($conf->global->MARGIN_TYPE) && $conf->global->MARGIN_TYPE ==
'pmp') {
8657 require_once DOL_DOCUMENT_ROOT.
'/product/class/product.class.php';
8658 $product =
new Product($this->db);
8659 $result = $product->fetch($fk_product);
8661 $this->errors[] =
'ErrorProductIdDoesNotExists';
8664 if ($product->pmp > 0) {
8665 $buyPrice = $product->pmp;
8669 if (empty($buyPrice) && isset($conf->global->MARGIN_TYPE) && in_array($conf->global->MARGIN_TYPE, array(
'1',
'pmp',
'costprice'))) {
8670 require_once DOL_DOCUMENT_ROOT.
'/fourn/class/fournisseur.product.class.php';
8672 if (($result = $productFournisseur->find_min_price_product_fournisseur($fk_product)) > 0) {
8673 $buyPrice = $productFournisseur->fourn_unitprice;
8674 } elseif ($result < 0) {
8675 $this->errors[] = $productFournisseur->error;
8704 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')
8707 global $conf, $user, $langs;
8709 include_once DOL_DOCUMENT_ROOT.
'/core/lib/files.lib.php';
8710 include_once DOL_DOCUMENT_ROOT.
'/core/lib/images.lib.php';
8712 $sortfield =
'position_name';
8718 $dir .=
get_exdir(0, 0, 0, 0, $this, $modulepart);
8719 $pdir .=
get_exdir(0, 0, 0, 0, $this, $modulepart);
8722 if ($modulepart ==
'product') {
8724 $dir = $sdir.
'/'.
get_exdir($this->
id, 2, 0, 0, $this, $modulepart).$this->id.
"/photos/";
8725 $pdir =
'/'.get_exdir($this->
id, 2, 0, 0, $this, $modulepart).$this->id.
"/photos/";
8732 $relativedir = preg_replace(
'/^'.preg_quote(DOL_DATA_ROOT,
'/').
'/',
'', $dir);
8733 $relativedir = preg_replace(
'/^[\\/]/',
'', $relativedir);
8734 $relativedir = preg_replace(
'/[\\/]$/',
'', $relativedir);
8737 $dirthumb = $dir.
'thumbs/';
8738 $pdirthumb = $pdir.
'thumbs/';
8740 $return =
'<!-- Photo -->'.
"\n";
8743 $filearray =
dol_dir_list($dir,
"files", 0,
'',
'(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) ==
'desc' ?SORT_DESC:SORT_ASC), 1);
8753 if (count($filearray)) {
8754 if ($sortfield && $sortorder) {
8758 foreach ($filearray as $key => $val) {
8760 $file = $val[
'name'];
8766 $viewfilename = $file;
8768 if ($size == 1 || $size ==
'small') {
8775 $photo_vignette = basename($file);
8782 if ($nbphoto == 1) {
8783 $return .=
'<table class="valigntop center centpercent" style="border: 0; padding: 2px; border-spacing: 2px; border-collapse: separate;">';
8786 if ($nbphoto % $nbbyrow == 1) {
8787 $return .=
'<tr class="center valignmiddle" style="border: 1px">';
8789 $return .=
'<td style="width: '.ceil(100 / $nbbyrow).
'%" class="photo">'.
"\n";
8790 } elseif ($nbbyrow < 0) {
8791 $return .=
'<div class="inline-block">'.
"\n";
8794 $relativefile = preg_replace(
'/^\//',
'', $pdir.$photo);
8795 if (empty($nolink)) {
8798 $return .=
'<a href="'.$urladvanced.
'">';
8800 $return .=
'<a href="'.DOL_URL_ROOT.
'/viewimage.php?modulepart='.$modulepart.
'&entity='.$this->entity.
'&file='.urlencode($pdir.$photo).
'" class="aphoto" target="_blank" rel="noopener noreferrer">';
8806 $alt = $langs->transnoentitiesnoconv(
'File').
': '.$relativefile;
8807 $alt .=
' - '.$langs->transnoentitiesnoconv(
'Size').
': '.$imgarray[
'width'].
'x'.$imgarray[
'height'];
8808 if ($overwritetitle) {
8809 if (is_numeric($overwritetitle)) {
8812 $alt = $overwritetitle;
8816 if ($usesharelink) {
8817 if ($val[
'share']) {
8818 if (empty($maxHeight) || ($photo_vignette && $imgarray[
'height'] > $maxHeight)) {
8819 $return .=
'<!-- Show original file (thumb not yet available with shared links) -->';
8820 $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).
'">';
8822 $return .=
'<!-- Show original file -->';
8823 $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).
'">';
8826 $return .=
'<!-- Show nophoto file (because file is not shared) -->';
8827 $return .=
'<img class="photo photowithmargin'.($addphotorefcss ?
' '.$addphotorefcss :
'').
'" height="'.$maxHeight.
'" src="'.DOL_URL_ROOT.
'/public/theme/common/nophoto.png" title="'.
dol_escape_htmltag($alt).
'">';
8830 if (empty($maxHeight) || ($photo_vignette && $imgarray[
'height'] > $maxHeight)) {
8831 $return .=
'<!-- Show thumb -->';
8832 $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).
'">';
8834 $return .=
'<!-- Show original file -->';
8835 $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).
'">';
8839 if (empty($nolink)) {
8843 if ($showfilename) {
8844 $return .=
'<br>'.$viewfilename;
8849 if ($photo_vignette && (
image_format_supported($photo) > 0) && ($this->imgWidth > $maxWidth || $this->imgHeight > $maxHeight)) {
8850 $return .=
'<a href="'.$_SERVER[
"PHP_SELF"].
'?id='.$this->
id.
'&action=addthumb&token='.newToken().
'&file='.urlencode($pdir.$viewfilename).
'">'.
img_picto($langs->trans(
'GenerateThumb'),
'refresh').
' </a>';
8853 if ($modulepart ==
'product' && ($user->hasRight(
'produit',
'creer') || $user->hasRight(
'service',
'creer'))) {
8855 $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> ';
8858 $return .=
'<a href="'.$_SERVER[
"PHP_SELF"].
'?id='.$this->
id.
'&action=delete&token='.newToken().
'&file='.urlencode($pdir.$viewfilename).
'">';
8866 if (($nbphoto % $nbbyrow) == 0) {
8869 } elseif ($nbbyrow < 0) {
8870 $return .=
'</div>'.
"\n";
8875 $return .=
'<img class="photo photowithmargin" src="'.DOL_URL_ROOT.
'/viewimage.php?modulepart='.$modulepart.
'&entity='.$this->entity.
'&file='.urlencode($pdir.$photo).
'">';
8877 if ($showfilename) {
8878 $return .=
'<br>'.$viewfilename;
8882 if ($modulepart ==
'product' && ($user->hasRight(
'produit',
'creer') || $user->hasRight(
'service',
'creer'))) {
8884 $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> ';
8887 $return .=
'<a href="'.$_SERVER[
"PHP_SELF"].
'?id='.$this->
id.
'&action=delete&token='.newToken().
'&file='.urlencode($pdir.$viewfilename).
'">';
8894 if ($nbmax && $nbphoto >= $nbmax) {
8900 if ($size == 1 || $size ==
'small') {
8903 while ($nbphoto % $nbbyrow) {
8904 $return .=
'<td style="width: '.ceil(100 / $nbbyrow).
'%"> </td>';
8909 $return .=
'</table>';
8915 $this->nbphoto = $nbphoto;
8929 if (is_array($info)) {
8930 if (isset($info[
'type']) && $info[
'type'] ==
'array') {
8947 if (isset($info[
'type']) && ($info[
'type'] ==
'date' || $info[
'type'] ==
'datetime' || $info[
'type'] ==
'timestamp')) {
8961 if (is_array($info)) {
8962 if (isset($info[
'type']) && ($info[
'type'] ==
'duration')) {
8980 if (is_array($info)) {
8981 if (isset($info[
'type']) && (preg_match(
'/(^int|int$)/i', $info[
'type']))) {
8999 if (is_array($info)) {
9000 if (isset($info[
'type']) && (preg_match(
'/^(double|real|price)/i', $info[
'type']))) {
9017 if (is_array($info)) {
9018 if (isset($info[
'type']) && $info[
'type'] ==
'text') {
9035 if (is_array($info)) {
9036 if (isset($info[
'notnull']) && $info[
'notnull'] !=
'1') {
9053 if (is_array($info)) {
9054 if (isset($info[
'notnull']) && $info[
'notnull'] ==
'-1') {
9071 if (is_array($info)) {
9072 if (isset($info[
'index']) && $info[
'index'] ==
true) {
9094 $queryarray = array();
9095 foreach ($this->fields as $field => $info) {
9097 if ($this->isDate($info)) {
9098 if (empty($this->{$field})) {
9099 $queryarray[$field] =
null;
9101 $queryarray[$field] = $this->db->idate($this->{$field});
9103 } elseif ($this->isDuration($info)) {
9105 if ((isset($this->{$field}) && $this->{$field} !=
'') || !empty($info[
'notnull'])) {
9106 if (!isset($this->{$field})) {
9107 if (!empty($info[
'default'])) {
9108 $queryarray[$field] = $info[
'default'];
9110 $queryarray[$field] = 0;
9113 $queryarray[$field] = (int) $this->{$field};
9116 $queryarray[$field] =
null;
9118 } elseif ($this->isInt($info) || $this->isFloat($info)) {
9119 if ($field ==
'entity' && is_null($this->{$field})) {
9120 $queryarray[$field] = ((int) $conf->entity);
9123 if ((isset($this->{$field}) && $this->{$field} !=
'') || !empty($info[
'notnull'])) {
9124 if (!isset($this->{$field})) {
9125 $queryarray[$field] = 0;
9126 } elseif ($this->isInt($info)) {
9127 $queryarray[$field] = (int) $this->{$field};
9128 } elseif ($this->isFloat($info)) {
9129 $queryarray[$field] = (double) $this->{$field};
9132 $queryarray[$field] =
null;
9138 $queryarray[$field] = $this->{$field};
9141 if ($info[
'type'] ==
'timestamp' && empty($queryarray[$field])) {
9142 unset($queryarray[$field]);
9144 if (!empty($info[
'notnull']) && $info[
'notnull'] == -1 && empty($queryarray[$field])) {
9145 $queryarray[$field] =
null;
9162 foreach ($this->fields as $field => $info) {
9163 if ($this->isDate($info)) {
9164 if (!isset($obj->$field) || is_null($obj->$field) || $obj->$field ===
'' || $obj->$field ===
'0000-00-00 00:00:00' || $obj->$field ===
'1000-01-01 00:00:00') {
9167 $this->$field = $db->jdate($obj->$field);
9169 } elseif ($this->isInt($info)) {
9170 if ($field ==
'rowid') {
9171 $this->
id = (int) $obj->$field;
9173 if ($this->isForcedToNullIfZero($info)) {
9174 if (empty($obj->$field)) {
9175 $this->$field =
null;
9177 $this->$field = (double) $obj->$field;
9180 if (isset($obj->$field) && (!is_null($obj->$field) || (isset($info[
'notnull']) && $info[
'notnull'] == 1))) {
9181 $this->$field = (int) $obj->$field;
9183 $this->$field =
null;
9187 } elseif ($this->isFloat($info)) {
9188 if ($this->isForcedToNullIfZero($info)) {
9189 if (empty($obj->$field)) {
9190 $this->$field =
null;
9192 $this->$field = (double) $obj->$field;
9195 if (isset($obj->$field) && (!is_null($obj->$field) || (isset($info[
'notnull']) && $info[
'notnull'] == 1))) {
9196 $this->$field = (double) $obj->$field;
9198 $this->$field =
null;
9202 $this->$field = isset($obj->$field) ? $obj->$field :
null;
9207 if (!isset($this->fields[
'ref']) && isset($this->
id)) {
9208 $this->
ref = $this->id;
9221 $keys = array_keys($this->fields);
9222 if (!empty($alias)) {
9223 $keys_with_alias = array();
9224 foreach ($keys as $fieldname) {
9225 if (!empty($excludefields)) {
9226 if (in_array($fieldname, $excludefields)) {
9230 $keys_with_alias[] = $alias .
'.' . $fieldname;
9232 return implode(
',', $keys_with_alias);
9234 return implode(
',', $keys);
9245 protected function quote($value, $fieldsentry)
9247 if (is_null($value)) {
9249 } elseif (preg_match(
'/^(int|double|real|price)/i', $fieldsentry[
'type'])) {
9251 } elseif (preg_match(
'/int$/i', $fieldsentry[
'type'])) {
9252 return (
int) $value;
9253 } elseif ($fieldsentry[
'type'] ==
'boolean') {
9260 return "'".$this->db->escape($value).
"'";
9275 dol_syslog(get_class($this).
"::createCommon create", LOG_DEBUG);
9281 $fieldvalues = $this->setSaveQuery();
9283 if (array_key_exists(
'date_creation', $fieldvalues) && empty($fieldvalues[
'date_creation'])) {
9284 $fieldvalues[
'date_creation'] = $this->db->idate($now);
9286 if (array_key_exists(
'fk_user_creat', $fieldvalues) && !($fieldvalues[
'fk_user_creat'] > 0)) {
9287 $fieldvalues[
'fk_user_creat'] = $user->id;
9288 $this->fk_user_creat = $user->id;
9290 if (array_key_exists(
'user_modification_id', $fieldvalues) && !($fieldvalues[
'user_modification_id'] > 0)) {
9291 $fieldvalues[
'user_modification_id'] = $user->id;
9292 $this->user_modification_id = $user->id;
9294 unset($fieldvalues[
'rowid']);
9295 if (array_key_exists(
'ref', $fieldvalues)) {
9301 foreach ($fieldvalues as $k => $v) {
9303 $value = $this->fields[$k];
9304 $values[$k] = $this->quote($v, $value);
9308 foreach ($keys as $key) {
9310 if (preg_match(
'/^integer:/i', $this->fields[$key][
'type']) && $values[$key] ==
'-1') {
9313 if (!empty($this->fields[$key][
'foreignkey']) && $values[$key] ==
'-1') {
9317 if (isset($this->fields[$key][
'notnull']) && $this->fields[$key][
'notnull'] == 1 && (!isset($values[$key]) || $values[$key] ===
'NULL') && is_null($this->fields[$key][
'default'])) {
9319 $langs->load(
"errors");
9320 dol_syslog(
"Mandatory field '".$key.
"' is empty and required into ->fields definition of class");
9321 $this->errors[] = $langs->trans(
"ErrorFieldRequired", $this->fields[$key][
'label']);
9325 if (isset($this->fields[$key][
'notnull']) && $this->fields[$key][
'notnull'] == 1 && (!isset($values[$key]) || $values[$key] ===
'NULL') && !is_null($this->fields[$key][
'default'])) {
9326 $values[$key] = $this->quote($this->fields[$key][
'default'], $this->fields[$key]);
9330 if (preg_match(
'/^integer:/i', $this->fields[$key][
'type']) && empty($values[$key])) {
9331 if (isset($this->fields[$key][
'default'])) {
9332 $values[$key] = ((int) $this->fields[$key][
'default']);
9334 $values[$key] =
'null';
9337 if (!empty($this->fields[$key][
'foreignkey']) && empty($values[$key])) {
9338 $values[$key] =
'null';
9349 $sql =
"INSERT INTO ".$this->db->prefix().$this->table_element;
9350 $sql .=
" (".implode(
", ", $keys).
')';
9351 $sql .=
" VALUES (".implode(
", ", $values).
")";
9353 $res = $this->db->query($sql);
9356 if ($this->db->lasterrno() ==
'DB_ERROR_RECORD_ALREADY_EXISTS') {
9357 $this->errors[] =
"ErrorRefAlreadyExists";
9359 $this->errors[] = $this->db->lasterror();
9365 $this->
id = $this->db->last_insert_id($this->db->prefix().$this->table_element);
9370 if (key_exists(
'ref', $this->fields) && $this->fields[
'ref'][
'notnull'] > 0 && key_exists(
'default', $this->fields[
'ref']) && $this->fields[
'ref'][
'default'] ==
'(PROV)') {
9371 $sql =
"UPDATE ".$this->db->prefix().$this->table_element.
" SET ref = '(PROV".((int) $this->
id).
")' WHERE (ref = '(PROV)' OR ref = '') AND rowid = ".((int) $this->
id);
9372 $resqlupdate = $this->db->query($sql);
9374 if ($resqlupdate ===
false) {
9376 $this->errors[] = $this->db->lasterror();
9378 $this->
ref =
'(PROV'.$this->id.
')';
9385 $result = $this->insertExtraFields();
9392 if (!empty($this->table_element_line) && !empty($this->fk_element)) {
9393 $num = (is_array($this->lines) ? count($this->lines) : 0);
9394 for ($i = 0; $i < $num; $i++) {
9395 $line = $this->lines[$i];
9397 $keyforparent = $this->fk_element;
9398 $line->$keyforparent = $this->id;
9402 if (!is_object($line)) {
9403 $line = (object) $line;
9407 if (method_exists($line,
'insert')) {
9408 $result = $line->insert($user, 1);
9409 } elseif (method_exists($line,
'create')) {
9410 $result = $line->create($user, 1);
9413 $this->error = $line->error;
9414 $this->db->rollback();
9421 if (!$error && !$notrigger) {
9423 $result = $this->call_trigger(strtoupper(get_class($this)).
'_CREATE', $user);
9432 $this->db->rollback();
9435 $this->db->commit();
9451 if (empty($id) && empty($ref) && empty($morewhere)) {
9455 $fieldlist = $this->getFieldList(
't');
9456 if (empty($fieldlist)) {
9460 $sql =
"SELECT ".$fieldlist;
9461 $sql .=
" FROM ".$this->db->prefix().$this->table_element.
' as t';
9464 $sql .=
' WHERE t.rowid = '.((int) $id);
9465 } elseif (!empty($ref)) {
9466 $sql .=
" WHERE t.ref = '".$this->db->escape($ref).
"'";
9468 $sql .=
' WHERE 1 = 1';
9470 if (empty($id) && isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
9471 $sql .=
' AND t.entity IN ('.getEntity($this->element).
')';
9478 $res = $this->db->query($sql);
9480 $obj = $this->db->fetch_object($res);
9482 $this->setVarsFromFetchObj($obj);
9486 $this->fetch_optionals();
9493 $this->error = $this->db->lasterror();
9494 $this->errors[] = $this->error;
9507 $objectlineclassname = get_class($this).
'Line';
9508 if (!class_exists($objectlineclassname)) {
9509 $this->error =
'Error, class '.$objectlineclassname.
' not found during call of fetchLinesCommon';
9513 $objectline =
new $objectlineclassname($this->db);
9515 $sql =
"SELECT ".$objectline->getFieldList(
'l');
9516 $sql .=
" FROM ".$this->db->prefix().$objectline->table_element.
" as l";
9517 $sql .=
" WHERE l.fk_".$this->db->escape($this->element).
" = ".((int) $this->
id);
9521 if (isset($objectline->fields[
'position'])) {
9522 $sql .= $this->db->order(
'position',
'ASC');
9525 $resql = $this->db->query($sql);
9527 $num_rows = $this->db->num_rows($resql);
9529 $this->lines = array();
9530 while ($i < $num_rows) {
9531 $obj = $this->db->fetch_object($resql);
9533 $newline =
new $objectlineclassname($this->db);
9534 $newline->setVarsFromFetchObj($obj);
9536 $this->lines[] = $newline;
9543 $this->error = $this->db->lasterror();
9544 $this->errors[] = $this->error;
9558 global $conf, $langs;
9559 dol_syslog(get_class($this).
"::updateCommon update", LOG_DEBUG);
9570 $fieldvalues = $this->setSaveQuery();
9572 if (array_key_exists(
'date_modification', $fieldvalues) && empty($fieldvalues[
'date_modification'])) {
9573 $fieldvalues[
'date_modification'] = $this->db->idate($now);
9575 if (array_key_exists(
'fk_user_modif', $fieldvalues) && !($fieldvalues[
'fk_user_modif'] > 0)) {
9576 $fieldvalues[
'fk_user_modif'] = $user->id;
9578 unset($fieldvalues[
'rowid']);
9579 if (array_key_exists(
'ref', $fieldvalues)) {
9587 foreach ($fieldvalues as $k => $v) {
9589 $value = $this->fields[$k];
9590 $values[$k] = $this->quote($v, $value);
9591 $tmp[] = $k.
'='.$this->quote($v, $this->fields[$k]);
9595 foreach ($keys as $key) {
9596 if (preg_match(
'/^integer:/i', $this->fields[$key][
'type']) && $values[$key] ==
'-1') {
9599 if (!empty($this->fields[$key][
'foreignkey']) && $values[$key] ==
'-1') {
9612 $sql =
'UPDATE '.$this->db->prefix().$this->table_element.
' SET '.implode(
', ', $tmp).
' WHERE rowid='.((int) $this->
id);
9617 $res = $this->db->query($sql);
9620 $this->errors[] = $this->db->lasterror();
9626 $result = $this->insertExtraFields();
9633 if (!$error && !$notrigger) {
9635 $result = $this->call_trigger(strtoupper(get_class($this)).
'_MODIFY', $user);
9644 $this->db->rollback();
9647 $this->db->commit();
9662 dol_syslog(get_class($this).
"::deleteCommon delete", LOG_DEBUG);
9668 if ($forcechilddeletion) {
9669 foreach ($this->childtables as $table) {
9670 $sql =
"DELETE FROM ".$this->db->prefix().$table.
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
9671 $resql = $this->db->query($sql);
9673 $this->error = $this->db->lasterror();
9674 $this->errors[] = $this->error;
9675 $this->db->rollback();
9679 } elseif (!empty($this->childtables)) {
9680 $objectisused = $this->isObjectUsed($this->
id);
9681 if (!empty($objectisused)) {
9682 dol_syslog(get_class($this).
"::deleteCommon Can't delete record as it has some child", LOG_WARNING);
9683 $this->error =
'ErrorRecordHasChildren';
9684 $this->errors[] = $this->error;
9685 $this->db->rollback();
9691 if (is_array($this->childtablesoncascade) && !empty($this->childtablesoncascade)) {
9692 foreach ($this->childtablesoncascade as $table) {
9693 $deleteFromObject = explode(
':', $table);
9694 if (count($deleteFromObject) >= 2) {
9695 $className = str_replace(
'@',
'', $deleteFromObject[0]);
9696 $filePath = $deleteFromObject[1];
9697 $columnName = $deleteFromObject[2];
9698 $TMoreSQL = array();
9699 $more_sql = $deleteFromObject[3];
9700 if (!empty($more_sql)) {
9701 $TMoreSQL[
'customsql'] = $more_sql;
9704 $childObject =
new $className($this->db);
9705 if (method_exists($childObject,
'deleteByParentField')) {
9706 $result = $childObject->deleteByParentField($this->
id, $columnName, $TMoreSQL);
9709 $this->errors[] = $childObject->error;
9714 $this->errors[] =
"You defined a cascade delete on an object $childObject but there is no method deleteByParentField for it";
9719 $this->errors[] =
'Cannot include child class file '.$filePath;
9724 $sql =
"DELETE FROM ".$this->db->prefix().$table.
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
9726 $resql = $this->db->query($sql);
9729 $this->error = $this->db->lasterror();
9730 $this->errors[] = $this->error;
9740 $result = $this->call_trigger(strtoupper(get_class($this)).
'_DELETE', $user);
9750 $res = $this->deleteEcmFiles(1);
9757 $res = $this->deleteObjectLinked();
9762 if (!$error && !empty($this->isextrafieldmanaged)) {
9763 $result = $this->deleteExtraFields();
9770 $sql =
'DELETE FROM '.$this->db->prefix().$this->table_element.
' WHERE rowid='.((int) $this->
id);
9772 $resql = $this->db->query($sql);
9775 $this->errors[] = $this->db->lasterror();
9781 $this->db->rollback();
9784 $this->db->commit();
9806 if (!empty($parentId) && !empty($parentField)) {
9809 $sql =
"SELECT rowid FROM ".$this->db->prefix().$this->table_element;
9810 $sql .=
" WHERE ".$parentField.
" = ".(int) $parentId;
9813 $sqlwhere = array();
9814 if (count($filter) > 0) {
9815 foreach ($filter as $key => $value) {
9816 if ($key ==
'customsql') {
9817 $sqlwhere[] = $value;
9818 } elseif (strpos($value,
'%') ===
false) {
9819 $sqlwhere[] = $key.
" IN (".$this->db->sanitize($this->db->escape($value)).
")";
9821 $sqlwhere[] = $key.
" LIKE '%".$this->db->escape($value).
"%'";
9825 if (count($sqlwhere) > 0) {
9826 $sql .=
" AND (".implode(
" ".$filtermode.
" ", $sqlwhere).
")";
9829 $resql = $this->db->query($sql);
9831 $this->errors[] = $this->db->lasterror();
9834 while ($obj = $this->db->fetch_object($resql)) {
9835 $result = $this->fetch($obj->rowid);
9838 $this->errors[] = $this->error;
9840 if (get_class($this) ==
'Contact') {
9841 $result = $this->
delete();
9843 $result = $this->
delete($user);
9847 $this->errors[] = $this->error;
9855 if (empty($error)) {
9856 $this->db->commit();
9859 $this->error = implode(
', ', $this->errors);
9860 $this->db->rollback();
9882 $tmpforobjectclass = get_class($this);
9883 $tmpforobjectlineclass = ucfirst($tmpforobjectclass).
'Line';
9888 $result = $this->call_trigger(
'LINE'.strtoupper($tmpforobjectclass).
'_DELETE', $user);
9894 if (empty($error)) {
9895 $sql =
"DELETE FROM ".$this->db->prefix().$this->table_element_line;
9896 $sql .=
" WHERE rowid = ".((int) $idline);
9898 $resql = $this->db->query($sql);
9900 $this->error =
"Error ".$this->db->lasterror();
9905 if (empty($error)) {
9907 $tmpobjectline =
new $tmpforobjectlineclass($this->db);
9908 if (!isset($tmpobjectline->isextrafieldmanaged) || !empty($tmpobjectline->isextrafieldmanaged)) {
9909 $tmpobjectline->id = $idline;
9910 $result = $tmpobjectline->deleteExtraFields();
9913 $this->error =
"Error ".get_class($this).
"::deleteLineCommon deleteExtraFields error -4 ".$tmpobjectline->error;
9918 if (empty($error)) {
9919 $this->db->commit();
9922 dol_syslog(get_class($this).
"::deleteLineCommon ERROR:".$this->error, LOG_ERR);
9923 $this->db->rollback();
9944 $statusfield =
'status';
9945 if (in_array($this->element, array(
'don',
'donation',
'shipping'))) {
9946 $statusfield =
'fk_statut';
9949 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
9950 $sql .=
" SET ".$statusfield.
" = ".((int) $status);
9951 $sql .=
" WHERE rowid = ".((int) $this->
id);
9953 if ($this->db->query($sql)) {
9955 $this->oldcopy = clone $this;
9958 if (!$error && !$notrigger) {
9960 $result = $this->call_trigger($triggercode, $user);
9967 $this->status = $status;
9968 $this->db->commit();
9971 $this->db->rollback();
9975 $this->error = $this->db->error();
9976 $this->db->rollback();
9993 $this->specimen = 1;
9995 'label' =>
'This is label',
9996 'ref' =>
'ABCD1234',
9997 'description' =>
'This is a description',
9999 'note_public' =>
'Public note',
10000 'note_private' =>
'Private note',
10001 'date_creation' => (
dol_now() - 3600 * 48),
10002 'date_modification' => (
dol_now() - 3600 * 24),
10003 'fk_user_creat' => $user->id,
10004 'fk_user_modif' => $user->id,
10007 foreach ($fields as $key => $value) {
10008 if (array_key_exists($key, $this->fields)) {
10009 $this->{$key} = $value;
10014 if (property_exists($this,
'fields')) {
10015 foreach ($this->fields as $key => $value) {
10017 if (array_key_exists($key, $fields)) {
10021 if (!empty($value[
'default'])) {
10022 $this->$key = $value[
'default'];
10039 require_once DOL_DOCUMENT_ROOT.
'/core/class/comment.class.php';
10041 $comment =
new Comment($this->db);
10042 $result = $comment->fetchAllFor($this->element, $this->
id);
10044 $this->errors = array_merge($this->errors, $comment->errors);
10047 $this->comments = $comment->comments;
10049 return count($this->comments);
10059 return count($this->comments);
10070 if (!is_array($parameters)) {
10073 foreach ($parameters as $parameter) {
10074 if (isset($this->$parameter)) {
10075 $this->$parameter = trim($this->$parameter);
10094 require_once DOL_DOCUMENT_ROOT.
'/categories/class/categorie.class.php';
10098 $existing = $c->containing($this->
id, $type_categ,
'id');
10118 if (!is_array($categories)) {
10119 $categories = array($categories);
10122 dol_syslog(get_class($this).
"::setCategoriesCommon Oject Id:".$this->
id.
' type_categ:'.$type_categ.
' nb tag add:'.count($categories), LOG_DEBUG);
10124 require_once DOL_DOCUMENT_ROOT.
'/categories/class/categorie.class.php';
10126 if (empty($type_categ)) {
10127 dol_syslog(__METHOD__.
': Type '.$type_categ.
'is an unknown category type. Done nothing.', LOG_ERR);
10133 $existing = $c->containing($this->
id, $type_categ,
'id');
10134 if ($remove_existing) {
10136 if (is_array($existing)) {
10137 $to_del = array_diff($existing, $categories);
10138 $to_add = array_diff($categories, $existing);
10141 $to_add = $categories;
10145 $to_add = array_diff($categories, $existing);
10152 foreach ($to_del as $del) {
10153 if ($c->fetch($del) > 0) {
10154 $result=$c->del_type($this, $type_categ);
10157 $this->error = $c->error;
10158 $this->errors = $c->errors;
10165 foreach ($to_add as $add) {
10166 if ($c->fetch($add) > 0) {
10167 $result = $c->add_type($this, $type_categ);
10170 $this->error = $c->error;
10171 $this->errors = $c->errors;
10179 return $error ? (-1 * $error) : $ok;
10192 $this->db->begin();
10194 if (empty($type)) {
10195 $type = $this->table_element;
10198 require_once DOL_DOCUMENT_ROOT.
'/categories/class/categorie.class.php';
10199 $categorystatic =
new Categorie($this->db);
10201 $sql =
"INSERT INTO ".$this->db->prefix().
"categorie_".(empty($categorystatic->MAP_CAT_TABLE[$type]) ? $type : $categorystatic->MAP_CAT_TABLE[$type]).
" (fk_categorie, fk_product)";
10202 $sql .=
" SELECT fk_categorie, $toId FROM ".$this->db->prefix().
"categorie_".(empty($categorystatic->MAP_CAT_TABLE[$type]) ? $type : $categorystatic->MAP_CAT_TABLE[$type]);
10203 $sql .=
" WHERE fk_product = ".((int) $fromId);
10205 if (!$this->db->query($sql)) {
10206 $this->error = $this->db->lasterror();
10207 $this->db->rollback();
10211 $this->db->commit();
10225 $this->db->begin();
10229 switch ($this->element) {
10231 $element =
'propale';
10234 $element =
'produit';
10236 case 'order_supplier':
10237 $element =
'fournisseur/commande';
10239 case 'invoice_supplier':
10240 $element =
'fournisseur/facture/'.get_exdir($this->
id, 2, 0, 1, $this,
'invoice_supplier');
10243 $element =
'expedition/sending';
10246 $element = $this->element;
10250 $sql =
"DELETE FROM ".$this->db->prefix().
"ecm_files_extrafields WHERE fk_object IN (";
10251 $sql .=
" SELECT rowid FROM ".$this->db->prefix().
"ecm_files WHERE filename LIKE '".$this->db->escape($this->
ref).
"%'";
10252 $sql .=
" AND filepath = '".$this->db->escape($element).
"/".$this->db->escape($this->
ref).
"' AND entity = ".((int) $conf->entity);
10255 if (!$this->db->query($sql)) {
10256 $this->error = $this->db->lasterror();
10257 $this->db->rollback();
10262 $sql =
"DELETE FROM ".$this->db->prefix().
"ecm_files";
10263 $sql .=
" WHERE filename LIKE '".$this->db->escape($this->
ref).
"%'";
10264 $sql .=
" AND filepath = '".$this->db->escape($element).
"/".$this->db->escape($this->
ref).
"' AND entity = ".((int) $conf->entity);
10266 if (!$this->db->query($sql)) {
10267 $this->error = $this->db->lasterror();
10268 $this->db->rollback();
10275 $sql =
'DELETE FROM '.$this->db->prefix().
"ecm_files_extrafields";
10276 $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).
")";
10277 $resql = $this->db->query($sql);
10279 $this->error = $this->db->lasterror();
10280 $this->db->rollback();
10284 $sql =
'DELETE FROM '.$this->db->prefix().
"ecm_files";
10285 $sql .=
" WHERE src_object_type = '".$this->db->escape($this->table_element.(empty($this->module) ?
"" :
"@".$this->module)).
"' AND src_object_id = ".((int) $this->
id);
10286 $resql = $this->db->query($sql);
10288 $this->error = $this->db->lasterror();
10289 $this->db->rollback();
10294 $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.
liste_contact($statusoflink=-1, $source='external', $list=0, $code='', $status=-1, $arrayoftcids=array())
Get array of all contacts for an object.
fetchObjectFrom($table, $field, $key, $element=null)
Load object from specific field.
fetch_thirdparty($force_thirdparty_id=0)
Load the third party of object, from id $this->socid or $this->fk_soc, into this->thirdparty.
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
validateField($fields, $fieldKey, $fieldValue)
Return validation test result for a field.
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...
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.
update_note($note, $suffix='', $notrigger=0)
Update note of element.
getFullAddress($withcountry=0, $sep="\n", $withregion=0, $extralangcode='')
Return full address of contact.
fetch_project()
Load the project with id $this->fk_project into this->project.
setStatut($status, $elementId=null, $elementType='', $trigkey='', $fieldstatus='fk_statut')
Set status of an object.
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).
getFieldList($alias='', $excludefields=array())
Function to concat keys of fields.
getNbComments()
Return nb comments already posted.
setVarsFromFetchObj(&$obj)
Function to load data from a SQL pointer into properties of current object $this.
printObjectLines($action, $seller, $buyer, $selected=0, $dateSelector=0, $defaulttpldir='/core/tpl')
Return HTML table for object lines TODO Move this into an output class file (htmlline....
getChildrenOfLine($id, $includealltree=0)
Get children of line.
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 return the array of data key-value from the ->fields and all the ->properties of an objec...
setValuesForExtraLanguages($onlykey='')
Fill array_options property of object by extrafields value (using for data sent by forms)
insertExtraLanguages($trigger='', $userused=null)
Add/Update all extra fields values for the current object.
setTransportMode($id)
Change the transport mode methods.
isArray($info)
Function test if type is array.
isInt($info)
Function test if type is integer.
fetchObjectLinked($sourceid=null, $sourcetype='', $targetid=null, $targettype='', $clause='OR', $alsosametype=1, $orderby='sourcetype', $loadalsoobjects=1)
Fetch array of objects linked to current object (object of enabled modules only).
delete_contact($rowid, $notrigger=0)
Delete a link to contact line.
updateLineUp($rowid, $rang)
Update position of line up (rang)
fetch_user($userid)
Load the user with id $userid into this->user.
errorsToString()
Method to output saved errors.
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.
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.
load_previous_next_ref($filter, $fieldid, $nodbprefix=0)
Load properties id_previous and id_next by comparing $fieldid with $this->ref.
setCategoriesCommon($categories, $type_categ='', $remove_existing=true)
Sets object to given categories.
fetchValuesForExtraLanguages()
Function to get alternative languages of a data into $this->array_languages This method is NOT called...
fetchNoCompute($id)
Function to make a fetch but set environment to avoid to load computed values before.
line_max($fk_parent_line=0)
Get max value used for position of line (rang)
getJSListDependancies($type='_extra')
setProject($projectid, $notrigger=0)
Link element with a project.
isForcedToNullIfZero($info)
Function test if field is forced to null if zero or empty.
line_ajaxorder($rows)
Update position of line with ajax (rang)
printOriginLinesList($restrictlist='', $selectedLines=array())
Return HTML table table of source object lines TODO Move this and previous function into output html ...
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.
print $langs trans("Ref").' m m m statut
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.
convertSecondToTime($iSecond, $format='all', $lengthOfDay=86400, $lengthOfWeek=7)
Return, in clear text, value of a number of seconds in days, hours and minutes.
dol_meta_create($object)
Create a meta file with document file into same directory.
dol_delete_file($file, $disableglob=0, $nophperrors=0, $nohook=0, $object=null, $allowdotdot=false, $indexdatabase=1, $nolog=0)
Remove a file or several files with a mask.
dol_is_file($pathoffile)
Return if path is a file.
dol_dir_list($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.
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...
if(!function_exists( 'dol_getprefix')) dol_include_once($relpath, $classname='')
Make an include_once using default root and alternate root if it fails.
dol_clone($object, $native=0)
Create a clone of instance of object (new instance with same value for each properties) With native =...
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.
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.
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.
publicphonebutton2 phonegreen basiclayout basiclayout TotalHT VATCode TotalVAT TotalLT1 TotalLT2 TotalTTC TotalHT clearboth nowraponall right right takeposterminal SELECT e rowid
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.