Passed
Branch develop (27134a)
by
unknown
40:37
created

Notify::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
c 0
b 0
f 0
nc 1
nop 1
dl 0
loc 3
rs 10
1
<?php
2
/* Copyright (C) 2003-2005 Rodolphe Quiedeville <[email protected]>
3
 * Copyright (C) 2004-2011 Laurent Destailleur  <[email protected]>
4
 * Copyright (C) 2014	   Juanjo Menent		<[email protected]>
5
 * Copyright (C) 2018 	   Philippe Grand		<[email protected]>
6
 * Copyright (C) 2021 	   Thibault FOUCART		<[email protected]>
7
 *
8
 * This program is free software; you can redistribute it and/or modify
9
 * it under the terms of the GNU General Public License as published by
10
 * the Free Software Foundation; either version 3 of the License, or
11
 * (at your option) any later version.
12
 *
13
 * This program is distributed in the hope that it will be useful,
14
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16
 * GNU General Public License for more details.
17
 *
18
 * You should have received a copy of the GNU General Public License
19
 * along with this program. If not, see <https://www.gnu.org/licenses/>.
20
 */
21
22
/**
23
 *      \file       htdocs/core/class/notify.class.php
24
 *      \ingroup    notification
25
 *      \brief      File of class to manage notifications
26
 */
27
require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
28
29
/**
30
 *      Class to manage notifications
31
 */
