dolibarr  16.0.1
project.class.php
Go to the documentation of this file.
1 <?php
2 /* Copyright (C) 2002-2005 Rodolphe Quiedeville <rodolphe@quiedeville.org>
3  * Copyright (C) 2005-2020 Laurent Destailleur <eldy@users.sourceforge.net>
4  * Copyright (C) 2005-2010 Regis Houssin <regis.houssin@inodbox.com>
5  * Copyright (C) 2013 Florian Henry <florian.henry@open-concept.pro>
6  * Copyright (C) 2014-2017 Marcos GarcĂ­a <marcosgdf@gmail.com>
7  * Copyright (C) 2017 Ferran Marcet <fmarcet@2byte.es>
8  * Copyright (C) 2019 Juanjo Menent <jmenent@2byte.es>
9  * Copyright (C) 2022 Charlene Benke <charlene@patas-monkey.com>
10  *
11  * This program is free software; you can redistribute it and/or modify
12  * it under the terms of the GNU General Public License as published by
13  * the Free Software Foundation; either version 3 of the License, or
14  * (at your option) any later version.
15  *
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19  * GNU General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public License
22  * along with this program. If not, see <https://www.gnu.org/licenses/>.
23  */
24 
30 require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
31 
35 class Project extends CommonObject
36 {
37 
41  public $element = 'project';
42 
46  public $table_element = 'projet';
47 
51  public $table_element_line = 'projet_task';
52 
56  public $table_element_date;
57 
61  public $fk_element = 'fk_projet';
62 
67  public $ismultientitymanaged = 1;
68 
72  public $picto = 'project';
73 
77  protected $table_ref_field = 'ref';
78 
82  public $description;
83 
87  public $title;
88 
94  public $dateo;
95 
99  public $date_start;
100 
106  public $datee;
107 
111  public $date_end;
112 
116  public $date_close;
117 
118  public $socid; // To store id of thirdparty
119  public $thirdparty_name; // To store name of thirdparty (defined only in some cases)
120 
122 
126  public $fk_user_close;
127 
131  public $user_close_id;
132  public $public;
133 
137  public $budget_amount;
138 
142  public $usage_opportunity;
143 
147  public $usage_task;
148 
152  public $usage_bill_time; // Is the time spent on project must be invoiced or not
153 
157  public $usage_organize_event;
158 
162  public $accept_conference_suggestions;
163 
167  public $accept_booth_suggestions;
168 
172  public $price_registration;
173 
177  public $price_booth;
178 
182  public $max_attendees;
183 
184  public $statuts_short;
185  public $statuts_long;
186 
187  public $statut; // 0=draft, 1=opened, 2=closed
188 
189  public $opp_status; // opportunity status, into table llx_c_lead_status
190  public $fk_opp_status; // opportunity status, into table llx_c_lead_status
191  public $opp_percent; // opportunity probability
192 
193  public $email_msgid;
194 
195  public $oldcopy;
196 
197  public $weekWorkLoad; // Used to store workload details of a projet
198  public $weekWorkLoadPerTask; // Used to store workload details of tasks of a projet
199 
205  public $datec;
206 
210  public $date_c;
211 
217  public $datem;
218 
222  public $date_m;
223 
227  public $lines;
228 
253  // BEGIN MODULEBUILDER PROPERTIES
257  public $fields = array(
258  'rowid' =>array('type'=>'integer', 'label'=>'ID', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>10),
259  'ref' =>array('type'=>'varchar(50)', 'label'=>'Ref', 'enabled'=>1, 'visible'=>1, 'showoncombobox'=>1, 'position'=>15, 'searchall'=>1),
260  'title' =>array('type'=>'varchar(255)', 'label'=>'ProjectLabel', 'enabled'=>1, 'visible'=>1, 'notnull'=>1, 'position'=>17, 'showoncombobox'=>2, 'searchall'=>1),
261  'entity' =>array('type'=>'integer', 'label'=>'Entity', 'default'=>1, 'enabled'=>1, 'visible'=>3, 'notnull'=>1, 'position'=>19),
262  'fk_soc' =>array('type'=>'integer', 'label'=>'Thirdparty', 'enabled'=>1, 'visible'=>0, 'position'=>20),
263  'dateo' =>array('type'=>'date', 'label'=>'DateStart', 'enabled'=>1, 'visible'=>1, 'position'=>30),
264  'datee' =>array('type'=>'date', 'label'=>'DateEnd', 'enabled'=>1, 'visible'=>1, 'position'=>35),
265  'description' =>array('type'=>'text', 'label'=>'Description', 'enabled'=>1, 'visible'=>3, 'position'=>55, 'searchall'=>1),
266  'public' =>array('type'=>'integer', 'label'=>'Visibility', 'enabled'=>1, 'visible'=>1, 'position'=>65),
267  'fk_opp_status' =>array('type'=>'integer', 'label'=>'OpportunityStatusShort', 'enabled'=>'!empty($conf->global->PROJECT_USE_OPPORTUNITIES)', 'visible'=>1, 'position'=>75),
268  'opp_percent' =>array('type'=>'double(5,2)', 'label'=>'OpportunityProbabilityShort', 'enabled'=>'!empty($conf->global->PROJECT_USE_OPPORTUNITIES)', 'visible'=>1, 'position'=>80),
269  'note_private' =>array('type'=>'text', 'label'=>'NotePrivate', 'enabled'=>1, 'visible'=>0, 'position'=>85, 'searchall'=>1),
270  'note_public' =>array('type'=>'text', 'label'=>'NotePublic', 'enabled'=>1, 'visible'=>0, 'position'=>90, 'searchall'=>1),
271  'model_pdf' =>array('type'=>'varchar(255)', 'label'=>'ModelPdf', 'enabled'=>1, 'visible'=>0, 'position'=>95),
272  'date_close' =>array('type'=>'datetime', 'label'=>'DateClosing', 'enabled'=>1, 'visible'=>0, 'position'=>105),
273  'fk_user_close' =>array('type'=>'integer', 'label'=>'UserClosing', 'enabled'=>1, 'visible'=>0, 'position'=>110),
274  'opp_amount' =>array('type'=>'double(24,8)', 'label'=>'OpportunityAmountShort', 'enabled'=>1, 'visible'=>'!empty($conf->global->PROJECT_USE_OPPORTUNITIES)', 'position'=>115),
275  'budget_amount' =>array('type'=>'double(24,8)', 'label'=>'Budget', 'enabled'=>1, 'visible'=>1, 'position'=>119),
276  'usage_bill_time' =>array('type'=>'integer', 'label'=>'UsageBillTimeShort', 'enabled'=>1, 'visible'=>-1, 'position'=>130),
277  'usage_opportunity' =>array('type'=>'integer', 'label'=>'UsageOpportunity', 'enabled'=>1, 'visible'=>-1, 'position'=>135),
278  'usage_task' =>array('type'=>'integer', 'label'=>'UsageTasks', 'enabled'=>1, 'visible'=>-1, 'position'=>140),
279  'usage_organize_event' =>array('type'=>'integer', 'label'=>'UsageOrganizeEvent', 'enabled'=>1, 'visible'=>-1, 'position'=>145),
280  'accept_conference_suggestions' =>array('type'=>'integer', 'label'=>'AllowUnknownPeopleSuggestConf', 'enabled'=>1, 'visible'=>-1, 'position'=>146),
281  'accept_booth_suggestions' =>array('type'=>'integer', 'label'=>'AllowUnknownPeopleSuggestBooth', 'enabled'=>1, 'visible'=>-1, 'position'=>147),
282  'price_registration' =>array('type'=>'double(24,8)', 'label'=>'PriceOfRegistration', 'enabled'=>1, 'visible'=>-1, 'position'=>148),
283  'price_booth' =>array('type'=>'double(24,8)', 'label'=>'PriceOfBooth', 'enabled'=>1, 'visible'=>-1, 'position'=>149),
284  'max_attendees' =>array('type'=>'integer', 'label'=>'MaxNbOfAttendees', 'enabled'=>1, 'visible'=>-1, 'position'=>150),
285  'datec' =>array('type'=>'datetime', 'label'=>'DateCreationShort', 'enabled'=>1, 'visible'=>-2, 'position'=>200),
286  'tms' =>array('type'=>'timestamp', 'label'=>'DateModificationShort', 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>205),
287  'fk_user_creat' =>array('type'=>'integer', 'label'=>'UserCreation', 'enabled'=>1, 'visible'=>0, 'notnull'=>1, 'position'=>210),
288  'fk_user_modif' =>array('type'=>'integer', 'label'=>'UserModification', 'enabled'=>1, 'visible'=>0, 'position'=>215),
289  'import_key' =>array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>1, 'visible'=>0, 'position'=>220),
290  'email_msgid'=>array('type'=>'varchar(255)', 'label'=>'EmailMsgID', 'enabled'=>1, 'visible'=>-1, 'position'=>250, 'help'=>'EmailMsgIDWhenSourceisEmail'),
291  'fk_statut' =>array('type'=>'smallint(6)', 'label'=>'Status', 'enabled'=>1, 'visible'=>1, 'notnull'=>1, 'position'=>500)
292  );
293  // END MODULEBUILDER PROPERTIES
294 
298  const STATUS_DRAFT = 0;
299 
303  const STATUS_VALIDATED = 1;
304 
308  const STATUS_CLOSED = 2;
309 
315  public function __construct($db)
316  {
317  global $conf;
318 
319  $this->db = $db;
320 
321  $this->statuts_short = array(0 => 'Draft', 1 => 'Opened', 2 => 'Closed');
322  $this->statuts_long = array(0 => 'Draft', 1 => 'Opened', 2 => 'Closed');
323 
324  global $conf;
325 
326  if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID)) {
327  $this->fields['rowid']['visible'] = 0;
328  }
329 
330  if (empty($conf->global->PROJECT_USE_OPPORTUNITIES)) {
331  $this->fields['fk_opp_status']['enabled'] = 0;
332  $this->fields['opp_percent']['enabled'] = 0;
333  $this->fields['opp_amount']['enabled'] = 0;
334  $this->fields['usage_opportunity']['enabled'] = 0;
335  }
336 
337  if (!empty($conf->global->PROJECT_HIDE_TASKS)) {
338  $this->fields['usage_bill_time']['visible'] = 0;
339  $this->fields['usage_task']['visible'] = 0;
340  }
341 
342  if (empty($conf->eventorganization->enabled)) {
343  $this->fields['usage_organize_event']['visible'] = 0;
344  $this->fields['accept_conference_suggestions']['enabled'] = 0;
345  $this->fields['accept_booth_suggestions']['enabled'] = 0;
346  $this->fields['price_registration']['enabled'] = 0;
347  $this->fields['price_booth']['enabled'] = 0;
348  $this->fields['max_attendees']['enabled'] = 0;
349  }
350  }
351 
359  public function create($user, $notrigger = 0)
360  {
361  global $conf, $langs;
362 
363  $error = 0;
364  $ret = 0;
365 
366  $now = dol_now();
367 
368  // Clean parameters
369  $this->note_private = dol_substr($this->note_private, 0, 65535);
370  $this->note_public = dol_substr($this->note_public, 0, 65535);
371 
372  // Check parameters
373  if (!trim($this->ref)) {
374  $this->error = 'ErrorFieldsRequired';
375  dol_syslog(get_class($this)."::create error -1 ref null", LOG_ERR);
376  return -1;
377  }
378  if (!empty($conf->global->PROJECT_THIRDPARTY_REQUIRED) && !($this->socid > 0)) {
379  $this->error = 'ErrorFieldsRequired';
380  dol_syslog(get_class($this)."::create error -1 thirdparty not defined and option PROJECT_THIRDPARTY_REQUIRED is set", LOG_ERR);
381  return -1;
382  }
383 
384  // Create project
385  $this->db->begin();
386 
387  $sql = "INSERT INTO ".MAIN_DB_PREFIX."projet (";
388  $sql .= "ref";
389  $sql .= ", title";
390  $sql .= ", description";
391  $sql .= ", fk_soc";
392  $sql .= ", fk_user_creat";
393  $sql .= ", fk_statut";
394  $sql .= ", fk_opp_status";
395  $sql .= ", opp_percent";
396  $sql .= ", public";
397  $sql .= ", datec";
398  $sql .= ", dateo";
399  $sql .= ", datee";
400  $sql .= ", opp_amount";
401  $sql .= ", budget_amount";
402  $sql .= ", usage_opportunity";
403  $sql .= ", usage_task";
404  $sql .= ", usage_bill_time";
405  $sql .= ", usage_organize_event";
406  $sql .= ", accept_conference_suggestions";
407  $sql .= ", accept_booth_suggestions";
408  $sql .= ", price_registration";
409  $sql .= ", price_booth";
410  $sql .= ", max_attendees";
411  $sql .= ", email_msgid";
412  $sql .= ", note_private";
413  $sql .= ", note_public";
414  $sql .= ", entity";
415  $sql .= ") VALUES (";
416  $sql .= "'".$this->db->escape($this->ref)."'";
417  $sql .= ", '".$this->db->escape($this->title)."'";
418  $sql .= ", '".$this->db->escape($this->description)."'";
419  $sql .= ", ".($this->socid > 0 ? $this->socid : "null");
420  $sql .= ", ".((int) $user->id);
421  $sql .= ", ".(is_numeric($this->statut) ? ((int) $this->statut) : '0');
422  $sql .= ", ".((is_numeric($this->opp_status) && $this->opp_status > 0) ? ((int) $this->opp_status) : 'NULL');
423  $sql .= ", ".(is_numeric($this->opp_percent) ? ((int) $this->opp_percent) : 'NULL');
424  $sql .= ", ".($this->public ? 1 : 0);
425  $sql .= ", '".$this->db->idate($now)."'";
426  $sql .= ", ".($this->date_start != '' ? "'".$this->db->idate($this->date_start)."'" : 'null');
427  $sql .= ", ".($this->date_end != '' ? "'".$this->db->idate($this->date_end)."'" : 'null');
428  $sql .= ", ".(strcmp($this->opp_amount, '') ? price2num($this->opp_amount) : 'null');
429  $sql .= ", ".(strcmp($this->budget_amount, '') ? price2num($this->budget_amount) : 'null');
430  $sql .= ", ".($this->usage_opportunity ? 1 : 0);
431  $sql .= ", ".($this->usage_task ? 1 : 0);
432  $sql .= ", ".($this->usage_bill_time ? 1 : 0);
433  $sql .= ", ".($this->usage_organize_event ? 1 : 0);
434  $sql .= ", ".($this->accept_conference_suggestions ? 1 : 0);
435  $sql .= ", ".($this->accept_booth_suggestions ? 1 : 0);
436  $sql .= ", ".(strcmp($this->price_registration, '') ? price2num($this->price_registration) : 'null');
437  $sql .= ", ".(strcmp($this->price_booth, '') ? price2num($this->price_booth) : 'null');
438  $sql .= ", ".(strcmp($this->max_attendees, '') ? ((int) $this->max_attendees) : 'null');
439  $sql .= ", ".($this->email_msgid ? "'".$this->db->escape($this->email_msgid)."'" : 'null');
440  $sql .= ", ".($this->note_private ? "'".$this->db->escape($this->note_private)."'" : 'null');
441  $sql .= ", ".($this->note_public ? "'".$this->db->escape($this->note_public)."'" : 'null');
442  $sql .= ", ".((int) $conf->entity);
443  $sql .= ")";
444 
445  dol_syslog(get_class($this)."::create", LOG_DEBUG);
446  $resql = $this->db->query($sql);
447  if ($resql) {
448  $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."projet");
449  $ret = $this->id;
450 
451  if (!$notrigger) {
452  // Call trigger
453  $result = $this->call_trigger('PROJECT_CREATE', $user);
454  if ($result < 0) {
455  $error++;
456  }
457  // End call triggers
458  }
459  } else {
460  $this->error = $this->db->lasterror();
461  $this->errno = $this->db->lasterrno();
462  $error++;
463  }
464 
465  // Update extrafield
466  if (!$error) {
467  $result = $this->insertExtraFields();
468  if ($result < 0) {
469  $error++;
470  }
471  }
472 
473  if (!$error && !empty($conf->global->MAIN_DISABLEDRAFTSTATUS)) {
474  $res = $this->setValid($user);
475  if ($res < 0) {
476  $error++;
477  }
478  }
479 
480  if (!$error) {
481  $this->db->commit();
482  return $ret;
483  } else {
484  $this->db->rollback();
485  return -1;
486  }
487  }
488 
496  public function update($user, $notrigger = 0)
497  {
498  global $langs, $conf;
499 
500  $error = 0;
501 
502  // Clean parameters
503  $this->title = trim($this->title);
504  $this->description = trim($this->description);
505  if ($this->opp_amount < 0) {
506  $this->opp_amount = '';
507  }
508  if ($this->opp_percent < 0) {
509  $this->opp_percent = '';
510  }
511  if ($this->date_end && $this->date_end < $this->date_start) {
512  $this->error = $langs->trans("ErrorDateEndLowerThanDateStart");
513  $this->errors[] = $this->error;
514  $this->db->rollback();
515  dol_syslog(get_class($this)."::update error -3 ".$this->error, LOG_ERR);
516  return -3;
517  }
518 
519  $this->entity = ((isset($this->entity) && is_numeric($this->entity)) ? $this->entity : $conf->entity);
520 
521  if (dol_strlen(trim($this->ref)) > 0) {
522  $this->db->begin();
523 
524  $sql = "UPDATE ".MAIN_DB_PREFIX."projet SET";
525  $sql .= " ref='".$this->db->escape($this->ref)."'";
526  $sql .= ", title = '".$this->db->escape($this->title)."'";
527  $sql .= ", description = '".$this->db->escape($this->description)."'";
528  $sql .= ", fk_soc = ".($this->socid > 0 ? $this->socid : "null");
529  $sql .= ", fk_statut = ".((int) $this->statut);
530  $sql .= ", fk_opp_status = ".((is_numeric($this->opp_status) && $this->opp_status > 0) ? $this->opp_status : 'null');
531  $sql .= ", opp_percent = ".((is_numeric($this->opp_percent) && $this->opp_percent != '') ? $this->opp_percent : 'null');
532  $sql .= ", public = ".($this->public ? 1 : 0);
533  $sql .= ", datec=".($this->date_c != '' ? "'".$this->db->idate($this->date_c)."'" : 'null');
534  $sql .= ", dateo=".($this->date_start != '' ? "'".$this->db->idate($this->date_start)."'" : 'null');
535  $sql .= ", datee=".($this->date_end != '' ? "'".$this->db->idate($this->date_end)."'" : 'null');
536  $sql .= ", date_close=".($this->date_close != '' ? "'".$this->db->idate($this->date_close)."'" : 'null');
537  $sql .= ", fk_user_close=".($this->fk_user_close > 0 ? $this->fk_user_close : "null");
538  $sql .= ", opp_amount = ".(strcmp($this->opp_amount, '') ? price2num($this->opp_amount) : "null");
539  $sql .= ", budget_amount = ".(strcmp($this->budget_amount, '') ? price2num($this->budget_amount) : "null");
540  $sql .= ", fk_user_modif = ".$user->id;
541  $sql .= ", usage_opportunity = ".($this->usage_opportunity ? 1 : 0);
542  $sql .= ", usage_task = ".($this->usage_task ? 1 : 0);
543  $sql .= ", usage_bill_time = ".($this->usage_bill_time ? 1 : 0);
544  $sql .= ", usage_organize_event = ".($this->usage_organize_event ? 1 : 0);
545  $sql .= ", accept_conference_suggestions = ".($this->accept_conference_suggestions ? 1 : 0);
546  $sql .= ", accept_booth_suggestions = ".($this->accept_booth_suggestions ? 1 : 0);
547  $sql .= ", price_registration = ".(strcmp($this->price_registration, '') ? price2num($this->price_registration) : "null");
548  $sql .= ", price_booth = ".(strcmp($this->price_booth, '') ? price2num($this->price_booth) : "null");
549  $sql .= ", max_attendees = ".(strcmp($this->max_attendees, '') ? price2num($this->max_attendees) : "null");
550  $sql .= ", entity = ".((int) $this->entity);
551  $sql .= " WHERE rowid = ".((int) $this->id);
552 
553  dol_syslog(get_class($this)."::update", LOG_DEBUG);
554  $resql = $this->db->query($sql);
555  if ($resql) {
556  // Update extrafield
557  if (!$error) {
558  $result = $this->insertExtraFields();
559  if ($result < 0) {
560  $error++;
561  }
562  }
563 
564  if (!$error && !$notrigger) {
565  // Call trigger
566  $result = $this->call_trigger('PROJECT_MODIFY', $user);
567  if ($result < 0) {
568  $error++;
569  }
570  // End call triggers
571  }
572 
573  if (!$error && (is_object($this->oldcopy) && $this->oldcopy->ref !== $this->ref)) {
574  // We remove directory
575  if ($conf->project->dir_output) {
576  $olddir = $conf->project->dir_output."/".dol_sanitizeFileName($this->oldcopy->ref);
577  $newdir = $conf->project->dir_output."/".dol_sanitizeFileName($this->ref);
578  if (file_exists($olddir)) {
579  include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
580  $res = @rename($olddir, $newdir);
581  if (!$res) {
582  $langs->load("errors");
583  $this->error = $langs->trans('ErrorFailToRenameDir', $olddir, $newdir);
584  $error++;
585  }
586  }
587  }
588  }
589  if (!$error) {
590  $this->db->commit();
591  $result = 1;
592  } else {
593  $this->db->rollback();
594  $result = -1;
595  }
596  } else {
597  $this->error = $this->db->lasterror();
598  $this->errors[] = $this->error;
599  $this->db->rollback();
600  if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
601  $result = -4;
602  } else {
603  $result = -2;
604  }
605  dol_syslog(get_class($this)."::update error ".$result." ".$this->error, LOG_ERR);
606  }
607  } else {
608  dol_syslog(get_class($this)."::update ref null");
609  $result = -1;
610  }
611 
612  return $result;
613  }
614 
624  public function fetch($id, $ref = '', $ref_ext = '', $email_msgid = '')
625  {
626  global $conf;
627 
628  if (empty($id) && empty($ref) && empty($ref_ext) && empty($email_msgid)) {
629  dol_syslog(get_class($this)."::fetch Bad parameters", LOG_WARNING);
630  return -1;
631  }
632 
633  $sql = "SELECT rowid, entity, ref, title, description, public, datec, opp_amount, budget_amount,";
634  $sql .= " tms, dateo, datee, date_close, fk_soc, fk_user_creat, fk_user_modif, fk_user_close, fk_statut as status, fk_opp_status, opp_percent,";
635  $sql .= " note_private, note_public, model_pdf, usage_opportunity, usage_task, usage_bill_time, usage_organize_event, email_msgid,";
636  $sql .= " accept_conference_suggestions, accept_booth_suggestions, price_registration, price_booth, max_attendees";
637  $sql .= " FROM ".MAIN_DB_PREFIX."projet";
638  if (!empty($id)) {
639  $sql .= " WHERE rowid = ".((int) $id);
640  } else {
641  $sql .= " WHERE entity IN (".getEntity('project').")";
642  if (!empty($ref)) {
643  $sql .= " AND ref = '".$this->db->escape($ref)."'";
644  } elseif (!empty($ref_ext)) {
645  $sql .= " AND ref_ext = '".$this->db->escape($ref_ext)."'";
646  } else {
647  $sql .= " AND email_msgid = '".$this->db->escape($email_msgid)."'";
648  }
649  }
650 
651  dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
652  $resql = $this->db->query($sql);
653  if ($resql) {
654  $num_rows = $this->db->num_rows($resql);
655 
656  if ($num_rows) {
657  $obj = $this->db->fetch_object($resql);
658 
659  $this->id = $obj->rowid;
660  $this->entity = $obj->entity;
661  $this->ref = $obj->ref;
662  $this->title = $obj->title;
663  $this->description = $obj->description;
664  $this->date_c = $this->db->jdate($obj->datec);
665  $this->datec = $this->db->jdate($obj->datec); // TODO deprecated
666  $this->date_m = $this->db->jdate($obj->tms);
667  $this->datem = $this->db->jdate($obj->tms); // TODO deprecated
668  $this->date_start = $this->db->jdate($obj->dateo);
669  $this->date_end = $this->db->jdate($obj->datee);
670  $this->date_close = $this->db->jdate($obj->date_close);
671  $this->note_private = $obj->note_private;
672  $this->note_public = $obj->note_public;
673  $this->socid = $obj->fk_soc;
674  $this->user_author_id = $obj->fk_user_creat;
675  $this->user_modification_id = $obj->fk_user_modif;
676  $this->user_close_id = $obj->fk_user_close;
677  $this->public = $obj->public;
678  $this->statut = $obj->status; // deprecated
679  $this->status = $obj->status;
680  $this->opp_status = $obj->fk_opp_status;
681  $this->opp_amount = $obj->opp_amount;
682  $this->opp_percent = $obj->opp_percent;
683  $this->budget_amount = $obj->budget_amount;
684  $this->model_pdf = $obj->model_pdf;
685  $this->modelpdf = $obj->model_pdf; // deprecated
686  $this->usage_opportunity = (int) $obj->usage_opportunity;
687  $this->usage_task = (int) $obj->usage_task;
688  $this->usage_bill_time = (int) $obj->usage_bill_time;
689  $this->usage_organize_event = (int) $obj->usage_organize_event;
690  $this->accept_conference_suggestions = (int) $obj->accept_conference_suggestions;
691  $this->accept_booth_suggestions = (int) $obj->accept_booth_suggestions;
692  $this->price_registration = $obj->price_registration;
693  $this->price_booth = $obj->price_booth;
694  $this->max_attendees = $obj->max_attendees;
695  $this->email_msgid = $obj->email_msgid;
696 
697  $this->db->free($resql);
698 
699  // Retrieve all extrafield
700  // fetch optionals attributes and labels
701  $this->fetch_optionals();
702 
703  return 1;
704  }
705 
706  $this->db->free($resql);
707 
708  return 0;
709  } else {
710  $this->error = $this->db->lasterror();
711  $this->errors[] = $this->db->lasterror();
712  return -1;
713  }
714  }
715 
716  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
728  public function get_element_list($type, $tablename, $datefieldname = '', $date_start = '', $date_end = '', $projectkey = 'fk_projet')
729  {
730  // phpcs:enable
731 
732  global $hookmanager;
733 
734  $elements = array();
735 
736  if ($this->id <= 0) {
737  return $elements;
738  }
739 
740  $ids = $this->id;
741 
742  if ($type == 'agenda') {
743  $sql = "SELECT id as rowid FROM ".MAIN_DB_PREFIX."actioncomm WHERE fk_project IN (".$this->db->sanitize($ids).") AND entity IN (".getEntity('agenda').")";
744  } elseif ($type == 'expensereport') {
745  $sql = "SELECT ed.rowid FROM ".MAIN_DB_PREFIX."expensereport as e, ".MAIN_DB_PREFIX."expensereport_det as ed WHERE e.rowid = ed.fk_expensereport AND e.entity IN (".getEntity('expensereport').") AND ed.fk_projet IN (".$this->db->sanitize($ids).")";
746  } elseif ($type == 'project_task') {
747  $sql = "SELECT DISTINCT pt.rowid FROM ".MAIN_DB_PREFIX."projet_task as pt WHERE pt.fk_projet IN (".$this->db->sanitize($ids).")";
748  } elseif ($type == 'project_task_time') { // Case we want to duplicate line foreach user
749  $sql = "SELECT DISTINCT pt.rowid, ptt.fk_user FROM ".MAIN_DB_PREFIX."projet_task as pt, ".MAIN_DB_PREFIX."projet_task_time as ptt WHERE pt.rowid = ptt.fk_task AND pt.fk_projet IN (".$this->db->sanitize($ids).")";
750  } elseif ($type == 'stock_mouvement') {
751  $sql = "SELECT ms.rowid, ms.fk_user_author as fk_user FROM ".MAIN_DB_PREFIX."stock_mouvement as ms, ".MAIN_DB_PREFIX."entrepot as e WHERE e.rowid = ms.fk_entrepot AND e.entity IN (".getEntity('stock').") AND ms.origintype = 'project' AND ms.fk_origin IN (".$this->db->sanitize($ids).") AND ms.type_mouvement = 1";
752  } elseif ($type == 'loan') {
753  $sql = "SELECT l.rowid, l.fk_user_author as fk_user FROM ".MAIN_DB_PREFIX."loan as l WHERE l.entity IN (".getEntity('loan').") AND l.fk_projet IN (".$this->db->sanitize($ids).")";
754  } else {
755  $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX.$tablename." WHERE ".$projectkey." IN (".$this->db->sanitize($ids).") AND entity IN (".getEntity($type).")";
756  }
757 
758  if ($date_start > 0 && $type == 'loan') {
759  $sql .= " AND (dateend > '".$this->db->idate($date_start)."' OR dateend IS NULL)";
760  } elseif ($date_start > 0 && ($type != 'project_task')) { // For table project_taks, we want the filter on date apply on project_time_spent table
761  if (empty($datefieldname) && !empty($this->table_element_date)) {
762  $datefieldname = $this->table_element_date;
763  }
764  if (empty($datefieldname)) {
765  return 'Error this object has no date field defined';
766  }
767  $sql .= " AND (".$datefieldname." >= '".$this->db->idate($date_start)."' OR ".$datefieldname." IS NULL)";
768  }
769 
770  if ($date_end > 0 && $type == 'loan') {
771  $sql .= " AND (datestart < '".$this->db->idate($date_end)."' OR datestart IS NULL)";
772  } elseif ($date_end > 0 && ($type != 'project_task')) { // For table project_taks, we want the filter on date apply on project_time_spent table
773  if (empty($datefieldname) && !empty($this->table_element_date)) {
774  $datefieldname = $this->table_element_date;
775  }
776  if (empty($datefieldname)) {
777  return 'Error this object has no date field defined';
778  }
779  $sql .= " AND (".$datefieldname." <= '".$this->db->idate($date_end)."' OR ".$datefieldname." IS NULL)";
780  }
781 
782  $parameters = array(
783  'sql'=>$sql,
784  'type' => $type,
785  'tablename' => $tablename,
786  'datefieldname' => $datefieldname,
787  'dates' => $date_start,
788  'datee' => $date_end,
789  'fk_projet' => $projectkey,
790  'ids' => $ids,
791  );
792  $reshook = $hookmanager->executeHooks('getElementList', $parameters);
793  if ($reshook > 0) {
794  $sql = $hookmanager->resPrint;
795  } else {
796  $sql .= $hookmanager->resPrint;
797  }
798 
799  if (!$sql) {
800  return -1;
801  }
802 
803  //print $sql;
804  dol_syslog(get_class($this)."::get_element_list", LOG_DEBUG);
805  $result = $this->db->query($sql);
806  if ($result) {
807  $nump = $this->db->num_rows($result);
808  if ($nump) {
809  $i = 0;
810  while ($i < $nump) {
811  $obj = $this->db->fetch_object($result);
812 
813  $elements[$i] = $obj->rowid.(empty($obj->fk_user) ? '' : '_'.$obj->fk_user);
814 
815  $i++;
816  }
817  $this->db->free($result);
818  }
819 
820  /* Return array even if empty*/
821  return $elements;
822  } else {
823  dol_print_error($this->db);
824  }
825  }
826 
834  public function delete($user, $notrigger = 0)
835  {
836  global $langs, $conf;
837  require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
838 
839  $error = 0;
840 
841  $this->db->begin();
842 
843  if (!$error) {
844  // Delete linked contacts
845  $res = $this->delete_linked_contact();
846  if ($res < 0) {
847  $this->error = 'ErrorFailToDeleteLinkedContact';
848  //$error++;
849  $this->db->rollback();
850  return 0;
851  }
852  }
853 
854  // Set fk_projet into elements to null
855  $listoftables = array(
856  'propal'=>'fk_projet', 'commande'=>'fk_projet', 'facture'=>'fk_projet',
857  'supplier_proposal'=>'fk_projet', 'commande_fournisseur'=>'fk_projet', 'facture_fourn'=>'fk_projet',
858  'expensereport_det'=>'fk_projet', 'contrat'=>'fk_projet',
859  'fichinter'=>'fk_projet',
860  'don'=>array('field'=>'fk_projet', 'module'=>'don'),
861  'actioncomm'=>'fk_project',
862  'mrp_mo'=>'fk_project',
863  'entrepot'=>'fk_project'
864  );
865  foreach ($listoftables as $key => $value) {
866  if (is_array($value)) {
867  if (!isModEnabled($value['module'])) {
868  continue;
869  }
870  $fieldname = $value['field'];
871  } else {
872  $fieldname = $value;
873  }
874  $sql = "UPDATE ".MAIN_DB_PREFIX.$key." SET ".$fieldname." = NULL where ".$fieldname." = ".((int) $this->id);
875 
876  $resql = $this->db->query($sql);
877  if (!$resql) {
878  $this->errors[] = $this->db->lasterror();
879  $error++;
880  break;
881  }
882  }
883 
884  // Remove linked categories.
885  if (!$error) {
886  $sql = "DELETE FROM ".MAIN_DB_PREFIX."categorie_project";
887  $sql .= " WHERE fk_project = ".((int) $this->id);
888 
889  $result = $this->db->query($sql);
890  if (!$result) {
891  $error++;
892  $this->errors[] = $this->db->lasterror();
893  }
894  }
895 
896  // Fetch tasks
897  $this->getLinesArray($user);
898 
899  // Delete tasks
900  $ret = $this->deleteTasks($user);
901  if ($ret < 0) {
902  $error++;
903  }
904 
905 
906  // Delete all child tables
907  if (!$error) {
908  $elements = array('categorie_project'); // elements to delete. TODO Make goodway to delete
909  foreach ($elements as $table) {
910  if (!$error) {
911  $sql = "DELETE FROM ".MAIN_DB_PREFIX.$table;
912  $sql .= " WHERE fk_project = ".((int) $this->id);
913 
914  $result = $this->db->query($sql);
915  if (!$result) {
916  $error++;
917  $this->errors[] = $this->db->lasterror();
918  }
919  }
920  }
921  }
922 
923  if (!$error) {
924  $sql = "DELETE FROM ".MAIN_DB_PREFIX."projet_extrafields";
925  $sql .= " WHERE fk_object = ".((int) $this->id);
926 
927  $resql = $this->db->query($sql);
928  if (!$resql) {
929  $this->errors[] = $this->db->lasterror();
930  $error++;
931  }
932  }
933 
934  // Delete project
935  if (!$error) {
936  $sql = "DELETE FROM ".MAIN_DB_PREFIX."projet";
937  $sql .= " WHERE rowid=".((int) $this->id);
938 
939  $resql = $this->db->query($sql);
940  if (!$resql) {
941  $this->errors[] = $langs->trans("CantRemoveProject", $langs->transnoentitiesnoconv("ProjectOverview"));
942  $error++;
943  }
944  }
945 
946 
947 
948  if (empty($error)) {
949  // We remove directory
950  $projectref = dol_sanitizeFileName($this->ref);
951  if ($conf->project->dir_output) {
952  $dir = $conf->project->dir_output."/".$projectref;
953  if (file_exists($dir)) {
954  $res = @dol_delete_dir_recursive($dir);
955  if (!$res) {
956  $this->errors[] = 'ErrorFailToDeleteDir';
957  $error++;
958  }
959  }
960  }
961 
962  if (!$notrigger) {
963  // Call trigger
964  $result = $this->call_trigger('PROJECT_DELETE', $user);
965 
966  if ($result < 0) {
967  $error++;
968  }
969  // End call triggers
970  }
971  }
972 
973  if (empty($error)) {
974  $this->db->commit();
975  return 1;
976  } else {
977  foreach ($this->errors as $errmsg) {
978  dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
979  $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
980  }
981  dol_syslog(get_class($this)."::delete ".$this->error, LOG_ERR);
982  $this->db->rollback();
983  return -1;
984  }
985  }
986 
995  public function getElementCount($type, $tablename, $projectkey = 'fk_projet')
996  {
997  if ($this->id <= 0) {
998  return 0;
999  }
1000 
1001  if ($type == 'agenda') {
1002  $sql = "SELECT COUNT(id) as nb FROM ".MAIN_DB_PREFIX."actioncomm WHERE fk_project = ".((int) $this->id)." AND entity IN (".getEntity('agenda').")";
1003  } elseif ($type == 'expensereport') {
1004  $sql = "SELECT COUNT(ed.rowid) as nb FROM ".MAIN_DB_PREFIX."expensereport as e, ".MAIN_DB_PREFIX."expensereport_det as ed WHERE e.rowid = ed.fk_expensereport AND e.entity IN (".getEntity('expensereport').") AND ed.fk_projet = ".((int) $this->id);
1005  } elseif ($type == 'project_task') {
1006  $sql = "SELECT DISTINCT COUNT(pt.rowid) as nb FROM ".MAIN_DB_PREFIX."projet_task as pt WHERE pt.fk_projet = ".((int) $this->id);
1007  } elseif ($type == 'project_task_time') { // Case we want to duplicate line foreach user
1008  $sql = "SELECT DISTINCT COUNT(pt.rowid) as nb FROM ".MAIN_DB_PREFIX."projet_task as pt, ".MAIN_DB_PREFIX."projet_task_time as ptt WHERE pt.rowid = ptt.fk_task AND pt.fk_projet = ".((int) $this->id);
1009  } elseif ($type == 'stock_mouvement') {
1010  $sql = "SELECT COUNT(ms.rowid) as nb FROM ".MAIN_DB_PREFIX."stock_mouvement as ms, ".MAIN_DB_PREFIX."entrepot as e WHERE e.rowid = ms.fk_entrepot AND e.entity IN (".getEntity('stock').") AND ms.origintype = 'project' AND ms.fk_origin = ".((int) $this->id)." AND ms.type_mouvement = 1";
1011  } elseif ($type == 'loan') {
1012  $sql = "SELECT COUNT(l.rowid) as nb FROM ".MAIN_DB_PREFIX."loan as l WHERE l.entity IN (".getEntity('loan').") AND l.fk_projet = ".((int) $this->id);
1013  } else {
1014  $sql = "SELECT COUNT(rowid) as nb FROM ".MAIN_DB_PREFIX.$tablename." WHERE ".$projectkey." = ".((int) $this->id)." AND entity IN (".getEntity($type).")";
1015  }
1016 
1017  $result = $this->db->query($sql);
1018 
1019  if (!$result) {
1020  return 0;
1021  }
1022 
1023  $obj = $this->db->fetch_object($result);
1024 
1025  $this->db->free($result);
1026 
1027  return $obj->nb;
1028  }
1029 
1036  public function deleteTasks($user)
1037  {
1038  $countTasks = count($this->lines);
1039  $deleted = false;
1040  if ($countTasks) {
1041  foreach ($this->lines as $task) {
1042  if ($task->hasChildren() <= 0) { // If there is no children (or error to detect them)
1043  $deleted = true;
1044  $ret = $task->delete($user);
1045  if ($ret <= 0) {
1046  $this->errors[] = $this->db->lasterror();
1047  return -1;
1048  }
1049  }
1050  }
1051  }
1052  $this->getLinesArray($user);
1053  if ($deleted && count($this->lines) < $countTasks) {
1054  if (count($this->lines)) {
1055  $this->deleteTasks($this->lines);
1056  }
1057  }
1058 
1059  return 1;
1060  }
1061 
1069  public function setValid($user, $notrigger = 0)
1070  {
1071  global $langs, $conf;
1072 
1073  $error = 0;
1074 
1075  if ($this->statut != 1) {
1076  // Check parameters
1077  if (preg_match('/^'.preg_quote($langs->trans("CopyOf").' ').'/', $this->title)) {
1078  $this->error = $langs->trans("ErrorFieldFormat", $langs->transnoentities("Label")).'. '.$langs->trans('RemoveString', $langs->transnoentitiesnoconv("CopyOf"));
1079  return -1;
1080  }
1081 
1082  $this->db->begin();
1083 
1084  $sql = "UPDATE ".MAIN_DB_PREFIX."projet";
1085  $sql .= " SET fk_statut = 1";
1086  $sql .= " WHERE rowid = ".((int) $this->id);
1087  $sql .= " AND entity = ".((int) $conf->entity);
1088 
1089  dol_syslog(get_class($this)."::setValid", LOG_DEBUG);
1090  $resql = $this->db->query($sql);
1091  if ($resql) {
1092  // Call trigger
1093  if (empty($notrigger)) {
1094  $result = $this->call_trigger('PROJECT_VALIDATE', $user);
1095  if ($result < 0) {
1096  $error++;
1097  }
1098  // End call triggers
1099  }
1100 
1101  if (!$error) {
1102  $this->statut = 1;
1103  $this->db->commit();
1104  return 1;
1105  } else {
1106  $this->db->rollback();
1107  $this->error = join(',', $this->errors);
1108  dol_syslog(get_class($this)."::setValid ".$this->error, LOG_ERR);
1109  return -1;
1110  }
1111  } else {
1112  $this->db->rollback();
1113  $this->error = $this->db->lasterror();
1114  return -1;
1115  }
1116  }
1117  }
1118 
1125  public function setClose($user)
1126  {
1127  global $langs, $conf;
1128 
1129  $now = dol_now();
1130 
1131  $error = 0;
1132 
1133  if ($this->statut != self::STATUS_CLOSED) {
1134  $this->db->begin();
1135 
1136  $sql = "UPDATE ".MAIN_DB_PREFIX."projet";
1137  $sql .= " SET fk_statut = ".self::STATUS_CLOSED.", fk_user_close = ".((int) $user->id).", date_close = '".$this->db->idate($now)."'";
1138  $sql .= " WHERE rowid = ".((int) $this->id);
1139  $sql .= " AND fk_statut = ".self::STATUS_VALIDATED;
1140 
1141  if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) {
1142  // TODO What to do if fk_opp_status is not code 'WON' or 'LOST'
1143  }
1144 
1145  dol_syslog(get_class($this)."::setClose", LOG_DEBUG);
1146  $resql = $this->db->query($sql);
1147  if ($resql) {
1148  // Call trigger
1149  $result = $this->call_trigger('PROJECT_CLOSE', $user);
1150  if ($result < 0) {
1151  $error++;
1152  }
1153  // End call triggers
1154 
1155  if (!$error) {
1156  $this->statut = 2;
1157  $this->db->commit();
1158  return 1;
1159  } else {
1160  $this->db->rollback();
1161  $this->error = join(',', $this->errors);
1162  dol_syslog(get_class($this)."::setClose ".$this->error, LOG_ERR);
1163  return -1;
1164  }
1165  } else {
1166  $this->db->rollback();
1167  $this->error = $this->db->lasterror();
1168  return -1;
1169  }
1170  }
1171 
1172  return 0;
1173  }
1174 
1181  public function getLibStatut($mode = 0)
1182  {
1183  return $this->LibStatut(isset($this->statut) ? $this->statut : $this->status, $mode);
1184  }
1185 
1186  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1194  public function LibStatut($status, $mode = 0)
1195  {
1196  // phpcs:enable
1197  global $langs;
1198 
1199  $statustrans = array(
1200  0 => 'status0',
1201  1 => 'status4',
1202  2 => 'status6',
1203  );
1204 
1205  $statusClass = 'status0';
1206  if (!empty($statustrans[$status])) {
1207  $statusClass = $statustrans[$status];
1208  }
1209 
1210  return dolGetStatus($langs->transnoentitiesnoconv($this->statuts_long[$status]), $langs->transnoentitiesnoconv($this->statuts_short[$status]), '', $statusClass, $mode);
1211  }
1212 
1226  public function getNomUrl($withpicto = 0, $option = '', $addlabel = 0, $moreinpopup = '', $sep = ' - ', $notooltip = 0, $save_lastsearch_value = -1, $morecss = '')
1227  {
1228  global $conf, $langs, $user, $hookmanager;
1229 
1230  if (!empty($conf->dol_no_mouse_hover)) {
1231  $notooltip = 1; // Force disable tooltips
1232  }
1233 
1234  $result = '';
1235  if (!empty($conf->global->PROJECT_OPEN_ALWAYS_ON_TAB)) {
1236  $option = $conf->global->PROJECT_OPEN_ALWAYS_ON_TAB;
1237  }
1238 
1239  $label = '';
1240  if ($option != 'nolink') {
1241  $label = img_picto('', $this->picto, 'class="pictofixedwidth"').' <u class="paddingrightonly">'.$langs->trans("Project").'</u>';
1242  }
1243  if (isset($this->status)) {
1244  $label .= ' '.$this->getLibStatut(5);
1245  }
1246  $label .= ($label ? '<br>' : '').'<b>'.$langs->trans('Ref').': </b>'.$this->ref; // The space must be after the : to not being explode when showing the title in img_picto
1247  $label .= ($label ? '<br>' : '').'<b>'.$langs->trans('Label').': </b>'.$this->title; // The space must be after the : to not being explode when showing the title in img_picto
1248  if (isset($this->public)) {
1249  $label .= '<br><b>'.$langs->trans("Visibility").":</b> ";
1250  $label .= ($this->public ? img_picto($langs->trans('SharedProject'), 'world', 'class="paddingrightonly"').$langs->trans("SharedProject") : img_picto($langs->trans('PrivateProject'), 'private', 'class="paddingrightonly"').$langs->trans("PrivateProject"));
1251  }
1252  if (!empty($this->thirdparty_name)) {
1253  $label .= ($label ? '<br>' : '').'<b>'.$langs->trans('ThirdParty').': </b>'.$this->thirdparty_name; // The space must be after the : to not being explode when showing the title in img_picto
1254  }
1255  if (!empty($this->date_start)) {
1256  $label .= ($label ? '<br>' : '').'<b>'.$langs->trans('DateStart').': </b>'.dol_print_date($this->date_start, 'day'); // The space must be after the : to not being explode when showing the title in img_picto
1257  }
1258  if (!empty($this->date_end)) {
1259  $label .= ($label ? '<br>' : '').'<b>'.$langs->trans('DateEnd').': </b>'.dol_print_date($this->date_end, 'day'); // The space must be after the : to not being explode when showing the title in img_picto
1260  }
1261  if ($moreinpopup) {
1262  $label .= '<br>'.$moreinpopup;
1263  }
1264 
1265  $url = '';
1266  if ($option != 'nolink') {
1267  if (preg_match('/\.php$/', $option)) {
1268  $url = dol_buildpath($option, 1).'?id='.$this->id;
1269  } elseif ($option == 'task') {
1270  $url = DOL_URL_ROOT.'/projet/tasks.php?id='.$this->id;
1271  } elseif ($option == 'preview') {
1272  $url = DOL_URL_ROOT.'/projet/element.php?id='.$this->id;
1273  } elseif ($option == 'eventorganization') {
1274  $url = DOL_URL_ROOT.'/eventorganization/conferenceorbooth_list.php?projectid='.$this->id;
1275  } else {
1276  $url = DOL_URL_ROOT.'/projet/card.php?id='.$this->id;
1277  }
1278  // Add param to save lastsearch_values or not
1279  $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
1280  if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
1281  $add_save_lastsearch_values = 1;
1282  }
1283  if ($add_save_lastsearch_values) {
1284  $url .= '&save_lastsearch_values=1';
1285  }
1286  }
1287 
1288  $linkclose = '';
1289  if (empty($notooltip) && $user->hasRight('projet', 'lire')) {
1290  if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
1291  $label = $langs->trans("ShowProject");
1292  $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
1293  }
1294  $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"';
1295  $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"';
1296  } else {
1297  $linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
1298  }
1299 
1300  $picto = 'projectpub';
1301  if (!$this->public) {
1302  $picto = 'project';
1303  }
1304 
1305  $linkstart = '<a href="'.$url.'"';
1306  $linkstart .= $linkclose.'>';
1307  $linkend = '</a>';
1308 
1309  $result .= $linkstart;
1310  if ($withpicto) {
1311  $result .= img_object(($notooltip ? '' : $label), $picto, ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip pictofixedwidth em088"'), 0, 0, $notooltip ? 0 : 1);
1312  }
1313  if ($withpicto != 2) {
1314  $result .= $this->ref;
1315  }
1316  $result .= $linkend;
1317  if ($withpicto != 2) {
1318  $result .= (($addlabel && $this->title) ? $sep.dol_trunc($this->title, ($addlabel > 1 ? $addlabel : 0)) : '');
1319  }
1320 
1321  global $action;
1322  $hookmanager->initHooks(array('projectdao'));
1323  $parameters = array('id'=>$this->id, 'getnomurl' => &$result);
1324  $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
1325  if ($reshook > 0) {
1326  $result = $hookmanager->resPrint;
1327  } else {
1328  $result .= $hookmanager->resPrint;
1329  }
1330 
1331  return $result;
1332  }
1333 
1341  public function initAsSpecimen()
1342  {
1343  global $user, $langs, $conf;
1344 
1345  $now = dol_now();
1346 
1347  // Initialise parameters
1348  $this->id = 0;
1349  $this->ref = 'SPECIMEN';
1350  $this->specimen = 1;
1351  $this->socid = 1;
1352  $this->date_c = $now;
1353  $this->date_m = $now;
1354  $this->date_start = $now;
1355  $this->date_end = $now + (3600 * 24 * 365);
1356  $this->note_public = 'SPECIMEN';
1357  $this->fk_ele = 20000;
1358  $this->opp_amount = 20000;
1359  $this->budget_amount = 10000;
1360 
1361  $this->usage_opportunity = 1;
1362  $this->usage_task = 1;
1363  $this->usage_bill_time = 1;
1364  $this->usage_organize_event = 1;
1365 
1366  /*
1367  $nbp = mt_rand(1, 9);
1368  $xnbp = 0;
1369  while ($xnbp < $nbp)
1370  {
1371  $line = new Task($this->db);
1372  $line->fk_project = 0;
1373  $line->label = $langs->trans("Label") . " " . $xnbp;
1374  $line->description = $langs->trans("Description") . " " . $xnbp;
1375 
1376  $this->lines[]=$line;
1377  $xnbp++;
1378  }
1379  */
1380  }
1381 
1389  public function restrictedProjectArea(User $user, $mode = 'read')
1390  {
1391  // To verify role of users
1392  $userAccess = 0;
1393  if (($mode == 'read' && !empty($user->rights->projet->all->lire)) || ($mode == 'write' && !empty($user->rights->projet->all->creer)) || ($mode == 'delete' && !empty($user->rights->projet->all->supprimer))) {
1394  $userAccess = 1;
1395  } elseif ($this->public && (($mode == 'read' && !empty($user->rights->projet->lire)) || ($mode == 'write' && !empty($user->rights->projet->creer)) || ($mode == 'delete' && !empty($user->rights->projet->supprimer)))) {
1396  $userAccess = 1;
1397  } else { // No access due to permission to read all projects, so we check if we are a contact of project
1398  foreach (array('internal', 'external') as $source) {
1399  $userRole = $this->liste_contact(4, $source);
1400  $num = count($userRole);
1401 
1402  $nblinks = 0;
1403  while ($nblinks < $num) {
1404  if ($source == 'internal' && $user->id == $userRole[$nblinks]['id']) { // $userRole[$nblinks]['id'] is id of user (llx_user) for internal contacts
1405  if ($mode == 'read' && $user->rights->projet->lire) {
1406  $userAccess++;
1407  }
1408  if ($mode == 'write' && $user->rights->projet->creer) {
1409  $userAccess++;
1410  }
1411  if ($mode == 'delete' && $user->rights->projet->supprimer) {
1412  $userAccess++;
1413  }
1414  }
1415  if ($source == 'external' && $user->socid > 0 && $user->socid == $userRole[$nblinks]['socid']) { // $userRole[$nblinks]['id'] is id of contact (llx_socpeople) or external contacts
1416  if ($mode == 'read' && $user->rights->projet->lire) {
1417  $userAccess++;
1418  }
1419  if ($mode == 'write' && $user->rights->projet->creer) {
1420  $userAccess++;
1421  }
1422  if ($mode == 'delete' && $user->rights->projet->supprimer) {
1423  $userAccess++;
1424  }
1425  }
1426  $nblinks++;
1427  }
1428  }
1429  //if (empty($nblinks)) // If nobody has permission, we grant creator
1430  //{
1431  // if ((!empty($this->user_author_id) && $this->user_author_id == $user->id))
1432  // {
1433  // $userAccess = 1;
1434  // }
1435  //}
1436  }
1437 
1438  return ($userAccess ? $userAccess : -1);
1439  }
1440 
1451  public function getProjectsAuthorizedForUser($user, $mode = 0, $list = 0, $socid = 0, $filter = '')
1452  {
1453  $projects = array();
1454  $temp = array();
1455 
1456  $sql = "SELECT ".(($mode == 0 || $mode == 1) ? "DISTINCT " : "")."p.rowid, p.ref";
1457  $sql .= " FROM ".MAIN_DB_PREFIX."projet as p";
1458  if ($mode == 0) {
1459  $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."element_contact as ec ON ec.element_id = p.rowid";
1460  } elseif ($mode == 1) {
1461  $sql .= ", ".MAIN_DB_PREFIX."element_contact as ec";
1462  } elseif ($mode == 2) {
1463  // No filter. Use this if user has permission to see all project
1464  }
1465  $sql .= " WHERE p.entity IN (".getEntity('project').")";
1466  // Internal users must see project he is contact to even if project linked to a third party he can't see.
1467  //if ($socid || ! $user->rights->societe->client->voir) $sql.= " AND (p.fk_soc IS NULL OR p.fk_soc = 0 OR p.fk_soc = ".((int) $socid).")";
1468  if ($socid > 0) {
1469  $sql .= " AND (p.fk_soc IS NULL OR p.fk_soc = 0 OR p.fk_soc = ".((int) $socid).")";
1470  }
1471 
1472  // Get id of types of contacts for projects (This list never contains a lot of elements)
1473  $listofprojectcontacttype = array();
1474  $sql2 = "SELECT ctc.rowid, ctc.code FROM ".MAIN_DB_PREFIX."c_type_contact as ctc";
1475  $sql2 .= " WHERE ctc.element = '".$this->db->escape($this->element)."'";
1476  $sql2 .= " AND ctc.source = 'internal'";
1477  $resql = $this->db->query($sql2);
1478  if ($resql) {
1479  while ($obj = $this->db->fetch_object($resql)) {
1480  $listofprojectcontacttype[$obj->rowid] = $obj->code;
1481  }
1482  } else {
1483  dol_print_error($this->db);
1484  }
1485  if (count($listofprojectcontacttype) == 0) {
1486  $listofprojectcontacttype[0] = '0'; // To avoid syntax error if not found
1487  }
1488 
1489  if ($mode == 0) {
1490  $sql .= " AND ( p.public = 1";
1491  $sql .= " OR ( ec.fk_c_type_contact IN (".$this->db->sanitize(join(',', array_keys($listofprojectcontacttype))).")";
1492  $sql .= " AND ec.fk_socpeople = ".((int) $user->id).")";
1493  $sql .= " )";
1494  } elseif ($mode == 1) {
1495  $sql .= " AND ec.element_id = p.rowid";
1496  $sql .= " AND (";
1497  $sql .= " ( ec.fk_c_type_contact IN (".$this->db->sanitize(join(',', array_keys($listofprojectcontacttype))).")";
1498  $sql .= " AND ec.fk_socpeople = ".((int) $user->id).")";
1499  $sql .= " )";
1500  } elseif ($mode == 2) {
1501  // No filter. Use this if user has permission to see all project
1502  }
1503 
1504  $sql .= $filter;
1505  //print $sql;
1506 
1507  $resql = $this->db->query($sql);
1508  if ($resql) {
1509  $num = $this->db->num_rows($resql);
1510  $i = 0;
1511  while ($i < $num) {
1512  $row = $this->db->fetch_row($resql);
1513  $projects[$row[0]] = $row[1];
1514  $temp[] = $row[0];
1515  $i++;
1516  }
1517 
1518  $this->db->free($resql);
1519 
1520  if ($list) {
1521  if (empty($temp)) {
1522  return '0';
1523  }
1524  $result = implode(',', $temp);
1525  return $result;
1526  }
1527  } else {
1528  dol_print_error($this->db);
1529  }
1530 
1531  return $projects;
1532  }
1533 
1549  public function createFromClone(User $user, $fromid, $clone_contact = false, $clone_task = true, $clone_project_file = false, $clone_task_file = false, $clone_note = true, $move_date = true, $notrigger = 0, $newthirdpartyid = 0)
1550  {
1551  global $langs, $conf;
1552 
1553  $error = 0;
1554 
1555  dol_syslog("createFromClone clone_contact=".$clone_contact." clone_task=".$clone_task." clone_project_file=".$clone_project_file." clone_note=".$clone_note." move_date=".$move_date, LOG_DEBUG);
1556 
1557  $now = dol_mktime(0, 0, 0, idate('m', dol_now()), idate('d', dol_now()), idate('Y', dol_now()));
1558 
1559  $clone_project = new Project($this->db);
1560 
1561  $clone_project->context['createfromclone'] = 'createfromclone';
1562 
1563  $this->db->begin();
1564 
1565  // Load source object
1566  $clone_project->fetch($fromid);
1567  $clone_project->fetch_optionals();
1568  if ($newthirdpartyid > 0) {
1569  $clone_project->socid = $newthirdpartyid;
1570  }
1571  $clone_project->fetch_thirdparty();
1572 
1573  $orign_dt_start = $clone_project->date_start;
1574  $orign_project_ref = $clone_project->ref;
1575 
1576  $clone_project->id = 0;
1577  if ($move_date) {
1578  $clone_project->date_start = $now;
1579  if (!(empty($clone_project->date_end))) {
1580  $clone_project->date_end = $clone_project->date_end + ($now - $orign_dt_start);
1581  }
1582  }
1583 
1584  $clone_project->date_c = $now;
1585 
1586  if (!$clone_note) {
1587  $clone_project->note_private = '';
1588  $clone_project->note_public = '';
1589  }
1590 
1591  //Generate next ref
1592  $defaultref = '';
1593  $obj = empty($conf->global->PROJECT_ADDON) ? 'mod_project_simple' : $conf->global->PROJECT_ADDON;
1594  // Search template files
1595  $file = ''; $classname = ''; $filefound = 0;
1596  $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
1597  foreach ($dirmodels as $reldir) {
1598  $file = dol_buildpath($reldir."core/modules/project/".$obj.'.php', 0);
1599  if (file_exists($file)) {
1600  $filefound = 1;
1601  dol_include_once($reldir."core/modules/project/".$obj.'.php');
1602  $modProject = new $obj;
1603  $defaultref = $modProject->getNextValue(is_object($clone_project->thirdparty) ? $clone_project->thirdparty : null, $clone_project);
1604  break;
1605  }
1606  }
1607  if (is_numeric($defaultref) && $defaultref <= 0) {
1608  $defaultref = '';
1609  }
1610 
1611  $clone_project->ref = $defaultref;
1612  $clone_project->title = $langs->trans("CopyOf").' '.$clone_project->title;
1613 
1614  // Create clone
1615  $result = $clone_project->create($user, $notrigger);
1616 
1617  // Other options
1618  if ($result < 0) {
1619  $this->error .= $clone_project->error;
1620  $error++;
1621  }
1622 
1623  if (!$error) {
1624  //Get the new project id
1625  $clone_project_id = $clone_project->id;
1626 
1627  //Note Update
1628  if (!$clone_note) {
1629  $clone_project->note_private = '';
1630  $clone_project->note_public = '';
1631  } else {
1632  $this->db->begin();
1633  $res = $clone_project->update_note(dol_html_entity_decode($clone_project->note_public, ENT_QUOTES | ENT_HTML5), '_public');
1634  if ($res < 0) {
1635  $this->error .= $clone_project->error;
1636  $error++;
1637  $this->db->rollback();
1638  } else {
1639  $this->db->commit();
1640  }
1641 
1642  $this->db->begin();
1643  $res = $clone_project->update_note(dol_html_entity_decode($clone_project->note_private, ENT_QUOTES | ENT_HTML5), '_private');
1644  if ($res < 0) {
1645  $this->error .= $clone_project->error;
1646  $error++;
1647  $this->db->rollback();
1648  } else {
1649  $this->db->commit();
1650  }
1651  }
1652 
1653  //Duplicate contact
1654  if ($clone_contact) {
1655  $origin_project = new Project($this->db);
1656  $origin_project->fetch($fromid);
1657 
1658  foreach (array('internal', 'external') as $source) {
1659  $tab = $origin_project->liste_contact(-1, $source);
1660  if (is_array($tab) && count($tab)>0) {
1661  foreach ($tab as $contacttoadd) {
1662  $clone_project->add_contact($contacttoadd['id'], $contacttoadd['code'], $contacttoadd['source'], $notrigger);
1663  if ($clone_project->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
1664  $langs->load("errors");
1665  $this->error .= $langs->trans("ErrorThisContactIsAlreadyDefinedAsThisType");
1666  $error++;
1667  } else {
1668  if ($clone_project->error != '') {
1669  $this->error .= $clone_project->error;
1670  $error++;
1671  }
1672  }
1673  }
1674  } elseif ($tab < 0) {
1675  $this->error .= $origin_project->error;
1676  $error++;
1677  }
1678  }
1679  }
1680 
1681  //Duplicate file
1682  if ($clone_project_file) {
1683  require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
1684 
1685  $clone_project_dir = $conf->project->dir_output."/".dol_sanitizeFileName($defaultref);
1686  $ori_project_dir = $conf->project->dir_output."/".dol_sanitizeFileName($orign_project_ref);
1687 
1688  if (dol_mkdir($clone_project_dir) >= 0) {
1689  $filearray = dol_dir_list($ori_project_dir, "files", 0, '', '(\.meta|_preview.*\.png)$', '', SORT_ASC, 1);
1690  foreach ($filearray as $key => $file) {
1691  $rescopy = dol_copy($ori_project_dir.'/'.$file['name'], $clone_project_dir.'/'.$file['name'], 0, 1);
1692  if (is_numeric($rescopy) && $rescopy < 0) {
1693  $this->error .= $langs->trans("ErrorFailToCopyFile", $ori_project_dir.'/'.$file['name'], $clone_project_dir.'/'.$file['name']);
1694  $error++;
1695  }
1696  }
1697  } else {
1698  $this->error .= $langs->trans('ErrorInternalErrorDetected').':dol_mkdir';
1699  $error++;
1700  }
1701  }
1702 
1703  //Duplicate task
1704  if ($clone_task) {
1705  require_once DOL_DOCUMENT_ROOT.'/projet/class/task.class.php';
1706 
1707  $taskstatic = new Task($this->db);
1708 
1709  // Security check
1710  $socid = 0;
1711  if ($user->socid > 0) {
1712  $socid = $user->socid;
1713  }
1714 
1715  $tasksarray = $taskstatic->getTasksArray(0, 0, $fromid, $socid, 0);
1716 
1717  $tab_conv_child_parent = array();
1718 
1719  // Loop on each task, to clone it
1720  foreach ($tasksarray as $tasktoclone) {
1721  $result_clone = $taskstatic->createFromClone($user, $tasktoclone->id, $clone_project_id, $tasktoclone->fk_parent, $move_date, true, false, $clone_task_file, true, false);
1722  if ($result_clone <= 0) {
1723  $this->error .= $taskstatic->error;
1724  $error++;
1725  } else {
1726  $new_task_id = $result_clone;
1727  $taskstatic->fetch($tasktoclone->id);
1728 
1729  //manage new parent clone task id
1730  // if the current task has child we store the original task id and the equivalent clone task id
1731  if (($taskstatic->hasChildren()) && !array_key_exists($tasktoclone->id, $tab_conv_child_parent)) {
1732  $tab_conv_child_parent[$tasktoclone->id] = $new_task_id;
1733  }
1734  }
1735  }
1736 
1737  //Parse all clone node to be sure to update new parent
1738  $tasksarray = $taskstatic->getTasksArray(0, 0, $clone_project_id, $socid, 0);
1739  foreach ($tasksarray as $task_cloned) {
1740  $taskstatic->fetch($task_cloned->id);
1741  if ($taskstatic->fk_task_parent != 0) {
1742  $taskstatic->fk_task_parent = $tab_conv_child_parent[$taskstatic->fk_task_parent];
1743  }
1744  $res = $taskstatic->update($user, $notrigger);
1745  if ($result_clone <= 0) {
1746  $this->error .= $taskstatic->error;
1747  $error++;
1748  }
1749  }
1750  }
1751  }
1752 
1753  unset($clone_project->context['createfromclone']);
1754 
1755  if (!$error) {
1756  $this->db->commit();
1757  return $clone_project_id;
1758  } else {
1759  $this->db->rollback();
1760  dol_syslog(get_class($this)."::createFromClone nbError: ".$error." error : ".$this->error, LOG_ERR);
1761  return -1;
1762  }
1763  }
1764 
1765 
1772  public function shiftTaskDate($old_project_dt_start)
1773  {
1774  global $user, $langs, $conf;
1775 
1776  $error = 0;
1777  $result = 0;
1778 
1779  $taskstatic = new Task($this->db);
1780 
1781  // Security check
1782  $socid = 0;
1783  if ($user->socid > 0) {
1784  $socid = $user->socid;
1785  }
1786 
1787  $tasksarray = $taskstatic->getTasksArray(0, 0, $this->id, $socid, 0);
1788 
1789  foreach ($tasksarray as $tasktoshiftdate) {
1790  $to_update = false;
1791  // Fetch only if update of date will be made
1792  if ((!empty($tasktoshiftdate->date_start)) || (!empty($tasktoshiftdate->date_end))) {
1793  //dol_syslog(get_class($this)."::shiftTaskDate to_update", LOG_DEBUG);
1794  $to_update = true;
1795  $task = new Task($this->db);
1796  $result = $task->fetch($tasktoshiftdate->id);
1797  if (!$result) {
1798  $error++;
1799  $this->error .= $task->error;
1800  }
1801  }
1802  //print "$this->date_start + $tasktoshiftdate->date_start - $old_project_dt_start";exit;
1803 
1804  //Calcultate new task start date with difference between old proj start date and origin task start date
1805  if (!empty($tasktoshiftdate->date_start)) {
1806  $task->date_start = $this->date_start + ($tasktoshiftdate->date_start - $old_project_dt_start);
1807  }
1808 
1809  //Calcultate new task end date with difference between origin proj end date and origin task end date
1810  if (!empty($tasktoshiftdate->date_end)) {
1811  $task->date_end = $this->date_start + ($tasktoshiftdate->date_end - $old_project_dt_start);
1812  }
1813 
1814  if ($to_update) {
1815  $result = $task->update($user);
1816  if (!$result) {
1817  $error++;
1818  $this->error .= $task->error;
1819  }
1820  }
1821  }
1822  if ($error != 0) {
1823  return -1;
1824  }
1825  return $result;
1826  }
1827 
1828 
1829  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1837  public function update_element($tableName, $elementSelectId)
1838  {
1839  // phpcs:enable
1840  $sql = "UPDATE ".MAIN_DB_PREFIX.$tableName;
1841 
1842  if ($tableName == "actioncomm") {
1843  $sql .= " SET fk_project=".$this->id;
1844  $sql .= " WHERE id=".((int) $elementSelectId);
1845  } elseif ($tableName == "entrepot") {
1846  $sql .= " SET fk_project=".$this->id;
1847  $sql .= " WHERE rowid=".((int) $elementSelectId);
1848  } else {
1849  $sql .= " SET fk_projet=".$this->id;
1850  $sql .= " WHERE rowid=".((int) $elementSelectId);
1851  }
1852 
1853  dol_syslog(get_class($this)."::update_element", LOG_DEBUG);
1854  $resql = $this->db->query($sql);
1855  if (!$resql) {
1856  $this->error = $this->db->lasterror();
1857  return -1;
1858  } else {
1859  return 1;
1860  }
1861  }
1862 
1863  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1873  public function remove_element($tableName, $elementSelectId, $projectfield = 'fk_projet')
1874  {
1875  // phpcs:enable
1876  $sql = "UPDATE ".MAIN_DB_PREFIX.$tableName;
1877 
1878  if ($tableName == "actioncomm") {
1879  $sql .= " SET fk_project=NULL";
1880  $sql .= " WHERE id=".((int) $elementSelectId);
1881  } else {
1882  $sql .= " SET ".$projectfield."=NULL";
1883  $sql .= " WHERE rowid=".((int) $elementSelectId);
1884  }
1885 
1886  dol_syslog(get_class($this)."::remove_element", LOG_DEBUG);
1887  $resql = $this->db->query($sql);
1888  if (!$resql) {
1889  $this->error = $this->db->lasterror();
1890  return -1;
1891  } else {
1892  return 1;
1893  }
1894  }
1895 
1906  public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0)
1907  {
1908  global $conf, $langs;
1909 
1910  $langs->load("projects");
1911 
1912  if (!dol_strlen($modele)) {
1913  $modele = 'baleine';
1914 
1915  if ($this->model_pdf) {
1916  $modele = $this->model_pdf;
1917  } elseif (!empty($conf->global->PROJECT_ADDON_PDF)) {
1918  $modele = $conf->global->PROJECT_ADDON_PDF;
1919  }
1920  }
1921 
1922  $modelpath = "core/modules/project/doc/";
1923 
1924  return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref);
1925  }
1926 
1927 
1937  public function loadTimeSpent($datestart, $taskid = 0, $userid = 0)
1938  {
1939  $error = 0;
1940 
1941  $this->weekWorkLoad = array();
1942  $this->weekWorkLoadPerTask = array();
1943 
1944  if (empty($datestart)) {
1945  dol_print_error('', 'Error datestart parameter is empty');
1946  }
1947 
1948  $sql = "SELECT ptt.rowid as taskid, ptt.task_duration, ptt.task_date, ptt.task_datehour, ptt.fk_task";
1949  $sql .= " FROM ".MAIN_DB_PREFIX."projet_task_time AS ptt, ".MAIN_DB_PREFIX."projet_task as pt";
1950  $sql .= " WHERE ptt.fk_task = pt.rowid";
1951  $sql .= " AND pt.fk_projet = ".((int) $this->id);
1952  $sql .= " AND (ptt.task_date >= '".$this->db->idate($datestart)."' ";
1953  $sql .= " AND ptt.task_date <= '".$this->db->idate(dol_time_plus_duree($datestart, 1, 'w') - 1)."')";
1954  if ($taskid) {
1955  $sql .= " AND ptt.fk_task=".((int) $taskid);
1956  }
1957  if (is_numeric($userid)) {
1958  $sql .= " AND ptt.fk_user=".((int) $userid);
1959  }
1960 
1961  //print $sql;
1962  $resql = $this->db->query($sql);
1963  if ($resql) {
1964  $daylareadyfound = array();
1965 
1966  $num = $this->db->num_rows($resql);
1967  $i = 0;
1968  // Loop on each record found, so each couple (project id, task id)
1969  while ($i < $num) {
1970  $obj = $this->db->fetch_object($resql);
1971  $day = $this->db->jdate($obj->task_date); // task_date is date without hours
1972  if (empty($daylareadyfound[$day])) {
1973  $this->weekWorkLoad[$day] = $obj->task_duration;
1974  $this->weekWorkLoadPerTask[$day][$obj->fk_task] = $obj->task_duration;
1975  } else {
1976  $this->weekWorkLoad[$day] += $obj->task_duration;
1977  $this->weekWorkLoadPerTask[$day][$obj->fk_task] += $obj->task_duration;
1978  }
1979  $daylareadyfound[$day] = 1;
1980  $i++;
1981  }
1982  $this->db->free($resql);
1983  return 1;
1984  } else {
1985  $this->error = "Error ".$this->db->lasterror();
1986  dol_syslog(get_class($this)."::fetch ".$this->error, LOG_ERR);
1987  return -1;
1988  }
1989  }
1990 
2000  public function loadTimeSpentMonth($datestart, $taskid = 0, $userid = 0)
2001  {
2002  $error = 0;
2003 
2004  $this->monthWorkLoad = array();
2005  $this->monthWorkLoadPerTask = array();
2006 
2007  if (empty($datestart)) {
2008  dol_print_error('', 'Error datestart parameter is empty');
2009  }
2010 
2011  $sql = "SELECT ptt.rowid as taskid, ptt.task_duration, ptt.task_date, ptt.task_datehour, ptt.fk_task";
2012  $sql .= " FROM ".MAIN_DB_PREFIX."projet_task_time AS ptt, ".MAIN_DB_PREFIX."projet_task as pt";
2013  $sql .= " WHERE ptt.fk_task = pt.rowid";
2014  $sql .= " AND pt.fk_projet = ".((int) $this->id);
2015  $sql .= " AND (ptt.task_date >= '".$this->db->idate($datestart)."' ";
2016  $sql .= " AND ptt.task_date <= '".$this->db->idate(dol_time_plus_duree($datestart, 1, 'm') - 1)."')";
2017  if ($task_id) {
2018  $sql .= " AND ptt.fk_task=".((int) $taskid);
2019  }
2020  if (is_numeric($userid)) {
2021  $sql .= " AND ptt.fk_user=".((int) $userid);
2022  }
2023 
2024  //print $sql;
2025  $resql = $this->db->query($sql);
2026  if ($resql) {
2027  $weekalreadyfound = array();
2028 
2029  $num = $this->db->num_rows($resql);
2030  $i = 0;
2031  // Loop on each record found, so each couple (project id, task id)
2032  while ($i < $num) {
2033  $obj = $this->db->fetch_object($resql);
2034  if (!empty($obj->task_date)) {
2035  $date = explode('-', $obj->task_date);
2036  $week_number = getWeekNumber($date[2], $date[1], $date[0]);
2037  }
2038  if (empty($weekalreadyfound[$week_number])) {
2039  $this->monthWorkLoad[$week_number] = $obj->task_duration;
2040  $this->monthWorkLoadPerTask[$week_number][$obj->fk_task] = $obj->task_duration;
2041  } else {
2042  $this->monthWorkLoad[$week_number] += $obj->task_duration;
2043  $this->monthWorkLoadPerTask[$week_number][$obj->fk_task] += $obj->task_duration;
2044  }
2045  $weekalreadyfound[$week_number] = 1;
2046  $i++;
2047  }
2048  $this->db->free($resql);
2049  return 1;
2050  } else {
2051  $this->error = "Error ".$this->db->lasterror();
2052  dol_syslog(get_class($this)."::fetch ".$this->error, LOG_ERR);
2053  return -1;
2054  }
2055  }
2056 
2057 
2058  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2065  public function load_board($user)
2066  {
2067  // phpcs:enable
2068  global $conf, $langs;
2069 
2070  // For external user, no check is done on company because readability is managed by public status of project and assignement.
2071  //$socid=$user->socid;
2072 
2073  $projectsListId = null;
2074  if (empty($user->rights->projet->all->lire)) {
2075  $projectsListId = $this->getProjectsAuthorizedForUser($user, 0, 1);
2076  }
2077 
2078  $sql = "SELECT p.rowid, p.fk_statut as status, p.fk_opp_status, p.datee as datee";
2079  $sql .= " FROM (".MAIN_DB_PREFIX."projet as p";
2080  $sql .= ")";
2081  $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s on p.fk_soc = s.rowid";
2082  // For external user, no check is done on company permission because readability is managed by public status of project and assignement.
2083  //if (! $user->rights->societe->client->voir && ! $socid) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON sc.fk_soc = s.rowid";
2084  $sql .= " WHERE p.fk_statut = 1";
2085  $sql .= " AND p.entity IN (".getEntity('project').')';
2086  if (!empty($projectsListId)) {
2087  $sql .= " AND p.rowid IN (".$this->db->sanitize($projectsListId).")";
2088  }
2089  // No need to check company, as filtering of projects must be done by getProjectsAuthorizedForUser
2090  //if ($socid || ! $user->rights->societe->client->voir) $sql.= " AND (p.fk_soc IS NULL OR p.fk_soc = 0 OR p.fk_soc = ".((int) $socid).")";
2091  // For external user, no check is done on company permission because readability is managed by public status of project and assignement.
2092  //if (! $user->rights->societe->client->voir && ! $socid) $sql.= " AND ((s.rowid = sc.fk_soc AND sc.fk_user = ".((int) $user->id).") OR (s.rowid IS NULL))";
2093 
2094  //print $sql;
2095  $resql = $this->db->query($sql);
2096  if ($resql) {
2097  $project_static = new Project($this->db);
2098 
2099  $response = new WorkboardResponse();
2100  $response->warning_delay = $conf->project->warning_delay / 60 / 60 / 24;
2101  $response->label = $langs->trans("OpenedProjects");
2102  $response->labelShort = $langs->trans("Opened");
2103  if ($user->rights->projet->all->lire) {
2104  $response->url = DOL_URL_ROOT.'/projet/list.php?search_status=1&mainmenu=project';
2105  } else {
2106  $response->url = DOL_URL_ROOT.'/projet/list.php?search_project_user=-1&search_status=1&mainmenu=project';
2107  }
2108  $response->img = img_object('', "projectpub");
2109 
2110  // This assignment in condition is not a bug. It allows walking the results.
2111  while ($obj = $this->db->fetch_object($resql)) {
2112  $response->nbtodo++;
2113 
2114  $project_static->statut = $obj->status;
2115  $project_static->opp_status = $obj->fk_opp_status;
2116  $project_static->date_end = $this->db->jdate($obj->datee);
2117 
2118  if ($project_static->hasDelay()) {
2119  $response->nbtodolate++;
2120  }
2121  }
2122 
2123  return $response;
2124  } else {
2125  $this->error = $this->db->error();
2126  return -1;
2127  }
2128  }
2129 
2130 
2139  public static function replaceThirdparty(DoliDB $db, $origin_id, $dest_id)
2140  {
2141  $tables = array(
2142  'projet'
2143  );
2144 
2145  return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables);
2146  }
2147 
2148 
2149  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2155  public function load_state_board()
2156  {
2157  // phpcs:enable
2158  global $user;
2159 
2160  $this->nb = array();
2161 
2162  $sql = "SELECT count(p.rowid) as nb";
2163  $sql .= " FROM ".MAIN_DB_PREFIX."projet as p";
2164  $sql .= " WHERE";
2165  $sql .= " p.entity IN (".getEntity('project').")";
2166  if (empty($user->rights->projet->all->lire)) {
2167  $projectsListId = $this->getProjectsAuthorizedForUser($user, 0, 1);
2168  $sql .= "AND p.rowid IN (".$this->db->sanitize($projectsListId).")";
2169  }
2170 
2171  $resql = $this->db->query($sql);
2172  if ($resql) {
2173  while ($obj = $this->db->fetch_object($resql)) {
2174  $this->nb["projects"] = $obj->nb;
2175  }
2176  $this->db->free($resql);
2177  return 1;
2178  } else {
2179  dol_print_error($this->db);
2180  $this->error = $this->db->error();
2181  return -1;
2182  }
2183  }
2184 
2185 
2191  public function hasDelay()
2192  {
2193  global $conf;
2194 
2195  if (!($this->statut == self::STATUS_VALIDATED)) {
2196  return false;
2197  }
2198  if (!$this->date_end) {
2199  return false;
2200  }
2201 
2202  $now = dol_now();
2203 
2204  return ($this->date_end) < ($now - $conf->project->warning_delay);
2205  }
2206 
2207 
2214  public function info($id)
2215  {
2216  $sql = 'SELECT c.rowid, datec as datec, tms as datem,';
2217  $sql .= ' date_close as datecloture,';
2218  $sql .= ' fk_user_creat as fk_user_author, fk_user_close as fk_use_cloture';
2219  $sql .= ' FROM '.MAIN_DB_PREFIX.'projet as c';
2220  $sql .= ' WHERE c.rowid = '.((int) $id);
2221  $result = $this->db->query($sql);
2222  if ($result) {
2223  if ($this->db->num_rows($result)) {
2224  $obj = $this->db->fetch_object($result);
2225  $this->id = $obj->rowid;
2226  if ($obj->fk_user_author) {
2227  $cuser = new User($this->db);
2228  $cuser->fetch($obj->fk_user_author);
2229  $this->user_creation = $cuser;
2230  }
2231 
2232  if ($obj->fk_user_cloture) {
2233  $cluser = new User($this->db);
2234  $cluser->fetch($obj->fk_user_cloture);
2235  $this->user_cloture = $cluser;
2236  }
2237 
2238  $this->date_creation = $this->db->jdate($obj->datec);
2239  $this->date_modification = $this->db->jdate($obj->datem);
2240  $this->date_cloture = $this->db->jdate($obj->datecloture);
2241  }
2242 
2243  $this->db->free($result);
2244  } else {
2245  dol_print_error($this->db);
2246  }
2247  }
2248 
2259  public function setCategories($categories)
2260  {
2261  require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
2262  return parent::setCategoriesCommon($categories, Categorie::TYPE_PROJECT);
2263  }
2264 
2265 
2272  public function getLinesArray($user)
2273  {
2274  require_once DOL_DOCUMENT_ROOT.'/projet/class/task.class.php';
2275  $taskstatic = new Task($this->db);
2276 
2277  $this->lines = $taskstatic->getTasksArray(0, $user, $this->id, 0, 0);
2278  }
2279 }
if(!function_exists('dol_getprefix')) dol_include_once($relpath, $classname= '')
Make an include_once using default root and alternate root if it fails.
dol_copy($srcfile, $destfile, $newmask=0, $overwriteifexists=1)
Copy a file to another file.
Definition: files.lib.php:702
load_state_board()
Charge indicateurs this-&gt;nb pour le tableau de bord.
dol_substr($string, $start, $length, $stringencoding= '', $trunconbytes=0)
Make a substring.
dol_mktime($hour, $minute, $second, $month, $day, $year, $gm= 'auto', $check=1)
Return a timestamp date built from detailed informations (by default a local PHP server timestamp) Re...
dol_mkdir($dir, $dataroot= '', $newmask= '')
Creation of a directory (this can create recursive subdir)
loadTimeSpentMonth($datestart, $taskid=0, $userid=0)
Load time spent into this-&gt;weekWorkLoad and this-&gt;weekWorkLoadPerTask for all day of a week of projec...
loadTimeSpent($datestart, $taskid=0, $userid=0)
Load time spent into this-&gt;weekWorkLoad and this-&gt;weekWorkLoadPerTask for all day of a week of projec...
$conf db
API class for accounts.
Definition: inc.php:41
getNomUrl($withpicto=0, $option= '', $addlabel=0, $moreinpopup= '', $sep= '- ', $notooltip=0, $save_lastsearch_value=-1, $morecss= '')
Return clickable name (with picto eventually)
initAsSpecimen()
Initialise an instance with random values.
dol_html_entity_decode($a, $b, $c= 'UTF-8', $keepsomeentities=0)
Replace html_entity_decode functions to manage errors.
dol_now($mode= 'auto')
Return date for now.
setCategories($categories)
Sets object to supplied categories.
delete_linked_contact($source= '', $code= '')
Delete all links between an object $this and all its contacts.
Class to manage Dolibarr users.
Definition: user.class.php:44
Class to manage Dolibarr database access.
deleteTasks($user)
Delete tasks with no children first, then task with children recursively.
commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams=null)
Common function for all objects extending CommonObject for generating documents.
hasDelay()
Is the project delayed?
const STATUS_CLOSED
Closed status.
load_board($user)
Load indicators for dashboard (this-&gt;nbtodo and this-&gt;nbtodolate)
dol_buildpath($path, $type=0, $returnemptyifnotfound=0)
Return path of url or filesystem.
dol_time_plus_duree($time, $duration_value, $duration_unit, $ruleforendofmonth=0)
Add a delay to a date.
Definition: date.lib.php:121
const STATUS_VALIDATED
Open/Validated status.
restrictedProjectArea(User $user, $mode= 'read')
Check if user has permission on current project.
insertExtraFields($trigger= '', $userused=null)
Add/Update all extra fields values for the current object.
getElementCount($type, $tablename, $projectkey= 'fk_projet')
Return the count of a type of linked elements of this project.
__construct($db)
Constructor.
shiftTaskDate($old_project_dt_start)
Shift project task date from current date to delta.
getEntity($element, $shared=1, $currentobject=null)
Get list of entity id to use.
getLinesArray($user)
Create an array of tasks of current project.
Class to manage projects.
dol_strlen($string, $stringencoding= 'UTF-8')
Make a strlen call.
price2num($amount, $rounding= '', $option=0)
Function that return a number with universal decimal format (decimal separator is &#39;...
info($id)
Charge les informations d&#39;ordre info dans l&#39;objet commande.
dol_delete_dir_recursive($dir, $count=0, $nophperrors=0, $onlysub=0, &$countdeleted=0, $indexdatabase=1, $nolog=0)
Remove a directory $dir and its subdirectories (or only files and subdirectories) ...
Definition: files.lib.php:1382
generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0)
Create an intervention document on disk using template defined into PROJECT_ADDON_PDF.
static commonReplaceThirdparty(DoliDB $db, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
Function used to replace a thirdparty id with another one.
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)
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename= '', $restricttologhandler= '', $logcontext=null)
Write log message into outputs.
img_object($titlealt, $picto, $moreatt= '', $pictoisfullpath=false, $srconly=0, $notitle=0)
Show a picto called object_picto (generic function)
$user_author_id
Id of project creator. Not defined if shared project.
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
get_element_list($type, $tablename, $datefieldname= '', $date_start= '', $date_end= '', $projectkey= 'fk_projet')
Return list of elements for type, linked to a project.
fetch_optionals($rowid=null, $optionsArray=null)
Function to get extra fields of an object into $this-&gt;array_options This method is in most cases call...
getWeekNumber($day, $month, $year)
Return week number.
Definition: date.lib.php:1133
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
remove_element($tableName, $elementSelectId, $projectfield= 'fk_projet')
Associate element to a project.
$public
Tell if this is a public or private project.
print *****$script_file(".$version.") pid cd cd cd description as description
Only used if Module[ID]Desc translation string is not found.
Class to manage tasks.
Definition: task.class.php:37
create($user, $notrigger=0)
Create a project into database.
dol_print_date($time, $format= '', $tzoutput= 'auto', $outputlangs= '', $encodetooutput=false)
Output date in a string format according to outputlangs (or langs if not defined).
$table_ref_field
{}
call_trigger($triggerName, $user)
Call trigger based on this instance.
getProjectsAuthorizedForUser($user, $mode=0, $list=0, $socid=0, $filter= '')
Return array of projects a user has permission on, is affected to, or all projects.
createFromClone(User $user, $fromid, $clone_contact=false, $clone_task=true, $clone_project_file=false, $clone_task_file=false, $clone_note=true, $move_date=true, $notrigger=0, $newthirdpartyid=0)
Load an object from its id and create a new one in database.
$object ref
Definition: info.php:77
update($user, $notrigger=0)
Update a project.
dol_print_error($db= '', $error= '', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
setValid($user, $notrigger=0)
Validate a project.
LibStatut($status, $mode=0)
Renvoi status label for a status.
isModEnabled($module)
Is Dolibarr module enabled.
update_element($tableName, $elementSelectId)
Associate element to a project.
dolGetStatus($statusLabel= '', $statusLabelShort= '', $html= '', $statusType= 'status0', $displayMode=0, $url= '', $params=array())
Output the badge of a status.
liste_contact($status=-1, $source= 'external', $list=0, $code= '')
Get array of all contacts for an object.
const STATUS_DRAFT
Draft status.
getLibStatut($mode=0)
Return status label of object.
Parent class of all other business classes (invoices, contracts, proposals, orders, ...)
setClose($user)
Close a project.
static replaceThirdparty(DoliDB $db, $origin_id, $dest_id)
Function used to replace a thirdparty id with another one.
fetch($id, $ref= '', $ref_ext= '', $email_msgid= '')
Get object from database.