diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md
index d17347a0ad7..68fe9de68d6 100644
--- a/.github/CONTRIBUTING.md
+++ b/.github/CONTRIBUTING.md
@@ -116,13 +116,13 @@ a process to follow to optimize the chance to have PRs merged efficiently...
Also, some code changes need a prior approbation:
-* if you want to include a new external library (into htdocs/includes directory), please ask before to the core project manager (mention @dolibarr-yoda in your issue) to see if such a library can be accepted.
+* if you want to include a new external library (into htdocs/includes directory), please ask before to the core project manager (mention @dolibarr-jedi in your issue) to see if such a library can be accepted.
-* if you add a new table, you must first create a page on https://wiki.dolibarr.org/index.php/Category:Table_SQL (copy an existing page changing its name to see it into this index page). Then ask the project manager (@dolibarr-yoda) if the new data model you plan to add is compatible with curent and future works in progress and can be accepted as you suggest.
+* if you add a new tables or fields, you MUST first submit a standalone PR with the data structure changes you plan to add/modify (and only data structure changes). Start development only once this data structure has been accepted.
Once a PR has been submitted, you may need to wait for its integration. It is common that the project leader let the PR open for a long delay to allow every developer discuss about the PR (A label is added in such a case).
-If the label of PR start with "Draft" or "WIP" (Work In Progress), it will not be analyzed for merging until you change the label of PR (but it can be analyzed for discussion).
+If the label of PR start with "Draft" or "WIP" (Work In Progress), it will not be analyzed for merging until you change the label of the PR (but it can be analyzed for discussion).
If your PR has errors reported by the Continuous Integration Platform, it means your PR is not valid and nothing will be done with it. It will be kept open to allow developers to fix this, or it may be closed several month later. Don't expect anything on your PR if you have such errors, you MUST first fix the Continuous Integration error to have it taken into consideration.
diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md
index 84deea18f00..13a3e6fa77b 100644
--- a/.github/PULL_REQUEST_TEMPLATE.md
+++ b/.github/PULL_REQUEST_TEMPLATE.md
@@ -1,18 +1,18 @@
# Instructions
*This is a template to help you make good pull requests. You may use [Github Markdown](https://help.github.com/articles/getting-started-with-writing-and-formatting-on-github/) syntax to format your issue report.*
*Please:*
-- *only keep the "Fix", "Close" or "New" section*
+- *only keep the "FIX", "CLOSE" or "NEW" section* (use uppercase to have the PR appears into the ChangeLog, lowercase will not appears)
- *follow the project [contributing guidelines](/.github/CONTRIBUTING.md)*
- *replace the bracket enclosed texts with meaningful information*
-# Fix #[*issue_number Short description*]
+# FIX|Fix #[*issue_number Short description*]
[*Long description*]
-# Close #[*issue_number Short description*]
+# CLOSE|Close #[*issue_number Short description*]
[*Long description*]
-# New [*Short description*]
+# NEW|New [*Short description*]
[*Long description*]
diff --git a/htdocs/accountancy/class/accountancyexport.class.php b/htdocs/accountancy/class/accountancyexport.class.php
index 81060f0e413..2c4dbfd51cd 100644
--- a/htdocs/accountancy/class/accountancyexport.class.php
+++ b/htdocs/accountancy/class/accountancyexport.class.php
@@ -914,7 +914,8 @@ class AccountancyExport
print "ValidDate".$separator;
print "Montantdevise".$separator;
print "Idevise".$separator;
- print "DateLimitReglmt";
+ print "DateLimitReglmt".$separator;
+ print "NumFacture".$separator;
print $end_line;
foreach ($objectLines as $line) {
@@ -927,6 +928,22 @@ class AccountancyExport
$date_validation = dol_print_date($line->date_validation, '%Y%m%d');
$date_limit_payment = dol_print_date($line->date_lim_reglement, '%Y%m%d');
+ if ($line->doc_type == 'customer_invoice') {
+ // Customer invoice
+ require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
+ $invoice = new Facture($db);
+ $invoice->fetch($line->fk_doc);
+
+ $refInvoice = $invoice->ref;
+ } elseif ($line->doc_type == 'supplier_invoice') {
+ // Supplier invoice
+ require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php';
+ $invoice = new FactureFournisseur($db);
+ $invoice->fetch($line->fk_doc);
+
+ $refInvoice = $invoice->ref_supplier;
+ }
+
// FEC:JournalCode
print $line->code_journal . $separator;
@@ -984,6 +1001,9 @@ class AccountancyExport
// FEC_suppl:DateLimitReglmt
print $date_limit_payment;
+ // FEC_suppl:NumFacture
+ print dol_trunc(self::toAnsi($refInvoice), 17, 'right', 'UTF-8', 1) . $separator;
+
print $end_line;
}
}
@@ -1020,7 +1040,8 @@ class AccountancyExport
print "ValidDate".$separator;
print "Montantdevise".$separator;
print "Idevise".$separator;
- print "DateLimitReglmt";
+ print "DateLimitReglmt".$separator;
+ print "NumFacture".$separator;
print $end_line;
foreach ($objectLines as $line) {
@@ -1033,6 +1054,22 @@ class AccountancyExport
$date_validation = dol_print_date($line->date_validation, '%Y%m%d');
$date_limit_payment = dol_print_date($line->date_lim_reglement, '%Y%m%d');
+ if ($line->doc_type == 'customer_invoice') {
+ // Customer invoice
+ require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
+ $invoice = new Facture($db);
+ $invoice->fetch($line->fk_doc);
+
+ $refInvoice = $invoice->ref;
+ } elseif ($line->doc_type == 'supplier_invoice') {
+ // Supplier invoice
+ require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php';
+ $invoice = new FactureFournisseur($db);
+ $invoice->fetch($line->fk_doc);
+
+ $refInvoice = $invoice->ref_supplier;
+ }
+
// FEC:JournalCode
print $line->code_journal . $separator;
@@ -1090,6 +1127,10 @@ class AccountancyExport
// FEC_suppl:DateLimitReglmt
print $date_limit_payment;
+ // FEC_suppl:NumFacture
+ print dol_trunc(self::toAnsi($refInvoice), 17, 'right', 'UTF-8', 1) . $separator;
+
+
print $end_line;
}
}
diff --git a/htdocs/accountancy/customer/lines.php b/htdocs/accountancy/customer/lines.php
index 1e7c38b2607..7f09e111a23 100644
--- a/htdocs/accountancy/customer/lines.php
+++ b/htdocs/accountancy/customer/lines.php
@@ -191,7 +191,14 @@ print '';
+ }
+ } elseif ($val['type'] == 'product') {
+ if (!empty($conf->product->enabled) || !empty($conf->service->enabled)) {
+ $selected = (empty($conf->global->$constname) ? '' : $conf->global->$constname);
+ $form->select_produits($selected, $constname, '', 0);
+ }
+ } else {
+ print '';
+ }
+ print '';
+ }
+ }
+ print '';
+
+ print '
';
if ($massactionbutton || $massaction) { // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined
diff --git a/htdocs/fourn/index.php b/htdocs/fourn/index.php
index 2b3017708dc..44a689fcd80 100644
--- a/htdocs/fourn/index.php
+++ b/htdocs/fourn/index.php
@@ -229,9 +229,17 @@ print '
';
* List last modified supliers
*/
$max = 10;
-$sql = "SELECT s.rowid as socid, s.nom as name, s.town, s.datec, s.tms, s.prefix_comm, s.code_fournisseur, s.code_compta_fournisseur";
+$sql = "SELECT s.rowid as socid, s.nom as name, s.town, s.datec, s.tms, s.prefix_comm, s.code_fournisseur";
+if (!empty($conf->global->MAIN_COMPANY_PERENTITY_SHARED)) {
+ $sql .= ", spe.accountancy_code_supplier as code_compta_fournisseur";
+} else {
+ $sql .= ", s.code_compta_fournisseur";
+}
$sql .= ", st.libelle as stcomm";
$sql .= " FROM ".MAIN_DB_PREFIX."societe as s";
+if (!empty($conf->global->MAIN_COMPANY_PERENTITY_SHARED)) {
+ $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "societe_perentity as spe ON spe.fk_soc = s.rowid AND spe.entity = " . ((int) $conf->entity);
+}
$sql .= ", ".MAIN_DB_PREFIX."c_stcomm as st";
if (!$user->rights->societe->client->voir && !$socid) {
$sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
diff --git a/htdocs/hrm/admin/admin_establishment.php b/htdocs/hrm/admin/admin_establishment.php
index f5baeee4027..dd17a2be4b0 100644
--- a/htdocs/hrm/admin/admin_establishment.php
+++ b/htdocs/hrm/admin/admin_establishment.php
@@ -21,7 +21,7 @@
* \brief HRM Establishment module setup page
*/
require '../../main.inc.php';
-require_once DOL_DOCUMENT_ROOT.'/core/lib/hrm.lib.php';
+require_once DOL_DOCUMENT_ROOT.'/hrm/lib/hrm.lib.php';
require_once DOL_DOCUMENT_ROOT.'/hrm/class/establishment.class.php';
// Load translation files required by the page
@@ -80,12 +80,12 @@ $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit;
// Subheader
$linkback = ''.$langs->trans("BackToModuleList").'';
-print load_fiche_titre($langs->trans("HRMSetup"), $linkback);
+print load_fiche_titre($langs->trans("HRMSetup"), $linkback, 'title_setup');
$newcardbutton = dolGetButtonTitle($langs->trans('NewEstablishment'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/hrm/establishment/card.php?action=create&backtopage='.urlencode($_SERVER['PHP_SELF']), '', $permissiontoadd);
// Configuration header
-$head = hrm_admin_prepare_head();
+$head = hrmAdminPrepareHead();
print dol_get_fiche_head($head, 'establishments', $langs->trans("HRM"), -1, "user", 0, $newcardbutton);
$sql = "SELECT e.rowid, e.rowid as ref, e.label, e.address, e.zip, e.town, e.status";
diff --git a/htdocs/hrm/class/evaluation.class.php b/htdocs/hrm/class/evaluation.class.php
new file mode 100644
index 00000000000..30e95e2d44e
--- /dev/null
+++ b/htdocs/hrm/class/evaluation.class.php
@@ -0,0 +1,1145 @@
+
+ * Copyright (C) 2021 Gauthier VERDOL
+ * Copyright (C) 2021 Greg Rastklan
+ * Copyright (C) 2021 Jean-Pascal BOUDET
+ * Copyright (C) 2021 Grégory BLEMAND
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see .
+ */
+
+/**
+ * \file class/evaluation.class.php
+ * \ingroup hrm
+ * \brief This file is a CRUD class file for Evaluation (Create/Read/Update/Delete)
+ */
+
+// Put here all includes required by your class file
+require_once DOL_DOCUMENT_ROOT . '/core/class/commonobject.class.php';
+require_once DOL_DOCUMENT_ROOT . '/hrm/class/evaluationdet.class.php';
+//require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php';
+//require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
+
+/**
+ * Class for Evaluation
+ */
+class Evaluation extends CommonObject
+{
+ /**
+ * @var string ID of module.
+ */
+ public $module = 'hrm';
+
+ /**
+ * @var string ID to identify managed object.
+ */
+ public $element = 'evaluation';
+
+ /**
+ * @var string Name of table without prefix where object is stored. This is also the key used for extrafields management.
+ */
+ public $table_element = 'hrm_evaluation';
+
+ /**
+ * @var int Does this object support multicompany module ?
+ * 0=No test on entity, 1=Test with field entity, 'field@table'=Test with link by field@table
+ */
+ public $ismultientitymanaged = 0;
+
+ /**
+ * @var int Does object support extrafields ? 0=No, 1=Yes
+ */
+ public $isextrafieldmanaged = 1;
+
+ /**
+ * @var string String with name of icon for evaluation. Must be the part after the 'object_' into object_evaluation.png
+ */
+ public $picto = 'label';
+
+
+ const STATUS_DRAFT = 0;
+ const STATUS_VALIDATED = 1;
+ const STATUS_CANCELED = 9;
+ const STATUS_CLOSED = 6;
+
+
+ /**
+ * 'type' field format ('integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter]]', 'sellist:TableName:LabelFieldName[:KeyFieldName[:KeyFieldParent[:Filter]]]', 'varchar(x)', 'double(24,8)', 'real', 'price', 'text', 'text:none', 'html', 'date', 'datetime', 'timestamp', 'duration', 'mail', 'phone', 'url', 'password')
+ * Note: Filter can be a string like "(t.ref:like:'SO-%') or (t.date_creation:<:'20160101') or (t.nature:is:NULL)"
+ * 'label' the translation key.
+ * 'picto' is code of a picto to show before value in forms
+ * 'enabled' is a condition when the field must be managed (Example: 1 or '$conf->global->MY_SETUP_PARAM)
+ * 'position' is the sort order of field.
+ * 'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0).
+ * 'visible' says if field is visible in list (Examples: 0=Not visible, 1=Visible on list and create/update/view forms, 2=Visible on list only, 3=Visible on create/update/view form only (not list), 4=Visible on list and update/view form only (not create). 5=Visible on list and view only (not create/not update). Using a negative value means field is not shown by default on list but can be selected for viewing)
+ * 'noteditable' says if field is not editable (1 or 0)
+ * 'default' is a default value for creation (can still be overwrote by the Setup of Default Values if field is editable in creation form). Note: If default is set to '(PROV)' and field is 'ref', the default value will be set to '(PROVid)' where id is rowid when a new record is created.
+ * 'index' if we want an index in database.
+ * 'foreignkey'=>'tablename.field' if the field is a foreign key (it is recommanded to name the field fk_...).
+ * 'searchall' is 1 if we want to search in this field when making a search from the quick search button.
+ * 'isameasure' must be set to 1 if you want to have a total on list for this field. Field type must be summable like integer or double(24,8).
+ * 'css' and 'cssview' and 'csslist' is the CSS style to use on field. 'css' is used in creation and update. 'cssview' is used in view mode. 'csslist' is used for columns in lists. For example: 'css'=>'minwidth300 maxwidth500 widthcentpercentminusx', 'cssview'=>'wordbreak', 'csslist'=>'tdoverflowmax200'
+ * 'help' is a 'TranslationString' to use to show a tooltip on field. You can also use 'TranslationString:keyfortooltiponlick' for a tooltip on click.
+ * 'showoncombobox' if value of the field must be visible into the label of the combobox that list record
+ * 'disabled' is 1 if we want to have the field locked by a 'disabled' attribute. In most cases, this is never set into the definition of $fields into class, but is set dynamically by some part of code.
+ * 'arrayofkeyval' to set a list of values if type is a list of predefined values. For example: array("0"=>"Draft","1"=>"Active","-1"=>"Cancel"). Note that type can be 'integer' or 'varchar'
+ * 'autofocusoncreate' to have field having the focus on a create form. Only 1 field should have this property set to 1.
+ * 'comment' is not used. You can store here any text of your choice. It is not used by application.
+ *
+ * Note: To have value dynamic, you can set value to 0 in definition and edit the value on the fly into the constructor.
+ */
+
+ // BEGIN MODULEBUILDER PROPERTIES
+ /**
+ * @var array Array with all fields and their property. Do not use it as a static var. It may be modified by constructor.
+ */
+ public $fields=array(
+ 'rowid' => array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>'1', 'position'=>1, 'notnull'=>1, 'visible'=>0, 'noteditable'=>'1', 'index'=>1, 'css'=>'left', 'comment'=>"Id"),
+ 'ref' => array('type'=>'varchar(128)', 'label'=>'Ref', 'enabled'=>'1', 'position'=>20, 'notnull'=>1, 'visible'=>4, 'noteditable'=>'1', 'default'=>'(PROV)', 'index'=>1, 'searchall'=>1, 'showoncombobox'=>'1', 'comment'=>"Reference of object"),
+ 'label' => array('type'=>'varchar(255)', 'label'=>'Label', 'enabled'=>'1', 'position'=>30, 'notnull'=>0, 'visible'=>1, 'searchall'=>1, 'css'=>'minwidth300', 'cssview'=>'wordbreak', 'showoncombobox'=>'2',),
+ 'description' => array('type'=>'text', 'label'=>'Description', 'enabled'=>'1', 'position'=>60, 'notnull'=>0, 'visible'=>3,),
+ 'note_public' => array('type'=>'html', 'label'=>'NotePublic', 'enabled'=>'1', 'position'=>61, 'notnull'=>0, 'visible'=>0,),
+ 'note_private' => array('type'=>'html', 'label'=>'NotePrivate', 'enabled'=>'1', 'position'=>62, 'notnull'=>0, 'visible'=>0,),
+ 'date_creation' => array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>'1', 'position'=>500, 'notnull'=>1, 'visible'=>-2,),
+ 'tms' => array('type'=>'timestamp', 'label'=>'DateModification', 'enabled'=>'1', 'position'=>501, 'notnull'=>0, 'visible'=>-2,),
+ 'fk_user_creat' => array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserAuthor', 'enabled'=>'1', 'position'=>510, 'notnull'=>1, 'visible'=>-2, 'foreignkey'=>'user.rowid',),
+ 'fk_user_modif' => array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserModif', 'enabled'=>'1', 'position'=>511, 'notnull'=>-1, 'visible'=>-2,),
+ 'import_key' => array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>'1', 'position'=>1000, 'notnull'=>-1, 'visible'=>-2,),
+ 'status' => array('type'=>'smallint', 'label'=>'Status', 'enabled'=>'1', 'position'=>1000, 'notnull'=>1, 'default'=>0, 'visible'=>5, 'index'=>1, 'arrayofkeyval'=>array('0'=>'Brouillon', '1'=>'Validé'),),
+ 'date_eval' => array('type'=>'date', 'label'=>'DateEval', 'enabled'=>'1', 'position'=>502, 'notnull'=>1, 'visible'=>1,),
+ 'fk_user' => array('type'=>'integer:User:user/class/user.class.php', 'label'=>'User', 'enabled'=>'1', 'position'=>504, 'notnull'=>1, 'visible'=>1,),
+ 'fk_job' => array('type'=>'integer:Job:/hrm/class/job.class.php', 'label'=>'Job', 'enabled'=>'1', 'position'=>505, 'notnull'=>1, 'visible'=>1,),
+ );
+ public $rowid;
+ public $ref;
+ public $label;
+ public $description;
+ public $note_public;
+ public $note_private;
+ public $date_creation;
+ public $tms;
+ public $fk_user_creat;
+ public $fk_user_modif;
+ public $import_key;
+ public $status;
+ public $date_eval;
+ public $fk_user;
+ public $fk_job;
+ // END MODULEBUILDER PROPERTIES
+
+
+ // If this object has a subtable with lines
+
+ /**
+ * @var string Name of subtable line
+ */
+ public $table_element_line = 'hrm_evaluationdet';
+
+ /**
+ * @var string Field with ID of parent key if this object has a parent
+ */
+ public $fk_element = 'fk_evaluation';
+
+ /**
+ * @var string Name of subtable class that manage subtable lines
+ */
+ public $class_element_line = 'Evaluationline';
+
+ // /**
+ // * @var array List of child tables. To test if we can delete object.
+ // */
+ // protected $childtables = array();
+
+ // /**
+ // * @var array List of child tables. To know object to delete on cascade.
+ // * If name matches '@ClassNAme:FilePathClass;ParentFkFieldName' it will
+ // * call method deleteByParentField(parentId, ParentFkFieldName) to fetch and delete child object
+ // */
+ protected $childtablesoncascade = array('@Evaluationline:hrm/class/evaluationdet.class.php:fk_evaluation');
+
+ /**
+ * @var Evaluationline[] Array of subtable lines
+ */
+ public $lines = array();
+
+
+
+ /**
+ * Constructor
+ *
+ * @param DoliDb $db Database handler
+ */
+ public function __construct(DoliDB $db)
+ {
+ global $conf, $langs;
+
+ $this->db = $db;
+
+ if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID) && isset($this->fields['rowid'])) {
+ $this->fields['rowid']['visible'] = 0;
+ }
+ if (empty($conf->multicompany->enabled) && isset($this->fields['entity'])) {
+ $this->fields['entity']['enabled'] = 0;
+ }
+
+ $this->date_eval = dol_now();
+
+ // Unset fields that are disabled
+ foreach ($this->fields as $key => $val) {
+ if (isset($val['enabled']) && empty($val['enabled'])) {
+ unset($this->fields[$key]);
+ }
+ }
+
+ // Translate some data of arrayofkeyval
+ if (is_object($langs)) {
+ foreach ($this->fields as $key => $val) {
+ if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
+ foreach ($val['arrayofkeyval'] as $key2 => $val2) {
+ $this->fields[$key]['arrayofkeyval'][$key2] = $langs->trans($val2);
+ }
+ }
+ }
+ }
+ }
+
+ /**
+ * Create object into database
+ *
+ * @param User $user User that creates
+ * @param bool $notrigger false=launch triggers after, true=disable triggers
+ * @return int <0 if KO, Id of created object if OK
+ */
+ public function create(User $user, $notrigger = false)
+ {
+ $resultcreate = $this->createCommon($user, $notrigger);
+
+ if ($resultcreate > 0) {
+ require_once DOL_DOCUMENT_ROOT . '/hrm/class/skillrank.class.php';
+ $skillRank = new SkillRank($this->db);
+ $TRequiredRanks = $skillRank->fetchAll('ASC', 't.rowid', 0, 0, array('customsql' => 'fk_object='.$this->fk_job." AND objecttype='job'"));
+
+ if (is_array($TRequiredRanks) && !empty($TRequiredRanks)) {
+ $this->lines = array();
+ foreach ($TRequiredRanks as $required) {
+ $line = new Evaluationline($this->db);
+ $line->fk_evaluation = $resultcreate;
+ $line->fk_skill = $required->fk_skill;
+ $line->required_rank = $required->rank;
+ $line->fk_rank = 0;
+
+ $res = $line->create($user, $notrigger);
+ if ($res > 0) $this->lines[] = $line;
+ }
+ }
+ }
+
+ return $resultcreate;
+ }
+
+ /**
+ * Clone an object into another one
+ *
+ * @param User $user User that creates
+ * @param int $fromid Id of object to clone
+ * @return mixed New object created, <0 if KO
+ */
+ public function createFromClone(User $user, $fromid)
+ {
+ global $langs, $extrafields;
+ $error = 0;
+
+ dol_syslog(__METHOD__, LOG_DEBUG);
+
+ $object = new self($this->db);
+
+ $this->db->begin();
+
+ // Load source object
+ $result = $object->fetchCommon($fromid);
+ if ($result > 0 && !empty($object->table_element_line)) {
+ $object->fetchLines();
+ }
+
+ // get lines so they will be clone
+ //foreach($this->lines as $line)
+ // $line->fetch_optionals();
+
+ // Reset some properties
+ unset($object->id);
+ unset($object->fk_user_creat);
+ unset($object->import_key);
+
+ // Clear fields
+ if (property_exists($object, 'ref')) {
+ $object->ref = empty($this->fields['ref']['default']) ? "Copy_Of_".$object->ref : $this->fields['ref']['default'];
+ }
+ if (property_exists($object, 'label')) {
+ $object->label = empty($this->fields['label']['default']) ? $langs->trans("CopyOf")." ".$object->label : $this->fields['label']['default'];
+ }
+ if (property_exists($object, 'status')) {
+ $object->status = self::STATUS_DRAFT;
+ }
+ if (property_exists($object, 'date_creation')) {
+ $object->date_creation = dol_now();
+ }
+ if (property_exists($object, 'date_modification')) {
+ $object->date_modification = null;
+ }
+ // ...
+ // Clear extrafields that are unique
+ if (is_array($object->array_options) && count($object->array_options) > 0) {
+ $extrafields->fetch_name_optionals_label($this->table_element);
+ foreach ($object->array_options as $key => $option) {
+ $shortkey = preg_replace('/options_/', '', $key);
+ if (!empty($extrafields->attributes[$this->table_element]['unique'][$shortkey])) {
+ //var_dump($key); var_dump($clonedObj->array_options[$key]); exit;
+ unset($object->array_options[$key]);
+ }
+ }
+ }
+
+ // Create clone
+ $object->context['createfromclone'] = 'createfromclone';
+ $result = $object->createCommon($user);
+ if ($result < 0) {
+ $error++;
+ $this->error = $object->error;
+ $this->errors = $object->errors;
+ }
+
+ if (!$error) {
+ // copy internal contacts
+ if ($this->copy_linked_contact($object, 'internal') < 0) {
+ $error++;
+ }
+ }
+
+ if (!$error) {
+ // copy external contacts if same company
+ if (property_exists($this, 'fk_soc') && $this->fk_soc == $object->socid) {
+ if ($this->copy_linked_contact($object, 'external') < 0) {
+ $error++;
+ }
+ }
+ }
+
+ unset($object->context['createfromclone']);
+
+ // End
+ if (!$error) {
+ $this->db->commit();
+ return $object;
+ } else {
+ $this->db->rollback();
+ return -1;
+ }
+ }
+
+ /**
+ * Load object in memory from the database
+ *
+ * @param int $id Id object
+ * @param string $ref Ref
+ * @return int <0 if KO, 0 if not found, >0 if OK
+ */
+ public function fetch($id, $ref = null)
+ {
+ $result = $this->fetchCommon($id, $ref);
+ if ($result > 0 && !empty($this->table_element_line)) {
+ $this->fetchLines();
+ }
+ return $result;
+ }
+
+ /**
+ * Load object lines in memory from the database
+ *
+ * @return int <0 if KO, 0 if not found, >0 if OK
+ */
+ public function fetchLines()
+ {
+ $this->lines = array();
+
+ $result = $this->fetchLinesCommon();
+ return $result;
+ }
+
+
+ /**
+ * Load list of objects in memory from the database.
+ *
+ * @param string $sortorder Sort Order
+ * @param string $sortfield Sort field
+ * @param int $limit limit
+ * @param int $offset Offset
+ * @param array $filter Filter array. Example array('field'=>'valueforlike', 'customurl'=>...)
+ * @param string $filtermode Filter mode (AND or OR)
+ * @return array|int int <0 if KO, array of pages if OK
+ */
+ public function fetchAll($sortorder = '', $sortfield = '', $limit = 0, $offset = 0, array $filter = array(), $filtermode = 'AND')
+ {
+ global $conf;
+
+ dol_syslog(__METHOD__, LOG_DEBUG);
+
+ $records = array();
+
+ $sql = 'SELECT ';
+ $sql .= $this->getFieldList('t');
+ $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t';
+ if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
+ $sql .= ' WHERE t.entity IN ('.getEntity($this->table_element).')';
+ } else {
+ $sql .= ' WHERE 1 = 1';
+ }
+ // Manage filter
+ $sqlwhere = array();
+ if (count($filter) > 0) {
+ foreach ($filter as $key => $value) {
+ if ($key == 't.rowid') {
+ $sqlwhere[] = $key.'='.$value;
+ } elseif (in_array($this->fields[$key]['type'], array('date', 'datetime', 'timestamp'))) {
+ $sqlwhere[] = $key.' = \''.$this->db->idate($value).'\'';
+ } elseif ($key == 'customsql') {
+ $sqlwhere[] = $value;
+ } elseif (strpos($value, '%') === false) {
+ $sqlwhere[] = $key.' IN ('.$this->db->sanitize($this->db->escape($value)).')';
+ } else {
+ $sqlwhere[] = $key.' LIKE \'%'.$this->db->escape($value).'%\'';
+ }
+ }
+ }
+ if (count($sqlwhere) > 0) {
+ $sql .= " AND (".implode(" ".$filtermode." ", $sqlwhere).")";
+ }
+
+ if (!empty($sortfield)) {
+ $sql .= $this->db->order($sortfield, $sortorder);
+ }
+ if (!empty($limit)) {
+ $sql .= ' '.$this->db->plimit($limit, $offset);
+ }
+
+ $resql = $this->db->query($sql);
+ if ($resql) {
+ $num = $this->db->num_rows($resql);
+ $i = 0;
+ while ($i < ($limit ? min($limit, $num) : $num)) {
+ $obj = $this->db->fetch_object($resql);
+
+ $record = new self($this->db);
+ $record->setVarsFromFetchObj($obj);
+
+ $records[$record->id] = $record;
+
+ $i++;
+ }
+ $this->db->free($resql);
+
+ return $records;
+ } else {
+ $this->errors[] = 'Error '.$this->db->lasterror();
+ dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
+
+ return -1;
+ }
+ }
+
+ /**
+ * Update object into database
+ *
+ * @param User $user User that modifies
+ * @param bool $notrigger false=launch triggers after, true=disable triggers
+ * @return int <0 if KO, >0 if OK
+ */
+ public function update(User $user, $notrigger = false)
+ {
+ return $this->updateCommon($user, $notrigger);
+ }
+
+ /**
+ * Delete object in database
+ *
+ * @param User $user User that deletes
+ * @param bool $notrigger false=launch triggers after, true=disable triggers
+ * @return int <0 if KO, >0 if OK
+ */
+ public function delete(User $user, $notrigger = false)
+ {
+ return $this->deleteCommon($user, $notrigger);
+ //return $this->deleteCommon($user, $notrigger, 1);
+ }
+
+ /**
+ * Delete a line of object in database
+ *
+ * @param User $user User that delete
+ * @param int $idline Id of line to delete
+ * @param bool $notrigger false=launch triggers after, true=disable triggers
+ * @return int >0 if OK, <0 if KO
+ */
+ public function deleteLine(User $user, $idline, $notrigger = false)
+ {
+ if ($this->status < 0) {
+ $this->error = 'ErrorDeleteLineNotAllowedByObjectStatus';
+ return -2;
+ }
+
+ return $this->deleteLineCommon($user, $idline, $notrigger);
+ }
+
+
+ /**
+ * Validate object
+ *
+ * @param User $user User making status change
+ * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
+ * @return int <=0 if OK, 0=Nothing done, >0 if KO
+ */
+ public function validate($user, $notrigger = 0)
+ {
+ global $conf, $langs;
+
+ require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
+
+ $error = 0;
+
+ // Protection
+ if ($this->status == self::STATUS_VALIDATED) {
+ dol_syslog(get_class($this)."::validate action abandonned: already validated", LOG_WARNING);
+ return 0;
+ }
+
+
+
+ $now = dol_now();
+
+ $this->db->begin();
+
+ // Define new ref
+ if (!$error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) { // empty should not happened, but when it occurs, the test save life
+ $num = $this->getNextNumRef();
+ } else {
+ $num = $this->ref;
+ }
+ $this->newref = $num;
+
+ if (!empty($num)) {
+ // Validate
+ $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
+ $sql .= " SET ref = '".$this->db->escape($num)."',";
+ $sql .= " status = ".self::STATUS_VALIDATED;
+ if (!empty($this->fields['date_validation'])) {
+ $sql .= ", date_validation = '".$this->db->idate($now)."'";
+ }
+ if (!empty($this->fields['fk_user_valid'])) {
+ $sql .= ", fk_user_valid = ".((int) $user->id);
+ }
+ $sql .= " WHERE rowid = ".((int) $this->id);
+
+ dol_syslog(get_class($this)."::validate()", LOG_DEBUG);
+ $resql = $this->db->query($sql);
+ if (!$resql) {
+ dol_print_error($this->db);
+ $this->error = $this->db->lasterror();
+ $error++;
+ }
+
+ if (!$error && !$notrigger) {
+ // Call trigger
+ $result = $this->call_trigger('EVALUATION_VALIDATE', $user);
+ if ($result < 0) {
+ $error++;
+ }
+ // End call triggers
+ }
+ }
+
+ if (!$error) {
+ $this->oldref = $this->ref;
+
+ // Rename directory if dir was a temporary ref
+ if (preg_match('/^[\(]?PROV/i', $this->ref)) {
+ // Now we rename also files into index
+ $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filename = CONCAT('".$this->db->escape($this->newref)."', SUBSTR(filename, ".(strlen($this->ref) + 1).")), filepath = 'evaluation/".$this->db->escape($this->newref)."'";
+ $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'evaluation/".$this->db->escape($this->ref)."' and entity = ".$conf->entity;
+ $resql = $this->db->query($sql);
+ if (!$resql) {
+ $error++; $this->error = $this->db->lasterror();
+ }
+
+ // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments
+ $oldref = dol_sanitizeFileName($this->ref);
+ $newref = dol_sanitizeFileName($num);
+ $dirsource = $conf->hrm->dir_output.'/evaluation/'.$oldref;
+ $dirdest = $conf->hrm->dir_output.'/evaluation/'.$newref;
+ if (!$error && file_exists($dirsource)) {
+ dol_syslog(get_class($this)."::validate() rename dir ".$dirsource." into ".$dirdest);
+
+ if (@rename($dirsource, $dirdest)) {
+ dol_syslog("Rename ok");
+ // Rename docs starting with $oldref with $newref
+ $listoffiles = dol_dir_list($conf->hrm->dir_output.'/evaluation/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/'));
+ foreach ($listoffiles as $fileentry) {
+ $dirsource = $fileentry['name'];
+ $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource);
+ $dirsource = $fileentry['path'].'/'.$dirsource;
+ $dirdest = $fileentry['path'].'/'.$dirdest;
+ @rename($dirsource, $dirdest);
+ }
+ }
+ }
+ }
+ }
+
+ // Set new ref and current status
+ if (!$error) {
+ $this->ref = $num;
+ $this->status = self::STATUS_VALIDATED;
+ }
+
+ if (!$error) {
+ $this->db->commit();
+ return 1;
+ } else {
+ $this->db->rollback();
+ return -1;
+ }
+ }
+
+ /**
+ * Get the last evaluation by date for the user assigned
+ *
+ * @param int $fk_user ID of user we need to get last eval
+ * @return Evaluation|null
+ */
+ public function getLastEvaluationForUser($fk_user)
+ {
+ $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."hrm_evaluation ";
+ $sql.= "WHERE fk_user=".((int) $fk_user)." ";
+ $sql.= "ORDER BY date_eval DESC ";
+ $sql.= "LIMIT 1 ";
+
+ $res = $this->db->query($sql);
+ if (!$res) { dol_print_error($this->db);}
+
+ $Tab = $this->db->fetch_object($res);
+
+ if (empty($Tab)) return null;
+ else {
+ $evaluation = new Evaluation($this->db);
+ $evaluation->fetch($Tab->rowid);
+
+ return $evaluation;
+ }
+ }
+
+
+ /**
+ * Set draft status
+ *
+ * @param User $user Object user that modify
+ * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers
+ * @return int <0 if KO, >0 if OK
+ */
+ public function setDraft($user, $notrigger = 0)
+ {
+ // Protection
+ if ($this->status <= self::STATUS_DRAFT) {
+ return 0;
+ }
+
+
+
+ return $this->setStatusCommon($user, self::STATUS_DRAFT, $notrigger, 'EVALUATION_UNVALIDATE');
+ }
+
+ /**
+ * Set cancel status
+ *
+ * @param User $user Object user that modify
+ * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers
+ * @return int <0 if KO, 0=Nothing done, >0 if OK
+ */
+ public function cancel($user, $notrigger = 0)
+ {
+ // Protection
+ if ($this->status != self::STATUS_VALIDATED) {
+ return 0;
+ }
+
+
+
+ return $this->setStatusCommon($user, self::STATUS_CANCELED, $notrigger, 'EVALUATION_CANCEL');
+ }
+
+ /**
+ * Set back to validated status
+ *
+ * @param User $user Object user that modify
+ * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers
+ * @return int <0 if KO, 0=Nothing done, >0 if OK
+ */
+ public function reopen($user, $notrigger = 0)
+ {
+ // Protection
+ if ($this->status != self::STATUS_CANCELED) {
+ return 0;
+ }
+
+
+
+ return $this->setStatusCommon($user, self::STATUS_VALIDATED, $notrigger, 'EVALUATION_REOPEN');
+ }
+
+ /**
+ * Return a link to the object card (with optionaly the picto)
+ *
+ * @param int $withpicto Include picto in link (0=No picto, 1=Include picto into link, 2=Only picto)
+ * @param string $option On what the link point to ('nolink', ...)
+ * @param int $notooltip 1=Disable tooltip
+ * @param string $morecss Add more css on link
+ * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
+ * @return string String with URL
+ */
+ public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $morecss = '', $save_lastsearch_value = -1)
+ {
+ global $conf, $langs, $hookmanager;
+
+ if (!empty($conf->dol_no_mouse_hover)) {
+ $notooltip = 1; // Force disable tooltips
+ }
+
+ $result = '';
+
+ $label = img_picto('', $this->picto).' '.$langs->trans("Evaluation").'';
+ if (isset($this->status)) {
+ $label .= ' '.$this->getLibStatut(5);
+ }
+ $label .= ' ';
+ $label .= ''.$langs->trans('Ref').': '.$this->ref;
+
+ $url = dol_buildpath('/hrm/evaluation_card.php', 1).'?id='.$this->id;
+
+ if ($option != 'nolink') {
+ // Add param to save lastsearch_values or not
+ $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
+ if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
+ $add_save_lastsearch_values = 1;
+ }
+ if ($add_save_lastsearch_values) {
+ $url .= '&save_lastsearch_values=1';
+ }
+ }
+
+ $linkclose = '';
+ if (empty($notooltip)) {
+ if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
+ $label = $langs->trans("ShowEvaluation");
+ $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
+ }
+ $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"';
+ $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"';
+ } else {
+ $linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
+ }
+
+ if ($option == 'nolink') {
+ $linkstart = '';
+ if ($option == 'nolink') {
+ $linkend = '';
+ } else {
+ $linkend = '';
+ }
+
+ $result .= $linkstart;
+
+ if (empty($this->showphoto_on_popup)) {
+ if ($withpicto) {
+ $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
+ }
+ } else {
+ if ($withpicto) {
+ require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
+
+ list($class, $module) = explode('@', $this->picto);
+ $upload_dir = $conf->$module->multidir_output[$conf->entity]."/$class/".dol_sanitizeFileName($this->ref);
+ $filearray = dol_dir_list($upload_dir, "files");
+ $filename = $filearray[0]['name'];
+ if (!empty($filename)) {
+ $pospoint = strpos($filearray[0]['name'], '.');
+
+ $pathtophoto = $class.'/'.$this->ref.'/thumbs/'.substr($filename, 0, $pospoint).'_mini'.substr($filename, $pospoint);
+ if (empty($conf->global->{strtoupper($module.'_'.$class).'_FORMATLISTPHOTOSASUSERS'})) {
+ $result .= '
';
+ } else {
+ $result .= '
';
+ }
+
+ $result .= '
';
+ } else {
+ $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
+ }
+ }
+ }
+
+ if ($withpicto != 2) {
+ $result .= $this->ref;
+ }
+
+ $result .= $linkend;
+ //if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : '');
+
+ global $action, $hookmanager;
+ $hookmanager->initHooks(array('evaluationdao'));
+ $parameters = array('id'=>$this->id, 'getnomurl'=>$result);
+ $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
+ if ($reshook > 0) {
+ $result = $hookmanager->resPrint;
+ } else {
+ $result .= $hookmanager->resPrint;
+ }
+
+ return $result;
+ }
+
+ /**
+ * Return the label of the status
+ *
+ * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto, 6=Long label + Picto
+ * @return string Label of status
+ */
+ public function getLibStatut($mode = 0)
+ {
+ return $this->LibStatut($this->status, $mode);
+ }
+
+ // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
+ /**
+ * Return the status
+ *
+ * @param int $status Id status
+ * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto, 6=Long label + Picto
+ * @return string Label of status
+ */
+ public function LibStatut($status, $mode = 0)
+ {
+ // phpcs:enable
+ if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
+ global $langs;
+ //$langs->load("hrm");
+ $this->labelStatus[self::STATUS_DRAFT] = $langs->trans('Draft');
+ $this->labelStatus[self::STATUS_VALIDATED] = $langs->trans('Validated');
+ $this->labelStatus[self::STATUS_CLOSED] = $langs->trans('Closed');
+ $this->labelStatusShort[self::STATUS_DRAFT] = $langs->trans('Draft');
+ $this->labelStatusShort[self::STATUS_VALIDATED] = $langs->trans('Validated');
+ $this->labelStatus[self::STATUS_CLOSED] = $langs->trans('Closed');
+ }
+
+ $statusType = 'status'.$status;
+ //if ($status == self::STATUS_VALIDATED) $statusType = 'status1';
+ if ($status == self::STATUS_CANCELED) {
+ $statusType = 'status6';
+ }
+
+ return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
+ }
+
+ /**
+ * Load the info information in the object
+ *
+ * @param int $id Id of object
+ * @return void
+ */
+ public function info($id)
+ {
+ $sql = 'SELECT rowid, date_creation as datec, tms as datem,';
+ $sql .= ' fk_user_creat, fk_user_modif';
+ $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t';
+ $sql .= ' WHERE t.rowid = '.((int) $id);
+ $result = $this->db->query($sql);
+ if ($result) {
+ if ($this->db->num_rows($result)) {
+ $obj = $this->db->fetch_object($result);
+ $this->id = $obj->rowid;
+ if ($obj->fk_user_author) {
+ $cuser = new User($this->db);
+ $cuser->fetch($obj->fk_user_author);
+ $this->user_creation = $cuser;
+ }
+
+ if ($obj->fk_user_valid) {
+ $vuser = new User($this->db);
+ $vuser->fetch($obj->fk_user_valid);
+ $this->user_validation = $vuser;
+ }
+
+ if ($obj->fk_user_cloture) {
+ $cluser = new User($this->db);
+ $cluser->fetch($obj->fk_user_cloture);
+ $this->user_cloture = $cluser;
+ }
+
+ $this->date_creation = $this->db->jdate($obj->datec);
+ $this->date_modification = $this->db->jdate($obj->datem);
+ $this->date_validation = $this->db->jdate($obj->datev);
+ }
+
+ $this->db->free($result);
+ } else {
+ dol_print_error($this->db);
+ }
+ }
+
+ /**
+ * Initialise object with example values
+ * Id must be 0 if object instance is a specimen
+ *
+ * @return void
+ */
+ public function initAsSpecimen()
+ {
+ // Set here init that are not commonf fields
+ // $this->property1 = ...
+ // $this->property2 = ...
+
+ $this->initAsSpecimenCommon();
+ }
+
+ /**
+ * Create an array of lines
+ *
+ * @return array|int array of lines if OK, <0 if KO
+ */
+ public function getLinesArray()
+ {
+ $this->lines = array();
+
+ $objectline = new Evaluationline($this->db);
+ $result = $objectline->fetchAll('ASC', '', 0, 0, array('customsql'=>'fk_evaluation = '.$this->id));
+
+ if (is_numeric($result)) {
+ $this->error = $this->error;
+ $this->errors = $this->errors;
+ return $result;
+ } else {
+ $this->lines = $result;
+ return $this->lines;
+ }
+ }
+
+ /**
+ * Returns the reference to the following non used object depending on the active numbering module.
+ *
+ * @return string Object free reference
+ */
+ public function getNextNumRef()
+ {
+ global $langs, $conf;
+ $langs->load("hrm");
+
+ if (empty($conf->global->HRMTEST_EVALUATION_ADDON)) {
+ $conf->global->HRMTEST_EVALUATION_ADDON = 'mod_evaluation_standard';
+ }
+
+ if (!empty($conf->global->HRMTEST_EVALUATION_ADDON)) {
+ $mybool = false;
+
+ $file = $conf->global->HRMTEST_EVALUATION_ADDON.".php";
+ $classname = $conf->global->HRMTEST_EVALUATION_ADDON;
+
+ // Include file with class
+ $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
+ foreach ($dirmodels as $reldir) {
+ $dir = dol_buildpath($reldir."core/modules/hrm/");
+
+ // Load file with numbering class (if found)
+ $mybool |= @include_once $dir.$file;
+ }
+
+ if ($mybool === false) {
+ dol_print_error('', "Failed to include file ".$file);
+ return '';
+ }
+
+ if (class_exists($classname)) {
+ $obj = new $classname();
+ $numref = $obj->getNextValue($this);
+
+ if ($numref != '' && $numref != '-1') {
+ return $numref;
+ } else {
+ $this->error = $obj->error;
+ //dol_print_error($this->db,get_class($this)."::getNextNumRef ".$obj->error);
+ return "";
+ }
+ } else {
+ print $langs->trans("Error")." ".$langs->trans("ClassNotFound").' '.$classname;
+ return "";
+ }
+ } else {
+ print $langs->trans("ErrorNumberingModuleNotSetup", $this->element);
+ return "";
+ }
+ }
+
+ /**
+ * Create a document onto disk according to template module.
+ *
+ * @param string $modele Force template to use ('' to not force)
+ * @param Translate $outputlangs objet lang a utiliser pour traduction
+ * @param int $hidedetails Hide details of lines
+ * @param int $hidedesc Hide description
+ * @param int $hideref Hide ref
+ * @param null|array $moreparams Array to provide more information
+ * @return int 0 if KO, 1 if OK
+ */
+ public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
+ {
+ global $conf, $langs;
+
+ $result = 0;
+ $includedocgeneration = 0;
+
+ $langs->load("hrm");
+
+ if (!dol_strlen($modele)) {
+ $modele = 'standard_evaluation';
+
+ if (!empty($this->model_pdf)) {
+ $modele = $this->model_pdf;
+ } elseif (!empty($conf->global->EVALUATION_ADDON_PDF)) {
+ $modele = $conf->global->EVALUATION_ADDON_PDF;
+ }
+ }
+
+ $modelpath = "core/modules/hrm/doc/";
+
+ if ($includedocgeneration && !empty($modele)) {
+ $result = $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
+ }
+
+ return $result;
+ }
+
+ /**
+ * Action executed by scheduler
+ * CAN BE A CRON TASK. In such a case, parameters come from the schedule job setup field 'Parameters'
+ * Use public function doScheduledJob($param1, $param2, ...) to get parameters
+ *
+ * @return int 0 if OK, <>0 if KO (this function is used also by cron so only 0 is OK)
+ */
+ public function doScheduledJob()
+ {
+ global $conf, $langs;
+
+ //$conf->global->SYSLOG_FILE = 'DOL_DATA_ROOT/dolibarr_mydedicatedlofile.log';
+
+ $error = 0;
+ $this->output = '';
+ $this->error = '';
+
+ dol_syslog(__METHOD__, LOG_DEBUG);
+
+ $now = dol_now();
+
+ $this->db->begin();
+
+ // ...
+
+ $this->db->commit();
+
+ return $error;
+ }
+
+ /**
+ * @param string $action
+ * @param int $selected
+ */
+ // public function printObjectLines($action, $selected = 0)
+ // {
+ // global $conf, $hookmanager, $langs, $user, $extrafields, $object;
+ // // TODO We should not use global var for this
+ // global $inputalsopricewithtax, $usemargins, $disableedit, $disablemove, $disableremove, $outputalsopricetotalwithtax;
+ //
+ // // Define usemargins
+ //// $usemargins = 0;
+ //// if (!empty($conf->margin->enabled) && !empty($this->element) && in_array($this->element, array('facture', 'facturerec', 'propal', 'commande'))) {
+ //// $usemargins = 1;
+ //// }
+ //
+ // $num = count($this->lines);
+ //
+ // // Line extrafield
+ // if (!is_object($extrafields)) {
+ // require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
+ // $extrafields = new ExtraFields($this->db);
+ // }
+ // $extrafields->fetch_name_optionals_label($this->table_element_line);
+ //
+ // $parameters = array('num'=>$num, 'selected'=>$selected, 'table_element_line'=>$this->table_element_line);
+ // $reshook = $hookmanager->executeHooks('printObjectLineTitle', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
+ // if (empty($reshook)) {
+ // // Output template part (modules that overwrite templates must declare this into descriptor)
+ // // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook.
+ // include dol_buildpath('hrm/core/tpl/objectline_title.tpl.php');
+ // }
+ //
+ // $i = 0;
+ //
+ // print "\n";
+ // foreach ($this->lines as $line) {
+ // //Line extrafield
+ // $line->fetch_optionals();
+ //
+ // //if (is_object($hookmanager) && (($line->product_type == 9 && ! empty($line->special_code)) || ! empty($line->fk_parent_line)))
+ // if (is_object($hookmanager)) { // Old code is commented on preceding line.
+ // if (empty($line->fk_parent_line)) {
+ // $parameters = array('line'=>$line, 'num'=>$num, 'i'=>$i, 'selected'=>$selected, 'table_element_line'=>$line->table_element);
+ // $reshook = $hookmanager->executeHooks('printObjectLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
+ // } else {
+ // $parameters = array('line'=>$line, 'num'=>$num, 'i'=>$i, 'selected'=>$selected, 'table_element_line'=>$line->table_element, 'fk_parent_line'=>$line->fk_parent_line);
+ // $reshook = $hookmanager->executeHooks('printObjectSubLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
+ // }
+ // }
+ // if (empty($reshook)) {
+ // $this->printObjectLine($action, $line);
+ // }
+ //
+ // $i++;
+ // }
+ // print "\n";
+ // }
+
+ // public function printObjectLine($action, $line)
+ // {
+ // global $conf, $langs, $user, $object, $hookmanager;
+ // global $form;
+ // global $object_rights, $disableedit, $disablemove, $disableremove; // TODO We should not use global var for this !
+ //
+ // $object_rights = $this->getRights();
+ //
+ // $element = $this->element;
+ //
+ // $text = '';
+ // $description = '';
+ //
+ // include dol_buildpath('hrm/tpl/objectline_view.tpl.php');
+ // }
+}
diff --git a/htdocs/hrm/class/evaluationdet.class.php b/htdocs/hrm/class/evaluationdet.class.php
new file mode 100644
index 00000000000..83a4c5a387b
--- /dev/null
+++ b/htdocs/hrm/class/evaluationdet.class.php
@@ -0,0 +1,1045 @@
+
+ * Copyright (C) 2021 Gauthier VERDOL
+ * Copyright (C) 2021 Greg Rastklan
+ * Copyright (C) 2021 Jean-Pascal BOUDET
+ * Copyright (C) 2021 Grégory BLEMAND
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see .
+ */
+
+/**
+ * \file class/evaluationdet.class.php
+ * \ingroup hrm
+ * \brief This file is a CRUD class file for Evaluationdet (Create/Read/Update/Delete)
+ */
+
+// Put here all includes required by your class file
+require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
+require_once DOL_DOCUMENT_ROOT . '/hrm/class/skillrank.class.php';
+//require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php';
+//require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
+
+/**
+ * Class for Evaluationline
+ */
+class Evaluationline extends CommonObject
+{
+ /**
+ * @var string ID of module.
+ */
+ public $module = 'hrm';
+
+ /**
+ * @var string ID to identify managed object.
+ */
+ public $element = 'evaluationdet';
+
+ /**
+ * @var string Name of table without prefix where object is stored. This is also the key used for extrafields management.
+ */
+ public $table_element = 'hrm_evaluationdet';
+
+ /**
+ * @var int Does this object support multicompany module ?
+ * 0=No test on entity, 1=Test with field entity, 'field@table'=Test with link by field@table
+ */
+ public $ismultientitymanaged = 0;
+
+ /**
+ * @var int Does object support extrafields ? 0=No, 1=Yes
+ */
+ public $isextrafieldmanaged = 1;
+
+ /**
+ * @var string String with name of icon for evaluationdet. Must be the part after the 'object_' into object_evaluationdet.png
+ */
+ public $picto = 'evaluationdet@hrm';
+
+
+ const STATUS_DRAFT = 0;
+ const STATUS_VALIDATED = 1;
+ const STATUS_CANCELED = 9;
+
+
+ /**
+ * 'type' field format ('integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter]]', 'sellist:TableName:LabelFieldName[:KeyFieldName[:KeyFieldParent[:Filter]]]', 'varchar(x)', 'double(24,8)', 'real', 'price', 'text', 'text:none', 'html', 'date', 'datetime', 'timestamp', 'duration', 'mail', 'phone', 'url', 'password')
+ * Note: Filter can be a string like "(t.ref:like:'SO-%') or (t.date_creation:<:'20160101') or (t.nature:is:NULL)"
+ * 'label' the translation key.
+ * 'picto' is code of a picto to show before value in forms
+ * 'enabled' is a condition when the field must be managed (Example: 1 or '$conf->global->MY_SETUP_PARAM)
+ * 'position' is the sort order of field.
+ * 'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0).
+ * 'visible' says if field is visible in list (Examples: 0=Not visible, 1=Visible on list and create/update/view forms, 2=Visible on list only, 3=Visible on create/update/view form only (not list), 4=Visible on list and update/view form only (not create). 5=Visible on list and view only (not create/not update). Using a negative value means field is not shown by default on list but can be selected for viewing)
+ * 'noteditable' says if field is not editable (1 or 0)
+ * 'default' is a default value for creation (can still be overwrote by the Setup of Default Values if field is editable in creation form). Note: If default is set to '(PROV)' and field is 'ref', the default value will be set to '(PROVid)' where id is rowid when a new record is created.
+ * 'index' if we want an index in database.
+ * 'foreignkey'=>'tablename.field' if the field is a foreign key (it is recommanded to name the field fk_...).
+ * 'searchall' is 1 if we want to search in this field when making a search from the quick search button.
+ * 'isameasure' must be set to 1 if you want to have a total on list for this field. Field type must be summable like integer or double(24,8).
+ * 'css' and 'cssview' and 'csslist' is the CSS style to use on field. 'css' is used in creation and update. 'cssview' is used in view mode. 'csslist' is used for columns in lists. For example: 'css'=>'minwidth300 maxwidth500 widthcentpercentminusx', 'cssview'=>'wordbreak', 'csslist'=>'tdoverflowmax200'
+ * 'help' is a 'TranslationString' to use to show a tooltip on field. You can also use 'TranslationString:keyfortooltiponlick' for a tooltip on click.
+ * 'showoncombobox' if value of the field must be visible into the label of the combobox that list record
+ * 'disabled' is 1 if we want to have the field locked by a 'disabled' attribute. In most cases, this is never set into the definition of $fields into class, but is set dynamically by some part of code.
+ * 'arrayofkeyval' to set a list of values if type is a list of predefined values. For example: array("0"=>"Draft","1"=>"Active","-1"=>"Cancel"). Note that type can be 'integer' or 'varchar'
+ * 'autofocusoncreate' to have field having the focus on a create form. Only 1 field should have this property set to 1.
+ * 'comment' is not used. You can store here any text of your choice. It is not used by application.
+ *
+ * Note: To have value dynamic, you can set value to 0 in definition and edit the value on the fly into the constructor.
+ */
+
+ // BEGIN MODULEBUILDER PROPERTIES
+ /**
+ * @var array Array with all fields and their property. Do not use it as a static var. It may be modified by constructor.
+ */
+ public $fields=array(
+ 'rowid' => array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>'1', 'position'=>1, 'notnull'=>1, 'visible'=>0, 'noteditable'=>'1', 'index'=>1, 'css'=>'left', 'comment'=>"Id"),
+ 'date_creation' => array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>'1', 'position'=>500, 'notnull'=>1, 'visible'=>-2,),
+ 'tms' => array('type'=>'timestamp', 'label'=>'DateModification', 'enabled'=>'1', 'position'=>501, 'notnull'=>0, 'visible'=>-2,),
+ 'fk_user_creat' => array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserAuthor', 'enabled'=>'1', 'position'=>510, 'notnull'=>1, 'visible'=>-2, 'foreignkey'=>'user.rowid',),
+ 'fk_user_modif' => array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserModif', 'enabled'=>'1', 'position'=>511, 'notnull'=>-1, 'visible'=>-2,),
+ 'fk_skill' => array('type'=>'integer:Skill:hrm/class/skill.class.php:1', 'label'=>'Skill', 'enabled'=>'1', 'position'=>3, 'notnull'=>1, 'visible'=>1, 'index'=>1,),
+ 'fk_evaluation' => array('type'=>'integer:Evaluation:hrm/class/evaluation.class.php:1', 'label'=>'Evaluation', 'enabled'=>'1', 'position'=>3, 'notnull'=>1, 'visible'=>1, 'index'=>1,),
+ 'rank' => array('type'=>'integer', 'label'=>'Rank', 'enabled'=>'1', 'position'=>4, 'notnull'=>1, 'visible'=>1,),
+ 'required_rank' => array('type'=>'integer', 'label'=>'requiredRank', 'enabled'=>'1', 'position'=>5, 'notnull'=>1, 'visible'=>1,),
+ 'import_key' => array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>'1', 'position'=>1000, 'notnull'=>-1, 'visible'=>-2,),
+ );
+ public $rowid;
+ public $date_creation;
+ public $tms;
+ public $fk_user_creat;
+ public $fk_user_modif;
+ public $fk_skill;
+ public $fk_evaluation;
+ public $fk_rank;
+ public $required_rank;
+ public $import_key;
+ // END MODULEBUILDER PROPERTIES
+
+
+ // If this object has a subtable with lines
+
+ // /**
+ // * @var string Name of subtable line
+ // */
+ // public $table_element_line = 'hrm_evaluationline';
+
+ // /**
+ // * @var string Field with ID of parent key if this object has a parent
+ // */
+ // public $fk_element = 'fk_evaluationdet';
+
+ // /**
+ // * @var string Name of subtable class that manage subtable lines
+ // */
+ // public $class_element_line = 'Evaluationline';
+
+ // /**
+ // * @var array List of child tables. To test if we can delete object.
+ // */
+ // protected $childtables = array();
+
+ // /**
+ // * @var array List of child tables. To know object to delete on cascade.
+ // * If name matches '@ClassNAme:FilePathClass;ParentFkFieldName' it will
+ // * call method deleteByParentField(parentId, ParentFkFieldName) to fetch and delete child object
+ // */
+ // protected $childtablesoncascade = array('hrm_evaluationdetdet');
+
+ // /**
+ // * @var EvaluationLine[] Array of subtable lines
+ // */
+ // public $lines = array();
+
+
+
+ /**
+ * Constructor
+ *
+ * @param DoliDb $db Database handler
+ */
+ public function __construct(DoliDB $db)
+ {
+ global $conf, $langs;
+
+ $this->db = $db;
+
+ if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID) && isset($this->fields['rowid'])) {
+ $this->fields['rowid']['visible'] = 0;
+ }
+ if (empty($conf->multicompany->enabled) && isset($this->fields['entity'])) {
+ $this->fields['entity']['enabled'] = 0;
+ }
+
+ // Example to show how to set values of fields definition dynamically
+ /*if ($user->rights->hrm->evaluationdet->read) {
+ $this->fields['myfield']['visible'] = 1;
+ $this->fields['myfield']['noteditable'] = 0;
+ }*/
+
+ // Unset fields that are disabled
+ foreach ($this->fields as $key => $val) {
+ if (isset($val['enabled']) && empty($val['enabled'])) {
+ unset($this->fields[$key]);
+ }
+ }
+
+ // Translate some data of arrayofkeyval
+ if (is_object($langs)) {
+ foreach ($this->fields as $key => $val) {
+ if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
+ foreach ($val['arrayofkeyval'] as $key2 => $val2) {
+ $this->fields[$key]['arrayofkeyval'][$key2] = $langs->trans($val2);
+ }
+ }
+ }
+ }
+ }
+
+ /**
+ * Create object into database
+ *
+ * @param User $user User that creates
+ * @param bool $notrigger false=launch triggers after, true=disable triggers
+ * @return int <0 if KO, Id of created object if OK
+ */
+ public function create(User $user, $notrigger = false)
+ {
+ $resultcreate = $this->createCommon($user, $notrigger);
+
+ return $resultcreate;
+ }
+
+ /**
+ * Clone an object into another one
+ *
+ * @param User $user User that creates
+ * @param int $fromid Id of object to clone
+ * @return mixed New object created, <0 if KO
+ */
+ public function createFromClone(User $user, $fromid)
+ {
+ global $langs, $extrafields;
+ $error = 0;
+
+ dol_syslog(__METHOD__, LOG_DEBUG);
+
+ $object = new self($this->db);
+
+ $this->db->begin();
+
+ // Load source object
+ $result = $object->fetchCommon($fromid);
+ if ($result > 0 && !empty($object->table_element_line)) {
+ $object->fetchLines();
+ }
+
+ // get lines so they will be clone
+ //foreach($this->lines as $line)
+ // $line->fetch_optionals();
+
+ // Reset some properties
+ unset($object->id);
+ unset($object->fk_user_creat);
+ unset($object->import_key);
+
+ // Clear fields
+ if (property_exists($object, 'ref')) {
+ $object->ref = empty($this->fields['ref']['default']) ? "Copy_Of_".$object->ref : $this->fields['ref']['default'];
+ }
+ if (property_exists($object, 'label')) {
+ $object->label = empty($this->fields['label']['default']) ? $langs->trans("CopyOf")." ".$object->label : $this->fields['label']['default'];
+ }
+ if (property_exists($object, 'status')) {
+ $object->status = self::STATUS_DRAFT;
+ }
+ if (property_exists($object, 'date_creation')) {
+ $object->date_creation = dol_now();
+ }
+ if (property_exists($object, 'date_modification')) {
+ $object->date_modification = null;
+ }
+ // ...
+ // Clear extrafields that are unique
+ if (is_array($object->array_options) && count($object->array_options) > 0) {
+ $extrafields->fetch_name_optionals_label($this->table_element);
+ foreach ($object->array_options as $key => $option) {
+ $shortkey = preg_replace('/options_/', '', $key);
+ if (!empty($extrafields->attributes[$this->table_element]['unique'][$shortkey])) {
+ //var_dump($key); var_dump($clonedObj->array_options[$key]); exit;
+ unset($object->array_options[$key]);
+ }
+ }
+ }
+
+ // Create clone
+ $object->context['createfromclone'] = 'createfromclone';
+ $result = $object->createCommon($user);
+ if ($result < 0) {
+ $error++;
+ $this->error = $object->error;
+ $this->errors = $object->errors;
+ }
+
+ if (!$error) {
+ // copy internal contacts
+ if ($this->copy_linked_contact($object, 'internal') < 0) {
+ $error++;
+ }
+ }
+
+ if (!$error) {
+ // copy external contacts if same company
+ if (property_exists($this, 'fk_soc') && $this->fk_soc == $object->socid) {
+ if ($this->copy_linked_contact($object, 'external') < 0) {
+ $error++;
+ }
+ }
+ }
+
+ unset($object->context['createfromclone']);
+
+ // End
+ if (!$error) {
+ $this->db->commit();
+ return $object;
+ } else {
+ $this->db->rollback();
+ return -1;
+ }
+ }
+
+ /**
+ * Load object in memory from the database
+ *
+ * @param int $id Id object
+ * @param string $ref Ref
+ * @return int <0 if KO, 0 if not found, >0 if OK
+ */
+ public function fetch($id, $ref = null)
+ {
+ $result = $this->fetchCommon($id, $ref);
+ if ($result > 0 && !empty($this->table_element_line)) {
+ $this->fetchLines();
+ }
+ return $result;
+ }
+
+ /**
+ * Load object lines in memory from the database
+ *
+ * @return int <0 if KO, 0 if not found, >0 if OK
+ */
+ public function fetchLines()
+ {
+ $this->lines = array();
+
+ $result = $this->fetchLinesCommon();
+ return $result;
+ }
+
+
+ /**
+ * Load list of objects in memory from the database.
+ *
+ * @param string $sortorder Sort Order
+ * @param string $sortfield Sort field
+ * @param int $limit limit
+ * @param int $offset Offset
+ * @param array $filter Filter array. Example array('field'=>'valueforlike', 'customurl'=>...)
+ * @param string $filtermode Filter mode (AND or OR)
+ * @return array|int int <0 if KO, array of pages if OK
+ */
+ public function fetchAll($sortorder = '', $sortfield = '', $limit = 0, $offset = 0, array $filter = array(), $filtermode = 'AND')
+ {
+ global $conf;
+
+ dol_syslog(__METHOD__, LOG_DEBUG);
+
+ $records = array();
+
+ $sql = 'SELECT ';
+ $sql .= $this->getFieldList('t');
+ $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t';
+ if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
+ $sql .= ' WHERE t.entity IN ('.getEntity($this->table_element).')';
+ } else {
+ $sql .= ' WHERE 1 = 1';
+ }
+ // Manage filter
+ $sqlwhere = array();
+ if (count($filter) > 0) {
+ foreach ($filter as $key => $value) {
+ if ($key == 't.rowid') {
+ $sqlwhere[] = $key.'='.$value;
+ } elseif (in_array($this->fields[$key]['type'], array('date', 'datetime', 'timestamp'))) {
+ $sqlwhere[] = $key.' = \''.$this->db->idate($value).'\'';
+ } elseif ($key == 'customsql') {
+ $sqlwhere[] = $value;
+ } elseif (strpos($value, '%') === false) {
+ $sqlwhere[] = $key.' IN ('.$this->db->sanitize($this->db->escape($value)).')';
+ } else {
+ $sqlwhere[] = $key.' LIKE \'%'.$this->db->escape($value).'%\'';
+ }
+ }
+ }
+ if (count($sqlwhere) > 0) {
+ $sql .= " AND (".implode(" ".$filtermode." ", $sqlwhere).")";
+ }
+
+ if (!empty($sortfield)) {
+ $sql .= $this->db->order($sortfield, $sortorder);
+ }
+ if (!empty($limit)) {
+ $sql .= ' '.$this->db->plimit($limit, $offset);
+ }
+
+ $resql = $this->db->query($sql);
+ if ($resql) {
+ $num = $this->db->num_rows($resql);
+ $i = 0;
+ while ($i < ($limit ? min($limit, $num) : $num)) {
+ $obj = $this->db->fetch_object($resql);
+
+ $record = new self($this->db);
+ $record->setVarsFromFetchObj($obj);
+
+ $records[$record->id] = $record;
+
+ $i++;
+ }
+ $this->db->free($resql);
+
+ return $records;
+ } else {
+ $this->errors[] = 'Error '.$this->db->lasterror();
+ dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
+
+ return -1;
+ }
+ }
+
+ /**
+ * Update object into database
+ *
+ * @param User $user User that modifies
+ * @param bool $notrigger false=launch triggers after, true=disable triggers
+ * @return int <0 if KO, >0 if OK
+ */
+ public function update(User $user, $notrigger = false)
+ {
+ return $this->updateCommon($user, $notrigger);
+ }
+
+ /**
+ * Delete object in database
+ *
+ * @param User $user User that deletes
+ * @param bool $notrigger false=launch triggers after, true=disable triggers
+ * @return int <0 if KO, >0 if OK
+ */
+ public function delete(User $user, $notrigger = false)
+ {
+ if ($this->fk_rank) {
+ $skillRank = new SkillRank($this->db);
+ $skillRank->fetch($this->fk_rank);
+ $skillRank->delete($user, $notrigger);
+ }
+ return $this->deleteCommon($user, $notrigger);
+ //return $this->deleteCommon($user, $notrigger, 1);
+ }
+
+ /**
+ * Delete a line of object in database
+ *
+ * @param User $user User that delete
+ * @param int $idline Id of line to delete
+ * @param bool $notrigger false=launch triggers after, true=disable triggers
+ * @return int >0 if OK, <0 if KO
+ */
+ public function deleteLine(User $user, $idline, $notrigger = false)
+ {
+ if ($this->status < 0) {
+ $this->error = 'ErrorDeleteLineNotAllowedByObjectStatus';
+ return -2;
+ }
+
+ return $this->deleteLineCommon($user, $idline, $notrigger);
+ }
+
+
+ /**
+ * Validate object
+ *
+ * @param User $user User making status change
+ * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
+ * @return int <=0 if OK, 0=Nothing done, >0 if KO
+ */
+ public function validate($user, $notrigger = 0)
+ {
+ global $conf, $langs;
+
+ require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
+
+ $error = 0;
+
+ // Protection
+ if ($this->status == self::STATUS_VALIDATED) {
+ dol_syslog(get_class($this)."::validate action abandonned: already validated", LOG_WARNING);
+ return 0;
+ }
+
+ /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->hrm->evaluationdet->write))
+ || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->hrm->evaluationdet->evaluationdet_advance->validate))))
+ {
+ $this->error='NotEnoughPermissions';
+ dol_syslog(get_class($this)."::valid ".$this->error, LOG_ERR);
+ return -1;
+ }*/
+
+ $now = dol_now();
+
+ $this->db->begin();
+
+ // Define new ref
+ if (!$error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) { // empty should not happened, but when it occurs, the test save life
+ $num = $this->getNextNumRef();
+ } else {
+ $num = $this->ref;
+ }
+ $this->newref = $num;
+
+ if (!empty($num)) {
+ // Validate
+ $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
+ $sql .= " SET ref = '".$this->db->escape($num)."',";
+ $sql .= " status = ".self::STATUS_VALIDATED;
+ if (!empty($this->fields['date_validation'])) {
+ $sql .= ", date_validation = '".$this->db->idate($now)."'";
+ }
+ if (!empty($this->fields['fk_user_valid'])) {
+ $sql .= ", fk_user_valid = ".((int) $user->id);
+ }
+ $sql .= " WHERE rowid = ".((int) $this->id);
+
+ dol_syslog(get_class($this)."::validate()", LOG_DEBUG);
+ $resql = $this->db->query($sql);
+ if (!$resql) {
+ dol_print_error($this->db);
+ $this->error = $this->db->lasterror();
+ $error++;
+ }
+
+ if (!$error && !$notrigger) {
+ // Call trigger
+ $result = $this->call_trigger('EVALUATIONLINE_VALIDATE', $user);
+ if ($result < 0) {
+ $error++;
+ }
+ // End call triggers
+ }
+ }
+
+ if (!$error) {
+ $this->oldref = $this->ref;
+
+ // Rename directory if dir was a temporary ref
+ if (preg_match('/^[\(]?PROV/i', $this->ref)) {
+ // Now we rename also files into index
+ $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filename = CONCAT('".$this->db->escape($this->newref)."', SUBSTR(filename, ".(strlen($this->ref) + 1).")), filepath = 'evaluationline/".$this->db->escape($this->newref)."'";
+ $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'evaluationline/".$this->db->escape($this->ref)."' and entity = ".$conf->entity;
+ $resql = $this->db->query($sql);
+ if (!$resql) {
+ $error++; $this->error = $this->db->lasterror();
+ }
+
+ // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments
+ $oldref = dol_sanitizeFileName($this->ref);
+ $newref = dol_sanitizeFileName($num);
+ $dirsource = $conf->hrm->dir_output.'/evaluationline/'.$oldref;
+ $dirdest = $conf->hrm->dir_output.'/evaluationline/'.$newref;
+ if (!$error && file_exists($dirsource)) {
+ dol_syslog(get_class($this)."::validate() rename dir ".$dirsource." into ".$dirdest);
+
+ if (@rename($dirsource, $dirdest)) {
+ dol_syslog("Rename ok");
+ // Rename docs starting with $oldref with $newref
+ $listoffiles = dol_dir_list($conf->hrm->dir_output.'/evaluationline/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/'));
+ foreach ($listoffiles as $fileentry) {
+ $dirsource = $fileentry['name'];
+ $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource);
+ $dirsource = $fileentry['path'].'/'.$dirsource;
+ $dirdest = $fileentry['path'].'/'.$dirdest;
+ @rename($dirsource, $dirdest);
+ }
+ }
+ }
+ }
+ }
+
+ // Set new ref and current status
+ if (!$error) {
+ $this->ref = $num;
+ $this->status = self::STATUS_VALIDATED;
+ }
+
+ if (!$error) {
+ $this->db->commit();
+ return 1;
+ } else {
+ $this->db->rollback();
+ return -1;
+ }
+ }
+
+
+ /**
+ * Set draft status
+ *
+ * @param User $user Object user that modify
+ * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers
+ * @return int <0 if KO, >0 if OK
+ */
+ public function setDraft($user, $notrigger = 0)
+ {
+ // Protection
+ if ($this->status <= self::STATUS_DRAFT) {
+ return 0;
+ }
+
+ /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->hrm->write))
+ || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->hrm->hrm_advance->validate))))
+ {
+ $this->error='Permission denied';
+ return -1;
+ }*/
+
+ return $this->setStatusCommon($user, self::STATUS_DRAFT, $notrigger, 'EVALUATIONLINE_UNVALIDATE');
+ }
+
+ /**
+ * Set cancel status
+ *
+ * @param User $user Object user that modify
+ * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers
+ * @return int <0 if KO, 0=Nothing done, >0 if OK
+ */
+ public function cancel($user, $notrigger = 0)
+ {
+ // Protection
+ if ($this->status != self::STATUS_VALIDATED) {
+ return 0;
+ }
+
+ /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->hrm->write))
+ || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->hrm->hrm_advance->validate))))
+ {
+ $this->error='Permission denied';
+ return -1;
+ }*/
+
+ return $this->setStatusCommon($user, self::STATUS_CANCELED, $notrigger, 'EVALUATIONLINE_CANCEL');
+ }
+
+ /**
+ * Set back to validated status
+ *
+ * @param User $user Object user that modify
+ * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers
+ * @return int <0 if KO, 0=Nothing done, >0 if OK
+ */
+ public function reopen($user, $notrigger = 0)
+ {
+ // Protection
+ if ($this->status != self::STATUS_CANCELED) {
+ return 0;
+ }
+
+ /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->hrm->write))
+ || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->hrm->hrm_advance->validate))))
+ {
+ $this->error='Permission denied';
+ return -1;
+ }*/
+
+ return $this->setStatusCommon($user, self::STATUS_VALIDATED, $notrigger, 'EVALUATIONLINE_REOPEN');
+ }
+
+ /**
+ * Return a link to the object card (with optionaly the picto)
+ *
+ * @param int $withpicto Include picto in link (0=No picto, 1=Include picto into link, 2=Only picto)
+ * @param string $option On what the link point to ('nolink', ...)
+ * @param int $notooltip 1=Disable tooltip
+ * @param string $morecss Add more css on link
+ * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
+ * @return string String with URL
+ */
+ public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $morecss = '', $save_lastsearch_value = -1)
+ {
+ global $conf, $langs, $hookmanager;
+
+ if (!empty($conf->dol_no_mouse_hover)) {
+ $notooltip = 1; // Force disable tooltips
+ }
+
+ $result = '';
+
+ $label = img_picto('', $this->picto).' '.$langs->trans("Evaluationdet").'';
+ if (isset($this->status)) {
+ $label .= ' '.$this->getLibStatut(5);
+ }
+ $label .= ' ';
+ $label .= ''.$langs->trans('Ref').': '.$this->ref;
+
+ $url = dol_buildpath('/hrm/evaluationdet_card.php', 1).'?id='.$this->id;
+
+ if ($option != 'nolink') {
+ // Add param to save lastsearch_values or not
+ $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
+ if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
+ $add_save_lastsearch_values = 1;
+ }
+ if ($add_save_lastsearch_values) {
+ $url .= '&save_lastsearch_values=1';
+ }
+ }
+
+ $linkclose = '';
+ if (empty($notooltip)) {
+ if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
+ $label = $langs->trans("ShowEvaluationdet");
+ $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
+ }
+ $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"';
+ $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"';
+ } else {
+ $linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
+ }
+
+ if ($option == 'nolink') {
+ $linkstart = '';
+ if ($option == 'nolink') {
+ $linkend = '';
+ } else {
+ $linkend = '';
+ }
+
+ $result .= $linkstart;
+
+ if (empty($this->showphoto_on_popup)) {
+ if ($withpicto) {
+ $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
+ }
+ } else {
+ if ($withpicto) {
+ require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
+
+ list($class, $module) = explode('@', $this->picto);
+ $upload_dir = $conf->$module->multidir_output[$conf->entity]."/$class/".dol_sanitizeFileName($this->ref);
+ $filearray = dol_dir_list($upload_dir, "files");
+ $filename = $filearray[0]['name'];
+ if (!empty($filename)) {
+ $pospoint = strpos($filearray[0]['name'], '.');
+
+ $pathtophoto = $class.'/'.$this->ref.'/thumbs/'.substr($filename, 0, $pospoint).'_mini'.substr($filename, $pospoint);
+ if (empty($conf->global->{strtoupper($module.'_'.$class).'_FORMATLISTPHOTOSASUSERS'})) {
+ $result .= '
';
+ } else {
+ $result .= '
';
+ }
+
+ $result .= '
';
+ } else {
+ $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
+ }
+ }
+ }
+
+ if ($withpicto != 2) {
+ $result .= $this->ref;
+ }
+
+ $result .= $linkend;
+ //if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : '');
+
+ global $action, $hookmanager;
+ $hookmanager->initHooks(array('evaluationlinedao'));
+ $parameters = array('id'=>$this->id, 'getnomurl'=>$result);
+ $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
+ if ($reshook > 0) {
+ $result = $hookmanager->resPrint;
+ } else {
+ $result .= $hookmanager->resPrint;
+ }
+
+ return $result;
+ }
+
+ /**
+ * Return the label of the status
+ *
+ * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto, 6=Long label + Picto
+ * @return string Label of status
+ */
+ public function getLibStatut($mode = 0)
+ {
+ return $this->LibStatut($this->status, $mode);
+ }
+
+ // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
+ /**
+ * Return the status
+ *
+ * @param int $status Id status
+ * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto, 6=Long label + Picto
+ * @return string Label of status
+ */
+ public function LibStatut($status, $mode = 0)
+ {
+ // phpcs:enable
+ if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
+ global $langs;
+ //$langs->load("hrm");
+ $this->labelStatus[self::STATUS_DRAFT] = $langs->trans('Draft');
+ $this->labelStatus[self::STATUS_VALIDATED] = $langs->trans('Enabled');
+ $this->labelStatus[self::STATUS_CANCELED] = $langs->trans('Disabled');
+ $this->labelStatusShort[self::STATUS_DRAFT] = $langs->trans('Draft');
+ $this->labelStatusShort[self::STATUS_VALIDATED] = $langs->trans('Enabled');
+ $this->labelStatusShort[self::STATUS_CANCELED] = $langs->trans('Disabled');
+ }
+
+ $statusType = 'status'.$status;
+ //if ($status == self::STATUS_VALIDATED) $statusType = 'status1';
+ if ($status == self::STATUS_CANCELED) {
+ $statusType = 'status6';
+ }
+
+ return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
+ }
+
+ /**
+ * Load the info information in the object
+ *
+ * @param int $id Id of object
+ * @return void
+ */
+ public function info($id)
+ {
+ $sql = 'SELECT rowid, date_creation as datec, tms as datem,';
+ $sql .= ' fk_user_creat, fk_user_modif';
+ $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t';
+ $sql .= ' WHERE t.rowid = '.((int) $id);
+ $result = $this->db->query($sql);
+ if ($result) {
+ if ($this->db->num_rows($result)) {
+ $obj = $this->db->fetch_object($result);
+ $this->id = $obj->rowid;
+ if ($obj->fk_user_author) {
+ $cuser = new User($this->db);
+ $cuser->fetch($obj->fk_user_author);
+ $this->user_creation = $cuser;
+ }
+
+ if ($obj->fk_user_valid) {
+ $vuser = new User($this->db);
+ $vuser->fetch($obj->fk_user_valid);
+ $this->user_validation = $vuser;
+ }
+
+ if ($obj->fk_user_cloture) {
+ $cluser = new User($this->db);
+ $cluser->fetch($obj->fk_user_cloture);
+ $this->user_cloture = $cluser;
+ }
+
+ $this->date_creation = $this->db->jdate($obj->datec);
+ $this->date_modification = $this->db->jdate($obj->datem);
+ $this->date_validation = $this->db->jdate($obj->datev);
+ }
+
+ $this->db->free($result);
+ } else {
+ dol_print_error($this->db);
+ }
+ }
+
+ /**
+ * Initialise object with example values
+ * Id must be 0 if object instance is a specimen
+ *
+ * @return void
+ */
+ public function initAsSpecimen()
+ {
+ // Set here init that are not commonf fields
+ // $this->property1 = ...
+ // $this->property2 = ...
+
+ $this->initAsSpecimenCommon();
+ }
+
+ /**
+ * Create an array of lines
+ *
+ * @return array|int array of lines if OK, <0 if KO
+ */
+ public function getLinesArray()
+ {
+ $this->lines = array();
+
+ $objectline = new EvaluationLine($this->db);
+ $result = $objectline->fetchAll('ASC', 'position', 0, 0, array('customsql'=>'fk_evaluationdet = '.$this->id));
+
+ if (is_numeric($result)) {
+ $this->error = $this->error;
+ $this->errors = $this->errors;
+ return $result;
+ } else {
+ $this->lines = $result;
+ return $this->lines;
+ }
+ }
+
+ /**
+ * Returns the reference to the following non used object depending on the active numbering module.
+ *
+ * @return string Object free reference
+ */
+ public function getNextNumRef()
+ {
+ global $langs, $conf;
+ $langs->load("hrm");
+
+ if (empty($conf->global->hrm_EVALUATIONLINE_ADDON)) {
+ $conf->global->hrm_EVALUATIONLINE_ADDON = 'mod_evaluationdet_standard';
+ }
+
+ if (!empty($conf->global->hrm_EVALUATIONLINE_ADDON)) {
+ $mybool = false;
+
+ $file = $conf->global->hrm_EVALUATIONLINE_ADDON.".php";
+ $classname = $conf->global->hrm_EVALUATIONLINE_ADDON;
+
+ // Include file with class
+ $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
+ foreach ($dirmodels as $reldir) {
+ $dir = dol_buildpath($reldir."core/modules/hrm/");
+
+ // Load file with numbering class (if found)
+ $mybool |= @include_once $dir.$file;
+ }
+
+ if ($mybool === false) {
+ dol_print_error('', "Failed to include file ".$file);
+ return '';
+ }
+
+ if (class_exists($classname)) {
+ $obj = new $classname();
+ $numref = $obj->getNextValue($this);
+
+ if ($numref != '' && $numref != '-1') {
+ return $numref;
+ } else {
+ $this->error = $obj->error;
+ //dol_print_error($this->db,get_class($this)."::getNextNumRef ".$obj->error);
+ return "";
+ }
+ } else {
+ print $langs->trans("Error")." ".$langs->trans("ClassNotFound").' '.$classname;
+ return "";
+ }
+ } else {
+ print $langs->trans("ErrorNumberingModuleNotSetup", $this->element);
+ return "";
+ }
+ }
+
+ /**
+ * Create a document onto disk according to template module.
+ *
+ * @param string $modele Force template to use ('' to not force)
+ * @param Translate $outputlangs objet lang a utiliser pour traduction
+ * @param int $hidedetails Hide details of lines
+ * @param int $hidedesc Hide description
+ * @param int $hideref Hide ref
+ * @param null|array $moreparams Array to provide more information
+ * @return int 0 if KO, 1 if OK
+ */
+ public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
+ {
+ global $conf, $langs;
+
+ $result = 0;
+ $includedocgeneration = 0;
+
+ $langs->load("hrm");
+
+ if (!dol_strlen($modele)) {
+ $modele = 'standard_evaluationdet';
+
+ if (!empty($this->model_pdf)) {
+ $modele = $this->model_pdf;
+ } elseif (!empty($conf->global->EVALUATIONLINE_ADDON_PDF)) {
+ $modele = $conf->global->EVALUATIONLINE_ADDON_PDF;
+ }
+ }
+
+ $modelpath = "core/modules/hrm/doc/";
+
+ if ($includedocgeneration && !empty($modele)) {
+ $result = $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
+ }
+
+ return $result;
+ }
+
+ /**
+ * Action executed by scheduler
+ * CAN BE A CRON TASK. In such a case, parameters come from the schedule job setup field 'Parameters'
+ * Use public function doScheduledJob($param1, $param2, ...) to get parameters
+ *
+ * @return int 0 if OK, <>0 if KO (this function is used also by cron so only 0 is OK)
+ */
+ public function doScheduledJob()
+ {
+ global $conf, $langs;
+
+ //$conf->global->SYSLOG_FILE = 'DOL_DATA_ROOT/dolibarr_mydedicatedlofile.log';
+
+ $error = 0;
+ $this->output = '';
+ $this->error = '';
+
+ dol_syslog(__METHOD__, LOG_DEBUG);
+
+ $now = dol_now();
+
+ $this->db->begin();
+
+ // ...
+
+ $this->db->commit();
+
+ return $error;
+ }
+}
+
+
+require_once DOL_DOCUMENT_ROOT.'/core/class/commonobjectline.class.php';
diff --git a/htdocs/hrm/class/job.class.php b/htdocs/hrm/class/job.class.php
new file mode 100644
index 00000000000..4ff5ccbe303
--- /dev/null
+++ b/htdocs/hrm/class/job.class.php
@@ -0,0 +1,1103 @@
+
+ * Copyright (C) 2021 Gauthier VERDOL
+ * Copyright (C) 2021 Greg Rastklan
+ * Copyright (C) 2021 Jean-Pascal BOUDET
+ * Copyright (C) 2021 Grégory BLEMAND
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see .
+ */
+
+/**
+ * \file class/job.class.php
+ * \ingroup hrm
+ * \brief This file is a CRUD class file for Job (Create/Read/Update/Delete)
+ */
+
+// Put here all includes required by your class file
+require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
+//require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php';
+//require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
+
+/**
+ * Class for Job
+ */
+class Job extends CommonObject
+{
+ /**
+ * @var string ID of module.
+ */
+ public $module = 'hrm';
+
+ /**
+ * @var string ID to identify managed object.
+ */
+ public $element = 'job';
+
+ /**
+ * @var string Name of table without prefix where object is stored. This is also the key used for extrafields management.
+ */
+ public $table_element = 'hrm_job';
+
+ /**
+ * @var int Does this object support multicompany module ?
+ * 0=No test on entity, 1=Test with field entity, 'field@table'=Test with link by field@table
+ */
+ public $ismultientitymanaged = 0;
+
+ /**
+ * @var int Does object support extrafields ? 0=No, 1=Yes
+ */
+ public $isextrafieldmanaged = 1;
+
+ /**
+ * @var string String with name of icon for job. Must be the part after the 'object_' into object_job.png
+ */
+ public $picto = 'technic';
+
+
+ const STATUS_DRAFT = 0;
+ const STATUS_VALIDATED = 1;
+ const STATUS_CANCELED = 9;
+
+
+ /**
+ * 'type' field format ('integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter]]', 'sellist:TableName:LabelFieldName[:KeyFieldName[:KeyFieldParent[:Filter]]]', 'varchar(x)', 'double(24,8)', 'real', 'price', 'text', 'text:none', 'html', 'date', 'datetime', 'timestamp', 'duration', 'mail', 'phone', 'url', 'password')
+ * Note: Filter can be a string like "(t.ref:like:'SO-%') or (t.date_creation:<:'20160101') or (t.nature:is:NULL)"
+ * 'label' the translation key.
+ * 'picto' is code of a picto to show before value in forms
+ * 'enabled' is a condition when the field must be managed (Example: 1 or '$conf->global->MY_SETUP_PARAM)
+ * 'position' is the sort order of field.
+ * 'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0).
+ * 'visible' says if field is visible in list (Examples: 0=Not visible, 1=Visible on list and create/update/view forms, 2=Visible on list only, 3=Visible on create/update/view form only (not list), 4=Visible on list and update/view form only (not create). 5=Visible on list and view only (not create/not update). Using a negative value means field is not shown by default on list but can be selected for viewing)
+ * 'noteditable' says if field is not editable (1 or 0)
+ * 'default' is a default value for creation (can still be overwrote by the Setup of Default Values if field is editable in creation form). Note: If default is set to '(PROV)' and field is 'ref', the default value will be set to '(PROVid)' where id is rowid when a new record is created.
+ * 'index' if we want an index in database.
+ * 'foreignkey'=>'tablename.field' if the field is a foreign key (it is recommanded to name the field fk_...).
+ * 'searchall' is 1 if we want to search in this field when making a search from the quick search button.
+ * 'isameasure' must be set to 1 if you want to have a total on list for this field. Field type must be summable like integer or double(24,8).
+ * 'css' and 'cssview' and 'csslist' is the CSS style to use on field. 'css' is used in creation and update. 'cssview' is used in view mode. 'csslist' is used for columns in lists. For example: 'css'=>'minwidth300 maxwidth500 widthcentpercentminusx', 'cssview'=>'wordbreak', 'csslist'=>'tdoverflowmax200'
+ * 'help' is a 'TranslationString' to use to show a tooltip on field. You can also use 'TranslationString:keyfortooltiponlick' for a tooltip on click.
+ * 'showoncombobox' if value of the field must be visible into the label of the combobox that list record
+ * 'disabled' is 1 if we want to have the field locked by a 'disabled' attribute. In most cases, this is never set into the definition of $fields into class, but is set dynamically by some part of code.
+ * 'arrayofkeyval' to set a list of values if type is a list of predefined values. For example: array("0"=>"Draft","1"=>"Active","-1"=>"Cancel"). Note that type can be 'integer' or 'varchar'
+ * 'autofocusoncreate' to have field having the focus on a create form. Only 1 field should have this property set to 1.
+ * 'comment' is not used. You can store here any text of your choice. It is not used by application.
+ *
+ * Note: To have value dynamic, you can set value to 0 in definition and edit the value on the fly into the constructor.
+ */
+
+ // BEGIN MODULEBUILDER PROPERTIES
+ /**
+ * @var array Array with all fields and their property. Do not use it as a static var. It may be modified by constructor.
+ */
+ public $fields=array(
+ 'rowid' => array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>'1', 'position'=>1, 'notnull'=>1, 'visible'=>0, 'noteditable'=>'1', 'index'=>1, 'css'=>'left', 'comment'=>"Id"),
+ 'label' => array('type'=>'varchar(128)', 'label'=>'Label', 'enabled'=>'1', 'position'=>20, 'notnull'=>1, 'visible'=>1, 'index'=>1, 'searchall'=>1, 'showoncombobox'=>'1', 'comment'=>"Label of object"),
+ 'description' => array('type'=>'text', 'label'=>'Description', 'enabled'=>'1', 'position'=>21, 'notnull'=>0, 'visible'=>1,),
+ 'date_creation' => array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>'1', 'position'=>500, 'notnull'=>1, 'visible'=>2,),
+ 'tms' => array('type'=>'timestamp', 'label'=>'DateModification', 'enabled'=>'1', 'position'=>501, 'notnull'=>0, 'visible'=>2,),
+ 'deplacement' => array('type'=>'select', 'required'=> 1,'label'=> 'deplacement', 'enabled'=> 1, 'position'=> 90, 'notnull'=> 1, 'visible'=> 1, 'arrayofkeyval'=> array(0 =>"No", 1=>"Yes"), 'default'=>0),
+ 'note_public' => array('type'=>'html', 'label'=>'NotePublic', 'enabled'=>'1', 'position'=>70, 'notnull'=>0, 'visible'=>0,),
+ 'note_private' => array('type'=>'html', 'label'=>'NotePrivate', 'enabled'=>'1', 'position'=>71, 'notnull'=>0, 'visible'=>0,),
+ 'fk_user_creat' => array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserAuthor', 'enabled'=>'1', 'position'=>510, 'notnull'=>1, 'visible'=>-2, 'foreignkey'=>'user.rowid',),
+ 'fk_user_modif' => array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserModif', 'enabled'=>'1', 'position'=>511, 'notnull'=>-1, 'visible'=>-2,),
+ );
+ public $rowid;
+ public $ref;
+ public $description;
+ public $date_creation;
+ public $tms;
+ public $deplacement;
+ public $note_public;
+ public $note_private;
+ public $fk_user_creat;
+ public $fk_user_modif;
+ // END MODULEBUILDER PROPERTIES
+
+
+ // If this object has a subtable with lines
+
+ // /**
+ // * @var string Name of subtable line
+ // */
+ // public $table_element_line = 'hrm_jobline';
+
+ // /**
+ // * @var string Field with ID of parent key if this object has a parent
+ // */
+ public $fk_element = 'fk_job';
+
+ // /**
+ // * @var string Name of subtable class that manage subtable lines
+ // */
+ // public $class_element_line = 'Jobline';
+
+ // /**
+ // * @var array List of child tables. To test if we can delete object.
+ // */
+ protected $childtables = array('hrm_evaluation', 'hrm_job_user');
+
+ // /**
+ // * @var array List of child tables. To know object to delete on cascade.
+ // * If name matches '@ClassNAme:FilePathClass;ParentFkFieldName' it will
+ // * call method deleteByParentField(parentId, ParentFkFieldName) to fetch and delete child object
+ // */
+ // protected $childtablesoncascade = array('hrm_jobdet');
+
+ // /**
+ // * @var JobLine[] Array of subtable lines
+ // */
+ // public $lines = array();
+
+
+
+ /**
+ * Constructor
+ *
+ * @param DoliDb $db Database handler
+ */
+ public function __construct(DoliDB $db)
+ {
+ global $conf, $langs;
+
+ $this->db = $db;
+
+ if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID) && isset($this->fields['rowid'])) {
+ $this->fields['rowid']['visible'] = 0;
+ }
+ if (empty($conf->multicompany->enabled) && isset($this->fields['entity'])) {
+ $this->fields['entity']['enabled'] = 0;
+ }
+
+ // Example to show how to set values of fields definition dynamically
+ /*if ($user->rights->hrm->job->read) {
+ $this->fields['myfield']['visible'] = 1;
+ $this->fields['myfield']['noteditable'] = 0;
+ }*/
+
+ // Unset fields that are disabled
+ foreach ($this->fields as $key => $val) {
+ if (isset($val['enabled']) && empty($val['enabled'])) {
+ unset($this->fields[$key]);
+ }
+ }
+
+ // Translate some data of arrayofkeyval
+ if (is_object($langs)) {
+ foreach ($this->fields as $key => $val) {
+ if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
+ foreach ($val['arrayofkeyval'] as $key2 => $val2) {
+ $this->fields[$key]['arrayofkeyval'][$key2] = $langs->trans($val2);
+ }
+ }
+ }
+ }
+ }
+
+ /**
+ * Create object into database
+ *
+ * @param User $user User that creates
+ * @param bool $notrigger false=launch triggers after, true=disable triggers
+ * @return int <0 if KO, Id of created object if OK
+ */
+ public function create(User $user, $notrigger = false)
+ {
+ $resultcreate = $this->createCommon($user, $notrigger);
+
+ //$resultvalidate = $this->validate($user, $notrigger);
+
+ return $resultcreate;
+ }
+
+ /**
+ * Clone an object into another one
+ *
+ * @param User $user User that creates
+ * @param int $fromid Id of object to clone
+ * @return mixed New object created, <0 if KO
+ */
+ public function createFromClone(User $user, $fromid)
+ {
+ global $langs, $extrafields;
+ $error = 0;
+
+ dol_syslog(__METHOD__, LOG_DEBUG);
+
+ $object = new self($this->db);
+
+ $this->db->begin();
+
+ // Load source object
+ $result = $object->fetchCommon($fromid);
+ if ($result > 0 && !empty($object->table_element_line)) {
+ $object->fetchLines();
+ }
+
+ // get lines so they will be clone
+ //foreach($this->lines as $line)
+ // $line->fetch_optionals();
+
+ // Reset some properties
+ unset($object->id);
+ unset($object->fk_user_creat);
+ unset($object->import_key);
+
+ // Clear fields
+ if (property_exists($object, 'ref')) {
+ $object->ref = empty($this->fields['ref']['default']) ? "Copy_Of_".$object->ref : $this->fields['ref']['default'];
+ }
+ if (property_exists($object, 'label')) {
+ $object->label = empty($this->fields['label']['default']) ? $langs->trans("CopyOf")." ".$object->label : $this->fields['label']['default'];
+ }
+ if (property_exists($object, 'status')) {
+ $object->status = self::STATUS_DRAFT;
+ }
+ if (property_exists($object, 'date_creation')) {
+ $object->date_creation = dol_now();
+ }
+ if (property_exists($object, 'date_modification')) {
+ $object->date_modification = null;
+ }
+ // ...
+ // Clear extrafields that are unique
+ if (is_array($object->array_options) && count($object->array_options) > 0) {
+ $extrafields->fetch_name_optionals_label($this->table_element);
+ foreach ($object->array_options as $key => $option) {
+ $shortkey = preg_replace('/options_/', '', $key);
+ if (!empty($extrafields->attributes[$this->table_element]['unique'][$shortkey])) {
+ //var_dump($key); var_dump($clonedObj->array_options[$key]); exit;
+ unset($object->array_options[$key]);
+ }
+ }
+ }
+
+ // Create clone
+ $object->context['createfromclone'] = 'createfromclone';
+ $result = $object->createCommon($user);
+ if ($result < 0) {
+ $error++;
+ $this->error = $object->error;
+ $this->errors = $object->errors;
+ }
+
+ if (!$error) {
+ // copy internal contacts
+ if ($this->copy_linked_contact($object, 'internal') < 0) {
+ $error++;
+ }
+ }
+
+ if (!$error) {
+ // copy external contacts if same company
+ if (property_exists($this, 'fk_soc') && $this->fk_soc == $object->socid) {
+ if ($this->copy_linked_contact($object, 'external') < 0) {
+ $error++;
+ }
+ }
+ }
+
+ unset($object->context['createfromclone']);
+
+ // End
+ if (!$error) {
+ $this->db->commit();
+ return $object;
+ } else {
+ $this->db->rollback();
+ return -1;
+ }
+ }
+
+ /**
+ * Load object in memory from the database
+ *
+ * @param int $id Id object
+ * @param string $ref Ref
+ * @return int <0 if KO, 0 if not found, >0 if OK
+ */
+ public function fetch($id, $ref = null)
+ {
+ $result = $this->fetchCommon($id, $ref);
+ if ($result > 0 && !empty($this->table_element_line)) {
+ $this->fetchLines();
+ }
+ return $result;
+ }
+
+ /**
+ * Load object lines in memory from the database
+ *
+ * @return int <0 if KO, 0 if not found, >0 if OK
+ */
+ public function fetchLines()
+ {
+ $this->lines = array();
+
+ $result = $this->fetchLinesCommon();
+ return $result;
+ }
+
+
+ /**
+ * Load list of objects in memory from the database.
+ *
+ * @param string $sortorder Sort Order
+ * @param string $sortfield Sort field
+ * @param int $limit limit
+ * @param int $offset Offset
+ * @param array $filter Filter array. Example array('field'=>'valueforlike', 'customurl'=>...)
+ * @param string $filtermode Filter mode (AND or OR)
+ * @return array|int int <0 if KO, array of pages if OK
+ */
+ public function fetchAll($sortorder = '', $sortfield = '', $limit = 0, $offset = 0, array $filter = array(), $filtermode = 'AND')
+ {
+ global $conf;
+
+ dol_syslog(__METHOD__, LOG_DEBUG);
+
+ $records = array();
+
+ $sql = 'SELECT ';
+ $sql .= $this->getFieldList('t');
+ $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t';
+ if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
+ $sql .= ' WHERE t.entity IN ('.getEntity($this->table_element).')';
+ } else {
+ $sql .= ' WHERE 1 = 1';
+ }
+ // Manage filter
+ $sqlwhere = array();
+ if (count($filter) > 0) {
+ foreach ($filter as $key => $value) {
+ if ($key == 't.rowid') {
+ $sqlwhere[] = $key.'='.$value;
+ } elseif (in_array($this->fields[$key]['type'], array('date', 'datetime', 'timestamp'))) {
+ $sqlwhere[] = $key.' = \''.$this->db->idate($value).'\'';
+ } elseif ($key == 'customsql') {
+ $sqlwhere[] = $value;
+ } elseif (strpos($value, '%') === false) {
+ $sqlwhere[] = $key.' IN ('.$this->db->sanitize($this->db->escape($value)).')';
+ } else {
+ $sqlwhere[] = $key.' LIKE \'%'.$this->db->escape($value).'%\'';
+ }
+ }
+ }
+ if (count($sqlwhere) > 0) {
+ $sql .= " AND (".implode(" ".$filtermode." ", $sqlwhere).")";
+ }
+
+ if (!empty($sortfield)) {
+ $sql .= $this->db->order($sortfield, $sortorder);
+ }
+ if (!empty($limit)) {
+ $sql .= ' '.$this->db->plimit($limit, $offset);
+ }
+
+ $resql = $this->db->query($sql);
+ if ($resql) {
+ $num = $this->db->num_rows($resql);
+ $i = 0;
+ while ($i < ($limit ? min($limit, $num) : $num)) {
+ $obj = $this->db->fetch_object($resql);
+
+ $record = new self($this->db);
+ $record->setVarsFromFetchObj($obj);
+
+ $records[$record->id] = $record;
+
+ $i++;
+ }
+ $this->db->free($resql);
+
+ return $records;
+ } else {
+ $this->errors[] = 'Error '.$this->db->lasterror();
+ dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
+
+ return -1;
+ }
+ }
+
+ /**
+ * Update object into database
+ *
+ * @param User $user User that modifies
+ * @param bool $notrigger false=launch triggers after, true=disable triggers
+ * @return int <0 if KO, >0 if OK
+ */
+ public function update(User $user, $notrigger = false)
+ {
+ return $this->updateCommon($user, $notrigger);
+ }
+
+ /**
+ * Delete object in database
+ *
+ * @param User $user User that deletes
+ * @param bool $notrigger false=launch triggers after, true=disable triggers
+ * @return int <0 if KO, >0 if OK
+ */
+ public function delete(User $user, $notrigger = false)
+ {
+ return $this->deleteCommon($user, $notrigger);
+ //return $this->deleteCommon($user, $notrigger, 1);
+ }
+
+ /**
+ * Delete a line of object in database
+ *
+ * @param User $user User that delete
+ * @param int $idline Id of line to delete
+ * @param bool $notrigger false=launch triggers after, true=disable triggers
+ * @return int >0 if OK, <0 if KO
+ */
+ public function deleteLine(User $user, $idline, $notrigger = false)
+ {
+ if ($this->status < 0) {
+ $this->error = 'ErrorDeleteLineNotAllowedByObjectStatus';
+ return -2;
+ }
+
+ return $this->deleteLineCommon($user, $idline, $notrigger);
+ }
+
+
+ /**
+ * Validate object
+ *
+ * @param User $user User making status change
+ * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
+ * @return int <=0 if OK, 0=Nothing done, >0 if KO
+ */
+ public function validate($user, $notrigger = 0)
+ {
+ global $conf, $langs;
+
+ require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
+
+ $error = 0;
+
+ // Protection
+ if ($this->status == self::STATUS_VALIDATED) {
+ dol_syslog(get_class($this)."::validate action abandonned: already validated", LOG_WARNING);
+ return 0;
+ }
+
+ /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->hrm->job->write))
+ || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->hrm->job->job_advance->validate))))
+ {
+ $this->error='NotEnoughPermissions';
+ dol_syslog(get_class($this)."::valid ".$this->error, LOG_ERR);
+ return -1;
+ }*/
+
+ $now = dol_now();
+
+ $this->db->begin();
+
+ // Define new ref
+ if (!$error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) { // empty should not happened, but when it occurs, the test save life
+ $num = $this->getNextNumRef();
+ } else {
+ $num = $this->ref;
+ }
+ $this->newref = $num;
+
+ if (!empty($num)) {
+ // Validate
+ $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
+ $sql .= " SET ref = '".$this->db->escape($num)."',";
+ $sql .= " status = ".self::STATUS_VALIDATED;
+ if (!empty($this->fields['date_validation'])) {
+ $sql .= ", date_validation = '".$this->db->idate($now)."'";
+ }
+ if (!empty($this->fields['fk_user_valid'])) {
+ $sql .= ", fk_user_valid = ".((int) $user->id);
+ }
+ $sql .= " WHERE rowid = ".((int) $this->id);
+
+ dol_syslog(get_class($this)."::validate()", LOG_DEBUG);
+ $resql = $this->db->query($sql);
+ if (!$resql) {
+ dol_print_error($this->db);
+ $this->error = $this->db->lasterror();
+ $error++;
+ }
+
+ if (!$error && !$notrigger) {
+ // Call trigger
+ $result = $this->call_trigger('JOB_VALIDATE', $user);
+ if ($result < 0) {
+ $error++;
+ }
+ // End call triggers
+ }
+ }
+
+ if (!$error) {
+ $this->oldref = $this->ref;
+
+ // Rename directory if dir was a temporary ref
+ if (preg_match('/^[\(]?PROV/i', $this->ref)) {
+ // Now we rename also files into index
+ $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filename = CONCAT('".$this->db->escape($this->newref)."', SUBSTR(filename, ".(strlen($this->ref) + 1).")), filepath = 'job/".$this->db->escape($this->newref)."'";
+ $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'job/".$this->db->escape($this->ref)."' and entity = ".$conf->entity;
+ $resql = $this->db->query($sql);
+ if (!$resql) {
+ $error++; $this->error = $this->db->lasterror();
+ }
+
+ // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments
+ $oldref = dol_sanitizeFileName($this->ref);
+ $newref = dol_sanitizeFileName($num);
+ $dirsource = $conf->hrm->dir_output.'/job/'.$oldref;
+ $dirdest = $conf->hrm->dir_output.'/job/'.$newref;
+ if (!$error && file_exists($dirsource)) {
+ dol_syslog(get_class($this)."::validate() rename dir ".$dirsource." into ".$dirdest);
+
+ if (@rename($dirsource, $dirdest)) {
+ dol_syslog("Rename ok");
+ // Rename docs starting with $oldref with $newref
+ $listoffiles = dol_dir_list($conf->hrm->dir_output.'/job/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/'));
+ foreach ($listoffiles as $fileentry) {
+ $dirsource = $fileentry['name'];
+ $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource);
+ $dirsource = $fileentry['path'].'/'.$dirsource;
+ $dirdest = $fileentry['path'].'/'.$dirdest;
+ @rename($dirsource, $dirdest);
+ }
+ }
+ }
+ }
+ }
+
+ // Set new ref and current status
+ if (!$error) {
+ $this->ref = $num;
+ $this->status = self::STATUS_VALIDATED;
+ }
+
+ if (!$error) {
+ $this->db->commit();
+ return 1;
+ } else {
+ $this->db->rollback();
+ return -1;
+ }
+ }
+
+ /**
+ * Get last job for user
+ *
+ * @param int $fk_user id of user we need to get last job
+ * @return mixed|string|null
+ */
+ public function getLastJobForUser($fk_user)
+ {
+ global $db;
+
+ $j = new Job($db);
+ $Tab = $j->getForUser($fk_user);
+
+ if (empty($Tab)) return '';
+
+ $job = array_shift($Tab);
+
+ return $job;
+ }
+
+ /**
+ * Get jobs for user
+ *
+ * @param int $userid id of user we need to get job list
+ * @return array of jobs
+ */
+ public function getForUser($userid)
+ {
+ global $db;
+
+ $TReturn = array();
+ $position = new Position($db);
+ $TPosition = $position->getForUser($userid);
+ foreach ($TPosition as $UPosition) {
+ $TReturn[$UPosition->Job->rowid] = $UPosition->Job->ref;
+ }
+ return $TReturn;
+ }
+
+ /**
+ * Set draft status
+ *
+ * @param User $user Object user that modify
+ * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers
+ * @return int <0 if KO, >0 if OK
+ */
+ public function setDraft($user, $notrigger = 0)
+ {
+ // Protection
+ if ($this->status <= self::STATUS_DRAFT) {
+ return 0;
+ }
+
+ /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->hrm->write))
+ || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->hrm->hrm_advance->validate))))
+ {
+ $this->error='Permission denied';
+ return -1;
+ }*/
+
+ return $this->setStatusCommon($user, self::STATUS_DRAFT, $notrigger, 'JOB_UNVALIDATE');
+ }
+
+ /**
+ * Set cancel status
+ *
+ * @param User $user Object user that modify
+ * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers
+ * @return int <0 if KO, 0=Nothing done, >0 if OK
+ */
+ public function cancel($user, $notrigger = 0)
+ {
+ // Protection
+ if ($this->status != self::STATUS_VALIDATED) {
+ return 0;
+ }
+
+ /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->hrm->write))
+ || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->hrm->hrm_advance->validate))))
+ {
+ $this->error='Permission denied';
+ return -1;
+ }*/
+
+ return $this->setStatusCommon($user, self::STATUS_CANCELED, $notrigger, 'JOB_CANCEL');
+ }
+
+ /**
+ * Set back to validated status
+ *
+ * @param User $user Object user that modify
+ * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers
+ * @return int <0 if KO, 0=Nothing done, >0 if OK
+ */
+ public function reopen($user, $notrigger = 0)
+ {
+ // Protection
+ if ($this->status != self::STATUS_CANCELED) {
+ return 0;
+ }
+
+ /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->hrm->write))
+ || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->hrm->hrm_advance->validate))))
+ {
+ $this->error='Permission denied';
+ return -1;
+ }*/
+
+ return $this->setStatusCommon($user, self::STATUS_VALIDATED, $notrigger, 'JOB_REOPEN');
+ }
+
+ /**
+ * Return a link to the object card (with optionaly the picto)
+ *
+ * @param int $withpicto Include picto in link (0=No picto, 1=Include picto into link, 2=Only picto)
+ * @param string $option On what the link point to ('nolink', ...)
+ * @param int $notooltip 1=Disable tooltip
+ * @param string $morecss Add more css on link
+ * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
+ * @return string String with URL
+ */
+ public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $morecss = '', $save_lastsearch_value = -1)
+ {
+ global $conf, $langs, $hookmanager;
+
+ if (!empty($conf->dol_no_mouse_hover)) {
+ $notooltip = 1; // Force disable tooltips
+ }
+
+ $result = '';
+
+ $label = img_picto('', $this->picto).' '.$langs->trans("Job").'';
+ if (isset($this->status)) {
+ $label .= ' '.$this->getLibStatut(5);
+ }
+ $label .= ' ';
+ $label .= ''.$langs->trans('Label').': '.$this->label;
+
+ $url = dol_buildpath('/hrm/job_card.php', 1).'?id='.$this->id;
+
+ if ($option != 'nolink') {
+ // Add param to save lastsearch_values or not
+ $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
+ if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
+ $add_save_lastsearch_values = 1;
+ }
+ if ($add_save_lastsearch_values) {
+ $url .= '&save_lastsearch_values=1';
+ }
+ }
+
+ $linkclose = '';
+ if (empty($notooltip)) {
+ if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
+ $label = $langs->trans("ShowJob");
+ $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
+ }
+ $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"';
+ $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"';
+ } else {
+ $linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
+ }
+
+ if ($option == 'nolink') {
+ $linkstart = '';
+ if ($option == 'nolink') {
+ $linkend = '';
+ } else {
+ $linkend = '';
+ }
+
+ $result .= $linkstart;
+
+ if (empty($this->showphoto_on_popup)) {
+ if ($withpicto) {
+ $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
+ }
+ } else {
+ if ($withpicto) {
+ require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
+
+ list($class, $module) = explode('@', $this->picto);
+ $upload_dir = $conf->$module->multidir_output[$conf->entity]."/$class/".dol_sanitizeFileName($this->label);
+ $filearray = dol_dir_list($upload_dir, "files");
+ $filename = $filearray[0]['name'];
+ if (!empty($filename)) {
+ $pospoint = strpos($filearray[0]['name'], '.');
+
+ $pathtophoto = $class.'/'.$this->label.'/thumbs/'.substr($filename, 0, $pospoint).'_mini'.substr($filename, $pospoint);
+ if (empty($conf->global->{strtoupper($module.'_'.$class).'_FORMATLISTPHOTOSASUSERS'})) {
+ $result .= '
';
+ } else {
+ $result .= '
';
+ }
+
+ $result .= '';
+ } else {
+ $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
+ }
+ }
+ }
+
+ if ($withpicto != 2) {
+ $result .= $this->label;
+ }
+
+ $result .= $linkend;
+ //if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : '');
+
+ global $action, $hookmanager;
+ $hookmanager->initHooks(array('jobdao'));
+ $parameters = array('id'=>$this->id, 'getnomurl'=>$result);
+ $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
+ if ($reshook > 0) {
+ $result = $hookmanager->resPrint;
+ } else {
+ $result .= $hookmanager->resPrint;
+ }
+
+ return $result;
+ }
+
+ /**
+ * Return the label of the status
+ *
+ * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto, 6=Long label + Picto
+ * @return string Label of status
+ */
+ public function getLibStatut($mode = 0)
+ {
+ return $this->LibStatut($this->status, $mode);
+ }
+
+ // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
+ /**
+ * Return the status
+ *
+ * @param int $status Id status
+ * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto, 6=Long label + Picto
+ * @return string Label of status
+ */
+ public function LibStatut($status, $mode = 0)
+ {
+ // phpcs:enable
+ if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
+ global $langs;
+ //$langs->load("hrm");
+ $this->labelStatus[self::STATUS_DRAFT] = $langs->trans('Draft');
+ $this->labelStatus[self::STATUS_VALIDATED] = $langs->trans('Enabled');
+ $this->labelStatus[self::STATUS_CANCELED] = $langs->trans('Disabled');
+ $this->labelStatusShort[self::STATUS_DRAFT] = $langs->trans('Draft');
+ $this->labelStatusShort[self::STATUS_VALIDATED] = $langs->trans('Enabled');
+ $this->labelStatusShort[self::STATUS_CANCELED] = $langs->trans('Disabled');
+ }
+
+ $statusType = 'status'.$status;
+ //if ($status == self::STATUS_VALIDATED) $statusType = 'status1';
+ if ($status == self::STATUS_CANCELED) {
+ $statusType = 'status6';
+ }
+
+ return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
+ }
+
+ /**
+ * Load the info information in the object
+ *
+ * @param int $id Id of object
+ * @return void
+ */
+ public function info($id)
+ {
+ $sql = 'SELECT rowid, date_creation as datec, tms as datem,';
+ $sql .= ' fk_user_creat, fk_user_modif';
+ $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t';
+ $sql .= ' WHERE t.rowid = '.((int) $id);
+ $result = $this->db->query($sql);
+ if ($result) {
+ if ($this->db->num_rows($result)) {
+ $obj = $this->db->fetch_object($result);
+ $this->id = $obj->rowid;
+ if ($obj->fk_user_author) {
+ $cuser = new User($this->db);
+ $cuser->fetch($obj->fk_user_author);
+ $this->user_creation = $cuser;
+ }
+
+ if ($obj->fk_user_valid) {
+ $vuser = new User($this->db);
+ $vuser->fetch($obj->fk_user_valid);
+ $this->user_validation = $vuser;
+ }
+
+ if ($obj->fk_user_cloture) {
+ $cluser = new User($this->db);
+ $cluser->fetch($obj->fk_user_cloture);
+ $this->user_cloture = $cluser;
+ }
+
+ $this->date_creation = $this->db->jdate($obj->datec);
+ $this->date_modification = $this->db->jdate($obj->datem);
+ $this->date_validation = $this->db->jdate($obj->datev);
+ }
+
+ $this->db->free($result);
+ } else {
+ dol_print_error($this->db);
+ }
+ }
+
+ /**
+ * Initialise object with example values
+ * Id must be 0 if object instance is a specimen
+ *
+ * @return void
+ */
+ public function initAsSpecimen()
+ {
+ // Set here init that are not commonf fields
+ // $this->property1 = ...
+ // $this->property2 = ...
+
+ $this->initAsSpecimenCommon();
+ }
+
+ /**
+ * Create an array of lines
+ *
+ * @return array|int array of lines if OK, <0 if KO
+ */
+ public function getLinesArray()
+ {
+ $this->lines = array();
+
+ $objectline = new JobLine($this->db);
+ $result = $objectline->fetchAll('ASC', 'position', 0, 0, array('customsql'=>'fk_job = '.$this->id));
+
+ if (is_numeric($result)) {
+ $this->error = $this->error;
+ $this->errors = $this->errors;
+ return $result;
+ } else {
+ $this->lines = $result;
+ return $this->lines;
+ }
+ }
+
+ /**
+ * Returns the reference to the following non used object depending on the active numbering module.
+ *
+ * @return string Object free reference
+ */
+ public function getNextNumRef()
+ {
+ global $langs, $conf;
+ $langs->load("hrm");
+
+ if (empty($conf->global->hrm_JOB_ADDON)) {
+ $conf->global->hrm_JOB_ADDON = 'mod_job_standard';
+ }
+
+ if (!empty($conf->global->hrm_JOB_ADDON)) {
+ $mybool = false;
+
+ $file = $conf->global->hrm_JOB_ADDON.".php";
+ $classname = $conf->global->hrm_JOB_ADDON;
+
+ // Include file with class
+ $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
+ foreach ($dirmodels as $reldir) {
+ $dir = dol_buildpath($reldir."core/modules/hrm/");
+
+ // Load file with numbering class (if found)
+ $mybool |= @include_once $dir.$file;
+ }
+
+ if ($mybool === false) {
+ dol_print_error('', "Failed to include file ".$file);
+ return '';
+ }
+
+ if (class_exists($classname)) {
+ $obj = new $classname();
+ $numref = $obj->getNextValue($this);
+
+ if ($numref != '' && $numref != '-1') {
+ return $numref;
+ } else {
+ $this->error = $obj->error;
+ //dol_print_error($this->db,get_class($this)."::getNextNumRef ".$obj->error);
+ return "";
+ }
+ } else {
+ print $langs->trans("Error")." ".$langs->trans("ClassNotFound").' '.$classname;
+ return "";
+ }
+ } else {
+ print $langs->trans("ErrorNumberingModuleNotSetup", $this->element);
+ return "";
+ }
+ }
+
+ /**
+ * Create a document onto disk according to template module.
+ *
+ * @param string $modele Force template to use ('' to not force)
+ * @param Translate $outputlangs objet lang a utiliser pour traduction
+ * @param int $hidedetails Hide details of lines
+ * @param int $hidedesc Hide description
+ * @param int $hideref Hide ref
+ * @param null|array $moreparams Array to provide more information
+ * @return int 0 if KO, 1 if OK
+ */
+ public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
+ {
+ global $conf, $langs;
+
+ $result = 0;
+ $includedocgeneration = 0;
+
+ $langs->load("hrm");
+
+ if (!dol_strlen($modele)) {
+ $modele = 'standard_job';
+
+ if (!empty($this->model_pdf)) {
+ $modele = $this->model_pdf;
+ } elseif (!empty($conf->global->JOB_ADDON_PDF)) {
+ $modele = $conf->global->JOB_ADDON_PDF;
+ }
+ }
+
+ $modelpath = "core/modules/hrm/doc/";
+
+ if ($includedocgeneration && !empty($modele)) {
+ $result = $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
+ }
+
+ return $result;
+ }
+
+ /**
+ * Action executed by scheduler
+ * CAN BE A CRON TASK. In such a case, parameters come from the schedule job setup field 'Parameters'
+ * Use public function doScheduledJob($param1, $param2, ...) to get parameters
+ *
+ * @return int 0 if OK, <>0 if KO (this function is used also by cron so only 0 is OK)
+ */
+ public function doScheduledJob()
+ {
+ global $conf, $langs;
+
+ //$conf->global->SYSLOG_FILE = 'DOL_DATA_ROOT/dolibarr_mydedicatedlofile.log';
+
+ $error = 0;
+ $this->output = '';
+ $this->error = '';
+
+ dol_syslog(__METHOD__, LOG_DEBUG);
+
+ $now = dol_now();
+
+ $this->db->begin();
+
+ // ...
+
+ $this->db->commit();
+
+ return $error;
+ }
+}
+
+
+require_once DOL_DOCUMENT_ROOT.'/core/class/commonobjectline.class.php';
+
+/**
+ * Class JobLine. You can also remove this and generate a CRUD class for lines objects.
+ */
+class JobLine extends CommonObjectLine
+{
+ // To complete with content of an object JobLine
+ // We should have a field rowid, fk_job and position
+
+ /**
+ * @var int Does object support extrafields ? 0=No, 1=Yes
+ */
+ public $isextrafieldmanaged = 0;
+
+ /**
+ * Constructor
+ *
+ * @param DoliDb $db Database handler
+ */
+ public function __construct(DoliDB $db)
+ {
+ $this->db = $db;
+ }
+}
diff --git a/htdocs/hrm/class/position.class.php b/htdocs/hrm/class/position.class.php
new file mode 100644
index 00000000000..f349514b69a
--- /dev/null
+++ b/htdocs/hrm/class/position.class.php
@@ -0,0 +1,1091 @@
+
+ * Copyright (C) 2021 Gauthier VERDOL
+ * Copyright (C) 2021 Greg Rastklan
+ * Copyright (C) 2021 Jean-Pascal BOUDET
+ * Copyright (C) 2021 Grégory BLEMAND
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see .
+ */
+
+/**
+ * \file class/position.class.php
+ * \ingroup hrm
+ * \brief This file is a CRUD class file for Position (Create/Read/Update/Delete)
+ */
+
+// Put here all includes required by your class file
+require_once DOL_DOCUMENT_ROOT . '/core/class/commonobject.class.php';
+//require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php';
+//require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
+
+/**
+ * Class for Position
+ */
+class Position extends CommonObject
+{
+ /**
+ * @var string ID of module.
+ */
+ public $module = 'hrm';
+
+ /**
+ * @var string ID to identify managed object.
+ */
+ public $element = 'position';
+
+ /**
+ * @var string Name of table without prefix where object is stored. This is also the key used for extrafields management.
+ */
+ public $table_element = 'hrm_job_user';
+
+ /**
+ * @var int Does this object support multicompany module ?
+ * 0=No test on entity, 1=Test with field entity, 'field@table'=Test with link by field@table
+ */
+ public $ismultientitymanaged = 0;
+
+ /**
+ * @var int Does object support extrafields ? 0=No, 1=Yes
+ */
+ public $isextrafieldmanaged = 1;
+
+ /**
+ * @var string String with name of icon for position. Must be the part after the 'object_' into object_position.png
+ */
+ public $picto = 'user-cog';
+
+
+ const STATUS_DRAFT = 0;
+ const STATUS_VALIDATED = 1;
+ const STATUS_CANCELED = 9;
+
+
+ /**
+ * 'type' field format ('integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter]]', 'sellist:TableName:LabelFieldName[:KeyFieldName[:KeyFieldParent[:Filter]]]', 'varchar(x)', 'double(24,8)', 'real', 'price', 'text', 'text:none', 'html', 'date', 'datetime', 'timestamp', 'duration', 'mail', 'phone', 'url', 'password')
+ * Note: Filter can be a string like "(t.ref:like:'SO-%') or (t.date_creation:<:'20160101') or (t.nature:is:NULL)"
+ * 'label' the translation key.
+ * 'picto' is code of a picto to show before value in forms
+ * 'enabled' is a condition when the field must be managed (Example: 1 or '$conf->global->MY_SETUP_PARAM)
+ * 'position' is the sort order of field.
+ * 'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0).
+ * 'visible' says if field is visible in list (Examples: 0=Not visible, 1=Visible on list and create/update/view forms, 2=Visible on list only, 3=Visible on create/update/view form only (not list), 4=Visible on list and update/view form only (not create). 5=Visible on list and view only (not create/not update). Using a negative value means field is not shown by default on list but can be selected for viewing)
+ * 'noteditable' says if field is not editable (1 or 0)
+ * 'default' is a default value for creation (can still be overwrote by the Setup of Default Values if field is editable in creation form). Note: If default is set to '(PROV)' and field is 'ref', the default value will be set to '(PROVid)' where id is rowid when a new record is created.
+ * 'index' if we want an index in database.
+ * 'foreignkey'=>'tablename.field' if the field is a foreign key (it is recommanded to name the field fk_...).
+ * 'searchall' is 1 if we want to search in this field when making a search from the quick search button.
+ * 'isameasure' must be set to 1 if you want to have a total on list for this field. Field type must be summable like integer or double(24,8).
+ * 'css' and 'cssview' and 'csslist' is the CSS style to use on field. 'css' is used in creation and update. 'cssview' is used in view mode. 'csslist' is used for columns in lists. For example: 'css'=>'minwidth300 maxwidth500 widthcentpercentminusx', 'cssview'=>'wordbreak', 'csslist'=>'tdoverflowmax200'
+ * 'help' is a 'TranslationString' to use to show a tooltip on field. You can also use 'TranslationString:keyfortooltiponlick' for a tooltip on click.
+ * 'showoncombobox' if value of the field must be visible into the label of the combobox that list record
+ * 'disabled' is 1 if we want to have the field locked by a 'disabled' attribute. In most cases, this is never set into the definition of $fields into class, but is set dynamically by some part of code.
+ * 'arrayofkeyval' to set a list of values if type is a list of predefined values. For example: array("0"=>"Draft","1"=>"Active","-1"=>"Cancel"). Note that type can be 'integer' or 'varchar'
+ * 'autofocusoncreate' to have field having the focus on a create form. Only 1 field should have this property set to 1.
+ * 'comment' is not used. You can store here any text of your choice. It is not used by application.
+ *
+ * Note: To have value dynamic, you can set value to 0 in definition and edit the value on the fly into the constructor.
+ */
+
+ // BEGIN MODULEBUILDER PROPERTIES
+ /**
+ * @var array Array with all fields and their property. Do not use it as a static var. It may be modified by constructor.
+ */
+ public $fields=array(
+ 'rowid' => array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>'1', 'position'=>1, 'notnull'=>1, 'visible'=>2, 'index'=>1, 'css'=>'left', 'comment'=>"Id"),
+ //'ref' => array('type'=>'varchar(128)', 'label'=>'Ref', 'enabled'=>'1', 'position'=>20, 'notnull'=>1, 'visible'=>1, 'index'=>1, 'searchall'=>1, 'showoncombobox'=>'1', 'comment'=>"Reference of object"),
+ 'description' => array('type'=>'text', 'label'=>'Description', 'enabled'=>'1', 'position'=>60, 'notnull'=>0, 'visible'=>3,),
+ 'date_creation' => array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>'1', 'position'=>500, 'notnull'=>1, 'visible'=>-2,),
+ 'tms' => array('type'=>'timestamp', 'label'=>'DateModification', 'enabled'=>'1', 'position'=>501, 'notnull'=>0, 'visible'=>-2,),
+ 'fk_contrat' => array('type'=>'integer:Contrat:contrat/class/contrat.class.php', 'label'=>'fk_contrat', 'enabled'=>'1', 'position'=>50, 'notnull'=>0, 'visible'=>0,),
+ 'fk_user' => array('type'=>'integer:User:user/class/user.class.php', 'label'=>'Employee', 'enabled'=>'1', 'position'=>55, 'notnull'=>1, 'visible'=>1,),
+ 'fk_job' => array('type'=>'integer:Job:/hrm/class/job.class.php', 'label'=>'Job', 'enabled'=>'1', 'position'=>56, 'notnull'=>1, 'visible'=>1,),
+ 'date_start' => array('type'=>'date', 'label'=>'DateStart', 'enabled'=>'1', 'position'=>51, 'notnull'=>1, 'visible'=>1,),
+ 'date_end' => array('type'=>'date', 'label'=>'DateEnd', 'enabled'=>'1', 'position'=>52, 'notnull'=>0, 'visible'=>1,),
+ 'commentaire_abandon' => array('type'=>'varchar(255)', 'label'=>'AbandonmentComment', 'enabled'=>'1', 'position'=>502, 'notnull'=>0, 'visible'=>1,),
+ 'note_public' => array('type'=>'html', 'label'=>'NotePublic', 'enabled'=>'1', 'position'=>70, 'notnull'=>0, 'visible'=>0,),
+ 'note_private' => array('type'=>'html', 'label'=>'NotePrivate', 'enabled'=>'1', 'position'=>71, 'notnull'=>0, 'visible'=>0,),
+ 'fk_user_creat' => array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserAuthor', 'enabled'=>'1', 'position'=>510, 'notnull'=>1, 'visible'=>-2, 'foreignkey'=>'user.rowid',),
+ 'fk_user_modif' => array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserModif', 'enabled'=>'1', 'position'=>511, 'notnull'=>-1, 'visible'=>-2,),
+ );
+ public $rowid;
+ public $ref;
+ public $description;
+ public $date_creation;
+ public $tms;
+ public $fk_contrat;
+ public $fk_user;
+ public $fk_job;
+ public $date_start;
+ public $date_end;
+ public $commentaire_abandon;
+ public $note_public;
+ public $note_private;
+ public $fk_user_creat;
+ public $fk_user_modif;
+
+
+ // END MODULEBUILDER PROPERTIES
+
+
+ // If this object has a subtable with lines
+
+ // /**
+ // * @var string Name of subtable line
+ // */
+ // public $table_element_line = 'hrm_job_userline';
+
+ // /**
+ // * @var string Field with ID of parent key if this object has a parent
+ // */
+ // public $fk_element = 'fk_position';
+
+ // /**
+ // * @var string Name of subtable class that manage subtable lines
+ // */
+ // public $class_element_line = 'Positionline';
+
+ // /**
+ // * @var array List of child tables. To test if we can delete object.
+ // */
+ // protected $childtables = array();
+
+ // /**
+ // * @var array List of child tables. To know object to delete on cascade.
+ // * If name matches '@ClassNAme:FilePathClass;ParentFkFieldName' it will
+ // * call method deleteByParentField(parentId, ParentFkFieldName) to fetch and delete child object
+ // */
+ // protected $childtablesoncascade = array('hrm_job_userdet');
+
+ // /**
+ // * @var PositionLine[] Array of subtable lines
+ // */
+ // public $lines = array();
+
+
+ /**
+ * Constructor
+ *
+ * @param DoliDb $db Database handler
+ */
+ public function __construct(DoliDB $db)
+ {
+ global $conf, $langs;
+
+ $this->db = $db;
+
+ if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID) && isset($this->fields['rowid'])) {
+ //$this->fields['rowid']['visible'] = 0;
+ }
+ if (empty($conf->multicompany->enabled) && isset($this->fields['entity'])) {
+ $this->fields['entity']['enabled'] = 0;
+ }
+
+ // Example to show how to set values of fields definition dynamically
+ /*if ($user->rights->hrm->position->read) {
+ $this->fields['myfield']['visible'] = 1;
+ $this->fields['myfield']['noteditable'] = 0;
+ }*/
+
+ // Unset fields that are disabled
+ foreach ($this->fields as $key => $val) {
+ if (isset($val['enabled']) && empty($val['enabled'])) {
+ unset($this->fields[$key]);
+ }
+ }
+
+ // Translate some data of arrayofkeyval
+ if (is_object($langs)) {
+ foreach ($this->fields as $key => $val) {
+ if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
+ foreach ($val['arrayofkeyval'] as $key2 => $val2) {
+ $this->fields[$key]['arrayofkeyval'][$key2] = $langs->trans($val2);
+ }
+ }
+ }
+ }
+ }
+
+ /**
+ * Create object into database
+ *
+ * @param User $user User that creates
+ * @param bool $notrigger false=launch triggers after, true=disable triggers
+ * @return int <0 if KO, Id of created object if OK
+ */
+ public function create(User $user, $notrigger = false)
+ {
+ $resultcreate = $this->createCommon($user, $notrigger);
+
+ //$resultvalidate = $this->validate($user, $notrigger);
+
+ return $resultcreate;
+ }
+
+ /**
+ * Clone an object into another one
+ *
+ * @param User $user User that creates
+ * @param int $fromid Id of object to clone
+ * @return mixed New object created, <0 if KO
+ */
+ public function createFromClone(User $user, $fromid)
+ {
+ global $langs, $extrafields;
+ $error = 0;
+
+ dol_syslog(__METHOD__, LOG_DEBUG);
+
+ $object = new self($this->db);
+
+ $this->db->begin();
+
+ // Load source object
+ $result = $object->fetchCommon($fromid);
+ if ($result > 0 && !empty($object->table_element_line)) {
+ $object->fetchLines();
+ }
+
+ // get lines so they will be clone
+ //foreach($this->lines as $line)
+ // $line->fetch_optionals();
+
+ // Reset some properties
+ unset($object->id);
+ unset($object->fk_user_creat);
+ unset($object->import_key);
+
+ // Clear fields
+ if (property_exists($object, 'ref')) {
+ $object->ref = empty($this->fields['ref']['default']) ? "Copy_Of_" . $object->ref : $this->fields['ref']['default'];
+ }
+ if (property_exists($object, 'label')) {
+ $object->label = empty($this->fields['label']['default']) ? $langs->trans("CopyOf") . " " . $object->label : $this->fields['label']['default'];
+ }
+ if (property_exists($object, 'status')) {
+ $object->status = self::STATUS_DRAFT;
+ }
+ if (property_exists($object, 'date_creation')) {
+ $object->date_creation = dol_now();
+ }
+ if (property_exists($object, 'date_modification')) {
+ $object->date_modification = null;
+ }
+ // ...
+ // Clear extrafields that are unique
+ if (is_array($object->array_options) && count($object->array_options) > 0) {
+ $extrafields->fetch_name_optionals_label($this->table_element);
+ foreach ($object->array_options as $key => $option) {
+ $shortkey = preg_replace('/options_/', '', $key);
+ if (!empty($extrafields->attributes[$this->table_element]['unique'][$shortkey])) {
+ //var_dump($key); var_dump($clonedObj->array_options[$key]); exit;
+ unset($object->array_options[$key]);
+ }
+ }
+ }
+
+ // Create clone
+ $object->context['createfromclone'] = 'createfromclone';
+ $result = $object->createCommon($user);
+ if ($result < 0) {
+ $error++;
+ $this->error = $object->error;
+ $this->errors = $object->errors;
+ }
+
+ if (!$error) {
+ // copy internal contacts
+ if ($this->copy_linked_contact($object, 'internal') < 0) {
+ $error++;
+ }
+ }
+
+ if (!$error) {
+ // copy external contacts if same company
+ if (property_exists($this, 'fk_soc') && $this->fk_soc == $object->socid) {
+ if ($this->copy_linked_contact($object, 'external') < 0) {
+ $error++;
+ }
+ }
+ }
+
+ unset($object->context['createfromclone']);
+
+ // End
+ if (!$error) {
+ $this->db->commit();
+ return $object;
+ } else {
+ $this->db->rollback();
+ return -1;
+ }
+ }
+
+ /**
+ * Load object in memory from the database
+ *
+ * @param int $id Id object
+ * @param string $ref Ref
+ * @return int <0 if KO, 0 if not found, >0 if OK
+ */
+ public function fetch($id, $ref = null)
+ {
+ $result = $this->fetchCommon($id, $ref);
+ if ($result > 0 && !empty($this->table_element_line)) {
+ $this->fetchLines();
+ }
+ return $result;
+ }
+
+ /**
+ * Load object lines in memory from the database
+ *
+ * @return int <0 if KO, 0 if not found, >0 if OK
+ */
+ public function fetchLines()
+ {
+ $this->lines = array();
+
+ $result = $this->fetchLinesCommon();
+ return $result;
+ }
+
+
+ /**
+ * Load list of objects in memory from the database.
+ *
+ * @param string $sortorder Sort Order
+ * @param string $sortfield Sort field
+ * @param int $limit limit
+ * @param int $offset Offset
+ * @param array $filter Filter array. Example array('field'=>'valueforlike', 'customurl'=>...)
+ * @param string $filtermode Filter mode (AND or OR)
+ * @return array|int int <0 if KO, array of pages if OK
+ */
+ public function fetchAll($sortorder = '', $sortfield = '', $limit = 0, $offset = 0, array $filter = array(), $filtermode = 'AND')
+ {
+ global $conf;
+
+ dol_syslog(__METHOD__, LOG_DEBUG);
+
+ $records = array();
+
+ $sql = 'SELECT ';
+ $sql .= $this->getFieldList('t');
+ $sql .= ' FROM ' . MAIN_DB_PREFIX . $this->table_element . ' as t';
+ if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
+ $sql .= ' WHERE t.entity IN (' . getEntity($this->table_element) . ')';
+ } else {
+ $sql .= ' WHERE 1 = 1';
+ }
+ // Manage filter
+ $sqlwhere = array();
+ if (count($filter) > 0) {
+ foreach ($filter as $key => $value) {
+ if ($key == 't.rowid') {
+ $sqlwhere[] = $key . '=' . $value;
+ } elseif (in_array($this->fields[$key]['type'], array('date', 'datetime', 'timestamp'))) {
+ $sqlwhere[] = $key . ' = \'' . $this->db->idate($value) . '\'';
+ } elseif ($key == 'customsql') {
+ $sqlwhere[] = $value;
+ } elseif (strpos($value, '%') === false) {
+ $sqlwhere[] = $key . ' IN (' . $this->db->sanitize($this->db->escape($value)) . ')';
+ } else {
+ $sqlwhere[] = $key . ' LIKE \'%' . $this->db->escape($value) . '%\'';
+ }
+ }
+ }
+ if (count($sqlwhere) > 0) {
+ $sql .= " AND (".implode(" ".$filtermode." ", $sqlwhere).")";
+ }
+
+ if (!empty($sortfield)) {
+ $sql .= $this->db->order($sortfield, $sortorder);
+ }
+ if (!empty($limit)) {
+ $sql .= ' ' . $this->db->plimit($limit, $offset);
+ }
+
+ $resql = $this->db->query($sql);
+ if ($resql) {
+ $num = $this->db->num_rows($resql);
+ $i = 0;
+ while ($i < ($limit ? min($limit, $num) : $num)) {
+ $obj = $this->db->fetch_object($resql);
+
+ $record = new self($this->db);
+ $record->setVarsFromFetchObj($obj);
+
+ $records[$record->id] = $record;
+
+ $i++;
+ }
+ $this->db->free($resql);
+
+ return $records;
+ } else {
+ $this->errors[] = 'Error ' . $this->db->lasterror();
+ dol_syslog(__METHOD__ . ' ' . join(',', $this->errors), LOG_ERR);
+
+ return -1;
+ }
+ }
+
+ /**
+ * Update object into database
+ *
+ * @param User $user User that modifies
+ * @param bool $notrigger false=launch triggers after, true=disable triggers
+ * @return int <0 if KO, >0 if OK
+ */
+ public function update(User $user, $notrigger = false)
+ {
+ return $this->updateCommon($user, $notrigger);
+ }
+
+ /**
+ * Delete object in database
+ *
+ * @param User $user User that deletes
+ * @param bool $notrigger false=launch triggers after, true=disable triggers
+ * @return int <0 if KO, >0 if OK
+ */
+ public function delete(User $user, $notrigger = false)
+ {
+ return $this->deleteCommon($user, $notrigger);
+ //return $this->deleteCommon($user, $notrigger, 1);
+ }
+
+ /**
+ * Delete a line of object in database
+ *
+ * @param User $user User that delete
+ * @param int $idline Id of line to delete
+ * @param bool $notrigger false=launch triggers after, true=disable triggers
+ * @return int >0 if OK, <0 if KO
+ */
+ public function deleteLine(User $user, $idline, $notrigger = false)
+ {
+ if ($this->status < 0) {
+ $this->error = 'ErrorDeleteLineNotAllowedByObjectStatus';
+ return -2;
+ }
+
+ return $this->deleteLineCommon($user, $idline, $notrigger);
+ }
+
+
+ /**
+ * Validate object
+ *
+ * @param User $user User making status change
+ * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
+ * @return int <=0 if OK, 0=Nothing done, >0 if KO
+ */
+ public function validate($user, $notrigger = 0)
+ {
+ global $conf, $langs;
+
+ require_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php';
+
+ $error = 0;
+
+ // Protection
+ if ($this->status == self::STATUS_VALIDATED) {
+ dol_syslog(get_class($this) . "::validate action abandonned: already validated", LOG_WARNING);
+ return 0;
+ }
+
+ /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->hrm->position->write))
+ || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->hrm->position->position_advance->validate))))
+ {
+ $this->error='NotEnoughPermissions';
+ dol_syslog(get_class($this)."::valid ".$this->error, LOG_ERR);
+ return -1;
+ }*/
+
+ $now = dol_now();
+
+ $this->db->begin();
+
+ // Define new ref
+ if (!$error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) { // empty should not happened, but when it occurs, the test save life
+ $num = $this->getNextNumRef();
+ } else {
+ $num = $this->ref;
+ }
+ $this->newref = $num;
+
+ if (!empty($num)) {
+ // Validate
+ $sql = "UPDATE " . MAIN_DB_PREFIX . $this->table_element;
+ $sql .= " SET ref = '" . $this->db->escape($num) . "',";
+ $sql .= " status = " . self::STATUS_VALIDATED;
+ if (!empty($this->fields['date_validation'])) {
+ $sql .= ", date_validation = '" . $this->db->idate($now) . "'";
+ }
+ if (!empty($this->fields['fk_user_valid'])) {
+ $sql .= ", fk_user_valid = " . ((int) $user->id);
+ }
+ $sql .= " WHERE rowid = " . ((int) $this->id);
+
+ dol_syslog(get_class($this) . "::validate()", LOG_DEBUG);
+ $resql = $this->db->query($sql);
+ if (!$resql) {
+ dol_print_error($this->db);
+ $this->error = $this->db->lasterror();
+ $error++;
+ }
+
+ if (!$error && !$notrigger) {
+ // Call trigger
+ $result = $this->call_trigger('POSITION_VALIDATE', $user);
+ if ($result < 0) {
+ $error++;
+ }
+ // End call triggers
+ }
+ }
+
+ if (!$error) {
+ $this->oldref = $this->ref;
+
+ // Rename directory if dir was a temporary ref
+ if (preg_match('/^[\(]?PROV/i', $this->ref)) {
+ // Now we rename also files into index
+ $sql = 'UPDATE ' . MAIN_DB_PREFIX . "ecm_files set filename = CONCAT('" . $this->db->escape($this->newref) . "', SUBSTR(filename, " . (strlen($this->ref) + 1) . ")), filepath = 'position/" . $this->db->escape($this->newref) . "'";
+ $sql .= " WHERE filename LIKE '" . $this->db->escape($this->ref) . "%' AND filepath = 'position/" . $this->db->escape($this->ref) . "' and entity = " . $conf->entity;
+ $resql = $this->db->query($sql);
+ if (!$resql) {
+ $error++;
+ $this->error = $this->db->lasterror();
+ }
+
+ // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments
+ $oldref = dol_sanitizeFileName($this->ref);
+ $newref = dol_sanitizeFileName($num);
+ $dirsource = $conf->hrm->dir_output . '/position/' . $oldref;
+ $dirdest = $conf->hrm->dir_output . '/position/' . $newref;
+ if (!$error && file_exists($dirsource)) {
+ dol_syslog(get_class($this) . "::validate() rename dir " . $dirsource . " into " . $dirdest);
+
+ if (@rename($dirsource, $dirdest)) {
+ dol_syslog("Rename ok");
+ // Rename docs starting with $oldref with $newref
+ $listoffiles = dol_dir_list($conf->hrm->dir_output . '/position/' . $newref, 'files', 1, '^' . preg_quote($oldref, '/'));
+ foreach ($listoffiles as $fileentry) {
+ $dirsource = $fileentry['name'];
+ $dirdest = preg_replace('/^' . preg_quote($oldref, '/') . '/', $newref, $dirsource);
+ $dirsource = $fileentry['path'] . '/' . $dirsource;
+ $dirdest = $fileentry['path'] . '/' . $dirdest;
+ @rename($dirsource, $dirdest);
+ }
+ }
+ }
+ }
+ }
+
+ // Set new ref and current status
+ if (!$error) {
+ $this->ref = $num;
+ $this->status = self::STATUS_VALIDATED;
+ }
+
+ if (!$error) {
+ $this->db->commit();
+ return 1;
+ } else {
+ $this->db->rollback();
+ return -1;
+ }
+ }
+
+
+ /**
+ * Set draft status
+ *
+ * @param User $user Object user that modify
+ * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers
+ * @return int <0 if KO, >0 if OK
+ */
+ public function setDraft($user, $notrigger = 0)
+ {
+ // Protection
+ if ($this->status <= self::STATUS_DRAFT) {
+ return 0;
+ }
+
+ /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->hrm->write))
+ || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->hrm->hrm_advance->validate))))
+ {
+ $this->error='Permission denied';
+ return -1;
+ }*/
+
+ return $this->setStatusCommon($user, self::STATUS_DRAFT, $notrigger, 'POSITION_UNVALIDATE');
+ }
+
+ /**
+ * Set cancel status
+ *
+ * @param User $user Object user that modify
+ * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers
+ * @return int <0 if KO, 0=Nothing done, >0 if OK
+ */
+ public function cancel($user, $notrigger = 0)
+ {
+ // Protection
+ if ($this->status != self::STATUS_VALIDATED) {
+ return 0;
+ }
+
+ /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->hrm->write))
+ || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->hrm->hrm_advance->validate))))
+ {
+ $this->error='Permission denied';
+ return -1;
+ }*/
+
+ return $this->setStatusCommon($user, self::STATUS_CANCELED, $notrigger, 'POSITION_CANCEL');
+ }
+
+ /**
+ * Set back to validated status
+ *
+ * @param User $user Object user that modify
+ * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers
+ * @return int <0 if KO, 0=Nothing done, >0 if OK
+ */
+ public function reopen($user, $notrigger = 0)
+ {
+ // Protection
+ if ($this->status != self::STATUS_CANCELED) {
+ return 0;
+ }
+
+ /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->hrm->write))
+ || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->hrm->hrm_advance->validate))))
+ {
+ $this->error='Permission denied';
+ return -1;
+ }*/
+
+ return $this->setStatusCommon($user, self::STATUS_VALIDATED, $notrigger, 'POSITION_REOPEN');
+ }
+
+ /**
+ * Return a link to the object card (with optionaly the picto)
+ *
+ * @param int $withpicto Include picto in link (0=No picto, 1=Include picto into link, 2=Only picto)
+ * @param string $option On what the link point to ('nolink', ...)
+ * @param int $notooltip 1=Disable tooltip
+ * @param string $morecss Add more css on link
+ * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
+ * @return string String with URL
+ */
+ public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $morecss = '', $save_lastsearch_value = -1)
+ {
+ global $conf, $langs, $hookmanager;
+
+ if (!empty($conf->dol_no_mouse_hover)) {
+ $notooltip = 1; // Force disable tooltips
+ }
+
+ $result = '';
+
+ $label = img_picto('', $this->picto) . ' ' . $langs->trans("Position") . '';
+ if (isset($this->status)) {
+ $label .= ' ' . $this->getLibStatut(5);
+ }
+ $label .= ' ';
+ $label .= '' . $langs->trans('Ref') . ': ' . $this->ref;
+
+ $url = dol_buildpath('/hrm/position_card.php', 1) . '?id=' . $this->id;
+
+ if ($option != 'nolink') {
+ // Add param to save lastsearch_values or not
+ $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
+ if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
+ $add_save_lastsearch_values = 1;
+ }
+ if ($add_save_lastsearch_values) {
+ $url .= '&save_lastsearch_values=1';
+ }
+ }
+
+ $linkclose = '';
+ if (empty($notooltip)) {
+ if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
+ $label = $langs->trans("ShowPosition");
+ $linkclose .= ' alt="' . dol_escape_htmltag($label, 1) . '"';
+ }
+ $linkclose .= ' title="' . dol_escape_htmltag($label, 1) . '"';
+ $linkclose .= ' class="classfortooltip' . ($morecss ? ' ' . $morecss : '') . '"';
+ } else {
+ $linkclose = ($morecss ? ' class="' . $morecss . '"' : '');
+ }
+
+ if ($option == 'nolink') {
+ $linkstart = '';
+ if ($option == 'nolink') {
+ $linkend = '';
+ } else {
+ $linkend = '';
+ }
+
+ $result .= $linkstart;
+
+ if (empty($this->showphoto_on_popup)) {
+ if ($withpicto) {
+ $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="' . (($withpicto != 2) ? 'paddingright ' : '') . 'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
+ }
+ } else {
+ if ($withpicto) {
+ require_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php';
+
+ list($class, $module) = explode('@', $this->picto);
+ $upload_dir = $conf->$module->multidir_output[$conf->entity] . "/$class/" . dol_sanitizeFileName($this->ref);
+ $filearray = dol_dir_list($upload_dir, "files");
+ $filename = $filearray[0]['name'];
+ if (!empty($filename)) {
+ $pospoint = strpos($filearray[0]['name'], '.');
+
+ $pathtophoto = $class . '/' . $this->ref . '/thumbs/' . substr($filename, 0, $pospoint) . '_mini' . substr($filename, $pospoint);
+ if (empty($conf->global->{strtoupper($module . '_' . $class) . '_FORMATLISTPHOTOSASUSERS'})) {
+ $result .= '
';
+ } else {
+ $result .= '
';
+ }
+
+ $result .= '';
+ } else {
+ $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="' . (($withpicto != 2) ? 'paddingright ' : '') . 'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
+ }
+ }
+ }
+
+ if ($withpicto != 2) {
+ $result .= $this->ref;
+ }
+
+ $result .= $linkend;
+ //if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : '');
+
+ global $action, $hookmanager;
+ $hookmanager->initHooks(array('positiondao'));
+ $parameters = array('id' => $this->id, 'getnomurl' => $result);
+ $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
+ if ($reshook > 0) {
+ $result = $hookmanager->resPrint;
+ } else {
+ $result .= $hookmanager->resPrint;
+ }
+
+ return $result;
+ }
+
+ /**
+ * Return the label of the status
+ *
+ * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto, 6=Long label + Picto
+ * @return string Label of status
+ */
+ public function getLibStatut($mode = 0)
+ {
+ return $this->LibStatut($this->status, $mode);
+ }
+
+ // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
+
+ /**
+ * Return the status
+ *
+ * @param int $status Id status
+ * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto, 6=Long label + Picto
+ * @return string Label of status
+ */
+ public function LibStatut($status, $mode = 0)
+ {
+ // phpcs:enable
+ if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
+ global $langs;
+ //$langs->load("hrm");
+ $this->labelStatus[self::STATUS_DRAFT] = $langs->trans('Draft');
+ $this->labelStatus[self::STATUS_VALIDATED] = $langs->trans('Enabled');
+ $this->labelStatus[self::STATUS_CANCELED] = $langs->trans('Disabled');
+ $this->labelStatusShort[self::STATUS_DRAFT] = $langs->trans('Draft');
+ $this->labelStatusShort[self::STATUS_VALIDATED] = $langs->trans('Enabled');
+ $this->labelStatusShort[self::STATUS_CANCELED] = $langs->trans('Disabled');
+ }
+
+ $statusType = 'status' . $status;
+ //if ($status == self::STATUS_VALIDATED) $statusType = 'status1';
+ if ($status == self::STATUS_CANCELED) {
+ $statusType = 'status6';
+ }
+
+ return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
+ }
+
+ /**
+ * Load the info information in the object
+ *
+ * @param int $id Id of object
+ * @return void
+ */
+ public function info($id)
+ {
+ $sql = 'SELECT rowid, date_creation as datec, tms as datem,';
+ $sql .= ' fk_user_creat, fk_user_modif';
+ $sql .= ' FROM ' . MAIN_DB_PREFIX . $this->table_element . ' as t';
+ $sql .= ' WHERE t.rowid = ' . ((int) $id);
+ $result = $this->db->query($sql);
+ if ($result) {
+ if ($this->db->num_rows($result)) {
+ $obj = $this->db->fetch_object($result);
+ $this->id = $obj->rowid;
+ if ($obj->fk_user_author) {
+ $cuser = new User($this->db);
+ $cuser->fetch($obj->fk_user_author);
+ $this->user_creation = $cuser;
+ }
+
+ if ($obj->fk_user_valid) {
+ $vuser = new User($this->db);
+ $vuser->fetch($obj->fk_user_valid);
+ $this->user_validation = $vuser;
+ }
+
+ if ($obj->fk_user_cloture) {
+ $cluser = new User($this->db);
+ $cluser->fetch($obj->fk_user_cloture);
+ $this->user_cloture = $cluser;
+ }
+
+ $this->date_creation = $this->db->jdate($obj->datec);
+ $this->date_modification = $this->db->jdate($obj->datem);
+ $this->date_validation = $this->db->jdate($obj->datev);
+ }
+
+ $this->db->free($result);
+ } else {
+ dol_print_error($this->db);
+ }
+ }
+
+ /**
+ * Initialise object with example values
+ * Id must be 0 if object instance is a specimen
+ *
+ * @return void
+ */
+ public function initAsSpecimen()
+ {
+ // Set here init that are not commonf fields
+ // $this->property1 = ...
+ // $this->property2 = ...
+
+ $this->initAsSpecimenCommon();
+ }
+
+ /**
+ * Create an array of lines
+ *
+ * @return array|int array of lines if OK, <0 if KO
+ */
+ public function getLinesArray()
+ {
+ $this->lines = array();
+
+ $objectline = new PositionLine($this->db);
+ $result = $objectline->fetchAll('ASC', 'position', 0, 0, array('customsql' => 'fk_position = ' . $this->id));
+
+ if (is_numeric($result)) {
+ $this->error = $this->error;
+ $this->errors = $this->errors;
+ return $result;
+ } else {
+ $this->lines = $result;
+ return $this->lines;
+ }
+ }
+
+ /**
+ * Returns the reference to the following non used object depending on the active numbering module.
+ *
+ * @return string Object free reference
+ */
+ public function getNextNumRef()
+ {
+ global $langs, $conf;
+ $langs->load("hrm");
+
+ if (empty($conf->global->hrm_POSITION_ADDON)) {
+ $conf->global->hrm_POSITION_ADDON = 'mod_position_standard';
+ }
+
+ if (!empty($conf->global->hrm_POSITION_ADDON)) {
+ $mybool = false;
+
+ $file = $conf->global->hrm_POSITION_ADDON . ".php";
+ $classname = $conf->global->hrm_POSITION_ADDON;
+
+ // Include file with class
+ $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
+ foreach ($dirmodels as $reldir) {
+ $dir = dol_buildpath($reldir . "core/modules/hrm/");
+
+ // Load file with numbering class (if found)
+ $mybool |= @include_once $dir . $file;
+ }
+
+ if ($mybool === false) {
+ dol_print_error('', "Failed to include file " . $file);
+ return '';
+ }
+
+ if (class_exists($classname)) {
+ $obj = new $classname();
+ $numref = $obj->getNextValue($this);
+
+ if ($numref != '' && $numref != '-1') {
+ return $numref;
+ } else {
+ $this->error = $obj->error;
+ //dol_print_error($this->db,get_class($this)."::getNextNumRef ".$obj->error);
+ return "";
+ }
+ } else {
+ print $langs->trans("Error") . " " . $langs->trans("ClassNotFound") . ' ' . $classname;
+ return "";
+ }
+ } else {
+ print $langs->trans("ErrorNumberingModuleNotSetup", $this->element);
+ return "";
+ }
+ }
+
+ /**
+ * @param int $userid id of user we need to get position list
+ * @return array|int of positions of user with for each of them the job fetched into that array
+ */
+ public function getForUser($userid)
+ {
+ $TPosition = array();
+
+ $TPosition = $this->fetchAll('ASC', 't.rowid', 0, 0, array('customsql' => 'fk_user=' . $userid));
+
+ return $TPosition;
+ }
+
+ /**
+ * Create a document onto disk according to template module.
+ *
+ * @param string $modele Force template to use ('' to not force)
+ * @param Translate $outputlangs objet lang a utiliser pour traduction
+ * @param int $hidedetails Hide details of lines
+ * @param int $hidedesc Hide description
+ * @param int $hideref Hide ref
+ * @param null|array $moreparams Array to provide more information
+ * @return int 0 if KO, 1 if OK
+ */
+ public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
+ {
+ global $conf, $langs;
+
+ $result = 0;
+ $includedocgeneration = 0;
+
+ $langs->load("hrm");
+
+ if (!dol_strlen($modele)) {
+ $modele = 'standard_position';
+
+ if (!empty($this->model_pdf)) {
+ $modele = $this->model_pdf;
+ } elseif (!empty($conf->global->POSITION_ADDON_PDF)) {
+ $modele = $conf->global->POSITION_ADDON_PDF;
+ }
+ }
+
+ $modelpath = "core/modules/hrm/doc/";
+
+ if ($includedocgeneration && !empty($modele)) {
+ $result = $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
+ }
+
+ return $result;
+ }
+
+ /**
+ * Action executed by scheduler
+ * CAN BE A CRON TASK. In such a case, parameters come from the schedule job setup field 'Parameters'
+ * Use public function doScheduledJob($param1, $param2, ...) to get parameters
+ *
+ * @return int 0 if OK, <>0 if KO (this function is used also by cron so only 0 is OK)
+ */
+ public function doScheduledJob()
+ {
+ global $conf, $langs;
+
+ //$conf->global->SYSLOG_FILE = 'DOL_DATA_ROOT/dolibarr_mydedicatedlofile.log';
+
+ $error = 0;
+ $this->output = '';
+ $this->error = '';
+
+ dol_syslog(__METHOD__, LOG_DEBUG);
+
+ $now = dol_now();
+
+ $this->db->begin();
+
+ // ...
+
+ $this->db->commit();
+
+ return $error;
+ }
+}
+
+
+require_once DOL_DOCUMENT_ROOT . '/core/class/commonobjectline.class.php';
+
+/**
+ * Class PositionLine. You can also remove this and generate a CRUD class for lines objects.
+ */
+class PositionLine extends CommonObjectLine
+{
+ // To complete with content of an object PositionLine
+ // We should have a field rowid, fk_position and position
+
+ /**
+ * @var int Does object support extrafields ? 0=No, 1=Yes
+ */
+ public $isextrafieldmanaged = 0;
+
+ /**
+ * Constructor
+ *
+ * @param DoliDb $db Database handler
+ */
+ public function __construct(DoliDB $db)
+ {
+ $this->db = $db;
+ }
+}
diff --git a/htdocs/hrm/class/skill.class.php b/htdocs/hrm/class/skill.class.php
new file mode 100644
index 00000000000..ba7d0f43d3c
--- /dev/null
+++ b/htdocs/hrm/class/skill.class.php
@@ -0,0 +1,1109 @@
+
+ * Copyright (C) 2021 Gauthier VERDOL
+ * Copyright (C) 2021 Greg Rastklan
+ * Copyright (C) 2021 Jean-Pascal BOUDET
+ * Copyright (C) 2021 Grégory BLEMAND
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see .
+ */
+
+/**
+ * \file class/skill.class.php
+ * \ingroup hrm
+ * \brief This file is a CRUD class file for Skill (Create/Read/Update/Delete)
+ */
+
+// Put here all includes required by your class file
+require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
+//require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php';
+//require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
+
+/**
+ * Class for Skill
+ */
+class Skill extends CommonObject
+{
+ /**
+ * @var string ID of module.
+ */
+ public $module = 'hrm';
+
+ /**
+ * @var string ID to identify managed object.
+ */
+ public $element = 'skill';
+
+ /**
+ * @var string Name of table without prefix where object is stored. This is also the key used for extrafields management.
+ */
+ public $table_element = 'hrm_skill';
+
+
+ /**
+ * @var string Name of subtable line
+ */
+ public $table_element_line = 'skilldet';
+
+ /**
+ * @var int Does this object support multicompany module ?
+ * 0=No test on entity, 1=Test with field entity, 'field@table'=Test with link by field@table
+ */
+ public $ismultientitymanaged = 0;
+
+ /**
+ * @var int Does object support extrafields ? 0=No, 1=Yes
+ */
+ public $isextrafieldmanaged = 1;
+
+ /**
+ * @var string String with name of icon for skill. Must be the part after the 'object_' into object_skill.png
+ */
+ public $picto = 'shapes';
+
+
+ const STATUS_DRAFT = 0;
+ const STATUS_VALIDATED = 1;
+ const STATUS_CANCELED = 9;
+ const DEFAULT_MAX_RANK_PER_SKILL = 5;
+
+ /**
+ * 'type' field format ('integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter]]', 'sellist:TableName:LabelFieldName[:KeyFieldName[:KeyFieldParent[:Filter]]]', 'varchar(x)', 'double(24,8)', 'real', 'price', 'text', 'text:none', 'html', 'date', 'datetime', 'timestamp', 'duration', 'mail', 'phone', 'url', 'password')
+ * Note: Filter can be a string like "(t.ref:like:'SO-%') or (t.date_creation:<:'20160101') or (t.nature:is:NULL)"
+ * 'label' the translation key.
+ * 'picto' is code of a picto to show before value in forms
+ * 'enabled' is a condition when the field must be managed (Example: 1 or '$conf->global->MY_SETUP_PARAM)
+ * 'position' is the sort order of field.
+ * 'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0).
+ * 'visible' says if field is visible in list (Examples: 0=Not visible, 1=Visible on list and create/update/view forms, 2=Visible on list only, 3=Visible on create/update/view form only (not list), 4=Visible on list and update/view form only (not create). 5=Visible on list and view only (not create/not update). Using a negative value means field is not shown by default on list but can be selected for viewing)
+ * 'noteditable' says if field is not editable (1 or 0)
+ * 'default' is a default value for creation (can still be overwrote by the Setup of Default Values if field is editable in creation form). Note: If default is set to '(PROV)' and field is 'ref', the default value will be set to '(PROVid)' where id is rowid when a new record is created.
+ * 'index' if we want an index in database.
+ * 'foreignkey'=>'tablename.field' if the field is a foreign key (it is recommanded to name the field fk_...).
+ * 'searchall' is 1 if we want to search in this field when making a search from the quick search button.
+ * 'isameasure' must be set to 1 if you want to have a total on list for this field. Field type must be summable like integer or double(24,8).
+ * 'css' and 'cssview' and 'csslist' is the CSS style to use on field. 'css' is used in creation and update. 'cssview' is used in view mode. 'csslist' is used for columns in lists. For example: 'css'=>'minwidth300 maxwidth500 widthcentpercentminusx', 'cssview'=>'wordbreak', 'csslist'=>'tdoverflowmax200'
+ * 'help' is a 'TranslationString' to use to show a tooltip on field. You can also use 'TranslationString:keyfortooltiponlick' for a tooltip on click.
+ * 'showoncombobox' if value of the field must be visible into the label of the combobox that list record
+ * 'disabled' is 1 if we want to have the field locked by a 'disabled' attribute. In most cases, this is never set into the definition of $fields into class, but is set dynamically by some part of code.
+ * 'arrayofkeyval' to set a list of values if type is a list of predefined values. For example: array("0"=>"Draft","1"=>"Active","-1"=>"Cancel"). Note that type can be 'integer' or 'varchar'
+ * 'autofocusoncreate' to have field having the focus on a create form. Only 1 field should have this property set to 1.
+ * 'comment' is not used. You can store here any text of your choice. It is not used by application.
+ *
+ * Note: To have value dynamic, you can set value to 0 in definition and edit the value on the fly into the constructor.
+ */
+
+ // BEGIN MODULEBUILDER PROPERTIES
+ /**
+ * @var array Array with all fields and their property. Do not use it as a static var. It may be modified by constructor.
+ */
+ public $fields=array(
+ 'rowid' => array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>'1', 'position'=>1, 'notnull'=>1, 'visible'=>0, 'noteditable'=>'1', 'index'=>1, 'css'=>'left', 'comment'=>"Id"),
+ 'label' => array('type'=>'varchar(255)', 'label'=>'Label', 'enabled'=>'1', 'position'=>30, 'notnull'=>1, 'visible'=>1, 'searchall'=>1, 'css'=>'minwidth300', 'cssview'=>'wordbreak', 'showoncombobox'=>'2',),
+ 'description' => array('type'=>'text', 'label'=>'Description', 'enabled'=>'1', 'position'=>60, 'notnull'=>0, 'visible'=>3,),
+ 'date_creation' => array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>'1', 'position'=>500, 'notnull'=>1, 'visible'=>-2,),
+ 'tms' => array('type'=>'timestamp', 'label'=>'DateModification', 'enabled'=>'1', 'position'=>501, 'notnull'=>0, 'visible'=>-2,),
+ 'fk_user_creat' => array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserAuthor', 'enabled'=>'1', 'position'=>510, 'notnull'=>1, 'visible'=>-2, 'foreignkey'=>'user.rowid',),
+ 'fk_user_modif' => array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserModif', 'enabled'=>'1', 'position'=>511, 'notnull'=>-1, 'visible'=>-2,),
+ 'required_level' => array('type'=>'integer', 'label'=>'requiredLevel', 'enabled'=>'1', 'position'=>50, 'notnull'=>1, 'visible'=>0,),
+ 'date_validite' => array('type'=>'integer', 'label'=>'date_validite', 'enabled'=>'1', 'position'=>52, 'notnull'=>1, 'visible'=>0,),
+ 'temps_theorique' => array('type'=>'double(24,8)', 'label'=>'temps_theorique', 'enabled'=>'1', 'position'=>54, 'notnull'=>1, 'visible'=>0,),
+ 'skill_type' => array('type'=>'integer', 'label'=>'SkillType', 'enabled'=>'1', 'position'=>55, 'notnull'=>1, 'visible'=>1, 'index'=>1, 'arrayofkeyval'=>array('0'=>'knowHow', '1'=>'HowToBe', '9'=>'knowledge'), 'default'=>0),
+ 'note_public' => array('type'=>'html', 'label'=>'NotePublic', 'enabled'=>'1', 'position'=>70, 'notnull'=>0, 'visible'=>0,),
+ 'note_private' => array('type'=>'html', 'label'=>'NotePrivate', 'enabled'=>'1', 'position'=>71, 'notnull'=>0, 'visible'=>0,),
+ );
+ public $rowid;
+ public $label;
+ public $description;
+ public $date_creation;
+ public $tms;
+ public $fk_user_creat;
+ public $fk_user_modif;
+ public $required_level;
+ public $date_validite;
+ public $temps_theorique;
+ public $skill_type;
+ public $note_public;
+ public $note_private;
+ // END MODULEBUILDER PROPERTIES
+
+
+ // If this object has a subtable with lines
+
+ // /**
+ // * @var string Name of subtable line
+ // */
+ // public $table_element_line = 'hrm_skillline';
+
+ // /**
+ // * @var string Field with ID of parent key if this object has a parent
+ // */
+ public $fk_element = 'fk_skill';
+
+ // /**
+ // * @var string Name of subtable class that manage subtable lines
+ // */
+ // public $class_element_line = 'Skillline';
+
+ // /**
+ // * @var array List of child tables. To test if we can delete object.
+ // */
+ protected $childtables = array('hrm_skillrank', 'hrm_evaluationdet');
+
+ // /**
+ // * @var array List of child tables. To know object to delete on cascade.
+ // * If name matches '@ClassNAme:FilePathClass;ParentFkFieldName' it will
+ // * call method deleteByParentField(parentId, ParentFkFieldName) to fetch and delete child object
+ // */
+ protected $childtablesoncascade = array('hrm_skilldet');
+
+ // /**
+ // * @var SkillLine[] Array of subtable lines
+ // */
+ // public $lines = array();
+
+
+
+ /**
+ * Constructor
+ *
+ * @param DoliDb $db Database handler
+ */
+ public function __construct(DoliDB $db)
+ {
+ global $conf, $langs;
+
+ $this->db = $db;
+
+ if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID) && isset($this->fields['rowid'])) {
+ $this->fields['rowid']['visible'] = 0;
+ }
+ if (empty($conf->multicompany->enabled) && isset($this->fields['entity'])) {
+ $this->fields['entity']['enabled'] = 0;
+ }
+
+ // Example to show how to set values of fields definition dynamically
+ /*if ($user->rights->hrm->skill->read) {
+ $this->fields['myfield']['visible'] = 1;
+ $this->fields['myfield']['noteditable'] = 0;
+ }*/
+
+ // Unset fields that are disabled
+ foreach ($this->fields as $key => $val) {
+ if (isset($val['enabled']) && empty($val['enabled'])) {
+ unset($this->fields[$key]);
+ }
+ }
+
+ // Translate some data of arrayofkeyval
+ if (is_object($langs)) {
+ foreach ($this->fields as $key => $val) {
+ if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
+ foreach ($val['arrayofkeyval'] as $key2 => $val2) {
+ $this->fields[$key]['arrayofkeyval'][$key2] = $langs->trans($val2);
+ }
+ }
+ }
+ }
+ }
+
+ /**
+ * Create object into database
+ *
+ * @param User $user User that creates
+ * @param bool $notrigger false=launch triggers after, true=disable triggers
+ * @return int <0 if KO, Id of created object if OK
+ */
+ public function create(User $user, $notrigger = false)
+ {
+ global $langs,$conf;
+
+ $resultcreate = $this->createCommon($user, $notrigger);
+
+
+ if ($resultcreate > 0) {
+ // skillDet create
+ $this->createSkills();
+ }
+
+ return $resultcreate;
+ }
+
+ /**
+ * @param int $i rank from which we want to create skilldets
+ * @return null
+ */
+ public function createSkills($i = 1)
+ {
+
+ global $conf, $user, $langs;
+
+ $MaxNumberSkill = isset($conf->global->HRM_MAXRANK) ? $conf->global->HRM_MAXRANK : self::DEFAULT_MAX_RANK_PER_SKILL;
+ $defaultSkillDesc = !empty($conf->global->HRM_DEFAULT_SKILL_DESCRIPTION) ? $conf->global->HRM_DEFAULT_SKILL_DESCRIPTION : 'no Description';
+ require_once __DIR__ . '/skilldet.class.php';
+ for ($i; $i <= $MaxNumberSkill ; $i++) {
+ $skilldet = new Skilldet($this->db);
+ $skilldet->description = $defaultSkillDesc . " " . $i ;
+ $skilldet->rank = $i;
+ $skilldet->fk_skill = $this->id;
+
+ $result = $skilldet->create($user);
+
+ if ($result > 0) {
+ setEventMessage($langs->trans('TraductionCreadted'), $i);
+ }
+ }
+ }
+
+ /**
+ * Clone an object into another one
+ *
+ * @param User $user User that creates
+ * @param int $fromid Id of object to clone
+ * @return mixed New object created, <0 if KO
+ */
+ public function createFromClone(User $user, $fromid)
+ {
+ global $langs, $extrafields;
+ $error = 0;
+
+ dol_syslog(__METHOD__, LOG_DEBUG);
+
+ $object = new self($this->db);
+
+ $this->db->begin();
+
+ // Load source object
+ $result = $object->fetchCommon($fromid);
+ if ($result > 0 && !empty($object->table_element_line)) {
+ $object->fetchLines();
+ }
+
+ // get lines so they will be clone
+ //foreach($this->lines as $line)
+ // $line->fetch_optionals();
+
+ // Reset some properties
+ unset($object->id);
+ unset($object->fk_user_creat);
+ unset($object->import_key);
+
+ // Clear fields
+ if (property_exists($object, 'ref')) {
+ $object->ref = empty($this->fields['ref']['default']) ? "Copy_Of_".$object->ref : $this->fields['ref']['default'];
+ }
+ if (property_exists($object, 'label')) {
+ $object->label = empty($this->fields['label']['default']) ? $langs->trans("CopyOf")." ".$object->label : $this->fields['label']['default'];
+ }
+ if (property_exists($object, 'status')) {
+ $object->status = self::STATUS_DRAFT;
+ }
+ if (property_exists($object, 'date_creation')) {
+ $object->date_creation = dol_now();
+ }
+ if (property_exists($object, 'date_modification')) {
+ $object->date_modification = null;
+ }
+ // ...
+ // Clear extrafields that are unique
+ if (is_array($object->array_options) && count($object->array_options) > 0) {
+ $extrafields->fetch_name_optionals_label($this->table_element);
+ foreach ($object->array_options as $key => $option) {
+ $shortkey = preg_replace('/options_/', '', $key);
+ if (!empty($extrafields->attributes[$this->table_element]['unique'][$shortkey])) {
+ //var_dump($key); var_dump($clonedObj->array_options[$key]); exit;
+ unset($object->array_options[$key]);
+ }
+ }
+ }
+
+ // Create clone
+ $object->context['createfromclone'] = 'createfromclone';
+ $result = $object->createCommon($user);
+ if ($result < 0) {
+ $error++;
+ $this->error = $object->error;
+ $this->errors = $object->errors;
+ }
+
+ if (!$error) {
+ // copy internal contacts
+ if ($this->copy_linked_contact($object, 'internal') < 0) {
+ $error++;
+ }
+ }
+
+ if (!$error) {
+ // copy external contacts if same company
+ if (property_exists($this, 'fk_soc') && $this->fk_soc == $object->socid) {
+ if ($this->copy_linked_contact($object, 'external') < 0) {
+ $error++;
+ }
+ }
+ }
+
+ unset($object->context['createfromclone']);
+
+ // End
+ if (!$error) {
+ $this->db->commit();
+ return $object;
+ } else {
+ $this->db->rollback();
+ return -1;
+ }
+ }
+
+ /**
+ * Load object in memory from the database
+ *
+ * @param int $id Id object
+ * @param string $ref Ref
+ * @return int <0 if KO, 0 if not found, >0 if OK
+ */
+ public function fetch($id, $ref = null)
+ {
+ $result = $this->fetchCommon($id, $ref);
+ if ($result > 0 && !empty($this->table_element_line)) {
+ $this->fetchLines();
+ }
+ return $result;
+ }
+
+ /**
+ * Load object lines in memory from the database
+ *
+ * @return int | array <0 if KO, 0 if not found, array if OK
+ */
+ public function fetchLines()
+ {
+ $this->lines = array();
+ require_once __DIR__ . '/skilldet.class.php';
+ $skilldet = new Skilldet($this->db);
+ $this->lines = $skilldet->fetchAll('ASC', '', '', '', array('fk_skill' => $this->id), '');
+
+ return (count($this->lines) > 0 ) ? $this->lines : 0;
+ }
+
+
+ /**
+ * Load list of objects in memory from the database.
+ *
+ * @param string $sortorder Sort Order
+ * @param string $sortfield Sort field
+ * @param int $limit limit
+ * @param int $offset Offset
+ * @param array $filter Filter array. Example array('field'=>'valueforlike', 'customurl'=>...)
+ * @param string $filtermode Filter mode (AND or OR)
+ * @return array|int int <0 if KO, array of pages if OK
+ */
+ public function fetchAll($sortorder = '', $sortfield = '', $limit = 0, $offset = 0, array $filter = array(), $filtermode = 'AND')
+ {
+ global $conf;
+
+ dol_syslog(__METHOD__, LOG_DEBUG);
+
+ $records = array();
+
+ $sql = 'SELECT ';
+ $sql .= $this->getFieldList('t');
+ $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t';
+ if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
+ $sql .= ' WHERE t.entity IN ('.getEntity($this->table_element).')';
+ } else {
+ $sql .= ' WHERE 1 = 1';
+ }
+ // Manage filter
+ $sqlwhere = array();
+ if (count($filter) > 0) {
+ foreach ($filter as $key => $value) {
+ if ($key == 't.rowid') {
+ $sqlwhere[] = $key.'='.$value;
+ } elseif (in_array($this->fields[$key]['type'], array('date', 'datetime', 'timestamp'))) {
+ $sqlwhere[] = $key.' = \''.$this->db->idate($value).'\'';
+ } elseif ($key == 'customsql') {
+ $sqlwhere[] = $value;
+ } elseif (strpos($value, '%') === false) {
+ $sqlwhere[] = $key.' IN ('.$this->db->sanitize($this->db->escape($value)).')';
+ } else {
+ $sqlwhere[] = $key.' LIKE \'%'.$this->db->escape($value).'%\'';
+ }
+ }
+ }
+ if (count($sqlwhere) > 0) {
+ $sql .= " AND (".implode(" ".$filtermode." ", $sqlwhere).")";
+ }
+
+ if (!empty($sortfield)) {
+ $sql .= $this->db->order($sortfield, $sortorder);
+ }
+ if (!empty($limit)) {
+ $sql .= ' '.$this->db->plimit($limit, $offset);
+ }
+
+ $resql = $this->db->query($sql);
+ if ($resql) {
+ $num = $this->db->num_rows($resql);
+ $i = 0;
+ while ($i < ($limit ? min($limit, $num) : $num)) {
+ $obj = $this->db->fetch_object($resql);
+
+ $record = new self($this->db);
+ $record->setVarsFromFetchObj($obj);
+
+ $records[$record->id] = $record;
+
+ $i++;
+ }
+ $this->db->free($resql);
+
+ return $records;
+ } else {
+ $this->errors[] = 'Error '.$this->db->lasterror();
+ dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
+
+ return -1;
+ }
+ }
+
+ /**
+ * Update object into database
+ *
+ * @param User $user User that modifies
+ * @param bool $notrigger false=launch triggers after, true=disable triggers
+ * @return int <0 if KO, >0 if OK
+ */
+ public function update(User $user, $notrigger = false)
+ {
+ return $this->updateCommon($user, $notrigger);
+ }
+
+ /**
+ * Delete object in database
+ *
+ * @param User $user User that deletes
+ * @param bool $notrigger false=launch triggers after, true=disable triggers
+ * @return int <0 if KO, >0 if OK
+ */
+ public function delete(User $user, $notrigger = false)
+ {
+ return $this->deleteCommon($user, $notrigger);;
+ }
+
+ /**
+ * Delete a line of object in database
+ *
+ * @param User $user User that delete
+ * @param int $idline Id of line to delete
+ * @param bool $notrigger false=launch triggers after, true=disable triggers
+ * @return int >0 if OK, <0 if KO
+ */
+ public function deleteLine(User $user, $idline, $notrigger = false)
+ {
+ if ($this->status < 0) {
+ $this->error = 'ErrorDeleteLineNotAllowedByObjectStatus';
+ return -2;
+ }
+
+ return $this->deleteLineCommon($user, $idline, $notrigger);
+ }
+
+
+ /**
+ * Validate object
+ *
+ * @param User $user User making status change
+ * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
+ * @return int <=0 if OK, 0=Nothing done, >0 if KO
+ */
+ public function validate($user, $notrigger = 0)
+ {
+ global $conf, $langs;
+
+ require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
+
+ $error = 0;
+
+ // Protection
+ if ($this->status == self::STATUS_VALIDATED) {
+ dol_syslog(get_class($this)."::validate action abandonned: already validated", LOG_WARNING);
+ return 0;
+ }
+
+ /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->hrm->skill->write))
+ || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->hrm->skill->skill_advance->validate))))
+ {
+ $this->error='NotEnoughPermissions';
+ dol_syslog(get_class($this)."::valid ".$this->error, LOG_ERR);
+ return -1;
+ }*/
+
+ $now = dol_now();
+
+ $this->db->begin();
+
+ // Define new ref
+ if (!$error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) { // empty should not happened, but when it occurs, the test save life
+ $num = $this->getNextNumRef();
+ } else {
+ $num = $this->ref;
+ }
+ $this->newref = $num;
+
+ if (!empty($num)) {
+ // Validate
+ $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
+ $sql .= " SET ref = '".$this->db->escape($num)."',";
+ $sql .= " status = ".self::STATUS_VALIDATED;
+ if (!empty($this->fields['date_validation'])) {
+ $sql .= ", date_validation = '".$this->db->idate($now)."'";
+ }
+ if (!empty($this->fields['fk_user_valid'])) {
+ $sql .= ", fk_user_valid = ".((int) $user->id);
+ }
+ $sql .= " WHERE rowid = ".((int) $this->id);
+
+ dol_syslog(get_class($this)."::validate()", LOG_DEBUG);
+ $resql = $this->db->query($sql);
+ if (!$resql) {
+ dol_print_error($this->db);
+ $this->error = $this->db->lasterror();
+ $error++;
+ }
+
+ if (!$error && !$notrigger) {
+ // Call trigger
+ $result = $this->call_trigger('SKILL_VALIDATE', $user);
+ if ($result < 0) {
+ $error++;
+ }
+ // End call triggers
+ }
+ }
+
+ if (!$error) {
+ $this->oldref = $this->ref;
+
+ // Rename directory if dir was a temporary ref
+ if (preg_match('/^[\(]?PROV/i', $this->ref)) {
+ // Now we rename also files into index
+ $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filename = CONCAT('".$this->db->escape($this->newref)."', SUBSTR(filename, ".(strlen($this->ref) + 1).")), filepath = 'skill/".$this->db->escape($this->newref)."'";
+ $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'skill/".$this->db->escape($this->ref)."' and entity = ".$conf->entity;
+ $resql = $this->db->query($sql);
+ if (!$resql) {
+ $error++; $this->error = $this->db->lasterror();
+ }
+
+ // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments
+ $oldref = dol_sanitizeFileName($this->ref);
+ $newref = dol_sanitizeFileName($num);
+ $dirsource = $conf->hrm->dir_output.'/skill/'.$oldref;
+ $dirdest = $conf->hrm->dir_output.'/skill/'.$newref;
+ if (!$error && file_exists($dirsource)) {
+ dol_syslog(get_class($this)."::validate() rename dir ".$dirsource." into ".$dirdest);
+
+ if (@rename($dirsource, $dirdest)) {
+ dol_syslog("Rename ok");
+ // Rename docs starting with $oldref with $newref
+ $listoffiles = dol_dir_list($conf->hrm->dir_output.'/skill/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/'));
+ foreach ($listoffiles as $fileentry) {
+ $dirsource = $fileentry['name'];
+ $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource);
+ $dirsource = $fileentry['path'].'/'.$dirsource;
+ $dirdest = $fileentry['path'].'/'.$dirdest;
+ @rename($dirsource, $dirdest);
+ }
+ }
+ }
+ }
+ }
+
+ // Set new ref and current status
+ if (!$error) {
+ $this->ref = $num;
+ $this->status = self::STATUS_VALIDATED;
+ }
+
+ if (!$error) {
+ $this->db->commit();
+ return 1;
+ } else {
+ $this->db->rollback();
+ return -1;
+ }
+ }
+
+
+ /**
+ * Set draft status
+ *
+ * @param User $user Object user that modify
+ * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers
+ * @return int <0 if KO, >0 if OK
+ */
+ public function setDraft($user, $notrigger = 0)
+ {
+ // Protection
+ if ($this->status <= self::STATUS_DRAFT) {
+ return 0;
+ }
+
+ /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->hrm->write))
+ || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->hrm->hrm_advance->validate))))
+ {
+ $this->error='Permission denied';
+ return -1;
+ }*/
+
+ return $this->setStatusCommon($user, self::STATUS_DRAFT, $notrigger, 'SKILL_UNVALIDATE');
+ }
+
+ /**
+ * Set cancel status
+ *
+ * @param User $user Object user that modify
+ * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers
+ * @return int <0 if KO, 0=Nothing done, >0 if OK
+ */
+ public function cancel($user, $notrigger = 0)
+ {
+ // Protection
+ if ($this->status != self::STATUS_VALIDATED) {
+ return 0;
+ }
+
+ /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->hrm->write))
+ || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->hrm->hrm_advance->validate))))
+ {
+ $this->error='Permission denied';
+ return -1;
+ }*/
+
+ return $this->setStatusCommon($user, self::STATUS_CANCELED, $notrigger, 'SKILL_CANCEL');
+ }
+
+ /**
+ * Set back to validated status
+ *
+ * @param User $user Object user that modify
+ * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers
+ * @return int <0 if KO, 0=Nothing done, >0 if OK
+ */
+ public function reopen($user, $notrigger = 0)
+ {
+ // Protection
+ if ($this->status != self::STATUS_CANCELED) {
+ return 0;
+ }
+
+ /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->hrm->write))
+ || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->hrm->hrm_advance->validate))))
+ {
+ $this->error='Permission denied';
+ return -1;
+ }*/
+
+ return $this->setStatusCommon($user, self::STATUS_VALIDATED, $notrigger, 'SKILL_REOPEN');
+ }
+
+ /**
+ * Return a link to the object card (with optionaly the picto)
+ *
+ * @param int $withpicto Include picto in link (0=No picto, 1=Include picto into link, 2=Only picto)
+ * @param string $option On what the link point to ('nolink', ...)
+ * @param int $notooltip 1=Disable tooltip
+ * @param string $morecss Add more css on link
+ * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
+ * @return string String with URL
+ */
+ /**
+ * Return a link to the object card (with optionaly the picto)
+ *
+ * @param int $withpicto Include picto in link (0=No picto, 1=Include picto into link, 2=Only picto)
+ * @param string $option On what the link point to ('nolink', ...)
+ * @param int $notooltip 1=Disable tooltip
+ * @param string $morecss Add more css on link
+ * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
+ * @return string String with URL
+ */
+ public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $morecss = '', $save_lastsearch_value = -1)
+ {
+ global $conf, $langs, $hookmanager;
+
+ if (!empty($conf->dol_no_mouse_hover)) {
+ $notooltip = 1; // Force disable tooltips
+ }
+
+ $result = '';
+
+ $label = img_picto('', $this->picto).' '.$langs->trans("Skill").'';
+ if (isset($this->status)) {
+ $label .= ' '.$this->getLibStatut(5);
+ }
+ $label .= ' ';
+ $label .= ''.$langs->trans('Label').': '.$this->label;
+
+ $url = dol_buildpath('/hrm/skill_card.php', 1).'?id='.$this->id;
+
+ if ($option != 'nolink') {
+ // Add param to save lastsearch_values or not
+ $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
+ if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
+ $add_save_lastsearch_values = 1;
+ }
+ if ($add_save_lastsearch_values) {
+ $url .= '&save_lastsearch_values=1';
+ }
+ }
+
+ $linkclose = '';
+ if (empty($notooltip)) {
+ if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
+ $label = $langs->trans("ShowSkill");
+ $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
+ }
+ $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"';
+ $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"';
+ } else {
+ $linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
+ }
+
+ if ($option == 'nolink') {
+ $linkstart = '';
+ if ($option == 'nolink') {
+ $linkend = '';
+ } else {
+ $linkend = '';
+ }
+
+ $result .= $linkstart;
+
+ if (empty($this->showphoto_on_popup)) {
+ if ($withpicto) {
+ $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
+ }
+ } else {
+ if ($withpicto) {
+ require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
+
+ list($class, $module) = explode('@', $this->picto);
+ $upload_dir = $conf->$module->multidir_output[$conf->entity]."/$class/".dol_sanitizeFileName($this->ref);
+ $filearray = dol_dir_list($upload_dir, "files");
+ $filename = $filearray[0]['name'];
+ if (!empty($filename)) {
+ $pospoint = strpos($filearray[0]['name'], '.');
+
+ $pathtophoto = $class.'/'.$this->ref.'/thumbs/'.substr($filename, 0, $pospoint).'_mini'.substr($filename, $pospoint);
+ if (empty($conf->global->{strtoupper($module.'_'.$class).'_FORMATLISTPHOTOSASUSERS'})) {
+ $result .= '
';
+ } else {
+ $result .= '
';
+ }
+
+ $result .= '';
+ } else {
+ $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
+ }
+ }
+ }
+
+ if ($withpicto != 2) {
+ $result .= $this->label;
+ }
+
+ $result .= $linkend;
+ //if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : '');
+
+ global $action, $hookmanager;
+ $hookmanager->initHooks(array('jobdao'));
+ $parameters = array('id'=>$this->id, 'getnomurl'=>$result);
+ $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
+ if ($reshook > 0) {
+ $result = $hookmanager->resPrint;
+ } else {
+ $result .= $hookmanager->resPrint;
+ }
+
+ return $result;
+ }
+
+ /**
+ * Return the label of the status
+ *
+ * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto, 6=Long label + Picto
+ * @return string Label of status
+ */
+ public function getLibStatut($mode = 0)
+ {
+ return $this->LibStatut($this->status, $mode);
+ }
+
+ // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
+ /**
+ * Return the status
+ *
+ * @param int $status Id status
+ * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto, 6=Long label + Picto
+ * @return string Label of status
+ */
+ public function LibStatut($status, $mode = 0)
+ {
+ // phpcs:enable
+ if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
+ global $langs;
+ //$langs->load("hrm");
+ $this->labelStatus[self::STATUS_DRAFT] = $langs->trans('Draft');
+ $this->labelStatus[self::STATUS_VALIDATED] = $langs->trans('Enabled');
+ $this->labelStatus[self::STATUS_CANCELED] = $langs->trans('Disabled');
+ $this->labelStatusShort[self::STATUS_DRAFT] = $langs->trans('Draft');
+ $this->labelStatusShort[self::STATUS_VALIDATED] = $langs->trans('Enabled');
+ $this->labelStatusShort[self::STATUS_CANCELED] = $langs->trans('Disabled');
+ }
+
+ $statusType = 'status'.$status;
+ //if ($status == self::STATUS_VALIDATED) $statusType = 'status1';
+ if ($status == self::STATUS_CANCELED) {
+ $statusType = 'status6';
+ }
+
+ return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
+ }
+
+ /**
+ * Load the info information in the object
+ *
+ * @param int $id Id of object
+ * @return void
+ */
+ public function info($id)
+ {
+ $sql = 'SELECT rowid, date_creation as datec, tms as datem,';
+ $sql .= ' fk_user_creat, fk_user_modif';
+ $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t';
+ $sql .= ' WHERE t.rowid = '.((int) $id);
+ $result = $this->db->query($sql);
+ if ($result) {
+ if ($this->db->num_rows($result)) {
+ $obj = $this->db->fetch_object($result);
+ $this->id = $obj->rowid;
+ if ($obj->fk_user_author) {
+ $cuser = new User($this->db);
+ $cuser->fetch($obj->fk_user_author);
+ $this->user_creation = $cuser;
+ }
+
+ if ($obj->fk_user_valid) {
+ $vuser = new User($this->db);
+ $vuser->fetch($obj->fk_user_valid);
+ $this->user_validation = $vuser;
+ }
+
+ if ($obj->fk_user_cloture) {
+ $cluser = new User($this->db);
+ $cluser->fetch($obj->fk_user_cloture);
+ $this->user_cloture = $cluser;
+ }
+
+ $this->date_creation = $this->db->jdate($obj->datec);
+ $this->date_modification = $this->db->jdate($obj->datem);
+ $this->date_validation = $this->db->jdate($obj->datev);
+ }
+
+ $this->db->free($result);
+ } else {
+ dol_print_error($this->db);
+ }
+ }
+
+ /**
+ * Initialise object with example values
+ * Id must be 0 if object instance is a specimen
+ *
+ * @return void
+ */
+ public function initAsSpecimen()
+ {
+ // Set here init that are not commonf fields
+ // $this->property1 = ...
+ // $this->property2 = ...
+
+ $this->initAsSpecimenCommon();
+ }
+
+ /**
+ * Create an array of lines
+ *
+ * @return array|int array of lines if OK, <0 if KO
+ */
+ public function getLinesArray()
+ {
+ $this->lines = array();
+
+ $objectline = new SkillLine($this->db);
+ $result = $objectline->fetchAll('ASC', 'rank', 0, 0, array('customsql'=>'fk_skill = '.$this->id));
+
+ if (is_numeric($result)) {
+ $this->error = $this->error;
+ $this->errors = $this->errors;
+ return $result;
+ } else {
+ $this->lines = $result;
+ return $this->lines;
+ }
+ }
+
+ /**
+ * Returns the reference to the following non used object depending on the active numbering module.
+ *
+ * @return string Object free reference
+ */
+ public function getNextNumRef()
+ {
+ global $langs, $conf;
+ $langs->load("hrm");
+
+ if (empty($conf->global->hrm_SKILL_ADDON)) {
+ $conf->global->hrm_SKILL_ADDON = 'mod_skill_standard';
+ }
+
+ if (!empty($conf->global->hrm_SKILL_ADDON)) {
+ $mybool = false;
+
+ $file = $conf->global->hrm_SKILL_ADDON.".php";
+ $classname = $conf->global->hrm_SKILL_ADDON;
+
+ // Include file with class
+ $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
+ foreach ($dirmodels as $reldir) {
+ $dir = dol_buildpath($reldir."core/modules/hrm/");
+
+ // Load file with numbering class (if found)
+ $mybool |= @include_once $dir.$file;
+ }
+
+ if ($mybool === false) {
+ dol_print_error('', "Failed to include file ".$file);
+ return '';
+ }
+
+ if (class_exists($classname)) {
+ $obj = new $classname();
+ $numref = $obj->getNextValue($this);
+
+ if ($numref != '' && $numref != '-1') {
+ return $numref;
+ } else {
+ $this->error = $obj->error;
+ //dol_print_error($this->db,get_class($this)."::getNextNumRef ".$obj->error);
+ return "";
+ }
+ } else {
+ print $langs->trans("Error")." ".$langs->trans("ClassNotFound").' '.$classname;
+ return "";
+ }
+ } else {
+ print $langs->trans("ErrorNumberingModuleNotSetup", $this->element);
+ return "";
+ }
+ }
+
+ /**
+ * Create a document onto disk according to template module.
+ *
+ * @param string $modele Force template to use ('' to not force)
+ * @param Translate $outputlangs objet lang a utiliser pour traduction
+ * @param int $hidedetails Hide details of lines
+ * @param int $hidedesc Hide description
+ * @param int $hideref Hide ref
+ * @param null|array $moreparams Array to provide more information
+ * @return int 0 if KO, 1 if OK
+ */
+ public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
+ {
+ global $conf, $langs;
+
+ $result = 0;
+ $includedocgeneration = 0;
+
+ $langs->load("hrm");
+
+ if (!dol_strlen($modele)) {
+ $modele = 'standard_skill';
+
+ if (!empty($this->model_pdf)) {
+ $modele = $this->model_pdf;
+ } elseif (!empty($conf->global->SKILL_ADDON_PDF)) {
+ $modele = $conf->global->SKILL_ADDON_PDF;
+ }
+ }
+
+ $modelpath = "core/modules/hrm/doc/";
+
+ if ($includedocgeneration && !empty($modele)) {
+ $result = $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
+ }
+
+ return $result;
+ }
+
+ /**
+ * Action executed by scheduler
+ * CAN BE A CRON TASK. In such a case, parameters come from the schedule job setup field 'Parameters'
+ * Use public function doScheduledJob($param1, $param2, ...) to get parameters
+ *
+ * @return int 0 if OK, <>0 if KO (this function is used also by cron so only 0 is OK)
+ */
+ public function doScheduledJob()
+ {
+ global $conf, $langs;
+
+ //$conf->global->SYSLOG_FILE = 'DOL_DATA_ROOT/dolibarr_mydedicatedlofile.log';
+
+ $error = 0;
+ $this->output = '';
+ $this->error = '';
+
+ dol_syslog(__METHOD__, LOG_DEBUG);
+
+ $now = dol_now();
+
+ $this->db->begin();
+
+ // ...
+
+ $this->db->commit();
+
+ return $error;
+ }
+
+ /**
+ * @param int $code number of code label
+ * @return int|string
+ */
+ public static function typeCodeToLabel($code)
+ {
+ global $langs;
+ $result = '';
+ switch ($code) {
+ case 0 : $result = $langs->trans("knowHow"); break; //"Savoir Faire"
+ case 1 : $result = $langs->trans("HowToBe"); break; // "Savoir être"
+ case 9 : $result = $langs->trans("knowledge"); break; //"Savoir"
+ }
+ return $result;
+ }
+}
diff --git a/htdocs/hrm/class/skilldet.class.php b/htdocs/hrm/class/skilldet.class.php
new file mode 100644
index 00000000000..e4ac293c297
--- /dev/null
+++ b/htdocs/hrm/class/skilldet.class.php
@@ -0,0 +1,1030 @@
+
+ * Copyright (C) 2021 Gauthier VERDOL
+ * Copyright (C) 2021 Greg Rastklan
+ * Copyright (C) 2021 Jean-Pascal BOUDET
+ * Copyright (C) 2021 Grégory BLEMAND
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see .
+ */
+
+/**
+ * \file class/skilldet.class.php
+ * \ingroup hrm
+ * \brief This file is a CRUD class file for Skilldet (Create/Read/Update/Delete)
+ */
+
+// Put here all includes required by your class file
+require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
+//require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php';
+//require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
+
+/**
+ * Class for Skilldet
+ */
+class Skilldet extends CommonObject
+{
+ /**
+ * @var string ID of module.
+ */
+ public $module = 'hrm';
+
+ /**
+ * @var string ID to identify managed object.
+ */
+ public $element = 'skilldet';
+
+ /**
+ * @var string Name of table without prefix where object is stored. This is also the key used for extrafields management.
+ */
+ public $table_element = 'hrm_skilldet';
+
+ /**
+ * @var int Does this object support multicompany module ?
+ * 0=No test on entity, 1=Test with field entity, 'field@table'=Test with link by field@table
+ */
+ public $ismultientitymanaged = 0;
+
+ /**
+ * @var int Does object support extrafields ? 0=No, 1=Yes
+ */
+ public $isextrafieldmanaged = 1;
+
+ /**
+ * @var string String with name of icon for skilldet. Must be the part after the 'object_' into object_skilldet.png
+ */
+ public $picto = 'skilldet@hrm';
+
+
+ const STATUS_DRAFT = 0;
+ const STATUS_VALIDATED = 1;
+ const STATUS_CANCELED = 9;
+
+
+ /**
+ * 'type' field format ('integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter]]', 'sellist:TableName:LabelFieldName[:KeyFieldName[:KeyFieldParent[:Filter]]]', 'varchar(x)', 'double(24,8)', 'real', 'price', 'text', 'text:none', 'html', 'date', 'datetime', 'timestamp', 'duration', 'mail', 'phone', 'url', 'password')
+ * Note: Filter can be a string like "(t.ref:like:'SO-%') or (t.date_creation:<:'20160101') or (t.nature:is:NULL)"
+ * 'label' the translation key.
+ * 'picto' is code of a picto to show before value in forms
+ * 'enabled' is a condition when the field must be managed (Example: 1 or '$conf->global->MY_SETUP_PARAM)
+ * 'position' is the sort order of field.
+ * 'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0).
+ * 'visible' says if field is visible in list (Examples: 0=Not visible, 1=Visible on list and create/update/view forms, 2=Visible on list only, 3=Visible on create/update/view form only (not list), 4=Visible on list and update/view form only (not create). 5=Visible on list and view only (not create/not update). Using a negative value means field is not shown by default on list but can be selected for viewing)
+ * 'noteditable' says if field is not editable (1 or 0)
+ * 'default' is a default value for creation (can still be overwrote by the Setup of Default Values if field is editable in creation form). Note: If default is set to '(PROV)' and field is 'ref', the default value will be set to '(PROVid)' where id is rowid when a new record is created.
+ * 'index' if we want an index in database.
+ * 'foreignkey'=>'tablename.field' if the field is a foreign key (it is recommanded to name the field fk_...).
+ * 'searchall' is 1 if we want to search in this field when making a search from the quick search button.
+ * 'isameasure' must be set to 1 if you want to have a total on list for this field. Field type must be summable like integer or double(24,8).
+ * 'css' and 'cssview' and 'csslist' is the CSS style to use on field. 'css' is used in creation and update. 'cssview' is used in view mode. 'csslist' is used for columns in lists. For example: 'css'=>'minwidth300 maxwidth500 widthcentpercentminusx', 'cssview'=>'wordbreak', 'csslist'=>'tdoverflowmax200'
+ * 'help' is a 'TranslationString' to use to show a tooltip on field. You can also use 'TranslationString:keyfortooltiponlick' for a tooltip on click.
+ * 'showoncombobox' if value of the field must be visible into the label of the combobox that list record
+ * 'disabled' is 1 if we want to have the field locked by a 'disabled' attribute. In most cases, this is never set into the definition of $fields into class, but is set dynamically by some part of code.
+ * 'arrayofkeyval' to set a list of values if type is a list of predefined values. For example: array("0"=>"Draft","1"=>"Active","-1"=>"Cancel"). Note that type can be 'integer' or 'varchar'
+ * 'autofocusoncreate' to have field having the focus on a create form. Only 1 field should have this property set to 1.
+ * 'comment' is not used. You can store here any text of your choice. It is not used by application.
+ *
+ * Note: To have value dynamic, you can set value to 0 in definition and edit the value on the fly into the constructor.
+ */
+
+ // BEGIN MODULEBUILDER PROPERTIES
+ /**
+ * @var array Array with all fields and their property. Do not use it as a static var. It may be modified by constructor.
+ */
+ public $fields=array(
+ 'rowid' => array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>'1', 'position'=>1, 'notnull'=>1, 'visible'=>0, 'noteditable'=>'1', 'index'=>1, 'css'=>'left', 'comment'=>"Id"),
+ 'rank' => array('type'=>'integer', 'label'=>'rank', 'enabled'=>'1', 'position'=>2, 'notnull'=>0, 'visible'=>2,),
+ 'description' => array('type'=>'text', 'label'=>'Description', 'enabled'=>'1', 'position'=>60, 'notnull'=>0, 'visible'=>1,),
+ 'fk_user_creat' => array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserAuthor', 'enabled'=>'1', 'position'=>510, 'notnull'=>1, 'visible'=>-2, 'foreignkey'=>'user.rowid',),
+ 'fk_user_modif' => array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserModif', 'enabled'=>'1', 'position'=>511, 'notnull'=>-1, 'visible'=>0,),
+ 'fk_skill' => array('type'=>'integer:Skill:/hrm/class/skill.class.php', 'label'=>'fk_skill', 'enabled'=>'1', 'position'=>513, 'notnull'=>1, 'visible'=>0,),
+ );
+ public $rowid;
+ public $description;
+ public $fk_user_creat;
+ public $fk_user_modif;
+ public $fk_skill;
+ public $rank;
+ // END MODULEBUILDER PROPERTIES
+
+
+ // If this object has a subtable with lines
+
+ // /**
+ // * @var string Name of subtable line
+ // */
+ // public $table_element_line = 'hrm_skilldetline';
+
+ // /**
+ // * @var string Field with ID of parent key if this object has a parent
+ // */
+ // public $fk_element = 'fk_skilldet';
+
+ // /**
+ // * @var string Name of subtable class that manage subtable lines
+ // */
+ // public $class_element_line = 'Skilldetline';
+
+ // /**
+ // * @var array List of child tables. To test if we can delete object.
+ // */
+ // protected $childtables = array();
+
+ // /**
+ // * @var array List of child tables. To know object to delete on cascade.
+ // * If name matches '@ClassNAme:FilePathClass;ParentFkFieldName' it will
+ // * call method deleteByParentField(parentId, ParentFkFieldName) to fetch and delete child object
+ // */
+ // protected $childtablesoncascade = array('hrm_skilldetdet');
+
+ // /**
+ // * @var SkilldetLine[] Array of subtable lines
+ // */
+ // public $lines = array();
+
+
+
+ /**
+ * Constructor
+ *
+ * @param DoliDb $db Database handler
+ */
+ public function __construct(DoliDB $db)
+ {
+ global $conf, $langs;
+
+ $this->db = $db;
+
+ if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID) && isset($this->fields['rowid'])) {
+ $this->fields['rowid']['visible'] = 0;
+ }
+ if (empty($conf->multicompany->enabled) && isset($this->fields['entity'])) {
+ $this->fields['entity']['enabled'] = 0;
+ }
+
+ // Example to show how to set values of fields definition dynamically
+ /*if ($user->rights->hrm->skilldet->read) {
+ $this->fields['myfield']['visible'] = 1;
+ $this->fields['myfield']['noteditable'] = 0;
+ }*/
+
+ // Unset fields that are disabled
+ foreach ($this->fields as $key => $val) {
+ if (isset($val['enabled']) && empty($val['enabled'])) {
+ unset($this->fields[$key]);
+ }
+ }
+
+ // Translate some data of arrayofkeyval
+ if (is_object($langs)) {
+ foreach ($this->fields as $key => $val) {
+ if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
+ foreach ($val['arrayofkeyval'] as $key2 => $val2) {
+ $this->fields[$key]['arrayofkeyval'][$key2] = $langs->trans($val2);
+ }
+ }
+ }
+ }
+ }
+
+ /**
+ * Create object into database
+ *
+ * @param User $user User that creates
+ * @param bool $notrigger false=launch triggers after, true=disable triggers
+ * @return int <0 if KO, Id of created object if OK
+ */
+ public function create(User $user, $notrigger = false)
+ {
+ $resultcreate = $this->createCommon($user, $notrigger);
+
+ //$resultvalidate = $this->validate($user, $notrigger);
+
+ return $resultcreate;
+ }
+
+ /**
+ * Clone an object into another one
+ *
+ * @param User $user User that creates
+ * @param int $fromid Id of object to clone
+ * @return mixed New object created, <0 if KO
+ */
+ public function createFromClone(User $user, $fromid)
+ {
+ global $langs, $extrafields;
+ $error = 0;
+
+ dol_syslog(__METHOD__, LOG_DEBUG);
+
+ $object = new self($this->db);
+
+ $this->db->begin();
+
+ // Load source object
+ $result = $object->fetchCommon($fromid);
+ if ($result > 0 && !empty($object->table_element_line)) {
+ $object->fetchLines();
+ }
+
+ // get lines so they will be clone
+ //foreach($this->lines as $line)
+ // $line->fetch_optionals();
+
+ // Reset some properties
+ unset($object->id);
+ unset($object->fk_user_creat);
+ unset($object->import_key);
+
+ // Clear fields
+ if (property_exists($object, 'ref')) {
+ $object->ref = empty($this->fields['ref']['default']) ? "Copy_Of_".$object->ref : $this->fields['ref']['default'];
+ }
+ if (property_exists($object, 'label')) {
+ $object->label = empty($this->fields['label']['default']) ? $langs->trans("CopyOf")." ".$object->label : $this->fields['label']['default'];
+ }
+ if (property_exists($object, 'status')) {
+ $object->status = self::STATUS_DRAFT;
+ }
+ if (property_exists($object, 'date_creation')) {
+ $object->date_creation = dol_now();
+ }
+ if (property_exists($object, 'date_modification')) {
+ $object->date_modification = null;
+ }
+ // ...
+ // Clear extrafields that are unique
+ if (is_array($object->array_options) && count($object->array_options) > 0) {
+ $extrafields->fetch_name_optionals_label($this->table_element);
+ foreach ($object->array_options as $key => $option) {
+ $shortkey = preg_replace('/options_/', '', $key);
+ if (!empty($extrafields->attributes[$this->table_element]['unique'][$shortkey])) {
+ //var_dump($key); var_dump($clonedObj->array_options[$key]); exit;
+ unset($object->array_options[$key]);
+ }
+ }
+ }
+
+ // Create clone
+ $object->context['createfromclone'] = 'createfromclone';
+ $result = $object->createCommon($user);
+ if ($result < 0) {
+ $error++;
+ $this->error = $object->error;
+ $this->errors = $object->errors;
+ }
+
+ if (!$error) {
+ // copy internal contacts
+ if ($this->copy_linked_contact($object, 'internal') < 0) {
+ $error++;
+ }
+ }
+
+ if (!$error) {
+ // copy external contacts if same company
+ if (property_exists($this, 'fk_soc') && $this->fk_soc == $object->socid) {
+ if ($this->copy_linked_contact($object, 'external') < 0) {
+ $error++;
+ }
+ }
+ }
+
+ unset($object->context['createfromclone']);
+
+ // End
+ if (!$error) {
+ $this->db->commit();
+ return $object;
+ } else {
+ $this->db->rollback();
+ return -1;
+ }
+ }
+
+ /**
+ * Load object in memory from the database
+ *
+ * @param int $id Id object
+ * @param string $ref Ref
+ * @return int <0 if KO, 0 if not found, >0 if OK
+ */
+ public function fetch($id, $ref = null)
+ {
+ $result = $this->fetchCommon($id, $ref);
+ if ($result > 0 && !empty($this->table_element_line)) {
+ $this->fetchLines();
+ }
+ return $result;
+ }
+
+ /**
+ * Load object lines in memory from the database
+ *
+ * @return int <0 if KO, 0 if not found, >0 if OK
+ */
+ public function fetchLines()
+ {
+ $this->lines = array();
+
+ $result = $this->fetchLinesCommon();
+ return $result;
+ }
+
+
+ /**
+ * Load list of objects in memory from the database.
+ *
+ * @param string $sortorder Sort Order
+ * @param string $sortfield Sort field
+ * @param int $limit limit
+ * @param int $offset Offset
+ * @param array $filter Filter array. Example array('field'=>'valueforlike', 'customurl'=>...)
+ * @param string $filtermode Filter mode (AND or OR)
+ * @return array|int int <0 if KO, array of pages if OK
+ */
+ public function fetchAll($sortorder = '', $sortfield = '', $limit = 0, $offset = 0, array $filter = array(), $filtermode = 'AND')
+ {
+ global $conf;
+
+ dol_syslog(__METHOD__, LOG_DEBUG);
+
+ $records = array();
+
+ $sql = 'SELECT ';
+ $sql .= $this->getFieldList('t');
+ $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t';
+ if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
+ $sql .= ' WHERE t.entity IN ('.getEntity($this->table_element).')';
+ } else {
+ $sql .= ' WHERE 1 = 1';
+ }
+ // Manage filter
+ $sqlwhere = array();
+ if (count($filter) > 0) {
+ foreach ($filter as $key => $value) {
+ if ($key == 't.rowid') {
+ $sqlwhere[] = $key.'='.$value;
+ } elseif (in_array($this->fields[$key]['type'], array('date', 'datetime', 'timestamp'))) {
+ $sqlwhere[] = $key.' = \''.$this->db->idate($value).'\'';
+ } elseif ($key == 'customsql') {
+ $sqlwhere[] = $value;
+ } elseif (strpos($value, '%') === false) {
+ $sqlwhere[] = $key.' IN ('.$this->db->sanitize($this->db->escape($value)).')';
+ } else {
+ $sqlwhere[] = $key.' LIKE \'%'.$this->db->escape($value).'%\'';
+ }
+ }
+ }
+ if (count($sqlwhere) > 0) {
+ $sql .= " AND (".implode(" ".$filtermode." ", $sqlwhere).")";
+ }
+
+ if (!empty($sortfield)) {
+ $sql .= $this->db->order($sortfield, $sortorder);
+ }
+ if (!empty($limit)) {
+ $sql .= ' '.$this->db->plimit($limit, $offset);
+ }
+
+ $resql = $this->db->query($sql);
+ if ($resql) {
+ $num = $this->db->num_rows($resql);
+ $i = 0;
+ while ($i < ($limit ? min($limit, $num) : $num)) {
+ $obj = $this->db->fetch_object($resql);
+
+ $record = new self($this->db);
+ $record->setVarsFromFetchObj($obj);
+
+ $records[$record->id] = $record;
+
+ $i++;
+ }
+ $this->db->free($resql);
+
+ return $records;
+ } else {
+ $this->errors[] = 'Error '.$this->db->lasterror();
+ dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
+
+ return -1;
+ }
+ }
+
+ /**
+ * Update object into database
+ *
+ * @param User $user User that modifies
+ * @param bool $notrigger false=launch triggers after, true=disable triggers
+ * @return int <0 if KO, >0 if OK
+ */
+ public function update(User $user, $notrigger = false)
+ {
+ return $this->updateCommon($user, $notrigger);
+ }
+
+ /**
+ * Delete object in database
+ *
+ * @param User $user User that deletes
+ * @param bool $notrigger false=launch triggers after, true=disable triggers
+ * @return int <0 if KO, >0 if OK
+ */
+ public function delete(User $user, $notrigger = false)
+ {
+ return $this->deleteCommon($user, $notrigger);
+ //return $this->deleteCommon($user, $notrigger, 1);
+ }
+
+ /**
+ * Delete a line of object in database
+ *
+ * @param User $user User that delete
+ * @param int $idline Id of line to delete
+ * @param bool $notrigger false=launch triggers after, true=disable triggers
+ * @return int >0 if OK, <0 if KO
+ */
+ public function deleteLine(User $user, $idline, $notrigger = false)
+ {
+ if ($this->status < 0) {
+ $this->error = 'ErrorDeleteLineNotAllowedByObjectStatus';
+ return -2;
+ }
+
+ return $this->deleteLineCommon($user, $idline, $notrigger);
+ }
+
+
+ /**
+ * Validate object
+ *
+ * @param User $user User making status change
+ * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
+ * @return int <=0 if OK, 0=Nothing done, >0 if KO
+ */
+ public function validate($user, $notrigger = 0)
+ {
+ global $conf, $langs;
+
+ require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
+
+ $error = 0;
+
+ // Protection
+ if ($this->status == self::STATUS_VALIDATED) {
+ dol_syslog(get_class($this)."::validate action abandonned: already validated", LOG_WARNING);
+ return 0;
+ }
+
+ /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->hrm->skilldet->write))
+ || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->hrm->skilldet->skilldet_advance->validate))))
+ {
+ $this->error='NotEnoughPermissions';
+ dol_syslog(get_class($this)."::valid ".$this->error, LOG_ERR);
+ return -1;
+ }*/
+
+ $now = dol_now();
+
+ $this->db->begin();
+
+ // Define new ref
+ if (!$error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) { // empty should not happened, but when it occurs, the test save life
+ $num = $this->getNextNumRef();
+ } else {
+ $num = $this->ref;
+ }
+ $this->newref = $num;
+
+ if (!empty($num)) {
+ // Validate
+ $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
+ $sql .= " SET ref = '".$this->db->escape($num)."',";
+ $sql .= " status = ".self::STATUS_VALIDATED;
+ if (!empty($this->fields['date_validation'])) {
+ $sql .= ", date_validation = '".$this->db->idate($now)."'";
+ }
+ if (!empty($this->fields['fk_user_valid'])) {
+ $sql .= ", fk_user_valid = ".((int) $user->id);
+ }
+ $sql .= " WHERE rowid = ".((int) $this->id);
+
+ dol_syslog(get_class($this)."::validate()", LOG_DEBUG);
+ $resql = $this->db->query($sql);
+ if (!$resql) {
+ dol_print_error($this->db);
+ $this->error = $this->db->lasterror();
+ $error++;
+ }
+
+ if (!$error && !$notrigger) {
+ // Call trigger
+ $result = $this->call_trigger('SKILLDET_VALIDATE', $user);
+ if ($result < 0) {
+ $error++;
+ }
+ // End call triggers
+ }
+ }
+
+ if (!$error) {
+ $this->oldref = $this->ref;
+
+ // Rename directory if dir was a temporary ref
+ if (preg_match('/^[\(]?PROV/i', $this->ref)) {
+ // Now we rename also files into index
+ $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filename = CONCAT('".$this->db->escape($this->newref)."', SUBSTR(filename, ".(strlen($this->ref) + 1).")), filepath = 'skilldet/".$this->db->escape($this->newref)."'";
+ $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'skilldet/".$this->db->escape($this->ref)."' and entity = ".$conf->entity;
+ $resql = $this->db->query($sql);
+ if (!$resql) {
+ $error++; $this->error = $this->db->lasterror();
+ }
+
+ // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments
+ $oldref = dol_sanitizeFileName($this->ref);
+ $newref = dol_sanitizeFileName($num);
+ $dirsource = $conf->hrm->dir_output.'/skilldet/'.$oldref;
+ $dirdest = $conf->hrm->dir_output.'/skilldet/'.$newref;
+ if (!$error && file_exists($dirsource)) {
+ dol_syslog(get_class($this)."::validate() rename dir ".$dirsource." into ".$dirdest);
+
+ if (@rename($dirsource, $dirdest)) {
+ dol_syslog("Rename ok");
+ // Rename docs starting with $oldref with $newref
+ $listoffiles = dol_dir_list($conf->hrm->dir_output.'/skilldet/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/'));
+ foreach ($listoffiles as $fileentry) {
+ $dirsource = $fileentry['name'];
+ $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource);
+ $dirsource = $fileentry['path'].'/'.$dirsource;
+ $dirdest = $fileentry['path'].'/'.$dirdest;
+ @rename($dirsource, $dirdest);
+ }
+ }
+ }
+ }
+ }
+
+ // Set new ref and current status
+ if (!$error) {
+ $this->ref = $num;
+ $this->status = self::STATUS_VALIDATED;
+ }
+
+ if (!$error) {
+ $this->db->commit();
+ return 1;
+ } else {
+ $this->db->rollback();
+ return -1;
+ }
+ }
+
+
+ /**
+ * Set draft status
+ *
+ * @param User $user Object user that modify
+ * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers
+ * @return int <0 if KO, >0 if OK
+ */
+ public function setDraft($user, $notrigger = 0)
+ {
+ // Protection
+ if ($this->status <= self::STATUS_DRAFT) {
+ return 0;
+ }
+
+ /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->hrm->write))
+ || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->hrm->hrm_advance->validate))))
+ {
+ $this->error='Permission denied';
+ return -1;
+ }*/
+
+ return $this->setStatusCommon($user, self::STATUS_DRAFT, $notrigger, 'SKILLDET_UNVALIDATE');
+ }
+
+ /**
+ * Set cancel status
+ *
+ * @param User $user Object user that modify
+ * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers
+ * @return int <0 if KO, 0=Nothing done, >0 if OK
+ */
+ public function cancel($user, $notrigger = 0)
+ {
+ // Protection
+ if ($this->status != self::STATUS_VALIDATED) {
+ return 0;
+ }
+
+ /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->hrm->write))
+ || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->hrm->hrm_advance->validate))))
+ {
+ $this->error='Permission denied';
+ return -1;
+ }*/
+
+ return $this->setStatusCommon($user, self::STATUS_CANCELED, $notrigger, 'SKILLDET_CANCEL');
+ }
+
+ /**
+ * Set back to validated status
+ *
+ * @param User $user Object user that modify
+ * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers
+ * @return int <0 if KO, 0=Nothing done, >0 if OK
+ */
+ public function reopen($user, $notrigger = 0)
+ {
+ // Protection
+ if ($this->status != self::STATUS_CANCELED) {
+ return 0;
+ }
+
+ /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->hrm->write))
+ || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->hrm->hrm_advance->validate))))
+ {
+ $this->error='Permission denied';
+ return -1;
+ }*/
+
+ return $this->setStatusCommon($user, self::STATUS_VALIDATED, $notrigger, 'SKILLDET_REOPEN');
+ }
+
+ /**
+ * Return a link to the object card (with optionaly the picto)
+ *
+ * @param int $withpicto Include picto in link (0=No picto, 1=Include picto into link, 2=Only picto)
+ * @param string $option On what the link point to ('nolink', ...)
+ * @param int $notooltip 1=Disable tooltip
+ * @param string $morecss Add more css on link
+ * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
+ * @return string String with URL
+ */
+ public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $morecss = '', $save_lastsearch_value = -1)
+ {
+ global $conf, $langs, $hookmanager;
+
+ if (!empty($conf->dol_no_mouse_hover)) {
+ $notooltip = 1; // Force disable tooltips
+ }
+
+ $result = '';
+
+ $label = img_picto('', $this->picto).' '.$langs->trans("Skilldet").'';
+ if (isset($this->status)) {
+ $label .= ' '.$this->getLibStatut(5);
+ }
+ $label .= ' ';
+ $label .= ''.$langs->trans('Ref').': '.$this->ref;
+
+ $url = dol_buildpath('/hrm/skilldet_card.php', 1).'?id='.$this->id;
+
+ if ($option != 'nolink') {
+ // Add param to save lastsearch_values or not
+ $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
+ if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
+ $add_save_lastsearch_values = 1;
+ }
+ if ($add_save_lastsearch_values) {
+ $url .= '&save_lastsearch_values=1';
+ }
+ }
+
+ $linkclose = '';
+ if (empty($notooltip)) {
+ if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
+ $label = $langs->trans("ShowSkilldet");
+ $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
+ }
+ $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"';
+ $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"';
+ } else {
+ $linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
+ }
+
+ if ($option == 'nolink') {
+ $linkstart = '';
+ if ($option == 'nolink') {
+ $linkend = '';
+ } else {
+ $linkend = '';
+ }
+
+ $result .= $linkstart;
+
+ if (empty($this->showphoto_on_popup)) {
+ if ($withpicto) {
+ $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
+ }
+ } else {
+ if ($withpicto) {
+ require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
+
+ list($class, $module) = explode('@', $this->picto);
+ $upload_dir = $conf->$module->multidir_output[$conf->entity]."/$class/".dol_sanitizeFileName($this->ref);
+ $filearray = dol_dir_list($upload_dir, "files");
+ $filename = $filearray[0]['name'];
+ if (!empty($filename)) {
+ $pospoint = strpos($filearray[0]['name'], '.');
+
+ $pathtophoto = $class.'/'.$this->ref.'/thumbs/'.substr($filename, 0, $pospoint).'_mini'.substr($filename, $pospoint);
+ if (empty($conf->global->{strtoupper($module.'_'.$class).'_FORMATLISTPHOTOSASUSERS'})) {
+ $result .= '
';
+ } else {
+ $result .= '
';
+ }
+
+ $result .= '';
+ } else {
+ $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
+ }
+ }
+ }
+
+ if ($withpicto != 2) {
+ $result .= $this->ref;
+ }
+
+ $result .= $linkend;
+ //if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : '');
+
+ global $action, $hookmanager;
+ $hookmanager->initHooks(array('skilldetdao'));
+ $parameters = array('id'=>$this->id, 'getnomurl'=>$result);
+ $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
+ if ($reshook > 0) {
+ $result = $hookmanager->resPrint;
+ } else {
+ $result .= $hookmanager->resPrint;
+ }
+
+ return $result;
+ }
+
+ /**
+ * Return the label of the status
+ *
+ * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto, 6=Long label + Picto
+ * @return string Label of status
+ */
+ public function getLibStatut($mode = 0)
+ {
+ return $this->LibStatut($this->status, $mode);
+ }
+
+ // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
+ /**
+ * Return the status
+ *
+ * @param int $status Id status
+ * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto, 6=Long label + Picto
+ * @return string Label of status
+ */
+ public function LibStatut($status, $mode = 0)
+ {
+ // phpcs:enable
+ if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
+ global $langs;
+ //$langs->load("hrm");
+ $this->labelStatus[self::STATUS_DRAFT] = $langs->trans('Draft');
+ $this->labelStatus[self::STATUS_VALIDATED] = $langs->trans('Enabled');
+ $this->labelStatus[self::STATUS_CANCELED] = $langs->trans('Disabled');
+ $this->labelStatusShort[self::STATUS_DRAFT] = $langs->trans('Draft');
+ $this->labelStatusShort[self::STATUS_VALIDATED] = $langs->trans('Enabled');
+ $this->labelStatusShort[self::STATUS_CANCELED] = $langs->trans('Disabled');
+ }
+
+ $statusType = 'status'.$status;
+ //if ($status == self::STATUS_VALIDATED) $statusType = 'status1';
+ if ($status == self::STATUS_CANCELED) {
+ $statusType = 'status6';
+ }
+
+ return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
+ }
+
+ /**
+ * Load the info information in the object
+ *
+ * @param int $id Id of object
+ * @return void
+ */
+ public function info($id)
+ {
+ $sql = 'SELECT rowid, date_creation as datec, tms as datem,';
+ $sql .= ' fk_user_creat, fk_user_modif';
+ $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t';
+ $sql .= ' WHERE t.rowid = '.((int) $id);
+ $result = $this->db->query($sql);
+ if ($result) {
+ if ($this->db->num_rows($result)) {
+ $obj = $this->db->fetch_object($result);
+ $this->id = $obj->rowid;
+ if ($obj->fk_user_author) {
+ $cuser = new User($this->db);
+ $cuser->fetch($obj->fk_user_author);
+ $this->user_creation = $cuser;
+ }
+
+ if ($obj->fk_user_valid) {
+ $vuser = new User($this->db);
+ $vuser->fetch($obj->fk_user_valid);
+ $this->user_validation = $vuser;
+ }
+
+ if ($obj->fk_user_cloture) {
+ $cluser = new User($this->db);
+ $cluser->fetch($obj->fk_user_cloture);
+ $this->user_cloture = $cluser;
+ }
+
+ $this->date_creation = $this->db->jdate($obj->datec);
+ $this->date_modification = $this->db->jdate($obj->datem);
+ $this->date_validation = $this->db->jdate($obj->datev);
+ }
+
+ $this->db->free($result);
+ } else {
+ dol_print_error($this->db);
+ }
+ }
+
+ /**
+ * Initialise object with example values
+ * Id must be 0 if object instance is a specimen
+ *
+ * @return void
+ */
+ public function initAsSpecimen()
+ {
+ // Set here init that are not commonf fields
+ // $this->property1 = ...
+ // $this->property2 = ...
+
+ $this->initAsSpecimenCommon();
+ }
+
+ /**
+ * Create an array of lines
+ *
+ * @return array|int array of lines if OK, <0 if KO
+ */
+ public function getLinesArray()
+ {
+ $this->lines = array();
+
+ $objectline = new SkilldetLine($this->db);
+ $result = $objectline->fetchAll('ASC', 'position', 0, 0, array('customsql'=>'fk_skilldet = '.$this->id));
+
+ if (is_numeric($result)) {
+ $this->error = $this->error;
+ $this->errors = $this->errors;
+ return $result;
+ } else {
+ $this->lines = $result;
+ return $this->lines;
+ }
+ }
+
+ /**
+ * Returns the reference to the following non used object depending on the active numbering module.
+ *
+ * @return string Object free reference
+ */
+ public function getNextNumRef()
+ {
+ global $langs, $conf;
+ $langs->load("hrm");
+
+ if (empty($conf->global->hrm_SKILLDET_ADDON)) {
+ $conf->global->hrm_SKILLDET_ADDON = 'mod_skilldet_standard';
+ }
+
+ if (!empty($conf->global->hrm_SKILLDET_ADDON)) {
+ $mybool = false;
+
+ $file = $conf->global->hrm_SKILLDET_ADDON.".php";
+ $classname = $conf->global->hrm_SKILLDET_ADDON;
+
+ // Include file with class
+ $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
+ foreach ($dirmodels as $reldir) {
+ $dir = dol_buildpath($reldir."core/modules/hrm/");
+
+ // Load file with numbering class (if found)
+ $mybool |= @include_once $dir.$file;
+ }
+
+ if ($mybool === false) {
+ dol_print_error('', "Failed to include file ".$file);
+ return '';
+ }
+
+ if (class_exists($classname)) {
+ $obj = new $classname();
+ $numref = $obj->getNextValue($this);
+
+ if ($numref != '' && $numref != '-1') {
+ return $numref;
+ } else {
+ $this->error = $obj->error;
+ //dol_print_error($this->db,get_class($this)."::getNextNumRef ".$obj->error);
+ return "";
+ }
+ } else {
+ print $langs->trans("Error")." ".$langs->trans("ClassNotFound").' '.$classname;
+ return "";
+ }
+ } else {
+ print $langs->trans("ErrorNumberingModuleNotSetup", $this->element);
+ return "";
+ }
+ }
+
+ /**
+ * Create a document onto disk according to template module.
+ *
+ * @param string $modele Force template to use ('' to not force)
+ * @param Translate $outputlangs objet lang a utiliser pour traduction
+ * @param int $hidedetails Hide details of lines
+ * @param int $hidedesc Hide description
+ * @param int $hideref Hide ref
+ * @param null|array $moreparams Array to provide more information
+ * @return int 0 if KO, 1 if OK
+ */
+ public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
+ {
+ global $conf, $langs;
+
+ $result = 0;
+ $includedocgeneration = 0;
+
+ $langs->load("hrm");
+
+ if (!dol_strlen($modele)) {
+ $modele = 'standard_skilldet';
+
+ if (!empty($this->model_pdf)) {
+ $modele = $this->model_pdf;
+ } elseif (!empty($conf->global->SKILLDET_ADDON_PDF)) {
+ $modele = $conf->global->SKILLDET_ADDON_PDF;
+ }
+ }
+
+ $modelpath = "core/modules/hrm/doc/";
+
+ if ($includedocgeneration && !empty($modele)) {
+ $result = $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
+ }
+
+ return $result;
+ }
+
+ /**
+ * Action executed by scheduler
+ * CAN BE A CRON TASK. In such a case, parameters come from the schedule job setup field 'Parameters'
+ * Use public function doScheduledJob($param1, $param2, ...) to get parameters
+ *
+ * @return int 0 if OK, <>0 if KO (this function is used also by cron so only 0 is OK)
+ */
+ public function doScheduledJob()
+ {
+ global $conf, $langs;
+
+ //$conf->global->SYSLOG_FILE = 'DOL_DATA_ROOT/dolibarr_mydedicatedlofile.log';
+
+ $error = 0;
+ $this->output = '';
+ $this->error = '';
+
+ dol_syslog(__METHOD__, LOG_DEBUG);
+
+ $now = dol_now();
+
+ $this->db->begin();
+
+ // ...
+
+ $this->db->commit();
+
+ return $error;
+ }
+}
diff --git a/htdocs/hrm/class/skillrank.class.php b/htdocs/hrm/class/skillrank.class.php
new file mode 100644
index 00000000000..97fcd7edab4
--- /dev/null
+++ b/htdocs/hrm/class/skillrank.class.php
@@ -0,0 +1,1086 @@
+
+ * Copyright (C) 2021 Gauthier VERDOL
+ * Copyright (C) 2021 Greg Rastklan
+ * Copyright (C) 2021 Jean-Pascal BOUDET
+ * Copyright (C) 2021 Grégory BLEMAND
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see .
+ */
+
+/**
+ * \file class/skillrank.class.php
+ * \ingroup hrm
+ * \brief This file is a CRUD class file for SkillRank (Create/Read/Update/Delete)
+ */
+
+// Put here all includes required by your class file
+require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
+require_once DOL_DOCUMENT_ROOT . '/hrm/lib/hrm_skillrank.lib.php';
+
+/**
+ * Class for SkillRank
+ */
+class SkillRank extends CommonObject
+{
+ /**
+ * @var string ID of module.
+ */
+ public $module = 'hrm';
+
+ /**
+ * @var string ID to identify managed object.
+ */
+ public $element = 'skillrank';
+
+ /**
+ * @var string Name of table without prefix where object is stored. This is also the key used for extrafields management.
+ */
+ public $table_element = 'hrm_skillrank';
+
+ /**
+ * @var int Does this object support multicompany module ?
+ * 0=No test on entity, 1=Test with field entity, 'field@table'=Test with link by field@table
+ */
+ public $ismultientitymanaged = 0;
+
+ /**
+ * @var int Does object support extrafields ? 0=No, 1=Yes
+ */
+ public $isextrafieldmanaged = 0;
+
+ /**
+ * @var string String with name of icon for skillrank. Must be the part after the 'object_' into object_skillrank.png
+ */
+ public $picto = 'skillrank@hrm';
+
+
+ const STATUS_DRAFT = 0;
+ const STATUS_VALIDATED = 1;
+ const STATUS_CANCELED = 9;
+
+ const SKILLRANK_TYPE_JOB = "job";
+ const SKILLRANK_TYPE_USER = "user";
+ const SKILLRANK_TYPE_EVALDET = "evaluationdet";
+
+ /**
+ * 'type' field format ('integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter]]', 'sellist:TableName:LabelFieldName[:KeyFieldName[:KeyFieldParent[:Filter]]]', 'varchar(x)', 'double(24,8)', 'real', 'price', 'text', 'text:none', 'html', 'date', 'datetime', 'timestamp', 'duration', 'mail', 'phone', 'url', 'password')
+ * Note: Filter can be a string like "(t.ref:like:'SO-%') or (t.date_creation:<:'20160101') or (t.nature:is:NULL)"
+ * 'label' the translation key.
+ * 'picto' is code of a picto to show before value in forms
+ * 'enabled' is a condition when the field must be managed (Example: 1 or '$conf->global->MY_SETUP_PARAM)
+ * 'position' is the sort order of field.
+ * 'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0).
+ * 'visible' says if field is visible in list (Examples: 0=Not visible, 1=Visible on list and create/update/view forms, 2=Visible on list only, 3=Visible on create/update/view form only (not list), 4=Visible on list and update/view form only (not create). 5=Visible on list and view only (not create/not update). Using a negative value means field is not shown by default on list but can be selected for viewing)
+ * 'noteditable' says if field is not editable (1 or 0)
+ * 'default' is a default value for creation (can still be overwrote by the Setup of Default Values if field is editable in creation form). Note: If default is set to '(PROV)' and field is 'ref', the default value will be set to '(PROVid)' where id is rowid when a new record is created.
+ * 'index' if we want an index in database.
+ * 'foreignkey'=>'tablename.field' if the field is a foreign key (it is recommanded to name the field fk_...).
+ * 'searchall' is 1 if we want to search in this field when making a search from the quick search button.
+ * 'isameasure' must be set to 1 if you want to have a total on list for this field. Field type must be summable like integer or double(24,8).
+ * 'css' and 'cssview' and 'csslist' is the CSS style to use on field. 'css' is used in creation and update. 'cssview' is used in view mode. 'csslist' is used for columns in lists. For example: 'css'=>'minwidth300 maxwidth500 widthcentpercentminusx', 'cssview'=>'wordbreak', 'csslist'=>'tdoverflowmax200'
+ * 'help' is a 'TranslationString' to use to show a tooltip on field. You can also use 'TranslationString:keyfortooltiponlick' for a tooltip on click.
+ * 'showoncombobox' if value of the field must be visible into the label of the combobox that list record
+ * 'disabled' is 1 if we want to have the field locked by a 'disabled' attribute. In most cases, this is never set into the definition of $fields into class, but is set dynamically by some part of code.
+ * 'arrayofkeyval' to set a list of values if type is a list of predefined values. For example: array("0"=>"Draft","1"=>"Active","-1"=>"Cancel"). Note that type can be 'integer' or 'varchar'
+ * 'autofocusoncreate' to have field having the focus on a create form. Only 1 field should have this property set to 1.
+ * 'comment' is not used. You can store here any text of your choice. It is not used by application.
+ *
+ * Note: To have value dynamic, you can set value to 0 in definition and edit the value on the fly into the constructor.
+ */
+
+ // BEGIN MODULEBUILDER PROPERTIES
+ /**
+ * @var array Array with all fields and their property. Do not use it as a static var. It may be modified by constructor.
+ */
+ public $fields=array(
+ 'rowid' => array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>'1', 'position'=>1, 'notnull'=>1, 'visible'=>0, 'noteditable'=>'1', 'index'=>1, 'css'=>'left', 'comment'=>"Id"),
+ 'fk_skill' => array('type'=>'integer:Skill:hrm/class/skill.class.php:1', 'label'=>'Skill', 'enabled'=>'1', 'position'=>3, 'notnull'=>1, 'visible'=>1, 'index'=>1,),
+ 'rank' => array('type'=>'integer', 'label'=>'Rank', 'enabled'=>'1', 'position'=>4, 'notnull'=>1, 'visible'=>1, 'default' => 0),
+ 'fk_object' => array('type'=>'integer', 'label'=>'object', 'enabled'=>'1', 'position'=>5, 'notnull'=>1, 'visible'=>0,),
+ 'date_creation' => array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>'1', 'position'=>500, 'notnull'=>1, 'visible'=>-2,),
+ 'tms' => array('type'=>'timestamp', 'label'=>'DateModification', 'enabled'=>'1', 'position'=>501, 'notnull'=>0, 'visible'=>-2,),
+ 'fk_user_creat' => array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserAuthor', 'enabled'=>'1', 'position'=>510, 'notnull'=>1, 'visible'=>-2, 'foreignkey'=>'user.rowid',),
+ 'fk_user_modif' => array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserModif', 'enabled'=>'1', 'position'=>511, 'notnull'=>-1, 'visible'=>-2,),
+ 'objecttype' => array('type'=>'varchar(128)', 'label'=>'objecttype', 'enabled'=>'1', 'position'=>6, 'notnull'=>1, 'visible'=>0,),
+ );
+ public $rowid;
+ public $fk_skill;
+ public $rank;
+ public $fk_object;
+ public $date_creation;
+ public $tms;
+ public $fk_user_creat;
+ public $fk_user_modif;
+ public $objecttype;
+ // END MODULEBUILDER PROPERTIES
+
+
+ // If this object has a subtable with lines
+
+ // /**
+ // * @var string Name of subtable line
+ // */
+ // public $table_element_line = 'hrm_skillrankline';
+
+ // /**
+ // * @var string Field with ID of parent key if this object has a parent
+ // */
+ // public $fk_element = 'fk_skillrank';
+
+ // /**
+ // * @var string Name of subtable class that manage subtable lines
+ // */
+ // public $class_element_line = 'SkillRankline';
+
+ // /**
+ // * @var array List of child tables. To test if we can delete object.
+ // */
+ // protected $childtables = array();
+
+ // /**
+ // * @var array List of child tables. To know object to delete on cascade.
+ // * If name matches '@ClassNAme:FilePathClass;ParentFkFieldName' it will
+ // * call method deleteByParentField(parentId, ParentFkFieldName) to fetch and delete child object
+ // */
+ // protected $childtablesoncascade = array('hrm_skillrankdet');
+
+ // /**
+ // * @var SkillRankLine[] Array of subtable lines
+ // */
+ // public $lines = array();
+
+
+
+ /**
+ * Constructor
+ *
+ * @param DoliDb $db Database handler
+ */
+ public function __construct(DoliDB $db)
+ {
+ global $conf, $langs;
+
+ $this->db = $db;
+
+ if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID) && isset($this->fields['rowid'])) {
+ $this->fields['rowid']['visible'] = 0;
+ }
+ if (empty($conf->multicompany->enabled) && isset($this->fields['entity'])) {
+ $this->fields['entity']['enabled'] = 0;
+ }
+
+ // Example to show how to set values of fields definition dynamically
+ /*if ($user->rights->hrm->skillrank->read) {
+ $this->fields['myfield']['visible'] = 1;
+ $this->fields['myfield']['noteditable'] = 0;
+ }*/
+
+ // Unset fields that are disabled
+ foreach ($this->fields as $key => $val) {
+ if (isset($val['enabled']) && empty($val['enabled'])) {
+ unset($this->fields[$key]);
+ }
+ }
+
+ // Translate some data of arrayofkeyval
+ if (is_object($langs)) {
+ foreach ($this->fields as $key => $val) {
+ if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
+ foreach ($val['arrayofkeyval'] as $key2 => $val2) {
+ $this->fields[$key]['arrayofkeyval'][$key2] = $langs->trans($val2);
+ }
+ }
+ }
+ }
+ }
+
+ /**
+ * Create object into database
+ *
+ * @param User $user User that creates
+ * @param bool $notrigger false=launch triggers after, true=disable triggers
+ * @return int <0 if KO, Id of created object if OK
+ */
+ public function create(User $user, $notrigger = false)
+ {
+ global $langs;
+
+ $sqlfilter = 'fk_object='.((int) $this->fk_object)." AND objecttype='".$this->db->escape($this->objecttype)."' AND fk_skill = ".((int) $this->fk_skill);
+ $alreadyLinked = $this->fetchAll('ASC', 'rowid', 0, 0, array('customsql' => $sqlfilter));
+ if (!empty($alreadyLinked)) {
+ $this->error = $langs->trans('ErrSkillAlreadyAdded');
+ return -1;
+ }
+
+ $resultcreate = $this->createCommon($user, $notrigger);
+
+ return $resultcreate;
+ }
+
+ /**
+ * Clone an object into another one
+ *
+ * @param User $user User that creates
+ * @param int $fromid Id of object to clone
+ * @return mixed New object created, <0 if KO
+ */
+ public function createFromClone(User $user, $fromid)
+ {
+ global $langs, $extrafields;
+ $error = 0;
+
+ dol_syslog(__METHOD__, LOG_DEBUG);
+
+ $object = new self($this->db);
+
+ $this->db->begin();
+
+ // Load source object
+ $result = $object->fetchCommon($fromid);
+ if ($result > 0 && !empty($object->table_element_line)) {
+ $object->fetchLines();
+ }
+
+ // get lines so they will be clone
+ //foreach($this->lines as $line)
+ // $line->fetch_optionals();
+
+ // Reset some properties
+ unset($object->id);
+ unset($object->fk_user_creat);
+ unset($object->import_key);
+
+ // Clear fields
+ if (property_exists($object, 'ref')) {
+ $object->ref = empty($this->fields['ref']['default']) ? "Copy_Of_".$object->ref : $this->fields['ref']['default'];
+ }
+ if (property_exists($object, 'label')) {
+ $object->label = empty($this->fields['label']['default']) ? $langs->trans("CopyOf")." ".$object->label : $this->fields['label']['default'];
+ }
+ if (property_exists($object, 'status')) {
+ $object->status = self::STATUS_DRAFT;
+ }
+ if (property_exists($object, 'date_creation')) {
+ $object->date_creation = dol_now();
+ }
+ if (property_exists($object, 'date_modification')) {
+ $object->date_modification = null;
+ }
+ // ...
+ // Clear extrafields that are unique
+ if (is_array($object->array_options) && count($object->array_options) > 0) {
+ $extrafields->fetch_name_optionals_label($this->table_element);
+ foreach ($object->array_options as $key => $option) {
+ $shortkey = preg_replace('/options_/', '', $key);
+ if (!empty($extrafields->attributes[$this->table_element]['unique'][$shortkey])) {
+ //var_dump($key); var_dump($clonedObj->array_options[$key]); exit;
+ unset($object->array_options[$key]);
+ }
+ }
+ }
+
+ // Create clone
+ $object->context['createfromclone'] = 'createfromclone';
+ $result = $object->createCommon($user);
+ if ($result < 0) {
+ $error++;
+ $this->error = $object->error;
+ $this->errors = $object->errors;
+ }
+
+ if (!$error) {
+ // copy internal contacts
+ if ($this->copy_linked_contact($object, 'internal') < 0) {
+ $error++;
+ }
+ }
+
+ if (!$error) {
+ // copy external contacts if same company
+ if (property_exists($this, 'fk_soc') && $this->fk_soc == $object->socid) {
+ if ($this->copy_linked_contact($object, 'external') < 0) {
+ $error++;
+ }
+ }
+ }
+
+ unset($object->context['createfromclone']);
+
+ // End
+ if (!$error) {
+ $this->db->commit();
+ return $object;
+ } else {
+ $this->db->rollback();
+ return -1;
+ }
+ }
+
+ /**
+ * Load object in memory from the database
+ *
+ * @param int $id Id object
+ * @param string $ref Ref
+ * @return int <0 if KO, 0 if not found, >0 if OK
+ */
+ public function fetch($id, $ref = null)
+ {
+ $result = $this->fetchCommon($id, $ref);
+ if ($result > 0 && !empty($this->table_element_line)) {
+ $this->fetchLines();
+ }
+ return $result;
+ }
+
+ /**
+ * Load object lines in memory from the database
+ *
+ * @return int <0 if KO, 0 if not found, >0 if OK
+ */
+ public function fetchLines()
+ {
+ $this->lines = array();
+
+ $result = $this->fetchLinesCommon();
+ return $result;
+ }
+
+ /**
+ * Clone skillrank Object linked to job with user id
+ * The skillrank table is a join table that is marked for multiple objects
+ *
+ * @param SkillRank $currentSkill line of evaluation (skill) we need to clone and add to user skills list
+ * @param int $fk_user id of user linked to skillrank
+ * @return int > 0 if ok, < 0 if ko
+ */
+ public function cloneFromCurrentSkill($currentSkill, $fk_user)
+ {
+
+ global $user;
+
+ $this->fk_skill = $currentSkill->fk_skill;
+ $this->rank = $currentSkill->rank;
+ $this->fk_object = $fk_user;
+ $this->date_creation = dol_now();
+ $this->fk_user_creat = $user->id;
+ $this->fk_user_modif = $user->id;
+ $this->objecttype = self::SKILLRANK_TYPE_USER;
+ $result = $this->create($user);
+
+ return $result;
+ }
+
+ /**
+ * Load list of objects in memory from the database.
+ *
+ * @param string $sortorder Sort Order
+ * @param string $sortfield Sort field
+ * @param int $limit limit
+ * @param int $offset Offset
+ * @param array $filter Filter array. Example array('field'=>'valueforlike', 'customurl'=>...)
+ * @param string $filtermode Filter mode (AND or OR)
+ * @return array|int int <0 if KO, array of pages if OK
+ */
+ public function fetchAll($sortorder = '', $sortfield = '', $limit = 0, $offset = 0, array $filter = array(), $filtermode = 'AND')
+ {
+ global $conf;
+
+ dol_syslog(__METHOD__, LOG_DEBUG);
+
+ $records = array();
+
+ $sql = 'SELECT ';
+ $sql .= $this->getFieldList('t');
+ $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t';
+ if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
+ $sql .= ' WHERE t.entity IN ('.getEntity($this->table_element).')';
+ } else {
+ $sql .= ' WHERE 1 = 1';
+ }
+ // Manage filter
+ $sqlwhere = array();
+ if (count($filter) > 0) {
+ foreach ($filter as $key => $value) {
+ if ($key == 't.rowid') {
+ $sqlwhere[] = $key.'='.$value;
+ } elseif (in_array($this->fields[$key]['type'], array('date', 'datetime', 'timestamp'))) {
+ $sqlwhere[] = $key.' = \''.$this->db->idate($value).'\'';
+ } elseif ($key == 'customsql') {
+ $sqlwhere[] = $value;
+ } elseif (strpos($value, '%') === false) {
+ $sqlwhere[] = $key.' IN ('.$this->db->sanitize($this->db->escape($value)).')';
+ } else {
+ $sqlwhere[] = $key.' LIKE \'%'.$this->db->escape($value).'%\'';
+ }
+ }
+ }
+ if (count($sqlwhere) > 0) {
+ $sql .= " AND (".implode(" ".$filtermode." ", $sqlwhere).")";
+ }
+
+ if (!empty($sortfield)) {
+ $sql .= $this->db->order($sortfield, $sortorder);
+ }
+ if (!empty($limit)) {
+ $sql .= ' '.$this->db->plimit($limit, $offset);
+ }
+
+ $resql = $this->db->query($sql);
+ if ($resql) {
+ $num = $this->db->num_rows($resql);
+ $i = 0;
+ while ($i < ($limit ? min($limit, $num) : $num)) {
+ $obj = $this->db->fetch_object($resql);
+
+ $record = new self($this->db);
+ $record->setVarsFromFetchObj($obj);
+
+ $records[$record->id] = $record;
+
+ $i++;
+ }
+ $this->db->free($resql);
+
+ return $records;
+ } else {
+ $this->errors[] = 'Error '.$this->db->lasterror();
+ dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
+
+ return -1;
+ }
+ }
+
+ /**
+ * Update object into database
+ *
+ * @param User $user User that modifies
+ * @param bool $notrigger false=launch triggers after, true=disable triggers
+ * @return int <0 if KO, >0 if OK
+ */
+ public function update(User $user, $notrigger = false)
+ {
+ return $this->updateCommon($user, $notrigger);
+ }
+
+ /**
+ * Delete object in database
+ *
+ * @param User $user User that deletes
+ * @param bool $notrigger false=launch triggers after, true=disable triggers
+ * @return int <0 if KO, >0 if OK
+ */
+ public function delete(User $user, $notrigger = false)
+ {
+ return $this->deleteCommon($user, $notrigger);
+ //return $this->deleteCommon($user, $notrigger, 1);
+ }
+
+ /**
+ * Delete a line of object in database
+ *
+ * @param User $user User that delete
+ * @param int $idline Id of line to delete
+ * @param bool $notrigger false=launch triggers after, true=disable triggers
+ * @return int >0 if OK, <0 if KO
+ */
+ public function deleteLine(User $user, $idline, $notrigger = false)
+ {
+ if ($this->status < 0) {
+ $this->error = 'ErrorDeleteLineNotAllowedByObjectStatus';
+ return -2;
+ }
+
+ return $this->deleteLineCommon($user, $idline, $notrigger);
+ }
+
+
+ /**
+ * Validate object
+ *
+ * @param User $user User making status change
+ * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
+ * @return int <=0 if OK, 0=Nothing done, >0 if KO
+ */
+ public function validate($user, $notrigger = 0)
+ {
+ global $conf, $langs;
+
+ require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
+
+ $error = 0;
+
+ // Protection
+ if ($this->status == self::STATUS_VALIDATED) {
+ dol_syslog(get_class($this)."::validate action abandonned: already validated", LOG_WARNING);
+ return 0;
+ }
+
+ /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->hrm->skillrank->write))
+ || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->hrm->skillrank->skillrank_advance->validate))))
+ {
+ $this->error='NotEnoughPermissions';
+ dol_syslog(get_class($this)."::valid ".$this->error, LOG_ERR);
+ return -1;
+ }*/
+
+ $now = dol_now();
+
+ $this->db->begin();
+
+ // Define new ref
+ if (!$error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) { // empty should not happened, but when it occurs, the test save life
+ $num = $this->getNextNumRef();
+ } else {
+ $num = $this->ref;
+ }
+ $this->newref = $num;
+
+ if (!empty($num)) {
+ // Validate
+ $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
+ $sql .= " SET ref = '".$this->db->escape($num)."',";
+ $sql .= " status = ".self::STATUS_VALIDATED;
+ if (!empty($this->fields['date_validation'])) {
+ $sql .= ", date_validation = '".$this->db->idate($now)."'";
+ }
+ if (!empty($this->fields['fk_user_valid'])) {
+ $sql .= ", fk_user_valid = ".((int) $user->id);
+ }
+ $sql .= " WHERE rowid = ".((int) $this->id);
+
+ dol_syslog(get_class($this)."::validate()", LOG_DEBUG);
+ $resql = $this->db->query($sql);
+ if (!$resql) {
+ dol_print_error($this->db);
+ $this->error = $this->db->lasterror();
+ $error++;
+ }
+
+ if (!$error && !$notrigger) {
+ // Call trigger
+ $result = $this->call_trigger('SKILLRANK_VALIDATE', $user);
+ if ($result < 0) {
+ $error++;
+ }
+ // End call triggers
+ }
+ }
+
+ if (!$error) {
+ $this->oldref = $this->ref;
+
+ // Rename directory if dir was a temporary ref
+ if (preg_match('/^[\(]?PROV/i', $this->ref)) {
+ // Now we rename also files into index
+ $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filename = CONCAT('".$this->db->escape($this->newref)."', SUBSTR(filename, ".(strlen($this->ref) + 1).")), filepath = 'skillrank/".$this->db->escape($this->newref)."'";
+ $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'skillrank/".$this->db->escape($this->ref)."' and entity = ".((int) $conf->entity);
+ $resql = $this->db->query($sql);
+ if (!$resql) {
+ $error++; $this->error = $this->db->lasterror();
+ }
+
+ // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments
+ $oldref = dol_sanitizeFileName($this->ref);
+ $newref = dol_sanitizeFileName($num);
+ $dirsource = $conf->hrm->dir_output.'/skillrank/'.$oldref;
+ $dirdest = $conf->hrm->dir_output.'/skillrank/'.$newref;
+ if (!$error && file_exists($dirsource)) {
+ dol_syslog(get_class($this)."::validate() rename dir ".$dirsource." into ".$dirdest);
+
+ if (@rename($dirsource, $dirdest)) {
+ dol_syslog("Rename ok");
+ // Rename docs starting with $oldref with $newref
+ $listoffiles = dol_dir_list($conf->hrm->dir_output.'/skillrank/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/'));
+ foreach ($listoffiles as $fileentry) {
+ $dirsource = $fileentry['name'];
+ $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource);
+ $dirsource = $fileentry['path'].'/'.$dirsource;
+ $dirdest = $fileentry['path'].'/'.$dirdest;
+ @rename($dirsource, $dirdest);
+ }
+ }
+ }
+ }
+ }
+
+ // Set new ref and current status
+ if (!$error) {
+ $this->ref = $num;
+ $this->status = self::STATUS_VALIDATED;
+ }
+
+ if (!$error) {
+ $this->db->commit();
+ return 1;
+ } else {
+ $this->db->rollback();
+ return -1;
+ }
+ }
+
+
+ /**
+ * Set draft status
+ *
+ * @param User $user Object user that modify
+ * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers
+ * @return int <0 if KO, >0 if OK
+ */
+ public function setDraft($user, $notrigger = 0)
+ {
+ // Protection
+ if ($this->status <= self::STATUS_DRAFT) {
+ return 0;
+ }
+
+ /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->hrm->write))
+ || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->hrm->hrm_advance->validate))))
+ {
+ $this->error='Permission denied';
+ return -1;
+ }*/
+
+ return $this->setStatusCommon($user, self::STATUS_DRAFT, $notrigger, 'SKILLRANK_UNVALIDATE');
+ }
+
+ /**
+ * Set cancel status
+ *
+ * @param User $user Object user that modify
+ * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers
+ * @return int <0 if KO, 0=Nothing done, >0 if OK
+ */
+ public function cancel($user, $notrigger = 0)
+ {
+ // Protection
+ if ($this->status != self::STATUS_VALIDATED) {
+ return 0;
+ }
+
+ /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->hrm->write))
+ || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->hrm->hrm_advance->validate))))
+ {
+ $this->error='Permission denied';
+ return -1;
+ }*/
+
+ return $this->setStatusCommon($user, self::STATUS_CANCELED, $notrigger, 'SKILLRANK_CANCEL');
+ }
+
+ /**
+ * Set back to validated status
+ *
+ * @param User $user Object user that modify
+ * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers
+ * @return int <0 if KO, 0=Nothing done, >0 if OK
+ */
+ public function reopen($user, $notrigger = 0)
+ {
+ // Protection
+ if ($this->status != self::STATUS_CANCELED) {
+ return 0;
+ }
+
+ /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->hrm->write))
+ || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->hrm->hrm_advance->validate))))
+ {
+ $this->error='Permission denied';
+ return -1;
+ }*/
+
+ return $this->setStatusCommon($user, self::STATUS_VALIDATED, $notrigger, 'SKILLRANK_REOPEN');
+ }
+
+ /**
+ * Return a link to the object card (with optionaly the picto)
+ *
+ * @param int $withpicto Include picto in link (0=No picto, 1=Include picto into link, 2=Only picto)
+ * @param string $option On what the link point to ('nolink', ...)
+ * @param int $notooltip 1=Disable tooltip
+ * @param string $morecss Add more css on link
+ * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
+ * @return string String with URL
+ */
+ public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $morecss = '', $save_lastsearch_value = -1)
+ {
+ global $conf, $langs, $hookmanager;
+
+ if (!empty($conf->dol_no_mouse_hover)) {
+ $notooltip = 1; // Force disable tooltips
+ }
+
+ $result = '';
+
+ $label = img_picto('', $this->picto).' '.$langs->trans("SkillRank").'';
+ if (isset($this->status)) {
+ $label .= ' '.$this->getLibStatut(5);
+ }
+ $label .= ' ';
+ $label .= ''.$langs->trans('Ref').': '.$this->ref;
+
+ $url = dol_buildpath('/hrm/skillrank_card.php', 1).'?id='.$this->id;
+
+ if ($option != 'nolink') {
+ // Add param to save lastsearch_values or not
+ $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
+ if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
+ $add_save_lastsearch_values = 1;
+ }
+ if ($add_save_lastsearch_values) {
+ $url .= '&save_lastsearch_values=1';
+ }
+ }
+
+ $linkclose = '';
+ if (empty($notooltip)) {
+ if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
+ $label = $langs->trans("ShowSkillRank");
+ $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
+ }
+ $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"';
+ $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"';
+ } else {
+ $linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
+ }
+
+ if ($option == 'nolink') {
+ $linkstart = '';
+ if ($option == 'nolink') {
+ $linkend = '';
+ } else {
+ $linkend = '';
+ }
+
+ $result .= $linkstart;
+
+ if (empty($this->showphoto_on_popup)) {
+ if ($withpicto) {
+ $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
+ }
+ } else {
+ if ($withpicto) {
+ require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
+
+ list($class, $module) = explode('@', $this->picto);
+ $upload_dir = $conf->$module->multidir_output[$conf->entity]."/$class/".dol_sanitizeFileName($this->ref);
+ $filearray = dol_dir_list($upload_dir, "files");
+ $filename = $filearray[0]['name'];
+ if (!empty($filename)) {
+ $pospoint = strpos($filearray[0]['name'], '.');
+
+ $pathtophoto = $class.'/'.$this->ref.'/thumbs/'.substr($filename, 0, $pospoint).'_mini'.substr($filename, $pospoint);
+ if (empty($conf->global->{strtoupper($module.'_'.$class).'_FORMATLISTPHOTOSASUSERS'})) {
+ $result .= '
';
+ } else {
+ $result .= '
';
+ }
+
+ $result .= '';
+ } else {
+ $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
+ }
+ }
+ }
+
+ if ($withpicto != 2) {
+ $result .= $this->ref;
+ }
+
+ $result .= $linkend;
+ //if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : '');
+
+ global $action, $hookmanager;
+ $hookmanager->initHooks(array('skillrankdao'));
+ $parameters = array('id'=>$this->id, 'getnomurl'=>$result);
+ $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
+ if ($reshook > 0) {
+ $result = $hookmanager->resPrint;
+ } else {
+ $result .= $hookmanager->resPrint;
+ }
+
+ return $result;
+ }
+
+ /**
+ * Return the label of the status
+ *
+ * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto, 6=Long label + Picto
+ * @return string Label of status
+ */
+ public function getLibStatut($mode = 0)
+ {
+ return $this->LibStatut($this->status, $mode);
+ }
+
+ // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
+ /**
+ * Return the status
+ *
+ * @param int $status Id status
+ * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto, 6=Long label + Picto
+ * @return string Label of status
+ */
+ public function LibStatut($status, $mode = 0)
+ {
+ // phpcs:enable
+ if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
+ global $langs;
+ //$langs->load("hrm");
+ $this->labelStatus[self::STATUS_DRAFT] = $langs->trans('Draft');
+ $this->labelStatus[self::STATUS_VALIDATED] = $langs->trans('Enabled');
+ $this->labelStatus[self::STATUS_CANCELED] = $langs->trans('Disabled');
+ $this->labelStatusShort[self::STATUS_DRAFT] = $langs->trans('Draft');
+ $this->labelStatusShort[self::STATUS_VALIDATED] = $langs->trans('Enabled');
+ $this->labelStatusShort[self::STATUS_CANCELED] = $langs->trans('Disabled');
+ }
+
+ $statusType = 'status'.$status;
+ //if ($status == self::STATUS_VALIDATED) $statusType = 'status1';
+ if ($status == self::STATUS_CANCELED) {
+ $statusType = 'status6';
+ }
+
+ return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
+ }
+
+ /**
+ * Load the info information in the object
+ *
+ * @param int $id Id of object
+ * @return void
+ */
+ public function info($id)
+ {
+ $sql = 'SELECT rowid, date_creation as datec, tms as datem,';
+ $sql .= ' fk_user_creat, fk_user_modif';
+ $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t';
+ $sql .= ' WHERE t.rowid = '.((int) $id);
+ $result = $this->db->query($sql);
+ if ($result) {
+ if ($this->db->num_rows($result)) {
+ $obj = $this->db->fetch_object($result);
+ $this->id = $obj->rowid;
+ if ($obj->fk_user_author) {
+ $cuser = new User($this->db);
+ $cuser->fetch($obj->fk_user_author);
+ $this->user_creation = $cuser;
+ }
+
+ if ($obj->fk_user_valid) {
+ $vuser = new User($this->db);
+ $vuser->fetch($obj->fk_user_valid);
+ $this->user_validation = $vuser;
+ }
+
+ if ($obj->fk_user_cloture) {
+ $cluser = new User($this->db);
+ $cluser->fetch($obj->fk_user_cloture);
+ $this->user_cloture = $cluser;
+ }
+
+ $this->date_creation = $this->db->jdate($obj->datec);
+ $this->date_modification = $this->db->jdate($obj->datem);
+ $this->date_validation = $this->db->jdate($obj->datev);
+ }
+
+ $this->db->free($result);
+ } else {
+ dol_print_error($this->db);
+ }
+ }
+
+ /**
+ * Initialise object with example values
+ * Id must be 0 if object instance is a specimen
+ *
+ * @return void
+ */
+ public function initAsSpecimen()
+ {
+ // Set here init that are not commonf fields
+ // $this->property1 = ...
+ // $this->property2 = ...
+
+ $this->initAsSpecimenCommon();
+ }
+
+ /**
+ * Create an array of lines
+ *
+ * @return array|int array of lines if OK, <0 if KO
+ */
+ public function getLinesArray()
+ {
+ $this->lines = array();
+
+ $objectline = new SkillRankLine($this->db);
+ $result = $objectline->fetchAll('ASC', 'position', 0, 0, array('customsql'=>'fk_skillrank = '.((int) $this->id)));
+
+ if (is_numeric($result)) {
+ $this->error = $this->error;
+ $this->errors = $this->errors;
+ return $result;
+ } else {
+ $this->lines = $result;
+ return $this->lines;
+ }
+ }
+
+ /**
+ * Returns the reference to the following non used object depending on the active numbering module.
+ *
+ * @return string Object free reference
+ */
+ public function getNextNumRef()
+ {
+ global $langs, $conf;
+ $langs->load("hrm");
+
+ if (empty($conf->global->hrm_SKILLRANK_ADDON)) {
+ $conf->global->hrm_SKILLRANK_ADDON = 'mod_skillrank_standard';
+ }
+
+ if (!empty($conf->global->hrm_SKILLRANK_ADDON)) {
+ $mybool = false;
+
+ $file = $conf->global->hrm_SKILLRANK_ADDON.".php";
+ $classname = $conf->global->hrm_SKILLRANK_ADDON;
+
+ // Include file with class
+ $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
+ foreach ($dirmodels as $reldir) {
+ $dir = dol_buildpath($reldir."core/modules/hrm/");
+
+ // Load file with numbering class (if found)
+ $mybool |= @include_once $dir.$file;
+ }
+
+ if ($mybool === false) {
+ dol_print_error('', "Failed to include file ".$file);
+ return '';
+ }
+
+ if (class_exists($classname)) {
+ $obj = new $classname();
+ $numref = $obj->getNextValue($this);
+
+ if ($numref != '' && $numref != '-1') {
+ return $numref;
+ } else {
+ $this->error = $obj->error;
+ //dol_print_error($this->db,get_class($this)."::getNextNumRef ".$obj->error);
+ return "";
+ }
+ } else {
+ print $langs->trans("Error")." ".$langs->trans("ClassNotFound").' '.$classname;
+ return "";
+ }
+ } else {
+ print $langs->trans("ErrorNumberingModuleNotSetup", $this->element);
+ return "";
+ }
+ }
+
+ /**
+ * Create a document onto disk according to template module.
+ *
+ * @param string $modele Force template to use ('' to not force)
+ * @param Translate $outputlangs objet lang a utiliser pour traduction
+ * @param int $hidedetails Hide details of lines
+ * @param int $hidedesc Hide description
+ * @param int $hideref Hide ref
+ * @param null|array $moreparams Array to provide more information
+ * @return int 0 if KO, 1 if OK
+ */
+ public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
+ {
+ global $conf, $langs;
+
+ $result = 0;
+ $includedocgeneration = 0;
+
+ $langs->load("hrm");
+
+ if (!dol_strlen($modele)) {
+ $modele = 'standard_skillrank';
+
+ if (!empty($this->model_pdf)) {
+ $modele = $this->model_pdf;
+ } elseif (!empty($conf->global->SKILLRANK_ADDON_PDF)) {
+ $modele = $conf->global->SKILLRANK_ADDON_PDF;
+ }
+ }
+
+ $modelpath = "core/modules/hrm/doc/";
+
+ if ($includedocgeneration && !empty($modele)) {
+ $result = $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
+ }
+
+ return $result;
+ }
+
+ /**
+ * Action executed by scheduler
+ * CAN BE A CRON TASK. In such a case, parameters come from the schedule job setup field 'Parameters'
+ * Use public function doScheduledJob($param1, $param2, ...) to get parameters
+ *
+ * @return int 0 if OK, <>0 if KO (this function is used also by cron so only 0 is OK)
+ */
+ public function doScheduledJob()
+ {
+ global $conf, $langs;
+
+ //$conf->global->SYSLOG_FILE = 'DOL_DATA_ROOT/dolibarr_mydedicatedlofile.log';
+
+ $error = 0;
+ $this->output = '';
+ $this->error = '';
+
+ dol_syslog(__METHOD__, LOG_DEBUG);
+
+ $now = dol_now();
+
+ $this->db->begin();
+
+ // ...
+
+ $this->db->commit();
+
+ return $error;
+ }
+
+ /**
+ * @param array $val
+ * @param string $key
+ * @param string $value
+ * @param string $moreparam
+ * @param string $keysuffix
+ * @param string $keyprefix
+ * @param string $morecss
+ * @return string
+ */
+ // public function showOutputField($val, $key, $value, $moreparam = '', $keysuffix = '', $keyprefix = '', $morecss = '')
+ // {
+ // if ($key == "rank") {
+ // return displayRankInfos($this);
+ // } else return parent::showOutputField($val, $key, $value, $moreparam, $keysuffix, $keyprefix, $morecss);
+ // }
+}
diff --git a/htdocs/hrm/compare.php b/htdocs/hrm/compare.php
new file mode 100644
index 00000000000..13b83af9737
--- /dev/null
+++ b/htdocs/hrm/compare.php
@@ -0,0 +1,566 @@
+
+ * Copyright (C) 2021 Gauthier VERDOL
+ * Copyright (C) 2021 Greg Rastklan
+ * Copyright (C) 2021 Jean-Pascal BOUDET
+ * Copyright (C) 2021 Grégory BLEMAND
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see .
+
+ * \file class/compare.php
+ * \ingroup hrm
+ * \brief This file compares skills of user groups
+ *
+ * Displays a table in three parts.
+ * 1- the left part displays the list of users of the selected group 1.
+ *
+ * 2- the central part displays the skills. display of the maximum score for this group and the number of occurrences.
+ *
+ * 3- the right part displays the members of group 2 or the job to be compared
+ *
+ *
+ *
+ */
+
+require_once '../main.inc.php';
+require_once DOL_DOCUMENT_ROOT.'/core/lib/functions.lib.php';
+require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
+
+ini_set('display_errors', 1);
+
+require_once DOL_DOCUMENT_ROOT . '/hrm/class/skill.class.php';
+require_once DOL_DOCUMENT_ROOT . '/hrm/class/job.class.php';
+require_once DOL_DOCUMENT_ROOT . '/hrm/class/evaluation.class.php';
+require_once DOL_DOCUMENT_ROOT . '/hrm/class/position.class.php';
+require_once DOL_DOCUMENT_ROOT . '/hrm/lib/hrm.lib.php';
+
+$permissiontoread = $user->rights->hrm->compare->read;
+if (empty($conf->hrm->enabled)) accessforbidden();
+if (!$permissiontoread || ($action === 'create' && !$permissiontoadd)) accessforbidden();
+
+$langs->load('hrm');
+
+$css = array();
+$css[] = '/hrm/css/style.css';
+llxHeader('', $langs->trans('SkillComparison'), '', '', 0, 0, '', $css);
+
+$head = array();
+
+$h = 0;
+$head[$h][0] = $_SERVER["PHP_SELF"];
+$head[$h][1] = $langs->trans("SkillComparison");
+$head[$h][2] = 'compare';
+
+print dol_get_fiche_head($head, 'compare', '', 1);
+
+//$PDOdb = new TPDOdb;
+$form = new Form($db);
+?>
+
+
+
+
+
+
+
';
+ }
+
+ $out .= '';
+
+ return $out;
+}
+
+/**
+ * Return a html list with rank informations
+ * @param array $TMergedSkills skill list for display
+ * @param string $field which column of comparison we are working with
+ * @return string
+ */
+function rate(&$TMergedSkills, $field)
+{
+ global $langs, $fk_job;
+
+ $out = '
';
+
+ return $out;
+}
+
+/**
+ * return a html ul list of skills
+ *
+ * @param array $TMergedSkills skill list for display
+ * @return string (ul list in html )
+ */
+function skillList(&$TMergedSkills)
+{
+
+ $out = '
';
+ }
+
+ return $out;
+}
+
+
+/**
+ *
+ * Allow to get skill(s) of a user
+ *
+ * @param array $TUser array of employees we need to get skills
+ * @return array|int
+ */
+function getSkillForUsers($TUser)
+{
+ global $db;
+
+ //I go back to the user with the highest score in a given group for all the skills assessed in that group
+ if (empty($TUser)) return array();
+
+ $sql = 'SELECT sk.rowid, sk.label, sk.description, sk.skill_type, sr.fk_object, sr.objecttype, sr.fk_skill, ';
+ $sql.= ' MAX(sr.rank) as "rank"';
+ $sql.= ' FROM '.MAIN_DB_PREFIX.'hrm_skill sk';
+ $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'hrm_skillrank sr ON (sk.rowid = sr.fk_skill)';
+ $sql.= " WHERE sr.objecttype = '".SkillRank::SKILLRANK_TYPE_USER."'";
+ $sql.= ' AND sr.fk_object IN ('.$db->sanitize(implode(',', $TUser)).')';
+ $sql.= " GROUP BY sk.rowid, sk.label, sk.description, sk.skill_type, sr.fk_object, sr.objecttype, sr.fk_skill "; // group par competence
+
+ $resql = $db->query($sql);
+ $Tab = array();
+
+ if ($resql) {
+ //For each skill, we count the number of times that the max score has been reached within a given group
+ $num = 0;
+ while ($obj = $db->fetch_object($resql) ) {
+ $sql1 = "SELECT count(*) as how_many_max FROM ".MAIN_DB_PREFIX."hrm_skillrank sr";
+ $sql1.=" WHERE sr.rank = ".((int) $obj->rank);
+ $sql1.=" AND sr.objecttype = '".Skillrank::SKILLRANK_TYPE_USER."'";
+ $sql1.=" AND sr.fk_skill = ".((int) $obj->fk_skill);
+ $sql1.=" AND sr.fk_object IN (".$db->sanitize(implode(',', $TUser)).")";
+ $resql1 = $db->query($sql1);
+
+ $objMax = $db->fetch_object($resql1);
+
+ $Tab[$num] = new stdClass();
+ $Tab[$num]->fk_skill = $obj->fk_skill;
+ $Tab[$num]->label = $obj->label;
+ $Tab[$num]->description = $obj->description;
+ $Tab[$num]->skill_type = $obj->skill_type;
+ $Tab[$num]->fk_object = $obj->fk_object;
+ $Tab[$num]->objectType = SkillRank::SKILLRANK_TYPE_USER;
+ $Tab[$num]->rank = $obj->rank;
+ $Tab[$num]->how_many_max = $objMax->how_many_max;
+
+ $num++;
+ }
+ } else {
+ dol_print_error($db);
+ }
+
+ return $Tab;
+}
+
+/**
+ * Allow to get skill(s) of a job
+ *
+ * @param int $fk_job job we need to get required skills
+ * @return array|int
+ */
+function getSkillForJob($fk_job)
+{
+ global $db;
+
+ if (empty($fk_job)) return array();
+
+ $sql = 'SELECT sk.rowid, sk.label, sk.description, sk.skill_type, sr.fk_object, sr.objecttype, sr.fk_skill, ';
+ $sql.= ' MAX(sr.rank) as "rank"';
+ $sql.=' FROM '.MAIN_DB_PREFIX.'hrm_skill sk';
+ $sql.=' LEFT JOIN '.MAIN_DB_PREFIX.'hrm_skillrank sr ON (sk.rowid = sr.fk_skill)';
+ $sql.=" WHERE sr.objecttype = '".SkillRank::SKILLRANK_TYPE_JOB."'";
+ $sql.=' AND sr.fk_object = '.((int) $fk_job);
+ $sql.=' GROUP BY sk.rowid, sk.label, sk.description, sk.skill_type, sr.fk_object, sr.objecttype, sr.fk_skill '; // group par competence*/
+
+ $resql = $db->query($sql);
+ $Tab = array();
+
+
+ if ($resql) {
+ $num = 0;
+ while ($obj = $db->fetch_object($resql) ) {
+ $Tab[$num] = new stdClass();
+ $Tab[$num]->fk_skill = $obj->fk_skill;
+ $Tab[$num]->label = $obj->label;
+ $Tab[$num]->description = $obj->description;
+ $Tab[$num]->skill_type = $obj->skill_type;
+ //$Tab[$num]->date_start = '';// du poste
+ //$Tab[$num]->date_end = ''; // du poste
+ $Tab[$num]->fk_object = $obj->fk_object;
+ $Tab[$num]->objectType = SkillRank::SKILLRANK_TYPE_JOB;
+ $Tab[$num]->rank = $obj->rank;
+ $Tab[$num]->how_many_max = $obj->how_many_max;
+
+ $num++;
+ }
+ } else {
+ dol_print_error($db);
+ }
+
+
+ return $Tab;
+}
diff --git a/htdocs/hrm/core/tpl/objectline_title.tpl.php b/htdocs/hrm/core/tpl/objectline_title.tpl.php
new file mode 100644
index 00000000000..3801288543a
--- /dev/null
+++ b/htdocs/hrm/core/tpl/objectline_title.tpl.php
@@ -0,0 +1,80 @@
+
+ * Copyright (C) 2010-2011 Laurent Destailleur
+ * Copyright (C) 2012-2013 Christophe Battarel
+ * Copyright (C) 2012 Cédric Salvador
+ * Copyright (C) 2012-2014 Raphaël Doursenaud
+ * Copyright (C) 2013 Florian Henry
+ * Copyright (C) 2017 Juanjo Menent
+ * Copyright (C) 2021 Gauthier VERDOL
+ * Copyright (C) 2021 Greg Rastklan
+ * Copyright (C) 2021 Jean-Pascal BOUDET
+ * Copyright (C) 2021 Grégory BLEMAND
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see .
+ *
+ * Need to have following variables defined:
+ * $object (invoice, order, ...)
+ * $conf
+ * $langs
+ * $element (used to test $user->rights->$element->creer)
+ * $permtoedit (used to replace test $user->rights->$element->creer)
+ * $inputalsopricewithtax (0 by default, 1 to also show column with unit price including tax)
+ * $outputalsopricetotalwithtax
+ * $usemargins (0 to disable all margins columns, 1 to show according to margin setup)
+ *
+ * $type, $text, $description, $line
+ */
+
+// Protection to avoid direct call of template
+if (empty($object) || !is_object($object)) {
+ print "Error, template page can't be called as URL";
+ exit;
+}
+
+print "\n";
+
+// Title line
+print "\n";
+
+print '
';
+
+// Adds a line numbering column
+if (!empty($conf->global->MAIN_VIEW_LINE_NUMBER)) {
+ print '
';
+}
+
+// Skill type
+print '
'.$langs->trans('SkillType').'
';
+
+// Label skill
+print '
'.$langs->trans('Label').'
';
+
+// Description
+print '
'.$langs->trans('Description').'
';
+
+// Note
+print '
'.$langs->trans('EmployeeRank').'
';
+
+
+//print '
'; // No width to allow autodim
+
+//print '
';
+
+//print '
';
+
+print "
\n";
+print "\n";
+
+print "\n";
diff --git a/htdocs/hrm/core/tpl/objectline_view.tpl.php b/htdocs/hrm/core/tpl/objectline_view.tpl.php
new file mode 100644
index 00000000000..9be74a5f38f
--- /dev/null
+++ b/htdocs/hrm/core/tpl/objectline_view.tpl.php
@@ -0,0 +1,165 @@
+
+ * Copyright (C) 2010-2011 Laurent Destailleur
+ * Copyright (C) 2012-2013 Christophe Battarel
+ * Copyright (C) 2012 Cédric Salvador
+ * Copyright (C) 2012-2014 Raphaël Doursenaud
+ * Copyright (C) 2013 Florian Henry
+ * Copyright (C) 2017 Juanjo Menent
+ * Copyright (C) 2021 Gauthier VERDOL
+ * Copyright (C) 2021 Greg Rastklan
+ * Copyright (C) 2021 Jean-Pascal BOUDET
+ * Copyright (C) 2021 Grégory BLEMAND
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see .
+ *
+ * Need to have following variables defined:
+ * $object (invoice, order, ...)
+ * $conf
+ * $langs
+ * $dateSelector
+ * $forceall (0 by default, 1 for supplier invoices/orders)
+ * $element (used to test $user->rights->$element->creer)
+ * $permtoedit (used to replace test $user->rights->$element->creer)
+ * $senderissupplier (0 by default, 1 for supplier invoices/orders)
+ * $inputalsopricewithtax (0 by default, 1 to also show column with unit price including tax)
+ * $outputalsopricetotalwithtax
+ * $usemargins (0 to disable all margins columns, 1 to show according to margin setup)
+ * $object_rights->creer initialized from = $object->getRights()
+ * $disableedit, $disablemove, $disableremove
+ *
+ * $text, $description, $line
+ */
+
+// Protection to avoid direct call of template
+if (empty($object) || !is_object($object)) {
+ print "Error, template page can't be called as URL";
+ exit;
+}
+
+global $mysoc;
+global $forceall, $senderissupplier, $inputalsopricewithtax, $outputalsopricetotalwithtax;
+
+// add html5 elements
+$domData = ' data-element="'.$line->element.'"';
+$domData .= ' data-id="'.$line->id.'"';
+$domData .= ' data-qty="'.$line->qty.'"';
+$domData .= ' data-product_type="'.$line->product_type.'"';
+
+$sign = 1;
+if (!empty($conf->global->INVOICE_POSITIVE_CREDIT_NOTE_SCREEN) && in_array($object->element, array('facture', 'invoice_supplier')) && $object->type == $object::TYPE_CREDIT_NOTE) {
+ $sign = -1;
+}
+
+$coldisplay = 0;
+?>
+
+
' . "\n";
+
+ // Common attributes
+ //$keyforbreak='fieldkeytoswitchonsecondcolumn'; // We change column just before this field
+ //unset($object->fields['fk_project']); // Hide field already shown in banner
+ //unset($object->fields['fk_soc']); // Hide field already shown in banner
+ $object->fields['label']['visible']=0; // Already in banner
+ include DOL_DOCUMENT_ROOT . '/core/tpl/commonfields_view.tpl.php';
+
+ // Other attributes. Fields from hook formObjectOptions and Extrafields.
+ include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php';
+
+ print '
' . "\n";
+
+ // Common attributes
+ //$keyforbreak='fieldkeytoswitchonsecondcolumn'; // We change column just before this field
+ //unset($object->fields['fk_project']); // Hide field already shown in banner
+ //unset($object->fields['fk_soc']); // Hide field already shown in banner
+ $object->fields['label']['visible']=0; // Already in banner
+ include DOL_DOCUMENT_ROOT . '/core/tpl/commonfields_view.tpl.php';
+
+ // Other attributes. Fields from hook formObjectOptions and Extrafields.
+ include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php';
+
+ print '
';
+ print '
';
+ print '
';
+
+ print '';
+
+ print dol_get_fiche_end();
+}
+
+
+/**
+ * Show a list of positions for the current job
+ *
+ * @return void
+ */
+function DisplayPositionList()
+{
+ global $user, $langs, $db, $conf, $extrafields, $hookmanager, $permissiontoadd, $permissiontodelete;
+
+ require_once DOL_DOCUMENT_ROOT . '/core/class/html.formcompany.class.php';
+ require_once DOL_DOCUMENT_ROOT . '/core/lib/date.lib.php';
+ require_once DOL_DOCUMENT_ROOT . '/core/lib/company.lib.php';
+
+ // load hrm libraries
+ require_once __DIR__ . '/class/position.class.php';
+
+ // for other modules
+ //dol_include_once('/othermodule/class/otherobject.class.php');
+
+ $action = GETPOST('action', 'aZ09') ? GETPOST('action', 'aZ09') : 'view'; // The action 'add', 'create', 'edit', 'update', 'view', ...
+ $massaction = GETPOST('massaction', 'alpha'); // The bulk action (combo box choice into lists)
+ $show_files = GETPOST('show_files', 'int'); // Show files area generated by bulk actions ?
+ $confirm = GETPOST('confirm', 'alpha'); // Result of a confirmation
+ $cancel = GETPOST('cancel', 'alpha'); // We click on a Cancel button
+ $toselect = GETPOST('toselect', 'array'); // Array of ids of elements selected into a list
+ $contextpage = GETPOST('contextpage', 'aZ') ? GETPOST('contextpage', 'aZ') : 'positionlist'; // To manage different context of search
+ $optioncss = GETPOST('optioncss', 'aZ'); // Option for the css output (always '' except when 'print')
+ $id = GETPOST('id', 'int');
+ $fk_job = GETPOST('fk_job', 'int');
+
+ // Load variable for pagination
+ $limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : $conf->liste_limit;
+ $sortfield = GETPOST('sortfield', 'aZ09comma');
+ $sortorder = GETPOST('sortorder', 'aZ09comma');
+ $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
+ if (empty($page) || $page < 0 || GETPOST('button_search', 'alpha') || GETPOST('button_removefilter', 'alpha')) {
+ // If $page is not defined, or '' or -1 or if we click on clear filters
+ $page = 0;
+ }
+ $offset = $limit * $page;
+ $pageprev = $page - 1;
+ $pagenext = $page + 1;
+
+ // Initialize technical objects
+ $object = new Position($db);
+
+ $extrafields = new ExtraFields($db);
+ $diroutputmassaction = $conf->hrm->dir_output . '/temp/massgeneration/' . $user->id;
+ $hookmanager->initHooks(array('positiontablist')); // Note that conf->hooks_modules contains array
+
+ // Fetch optionals attributes and labels
+ $extrafields->fetch_name_optionals_label($object->table_element);
+ //$extrafields->fetch_name_optionals_label($object->table_element_line);
+
+ $search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_');
+
+ // Default sort order (if not yet defined by previous GETPOST)
+ if (!$sortfield) {
+ reset($object->fields); // Reset is required to avoid key() to return null.
+ $sortfield = "t." . key($object->fields); // Set here default search field. By default 1st field in definition.
+ }
+ if (!$sortorder) {
+ $sortorder = "ASC";
+ }
+
+ // Initialize array of search criterias
+ $search_all = GETPOST('search_all', 'alphanohtml') ? GETPOST('search_all', 'alphanohtml') : GETPOST('sall', 'alphanohtml');
+ $search = array();
+ foreach ($object->fields as $key => $val) {
+ if (GETPOST('search_' . $key, 'alpha') !== '') {
+ $search[$key] = GETPOST('search_' . $key, 'alpha');
+ }
+ if (preg_match('/^(date|timestamp|datetime)/', $val['type'])) {
+ $search[$key . '_dtstart'] = dol_mktime(0, 0, 0, GETPOST('search_' . $key . '_dtstartmonth', 'int'), GETPOST('search_' . $key . '_dtstartday', 'int'), GETPOST('search_' . $key . '_dtstartyear', 'int'));
+ $search[$key . '_dtend'] = dol_mktime(23, 59, 59, GETPOST('search_' . $key . '_dtendmonth', 'int'), GETPOST('search_' . $key . '_dtendday', 'int'), GETPOST('search_' . $key . '_dtendyear', 'int'));
+ }
+ }
+
+ // List of fields to search into when doing a "search in all"
+ $fieldstosearchall = array();
+ foreach ($object->fields as $key => $val) {
+ if (!empty($val['searchall'])) {
+ $fieldstosearchall['t.' . $key] = $val['label'];
+ }
+ }
+
+ // Definition of array of fields for columns
+ $arrayfields = array();
+ foreach ($object->fields as $key => $val) {
+ // If $val['visible']==0, then we never show the field
+ if (!empty($val['visible'])) {
+ $visible = (int) dol_eval($val['visible'], 1);
+ $arrayfields['t.' . $key] = array(
+ 'label' => $val['label'],
+ 'checked' => (($visible < 0) ? 0 : 1),
+ 'enabled' => ($visible != 3 && dol_eval($val['enabled'], 1)),
+ 'position' => $val['position'],
+ 'help' => isset($val['help']) ? $val['help'] : ''
+ );
+ }
+ }
+ // Extra fields
+ include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_list_array_fields.tpl.php';
+
+ $object->fields = dol_sort_array($object->fields, 'position');
+ $arrayfields = dol_sort_array($arrayfields, 'position');
+
+ // Security check
+ if (empty($conf->hrm->enabled)) {
+ accessforbidden('Module not enabled');
+ }
+
+ // Security check (enable the most restrictive one)
+ if ($user->socid > 0) accessforbidden();
+ //if ($user->socid > 0) accessforbidden();
+ //$socid = 0; if ($user->socid > 0) $socid = $user->socid;
+ //$isdraft = (($object->status == $object::STATUS_DRAFT) ? 1 : 0);
+ //restrictedArea($user, $object->element, $object->id, $object->table_element, '', 'fk_soc', 'rowid', $isdraft);
+ //if (empty($conf->hrm->enabled)) accessforbidden();
+ //if (!$permissiontoread) accessforbidden();
+
+
+ /*
+ * Actions
+ */
+
+ if (GETPOST('cancel', 'alpha')) {
+ $action = 'list';
+ $massaction = '';
+ }
+ if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') {
+ $massaction = '';
+ }
+
+ $parameters = array();
+ $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
+ if ($reshook < 0) {
+ setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
+ }
+
+ if (empty($reshook)) {
+ // Selection of new fields
+ include DOL_DOCUMENT_ROOT . '/core/actions_changeselectedfields.inc.php';
+
+ // Purge search criteria
+ if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // All tests are required to be compatible with all browsers
+ foreach ($object->fields as $key => $val) {
+ $search[$key] = '';
+ if (preg_match('/^(date|timestamp|datetime)/', $val['type'])) {
+ $search[$key . '_dtstart'] = '';
+ $search[$key . '_dtend'] = '';
+ }
+ }
+ $toselect = array();
+ $search_array_options = array();
+ }
+ if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')
+ || GETPOST('button_search_x', 'alpha') || GETPOST('button_search.x', 'alpha') || GETPOST('button_search', 'alpha')) {
+ $massaction = ''; // Protection to avoid mass action if we force a new search during a mass action confirmation
+ }
+
+ // Mass actions
+ $objectclass = 'Position';
+ $objectlabel = 'Position';
+ $uploaddir = $conf->hrm->dir_output;
+ include DOL_DOCUMENT_ROOT . '/core/actions_massactions.inc.php';
+ }
+
+
+ /*
+ * View
+ */
+
+ $form = new Form($db);
+
+ $now = dol_now();
+
+ //$help_url="EN:Module_Position|FR:Module_Position_FR|ES:Módulo_Position";
+ $help_url = '';
+ $title = $langs->trans('ListOf', $langs->transnoentitiesnoconv("Positions"));
+ $morejs = array();
+ $morecss = array();
+
+
+ // Build and execute select
+ // --------------------------------------------------------------------
+ $sql = 'SELECT ';
+ $sql .= $object->getFieldList('t');
+ // Add fields from extrafields
+ if (!empty($extrafields->attributes[$object->table_element]['label'])) {
+ foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) {
+ $sql .= ($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? ", ef." . $key . " as options_" . $key . ', ' : '');
+ }
+ }
+ // Add fields from hooks
+ $parameters = array();
+ $reshook = $hookmanager->executeHooks('printFieldListSelect', $parameters, $object); // Note that $action and $object may have been modified by hook
+ $sql .= preg_replace('/^,/', '', $hookmanager->resPrint);
+ $sql = preg_replace('/,\s*$/', '', $sql);
+ $sql .= " FROM " . MAIN_DB_PREFIX . $object->table_element . " as t";
+ if (isset($extrafields->attributes[$object->table_element]['label']) && is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) {
+ $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . $object->table_element . "_extrafields as ef on (t.rowid = ef.fk_object)";
+ }
+ // Add table from hooks
+ $parameters = array();
+ $reshook = $hookmanager->executeHooks('printFieldListFrom', $parameters, $object); // Note that $action and $object may have been modified by hook
+ $sql .= $hookmanager->resPrint;
+ if ($object->ismultientitymanaged == 1) {
+ $sql .= " WHERE t.entity IN (" . getEntity($object->element) . ")";
+ } else {
+ $sql .= " WHERE 1 = 1";
+ }
+ $sql .= " AND t.fk_job = " . ((int) $fk_job) . " ";
+
+ foreach ($search as $key => $val) {
+ if (array_key_exists($key, $object->fields)) {
+ if ($key == 'status' && $search[$key] == -1) {
+ continue;
+ }
+ $mode_search = (($object->isInt($object->fields[$key]) || $object->isFloat($object->fields[$key])) ? 1 : 0);
+ if ((strpos($object->fields[$key]['type'], 'integer:') === 0) || (strpos($object->fields[$key]['type'], 'sellist:') === 0) || !empty($object->fields[$key]['arrayofkeyval'])) {
+ if ($search[$key] == '-1' || $search[$key] === '0') {
+ $search[$key] = '';
+ }
+ $mode_search = 2;
+ }
+ if ($search[$key] != '') {
+ $sql .= natural_search($key, $search[$key], (($key == 'status') ? 2 : $mode_search));
+ }
+ } else {
+ if (preg_match('/(_dtstart|_dtend)$/', $key) && $search[$key] != '') {
+ $columnName = preg_replace('/(_dtstart|_dtend)$/', '', $key);
+ if (preg_match('/^(date|timestamp|datetime)/', $object->fields[$columnName]['type'])) {
+ if (preg_match('/_dtstart$/', $key)) {
+ $sql .= " AND t." . $columnName . " >= '" . $db->idate($search[$key]) . "'";
+ }
+ if (preg_match('/_dtend$/', $key)) {
+ $sql .= " AND t." . $columnName . " <= '" . $db->idate($search[$key]) . "'";
+ }
+ }
+ }
+ }
+ }
+ if ($search_all) {
+ $sql .= natural_search(array_keys($fieldstosearchall), $search_all);
+ }
+ //$sql.= dolSqlDateFilter("t.field", $search_xxxday, $search_xxxmonth, $search_xxxyear);
+ // Add where from extra fields
+ include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_list_search_sql.tpl.php';
+ // Add where from hooks
+ $parameters = array();
+ $reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters, $object); // Note that $action and $object may have been modified by hook
+ $sql .= $hookmanager->resPrint;
+
+ /* If a group by is required
+ $sql .= " GROUP BY ";
+ foreach($object->fields as $key => $val) {
+ $sql .= "t.".$key.", ";
+ }
+ // Add fields from extrafields
+ if (!empty($extrafields->attributes[$object->table_element]['label'])) {
+ foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) {
+ $sql .= ($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? "ef.".$key.', ' : '');
+ }
+ }
+ // Add where from hooks
+ $parameters = array();
+ $reshook = $hookmanager->executeHooks('printFieldListGroupBy', $parameters, $object); // Note that $action and $object may have been modified by hook
+ $sql .= $hookmanager->resPrint;
+ $sql = preg_replace('/,\s*$/', '', $sql);
+ */
+
+ $sql .= $db->order($sortfield, $sortorder);
+
+ // Count total nb of records
+ $nbtotalofrecords = '';
+ if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) {
+ $resql = $db->query($sql);
+ $nbtotalofrecords = $db->num_rows($resql);
+ if (($page * $limit) > $nbtotalofrecords) { // if total of record found is smaller than page * limit, goto and load page 0
+ $page = 0;
+ $offset = 0;
+ }
+ }
+ // if total of record found is smaller than limit, no need to do paging and to restart another select with limits set.
+ if (is_numeric($nbtotalofrecords) && ($limit > $nbtotalofrecords || empty($limit))) {
+ $num = $nbtotalofrecords;
+ } else {
+ if ($limit) {
+ $sql .= $db->plimit($limit + 1, $offset);
+ }
+
+ $resql = $db->query($sql);
+ if (!$resql) {
+ dol_print_error($db);
+ exit;
+ }
+
+ $num = $db->num_rows($resql);
+ }
+
+ // Direct jump if only one record found
+ if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $search_all && !$page) {
+ $obj = $db->fetch_object($resql);
+ $id = $obj->rowid;
+ header("Location: " . dol_buildpath('/hrm/position.php', 1) . '?id=' . $id);
+ exit;
+ }
+
+ $arrayofselected = is_array($toselect) ? $toselect : array();
+
+ $param = 'fk_job=' . $fk_job;
+ if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) {
+ $param .= '&contextpage=' . urlencode($contextpage);
+ }
+ if ($limit > 0 && $limit != $conf->liste_limit) {
+ $param .= '&limit=' . urlencode($limit);
+ }
+ foreach ($search as $key => $val) {
+ if (is_array($search[$key]) && count($search[$key])) {
+ foreach ($search[$key] as $skey) {
+ $param .= '&search_' . $key . '[]=' . urlencode($skey);
+ }
+ } else {
+ $param .= '&search_' . $key . '=' . urlencode($search[$key]);
+ }
+ }
+ if ($optioncss != '') {
+ $param .= '&optioncss=' . urlencode($optioncss);
+ }
+ // Add $param from extra fields
+ include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_list_search_param.tpl.php';
+ // Add $param from hooks
+ $parameters = array();
+ $reshook = $hookmanager->executeHooks('printFieldListSearchParam', $parameters, $object); // Note that $action and $object may have been modified by hook
+ $param .= $hookmanager->resPrint;
+
+ // List of mass actions available
+ $arrayofmassactions = array(
+ //'validate'=>img_picto('', 'check', 'class="pictofixedwidth"').$langs->trans("Validate"),
+ //'generate_doc'=>img_picto('', 'pdf', 'class="pictofixedwidth"').$langs->trans("ReGeneratePDF"),
+ //'builddoc'=>img_picto('', 'pdf', 'class="pictofixedwidth"').$langs->trans("PDFMerge"),
+ //'presend'=>img_picto('', 'email', 'class="pictofixedwidth"').$langs->trans("SendByMail"),
+ );
+ if ($permissiontodelete) {
+ $arrayofmassactions['predelete'] = img_picto('', 'delete', 'class="pictofixedwidth"') . $langs->trans("Delete");
+ }
+ if (GETPOST('nomassaction', 'int') || in_array($massaction, array('presend', 'predelete'))) {
+ $arrayofmassactions = array();
+ }
+ $massactionbutton = $form->selectMassAction('', $arrayofmassactions);
+
+ print '' . "\n";
+
+ if (in_array('builddoc', $arrayofmassactions) && ($nbtotalofrecords === '' || $nbtotalofrecords)) {
+ $hidegeneratedfilelistifempty = 1;
+ if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) {
+ $hidegeneratedfilelistifempty = 0;
+ }
+
+ require_once DOL_DOCUMENT_ROOT . '/core/class/html.formfile.class.php';
+ $formfile = new FormFile($db);
+
+ // Show list of available documents
+ $urlsource = $_SERVER['PHP_SELF'] . '?sortfield=' . $sortfield . '&sortorder=' . $sortorder;
+ $urlsource .= str_replace('&', '&', $param);
+
+ $filedir = $diroutputmassaction;
+ $genallowed = $permissiontoread;
+ $delallowed = $permissiontoadd;
+
+ print $formfile->showdocuments('massfilesarea_hrm', '', $filedir, $urlsource, 0, $delallowed, '', 1, 1, 0, 48, 1, $param, $title, '', '', '', null, $hidegeneratedfilelistifempty);
+ }
+}
+
+// Part to create
+if ($action == 'create') {
+ $object = new Position($db);
+ print load_fiche_titre($langs->trans("NewObject", $langs->transnoentitiesnoconv("Position")), '', 'object_' . $object->picto);
+
+ print '';
+
+ //dol_set_focus('input[name="ref"]');
+}
+
+// End of page
+llxFooter();
+$db->close();
diff --git a/htdocs/hrm/position_agenda.php b/htdocs/hrm/position_agenda.php
new file mode 100644
index 00000000000..670ec51304b
--- /dev/null
+++ b/htdocs/hrm/position_agenda.php
@@ -0,0 +1,282 @@
+
+ * Copyright (C) 2021 Gauthier VERDOL
+ * Copyright (C) 2021 Greg Rastklan
+ * Copyright (C) 2021 Jean-Pascal BOUDET
+ * Copyright (C) 2021 Grégory BLEMAND
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see .
+ */
+
+/**
+ * \file position_agenda.php
+ * \ingroup hrm
+ * \brief Tab of events on Position
+ */
+
+//if (! defined('NOREQUIREDB')) define('NOREQUIREDB', '1'); // Do not create database handler $db
+//if (! defined('NOREQUIREUSER')) define('NOREQUIREUSER', '1'); // Do not load object $user
+//if (! defined('NOREQUIRESOC')) define('NOREQUIRESOC', '1'); // Do not load object $mysoc
+//if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN', '1'); // Do not load object $langs
+//if (! defined('NOSCANGETFORINJECTION')) define('NOSCANGETFORINJECTION', '1'); // Do not check injection attack on GET parameters
+//if (! defined('NOSCANPOSTFORINJECTION')) define('NOSCANPOSTFORINJECTION', '1'); // Do not check injection attack on POST parameters
+//if (! defined('NOCSRFCHECK')) define('NOCSRFCHECK', '1'); // Do not check CSRF attack (test on referer + on token if option MAIN_SECURITY_CSRF_WITH_TOKEN is on).
+//if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1'); // Do not roll the Anti CSRF token (used if MAIN_SECURITY_CSRF_WITH_TOKEN is on)
+//if (! defined('NOSTYLECHECK')) define('NOSTYLECHECK', '1'); // Do not check style html tag into posted data
+//if (! defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1'); // If there is no need to load and show top and left menu
+//if (! defined('NOREQUIREHTML')) define('NOREQUIREHTML', '1'); // If we don't need to load the html.form.class.php
+//if (! defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); // Do not load ajax.lib.php library
+//if (! defined("NOLOGIN")) define("NOLOGIN", '1'); // If this page is public (can be called outside logged session). This include the NOIPCHECK too.
+//if (! defined('NOIPCHECK')) define('NOIPCHECK', '1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip
+//if (! defined("MAIN_LANG_DEFAULT")) define('MAIN_LANG_DEFAULT', 'auto'); // Force lang to a particular value
+//if (! defined("MAIN_AUTHENTICATION_MODE")) define('MAIN_AUTHENTICATION_MODE', 'aloginmodule'); // Force authentication handler
+//if (! defined("NOREDIRECTBYMAINTOLOGIN")) define('NOREDIRECTBYMAINTOLOGIN', 1); // The main.inc.php does not make a redirect if not logged, instead show simple error message
+//if (! defined("FORCECSP")) define('FORCECSP', 'none'); // Disable all Content Security Policies
+//if (! defined('CSRFCHECK_WITH_TOKEN')) define('CSRFCHECK_WITH_TOKEN', '1'); // Force use of CSRF protection with tokens even for GET
+//if (! defined('NOBROWSERNOTIF')) define('NOBROWSERNOTIF', '1'); // Disable browser notification
+
+// Load Dolibarr environment
+$res = 0;
+// Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined)
+if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) {
+ $res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php";
+}
+// Try main.inc.php into web root detected using web root calculated from SCRIPT_FILENAME
+$tmp = empty($_SERVER['SCRIPT_FILENAME']) ? '' : $_SERVER['SCRIPT_FILENAME']; $tmp2 = realpath(__FILE__); $i = strlen($tmp) - 1; $j = strlen($tmp2) - 1;
+while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) {
+ $i--; $j--;
+}
+if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) {
+ $res = @include substr($tmp, 0, ($i + 1))."/main.inc.php";
+}
+if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) {
+ $res = @include dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php";
+}
+// Try main.inc.php using relative path
+if (!$res && file_exists("../main.inc.php")) {
+ $res = @include "../main.inc.php";
+}
+if (!$res && file_exists("../../main.inc.php")) {
+ $res = @include "../../main.inc.php";
+}
+if (!$res && file_exists("../../../main.inc.php")) {
+ $res = @include "../../../main.inc.php";
+}
+if (!$res) {
+ die("Include of main fails");
+}
+
+require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
+require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
+require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
+require_once DOL_DOCUMENT_ROOT.'/hrm/class/position.class.php';
+require_once DOL_DOCUMENT_ROOT.'/hrm/lib/hrm_position.lib.php';
+require_once DOL_DOCUMENT_ROOT . '/hrm/class/job.class.php';
+
+
+// Load translation files required by the page
+$langs->loadLangs(array("hrm", "other"));
+
+// Get parameters
+$id = GETPOST('id', 'int');
+$ref = GETPOST('ref', 'alpha');
+$action = GETPOST('action', 'aZ09');
+$cancel = GETPOST('cancel', 'aZ09');
+$backtopage = GETPOST('backtopage', 'alpha');
+
+if (GETPOST('actioncode', 'array')) {
+ $actioncode = GETPOST('actioncode', 'array', 3);
+ if (!count($actioncode)) {
+ $actioncode = '0';
+ }
+} else {
+ $actioncode = GETPOST("actioncode", "alpha", 3) ? GETPOST("actioncode", "alpha", 3) : (GETPOST("actioncode") == '0' ? '0' : (empty($conf->global->AGENDA_DEFAULT_FILTER_TYPE_FOR_OBJECT) ? '' : $conf->global->AGENDA_DEFAULT_FILTER_TYPE_FOR_OBJECT));
+}
+$search_agenda_label = GETPOST('search_agenda_label');
+
+$limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : $conf->liste_limit;
+$sortfield = GETPOST("sortfield", 'alpha');
+$sortorder = GETPOST("sortorder", 'alpha');
+$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
+if (empty($page) || $page == -1) {
+ $page = 0;
+} // If $page is not defined, or '' or -1
+$offset = $limit * $page;
+$pageprev = $page - 1;
+$pagenext = $page + 1;
+if (!$sortfield) {
+ $sortfield = 'a.datep,a.id';
+}
+if (!$sortorder) {
+ $sortorder = 'DESC,DESC';
+}
+
+// Initialize technical objects
+$object = new Position($db);
+$extrafields = new ExtraFields($db);
+$diroutputmassaction = $conf->hrm->dir_output.'/temp/massgeneration/'.$user->id;
+$hookmanager->initHooks(array('positionagenda', 'globalcard')); // Note that conf->hooks_modules contains array
+// Fetch optionals attributes and labels
+$extrafields->fetch_name_optionals_label($object->table_element);
+
+// Load object
+include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once // Must be include, not include_once. Include fetch and fetch_thirdparty but not fetch_optionals
+if ($id > 0 || !empty($ref)) {
+ $upload_dir = $conf->hrm->multidir_output[$object->entity]."/".$object->id;
+}
+
+$permissiontoread = $user->rights->hrm->all->read;
+$permissiontoadd = $user->rights->hrm->all->write; // Used by the include of actions_addupdatedelete.inc.php
+
+// Security check (enable the most restrictive one)
+//if ($user->socid > 0) accessforbidden();
+//if ($user->socid > 0) $socid = $user->socid;
+//$isdraft = (($object->status == $object::STATUS_DRAFT) ? 1 : 0);
+//restrictedArea($user, $object->element, $object->id, $object->table_element, '', 'fk_soc', 'rowid', $isdraft);
+if (empty($conf->hrm->enabled)) accessforbidden();
+if (!$permissiontoread) accessforbidden();
+
+
+/*
+ * Actions
+ */
+
+$parameters = array('id'=>$id);
+$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
+if ($reshook < 0) {
+ setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
+}
+
+if (empty($reshook)) {
+ // Cancel
+ if (GETPOST('cancel', 'alpha') && !empty($backtopage)) {
+ header("Location: ".$backtopage);
+ exit;
+ }
+
+ // Purge search criteria
+ if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // All tests are required to be compatible with all browsers
+ $actioncode = '';
+ $search_agenda_label = '';
+ }
+}
+
+
+
+/*
+ * View
+ */
+
+$form = new Form($db);
+
+if ($object->id > 0) {
+ $title = $langs->trans("Agenda");
+ //if (! empty($conf->global->MAIN_HTML_TITLE) && preg_match('/thirdpartynameonly/',$conf->global->MAIN_HTML_TITLE) && $object->name) $title=$object->name." - ".$title;
+ $help_url = 'EN:Module_Agenda_En';
+ llxHeader('', $title, $help_url);
+
+ if (!empty($conf->notification->enabled)) {
+ $langs->load("mails");
+ }
+ $head = PositionCardPrepareHead($object);
+
+
+ print dol_get_fiche_head($head, 'agenda', $langs->trans("Agenda"), -1, $object->picto);
+
+ // Object card
+ // ------------------------------------------------------------
+ $linkback = ''.$langs->trans("BackToList").'';
+
+ $morehtmlref = '
' . "\n";
+
+ // Common attributes
+ //$keyforbreak='fieldkeytoswitchonsecondcolumn'; // We change column just before this field
+ //unset($object->fields['fk_project']); // Hide field already shown in banner
+ //unset($object->fields['fk_soc']); // Hide field already shown in banner
+ $object->fields['fk_user']['visible']=0; // Already in banner
+ $object->fields['fk_job']['visible']=0; // Already in banner
+ include DOL_DOCUMENT_ROOT . '/core/tpl/commonfields_view.tpl.php';
+
+ // Other attributes. Fields from hook formObjectOptions and Extrafields.
+ include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php';
+
+ print '