dolibarr  16.0.5
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 = 'fa-file';
65 
66 
67  const STATUS_DRAFT = 0;
68  const STATUS_VALIDATED = 1;
69  const STATUS_CANCELED = 9;
70 
71 
110  // BEGIN MODULEBUILDER PROPERTIES
114  public $fields = array(
115  'rowid' => array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>1, 'visible'=>-2, 'noteditable'=>1, 'notnull'=> 1, 'index'=>1, 'position'=>1, 'comment'=>'Id', 'css'=>'left'),
116  'entity' => array('type'=>'integer', 'label'=>'Entity', 'enabled'=>1, 'visible'=>0, 'notnull'=> 1, 'default'=>1, 'index'=>1, 'position'=>10),
117  '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),
118  '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),
119  '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),
120  '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),
121  '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'=>'$conf->societe->enabled', 'position'=>50, 'notnull'=>-1, 'index'=>1, 'help'=>'OrganizationEventLinkToThirdParty', 'validate'=>1, 'css'=>'maxwidth500 widthcentpercentminusxx'),
122  'fk_project' => array('type'=>'integer:Project:projet/class/project.class.php:1', 'label'=>'Project', 'picto'=>'project', 'enabled'=>'$conf->project->enabled', 'visible'=>-1, 'position'=>52, 'notnull'=>-1, 'index'=>1, 'validate'=>1, 'css'=>'maxwidth500 widthcentpercentminusxx'),
123  'description' => array('type'=>'text', 'label'=>'Description', 'enabled'=>1, 'visible'=>3, 'position'=>60, 'validate'=>1),
124  'note_public' => array('type'=>'html', 'label'=>'NotePublic', 'enabled'=>1, 'visible'=>0, 'position'=>61, 'validate'=>1, 'cssview'=>'wordbreak'),
125  'note_private' => array('type'=>'html', 'label'=>'NotePrivate', 'enabled'=>1, 'visible'=>0, 'position'=>62, 'validate'=>1, 'cssview'=>'wordbreak'),
126  'date_creation' => array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-2, 'notnull'=> 1, 'position'=>500),
127  'tms' => array('type'=>'timestamp', 'label'=>'DateModification', 'enabled'=>1, 'visible'=>-2, 'notnull'=> 0, 'position'=>501),
128  //'date_validation ' =>array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-2, 'position'=>502),
129  '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'),
130  'fk_user_modif' => array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserModif', 'picto'=>'user', 'enabled'=>1, 'visible'=>-2, 'notnull'=>-1, 'position'=>511),
131  //'fk_user_valid' => array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserValidation', 'enabled'=>1, 'visible'=>-1, 'position'=>512),
132  'last_main_doc' => array('type'=>'varchar(255)', 'label'=>'LastMainDoc', 'enabled'=>1, 'visible'=>0, 'notnull'=>0, 'position'=>600),
133  'import_key' => array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>1, 'visible'=>-2, 'notnull'=>-1, 'index'=>0, 'position'=>1000),
134  'model_pdf' => array('type'=>'varchar(255)', 'label'=>'Model pdf', 'enabled'=>1, 'visible'=>0, 'notnull'=>-1, 'position'=>1010),
135  '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),
136  );
137 
141  public $rowid;
142 
146  public $ref;
147 
151  public $entity;
152 
156  public $label;
157 
161  public $amount;
162 
166  public $socid; // both socid and fk_soc are used
167  public $fk_soc; // both socid and fk_soc are used
168 
172  public $status;
173 
177  public $date_creation;
178 
182  public $tms;
183 
187  public $fk_user_creat;
188 
192  public $fk_user_modif;
193 
197  public $last_main_doc;
198 
202  public $import_key;
203  // END MODULEBUILDER PROPERTIES
204 
205 
206  // If this object has a subtable with lines
207 
208  // /**
209  // * @var string Name of subtable line
210  // */
211  // public $table_element_line = 'mymodule_myobjectline';
212 
213  // /**
214  // * @var string Field with ID of parent key if this object has a parent
215  // */
216  // public $fk_element = 'fk_myobject';
217 
218  // /**
219  // * @var string Name of subtable class that manage subtable lines
220  // */
221  // public $class_element_line = 'MyObjectline';
222 
223  // /**
224  // * @var array List of child tables. To test if we can delete object.
225  // */
226  // protected $childtables = array();
227 
228  // /**
229  // * @var array List of child tables. To know object to delete on cascade.
230  // * If name matches '@ClassNAme:FilePathClass;ParentFkFieldName' it will
231  // * call method deleteByParentField(parentId, ParentFkFieldName) to fetch and delete child object
232  // */
233  // protected $childtablesoncascade = array('mymodule_myobjectdet');
234 
235  // /**
236  // * @var MyObjectLine[] Array of subtable lines
237  // */
238  // public $lines = array();
239 
240 
241 
247  public function __construct(DoliDB $db)
248  {
249  global $conf, $langs;
250 
251  $this->db = $db;
252 
253  if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID) && isset($this->fields['rowid']) && !empty($this->fields['ref'])) {
254  $this->fields['rowid']['visible'] = 0;
255  }
256  if (empty($conf->multicompany->enabled) && isset($this->fields['entity'])) {
257  $this->fields['entity']['enabled'] = 0;
258  }
259 
260  // Example to show how to set values of fields definition dynamically
261  /*if ($user->rights->mymodule->myobject->read) {
262  $this->fields['myfield']['visible'] = 1;
263  $this->fields['myfield']['noteditable'] = 0;
264  }*/
265 
266  // Unset fields that are disabled
267  foreach ($this->fields as $key => $val) {
268  if (isset($val['enabled']) && empty($val['enabled'])) {
269  unset($this->fields[$key]);
270  }
271  }
272 
273  // Translate some data of arrayofkeyval
274  if (is_object($langs)) {
275  foreach ($this->fields as $key => $val) {
276  if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
277  foreach ($val['arrayofkeyval'] as $key2 => $val2) {
278  $this->fields[$key]['arrayofkeyval'][$key2] = $langs->trans($val2);
279  }
280  }
281  }
282  }
283  }
284 
292  public function create(User $user, $notrigger = false)
293  {
294  $resultcreate = $this->createCommon($user, $notrigger);
295 
296  //$resultvalidate = $this->validate($user, $notrigger);
297 
298  return $resultcreate;
299  }
300 
308  public function createFromClone(User $user, $fromid)
309  {
310  global $langs, $extrafields;
311  $error = 0;
312 
313  dol_syslog(__METHOD__, LOG_DEBUG);
314 
315  $object = new self($this->db);
316 
317  $this->db->begin();
318 
319  // Load source object
320  $result = $object->fetchCommon($fromid);
321  if ($result > 0 && !empty($object->table_element_line)) {
322  $object->fetchLines();
323  }
324 
325  // get lines so they will be clone
326  //foreach($this->lines as $line)
327  // $line->fetch_optionals();
328 
329  // Reset some properties
330  unset($object->id);
331  unset($object->fk_user_creat);
332  unset($object->import_key);
333 
334  // Clear fields
335  if (property_exists($object, 'ref')) {
336  $object->ref = empty($this->fields['ref']['default']) ? "Copy_Of_".$object->ref : $this->fields['ref']['default'];
337  }
338  if (property_exists($object, 'label')) {
339  $object->label = empty($this->fields['label']['default']) ? $langs->trans("CopyOf")." ".$object->label : $this->fields['label']['default'];
340  }
341  if (property_exists($object, 'status')) {
342  $object->status = self::STATUS_DRAFT;
343  }
344  if (property_exists($object, 'date_creation')) {
345  $object->date_creation = dol_now();
346  }
347  if (property_exists($object, 'date_modification')) {
348  $object->date_modification = null;
349  }
350  // ...
351  // Clear extrafields that are unique
352  if (is_array($object->array_options) && count($object->array_options) > 0) {
353  $extrafields->fetch_name_optionals_label($this->table_element);
354  foreach ($object->array_options as $key => $option) {
355  $shortkey = preg_replace('/options_/', '', $key);
356  if (!empty($extrafields->attributes[$this->table_element]['unique'][$shortkey])) {
357  //var_dump($key);
358  //var_dump($clonedObj->array_options[$key]); exit;
359  unset($object->array_options[$key]);
360  }
361  }
362  }
363 
364  // Create clone
365  $object->context['createfromclone'] = 'createfromclone';
366  $result = $object->createCommon($user);
367  if ($result < 0) {
368  $error++;
369  $this->error = $object->error;
370  $this->errors = $object->errors;
371  }
372 
373  if (!$error) {
374  // copy internal contacts
375  if ($this->copy_linked_contact($object, 'internal') < 0) {
376  $error++;
377  }
378  }
379 
380  if (!$error) {
381  // copy external contacts if same company
382  if (!empty($object->socid) && property_exists($this, 'fk_soc') && $this->fk_soc == $object->socid) {
383  if ($this->copy_linked_contact($object, 'external') < 0) {
384  $error++;
385  }
386  }
387  }
388 
389  unset($object->context['createfromclone']);
390 
391  // End
392  if (!$error) {
393  $this->db->commit();
394  return $object;
395  } else {
396  $this->db->rollback();
397  return -1;
398  }
399  }
400 
408  public function fetch($id, $ref = null)
409  {
410  $result = $this->fetchCommon($id, $ref);
411  if ($result > 0 && !empty($this->table_element_line)) {
412  $this->fetchLines();
413  }
414  return $result;
415  }
416 
422  public function fetchLines()
423  {
424  $this->lines = array();
425 
426  $result = $this->fetchLinesCommon();
427  return $result;
428  }
429 
430 
442  public function fetchAll($sortorder = '', $sortfield = '', $limit = 0, $offset = 0, array $filter = array(), $filtermode = 'AND')
443  {
444  global $conf;
445 
446  dol_syslog(__METHOD__, LOG_DEBUG);
447 
448  $records = array();
449 
450  $sql = "SELECT ";
451  $sql .= $this->getFieldList('t');
452  $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element." as t";
453  if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
454  $sql .= " WHERE t.entity IN (".getEntity($this->element).")";
455  } else {
456  $sql .= " WHERE 1 = 1";
457  }
458  // Manage filter
459  $sqlwhere = array();
460  if (count($filter) > 0) {
461  foreach ($filter as $key => $value) {
462  if ($key == 't.rowid') {
463  $sqlwhere[] = $key." = ".((int) $value);
464  } elseif (in_array($this->fields[$key]['type'], array('date', 'datetime', 'timestamp'))) {
465  $sqlwhere[] = $key." = '".$this->db->idate($value)."'";
466  } elseif ($key == 'customsql') {
467  $sqlwhere[] = $value;
468  } elseif (strpos($value, '%') === false) {
469  $sqlwhere[] = $key." IN (".$this->db->sanitize($this->db->escape($value)).")";
470  } else {
471  $sqlwhere[] = $key." LIKE '%".$this->db->escape($value)."%'";
472  }
473  }
474  }
475  if (count($sqlwhere) > 0) {
476  $sql .= " AND (".implode(" ".$filtermode." ", $sqlwhere).")";
477  }
478 
479  if (!empty($sortfield)) {
480  $sql .= $this->db->order($sortfield, $sortorder);
481  }
482  if (!empty($limit)) {
483  $sql .= $this->db->plimit($limit, $offset);
484  }
485 
486  $resql = $this->db->query($sql);
487  if ($resql) {
488  $num = $this->db->num_rows($resql);
489  $i = 0;
490  while ($i < ($limit ? min($limit, $num) : $num)) {
491  $obj = $this->db->fetch_object($resql);
492 
493  $record = new self($this->db);
494  $record->setVarsFromFetchObj($obj);
495 
496  $records[$record->id] = $record;
497 
498  $i++;
499  }
500  $this->db->free($resql);
501 
502  return $records;
503  } else {
504  $this->errors[] = 'Error '.$this->db->lasterror();
505  dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
506 
507  return -1;
508  }
509  }
510 
518  public function update(User $user, $notrigger = false)
519  {
520  return $this->updateCommon($user, $notrigger);
521  }
522 
530  public function delete(User $user, $notrigger = false)
531  {
532  return $this->deleteCommon($user, $notrigger);
533  //return $this->deleteCommon($user, $notrigger, 1);
534  }
535 
544  public function deleteLine(User $user, $idline, $notrigger = false)
545  {
546  if ($this->status < 0) {
547  $this->error = 'ErrorDeleteLineNotAllowedByObjectStatus';
548  return -2;
549  }
550 
551  return $this->deleteLineCommon($user, $idline, $notrigger);
552  }
553 
554 
562  public function validate($user, $notrigger = 0)
563  {
564  global $conf, $langs;
565 
566  require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
567 
568  $error = 0;
569 
570  // Protection
571  if ($this->status == self::STATUS_VALIDATED) {
572  dol_syslog(get_class($this)."::validate action abandonned: already validated", LOG_WARNING);
573  return 0;
574  }
575 
576  /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->mymodule->myobject->write))
577  || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->mymodule->myobject->myobject_advance->validate))))
578  {
579  $this->error='NotEnoughPermissions';
580  dol_syslog(get_class($this)."::valid ".$this->error, LOG_ERR);
581  return -1;
582  }*/
583 
584  $now = dol_now();
585 
586  $this->db->begin();
587 
588  // Define new ref
589  if (!$error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) { // empty should not happened, but when it occurs, the test save life
590  $num = $this->getNextNumRef();
591  } else {
592  $num = $this->ref;
593  }
594  $this->newref = $num;
595 
596  if (!empty($num)) {
597  // Validate
598  $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
599  $sql .= " SET ref = '".$this->db->escape($num)."',";
600  $sql .= " status = ".self::STATUS_VALIDATED;
601  if (!empty($this->fields['date_validation'])) {
602  $sql .= ", date_validation = '".$this->db->idate($now)."'";
603  }
604  if (!empty($this->fields['fk_user_valid'])) {
605  $sql .= ", fk_user_valid = ".((int) $user->id);
606  }
607  $sql .= " WHERE rowid = ".((int) $this->id);
608 
609  dol_syslog(get_class($this)."::validate()", LOG_DEBUG);
610  $resql = $this->db->query($sql);
611  if (!$resql) {
612  dol_print_error($this->db);
613  $this->error = $this->db->lasterror();
614  $error++;
615  }
616 
617  if (!$error && !$notrigger) {
618  // Call trigger
619  $result = $this->call_trigger('MYOBJECT_VALIDATE', $user);
620  if ($result < 0) {
621  $error++;
622  }
623  // End call triggers
624  }
625  }
626 
627  if (!$error) {
628  $this->oldref = $this->ref;
629 
630  // Rename directory if dir was a temporary ref
631  if (preg_match('/^[\(]?PROV/i', $this->ref)) {
632  // Now we rename also files into index
633  $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)."'";
634  $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'myobject/".$this->db->escape($this->ref)."' and entity = ".$conf->entity;
635  $resql = $this->db->query($sql);
636  if (!$resql) {
637  $error++; $this->error = $this->db->lasterror();
638  }
639 
640  // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments
641  $oldref = dol_sanitizeFileName($this->ref);
642  $newref = dol_sanitizeFileName($num);
643  $dirsource = $conf->mymodule->dir_output.'/myobject/'.$oldref;
644  $dirdest = $conf->mymodule->dir_output.'/myobject/'.$newref;
645  if (!$error && file_exists($dirsource)) {
646  dol_syslog(get_class($this)."::validate() rename dir ".$dirsource." into ".$dirdest);
647 
648  if (@rename($dirsource, $dirdest)) {
649  dol_syslog("Rename ok");
650  // Rename docs starting with $oldref with $newref
651  $listoffiles = dol_dir_list($conf->mymodule->dir_output.'/myobject/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/'));
652  foreach ($listoffiles as $fileentry) {
653  $dirsource = $fileentry['name'];
654  $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource);
655  $dirsource = $fileentry['path'].'/'.$dirsource;
656  $dirdest = $fileentry['path'].'/'.$dirdest;
657  @rename($dirsource, $dirdest);
658  }
659  }
660  }
661  }
662  }
663 
664  // Set new ref and current status
665  if (!$error) {
666  $this->ref = $num;
667  $this->status = self::STATUS_VALIDATED;
668  }
669 
670  if (!$error) {
671  $this->db->commit();
672  return 1;
673  } else {
674  $this->db->rollback();
675  return -1;
676  }
677  }
678 
679 
687  public function setDraft($user, $notrigger = 0)
688  {
689  // Protection
690  if ($this->status <= self::STATUS_DRAFT) {
691  return 0;
692  }
693 
694  /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->mymodule->write))
695  || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->mymodule->mymodule_advance->validate))))
696  {
697  $this->error='Permission denied';
698  return -1;
699  }*/
700 
701  return $this->setStatusCommon($user, self::STATUS_DRAFT, $notrigger, 'MYOBJECT_UNVALIDATE');
702  }
703 
711  public function cancel($user, $notrigger = 0)
712  {
713  // Protection
714  if ($this->status != self::STATUS_VALIDATED) {
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_CANCELED, $notrigger, 'MYOBJECT_CANCEL');
726  }
727 
735  public function reopen($user, $notrigger = 0)
736  {
737  // Protection
738  if ($this->status != self::STATUS_CANCELED) {
739  return 0;
740  }
741 
742  /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->mymodule->write))
743  || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->mymodule->mymodule_advance->validate))))
744  {
745  $this->error='Permission denied';
746  return -1;
747  }*/
748 
749  return $this->setStatusCommon($user, self::STATUS_VALIDATED, $notrigger, 'MYOBJECT_REOPEN');
750  }
751 
762  public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $morecss = '', $save_lastsearch_value = -1)
763  {
764  global $conf, $langs, $hookmanager;
765 
766  if (!empty($conf->dol_no_mouse_hover)) {
767  $notooltip = 1; // Force disable tooltips
768  }
769 
770  $result = '';
771 
772  $label = img_picto('', $this->picto).' <u>'.$langs->trans("MyObject").'</u>';
773  if (isset($this->status)) {
774  $label .= ' '.$this->getLibStatut(5);
775  }
776  $label .= '<br>';
777  $label .= '<b>'.$langs->trans('Ref').':</b> '.$this->ref;
778 
779  $url = dol_buildpath('/mymodule/myobject_card.php', 1).'?id='.$this->id;
780 
781  if ($option != 'nolink') {
782  // Add param to save lastsearch_values or not
783  $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
784  if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
785  $add_save_lastsearch_values = 1;
786  }
787  if ($url && $add_save_lastsearch_values) {
788  $url .= '&save_lastsearch_values=1';
789  }
790  }
791 
792  $linkclose = '';
793  if (empty($notooltip)) {
794  if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
795  $label = $langs->trans("ShowMyObject");
796  $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
797  }
798  $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"';
799  $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"';
800  } else {
801  $linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
802  }
803 
804  if ($option == 'nolink' || empty($url)) {
805  $linkstart = '<span';
806  } else {
807  $linkstart = '<a href="'.$url.'"';
808  }
809  $linkstart .= $linkclose.'>';
810  if ($option == 'nolink' || empty($url)) {
811  $linkend = '</span>';
812  } else {
813  $linkend = '</a>';
814  }
815 
816  $result .= $linkstart;
817 
818  if (empty($this->showphoto_on_popup)) {
819  if ($withpicto) {
820  $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);
821  }
822  } else {
823  if ($withpicto) {
824  require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
825 
826  list($class, $module) = explode('@', $this->picto);
827  $upload_dir = $conf->$module->multidir_output[$conf->entity]."/$class/".dol_sanitizeFileName($this->ref);
828  $filearray = dol_dir_list($upload_dir, "files");
829  $filename = $filearray[0]['name'];
830  if (!empty($filename)) {
831  $pospoint = strpos($filearray[0]['name'], '.');
832 
833  $pathtophoto = $class.'/'.$this->ref.'/thumbs/'.substr($filename, 0, $pospoint).'_mini'.substr($filename, $pospoint);
834  if (empty($conf->global->{strtoupper($module.'_'.$class).'_FORMATLISTPHOTOSASUSERS'})) {
835  $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>';
836  } else {
837  $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>';
838  }
839 
840  $result .= '</div>';
841  } else {
842  $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);
843  }
844  }
845  }
846 
847  if ($withpicto != 2) {
848  $result .= $this->ref;
849  }
850 
851  $result .= $linkend;
852  //if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : '');
853 
854  global $action, $hookmanager;
855  $hookmanager->initHooks(array('myobjectdao'));
856  $parameters = array('id'=>$this->id, 'getnomurl' => &$result);
857  $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
858  if ($reshook > 0) {
859  $result = $hookmanager->resPrint;
860  } else {
861  $result .= $hookmanager->resPrint;
862  }
863 
864  return $result;
865  }
866 
873  public function getLabelStatus($mode = 0)
874  {
875  return $this->LibStatut($this->status, $mode);
876  }
877 
884  public function getLibStatut($mode = 0)
885  {
886  return $this->LibStatut($this->status, $mode);
887  }
888 
889  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
897  public function LibStatut($status, $mode = 0)
898  {
899  // phpcs:enable
900  if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
901  global $langs;
902  //$langs->load("mymodule@mymodule");
903  $this->labelStatus[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('Draft');
904  $this->labelStatus[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('Enabled');
905  $this->labelStatus[self::STATUS_CANCELED] = $langs->transnoentitiesnoconv('Disabled');
906  $this->labelStatusShort[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('Draft');
907  $this->labelStatusShort[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('Enabled');
908  $this->labelStatusShort[self::STATUS_CANCELED] = $langs->transnoentitiesnoconv('Disabled');
909  }
910 
911  $statusType = 'status'.$status;
912  //if ($status == self::STATUS_VALIDATED) $statusType = 'status1';
913  if ($status == self::STATUS_CANCELED) {
914  $statusType = 'status6';
915  }
916 
917  return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
918  }
919 
926  public function info($id)
927  {
928  $sql = "SELECT rowid,";
929  $sql .= " date_creation as datec, tms as datem,";
930  $sql .= " fk_user_creat, fk_user_modif";
931  $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element." as t";
932  $sql .= " WHERE t.rowid = ".((int) $id);
933 
934  $result = $this->db->query($sql);
935  if ($result) {
936  if ($this->db->num_rows($result)) {
937  $obj = $this->db->fetch_object($result);
938 
939  $this->id = $obj->rowid;
940 
941  $this->user_creation_id = $obj->fk_user_creat;
942  $this->user_modification_id = $obj->fk_user_modif;
943  if (!empty($obj->fk_user_valid)) {
944  $this->user_validation_id = $obj->fk_user_valid;
945  }
946  $this->date_creation = $this->db->jdate($obj->datec);
947  $this->date_modification = empty($obj->datem) ? '' : $this->db->jdate($obj->datem);
948  if (!empty($obj->datev)) {
949  $this->date_validation = empty($obj->datev) ? '' : $this->db->jdate($obj->datev);
950  }
951  }
952 
953  $this->db->free($result);
954  } else {
955  dol_print_error($this->db);
956  }
957  }
958 
965  public function initAsSpecimen()
966  {
967  // Set here init that are not commonf fields
968  // $this->property1 = ...
969  // $this->property2 = ...
970 
971  $this->initAsSpecimenCommon();
972  }
973 
979  public function getLinesArray()
980  {
981  $this->lines = array();
982 
983  $objectline = new MyObjectLine($this->db);
984  $result = $objectline->fetchAll('ASC', 'position', 0, 0, array('customsql'=>'fk_myobject = '.((int) $this->id)));
985 
986  if (is_numeric($result)) {
987  $this->error = $objectline->error;
988  $this->errors = $objectline->errors;
989  return $result;
990  } else {
991  $this->lines = $result;
992  return $this->lines;
993  }
994  }
995 
1001  public function getNextNumRef()
1002  {
1003  global $langs, $conf;
1004  $langs->load("mymodule@mymodule");
1005 
1006  if (empty($conf->global->MYMODULE_MYOBJECT_ADDON)) {
1007  $conf->global->MYMODULE_MYOBJECT_ADDON = 'mod_myobject_standard';
1008  }
1009 
1010  if (!empty($conf->global->MYMODULE_MYOBJECT_ADDON)) {
1011  $mybool = false;
1012 
1013  $file = $conf->global->MYMODULE_MYOBJECT_ADDON.".php";
1014  $classname = $conf->global->MYMODULE_MYOBJECT_ADDON;
1015 
1016  // Include file with class
1017  $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
1018  foreach ($dirmodels as $reldir) {
1019  $dir = dol_buildpath($reldir."core/modules/mymodule/");
1020 
1021  // Load file with numbering class (if found)
1022  $mybool |= @include_once $dir.$file;
1023  }
1024 
1025  if ($mybool === false) {
1026  dol_print_error('', "Failed to include file ".$file);
1027  return '';
1028  }
1029 
1030  if (class_exists($classname)) {
1031  $obj = new $classname();
1032  $numref = $obj->getNextValue($this);
1033 
1034  if ($numref != '' && $numref != '-1') {
1035  return $numref;
1036  } else {
1037  $this->error = $obj->error;
1038  //dol_print_error($this->db,get_class($this)."::getNextNumRef ".$obj->error);
1039  return "";
1040  }
1041  } else {
1042  print $langs->trans("Error")." ".$langs->trans("ClassNotFound").' '.$classname;
1043  return "";
1044  }
1045  } else {
1046  print $langs->trans("ErrorNumberingModuleNotSetup", $this->element);
1047  return "";
1048  }
1049  }
1050 
1062  public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
1063  {
1064  global $conf, $langs;
1065 
1066  $result = 0;
1067  $includedocgeneration = 0;
1068 
1069  $langs->load("mymodule@mymodule");
1070 
1071  if (!dol_strlen($modele)) {
1072  $modele = 'standard_myobject';
1073 
1074  if (!empty($this->model_pdf)) {
1075  $modele = $this->model_pdf;
1076  } elseif (!empty($conf->global->MYOBJECT_ADDON_PDF)) {
1077  $modele = $conf->global->MYOBJECT_ADDON_PDF;
1078  }
1079  }
1080 
1081  $modelpath = "core/modules/mymodule/doc/";
1082 
1083  if ($includedocgeneration && !empty($modele)) {
1084  $result = $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
1085  }
1086 
1087  return $result;
1088  }
1089 
1097  public function doScheduledJob()
1098  {
1099  global $conf, $langs;
1100 
1101  //$conf->global->SYSLOG_FILE = 'DOL_DATA_ROOT/dolibarr_mydedicatedlofile.log';
1102 
1103  $error = 0;
1104  $this->output = '';
1105  $this->error = '';
1106 
1107  dol_syslog(__METHOD__, LOG_DEBUG);
1108 
1109  $now = dol_now();
1110 
1111  $this->db->begin();
1112 
1113  // ...
1114 
1115  $this->db->commit();
1116 
1117  return $error;
1118  }
1119 }
1120 
1121 
1122 require_once DOL_DOCUMENT_ROOT.'/core/class/commonobjectline.class.php';
1123 
1128 {
1129  // To complete with content of an object MyObjectLine
1130  // We should have a field rowid, fk_myobject and position
1131 
1135  public $isextrafieldmanaged = 0;
1136 
1142  public function __construct(DoliDB $db)
1143  {
1144  $this->db = $db;
1145  }
1146 }
CommonObject\deleteCommon
deleteCommon(User $user, $notrigger=false, $forcechilddeletion=0)
Delete object in database.
Definition: commonobject.class.php:9406
CommonObject\setStatusCommon
setStatusCommon($user, $status, $notrigger=0, $triggercode='')
Set to a status.
Definition: commonobject.class.php:9683
MyObject\validate
validate($user, $notrigger=0)
Validate object.
Definition: myobject.class.php:562
db
$conf db
API class for accounts.
Definition: inc.php:41
MyObject\reopen
reopen($user, $notrigger=0)
Set back to validated status.
Definition: myobject.class.php:735
CommonObject\fetchCommon
fetchCommon($id, $ref=null, $morewhere='')
Load object in memory from the database.
Definition: commonobject.class.php:9202
dol_sanitizeFileName
dol_sanitizeFileName($str, $newstr='_', $unaccent=1)
Clean a string to use it as a file name.
Definition: functions.lib.php:1226
CommonObject\copy_linked_contact
copy_linked_contact($objFrom, $source='internal')
Copy contact from one element to current.
Definition: commonobject.class.php:1217
MyObject\__construct
__construct(DoliDB $db)
Constructor.
Definition: myobject.class.php:247
MyObject\createFromClone
createFromClone(User $user, $fromid)
Clone an object into another one.
Definition: myobject.class.php:308
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:518
MyObject\LibStatut
LibStatut($status, $mode=0)
Return the status.
Definition: myobject.class.php:897
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:4844
dol_buildpath
dol_buildpath($path, $type=0, $returnemptyifnotfound=0)
Return path of url or filesystem.
Definition: functions.lib.php:1062
CommonObject\fetchLinesCommon
fetchLinesCommon($morewhere='')
Load object in memory from the database.
Definition: commonobject.class.php:9258
ref
$object ref
Definition: info.php:77
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)
Scan a directory and return a list of files/directories.
Definition: files.lib.php:60
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:44
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:1062
MyObject\fetchLines
fetchLines()
Load object lines in memory from the database.
Definition: myobject.class.php:422
MyObject\getLabelStatus
getLabelStatus($mode=0)
Return the label of the status.
Definition: myobject.class.php:873
MyObjectLine
Class MyObjectLine.
Definition: myobject.class.php:1127
MyObject\deleteLine
deleteLine(User $user, $idline, $notrigger=false)
Delete a line of object in database.
Definition: myobject.class.php:544
MyObject\getLinesArray
getLinesArray()
Create an array of lines.
Definition: myobject.class.php:979
MyObject\cancel
cancel($user, $notrigger=0)
Set cancel status.
Definition: myobject.class.php:711
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:3880
CommonObject\createCommon
createCommon(User $user, $notrigger=false)
Create object into database.
Definition: commonobject.class.php:9035
MyObject\initAsSpecimen
initAsSpecimen()
Initialise object with example values Id must be 0 if object instance is a specimen.
Definition: myobject.class.php:965
MyObject\getLibStatut
getLibStatut($mode=0)
Return the label of the status.
Definition: myobject.class.php:884
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:762
MyObject\fetch
fetch($id, $ref=null)
Load object in memory from the database.
Definition: myobject.class.php:408
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:442
MyObject\create
create(User $user, $notrigger=false)
Create object into database.
Definition: myobject.class.php:292
dol_syslog
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
Definition: functions.lib.php:1603
MyObject\doScheduledJob
doScheduledJob()
Action executed by scheduler CAN BE A CRON TASK.
Definition: myobject.class.php:1097
CommonObject\updateCommon
updateCommon(User $user, $notrigger=false)
Update object into database.
Definition: commonobject.class.php:9308
dol_strlen
dol_strlen($string, $stringencoding='UTF-8')
Make a strlen call.
Definition: functions.lib.php:3747
MyObject\info
info($id)
Load the info information in the object.
Definition: myobject.class.php:926
MyObject
Class for MyObject.
Definition: myobject.class.php:33
User
Class to manage Dolibarr users.
Definition: user.class.php:44
MyObjectLine\__construct
__construct(DoliDB $db)
Constructor.
Definition: myobject.class.php:1142
dolGetStatus
dolGetStatus($statusLabel='', $statusLabelShort='', $html='', $statusType='status0', $displayMode=0, $url='', $params=array())
Output the badge of a status.
Definition: functions.lib.php:10338
MyObject\setDraft
setDraft($user, $notrigger=0)
Set draft status.
Definition: myobject.class.php:687
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:4211
MyObject\getNextNumRef
getNextNumRef()
Returns the reference to the following non used object depending on the active numbering module.
Definition: myobject.class.php:1001
dol_now
dol_now($mode='auto')
Return date for now.
Definition: functions.lib.php:2845
$resql
if(isModEnabled('facture') &&!empty($user->rights->facture->lire)) if((isModEnabled('fournisseur') &&empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) && $user->rights->fournisseur->facture->lire)||(isModEnabled('supplier_invoice') && $user->rights->supplier_invoice->lire)) if(isModEnabled('don') &&!empty($user->rights->don->lire)) if(isModEnabled('tax') &&!empty($user->rights->tax->charges->lire)) if(isModEnabled('facture') &&isModEnabled('commande') && $user->rights->commande->lire &&empty($conf->global->WORKFLOW_DISABLE_CREATE_INVOICE_FROM_ORDER)) $resql
Social contributions to pay.
Definition: index.php:742
CommonObject\deleteLineCommon
deleteLineCommon(User $user, $idline, $notrigger=false)
Delete a line of object in database.
Definition: commonobject.class.php:9622
CommonObject\call_trigger
call_trigger($triggerName, $user)
Call trigger based on this instance.
Definition: commonobject.class.php:5791
CommonObject\getFieldList
getFieldList($alias='')
Function to concat keys of fields.
Definition: commonobject.class.php:8987