knowledgerecord.class.php.back 36 KB

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