dolibarr 22.0.5
project.class.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2002-2005 Rodolphe Quiedeville <rodolphe@quiedeville.org>
3 * Copyright (C) 2005-2020 Laurent Destailleur <eldy@users.sourceforge.net>
4 * Copyright (C) 2005-2010 Regis Houssin <regis.houssin@inodbox.com>
5 * Copyright (C) 2013 Florian Henry <florian.henry@open-concept.pro>
6 * Copyright (C) 2014-2017 Marcos García <marcosgdf@gmail.com>
7 * Copyright (C) 2017 Ferran Marcet <fmarcet@2byte.es>
8 * Copyright (C) 2019 Juanjo Menent <jmenent@2byte.es>
9 * Copyright (C) 2022 Charlene Benke <charlene@patas-monkey.com>
10 * Copyright (C) 2023 Gauthier VERDOL <gauthier.verdol@atm-consulting.fr>
11 * Copyright (C) 2024-2025 Frédéric France <frederic.france@free.fr>
12 * Copyright (C) 2024-2025 MDW <mdeweerd@users.noreply.github.com>
13 * Copyright (C) 2024 William Mead <william.mead@manchenumerique.fr>
14 *
15 * This program is free software; you can redistribute it and/or modify
16 * it under the terms of the GNU General Public License as published by
17 * the Free Software Foundation; either version 3 of the License, or
18 * (at your option) any later version.
19 *
20 * This program is distributed in the hope that it will be useful,
21 * but WITHOUT ANY WARRANTY; without even the implied warranty of
22 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23 * GNU General Public License for more details.
24 *
25 * You should have received a copy of the GNU General Public License
26 * along with this program. If not, see <https://www.gnu.org/licenses/>.
27 */
28
34require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
35
39class Project extends CommonObject
40{
44 public $element = 'project';
45
49 public $table_element = 'projet';
50
54 public $table_element_line = 'projet_task';
55
59 public $table_element_date;
60
64 public $fk_element = 'fk_projet';
65
69 public $picto = 'project';
70
74 protected $table_ref_field = 'ref';
75
79 public $fk_project;
80
84 public $description;
85
89 public $title;
90
95 public $dateo;
96
100 public $date_start;
101
106 public $datee;
107
111 public $date_end;
112
116 public $date_start_event;
117
121 public $date_end_event;
122
126 public $location;
127
131 public $date_close;
132
136 public $socid; // To store id of thirdparty
137
141 public $thirdparty_name; // To store name of thirdparty (defined only in some cases)
142
146 public $user_author_id;
147
151 public $fk_user_close;
152
156 public $public;
157
161 public $budget_amount;
162
166 public $usage_opportunity;
167
171 public $usage_task;
172
176 public $usage_bill_time; // Is the time spent on project must be invoiced or not
177
181 public $usage_organize_event;
182
186 public $accept_conference_suggestions;
187
191 public $accept_booth_suggestions;
192
196 public $price_registration;
197
201 public $price_booth;
202
206 public $max_attendees;
207
212 public $statut; // 0=draft, 1=opened, 2=closed
213
217 public $opp_status; // opportunity status, into table llx_c_lead_status
218
222 public $opp_status_code;
223
227 public $fk_opp_status; // opportunity status, into table llx_c_lead_status
228
232 public $opp_amount; // opportunity amount
233
237 public $opp_percent; // opportunity probability
238
242 public $opp_weighted_amount; // opportunity weighted amount
243
247 public $email_msgid;
248
252 public $weekWorkLoad;
256 public $weekWorkLoadPerTask; // Used to store workload details of tasks of a projet
257
261 public $monthWorkLoad;
262
266 public $monthWorkLoadPerTask;
267
272 public $datec;
273
277 public $date_c;
278
283 public $datem;
284
288 public $date_m;
289
293 public $ip;
294
298 public $lines;
299
340 // BEGIN MODULEBUILDER PROPERTIES
344 public $fields = array(
345 'rowid' => array('type' => 'integer', 'label' => 'ID', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 10),
346 'fk_project' => array('type' => 'integer', 'label' => 'Parent', 'enabled' => 1, 'visible' => 1, 'notnull' => 0, 'position' => 12),
347 'ref' => array('type' => 'varchar(50)', 'label' => 'Ref', 'enabled' => 1, 'visible' => 1, 'showoncombobox' => 1, 'position' => 15, 'searchall' => 1),
348 'title' => array('type' => 'varchar(255)', 'label' => 'ProjectLabel', 'enabled' => 1, 'visible' => 1, 'notnull' => 1, 'position' => 17, 'showoncombobox' => 2, 'searchall' => 1),
349 'entity' => array('type' => 'integer', 'label' => 'Entity', 'default' => '1', 'enabled' => 1, 'visible' => 3, 'notnull' => 1, 'position' => 19),
350 'fk_soc' => array('type' => 'integer:Societe:societe/class/societe.class.php', 'label' => 'ThirdParty', 'enabled' => 1, 'visible' => 0, 'position' => 20),
351 'dateo' => array('type' => 'date', 'label' => 'DateStart', 'enabled' => 1, 'visible' => -1, 'position' => 30),
352 'datee' => array('type' => 'date', 'label' => 'DateEnd', 'enabled' => 1, 'visible' => 1, 'position' => 35),
353 'description' => array('type' => 'text', 'label' => 'Description', 'enabled' => 1, 'visible' => 3, 'position' => 55, 'searchall' => 1),
354 'public' => array('type' => 'integer', 'label' => 'Visibility', 'enabled' => 1, 'visible' => -1, 'position' => 65),
355 'fk_opp_status' => array('type' => 'integer:CLeadStatus:core/class/cleadstatus.class.php', 'label' => 'OpportunityStatusShort', 'enabled' => 'getDolGlobalString("PROJECT_USE_OPPORTUNITIES")', 'visible' => 1, 'position' => 75),
356 'opp_percent' => array('type' => 'double(5,2)', 'label' => 'OpportunityProbabilityShort', 'enabled' => 'getDolGlobalString("PROJECT_USE_OPPORTUNITIES")', 'visible' => 1, 'position' => 80),
357 'note_private' => array('type' => 'html', 'label' => 'NotePrivate', 'enabled' => 1, 'visible' => 0, 'position' => 85, 'searchall' => 1),
358 'note_public' => array('type' => 'html', 'label' => 'NotePublic', 'enabled' => 1, 'visible' => 0, 'position' => 90, 'searchall' => 1),
359 'model_pdf' => array('type' => 'varchar(255)', 'label' => 'ModelPdf', 'enabled' => 1, 'visible' => 0, 'position' => 95),
360 'date_close' => array('type' => 'datetime', 'label' => 'DateClosing', 'enabled' => 1, 'visible' => 0, 'position' => 105),
361 'fk_user_close' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserClosing', 'enabled' => 1, 'visible' => 0, 'position' => 110),
362 'opp_amount' => array('type' => 'double(24,8)', 'label' => 'OpportunityAmountShort', 'enabled' => 1, 'visible' => 'getDolGlobalString("PROJECT_USE_OPPORTUNITIES")', 'position' => 115),
363 'budget_amount' => array('type' => 'double(24,8)', 'label' => 'Budget', 'enabled' => 1, 'visible' => -1, 'position' => 119),
364 'usage_opportunity' => array('type' => 'integer', 'label' => 'UsageOpportunity', 'enabled' => 1, 'visible' => -1, 'position' => 130),
365 'usage_task' => array('type' => 'integer', 'label' => 'UsageTasks', 'enabled' => 1, 'visible' => -1, 'position' => 135),
366 'usage_bill_time' => array('type' => 'integer', 'label' => 'UsageBillTimeShort', 'enabled' => 1, 'visible' => -1, 'position' => 140),
367 'usage_organize_event' => array('type' => 'integer', 'label' => 'UsageOrganizeEvent', 'enabled' => 1, 'visible' => -1, 'position' => 145),
368 // Properties for event organization
369 'date_start_event' => array('type' => 'date', 'label' => 'DateStartEvent', 'enabled' => "isModEnabled('eventorganization')", 'visible' => 1, 'position' => 200),
370 'date_end_event' => array('type' => 'date', 'label' => 'DateEndEvent', 'enabled' => "isModEnabled('eventorganization')", 'visible' => 1, 'position' => 201),
371 'location' => array('type' => 'text', 'label' => 'Location', 'enabled' => 1, 'visible' => 3, 'position' => 202, 'searchall' => 1),
372 'accept_conference_suggestions' => array('type' => 'integer', 'label' => 'AllowUnknownPeopleSuggestConf', 'enabled' => 1, 'visible' => -1, 'position' => 210),
373 'accept_booth_suggestions' => array('type' => 'integer', 'label' => 'AllowUnknownPeopleSuggestBooth', 'enabled' => 1, 'visible' => -1, 'position' => 211),
374 'price_registration' => array('type' => 'double(24,8)', 'label' => 'PriceOfRegistration', 'enabled' => 1, 'visible' => -1, 'position' => 212),
375 'price_booth' => array('type' => 'double(24,8)', 'label' => 'PriceOfBooth', 'enabled' => 1, 'visible' => -1, 'position' => 215),
376 'max_attendees' => array('type' => 'integer', 'label' => 'MaxNbOfAttendees', 'enabled' => 1, 'visible' => -1, 'position' => 215),
377 // Generic
378 'datec' => array('type' => 'datetime', 'label' => 'DateCreationShort', 'enabled' => 1, 'visible' => -2, 'position' => 400),
379 'tms' => array('type' => 'timestamp', 'label' => 'DateModificationShort', 'enabled' => 1, 'visible' => -2, 'notnull' => 1, 'position' => 405),
380 'fk_user_creat' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserCreation', 'enabled' => 1, 'visible' => 0, 'notnull' => 1, 'position' => 410),
381 'fk_user_modif' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserModification', 'enabled' => 1, 'visible' => 0, 'position' => 415),
382 'import_key' => array('type' => 'varchar(14)', 'label' => 'ImportId', 'enabled' => 1, 'visible' => -1, 'position' => 420),
383 'email_msgid' => array('type' => 'varchar(255)', 'label' => 'EmailMsgID', 'enabled' => 1, 'visible' => -1, 'position' => 450, 'help' => 'EmailMsgIDWhenSourceisEmail', 'csslist' => 'tdoverflowmax125'),
384 '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')),
385 );
386 // END MODULEBUILDER PROPERTIES
387
391 const STATUS_DRAFT = 0;
392
397
401 const STATUS_CLOSED = 2;
402
403
409 public function __construct($db)
410 {
411 global $conf;
412
413 $this->db = $db;
414
415 $this->ismultientitymanaged = 1;
416 $this->isextrafieldmanaged = 1;
417
418 $this->labelStatusShort = array(0 => 'Draft', 1 => 'Opened', 2 => 'Closed');
419 $this->labelStatus = array(0 => 'Draft', 1 => 'Opened', 2 => 'Closed');
420
421 global $conf;
422
423 if (!getDolGlobalString('MAIN_SHOW_TECHNICAL_ID')) {
424 $this->fields['rowid']['visible'] = 0;
425 }
426
427 if (!getDolGlobalString('PROJECT_USE_OPPORTUNITIES')) {
428 $this->fields['fk_opp_status']['enabled'] = 0;
429 $this->fields['opp_percent']['enabled'] = 0;
430 $this->fields['opp_amount']['enabled'] = 0;
431 $this->fields['usage_opportunity']['enabled'] = 0;
432 }
433
434 if (getDolGlobalString('PROJECT_HIDE_TASKS')) {
435 $this->fields['usage_bill_time']['visible'] = 0;
436 $this->fields['usage_task']['visible'] = 0;
437 }
438
439 if (empty($conf->eventorganization->enabled)) {
440 $this->fields['usage_organize_event']['visible'] = 0;
441 $this->fields['accept_conference_suggestions']['enabled'] = 0;
442 $this->fields['accept_booth_suggestions']['enabled'] = 0;
443 $this->fields['price_registration']['enabled'] = 0;
444 $this->fields['price_booth']['enabled'] = 0;
445 $this->fields['max_attendees']['enabled'] = 0;
446 }
447 }
448
456 public function create($user, $notrigger = 0)
457 {
458 $error = 0;
459 $ret = 0;
460
461 $now = dol_now();
462
463 // Clean parameters
464 $this->note_private = dol_substr($this->note_private, 0, 65535);
465 $this->note_public = dol_substr($this->note_public, 0, 65535);
466
467 // Check parameters
468 if (!trim($this->ref)) {
469 $this->error = 'ErrorFieldsRequired';
470 dol_syslog(get_class($this)."::create error -1 ref null", LOG_ERR);
471 return -1;
472 }
473 if (getDolGlobalString('PROJECT_THIRDPARTY_REQUIRED') && !($this->socid > 0)) {
474 $this->error = 'ErrorFieldsRequired';
475 dol_syslog(get_class($this)."::create error -1 thirdparty not defined and option PROJECT_THIRDPARTY_REQUIRED is set", LOG_ERR);
476 return -1;
477 }
478
479 // Create project
480 $this->db->begin();
481
482 $sql = "INSERT INTO ".MAIN_DB_PREFIX."projet (";
483 $sql .= "ref";
484 $sql .= ", fk_project";
485 $sql .= ", title";
486 $sql .= ", description";
487 $sql .= ", fk_soc";
488 $sql .= ", fk_user_creat";
489 $sql .= ", fk_statut";
490 $sql .= ", fk_opp_status";
491 $sql .= ", opp_percent";
492 $sql .= ", public";
493 $sql .= ", datec";
494 $sql .= ", dateo";
495 $sql .= ", datee";
496 $sql .= ", opp_amount";
497 $sql .= ", budget_amount";
498 $sql .= ", usage_opportunity";
499 $sql .= ", usage_task";
500 $sql .= ", usage_bill_time";
501 $sql .= ", usage_organize_event";
502 $sql .= ", accept_conference_suggestions";
503 $sql .= ", accept_booth_suggestions";
504 $sql .= ", price_registration";
505 $sql .= ", price_booth";
506 $sql .= ", max_attendees";
507 $sql .= ", date_start_event";
508 $sql .= ", date_end_event";
509 $sql .= ", location";
510 $sql .= ", email_msgid";
511 $sql .= ", note_private";
512 $sql .= ", note_public";
513 $sql .= ", entity";
514 $sql .= ", ip";
515 $sql .= ") VALUES (";
516 $sql .= "'".$this->db->escape($this->ref)."'";
517 $sql .= ", ".($this->fk_project ? ((int) $this->fk_project) : "null");
518 $sql .= ", '".$this->db->escape($this->title)."'";
519 $sql .= ", '".$this->db->escape($this->description)."'";
520 $sql .= ", ".($this->socid > 0 ? $this->socid : "null");
521 $sql .= ", ".((int) $user->id);
522 $sql .= ", ".(is_numeric($this->status) ? ((int) $this->status) : '0');
523 $sql .= ", ".((is_numeric($this->opp_status) && $this->opp_status > 0) ? ((int) $this->opp_status) : 'NULL');
524 $sql .= ", ".(is_numeric($this->opp_percent) ? ((int) $this->opp_percent) : 'NULL');
525 $sql .= ", ".($this->public ? 1 : 0);
526 $sql .= ", '".$this->db->idate($now)."'";
527 $sql .= ", ".($this->date_start != '' ? "'".$this->db->idate($this->date_start)."'" : 'null');
528 $sql .= ", ".($this->date_end != '' ? "'".$this->db->idate($this->date_end)."'" : 'null');
529 $sql .= ", ".(strcmp($this->opp_amount, '') ? price2num($this->opp_amount) : 'null');
530 $sql .= ", ".(strcmp((string) $this->budget_amount, '') ? price2num($this->budget_amount) : 'null');
531 $sql .= ", ".($this->usage_opportunity ? 1 : 0);
532 $sql .= ", ".($this->usage_task ? 1 : 0);
533 $sql .= ", ".($this->usage_bill_time ? 1 : 0);
534 $sql .= ", ".($this->usage_organize_event ? 1 : 0);
535 $sql .= ", ".($this->accept_conference_suggestions ? 1 : 0);
536 $sql .= ", ".($this->accept_booth_suggestions ? 1 : 0);
537 $sql .= ", ".(strcmp((string) $this->price_registration, '') ? price2num($this->price_registration) : 'null');
538 $sql .= ", ".(strcmp((string) $this->price_booth, '') ? price2num($this->price_booth) : 'null');
539 $sql .= ", ".(strcmp((string) $this->max_attendees, '') ? ((int) $this->max_attendees) : 'null');
540 $sql .= ", ".($this->date_start_event != '' ? "'".$this->db->idate($this->date_start_event)."'" : 'null');
541 $sql .= ", ".($this->date_end_event != '' ? "'".$this->db->idate($this->date_end_event)."'" : 'null');
542 $sql .= ", ".($this->location ? "'".$this->db->escape($this->location)."'" : 'null');
543 $sql .= ", ".($this->email_msgid ? "'".$this->db->escape($this->email_msgid)."'" : 'null');
544 $sql .= ", ".($this->note_private ? "'".$this->db->escape($this->note_private)."'" : 'null');
545 $sql .= ", ".($this->note_public ? "'".$this->db->escape($this->note_public)."'" : 'null');
546 $sql .= ", ".setEntity($this);
547 $sql .= ", ".(!isset($this->ip) ? 'NULL' : "'".$this->db->escape($this->ip)."'");
548 $sql .= ")";
549
550 dol_syslog(get_class($this)."::create", LOG_DEBUG);
551 $resql = $this->db->query($sql);
552 if ($resql) {
553 $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."projet");
554 $ret = $this->id;
555
556 if (!$notrigger) {
557 // Call trigger
558 $result = $this->call_trigger('PROJECT_CREATE', $user);
559 if ($result < 0) {
560 $error++;
561 }
562 // End call triggers
563 }
564 } else {
565 $this->error = $this->db->lasterror();
566 $error++;
567 }
568
569 // Update extrafield
570 if (!$error) {
571 $result = $this->insertExtraFields();
572 if ($result < 0) {
573 $error++;
574 }
575 }
576
577 if (!$error && (getDolGlobalString('MAIN_DISABLEDRAFTSTATUS') || getDolGlobalString('MAIN_DISABLEDRAFTSTATUS_PROJECT'))) {
578 $res = $this->setValid($user);
579 if ($res < 0) {
580 $error++;
581 }
582 }
583
584 if (!$error) {
585 $this->db->commit();
586 return $ret;
587 } else {
588 $this->db->rollback();
589 return -1;
590 }
591 }
592
600 public function update($user, $notrigger = 0)
601 {
602 global $langs, $conf;
603
604 $error = 0;
605
606 // Clean parameters
607 $this->title = trim($this->title);
608 $this->description = trim($this->description);
609 if ($this->opp_amount < 0) {
610 $this->opp_amount = '';
611 }
612 if ($this->opp_percent < 0) {
613 $this->opp_percent = '';
614 }
615 if ($this->date_end && $this->date_end < $this->date_start) {
616 $langs->load("errors");
617 $this->error = $langs->trans("ErrorStartDateGreaterEnd");
618 $this->errors[] = $this->error;
619 $this->db->rollback();
620 dol_syslog(get_class($this)."::update error -3 ".$this->error, LOG_ERR);
621 return -3;
622 }
623
624 $this->entity = ((isset($this->entity) && is_numeric($this->entity)) ? $this->entity : $conf->entity);
625
626 if (dol_strlen(trim($this->ref)) > 0) {
627 $this->db->begin();
628
629 $sql = "UPDATE ".MAIN_DB_PREFIX."projet SET";
630 $sql .= " ref='".$this->db->escape($this->ref)."'";
631 $sql .= ", fk_project=".($this->fk_project ? ((int) $this->fk_project) : "null");
632 $sql .= ", title = '".$this->db->escape($this->title)."'";
633 $sql .= ", description = '".$this->db->escape($this->description)."'";
634 $sql .= ", fk_soc = ".($this->socid > 0 ? $this->socid : "null");
635 $sql .= ", fk_statut = ".((int) $this->status);
636 $sql .= ", fk_opp_status = ".((is_numeric($this->opp_status) && $this->opp_status > 0) ? $this->opp_status : 'null');
637 $sql .= ", opp_percent = ".((is_numeric($this->opp_percent) && $this->opp_percent != '') ? $this->opp_percent : 'null');
638 $sql .= ", public = ".($this->public ? 1 : 0);
639 $sql .= ", datec = ".($this->date_c != '' ? "'".$this->db->idate($this->date_c)."'" : 'null');
640 $sql .= ", dateo = ".($this->date_start != '' ? "'".$this->db->idate($this->date_start)."'" : 'null');
641 $sql .= ", datee = ".($this->date_end != '' ? "'".$this->db->idate($this->date_end)."'" : 'null');
642 $sql .= ", date_close = ".($this->date_close != '' ? "'".$this->db->idate($this->date_close)."'" : 'null');
643 $sql .= ", note_public = ".($this->note_public ? "'".$this->db->escape($this->note_public)."'" : "null");
644 $sql .= ", note_private = ".($this->note_private ? "'".$this->db->escape($this->note_private)."'" : "null");
645 $sql .= ", fk_user_close = ".($this->fk_user_close > 0 ? $this->fk_user_close : "null");
646 $sql .= ", opp_amount = ".(strcmp($this->opp_amount, '') ? price2num($this->opp_amount) : "null");
647 $sql .= ", budget_amount = ".(strcmp($this->budget_amount, '') ? price2num($this->budget_amount) : "null");
648 $sql .= ", fk_user_modif = ".((int) $user->id);
649 $sql .= ", usage_opportunity = ".($this->usage_opportunity ? 1 : 0);
650 $sql .= ", usage_task = ".($this->usage_task ? 1 : 0);
651 $sql .= ", usage_bill_time = ".($this->usage_bill_time ? 1 : 0);
652 $sql .= ", usage_organize_event = ".($this->usage_organize_event ? 1 : 0);
653 $sql .= ", accept_conference_suggestions = ".($this->accept_conference_suggestions ? 1 : 0);
654 $sql .= ", accept_booth_suggestions = ".($this->accept_booth_suggestions ? 1 : 0);
655 $sql .= ", price_registration = ".(isset($this->price_registration) && strcmp($this->price_registration, '') ? price2num($this->price_registration) : "null");
656 $sql .= ", price_booth = ".(isset($this->price_booth) && strcmp((string) $this->price_booth, '') ? price2num($this->price_booth) : "null");
657 $sql .= ", max_attendees = ".(strcmp((string) $this->max_attendees, '') ? (int) $this->max_attendees : "null");
658 $sql .= ", date_start_event = ".($this->date_start_event != '' ? "'".$this->db->idate($this->date_start_event)."'" : 'null');
659 $sql .= ", date_end_event = ".($this->date_end_event != '' ? "'".$this->db->idate($this->date_end_event)."'" : 'null');
660 $sql .= ", location = '".$this->db->escape($this->location)."'";
661 $sql .= ", entity = ".((int) $this->entity);
662 $sql .= " WHERE rowid = ".((int) $this->id);
663
664 dol_syslog(get_class($this)."::update", LOG_DEBUG);
665 $resql = $this->db->query($sql);
666 if ($resql) {
667 // Update extrafield
668 if (!$error) {
669 $result = $this->insertExtraFields();
670 if ($result < 0) {
671 $error++;
672 }
673 }
674
675 if (!$error && !$notrigger) {
676 // Call trigger
677 $result = $this->call_trigger('PROJECT_MODIFY', $user);
678 if ($result < 0) {
679 $error++;
680 }
681 // End call triggers
682 }
683
684 if (!$error && (is_object($this->oldcopy) && $this->oldcopy->ref !== $this->ref)) {
685 // We remove directory
686 if ($conf->project->dir_output) {
687 $olddir = $conf->project->dir_output."/".dol_sanitizeFileName($this->oldcopy->ref);
688 $newdir = $conf->project->dir_output."/".dol_sanitizeFileName($this->ref);
689 if (file_exists($olddir)) {
690 include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
691 $res = @rename($olddir, $newdir);
692 if (!$res) {
693 $langs->load("errors");
694 $this->error = $langs->trans('ErrorFailToRenameDir', $olddir, $newdir);
695 $error++;
696 }
697 }
698 }
699 }
700 if (!$error) {
701 $this->db->commit();
702 $result = 1;
703 } else {
704 $this->db->rollback();
705 $result = -1;
706 }
707 } else {
708 $this->error = $this->db->lasterror();
709 $this->errors[] = $this->error;
710 $this->db->rollback();
711 if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
712 $result = -4;
713 } else {
714 $result = -2;
715 }
716 dol_syslog(get_class($this)."::update error ".$result." ".$this->error, LOG_ERR);
717 }
718 } else {
719 dol_syslog(get_class($this)."::update ref null");
720 $result = -1;
721 }
722
723 return $result;
724 }
725
735 public function fetch($id, $ref = '', $ref_ext = '', $email_msgid = '')
736 {
737 if (empty($id) && empty($ref) && empty($ref_ext) && empty($email_msgid)) {
738 dol_syslog(get_class($this)."::fetch Bad parameters", LOG_WARNING);
739 return -1;
740 }
741
742 $sql = "SELECT rowid, entity, fk_project, ref, title, description, public, datec, opp_amount, budget_amount,";
743 $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,";
744 $sql .= " note_private, note_public, model_pdf, usage_opportunity, usage_task, usage_bill_time, usage_organize_event, email_msgid,";
745 $sql .= " accept_conference_suggestions, accept_booth_suggestions, price_registration, price_booth, max_attendees, date_start_event, date_end_event, location, extraparams";
746 $sql .= " FROM ".MAIN_DB_PREFIX."projet";
747 if (!empty($id)) {
748 $sql .= " WHERE rowid = ".((int) $id);
749 } else {
750 $sql .= " WHERE entity IN (".getEntity('project').")";
751 if (!empty($ref)) {
752 $sql .= " AND ref = '".$this->db->escape($ref)."'";
753 } elseif (!empty($ref_ext)) {
754 $sql .= " AND ref_ext = '".$this->db->escape($ref_ext)."'";
755 } else {
756 $sql .= " AND email_msgid = '".$this->db->escape($email_msgid)."'";
757 }
758 }
759
760 dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
761 $resql = $this->db->query($sql);
762 if ($resql) {
763 $num_rows = $this->db->num_rows($resql);
764
765 if ($num_rows) {
766 $obj = $this->db->fetch_object($resql);
767
768 $this->id = $obj->rowid;
769 $this->entity = $obj->entity;
770 $this->ref = $obj->ref;
771 $this->fk_project = $obj->fk_project;
772 $this->title = $obj->title;
773 $this->description = $obj->description;
774 $this->date_c = $this->db->jdate($obj->datec);
775 $this->datec = $this->db->jdate($obj->datec); // TODO deprecated
776 $this->date_m = $this->db->jdate($obj->tms);
777 $this->datem = $this->db->jdate($obj->tms); // TODO deprecated
778 $this->date_start = $this->db->jdate($obj->date_start);
779 $this->date_end = $this->db->jdate($obj->date_end);
780 $this->date_close = $this->db->jdate($obj->date_close);
781 $this->note_private = $obj->note_private;
782 $this->note_public = $obj->note_public;
783 $this->socid = $obj->fk_soc;
784 $this->user_author_id = $obj->fk_user_creat;
785 $this->user_modification_id = $obj->fk_user_modif;
786 $this->user_closing_id = $obj->fk_user_close;
787 $this->public = $obj->public;
788 $this->statut = $obj->status; // deprecated
789 $this->status = $obj->status;
790 $this->opp_status = $obj->fk_opp_status;
791 $this->opp_amount = $obj->opp_amount;
792 $this->opp_percent = $obj->opp_percent;
793 $this->budget_amount = $obj->budget_amount;
794 $this->model_pdf = $obj->model_pdf;
795 $this->usage_opportunity = (int) $obj->usage_opportunity;
796 $this->usage_task = (int) $obj->usage_task;
797 $this->usage_bill_time = (int) $obj->usage_bill_time;
798 $this->usage_organize_event = (int) $obj->usage_organize_event;
799 $this->accept_conference_suggestions = (int) $obj->accept_conference_suggestions;
800 $this->accept_booth_suggestions = (int) $obj->accept_booth_suggestions;
801 $this->price_registration = $obj->price_registration;
802 $this->price_booth = $obj->price_booth;
803 $this->max_attendees = $obj->max_attendees;
804 $this->date_start_event = $this->db->jdate($obj->date_start_event);
805 $this->date_end_event = $this->db->jdate($obj->date_end_event);
806 $this->location = $obj->location;
807 $this->email_msgid = $obj->email_msgid;
808 $this->extraparams = !empty($obj->extraparams) ? (array) json_decode($obj->extraparams, true) : array();
809
810 $this->db->free($resql);
811
812 // Retrieve all extrafield
813 // fetch optionals attributes and labels
814 $this->fetch_optionals();
815
816 return 1;
817 }
818
819 $this->db->free($resql);
820
821 return 0;
822 } else {
823 $this->error = $this->db->lasterror();
824 $this->errors[] = $this->db->lasterror();
825 return -1;
826 }
827 }
828
837 public function fetchAndSetSubstitution($id, $key, $fetched = false)
838 {
839 $substitution = '';
840
841 if ($fetched === false) {
842 $res = $this->fetch($id);
843 if ($res > 0) {
844 $fetched = true;
845 }
846 }
847
848 if ($fetched === true) {
849 if ($key == '__PROJECT_ID__') {
850 $substitution = ($this->id > 0 ? $this->id : '');
851 } elseif ($key == '__PROJECT_REF__') {
852 $substitution = $this->ref;
853 } elseif ($key == '__PROJECT_NAME__') {
854 $substitution = $this->title;
855 }
856 }
857
858 return $substitution;
859 }
860
861 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
873 public function get_element_list($type, $tablename, $datefieldname = '', $date_start = null, $date_end = null, $projectkey = 'fk_projet')
874 {
875 // phpcs:enable
876
877 global $hookmanager;
878
879 $elements = array();
880
881 if ($this->id <= 0) {
882 return $elements;
883 }
884
885 $ids = $this->id;
886
887 if ($type == 'agenda') {
888 $sql = "SELECT id as rowid FROM ".MAIN_DB_PREFIX."actioncomm WHERE fk_project IN (".$this->db->sanitize((string) $ids).") AND entity IN (".getEntity('agenda').")";
889 } elseif ($type == 'expensereport') {
890 $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((string) $ids).")";
891 } elseif ($type == 'project_task') {
892 $sql = "SELECT DISTINCT pt.rowid FROM ".MAIN_DB_PREFIX."projet_task as pt WHERE pt.fk_projet IN (".$this->db->sanitize((string) $ids).")";
893 } elseif ($type == 'element_time') { // Case we want to duplicate line foreach user
894 $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((string) $ids).")";
895 } elseif ($type == 'stocktransfer_stocktransfer') {
896 $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((string) $ids).") AND ms.type_mouvement = 1";
897 } elseif ($type == 'loan') {
898 $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((string) $ids).")";
899 } else {
900 $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX.$tablename." WHERE ".$projectkey." IN (".$this->db->sanitize((string) $ids).") AND entity IN (".getEntity($type).")";
901 }
902
903 if (isDolTms($date_start) && $type == 'loan') {
904 $sql .= " AND (dateend > '".$this->db->idate((int) $date_start)."' OR dateend IS NULL)";
905 } elseif (isDolTms($date_start) && ($type != 'project_task')) { // For table project_taks, we want the filter on date apply on project_time_spent table
906 if (empty($datefieldname) && !empty($this->table_element_date)) {
907 $datefieldname = $this->table_element_date;
908 }
909 if (empty($datefieldname)) {
910 return 'Error this object has no date field defined';
911 }
912 $sql .= " AND (".$datefieldname." >= '".$this->db->idate((int) $date_start)."' OR ".$datefieldname." IS NULL)";
913 }
914
915 if (isDolTms($date_end) && $type == 'loan') {
916 $sql .= " AND (datestart < '".$this->db->idate((int) $date_end)."' OR datestart IS NULL)";
917 } elseif (isDolTms($date_end) && ($type != 'project_task')) { // For table project_taks, we want the filter on date apply on project_time_spent table
918 if (empty($datefieldname) && !empty($this->table_element_date)) {
919 $datefieldname = $this->table_element_date;
920 }
921 if (empty($datefieldname)) {
922 return 'Error this object has no date field defined';
923 }
924 $sql .= " AND (".$datefieldname." <= '".$this->db->idate((int) $date_end)."' OR ".$datefieldname." IS NULL)";
925 }
926
927 $parameters = array(
928 'sql' => $sql,
929 'type' => $type,
930 'tablename' => $tablename,
931 'datefieldname' => $datefieldname,
932 'dates' => $date_start,
933 'datee' => $date_end,
934 'fk_projet' => $projectkey,
935 'ids' => $ids,
936 );
937 $reshook = $hookmanager->executeHooks('getElementList', $parameters);
938 if ($reshook > 0) {
939 $sql = $hookmanager->resPrint;
940 } else {
941 $sql .= $hookmanager->resPrint;
942 }
943
944 if (!$sql) {
945 return -1;
946 }
947
948 //print $sql;
949 dol_syslog(get_class($this)."::get_element_list", LOG_DEBUG);
950 $result = $this->db->query($sql);
951 if ($result) {
952 $nump = $this->db->num_rows($result);
953 if ($nump) {
954 $i = 0;
955 while ($i < $nump) {
956 $obj = $this->db->fetch_object($result);
957
958 $elements[$i] = $obj->rowid.(empty($obj->fk_user) ? '' : '_'.$obj->fk_user);
959
960 $i++;
961 }
962 $this->db->free($result);
963 }
964
965 /* Return array even if empty*/
966 return $elements;
967 } else {
968 dol_print_error($this->db);
969 }
970 return -1;
971 }
972
980 public function delete($user, $notrigger = 0)
981 {
982 global $langs, $conf;
983 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
984
985 $error = 0;
986
987 $this->db->begin();
988
989 if (!$error) {
990 // Delete linked contacts
991 $res = $this->delete_linked_contact();
992 if ($res < 0) {
993 $this->error = 'ErrorFailToDeleteLinkedContact';
994 //$error++;
995 $this->db->rollback();
996 return 0;
997 }
998 }
999
1000 // Set fk_projet into elements to null
1001 $listoftables = array(
1002 'propal' => 'fk_projet',
1003 'commande' => 'fk_projet',
1004 'facture' => 'fk_projet',
1005 'supplier_proposal' => 'fk_projet',
1006 'commande_fournisseur' => 'fk_projet',
1007 'facture_fourn' => 'fk_projet',
1008 'expensereport_det' => 'fk_projet',
1009 'contrat' => 'fk_projet',
1010 'fichinter' => 'fk_projet',
1011 'don' => array('field' => 'fk_projet', 'module' => 'don'),
1012 'actioncomm' => 'fk_project',
1013 'mrp_mo' => array('field' => 'fk_project', 'module' => 'mrp'),
1014 'entrepot' => 'fk_project',
1015 );
1016 foreach ($listoftables as $key => $value) {
1017 if (is_array($value)) {
1018 if (!isModEnabled($value['module'])) {
1019 continue;
1020 }
1021 $fieldname = $value['field'];
1022 } else {
1023 $fieldname = $value;
1024 }
1025 $sql = "UPDATE ".MAIN_DB_PREFIX.$key." SET ".$fieldname." = NULL where ".$fieldname." = ".((int) $this->id);
1026
1027 $resql = $this->db->query($sql);
1028 if (!$resql) {
1029 $this->errors[] = $this->db->lasterror();
1030 $error++;
1031 break;
1032 }
1033 }
1034
1035 // Remove linked categories.
1036 if (!$error) {
1037 $sql = "DELETE FROM ".MAIN_DB_PREFIX."categorie_project";
1038 $sql .= " WHERE fk_project = ".((int) $this->id);
1039
1040 $result = $this->db->query($sql);
1041 if (!$result) {
1042 $error++;
1043 $this->errors[] = $this->db->lasterror();
1044 }
1045 }
1046
1047 // Fetch tasks
1048 $this->getLinesArray($user, 0);
1049
1050 // Delete tasks
1051 $ret = $this->deleteTasks($user);
1052 if ($ret < 0) {
1053 $error++;
1054 }
1055
1056
1057 // Delete all child tables
1058 if (!$error) {
1059 $elements = array('categorie_project'); // elements to delete. TODO Make goodway to delete
1060 foreach ($elements as $table) {
1061 if (!$error) {
1062 $sql = "DELETE FROM ".MAIN_DB_PREFIX.$table;
1063 $sql .= " WHERE fk_project = ".((int) $this->id);
1064
1065 $result = $this->db->query($sql);
1066 if (!$result) {
1067 $error++;
1068 $this->errors[] = $this->db->lasterror();
1069 }
1070 }
1071 }
1072 }
1073
1074 if (!$error) {
1075 $sql = "DELETE FROM ".MAIN_DB_PREFIX."projet_extrafields";
1076 $sql .= " WHERE fk_object = ".((int) $this->id);
1077
1078 $resql = $this->db->query($sql);
1079 if (!$resql) {
1080 $this->errors[] = $this->db->lasterror();
1081 $error++;
1082 }
1083 }
1084
1085 // Delete project
1086 if (!$error) {
1087 $sql = "DELETE FROM ".MAIN_DB_PREFIX."projet";
1088 $sql .= " WHERE rowid=".((int) $this->id);
1089
1090 $resql = $this->db->query($sql);
1091 if (!$resql) {
1092 $this->errors[] = $langs->trans("CantRemoveProject", $langs->transnoentitiesnoconv("ProjectOverview"));
1093 $error++;
1094 }
1095 }
1096
1097
1098
1099 if (empty($error)) {
1100 // We remove directory
1101 $projectref = dol_sanitizeFileName($this->ref);
1102 if ($conf->project->dir_output && !empty($projectref)) {
1103 $dir = $conf->project->dir_output."/".$projectref;
1104 if (file_exists($dir)) {
1105 $res = @dol_delete_dir_recursive($dir);
1106 if (!$res) {
1107 $this->errors[] = 'ErrorFailToDeleteDir';
1108 $error++;
1109 }
1110 }
1111 }
1112
1113 if (!$notrigger) {
1114 // Call trigger
1115 $result = $this->call_trigger('PROJECT_DELETE', $user);
1116
1117 if ($result < 0) {
1118 $error++;
1119 }
1120 // End call triggers
1121 }
1122 }
1123
1124 if (empty($error)) {
1125 $this->db->commit();
1126 return 1;
1127 } else {
1128 foreach ($this->errors as $errmsg) {
1129 dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
1130 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
1131 }
1132 dol_syslog(get_class($this)."::delete ".$this->error, LOG_ERR);
1133 $this->db->rollback();
1134 return -1;
1135 }
1136 }
1137
1146 public function getElementCount($type, $tablename, $projectkey = 'fk_projet')
1147 {
1148 if ($this->id <= 0) {
1149 return 0;
1150 }
1151
1152 if ($type == 'agenda') {
1153 $sql = "SELECT COUNT(id) as nb FROM ".MAIN_DB_PREFIX."actioncomm WHERE fk_project = ".((int) $this->id)." AND entity IN (".getEntity('agenda').")";
1154 } elseif ($type == 'expensereport') {
1155 $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);
1156 } elseif ($type == 'project_task') {
1157 $sql = "SELECT DISTINCT COUNT(pt.rowid) as nb FROM ".MAIN_DB_PREFIX."projet_task as pt WHERE pt.fk_projet = ".((int) $this->id);
1158 } elseif ($type == 'element_time') { // Case we want to duplicate line foreach user
1159 $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);
1160 } elseif ($type == 'stock_mouvement') {
1161 $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";
1162 } elseif ($type == 'loan') {
1163 $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);
1164 } else {
1165 $sql = "SELECT COUNT(rowid) as nb FROM ".MAIN_DB_PREFIX.$tablename." WHERE ".$projectkey." = ".((int) $this->id)." AND entity IN (".getEntity($type).")";
1166 }
1167
1168 $result = $this->db->query($sql);
1169
1170 if (!$result) {
1171 return 0;
1172 }
1173
1174 $obj = $this->db->fetch_object($result);
1175
1176 $this->db->free($result);
1177
1178 return $obj->nb;
1179 }
1180
1187 public function deleteTasks($user)
1188 {
1189 $countTasks = count($this->lines);
1190 $deleted = false;
1191 if ($countTasks) {
1192 foreach ($this->lines as $task) {
1193 if ($task->hasChildren() <= 0) { // If there is no children (or error to detect them)
1194 $deleted = true;
1195 $ret = $task->delete($user);
1196 if ($ret <= 0) {
1197 $this->errors[] = $this->db->lasterror();
1198 return -1;
1199 }
1200 }
1201 }
1202 }
1203 $this->getLinesArray($user);
1204 if ($deleted && count($this->lines) < $countTasks) {
1205 if (count($this->lines)) {
1206 $this->deleteTasks($user);
1207 }
1208 }
1209
1210 return 1;
1211 }
1212
1220 public function setValid($user, $notrigger = 0)
1221 {
1222 global $langs;
1223
1224 $error = 0;
1225
1226 // Protection
1227 if ($this->status == self::STATUS_VALIDATED) {
1228 dol_syslog(get_class($this)."::validate action abandoned: already validated", LOG_WARNING);
1229 return 0;
1230 }
1231
1232 // Check parameters
1233 if (preg_match('/^'.preg_quote($langs->trans("CopyOf").' ').'/', $this->title)) {
1234 $this->error = $langs->trans("ErrorFieldFormat", $langs->transnoentities("Label")).'. '.$langs->trans('RemoveString', $langs->transnoentitiesnoconv("CopyOf"));
1235 return -1;
1236 }
1237
1238 $this->db->begin();
1239
1240 $sql = "UPDATE ".MAIN_DB_PREFIX."projet";
1241 $sql .= " SET fk_statut = ".self::STATUS_VALIDATED;
1242 $sql .= " WHERE rowid = ".((int) $this->id);
1243 //$sql .= " AND entity = ".((int) $conf->entity); // Disabled, when we use the ID for the where, we must not add any other search condition
1244
1245 dol_syslog(get_class($this)."::setValid", LOG_DEBUG);
1246 $resql = $this->db->query($sql);
1247 if ($resql) {
1248 // Call trigger
1249 if (empty($notrigger)) {
1250 $result = $this->call_trigger('PROJECT_VALIDATE', $user);
1251 if ($result < 0) {
1252 $error++;
1253 }
1254 // End call triggers
1255 }
1256
1257 if (!$error) {
1258 $this->statut = 1;
1259 $this->status = 1;
1260 $this->db->commit();
1261 return 1;
1262 } else {
1263 $this->db->rollback();
1264 $this->error = implode(',', $this->errors);
1265 dol_syslog(get_class($this)."::setValid ".$this->error, LOG_ERR);
1266 return -1;
1267 }
1268 } else {
1269 $this->db->rollback();
1270 $this->error = $this->db->lasterror();
1271 return -1;
1272 }
1273 }
1274
1281 public function setClose($user)
1282 {
1283 $now = dol_now();
1284
1285 $error = 0;
1286
1287 if ($this->status != self::STATUS_CLOSED) {
1288 $this->db->begin();
1289
1290 $sql = "UPDATE ".MAIN_DB_PREFIX."projet";
1291 $sql .= " SET fk_statut = ".self::STATUS_CLOSED.", fk_user_close = ".((int) $user->id).", date_close = '".$this->db->idate($now)."'";
1292 $sql .= " WHERE rowid = ".((int) $this->id);
1293 $sql .= " AND fk_statut = ".self::STATUS_VALIDATED;
1294
1295 if (getDolGlobalString('PROJECT_USE_OPPORTUNITIES')) {
1296 // TODO What to do if fk_opp_status is not code 'WON' or 'LOST'
1297 }
1298
1299 dol_syslog(get_class($this)."::setClose", LOG_DEBUG);
1300 $resql = $this->db->query($sql);
1301 if ($resql) {
1302 // Call trigger
1303 $result = $this->call_trigger('PROJECT_CLOSE', $user);
1304 if ($result < 0) {
1305 $error++;
1306 }
1307 // End call triggers
1308
1309 if (!$error) {
1310 $this->status = 2;
1311 $this->db->commit();
1312 return 1;
1313 } else {
1314 $this->db->rollback();
1315 $this->error = implode(',', $this->errors);
1316 dol_syslog(get_class($this)."::setClose ".$this->error, LOG_ERR);
1317 return -1;
1318 }
1319 } else {
1320 $this->db->rollback();
1321 $this->error = $this->db->lasterror();
1322 return -1;
1323 }
1324 }
1325
1326 return 0;
1327 }
1328
1335 public function getLibStatut($mode = 0)
1336 {
1337 return $this->LibStatut(isset($this->status) ? $this->status : $this->statut, $mode);
1338 }
1339
1340 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1348 public function LibStatut($status, $mode = 0)
1349 {
1350 // phpcs:enable
1351 global $langs;
1352
1353 if (is_null($status)) {
1354 return '';
1355 }
1356
1357 $statustrans = array(
1358 0 => 'status0',
1359 1 => 'status4',
1360 2 => 'status6',
1361 );
1362
1363 $statusClass = 'status0';
1364 if (!empty($statustrans[$status])) {
1365 $statusClass = $statustrans[$status];
1366 }
1367
1368 return dolGetStatus($langs->transnoentitiesnoconv($this->labelStatus[$status]), $langs->transnoentitiesnoconv($this->labelStatusShort[$status]), '', $statusClass, $mode);
1369 }
1370
1377 public function getTooltipContentArray($params)
1378 {
1379 global $conf, $langs;
1380
1381 $langs->load('projects');
1382 $option = $params['option'] ?? '';
1383 $moreinpopup = $params['moreinpopup'] ?? '';
1384
1385 $datas = [];
1386 if ($option != 'nolink') {
1387 $datas['picto'] = img_picto('', $this->picto, 'class="pictofixedwidth"').' <u class="paddingrightonly">'.$langs->trans("Project").'</u>';
1388 }
1389 if (isset($this->status)) {
1390 $datas['picto'] .= ' '.$this->getLibStatut(5);
1391 }
1392 $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
1393 $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
1394 if (isset($this->public)) {
1395 $datas['visibility'] = '<br><b>'.$langs->trans("Visibility").":</b> ";
1396 $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"));
1397 }
1398 if (!empty($this->thirdparty_name)) {
1399 $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
1400 }
1401 if (!empty($this->date_start)) {
1402 $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
1403 }
1404 if (!empty($this->date_end)) {
1405 $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
1406 }
1407 if ($moreinpopup) {
1408 $datas['moreinpopup'] = '<br>'.$moreinpopup;
1409 }
1410
1411 return $datas;
1412 }
1413
1428 public function getNomUrl($withpicto = 0, $option = '', $addlabel = 0, $moreinpopup = '', $sep = ' - ', $notooltip = 0, $save_lastsearch_value = -1, $morecss = '', $save_pageforbacktolist = '')
1429 {
1430 global $conf, $langs, $user, $hookmanager;
1431
1432 if (!empty($conf->dol_no_mouse_hover)) {
1433 $notooltip = 1; // Force disable tooltips
1434 }
1435
1436 $result = '';
1437 if (getDolGlobalString('PROJECT_OPEN_ALWAYS_ON_TAB')) {
1438 $option = getDolGlobalString('PROJECT_OPEN_ALWAYS_ON_TAB');
1439 }
1440 $params = [
1441 'id' => $this->id,
1442 'objecttype' => $this->element,
1443 'moreinpopup' => $moreinpopup,
1444 'option' => $option,
1445 ];
1446 $classfortooltip = 'classfortooltip';
1447 $dataparams = '';
1448 if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
1449 $classfortooltip = 'classforajaxtooltip';
1450 $dataparams = ' data-params="'.dol_escape_htmltag(json_encode($params)).'"';
1451 $label = '';
1452 } else {
1453 $label = implode($this->getTooltipContentArray($params));
1454 }
1455
1456 $url = '';
1457 if ($option != 'nolink') {
1458 if (preg_match('/\.php$/', $option)) {
1459 $url = dol_buildpath($option, 1).'?id='.$this->id;
1460 } elseif ($option == 'task') {
1461 $url = DOL_URL_ROOT.'/projet/tasks.php?id='.$this->id;
1462 } elseif ($option == 'preview') {
1463 $url = DOL_URL_ROOT.'/projet/element.php?id='.$this->id;
1464 } elseif ($option == 'eventorganization') {
1465 $url = DOL_URL_ROOT.'/eventorganization/conferenceorbooth_list.php?projectid='.$this->id;
1466 } else {
1467 $url = DOL_URL_ROOT.'/projet/card.php?id='.$this->id;
1468 }
1469 // Add param to save lastsearch_values or not
1470 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
1471 if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
1472 $add_save_lastsearch_values = 1;
1473 }
1474 if ($add_save_lastsearch_values) {
1475 $url .= '&save_lastsearch_values=1';
1476 }
1477 $add_save_backpagefor = ($save_pageforbacktolist ? 1 : 0);
1478 if ($add_save_backpagefor) {
1479 $url .= "&save_pageforbacktolist=".urlencode($save_pageforbacktolist);
1480 }
1481 }
1482
1483 $linkclose = '';
1484 if (empty($notooltip) && $user->hasRight('projet', 'lire')) {
1485 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
1486 $label = $langs->trans("ShowProject");
1487 $linkclose .= ' alt="'.dolPrintHTMLForAttribute($label).'"';
1488 }
1489 $linkclose .= ($label ? ' title="'.dolPrintHTMLForAttribute($label).'"' : ' title="tocomplete"');
1490 $linkclose .= $dataparams.' class="'.$classfortooltip.($morecss ? ' '.$morecss : '').'"';
1491 } else {
1492 $linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
1493 }
1494
1495 $picto = 'projectpub';
1496 if (!$this->public) {
1497 $picto = 'project';
1498 }
1499
1500 $linkstart = '<a href="'.$url.'"';
1501 $linkstart .= $linkclose.'>';
1502 $linkend = '</a>';
1503
1504 $result .= $linkstart;
1505 if ($withpicto) {
1506 $result .= img_object(($notooltip ? '' : $label), $picto, 'class="pictofixedwidth em088"', 0, 0, $notooltip ? 0 : 1);
1507 }
1508 if ($withpicto != 2) {
1509 if ($addlabel >= 0) {
1510 $result .= $this->ref;
1511 } else {
1512 $result .= $this->title;
1513 }
1514 }
1515 $result .= $linkend;
1516 if ($withpicto != 2) {
1517 $result .= (($addlabel > 0 && $this->title) ? '<span class="opacitymedium">'.$sep.dol_trunc($this->title, ($addlabel > 1 ? $addlabel : 0)).'</span>' : '');
1518 }
1519
1520 global $action;
1521 $hookmanager->initHooks(array('projectdao'));
1522 $parameters = array('id' => $this->id, 'getnomurl' => &$result);
1523 $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
1524 if ($reshook > 0) {
1525 $result = $hookmanager->resPrint;
1526 } else {
1527 $result .= $hookmanager->resPrint;
1528 }
1529
1530 return $result;
1531 }
1532
1540 public function initAsSpecimen()
1541 {
1542 global $user, $langs, $conf;
1543
1544 $now = dol_now();
1545
1546 // Initialise parameters
1547 $this->id = 0;
1548 $this->ref = 'SPECIMEN';
1549 $this->entity = $conf->entity;
1550 $this->specimen = 1;
1551 $this->socid = 1;
1552 $this->date_c = $now;
1553 $this->date_m = $now;
1554 $this->date_start = $now;
1555 $this->date_end = $now + (3600 * 24 * 365);
1556 $this->note_public = 'SPECIMEN';
1557 $this->note_private = 'Private Note';
1558 $this->fk_project = 0;
1559 $this->opp_amount = 20000;
1560 $this->budget_amount = 10000;
1561
1562 $this->usage_opportunity = 1;
1563 $this->usage_task = 1;
1564 $this->usage_bill_time = 1;
1565 $this->usage_organize_event = 1;
1566
1567 /*
1568 $nbp = mt_rand(1, 9);
1569 $xnbp = 0;
1570 while ($xnbp < $nbp)
1571 {
1572 $line = new Task($this->db);
1573 $line->fk_project = 0;
1574 $line->label = $langs->trans("Label") . " " . $xnbp;
1575 $line->description = $langs->trans("Description") . " " . $xnbp;
1576
1577 $this->lines[]=$line;
1578 $xnbp++;
1579 }
1580 */
1581
1582 return 1;
1583 }
1584
1592 public function restrictedProjectArea(User $user, $mode = 'read')
1593 {
1594 // To verify role of users
1595 $userAccess = 0;
1596 if (($mode == 'read' && $user->hasRight('projet', 'all', 'lire')) || ($mode == 'write' && $user->hasRight('projet', 'all', 'creer')) || ($mode == 'delete' && $user->hasRight('projet', 'all', 'supprimer'))) {
1597 $userAccess = 1;
1598 } elseif ($this->public && (($mode == 'read' && $user->hasRight('projet', 'lire')) || ($mode == 'write' && $user->hasRight('projet', 'creer')) || ($mode == 'delete' && $user->hasRight('projet', 'supprimer')))) {
1599 $userAccess = 1;
1600 } else { // No access due to permission to read all projects, so we check if we are a contact of project
1601 foreach (array('internal', 'external') as $source) {
1602 $userRole = $this->liste_contact(4, $source);
1603 $num = count($userRole);
1604
1605 $nblinks = 0;
1606 while ($nblinks < $num) {
1607 if ($source == 'internal' && $user->id == $userRole[$nblinks]['id']) { // $userRole[$nblinks]['id'] is id of user (llx_user) for internal contacts
1608 if ($mode == 'read' && $user->hasRight('projet', 'lire')) {
1609 $userAccess++;
1610 }
1611 if ($mode == 'write' && $user->hasRight('projet', 'creer')) {
1612 $userAccess++;
1613 }
1614 if ($mode == 'delete' && $user->hasRight('projet', 'supprimer')) {
1615 $userAccess++;
1616 }
1617 }
1618 if ($source == 'external' && $user->socid > 0 && $user->socid == $userRole[$nblinks]['socid']) { // $userRole[$nblinks]['id'] is id of contact (llx_socpeople) or external contacts
1619 if ($mode == 'read' && $user->hasRight('projet', 'lire')) {
1620 $userAccess++;
1621 }
1622 if ($mode == 'write' && $user->hasRight('projet', 'creer')) {
1623 $userAccess++;
1624 }
1625 if ($mode == 'delete' && $user->hasRight('projet', 'supprimer')) {
1626 $userAccess++;
1627 }
1628 }
1629 $nblinks++;
1630 }
1631 }
1632 //if (empty($nblinks)) // If nobody has permission, we grant creator
1633 //{
1634 // if ((!empty($this->user_author_id) && $this->user_author_id == $user->id))
1635 // {
1636 // $userAccess = 1;
1637 // }
1638 //}
1639 }
1640
1641 return ($userAccess ? $userAccess : -1);
1642 }
1643
1654 public function getProjectsAuthorizedForUser($user, $mode = 0, $list = 0, $socid = 0, $filter = '')
1655 {
1656 $projects = array();
1657 $temp = array();
1658
1659 $sql = "SELECT ".(($mode == 0 || $mode == 1) ? "DISTINCT " : "")."p.rowid, p.ref";
1660 $sql .= " FROM ".MAIN_DB_PREFIX."projet as p";
1661 if ($mode == 0) {
1662 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."element_contact as ec ON ec.element_id = p.rowid";
1663 } elseif ($mode == 1) {
1664 $sql .= ", ".MAIN_DB_PREFIX."element_contact as ec";
1665 } // elseif ($mode == 2) {
1666 // No filter. Use this if user has permission to see all project
1667 // }
1668 $sql .= " WHERE p.entity IN (".getEntity('project').")";
1669 // Internal users must see project he is contact to even if project linked to a third party he can't see.
1670 //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).")";
1671 if ($socid > 0) {
1672 $sql .= " AND (p.fk_soc IS NULL OR p.fk_soc = 0 OR p.fk_soc = ".((int) $socid).")";
1673 }
1674
1675 // Get id of types of contacts for projects (This list never contains a lot of elements)
1676 $listofprojectcontacttype = array();
1677 $sql2 = "SELECT ctc.rowid, ctc.code FROM ".MAIN_DB_PREFIX."c_type_contact as ctc";
1678 $sql2 .= " WHERE ctc.element = '".$this->db->escape($this->element)."'";
1679 $sql2 .= " AND ctc.source = 'internal'";
1680 $resql = $this->db->query($sql2);
1681 if ($resql) {
1682 while ($obj = $this->db->fetch_object($resql)) {
1683 $listofprojectcontacttype[$obj->rowid] = $obj->code;
1684 }
1685 } else {
1686 dol_print_error($this->db);
1687 }
1688 if (count($listofprojectcontacttype) == 0) {
1689 $listofprojectcontacttype[0] = '0'; // To avoid syntax error if not found
1690 }
1691
1692 if ($mode == 0) {
1693 $sql .= " AND ( p.public = 1";
1694 $sql .= " OR ( ec.fk_c_type_contact IN (".$this->db->sanitize(implode(',', array_keys($listofprojectcontacttype))).")";
1695 $sql .= " AND ec.fk_socpeople = ".((int) $user->id).")";
1696 $sql .= " )";
1697 } elseif ($mode == 1) {
1698 $sql .= " AND ec.element_id = p.rowid";
1699 $sql .= " AND (";
1700 $sql .= " ( ec.fk_c_type_contact IN (".$this->db->sanitize(implode(',', array_keys($listofprojectcontacttype))).")";
1701 $sql .= " AND ec.fk_socpeople = ".((int) $user->id).")";
1702 $sql .= " )";
1703 } // elseif ($mode == 2) {
1704 // No filter. Use this if user has permission to see all project
1705 //}
1706
1707 // Manage filter
1708 $errormessage = '';
1709 $sql .= forgeSQLFromUniversalSearchCriteria($filter, $errormessage);
1710 if ($errormessage) {
1711 $this->errors[] = $errormessage;
1712 dol_syslog(__METHOD__.' '.implode(',', $this->errors), LOG_ERR);
1713 $sql .= $filter;
1714 }
1715
1716 //print $sql;
1717
1718 $resql = $this->db->query($sql);
1719 if ($resql) {
1720 $num = $this->db->num_rows($resql);
1721 $i = 0;
1722 while ($i < $num) {
1723 $row = $this->db->fetch_row($resql);
1724 $projects[$row[0]] = $row[1];
1725 $temp[] = $row[0];
1726 $i++;
1727 }
1728
1729 $this->db->free($resql);
1730
1731 if ($list) {
1732 if (empty($temp)) {
1733 return '0';
1734 }
1735 $result = implode(',', $temp);
1736 return $result;
1737 }
1738 } else {
1739 dol_print_error($this->db);
1740 }
1741
1742 return $projects;
1743 }
1744
1760 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)
1761 {
1762 global $langs, $conf;
1763
1764 $error = 0;
1765 $clone_project_id = 0; // For static toolcheck
1766
1767 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);
1768
1769 $now = dol_mktime(0, 0, 0, idate('m', dol_now()), idate('d', dol_now()), idate('Y', dol_now()));
1770
1771 $clone_project = new Project($this->db);
1772
1773 $clone_project->context['createfromclone'] = 'createfromclone';
1774
1775 $this->db->begin();
1776
1777 // Load source object
1778 $clone_project->fetch($fromid);
1779 $clone_project->fetch_optionals();
1780 $clone_project->socid = ($newthirdpartyid > 0 ? $newthirdpartyid : 0);
1781 $clone_project->fetch_thirdparty();
1782
1783 $orign_dt_start = $clone_project->date_start;
1784 $orign_project_ref = $clone_project->ref;
1785
1786 $clone_project->id = 0;
1787 if ($move_date) {
1788 $clone_project->date_start = $now;
1789 if (!empty($clone_project->date_end)) {
1790 if (!empty($orign_dt_start)) {
1791 $clone_project->date_end += ($now - (int) $orign_dt_start);
1792 } elseif (!empty($clone_project->date_c)) {
1793 $clone_project->date_end += ($now - (int) $clone_project->date_c);
1794 }
1795 }
1796 }
1797
1798 $clone_project->date_c = $now;
1799
1800 if (!$clone_note) {
1801 $clone_project->note_private = '';
1802 $clone_project->note_public = '';
1803 }
1804
1805 //Generate next ref
1806 $defaultref = '';
1807 $obj = getDolGlobalString('PROJECT_ADDON', 'mod_project_simple');
1808 // Search template files
1809 $file = '';
1810 $classname = '';
1811 $filefound = 0;
1812 $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
1813 foreach ($dirmodels as $reldir) {
1814 $file = dol_buildpath($reldir."core/modules/project/".$obj.'.php', 0);
1815 if (file_exists($file)) {
1816 $filefound = 1;
1817 dol_include_once($reldir."core/modules/project/".$obj.'.php');
1818 $modProject = new $obj();
1819 '@phan-var-force ModeleNumRefProjects $modProject';
1820 $defaultref = $modProject->getNextValue(is_object($clone_project->thirdparty) ? $clone_project->thirdparty : null, $clone_project);
1821 break;
1822 }
1823 }
1824 if (is_numeric($defaultref) && $defaultref <= 0) {
1825 $defaultref = '';
1826 }
1827
1828 $clone_project->ref = $defaultref;
1829 $clone_project->title = $langs->trans("CopyOf").' '.$clone_project->title;
1830
1831 // Create clone
1832 $result = $clone_project->create($user, $notrigger);
1833
1834 // Other options
1835 if ($result < 0) {
1836 $this->error .= $clone_project->error;
1837 $error++;
1838 }
1839
1840 if (!$error) {
1841 //Get the new project id
1842 $clone_project_id = $clone_project->id;
1843
1844 //Note Update
1845 if (!$clone_note) {
1846 $clone_project->note_private = '';
1847 $clone_project->note_public = '';
1848 } else {
1849 $this->db->begin();
1850 $res = $clone_project->update_note(dol_html_entity_decode($clone_project->note_public, ENT_QUOTES | ENT_HTML5), '_public');
1851 if ($res < 0) {
1852 $this->error .= $clone_project->error;
1853 $error++;
1854 $this->db->rollback();
1855 } else {
1856 $this->db->commit();
1857 }
1858
1859 $this->db->begin();
1860 $res = $clone_project->update_note(dol_html_entity_decode($clone_project->note_private, ENT_QUOTES | ENT_HTML5), '_private');
1861 if ($res < 0) {
1862 $this->error .= $clone_project->error;
1863 $error++;
1864 $this->db->rollback();
1865 } else {
1866 $this->db->commit();
1867 }
1868 }
1869
1870 //Duplicate contact
1871 if ($clone_contact) {
1872 $origin_project = new Project($this->db);
1873 $origin_project->fetch($fromid);
1874
1875 foreach (array('internal', 'external') as $source) {
1876 $tab = $origin_project->liste_contact(-1, $source);
1877 if (is_array($tab) && count($tab) > 0) {
1878 foreach ($tab as $contacttoadd) {
1879 $clone_project->add_contact($contacttoadd['id'], $contacttoadd['code'], $contacttoadd['source'], $notrigger);
1880 if ($clone_project->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
1881 $langs->load("errors");
1882 $this->error .= $langs->trans("ErrorThisContactIsAlreadyDefinedAsThisType");
1883 $error++;
1884 } else {
1885 if ($clone_project->error != '') {
1886 $this->error .= $clone_project->error;
1887 $error++;
1888 }
1889 }
1890 }
1891 } elseif ($tab < 0) {
1892 $this->error .= $origin_project->error;
1893 $error++;
1894 }
1895 }
1896 }
1897
1898 //Duplicate file
1899 if ($clone_project_file) {
1900 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
1901
1902 $clone_project_dir = $conf->project->dir_output."/".dol_sanitizeFileName($defaultref);
1903 $ori_project_dir = $conf->project->dir_output."/".dol_sanitizeFileName($orign_project_ref);
1904
1905 if (dol_mkdir($clone_project_dir) >= 0) {
1906 $filearray = dol_dir_list($ori_project_dir, "files", 0, '', '(\.meta|_preview.*\.png)$', '', SORT_ASC, 1);
1907 foreach ($filearray as $key => $file) {
1908 $rescopy = dol_copy($ori_project_dir.'/'.$file['name'], $clone_project_dir.'/'.$file['name'], '0', 1);
1909 if (is_numeric($rescopy) && $rescopy < 0) {
1910 $this->error .= $langs->trans("ErrorFailToCopyFile", $ori_project_dir.'/'.$file['name'], $clone_project_dir.'/'.$file['name']);
1911 $error++;
1912 }
1913 }
1914 } else {
1915 $this->error .= $langs->trans('ErrorInternalErrorDetected').':dol_mkdir';
1916 $error++;
1917 }
1918 }
1919
1920 //Duplicate task
1921 if ($clone_task) {
1922 require_once DOL_DOCUMENT_ROOT.'/projet/class/task.class.php';
1923
1924 $taskstatic = new Task($this->db);
1925
1926 // Security check
1927 $socid = 0;
1928 if ($user->socid > 0) {
1929 $socid = $user->socid;
1930 }
1931
1932 $tasksarray = $taskstatic->getTasksArray(null, null, $fromid, $socid, 0);
1933
1934 $tab_conv_child_parent = array();
1935 $result_clone = 0;
1936
1937 // Loop on each task, to clone it
1938 foreach ($tasksarray as $tasktoclone) {
1939 $result_clone = $taskstatic->createFromClone($user, $tasktoclone->id, $clone_project_id, $tasktoclone->fk_task_parent, $move_date, true, false, $clone_task_file, true, false);
1940 if ($result_clone <= 0) {
1941 $this->error .= $taskstatic->error;
1942 $error++;
1943 } else {
1944 $new_task_id = $result_clone;
1945 $taskstatic->fetch($tasktoclone->id);
1946
1947 //manage new parent clone task id
1948 // if the current task has child we store the original task id and the equivalent clone task id
1949 if (($taskstatic->hasChildren()) && !array_key_exists($tasktoclone->id, $tab_conv_child_parent)) {
1950 $tab_conv_child_parent[$tasktoclone->id] = $new_task_id;
1951 }
1952 }
1953 }
1954
1955 //Parse all clone node to be sure to update new parent
1956 $tasksarray = $taskstatic->getTasksArray(null, null, $clone_project_id, $socid, 0);
1957 foreach ($tasksarray as $task_cloned) {
1958 $taskstatic->fetch($task_cloned->id);
1959 if ($taskstatic->fk_task_parent != 0) {
1960 $taskstatic->fk_task_parent = $tab_conv_child_parent[$taskstatic->fk_task_parent];
1961 }
1962 $res = $taskstatic->update($user, $notrigger);
1963 if ($result_clone <= 0) {
1964 $this->error .= $taskstatic->error;
1965 $error++;
1966 }
1967 }
1968 }
1969 }
1970
1971 unset($clone_project->context['createfromclone']);
1972
1973 if (!$error && $clone_project_id != 0) {
1974 $this->db->commit();
1975 return $clone_project_id;
1976 } else {
1977 $this->db->rollback();
1978 dol_syslog(get_class($this)."::createFromClone nbError: ".$error." error : ".$this->error, LOG_ERR);
1979 return -1;
1980 }
1981 }
1982
1983
1990 public function shiftTaskDate($old_project_dt_start)
1991 {
1992 global $user, $langs, $conf;
1993
1994 $error = 0;
1995 $result = 0;
1996
1997 $taskstatic = new Task($this->db);
1998
1999 // Security check
2000 $socid = 0;
2001 if ($user->socid > 0) {
2002 $socid = $user->socid;
2003 }
2004
2005 $tasksarray = $taskstatic->getTasksArray(null, null, $this->id, $socid, 0);
2006
2007 foreach ($tasksarray as $tasktoshiftdate) {
2008 $to_update = false;
2009 // Fetch only if update of date will be made
2010 if ((!empty($tasktoshiftdate->date_start)) || (!empty($tasktoshiftdate->date_end))) {
2011 //dol_syslog(get_class($this)."::shiftTaskDate to_update", LOG_DEBUG);
2012 $to_update = true;
2013 $task = new Task($this->db);
2014 $result = $task->fetch($tasktoshiftdate->id);
2015 if (!$result) {
2016 $error++;
2017 $this->error .= $task->error;
2018 }
2019 } else {
2020 continue;
2021 }
2022 //print "$this->date_start + $tasktoshiftdate->date_start - $old_project_dt_start";exit;
2023
2024 //Calculate new task start date with difference between old proj start date and origin task start date
2025 if (!empty($tasktoshiftdate->date_start)) {
2026 $task->date_start = $this->date_start + ($tasktoshiftdate->date_start - $old_project_dt_start);
2027 }
2028
2029 //Calculate new task end date with difference between origin proj end date and origin task end date
2030 if (!empty($tasktoshiftdate->date_end)) {
2031 $task->date_end = $this->date_start + ($tasktoshiftdate->date_end - $old_project_dt_start);
2032 }
2033
2034 if ($to_update) {
2035 $result = $task->update($user);
2036 if (!$result) {
2037 $error++;
2038 $this->error .= $task->error;
2039 }
2040 }
2041 }
2042 if ($error != 0) {
2043 return -1;
2044 }
2045 return $result;
2046 }
2047
2048
2049 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2057 public function update_element($tableName, $elementSelectId)
2058 {
2059 // phpcs:enable
2060 $sql = "UPDATE ".MAIN_DB_PREFIX.$this->db->sanitize($tableName);
2061
2062 if ($tableName == "actioncomm") {
2063 $sql .= " SET fk_project=".$this->id;
2064 $sql .= " WHERE id=".((int) $elementSelectId);
2065 } elseif (in_array($tableName, ["entrepot","mrp_mo","stocktransfer_stocktransfer"])) {
2066 $sql .= " SET fk_project=".$this->id;
2067 $sql .= " WHERE rowid=".((int) $elementSelectId);
2068 } else {
2069 $sql .= " SET fk_projet=".$this->id;
2070 $sql .= " WHERE rowid=".((int) $elementSelectId);
2071 }
2072
2073 dol_syslog(get_class($this)."::update_element", LOG_DEBUG);
2074 $resql = $this->db->query($sql);
2075 if (!$resql) {
2076 $this->error = $this->db->lasterror();
2077 return -1;
2078 } else {
2079 return 1;
2080 }
2081 }
2082
2083 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2093 public function remove_element($tableName, $elementSelectId, $projectfield = 'fk_projet')
2094 {
2095 // phpcs:enable
2096 $sql = "UPDATE ".MAIN_DB_PREFIX.$this->db->sanitize($tableName);
2097
2098 if ($tableName == "actioncomm") {
2099 $sql .= " SET fk_project = NULL";
2100 $sql .= " WHERE id = ".((int) $elementSelectId);
2101 } else {
2102 $sql .= " SET ".$this->db->sanitize($projectfield)." = NULL";
2103 $sql .= " WHERE rowid = ".((int) $elementSelectId);
2104 }
2105
2106 dol_syslog(get_class($this)."::remove_element", LOG_DEBUG);
2107 $resql = $this->db->query($sql);
2108 if (!$resql) {
2109 $this->error = $this->db->lasterror();
2110 return -1;
2111 } else {
2112 return 1;
2113 }
2114 }
2115
2126 public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0)
2127 {
2128 global $conf, $langs;
2129
2130 $langs->load("projects");
2131
2132 if (!dol_strlen($modele)) {
2133 $modele = 'baleine';
2134
2135 if ($this->model_pdf) {
2136 $modele = $this->model_pdf;
2137 } elseif (getDolGlobalString('PROJECT_ADDON_PDF')) {
2138 $modele = getDolGlobalString('PROJECT_ADDON_PDF');
2139 }
2140 }
2141
2142 $modelpath = "core/modules/project/doc/";
2143
2144 return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref);
2145 }
2146
2147
2157 public function loadTimeSpent($datestart, $taskid = 0, $userid = 0)
2158 {
2159 $this->weekWorkLoad = array();
2160 $this->weekWorkLoadPerTask = array();
2161
2162 if (empty($datestart)) {
2163 dol_print_error(null, 'Error datestart parameter is empty');
2164 }
2165
2166 $sql = "SELECT ptt.rowid as taskid, ptt.element_duration, ptt.element_date, ptt.element_datehour, ptt.fk_element";
2167 $sql .= " FROM ".MAIN_DB_PREFIX."element_time AS ptt, ".MAIN_DB_PREFIX."projet_task as pt";
2168 $sql .= " WHERE ptt.fk_element = pt.rowid";
2169 $sql .= " AND ptt.elementtype = 'task'";
2170 $sql .= " AND pt.fk_projet = ".((int) $this->id);
2171 $sql .= " AND (ptt.element_date >= '".$this->db->idate($datestart)."' ";
2172 $sql .= " AND ptt.element_date <= '".$this->db->idate(dol_time_plus_duree($datestart, 1, 'w') - 1)."')";
2173 if ($taskid) {
2174 $sql .= " AND ptt.fk_element=".((int) $taskid);
2175 }
2176 if (is_numeric($userid)) {
2177 $sql .= " AND ptt.fk_user=".((int) $userid);
2178 }
2179
2180 //print $sql;
2181 $resql = $this->db->query($sql);
2182 if ($resql) {
2183 $dayallreadyfound = array();
2184
2185 $num = $this->db->num_rows($resql);
2186 $i = 0;
2187 // Loop on each record found, so each couple (project id, task id)
2188 while ($i < $num) {
2189 $obj = $this->db->fetch_object($resql);
2190 $day = $this->db->jdate($obj->element_date); // task_date is date without hours
2191 if (empty($dayallreadyfound[$day])) {
2192 $this->weekWorkLoad[$day] = $obj->element_duration;
2193 $this->weekWorkLoadPerTask[$day][$obj->fk_element] = $obj->element_duration;
2194 } else {
2195 $this->weekWorkLoad[$day] += $obj->element_duration;
2196 $this->weekWorkLoadPerTask[$day][$obj->fk_element] += $obj->element_duration;
2197 }
2198 $dayallreadyfound[$day] = 1;
2199 $i++;
2200 }
2201 $this->db->free($resql);
2202 return 1;
2203 } else {
2204 $this->error = "Error ".$this->db->lasterror();
2205 dol_syslog(get_class($this)."::fetch ".$this->error, LOG_ERR);
2206 return -1;
2207 }
2208 }
2209
2219 public function loadTimeSpentMonth($datestart, $taskid = 0, $userid = 0)
2220 {
2221 $this->monthWorkLoad = array();
2222 $this->monthWorkLoadPerTask = array();
2223
2224 if (empty($datestart)) {
2225 dol_print_error(null, 'Error datestart parameter is empty');
2226 }
2227
2228 $sql = "SELECT ptt.rowid as taskid, ptt.element_duration, ptt.element_date, ptt.element_datehour, ptt.fk_element";
2229 $sql .= " FROM ".MAIN_DB_PREFIX."element_time AS ptt, ".MAIN_DB_PREFIX."projet_task as pt";
2230 $sql .= " WHERE ptt.fk_element = pt.rowid";
2231 $sql .= " AND ptt.elementtype = 'task'";
2232 $sql .= " AND pt.fk_projet = ".((int) $this->id);
2233 $sql .= " AND (ptt.element_date >= '".$this->db->idate($datestart)."' ";
2234 $sql .= " AND ptt.element_date <= '".$this->db->idate(dol_time_plus_duree($datestart, 1, 'm') - 1)."')";
2235 if ($taskid) {
2236 $sql .= " AND ptt.fk_element=".((int) $taskid);
2237 }
2238 if (is_numeric($userid)) {
2239 $sql .= " AND ptt.fk_user=".((int) $userid);
2240 }
2241
2242 //print $sql;
2243 $resql = $this->db->query($sql);
2244 if ($resql) {
2245 $weekalreadyfound = array();
2246
2247 $num = $this->db->num_rows($resql);
2248 $i = 0;
2249 $week_number = ''; // Initialisation for static analysis
2250 // Loop on each record found, so each couple (project id, task id)
2251 while ($i < $num) {
2252 $obj = $this->db->fetch_object($resql);
2253 if (!empty($obj->element_date)) {
2254 $date = explode('-', $obj->element_date);
2255 $week_number = getWeekNumber((int) $date[2], (int) $date[1], (int) $date[0]);
2256 }
2257 if (empty($weekalreadyfound[$week_number])) {
2258 $this->monthWorkLoad[$week_number] = $obj->element_duration;
2259 $this->monthWorkLoadPerTask[$week_number][$obj->fk_element] = $obj->element_duration;
2260 } else {
2261 $this->monthWorkLoad[$week_number] += $obj->element_duration;
2262 if (!isset($this->monthWorkLoadPerTask[$week_number][$obj->fk_element])) {
2263 $this->monthWorkLoadPerTask[$week_number][$obj->fk_element] = 0;
2264 }
2265 $this->monthWorkLoadPerTask[$week_number][$obj->fk_element] += $obj->element_duration;
2266 }
2267 $weekalreadyfound[$week_number] = 1;
2268 $i++;
2269 }
2270 $this->db->free($resql);
2271 return 1;
2272 } else {
2273 $this->error = "Error ".$this->db->lasterror();
2274 dol_syslog(get_class($this)."::fetch ".$this->error, LOG_ERR);
2275 return -1;
2276 }
2277 }
2278
2279 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2286 public function load_board($user)
2287 {
2288 // phpcs:enable
2289 global $conf, $langs;
2290
2291 // For external user, no check is done on company because readability is managed by public status of project and assignment.
2292 //$socid=$user->socid;
2293
2294 $response = new WorkboardResponse();
2295 $response->warning_delay = $conf->project->warning_delay / 60 / 60 / 24;
2296 $response->label = $langs->trans("OpenedProjects");
2297 $response->labelShort = $langs->trans("Opened");
2298 $response->url = DOL_URL_ROOT.'/projet/list.php?search_project_user=-1&search_status=1&mainmenu=project';
2299 $response->url_late = DOL_URL_ROOT.'/projet/list.php?search_option=late&mainmenu=project';
2300 $response->img = img_object('', "projectpub");
2301 $response->nbtodo = 0;
2302 $response->nbtodolate = 0;
2303
2304 $sql = "SELECT p.rowid, p.fk_statut as status, p.fk_opp_status, p.datee as datee";
2305 $sql .= " FROM (".MAIN_DB_PREFIX."projet as p";
2306 $sql .= ")";
2307 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s on p.fk_soc = s.rowid";
2308 // For external user, no check is done on company permission because readability is managed by public status of project and assignment.
2309 //if (! $user->rights->societe->client->voir && ! $socid) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON sc.fk_soc = s.rowid";
2310 $sql .= " WHERE p.fk_statut = 1";
2311 $sql .= " AND p.entity IN (".getEntity('project').')';
2312
2313
2314 $projectsListId = null;
2315 if (!$user->hasRight("projet", "all", "lire")) {
2316 $response->url = DOL_URL_ROOT.'/projet/list.php?search_status=1&mainmenu=project';
2317 $projectsListId = $this->getProjectsAuthorizedForUser($user, 0, 1);
2318 if (empty($projectsListId)) {
2319 return $response;
2320 }
2321
2322 $sql .= " AND p.rowid IN (".$this->db->sanitize($projectsListId).")";
2323 }
2324
2325 // No need to check company, as filtering of projects must be done by getProjectsAuthorizedForUser
2326 //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).")";
2327 // For external user, no check is done on company permission because readability is managed by public status of project and assignment.
2328 //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))";
2329
2330 //print $sql;
2331 $resql = $this->db->query($sql);
2332 if ($resql) {
2333 $project_static = new Project($this->db);
2334
2335
2336 // This assignment in condition is not a bug. It allows walking the results.
2337 while ($obj = $this->db->fetch_object($resql)) {
2338 $response->nbtodo++;
2339
2340 $project_static->statut = $obj->status;
2341 $project_static->status = $obj->status;
2342 $project_static->opp_status = $obj->fk_opp_status;
2343 $project_static->date_end = $this->db->jdate($obj->datee);
2344
2345 if ($project_static->hasDelay()) {
2346 $response->nbtodolate++;
2347 }
2348 }
2349
2350 return $response;
2351 }
2352
2353 $this->error = $this->db->error();
2354 return -1;
2355 }
2356
2365 public static function replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
2366 {
2367 $tables = array(
2368 'projet'
2369 );
2370
2371 return CommonObject::commonReplaceThirdparty($dbs, $origin_id, $dest_id, $tables);
2372 }
2373
2374
2380 public function loadStateBoard()
2381 {
2382 global $user;
2383
2384 $this->nb = array();
2385
2386 $sql = "SELECT count(p.rowid) as nb";
2387 $sql .= " FROM ".MAIN_DB_PREFIX."projet as p";
2388 $sql .= " WHERE";
2389 $sql .= " p.entity IN (".getEntity('project').")";
2390 if (!$user->hasRight('projet', 'all', 'lire')) {
2391 $projectsListId = $this->getProjectsAuthorizedForUser($user, 0, 1);
2392 $sql .= "AND p.rowid IN (".$this->db->sanitize($projectsListId).")";
2393 }
2394
2395 $resql = $this->db->query($sql);
2396 if ($resql) {
2397 while ($obj = $this->db->fetch_object($resql)) {
2398 $this->nb["projects"] = $obj->nb;
2399 }
2400 $this->db->free($resql);
2401 return 1;
2402 } else {
2403 dol_print_error($this->db);
2404 $this->error = $this->db->error();
2405 return -1;
2406 }
2407 }
2408
2409
2415 public function hasDelay()
2416 {
2417 global $conf;
2418
2419 if (!($this->status == self::STATUS_VALIDATED)) {
2420 return false;
2421 }
2422 if (!$this->date_end) {
2423 return false;
2424 }
2425
2426 $now = dol_now();
2427
2428 return ($this->date_end) < ($now - $conf->project->warning_delay);
2429 }
2430
2431
2438 public function info($id)
2439 {
2440 $sql = 'SELECT c.rowid, datec as datec, tms as datem,';
2441 $sql .= ' date_close as datecloture,';
2442 $sql .= ' fk_user_creat as fk_user_author, fk_user_close as fk_user_cloture';
2443 $sql .= ' FROM '.MAIN_DB_PREFIX.'projet as c';
2444 $sql .= ' WHERE c.rowid = '.((int) $id);
2445 $result = $this->db->query($sql);
2446 if ($result) {
2447 if ($this->db->num_rows($result)) {
2448 $obj = $this->db->fetch_object($result);
2449
2450 $this->id = $obj->rowid;
2451
2452 $this->user_creation_id = $obj->fk_user_author;
2453 $this->user_closing_id = $obj->fk_user_cloture;
2454
2455 $this->date_creation = $this->db->jdate($obj->datec);
2456 $this->date_modification = $this->db->jdate($obj->datem);
2457 $this->date_cloture = $this->db->jdate($obj->datecloture);
2458 }
2459
2460 $this->db->free($result);
2461 } else {
2462 dol_print_error($this->db);
2463 }
2464 }
2465
2476 public function setCategories($categories)
2477 {
2478 require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
2479 return parent::setCategoriesCommon($categories, Categorie::TYPE_PROJECT);
2480 }
2481
2482
2490 public function getLinesArray($user, $loadRoleMode = 1)
2491 {
2492 require_once DOL_DOCUMENT_ROOT.'/projet/class/task.class.php';
2493 $taskstatic = new Task($this->db);
2494
2495 $this->lines = $taskstatic->getTasksArray(null, $user, $this->id, 0, 0, '', '-1', '', 0, 0, null, 0, array(), 0, $loadRoleMode);
2496 return 1;
2497 }
2498
2517 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 = '')
2518 {
2519 // TODO EMAIL
2520
2521 return 1;
2522 }
2523
2532 public function getKanbanView($option = '', $arraydata = null, $size = '')
2533 {
2534 global $conf, $langs;
2535
2536 $selected = (empty($arraydata['selected']) ? 0 : $arraydata['selected']);
2537
2538 if (empty($size)) {
2539 if (empty($conf->dol_optimize_smallscreen)) {
2540 $size = 'large';
2541 } else {
2542 $size = 'small';
2543 }
2544 }
2545
2546 $return = '<div class="box-flex-item '.($size == 'small' ? 'box-flex-item-small' : '').' box-flex-grow-zero '.($arraydata['mode'] == 'kanbangroupby' ? 'kanban-draggable" data-itemid="'.$this->id.'" data-element="'.$this->element.'" data-tableelement="'.$this->table_element.'"' : '"').'>';
2547 $return .= '<div class="info-box info-box-sm">';
2548 $return .= '<span class="info-box-icon bg-infobox-action">';
2549 $return .= img_picto('', $this->public ? 'projectpub' : $this->picto);
2550 //$return .= '<i class="fa fa-dol-action"></i>'; // Can be image
2551 $return .= '</span>';
2552 $return .= '<div class="info-box-content">';
2553 $return .= '<span class="info-box-ref inline-block tdoverflowmax150 valignmiddle">'.(method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref);
2554 if ($this->hasDelay()) {
2555 $return .= img_warning($langs->trans('Late'));
2556 }
2557 $return .= '</span>';
2558 if ($selected >= 0) {
2559 $return .= '<input id="cb'.$this->id.'" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="'.$this->id.'"'.($selected ? ' checked="checked"' : '').'>';
2560 }
2561 // Date
2562 /*
2563 if (property_exists($this, 'date_start') && $this->date_start) {
2564 $return .= '<br><span class="info-box-label">'.dol_print_date($this->date_start, 'day').'</>';
2565 }
2566 if (property_exists($this, 'date_end') && $this->date_end) {
2567 if ($this->date_start) {
2568 $return .= ' - ';
2569 } else {
2570 $return .= '<br>';
2571 }
2572 $return .= '<span class="info-box-label">'.dol_print_date($this->date_end, 'day').'</span>';
2573 }*/
2574 if (property_exists($this, 'thirdparty') && !is_null($this->thirdparty) && is_object($this->thirdparty) && $this->thirdparty instanceof Societe && $this->thirdparty->id > 0) {
2575 $return .= '<br><div class="info-box-ref tdoverflowmax125 inline-block valignmiddle">'.$this->thirdparty->getNomUrl(1);
2576 $return .= '</div>';
2577 if (!empty($this->thirdparty->phone)) {
2578 $return .= '<div class="inline-block valignmiddle">';
2579 $return .= dol_print_phone($this->thirdparty->phone, $this->thirdparty->country_code, 0, $this->thirdparty->id, 'tel', 'hidenum', 'phone', $this->thirdparty->phone, 0, 'paddingleft paddingright'); // @phan-suppress-current-line PhanPluginSuspiciousParamPosition
2580 $return .= '</div>';
2581 }
2582 if (!empty($this->thirdparty->email)) {
2583 $return .= '<div class="inline-block valignmiddle">';
2584 $return .= dol_print_email($this->thirdparty->email, 0, $this->thirdparty->id, 'thirdparty', -1, 1, 2, 'paddingleft paddingright');
2585 $return .= '</div>';
2586 }
2587 }
2588 if (!empty($arraydata['assignedusers'])) {
2589 $return .= '<br>';
2590 if ($this->public) {
2591 $return .= img_picto($langs->trans('Visibility').': '.$langs->trans('SharedProject'), 'world', 'class="paddingrightonly valignmiddle"');
2592 //print $langs->trans('SharedProject');
2593 } else {
2594 $return .= img_picto($langs->trans('Visibility').': '.$langs->trans('PrivateProject'), 'private', 'class="paddingrightonly valignmiddle"');
2595 //print $langs->trans('PrivateProject');
2596 }
2597
2598 $return .= ' <span class="small valignmiddle">'.$arraydata['assignedusers'].'</span>';
2599 }
2600 /*if (property_exists($this, 'user_author_id')) {
2601 $return .= '<br><span class="info-box-label opacitymedium">'.$langs->trans("Author").'</span>';
2602 $return .= '<span> : '.$user->getNomUrl(1).'</span>';
2603 }*/
2604 $return .= '<br><div>'; // start div line status
2605 if ($this->usage_opportunity && $this->opp_status_code) {
2606 //$return .= '<br><span class="info-bo-label opacitymedium">'.$langs->trans("OpportunityStatusShort").'</span>';
2607 //$return .= '<div class="small inline-block">'.dol_trunc($langs->trans("OppStatus".$this->opp_status_code), 5).'</div>';
2608 $return .= '<div class="opacitymedium small marginrightonly inline-block" title="'.dol_escape_htmltag($langs->trans("OppStatus".$this->opp_status_code)).'">'.round($this->opp_percent).'%</div>';
2609 $return .= ' <div class="amount small marginrightonly inline-block">'.price($this->opp_amount).'</div>';
2610 }
2611 if (method_exists($this, 'getLibStatut')) {
2612 $return .= '<div class="info-box-status small inline-block valignmiddle">'.$this->getLibStatut(3).'</div>';
2613 }
2614 $return .= '</div>'; // end div line status
2615
2616 $return .= '</div>';
2617 $return .= '</div>';
2618 $return .= '</div>';
2619
2620 return $return;
2621 }
2622
2628 public function getChildren()
2629 {
2630 $children = [];
2631 $sql = 'SELECT rowid,title';
2632 $sql .= ' FROM '.MAIN_DB_PREFIX.'projet';
2633 $sql .= ' WHERE fk_project = '.((int) $this->id);
2634 $sql .= ' ORDER BY title';
2635 $result = $this->db->query($sql);
2636 if ($result) {
2637 $n = $this->db->num_rows($result);
2638 while ($n) {
2639 $children[] = $this->db->fetch_object($result);
2640 $n--;
2641 }
2642 $this->db->free($result);
2643 } else {
2644 dol_print_error($this->db);
2645 }
2646
2647 return $children;
2648 }
2649
2655 public function createWeeklyReport()
2656 {
2657 global $mysoc, $user, $langs;
2658
2659 $now = dol_now();
2660 $nowDate = dol_getdate($now, true);
2661
2662 $errormesg = '';
2663 $errorsMsg = array();
2664
2665 $firstDayOfWeekTS = dol_get_first_day_week($nowDate['mday'], $nowDate['mon'], $nowDate['year']);
2666
2667 $firstDayOfWeekDate = dol_mktime(0, 0, 0, $nowDate['mon'], $firstDayOfWeekTS['first_day'], $nowDate['year']);
2668
2669 $lastWeekStartTS = dol_time_plus_duree($firstDayOfWeekDate, -7, 'd');
2670
2671 $lastWeekEndTS = dol_time_plus_duree($lastWeekStartTS, 6, 'd');
2672
2673 $startDate = dol_print_date($lastWeekStartTS, '%Y-%m-%d 00:00:00');
2674 $endDate = dol_print_date($lastWeekEndTS, '%Y-%m-%d 23:59:59');
2675
2676 $sql = "SELECT
2677 u.rowid AS user_id,
2678 CONCAT(u.firstname, ' ', u.lastname) AS name,
2679 u.email,u.weeklyhours,
2680 SUM(et.element_duration) AS total_seconds
2681 FROM
2682 ".MAIN_DB_PREFIX."element_time AS et
2683 JOIN
2684 ".MAIN_DB_PREFIX."user AS u ON et.fk_user = u.rowid
2685 WHERE
2686 et.element_date BETWEEN '".$this->db->escape($startDate)."' AND '".$this->db->escape($endDate)."'
2687 AND et.elementtype = 'task'
2688 GROUP BY
2689 et.fk_user";
2690
2691 $resql = $this->db->query($sql);
2692 if (!$resql) {
2693 dol_print_error($this->db);
2694 return -1;
2695 } else {
2696 $reportContent = "<span>Weekly time report from $startDate to $endDate </span><br><br>";
2697 $reportContent .= '<table border="1" style="border-collapse: collapse;">';
2698 $reportContent .= '<tr><th>'.$langs->trans("User").'</th><th>Temps saisi (heures)</th><th>Temps travaillé par semaine (heures)</th></tr>';
2699
2700 $to = '';
2701 $nbMailSend = 0;
2702 $error = 0;
2703 $errors_to = '';
2704 while ($obj = $this->db->fetch_object($resql)) {
2705 $to = $obj->email;
2706
2707 $weekendEnabled = 0;
2708 $numHolidays = num_public_holiday($lastWeekStartTS, $lastWeekEndTS, $mysoc->country_code, 1);
2709 if (getDolGlobalString('MAIN_NON_WORKING_DAYS_INCLUDE_MONDAY')) {
2710 $numHolidays -= 1;
2711 $weekendEnabled += 1;
2712 }
2713 if (getDolGlobalString('MAIN_NON_WORKING_DAYS_INCLUDE_TUESDAY')) {
2714 $numHolidays -= 1;
2715 $weekendEnabled += 1;
2716 }
2717 if (getDolGlobalString('MAIN_NON_WORKING_DAYS_INCLUDE_SATURDAY')) {
2718 $numHolidays -= 1;
2719 $weekendEnabled += 1;
2720 }
2721 if (getDolGlobalString('MAIN_NON_WORKING_DAYS_INCLUDE_SUNDAY')) {
2722 $numHolidays -= 1;
2723 $weekendEnabled += 1;
2724 }
2725
2726 $dailyHours = $obj->weeklyhours / (7 - $weekendEnabled);
2727
2728 // Adjust total on seconde
2729 $adjustedSeconds = $obj->total_seconds + ($numHolidays * $dailyHours * 3600);
2730
2731 $totalHours = round($adjustedSeconds / 3600, 2);
2732
2733 $reportContent .= "<tr><td>{$obj->name}</td><td>{$totalHours}</td><td>".round($obj->weeklyhours, 2)."</td></tr>";
2734
2735 $reportContent .= '</table>';
2736
2737 require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
2738
2739 // PREPARE EMAIL
2740 $errormesg = '';
2741
2742 $subject = 'Rapport hebdomadaire des temps travaillés';
2743
2744 $from = getDolGlobalString('MAIN_MAIL_EMAIL_FROM');
2745 if (empty($from)) {
2746 $errormesg = "Failed to get sender into global setup MAIN_MAIL_EMAIL_FROM";
2747 $error++;
2748 }
2749
2750 $mail = new CMailFile($subject, $to, $from, $reportContent, array(), array(), array(), '', '', 0, -1, '', '', '', 'text/html');
2751
2752 if ($mail->sendfile()) {
2753 $nbMailSend++;
2754
2755 // Add a line into event table
2756 require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php';
2757
2758 // Insert record of emails sent
2759 $actioncomm = new ActionComm($this->db);
2760
2761 $actioncomm->type_code = 'AC_OTH_AUTO'; // Event insert into agenda automatically
2762 $actioncomm->socid = $this->thirdparty->id; // To link to a company
2763 $actioncomm->contact_id = 0;
2764
2765 $actioncomm->code = 'AC_EMAIL';
2766 $actioncomm->label = 'createWeeklyReportOK()';
2767 $actioncomm->fk_project = $this->id;
2768 $actioncomm->datep = dol_now();
2769 $actioncomm->datef = $actioncomm->datep;
2770 $actioncomm->percentage = -1; // Not applicable
2771 $actioncomm->authorid = $user->id; // User saving action
2772 $actioncomm->userownerid = $user->id; // Owner of action
2773 // Fields when action is an email (content should be added into note)
2774 $actioncomm->email_msgid = $mail->msgid;
2775 $actioncomm->email_subject = $subject;
2776 $actioncomm->email_from = $from;
2777 $actioncomm->email_sender = '';
2778 $actioncomm->email_to = $to;
2779
2780 $actioncomm->errors_to = $errors_to;
2781
2782 $actioncomm->elementtype = 'project_task';
2783 $actioncomm->fk_element = (int) $this->element;
2784
2785 $actioncomm->create($user);
2786 } else {
2787 $errormesg = $mail->error.' : '.$to;
2788 $error++;
2789
2790 // Add a line into event table
2791 require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php';
2792
2793 // Insert record of emails sent
2794 $actioncomm = new ActionComm($this->db);
2795
2796 $actioncomm->type_code = 'AC_OTH_AUTO'; // Event insert into agenda automatically
2797 $actioncomm->socid = $this->thirdparty->id; // To link to a company
2798 $actioncomm->contact_id = 0;
2799
2800 $actioncomm->code = 'AC_EMAIL';
2801 $actioncomm->label = 'createWeeklyReportKO()';
2802 $actioncomm->note_private = $errormesg;
2803 $actioncomm->fk_project = $this->id;
2804 $actioncomm->datep = dol_now();
2805 $actioncomm->datef = $actioncomm->datep;
2806 $actioncomm->authorid = $user->id; // User saving action
2807 $actioncomm->userownerid = $user->id; // Owner of action
2808 // Fields when action is an email (content should be added into note)
2809 $actioncomm->email_msgid = $mail->msgid;
2810 $actioncomm->email_from = $from;
2811 $actioncomm->email_sender = '';
2812 $actioncomm->email_to = $to;
2813
2814 $actioncomm->errors_to = $errors_to;
2815
2816 $actioncomm->elementtype = 'project_task';
2817 $actioncomm->fk_element = (int) $this->element;
2818
2819 $actioncomm->create($user);
2820 }
2821 $this->db->commit();
2822 }
2823 }
2824 if (!empty($errormesg)) {
2825 $errorsMsg[] = $errormesg;
2826 }
2827
2828 if (!$error) {
2829 $this->output .= 'Nb of emails sent : '.$nbMailSend;
2830 dol_syslog(__METHOD__." end - ".$this->output, LOG_INFO);
2831 return 0;
2832 } else {
2833 $this->error = 'Nb of emails sent : '.$nbMailSend.', '.(empty($errorsMsg) ? $error : implode(', ', $errorsMsg));
2834 dol_syslog(__METHOD__." end - ".$this->error, LOG_INFO);
2835 return $error;
2836 }
2837 }
2838}
$object ref
Definition info.php:90
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.
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 optional picto)
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.
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 clickable 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.
print $langs trans("Ref").' m titre as m m statut as status
Or an array listing all the potential status of the object: array: int of the status => translated la...
Definition index.php:171
dol_get_first_day_week($day, $month, $year, $gm=false)
Return first day of week for a date.
Definition date.lib.php:675
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:125
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:769
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_copy($srcfile, $destfile, $newmask='0', $overwriteifexists=1, $testvirus=0, $indexdatabase=0)
Copy a file to another file.
dol_delete_dir_recursive($dir, $count=0, $nophperrors=0, $onlysub=0, &$countdeleted=0, $indexdatabase=1, $nolog=0, $level=0)
Remove a directory $dir and its subdirectories (or only files and subdirectories)
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_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2, $allowothertags=array())
Show picto whatever it's its name (generic function)
img_warning($titlealt='default', $moreatt='', $morecss='pictowarning')
Show warning logo.
dol_print_phone($phone, $countrycode='', $cid=0, $socid=0, $addlink='', $separ="&nbsp;", $withpicto='', $titlealt='', $adddivfloat=0, $morecss='paddingright')
Format phone numbers according to country.
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.
img_object($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $allowothertags=array())
Show a picto called object_picto (generic function)
dol_strlen($string, $stringencoding='UTF-8')
Make a strlen call.
forgeSQLFromUniversalSearchCriteria($filter, &$errorstr='', $noand=0, $nopar=0, $noerror=0)
forgeSQLFromUniversalSearchCriteria
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_print_email($email, $cid=0, $socid=0, $addlink=0, $max=64, $showinvalid=1, $withpicto=0, $morecss='paddingrightonly')
Show EMail link formatted for HTML output.
dolGetStatus($statusLabel='', $statusLabelShort='', $html='', $statusType='status0', $displayMode=0, $url='', $params=array())
Output the badge of a status.
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_print_error($db=null, $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
dol_sanitizeFileName($str, $newstr='_', $unaccent=1, $includequotes=0)
Clean a string to use it as a file name.
getDolGlobalString($key, $default='')
Return a 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)
global $conf
The following vars must be defined: $type2label $form $conf, $lang, The following vars may also be de...
Definition member.php:79