dolibarr  16.0.5
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, 0);
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->entity = $conf->entity;
1351  $this->specimen = 1;
1352  $this->socid = 1;
1353  $this->date_c = $now;
1354  $this->date_m = $now;
1355  $this->date_start = $now;
1356  $this->date_end = $now + (3600 * 24 * 365);
1357  $this->note_public = 'SPECIMEN';
1358  $this->fk_ele = 20000;
1359  $this->opp_amount = 20000;
1360  $this->budget_amount = 10000;
1361 
1362  $this->usage_opportunity = 1;
1363  $this->usage_task = 1;
1364  $this->usage_bill_time = 1;
1365  $this->usage_organize_event = 1;
1366 
1367  /*
1368  $nbp = mt_rand(1, 9);
1369  $xnbp = 0;
1370  while ($xnbp < $nbp)
1371  {
1372  $line = new Task($this->db);
1373  $line->fk_project = 0;
1374  $line->label = $langs->trans("Label") . " " . $xnbp;
1375  $line->description = $langs->trans("Description") . " " . $xnbp;
1376 
1377  $this->lines[]=$line;
1378  $xnbp++;
1379  }
1380  */
1381  }
1382 
1390  public function restrictedProjectArea(User $user, $mode = 'read')
1391  {
1392  // To verify role of users
1393  $userAccess = 0;
1394  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))) {
1395  $userAccess = 1;
1396  } elseif ($this->public && (($mode == 'read' && !empty($user->rights->projet->lire)) || ($mode == 'write' && !empty($user->rights->projet->creer)) || ($mode == 'delete' && !empty($user->rights->projet->supprimer)))) {
1397  $userAccess = 1;
1398  } else { // No access due to permission to read all projects, so we check if we are a contact of project
1399  foreach (array('internal', 'external') as $source) {
1400  $userRole = $this->liste_contact(4, $source);
1401  $num = count($userRole);
1402 
1403  $nblinks = 0;
1404  while ($nblinks < $num) {
1405  if ($source == 'internal' && $user->id == $userRole[$nblinks]['id']) { // $userRole[$nblinks]['id'] is id of user (llx_user) for internal contacts
1406  if ($mode == 'read' && $user->rights->projet->lire) {
1407  $userAccess++;
1408  }
1409  if ($mode == 'write' && $user->rights->projet->creer) {
1410  $userAccess++;
1411  }
1412  if ($mode == 'delete' && $user->rights->projet->supprimer) {
1413  $userAccess++;
1414  }
1415  }
1416  if ($source == 'external' && $user->socid > 0 && $user->socid == $userRole[$nblinks]['socid']) { // $userRole[$nblinks]['id'] is id of contact (llx_socpeople) or external contacts
1417  if ($mode == 'read' && $user->rights->projet->lire) {
1418  $userAccess++;
1419  }
1420  if ($mode == 'write' && $user->rights->projet->creer) {
1421  $userAccess++;
1422  }
1423  if ($mode == 'delete' && $user->rights->projet->supprimer) {
1424  $userAccess++;
1425  }
1426  }
1427  $nblinks++;
1428  }
1429  }
1430  //if (empty($nblinks)) // If nobody has permission, we grant creator
1431  //{
1432  // if ((!empty($this->user_author_id) && $this->user_author_id == $user->id))
1433  // {
1434  // $userAccess = 1;
1435  // }
1436  //}
1437  }
1438 
1439  return ($userAccess ? $userAccess : -1);
1440  }
1441 
1452  public function getProjectsAuthorizedForUser($user, $mode = 0, $list = 0, $socid = 0, $filter = '')
1453  {
1454  $projects = array();
1455  $temp = array();
1456 
1457  $sql = "SELECT ".(($mode == 0 || $mode == 1) ? "DISTINCT " : "")."p.rowid, p.ref";
1458  $sql .= " FROM ".MAIN_DB_PREFIX."projet as p";
1459  if ($mode == 0) {
1460  $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."element_contact as ec ON ec.element_id = p.rowid";
1461  } elseif ($mode == 1) {
1462  $sql .= ", ".MAIN_DB_PREFIX."element_contact as ec";
1463  } elseif ($mode == 2) {
1464  // No filter. Use this if user has permission to see all project
1465  }
1466  $sql .= " WHERE p.entity IN (".getEntity('project').")";
1467  // Internal users must see project he is contact to even if project linked to a third party he can't see.
1468  //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).")";
1469  if ($socid > 0) {
1470  $sql .= " AND (p.fk_soc IS NULL OR p.fk_soc = 0 OR p.fk_soc = ".((int) $socid).")";
1471  }
1472 
1473  // Get id of types of contacts for projects (This list never contains a lot of elements)
1474  $listofprojectcontacttype = array();
1475  $sql2 = "SELECT ctc.rowid, ctc.code FROM ".MAIN_DB_PREFIX."c_type_contact as ctc";
1476  $sql2 .= " WHERE ctc.element = '".$this->db->escape($this->element)."'";
1477  $sql2 .= " AND ctc.source = 'internal'";
1478  $resql = $this->db->query($sql2);
1479  if ($resql) {
1480  while ($obj = $this->db->fetch_object($resql)) {
1481  $listofprojectcontacttype[$obj->rowid] = $obj->code;
1482  }
1483  } else {
1484  dol_print_error($this->db);
1485  }
1486  if (count($listofprojectcontacttype) == 0) {
1487  $listofprojectcontacttype[0] = '0'; // To avoid syntax error if not found
1488  }
1489 
1490  if ($mode == 0) {
1491  $sql .= " AND ( p.public = 1";
1492  $sql .= " OR ( ec.fk_c_type_contact IN (".$this->db->sanitize(join(',', array_keys($listofprojectcontacttype))).")";
1493  $sql .= " AND ec.fk_socpeople = ".((int) $user->id).")";
1494  $sql .= " )";
1495  } elseif ($mode == 1) {
1496  $sql .= " AND ec.element_id = p.rowid";
1497  $sql .= " AND (";
1498  $sql .= " ( ec.fk_c_type_contact IN (".$this->db->sanitize(join(',', array_keys($listofprojectcontacttype))).")";
1499  $sql .= " AND ec.fk_socpeople = ".((int) $user->id).")";
1500  $sql .= " )";
1501  } elseif ($mode == 2) {
1502  // No filter. Use this if user has permission to see all project
1503  }
1504 
1505  $sql .= $filter;
1506  //print $sql;
1507 
1508  $resql = $this->db->query($sql);
1509  if ($resql) {
1510  $num = $this->db->num_rows($resql);
1511  $i = 0;
1512  while ($i < $num) {
1513  $row = $this->db->fetch_row($resql);
1514  $projects[$row[0]] = $row[1];
1515  $temp[] = $row[0];
1516  $i++;
1517  }
1518 
1519  $this->db->free($resql);
1520 
1521  if ($list) {
1522  if (empty($temp)) {
1523  return '0';
1524  }
1525  $result = implode(',', $temp);
1526  return $result;
1527  }
1528  } else {
1529  dol_print_error($this->db);
1530  }
1531 
1532  return $projects;
1533  }
1534 
1550  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)
1551  {
1552  global $langs, $conf;
1553 
1554  $error = 0;
1555 
1556  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);
1557 
1558  $now = dol_mktime(0, 0, 0, idate('m', dol_now()), idate('d', dol_now()), idate('Y', dol_now()));
1559 
1560  $clone_project = new Project($this->db);
1561 
1562  $clone_project->context['createfromclone'] = 'createfromclone';
1563 
1564  $this->db->begin();
1565 
1566  // Load source object
1567  $clone_project->fetch($fromid);
1568  $clone_project->fetch_optionals();
1569  if ($newthirdpartyid > 0) {
1570  $clone_project->socid = $newthirdpartyid;
1571  }
1572  $clone_project->fetch_thirdparty();
1573 
1574  $orign_dt_start = $clone_project->date_start;
1575  $orign_project_ref = $clone_project->ref;
1576 
1577  $clone_project->id = 0;
1578  if ($move_date) {
1579  $clone_project->date_start = $now;
1580  if (!(empty($clone_project->date_end))) {
1581  $clone_project->date_end = $clone_project->date_end + ($now - $orign_dt_start);
1582  }
1583  }
1584 
1585  $clone_project->date_c = $now;
1586 
1587  if (!$clone_note) {
1588  $clone_project->note_private = '';
1589  $clone_project->note_public = '';
1590  }
1591 
1592  //Generate next ref
1593  $defaultref = '';
1594  $obj = empty($conf->global->PROJECT_ADDON) ? 'mod_project_simple' : $conf->global->PROJECT_ADDON;
1595  // Search template files
1596  $file = ''; $classname = ''; $filefound = 0;
1597  $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
1598  foreach ($dirmodels as $reldir) {
1599  $file = dol_buildpath($reldir."core/modules/project/".$obj.'.php', 0);
1600  if (file_exists($file)) {
1601  $filefound = 1;
1602  dol_include_once($reldir."core/modules/project/".$obj.'.php');
1603  $modProject = new $obj;
1604  $defaultref = $modProject->getNextValue(is_object($clone_project->thirdparty) ? $clone_project->thirdparty : null, $clone_project);
1605  break;
1606  }
1607  }
1608  if (is_numeric($defaultref) && $defaultref <= 0) {
1609  $defaultref = '';
1610  }
1611 
1612  $clone_project->ref = $defaultref;
1613  $clone_project->title = $langs->trans("CopyOf").' '.$clone_project->title;
1614 
1615  // Create clone
1616  $result = $clone_project->create($user, $notrigger);
1617 
1618  // Other options
1619  if ($result < 0) {
1620  $this->error .= $clone_project->error;
1621  $error++;
1622  }
1623 
1624  if (!$error) {
1625  //Get the new project id
1626  $clone_project_id = $clone_project->id;
1627 
1628  //Note Update
1629  if (!$clone_note) {
1630  $clone_project->note_private = '';
1631  $clone_project->note_public = '';
1632  } else {
1633  $this->db->begin();
1634  $res = $clone_project->update_note(dol_html_entity_decode($clone_project->note_public, ENT_QUOTES | ENT_HTML5), '_public');
1635  if ($res < 0) {
1636  $this->error .= $clone_project->error;
1637  $error++;
1638  $this->db->rollback();
1639  } else {
1640  $this->db->commit();
1641  }
1642 
1643  $this->db->begin();
1644  $res = $clone_project->update_note(dol_html_entity_decode($clone_project->note_private, ENT_QUOTES | ENT_HTML5), '_private');
1645  if ($res < 0) {
1646  $this->error .= $clone_project->error;
1647  $error++;
1648  $this->db->rollback();
1649  } else {
1650  $this->db->commit();
1651  }
1652  }
1653 
1654  //Duplicate contact
1655  if ($clone_contact) {
1656  $origin_project = new Project($this->db);
1657  $origin_project->fetch($fromid);
1658 
1659  foreach (array('internal', 'external') as $source) {
1660  $tab = $origin_project->liste_contact(-1, $source);
1661  if (is_array($tab) && count($tab)>0) {
1662  foreach ($tab as $contacttoadd) {
1663  $clone_project->add_contact($contacttoadd['id'], $contacttoadd['code'], $contacttoadd['source'], $notrigger);
1664  if ($clone_project->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
1665  $langs->load("errors");
1666  $this->error .= $langs->trans("ErrorThisContactIsAlreadyDefinedAsThisType");
1667  $error++;
1668  } else {
1669  if ($clone_project->error != '') {
1670  $this->error .= $clone_project->error;
1671  $error++;
1672  }
1673  }
1674  }
1675  } elseif ($tab < 0) {
1676  $this->error .= $origin_project->error;
1677  $error++;
1678  }
1679  }
1680  }
1681 
1682  //Duplicate file
1683  if ($clone_project_file) {
1684  require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
1685 
1686  $clone_project_dir = $conf->project->dir_output."/".dol_sanitizeFileName($defaultref);
1687  $ori_project_dir = $conf->project->dir_output."/".dol_sanitizeFileName($orign_project_ref);
1688 
1689  if (dol_mkdir($clone_project_dir) >= 0) {
1690  $filearray = dol_dir_list($ori_project_dir, "files", 0, '', '(\.meta|_preview.*\.png)$', '', SORT_ASC, 1);
1691  foreach ($filearray as $key => $file) {
1692  $rescopy = dol_copy($ori_project_dir.'/'.$file['name'], $clone_project_dir.'/'.$file['name'], 0, 1);
1693  if (is_numeric($rescopy) && $rescopy < 0) {
1694  $this->error .= $langs->trans("ErrorFailToCopyFile", $ori_project_dir.'/'.$file['name'], $clone_project_dir.'/'.$file['name']);
1695  $error++;
1696  }
1697  }
1698  } else {
1699  $this->error .= $langs->trans('ErrorInternalErrorDetected').':dol_mkdir';
1700  $error++;
1701  }
1702  }
1703 
1704  //Duplicate task
1705  if ($clone_task) {
1706  require_once DOL_DOCUMENT_ROOT.'/projet/class/task.class.php';
1707 
1708  $taskstatic = new Task($this->db);
1709 
1710  // Security check
1711  $socid = 0;
1712  if ($user->socid > 0) {
1713  $socid = $user->socid;
1714  }
1715 
1716  $tasksarray = $taskstatic->getTasksArray(0, 0, $fromid, $socid, 0);
1717 
1718  $tab_conv_child_parent = array();
1719 
1720  // Loop on each task, to clone it
1721  foreach ($tasksarray as $tasktoclone) {
1722  $result_clone = $taskstatic->createFromClone($user, $tasktoclone->id, $clone_project_id, $tasktoclone->fk_parent, $move_date, true, false, $clone_task_file, true, false);
1723  if ($result_clone <= 0) {
1724  $this->error .= $taskstatic->error;
1725  $error++;
1726  } else {
1727  $new_task_id = $result_clone;
1728  $taskstatic->fetch($tasktoclone->id);
1729 
1730  //manage new parent clone task id
1731  // if the current task has child we store the original task id and the equivalent clone task id
1732  if (($taskstatic->hasChildren()) && !array_key_exists($tasktoclone->id, $tab_conv_child_parent)) {
1733  $tab_conv_child_parent[$tasktoclone->id] = $new_task_id;
1734  }
1735  }
1736  }
1737 
1738  //Parse all clone node to be sure to update new parent
1739  $tasksarray = $taskstatic->getTasksArray(0, 0, $clone_project_id, $socid, 0);
1740  foreach ($tasksarray as $task_cloned) {
1741  $taskstatic->fetch($task_cloned->id);
1742  if ($taskstatic->fk_task_parent != 0) {
1743  $taskstatic->fk_task_parent = $tab_conv_child_parent[$taskstatic->fk_task_parent];
1744  }
1745  $res = $taskstatic->update($user, $notrigger);
1746  if ($result_clone <= 0) {
1747  $this->error .= $taskstatic->error;
1748  $error++;
1749  }
1750  }
1751  }
1752  }
1753 
1754  unset($clone_project->context['createfromclone']);
1755 
1756  if (!$error) {
1757  $this->db->commit();
1758  return $clone_project_id;
1759  } else {
1760  $this->db->rollback();
1761  dol_syslog(get_class($this)."::createFromClone nbError: ".$error." error : ".$this->error, LOG_ERR);
1762  return -1;
1763  }
1764  }
1765 
1766 
1773  public function shiftTaskDate($old_project_dt_start)
1774  {
1775  global $user, $langs, $conf;
1776 
1777  $error = 0;
1778  $result = 0;
1779 
1780  $taskstatic = new Task($this->db);
1781 
1782  // Security check
1783  $socid = 0;
1784  if ($user->socid > 0) {
1785  $socid = $user->socid;
1786  }
1787 
1788  $tasksarray = $taskstatic->getTasksArray(0, 0, $this->id, $socid, 0);
1789 
1790  foreach ($tasksarray as $tasktoshiftdate) {
1791  $to_update = false;
1792  // Fetch only if update of date will be made
1793  if ((!empty($tasktoshiftdate->date_start)) || (!empty($tasktoshiftdate->date_end))) {
1794  //dol_syslog(get_class($this)."::shiftTaskDate to_update", LOG_DEBUG);
1795  $to_update = true;
1796  $task = new Task($this->db);
1797  $result = $task->fetch($tasktoshiftdate->id);
1798  if (!$result) {
1799  $error++;
1800  $this->error .= $task->error;
1801  }
1802  }
1803  //print "$this->date_start + $tasktoshiftdate->date_start - $old_project_dt_start";exit;
1804 
1805  //Calcultate new task start date with difference between old proj start date and origin task start date
1806  if (!empty($tasktoshiftdate->date_start)) {
1807  $task->date_start = $this->date_start + ($tasktoshiftdate->date_start - $old_project_dt_start);
1808  }
1809 
1810  //Calcultate new task end date with difference between origin proj end date and origin task end date
1811  if (!empty($tasktoshiftdate->date_end)) {
1812  $task->date_end = $this->date_start + ($tasktoshiftdate->date_end - $old_project_dt_start);
1813  }
1814 
1815  if ($to_update) {
1816  $result = $task->update($user);
1817  if (!$result) {
1818  $error++;
1819  $this->error .= $task->error;
1820  }
1821  }
1822  }
1823  if ($error != 0) {
1824  return -1;
1825  }
1826  return $result;
1827  }
1828 
1829 
1830  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1838  public function update_element($tableName, $elementSelectId)
1839  {
1840  // phpcs:enable
1841  $sql = "UPDATE ".MAIN_DB_PREFIX.$tableName;
1842 
1843  if ($tableName == "actioncomm") {
1844  $sql .= " SET fk_project=".$this->id;
1845  $sql .= " WHERE id=".((int) $elementSelectId);
1846  } elseif ($tableName == "entrepot") {
1847  $sql .= " SET fk_project=".$this->id;
1848  $sql .= " WHERE rowid=".((int) $elementSelectId);
1849  } else {
1850  $sql .= " SET fk_projet=".$this->id;
1851  $sql .= " WHERE rowid=".((int) $elementSelectId);
1852  }
1853 
1854  dol_syslog(get_class($this)."::update_element", LOG_DEBUG);
1855  $resql = $this->db->query($sql);
1856  if (!$resql) {
1857  $this->error = $this->db->lasterror();
1858  return -1;
1859  } else {
1860  return 1;
1861  }
1862  }
1863 
1864  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1874  public function remove_element($tableName, $elementSelectId, $projectfield = 'fk_projet')
1875  {
1876  // phpcs:enable
1877  $sql = "UPDATE ".MAIN_DB_PREFIX.$tableName;
1878 
1879  if ($tableName == "actioncomm") {
1880  $sql .= " SET fk_project=NULL";
1881  $sql .= " WHERE id=".((int) $elementSelectId);
1882  } else {
1883  $sql .= " SET ".$projectfield."=NULL";
1884  $sql .= " WHERE rowid=".((int) $elementSelectId);
1885  }
1886 
1887  dol_syslog(get_class($this)."::remove_element", LOG_DEBUG);
1888  $resql = $this->db->query($sql);
1889  if (!$resql) {
1890  $this->error = $this->db->lasterror();
1891  return -1;
1892  } else {
1893  return 1;
1894  }
1895  }
1896 
1907  public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0)
1908  {
1909  global $conf, $langs;
1910 
1911  $langs->load("projects");
1912 
1913  if (!dol_strlen($modele)) {
1914  $modele = 'baleine';
1915 
1916  if ($this->model_pdf) {
1917  $modele = $this->model_pdf;
1918  } elseif (!empty($conf->global->PROJECT_ADDON_PDF)) {
1919  $modele = $conf->global->PROJECT_ADDON_PDF;
1920  }
1921  }
1922 
1923  $modelpath = "core/modules/project/doc/";
1924 
1925  return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref);
1926  }
1927 
1928 
1938  public function loadTimeSpent($datestart, $taskid = 0, $userid = 0)
1939  {
1940  $error = 0;
1941 
1942  $this->weekWorkLoad = array();
1943  $this->weekWorkLoadPerTask = array();
1944 
1945  if (empty($datestart)) {
1946  dol_print_error('', 'Error datestart parameter is empty');
1947  }
1948 
1949  $sql = "SELECT ptt.rowid as taskid, ptt.task_duration, ptt.task_date, ptt.task_datehour, ptt.fk_task";
1950  $sql .= " FROM ".MAIN_DB_PREFIX."projet_task_time AS ptt, ".MAIN_DB_PREFIX."projet_task as pt";
1951  $sql .= " WHERE ptt.fk_task = pt.rowid";
1952  $sql .= " AND pt.fk_projet = ".((int) $this->id);
1953  $sql .= " AND (ptt.task_date >= '".$this->db->idate($datestart)."' ";
1954  $sql .= " AND ptt.task_date <= '".$this->db->idate(dol_time_plus_duree($datestart, 1, 'w') - 1)."')";
1955  if ($taskid) {
1956  $sql .= " AND ptt.fk_task=".((int) $taskid);
1957  }
1958  if (is_numeric($userid)) {
1959  $sql .= " AND ptt.fk_user=".((int) $userid);
1960  }
1961 
1962  //print $sql;
1963  $resql = $this->db->query($sql);
1964  if ($resql) {
1965  $daylareadyfound = array();
1966 
1967  $num = $this->db->num_rows($resql);
1968  $i = 0;
1969  // Loop on each record found, so each couple (project id, task id)
1970  while ($i < $num) {
1971  $obj = $this->db->fetch_object($resql);
1972  $day = $this->db->jdate($obj->task_date); // task_date is date without hours
1973  if (empty($daylareadyfound[$day])) {
1974  $this->weekWorkLoad[$day] = $obj->task_duration;
1975  $this->weekWorkLoadPerTask[$day][$obj->fk_task] = $obj->task_duration;
1976  } else {
1977  $this->weekWorkLoad[$day] += $obj->task_duration;
1978  $this->weekWorkLoadPerTask[$day][$obj->fk_task] += $obj->task_duration;
1979  }
1980  $daylareadyfound[$day] = 1;
1981  $i++;
1982  }
1983  $this->db->free($resql);
1984  return 1;
1985  } else {
1986  $this->error = "Error ".$this->db->lasterror();
1987  dol_syslog(get_class($this)."::fetch ".$this->error, LOG_ERR);
1988  return -1;
1989  }
1990  }
1991 
2001  public function loadTimeSpentMonth($datestart, $taskid = 0, $userid = 0)
2002  {
2003  $error = 0;
2004 
2005  $this->monthWorkLoad = array();
2006  $this->monthWorkLoadPerTask = array();
2007 
2008  if (empty($datestart)) {
2009  dol_print_error('', 'Error datestart parameter is empty');
2010  }
2011 
2012  $sql = "SELECT ptt.rowid as taskid, ptt.task_duration, ptt.task_date, ptt.task_datehour, ptt.fk_task";
2013  $sql .= " FROM ".MAIN_DB_PREFIX."projet_task_time AS ptt, ".MAIN_DB_PREFIX."projet_task as pt";
2014  $sql .= " WHERE ptt.fk_task = pt.rowid";
2015  $sql .= " AND pt.fk_projet = ".((int) $this->id);
2016  $sql .= " AND (ptt.task_date >= '".$this->db->idate($datestart)."' ";
2017  $sql .= " AND ptt.task_date <= '".$this->db->idate(dol_time_plus_duree($datestart, 1, 'm') - 1)."')";
2018  if ($task_id) {
2019  $sql .= " AND ptt.fk_task=".((int) $taskid);
2020  }
2021  if (is_numeric($userid)) {
2022  $sql .= " AND ptt.fk_user=".((int) $userid);
2023  }
2024 
2025  //print $sql;
2026  $resql = $this->db->query($sql);
2027  if ($resql) {
2028  $weekalreadyfound = array();
2029 
2030  $num = $this->db->num_rows($resql);
2031  $i = 0;
2032  // Loop on each record found, so each couple (project id, task id)
2033  while ($i < $num) {
2034  $obj = $this->db->fetch_object($resql);
2035  if (!empty($obj->task_date)) {
2036  $date = explode('-', $obj->task_date);
2037  $week_number = getWeekNumber($date[2], $date[1], $date[0]);
2038  }
2039  if (empty($weekalreadyfound[$week_number])) {
2040  $this->monthWorkLoad[$week_number] = $obj->task_duration;
2041  $this->monthWorkLoadPerTask[$week_number][$obj->fk_task] = $obj->task_duration;
2042  } else {
2043  $this->monthWorkLoad[$week_number] += $obj->task_duration;
2044  $this->monthWorkLoadPerTask[$week_number][$obj->fk_task] += $obj->task_duration;
2045  }
2046  $weekalreadyfound[$week_number] = 1;
2047  $i++;
2048  }
2049  $this->db->free($resql);
2050  return 1;
2051  } else {
2052  $this->error = "Error ".$this->db->lasterror();
2053  dol_syslog(get_class($this)."::fetch ".$this->error, LOG_ERR);
2054  return -1;
2055  }
2056  }
2057 
2058 
2059  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2066  public function load_board($user)
2067  {
2068  // phpcs:enable
2069  global $conf, $langs;
2070 
2071  // For external user, no check is done on company because readability is managed by public status of project and assignement.
2072  //$socid=$user->socid;
2073 
2074  $projectsListId = null;
2075  if (empty($user->rights->projet->all->lire)) {
2076  $projectsListId = $this->getProjectsAuthorizedForUser($user, 0, 1);
2077  }
2078 
2079  $sql = "SELECT p.rowid, p.fk_statut as status, p.fk_opp_status, p.datee as datee";
2080  $sql .= " FROM (".MAIN_DB_PREFIX."projet as p";
2081  $sql .= ")";
2082  $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s on p.fk_soc = s.rowid";
2083  // For external user, no check is done on company permission because readability is managed by public status of project and assignement.
2084  //if (! $user->rights->societe->client->voir && ! $socid) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON sc.fk_soc = s.rowid";
2085  $sql .= " WHERE p.fk_statut = 1";
2086  $sql .= " AND p.entity IN (".getEntity('project').')';
2087  if (!empty($projectsListId)) {
2088  $sql .= " AND p.rowid IN (".$this->db->sanitize($projectsListId).")";
2089  }
2090  // No need to check company, as filtering of projects must be done by getProjectsAuthorizedForUser
2091  //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).")";
2092  // For external user, no check is done on company permission because readability is managed by public status of project and assignement.
2093  //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))";
2094 
2095  //print $sql;
2096  $resql = $this->db->query($sql);
2097  if ($resql) {
2098  $project_static = new Project($this->db);
2099 
2100  $response = new WorkboardResponse();
2101  $response->warning_delay = $conf->project->warning_delay / 60 / 60 / 24;
2102  $response->label = $langs->trans("OpenedProjects");
2103  $response->labelShort = $langs->trans("Opened");
2104  if ($user->rights->projet->all->lire) {
2105  $response->url = DOL_URL_ROOT.'/projet/list.php?search_status=1&mainmenu=project';
2106  } else {
2107  $response->url = DOL_URL_ROOT.'/projet/list.php?search_project_user=-1&search_status=1&mainmenu=project';
2108  }
2109  $response->img = img_object('', "projectpub");
2110 
2111  // This assignment in condition is not a bug. It allows walking the results.
2112  while ($obj = $this->db->fetch_object($resql)) {
2113  $response->nbtodo++;
2114 
2115  $project_static->statut = $obj->status;
2116  $project_static->opp_status = $obj->fk_opp_status;
2117  $project_static->date_end = $this->db->jdate($obj->datee);
2118 
2119  if ($project_static->hasDelay()) {
2120  $response->nbtodolate++;
2121  }
2122  }
2123 
2124  return $response;
2125  } else {
2126  $this->error = $this->db->error();
2127  return -1;
2128  }
2129  }
2130 
2131 
2140  public static function replaceThirdparty(DoliDB $db, $origin_id, $dest_id)
2141  {
2142  $tables = array(
2143  'projet'
2144  );
2145 
2146  return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables);
2147  }
2148 
2149 
2150  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2156  public function load_state_board()
2157  {
2158  // phpcs:enable
2159  global $user;
2160 
2161  $this->nb = array();
2162 
2163  $sql = "SELECT count(p.rowid) as nb";
2164  $sql .= " FROM ".MAIN_DB_PREFIX."projet as p";
2165  $sql .= " WHERE";
2166  $sql .= " p.entity IN (".getEntity('project').")";
2167  if (empty($user->rights->projet->all->lire)) {
2168  $projectsListId = $this->getProjectsAuthorizedForUser($user, 0, 1);
2169  $sql .= "AND p.rowid IN (".$this->db->sanitize($projectsListId).")";
2170  }
2171 
2172  $resql = $this->db->query($sql);
2173  if ($resql) {
2174  while ($obj = $this->db->fetch_object($resql)) {
2175  $this->nb["projects"] = $obj->nb;
2176  }
2177  $this->db->free($resql);
2178  return 1;
2179  } else {
2180  dol_print_error($this->db);
2181  $this->error = $this->db->error();
2182  return -1;
2183  }
2184  }
2185 
2186 
2192  public function hasDelay()
2193  {
2194  global $conf;
2195 
2196  if (!($this->statut == self::STATUS_VALIDATED)) {
2197  return false;
2198  }
2199  if (!$this->date_end) {
2200  return false;
2201  }
2202 
2203  $now = dol_now();
2204 
2205  return ($this->date_end) < ($now - $conf->project->warning_delay);
2206  }
2207 
2208 
2215  public function info($id)
2216  {
2217  $sql = 'SELECT c.rowid, datec as datec, tms as datem,';
2218  $sql .= ' date_close as datecloture,';
2219  $sql .= ' fk_user_creat as fk_user_author, fk_user_close as fk_use_cloture';
2220  $sql .= ' FROM '.MAIN_DB_PREFIX.'projet as c';
2221  $sql .= ' WHERE c.rowid = '.((int) $id);
2222  $result = $this->db->query($sql);
2223  if ($result) {
2224  if ($this->db->num_rows($result)) {
2225  $obj = $this->db->fetch_object($result);
2226  $this->id = $obj->rowid;
2227  if ($obj->fk_user_author) {
2228  $cuser = new User($this->db);
2229  $cuser->fetch($obj->fk_user_author);
2230  $this->user_creation = $cuser;
2231  }
2232 
2233  if ($obj->fk_user_cloture) {
2234  $cluser = new User($this->db);
2235  $cluser->fetch($obj->fk_user_cloture);
2236  $this->user_cloture = $cluser;
2237  }
2238 
2239  $this->date_creation = $this->db->jdate($obj->datec);
2240  $this->date_modification = $this->db->jdate($obj->datem);
2241  $this->date_cloture = $this->db->jdate($obj->datecloture);
2242  }
2243 
2244  $this->db->free($result);
2245  } else {
2246  dol_print_error($this->db);
2247  }
2248  }
2249 
2260  public function setCategories($categories)
2261  {
2262  require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
2263  return parent::setCategoriesCommon($categories, Categorie::TYPE_PROJECT);
2264  }
2265 
2266 
2274  public function getLinesArray($user, $loadRoleMode = 1)
2275  {
2276  require_once DOL_DOCUMENT_ROOT.'/projet/class/task.class.php';
2277  $taskstatic = new Task($this->db);
2278 
2279  $this->lines = $taskstatic->getTasksArray(0, $user, $this->id, 0, 0, '', '-1', '', 0, 0, array(), 0, array(), 0, $loadRoleMode);
2280  }
2281 }
Project\getNomUrl
getNomUrl($withpicto=0, $option='', $addlabel=0, $moreinpopup='', $sep=' - ', $notooltip=0, $save_lastsearch_value=-1, $morecss='')
Return clickable name (with picto eventually)
Definition: project.class.php:1226
CommonObject\liste_contact
liste_contact($status=-1, $source='external', $list=0, $code='')
Get array of all contacts for an object.
Definition: commonobject.class.php:1362
db
$conf db
API class for accounts.
Definition: inc.php:41
Project\createFromClone
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.
Definition: project.class.php:1550
Project\loadTimeSpentMonth
loadTimeSpentMonth($datestart, $taskid=0, $userid=0)
Load time spent into this->weekWorkLoad and this->weekWorkLoadPerTask for all day of a week of projec...
Definition: project.class.php:2001
dol_sanitizeFileName
dol_sanitizeFileName($str, $newstr='_', $unaccent=1)
Clean a string to use it as a file name.
Definition: functions.lib.php:1226
description
print *****$script_file(".$version.") pid cd cd cd description as description
Definition: email_expire_services_to_customers.php:83
Project
Class to manage projects.
Definition: project.class.php:35
Project\getProjectsAuthorizedForUser
getProjectsAuthorizedForUser($user, $mode=0, $list=0, $socid=0, $filter='')
Return array of projects a user has permission on, is affected to, or all projects.
Definition: project.class.php:1452
Project\__construct
__construct($db)
Constructor.
Definition: project.class.php:315
Project\getLinesArray
getLinesArray($user, $loadRoleMode=1)
Create an array of tasks of current project.
Definition: project.class.php:2274
Project\$user_author_id
$user_author_id
Id of project creator. Not defined if shared project.
Definition: project.class.php:121
getWeekNumber
getWeekNumber($day, $month, $year)
Return week number.
Definition: date.lib.php:1134
dol_delete_dir_recursive
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:1383
DoliDB
Class to manage Dolibarr database access.
Definition: DoliDB.class.php:30
dol_substr
dol_substr($string, $start, $length, $stringencoding='', $trunconbytes=0)
Make a substring.
Definition: functions.lib.php:3766
Project\hasDelay
hasDelay()
Is the project delayed?
Definition: project.class.php:2192
Project\getElementCount
getElementCount($type, $tablename, $projectkey='fk_projet')
Return the count of a type of linked elements of this project.
Definition: project.class.php:995
dol_print_error
dol_print_error($db='', $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
Definition: functions.lib.php:4844
Project\loadTimeSpent
loadTimeSpent($datestart, $taskid=0, $userid=0)
Load time spent into this->weekWorkLoad and this->weekWorkLoadPerTask for all day of a week of projec...
Definition: project.class.php:1938
dol_include_once
if(!function_exists('dol_getprefix')) dol_include_once($relpath, $classname='')
Make an include_once using default root and alternate root if it fails.
Definition: functions.lib.php:1033
dol_buildpath
dol_buildpath($path, $type=0, $returnemptyifnotfound=0)
Return path of url or filesystem.
Definition: functions.lib.php:1062
Project\getLibStatut
getLibStatut($mode=0)
Return status label of object.
Definition: project.class.php:1181
Project\remove_element
remove_element($tableName, $elementSelectId, $projectfield='fk_projet')
Associate element to a project.
Definition: project.class.php:1874
Task
Class to manage tasks.
Definition: task.class.php:37
ref
$object ref
Definition: info.php:77
Project\LibStatut
LibStatut($status, $mode=0)
Renvoi status label for a status.
Definition: project.class.php:1194
dol_dir_list
dol_dir_list($path, $types="all", $recursive=0, $filter="", $excludefilter=null, $sortcriteria="name", $sortorder=SORT_ASC, $mode=0, $nohook=0, $relativename="", $donotfollowsymlinks=0)
Scan a directory and return a list of files/directories.
Definition: files.lib.php:60
CommonObject
Parent class of all other business classes (invoices, contracts, proposals, orders,...
Definition: commonobject.class.php:44
Project\$public
$public
Tell if this is a public or private project.
Definition: project.class.php:132
Project\info
info($id)
Charge les informations d'ordre info dans l'objet commande.
Definition: project.class.php:2215
price2num
price2num($amount, $rounding='', $option=0)
Function that return a number with universal decimal format (decimal separator is '.
Definition: functions.lib.php:5661
dol_print_date
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs='', $encodetooutput=false)
Output date in a string format according to outputlangs (or langs if not defined).
Definition: functions.lib.php:2514
WorkboardResponse
Definition: workboardresponse.class.php:25
img_picto
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=false, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2)
Show picto whatever it's its name (generic function)
Definition: functions.lib.php:3880
CommonObject\commonGenerateDocument
commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams=null)
Common function for all objects extending CommonObject for generating documents.
Definition: commonobject.class.php:5406
Project\update
update($user, $notrigger=0)
Update a project.
Definition: project.class.php:496
Project\load_state_board
load_state_board()
Charge indicateurs this->nb pour le tableau de bord.
Definition: project.class.php:2156
dol_copy
dol_copy($srcfile, $destfile, $newmask=0, $overwriteifexists=1)
Copy a file to another file.
Definition: files.lib.php:703
getEntity
getEntity($element, $shared=1, $currentobject=null)
Get list of entity id to use.
Definition: functions.lib.php:148
Project\initAsSpecimen
initAsSpecimen()
Initialise an instance with random values.
Definition: project.class.php:1341
CommonObject\insertExtraFields
insertExtraFields($trigger='', $userused=null)
Add/Update all extra fields values for the current object.
Definition: commonobject.class.php:6156
CommonObject\delete_linked_contact
delete_linked_contact($source='', $code='')
Delete all links between an object $this and all its contacts in llx_element_contact.
Definition: commonobject.class.php:1319
Project\setValid
setValid($user, $notrigger=0)
Validate a project.
Definition: project.class.php:1069
Project\generateDocument
generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0)
Create an intervention document on disk using template defined into PROJECT_ADDON_PDF.
Definition: project.class.php:1907
CommonObject\commonReplaceThirdparty
static commonReplaceThirdparty(DoliDB $db, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
Function used to replace a thirdparty id with another one.
Definition: commonobject.class.php:8347
dol_syslog
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
Definition: functions.lib.php:1603
CommonObject\fetch_optionals
fetch_optionals($rowid=null, $optionsArray=null)
Function to get extra fields of an object into $this->array_options This method is in most cases call...
Definition: commonobject.class.php:6007
dol_strlen
dol_strlen($string, $stringencoding='UTF-8')
Make a strlen call.
Definition: functions.lib.php:3747
Project\get_element_list
get_element_list($type, $tablename, $datefieldname='', $date_start='', $date_end='', $projectkey='fk_projet')
Return list of elements for type, linked to a project.
Definition: project.class.php:728
Project\shiftTaskDate
shiftTaskDate($old_project_dt_start)
Shift project task date from current date to delta.
Definition: project.class.php:1773
Project\create
create($user, $notrigger=0)
Create a project into database.
Definition: project.class.php:359
isModEnabled
isModEnabled($module)
Is Dolibarr module enabled.
Definition: functions.lib.php:105
Project\deleteTasks
deleteTasks($user)
Delete tasks with no children first, then task with children recursively.
Definition: project.class.php:1036
dol_time_plus_duree
dol_time_plus_duree($time, $duration_value, $duration_unit, $ruleforendofmonth=0)
Add a delay to a date.
Definition: date.lib.php:121
User
Class to manage Dolibarr users.
Definition: user.class.php:44
Project\STATUS_VALIDATED
const STATUS_VALIDATED
Open/Validated status.
Definition: project.class.php:303
dol_html_entity_decode
dol_html_entity_decode($a, $b, $c='UTF-8', $keepsomeentities=0)
Replace html_entity_decode functions to manage errors.
Definition: functions.lib.php:7052
Project\update_element
update_element($tableName, $elementSelectId)
Associate element to a project.
Definition: project.class.php:1838
dolGetStatus
dolGetStatus($statusLabel='', $statusLabelShort='', $html='', $statusType='status0', $displayMode=0, $url='', $params=array())
Output the badge of a status.
Definition: functions.lib.php:10338
img_object
img_object($titlealt, $picto, $moreatt='', $pictoisfullpath=false, $srconly=0, $notitle=0)
Show a picto called object_picto (generic function)
Definition: functions.lib.php:4211
Project\setCategories
setCategories($categories)
Sets object to supplied categories.
Definition: project.class.php:2260
dol_now
dol_now($mode='auto')
Return date for now.
Definition: functions.lib.php:2845
$resql
if(isModEnabled('facture') &&!empty($user->rights->facture->lire)) if((isModEnabled('fournisseur') &&empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) && $user->rights->fournisseur->facture->lire)||(isModEnabled('supplier_invoice') && $user->rights->supplier_invoice->lire)) if(isModEnabled('don') &&!empty($user->rights->don->lire)) if(isModEnabled('tax') &&!empty($user->rights->tax->charges->lire)) if(isModEnabled('facture') &&isModEnabled('commande') && $user->rights->commande->lire &&empty($conf->global->WORKFLOW_DISABLE_CREATE_INVOICE_FROM_ORDER)) $resql
Social contributions to pay.
Definition: index.php:742
Project\STATUS_CLOSED
const STATUS_CLOSED
Closed status.
Definition: project.class.php:308
CommonObject\call_trigger
call_trigger($triggerName, $user)
Call trigger based on this instance.
Definition: commonobject.class.php:5791
Project\$table_ref_field
$table_ref_field
{}
Definition: project.class.php:77
Project\fetch
fetch($id, $ref='', $ref_ext='', $email_msgid='')
Get object from database.
Definition: project.class.php:624
dol_mkdir
dol_mkdir($dir, $dataroot='', $newmask='')
Creation of a directory (this can create recursive subdir)
Definition: functions.lib.php:6603
dol_mktime
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...
Definition: functions.lib.php:2757
Project\STATUS_DRAFT
const STATUS_DRAFT
Draft status.
Definition: project.class.php:298
Project\setClose
setClose($user)
Close a project.
Definition: project.class.php:1125
Project\replaceThirdparty
static replaceThirdparty(DoliDB $db, $origin_id, $dest_id)
Function used to replace a thirdparty id with another one.
Definition: project.class.php:2140
Project\load_board
load_board($user)
Load indicators for dashboard (this->nbtodo and this->nbtodolate)
Definition: project.class.php:2066
Project\restrictedProjectArea
restrictedProjectArea(User $user, $mode='read')
Check if user has permission on current project.
Definition: project.class.php:1390