position.class.php 37 KB

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