group.class.php.back 38 KB

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