workstation.class.php 36 KB

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