assetmodel.class.php 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822
  1. <?php
  2. /* Copyright (C) 2017 Laurent Destailleur <eldy@users.sourceforge.net>
  3. * Copyright (C) 2021 Open-Dsi <support@open-dsi.fr>
  4. *
  5. * This program is free software; you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation; either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. /**
  19. * \file class/assetmodel.class.php
  20. * \ingroup asset
  21. * \brief This file is a CRUD class file for AssetModel (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 AssetModel
  29. */
  30. class AssetModel extends CommonObject
  31. {
  32. /**
  33. * @var string ID of module.
  34. */
  35. public $module = 'asset';
  36. /**
  37. * @var string ID to identify managed object.
  38. */
  39. public $element = 'assetmodel';
  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 = 'asset_model';
  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 = 1;
  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 assetmodel. Must be the part after the 'object_' into object_assetmodel.png
  55. */
  56. public $picto = 'asset';
  57. const STATUS_DRAFT = 0;
  58. const STATUS_VALIDATED = 1;
  59. const STATUS_CANCELED = 9;
  60. /**
  61. * 'type' field format ('integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter[:Sortfield]]]', 'sellist:TableName:LabelFieldName[:KeyFieldName[:KeyFieldParent[:Filter[:Sortfield]]]]', 'varchar(x)', 'double(24,8)', 'real', 'price', 'text', 'text:none', 'html', 'date', 'datetime', 'timestamp', 'duration', 'mail', 'phone', 'url', 'password')
  62. * Note: Filter can be a string like "(t.ref:like:'SO-%') or (t.date_creation:<:'20160101') or (t.nature:is:NULL)"
  63. * 'label' the translation key.
  64. * 'picto' is code of a picto to show before value in forms
  65. * 'enabled' is a condition when the field must be managed (Example: 1 or '$conf->global->MY_SETUP_PARAM)
  66. * 'position' is the sort order of field.
  67. * 'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0).
  68. * 'visible' says if field is visible in list (Examples: 0=Not visible, 1=Visible on list and create/update/view forms, 2=Visible on list only, 3=Visible on create/update/view form only (not list), 4=Visible on list and update/view form only (not create). 5=Visible on list and view only (not create/not update). Using a negative value means field is not shown by default on list but can be selected for viewing)
  69. * 'noteditable' says if field is not editable (1 or 0)
  70. * 'default' is a default value for creation (can still be overwrote by the Setup of Default Values if field is editable in creation form). Note: If default is set to '(PROV)' and field is 'ref', the default value will be set to '(PROVid)' where id is rowid when a new record is created.
  71. * 'index' if we want an index in database.
  72. * 'foreignkey'=>'tablename.field' if the field is a foreign key (it is recommanded to name the field fk_...).
  73. * 'searchall' is 1 if we want to search in this field when making a search from the quick search button.
  74. * 'isameasure' must be set to 1 or 2 if field can be used for measure. Field type must be summable like integer or double(24,8). Use 1 in most cases, or 2 if you don't want to see the column total into list (for example for percentage)
  75. * 'css' and 'cssview' and 'csslist' is the CSS style to use on field. 'css' is used in creation and update. 'cssview' is used in view mode. 'csslist' is used for columns in lists. For example: 'css'=>'minwidth300 maxwidth500 widthcentpercentminusx', 'cssview'=>'wordbreak', 'csslist'=>'tdoverflowmax200'
  76. * 'help' is a 'TranslationString' to use to show a tooltip on field. You can also use 'TranslationString:keyfortooltiponlick' for a tooltip on click.
  77. * 'showoncombobox' if value of the field must be visible into the label of the combobox that list record
  78. * 'disabled' is 1 if we want to have the field locked by a 'disabled' attribute. In most cases, this is never set into the definition of $fields into class, but is set dynamically by some part of code.
  79. * 'arrayofkeyval' to set a list of values if type is a list of predefined values. For example: array("0"=>"Draft","1"=>"Active","-1"=>"Cancel"). Note that type can be 'integer' or 'varchar'
  80. * 'autofocusoncreate' to have field having the focus on a create form. Only 1 field should have this property set to 1.
  81. * 'comment' is not used. You can store here any text of your choice. It is not used by application.
  82. * 'validate' is 1 if need to validate with $this->validateField()
  83. * 'copytoclipboard' is 1 or 2 to allow to add a picto to copy value into clipboard (1=picto after label, 2=picto after value)
  84. *
  85. * Note: To have value dynamic, you can set value to 0 in definition and edit the value on the fly into the constructor.
  86. */
  87. /**
  88. * @var array Array with all fields and their property. Do not use it as a static var. It may be modified by constructor.
  89. */
  90. public $fields=array(
  91. 'rowid' => array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>'1', 'position'=>1, 'notnull'=>1, 'visible'=>0, 'noteditable'=>'1', 'index'=>1, 'css'=>'left', 'comment'=>"Id"),
  92. 'ref' => array('type'=>'varchar(128)', 'label'=>'Ref', 'enabled'=>'1', 'position'=>20, 'notnull'=>1, 'visible'=>1, 'index'=>1, 'searchall'=>1, 'showoncombobox'=>'1', 'validate'=>'1'),
  93. 'label' => array('type'=>'varchar(255)', 'label'=>'Label', 'enabled'=>'1', 'position'=>30, 'notnull'=>1, 'visible'=>1, 'searchall'=>1, 'css'=>'minwidth300', 'cssview'=>'wordbreak', 'showoncombobox'=>'2', 'validate'=>'1',),
  94. 'asset_type' => array('type'=>'smallint', 'label'=>'AssetType', 'enabled'=>'1', 'position'=>40, 'notnull'=>1, 'visible'=>1, 'arrayofkeyval'=>array('0'=>'AssetTypeIntangible', '1'=>'AssetTypeTangible', '2'=>'AssetTypeInProgress', '3'=>'AssetTypeFinancial'), 'validate'=>'1',),
  95. 'note_public' => array('type'=>'html', 'label'=>'NotePublic', 'enabled'=>'1', 'position'=>300, 'notnull'=>0, 'visible'=>0, 'validate'=>'1',),
  96. 'note_private' => array('type'=>'html', 'label'=>'NotePrivate', 'enabled'=>'1', 'position'=>301, 'notnull'=>0, 'visible'=>0, 'validate'=>'1',),
  97. 'date_creation' => array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>'1', 'position'=>500, 'notnull'=>1, 'visible'=>-2,),
  98. 'tms' => array('type'=>'timestamp', 'label'=>'DateModification', 'enabled'=>'1', 'position'=>501, 'notnull'=>0, 'visible'=>-2,),
  99. 'fk_user_creat' => array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserAuthor', 'enabled'=>'1', 'position'=>510, 'notnull'=>1, 'visible'=>-2, 'foreignkey'=>'user.rowid',),
  100. 'fk_user_modif' => array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserModif', 'enabled'=>'1', 'position'=>511, 'notnull'=>-1, 'visible'=>-2,),
  101. 'import_key' => array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>'1', 'position'=>1000, 'notnull'=>-1, 'visible'=>-2,),
  102. 'status' => array('type'=>'smallint', 'label'=>'Status', 'enabled'=>'1', 'position'=>1000, 'notnull'=>1, 'default'=>'0', 'visible'=>2, 'index'=>1, 'arrayofkeyval'=>array('0'=>'Draft', '1'=>'Enabled', '9'=>'Disabled'), 'validate'=>'1',),
  103. );
  104. public $rowid;
  105. public $ref;
  106. public $label;
  107. public $asset_type;
  108. public $note_public;
  109. public $note_private;
  110. public $date_creation;
  111. public $tms;
  112. public $fk_user_creat;
  113. public $fk_user_modif;
  114. public $last_main_doc;
  115. public $import_key;
  116. public $model_pdf;
  117. public $status;
  118. public $asset_depreciation_options;
  119. // /**
  120. // * @var string Field with ID of parent key if this object has a parent
  121. // */
  122. // public $fk_element = 'fk_assetmodel';
  123. // /**
  124. // * @var array List of child tables. To test if we can delete object.
  125. // */
  126. // protected $childtables = array();
  127. // /**
  128. // * @var array List of child tables. To know object to delete on cascade.
  129. // * If name matches '@ClassNAme:FilePathClass;ParentFkFieldName' it will
  130. // * call method deleteByParentField(parentId, ParentFkFieldName) to fetch and delete child object
  131. // */
  132. // protected $childtablesoncascade = array('asset_assetmodeldet');
  133. /**
  134. * Constructor
  135. *
  136. * @param DoliDb $db Database handler
  137. */
  138. public function __construct(DoliDB $db)
  139. {
  140. global $conf, $langs;
  141. $this->db = $db;
  142. if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID) && isset($this->fields['rowid'])) {
  143. $this->fields['rowid']['visible'] = 0;
  144. }
  145. if (empty($conf->multicompany->enabled) && isset($this->fields['entity'])) {
  146. $this->fields['entity']['enabled'] = 0;
  147. }
  148. // Unset fields that are disabled
  149. foreach ($this->fields as $key => $val) {
  150. if (isset($val['enabled']) && empty($val['enabled'])) {
  151. unset($this->fields[$key]);
  152. }
  153. }
  154. // Translate some data of arrayofkeyval
  155. if (is_object($langs)) {
  156. foreach ($this->fields as $key => $val) {
  157. if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
  158. foreach ($val['arrayofkeyval'] as $key2 => $val2) {
  159. $this->fields[$key]['arrayofkeyval'][$key2] = $langs->trans($val2);
  160. }
  161. }
  162. }
  163. }
  164. }
  165. /**
  166. * Create object into database
  167. *
  168. * @param User $user User that creates
  169. * @param bool $notrigger false=launch triggers after, true=disable triggers
  170. * @return int <0 if KO, Id of created object if OK
  171. */
  172. public function create(User $user, $notrigger = false)
  173. {
  174. $resultcreate = $this->createCommon($user, $notrigger);
  175. return $resultcreate;
  176. }
  177. /**
  178. * Clone an object into another one
  179. *
  180. * @param User $user User that creates
  181. * @param int $fromid Id of object to clone
  182. * @return mixed New object created, <0 if KO
  183. */
  184. public function createFromClone(User $user, $fromid)
  185. {
  186. global $langs, $extrafields;
  187. $error = 0;
  188. dol_syslog(__METHOD__, LOG_DEBUG);
  189. $object = new self($this->db);
  190. $this->db->begin();
  191. // Load source object
  192. $result = $object->fetchCommon($fromid);
  193. if ($result > 0 && !empty($object->table_element_line)) {
  194. $object->fetchLines();
  195. }
  196. // get lines so they will be clone
  197. //foreach($this->lines as $line)
  198. // $line->fetch_optionals();
  199. // Reset some properties
  200. unset($object->id);
  201. unset($object->fk_user_creat);
  202. unset($object->import_key);
  203. // Clear fields
  204. if (property_exists($object, 'ref')) {
  205. $object->ref = empty($this->fields['ref']['default']) ? "Copy_Of_".$object->ref : $this->fields['ref']['default'];
  206. }
  207. if (property_exists($object, 'label')) {
  208. $object->label = empty($this->fields['label']['default']) ? $langs->trans("CopyOf")." ".$object->label : $this->fields['label']['default'];
  209. }
  210. if (property_exists($object, 'status')) {
  211. $object->status = self::STATUS_DRAFT;
  212. }
  213. if (property_exists($object, 'date_creation')) {
  214. $object->date_creation = dol_now();
  215. }
  216. if (property_exists($object, 'date_modification')) {
  217. $object->date_modification = null;
  218. }
  219. // ...
  220. // Clear extrafields that are unique
  221. if (is_array($object->array_options) && count($object->array_options) > 0) {
  222. $extrafields->fetch_name_optionals_label($this->table_element);
  223. foreach ($object->array_options as $key => $option) {
  224. $shortkey = preg_replace('/options_/', '', $key);
  225. if (!empty($extrafields->attributes[$this->table_element]['unique'][$shortkey])) {
  226. //var_dump($key); var_dump($clonedObj->array_options[$key]); exit;
  227. unset($object->array_options[$key]);
  228. }
  229. }
  230. }
  231. // Create clone
  232. $object->context['createfromclone'] = 'createfromclone';
  233. $result = $object->createCommon($user);
  234. if ($result < 0) {
  235. $error++;
  236. $this->error = $object->error;
  237. $this->errors = $object->errors;
  238. }
  239. if (!$error) {
  240. // copy internal contacts
  241. if ($this->copy_linked_contact($object, 'internal') < 0) {
  242. $error++;
  243. }
  244. }
  245. if (!$error) {
  246. // copy external contacts if same company
  247. if (property_exists($this, 'fk_soc') && $this->fk_soc == $object->socid) {
  248. if ($this->copy_linked_contact($object, 'external') < 0) {
  249. $error++;
  250. }
  251. }
  252. }
  253. unset($object->context['createfromclone']);
  254. // End
  255. if (!$error) {
  256. $this->db->commit();
  257. return $object;
  258. } else {
  259. $this->db->rollback();
  260. return -1;
  261. }
  262. }
  263. /**
  264. * Load object in memory from the database
  265. *
  266. * @param int $id Id object
  267. * @param string $ref Ref
  268. * @return int <0 if KO, 0 if not found, >0 if OK
  269. */
  270. public function fetch($id, $ref = null)
  271. {
  272. $result = $this->fetchCommon($id, $ref);
  273. if ($result > 0 && !empty($this->table_element_line)) {
  274. $this->fetchLines();
  275. }
  276. return $result;
  277. }
  278. /**
  279. * Load object lines in memory from the database
  280. *
  281. * @return int <0 if KO, 0 if not found, >0 if OK
  282. */
  283. public function fetchLines()
  284. {
  285. $this->lines = array();
  286. return 1;
  287. }
  288. /**
  289. * Load list of objects in memory from the database.
  290. *
  291. * @param string $sortorder Sort Order
  292. * @param string $sortfield Sort field
  293. * @param int $limit limit
  294. * @param int $offset Offset
  295. * @param array $filter Filter array. Example array('field'=>'valueforlike', 'customurl'=>...)
  296. * @param string $filtermode Filter mode (AND or OR)
  297. * @return array|int int <0 if KO, array of pages if OK
  298. */
  299. public function fetchAll($sortorder = '', $sortfield = '', $limit = 0, $offset = 0, array $filter = array(), $filtermode = 'AND')
  300. {
  301. global $conf;
  302. dol_syslog(__METHOD__, LOG_DEBUG);
  303. $records = array();
  304. $sql = "SELECT ";
  305. $sql .= $this->getFieldList('t');
  306. $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element." as t";
  307. if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
  308. $sql .= " WHERE t.entity IN (".getEntity($this->table_element).")";
  309. } else {
  310. $sql .= " WHERE 1 = 1";
  311. }
  312. // Manage filter
  313. $sqlwhere = array();
  314. if (count($filter) > 0) {
  315. foreach ($filter as $key => $value) {
  316. if ($key == 't.rowid') {
  317. $sqlwhere[] = $key." = ".((int) $value);
  318. } elseif (in_array($this->fields[$key]['type'], array('date', 'datetime', 'timestamp'))) {
  319. $sqlwhere[] = $key." = '".$this->db->idate($value)."'";
  320. } elseif ($key == 'customsql') {
  321. $sqlwhere[] = $value;
  322. } elseif (strpos($value, '%') === false) {
  323. $sqlwhere[] = $key." IN (".$this->db->sanitize($this->db->escape($value)).")";
  324. } else {
  325. $sqlwhere[] = $key." LIKE '%".$this->db->escape($value)."%'";
  326. }
  327. }
  328. }
  329. if (count($sqlwhere) > 0) {
  330. $sql .= " AND (".implode(" ".$filtermode." ", $sqlwhere).")";
  331. }
  332. if (!empty($sortfield)) {
  333. $sql .= $this->db->order($sortfield, $sortorder);
  334. }
  335. if (!empty($limit)) {
  336. $sql .= $this->db->plimit($limit, $offset);
  337. }
  338. $resql = $this->db->query($sql);
  339. if ($resql) {
  340. $num = $this->db->num_rows($resql);
  341. $i = 0;
  342. while ($i < ($limit ? min($limit, $num) : $num)) {
  343. $obj = $this->db->fetch_object($resql);
  344. $record = new self($this->db);
  345. $record->setVarsFromFetchObj($obj);
  346. $records[$record->id] = $record;
  347. $i++;
  348. }
  349. $this->db->free($resql);
  350. return $records;
  351. } else {
  352. $this->errors[] = 'Error '.$this->db->lasterror();
  353. dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
  354. return -1;
  355. }
  356. }
  357. /**
  358. * Update object into database
  359. *
  360. * @param User $user User that modifies
  361. * @param bool $notrigger false=launch triggers after, true=disable triggers
  362. * @return int <0 if KO, >0 if OK
  363. */
  364. public function update(User $user, $notrigger = false)
  365. {
  366. return $this->updateCommon($user, $notrigger);
  367. }
  368. /**
  369. * Delete object in database
  370. *
  371. * @param User $user User that deletes
  372. * @param bool $notrigger false=launch triggers after, true=disable triggers
  373. * @return int <0 if KO, >0 if OK
  374. */
  375. public function delete(User $user, $notrigger = false)
  376. {
  377. return $this->deleteCommon($user, $notrigger);
  378. //return $this->deleteCommon($user, $notrigger, 1);
  379. }
  380. /**
  381. * Validate object
  382. *
  383. * @param User $user User making status change
  384. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  385. * @return int <=0 if OK, 0=Nothing done, >0 if KO
  386. */
  387. public function validate($user, $notrigger = 0)
  388. {
  389. global $conf, $langs;
  390. $error = 0;
  391. // Protection
  392. if ($this->status == self::STATUS_VALIDATED) {
  393. dol_syslog(get_class($this) . "::validate action abandonned: already validated", LOG_WARNING);
  394. return 0;
  395. }
  396. $now = dol_now();
  397. $this->db->begin();
  398. // Validate
  399. $sql = "UPDATE " . MAIN_DB_PREFIX . $this->table_element;
  400. $sql .= " SET status = " . self::STATUS_VALIDATED;
  401. if (!empty($this->fields['date_validation'])) {
  402. $sql .= ", date_validation = '" . $this->db->idate($now) . "'";
  403. }
  404. if (!empty($this->fields['fk_user_valid'])) {
  405. $sql .= ", fk_user_valid = " . ((int) $user->id);
  406. }
  407. $sql .= " WHERE rowid = " . ((int) $this->id);
  408. dol_syslog(get_class($this) . "::validate()", LOG_DEBUG);
  409. $resql = $this->db->query($sql);
  410. if (!$resql) {
  411. dol_print_error($this->db);
  412. $this->error = $this->db->lasterror();
  413. $error++;
  414. }
  415. if (!$error && !$notrigger) {
  416. // Call trigger
  417. $result = $this->call_trigger('ASSETMODEL_VALIDATE', $user);
  418. if ($result < 0) {
  419. $error++;
  420. }
  421. // End call triggers
  422. }
  423. // Set new ref and current status
  424. if (!$error) {
  425. $this->status = self::STATUS_VALIDATED;
  426. }
  427. if (!$error) {
  428. $this->db->commit();
  429. return 1;
  430. } else {
  431. $this->db->rollback();
  432. return -1;
  433. }
  434. }
  435. /**
  436. * Set draft status
  437. *
  438. * @param User $user Object user that modify
  439. * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers
  440. * @return int <0 if KO, >0 if OK
  441. */
  442. public function setDraft($user, $notrigger = 0)
  443. {
  444. // Protection
  445. if ($this->status <= self::STATUS_DRAFT) {
  446. return 0;
  447. }
  448. return $this->setStatusCommon($user, self::STATUS_DRAFT, $notrigger, 'ASSETMODEL_UNVALIDATE');
  449. }
  450. /**
  451. * Set cancel status
  452. *
  453. * @param User $user Object user that modify
  454. * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers
  455. * @return int <0 if KO, 0=Nothing done, >0 if OK
  456. */
  457. public function cancel($user, $notrigger = 0)
  458. {
  459. // Protection
  460. if ($this->status != self::STATUS_VALIDATED) {
  461. return 0;
  462. }
  463. return $this->setStatusCommon($user, self::STATUS_CANCELED, $notrigger, 'ASSETMODEL_CANCEL');
  464. }
  465. /**
  466. * Set back to validated status
  467. *
  468. * @param User $user Object user that modify
  469. * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers
  470. * @return int <0 if KO, 0=Nothing done, >0 if OK
  471. */
  472. public function reopen($user, $notrigger = 0)
  473. {
  474. // Protection
  475. if ($this->status != self::STATUS_CANCELED) {
  476. return 0;
  477. }
  478. return $this->setStatusCommon($user, self::STATUS_VALIDATED, $notrigger, 'ASSETMODEL_REOPEN');
  479. }
  480. /**
  481. * Return a link to the object card (with optionaly the picto)
  482. *
  483. * @param int $withpicto Include picto in link (0=No picto, 1=Include picto into link, 2=Only picto)
  484. * @param string $option On what the link point to ('nolink', ...)
  485. * @param int $notooltip 1=Disable tooltip
  486. * @param string $morecss Add more css on link
  487. * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
  488. * @return string String with URL
  489. */
  490. public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $morecss = '', $save_lastsearch_value = -1)
  491. {
  492. global $conf, $langs, $hookmanager;
  493. if (!empty($conf->dol_no_mouse_hover)) {
  494. $notooltip = 1; // Force disable tooltips
  495. }
  496. $result = '';
  497. $label = img_picto('', $this->picto).' <u>'.$langs->trans("AssetModel").'</u>';
  498. if (isset($this->status)) {
  499. $label .= ' '.$this->getLibStatut(5);
  500. }
  501. $label .= '<br>';
  502. $label .= '<b>'.$langs->trans('Ref').':</b> '.$this->ref;
  503. $url = dol_buildpath('/asset/model/card.php', 1).'?id='.$this->id;
  504. if ($option != 'nolink') {
  505. // Add param to save lastsearch_values or not
  506. $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
  507. if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
  508. $add_save_lastsearch_values = 1;
  509. }
  510. if ($add_save_lastsearch_values) {
  511. $url .= '&save_lastsearch_values=1';
  512. }
  513. }
  514. $linkclose = '';
  515. if (empty($notooltip)) {
  516. if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  517. $label = $langs->trans("ShowAssetModel");
  518. $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
  519. }
  520. $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"';
  521. $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"';
  522. } else {
  523. $linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
  524. }
  525. if ($option == 'nolink') {
  526. $linkstart = '<span';
  527. } else {
  528. $linkstart = '<a href="'.$url.'"';
  529. }
  530. $linkstart .= $linkclose.'>';
  531. if ($option == 'nolink') {
  532. $linkend = '</span>';
  533. } else {
  534. $linkend = '</a>';
  535. }
  536. $result .= $linkstart;
  537. if (empty($this->showphoto_on_popup)) {
  538. if ($withpicto) {
  539. $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);
  540. }
  541. } else {
  542. if ($withpicto) {
  543. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  544. list($class, $module) = explode('@', $this->picto);
  545. $upload_dir = $conf->$module->multidir_output[$conf->entity]."/$class/".dol_sanitizeFileName($this->ref);
  546. $filearray = dol_dir_list($upload_dir, "files");
  547. $filename = $filearray[0]['name'];
  548. if (!empty($filename)) {
  549. $pospoint = strpos($filearray[0]['name'], '.');
  550. $pathtophoto = $class.'/'.$this->ref.'/thumbs/'.substr($filename, 0, $pospoint).'_mini'.substr($filename, $pospoint);
  551. if (empty($conf->global->{strtoupper($module.'_'.$class).'_FORMATLISTPHOTOSASUSERS'})) {
  552. $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>';
  553. } else {
  554. $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>';
  555. }
  556. $result .= '</div>';
  557. } else {
  558. $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);
  559. }
  560. }
  561. }
  562. if ($withpicto != 2) {
  563. $result .= $this->ref;
  564. }
  565. $result .= $linkend;
  566. //if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : '');
  567. global $action, $hookmanager;
  568. $hookmanager->initHooks(array('assetmodeldao'));
  569. $parameters = array('id'=>$this->id, 'getnomurl'=>$result);
  570. $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  571. if ($reshook > 0) {
  572. $result = $hookmanager->resPrint;
  573. } else {
  574. $result .= $hookmanager->resPrint;
  575. }
  576. return $result;
  577. }
  578. /**
  579. * Return the label of the status
  580. *
  581. * @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
  582. * @return string Label of status
  583. */
  584. public function getLabelStatus($mode = 0)
  585. {
  586. return $this->LibStatut($this->status, $mode);
  587. }
  588. /**
  589. * Return the label of the status
  590. *
  591. * @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
  592. * @return string Label of status
  593. */
  594. public function getLibStatut($mode = 0)
  595. {
  596. return $this->LibStatut($this->status, $mode);
  597. }
  598. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  599. /**
  600. * Return the status
  601. *
  602. * @param int $status Id status
  603. * @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
  604. * @return string Label of status
  605. */
  606. public function LibStatut($status, $mode = 0)
  607. {
  608. // phpcs:enable
  609. if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
  610. global $langs;
  611. //$langs->load("asset@asset");
  612. $this->labelStatus[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('Draft');
  613. $this->labelStatus[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('Enabled');
  614. $this->labelStatus[self::STATUS_CANCELED] = $langs->transnoentitiesnoconv('Disabled');
  615. $this->labelStatusShort[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('Draft');
  616. $this->labelStatusShort[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('Enabled');
  617. $this->labelStatusShort[self::STATUS_CANCELED] = $langs->transnoentitiesnoconv('Disabled');
  618. }
  619. $statusType = 'status'.$status;
  620. //if ($status == self::STATUS_VALIDATED) $statusType = 'status1';
  621. if ($status == self::STATUS_CANCELED) {
  622. $statusType = 'status6';
  623. }
  624. return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
  625. }
  626. /**
  627. * Load the info information in the object
  628. *
  629. * @param int $id Id of object
  630. * @return void
  631. */
  632. public function info($id)
  633. {
  634. $sql = "SELECT rowid, date_creation as datec, tms as datem,";
  635. $sql .= " fk_user_creat, fk_user_modif";
  636. $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element." as t";
  637. $sql .= " WHERE t.rowid = ".((int) $id);
  638. $result = $this->db->query($sql);
  639. if ($result) {
  640. if ($this->db->num_rows($result)) {
  641. $obj = $this->db->fetch_object($result);
  642. $this->id = $obj->rowid;
  643. if ($obj->fk_user_author) {
  644. $cuser = new User($this->db);
  645. $cuser->fetch($obj->fk_user_author);
  646. $this->user_creation = $cuser;
  647. }
  648. if ($obj->fk_user_valid) {
  649. $vuser = new User($this->db);
  650. $vuser->fetch($obj->fk_user_valid);
  651. $this->user_validation = $vuser;
  652. }
  653. if ($obj->fk_user_cloture) {
  654. $cluser = new User($this->db);
  655. $cluser->fetch($obj->fk_user_cloture);
  656. $this->user_cloture = $cluser;
  657. }
  658. $this->date_creation = $this->db->jdate($obj->datec);
  659. $this->date_modification = $this->db->jdate($obj->datem);
  660. $this->date_validation = $this->db->jdate($obj->datev);
  661. }
  662. $this->db->free($result);
  663. } else {
  664. dol_print_error($this->db);
  665. }
  666. }
  667. /**
  668. * Initialise object with example values
  669. * Id must be 0 if object instance is a specimen
  670. *
  671. * @return void
  672. */
  673. public function initAsSpecimen()
  674. {
  675. // Set here init that are not commonf fields
  676. // $this->property1 = ...
  677. // $this->property2 = ...
  678. $this->initAsSpecimenCommon();
  679. }
  680. /**
  681. * Create an array of lines
  682. *
  683. * @return array|int array of lines if OK, <0 if KO
  684. */
  685. public function getLinesArray()
  686. {
  687. $this->lines = array();
  688. return $this->lines;
  689. }
  690. /**
  691. * Action executed by scheduler
  692. * CAN BE A CRON TASK. In such a case, parameters come from the schedule job setup field 'Parameters'
  693. * Use public function doScheduledJob($param1, $param2, ...) to get parameters
  694. *
  695. * @return int 0 if OK, <>0 if KO (this function is used also by cron so only 0 is OK)
  696. */
  697. public function doScheduledJob()
  698. {
  699. global $conf, $langs;
  700. //$conf->global->SYSLOG_FILE = 'DOL_DATA_ROOT/dolibarr_mydedicatedlofile.log';
  701. $error = 0;
  702. $this->output = '';
  703. $this->error = '';
  704. dol_syslog(__METHOD__, LOG_DEBUG);
  705. $now = dol_now();
  706. $this->db->begin();
  707. // ...
  708. $this->db->commit();
  709. return $error;
  710. }
  711. }