job.class.php 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084
  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/job.class.php
  23. * \ingroup hrm
  24. * \brief This file is a CRUD class file for Job (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 Job
  32. */
  33. class Job 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 = 'job';
  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_job';
  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 job. Must be the part after the 'object_' into object_job.png
  58. */
  59. public $picto = 'technic';
  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. '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"),
  95. 'description' => array('type'=>'text', 'label'=>'Description', 'enabled'=>'1', 'position'=>21, 'notnull'=>0, 'visible'=>1,),
  96. 'date_creation' => array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>'1', 'position'=>500, 'notnull'=>1, 'visible'=>2,),
  97. 'tms' => array('type'=>'timestamp', 'label'=>'DateModification', 'enabled'=>'1', 'position'=>501, 'notnull'=>0, 'visible'=>2,),
  98. 'deplacement' => array('type'=>'select', 'required'=> 1,'label'=> 'NeedBusinessTravels', 'enabled'=> 1, 'position'=> 90, 'notnull'=> 1, 'visible'=> 1, 'arrayofkeyval'=> array(0 =>"No", 1=>"Yes"), 'default'=>0),
  99. 'note_public' => array('type'=>'html', 'label'=>'NotePublic', 'enabled'=>'1', 'position'=>70, 'notnull'=>0, 'visible'=>0,),
  100. 'note_private' => array('type'=>'html', 'label'=>'NotePrivate', 'enabled'=>'1', 'position'=>71, 'notnull'=>0, 'visible'=>0,),
  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. );
  104. public $rowid;
  105. public $ref;
  106. public $description;
  107. public $date_creation;
  108. public $tms;
  109. public $deplacement;
  110. public $note_public;
  111. public $note_private;
  112. public $fk_user_creat;
  113. public $fk_user_modif;
  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_jobline';
  120. // /**
  121. // * @var string Field with ID of parent key if this object has a parent
  122. // */
  123. public $fk_element = 'fk_job';
  124. // /**
  125. // * @var string Name of subtable class that manage subtable lines
  126. // */
  127. // public $class_element_line = 'Jobline';
  128. // /**
  129. // * @var array List of child tables. To test if we can delete object.
  130. // */
  131. protected $childtables = array('hrm_evaluation', 'hrm_job_user');
  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("@SkillRank:hrm/class/skillrank.class.php:fk_object:objecttype='job'");
  138. // /**
  139. // * @var JobLine[] 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 (!isModEnabled('multicompany') && 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->job->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. $resultcreate = $this->createCommon($user, $notrigger);
  189. //$resultvalidate = $this->validate($user, $notrigger);
  190. return $resultcreate;
  191. }
  192. /**
  193. * Clone an object into another one
  194. *
  195. * @param User $user User that creates
  196. * @param int $fromid Id of object to clone
  197. * @return mixed New object created, <0 if KO
  198. */
  199. public function createFromClone(User $user, $fromid)
  200. {
  201. global $langs, $extrafields;
  202. $error = 0;
  203. dol_syslog(__METHOD__, LOG_DEBUG);
  204. $object = new self($this->db);
  205. $this->db->begin();
  206. // Load source object
  207. $result = $object->fetchCommon($fromid);
  208. if ($result > 0 && !empty($object->table_element_line)) {
  209. $object->fetchLines();
  210. }
  211. // get lines so they will be clone
  212. //foreach($this->lines as $line)
  213. // $line->fetch_optionals();
  214. // Reset some properties
  215. unset($object->id);
  216. unset($object->fk_user_creat);
  217. unset($object->import_key);
  218. // Clear fields
  219. if (property_exists($object, 'ref')) {
  220. $object->ref = empty($this->fields['ref']['default']) ? "Copy_Of_".$object->ref : $this->fields['ref']['default'];
  221. }
  222. if (property_exists($object, 'label')) {
  223. $object->label = empty($this->fields['label']['default']) ? $langs->trans("CopyOf")." ".$object->label : $this->fields['label']['default'];
  224. }
  225. if (property_exists($object, 'status')) {
  226. $object->status = self::STATUS_DRAFT;
  227. }
  228. if (property_exists($object, 'date_creation')) {
  229. $object->date_creation = dol_now();
  230. }
  231. if (property_exists($object, 'date_modification')) {
  232. $object->date_modification = null;
  233. }
  234. // ...
  235. // Clear extrafields that are unique
  236. if (is_array($object->array_options) && count($object->array_options) > 0) {
  237. $extrafields->fetch_name_optionals_label($this->table_element);
  238. foreach ($object->array_options as $key => $option) {
  239. $shortkey = preg_replace('/options_/', '', $key);
  240. if (!empty($extrafields->attributes[$this->table_element]['unique'][$shortkey])) {
  241. //var_dump($key); var_dump($clonedObj->array_options[$key]); exit;
  242. unset($object->array_options[$key]);
  243. }
  244. }
  245. }
  246. // Create clone
  247. $object->context['createfromclone'] = 'createfromclone';
  248. $result = $object->createCommon($user);
  249. if ($result < 0) {
  250. $error++;
  251. $this->error = $object->error;
  252. $this->errors = $object->errors;
  253. }
  254. if (!$error) {
  255. // copy internal contacts
  256. if ($this->copy_linked_contact($object, 'internal') < 0) {
  257. $error++;
  258. }
  259. }
  260. if (!$error) {
  261. // copy external contacts if same company
  262. if (property_exists($this, 'fk_soc') && $this->fk_soc == $object->socid) {
  263. if ($this->copy_linked_contact($object, 'external') < 0) {
  264. $error++;
  265. }
  266. }
  267. }
  268. unset($object->context['createfromclone']);
  269. // End
  270. if (!$error) {
  271. $this->db->commit();
  272. return $object;
  273. } else {
  274. $this->db->rollback();
  275. return -1;
  276. }
  277. }
  278. /**
  279. * Load object in memory from the database
  280. *
  281. * @param int $id Id object
  282. * @param string $ref Ref
  283. * @return int <0 if KO, 0 if not found, >0 if OK
  284. */
  285. public function fetch($id, $ref = null)
  286. {
  287. $result = $this->fetchCommon($id, $ref);
  288. if ($result > 0 && !empty($this->table_element_line)) {
  289. $this->fetchLines();
  290. }
  291. return $result;
  292. }
  293. /**
  294. * Load object lines in memory from the database
  295. *
  296. * @return int <0 if KO, 0 if not found, >0 if OK
  297. */
  298. public function fetchLines()
  299. {
  300. $this->lines = array();
  301. $result = $this->fetchLinesCommon();
  302. return $result;
  303. }
  304. /**
  305. * Load list of objects in memory from the database.
  306. *
  307. * @param string $sortorder Sort Order
  308. * @param string $sortfield Sort field
  309. * @param int $limit limit
  310. * @param int $offset Offset
  311. * @param array $filter Filter array. Example array('field'=>'valueforlike', 'customurl'=>...)
  312. * @param string $filtermode Filter mode (AND or OR)
  313. * @return array|int int <0 if KO, array of pages if OK
  314. */
  315. public function fetchAll($sortorder = '', $sortfield = '', $limit = 0, $offset = 0, array $filter = array(), $filtermode = 'AND')
  316. {
  317. global $conf;
  318. dol_syslog(__METHOD__, LOG_DEBUG);
  319. $records = array();
  320. $sql = 'SELECT ';
  321. $sql .= $this->getFieldList('t');
  322. $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t';
  323. if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
  324. $sql .= ' WHERE t.entity IN ('.getEntity($this->element).')';
  325. } else {
  326. $sql .= ' WHERE 1 = 1';
  327. }
  328. // Manage filter
  329. $sqlwhere = array();
  330. if (count($filter) > 0) {
  331. foreach ($filter as $key => $value) {
  332. if ($key == 't.rowid') {
  333. $sqlwhere[] = $key.'='.$value;
  334. } elseif (in_array($this->fields[$key]['type'], array('date', 'datetime', 'timestamp'))) {
  335. $sqlwhere[] = $key.' = \''.$this->db->idate($value).'\'';
  336. } elseif ($key == 'customsql') {
  337. $sqlwhere[] = $value;
  338. } elseif (strpos($value, '%') === false) {
  339. $sqlwhere[] = $key.' IN ('.$this->db->sanitize($this->db->escape($value)).')';
  340. } else {
  341. $sqlwhere[] = $key.' LIKE \'%'.$this->db->escape($value).'%\'';
  342. }
  343. }
  344. }
  345. if (count($sqlwhere) > 0) {
  346. $sql .= " AND (".implode(" ".$filtermode." ", $sqlwhere).")";
  347. }
  348. if (!empty($sortfield)) {
  349. $sql .= $this->db->order($sortfield, $sortorder);
  350. }
  351. if (!empty($limit)) {
  352. $sql .= ' '.$this->db->plimit($limit, $offset);
  353. }
  354. $resql = $this->db->query($sql);
  355. if ($resql) {
  356. $num = $this->db->num_rows($resql);
  357. $i = 0;
  358. while ($i < ($limit ? min($limit, $num) : $num)) {
  359. $obj = $this->db->fetch_object($resql);
  360. $record = new self($this->db);
  361. $record->setVarsFromFetchObj($obj);
  362. $records[$record->id] = $record;
  363. $i++;
  364. }
  365. $this->db->free($resql);
  366. return $records;
  367. } else {
  368. $this->errors[] = 'Error '.$this->db->lasterror();
  369. dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
  370. return -1;
  371. }
  372. }
  373. /**
  374. * Update object into database
  375. *
  376. * @param User $user User that modifies
  377. * @param bool $notrigger false=launch triggers after, true=disable triggers
  378. * @return int <0 if KO, >0 if OK
  379. */
  380. public function update(User $user, $notrigger = false)
  381. {
  382. return $this->updateCommon($user, $notrigger);
  383. }
  384. /**
  385. * Delete object in database
  386. *
  387. * @param User $user User that deletes
  388. * @param bool $notrigger false=launch triggers after, true=disable triggers
  389. * @return int <0 if KO, >0 if OK
  390. */
  391. public function delete(User $user, $notrigger = false)
  392. {
  393. return $this->deleteCommon($user, $notrigger);
  394. //return $this->deleteCommon($user, $notrigger, 1);
  395. }
  396. /**
  397. * Delete a line of object in database
  398. *
  399. * @param User $user User that delete
  400. * @param int $idline Id of line to delete
  401. * @param bool $notrigger false=launch triggers after, true=disable triggers
  402. * @return int >0 if OK, <0 if KO
  403. */
  404. public function deleteLine(User $user, $idline, $notrigger = false)
  405. {
  406. if ($this->status < 0) {
  407. $this->error = 'ErrorDeleteLineNotAllowedByObjectStatus';
  408. return -2;
  409. }
  410. return $this->deleteLineCommon($user, $idline, $notrigger);
  411. }
  412. /**
  413. * Validate object
  414. *
  415. * @param User $user User making status change
  416. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  417. * @return int <=0 if OK, 0=Nothing done, >0 if KO
  418. */
  419. public function validate($user, $notrigger = 0)
  420. {
  421. global $conf, $langs;
  422. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  423. $error = 0;
  424. // Protection
  425. if ($this->status == self::STATUS_VALIDATED) {
  426. dol_syslog(get_class($this)."::validate action abandonned: already validated", LOG_WARNING);
  427. return 0;
  428. }
  429. /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->hrm->job->write))
  430. || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->hrm->job->job_advance->validate))))
  431. {
  432. $this->error='NotEnoughPermissions';
  433. dol_syslog(get_class($this)."::valid ".$this->error, LOG_ERR);
  434. return -1;
  435. }*/
  436. $now = dol_now();
  437. $this->db->begin();
  438. // Define new ref
  439. if (!$error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) { // empty should not happened, but when it occurs, the test save life
  440. $num = $this->getNextNumRef();
  441. } else {
  442. $num = $this->ref;
  443. }
  444. $this->newref = $num;
  445. if (!empty($num)) {
  446. // Validate
  447. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
  448. $sql .= " SET ref = '".$this->db->escape($num)."',";
  449. $sql .= " status = ".self::STATUS_VALIDATED;
  450. if (!empty($this->fields['date_validation'])) {
  451. $sql .= ", date_validation = '".$this->db->idate($now)."'";
  452. }
  453. if (!empty($this->fields['fk_user_valid'])) {
  454. $sql .= ", fk_user_valid = ".((int) $user->id);
  455. }
  456. $sql .= " WHERE rowid = ".((int) $this->id);
  457. dol_syslog(get_class($this)."::validate()", LOG_DEBUG);
  458. $resql = $this->db->query($sql);
  459. if (!$resql) {
  460. dol_print_error($this->db);
  461. $this->error = $this->db->lasterror();
  462. $error++;
  463. }
  464. if (!$error && !$notrigger) {
  465. // Call trigger
  466. $result = $this->call_trigger('JOB_VALIDATE', $user);
  467. if ($result < 0) {
  468. $error++;
  469. }
  470. // End call triggers
  471. }
  472. }
  473. if (!$error) {
  474. $this->oldref = $this->ref;
  475. // Rename directory if dir was a temporary ref
  476. if (preg_match('/^[\(]?PROV/i', $this->ref)) {
  477. // Now we rename also files into index
  478. $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)."'";
  479. $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'job/".$this->db->escape($this->ref)."' and entity = ".$conf->entity;
  480. $resql = $this->db->query($sql);
  481. if (!$resql) {
  482. $error++; $this->error = $this->db->lasterror();
  483. }
  484. // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments
  485. $oldref = dol_sanitizeFileName($this->ref);
  486. $newref = dol_sanitizeFileName($num);
  487. $dirsource = $conf->hrm->dir_output.'/job/'.$oldref;
  488. $dirdest = $conf->hrm->dir_output.'/job/'.$newref;
  489. if (!$error && file_exists($dirsource)) {
  490. dol_syslog(get_class($this)."::validate() rename dir ".$dirsource." into ".$dirdest);
  491. if (@rename($dirsource, $dirdest)) {
  492. dol_syslog("Rename ok");
  493. // Rename docs starting with $oldref with $newref
  494. $listoffiles = dol_dir_list($conf->hrm->dir_output.'/job/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/'));
  495. foreach ($listoffiles as $fileentry) {
  496. $dirsource = $fileentry['name'];
  497. $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource);
  498. $dirsource = $fileentry['path'].'/'.$dirsource;
  499. $dirdest = $fileentry['path'].'/'.$dirdest;
  500. @rename($dirsource, $dirdest);
  501. }
  502. }
  503. }
  504. }
  505. }
  506. // Set new ref and current status
  507. if (!$error) {
  508. $this->ref = $num;
  509. $this->status = self::STATUS_VALIDATED;
  510. }
  511. if (!$error) {
  512. $this->db->commit();
  513. return 1;
  514. } else {
  515. $this->db->rollback();
  516. return -1;
  517. }
  518. }
  519. /**
  520. * Get the last occupied position for a user
  521. *
  522. * @param int $fk_user Id of user we need to get last job
  523. * @return Position|string Last occupied position
  524. */
  525. public function getLastJobForUser($fk_user)
  526. {
  527. $Tab = $this->getForUser($fk_user);
  528. if (empty($Tab)) return '';
  529. $lastpos = array_shift($Tab);
  530. return $lastpos;
  531. }
  532. /**
  533. * Get array of occupied positions for a user
  534. *
  535. * @param int $userid Id of user we need to get job list
  536. * @return Position[] Array of occupied positions
  537. */
  538. public function getForUser($userid)
  539. {
  540. global $db;
  541. $TReturn = array();
  542. $position = new Position($db);
  543. $TPosition = $position->getForUser($userid);
  544. foreach ($TPosition as $UPosition) {
  545. $TReturn[$UPosition->Job->rowid] = $UPosition->Job->ref;
  546. }
  547. return $TReturn;
  548. }
  549. /**
  550. * Set draft status
  551. *
  552. * @param User $user Object user that modify
  553. * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers
  554. * @return int <0 if KO, >0 if OK
  555. */
  556. public function setDraft($user, $notrigger = 0)
  557. {
  558. // Protection
  559. if ($this->status <= self::STATUS_DRAFT) {
  560. return 0;
  561. }
  562. /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->hrm->write))
  563. || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->hrm->hrm_advance->validate))))
  564. {
  565. $this->error='Permission denied';
  566. return -1;
  567. }*/
  568. return $this->setStatusCommon($user, self::STATUS_DRAFT, $notrigger, 'JOB_UNVALIDATE');
  569. }
  570. /**
  571. * Set cancel status
  572. *
  573. * @param User $user Object user that modify
  574. * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers
  575. * @return int <0 if KO, 0=Nothing done, >0 if OK
  576. */
  577. public function cancel($user, $notrigger = 0)
  578. {
  579. // Protection
  580. if ($this->status != self::STATUS_VALIDATED) {
  581. return 0;
  582. }
  583. /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->hrm->write))
  584. || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->hrm->hrm_advance->validate))))
  585. {
  586. $this->error='Permission denied';
  587. return -1;
  588. }*/
  589. return $this->setStatusCommon($user, self::STATUS_CANCELED, $notrigger, 'JOB_CANCEL');
  590. }
  591. /**
  592. * Set back to validated status
  593. *
  594. * @param User $user Object user that modify
  595. * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers
  596. * @return int <0 if KO, 0=Nothing done, >0 if OK
  597. */
  598. public function reopen($user, $notrigger = 0)
  599. {
  600. // Protection
  601. if ($this->status != self::STATUS_CANCELED) {
  602. return 0;
  603. }
  604. /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->hrm->write))
  605. || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->hrm->hrm_advance->validate))))
  606. {
  607. $this->error='Permission denied';
  608. return -1;
  609. }*/
  610. return $this->setStatusCommon($user, self::STATUS_VALIDATED, $notrigger, 'JOB_REOPEN');
  611. }
  612. /**
  613. * Return a link to the object card (with optionaly the picto)
  614. *
  615. * @param int $withpicto Include picto in link (0=No picto, 1=Include picto into link, 2=Only picto)
  616. * @param string $option On what the link point to ('nolink', ...)
  617. * @param int $notooltip 1=Disable tooltip
  618. * @param string $morecss Add more css on link
  619. * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
  620. * @return string String with URL
  621. */
  622. public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $morecss = '', $save_lastsearch_value = -1)
  623. {
  624. global $conf, $langs, $hookmanager;
  625. if (!empty($conf->dol_no_mouse_hover)) {
  626. $notooltip = 1; // Force disable tooltips
  627. }
  628. $result = '';
  629. $label = img_picto('', $this->picto).' <u>'.$langs->trans("Job").'</u>';
  630. if (isset($this->status)) {
  631. $label .= ' '.$this->getLibStatut(5);
  632. }
  633. $label .= '<br>';
  634. $label .= '<b>'.$langs->trans('Label').':</b> '.$this->label;
  635. $url = dol_buildpath('/hrm/job_card.php', 1).'?id='.$this->id;
  636. if ($option != 'nolink') {
  637. // Add param to save lastsearch_values or not
  638. $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
  639. if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
  640. $add_save_lastsearch_values = 1;
  641. }
  642. if ($add_save_lastsearch_values) {
  643. $url .= '&save_lastsearch_values=1';
  644. }
  645. }
  646. $linkclose = '';
  647. if (empty($notooltip)) {
  648. if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  649. $label = $langs->trans("ShowJob");
  650. $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
  651. }
  652. $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"';
  653. $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"';
  654. } else {
  655. $linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
  656. }
  657. if ($option == 'nolink') {
  658. $linkstart = '<span';
  659. } else {
  660. $linkstart = '<a href="'.$url.'"';
  661. }
  662. $linkstart .= $linkclose.'>';
  663. if ($option == 'nolink') {
  664. $linkend = '</span>';
  665. } else {
  666. $linkend = '</a>';
  667. }
  668. $result .= $linkstart;
  669. if (empty($this->showphoto_on_popup)) {
  670. if ($withpicto) {
  671. $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);
  672. }
  673. } else {
  674. if ($withpicto) {
  675. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  676. list($class, $module) = explode('@', $this->picto);
  677. $upload_dir = $conf->$module->multidir_output[$conf->entity]."/$class/".dol_sanitizeFileName($this->label);
  678. $filearray = dol_dir_list($upload_dir, "files");
  679. $filename = $filearray[0]['name'];
  680. if (!empty($filename)) {
  681. $pospoint = strpos($filearray[0]['name'], '.');
  682. $pathtophoto = $class.'/'.$this->label.'/thumbs/'.substr($filename, 0, $pospoint).'_mini'.substr($filename, $pospoint);
  683. if (empty($conf->global->{strtoupper($module.'_'.$class).'_FORMATLISTPHOTOSASUSERS'})) {
  684. $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>';
  685. } else {
  686. $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>';
  687. }
  688. $result .= '</div>';
  689. } else {
  690. $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);
  691. }
  692. }
  693. }
  694. if ($withpicto != 2) {
  695. $result .= $this->label;
  696. }
  697. $result .= $linkend;
  698. //if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : '');
  699. global $action, $hookmanager;
  700. $hookmanager->initHooks(array('jobdao'));
  701. $parameters = array('id'=>$this->id, 'getnomurl' => &$result);
  702. $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  703. if ($reshook > 0) {
  704. $result = $hookmanager->resPrint;
  705. } else {
  706. $result .= $hookmanager->resPrint;
  707. }
  708. return $result;
  709. }
  710. /**
  711. * Return the label of the status
  712. *
  713. * @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
  714. * @return string Label of status
  715. */
  716. public function getLibStatut($mode = 0)
  717. {
  718. return $this->LibStatut($this->status, $mode);
  719. }
  720. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  721. /**
  722. * Return the status
  723. *
  724. * @param int $status Id status
  725. * @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
  726. * @return string Label of status
  727. */
  728. public function LibStatut($status, $mode = 0)
  729. {
  730. // phpcs:enable
  731. if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
  732. global $langs;
  733. //$langs->load("hrm");
  734. $this->labelStatus[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('Draft');
  735. $this->labelStatus[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('Enabled');
  736. $this->labelStatus[self::STATUS_CANCELED] = $langs->transnoentitiesnoconv('Disabled');
  737. $this->labelStatusShort[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('Draft');
  738. $this->labelStatusShort[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('Enabled');
  739. $this->labelStatusShort[self::STATUS_CANCELED] = $langs->transnoentitiesnoconv('Disabled');
  740. }
  741. $statusType = 'status'.$status;
  742. //if ($status == self::STATUS_VALIDATED) $statusType = 'status1';
  743. if ($status == self::STATUS_CANCELED) {
  744. $statusType = 'status6';
  745. }
  746. return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
  747. }
  748. /**
  749. * Load the info information in the object
  750. *
  751. * @param int $id Id of object
  752. * @return void
  753. */
  754. public function info($id)
  755. {
  756. $sql = 'SELECT rowid, date_creation as datec, tms as datem,';
  757. $sql .= ' fk_user_creat, fk_user_modif';
  758. $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t';
  759. $sql .= ' WHERE t.rowid = '.((int) $id);
  760. $result = $this->db->query($sql);
  761. if ($result) {
  762. if ($this->db->num_rows($result)) {
  763. $obj = $this->db->fetch_object($result);
  764. $this->id = $obj->rowid;
  765. $this->user_creation_id = $obj->fk_user_creat;
  766. $this->user_modification_id = $obj->fk_user_modif;
  767. $this->date_creation = $this->db->jdate($obj->datec);
  768. $this->date_modification = empty($obj->datem) ? '' : $this->db->jdate($obj->datem);
  769. }
  770. $this->db->free($result);
  771. } else {
  772. dol_print_error($this->db);
  773. }
  774. }
  775. /**
  776. * Initialise object with example values
  777. * Id must be 0 if object instance is a specimen
  778. *
  779. * @return void
  780. */
  781. public function initAsSpecimen()
  782. {
  783. // Set here init that are not commonf fields
  784. // $this->property1 = ...
  785. // $this->property2 = ...
  786. $this->initAsSpecimenCommon();
  787. }
  788. /**
  789. * Create an array of lines
  790. *
  791. * @return array|int array of lines if OK, <0 if KO
  792. */
  793. public function getLinesArray()
  794. {
  795. $this->lines = array();
  796. $objectline = new JobLine($this->db);
  797. $result = $objectline->fetchAll('ASC', 'position', 0, 0, array('customsql'=>'fk_job = '.$this->id));
  798. if (is_numeric($result)) {
  799. $this->error = $objectline->error;
  800. $this->errors = $objectline->errors;
  801. return $result;
  802. } else {
  803. $this->lines = $result;
  804. return $this->lines;
  805. }
  806. }
  807. /**
  808. * Returns the reference to the following non used object depending on the active numbering module.
  809. *
  810. * @return string Object free reference
  811. */
  812. public function getNextNumRef()
  813. {
  814. global $langs, $conf;
  815. $langs->load("hrm");
  816. if (empty($conf->global->hrm_JOB_ADDON)) {
  817. $conf->global->hrm_JOB_ADDON = 'mod_job_standard';
  818. }
  819. if (!empty($conf->global->hrm_JOB_ADDON)) {
  820. $mybool = false;
  821. $file = $conf->global->hrm_JOB_ADDON.".php";
  822. $classname = $conf->global->hrm_JOB_ADDON;
  823. // Include file with class
  824. $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
  825. foreach ($dirmodels as $reldir) {
  826. $dir = dol_buildpath($reldir."core/modules/hrm/");
  827. // Load file with numbering class (if found)
  828. $mybool |= @include_once $dir.$file;
  829. }
  830. if ($mybool === false) {
  831. dol_print_error('', "Failed to include file ".$file);
  832. return '';
  833. }
  834. if (class_exists($classname)) {
  835. $obj = new $classname();
  836. $numref = $obj->getNextValue($this);
  837. if ($numref != '' && $numref != '-1') {
  838. return $numref;
  839. } else {
  840. $this->error = $obj->error;
  841. //dol_print_error($this->db,get_class($this)."::getNextNumRef ".$obj->error);
  842. return "";
  843. }
  844. } else {
  845. print $langs->trans("Error")." ".$langs->trans("ClassNotFound").' '.$classname;
  846. return "";
  847. }
  848. } else {
  849. print $langs->trans("ErrorNumberingModuleNotSetup", $this->element);
  850. return "";
  851. }
  852. }
  853. /**
  854. * Create a document onto disk according to template module.
  855. *
  856. * @param string $modele Force template to use ('' to not force)
  857. * @param Translate $outputlangs objet lang a utiliser pour traduction
  858. * @param int $hidedetails Hide details of lines
  859. * @param int $hidedesc Hide description
  860. * @param int $hideref Hide ref
  861. * @param null|array $moreparams Array to provide more information
  862. * @return int 0 if KO, 1 if OK
  863. */
  864. public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
  865. {
  866. global $conf, $langs;
  867. $result = 0;
  868. $includedocgeneration = 0;
  869. $langs->load("hrm");
  870. if (!dol_strlen($modele)) {
  871. $modele = 'standard_job';
  872. if (!empty($this->model_pdf)) {
  873. $modele = $this->model_pdf;
  874. } elseif (!empty($conf->global->JOB_ADDON_PDF)) {
  875. $modele = $conf->global->JOB_ADDON_PDF;
  876. }
  877. }
  878. $modelpath = "core/modules/hrm/doc/";
  879. if ($includedocgeneration && !empty($modele)) {
  880. $result = $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
  881. }
  882. return $result;
  883. }
  884. /**
  885. * Action executed by scheduler
  886. * CAN BE A CRON TASK. In such a case, parameters come from the schedule job setup field 'Parameters'
  887. * Use public function doScheduledJob($param1, $param2, ...) to get parameters
  888. *
  889. * @return int 0 if OK, <>0 if KO (this function is used also by cron so only 0 is OK)
  890. */
  891. public function doScheduledJob()
  892. {
  893. global $conf, $langs;
  894. //$conf->global->SYSLOG_FILE = 'DOL_DATA_ROOT/dolibarr_mydedicatedlofile.log';
  895. $error = 0;
  896. $this->output = '';
  897. $this->error = '';
  898. dol_syslog(__METHOD__, LOG_DEBUG);
  899. $now = dol_now();
  900. $this->db->begin();
  901. // ...
  902. $this->db->commit();
  903. return $error;
  904. }
  905. }
  906. require_once DOL_DOCUMENT_ROOT.'/core/class/commonobjectline.class.php';
  907. /**
  908. * Class JobLine. You can also remove this and generate a CRUD class for lines objects.
  909. */
  910. class JobLine extends CommonObjectLine
  911. {
  912. // To complete with content of an object JobLine
  913. // We should have a field rowid, fk_job and position
  914. /**
  915. * @var int Does object support extrafields ? 0=No, 1=Yes
  916. */
  917. public $isextrafieldmanaged = 0;
  918. /**
  919. * Constructor
  920. *
  921. * @param DoliDb $db Database handler
  922. */
  923. public function __construct(DoliDB $db)
  924. {
  925. $this->db = $db;
  926. }
  927. }