dolibarr 25.0.0-alpha
myobject.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-2025 Frédéric France <frederic.france@free.fr>
4 * Copyright (C) ---Replace with your own copyright and developer email---
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';
28require_once DOL_DOCUMENT_ROOT . '/core/lib/functions.lib.php';
29//require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php';
30//require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
31
36{
40 public $module = 'mymodule';
41
45 public $element = 'myobject';
46
51 public $TRIGGER_PREFIX = 'MYMODULE_MYOBJECT'; // Will be used to build trigger keys 'MYMODULE_MYOBJECT_MODIFY', ...
52
56 public $table_element = 'mymodule_myobject';
57
61 //public $element_for_permission = 'mymodule';
62
66 public $picto = 'fa-file';
67
71 public $isextrafieldmanaged = 0;
72
77 public $ismultientitymanaged = 0;
78 // BEGIN MODULEBUILDER ACCESSPOLICY
79 // END MODULEBUILDER ACCESSPOLICY
80
81
82 const STATUS_DRAFT = 0;
83 const STATUS_VALIDATED = 1;
84 const STATUS_CANCELED = 9;
85
131 // BEGIN MODULEBUILDER PROPERTIES
136 public $fields = array(
137 'rowid' => array('type' => 'integer', 'label' => 'TechnicalID', 'enabled' => 1, 'position' => 1, 'notnull' => 1, 'visible' => -1, 'noteditable' => 1, 'index' => 1, 'css' => 'left', 'comment' => 'Id', 'lang' => 'mymodule@mymodule'),
138 'ref' => array('type' => 'varchar(128)', 'label' => 'Ref', 'enabled' => 1, 'position' => 15, 'notnull' => 1, 'visible' => 1, 'index' => 1, 'searchall' => 1, 'showoncombobox' => 1, 'validate' => 1, 'comment' => 'Reference of object', 'lang' => 'mymodule@mymodule'),
139 'entity' => array('type' => 'integer', 'label' => 'Entity', 'default' => '1', 'enabled' => 1, 'visible' => 0, 'notnull' => 1, 'position' => 20, 'index' => 1),
140 'label' => array('type' => 'varchar(255)', 'label' => 'Label', 'enabled' => 1, 'position' => 30, 'notnull' => 0, 'visible' => 1, 'alwayseditable' => 1, 'searchall' => 1, 'css' => 'minwidth300', 'cssview' => 'wordbreak', 'help' => 'Help text', 'showoncombobox' => 2, 'validate' => 1, 'lang' => 'mymodule@mymodule'),
141 'amount' => array('type' => 'price', 'label' => 'Amount', 'enabled' => 1, 'position' => 40, 'notnull' => 0, 'visible' => 1, 'default' => 'null', 'isameasure' => 1, 'help' => 'Help text for amount', 'validate' => 1, 'lang' => 'mymodule@mymodule'),
142 'qty' => array('type' => 'real', 'label' => 'Qty', 'enabled' => 1, 'position' => 45, 'notnull' => 0, 'visible' => 1, 'default' => '0', 'isameasure' => 1, 'css' => 'maxwidth75imp', 'help' => 'Help text for quantity', 'validate' => 1, 'lang' => 'mymodule@mymodule'),
143 'fk_soc' => array('type' => 'integer:Societe:societe/class/societe.class.php:1:((status:=:1) AND (entity:IN:__SHARED_ENTITIES__))', 'label' => 'ThirdParty', 'picto' => 'company', 'enabled' => 'isModEnabled("societe")', 'position' => 50, 'notnull' => -1, 'visible' => 1, 'index' => 1, 'css' => 'maxwidth500 widthcentpercentminusxx', 'csslist' => 'tdoverflowmax150', 'help' => 'OrganizationEventLinkToThirdParty', 'validate' => 1, 'lang' => 'mymodule@mymodule'),
144 'fk_project' => array('type' => 'integer:Project:projet/class/project.class.php:1', 'label' => 'Project', 'picto' => 'project', 'enabled' => 'isModEnabled("project")', 'position' => 52, 'notnull' => -1, 'visible' => -1, 'index' => 1, 'css' => 'maxwidth500 widthcentpercentminusxx', 'csslist' => 'tdoverflowmax150', 'validate' => 1, 'lang' => 'mymodule@mymodule'),
145 'description' => array('type' => 'text', 'label' => 'Description', 'enabled' => 1, 'position' => 60, 'notnull' => 0, 'visible' => 3, 'validate' => 1, 'lang' => 'mymodule@mymodule'),
146 'note_public' => array('type' => 'html', 'label' => 'NotePublic', 'enabled' => 1, 'position' => 61, 'notnull' => 0, 'visible' => 0, 'cssview' => 'wordbreak', 'validate' => 1, 'lang' => 'mymodule@mymodule'),
147 'note_private' => array('type' => 'html', 'label' => 'NotePrivate', 'enabled' => 1, 'position' => 62, 'notnull' => 0, 'visible' => 0, 'cssview' => 'wordbreak', 'validate' => 1, 'lang' => 'mymodule@mymodule'),
148 'date_creation' => array('type' => 'datetime', 'label' => 'DateCreation', 'enabled' => 1, 'position' => 500, 'notnull' => 1, 'visible' => -2, 'lang' => 'mymodule@mymodule'),
149 'tms' => array('type' => 'timestamp', 'label' => 'DateModification', 'enabled' => 1, 'position' => 501, 'notnull' => 0, 'visible' => -2, 'lang' => 'mymodule@mymodule'),
150 'fk_user_creat' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserAuthor', 'picto' => 'user', 'enabled' => 1, 'position' => 510, 'notnull' => 1, 'visible' => -2, 'foreignkey' => '0', 'csslist' => 'tdoverflowmax150', 'lang' => 'mymodule@mymodule'),
151 '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', 'lang' => 'mymodule@mymodule'),
152 'last_main_doc' => array('type' => 'varchar(255)', 'label' => 'LastMainDoc', 'enabled' => 1, 'position' => 600, 'notnull' => 0, 'visible' => 0, 'lang' => 'mymodule@mymodule'),
153 'import_key' => array('type' => 'varchar(14)', 'label' => 'ImportId', 'enabled' => 1, 'position' => 1000, 'notnull' => -1, 'visible' => -2, 'lang' => 'mymodule@mymodule'),
154 'model_pdf' => array('type' => 'varchar(255)', 'label' => 'Model pdf', 'enabled' => 1, 'position' => 1010, 'notnull' => -1, 'visible' => 0, 'lang' => 'mymodule@mymodule'),
155 'status' => array('type' => 'integer', 'label' => 'Status', 'enabled' => 1, 'position' => 2000, 'notnull' => 1, 'visible' => 1, 'index' => 1, 'arrayofkeyval' => array(0 => 'Draft', '1' => 'Validated', 9 => 'Canceled'), 'validate' => 1, 'lang' => 'mymodule@mymodule'),
156 );
157
161 public $rowid;
162
166 public $ref;
167
171 public $label;
172
176 public $amount;
177
181 public $socid; // both socid and fk_soc are used
185 public $fk_soc; // both socid and fk_soc are used
186
190 public $status;
191
195 public $fk_user_creat;
196
200 public $fk_user_modif;
201
205 public $last_main_doc;
206
210 public $import_key;
211 // END MODULEBUILDER PROPERTIES
212
213 //BEGIN MODULEBUILDER LINES
214 // If this object has a subtable with lines
215
219 public $table_element_line = 'mymodule_myobjectline';
220
224 public $fk_element = 'fk_myobject';
225
229 public $class_element_line = 'MyObjectline';
230
234 protected $childtables = array('mychildtable' => array('name' => 'MyObject', 'fk_element' => 'fk_myobject'));
235
241 protected $childtablesoncascade = array('mymodule_myobjectdet');
242
246 public $lines = array();
247
248 //END MODULEBUILDER LINES
249
255 public function __construct(DoliDB $db)
256 {
257 global $langs;
258
259 $this->db = $db;
260
261 if (!getDolGlobalInt('MAIN_SHOW_TECHNICAL_ID') && isset($this->fields['rowid']) && !empty($this->fields['ref'])) {
262 $this->fields['rowid']['visible'] = 0;
263 }
264 if (!isModEnabled('multicompany') && isset($this->fields['entity'])) {
265 $this->fields['entity']['enabled'] = 0;
266 }
267
268 // Example to show how to set values of fields definition dynamically
269 /*if ($user->hasRight('mymodule', 'myobject', 'read')) {
270 $this->fields['myfield']['visible'] = 1;
271 $this->fields['myfield']['noteditable'] = 0;
272 }*/
273
274 // Unset fields that are disabled
275 foreach ($this->fields as $key => $val) {
276 if (isset($val['enabled']) && empty($val['enabled'])) {
277 unset($this->fields[$key]);
278 }
279 }
280
281 // Translate some data of arrayofkeyval
282 if (is_object($langs)) {
283 foreach ($this->fields as $key => $val) {
284 if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
285 foreach ($val['arrayofkeyval'] as $key2 => $val2) {
286 $this->fields[$key]['arrayofkeyval'][$key2] = $langs->trans($val2);
287 }
288 }
289 }
290 }
291 }
292
300 public function create(User $user, $notrigger = 0)
301 {
302 $result = $this->createCommon($user, $notrigger);
303
304 // uncomment lines below if you want to validate object after creation
305 // if ($result > 0) {
306 // $this->fetch($this->id); // needed to retrieve some fields (ie date_creation for masked ref)
307 // $resultupdate = $this->validate($user, $notrigger);
308 // if ($resultupdate < 0) { return $resultupdate; }
309 // }
310
311 return $result;
312 }
313
321 public function createFromClone(User $user, $fromid)
322 {
323 global $langs, $extrafields;
324 $error = 0;
325
326 dol_syslog(__METHOD__, LOG_DEBUG);
327
328 $object = new self($this->db);
329
330 $this->db->begin();
331
332 // Load source object
333 $result = $object->fetchCommon($fromid);
334
335 //BEGIN MODULEBUILDER LINES
336 if ($result > 0 && !empty($object->table_element_line)) {
337 $object->fetchLines();
338 }
339
340 // get lines so they will be clone
341 foreach ($this->lines as $line) {
342 $line->fetch_optionals();
343 }
344 //END MODULEBUILDER LINES
345
346 $fromref = (property_exists($object, 'ref') ? $object->ref : ''); // Save ref of source object before it is overwritten
347
348 // Reset some properties
349 unset($object->id);
350 unset($object->fk_user_creat);
351 unset($object->import_key);
352
353 // Clear fields
354 if (property_exists($object, 'ref')) {
355 $object->ref = empty($this->fields['ref']['default']) ? "Copy_Of_".$object->ref : $this->fields['ref']['default'];
356 }
357 if (property_exists($object, 'label')) {
358 $object->label = empty($this->fields['label']['default']) ? $langs->trans("CopyOf")." ".$object->label : $this->fields['label']['default'];
359 }
360 if (property_exists($object, 'status')) {
361 $object->status = self::STATUS_DRAFT;
362 }
363 if (property_exists($object, 'date_creation')) {
364 $object->date_creation = dol_now();
365 }
366 if (property_exists($object, 'date_modification')) {
367 $object->date_modification = null;
368 }
369 // ...
370 // Clear extrafields that are unique
371 if (is_array($object->array_options) && count($object->array_options) > 0) {
372 $extrafields->fetch_name_optionals_label($this->table_element);
373 foreach ($object->array_options as $key => $option) {
374 $shortkey = preg_replace('/options_/', '', $key);
375 if (!empty($extrafields->attributes[$this->table_element]['unique'][$shortkey])) {
376 //var_dump($key);
377 //var_dump($clonedObj->array_options[$key]); exit;
378 unset($object->array_options[$key]);
379 }
380 }
381 }
382
383 // Create clone
384 $object->context['createfromclone'] = 'createfromclone';
385 $object->context['createfromclone_fromid'] = $fromid;
386 $object->context['createfromclone_fromref'] = $fromref;
387 $result = $object->createCommon($user);
388 if ($result < 0) {
389 $error++;
391 }
392
393 if (!$error) {
394 // copy internal contacts
395 if ($this->copy_linked_contact($object, 'internal') < 0) {
396 $error++;
397 }
398 }
399
400 if (!$error) {
401 // copy external contacts if same company
402 if (!empty($object->socid) && ((property_exists($this, 'fk_soc') && ($this->fk_soc == $object->socid)) || (property_exists($this, 'socid') && ($this->socid == $object->socid)))) { // @phpstan-ignore-line
403 if ($this->copy_linked_contact($object, 'external') < 0) {
404 $error++;
405 }
406 }
407 }
408
409 unset($object->context['createfromclone']);
410 unset($object->context['createfromclone_fromid']);
411 unset($object->context['createfromclone_fromref']);
412
413 // End
414 if (!$error) {
415 $this->db->commit();
416 return $object;
417 } else {
418 $this->db->rollback();
419 return -1;
420 }
421 }
422
432 public function fetch($id, $ref = null, $noextrafields = 0, $nolines = 0)
433 {
434 $result = $this->fetchCommon($id, $ref, '', $noextrafields);
435 //BEGIN MODULEBUILDER LINES
436 if ($result > 0 && !empty($this->table_element_line) && empty($nolines)) {
437 $this->fetchLines($noextrafields);
438 }
439 //END MODULEBUILDER LINES
440 return $result;
441 }
442
443 //BEGIN MODULEBUILDER LINES
450 public function fetchLines($noextrafields = 0)
451 {
452 $this->lines = array();
453
454 $result = $this->fetchLinesCommon('', $noextrafields);
455 return $result;
456 }
457 //END MODULEBUILDER LINES
472 public function fetchAll($sortorder = '', $sortfield = '', $limit = 1000, $offset = 0, string $filter = '', $filtermode = 'AND')
473 {
474 dol_syslog(__METHOD__, LOG_DEBUG);
475
476 $records = array();
477
478 $sql = "SELECT ";
479 $sql .= $this->getFieldList('t');
480 $sql .= " FROM ".$this->db->prefix().$this->table_element." as t";
481 if (!empty($this->isextrafieldmanaged) && $this->isextrafieldmanaged == 1) {
482 $sql .= " LEFT JOIN ".$this->db->prefix().$this->table_element."_extrafields as te ON te.fk_object = t.rowid";
483 }
484 if (!empty($this->ismultientitymanaged) && (int) $this->ismultientitymanaged == 1) {
485 $sql .= " WHERE t.entity IN (".getEntity($this->element).")";
486 } elseif (preg_match('/^\w+@\w+$/', (string) $this->ismultientitymanaged)) {
487 $tmparray = explode('@', (string) $this->ismultientitymanaged);
488 $sql .= " LEFT JOIN ".$this->db->prefix().$this->db->sanitize($tmparray[1])." as pt ON t.".$this->db->sanitize($tmparray[0])." = pt.rowid";
489 $sql .= " WHERE pt.entity IN (".getEntity($this->element).")";
490 } else {
491 $sql .= " WHERE 1 = 1";
492 }
493
494 // Manage filter
495 $errormessage = '';
496 $sql .= forgeSQLFromUniversalSearchCriteria($filter, $errormessage);
497 if ($errormessage) {
498 $this->errors[] = $errormessage;
499 dol_syslog(__METHOD__.' '.implode(',', $this->errors), LOG_ERR);
500 return -1;
501 }
502
503 if (!empty($sortfield)) {
504 $sql .= $this->db->order($sortfield, $sortorder);
505 }
506 if (!empty($limit)) {
507 $sql .= $this->db->plimit($limit, $offset);
508 }
509
510 $resql = $this->db->query($sql);
511 if ($resql) {
512 $num = $this->db->num_rows($resql);
513 $i = 0;
514 while ($i < ($limit ? min($limit, $num) : $num)) {
515 $obj = $this->db->fetch_object($resql);
516
517 $record = new self($this->db);
518 $record->setVarsFromFetchObj($obj);
519
520 if (!empty($record->isextrafieldmanaged)) {
521 $record->fetch_optionals();
522 }
523
524 $records[$record->id] = $record;
525
526 $i++;
527 }
528 $this->db->free($resql);
529
530 return $records;
531 } else {
532 $this->errors[] = 'Error '.$this->db->lasterror();
533 dol_syslog(__METHOD__.' '.implode(',', $this->errors), LOG_ERR);
534
535 return -1;
536 }
537 }
538
546 public function update(User $user, $notrigger = 0)
547 {
548 return $this->updateCommon($user, $notrigger);
549 }
550
558 public function delete(User $user, $notrigger = 0)
559 {
560 return $this->deleteCommon($user, $notrigger);
561 //return $this->deleteCommon($user, $notrigger, 1);
562 }
563
564 //BEGIN MODULEBUILDER LINES
573 public function deleteLine(User $user, $idline, $notrigger = 0)
574 {
575 if ($this->status < 0) {
576 $this->error = 'ErrorDeleteLineNotAllowedByObjectStatus';
577 return -2;
578 }
579
580 return $this->deleteLineCommon($user, $idline, $notrigger);
581 }
582 //END MODULEBUILDER LINES
583
584
592 public function validate($user, $notrigger = 0)
593 {
594 global $conf;
595
596 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
597
598 $error = 0;
599
600 // Protection
601 if ($this->status == self::STATUS_VALIDATED) {
602 dol_syslog(get_class($this)."::validate action abandoned: already validated", LOG_WARNING);
603 return 0;
604 }
605
606 /* if (! ((!getDolGlobalInt('MAIN_USE_ADVANCED_PERMS') && $user->hasRight('mymodule', 'myobject', 'write'))
607 || (getDolGlobalInt('MAIN_USE_ADVANCED_PERMS') && $user->hasRight('mymodule', 'myobject_advance', 'validate')))
608 {
609 $this->error='NotEnoughPermissions';
610 dol_syslog(get_class($this)."::valid ".$this->error, LOG_ERR);
611 return -1;
612 }*/
613
614 $now = dol_now();
615
616 $this->db->begin();
617
618 // Define new ref
619 if (preg_match('/^[\‍(]?PROV/i', $this->ref) || empty($this->ref)) { // empty should not happened, but when it occurs, the test save life
620 $num = $this->getNextNumRef();
621 } else {
622 $num = (string) $this->ref;
623 }
624 $this->newref = $num;
625
626 if (!empty($num)) {
627 // Validate
628 $sql = "UPDATE ".$this->db->prefix().$this->table_element;
629 $sql .= " SET ";
630 if (!empty($this->fields['ref'])) {
631 $sql .= " ref = '".$this->db->escape($num)."',";
632 }
633 $sql .= " status = ".self::STATUS_VALIDATED;
634 if (!empty($this->fields['date_validation'])) {
635 $sql .= ", date_validation = '".$this->db->idate($now)."'";
636 }
637 if (!empty($this->fields['fk_user_valid'])) {
638 $sql .= ", fk_user_valid = ".((int) $user->id);
639 }
640 $sql .= " WHERE rowid = ".((int) $this->id);
641
642 dol_syslog(get_class($this)."::validate()", LOG_DEBUG);
643 $resql = $this->db->query($sql);
644 if (!$resql) {
645 dol_print_error($this->db);
646 $this->error = $this->db->lasterror();
647 $error++;
648 }
649
650 if (!$error && !$notrigger) {
651 // Call trigger
652 $result = $this->call_trigger('MYMODULE_MYOBJECT_VALIDATE', $user);
653 if ($result < 0) {
654 $error++;
655 }
656 // End call triggers
657 }
658 }
659
660 if (!$error) {
661 $this->oldref = $this->ref;
662
663 // Rename directory if dir was a temporary ref
664 if (preg_match('/^[\‍(]?PROV/i', $this->ref)) {
665 // Now we rename also files into index
666 $sql = 'UPDATE '.$this->db->prefix()."ecm_files set filename = CONCAT('".$this->db->escape($this->newref)."', SUBSTR(filename, ".(dol_strlen($this->ref) + 1).")), filepath = 'myobject/".$this->db->escape($this->newref)."'";
667 $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'myobject/".$this->db->escape($this->ref)."' and entity = ".((int) $conf->entity);
668 $resql = $this->db->query($sql);
669 if (!$resql) {
670 $error++;
671 $this->error = $this->db->lasterror();
672 }
673 $sql = 'UPDATE '.$this->db->prefix()."ecm_files set filepath = 'myobject/".$this->db->escape($this->newref)."'";
674 $sql .= " WHERE filepath = 'myobject/".$this->db->escape($this->ref)."' and entity = ".((int) $conf->entity);
675 $resql = $this->db->query($sql);
676 if (!$resql) {
677 $error++;
678 $this->error = $this->db->lasterror();
679 }
680
681 // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments
682 $oldref = dol_sanitizeFileName($this->ref);
683 $newref = dol_sanitizeFileName($num);
684 $dirsource = $conf->mymodule->dir_output.'/myobject/'.$oldref;
685 $dirdest = $conf->mymodule->dir_output.'/myobject/'.$newref;
686 if (!$error && file_exists($dirsource)) {
687 dol_syslog(get_class($this)."::validate() rename dir ".$dirsource." into ".$dirdest);
688
689 if (@rename($dirsource, $dirdest)) {
690 dol_syslog("Rename ok");
691 // Rename docs starting with $oldref with $newref
692 $listoffiles = dol_dir_list($conf->mymodule->dir_output.'/myobject/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/'));
693 foreach ($listoffiles as $fileentry) {
694 $dirsource = $fileentry['name'];
695 $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource);
696 $dirsource = $fileentry['path'].'/'.$dirsource;
697 $dirdest = $fileentry['path'].'/'.$dirdest;
698 @rename($dirsource, $dirdest);
699 }
700 }
701 }
702 }
703 }
704
705 // Set new ref and current status
706 if (!$error) {
707 $this->ref = $num;
708 $this->status = self::STATUS_VALIDATED;
709 }
710
711 if (!$error) {
712 $this->db->commit();
713 return 1;
714 } else {
715 $this->db->rollback();
716 return -1;
717 }
718 }
719
720
728 public function setDraft($user, $notrigger = 0)
729 {
730 // Protection
731 if ($this->status <= self::STATUS_DRAFT) {
732 return 0;
733 }
734
735 /* if (! ((!getDolGlobalInt('MAIN_USE_ADVANCED_PERMS') && $user->hasRight('mymodule','write'))
736 || (getDolGlobalInt('MAIN_USE_ADVANCED_PERMS') && $user->hasRight('mymodule','mymodule_advance','validate'))))
737 {
738 $this->error='Permission denied';
739 return -1;
740 }*/
741
742 return $this->setStatusCommon($user, self::STATUS_DRAFT, $notrigger, 'MYMODULE_MYOBJECT_UNVALIDATE');
743 }
744
752 public function cancel($user, $notrigger = 0)
753 {
754 // Protection
755 if ($this->status != self::STATUS_VALIDATED) {
756 return 0;
757 }
758
759 /* if (! ((!getDolGlobalInt('MAIN_USE_ADVANCED_PERMS') && $user->hasRight('mymodule','write'))
760 || (getDolGlobalInt('MAIN_USE_ADVANCED_PERMS') && $user->hasRight('mymodule','mymodule_advance','validate'))))
761 {
762 $this->error='Permission denied';
763 return -1;
764 }*/
765
766 return $this->setStatusCommon($user, self::STATUS_CANCELED, $notrigger, 'MYMODULE_MYOBJECT_CANCEL');
767 }
768
776 public function reopen($user, $notrigger = 0)
777 {
778 // Protection
779 if ($this->status == self::STATUS_VALIDATED) {
780 return 0;
781 }
782
783 /*if (! ((!getDolGlobalInt('MAIN_USE_ADVANCED_PERMS') && $user->hasRight('mymodule','write'))
784 || (getDolGlobalInt('MAIN_USE_ADVANCED_PERMS') && $user->hasRight('mymodule','mymodule_advance','validate'))))
785 {
786 $this->error='Permission denied';
787 return -1;
788 }*/
789
790 return $this->setStatusCommon($user, self::STATUS_VALIDATED, $notrigger, 'MYMODULE_MYOBJECT_REOPEN');
791 }
792
800 public function getTooltipContentArray($params)
801 {
802 global $langs;
803
804 $datas = [];
805
806 if (getDolGlobalInt('MAIN_OPTIMIZEFORTEXTBROWSER')) {
807 return ['optimize' => $langs->trans("ShowMyObject")];
808 }
809 $datas['picto'] = img_picto('', $this->picto).' <u>'.$langs->trans("MyObject").'</u>';
810 if (isset($this->status)) {
811 $datas['picto'] .= ' '.$this->getLibStatut(5);
812 }
813 if (property_exists($this, 'ref')) {
814 $datas['ref'] = '<br><b>'.$langs->trans('Ref').':</b> '.$this->ref;
815 }
816 if (property_exists($this, 'label')) {
817 $datas['label'] = '<br>'.$langs->trans('Label').':</b> '.$this->label;
818 }
819
820 return $datas;
821 }
822
833 public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $morecss = '', $save_lastsearch_value = -1)
834 {
835 global $conf, $langs, $hookmanager;
836
837 if (!empty($conf->dol_no_mouse_hover)) {
838 $notooltip = 1; // Force disable tooltips
839 }
840
841 $result = '';
842 $params = [
843 'id' => (string) $this->id,
844 'objecttype' => $this->element.($this->module ? '@'.$this->module : ''),
845 'option' => $option,
846 ];
847 $classfortooltip = 'classfortooltip';
848 $dataparams = '';
849 if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
850 $classfortooltip = 'classforajaxtooltip';
851 $dataparams = ' data-params="'.dol_escape_htmltag(json_encode($params)).'"';
852 $label = '';
853 } else {
854 $label = implode($this->getTooltipContentArray($params));
855 }
856
857 $baseurl = dol_buildpath('/mymodule/myobject_card.php', 1);
858 $query = ['id' => $this->id];
859 if ($option !== 'nolink') {
860 // Add param to save lastsearch_values or not
861 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
862 if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
863 $add_save_lastsearch_values = 1;
864 }
865 if ($add_save_lastsearch_values) {
866 $query = array_merge($query, ['save_lastsearch_values' => 1]);
867 }
868 }
869 $url = dolBuildUrl($baseurl, $query);
870
871 $linkclose = '';
872 if (empty($notooltip)) {
873 if (getDolGlobalInt('MAIN_OPTIMIZEFORTEXTBROWSER')) {
874 $label = $langs->trans("ShowMyObject");
875 $linkclose .= ' alt="'.dolPrintHTMLForAttribute($label).'"';
876 }
877 $linkclose .= ($label ? ' title="'.dolPrintHTMLForAttribute($label).'"' : ' title="tocomplete"');
878 $linkclose .= $dataparams.' class="'.$classfortooltip.($morecss ? ' '.$morecss : '').'"';
879 } else {
880 $linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
881 }
882
883 if ($option == 'nolink') {
884 $linkstart = '<span';
885 } else {
886 $linkstart = '<a href="'.$url.'"';
887 }
888 $linkstart .= $linkclose.'>';
889 if ($option == 'nolink') {
890 $linkend = '</span>';
891 } else {
892 $linkend = '</a>';
893 }
894
895 $result .= $linkstart;
896
897 if (empty($this->showphoto_on_popup)) {
898 if ($withpicto) {
899 $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), (($withpicto != 2) ? 'class="paddingright"' : ''), 0, 0, $notooltip ? 0 : 1);
900 }
901 } else {
902 if ($withpicto) {
903 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
904
905 list($class, $module) = explode('@', $this->picto);
906 $upload_dir = $conf->$module->multidir_output[$conf->entity]."/$class/".dol_sanitizeFileName($this->ref);
907 $filearray = dol_dir_list($upload_dir, "files");
908 $filename = $filearray[0]['name'];
909 if (!empty($filename)) {
910 $pospoint = strpos($filearray[0]['name'], '.');
911
912 $pathtophoto = $class.'/'.$this->ref.'/thumbs/'.dol_substr($filename, 0, $pospoint).'_mini'.dol_substr($filename, $pospoint);
913 if (!getDolGlobalString(dol_strtoupper($module.'_'.$class).'_FORMATLISTPHOTOSASUSERS')) {
914 $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>';
915 } else {
916 $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>';
917 }
918
919 $result .= '</div>';
920 } else {
921 $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'"'), 0, 0, $notooltip ? 0 : 1);
922 }
923 }
924 }
925
926 if ($withpicto != 2) {
927 $result .= $this->ref;
928 }
929
930 $result .= $linkend;
931 //if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : '');
932
933 global $action, $hookmanager;
934 $hookmanager->initHooks(array($this->element.'dao'));
935 $parameters = array('id' => $this->id, 'getnomurl' => &$result);
936 $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
937 if ($reshook > 0) {
938 $result = $hookmanager->resPrint;
939 } else {
940 $result .= $hookmanager->resPrint;
941 }
942
943 return $result;
944 }
945
953 public function getKanbanView($option = '', $arraydata = null)
954 {
955 global $conf, $langs;
956
957 $selected = (empty($arraydata['selected']) ? 0 : $arraydata['selected']);
958
959 $return = '<div class="box-flex-item box-flex-grow-zero">';
960 $return .= '<div class="info-box info-box-sm">';
961 $return .= '<span class="info-box-icon bg-infobox-action">';
962 $return .= img_picto('', $this->picto);
963 $return .= '</span>';
964 $return .= '<div class="info-box-content">';
965 $return .= '<span class="info-box-ref inline-block tdoverflowmax150 valignmiddle">'.(method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref).'</span>';
966 if ($selected >= 0) {
967 $return .= '<input id="cb'.$this->id.'" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="'.$this->id.'"'.($selected ? ' checked="checked"' : '').'>';
968 }
969 if (property_exists($this, 'label')) {
970 $return .= ' <div class="inline-block opacitymedium valignmiddle tdoverflowmax100">'.$this->label.'</div>';
971 }
972 if (property_exists($this, 'thirdparty') && is_object($this->thirdparty)) {
973 $return .= '<br><div class="info-box-ref tdoverflowmax150">'.$this->thirdparty->getNomUrl(1).'</div>';
974 }
975 if (property_exists($this, 'amount')) {
976 $return .= '<br>';
977 $return .= '<span class="info-box-label amount">'.price($this->amount, 0, $langs, 1, -1, -1, $conf->currency).'</span>';
978 }
979 if (method_exists($this, 'getLibStatut')) {
980 $return .= '<br><div class="info-box-status">'.$this->getLibStatut(3).'</div>';
981 }
982 $return .= '</div>';
983 $return .= '</div>';
984 $return .= '</div>';
985
986 return $return;
987 }
988
995 public function getLabelStatus($mode = 0)
996 {
997 return $this->LibStatut($this->status, $mode);
998 }
999
1006 public function getLibStatut($mode = 0)
1007 {
1008 return $this->LibStatut($this->status, $mode);
1009 }
1010
1011 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1019 public function LibStatut($status, $mode = 0)
1020 {
1021 // phpcs:enable
1022 if (is_null($status)) {
1023 return '';
1024 }
1025
1026 $paramsBadge = array('badgeParams' => array('attr' => array(
1027 'data-status-element' => $this->element,
1028 'data-status' => (int) $status
1029 )));
1030
1031
1032 if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
1033 global $langs;
1034 //$langs->load("mymodule@mymodule");
1035 // Build status labels from the 'status' field arrayofkeyval so that the badge (LibStatut),
1036 // the list filter and the select all show the same, configurable labels.
1037 if (!empty($this->fields['status']['arrayofkeyval']) && is_array($this->fields['status']['arrayofkeyval'])) {
1038 foreach ($this->fields['status']['arrayofkeyval'] as $statuskey => $statuslabel) {
1039 $this->labelStatus[$statuskey] = $langs->transnoentitiesnoconv($statuslabel);
1040 $this->labelStatusShort[$statuskey] = $langs->transnoentitiesnoconv($statuslabel);
1041 }
1042 }
1043 }
1044
1045 $statusType = 'status'.$status;
1046 //if ($status == self::STATUS_VALIDATED) $statusType = 'status1';
1047 if ($status == self::STATUS_CANCELED) {
1048 $statusType = 'status6';
1049 }
1050
1051 return dolGetStatus($this->labelStatus[$status] ?? '', $this->labelStatusShort[$status] ?? '', '', $statusType, $mode, '', $paramsBadge);
1052 }
1053
1060 public function info($id)
1061 {
1062 $sql = "SELECT t.rowid, t.date_creation as datec";
1063 if (!empty($this->isextrafieldmanaged) && $this->isextrafieldmanaged == 1) {
1064 $sql .= ", GREATEST(t.tms, COALESCE(te.tms, t.tms)) as datem";
1065 } else {
1066 $sql .= ", t.tms as datem";
1067 }
1068 if (!empty($this->fields['date_validation'])) {
1069 $sql .= ", t.date_validation as datev";
1070 }
1071 if (!empty($this->fields['fk_user_creat'])) {
1072 $sql .= ", t.fk_user_creat";
1073 }
1074 if (!empty($this->fields['fk_user_modif'])) {
1075 $sql .= ", t.fk_user_modif";
1076 }
1077 if (!empty($this->fields['fk_user_valid'])) {
1078 $sql .= ", t.fk_user_valid";
1079 }
1080 $sql .= " FROM ".$this->db->prefix().$this->table_element." as t";
1081 if (!empty($this->isextrafieldmanaged) && $this->isextrafieldmanaged == 1) {
1082 $sql .= " LEFT JOIN ".$this->db->prefix().$this->table_element."_extrafields as te ON te.fk_object = t.rowid";
1083 }
1084 $sql .= " WHERE t.rowid = ".((int) $id);
1085
1086 $result = $this->db->query($sql);
1087 if ($result) {
1088 if ($this->db->num_rows($result)) {
1089 $obj = $this->db->fetch_object($result);
1090
1091 $this->id = $obj->rowid;
1092
1093 if (!empty($this->fields['fk_user_creat'])) {
1094 $this->user_creation_id = $obj->fk_user_creat;
1095 }
1096 if (!empty($this->fields['fk_user_modif'])) {
1097 $this->user_modification_id = $obj->fk_user_modif;
1098 }
1099 if (!empty($this->fields['fk_user_valid'])) {
1100 $this->user_validation_id = $obj->fk_user_valid;
1101 }
1102 $this->date_creation = $this->db->jdate($obj->datec);
1103 $this->date_modification = empty($obj->datem) ? '' : $this->db->jdate($obj->datem);
1104 if (!empty($obj->datev)) {
1105 $this->date_validation = empty($obj->datev) ? '' : $this->db->jdate($obj->datev);
1106 }
1107 }
1108
1109 $this->db->free($result);
1110 } else {
1111 dol_print_error($this->db);
1112 }
1113 }
1114
1121 public function initAsSpecimen()
1122 {
1123 // Set here init that are not commonf fields
1124 // $this->property1 = ...
1125 // $this->property2 = ...
1126
1127 return $this->initAsSpecimenCommon();
1128 }
1129
1130 //BEGIN MODULEBUILDER LINES
1136 public function getLinesArray()
1137 {
1138 $this->lines = array();
1139
1140 $objectline = new MyObjectLine($this->db);
1141 $result = $objectline->fetchAll('ASC', 'position', 0, 0, '(fk_myobject:=:'.((int) $this->id).')');
1142
1143 if (is_numeric($result)) {
1144 $this->setErrorsFromObject($objectline);
1145 return $result;
1146 } else {
1148 $this->lines = $result;
1149 return $this->lines;
1150 }
1151 }
1152 //END MODULEBUILDER LINES
1153
1159 public function getNextNumRef()
1160 {
1161 global $langs, $conf;
1162 $langs->load("mymodule@mymodule");
1163
1164 if (!getDolGlobalString('MYMODULE_MYOBJECT_ADDON')) {
1165 $conf->global->MYMODULE_MYOBJECT_ADDON = 'mod_myobject_standard';
1166 }
1167
1168 if (getDolGlobalString('MYMODULE_MYOBJECT_ADDON')) {
1169 $mybool = false;
1170
1171 $file = getDolGlobalString('MYMODULE_MYOBJECT_ADDON').".php";
1172 $classname = getDolGlobalString('MYMODULE_MYOBJECT_ADDON');
1173
1174 // Include file with class
1175 $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
1176 foreach ($dirmodels as $reldir) {
1177 $dir = dol_buildpath($reldir."core/modules/mymodule/");
1178
1179 // Load file with numbering class (if found)
1180 $mybool = $mybool || @include_once $dir.$file;
1181 }
1182
1183 if (!$mybool) {
1184 dol_print_error(null, "Failed to include file ".$file);
1185 return '';
1186 }
1187
1188 if (class_exists($classname)) {
1189 $obj = new $classname();
1190 '@phan-var-force ModeleNumRefMyObject $obj';
1191 $numref = $obj->getNextValue($this);
1192
1193 if ($numref != '' && $numref != '-1') {
1194 return $numref;
1195 } else {
1196 $this->error = $obj->error;
1197 //dol_print_error($this->db,get_class($this)."::getNextNumRef ".$obj->error);
1198 return "";
1199 }
1200 } else {
1201 print $langs->trans("Error")." ".$langs->trans("ClassNotFound").' '.$classname;
1202 return "";
1203 }
1204 } else {
1205 print $langs->trans("ErrorNumberingModuleNotSetup", $this->element);
1206 return "";
1207 }
1208 }
1209
1221 public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
1222 {
1223 global $langs;
1224
1225 $result = 0;
1226 $includedocgeneration = 0;
1227
1228 $langs->load("mymodule@mymodule");
1229
1230 if (!dol_strlen($modele)) {
1231 if (!empty($this->model_pdf)) {
1232 $modele = $this->model_pdf;
1233 } else {
1234 $modele = getDolGlobalString('MYOBJECT_ADDON_PDF', 'standard_myobject');
1235 }
1236 }
1237
1238 $modelpath = "core/modules/mymodule/doc/";
1239
1240 if ($includedocgeneration && !empty($modele)) {
1241 $result = $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
1242 }
1243
1244 return $result;
1245 }
1246
1256 public function validateField($fields, $fieldKey, $fieldValue)
1257 {
1258 // Add your own validation rules here.
1259 // ...
1260
1261 return parent::validateField($fields, $fieldKey, $fieldValue);
1262 }
1263
1271 public function doScheduledJob()
1272 {
1273 //global $conf, $langs;
1274
1275 //$conf->global->SYSLOG_FILE = 'DOL_DATA_ROOT/dolibarr_mydedicatedlogfile.log';
1276
1277 $error = 0;
1278 $this->output = '';
1279 $this->error = '';
1280
1281 dol_syslog(__METHOD__." start", LOG_INFO);
1282
1283 //$now = dol_now();
1284
1285 $this->db->begin();
1286
1287 // ...
1288
1289 $this->db->commit();
1290
1291 dol_syslog(__METHOD__." end", LOG_INFO);
1292
1293 return $error;
1294 }
1295}
1296
1297
1298require_once DOL_DOCUMENT_ROOT.'/core/class/commonobjectline.class.php';
1299//BEGIN MODULEBUILDER LINES
1304{
1305 // To complete with content of an object MyObjectLine
1306 // We should have a field rowid, fk_myobject and position
1307
1312 public $parent_element = ''; // Example: '' or 'myobject'
1313
1318 public $fk_parent_attribute = ''; // Example: '' or 'fk_myobject'
1319
1323 public $isextrafieldmanaged = 0;
1324
1329 public $ismultientitymanaged = 0;
1330
1331
1337 public function __construct(DoliDB $db)
1338 {
1339 $this->db = $db;
1340 }
1341}
1342//END MODULEBUILDER LINES
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.
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.
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.
Parent class for class inheritance lines of business objects This class is useless for the moment so ...
Class to manage Dolibarr database access.
Class for MyObject.
generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0, $moreparams=null)
Create a document onto disk according to template module.
createFromClone(User $user, $fromid)
Clone an object into another one.
getKanbanView($option='', $arraydata=null)
Return a thumb for kanban views.
getLibStatut($mode=0)
Return the label of the status.
create(User $user, $notrigger=0)
Create object into database.
update(User $user, $notrigger=0)
Update object into database.
getTooltipContentArray($params)
getTooltipContentArray
reopen($user, $notrigger=0)
Set back to validated status.
setDraft($user, $notrigger=0)
Set draft status.
getNomUrl($withpicto=0, $option='', $notooltip=0, $morecss='', $save_lastsearch_value=-1)
Return a link to the object card (with optionally the picto)
LibStatut($status, $mode=0)
Return the label of a given status.
validateField($fields, $fieldKey, $fieldValue)
Return validation test result for a field.
getNextNumRef()
Returns the reference to the following non used object depending on the active numbering module.
fetchAll($sortorder='', $sortfield='', $limit=1000, $offset=0, string $filter='', $filtermode='AND')
Load list of objects in memory from the database.
initAsSpecimen()
Initialize object with example values Id must be 0 if object instance is a specimen.
__construct(DoliDB $db)
Constructor.
deleteLine(User $user, $idline, $notrigger=0)
Delete a line of object in database.
cancel($user, $notrigger=0)
Set cancel status.
fetchLines($noextrafields=0)
Load object lines in memory from the database.
info($id)
Load the info information in the object.
doScheduledJob()
Action executed by scheduler CAN BE A CRON TASK.
fetch($id, $ref=null, $noextrafields=0, $nolines=0)
Load object in memory from the database.
getLabelStatus($mode=0)
Return the label of the status.
validate($user, $notrigger=0)
Validate object.
$fields
'type' field format: 'integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter[:Sortf...
getLinesArray()
Create an array of lines.
Class MyObjectLine.
$parent_element
To overload.
$fk_parent_attribute
To overload.
__construct(DoliDB $db)
Constructor.
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_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.
dol_strlen($string, $stringencoding='UTF-8', $binarycount=0)
Make a strlen call.
dolBuildUrl($url, $params=[], $addtoken=false, $anchor='')
Return path of url.
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_strtoupper($string, $encoding="UTF-8")
Convert a string to upper.
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.
print $langs trans('Date')." left Ref Label right Qty right Price right TotalHT right TotalTTC right right right right right right right right right centpercent right TotalHT right n right VAT right n right TotalVAT right n No sujeto a RE IRPF right TotalLT1 right n right TotalLT2 right n right TotalTTC right n takeposcustomercurrency takeposcustomercurrency takeposcustomercurrency takeposcustomercurrency right TotalTTC takeposcustomercurrency right takeposcustomercurrency n right Paid right PaymentTypeShortLIQ right SELECT p pos_change as p datep as p p num_paiement as f pf amount as amount
Definition receipt.php:494