32
class Notify
33
{
34
	/**
35
	 * @var int ID
36
	 */
37
	public $id;
38
39
	/**
40
	 * @var DoliDB Database handler.
41
	 */
42
	public $db;
43
44
	/**
45
	 * @var string Error code (or message)
46
	 */
47
	public $error = '';
48
49
	/**
50
	 * @var string[] Error codes (or messages)
51
	 */
52
	public $errors = array();
53
54
	public $author;
55
	public $ref;
56
	public $date;
57
	public $duree;
58
	public $note;
59
60
	/**
61
	 * @var int Project ID
62
	 */
63
	public $fk_project;
64
65
	// This codes actions are defined into table llx_notify_def
66
	static public $arrayofnotifsupported = array(
67
		'BILL_VALIDATE',
68
		'BILL_PAYED',
69
		'ORDER_CREATE',
70
		'ORDER_VALIDATE',
71
		'PROPAL_VALIDATE',
72
		'PROPAL_CLOSE_SIGNED',
73
		'FICHINTER_VALIDATE',
74
		'FICHINTER_ADD_CONTACT',
75
		'ORDER_SUPPLIER_VALIDATE',
76
		'ORDER_SUPPLIER_APPROVE',
77
		'ORDER_SUPPLIER_REFUSE',
78
		'SHIPPING_VALIDATE',
79
		'EXPENSE_REPORT_VALIDATE',
80
		'EXPENSE_REPORT_APPROVE',
81
		'HOLIDAY_VALIDATE',
82
		'HOLIDAY_APPROVE',
83
		'ACTION_CREATE'
84
	);
85
86
	/**
87
	 *	Constructor
88
	 *
89
	 *	@param 		DoliDB		$db		Database handler
90
	 */
91
	public function __construct($db)
92
	{
93
		$this->db = $db;
94
	}
95
96
97
	/**
98
	 *  Return message that say how many notification (and to which email) will occurs on requested event.
99
	 *	This is to show confirmation messages before event is recorded.
100
	 *
101
	 * 	@param	string	$action		Id of action in llx_c_action_trigger
102
	 * 	@param	int		$socid		Id of third party
103
	 *  @param	Object	$object		Object the notification is about
104
	 *	@return	string				Message
105
	 */
106
	public function confirmMessage($action, $socid, $object)
107
	{
108
		global $conf, $langs;
109
		$langs->load("mails");
110
111
		// Get full list of all notifications subscribed for $action, $socid and $object
112
		$listofnotiftodo = $this->getNotificationsArray($action, $socid, $object, 0);
113
114
		if (!empty($conf->global->NOTIFICATION_EMAIL_DISABLE_CONFIRM_MESSAGE_USER)) {
115
			foreach ($listofnotiftodo as $val) {
116
				if ($val['type'] == 'touser') {
117
					unset($listofnotiftodo[$val['email']]);
118
					//$listofnotiftodo = array_merge($listofnotiftodo);
119
				}
120
			}
121
		}
122
		if (!empty($conf->global->NOTIFICATION_EMAIL_DISABLE_CONFIRM_MESSAGE_CONTACT)) {
123
			foreach ($listofnotiftodo as $val) {
124
				if ($val['type'] == 'tocontact') {
125
					unset($listofnotiftodo[$val['email']]);
126
					//$listofnotiftodo = array_merge($listofnotiftodo);
127
				}
128
			}
129
		}
130
		if (!empty($conf->global->NOTIFICATION_EMAIL_DISABLE_CONFIRM_MESSAGE_FIX)) {
131
			foreach ($listofnotiftodo as $val) {
132
				if ($val['type'] == 'tofixedemail') {
133
					unset($listofnotiftodo[$val['email']]);
134
					//$listofnotiftodo = array_merge($listofnotiftodo);
135
				}
136
			}
137
		}
138
139
		$texte = '';
140
		$nb = -1;
141
		if (is_array($listofnotiftodo)) {
142
			$nb = count($listofnotiftodo);
143
		}
144
		if ($nb < 0) {
145
			$texte = img_object($langs->trans("Notifications"), 'email').' '.$langs->trans("ErrorFailedToGetListOfNotificationsToSend");
146
		} elseif ($nb == 0) {
147
			$texte = img_object($langs->trans("Notifications"), 'email').' '.$langs->trans("NoNotificationsWillBeSent");
148
		} elseif ($nb == 1) {
149
			$texte = img_object($langs->trans("Notifications"), 'email').' '.$langs->trans("ANotificationsWillBeSent");
150
		} elseif ($nb >= 2) {
151
			$texte = img_object($langs->trans("Notifications"), 'email').' '.$langs->trans("SomeNotificationsWillBeSent", $nb);
152
		}
153
154
		if (is_array($listofnotiftodo)) {
155
			$i = 0;
156
			foreach ($listofnotiftodo as $val) {
157
				if ($i) {
158
					$texte .= ', ';
159
				} else {
160
					$texte .= ' (';
161
				}
162
				if ($val['isemailvalid']) {
163
					$texte .= $val['email'];
164
				} else {
165
					$texte .= $val['emaildesc'];
166
				}
167
				$i++;
168
			}
169
			if ($i) {
170
				$texte .= ')';
171
			}
172
		}
173
174
		return $texte;
175
	}
176
177
	/**
178
	 * Return number of notifications activated for action code (and third party)
179
	 *
180
	 * @param	string	$notifcode		Code of action in llx_c_action_trigger (new usage) or Id of action in llx_c_action_trigger (old usage)
181
	 * @param	int		$socid			Id of third party or 0 for all thirdparties or -1 for no thirdparties
182
	 * @param	Object	$object			Object the notification is about (need it to check threshold value of some notifications)
183
	 * @param	int		$userid         Id of user or 0 for all users or -1 for no users
184
	 * @param   array   $scope          Scope where to search
185
	 * @return	array|int				<0 if KO, array of notifications to send if OK
186
	 */
187
	public function getNotificationsArray($notifcode, $socid = 0, $object = null, $userid = 0, $scope = array('thirdparty', 'user', 'global'))
188
	{
189
		global $conf, $user;
190
191
		$error = 0;
192
		$resarray = array();
193
194
		$valueforthreshold = 0;
195
		if (is_object($object)) {
196
			$valueforthreshold = $object->total_ht;
197
		}
198
199
		$sqlnotifcode = '';
200
		if ($notifcode) {
201
			if (is_numeric($notifcode)) {
202
				$sqlnotifcode = " AND n.fk_action = ".((int) $notifcode); // Old usage
203
			} else {
204
				$sqlnotifcode = " AND a.code = '".$this->db->escape($notifcode)."'"; // New usage
205
			}
206
		}
207
208
		if (!$error) {
209
			if ($socid >= 0 && in_array('thirdparty', $scope)) {
210
				$sql = "SELECT a.code, c.email, c.rowid";
211
				$sql .= " FROM ".MAIN_DB_PREFIX."notify_def as n,";
212
				$sql .= " ".MAIN_DB_PREFIX."socpeople as c,";
213
				$sql .= " ".MAIN_DB_PREFIX."c_action_trigger as a,";
214
				$sql .= " ".MAIN_DB_PREFIX."societe as s";
215
				$sql .= " WHERE n.fk_contact = c.rowid";
216
				$sql .= " AND a.rowid = n.fk_action";
217
				$sql .= " AND n.fk_soc = s.rowid";
218
				$sql .= $sqlnotifcode;
219
				$sql .= " AND s.entity IN (".getEntity('societe').")";
220
				if ($socid > 0) {
221
					$sql .= " AND s.rowid = ".((int) $socid);
222
				}
223
224
				dol_syslog(__METHOD__." ".$notifcode.", ".$socid."", LOG_DEBUG);
225
226
				$resql = $this->db->query($sql);
227
				if ($resql) {
228
					$num = $this->db->num_rows($resql);
229
					$i = 0;
230
					while ($i < $num) {
231
						$obj = $this->db->fetch_object($resql);
232
						if ($obj) {
233
							$newval2 = trim($obj->email);
234
							$isvalid = isValidEmail($newval2);
235
							if (empty($resarray[$newval2])) {
236
								$resarray[$newval2] = array('type'=> 'tocontact', 'code'=>trim($obj->code), 'emaildesc'=>'Contact id '.$obj->rowid, 'email'=>$newval2, 'contactid'=>$obj->rowid, 'isemailvalid'=>$isvalid);
237
							}
238
						}
239
						$i++;
240
					}
241
				} else {
242
					$error++;
243
					$this->error = $this->db->lasterror();
244
				}
245
			}
246
		}
247
248
		if (!$error) {
249
			if ($userid >= 0 && in_array('user', $scope)) {
250
				$sql = "SELECT a.code, c.email, c.rowid";
251
				$sql .= " FROM ".MAIN_DB_PREFIX."notify_def as n,";
252
				$sql .= " ".MAIN_DB_PREFIX."user as c,";
253
				$sql .= " ".MAIN_DB_PREFIX."c_action_trigger as a";
254
				$sql .= " WHERE n.fk_user = c.rowid";
255
				$sql .= " AND a.rowid = n.fk_action";
256
				$sql .= $sqlnotifcode;
257
				$sql .= " AND c.entity IN (".getEntity('user').")";
258
				if ($userid > 0) {
259
					$sql .= " AND c.rowid = ".((int) $userid);
260
				}
261
262
				dol_syslog(__METHOD__." ".$notifcode.", ".$socid."", LOG_DEBUG);
263
264
				$resql = $this->db->query($sql);
265
				if ($resql) {
266
					$num = $this->db->num_rows($resql);
267
					$i = 0;
268
					while ($i < $num) {
269
						$obj = $this->db->fetch_object($resql);
270
						if ($obj) {
271
							$newval2 = trim($obj->email);
272
							$isvalid = isValidEmail($newval2);
273
							if (empty($resarray[$newval2])) {
274
								$resarray[$newval2] = array('type'=> 'touser', 'code'=>trim($obj->code), 'emaildesc'=>'User id '.$obj->rowid, 'email'=>$newval2, 'userid'=>$obj->rowid, 'isemailvalid'=>$isvalid);
275
							}
276
						}
277
						$i++;
278
					}
279
				} else {
280
					$error++;
281
					$this->error = $this->db->lasterror();
282
				}
283
			}
284
		}
285
286
		if (!$error) {
287
			if (in_array('global', $scope)) {
288
				// List of notifications enabled for fixed email
289
				foreach ($conf->global as $key => $val) {
290
					if ($notifcode) {
291
						if ($val == '' || !preg_match('/^NOTIFICATION_FIXEDEMAIL_'.$notifcode.'_THRESHOLD_HIGHER_(.*)$/', $key, $reg)) {
292
							continue;
293
						}
294
					} else {
295
						if ($val == '' || !preg_match('/^NOTIFICATION_FIXEDEMAIL_.*_THRESHOLD_HIGHER_(.*)$/', $key, $reg)) {
296
							continue;
297
						}
298
					}
299
300
					$threshold = (float) $reg[1];
301
					if ($valueforthreshold < $threshold) {
302
						continue;
303
					}
304
305
					$tmpemail = explode(',', $val);
306
					foreach ($tmpemail as $key2 => $val2) {
307
						$newval2 = trim($val2);
308
						if ($newval2 == '__SUPERVISOREMAIL__') {
309
							if ($user->fk_user > 0) {
310
								$tmpuser = new User($this->db);
311
								$tmpuser->fetch($user->fk_user);
312
								if ($tmpuser->email) {
313
									$newval2 = trim($tmpuser->email);
314
								} else {
315
									$newval2 = '';
316
								}
317
							} else {
318
								$newval2 = '';
319
							}
320
						}
321
						if ($newval2) {
322
							$isvalid = isValidEmail($newval2, 0);
323
							if (empty($resarray[$newval2])) {
324
								$resarray[$newval2] = array('type'=> 'tofixedemail', 'code'=>trim($key), 'emaildesc'=>trim($val2), 'email'=>$newval2, 'isemailvalid'=>$isvalid);
325
							}
326
						}
327
					}
328
				}
329
			}
330
		}
331
332
		if ($error) {
333
			return -1;
334
		}
335
336
		//var_dump($resarray);
337
		return $resarray;
338
	}
339
340
	/**
341
	 *  Check if notification are active for couple action/company.
342
	 * 	If yes, send mail and save trace into llx_notify.
343
	 *
344
	 * 	@param	string	$notifcode			Code of action in llx_c_action_trigger (new usage) or Id of action in llx_c_action_trigger (old usage)
345
	 * 	@param	Object	$object				Object the notification deals on
346
	 *	@param 	array	$filename_list		List of files to attach (full path of filename on file system)
347
	 *	@param 	array	$mimetype_list		List of MIME type of attached files
348
	 *	@param 	array	$mimefilename_list	List of attached file name in message
349
	 *	@return	int							<0 if KO, or number of changes if OK
350
	 */
351
	public function send($notifcode, $object, $filename_list = array(), $mimetype_list = array(), $mimefilename_list = array())
352
	{
353
		global $user, $conf, $langs, $mysoc;
354
		global $hookmanager;
355
		global $dolibarr_main_url_root;
356
		global $action;
357
358
		if (!in_array($notifcode, Notify::$arrayofnotifsupported)) {
359
			return 0;
360
		}
361
362
		include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
363
		if (!is_object($hookmanager)) {
364
			include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
365
			$hookmanager = new HookManager($this->db);
366
		}
367
		$hookmanager->initHooks(array('notification'));
368
369
		dol_syslog(get_class($this)."::send notifcode=".$notifcode.", object=".$object->id);
370
371
		$langs->load("other");
372
373
		// Define $urlwithroot
374
		$urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
375
		$urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
376
		//$urlwithroot=DOL_MAIN_URL_ROOT;						// This is to use same domain name than current
377
378
		// Define some vars
379
		$application = 'Dolibarr';
380
		if (!empty($conf->global->MAIN_APPLICATION_TITLE)) {
381
			$application = $conf->global->MAIN_APPLICATION_TITLE;
382
		}
383
		$replyto = $conf->notification->email_from;
384
		$object_type = '';
385
		$link = '';
386
		$num = 0;
387
		$error = 0;
388
389
		$oldref = (empty($object->oldref) ? $object->ref : $object->oldref);
390
		$newref = (empty($object->newref) ? $object->ref : $object->newref);
391
392
		$sql = '';
393
394
		// Check notification per third party
395
		if (!empty($object->socid) && $object->socid > 0) {
396
			$sql .= "SELECT 'tocontactid' as type_target, c.email, c.rowid as cid, c.lastname, c.firstname, c.default_lang,";
397
			$sql .= " a.rowid as adid, a.label, a.code, n.rowid, n.type";
398
			$sql .= " FROM ".MAIN_DB_PREFIX."socpeople as c,";
399
			$sql .= " ".MAIN_DB_PREFIX."c_action_trigger as a,";
400
			$sql .= " ".MAIN_DB_PREFIX."notify_def as n,";
401
			$sql .= " ".MAIN_DB_PREFIX."societe as s";
402
			$sql .= " WHERE n.fk_contact = c.rowid AND a.rowid = n.fk_action";
403
			$sql .= " AND n.fk_soc = s.rowid";
404
			$sql .= " AND c.statut = 1";
405
			if (is_numeric($notifcode)) {
406
				$sql .= " AND n.fk_action = ".((int) $notifcode); // Old usage
407
			} else {
408
				$sql .= " AND a.code = '".$this->db->escape($notifcode)."'"; // New usage
409
			}
410
			$sql .= " AND s.rowid = ".((int) $object->socid);
411
412
			$sql .= "\nUNION\n";
413
		}
414
415
		// Check notification per user
416
		$sql .= "SELECT 'touserid' as type_target, c.email, c.rowid as cid, c.lastname, c.firstname, c.lang as default_lang,";
417
		$sql .= " a.rowid as adid, a.label, a.code, n.rowid, n.type";
418
		$sql .= " FROM ".MAIN_DB_PREFIX."user as c,";
419
		$sql .= " ".MAIN_DB_PREFIX."c_action_trigger as a,";
420
		$sql .= " ".MAIN_DB_PREFIX."notify_def as n";
421
		$sql .= " WHERE n.fk_user = c.rowid AND a.rowid = n.fk_action";
422
		$sql .= " AND c.statut = 1";
423
		if (is_numeric($notifcode)) {
424
			$sql .= " AND n.fk_action = ".((int) $notifcode); // Old usage
425
		} else {
426
			$sql .= " AND a.code = '".$this->db->escape($notifcode)."'"; // New usage
427
		}
428
429
		$result = $this->db->query($sql);
430
		if ($result) {
431
			$num = $this->db->num_rows($result);
432
			$projtitle = '';
433
			if (!empty($object->fk_project)) {
434
				require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
435
				$proj = new Project($this->db);
436
				$proj->fetch($object->fk_project);
437
				$projtitle = '('.$proj->title.')';
438
			}
439
440
			if ($num > 0) {
441
				$i = 0;
442
				while ($i < $num && !$error) {	// For each notification couple defined (third party/actioncode)
443
					$obj = $this->db->fetch_object($result);
444
445
					$sendto = dolGetFirstLastname($obj->firstname, $obj->lastname)." <".$obj->email.">";
446
					$notifcodedefid = $obj->adid;
447
					$trackid = '';
448
					if ($obj->type_target == 'tocontactid') {
449
						$trackid = 'con'.$obj->cid;
450
					}
451
					if ($obj->type_target == 'touserid') {
452
						$trackid = 'use'.$obj->cid;
453
					}
454
455
					if (dol_strlen($obj->email)) {
456
						// Set output language
457
						$outputlangs = $langs;
458
						if ($obj->default_lang && $obj->default_lang != $langs->defaultlang) {
459
							$outputlangs = new Translate('', $conf);
460
							$outputlangs->setDefaultLang($obj->default_lang);
461
							$outputlangs->loadLangs(array("main", "other"));
462
						}
463
464
						$subject = '['.$mysoc->name.'] '.$outputlangs->transnoentitiesnoconv("DolibarrNotification").($projtitle ? ' '.$projtitle : '');
465
466
						switch ($notifcode) {
467
							case 'BILL_VALIDATE':
468
								$link = '<a href="'.$urlwithroot.'/compta/facture/card.php?facid='.$object->id.'&entity='.$object->entity.'">'.$newref.'</a>';
469
								$dir_output = $conf->facture->dir_output."/".get_exdir(0, 0, 0, 1, $object, 'invoice');
470
								$object_type = 'facture';
471
								$labeltouse = $conf->global->BILL_VALIDATE_TEMPLATE;
472
								$mesg = $outputlangs->transnoentitiesnoconv("EMailTextInvoiceValidated", $link);
473
								break;
474
							case 'BILL_PAYED':
475
								$link = '<a href="'.$urlwithroot.'/compta/facture/card.php?facid='.$object->id.'&entity='.$object->entity.'">'.$newref.'</a>';
476
								$dir_output = $conf->facture->dir_output."/".get_exdir(0, 0, 0, 1, $object, 'invoice');
477
								$object_type = 'facture';
478
								$labeltouse = $conf->global->BILL_PAYED_TEMPLATE;
479
								$mesg = $outputlangs->transnoentitiesnoconv("EMailTextInvoicePayed", $link);
480
								break;
481
							case 'ORDER_VALIDATE':
482
								$link = '<a href="'.$urlwithroot.'/commande/card.php?id='.$object->id.'&entity='.$object->entity.'">'.$newref.'</a>';
483
								$dir_output = $conf->commande->dir_output."/".get_exdir(0, 0, 0, 1, $object, 'commande');
484
								$object_type = 'order';
485
								$labeltouse = $conf->global->ORDER_VALIDATE_TEMPLATE;
486
								$mesg = $outputlangs->transnoentitiesnoconv("EMailTextOrderValidated", $link);
487
								break;
488
							case 'PROPAL_VALIDATE':
489
								$link = '<a href="'.$urlwithroot.'/comm/propal/card.php?id='.$object->id.'&entity='.$object->entity.'">'.$newref.'</a>';
490
								$dir_output = $conf->propal->multidir_output[$object->entity]."/".get_exdir(0, 0, 0, 1, $object, 'propal');
491
								$object_type = 'propal';
492
								$labeltouse = $conf->global->PROPAL_VALIDATE_TEMPLATE;
493
								$mesg = $outputlangs->transnoentitiesnoconv("EMailTextProposalValidated", $link);
494
								break;
495
							case 'PROPAL_CLOSE_SIGNED':
496
								$link = '<a href="'.$urlwithroot.'/comm/propal/card.php?id='.$object->id.'&entity='.$object->entity.'">'.$newref.'</a>';
497
								$dir_output = $conf->propal->multidir_output[$object->entity]."/".get_exdir(0, 0, 0, 1, $object, 'propal');
498
								$object_type = 'propal';
499
								$labeltouse = $conf->global->PROPAL_CLOSE_SIGNED_TEMPLATE;
500
								$mesg = $outputlangs->transnoentitiesnoconv("EMailTextProposalClosedSigned", $link);
501
								break;
502
							case 'FICHINTER_ADD_CONTACT':
503
								$link = '<a href="'.$urlwithroot.'/fichinter/card.php?id='.$object->id.'&entity='.$object->entity.'">'.$newref.'</a>';
504
								$dir_output = $conf->ficheinter->dir_output;
505
								$object_type = 'ficheinter';
506
								$mesg = $outputlangs->transnoentitiesnoconv("EMailTextInterventionAddedContact", $link);
507
								break;
508
							case 'FICHINTER_VALIDATE':
509
								$link = '<a href="'.$urlwithroot.'/fichinter/card.php?id='.$object->id.'&entity='.$object->entity.'">'.$newref.'</a>';
510
								$dir_output = $conf->ficheinter->dir_output;
511
								$object_type = 'ficheinter';
512
								$mesg = $outputlangs->transnoentitiesnoconv("EMailTextInterventionValidated", $link);
513
								break;
514
							case 'ORDER_SUPPLIER_VALIDATE':
515
								$link = '<a href="'.$urlwithroot.'/fourn/commande/card.php?id='.$object->id.'&entity='.$object->entity.'">'.$newref.'</a>';
516
								$dir_output = $conf->fournisseur->commande->dir_output;
517
								$object_type = 'order_supplier';
518
								$mesg = $outputlangs->transnoentitiesnoconv("Hello").",\n\n";
519
								$mesg .= $outputlangs->transnoentitiesnoconv("EMailTextOrderValidatedBy", $link, $user->getFullName($outputlangs));
520
								$mesg .= "\n\n".$outputlangs->transnoentitiesnoconv("Sincerely").".\n\n";
521
								break;
522
							case 'ORDER_SUPPLIER_APPROVE':
523
								$link = '<a href="'.$urlwithroot.'/fourn/commande/card.php?id='.$object->id.'&entity='.$object->entity.'">'.$newref.'</a>';
524
								$dir_output = $conf->fournisseur->commande->dir_output;
525
								$object_type = 'order_supplier';
526
								$mesg = $outputlangs->transnoentitiesnoconv("Hello").",\n\n";
527
								$mesg .= $outputlangs->transnoentitiesnoconv("EMailTextOrderApprovedBy", $link, $user->getFullName($outputlangs));
528
								$mesg .= "\n\n".$outputlangs->transnoentitiesnoconv("Sincerely").".\n\n";
529
								break;
530
							case 'ORDER_SUPPLIER_REFUSE':
531
								$link = '<a href="'.$urlwithroot.'/fourn/commande/card.php?id='.$object->id.'&entity='.$object->entity.'">'.$newref.'</a>';
532
								$dir_output = $conf->fournisseur->commande->dir_output;
533
								$object_type = 'order_supplier';
534
								$mesg = $outputlangs->transnoentitiesnoconv("Hello").",\n\n";
535
								$mesg .= $outputlangs->transnoentitiesnoconv("EMailTextOrderRefusedBy", $link, $user->getFullName($outputlangs));
536
								$mesg .= "\n\n".$outputlangs->transnoentitiesnoconv("Sincerely").".\n\n";
537
								break;
538
							case 'SHIPPING_VALIDATE':
539
								$link = '<a href="'.$urlwithroot.'/expedition/card.php?id='.$object->id.'&entity='.$object->entity.'">'.$newref.'</a>';
540
								$dir_output = $conf->expedition->dir_output."/sending/".get_exdir(0, 0, 0, 1, $object, 'shipment');
541
								$object_type = 'shipping';
542
								$labeltouse = $conf->global->SHIPPING_VALIDATE_TEMPLATE;
543
								$mesg = $outputlangs->transnoentitiesnoconv("EMailTextExpeditionValidated", $link);
544
								break;
545
							case 'EXPENSE_REPORT_VALIDATE':
546
								$link = '<a href="'.$urlwithroot.'/expensereport/card.php?id='.$object->id.'&entity='.$object->entity.'">'.$newref.'</a>';
547
								$dir_output = $conf->expensereport->dir_output;
548
								$object_type = 'expensereport';
549
								$labeltouse = $conf->global->EXPENSE_REPORT_VALIDATE_TEMPLATE;
550
								$mesg = $outputlangs->transnoentitiesnoconv("EMailTextExpenseReportValidated", $link);
551
								break;
552
							case 'EXPENSE_REPORT_APPROVE':
553
								$link = '<a href="'.$urlwithroot.'/expensereport/card.php?id='.$object->id.'&entity='.$object->entity.'">'.$newref.'</a>';
554
								$dir_output = $conf->expensereport->dir_output;
555
								$object_type = 'expensereport';
556
								$labeltouse = $conf->global->EXPENSE_REPORT_APPROVE_TEMPLATE;
557
								$mesg = $outputlangs->transnoentitiesnoconv("EMailTextExpenseReportApproved", $link);
558
								break;
559
							case 'HOLIDAY_VALIDATE':
560
								$link = '<a href="'.$urlwithroot.'/holiday/card.php?id='.$object->id.'&entity='.$object->entity.'">'.$newref.'</a>';
561
								$dir_output = $conf->holiday->dir_output;
562
								$object_type = 'holiday';
563
								$labeltouse = $conf->global->HOLIDAY_VALIDATE_TEMPLATE;
564
								$mesg = $outputlangs->transnoentitiesnoconv("EMailTextHolidayValidated", $link);
565
								break;
566
							case 'HOLIDAY_APPROVE':
567
								$link = '<a href="'.$urlwithroot.'/holiday/card.php?id='.$object->id.'&entity='.$object->entity.'">'.$newref.'</a>';
568
								$dir_output = $conf->holiday->dir_output;
569
								$object_type = 'holiday';
570
								$labeltouse = $conf->global->HOLIDAY_APPROVE_TEMPLATE;
571
								$mesg = $outputlangs->transnoentitiesnoconv("EMailTextHolidayApproved", $link);
572
								break;
573
							case 'ACTION_CREATE':
574
								$link = '<a href="'.$urlwithroot.'/comm/action/card.php?id='.$object->id.'&entity='.$object->entity.'">'.$newref.'</a>';
575
								$dir_output = $conf->agenda->dir_output;
576
								$object_type = 'action';
577
								$labeltouse = $conf->global->ACTION_CREATE_TEMPLATE;
578
								$mesg = $outputlangs->transnoentitiesnoconv("EMailTextActionAdded", $link);
579
								break;
580
						}
581
582
						include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
583
						$formmail = new FormMail($this->db);
584
						$arraydefaultmessage = null;
585
586
						if (!empty($labeltouse)) $arraydefaultmessage = $formmail->getEMailTemplate($this->db, $object_type.'_send', $user, $outputlangs, 0, 1, $labeltouse);
587
						if (!empty($labeltouse) && is_object($arraydefaultmessage) && $arraydefaultmessage->id > 0) {
588
							$substitutionarray = getCommonSubstitutionArray($outputlangs, 0, null, $object);
589
							complete_substitutions_array($substitutionarray, $outputlangs, $object);
590
							$subject = make_substitutions($arraydefaultmessage->topic, $substitutionarray, $outputlangs);
591
							$message = make_substitutions($arraydefaultmessage->content, $substitutionarray, $outputlangs);
592
						} else {
593
							$message = $outputlangs->transnoentities("YouReceiveMailBecauseOfNotification", $application, $mysoc->name)."\n";
594
							$message .= $outputlangs->transnoentities("YouReceiveMailBecauseOfNotification2", $application, $mysoc->name)."\n";
595
							$message .= "\n";
596
							$message .= $mesg;
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $mesg does not seem to be defined for all execution paths leading up to this point.
Loading history...
597
						}
598
599
						$ref = dol_sanitizeFileName($newref);
600
						$pdf_path = $dir_output."/".$ref.".pdf";
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $dir_output does not seem to be defined for all execution paths leading up to this point.
Loading history...
601
						if (!dol_is_file($pdf_path)) {
602
							// We can't add PDF as it is not generated yet.
603
							$filepdf = '';
604
						} else {
605
							$filepdf = $pdf_path;
606
							$filename_list[] = $filepdf;
607
							$mimetype_list[] = mime_content_type($filepdf);
608
							$mimefilename_list[] = $ref.".pdf";
609
						}
610
611
						$parameters = array('notifcode'=>$notifcode, 'sendto'=>$sendto, 'replyto'=>$replyto, 'file'=>$filename_list, 'mimefile'=>$mimetype_list, 'filename'=>$mimefilename_list);
612
						if (!isset($action)) {
613
							$action = '';
614
						}
615
616
						$reshook = $hookmanager->executeHooks('formatNotificationMessage', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
617
						if (empty($reshook)) {
618
							if (!empty($hookmanager->resArray['subject'])) {
619
								$subject .= $hookmanager->resArray['subject'];
620
							}
621
							if (!empty($hookmanager->resArray['message'])) {
622
								$message .= $hookmanager->resArray['message'];
623
							}
624
						}
625
626
						$mailfile = new CMailFile(
627
							$subject,
628
							$sendto,
629
							$replyto,
630
							$message,
631
							$filename_list,
632
							$mimetype_list,
633
							$mimefilename_list,
634
							'',
635
							'',
636
							0,
637
							-1,
638
							'',
639
							'',
640
							$trackid,
641
							'',
642
							'notification'
643
						);
644
645
						if ($mailfile->sendfile()) {
646
							if ($obj->type_target == 'touserid') {
647
								$sql = "INSERT INTO ".MAIN_DB_PREFIX."notify (daten, fk_action, fk_soc, fk_user, type, objet_type, type_target, objet_id, email)";
648
								$sql .= " VALUES ('".$this->db->idate(dol_now())."', ".((int) $notifcodedefid).", ".($object->socid > 0 ? ((int) $object->socid) : 'null').", ".((int) $obj->cid).", '".$this->db->escape($obj->type)."', '".$this->db->escape($object_type)."', '".$this->db->escape($obj->type_target)."', ".((int) $object->id).", '".$this->db->escape($obj->email)."')";
649
							} else {
650
								$sql = "INSERT INTO ".MAIN_DB_PREFIX."notify (daten, fk_action, fk_soc, fk_contact, type, objet_type, type_target, objet_id, email)";
651
								$sql .= " VALUES ('".$this->db->idate(dol_now())."', ".((int) $notifcodedefid).", ".($object->socid > 0 ? ((int) $object->socid) : 'null').", ".((int) $obj->cid).", '".$this->db->escape($obj->type)."', '".$this->db->escape($object_type)."', '".$this->db->escape($obj->type_target)."', ".((int) $object->id).", '".$this->db->escape($obj->email)."')";
652
							}
653
							if (!$this->db->query($sql)) {
654
								dol_print_error($this->db);
655
							}
656
						} else {
657
							$error++;
658
							$this->errors[] = $mailfile->error;
659
						}
660
					} else {
661
						dol_syslog("No notification sent for ".$sendto." because email is empty");
662
					}
663
					$i++;
664
				}
665
			} else {
666
				dol_syslog("No notification to thirdparty sent, nothing into notification setup for the thirdparty socid = ".(empty($object->socid) ? '' : $object->socid));
667
			}
668
		} else {
669
			$error++;
670
			$this->errors[] = $this->db->lasterror();
671
			dol_syslog("Failed to get list of notification to send ".$this->db->lasterror(), LOG_ERR);
672
			return -1;
673
		}
674
675
		// Check notification using fixed email
676
		if (!$error) {
677
			foreach ($conf->global as $key => $val) {
678
				$reg = array();
679
				if ($val == '' || !preg_match('/^NOTIFICATION_FIXEDEMAIL_'.$notifcode.'_THRESHOLD_HIGHER_(.*)$/', $key, $reg)) {
680
					continue;
681
				}
682
683
				$threshold = (float) $reg[1];
684
				if (!empty($object->total_ht) && $object->total_ht <= $threshold) {
685
					dol_syslog("A notification is requested for notifcode = ".$notifcode." but amount = ".$object->total_ht." so lower than threshold = ".$threshold.". We discard this notification");
686
					continue;
687
				}
688
689
				$param = 'NOTIFICATION_FIXEDEMAIL_'.$notifcode.'_THRESHOLD_HIGHER_'.$reg[1];
690
691
				$sendto = $conf->global->$param;
692
				$notifcodedefid = dol_getIdFromCode($this->db, $notifcode, 'c_action_trigger', 'code', 'rowid');
693
				if ($notifcodedefid <= 0) {
694
					dol_print_error($this->db, 'Failed to get id from code');
695
				}
696
				$trackid = '';
697
698
				$object_type = '';
699
				$link = '';
700
				$num++;
701
702
				$subject = '['.$mysoc->name.'] '.$langs->transnoentitiesnoconv("DolibarrNotification").($projtitle ? ' '.$projtitle : '');
703
704
				switch ($notifcode) {
705
					case 'BILL_VALIDATE':
706
						$link = '<a href="'.$urlwithroot.'/compta/facture/card.php?facid='.$object->id.'&entity='.$object->entity.'">'.$newref.'</a>';
707
						$dir_output = $conf->facture->dir_output."/".get_exdir(0, 0, 0, 1, $object, 'invoice');
708
						$object_type = 'facture';
709
						$mesg = $langs->transnoentitiesnoconv("EMailTextInvoiceValidated", $link);
710
						break;
711
					case 'BILL_PAYED':
712
						$link = '<a href="'.$urlwithroot.'/compta/facture/card.php?facid='.$object->id.'&entity='.$object->entity.'">'.$newref.'</a>';
713
						$dir_output = $conf->facture->dir_output."/".get_exdir(0, 0, 0, 1, $object, 'invoice');
714
						$object_type = 'facture';
715
						$mesg = $langs->transnoentitiesnoconv("EMailTextInvoicePayed", $link);
716
						break;
717
					case 'ORDER_VALIDATE':
718
						$link = '<a href="'.$urlwithroot.'/commande/card.php?id='.$object->id.'&entity='.$object->entity.'">'.$newref.'</a>';
719
						$dir_output = $conf->commande->dir_output."/".get_exdir(0, 0, 0, 1, $object, 'commande');
720
						$object_type = 'order';
721
						$mesg = $langs->transnoentitiesnoconv("EMailTextOrderValidated", $link);
722
						break;
723
					case 'PROPAL_VALIDATE':
724
						$link = '<a href="'.$urlwithroot.'/comm/propal/card.php?id='.$object->id.'&entity='.$object->entity.'">'.$newref.'</a>';
725
						$dir_output = $conf->propal->multidir_output[$object->entity]."/".get_exdir(0, 0, 0, 1, $object, 'propal');
726
						$object_type = 'propal';
727
						$mesg = $langs->transnoentitiesnoconv("EMailTextProposalValidated", $link);
728
						break;
729
					case 'PROPAL_CLOSE_SIGNED':
730
						$link = '<a href="'.$urlwithroot.'/comm/propal/card.php?id='.$object->id.'&entity='.$object->entity.'">'.$newref.'</a>';
731
						$dir_output = $conf->propal->multidir_output[$object->entity]."/".get_exdir(0, 0, 0, 1, $object, 'propal');
732
						$object_type = 'propal';
733
						$mesg = $langs->transnoentitiesnoconv("EMailTextProposalClosedSigned", $link);
734
						break;
735
					case 'FICHINTER_ADD_CONTACT':
736
						$link = '<a href="'.$urlwithroot.'/fichinter/card.php?id='.$object->id.'&entity='.$object->entity.'">'.$newref.'</a>';
737
						$dir_output = $conf->ficheinter->dir_output;
738
						$object_type = 'ficheinter';
739
						$mesg = $langs->transnoentitiesnoconv("EMailTextInterventionAddedContact", $link);
740
						break;
741
					case 'FICHINTER_VALIDATE':
742
						$link = '<a href="'.$urlwithroot.'/fichinter/card.php?id='.$object->id.'&entity='.$object->entity.'">'.$newref.'</a>';
743
						$dir_output = $conf->facture->dir_output;
744
						$object_type = 'ficheinter';
745
						$mesg = $langs->transnoentitiesnoconv("EMailTextInterventionValidated", $link);
746
						break;
747
					case 'ORDER_SUPPLIER_VALIDATE':
748
						$link = '<a href="'.$urlwithroot.'/fourn/commande/card.php?id='.$object->id.'&entity='.$object->entity.'">'.$newref.'</a>';
749
						$dir_output = $conf->fournisseur->commande->dir_output;
750
						$object_type = 'order_supplier';
751
						$mesg = $langs->transnoentitiesnoconv("Hello").",\n\n";
752
						$mesg .= $langs->transnoentitiesnoconv("EMailTextOrderValidatedBy", $link, $user->getFullName($langs));
753
						$mesg .= "\n\n".$langs->transnoentitiesnoconv("Sincerely").".\n\n";
754
						break;
755
					case 'ORDER_SUPPLIER_APPROVE':
756
						$link = '<a href="'.$urlwithroot.'/fourn/commande/card.php?id='.$object->id.'&entity='.$object->entity.'">'.$newref.'</a>';
757
						$dir_output = $conf->fournisseur->commande->dir_output;
758
						$object_type = 'order_supplier';
759
						$mesg = $langs->transnoentitiesnoconv("Hello").",\n\n";
760
						$mesg .= $langs->transnoentitiesnoconv("EMailTextOrderApprovedBy", $link, $user->getFullName($langs));
761
						$mesg .= "\n\n".$langs->transnoentitiesnoconv("Sincerely").".\n\n";
762
						break;
763
					case 'ORDER_SUPPLIER_APPROVE2':
764
						$link = '<a href="'.$urlwithroot.'/fourn/commande/card.php?id='.$object->id.'&entity='.$object->entity.'">'.$newref.'</a>';
765
						$dir_output = $conf->fournisseur->commande->dir_output;
766
						$object_type = 'order_supplier';
767
						$mesg = $langs->transnoentitiesnoconv("Hello").",\n\n";
768
						$mesg .= $langs->transnoentitiesnoconv("EMailTextOrderApprovedBy", $link, $user->getFullName($langs));
769
						$mesg .= "\n\n".$langs->transnoentitiesnoconv("Sincerely").".\n\n";
770
						break;
771
					case 'ORDER_SUPPLIER_REFUSE':
772
						$link = '<a href="'.$urlwithroot.'/fourn/commande/card.php?id='.$object->id.'&entity='.$object->entity.'">'.$newref.'</a>';
773
						$dir_output = $conf->fournisseur->dir_output.'/commande/';
774
						$object_type = 'order_supplier';
775
						$mesg = $langs->transnoentitiesnoconv("Hello").",\n\n";
776
						$mesg .= $langs->transnoentitiesnoconv("EMailTextOrderRefusedBy", $link, $user->getFullName($langs));
777
						$mesg .= "\n\n".$langs->transnoentitiesnoconv("Sincerely").".\n\n";
778
						break;
779
					case 'SHIPPING_VALIDATE':
780
						$link = '<a href="'.$urlwithroot.'/expedition/card.php?id='.$object->id.'&entity='.$object->entity.'">'.$newref.'</a>';
781
						$dir_output = $conf->expedition->dir_output."/sending/".get_exdir(0, 0, 0, 1, $object, 'shipment');
782
						$object_type = 'order_supplier';
783
						$mesg = $langs->transnoentitiesnoconv("EMailTextExpeditionValidated", $link);
784
						break;
785
					case 'EXPENSE_REPORT_VALIDATE':
786
						$link = '<a href="'.$urlwithroot.'/expensereport/card.php?id='.$object->id.'&entity='.$object->entity.'">'.$newref.'</a>';
787
						$dir_output = $conf->expensereport->dir_output;
788
						$object_type = 'expensereport';
789
						$mesg = $langs->transnoentitiesnoconv("EMailTextExpenseReportValidated", $link);
790
						break;
791
					case 'EXPENSE_REPORT_APPROVE':
792
						$link = '<a href="'.$urlwithroot.'/expensereport/card.php?id='.$object->id.'&entity='.$object->entity.'">'.$newref.'</a>';
793
						$dir_output = $conf->expensereport->dir_output;
794
						$object_type = 'expensereport';
795
						$mesg = $langs->transnoentitiesnoconv("EMailTextExpenseReportApproved", $link);
796
						break;
797
					case 'HOLIDAY_VALIDATE':
798
						$link = '<a href="'.$urlwithroot.'/holiday/card.php?id='.$object->id.'&entity='.$object->entity.'">'.$newref.'</a>';
799
						$dir_output = $conf->holiday->dir_output;
800
						$object_type = 'holiday';
801
						$mesg = $langs->transnoentitiesnoconv("EMailTextHolidayValidated", $link);
802
						break;
803
					case 'HOLIDAY_APPROVE':
804
						$link = '<a href="'.$urlwithroot.'/holiday/card.php?id='.$object->id.'&entity='.$object->entity.'">'.$newref.'</a>';
805
						$dir_output = $conf->holiday->dir_output;
806
						$object_type = 'holiday';
807
						$mesg = $langs->transnoentitiesnoconv("EMailTextHolidayApproved", $link);
808
						break;
809
					case 'ACTION_CREATE':
810
						$link = '<a href="'.$urlwithroot.'/comm/action/card.php?id='.$object->id.'&entity='.$object->entity.'">'.$newref.'</a>';
811
						$dir_output = $conf->agenda->dir_output;
812
						$object_type = 'action';
813
						$mesg = $langs->transnoentitiesnoconv("EMailTextActionAdded", $link);
814
						break;
815
				}
816
				$ref = dol_sanitizeFileName($newref);
817
				$pdf_path = $dir_output."/".$ref."/".$ref.".pdf";
818
				if (!dol_is_file($pdf_path)) {
819
					// We can't add PDF as it is not generated yet.
820
					$filepdf = '';
821
				} else {
822
					$filepdf = $pdf_path;
823
					$filename_list[] = $pdf_path;
824
					$mimetype_list[] = mime_content_type($filepdf);
825
					$mimefilename_list[] = $ref.".pdf";
826
				}
827
828
				$message .= $langs->transnoentities("YouReceiveMailBecauseOfNotification2", $application, $mysoc->name)."\n";
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $message does not seem to be defined for all execution paths leading up to this point.
Loading history...
829
				$message .= "\n";
830
				$message .= $mesg;
831
832
				$message = nl2br($message);
833
834
				// Replace keyword __SUPERVISOREMAIL__
835
				if (preg_match('/__SUPERVISOREMAIL__/', $sendto)) {
836
					$newval = '';
837
					if ($user->fk_user > 0) {
838
						$supervisoruser = new User($this->db);
839
						$supervisoruser->fetch($user->fk_user);
840
						if ($supervisoruser->email) {
841
							$newval = trim(dolGetFirstLastname($supervisoruser->firstname, $supervisoruser->lastname).' <'.$supervisoruser->email.'>');
842
						}
843
					}
844
					dol_syslog("Replace the __SUPERVISOREMAIL__ key into recipient email string with ".$newval);
845
					$sendto = preg_replace('/__SUPERVISOREMAIL__/', $newval, $sendto);
846
					$sendto = preg_replace('/,\s*,/', ',', $sendto); // in some case you can have $sendto like "email, __SUPERVISOREMAIL__ , otheremail" then you have "email,  , othermail" and it's not valid
847
					$sendto = preg_replace('/^[\s,]+/', '', $sendto); // Clean start of string
848
					$sendto = preg_replace('/[\s,]+$/', '', $sendto); // Clean end of string
849
				}
850
851
				if ($sendto) {
852
					$parameters = array('notifcode'=>$notifcode, 'sendto'=>$sendto, 'replyto'=>$replyto, 'file'=>$filename_list, 'mimefile'=>$mimetype_list, 'filename'=>$mimefilename_list);
853
					$reshook = $hookmanager->executeHooks('formatNotificationMessage', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
854
					if (empty($reshook)) {
855
						if (!empty($hookmanager->resArray['subject'])) {
856
							$subject .= $hookmanager->resArray['subject'];
857
						}
858
						if (!empty($hookmanager->resArray['message'])) {
859
							$message .= $hookmanager->resArray['message'];
860
						}
861
					}
862
					$mailfile = new CMailFile(
863
						$subject,
864
						$sendto,
865
						$replyto,
866
						$message,
867
						$filename_list,
868
						$mimetype_list,
869
						$mimefilename_list,
870
						'',
871
						'',
872
						0,
873
						1,
874
						'',
875
						$trackid,
876
						'',
877
						'',
878
						'notification'
879
					);
880
881
					if ($mailfile->sendfile()) {
882
						$sql = "INSERT INTO ".MAIN_DB_PREFIX."notify (daten, fk_action, fk_soc, fk_contact, type, type_target, objet_type, objet_id, email)";
883
						$sql .= " VALUES ('".$this->db->idate(dol_now())."', ".((int) $notifcodedefid).", ".($object->socid > 0 ? ((int) $object->socid) : 'null').", null, 'email', 'tofixedemail', '".$this->db->escape($object_type)."', ".((int) $object->id).", '".$this->db->escape($conf->global->$param)."')";
884
						if (!$this->db->query($sql)) {
885
							dol_print_error($this->db);
886
						}
887
					} else {
888
						$error++;
889
						$this->errors[] = $mailfile->error;
890
					}
891
				}
892
			}
893
		}
894
895
		if (!$error) {
896
			return $num;
897
		} else {
898
			return -1 * $error;
899
		}
900
	}
901
}
902