dolibarr 21.0.0-alpha
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 * Copyright (C) 2023 Gauthier VERDOL <gauthier.verdol@atm-consulting.fr>
11 * Copyright (C) 2024 Frédéric France <frederic.france@free.fr>
12 * Copyright (C) 2024 MDW <mdeweerd@users.noreply.github.com>
13 *
14 * This program is free software; you can redistribute it and/or modify
15 * it under the terms of the GNU General Public License as published by
16 * the Free Software Foundation; either version 3 of the License, or
17 * (at your option) any later version.
18 *
19 * This program is distributed in the hope that it will be useful,
20 * but WITHOUT ANY WARRANTY; without even the implied warranty of
21 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 * GNU General Public License for more details.
23 *
24 * You should have received a copy of the GNU General Public License
25 * along with this program. If not, see <https://www.gnu.org/licenses/>.
26 */
27
33require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
34
38class Project extends CommonObject
39{
43 public $element = 'project';
44
48 public $table_element = 'projet';
49
53 public $table_element_line = 'projet_task';
54
58 public $table_element_date;
59
63 public $fk_element = 'fk_projet';
64
68 public $picto = 'project';
69
73 protected $table_ref_field = 'ref';
74
78 public $fk_project;
79
83 public $description;
84
88 public $title;
89
95 public $dateo;
96
100 public $date_start;
101
107 public $datee;
108
112 public $date_end;
113
117 public $date_start_event;
118
122 public $date_end_event;
123
127 public $location;
128
132 public $date_close;
133
134 public $socid; // To store id of thirdparty
135
139 public $thirdparty_name; // To store name of thirdparty (defined only in some cases)
140
142
146 public $fk_user_close;
147
148 public $public;
149
153 public $budget_amount;
154
158 public $usage_opportunity;
159
163 public $usage_task;
164
168 public $usage_bill_time; // Is the time spent on project must be invoiced or not
169
173 public $usage_organize_event;
174
178 public $accept_conference_suggestions;
179
183 public $accept_booth_suggestions;
184
188 public $price_registration;
189
193 public $price_booth;
194
198 public $max_attendees;
199
205 public $statut; // 0=draft, 1=opened, 2=closed
206
210 public $opp_status; // opportunity status, into table llx_c_lead_status
211
215 public $opp_status_code;
216
220 public $fk_opp_status; // opportunity status, into table llx_c_lead_status
221
225 public $opp_amount; // opportunity amount
226
230 public $opp_percent; // opportunity probability
231
235 public $opp_weighted_amount; // opportunity weighted amount
236
240 public $email_msgid;
241
242 public $oldcopy;
243
244 public $weekWorkLoad; // Used to store workload details of a projet
245 public $weekWorkLoadPerTask; // Used to store workload details of tasks of a projet
246
250 public $monthWorkLoad;
251
255 public $monthWorkLoadPerTask;
256
262 public $datec;
263
267 public $date_c;
268
274 public $datem;
275
279 public $date_m;
280
284 public $ip;
285
289 public $lines;
290
331 // BEGIN MODULEBUILDER PROPERTIES
335 public $fields = array(
336 'rowid' => array('type' => 'integer', 'label' => 'ID', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 10),
337 'fk_project' => array('type' => 'integer', 'label' => 'Parent', 'enabled' => 1, 'visible' => 1, 'notnull' => 0, 'position' => 12),
338 'ref' => array('type' => 'varchar(50)', 'label' => 'Ref', 'enabled' => 1, 'visible' => 1, 'showoncombobox' => 1, 'position' => 15, 'searchall' => 1),
339 'title' => array('type' => 'varchar(255)', 'label' => 'ProjectLabel', 'enabled' => 1, 'visible' => 1, 'notnull' => 1, 'position' => 17, 'showoncombobox' => 2, 'searchall' => 1),
340 'entity' => array('type' => 'integer', 'label' => 'Entity', 'default' => '1', 'enabled' => 1, 'visible' => 3, 'notnull' => 1, 'position' => 19),
341 'fk_soc' => array('type' => 'integer', 'label' => 'Thirdparty', 'enabled' => 1, 'visible' => 0, 'position' => 20),
342 'dateo' => array('type' => 'date', 'label' => 'DateStart', 'enabled' => 1, 'visible' => -1, 'position' => 30),
343 'datee' => array('type' => 'date', 'label' => 'DateEnd', 'enabled' => 1, 'visible' => 1, 'position' => 35),
344 'description' => array('type' => 'text', 'label' => 'Description', 'enabled' => 1, 'visible' => 3, 'position' => 55, 'searchall' => 1),
345 'public' => array('type' => 'integer', 'label' => 'Visibility', 'enabled' => 1, 'visible' => -1, 'position' => 65),
346 'fk_opp_status' => array('type' => 'integer:CLeadStatus:core/class/cleadstatus.class.php', 'label' => 'OpportunityStatusShort', 'enabled' => 'getDolGlobalString("PROJECT_USE_OPPORTUNITIES")', 'visible' => 1, 'position' => 75),
347 'opp_percent' => array('type' => 'double(5,2)', 'label' => 'OpportunityProbabilityShort', 'enabled' => 'getDolGlobalString("PROJECT_USE_OPPORTUNITIES")', 'visible' => 1, 'position' => 80),
348 'note_private' => array('type' => 'html', 'label' => 'NotePrivate', 'enabled' => 1, 'visible' => 0, 'position' => 85, 'searchall' => 1),
349 'note_public' => array('type' => 'html', 'label' => 'NotePublic', 'enabled' => 1, 'visible' => 0, 'position' => 90, 'searchall' => 1),
350 'model_pdf' => array('type' => 'varchar(255)', 'label' => 'ModelPdf', 'enabled' => 1, 'visible' => 0, 'position' => 95),
351 'date_close' => array('type' => 'datetime', 'label' => 'DateClosing', 'enabled' => 1, 'visible' => 0, 'position' => 105),
352 'fk_user_close' => array('type' => 'integer', 'label' => 'UserClosing', 'enabled' => 1, 'visible' => 0, 'position' => 110),
353 'opp_amount' => array('type' => 'double(24,8)', 'label' => 'OpportunityAmountShort', 'enabled' => 1, 'visible' => 'getDolGlobalString("PROJECT_USE_OPPORTUNITIES")', 'position' => 115),
354 'budget_amount' => array('type' => 'double(24,8)', 'label' => 'Budget', 'enabled' => 1, 'visible' => -1, 'position' => 119),
355 'usage_opportunity' => array('type' => 'integer', 'label' => 'UsageOpportunity', 'enabled' => 1, 'visible' => -1, 'position' => 130),
356 'usage_task' => array('type' => 'integer', 'label' => 'UsageTasks', 'enabled' => 1, 'visible' => -1, 'position' => 135),
357 'usage_bill_time' => array('type' => 'integer', 'label' => 'UsageBillTimeShort', 'enabled' => 1, 'visible' => -1, 'position' => 140),
358 'usage_organize_event' => array('type' => 'integer', 'label' => 'UsageOrganizeEvent', 'enabled' => 1, 'visible' => -1, 'position' => 145),
359 // Properties for event organization
360 'date_start_event' => array('type' => 'date', 'label' => 'DateStartEvent', 'enabled' => "isModEnabled('eventorganization')", 'visible' => 1, 'position' => 200),
361 'date_end_event' => array('type' => 'date', 'label' => 'DateEndEvent', 'enabled' => "isModEnabled('eventorganization')", 'visible' => 1, 'position' => 201),
362 'location' => array('type' => 'text', 'label' => 'Location', 'enabled' => 1, 'visible' => 3, 'position' => 55, 'searchall' => 202),
363 'accept_conference_suggestions' => array('type' => 'integer', 'label' => 'AllowUnknownPeopleSuggestConf', 'enabled' => 1, 'visible' => -1, 'position' => 210),
364 'accept_booth_suggestions' => array('type' => 'integer', 'label' => 'AllowUnknownPeopleSuggestBooth', 'enabled' => 1, 'visible' => -1, 'position' => 211),
365 'price_registration' => array('type' => 'double(24,8)', 'label' => 'PriceOfRegistration', 'enabled' => 1, 'visible' => -1, 'position' => 212),
366 'price_booth' => array('type' => 'double(24,8)', 'label' => 'PriceOfBooth', 'enabled' => 1, 'visible' => -1, 'position' => 215),
367 'max_attendees' => array('type' => 'integer', 'label' => 'MaxNbOfAttendees', 'enabled' => 1, 'visible' => -1, 'position' => 215),
368 // Generic
369 'datec' => array('type' => 'datetime', 'label' => 'DateCreationShort', 'enabled' => 1, 'visible' => -2, 'position' => 400),
370 'tms' => array('type' => 'timestamp', 'label' => 'DateModificationShort', 'enabled' => 1, 'visible' => -2, 'notnull' => 1, 'position' => 405),
371 'fk_user_creat' => array('type' => 'integer', 'label' => 'UserCreation', 'enabled' => 1, 'visible' => 0, 'notnull' => 1, 'position' => 410),
372 'fk_user_modif' => array('type' => 'integer', 'label' => 'UserModification', 'enabled' => 1, 'visible' => 0, 'position' => 415),
373 'import_key' => array('type' => 'varchar(14)', 'label' => 'ImportId', 'enabled' => 1, 'visible' => -1, 'position' => 420),
374 'email_msgid' => array('type' => 'varchar(255)', 'label' => 'EmailMsgID', 'enabled' => 1, 'visible' => -1, 'position' => 450, 'help' => 'EmailMsgIDWhenSourceisEmail', 'csslist' => 'tdoverflowmax125'),
375 'fk_statut' => array('type' => 'smallint(6)', 'label' => 'Status', 'alias' => 'status', 'enabled' => 1, 'visible' => 1, 'notnull' => 1, 'position' => 500, 'arrayofkeyval' => array(0 => 'Draft', 1 => 'Validated', 2 => 'Closed')),
376 );
377 // END MODULEBUILDER PROPERTIES
378
382 const STATUS_DRAFT = 0;
383
388
392 const STATUS_CLOSED = 2;
393
394
400 public function __construct($db)
401 {
402 global $conf;
403
404 $this->db = $db;
405
406 $this->ismultientitymanaged = 1;
407 $this->isextrafieldmanaged = 1;
408
409 $this->labelStatusShort = array(0 => 'Draft', 1 => 'Opened', 2 => 'Closed');
410 $this->labelStatus = array(0 => 'Draft', 1 => 'Opened', 2 => 'Closed');
411
412 global $conf;
413
414 if (!getDolGlobalString('MAIN_SHOW_TECHNICAL_ID')) {
415 $this->fields['rowid']['visible'] = 0;
416 }
417
418 if (!getDolGlobalString('PROJECT_USE_OPPORTUNITIES')) {
419 $this->fields['fk_opp_status']['enabled'] = 0;
420 $this->fields['opp_percent']['enabled'] = 0;
421 $this->fields['opp_amount']['enabled'] = 0;
422 $this->fields['usage_opportunity']['enabled'] = 0;
423 }
424
425 if (getDolGlobalString('PROJECT_HIDE_TASKS')) {
426 $this->fields['usage_bill_time']['visible'] = 0;
427 $this->fields['usage_task']['visible'] = 0;
428 }
429
430 if (empty($conf->eventorganization->enabled)) {
431 $this->fields['usage_organize_event']['visible'] = 0;
432 $this->fields['accept_conference_suggestions']['enabled'] = 0;
433 $this->fields['accept_booth_suggestions']['enabled'] = 0;
434 $this->fields['price_registration']['enabled'] = 0;
435 $this->fields['price_booth']['enabled'] = 0;
436 $this->fields['max_attendees']['enabled'] = 0;
437 }
438 }
439
447 public function create($user, $notrigger = 0)
448 {
449 $error = 0;
450 $ret = 0;
451
452 $now = dol_now();
453
454 // Clean parameters
455 $this->note_private = dol_substr($this->note_private, 0, 65535);
456 $this->note_public = dol_substr($this->note_public, 0, 65535);
457
458 // Check parameters
459 if (!trim($this->ref)) {
460 $this->error = 'ErrorFieldsRequired';
461 dol_syslog(get_class($this)."::create error -1 ref null", LOG_ERR);
462 return -1;
463 }
464 if (getDolGlobalString('PROJECT_THIRDPARTY_REQUIRED') && !($this->socid > 0)) {
465 $this->error = 'ErrorFieldsRequired';
466 dol_syslog(get_class($this)."::create error -1 thirdparty not defined and option PROJECT_THIRDPARTY_REQUIRED is set", LOG_ERR);
467 return -1;
468 }
469
470 // Create project
471 $this->db->begin();
472
473 $sql = "INSERT INTO ".MAIN_DB_PREFIX."projet (";
474 $sql .= "ref";
475 $sql .= ", fk_project";
476 $sql .= ", title";
477 $sql .= ", description";
478 $sql .= ", fk_soc";
479 $sql .= ", fk_user_creat";
480 $sql .= ", fk_statut";
481 $sql .= ", fk_opp_status";
482 $sql .= ", opp_percent";
483 $sql .= ", public";
484 $sql .= ", datec";
485 $sql .= ", dateo";
486 $sql .= ", datee";
487 $sql .= ", opp_amount";
488 $sql .= ", budget_amount";
489 $sql .= ", usage_opportunity";
490 $sql .= ", usage_task";
491 $sql .= ", usage_bill_time";
492 $sql .= ", usage_organize_event";
493 $sql .= ", accept_conference_suggestions";
494 $sql .= ", accept_booth_suggestions";
495 $sql .= ", price_registration";
496 $sql .= ", price_booth";
497 $sql .= ", max_attendees";
498 $sql .= ", date_start_event";
499 $sql .= ", date_end_event";
500 $sql .= ", location";
501 $sql .= ", email_msgid";
502 $sql .= ", note_private";
503 $sql .= ", note_public";
504 $sql .= ", entity";
505 $sql .= ", ip";
506 $sql .= ") VALUES (";
507 $sql .= "'".$this->db->escape($this->ref)."'";
508 $sql .= ", ".($this->fk_project ? ((int) $this->fk_project) : "null");
509 $sql .= ", '".$this->db->escape($this->title)."'";
510 $sql .= ", '".$this->db->escape($this->description)."'";
511 $sql .= ", ".($this->socid > 0 ? $this->socid : "null");
512 $sql .= ", ".((int) $user->id);
513 $sql .= ", ".(is_numeric($this->status) ? ((int) $this->status) : '0');
514 $sql .= ", ".((is_numeric($this->opp_status) && $this->opp_status > 0) ? ((int) $this->opp_status) : 'NULL');
515 $sql .= ", ".(is_numeric($this->opp_percent) ? ((int) $this->opp_percent) : 'NULL');
516 $sql .= ", ".($this->public ? 1 : 0);
517 $sql .= ", '".$this->db->idate($now)."'";
518 $sql .= ", ".($this->date_start != '' ? "'".$this->db->idate($this->date_start)."'" : 'null');
519 $sql .= ", ".($this->date_end != '' ? "'".$this->db->idate($this->date_end)."'" : 'null');
520 $sql .= ", ".(strcmp($this->opp_amount, '') ? price2num($this->opp_amount) : 'null');
521 $sql .= ", ".(strcmp((string) $this->budget_amount, '') ? price2num($this->budget_amount) : 'null');
522 $sql .= ", ".($this->usage_opportunity ? 1 : 0);
523 $sql .= ", ".($this->usage_task ? 1 : 0);
524 $sql .= ", ".($this->usage_bill_time ? 1 : 0);
525 $sql .= ", ".($this->usage_organize_event ? 1 : 0);
526 $sql .= ", ".($this->accept_conference_suggestions ? 1 : 0);
527 $sql .= ", ".($this->accept_booth_suggestions ? 1 : 0);
528 $sql .= ", ".(strcmp((string) $this->price_registration, '') ? price2num($this->price_registration) : 'null');
529 $sql .= ", ".(strcmp((string) $this->price_booth, '') ? price2num($this->price_booth) : 'null');
530 $sql .= ", ".(strcmp((string) $this->max_attendees, '') ? ((int) $this->max_attendees) : 'null');
531 $sql .= ", ".($this->date_start_event != '' ? "'".$this->db->idate($this->date_start_event)."'" : 'null');
532 $sql .= ", ".($this->date_end_event != '' ? "'".$this->db->idate($this->date_end_event)."'" : 'null');
533 $sql .= ", ".($this->location ? "'".$this->db->escape($this->location)."'" : 'null');
534 $sql .= ", ".($this->email_msgid ? "'".$this->db->escape($this->email_msgid)."'" : 'null');
535 $sql .= ", ".($this->note_private ? "'".$this->db->escape($this->note_private)."'" : 'null');
536 $sql .= ", ".($this->note_public ? "'".$this->db->escape($this->note_public)."'" : 'null');
537 $sql .= ", ".setEntity($this);
538 $sql .= ", ".(!isset($this->ip) ? 'NULL' : "'".$this->db->escape($this->ip)."'");
539 $sql .= ")";
540
541 dol_syslog(get_class($this)."::create", LOG_DEBUG);
542 $resql = $this->db->query($sql);
543 if ($resql) {
544 $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."projet");
545 $ret = $this->id;
546
547 if (!$notrigger) {
548 // Call trigger
549 $result = $this->call_trigger('PROJECT_CREATE', $user);
550 if ($result < 0) {
551 $error++;
552 }
553 // End call triggers
554 }
555 } else {
556 $this->error = $this->db->lasterror();
557 $error++;
558 }
559
560 // Update extrafield
561 if (!$error) {
562 $result = $this->insertExtraFields();
563 if ($result < 0) {
564 $error++;
565 }
566 }
567
568 if (!$error && (getDolGlobalString('MAIN_DISABLEDRAFTSTATUS') || getDolGlobalString('MAIN_DISABLEDRAFTSTATUS_PROJECT'))) {
569 $res = $this->setValid($user);
570 if ($res < 0) {
571 $error++;
572 }
573 }
574
575 if (!$error) {
576 $this->db->commit();
577 return $ret;
578 } else {
579 $this->db->rollback();
580 return -1;
581 }
582 }
583
591 public function update($user, $notrigger = 0)
592 {
593 global $langs, $conf;
594
595 $error = 0;
596
597 // Clean parameters
598 $this->title = trim($this->title);
599 $this->description = trim($this->description);
600 if ($this->opp_amount < 0) {
601 $this->opp_amount = '';
602 }
603 if ($this->opp_percent < 0) {
604 $this->opp_percent = '';
605 }
606 if ($this->date_end && $this->date_end < $this->date_start) {
607 $this->error = $langs->trans("ErrorDateEndLowerThanDateStart");
608 $this->errors[] = $this->error;
609 $this->db->rollback();
610 dol_syslog(get_class($this)."::update error -3 ".$this->error, LOG_ERR);
611 return -3;
612 }
613
614 $this->entity = ((isset($this->entity) && is_numeric($this->entity)) ? $this->entity : $conf->entity);
615
616 if (dol_strlen(trim($this->ref)) > 0) {
617 $this->db->begin();
618
619 $sql = "UPDATE ".MAIN_DB_PREFIX."projet SET";
620 $sql .= " ref='".$this->db->escape($this->ref)."'";
621 $sql .= ", fk_project=".($this->fk_project ? ((int) $this->fk_project) : "null");
622 $sql .= ", title = '".$this->db->escape($this->title)."'";
623 $sql .= ", description = '".$this->db->escape($this->description)."'";
624 $sql .= ", fk_soc = ".($this->socid > 0 ? $this->socid : "null");
625 $sql .= ", fk_statut = ".((int) $this->status);
626 $sql .= ", fk_opp_status = ".((is_numeric($this->opp_status) && $this->opp_status > 0) ? $this->opp_status : 'null');
627 $sql .= ", opp_percent = ".((is_numeric($this->opp_percent) && $this->opp_percent != '') ? $this->opp_percent : 'null');
628 $sql .= ", public = ".($this->public ? 1 : 0);
629 $sql .= ", datec = ".($this->date_c != '' ? "'".$this->db->idate($this->date_c)."'" : 'null');
630 $sql .= ", dateo = ".($this->date_start != '' ? "'".$this->db->idate($this->date_start)."'" : 'null');
631 $sql .= ", datee = ".($this->date_end != '' ? "'".$this->db->idate($this->date_end)."'" : 'null');
632 $sql .= ", date_close = ".($this->date_close != '' ? "'".$this->db->idate($this->date_close)."'" : 'null');
633 $sql .= ", note_public = ".($this->note_public ? "'".$this->db->escape($this->note_public)."'" : "null");
634 $sql .= ", note_private = ".($this->note_private ? "'".$this->db->escape($this->note_private)."'" : "null");
635 $sql .= ", fk_user_close = ".($this->fk_user_close > 0 ? $this->fk_user_close : "null");
636 $sql .= ", opp_amount = ".(strcmp($this->opp_amount, '') ? price2num($this->opp_amount) : "null");
637 $sql .= ", budget_amount = ".(strcmp($this->budget_amount, '') ? price2num($this->budget_amount) : "null");
638 $sql .= ", fk_user_modif = ".$user->id;
639 $sql .= ", usage_opportunity = ".($this->usage_opportunity ? 1 : 0);
640 $sql .= ", usage_task = ".($this->usage_task ? 1 : 0);
641 $sql .= ", usage_bill_time = ".($this->usage_bill_time ? 1 : 0);
642 $sql .= ", usage_organize_event = ".($this->usage_organize_event ? 1 : 0);
643 $sql .= ", accept_conference_suggestions = ".($this->accept_conference_suggestions ? 1 : 0);
644 $sql .= ", accept_booth_suggestions = ".($this->accept_booth_suggestions ? 1 : 0);
645 $sql .= ", price_registration = ".(isset($this->price_registration) && strcmp($this->price_registration, '') ? price2num($this->price_registration) : "null");
646 $sql .= ", price_booth = ".(isset($this->price_booth) && strcmp((string) $this->price_booth, '') ? price2num($this->price_booth) : "null");
647 $sql .= ", max_attendees = ".(strcmp((string) $this->max_attendees, '') ? (int) $this->max_attendees : "null");
648 $sql .= ", date_start_event = ".($this->date_start_event != '' ? "'".$this->db->idate($this->date_start_event)."'" : 'null');
649 $sql .= ", date_end_event = ".($this->date_end_event != '' ? "'".$this->db->idate($this->date_end_event)."'" : 'null');
650 $sql .= ", location = '".$this->db->escape($this->location)."'";
651 $sql .= ", entity = ".((int) $this->entity);
652 $sql .= " WHERE rowid = ".((int) $this->id);
653
654 dol_syslog(get_class($this)."::update", LOG_DEBUG);
655 $resql = $this->db->query($sql);
656 if ($resql) {
657 // Update extrafield
658 if (!$error) {
659 $result = $this->insertExtraFields();
660 if ($result < 0) {
661 $error++;
662 }
663 }
664
665 if (!$error && !$notrigger) {
666 // Call trigger
667 $result = $this->call_trigger('PROJECT_MODIFY', $user);
668 if ($result < 0) {
669 $error++;
670 }
671 // End call triggers
672 }
673
674 if (!$error && (is_object($this->oldcopy) && $this->oldcopy->ref !== $this->ref)) {
675 // We remove directory
676 if ($conf->project->dir_output) {
677 $olddir = $conf->project->dir_output."/".dol_sanitizeFileName($this->oldcopy->ref);
678 $newdir = $conf->project->dir_output."/".dol_sanitizeFileName($this->ref);
679 if (file_exists($olddir)) {
680 include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
681 $res = @rename($olddir, $newdir);
682 if (!$res) {
683 $langs->load("errors");
684 $this->error = $langs->trans('ErrorFailToRenameDir', $olddir, $newdir);
685 $error++;
686 }
687 }
688 }
689 }
690 if (!$error) {
691 $this->db->commit();
692 $result = 1;
693 } else {
694 $this->db->rollback();
695 $result = -1;
696 }
697 } else {
698 $this->error = $this->db->lasterror();
699 $this->errors[] = $this->error;
700 $this->db->rollback();
701 if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
702 $result = -4;
703 } else {
704 $result = -2;
705 }
706 dol_syslog(get_class($this)."::update error ".$result." ".$this->error, LOG_ERR);
707 }
708 } else {
709 dol_syslog(get_class($this)."::update ref null");
710 $result = -1;
711 }
712
713 return $result;
714 }
715
725 public function fetch($id, $ref = '', $ref_ext = '', $email_msgid = '')
726 {
727 if (empty($id) && empty($ref) && empty($ref_ext) && empty($email_msgid)) {
728 dol_syslog(get_class($this)."::fetch Bad parameters", LOG_WARNING);
729 return -1;
730 }
731
732 $sql = "SELECT rowid, entity, fk_project, ref, title, description, public, datec, opp_amount, budget_amount,";
733 $sql .= " tms, dateo as date_start, datee as date_end, date_close, fk_soc, fk_user_creat, fk_user_modif, fk_user_close, fk_statut as status, fk_opp_status, opp_percent,";
734 $sql .= " note_private, note_public, model_pdf, usage_opportunity, usage_task, usage_bill_time, usage_organize_event, email_msgid,";
735 $sql .= " accept_conference_suggestions, accept_booth_suggestions, price_registration, price_booth, max_attendees, date_start_event, date_end_event, location, extraparams";
736 $sql .= " FROM ".MAIN_DB_PREFIX."projet";
737 if (!empty($id)) {
738 $sql .= " WHERE rowid = ".((int) $id);
739 } else {
740 $sql .= " WHERE entity IN (".getEntity('project').")";
741 if (!empty($ref)) {
742 $sql .= " AND ref = '".$this->db->escape($ref)."'";
743 } elseif (!empty($ref_ext)) {
744 $sql .= " AND ref_ext = '".$this->db->escape($ref_ext)."'";
745 } else {
746 $sql .= " AND email_msgid = '".$this->db->escape($email_msgid)."'";
747 }
748 }
749
750 dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
751 $resql = $this->db->query($sql);
752 if ($resql) {
753 $num_rows = $this->db->num_rows($resql);
754
755 if ($num_rows) {
756 $obj = $this->db->fetch_object($resql);
757
758 $this->id = $obj->rowid;
759 $this->entity = $obj->entity;
760 $this->ref = $obj->ref;
761 $this->fk_project = $obj->fk_project;
762 $this->title = $obj->title;
763 $this->description = $obj->description;
764 $this->date_c = $this->db->jdate($obj->datec);
765 $this->datec = $this->db->jdate($obj->datec); // TODO deprecated
766 $this->date_m = $this->db->jdate($obj->tms);
767 $this->datem = $this->db->jdate($obj->tms); // TODO deprecated
768 $this->date_start = $this->db->jdate($obj->date_start);
769 $this->date_end = $this->db->jdate($obj->date_end);
770 $this->date_close = $this->db->jdate($obj->date_close);
771 $this->note_private = $obj->note_private;
772 $this->note_public = $obj->note_public;
773 $this->socid = $obj->fk_soc;
774 $this->user_author_id = $obj->fk_user_creat;
775 $this->user_modification_id = $obj->fk_user_modif;
776 $this->user_closing_id = $obj->fk_user_close;
777 $this->public = $obj->public;
778 $this->statut = $obj->status; // deprecated
779 $this->status = $obj->status;
780 $this->opp_status = $obj->fk_opp_status;
781 $this->opp_amount = $obj->opp_amount;
782 $this->opp_percent = $obj->opp_percent;
783 $this->budget_amount = $obj->budget_amount;
784 $this->model_pdf = $obj->model_pdf;
785 $this->usage_opportunity = (int) $obj->usage_opportunity;
786 $this->usage_task = (int) $obj->usage_task;
787 $this->usage_bill_time = (int) $obj->usage_bill_time;
788 $this->usage_organize_event = (int) $obj->usage_organize_event;
789 $this->accept_conference_suggestions = (int) $obj->accept_conference_suggestions;
790 $this->accept_booth_suggestions = (int) $obj->accept_booth_suggestions;
791 $this->price_registration = $obj->price_registration;
792 $this->price_booth = $obj->price_booth;
793 $this->max_attendees = $obj->max_attendees;
794 $this->date_start_event = $this->db->jdate($obj->date_start_event);
795 $this->date_end_event = $this->db->jdate($obj->date_end_event);
796 $this->location = $obj->location;
797 $this->email_msgid = $obj->email_msgid;
798 $this->extraparams = !empty($obj->extraparams) ? (array) json_decode($obj->extraparams, true) : array();
799
800 $this->db->free($resql);
801
802 // Retrieve all extrafield
803 // fetch optionals attributes and labels
804 $this->fetch_optionals();
805
806 return 1;
807 }
808
809 $this->db->free($resql);
810
811 return 0;
812 } else {
813 $this->error = $this->db->lasterror();
814 $this->errors[] = $this->db->lasterror();
815 return -1;
816 }
817 }
818
827 public function fetchAndSetSubstitution($id, $key, $fetched = false)
828 {
829 $substitution = '';
830
831 if ($fetched === false) {
832 $res = $this->fetch($id);
833 if ($res > 0) {
834 $fetched = true;
835 }
836 }
837
838 if ($fetched === true) {
839 if ($key == '__PROJECT_ID__') {
840 $substitution = ($this->id > 0 ? $this->id : '');
841 } elseif ($key == '__PROJECT_REF__') {
842 $substitution = $this->ref;
843 } elseif ($key == '__PROJECT_NAME__') {
844 $substitution = $this->title;
845 }
846 }
847
848 return $substitution;
849 }
850
851 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
863 public function get_element_list($type, $tablename, $datefieldname = '', $date_start = null, $date_end = null, $projectkey = 'fk_projet')
864 {
865 // phpcs:enable
866
867 global $hookmanager;
868
869 $elements = array();
870
871 if ($this->id <= 0) {
872 return $elements;
873 }
874
875 $ids = $this->id;
876
877 if ($type == 'agenda') {
878 $sql = "SELECT id as rowid FROM ".MAIN_DB_PREFIX."actioncomm WHERE fk_project IN (".$this->db->sanitize($ids).") AND entity IN (".getEntity('agenda').")";
879 } elseif ($type == 'expensereport') {
880 $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).")";
881 } elseif ($type == 'project_task') {
882 $sql = "SELECT DISTINCT pt.rowid FROM ".MAIN_DB_PREFIX."projet_task as pt WHERE pt.fk_projet IN (".$this->db->sanitize($ids).")";
883 } elseif ($type == 'element_time') { // Case we want to duplicate line foreach user
884 $sql = "SELECT DISTINCT pt.rowid, ptt.fk_user FROM ".MAIN_DB_PREFIX."projet_task as pt, ".MAIN_DB_PREFIX."element_time as ptt WHERE pt.rowid = ptt.fk_element AND ptt.elementtype = 'task' AND pt.fk_projet IN (".$this->db->sanitize($ids).")";
885 } elseif ($type == 'stocktransfer_stocktransfer') {
886 $sql = "SELECT ms.rowid, ms.fk_user_author as fk_user FROM ".MAIN_DB_PREFIX."stocktransfer_stocktransfer 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";
887 } elseif ($type == 'loan') {
888 $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).")";
889 } else {
890 $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX.$tablename." WHERE ".$projectkey." IN (".$this->db->sanitize($ids).") AND entity IN (".getEntity($type).")";
891 }
892
893 if (isDolTms($date_start) && $type == 'loan') {
894 $sql .= " AND (dateend > '".$this->db->idate($date_start)."' OR dateend IS NULL)";
895 } elseif (isDolTms($date_start) && ($type != 'project_task')) { // For table project_taks, we want the filter on date apply on project_time_spent table
896 if (empty($datefieldname) && !empty($this->table_element_date)) {
897 $datefieldname = $this->table_element_date;
898 }
899 if (empty($datefieldname)) {
900 return 'Error this object has no date field defined';
901 }
902 $sql .= " AND (".$datefieldname." >= '".$this->db->idate($date_start)."' OR ".$datefieldname." IS NULL)";
903 }
904
905 if (isDolTms($date_end) && $type == 'loan') {
906 $sql .= " AND (datestart < '".$this->db->idate($date_end)."' OR datestart IS NULL)";
907 } elseif (isDolTms($date_end) && ($type != 'project_task')) { // For table project_taks, we want the filter on date apply on project_time_spent table
908 if (empty($datefieldname) && !empty($this->table_element_date)) {
909 $datefieldname = $this->table_element_date;
910 }
911 if (empty($datefieldname)) {
912 return 'Error this object has no date field defined';
913 }
914 $sql .= " AND (".$datefieldname." <= '".$this->db->idate($date_end)."' OR ".$datefieldname." IS NULL)";
915 }
916
917 $parameters = array(
918 'sql' => $sql,
919 'type' => $type,
920 'tablename' => $tablename,
921 'datefieldname' => $datefieldname,
922 'dates' => $date_start,
923 'datee' => $date_end,
924 'fk_projet' => $projectkey,
925 'ids' => $ids,
926 );
927 $reshook = $hookmanager->executeHooks('getElementList', $parameters);
928 if ($reshook > 0) {
929 $sql = $hookmanager->resPrint;
930 } else {
931 $sql .= $hookmanager->resPrint;
932 }
933
934 if (!$sql) {
935 return -1;
936 }
937
938 //print $sql;
939 dol_syslog(get_class($this)."::get_element_list", LOG_DEBUG);
940 $result = $this->db->query($sql);
941 if ($result) {
942 $nump = $this->db->num_rows($result);
943 if ($nump) {
944 $i = 0;
945 while ($i < $nump) {
946 $obj = $this->db->fetch_object($result);
947
948 $elements[$i] = $obj->rowid.(empty($obj->fk_user) ? '' : '_'.$obj->fk_user);
949
950 $i++;
951 }
952 $this->db->free($result);
953 }
954
955 /* Return array even if empty*/
956 return $elements;
957 } else {
958 dol_print_error($this->db);
959 }
960 return -1;
961 }
962
970 public function delete($user, $notrigger = 0)
971 {
972 global $langs, $conf;
973 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
974
975 $error = 0;
976
977 $this->db->begin();
978
979 if (!$error) {
980 // Delete linked contacts
981 $res = $this->delete_linked_contact();
982 if ($res < 0) {
983 $this->error = 'ErrorFailToDeleteLinkedContact';
984 //$error++;
985 $this->db->rollback();
986 return 0;
987 }
988 }
989
990 // Set fk_projet into elements to null
991 $listoftables = array(
992 'propal' => 'fk_projet',
993 'commande' => 'fk_projet',
994 'facture' => 'fk_projet',
995 'supplier_proposal' => 'fk_projet',
996 'commande_fournisseur' => 'fk_projet',
997 'facture_fourn' => 'fk_projet',
998 'expensereport_det' => 'fk_projet',
999 'contrat' => 'fk_projet',
1000 'fichinter' => 'fk_projet',
1001 'don' => array('field' => 'fk_projet', 'module' => 'don'),
1002 'actioncomm' => 'fk_project',
1003 'mrp_mo' => 'fk_project',
1004 'entrepot' => 'fk_project',
1005 );
1006 foreach ($listoftables as $key => $value) {
1007 if (is_array($value)) {
1008 if (!isModEnabled($value['module'])) {
1009 continue;
1010 }
1011 $fieldname = $value['field'];
1012 } else {
1013 $fieldname = $value;
1014 }
1015 $sql = "UPDATE ".MAIN_DB_PREFIX.$key." SET ".$fieldname." = NULL where ".$fieldname." = ".((int) $this->id);
1016
1017 $resql = $this->db->query($sql);
1018 if (!$resql) {
1019 $this->errors[] = $this->db->lasterror();
1020 $error++;
1021 break;
1022 }
1023 }
1024
1025 // Remove linked categories.
1026 if (!$error) {
1027 $sql = "DELETE FROM ".MAIN_DB_PREFIX."categorie_project";
1028 $sql .= " WHERE fk_project = ".((int) $this->id);
1029
1030 $result = $this->db->query($sql);
1031 if (!$result) {
1032 $error++;
1033 $this->errors[] = $this->db->lasterror();
1034 }
1035 }
1036
1037 // Fetch tasks
1038 $this->getLinesArray($user, 0);
1039
1040 // Delete tasks
1041 $ret = $this->deleteTasks($user);
1042 if ($ret < 0) {
1043 $error++;
1044 }
1045
1046
1047 // Delete all child tables
1048 if (!$error) {
1049 $elements = array('categorie_project'); // elements to delete. TODO Make goodway to delete
1050 foreach ($elements as $table) {
1051 if (!$error) {
1052 $sql = "DELETE FROM ".MAIN_DB_PREFIX.$table;
1053 $sql .= " WHERE fk_project = ".((int) $this->id);
1054
1055 $result = $this->db->query($sql);
1056 if (!$result) {
1057 $error++;
1058 $this->errors[] = $this->db->lasterror();
1059 }
1060 }
1061 }
1062 }
1063
1064 if (!$error) {
1065 $sql = "DELETE FROM ".MAIN_DB_PREFIX."projet_extrafields";
1066 $sql .= " WHERE fk_object = ".((int) $this->id);
1067
1068 $resql = $this->db->query($sql);
1069 if (!$resql) {
1070 $this->errors[] = $this->db->lasterror();
1071 $error++;
1072 }
1073 }
1074
1075 // Delete project
1076 if (!$error) {
1077 $sql = "DELETE FROM ".MAIN_DB_PREFIX."projet";
1078 $sql .= " WHERE rowid=".((int) $this->id);
1079
1080 $resql = $this->db->query($sql);
1081 if (!$resql) {
1082 $this->errors[] = $langs->trans("CantRemoveProject", $langs->transnoentitiesnoconv("ProjectOverview"));
1083 $error++;
1084 }
1085 }
1086
1087
1088
1089 if (empty($error)) {
1090 // We remove directory
1091 $projectref = dol_sanitizeFileName($this->ref);
1092 if ($conf->project->dir_output) {
1093 $dir = $conf->project->dir_output."/".$projectref;
1094 if (file_exists($dir)) {
1095 $res = @dol_delete_dir_recursive($dir);
1096 if (!$res) {
1097 $this->errors[] = 'ErrorFailToDeleteDir';
1098 $error++;
1099 }
1100 }
1101 }
1102
1103 if (!$notrigger) {
1104 // Call trigger
1105 $result = $this->call_trigger('PROJECT_DELETE', $user);
1106
1107 if ($result < 0) {
1108 $error++;
1109 }
1110 // End call triggers
1111 }
1112 }
1113
1114 if (empty($error)) {
1115 $this->db->commit();
1116 return 1;
1117 } else {
1118 foreach ($this->errors as $errmsg) {
1119 dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
1120 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
1121 }
1122 dol_syslog(get_class($this)."::delete ".$this->error, LOG_ERR);
1123 $this->db->rollback();
1124 return -1;
1125 }
1126 }
1127
1136 public function getElementCount($type, $tablename, $projectkey = 'fk_projet')
1137 {
1138 if ($this->id <= 0) {
1139 return 0;
1140 }
1141
1142 if ($type == 'agenda') {
1143 $sql = "SELECT COUNT(id) as nb FROM ".MAIN_DB_PREFIX."actioncomm WHERE fk_project = ".((int) $this->id)." AND entity IN (".getEntity('agenda').")";
1144 } elseif ($type == 'expensereport') {
1145 $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);
1146 } elseif ($type == 'project_task') {
1147 $sql = "SELECT DISTINCT COUNT(pt.rowid) as nb FROM ".MAIN_DB_PREFIX."projet_task as pt WHERE pt.fk_projet = ".((int) $this->id);
1148 } elseif ($type == 'element_time') { // Case we want to duplicate line foreach user
1149 $sql = "SELECT DISTINCT COUNT(pt.rowid) as nb FROM ".MAIN_DB_PREFIX."projet_task as pt, ".MAIN_DB_PREFIX."element_time as ptt WHERE pt.rowid = ptt.fk_element AND ptt.elementtype = 'task' AND pt.fk_projet = ".((int) $this->id);
1150 } elseif ($type == 'stock_mouvement') {
1151 $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";
1152 } elseif ($type == 'loan') {
1153 $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);
1154 } else {
1155 $sql = "SELECT COUNT(rowid) as nb FROM ".MAIN_DB_PREFIX.$tablename." WHERE ".$projectkey." = ".((int) $this->id)." AND entity IN (".getEntity($type).")";
1156 }
1157
1158 $result = $this->db->query($sql);
1159
1160 if (!$result) {
1161 return 0;
1162 }
1163
1164 $obj = $this->db->fetch_object($result);
1165
1166 $this->db->free($result);
1167
1168 return $obj->nb;
1169 }
1170
1177 public function deleteTasks($user)
1178 {
1179 $countTasks = count($this->lines);
1180 $deleted = false;
1181 if ($countTasks) {
1182 foreach ($this->lines as $task) {
1183 if ($task->hasChildren() <= 0) { // If there is no children (or error to detect them)
1184 $deleted = true;
1185 $ret = $task->delete($user);
1186 if ($ret <= 0) {
1187 $this->errors[] = $this->db->lasterror();
1188 return -1;
1189 }
1190 }
1191 }
1192 }
1193 $this->getLinesArray($user);
1194 if ($deleted && count($this->lines) < $countTasks) {
1195 if (count($this->lines)) {
1196 $this->deleteTasks($user);
1197 }
1198 }
1199
1200 return 1;
1201 }
1202
1210 public function setValid($user, $notrigger = 0)
1211 {
1212 global $langs;
1213
1214 $error = 0;
1215
1216 // Protection
1217 if ($this->status == self::STATUS_VALIDATED) {
1218 dol_syslog(get_class($this)."::validate action abandoned: already validated", LOG_WARNING);
1219 return 0;
1220 }
1221
1222 // Check parameters
1223 if (preg_match('/^'.preg_quote($langs->trans("CopyOf").' ').'/', $this->title)) {
1224 $this->error = $langs->trans("ErrorFieldFormat", $langs->transnoentities("Label")).'. '.$langs->trans('RemoveString', $langs->transnoentitiesnoconv("CopyOf"));
1225 return -1;
1226 }
1227
1228 $this->db->begin();
1229
1230 $sql = "UPDATE ".MAIN_DB_PREFIX."projet";
1231 $sql .= " SET fk_statut = ".self::STATUS_VALIDATED;
1232 $sql .= " WHERE rowid = ".((int) $this->id);
1233 //$sql .= " AND entity = ".((int) $conf->entity); // Disabled, when we use the ID for the where, we must not add any other search condition
1234
1235 dol_syslog(get_class($this)."::setValid", LOG_DEBUG);
1236 $resql = $this->db->query($sql);
1237 if ($resql) {
1238 // Call trigger
1239 if (empty($notrigger)) {
1240 $result = $this->call_trigger('PROJECT_VALIDATE', $user);
1241 if ($result < 0) {
1242 $error++;
1243 }
1244 // End call triggers
1245 }
1246
1247 if (!$error) {
1248 $this->statut = 1;
1249 $this->status = 1;
1250 $this->db->commit();
1251 return 1;
1252 } else {
1253 $this->db->rollback();
1254 $this->error = implode(',', $this->errors);
1255 dol_syslog(get_class($this)."::setValid ".$this->error, LOG_ERR);
1256 return -1;
1257 }
1258 } else {
1259 $this->db->rollback();
1260 $this->error = $this->db->lasterror();
1261 return -1;
1262 }
1263 }
1264
1271 public function setClose($user)
1272 {
1273 $now = dol_now();
1274
1275 $error = 0;
1276
1277 if ($this->status != self::STATUS_CLOSED) {
1278 $this->db->begin();
1279
1280 $sql = "UPDATE ".MAIN_DB_PREFIX."projet";
1281 $sql .= " SET fk_statut = ".self::STATUS_CLOSED.", fk_user_close = ".((int) $user->id).", date_close = '".$this->db->idate($now)."'";
1282 $sql .= " WHERE rowid = ".((int) $this->id);
1283 $sql .= " AND fk_statut = ".self::STATUS_VALIDATED;
1284
1285 if (getDolGlobalString('PROJECT_USE_OPPORTUNITIES')) {
1286 // TODO What to do if fk_opp_status is not code 'WON' or 'LOST'
1287 }
1288
1289 dol_syslog(get_class($this)."::setClose", LOG_DEBUG);
1290 $resql = $this->db->query($sql);
1291 if ($resql) {
1292 // Call trigger
1293 $result = $this->call_trigger('PROJECT_CLOSE', $user);
1294 if ($result < 0) {
1295 $error++;
1296 }
1297 // End call triggers
1298
1299 if (!$error) {
1300 $this->status = 2;
1301 $this->db->commit();
1302 return 1;
1303 } else {
1304 $this->db->rollback();
1305 $this->error = implode(',', $this->errors);
1306 dol_syslog(get_class($this)."::setClose ".$this->error, LOG_ERR);
1307 return -1;
1308 }
1309 } else {
1310 $this->db->rollback();
1311 $this->error = $this->db->lasterror();
1312 return -1;
1313 }
1314 }
1315
1316 return 0;
1317 }
1318
1325 public function getLibStatut($mode = 0)
1326 {
1327 return $this->LibStatut(isset($this->status) ? $this->status : $this->statut, $mode);
1328 }
1329
1330 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1338 public function LibStatut($status, $mode = 0)
1339 {
1340 // phpcs:enable
1341 global $langs;
1342
1343 if (is_null($status)) {
1344 return '';
1345 }
1346
1347 $statustrans = array(
1348 0 => 'status0',
1349 1 => 'status4',
1350 2 => 'status6',
1351 );
1352
1353 $statusClass = 'status0';
1354 if (!empty($statustrans[$status])) {
1355 $statusClass = $statustrans[$status];
1356 }
1357
1358 return dolGetStatus($langs->transnoentitiesnoconv($this->labelStatus[$status]), $langs->transnoentitiesnoconv($this->labelStatusShort[$status]), '', $statusClass, $mode);
1359 }
1360
1368 public function getTooltipContentArray($params)
1369 {
1370 global $conf, $langs;
1371
1372 $langs->load('projects');
1373 $option = $params['option'] ?? '';
1374 $moreinpopup = $params['moreinpopup'] ?? '';
1375
1376 $datas = [];
1377 if ($option != 'nolink') {
1378 $datas['picto'] = img_picto('', $this->picto, 'class="pictofixedwidth"').' <u class="paddingrightonly">'.$langs->trans("Project").'</u>';
1379 }
1380 if (isset($this->status)) {
1381 $datas['picto'] .= ' '.$this->getLibStatut(5);
1382 }
1383 $datas['ref'] = (isset($datas['picto']) ? '<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
1384 $datas['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
1385 if (isset($this->public)) {
1386 $datas['visibility'] = '<br><b>'.$langs->trans("Visibility").":</b> ";
1387 $datas['visibility'] .= ($this->public ? img_picto($langs->trans('SharedProject'), 'world', 'class="pictofixedwidth"').$langs->trans("SharedProject") : img_picto($langs->trans('PrivateProject'), 'private', 'class="pictofixedwidth"').$langs->trans("PrivateProject"));
1388 }
1389 if (!empty($this->thirdparty_name)) {
1390 $datas['thirdparty'] = '<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
1391 }
1392 if (!empty($this->date_start)) {
1393 $datas['datestart'] = '<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
1394 }
1395 if (!empty($this->date_end)) {
1396 $datas['dateend'] = '<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
1397 }
1398 if ($moreinpopup) {
1399 $datas['moreinpopup'] = '<br>'.$moreinpopup;
1400 }
1401
1402 return $datas;
1403 }
1404
1419 public function getNomUrl($withpicto = 0, $option = '', $addlabel = 0, $moreinpopup = '', $sep = ' - ', $notooltip = 0, $save_lastsearch_value = -1, $morecss = '', $save_pageforbacktolist = '')
1420 {
1421 global $conf, $langs, $user, $hookmanager;
1422
1423 if (!empty($conf->dol_no_mouse_hover)) {
1424 $notooltip = 1; // Force disable tooltips
1425 }
1426
1427 $result = '';
1428 if (getDolGlobalString('PROJECT_OPEN_ALWAYS_ON_TAB')) {
1429 $option = getDolGlobalString('PROJECT_OPEN_ALWAYS_ON_TAB');
1430 }
1431 $params = [
1432 'id' => $this->id,
1433 'objecttype' => $this->element,
1434 'moreinpopup' => $moreinpopup,
1435 'option' => $option,
1436 ];
1437 $classfortooltip = 'classfortooltip';
1438 $dataparams = '';
1439 if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
1440 $classfortooltip = 'classforajaxtooltip';
1441 $dataparams = ' data-params="'.dol_escape_htmltag(json_encode($params)).'"';
1442 $label = '';
1443 } else {
1444 $label = implode($this->getTooltipContentArray($params));
1445 }
1446
1447 $url = '';
1448 if ($option != 'nolink') {
1449 if (preg_match('/\.php$/', $option)) {
1450 $url = dol_buildpath($option, 1).'?id='.$this->id;
1451 } elseif ($option == 'task') {
1452 $url = DOL_URL_ROOT.'/projet/tasks.php?id='.$this->id;
1453 } elseif ($option == 'preview') {
1454 $url = DOL_URL_ROOT.'/projet/element.php?id='.$this->id;
1455 } elseif ($option == 'eventorganization') {
1456 $url = DOL_URL_ROOT.'/eventorganization/conferenceorbooth_list.php?projectid='.$this->id;
1457 } else {
1458 $url = DOL_URL_ROOT.'/projet/card.php?id='.$this->id;
1459 }
1460 // Add param to save lastsearch_values or not
1461 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
1462 if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
1463 $add_save_lastsearch_values = 1;
1464 }
1465 if ($add_save_lastsearch_values) {
1466 $url .= '&save_lastsearch_values=1';
1467 }
1468 $add_save_backpagefor = ($save_pageforbacktolist ? 1 : 0);
1469 if ($add_save_backpagefor) {
1470 $url .= "&save_pageforbacktolist=".urlencode($save_pageforbacktolist);
1471 }
1472 }
1473
1474 $linkclose = '';
1475 if (empty($notooltip) && $user->hasRight('projet', 'lire')) {
1476 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
1477 $label = $langs->trans("ShowProject");
1478 $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
1479 }
1480 $linkclose .= ($label ? ' title="'.dol_escape_htmltag($label, 1).'"' : ' title="tocomplete"');
1481 $linkclose .= $dataparams.' class="'.$classfortooltip.($morecss ? ' '.$morecss : '').'"';
1482 } else {
1483 $linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
1484 }
1485
1486 $picto = 'projectpub';
1487 if (!$this->public) {
1488 $picto = 'project';
1489 }
1490
1491 $linkstart = '<a href="'.$url.'"';
1492 $linkstart .= $linkclose.'>';
1493 $linkend = '</a>';
1494
1495 $result .= $linkstart;
1496 if ($withpicto) {
1497 $result .= img_object(($notooltip ? '' : $label), $picto, 'class="pictofixedwidth em088"', 0, 0, $notooltip ? 0 : 1);
1498 }
1499 if ($withpicto != 2) {
1500 $result .= $this->ref;
1501 }
1502 $result .= $linkend;
1503 if ($withpicto != 2) {
1504 $result .= (($addlabel && $this->title) ? '<span class="opacitymedium">'.$sep.dol_trunc($this->title, ($addlabel > 1 ? $addlabel : 0)).'</span>' : '');
1505 }
1506
1507 global $action;
1508 $hookmanager->initHooks(array('projectdao'));
1509 $parameters = array('id' => $this->id, 'getnomurl' => &$result);
1510 $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
1511 if ($reshook > 0) {
1512 $result = $hookmanager->resPrint;
1513 } else {
1514 $result .= $hookmanager->resPrint;
1515 }
1516
1517 return $result;
1518 }
1519
1527 public function initAsSpecimen()
1528 {
1529 global $user, $langs, $conf;
1530
1531 $now = dol_now();
1532
1533 // Initialise parameters
1534 $this->id = 0;
1535 $this->ref = 'SPECIMEN';
1536 $this->entity = $conf->entity;
1537 $this->specimen = 1;
1538 $this->socid = 1;
1539 $this->date_c = $now;
1540 $this->date_m = $now;
1541 $this->date_start = $now;
1542 $this->date_end = $now + (3600 * 24 * 365);
1543 $this->note_public = 'SPECIMEN';
1544 $this->note_private = 'Private Note';
1545 $this->fk_project = 0;
1546 $this->opp_amount = 20000;
1547 $this->budget_amount = 10000;
1548
1549 $this->usage_opportunity = 1;
1550 $this->usage_task = 1;
1551 $this->usage_bill_time = 1;
1552 $this->usage_organize_event = 1;
1553
1554 /*
1555 $nbp = mt_rand(1, 9);
1556 $xnbp = 0;
1557 while ($xnbp < $nbp)
1558 {
1559 $line = new Task($this->db);
1560 $line->fk_project = 0;
1561 $line->label = $langs->trans("Label") . " " . $xnbp;
1562 $line->description = $langs->trans("Description") . " " . $xnbp;
1563
1564 $this->lines[]=$line;
1565 $xnbp++;
1566 }
1567 */
1568
1569 return 1;
1570 }
1571
1579 public function restrictedProjectArea(User $user, $mode = 'read')
1580 {
1581 // To verify role of users
1582 $userAccess = 0;
1583 if (($mode == 'read' && $user->hasRight('projet', 'all', 'lire')) || ($mode == 'write' && $user->hasRight('projet', 'all', 'creer')) || ($mode == 'delete' && $user->hasRight('projet', 'all', 'supprimer'))) {
1584 $userAccess = 1;
1585 } elseif ($this->public && (($mode == 'read' && $user->hasRight('projet', 'lire')) || ($mode == 'write' && $user->hasRight('projet', 'creer')) || ($mode == 'delete' && $user->hasRight('projet', 'supprimer')))) {
1586 $userAccess = 1;
1587 } else { // No access due to permission to read all projects, so we check if we are a contact of project
1588 foreach (array('internal', 'external') as $source) {
1589 $userRole = $this->liste_contact(4, $source);
1590 $num = count($userRole);
1591
1592 $nblinks = 0;
1593 while ($nblinks < $num) {
1594 if ($source == 'internal' && $user->id == $userRole[$nblinks]['id']) { // $userRole[$nblinks]['id'] is id of user (llx_user) for internal contacts
1595 if ($mode == 'read' && $user->hasRight('projet', 'lire')) {
1596 $userAccess++;
1597 }
1598 if ($mode == 'write' && $user->hasRight('projet', 'creer')) {
1599 $userAccess++;
1600 }
1601 if ($mode == 'delete' && $user->hasRight('projet', 'supprimer')) {
1602 $userAccess++;
1603 }
1604 }
1605 if ($source == 'external' && $user->socid > 0 && $user->socid == $userRole[$nblinks]['socid']) { // $userRole[$nblinks]['id'] is id of contact (llx_socpeople) or external contacts
1606 if ($mode == 'read' && $user->hasRight('projet', 'lire')) {
1607 $userAccess++;
1608 }
1609 if ($mode == 'write' && $user->hasRight('projet', 'creer')) {
1610 $userAccess++;
1611 }
1612 if ($mode == 'delete' && $user->hasRight('projet', 'supprimer')) {
1613 $userAccess++;
1614 }
1615 }
1616 $nblinks++;
1617 }
1618 }
1619 //if (empty($nblinks)) // If nobody has permission, we grant creator
1620 //{
1621 // if ((!empty($this->user_author_id) && $this->user_author_id == $user->id))
1622 // {
1623 // $userAccess = 1;
1624 // }
1625 //}
1626 }
1627
1628 return ($userAccess ? $userAccess : -1);
1629 }
1630
1641 public function getProjectsAuthorizedForUser($user, $mode = 0, $list = 0, $socid = 0, $filter = '')
1642 {
1643 $projects = array();
1644 $temp = array();
1645
1646 $sql = "SELECT ".(($mode == 0 || $mode == 1) ? "DISTINCT " : "")."p.rowid, p.ref";
1647 $sql .= " FROM ".MAIN_DB_PREFIX."projet as p";
1648 if ($mode == 0) {
1649 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."element_contact as ec ON ec.element_id = p.rowid";
1650 } elseif ($mode == 1) {
1651 $sql .= ", ".MAIN_DB_PREFIX."element_contact as ec";
1652 } elseif ($mode == 2) {
1653 // No filter. Use this if user has permission to see all project
1654 }
1655 $sql .= " WHERE p.entity IN (".getEntity('project').")";
1656 // Internal users must see project he is contact to even if project linked to a third party he can't see.
1657 //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).")";
1658 if ($socid > 0) {
1659 $sql .= " AND (p.fk_soc IS NULL OR p.fk_soc = 0 OR p.fk_soc = ".((int) $socid).")";
1660 }
1661
1662 // Get id of types of contacts for projects (This list never contains a lot of elements)
1663 $listofprojectcontacttype = array();
1664 $sql2 = "SELECT ctc.rowid, ctc.code FROM ".MAIN_DB_PREFIX."c_type_contact as ctc";
1665 $sql2 .= " WHERE ctc.element = '".$this->db->escape($this->element)."'";
1666 $sql2 .= " AND ctc.source = 'internal'";
1667 $resql = $this->db->query($sql2);
1668 if ($resql) {
1669 while ($obj = $this->db->fetch_object($resql)) {
1670 $listofprojectcontacttype[$obj->rowid] = $obj->code;
1671 }
1672 } else {
1673 dol_print_error($this->db);
1674 }
1675 if (count($listofprojectcontacttype) == 0) {
1676 $listofprojectcontacttype[0] = '0'; // To avoid syntax error if not found
1677 }
1678
1679 if ($mode == 0) {
1680 $sql .= " AND ( p.public = 1";
1681 $sql .= " OR ( ec.fk_c_type_contact IN (".$this->db->sanitize(implode(',', array_keys($listofprojectcontacttype))).")";
1682 $sql .= " AND ec.fk_socpeople = ".((int) $user->id).")";
1683 $sql .= " )";
1684 } elseif ($mode == 1) {
1685 $sql .= " AND ec.element_id = p.rowid";
1686 $sql .= " AND (";
1687 $sql .= " ( ec.fk_c_type_contact IN (".$this->db->sanitize(implode(',', array_keys($listofprojectcontacttype))).")";
1688 $sql .= " AND ec.fk_socpeople = ".((int) $user->id).")";
1689 $sql .= " )";
1690 } elseif ($mode == 2) {
1691 // No filter. Use this if user has permission to see all project
1692 }
1693
1694 $sql .= $filter;
1695 //print $sql;
1696
1697 $resql = $this->db->query($sql);
1698 if ($resql) {
1699 $num = $this->db->num_rows($resql);
1700 $i = 0;
1701 while ($i < $num) {
1702 $row = $this->db->fetch_row($resql);
1703 $projects[$row[0]] = $row[1];
1704 $temp[] = $row[0];
1705 $i++;
1706 }
1707
1708 $this->db->free($resql);
1709
1710 if ($list) {
1711 if (empty($temp)) {
1712 return '0';
1713 }
1714 $result = implode(',', $temp);
1715 return $result;
1716 }
1717 } else {
1718 dol_print_error($this->db);
1719 }
1720
1721 return $projects;
1722 }
1723
1739 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)
1740 {
1741 global $langs, $conf;
1742
1743 $error = 0;
1744 $clone_project_id = 0; // For static toolcheck
1745
1746 dol_syslog("createFromClone clone_contact=".json_encode($clone_contact)." clone_task=".json_encode($clone_task)." clone_project_file=".json_encode($clone_project_file)." clone_note=".json_encode($clone_note)." move_date=".json_encode($move_date), LOG_DEBUG);
1747
1748 $now = dol_mktime(0, 0, 0, idate('m', dol_now()), idate('d', dol_now()), idate('Y', dol_now()));
1749
1750 $clone_project = new Project($this->db);
1751
1752 $clone_project->context['createfromclone'] = 'createfromclone';
1753
1754 $this->db->begin();
1755
1756 // Load source object
1757 $clone_project->fetch($fromid);
1758 $clone_project->fetch_optionals();
1759 if ($newthirdpartyid > 0) {
1760 $clone_project->socid = $newthirdpartyid;
1761 }
1762 $clone_project->fetch_thirdparty();
1763
1764 $orign_dt_start = $clone_project->date_start;
1765 $orign_project_ref = $clone_project->ref;
1766
1767 $clone_project->id = 0;
1768 if ($move_date) {
1769 $clone_project->date_start = $now;
1770 if (!(empty($clone_project->date_end))) {
1771 $clone_project->date_end = $clone_project->date_end + ($now - $orign_dt_start);
1772 }
1773 }
1774
1775 $clone_project->date_c = $now;
1776
1777 if (!$clone_note) {
1778 $clone_project->note_private = '';
1779 $clone_project->note_public = '';
1780 }
1781
1782 //Generate next ref
1783 $defaultref = '';
1784 $obj = !getDolGlobalString('PROJECT_ADDON') ? 'mod_project_simple' : $conf->global->PROJECT_ADDON;
1785 // Search template files
1786 $file = '';
1787 $classname = '';
1788 $filefound = 0;
1789 $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
1790 foreach ($dirmodels as $reldir) {
1791 $file = dol_buildpath($reldir."core/modules/project/".$obj.'.php', 0);
1792 if (file_exists($file)) {
1793 $filefound = 1;
1794 dol_include_once($reldir."core/modules/project/".$obj.'.php');
1795 $modProject = new $obj();
1796 $defaultref = $modProject->getNextValue(is_object($clone_project->thirdparty) ? $clone_project->thirdparty : null, $clone_project);
1797 break;
1798 }
1799 }
1800 if (is_numeric($defaultref) && $defaultref <= 0) {
1801 $defaultref = '';
1802 }
1803
1804 $clone_project->ref = $defaultref;
1805 $clone_project->title = $langs->trans("CopyOf").' '.$clone_project->title;
1806
1807 // Create clone
1808 $result = $clone_project->create($user, $notrigger);
1809
1810 // Other options
1811 if ($result < 0) {
1812 $this->error .= $clone_project->error;
1813 $error++;
1814 }
1815
1816 if (!$error) {
1817 //Get the new project id
1818 $clone_project_id = $clone_project->id;
1819
1820 //Note Update
1821 if (!$clone_note) {
1822 $clone_project->note_private = '';
1823 $clone_project->note_public = '';
1824 } else {
1825 $this->db->begin();
1826 $res = $clone_project->update_note(dol_html_entity_decode($clone_project->note_public, ENT_QUOTES | ENT_HTML5), '_public');
1827 if ($res < 0) {
1828 $this->error .= $clone_project->error;
1829 $error++;
1830 $this->db->rollback();
1831 } else {
1832 $this->db->commit();
1833 }
1834
1835 $this->db->begin();
1836 $res = $clone_project->update_note(dol_html_entity_decode($clone_project->note_private, ENT_QUOTES | ENT_HTML5), '_private');
1837 if ($res < 0) {
1838 $this->error .= $clone_project->error;
1839 $error++;
1840 $this->db->rollback();
1841 } else {
1842 $this->db->commit();
1843 }
1844 }
1845
1846 //Duplicate contact
1847 if ($clone_contact) {
1848 $origin_project = new Project($this->db);
1849 $origin_project->fetch($fromid);
1850
1851 foreach (array('internal', 'external') as $source) {
1852 $tab = $origin_project->liste_contact(-1, $source);
1853 if (is_array($tab) && count($tab) > 0) {
1854 foreach ($tab as $contacttoadd) {
1855 $clone_project->add_contact($contacttoadd['id'], $contacttoadd['code'], $contacttoadd['source'], $notrigger);
1856 if ($clone_project->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
1857 $langs->load("errors");
1858 $this->error .= $langs->trans("ErrorThisContactIsAlreadyDefinedAsThisType");
1859 $error++;
1860 } else {
1861 if ($clone_project->error != '') {
1862 $this->error .= $clone_project->error;
1863 $error++;
1864 }
1865 }
1866 }
1867 } elseif ($tab < 0) {
1868 $this->error .= $origin_project->error;
1869 $error++;
1870 }
1871 }
1872 }
1873
1874 //Duplicate file
1875 if ($clone_project_file) {
1876 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
1877
1878 $clone_project_dir = $conf->project->dir_output."/".dol_sanitizeFileName($defaultref);
1879 $ori_project_dir = $conf->project->dir_output."/".dol_sanitizeFileName($orign_project_ref);
1880
1881 if (dol_mkdir($clone_project_dir) >= 0) {
1882 $filearray = dol_dir_list($ori_project_dir, "files", 0, '', '(\.meta|_preview.*\.png)$', '', SORT_ASC, 1);
1883 foreach ($filearray as $key => $file) {
1884 $rescopy = dol_copy($ori_project_dir.'/'.$file['name'], $clone_project_dir.'/'.$file['name'], 0, 1);
1885 if (is_numeric($rescopy) && $rescopy < 0) {
1886 $this->error .= $langs->trans("ErrorFailToCopyFile", $ori_project_dir.'/'.$file['name'], $clone_project_dir.'/'.$file['name']);
1887 $error++;
1888 }
1889 }
1890 } else {
1891 $this->error .= $langs->trans('ErrorInternalErrorDetected').':dol_mkdir';
1892 $error++;
1893 }
1894 }
1895
1896 //Duplicate task
1897 if ($clone_task) {
1898 require_once DOL_DOCUMENT_ROOT.'/projet/class/task.class.php';
1899
1900 $taskstatic = new Task($this->db);
1901
1902 // Security check
1903 $socid = 0;
1904 if ($user->socid > 0) {
1905 $socid = $user->socid;
1906 }
1907
1908 $tasksarray = $taskstatic->getTasksArray(0, 0, $fromid, $socid, 0);
1909
1910 $tab_conv_child_parent = array();
1911
1912 // Loop on each task, to clone it
1913 foreach ($tasksarray as $tasktoclone) {
1914 $result_clone = $taskstatic->createFromClone($user, $tasktoclone->id, $clone_project_id, $tasktoclone->fk_task_parent, $move_date, true, false, $clone_task_file, true, false);
1915 if ($result_clone <= 0) {
1916 $this->error .= $taskstatic->error;
1917 $error++;
1918 } else {
1919 $new_task_id = $result_clone;
1920 $taskstatic->fetch($tasktoclone->id);
1921
1922 //manage new parent clone task id
1923 // if the current task has child we store the original task id and the equivalent clone task id
1924 if (($taskstatic->hasChildren()) && !array_key_exists($tasktoclone->id, $tab_conv_child_parent)) {
1925 $tab_conv_child_parent[$tasktoclone->id] = $new_task_id;
1926 }
1927 }
1928 }
1929
1930 //Parse all clone node to be sure to update new parent
1931 $tasksarray = $taskstatic->getTasksArray(0, 0, $clone_project_id, $socid, 0);
1932 foreach ($tasksarray as $task_cloned) {
1933 $taskstatic->fetch($task_cloned->id);
1934 if ($taskstatic->fk_task_parent != 0) {
1935 $taskstatic->fk_task_parent = $tab_conv_child_parent[$taskstatic->fk_task_parent];
1936 }
1937 $res = $taskstatic->update($user, $notrigger);
1938 if ($result_clone <= 0) {
1939 $this->error .= $taskstatic->error;
1940 $error++;
1941 }
1942 }
1943 }
1944 }
1945
1946 unset($clone_project->context['createfromclone']);
1947
1948 if (!$error && $clone_project_id != 0) {
1949 $this->db->commit();
1950 return $clone_project_id;
1951 } else {
1952 $this->db->rollback();
1953 dol_syslog(get_class($this)."::createFromClone nbError: ".$error." error : ".$this->error, LOG_ERR);
1954 return -1;
1955 }
1956 }
1957
1958
1965 public function shiftTaskDate($old_project_dt_start)
1966 {
1967 global $user, $langs, $conf;
1968
1969 $error = 0;
1970 $result = 0;
1971
1972 $taskstatic = new Task($this->db);
1973
1974 // Security check
1975 $socid = 0;
1976 if ($user->socid > 0) {
1977 $socid = $user->socid;
1978 }
1979
1980 $tasksarray = $taskstatic->getTasksArray(0, 0, $this->id, $socid, 0);
1981
1982 foreach ($tasksarray as $tasktoshiftdate) {
1983 $to_update = false;
1984 // Fetch only if update of date will be made
1985 if ((!empty($tasktoshiftdate->date_start)) || (!empty($tasktoshiftdate->date_end))) {
1986 //dol_syslog(get_class($this)."::shiftTaskDate to_update", LOG_DEBUG);
1987 $to_update = true;
1988 $task = new Task($this->db);
1989 $result = $task->fetch($tasktoshiftdate->id);
1990 if (!$result) {
1991 $error++;
1992 $this->error .= $task->error;
1993 }
1994 }
1995 //print "$this->date_start + $tasktoshiftdate->date_start - $old_project_dt_start";exit;
1996
1997 //Calculate new task start date with difference between old proj start date and origin task start date
1998 if (!empty($tasktoshiftdate->date_start)) {
1999 $task->date_start = $this->date_start + ($tasktoshiftdate->date_start - $old_project_dt_start);
2000 }
2001
2002 //Calculate new task end date with difference between origin proj end date and origin task end date
2003 if (!empty($tasktoshiftdate->date_end)) {
2004 $task->date_end = $this->date_start + ($tasktoshiftdate->date_end - $old_project_dt_start);
2005 }
2006
2007 if ($to_update) {
2008 $result = $task->update($user);
2009 if (!$result) {
2010 $error++;
2011 $this->error .= $task->error;
2012 }
2013 }
2014 }
2015 if ($error != 0) {
2016 return -1;
2017 }
2018 return $result;
2019 }
2020
2021
2022 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2030 public function update_element($tableName, $elementSelectId)
2031 {
2032 // phpcs:enable
2033 $sql = "UPDATE ".MAIN_DB_PREFIX.$tableName;
2034
2035 if ($tableName == "actioncomm") {
2036 $sql .= " SET fk_project=".$this->id;
2037 $sql .= " WHERE id=".((int) $elementSelectId);
2038 } elseif (in_array($tableName, ["entrepot","mrp_mo","stocktransfer_stocktransfer"])) {
2039 $sql .= " SET fk_project=".$this->id;
2040 $sql .= " WHERE rowid=".((int) $elementSelectId);
2041 } else {
2042 $sql .= " SET fk_projet=".$this->id;
2043 $sql .= " WHERE rowid=".((int) $elementSelectId);
2044 }
2045
2046 dol_syslog(get_class($this)."::update_element", LOG_DEBUG);
2047 $resql = $this->db->query($sql);
2048 if (!$resql) {
2049 $this->error = $this->db->lasterror();
2050 return -1;
2051 } else {
2052 return 1;
2053 }
2054 }
2055
2056 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2066 public function remove_element($tableName, $elementSelectId, $projectfield = 'fk_projet')
2067 {
2068 // phpcs:enable
2069 $sql = "UPDATE ".MAIN_DB_PREFIX.$tableName;
2070
2071 if ($tableName == "actioncomm") {
2072 $sql .= " SET fk_project=NULL";
2073 $sql .= " WHERE id=".((int) $elementSelectId);
2074 } else {
2075 $sql .= " SET ".$projectfield."=NULL";
2076 $sql .= " WHERE rowid=".((int) $elementSelectId);
2077 }
2078
2079 dol_syslog(get_class($this)."::remove_element", LOG_DEBUG);
2080 $resql = $this->db->query($sql);
2081 if (!$resql) {
2082 $this->error = $this->db->lasterror();
2083 return -1;
2084 } else {
2085 return 1;
2086 }
2087 }
2088
2099 public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0)
2100 {
2101 global $conf, $langs;
2102
2103 $langs->load("projects");
2104
2105 if (!dol_strlen($modele)) {
2106 $modele = 'baleine';
2107
2108 if ($this->model_pdf) {
2109 $modele = $this->model_pdf;
2110 } elseif (getDolGlobalString('PROJECT_ADDON_PDF')) {
2111 $modele = getDolGlobalString('PROJECT_ADDON_PDF');
2112 }
2113 }
2114
2115 $modelpath = "core/modules/project/doc/";
2116
2117 return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref);
2118 }
2119
2120
2130 public function loadTimeSpent($datestart, $taskid = 0, $userid = 0)
2131 {
2132 $this->weekWorkLoad = array();
2133 $this->weekWorkLoadPerTask = array();
2134
2135 if (empty($datestart)) {
2136 dol_print_error(null, 'Error datestart parameter is empty');
2137 }
2138
2139 $sql = "SELECT ptt.rowid as taskid, ptt.element_duration, ptt.element_date, ptt.element_datehour, ptt.fk_element";
2140 $sql .= " FROM ".MAIN_DB_PREFIX."element_time AS ptt, ".MAIN_DB_PREFIX."projet_task as pt";
2141 $sql .= " WHERE ptt.fk_element = pt.rowid";
2142 $sql .= " AND ptt.elementtype = 'task'";
2143 $sql .= " AND pt.fk_projet = ".((int) $this->id);
2144 $sql .= " AND (ptt.element_date >= '".$this->db->idate($datestart)."' ";
2145 $sql .= " AND ptt.element_date <= '".$this->db->idate(dol_time_plus_duree($datestart, 1, 'w') - 1)."')";
2146 if ($taskid) {
2147 $sql .= " AND ptt.fk_element=".((int) $taskid);
2148 }
2149 if (is_numeric($userid)) {
2150 $sql .= " AND ptt.fk_user=".((int) $userid);
2151 }
2152
2153 //print $sql;
2154 $resql = $this->db->query($sql);
2155 if ($resql) {
2156 $daylareadyfound = array();
2157
2158 $num = $this->db->num_rows($resql);
2159 $i = 0;
2160 // Loop on each record found, so each couple (project id, task id)
2161 while ($i < $num) {
2162 $obj = $this->db->fetch_object($resql);
2163 $day = $this->db->jdate($obj->element_date); // task_date is date without hours
2164 if (empty($daylareadyfound[$day])) {
2165 $this->weekWorkLoad[$day] = $obj->element_duration;
2166 $this->weekWorkLoadPerTask[$day][$obj->fk_element] = $obj->element_duration;
2167 } else {
2168 $this->weekWorkLoad[$day] += $obj->element_duration;
2169 $this->weekWorkLoadPerTask[$day][$obj->fk_element] += $obj->element_duration;
2170 }
2171 $daylareadyfound[$day] = 1;
2172 $i++;
2173 }
2174 $this->db->free($resql);
2175 return 1;
2176 } else {
2177 $this->error = "Error ".$this->db->lasterror();
2178 dol_syslog(get_class($this)."::fetch ".$this->error, LOG_ERR);
2179 return -1;
2180 }
2181 }
2182
2192 public function loadTimeSpentMonth($datestart, $taskid = 0, $userid = 0)
2193 {
2194 $this->monthWorkLoad = array();
2195 $this->monthWorkLoadPerTask = array();
2196
2197 if (empty($datestart)) {
2198 dol_print_error(null, 'Error datestart parameter is empty');
2199 }
2200
2201 $sql = "SELECT ptt.rowid as taskid, ptt.element_duration, ptt.element_date, ptt.element_datehour, ptt.fk_element";
2202 $sql .= " FROM ".MAIN_DB_PREFIX."element_time AS ptt, ".MAIN_DB_PREFIX."projet_task as pt";
2203 $sql .= " WHERE ptt.fk_element = pt.rowid";
2204 $sql .= " AND ptt.elementtype = 'task'";
2205 $sql .= " AND pt.fk_projet = ".((int) $this->id);
2206 $sql .= " AND (ptt.element_date >= '".$this->db->idate($datestart)."' ";
2207 $sql .= " AND ptt.element_date <= '".$this->db->idate(dol_time_plus_duree($datestart, 1, 'm') - 1)."')";
2208 if ($taskid) {
2209 $sql .= " AND ptt.fk_element=".((int) $taskid);
2210 }
2211 if (is_numeric($userid)) {
2212 $sql .= " AND ptt.fk_user=".((int) $userid);
2213 }
2214
2215 //print $sql;
2216 $resql = $this->db->query($sql);
2217 if ($resql) {
2218 $weekalreadyfound = array();
2219
2220 $num = $this->db->num_rows($resql);
2221 $i = 0;
2222 // Loop on each record found, so each couple (project id, task id)
2223 while ($i < $num) {
2224 $obj = $this->db->fetch_object($resql);
2225 if (!empty($obj->element_date)) {
2226 $date = explode('-', $obj->element_date);
2227 $week_number = getWeekNumber($date[2], $date[1], $date[0]);
2228 }
2229 '@phan-var-force int $week_number'; // Needed because phan considers it might be null
2230 if (empty($weekalreadyfound[$week_number])) {
2231 $this->monthWorkLoad[$week_number] = $obj->element_duration;
2232 $this->monthWorkLoadPerTask[$week_number][$obj->fk_element] = $obj->element_duration;
2233 } else {
2234 $this->monthWorkLoad[$week_number] += $obj->element_duration;
2235 $this->monthWorkLoadPerTask[$week_number][$obj->fk_element] += $obj->element_duration;
2236 }
2237 $weekalreadyfound[$week_number] = 1;
2238 $i++;
2239 }
2240 $this->db->free($resql);
2241 return 1;
2242 } else {
2243 $this->error = "Error ".$this->db->lasterror();
2244 dol_syslog(get_class($this)."::fetch ".$this->error, LOG_ERR);
2245 return -1;
2246 }
2247 }
2248
2249 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2256 public function load_board($user)
2257 {
2258 // phpcs:enable
2259 global $conf, $langs;
2260
2261 // For external user, no check is done on company because readability is managed by public status of project and assignment.
2262 //$socid=$user->socid;
2263
2264 $response = new WorkboardResponse();
2265 $response->warning_delay = $conf->project->warning_delay / 60 / 60 / 24;
2266 $response->label = $langs->trans("OpenedProjects");
2267 $response->labelShort = $langs->trans("Opened");
2268 $response->url = DOL_URL_ROOT.'/projet/list.php?search_project_user=-1&search_status=1&mainmenu=project';
2269 $response->img = img_object('', "projectpub");
2270 $response->nbtodo = 0;
2271 $response->nbtodolate = 0;
2272
2273 $sql = "SELECT p.rowid, p.fk_statut as status, p.fk_opp_status, p.datee as datee";
2274 $sql .= " FROM (".MAIN_DB_PREFIX."projet as p";
2275 $sql .= ")";
2276 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s on p.fk_soc = s.rowid";
2277 // For external user, no check is done on company permission because readability is managed by public status of project and assignment.
2278 //if (! $user->rights->societe->client->voir && ! $socid) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON sc.fk_soc = s.rowid";
2279 $sql .= " WHERE p.fk_statut = 1";
2280 $sql .= " AND p.entity IN (".getEntity('project').')';
2281
2282
2283 $projectsListId = null;
2284 if (!$user->hasRight("projet", "all", "lire")) {
2285 $response->url = DOL_URL_ROOT.'/projet/list.php?search_status=1&mainmenu=project';
2286 $projectsListId = $this->getProjectsAuthorizedForUser($user, 0, 1);
2287 if (empty($projectsListId)) {
2288 return $response;
2289 }
2290
2291 $sql .= " AND p.rowid IN (".$this->db->sanitize($projectsListId).")";
2292 }
2293
2294 // No need to check company, as filtering of projects must be done by getProjectsAuthorizedForUser
2295 //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).")";
2296 // For external user, no check is done on company permission because readability is managed by public status of project and assignment.
2297 //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))";
2298
2299 //print $sql;
2300 $resql = $this->db->query($sql);
2301 if ($resql) {
2302 $project_static = new Project($this->db);
2303
2304
2305 // This assignment in condition is not a bug. It allows walking the results.
2306 while ($obj = $this->db->fetch_object($resql)) {
2307 $response->nbtodo++;
2308
2309 $project_static->statut = $obj->status;
2310 $project_static->status = $obj->status;
2311 $project_static->opp_status = $obj->fk_opp_status;
2312 $project_static->date_end = $this->db->jdate($obj->datee);
2313
2314 if ($project_static->hasDelay()) {
2315 $response->nbtodolate++;
2316 }
2317 }
2318
2319 return $response;
2320 }
2321
2322 $this->error = $this->db->error();
2323 return -1;
2324 }
2325
2334 public static function replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
2335 {
2336 $tables = array(
2337 'projet'
2338 );
2339
2340 return CommonObject::commonReplaceThirdparty($dbs, $origin_id, $dest_id, $tables);
2341 }
2342
2343
2349 public function loadStateBoard()
2350 {
2351 global $user;
2352
2353 $this->nb = array();
2354
2355 $sql = "SELECT count(p.rowid) as nb";
2356 $sql .= " FROM ".MAIN_DB_PREFIX."projet as p";
2357 $sql .= " WHERE";
2358 $sql .= " p.entity IN (".getEntity('project').")";
2359 if (!$user->hasRight('projet', 'all', 'lire')) {
2360 $projectsListId = $this->getProjectsAuthorizedForUser($user, 0, 1);
2361 $sql .= "AND p.rowid IN (".$this->db->sanitize($projectsListId).")";
2362 }
2363
2364 $resql = $this->db->query($sql);
2365 if ($resql) {
2366 while ($obj = $this->db->fetch_object($resql)) {
2367 $this->nb["projects"] = $obj->nb;
2368 }
2369 $this->db->free($resql);
2370 return 1;
2371 } else {
2372 dol_print_error($this->db);
2373 $this->error = $this->db->error();
2374 return -1;
2375 }
2376 }
2377
2378
2384 public function hasDelay()
2385 {
2386 global $conf;
2387
2388 if (!($this->status == self::STATUS_VALIDATED)) {
2389 return false;
2390 }
2391 if (!$this->date_end) {
2392 return false;
2393 }
2394
2395 $now = dol_now();
2396
2397 return ($this->date_end) < ($now - $conf->project->warning_delay);
2398 }
2399
2400
2407 public function info($id)
2408 {
2409 $sql = 'SELECT c.rowid, datec as datec, tms as datem,';
2410 $sql .= ' date_close as datecloture,';
2411 $sql .= ' fk_user_creat as fk_user_author, fk_user_close as fk_user_cloture';
2412 $sql .= ' FROM '.MAIN_DB_PREFIX.'projet as c';
2413 $sql .= ' WHERE c.rowid = '.((int) $id);
2414 $result = $this->db->query($sql);
2415 if ($result) {
2416 if ($this->db->num_rows($result)) {
2417 $obj = $this->db->fetch_object($result);
2418
2419 $this->id = $obj->rowid;
2420
2421 $this->user_creation_id = $obj->fk_user_author;
2422 $this->user_closing_id = $obj->fk_user_cloture;
2423
2424 $this->date_creation = $this->db->jdate($obj->datec);
2425 $this->date_modification = $this->db->jdate($obj->datem);
2426 $this->date_cloture = $this->db->jdate($obj->datecloture);
2427 }
2428
2429 $this->db->free($result);
2430 } else {
2431 dol_print_error($this->db);
2432 }
2433 }
2434
2445 public function setCategories($categories)
2446 {
2447 require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
2448 return parent::setCategoriesCommon($categories, Categorie::TYPE_PROJECT);
2449 }
2450
2451
2459 public function getLinesArray($user, $loadRoleMode = 1)
2460 {
2461 require_once DOL_DOCUMENT_ROOT.'/projet/class/task.class.php';
2462 $taskstatic = new Task($this->db);
2463
2464 $this->lines = $taskstatic->getTasksArray(0, $user, $this->id, 0, 0, '', '-1', '', 0, 0, array(), 0, array(), 0, $loadRoleMode);
2465 return 1;
2466 }
2467
2486 public function sendEmail($text, $subject, $filename_list = array(), $mimetype_list = array(), $mimefilename_list = array(), $addr_cc = "", $addr_bcc = "", $deliveryreceipt = 0, $msgishtml = -1, $errors_to = '', $moreinheader = '')
2487 {
2488 // TODO EMAIL
2489
2490 return 1;
2491 }
2492
2501 public function getKanbanView($option = '', $arraydata = null, $size = '')
2502 {
2503 global $conf, $langs;
2504
2505 $selected = (empty($arraydata['selected']) ? 0 : $arraydata['selected']);
2506
2507 if (empty($size)) {
2508 if (empty($conf->dol_optimize_smallscreen)) {
2509 $size = 'large';
2510 } else {
2511 $size = 'small';
2512 }
2513 }
2514
2515 $return = '<div class="box-flex-item '.($size == 'small' ? 'box-flex-item-small' : '').' box-flex-grow-zero">';
2516 $return .= '<div class="info-box info-box-sm">';
2517 $return .= '<span class="info-box-icon bg-infobox-action">';
2518 $return .= img_picto('', $this->public ? 'projectpub' : $this->picto);
2519 //$return .= '<i class="fa fa-dol-action"></i>'; // Can be image
2520 $return .= '</span>';
2521 $return .= '<div class="info-box-content">';
2522 $return .= '<span class="info-box-ref inline-block tdoverflowmax150 valignmiddle">'.(method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref);
2523 if ($this->hasDelay()) {
2524 $return .= img_warning($langs->trans('Late'));
2525 }
2526 $return .= '</span>';
2527 if ($selected >= 0) {
2528 $return .= '<input id="cb'.$this->id.'" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="'.$this->id.'"'.($selected ? ' checked="checked"' : '').'>';
2529 }
2530 // Date
2531 /*
2532 if (property_exists($this, 'date_start') && $this->date_start) {
2533 $return .= '<br><span class="info-box-label">'.dol_print_date($this->date_start, 'day').'</>';
2534 }
2535 if (property_exists($this, 'date_end') && $this->date_end) {
2536 if ($this->date_start) {
2537 $return .= ' - ';
2538 } else {
2539 $return .= '<br>';
2540 }
2541 $return .= '<span class="info-box-label">'.dol_print_date($this->date_end, 'day').'</span>';
2542 }*/
2543 if (property_exists($this, 'thirdparty') && !is_null($this->thirdparty) && is_object($this->thirdparty) && $this->thirdparty instanceof Societe) {
2544 $return .= '<br><div class="info-box-ref tdoverflowmax125 inline-block valignmiddle">'.$this->thirdparty->getNomUrl(1);
2545 $return .= '</div>';
2546 if (!empty($this->thirdparty->phone)) {
2547 $return .= '<div class="inline-block valignmiddle">';
2548 $return .= dol_print_phone($this->thirdparty->phone, $this->thirdparty->country_code, 0, $this->thirdparty->id, 'tel', 'hidenum', 'phone', $this->thirdparty->phone, 0, 'marginleftonly');
2549 $return .= '</div>';
2550 }
2551 if (!empty($this->thirdparty->email)) {
2552 $return .= '<div class="inline-block valignmiddle">';
2553 $return .= dol_print_email($this->thirdparty->email, 0, $this->thirdparty->id, 'thirdparty', -1, 1, 1);
2554 $return .= '</div>';
2555 }
2556 }
2557 if (!empty($arraydata['assignedusers'])) {
2558 $return .= '<br>';
2559 if ($this->public) {
2560 $return .= img_picto($langs->trans('Visibility').': '.$langs->trans('SharedProject'), 'world', 'class="paddingrightonly valignmiddle"');
2561 //print $langs->trans('SharedProject');
2562 } else {
2563 $return .= img_picto($langs->trans('Visibility').': '.$langs->trans('PrivateProject'), 'private', 'class="paddingrightonly valignmiddle"');
2564 //print $langs->trans('PrivateProject');
2565 }
2566
2567 $return .= ' <span class="small valignmiddle">'.$arraydata['assignedusers'].'</span>';
2568 }
2569 /*if (property_exists($this, 'user_author_id')) {
2570 $return .= '<br><span class="info-box-label opacitymedium">'.$langs->trans("Author").'</span>';
2571 $return .= '<span> : '.$user->getNomUrl(1).'</span>';
2572 }*/
2573 $return .= '<br><div>'; // start div line status
2574 if ($this->usage_opportunity && $this->opp_status_code) {
2575 //$return .= '<br><span class="info-bo-label opacitymedium">'.$langs->trans("OpportunityStatusShort").'</span>';
2576 //$return .= '<div class="small inline-block">'.dol_trunc($langs->trans("OppStatus".$this->opp_status_code), 5).'</div>';
2577 $return .= '<div class="opacitymedium small marginrightonly inline-block" title="'.dol_escape_htmltag($langs->trans("OppStatus".$this->opp_status_code)).'">'.round($this->opp_percent).'%</div>';
2578 $return .= ' <div class="amount small marginrightonly inline-block">'.price($this->opp_amount).'</div>';
2579 }
2580 if (method_exists($this, 'getLibStatut')) {
2581 $return .= '<div class="info-box-status small inline-block valignmiddle">'.$this->getLibStatut(3).'</div>';
2582 }
2583 $return .= '</div>'; // end div line status
2584
2585 $return .= '</div>';
2586 $return .= '</div>';
2587 $return .= '</div>';
2588
2589 return $return;
2590 }
2591
2597 public function getChildren()
2598 {
2599 $children = [];
2600 $sql = 'SELECT rowid,title';
2601 $sql .= ' FROM '.MAIN_DB_PREFIX.'projet';
2602 $sql .= ' WHERE fk_project = '.((int) $this->id);
2603 $sql .= ' ORDER BY title';
2604 $result = $this->db->query($sql);
2605 if ($result) {
2606 $n = $this->db->num_rows($result);
2607 while ($n) {
2608 $children[] = $this->db->fetch_object($result);
2609 $n--;
2610 }
2611 $this->db->free($result);
2612 } else {
2613 dol_print_error($this->db);
2614 }
2615
2616 return $children;
2617 }
2618
2623 public function createWeeklyReport()
2624 {
2625 global $mysoc, $user;
2626
2627 $now = dol_now();
2628 $nowDate = dol_getdate($now, true);
2629
2630 $errormesg = '';
2631 $errorsMsg = array();
2632
2633 $firstDayOfWeekTS = dol_get_first_day_week($nowDate['mday'], $nowDate['mon'], $nowDate['year']);
2634
2635 $firstDayOfWeekDate = dol_mktime(0, 0, 0, $nowDate['mon'], $firstDayOfWeekTS['first_day'], $nowDate['year']);
2636
2637 $lastWeekStartTS = dol_time_plus_duree($firstDayOfWeekDate, -7, 'd');
2638
2639 $lastWeekEndTS = dol_time_plus_duree($lastWeekStartTS, 6, 'd');
2640
2641 $startDate = dol_print_date($lastWeekStartTS, '%Y-%m-%d 00:00:00');
2642 $endDate = dol_print_date($lastWeekEndTS, '%Y-%m-%d 23:59:59');
2643
2644 $sql = "SELECT
2645 u.rowid AS user_id,
2646 CONCAT(u.firstname, ' ', u.lastname) AS name,
2647 u.email,u.weeklyhours,
2648 SUM(et.element_duration) AS total_seconds
2649 FROM
2650 ".MAIN_DB_PREFIX."element_time AS et
2651 JOIN
2652 ".MAIN_DB_PREFIX."user AS u ON et.fk_user = u.rowid
2653 WHERE
2654 et.element_date BETWEEN '".$this->db->escape($startDate)."' AND '".$this->db->escape($endDate)."'
2655 AND et.elementtype = 'task'
2656 GROUP BY
2657 et.fk_user";
2658
2659 $resql = $this->db->query($sql);
2660 if (!$resql) {
2661 dol_print_error($this->db);
2662 return -1;
2663 } else {
2664 $reportContent = "<span>Weekly time report from $startDate to $endDate </span><br><br>";
2665 $reportContent .= '<table border="1" style="border-collapse: collapse;">';
2666 $reportContent .= '<tr><th>Nom d\'utilisateur</th><th>Temps saisi (heures)</th><th>Temps travaillé par semaine (heures)</th></tr>';
2667
2668 $weekendEnabled = 0;
2669 $to = '';
2670 $nbMailSend = 0;
2671 $error = 0;
2672 $errors_to = '';
2673 while ($obj = $this->db->fetch_object($resql)) {
2674 $to = $obj->email;
2675 $numHolidays = num_public_holiday($lastWeekStartTS, $lastWeekEndTS, $mysoc->country_code, 1);
2676 if (getDolGlobalString('MAIN_NON_WORKING_DAYS_INCLUDE_SATURDAY') && getDolGlobalString('MAIN_NON_WORKING_DAYS_INCLUDE_SUNDAY')) {
2677 $numHolidays = $numHolidays - 2;
2678 $weekendEnabled = 2;
2679 }
2680
2681 $dailyHours = $obj->weeklyhours / (7 - $weekendEnabled);
2682
2683 // Adjust total on seconde
2684 $adjustedSeconds = $obj->total_seconds + ($numHolidays * $dailyHours * 3600);
2685
2686 $totalHours = round($adjustedSeconds / 3600, 2);
2687
2688 $reportContent .= "<tr><td>{$obj->name}</td><td>{$totalHours}</td><td>".round($obj->weeklyhours, 2)."</td></tr>";
2689
2690 $reportContent .= '</table>';
2691
2692 require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
2693
2694 // PREPARE EMAIL
2695 $errormesg = '';
2696
2697 $subject = 'Rapport hebdomadaire des temps travaillés';
2698
2699 $from = getDolGlobalString('MAIN_MAIL_EMAIL_FROM');
2700 if (empty($from)) {
2701 $errormesg = "Failed to get sender into global setup MAIN_MAIL_EMAIL_FROM";
2702 $error++;
2703 }
2704
2705 $mail = new CMailFile($subject, $to, $from, $reportContent, array(), array(), array(), '', '', 0, -1, '', '', 0, 'text/html');
2706
2707 if ($mail->sendfile()) {
2708 $nbMailSend++;
2709
2710 // Add a line into event table
2711 require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php';
2712
2713 // Insert record of emails sent
2714 $actioncomm = new ActionComm($this->db);
2715
2716 $actioncomm->type_code = 'AC_OTH_AUTO'; // Event insert into agenda automatically
2717 $actioncomm->socid = $this->thirdparty->id; // To link to a company
2718 $actioncomm->contact_id = 0;
2719
2720 $actioncomm->code = 'AC_EMAIL';
2721 $actioncomm->label = 'createWeeklyReportOK()';
2722 $actioncomm->fk_project = $this->id;
2723 $actioncomm->datep = dol_now();
2724 $actioncomm->datef = $actioncomm->datep;
2725 $actioncomm->percentage = -1; // Not applicable
2726 $actioncomm->authorid = $user->id; // User saving action
2727 $actioncomm->userownerid = $user->id; // Owner of action
2728 // Fields when action is an email (content should be added into note)
2729 $actioncomm->email_msgid = $mail->msgid;
2730 $actioncomm->email_subject = $subject;
2731 $actioncomm->email_from = $from;
2732 $actioncomm->email_sender = '';
2733 $actioncomm->email_to = $to;
2734
2735 $actioncomm->errors_to = $errors_to;
2736
2737 $actioncomm->elementtype = 'project_task';
2738 $actioncomm->fk_element = (int) $this->element;
2739
2740 $actioncomm->create($user);
2741 } else {
2742 $errormesg = $mail->error.' : '.$to;
2743 $error++;
2744
2745 // Add a line into event table
2746 require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php';
2747
2748 // Insert record of emails sent
2749 $actioncomm = new ActionComm($this->db);
2750
2751 $actioncomm->type_code = 'AC_OTH_AUTO'; // Event insert into agenda automatically
2752 $actioncomm->socid = $this->thirdparty->id; // To link to a company
2753 $actioncomm->contact_id = 0;
2754
2755 $actioncomm->code = 'AC_EMAIL';
2756 $actioncomm->label = 'createWeeklyReportKO()';
2757 $actioncomm->note_private = $errormesg;
2758 $actioncomm->fk_project = $this->id;
2759 $actioncomm->datep = dol_now();
2760 $actioncomm->datef = $actioncomm->datep;
2761 $actioncomm->authorid = $user->id; // User saving action
2762 $actioncomm->userownerid = $user->id; // Owner of action
2763 // Fields when action is an email (content should be added into note)
2764 $actioncomm->email_msgid = $mail->msgid;
2765 $actioncomm->email_from = $from;
2766 $actioncomm->email_sender = '';
2767 $actioncomm->email_to = $to;
2768
2769 $actioncomm->errors_to = $errors_to;
2770
2771 $actioncomm->elementtype = 'project_task';
2772 $actioncomm->fk_element = (int) $this->element;
2773
2774 $actioncomm->create($user);
2775 }
2776 $this->db->commit();
2777 }
2778 }
2779 if (!empty($errormesg)) {
2780 $errorsMsg[] = $errormesg;
2781 }
2782
2783 if (!$error) {
2784 $this->output .= 'Nb of emails sent : '.$nbMailSend;
2785 dol_syslog(__METHOD__." end - ".$this->output, LOG_INFO);
2786 return 0;
2787 } else {
2788 $this->error = 'Nb of emails sent : '.$nbMailSend.', '.(empty($errorsMsg) ? $error : implode(', ', $errorsMsg));
2789 dol_syslog(__METHOD__." end - ".$this->error, LOG_INFO);
2790 return $error;
2791 }
2792 }
2793}
print $langs trans("AuditedSecurityEvents").'</strong >< span class="opacitymedium"></span >< br > status
Or an array listing all the potential status of the object: array: int of the status => translated la...
Definition security.php:626
$object ref
Definition info.php:79
Class to manage agenda events (actions)
Class to send emails (with attachments or not) Usage: $mailfile = new CMailFile($subject,...
Parent class of all other business classes (invoices, contracts, proposals, orders,...
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...
commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams=null)
Common function for all objects extending CommonObject for generating documents.
liste_contact($statusoflink=-1, $source='external', $list=0, $code='', $status=-1, $arrayoftcids=array())
Get array of all contacts for an object.
static commonReplaceThirdparty(DoliDB $dbs, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
Function used to replace a thirdparty id with another one.
insertExtraFields($trigger='', $userused=null)
Add/Update all extra fields values for the current object.
delete_linked_contact($source='', $code='')
Delete all links between an object $this and all its contacts in llx_element_contact.
call_trigger($triggerName, $user)
Call trigger based on this instance.
Class to manage Dolibarr database access.
Class to manage projects.
$user_author_id
Id of project creator. Not defined if shared project.
LibStatut($status, $mode=0)
Renvoi status label for a status.
getLibStatut($mode=0)
Return status label of object.
getElementCount($type, $tablename, $projectkey='fk_projet')
Return the count of a type of linked elements of this project.
getNomUrl($withpicto=0, $option='', $addlabel=0, $moreinpopup='', $sep=' - ', $notooltip=0, $save_lastsearch_value=-1, $morecss='', $save_pageforbacktolist='')
Return clickable name (with picto eventually)
fetchAndSetSubstitution($id, $key, $fetched=false)
Fetch object and substitute key.
getChildren()
Return array of sub-projects of the current project.
setValid($user, $notrigger=0)
Validate a project.
createWeeklyReport()
Method for calculating weekly hours worked and generating a report.
static replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
Function used to replace a thirdparty id with another one.
const STATUS_VALIDATED
Open/Validated status.
$public
Tell if this is a public or private project.
getProjectsAuthorizedForUser($user, $mode=0, $list=0, $socid=0, $filter='')
Return array of projects a user has permission on, is affected to, or all projects.
create($user, $notrigger=0)
Create a project into database.
const STATUS_CLOSED
Closed status.
const STATUS_DRAFT
Draft status.
loadTimeSpentMonth($datestart, $taskid=0, $userid=0)
Load time spent into this->weekWorkLoad and this->weekWorkLoadPerTask for all day of a week of projec...
__construct($db)
Constructor.
fetch($id, $ref='', $ref_ext='', $email_msgid='')
Get object from database.
shiftTaskDate($old_project_dt_start)
Shift project task date from current date to delta.
hasDelay()
Is the project delayed?
remove_element($tableName, $elementSelectId, $projectfield='fk_projet')
Associate element to a project.
setCategories($categories)
Sets object to supplied categories.
update_element($tableName, $elementSelectId)
Associate element to a project.
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.
loadStateBoard()
Load indicators this->nb for the state board.
load_board($user)
Load indicators for dashboard (this->nbtodo and this->nbtodolate)
getLinesArray($user, $loadRoleMode=1)
Create an array of tasks of current project.
get_element_list($type, $tablename, $datefieldname='', $date_start=null, $date_end=null, $projectkey='fk_projet')
Return list of elements for type, linked to a project.
getKanbanView($option='', $arraydata=null, $size='')
Return clicable link of object (with eventually picto)
info($id)
Charge les information d'ordre info dans l'objet commande.
getTooltipContentArray($params)
getTooltipContentArray
sendEmail($text, $subject, $filename_list=array(), $mimetype_list=array(), $mimefilename_list=array(), $addr_cc="", $addr_bcc="", $deliveryreceipt=0, $msgishtml=-1, $errors_to='', $moreinheader='')
Function sending an email to the current project with the text supplied in parameter.
initAsSpecimen()
Initialise an instance with random values.
setClose($user)
Close a project.
loadTimeSpent($datestart, $taskid=0, $userid=0)
Load time spent into this->weekWorkLoad and this->weekWorkLoadPerTask for all day of a week of projec...
generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0)
Create an intervention document on disk using template defined into PROJECT_ADDON_PDF.
restrictedProjectArea(User $user, $mode='read')
Check if user has permission on current project.
deleteTasks($user)
Delete tasks with no children first, then task with children recursively.
update($user, $notrigger=0)
Update a project.
Class to manage third parties objects (customers, suppliers, prospects...)
Class to manage tasks.
Class to manage Dolibarr users.
dol_get_first_day_week($day, $month, $year, $gm=false)
Return first day of week for a date.
Definition date.lib.php:669
getWeekNumber($day, $month, $year)
Return week number.
dol_time_plus_duree($time, $duration_value, $duration_unit, $ruleforendofmonth=0)
Add a delay to a date.
Definition date.lib.php:124
num_public_holiday($timestampStart, $timestampEnd, $country_code='', $lastday=0, $includesaturday=-1, $includesunday=-1, $includefriday=-1, $includemonday=-1)
Return the number of non working days including Friday, Saturday and Sunday (or not) between 2 dates ...
Definition date.lib.php:763
print $script_file $mode $langs defaultlang(is_numeric($duration_value) ? " delay=". $duration_value :"").(is_numeric($duration_value2) ? " after cd cd cd description as description
Only used if Module[ID]Desc translation string is not found.
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)
dol_copy($srcfile, $destfile, $newmask='0', $overwriteifexists=1, $testvirus=0, $indexdatabase=0)
Copy a file to another file.
dol_dir_list($utf8_path, $types="all", $recursive=0, $filter="", $excludefilter=null, $sortcriteria="name", $sortorder=SORT_ASC, $mode=0, $nohook=0, $relativename="", $donotfollowsymlinks=0, $nbsecondsold=0)
Scan a directory and return a list of files/directories.
Definition files.lib.php:63
dol_html_entity_decode($a, $b, $c='UTF-8', $keepsomeentities=0)
Replace html_entity_decode functions to manage errors.
dol_mktime($hour, $minute, $second, $month, $day, $year, $gm='auto', $check=1)
Return a timestamp date built from detailed information (by default a local PHP server timestamp) Rep...
img_object($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0)
Show a picto called object_picto (generic function)
dol_print_phone($phone, $countrycode='', $cid=0, $socid=0, $addlink='', $separ="&nbsp;", $withpicto='', $titlealt='', $adddivfloat=0, $morecss='')
Format phone numbers according to country.
img_warning($titlealt='default', $moreatt='', $morecss='pictowarning')
Show warning logo.
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2)
Show picto whatever it's its name (generic function)
price2num($amount, $rounding='', $option=0)
Function that return a number with universal decimal format (decimal separator is '.
isDolTms($timestamp)
isDolTms check if a timestamp is valid.
dol_strlen($string, $stringencoding='UTF-8')
Make a strlen call.
dol_print_email($email, $cid=0, $socid=0, $addlink=0, $max=64, $showinvalid=1, $withpicto=0)
Show EMail link formatted for HTML output.
dol_now($mode='auto')
Return date for now.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false)
Output date in a string format according to outputlangs (or langs if not defined).
if(!function_exists( 'dol_getprefix')) dol_include_once($relpath, $classname='')
Make an include_once using default root and alternate root if it fails.
dol_substr($string, $start, $length=null, $stringencoding='', $trunconbytes=0)
Make a substring.
dol_buildpath($path, $type=0, $returnemptyifnotfound=0)
Return path of url or filesystem.
dol_sanitizeFileName($str, $newstr='_', $unaccent=1)
Clean a string to use it as a file name.
dol_print_error($db=null, $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
getDolGlobalString($key, $default='')
Return dolibarr global constant string value.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
getEntity($element, $shared=1, $currentobject=null)
Get list of entity id to use.
dol_getdate($timestamp, $fast=false, $forcetimezone='')
Return an array with locale date info.
dol_mkdir($dir, $dataroot='', $newmask='')
Creation of a directory (this can create recursive subdir)
publicphonebutton2 phonegreen basiclayout basiclayout TotalHT VATCode TotalVAT TotalLT1 TotalLT2 TotalTTC TotalHT clearboth nowraponall TAKEPOS_SHOW_SUBPRICE right right right takeposterminal SELECT e e e e e statut
Definition invoice.php:1929