dolibarr  13.0.2
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) ---Put here your own copyright and developer email---
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 3 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program. If not, see <https://www.gnu.org/licenses/>.
17  */
18 
25 // Put here all includes required by your class file
26 require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
27 //require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php';
28 //require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
29 
33 class MyObject extends CommonObject
34 {
38  public $module = 'mymodule';
39 
43  public $element = 'myobject';
44 
48  public $table_element = 'mymodule_myobject';
49 
54  public $ismultientitymanaged = 0;
55 
59  public $isextrafieldmanaged = 1;
60 
64  public $picto = 'myobject@mymodule';
65 
66 
67  const STATUS_DRAFT = 0;
68  const STATUS_VALIDATED = 1;
69  const STATUS_CANCELED = 9;
70 
71 
98  // BEGIN MODULEBUILDER PROPERTIES
102  public $fields = array(
103  'rowid' => array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>1, 'visible'=>-2, 'noteditable'=>1, 'notnull'=> 1, 'index'=>1, 'position'=>1, 'comment'=>'Id', 'css'=>'left'),
104  'ref' => array('type'=>'varchar(128)', 'label'=>'Ref', 'enabled'=>1, 'visible'=>1, 'noteditable'=>0, 'default'=>'', 'notnull'=> 1, 'showoncombobox'=>1, 'index'=>1, 'position'=>10, 'searchall'=>1, 'comment'=>'Reference of object'),
105  'entity' => array('type'=>'integer', 'label'=>'Entity', 'enabled'=>1, 'visible'=>0, 'notnull'=> 1, 'default'=>1, 'index'=>1, 'position'=>20),
106  'label' => array('type'=>'varchar(255)', 'label'=>'Label', 'enabled'=>1, 'visible'=>1, 'position'=>30, 'searchall'=>1, 'css'=>'minwidth300', 'cssview'=>'wordbreak', 'help'=>'Help text', 'showoncombobox'=>1),
107  'amount' => array('type'=>'price', 'label'=>'Amount', 'enabled'=>1, 'visible'=>1, 'default'=>'null', 'position'=>40, 'searchall'=>0, 'isameasure'=>1, 'help'=>'Help text for amount'),
108  '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'),
109  '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'=>1, 'position'=>50, 'notnull'=>-1, 'index'=>1, 'help'=>'LinkToThirparty'),
110  'fk_project' => array('type'=>'integer:Project:projet/class/project.class.php:1', 'label'=>'Project', 'picto'=>'project', 'enabled'=>1, 'visible'=>-1, 'position'=>52, 'notnull'=>-1, 'index'=>1),
111  'description' => array('type'=>'text', 'label'=>'Description', 'enabled'=>1, 'visible'=>3, 'position'=>60),
112  'note_public' => array('type'=>'html', 'label'=>'NotePublic', 'enabled'=>1, 'visible'=>0, 'position'=>61),
113  'note_private' => array('type'=>'html', 'label'=>'NotePrivate', 'enabled'=>1, 'visible'=>0, 'position'=>62),
114  'date_creation' => array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-2, 'notnull'=> 1, 'position'=>500),
115  'tms' => array('type'=>'timestamp', 'label'=>'DateModification', 'enabled'=>1, 'visible'=>-2, 'notnull'=> 0, 'position'=>501),
116  //'date_validation ' =>array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-2, 'position'=>502),
117  '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'),
118  'fk_user_modif' => array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserModif', 'picto'=>'user', 'enabled'=>1, 'visible'=>-2, 'notnull'=>-1, 'position'=>511),
119  //'fk_user_valid' => array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserValidation', 'enabled'=>1, 'visible'=>-1, 'position'=>512),
120  'last_main_doc' => array('type'=>'varchar(255)', 'label'=>'LastMainDoc', 'enabled'=>1, 'visible'=>0, 'notnull'=>0, 'position'=>600),
121  'import_key' => array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>1, 'visible'=>-2, 'notnull'=>-1, 'index'=>0, 'position'=>1000),
122  'model_pdf' => array('type'=>'varchar(255)', 'label'=>'Model pdf', 'enabled'=>1, 'visible'=>0, 'notnull'=>-1, 'position'=>1010),
123  'status' => array('type'=>'smallint', 'label'=>'Status', 'enabled'=>1, 'visible'=>1, 'notnull'=> 1, 'default'=>0, 'index'=>1, 'position'=>1000, 'arrayofkeyval'=>array(0=>'Draft', 1=>'Validated', 9=>'Canceled')),
124  );
125 
129  public $rowid;
130 
134  public $ref;
135 
139  public $entity;
140 
144  public $label;
145 
149  public $amount;
150 
154  public $status;
155 
159  public $date_creation;
160 
164  public $tms;
165 
169  public $fk_user_creat;
170 
174  public $fk_user_modif;
175 
179  public $last_main_doc;
180 
184  public $import_key;
185  // END MODULEBUILDER PROPERTIES
186 
187 
188  // If this object has a subtable with lines
189 
190  // /**
191  // * @var string Name of subtable line
192  // */
193  // public $table_element_line = 'mymodule_myobjectline';
194 
195  // /**
196  // * @var string Field with ID of parent key if this object has a parent
197  // */
198  // public $fk_element = 'fk_myobject';
199 
200  // /**
201  // * @var string Name of subtable class that manage subtable lines
202  // */
203  // public $class_element_line = 'MyObjectline';
204 
205  // /**
206  // * @var array List of child tables. To test if we can delete object.
207  // */
208  // protected $childtables = array();
209 
210  // /**
211  // * @var array List of child tables. To know object to delete on cascade.
212  // * If name matches '@ClassNAme:FilePathClass;ParentFkFieldName' it will
213  // * call method deleteByParentField(parentId, ParentFkFieldName) to fetch and delete child object
214  // */
215  // protected $childtablesoncascade = array('mymodule_myobjectdet');
216 
217  // /**
218  // * @var MyObjectLine[] Array of subtable lines
219  // */
220  // public $lines = array();
221 
222 
223 
229  public function __construct(DoliDB $db)
230  {
231  global $conf, $langs;
232 
233  $this->db = $db;
234 
235  if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID) && isset($this->fields['rowid'])) $this->fields['rowid']['visible'] = 0;
236  if (empty($conf->multicompany->enabled) && isset($this->fields['entity'])) $this->fields['entity']['enabled'] = 0;
237 
238  // Example to show how to set values of fields definition dynamically
239  /*if ($user->rights->mymodule->myobject->read) {
240  $this->fields['myfield']['visible'] = 1;
241  $this->fields['myfield']['noteditable'] = 0;
242  }*/
243 
244  // Unset fields that are disabled
245  foreach ($this->fields as $key => $val)
246  {
247  if (isset($val['enabled']) && empty($val['enabled']))
248  {
249  unset($this->fields[$key]);
250  }
251  }
252 
253  // Translate some data of arrayofkeyval
254  if (is_object($langs))
255  {
256  foreach ($this->fields as $key => $val)
257  {
258  if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval']))
259  {
260  foreach ($val['arrayofkeyval'] as $key2 => $val2)
261  {
262  $this->fields[$key]['arrayofkeyval'][$key2] = $langs->trans($val2);
263  }
264  }
265  }
266  }
267  }
268 
276  public function create(User $user, $notrigger = false)
277  {
278  return $this->createCommon($user, $notrigger);
279  }
280 
288  public function createFromClone(User $user, $fromid)
289  {
290  global $langs, $extrafields;
291  $error = 0;
292 
293  dol_syslog(__METHOD__, LOG_DEBUG);
294 
295  $object = new self($this->db);
296 
297  $this->db->begin();
298 
299  // Load source object
300  $result = $object->fetchCommon($fromid);
301  if ($result > 0 && !empty($object->table_element_line)) $object->fetchLines();
302 
303  // get lines so they will be clone
304  //foreach($this->lines as $line)
305  // $line->fetch_optionals();
306 
307  // Reset some properties
308  unset($object->id);
309  unset($object->fk_user_creat);
310  unset($object->import_key);
311 
312  // Clear fields
313  if (property_exists($object, 'ref')) $object->ref = empty($this->fields['ref']['default']) ? "Copy_Of_".$object->ref : $this->fields['ref']['default'];
314  if (property_exists($object, 'label')) $object->label = empty($this->fields['label']['default']) ? $langs->trans("CopyOf")." ".$object->label : $this->fields['label']['default'];
315  if (property_exists($object, 'status')) { $object->status = self::STATUS_DRAFT; }
316  if (property_exists($object, 'date_creation')) { $object->date_creation = dol_now(); }
317  if (property_exists($object, 'date_modification')) { $object->date_modification = null; }
318  // ...
319  // Clear extrafields that are unique
320  if (is_array($object->array_options) && count($object->array_options) > 0)
321  {
322  $extrafields->fetch_name_optionals_label($this->table_element);
323  foreach ($object->array_options as $key => $option)
324  {
325  $shortkey = preg_replace('/options_/', '', $key);
326  if (!empty($extrafields->attributes[$this->table_element]['unique'][$shortkey]))
327  {
328  //var_dump($key); var_dump($clonedObj->array_options[$key]); exit;
329  unset($object->array_options[$key]);
330  }
331  }
332  }
333 
334  // Create clone
335  $object->context['createfromclone'] = 'createfromclone';
336  $result = $object->createCommon($user);
337  if ($result < 0) {
338  $error++;
339  $this->error = $object->error;
340  $this->errors = $object->errors;
341  }
342 
343  if (!$error)
344  {
345  // copy internal contacts
346  if ($this->copy_linked_contact($object, 'internal') < 0)
347  {
348  $error++;
349  }
350  }
351 
352  if (!$error)
353  {
354  // copy external contacts if same company
355  if (property_exists($this, 'socid') && $this->socid == $object->socid)
356  {
357  if ($this->copy_linked_contact($object, 'external') < 0)
358  $error++;
359  }
360  }
361 
362  unset($object->context['createfromclone']);
363 
364  // End
365  if (!$error) {
366  $this->db->commit();
367  return $object;
368  } else {
369  $this->db->rollback();
370  return -1;
371  }
372  }
373 
381  public function fetch($id, $ref = null)
382  {
383  $result = $this->fetchCommon($id, $ref);
384  if ($result > 0 && !empty($this->table_element_line)) $this->fetchLines();
385  return $result;
386  }
387 
393  public function fetchLines()
394  {
395  $this->lines = array();
396 
397  $result = $this->fetchLinesCommon();
398  return $result;
399  }
400 
401 
413  public function fetchAll($sortorder = '', $sortfield = '', $limit = 0, $offset = 0, array $filter = array(), $filtermode = 'AND')
414  {
415  global $conf;
416 
417  dol_syslog(__METHOD__, LOG_DEBUG);
418 
419  $records = array();
420 
421  $sql = 'SELECT ';
422  $sql .= $this->getFieldList();
423  $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t';
424  if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) $sql .= ' WHERE t.entity IN ('.getEntity($this->table_element).')';
425  else $sql .= ' WHERE 1 = 1';
426  // Manage filter
427  $sqlwhere = array();
428  if (count($filter) > 0) {
429  foreach ($filter as $key => $value) {
430  if ($key == 't.rowid') {
431  $sqlwhere[] = $key.'='.$value;
432  } elseif (in_array($this->fields[$key]['type'], array('date', 'datetime', 'timestamp'))) {
433  $sqlwhere[] = $key.' = \''.$this->db->idate($value).'\'';
434  } elseif ($key == 'customsql') {
435  $sqlwhere[] = $value;
436  } elseif (strpos($value, '%') === false) {
437  $sqlwhere[] = $key.' IN ('.$this->db->sanitize($this->db->escape($value)).')';
438  } else {
439  $sqlwhere[] = $key.' LIKE \'%'.$this->db->escape($value).'%\'';
440  }
441  }
442  }
443  if (count($sqlwhere) > 0) {
444  $sql .= ' AND ('.implode(' '.$filtermode.' ', $sqlwhere).')';
445  }
446 
447  if (!empty($sortfield)) {
448  $sql .= $this->db->order($sortfield, $sortorder);
449  }
450  if (!empty($limit)) {
451  $sql .= ' '.$this->db->plimit($limit, $offset);
452  }
453 
454  $resql = $this->db->query($sql);
455  if ($resql) {
456  $num = $this->db->num_rows($resql);
457  $i = 0;
458  while ($i < ($limit ? min($limit, $num) : $num))
459  {
460  $obj = $this->db->fetch_object($resql);
461 
462  $record = new self($this->db);
463  $record->setVarsFromFetchObj($obj);
464 
465  $records[$record->id] = $record;
466 
467  $i++;
468  }
469  $this->db->free($resql);
470 
471  return $records;
472  } else {
473  $this->errors[] = 'Error '.$this->db->lasterror();
474  dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
475 
476  return -1;
477  }
478  }
479 
487  public function update(User $user, $notrigger = false)
488  {
489  return $this->updateCommon($user, $notrigger);
490  }
491 
499  public function delete(User $user, $notrigger = false)
500  {
501  return $this->deleteCommon($user, $notrigger);
502  //return $this->deleteCommon($user, $notrigger, 1);
503  }
504 
513  public function deleteLine(User $user, $idline, $notrigger = false)
514  {
515  if ($this->status < 0)
516  {
517  $this->error = 'ErrorDeleteLineNotAllowedByObjectStatus';
518  return -2;
519  }
520 
521  return $this->deleteLineCommon($user, $idline, $notrigger);
522  }
523 
524 
532  public function validate($user, $notrigger = 0)
533  {
534  global $conf, $langs;
535 
536  require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
537 
538  $error = 0;
539 
540  // Protection
541  if ($this->status == self::STATUS_VALIDATED)
542  {
543  dol_syslog(get_class($this)."::validate action abandonned: already validated", LOG_WARNING);
544  return 0;
545  }
546 
547  /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->mymodule->myobject->write))
548  || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->mymodule->myobject->myobject_advance->validate))))
549  {
550  $this->error='NotEnoughPermissions';
551  dol_syslog(get_class($this)."::valid ".$this->error, LOG_ERR);
552  return -1;
553  }*/
554 
555  $now = dol_now();
556 
557  $this->db->begin();
558 
559  // Define new ref
560  if (!$error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) // empty should not happened, but when it occurs, the test save life
561  {
562  $num = $this->getNextNumRef();
563  } else {
564  $num = $this->ref;
565  }
566  $this->newref = $num;
567 
568  if (!empty($num)) {
569  // Validate
570  $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
571  $sql .= " SET ref = '".$this->db->escape($num)."',";
572  $sql .= " status = ".self::STATUS_VALIDATED;
573  if (!empty($this->fields['date_validation'])) $sql .= ", date_validation = '".$this->db->idate($now)."'";
574  if (!empty($this->fields['fk_user_valid'])) $sql .= ", fk_user_valid = ".$user->id;
575  $sql .= " WHERE rowid = ".$this->id;
576 
577  dol_syslog(get_class($this)."::validate()", LOG_DEBUG);
578  $resql = $this->db->query($sql);
579  if (!$resql)
580  {
581  dol_print_error($this->db);
582  $this->error = $this->db->lasterror();
583  $error++;
584  }
585 
586  if (!$error && !$notrigger)
587  {
588  // Call trigger
589  $result = $this->call_trigger('MYOBJECT_VALIDATE', $user);
590  if ($result < 0) $error++;
591  // End call triggers
592  }
593  }
594 
595  if (!$error)
596  {
597  $this->oldref = $this->ref;
598 
599  // Rename directory if dir was a temporary ref
600  if (preg_match('/^[\(]?PROV/i', $this->ref))
601  {
602  // Now we rename also files into index
603  $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)."'";
604  $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'myobject/".$this->db->escape($this->ref)."' and entity = ".$conf->entity;
605  $resql = $this->db->query($sql);
606  if (!$resql) { $error++; $this->error = $this->db->lasterror(); }
607 
608  // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments
609  $oldref = dol_sanitizeFileName($this->ref);
610  $newref = dol_sanitizeFileName($num);
611  $dirsource = $conf->mymodule->dir_output.'/myobject/'.$oldref;
612  $dirdest = $conf->mymodule->dir_output.'/myobject/'.$newref;
613  if (!$error && file_exists($dirsource))
614  {
615  dol_syslog(get_class($this)."::validate() rename dir ".$dirsource." into ".$dirdest);
616 
617  if (@rename($dirsource, $dirdest))
618  {
619  dol_syslog("Rename ok");
620  // Rename docs starting with $oldref with $newref
621  $listoffiles = dol_dir_list($conf->mymodule->dir_output.'/myobject/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/'));
622  foreach ($listoffiles as $fileentry)
623  {
624  $dirsource = $fileentry['name'];
625  $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource);
626  $dirsource = $fileentry['path'].'/'.$dirsource;
627  $dirdest = $fileentry['path'].'/'.$dirdest;
628  @rename($dirsource, $dirdest);
629  }
630  }
631  }
632  }
633  }
634 
635  // Set new ref and current status
636  if (!$error)
637  {
638  $this->ref = $num;
639  $this->status = self::STATUS_VALIDATED;
640  }
641 
642  if (!$error)
643  {
644  $this->db->commit();
645  return 1;
646  } else {
647  $this->db->rollback();
648  return -1;
649  }
650  }
651 
652 
660  public function setDraft($user, $notrigger = 0)
661  {
662  // Protection
663  if ($this->status <= self::STATUS_DRAFT)
664  {
665  return 0;
666  }
667 
668  /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->mymodule->write))
669  || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->mymodule->mymodule_advance->validate))))
670  {
671  $this->error='Permission denied';
672  return -1;
673  }*/
674 
675  return $this->setStatusCommon($user, self::STATUS_DRAFT, $notrigger, 'MYOBJECT_UNVALIDATE');
676  }
677 
685  public function cancel($user, $notrigger = 0)
686  {
687  // Protection
688  if ($this->status != self::STATUS_VALIDATED)
689  {
690  return 0;
691  }
692 
693  /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->mymodule->write))
694  || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->mymodule->mymodule_advance->validate))))
695  {
696  $this->error='Permission denied';
697  return -1;
698  }*/
699 
700  return $this->setStatusCommon($user, self::STATUS_CANCELED, $notrigger, 'MYOBJECT_CANCEL');
701  }
702 
710  public function reopen($user, $notrigger = 0)
711  {
712  // Protection
713  if ($this->status != self::STATUS_CANCELED)
714  {
715  return 0;
716  }
717 
718  /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->mymodule->write))
719  || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->mymodule->mymodule_advance->validate))))
720  {
721  $this->error='Permission denied';
722  return -1;
723  }*/
724 
725  return $this->setStatusCommon($user, self::STATUS_VALIDATED, $notrigger, 'MYOBJECT_REOPEN');
726  }
727 
738  public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $morecss = '', $save_lastsearch_value = -1)
739  {
740  global $conf, $langs, $hookmanager;
741 
742  if (!empty($conf->dol_no_mouse_hover)) $notooltip = 1; // Force disable tooltips
743 
744  $result = '';
745 
746  $label = img_picto('', $this->picto).' <u>'.$langs->trans("MyObject").'</u>';
747  if (isset($this->status)) {
748  $label .= ' '.$this->getLibStatut(5);
749  }
750  $label .= '<br>';
751  $label .= '<b>'.$langs->trans('Ref').':</b> '.$this->ref;
752 
753  $url = dol_buildpath('/mymodule/myobject_card.php', 1).'?id='.$this->id;
754 
755  if ($option != 'nolink')
756  {
757  // Add param to save lastsearch_values or not
758  $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
759  if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) $add_save_lastsearch_values = 1;
760  if ($add_save_lastsearch_values) $url .= '&save_lastsearch_values=1';
761  }
762 
763  $linkclose = '';
764  if (empty($notooltip))
765  {
766  if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
767  {
768  $label = $langs->trans("ShowMyObject");
769  $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
770  }
771  $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"';
772  $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"';
773  } else $linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
774 
775  $linkstart = '<a href="'.$url.'"';
776  $linkstart .= $linkclose.'>';
777  $linkend = '</a>';
778 
779  $result .= $linkstart;
780 
781  if (empty($this->showphoto_on_popup)) {
782  if ($withpicto) $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
783  } else {
784  if ($withpicto) {
785  require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
786 
787  list($class, $module) = explode('@', $this->picto);
788  $upload_dir = $conf->$module->multidir_output[$conf->entity]."/$class/".dol_sanitizeFileName($this->ref);
789  $filearray = dol_dir_list($upload_dir, "files");
790  $filename = $filearray[0]['name'];
791  if (!empty($filename)) {
792  $pospoint = strpos($filearray[0]['name'], '.');
793 
794  $pathtophoto = $class.'/'.$this->ref.'/thumbs/'.substr($filename, 0, $pospoint).'_mini'.substr($filename, $pospoint);
795  if (empty($conf->global->{strtoupper($module.'_'.$class).'_FORMATLISTPHOTOSASUSERS'})) {
796  $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>';
797  } else {
798  $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>';
799  }
800 
801  $result .= '</div>';
802  } else {
803  $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
804  }
805  }
806  }
807 
808  if ($withpicto != 2) $result .= $this->ref;
809 
810  $result .= $linkend;
811  //if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : '');
812 
813  global $action, $hookmanager;
814  $hookmanager->initHooks(array('myobjectdao'));
815  $parameters = array('id'=>$this->id, 'getnomurl'=>$result);
816  $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
817  if ($reshook > 0) $result = $hookmanager->resPrint;
818  else $result .= $hookmanager->resPrint;
819 
820  return $result;
821  }
822 
829  public function getLibStatut($mode = 0)
830  {
831  return $this->LibStatut($this->status, $mode);
832  }
833 
834  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
842  public function LibStatut($status, $mode = 0)
843  {
844  // phpcs:enable
845  if (empty($this->labelStatus) || empty($this->labelStatusShort))
846  {
847  global $langs;
848  //$langs->load("mymodule@mymodule");
849  $this->labelStatus[self::STATUS_DRAFT] = $langs->trans('Draft');
850  $this->labelStatus[self::STATUS_VALIDATED] = $langs->trans('Enabled');
851  $this->labelStatus[self::STATUS_CANCELED] = $langs->trans('Disabled');
852  $this->labelStatusShort[self::STATUS_DRAFT] = $langs->trans('Draft');
853  $this->labelStatusShort[self::STATUS_VALIDATED] = $langs->trans('Enabled');
854  $this->labelStatusShort[self::STATUS_CANCELED] = $langs->trans('Disabled');
855  }
856 
857  $statusType = 'status'.$status;
858  //if ($status == self::STATUS_VALIDATED) $statusType = 'status1';
859  if ($status == self::STATUS_CANCELED) $statusType = 'status6';
860 
861  return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
862  }
863 
870  public function info($id)
871  {
872  $sql = 'SELECT rowid, date_creation as datec, tms as datem,';
873  $sql .= ' fk_user_creat, fk_user_modif';
874  $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t';
875  $sql .= ' WHERE t.rowid = '.$id;
876  $result = $this->db->query($sql);
877  if ($result)
878  {
879  if ($this->db->num_rows($result))
880  {
881  $obj = $this->db->fetch_object($result);
882  $this->id = $obj->rowid;
883  if ($obj->fk_user_author)
884  {
885  $cuser = new User($this->db);
886  $cuser->fetch($obj->fk_user_author);
887  $this->user_creation = $cuser;
888  }
889 
890  if ($obj->fk_user_valid)
891  {
892  $vuser = new User($this->db);
893  $vuser->fetch($obj->fk_user_valid);
894  $this->user_validation = $vuser;
895  }
896 
897  if ($obj->fk_user_cloture)
898  {
899  $cluser = new User($this->db);
900  $cluser->fetch($obj->fk_user_cloture);
901  $this->user_cloture = $cluser;
902  }
903 
904  $this->date_creation = $this->db->jdate($obj->datec);
905  $this->date_modification = $this->db->jdate($obj->datem);
906  $this->date_validation = $this->db->jdate($obj->datev);
907  }
908 
909  $this->db->free($result);
910  } else {
911  dol_print_error($this->db);
912  }
913  }
914 
921  public function initAsSpecimen()
922  {
923  $this->initAsSpecimenCommon();
924  }
925 
931  public function getLinesArray()
932  {
933  $this->lines = array();
934 
935  $objectline = new MyObjectLine($this->db);
936  $result = $objectline->fetchAll('ASC', 'position', 0, 0, array('customsql'=>'fk_myobject = '.$this->id));
937 
938  if (is_numeric($result))
939  {
940  $this->error = $this->error;
941  $this->errors = $this->errors;
942  return $result;
943  } else {
944  $this->lines = $result;
945  return $this->lines;
946  }
947  }
948 
954  public function getNextNumRef()
955  {
956  global $langs, $conf;
957  $langs->load("mymodule@mymodule");
958 
959  if (empty($conf->global->MYMODULE_MYOBJECT_ADDON)) {
960  $conf->global->MYMODULE_MYOBJECT_ADDON = 'mod_myobject_standard';
961  }
962 
963  if (!empty($conf->global->MYMODULE_MYOBJECT_ADDON))
964  {
965  $mybool = false;
966 
967  $file = $conf->global->MYMODULE_MYOBJECT_ADDON.".php";
968  $classname = $conf->global->MYMODULE_MYOBJECT_ADDON;
969 
970  // Include file with class
971  $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
972  foreach ($dirmodels as $reldir)
973  {
974  $dir = dol_buildpath($reldir."core/modules/mymodule/");
975 
976  // Load file with numbering class (if found)
977  $mybool |= @include_once $dir.$file;
978  }
979 
980  if ($mybool === false)
981  {
982  dol_print_error('', "Failed to include file ".$file);
983  return '';
984  }
985 
986  if (class_exists($classname)) {
987  $obj = new $classname();
988  $numref = $obj->getNextValue($this);
989 
990  if ($numref != '' && $numref != '-1')
991  {
992  return $numref;
993  } else {
994  $this->error = $obj->error;
995  //dol_print_error($this->db,get_class($this)."::getNextNumRef ".$obj->error);
996  return "";
997  }
998  } else {
999  print $langs->trans("Error")." ".$langs->trans("ClassNotFound").' '.$classname;
1000  return "";
1001  }
1002  } else {
1003  print $langs->trans("ErrorNumberingModuleNotSetup", $this->element);
1004  return "";
1005  }
1006  }
1007 
1019  public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
1020  {
1021  global $conf, $langs;
1022 
1023  $result = 0;
1024  $includedocgeneration = 0;
1025 
1026  $langs->load("mymodule@mymodule");
1027 
1028  if (!dol_strlen($modele)) {
1029  $modele = 'standard_myobject';
1030 
1031  if (!empty($this->model_pdf)) {
1032  $modele = $this->model_pdf;
1033  } elseif (!empty($conf->global->MYOBJECT_ADDON_PDF)) {
1034  $modele = $conf->global->MYOBJECT_ADDON_PDF;
1035  }
1036  }
1037 
1038  $modelpath = "core/modules/mymodule/doc/";
1039 
1040  if ($includedocgeneration && !empty($modele)) {
1041  $result = $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
1042  }
1043 
1044  return $result;
1045  }
1046 
1054  public function doScheduledJob()
1055  {
1056  global $conf, $langs;
1057 
1058  //$conf->global->SYSLOG_FILE = 'DOL_DATA_ROOT/dolibarr_mydedicatedlofile.log';
1059 
1060  $error = 0;
1061  $this->output = '';
1062  $this->error = '';
1063 
1064  dol_syslog(__METHOD__, LOG_DEBUG);
1065 
1066  $now = dol_now();
1067 
1068  $this->db->begin();
1069 
1070  // ...
1071 
1072  $this->db->commit();
1073 
1074  return $error;
1075  }
1076 }
1077 
1078 
1079 require_once DOL_DOCUMENT_ROOT.'/core/class/commonobjectline.class.php';
1080 
1085 {
1086  // To complete with content of an object MyObjectLine
1087  // We should have a field rowid, fk_myobject and position
1088 
1092  public $isextrafieldmanaged = 0;
1093 
1099  public function __construct(DoliDB $db)
1100  {
1101  $this->db = $db;
1102  }
1103 }
cancel($user, $notrigger=0)
Set cancel status.
deleteCommon(User $user, $notrigger=false, $forcechilddeletion=0)
Delete object in database.
generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0, $moreparams=null)
Create a document onto disk according to template module.
getLibStatut($mode=0)
Return the label of the status.
getNextNumRef()
Returns the reference to the following non used object depending on the active numbering module...
getNomUrl($withpicto=0, $option= '', $notooltip=0, $morecss= '', $save_lastsearch_value=-1)
Return a link to the object card (with optionaly the picto)
fetchLinesCommon($morewhere= '')
Load object in memory from the database.
setDraft($user, $notrigger=0)
Set draft status.
foreach($object->fields as $key=> $val) if(is_array($extrafields->attributes[$object->table_element]['label'])&&count($extrafields->attributes[$object->table_element]['label']) > 0) $object fields
initAsSpecimen()
Initialise object with example values Id must be 0 if object instance is a specimen.
dol_now($mode= 'auto')
Return date for now.
Class to manage Dolibarr users.
Definition: user.class.php:44
Class to manage Dolibarr database access.
__construct(DoliDB $db)
Constructor.
fetch($id, $ref=null)
Load object in memory from the database.
createCommon(User $user, $notrigger=false)
Create object into database.
Class for MyObject.
reopen($user, $notrigger=0)
Set back to validated status.
doScheduledJob()
Action executed by scheduler CAN BE A CRON TASK.
info($id)
Load the info information in the object.
dol_buildpath($path, $type=0, $returnemptyifnotfound=0)
Return path of url or filesystem.
$conf db
API class for accounts.
Definition: inc.php:54
Parent class for class inheritance lines of business objects This class is useless for the moment so ...
update(User $user, $notrigger=false)
Update object into database.
dol_strlen($string, $stringencoding= 'UTF-8')
Make a strlen call.
img_picto($titlealt, $picto, $moreatt= '', $pictoisfullpath=false, $srconly=0, $notitle=0, $alt= '', $morecss= '', $marginleftonlyshort=2)
Show picto whatever it&#39;s its name (generic function)
fetchLines()
Load object lines in memory from the database.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename= '', $restricttologhandler= '', $logcontext=null)
Write log message into outputs.
Class MyObjectLine.
img_object($titlealt, $picto, $moreatt= '', $pictoisfullpath=false, $srconly=0, $notitle=0)
Show a picto called object_picto (generic function)
updateCommon(User $user, $notrigger=false)
Update object into database.
dol_sanitizeFileName($str, $newstr= '_', $unaccent=1)
Clean a string to use it as a file name.
dol_dir_list($path, $types="all", $recursive=0, $filter="", $excludefilter=null, $sortcriteria="name", $sortorder=SORT_ASC, $mode=0, $nohook=0, $relativename="", $donotfollowsymlinks=0)
Scan a directory and return a list of files/directories.
Definition: files.lib.php:60
validate($user, $notrigger=0)
Validate object.
print $_SERVER["PHP_SELF"]
Edit parameters.
__construct(DoliDB $db)
Constructor.
deleteLineCommon(User $user, $idline, $notrigger=false)
Delete a line of object in database.
copy_linked_contact($objFrom, $source= 'internal')
Copy contact from one element to current.
print
Draft customers invoices.
Definition: index.php:89
call_trigger($triggerName, $user)
Call trigger based on this instance.
fetchAll($sortorder= '', $sortfield= '', $limit=0, $offset=0, array $filter=array(), $filtermode= 'AND')
Load list of objects in memory from the database.
if(!empty($conf->facture->enabled)&&$user->rights->facture->lire) if((!empty($conf->fournisseur->enabled)&&empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD)||!empty($conf->supplier_invoice->enabled))&&$user->rights->fournisseur->facture->lire) if(!empty($conf->don->enabled)&&$user->rights->don->lire) if(!empty($conf->tax->enabled)&&$user->rights->tax->charges->lire) if(!empty($conf->facture->enabled)&&!empty($conf->commande->enabled)&&$user->rights->commande->lire &&empty($conf->global->WORKFLOW_DISABLE_CREATE_INVOICE_FROM_ORDER)) if(!empty($conf->facture->enabled)&&$user->rights->facture->lire) if((!empty($conf->fournisseur->enabled)&&empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD)||!empty($conf->supplier_invoice->enabled))&&$user->rights->fournisseur->facture->lire) $resql
Social contributions to pay.
Definition: index.php:1232
dol_print_error($db= '', $error= '', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
setStatusCommon($user, $status, $notrigger=0, $triggercode= '')
Set to a status.
getFieldList()
Function to concat keys of fields.
dolGetStatus($statusLabel= '', $statusLabelShort= '', $html= '', $statusType= 'status0', $displayMode=0, $url= '', $params=array())
Output the badge of a status.
createFromClone(User $user, $fromid)
Clone an object into another one.
LibStatut($status, $mode=0)
Return the status.
Parent class of all other business classes (invoices, contracts, proposals, orders, ...)
create(User $user, $notrigger=false)
Create object into database.
fetchCommon($id, $ref=null, $morewhere= '')
Load object in memory from the database.
deleteLine(User $user, $idline, $notrigger=false)
Delete a line of object in database.
getLinesArray()
Create an array of lines.