dolibarr  19.0.0-dev
timespent.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) 2023 Gauthier VERDOL <gauthier.verdol@atm-consulting.fr>
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 TimeSpent extends CommonObject
35 {
39  public $module = 'timespent';
40 
44  public $element = 'timespent';
45 
49  public $table_element = 'element_time';
50 
55  public $ismultientitymanaged = 0;
56 
60  public $isextrafieldmanaged = 0;
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', 'position'=>1, 'notnull'=>1, 'visible'=>0, 'noteditable'=>'1', 'index'=>1, 'css'=>'left', 'comment'=>"Id"),
118  'tms' => array('type'=>'timestamp', 'label'=>'DateModification', 'enabled'=>'1', 'position'=>17, 'notnull'=>0, 'visible'=>-2,),
119  'import_key' => array('type'=>'varchar(14)', 'label'=>'import_key', 'enabled'=>'1', 'position'=>15, 'notnull'=>0, 'visible'=>-1,),
120  'fk_element' => array('type'=>'integer', 'label'=>'fk_element', 'enabled'=>'1', 'position'=>2, 'notnull'=>1, 'visible'=>-1,),
121  'elementtype' => array('type'=>'varchar(32)', 'label'=>'elementtype', 'enabled'=>'1', 'position'=>3, 'notnull'=>1, 'visible'=>-1,),
122  'element_date' => array('type'=>'date', 'label'=>'element_date', 'enabled'=>'1', 'position'=>4, 'notnull'=>0, 'visible'=>-1,),
123  'element_datehour' => array('type'=>'datetime', 'label'=>'element_datehour', 'enabled'=>'1', 'position'=>5, 'notnull'=>0, 'visible'=>-1,),
124  'element_date_withhour' => array('type'=>'integer', 'label'=>'element_date_withhour', 'enabled'=>'1', 'position'=>6, 'notnull'=>0, 'visible'=>-1,),
125  'element_duration' => array('type'=>'double', 'label'=>'element_duration', 'enabled'=>'1', 'position'=>7, 'notnull'=>0, 'visible'=>-1,),
126  'fk_product' => array('type'=>'integer', 'label'=>'fk_product', 'enabled'=>'1', 'position'=>8, 'notnull'=>0, 'visible'=>-1,),
127  'fk_user' => array('type'=>'integer', 'label'=>'fk_user', 'enabled'=>'1', 'position'=>9, 'notnull'=>0, 'visible'=>-1,),
128  'thm' => array('type'=>'double(24,8)', 'label'=>'thm', 'enabled'=>'1', 'position'=>10, 'notnull'=>0, 'visible'=>-1,),
129  'invoice_id' => array('type'=>'integer', 'label'=>'invoice_id', 'enabled'=>'1', 'position'=>11, 'notnull'=>0, 'visible'=>-1, 'default'=>'NULL',),
130  'invoice_line_id' => array('type'=>'integer', 'label'=>'invoice_line_id', 'enabled'=>'1', 'position'=>12, 'notnull'=>0, 'visible'=>-1, 'default'=>'NULL',),
131  'intervention_id' => array('type'=>'integer', 'label'=>'intervention_id', 'enabled'=>'1', 'position'=>13, 'notnull'=>0, 'visible'=>-1, 'default'=>'NULL',),
132  'intervention_line_id' => array('type'=>'integer', 'label'=>'intervention_line_id', 'enabled'=>'1', 'position'=>14, 'notnull'=>0, 'visible'=>-1, 'default'=>'NULL',),
133  'datec' => array('type'=>'datetime', 'label'=>'datec', 'enabled'=>'1', 'position'=>16, 'notnull'=>0, 'visible'=>-1,),
134  'note' => array('type'=>'text', 'label'=>'note', 'enabled'=>'1', 'position'=>18, 'notnull'=>0, 'visible'=>-1,),
135  );
136  public $rowid;
137  public $tms;
138  public $import_key;
139  public $fk_element;
140  public $elementtype;
141  public $element_date;
142  public $element_datehour;
143  public $element_date_withhour;
144  public $element_duration;
145  public $fk_product;
146  public $fk_user;
147  public $thm;
148  public $invoice_id;
149  public $invoice_line_id;
150  public $intervention_id;
151  public $intervention_line_id;
152  public $datec;
153  public $note;
154  // END MODULEBUILDER PROPERTIES
155 
156 
157  // If this object has a subtable with lines
158 
159  // /**
160  // * @var string Name of subtable line
161  // */
162  // public $table_element_line = 'timespent_timespentline';
163 
164  // /**
165  // * @var string Field with ID of parent key if this object has a parent
166  // */
167  // public $fk_element = 'fk_timespent';
168 
169  // /**
170  // * @var string Name of subtable class that manage subtable lines
171  // */
172  // public $class_element_line = 'TimeSpentline';
173 
174  // /**
175  // * @var array List of child tables. To test if we can delete object.
176  // */
177  // protected $childtables = array();
178 
179  // /**
180  // * @var array List of child tables. To know object to delete on cascade.
181  // * If name matches '@ClassNAme:FilePathClass;ParentFkFieldName' it will
182  // * call method deleteByParentField(parentId, ParentFkFieldName) to fetch and delete child object
183  // */
184  // protected $childtablesoncascade = array('timespent_timespentdet');
185 
186  // /**
187  // * @var TimeSpentLine[] Array of subtable lines
188  // */
189  // public $lines = array();
190 
191 
192 
198  public function __construct(DoliDB $db)
199  {
200  global $conf, $langs;
201 
202  $this->db = $db;
203 
204  if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID) && isset($this->fields['rowid']) && !empty($this->fields['ref'])) {
205  $this->fields['rowid']['visible'] = 0;
206  }
207  if (!isModEnabled('multicompany') && isset($this->fields['entity'])) {
208  $this->fields['entity']['enabled'] = 0;
209  }
210 
211  // Example to show how to set values of fields definition dynamically
212  /*if ($user->rights->timespent->timespent->read) {
213  $this->fields['myfield']['visible'] = 1;
214  $this->fields['myfield']['noteditable'] = 0;
215  }*/
216 
217  // Unset fields that are disabled
218  foreach ($this->fields as $key => $val) {
219  if (isset($val['enabled']) && empty($val['enabled'])) {
220  unset($this->fields[$key]);
221  }
222  }
223 
224  // Translate some data of arrayofkeyval
225  if (is_object($langs)) {
226  foreach ($this->fields as $key => $val) {
227  if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
228  foreach ($val['arrayofkeyval'] as $key2 => $val2) {
229  $this->fields[$key]['arrayofkeyval'][$key2] = $langs->trans($val2);
230  }
231  }
232  }
233  }
234  }
235 
243  public function create(User $user, $notrigger = false)
244  {
245  $resultcreate = $this->createCommon($user, $notrigger);
246 
247  //$resultvalidate = $this->validate($user, $notrigger);
248 
249  return $resultcreate;
250  }
251 
259  public function createFromClone(User $user, $fromid)
260  {
261  global $langs, $extrafields;
262  $error = 0;
263 
264  dol_syslog(__METHOD__, LOG_DEBUG);
265 
266  $object = new self($this->db);
267 
268  $this->db->begin();
269 
270  // Load source object
271  $result = $object->fetchCommon($fromid);
272  if ($result > 0 && !empty($object->table_element_line)) {
273  $object->fetchLines();
274  }
275 
276  // get lines so they will be clone
277  //foreach($this->lines as $line)
278  // $line->fetch_optionals();
279 
280  // Reset some properties
281  unset($object->id);
282  unset($object->fk_user_creat);
283  unset($object->import_key);
284 
285  // Clear fields
286  if (property_exists($object, 'ref')) {
287  $object->ref = empty($this->fields['ref']['default']) ? "Copy_Of_".$object->ref : $this->fields['ref']['default'];
288  }
289  if (property_exists($object, 'label')) {
290  $object->label = empty($this->fields['label']['default']) ? $langs->trans("CopyOf")." ".$object->label : $this->fields['label']['default'];
291  }
292  if (property_exists($object, 'status')) {
293  $object->status = self::STATUS_DRAFT;
294  }
295  if (property_exists($object, 'date_creation')) {
296  $object->date_creation = dol_now();
297  }
298  if (property_exists($object, 'date_modification')) {
299  $object->date_modification = null;
300  }
301  // ...
302  // Clear extrafields that are unique
303  if (is_array($object->array_options) && count($object->array_options) > 0) {
304  $extrafields->fetch_name_optionals_label($this->table_element);
305  foreach ($object->array_options as $key => $option) {
306  $shortkey = preg_replace('/options_/', '', $key);
307  if (!empty($extrafields->attributes[$this->table_element]['unique'][$shortkey])) {
308  //var_dump($key);
309  //var_dump($clonedObj->array_options[$key]); exit;
310  unset($object->array_options[$key]);
311  }
312  }
313  }
314 
315  // Create clone
316  $object->context['createfromclone'] = 'createfromclone';
317  $result = $object->createCommon($user);
318  if ($result < 0) {
319  $error++;
320  $this->error = $object->error;
321  $this->errors = $object->errors;
322  }
323 
324  if (!$error) {
325  // copy internal contacts
326  if ($this->copy_linked_contact($object, 'internal') < 0) {
327  $error++;
328  }
329  }
330 
331  if (!$error) {
332  // copy external contacts if same company
333  if (!empty($object->socid) && property_exists($this, 'fk_soc') && $this->fk_soc == $object->socid) {
334  if ($this->copy_linked_contact($object, 'external') < 0) {
335  $error++;
336  }
337  }
338  }
339 
340  unset($object->context['createfromclone']);
341 
342  // End
343  if (!$error) {
344  $this->db->commit();
345  return $object;
346  } else {
347  $this->db->rollback();
348  return -1;
349  }
350  }
351 
359  public function fetch($id, $ref = null)
360  {
361  $result = $this->fetchCommon($id, $ref);
362  if ($result > 0 && !empty($this->table_element_line)) {
363  $this->fetchLines();
364  }
365  return $result;
366  }
367 
373  public function fetchLines()
374  {
375  $this->lines = array();
376 
377  $result = $this->fetchLinesCommon();
378  return $result;
379  }
380 
381 
393  public function fetchAll($sortorder = '', $sortfield = '', $limit = 0, $offset = 0, array $filter = array(), $filtermode = 'AND')
394  {
395  global $conf;
396 
397  dol_syslog(__METHOD__, LOG_DEBUG);
398 
399  $records = array();
400 
401  $sql = "SELECT ";
402  $sql .= $this->getFieldList('t');
403  $sql .= " FROM ".$this->db->prefix().$this->table_element." as t";
404  if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
405  $sql .= " WHERE t.entity IN (".getEntity($this->element).")";
406  } else {
407  $sql .= " WHERE 1 = 1";
408  }
409  // Manage filter
410  $sqlwhere = array();
411  if (count($filter) > 0) {
412  foreach ($filter as $key => $value) {
413  if ($key == 't.rowid') {
414  $sqlwhere[] = $key." = ".((int) $value);
415  } elseif (in_array($this->fields[$key]['type'], array('date', 'datetime', 'timestamp'))) {
416  $sqlwhere[] = $key." = '".$this->db->idate($value)."'";
417  } elseif ($key == 'customsql') {
418  $sqlwhere[] = $value;
419  } elseif (strpos($value, '%') === false) {
420  $sqlwhere[] = $key." IN (".$this->db->sanitize($this->db->escape($value)).")";
421  } else {
422  $sqlwhere[] = $key." LIKE '%".$this->db->escape($value)."%'";
423  }
424  }
425  }
426  if (count($sqlwhere) > 0) {
427  $sql .= " AND (".implode(" ".$filtermode." ", $sqlwhere).")";
428  }
429 
430  if (!empty($sortfield)) {
431  $sql .= $this->db->order($sortfield, $sortorder);
432  }
433  if (!empty($limit)) {
434  $sql .= $this->db->plimit($limit, $offset);
435  }
436 
437  $resql = $this->db->query($sql);
438  if ($resql) {
439  $num = $this->db->num_rows($resql);
440  $i = 0;
441  while ($i < ($limit ? min($limit, $num) : $num)) {
442  $obj = $this->db->fetch_object($resql);
443 
444  $record = new self($this->db);
445  $record->setVarsFromFetchObj($obj);
446 
447  $records[$record->id] = $record;
448 
449  $i++;
450  }
451  $this->db->free($resql);
452 
453  return $records;
454  } else {
455  $this->errors[] = 'Error '.$this->db->lasterror();
456  dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
457 
458  return -1;
459  }
460  }
461 
469  public function update(User $user, $notrigger = false)
470  {
471  return $this->updateCommon($user, $notrigger);
472  }
473 
481  public function delete(User $user, $notrigger = false)
482  {
483  return $this->deleteCommon($user, $notrigger);
484  //return $this->deleteCommon($user, $notrigger, 1);
485  }
486 
495  public function deleteLine(User $user, $idline, $notrigger = false)
496  {
497  if ($this->status < 0) {
498  $this->error = 'ErrorDeleteLineNotAllowedByObjectStatus';
499  return -2;
500  }
501 
502  return $this->deleteLineCommon($user, $idline, $notrigger);
503  }
504 
505 
513  public function validate($user, $notrigger = 0)
514  {
515  global $conf, $langs;
516 
517  require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
518 
519  $error = 0;
520 
521  // Protection
522  if ($this->status == self::STATUS_VALIDATED) {
523  dol_syslog(get_class($this)."::validate action abandonned: already validated", LOG_WARNING);
524  return 0;
525  }
526 
527  /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->timespent->timespent->write))
528  || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->timespent->timespent->timespent_advance->validate))))
529  {
530  $this->error='NotEnoughPermissions';
531  dol_syslog(get_class($this)."::valid ".$this->error, LOG_ERR);
532  return -1;
533  }*/
534 
535  $now = dol_now();
536 
537  $this->db->begin();
538 
539  // Define new ref
540  if (!$error && (preg_match('/^[\‍(]?PROV/i', $this->ref) || empty($this->ref))) { // empty should not happened, but when it occurs, the test save life
541  $num = $this->getNextNumRef();
542  } else {
543  $num = $this->ref;
544  }
545  $this->newref = $num;
546 
547  if (!empty($num)) {
548  // Validate
549  $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
550  $sql .= " SET ref = '".$this->db->escape($num)."',";
551  $sql .= " status = ".self::STATUS_VALIDATED;
552  if (!empty($this->fields['date_validation'])) {
553  $sql .= ", date_validation = '".$this->db->idate($now)."'";
554  }
555  if (!empty($this->fields['fk_user_valid'])) {
556  $sql .= ", fk_user_valid = ".((int) $user->id);
557  }
558  $sql .= " WHERE rowid = ".((int) $this->id);
559 
560  dol_syslog(get_class($this)."::validate()", LOG_DEBUG);
561  $resql = $this->db->query($sql);
562  if (!$resql) {
563  dol_print_error($this->db);
564  $this->error = $this->db->lasterror();
565  $error++;
566  }
567 
568  if (!$error && !$notrigger) {
569  // Call trigger
570  $result = $this->call_trigger('timespent_VALIDATE', $user);
571  if ($result < 0) {
572  $error++;
573  }
574  // End call triggers
575  }
576  }
577 
578  if (!$error) {
579  $this->oldref = $this->ref;
580 
581  // Rename directory if dir was a temporary ref
582  if (preg_match('/^[\‍(]?PROV/i', $this->ref)) {
583  // Now we rename also files into index
584  $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filename = CONCAT('".$this->db->escape($this->newref)."', SUBSTR(filename, ".(strlen($this->ref) + 1).")), filepath = 'timespent/".$this->db->escape($this->newref)."'";
585  $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'timespent/".$this->db->escape($this->ref)."' and entity = ".$conf->entity;
586  $resql = $this->db->query($sql);
587  if (!$resql) {
588  $error++; $this->error = $this->db->lasterror();
589  }
590 
591  // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments
592  $oldref = dol_sanitizeFileName($this->ref);
593  $newref = dol_sanitizeFileName($num);
594  $dirsource = $conf->timespent->dir_output.'/timespent/'.$oldref;
595  $dirdest = $conf->timespent->dir_output.'/timespent/'.$newref;
596  if (!$error && file_exists($dirsource)) {
597  dol_syslog(get_class($this)."::validate() rename dir ".$dirsource." into ".$dirdest);
598 
599  if (@rename($dirsource, $dirdest)) {
600  dol_syslog("Rename ok");
601  // Rename docs starting with $oldref with $newref
602  $listoffiles = dol_dir_list($conf->timespent->dir_output.'/timespent/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/'));
603  foreach ($listoffiles as $fileentry) {
604  $dirsource = $fileentry['name'];
605  $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource);
606  $dirsource = $fileentry['path'].'/'.$dirsource;
607  $dirdest = $fileentry['path'].'/'.$dirdest;
608  @rename($dirsource, $dirdest);
609  }
610  }
611  }
612  }
613  }
614 
615  // Set new ref and current status
616  if (!$error) {
617  $this->ref = $num;
618  $this->status = self::STATUS_VALIDATED;
619  }
620 
621  if (!$error) {
622  $this->db->commit();
623  return 1;
624  } else {
625  $this->db->rollback();
626  return -1;
627  }
628  }
629 
630 
638  public function setDraft($user, $notrigger = 0)
639  {
640  // Protection
641  if ($this->status <= self::STATUS_DRAFT) {
642  return 0;
643  }
644 
645  /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->timespent->write))
646  || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->timespent->timespent_advance->validate))))
647  {
648  $this->error='Permission denied';
649  return -1;
650  }*/
651 
652  return $this->setStatusCommon($user, self::STATUS_DRAFT, $notrigger, 'timespent_UNVALIDATE');
653  }
654 
662  public function cancel($user, $notrigger = 0)
663  {
664  // Protection
665  if ($this->status != self::STATUS_VALIDATED) {
666  return 0;
667  }
668 
669  /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->timespent->write))
670  || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->timespent->timespent_advance->validate))))
671  {
672  $this->error='Permission denied';
673  return -1;
674  }*/
675 
676  return $this->setStatusCommon($user, self::STATUS_CANCELED, $notrigger, 'timespent_CANCEL');
677  }
678 
686  public function reopen($user, $notrigger = 0)
687  {
688  // Protection
689  if ($this->status == self::STATUS_VALIDATED) {
690  return 0;
691  }
692 
693  /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->timespent->write))
694  || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->timespent->timespent_advance->validate))))
695  {
696  $this->error='Permission denied';
697  return -1;
698  }*/
699 
700  return $this->setStatusCommon($user, self::STATUS_VALIDATED, $notrigger, 'timespent_REOPEN');
701  }
702 
709  public function getTooltipContentArray($params)
710  {
711  global $conf, $langs, $user;
712 
713  $datas = [];
714 
715  if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
716  return ['optimize' => $langs->trans("ShowTimeSpent")];
717  }
718  $datas['picto'] = img_picto('', $this->picto).' <u>'.$langs->trans("TimeSpent").'</u>';
719  if (isset($this->status)) {
720  $datas['picto'] .= ' '.$this->getLibStatut(5);
721  }
722  $datas['ref'] .= '<br><b>'.$langs->trans('Ref').':</b> '.$this->ref;
723 
724  return $datas;
725  }
726 
737  public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $morecss = '', $save_lastsearch_value = -1)
738  {
739  global $conf, $langs, $hookmanager;
740 
741  if (!empty($conf->dol_no_mouse_hover)) {
742  $notooltip = 1; // Force disable tooltips
743  }
744 
745  $result = '';
746  $params = [
747  'id' => $this->id,
748  'objecttype' => $this->element,
749  'option' => $option,
750  ];
751  $classfortooltip = 'classfortooltip';
752  $dataparams = '';
753  if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
754  $classfortooltip = 'classforajaxtooltip';
755  $dataparams = ' data-params="'.dol_escape_htmltag(json_encode($params)).'"';
756  $label = '';
757  } else {
758  $label = implode($this->getTooltipContentArray($params));
759  }
760 
761  $url = dol_buildpath('/timespent/timespent_card.php', 1).'?id='.$this->id;
762 
763  if ($option != 'nolink') {
764  // Add param to save lastsearch_values or not
765  $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
766  if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
767  $add_save_lastsearch_values = 1;
768  }
769  if ($url && $add_save_lastsearch_values) {
770  $url .= '&save_lastsearch_values=1';
771  }
772  }
773 
774  $linkclose = '';
775  if (empty($notooltip)) {
776  if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
777  $label = $langs->trans("ShowTimeSpent");
778  $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
779  }
780  $linkclose .= ($label ? ' title="'.dol_escape_htmltag($label, 1).'"' : ' title="tocomplete"');
781  $linkclose .= $dataparams.' class="'.$classfortooltip.($morecss ? ' '.$morecss : '').'"';
782  } else {
783  $linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
784  }
785 
786  if ($option == 'nolink' || empty($url)) {
787  $linkstart = '<span';
788  } else {
789  $linkstart = '<a href="'.$url.'"';
790  }
791  $linkstart .= $linkclose.'>';
792  if ($option == 'nolink' || empty($url)) {
793  $linkend = '</span>';
794  } else {
795  $linkend = '</a>';
796  }
797 
798  $result .= $linkstart;
799 
800  if (empty($this->showphoto_on_popup)) {
801  if ($withpicto) {
802  $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : $dataparams.' class="'.(($withpicto != 2) ? 'paddingright ' : '').$classfortooltip.'"'), 0, 0, $notooltip ? 0 : 1);
803  }
804  } else {
805  if ($withpicto) {
806  require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
807 
808  list($class, $module) = explode('@', $this->picto);
809  $upload_dir = $conf->$module->multidir_output[$conf->entity]."/$class/".dol_sanitizeFileName($this->ref);
810  $filearray = dol_dir_list($upload_dir, "files");
811  $filename = $filearray[0]['name'];
812  if (!empty($filename)) {
813  $pospoint = strpos($filearray[0]['name'], '.');
814 
815  $pathtophoto = $class.'/'.$this->ref.'/thumbs/'.substr($filename, 0, $pospoint).'_mini'.substr($filename, $pospoint);
816  if (!getDolGlobalString(strtoupper($module.'_'.$class).'_FORMATLISTPHOTOSASUSERS')) {
817  $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>';
818  } else {
819  $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>';
820  }
821 
822  $result .= '</div>';
823  } else {
824  $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);
825  }
826  }
827  }
828 
829  if ($withpicto != 2) {
830  $result .= $this->ref;
831  }
832 
833  $result .= $linkend;
834  //if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : '');
835 
836  global $action, $hookmanager;
837  $hookmanager->initHooks(array($this->element.'dao'));
838  $parameters = array('id'=>$this->id, 'getnomurl' => &$result);
839  $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
840  if ($reshook > 0) {
841  $result = $hookmanager->resPrint;
842  } else {
843  $result .= $hookmanager->resPrint;
844  }
845 
846  return $result;
847  }
848 
856  public function getKanbanView($option = '', $arraydata = null)
857  {
858  global $conf, $langs;
859 
860  //$selected = (empty($arraydata['selected']) ? 0 : $arraydata['selected']);
861 
862  $return = '<div class="box-flex-item box-flex-grow-zero">';
863  $return .= '<div class="info-box info-box-sm">';
864  $return .= '<span class="info-box-icon bg-infobox-action">';
865  $return .= img_picto('', $this->picto);
866  $return .= '</span>';
867  $return .= '<div class="info-box-content">';
868  $return .= '<span class="info-box-ref inline-block tdoverflowmax150 valignmiddle">'.(method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref).'</span>';
869  //$return .= '<input id="cb'.$this->id.'" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="'.$this->id.'"'.($selected ? ' checked="checked"' : '').'>';
870 
871  if (property_exists($this, 'label')) {
872  $return .= ' <div class="inline-block opacitymedium valignmiddle tdoverflowmax100">'.$this->label.'</div>';
873  }
874  if (property_exists($this, 'amount')) {
875  $return .= '<br>';
876  $return .= '<span class="info-box-label amount">'.price($this->amount, 0, $langs, 1, -1, -1, $conf->currency).'</span>';
877  }
878  if (method_exists($this, 'getLibStatut')) {
879  $return .= '<br><div class="info-box-status margintoponly">'.$this->getLibStatut(5).'</div>';
880  }
881  $return .= '</div>';
882  $return .= '</div>';
883  $return .= '</div>';
884 
885  return $return;
886  }
887 
894  public function getLabelStatus($mode = 0)
895  {
896  return $this->LibStatut($this->status, $mode);
897  }
898 
905  public function getLibStatut($mode = 0)
906  {
907  return $this->LibStatut($this->status, $mode);
908  }
909 
910  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
918  public function LibStatut($status, $mode = 0)
919  {
920  // phpcs:enable
921  if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
922  global $langs;
923  //$langs->load("timespent@timespent");
924  $this->labelStatus[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('Draft');
925  $this->labelStatus[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('Enabled');
926  $this->labelStatus[self::STATUS_CANCELED] = $langs->transnoentitiesnoconv('Disabled');
927  $this->labelStatusShort[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('Draft');
928  $this->labelStatusShort[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('Enabled');
929  $this->labelStatusShort[self::STATUS_CANCELED] = $langs->transnoentitiesnoconv('Disabled');
930  }
931 
932  $statusType = 'status'.$status;
933  //if ($status == self::STATUS_VALIDATED) $statusType = 'status1';
934  if ($status == self::STATUS_CANCELED) {
935  $statusType = 'status6';
936  }
937 
938  return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
939  }
940 
947  public function info($id)
948  {
949  $sql = "SELECT rowid,";
950  $sql .= " date_creation as datec, tms as datem,";
951  $sql .= " fk_user_creat, fk_user_modif";
952  $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element." as t";
953  $sql .= " WHERE t.rowid = ".((int) $id);
954 
955  $result = $this->db->query($sql);
956  if ($result) {
957  if ($this->db->num_rows($result)) {
958  $obj = $this->db->fetch_object($result);
959 
960  $this->id = $obj->rowid;
961 
962  $this->user_creation_id = $obj->fk_user_creat;
963  $this->user_modification_id = $obj->fk_user_modif;
964  if (!empty($obj->fk_user_valid)) {
965  $this->user_validation_id = $obj->fk_user_valid;
966  }
967  $this->date_creation = $this->db->jdate($obj->datec);
968  $this->date_modification = empty($obj->datem) ? '' : $this->db->jdate($obj->datem);
969  if (!empty($obj->datev)) {
970  $this->date_validation = empty($obj->datev) ? '' : $this->db->jdate($obj->datev);
971  }
972  }
973 
974  $this->db->free($result);
975  } else {
976  dol_print_error($this->db);
977  }
978  }
979 
986  public function initAsSpecimen()
987  {
988  // Set here init that are not commonf fields
989  // $this->property1 = ...
990  // $this->property2 = ...
991 
992  $this->initAsSpecimenCommon();
993  }
994 
1000  public function getLinesArray()
1001  {
1002  $this->lines = array();
1003 
1004  $objectline = new TimeSpentLine($this->db);
1005  $result = $objectline->fetchAll('ASC', 'position', 0, 0, array('customsql'=>'fk_timespent = '.((int) $this->id)));
1006 
1007  if (is_numeric($result)) {
1008  $this->error = $objectline->error;
1009  $this->errors = $objectline->errors;
1010  return $result;
1011  } else {
1012  $this->lines = $result;
1013  return $this->lines;
1014  }
1015  }
1016 
1022  public function getNextNumRef()
1023  {
1024  global $langs, $conf;
1025  $langs->load("timespent@timespent");
1026 
1027  if (empty($conf->global->TIMESPENT_timespent_ADDON)) {
1028  $conf->global->TIMESPENT_timespent_ADDON = 'mod_timespent_standard';
1029  }
1030 
1031  if (!empty($conf->global->TIMESPENT_timespent_ADDON)) {
1032  $mybool = false;
1033 
1034  $file = $conf->global->TIMESPENT_timespent_ADDON.".php";
1035  $classname = $conf->global->TIMESPENT_timespent_ADDON;
1036 
1037  // Include file with class
1038  $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
1039  foreach ($dirmodels as $reldir) {
1040  $dir = dol_buildpath($reldir."core/modules/timespent/");
1041 
1042  // Load file with numbering class (if found)
1043  $mybool |= @include_once $dir.$file;
1044  }
1045 
1046  if ($mybool === false) {
1047  dol_print_error('', "Failed to include file ".$file);
1048  return '';
1049  }
1050 
1051  if (class_exists($classname)) {
1052  $obj = new $classname();
1053  $numref = $obj->getNextValue($this);
1054 
1055  if ($numref != '' && $numref != '-1') {
1056  return $numref;
1057  } else {
1058  $this->error = $obj->error;
1059  //dol_print_error($this->db,get_class($this)."::getNextNumRef ".$obj->error);
1060  return "";
1061  }
1062  } else {
1063  print $langs->trans("Error")." ".$langs->trans("ClassNotFound").' '.$classname;
1064  return "";
1065  }
1066  } else {
1067  print $langs->trans("ErrorNumberingModuleNotSetup", $this->element);
1068  return "";
1069  }
1070  }
1071 
1083  public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
1084  {
1085  global $conf, $langs;
1086 
1087  $result = 0;
1088  $includedocgeneration = 0;
1089 
1090  $langs->load("timespent@timespent");
1091 
1092  if (!dol_strlen($modele)) {
1093  $modele = 'standard_timespent';
1094 
1095  if (!empty($this->model_pdf)) {
1096  $modele = $this->model_pdf;
1097  } elseif (!empty($conf->global->timespent_ADDON_PDF)) {
1098  $modele = $conf->global->timespent_ADDON_PDF;
1099  }
1100  }
1101 
1102  $modelpath = "core/modules/timespent/doc/";
1103 
1104  if ($includedocgeneration && !empty($modele)) {
1105  $result = $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
1106  }
1107 
1108  return $result;
1109  }
1110 
1118  public function doScheduledJob()
1119  {
1120  //global $conf, $langs;
1121 
1122  //$conf->global->SYSLOG_FILE = 'DOL_DATA_ROOT/dolibarr_mydedicatedlofile.log';
1123 
1124  $error = 0;
1125  $this->output = '';
1126  $this->error = '';
1127 
1128  dol_syslog(__METHOD__, LOG_DEBUG);
1129 
1130  $now = dol_now();
1131 
1132  $this->db->begin();
1133 
1134  // ...
1135 
1136  $this->db->commit();
1137 
1138  return $error;
1139  }
1140 }
$object ref
Definition: info.php:78
Parent class of all other business classes (invoices, contracts, proposals, orders,...
commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams=null)
Common function for all objects extending CommonObject for generating documents.
deleteLineCommon(User $user, $idline, $notrigger=false)
Delete a line of object in database.
getFieldList($alias='')
Function to concat keys of fields.
fetchCommon($id, $ref=null, $morewhere='')
Load object in memory from the database.
createCommon(User $user, $notrigger=false)
Create object into database.
deleteCommon(User $user, $notrigger=false, $forcechilddeletion=0)
Delete object in database.
setStatusCommon($user, $status, $notrigger=0, $triggercode='')
Set to a status.
initAsSpecimenCommon()
Initialise object with example values Id must be 0 if object instance is a specimen.
copy_linked_contact($objFrom, $source='internal')
Copy contact from one element to current.
updateCommon(User $user, $notrigger=false)
Update object into database.
fetchLinesCommon($morewhere='')
Load object in memory from the database.
call_trigger($triggerName, $user)
Call trigger based on this instance.
Class to manage Dolibarr database access.
Class for TimeSpent.
validate($user, $notrigger=0)
Validate object.
fetchLines()
Load object lines in memory from the database.
getNomUrl($withpicto=0, $option='', $notooltip=0, $morecss='', $save_lastsearch_value=-1)
Return a link to the object card (with optionaly the picto)
fetch($id, $ref=null)
Load object in memory from the database.
setDraft($user, $notrigger=0)
Set draft status.
getTooltipContentArray($params)
getTooltipContentArray
cancel($user, $notrigger=0)
Set cancel status.
initAsSpecimen()
Initialise object with example values Id must be 0 if object instance is a specimen.
deleteLine(User $user, $idline, $notrigger=false)
Delete a line of object in database.
doScheduledJob()
Action executed by scheduler CAN BE A CRON TASK.
fetchAll($sortorder='', $sortfield='', $limit=0, $offset=0, array $filter=array(), $filtermode='AND')
Load list of objects in memory from the database.
getLabelStatus($mode=0)
Return the label of the status.
__construct(DoliDB $db)
Constructor.
getLibStatut($mode=0)
Return the label of the status.
generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0, $moreparams=null)
Create a document onto disk according to template module.
reopen($user, $notrigger=0)
Set back to validated status.
createFromClone(User $user, $fromid)
Clone an object into another one.
info($id)
Load the info information in the object.
LibStatut($status, $mode=0)
Return the status.
update(User $user, $notrigger=false)
Update object into database.
getNextNumRef()
Returns the reference to the following non used object depending on the active numbering module.
create(User $user, $notrigger=false)
Create object into database.
getKanbanView($option='', $arraydata=null)
Return a thumb for kanban views.
getLinesArray()
Create an array of lines.
Class to manage Dolibarr users.
Definition: user.class.php:48
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_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
dol_print_error($db='', $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
img_object($titlealt, $picto, $moreatt='', $pictoisfullpath=false, $srconly=0, $notitle=0)
Show a picto called object_picto (generic function)
dol_strlen($string, $stringencoding='UTF-8')
Make a strlen call.
dol_now($mode='auto')
Return date for now.
getDolGlobalInt($key, $default=0)
Return dolibarr global constant int value.
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=false, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2)
Show picto whatever it's its name (generic function)
dolGetStatus($statusLabel='', $statusLabelShort='', $html='', $statusType='status0', $displayMode=0, $url='', $params=array())
Output the badge of a status.
dol_buildpath($path, $type=0, $returnemptyifnotfound=0)
Return path of url or filesystem.
dol_sanitizeFileName($str, $newstr='_', $unaccent=1)
Clean a string to use it as a file name.
getDolGlobalString($key, $default='')
Return dolibarr global constant string value.
isModEnabled($module)
Is Dolibarr module enabled.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.