dolibarr  19.0.0-dev
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 Frédéric France <frederic.france@netlogic.fr>
4  * Copyright (C) ---Put here 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
27 require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
28 //require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php';
29 //require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
30 
34 class MyObject extends CommonObject
35 {
39  public $module = 'mymodule';
40 
44  public $element = 'myobject';
45 
49  public $table_element = 'mymodule_myobject';
50 
55  public $ismultientitymanaged = 0;
56 
60  public $isextrafieldmanaged = 1;
61 
65  public $picto = 'fa-file';
66 
67 
68  const STATUS_DRAFT = 0;
69  const STATUS_VALIDATED = 1;
70  const STATUS_CANCELED = 9;
71 
72 
112  // BEGIN MODULEBUILDER PROPERTIES
116  public $fields = array(
117  'rowid' => array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>1, 'visible'=>-2, 'noteditable'=>1, 'notnull'=> 1, 'index'=>1, 'position'=>1, 'comment'=>'Id', 'css'=>'left'),
118  'entity' => array('type'=>'integer', 'label'=>'Entity', 'enabled'=>1, 'visible'=>0, 'notnull'=> 1, 'default'=>1, 'index'=>1, 'position'=>10),
119  'ref' => array('type'=>'varchar(128)', 'label'=>'Ref', 'enabled'=>1, 'visible'=>1, 'noteditable'=>0, 'default'=>'', 'notnull'=> 1, 'showoncombobox'=>1, 'index'=>1, 'position'=>20, 'searchall'=>1, 'comment'=>'Reference of object', 'validate'=>1),
120  'label' => array('type'=>'varchar(255)', 'label'=>'Label', 'enabled'=>1, 'visible'=>1, 'position'=>30, 'searchall'=>1, 'css'=>'minwidth300', 'cssview'=>'wordbreak', 'help'=>'Help text', 'showoncombobox'=>2, 'validate'=>1, 'alwayseditable'=>1),
121  'amount' => array('type'=>'price', 'label'=>'Amount', 'enabled'=>1, 'visible'=>1, 'default'=>'null', 'position'=>40, 'searchall'=>0, 'isameasure'=>1, 'help'=>'Help text for amount', 'validate'=>1),
122  'qty' => array('type'=>'real', 'label'=>'Qty', 'enabled'=>1, 'visible'=>1, 'default'=>'0', 'position'=>45, 'searchall'=>0, 'isameasure'=>1, 'help'=>'Help text for quantity', 'css'=>'maxwidth75imp', 'validate'=>1),
123  'fk_soc' => array('type'=>'integer:Societe:societe/class/societe.class.php:1:((status:=:1) AND (entity:IN:__SHARED_ENTITIES__))', 'picto'=>'company', 'label'=>'ThirdParty', 'visible'=> 1, 'enabled'=>'isModEnabled("societe")', 'position'=>50, 'notnull'=>-1, 'index'=>1, 'help'=>'OrganizationEventLinkToThirdParty', 'validate'=>1, 'css'=>'maxwidth500 widthcentpercentminusxx', 'csslist'=>'tdoverflowmax150'),
124  'fk_project' => array('type'=>'integer:Project:projet/class/project.class.php:1', 'label'=>'Project', 'picto'=>'project', 'enabled'=>'isModEnabled("project")', 'visible'=>-1, 'position'=>52, 'notnull'=>-1, 'index'=>1, 'validate'=>1, 'css'=>'maxwidth500 widthcentpercentminusxx', 'csslist'=>'tdoverflowmax150'),
125  'description' => array('type'=>'text', 'label'=>'Description', 'enabled'=>1, 'visible'=>3, 'position'=>60, 'validate'=>1),
126  'note_public' => array('type'=>'html', 'label'=>'NotePublic', 'enabled'=>1, 'visible'=>0, 'position'=>61, 'validate'=>1, 'cssview'=>'wordbreak'),
127  'note_private' => array('type'=>'html', 'label'=>'NotePrivate', 'enabled'=>1, 'visible'=>0, 'position'=>62, 'validate'=>1, 'cssview'=>'wordbreak'),
128  'date_creation' => array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-2, 'notnull'=> 1, 'position'=>500),
129  'tms' => array('type'=>'timestamp', 'label'=>'DateModification', 'enabled'=>1, 'visible'=>-2, 'notnull'=> 0, 'position'=>501),
130  //'date_validation ' =>array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-2, 'position'=>502),
131  'fk_user_creat' => array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserAuthor', 'picto'=>'user', 'enabled'=>1, 'visible'=>-2, 'notnull'=> 1, 'position'=>510, 'foreignkey'=>'user.rowid', 'csslist'=>'tdoverflowmax150'),
132  'fk_user_modif' => array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserModif', 'picto'=>'user', 'enabled'=>1, 'visible'=>-2, 'notnull'=>-1, 'position'=>511, 'csslist'=>'tdoverflowmax150'),
133  //'fk_user_valid' => array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserValidation', 'enabled'=>1, 'visible'=>-1, 'position'=>512),
134  'last_main_doc' => array('type'=>'varchar(255)', 'label'=>'LastMainDoc', 'enabled'=>1, 'visible'=>0, 'notnull'=>0, 'position'=>600),
135  'import_key' => array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>1, 'visible'=>-2, 'notnull'=>-1, 'index'=>0, 'position'=>1000),
136  'model_pdf' => array('type'=>'varchar(255)', 'label'=>'Model pdf', 'enabled'=>1, 'visible'=>0, 'notnull'=>-1, 'position'=>1010),
137  'status' => array('type'=>'integer', 'label'=>'Status', 'enabled'=>1, 'visible'=>1, 'notnull'=> 1, 'default'=>0, 'index'=>1, 'position'=>2000, 'arrayofkeyval'=>array(0=>'Draft', 1=>'Validated', 9=>'Canceled'), 'validate'=>1),
138  );
139 
143  public $rowid;
144 
148  public $ref;
149 
153  public $entity;
154 
158  public $label;
159 
163  public $amount;
164 
168  public $socid; // both socid and fk_soc are used
169  public $fk_soc; // both socid and fk_soc are used
170 
174  public $status;
175 
179  public $date_creation;
180 
184  public $tms;
185 
189  public $fk_user_creat;
190 
194  public $fk_user_modif;
195 
199  public $last_main_doc;
200 
204  public $import_key;
205  // END MODULEBUILDER PROPERTIES
206 
207 
208  // If this object has a subtable with lines
209 
210  // /**
211  // * @var string Name of subtable line
212  // */
213  // public $table_element_line = 'mymodule_myobjectline';
214 
215  // /**
216  // * @var string Field with ID of parent key if this object has a parent
217  // */
218  // public $fk_element = 'fk_myobject';
219 
220  // /**
221  // * @var string Name of subtable class that manage subtable lines
222  // */
223  // public $class_element_line = 'MyObjectline';
224 
225  // /**
226  // * @var array List of child tables. To test if we can delete object.
227  // */
228  // protected $childtables = array('mychildtable' => array('name'=>'MyObject', 'fk_element'=>'fk_myobject'));
229 
230  // /**
231  // * @var array List of child tables. To know object to delete on cascade.
232  // * If name matches '@ClassNAme:FilePathClass;ParentFkFieldName' it will
233  // * call method deleteByParentField(parentId, ParentFkFieldName) to fetch and delete child object
234  // */
235  // protected $childtablesoncascade = array('mymodule_myobjectdet');
236 
237  // /**
238  // * @var MyObjectLine[] Array of subtable lines
239  // */
240  // public $lines = array();
241 
242 
243 
249  public function __construct(DoliDB $db)
250  {
251  global $conf, $langs;
252 
253  $this->db = $db;
254 
255  if (!getDolGlobalInt('MAIN_SHOW_TECHNICAL_ID') && isset($this->fields['rowid']) && !empty($this->fields['ref'])) {
256  $this->fields['rowid']['visible'] = 0;
257  }
258  if (!isModEnabled('multicompany') && isset($this->fields['entity'])) {
259  $this->fields['entity']['enabled'] = 0;
260  }
261 
262  // Example to show how to set values of fields definition dynamically
263  /*if ($user->hasRight('mymodule', 'myobject', 'read')) {
264  $this->fields['myfield']['visible'] = 1;
265  $this->fields['myfield']['noteditable'] = 0;
266  }*/
267 
268  // Unset fields that are disabled
269  foreach ($this->fields as $key => $val) {
270  if (isset($val['enabled']) && empty($val['enabled'])) {
271  unset($this->fields[$key]);
272  }
273  }
274 
275  // Translate some data of arrayofkeyval
276  if (is_object($langs)) {
277  foreach ($this->fields as $key => $val) {
278  if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
279  foreach ($val['arrayofkeyval'] as $key2 => $val2) {
280  $this->fields[$key]['arrayofkeyval'][$key2] = $langs->trans($val2);
281  }
282  }
283  }
284  }
285  }
286 
294  public function create(User $user, $notrigger = false)
295  {
296  $resultcreate = $this->createCommon($user, $notrigger);
297 
298  //$resultvalidate = $this->validate($user, $notrigger);
299 
300  return $resultcreate;
301  }
302 
310  public function createFromClone(User $user, $fromid)
311  {
312  global $langs, $extrafields;
313  $error = 0;
314 
315  dol_syslog(__METHOD__, LOG_DEBUG);
316 
317  $object = new self($this->db);
318 
319  $this->db->begin();
320 
321  // Load source object
322  $result = $object->fetchCommon($fromid);
323  if ($result > 0 && !empty($object->table_element_line)) {
324  $object->fetchLines();
325  }
326 
327  // get lines so they will be clone
328  //foreach($this->lines as $line)
329  // $line->fetch_optionals();
330 
331  // Reset some properties
332  unset($object->id);
333  unset($object->fk_user_creat);
334  unset($object->import_key);
335 
336  // Clear fields
337  if (property_exists($object, 'ref')) {
338  $object->ref = empty($this->fields['ref']['default']) ? "Copy_Of_".$object->ref : $this->fields['ref']['default'];
339  }
340  if (property_exists($object, 'label')) {
341  $object->label = empty($this->fields['label']['default']) ? $langs->trans("CopyOf")." ".$object->label : $this->fields['label']['default'];
342  }
343  if (property_exists($object, 'status')) {
344  $object->status = self::STATUS_DRAFT;
345  }
346  if (property_exists($object, 'date_creation')) {
347  $object->date_creation = dol_now();
348  }
349  if (property_exists($object, 'date_modification')) {
350  $object->date_modification = null;
351  }
352  // ...
353  // Clear extrafields that are unique
354  if (is_array($object->array_options) && count($object->array_options) > 0) {
355  $extrafields->fetch_name_optionals_label($this->table_element);
356  foreach ($object->array_options as $key => $option) {
357  $shortkey = preg_replace('/options_/', '', $key);
358  if (!empty($extrafields->attributes[$this->table_element]['unique'][$shortkey])) {
359  //var_dump($key);
360  //var_dump($clonedObj->array_options[$key]); exit;
361  unset($object->array_options[$key]);
362  }
363  }
364  }
365 
366  // Create clone
367  $object->context['createfromclone'] = 'createfromclone';
368  $result = $object->createCommon($user);
369  if ($result < 0) {
370  $error++;
371  $this->setErrorsFromObject($object);
372  }
373 
374  if (!$error) {
375  // copy internal contacts
376  if ($this->copy_linked_contact($object, 'internal') < 0) {
377  $error++;
378  }
379  }
380 
381  if (!$error) {
382  // copy external contacts if same company
383  if (!empty($object->socid) && property_exists($this, 'fk_soc') && $this->fk_soc == $object->socid) {
384  if ($this->copy_linked_contact($object, 'external') < 0) {
385  $error++;
386  }
387  }
388  }
389 
390  unset($object->context['createfromclone']);
391 
392  // End
393  if (!$error) {
394  $this->db->commit();
395  return $object;
396  } else {
397  $this->db->rollback();
398  return -1;
399  }
400  }
401 
409  public function fetch($id, $ref = null)
410  {
411  $result = $this->fetchCommon($id, $ref);
412  if ($result > 0 && !empty($this->table_element_line)) {
413  $this->fetchLines();
414  }
415  return $result;
416  }
417 
423  public function fetchLines()
424  {
425  $this->lines = array();
426 
427  $result = $this->fetchLinesCommon();
428  return $result;
429  }
430 
431 
443  public function fetchAll($sortorder = '', $sortfield = '', $limit = 0, $offset = 0, array $filter = array(), $filtermode = 'AND')
444  {
445  global $conf;
446 
447  dol_syslog(__METHOD__, LOG_DEBUG);
448 
449  $records = array();
450 
451  $sql = "SELECT ";
452  $sql .= $this->getFieldList('t');
453  $sql .= " FROM ".$this->db->prefix().$this->table_element." as t";
454  if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
455  $sql .= " WHERE t.entity IN (".getEntity($this->element).")";
456  } else {
457  $sql .= " WHERE 1 = 1";
458  }
459  // Manage filter
460  $sqlwhere = array();
461  if (count($filter) > 0) {
462  foreach ($filter as $key => $value) {
463  if ($key == 't.rowid') {
464  $sqlwhere[] = $key." = ".((int) $value);
465  } elseif (in_array($this->fields[$key]['type'], array('date', 'datetime', 'timestamp'))) {
466  $sqlwhere[] = $key." = '".$this->db->idate($value)."'";
467  } elseif ($key == 'customsql') {
468  $sqlwhere[] = $value;
469  } elseif (strpos($value, '%') === false) {
470  $sqlwhere[] = $key." IN (".$this->db->sanitize($this->db->escape($value)).")";
471  } else {
472  $sqlwhere[] = $key." LIKE '%".$this->db->escape($value)."%'";
473  }
474  }
475  }
476  if (count($sqlwhere) > 0) {
477  $sql .= " AND (".implode(" ".$filtermode." ", $sqlwhere).")";
478  }
479 
480  if (!empty($sortfield)) {
481  $sql .= $this->db->order($sortfield, $sortorder);
482  }
483  if (!empty($limit)) {
484  $sql .= $this->db->plimit($limit, $offset);
485  }
486 
487  $resql = $this->db->query($sql);
488  if ($resql) {
489  $num = $this->db->num_rows($resql);
490  $i = 0;
491  while ($i < ($limit ? min($limit, $num) : $num)) {
492  $obj = $this->db->fetch_object($resql);
493 
494  $record = new self($this->db);
495  $record->setVarsFromFetchObj($obj);
496 
497  $records[$record->id] = $record;
498 
499  $i++;
500  }
501  $this->db->free($resql);
502 
503  return $records;
504  } else {
505  $this->errors[] = 'Error '.$this->db->lasterror();
506  dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
507 
508  return -1;
509  }
510  }
511 
519  public function update(User $user, $notrigger = false)
520  {
521  return $this->updateCommon($user, $notrigger);
522  }
523 
531  public function delete(User $user, $notrigger = false)
532  {
533  return $this->deleteCommon($user, $notrigger);
534  //return $this->deleteCommon($user, $notrigger, 1);
535  }
536 
545  public function deleteLine(User $user, $idline, $notrigger = false)
546  {
547  if ($this->status < 0) {
548  $this->error = 'ErrorDeleteLineNotAllowedByObjectStatus';
549  return -2;
550  }
551 
552  return $this->deleteLineCommon($user, $idline, $notrigger);
553  }
554 
555 
563  public function validate($user, $notrigger = 0)
564  {
565  global $conf, $langs;
566 
567  require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
568 
569  $error = 0;
570 
571  // Protection
572  if ($this->status == self::STATUS_VALIDATED) {
573  dol_syslog(get_class($this)."::validate action abandonned: already validated", LOG_WARNING);
574  return 0;
575  }
576 
577  /*if (! ((!getDolGlobalInt('MAIN_USE_ADVANCED_PERMS') && !empty($user->rights->mymodule->myobject->write))
578  || (getDolGlobalInt('MAIN_USE_ADVANCED_PERMS') && !empty($user->rights->mymodule->myobject->myobject_advance->validate))))
579  {
580  $this->error='NotEnoughPermissions';
581  dol_syslog(get_class($this)."::valid ".$this->error, LOG_ERR);
582  return -1;
583  }*/
584 
585  $now = dol_now();
586 
587  $this->db->begin();
588 
589  // Define new ref
590  if (!$error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) { // empty should not happened, but when it occurs, the test save life
591  $num = $this->getNextNumRef();
592  } else {
593  $num = $this->ref;
594  }
595  $this->newref = $num;
596 
597  if (!empty($num)) {
598  // Validate
599  $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
600  $sql .= " SET ref = '".$this->db->escape($num)."',";
601  $sql .= " status = ".self::STATUS_VALIDATED;
602  if (!empty($this->fields['date_validation'])) {
603  $sql .= ", date_validation = '".$this->db->idate($now)."'";
604  }
605  if (!empty($this->fields['fk_user_valid'])) {
606  $sql .= ", fk_user_valid = ".((int) $user->id);
607  }
608  $sql .= " WHERE rowid = ".((int) $this->id);
609 
610  dol_syslog(get_class($this)."::validate()", LOG_DEBUG);
611  $resql = $this->db->query($sql);
612  if (!$resql) {
613  dol_print_error($this->db);
614  $this->error = $this->db->lasterror();
615  $error++;
616  }
617 
618  if (!$error && !$notrigger) {
619  // Call trigger
620  $result = $this->call_trigger('MYOBJECT_VALIDATE', $user);
621  if ($result < 0) {
622  $error++;
623  }
624  // End call triggers
625  }
626  }
627 
628  if (!$error) {
629  $this->oldref = $this->ref;
630 
631  // Rename directory if dir was a temporary ref
632  if (preg_match('/^[\(]?PROV/i', $this->ref)) {
633  // Now we rename also files into index
634  $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filename = CONCAT('".$this->db->escape($this->newref)."', SUBSTR(filename, ".(strlen($this->ref) + 1).")), filepath = 'myobject/".$this->db->escape($this->newref)."'";
635  $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'myobject/".$this->db->escape($this->ref)."' and entity = ".$conf->entity;
636  $resql = $this->db->query($sql);
637  if (!$resql) {
638  $error++; $this->error = $this->db->lasterror();
639  }
640 
641  // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments
642  $oldref = dol_sanitizeFileName($this->ref);
643  $newref = dol_sanitizeFileName($num);
644  $dirsource = $conf->mymodule->dir_output.'/myobject/'.$oldref;
645  $dirdest = $conf->mymodule->dir_output.'/myobject/'.$newref;
646  if (!$error && file_exists($dirsource)) {
647  dol_syslog(get_class($this)."::validate() rename dir ".$dirsource." into ".$dirdest);
648 
649  if (@rename($dirsource, $dirdest)) {
650  dol_syslog("Rename ok");
651  // Rename docs starting with $oldref with $newref
652  $listoffiles = dol_dir_list($conf->mymodule->dir_output.'/myobject/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/'));
653  foreach ($listoffiles as $fileentry) {
654  $dirsource = $fileentry['name'];
655  $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource);
656  $dirsource = $fileentry['path'].'/'.$dirsource;
657  $dirdest = $fileentry['path'].'/'.$dirdest;
658  @rename($dirsource, $dirdest);
659  }
660  }
661  }
662  }
663  }
664 
665  // Set new ref and current status
666  if (!$error) {
667  $this->ref = $num;
668  $this->status = self::STATUS_VALIDATED;
669  }
670 
671  if (!$error) {
672  $this->db->commit();
673  return 1;
674  } else {
675  $this->db->rollback();
676  return -1;
677  }
678  }
679 
680 
688  public function setDraft($user, $notrigger = 0)
689  {
690  // Protection
691  if ($this->status <= self::STATUS_DRAFT) {
692  return 0;
693  }
694 
695  /*if (! ((!getDolGlobalInt('MAIN_USE_ADVANCED_PERMS') && !empty($user->rights->mymodule->write))
696  || (getDolGlobalInt('MAIN_USE_ADVANCED_PERMS') && !empty($user->rights->mymodule->mymodule_advance->validate))))
697  {
698  $this->error='Permission denied';
699  return -1;
700  }*/
701 
702  return $this->setStatusCommon($user, self::STATUS_DRAFT, $notrigger, 'MYOBJECT_UNVALIDATE');
703  }
704 
712  public function cancel($user, $notrigger = 0)
713  {
714  // Protection
715  if ($this->status != self::STATUS_VALIDATED) {
716  return 0;
717  }
718 
719  /*if (! ((!getDolGlobalInt('MAIN_USE_ADVANCED_PERMS') && !empty($user->rights->mymodule->write))
720  || (getDolGlobalInt('MAIN_USE_ADVANCED_PERMS') && !empty($user->rights->mymodule->mymodule_advance->validate))))
721  {
722  $this->error='Permission denied';
723  return -1;
724  }*/
725 
726  return $this->setStatusCommon($user, self::STATUS_CANCELED, $notrigger, 'MYOBJECT_CANCEL');
727  }
728 
736  public function reopen($user, $notrigger = 0)
737  {
738  // Protection
739  if ($this->status == self::STATUS_VALIDATED) {
740  return 0;
741  }
742 
743  /*if (! ((!getDolGlobalInt('MAIN_USE_ADVANCED_PERMS') && !empty($user->rights->mymodule->write))
744  || (getDolGlobalInt('MAIN_USE_ADVANCED_PERMS') && !empty($user->rights->mymodule->mymodule_advance->validate))))
745  {
746  $this->error='Permission denied';
747  return -1;
748  }*/
749 
750  return $this->setStatusCommon($user, self::STATUS_VALIDATED, $notrigger, 'MYOBJECT_REOPEN');
751  }
752 
760  public function getTooltipContentArray($params)
761  {
762  global $conf, $langs;
763 
764  $datas = [];
765 
766  if (getDolGlobalInt('MAIN_OPTIMIZEFORTEXTBROWSER')) {
767  return ['optimize' => $langs->trans("ShowMyObject")];
768  }
769  $datas['picto'] = img_picto('', $this->picto).' <u>'.$langs->trans("MyObject").'</u>';
770  if (isset($this->status)) {
771  $datas['picto'] .= ' '.$this->getLibStatut(5);
772  }
773  $datas['ref'] .= '<br><b>'.$langs->trans('Ref').':</b> '.$this->ref;
774 
775  return $datas;
776  }
777 
788  public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $morecss = '', $save_lastsearch_value = -1)
789  {
790  global $conf, $langs, $hookmanager;
791 
792  if (!empty($conf->dol_no_mouse_hover)) {
793  $notooltip = 1; // Force disable tooltips
794  }
795 
796  $result = '';
797  $params = [
798  'id' => $this->id,
799  'objecttype' => $this->element.($this->module ? '@'.$this->module : ''),
800  'option' => $option,
801  ];
802  $classfortooltip = 'classfortooltip';
803  $dataparams = '';
804  if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
805  $classfortooltip = 'classforajaxtooltip';
806  $dataparams = ' data-params="'.dol_escape_htmltag(json_encode($params)).'"';
807  $label = '';
808  } else {
809  $label = implode($this->getTooltipContentArray($params));
810  }
811 
812  $url = dol_buildpath('/mymodule/myobject_card.php', 1).'?id='.$this->id;
813 
814  if ($option !== 'nolink') {
815  // Add param to save lastsearch_values or not
816  $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
817  if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
818  $add_save_lastsearch_values = 1;
819  }
820  if ($url && $add_save_lastsearch_values) {
821  $url .= '&save_lastsearch_values=1';
822  }
823  }
824 
825  $linkclose = '';
826  if (empty($notooltip)) {
827  if (getDolGlobalInt('MAIN_OPTIMIZEFORTEXTBROWSER')) {
828  $label = $langs->trans("ShowMyObject");
829  $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
830  }
831  $linkclose .= ($label ? ' title="'.dol_escape_htmltag($label, 1).'"' : ' title="tocomplete"');
832  $linkclose .= $dataparams.' class="'.$classfortooltip.($morecss ? ' '.$morecss : '').'"';
833  } else {
834  $linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
835  }
836 
837  if ($option == 'nolink' || empty($url)) {
838  $linkstart = '<span';
839  } else {
840  $linkstart = '<a href="'.$url.'"';
841  }
842  $linkstart .= $linkclose.'>';
843  if ($option == 'nolink' || empty($url)) {
844  $linkend = '</span>';
845  } else {
846  $linkend = '</a>';
847  }
848 
849  $result .= $linkstart;
850 
851  if (empty($this->showphoto_on_popup)) {
852  if ($withpicto) {
853  $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), (($withpicto != 2) ? 'class="paddingright"' : ''), 0, 0, $notooltip ? 0 : 1);
854  }
855  } else {
856  if ($withpicto) {
857  require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
858 
859  list($class, $module) = explode('@', $this->picto);
860  $upload_dir = $conf->$module->multidir_output[$conf->entity]."/$class/".dol_sanitizeFileName($this->ref);
861  $filearray = dol_dir_list($upload_dir, "files");
862  $filename = $filearray[0]['name'];
863  if (!empty($filename)) {
864  $pospoint = strpos($filearray[0]['name'], '.');
865 
866  $pathtophoto = $class.'/'.$this->ref.'/thumbs/'.substr($filename, 0, $pospoint).'_mini'.substr($filename, $pospoint);
867  if (!getDolGlobalInt(strtoupper($module.'_'.$class).'_FORMATLISTPHOTOSASUSERS')) {
868  $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>';
869  } else {
870  $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>';
871  }
872 
873  $result .= '</div>';
874  } else {
875  $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'"'), 0, 0, $notooltip ? 0 : 1);
876  }
877  }
878  }
879 
880  if ($withpicto != 2) {
881  $result .= $this->ref;
882  }
883 
884  $result .= $linkend;
885  //if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : '');
886 
887  global $action, $hookmanager;
888  $hookmanager->initHooks(array($this->element.'dao'));
889  $parameters = array('id' => $this->id, 'getnomurl' => &$result);
890  $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
891  if ($reshook > 0) {
892  $result = $hookmanager->resPrint;
893  } else {
894  $result .= $hookmanager->resPrint;
895  }
896 
897  return $result;
898  }
899 
907  public function getKanbanView($option = '', $arraydata = null)
908  {
909  global $conf, $langs;
910 
911  $selected = (empty($arraydata['selected']) ? 0 : $arraydata['selected']);
912 
913  $return = '<div class="box-flex-item box-flex-grow-zero">';
914  $return .= '<div class="info-box info-box-sm">';
915  $return .= '<span class="info-box-icon bg-infobox-action">';
916  $return .= img_picto('', $this->picto);
917  $return .= '</span>';
918  $return .= '<div class="info-box-content">';
919  $return .= '<span class="info-box-ref inline-block tdoverflowmax150 valignmiddle">'.(method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref).'</span>';
920  if ($selected >= 0) {
921  $return .= '<input id="cb'.$this->id.'" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="'.$this->id.'"'.($selected ? ' checked="checked"' : '').'>';
922  }
923  if (property_exists($this, 'label')) {
924  $return .= ' <div class="inline-block opacitymedium valignmiddle tdoverflowmax100">'.$this->label.'</div>';
925  }
926  if (property_exists($this, 'amount')) {
927  $return .= '<br>';
928  $return .= '<span class="info-box-label amount">'.price($this->amount, 0, $langs, 1, -1, -1, $conf->currency).'</span>';
929  }
930  if (method_exists($this, 'getLibStatut')) {
931  $return .= '<br><div class="info-box-status margintoponly">'.$this->getLibStatut(3).'</div>';
932  }
933  $return .= '</div>';
934  $return .= '</div>';
935  $return .= '</div>';
936 
937  return $return;
938  }
939 
946  public function getLabelStatus($mode = 0)
947  {
948  return $this->LibStatut($this->status, $mode);
949  }
950 
957  public function getLibStatut($mode = 0)
958  {
959  return $this->LibStatut($this->status, $mode);
960  }
961 
962  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
970  public function LibStatut($status, $mode = 0)
971  {
972  // phpcs:enable
973  if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
974  global $langs;
975  //$langs->load("mymodule@mymodule");
976  $this->labelStatus[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('Draft');
977  $this->labelStatus[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('Enabled');
978  $this->labelStatus[self::STATUS_CANCELED] = $langs->transnoentitiesnoconv('Disabled');
979  $this->labelStatusShort[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('Draft');
980  $this->labelStatusShort[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('Enabled');
981  $this->labelStatusShort[self::STATUS_CANCELED] = $langs->transnoentitiesnoconv('Disabled');
982  }
983 
984  $statusType = 'status'.$status;
985  //if ($status == self::STATUS_VALIDATED) $statusType = 'status1';
986  if ($status == self::STATUS_CANCELED) {
987  $statusType = 'status6';
988  }
989 
990  return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
991  }
992 
999  public function info($id)
1000  {
1001  $sql = "SELECT rowid,";
1002  $sql .= " date_creation as datec, tms as datem,";
1003  $sql .= " fk_user_creat, fk_user_modif";
1004  $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element." as t";
1005  $sql .= " WHERE t.rowid = ".((int) $id);
1006 
1007  $result = $this->db->query($sql);
1008  if ($result) {
1009  if ($this->db->num_rows($result)) {
1010  $obj = $this->db->fetch_object($result);
1011 
1012  $this->id = $obj->rowid;
1013 
1014  $this->user_creation_id = $obj->fk_user_creat;
1015  $this->user_modification_id = $obj->fk_user_modif;
1016  if (!empty($obj->fk_user_valid)) {
1017  $this->user_validation_id = $obj->fk_user_valid;
1018  }
1019  $this->date_creation = $this->db->jdate($obj->datec);
1020  $this->date_modification = empty($obj->datem) ? '' : $this->db->jdate($obj->datem);
1021  if (!empty($obj->datev)) {
1022  $this->date_validation = empty($obj->datev) ? '' : $this->db->jdate($obj->datev);
1023  }
1024  }
1025 
1026  $this->db->free($result);
1027  } else {
1028  dol_print_error($this->db);
1029  }
1030  }
1031 
1038  public function initAsSpecimen()
1039  {
1040  // Set here init that are not commonf fields
1041  // $this->property1 = ...
1042  // $this->property2 = ...
1043 
1044  $this->initAsSpecimenCommon();
1045  }
1046 
1052  public function getLinesArray()
1053  {
1054  $this->lines = array();
1055 
1056  $objectline = new MyObjectLine($this->db);
1057  $result = $objectline->fetchAll('ASC', 'position', 0, 0, array('customsql'=>'fk_myobject = '.((int) $this->id)));
1058 
1059  if (is_numeric($result)) {
1060  $this->setErrorsFromObject($objectline);
1061  return $result;
1062  } else {
1063  $this->lines = $result;
1064  return $this->lines;
1065  }
1066  }
1067 
1073  public function getNextNumRef()
1074  {
1075  global $langs, $conf;
1076  $langs->load("mymodule@mymodule");
1077 
1078  if (empty(getDolGlobalString('MYMODULE_MYOBJECT_ADDON'))) {
1079  $conf->global->MYMODULE_MYOBJECT_ADDON = 'mod_myobject_standard';
1080  }
1081 
1082  if (!empty(getDolGlobalString('MYMODULE_MYOBJECT_ADDON'))) {
1083  $mybool = false;
1084 
1085  $file = getDolGlobalString('MYMODULE_MYOBJECT_ADDON').".php";
1086  $classname = getDolGlobalString('MYMODULE_MYOBJECT_ADDON');
1087 
1088  // Include file with class
1089  $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
1090  foreach ($dirmodels as $reldir) {
1091  $dir = dol_buildpath($reldir."core/modules/mymodule/");
1092 
1093  // Load file with numbering class (if found)
1094  $mybool |= @include_once $dir.$file;
1095  }
1096 
1097  if ($mybool === false) {
1098  dol_print_error('', "Failed to include file ".$file);
1099  return '';
1100  }
1101 
1102  if (class_exists($classname)) {
1103  $obj = new $classname();
1104  $numref = $obj->getNextValue($this);
1105 
1106  if ($numref != '' && $numref != '-1') {
1107  return $numref;
1108  } else {
1109  $this->error = $obj->error;
1110  //dol_print_error($this->db,get_class($this)."::getNextNumRef ".$obj->error);
1111  return "";
1112  }
1113  } else {
1114  print $langs->trans("Error")." ".$langs->trans("ClassNotFound").' '.$classname;
1115  return "";
1116  }
1117  } else {
1118  print $langs->trans("ErrorNumberingModuleNotSetup", $this->element);
1119  return "";
1120  }
1121  }
1122 
1134  public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
1135  {
1136  global $conf, $langs;
1137 
1138  $result = 0;
1139  $includedocgeneration = 0;
1140 
1141  $langs->load("mymodule@mymodule");
1142 
1143  if (!dol_strlen($modele)) {
1144  $modele = 'standard_myobject';
1145 
1146  if (!empty($this->model_pdf)) {
1147  $modele = $this->model_pdf;
1148  } elseif (getDolGlobalString('MYOBJECT_ADDON_PDF')) {
1149  $modele = getDolGlobalString('MYOBJECT_ADDON_PDF');
1150  }
1151  }
1152 
1153  $modelpath = "core/modules/mymodule/doc/";
1154 
1155  if ($includedocgeneration && !empty($modele)) {
1156  $result = $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
1157  }
1158 
1159  return $result;
1160  }
1161 
1169  public function doScheduledJob()
1170  {
1171  //global $conf, $langs;
1172 
1173  //$conf->global->SYSLOG_FILE = 'DOL_DATA_ROOT/dolibarr_mydedicatedlofile.log';
1174 
1175  $error = 0;
1176  $this->output = '';
1177  $this->error = '';
1178 
1179  dol_syslog(__METHOD__, LOG_DEBUG);
1180 
1181  $now = dol_now();
1182 
1183  $this->db->begin();
1184 
1185  // ...
1186 
1187  $this->db->commit();
1188 
1189  return $error;
1190  }
1191 }
1192 
1193 
1194 require_once DOL_DOCUMENT_ROOT.'/core/class/commonobjectline.class.php';
1195 
1200 {
1201  // To complete with content of an object MyObjectLine
1202  // We should have a field rowid, fk_myobject and position
1203 
1207  public $isextrafieldmanaged = 0;
1208 
1214  public function __construct(DoliDB $db)
1215  {
1216  $this->db = $db;
1217  }
1218 }
CommonObject\deleteCommon
deleteCommon(User $user, $notrigger=false, $forcechilddeletion=0)
Delete object in database.
Definition: commonobject.class.php:9605
CommonObject\setStatusCommon
setStatusCommon($user, $status, $notrigger=0, $triggercode='')
Set to a status.
Definition: commonobject.class.php:9883
MyObject\validate
validate($user, $notrigger=0)
Validate object.
Definition: myobject.class.php:563
MyObject\reopen
reopen($user, $notrigger=0)
Set back to validated status.
Definition: myobject.class.php:736
CommonObject\fetchCommon
fetchCommon($id, $ref=null, $morewhere='')
Load object in memory from the database.
Definition: commonobject.class.php:9395
dol_sanitizeFileName
dol_sanitizeFileName($str, $newstr='_', $unaccent=1)
Clean a string to use it as a file name.
Definition: functions.lib.php:1323
CommonObject\copy_linked_contact
copy_linked_contact($objFrom, $source='internal')
Copy contact from one element to current.
Definition: commonobject.class.php:1132
MyObject\__construct
__construct(DoliDB $db)
Constructor.
Definition: myobject.class.php:249
MyObject\createFromClone
createFromClone(User $user, $fromid)
Clone an object into another one.
Definition: myobject.class.php:310
DoliDB
Class to manage Dolibarr database access.
Definition: DoliDB.class.php:30
MyObject\update
update(User $user, $notrigger=false)
Update object into database.
Definition: myobject.class.php:519
MyObject\LibStatut
LibStatut($status, $mode=0)
Return the label of a given status.
Definition: myobject.class.php:970
dol_print_error
dol_print_error($db='', $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
Definition: functions.lib.php:5107
CommonObject\setErrorsFromObject
setErrorsFromObject($object)
setErrorsFromObject
Definition: commonobject.class.php:743
dol_buildpath
dol_buildpath($path, $type=0, $returnemptyifnotfound=0)
Return path of url or filesystem.
Definition: functions.lib.php:1158
dol_dir_list
dol_dir_list($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:62
CommonObject\fetchLinesCommon
fetchLinesCommon($morewhere='')
Load object in memory from the database.
Definition: commonobject.class.php:9451
CommonObject\initAsSpecimenCommon
initAsSpecimenCommon()
Initialise object with example values Id must be 0 if object instance is a specimen.
Definition: commonobject.class.php:9933
CommonObjectLine
Parent class for class inheritance lines of business objects This class is useless for the moment so ...
Definition: commonobjectline.class.php:32
CommonObject
Parent class of all other business classes (invoices, contracts, proposals, orders,...
Definition: commonobject.class.php:45
MyObject\generateDocument
generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0, $moreparams=null)
Create a document onto disk according to template module.
Definition: myobject.class.php:1134
MyObject\getTooltipContentArray
getTooltipContentArray($params)
getTooltipContentArray
Definition: myobject.class.php:760
MyObject\fetchLines
fetchLines()
Load object lines in memory from the database.
Definition: myobject.class.php:423
MyObject\getLabelStatus
getLabelStatus($mode=0)
Return the label of the status.
Definition: myobject.class.php:946
MyObjectLine
Class MyObjectLine.
Definition: myobject.class.php:1199
MyObject\deleteLine
deleteLine(User $user, $idline, $notrigger=false)
Delete a line of object in database.
Definition: myobject.class.php:545
MyObject\getLinesArray
getLinesArray()
Create an array of lines.
Definition: myobject.class.php:1052
MyObject\cancel
cancel($user, $notrigger=0)
Set cancel status.
Definition: myobject.class.php:712
img_picto
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=false, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2)
Show picto whatever it's its name (generic function)
Definition: functions.lib.php:4135
CommonObject\commonGenerateDocument
commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams=null)
Common function for all objects extending CommonObject for generating documents.
Definition: commonobject.class.php:5381
CommonObject\createCommon
createCommon(User $user, $notrigger=false)
Create object into database.
Definition: commonobject.class.php:9228
MyObject\initAsSpecimen
initAsSpecimen()
Initialise object with example values Id must be 0 if object instance is a specimen.
Definition: myobject.class.php:1038
MyObject\getLibStatut
getLibStatut($mode=0)
Return the label of the status.
Definition: myobject.class.php:957
MyObject\getNomUrl
getNomUrl($withpicto=0, $option='', $notooltip=0, $morecss='', $save_lastsearch_value=-1)
Return a link to the object card (with optionaly the picto)
Definition: myobject.class.php:788
MyObject\fetch
fetch($id, $ref=null)
Load object in memory from the database.
Definition: myobject.class.php:409
MyObject\fetchAll
fetchAll($sortorder='', $sortfield='', $limit=0, $offset=0, array $filter=array(), $filtermode='AND')
Load list of objects in memory from the database.
Definition: myobject.class.php:443
MyObject\create
create(User $user, $notrigger=false)
Create object into database.
Definition: myobject.class.php:294
dol_syslog
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
Definition: functions.lib.php:1741
MyObject\doScheduledJob
doScheduledJob()
Action executed by scheduler CAN BE A CRON TASK.
Definition: myobject.class.php:1169
CommonObject\updateCommon
updateCommon(User $user, $notrigger=false)
Update object into database.
Definition: commonobject.class.php:9501
$sql
if(isModEnabled('facture') && $user->hasRight('facture', 'lire')) if((isModEnabled('fournisseur') &&empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) && $user->hasRight("fournisseur", "facture", "lire"))||(isModEnabled('supplier_invoice') && $user->hasRight("supplier_invoice", "lire"))) if(isModEnabled('don') && $user->hasRight('don', 'lire')) if(isModEnabled('tax') &&!empty($user->rights->tax->charges->lire)) if(isModEnabled('facture') &&isModEnabled('commande') && $user->hasRight("commande", "lire") &&empty($conf->global->WORKFLOW_DISABLE_CREATE_INVOICE_FROM_ORDER)) $sql
Social contributions to pay.
Definition: index.php:746
dol_strlen
dol_strlen($string, $stringencoding='UTF-8')
Make a strlen call.
Definition: functions.lib.php:3997
isModEnabled
isModEnabled($module)
Is Dolibarr module enabled.
Definition: functions.lib.php:207
MyObject\info
info($id)
Load the info information in the object.
Definition: myobject.class.php:999
ref
$object ref
Definition: info.php:78
getDolGlobalString
getDolGlobalString($key, $default='')
Return dolibarr global constant string value.
Definition: functions.lib.php:142
MyObject
Class for MyObject.
Definition: myobject.class.php:34
User
Class to manage Dolibarr users.
Definition: user.class.php:47
MyObjectLine\__construct
__construct(DoliDB $db)
Constructor.
Definition: myobject.class.php:1214
MyObject\getKanbanView
getKanbanView($option='', $arraydata=null)
Return a thumb for kanban views.
Definition: myobject.class.php:907
dolGetStatus
dolGetStatus($statusLabel='', $statusLabelShort='', $html='', $statusType='status0', $displayMode=0, $url='', $params=array())
Output the badge of a status.
Definition: functions.lib.php:10967
MyObject\setDraft
setDraft($user, $notrigger=0)
Set draft status.
Definition: myobject.class.php:688
img_object
img_object($titlealt, $picto, $moreatt='', $pictoisfullpath=false, $srconly=0, $notitle=0)
Show a picto called object_picto (generic function)
Definition: functions.lib.php:4473
MyObject\getNextNumRef
getNextNumRef()
Returns the reference to the following non used object depending on the active numbering module.
Definition: myobject.class.php:1073
dol_now
dol_now($mode='auto')
Return date for now.
Definition: functions.lib.php:3056
CommonObject\deleteLineCommon
deleteLineCommon(User $user, $idline, $notrigger=false)
Delete a line of object in database.
Definition: commonobject.class.php:9821
CommonObject\call_trigger
call_trigger($triggerName, $user)
Call trigger based on this instance.
Definition: commonobject.class.php:5790
getDolGlobalInt
getDolGlobalInt($key, $default=0)
Return dolibarr global constant int value.
Definition: functions.lib.php:156
CommonObject\getFieldList
getFieldList($alias='')
Function to concat keys of fields.
Definition: commonobject.class.php:9180