documentfollowerprocessuser.class.php.back 37 KB

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