dolibarr 25.0.0-alpha
memo.class.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2017 Laurent Destailleur <eldy@users.sourceforge.net>
3 * Copyright (C) 2023-2026 Frédéric France <frederic.france@free.fr>
4 * Copyright (C) 2026 John BOTELLA
5 * Copyright (C) 2026 MDW <mdeweerd@users.noreply.github.com>
6 *
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
19 */
20
27// Put here all includes required by your class file
28require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
29//require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php';
30//require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
31
35class Memo extends CommonObject
36{
40 public $module = 'quickmemo';
41
45 public $element = 'memo';
46
51 public $TRIGGER_PREFIX = 'QUICKMEMO_MEMO'; // Will be used to build trgiger keys 'QUICKMEMO_MEMO_MODIFY', ...
52
56 public $table_element = 'quickmemo_memo';
57
61 //public $element_for_permission = 'quickmemo';
62
66 public $picto = 'fa-file';
67
71 public $isextrafieldmanaged = 0;
72
77 public $ismultientitymanaged = 1;
78
79
80
81 const STATUS_TPL = 2;
82 const STATUS_VALIDATED = 1;
83 const STATUS_CANCELED = 9; // fall back in case of
84 const STATUS_ARCHIVED = 9;
85
133 public $fields = array(
134 "rowid" => array("type" => "integer", "label" => "TechnicalID", 'enabled' => 1, 'position' => 1, 'notnull' => 1, "visible" => 0, 'noteditable' => 1, 'index' => 1, "css" => "left", "comment" => "Id"),
135 "entity" => array("type" => "integer", "label" => "Entity", 'enabled' => 1, 'position' => 2, 'notnull' => 1, "visible" => 0, 'default' => '1', 'index' => 1),
136 "quick_note" => array("type" => "text", "label" => "Note", 'enabled' => 1, 'position' => 61, 'notnull' => 0, "visible" => -1, "cssview" => "wordbreak", "validate" => 1,),
137 "date_creation" => array("type" => "datetime", "label" => "DateCreation", 'enabled' => 1, 'position' => 500, 'notnull' => 1, "visible" => -2,),
138 "tms" => array("type" => "timestamp", "label" => "DateModification", 'enabled' => 1, 'position' => 501, 'notnull' => 0, "visible" => -2,),
139 "date_archived" => array("type" => "timestamp", "label" => "DateArchived", 'enabled' => 1, 'position' => 502, 'notnull' => 0, "visible" => -2,),
140 "fk_user_creat" => array("type" => "integer:User:user/class/user.class.php", "label" => "UserAuthor", "picto" => "user", 'enabled' => 1, 'position' => 510, 'notnull' => 1, "visible" => -2, "csslist" => "tdoverflowmax150",),
141 "fk_user_modif" => array("type" => "integer:User:user/class/user.class.php", "label" => "UserModif", "picto" => "user", 'enabled' => 1, 'position' => 511, 'notnull' => -1, "visible" => -2, "csslist" => "tdoverflowmax150",),
142 "fk_user_archived" => array("type" => "integer:User:user/class/user.class.php", "label" => "ArchivedBy", "picto" => "user", 'enabled' => 1, 'position' => 511, 'notnull' => -1, "visible" => -2, "csslist" => "tdoverflowmax150",),
143 "fk_element" => array('type' => 'integer','label' => 'MemoLinkedTo','help' => 'MemoLinkedToHelp','enabled' => 1,'visible' => 5,'notnull' => 0,'default' => 0,'index' => 1,'position' => 0),
144 "element_type" => array('type' => 'varchar(64)','label' => 'QuickMemoElementType','enabled' => 1,'visible' => 5,'position' => 10,'required' => 0),
145 "pos_z" => array("type" => "integer", "label" => "PosZ", 'enabled' => 1, 'position' => 1000, 'notnull' => 1, "visible" => 0, "default" => 0, "validate" => 1),
146 "pos_y" => array("type" => "integer", "label" => "PosY", 'enabled' => 1, 'position' => 1000, 'notnull' => 1, "visible" => 0, "default" => 0, "validate" => 1),
147 "pos_x" => array("type" => "integer", "label" => "PosX", 'enabled' => 1, 'position' => 1000, 'notnull' => 1, "visible" => 0, "default" => 0, "validate" => 1),
148 "pos_w" => array("type" => "integer", "label" => "PosW", 'enabled' => 1, 'position' => 1000, 'notnull' => 1, "visible" => 0, "default" => 0, "validate" => 1),
149 "pos_h" => array("type" => "integer", "label" => "PosH", 'enabled' => 1, 'position' => 1000, 'notnull' => 1, "visible" => 0, "default" => 0, "validate" => 1),
150 "color" => array('type' => 'varchar(10)', 'label' => 'Color','enabled' => 1,'visible' => 1,'position' => 10,'required' => 0),
151 "context_tab" => array('type' => 'varchar(64)', 'label' => 'ContextTab','enabled' => 1,'visible' => 1,'position' => 10,'required' => 0),
152 "private" => array("type" => "integer", "label" => "Private", 'enabled' => 1, 'position' => 1990, 'notnull' => 1, "visible" => 1, 'index' => 1, "arrayofkeyval" => array(0 => "No", 1 => "Yes"),'default' => 1, "validate" => 1,),
153 "private_tpl" => array("type" => "integer", "label" => "PrivateTemplate", 'enabled' => 1, 'position' => 1990, 'notnull' => 0, "visible" => 1, 'index' => 1, "arrayofkeyval" => array(0 => "No", 1 => "Yes"),'default' => 0, "validate" => 1,),
154 "rank_tpl" => array("type" => "integer", "label" => "TemplateRank", 'enabled' => 1, 'position' => 1990, 'notnull' => 0, "visible" => 0, 'index' => 1,'default' => 0, "validate" => 1,),
155 "name_tpl" => array('type' => 'varchar(256)','label' => 'QuickMemoTemplateName','enabled' => 1,'visible' => -1,'position' => 1,'required' => 0),
156 "shared_on_element" => array("type" => "integer", "label" => "SharedBetweenElement", 'enabled' => 1, 'position' => 1991, 'notnull' => 1, "visible" => 1, 'index' => 1, "arrayofkeyval" => array(0 => "No", 1 => "Yes"), "validate" => 1,),
157 "import_key" => array("type" => "varchar(14)", "label" => "ImportId", 'enabled' => 1, 'position' => 1000, 'notnull' => -1, "visible" => -2,),
158 "status" => array("type" => "integer", "label" => "Status", 'enabled' => 1, 'position' => 2000, 'notnull' => 1, "visible" => 1, 'index' => 1, "arrayofkeyval" => array(1 => "Active",2 => "Template", 9 => "Archived"), "validate" => 1,),
159 );
160
162 public $rowid;
163
165 public $date_archived;
166
168 public $fk_user_archived;
169
171 public $quick_note;
172
174 public $date_creat;
175
180 public $fk_element;
181
183 public $element_type;
184
186 public $pos_z;
187
189 public $pos_y;
190
192 public $pos_x;
193
195 public $pos_w;
196
198 public $pos_h;
199
201 public $color;
202
204 public $context_tab;
205
207 public $import_key;
208
217 public $status;
218
220 public $private;
221
223 public $private_tpl;
224
226 public $name_tpl;
227
229 public $shared_on_element;
230
236 public function __construct(DoliDB $db)
237 {
238 global $langs;
239
240 $this->db = $db;
241
242 if (!getDolGlobalInt('MAIN_SHOW_TECHNICAL_ID') && isset($this->fields['rowid']) && !empty($this->fields['ref'])) {
243 $this->fields['rowid']['visible'] = 0;
244 }
245 if (!isModEnabled('multicompany') && isset($this->fields['entity'])) {
246 $this->fields['entity']['enabled'] = 0;
247 }
248
249 // Unset fields that are disabled
250 foreach ($this->fields as $key => $val) {
251 if (isset($val['enabled']) && empty($val['enabled'])) {
252 unset($this->fields[$key]);
253 }
254 }
255
256 // Translate some data of arrayofkeyval
257 if (is_object($langs)) {
258 foreach ($this->fields as $key => $val) {
259 if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
260 foreach ($val['arrayofkeyval'] as $key2 => $val2) {
261 $this->fields[$key]['arrayofkeyval'][$key2] = $langs->trans($val2);
262 }
263 }
264 }
265 }
266 }
267
275 public function create(User $user, $notrigger = 0)
276 {
277 $result = $this->createCommon($user, $notrigger);
278
279 return $result;
280 }
281
289 public function createFromClone(User $user, $fromid)
290 {
291 global $langs, $extrafields;
292 $error = 0;
293
294 dol_syslog(__METHOD__, LOG_DEBUG);
295
296 $object = new self($this->db);
297
298 $this->db->begin();
299
300 // Load source object
301 $result = $object->fetchCommon($fromid);
302 if ($result > 0 && !empty($object->table_element_line)) {
303 $object->fetchLines();
304 }
305
306 // Reset some properties
307 unset($object->id);
308 unset($object->fk_user_creat);
309 unset($object->import_key);
310
311
312 $object->status = self::STATUS_VALIDATED;
313
314 $object->date_creation = dol_now();
315
316 $object->date_modification = null;
317
318 // ...
319 // Clear extrafields that are unique
320 if (is_array($object->array_options) && count($object->array_options) > 0) {
321 $extrafields->fetch_name_optionals_label($this->table_element);
322 foreach ($object->array_options as $key => $option) {
323 $shortkey = preg_replace('/options_/', '', $key);
324 if (!empty($extrafields->attributes[$this->table_element]['unique'][$shortkey])) {
325 //var_dump($key);
326 //var_dump($clonedObj->array_options[$key]); exit;
327 unset($object->array_options[$key]);
328 }
329 }
330 }
331
332 // Create clone
333 $object->context['createfromclone'] = 'createfromclone';
334 $result = $object->createCommon($user);
335 if ($result < 0) {
336 $error++;
338 }
339
340 unset($object->context['createfromclone']);
341
342 // End
343 if (!$error) {
344 $this->db->commit();
345 return $object;
346 } else {
347 $this->db->rollback();
348 return -1;
349 }
350 }
351
361 public function fetch($id, $ref = null, $noextrafields = 0, $nolines = 0)
362 {
363 $result = $this->fetchCommon($id, $ref, '', $noextrafields);
364 if ($result > 0 && !empty($this->table_element_line) && empty($nolines)) {
365 $this->fetchLines($noextrafields);
366 }
367 return $result;
368 }
369
376 public function fetchLines($noextrafields = 0)
377 {
378 $this->lines = array();
379
380 $result = $this->fetchLinesCommon('', $noextrafields);
381 return $result;
382 }
383
384
399 public function fetchAll($sortorder = '', $sortfield = '', $limit = 1000, $offset = 0, string $filter = '', $filtermode = 'AND')
400 {
401 dol_syslog(__METHOD__, LOG_DEBUG);
402
403 $records = array();
404
405 $sql = "SELECT ";
406 $sql .= $this->getFieldList('t');
407 $sql .= " FROM ".$this->db->prefix().$this->table_element." as t";
408 if (!empty($this->isextrafieldmanaged) && $this->isextrafieldmanaged == 1) {
409 $sql .= " LEFT JOIN ".$this->db->prefix().$this->table_element."_extrafields as te ON te.fk_object = t.rowid";
410 }
411 if (!empty($this->ismultientitymanaged) && (int) $this->ismultientitymanaged == 1) {
412 $sql .= " WHERE t.entity IN (".getEntity($this->element).")";
413 } elseif (preg_match('/^\w+@\w+$/', (string) $this->ismultientitymanaged)) {
414 $tmparray = explode('@', (string) $this->ismultientitymanaged);
415 $sql .= " LEFT JOIN ".$this->db->prefix().$this->db->sanitize($tmparray[1])." as pt ON t.".$this->db->sanitize($tmparray[0])." = pt.rowid";
416 $sql .= " WHERE pt.entity IN (".getEntity($this->element).")";
417 } else {
418 $sql .= " WHERE 1 = 1";
419 }
420
421 // Manage filter
422 $errormessage = '';
423 $sql .= forgeSQLFromUniversalSearchCriteria($filter, $errormessage);
424 if ($errormessage) {
425 $this->errors[] = $errormessage;
426 dol_syslog(__METHOD__.' '.implode(',', $this->errors), LOG_ERR);
427 return -1;
428 }
429
430 if (!empty($sortfield)) {
431 $sql .= $this->db->order($sortfield, $sortorder);
432 }
433 if (!empty($limit)) {
434 $sql .= $this->db->plimit($limit, $offset);
435 }
436
437 $resql = $this->db->query($sql);
438 if ($resql) {
439 $num = $this->db->num_rows($resql);
440 $i = 0;
441 while ($i < ($limit ? min($limit, $num) : $num)) {
442 $obj = $this->db->fetch_object($resql);
443
444 $record = new self($this->db);
445 $record->setVarsFromFetchObj($obj);
446
447 if (!empty($record->isextrafieldmanaged)) {
448 $record->fetch_optionals();
449 }
450
451 $records[$record->id] = $record;
452
453 $i++;
454 }
455 $this->db->free($resql);
456
457 return $records;
458 } else {
459 $this->errors[] = 'Error '.$this->db->lasterror();
460 dol_syslog(__METHOD__.' '.implode(',', $this->errors), LOG_ERR);
461
462 return -1;
463 }
464 }
465
473 public function update(User $user, $notrigger = 0)
474 {
475 return $this->updateCommon($user, $notrigger);
476 }
477
490 public function updatePosition(User $user, int $x, int $y, int $w, int $h, int $z)
491 {
492 if (empty($this->id)) {
493 return false;
494 }
495
496 $x = (int) $x;
497 $y = (int) $y;
498 $w = (int) $w;
499 $h = (int) $h;
500 $z = (int) $z;
501
502 // CREATEUR
503 if ((int) $this->fk_user_creat === (int) $user->id) {
504 $this->pos_x = $x;
505 $this->pos_y = $y;
506 $this->pos_w = $w;
507 $this->pos_h = $h;
508 $this->pos_z = $z;
509
510 if ($this->update($user) <= 0) {
511 return false;
512 }
513
514 return true;
515 }
516
517 // USER NOT CREATOR
518
519 $sql = 'SELECT rowid';
520 $sql .= ' FROM '.$this->db->prefix().'quickmemo_memo_user';
521 $sql .= ' WHERE fk_memo = '.((int) $this->id);
522 $sql .= ' AND fk_user = '.((int) $user->id);
523
524 $resql = $this->db->query($sql);
525 if (!$resql) {
526 return false;
527 }
528
529 if ($this->db->num_rows($resql) > 0) {
530 // UPDATE
531 $sql = 'UPDATE '.$this->db->prefix().'quickmemo_memo_user SET';
532 $sql .= ' pos_x = '. (int) $x.',';
533 $sql .= ' pos_y = '. (int) $y.',';
534 $sql .= ' pos_w = '. (int) $w.',';
535 $sql .= ' pos_h = '. (int) $h.',';
536 $sql .= ' pos_z = '. (int) $z;
537 $sql .= ' WHERE fk_memo = '.((int) $this->id);
538 $sql .= ' AND fk_user = '.((int) $user->id);
539
540 if (!$this->db->query($sql)) {
541 return false;
542 }
543 } else {
544 // INSERT
545 $sql = 'INSERT INTO '.$this->db->prefix().'quickmemo_memo_user (';
546 $sql .= 'fk_memo,';
547 $sql .= 'fk_user,';
548 $sql .= 'date_creation,';
549 $sql .= 'pos_x,';
550 $sql .= 'pos_y,';
551 $sql .= 'pos_w,';
552 $sql .= 'pos_h,';
553 $sql .= 'pos_z';
554 $sql .= ') VALUES (';
555 $sql .= ((int) $this->id).',';
556 $sql .= ((int) $user->id).',';
557 $sql .= '\''. $this->db->idate(dol_now()) .'\',';
558 $sql .= (int) $x.',';
559 $sql .= (int) $y.',';
560 $sql .= (int) $w.',';
561 $sql .= (int) $h.',';
562 $sql .= (int) $z;
563 $sql .= ')';
564
565 if (!$this->db->query($sql)) {
566 return false;
567 }
568 }
569
570 return true;
571 }
572
573
581 public function delete(User $user, $notrigger = 0)
582 {
583 // fetch() does not filter on entity, so an id of a memo of another entity may be provided (mass delete...)
584 if (!$this->isInCurrentEntity()) {
585 $this->error = 'ErrorRecordNotFound';
586 return -1;
587 }
588
589 return $this->deleteCommon($user, $notrigger);
590 //return $this->deleteCommon($user, $notrigger, 1);
591 }
592
601 public function deleteLine(User $user, $idline, $notrigger = 0)
602 {
603 if ($this->status < 0) {
604 $this->error = 'ErrorDeleteLineNotAllowedByObjectStatus';
605 return -2;
606 }
607
608 return $this->deleteLineCommon($user, $idline, $notrigger);
609 }
610
611
619 public function validate($user, $notrigger = 0)
620 {
621 global $conf;
622
623 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
624
625 $error = 0;
626
627 // Protection
628 if ($this->status == self::STATUS_VALIDATED) {
629 dol_syslog(get_class($this)."::validate action abandoned: already validated", LOG_WARNING);
630 return 0;
631 }
632
633 /* if (! ((!getDolGlobalInt('MAIN_USE_ADVANCED_PERMS') && $user->hasRight('quickmemo', 'memo', 'write'))
634 || (getDolGlobalInt('MAIN_USE_ADVANCED_PERMS') && $user->hasRight('quickmemo', 'memo_advance', 'validate')))
635 {
636 $this->error='NotEnoughPermissions';
637 dol_syslog(get_class($this)."::valid ".$this->error, LOG_ERR);
638 return -1;
639 }*/
640
641 $now = dol_now();
642
643 $this->db->begin();
644
645 // Define new ref
646 if (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref)) { // empty should not happened, but when it occurs, the test save life
647 $num = $this->getNextNumRef();
648 } else {
649 $num = (string) $this->ref;
650 }
651 $this->newref = $num;
652
653 if (!empty($num)) {
654 // Validate
655 $sql = "UPDATE ".$this->db->prefix().$this->table_element;
656 $sql .= " SET ";
657 if (!empty($this->fields['ref'])) {
658 $sql .= " ref = '".$this->db->escape($num)."',";
659 }
660 $sql .= " status = ".self::STATUS_VALIDATED;
661 if (!empty($this->fields['date_validation'])) {
662 $sql .= ", date_validation = '".$this->db->idate($now)."'";
663 }
664 if (!empty($this->fields['fk_user_valid'])) {
665 $sql .= ", fk_user_valid = ".((int) $user->id);
666 }
667 $sql .= " WHERE rowid = ".((int) $this->id);
668
669 dol_syslog(get_class($this)."::validate()", LOG_DEBUG);
670 $resql = $this->db->query($sql);
671 if (!$resql) {
672 dol_print_error($this->db);
673 $this->error = $this->db->lasterror();
674 $error++;
675 }
676
677 if (!$error && !$notrigger) {
678 // Call trigger
679 $result = $this->call_trigger('MEMO_VALIDATE', $user);
680 if ($result < 0) {
681 $error++;
682 }
683 // End call triggers
684 }
685 }
686
687 if (!$error) {
688 $this->oldref = $this->ref;
689
690 // Rename directory if dir was a temporary ref
691 if (preg_match('/^[\(]?PROV/i', $this->ref)) {
692 // Now we rename also files into index
693 $sql = 'UPDATE '.$this->db->prefix()."ecm_files set filename = CONCAT('".$this->db->escape($this->newref)."', SUBSTR(filename, ".(strlen($this->ref) + 1).")), filepath = 'memo/".$this->db->escape($this->newref)."'";
694 $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'memo/".$this->db->escape($this->ref)."' and entity = ".((int) $conf->entity);
695 $resql = $this->db->query($sql);
696 if (!$resql) {
697 $error++;
698 $this->error = $this->db->lasterror();
699 }
700 $sql = 'UPDATE '.$this->db->prefix()."ecm_files set filepath = 'memo/".$this->db->escape($this->newref)."'";
701 $sql .= " WHERE filepath = 'memo/".$this->db->escape($this->ref)."' and entity = ".((int) $conf->entity);
702 $resql = $this->db->query($sql);
703 if (!$resql) {
704 $error++;
705 $this->error = $this->db->lasterror();
706 }
707
708 // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments
709 $oldref = dol_sanitizeFileName($this->ref);
710 $newref = dol_sanitizeFileName($num);
711 $dirsource = $conf->quickmemo->dir_output.'/memo/'.$oldref;
712 $dirdest = $conf->quickmemo->dir_output.'/memo/'.$newref;
713 if (!$error && file_exists($dirsource)) {
714 dol_syslog(get_class($this)."::validate() rename dir ".$dirsource." into ".$dirdest);
715
716 if (@rename($dirsource, $dirdest)) {
717 dol_syslog("Rename ok");
718 // Rename docs starting with $oldref with $newref
719 $listoffiles = dol_dir_list($conf->quickmemo->dir_output.'/memo/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/'));
720 foreach ($listoffiles as $fileentry) {
721 $dirsource = $fileentry['name'];
722 $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource);
723 $dirsource = $fileentry['path'].'/'.$dirsource;
724 $dirdest = $fileentry['path'].'/'.$dirdest;
725 @rename($dirsource, $dirdest);
726 }
727 }
728 }
729 }
730 }
731
732 // Set new ref and current status
733 if (!$error) {
734 $this->ref = $num;
735 $this->status = self::STATUS_VALIDATED;
736 }
737
738 if (!$error) {
739 $this->db->commit();
740 return 1;
741 } else {
742 $this->db->rollback();
743 return -1;
744 }
745 }
746
747
755 public function setDraft($user, $notrigger = 0)
756 {
757 // Protection
758 if ($this->status <= self::STATUS_VALIDATED) {
759 return 0;
760 }
761
762 /* if (! ((!getDolGlobalInt('MAIN_USE_ADVANCED_PERMS') && $user->hasRight('quickmemo','write'))
763 || (getDolGlobalInt('MAIN_USE_ADVANCED_PERMS') && $user->hasRight('quickmemo','quickmemo_advance','validate'))))
764 {
765 $this->error='Permission denied';
766 return -1;
767 }*/
768
769 return $this->setStatusCommon($user, self::STATUS_VALIDATED, $notrigger, 'QUICKMEMO_MEMO_UNVALIDATE');
770 }
771
772
780 public function setArchived($user, $notrigger = 0)
781 {
782 $this->date_archived = dol_now();
783 $this->fk_user_archived = $user->id;
784 $this->status = self::STATUS_ARCHIVED;
785 return $this->update($user, $notrigger);
786 }
787
788
796 public function setUnArchived($user, $notrigger = 0)
797 {
798 $this->date_archived = null;
799 $this->fk_user_archived = null;
800 $this->status = self::STATUS_VALIDATED;
801 return $this->update($user, $notrigger);
802 }
803
811 public function cancel($user, $notrigger = 0)
812 {
813 // Protection
814 if ($this->status != self::STATUS_VALIDATED) {
815 return 0;
816 }
817
818 /* if (! ((!getDolGlobalInt('MAIN_USE_ADVANCED_PERMS') && $user->hasRight('quickmemo','write'))
819 || (getDolGlobalInt('MAIN_USE_ADVANCED_PERMS') && $user->hasRight('quickmemo','quickmemo_advance','validate'))))
820 {
821 $this->error='Permission denied';
822 return -1;
823 }*/
824
825 return $this->setStatusCommon($user, self::STATUS_CANCELED, $notrigger, 'QUICKMEMO_MEMO_CANCEL');
826 }
827
835 public function reopen($user, $notrigger = 0)
836 {
837 // Protection
838 if ($this->status == self::STATUS_VALIDATED) {
839 return 0;
840 }
841
842 /*if (! ((!getDolGlobalInt('MAIN_USE_ADVANCED_PERMS') && $user->hasRight('quickmemo','write'))
843 || (getDolGlobalInt('MAIN_USE_ADVANCED_PERMS') && $user->hasRight('quickmemo','quickmemo_advance','validate'))))
844 {
845 $this->error='Permission denied';
846 return -1;
847 }*/
848
849 return $this->setStatusCommon($user, self::STATUS_VALIDATED, $notrigger, 'QUICKMEMO_MEMO_REOPEN');
850 }
851
859 public function getTooltipContentArray($params)
860 {
861 global $langs;
862
863 $datas = [];
864
865 if (getDolGlobalInt('MAIN_OPTIMIZEFORTEXTBROWSER')) {
866 return ['optimize' => $langs->trans("ShowMemo")];
867 }
868 $datas['picto'] = img_picto('', $this->picto).' <u>'.$langs->trans("Memo").'</u>';
869 if (isset($this->status)) {
870 $datas['picto'] .= ' '.$this->getLibStatut(5);
871 }
872
873 return $datas;
874 }
875
886 public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $morecss = '', $save_lastsearch_value = -1)
887 {
888 global $conf, $langs, $hookmanager;
889
890 if (!empty($conf->dol_no_mouse_hover)) {
891 $notooltip = 1; // Force disable tooltips
892 }
893
894 $result = '';
895 $params = [
896 'id' => (string) $this->id,
897 'objecttype' => $this->element.($this->module ? '@'.$this->module : ''),
898 'option' => $option,
899 ];
900 $classfortooltip = 'classfortooltip';
901 $dataparams = '';
902 if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
903 $classfortooltip = 'classforajaxtooltip';
904 $dataparams = ' data-params="'.dol_escape_htmltag(json_encode($params)).'"';
905 $label = '';
906 } else {
907 $label = implode($this->getTooltipContentArray($params));
908 }
909
910 $baseurl = dol_buildpath('/quickmemo/memo_card.php', 1);
911 $query = ['id' => $this->id];
912 if ($option !== 'nolink') {
913 // Add param to save lastsearch_values or not
914 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
915 if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
916 $add_save_lastsearch_values = 1;
917 }
918 if ($add_save_lastsearch_values) {
919 $query = array_merge($query, ['save_lastsearch_values' => 1]);
920 }
921 }
922 $url = dolBuildUrl($baseurl, $query);
923
924 $linkclose = '';
925 if (empty($notooltip)) {
926 if (getDolGlobalInt('MAIN_OPTIMIZEFORTEXTBROWSER')) {
927 $label = $langs->trans("ShowMemo");
928 $linkclose .= ' alt="'.dolPrintHTMLForAttribute($label).'"';
929 }
930 $linkclose .= ($label ? ' title="'.dolPrintHTMLForAttribute($label).'"' : ' title="tocomplete"');
931 $linkclose .= $dataparams.' class="'.$classfortooltip.($morecss ? ' '.$morecss : '').'"';
932 } else {
933 $linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
934 }
935
936 if ($option == 'nolink') {
937 $linkstart = '<span';
938 } else {
939 $linkstart = '<a href="'.$url.'"';
940 }
941 $linkstart .= $linkclose.'>';
942 if ($option == 'nolink') {
943 $linkend = '</span>';
944 } else {
945 $linkend = '</a>';
946 }
947
948 $result .= $linkstart;
949
950 if (empty($this->showphoto_on_popup)) {
951 if ($withpicto) {
952 $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), (($withpicto != 2) ? 'class="paddingright"' : ''), 0, 0, $notooltip ? 0 : 1);
953 }
954 } else {
955 if ($withpicto) {
956 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
957
958 [$class, $module] = explode('@', $this->picto);
959 $upload_dir = $conf->$module->multidir_output[$conf->entity]."/$class/".dol_sanitizeFileName($this->ref);
960 $filearray = dol_dir_list($upload_dir, "files");
961 $filename = $filearray[0]['name'];
962 if (!empty($filename)) {
963 $pospoint = strpos($filearray[0]['name'], '.');
964
965 $pathtophoto = $class.'/'.$this->ref.'/thumbs/'.dol_substr($filename, 0, $pospoint).'_mini'.dol_substr($filename, $pospoint);
966 if (!getDolGlobalString(strtoupper($module.'_'.$class).'_FORMATLISTPHOTOSASUSERS')) {
967 $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>';
968 } else {
969 $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>';
970 }
971
972 $result .= '</div>';
973 } else {
974 $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'"'), 0, 0, $notooltip ? 0 : 1);
975 }
976 }
977 }
978
979 if ($withpicto != 2) {
980 $result .= $this->ref;
981 }
982
983 $result .= $linkend;
984 //if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : '');
985
986 global $action, $hookmanager;
987 $hookmanager->initHooks(array($this->element.'dao'));
988 $parameters = array('id' => $this->id, 'getnomurl' => &$result);
989 $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
990 if ($reshook > 0) {
991 $result = $hookmanager->resPrint;
992 } else {
993 $result .= $hookmanager->resPrint;
994 }
995
996 return $result;
997 }
998
1006 public function getKanbanView($option = '', $arraydata = null)
1007 {
1008 global $conf, $langs;
1009
1010 $selected = (empty($arraydata['selected']) ? 0 : $arraydata['selected']);
1011
1012 $return = '<div class="box-flex-item box-flex-grow-zero">';
1013 $isDarkMode = !empty($this->color) && !colorIsLight($this->color) ? '--memo-is-dark' : '';
1014 $style = !empty($this->color) && Memo::checkColor($this->color) ? ' style="--memo-color : '.$this->color.'" ' : '';
1015 $return .= '<div class="info-box-quickmemo '.$isDarkMode.'" '.$style.' >';
1016 $return .= '<div class="info-box-content-quickmemo">';
1017
1018 $return .= '<span class="info-box-status">'.$this->getLibStatut(4).'</span>';
1019
1020 // $return .= '<span class="info-box-ref inline-block tdoverflowmax150 valignmiddle">'.(method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref).'</span>';
1021 if ($selected >= 0) {
1022 $return .= '<input id="cb'.$this->id.'" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="'.$this->id.'"'.($selected ? ' checked="checked"' : '').'>';
1023 }
1024
1025
1026
1027 $return .= ' <div class="info-box-content-quicknote">';
1028 $return .= nl2br(htmlentities($this->quick_note));
1029 $return .= '</div>';
1030
1031 $return .= '<div class="quickmemo-info" >';
1032 $return .= ' <div class="quickmemo-info__create" >';
1033 $return .= ' <span class="quickmemo-info__user-create-name">'.$this->showOutputField($this->fields['fk_user_creat'], 'fk_user_creat', $this->user_creation_id).'</span>';
1034 $return .= ' <span class="quickmemo-info__date_create">'.dol_print_date($this->date_creation, '%d/%m/%Y %H:%M', 'tzuserrel').'</span>';
1035 $return .= ' </div>';
1036
1037
1038 if (!empty($this->tms) && $this->tms != $this->date_creation) {
1039 $return .= ' <div class="quickmemo-info__update" >';
1040
1041 $return .= ' <span class="quickmemo-info__date_update">'.$langs->trans('QuickMemoModified') . ' ' .dol_print_date($this->date_modification, '%d/%m/%Y %H:%M', 'tzuserrel').'</span>';
1042 if ($this->user_modification_id != $this->user_creation_id) {
1043 $return .= ' <span class="quickmemo-info__user-update-name">'.$langs->trans('QuickMemoBy') . ' ' .$this->showOutputField($this->fields['fk_user_modif'], 'fk_user_modif', $this->user_modification_id).'</span>';
1044 }
1045
1046 $return .= ' </div>';
1047 }
1048
1049 if (!empty($this->date_archived) && $this->status == self::STATUS_ARCHIVED) {
1050 $return .= ' <div class="quickmemo-info__update" >';
1051
1052 $return .= ' <span class="quickmemo-info__date_update">'.$langs->trans('QuickMemoArchived') . ' ' .dol_print_date($this->date_archived, '%d/%m/%Y %H:%M', 'tzuserrel').'</span>';
1053 if ($this->fk_user_modif != $this->fk_user_archived) {
1054 $return .= ' <span class="quickmemo-info__user-update-name">'.$langs->trans('QuickMemoBy') . ' ' .$this->showOutputField($this->fields['fk_user_archived'], 'fk_user_archived', $this->fk_user_archived).'</span>';
1055 }
1056
1057 $return .= ' </div>';
1058 }
1059
1060 $return .= '</div>';
1061
1062
1063
1064
1065 $return .= '</div>';
1066 $return .= '</div>';
1067 $return .= '</div>';
1068
1069 return $return;
1070 }
1071
1078 public function getLabelStatus($mode = 0)
1079 {
1080 return $this->LibStatut($this->status, $mode);
1081 }
1082
1089 public function getLibStatut($mode = 0)
1090 {
1091 return $this->LibStatut($this->status, $mode);
1092 }
1093
1094 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1102 public function LibStatut($status, $mode = 0)
1103 {
1104 // phpcs:enable
1105 if (is_null($status)) {
1106 return '';
1107 }
1108
1109 $paramsBadge = array('badgeParams' => array('attr' => array(
1110 'data-status-element' => $this->element,
1111 'data-status' => (int) $status
1112 )));
1113
1114
1115 if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
1116 global $langs;
1117 //$langs->load("quickmemo");
1118 $this->labelStatus[self::STATUS_TPL] = $langs->transnoentitiesnoconv('Template');
1119 $this->labelStatus[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('Enabled');
1120 $this->labelStatus[self::STATUS_ARCHIVED] = $langs->transnoentitiesnoconv('Archived');
1121 $this->labelStatusShort[self::STATUS_TPL] = $langs->transnoentitiesnoconv('Template');
1122 $this->labelStatusShort[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('Enabled');
1123 $this->labelStatusShort[self::STATUS_ARCHIVED] = $langs->transnoentitiesnoconv('Archived');
1124 }
1125
1126 $statusType = 'status'.$status;
1127 //if ($status == self::STATUS_VALIDATED) $statusType = 'status1';
1128 if ($status == self::STATUS_ARCHIVED) {
1129 $statusType = 'status6';
1130 }
1131
1132 return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode, '', $paramsBadge);
1133 }
1134
1141 public function info($id)
1142 {
1143 $sql = "SELECT t.rowid, t.date_creation as datec";
1144 if (!empty($this->isextrafieldmanaged) && $this->isextrafieldmanaged == 1) {
1145 $sql .= ", GREATEST(t.tms, te.tms) as datem";
1146 } else {
1147 $sql .= ", t.tms as datem";
1148 }
1149 if (!empty($this->fields['date_validation'])) {
1150 $sql .= ", t.date_validation as datev";
1151 }
1152 if (!empty($this->fields['fk_user_creat'])) {
1153 $sql .= ", t.fk_user_creat";
1154 }
1155 if (!empty($this->fields['fk_user_modif'])) {
1156 $sql .= ", t.fk_user_modif";
1157 }
1158 if (!empty($this->fields['fk_user_valid'])) {
1159 $sql .= ", t.fk_user_valid";
1160 }
1161 $sql .= " FROM ".$this->db->prefix().$this->table_element." as t";
1162 if (!empty($this->isextrafieldmanaged) && $this->isextrafieldmanaged == 1) {
1163 $sql .= " LEFT JOIN ".$this->db->prefix().$this->table_element."_extrafields as te ON te.fk_object = t.rowid";
1164 }
1165 $sql .= " WHERE t.rowid = ".((int) $id);
1166
1167 $result = $this->db->query($sql);
1168 if ($result) {
1169 if ($this->db->num_rows($result)) {
1170 $obj = $this->db->fetch_object($result);
1171
1172 $this->id = $obj->rowid;
1173
1174 if (!empty($this->fields['fk_user_creat'])) {
1175 $this->user_creation_id = $obj->fk_user_creat;
1176 }
1177 if (!empty($this->fields['fk_user_modif'])) {
1178 $this->user_modification_id = $obj->fk_user_modif;
1179 }
1180 if (!empty($this->fields['fk_user_valid'])) {
1181 $this->user_validation_id = $obj->fk_user_valid;
1182 }
1183 $this->date_creation = $this->db->jdate($obj->datec);
1184 $this->date_modification = empty($obj->datem) ? '' : $this->db->jdate($obj->datem);
1185 if (!empty($obj->datev)) {
1186 $this->date_validation = empty($obj->datev) ? '' : $this->db->jdate($obj->datev);
1187 }
1188 }
1189
1190 $this->db->free($result);
1191 } else {
1192 dol_print_error($this->db);
1193 }
1194 }
1195
1202 public function initAsSpecimen()
1203 {
1204 // Set here init that are not commonf fields
1205 // $this->property1 = ...
1206 // $this->property2 = ...
1207
1208 return $this->initAsSpecimenCommon();
1209 }
1210
1211
1217 public function getNextNumRef()
1218 {
1219 return '';
1220 }
1221
1233 public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
1234 {
1235 return 0;
1236 }
1237
1244 public static function checkColor($color)
1245 {
1246 if (!is_string($color)) {
1247 return false;
1248 }
1249
1250 // Remove spaces at the beginning/end
1251 $color = trim($color);
1252
1253 // Checks for #fff or #ffffff
1254 return preg_match('/^#([0-9A-Fa-f]{3}|[0-9A-Fa-f]{6})$/', $color) === 1;
1255 }
1256
1262 public static function getColorPreset()
1263 {
1264
1265 $colorsConf = getDolGlobalString('QUICKMEMO_COLORS_PRESET');
1266 $colors = explode(',', $colorsConf);
1267 if (!empty($colors)) {
1268 foreach ($colors as $iColor => $color) {
1269 if (!preg_match('/^#[a-f0-9]{6}$/i', $color)) {
1270 unset($colors[$iColor]);
1271 }
1272 }
1273 }
1274
1275 if (empty($colors)) {
1276 $colors = ['#fff8a6', '#ffd6d6', '#d6ffd9', '#d6e6ff', '#f3d6ff', '#ffffff', '#f5f5f5'];
1277 }
1278
1279 return array_values($colors);
1280 }
1281
1290 public static function getMemoContext($context, $object = null)
1291 {
1292 global $db,$action, $hookmanager;
1293
1294 if (!isModEnabled('quickmemo')) {
1295 return '';
1296 }
1297
1298 if (!is_array($context)) {
1299 $context = explode(':', $context);
1300 }
1301
1302 $contextMapping = self::getAvailableMemoContextMapping();
1303
1304 $memoContext = '';
1305 foreach ($contextMapping as $key => $values) {
1306 $values = (array) $values;
1307
1308 if (array_intersect($context, $values)) {
1309 $memoContext = $key;
1310 break;
1311 }
1312 }
1313
1314 $staticMemo = new self($db);
1315
1316 $hookmanager->initHooks(array($staticMemo->element.'dao'));
1317 $parameters = array(
1318 'memoContext' => & $memoContext
1319 );
1320
1321 $reshook = $hookmanager->executeHooks('getMemoContext', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
1322 if ($reshook > 0) {
1323 return $hookmanager->resPrint;
1324 }
1325
1326 return $memoContext;
1327 }
1328
1336 public static function completeMemoContextMapping(array &$contextTabMapping, string $tabContext, string $dolibarrContext = '')
1337 {
1338 $dolibarrContext = trim($dolibarrContext) ?: $tabContext;
1339
1340 if (!isset($contextTabMapping[$tabContext])) {
1341 $contextTabMapping[$tabContext] = [$dolibarrContext];
1342 return;
1343 }
1344
1345 if (!in_array($dolibarrContext, $contextTabMapping[$tabContext], true)) {
1346 $contextTabMapping[$tabContext][] = $dolibarrContext;
1347 }
1348 }
1349
1358 public static function getAvailableMemoContextMapping($object = null, $onlyActiveModules = true)
1359 {
1360 global $db,$action, $hookmanager;
1361
1362 $contextTabMapping = [];
1363
1364 // Start Correction of no standard Dolibarr context and special context
1365 if (isModEnabled('propal') || !$onlyActiveModules) {
1366 self::completeMemoContextMapping($contextTabMapping, 'contactcard', 'proposalcontactcard');
1367 }
1368
1369 if (isModEnabled('supplier_order') || !$onlyActiveModules) {
1370 self::completeMemoContextMapping($contextTabMapping, 'contactcard', 'ordersuppliercontactcard');
1371 self::completeMemoContextMapping($contextTabMapping, 'document', 'ordersuppliercarddocument');
1372 self::completeMemoContextMapping($contextTabMapping, 'agenda', 'ordersuppliercardinfo');
1373 self::completeMemoContextMapping($contextTabMapping, 'ordersupplierdispatch');
1374 }
1375
1376 if (isModEnabled('contract') || !$onlyActiveModules) {
1377 self::completeMemoContextMapping($contextTabMapping, 'agenda', 'agendacontract');
1378 }
1379
1380 if (isModEnabled('order') || !$onlyActiveModules) {
1381 self::completeMemoContextMapping($contextTabMapping, 'ordershipmentcard');
1382 }
1383
1384 if (isModEnabled('shipping')) {
1385 self::completeMemoContextMapping($contextTabMapping, 'contactcard', 'shipmentcontactcard');
1386 }
1387
1388 if (isModEnabled('product')) {
1389 self::completeMemoContextMapping($contextTabMapping, 'productpricecard');
1390 self::completeMemoContextMapping($contextTabMapping, 'pricesuppliercard');
1391 self::completeMemoContextMapping($contextTabMapping, 'producttranslationcard');
1392 self::completeMemoContextMapping($contextTabMapping, 'productcompositioncard');
1393 self::completeMemoContextMapping($contextTabMapping, 'stockproductcard');
1394 self::completeMemoContextMapping($contextTabMapping, 'productstatsinvoice');
1395 self::completeMemoContextMapping($contextTabMapping, 'productstatscard');
1396 self::completeMemoContextMapping($contextTabMapping, 'tabproductmarginlist');
1397 }
1398
1399 // End of corrections
1400
1401 // Generate standard context
1402 // TODO : Common contexts such as document, agenda, contact card, and stat, which are used across most Dolibarr objects, are not defined as standard global contexts.
1403 // Instead of having dedicated contexts like global_document, global_agenda, global_contactcard, or global_stat (similar to global_card), pages currently mix global_card with object-specific contexts (e.g. product_document, propal_agenda, etc.).
1404 // This creates inconsistent context handling. These contexts should include both their object-specific context and a proper global context (e.g. global_document or global_agenda) depending on the active tab.
1405 $commonCardContext = ['document', 'agenda', 'contactcard', 'stats']; // for common object
1406 $modules = ['order', 'propal', 'invoice', 'supplier_proposal', 'supplier_order', 'supplier_invoice', 'contract', 'product', 'shipping'];
1407 foreach ($modules as $module) {
1408 if (!isModEnabled($module) && $onlyActiveModules) {
1409 continue;
1410 }
1411
1412 $moduleClean = str_replace('_', '', $module);
1413
1414 foreach ($commonCardContext as $context) {
1415 self::completeMemoContextMapping($contextTabMapping, $context, $moduleClean.$context);
1416 }
1417 }
1418
1419 if (!empty($object) && !empty($object->element)) {
1420 foreach ($commonCardContext as $context) {
1421 self::completeMemoContextMapping($contextTabMapping, $context, $object->element.$context);
1422 }
1423 }
1424
1425 // Need to be at end of tests
1426 self::completeMemoContextMapping($contextTabMapping, 'index');
1427 self::completeMemoContextMapping($contextTabMapping, 'card', 'globalcard');
1428
1429 $staticMemo = new self($db);
1430 $hookmanager->initHooks(array($staticMemo->element.'dao'));
1431 $parameters = array(
1432 'contextTabMapping' => & $contextTabMapping,
1433 'onlyActiveModules' => $onlyActiveModules
1434 );
1435
1436 $reshook = $hookmanager->executeHooks('getAvailableMemoContextMapping', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
1437 if ($reshook > 0) {
1438 return $hookmanager->resArray;
1439 }
1440
1441 return $contextTabMapping;
1442 }
1443
1444
1450 public static function getAvailableMemoContext()
1451 {
1452 global $db,$action, $hookmanager;
1453
1454 $contextMapping = self::getAvailableMemoContextMapping();
1455 $list = array_keys($contextMapping);
1456
1457 $staticMemo = new self($db);
1458 $hookmanager->initHooks(array($staticMemo->element.'dao'));
1459 $parameters = array(
1460 'list' => & $list
1461 );
1462 $object = null; // @phan-suppress-next-line PhanPluginConstantVariableNull
1463 $reshook = $hookmanager->executeHooks('getAvailableMemoContext', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
1464 if ($reshook > 0) {
1465 $list = $hookmanager->resArray;
1466 }
1467
1468 // Security check
1469 $result = [];
1470 foreach ($list as $k => $v) {
1471 if (!is_string($v)) {
1472 continue;
1473 }
1474 if (strlen($v) > 64) {
1475 continue;
1476 }
1477 if (preg_match('/^[a-zA-Z0-9_]+$/', $k) !== 1) {
1478 continue;
1479 }
1480 $result[] = $v;
1481 }
1482
1483 return $result;
1484 }
1485
1486
1497 public function countArchivedMemoQuery($element_type, $element_id, $context, $id = 0)
1498 {
1499 global $user;
1500
1501 $sql = 'SELECT COUNT(m.rowid) nb
1502 FROM '.MAIN_DB_PREFIX.$this->table_element.' m
1503 WHERE m.entity IN ('.getEntity(self::getEntityElementKey($element_type)).')
1504 AND m.element_type = \''.$this->db->escape($element_type).'\'
1505 AND ( m.fk_element = '.(int) $element_id.' OR m.shared_on_element = 1 )
1506 AND m.context_tab = \''.$this->db->escape($context).'\'
1507 AND m.status = '.Memo::STATUS_ARCHIVED.'
1508 AND (m.private = 0 OR m.fk_user_creat = '.(int) $user->id.')
1509 ';
1510
1511 if ((int) $id > 0) {
1512 $sql .= ' AND m.rowid = ' . (int) $id;
1513 }
1514
1515 $obj = $this->db->getRow($sql);
1516 if (!$obj) {
1517 return false;
1518 }
1519
1520 return (int) $obj->nb;
1521 }
1522
1533 public function getMemosQuery($element_type, $element_id, $context, $id = 0)
1534 {
1535 global $user;
1536
1537 $sql = 'SELECT m.rowid, m.quick_note, m.pos_x, m.pos_y, m.pos_w, m.pos_h, m.pos_z, m.color, m.fk_user_creat, m.fk_user_modif, m.shared_on_element, m.date_creation, m.tms, m.private,
1538 mu.pos_x as user_pos_x, mu.pos_y as user_pos_y, mu.pos_w as user_pos_w, mu.pos_h as user_pos_h, mu.pos_z as user_pos_z
1539 FROM '.MAIN_DB_PREFIX.$this->table_element.' m
1540 LEFT JOIN '.MAIN_DB_PREFIX.$this->table_element.'_user mu
1541 ON mu.fk_memo = m.rowid
1542 AND mu.fk_user = '.(int) $user->id.'
1543 WHERE m.entity IN ('.getEntity(self::getEntityElementKey($element_type)).')
1544 AND m.element_type = \''.$this->db->escape($element_type).'\'
1545 AND ( m.fk_element = '.(int) $element_id.' OR m.shared_on_element = 1 )
1546 AND m.context_tab = \''.$this->db->escape($context).'\'
1547 AND m.status = '.self::STATUS_VALIDATED.'
1548 AND (COALESCE(m.private, 0) = 0 OR m.fk_user_creat = '.(int) $user->id.')
1549 ';
1550
1551 if ((int) $id > 0) {
1552 $sql .= ' AND m.rowid = ' . (int) $id;
1553 }
1554
1555 $sql .= ' ORDER BY COALESCE(mu.pos_z, m.pos_z) ASC';
1556 return $sql;
1557 }
1558
1559
1569 public function getTemplateMemosQuery($element_type, $context_tab = '', $id = 0)
1570 {
1571 global $user;
1572
1573 $sql = 'SELECT m.rowid, m.quick_note, m.pos_x, m.pos_y, m.pos_w, m.pos_h, m.color, m.pos_z,
1574 m.fk_user_creat, m.fk_user_modif, m.shared_on_element, m.date_creation, m.tms, m.private, m.name_tpl,m.rank_tpl,
1575 mu.pos_x as user_pos_x, mu.pos_y as user_pos_y, mu.pos_w as user_pos_w, mu.pos_h as user_pos_h, mu.pos_z as user_pos_z
1576 FROM '.MAIN_DB_PREFIX.$this->table_element.' m
1577 LEFT JOIN '.MAIN_DB_PREFIX.$this->table_element.'_user mu
1578 ON mu.fk_memo = m.rowid
1579 AND mu.fk_user = '.(int) $user->id.'
1580 WHERE m.entity IN ('.getEntity($this->element).')
1581 AND m.element_type IN (\''.$this->db->escape($element_type).'\', \'\')
1582 AND m.status = '.self::STATUS_TPL.'
1583 AND (COALESCE(m.private_tpl, 0) = 0 OR m.fk_user_creat = '.(int) $user->id.')
1584 ';
1585
1586 if (!empty($context_tab)) {
1587 //$sql.= ' AND (m.context_tab = \''.$this->db->escape($context_tab).'\' OR m.element_type = \'\' ) ';
1588 }
1589
1590 if ((int) $id > 0) {
1591 $sql .= ' AND m.rowid = ' . (int) $id;
1592 }
1593
1594 $sql .= " ORDER BY m.rank_tpl DESC, m.rowid ASC "; // Due to multiple type of sort panel rank_tpl is reversed higher is first and rowid ASC to keep last add is last
1595
1596 return $sql;
1597 }
1598
1612 public function showOutputField($val, $key, $value, $moreparam = '', $keysuffix = '', $keyprefix = '', $morecss = '')
1613 {
1614 global $conf, $langs, $form;
1615
1616 if ($key == 'color' && self::checkColor($value)) {
1617 $badgeBase = colorIsLight($value) ? 'badge-light' : 'badge-dark';
1618 return '<span class="badge badge-pill '.$badgeBase.'" style="background-color: '.$value.'" >'.$value.'</span>';
1619 }
1620
1621 if ($key == 'quick_note') {
1622 return nl2br(htmlentities($value));
1623 }
1624
1625 return parent::showOutputField($val, $key, $value, $moreparam, $keysuffix, $keyprefix, $morecss);
1626 }
1627
1634 public static function loadQuickMemoJsInterface($jsConfVars)
1635 {
1636 global $user;
1637
1638 if (!isModEnabled('quickmemo')) {
1639 return false;
1640 }
1641
1642 // DO NOT LOAD TWICE
1643 if (defined('QUICKMEMOJS')) {
1644 return false;
1645 }
1646
1647 if (defined('NOREQUIRETRAN') || empty($user) || empty($user->id) || (int) $user->socid > 0) {
1648 return false;
1649 }
1650
1651 if (!$user->hasRight('quickmemo', 'memo', 'read')) {
1652 return false;
1653 }
1654
1655 // Do not show memos of an object the user is not allowed to read
1656 if (!empty($jsConfVars['elementType'])) {
1657 require_once __DIR__.'/../lib/quickmemo.lib.php';
1658 if (!quickMemoInterfaceCanAccessElement((string) $jsConfVars['elementType'], (int) ($jsConfVars['elementId'] ?? 0))) {
1659 return false;
1660 }
1661 }
1662
1663 $autoResizeFontMin = getDolGlobalFloat('QUICKMEMO_AUTO_RESIZE_MIN_FONT_SIZE', 1);
1664 $autoResizeFontMax = getDolGlobalFloat('QUICKMEMO_AUTO_RESIZE_MAX_FONT_SIZE', 1.4);
1665
1666 // Apply safety limits
1667 $autoResizeFontMin = max($autoResizeFontMin, 0.3);
1668 $autoResizeFontMax = min($autoResizeFontMax, 5);
1669
1670 // Ensure min value is always lower than max value
1671 if ($autoResizeFontMin >= $autoResizeFontMax) {
1672 $autoResizeFontMin = max(0.3, $autoResizeFontMax - 0.1);
1673 }
1674
1675 $defaultJsConfVars = [
1676 'interfaceUrl' => dol_buildpath('quickmemo/interface.php', 1),
1677 'archivesUrl' => dol_buildpath('quickmemo/memo_list.php', 1) . '?mode=kanban&search_status='.Memo::STATUS_ARCHIVED . ($jsConfVars['archivesUrlParams'] ?? ''),
1678 'elementId' => 0,
1679 'elementType' => '',
1680 'context' => null,
1681 'token' => currentToken(),
1682 'colors' => Memo::getColorPreset(),
1683 'userReadRight' => $user->hasRight('quickmemo', 'memo', 'read'),
1684 'userWriteRight' => $user->hasRight('quickmemo', 'memo', 'write'),
1685 'userDeleteRight' => $user->hasRight('quickmemo', 'memo', 'delete'),
1686 'autoResizeFontSize' => !getDolGlobalInt('QUICKMEMO_DISABLE_AUTO_RESIZE_FONT_SIZE'),
1687 'autoResizeFontMin' => $autoResizeFontMin,
1688 'autoResizeFontMax' => $autoResizeFontMax,
1689 ];
1690 $jsConfVars = array_merge($defaultJsConfVars, $jsConfVars);
1691
1692 if (!empty($jsConfVars['elementType'])) {
1693 $jsConfVars['shareBtnStatus'] = 1;
1694 }
1695
1696 // LOAD Memo class
1697 print '<link rel="stylesheet" type="text/css" href="'.dol_buildpath('quickmemo/css/memo.css', 1) . '">'."\n";
1698 print '<link rel="stylesheet" type="text/css" href="'.dol_buildpath('quickmemo/css/memo-dialog.css', 1) . '">'."\n";
1699 print '<script nonce="'.getNonce().'" src="'.dol_buildpath('quickmemo/js/QuickMemo.js', 1).'" ></script>'."\n";
1700
1701 print '<script nonce="'.getNonce().'">
1702 document.addEventListener(\'Dolibarr:Ready\', function() {
1703 if(!Dolibarr.checkToolExist(\'quickMemo\')) {
1704 Dolibarr.defineTool(\'quickMemo\', new QuickMemo('.json_encode($jsConfVars).') );
1705 }
1706 });
1707 </script>'."\n";
1708
1709 define('QUICKMEMOJS', true);
1710 return true;
1711 }
1712
1720 public function getJsMemo(User $currentUser)
1721 {
1722 global $langs;
1723
1724 $memo = self::getJsMemoDefault();
1725 $memo->id = $this->id;
1726 $memo->color = $this->color;
1727 $memo->note = $this->quick_note;
1728
1729 $memo->pos_x = (int) $this->pos_x;
1730 $memo->pos_y = (int) $this->pos_y;
1731 $memo->pos_w = (int) $this->pos_w;
1732 $memo->pos_h = (int) $this->pos_h;
1733
1734 if ($currentUser->id != $memo->fk_user_creat) {
1735 // TODO update positions
1736 }
1737
1738 $memo->shared_on_element = $this->shared_on_element;
1739 $memo->private = (int) $this->private;
1740 $memo->date_creation = dol_print_date($this->date_creation, '%d/%m/%Y %H:%M', 'tzuserrel');
1741 $memo->date_change = '';
1742 if (!empty($this->tms) && ((int) $this->date_creation !== (int) $this->tms || (int) $this->fk_user_modif > 0)) {
1743 $memo->date_change = dol_print_date($this->tms, '%d/%m/%Y %H:%M', 'tzuserrel');
1744 }
1745
1746 $memo->fk_user_creat = $this->fk_user_creat;
1747 $memo->user_name = '';
1748 if ((int) $this->fk_user_creat > 0) {
1749 $userCreate = new User($this->db);
1750 if ($userCreate->fetch((int) $this->fk_user_creat) > 0) {
1751 $memo->user_name = $userCreate->getFullName($langs);
1752 }
1753 }
1754
1755 $memo->fk_user_modif = $this->fk_user_modif;
1756 $memo->user_change_name = '';
1757 if ((int) $this->fk_user_modif > 0) {
1758 $userMod = new User($this->db);
1759 if ($userMod->fetch((int) $this->fk_user_modif) > 0) {
1760 $memo->user_change_name = $userMod->getFullName($langs);
1761 }
1762 }
1763
1764 return $memo;
1765 }
1766
1772 public function isInCurrentEntity()
1773 {
1774 // Without multicompany, field entity is removed by constructor and all memos are in entity 1
1775 if (!isModEnabled('multicompany')) {
1776 return true;
1777 }
1778
1779 $entityKey = ($this->status == self::STATUS_TPL ? $this->element : self::getEntityElementKey((string) $this->element_type));
1780
1781 return in_array((int) $this->entity, array_map('intval', explode(',', getEntity($entityKey))), true);
1782 }
1783
1792 public static function getEntityElementKey($element_type)
1793 {
1794 return empty($element_type) ? 'memo' : $element_type;
1795 }
1796
1802 public static function getJsMemoDefault()
1803 {
1804 $memo = new stdClass();
1805 $memo->id = null;
1806 $memo->color = null;
1807 $memo->note = null;
1808 $memo->pos_x = 0;
1809 $memo->pos_y = 0;
1810 $memo->pos_w = 0;
1811 $memo->pos_h = 0;
1812 $memo->shared_on_element = 0;
1813 $memo->private = 0;
1814 $memo->date_creation = '';
1815 $memo->date_change = '';
1816 $memo->fk_user_creat = null;
1817 $memo->user_name = '';
1818 $memo->fk_user_modif = null;
1819 $memo->user_change_name = '';
1820 return $memo;
1821 }
1822}
write(string $newInnerBlock)
Replace the whole permissions block, markers included, in a single write.
$id
Support class for third parties, contacts, members, users or resources.
Definition account.php:47
if(! $sortfield) if(! $sortorder) $object
Definition account.php:100
$propal type
'integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter[:Sortfield]]]',...
Definition propal.php:281
$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:
setErrorsFromObject($object)
setErrorsFromObject
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.
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.
Class to manage Dolibarr database access.
Class for Memo.
static loadQuickMemoJsInterface($jsConfVars)
Load the Javascript interface for QuickMemo.
$fields
'type' field format: 'integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter[:Sortf...
static getAvailableMemoContext()
Get available memo context.
createFromClone(User $user, $fromid)
Clone an object into another one.
create(User $user, $notrigger=0)
Create object into database.
static getAvailableMemoContextMapping($object=null, $onlyActiveModules=true)
Get available memo context.
fetchAll($sortorder='', $sortfield='', $limit=1000, $offset=0, string $filter='', $filtermode='AND')
Load list of objects in memory from the database.
getJsMemo(User $currentUser)
Get JS memo.
update(User $user, $notrigger=0)
Update object into database.
static getJsMemoDefault()
Get JS memo default.
showOutputField($val, $key, $value, $moreparam='', $keysuffix='', $keyprefix='', $morecss='')
Return HTML string to show a field into a page Code very similar with showOutputField of extra fields...
getMemosQuery($element_type, $element_id, $context, $id=0)
Get memos query.
fetch($id, $ref=null, $noextrafields=0, $nolines=0)
Load object in memory from the database.
__construct(DoliDB $db)
Constructor.
fetchLines($noextrafields=0)
Load object lines in memory from the database.
static getMemoContext($context, $object=null)
Get memo context.
isInCurrentEntity()
Check that the memo (loaded with fetch(), which does not filter on entity) belongs to an entity visib...
static getColorPreset()
Get color preset.
getNomUrl($withpicto=0, $option='', $notooltip=0, $morecss='', $save_lastsearch_value=-1)
Return a link to the object card (with optionally the picto)
static getEntityElementKey($element_type)
Element key to use with getEntity() for memos of an element type.
validate($user, $notrigger=0)
Validate object.
updatePosition(User $user, int $x, int $y, int $w, int $h, int $z)
Update position of a memo for a specific user.
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_now($mode='gmt')
Return date for now.
getDolGlobalFloat($key, $default=0)
Return a Dolibarr global constant float value.
currentToken()
Return the value of token currently saved into session with name 'token'.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
forgeSQLFromUniversalSearchCriteria($filter, &$errorstr='', $noand=0, $nopar=0, $noerror=0, $forbiddenfields=array())
forgeSQLFromUniversalSearchCriteria
colorIsLight($stringcolor)
Return true if the color is light.
dol_buildpath($path, $type=0, $returnemptyifnotfound=0)
Return path of url or filesystem.
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false, $decorate=0)
Output date in a string format according to outputlangs (or langs if not defined).
isModEnabled($module)
Is Dolibarr module enabled.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
getEntity($element, $shared=1, $currentobject=null)
Get list of entity id to use.
if(!defined( 'CSRFCHECK_WITH_TOKEN'))
Build the customer statement lines (invoices and payments) with running balance.
quickMemoInterfaceCanAccessElement($element_type, $element_id, $moduleLevelOnly=false)
Check that current user can read the object a memo is attached to.
$conf db name
Only used if Module[ID]Name translation string is not found.
Definition repair.php:165