skilldet.class.php 33 KB

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