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;
635 public $next_prev_filter;
640 public $specimen = 0;
654 protected $labelStatusShort;
659 public $showphoto_on_popup;
664 public $nb = array();
674 public $extraparams = array();
679 protected $childtables = array();
686 protected $childtablesoncascade = array();
706 $sql =
"SELECT rowid, ref, ref_ext";
707 $sql .=
" FROM ".$db->prefix().$element;
708 $sql .=
" WHERE entity IN (".getEntity($element).
")";
711 $sql .=
" AND rowid = ".((int) $id);
713 $sql .=
" AND ref = '".$db->escape($ref).
"'";
714 } elseif ($ref_ext) {
715 $sql .=
" AND ref_ext = '".$db->escape($ref_ext).
"'";
717 $error =
'ErrorWrongParameters';
721 if ($ref || $ref_ext) {
722 $sql .=
" AND entity = ".((int) $conf->entity);
725 dol_syslog(get_class().
"::isExistingObject", LOG_DEBUG);
726 $resql = $db->query($sql);
728 $num = $db->num_rows($resql);
746 if (!empty($object->error)) {
747 $this->error = $object->error;
749 if (!empty($object->errors)) {
750 $this->errors = array_merge($this->errors, $object->errors);
775 global $action, $extrafields, $langs, $hookmanager;
778 $MAX_EXTRAFIELDS_TO_SHOW_IN_TOOLTIP =
getDolGlobalInt(
'MAX_EXTRAFIELDS_TO_SHOW_IN_TOOLTIP', 3);
784 if (!empty($extrafields->attributes[$this->table_element][
'label'])) {
785 foreach ($extrafields->attributes[$this->table_element][
'label'] as $key => $val) {
786 if ($extrafields->attributes[$this->table_element][
'type'][$key] ==
'separate') {
789 if ($count >= abs($MAX_EXTRAFIELDS_TO_SHOW_IN_TOOLTIP)) {
790 $datas[
'more_extrafields'] =
'<br>...';
794 if ($enabled && isset($extrafields->attributes[$this->table_element][
'enabled'][$key])) {
795 $enabled =
dol_eval($extrafields->attributes[$this->table_element][
'enabled'][$key], 1, 1,
'2');
797 if ($enabled && isset($extrafields->attributes[$this->table_element][
'list'][$key])) {
798 $enabled =
dol_eval($extrafields->attributes[$this->table_element][
'list'][$key], 1, 1,
'2');
801 if ($perms && isset($extrafields->attributes[$this->table_element][
'perms'][$key])) {
802 $perms =
dol_eval($extrafields->attributes[$this->table_element][
'perms'][$key], 1, 1,
'2');
804 if (empty($enabled)) {
807 if (abs($enabled) != 1 && abs($enabled) != 3 && abs($enabled) != 5 && abs($enabled) != 4) {
813 if (!empty($extrafields->attributes[$this->table_element][
'langfile'][$key])) {
814 $langs->load($extrafields->attributes[$this->table_element][
'langfile'][$key]);
816 $labelextra = $langs->trans((
string) $extrafields->attributes[$this->table_element][
'label'][$key]);
817 if ($extrafields->attributes[$this->table_element][
'type'][$key] ==
'separate') {
818 $datas[$key]=
'<br><b><u>'. $labelextra .
'</u></b>';
820 $value = (empty($this->array_options[
'options_' . $key]) ?
'' : $this->array_options[
'options_' . $key]);
821 $datas[$key]=
'<br><b>'. $labelextra .
':</b> ' . $extrafields->showOutputField($key, $value,
'', $this->table_element);
827 $hookmanager->initHooks(array($this->element .
'dao'));
829 'tooltipcontentarray' => &$datas,
833 $hookmanager->executeHooks(
'getTooltipContent', $parameters, $this, $action);
836 $label = implode($datas);
849 return $this->error.(is_array($this->errors) ? (($this->error !=
'' ?
', ' :
'').join(
', ', $this->errors)) :
'');
863 $parameters = array(
'objref'=>$objref);
865 $reshook = $hookmanager->executeHooks(
'getFormatedCustomerRef', $parameters, $this, $action);
867 return $hookmanager->resArray[
'objref'];
869 return $objref.(isset($hookmanager->resArray[
'objref']) ? $hookmanager->resArray[
'objref'] :
'');
882 $parameters = array(
'objref'=>$objref);
884 $reshook = $hookmanager->executeHooks(
'getFormatedSupplierRef', $parameters, $this, $action);
886 return $hookmanager->resArray[
'objref'];
888 return $objref.(isset($hookmanager->resArray[
'objref']) ? $hookmanager->resArray[
'objref'] :
'');
900 public function getFullAddress($withcountry = 0, $sep =
"\n", $withregion = 0, $extralangcode =
'')
902 if ($withcountry && $this->country_id && (empty($this->country_code) || empty($this->country))) {
903 require_once DOL_DOCUMENT_ROOT.
'/core/lib/company.lib.php';
904 $tmparray =
getCountry($this->country_id,
'all');
905 $this->country_code = $tmparray[
'code'];
906 $this->country = $tmparray[
'label'];
909 if ($withregion && $this->state_id && (empty($this->state_code) || empty($this->state) || empty($this->region) || empty($this->region_code))) {
910 require_once DOL_DOCUMENT_ROOT.
'/core/lib/company.lib.php';
911 $tmparray =
getState($this->state_id,
'all', 0, 1);
912 $this->state_code = $tmparray[
'code'];
913 $this->state = $tmparray[
'label'];
914 $this->region_code = $tmparray[
'region_code'];
915 $this->region = $tmparray[
'region'];
932 global $user, $dolibarr_main_url_root;
934 if (empty($this->last_main_doc)) {
938 include_once DOL_DOCUMENT_ROOT.
'/ecm/class/ecmfiles.class.php';
940 $result = $ecmfile->fetch(0,
'', $this->last_main_doc);
942 $this->error = $ecmfile->error;
943 $this->errors = $ecmfile->errors;
947 if (empty($ecmfile->id)) {
950 require_once DOL_DOCUMENT_ROOT.
'/core/lib/security2.lib.php';
972 } elseif (empty($ecmfile->share)) {
975 require_once DOL_DOCUMENT_ROOT.
'/core/lib/security2.lib.php';
977 $ecmfile->update($user);
983 $urlwithouturlroot = preg_replace(
'/'.preg_quote(DOL_URL_ROOT,
'/').
'$/i',
'', trim($dolibarr_main_url_root));
987 $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT;
996 if (!empty($ecmfile->share)) {
997 $paramlink .= ($paramlink ?
'&' :
'').
'hashp='.$ecmfile->share;
999 if ($forcedownload) {
1000 $paramlink .= ($paramlink ?
'&' :
'').
'attachment=1';
1003 if ($relativelink) {
1004 $linktoreturn =
'document.php'.($paramlink ?
'?'.$paramlink :
'');
1006 $linktoreturn = $urlwithroot.
'/document.php'.($paramlink ?
'?'.$paramlink :
'');
1010 return $linktoreturn;
1024 public function add_contact($fk_socpeople, $type_contact, $source =
'external', $notrigger = 0)
1027 global $user, $langs;
1030 dol_syslog(get_class($this).
"::add_contact $fk_socpeople, $type_contact, $source, $notrigger");
1033 if ($fk_socpeople <= 0) {
1034 $langs->load(
"errors");
1035 $this->error = $langs->trans(
"ErrorWrongValueForParameterX",
"1");
1036 dol_syslog(get_class($this).
"::add_contact ".$this->error, LOG_ERR);
1039 if (!$type_contact) {
1040 $langs->load(
"errors");
1041 $this->error = $langs->trans(
"ErrorWrongValueForParameterX",
"2");
1042 dol_syslog(get_class($this).
"::add_contact ".$this->error, LOG_ERR);
1046 $id_type_contact = 0;
1047 if (is_numeric($type_contact)) {
1048 $id_type_contact = $type_contact;
1051 $sql =
"SELECT tc.rowid";
1052 $sql .=
" FROM ".$this->db->prefix().
"c_type_contact as tc";
1053 $sql .=
" WHERE tc.element='".$this->db->escape($this->element).
"'";
1054 $sql .=
" AND tc.source='".$this->db->escape($source).
"'";
1055 $sql .=
" AND tc.code='".$this->db->escape($type_contact).
"' AND tc.active=1";
1057 $resql = $this->db->query($sql);
1059 $obj = $this->db->fetch_object($resql);
1061 $id_type_contact = $obj->rowid;
1066 if ($id_type_contact == 0) {
1067 dol_syslog(
"CODE_NOT_VALID_FOR_THIS_ELEMENT: Code type of contact '".$type_contact.
"' does not exists or is not active for element ".$this->element.
", we can ignore it");
1075 $already_added =
false;
1076 if (is_array($TListeContacts) && !empty($TListeContacts)) {
1077 foreach ($TListeContacts as $array_contact) {
1078 if ($array_contact[
'status'] == 4 && $array_contact[
'id'] == $fk_socpeople && $array_contact[
'fk_c_type_contact'] == $id_type_contact) {
1079 $already_added =
true;
1085 if (!$already_added) {
1089 $sql =
"INSERT INTO ".$this->db->prefix().
"element_contact";
1090 $sql .=
" (element_id, fk_socpeople, datecreate, statut, fk_c_type_contact) ";
1091 $sql .=
" VALUES (".$this->id.
", ".((int) $fk_socpeople).
" , ";
1092 $sql .=
"'".$this->db->idate($datecreate).
"'";
1093 $sql .=
", 4, ".((int) $id_type_contact);
1096 $resql = $this->db->query($sql);
1099 $result = $this->
call_trigger(strtoupper($this->element).
'_ADD_CONTACT', $user);
1101 $this->db->rollback();
1106 $this->db->commit();
1109 if ($this->db->errno() ==
'DB_ERROR_RECORD_ALREADY_EXISTS') {
1110 $this->error = $this->db->errno();
1111 $this->db->rollback();
1114 $this->error = $this->db->lasterror();
1115 $this->db->rollback();
1135 $contacts = $objFrom->liste_contact(-1, $source);
1136 foreach ($contacts as $contact) {
1137 if ($this->
add_contact($contact[
'id'], $contact[
'fk_c_type_contact'], $contact[
'source']) < 0) {
1154 public function update_contact($rowid, $statut, $type_contact_id = 0, $fk_socpeople = 0)
1158 $sql =
"UPDATE ".$this->db->prefix().
"element_contact set";
1159 $sql .=
" statut = ".$statut;
1160 if ($type_contact_id) {
1161 $sql .=
", fk_c_type_contact = ".((int) $type_contact_id);
1163 if ($fk_socpeople) {
1164 $sql .=
", fk_socpeople = ".((int) $fk_socpeople);
1166 $sql .=
" where rowid = ".((int) $rowid);
1167 $resql = $this->db->query($sql);
1171 $this->error = $this->db->lasterror();
1193 if (!$error && empty($notrigger)) {
1195 $this->context[
'contact_id'] = ((int) $rowid);
1196 $result = $this->
call_trigger(strtoupper($this->element).
'_DELETE_CONTACT', $user);
1204 dol_syslog(get_class($this).
"::delete_contact", LOG_DEBUG);
1206 $sql =
"DELETE FROM ".MAIN_DB_PREFIX.
"element_contact";
1207 $sql .=
" WHERE rowid = ".((int) $rowid);
1209 $result = $this->db->query($sql);
1212 $this->errors[] = $this->db->lasterror();
1217 $this->db->commit();
1220 $this->error = $this->db->lasterror();
1221 $this->db->rollback();
1241 if (!empty($typeContact)) {
1242 foreach ($typeContact as $key => $value) {
1243 array_push($temp, $key);
1245 $listId = implode(
",", $temp);
1250 if (empty($listId)) {
1254 $sql =
"DELETE FROM ".$this->db->prefix().
"element_contact";
1255 $sql .=
" WHERE element_id = ".((int) $this->
id);
1256 $sql .=
" AND fk_c_type_contact IN (".$this->db->sanitize($listId).
")";
1258 dol_syslog(get_class($this).
"::delete_linked_contact", LOG_DEBUG);
1259 if ($this->db->query($sql)) {
1262 $this->error = $this->db->lasterror();
1279 public function liste_contact($statusoflink = -1, $source =
'external', $list = 0, $code =
'', $status = -1, $arrayoftcids = array())
1286 $sql =
"SELECT ec.rowid, ec.statut as statuslink, ec.fk_socpeople as id, ec.fk_c_type_contact";
1287 if ($source ==
'internal') {
1288 $sql .=
", '-1' as socid, t.statut as statuscontact, t.login, t.photo";
1290 if ($source ==
'external' || $source ==
'thirdparty') {
1291 $sql .=
", t.fk_soc as socid, t.statut as statuscontact";
1293 $sql .=
", t.civility as civility, t.lastname as lastname, t.firstname, t.email";
1294 $sql .=
", tc.source, tc.element, tc.code, tc.libelle";
1295 $sql .=
" FROM ".$this->db->prefix().
"c_type_contact tc,";
1296 $sql .=
" ".$this->db->prefix().
"element_contact ec";
1297 if ($source ==
'internal') {
1298 $sql .=
" LEFT JOIN ".$this->db->prefix().
"user t on ec.fk_socpeople = t.rowid";
1300 if ($source ==
'external' || $source ==
'thirdparty') {
1301 $sql .=
" LEFT JOIN ".$this->db->prefix().
"socpeople t on ec.fk_socpeople = t.rowid";
1303 $sql .=
" WHERE ec.element_id = ".((int) $this->
id);
1304 $sql .=
" AND ec.fk_c_type_contact = tc.rowid";
1305 $sql .=
" AND tc.element = '".$this->db->escape($this->element).
"'";
1307 $sql .=
" AND tc.code = '".$this->db->escape($code).
"'";
1309 if ($source ==
'internal') {
1310 $sql .=
" AND tc.source = 'internal'";
1312 $sql .=
" AND t.statut = ".((int) $status);
1315 if ($source ==
'external' || $source ==
'thirdparty') {
1316 $sql .=
" AND tc.source = 'external'";
1318 $sql .=
" AND t.statut = ".((int) $status);
1321 $sql .=
" AND tc.active = 1";
1322 if ($statusoflink >= 0) {
1323 $sql .=
" AND ec.statut = ".((int) $statusoflink);
1325 $sql .=
" ORDER BY t.lastname ASC";
1327 dol_syslog(get_class($this).
"::liste_contact", LOG_DEBUG);
1328 $resql = $this->db->query($sql);
1330 $num = $this->db->num_rows($resql);
1333 $obj = $this->db->fetch_object($resql);
1336 $transkey =
"TypeContact_".$obj->element.
"_".$obj->source.
"_".$obj->code;
1337 $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle);
1339 'parentId' => $this->
id,
1340 'source' => $obj->source,
1341 'socid' => $obj->socid,
1343 'nom' => $obj->lastname,
1344 'civility' => $obj->civility,
1345 'lastname' => $obj->lastname,
1346 'firstname' => $obj->firstname,
1347 'email'=>$obj->email,
1348 'login'=> (empty($obj->login) ?
'' : $obj->login),
1349 'photo' => (empty($obj->photo) ?
'' : $obj->photo),
1350 'statuscontact' => $obj->statuscontact,
1351 'rowid' => $obj->rowid,
1352 'code' => $obj->code,
1353 'libelle' => $libelle_type,
1354 'status' => $obj->statuslink,
1355 'fk_c_type_contact' => $obj->fk_c_type_contact
1358 $tab[$i] = $obj->id;
1366 $this->error = $this->db->lasterror();
1381 $sql =
"SELECT ec.datecreate, ec.statut, ec.fk_socpeople, ec.fk_c_type_contact,";
1382 $sql .=
" tc.code, tc.libelle";
1383 $sql .=
" FROM (".$this->db->prefix().
"element_contact as ec, ".$this->db->prefix().
"c_type_contact as tc)";
1384 $sql .=
" WHERE ec.rowid =".((int) $rowid);
1385 $sql .=
" AND ec.fk_c_type_contact=tc.rowid";
1386 $sql .=
" AND tc.element = '".$this->db->escape($this->element).
"'";
1388 dol_syslog(get_class($this).
"::swapContactStatus", LOG_DEBUG);
1389 $resql = $this->db->query($sql);
1391 $obj = $this->db->fetch_object($resql);
1392 $newstatut = ($obj->statut == 4) ? 5 : 4;
1394 $this->db->free($resql);
1397 $this->error = $this->db->error();
1414 public function liste_type_contact($source =
'internal', $order =
'position', $option = 0, $activeonly = 0, $code =
'')
1419 if (empty($order)) {
1420 $order =
'position';
1422 if ($order ==
'position') {
1427 $sql =
"SELECT DISTINCT tc.rowid, tc.code, tc.libelle, tc.position";
1428 $sql .=
" FROM ".$this->db->prefix().
"c_type_contact as tc";
1429 $sql .=
" WHERE tc.element='".$this->db->escape($this->element).
"'";
1430 if ($activeonly == 1) {
1431 $sql .=
" AND tc.active=1";
1433 if (!empty($source) && $source !=
'all') {
1434 $sql .=
" AND tc.source='".$this->db->escape($source).
"'";
1436 if (!empty($code)) {
1437 $sql .=
" AND tc.code='".$this->db->escape($code).
"'";
1439 $sql .= $this->db->order($order,
'ASC');
1442 $resql = $this->db->query($sql);
1444 $num = $this->db->num_rows($resql);
1447 $obj = $this->db->fetch_object($resql);
1449 $transkey =
"TypeContact_".$this->element.
"_".$source.
"_".$obj->code;
1450 $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle);
1451 if (empty($option)) {
1452 $tab[$obj->rowid] = $libelle_type;
1454 $tab[$obj->code] = $libelle_type;
1460 $this->error = $this->db->lasterror();
1477 public function listeTypeContacts($source =
'internal', $option = 0, $activeonly = 0, $code =
'', $element =
'', $excludeelement =
'')
1479 global $langs, $conf;
1481 $langs->loadLangs(array(
'bills',
'contracts',
'interventions',
'orders',
'projects',
'propal',
'ticket',
'agenda'));
1485 $sql =
"SELECT DISTINCT tc.rowid, tc.code, tc.libelle, tc.position, tc.element";
1486 $sql .=
" FROM ".$this->db->prefix().
"c_type_contact as tc";
1488 $sqlWhere = array();
1489 if (!empty($element)) {
1490 $sqlWhere[] =
" tc.element='".$this->db->escape($element).
"'";
1492 if (!empty($excludeelement)) {
1493 $sqlWhere[] =
" tc.element <> '".$this->db->escape($excludeelement).
"'";
1496 if ($activeonly == 1) {
1497 $sqlWhere[] =
" tc.active=1";
1500 if (!empty($source) && $source !=
'all') {
1501 $sqlWhere[] =
" tc.source='".$this->db->escape($source).
"'";
1504 if (!empty($code)) {
1505 $sqlWhere[] =
" tc.code='".$this->db->escape($code).
"'";
1508 if (count($sqlWhere) > 0) {
1509 $sql .=
" WHERE ".implode(
' AND ', $sqlWhere);
1512 $sql .= $this->db->order(
'tc.element, tc.position',
'ASC');
1515 $resql = $this->db->query($sql);
1517 $num = $this->db->num_rows($resql);
1519 $langs->loadLangs(array(
"propal",
"orders",
"bills",
"suppliers",
"contracts",
"supplier_proposal"));
1521 while ($obj = $this->db->fetch_object($resql)) {
1522 $modulename = $obj->element;
1523 if (strpos($obj->element,
'project') !==
false) {
1524 $modulename =
'projet';
1525 } elseif ($obj->element ==
'contrat') {
1526 $element =
'contract';
1527 } elseif ($obj->element ==
'action') {
1528 $modulename =
'agenda';
1529 } elseif (strpos($obj->element,
'supplier') !==
false && $obj->element !=
'supplier_proposal') {
1530 $modulename =
'fournisseur';
1531 } elseif (strpos($obj->element,
'supplier') !==
false && $obj->element !=
'supplier_proposal') {
1532 $modulename =
'fournisseur';
1534 if (!empty($conf->{$modulename}->enabled)) {
1535 $libelle_element = $langs->trans(
'ContactDefault_'.$obj->element);
1536 $tmpelement = $obj->element;
1537 $transkey =
"TypeContact_".$tmpelement.
"_".$source.
"_".$obj->code;
1538 $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle);
1539 if (empty($option)) {
1540 $tab[$obj->rowid] = $libelle_element.
' - '.$libelle_type;
1542 $tab[$obj->rowid] = $libelle_element.
' - '.$libelle_type;
1549 $this->error = $this->db->lasterror();
1572 if ($this->element ==
'shipping' && $this->origin_id != 0) {
1573 $id = $this->origin_id;
1574 $element =
'commande';
1575 } elseif ($this->element ==
'reception' && $this->origin_id != 0) {
1576 $id = $this->origin_id;
1577 $element =
'order_supplier';
1580 $element = $this->element;
1583 $sql =
"SELECT ec.fk_socpeople";
1584 $sql .=
" FROM ".$this->db->prefix().
"element_contact as ec,";
1585 if ($source ==
'internal') {
1586 $sql .=
" ".$this->db->prefix().
"user as c,";
1588 if ($source ==
'external') {
1589 $sql .=
" ".$this->db->prefix().
"socpeople as c,";
1591 $sql .=
" ".$this->db->prefix().
"c_type_contact as tc";
1592 $sql .=
" WHERE ec.element_id = ".((int) $id);
1593 $sql .=
" AND ec.fk_socpeople = c.rowid";
1594 if ($source ==
'internal') {
1595 $sql .=
" AND c.entity IN (".getEntity(
'user').
")";
1597 if ($source ==
'external') {
1598 $sql .=
" AND c.entity IN (".getEntity(
'societe').
")";
1600 $sql .=
" AND ec.fk_c_type_contact = tc.rowid";
1601 $sql .=
" AND tc.element = '".$this->db->escape($element).
"'";
1602 $sql .=
" AND tc.source = '".$this->db->escape($source).
"'";
1604 $sql .=
" AND tc.code = '".$this->db->escape($code).
"'";
1606 $sql .=
" AND tc.active = 1";
1608 $sql .=
" AND ec.statut = ".((int) $status);
1611 dol_syslog(get_class($this).
"::getIdContact", LOG_DEBUG);
1612 $resql = $this->db->query($sql);
1614 while ($obj = $this->db->fetch_object($resql)) {
1615 $result[$i] = $obj->fk_socpeople;
1619 $this->error = $this->db->error();
1636 if (empty($contactid)) {
1637 $contactid = $this->contact_id;
1640 if (empty($contactid)) {
1644 require_once DOL_DOCUMENT_ROOT.
'/contact/class/contact.class.php';
1645 $contact =
new Contact($this->db);
1646 $result = $contact->fetch($contactid);
1647 $this->contact = $contact;
1663 if (empty($this->socid) && empty($this->fk_soc) && empty($force_thirdparty_id)) {
1667 require_once DOL_DOCUMENT_ROOT.
'/societe/class/societe.class.php';
1669 $idtofetch = isset($this->socid) ? $this->socid : (isset($this->fk_soc) ? $this->fk_soc : 0);
1670 if ($force_thirdparty_id) {
1671 $idtofetch = $force_thirdparty_id;
1675 $thirdparty =
new Societe($this->db);
1676 $result = $thirdparty->fetch($idtofetch);
1678 $this->errors=array_merge($this->errors, $thirdparty->errors);
1680 $this->thirdparty = $thirdparty;
1683 if (!empty($conf->global->PRODUIT_MULTIPRICES) && empty($this->thirdparty->price_level)) {
1684 $this->thirdparty->price_level = 1;
1703 if (!$this->table_ref_field) {
1707 $sql =
"SELECT rowid FROM ".$this->db->prefix().$this->table_element.
" WHERE ".$this->table_ref_field.
" LIKE '".$this->db->escape($ref).
"' LIMIT 1";
1709 $query = $this->db->query($sql);
1711 if (!$this->db->num_rows($query)) {
1715 $result = $this->db->fetch_object($query);
1717 return $this->fetch($result->rowid);
1733 dol_syslog(get_class($this).
'::fetch_barcode this->element='.$this->element.
' this->barcode_type='.$this->barcode_type);
1735 $idtype = $this->barcode_type;
1736 if (empty($idtype) && $idtype !=
'0') {
1737 if ($this->element ==
'product' && !empty($conf->global->PRODUIT_DEFAULT_BARCODE_TYPE)) {
1738 $idtype = $conf->global->PRODUIT_DEFAULT_BARCODE_TYPE;
1739 } elseif ($this->element ==
'societe') {
1740 $idtype = $conf->global->GENBARCODE_BARCODETYPE_THIRDPARTY;
1742 dol_syslog(
'Call fetch_barcode with barcode_type not defined and cant be guessed', LOG_WARNING);
1747 if (empty($this->barcode_type) || empty($this->barcode_type_code) || empty($this->barcode_type_label) || empty($this->barcode_type_coder)) {
1748 $sql =
"SELECT rowid, code, libelle as label, coder";
1749 $sql .=
" FROM ".$this->db->prefix().
"c_barcode_type";
1750 $sql .=
" WHERE rowid = ".((int) $idtype);
1751 dol_syslog(get_class($this).
'::fetch_barcode', LOG_DEBUG);
1752 $resql = $this->db->query($sql);
1754 $obj = $this->db->fetch_object($resql);
1755 $this->barcode_type = $obj->rowid;
1756 $this->barcode_type_code = $obj->code;
1757 $this->barcode_type_label = $obj->label;
1758 $this->barcode_type_coder = $obj->coder;
1778 return $this->fetch_projet();
1790 include_once DOL_DOCUMENT_ROOT.
'/projet/class/project.class.php';
1792 if (empty($this->fk_project) && !empty($this->fk_projet)) {
1793 $this->fk_project = $this->fk_projet;
1795 if (empty($this->fk_project)) {
1799 $project =
new Project($this->db);
1800 $result = $project->fetch($this->fk_project);
1802 $this->projet = $project;
1803 $this->project = $project;
1816 include_once DOL_DOCUMENT_ROOT.
'/product/class/product.class.php';
1818 if (empty($this->fk_product)) {
1822 $product =
new Product($this->db);
1823 $result = $product->fetch($this->fk_product);
1825 $this->product = $product;
1839 $user =
new User($this->db);
1840 $result = $user->fetch($userid);
1841 $this->
user = $user;
1854 if ($this->origin ==
'shipping') {
1855 $this->origin =
'expedition';
1857 if ($this->origin ==
'delivery') {
1858 $this->origin =
'livraison';
1860 if ($this->origin ==
'order_supplier') {
1861 $this->origin =
'commandeFournisseur';
1864 $origin = $this->origin;
1866 $classname = ucfirst($origin);
1867 $this->$origin =
new $classname($this->db);
1868 $this->$origin->fetch($this->origin_id);
1886 $sql =
"SELECT rowid FROM ".$this->db->prefix().$table;
1887 $sql .=
" WHERE ".$field.
" = '".$this->db->escape($key).
"'";
1888 if (!empty($element)) {
1889 $sql .=
" AND entity IN (".getEntity($element).
")";
1891 $sql .=
" AND entity = ".((int) $conf->entity);
1894 dol_syslog(get_class($this).
'::fetchObjectFrom', LOG_DEBUG);
1895 $resql = $this->db->query($sql);
1897 $row = $this->db->fetch_row($resql);
1900 $result = $this->fetch($row[0]);
1918 if (!empty($id) && !empty($field) && !empty($table)) {
1919 $sql =
"SELECT ".$field.
" FROM ".$this->db->prefix().$table;
1920 $sql .=
" WHERE rowid = ".((int) $id);
1922 dol_syslog(get_class($this).
'::getValueFrom', LOG_DEBUG);
1923 $resql = $this->db->query($sql);
1925 $row = $this->db->fetch_row($resql);
1948 public function setValueFrom($field, $value, $table =
'', $id =
null, $format =
'', $id_field =
'', $fuser =
null, $trigkey =
'', $fk_user_field =
'fk_user_modif')
1952 if (empty($table)) {
1953 $table = $this->table_element;
1958 if (empty($format)) {
1961 if (empty($id_field)) {
1962 $id_field =
'rowid';
1966 if ($table ==
'product' && $field ==
'note_private') {
1970 if (in_array($table, array(
'actioncomm',
'adherent',
'advtargetemailing',
'cronjob',
'establishment'))) {
1971 $fk_user_field =
'fk_user_mod';
1973 if (in_array($table, array(
'prelevement_bons'))) {
1974 $fk_user_field =
'';
1980 $sql =
"SELECT " . $field;
1981 $sql .=
" FROM " . MAIN_DB_PREFIX . $table;
1982 $sql .=
" WHERE " . $id_field .
" = " . ((int) $id);
1984 $resql = $this->db->query($sql);
1986 if ($obj = $this->db->fetch_object($resql)) {
1987 if ($format ==
'date') {
1988 $oldvalue = $this->db->jdate($obj->$field);
1990 $oldvalue = $obj->$field;
1994 $this->error = $this->db->lasterror();
2005 $sql =
"UPDATE ".$this->db->prefix().$table.
" SET ";
2007 if ($format ==
'text') {
2008 $sql .= $field.
" = '".$this->db->escape($value).
"'";
2009 } elseif ($format ==
'int') {
2010 $sql .= $field.
" = ".((int) $value);
2011 } elseif ($format ==
'date') {
2012 $sql .= $field.
" = ".($value ?
"'".$this->db->idate($value).
"'" :
"null");
2013 } elseif ($format ==
'dategmt') {
2014 $sql .= $field.
" = ".($value ?
"'".$this->db->idate($value,
'gmt').
"'" :
"null");
2017 if ($fk_user_field) {
2018 if (!empty($fuser) && is_object($fuser)) {
2019 $sql .=
", ".$fk_user_field.
" = ".((int) $fuser->id);
2020 } elseif (empty($fuser) || $fuser !=
'none') {
2021 $sql .=
", ".$fk_user_field.
" = ".((int) $user->id);
2025 $sql .=
" WHERE ".$id_field.
" = ".((int) $id);
2027 $resql = $this->db->query($sql);
2031 if (method_exists($this,
'fetch')) {
2032 $result = $this->fetch($id);
2034 $result = $this->fetchCommon($id);
2036 $this->oldcopy = clone $this;
2037 if (property_exists($this->oldcopy, $field)) {
2038 $this->oldcopy->$field = $oldvalue;
2042 $result = $this->call_trigger($trigkey, (!empty($fuser) && is_object($fuser)) ? $fuser : $user);
2050 if (property_exists($this, $field)) {
2051 $this->$field = $value;
2053 $this->db->commit();
2056 $this->db->rollback();
2060 if ($this->db->lasterrno() ==
'DB_ERROR_RECORD_ALREADY_EXISTS') {
2061 $this->error =
'DB_ERROR_RECORD_ALREADY_EXISTS';
2063 $this->error = $this->db->lasterror();
2065 $this->db->rollback();
2083 global $conf, $user;
2085 if (!$this->table_element) {
2086 dol_print_error(
'', get_class($this).
"::load_previous_next_ref was called on objet with property table_element not defined");
2089 if ($fieldid ==
'none') {
2094 if (in_array($this->table_element, array(
'facture_rec',
'facture_fourn_rec')) && $fieldid ==
'title') {
2100 if ($user->socid > 0) {
2101 $socid = $user->socid;
2106 $aliastablesociete =
's';
2107 if ($this->element ==
'societe') {
2108 $aliastablesociete =
'te';
2110 $restrictiononfksoc = empty($this->restrictiononfksoc) ? 0 : $this->restrictiononfksoc;
2111 $sql =
"SELECT MAX(te.".$fieldid.
")";
2112 $sql .=
" FROM ".(empty($nodbprefix) ?$this->db->prefix():
'').$this->table_element.
" as te";
2113 if ($this->element ==
'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
2114 $sql .=
",".$this->db->prefix().
"usergroup_user as ug";
2116 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2117 $tmparray = explode(
'@', $this->ismultientitymanaged);
2118 $sql .=
", ".$this->db->prefix().$tmparray[1].
" as ".($tmparray[1] ==
'societe' ?
's' :
'parenttable');
2119 } elseif ($restrictiononfksoc == 1 && $this->element !=
'societe' && empty($user->rights->societe->client->voir) && !$socid) {
2120 $sql .=
", ".$this->db->prefix().
"societe as s";
2121 } elseif ($restrictiononfksoc == 2 && $this->element !=
'societe' && empty($user->rights->societe->client->voir) && !$socid) {
2122 $sql .=
" LEFT JOIN ".$this->db->prefix().
"societe as s ON te.fk_soc = s.rowid";
2124 if ($restrictiononfksoc && empty($user->rights->societe->client->voir) && !$socid) {
2125 $sql .=
" LEFT JOIN ".$this->db->prefix().
"societe_commerciaux as sc ON ".$aliastablesociete.
".rowid = sc.fk_soc";
2127 $sql .=
" WHERE te.".$fieldid.
" < '".$this->db->escape($fieldid ==
'rowid' ? $this->
id : $this->ref).
"'";
2128 if ($restrictiononfksoc == 1 && empty($user->rights->societe->client->voir) && !$socid) {
2129 $sql .=
" AND sc.fk_user = ".((int) $user->id);
2131 if ($restrictiononfksoc == 2 && empty($user->rights->societe->client->voir) && !$socid) {
2132 $sql .=
" AND (sc.fk_user = ".((int) $user->id).
' OR te.fk_soc IS NULL)';
2134 if (!empty($filter)) {
2135 if (!preg_match(
'/^\s*AND/i', $filter)) {
2140 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2141 $tmparray = explode(
'@', $this->ismultientitymanaged);
2142 $sql .=
" AND te.".$tmparray[0].
" = ".($tmparray[1] ==
"societe" ?
"s" :
"parenttable").
".rowid";
2143 } elseif ($restrictiononfksoc == 1 && $this->element !=
'societe' && empty($user->rights->societe->client->voir) && !$socid) {
2144 $sql .=
' AND te.fk_soc = s.rowid';
2146 if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
2147 if ($this->element ==
'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
2148 if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
2149 $sql .=
" AND te.entity IS NOT NULL";
2151 $sql .=
" AND ug.fk_user = te.rowid";
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 $sql .=
",".$this->db->prefix().
"usergroup_user as ug";
2186 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2187 $tmparray = explode(
'@', $this->ismultientitymanaged);
2188 $sql .=
", ".$this->db->prefix().$tmparray[1].
" as ".($tmparray[1] ==
'societe' ?
's' :
'parenttable');
2189 } elseif ($restrictiononfksoc == 1 && $this->element !=
'societe' && empty($user->rights->societe->client->voir) && !$socid) {
2190 $sql .=
", ".$this->db->prefix().
"societe as s";
2191 } elseif ($restrictiononfksoc == 2 && $this->element !=
'societe' && empty($user->rights->societe->client->voir) && !$socid) {
2192 $sql .=
" LEFT JOIN ".$this->db->prefix().
"societe as s ON te.fk_soc = s.rowid";
2194 if ($restrictiononfksoc && empty($user->rights->societe->client->voir) && !$socid) {
2195 $sql .=
" LEFT JOIN ".$this->db->prefix().
"societe_commerciaux as sc ON ".$aliastablesociete.
".rowid = sc.fk_soc";
2197 $sql .=
" WHERE te.".$fieldid.
" > '".$this->db->escape($fieldid ==
'rowid' ? $this->
id : $this->ref).
"'";
2198 if ($restrictiononfksoc == 1 && empty($user->rights->societe->client->voir) && !$socid) {
2199 $sql .=
" AND sc.fk_user = ".((int) $user->id);
2201 if ($restrictiononfksoc == 2 && empty($user->rights->societe->client->voir) && !$socid) {
2202 $sql .=
" AND (sc.fk_user = ".((int) $user->id).
' OR te.fk_soc IS NULL)';
2204 if (!empty($filter)) {
2205 if (!preg_match(
'/^\s*AND/i', $filter)) {
2210 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2211 $tmparray = explode(
'@', $this->ismultientitymanaged);
2212 $sql .=
" AND te.".$tmparray[0].
" = ".($tmparray[1] ==
"societe" ?
"s" :
"parenttable").
".rowid";
2213 } elseif ($restrictiononfksoc == 1 && $this->element !=
'societe' && empty($user->rights->societe->client->voir) && !$socid) {
2214 $sql .=
' AND te.fk_soc = s.rowid';
2216 if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
2217 if ($this->element ==
'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
2218 if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
2219 $sql .=
" AND te.entity IS NOT NULL";
2221 $sql .=
" AND ug.fk_user = te.rowid";
2222 $sql .=
" AND ug.entity IN (".getEntity(
'usergroup').
")";
2225 $sql .=
' AND te.entity IN ('.getEntity($this->element).
')';
2228 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged) && $this->element !=
'societe') {
2229 $tmparray = explode(
'@', $this->ismultientitymanaged);
2230 $sql .=
' AND parenttable.entity IN ('.getEntity($tmparray[1]).
')';
2232 if ($restrictiononfksoc == 1 && $socid && $this->element !=
'societe') {
2233 $sql .=
' AND te.fk_soc = '.((int) $socid);
2235 if ($restrictiononfksoc == 2 && $socid && $this->element !=
'societe') {
2236 $sql .=
' AND (te.fk_soc = '.((int) $socid).
' OR te.fk_soc IS NULL)';
2238 if ($restrictiononfksoc && $socid && $this->element ==
'societe') {
2239 $sql .=
' AND te.rowid = '.((int) $socid);
2244 $result = $this->db->query($sql);
2246 $this->error = $this->db->lasterror();
2249 $row = $this->db->fetch_row($result);
2250 $this->ref_next = $row[0];
2265 $contactAlreadySelected = array();
2266 $tab = $this->liste_contact(-1, $source);
2270 if ($source ==
'thirdparty') {
2271 $contactAlreadySelected[$i] = $tab[$i][
'socid'];
2273 $contactAlreadySelected[$i] = $tab[$i][
'id'];
2277 return $contactAlreadySelected;
2293 if (!$this->table_element) {
2294 dol_syslog(get_class($this).
"::setProject was called on objet with property table_element not defined", LOG_ERR);
2298 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
2299 if (!empty($this->fields[
'fk_project'])) {
2301 $sql .=
" SET fk_project = ".((int) $projectid);
2303 $sql .=
" SET fk_project = NULL";
2305 $sql .=
' WHERE rowid = '.((int) $this->
id);
2306 } elseif ($this->table_element ==
'actioncomm') {
2308 $sql .=
" SET fk_project = ".((int) $projectid);
2310 $sql .=
" SET fk_project = NULL";
2312 $sql .=
' WHERE id = '.((int) $this->
id);
2316 $sql .=
' SET fk_projet = '.((int) $projectid);
2318 $sql .=
' SET fk_projet = NULL';
2320 $sql .=
" WHERE rowid = ".((int) $this->
id);
2325 dol_syslog(get_class($this).
"::setProject", LOG_DEBUG);
2326 if ($this->db->query($sql)) {
2327 $this->fk_project = ((int) $projectid);
2334 if (!$error && !$notrigger) {
2336 $result = $this->call_trigger(strtoupper($this->element) .
'_MODIFY', $user);
2345 $this->db->rollback();
2348 $this->db->commit();
2363 $error = 0; $notrigger = 0;
2365 dol_syslog(get_class($this).
'::setPaymentMethods('.$id.
')');
2367 if ($this->
statut >= 0 || $this->element ==
'societe') {
2369 $fieldname =
'fk_mode_reglement';
2370 if ($this->element ==
'societe') {
2371 $fieldname =
'mode_reglement';
2373 if (get_class($this) ==
'Fournisseur') {
2374 $fieldname =
'mode_reglement_supplier';
2376 if (get_class($this) ==
'Tva') {
2377 $fieldname =
'fk_typepayment';
2379 if (get_class($this) ==
'Salary') {
2380 $fieldname =
'fk_typepayment';
2383 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
2384 $sql .=
" SET ".$fieldname.
" = ".(($id > 0 || $id ==
'0') ? ((
int) $id) :
'NULL');
2385 $sql .=
' WHERE rowid='.((int) $this->
id);
2387 if ($this->db->query($sql)) {
2388 $this->mode_reglement_id = $id;
2390 if (get_class($this) ==
'Fournisseur') {
2391 $this->mode_reglement_supplier_id = $id;
2394 if (!$error && !$notrigger) {
2396 if (get_class($this) ==
'Commande') {
2397 $result = $this->call_trigger(
'ORDER_MODIFY', $user);
2399 $result = $this->call_trigger(strtoupper(get_class($this)).
'_MODIFY', $user);
2408 dol_syslog(get_class($this).
'::setPaymentMethods Error '.$this->db->error());
2409 $this->error = $this->db->error();
2413 dol_syslog(get_class($this).
'::setPaymentMethods, status of the object is incompatible');
2414 $this->error =
'Status of the object is incompatible '.$this->statut;
2427 dol_syslog(get_class($this).
'::setMulticurrencyCode('.$code.
')');
2428 if ($this->
statut >= 0 || $this->element ==
'societe') {
2429 $fieldname =
'multicurrency_code';
2431 $sql =
'UPDATE '.$this->db->prefix().$this->table_element;
2432 $sql .=
" SET ".$fieldname.
" = '".$this->db->escape($code).
"'";
2433 $sql .=
' WHERE rowid='.((int) $this->
id);
2435 if ($this->db->query($sql)) {
2436 $this->multicurrency_code = $code;
2440 $this->setMulticurrencyRate($rate, 2);
2445 dol_syslog(get_class($this).
'::setMulticurrencyCode Error '.$sql.
' - '.$this->db->error());
2446 $this->error = $this->db->error();
2450 dol_syslog(get_class($this).
'::setMulticurrencyCode, status of the object is incompatible');
2451 $this->error =
'Status of the object is incompatible '.$this->statut;
2463 public function setMulticurrencyRate($rate, $mode = 1)
2465 dol_syslog(get_class($this).
'::setMulticurrencyRate('.$rate.
','.$mode.
')');
2466 if ($this->
statut >= 0 || $this->element ==
'societe') {
2467 $fieldname =
'multicurrency_tx';
2469 $sql =
'UPDATE '.$this->db->prefix().$this->table_element;
2470 $sql .=
" SET ".$fieldname.
" = ".((float) $rate);
2471 $sql .=
' WHERE rowid='.((int) $this->
id);
2473 if ($this->db->query($sql)) {
2474 $this->multicurrency_tx = $rate;
2477 if (!empty($this->lines)) {
2478 foreach ($this->lines as &$line) {
2481 $line->subprice = 0;
2486 $line->multicurrency_subprice = 0;
2489 switch ($this->element) {
2497 $line->remise_percent,
2499 $line->localtax1_tx,
2500 $line->localtax2_tx,
2501 ($line->description ? $line->description : $line->desc),
2504 $line->special_code,
2505 $line->fk_parent_line,
2506 $line->skip_update_total,
2507 $line->fk_fournprice,
2510 $line->product_type,
2513 $line->array_options,
2515 $line->multicurrency_subprice
2523 ($line->description ? $line->description : $line->desc),
2526 $line->remise_percent,
2528 $line->localtax1_tx,
2529 $line->localtax2_tx,
2534 $line->product_type,
2535 $line->fk_parent_line,
2536 $line->skip_update_total,
2537 $line->fk_fournprice,
2540 $line->special_code,
2541 $line->array_options,
2543 $line->multicurrency_subprice
2551 ($line->description ? $line->description : $line->desc),
2554 $line->remise_percent,
2558 $line->localtax1_tx,
2559 $line->localtax2_tx,
2562 $line->product_type,
2563 $line->fk_parent_line,
2564 $line->skip_update_total,
2565 $line->fk_fournprice,
2568 $line->special_code,
2569 $line->array_options,
2570 $line->situation_percent,
2572 $line->multicurrency_subprice
2575 case 'supplier_proposal':
2582 $line->remise_percent,
2584 $line->localtax1_tx,
2585 $line->localtax2_tx,
2586 ($line->description ? $line->description : $line->desc),
2589 $line->special_code,
2590 $line->fk_parent_line,
2591 $line->skip_update_total,
2592 $line->fk_fournprice,
2595 $line->product_type,
2596 $line->array_options,
2598 $line->multicurrency_subprice
2601 case 'order_supplier':
2606 ($line->description ? $line->description : $line->desc),
2609 $line->remise_percent,
2611 $line->localtax1_tx,
2612 $line->localtax2_tx,
2615 $line->product_type,
2619 $line->array_options,
2621 $line->multicurrency_subprice,
2625 case 'invoice_supplier':
2630 ($line->description ? $line->description : $line->desc),
2633 $line->localtax1_tx,
2634 $line->localtax2_tx,
2639 $line->product_type,
2640 $line->remise_percent,
2644 $line->array_options,
2646 $line->multicurrency_subprice,
2651 dol_syslog(get_class($this).
'::setMulticurrencyRate no updateline defined', LOG_DEBUG);
2659 dol_syslog(get_class($this).
'::setMulticurrencyRate Error '.$sql.
' - '.$this->db->error());
2660 $this->error = $this->db->error();
2664 dol_syslog(get_class($this).
'::setMulticurrencyRate, status of the object is incompatible');
2665 $this->error =
'Status of the object is incompatible '.$this->statut;
2679 dol_syslog(get_class($this).
'::setPaymentTerms('.$id.
', '.var_export($deposit_percent,
true).
')');
2680 if ($this->
statut >= 0 || $this->element ==
'societe') {
2682 $fieldname =
'fk_cond_reglement';
2683 if ($this->element ==
'societe') {
2684 $fieldname =
'cond_reglement';
2686 if (get_class($this) ==
'Fournisseur') {
2687 $fieldname =
'cond_reglement_supplier';
2690 if (empty($deposit_percent) || $deposit_percent < 0) {
2694 if ($deposit_percent > 100) {
2695 $deposit_percent = 100;
2698 $sql =
'UPDATE '.$this->db->prefix().$this->table_element;
2699 $sql .=
" SET ".$fieldname.
" = ".(($id > 0 || $id ==
'0') ? ((
int) $id) :
'NULL');
2700 if (in_array($this->table_element, array(
'propal',
'commande',
'societe'))) {
2701 $sql .=
" , deposit_percent = " . (empty($deposit_percent) ?
'NULL' :
"'".$this->db->escape($deposit_percent).
"'");
2703 $sql .=
' WHERE rowid='.((int) $this->
id);
2705 if ($this->db->query($sql)) {
2706 $this->cond_reglement_id = $id;
2708 if (get_class($this) ==
'Fournisseur') {
2709 $this->cond_reglement_supplier_id = $id;
2711 $this->cond_reglement = $id;
2712 $this->deposit_percent = $deposit_percent;
2715 dol_syslog(get_class($this).
'::setPaymentTerms Error '.$sql.
' - '.$this->db->error());
2716 $this->error = $this->db->error();
2720 dol_syslog(get_class($this).
'::setPaymentTerms, status of the object is incompatible');
2721 $this->error =
'Status of the object is incompatible '.$this->statut;
2734 dol_syslog(get_class($this).
'::setTransportMode('.$id.
')');
2735 if ($this->
statut >= 0 || $this->element ==
'societe') {
2736 $fieldname =
'fk_transport_mode';
2737 if ($this->element ==
'societe') {
2738 $fieldname =
'transport_mode';
2740 if (get_class($this) ==
'Fournisseur') {
2741 $fieldname =
'transport_mode_supplier';
2744 $sql =
'UPDATE '.$this->db->prefix().$this->table_element;
2745 $sql .=
" SET ".$fieldname.
" = ".(($id > 0 || $id ==
'0') ? ((
int) $id) :
'NULL');
2746 $sql .=
' WHERE rowid='.((int) $this->
id);
2748 if ($this->db->query($sql)) {
2749 $this->transport_mode_id = $id;
2751 if (get_class($this) ==
'Fournisseur') {
2752 $this->transport_mode_supplier_id = $id;
2756 dol_syslog(get_class($this).
'::setTransportMode Error '.$sql.
' - '.$this->db->error());
2757 $this->error = $this->db->error();
2761 dol_syslog(get_class($this).
'::setTransportMode, status of the object is incompatible');
2762 $this->error =
'Status of the object is incompatible '.$this->statut;
2775 dol_syslog(get_class($this).
'::setRetainedWarrantyPaymentTerms('.$id.
')');
2776 if ($this->
statut >= 0 || $this->element ==
'societe') {
2777 $fieldname =
'retained_warranty_fk_cond_reglement';
2779 $sql =
'UPDATE '.$this->db->prefix().$this->table_element;
2780 $sql .=
" SET ".$fieldname.
" = ".((int) $id);
2781 $sql .=
' WHERE rowid='.((int) $this->
id);
2783 if ($this->db->query($sql)) {
2784 $this->retained_warranty_fk_cond_reglement = $id;
2787 dol_syslog(get_class($this).
'::setRetainedWarrantyPaymentTerms Error '.$sql.
' - '.$this->db->error());
2788 $this->error = $this->db->error();
2792 dol_syslog(get_class($this).
'::setRetainedWarrantyPaymentTerms, status of the object is incompatible');
2793 $this->error =
'Status of the object is incompatible '.$this->statut;
2807 $fieldname =
'fk_delivery_address';
2808 if ($this->element ==
'delivery' || $this->element ==
'shipping') {
2809 $fieldname =
'fk_address';
2812 $sql =
"UPDATE ".$this->db->prefix().$this->table_element.
" SET ".$fieldname.
" = ".((int) $id);
2813 $sql .=
" WHERE rowid = ".((int) $this->
id).
" AND fk_statut = 0";
2815 if ($this->db->query($sql)) {
2816 $this->fk_delivery_address = $id;
2819 $this->error = $this->db->error();
2820 dol_syslog(get_class($this).
'::setDeliveryAddress Error '.$this->error);
2839 if (empty($userused)) {
2845 if (!$this->table_element) {
2846 dol_syslog(get_class($this).
"::setShippingMethod was called on objet with property table_element not defined", LOG_ERR);
2852 if ($shipping_method_id < 0) {
2853 $shipping_method_id =
'NULL';
2855 dol_syslog(get_class($this).
'::setShippingMethod('.$shipping_method_id.
')');
2857 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
2858 $sql .=
" SET fk_shipping_method = ".((int) $shipping_method_id);
2859 $sql .=
" WHERE rowid=".((int) $this->
id);
2860 $resql = $this->db->query($sql);
2862 dol_syslog(get_class($this).
'::setShippingMethod Error ', LOG_DEBUG);
2863 $this->error = $this->db->lasterror();
2868 $this->context = array(
'shippingmethodupdate'=>1);
2869 $result = $this->call_trigger(strtoupper(get_class($this)).
'_MODIFY', $userused);
2877 $this->db->rollback();
2880 $this->shipping_method_id = ($shipping_method_id ==
'NULL') ?
null:$shipping_method_id;
2881 $this->db->commit();
2895 if (!$this->table_element) {
2896 dol_syslog(get_class($this).
"::setWarehouse was called on objet with property table_element not defined", LOG_ERR);
2899 if ($warehouse_id < 0) {
2900 $warehouse_id =
'NULL';
2902 dol_syslog(get_class($this).
'::setWarehouse('.$warehouse_id.
')');
2904 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
2905 $sql .=
" SET fk_warehouse = ".((int) $warehouse_id);
2906 $sql .=
" WHERE rowid=".((int) $this->
id);
2908 if ($this->db->query($sql)) {
2909 $this->warehouse_id = ($warehouse_id ==
'NULL') ?
null:$warehouse_id;
2912 dol_syslog(get_class($this).
'::setWarehouse Error ', LOG_DEBUG);
2913 $this->error = $this->db->error();
2928 if (!$this->table_element) {
2929 dol_syslog(get_class($this).
"::setDocModel was called on objet with property table_element not defined", LOG_ERR);
2933 $newmodelpdf =
dol_trunc($modelpdf, 255);
2935 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
2936 $sql .=
" SET model_pdf = '".$this->db->escape($newmodelpdf).
"'";
2937 $sql .=
" WHERE rowid = ".((int) $this->
id);
2939 dol_syslog(get_class($this).
"::setDocModel", LOG_DEBUG);
2940 $resql = $this->db->query($sql);
2942 $this->model_pdf = $modelpdf;
2943 $this->modelpdf = $modelpdf;
2964 if (empty($userused)) {
2970 if (!$this->table_element) {
2971 dol_syslog(get_class($this).
"::setBankAccount was called on objet with property table_element not defined", LOG_ERR);
2976 if ($fk_account < 0) {
2977 $fk_account =
'NULL';
2979 dol_syslog(get_class($this).
'::setBankAccount('.$fk_account.
')');
2981 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
2982 $sql .=
" SET fk_account = ".((int) $fk_account);
2983 $sql .=
" WHERE rowid=".((int) $this->
id);
2985 $resql = $this->db->query($sql);
2987 dol_syslog(get_class($this).
'::setBankAccount Error '.$sql.
' - '.$this->db->error());
2988 $this->error = $this->db->lasterror();
2993 $this->context = array(
'bankaccountupdate'=>1);
2994 $result = $this->call_trigger(strtoupper(get_class($this)).
'_MODIFY', $userused);
3002 $this->db->rollback();
3005 $this->fk_account = ($fk_account ==
'NULL') ?
null:$fk_account;
3006 $this->db->commit();
3024 public function line_order($renum =
false, $rowidorder =
'ASC', $fk_parent_line =
true)
3027 if (!$this->table_element_line) {
3028 dol_syslog(get_class($this).
"::line_order was called on objet with property table_element_line not defined", LOG_ERR);
3031 if (!$this->fk_element) {
3032 dol_syslog(get_class($this).
"::line_order was called on objet with property fk_element not defined", LOG_ERR);
3036 $fieldposition =
'rang';
3037 if (in_array($this->table_element_line, array(
'bom_bomline',
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3038 $fieldposition =
'position';
3043 $sql =
"SELECT count(rowid) FROM ".$this->db->prefix().$this->table_element_line;
3044 $sql .=
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
3046 $sql .=
" AND " . $fieldposition .
" = 0";
3049 $sql .=
" AND " . $fieldposition .
" <> 0";
3052 dol_syslog(get_class($this).
"::line_order", LOG_DEBUG);
3053 $resql = $this->db->query($sql);
3055 $row = $this->db->fetch_row($resql);
3065 $sql =
"SELECT rowid FROM ".$this->db->prefix().$this->table_element_line;
3066 $sql .=
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
3067 if ($fk_parent_line) {
3068 $sql .=
' AND fk_parent_line IS NULL';
3070 $sql .=
" ORDER BY " . $fieldposition .
" ASC, rowid " . $rowidorder;
3072 dol_syslog(get_class($this).
"::line_order search all parent lines", LOG_DEBUG);
3073 $resql = $this->db->query($sql);
3076 $num = $this->db->num_rows($resql);
3078 $row = $this->db->fetch_row($resql);
3080 $childrens = $this->getChildrenOfLine($row[0]);
3081 if (!empty($childrens)) {
3082 foreach ($childrens as $child) {
3083 array_push($rows, $child);
3090 if (!empty($rows)) {
3091 foreach ($rows as $key => $row) {
3092 $this->updateRangOfLine($row, ($key + 1));
3111 $fieldposition =
'rang';
3112 if (in_array($this->table_element_line, array(
'bom_bomline',
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3113 $fieldposition =
'position';
3118 $sql =
"SELECT rowid FROM ".$this->db->prefix().$this->table_element_line;
3119 $sql .=
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
3120 $sql .=
' AND fk_parent_line = '.((int) $id);
3121 $sql .=
" ORDER BY " . $fieldposition .
" ASC";
3123 dol_syslog(get_class($this).
"::getChildrenOfLine search children lines for line ".$id, LOG_DEBUG);
3124 $resql = $this->db->query($sql);
3126 if ($this->db->num_rows($resql) > 0) {
3127 while ($row = $this->db->fetch_row($resql)) {
3129 if (!empty($includealltree)) {
3130 $rows = array_merge($rows, $this->getChildrenOfLine($row[0], $includealltree));
3146 public function line_up($rowid, $fk_parent_line =
true)
3149 $this->line_order(
false,
'ASC', $fk_parent_line);
3152 $rang = $this->getRangOfLine($rowid);
3155 $this->updateLineUp($rowid, $rang);
3169 $this->line_order(
false,
'ASC', $fk_parent_line);
3172 $rang = $this->getRangOfLine($rowid);
3175 $max = $this->line_max();
3178 $this->updateLineDown($rowid, $rang, $max);
3190 global $hookmanager;
3191 $fieldposition =
'rang';
3192 if (in_array($this->table_element_line, array(
'bom_bomline',
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3193 $fieldposition =
'position';
3196 $sql =
"UPDATE ".$this->db->prefix().$this->table_element_line.
" SET ".$fieldposition.
" = ".((int) $rang);
3197 $sql .=
' WHERE rowid = '.((int) $rowid);
3199 dol_syslog(get_class($this).
"::updateRangOfLine", LOG_DEBUG);
3200 if (!$this->db->query($sql)) {
3204 $parameters=array(
'rowid'=>$rowid,
'rang'=>$rang,
'fieldposition' => $fieldposition);
3206 $reshook = $hookmanager->executeHooks(
'afterRankOfLineUpdate', $parameters, $this, $action);
3221 $num = count($rows);
3222 for ($i = 0; $i < $num; $i++) {
3223 $this->updateRangOfLine($rows[$i], ($i + 1));
3237 $fieldposition =
'rang';
3238 if (in_array($this->table_element_line, array(
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3239 $fieldposition =
'position';
3242 $sql =
"UPDATE ".$this->db->prefix().$this->table_element_line.
" SET ".$fieldposition.
" = ".((int) $rang);
3243 $sql .=
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
3244 $sql .=
" AND " . $fieldposition .
" = " . ((int) ($rang - 1));
3245 if ($this->db->query($sql)) {
3246 $sql =
"UPDATE ".$this->db->prefix().$this->table_element_line.
" SET ".$fieldposition.
" = ".((int) ($rang - 1));
3247 $sql .=
' WHERE rowid = '.((int) $rowid);
3248 if (!$this->db->query($sql)) {
3268 $fieldposition =
'rang';
3269 if (in_array($this->table_element_line, array(
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3270 $fieldposition =
'position';
3273 $sql =
"UPDATE ".$this->db->prefix().$this->table_element_line.
" SET ".$fieldposition.
" = ".((int) $rang);
3274 $sql .=
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
3275 $sql .=
" AND " . $fieldposition .
" = " . ((int) ($rang + 1));
3276 if ($this->db->query($sql)) {
3277 $sql =
"UPDATE ".$this->db->prefix().$this->table_element_line.
" SET ".$fieldposition.
" = ".((int) ($rang + 1));
3278 $sql .=
' WHERE rowid = '.((int) $rowid);
3279 if (!$this->db->query($sql)) {
3296 $fieldposition =
'rang';
3297 if (in_array($this->table_element_line, array(
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3298 $fieldposition =
'position';
3301 $sql =
"SELECT " . $fieldposition .
" FROM ".$this->db->prefix().$this->table_element_line;
3302 $sql .=
" WHERE rowid = ".((int) $rowid);
3304 dol_syslog(get_class($this).
"::getRangOfLine", LOG_DEBUG);
3305 $resql = $this->db->query($sql);
3307 $row = $this->db->fetch_row($resql);
3322 $fieldposition =
'rang';
3323 if (in_array($this->table_element_line, array(
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3324 $fieldposition =
'position';
3327 $sql =
"SELECT rowid FROM ".$this->db->prefix().$this->table_element_line;
3328 $sql .=
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
3329 $sql .=
" AND " . $fieldposition .
" = ".((int) $rang);
3330 $resql = $this->db->query($sql);
3332 $row = $this->db->fetch_row($resql);
3349 $positionfield =
'rang';
3350 if (in_array($this->table_element, array(
'bom_bom',
'product_attribute'))) {
3351 $positionfield =
'position';
3355 if ($fk_parent_line) {
3356 $sql =
"SELECT max(".$positionfield.
") FROM ".$this->db->prefix().$this->table_element_line;
3357 $sql .=
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
3358 $sql .=
" AND fk_parent_line = ".((int) $fk_parent_line);
3360 dol_syslog(get_class($this).
"::line_max", LOG_DEBUG);
3361 $resql = $this->db->query($sql);
3363 $row = $this->db->fetch_row($resql);
3364 if (!empty($row[0])) {
3367 return $this->getRangOfLine($fk_parent_line);
3372 $sql =
"SELECT max(".$positionfield.
") FROM ".$this->db->prefix().$this->table_element_line;
3373 $sql .=
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
3375 dol_syslog(get_class($this).
"::line_max", LOG_DEBUG);
3376 $resql = $this->db->query($sql);
3378 $row = $this->db->fetch_row($resql);
3396 if (!$this->table_element) {
3397 dol_syslog(get_class($this).
"::update_ref_ext was called on objet with property table_element not defined", LOG_ERR);
3401 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
3402 $sql .=
" SET ref_ext = '".$this->db->escape($ref_ext).
"'";
3403 $sql .=
" WHERE ".(isset($this->table_rowid) ? $this->table_rowid :
'rowid').
" = ".((
int) $this->id);
3405 dol_syslog(get_class($this).
"::update_ref_ext", LOG_DEBUG);
3406 if ($this->db->query($sql)) {
3407 $this->ref_ext = $ref_ext;
3410 $this->error = $this->db->error();
3429 if (!$this->table_element) {
3430 $this->error =
'update_note was called on objet with property table_element not defined';
3431 dol_syslog(get_class($this).
"::update_note was called on objet with property table_element not defined", LOG_ERR);
3434 if (!in_array($suffix, array(
'',
'_public',
'_private'))) {
3435 $this->error =
'update_note Parameter suffix must be empty, \'_private\' or \'_public\'';
3436 dol_syslog(get_class($this).
"::update_note Parameter suffix must be empty, '_private' or '_public'", LOG_ERR);
3440 $newsuffix = $suffix;
3443 if ($this->table_element ==
'product' && $newsuffix ==
'_private') {
3446 if (in_array($this->table_element, array(
'actioncomm',
'adherent',
'advtargetemailing',
'cronjob',
'establishment'))) {
3447 $fieldusermod =
"fk_user_mod";
3448 } elseif ($this->table_element ==
'ecm_files') {
3449 $fieldusermod =
"fk_user_m";
3451 $fieldusermod =
"fk_user_modif";
3453 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
3454 $sql .=
" SET note".$newsuffix.
" = ".(!empty($note) ? (
"'".$this->db->escape($note).
"'") :
"NULL");
3455 $sql .=
", ".$fieldusermod.
" = ".((int) $user->id);
3456 $sql .=
" WHERE rowid = ".((int) $this->
id);
3458 dol_syslog(get_class($this).
"::update_note", LOG_DEBUG);
3459 if ($this->db->query($sql)) {
3460 if ($suffix ==
'_public') {
3461 $this->note_public = $note;
3462 } elseif ($suffix ==
'_private') {
3463 $this->note_private = $note;
3465 $this->note = $note;
3466 $this->note_private = $note;
3468 if (empty($notrigger)) {
3469 switch ($this->element) {
3471 $trigger_name =
'COMPANY_MODIFY';
3474 $trigger_name =
'ORDER_MODIFY';
3477 $trigger_name =
'BILL_MODIFY';
3479 case 'invoice_supplier':
3480 $trigger_name =
'BILL_SUPPLIER_MODIFY';
3483 $trigger_name =
'BILLREC_MODIFIY';
3485 case 'expensereport':
3486 $trigger_name =
'EXPENSE_REPORT_MODIFY';
3489 $trigger_name = strtoupper($this->element) .
'_MODIFY';
3491 $ret = $this->call_trigger($trigger_name, $user);
3498 $this->error = $this->db->lasterror();
3515 return $this->update_note($note,
'_public');
3529 public function update_price($exclspec = 0, $roundingadjust =
'none', $nodatabaseupdate = 0, $seller =
null)
3532 global $conf, $hookmanager, $action;
3534 $parameters = array(
'exclspec' => $exclspec,
'roundingadjust' => $roundingadjust,
'nodatabaseupdate' => $nodatabaseupdate,
'seller' => $seller);
3535 $reshook = $hookmanager->executeHooks(
'updateTotalPrice', $parameters, $this, $action);
3538 } elseif ($reshook < 0) {
3544 if ($this->element ==
'propal') {
3545 $MODULE =
"MODULE_DISALLOW_UPDATE_PRICE_PROPOSAL";
3546 } elseif ($this->element ==
'commande' || $this->element ==
'order') {
3547 $MODULE =
"MODULE_DISALLOW_UPDATE_PRICE_ORDER";
3548 } elseif ($this->element ==
'facture' || $this->element ==
'invoice') {
3549 $MODULE =
"MODULE_DISALLOW_UPDATE_PRICE_INVOICE";
3550 } elseif ($this->element ==
'facture_fourn' || $this->element ==
'supplier_invoice' || $this->element ==
'invoice_supplier' || $this->element ==
'invoice_supplier_rec') {
3551 $MODULE =
"MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_INVOICE";
3552 } elseif ($this->element ==
'order_supplier' || $this->element ==
'supplier_order') {
3553 $MODULE =
"MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_ORDER";
3554 } elseif ($this->element ==
'supplier_proposal') {
3555 $MODULE =
"MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_PROPOSAL";
3558 if (!empty($MODULE)) {
3559 if (!empty($conf->global->$MODULE)) {
3560 $modsactivated = explode(
',', $conf->global->$MODULE);
3561 foreach ($modsactivated as $mod) {
3562 if (isModEnabled($mod)) {
3569 include_once DOL_DOCUMENT_ROOT.
'/core/lib/price.lib.php';
3571 $forcedroundingmode = $roundingadjust;
3572 if ($forcedroundingmode ==
'auto' && isset($conf->global->MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND)) {
3574 } elseif ($forcedroundingmode ==
'auto') {
3575 $forcedroundingmode =
'0';
3580 $multicurrency_tx = !empty($this->multicurrency_tx) ? $this->multicurrency_tx : 1;
3583 $fieldtva =
'total_tva';
3584 $fieldlocaltax1 =
'total_localtax1';
3585 $fieldlocaltax2 =
'total_localtax2';
3586 $fieldup =
'subprice';
3587 if ($this->element ==
'facture_fourn' || $this->element ==
'invoice_supplier') {
3591 if ($this->element ==
'invoice_supplier_rec') {
3594 if ($this->element ==
'expensereport') {
3595 $fieldup =
'value_unit';
3598 $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,";
3599 $sql .=
' tva_tx as vatrate, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type, info_bits, product_type';
3600 if ($this->table_element_line ==
'facturedet') {
3601 $sql .=
', situation_percent';
3603 $sql .=
', multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc';
3604 $sql .=
" FROM ".$this->db->prefix().$this->table_element_line;
3605 $sql .=
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
3607 $product_field =
'product_type';
3608 if ($this->table_element_line ==
'contratdet') {
3609 $product_field =
'';
3611 if ($product_field) {
3612 $sql .=
" AND ".$product_field.
" <> 9";
3615 $sql .=
' ORDER by rowid';
3617 dol_syslog(get_class($this).
"::update_price", LOG_DEBUG);
3619 $resql = $this->db->query($sql);
3621 $this->total_ht = 0;
3622 $this->total_tva = 0;
3623 $this->total_localtax1 = 0;
3624 $this->total_localtax2 = 0;
3625 $this->total_ttc = 0;
3626 $total_ht_by_vats = array();
3627 $total_tva_by_vats = array();
3628 $total_ttc_by_vats = array();
3629 $this->multicurrency_total_ht = 0;
3630 $this->multicurrency_total_tva = 0;
3631 $this->multicurrency_total_ttc = 0;
3635 $num = $this->db->num_rows($resql);
3638 $obj = $this->db->fetch_object($resql);
3641 $parameters = array(
'fk_element' => $obj->rowid);
3642 $reshook = $hookmanager->executeHooks(
'changeRoundingMode', $parameters, $this, $action);
3644 if (empty($reshook) && $forcedroundingmode ==
'0') {
3646 $localtax_array = array($obj->localtax1_type, $obj->localtax1_tx, $obj->localtax2_type, $obj->localtax2_tx);
3647 $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);
3649 $diff_when_using_price_ht =
price2num($tmpcal[1] - $obj->total_tva,
'MT', 1);
3650 $diff_on_current_total =
price2num($obj->total_ttc - $obj->total_ht - $obj->total_tva - $obj->total_localtax1 - $obj->total_localtax2,
'MT', 1);
3654 if ($diff_on_current_total) {
3656 $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);
3657 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);
3658 $resqlfix = $this->db->query($sqlfix);
3662 $obj->total_tva = $tmpcal[1];
3663 $obj->total_ttc = $tmpcal[2];
3664 } elseif ($diff_when_using_price_ht && $roundingadjust ==
'0') {
3667 $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);
3668 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);
3669 $resqlfix = $this->db->query($sqlfix);
3673 $obj->total_tva = $tmpcal[1];
3674 $obj->total_ttc = $tmpcal[2];
3678 $this->total_ht += $obj->total_ht;
3679 $this->total_tva += $obj->total_tva;
3680 $this->total_localtax1 += $obj->total_localtax1;
3681 $this->total_localtax2 += $obj->total_localtax2;
3682 $this->total_ttc += $obj->total_ttc;
3683 $this->multicurrency_total_ht += $obj->multicurrency_total_ht;
3684 $this->multicurrency_total_tva += $obj->multicurrency_total_tva;
3685 $this->multicurrency_total_ttc += $obj->multicurrency_total_ttc;
3687 if (!isset($total_ht_by_vats[$obj->vatrate])) {
3688 $total_ht_by_vats[$obj->vatrate] = 0;
3690 if (!isset($total_tva_by_vats[$obj->vatrate])) {
3691 $total_tva_by_vats[$obj->vatrate] = 0;
3693 if (!isset($total_ttc_by_vats[$obj->vatrate])) {
3694 $total_ttc_by_vats[$obj->vatrate] = 0;
3696 $total_ht_by_vats[$obj->vatrate] += $obj->total_ht;
3697 $total_tva_by_vats[$obj->vatrate] += $obj->total_tva;
3698 $total_ttc_by_vats[$obj->vatrate] += $obj->total_ttc;
3700 if ($forcedroundingmode ==
'1') {
3701 $tmpvat =
price2num($total_ht_by_vats[$obj->vatrate] * $obj->vatrate / 100,
'MT', 1);
3702 $diff =
price2num($total_tva_by_vats[$obj->vatrate] - $tmpvat,
'MT', 1);
3705 if (abs($diff) > (10 * pow(10, -1 *
getDolGlobalInt(
'MAIN_MAX_DECIMALS_TOT', 0)))) {
3707 $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.';
3709 $this->error = $errmsg;
3713 $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);
3714 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);
3716 $resqlfix = $this->db->query($sqlfix);
3722 $this->total_tva = (float)
price2num($this->total_tva - $diff,
'', 1);
3723 $this->total_ttc = (float)
price2num($this->total_ttc - $diff,
'', 1);
3724 $total_tva_by_vats[$obj->vatrate] = (float)
price2num($total_tva_by_vats[$obj->vatrate] - $diff,
'', 1);
3725 $total_ttc_by_vats[$obj->vatrate] = (float)
price2num($total_ttc_by_vats[$obj->vatrate] - $diff,
'', 1);
3733 $this->total_ttc += isset($this->revenuestamp) ? $this->revenuestamp : 0;
3734 $this->multicurrency_total_ttc += isset($this->revenuestamp) ? ($this->revenuestamp * $multicurrency_tx) : 0;
3737 if (!empty($this->situation_cycle_ref) && $this->situation_counter > 1 && method_exists($this,
'get_prev_sits') && $this->
type != $this::TYPE_CREDIT_NOTE) {
3738 $prev_sits = $this->get_prev_sits();
3740 foreach ($prev_sits as $sit) {
3741 $this->total_ht -= $sit->total_ht;
3742 $this->total_tva -= $sit->total_tva;
3743 $this->total_localtax1 -= $sit->total_localtax1;
3744 $this->total_localtax2 -= $sit->total_localtax2;
3745 $this->total_ttc -= $sit->total_ttc;
3746 $this->multicurrency_total_ht -= $sit->multicurrency_total_ht;
3747 $this->multicurrency_total_tva -= $sit->multicurrency_total_tva;
3748 $this->multicurrency_total_ttc -= $sit->multicurrency_total_ttc;
3753 $this->total_ht = (float)
price2num($this->total_ht);
3754 $this->total_tva = (float)
price2num($this->total_tva);
3755 $this->total_localtax1 = (float)
price2num($this->total_localtax1);
3756 $this->total_localtax2 = (float)
price2num($this->total_localtax2);
3757 $this->total_ttc = (float)
price2num($this->total_ttc);
3759 $this->db->free($resql);
3762 $fieldht =
'total_ht';
3764 $fieldlocaltax1 =
'localtax1';
3765 $fieldlocaltax2 =
'localtax2';
3766 $fieldttc =
'total_ttc';
3768 if (in_array($this->element, array(
'propal',
'commande',
'facture',
'facturerec',
'supplier_proposal',
'order_supplier',
'facture_fourn',
'invoice_supplier',
'invoice_supplier_rec',
'expensereport'))) {
3769 $fieldtva =
'total_tva';
3772 if (!$error && empty($nodatabaseupdate)) {
3773 $sql =
"UPDATE ".$this->db->prefix().$this->table_element.
' SET';
3774 $sql .=
" ".$fieldht.
" = ".((float)
price2num($this->total_ht,
'MT', 1)).
",";
3775 $sql .=
" ".$fieldtva.
" = ".((float)
price2num($this->total_tva,
'MT', 1)).
",";
3776 $sql .=
" ".$fieldlocaltax1.
" = ".((float)
price2num($this->total_localtax1,
'MT', 1)).
",";
3777 $sql .=
" ".$fieldlocaltax2.
" = ".((float)
price2num($this->total_localtax2,
'MT', 1)).
",";
3778 $sql .=
" ".$fieldttc.
" = ".((float)
price2num($this->total_ttc,
'MT', 1));
3779 $sql .=
", multicurrency_total_ht = ".((float)
price2num($this->multicurrency_total_ht,
'MT', 1));
3780 $sql .=
", multicurrency_total_tva = ".((float)
price2num($this->multicurrency_total_tva,
'MT', 1));
3781 $sql .=
", multicurrency_total_ttc = ".((float)
price2num($this->multicurrency_total_ttc,
'MT', 1));
3782 $sql .=
" WHERE rowid = ".((int) $this->
id);
3784 dol_syslog(get_class($this).
"::update_price", LOG_DEBUG);
3785 $resql = $this->db->query($sql);
3789 $this->error = $this->db->lasterror();
3790 $this->errors[] = $this->db->lasterror();
3795 $this->db->commit();
3798 $this->db->rollback();
3818 public function add_object_linked($origin =
null, $origin_id =
null, $f_user =
null, $notrigger = 0)
3821 global $user, $hookmanager, $action;
3822 $origin = (!empty($origin) ? $origin : $this->origin);
3823 $origin_id = (!empty($origin_id) ? $origin_id : $this->origin_id);
3824 $f_user = isset($f_user) ? $f_user : $user;
3827 if ($origin ==
'order') {
3828 $origin =
'commande';
3830 if ($origin ==
'invoice') {
3831 $origin =
'facture';
3833 if ($origin ==
'invoice_template') {
3834 $origin =
'facturerec';
3836 if ($origin ==
'supplierorder') {
3837 $origin =
'order_supplier';
3842 $coremodule = array(
'knowledgemanagement',
'partnership',
'workstation',
'ticket',
'recruitment',
'eventorganization',
'asset');
3844 $targettype = ((!empty($this->module) && ! in_array($this->module, $coremodule)) ? $this->module.
'_' :
'').$this->element;
3846 $parameters = array(
'targettype'=>$targettype);
3848 $reshook = $hookmanager->executeHooks(
'setLinkedObjectSourceTargetType', $parameters, $this, $action);
3850 if (!empty($hookmanager->resArray[
'targettype'])) $targettype = $hookmanager->resArray[
'targettype'];
3856 $sql =
"INSERT INTO " . $this->db->prefix() .
"element_element (";
3857 $sql .=
"fk_source";
3858 $sql .=
", sourcetype";
3859 $sql .=
", fk_target";
3860 $sql .=
", targettype";
3861 $sql .=
") VALUES (";
3862 $sql .= ((int) $origin_id);
3863 $sql .=
", '" . $this->db->escape($origin) .
"'";
3864 $sql .=
", " . ((int) $this->
id);
3865 $sql .=
", '" . $this->db->escape($targettype) .
"'";
3868 dol_syslog(get_class($this) .
"::add_object_linked", LOG_DEBUG);
3869 if ($this->db->query($sql)) {
3872 $this->context[
'link_origin'] = $origin;
3873 $this->context[
'link_origin_id'] = $origin_id;
3874 $result = $this->call_trigger(
'OBJECT_LINK_INSERT', $f_user);
3881 $this->error = $this->db->lasterror();
3886 $this->db->commit();
3889 $this->db->rollback();
3916 public function fetchObjectLinked($sourceid =
null, $sourcetype =
'', $targetid =
null, $targettype =
'', $clause =
'OR', $alsosametype = 1, $orderby =
'sourcetype', $loadalsoobjects = 1)
3918 global $conf, $hookmanager, $action;
3922 if ($this->
id > 0 && !empty($this->linkedObjectsFullLoaded[$this->
id])) {
3926 $this->linkedObjectsIds = array();
3927 $this->linkedObjects = array();
3929 $justsource =
false;
3930 $justtarget =
false;
3931 $withtargettype =
false;
3932 $withsourcetype =
false;
3934 $parameters = array(
'sourcetype'=>$sourcetype,
'sourceid'=>$sourceid,
'targettype'=>$targettype,
'targetid'=>$targetid);
3936 $reshook = $hookmanager->executeHooks(
'setLinkedObjectSourceTargetType', $parameters, $this, $action);
3938 if (!empty($hookmanager->resArray[
'sourcetype'])) $sourcetype = $hookmanager->resArray[
'sourcetype'];
3939 if (!empty($hookmanager->resArray[
'sourceid'])) $sourceid = $hookmanager->resArray[
'sourceid'];
3940 if (!empty($hookmanager->resArray[
'targettype'])) $targettype = $hookmanager->resArray[
'targettype'];
3941 if (!empty($hookmanager->resArray[
'targetid'])) $targetid = $hookmanager->resArray[
'targetid'];
3944 if (!empty($sourceid) && !empty($sourcetype) && empty($targetid)) {
3946 if (!empty($targettype)) {
3947 $withtargettype =
true;
3950 if (!empty($targetid) && !empty($targettype) && empty($sourceid)) {
3952 if (!empty($sourcetype)) {
3953 $withsourcetype =
true;
3957 $sourceid = (!empty($sourceid) ? $sourceid : $this->id);
3958 $targetid = (!empty($targetid) ? $targetid : $this->id);
3959 $sourcetype = (!empty($sourcetype) ? $sourcetype : $this->element);
3960 $targettype = (!empty($targettype) ? $targettype : $this->element);
3969 $sql =
"SELECT rowid, fk_source, sourcetype, fk_target, targettype";
3970 $sql .=
" FROM ".$this->db->prefix().
"element_element";
3972 if ($justsource || $justtarget) {
3974 $sql .=
"fk_source = ".((int) $sourceid).
" AND sourcetype = '".$this->db->escape($sourcetype).
"'";
3975 if ($withtargettype) {
3976 $sql .=
" AND targettype = '".$this->db->escape($targettype).
"'";
3978 } elseif ($justtarget) {
3979 $sql .=
"fk_target = ".((int) $targetid).
" AND targettype = '".$this->db->escape($targettype).
"'";
3980 if ($withsourcetype) {
3981 $sql .=
" AND sourcetype = '".$this->db->escape($sourcetype).
"'";
3985 $sql .=
"(fk_source = ".((int) $sourceid).
" AND sourcetype = '".$this->db->escape($sourcetype).
"')";
3986 $sql .=
" ".$clause.
" (fk_target = ".((int) $targetid).
" AND targettype = '".$this->db->escape($targettype).
"')";
3987 if ($loadalsoobjects && $this->
id > 0 && $sourceid == $this->
id && $sourcetype == $this->element && $targetid == $this->
id && $targettype == $this->element && $clause ==
'OR') {
3988 $this->linkedObjectsFullLoaded[$this->id] =
true;
3991 $sql .=
" ORDER BY ".$orderby;
3993 dol_syslog(get_class($this).
"::fetchObjectLink", LOG_DEBUG);
3994 $resql = $this->db->query($sql);
3996 $num = $this->db->num_rows($resql);
3999 $obj = $this->db->fetch_object($resql);
4000 if ($justsource || $justtarget) {
4002 $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
4003 } elseif ($justtarget) {
4004 $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
4007 if ($obj->fk_source == $sourceid && $obj->sourcetype == $sourcetype) {
4008 $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
4010 if ($obj->fk_target == $targetid && $obj->targettype == $targettype) {
4011 $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
4017 if (!empty($this->linkedObjectsIds)) {
4018 $tmparray = $this->linkedObjectsIds;
4019 foreach ($tmparray as $objecttype => $objectids) {
4021 $module = $element = $subelement = $objecttype;
4023 if ($objecttype !=
'supplier_proposal' && $objecttype !=
'order_supplier' && $objecttype !=
'invoice_supplier'
4024 && preg_match(
'/^([^_]+)_([^_]+)/i', $objecttype, $regs)) {
4025 $module = $element = $regs[1];
4026 $subelement = $regs[2];
4029 $classpath = $element.
'/class';
4031 if ($objecttype ==
'facture') {
4032 $classpath =
'compta/facture/class';
4033 } elseif ($objecttype ==
'facturerec') {
4034 $classpath =
'compta/facture/class';
4035 $module =
'facture';
4036 } elseif ($objecttype ==
'propal') {
4037 $classpath =
'comm/propal/class';
4038 } elseif ($objecttype ==
'supplier_proposal') {
4039 $classpath =
'supplier_proposal/class';
4040 } elseif ($objecttype ==
'shipping') {
4041 $classpath =
'expedition/class';
4042 $subelement =
'expedition';
4043 $module =
'expedition';
4044 } elseif ($objecttype ==
'delivery') {
4045 $classpath =
'delivery/class';
4046 $subelement =
'delivery';
4047 $module =
'delivery_note';
4048 } elseif ($objecttype ==
'invoice_supplier' || $objecttype ==
'order_supplier') {
4049 $classpath =
'fourn/class';
4050 $module =
'fournisseur';
4051 } elseif ($objecttype ==
'fichinter') {
4052 $classpath =
'fichinter/class';
4053 $subelement =
'fichinter';
4054 $module =
'ficheinter';
4055 } elseif ($objecttype ==
'subscription') {
4056 $classpath =
'adherents/class';
4057 $module =
'adherent';
4058 } elseif ($objecttype ==
'contact') {
4059 $module =
'societe';
4062 $classfile = strtolower($subelement);
4063 $classname = ucfirst($subelement);
4065 if ($objecttype ==
'order') {
4066 $classfile =
'commande';
4067 $classname =
'Commande';
4068 } elseif ($objecttype ==
'invoice_supplier') {
4069 $classfile =
'fournisseur.facture';
4070 $classname =
'FactureFournisseur';
4071 } elseif ($objecttype ==
'order_supplier') {
4072 $classfile =
'fournisseur.commande';
4073 $classname =
'CommandeFournisseur';
4074 } elseif ($objecttype ==
'supplier_proposal') {
4075 $classfile =
'supplier_proposal';
4076 $classname =
'SupplierProposal';
4077 } elseif ($objecttype ==
'facturerec') {
4078 $classfile =
'facture-rec';
4079 $classname =
'FactureRec';
4080 } elseif ($objecttype ==
'subscription') {
4081 $classfile =
'subscription';
4082 $classname =
'Subscription';
4083 } elseif ($objecttype ==
'project' || $objecttype ==
'projet') {
4084 $classpath =
'projet/class';
4085 $classfile =
'project';
4086 $classname =
'Project';
4087 } elseif ($objecttype ==
'conferenceorboothattendee') {
4088 $classpath =
'eventorganization/class';
4089 $classfile =
'conferenceorboothattendee';
4090 $classname =
'ConferenceOrBoothAttendee';
4091 $module =
'eventorganization';
4092 } elseif ($objecttype ==
'conferenceorbooth') {
4093 $classpath =
'eventorganization/class';
4094 $classfile =
'conferenceorbooth';
4095 $classname =
'ConferenceOrBooth';
4096 $module =
'eventorganization';
4097 } elseif ($objecttype ==
'mo') {
4098 $classpath =
'mrp/class';
4105 if (isModEnabled($module) && (($element != $this->element) || $alsosametype)) {
4106 if ($loadalsoobjects && (is_numeric($loadalsoobjects) || ($loadalsoobjects === $objecttype))) {
4109 if (class_exists($classname)) {
4110 foreach ($objectids as $i => $objectid) {
4111 $object =
new $classname($this->db);
4112 $ret = $object->fetch($objectid);
4114 $this->linkedObjects[$objecttype][$i] = $object;
4120 unset($this->linkedObjectsIds[$objecttype]);
4139 if ($this->
id > 0 && !empty($this->linkedObjectsFullLoaded[$this->
id])) {
4140 unset($this->linkedObjectsFullLoaded[$this->
id]);
4158 public function updateObjectLinked($sourceid =
null, $sourcetype =
'', $targetid =
null, $targettype =
'', $f_user =
null, $notrigger = 0)
4161 $updatesource =
false;
4162 $updatetarget =
false;
4163 $f_user = isset($f_user) ? $f_user : $user;
4165 if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) {
4166 $updatesource =
true;
4167 } elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) {
4168 $updatetarget =
true;
4174 $sql =
"UPDATE " . $this->db->prefix() .
"element_element SET ";
4175 if ($updatesource) {
4176 $sql .=
"fk_source = " . ((int) $sourceid);
4177 $sql .=
", sourcetype = '" . $this->db->escape($sourcetype) .
"'";
4178 $sql .=
" WHERE fk_target = " . ((int) $this->
id);
4179 $sql .=
" AND targettype = '" . $this->db->escape($this->element) .
"'";
4180 } elseif ($updatetarget) {
4181 $sql .=
"fk_target = " . ((int) $targetid);
4182 $sql .=
", targettype = '" . $this->db->escape($targettype) .
"'";
4183 $sql .=
" WHERE fk_source = " . ((int) $this->
id);
4184 $sql .=
" AND sourcetype = '" . $this->db->escape($this->element) .
"'";
4187 dol_syslog(get_class($this) .
"::updateObjectLinked", LOG_DEBUG);
4188 if ($this->db->query($sql)) {
4191 $this->context[
'link_source_id'] = $sourceid;
4192 $this->context[
'link_source_type'] = $sourcetype;
4193 $this->context[
'link_target_id'] = $targetid;
4194 $this->context[
'link_target_type'] = $targettype;
4195 $result = $this->call_trigger(
'OBJECT_LINK_MODIFY', $f_user);
4202 $this->error = $this->db->lasterror();
4207 $this->db->commit();
4210 $this->db->rollback();
4228 public function deleteObjectLinked($sourceid =
null, $sourcetype =
'', $targetid =
null, $targettype =
'', $rowid =
'', $f_user =
null, $notrigger = 0)
4231 $deletesource =
false;
4232 $deletetarget =
false;
4233 $f_user = isset($f_user) ? $f_user : $user;
4235 if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) {
4236 $deletesource =
true;
4237 } elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) {
4238 $deletetarget =
true;
4241 $sourceid = (!empty($sourceid) ? $sourceid : $this->id);
4242 $sourcetype = (!empty($sourcetype) ? $sourcetype : $this->element);
4243 $targetid = (!empty($targetid) ? $targetid : $this->id);
4244 $targettype = (!empty($targettype) ? $targettype : $this->element);
4250 $this->context[
'link_id'] = $rowid;
4251 $this->context[
'link_source_id'] = $sourceid;
4252 $this->context[
'link_source_type'] = $sourcetype;
4253 $this->context[
'link_target_id'] = $targetid;
4254 $this->context[
'link_target_type'] = $targettype;
4255 $result = $this->call_trigger(
'OBJECT_LINK_DELETE', $f_user);
4263 $sql =
"DELETE FROM " . $this->db->prefix() .
"element_element";
4266 $sql .=
" rowid = " . ((int) $rowid);
4268 if ($deletesource) {
4269 $sql .=
" fk_source = " . ((int) $sourceid) .
" AND sourcetype = '" . $this->db->escape($sourcetype) .
"'";
4270 $sql .=
" AND fk_target = " . ((int) $this->
id) .
" AND targettype = '" . $this->db->escape($this->element) .
"'";
4271 } elseif ($deletetarget) {
4272 $sql .=
" fk_target = " . ((int) $targetid) .
" AND targettype = '" . $this->db->escape($targettype) .
"'";
4273 $sql .=
" AND fk_source = " . ((int) $this->
id) .
" AND sourcetype = '" . $this->db->escape($this->element) .
"'";
4275 $sql .=
" (fk_source = " . ((int) $this->
id) .
" AND sourcetype = '" . $this->db->escape($this->element) .
"')";
4277 $sql .=
" (fk_target = " . ((int) $this->
id) .
" AND targettype = '" . $this->db->escape($this->element) .
"')";
4281 dol_syslog(get_class($this) .
"::deleteObjectLinked", LOG_DEBUG);
4282 if (!$this->db->query($sql)) {
4283 $this->error = $this->db->lasterror();
4284 $this->errors[] = $this->error;
4290 $this->db->commit();
4293 $this->db->rollback();
4309 if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
4315 $sql =
"SELECT ".$field_select.
" FROM ".$db->prefix().$table_element.
" WHERE ".$field_where.
" = ".((int) $fk_object_where);
4316 $resql = $db->query($sql);
4319 if (!empty($resql)) {
4320 while ($res = $db->fetch_object($resql)) {
4321 $TRes[] = $res->{$field_select};
4338 if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
4344 $sql =
"DELETE FROM ".$db->prefix().$table_element.
" WHERE ".$field_where.
" = ".((int) $fk_object_where);
4345 $resql = $db->query($sql);
4347 if (empty($resql)) {
4364 public function setStatut($status, $elementId =
null, $elementType =
'', $trigkey =
'', $fieldstatus =
'fk_statut')
4366 global $user, $langs, $conf;
4368 $savElementId = $elementId;
4370 $elementId = (!empty($elementId) ? $elementId : $this->id);
4371 $elementTable = (!empty($elementType) ? $elementType : $this->table_element);
4375 if ($elementTable ==
'facture_rec') {
4376 $fieldstatus =
"suspended";
4378 if ($elementTable ==
'mailing') {
4379 $fieldstatus =
"statut";
4381 if ($elementTable ==
'cronjob') {
4382 $fieldstatus =
"status";
4384 if ($elementTable ==
'user') {
4385 $fieldstatus =
"statut";
4387 if ($elementTable ==
'expensereport') {
4388 $fieldstatus =
"fk_statut";
4390 if ($elementTable ==
'commande_fournisseur_dispatch') {
4391 $fieldstatus =
"status";
4393 if (isset($this->fields) && is_array($this->fields) && array_key_exists(
'status', $this->fields)) {
4394 $fieldstatus =
'status';
4397 $sql =
"UPDATE ".$this->db->prefix().$elementTable;
4398 $sql .=
" SET ".$fieldstatus.
" = ".((int) $status);
4401 if ($status == 1 && in_array($elementTable, array(
'expensereport',
'inventory'))) {
4402 $sql .=
", fk_user_valid = ".((int) $user->id);
4404 if ($status == 1 && in_array($elementTable, array(
'expensereport'))) {
4405 $sql .=
", date_valid = '".$this->db->idate(
dol_now()).
"'";
4407 if ($status == 1 && in_array($elementTable, array(
'inventory'))) {
4408 $sql .=
", date_validation = '".$this->db->idate(
dol_now()).
"'";
4410 $sql .=
" WHERE rowid = ".((int) $elementId);
4411 $sql .=
" AND ".$fieldstatus.
" <> ".((int) $status);
4413 dol_syslog(get_class($this).
"::setStatut", LOG_DEBUG);
4414 $resql = $this->db->query($sql);
4418 $nb_rows_affected = $this->db->affected_rows($resql);
4420 if ($nb_rows_affected > 0) {
4421 if (empty($trigkey)) {
4423 if ($this->element ==
'supplier_proposal' && $status == 2) {
4424 $trigkey =
'SUPPLIER_PROPOSAL_SIGN';
4426 if ($this->element ==
'supplier_proposal' && $status == 3) {
4427 $trigkey =
'SUPPLIER_PROPOSAL_REFUSE';
4429 if ($this->element ==
'supplier_proposal' && $status == 4) {
4430 $trigkey =
'SUPPLIER_PROPOSAL_CLOSE';
4432 if ($this->element ==
'fichinter' && $status == 3) {
4433 $trigkey =
'FICHINTER_CLASSIFY_DONE';
4435 if ($this->element ==
'fichinter' && $status == 2) {
4436 $trigkey =
'FICHINTER_CLASSIFY_BILLED';
4438 if ($this->element ==
'fichinter' && $status == 1) {
4439 $trigkey =
'FICHINTER_CLASSIFY_UNBILLED';
4445 $result = $this->call_trigger($trigkey, $user);
4456 $this->db->commit();
4458 if (empty($savElementId)) {
4460 if ($fieldstatus ==
'tosell') {
4461 $this->status = $status;
4462 } elseif ($fieldstatus ==
'tobuy') {
4463 $this->status_buy = $status;
4466 $this->status = $status;
4472 $this->db->rollback();
4473 dol_syslog(get_class($this).
"::setStatut ".$this->error, LOG_ERR);
4477 $this->error = $this->db->lasterror();
4478 $this->db->rollback();
4495 if (empty($id) && empty($ref)) {
4498 if (!empty($conf->global->MAIN_DISABLE_CANVAS)) {
4505 $sql =
"SELECT rowid, canvas";
4506 $sql .=
" FROM ".$this->db->prefix().$this->table_element;
4507 $sql .=
" WHERE entity IN (".getEntity($this->element).
")";
4509 $sql .=
" AND rowid = ".((int) $id);
4512 $sql .=
" AND ref = '".$this->db->escape($ref).
"'";
4515 $resql = $this->db->query($sql);
4517 $obj = $this->db->fetch_object($resql);
4519 $this->canvas = $obj->canvas;
4539 $sql =
"SELECT special_code FROM ".$this->db->prefix().$this->table_element_line;
4540 $sql .=
" WHERE rowid = ".((int) $lineid);
4541 $resql = $this->db->query($sql);
4543 $row = $this->db->fetch_row($resql);
4544 return (!empty($row[0]) ? $row[0] : 0);
4567 if (!isset($this->childtables) || !is_array($this->childtables) || count($this->childtables) == 0) {
4568 dol_print_error(
'Called isObjectUsed on a class with property this->childtables not defined');
4572 $arraytoscan = $this->childtables;
4574 $tmparray = array_keys($this->childtables);
4575 if (is_numeric($tmparray[0])) {
4576 $arraytoscan = array_flip($this->childtables);
4581 foreach ($arraytoscan as $table => $element) {
4584 $sql =
"SELECT COUNT(*) as nb";
4585 $sql.=
" FROM ".$this->db->prefix().$table.
" as c";
4586 if (!empty($element[
'parent']) && !empty($element[
'parentkey'])) {
4587 $sql.=
", ".$this->db->prefix().$element[
'parent'].
" as p";
4589 if (!empty($element[
'fk_element'])) {
4590 $sql.=
" WHERE c.".$element[
'fk_element'].
" = ".((int) $id);
4592 $sql.=
" WHERE c.".$this->fk_element.
" = ".((int) $id);
4594 if (!empty($element[
'parent']) && !empty($element[
'parentkey'])) {
4595 $sql.=
" AND c.".$element[
'parentkey'].
" = p.rowid";
4597 if (!empty($element[
'parent']) && !empty($element[
'parenttypefield']) && !empty($element[
'parenttypevalue'])) {
4598 $sql.=
" AND c.".$element[
'parenttypefield'].
" = '".$this->db->escape($element[
'parenttypevalue']).
"'";
4600 if (!empty($entity)) {
4601 if (!empty($element[
'parent']) && !empty($element[
'parentkey'])) {
4602 $sql.=
" AND p.entity = ".((int) $entity);
4604 $sql.=
" AND c.entity = ".((int) $entity);
4608 $resql = $this->db->query($sql);
4610 $obj = $this->db->fetch_object($resql);
4612 $langs->load(
"errors");
4614 $haschild += $obj->nb;
4615 if (is_numeric($element)) {
4616 $this->errors[] = $langs->transnoentitiesnoconv(
"ErrorRecordHasAtLeastOneChildOfType", method_exists($this,
'getNomUrl') ? $this->getNomUrl() : $this->ref, $table);
4617 } elseif (is_string($element)) {
4618 $this->errors[] = $langs->transnoentitiesnoconv(
"ErrorRecordHasAtLeastOneChildOfType", method_exists($this,
'getNomUrl') ? $this->getNomUrl() : $this->ref, $langs->transnoentitiesnoconv($element));
4620 $this->errors[] = $langs->transnoentitiesnoconv(
"ErrorRecordHasAtLeastOneChildOfType", method_exists($this,
'getNomUrl') ? $this->getNomUrl() : $this->ref, $langs->transnoentitiesnoconv($element[
'name']));
4625 $this->errors[] = $this->db->lasterror();
4629 if ($haschild > 0) {
4630 $this->errors[] =
"ErrorRecordHasChildren";
4647 foreach ($this->lines as $key => $val) {
4649 if ($predefined == -1) {
4652 if ($predefined == 1 && $val->fk_product > 0) {
4655 if ($predefined == 0 && $val->fk_product <= 0) {
4658 if ($predefined == 2 && $val->fk_product > 0 && $val->product_type == 0) {
4661 if ($predefined == 3 && $val->fk_product > 0 && $val->product_type == 1) {
4668 dol_syslog(get_class($this).
'::hasProductsOrServices we found '.$nb.
' qualified lines of products/servcies');
4679 if (!empty($this->table_element_line) ) {
4680 $total_discount = 0.00;
4682 $sql =
"SELECT subprice as pu_ht, qty, remise_percent, total_ht";
4683 $sql .=
" FROM ".$this->db->prefix().$this->table_element_line;
4684 $sql .=
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
4686 dol_syslog(get_class($this).
'::getTotalDiscount', LOG_DEBUG);
4687 $resql = $this->db->query($sql);
4689 $num = $this->db->num_rows($resql);
4692 $obj = $this->db->fetch_object($resql);
4694 $pu_ht = $obj->pu_ht;
4696 $total_ht = $obj->total_ht;
4698 $total_discount_line = floatval(
price2num(($pu_ht * $qty) - $total_ht,
'MT'));
4699 $total_discount += $total_discount_line;
4728 foreach ($this->lines as $line) {
4729 if (isset($line->qty_asked)) {
4730 if (empty($totalOrdered)) {
4733 $totalOrdered += $line->qty_asked;
4735 if (isset($line->qty_shipped)) {
4736 if (empty($totalToShip)) {
4739 $totalToShip += $line->qty_shipped;
4740 } elseif ($line->element ==
'commandefournisseurdispatch' && isset($line->qty)) {
4741 if (empty($totalToShip)) {
4744 $totalToShip += $line->qty;
4748 if ($this->element ==
'shipping') {
4750 $qty = $line->qty_shipped ? $line->qty_shipped : 0;
4752 $qty = $line->qty ? $line->qty : 0;
4755 $weight = !empty($line->weight) ? $line->weight : 0;
4756 ($weight == 0 && !empty($line->product->weight)) ? $weight = $line->product->weight : 0;
4757 $volume = !empty($line->volume) ? $line->volume : 0;
4758 ($volume == 0 && !empty($line->product->volume)) ? $volume = $line->product->volume : 0;
4760 $weight_units = !empty($line->weight_units) ? $line->weight_units : 0;
4761 ($weight_units == 0 && !empty($line->product->weight_units)) ? $weight_units = $line->product->weight_units : 0;
4762 $volume_units = !empty($line->volume_units) ? $line->volume_units : 0;
4763 ($volume_units == 0 && !empty($line->product->volume_units)) ? $volume_units = $line->product->volume_units : 0;
4767 if (!empty($weight_units)) {
4768 $weightUnit = $weight_units;
4770 if (!empty($volume_units)) {
4771 $volumeUnit = $volume_units;
4774 if (empty($totalWeight)) {
4777 if (empty($totalVolume)) {
4782 if ($weight_units < 50) {
4783 $trueWeightUnit = pow(10, $weightUnit);
4784 $totalWeight += $weight * $qty * $trueWeightUnit;
4786 if ($weight_units == 99) {
4788 $trueWeightUnit = 0.45359237;
4789 $totalWeight += $weight * $qty * $trueWeightUnit;
4790 } elseif ($weight_units == 98) {
4792 $trueWeightUnit = 0.0283495;
4793 $totalWeight += $weight * $qty * $trueWeightUnit;
4795 $totalWeight += $weight * $qty;
4798 if ($volume_units < 50) {
4800 $trueVolumeUnit = pow(10, $volumeUnit);
4802 $totalVolume += $volume * $qty * $trueVolumeUnit;
4804 $totalVolume += $volume * $qty;
4808 return array(
'weight'=>$totalWeight,
'volume'=>$totalVolume,
'ordered'=>$totalOrdered,
'toship'=>$totalToShip);
4821 $extraparams = (!empty($this->extraparams) ? json_encode($this->extraparams) :
null);
4823 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
4824 $sql .=
" SET extraparams = ".(!empty($extraparams) ?
"'".$this->db->escape($extraparams).
"'" :
"null");
4825 $sql .=
" WHERE rowid = ".((int) $this->
id);
4827 dol_syslog(get_class($this).
"::setExtraParameters", LOG_DEBUG);
4828 $resql = $this->db->query($sql);
4830 $this->error = $this->db->lasterror();
4831 $this->db->rollback();
4834 $this->db->commit();
4857 global $conf, $user, $langs, $object, $hookmanager, $extrafields;
4861 if (!is_object($extrafields)) {
4862 require_once DOL_DOCUMENT_ROOT.
'/core/class/extrafields.class.php';
4865 $extrafields->fetch_name_optionals_label($this->table_element_line);
4870 $dirtpls = array_merge($conf->modules_parts[
'tpl'], array($defaulttpldir));
4871 foreach ($dirtpls as $module => $reldir) {
4872 if (!empty($module)) {
4875 $tpl = DOL_DOCUMENT_ROOT.$reldir.
'/objectline_create.tpl.php';
4878 if (empty($conf->file->strict_mode)) {
4879 $res = @include $tpl;
4881 $res = include $tpl;
4908 public function printObjectLines($action, $seller, $buyer, $selected = 0, $dateSelector = 0, $defaulttpldir =
'/core/tpl')
4910 global $conf, $hookmanager, $langs, $user, $form, $extrafields, $object;
4912 global $inputalsopricewithtax, $usemargins, $disableedit, $disablemove, $disableremove, $outputalsopricetotalwithtax;
4916 if (isModEnabled(
'margin') && !empty($this->element) && in_array($this->element, array(
'facture',
'facturerec',
'propal',
'commande'))) {
4920 $num = count($this->lines);
4923 if (!is_object($extrafields)) {
4924 require_once DOL_DOCUMENT_ROOT.
'/core/class/extrafields.class.php';
4927 $extrafields->fetch_name_optionals_label($this->table_element_line);
4929 $parameters = array(
'num'=>$num,
'dateSelector'=>$dateSelector,
'seller'=>$seller,
'buyer'=>$buyer,
'selected'=>$selected,
'table_element_line'=>$this->table_element_line);
4930 $reshook = $hookmanager->executeHooks(
'printObjectLineTitle', $parameters, $this, $action);
4931 if (empty($reshook)) {
4935 $dirtpls = array_merge($conf->modules_parts[
'tpl'], array($defaulttpldir));
4936 foreach ($dirtpls as $module => $reldir) {
4938 if (!empty($module)) {
4941 $tpl = DOL_DOCUMENT_ROOT.$reldir.
'/objectline_title.tpl.php';
4943 if (file_exists($tpl)) {
4944 if (empty($conf->file->strict_mode)) {
4945 $res = @include $tpl;
4947 $res = include $tpl;
4958 print
"<!-- begin printObjectLines() --><tbody>\n";
4959 foreach ($this->lines as $line) {
4961 $line->fetch_optionals();
4964 if (is_object($hookmanager)) {
4965 if (empty($line->fk_parent_line)) {
4966 $parameters = array(
'line'=>$line,
'num'=>$num,
'i'=>$i,
'dateSelector'=>$dateSelector,
'seller'=>$seller,
'buyer'=>$buyer,
'selected'=>$selected,
'table_element_line'=>$line->table_element,
'defaulttpldir'=>$defaulttpldir);
4967 $reshook = $hookmanager->executeHooks(
'printObjectLine', $parameters, $this, $action);
4969 $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);
4970 $reshook = $hookmanager->executeHooks(
'printObjectSubLine', $parameters, $this, $action);
4973 if (empty($reshook)) {
4974 $this->printObjectLine($action, $line,
'', $num, $i, $dateSelector, $seller, $buyer, $selected, $extrafields, $defaulttpldir);
4979 print
"</tbody><!-- end printObjectLines() -->\n";
4999 public function printObjectLine($action, $line, $var, $num, $i, $dateSelector, $seller, $buyer, $selected = 0, $extrafields =
null, $defaulttpldir =
'/core/tpl')
5001 global $conf, $langs, $user, $object, $hookmanager;
5003 global $object_rights, $disableedit, $disablemove, $disableremove;
5005 $object_rights = $this->getRights();
5011 if ($action !=
'editline' || $selected != $line->id) {
5013 if (!empty($line->fk_product) && $line->fk_product > 0) {
5014 $product_static =
new Product($this->db);
5015 $product_static->fetch($line->fk_product);
5017 $product_static->ref = $line->ref;
5018 $product_static->label = !empty($line->label) ? $line->label :
"";
5020 $text = $product_static->getNomUrl(1);
5024 if (property_exists($this,
'socid') && !is_object($this->thirdparty)) {
5025 dol_print_error(
'',
'Error: Method printObjectLine was called on an object and object->fetch_thirdparty was not done before');
5029 $prod =
new Product($this->db);
5030 $prod->fetch($line->fk_product);
5032 $outputlangs = $langs;
5034 if (empty($newlang) &&
GETPOST(
'lang_id',
'aZ09')) {
5035 $newlang =
GETPOST(
'lang_id',
'aZ09');
5037 if (!empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE) && empty($newlang) && is_object($this->thirdparty)) {
5038 $newlang = $this->thirdparty->default_lang;
5040 if (!empty($newlang)) {
5041 $outputlangs =
new Translate(
"", $conf);
5042 $outputlangs->setDefaultLang($newlang);
5045 $label = (!empty($prod->multilangs[$outputlangs->defaultlang][
"label"])) ? $prod->multilangs[$outputlangs->defaultlang][
"label"] : $line->product_label;
5047 $label = $line->product_label;
5050 $text .=
' - '.(!empty($line->label) ? $line->label : $label);
5051 $description .= (
getDolGlobalInt(
'PRODUIT_DESC_IN_FORM_ACCORDING_TO_DEVICE') ?
'' : (!empty($line->description) ?
dol_htmlentitiesbr($line->description) :
''));
5054 $line->pu_ttc =
price2num((!empty($line->subprice) ? $line->subprice : 0) * (1 + ((!empty($line->tva_tx) ? $line->tva_tx : 0) / 100)),
'MU');
5059 $dirtpls = array_merge($conf->modules_parts[
'tpl'], array($defaulttpldir));
5060 foreach ($dirtpls as $module => $reldir) {
5062 if (!empty($module)) {
5065 $tpl = DOL_DOCUMENT_ROOT.$reldir.
'/objectline_view.tpl.php';
5067 if (file_exists($tpl)) {
5068 if (empty($conf->file->strict_mode)) {
5069 $res = @include $tpl;
5071 $res = include $tpl;
5081 if ($this->
statut == 0 && $action ==
'editline' && $selected == $line->id) {
5082 $label = (!empty($line->label) ? $line->label : (($line->fk_product > 0) ? $line->product_label :
''));
5084 $line->pu_ttc =
price2num($line->subprice * (1 + ($line->tva_tx / 100)),
'MU');
5089 $dirtpls = array_merge($conf->modules_parts[
'tpl'], array($defaulttpldir));
5090 foreach ($dirtpls as $module => $reldir) {
5091 if (!empty($module)) {
5094 $tpl = DOL_DOCUMENT_ROOT.$reldir.
'/objectline_edit.tpl.php';
5097 if (empty($conf->file->strict_mode)) {
5098 $res = @include $tpl;
5100 $res = include $tpl;
5125 global $langs, $hookmanager, $conf, $form, $action;
5127 print
'<tr class="liste_titre">';
5128 print
'<td class="linecolref">'.$langs->trans(
'Ref').
'</td>';
5129 print
'<td class="linecoldescription">'.$langs->trans(
'Description').
'</td>';
5130 print
'<td class="linecolvat right">'.$langs->trans(
'VATRate').
'</td>';
5131 print
'<td class="linecoluht right">'.$langs->trans(
'PriceUHT').
'</td>';
5132 if (isModEnabled(
"multicurrency")) {
5133 print
'<td class="linecoluht_currency right">'.$langs->trans(
'PriceUHTCurrency').
'</td>';
5135 print
'<td class="linecolqty right">'.$langs->trans(
'Qty').
'</td>';
5137 print
'<td class="linecoluseunit left">'.$langs->trans(
'Unit').
'</td>';
5139 print
'<td class="linecoldiscount right">'.$langs->trans(
'ReductionShort').
'</td>';
5140 print
'<td class="linecolht right">'.$langs->trans(
'TotalHT').
'</td>';
5141 print
'<td class="center">'.$form->showCheckAddButtons(
'checkforselect', 1).
'</td>';
5145 if (!empty($this->lines)) {
5146 foreach ($this->lines as $line) {
5149 if (is_object($hookmanager)) {
5150 $parameters = array(
'line'=>$line,
'i'=>$i,
'restrictlist'=>$restrictlist,
'selectedLines'=> $selectedLines);
5151 if (!empty($line->fk_parent_line)) { $parameters[
'fk_parent_line'] = $line->fk_parent_line; }
5152 $reshook = $hookmanager->executeHooks(
'printOriginObjectLine', $parameters, $this, $action);
5154 if (empty($reshook)) {
5155 $this->printOriginLine($line,
'', $restrictlist,
'/core/tpl', $selectedLines);
5176 public function printOriginLine($line, $var, $restrictlist =
'', $defaulttpldir =
'/core/tpl', $selectedLines = array())
5178 global $langs, $conf;
5181 if (!empty($line->date_start)) {
5182 $date_start = $line->date_start;
5184 $date_start = $line->date_debut_prevue;
5185 if ($line->date_debut_reel) {
5186 $date_start = $line->date_debut_reel;
5189 if (!empty($line->date_end)) {
5190 $date_end = $line->date_end;
5192 $date_end = $line->date_fin_prevue;
5193 if ($line->date_fin_reel) {
5194 $date_end = $line->date_fin_reel;
5198 $this->tpl[
'id'] = $line->id;
5200 $this->tpl[
'label'] =
'';
5201 if (!empty($line->fk_parent_line)) {
5202 $this->tpl[
'label'] .=
img_picto(
'',
'rightarrow');
5205 if (($line->info_bits & 2) == 2) {
5207 $discount->fk_soc = $this->socid;
5208 $this->tpl[
'label'] .= $discount->getNomUrl(0,
'discount');
5209 } elseif (!empty($line->fk_product)) {
5210 $productstatic =
new Product($this->db);
5211 $productstatic->id = $line->fk_product;
5212 $productstatic->ref = $line->ref;
5213 $productstatic->type = $line->fk_product_type;
5214 if (empty($productstatic->ref)) {
5215 $line->fetch_product();
5216 $productstatic = $line->product;
5219 $this->tpl[
'label'] .= $productstatic->getNomUrl(1);
5220 $this->tpl[
'label'] .=
' - '.(!empty($line->label) ? $line->label : $line->product_label);
5222 if ($line->product_type == 1 && ($date_start || $date_end)) {
5226 $this->tpl[
'label'] .= ($line->product_type == -1 ?
' ' : ($line->product_type == 1 ?
img_object($langs->trans(
''),
'service') :
img_object($langs->trans(
''),
'product')));
5227 if (!empty($line->desc)) {
5228 $this->tpl[
'label'] .= $line->desc;
5230 $this->tpl[
'label'] .= ($line->label ?
' '.$line->label :
'');
5234 if ($line->product_type == 1 && ($date_start || $date_end)) {
5239 if (!empty($line->desc)) {
5240 if ($line->desc ==
'(CREDIT_NOTE)') {
5242 $discount->fetch($line->fk_remise_except);
5243 $this->tpl[
'description'] = $langs->transnoentities(
"DiscountFromCreditNote", $discount->getNomUrl(0));
5244 } elseif ($line->desc ==
'(DEPOSIT)') {
5246 $discount->fetch($line->fk_remise_except);
5247 $this->tpl[
'description'] = $langs->transnoentities(
"DiscountFromDeposit", $discount->getNomUrl(0));
5248 } elseif ($line->desc ==
'(EXCESS RECEIVED)') {
5250 $discount->fetch($line->fk_remise_except);
5251 $this->tpl[
'description'] = $langs->transnoentities(
"DiscountFromExcessReceived", $discount->getNomUrl(0));
5252 } elseif ($line->desc ==
'(EXCESS PAID)') {
5254 $discount->fetch($line->fk_remise_except);
5255 $this->tpl[
'description'] = $langs->transnoentities(
"DiscountFromExcessPaid", $discount->getNomUrl(0));
5257 $this->tpl[
'description'] =
dol_trunc($line->desc, 60);
5260 $this->tpl[
'description'] =
' ';
5264 $this->tpl[
'vat_rate'] =
vatrate($line->tva_tx,
true);
5265 $this->tpl[
'vat_rate'] .= (($line->info_bits & 1) == 1) ?
'*' :
'';
5266 if (!empty($line->vat_src_code) && !preg_match(
'/\(/', $this->tpl[
'vat_rate'])) {
5267 $this->tpl[
'vat_rate'] .=
' ('.$line->vat_src_code.
')';
5270 $this->tpl[
'price'] =
price($line->subprice);
5271 $this->tpl[
'total_ht'] =
price($line->total_ht);
5272 $this->tpl[
'multicurrency_price'] =
price($line->multicurrency_subprice);
5273 $this->tpl[
'qty'] = (($line->info_bits & 2) != 2) ? $line->qty :
' ';
5275 $this->tpl[
'unit'] = $langs->transnoentities($line->getLabelOfUnit(
'long'));
5277 $this->tpl[
'remise_percent'] = (($line->info_bits & 2) != 2) ?
vatrate($line->remise_percent,
true) :
' ';
5280 $this->tpl[
'strike'] = 0;
5282 $this->tpl[
'strike'] = 1;
5287 $dirtpls = array_merge($conf->modules_parts[
'tpl'], array($defaulttpldir));
5288 foreach ($dirtpls as $module => $reldir) {
5289 if (!empty($module)) {
5292 $tpl = DOL_DOCUMENT_ROOT.$reldir.
'/originproductline.tpl.php';
5295 if (empty($conf->file->strict_mode)) {
5296 $res = @include $tpl;
5298 $res = include $tpl;
5323 $sql =
"INSERT INTO ".$this->db->prefix().
"element_resources (";
5324 $sql .=
"resource_id";
5325 $sql .=
", resource_type";
5326 $sql .=
", element_id";
5327 $sql .=
", element_type";
5329 $sql .=
", mandatory";
5330 $sql .=
") VALUES (";
5331 $sql .= ((int) $resource_id);
5332 $sql .=
", '".$this->db->escape($resource_type).
"'";
5333 $sql .=
", '".$this->db->escape($this->
id).
"'";
5334 $sql .=
", '".$this->db->escape($this->element).
"'";
5335 $sql .=
", '".$this->db->escape($busy).
"'";
5336 $sql .=
", '".$this->db->escape($mandatory).
"'";
5339 dol_syslog(get_class($this).
"::add_element_resource", LOG_DEBUG);
5340 if ($this->db->query($sql)) {
5341 $this->db->commit();
5344 $this->error = $this->db->lasterror();
5345 $this->db->rollback();
5366 $sql =
"DELETE FROM ".$this->db->prefix().
"element_resources";
5367 $sql .=
" WHERE rowid = ".((int) $rowid);
5369 dol_syslog(get_class($this).
"::delete_resource", LOG_DEBUG);
5371 $resql = $this->db->query($sql);
5373 $this->error = $this->db->lasterror();
5374 $this->db->rollback();
5378 $result = $this->call_trigger(strtoupper($element).
'_DELETE_RESOURCE', $user);
5380 $this->db->rollback();
5384 $this->db->commit();
5398 if (isset($this->lines) && is_array($this->lines)) {
5399 $nboflines = count($this->lines);
5400 for ($i = 0; $i < $nboflines; $i++) {
5401 if (is_object($this->lines[$i])) {
5402 $this->lines[$i] = clone $this->lines[$i];
5421 protected function commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams =
null)
5423 global $conf, $langs, $user, $hookmanager, $action;
5425 $srctemplatepath =
'';
5427 $parameters = array(
'modelspath'=>$modelspath,
'modele'=>$modele,
'outputlangs'=>$outputlangs,
'hidedetails'=>$hidedetails,
'hidedesc'=>$hidedesc,
'hideref'=>$hideref,
'moreparams'=>$moreparams);
5428 $reshook = $hookmanager->executeHooks(
'commonGenerateDocument', $parameters, $this, $action);
5430 if (!empty($reshook)) {
5434 dol_syslog(
"commonGenerateDocument modele=".$modele.
" outputlangs->defaultlang=".(is_object($outputlangs) ? $outputlangs->defaultlang :
'null'));
5436 if (empty($modele)) {
5437 $this->error =
'BadValueForParameterModele';
5442 $err = error_reporting();
5444 @set_time_limit(120);
5445 error_reporting($err);
5448 $tmp = explode(
':', $modele, 2);
5449 if (!empty($tmp[1])) {
5451 $srctemplatepath = $tmp[1];
5458 $dirmodels = array(
'/');
5459 if (is_array($conf->modules_parts[
'models'])) {
5460 $dirmodels = array_merge($dirmodels, $conf->modules_parts[
'models']);
5462 foreach ($dirmodels as $reldir) {
5463 foreach (array(
'doc',
'pdf') as $prefix) {
5464 if (in_array(get_class($this), array(
'Adherent'))) {
5466 $file = $prefix.
"_".$modele.
".class.php";
5469 $file = $prefix.
"_".$modele.
".modules.php";
5474 if (file_exists($file)) {
5476 $classname = $prefix.
'_'.$modele;
5486 $this->error = $langs->trans(
"Error").
' Failed to load doc generator with modelpaths='.$modelspath.
' - modele='.$modele;
5487 $this->errors[] = $this->error;
5497 $obj =
new $classname($this->db);
5500 if ($obj->type ==
'odt' && empty($srctemplatepath)) {
5501 $varfortemplatedir = $obj->scandir;
5502 if ($varfortemplatedir && !empty($conf->global->$varfortemplatedir)) {
5503 $dirtoscan = $conf->global->$varfortemplatedir;
5505 $listoffiles = array();
5508 $listofdir = explode(
',', $dirtoscan);
5509 foreach ($listofdir as $key => $tmpdir) {
5510 $tmpdir = trim($tmpdir);
5511 $tmpdir = preg_replace(
'/DOL_DATA_ROOT/', DOL_DATA_ROOT, $tmpdir);
5513 unset($listofdir[$key]);
5516 if (is_dir($tmpdir)) {
5517 $tmpfiles =
dol_dir_list($tmpdir,
'files', 0,
'\.od(s|t)$',
'',
'name', SORT_ASC, 0);
5518 if (count($tmpfiles)) {
5519 $listoffiles = array_merge($listoffiles, $tmpfiles);
5524 if (count($listoffiles)) {
5525 foreach ($listoffiles as $record) {
5526 $srctemplatepath = $record[
'fullname'];
5532 if (empty($srctemplatepath)) {
5533 $this->error =
'ErrorGenerationAskedForOdtTemplateWithSrcFileNotDefined';
5538 if ($obj->type ==
'odt' && !empty($srctemplatepath)) {
5540 dol_syslog(
"Failed to locate template file ".$srctemplatepath, LOG_WARNING);
5541 $this->error =
'ErrorGenerationAskedForOdtTemplateWithSrcFileNotFound';
5548 $sav_charset_output = empty($outputlangs->charset_output) ?
'' : $outputlangs->charset_output;
5550 if (in_array(get_class($this), array(
'Adherent'))) {
5551 $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath,
'member', 1,
'tmp_cards', $moreparams);
5553 $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, $hidedetails, $hidedesc, $hideref, $moreparams);
5557 if ($resultwritefile > 0) {
5558 $outputlangs->charset_output = $sav_charset_output;
5561 require_once DOL_DOCUMENT_ROOT.
'/core/lib/files.lib.php';
5565 if (!empty($obj->result[
'fullpath'])) {
5566 $destfull = $obj->result[
'fullpath'];
5569 $update_main_doc_field = 0;
5570 if (!empty($obj->update_main_doc_field)) {
5571 $update_main_doc_field = 1;
5577 $this->indexFile($destfull, $update_main_doc_field);
5580 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);
5588 $outputlangs->charset_output = $sav_charset_output;
5589 $this->error = $obj->error;
5590 $this->errors = $obj->errors;
5591 dol_syslog(
"Error generating document for ".__CLASS__.
". Error: ".$obj->error, LOG_ERR);
5605 public function indexFile($destfull, $update_main_doc_field)
5607 global $conf, $user;
5609 $upload_dir = dirname($destfull);
5610 $destfile = basename($destfull);
5611 $rel_dir = preg_replace(
'/^'.preg_quote(DOL_DATA_ROOT,
'/').
'/',
'', $upload_dir);
5613 if (!preg_match(
'/[\\/]temp[\\/]|[\\/]thumbs|\.meta$/', $rel_dir)) {
5614 $filename = basename($destfile);
5615 $rel_dir = preg_replace(
'/[\\/]$/',
'', $rel_dir);
5616 $rel_dir = preg_replace(
'/^[\\/]/',
'', $rel_dir);
5618 include_once DOL_DOCUMENT_ROOT.
'/ecm/class/ecmfiles.class.php';
5619 $ecmfile =
new EcmFiles($this->db);
5620 $result = $ecmfile->fetch(0,
'', ($rel_dir ? $rel_dir.
'/' :
'').$filename);
5623 $setsharekey =
false;
5624 if ($this->element ==
'propal' || $this->element ==
'proposal') {
5625 if (!isset($conf->global->PROPOSAL_ALLOW_ONLINESIGN) || !empty($conf->global->PROPOSAL_ALLOW_ONLINESIGN)) {
5626 $setsharekey =
true;
5628 if (!empty($conf->global->PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD)) {
5629 $setsharekey =
true;
5632 if ($this->element ==
'commande' && !empty($conf->global->ORDER_ALLOW_EXTERNAL_DOWNLOAD)) {
5633 $setsharekey =
true;
5635 if ($this->element ==
'facture' && !empty($conf->global->INVOICE_ALLOW_EXTERNAL_DOWNLOAD)) {
5636 $setsharekey =
true;
5638 if ($this->element ==
'bank_account' && !empty($conf->global->BANK_ACCOUNT_ALLOW_EXTERNAL_DOWNLOAD)) {
5639 $setsharekey =
true;
5641 if ($this->element ==
'product' && !empty($conf->global->PRODUCT_ALLOW_EXTERNAL_DOWNLOAD)) {
5642 $setsharekey =
true;
5644 if ($this->element ==
'contrat' && !empty($conf->global->CONTRACT_ALLOW_EXTERNAL_DOWNLOAD)) {
5645 $setsharekey =
true;
5647 if ($this->element ==
'fichinter' && !empty($conf->global->FICHINTER_ALLOW_EXTERNAL_DOWNLOAD)) {
5648 $setsharekey =
true;
5650 if ($this->element ==
'supplier_proposal' && !empty($conf->global->SUPPLIER_PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD)) {
5651 $setsharekey =
true;
5655 if (empty($ecmfile->share)) {
5656 require_once DOL_DOCUMENT_ROOT.
'/core/lib/security2.lib.php';
5663 $ecmfile->fullpath_orig =
'';
5664 $ecmfile->gen_or_uploaded =
'generated';
5665 $ecmfile->description =
'';
5666 $ecmfile->keywords =
'';
5667 $result = $ecmfile->update($user);
5673 $ecmfile->entity = $conf->entity;
5674 $ecmfile->filepath = $rel_dir;
5675 $ecmfile->filename = $filename;
5677 $ecmfile->fullpath_orig =
'';
5678 $ecmfile->gen_or_uploaded =
'generated';
5679 $ecmfile->description =
'';
5680 $ecmfile->keywords =
'';
5681 $ecmfile->src_object_type = $this->table_element;
5682 $ecmfile->src_object_id = $this->id;
5684 $result = $ecmfile->create($user);
5696 if ($update_main_doc_field && !empty($this->table_element)) {
5697 $sql =
"UPDATE ".$this->db->prefix().$this->table_element.
" SET last_main_doc = '".$this->db->escape($ecmfile->filepath.
"/".$ecmfile->filename).
"'";
5698 $sql .=
" WHERE rowid = ".((int) $this->
id);
5700 $resql = $this->db->query($sql);
5705 $this->last_main_doc = $ecmfile->filepath.
'/'.$ecmfile->filename;
5724 if (file_exists($file_osencoded)) {
5725 require_once DOL_DOCUMENT_ROOT.
'/core/lib/images.lib.php';
5728 $maxwidthsmall = $tmparraysize[
'maxwidthsmall'];
5729 $maxheightsmall = $tmparraysize[
'maxheightsmall'];
5730 $maxwidthmini = $tmparraysize[
'maxwidthmini'];
5731 $maxheightmini = $tmparraysize[
'maxheightmini'];
5737 vignette($file_osencoded, $maxwidthsmall, $maxheightsmall,
'_small', $quality);
5741 vignette($file_osencoded, $maxwidthmini, $maxheightmini,
'_mini', $quality);
5780 global $conf, $_POST;
5783 if (GETPOSTISSET($fieldname)) {
5784 return GETPOST($fieldname, $type, 3);
5787 if (isset($alternatevalue)) {
5788 return $alternatevalue;
5791 $newelement = $this->element;
5792 if ($newelement ==
'facture') {
5793 $newelement =
'invoice';
5795 if ($newelement ==
'commande') {
5796 $newelement =
'order';
5798 if (empty($newelement)) {
5799 dol_syslog(
"Ask a default value using common method getDefaultCreateValueForField on an object with no property ->element defined. Return empty string.", LOG_WARNING);
5803 $keyforfieldname = strtoupper($newelement.
'_DEFAULT_'.$fieldname);
5805 if (isset($conf->global->$keyforfieldname)) {
5806 return $conf->global->$keyforfieldname;
5833 global $langs, $conf;
5834 if (!empty(self::TRIGGER_PREFIX) && strpos($triggerName, self::TRIGGER_PREFIX .
'_') !== 0) {
5835 dol_print_error(
'',
'The trigger "' . $triggerName .
'" does not start with "' . self::TRIGGER_PREFIX .
'_" as required.');
5838 if (!is_object($langs)) {
5839 include_once DOL_DOCUMENT_ROOT.
'/core/class/translate.class.php';
5843 include_once DOL_DOCUMENT_ROOT.
'/core/class/interfaces.class.php';
5845 $result = $interface->run_triggers($triggerName, $this, $user, $langs, $conf);
5848 if (!empty($this->errors)) {
5849 $this->errors = array_unique(array_merge($this->errors, $interface->errors));
5851 $this->errors = $interface->errors;
5871 if (!$this->element) {
5874 if (!($this->
id > 0)) {
5877 if (is_array($this->array_languages)) {
5881 $this->array_languages = array();
5883 $element = $this->element;
5884 if ($element ==
'categorie') {
5885 $element =
'categories';
5889 $sql =
"SELECT rowid, property, lang , value";
5890 $sql .=
" FROM ".$this->db->prefix().
"object_lang";
5891 $sql .=
" WHERE type_object = '".$this->db->escape($element).
"'";
5892 $sql .=
" AND fk_object = ".((int) $this->
id);
5895 $resql = $this->db->query($sql);
5897 $numrows = $this->db->num_rows($resql);
5900 while ($i < $numrows) {
5901 $obj = $this->db->fetch_object($resql);
5902 $key = $obj->property;
5903 $value = $obj->value;
5904 $codelang = $obj->lang;
5905 $type = $this->fields[$key][
'type'];
5908 if (preg_match(
'/date/', $type)) {
5909 $this->array_languages[$key][$codelang] = $this->db->jdate($value);
5911 $this->array_languages[$key][$codelang] = $value;
5918 $this->db->free($resql);
5939 global $_POST, $langs;
5942 foreach ($_POST as $postfieldkey => $postfieldvalue) {
5943 $tmparray = explode(
'-', $postfieldkey);
5944 if ($tmparray[0] !=
'field') {
5948 $element = $tmparray[1];
5949 $key = $tmparray[2];
5950 $codelang = $tmparray[3];
5953 if (!empty($onlykey) && $key != $onlykey) {
5956 if ($element != $this->element) {
5960 $key_type = $this->fields[$key][
'type'];
5963 if (isset($this->fields[$key][
'enabled'])) {
5964 $enabled =
dol_eval($this->fields[$key][
'enabled'], 1, 1,
'1');
5971 if (empty($enabled)) {
5976 if (in_array($key_type, array(
'date'))) {
5980 } elseif (in_array($key_type, array(
'datetime'))) {
5983 $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'));
5984 } elseif (in_array($key_type, array(
'checkbox',
'chkbxlst'))) {
5985 $value_arr =
GETPOST($postfieldkey,
'array');
5986 if (!empty($value_arr)) {
5987 $value_key = implode(
',', $value_arr);
5991 } elseif (in_array($key_type, array(
'price',
'double'))) {
5992 $value_arr =
GETPOST($postfieldkey,
'alpha');
5995 $value_key =
GETPOST($postfieldkey);
5996 if (in_array($key_type, array(
'link')) && $value_key ==
'-1') {
6001 $this->array_languages[$key][$codelang] = $value_key;
6026 $savDisableCompute = $conf->disable_compute;
6027 $conf->disable_compute = 1;
6029 $ret = $this->fetch($id);
6031 $conf->disable_compute = $savDisableCompute;
6049 global $conf, $extrafields;
6051 if (empty($rowid)) {
6054 if (empty($rowid) && isset($this->
rowid)) {
6055 $rowid = $this->rowid;
6059 if (!$this->table_element) {
6063 $this->array_options = array();
6065 if (!is_array($optionsArray)) {
6067 if (!isset($extrafields) || !is_object($extrafields)) {
6068 require_once DOL_DOCUMENT_ROOT.
'/core/class/extrafields.class.php';
6073 if (empty($extrafields->attributes[$this->table_element][
'loaded'])) {
6074 $extrafields->fetch_name_optionals_label($this->table_element);
6076 $optionsArray = (!empty($extrafields->attributes[$this->table_element][
'label']) ? $extrafields->attributes[$this->table_element][
'label'] :
null);
6078 global $extrafields;
6079 dol_syslog(
"Warning: fetch_optionals was called with param optionsArray defined when you should pass null now", LOG_WARNING);
6082 $table_element = $this->table_element;
6083 if ($table_element ==
'categorie') {
6084 $table_element =
'categories';
6088 if (is_array($optionsArray) && count($optionsArray) > 0) {
6089 $sql =
"SELECT rowid";
6090 foreach ($optionsArray as $name => $label) {
6091 if (empty($extrafields->attributes[$this->table_element][
'type'][$name]) || $extrafields->attributes[$this->table_element][
'type'][$name] !=
'separate') {
6095 $sql .=
" FROM ".$this->db->prefix().$table_element.
"_extrafields";
6096 $sql .=
" WHERE fk_object = ".((int) $rowid);
6099 $resql = $this->db->query($sql);
6101 $numrows = $this->db->num_rows($resql);
6103 $tab = $this->db->fetch_array($resql);
6105 foreach ($tab as $key => $value) {
6107 if ($key !=
'rowid' && $key !=
'tms' && $key !=
'fk_member' && !is_int($key)) {
6109 if (!empty($extrafields->attributes[$this->table_element]) && in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'date',
'datetime'))) {
6111 $this->array_options[
"options_".$key] = $this->db->jdate($value);
6113 $this->array_options[
"options_".$key] = $value;
6123 if (is_array($extrafields->attributes[$this->table_element][
'label'])) {
6124 foreach ($extrafields->attributes[$this->table_element][
'label'] as $key => $val) {
6125 if (!empty($extrafields->attributes[$this->table_element]) && !empty($extrafields->attributes[$this->table_element][
'computed'][$key])) {
6127 if (empty($conf->disable_compute)) {
6128 global $objectoffield;
6129 $objectoffield = $this;
6130 $this->array_options[
'options_' . $key] =
dol_eval($extrafields->attributes[$this->table_element][
'computed'][$key], 1, 0,
'');
6136 $this->db->free($resql);
6144 $this->errors[]=$this->db->lasterror;
6161 if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
6167 $table_element = $this->table_element;
6168 if ($table_element ==
'categorie') {
6169 $table_element =
'categories';
6172 dol_syslog(get_class($this).
"::deleteExtraFields delete", LOG_DEBUG);
6174 $sql_del =
"DELETE FROM ".$this->db->prefix().$table_element.
"_extrafields WHERE fk_object = ".((int) $this->
id);
6176 $resql = $this->db->query($sql_del);
6178 $this->error = $this->db->lasterror();
6179 $this->db->rollback();
6182 $this->db->commit();
6199 global $conf, $langs, $user;
6201 if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
6205 if (empty($userused)) {
6211 if (!empty($this->array_options)) {
6213 $langs->load(
'admin');
6214 require_once DOL_DOCUMENT_ROOT.
'/core/class/extrafields.class.php';
6216 $target_extrafields = $extrafields->fetch_name_optionals_label($this->table_element);
6219 $new_array_options = array();
6220 foreach ($this->array_options as $key => $value) {
6221 if (in_array(substr($key, 8), array_keys($target_extrafields))) {
6222 $new_array_options[$key] = $value;
6223 } elseif (in_array($key, array_keys($target_extrafields))) {
6224 $new_array_options[
'options_'.$key] = $value;
6228 foreach ($new_array_options as $key => $value) {
6229 $attributeKey = substr($key, 8);
6230 $attributeType = $extrafields->attributes[$this->table_element][
'type'][$attributeKey];
6231 $attributeLabel = $langs->transnoentities($extrafields->attributes[$this->table_element][
'label'][$attributeKey]);
6232 $attributeParam = $extrafields->attributes[$this->table_element][
'param'][$attributeKey];
6233 $attributeRequired = $extrafields->attributes[$this->table_element][
'required'][$attributeKey];
6234 $attributeUnique = $extrafields->attributes[$this->table_element][
'unique'][$attributeKey];
6235 $attrfieldcomputed = $extrafields->attributes[$this->table_element][
'computed'][$attributeKey];
6239 if (!empty($this->context[
'createfromclone']) && $this->context[
'createfromclone'] ==
'createfromclone' && !empty($attributeUnique)) {
6240 $new_array_options[$key] =
null;
6244 if ($attributeRequired) {
6245 $mandatorypb =
false;
6246 if ($attributeType ==
'link' && $this->array_options[$key] ==
'-1') {
6247 $mandatorypb =
true;
6249 if ($this->array_options[$key] ===
'') {
6250 $mandatorypb =
true;
6252 if ($attributeType ==
'sellist' && $this->array_options[$key] ==
'0') {
6253 $mandatorypb =
true;
6256 $langs->load(
"errors");
6257 dol_syslog(
"Mandatory field '".$key.
"' is empty during create and set to required into definition of extrafields");
6258 $this->errors[] = $langs->trans(
'ErrorFieldRequired', $attributeLabel);
6266 if (!empty($attrfieldcomputed)) {
6267 if (!empty($conf->global->MAIN_STORE_COMPUTED_EXTRAFIELDS)) {
6268 $value =
dol_eval($attrfieldcomputed, 1, 0,
'');
6269 dol_syslog($langs->trans(
"Extrafieldcomputed").
" sur ".$attributeLabel.
"(".$value.
")", LOG_DEBUG);
6270 $new_array_options[$key] = $value;
6272 $new_array_options[$key] =
null;
6276 switch ($attributeType) {
6278 if (!is_numeric($value) && $value !=
'') {
6279 $this->errors[] = $langs->trans(
"ExtraFieldHasWrongValue", $attributeLabel);
6281 } elseif ($value ==
'') {
6282 $new_array_options[$key] =
null;
6288 if (!is_numeric($value) && $value !=
'') {
6289 dol_syslog($langs->trans(
"ExtraFieldHasWrongValue").
" for ".$attributeLabel.
"(".$value.
"is not '".$attributeType.
"')", LOG_DEBUG);
6290 $this->errors[] = $langs->trans(
"ExtraFieldHasWrongValue", $attributeLabel);
6292 } elseif ($value ==
'') {
6296 $new_array_options[$key] = $value;
6306 if ($this->array_options[$key] !=
'' && is_array($extrafields->attributes[$this->table_element][
'param'][$attributeKey][
'options'])) {
6308 $tmparrays = array_keys($extrafields->attributes[$this->table_element][
'param'][$attributeKey][
'options']);
6309 $algo = reset($tmparrays);
6314 if (is_object($this->oldcopy)) {
6316 if (isset($this->oldcopy->array_options[$key]) && $this->array_options[$key] == $this->oldcopy->array_options[$key]) {
6317 $new_array_options[$key] = $this->array_options[$key];
6320 $newvalue =
dol_hash($this->array_options[$key], $algo);
6321 $new_array_options[$key] = $newvalue;
6324 $new_array_options[$key] = $this->array_options[$key];
6329 $new_array_options[$key] = $this->array_options[$key];
6335 if (!is_numeric($this->array_options[$key]) || $this->array_options[$key] != intval($this->array_options[$key])) {
6336 $this->array_options[$key] = strtotime($this->array_options[$key]);
6338 $new_array_options[$key] = $this->db->idate($this->array_options[$key]);
6342 if (!is_numeric($this->array_options[$key]) || $this->array_options[$key] != intval($this->array_options[$key])) {
6343 $this->array_options[$key] = strtotime($this->array_options[$key]);
6345 $new_array_options[$key] = $this->db->idate($this->array_options[$key],
'gmt');
6348 $param_list = array_keys($attributeParam[
'options']);
6351 $InfoFieldList = explode(
":", $param_list[0]);
6353 if ($InfoFieldList[0] && class_exists($InfoFieldList[0])) {
6354 if ($value ==
'-1') {
6355 $new_array_options[$key] =
'';
6357 $object =
new $InfoFieldList[0]($this->db);
6358 if (is_numeric($value)) {
6359 $res = $object->fetch($value);
6361 $res = $object->fetch(
'', $value);
6365 $new_array_options[$key] = $object->id;
6367 $this->error =
"Id/Ref '".$value.
"' for object '".$object->element.
"' not found";
6372 dol_syslog(
'Error bad setup of extrafield', LOG_WARNING);
6377 if (is_array($this->array_options[$key])) {
6378 $new_array_options[$key] = implode(
',', $this->array_options[$key]);
6380 $new_array_options[$key] = $this->array_options[$key];
6388 $table_element = $this->table_element;
6389 if ($table_element ==
'categorie') {
6390 $table_element =
'categories';
6393 dol_syslog(get_class($this).
"::insertExtraFields delete then insert", LOG_DEBUG);
6395 $sql_del =
"DELETE FROM ".$this->db->prefix().$table_element.
"_extrafields WHERE fk_object = ".((int) $this->
id);
6396 $this->db->query($sql_del);
6398 $sql =
"INSERT INTO ".$this->db->prefix().$table_element.
"_extrafields (fk_object";
6399 foreach ($new_array_options as $key => $value) {
6400 $attributeKey = substr($key, 8);
6402 if ($extrafields->attributes[$this->table_element][
'type'][$attributeKey] !=
'separate') {
6403 $sql .=
",".$attributeKey;
6407 if (!empty($extrafields->attributes[$this->table_element][
'mandatoryfieldsofotherentities']) && is_array($extrafields->attributes[$this->table_element][
'mandatoryfieldsofotherentities'])) {
6408 foreach ($extrafields->attributes[$this->table_element][
'mandatoryfieldsofotherentities'] as $tmpkey => $tmpval) {
6409 if (!isset($extrafields->attributes[$this->table_element][
'type'][$tmpkey])) {
6410 $sql .=
",".$tmpkey;
6414 $sql .=
") VALUES (".$this->id;
6416 foreach ($new_array_options as $key => $value) {
6417 $attributeKey = substr($key, 8);
6419 if ($extrafields->attributes[$this->table_element][
'type'][$attributeKey] !=
'separate') {
6420 if ($new_array_options[$key] !=
'' || $new_array_options[$key] ==
'0') {
6421 $sql .=
",'".$this->db->escape($new_array_options[$key]).
"'";
6428 if (!empty($extrafields->attributes[$this->table_element][
'mandatoryfieldsofotherentities']) && is_array($extrafields->attributes[$this->table_element][
'mandatoryfieldsofotherentities'])) {
6429 foreach ($extrafields->attributes[$this->table_element][
'mandatoryfieldsofotherentities'] as $tmpkey => $tmpval) {
6430 if (!isset($extrafields->attributes[$this->table_element][
'type'][$tmpkey])) {
6431 if (in_array($tmpval, array(
'int',
'double',
'price'))) {
6442 $resql = $this->db->query($sql);
6444 $this->error = $this->db->lasterror();
6448 if (!$error && $trigger) {
6450 $this->context = array(
'extrafieldaddupdate'=>1);
6451 $result = $this->call_trigger($trigger, $userused);
6459 $this->db->rollback();
6462 $this->db->commit();
6482 global $conf, $langs, $user;
6484 if (empty($userused)) {
6490 if (!empty($conf->global->MAIN_EXTRALANGUAGES_DISABLED)) {
6494 if (is_array($this->array_languages)) {
6495 $new_array_languages = $this->array_languages;
6497 foreach ($new_array_languages as $key => $value) {
6498 $attributeKey = $key;
6499 $attributeType = $this->fields[$attributeKey][
'type'];
6500 $attributeLabel = $this->fields[$attributeKey][
'label'];
6505 switch ($attributeType) {
6507 if (!is_numeric($value) && $value !=
'') {
6508 $this->errors[] = $langs->trans(
"ExtraLanguageHasWrongValue", $attributeLabel);
6510 } elseif ($value ==
'') {
6511 $new_array_languages[$key] =
null;
6516 if (!is_numeric($value) && $value !=
'') {
6517 dol_syslog($langs->trans(
"ExtraLanguageHasWrongValue").
" sur ".$attributeLabel.
"(".$value.
"is not '".$attributeType.
"')", LOG_DEBUG);
6518 $this->errors[] = $langs->trans(
"ExtraLanguageHasWrongValue", $attributeLabel);
6520 } elseif ($value ==
'') {
6521 $new_array_languages[$key] =
null;
6523 $new_array_languages[$key] = $value;
6537 $table_element = $this->table_element;
6538 if ($table_element ==
'categorie') {
6539 $table_element =
'categories';
6542 dol_syslog(get_class($this).
"::insertExtraLanguages delete then insert", LOG_DEBUG);
6544 foreach ($new_array_languages as $key => $langcodearray) {
6545 foreach ($langcodearray as $langcode => $value) {
6546 $sql_del =
"DELETE FROM ".$this->db->prefix().
"object_lang";
6547 $sql_del .=
" WHERE fk_object = ".((int) $this->
id).
" AND property = '".$this->db->escape($key).
"' AND type_object = '".$this->db->escape($table_element).
"'";
6548 $sql_del .=
" AND lang = '".$this->db->escape($langcode).
"'";
6549 $this->db->query($sql_del);
6551 if ($value !==
'') {
6552 $sql =
"INSERT INTO ".$this->db->prefix().
"object_lang (fk_object, property, type_object, lang, value";
6553 $sql .=
") VALUES (".$this->id.
", '".$this->db->escape($key).
"', '".$this->db->escape($table_element).
"', '".$this->db->escape($langcode).
"', '".$this->db->escape($value).
"'";
6556 $resql = $this->db->query($sql);
6558 $this->error = $this->db->lasterror();
6566 if (!$error && $trigger) {
6568 $this->context = array(
'extralanguagesaddupdate'=>1);
6569 $result = $this->call_trigger($trigger, $userused);
6577 $this->db->rollback();
6580 $this->db->commit();
6600 global $conf, $langs, $user;
6602 if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
6606 if (empty($userused)) {
6612 if (!empty($this->array_options) && isset($this->array_options[
"options_".$key])) {
6614 $langs->load(
'admin');
6615 require_once DOL_DOCUMENT_ROOT.
'/core/class/extrafields.class.php';
6617 $extrafields->fetch_name_optionals_label($this->table_element);
6619 $value = $this->array_options[
"options_".$key];
6621 $attributeType = $extrafields->attributes[$this->table_element][
'type'][$key];
6622 $attributeLabel = $extrafields->attributes[$this->table_element][
'label'][$key];
6623 $attributeParam = $extrafields->attributes[$this->table_element][
'param'][$key];
6624 $attributeRequired = $extrafields->attributes[$this->table_element][
'required'][$key];
6625 $attrfieldcomputed = $extrafields->attributes[$this->table_element][
'computed'][$key];
6628 if ($attributeRequired) {
6629 $mandatorypb =
false;
6630 if ($attributeType ==
'link' && $this->array_options[
"options_".$key] ==
'-1') {
6631 $mandatorypb =
true;
6633 if ($this->array_options[
"options_".$key] ===
'') {
6634 $mandatorypb =
true;
6637 $langs->load(
"errors");
6638 dol_syslog(
"Mandatory field 'options_".$key.
"' is empty during update and set to required into definition of extrafields");
6639 $this->errors[] = $langs->trans(
'ErrorFieldRequired', $attributeLabel);
6647 if (!empty($attrfieldcomputed)) {
6648 if (!empty($conf->global->MAIN_STORE_COMPUTED_EXTRAFIELDS)) {
6649 $value =
dol_eval($attrfieldcomputed, 1, 0,
'');
6650 dol_syslog($langs->trans(
"Extrafieldcomputed").
" sur ".$attributeLabel.
"(".$value.
")", LOG_DEBUG);
6651 $this->array_options[
"options_".$key] = $value;
6653 $this->array_options[
"options_".$key] =
null;
6657 switch ($attributeType) {
6659 if (!is_numeric($value) && $value !=
'') {
6660 $this->errors[] = $langs->trans(
"ExtraFieldHasWrongValue", $attributeLabel);
6662 } elseif ($value ===
'') {
6663 $this->array_options[
"options_".$key] =
null;
6669 if (!is_numeric($value) && $value !=
'') {
6670 dol_syslog($langs->trans(
"ExtraFieldHasWrongValue").
" sur ".$attributeLabel.
"(".$value.
"is not '".$attributeType.
"')", LOG_DEBUG);
6671 $this->errors[] = $langs->trans(
"ExtraFieldHasWrongValue", $attributeLabel);
6673 } elseif ($value ===
'') {
6677 $this->array_options[
"options_".$key] = $value;
6687 if (empty($this->array_options[
"options_".$key])) {
6688 $this->array_options[
"options_".$key] =
null;
6690 $this->array_options[
"options_".$key] = $this->db->idate($this->array_options[
"options_".$key]);
6694 if (empty($this->array_options[
"options_".$key])) {
6695 $this->array_options[
"options_".$key] =
null;
6697 $this->array_options[
"options_".$key] = $this->db->idate($this->array_options[
"options_".$key],
'gmt');
6701 if (empty($this->array_options[
"options_".$key])) {
6702 $this->array_options[
"options_".$key] =
null;
6706 if ($this->array_options[
"options_".$key] ===
'') {
6707 $this->array_options[
"options_".$key] =
null;
6741 if (is_array($this->array_options[$key])) {
6742 $new_array_options[$key] = implode(
',', $this->array_options[$key]);
6744 $new_array_options[$key] = $this->array_options[$key];
6751 $linealreadyfound = 0;
6754 $sql =
"SELECT COUNT(rowid) as nb FROM ".$this->db->prefix().$this->table_element.
"_extrafields WHERE fk_object = ".((int) $this->
id);
6755 $resql = $this->db->query($sql);
6757 $tmpobj = $this->db->fetch_object($resql);
6759 $linealreadyfound = $tmpobj->nb;
6763 if ($linealreadyfound) {
6764 if ($this->array_options[
"options_".$key] ===
null) {
6765 $sql =
"UPDATE ".$this->db->prefix().$this->table_element.
"_extrafields SET ".$key.
" = null";
6767 $sql =
"UPDATE ".$this->db->prefix().$this->table_element.
"_extrafields SET ".$key.
" = '".$this->db->escape($this->array_options[
"options_".$key]).
"'";
6769 $sql .=
" WHERE fk_object = ".((int) $this->
id);
6771 $result = $this->insertExtraFields(
'', $user);
6777 $resql = $this->db->query($sql);
6780 $this->error = $this->db->lasterror();
6782 if (!$error && $trigger) {
6784 $this->context = array(
'extrafieldupdate'=>1);
6785 $result = $this->call_trigger($trigger, $userused);
6793 dol_syslog(__METHOD__.$this->error, LOG_ERR);
6794 $this->db->rollback();
6797 $this->db->commit();
6817 global $conf, $langs, $user;
6819 if (empty($userused)) {
6825 if (!empty($conf->global->MAIN_EXTRALANGUAGES_DISABLED)) {
6847 public function showInputField($val, $key, $value, $moreparam =
'', $keysuffix =
'', $keyprefix =
'', $morecss = 0, $nonewbutton = 0)
6849 global $conf, $langs, $form;
6851 if (!is_object($form)) {
6852 require_once DOL_DOCUMENT_ROOT.
'/core/class/html.form.class.php';
6853 $form =
new Form($this->db);
6856 if (!empty($this->fields)) {
6857 $val = $this->fields[$key];
6861 $fieldValidationErrorMsg =
'';
6862 $validationClass =
'';
6863 $fieldValidationErrorMsg = $this->getFieldError($key);
6864 if (!empty($fieldValidationErrorMsg)) {
6865 $validationClass =
' --error';
6867 $validationClass =
' --success';
6874 $param[
'options'] = array();
6876 $size = !empty($this->fields[$key][
'size']) ? $this->fields[$key][
'size'] : 0;
6878 if (preg_match(
'/^(integer|link):(.*):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
6879 $param[
'options'] = array($reg[2].
':'.$reg[3].
':'.$reg[4].
':'.$reg[5] =>
'N');
6881 } elseif (preg_match(
'/^(integer|link):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
6882 $param[
'options'] = array($reg[2].
':'.$reg[3].
':'.$reg[4] =>
'N');
6884 } elseif (preg_match(
'/^(integer|link):(.*):(.*)/i', $val[
'type'], $reg)) {
6885 $param[
'options'] = array($reg[2].
':'.$reg[3] =>
'N');
6887 } elseif (preg_match(
'/^(sellist):(.*):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
6888 $param[
'options'] = array($reg[2].
':'.$reg[3].
':'.$reg[4].
':'.$reg[5] =>
'N');
6890 } elseif (preg_match(
'/^(sellist):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
6891 $param[
'options'] = array($reg[2].
':'.$reg[3].
':'.$reg[4] =>
'N');
6893 } elseif (preg_match(
'/^(sellist):(.*):(.*)/i', $val[
'type'], $reg)) {
6894 $param[
'options'] = array($reg[2].
':'.$reg[3] =>
'N');
6896 } elseif (preg_match(
'/^chkbxlst:(.*)/i', $val[
'type'], $reg)) {
6897 $param[
'options'] = array($reg[1] =>
'N');
6899 } elseif (preg_match(
'/varchar\((\d+)\)/', $val[
'type'], $reg)) {
6900 $param[
'options'] = array();
6903 } elseif (preg_match(
'/varchar/', $val[
'type'])) {
6904 $param[
'options'] = array();
6907 $param[
'options'] = array();
6908 $type = $this->fields[$key][
'type'];
6912 if (!empty($this->fields[$key][
'arrayofkeyval']) && is_array($this->fields[$key][
'arrayofkeyval'])) {
6913 $param[
'options'] = $this->fields[$key][
'arrayofkeyval'];
6917 $label = $this->fields[$key][
'label'];
6919 $default = (!empty($this->fields[$key][
'default']) ? $this->fields[$key][
'default'] :
'');
6920 $computed = (!empty($this->fields[$key][
'computed']) ? $this->fields[$key][
'computed'] :
'');
6921 $unique = (!empty($this->fields[$key][
'unique']) ? $this->fields[$key][
'unique'] : 0);
6922 $required = (!empty($this->fields[$key][
'required']) ? $this->fields[$key][
'required'] : 0);
6923 $autofocusoncreate = (!empty($this->fields[$key][
'autofocusoncreate']) ? $this->fields[$key][
'autofocusoncreate'] : 0);
6925 $langfile = (!empty($this->fields[$key][
'langfile']) ? $this->fields[$key][
'langfile'] :
'');
6926 $list = (!empty($this->fields[$key][
'list']) ? $this->fields[$key][
'list'] : 0);
6927 $hidden = (in_array(abs($this->fields[$key][
'visible']), array(0, 2)) ? 1 : 0);
6929 $objectid = $this->id;
6932 if (!preg_match(
'/^search_/', $keyprefix)) {
6933 return '<span class="opacitymedium">'.$langs->trans(
"AutomaticallyCalculated").
'</span>';
6940 if (empty($morecss) && !empty($val[
'css'])) {
6941 $morecss = $val[
'css'];
6942 } elseif (empty($morecss)) {
6943 if ($type ==
'date') {
6944 $morecss =
'minwidth100imp';
6945 } elseif ($type ==
'datetime' || $type ==
'link') {
6946 $morecss =
'minwidth200imp';
6947 } elseif (in_array($type, array(
'int',
'integer',
'price')) || preg_match(
'/^double(\([0-9],[0-9]\)){0,1}/', $type)) {
6948 $morecss =
'maxwidth75';
6949 } elseif ($type ==
'url') {
6950 $morecss =
'minwidth400';
6951 } elseif ($type ==
'boolean') {
6954 if (round($size) < 12) {
6955 $morecss =
'minwidth100';
6956 } elseif (round($size) <= 48) {
6957 $morecss =
'minwidth200';
6959 $morecss =
'minwidth400';
6965 if (!empty($validationClass)) {
6966 $morecss.= $validationClass;
6969 if (in_array($type, array(
'date'))) {
6970 $tmp = explode(
',', $size);
6975 if (!$required && $value ==
'') {
6980 $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required,
'', 1, (($keyprefix !=
'search_' && $keyprefix !=
'search_options_') ? 1 : 0), 0, 1);
6981 } elseif (in_array($type, array(
'datetime'))) {
6982 $tmp = explode(
',', $size);
6987 if (!$required && $value ==
'') $value =
'-1';
6990 $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required,
'', 1, (($keyprefix !=
'search_' && $keyprefix !=
'search_options_') ? 1 : 0), 0, 1,
'',
'',
'', 1,
'',
'',
'tzuserrel');
6991 } elseif (in_array($type, array(
'duration'))) {
6992 $out = $form->select_duration($keyprefix.$key.$keysuffix, $value, 0,
'text', 0, 1);
6993 } elseif (in_array($type, array(
'int',
'integer'))) {
6994 $tmp = explode(
',', $size);
6996 $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' :
'').
'>';
6997 } elseif (in_array($type, array(
'real'))) {
6998 $out =
'<input type="text" class="flat '.$morecss.
'" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.
dol_escape_htmltag($value).
'"'.($moreparam ? $moreparam :
'').($autofocusoncreate ?
' autofocus' :
'').
'>';
6999 } elseif (preg_match(
'/varchar/', $type)) {
7000 $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' :
'').
'>';
7001 } elseif (in_array($type, array(
'email',
'mail',
'phone',
'url',
'ip'))) {
7002 $out =
'<input type="text" class="flat '.$morecss.
'" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.
dol_escape_htmltag($value).
'" '.($moreparam ? $moreparam :
'').($autofocusoncreate ?
' autofocus' :
'').
'>';
7003 } elseif (preg_match(
'/^text/', $type)) {
7004 if (!preg_match(
'/search_/', $keyprefix)) {
7005 require_once DOL_DOCUMENT_ROOT.
'/core/class/doleditor.class.php';
7006 $doleditor =
new DolEditor($keyprefix.$key.$keysuffix, $value,
'', 200,
'dolibarr_notes',
'In',
false,
false,
false, ROWS_5,
'90%');
7007 $out = $doleditor->Create(1);
7009 $out =
'<input type="text" class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.
dol_escape_htmltag($value).
'" '.($moreparam ? $moreparam :
'').
'>';
7011 } elseif (preg_match(
'/^html/', $type)) {
7012 if (!preg_match(
'/search_/', $keyprefix)) {
7013 require_once DOL_DOCUMENT_ROOT.
'/core/class/doleditor.class.php';
7014 $doleditor =
new DolEditor($keyprefix.$key.$keysuffix, $value,
'', 200,
'dolibarr_notes',
'In',
false,
false, isModEnabled(
'fckeditor') && $conf->global->FCKEDITOR_ENABLE_SOCIETE, ROWS_5,
'90%');
7015 $out = $doleditor->Create(1,
'',
true,
'',
'', $moreparam, $morecss);
7017 $out =
'<input type="text" class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.
dol_escape_htmltag($value).
'" '.($moreparam ? $moreparam :
'').
'>';
7019 } elseif ($type ==
'boolean') {
7021 if (!empty($value)) {
7022 $checked =
' checked value="1" ';
7024 $checked =
' value="1" ';
7026 $out =
'<input type="checkbox" class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" '.$checked.
' '.($moreparam ? $moreparam :
'').
'>';
7027 } elseif ($type ==
'price') {
7028 if (!empty($value)) {
7029 $value =
price($value);
7031 $out =
'<input type="text" class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.$value.
'" '.($moreparam ? $moreparam :
'').
'> '.$langs->getCurrencySymbol($conf->currency);
7032 } elseif (preg_match(
'/^double(\([0-9],[0-9]\)){0,1}/', $type)) {
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 :
'').
'> ';
7037 } elseif ($type ==
'select') {
7039 if (!empty($conf->use_javascript_ajax) && empty($conf->global->MAIN_EXTRAFIELDS_DISABLE_SELECT2)) {
7040 include_once DOL_DOCUMENT_ROOT.
'/core/lib/ajax.lib.php';
7041 $out .=
ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
7044 $out .=
'<select class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" '.($moreparam ? $moreparam :
'').
'>';
7045 if ((!isset($this->fields[$key][
'default'])) || ($this->fields[$key][
'notnull'] != 1)) {
7046 $out .=
'<option value="0"> </option>';
7048 foreach ($param[
'options'] as $keyb => $valb) {
7049 if ((
string) $keyb ==
'') {
7052 if (strpos($valb,
"|") !==
false) {
7053 list($valb, $parent) = explode(
'|', $valb);
7055 $out .=
'<option value="'.$keyb.
'"';
7056 $out .= (((string) $value == (
string) $keyb) ?
' selected' :
'');
7057 $out .= (!empty($parent) ?
' parent="'.$parent.
'"' :
'');
7058 $out .=
'>'.$valb.
'</option>';
7060 $out .=
'</select>';
7061 } elseif ($type ==
'sellist') {
7063 if (!empty($conf->use_javascript_ajax) && empty($conf->global->MAIN_EXTRAFIELDS_DISABLE_SELECT2)) {
7064 include_once DOL_DOCUMENT_ROOT.
'/core/lib/ajax.lib.php';
7065 $out .=
ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
7068 $out .=
'<select class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" '.($moreparam ? $moreparam :
'').
'>';
7069 if (is_array($param[
'options'])) {
7070 $param_list = array_keys($param[
'options']);
7071 $InfoFieldList = explode(
":", $param_list[0]);
7081 $keyList = (empty($InfoFieldList[2]) ?
'rowid' : $InfoFieldList[2].
' as rowid');
7083 if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
7084 if (strpos($InfoFieldList[4],
'extra.') !==
false) {
7085 $keyList =
'main.'.$InfoFieldList[2].
' as rowid';
7087 $keyList = $InfoFieldList[2].
' as rowid';
7090 if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
7091 list($parentName, $parentField) = explode(
'|', $InfoFieldList[3]);
7092 $keyList .=
', '.$parentField;
7095 $filter_categorie =
false;
7096 if (count($InfoFieldList) > 5) {
7097 if ($InfoFieldList[0] ==
'categorie') {
7098 $filter_categorie =
true;
7102 if ($filter_categorie ===
false) {
7103 $fields_label = explode(
'|', $InfoFieldList[1]);
7104 if (is_array($fields_label)) {
7106 $keyList .= implode(
', ', $fields_label);
7110 $sql =
"SELECT " . $keyList;
7111 $sql .=
" FROM " . $this->db->prefix() . $InfoFieldList[0];
7112 if (!empty($InfoFieldList[4])) {
7114 if (strpos($InfoFieldList[4],
'$SEL$') !==
false) {
7115 $InfoFieldList[4] = str_replace(
'$SEL$',
'SELECT', $InfoFieldList[4]);
7119 if (strpos($InfoFieldList[4],
'$ID$') !==
false && !empty($objectid)) {
7120 $InfoFieldList[4] = str_replace(
'$ID$', $objectid, $InfoFieldList[4]);
7122 $InfoFieldList[4] = str_replace(
'$ID$',
'0', $InfoFieldList[4]);
7126 if (strpos($InfoFieldList[4],
'extra') !==
false) {
7127 $sql .=
" as main, " . $this->db->prefix() . $InfoFieldList[0] .
"_extrafields as extra";
7128 $sqlwhere .=
" WHERE extra.fk_object=main." . $InfoFieldList[2] .
" AND " . $InfoFieldList[4];
7130 $sqlwhere .=
" WHERE " . $InfoFieldList[4];
7133 $sqlwhere .=
' WHERE 1=1';
7136 if (in_array($InfoFieldList[0], array(
'tablewithentity'))) {
7137 $sqlwhere .=
" AND entity = " . ((int) $conf->entity);
7142 $sql .=
' ORDER BY ' . implode(
', ', $fields_label);
7144 dol_syslog(get_class($this) .
'::showInputField type=sellist', LOG_DEBUG);
7145 $resql = $this->db->query($sql);
7147 $out .=
'<option value="0"> </option>';
7148 $num = $this->db->num_rows($resql);
7152 $obj = $this->db->fetch_object($resql);
7156 $fields_label = explode(
'|', $InfoFieldList[1]);
7157 if (count($fields_label) > 1) {
7159 foreach ($fields_label as $field_toshow) {
7160 $labeltoshow .= $obj->$field_toshow .
' ';
7163 $labeltoshow = $obj->{$InfoFieldList[1]};
7165 $labeltoshow =
dol_trunc($labeltoshow, 45);
7167 if ($value == $obj->rowid) {
7168 foreach ($fields_label as $field_toshow) {
7169 $translabel = $langs->trans($obj->$field_toshow);
7170 if ($translabel != $obj->$field_toshow) {
7171 $labeltoshow =
dol_trunc($translabel) .
' ';
7173 $labeltoshow =
dol_trunc($obj->$field_toshow) .
' ';
7176 $out .=
'<option value="' . $obj->rowid .
'" selected>' . $labeltoshow .
'</option>';
7179 $translabel = $langs->trans($obj->{$InfoFieldList[1]});
7180 if ($translabel != $obj->{$InfoFieldList[1]}) {
7181 $labeltoshow =
dol_trunc($translabel, 18);
7183 $labeltoshow =
dol_trunc($obj->{$InfoFieldList[1]});
7186 if (empty($labeltoshow)) {
7187 $labeltoshow =
'(not defined)';
7189 if ($value == $obj->rowid) {
7190 $out .=
'<option value="' . $obj->rowid .
'" selected>' . $labeltoshow .
'</option>';
7193 if (!empty($InfoFieldList[3]) && $parentField) {
7194 $parent = $parentName .
':' . $obj->{$parentField};
7198 $out .=
'<option value="' . $obj->rowid .
'"';
7199 $out .= ($value == $obj->rowid ?
' selected' :
'');
7200 $out .= (!empty($parent) ?
' parent="' . $parent .
'"' :
'');
7201 $out .=
'>' . $labeltoshow .
'</option>';
7206 $this->db->free($resql);
7208 print
'Error in request ' . $sql .
' ' . $this->db->lasterror() .
'. Check setup of extra parameters.<br>';
7211 require_once DOL_DOCUMENT_ROOT.
'/categories/class/categorie.class.php';
7212 $data = $form->select_all_categories(Categorie::$MAP_ID_TO_CODE[$InfoFieldList[5]],
'',
'parent', 64, $InfoFieldList[6], 1, 1);
7213 $out .=
'<option value="0"> </option>';
7214 foreach ($data as $data_key => $data_value) {
7215 $out .=
'<option value="' . $data_key .
'"';
7216 $out .= ($value == $data_key ?
' selected' :
'');
7217 $out .=
'>' . $data_value .
'</option>';
7221 $out .=
'</select>';
7222 } elseif ($type ==
'checkbox') {
7223 $value_arr = explode(
',', $value);
7224 $out = $form->multiselectarray($keyprefix.$key.$keysuffix, (empty($param[
'options']) ?
null:$param[
'options']), $value_arr,
'', 0, $morecss, 0,
'100%');
7225 } elseif ($type ==
'radio') {
7227 foreach ($param[
'options'] as $keyopt => $valopt) {
7228 $out .=
'<input class="flat '.$morecss.
'" type="radio" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" '.($moreparam ? $moreparam :
'');
7229 $out .=
' value="'.$keyopt.
'"';
7230 $out .=
' id="'.$keyprefix.$key.$keysuffix.
'_'.$keyopt.
'"';
7231 $out .= ($value == $keyopt ?
'checked' :
'');
7232 $out .=
'/><label for="'.$keyprefix.$key.$keysuffix.
'_'.$keyopt.
'">'.$valopt.
'</label><br>';
7234 } elseif ($type ==
'chkbxlst') {
7235 if (is_array($value)) {
7236 $value_arr = $value;
7238 $value_arr = explode(
',', $value);
7241 if (is_array($param[
'options'])) {
7242 $param_list = array_keys($param[
'options']);
7243 $InfoFieldList = explode(
":", $param_list[0]);
7253 $keyList = (empty($InfoFieldList[2]) ?
'rowid' : $InfoFieldList[2].
' as rowid');
7255 if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
7256 list ($parentName, $parentField) = explode(
'|', $InfoFieldList[3]);
7257 $keyList .=
', '.$parentField;
7259 if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
7260 if (strpos($InfoFieldList[4],
'extra.') !==
false) {
7261 $keyList =
'main.'.$InfoFieldList[2].
' as rowid';
7263 $keyList = $InfoFieldList[2].
' as rowid';
7267 $filter_categorie =
false;
7268 if (count($InfoFieldList) > 5) {
7269 if ($InfoFieldList[0] ==
'categorie') {
7270 $filter_categorie =
true;
7274 if ($filter_categorie ===
false) {
7275 $fields_label = explode(
'|', $InfoFieldList[1]);
7276 if (is_array($fields_label)) {
7278 $keyList .= implode(
', ', $fields_label);
7282 $sql =
"SELECT " . $keyList;
7283 $sql .=
' FROM ' . $this->db->prefix() . $InfoFieldList[0];
7284 if (!empty($InfoFieldList[4])) {
7286 if (strpos($InfoFieldList[4],
'$SEL$') !==
false) {
7287 $InfoFieldList[4] = str_replace(
'$SEL$',
'SELECT', $InfoFieldList[4]);
7291 if (strpos($InfoFieldList[4],
'$ID$') !==
false && !empty($objectid)) {
7292 $InfoFieldList[4] = str_replace(
'$ID$', $objectid, $InfoFieldList[4]);
7294 $InfoFieldList[4] = str_replace(
'$ID$',
'0', $InfoFieldList[4]);
7298 if (strpos($InfoFieldList[4],
'extra') !==
false) {
7299 $sql .=
' as main, ' . $this->db->prefix() . $InfoFieldList[0] .
'_extrafields as extra';
7300 $sqlwhere .=
" WHERE extra.fk_object=main." . $InfoFieldList[2] .
" AND " . $InfoFieldList[4];
7302 $sqlwhere .=
" WHERE " . $InfoFieldList[4];
7305 $sqlwhere .=
' WHERE 1=1';
7308 if (in_array($InfoFieldList[0], array(
'tablewithentity'))) {
7309 $sqlwhere .=
" AND entity = " . ((int) $conf->entity);
7315 dol_syslog(get_class($this) .
'::showInputField type=chkbxlst', LOG_DEBUG);
7316 $resql = $this->db->query($sql);
7318 $num = $this->db->num_rows($resql);
7325 $obj = $this->db->fetch_object($resql);
7329 $fields_label = explode(
'|', $InfoFieldList[1]);
7330 if (count($fields_label) > 1) {
7332 foreach ($fields_label as $field_toshow) {
7333 $labeltoshow .= $obj->$field_toshow .
' ';
7336 $labeltoshow = $obj->{$InfoFieldList[1]};
7338 $labeltoshow =
dol_trunc($labeltoshow, 45);
7340 if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
7341 foreach ($fields_label as $field_toshow) {
7342 $translabel = $langs->trans($obj->$field_toshow);
7343 if ($translabel != $obj->$field_toshow) {
7344 $labeltoshow =
dol_trunc($translabel, 18) .
' ';
7346 $labeltoshow =
dol_trunc($obj->$field_toshow, 18) .
' ';
7350 $data[$obj->rowid] = $labeltoshow;
7353 $translabel = $langs->trans($obj->{$InfoFieldList[1]});
7354 if ($translabel != $obj->{$InfoFieldList[1]}) {
7355 $labeltoshow =
dol_trunc($translabel, 18);
7357 $labeltoshow =
dol_trunc($obj->{$InfoFieldList[1]}, 18);
7360 if (empty($labeltoshow)) {
7361 $labeltoshow =
'(not defined)';
7364 if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
7365 $data[$obj->rowid] = $labeltoshow;
7368 if (!empty($InfoFieldList[3]) && $parentField) {
7369 $parent = $parentName .
':' . $obj->{$parentField};
7373 $data[$obj->rowid] = $labeltoshow;
7378 $this->db->free($resql);
7380 $out = $form->multiselectarray($keyprefix . $key . $keysuffix, $data, $value_arr,
'', 0, $morecss, 0,
'100%');
7382 print
'Error in request ' . $sql .
' ' . $this->db->lasterror() .
'. Check setup of extra parameters.<br>';
7385 require_once DOL_DOCUMENT_ROOT.
'/categories/class/categorie.class.php';
7386 $data = $form->select_all_categories(Categorie::$MAP_ID_TO_CODE[$InfoFieldList[5]],
'',
'parent', 64, $InfoFieldList[6], 1, 1);
7387 $out = $form->multiselectarray($keyprefix . $key . $keysuffix, $data, $value_arr,
'', 0, $morecss, 0,
'100%');
7390 } elseif ($type ==
'link') {
7391 $param_list = array_keys($param[
'options']);
7392 $param_list_array = explode(
':', $param_list[0]);
7393 $showempty = (($required && $default !=
'') ? 0 : 1);
7395 if (!preg_match(
'/search_/', $keyprefix)) {
7396 if (!empty($param_list_array[2])) {
7397 if (!empty($this->fields[$key][
'picto'])) {
7398 $morecss .=
' widthcentpercentminusxx';
7400 $morecss .=
' widthcentpercentminusx';
7403 if (!empty($this->fields[$key][
'picto'])) {
7404 $morecss .=
' widthcentpercentminusx';
7409 $out = $form->selectForForms($param_list[0], $keyprefix.$key.$keysuffix, $value, $showempty,
'',
'', $morecss, $moreparam, 0, empty($val[
'disabled']) ? 0 : 1);
7411 if (!empty($param_list_array[2])) {
7412 if ((!GETPOSTISSET(
'backtopage') || strpos(
GETPOST(
'backtopage'), $_SERVER[
'PHP_SELF']) === 0)
7413 && empty($val[
'disabled']) && empty($nonewbutton)) {
7414 list($class, $classfile) = explode(
':', $param_list[0]);
7415 if (file_exists(
dol_buildpath(dirname(dirname($classfile)).
'/card.php'))) {
7416 $url_path =
dol_buildpath(dirname(dirname($classfile)).
'/card.php', 1);
7418 $url_path =
dol_buildpath(dirname(dirname($classfile)).
'/'.strtolower($class).
'_card.php', 1);
7420 $paramforthenewlink =
'';
7421 $paramforthenewlink .= (GETPOSTISSET(
'action') ?
'&action='.GETPOST(
'action',
'aZ09') :
'');
7422 $paramforthenewlink .= (GETPOSTISSET(
'id') ?
'&id='.GETPOST(
'id',
'int') :
'');
7423 $paramforthenewlink .= (GETPOSTISSET(
'origin') ?
'&origin='.GETPOST(
'origin',
'aZ09') :
'');
7424 $paramforthenewlink .= (GETPOSTISSET(
'originid') ?
'&originid='.GETPOST(
'originid',
'int') :
'');
7425 $paramforthenewlink .=
'&fk_'.strtolower($class).
'=--IDFORBACKTOPAGE--';
7427 $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>';
7430 } elseif ($type ==
'password') {
7432 $out =
'<input type="'.($keyprefix ==
'search_' ?
'text' :
'password').
'" class="flat '.$morecss.
'" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.$value.
'" '.($moreparam ? $moreparam :
'').
'>';
7433 } elseif ($type ==
'array') {
7435 $newval[
'type'] =
'varchar(256)';
7438 if (!empty($value)) {
7439 foreach ($value as $option) {
7440 $out .=
'<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).
'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
7441 $out .= $this->showInputField($newval, $keyprefix.$key.$keysuffix.
'[]', $option, $moreparam,
'',
'', $morecss).
'<br></span>';
7444 $out .=
'<a id="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).
'_add" href="javascript:;"><span class="fa fa-plus-circle valignmiddle"></span></a>';
7446 $newInput =
'<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).
'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
7447 $newInput .= $this->showInputField($newval, $keyprefix.$key.$keysuffix.
'[]',
'', $moreparam,
'',
'', $morecss).
'<br></span>';
7449 if (!empty($conf->use_javascript_ajax)) {
7451 <script nonce="'.getNonce().
'">
7452 $(document).ready(function() {
7453 $("a#'.
dol_escape_js($keyprefix.$key.$keysuffix).
'_add").click(function() {
7457 $(document).on("click", "a.'.
dol_escape_js($keyprefix.$key.$keysuffix).
'_del", function() {
7458 $(this).parent().remove();
7464 if (!empty($hidden)) {
7465 $out =
'<input type="hidden" value="'.$value.
'" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'"/>';
7468 if ($isDependList==1) {
7469 $out .= $this->getJSListDependancies(
'_common');
7477 if (!empty($fieldValidationErrorMsg) && function_exists(
'getFieldErrorIcon')) {
7478 $out .=
' '.getFieldErrorIcon($fieldValidationErrorMsg);
7497 public function showOutputField($val, $key, $value, $moreparam =
'', $keysuffix =
'', $keyprefix =
'', $morecss =
'')
7499 global $conf, $langs, $form;
7501 if (!is_object($form)) {
7502 require_once DOL_DOCUMENT_ROOT.
'/core/class/html.form.class.php';
7503 $form =
new Form($this->db);
7506 $label = empty($val[
'label']) ?
'' : $val[
'label'];
7507 $type = empty($val[
'type']) ?
'' : $val[
'type'];
7508 $size = empty($val[
'css']) ?
'' : $val[
'css'];
7512 if (preg_match(
'/varchar\((\d+)\)/', $type, $reg)) {
7515 } elseif (preg_match(
'/varchar/', $type)) {
7518 if (!empty($val[
'arrayofkeyval']) && is_array($val[
'arrayofkeyval'])) {
7521 if (preg_match(
'/^integer:(.*):(.*)/i', $val[
'type'], $reg)) {
7525 $default = empty($val[
'default']) ?
'' : $val[
'default'];
7526 $computed = empty($val[
'computed']) ?
'' : $val[
'computed'];
7527 $unique = empty($val[
'unique']) ?
'' : $val[
'unique'];
7528 $required = empty($val[
'required']) ?
'' : $val[
'required'];
7530 $param[
'options'] = array();
7532 if (!empty($val[
'arrayofkeyval']) && is_array($val[
'arrayofkeyval'])) {
7533 $param[
'options'] = $val[
'arrayofkeyval'];
7535 if (preg_match(
'/^integer:(.*):(.*)/i', $val[
'type'], $reg)) {
7537 $stringforoptions = $reg[1].
':'.$reg[2];
7538 if ($reg[1] ==
'User') {
7539 $stringforoptions .=
':-1';
7541 $param[
'options'] = array($stringforoptions => $stringforoptions);
7542 } elseif (preg_match(
'/^sellist:(.*):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
7543 $param[
'options'] = array($reg[1].
':'.$reg[2].
':'.$reg[3].
':'.$reg[4] =>
'N');
7545 } elseif (preg_match(
'/^sellist:(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
7546 $param[
'options'] = array($reg[1].
':'.$reg[2].
':'.$reg[3] =>
'N');
7548 } elseif (preg_match(
'/^sellist:(.*):(.*)/i', $val[
'type'], $reg)) {
7549 $param[
'options'] = array($reg[1].
':'.$reg[2] =>
'N');
7551 } elseif (preg_match(
'/^chkbxlst:(.*)/i', $val[
'type'], $reg)) {
7552 $param[
'options'] = array($reg[1] =>
'N');
7556 $langfile = empty($val[
'langfile']) ?
'' : $val[
'langfile'];
7557 $list = (empty($val[
'list']) ?
'' : $val[
'list']);
7558 $help = (empty($val[
'help']) ?
'' : $val[
'help']);
7559 $hidden = (($val[
'visible'] == 0) ? 1 : 0);
7569 $value =
dol_eval($computed, 1, 0,
'');
7572 if (empty($morecss)) {
7573 if ($type ==
'date') {
7574 $morecss =
'minwidth100imp';
7575 } elseif ($type ==
'datetime' || $type ==
'timestamp') {
7576 $morecss =
'minwidth200imp';
7577 } elseif (in_array($type, array(
'int',
'double',
'price'))) {
7578 $morecss =
'maxwidth75';
7579 } elseif ($type ==
'url') {
7580 $morecss =
'minwidth400';
7581 } elseif ($type ==
'boolean') {
7584 if (is_numeric($size) && round($size) < 12) {
7585 $morecss =
'minwidth100';
7586 } elseif (is_numeric($size) && round($size) <= 48) {
7587 $morecss =
'minwidth200';
7589 $morecss =
'minwidth400';
7595 if (in_array($key, array(
'rowid',
'ref')) && method_exists($this,
'getNomUrl')) {
7596 if ($key !=
'rowid' || empty($this->fields[
'ref'])) {
7597 $value = $this->getNomUrl(1,
'', 0,
'', 1);
7599 } elseif ($key ==
'status' && method_exists($this,
'getLibStatut')) {
7600 $value = $this->getLibStatut(3);
7601 } elseif ($type ==
'date') {
7602 if (!empty($value)) {
7607 } elseif ($type ==
'datetime' || $type ==
'timestamp') {
7608 if (!empty($value)) {
7613 } elseif ($type ==
'duration') {
7614 include_once DOL_DOCUMENT_ROOT.
'/core/lib/date.lib.php';
7615 if (!is_null($value) && $value !==
'') {
7618 } elseif ($type ==
'double' || $type ==
'real') {
7619 if (!is_null($value) && $value !==
'') {
7620 $value =
price($value);
7622 } elseif ($type ==
'boolean') {
7624 if (!empty($value)) {
7625 $checked =
' checked ';
7627 $value =
'<input type="checkbox" '.$checked.
' '.($moreparam ? $moreparam :
'').
' readonly disabled>';
7628 } elseif ($type ==
'mail' || $type ==
'email') {
7630 } elseif ($type ==
'url') {
7632 } elseif ($type ==
'phone') {
7634 } elseif ($type ==
'ip') {
7636 } elseif ($type ==
'price') {
7637 if (!is_null($value) && $value !==
'') {
7638 $value =
price($value, 0, $langs, 0, 0, -1, $conf->currency);
7640 } elseif ($type ==
'select') {
7641 $value = isset($param[
'options'][$value])?$param[
'options'][$value]:
'';
7642 } elseif ($type ==
'sellist') {
7643 $param_list = array_keys($param[
'options']);
7644 $InfoFieldList = explode(
":", $param_list[0]);
7646 $selectkey =
"rowid";
7649 if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
7650 $selectkey = $InfoFieldList[2];
7651 $keyList = $InfoFieldList[2].
' as rowid';
7654 $fields_label = explode(
'|', $InfoFieldList[1]);
7655 if (is_array($fields_label)) {
7657 $keyList .= implode(
', ', $fields_label);
7660 $filter_categorie =
false;
7661 if (count($InfoFieldList) > 5) {
7662 if ($InfoFieldList[0] ==
'categorie') {
7663 $filter_categorie =
true;
7667 $sql =
"SELECT ".$keyList;
7668 $sql .=
' FROM '.$this->db->prefix().$InfoFieldList[0];
7669 if (strpos($InfoFieldList[4],
'extra') !==
false) {
7672 if ($selectkey ==
'rowid' && empty($value)) {
7673 $sql .=
" WHERE ".$selectkey.
" = 0";
7674 } elseif ($selectkey ==
'rowid') {
7675 $sql .=
" WHERE ".$selectkey.
" = ".((int) $value);
7677 $sql .=
" WHERE ".$selectkey.
" = '".$this->db->escape($value).
"'";
7682 dol_syslog(get_class($this).
':showOutputField:$type=sellist', LOG_DEBUG);
7683 $resql = $this->db->query($sql);
7685 if ($filter_categorie ===
false) {
7687 $numrows = $this->db->num_rows($resql);
7689 $obj = $this->db->fetch_object($resql);
7692 $fields_label = explode(
'|', $InfoFieldList[1]);
7694 if (is_array($fields_label) && count($fields_label) > 1) {
7695 foreach ($fields_label as $field_toshow) {
7697 if (!empty($obj->$field_toshow)) {
7698 $translabel = $langs->trans($obj->$field_toshow);
7700 if ($translabel != $field_toshow) {
7701 $value .=
dol_trunc($translabel, 18) .
' ';
7703 $value .= $obj->$field_toshow .
' ';
7708 if (!empty($obj->{$InfoFieldList[1]})) {
7709 $translabel = $langs->trans($obj->{$InfoFieldList[1]});
7711 if ($translabel != $obj->{$InfoFieldList[1]}) {
7714 $value = $obj->{$InfoFieldList[1]};
7719 require_once DOL_DOCUMENT_ROOT .
'/categories/class/categorie.class.php';
7722 $obj = $this->db->fetch_object($resql);
7724 $c->fetch($obj->rowid);
7725 $ways = $c->print_all_ways();
7726 foreach ($ways as $way) {
7727 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories"' . ($c->color ?
' style="background: #' . $c->color .
';"' :
' style="background: #aaa"') .
'>' .
img_object(
'',
'category') .
' ' . $way .
'</li>';
7729 $value =
'<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(
' ', $toprint).
'</ul></div>';
7732 dol_syslog(get_class($this).
'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
7734 } elseif ($type ==
'radio') {
7735 $value = $param[
'options'][$value];
7736 } elseif ($type ==
'checkbox') {
7737 $value_arr = explode(
',', $value);
7739 if (is_array($value_arr) && count($value_arr) > 0) {
7741 foreach ($value_arr as $keyval => $valueval) {
7742 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">'.$param[
'options'][$valueval].
'</li>';
7744 $value =
'<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(
' ', $toprint).
'</ul></div>';
7746 } elseif ($type ==
'chkbxlst') {
7747 $value_arr = explode(
',', $value);
7749 $param_list = array_keys($param[
'options']);
7750 $InfoFieldList = explode(
":", $param_list[0]);
7752 $selectkey =
"rowid";
7755 if (count($InfoFieldList) >= 3) {
7756 $selectkey = $InfoFieldList[2];
7757 $keyList = $InfoFieldList[2].
' as rowid';
7760 $fields_label = explode(
'|', $InfoFieldList[1]);
7761 if (is_array($fields_label)) {
7763 $keyList .= implode(
', ', $fields_label);
7766 $filter_categorie =
false;
7767 if (count($InfoFieldList) > 5) {
7768 if ($InfoFieldList[0] ==
'categorie') {
7769 $filter_categorie =
true;
7773 $sql =
"SELECT ".$keyList;
7774 $sql .=
' FROM '.$this->db->prefix().$InfoFieldList[0];
7775 if (strpos($InfoFieldList[4],
'extra') !==
false) {
7781 dol_syslog(get_class($this).
':showOutputField:$type=chkbxlst', LOG_DEBUG);
7782 $resql = $this->db->query($sql);
7784 if ($filter_categorie ===
false) {
7787 while ($obj = $this->db->fetch_object($resql)) {
7789 $fields_label = explode(
'|', $InfoFieldList[1]);
7790 if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
7791 if (is_array($fields_label) && count($fields_label) > 1) {
7792 foreach ($fields_label as $field_toshow) {
7794 if (!empty($obj->$field_toshow)) {
7795 $translabel = $langs->trans($obj->$field_toshow);
7797 if ($translabel != $field_toshow) {
7798 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' .
dol_trunc($translabel, 18) .
'</li>';
7800 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' . $obj->$field_toshow .
'</li>';
7805 if (!empty($obj->{$InfoFieldList[1]})) {
7806 $translabel = $langs->trans($obj->{$InfoFieldList[1]});
7808 if ($translabel != $obj->{$InfoFieldList[1]}) {
7809 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' .
dol_trunc($translabel, 18) .
'</li>';
7811 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' . $obj->{$InfoFieldList[1]} .
'</li>';
7817 require_once DOL_DOCUMENT_ROOT .
'/categories/class/categorie.class.php';
7820 while ($obj = $this->db->fetch_object($resql)) {
7821 if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
7823 $c->fetch($obj->rowid);
7824 $ways = $c->print_all_ways();
7825 foreach ($ways as $way) {
7826 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories"' . ($c->color ?
' style="background: #' . $c->color .
';"' :
' style="background: #aaa"') .
'>' .
img_object(
'',
'category') .
' ' . $way .
'</li>';
7831 $value =
'<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(
' ', $toprint).
'</ul></div>';
7833 dol_syslog(get_class($this).
'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
7835 } elseif ($type ==
'link') {
7840 $param_list = array_keys($param[
'options']);
7842 $InfoFieldList = explode(
":", $param_list[0]);
7843 $classname = $InfoFieldList[0];
7844 $classpath = $InfoFieldList[1];
7845 $getnomurlparam = (empty($InfoFieldList[2]) ? 3 : $InfoFieldList[2]);
7846 $getnomurlparam2 = (empty($InfoFieldList[4]) ?
'' : $InfoFieldList[4]);
7847 if (!empty($classpath)) {
7849 if ($classname && class_exists($classname)) {
7850 $object =
new $classname($this->db);
7851 if ($object->element ===
'product') {
7852 $result = $object->fetch($value,
'',
'',
'', 0, 1, 1);
7854 $result = $object->fetch($value);
7857 if ($object->element ===
'product') {
7858 $get_name_url_param_arr = array($getnomurlparam, $getnomurlparam2, 0, -1, 0,
'', 0);
7859 if (isset($val[
'get_name_url_params'])) {
7860 $get_name_url_params = explode(
':', $val[
'get_name_url_params']);
7861 if (!empty($get_name_url_params)) {
7862 $param_num_max = count($get_name_url_param_arr) - 1;
7863 foreach ($get_name_url_params as $param_num => $param_value) {
7864 if ($param_num > $param_num_max) {
7867 $get_name_url_param_arr[$param_num] = $param_value;
7875 $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]);
7877 $value = $object->getNomUrl($getnomurlparam, $getnomurlparam2);
7884 dol_syslog(
'Error bad setup of extrafield', LOG_WARNING);
7885 return 'Error bad setup of extrafield';
7890 } elseif ($type ==
'password') {
7891 $value = preg_replace(
'/./i',
'*', $value);
7892 } elseif ($type ==
'array') {
7893 $value = implode(
'<br>', $value);
7913 unset($this->validateFieldsErrors[$fieldKey]);
7927 $msg = $langs->trans(
"UnknowError");
7930 $this->error = $this->validateFieldsErrors[$fieldKey] = $msg;
7941 if (!empty($this->validateFieldsErrors[$fieldKey])) {
7942 return $this->validateFieldsErrors[$fieldKey];
7959 if (!class_exists(
'Validate')) {
7960 require_once DOL_DOCUMENT_ROOT .
'/core/class/validate.class.php';
7963 $this->clearFieldError($fieldKey);
7965 if (!isset($fields[$fieldKey])) {
7966 $this->setFieldError($fieldKey, $langs->trans(
'FieldNotFoundInObject'));
7970 $val = $fields[$fieldKey];
7973 $param[
'options'] = array();
7974 $type = $val[
'type'];
7977 if (isset($val[
'notnull']) && $val[
'notnull'] === 1) {
7991 if (preg_match(
'/varchar\((\d+)\)/', $type, $reg)) {
7994 } elseif (preg_match(
'/varchar/', $type)) {
7998 if (!empty($val[
'arrayofkeyval']) && is_array($val[
'arrayofkeyval'])) {
8002 if (!empty($val[
'type']) && preg_match(
'/^integer:(.*):(.*)/i', $val[
'type'], $reg)) {
8006 if (!empty($val[
'arrayofkeyval']) && is_array($val[
'arrayofkeyval'])) {
8007 $param[
'options'] = $val[
'arrayofkeyval'];
8010 if (preg_match(
'/^integer:(.*):(.*)/i', $val[
'type'], $reg)) {
8012 $param[
'options'] = array($reg[1].
':'.$reg[2]=>$reg[1].
':'.$reg[2]);
8013 } elseif (preg_match(
'/^sellist:(.*):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
8014 $param[
'options'] = array($reg[1].
':'.$reg[2].
':'.$reg[3].
':'.$reg[4] =>
'N');
8016 } elseif (preg_match(
'/^sellist:(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
8017 $param[
'options'] = array($reg[1].
':'.$reg[2].
':'.$reg[3] =>
'N');
8019 } elseif (preg_match(
'/^sellist:(.*):(.*)/i', $val[
'type'], $reg)) {
8020 $param[
'options'] = array($reg[1].
':'.$reg[2] =>
'N');
8029 $validate =
new Validate($this->db, $langs);
8039 if ($required && !$validate->isNotEmptyString($fieldValue)) {
8040 $this->setFieldError($fieldKey, $validate->error);
8042 } elseif (!$required && !$validate->isNotEmptyString($fieldValue)) {
8048 if (!empty($maxSize) && !$validate->isMaxLength($fieldValue, $maxSize)) {
8049 $this->setFieldError($fieldKey, $validate->error);
8054 if (!empty($minSize) && !$validate->isMinLength($fieldValue, $minSize)) {
8055 $this->setFieldError($fieldKey, $validate->error);
8063 if (in_array($type, array(
'date',
'datetime',
'timestamp'))) {
8064 if (!$validate->isTimestamp($fieldValue)) {
8065 $this->setFieldError($fieldKey, $validate->error);
8067 }
else {
return true; }
8068 } elseif ($type ==
'duration') {
8069 if (!$validate->isDuration($fieldValue)) {
8070 $this->setFieldError($fieldKey, $validate->error);
8072 }
else {
return true; }
8073 } elseif (in_array($type, array(
'double',
'real',
'price'))) {
8075 if (!$validate->isNumeric($fieldValue)) {
8076 $this->setFieldError($fieldKey, $validate->error);
8078 }
else {
return true; }
8079 } elseif ($type ==
'boolean') {
8080 if (!$validate->isBool($fieldValue)) {
8081 $this->setFieldError($fieldKey, $validate->error);
8083 }
else {
return true; }
8084 } elseif ($type ==
'mail') {
8085 if (!$validate->isEmail($fieldValue)) {
8086 $this->setFieldError($fieldKey, $validate->error);
8089 } elseif ($type ==
'url') {
8090 if (!$validate->isUrl($fieldValue)) {
8091 $this->setFieldError($fieldKey, $validate->error);
8093 }
else {
return true; }
8094 } elseif ($type ==
'phone') {
8095 if (!$validate->isPhone($fieldValue)) {
8096 $this->setFieldError($fieldKey, $validate->error);
8098 }
else {
return true; }
8099 } elseif ($type ==
'select' || $type ==
'radio') {
8100 if (!isset($param[
'options'][$fieldValue])) {
8101 $this->error = $langs->trans(
'RequireValidValue');
8103 }
else {
return true; }
8104 } elseif ($type ==
'sellist' || $type ==
'chkbxlst') {
8105 $param_list = array_keys($param[
'options']);
8106 $InfoFieldList = explode(
":", $param_list[0]);
8107 $value_arr = explode(
',', $fieldValue);
8108 $value_arr = array_map(array($this->db,
'escape'), $value_arr);
8110 $selectkey =
"rowid";
8111 if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
8112 $selectkey = $InfoFieldList[2];
8115 if (!$validate->isInDb($value_arr, $InfoFieldList[0], $selectkey)) {
8116 $this->setFieldError($fieldKey, $validate->error);
8118 }
else {
return true; }
8119 } elseif ($type ==
'link') {
8120 $param_list = array_keys($param[
'options']);
8121 $InfoFieldList = explode(
":", $param_list[0]);
8122 $classname = $InfoFieldList[0];
8123 $classpath = $InfoFieldList[1];
8124 if (!$validate->isFetchable($fieldValue, $classname, $classpath)) {
8125 $this->setFieldError($fieldKey, $validate->error);
8127 }
else {
return true; }
8147 public function showOptionals($extrafields, $mode =
'view', $params =
null, $keysuffix =
'', $keyprefix =
'', $onetrtd = 0, $display_type =
'card')
8149 global $db, $conf, $langs, $action, $form, $hookmanager;
8151 if (!is_object($form)) {
8152 $form =
new Form($db);
8154 if (!is_object($extrafields)) {
8155 dol_syslog(
'Bad parameter extrafields for showOptionals', LOG_ERR);
8156 return 'Bad parameter extrafields for showOptionals';
8158 if (!is_array($extrafields->attributes[$this->table_element])) {
8159 dol_syslog(
"extrafields->attributes was not loaded with extrafields->fetch_name_optionals_label(table_element);", LOG_WARNING);
8164 $parameters = array(
'mode'=>$mode,
'params'=>$params,
'keysuffix'=>$keysuffix,
'keyprefix'=>$keyprefix,
'display_type'=>$display_type);
8165 $reshook = $hookmanager->executeHooks(
'showOptionals', $parameters, $this, $action);
8167 if (empty($reshook)) {
8168 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) {
8170 $out .=
'<!-- commonobject:showOptionals --> ';
8173 $nbofextrafieldsshown = 0;
8176 $lastseparatorkeyfound =
'';
8177 $extrafields_collapse_num =
'';
8178 $extrafields_collapse_num_old =
'';
8181 foreach ($extrafields->attributes[$this->table_element][
'label'] as $key => $label) {
8185 if (is_array($params) && array_key_exists(
'onlykey', $params) && $key != $params[
'onlykey']) {
8191 if ($enabled && isset($extrafields->attributes[$this->table_element][
'enabled'][$key])) {
8192 $enabled =
dol_eval($extrafields->attributes[$this->table_element][
'enabled'][$key], 1, 1,
'2');
8194 if (empty($enabled)) {
8199 if ($visibility && isset($extrafields->attributes[$this->table_element][
'list'][$key])) {
8200 $visibility =
dol_eval($extrafields->attributes[$this->table_element][
'list'][$key], 1, 1,
'2');
8204 if ($perms && isset($extrafields->attributes[$this->table_element][
'perms'][$key])) {
8205 $perms =
dol_eval($extrafields->attributes[$this->table_element][
'perms'][$key], 1, 1,
'2');
8208 if (($mode ==
'create') && abs($visibility) != 1 && abs($visibility) != 3) {
8210 } elseif (($mode ==
'edit') && abs($visibility) != 1 && abs($visibility) != 3 && abs($visibility) != 4) {
8212 } elseif ($mode ==
'view' && empty($visibility)) {
8215 if (empty($perms)) {
8220 if (!empty($extrafields->attributes[$this->table_element][
'langfile'][$key])) {
8221 $langs->load($extrafields->attributes[$this->table_element][
'langfile'][$key]);
8225 if (is_array($params) && count($params) > 0 && $display_type==
'card') {
8226 if (array_key_exists(
'cols', $params)) {
8227 $colspan = $params[
'cols'];
8228 } elseif (array_key_exists(
'colspan', $params)) {
8230 if (preg_match(
'/colspan="(\d+)"/', $params[
'colspan'], $reg)) {
8233 $colspan = $params[
'colspan'];
8237 $colspan = intval($colspan);
8241 $value = ((!empty($this->array_options) && array_key_exists(
"options_".$key.$keysuffix, $this->array_options)) ? $this->array_options[
"options_".$key.$keysuffix] :
null);
8247 $check =
'alphanohtml';
8248 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'html',
'text'))) {
8249 $check =
'restricthtml';
8251 $getposttemp =
GETPOST($keyprefix.
'options_'.$key.$keysuffix, $check, 3);
8253 if (is_array($getposttemp) || $getposttemp !=
'' || GETPOSTISSET($keyprefix.
'options_'.$key.$keysuffix)) {
8254 if (is_array($getposttemp)) {
8256 $value = implode(
",", $getposttemp);
8258 $value = $getposttemp;
8261 $value = (!empty($this->array_options[
"options_".$key]) ? $this->array_options[
"options_".$key] :
'');
8267 $nbofextrafieldsshown++;
8270 if ($extrafields->attributes[$this->table_element][
'type'][$key] ==
'separate') {
8271 $extrafields_collapse_num = $key;
8289 $out .= $extrafields->showSeparator($key, $this, ($colspan ? $colspan + 1 : 2), $display_type, $mode);
8291 $lastseparatorkeyfound = $key;
8293 $collapse_group = $extrafields_collapse_num.(!empty($this->
id) ?
'_'.$this->id :
'');
8295 $class = (!empty($extrafields->attributes[$this->table_element][
'hidden'][$key]) ?
'hideobject ' :
'');
8297 if (is_array($params) && count($params) > 0) {
8298 if (array_key_exists(
'class', $params)) {
8299 $class .= $params[
'class'].
' ';
8301 if (array_key_exists(
'style', $params)) {
8302 $csstyle = $params[
'style'];
8307 $domData =
' data-element="extrafield"';
8308 $domData .=
' data-targetelement="'.$this->element.
'"';
8309 $domData .=
' data-targetid="'.$this->id.
'"';
8311 $html_id = (empty($this->
id) ?
'' :
'extrarow-'.$this->element.
'_'.$key.
'_'.$this->id);
8312 if ($display_type==
'card') {
8313 if (!empty($conf->global->MAIN_EXTRAFIELDS_USE_TWO_COLUMS) && ($e % 2) == 0) {
8317 if ($action ==
'selectlines') {
8323 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'date'))) {
8324 $datenotinstring =
null;
8325 if (array_key_exists(
'options_'.$key, $this->array_options)) {
8326 $datenotinstring = $this->array_options[
'options_'.$key];
8327 if (!is_numeric($this->array_options[
'options_'.$key])) {
8328 $datenotinstring = $this->db->jdate($datenotinstring);
8331 $datekey = $keyprefix.
'options_'.$key.$keysuffix;
8332 $value = (GETPOSTISSET($datekey)) ?
dol_mktime(12, 0, 0,
GETPOST($datekey.
'month',
'int', 3),
GETPOST($datekey.
'day',
'int', 3),
GETPOST($datekey.
'year',
'int', 3)) : $datenotinstring;
8334 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'datetime'))) {
8335 $datenotinstring =
null;
8336 if (array_key_exists(
'options_'.$key, $this->array_options)) {
8337 $datenotinstring = $this->array_options[
'options_'.$key];
8338 if (!is_numeric($this->array_options[
'options_'.$key])) {
8339 $datenotinstring = $this->db->jdate($datenotinstring);
8342 $timekey = $keyprefix.
'options_'.$key.$keysuffix;
8343 $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;
8346 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'price',
'double'))) {
8347 if (GETPOSTISSET($keyprefix.
'options_'.$key.$keysuffix) || $value) {
8349 } elseif (isset($this->array_options[
'options_'.$key])) {
8350 $value = $this->array_options[
'options_'.$key];
8355 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'html',
'text',
'varchar',
'select',
'radio',
'int',
'boolean'))) {
8356 if ($action ==
'create') {
8357 $value = (GETPOSTISSET($keyprefix.
'options_'.$key.$keysuffix) || $value) ? $value : $extrafields->attributes[$this->table_element][
'default'][$key];
8361 $labeltoshow = $langs->trans($label);
8362 $helptoshow = $langs->trans($extrafields->attributes[$this->table_element][
'help'][$key]);
8364 if ($display_type ==
'card') {
8365 $out .=
'<tr '.($html_id ?
'id="'.$html_id.
'" ' :
'').$csstyle.
' class="field_options_'.$key.
' '.$class.$this->element.
'_extras_'.$key.
' trextrafields_collapse'.$collapse_group.
'" '.$domData.
' >';
8366 if (!empty($conf->global->MAIN_VIEW_LINE_NUMBER) && ($action ==
'view' || $action ==
'valid' || $action ==
'editline' || $action ==
'confirm_valid' || $action ==
'confirm_cancel')) {
8367 $out .=
'<td></td>';
8369 $out .=
'<td class="'.(empty($params[
'tdclass']) ?
'titlefieldcreate' : $params[
'tdclass']).
' wordbreak';
8370 } elseif ($display_type ==
'line') {
8371 $out .=
'<div '.($html_id ?
'id="'.$html_id.
'" ' :
'').$csstyle.
' class="fieldline_options_'.$key.
' '.$class.$this->element.
'_extras_'.$key.
' trextrafields_collapse'.$collapse_group.
'" '.$domData.
' >';
8372 $out .=
'<div style="display: inline-block; padding-right:4px" class="wordbreak';
8377 $tpl_context = isset($params[
"tpl_context"]) ? $params[
"tpl_context"] :
"none";
8378 if ($tpl_context !=
"public") {
8379 if ($mode !=
'view' && !empty($extrafields->attributes[$this->table_element][
'required'][$key])) {
8380 $out .=
' fieldrequired';
8384 if ($tpl_context ==
"public") {
8385 if (!empty($extrafields->attributes[$this->table_element][
'help'][$key])) {
8386 $out .= $form->textwithpicto($labeltoshow, $helptoshow);
8388 $out .= $labeltoshow;
8390 if ($mode !=
'view' && !empty($extrafields->attributes[$this->table_element][
'required'][$key])) {
8391 $out .=
' <span style="color: red">*</span>';
8394 if (!empty($extrafields->attributes[$this->table_element][
'help'][$key])) {
8395 $out .= $form->textwithpicto($labeltoshow, $helptoshow);
8397 $out .= $labeltoshow;
8401 $out .= ($display_type ==
'card' ?
'</td>' :
'</div>');
8403 $html_id = !empty($this->
id) ? $this->element.
'_extras_'.$key.
'_'.$this->id :
'';
8404 if ($display_type ==
'card') {
8406 $out .=
'<td '.($html_id ?
'id="'.$html_id.
'" ' :
'').
' class="valuefieldcreate '.$this->element.
'_extras_'.$key.
'" '.($colspan ?
' colspan="'.$colspan.
'"' :
'').
'>';
8407 } elseif ($display_type ==
'line') {
8408 $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].
'">';
8413 $out .= $extrafields->showOutputField($key, $value,
'', $this->table_element);
8416 $out .= $extrafields->showInputField($key, $value,
'', $keysuffix,
'', 0, $this->
id, $this->table_element);
8419 $out .= $extrafields->showInputField($key, $value,
'', $keysuffix,
'', 0, $this->
id, $this->table_element);
8423 $out .= ($display_type==
'card' ?
'</td>' :
'</div>');
8425 if (!empty($conf->global->MAIN_EXTRAFIELDS_USE_TWO_COLUMS) && (($e % 2) == 1)) {
8426 $out .= ($display_type==
'card' ?
'</tr>' :
'</div>');
8428 $out .= ($display_type==
'card' ?
'</tr>' :
'</div>');
8436 if (!empty($conf->use_javascript_ajax)) {
8437 $out .= $this->getJSListDependancies();
8440 $out .=
'<!-- commonobject:showOptionals end --> '.
"\n";
8442 if (empty($nbofextrafieldsshown)) {
8448 $out .= $hookmanager->resPrint;
8460 <script nonce="'.getNonce().
'">
8461 jQuery(document).ready(function() {
8462 function showOptions'.$type.
'(child_list, parent_list, orig_select)
8464 var val = $("select[name=\""+parent_list+"\"]").val();
8465 var parentVal = parent_list + ":" + val;
8466 if(typeof val == "string"){
8468 var options = orig_select.find("option[parent=\""+parentVal+"\"]").clone();
8469 $("select[name=\""+child_list+"\"] option[parent]").remove();
8470 $("select[name=\""+child_list+"\"]").append(options);
8472 var options = orig_select.find("option[parent]").clone();
8473 $("select[name=\""+child_list+"\"] option[parent]").remove();
8474 $("select[name=\""+child_list+"\"]").append(options);
8476 } else if(val > 0) {
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);
8486 function setListDependencies'.$type.
'() {
8487 jQuery("select option[parent]").parent().each(function() {
8488 var orig_select = {};
8489 var child_list = $(this).attr("name");
8490 orig_select[child_list] = $(this).clone();
8491 var parent = $(this).find("option[parent]:first").attr("parent");
8492 var infos = parent.split(":");
8493 var parent_list = infos[0];
8495 //Hide daughters lists
8496 if ($("#"+child_list).val() == 0 && $("#"+parent_list).val() == 0){
8497 $("#"+child_list).hide();
8499 } else if ($("#"+parent_list).val() != 0){
8500 $("#"+parent_list).show();
8502 //Show the child list if the parent list value is selected
8503 $("select[name=\""+parent_list+"\"]").click(function() {
8504 if ($(this).val() != 0){
8505 $("#"+child_list).show()
8509 //When we change parent list
8510 $("select[name=\""+parent_list+"\"]").change(function() {
8511 showOptions'.$type.
'(child_list, parent_list, orig_select[child_list]);
8512 //Select the value 0 on child list after a change on the parent list
8513 $("#"+child_list).val(0).trigger("change");
8514 //Hide child lists if the parent value is set to 0
8515 if ($(this).val() == 0){
8516 $("#"+child_list).hide();
8522 setListDependencies'.$type.
'();
8537 $module = empty($this->module) ?
'' : $this->module;
8538 $element = $this->element;
8540 if ($element ==
'facturerec') {
8541 $element =
'facture';
8542 } elseif ($element ==
'invoice_supplier_rec') {
8543 return empty($user->rights->fournisseur->facture) ? null : $user->rights->fournisseur->facture;
8544 } elseif ($module && !empty($user->rights->$module->$element)) {
8546 return $user->rights->$module->$element;
8549 return $user->rights->$element;
8566 foreach ($tables as $table) {
8567 $sql =
'UPDATE '.$dbs->prefix().$table.
' SET fk_soc = '.((int) $dest_id).
' WHERE fk_soc = '.((int) $origin_id);
8569 if (!$dbs->
query($sql)) {
8570 if ($ignoreerrors) {
8595 foreach ($tables as $table) {
8596 $sql =
'UPDATE '.MAIN_DB_PREFIX.$table.
' SET fk_product = '.((int) $dest_id).
' WHERE fk_product = '.((int) $origin_id);
8598 if (!$dbs->
query($sql)) {
8599 if ($ignoreerrors) {
8622 public function defineBuyPrice($unitPrice = 0.0, $discountPercent = 0.0, $fk_product = 0)
8628 if (($unitPrice > 0) && (isset($conf->global->ForceBuyingPriceIfNull) && $conf->global->ForceBuyingPriceIfNull > 0)) {
8630 $buyPrice = $unitPrice * (1 - $discountPercent / 100);
8633 if (!empty($fk_product) && $fk_product > 0) {
8634 if (isset($conf->global->MARGIN_TYPE) && $conf->global->MARGIN_TYPE ==
'costprice') {
8635 require_once DOL_DOCUMENT_ROOT.
'/product/class/product.class.php';
8636 $product =
new Product($this->db);
8637 $result = $product->fetch($fk_product);
8639 $this->errors[] =
'ErrorProductIdDoesNotExists';
8642 if ($product->cost_price > 0) {
8643 $buyPrice = $product->cost_price;
8644 } elseif ($product->pmp > 0) {
8645 $buyPrice = $product->pmp;
8647 } elseif (isset($conf->global->MARGIN_TYPE) && $conf->global->MARGIN_TYPE ==
'pmp') {
8648 require_once DOL_DOCUMENT_ROOT.
'/product/class/product.class.php';
8649 $product =
new Product($this->db);
8650 $result = $product->fetch($fk_product);
8652 $this->errors[] =
'ErrorProductIdDoesNotExists';
8655 if ($product->pmp > 0) {
8656 $buyPrice = $product->pmp;
8660 if (empty($buyPrice) && isset($conf->global->MARGIN_TYPE) && in_array($conf->global->MARGIN_TYPE, array(
'1',
'pmp',
'costprice'))) {
8661 require_once DOL_DOCUMENT_ROOT.
'/fourn/class/fournisseur.product.class.php';
8663 if (($result = $productFournisseur->find_min_price_product_fournisseur($fk_product)) > 0) {
8664 $buyPrice = $productFournisseur->fourn_unitprice;
8665 } elseif ($result < 0) {
8666 $this->errors[] = $productFournisseur->error;
8695 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')
8698 global $conf, $user, $langs;
8700 include_once DOL_DOCUMENT_ROOT.
'/core/lib/files.lib.php';
8701 include_once DOL_DOCUMENT_ROOT.
'/core/lib/images.lib.php';
8703 $sortfield =
'position_name';
8709 $dir .=
get_exdir(0, 0, 0, 0, $this, $modulepart);
8710 $pdir .=
get_exdir(0, 0, 0, 0, $this, $modulepart);
8713 if ($modulepart ==
'product') {
8715 $dir = $sdir.
'/'.
get_exdir($this->
id, 2, 0, 0, $this, $modulepart).$this->id.
"/photos/";
8716 $pdir =
'/'.get_exdir($this->
id, 2, 0, 0, $this, $modulepart).$this->id.
"/photos/";
8723 $relativedir = preg_replace(
'/^'.preg_quote(DOL_DATA_ROOT,
'/').
'/',
'', $dir);
8724 $relativedir = preg_replace(
'/^[\\/]/',
'', $relativedir);
8725 $relativedir = preg_replace(
'/[\\/]$/',
'', $relativedir);
8728 $dirthumb = $dir.
'thumbs/';
8729 $pdirthumb = $pdir.
'thumbs/';
8731 $return =
'<!-- Photo -->'.
"\n";
8734 $filearray =
dol_dir_list($dir,
"files", 0,
'',
'(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) ==
'desc' ?SORT_DESC:SORT_ASC), 1);
8744 if (count($filearray)) {
8745 if ($sortfield && $sortorder) {
8749 foreach ($filearray as $key => $val) {
8751 $file = $val[
'name'];
8757 $viewfilename = $file;
8759 if ($size == 1 || $size ==
'small') {
8766 $photo_vignette = basename($file);
8773 if ($nbphoto == 1) {
8774 $return .=
'<table class="valigntop center centpercent" style="border: 0; padding: 2px; border-spacing: 2px; border-collapse: separate;">';
8777 if ($nbphoto % $nbbyrow == 1) {
8778 $return .=
'<tr class="center valignmiddle" style="border: 1px">';
8780 $return .=
'<td style="width: '.ceil(100 / $nbbyrow).
'%" class="photo">'.
"\n";
8781 } elseif ($nbbyrow < 0) {
8782 $return .=
'<div class="inline-block">'.
"\n";
8785 $relativefile = preg_replace(
'/^\//',
'', $pdir.$photo);
8786 if (empty($nolink)) {
8789 $return .=
'<a href="'.$urladvanced.
'">';
8791 $return .=
'<a href="'.DOL_URL_ROOT.
'/viewimage.php?modulepart='.$modulepart.
'&entity='.$this->entity.
'&file='.urlencode($pdir.$photo).
'" class="aphoto" target="_blank" rel="noopener noreferrer">';
8797 $alt = $langs->transnoentitiesnoconv(
'File').
': '.$relativefile;
8798 $alt .=
' - '.$langs->transnoentitiesnoconv(
'Size').
': '.$imgarray[
'width'].
'x'.$imgarray[
'height'];
8799 if ($overwritetitle) {
8800 if (is_numeric($overwritetitle)) {
8803 $alt = $overwritetitle;
8807 if ($usesharelink) {
8808 if ($val[
'share']) {
8809 if (empty($maxHeight) || ($photo_vignette && $imgarray[
'height'] > $maxHeight)) {
8810 $return .=
'<!-- Show original file (thumb not yet available with shared links) -->';
8811 $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).
'">';
8813 $return .=
'<!-- Show original file -->';
8814 $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).
'">';
8817 $return .=
'<!-- Show nophoto file (because file is not shared) -->';
8818 $return .=
'<img class="photo photowithmargin'.($addphotorefcss ?
' '.$addphotorefcss :
'').
'" height="'.$maxHeight.
'" src="'.DOL_URL_ROOT.
'/public/theme/common/nophoto.png" title="'.
dol_escape_htmltag($alt).
'">';
8821 if (empty($maxHeight) || ($photo_vignette && $imgarray[
'height'] > $maxHeight)) {
8822 $return .=
'<!-- Show thumb -->';
8823 $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).
'">';
8825 $return .=
'<!-- Show original file -->';
8826 $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).
'">';
8830 if (empty($nolink)) {
8834 if ($showfilename) {
8835 $return .=
'<br>'.$viewfilename;
8840 if ($photo_vignette && (
image_format_supported($photo) > 0) && ($this->imgWidth > $maxWidth || $this->imgHeight > $maxHeight)) {
8841 $return .=
'<a href="'.$_SERVER[
"PHP_SELF"].
'?id='.$this->
id.
'&action=addthumb&token='.newToken().
'&file='.urlencode($pdir.$viewfilename).
'">'.
img_picto($langs->trans(
'GenerateThumb'),
'refresh').
' </a>';
8844 if ($modulepart ==
'product' && ($user->hasRight(
'produit',
'creer') || $user->hasRight(
'service',
'creer'))) {
8846 $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> ';
8849 $return .=
'<a href="'.$_SERVER[
"PHP_SELF"].
'?id='.$this->
id.
'&action=delete&token='.newToken().
'&file='.urlencode($pdir.$viewfilename).
'">';
8857 if (($nbphoto % $nbbyrow) == 0) {
8860 } elseif ($nbbyrow < 0) {
8861 $return .=
'</div>'.
"\n";
8866 $return .=
'<img class="photo photowithmargin" src="'.DOL_URL_ROOT.
'/viewimage.php?modulepart='.$modulepart.
'&entity='.$this->entity.
'&file='.urlencode($pdir.$photo).
'">';
8868 if ($showfilename) {
8869 $return .=
'<br>'.$viewfilename;
8873 if ($modulepart ==
'product' && ($user->hasRight(
'produit',
'creer') || $user->hasRight(
'service',
'creer'))) {
8875 $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> ';
8878 $return .=
'<a href="'.$_SERVER[
"PHP_SELF"].
'?id='.$this->
id.
'&action=delete&token='.newToken().
'&file='.urlencode($pdir.$viewfilename).
'">';
8885 if ($nbmax && $nbphoto >= $nbmax) {
8891 if ($size == 1 || $size ==
'small') {
8894 while ($nbphoto % $nbbyrow) {
8895 $return .=
'<td style="width: '.ceil(100 / $nbbyrow).
'%"> </td>';
8900 $return .=
'</table>';
8906 $this->nbphoto = $nbphoto;
8920 if (is_array($info)) {
8921 if (isset($info[
'type']) && $info[
'type'] ==
'array') {
8938 if (isset($info[
'type']) && ($info[
'type'] ==
'date' || $info[
'type'] ==
'datetime' || $info[
'type'] ==
'timestamp')) {
8952 if (is_array($info)) {
8953 if (isset($info[
'type']) && ($info[
'type'] ==
'duration')) {
8971 if (is_array($info)) {
8972 if (isset($info[
'type']) && (preg_match(
'/(^int|int$)/i', $info[
'type']))) {
8990 if (is_array($info)) {
8991 if (isset($info[
'type']) && (preg_match(
'/^(double|real|price)/i', $info[
'type']))) {
9008 if (is_array($info)) {
9009 if (isset($info[
'type']) && $info[
'type'] ==
'text') {
9026 if (is_array($info)) {
9027 if (isset($info[
'notnull']) && $info[
'notnull'] !=
'1') {
9044 if (is_array($info)) {
9045 if (isset($info[
'notnull']) && $info[
'notnull'] ==
'-1') {
9062 if (is_array($info)) {
9063 if (isset($info[
'index']) && $info[
'index'] ==
true) {
9085 $queryarray = array();
9086 foreach ($this->fields as $field => $info) {
9088 if ($this->isDate($info)) {
9089 if (empty($this->{$field})) {
9090 $queryarray[$field] =
null;
9092 $queryarray[$field] = $this->db->idate($this->{$field});
9094 } elseif ($this->isDuration($info)) {
9096 if ((isset($this->{$field}) && $this->{$field} !=
'') || !empty($info[
'notnull'])) {
9097 if (!isset($this->{$field})) {
9098 if (!empty($info[
'default'])) {
9099 $queryarray[$field] = $info[
'default'];
9101 $queryarray[$field] = 0;
9104 $queryarray[$field] = (int) $this->{$field};
9107 $queryarray[$field] =
null;
9109 } elseif ($this->isInt($info) || $this->isFloat($info)) {
9110 if ($field ==
'entity' && is_null($this->{$field})) {
9111 $queryarray[$field] = ((int) $conf->entity);
9114 if ((isset($this->{$field}) && $this->{$field} !=
'') || !empty($info[
'notnull'])) {
9115 if (!isset($this->{$field})) {
9116 $queryarray[$field] = 0;
9117 } elseif ($this->isInt($info)) {
9118 $queryarray[$field] = (int) $this->{$field};
9119 } elseif ($this->isFloat($info)) {
9120 $queryarray[$field] = (double) $this->{$field};
9123 $queryarray[$field] =
null;
9129 $queryarray[$field] = $this->{$field};
9132 if ($info[
'type'] ==
'timestamp' && empty($queryarray[$field])) {
9133 unset($queryarray[$field]);
9135 if (!empty($info[
'notnull']) && $info[
'notnull'] == -1 && empty($queryarray[$field])) {
9136 $queryarray[$field] =
null;
9153 foreach ($this->fields as $field => $info) {
9154 if ($this->isDate($info)) {
9155 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') {
9158 $this->$field = $db->jdate($obj->$field);
9160 } elseif ($this->isInt($info)) {
9161 if ($field ==
'rowid') {
9162 $this->
id = (int) $obj->$field;
9164 if ($this->isForcedToNullIfZero($info)) {
9165 if (empty($obj->$field)) {
9166 $this->$field =
null;
9168 $this->$field = (double) $obj->$field;
9171 if (isset($obj->$field) && (!is_null($obj->$field) || (isset($info[
'notnull']) && $info[
'notnull'] == 1))) {
9172 $this->$field = (int) $obj->$field;
9174 $this->$field =
null;
9178 } elseif ($this->isFloat($info)) {
9179 if ($this->isForcedToNullIfZero($info)) {
9180 if (empty($obj->$field)) {
9181 $this->$field =
null;
9183 $this->$field = (double) $obj->$field;
9186 if (isset($obj->$field) && (!is_null($obj->$field) || (isset($info[
'notnull']) && $info[
'notnull'] == 1))) {
9187 $this->$field = (double) $obj->$field;
9189 $this->$field =
null;
9193 $this->$field = isset($obj->$field) ? $obj->$field :
null;
9198 if (!isset($this->fields[
'ref']) && isset($this->
id)) {
9199 $this->
ref = $this->id;
9212 $keys = array_keys($this->fields);
9213 if (!empty($alias)) {
9214 $keys_with_alias = array();
9215 foreach ($keys as $fieldname) {
9216 if (!empty($excludefields)) {
9217 if (in_array($fieldname, $excludefields)) {
9221 $keys_with_alias[] = $alias .
'.' . $fieldname;
9223 return implode(
',', $keys_with_alias);
9225 return implode(
',', $keys);
9236 protected function quote($value, $fieldsentry)
9238 if (is_null($value)) {
9240 } elseif (preg_match(
'/^(int|double|real|price)/i', $fieldsentry[
'type'])) {
9242 } elseif (preg_match(
'/int$/i', $fieldsentry[
'type'])) {
9243 return (
int) $value;
9244 } elseif ($fieldsentry[
'type'] ==
'boolean') {
9251 return "'".$this->db->escape($value).
"'";
9266 dol_syslog(get_class($this).
"::createCommon create", LOG_DEBUG);
9272 $fieldvalues = $this->setSaveQuery();
9274 if (array_key_exists(
'date_creation', $fieldvalues) && empty($fieldvalues[
'date_creation'])) {
9275 $fieldvalues[
'date_creation'] = $this->db->idate($now);
9277 if (array_key_exists(
'fk_user_creat', $fieldvalues) && !($fieldvalues[
'fk_user_creat'] > 0)) {
9278 $fieldvalues[
'fk_user_creat'] = $user->id;
9279 $this->fk_user_creat = $user->id;
9281 if (array_key_exists(
'user_modification_id', $fieldvalues) && !($fieldvalues[
'user_modification_id'] > 0)) {
9282 $fieldvalues[
'user_modification_id'] = $user->id;
9283 $this->user_modification_id = $user->id;
9285 unset($fieldvalues[
'rowid']);
9286 if (array_key_exists(
'ref', $fieldvalues)) {
9292 foreach ($fieldvalues as $k => $v) {
9294 $value = $this->fields[$k];
9295 $values[$k] = $this->quote($v, $value);
9299 foreach ($keys as $key) {
9301 if (preg_match(
'/^integer:/i', $this->fields[$key][
'type']) && $values[$key] ==
'-1') {
9304 if (!empty($this->fields[$key][
'foreignkey']) && $values[$key] ==
'-1') {
9308 if (isset($this->fields[$key][
'notnull']) && $this->fields[$key][
'notnull'] == 1 && (!isset($values[$key]) || $values[$key] ===
'NULL') && is_null($this->fields[$key][
'default'])) {
9310 $langs->load(
"errors");
9311 dol_syslog(
"Mandatory field '".$key.
"' is empty and required into ->fields definition of class");
9312 $this->errors[] = $langs->trans(
"ErrorFieldRequired", $this->fields[$key][
'label']);
9316 if (isset($this->fields[$key][
'notnull']) && $this->fields[$key][
'notnull'] == 1 && (!isset($values[$key]) || $values[$key] ===
'NULL') && !is_null($this->fields[$key][
'default'])) {
9317 $values[$key] = $this->quote($this->fields[$key][
'default'], $this->fields[$key]);
9321 if (preg_match(
'/^integer:/i', $this->fields[$key][
'type']) && empty($values[$key])) {
9322 if (isset($this->fields[$key][
'default'])) {
9323 $values[$key] = ((int) $this->fields[$key][
'default']);
9325 $values[$key] =
'null';
9328 if (!empty($this->fields[$key][
'foreignkey']) && empty($values[$key])) {
9329 $values[$key] =
'null';
9340 $sql =
"INSERT INTO ".$this->db->prefix().$this->table_element;
9341 $sql .=
" (".implode(
", ", $keys).
')';
9342 $sql .=
" VALUES (".implode(
", ", $values).
")";
9344 $res = $this->db->query($sql);
9347 if ($this->db->lasterrno() ==
'DB_ERROR_RECORD_ALREADY_EXISTS') {
9348 $this->errors[] =
"ErrorRefAlreadyExists";
9350 $this->errors[] = $this->db->lasterror();
9356 $this->
id = $this->db->last_insert_id($this->db->prefix().$this->table_element);
9361 if (key_exists(
'ref', $this->fields) && $this->fields[
'ref'][
'notnull'] > 0 && key_exists(
'default', $this->fields[
'ref']) && $this->fields[
'ref'][
'default'] ==
'(PROV)') {
9362 $sql =
"UPDATE ".$this->db->prefix().$this->table_element.
" SET ref = '(PROV".((int) $this->
id).
")' WHERE (ref = '(PROV)' OR ref = '') AND rowid = ".((int) $this->
id);
9363 $resqlupdate = $this->db->query($sql);
9365 if ($resqlupdate ===
false) {
9367 $this->errors[] = $this->db->lasterror();
9369 $this->
ref =
'(PROV'.$this->id.
')';
9376 $result = $this->insertExtraFields();
9383 if (!empty($this->table_element_line) && !empty($this->fk_element)) {
9384 $num = (is_array($this->lines) ? count($this->lines) : 0);
9385 for ($i = 0; $i < $num; $i++) {
9386 $line = $this->lines[$i];
9388 $keyforparent = $this->fk_element;
9389 $line->$keyforparent = $this->id;
9393 if (!is_object($line)) {
9394 $line = (object) $line;
9398 if (method_exists($line,
'insert')) {
9399 $result = $line->insert($user, 1);
9400 } elseif (method_exists($line,
'create')) {
9401 $result = $line->create($user, 1);
9404 $this->error = $line->error;
9405 $this->db->rollback();
9412 if (!$error && !$notrigger) {
9414 $result = $this->call_trigger(strtoupper(get_class($this)).
'_CREATE', $user);
9423 $this->db->rollback();
9426 $this->db->commit();
9442 if (empty($id) && empty($ref) && empty($morewhere)) {
9446 $fieldlist = $this->getFieldList(
't');
9447 if (empty($fieldlist)) {
9451 $sql =
"SELECT ".$fieldlist;
9452 $sql .=
" FROM ".$this->db->prefix().$this->table_element.
' as t';
9455 $sql .=
' WHERE t.rowid = '.((int) $id);
9456 } elseif (!empty($ref)) {
9457 $sql .=
" WHERE t.ref = '".$this->db->escape($ref).
"'";
9459 $sql .=
' WHERE 1 = 1';
9461 if (empty($id) && isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
9462 $sql .=
' AND t.entity IN ('.getEntity($this->element).
')';
9469 $res = $this->db->query($sql);
9471 $obj = $this->db->fetch_object($res);
9473 $this->setVarsFromFetchObj($obj);
9477 $this->fetch_optionals();
9484 $this->error = $this->db->lasterror();
9485 $this->errors[] = $this->error;
9498 $objectlineclassname = get_class($this).
'Line';
9499 if (!class_exists($objectlineclassname)) {
9500 $this->error =
'Error, class '.$objectlineclassname.
' not found during call of fetchLinesCommon';
9504 $objectline =
new $objectlineclassname($this->db);
9506 $sql =
"SELECT ".$objectline->getFieldList(
'l');
9507 $sql .=
" FROM ".$this->db->prefix().$objectline->table_element.
" as l";
9508 $sql .=
" WHERE l.fk_".$this->db->escape($this->element).
" = ".((int) $this->
id);
9512 if (isset($objectline->fields[
'position'])) {
9513 $sql .= $this->db->order(
'position',
'ASC');
9516 $resql = $this->db->query($sql);
9518 $num_rows = $this->db->num_rows($resql);
9520 $this->lines = array();
9521 while ($i < $num_rows) {
9522 $obj = $this->db->fetch_object($resql);
9524 $newline =
new $objectlineclassname($this->db);
9525 $newline->setVarsFromFetchObj($obj);
9527 $this->lines[] = $newline;
9534 $this->error = $this->db->lasterror();
9535 $this->errors[] = $this->error;
9549 global $conf, $langs;
9550 dol_syslog(get_class($this).
"::updateCommon update", LOG_DEBUG);
9561 $fieldvalues = $this->setSaveQuery();
9563 if (array_key_exists(
'date_modification', $fieldvalues) && empty($fieldvalues[
'date_modification'])) {
9564 $fieldvalues[
'date_modification'] = $this->db->idate($now);
9566 if (array_key_exists(
'fk_user_modif', $fieldvalues) && !($fieldvalues[
'fk_user_modif'] > 0)) {
9567 $fieldvalues[
'fk_user_modif'] = $user->id;
9569 unset($fieldvalues[
'rowid']);
9570 if (array_key_exists(
'ref', $fieldvalues)) {
9578 foreach ($fieldvalues as $k => $v) {
9580 $value = $this->fields[$k];
9581 $values[$k] = $this->quote($v, $value);
9582 $tmp[] = $k.
'='.$this->quote($v, $this->fields[$k]);
9586 foreach ($keys as $key) {
9587 if (preg_match(
'/^integer:/i', $this->fields[$key][
'type']) && $values[$key] ==
'-1') {
9590 if (!empty($this->fields[$key][
'foreignkey']) && $values[$key] ==
'-1') {
9603 $sql =
'UPDATE '.$this->db->prefix().$this->table_element.
' SET '.implode(
', ', $tmp).
' WHERE rowid='.((int) $this->
id);
9608 $res = $this->db->query($sql);
9611 $this->errors[] = $this->db->lasterror();
9617 $result = $this->insertExtraFields();
9624 if (!$error && !$notrigger) {
9626 $result = $this->call_trigger(strtoupper(get_class($this)).
'_MODIFY', $user);
9635 $this->db->rollback();
9638 $this->db->commit();
9653 dol_syslog(get_class($this).
"::deleteCommon delete", LOG_DEBUG);
9659 if ($forcechilddeletion) {
9660 foreach ($this->childtables as $table) {
9661 $sql =
"DELETE FROM ".$this->db->prefix().$table.
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
9662 $resql = $this->db->query($sql);
9664 $this->error = $this->db->lasterror();
9665 $this->errors[] = $this->error;
9666 $this->db->rollback();
9670 } elseif (!empty($this->childtables)) {
9671 $objectisused = $this->isObjectUsed($this->
id);
9672 if (!empty($objectisused)) {
9673 dol_syslog(get_class($this).
"::deleteCommon Can't delete record as it has some child", LOG_WARNING);
9674 $this->error =
'ErrorRecordHasChildren';
9675 $this->errors[] = $this->error;
9676 $this->db->rollback();
9682 if (is_array($this->childtablesoncascade) && !empty($this->childtablesoncascade)) {
9683 foreach ($this->childtablesoncascade as $table) {
9684 $deleteFromObject = explode(
':', $table);
9685 if (count($deleteFromObject) >= 2) {
9686 $className = str_replace(
'@',
'', $deleteFromObject[0]);
9687 $filePath = $deleteFromObject[1];
9688 $columnName = $deleteFromObject[2];
9689 $TMoreSQL = array();
9690 $more_sql = $deleteFromObject[3];
9691 if (!empty($more_sql)) {
9692 $TMoreSQL[
'customsql'] = $more_sql;
9695 $childObject =
new $className($this->db);
9696 if (method_exists($childObject,
'deleteByParentField')) {
9697 $result = $childObject->deleteByParentField($this->
id, $columnName, $TMoreSQL);
9700 $this->errors[] = $childObject->error;
9705 $this->errors[] =
"You defined a cascade delete on an object $childObject but there is no method deleteByParentField for it";
9710 $this->errors[] =
'Cannot include child class file '.$filePath;
9715 $sql =
"DELETE FROM ".$this->db->prefix().$table.
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
9717 $resql = $this->db->query($sql);
9720 $this->error = $this->db->lasterror();
9721 $this->errors[] = $this->error;
9731 $result = $this->call_trigger(strtoupper(get_class($this)).
'_DELETE', $user);
9741 $res = $this->deleteEcmFiles(1);
9748 $res = $this->deleteObjectLinked();
9753 if (!$error && !empty($this->isextrafieldmanaged)) {
9754 $result = $this->deleteExtraFields();
9761 $sql =
'DELETE FROM '.$this->db->prefix().$this->table_element.
' WHERE rowid='.((int) $this->
id);
9763 $resql = $this->db->query($sql);
9766 $this->errors[] = $this->db->lasterror();
9772 $this->db->rollback();
9775 $this->db->commit();
9797 if (!empty($parentId) && !empty($parentField)) {
9800 $sql =
"SELECT rowid FROM ".$this->db->prefix().$this->table_element;
9801 $sql .=
" WHERE ".$parentField.
" = ".(int) $parentId;
9804 $sqlwhere = array();
9805 if (count($filter) > 0) {
9806 foreach ($filter as $key => $value) {
9807 if ($key ==
'customsql') {
9808 $sqlwhere[] = $value;
9809 } elseif (strpos($value,
'%') ===
false) {
9810 $sqlwhere[] = $key.
" IN (".$this->db->sanitize($this->db->escape($value)).
")";
9812 $sqlwhere[] = $key.
" LIKE '%".$this->db->escape($value).
"%'";
9816 if (count($sqlwhere) > 0) {
9817 $sql .=
" AND (".implode(
" ".$filtermode.
" ", $sqlwhere).
")";
9820 $resql = $this->db->query($sql);
9822 $this->errors[] = $this->db->lasterror();
9825 while ($obj = $this->db->fetch_object($resql)) {
9826 $result = $this->fetch($obj->rowid);
9829 $this->errors[] = $this->error;
9831 if (get_class($this) ==
'Contact') {
9832 $result = $this->
delete();
9834 $result = $this->
delete($user);
9838 $this->errors[] = $this->error;
9846 if (empty($error)) {
9847 $this->db->commit();
9850 $this->error = implode(
', ', $this->errors);
9851 $this->db->rollback();
9873 $tmpforobjectclass = get_class($this);
9874 $tmpforobjectlineclass = ucfirst($tmpforobjectclass).
'Line';
9879 $result = $this->call_trigger(
'LINE'.strtoupper($tmpforobjectclass).
'_DELETE', $user);
9885 if (empty($error)) {
9886 $sql =
"DELETE FROM ".$this->db->prefix().$this->table_element_line;
9887 $sql .=
" WHERE rowid = ".((int) $idline);
9889 $resql = $this->db->query($sql);
9891 $this->error =
"Error ".$this->db->lasterror();
9896 if (empty($error)) {
9898 $tmpobjectline =
new $tmpforobjectlineclass($this->db);
9899 if (!isset($tmpobjectline->isextrafieldmanaged) || !empty($tmpobjectline->isextrafieldmanaged)) {
9900 $tmpobjectline->id = $idline;
9901 $result = $tmpobjectline->deleteExtraFields();
9904 $this->error =
"Error ".get_class($this).
"::deleteLineCommon deleteExtraFields error -4 ".$tmpobjectline->error;
9909 if (empty($error)) {
9910 $this->db->commit();
9913 dol_syslog(get_class($this).
"::deleteLineCommon ERROR:".$this->error, LOG_ERR);
9914 $this->db->rollback();
9935 $statusfield =
'status';
9936 if (in_array($this->element, array(
'don',
'donation',
'shipping'))) {
9937 $statusfield =
'fk_statut';
9940 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
9941 $sql .=
" SET ".$statusfield.
" = ".((int) $status);
9942 $sql .=
" WHERE rowid = ".((int) $this->
id);
9944 if ($this->db->query($sql)) {
9946 $this->oldcopy = clone $this;
9949 if (!$error && !$notrigger) {
9951 $result = $this->call_trigger($triggercode, $user);
9958 $this->status = $status;
9959 $this->db->commit();
9962 $this->db->rollback();
9966 $this->error = $this->db->error();
9967 $this->db->rollback();
9984 $this->specimen = 1;
9986 'label' =>
'This is label',
9987 'ref' =>
'ABCD1234',
9988 'description' =>
'This is a description',
9990 'note_public' =>
'Public note',
9991 'note_private' =>
'Private note',
9992 'date_creation' => (
dol_now() - 3600 * 48),
9993 'date_modification' => (
dol_now() - 3600 * 24),
9994 'fk_user_creat' => $user->id,
9995 'fk_user_modif' => $user->id,
9998 foreach ($fields as $key => $value) {
9999 if (array_key_exists($key, $this->fields)) {
10000 $this->{$key} = $value;
10005 if (property_exists($this,
'fields')) {
10006 foreach ($this->fields as $key => $value) {
10008 if (array_key_exists($key, $fields)) {
10012 if (!empty($value[
'default'])) {
10013 $this->$key = $value[
'default'];
10030 require_once DOL_DOCUMENT_ROOT.
'/core/class/comment.class.php';
10032 $comment =
new Comment($this->db);
10033 $result = $comment->fetchAllFor($this->element, $this->
id);
10035 $this->errors = array_merge($this->errors, $comment->errors);
10038 $this->comments = $comment->comments;
10040 return count($this->comments);
10050 return count($this->comments);
10061 if (!is_array($parameters)) {
10064 foreach ($parameters as $parameter) {
10065 if (isset($this->$parameter)) {
10066 $this->$parameter = trim($this->$parameter);
10085 require_once DOL_DOCUMENT_ROOT.
'/categories/class/categorie.class.php';
10089 $existing = $c->containing($this->
id, $type_categ,
'id');
10109 if (!is_array($categories)) {
10110 $categories = array($categories);
10113 dol_syslog(get_class($this).
"::setCategoriesCommon Oject Id:".$this->
id.
' type_categ:'.$type_categ.
' nb tag add:'.count($categories), LOG_DEBUG);
10115 require_once DOL_DOCUMENT_ROOT.
'/categories/class/categorie.class.php';
10117 if (empty($type_categ)) {
10118 dol_syslog(__METHOD__.
': Type '.$type_categ.
'is an unknown category type. Done nothing.', LOG_ERR);
10124 $existing = $c->containing($this->
id, $type_categ,
'id');
10125 if ($remove_existing) {
10127 if (is_array($existing)) {
10128 $to_del = array_diff($existing, $categories);
10129 $to_add = array_diff($categories, $existing);
10132 $to_add = $categories;
10136 $to_add = array_diff($categories, $existing);
10143 foreach ($to_del as $del) {
10144 if ($c->fetch($del) > 0) {
10145 $result=$c->del_type($this, $type_categ);
10148 $this->error = $c->error;
10149 $this->errors = $c->errors;
10156 foreach ($to_add as $add) {
10157 if ($c->fetch($add) > 0) {
10158 $result = $c->add_type($this, $type_categ);
10161 $this->error = $c->error;
10162 $this->errors = $c->errors;
10170 return $error ? (-1 * $error) : $ok;
10183 $this->db->begin();
10185 if (empty($type)) {
10186 $type = $this->table_element;
10189 require_once DOL_DOCUMENT_ROOT.
'/categories/class/categorie.class.php';
10190 $categorystatic =
new Categorie($this->db);
10192 $sql =
"INSERT INTO ".$this->db->prefix().
"categorie_".(empty($categorystatic->MAP_CAT_TABLE[$type]) ? $type : $categorystatic->MAP_CAT_TABLE[$type]).
" (fk_categorie, fk_product)";
10193 $sql .=
" SELECT fk_categorie, $toId FROM ".$this->db->prefix().
"categorie_".(empty($categorystatic->MAP_CAT_TABLE[$type]) ? $type : $categorystatic->MAP_CAT_TABLE[$type]);
10194 $sql .=
" WHERE fk_product = ".((int) $fromId);
10196 if (!$this->db->query($sql)) {
10197 $this->error = $this->db->lasterror();
10198 $this->db->rollback();
10202 $this->db->commit();
10216 $this->db->begin();
10220 switch ($this->element) {
10222 $element =
'propale';
10225 $element =
'produit';
10227 case 'order_supplier':
10228 $element =
'fournisseur/commande';
10230 case 'invoice_supplier':
10231 $element =
'fournisseur/facture/'.get_exdir($this->
id, 2, 0, 1, $this,
'invoice_supplier');
10234 $element =
'expedition/sending';
10237 $element = $this->element;
10241 $sql =
"DELETE FROM ".$this->db->prefix().
"ecm_files_extrafields WHERE fk_object IN (";
10242 $sql .=
" SELECT rowid FROM ".$this->db->prefix().
"ecm_files WHERE filename LIKE '".$this->db->escape($this->
ref).
"%'";
10243 $sql .=
" AND filepath = '".$this->db->escape($element).
"/".$this->db->escape($this->
ref).
"' AND entity = ".((int) $conf->entity);
10246 if (!$this->db->query($sql)) {
10247 $this->error = $this->db->lasterror();
10248 $this->db->rollback();
10253 $sql =
"DELETE FROM ".$this->db->prefix().
"ecm_files";
10254 $sql .=
" WHERE filename LIKE '".$this->db->escape($this->
ref).
"%'";
10255 $sql .=
" AND filepath = '".$this->db->escape($element).
"/".$this->db->escape($this->
ref).
"' AND entity = ".((int) $conf->entity);
10257 if (!$this->db->query($sql)) {
10258 $this->error = $this->db->lasterror();
10259 $this->db->rollback();
10266 $sql =
'DELETE FROM '.$this->db->prefix().
"ecm_files_extrafields";
10267 $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).
")";
10268 $resql = $this->db->query($sql);
10270 $this->error = $this->db->lasterror();
10271 $this->db->rollback();
10275 $sql =
'DELETE FROM '.$this->db->prefix().
"ecm_files";
10276 $sql .=
" 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();
10285 $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_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.