booking.class.php 38 KB

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