toolnaplo.class.php 36 KB

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