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 if (empty($user->admin) || !empty($user->entity) || $conf->entity != 1) {
2115 $sql .=
" INNER JOIN ".MAIN_DB_PREFIX.
"usergroup_user as ug ON ug.fk_user = te.rowid";
2118 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2119 $tmparray = explode(
'@', $this->ismultientitymanaged);
2120 $sql .=
", ".$this->db->prefix().$tmparray[1].
" as ".($tmparray[1] ==
'societe' ?
's' :
'parenttable');
2121 } elseif ($restrictiononfksoc == 1 && $this->element !=
'societe' && empty($user->rights->societe->client->voir) && !$socid) {
2122 $sql .=
", ".$this->db->prefix().
"societe as s";
2123 } elseif ($restrictiononfksoc == 2 && $this->element !=
'societe' && empty($user->rights->societe->client->voir) && !$socid) {
2124 $sql .=
" LEFT JOIN ".$this->db->prefix().
"societe as s ON te.fk_soc = s.rowid";
2126 if ($restrictiononfksoc && empty($user->rights->societe->client->voir) && !$socid) {
2127 $sql .=
" LEFT JOIN ".$this->db->prefix().
"societe_commerciaux as sc ON ".$aliastablesociete.
".rowid = sc.fk_soc";
2129 $sql .=
" WHERE te.".$fieldid.
" < '".$this->db->escape($fieldid ==
'rowid' ? $this->
id : $this->ref).
"'";
2130 if ($restrictiononfksoc == 1 && empty($user->rights->societe->client->voir) && !$socid) {
2131 $sql .=
" AND sc.fk_user = ".((int) $user->id);
2133 if ($restrictiononfksoc == 2 && empty($user->rights->societe->client->voir) && !$socid) {
2134 $sql .=
" AND (sc.fk_user = ".((int) $user->id).
' OR te.fk_soc IS NULL)';
2136 if (!empty($filter)) {
2137 if (!preg_match(
'/^\s*AND/i', $filter)) {
2142 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2143 $tmparray = explode(
'@', $this->ismultientitymanaged);
2144 $sql .=
" AND te.".$tmparray[0].
" = ".($tmparray[1] ==
"societe" ?
"s" :
"parenttable").
".rowid";
2145 } elseif ($restrictiononfksoc == 1 && $this->element !=
'societe' && empty($user->rights->societe->client->voir) && !$socid) {
2146 $sql .=
' AND te.fk_soc = s.rowid';
2148 if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
2149 if ($this->element ==
'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
2150 if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
2151 $sql .=
" AND te.entity IS NOT NULL";
2153 $sql .=
" AND ug.entity IN (".getEntity(
'usergroup').
")";
2156 $sql .=
' AND te.entity IN ('.getEntity($this->element).
')';
2159 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged) && $this->element !=
'societe') {
2160 $tmparray = explode(
'@', $this->ismultientitymanaged);
2161 $sql .=
' AND parenttable.entity IN ('.getEntity($tmparray[1]).
')';
2163 if ($restrictiononfksoc == 1 && $socid && $this->element !=
'societe') {
2164 $sql .=
' AND te.fk_soc = '.((int) $socid);
2166 if ($restrictiononfksoc == 2 && $socid && $this->element !=
'societe') {
2167 $sql .=
' AND (te.fk_soc = '.((int) $socid).
' OR te.fk_soc IS NULL)';
2169 if ($restrictiononfksoc && $socid && $this->element ==
'societe') {
2170 $sql .=
' AND te.rowid = '.((int) $socid);
2174 $result = $this->db->query($sql);
2176 $this->error = $this->db->lasterror();
2179 $row = $this->db->fetch_row($result);
2180 $this->ref_previous = $row[0];
2182 $sql =
"SELECT MIN(te.".$fieldid.
")";
2183 $sql .=
" FROM ".(empty($nodbprefix) ?$this->db->prefix():
'').$this->table_element.
" as te";
2184 if ($this->element ==
'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
2185 if (empty($user->admin) || !empty($user->entity) || $conf->entity != 1) {
2186 $sql .=
" INNER JOIN ".MAIN_DB_PREFIX.
"usergroup_user as ug ON ug.fk_user = te.rowid";
2189 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2190 $tmparray = explode(
'@', $this->ismultientitymanaged);
2191 $sql .=
", ".$this->db->prefix().$tmparray[1].
" as ".($tmparray[1] ==
'societe' ?
's' :
'parenttable');
2192 } elseif ($restrictiononfksoc == 1 && $this->element !=
'societe' && empty($user->rights->societe->client->voir) && !$socid) {
2193 $sql .=
", ".$this->db->prefix().
"societe as s";
2194 } elseif ($restrictiononfksoc == 2 && $this->element !=
'societe' && empty($user->rights->societe->client->voir) && !$socid) {
2195 $sql .=
" LEFT JOIN ".$this->db->prefix().
"societe as s ON te.fk_soc = s.rowid";
2197 if ($restrictiononfksoc && empty($user->rights->societe->client->voir) && !$socid) {
2198 $sql .=
" LEFT JOIN ".$this->db->prefix().
"societe_commerciaux as sc ON ".$aliastablesociete.
".rowid = sc.fk_soc";
2200 $sql .=
" WHERE te.".$fieldid.
" > '".$this->db->escape($fieldid ==
'rowid' ? $this->
id : $this->ref).
"'";
2201 if ($restrictiononfksoc == 1 && empty($user->rights->societe->client->voir) && !$socid) {
2202 $sql .=
" AND sc.fk_user = ".((int) $user->id);
2204 if ($restrictiononfksoc == 2 && empty($user->rights->societe->client->voir) && !$socid) {
2205 $sql .=
" AND (sc.fk_user = ".((int) $user->id).
' OR te.fk_soc IS NULL)';
2207 if (!empty($filter)) {
2208 if (!preg_match(
'/^\s*AND/i', $filter)) {
2213 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2214 $tmparray = explode(
'@', $this->ismultientitymanaged);
2215 $sql .=
" AND te.".$tmparray[0].
" = ".($tmparray[1] ==
"societe" ?
"s" :
"parenttable").
".rowid";
2216 } elseif ($restrictiononfksoc == 1 && $this->element !=
'societe' && empty($user->rights->societe->client->voir) && !$socid) {
2217 $sql .=
' AND te.fk_soc = s.rowid';
2219 if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
2220 if ($this->element ==
'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
2221 if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
2222 $sql .=
" AND te.entity IS NOT NULL";
2224 $sql .=
" AND ug.entity IN (".getEntity(
'usergroup').
")";
2227 $sql .=
' AND te.entity IN ('.getEntity($this->element).
')';
2230 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged) && $this->element !=
'societe') {
2231 $tmparray = explode(
'@', $this->ismultientitymanaged);
2232 $sql .=
' AND parenttable.entity IN ('.getEntity($tmparray[1]).
')';
2234 if ($restrictiononfksoc == 1 && $socid && $this->element !=
'societe') {
2235 $sql .=
' AND te.fk_soc = '.((int) $socid);
2237 if ($restrictiononfksoc == 2 && $socid && $this->element !=
'societe') {
2238 $sql .=
' AND (te.fk_soc = '.((int) $socid).
' OR te.fk_soc IS NULL)';
2240 if ($restrictiononfksoc && $socid && $this->element ==
'societe') {
2241 $sql .=
' AND te.rowid = '.((int) $socid);
2246 $result = $this->db->query($sql);
2248 $this->error = $this->db->lasterror();
2251 $row = $this->db->fetch_row($result);
2252 $this->ref_next = $row[0];
2267 $contactAlreadySelected = array();
2268 $tab = $this->liste_contact(-1, $source);
2272 if ($source ==
'thirdparty') {
2273 $contactAlreadySelected[$i] = $tab[$i][
'socid'];
2275 $contactAlreadySelected[$i] = $tab[$i][
'id'];
2279 return $contactAlreadySelected;
2295 if (!$this->table_element) {
2296 dol_syslog(get_class($this).
"::setProject was called on objet with property table_element not defined", LOG_ERR);
2300 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
2301 if (!empty($this->fields[
'fk_project'])) {
2303 $sql .=
" SET fk_project = ".((int) $projectid);
2305 $sql .=
" SET fk_project = NULL";
2307 $sql .=
' WHERE rowid = '.((int) $this->
id);
2308 } elseif ($this->table_element ==
'actioncomm') {
2310 $sql .=
" SET fk_project = ".((int) $projectid);
2312 $sql .=
" SET fk_project = NULL";
2314 $sql .=
' WHERE id = '.((int) $this->
id);
2318 $sql .=
' SET fk_projet = '.((int) $projectid);
2320 $sql .=
' SET fk_projet = NULL';
2322 $sql .=
" WHERE rowid = ".((int) $this->
id);
2327 dol_syslog(get_class($this).
"::setProject", LOG_DEBUG);
2328 if ($this->db->query($sql)) {
2329 $this->fk_project = ((int) $projectid);
2336 if (!$error && !$notrigger) {
2338 $result = $this->call_trigger(strtoupper($this->element) .
'_MODIFY', $user);
2347 $this->db->rollback();
2350 $this->db->commit();
2365 $error = 0; $notrigger = 0;
2367 dol_syslog(get_class($this).
'::setPaymentMethods('.$id.
')');
2369 if ($this->
statut >= 0 || $this->element ==
'societe') {
2371 $fieldname =
'fk_mode_reglement';
2372 if ($this->element ==
'societe') {
2373 $fieldname =
'mode_reglement';
2375 if (get_class($this) ==
'Fournisseur') {
2376 $fieldname =
'mode_reglement_supplier';
2378 if (get_class($this) ==
'Tva') {
2379 $fieldname =
'fk_typepayment';
2381 if (get_class($this) ==
'Salary') {
2382 $fieldname =
'fk_typepayment';
2385 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
2386 $sql .=
" SET ".$fieldname.
" = ".(($id > 0 || $id ==
'0') ? ((
int) $id) :
'NULL');
2387 $sql .=
' WHERE rowid='.((int) $this->
id);
2389 if ($this->db->query($sql)) {
2390 $this->mode_reglement_id = $id;
2392 if (get_class($this) ==
'Fournisseur') {
2393 $this->mode_reglement_supplier_id = $id;
2396 if (!$error && !$notrigger) {
2398 if (get_class($this) ==
'Commande') {
2399 $result = $this->call_trigger(
'ORDER_MODIFY', $user);
2401 $result = $this->call_trigger(strtoupper(get_class($this)).
'_MODIFY', $user);
2410 dol_syslog(get_class($this).
'::setPaymentMethods Error '.$this->db->error());
2411 $this->error = $this->db->error();
2415 dol_syslog(get_class($this).
'::setPaymentMethods, status of the object is incompatible');
2416 $this->error =
'Status of the object is incompatible '.$this->statut;
2429 dol_syslog(get_class($this).
'::setMulticurrencyCode('.$code.
')');
2430 if ($this->
statut >= 0 || $this->element ==
'societe') {
2431 $fieldname =
'multicurrency_code';
2433 $sql =
'UPDATE '.$this->db->prefix().$this->table_element;
2434 $sql .=
" SET ".$fieldname.
" = '".$this->db->escape($code).
"'";
2435 $sql .=
' WHERE rowid='.((int) $this->
id);
2437 if ($this->db->query($sql)) {
2438 $this->multicurrency_code = $code;
2442 $this->setMulticurrencyRate($rate, 2);
2447 dol_syslog(get_class($this).
'::setMulticurrencyCode Error '.$sql.
' - '.$this->db->error());
2448 $this->error = $this->db->error();
2452 dol_syslog(get_class($this).
'::setMulticurrencyCode, status of the object is incompatible');
2453 $this->error =
'Status of the object is incompatible '.$this->statut;
2465 public function setMulticurrencyRate($rate, $mode = 1)
2467 dol_syslog(get_class($this).
'::setMulticurrencyRate('.$rate.
','.$mode.
')');
2468 if ($this->
statut >= 0 || $this->element ==
'societe') {
2469 $fieldname =
'multicurrency_tx';
2471 $sql =
'UPDATE '.$this->db->prefix().$this->table_element;
2472 $sql .=
" SET ".$fieldname.
" = ".((float) $rate);
2473 $sql .=
' WHERE rowid='.((int) $this->
id);
2475 if ($this->db->query($sql)) {
2476 $this->multicurrency_tx = $rate;
2479 if (!empty($this->lines)) {
2480 foreach ($this->lines as &$line) {
2483 $line->subprice = 0;
2488 $line->multicurrency_subprice = 0;
2491 switch ($this->element) {
2499 $line->remise_percent,
2501 $line->localtax1_tx,
2502 $line->localtax2_tx,
2503 ($line->description ? $line->description : $line->desc),
2506 $line->special_code,
2507 $line->fk_parent_line,
2508 $line->skip_update_total,
2509 $line->fk_fournprice,
2512 $line->product_type,
2515 $line->array_options,
2517 $line->multicurrency_subprice
2525 ($line->description ? $line->description : $line->desc),
2528 $line->remise_percent,
2530 $line->localtax1_tx,
2531 $line->localtax2_tx,
2536 $line->product_type,
2537 $line->fk_parent_line,
2538 $line->skip_update_total,
2539 $line->fk_fournprice,
2542 $line->special_code,
2543 $line->array_options,
2545 $line->multicurrency_subprice
2553 ($line->description ? $line->description : $line->desc),
2556 $line->remise_percent,
2560 $line->localtax1_tx,
2561 $line->localtax2_tx,
2564 $line->product_type,
2565 $line->fk_parent_line,
2566 $line->skip_update_total,
2567 $line->fk_fournprice,
2570 $line->special_code,
2571 $line->array_options,
2572 $line->situation_percent,
2574 $line->multicurrency_subprice
2577 case 'supplier_proposal':
2584 $line->remise_percent,
2586 $line->localtax1_tx,
2587 $line->localtax2_tx,
2588 ($line->description ? $line->description : $line->desc),
2591 $line->special_code,
2592 $line->fk_parent_line,
2593 $line->skip_update_total,
2594 $line->fk_fournprice,
2597 $line->product_type,
2598 $line->array_options,
2600 $line->multicurrency_subprice
2603 case 'order_supplier':
2608 ($line->description ? $line->description : $line->desc),
2611 $line->remise_percent,
2613 $line->localtax1_tx,
2614 $line->localtax2_tx,
2617 $line->product_type,
2621 $line->array_options,
2623 $line->multicurrency_subprice,
2627 case 'invoice_supplier':
2632 ($line->description ? $line->description : $line->desc),
2635 $line->localtax1_tx,
2636 $line->localtax2_tx,
2641 $line->product_type,
2642 $line->remise_percent,
2646 $line->array_options,
2648 $line->multicurrency_subprice,
2653 dol_syslog(get_class($this).
'::setMulticurrencyRate no updateline defined', LOG_DEBUG);
2661 dol_syslog(get_class($this).
'::setMulticurrencyRate Error '.$sql.
' - '.$this->db->error());
2662 $this->error = $this->db->error();
2666 dol_syslog(get_class($this).
'::setMulticurrencyRate, status of the object is incompatible');
2667 $this->error =
'Status of the object is incompatible '.$this->statut;
2681 dol_syslog(get_class($this).
'::setPaymentTerms('.$id.
', '.var_export($deposit_percent,
true).
')');
2682 if ($this->
statut >= 0 || $this->element ==
'societe') {
2684 $fieldname =
'fk_cond_reglement';
2685 if ($this->element ==
'societe') {
2686 $fieldname =
'cond_reglement';
2688 if (get_class($this) ==
'Fournisseur') {
2689 $fieldname =
'cond_reglement_supplier';
2692 if (empty($deposit_percent) || $deposit_percent < 0) {
2696 if ($deposit_percent > 100) {
2697 $deposit_percent = 100;
2700 $sql =
'UPDATE '.$this->db->prefix().$this->table_element;
2701 $sql .=
" SET ".$fieldname.
" = ".(($id > 0 || $id ==
'0') ? ((
int) $id) :
'NULL');
2702 if (in_array($this->table_element, array(
'propal',
'commande',
'societe'))) {
2703 $sql .=
" , deposit_percent = " . (empty($deposit_percent) ?
'NULL' :
"'".$this->db->escape($deposit_percent).
"'");
2705 $sql .=
' WHERE rowid='.((int) $this->
id);
2707 if ($this->db->query($sql)) {
2708 $this->cond_reglement_id = $id;
2710 if (get_class($this) ==
'Fournisseur') {
2711 $this->cond_reglement_supplier_id = $id;
2713 $this->cond_reglement = $id;
2714 $this->deposit_percent = $deposit_percent;
2717 dol_syslog(get_class($this).
'::setPaymentTerms Error '.$sql.
' - '.$this->db->error());
2718 $this->error = $this->db->error();
2722 dol_syslog(get_class($this).
'::setPaymentTerms, status of the object is incompatible');
2723 $this->error =
'Status of the object is incompatible '.$this->statut;
2736 dol_syslog(get_class($this).
'::setTransportMode('.$id.
')');
2737 if ($this->
statut >= 0 || $this->element ==
'societe') {
2738 $fieldname =
'fk_transport_mode';
2739 if ($this->element ==
'societe') {
2740 $fieldname =
'transport_mode';
2742 if (get_class($this) ==
'Fournisseur') {
2743 $fieldname =
'transport_mode_supplier';
2746 $sql =
'UPDATE '.$this->db->prefix().$this->table_element;
2747 $sql .=
" SET ".$fieldname.
" = ".(($id > 0 || $id ==
'0') ? ((
int) $id) :
'NULL');
2748 $sql .=
' WHERE rowid='.((int) $this->
id);
2750 if ($this->db->query($sql)) {
2751 $this->transport_mode_id = $id;
2753 if (get_class($this) ==
'Fournisseur') {
2754 $this->transport_mode_supplier_id = $id;
2758 dol_syslog(get_class($this).
'::setTransportMode Error '.$sql.
' - '.$this->db->error());
2759 $this->error = $this->db->error();
2763 dol_syslog(get_class($this).
'::setTransportMode, status of the object is incompatible');
2764 $this->error =
'Status of the object is incompatible '.$this->statut;
2777 dol_syslog(get_class($this).
'::setRetainedWarrantyPaymentTerms('.$id.
')');
2778 if ($this->
statut >= 0 || $this->element ==
'societe') {
2779 $fieldname =
'retained_warranty_fk_cond_reglement';
2781 $sql =
'UPDATE '.$this->db->prefix().$this->table_element;
2782 $sql .=
" SET ".$fieldname.
" = ".((int) $id);
2783 $sql .=
' WHERE rowid='.((int) $this->
id);
2785 if ($this->db->query($sql)) {
2786 $this->retained_warranty_fk_cond_reglement = $id;
2789 dol_syslog(get_class($this).
'::setRetainedWarrantyPaymentTerms Error '.$sql.
' - '.$this->db->error());
2790 $this->error = $this->db->error();
2794 dol_syslog(get_class($this).
'::setRetainedWarrantyPaymentTerms, status of the object is incompatible');
2795 $this->error =
'Status of the object is incompatible '.$this->statut;
2809 $fieldname =
'fk_delivery_address';
2810 if ($this->element ==
'delivery' || $this->element ==
'shipping') {
2811 $fieldname =
'fk_address';
2814 $sql =
"UPDATE ".$this->db->prefix().$this->table_element.
" SET ".$fieldname.
" = ".((int) $id);
2815 $sql .=
" WHERE rowid = ".((int) $this->
id).
" AND fk_statut = 0";
2817 if ($this->db->query($sql)) {
2818 $this->fk_delivery_address = $id;
2821 $this->error = $this->db->error();
2822 dol_syslog(get_class($this).
'::setDeliveryAddress Error '.$this->error);
2841 if (empty($userused)) {
2847 if (!$this->table_element) {
2848 dol_syslog(get_class($this).
"::setShippingMethod was called on objet with property table_element not defined", LOG_ERR);
2854 if ($shipping_method_id < 0) {
2855 $shipping_method_id =
'NULL';
2857 dol_syslog(get_class($this).
'::setShippingMethod('.$shipping_method_id.
')');
2859 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
2860 $sql .=
" SET fk_shipping_method = ".((int) $shipping_method_id);
2861 $sql .=
" WHERE rowid=".((int) $this->
id);
2862 $resql = $this->db->query($sql);
2864 dol_syslog(get_class($this).
'::setShippingMethod Error ', LOG_DEBUG);
2865 $this->error = $this->db->lasterror();
2870 $this->context = array(
'shippingmethodupdate'=>1);
2871 $result = $this->call_trigger(strtoupper(get_class($this)).
'_MODIFY', $userused);
2879 $this->db->rollback();
2882 $this->shipping_method_id = ($shipping_method_id ==
'NULL') ?
null:$shipping_method_id;
2883 $this->db->commit();
2897 if (!$this->table_element) {
2898 dol_syslog(get_class($this).
"::setWarehouse was called on objet with property table_element not defined", LOG_ERR);
2901 if ($warehouse_id < 0) {
2902 $warehouse_id =
'NULL';
2904 dol_syslog(get_class($this).
'::setWarehouse('.$warehouse_id.
')');
2906 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
2907 $sql .=
" SET fk_warehouse = ".((int) $warehouse_id);
2908 $sql .=
" WHERE rowid=".((int) $this->
id);
2910 if ($this->db->query($sql)) {
2911 $this->warehouse_id = ($warehouse_id ==
'NULL') ?
null:$warehouse_id;
2914 dol_syslog(get_class($this).
'::setWarehouse Error ', LOG_DEBUG);
2915 $this->error = $this->db->error();
2930 if (!$this->table_element) {
2931 dol_syslog(get_class($this).
"::setDocModel was called on objet with property table_element not defined", LOG_ERR);
2935 $newmodelpdf =
dol_trunc($modelpdf, 255);
2937 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
2938 $sql .=
" SET model_pdf = '".$this->db->escape($newmodelpdf).
"'";
2939 $sql .=
" WHERE rowid = ".((int) $this->
id);
2941 dol_syslog(get_class($this).
"::setDocModel", LOG_DEBUG);
2942 $resql = $this->db->query($sql);
2944 $this->model_pdf = $modelpdf;
2945 $this->modelpdf = $modelpdf;
2966 if (empty($userused)) {
2972 if (!$this->table_element) {
2973 dol_syslog(get_class($this).
"::setBankAccount was called on objet with property table_element not defined", LOG_ERR);
2978 if ($fk_account < 0) {
2979 $fk_account =
'NULL';
2981 dol_syslog(get_class($this).
'::setBankAccount('.$fk_account.
')');
2983 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
2984 $sql .=
" SET fk_account = ".((int) $fk_account);
2985 $sql .=
" WHERE rowid=".((int) $this->
id);
2987 $resql = $this->db->query($sql);
2989 dol_syslog(get_class($this).
'::setBankAccount Error '.$sql.
' - '.$this->db->error());
2990 $this->error = $this->db->lasterror();
2995 $this->context = array(
'bankaccountupdate'=>1);
2996 $result = $this->call_trigger(strtoupper(get_class($this)).
'_MODIFY', $userused);
3004 $this->db->rollback();
3007 $this->fk_account = ($fk_account ==
'NULL') ?
null:$fk_account;
3008 $this->db->commit();
3026 public function line_order($renum =
false, $rowidorder =
'ASC', $fk_parent_line =
true)
3029 if (!$this->table_element_line) {
3030 dol_syslog(get_class($this).
"::line_order was called on objet with property table_element_line not defined", LOG_ERR);
3033 if (!$this->fk_element) {
3034 dol_syslog(get_class($this).
"::line_order was called on objet with property fk_element not defined", LOG_ERR);
3038 $fieldposition =
'rang';
3039 if (in_array($this->table_element_line, array(
'bom_bomline',
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3040 $fieldposition =
'position';
3045 $sql =
"SELECT count(rowid) FROM ".$this->db->prefix().$this->table_element_line;
3046 $sql .=
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
3048 $sql .=
" AND " . $fieldposition .
" = 0";
3051 $sql .=
" AND " . $fieldposition .
" <> 0";
3054 dol_syslog(get_class($this).
"::line_order", LOG_DEBUG);
3055 $resql = $this->db->query($sql);
3057 $row = $this->db->fetch_row($resql);
3067 $sql =
"SELECT rowid FROM ".$this->db->prefix().$this->table_element_line;
3068 $sql .=
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
3069 if ($fk_parent_line) {
3070 $sql .=
' AND fk_parent_line IS NULL';
3072 $sql .=
" ORDER BY " . $fieldposition .
" ASC, rowid " . $rowidorder;
3074 dol_syslog(get_class($this).
"::line_order search all parent lines", LOG_DEBUG);
3075 $resql = $this->db->query($sql);
3078 $num = $this->db->num_rows($resql);
3080 $row = $this->db->fetch_row($resql);
3082 $childrens = $this->getChildrenOfLine($row[0]);
3083 if (!empty($childrens)) {
3084 foreach ($childrens as $child) {
3085 array_push($rows, $child);
3092 if (!empty($rows)) {
3093 foreach ($rows as $key => $row) {
3094 $this->updateRangOfLine($row, ($key + 1));
3113 $fieldposition =
'rang';
3114 if (in_array($this->table_element_line, array(
'bom_bomline',
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3115 $fieldposition =
'position';
3120 $sql =
"SELECT rowid FROM ".$this->db->prefix().$this->table_element_line;
3121 $sql .=
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
3122 $sql .=
' AND fk_parent_line = '.((int) $id);
3123 $sql .=
" ORDER BY " . $fieldposition .
" ASC";
3125 dol_syslog(get_class($this).
"::getChildrenOfLine search children lines for line ".$id, LOG_DEBUG);
3126 $resql = $this->db->query($sql);
3128 if ($this->db->num_rows($resql) > 0) {
3129 while ($row = $this->db->fetch_row($resql)) {
3131 if (!empty($includealltree)) {
3132 $rows = array_merge($rows, $this->getChildrenOfLine($row[0], $includealltree));
3148 public function line_up($rowid, $fk_parent_line =
true)
3151 $this->line_order(
false,
'ASC', $fk_parent_line);
3154 $rang = $this->getRangOfLine($rowid);
3157 $this->updateLineUp($rowid, $rang);
3171 $this->line_order(
false,
'ASC', $fk_parent_line);
3174 $rang = $this->getRangOfLine($rowid);
3177 $max = $this->line_max();
3180 $this->updateLineDown($rowid, $rang, $max);
3192 global $hookmanager;
3193 $fieldposition =
'rang';
3194 if (in_array($this->table_element_line, array(
'bom_bomline',
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3195 $fieldposition =
'position';
3198 $sql =
"UPDATE ".$this->db->prefix().$this->table_element_line.
" SET ".$fieldposition.
" = ".((int) $rang);
3199 $sql .=
' WHERE rowid = '.((int) $rowid);
3201 dol_syslog(get_class($this).
"::updateRangOfLine", LOG_DEBUG);
3202 if (!$this->db->query($sql)) {
3206 $parameters=array(
'rowid'=>$rowid,
'rang'=>$rang,
'fieldposition' => $fieldposition);
3208 $reshook = $hookmanager->executeHooks(
'afterRankOfLineUpdate', $parameters, $this, $action);
3223 $num = count($rows);
3224 for ($i = 0; $i < $num; $i++) {
3225 $this->updateRangOfLine($rows[$i], ($i + 1));
3239 $fieldposition =
'rang';
3240 if (in_array($this->table_element_line, array(
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3241 $fieldposition =
'position';
3244 $sql =
"UPDATE ".$this->db->prefix().$this->table_element_line.
" SET ".$fieldposition.
" = ".((int) $rang);
3245 $sql .=
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
3246 $sql .=
" AND " . $fieldposition .
" = " . ((int) ($rang - 1));
3247 if ($this->db->query($sql)) {
3248 $sql =
"UPDATE ".$this->db->prefix().$this->table_element_line.
" SET ".$fieldposition.
" = ".((int) ($rang - 1));
3249 $sql .=
' WHERE rowid = '.((int) $rowid);
3250 if (!$this->db->query($sql)) {
3270 $fieldposition =
'rang';
3271 if (in_array($this->table_element_line, array(
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3272 $fieldposition =
'position';
3275 $sql =
"UPDATE ".$this->db->prefix().$this->table_element_line.
" SET ".$fieldposition.
" = ".((int) $rang);
3276 $sql .=
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
3277 $sql .=
" AND " . $fieldposition .
" = " . ((int) ($rang + 1));
3278 if ($this->db->query($sql)) {
3279 $sql =
"UPDATE ".$this->db->prefix().$this->table_element_line.
" SET ".$fieldposition.
" = ".((int) ($rang + 1));
3280 $sql .=
' WHERE rowid = '.((int) $rowid);
3281 if (!$this->db->query($sql)) {
3298 $fieldposition =
'rang';
3299 if (in_array($this->table_element_line, array(
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3300 $fieldposition =
'position';
3303 $sql =
"SELECT " . $fieldposition .
" FROM ".$this->db->prefix().$this->table_element_line;
3304 $sql .=
" WHERE rowid = ".((int) $rowid);
3306 dol_syslog(get_class($this).
"::getRangOfLine", LOG_DEBUG);
3307 $resql = $this->db->query($sql);
3309 $row = $this->db->fetch_row($resql);
3324 $fieldposition =
'rang';
3325 if (in_array($this->table_element_line, array(
'ecm_files',
'emailcollector_emailcollectoraction',
'product_attribute_value'))) {
3326 $fieldposition =
'position';
3329 $sql =
"SELECT rowid FROM ".$this->db->prefix().$this->table_element_line;
3330 $sql .=
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
3331 $sql .=
" AND " . $fieldposition .
" = ".((int) $rang);
3332 $resql = $this->db->query($sql);
3334 $row = $this->db->fetch_row($resql);
3351 $positionfield =
'rang';
3352 if (in_array($this->table_element, array(
'bom_bom',
'product_attribute'))) {
3353 $positionfield =
'position';
3357 if ($fk_parent_line) {
3358 $sql =
"SELECT max(".$positionfield.
") FROM ".$this->db->prefix().$this->table_element_line;
3359 $sql .=
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
3360 $sql .=
" AND fk_parent_line = ".((int) $fk_parent_line);
3362 dol_syslog(get_class($this).
"::line_max", LOG_DEBUG);
3363 $resql = $this->db->query($sql);
3365 $row = $this->db->fetch_row($resql);
3366 if (!empty($row[0])) {
3369 return $this->getRangOfLine($fk_parent_line);
3374 $sql =
"SELECT max(".$positionfield.
") FROM ".$this->db->prefix().$this->table_element_line;
3375 $sql .=
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
3377 dol_syslog(get_class($this).
"::line_max", LOG_DEBUG);
3378 $resql = $this->db->query($sql);
3380 $row = $this->db->fetch_row($resql);
3398 if (!$this->table_element) {
3399 dol_syslog(get_class($this).
"::update_ref_ext was called on objet with property table_element not defined", LOG_ERR);
3403 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
3404 $sql .=
" SET ref_ext = '".$this->db->escape($ref_ext).
"'";
3405 $sql .=
" WHERE ".(isset($this->table_rowid) ? $this->table_rowid :
'rowid').
" = ".((
int) $this->id);
3407 dol_syslog(get_class($this).
"::update_ref_ext", LOG_DEBUG);
3408 if ($this->db->query($sql)) {
3409 $this->ref_ext = $ref_ext;
3412 $this->error = $this->db->error();
3431 if (!$this->table_element) {
3432 $this->error =
'update_note was called on objet with property table_element not defined';
3433 dol_syslog(get_class($this).
"::update_note was called on objet with property table_element not defined", LOG_ERR);
3436 if (!in_array($suffix, array(
'',
'_public',
'_private'))) {
3437 $this->error =
'update_note Parameter suffix must be empty, \'_private\' or \'_public\'';
3438 dol_syslog(get_class($this).
"::update_note Parameter suffix must be empty, '_private' or '_public'", LOG_ERR);
3442 $newsuffix = $suffix;
3445 if ($this->table_element ==
'product' && $newsuffix ==
'_private') {
3448 if (in_array($this->table_element, array(
'actioncomm',
'adherent',
'advtargetemailing',
'cronjob',
'establishment'))) {
3449 $fieldusermod =
"fk_user_mod";
3450 } elseif ($this->table_element ==
'ecm_files') {
3451 $fieldusermod =
"fk_user_m";
3453 $fieldusermod =
"fk_user_modif";
3455 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
3456 $sql .=
" SET note".$newsuffix.
" = ".(!empty($note) ? (
"'".$this->db->escape($note).
"'") :
"NULL");
3457 $sql .=
", ".$fieldusermod.
" = ".((int) $user->id);
3458 $sql .=
" WHERE rowid = ".((int) $this->
id);
3460 dol_syslog(get_class($this).
"::update_note", LOG_DEBUG);
3461 if ($this->db->query($sql)) {
3462 if ($suffix ==
'_public') {
3463 $this->note_public = $note;
3464 } elseif ($suffix ==
'_private') {
3465 $this->note_private = $note;
3467 $this->note = $note;
3468 $this->note_private = $note;
3470 if (empty($notrigger)) {
3471 switch ($this->element) {
3473 $trigger_name =
'COMPANY_MODIFY';
3476 $trigger_name =
'ORDER_MODIFY';
3479 $trigger_name =
'BILL_MODIFY';
3481 case 'invoice_supplier':
3482 $trigger_name =
'BILL_SUPPLIER_MODIFY';
3485 $trigger_name =
'BILLREC_MODIFIY';
3487 case 'expensereport':
3488 $trigger_name =
'EXPENSE_REPORT_MODIFY';
3491 $trigger_name = strtoupper($this->element) .
'_MODIFY';
3493 $ret = $this->call_trigger($trigger_name, $user);
3500 $this->error = $this->db->lasterror();
3517 return $this->update_note($note,
'_public');
3531 public function update_price($exclspec = 0, $roundingadjust =
'none', $nodatabaseupdate = 0, $seller =
null)
3534 global $conf, $hookmanager, $action;
3536 $parameters = array(
'exclspec' => $exclspec,
'roundingadjust' => $roundingadjust,
'nodatabaseupdate' => $nodatabaseupdate,
'seller' => $seller);
3537 $reshook = $hookmanager->executeHooks(
'updateTotalPrice', $parameters, $this, $action);
3540 } elseif ($reshook < 0) {
3546 if ($this->element ==
'propal') {
3547 $MODULE =
"MODULE_DISALLOW_UPDATE_PRICE_PROPOSAL";
3548 } elseif ($this->element ==
'commande' || $this->element ==
'order') {
3549 $MODULE =
"MODULE_DISALLOW_UPDATE_PRICE_ORDER";
3550 } elseif ($this->element ==
'facture' || $this->element ==
'invoice') {
3551 $MODULE =
"MODULE_DISALLOW_UPDATE_PRICE_INVOICE";
3552 } elseif ($this->element ==
'facture_fourn' || $this->element ==
'supplier_invoice' || $this->element ==
'invoice_supplier' || $this->element ==
'invoice_supplier_rec') {
3553 $MODULE =
"MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_INVOICE";
3554 } elseif ($this->element ==
'order_supplier' || $this->element ==
'supplier_order') {
3555 $MODULE =
"MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_ORDER";
3556 } elseif ($this->element ==
'supplier_proposal') {
3557 $MODULE =
"MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_PROPOSAL";
3560 if (!empty($MODULE)) {
3561 if (!empty($conf->global->$MODULE)) {
3562 $modsactivated = explode(
',', $conf->global->$MODULE);
3563 foreach ($modsactivated as $mod) {
3564 if (isModEnabled($mod)) {
3571 include_once DOL_DOCUMENT_ROOT.
'/core/lib/price.lib.php';
3573 $forcedroundingmode = $roundingadjust;
3574 if ($forcedroundingmode ==
'auto' && isset($conf->global->MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND)) {
3576 } elseif ($forcedroundingmode ==
'auto') {
3577 $forcedroundingmode =
'0';
3582 $multicurrency_tx = !empty($this->multicurrency_tx) ? $this->multicurrency_tx : 1;
3585 $fieldtva =
'total_tva';
3586 $fieldlocaltax1 =
'total_localtax1';
3587 $fieldlocaltax2 =
'total_localtax2';
3588 $fieldup =
'subprice';
3589 if ($this->element ==
'facture_fourn' || $this->element ==
'invoice_supplier') {
3593 if ($this->element ==
'invoice_supplier_rec') {
3596 if ($this->element ==
'expensereport') {
3597 $fieldup =
'value_unit';
3600 $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,";
3601 $sql .=
' tva_tx as vatrate, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type, info_bits, product_type';
3602 if ($this->table_element_line ==
'facturedet') {
3603 $sql .=
', situation_percent';
3605 $sql .=
', multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc';
3606 $sql .=
" FROM ".$this->db->prefix().$this->table_element_line;
3607 $sql .=
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
3609 $product_field =
'product_type';
3610 if ($this->table_element_line ==
'contratdet') {
3611 $product_field =
'';
3613 if ($product_field) {
3614 $sql .=
" AND ".$product_field.
" <> 9";
3617 $sql .=
' ORDER by rowid';
3619 dol_syslog(get_class($this).
"::update_price", LOG_DEBUG);
3621 $resql = $this->db->query($sql);
3623 $this->total_ht = 0;
3624 $this->total_tva = 0;
3625 $this->total_localtax1 = 0;
3626 $this->total_localtax2 = 0;
3627 $this->total_ttc = 0;
3628 $total_ht_by_vats = array();
3629 $total_tva_by_vats = array();
3630 $total_ttc_by_vats = array();
3631 $this->multicurrency_total_ht = 0;
3632 $this->multicurrency_total_tva = 0;
3633 $this->multicurrency_total_ttc = 0;
3637 $num = $this->db->num_rows($resql);
3640 $obj = $this->db->fetch_object($resql);
3643 $parameters = array(
'fk_element' => $obj->rowid);
3644 $reshook = $hookmanager->executeHooks(
'changeRoundingMode', $parameters, $this, $action);
3646 if (empty($reshook) && $forcedroundingmode ==
'0') {
3648 $localtax_array = array($obj->localtax1_type, $obj->localtax1_tx, $obj->localtax2_type, $obj->localtax2_tx);
3649 $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);
3651 $diff_when_using_price_ht =
price2num($tmpcal[1] - $obj->total_tva,
'MT', 1);
3652 $diff_on_current_total =
price2num($obj->total_ttc - $obj->total_ht - $obj->total_tva - $obj->total_localtax1 - $obj->total_localtax2,
'MT', 1);
3656 if ($diff_on_current_total) {
3658 $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);
3659 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);
3660 $resqlfix = $this->db->query($sqlfix);
3664 $obj->total_tva = $tmpcal[1];
3665 $obj->total_ttc = $tmpcal[2];
3666 } elseif ($diff_when_using_price_ht && $roundingadjust ==
'0') {
3669 $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);
3670 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);
3671 $resqlfix = $this->db->query($sqlfix);
3675 $obj->total_tva = $tmpcal[1];
3676 $obj->total_ttc = $tmpcal[2];
3680 $this->total_ht += $obj->total_ht;
3681 $this->total_tva += $obj->total_tva;
3682 $this->total_localtax1 += $obj->total_localtax1;
3683 $this->total_localtax2 += $obj->total_localtax2;
3684 $this->total_ttc += $obj->total_ttc;
3685 $this->multicurrency_total_ht += $obj->multicurrency_total_ht;
3686 $this->multicurrency_total_tva += $obj->multicurrency_total_tva;
3687 $this->multicurrency_total_ttc += $obj->multicurrency_total_ttc;
3689 if (!isset($total_ht_by_vats[$obj->vatrate])) {
3690 $total_ht_by_vats[$obj->vatrate] = 0;
3692 if (!isset($total_tva_by_vats[$obj->vatrate])) {
3693 $total_tva_by_vats[$obj->vatrate] = 0;
3695 if (!isset($total_ttc_by_vats[$obj->vatrate])) {
3696 $total_ttc_by_vats[$obj->vatrate] = 0;
3698 $total_ht_by_vats[$obj->vatrate] += $obj->total_ht;
3699 $total_tva_by_vats[$obj->vatrate] += $obj->total_tva;
3700 $total_ttc_by_vats[$obj->vatrate] += $obj->total_ttc;
3702 if ($forcedroundingmode ==
'1') {
3703 $tmpvat =
price2num($total_ht_by_vats[$obj->vatrate] * $obj->vatrate / 100,
'MT', 1);
3704 $diff =
price2num($total_tva_by_vats[$obj->vatrate] - $tmpvat,
'MT', 1);
3707 if (abs($diff) > (10 * pow(10, -1 *
getDolGlobalInt(
'MAIN_MAX_DECIMALS_TOT', 0)))) {
3709 $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.';
3711 $this->error = $errmsg;
3715 $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);
3716 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);
3718 $resqlfix = $this->db->query($sqlfix);
3724 $this->total_tva = (float)
price2num($this->total_tva - $diff,
'', 1);
3725 $this->total_ttc = (float)
price2num($this->total_ttc - $diff,
'', 1);
3726 $total_tva_by_vats[$obj->vatrate] = (float)
price2num($total_tva_by_vats[$obj->vatrate] - $diff,
'', 1);
3727 $total_ttc_by_vats[$obj->vatrate] = (float)
price2num($total_ttc_by_vats[$obj->vatrate] - $diff,
'', 1);
3735 $this->total_ttc += isset($this->revenuestamp) ? $this->revenuestamp : 0;
3736 $this->multicurrency_total_ttc += isset($this->revenuestamp) ? ($this->revenuestamp * $multicurrency_tx) : 0;
3739 if (!empty($this->situation_cycle_ref) && $this->situation_counter > 1 && method_exists($this,
'get_prev_sits') && $this->
type != $this::TYPE_CREDIT_NOTE) {
3740 $prev_sits = $this->get_prev_sits();
3742 foreach ($prev_sits as $sit) {
3743 $this->total_ht -= $sit->total_ht;
3744 $this->total_tva -= $sit->total_tva;
3745 $this->total_localtax1 -= $sit->total_localtax1;
3746 $this->total_localtax2 -= $sit->total_localtax2;
3747 $this->total_ttc -= $sit->total_ttc;
3748 $this->multicurrency_total_ht -= $sit->multicurrency_total_ht;
3749 $this->multicurrency_total_tva -= $sit->multicurrency_total_tva;
3750 $this->multicurrency_total_ttc -= $sit->multicurrency_total_ttc;
3755 $this->total_ht = (float)
price2num($this->total_ht);
3756 $this->total_tva = (float)
price2num($this->total_tva);
3757 $this->total_localtax1 = (float)
price2num($this->total_localtax1);
3758 $this->total_localtax2 = (float)
price2num($this->total_localtax2);
3759 $this->total_ttc = (float)
price2num($this->total_ttc);
3761 $this->db->free($resql);
3764 $fieldht =
'total_ht';
3766 $fieldlocaltax1 =
'localtax1';
3767 $fieldlocaltax2 =
'localtax2';
3768 $fieldttc =
'total_ttc';
3770 if (in_array($this->element, array(
'propal',
'commande',
'facture',
'facturerec',
'supplier_proposal',
'order_supplier',
'facture_fourn',
'invoice_supplier',
'invoice_supplier_rec',
'expensereport'))) {
3771 $fieldtva =
'total_tva';
3774 if (!$error && empty($nodatabaseupdate)) {
3775 $sql =
"UPDATE ".$this->db->prefix().$this->table_element.
' SET';
3776 $sql .=
" ".$fieldht.
" = ".((float)
price2num($this->total_ht,
'MT', 1)).
",";
3777 $sql .=
" ".$fieldtva.
" = ".((float)
price2num($this->total_tva,
'MT', 1)).
",";
3778 $sql .=
" ".$fieldlocaltax1.
" = ".((float)
price2num($this->total_localtax1,
'MT', 1)).
",";
3779 $sql .=
" ".$fieldlocaltax2.
" = ".((float)
price2num($this->total_localtax2,
'MT', 1)).
",";
3780 $sql .=
" ".$fieldttc.
" = ".((float)
price2num($this->total_ttc,
'MT', 1));
3781 $sql .=
", multicurrency_total_ht = ".((float)
price2num($this->multicurrency_total_ht,
'MT', 1));
3782 $sql .=
", multicurrency_total_tva = ".((float)
price2num($this->multicurrency_total_tva,
'MT', 1));
3783 $sql .=
", multicurrency_total_ttc = ".((float)
price2num($this->multicurrency_total_ttc,
'MT', 1));
3784 $sql .=
" WHERE rowid = ".((int) $this->
id);
3786 dol_syslog(get_class($this).
"::update_price", LOG_DEBUG);
3787 $resql = $this->db->query($sql);
3791 $this->error = $this->db->lasterror();
3792 $this->errors[] = $this->db->lasterror();
3797 $this->db->commit();
3800 $this->db->rollback();
3820 public function add_object_linked($origin =
null, $origin_id =
null, $f_user =
null, $notrigger = 0)
3823 global $user, $hookmanager, $action;
3824 $origin = (!empty($origin) ? $origin : $this->origin);
3825 $origin_id = (!empty($origin_id) ? $origin_id : $this->origin_id);
3826 $f_user = isset($f_user) ? $f_user : $user;
3829 if ($origin ==
'order') {
3830 $origin =
'commande';
3832 if ($origin ==
'invoice') {
3833 $origin =
'facture';
3835 if ($origin ==
'invoice_template') {
3836 $origin =
'facturerec';
3838 if ($origin ==
'supplierorder') {
3839 $origin =
'order_supplier';
3844 $coremodule = array(
'knowledgemanagement',
'partnership',
'workstation',
'ticket',
'recruitment',
'eventorganization',
'asset');
3846 $targettype = ((!empty($this->module) && ! in_array($this->module, $coremodule)) ? $this->module.
'_' :
'').$this->element;
3848 $parameters = array(
'targettype'=>$targettype);
3850 $reshook = $hookmanager->executeHooks(
'setLinkedObjectSourceTargetType', $parameters, $this, $action);
3852 if (!empty($hookmanager->resArray[
'targettype'])) $targettype = $hookmanager->resArray[
'targettype'];
3858 $sql =
"INSERT INTO " . $this->db->prefix() .
"element_element (";
3859 $sql .=
"fk_source";
3860 $sql .=
", sourcetype";
3861 $sql .=
", fk_target";
3862 $sql .=
", targettype";
3863 $sql .=
") VALUES (";
3864 $sql .= ((int) $origin_id);
3865 $sql .=
", '" . $this->db->escape($origin) .
"'";
3866 $sql .=
", " . ((int) $this->
id);
3867 $sql .=
", '" . $this->db->escape($targettype) .
"'";
3870 dol_syslog(get_class($this) .
"::add_object_linked", LOG_DEBUG);
3871 if ($this->db->query($sql)) {
3874 $this->context[
'link_origin'] = $origin;
3875 $this->context[
'link_origin_id'] = $origin_id;
3876 $result = $this->call_trigger(
'OBJECT_LINK_INSERT', $f_user);
3883 $this->error = $this->db->lasterror();
3888 $this->db->commit();
3891 $this->db->rollback();
3918 public function fetchObjectLinked($sourceid =
null, $sourcetype =
'', $targetid =
null, $targettype =
'', $clause =
'OR', $alsosametype = 1, $orderby =
'sourcetype', $loadalsoobjects = 1)
3920 global $conf, $hookmanager, $action;
3924 if ($this->
id > 0 && !empty($this->linkedObjectsFullLoaded[$this->
id])) {
3928 $this->linkedObjectsIds = array();
3929 $this->linkedObjects = array();
3931 $justsource =
false;
3932 $justtarget =
false;
3933 $withtargettype =
false;
3934 $withsourcetype =
false;
3936 $parameters = array(
'sourcetype'=>$sourcetype,
'sourceid'=>$sourceid,
'targettype'=>$targettype,
'targetid'=>$targetid);
3938 $reshook = $hookmanager->executeHooks(
'setLinkedObjectSourceTargetType', $parameters, $this, $action);
3940 if (!empty($hookmanager->resArray[
'sourcetype'])) $sourcetype = $hookmanager->resArray[
'sourcetype'];
3941 if (!empty($hookmanager->resArray[
'sourceid'])) $sourceid = $hookmanager->resArray[
'sourceid'];
3942 if (!empty($hookmanager->resArray[
'targettype'])) $targettype = $hookmanager->resArray[
'targettype'];
3943 if (!empty($hookmanager->resArray[
'targetid'])) $targetid = $hookmanager->resArray[
'targetid'];
3946 if (!empty($sourceid) && !empty($sourcetype) && empty($targetid)) {
3948 if (!empty($targettype)) {
3949 $withtargettype =
true;
3952 if (!empty($targetid) && !empty($targettype) && empty($sourceid)) {
3954 if (!empty($sourcetype)) {
3955 $withsourcetype =
true;
3959 $sourceid = (!empty($sourceid) ? $sourceid : $this->id);
3960 $targetid = (!empty($targetid) ? $targetid : $this->id);
3961 $sourcetype = (!empty($sourcetype) ? $sourcetype : $this->element);
3962 $targettype = (!empty($targettype) ? $targettype : $this->element);
3971 $sql =
"SELECT rowid, fk_source, sourcetype, fk_target, targettype";
3972 $sql .=
" FROM ".$this->db->prefix().
"element_element";
3974 if ($justsource || $justtarget) {
3976 $sql .=
"fk_source = ".((int) $sourceid).
" AND sourcetype = '".$this->db->escape($sourcetype).
"'";
3977 if ($withtargettype) {
3978 $sql .=
" AND targettype = '".$this->db->escape($targettype).
"'";
3980 } elseif ($justtarget) {
3981 $sql .=
"fk_target = ".((int) $targetid).
" AND targettype = '".$this->db->escape($targettype).
"'";
3982 if ($withsourcetype) {
3983 $sql .=
" AND sourcetype = '".$this->db->escape($sourcetype).
"'";
3987 $sql .=
"(fk_source = ".((int) $sourceid).
" AND sourcetype = '".$this->db->escape($sourcetype).
"')";
3988 $sql .=
" ".$clause.
" (fk_target = ".((int) $targetid).
" AND targettype = '".$this->db->escape($targettype).
"')";
3989 if ($loadalsoobjects && $this->
id > 0 && $sourceid == $this->
id && $sourcetype == $this->element && $targetid == $this->
id && $targettype == $this->element && $clause ==
'OR') {
3990 $this->linkedObjectsFullLoaded[$this->id] =
true;
3993 $sql .=
" ORDER BY ".$orderby;
3995 dol_syslog(get_class($this).
"::fetchObjectLink", LOG_DEBUG);
3996 $resql = $this->db->query($sql);
3998 $num = $this->db->num_rows($resql);
4001 $obj = $this->db->fetch_object($resql);
4002 if ($justsource || $justtarget) {
4004 $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
4005 } elseif ($justtarget) {
4006 $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
4009 if ($obj->fk_source == $sourceid && $obj->sourcetype == $sourcetype) {
4010 $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
4012 if ($obj->fk_target == $targetid && $obj->targettype == $targettype) {
4013 $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
4019 if (!empty($this->linkedObjectsIds)) {
4020 $tmparray = $this->linkedObjectsIds;
4021 foreach ($tmparray as $objecttype => $objectids) {
4023 $module = $element = $subelement = $objecttype;
4025 if ($objecttype !=
'supplier_proposal' && $objecttype !=
'order_supplier' && $objecttype !=
'invoice_supplier'
4026 && preg_match(
'/^([^_]+)_([^_]+)/i', $objecttype, $regs)) {
4027 $module = $element = $regs[1];
4028 $subelement = $regs[2];
4031 $classpath = $element.
'/class';
4033 if ($objecttype ==
'facture') {
4034 $classpath =
'compta/facture/class';
4035 } elseif ($objecttype ==
'facturerec') {
4036 $classpath =
'compta/facture/class';
4037 $module =
'facture';
4038 } elseif ($objecttype ==
'propal') {
4039 $classpath =
'comm/propal/class';
4040 } elseif ($objecttype ==
'supplier_proposal') {
4041 $classpath =
'supplier_proposal/class';
4042 } elseif ($objecttype ==
'shipping') {
4043 $classpath =
'expedition/class';
4044 $subelement =
'expedition';
4045 $module =
'expedition';
4046 } elseif ($objecttype ==
'delivery') {
4047 $classpath =
'delivery/class';
4048 $subelement =
'delivery';
4049 $module =
'delivery_note';
4050 } elseif ($objecttype ==
'invoice_supplier' || $objecttype ==
'order_supplier') {
4051 $classpath =
'fourn/class';
4052 $module =
'fournisseur';
4053 } elseif ($objecttype ==
'fichinter') {
4054 $classpath =
'fichinter/class';
4055 $subelement =
'fichinter';
4056 $module =
'ficheinter';
4057 } elseif ($objecttype ==
'subscription') {
4058 $classpath =
'adherents/class';
4059 $module =
'adherent';
4060 } elseif ($objecttype ==
'contact') {
4061 $module =
'societe';
4062 } elseif ($objecttype ==
'action') {
4064 $subelement =
'actionComm';
4068 $classfile = strtolower($subelement);
4069 $classname = ucfirst($subelement);
4071 if ($objecttype ==
'order') {
4072 $classfile =
'commande';
4073 $classname =
'Commande';
4074 } elseif ($objecttype ==
'invoice_supplier') {
4075 $classfile =
'fournisseur.facture';
4076 $classname =
'FactureFournisseur';
4077 } elseif ($objecttype ==
'order_supplier') {
4078 $classfile =
'fournisseur.commande';
4079 $classname =
'CommandeFournisseur';
4080 } elseif ($objecttype ==
'supplier_proposal') {
4081 $classfile =
'supplier_proposal';
4082 $classname =
'SupplierProposal';
4083 } elseif ($objecttype ==
'facturerec') {
4084 $classfile =
'facture-rec';
4085 $classname =
'FactureRec';
4086 } elseif ($objecttype ==
'subscription') {
4087 $classfile =
'subscription';
4088 $classname =
'Subscription';
4089 } elseif ($objecttype ==
'project' || $objecttype ==
'projet') {
4090 $classpath =
'projet/class';
4091 $classfile =
'project';
4092 $classname =
'Project';
4093 } elseif ($objecttype ==
'conferenceorboothattendee') {
4094 $classpath =
'eventorganization/class';
4095 $classfile =
'conferenceorboothattendee';
4096 $classname =
'ConferenceOrBoothAttendee';
4097 $module =
'eventorganization';
4098 } elseif ($objecttype ==
'conferenceorbooth') {
4099 $classpath =
'eventorganization/class';
4100 $classfile =
'conferenceorbooth';
4101 $classname =
'ConferenceOrBooth';
4102 $module =
'eventorganization';
4103 } elseif ($objecttype ==
'mo') {
4104 $classpath =
'mrp/class';
4111 if (isModEnabled($module) && (($element != $this->element) || $alsosametype)) {
4112 if ($loadalsoobjects && (is_numeric($loadalsoobjects) || ($loadalsoobjects === $objecttype))) {
4115 if (class_exists($classname)) {
4116 foreach ($objectids as $i => $objectid) {
4117 $object =
new $classname($this->db);
4118 $ret = $object->fetch($objectid);
4120 $this->linkedObjects[$objecttype][$i] = $object;
4126 unset($this->linkedObjectsIds[$objecttype]);
4145 if ($this->
id > 0 && !empty($this->linkedObjectsFullLoaded[$this->
id])) {
4146 unset($this->linkedObjectsFullLoaded[$this->
id]);
4164 public function updateObjectLinked($sourceid =
null, $sourcetype =
'', $targetid =
null, $targettype =
'', $f_user =
null, $notrigger = 0)
4167 $updatesource =
false;
4168 $updatetarget =
false;
4169 $f_user = isset($f_user) ? $f_user : $user;
4171 if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) {
4172 $updatesource =
true;
4173 } elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) {
4174 $updatetarget =
true;
4180 $sql =
"UPDATE " . $this->db->prefix() .
"element_element SET ";
4181 if ($updatesource) {
4182 $sql .=
"fk_source = " . ((int) $sourceid);
4183 $sql .=
", sourcetype = '" . $this->db->escape($sourcetype) .
"'";
4184 $sql .=
" WHERE fk_target = " . ((int) $this->
id);
4185 $sql .=
" AND targettype = '" . $this->db->escape($this->element) .
"'";
4186 } elseif ($updatetarget) {
4187 $sql .=
"fk_target = " . ((int) $targetid);
4188 $sql .=
", targettype = '" . $this->db->escape($targettype) .
"'";
4189 $sql .=
" WHERE fk_source = " . ((int) $this->
id);
4190 $sql .=
" AND sourcetype = '" . $this->db->escape($this->element) .
"'";
4193 dol_syslog(get_class($this) .
"::updateObjectLinked", LOG_DEBUG);
4194 if ($this->db->query($sql)) {
4197 $this->context[
'link_source_id'] = $sourceid;
4198 $this->context[
'link_source_type'] = $sourcetype;
4199 $this->context[
'link_target_id'] = $targetid;
4200 $this->context[
'link_target_type'] = $targettype;
4201 $result = $this->call_trigger(
'OBJECT_LINK_MODIFY', $f_user);
4208 $this->error = $this->db->lasterror();
4213 $this->db->commit();
4216 $this->db->rollback();
4234 public function deleteObjectLinked($sourceid =
null, $sourcetype =
'', $targetid =
null, $targettype =
'', $rowid =
'', $f_user =
null, $notrigger = 0)
4237 $deletesource =
false;
4238 $deletetarget =
false;
4239 $f_user = isset($f_user) ? $f_user : $user;
4241 if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) {
4242 $deletesource =
true;
4243 } elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) {
4244 $deletetarget =
true;
4247 $sourceid = (!empty($sourceid) ? $sourceid : $this->id);
4248 $sourcetype = (!empty($sourcetype) ? $sourcetype : $this->element);
4249 $targetid = (!empty($targetid) ? $targetid : $this->id);
4250 $targettype = (!empty($targettype) ? $targettype : $this->element);
4256 $this->context[
'link_id'] = $rowid;
4257 $this->context[
'link_source_id'] = $sourceid;
4258 $this->context[
'link_source_type'] = $sourcetype;
4259 $this->context[
'link_target_id'] = $targetid;
4260 $this->context[
'link_target_type'] = $targettype;
4261 $result = $this->call_trigger(
'OBJECT_LINK_DELETE', $f_user);
4269 $sql =
"DELETE FROM " . $this->db->prefix() .
"element_element";
4272 $sql .=
" rowid = " . ((int) $rowid);
4274 if ($deletesource) {
4275 $sql .=
" fk_source = " . ((int) $sourceid) .
" AND sourcetype = '" . $this->db->escape($sourcetype) .
"'";
4276 $sql .=
" AND fk_target = " . ((int) $this->
id) .
" AND targettype = '" . $this->db->escape($this->element) .
"'";
4277 } elseif ($deletetarget) {
4278 $sql .=
" fk_target = " . ((int) $targetid) .
" AND targettype = '" . $this->db->escape($targettype) .
"'";
4279 $sql .=
" AND fk_source = " . ((int) $this->
id) .
" AND sourcetype = '" . $this->db->escape($this->element) .
"'";
4281 $sql .=
" (fk_source = " . ((int) $this->
id) .
" AND sourcetype = '" . $this->db->escape($this->element) .
"')";
4283 $sql .=
" (fk_target = " . ((int) $this->
id) .
" AND targettype = '" . $this->db->escape($this->element) .
"')";
4287 dol_syslog(get_class($this) .
"::deleteObjectLinked", LOG_DEBUG);
4288 if (!$this->db->query($sql)) {
4289 $this->error = $this->db->lasterror();
4290 $this->errors[] = $this->error;
4296 $this->db->commit();
4299 $this->db->rollback();
4315 if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
4321 $sql =
"SELECT ".$field_select.
" FROM ".$db->prefix().$table_element.
" WHERE ".$field_where.
" = ".((int) $fk_object_where);
4322 $resql = $db->query($sql);
4325 if (!empty($resql)) {
4326 while ($res = $db->fetch_object($resql)) {
4327 $TRes[] = $res->{$field_select};
4344 if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
4350 $sql =
"DELETE FROM ".$db->prefix().$table_element.
" WHERE ".$field_where.
" = ".((int) $fk_object_where);
4351 $resql = $db->query($sql);
4353 if (empty($resql)) {
4370 public function setStatut($status, $elementId =
null, $elementType =
'', $trigkey =
'', $fieldstatus =
'fk_statut')
4372 global $user, $langs, $conf;
4374 $savElementId = $elementId;
4376 $elementId = (!empty($elementId) ? $elementId : $this->id);
4377 $elementTable = (!empty($elementType) ? $elementType : $this->table_element);
4381 if ($elementTable ==
'facture_rec') {
4382 $fieldstatus =
"suspended";
4384 if ($elementTable ==
'mailing') {
4385 $fieldstatus =
"statut";
4387 if ($elementTable ==
'cronjob') {
4388 $fieldstatus =
"status";
4390 if ($elementTable ==
'user') {
4391 $fieldstatus =
"statut";
4393 if ($elementTable ==
'expensereport') {
4394 $fieldstatus =
"fk_statut";
4396 if ($elementTable ==
'commande_fournisseur_dispatch') {
4397 $fieldstatus =
"status";
4399 if (isset($this->fields) && is_array($this->fields) && array_key_exists(
'status', $this->fields)) {
4400 $fieldstatus =
'status';
4403 $sql =
"UPDATE ".$this->db->prefix().$elementTable;
4404 $sql .=
" SET ".$fieldstatus.
" = ".((int) $status);
4407 if ($status == 1 && in_array($elementTable, array(
'expensereport',
'inventory'))) {
4408 $sql .=
", fk_user_valid = ".((int) $user->id);
4410 if ($status == 1 && in_array($elementTable, array(
'expensereport'))) {
4411 $sql .=
", date_valid = '".$this->db->idate(
dol_now()).
"'";
4413 if ($status == 1 && in_array($elementTable, array(
'inventory'))) {
4414 $sql .=
", date_validation = '".$this->db->idate(
dol_now()).
"'";
4416 $sql .=
" WHERE rowid = ".((int) $elementId);
4417 $sql .=
" AND ".$fieldstatus.
" <> ".((int) $status);
4419 dol_syslog(get_class($this).
"::setStatut", LOG_DEBUG);
4420 $resql = $this->db->query($sql);
4424 $nb_rows_affected = $this->db->affected_rows($resql);
4426 if ($nb_rows_affected > 0) {
4427 if (empty($trigkey)) {
4429 if ($this->element ==
'supplier_proposal' && $status == 2) {
4430 $trigkey =
'SUPPLIER_PROPOSAL_SIGN';
4432 if ($this->element ==
'supplier_proposal' && $status == 3) {
4433 $trigkey =
'SUPPLIER_PROPOSAL_REFUSE';
4435 if ($this->element ==
'supplier_proposal' && $status == 4) {
4436 $trigkey =
'SUPPLIER_PROPOSAL_CLOSE';
4438 if ($this->element ==
'fichinter' && $status == 3) {
4439 $trigkey =
'FICHINTER_CLASSIFY_DONE';
4441 if ($this->element ==
'fichinter' && $status == 2) {
4442 $trigkey =
'FICHINTER_CLASSIFY_BILLED';
4444 if ($this->element ==
'fichinter' && $status == 1) {
4445 $trigkey =
'FICHINTER_CLASSIFY_UNBILLED';
4451 $result = $this->call_trigger($trigkey, $user);
4462 $this->db->commit();
4464 if (empty($savElementId)) {
4466 if ($fieldstatus ==
'tosell') {
4467 $this->status = $status;
4468 } elseif ($fieldstatus ==
'tobuy') {
4469 $this->status_buy = $status;
4472 $this->status = $status;
4478 $this->db->rollback();
4479 dol_syslog(get_class($this).
"::setStatut ".$this->error, LOG_ERR);
4483 $this->error = $this->db->lasterror();
4484 $this->db->rollback();
4501 if (empty($id) && empty($ref)) {
4504 if (!empty($conf->global->MAIN_DISABLE_CANVAS)) {
4511 $sql =
"SELECT rowid, canvas";
4512 $sql .=
" FROM ".$this->db->prefix().$this->table_element;
4513 $sql .=
" WHERE entity IN (".getEntity($this->element).
")";
4515 $sql .=
" AND rowid = ".((int) $id);
4518 $sql .=
" AND ref = '".$this->db->escape($ref).
"'";
4521 $resql = $this->db->query($sql);
4523 $obj = $this->db->fetch_object($resql);
4525 $this->canvas = $obj->canvas;
4545 $sql =
"SELECT special_code FROM ".$this->db->prefix().$this->table_element_line;
4546 $sql .=
" WHERE rowid = ".((int) $lineid);
4547 $resql = $this->db->query($sql);
4549 $row = $this->db->fetch_row($resql);
4550 return (!empty($row[0]) ? $row[0] : 0);
4573 if (!isset($this->childtables) || !is_array($this->childtables) || count($this->childtables) == 0) {
4574 dol_print_error(
'Called isObjectUsed on a class with property this->childtables not defined');
4578 $arraytoscan = $this->childtables;
4580 $tmparray = array_keys($this->childtables);
4581 if (is_numeric($tmparray[0])) {
4582 $arraytoscan = array_flip($this->childtables);
4587 foreach ($arraytoscan as $table => $element) {
4590 $sql =
"SELECT COUNT(*) as nb";
4591 $sql.=
" FROM ".$this->db->prefix().$table.
" as c";
4592 if (!empty($element[
'parent']) && !empty($element[
'parentkey'])) {
4593 $sql.=
", ".$this->db->prefix().$element[
'parent'].
" as p";
4595 if (!empty($element[
'fk_element'])) {
4596 $sql.=
" WHERE c.".$element[
'fk_element'].
" = ".((int) $id);
4598 $sql.=
" WHERE c.".$this->fk_element.
" = ".((int) $id);
4600 if (!empty($element[
'parent']) && !empty($element[
'parentkey'])) {
4601 $sql.=
" AND c.".$element[
'parentkey'].
" = p.rowid";
4603 if (!empty($element[
'parent']) && !empty($element[
'parenttypefield']) && !empty($element[
'parenttypevalue'])) {
4604 $sql.=
" AND c.".$element[
'parenttypefield'].
" = '".$this->db->escape($element[
'parenttypevalue']).
"'";
4606 if (!empty($entity)) {
4607 if (!empty($element[
'parent']) && !empty($element[
'parentkey'])) {
4608 $sql.=
" AND p.entity = ".((int) $entity);
4610 $sql.=
" AND c.entity = ".((int) $entity);
4614 $resql = $this->db->query($sql);
4616 $obj = $this->db->fetch_object($resql);
4618 $langs->load(
"errors");
4620 $haschild += $obj->nb;
4621 if (is_numeric($element)) {
4622 $this->errors[] = $langs->transnoentitiesnoconv(
"ErrorRecordHasAtLeastOneChildOfType", method_exists($this,
'getNomUrl') ? $this->getNomUrl() : $this->ref, $table);
4623 } elseif (is_string($element)) {
4624 $this->errors[] = $langs->transnoentitiesnoconv(
"ErrorRecordHasAtLeastOneChildOfType", method_exists($this,
'getNomUrl') ? $this->getNomUrl() : $this->ref, $langs->transnoentitiesnoconv($element));
4626 $this->errors[] = $langs->transnoentitiesnoconv(
"ErrorRecordHasAtLeastOneChildOfType", method_exists($this,
'getNomUrl') ? $this->getNomUrl() : $this->ref, $langs->transnoentitiesnoconv($element[
'name']));
4631 $this->errors[] = $this->db->lasterror();
4635 if ($haschild > 0) {
4636 $this->errors[] =
"ErrorRecordHasChildren";
4653 foreach ($this->lines as $key => $val) {
4655 if ($predefined == -1) {
4658 if ($predefined == 1 && $val->fk_product > 0) {
4661 if ($predefined == 0 && $val->fk_product <= 0) {
4664 if ($predefined == 2 && $val->fk_product > 0 && $val->product_type == 0) {
4667 if ($predefined == 3 && $val->fk_product > 0 && $val->product_type == 1) {
4674 dol_syslog(get_class($this).
'::hasProductsOrServices we found '.$nb.
' qualified lines of products/servcies');
4685 if (!empty($this->table_element_line) ) {
4686 $total_discount = 0.00;
4688 $sql =
"SELECT subprice as pu_ht, qty, remise_percent, total_ht";
4689 $sql .=
" FROM ".$this->db->prefix().$this->table_element_line;
4690 $sql .=
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
4692 dol_syslog(get_class($this).
'::getTotalDiscount', LOG_DEBUG);
4693 $resql = $this->db->query($sql);
4695 $num = $this->db->num_rows($resql);
4698 $obj = $this->db->fetch_object($resql);
4700 $pu_ht = $obj->pu_ht;
4702 $total_ht = $obj->total_ht;
4704 $total_discount_line = floatval(
price2num(($pu_ht * $qty) - $total_ht,
'MT'));
4705 $total_discount += $total_discount_line;
4734 foreach ($this->lines as $line) {
4735 if (isset($line->qty_asked)) {
4736 if (empty($totalOrdered)) {
4739 $totalOrdered += $line->qty_asked;
4741 if (isset($line->qty_shipped)) {
4742 if (empty($totalToShip)) {
4745 $totalToShip += $line->qty_shipped;
4746 } elseif ($line->element ==
'commandefournisseurdispatch' && isset($line->qty)) {
4747 if (empty($totalToShip)) {
4750 $totalToShip += $line->qty;
4754 if ($this->element ==
'shipping') {
4756 $qty = $line->qty_shipped ? $line->qty_shipped : 0;
4758 $qty = $line->qty ? $line->qty : 0;
4761 $weight = !empty($line->weight) ? $line->weight : 0;
4762 ($weight == 0 && !empty($line->product->weight)) ? $weight = $line->product->weight : 0;
4763 $volume = !empty($line->volume) ? $line->volume : 0;
4764 ($volume == 0 && !empty($line->product->volume)) ? $volume = $line->product->volume : 0;
4766 $weight_units = !empty($line->weight_units) ? $line->weight_units : 0;
4767 ($weight_units == 0 && !empty($line->product->weight_units)) ? $weight_units = $line->product->weight_units : 0;
4768 $volume_units = !empty($line->volume_units) ? $line->volume_units : 0;
4769 ($volume_units == 0 && !empty($line->product->volume_units)) ? $volume_units = $line->product->volume_units : 0;
4773 if (!empty($weight_units)) {
4774 $weightUnit = $weight_units;
4776 if (!empty($volume_units)) {
4777 $volumeUnit = $volume_units;
4780 if (empty($totalWeight)) {
4783 if (empty($totalVolume)) {
4788 if ($weight_units < 50) {
4789 $trueWeightUnit = pow(10, $weightUnit);
4790 $totalWeight += $weight * $qty * $trueWeightUnit;
4792 if ($weight_units == 99) {
4794 $trueWeightUnit = 0.45359237;
4795 $totalWeight += $weight * $qty * $trueWeightUnit;
4796 } elseif ($weight_units == 98) {
4798 $trueWeightUnit = 0.0283495;
4799 $totalWeight += $weight * $qty * $trueWeightUnit;
4801 $totalWeight += $weight * $qty;
4804 if ($volume_units < 50) {
4806 $trueVolumeUnit = pow(10, $volumeUnit);
4808 $totalVolume += $volume * $qty * $trueVolumeUnit;
4810 $totalVolume += $volume * $qty;
4814 return array(
'weight'=>$totalWeight,
'volume'=>$totalVolume,
'ordered'=>$totalOrdered,
'toship'=>$totalToShip);
4827 $extraparams = (!empty($this->extraparams) ? json_encode($this->extraparams) :
null);
4829 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
4830 $sql .=
" SET extraparams = ".(!empty($extraparams) ?
"'".$this->db->escape($extraparams).
"'" :
"null");
4831 $sql .=
" WHERE rowid = ".((int) $this->
id);
4833 dol_syslog(get_class($this).
"::setExtraParameters", LOG_DEBUG);
4834 $resql = $this->db->query($sql);
4836 $this->error = $this->db->lasterror();
4837 $this->db->rollback();
4840 $this->db->commit();
4863 global $conf, $user, $langs, $object, $hookmanager, $extrafields;
4867 if (!is_object($extrafields)) {
4868 require_once DOL_DOCUMENT_ROOT.
'/core/class/extrafields.class.php';
4871 $extrafields->fetch_name_optionals_label($this->table_element_line);
4876 $dirtpls = array_merge($conf->modules_parts[
'tpl'], array($defaulttpldir));
4877 foreach ($dirtpls as $module => $reldir) {
4878 if (!empty($module)) {
4881 $tpl = DOL_DOCUMENT_ROOT.$reldir.
'/objectline_create.tpl.php';
4884 if (empty($conf->file->strict_mode)) {
4885 $res = @include $tpl;
4887 $res = include $tpl;
4914 public function printObjectLines($action, $seller, $buyer, $selected = 0, $dateSelector = 0, $defaulttpldir =
'/core/tpl')
4916 global $conf, $hookmanager, $langs, $user, $form, $extrafields, $object;
4918 global $inputalsopricewithtax, $usemargins, $disableedit, $disablemove, $disableremove, $outputalsopricetotalwithtax;
4922 if (isModEnabled(
'margin') && !empty($this->element) && in_array($this->element, array(
'facture',
'facturerec',
'propal',
'commande'))) {
4926 $num = count($this->lines);
4929 if (!is_object($extrafields)) {
4930 require_once DOL_DOCUMENT_ROOT.
'/core/class/extrafields.class.php';
4933 $extrafields->fetch_name_optionals_label($this->table_element_line);
4935 $parameters = array(
'num'=>$num,
'dateSelector'=>$dateSelector,
'seller'=>$seller,
'buyer'=>$buyer,
'selected'=>$selected,
'table_element_line'=>$this->table_element_line);
4936 $reshook = $hookmanager->executeHooks(
'printObjectLineTitle', $parameters, $this, $action);
4937 if (empty($reshook)) {
4941 $dirtpls = array_merge($conf->modules_parts[
'tpl'], array($defaulttpldir));
4942 foreach ($dirtpls as $module => $reldir) {
4944 if (!empty($module)) {
4947 $tpl = DOL_DOCUMENT_ROOT.$reldir.
'/objectline_title.tpl.php';
4949 if (file_exists($tpl)) {
4950 if (empty($conf->file->strict_mode)) {
4951 $res = @include $tpl;
4953 $res = include $tpl;
4964 print
"<!-- begin printObjectLines() --><tbody>\n";
4965 foreach ($this->lines as $line) {
4967 $line->fetch_optionals();
4970 if (is_object($hookmanager)) {
4971 if (empty($line->fk_parent_line)) {
4972 $parameters = array(
'line'=>$line,
'num'=>$num,
'i'=>$i,
'dateSelector'=>$dateSelector,
'seller'=>$seller,
'buyer'=>$buyer,
'selected'=>$selected,
'table_element_line'=>$line->table_element,
'defaulttpldir'=>$defaulttpldir);
4973 $reshook = $hookmanager->executeHooks(
'printObjectLine', $parameters, $this, $action);
4975 $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);
4976 $reshook = $hookmanager->executeHooks(
'printObjectSubLine', $parameters, $this, $action);
4979 if (empty($reshook)) {
4980 $this->printObjectLine($action, $line,
'', $num, $i, $dateSelector, $seller, $buyer, $selected, $extrafields, $defaulttpldir);
4985 print
"</tbody><!-- end printObjectLines() -->\n";
5005 public function printObjectLine($action, $line, $var, $num, $i, $dateSelector, $seller, $buyer, $selected = 0, $extrafields =
null, $defaulttpldir =
'/core/tpl')
5007 global $conf, $langs, $user, $object, $hookmanager;
5009 global $object_rights, $disableedit, $disablemove, $disableremove;
5011 $object_rights = $this->getRights();
5017 if ($action !=
'editline' || $selected != $line->id) {
5019 if (!empty($line->fk_product) && $line->fk_product > 0) {
5020 $product_static =
new Product($this->db);
5021 $product_static->fetch($line->fk_product);
5023 $product_static->ref = $line->ref;
5024 $product_static->label = !empty($line->label) ? $line->label :
"";
5026 $text = $product_static->getNomUrl(1);
5030 if (property_exists($this,
'socid') && !is_object($this->thirdparty)) {
5031 dol_print_error(
'',
'Error: Method printObjectLine was called on an object and object->fetch_thirdparty was not done before');
5035 $prod =
new Product($this->db);
5036 $prod->fetch($line->fk_product);
5038 $outputlangs = $langs;
5040 if (empty($newlang) &&
GETPOST(
'lang_id',
'aZ09')) {
5041 $newlang =
GETPOST(
'lang_id',
'aZ09');
5043 if (!empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE) && empty($newlang) && is_object($this->thirdparty)) {
5044 $newlang = $this->thirdparty->default_lang;
5046 if (!empty($newlang)) {
5047 $outputlangs =
new Translate(
"", $conf);
5048 $outputlangs->setDefaultLang($newlang);
5051 $label = (!empty($prod->multilangs[$outputlangs->defaultlang][
"label"])) ? $prod->multilangs[$outputlangs->defaultlang][
"label"] : $line->product_label;
5053 $label = $line->product_label;
5056 $text .=
' - '.(!empty($line->label) ? $line->label : $label);
5057 $description .= (
getDolGlobalInt(
'PRODUIT_DESC_IN_FORM_ACCORDING_TO_DEVICE') ?
'' : (!empty($line->description) ?
dol_htmlentitiesbr($line->description) :
''));
5060 $line->pu_ttc =
price2num((!empty($line->subprice) ? $line->subprice : 0) * (1 + ((!empty($line->tva_tx) ? $line->tva_tx : 0) / 100)),
'MU');
5065 $dirtpls = array_merge($conf->modules_parts[
'tpl'], array($defaulttpldir));
5066 foreach ($dirtpls as $module => $reldir) {
5068 if (!empty($module)) {
5071 $tpl = DOL_DOCUMENT_ROOT.$reldir.
'/objectline_view.tpl.php';
5073 if (file_exists($tpl)) {
5074 if (empty($conf->file->strict_mode)) {
5075 $res = @include $tpl;
5077 $res = include $tpl;
5087 if ($this->
statut == 0 && $action ==
'editline' && $selected == $line->id) {
5088 $label = (!empty($line->label) ? $line->label : (($line->fk_product > 0) ? $line->product_label :
''));
5090 $line->pu_ttc =
price2num($line->subprice * (1 + ($line->tva_tx / 100)),
'MU');
5095 $dirtpls = array_merge($conf->modules_parts[
'tpl'], array($defaulttpldir));
5096 foreach ($dirtpls as $module => $reldir) {
5097 if (!empty($module)) {
5100 $tpl = DOL_DOCUMENT_ROOT.$reldir.
'/objectline_edit.tpl.php';
5103 if (empty($conf->file->strict_mode)) {
5104 $res = @include $tpl;
5106 $res = include $tpl;
5131 global $langs, $hookmanager, $conf, $form, $action;
5133 print
'<tr class="liste_titre">';
5134 print
'<td class="linecolref">'.$langs->trans(
'Ref').
'</td>';
5135 print
'<td class="linecoldescription">'.$langs->trans(
'Description').
'</td>';
5136 print
'<td class="linecolvat right">'.$langs->trans(
'VATRate').
'</td>';
5137 print
'<td class="linecoluht right">'.$langs->trans(
'PriceUHT').
'</td>';
5138 if (isModEnabled(
"multicurrency")) {
5139 print
'<td class="linecoluht_currency right">'.$langs->trans(
'PriceUHTCurrency').
'</td>';
5141 print
'<td class="linecolqty right">'.$langs->trans(
'Qty').
'</td>';
5143 print
'<td class="linecoluseunit left">'.$langs->trans(
'Unit').
'</td>';
5145 print
'<td class="linecoldiscount right">'.$langs->trans(
'ReductionShort').
'</td>';
5146 print
'<td class="linecolht right">'.$langs->trans(
'TotalHT').
'</td>';
5147 print
'<td class="center">'.$form->showCheckAddButtons(
'checkforselect', 1).
'</td>';
5151 if (!empty($this->lines)) {
5152 foreach ($this->lines as $line) {
5155 if (is_object($hookmanager)) {
5156 $parameters = array(
'line'=>$line,
'i'=>$i,
'restrictlist'=>$restrictlist,
'selectedLines'=> $selectedLines);
5157 if (!empty($line->fk_parent_line)) { $parameters[
'fk_parent_line'] = $line->fk_parent_line; }
5158 $reshook = $hookmanager->executeHooks(
'printOriginObjectLine', $parameters, $this, $action);
5160 if (empty($reshook)) {
5161 $this->printOriginLine($line,
'', $restrictlist,
'/core/tpl', $selectedLines);
5182 public function printOriginLine($line, $var, $restrictlist =
'', $defaulttpldir =
'/core/tpl', $selectedLines = array())
5184 global $langs, $conf;
5187 if (!empty($line->date_start)) {
5188 $date_start = $line->date_start;
5190 $date_start = $line->date_debut_prevue;
5191 if ($line->date_debut_reel) {
5192 $date_start = $line->date_debut_reel;
5195 if (!empty($line->date_end)) {
5196 $date_end = $line->date_end;
5198 $date_end = $line->date_fin_prevue;
5199 if ($line->date_fin_reel) {
5200 $date_end = $line->date_fin_reel;
5204 $this->tpl[
'id'] = $line->id;
5206 $this->tpl[
'label'] =
'';
5207 if (!empty($line->fk_parent_line)) {
5208 $this->tpl[
'label'] .=
img_picto(
'',
'rightarrow');
5211 if (($line->info_bits & 2) == 2) {
5213 $discount->fk_soc = $this->socid;
5214 $this->tpl[
'label'] .= $discount->getNomUrl(0,
'discount');
5215 } elseif (!empty($line->fk_product)) {
5216 $productstatic =
new Product($this->db);
5217 $productstatic->id = $line->fk_product;
5218 $productstatic->ref = $line->ref;
5219 $productstatic->type = $line->fk_product_type;
5220 if (empty($productstatic->ref)) {
5221 $line->fetch_product();
5222 $productstatic = $line->product;
5225 $this->tpl[
'label'] .= $productstatic->getNomUrl(1);
5226 $this->tpl[
'label'] .=
' - '.(!empty($line->label) ? $line->label : $line->product_label);
5228 if ($line->product_type == 1 && ($date_start || $date_end)) {
5232 $this->tpl[
'label'] .= ($line->product_type == -1 ?
' ' : ($line->product_type == 1 ?
img_object($langs->trans(
''),
'service') :
img_object($langs->trans(
''),
'product')));
5233 if (!empty($line->desc)) {
5234 $this->tpl[
'label'] .= $line->desc;
5236 $this->tpl[
'label'] .= ($line->label ?
' '.$line->label :
'');
5240 if ($line->product_type == 1 && ($date_start || $date_end)) {
5245 if (!empty($line->desc)) {
5246 if ($line->desc ==
'(CREDIT_NOTE)') {
5248 $discount->fetch($line->fk_remise_except);
5249 $this->tpl[
'description'] = $langs->transnoentities(
"DiscountFromCreditNote", $discount->getNomUrl(0));
5250 } elseif ($line->desc ==
'(DEPOSIT)') {
5252 $discount->fetch($line->fk_remise_except);
5253 $this->tpl[
'description'] = $langs->transnoentities(
"DiscountFromDeposit", $discount->getNomUrl(0));
5254 } elseif ($line->desc ==
'(EXCESS RECEIVED)') {
5256 $discount->fetch($line->fk_remise_except);
5257 $this->tpl[
'description'] = $langs->transnoentities(
"DiscountFromExcessReceived", $discount->getNomUrl(0));
5258 } elseif ($line->desc ==
'(EXCESS PAID)') {
5260 $discount->fetch($line->fk_remise_except);
5261 $this->tpl[
'description'] = $langs->transnoentities(
"DiscountFromExcessPaid", $discount->getNomUrl(0));
5263 $this->tpl[
'description'] =
dol_trunc($line->desc, 60);
5266 $this->tpl[
'description'] =
' ';
5270 $this->tpl[
'vat_rate'] =
vatrate($line->tva_tx,
true);
5271 $this->tpl[
'vat_rate'] .= (($line->info_bits & 1) == 1) ?
'*' :
'';
5272 if (!empty($line->vat_src_code) && !preg_match(
'/\(/', $this->tpl[
'vat_rate'])) {
5273 $this->tpl[
'vat_rate'] .=
' ('.$line->vat_src_code.
')';
5276 $this->tpl[
'price'] =
price($line->subprice);
5277 $this->tpl[
'total_ht'] =
price($line->total_ht);
5278 $this->tpl[
'multicurrency_price'] =
price($line->multicurrency_subprice);
5279 $this->tpl[
'qty'] = (($line->info_bits & 2) != 2) ? $line->qty :
' ';
5281 $this->tpl[
'unit'] = $langs->transnoentities($line->getLabelOfUnit(
'long'));
5283 $this->tpl[
'remise_percent'] = (($line->info_bits & 2) != 2) ?
vatrate($line->remise_percent,
true) :
' ';
5286 $this->tpl[
'strike'] = 0;
5288 $this->tpl[
'strike'] = 1;
5293 $dirtpls = array_merge($conf->modules_parts[
'tpl'], array($defaulttpldir));
5294 foreach ($dirtpls as $module => $reldir) {
5295 if (!empty($module)) {
5298 $tpl = DOL_DOCUMENT_ROOT.$reldir.
'/originproductline.tpl.php';
5301 if (empty($conf->file->strict_mode)) {
5302 $res = @include $tpl;
5304 $res = include $tpl;
5329 $sql =
"INSERT INTO ".$this->db->prefix().
"element_resources (";
5330 $sql .=
"resource_id";
5331 $sql .=
", resource_type";
5332 $sql .=
", element_id";
5333 $sql .=
", element_type";
5335 $sql .=
", mandatory";
5336 $sql .=
") VALUES (";
5337 $sql .= ((int) $resource_id);
5338 $sql .=
", '".$this->db->escape($resource_type).
"'";
5339 $sql .=
", '".$this->db->escape($this->
id).
"'";
5340 $sql .=
", '".$this->db->escape($this->element).
"'";
5341 $sql .=
", '".$this->db->escape($busy).
"'";
5342 $sql .=
", '".$this->db->escape($mandatory).
"'";
5345 dol_syslog(get_class($this).
"::add_element_resource", LOG_DEBUG);
5346 if ($this->db->query($sql)) {
5347 $this->db->commit();
5350 $this->error = $this->db->lasterror();
5351 $this->db->rollback();
5372 $sql =
"DELETE FROM ".$this->db->prefix().
"element_resources";
5373 $sql .=
" WHERE rowid = ".((int) $rowid);
5375 dol_syslog(get_class($this).
"::delete_resource", LOG_DEBUG);
5377 $resql = $this->db->query($sql);
5379 $this->error = $this->db->lasterror();
5380 $this->db->rollback();
5384 $result = $this->call_trigger(strtoupper($element).
'_DELETE_RESOURCE', $user);
5386 $this->db->rollback();
5390 $this->db->commit();
5404 if (isset($this->lines) && is_array($this->lines)) {
5405 $nboflines = count($this->lines);
5406 for ($i = 0; $i < $nboflines; $i++) {
5407 if (is_object($this->lines[$i])) {
5408 $this->lines[$i] = clone $this->lines[$i];
5427 protected function commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams =
null)
5429 global $conf, $langs, $user, $hookmanager, $action;
5431 $srctemplatepath =
'';
5433 $parameters = array(
'modelspath'=>$modelspath,
'modele'=>$modele,
'outputlangs'=>$outputlangs,
'hidedetails'=>$hidedetails,
'hidedesc'=>$hidedesc,
'hideref'=>$hideref,
'moreparams'=>$moreparams);
5434 $reshook = $hookmanager->executeHooks(
'commonGenerateDocument', $parameters, $this, $action);
5436 if (!empty($reshook)) {
5440 dol_syslog(
"commonGenerateDocument modele=".$modele.
" outputlangs->defaultlang=".(is_object($outputlangs) ? $outputlangs->defaultlang :
'null'));
5442 if (empty($modele)) {
5443 $this->error =
'BadValueForParameterModele';
5448 $err = error_reporting();
5450 @set_time_limit(120);
5451 error_reporting($err);
5454 $tmp = explode(
':', $modele, 2);
5455 if (!empty($tmp[1])) {
5457 $srctemplatepath = $tmp[1];
5464 $dirmodels = array(
'/');
5465 if (is_array($conf->modules_parts[
'models'])) {
5466 $dirmodels = array_merge($dirmodels, $conf->modules_parts[
'models']);
5468 foreach ($dirmodels as $reldir) {
5469 foreach (array(
'doc',
'pdf') as $prefix) {
5470 if (in_array(get_class($this), array(
'Adherent'))) {
5472 $file = $prefix.
"_".$modele.
".class.php";
5475 $file = $prefix.
"_".$modele.
".modules.php";
5480 if (file_exists($file)) {
5482 $classname = $prefix.
'_'.$modele;
5492 $this->error = $langs->trans(
"Error").
' Failed to load doc generator with modelpaths='.$modelspath.
' - modele='.$modele;
5493 $this->errors[] = $this->error;
5503 $obj =
new $classname($this->db);
5506 if ($obj->type ==
'odt' && empty($srctemplatepath)) {
5507 $varfortemplatedir = $obj->scandir;
5508 if ($varfortemplatedir && !empty($conf->global->$varfortemplatedir)) {
5509 $dirtoscan = $conf->global->$varfortemplatedir;
5511 $listoffiles = array();
5514 $listofdir = explode(
',', $dirtoscan);
5515 foreach ($listofdir as $key => $tmpdir) {
5516 $tmpdir = trim($tmpdir);
5517 $tmpdir = preg_replace(
'/DOL_DATA_ROOT/', DOL_DATA_ROOT, $tmpdir);
5519 unset($listofdir[$key]);
5522 if (is_dir($tmpdir)) {
5523 $tmpfiles =
dol_dir_list($tmpdir,
'files', 0,
'\.od(s|t)$',
'',
'name', SORT_ASC, 0);
5524 if (count($tmpfiles)) {
5525 $listoffiles = array_merge($listoffiles, $tmpfiles);
5530 if (count($listoffiles)) {
5531 foreach ($listoffiles as $record) {
5532 $srctemplatepath = $record[
'fullname'];
5538 if (empty($srctemplatepath)) {
5539 $this->error =
'ErrorGenerationAskedForOdtTemplateWithSrcFileNotDefined';
5544 if ($obj->type ==
'odt' && !empty($srctemplatepath)) {
5546 dol_syslog(
"Failed to locate template file ".$srctemplatepath, LOG_WARNING);
5547 $this->error =
'ErrorGenerationAskedForOdtTemplateWithSrcFileNotFound';
5554 $sav_charset_output = empty($outputlangs->charset_output) ?
'' : $outputlangs->charset_output;
5556 if (in_array(get_class($this), array(
'Adherent'))) {
5557 $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath,
'member', 1,
'tmp_cards', $moreparams);
5559 $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, $hidedetails, $hidedesc, $hideref, $moreparams);
5563 if ($resultwritefile > 0) {
5564 $outputlangs->charset_output = $sav_charset_output;
5567 require_once DOL_DOCUMENT_ROOT.
'/core/lib/files.lib.php';
5571 if (!empty($obj->result[
'fullpath'])) {
5572 $destfull = $obj->result[
'fullpath'];
5575 $update_main_doc_field = 0;
5576 if (!empty($obj->update_main_doc_field)) {
5577 $update_main_doc_field = 1;
5583 $this->indexFile($destfull, $update_main_doc_field);
5586 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);
5594 $outputlangs->charset_output = $sav_charset_output;
5595 $this->error = $obj->error;
5596 $this->errors = $obj->errors;
5597 dol_syslog(
"Error generating document for ".__CLASS__.
". Error: ".$obj->error, LOG_ERR);
5611 public function indexFile($destfull, $update_main_doc_field)
5613 global $conf, $user;
5615 $upload_dir = dirname($destfull);
5616 $destfile = basename($destfull);
5617 $rel_dir = preg_replace(
'/^'.preg_quote(DOL_DATA_ROOT,
'/').
'/',
'', $upload_dir);
5619 if (!preg_match(
'/[\\/]temp[\\/]|[\\/]thumbs|\.meta$/', $rel_dir)) {
5620 $filename = basename($destfile);
5621 $rel_dir = preg_replace(
'/[\\/]$/',
'', $rel_dir);
5622 $rel_dir = preg_replace(
'/^[\\/]/',
'', $rel_dir);
5624 include_once DOL_DOCUMENT_ROOT.
'/ecm/class/ecmfiles.class.php';
5625 $ecmfile =
new EcmFiles($this->db);
5626 $result = $ecmfile->fetch(0,
'', ($rel_dir ? $rel_dir.
'/' :
'').$filename);
5629 $setsharekey =
false;
5630 if ($this->element ==
'propal' || $this->element ==
'proposal') {
5631 if (!isset($conf->global->PROPOSAL_ALLOW_ONLINESIGN) || !empty($conf->global->PROPOSAL_ALLOW_ONLINESIGN)) {
5632 $setsharekey =
true;
5634 if (!empty($conf->global->PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD)) {
5635 $setsharekey =
true;
5638 if ($this->element ==
'commande' && !empty($conf->global->ORDER_ALLOW_EXTERNAL_DOWNLOAD)) {
5639 $setsharekey =
true;
5641 if ($this->element ==
'facture' && !empty($conf->global->INVOICE_ALLOW_EXTERNAL_DOWNLOAD)) {
5642 $setsharekey =
true;
5644 if ($this->element ==
'bank_account' && !empty($conf->global->BANK_ACCOUNT_ALLOW_EXTERNAL_DOWNLOAD)) {
5645 $setsharekey =
true;
5647 if ($this->element ==
'product' && !empty($conf->global->PRODUCT_ALLOW_EXTERNAL_DOWNLOAD)) {
5648 $setsharekey =
true;
5650 if ($this->element ==
'contrat' && !empty($conf->global->CONTRACT_ALLOW_EXTERNAL_DOWNLOAD)) {
5651 $setsharekey =
true;
5653 if ($this->element ==
'fichinter' && !empty($conf->global->FICHINTER_ALLOW_EXTERNAL_DOWNLOAD)) {
5654 $setsharekey =
true;
5656 if ($this->element ==
'supplier_proposal' && !empty($conf->global->SUPPLIER_PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD)) {
5657 $setsharekey =
true;
5661 if (empty($ecmfile->share)) {
5662 require_once DOL_DOCUMENT_ROOT.
'/core/lib/security2.lib.php';
5669 $ecmfile->fullpath_orig =
'';
5670 $ecmfile->gen_or_uploaded =
'generated';
5671 $ecmfile->description =
'';
5672 $ecmfile->keywords =
'';
5673 $result = $ecmfile->update($user);
5679 $ecmfile->entity = $conf->entity;
5680 $ecmfile->filepath = $rel_dir;
5681 $ecmfile->filename = $filename;
5683 $ecmfile->fullpath_orig =
'';
5684 $ecmfile->gen_or_uploaded =
'generated';
5685 $ecmfile->description =
'';
5686 $ecmfile->keywords =
'';
5687 $ecmfile->src_object_type = $this->table_element;
5688 $ecmfile->src_object_id = $this->id;
5690 $result = $ecmfile->create($user);
5702 if ($update_main_doc_field && !empty($this->table_element)) {
5703 $sql =
"UPDATE ".$this->db->prefix().$this->table_element.
" SET last_main_doc = '".$this->db->escape($ecmfile->filepath.
"/".$ecmfile->filename).
"'";
5704 $sql .=
" WHERE rowid = ".((int) $this->
id);
5706 $resql = $this->db->query($sql);
5711 $this->last_main_doc = $ecmfile->filepath.
'/'.$ecmfile->filename;
5730 if (file_exists($file_osencoded)) {
5731 require_once DOL_DOCUMENT_ROOT.
'/core/lib/images.lib.php';
5734 $maxwidthsmall = $tmparraysize[
'maxwidthsmall'];
5735 $maxheightsmall = $tmparraysize[
'maxheightsmall'];
5736 $maxwidthmini = $tmparraysize[
'maxwidthmini'];
5737 $maxheightmini = $tmparraysize[
'maxheightmini'];
5743 vignette($file_osencoded, $maxwidthsmall, $maxheightsmall,
'_small', $quality);
5747 vignette($file_osencoded, $maxwidthmini, $maxheightmini,
'_mini', $quality);
5786 global $conf, $_POST;
5789 if (GETPOSTISSET($fieldname)) {
5790 return GETPOST($fieldname, $type, 3);
5793 if (isset($alternatevalue)) {
5794 return $alternatevalue;
5797 $newelement = $this->element;
5798 if ($newelement ==
'facture') {
5799 $newelement =
'invoice';
5801 if ($newelement ==
'commande') {
5802 $newelement =
'order';
5804 if (empty($newelement)) {
5805 dol_syslog(
"Ask a default value using common method getDefaultCreateValueForField on an object with no property ->element defined. Return empty string.", LOG_WARNING);
5809 $keyforfieldname = strtoupper($newelement.
'_DEFAULT_'.$fieldname);
5811 if (isset($conf->global->$keyforfieldname)) {
5812 return $conf->global->$keyforfieldname;
5839 global $langs, $conf;
5840 if (!empty(self::TRIGGER_PREFIX) && strpos($triggerName, self::TRIGGER_PREFIX .
'_') !== 0) {
5841 dol_print_error(
'',
'The trigger "' . $triggerName .
'" does not start with "' . self::TRIGGER_PREFIX .
'_" as required.');
5844 if (!is_object($langs)) {
5845 include_once DOL_DOCUMENT_ROOT.
'/core/class/translate.class.php';
5849 include_once DOL_DOCUMENT_ROOT.
'/core/class/interfaces.class.php';
5851 $result = $interface->run_triggers($triggerName, $this, $user, $langs, $conf);
5854 if (!empty($this->errors)) {
5855 $this->errors = array_unique(array_merge($this->errors, $interface->errors));
5857 $this->errors = $interface->errors;
5877 if (!$this->element) {
5880 if (!($this->
id > 0)) {
5883 if (is_array($this->array_languages)) {
5887 $this->array_languages = array();
5889 $element = $this->element;
5890 if ($element ==
'categorie') {
5891 $element =
'categories';
5895 $sql =
"SELECT rowid, property, lang , value";
5896 $sql .=
" FROM ".$this->db->prefix().
"object_lang";
5897 $sql .=
" WHERE type_object = '".$this->db->escape($element).
"'";
5898 $sql .=
" AND fk_object = ".((int) $this->
id);
5901 $resql = $this->db->query($sql);
5903 $numrows = $this->db->num_rows($resql);
5906 while ($i < $numrows) {
5907 $obj = $this->db->fetch_object($resql);
5908 $key = $obj->property;
5909 $value = $obj->value;
5910 $codelang = $obj->lang;
5911 $type = $this->fields[$key][
'type'];
5914 if (preg_match(
'/date/', $type)) {
5915 $this->array_languages[$key][$codelang] = $this->db->jdate($value);
5917 $this->array_languages[$key][$codelang] = $value;
5924 $this->db->free($resql);
5945 global $_POST, $langs;
5948 foreach ($_POST as $postfieldkey => $postfieldvalue) {
5949 $tmparray = explode(
'-', $postfieldkey);
5950 if ($tmparray[0] !=
'field') {
5954 $element = $tmparray[1];
5955 $key = $tmparray[2];
5956 $codelang = $tmparray[3];
5959 if (!empty($onlykey) && $key != $onlykey) {
5962 if ($element != $this->element) {
5966 $key_type = $this->fields[$key][
'type'];
5969 if (isset($this->fields[$key][
'enabled'])) {
5970 $enabled =
dol_eval($this->fields[$key][
'enabled'], 1, 1,
'1');
5977 if (empty($enabled)) {
5982 if (in_array($key_type, array(
'date'))) {
5986 } elseif (in_array($key_type, array(
'datetime'))) {
5989 $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'));
5990 } elseif (in_array($key_type, array(
'checkbox',
'chkbxlst'))) {
5991 $value_arr =
GETPOST($postfieldkey,
'array');
5992 if (!empty($value_arr)) {
5993 $value_key = implode(
',', $value_arr);
5997 } elseif (in_array($key_type, array(
'price',
'double'))) {
5998 $value_arr =
GETPOST($postfieldkey,
'alpha');
6001 $value_key =
GETPOST($postfieldkey);
6002 if (in_array($key_type, array(
'link')) && $value_key ==
'-1') {
6007 $this->array_languages[$key][$codelang] = $value_key;
6032 $savDisableCompute = $conf->disable_compute;
6033 $conf->disable_compute = 1;
6035 $ret = $this->fetch($id);
6037 $conf->disable_compute = $savDisableCompute;
6055 global $conf, $extrafields;
6057 if (empty($rowid)) {
6060 if (empty($rowid) && isset($this->
rowid)) {
6061 $rowid = $this->rowid;
6065 if (!$this->table_element) {
6069 $this->array_options = array();
6071 if (!is_array($optionsArray)) {
6073 if (!isset($extrafields) || !is_object($extrafields)) {
6074 require_once DOL_DOCUMENT_ROOT.
'/core/class/extrafields.class.php';
6079 if (empty($extrafields->attributes[$this->table_element][
'loaded'])) {
6080 $extrafields->fetch_name_optionals_label($this->table_element);
6082 $optionsArray = (!empty($extrafields->attributes[$this->table_element][
'label']) ? $extrafields->attributes[$this->table_element][
'label'] :
null);
6084 global $extrafields;
6085 dol_syslog(
"Warning: fetch_optionals was called with param optionsArray defined when you should pass null now", LOG_WARNING);
6088 $table_element = $this->table_element;
6089 if ($table_element ==
'categorie') {
6090 $table_element =
'categories';
6094 if (is_array($optionsArray) && count($optionsArray) > 0) {
6095 $sql =
"SELECT rowid";
6096 foreach ($optionsArray as $name => $label) {
6097 if (empty($extrafields->attributes[$this->table_element][
'type'][$name]) || $extrafields->attributes[$this->table_element][
'type'][$name] !=
'separate') {
6101 $sql .=
" FROM ".$this->db->prefix().$table_element.
"_extrafields";
6102 $sql .=
" WHERE fk_object = ".((int) $rowid);
6105 $resql = $this->db->query($sql);
6107 $numrows = $this->db->num_rows($resql);
6109 $tab = $this->db->fetch_array($resql);
6111 foreach ($tab as $key => $value) {
6113 if ($key !=
'rowid' && $key !=
'tms' && $key !=
'fk_member' && !is_int($key)) {
6115 if (!empty($extrafields->attributes[$this->table_element]) && in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'date',
'datetime'))) {
6117 $this->array_options[
"options_".$key] = $this->db->jdate($value);
6119 $this->array_options[
"options_".$key] = $value;
6129 if (is_array($extrafields->attributes[$this->table_element][
'label'])) {
6130 foreach ($extrafields->attributes[$this->table_element][
'label'] as $key => $val) {
6131 if (!empty($extrafields->attributes[$this->table_element]) && !empty($extrafields->attributes[$this->table_element][
'computed'][$key])) {
6133 if (empty($conf->disable_compute)) {
6134 global $objectoffield;
6135 $objectoffield = $this;
6136 $this->array_options[
'options_' . $key] =
dol_eval($extrafields->attributes[$this->table_element][
'computed'][$key], 1, 0,
'');
6142 $this->db->free($resql);
6150 $this->errors[]=$this->db->lasterror;
6167 if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
6173 $table_element = $this->table_element;
6174 if ($table_element ==
'categorie') {
6175 $table_element =
'categories';
6178 dol_syslog(get_class($this).
"::deleteExtraFields delete", LOG_DEBUG);
6180 $sql_del =
"DELETE FROM ".$this->db->prefix().$table_element.
"_extrafields WHERE fk_object = ".((int) $this->
id);
6182 $resql = $this->db->query($sql_del);
6184 $this->error = $this->db->lasterror();
6185 $this->db->rollback();
6188 $this->db->commit();
6205 global $conf, $langs, $user;
6207 if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
6211 if (empty($userused)) {
6217 if (!empty($this->array_options)) {
6219 $langs->load(
'admin');
6220 require_once DOL_DOCUMENT_ROOT.
'/core/class/extrafields.class.php';
6222 $target_extrafields = $extrafields->fetch_name_optionals_label($this->table_element);
6225 $new_array_options = array();
6226 foreach ($this->array_options as $key => $value) {
6227 if (in_array(substr($key, 8), array_keys($target_extrafields))) {
6228 $new_array_options[$key] = $value;
6229 } elseif (in_array($key, array_keys($target_extrafields))) {
6230 $new_array_options[
'options_'.$key] = $value;
6234 foreach ($new_array_options as $key => $value) {
6235 $attributeKey = substr($key, 8);
6236 $attributeType = $extrafields->attributes[$this->table_element][
'type'][$attributeKey];
6237 $attributeLabel = $langs->transnoentities($extrafields->attributes[$this->table_element][
'label'][$attributeKey]);
6238 $attributeParam = $extrafields->attributes[$this->table_element][
'param'][$attributeKey];
6239 $attributeRequired = $extrafields->attributes[$this->table_element][
'required'][$attributeKey];
6240 $attributeUnique = $extrafields->attributes[$this->table_element][
'unique'][$attributeKey];
6241 $attrfieldcomputed = $extrafields->attributes[$this->table_element][
'computed'][$attributeKey];
6245 if (!empty($this->context[
'createfromclone']) && $this->context[
'createfromclone'] ==
'createfromclone' && !empty($attributeUnique)) {
6246 $new_array_options[$key] =
null;
6250 if ($attributeRequired) {
6251 $mandatorypb =
false;
6252 if ($attributeType ==
'link' && $this->array_options[$key] ==
'-1') {
6253 $mandatorypb =
true;
6255 if ($this->array_options[$key] ===
'') {
6256 $mandatorypb =
true;
6258 if ($attributeType ==
'sellist' && $this->array_options[$key] ==
'0') {
6259 $mandatorypb =
true;
6262 $langs->load(
"errors");
6263 dol_syslog(
"Mandatory field '".$key.
"' is empty during create and set to required into definition of extrafields");
6264 $this->errors[] = $langs->trans(
'ErrorFieldRequired', $attributeLabel);
6272 if (!empty($attrfieldcomputed)) {
6273 if (!empty($conf->global->MAIN_STORE_COMPUTED_EXTRAFIELDS)) {
6274 $value =
dol_eval($attrfieldcomputed, 1, 0,
'');
6275 dol_syslog($langs->trans(
"Extrafieldcomputed").
" sur ".$attributeLabel.
"(".$value.
")", LOG_DEBUG);
6276 $new_array_options[$key] = $value;
6278 $new_array_options[$key] =
null;
6282 switch ($attributeType) {
6284 if (!is_numeric($value) && $value !=
'') {
6285 $this->errors[] = $langs->trans(
"ExtraFieldHasWrongValue", $attributeLabel);
6287 } elseif ($value ==
'') {
6288 $new_array_options[$key] =
null;
6294 if (!is_numeric($value) && $value !=
'') {
6295 dol_syslog($langs->trans(
"ExtraFieldHasWrongValue").
" for ".$attributeLabel.
"(".$value.
"is not '".$attributeType.
"')", LOG_DEBUG);
6296 $this->errors[] = $langs->trans(
"ExtraFieldHasWrongValue", $attributeLabel);
6298 } elseif ($value ==
'') {
6302 $new_array_options[$key] = $value;
6312 if ($this->array_options[$key] !=
'' && is_array($extrafields->attributes[$this->table_element][
'param'][$attributeKey][
'options'])) {
6314 $tmparrays = array_keys($extrafields->attributes[$this->table_element][
'param'][$attributeKey][
'options']);
6315 $algo = reset($tmparrays);
6320 if (is_object($this->oldcopy)) {
6322 if (isset($this->oldcopy->array_options[$key]) && $this->array_options[$key] == $this->oldcopy->array_options[$key]) {
6323 $new_array_options[$key] = $this->array_options[$key];
6326 $newvalue =
dol_hash($this->array_options[$key], $algo);
6327 $new_array_options[$key] = $newvalue;
6330 $new_array_options[$key] = $this->array_options[$key];
6335 $new_array_options[$key] = $this->array_options[$key];
6341 if (!is_numeric($this->array_options[$key]) || $this->array_options[$key] != intval($this->array_options[$key])) {
6342 $this->array_options[$key] = strtotime($this->array_options[$key]);
6344 $new_array_options[$key] = $this->db->idate($this->array_options[$key]);
6348 if (!is_numeric($this->array_options[$key]) || $this->array_options[$key] != intval($this->array_options[$key])) {
6349 $this->array_options[$key] = strtotime($this->array_options[$key]);
6351 $new_array_options[$key] = $this->db->idate($this->array_options[$key],
'gmt');
6354 $param_list = array_keys($attributeParam[
'options']);
6357 $InfoFieldList = explode(
":", $param_list[0]);
6359 if ($InfoFieldList[0] && class_exists($InfoFieldList[0])) {
6360 if ($value ==
'-1') {
6361 $new_array_options[$key] =
'';
6363 $object =
new $InfoFieldList[0]($this->db);
6364 if (is_numeric($value)) {
6365 $res = $object->fetch($value);
6367 $res = $object->fetch(
'', $value);
6371 $new_array_options[$key] = $object->id;
6373 $this->error =
"Id/Ref '".$value.
"' for object '".$object->element.
"' not found";
6378 dol_syslog(
'Error bad setup of extrafield', LOG_WARNING);
6383 if (is_array($this->array_options[$key])) {
6384 $new_array_options[$key] = implode(
',', $this->array_options[$key]);
6386 $new_array_options[$key] = $this->array_options[$key];
6394 $table_element = $this->table_element;
6395 if ($table_element ==
'categorie') {
6396 $table_element =
'categories';
6399 dol_syslog(get_class($this).
"::insertExtraFields delete then insert", LOG_DEBUG);
6401 $sql_del =
"DELETE FROM ".$this->db->prefix().$table_element.
"_extrafields WHERE fk_object = ".((int) $this->
id);
6402 $this->db->query($sql_del);
6404 $sql =
"INSERT INTO ".$this->db->prefix().$table_element.
"_extrafields (fk_object";
6405 foreach ($new_array_options as $key => $value) {
6406 $attributeKey = substr($key, 8);
6408 if ($extrafields->attributes[$this->table_element][
'type'][$attributeKey] !=
'separate') {
6409 $sql .=
",".$attributeKey;
6413 if (!empty($extrafields->attributes[$this->table_element][
'mandatoryfieldsofotherentities']) && is_array($extrafields->attributes[$this->table_element][
'mandatoryfieldsofotherentities'])) {
6414 foreach ($extrafields->attributes[$this->table_element][
'mandatoryfieldsofotherentities'] as $tmpkey => $tmpval) {
6415 if (!isset($extrafields->attributes[$this->table_element][
'type'][$tmpkey])) {
6416 $sql .=
",".$tmpkey;
6420 $sql .=
") VALUES (".$this->id;
6422 foreach ($new_array_options as $key => $value) {
6423 $attributeKey = substr($key, 8);
6425 if ($extrafields->attributes[$this->table_element][
'type'][$attributeKey] !=
'separate') {
6426 if ($new_array_options[$key] !=
'' || $new_array_options[$key] ==
'0') {
6427 $sql .=
",'".$this->db->escape($new_array_options[$key]).
"'";
6434 if (!empty($extrafields->attributes[$this->table_element][
'mandatoryfieldsofotherentities']) && is_array($extrafields->attributes[$this->table_element][
'mandatoryfieldsofotherentities'])) {
6435 foreach ($extrafields->attributes[$this->table_element][
'mandatoryfieldsofotherentities'] as $tmpkey => $tmpval) {
6436 if (!isset($extrafields->attributes[$this->table_element][
'type'][$tmpkey])) {
6437 if (in_array($tmpval, array(
'int',
'double',
'price'))) {
6448 $resql = $this->db->query($sql);
6450 $this->error = $this->db->lasterror();
6454 if (!$error && $trigger) {
6456 $this->context = array(
'extrafieldaddupdate'=>1);
6457 $result = $this->call_trigger($trigger, $userused);
6465 $this->db->rollback();
6468 $this->db->commit();
6488 global $conf, $langs, $user;
6490 if (empty($userused)) {
6496 if (!empty($conf->global->MAIN_EXTRALANGUAGES_DISABLED)) {
6500 if (is_array($this->array_languages)) {
6501 $new_array_languages = $this->array_languages;
6503 foreach ($new_array_languages as $key => $value) {
6504 $attributeKey = $key;
6505 $attributeType = $this->fields[$attributeKey][
'type'];
6506 $attributeLabel = $this->fields[$attributeKey][
'label'];
6511 switch ($attributeType) {
6513 if (!is_numeric($value) && $value !=
'') {
6514 $this->errors[] = $langs->trans(
"ExtraLanguageHasWrongValue", $attributeLabel);
6516 } elseif ($value ==
'') {
6517 $new_array_languages[$key] =
null;
6522 if (!is_numeric($value) && $value !=
'') {
6523 dol_syslog($langs->trans(
"ExtraLanguageHasWrongValue").
" sur ".$attributeLabel.
"(".$value.
"is not '".$attributeType.
"')", LOG_DEBUG);
6524 $this->errors[] = $langs->trans(
"ExtraLanguageHasWrongValue", $attributeLabel);
6526 } elseif ($value ==
'') {
6527 $new_array_languages[$key] =
null;
6529 $new_array_languages[$key] = $value;
6543 $table_element = $this->table_element;
6544 if ($table_element ==
'categorie') {
6545 $table_element =
'categories';
6548 dol_syslog(get_class($this).
"::insertExtraLanguages delete then insert", LOG_DEBUG);
6550 foreach ($new_array_languages as $key => $langcodearray) {
6551 foreach ($langcodearray as $langcode => $value) {
6552 $sql_del =
"DELETE FROM ".$this->db->prefix().
"object_lang";
6553 $sql_del .=
" WHERE fk_object = ".((int) $this->
id).
" AND property = '".$this->db->escape($key).
"' AND type_object = '".$this->db->escape($table_element).
"'";
6554 $sql_del .=
" AND lang = '".$this->db->escape($langcode).
"'";
6555 $this->db->query($sql_del);
6557 if ($value !==
'') {
6558 $sql =
"INSERT INTO ".$this->db->prefix().
"object_lang (fk_object, property, type_object, lang, value";
6559 $sql .=
") VALUES (".$this->id.
", '".$this->db->escape($key).
"', '".$this->db->escape($table_element).
"', '".$this->db->escape($langcode).
"', '".$this->db->escape($value).
"'";
6562 $resql = $this->db->query($sql);
6564 $this->error = $this->db->lasterror();
6572 if (!$error && $trigger) {
6574 $this->context = array(
'extralanguagesaddupdate'=>1);
6575 $result = $this->call_trigger($trigger, $userused);
6583 $this->db->rollback();
6586 $this->db->commit();
6606 global $conf, $langs, $user;
6608 if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
6612 if (empty($userused)) {
6618 if (!empty($this->array_options) && isset($this->array_options[
"options_".$key])) {
6620 $langs->load(
'admin');
6621 require_once DOL_DOCUMENT_ROOT.
'/core/class/extrafields.class.php';
6623 $extrafields->fetch_name_optionals_label($this->table_element);
6625 $value = $this->array_options[
"options_".$key];
6627 $attributeType = $extrafields->attributes[$this->table_element][
'type'][$key];
6628 $attributeLabel = $extrafields->attributes[$this->table_element][
'label'][$key];
6629 $attributeParam = $extrafields->attributes[$this->table_element][
'param'][$key];
6630 $attributeRequired = $extrafields->attributes[$this->table_element][
'required'][$key];
6631 $attrfieldcomputed = $extrafields->attributes[$this->table_element][
'computed'][$key];
6634 if ($attributeRequired) {
6635 $mandatorypb =
false;
6636 if ($attributeType ==
'link' && $this->array_options[
"options_".$key] ==
'-1') {
6637 $mandatorypb =
true;
6639 if ($this->array_options[
"options_".$key] ===
'') {
6640 $mandatorypb =
true;
6643 $langs->load(
"errors");
6644 dol_syslog(
"Mandatory field 'options_".$key.
"' is empty during update and set to required into definition of extrafields");
6645 $this->errors[] = $langs->trans(
'ErrorFieldRequired', $attributeLabel);
6653 if (!empty($attrfieldcomputed)) {
6654 if (!empty($conf->global->MAIN_STORE_COMPUTED_EXTRAFIELDS)) {
6655 $value =
dol_eval($attrfieldcomputed, 1, 0,
'');
6656 dol_syslog($langs->trans(
"Extrafieldcomputed").
" sur ".$attributeLabel.
"(".$value.
")", LOG_DEBUG);
6657 $this->array_options[
"options_".$key] = $value;
6659 $this->array_options[
"options_".$key] =
null;
6663 switch ($attributeType) {
6665 if (!is_numeric($value) && $value !=
'') {
6666 $this->errors[] = $langs->trans(
"ExtraFieldHasWrongValue", $attributeLabel);
6668 } elseif ($value ===
'') {
6669 $this->array_options[
"options_".$key] =
null;
6675 if (!is_numeric($value) && $value !=
'') {
6676 dol_syslog($langs->trans(
"ExtraFieldHasWrongValue").
" sur ".$attributeLabel.
"(".$value.
"is not '".$attributeType.
"')", LOG_DEBUG);
6677 $this->errors[] = $langs->trans(
"ExtraFieldHasWrongValue", $attributeLabel);
6679 } elseif ($value ===
'') {
6683 $this->array_options[
"options_".$key] = $value;
6693 if (empty($this->array_options[
"options_".$key])) {
6694 $this->array_options[
"options_".$key] =
null;
6696 $this->array_options[
"options_".$key] = $this->db->idate($this->array_options[
"options_".$key]);
6700 if (empty($this->array_options[
"options_".$key])) {
6701 $this->array_options[
"options_".$key] =
null;
6703 $this->array_options[
"options_".$key] = $this->db->idate($this->array_options[
"options_".$key],
'gmt');
6707 if (empty($this->array_options[
"options_".$key])) {
6708 $this->array_options[
"options_".$key] =
null;
6712 if ($this->array_options[
"options_".$key] ===
'') {
6713 $this->array_options[
"options_".$key] =
null;
6747 if (is_array($this->array_options[$key])) {
6748 $new_array_options[$key] = implode(
',', $this->array_options[$key]);
6750 $new_array_options[$key] = $this->array_options[$key];
6757 $linealreadyfound = 0;
6760 $sql =
"SELECT COUNT(rowid) as nb FROM ".$this->db->prefix().$this->table_element.
"_extrafields WHERE fk_object = ".((int) $this->
id);
6761 $resql = $this->db->query($sql);
6763 $tmpobj = $this->db->fetch_object($resql);
6765 $linealreadyfound = $tmpobj->nb;
6769 if ($linealreadyfound) {
6770 if ($this->array_options[
"options_".$key] ===
null) {
6771 $sql =
"UPDATE ".$this->db->prefix().$this->table_element.
"_extrafields SET ".$key.
" = null";
6773 $sql =
"UPDATE ".$this->db->prefix().$this->table_element.
"_extrafields SET ".$key.
" = '".$this->db->escape($this->array_options[
"options_".$key]).
"'";
6775 $sql .=
" WHERE fk_object = ".((int) $this->
id);
6777 $result = $this->insertExtraFields(
'', $user);
6783 $resql = $this->db->query($sql);
6786 $this->error = $this->db->lasterror();
6788 if (!$error && $trigger) {
6790 $this->context = array(
'extrafieldupdate'=>1);
6791 $result = $this->call_trigger($trigger, $userused);
6799 dol_syslog(__METHOD__.$this->error, LOG_ERR);
6800 $this->db->rollback();
6803 $this->db->commit();
6823 global $conf, $langs, $user;
6825 if (empty($userused)) {
6831 if (!empty($conf->global->MAIN_EXTRALANGUAGES_DISABLED)) {
6853 public function showInputField($val, $key, $value, $moreparam =
'', $keysuffix =
'', $keyprefix =
'', $morecss = 0, $nonewbutton = 0)
6855 global $conf, $langs, $form;
6857 if (!is_object($form)) {
6858 require_once DOL_DOCUMENT_ROOT.
'/core/class/html.form.class.php';
6859 $form =
new Form($this->db);
6862 if (!empty($this->fields)) {
6863 $val = $this->fields[$key];
6867 $fieldValidationErrorMsg =
'';
6868 $validationClass =
'';
6869 $fieldValidationErrorMsg = $this->getFieldError($key);
6870 if (!empty($fieldValidationErrorMsg)) {
6871 $validationClass =
' --error';
6873 $validationClass =
' --success';
6880 $param[
'options'] = array();
6882 $size = !empty($this->fields[$key][
'size']) ? $this->fields[$key][
'size'] : 0;
6884 if (preg_match(
'/^(integer|link):(.*):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
6885 $param[
'options'] = array($reg[2].
':'.$reg[3].
':'.$reg[4].
':'.$reg[5] =>
'N');
6887 } elseif (preg_match(
'/^(integer|link):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
6888 $param[
'options'] = array($reg[2].
':'.$reg[3].
':'.$reg[4] =>
'N');
6890 } elseif (preg_match(
'/^(integer|link):(.*):(.*)/i', $val[
'type'], $reg)) {
6891 $param[
'options'] = array($reg[2].
':'.$reg[3] =>
'N');
6893 } elseif (preg_match(
'/^(sellist):(.*):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
6894 $param[
'options'] = array($reg[2].
':'.$reg[3].
':'.$reg[4].
':'.$reg[5] =>
'N');
6896 } elseif (preg_match(
'/^(sellist):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
6897 $param[
'options'] = array($reg[2].
':'.$reg[3].
':'.$reg[4] =>
'N');
6899 } elseif (preg_match(
'/^(sellist):(.*):(.*)/i', $val[
'type'], $reg)) {
6900 $param[
'options'] = array($reg[2].
':'.$reg[3] =>
'N');
6902 } elseif (preg_match(
'/^chkbxlst:(.*)/i', $val[
'type'], $reg)) {
6903 $param[
'options'] = array($reg[1] =>
'N');
6905 } elseif (preg_match(
'/varchar\((\d+)\)/', $val[
'type'], $reg)) {
6906 $param[
'options'] = array();
6909 } elseif (preg_match(
'/varchar/', $val[
'type'])) {
6910 $param[
'options'] = array();
6913 $param[
'options'] = array();
6914 $type = $this->fields[$key][
'type'];
6918 if (!empty($this->fields[$key][
'arrayofkeyval']) && is_array($this->fields[$key][
'arrayofkeyval'])) {
6919 $param[
'options'] = $this->fields[$key][
'arrayofkeyval'];
6923 $label = $this->fields[$key][
'label'];
6925 $default = (!empty($this->fields[$key][
'default']) ? $this->fields[$key][
'default'] :
'');
6926 $computed = (!empty($this->fields[$key][
'computed']) ? $this->fields[$key][
'computed'] :
'');
6927 $unique = (!empty($this->fields[$key][
'unique']) ? $this->fields[$key][
'unique'] : 0);
6928 $required = (!empty($this->fields[$key][
'required']) ? $this->fields[$key][
'required'] : 0);
6929 $autofocusoncreate = (!empty($this->fields[$key][
'autofocusoncreate']) ? $this->fields[$key][
'autofocusoncreate'] : 0);
6931 $langfile = (!empty($this->fields[$key][
'langfile']) ? $this->fields[$key][
'langfile'] :
'');
6932 $list = (!empty($this->fields[$key][
'list']) ? $this->fields[$key][
'list'] : 0);
6933 $hidden = (in_array(abs($this->fields[$key][
'visible']), array(0, 2)) ? 1 : 0);
6935 $objectid = $this->id;
6938 if (!preg_match(
'/^search_/', $keyprefix)) {
6939 return '<span class="opacitymedium">'.$langs->trans(
"AutomaticallyCalculated").
'</span>';
6946 if (empty($morecss) && !empty($val[
'css'])) {
6947 $morecss = $val[
'css'];
6948 } elseif (empty($morecss)) {
6949 if ($type ==
'date') {
6950 $morecss =
'minwidth100imp';
6951 } elseif ($type ==
'datetime' || $type ==
'link') {
6952 $morecss =
'minwidth200imp';
6953 } elseif (in_array($type, array(
'int',
'integer',
'price')) || preg_match(
'/^double(\([0-9],[0-9]\)){0,1}/', $type)) {
6954 $morecss =
'maxwidth75';
6955 } elseif ($type ==
'url') {
6956 $morecss =
'minwidth400';
6957 } elseif ($type ==
'boolean') {
6960 if (round($size) < 12) {
6961 $morecss =
'minwidth100';
6962 } elseif (round($size) <= 48) {
6963 $morecss =
'minwidth200';
6965 $morecss =
'minwidth400';
6971 if (!empty($validationClass)) {
6972 $morecss.= $validationClass;
6975 if (in_array($type, array(
'date'))) {
6976 $tmp = explode(
',', $size);
6981 if (!$required && $value ==
'') {
6986 $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required,
'', 1, (($keyprefix !=
'search_' && $keyprefix !=
'search_options_') ? 1 : 0), 0, 1);
6987 } elseif (in_array($type, array(
'datetime'))) {
6988 $tmp = explode(
',', $size);
6993 if (!$required && $value ==
'') $value =
'-1';
6996 $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required,
'', 1, (($keyprefix !=
'search_' && $keyprefix !=
'search_options_') ? 1 : 0), 0, 1,
'',
'',
'', 1,
'',
'',
'tzuserrel');
6997 } elseif (in_array($type, array(
'duration'))) {
6998 $out = $form->select_duration($keyprefix.$key.$keysuffix, $value, 0,
'text', 0, 1);
6999 } elseif (in_array($type, array(
'int',
'integer'))) {
7000 $tmp = explode(
',', $size);
7002 $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' :
'').
'>';
7003 } elseif (in_array($type, array(
'real'))) {
7004 $out =
'<input type="text" class="flat '.$morecss.
'" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.
dol_escape_htmltag($value).
'"'.($moreparam ? $moreparam :
'').($autofocusoncreate ?
' autofocus' :
'').
'>';
7005 } elseif (preg_match(
'/varchar/', $type)) {
7006 $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' :
'').
'>';
7007 } elseif (in_array($type, array(
'email',
'mail',
'phone',
'url',
'ip'))) {
7008 $out =
'<input type="text" class="flat '.$morecss.
'" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.
dol_escape_htmltag($value).
'" '.($moreparam ? $moreparam :
'').($autofocusoncreate ?
' autofocus' :
'').
'>';
7009 } elseif (preg_match(
'/^text/', $type)) {
7010 if (!preg_match(
'/search_/', $keyprefix)) {
7011 require_once DOL_DOCUMENT_ROOT.
'/core/class/doleditor.class.php';
7012 $doleditor =
new DolEditor($keyprefix.$key.$keysuffix, $value,
'', 200,
'dolibarr_notes',
'In',
false,
false,
false, ROWS_5,
'90%');
7013 $out = $doleditor->Create(1);
7015 $out =
'<input type="text" class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.
dol_escape_htmltag($value).
'" '.($moreparam ? $moreparam :
'').
'>';
7017 } elseif (preg_match(
'/^html/', $type)) {
7018 if (!preg_match(
'/search_/', $keyprefix)) {
7019 require_once DOL_DOCUMENT_ROOT.
'/core/class/doleditor.class.php';
7020 $doleditor =
new DolEditor($keyprefix.$key.$keysuffix, $value,
'', 200,
'dolibarr_notes',
'In',
false,
false, isModEnabled(
'fckeditor') && $conf->global->FCKEDITOR_ENABLE_SOCIETE, ROWS_5,
'90%');
7021 $out = $doleditor->Create(1,
'',
true,
'',
'', $moreparam, $morecss);
7023 $out =
'<input type="text" class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.
dol_escape_htmltag($value).
'" '.($moreparam ? $moreparam :
'').
'>';
7025 } elseif ($type ==
'boolean') {
7027 if (!empty($value)) {
7028 $checked =
' checked value="1" ';
7030 $checked =
' value="1" ';
7032 $out =
'<input type="checkbox" class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" '.$checked.
' '.($moreparam ? $moreparam :
'').
'>';
7033 } elseif ($type ==
'price') {
7034 if (!empty($value)) {
7035 $value =
price($value);
7037 $out =
'<input type="text" class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.$value.
'" '.($moreparam ? $moreparam :
'').
'> '.$langs->getCurrencySymbol($conf->currency);
7038 } elseif (preg_match(
'/^double(\([0-9],[0-9]\)){0,1}/', $type)) {
7039 if (!empty($value)) {
7040 $value =
price($value);
7042 $out =
'<input type="text" class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.$value.
'" '.($moreparam ? $moreparam :
'').
'> ';
7043 } elseif ($type ==
'select') {
7045 if (!empty($conf->use_javascript_ajax) && empty($conf->global->MAIN_EXTRAFIELDS_DISABLE_SELECT2)) {
7046 include_once DOL_DOCUMENT_ROOT.
'/core/lib/ajax.lib.php';
7047 $out .=
ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
7050 $out .=
'<select class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" '.($moreparam ? $moreparam :
'').
'>';
7051 if ((!isset($this->fields[$key][
'default'])) || ($this->fields[$key][
'notnull'] != 1)) {
7052 $out .=
'<option value="0"> </option>';
7054 foreach ($param[
'options'] as $keyb => $valb) {
7055 if ((
string) $keyb ==
'') {
7058 if (strpos($valb,
"|") !==
false) {
7059 list($valb, $parent) = explode(
'|', $valb);
7061 $out .=
'<option value="'.$keyb.
'"';
7062 $out .= (((string) $value == (
string) $keyb) ?
' selected' :
'');
7063 $out .= (!empty($parent) ?
' parent="'.$parent.
'"' :
'');
7064 $out .=
'>'.$valb.
'</option>';
7066 $out .=
'</select>';
7067 } elseif ($type ==
'sellist') {
7069 if (!empty($conf->use_javascript_ajax) && empty($conf->global->MAIN_EXTRAFIELDS_DISABLE_SELECT2)) {
7070 include_once DOL_DOCUMENT_ROOT.
'/core/lib/ajax.lib.php';
7071 $out .=
ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
7074 $out .=
'<select class="flat '.$morecss.
' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" '.($moreparam ? $moreparam :
'').
'>';
7075 if (is_array($param[
'options'])) {
7076 $param_list = array_keys($param[
'options']);
7077 $InfoFieldList = explode(
":", $param_list[0]);
7087 $keyList = (empty($InfoFieldList[2]) ?
'rowid' : $InfoFieldList[2].
' as rowid');
7089 if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
7090 if (strpos($InfoFieldList[4],
'extra.') !==
false) {
7091 $keyList =
'main.'.$InfoFieldList[2].
' as rowid';
7093 $keyList = $InfoFieldList[2].
' as rowid';
7096 if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
7097 list($parentName, $parentField) = explode(
'|', $InfoFieldList[3]);
7098 $keyList .=
', '.$parentField;
7101 $filter_categorie =
false;
7102 if (count($InfoFieldList) > 5) {
7103 if ($InfoFieldList[0] ==
'categorie') {
7104 $filter_categorie =
true;
7108 if ($filter_categorie ===
false) {
7109 $fields_label = explode(
'|', $InfoFieldList[1]);
7110 if (is_array($fields_label)) {
7112 $keyList .= implode(
', ', $fields_label);
7116 $sql =
"SELECT " . $keyList;
7117 $sql .=
" FROM " . $this->db->prefix() . $InfoFieldList[0];
7118 if (!empty($InfoFieldList[4])) {
7120 if (strpos($InfoFieldList[4],
'$SEL$') !==
false) {
7121 $InfoFieldList[4] = str_replace(
'$SEL$',
'SELECT', $InfoFieldList[4]);
7125 if (strpos($InfoFieldList[4],
'$ID$') !==
false && !empty($objectid)) {
7126 $InfoFieldList[4] = str_replace(
'$ID$', $objectid, $InfoFieldList[4]);
7128 $InfoFieldList[4] = str_replace(
'$ID$',
'0', $InfoFieldList[4]);
7132 if (strpos($InfoFieldList[4],
'extra') !==
false) {
7133 $sql .=
" as main, " . $this->db->prefix() . $InfoFieldList[0] .
"_extrafields as extra";
7134 $sqlwhere .=
" WHERE extra.fk_object=main." . $InfoFieldList[2] .
" AND " . $InfoFieldList[4];
7136 $sqlwhere .=
" WHERE " . $InfoFieldList[4];
7139 $sqlwhere .=
' WHERE 1=1';
7142 if (in_array($InfoFieldList[0], array(
'tablewithentity'))) {
7143 $sqlwhere .=
" AND entity = " . ((int) $conf->entity);
7148 $sql .=
' ORDER BY ' . implode(
', ', $fields_label);
7150 dol_syslog(get_class($this) .
'::showInputField type=sellist', LOG_DEBUG);
7151 $resql = $this->db->query($sql);
7153 $out .=
'<option value="0"> </option>';
7154 $num = $this->db->num_rows($resql);
7158 $obj = $this->db->fetch_object($resql);
7162 $fields_label = explode(
'|', $InfoFieldList[1]);
7163 if (count($fields_label) > 1) {
7165 foreach ($fields_label as $field_toshow) {
7166 $labeltoshow .= $obj->$field_toshow .
' ';
7169 $labeltoshow = $obj->{$InfoFieldList[1]};
7171 $labeltoshow =
dol_trunc($labeltoshow, 45);
7173 if ($value == $obj->rowid) {
7174 foreach ($fields_label as $field_toshow) {
7175 $translabel = $langs->trans($obj->$field_toshow);
7176 if ($translabel != $obj->$field_toshow) {
7177 $labeltoshow =
dol_trunc($translabel) .
' ';
7179 $labeltoshow =
dol_trunc($obj->$field_toshow) .
' ';
7182 $out .=
'<option value="' . $obj->rowid .
'" selected>' . $labeltoshow .
'</option>';
7185 $translabel = $langs->trans($obj->{$InfoFieldList[1]});
7186 if ($translabel != $obj->{$InfoFieldList[1]}) {
7187 $labeltoshow =
dol_trunc($translabel, 18);
7189 $labeltoshow =
dol_trunc($obj->{$InfoFieldList[1]});
7192 if (empty($labeltoshow)) {
7193 $labeltoshow =
'(not defined)';
7195 if ($value == $obj->rowid) {
7196 $out .=
'<option value="' . $obj->rowid .
'" selected>' . $labeltoshow .
'</option>';
7199 if (!empty($InfoFieldList[3]) && $parentField) {
7200 $parent = $parentName .
':' . $obj->{$parentField};
7204 $out .=
'<option value="' . $obj->rowid .
'"';
7205 $out .= ($value == $obj->rowid ?
' selected' :
'');
7206 $out .= (!empty($parent) ?
' parent="' . $parent .
'"' :
'');
7207 $out .=
'>' . $labeltoshow .
'</option>';
7212 $this->db->free($resql);
7214 print
'Error in request ' . $sql .
' ' . $this->db->lasterror() .
'. Check setup of extra parameters.<br>';
7217 require_once DOL_DOCUMENT_ROOT.
'/categories/class/categorie.class.php';
7218 $data = $form->select_all_categories(Categorie::$MAP_ID_TO_CODE[$InfoFieldList[5]],
'',
'parent', 64, $InfoFieldList[6], 1, 1);
7219 $out .=
'<option value="0"> </option>';
7220 foreach ($data as $data_key => $data_value) {
7221 $out .=
'<option value="' . $data_key .
'"';
7222 $out .= ($value == $data_key ?
' selected' :
'');
7223 $out .=
'>' . $data_value .
'</option>';
7227 $out .=
'</select>';
7228 } elseif ($type ==
'checkbox') {
7229 $value_arr = explode(
',', $value);
7230 $out = $form->multiselectarray($keyprefix.$key.$keysuffix, (empty($param[
'options']) ?
null:$param[
'options']), $value_arr,
'', 0, $morecss, 0,
'100%');
7231 } elseif ($type ==
'radio') {
7233 foreach ($param[
'options'] as $keyopt => $valopt) {
7234 $out .=
'<input class="flat '.$morecss.
'" type="radio" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" '.($moreparam ? $moreparam :
'');
7235 $out .=
' value="'.$keyopt.
'"';
7236 $out .=
' id="'.$keyprefix.$key.$keysuffix.
'_'.$keyopt.
'"';
7237 $out .= ($value == $keyopt ?
'checked' :
'');
7238 $out .=
'/><label for="'.$keyprefix.$key.$keysuffix.
'_'.$keyopt.
'">'.$valopt.
'</label><br>';
7240 } elseif ($type ==
'chkbxlst') {
7241 if (is_array($value)) {
7242 $value_arr = $value;
7244 $value_arr = explode(
',', $value);
7247 if (is_array($param[
'options'])) {
7248 $param_list = array_keys($param[
'options']);
7249 $InfoFieldList = explode(
":", $param_list[0]);
7259 $keyList = (empty($InfoFieldList[2]) ?
'rowid' : $InfoFieldList[2].
' as rowid');
7261 if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
7262 list ($parentName, $parentField) = explode(
'|', $InfoFieldList[3]);
7263 $keyList .=
', '.$parentField;
7265 if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
7266 if (strpos($InfoFieldList[4],
'extra.') !==
false) {
7267 $keyList =
'main.'.$InfoFieldList[2].
' as rowid';
7269 $keyList = $InfoFieldList[2].
' as rowid';
7273 $filter_categorie =
false;
7274 if (count($InfoFieldList) > 5) {
7275 if ($InfoFieldList[0] ==
'categorie') {
7276 $filter_categorie =
true;
7280 if ($filter_categorie ===
false) {
7281 $fields_label = explode(
'|', $InfoFieldList[1]);
7282 if (is_array($fields_label)) {
7284 $keyList .= implode(
', ', $fields_label);
7288 $sql =
"SELECT " . $keyList;
7289 $sql .=
' FROM ' . $this->db->prefix() . $InfoFieldList[0];
7290 if (!empty($InfoFieldList[4])) {
7292 if (strpos($InfoFieldList[4],
'$SEL$') !==
false) {
7293 $InfoFieldList[4] = str_replace(
'$SEL$',
'SELECT', $InfoFieldList[4]);
7297 if (strpos($InfoFieldList[4],
'$ID$') !==
false && !empty($objectid)) {
7298 $InfoFieldList[4] = str_replace(
'$ID$', $objectid, $InfoFieldList[4]);
7300 $InfoFieldList[4] = str_replace(
'$ID$',
'0', $InfoFieldList[4]);
7304 if (strpos($InfoFieldList[4],
'extra') !==
false) {
7305 $sql .=
' as main, ' . $this->db->prefix() . $InfoFieldList[0] .
'_extrafields as extra';
7306 $sqlwhere .=
" WHERE extra.fk_object=main." . $InfoFieldList[2] .
" AND " . $InfoFieldList[4];
7308 $sqlwhere .=
" WHERE " . $InfoFieldList[4];
7311 $sqlwhere .=
' WHERE 1=1';
7314 if (in_array($InfoFieldList[0], array(
'tablewithentity'))) {
7315 $sqlwhere .=
" AND entity = " . ((int) $conf->entity);
7321 dol_syslog(get_class($this) .
'::showInputField type=chkbxlst', LOG_DEBUG);
7322 $resql = $this->db->query($sql);
7324 $num = $this->db->num_rows($resql);
7331 $obj = $this->db->fetch_object($resql);
7335 $fields_label = explode(
'|', $InfoFieldList[1]);
7336 if (count($fields_label) > 1) {
7338 foreach ($fields_label as $field_toshow) {
7339 $labeltoshow .= $obj->$field_toshow .
' ';
7342 $labeltoshow = $obj->{$InfoFieldList[1]};
7344 $labeltoshow =
dol_trunc($labeltoshow, 45);
7346 if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
7347 foreach ($fields_label as $field_toshow) {
7348 $translabel = $langs->trans($obj->$field_toshow);
7349 if ($translabel != $obj->$field_toshow) {
7350 $labeltoshow =
dol_trunc($translabel, 18) .
' ';
7352 $labeltoshow =
dol_trunc($obj->$field_toshow, 18) .
' ';
7356 $data[$obj->rowid] = $labeltoshow;
7359 $translabel = $langs->trans($obj->{$InfoFieldList[1]});
7360 if ($translabel != $obj->{$InfoFieldList[1]}) {
7361 $labeltoshow =
dol_trunc($translabel, 18);
7363 $labeltoshow =
dol_trunc($obj->{$InfoFieldList[1]}, 18);
7366 if (empty($labeltoshow)) {
7367 $labeltoshow =
'(not defined)';
7370 if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
7371 $data[$obj->rowid] = $labeltoshow;
7374 if (!empty($InfoFieldList[3]) && $parentField) {
7375 $parent = $parentName .
':' . $obj->{$parentField};
7379 $data[$obj->rowid] = $labeltoshow;
7384 $this->db->free($resql);
7386 $out = $form->multiselectarray($keyprefix . $key . $keysuffix, $data, $value_arr,
'', 0, $morecss, 0,
'100%');
7388 print
'Error in request ' . $sql .
' ' . $this->db->lasterror() .
'. Check setup of extra parameters.<br>';
7391 require_once DOL_DOCUMENT_ROOT.
'/categories/class/categorie.class.php';
7392 $data = $form->select_all_categories(Categorie::$MAP_ID_TO_CODE[$InfoFieldList[5]],
'',
'parent', 64, $InfoFieldList[6], 1, 1);
7393 $out = $form->multiselectarray($keyprefix . $key . $keysuffix, $data, $value_arr,
'', 0, $morecss, 0,
'100%');
7396 } elseif ($type ==
'link') {
7397 $param_list = array_keys($param[
'options']);
7398 $param_list_array = explode(
':', $param_list[0]);
7399 $showempty = (($required && $default !=
'') ? 0 : 1);
7401 if (!preg_match(
'/search_/', $keyprefix)) {
7402 if (!empty($param_list_array[2])) {
7403 if (!empty($this->fields[$key][
'picto'])) {
7404 $morecss .=
' widthcentpercentminusxx';
7406 $morecss .=
' widthcentpercentminusx';
7409 if (!empty($this->fields[$key][
'picto'])) {
7410 $morecss .=
' widthcentpercentminusx';
7415 $out = $form->selectForForms($param_list[0], $keyprefix.$key.$keysuffix, $value, $showempty,
'',
'', $morecss, $moreparam, 0, empty($val[
'disabled']) ? 0 : 1);
7417 if (!empty($param_list_array[2])) {
7418 if ((!GETPOSTISSET(
'backtopage') || strpos(
GETPOST(
'backtopage'), $_SERVER[
'PHP_SELF']) === 0)
7419 && empty($val[
'disabled']) && empty($nonewbutton)) {
7420 list($class, $classfile) = explode(
':', $param_list[0]);
7421 if (file_exists(
dol_buildpath(dirname(dirname($classfile)).
'/card.php'))) {
7422 $url_path =
dol_buildpath(dirname(dirname($classfile)).
'/card.php', 1);
7424 $url_path =
dol_buildpath(dirname(dirname($classfile)).
'/'.strtolower($class).
'_card.php', 1);
7426 $paramforthenewlink =
'';
7427 $paramforthenewlink .= (GETPOSTISSET(
'action') ?
'&action='.GETPOST(
'action',
'aZ09') :
'');
7428 $paramforthenewlink .= (GETPOSTISSET(
'id') ?
'&id='.GETPOST(
'id',
'int') :
'');
7429 $paramforthenewlink .= (GETPOSTISSET(
'origin') ?
'&origin='.GETPOST(
'origin',
'aZ09') :
'');
7430 $paramforthenewlink .= (GETPOSTISSET(
'originid') ?
'&originid='.GETPOST(
'originid',
'int') :
'');
7431 $paramforthenewlink .=
'&fk_'.strtolower($class).
'=--IDFORBACKTOPAGE--';
7433 $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>';
7436 } elseif ($type ==
'password') {
7438 $out =
'<input type="'.($keyprefix ==
'search_' ?
'text' :
'password').
'" class="flat '.$morecss.
'" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'" value="'.$value.
'" '.($moreparam ? $moreparam :
'').
'>';
7439 } elseif ($type ==
'array') {
7441 $newval[
'type'] =
'varchar(256)';
7444 if (!empty($value)) {
7445 foreach ($value as $option) {
7446 $out .=
'<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).
'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
7447 $out .= $this->showInputField($newval, $keyprefix.$key.$keysuffix.
'[]', $option, $moreparam,
'',
'', $morecss).
'<br></span>';
7450 $out .=
'<a id="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).
'_add" href="javascript:;"><span class="fa fa-plus-circle valignmiddle"></span></a>';
7452 $newInput =
'<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).
'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
7453 $newInput .= $this->showInputField($newval, $keyprefix.$key.$keysuffix.
'[]',
'', $moreparam,
'',
'', $morecss).
'<br></span>';
7455 if (!empty($conf->use_javascript_ajax)) {
7457 <script nonce="'.getNonce().
'">
7458 $(document).ready(function() {
7459 $("a#'.
dol_escape_js($keyprefix.$key.$keysuffix).
'_add").click(function() {
7463 $(document).on("click", "a.'.
dol_escape_js($keyprefix.$key.$keysuffix).
'_del", function() {
7464 $(this).parent().remove();
7470 if (!empty($hidden)) {
7471 $out =
'<input type="hidden" value="'.$value.
'" name="'.$keyprefix.$key.$keysuffix.
'" id="'.$keyprefix.$key.$keysuffix.
'"/>';
7474 if ($isDependList==1) {
7475 $out .= $this->getJSListDependancies(
'_common');
7483 if (!empty($fieldValidationErrorMsg) && function_exists(
'getFieldErrorIcon')) {
7484 $out .=
' '.getFieldErrorIcon($fieldValidationErrorMsg);
7503 public function showOutputField($val, $key, $value, $moreparam =
'', $keysuffix =
'', $keyprefix =
'', $morecss =
'')
7505 global $conf, $langs, $form;
7507 if (!is_object($form)) {
7508 require_once DOL_DOCUMENT_ROOT.
'/core/class/html.form.class.php';
7509 $form =
new Form($this->db);
7512 $label = empty($val[
'label']) ?
'' : $val[
'label'];
7513 $type = empty($val[
'type']) ?
'' : $val[
'type'];
7514 $size = empty($val[
'css']) ?
'' : $val[
'css'];
7518 if (preg_match(
'/varchar\((\d+)\)/', $type, $reg)) {
7521 } elseif (preg_match(
'/varchar/', $type)) {
7524 if (!empty($val[
'arrayofkeyval']) && is_array($val[
'arrayofkeyval'])) {
7527 if (preg_match(
'/^integer:(.*):(.*)/i', $val[
'type'], $reg)) {
7531 $default = empty($val[
'default']) ?
'' : $val[
'default'];
7532 $computed = empty($val[
'computed']) ?
'' : $val[
'computed'];
7533 $unique = empty($val[
'unique']) ?
'' : $val[
'unique'];
7534 $required = empty($val[
'required']) ?
'' : $val[
'required'];
7536 $param[
'options'] = array();
7538 if (!empty($val[
'arrayofkeyval']) && is_array($val[
'arrayofkeyval'])) {
7539 $param[
'options'] = $val[
'arrayofkeyval'];
7541 if (preg_match(
'/^integer:(.*):(.*)/i', $val[
'type'], $reg)) {
7543 $stringforoptions = $reg[1].
':'.$reg[2];
7544 if ($reg[1] ==
'User') {
7545 $stringforoptions .=
':-1';
7547 $param[
'options'] = array($stringforoptions => $stringforoptions);
7548 } elseif (preg_match(
'/^sellist:(.*):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
7549 $param[
'options'] = array($reg[1].
':'.$reg[2].
':'.$reg[3].
':'.$reg[4] =>
'N');
7551 } elseif (preg_match(
'/^sellist:(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
7552 $param[
'options'] = array($reg[1].
':'.$reg[2].
':'.$reg[3] =>
'N');
7554 } elseif (preg_match(
'/^sellist:(.*):(.*)/i', $val[
'type'], $reg)) {
7555 $param[
'options'] = array($reg[1].
':'.$reg[2] =>
'N');
7557 } elseif (preg_match(
'/^chkbxlst:(.*)/i', $val[
'type'], $reg)) {
7558 $param[
'options'] = array($reg[1] =>
'N');
7562 $langfile = empty($val[
'langfile']) ?
'' : $val[
'langfile'];
7563 $list = (empty($val[
'list']) ?
'' : $val[
'list']);
7564 $help = (empty($val[
'help']) ?
'' : $val[
'help']);
7565 $hidden = (($val[
'visible'] == 0) ? 1 : 0);
7575 $value =
dol_eval($computed, 1, 0,
'');
7578 if (empty($morecss)) {
7579 if ($type ==
'date') {
7580 $morecss =
'minwidth100imp';
7581 } elseif ($type ==
'datetime' || $type ==
'timestamp') {
7582 $morecss =
'minwidth200imp';
7583 } elseif (in_array($type, array(
'int',
'double',
'price'))) {
7584 $morecss =
'maxwidth75';
7585 } elseif ($type ==
'url') {
7586 $morecss =
'minwidth400';
7587 } elseif ($type ==
'boolean') {
7590 if (is_numeric($size) && round($size) < 12) {
7591 $morecss =
'minwidth100';
7592 } elseif (is_numeric($size) && round($size) <= 48) {
7593 $morecss =
'minwidth200';
7595 $morecss =
'minwidth400';
7601 if (in_array($key, array(
'rowid',
'ref')) && method_exists($this,
'getNomUrl')) {
7602 if ($key !=
'rowid' || empty($this->fields[
'ref'])) {
7603 $value = $this->getNomUrl(1,
'', 0,
'', 1);
7605 } elseif ($key ==
'status' && method_exists($this,
'getLibStatut')) {
7606 $value = $this->getLibStatut(3);
7607 } elseif ($type ==
'date') {
7608 if (!empty($value)) {
7613 } elseif ($type ==
'datetime' || $type ==
'timestamp') {
7614 if (!empty($value)) {
7619 } elseif ($type ==
'duration') {
7620 include_once DOL_DOCUMENT_ROOT.
'/core/lib/date.lib.php';
7621 if (!is_null($value) && $value !==
'') {
7624 } elseif ($type ==
'double' || $type ==
'real') {
7625 if (!is_null($value) && $value !==
'') {
7626 $value =
price($value);
7628 } elseif ($type ==
'boolean') {
7630 if (!empty($value)) {
7631 $checked =
' checked ';
7633 $value =
'<input type="checkbox" '.$checked.
' '.($moreparam ? $moreparam :
'').
' readonly disabled>';
7634 } elseif ($type ==
'mail' || $type ==
'email') {
7636 } elseif ($type ==
'url') {
7638 } elseif ($type ==
'phone') {
7640 } elseif ($type ==
'ip') {
7642 } elseif ($type ==
'price') {
7643 if (!is_null($value) && $value !==
'') {
7644 $value =
price($value, 0, $langs, 0, 0, -1, $conf->currency);
7646 } elseif ($type ==
'select') {
7647 $value = isset($param[
'options'][$value])?$param[
'options'][$value]:
'';
7648 } elseif ($type ==
'sellist') {
7649 $param_list = array_keys($param[
'options']);
7650 $InfoFieldList = explode(
":", $param_list[0]);
7652 $selectkey =
"rowid";
7655 if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
7656 $selectkey = $InfoFieldList[2];
7657 $keyList = $InfoFieldList[2].
' as rowid';
7660 $fields_label = explode(
'|', $InfoFieldList[1]);
7661 if (is_array($fields_label)) {
7663 $keyList .= implode(
', ', $fields_label);
7666 $filter_categorie =
false;
7667 if (count($InfoFieldList) > 5) {
7668 if ($InfoFieldList[0] ==
'categorie') {
7669 $filter_categorie =
true;
7673 $sql =
"SELECT ".$keyList;
7674 $sql .=
' FROM '.$this->db->prefix().$InfoFieldList[0];
7675 if (strpos($InfoFieldList[4],
'extra') !==
false) {
7678 if ($selectkey ==
'rowid' && empty($value)) {
7679 $sql .=
" WHERE ".$selectkey.
" = 0";
7680 } elseif ($selectkey ==
'rowid') {
7681 $sql .=
" WHERE ".$selectkey.
" = ".((int) $value);
7683 $sql .=
" WHERE ".$selectkey.
" = '".$this->db->escape($value).
"'";
7688 dol_syslog(get_class($this).
':showOutputField:$type=sellist', LOG_DEBUG);
7689 $resql = $this->db->query($sql);
7691 if ($filter_categorie ===
false) {
7693 $numrows = $this->db->num_rows($resql);
7695 $obj = $this->db->fetch_object($resql);
7698 $fields_label = explode(
'|', $InfoFieldList[1]);
7700 if (is_array($fields_label) && count($fields_label) > 1) {
7701 foreach ($fields_label as $field_toshow) {
7703 if (!empty($obj->$field_toshow)) {
7704 $translabel = $langs->trans($obj->$field_toshow);
7706 if ($translabel != $field_toshow) {
7707 $value .=
dol_trunc($translabel, 18) .
' ';
7709 $value .= $obj->$field_toshow .
' ';
7714 if (!empty($obj->{$InfoFieldList[1]})) {
7715 $translabel = $langs->trans($obj->{$InfoFieldList[1]});
7717 if ($translabel != $obj->{$InfoFieldList[1]}) {
7720 $value = $obj->{$InfoFieldList[1]};
7725 require_once DOL_DOCUMENT_ROOT .
'/categories/class/categorie.class.php';
7728 $obj = $this->db->fetch_object($resql);
7730 $c->fetch($obj->rowid);
7731 $ways = $c->print_all_ways();
7732 foreach ($ways as $way) {
7733 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories"' . ($c->color ?
' style="background: #' . $c->color .
';"' :
' style="background: #aaa"') .
'>' .
img_object(
'',
'category') .
' ' . $way .
'</li>';
7735 $value =
'<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(
' ', $toprint).
'</ul></div>';
7738 dol_syslog(get_class($this).
'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
7740 } elseif ($type ==
'radio') {
7741 $value = $param[
'options'][$value];
7742 } elseif ($type ==
'checkbox') {
7743 $value_arr = explode(
',', $value);
7745 if (is_array($value_arr) && count($value_arr) > 0) {
7747 foreach ($value_arr as $keyval => $valueval) {
7748 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">'.$param[
'options'][$valueval].
'</li>';
7750 $value =
'<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(
' ', $toprint).
'</ul></div>';
7752 } elseif ($type ==
'chkbxlst') {
7753 $value_arr = explode(
',', $value);
7755 $param_list = array_keys($param[
'options']);
7756 $InfoFieldList = explode(
":", $param_list[0]);
7758 $selectkey =
"rowid";
7761 if (count($InfoFieldList) >= 3) {
7762 $selectkey = $InfoFieldList[2];
7763 $keyList = $InfoFieldList[2].
' as rowid';
7766 $fields_label = explode(
'|', $InfoFieldList[1]);
7767 if (is_array($fields_label)) {
7769 $keyList .= implode(
', ', $fields_label);
7772 $filter_categorie =
false;
7773 if (count($InfoFieldList) > 5) {
7774 if ($InfoFieldList[0] ==
'categorie') {
7775 $filter_categorie =
true;
7779 $sql =
"SELECT ".$keyList;
7780 $sql .=
' FROM '.$this->db->prefix().$InfoFieldList[0];
7781 if (strpos($InfoFieldList[4],
'extra') !==
false) {
7787 dol_syslog(get_class($this).
':showOutputField:$type=chkbxlst', LOG_DEBUG);
7788 $resql = $this->db->query($sql);
7790 if ($filter_categorie ===
false) {
7793 while ($obj = $this->db->fetch_object($resql)) {
7795 $fields_label = explode(
'|', $InfoFieldList[1]);
7796 if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
7797 if (is_array($fields_label) && count($fields_label) > 1) {
7798 foreach ($fields_label as $field_toshow) {
7800 if (!empty($obj->$field_toshow)) {
7801 $translabel = $langs->trans($obj->$field_toshow);
7803 if ($translabel != $field_toshow) {
7804 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' .
dol_trunc($translabel, 18) .
'</li>';
7806 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' . $obj->$field_toshow .
'</li>';
7811 if (!empty($obj->{$InfoFieldList[1]})) {
7812 $translabel = $langs->trans($obj->{$InfoFieldList[1]});
7814 if ($translabel != $obj->{$InfoFieldList[1]}) {
7815 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' .
dol_trunc($translabel, 18) .
'</li>';
7817 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' . $obj->{$InfoFieldList[1]} .
'</li>';
7823 require_once DOL_DOCUMENT_ROOT .
'/categories/class/categorie.class.php';
7826 while ($obj = $this->db->fetch_object($resql)) {
7827 if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
7829 $c->fetch($obj->rowid);
7830 $ways = $c->print_all_ways();
7831 foreach ($ways as $way) {
7832 $toprint[] =
'<li class="select2-search-choice-dolibarr noborderoncategories"' . ($c->color ?
' style="background: #' . $c->color .
';"' :
' style="background: #aaa"') .
'>' .
img_object(
'',
'category') .
' ' . $way .
'</li>';
7837 $value =
'<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(
' ', $toprint).
'</ul></div>';
7839 dol_syslog(get_class($this).
'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
7841 } elseif ($type ==
'link') {
7846 $param_list = array_keys($param[
'options']);
7848 $InfoFieldList = explode(
":", $param_list[0]);
7849 $classname = $InfoFieldList[0];
7850 $classpath = $InfoFieldList[1];
7851 $getnomurlparam = (empty($InfoFieldList[2]) ? 3 : $InfoFieldList[2]);
7852 $getnomurlparam2 = (empty($InfoFieldList[4]) ?
'' : $InfoFieldList[4]);
7853 if (!empty($classpath)) {
7855 if ($classname && class_exists($classname)) {
7856 $object =
new $classname($this->db);
7857 if ($object->element ===
'product') {
7858 $result = $object->fetch($value,
'',
'',
'', 0, 1, 1);
7860 $result = $object->fetch($value);
7863 if ($object->element ===
'product') {
7864 $get_name_url_param_arr = array($getnomurlparam, $getnomurlparam2, 0, -1, 0,
'', 0);
7865 if (isset($val[
'get_name_url_params'])) {
7866 $get_name_url_params = explode(
':', $val[
'get_name_url_params']);
7867 if (!empty($get_name_url_params)) {
7868 $param_num_max = count($get_name_url_param_arr) - 1;
7869 foreach ($get_name_url_params as $param_num => $param_value) {
7870 if ($param_num > $param_num_max) {
7873 $get_name_url_param_arr[$param_num] = $param_value;
7881 $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]);
7883 $value = $object->getNomUrl($getnomurlparam, $getnomurlparam2);
7890 dol_syslog(
'Error bad setup of extrafield', LOG_WARNING);
7891 return 'Error bad setup of extrafield';
7896 } elseif ($type ==
'password') {
7897 $value = preg_replace(
'/./i',
'*', $value);
7898 } elseif ($type ==
'array') {
7899 $value = implode(
'<br>', $value);
7919 unset($this->validateFieldsErrors[$fieldKey]);
7933 $msg = $langs->trans(
"UnknowError");
7936 $this->error = $this->validateFieldsErrors[$fieldKey] = $msg;
7947 if (!empty($this->validateFieldsErrors[$fieldKey])) {
7948 return $this->validateFieldsErrors[$fieldKey];
7965 if (!class_exists(
'Validate')) {
7966 require_once DOL_DOCUMENT_ROOT .
'/core/class/validate.class.php';
7969 $this->clearFieldError($fieldKey);
7971 if (!isset($fields[$fieldKey])) {
7972 $this->setFieldError($fieldKey, $langs->trans(
'FieldNotFoundInObject'));
7976 $val = $fields[$fieldKey];
7979 $param[
'options'] = array();
7980 $type = $val[
'type'];
7983 if (isset($val[
'notnull']) && $val[
'notnull'] === 1) {
7997 if (preg_match(
'/varchar\((\d+)\)/', $type, $reg)) {
8000 } elseif (preg_match(
'/varchar/', $type)) {
8004 if (!empty($val[
'arrayofkeyval']) && is_array($val[
'arrayofkeyval'])) {
8008 if (!empty($val[
'type']) && preg_match(
'/^integer:(.*):(.*)/i', $val[
'type'], $reg)) {
8012 if (!empty($val[
'arrayofkeyval']) && is_array($val[
'arrayofkeyval'])) {
8013 $param[
'options'] = $val[
'arrayofkeyval'];
8016 if (preg_match(
'/^integer:(.*):(.*)/i', $val[
'type'], $reg)) {
8018 $param[
'options'] = array($reg[1].
':'.$reg[2]=>$reg[1].
':'.$reg[2]);
8019 } elseif (preg_match(
'/^sellist:(.*):(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
8020 $param[
'options'] = array($reg[1].
':'.$reg[2].
':'.$reg[3].
':'.$reg[4] =>
'N');
8022 } elseif (preg_match(
'/^sellist:(.*):(.*):(.*)/i', $val[
'type'], $reg)) {
8023 $param[
'options'] = array($reg[1].
':'.$reg[2].
':'.$reg[3] =>
'N');
8025 } elseif (preg_match(
'/^sellist:(.*):(.*)/i', $val[
'type'], $reg)) {
8026 $param[
'options'] = array($reg[1].
':'.$reg[2] =>
'N');
8035 $validate =
new Validate($this->db, $langs);
8045 if ($required && !$validate->isNotEmptyString($fieldValue)) {
8046 $this->setFieldError($fieldKey, $validate->error);
8048 } elseif (!$required && !$validate->isNotEmptyString($fieldValue)) {
8054 if (!empty($maxSize) && !$validate->isMaxLength($fieldValue, $maxSize)) {
8055 $this->setFieldError($fieldKey, $validate->error);
8060 if (!empty($minSize) && !$validate->isMinLength($fieldValue, $minSize)) {
8061 $this->setFieldError($fieldKey, $validate->error);
8069 if (in_array($type, array(
'date',
'datetime',
'timestamp'))) {
8070 if (!$validate->isTimestamp($fieldValue)) {
8071 $this->setFieldError($fieldKey, $validate->error);
8073 }
else {
return true; }
8074 } elseif ($type ==
'duration') {
8075 if (!$validate->isDuration($fieldValue)) {
8076 $this->setFieldError($fieldKey, $validate->error);
8078 }
else {
return true; }
8079 } elseif (in_array($type, array(
'double',
'real',
'price'))) {
8081 if (!$validate->isNumeric($fieldValue)) {
8082 $this->setFieldError($fieldKey, $validate->error);
8084 }
else {
return true; }
8085 } elseif ($type ==
'boolean') {
8086 if (!$validate->isBool($fieldValue)) {
8087 $this->setFieldError($fieldKey, $validate->error);
8089 }
else {
return true; }
8090 } elseif ($type ==
'mail') {
8091 if (!$validate->isEmail($fieldValue)) {
8092 $this->setFieldError($fieldKey, $validate->error);
8095 } elseif ($type ==
'url') {
8096 if (!$validate->isUrl($fieldValue)) {
8097 $this->setFieldError($fieldKey, $validate->error);
8099 }
else {
return true; }
8100 } elseif ($type ==
'phone') {
8101 if (!$validate->isPhone($fieldValue)) {
8102 $this->setFieldError($fieldKey, $validate->error);
8104 }
else {
return true; }
8105 } elseif ($type ==
'select' || $type ==
'radio') {
8106 if (!isset($param[
'options'][$fieldValue])) {
8107 $this->error = $langs->trans(
'RequireValidValue');
8109 }
else {
return true; }
8110 } elseif ($type ==
'sellist' || $type ==
'chkbxlst') {
8111 $param_list = array_keys($param[
'options']);
8112 $InfoFieldList = explode(
":", $param_list[0]);
8113 $value_arr = explode(
',', $fieldValue);
8114 $value_arr = array_map(array($this->db,
'escape'), $value_arr);
8116 $selectkey =
"rowid";
8117 if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
8118 $selectkey = $InfoFieldList[2];
8121 if (!$validate->isInDb($value_arr, $InfoFieldList[0], $selectkey)) {
8122 $this->setFieldError($fieldKey, $validate->error);
8124 }
else {
return true; }
8125 } elseif ($type ==
'link') {
8126 $param_list = array_keys($param[
'options']);
8127 $InfoFieldList = explode(
":", $param_list[0]);
8128 $classname = $InfoFieldList[0];
8129 $classpath = $InfoFieldList[1];
8130 if (!$validate->isFetchable($fieldValue, $classname, $classpath)) {
8131 $this->setFieldError($fieldKey, $validate->error);
8133 }
else {
return true; }
8153 public function showOptionals($extrafields, $mode =
'view', $params =
null, $keysuffix =
'', $keyprefix =
'', $onetrtd = 0, $display_type =
'card')
8155 global $db, $conf, $langs, $action, $form, $hookmanager;
8157 if (!is_object($form)) {
8158 $form =
new Form($db);
8160 if (!is_object($extrafields)) {
8161 dol_syslog(
'Bad parameter extrafields for showOptionals', LOG_ERR);
8162 return 'Bad parameter extrafields for showOptionals';
8164 if (!is_array($extrafields->attributes[$this->table_element])) {
8165 dol_syslog(
"extrafields->attributes was not loaded with extrafields->fetch_name_optionals_label(table_element);", LOG_WARNING);
8170 $parameters = array(
'mode'=>$mode,
'params'=>$params,
'keysuffix'=>$keysuffix,
'keyprefix'=>$keyprefix,
'display_type'=>$display_type);
8171 $reshook = $hookmanager->executeHooks(
'showOptionals', $parameters, $this, $action);
8173 if (empty($reshook)) {
8174 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) {
8176 $out .=
'<!-- commonobject:showOptionals --> ';
8179 $nbofextrafieldsshown = 0;
8182 $lastseparatorkeyfound =
'';
8183 $extrafields_collapse_num =
'';
8184 $extrafields_collapse_num_old =
'';
8187 foreach ($extrafields->attributes[$this->table_element][
'label'] as $key => $label) {
8191 if (is_array($params) && array_key_exists(
'onlykey', $params) && $key != $params[
'onlykey']) {
8197 if ($enabled && isset($extrafields->attributes[$this->table_element][
'enabled'][$key])) {
8198 $enabled =
dol_eval($extrafields->attributes[$this->table_element][
'enabled'][$key], 1, 1,
'2');
8200 if (empty($enabled)) {
8205 if ($visibility && isset($extrafields->attributes[$this->table_element][
'list'][$key])) {
8206 $visibility =
dol_eval($extrafields->attributes[$this->table_element][
'list'][$key], 1, 1,
'2');
8210 if ($perms && isset($extrafields->attributes[$this->table_element][
'perms'][$key])) {
8211 $perms =
dol_eval($extrafields->attributes[$this->table_element][
'perms'][$key], 1, 1,
'2');
8214 if (($mode ==
'create') && abs($visibility) != 1 && abs($visibility) != 3) {
8216 } elseif (($mode ==
'edit') && abs($visibility) != 1 && abs($visibility) != 3 && abs($visibility) != 4) {
8218 $ef_name =
'options_' . $key;
8219 $ef_value = $this->array_options[$ef_name];
8220 $out .=
'<input type="hidden" name="' . $ef_name .
'" id="' . $ef_name .
'" value="' . $ef_value .
'" />' .
"\n";
8222 } elseif ($mode ==
'view' && empty($visibility)) {
8225 if (empty($perms)) {
8230 if (!empty($extrafields->attributes[$this->table_element][
'langfile'][$key])) {
8231 $langs->load($extrafields->attributes[$this->table_element][
'langfile'][$key]);
8235 if (is_array($params) && count($params) > 0 && $display_type==
'card') {
8236 if (array_key_exists(
'cols', $params)) {
8237 $colspan = $params[
'cols'];
8238 } elseif (array_key_exists(
'colspan', $params)) {
8240 if (preg_match(
'/colspan="(\d+)"/', $params[
'colspan'], $reg)) {
8243 $colspan = $params[
'colspan'];
8247 $colspan = intval($colspan);
8251 $value = ((!empty($this->array_options) && array_key_exists(
"options_".$key.$keysuffix, $this->array_options)) ? $this->array_options[
"options_".$key.$keysuffix] :
null);
8257 $check =
'alphanohtml';
8258 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'html',
'text'))) {
8259 $check =
'restricthtml';
8261 $getposttemp =
GETPOST($keyprefix.
'options_'.$key.$keysuffix, $check, 3);
8263 if (is_array($getposttemp) || $getposttemp !=
'' || GETPOSTISSET($keyprefix.
'options_'.$key.$keysuffix)) {
8264 if (is_array($getposttemp)) {
8266 $value = implode(
",", $getposttemp);
8268 $value = $getposttemp;
8271 $value = (!empty($this->array_options[
"options_".$key]) ? $this->array_options[
"options_".$key] :
'');
8277 $nbofextrafieldsshown++;
8280 if ($extrafields->attributes[$this->table_element][
'type'][$key] ==
'separate') {
8281 $extrafields_collapse_num = $key;
8299 $out .= $extrafields->showSeparator($key, $this, ($colspan ? $colspan + 1 : 2), $display_type, $mode);
8301 $lastseparatorkeyfound = $key;
8303 $collapse_group = $extrafields_collapse_num.(!empty($this->
id) ?
'_'.$this->id :
'');
8305 $class = (!empty($extrafields->attributes[$this->table_element][
'hidden'][$key]) ?
'hideobject ' :
'');
8307 if (is_array($params) && count($params) > 0) {
8308 if (array_key_exists(
'class', $params)) {
8309 $class .= $params[
'class'].
' ';
8311 if (array_key_exists(
'style', $params)) {
8312 $csstyle = $params[
'style'];
8317 $domData =
' data-element="extrafield"';
8318 $domData .=
' data-targetelement="'.$this->element.
'"';
8319 $domData .=
' data-targetid="'.$this->id.
'"';
8321 $html_id = (empty($this->
id) ?
'' :
'extrarow-'.$this->element.
'_'.$key.
'_'.$this->id);
8322 if ($display_type==
'card') {
8323 if (!empty($conf->global->MAIN_EXTRAFIELDS_USE_TWO_COLUMS) && ($e % 2) == 0) {
8327 if ($action ==
'selectlines') {
8333 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'date'))) {
8334 $datenotinstring =
null;
8335 if (array_key_exists(
'options_'.$key, $this->array_options)) {
8336 $datenotinstring = $this->array_options[
'options_'.$key];
8337 if (!is_numeric($this->array_options[
'options_'.$key])) {
8338 $datenotinstring = $this->db->jdate($datenotinstring);
8341 $datekey = $keyprefix.
'options_'.$key.$keysuffix;
8342 $value = (GETPOSTISSET($datekey) && $this->
id ==
GETPOST(
'elrowid',
'int')) ?
dol_mktime(12, 0, 0,
GETPOST($datekey.
'month',
'int', 3),
GETPOST($datekey.
'day',
'int', 3),
GETPOST($datekey.
'year',
'int', 3)) : $datenotinstring;
8344 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'datetime'))) {
8345 $datenotinstring =
null;
8346 if (array_key_exists(
'options_'.$key, $this->array_options)) {
8347 $datenotinstring = $this->array_options[
'options_'.$key];
8348 if (!is_numeric($this->array_options[
'options_'.$key])) {
8349 $datenotinstring = $this->db->jdate($datenotinstring);
8352 $timekey = $keyprefix.
'options_'.$key.$keysuffix;
8353 $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;
8356 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'price',
'double'))) {
8357 if (GETPOSTISSET($keyprefix.
'options_'.$key.$keysuffix) || $value) {
8359 } elseif (isset($this->array_options[
'options_'.$key])) {
8360 $value = $this->array_options[
'options_'.$key];
8365 if (in_array($extrafields->attributes[$this->table_element][
'type'][$key], array(
'html',
'text',
'varchar',
'select',
'radio',
'int',
'boolean'))) {
8366 if ($action ==
'create') {
8367 $value = (GETPOSTISSET($keyprefix.
'options_'.$key.$keysuffix) || $value) ? $value : $extrafields->attributes[$this->table_element][
'default'][$key];
8371 $labeltoshow = $langs->trans($label);
8372 $helptoshow = $langs->trans($extrafields->attributes[$this->table_element][
'help'][$key]);
8374 if ($display_type ==
'card') {
8375 $out .=
'<tr '.($html_id ?
'id="'.$html_id.
'" ' :
'').$csstyle.
' class="field_options_'.$key.
' '.$class.$this->element.
'_extras_'.$key.
' trextrafields_collapse'.$collapse_group.
'" '.$domData.
' >';
8376 if (!empty($conf->global->MAIN_VIEW_LINE_NUMBER) && ($action ==
'view' || $action ==
'valid' || $action ==
'editline' || $action ==
'confirm_valid' || $action ==
'confirm_cancel')) {
8377 $out .=
'<td></td>';
8379 $out .=
'<td class="'.(empty($params[
'tdclass']) ?
'titlefieldcreate' : $params[
'tdclass']).
' wordbreak';
8380 } elseif ($display_type ==
'line') {
8381 $out .=
'<div '.($html_id ?
'id="'.$html_id.
'" ' :
'').$csstyle.
' class="fieldline_options_'.$key.
' '.$class.$this->element.
'_extras_'.$key.
' trextrafields_collapse'.$collapse_group.
'" '.$domData.
' >';
8382 $out .=
'<div style="display: inline-block; padding-right:4px" class="wordbreak';
8387 $tpl_context = isset($params[
"tpl_context"]) ? $params[
"tpl_context"] :
"none";
8388 if ($tpl_context !=
"public") {
8389 if ($mode !=
'view' && !empty($extrafields->attributes[$this->table_element][
'required'][$key])) {
8390 $out .=
' fieldrequired';
8394 if ($tpl_context ==
"public") {
8395 if (!empty($extrafields->attributes[$this->table_element][
'help'][$key])) {
8396 $out .= $form->textwithpicto($labeltoshow, $helptoshow);
8398 $out .= $labeltoshow;
8400 if ($mode !=
'view' && !empty($extrafields->attributes[$this->table_element][
'required'][$key])) {
8401 $out .=
' <span style="color: red">*</span>';
8404 if (!empty($extrafields->attributes[$this->table_element][
'help'][$key])) {
8405 $out .= $form->textwithpicto($labeltoshow, $helptoshow);
8407 $out .= $labeltoshow;
8411 $out .= ($display_type ==
'card' ?
'</td>' :
'</div>');
8413 $html_id = !empty($this->
id) ? $this->element.
'_extras_'.$key.
'_'.$this->id :
'';
8414 if ($display_type ==
'card') {
8416 $out .=
'<td '.($html_id ?
'id="'.$html_id.
'" ' :
'').
' class="valuefieldcreate '.$this->element.
'_extras_'.$key.
'" '.($colspan ?
' colspan="'.$colspan.
'"' :
'').
'>';
8417 } elseif ($display_type ==
'line') {
8418 $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].
'">';
8423 $out .= $extrafields->showOutputField($key, $value,
'', $this->table_element);
8426 $out .= $extrafields->showInputField($key, $value,
'', $keysuffix,
'', 0, $this->
id, $this->table_element);
8429 $out .= $extrafields->showInputField($key, $value,
'', $keysuffix,
'', 0, $this->
id, $this->table_element);
8433 $out .= ($display_type==
'card' ?
'</td>' :
'</div>');
8435 if (!empty($conf->global->MAIN_EXTRAFIELDS_USE_TWO_COLUMS) && (($e % 2) == 1)) {
8436 $out .= ($display_type==
'card' ?
'</tr>' :
'</div>');
8438 $out .= ($display_type==
'card' ?
'</tr>' :
'</div>');
8446 if (!empty($conf->use_javascript_ajax)) {
8447 $out .= $this->getJSListDependancies();
8450 $out .=
'<!-- commonobject:showOptionals end --> '.
"\n";
8452 if (empty($nbofextrafieldsshown)) {
8458 $out .= $hookmanager->resPrint;
8470 <script nonce="'.getNonce().
'">
8471 jQuery(document).ready(function() {
8472 function showOptions'.$type.
'(child_list, parent_list, orig_select)
8474 var val = $("select[name=\""+parent_list+"\"]").val();
8475 var parentVal = parent_list + ":" + val;
8476 if(typeof val == "string"){
8478 var options = orig_select.find("option[parent=\""+parentVal+"\"]").clone();
8479 $("select[name=\""+child_list+"\"] option[parent]").remove();
8480 $("select[name=\""+child_list+"\"]").append(options);
8482 var options = orig_select.find("option[parent]").clone();
8483 $("select[name=\""+child_list+"\"] option[parent]").remove();
8484 $("select[name=\""+child_list+"\"]").append(options);
8486 } else if(val > 0) {
8487 var options = orig_select.find("option[parent=\""+parentVal+"\"]").clone();
8488 $("select[name=\""+child_list+"\"] option[parent]").remove();
8489 $("select[name=\""+child_list+"\"]").append(options);
8491 var options = orig_select.find("option[parent]").clone();
8492 $("select[name=\""+child_list+"\"] option[parent]").remove();
8493 $("select[name=\""+child_list+"\"]").append(options);
8496 function setListDependencies'.$type.
'() {
8497 jQuery("select option[parent]").parent().each(function() {
8498 var orig_select = {};
8499 var child_list = $(this).attr("name");
8500 orig_select[child_list] = $(this).clone();
8501 var parent = $(this).find("option[parent]:first").attr("parent");
8502 var infos = parent.split(":");
8503 var parent_list = infos[0];
8505 //Hide daughters lists
8506 if ($("#"+child_list).val() == 0 && $("#"+parent_list).val() == 0){
8507 $("#"+child_list).hide();
8509 } else if ($("#"+parent_list).val() != 0){
8510 $("#"+parent_list).show();
8512 //Show the child list if the parent list value is selected
8513 $("select[name=\""+parent_list+"\"]").click(function() {
8514 if ($(this).val() != 0){
8515 $("#"+child_list).show()
8519 //When we change parent list
8520 $("select[name=\""+parent_list+"\"]").change(function() {
8521 showOptions'.$type.
'(child_list, parent_list, orig_select[child_list]);
8522 //Select the value 0 on child list after a change on the parent list
8523 $("#"+child_list).val(0).trigger("change");
8524 //Hide child lists if the parent value is set to 0
8525 if ($(this).val() == 0){
8526 $("#"+child_list).hide();
8532 setListDependencies'.$type.
'();
8547 $module = empty($this->module) ?
'' : $this->module;
8548 $element = $this->element;
8550 if ($element ==
'facturerec') {
8551 $element =
'facture';
8552 } elseif ($element ==
'invoice_supplier_rec') {
8553 return empty($user->rights->fournisseur->facture) ? null : $user->rights->fournisseur->facture;
8554 } elseif ($module && !empty($user->rights->$module->$element)) {
8556 return $user->rights->$module->$element;
8559 return $user->rights->$element;
8576 foreach ($tables as $table) {
8577 $sql =
'UPDATE '.$dbs->prefix().$table.
' SET fk_soc = '.((int) $dest_id).
' WHERE fk_soc = '.((int) $origin_id);
8579 if (!$dbs->
query($sql)) {
8580 if ($ignoreerrors) {
8605 foreach ($tables as $table) {
8606 $sql =
'UPDATE '.MAIN_DB_PREFIX.$table.
' SET fk_product = '.((int) $dest_id).
' WHERE fk_product = '.((int) $origin_id);
8608 if (!$dbs->
query($sql)) {
8609 if ($ignoreerrors) {
8632 public function defineBuyPrice($unitPrice = 0.0, $discountPercent = 0.0, $fk_product = 0)
8638 if (($unitPrice > 0) && (isset($conf->global->ForceBuyingPriceIfNull) && $conf->global->ForceBuyingPriceIfNull > 0)) {
8640 $buyPrice = $unitPrice * (1 - $discountPercent / 100);
8643 if (!empty($fk_product) && $fk_product > 0) {
8644 if (isset($conf->global->MARGIN_TYPE) && $conf->global->MARGIN_TYPE ==
'costprice') {
8645 require_once DOL_DOCUMENT_ROOT.
'/product/class/product.class.php';
8646 $product =
new Product($this->db);
8647 $result = $product->fetch($fk_product);
8649 $this->errors[] =
'ErrorProductIdDoesNotExists';
8652 if ($product->cost_price > 0) {
8653 $buyPrice = $product->cost_price;
8654 } elseif ($product->pmp > 0) {
8655 $buyPrice = $product->pmp;
8657 } elseif (isset($conf->global->MARGIN_TYPE) && $conf->global->MARGIN_TYPE ==
'pmp') {
8658 require_once DOL_DOCUMENT_ROOT.
'/product/class/product.class.php';
8659 $product =
new Product($this->db);
8660 $result = $product->fetch($fk_product);
8662 $this->errors[] =
'ErrorProductIdDoesNotExists';
8665 if ($product->pmp > 0) {
8666 $buyPrice = $product->pmp;
8670 if (empty($buyPrice) && isset($conf->global->MARGIN_TYPE) && in_array($conf->global->MARGIN_TYPE, array(
'1',
'pmp',
'costprice'))) {
8671 require_once DOL_DOCUMENT_ROOT.
'/fourn/class/fournisseur.product.class.php';
8673 if (($result = $productFournisseur->find_min_price_product_fournisseur($fk_product)) > 0) {
8674 $buyPrice = $productFournisseur->fourn_unitprice;
8675 } elseif ($result < 0) {
8676 $this->errors[] = $productFournisseur->error;
8705 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')
8708 global $conf, $user, $langs;
8710 include_once DOL_DOCUMENT_ROOT.
'/core/lib/files.lib.php';
8711 include_once DOL_DOCUMENT_ROOT.
'/core/lib/images.lib.php';
8713 $sortfield =
'position_name';
8719 $dir .=
get_exdir(0, 0, 0, 0, $this, $modulepart);
8720 $pdir .=
get_exdir(0, 0, 0, 0, $this, $modulepart);
8723 if ($modulepart ==
'product') {
8725 $dir = $sdir.
'/'.
get_exdir($this->
id, 2, 0, 0, $this, $modulepart).$this->id.
"/photos/";
8726 $pdir =
'/'.get_exdir($this->
id, 2, 0, 0, $this, $modulepart).$this->id.
"/photos/";
8733 $relativedir = preg_replace(
'/^'.preg_quote(DOL_DATA_ROOT,
'/').
'/',
'', $dir);
8734 $relativedir = preg_replace(
'/^[\\/]/',
'', $relativedir);
8735 $relativedir = preg_replace(
'/[\\/]$/',
'', $relativedir);
8738 $dirthumb = $dir.
'thumbs/';
8739 $pdirthumb = $pdir.
'thumbs/';
8741 $return =
'<!-- Photo -->'.
"\n";
8744 $filearray =
dol_dir_list($dir,
"files", 0,
'',
'(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) ==
'desc' ?SORT_DESC:SORT_ASC), 1);
8754 if (count($filearray)) {
8755 if ($sortfield && $sortorder) {
8759 foreach ($filearray as $key => $val) {
8761 $file = $val[
'name'];
8767 $viewfilename = $file;
8769 if ($size == 1 || $size ==
'small') {
8776 $photo_vignette = basename($file);
8783 if ($nbphoto == 1) {
8784 $return .=
'<table class="valigntop center centpercent" style="border: 0; padding: 2px; border-spacing: 2px; border-collapse: separate;">';
8787 if ($nbphoto % $nbbyrow == 1) {
8788 $return .=
'<tr class="center valignmiddle" style="border: 1px">';
8790 $return .=
'<td style="width: '.ceil(100 / $nbbyrow).
'%" class="photo">'.
"\n";
8791 } elseif ($nbbyrow < 0) {
8792 $return .=
'<div class="inline-block">'.
"\n";
8795 $relativefile = preg_replace(
'/^\//',
'', $pdir.$photo);
8796 if (empty($nolink)) {
8799 $return .=
'<a href="'.$urladvanced.
'">';
8801 $return .=
'<a href="'.DOL_URL_ROOT.
'/viewimage.php?modulepart='.$modulepart.
'&entity='.$this->entity.
'&file='.urlencode($pdir.$photo).
'" class="aphoto" target="_blank" rel="noopener noreferrer">';
8807 $alt = $langs->transnoentitiesnoconv(
'File').
': '.$relativefile;
8808 $alt .=
' - '.$langs->transnoentitiesnoconv(
'Size').
': '.$imgarray[
'width'].
'x'.$imgarray[
'height'];
8809 if ($overwritetitle) {
8810 if (is_numeric($overwritetitle)) {
8813 $alt = $overwritetitle;
8817 if ($usesharelink) {
8818 if ($val[
'share']) {
8819 if (empty($maxHeight) || ($photo_vignette && $imgarray[
'height'] > $maxHeight)) {
8820 $return .=
'<!-- Show original file (thumb not yet available with shared links) -->';
8821 $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).
'">';
8823 $return .=
'<!-- Show original file -->';
8824 $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).
'">';
8827 $return .=
'<!-- Show nophoto file (because file is not shared) -->';
8828 $return .=
'<img class="photo photowithmargin'.($addphotorefcss ?
' '.$addphotorefcss :
'').
'" height="'.$maxHeight.
'" src="'.DOL_URL_ROOT.
'/public/theme/common/nophoto.png" title="'.
dol_escape_htmltag($alt).
'">';
8831 if (empty($maxHeight) || ($photo_vignette && $imgarray[
'height'] > $maxHeight)) {
8832 $return .=
'<!-- Show thumb -->';
8833 $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).
'">';
8835 $return .=
'<!-- Show original file -->';
8836 $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).
'">';
8840 if (empty($nolink)) {
8844 if ($showfilename) {
8845 $return .=
'<br>'.$viewfilename;
8850 if ($photo_vignette && (
image_format_supported($photo) > 0) && ($this->imgWidth > $maxWidth || $this->imgHeight > $maxHeight)) {
8851 $return .=
'<a href="'.$_SERVER[
"PHP_SELF"].
'?id='.$this->
id.
'&action=addthumb&token='.newToken().
'&file='.urlencode($pdir.$viewfilename).
'">'.
img_picto($langs->trans(
'GenerateThumb'),
'refresh').
' </a>';
8854 if ($modulepart ==
'product' && ($user->hasRight(
'produit',
'creer') || $user->hasRight(
'service',
'creer'))) {
8856 $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> ';
8859 $return .=
'<a href="'.$_SERVER[
"PHP_SELF"].
'?id='.$this->
id.
'&action=delete&token='.newToken().
'&file='.urlencode($pdir.$viewfilename).
'">';
8867 if (($nbphoto % $nbbyrow) == 0) {
8870 } elseif ($nbbyrow < 0) {
8871 $return .=
'</div>'.
"\n";
8876 $return .=
'<img class="photo photowithmargin" src="'.DOL_URL_ROOT.
'/viewimage.php?modulepart='.$modulepart.
'&entity='.$this->entity.
'&file='.urlencode($pdir.$photo).
'">';
8878 if ($showfilename) {
8879 $return .=
'<br>'.$viewfilename;
8883 if ($modulepart ==
'product' && ($user->hasRight(
'produit',
'creer') || $user->hasRight(
'service',
'creer'))) {
8885 $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> ';
8888 $return .=
'<a href="'.$_SERVER[
"PHP_SELF"].
'?id='.$this->
id.
'&action=delete&token='.newToken().
'&file='.urlencode($pdir.$viewfilename).
'">';
8895 if ($nbmax && $nbphoto >= $nbmax) {
8901 if ($size == 1 || $size ==
'small') {
8904 while ($nbphoto % $nbbyrow) {
8905 $return .=
'<td style="width: '.ceil(100 / $nbbyrow).
'%"> </td>';
8910 $return .=
'</table>';
8916 $this->nbphoto = $nbphoto;
8930 if (is_array($info)) {
8931 if (isset($info[
'type']) && $info[
'type'] ==
'array') {
8948 if (isset($info[
'type']) && ($info[
'type'] ==
'date' || $info[
'type'] ==
'datetime' || $info[
'type'] ==
'timestamp')) {
8962 if (is_array($info)) {
8963 if (isset($info[
'type']) && ($info[
'type'] ==
'duration')) {
8981 if (is_array($info)) {
8982 if (isset($info[
'type']) && (preg_match(
'/(^int|int$)/i', $info[
'type']))) {
9000 if (is_array($info)) {
9001 if (isset($info[
'type']) && (preg_match(
'/^(double|real|price)/i', $info[
'type']))) {
9018 if (is_array($info)) {
9019 if (isset($info[
'type']) && $info[
'type'] ==
'text') {
9036 if (is_array($info)) {
9037 if (isset($info[
'notnull']) && $info[
'notnull'] !=
'1') {
9054 if (is_array($info)) {
9055 if (isset($info[
'notnull']) && $info[
'notnull'] ==
'-1') {
9072 if (is_array($info)) {
9073 if (isset($info[
'index']) && $info[
'index'] ==
true) {
9095 $queryarray = array();
9096 foreach ($this->fields as $field => $info) {
9098 if ($this->isDate($info)) {
9099 if (empty($this->{$field})) {
9100 $queryarray[$field] =
null;
9102 $queryarray[$field] = $this->db->idate($this->{$field});
9104 } elseif ($this->isDuration($info)) {
9106 if ((isset($this->{$field}) && $this->{$field} !=
'') || !empty($info[
'notnull'])) {
9107 if (!isset($this->{$field})) {
9108 if (!empty($info[
'default'])) {
9109 $queryarray[$field] = $info[
'default'];
9111 $queryarray[$field] = 0;
9114 $queryarray[$field] = (int) $this->{$field};
9117 $queryarray[$field] =
null;
9119 } elseif ($this->isInt($info) || $this->isFloat($info)) {
9120 if ($field ==
'entity' && is_null($this->{$field})) {
9121 $queryarray[$field] = ((int) $conf->entity);
9124 if ((isset($this->{$field}) && $this->{$field} !=
'') || !empty($info[
'notnull'])) {
9125 if (!isset($this->{$field})) {
9126 $queryarray[$field] = 0;
9127 } elseif ($this->isInt($info)) {
9128 $queryarray[$field] = (int) $this->{$field};
9129 } elseif ($this->isFloat($info)) {
9130 $queryarray[$field] = (double) $this->{$field};
9133 $queryarray[$field] =
null;
9139 $queryarray[$field] = $this->{$field};
9142 if ($info[
'type'] ==
'timestamp' && empty($queryarray[$field])) {
9143 unset($queryarray[$field]);
9145 if (!empty($info[
'notnull']) && $info[
'notnull'] == -1 && empty($queryarray[$field])) {
9146 $queryarray[$field] =
null;
9163 foreach ($this->fields as $field => $info) {
9164 if ($this->isDate($info)) {
9165 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') {
9168 $this->$field = $db->jdate($obj->$field);
9170 } elseif ($this->isInt($info)) {
9171 if ($field ==
'rowid') {
9172 $this->
id = (int) $obj->$field;
9174 if ($this->isForcedToNullIfZero($info)) {
9175 if (empty($obj->$field)) {
9176 $this->$field =
null;
9178 $this->$field = (double) $obj->$field;
9181 if (isset($obj->$field) && (!is_null($obj->$field) || (isset($info[
'notnull']) && $info[
'notnull'] == 1))) {
9182 $this->$field = (int) $obj->$field;
9184 $this->$field =
null;
9188 } elseif ($this->isFloat($info)) {
9189 if ($this->isForcedToNullIfZero($info)) {
9190 if (empty($obj->$field)) {
9191 $this->$field =
null;
9193 $this->$field = (double) $obj->$field;
9196 if (isset($obj->$field) && (!is_null($obj->$field) || (isset($info[
'notnull']) && $info[
'notnull'] == 1))) {
9197 $this->$field = (double) $obj->$field;
9199 $this->$field =
null;
9203 $this->$field = isset($obj->$field) ? $obj->$field :
null;
9208 if (!isset($this->fields[
'ref']) && isset($this->
id)) {
9209 $this->
ref = $this->id;
9222 $keys = array_keys($this->fields);
9223 if (!empty($alias)) {
9224 $keys_with_alias = array();
9225 foreach ($keys as $fieldname) {
9226 if (!empty($excludefields)) {
9227 if (in_array($fieldname, $excludefields)) {
9231 $keys_with_alias[] = $alias .
'.' . $fieldname;
9233 return implode(
',', $keys_with_alias);
9235 return implode(
',', $keys);
9246 protected function quote($value, $fieldsentry)
9248 if (is_null($value)) {
9250 } elseif (preg_match(
'/^(int|double|real|price)/i', $fieldsentry[
'type'])) {
9252 } elseif (preg_match(
'/int$/i', $fieldsentry[
'type'])) {
9253 return (
int) $value;
9254 } elseif ($fieldsentry[
'type'] ==
'boolean') {
9261 return "'".$this->db->escape($value).
"'";
9276 dol_syslog(get_class($this).
"::createCommon create", LOG_DEBUG);
9282 $fieldvalues = $this->setSaveQuery();
9284 if (array_key_exists(
'date_creation', $fieldvalues) && empty($fieldvalues[
'date_creation'])) {
9285 $fieldvalues[
'date_creation'] = $this->db->idate($now);
9287 if (array_key_exists(
'fk_user_creat', $fieldvalues) && !($fieldvalues[
'fk_user_creat'] > 0)) {
9288 $fieldvalues[
'fk_user_creat'] = $user->id;
9289 $this->fk_user_creat = $user->id;
9291 if (array_key_exists(
'user_modification_id', $fieldvalues) && !($fieldvalues[
'user_modification_id'] > 0)) {
9292 $fieldvalues[
'user_modification_id'] = $user->id;
9293 $this->user_modification_id = $user->id;
9295 unset($fieldvalues[
'rowid']);
9296 if (array_key_exists(
'ref', $fieldvalues)) {
9302 foreach ($fieldvalues as $k => $v) {
9304 $value = $this->fields[$k];
9305 $values[$k] = $this->quote($v, $value);
9309 foreach ($keys as $key) {
9311 if (preg_match(
'/^integer:/i', $this->fields[$key][
'type']) && $values[$key] ==
'-1') {
9314 if (!empty($this->fields[$key][
'foreignkey']) && $values[$key] ==
'-1') {
9318 if (isset($this->fields[$key][
'notnull']) && $this->fields[$key][
'notnull'] == 1 && (!isset($values[$key]) || $values[$key] ===
'NULL') && is_null($this->fields[$key][
'default'])) {
9320 $langs->load(
"errors");
9321 dol_syslog(
"Mandatory field '".$key.
"' is empty and required into ->fields definition of class");
9322 $this->errors[] = $langs->trans(
"ErrorFieldRequired", $this->fields[$key][
'label']);
9326 if (isset($this->fields[$key][
'notnull']) && $this->fields[$key][
'notnull'] == 1 && (!isset($values[$key]) || $values[$key] ===
'NULL') && !is_null($this->fields[$key][
'default'])) {
9327 $values[$key] = $this->quote($this->fields[$key][
'default'], $this->fields[$key]);
9331 if (preg_match(
'/^integer:/i', $this->fields[$key][
'type']) && empty($values[$key])) {
9332 if (isset($this->fields[$key][
'default'])) {
9333 $values[$key] = ((int) $this->fields[$key][
'default']);
9335 $values[$key] =
'null';
9338 if (!empty($this->fields[$key][
'foreignkey']) && empty($values[$key])) {
9339 $values[$key] =
'null';
9350 $sql =
"INSERT INTO ".$this->db->prefix().$this->table_element;
9351 $sql .=
" (".implode(
", ", $keys).
')';
9352 $sql .=
" VALUES (".implode(
", ", $values).
")";
9354 $res = $this->db->query($sql);
9357 if ($this->db->lasterrno() ==
'DB_ERROR_RECORD_ALREADY_EXISTS') {
9358 $this->errors[] =
"ErrorRefAlreadyExists";
9360 $this->errors[] = $this->db->lasterror();
9366 $this->
id = $this->db->last_insert_id($this->db->prefix().$this->table_element);
9371 if (key_exists(
'ref', $this->fields) && $this->fields[
'ref'][
'notnull'] > 0 && key_exists(
'default', $this->fields[
'ref']) && $this->fields[
'ref'][
'default'] ==
'(PROV)') {
9372 $sql =
"UPDATE ".$this->db->prefix().$this->table_element.
" SET ref = '(PROV".((int) $this->
id).
")' WHERE (ref = '(PROV)' OR ref = '') AND rowid = ".((int) $this->
id);
9373 $resqlupdate = $this->db->query($sql);
9375 if ($resqlupdate ===
false) {
9377 $this->errors[] = $this->db->lasterror();
9379 $this->
ref =
'(PROV'.$this->id.
')';
9386 $result = $this->insertExtraFields();
9393 if (!empty($this->table_element_line) && !empty($this->fk_element)) {
9394 $num = (is_array($this->lines) ? count($this->lines) : 0);
9395 for ($i = 0; $i < $num; $i++) {
9396 $line = $this->lines[$i];
9398 $keyforparent = $this->fk_element;
9399 $line->$keyforparent = $this->id;
9403 if (!is_object($line)) {
9404 $line = (object) $line;
9408 if (method_exists($line,
'insert')) {
9409 $result = $line->insert($user, 1);
9410 } elseif (method_exists($line,
'create')) {
9411 $result = $line->create($user, 1);
9414 $this->error = $line->error;
9415 $this->db->rollback();
9422 if (!$error && !$notrigger) {
9424 $result = $this->call_trigger(strtoupper(get_class($this)).
'_CREATE', $user);
9433 $this->db->rollback();
9436 $this->db->commit();
9452 if (empty($id) && empty($ref) && empty($morewhere)) {
9456 $fieldlist = $this->getFieldList(
't');
9457 if (empty($fieldlist)) {
9461 $sql =
"SELECT ".$fieldlist;
9462 $sql .=
" FROM ".$this->db->prefix().$this->table_element.
' as t';
9465 $sql .=
' WHERE t.rowid = '.((int) $id);
9466 } elseif (!empty($ref)) {
9467 $sql .=
" WHERE t.ref = '".$this->db->escape($ref).
"'";
9469 $sql .=
' WHERE 1 = 1';
9471 if (empty($id) && isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
9472 $sql .=
' AND t.entity IN ('.getEntity($this->element).
')';
9479 $res = $this->db->query($sql);
9481 $obj = $this->db->fetch_object($res);
9483 $this->setVarsFromFetchObj($obj);
9487 $this->fetch_optionals();
9494 $this->error = $this->db->lasterror();
9495 $this->errors[] = $this->error;
9508 $objectlineclassname = get_class($this).
'Line';
9509 if (!class_exists($objectlineclassname)) {
9510 $this->error =
'Error, class '.$objectlineclassname.
' not found during call of fetchLinesCommon';
9514 $objectline =
new $objectlineclassname($this->db);
9516 $sql =
"SELECT ".$objectline->getFieldList(
'l');
9517 $sql .=
" FROM ".$this->db->prefix().$objectline->table_element.
" as l";
9518 $sql .=
" WHERE l.fk_".$this->db->escape($this->element).
" = ".((int) $this->
id);
9522 if (isset($objectline->fields[
'position'])) {
9523 $sql .= $this->db->order(
'position',
'ASC');
9526 $resql = $this->db->query($sql);
9528 $num_rows = $this->db->num_rows($resql);
9530 $this->lines = array();
9531 while ($i < $num_rows) {
9532 $obj = $this->db->fetch_object($resql);
9534 $newline =
new $objectlineclassname($this->db);
9535 $newline->setVarsFromFetchObj($obj);
9537 $this->lines[] = $newline;
9544 $this->error = $this->db->lasterror();
9545 $this->errors[] = $this->error;
9559 global $conf, $langs;
9560 dol_syslog(get_class($this).
"::updateCommon update", LOG_DEBUG);
9571 $fieldvalues = $this->setSaveQuery();
9573 if (array_key_exists(
'date_modification', $fieldvalues) && empty($fieldvalues[
'date_modification'])) {
9574 $fieldvalues[
'date_modification'] = $this->db->idate($now);
9576 if (array_key_exists(
'fk_user_modif', $fieldvalues) && !($fieldvalues[
'fk_user_modif'] > 0)) {
9577 $fieldvalues[
'fk_user_modif'] = $user->id;
9579 unset($fieldvalues[
'rowid']);
9580 if (array_key_exists(
'ref', $fieldvalues)) {
9588 foreach ($fieldvalues as $k => $v) {
9590 $value = $this->fields[$k];
9591 $values[$k] = $this->quote($v, $value);
9592 $tmp[] = $k.
'='.$this->quote($v, $this->fields[$k]);
9596 foreach ($keys as $key) {
9597 if (preg_match(
'/^integer:/i', $this->fields[$key][
'type']) && $values[$key] ==
'-1') {
9600 if (!empty($this->fields[$key][
'foreignkey']) && $values[$key] ==
'-1') {
9613 $sql =
'UPDATE '.$this->db->prefix().$this->table_element.
' SET '.implode(
', ', $tmp).
' WHERE rowid='.((int) $this->
id);
9618 $res = $this->db->query($sql);
9621 $this->errors[] = $this->db->lasterror();
9627 $result = $this->insertExtraFields();
9634 if (!$error && !$notrigger) {
9636 $result = $this->call_trigger(strtoupper(get_class($this)).
'_MODIFY', $user);
9645 $this->db->rollback();
9648 $this->db->commit();
9663 dol_syslog(get_class($this).
"::deleteCommon delete", LOG_DEBUG);
9669 if ($forcechilddeletion) {
9670 foreach ($this->childtables as $table) {
9671 $sql =
"DELETE FROM ".$this->db->prefix().$table.
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
9672 $resql = $this->db->query($sql);
9674 $this->error = $this->db->lasterror();
9675 $this->errors[] = $this->error;
9676 $this->db->rollback();
9680 } elseif (!empty($this->childtables)) {
9681 $objectisused = $this->isObjectUsed($this->
id);
9682 if (!empty($objectisused)) {
9683 dol_syslog(get_class($this).
"::deleteCommon Can't delete record as it has some child", LOG_WARNING);
9684 $this->error =
'ErrorRecordHasChildren';
9685 $this->errors[] = $this->error;
9686 $this->db->rollback();
9692 if (is_array($this->childtablesoncascade) && !empty($this->childtablesoncascade)) {
9693 foreach ($this->childtablesoncascade as $table) {
9694 $deleteFromObject = explode(
':', $table);
9695 if (count($deleteFromObject) >= 2) {
9696 $className = str_replace(
'@',
'', $deleteFromObject[0]);
9697 $filePath = $deleteFromObject[1];
9698 $columnName = $deleteFromObject[2];
9699 $TMoreSQL = array();
9700 $more_sql = $deleteFromObject[3];
9701 if (!empty($more_sql)) {
9702 $TMoreSQL[
'customsql'] = $more_sql;
9705 $childObject =
new $className($this->db);
9706 if (method_exists($childObject,
'deleteByParentField')) {
9707 $result = $childObject->deleteByParentField($this->
id, $columnName, $TMoreSQL);
9710 $this->errors[] = $childObject->error;
9715 $this->errors[] =
"You defined a cascade delete on an object $childObject but there is no method deleteByParentField for it";
9720 $this->errors[] =
'Cannot include child class file '.$filePath;
9725 $sql =
"DELETE FROM ".$this->db->prefix().$table.
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
9727 $resql = $this->db->query($sql);
9730 $this->error = $this->db->lasterror();
9731 $this->errors[] = $this->error;
9741 $result = $this->call_trigger(strtoupper(get_class($this)).
'_DELETE', $user);
9751 $res = $this->deleteEcmFiles(1);
9758 $res = $this->deleteObjectLinked();
9763 if (!$error && !empty($this->isextrafieldmanaged)) {
9764 $result = $this->deleteExtraFields();
9771 $sql =
'DELETE FROM '.$this->db->prefix().$this->table_element.
' WHERE rowid='.((int) $this->
id);
9773 $resql = $this->db->query($sql);
9776 $this->errors[] = $this->db->lasterror();
9782 $this->db->rollback();
9785 $this->db->commit();
9807 if (!empty($parentId) && !empty($parentField)) {
9810 $sql =
"SELECT rowid FROM ".$this->db->prefix().$this->table_element;
9811 $sql .=
" WHERE ".$parentField.
" = ".(int) $parentId;
9814 $sqlwhere = array();
9815 if (count($filter) > 0) {
9816 foreach ($filter as $key => $value) {
9817 if ($key ==
'customsql') {
9818 $sqlwhere[] = $value;
9819 } elseif (strpos($value,
'%') ===
false) {
9820 $sqlwhere[] = $key.
" IN (".$this->db->sanitize($this->db->escape($value)).
")";
9822 $sqlwhere[] = $key.
" LIKE '%".$this->db->escape($value).
"%'";
9826 if (count($sqlwhere) > 0) {
9827 $sql .=
" AND (".implode(
" ".$filtermode.
" ", $sqlwhere).
")";
9830 $resql = $this->db->query($sql);
9832 $this->errors[] = $this->db->lasterror();
9835 while ($obj = $this->db->fetch_object($resql)) {
9836 $result = $this->fetch($obj->rowid);
9839 $this->errors[] = $this->error;
9841 if (get_class($this) ==
'Contact') {
9842 $result = $this->
delete();
9844 $result = $this->
delete($user);
9848 $this->errors[] = $this->error;
9856 if (empty($error)) {
9857 $this->db->commit();
9860 $this->error = implode(
', ', $this->errors);
9861 $this->db->rollback();
9883 $tmpforobjectclass = get_class($this);
9884 $tmpforobjectlineclass = ucfirst($tmpforobjectclass).
'Line';
9889 $result = $this->call_trigger(
'LINE'.strtoupper($tmpforobjectclass).
'_DELETE', $user);
9895 if (empty($error)) {
9896 $sql =
"DELETE FROM ".$this->db->prefix().$this->table_element_line;
9897 $sql .=
" WHERE rowid = ".((int) $idline);
9899 $resql = $this->db->query($sql);
9901 $this->error =
"Error ".$this->db->lasterror();
9906 if (empty($error)) {
9908 $tmpobjectline =
new $tmpforobjectlineclass($this->db);
9909 if (!isset($tmpobjectline->isextrafieldmanaged) || !empty($tmpobjectline->isextrafieldmanaged)) {
9910 $tmpobjectline->id = $idline;
9911 $result = $tmpobjectline->deleteExtraFields();
9914 $this->error =
"Error ".get_class($this).
"::deleteLineCommon deleteExtraFields error -4 ".$tmpobjectline->error;
9919 if (empty($error)) {
9920 $this->db->commit();
9923 dol_syslog(get_class($this).
"::deleteLineCommon ERROR:".$this->error, LOG_ERR);
9924 $this->db->rollback();
9945 $statusfield =
'status';
9946 if (in_array($this->element, array(
'don',
'donation',
'shipping'))) {
9947 $statusfield =
'fk_statut';
9950 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
9951 $sql .=
" SET ".$statusfield.
" = ".((int) $status);
9952 $sql .=
" WHERE rowid = ".((int) $this->
id);
9954 if ($this->db->query($sql)) {
9956 $this->oldcopy = clone $this;
9959 if (!$error && !$notrigger) {
9961 $result = $this->call_trigger($triggercode, $user);
9968 $this->status = $status;
9969 $this->db->commit();
9972 $this->db->rollback();
9976 $this->error = $this->db->error();
9977 $this->db->rollback();
9994 $this->specimen = 1;
9996 'label' =>
'This is label',
9997 'ref' =>
'ABCD1234',
9998 'description' =>
'This is a description',
10000 'note_public' =>
'Public note',
10001 'note_private' =>
'Private note',
10002 'date_creation' => (
dol_now() - 3600 * 48),
10003 'date_modification' => (
dol_now() - 3600 * 24),
10004 'fk_user_creat' => $user->id,
10005 'fk_user_modif' => $user->id,
10008 foreach ($fields as $key => $value) {
10009 if (array_key_exists($key, $this->fields)) {
10010 $this->{$key} = $value;
10015 if (property_exists($this,
'fields')) {
10016 foreach ($this->fields as $key => $value) {
10018 if (array_key_exists($key, $fields)) {
10022 if (!empty($value[
'default'])) {
10023 $this->$key = $value[
'default'];
10040 require_once DOL_DOCUMENT_ROOT.
'/core/class/comment.class.php';
10042 $comment =
new Comment($this->db);
10043 $result = $comment->fetchAllFor($this->element, $this->
id);
10045 $this->errors = array_merge($this->errors, $comment->errors);
10048 $this->comments = $comment->comments;
10050 return count($this->comments);
10060 return count($this->comments);
10071 if (!is_array($parameters)) {
10074 foreach ($parameters as $parameter) {
10075 if (isset($this->$parameter)) {
10076 $this->$parameter = trim($this->$parameter);
10095 require_once DOL_DOCUMENT_ROOT.
'/categories/class/categorie.class.php';
10099 $existing = $c->containing($this->
id, $type_categ,
'id');
10119 if (!is_array($categories)) {
10120 $categories = array($categories);
10123 dol_syslog(get_class($this).
"::setCategoriesCommon Oject Id:".$this->
id.
' type_categ:'.$type_categ.
' nb tag add:'.count($categories), LOG_DEBUG);
10125 require_once DOL_DOCUMENT_ROOT.
'/categories/class/categorie.class.php';
10127 if (empty($type_categ)) {
10128 dol_syslog(__METHOD__.
': Type '.$type_categ.
'is an unknown category type. Done nothing.', LOG_ERR);
10134 $existing = $c->containing($this->
id, $type_categ,
'id');
10135 if ($remove_existing) {
10137 if (is_array($existing)) {
10138 $to_del = array_diff($existing, $categories);
10139 $to_add = array_diff($categories, $existing);
10142 $to_add = $categories;
10146 $to_add = array_diff($categories, $existing);
10153 foreach ($to_del as $del) {
10154 if ($c->fetch($del) > 0) {
10155 $result=$c->del_type($this, $type_categ);
10158 $this->error = $c->error;
10159 $this->errors = $c->errors;
10166 foreach ($to_add as $add) {
10167 if ($c->fetch($add) > 0) {
10168 $result = $c->add_type($this, $type_categ);
10171 $this->error = $c->error;
10172 $this->errors = $c->errors;
10180 return $error ? (-1 * $error) : $ok;
10193 $this->db->begin();
10195 if (empty($type)) {
10196 $type = $this->table_element;
10199 require_once DOL_DOCUMENT_ROOT.
'/categories/class/categorie.class.php';
10200 $categorystatic =
new Categorie($this->db);
10202 $sql =
"INSERT INTO ".$this->db->prefix().
"categorie_".(empty($categorystatic->MAP_CAT_TABLE[$type]) ? $type : $categorystatic->MAP_CAT_TABLE[$type]).
" (fk_categorie, fk_product)";
10203 $sql .=
" SELECT fk_categorie, $toId FROM ".$this->db->prefix().
"categorie_".(empty($categorystatic->MAP_CAT_TABLE[$type]) ? $type : $categorystatic->MAP_CAT_TABLE[$type]);
10204 $sql .=
" WHERE fk_product = ".((int) $fromId);
10206 if (!$this->db->query($sql)) {
10207 $this->error = $this->db->lasterror();
10208 $this->db->rollback();
10212 $this->db->commit();
10226 $this->db->begin();
10230 switch ($this->element) {
10232 $element =
'propale';
10235 $element =
'produit';
10237 case 'order_supplier':
10238 $element =
'fournisseur/commande';
10240 case 'invoice_supplier':
10241 $element =
'fournisseur/facture/'.get_exdir($this->
id, 2, 0, 1, $this,
'invoice_supplier');
10244 $element =
'expedition/sending';
10247 $element = $this->element;
10251 $sql =
"DELETE FROM ".$this->db->prefix().
"ecm_files_extrafields WHERE fk_object IN (";
10252 $sql .=
" SELECT rowid FROM ".$this->db->prefix().
"ecm_files WHERE filename LIKE '".$this->db->escape($this->
ref).
"%'";
10253 $sql .=
" AND filepath = '".$this->db->escape($element).
"/".$this->db->escape($this->
ref).
"' AND entity = ".((int) $conf->entity);
10256 if (!$this->db->query($sql)) {
10257 $this->error = $this->db->lasterror();
10258 $this->db->rollback();
10263 $sql =
"DELETE FROM ".$this->db->prefix().
"ecm_files";
10264 $sql .=
" WHERE filename LIKE '".$this->db->escape($this->
ref).
"%'";
10265 $sql .=
" AND filepath = '".$this->db->escape($element).
"/".$this->db->escape($this->
ref).
"' AND entity = ".((int) $conf->entity);
10267 if (!$this->db->query($sql)) {
10268 $this->error = $this->db->lasterror();
10269 $this->db->rollback();
10276 $sql =
'DELETE FROM '.$this->db->prefix().
"ecm_files_extrafields";
10277 $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).
")";
10278 $resql = $this->db->query($sql);
10280 $this->error = $this->db->lasterror();
10281 $this->db->rollback();
10285 $sql =
'DELETE FROM '.$this->db->prefix().
"ecm_files";
10286 $sql .=
" WHERE src_object_type = '".$this->db->escape($this->table_element.(empty($this->module) ?
"" :
"@".$this->module)).
"' AND src_object_id = ".((int) $this->
id);
10287 $resql = $this->db->query($sql);
10289 $this->error = $this->db->lasterror();
10290 $this->db->rollback();
10295 $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.