dolibarr 25.0.0-alpha
knowledgerecord.class.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2017 Laurent Destailleur <eldy@users.sourceforge.net>
3 * Copyright (C) 2024-2025 Frédéric France <frederic.france@free.fr>
4 * Copyright (C) 2024-2026 MDW <mdeweerd@users.noreply.github.com>
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 3 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <https://www.gnu.org/licenses/>.
18 */
19
26// Put here all includes required by your class file
27require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
28//require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php';
29//require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
30
35{
39 public $module = 'knowledgemanagement';
40
44 public $element = 'knowledgerecord';
45
49 public $table_element = 'knowledgemanagement_knowledgerecord';
50
54 public $picto = 'knowledgemanagement';
55
56
57 const STATUS_DRAFT = 0;
58 const STATUS_VALIDATED = 1;
59 const STATUS_CANCELED = 9;
60
61
89 // BEGIN MODULEBUILDER PROPERTIES
93 public $fields = array(
94 'rowid' => array('type' => 'integer', 'label' => 'TechnicalID', 'enabled' => 1, 'position' => 1, 'notnull' => 1, 'visible' => 0, 'noteditable' => 1, 'index' => 1, 'css' => 'left', 'comment' => "Id"),
95 'ref' => array('type' => 'varchar(128)', 'label' => 'Ref', 'enabled' => 1, 'position' => 10, 'notnull' => 1, 'default' => '(PROV)', 'visible' => 5, 'index' => 1, 'searchall' => 1, 'comment' => "Reference of object", "csslist" => "nowraponall", "showoncombobox" => 1),
96 'entity' => array('type' => 'integer', 'label' => 'Entity', 'default' => '1', 'enabled' => 1, 'visible' => 0, 'notnull' => 1, 'position' => 20, 'index' => 1),
97 'question' => array('type' => 'text', 'label' => 'Question', 'enabled' => 1, 'position' => 30, 'notnull' => 1, 'visible' => 1, 'searchall' => 1, 'csslist' => 'tdoverflowmax300 small', 'copytoclipboard' => 1, 'tdcss' => 'titlefieldcreate nowraponall'),
98 'lang' => array('type' => 'varchar(6)', 'label' => 'Language', 'enabled' => 1, 'position' => 40, 'notnull' => 0, 'visible' => 1, 'tdcss' => 'titlefieldcreate nowraponall', "csslist" => "tdoverflowmax100"),
99 'date_creation' => array('type' => 'datetime', 'label' => 'DateCreation', 'enabled' => 1, 'position' => 500, 'notnull' => 1, 'visible' => -2, 'csslist' => 'nowraponall'),
100 'tms' => array('type' => 'timestamp', 'label' => 'DateModification', 'enabled' => 1, 'position' => 501, 'notnull' => 0, 'visible' => 2,),
101 'last_main_doc' => array('type' => 'varchar(255)', 'label' => 'LastMainDoc', 'enabled' => 1, 'position' => 600, 'notnull' => 0, 'visible' => 0,),
102 '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', 'csslist' => 'tdoverflowmax100'),
103 'fk_user_modif' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserModif', 'enabled' => 1, 'position' => 511, 'notnull' => -1, 'visible' => -2, 'csslist' => 'tdoverflowmax100'),
104 'fk_user_valid' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserValidation', 'enabled' => 1, 'position' => 512, 'notnull' => 0, 'visible' => -2, 'csslist' => 'tdoverflowmax100'),
105 'import_key' => array('type' => 'varchar(14)', 'label' => 'ImportId', 'enabled' => 1, 'position' => 1000, 'notnull' => -1, 'visible' => -2,),
106 'model_pdf' => array('type' => 'varchar(255)', 'label' => 'Model pdf', 'enabled' => 1, 'position' => 1010, 'notnull' => -1, 'visible' => 0,),
107 //'url' => array('type'=>'varchar(255)', 'label'=>'URL', 'enabled'=>'1', 'position'=>55, 'notnull'=>0, 'visible'=>-1, 'csslist'=>'tdoverflow200', 'help'=>'UrlForInfoPage'),
108 'fk_c_ticket_category' => array('type' => 'integer:CTicketCategory:ticket/class/cticketcategory.class.php:0:(t.active:=:1):pos', 'label' => 'SuggestedForTicketsInGroup', 'enabled' => 'isModEnabled("ticket")', 'position' => 520, 'notnull' => 0, 'visible' => -1, 'help' => 'YouCanLinkArticleToATicketCategory', 'csslist' => 'minwidth150 tdoverflowmax200'),
109 'answer' => array('type' => 'html', 'label' => 'Solution', 'enabled' => 1, 'position' => 600, 'notnull' => 0, 'visible' => 3, 'searchall' => 1, 'csslist' => 'tdoverflowmax300', 'copytoclipboard' => 1, 'tdcss' => 'titlefieldcreate nowraponall'),
110 'status' => array('type' => 'integer', 'label' => 'Status', 'enabled' => 1, 'position' => 1000, 'notnull' => 1, 'visible' => 5, 'default' => '0', 'index' => 1, 'arrayofkeyval' => array(0 => 'Draft', 1 => 'Validated', 9 => 'Obsolete'),),
111 );
112
116 public $rowid;
117
121 public $ref;
122
126 public $last_main_doc;
130 public $fk_user_creat;
134 public $fk_user_modif;
138 public $fk_user_valid;
142 public $import_key;
146 public $model_pdf;
147
151 public $question;
152
156 public $answer;
160 public $url;
161
165 public $status;
166
170 public $lang;
171 // END MODULEBUILDER PROPERTIES
172
173
174 // If this object has a subtable with lines
175
176 // /**
177 // * @var string Name of subtable line
178 // */
179 // public $table_element_line = 'knowledgemanagement_knowledgerecordline';
180
181 // /**
182 // * @var string Field with ID of parent key if this object has a parent
183 // */
184 // public $fk_element = 'fk_knowledgerecord';
185
186 // /**
187 // * @var string Name of subtable class that manage subtable lines
188 // */
189 // public $class_element_line = 'KnowledgeRecordline';
190
191 // /**
192 // * @var array List of child tables. To test if we can delete object.
193 // */
194 // protected $childtables = array();
195
196 // /**
197 // * @var array List of child tables. To know object to delete on cascade.
198 // * If name matches '@ClassNAme:FilePathClass;ParentFkFieldName' it will
199 // * call method deleteByParentField(parentId, ParentFkFieldName) to fetch and delete child object
200 // */
201 // protected $childtablesoncascade = array('knowledgemanagement_knowledgerecorddet');
202
203 // /**
204 // * @var KnowledgeRecordLine[] Array of subtable lines
205 // */
206 // public $lines = array();
207
208
209
215 public function __construct(DoliDB $db)
216 {
217 global $langs;
218
219 $this->db = $db;
220
221 $this->ismultientitymanaged = 1;
222 $this->isextrafieldmanaged = 1;
223
224 if (!getDolGlobalString('MAIN_SHOW_TECHNICAL_ID') && isset($this->fields['rowid'])) {
225 $this->fields['rowid']['visible'] = 0;
226 }
227 if (!isModEnabled('multicompany') && isset($this->fields['entity'])) {
228 $this->fields['entity']['enabled'] = 0;
229 }
230
231 // Unset fields that are disabled
232 foreach ($this->fields as $key => $val) {
233 if (isset($val['enabled']) && empty($val['enabled'])) {
234 unset($this->fields[$key]);
235 }
236 }
237
238 // Translate some data of arrayofkeyval
239 if (is_object($langs)) {
240 foreach ($this->fields as $key => $val) {
241 if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
242 foreach ($val['arrayofkeyval'] as $key2 => $val2) {
243 $this->fields[$key]['arrayofkeyval'][$key2] = $langs->trans($val2);
244 }
245 }
246 }
247 }
248 }
249
257 public function create(User $user, $notrigger = 0)
258 {
259 return $this->createCommon($user, $notrigger);
260 }
261
269 public function createFromClone(User $user, $fromid)
270 {
271 global $langs, $extrafields;
272 $error = 0;
273
274 dol_syslog(__METHOD__, LOG_DEBUG);
275
276 $object = new self($this->db);
277
278 $this->db->begin();
279
280 // Load source object
281 $result = $object->fetchCommon($fromid);
282 if ($result > 0 && !empty($object->table_element_line)) {
283 $object->fetchLines();
284 }
285
286 // get lines so they will be clone
287 //foreach($this->lines as $line)
288 // $line->fetch_optionals();
289
290 // Reset some properties
291 unset($object->id);
292 unset($object->fk_user_creat);
293 unset($object->import_key);
294
295 // Clear fields
296 if (property_exists($object, 'ref')) {
297 // @phan-suppress-next-line PhanTypeMismatchProperty
298 $object->ref = empty($this->fields['ref']['default']) ? "Copy_Of_".$object->ref : $this->fields['ref']['default'];
299 }
300 if (property_exists($object, 'question')) {
301 // @phan-suppress-next-line PhanTypeInvalidDimOffset
302 $object->question = empty($this->fields['question']['default']) ? $langs->trans("CopyOf")." ".$object->question : $this->fields['question']['default'];
303 }
304 if (property_exists($object, 'status')) {
305 $object->status = self::STATUS_DRAFT;
306 }
307 if (property_exists($object, 'date_creation')) {
308 $object->date_creation = dol_now();
309 }
310 if (property_exists($object, 'date_modification')) {
311 $object->date_modification = null;
312 }
313 // ...
314 // Clear extrafields that are unique
315 if (is_array($object->array_options) && count($object->array_options) > 0) {
316 $extrafields->fetch_name_optionals_label($this->table_element);
317 foreach ($object->array_options as $key => $option) {
318 $shortkey = preg_replace('/options_/', '', $key);
319 if (!empty($extrafields->attributes[$this->table_element]['unique'][$shortkey])) {
320 //var_dump($key);
321 //var_dump($clonedObj->array_options[$key]); exit;
322 unset($object->array_options[$key]);
323 }
324 }
325 }
326
327 // Create clone
328 $object->context['createfromclone'] = 'createfromclone';
329 $result = $object->createCommon($user);
330 if ($result < 0) {
331 $error++;
332 $this->error = $object->error;
333 $this->errors = $object->errors;
334 }
335
336 if (!$error) {
337 // copy internal contacts
338 if ($this->copy_linked_contact($object, 'internal') < 0) {
339 $error++;
340 }
341 }
342
343 unset($object->context['createfromclone']);
344
345 // End
346 if (!$error) {
347 $this->db->commit();
348 return $object;
349 } else {
350 $this->db->rollback();
351 return -1;
352 }
353 }
354
362 public function fetch($id, $ref = null)
363 {
364 $result = $this->fetchCommon($id, $ref);
365 if ($result > 0 && !empty($this->table_element_line)) {
366 $this->fetchLines();
367 }
368 return $result;
369 }
370
376 public function fetchLines()
377 {
378 $this->lines = array();
379
380 $result = $this->fetchLinesCommon();
381 return $result;
382 }
383
384
396 public function fetchAll($sortorder = '', $sortfield = '', $limit = 0, $offset = 0, $filter = '', $filtermode = 'AND')
397 {
398 dol_syslog(__METHOD__, LOG_DEBUG);
399
400 $records = array();
401
402 $sql = 'SELECT ';
403 $sql .= $this->getFieldList('t');
404 $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t';
405 if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
406 $sql .= ' WHERE t.entity IN ('.getEntity($this->element).')';
407 } else {
408 $sql .= ' WHERE 1 = 1';
409 }
410
411 // Manage filter
412 if (is_array($filter)) {
413 $sqlwhere = array();
414 if (count($filter) > 0) {
415 foreach ($filter as $key => $value) {
416 if ($key == 't.rowid') {
417 $sqlwhere[] = $this->db->sanitize($key)." = ".((int) $value);
418 } elseif (array_key_exists($key, $this->fields) && in_array($this->fields[$key]['type'], array('date', 'datetime', 'timestamp'))) {
419 $sqlwhere[] = $this->db->sanitize($key)." = '".$this->db->idate((int) $value)."'";
420 } elseif (strpos($value, '%') === false) {
421 $sqlwhere[] = $this->db->sanitize($key).' IN ('.$this->db->sanitize($this->db->escape($value)).')';
422 } else {
423 $sqlwhere[] = $this->db->sanitize($key)." LIKE '%".$this->db->escape($this->db->escapeforlike($value))."%'";
424 }
425 }
426 }
427 if (count($sqlwhere) > 0) {
428 $sql .= ' AND ('.implode(' '.$this->db->sanitize($filtermode).' ', $sqlwhere).')';
429 }
430
431 $filter = '';
432 }
433
434 // Manage filter
435 $errormessage = '';
436 $sql .= forgeSQLFromUniversalSearchCriteria($filter, $errormessage);
437 if ($errormessage) {
438 $this->errors[] = $errormessage;
439 dol_syslog(__METHOD__.' '.implode(',', $this->errors), LOG_ERR);
440 return -1;
441 }
442
443 if (!empty($sortfield)) {
444 $sql .= $this->db->order($sortfield, $sortorder);
445 }
446 if (!empty($limit)) {
447 $sql .= $this->db->plimit($limit, $offset);
448 }
449
450 $resql = $this->db->query($sql);
451 if ($resql) {
452 $num = $this->db->num_rows($resql);
453 $i = 0;
454 while ($i < ($limit ? min($limit, $num) : $num)) {
455 $obj = $this->db->fetch_object($resql);
456
457 $record = new self($this->db);
458 $record->setVarsFromFetchObj($obj);
459
460 $records[$record->id] = $record;
461
462 $i++;
463 }
464 $this->db->free($resql);
465
466 return $records;
467 } else {
468 $this->errors[] = 'Error '.$this->db->lasterror();
469 dol_syslog(__METHOD__.' '.implode(',', $this->errors), LOG_ERR);
470
471 return -1;
472 }
473 }
474
482 public function update(User $user, $notrigger = 0)
483 {
484 return $this->updateCommon($user, $notrigger);
485 }
486
494 public function delete(User $user, $notrigger = 0)
495 {
496 global $conf;
497
498 $error = 0;
499 $sql = "DELETE FROM ".MAIN_DB_PREFIX."categorie_knowledgemanagement WHERE fk_knowledgemanagement = ".((int) $this->id);
500 dol_syslog(get_class($this)."::delete", LOG_DEBUG);
501 $resql = $this->db->query($sql);
502 if (!$resql) {
503 $error++;
504 $this->error .= $this->db->lasterror();
505 $errorflag = -1;
506 }
507
508 // Delete all child tables
509 if (!$error) {
510 $elements = array('categorie_knowledgemanagement');
511 foreach ($elements as $table) {
512 if (!$error) {
513 $sql = "DELETE FROM ".MAIN_DB_PREFIX.$table;
514 $sql .= " WHERE fk_knowledgemanagement = ".(int) $this->id;
515
516 $result = $this->db->query($sql);
517 if (!$result) {
518 $error++;
519 $this->errors[] = $this->db->lasterror();
520 }
521 }
522 }
523 }
524
525 $result = $this->deleteCommon($user, $notrigger);
526
527 // Remove the linked files directory (uploads attached to the article)
528 if ($result > 0 && !empty($conf->knowledgemanagement->dir_output) && !empty($this->ref)) {
529 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
530 $dir = $conf->knowledgemanagement->dir_output.'/knowledgerecord/'.dol_sanitizeFileName($this->ref);
531 if (file_exists($dir)) {
532 if (!@dol_delete_dir_recursive($dir)) {
533 $this->errors[] = 'ErrorFailToDeleteDir';
534 }
535 }
536 }
537
538 return $result;
539 }
540
549 public function deleteLine(User $user, $idline, $notrigger = 0)
550 {
551 if ($this->status < 0) {
552 $this->error = 'ErrorDeleteLineNotAllowedByObjectStatus';
553 return -2;
554 }
555
556 return $this->deleteLineCommon($user, $idline, $notrigger);
557 }
558
559
567 public function validate($user, $notrigger = 0)
568 {
569 global $conf, $langs;
570
571 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
572
573 $error = 0;
574
575 // Protection
576 if ($this->status == self::STATUS_VALIDATED) {
577 dol_syslog(get_class($this)."::validate action abandoned: already validated", LOG_WARNING);
578 return 0;
579 }
580
581 /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && $user->hasRight('knowledgemanagement', 'knowledgerecord', 'write'))
582 || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->knowledgemanagement->knowledgerecord->knowledgerecord_advance->validate))))
583 {
584 $this->error='NotEnoughPermissions';
585 dol_syslog(get_class($this)."::valid ".$this->error, LOG_ERR);
586 return -1;
587 }*/
588
589 $now = dol_now();
590
591 $this->db->begin();
592
593 // Define new ref
594 if (!$error && (preg_match('/^[\‍(]?PROV/i', $this->ref) || empty($this->ref))) { // empty should not happened, but when it occurs, the test save life
595 $num = $this->getNextNumRef();
596 } else {
597 $num = (string) $this->ref;
598 }
599 $this->newref = $num;
600
601 if (!empty($num)) {
602 // Validate
603 $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
604 $sql .= " SET ref = '".$this->db->escape($num)."',";
605 $sql .= " status = ".self::STATUS_VALIDATED;
606 if (!empty($this->fields['date_validation'])) {
607 $sql .= ", date_validation = '".$this->db->idate($now)."'";
608 }
609 if (!empty($this->fields['fk_user_valid'])) { // @phan-suppress-current-line PhanTypeMismatchProperty
610 $sql .= ", fk_user_valid = ".((int) $user->id);
611 }
612 $sql .= " WHERE rowid = ".((int) $this->id);
613
614 dol_syslog(get_class($this)."::validate()", LOG_DEBUG);
615 $resql = $this->db->query($sql);
616 if (!$resql) {
617 dol_print_error($this->db);
618 $this->error = $this->db->lasterror();
619 $error++;
620 }
621
622 if (!$error && !$notrigger) {
623 // Call trigger
624 $result = $this->call_trigger('KNOWLEDGERECORD_VALIDATE', $user);
625 if ($result < 0) {
626 $error++;
627 }
628 // End call triggers
629 }
630 }
631
632 if (!$error) {
633 $this->oldref = $this->ref;
634
635 // Rename directory if dir was a temporary ref
636 if (preg_match('/^[\‍(]?PROV/i', $this->ref)) {
637 // Now we rename also files into index
638 $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)."'";
639 $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'knowledgerecord/".$this->db->escape($this->ref)."' and entity = ".((int) $conf->entity);
640 $resql = $this->db->query($sql);
641 if (!$resql) {
642 $error++;
643 $this->error = $this->db->lasterror();
644 }
645 $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filepath = 'knowledgerecord/".$this->db->escape($this->newref)."'";
646 $sql .= " WHERE filepath = 'knowledgerecord/".$this->db->escape($this->ref)."' and entity = ".((int) $conf->entity);
647 $resql = $this->db->query($sql);
648 if (!$resql) {
649 $error++;
650 $this->error = $this->db->lasterror();
651 }
652
653 // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments
654 $oldref = dol_sanitizeFileName($this->ref);
655 $newref = dol_sanitizeFileName($num);
656 $dirsource = $conf->knowledgemanagement->dir_output.'/knowledgerecord/'.$oldref;
657 $dirdest = $conf->knowledgemanagement->dir_output.'/knowledgerecord/'.$newref;
658 if (!$error && file_exists($dirsource)) {
659 dol_syslog(get_class($this)."::validate() rename dir ".$dirsource." into ".$dirdest);
660
661 if (@rename($dirsource, $dirdest)) {
662 dol_syslog("Rename ok");
663 // Rename docs starting with $oldref with $newref
664 $listoffiles = dol_dir_list($conf->knowledgemanagement->dir_output.'/knowledgerecord/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/'));
665 foreach ($listoffiles as $fileentry) {
666 $dirsource = $fileentry['name'];
667 $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource);
668 $dirsource = $fileentry['path'].'/'.$dirsource;
669 $dirdest = $fileentry['path'].'/'.$dirdest;
670 @rename($dirsource, $dirdest);
671 }
672 }
673 }
674 }
675 }
676
677 // Set new ref and current status
678 if (!$error) {
679 $this->ref = $num;
680 $this->status = self::STATUS_VALIDATED;
681 }
682
683 if (!$error) {
684 $this->db->commit();
685 return 1;
686 } else {
687 $this->db->rollback();
688 return -1;
689 }
690 }
691
692
700 public function setDraft($user, $notrigger = 0)
701 {
702 // Protection
703 if ($this->status <= self::STATUS_DRAFT) {
704 return 0;
705 }
706
707 /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->knowledgemanagement->write))
708 || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->knowledgemanagement->knowledgemanagement_advance->validate))))
709 {
710 $this->error='Permission denied';
711 return -1;
712 }*/
713
714 return $this->setStatusCommon($user, self::STATUS_DRAFT, $notrigger, 'KNOWLEDGERECORD_UNVALIDATE');
715 }
716
724 public function cancel($user, $notrigger = 0)
725 {
726 // Protection
727 if ($this->status != self::STATUS_VALIDATED) {
728 return 0;
729 }
730
731 /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->knowledgemanagement->write))
732 || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->knowledgemanagement->knowledgemanagement_advance->validate))))
733 {
734 $this->error='Permission denied';
735 return -1;
736 }*/
737
738 return $this->setStatusCommon($user, self::STATUS_CANCELED, $notrigger, 'KNOWLEDGERECORD_CANCEL');
739 }
740
748 public function reopen($user, $notrigger = 0)
749 {
750 // Protection
751 if ($this->status != self::STATUS_CANCELED) {
752 return 0;
753 }
754
755 /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->knowledgemanagement->write))
756 || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->knowledgemanagement->knowledgemanagement_advance->validate))))
757 {
758 $this->error='Permission denied';
759 return -1;
760 }*/
761
762 return $this->setStatusCommon($user, self::STATUS_VALIDATED, $notrigger, 'KNOWLEDGERECORD_REOPEN');
763 }
764
771 public function getTooltipContentArray($params)
772 {
773 global $conf, $langs;
774
775 $langs->loadLangs(['knowledgemanagement', 'languages']);
776
777 $datas = array();
778 $nofetch = !empty($params['nofetch']);
779
780 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("KnowledgeRecord").'</u>';
781 if (isset($this->status)) {
782 $datas['picto'] .= ' '.$this->getLibStatut(5);
783 }
784 $datas['label'] = '<br><b>'.$langs->trans('Ref').':</b> '.$this->ref;
785 $datas['question'] = '<br><b>'.$langs->trans('Question').':</b> '.$this->question;
786 $labellang = ($this->lang ? $langs->trans('Language_'.$this->lang) : '');
787 $datas['lang'] = '<br><b>'.$langs->trans('Language').':</b> ' . picto_from_langcode($this->lang, 'class="paddingrightonly saturatemedium opacitylow"') . $labellang;
788 // show categories for this record only in ajax to not overload lists
789 if (isModEnabled('category') && !$nofetch) {
790 require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
791 $form = new Form($this->db);
792 $datas['categories'] = '<br>' . $form->showCategories($this->id, Categorie::TYPE_KNOWLEDGEMANAGEMENT, 1);
793 }
794
795 return $datas;
796 }
797
808 public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $morecss = '', $save_lastsearch_value = -1)
809 {
810 global $conf, $langs, $hookmanager;
811
812 if (!empty($conf->dol_no_mouse_hover)) {
813 $notooltip = 1; // Force disable tooltips
814 }
815
816 $result = '';
817
818 $params = [
819 'id' => $this->id,
820 'objecttype' => $this->element.($this->module ? '@'.$this->module : ''),
821 'option' => $option,
822 'nofetch' => 1,
823 ];
824 $classfortooltip = 'classfortooltip';
825 $dataparams = '';
826 if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
827 $classfortooltip = 'classforajaxtooltip';
828 $dataparams = ' data-params="'.dol_escape_htmltag(json_encode($params)).'"';
829 $label = '';
830 } else {
831 $label = implode($this->getTooltipContentArray($params));
832 }
833
834 $url = dol_buildpath('/knowledgemanagement/knowledgerecord_card.php', 1).'?id='.$this->id;
835
836 if ($option != 'nolink') {
837 // Add param to save lastsearch_values or not
838 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
839 if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
840 $add_save_lastsearch_values = 1;
841 }
842 if ($add_save_lastsearch_values) {
843 $url .= '&save_lastsearch_values=1';
844 }
845 }
846
847 $linkclose = '';
848 if (empty($notooltip)) {
849 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
850 $label = $langs->trans("ShowKnowledgeRecord");
851 $linkclose .= ' alt="'.dolPrintHTMLForAttribute($label).'"';
852 }
853 $linkclose .= ($label ? ' title="'.dolPrintHTMLForAttribute($label).'"' : ' title="tocomplete"');
854 $linkclose .= $dataparams.' class="'.$classfortooltip.($morecss ? ' '.$morecss : '').'"';
855 } else {
856 $linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
857 }
858
859 if ($option == 'nolink') {
860 $linkstart = '<span';
861 } else {
862 $linkstart = '<a href="'.$url.'"';
863 }
864 $linkstart .= $linkclose.'>';
865 if ($option == 'nolink') {
866 $linkend = '</span>';
867 } else {
868 $linkend = '</a>';
869 }
870
871 $result .= $linkstart;
872
873 if (empty($this->showphoto_on_popup)) {
874 if ($withpicto) {
875 $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : $dataparams.' class="'.(($withpicto != 2) ? 'paddingright ' : '').$classfortooltip.'"'), 0, 0, $notooltip ? 0 : 1);
876 }
877 } else {
878 if ($withpicto) {
879 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
880
881 list($class, $module) = explode('@', $this->picto);
882 $upload_dir = $conf->$module->multidir_output[$conf->entity]."/$class/".dol_sanitizeFileName($this->ref);
883 $filearray = dol_dir_list($upload_dir, "files");
884 $filename = $filearray[0]['name'];
885 if (!empty($filename)) {
886 $pospoint = strpos($filearray[0]['name'], '.');
887
888 $pathtophoto = $class.'/'.$this->ref.'/thumbs/'.dol_substr($filename, 0, $pospoint).'_mini'.dol_substr($filename, $pospoint);
889 if (!getDolGlobalString(strtoupper($module.'_'.$class).'_FORMATLISTPHOTOSASUSERS')) {
890 $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>';
891 } else {
892 $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>';
893 }
894
895 $result .= '</div>';
896 } else {
897 $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), (($withpicto != 2) ? 'class="paddingright"' : ''), 0, 0, $notooltip ? 0 : 1);
898 }
899 }
900 }
901
902 if ($withpicto != 2) {
903 $result .= $this->ref;
904 }
905
906 $result .= $linkend;
907 //if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : '');
908
909 global $action, $hookmanager;
910 $hookmanager->initHooks(array('knowledgerecorddao'));
911 $parameters = array('id' => $this->id, 'getnomurl' => &$result);
912 $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
913 if ($reshook > 0) {
914 $result = $hookmanager->resPrint;
915 } else {
916 $result .= $hookmanager->resPrint;
917 }
918
919 return $result;
920 }
921
928 public function getLibStatut($mode = 0)
929 {
930 return $this->LibStatut($this->status, $mode);
931 }
932
933 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
941 public function LibStatut($status, $mode = 0)
942 {
943 // phpcs:enable
944 if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
945 global $langs;
946 //$langs->load("knowledgemanagement");
947 $this->labelStatus[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('Draft');
948 $this->labelStatus[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('Validated');
949 $this->labelStatus[self::STATUS_CANCELED] = $langs->transnoentitiesnoconv('Obsolete');
950 $this->labelStatusShort[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('Draft');
951 $this->labelStatusShort[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('Validated');
952 $this->labelStatusShort[self::STATUS_CANCELED] = $langs->transnoentitiesnoconv('Obsolete');
953 }
954
955 $statusType = 'status'.$status;
956 if ($status == self::STATUS_VALIDATED) {
957 $statusType = 'status4';
958 }
959 if ($status == self::STATUS_CANCELED) {
960 $statusType = 'status6';
961 }
962
963 return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
964 }
965
972 public function info($id)
973 {
974 $sql = 'SELECT t.rowid, t.date_creation as datec, GREATEST(t.tms, COALESCE(kef.tms, t.tms)) as datem,';
975 $sql .= ' t.fk_user_creat, t.fk_user_modif';
976 $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t';
977 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$this->table_element."_extrafields as kef ON kef.fk_object = t.rowid";
978 $sql .= ' WHERE t.rowid = '.((int) $id);
979 $result = $this->db->query($sql);
980 if ($result) {
981 if ($this->db->num_rows($result)) {
982 $obj = $this->db->fetch_object($result);
983
984 $this->id = $obj->rowid;
985
986 $this->user_creation_id = $obj->fk_user_creat;
987 $this->user_modification_id = $obj->fk_user_modif;
988 $this->date_creation = $this->db->jdate($obj->datec);
989 $this->date_modification = empty($obj->datem) ? '' : $this->db->jdate($obj->datem);
990 }
991
992 $this->db->free($result);
993 } else {
994 dol_print_error($this->db);
995 }
996 }
997
1004 public function initAsSpecimen()
1005 {
1006 $this->question = "ABCD";
1007
1008 return $this->initAsSpecimenCommon();
1009 }
1010
1011 // /**
1012 // * Create an array of lines
1013 // *
1014 // * @return KnowledgeRecordLine[]|int array of lines if OK, <0 if KO
1015 // */
1016 // public function getLinesArray()
1017 // {
1018 // $this->lines = array();
1019
1020 // $objectline = new KnowledgeRecordLine($this->db);
1021 // $result = $objectline->fetchAll('ASC', 'position', 0, 0, '(fk_knowledgerecord:=:'.((int) $this->id).')');
1022
1023 // if (is_numeric($result)) {
1024 // $this->error = $objectline->error;
1025 // $this->errors = $objectline->errors;
1026 // return $result;
1027 // } else {
1028 // $this->lines = $result;
1029 // // @phpstan-ignore-next-line
1030 // return $result; // @phan-suppress-current-line PhanTypeMismatchReturn
1031 // }
1032 // }
1033
1039 public function getNextNumRef()
1040 {
1041 global $langs, $conf;
1042 $langs->load("knowledgemanagement");
1043
1044 if (!getDolGlobalString('KNOWLEDGEMANAGEMENT_KNOWLEDGERECORD_ADDON')) {
1045 $conf->global->KNOWLEDGEMANAGEMENT_KNOWLEDGERECORD_ADDON = 'mod_knowledgerecord_standard';
1046 }
1047
1048 if (getDolGlobalString('KNOWLEDGEMANAGEMENT_KNOWLEDGERECORD_ADDON')) {
1049 $mybool = false;
1050
1051 $file = getDolGlobalString('KNOWLEDGEMANAGEMENT_KNOWLEDGERECORD_ADDON') . ".php";
1052 $classname = getDolGlobalString('KNOWLEDGEMANAGEMENT_KNOWLEDGERECORD_ADDON');
1053
1054 // Include file with class
1055 $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
1056 foreach ($dirmodels as $reldir) {
1057 $dir = dol_buildpath($reldir."core/modules/knowledgemanagement/");
1058
1059 // Load file with numbering class (if found)
1060 $mybool = ((bool) @include_once $dir.$file) || $mybool;
1061 }
1062
1063 if (!$mybool) {
1064 dol_print_error(null, "Failed to include file ".$file);
1065 return '';
1066 }
1067
1068 if (class_exists($classname)) {
1069 $obj = new $classname();
1070 '@phan-var-force ModeleNumRefKnowledgeRecord $obj';
1071 $numref = $obj->getNextValue($this);
1072
1073 if ($numref != '' && $numref != '-1') {
1074 return $numref;
1075 } else {
1076 $this->error = $obj->error;
1077 //dol_print_error($this->db,get_class($this)."::getNextNumRef ".$obj->error);
1078 return "";
1079 }
1080 } else {
1081 print $langs->trans("Error")." ".$langs->trans("ClassNotFound").' '.$classname;
1082 return "";
1083 }
1084 } else {
1085 print $langs->trans("ErrorNumberingModuleNotSetup", $this->element);
1086 return "";
1087 }
1088 }
1089
1101 public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
1102 {
1103 global $conf, $langs;
1104
1105 $result = 0;
1106 $includedocgeneration = 0;
1107
1108 $langs->load("knowledgemanagement");
1109
1110 if (!dol_strlen($modele)) {
1111 $modele = 'standard_knowledgerecord';
1112
1113 if (!empty($this->model_pdf)) {
1114 $modele = $this->model_pdf;
1115 } elseif (getDolGlobalString('KNOWLEDGERECORD_ADDON_PDF')) {
1116 $modele = getDolGlobalString('KNOWLEDGERECORD_ADDON_PDF');
1117 }
1118 }
1119
1120 $modelpath = "core/modules/knowledgemanagement/doc/";
1121
1122 if ($includedocgeneration && !empty($modele)) {
1123 $result = $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
1124 }
1125
1126 return $result;
1127 }
1128
1136 public function doScheduledJob()
1137 {
1138 global $conf, $langs;
1139
1140 //$conf->global->SYSLOG_FILE = 'DOL_DATA_ROOT/dolibarr_mydedicatedlofile.log';
1141
1142 $error = 0;
1143 $this->output = '';
1144 $this->error = '';
1145
1146 dol_syslog(__METHOD__, LOG_DEBUG);
1147
1148 $now = dol_now();
1149
1150 $this->db->begin();
1151
1152 // ...
1153
1154 $this->db->commit();
1155
1156 return $error;
1157 }
1158
1169 public function setCategories($categories)
1170 {
1171 require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
1172 return parent::setCategoriesCommon($categories, Categorie::TYPE_KNOWLEDGEMANAGEMENT);
1173 }
1174
1182 public function getKanbanView($option = '', $arraydata = null)
1183 {
1184 $selected = (empty($arraydata['selected']) ? 0 : $arraydata['selected']);
1185
1186 $return = '<div class="box-flex-item box-flex-grow-zero">';
1187 $return .= '<div class="info-box info-box-sm">';
1188 $return .= '<span class="info-box-icon bg-infobox-action">';
1189 $return .= img_picto('', $this->picto);
1190 $return .= '</span>';
1191 $return .= '<div class="info-box-content">';
1192 $return .= '<span class="info-box-ref inline-block tdoverflowmax150 valignmiddle">'.(method_exists($this, 'getNomUrl') ? $this->getNomUrl(1) : $this->ref).'</span>';
1193 if ($selected >= 0) {
1194 $return .= '<input id="cb'.$this->id.'" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="'.$this->id.'"'.($selected ? ' checked="checked"' : '').'>';
1195 }
1196 if (property_exists($this, 'lang') && !empty($this->lang)) {
1197 //$return .= '<br><span class="opacitymedium">'.$langs->trans("Language").'</span> : <span class="info-box-label" title="'.$langs->trans("Language_".$this->lang).'">'.$langs->trans("Language_".$this->lang, '', '', '', '', 12).'</span>';
1198 $return .= '<br>'.picto_from_langcode($this->lang, 'class="paddingrightonly saturatemedium opacitylow paddingrightonly"');
1199 }
1200 if (property_exists($this, 'question')) {
1201 $return .= '<div class="info-box-label tdoverflowmax150 classfortooltip" title="'.dolPrintHTMLForAttribute($this->question).'">'.dolGetFirstLineOfText($this->question).'</div>';
1202 }
1203 if (method_exists($this, 'getLibStatut')) {
1204 $return .= '<div class="info-box-status">'.$this->getLibStatut(3).'</div>';
1205 }
1206 $return .= '</div>';
1207 $return .= '</div>';
1208 $return .= '</div>';
1209 return $return;
1210 }
1211
1217 public function loadStateBoard()
1218 {
1219 global $user;
1220
1221 $this->nb = array();
1222 $clause = "WHERE";
1223
1224 $sql = "SELECT count(t.rowid) as nb";
1225 $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t';
1226
1227 $resql = $this->db->query($sql);
1228 if ($resql) {
1229 while ($obj = $this->db->fetch_object($resql)) {
1230 $this->nb["knowledgebase"] = $obj->nb;
1231 }
1232
1233 $this->db->free($resql);
1234 return 1;
1235 } else {
1236 dol_print_error($this->db);
1237 $this->error = $this->db->error();
1238 return -1;
1239 }
1240 }
1241}
1242
1243
1244// require_once DOL_DOCUMENT_ROOT.'/core/class/commonobjectline.class.php';
1245
1246// /**
1247// * Class KnowledgeRecordLine. You can also remove this and generate a CRUD class for lines objects.
1248// */
1249// class KnowledgeRecordLine extends CommonObjectLine
1250// {
1251// // To complete with content of an object KnowledgeRecordLine
1252// // We should have a field rowid, fk_knowledgerecord and position
1253
1254// /**
1255// * Constructor
1256// *
1257// * @param DoliDB $db Database handler
1258// */
1259// public function __construct(DoliDB $db)
1260// {
1261// $this->db = $db;
1262
1263// $this->isextrafieldmanaged = 0;
1264// }
1265// }
if(! $sortfield) if(! $sortorder) $object
Definition account.php:100
$object ref
Definition info.php:90
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
deleteLineCommon(User $user, $idline, $notrigger=0)
Delete a line of object in database.
commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams=null)
Common function for all objects extending CommonObject for generating documents.
createCommon(User $user, $notrigger=0)
Create object in the database.
getFieldList($alias='', $excludefields=array())
Function to concat keys of fields.
updateCommon(User $user, $notrigger=0)
Update object into database.
setStatusCommon($user, $status, $notrigger=0, $triggercode='')
Set to a status.
initAsSpecimenCommon()
Initialise object with example values Id must be 0 if object instance is a specimen.
copy_linked_contact($objFrom, $source='internal')
Copy contact from one element to current.
fetchLinesCommon($morewhere='', $noextrafields=0)
Load object in memory from the database.
fetchCommon($id, $ref=null, $morewhere='', $noextrafields=0)
Load object in memory from the database.
deleteCommon(User $user, $notrigger=0, $forcechilddeletion=0)
Delete object in database.
Class to manage Dolibarr database access.
Class to manage generation of HTML components Only common components must be here.
Class for KnowledgeRecord.
getKanbanView($option='', $arraydata=null)
Return clickable link of object (with eventually picto)
fetch($id, $ref=null)
Load object in memory from the database.
validate($user, $notrigger=0)
Validate object.
getNextNumRef()
Create an array of lines.
fetchAll($sortorder='', $sortfield='', $limit=0, $offset=0, $filter='', $filtermode='AND')
Load list of objects in memory from the database.
info($id)
Load the info information in the object.
cancel($user, $notrigger=0)
Set cancel status.
update(User $user, $notrigger=0)
Update object into database.
fetchLines()
Load object lines in memory from the database.
LibStatut($status, $mode=0)
Return the status.
create(User $user, $notrigger=0)
Create object into database.
getTooltipContentArray($params)
getTooltipContentArray
loadStateBoard()
Load indicators into this->nb for board.
getNomUrl($withpicto=0, $option='', $notooltip=0, $morecss='', $save_lastsearch_value=-1)
Return a link to the object card (with optionally the picto)
createFromClone(User $user, $fromid)
Clone an object into another one.
deleteLine(User $user, $idline, $notrigger=0)
Delete a line of object in database.
doScheduledJob()
Action executed by scheduler CAN BE A CRON TASK.
setCategories($categories)
Sets object to supplied categories.
initAsSpecimen()
Initialise object with example values Id must be 0 if object instance is a specimen.
__construct(DoliDB $db)
Constructor.
getLibStatut($mode=0)
Return the label of the status.
generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0, $moreparams=null)
Create a document onto disk according to template module.
reopen($user, $notrigger=0)
Set back to validated status.
setDraft($user, $notrigger=0)
Set draft status.
Class to manage Dolibarr users.
print $langs trans("Ref").' m titre as m m statut as status
Or an array listing all the potential status of the object: array: int of the status => translated la...
Definition index.php:169
dol_delete_dir_recursive($dir, $count=0, $nophperrors=0, $onlysub=0, &$countdeleted=0, $indexdatabase=1, $nolog=0, $level=0)
Remove a directory $dir and its subdirectories (or only files and subdirectories)
dol_dir_list($utf8_path, $types="all", $recursive=0, $filter="", $excludefilter=null, $sortcriteria="name", $sortorder=SORT_ASC, $mode=0, $nohook=0, $relativename="", $donotfollowsymlinks=0, $nbsecondsold=0)
Scan a directory and return a list of files/directories.
Definition files.lib.php:66
dol_now($mode='gmt')
Return date for now.
dolGetFirstLineOfText($text, $nboflines=1, $charset='UTF-8')
Return first line of text.
dol_strlen($string, $stringencoding='UTF-8', $binarycount=0)
Make a strlen call.
dol_sanitizeFileName($str, $newstr='_', $unaccent=1, $includequotes=0, $allowdash=0)
Clean a string to use it as a file name.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
forgeSQLFromUniversalSearchCriteria($filter, &$errorstr='', $noand=0, $nopar=0, $noerror=0, $forbiddenfields=array())
forgeSQLFromUniversalSearchCriteria
dol_substr($string, $start, $length=null, $stringencoding='', $trunconbytes=0)
Make a substring.
dol_buildpath($path, $type=0, $returnemptyifnotfound=0)
Return path of url or filesystem.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
isModEnabled($module)
Is Dolibarr module enabled.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
picto_from_langcode($codelang, $moreatt='', $notitlealt=0)
Return img flag of country for a language code or country code.