skillrank.class.php 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072
  1. <?php
  2. /* Copyright (C) 2017 Laurent Destailleur <eldy@users.sourceforge.net>
  3. * Copyright (C) 2021 Gauthier VERDOL <gauthier.verdol@atm-consulting.fr>
  4. * Copyright (C) 2021 Greg Rastklan <greg.rastklan@atm-consulting.fr>
  5. * Copyright (C) 2021 Jean-Pascal BOUDET <jean-pascal.boudet@atm-consulting.fr>
  6. * Copyright (C) 2021 Grégory BLEMAND <gregory.blemand@atm-consulting.fr>
  7. *
  8. * This program is free software; you can redistribute it and/or modify
  9. * it under the terms of the GNU General Public License as published by
  10. * the Free Software Foundation; either version 3 of the License, or
  11. * (at your option) any later version.
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License
  19. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  20. */
  21. /**
  22. * \file class/skillrank.class.php
  23. * \ingroup hrm
  24. * \brief This file is a CRUD class file for SkillRank (Create/Read/Update/Delete)
  25. */
  26. // Put here all includes required by your class file
  27. require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
  28. require_once DOL_DOCUMENT_ROOT . '/hrm/lib/hrm_skillrank.lib.php';
  29. /**
  30. * Class for SkillRank
  31. */
  32. class SkillRank extends CommonObject
  33. {
  34. /**
  35. * @var string ID of module.
  36. */
  37. public $module = 'hrm';
  38. /**
  39. * @var string ID to identify managed object.
  40. */
  41. public $element = 'skillrank';
  42. /**
  43. * @var string Name of table without prefix where object is stored. This is also the key used for extrafields management.
  44. */
  45. public $table_element = 'hrm_skillrank';
  46. /**
  47. * @var int Does this object support multicompany module ?
  48. * 0=No test on entity, 1=Test with field entity, 'field@table'=Test with link by field@table
  49. */
  50. public $ismultientitymanaged = 0;
  51. /**
  52. * @var int Does object support extrafields ? 0=No, 1=Yes
  53. */
  54. public $isextrafieldmanaged = 0;
  55. /**
  56. * @var string String with name of icon for skillrank. Must be the part after the 'object_' into object_skillrank.png
  57. */
  58. public $picto = 'skillrank@hrm';
  59. const STATUS_DRAFT = 0;
  60. const STATUS_VALIDATED = 1;
  61. const STATUS_CANCELED = 9;
  62. const SKILLRANK_TYPE_JOB = "job";
  63. const SKILLRANK_TYPE_USER = "user";
  64. const SKILLRANK_TYPE_EVALDET = "evaluationdet";
  65. /**
  66. * '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')
  67. * Note: Filter can be a string like "(t.ref:like:'SO-%') or (t.date_creation:<:'20160101') or (t.nature:is:NULL)"
  68. * 'label' the translation key.
  69. * 'picto' is code of a picto to show before value in forms
  70. * 'enabled' is a condition when the field must be managed (Example: 1 or '$conf->global->MY_SETUP_PARAM)
  71. * 'position' is the sort order of field.
  72. * 'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0).
  73. * '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)
  74. * 'noteditable' says if field is not editable (1 or 0)
  75. * '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.
  76. * 'index' if we want an index in database.
  77. * 'foreignkey'=>'tablename.field' if the field is a foreign key (it is recommanded to name the field fk_...).
  78. * 'searchall' is 1 if we want to search in this field when making a search from the quick search button.
  79. * '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).
  80. * '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'
  81. * 'help' is a 'TranslationString' to use to show a tooltip on field. You can also use 'TranslationString:keyfortooltiponlick' for a tooltip on click.
  82. * 'showoncombobox' if value of the field must be visible into the label of the combobox that list record
  83. * '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.
  84. * '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'
  85. * 'autofocusoncreate' to have field having the focus on a create form. Only 1 field should have this property set to 1.
  86. * 'comment' is not used. You can store here any text of your choice. It is not used by application.
  87. *
  88. * Note: To have value dynamic, you can set value to 0 in definition and edit the value on the fly into the constructor.
  89. */
  90. // BEGIN MODULEBUILDER PROPERTIES
  91. /**
  92. * @var array Array with all fields and their property. Do not use it as a static var. It may be modified by constructor.
  93. */
  94. public $fields=array(
  95. 'rowid' => array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>'1', 'position'=>1, 'notnull'=>1, 'visible'=>0, 'noteditable'=>'1', 'index'=>1, 'css'=>'left', 'comment'=>"Id"),
  96. 'fk_skill' => array('type'=>'integer:Skill:hrm/class/skill.class.php:1', 'label'=>'Skill', 'enabled'=>'1', 'position'=>3, 'notnull'=>1, 'visible'=>1, 'index'=>1,),
  97. 'rankorder' => array('type'=>'integer', 'label'=>'Rank', 'enabled'=>'1', 'position'=>4, 'notnull'=>1, 'visible'=>1, 'default' => 0),
  98. 'fk_object' => array('type'=>'integer', 'label'=>'object', 'enabled'=>'1', 'position'=>5, 'notnull'=>1, 'visible'=>0,),
  99. 'date_creation' => array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>'1', 'position'=>500, 'notnull'=>1, 'visible'=>-2,),
  100. 'tms' => array('type'=>'timestamp', 'label'=>'DateModification', 'enabled'=>'1', 'position'=>501, 'notnull'=>0, 'visible'=>-2,),
  101. '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',),
  102. 'fk_user_modif' => array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserModif', 'enabled'=>'1', 'position'=>511, 'notnull'=>-1, 'visible'=>-2,),
  103. 'objecttype' => array('type'=>'varchar(128)', 'label'=>'objecttype', 'enabled'=>'1', 'position'=>6, 'notnull'=>1, 'visible'=>0,),
  104. );
  105. public $rowid;
  106. public $fk_skill;
  107. public $rank;
  108. public $fk_object;
  109. public $date_creation;
  110. public $tms;
  111. public $fk_user_creat;
  112. public $fk_user_modif;
  113. public $objecttype;
  114. // END MODULEBUILDER PROPERTIES
  115. // If this object has a subtable with lines
  116. // /**
  117. // * @var string Name of subtable line
  118. // */
  119. // public $table_element_line = 'hrm_skillrankline';
  120. // /**
  121. // * @var string Field with ID of parent key if this object has a parent
  122. // */
  123. // public $fk_element = 'fk_skillrank';
  124. // /**
  125. // * @var string Name of subtable class that manage subtable lines
  126. // */
  127. // public $class_element_line = 'SkillRankline';
  128. // /**
  129. // * @var array List of child tables. To test if we can delete object.
  130. // */
  131. // protected $childtables = array();
  132. // /**
  133. // * @var array List of child tables. To know object to delete on cascade.
  134. // * If name matches '@ClassNAme:FilePathClass;ParentFkFieldName' it will
  135. // * call method deleteByParentField(parentId, ParentFkFieldName) to fetch and delete child object
  136. // */
  137. // protected $childtablesoncascade = array('hrm_skillrankdet');
  138. // /**
  139. // * @var SkillRankLine[] Array of subtable lines
  140. // */
  141. // public $lines = array();
  142. /**
  143. * Constructor
  144. *
  145. * @param DoliDb $db Database handler
  146. */
  147. public function __construct(DoliDB $db)
  148. {
  149. global $conf, $langs;
  150. $this->db = $db;
  151. if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID) && isset($this->fields['rowid'])) {
  152. $this->fields['rowid']['visible'] = 0;
  153. }
  154. if (empty($conf->multicompany->enabled) && isset($this->fields['entity'])) {
  155. $this->fields['entity']['enabled'] = 0;
  156. }
  157. // Example to show how to set values of fields definition dynamically
  158. /*if ($user->rights->hrm->skillrank->read) {
  159. $this->fields['myfield']['visible'] = 1;
  160. $this->fields['myfield']['noteditable'] = 0;
  161. }*/
  162. // Unset fields that are disabled
  163. foreach ($this->fields as $key => $val) {
  164. if (isset($val['enabled']) && empty($val['enabled'])) {
  165. unset($this->fields[$key]);
  166. }
  167. }
  168. // Translate some data of arrayofkeyval
  169. if (is_object($langs)) {
  170. foreach ($this->fields as $key => $val) {
  171. if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
  172. foreach ($val['arrayofkeyval'] as $key2 => $val2) {
  173. $this->fields[$key]['arrayofkeyval'][$key2] = $langs->trans($val2);
  174. }
  175. }
  176. }
  177. }
  178. }
  179. /**
  180. * Create object into database
  181. *
  182. * @param User $user User that creates
  183. * @param bool $notrigger false=launch triggers after, true=disable triggers
  184. * @return int <0 if KO, Id of created object if OK
  185. */
  186. public function create(User $user, $notrigger = false)
  187. {
  188. global $langs;
  189. $sqlfilter = 'fk_object='.((int) $this->fk_object)." AND objecttype='".$this->db->escape($this->objecttype)."' AND fk_skill = ".((int) $this->fk_skill);
  190. $alreadyLinked = $this->fetchAll('ASC', 'rowid', 0, 0, array('customsql' => $sqlfilter));
  191. if (!empty($alreadyLinked)) {
  192. $this->error = $langs->trans('ErrSkillAlreadyAdded');
  193. return -1;
  194. }
  195. $resultcreate = $this->createCommon($user, $notrigger);
  196. return $resultcreate;
  197. }
  198. /**
  199. * Clone an object into another one
  200. *
  201. * @param User $user User that creates
  202. * @param int $fromid Id of object to clone
  203. * @return mixed New object created, <0 if KO
  204. */
  205. public function createFromClone(User $user, $fromid)
  206. {
  207. global $langs, $extrafields;
  208. $error = 0;
  209. dol_syslog(__METHOD__, LOG_DEBUG);
  210. $object = new self($this->db);
  211. $this->db->begin();
  212. // Load source object
  213. $result = $object->fetchCommon($fromid);
  214. if ($result > 0 && !empty($object->table_element_line)) {
  215. $object->fetchLines();
  216. }
  217. // get lines so they will be clone
  218. //foreach($this->lines as $line)
  219. // $line->fetch_optionals();
  220. // Reset some properties
  221. unset($object->id);
  222. unset($object->fk_user_creat);
  223. unset($object->import_key);
  224. // Clear fields
  225. if (property_exists($object, 'ref')) {
  226. $object->ref = empty($this->fields['ref']['default']) ? "Copy_Of_".$object->ref : $this->fields['ref']['default'];
  227. }
  228. if (property_exists($object, 'label')) {
  229. $object->label = empty($this->fields['label']['default']) ? $langs->trans("CopyOf")." ".$object->label : $this->fields['label']['default'];
  230. }
  231. if (property_exists($object, 'status')) {
  232. $object->status = self::STATUS_DRAFT;
  233. }
  234. if (property_exists($object, 'date_creation')) {
  235. $object->date_creation = dol_now();
  236. }
  237. if (property_exists($object, 'date_modification')) {
  238. $object->date_modification = null;
  239. }
  240. // ...
  241. // Clear extrafields that are unique
  242. if (is_array($object->array_options) && count($object->array_options) > 0) {
  243. $extrafields->fetch_name_optionals_label($this->table_element);
  244. foreach ($object->array_options as $key => $option) {
  245. $shortkey = preg_replace('/options_/', '', $key);
  246. if (!empty($extrafields->attributes[$this->table_element]['unique'][$shortkey])) {
  247. //var_dump($key); var_dump($clonedObj->array_options[$key]); exit;
  248. unset($object->array_options[$key]);
  249. }
  250. }
  251. }
  252. // Create clone
  253. $object->context['createfromclone'] = 'createfromclone';
  254. $result = $object->createCommon($user);
  255. if ($result < 0) {
  256. $error++;
  257. $this->error = $object->error;
  258. $this->errors = $object->errors;
  259. }
  260. if (!$error) {
  261. // copy internal contacts
  262. if ($this->copy_linked_contact($object, 'internal') < 0) {
  263. $error++;
  264. }
  265. }
  266. if (!$error) {
  267. // copy external contacts if same company
  268. if (property_exists($this, 'fk_soc') && $this->fk_soc == $object->socid) {
  269. if ($this->copy_linked_contact($object, 'external') < 0) {
  270. $error++;
  271. }
  272. }
  273. }
  274. unset($object->context['createfromclone']);
  275. // End
  276. if (!$error) {
  277. $this->db->commit();
  278. return $object;
  279. } else {
  280. $this->db->rollback();
  281. return -1;
  282. }
  283. }
  284. /**
  285. * Load object in memory from the database
  286. *
  287. * @param int $id Id object
  288. * @param string $ref Ref
  289. * @return int <0 if KO, 0 if not found, >0 if OK
  290. */
  291. public function fetch($id, $ref = null)
  292. {
  293. $result = $this->fetchCommon($id, $ref);
  294. if ($result > 0 && !empty($this->table_element_line)) {
  295. $this->fetchLines();
  296. }
  297. return $result;
  298. }
  299. /**
  300. * Load object lines in memory from the database
  301. *
  302. * @return int <0 if KO, 0 if not found, >0 if OK
  303. */
  304. public function fetchLines()
  305. {
  306. $this->lines = array();
  307. $result = $this->fetchLinesCommon();
  308. return $result;
  309. }
  310. /**
  311. * Clone skillrank Object linked to job with user id
  312. * The skillrank table is a join table that is marked for multiple objects
  313. *
  314. * @param SkillRank $currentSkill line of evaluation (skill) we need to clone and add to user skills list
  315. * @param int $fk_user id of user linked to skillrank
  316. * @return int > 0 if ok, < 0 if ko
  317. */
  318. public function cloneFromCurrentSkill($currentSkill, $fk_user)
  319. {
  320. global $user;
  321. $this->fk_skill = $currentSkill->fk_skill;
  322. $this->rankorder = $currentSkill->rankorder;
  323. $this->fk_object = $fk_user;
  324. $this->date_creation = dol_now();
  325. $this->fk_user_creat = $user->id;
  326. $this->fk_user_modif = $user->id;
  327. $this->objecttype = self::SKILLRANK_TYPE_USER;
  328. $result = $this->create($user);
  329. return $result;
  330. }
  331. /**
  332. * Load list of objects in memory from the database.
  333. *
  334. * @param string $sortorder Sort Order
  335. * @param string $sortfield Sort field
  336. * @param int $limit limit
  337. * @param int $offset Offset
  338. * @param array $filter Filter array. Example array('field'=>'valueforlike', 'customurl'=>...)
  339. * @param string $filtermode Filter mode (AND or OR)
  340. * @return array|int int <0 if KO, array of pages if OK
  341. */
  342. public function fetchAll($sortorder = '', $sortfield = '', $limit = 0, $offset = 0, array $filter = array(), $filtermode = 'AND')
  343. {
  344. global $conf;
  345. dol_syslog(__METHOD__, LOG_DEBUG);
  346. $records = array();
  347. $sql = 'SELECT ';
  348. $sql .= $this->getFieldList('t');
  349. $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t';
  350. if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
  351. $sql .= ' WHERE t.entity IN ('.getEntity($this->table_element).')';
  352. } else {
  353. $sql .= ' WHERE 1 = 1';
  354. }
  355. // Manage filter
  356. $sqlwhere = array();
  357. if (count($filter) > 0) {
  358. foreach ($filter as $key => $value) {
  359. if ($key == 't.rowid') {
  360. $sqlwhere[] = $key." = ".((int) $value);
  361. } elseif ($key != 'customsql' && in_array($this->fields[$key]['type'], array('date', 'datetime', 'timestamp'))) {
  362. $sqlwhere[] = $key." = '".$this->db->idate($value)."'";
  363. } elseif ($key == 'customsql') {
  364. $sqlwhere[] = $value;
  365. } elseif (strpos($value, '%') === false) {
  366. $sqlwhere[] = $key." IN (".$this->db->sanitize($this->db->escape($value)).")";
  367. } else {
  368. $sqlwhere[] = $key." LIKE '%".$this->db->escape($value)."%'";
  369. }
  370. }
  371. }
  372. if (count($sqlwhere) > 0) {
  373. $sql .= " AND (".implode(" ".$filtermode." ", $sqlwhere).")";
  374. }
  375. if (!empty($sortfield)) {
  376. $sql .= $this->db->order($sortfield, $sortorder);
  377. }
  378. if (!empty($limit)) {
  379. $sql .= ' '.$this->db->plimit($limit, $offset);
  380. }
  381. $resql = $this->db->query($sql);
  382. if ($resql) {
  383. $num = $this->db->num_rows($resql);
  384. $i = 0;
  385. while ($i < ($limit ? min($limit, $num) : $num)) {
  386. $obj = $this->db->fetch_object($resql);
  387. $record = new self($this->db);
  388. $record->setVarsFromFetchObj($obj);
  389. $records[$record->id] = $record;
  390. $i++;
  391. }
  392. $this->db->free($resql);
  393. return $records;
  394. } else {
  395. $this->errors[] = 'Error '.$this->db->lasterror();
  396. dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
  397. return -1;
  398. }
  399. }
  400. /**
  401. * Update object into database
  402. *
  403. * @param User $user User that modifies
  404. * @param bool $notrigger false=launch triggers after, true=disable triggers
  405. * @return int <0 if KO, >0 if OK
  406. */
  407. public function update(User $user, $notrigger = false)
  408. {
  409. return $this->updateCommon($user, $notrigger);
  410. }
  411. /**
  412. * Delete object in database
  413. *
  414. * @param User $user User that deletes
  415. * @param bool $notrigger false=launch triggers after, true=disable triggers
  416. * @return int <0 if KO, >0 if OK
  417. */
  418. public function delete(User $user, $notrigger = false)
  419. {
  420. return $this->deleteCommon($user, $notrigger);
  421. //return $this->deleteCommon($user, $notrigger, 1);
  422. }
  423. /**
  424. * Delete a line of object in database
  425. *
  426. * @param User $user User that delete
  427. * @param int $idline Id of line to delete
  428. * @param bool $notrigger false=launch triggers after, true=disable triggers
  429. * @return int >0 if OK, <0 if KO
  430. */
  431. public function deleteLine(User $user, $idline, $notrigger = false)
  432. {
  433. if ($this->status < 0) {
  434. $this->error = 'ErrorDeleteLineNotAllowedByObjectStatus';
  435. return -2;
  436. }
  437. return $this->deleteLineCommon($user, $idline, $notrigger);
  438. }
  439. /**
  440. * Validate object
  441. *
  442. * @param User $user User making status change
  443. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  444. * @return int <=0 if OK, 0=Nothing done, >0 if KO
  445. */
  446. public function validate($user, $notrigger = 0)
  447. {
  448. global $conf, $langs;
  449. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  450. $error = 0;
  451. // Protection
  452. if ($this->status == self::STATUS_VALIDATED) {
  453. dol_syslog(get_class($this)."::validate action abandonned: already validated", LOG_WARNING);
  454. return 0;
  455. }
  456. /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->hrm->skillrank->write))
  457. || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->hrm->skillrank->skillrank_advance->validate))))
  458. {
  459. $this->error='NotEnoughPermissions';
  460. dol_syslog(get_class($this)."::valid ".$this->error, LOG_ERR);
  461. return -1;
  462. }*/
  463. $now = dol_now();
  464. $this->db->begin();
  465. // Define new ref
  466. if (!$error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) { // empty should not happened, but when it occurs, the test save life
  467. $num = $this->getNextNumRef();
  468. } else {
  469. $num = $this->ref;
  470. }
  471. $this->newref = $num;
  472. if (!empty($num)) {
  473. // Validate
  474. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
  475. $sql .= " SET ref = '".$this->db->escape($num)."',";
  476. $sql .= " status = ".self::STATUS_VALIDATED;
  477. if (!empty($this->fields['date_validation'])) {
  478. $sql .= ", date_validation = '".$this->db->idate($now)."'";
  479. }
  480. if (!empty($this->fields['fk_user_valid'])) {
  481. $sql .= ", fk_user_valid = ".((int) $user->id);
  482. }
  483. $sql .= " WHERE rowid = ".((int) $this->id);
  484. dol_syslog(get_class($this)."::validate()", LOG_DEBUG);
  485. $resql = $this->db->query($sql);
  486. if (!$resql) {
  487. dol_print_error($this->db);
  488. $this->error = $this->db->lasterror();
  489. $error++;
  490. }
  491. if (!$error && !$notrigger) {
  492. // Call trigger
  493. $result = $this->call_trigger('SKILLRANK_VALIDATE', $user);
  494. if ($result < 0) {
  495. $error++;
  496. }
  497. // End call triggers
  498. }
  499. }
  500. if (!$error) {
  501. $this->oldref = $this->ref;
  502. // Rename directory if dir was a temporary ref
  503. if (preg_match('/^[\(]?PROV/i', $this->ref)) {
  504. // Now we rename also files into index
  505. $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)."'";
  506. $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'skillrank/".$this->db->escape($this->ref)."' and entity = ".((int) $conf->entity);
  507. $resql = $this->db->query($sql);
  508. if (!$resql) {
  509. $error++; $this->error = $this->db->lasterror();
  510. }
  511. // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments
  512. $oldref = dol_sanitizeFileName($this->ref);
  513. $newref = dol_sanitizeFileName($num);
  514. $dirsource = $conf->hrm->dir_output.'/skillrank/'.$oldref;
  515. $dirdest = $conf->hrm->dir_output.'/skillrank/'.$newref;
  516. if (!$error && file_exists($dirsource)) {
  517. dol_syslog(get_class($this)."::validate() rename dir ".$dirsource." into ".$dirdest);
  518. if (@rename($dirsource, $dirdest)) {
  519. dol_syslog("Rename ok");
  520. // Rename docs starting with $oldref with $newref
  521. $listoffiles = dol_dir_list($conf->hrm->dir_output.'/skillrank/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/'));
  522. foreach ($listoffiles as $fileentry) {
  523. $dirsource = $fileentry['name'];
  524. $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource);
  525. $dirsource = $fileentry['path'].'/'.$dirsource;
  526. $dirdest = $fileentry['path'].'/'.$dirdest;
  527. @rename($dirsource, $dirdest);
  528. }
  529. }
  530. }
  531. }
  532. }
  533. // Set new ref and current status
  534. if (!$error) {
  535. $this->ref = $num;
  536. $this->status = self::STATUS_VALIDATED;
  537. }
  538. if (!$error) {
  539. $this->db->commit();
  540. return 1;
  541. } else {
  542. $this->db->rollback();
  543. return -1;
  544. }
  545. }
  546. /**
  547. * Set draft status
  548. *
  549. * @param User $user Object user that modify
  550. * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers
  551. * @return int <0 if KO, >0 if OK
  552. */
  553. public function setDraft($user, $notrigger = 0)
  554. {
  555. // Protection
  556. if ($this->status <= self::STATUS_DRAFT) {
  557. return 0;
  558. }
  559. /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->hrm->write))
  560. || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->hrm->hrm_advance->validate))))
  561. {
  562. $this->error='Permission denied';
  563. return -1;
  564. }*/
  565. return $this->setStatusCommon($user, self::STATUS_DRAFT, $notrigger, 'SKILLRANK_UNVALIDATE');
  566. }
  567. /**
  568. * Set cancel status
  569. *
  570. * @param User $user Object user that modify
  571. * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers
  572. * @return int <0 if KO, 0=Nothing done, >0 if OK
  573. */
  574. public function cancel($user, $notrigger = 0)
  575. {
  576. // Protection
  577. if ($this->status != self::STATUS_VALIDATED) {
  578. return 0;
  579. }
  580. /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->hrm->write))
  581. || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->hrm->hrm_advance->validate))))
  582. {
  583. $this->error='Permission denied';
  584. return -1;
  585. }*/
  586. return $this->setStatusCommon($user, self::STATUS_CANCELED, $notrigger, 'SKILLRANK_CANCEL');
  587. }
  588. /**
  589. * Set back to validated status
  590. *
  591. * @param User $user Object user that modify
  592. * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers
  593. * @return int <0 if KO, 0=Nothing done, >0 if OK
  594. */
  595. public function reopen($user, $notrigger = 0)
  596. {
  597. // Protection
  598. if ($this->status != self::STATUS_CANCELED) {
  599. return 0;
  600. }
  601. /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->hrm->write))
  602. || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->hrm->hrm_advance->validate))))
  603. {
  604. $this->error='Permission denied';
  605. return -1;
  606. }*/
  607. return $this->setStatusCommon($user, self::STATUS_VALIDATED, $notrigger, 'SKILLRANK_REOPEN');
  608. }
  609. /**
  610. * Return a link to the object card (with optionaly the picto)
  611. *
  612. * @param int $withpicto Include picto in link (0=No picto, 1=Include picto into link, 2=Only picto)
  613. * @param string $option On what the link point to ('nolink', ...)
  614. * @param int $notooltip 1=Disable tooltip
  615. * @param string $morecss Add more css on link
  616. * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
  617. * @return string String with URL
  618. */
  619. public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $morecss = '', $save_lastsearch_value = -1)
  620. {
  621. global $conf, $langs, $hookmanager;
  622. if (!empty($conf->dol_no_mouse_hover)) {
  623. $notooltip = 1; // Force disable tooltips
  624. }
  625. $result = '';
  626. $label = img_picto('', $this->picto).' <u>'.$langs->trans("SkillRank").'</u>';
  627. if (isset($this->status)) {
  628. $label .= ' '.$this->getLibStatut(5);
  629. }
  630. $label .= '<br>';
  631. $label .= '<b>'.$langs->trans('Ref').':</b> '.$this->ref;
  632. $url = dol_buildpath('/hrm/skillrank_card.php', 1).'?id='.$this->id;
  633. if ($option != 'nolink') {
  634. // Add param to save lastsearch_values or not
  635. $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
  636. if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
  637. $add_save_lastsearch_values = 1;
  638. }
  639. if ($add_save_lastsearch_values) {
  640. $url .= '&save_lastsearch_values=1';
  641. }
  642. }
  643. $linkclose = '';
  644. if (empty($notooltip)) {
  645. if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  646. $label = $langs->trans("ShowSkillRank");
  647. $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
  648. }
  649. $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"';
  650. $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"';
  651. } else {
  652. $linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
  653. }
  654. if ($option == 'nolink') {
  655. $linkstart = '<span';
  656. } else {
  657. $linkstart = '<a href="'.$url.'"';
  658. }
  659. $linkstart .= $linkclose.'>';
  660. if ($option == 'nolink') {
  661. $linkend = '</span>';
  662. } else {
  663. $linkend = '</a>';
  664. }
  665. $result .= $linkstart;
  666. if (empty($this->showphoto_on_popup)) {
  667. if ($withpicto) {
  668. $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);
  669. }
  670. } else {
  671. if ($withpicto) {
  672. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  673. list($class, $module) = explode('@', $this->picto);
  674. $upload_dir = $conf->$module->multidir_output[$conf->entity]."/$class/".dol_sanitizeFileName($this->ref);
  675. $filearray = dol_dir_list($upload_dir, "files");
  676. $filename = $filearray[0]['name'];
  677. if (!empty($filename)) {
  678. $pospoint = strpos($filearray[0]['name'], '.');
  679. $pathtophoto = $class.'/'.$this->ref.'/thumbs/'.substr($filename, 0, $pospoint).'_mini'.substr($filename, $pospoint);
  680. if (empty($conf->global->{strtoupper($module.'_'.$class).'_FORMATLISTPHOTOSASUSERS'})) {
  681. $result .= '<div class="floatleft inline-block valignmiddle divphotoref"><div class="photoref"><img class="photo'.$module.'" alt="No photo" border="0" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$module.'&entity='.$conf->entity.'&file='.urlencode($pathtophoto).'"></div></div>';
  682. } else {
  683. $result .= '<div class="floatleft inline-block valignmiddle divphotoref"><img class="photouserphoto userphoto" alt="No photo" border="0" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$module.'&entity='.$conf->entity.'&file='.urlencode($pathtophoto).'"></div>';
  684. }
  685. $result .= '</div>';
  686. } else {
  687. $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);
  688. }
  689. }
  690. }
  691. if ($withpicto != 2) {
  692. $result .= $this->ref;
  693. }
  694. $result .= $linkend;
  695. //if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : '');
  696. global $action, $hookmanager;
  697. $hookmanager->initHooks(array('skillrankdao'));
  698. $parameters = array('id'=>$this->id, 'getnomurl' => &$result);
  699. $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  700. if ($reshook > 0) {
  701. $result = $hookmanager->resPrint;
  702. } else {
  703. $result .= $hookmanager->resPrint;
  704. }
  705. return $result;
  706. }
  707. /**
  708. * Return the label of the status
  709. *
  710. * @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
  711. * @return string Label of status
  712. */
  713. public function getLibStatut($mode = 0)
  714. {
  715. return $this->LibStatut($this->status, $mode);
  716. }
  717. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  718. /**
  719. * Return the status
  720. *
  721. * @param int $status Id status
  722. * @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
  723. * @return string Label of status
  724. */
  725. public function LibStatut($status, $mode = 0)
  726. {
  727. // phpcs:enable
  728. if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
  729. global $langs;
  730. //$langs->load("hrm");
  731. $this->labelStatus[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('Draft');
  732. $this->labelStatus[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('Enabled');
  733. $this->labelStatus[self::STATUS_CANCELED] = $langs->transnoentitiesnoconv('Disabled');
  734. $this->labelStatusShort[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('Draft');
  735. $this->labelStatusShort[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('Enabled');
  736. $this->labelStatusShort[self::STATUS_CANCELED] = $langs->transnoentitiesnoconv('Disabled');
  737. }
  738. $statusType = 'status'.$status;
  739. //if ($status == self::STATUS_VALIDATED) $statusType = 'status1';
  740. if ($status == self::STATUS_CANCELED) {
  741. $statusType = 'status6';
  742. }
  743. return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
  744. }
  745. /**
  746. * Load the info information in the object
  747. *
  748. * @param int $id Id of object
  749. * @return void
  750. */
  751. public function info($id)
  752. {
  753. $sql = 'SELECT rowid, date_creation as datec, tms as datem,';
  754. $sql .= ' fk_user_creat, fk_user_modif';
  755. $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t';
  756. $sql .= ' WHERE t.rowid = '.((int) $id);
  757. $result = $this->db->query($sql);
  758. if ($result) {
  759. if ($this->db->num_rows($result)) {
  760. $obj = $this->db->fetch_object($result);
  761. $this->id = $obj->rowid;
  762. $this->user_creation_id = $obj->fk_user_creat;
  763. $this->user_modification_id = $obj->fk_user_modif;
  764. $this->date_creation = $this->db->jdate($obj->datec);
  765. $this->date_modification = empty($obj->datem) ? '' : $this->db->jdate($obj->datem);
  766. }
  767. $this->db->free($result);
  768. } else {
  769. dol_print_error($this->db);
  770. }
  771. }
  772. /**
  773. * Initialise object with example values
  774. * Id must be 0 if object instance is a specimen
  775. *
  776. * @return void
  777. */
  778. public function initAsSpecimen()
  779. {
  780. // Set here init that are not commonf fields
  781. // $this->property1 = ...
  782. // $this->property2 = ...
  783. $this->initAsSpecimenCommon();
  784. }
  785. /**
  786. * Create an array of lines
  787. *
  788. * @return array|int array of lines if OK, <0 if KO
  789. */
  790. public function getLinesArray()
  791. {
  792. $this->lines = array();
  793. /*
  794. $objectline = new SkillRankLine($this->db);
  795. $result = $objectline->fetchAll('ASC', 'position', 0, 0, array('customsql'=>'fk_skillrank = '.((int) $this->id)));
  796. if (is_numeric($result)) {
  797. $this->error = $this->error;
  798. $this->errors = $this->errors;
  799. return $result;
  800. } else {
  801. $this->lines = $result;
  802. return $this->lines;
  803. }
  804. */
  805. }
  806. /**
  807. * Returns the reference to the following non used object depending on the active numbering module.
  808. *
  809. * @return string Object free reference
  810. */
  811. public function getNextNumRef()
  812. {
  813. global $langs, $conf;
  814. $langs->load("hrm");
  815. if (empty($conf->global->hrm_SKILLRANK_ADDON)) {
  816. $conf->global->hrm_SKILLRANK_ADDON = 'mod_skillrank_standard';
  817. }
  818. if (!empty($conf->global->hrm_SKILLRANK_ADDON)) {
  819. $mybool = false;
  820. $file = $conf->global->hrm_SKILLRANK_ADDON.".php";
  821. $classname = $conf->global->hrm_SKILLRANK_ADDON;
  822. // Include file with class
  823. $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
  824. foreach ($dirmodels as $reldir) {
  825. $dir = dol_buildpath($reldir."core/modules/hrm/");
  826. // Load file with numbering class (if found)
  827. $mybool |= @include_once $dir.$file;
  828. }
  829. if ($mybool === false) {
  830. dol_print_error('', "Failed to include file ".$file);
  831. return '';
  832. }
  833. if (class_exists($classname)) {
  834. $obj = new $classname();
  835. $numref = $obj->getNextValue($this);
  836. if ($numref != '' && $numref != '-1') {
  837. return $numref;
  838. } else {
  839. $this->error = $obj->error;
  840. //dol_print_error($this->db,get_class($this)."::getNextNumRef ".$obj->error);
  841. return "";
  842. }
  843. } else {
  844. print $langs->trans("Error")." ".$langs->trans("ClassNotFound").' '.$classname;
  845. return "";
  846. }
  847. } else {
  848. print $langs->trans("ErrorNumberingModuleNotSetup", $this->element);
  849. return "";
  850. }
  851. }
  852. /**
  853. * Create a document onto disk according to template module.
  854. *
  855. * @param string $modele Force template to use ('' to not force)
  856. * @param Translate $outputlangs objet lang a utiliser pour traduction
  857. * @param int $hidedetails Hide details of lines
  858. * @param int $hidedesc Hide description
  859. * @param int $hideref Hide ref
  860. * @param null|array $moreparams Array to provide more information
  861. * @return int 0 if KO, 1 if OK
  862. */
  863. public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
  864. {
  865. global $conf, $langs;
  866. $result = 0;
  867. $includedocgeneration = 0;
  868. $langs->load("hrm");
  869. if (!dol_strlen($modele)) {
  870. $modele = 'standard_skillrank';
  871. if (!empty($this->model_pdf)) {
  872. $modele = $this->model_pdf;
  873. } elseif (!empty($conf->global->SKILLRANK_ADDON_PDF)) {
  874. $modele = $conf->global->SKILLRANK_ADDON_PDF;
  875. }
  876. }
  877. $modelpath = "core/modules/hrm/doc/";
  878. if ($includedocgeneration && !empty($modele)) {
  879. $result = $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
  880. }
  881. return $result;
  882. }
  883. /**
  884. * Action executed by scheduler
  885. * CAN BE A CRON TASK. In such a case, parameters come from the schedule job setup field 'Parameters'
  886. * Use public function doScheduledJob($param1, $param2, ...) to get parameters
  887. *
  888. * @return int 0 if OK, <>0 if KO (this function is used also by cron so only 0 is OK)
  889. */
  890. public function doScheduledJob()
  891. {
  892. global $conf, $langs;
  893. //$conf->global->SYSLOG_FILE = 'DOL_DATA_ROOT/dolibarr_mydedicatedlofile.log';
  894. $error = 0;
  895. $this->output = '';
  896. $this->error = '';
  897. dol_syslog(__METHOD__, LOG_DEBUG);
  898. $now = dol_now();
  899. $this->db->begin();
  900. // ...
  901. $this->db->commit();
  902. return $error;
  903. }
  904. /**
  905. * @param array $val
  906. * @param string $key
  907. * @param string $value
  908. * @param string $moreparam
  909. * @param string $keysuffix
  910. * @param string $keyprefix
  911. * @param string $morecss
  912. * @return string
  913. */
  914. // public function showOutputField($val, $key, $value, $moreparam = '', $keysuffix = '', $keyprefix = '', $morecss = '')
  915. // {
  916. // if ($key == "rank") {
  917. // return displayRankInfos($this);
  918. // } else return parent::showOutputField($val, $key, $value, $moreparam, $keysuffix, $keyprefix, $morecss);
  919. // }
  920. }