Passed
Push — release-2.1 ( 0e5bfc...908430 )
by Mathias
07:53 queued 12s
created

handleQuoteNotifications()   C

Complexity

Conditions 13
Paths 12

Size

Total Lines 69
Code Lines 39

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 13
eloc 39
nc 12
nop 0
dl 0
loc 69
rs 6.6166
c 2
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/**
4
 * This file contains code used to notify people when a new post is created that
5
 * is relevant to them in some way: new topics in boards they watch, replies to
6
 * topics they watch, posts that mention them, and/or posts that quote them.
7
 *
8
 * Simple Machines Forum (SMF)
9
 *
10
 * @package SMF
11
 * @author Simple Machines https://www.simplemachines.org
12
 * @copyright 2021 Simple Machines and individual contributors
13
 * @license https://www.simplemachines.org/about/smf/license.php BSD
14
 *
15
 * @version 2.1 RC4
16
 */
17
18
/**
19
 * Class CreatePost_Notify_Background
20
 */
21
class CreatePost_Notify_Background extends SMF_BackgroundTask
22
{
23
	/**
24
	 * Constants for reply types.
25
	 */
26
	const NOTIFY_TYPE_REPLIES_AND_MODERATION = 1;
27
	const NOTIFY_TYPE_REPLIES_AND_OWN_TOPIC_MODERATION = 2;
28
	const NOTIFY_TYPE_ONLY_REPLIES = 3;
29
	const NOTIFY_TYPE_NOTHING = 4;
30
31
	/**
32
	 * Constants for frequencies.
33
	 */
34
	const FREQUENCY_NOTHING = 0;
35
	const FREQUENCY_EVERYTHING = 1;
36
	const FREQUENCY_FIRST_UNREAD_MSG = 2;
37
	const FREQUENCY_DAILY_DIGEST = 3;
38
	const FREQUENCY_WEEKLY_DIGEST = 4;
39
40
	/**
41
	 * Minutes to wait before sending notifications about about mentions
42
	 * and quotes in unwatched and/or edited posts.
43
	 */
44
	const MENTION_DELAY = 5;
45
46
	/**
47
	 * @var array Info about members to be notified.
48
	 */
49
	private $members = array(
50
		// These three contain nested arrays of member info.
51
		'mentioned' => array(),
52
		'quoted' => array(),
53
		'watching' => array(),
54
55
		// These ones just contain member IDs.
56
		'all' => array(),
57
		'emailed' => array(),
58
		'alerted' => array(),
59
		'done' => array(),
60
	);
61
62
	/**
63
	 * @var array Alerts to be inserted into the alerts table.
64
	 */
65
	private $alert_rows = array();
66
67
	/**
68
	 * @var array Members' notification and alert preferences.
69
	 */
70
	private $prefs = array();
71
72
	/**
73
	 * @var int Timestamp after which email notifications should be sent about
74
	 *			mentions and quotes in unwatched and/or edited posts.
75
	 */
76
	private $mention_mail_time = 0;
77
78
	/**
79
	 * This executes the task: loads up the info, puts the email in the queue
80
	 * and inserts any alerts as needed.
81
	 *
82
	 * @return bool Always returns true
83
	 * @throws Exception
84
	 */
85
	public function execute()
86
	{
87
		global $smcFunc, $sourcedir, $scripturl, $language, $modSettings, $user_info;
88
89
		require_once($sourcedir . '/Subs-Post.php');
90
		require_once($sourcedir . '/Mentions.php');
91
		require_once($sourcedir . '/Subs-Notify.php');
92
		require_once($sourcedir . '/Subs.php');
93
		require_once($sourcedir . '/ScheduledTasks.php');
94
		loadEssentialThemeData();
95
96
		$msgOptions = &$this->_details['msgOptions'];
97
		$topicOptions = &$this->_details['topicOptions'];
98
		$posterOptions = &$this->_details['posterOptions'];
99
		$type = &$this->_details['type'];
100
101
		$this->mention_mail_time = $msgOptions['poster_time'] + self::MENTION_DELAY * 60;
102
103
		// We need some more info about the quoted and mentioned members.
104
		if (!empty($msgOptions['quoted_members']))
105
			$this->members['quoted'] = Mentions::getMentionsByContent('quote', $msgOptions['id'], array_keys($msgOptions['quoted_members']));
106
		if (!empty($msgOptions['mentioned_members']))
107
			$this->members['mentioned'] = Mentions::getMentionsByContent('msg', $msgOptions['id'], array_keys($msgOptions['mentioned_members']));
108
109
		// Find the people interested in receiving notifications for this topic
110
		$request = $smcFunc['db_query']('', '
111
			SELECT
112
				ln.id_member, ln.id_board, ln.id_topic, ln.sent,
113
				mem.email_address, mem.lngfile, mem.pm_ignore_list,
114
				mem.id_group, mem.id_post_group, mem.additional_groups,
115
				mem.time_format, mem.time_offset, mem.timezone,
116
				b.member_groups, t.id_member_started, t.id_member_updated
117
			FROM {db_prefix}log_notify AS ln
118
				INNER JOIN {db_prefix}members AS mem ON (ln.id_member = mem.id_member)
119
				LEFT JOIN {db_prefix}topics AS t ON (t.id_topic = ln.id_topic)
120
				LEFT JOIN {db_prefix}boards AS b ON (b.id_board = ln.id_board OR b.id_board = t.id_board)
121
			WHERE ln.id_member != {int:member}
122
				AND (ln.id_topic = {int:topic} OR ln.id_board = {int:board})',
123
			array(
124
				'member' => $posterOptions['id'],
125
				'topic' => $topicOptions['id'],
126
				'board' => $topicOptions['board'],
127
			)
128
		);
129
		while ($row = $smcFunc['db_fetch_assoc']($request))
130
		{
131
			// Skip members who aren't allowed to see this board
132
			$groups = array_merge(array($row['id_group'], $row['id_post_group']), (empty($row['additional_groups']) ? array() : explode(',', $row['additional_groups'])));
133
134
			$allowed_groups = explode(',', $row['member_groups']);
135
136
			if (!in_array(1, $groups) && count(array_intersect($groups, $allowed_groups)) == 0)
137
				continue;
138
			else
139
			{
140
				$row['groups'] = $groups;
141
				unset($row['id_group'], $row['id_post_group'], $row['additional_groups']);
142
			}
143
144
			$this->members['watching'][$row['id_member']] = $row;
145
		}
146
		$smcFunc['db_free_result']($request);
147
148
		// Filter out mentioned and quoted members who can't see this board.
149
		if (!empty($this->members['mentioned']) || !empty($this->members['quoted']))
150
		{
151
			// This won't be set yet if no one is watching this board or topic.
152
			if (!isset($allowed_groups))
153
			{
154
				$request = $smcFunc['db_query']('', '
155
					SELECT member_groups
156
					FROM {db_prefix}boards
157
					WHERE id_board = {int:board}',
158
					array(
159
						'board' => $topicOptions['board'],
160
					)
161
				);
162
				list($allowed_groups) = $smcFunc['db_fetch_row']($request);
163
				$smcFunc['db_free_result']($request);
164
				$allowed_groups = explode(',', $allowed_groups);
165
			}
166
167
			foreach (array('mentioned', 'quoted') as $member_type)
168
			{
169
				foreach ($this->members[$member_type] as $member_id => $member_data)
170
				{
171
					if (!in_array(1, $member_data['groups']) && count(array_intersect($member_data['groups'], $allowed_groups)) == 0)
172
						unset($this->members[$member_type][$member_id], $msgOptions[$member_type . '_members'][$member_id]);
173
				}
174
			}
175
		}
176
177
		$unnotified = array_filter($this->members['watching'], function ($member) {
178
			return empty($member['sent']);
179
		});
180
181
182
		// Modified post, or dealing with delayed mention and quote notifications.
183
		if ($type == 'edit' || !empty($this->_details['respawns']))
184
		{
185
			// Filter out members who have already been notified about this post's topic
186
			$this->members['quoted'] = array_intersect_key($this->members['quoted'], $unnotified);
187
			$this->members['mentioned'] = array_intersect_key($this->members['mentioned'], $unnotified);
188
189
			// Notifications about modified posts only go to members who were mentioned or quoted
190
			$this->members['watching'] = $type == 'edit' ? array(): $unnotified;
191
192
			// If this post has no quotes or mentions, just delete any obsolete alerts and bail out.
193
			if (empty($this->members['quoted']) && empty($this->members['mentioned']))
194
			{
195
				$this->updateAlerts($msgOptions['id']);
196
				return true;
197
			}
198
199
			// Never notify about edits to ancient posts.
200
			if (!empty($modSettings['oldTopicDays']) && time() > $msgOptions['poster_time'] + $modSettings['oldTopicDays'] * 86400)
201
				return true;
202
203
			// If editing is only allowed for a brief time, send after editing becomes disabled.
204
			if (!empty($modSettings['edit_disable_time']) && $modSettings['edit_disable_time'] <= self::MENTION_DELAY)
205
			{
206
				$this->mention_mail_time = $msgOptions['poster_time'] + $modSettings['edit_disable_time'] * 60;
207
			}
208
			// Otherwise, impose a delay before sending notifications about edited posts.
209
			else
210
			{
211
				if (!empty($this->_details['respawns']))
212
				{
213
					$request = $smcFunc['db_query']('', '
214
						SELECT modified_time
215
						FROM {db_prefix}messages
216
						WHERE id_msg = {int:msg}
217
						LIMIT 1',
218
						array(
219
							'msg' => $msgOptions['id'],
220
						)
221
					);
222
					list($real_modified_time) = $smcFunc['db_fetch_row']($request);
223
					$smcFunc['db_free_result']($request);
224
225
					// If it was modified again while we weren't looking, bail out.
226
					// A future instance of this task will take care of it instead.
227
					if ($msgOptions['modify_time'] < $real_modified_time)
228
						return true;
229
				}
230
231
				$this->mention_mail_time = $msgOptions['modify_time'] + self::MENTION_DELAY * 60;
232
			}
233
		}
234
235
		$this->members['all'] = array_unique(array_merge(array_keys($this->members['watching']), array_keys($this->members['quoted']), array_keys($this->members['mentioned'])));
236
237
		if (empty($this->members['all']))
238
			return true;
239
240
		$this->prefs = getNotifyPrefs($this->members['all'], '', true);
241
242
		// May as well disable these, since they'll be stripped out anyway.
243
		$disable = array('attach', 'img', 'iurl', 'url', 'youtube');
244
		if (!empty($modSettings['disabledBBC']))
245
		{
246
			$disabledBBC = $modSettings['disabledBBC'];
247
			$disable = array_unique(array_merge($disable, explode(',', $modSettings['disabledBBC'])));
248
		}
249
		$modSettings['disabledBBC'] = implode(',', $disable);
250
251
		// Notify any members who were mentioned.
252
		if (!empty($this->members['mentioned']))
253
			$this->handleMentionedNotifications();
254
255
		// Notify any members who were quoted.
256
		if (!empty($this->members['quoted']))
257
			$this->handleQuoteNotifications();
258
259
		// Handle rest of the notifications for watched topics and boards
260
		if (!empty($this->members['watching']))
261
			$this->handleWatchedNotifications();
262
263
		// Put this back the way we found it.
264
		if (!empty($disabledBBC))
265
			$modSettings['disabledBBC'] = $disabledBBC;
266
267
		// Track what we sent.
268
		$members_to_log = array_intersect($this->members['emailed'], array_keys($this->members['watching']));
269
		if (!empty($members_to_log))
270
		{
271
			$smcFunc['db_query']('', '
272
				UPDATE {db_prefix}log_notify
273
				SET sent = {int:is_sent}
274
				WHERE (id_topic = {int:topic} OR id_board = {int:board})
275
					AND id_member IN ({array_int:members})',
276
				array(
277
					'topic' => $topicOptions['id'],
278
					'board' => $topicOptions['board'],
279
					// 'members' => $this->members['emailed'],
280
					'members' => $members_to_log,
281
					'is_sent' => 1,
282
				)
283
			);
284
		}
285
286
		// Insert it into the digest for daily/weekly notifications
287
		if ($type != 'edit' && empty($this->_details['respawns']))
288
		{
289
			$smcFunc['db_insert']('',
290
				'{db_prefix}log_digest',
291
				array(
292
					'id_topic' => 'int', 'id_msg' => 'int', 'note_type' => 'string', 'exclude' => 'int',
293
				),
294
				array($topicOptions['id'], $msgOptions['id'], $type, $posterOptions['id']),
295
				array()
296
			);
297
		}
298
299
		// Insert the alerts if any
300
		$this->updateAlerts($msgOptions['id']);
301
302
		// If there is anyone still to notify via email, create a new task later.
303
		$unnotified = array_diff_key($unnotified, array_flip($this->members['emailed']));
304
		if (!empty($unnotified) || !empty($msgOptions['mentioned_members']) || !empty($msgOptions['quoted_members']))
305
		{
306
			$new_details = $this->_details;
307
308
			if (empty($new_details['respawns']))
309
				$new_details['respawns'] = 0;
310
311
			if ($new_details['respawns']++ < 10)
312
			{
313
				$smcFunc['db_insert']('',
314
					'{db_prefix}background_tasks',
315
					array(
316
						'task_file' => 'string',
317
						'task_class' => 'string',
318
						'task_data' => 'string',
319
						'claimed_time' => 'int',
320
					),
321
					array(
322
						'$sourcedir/tasks/CreatePost-Notify.php',
323
						'CreatePost_Notify_Background',
324
						$smcFunc['json_encode']($new_details),
325
						max(0, $this->mention_mail_time - MAX_CLAIM_THRESHOLD),
326
					),
327
					array('id_task')
328
				);
329
			}
330
		}
331
332
		return true;
333
	}
334
335
	private function updateAlerts($msg_id)
336
	{
337
		global $smcFunc;
338
339
		// We send alerts only on the first iteration of this task.
340
		if (!empty($this->_details['respawns']))
341
			return;
342
343
		// Delete alerts about any mentions and quotes that no longer exist.
344
		if ($this->_details['type'] == 'edit')
345
		{
346
			$old_alerts = array();
347
348
			$request = $smcFunc['db_query']('', '
349
				SELECT content_action, id_member
350
				FROM {db_prefix}user_alerts
351
				WHERE content_id = {int:msg_id}
352
					AND content_type = {literal:msg}
353
					AND (content_action = {literal:quote} OR content_action = {literal:mention})',
354
				array(
355
					'msg_id' => $msg_id,
356
				)
357
			);
358
			if ($smcFunc['db_num_rows']($request) != 0)
359
			{
360
				while ($row = $smcFunc['db_fetch_assoc']($request))
361
					$old_alerts[$row['content_action']][$row['id_member']] = $row['id_member'];
362
			}
363
			$smcFunc['db_free_result']($request);
364
365
			if (!empty($old_alerts))
366
			{
367
				$request = $smcFunc['db_query']('', '
368
					SELECT content_type, id_mentioned
369
					FROM {db_prefix}mentions
370
					WHERE content_id = {int:msg_id}
371
						AND (content_type = {literal:quote} OR content_type = {literal:msg})',
372
					array(
373
						'msg_id' => $msg_id,
374
					)
375
				);
376
				while ($row = $smcFunc['db_fetch_assoc']($request))
377
				{
378
					$content_action = $row['content_type'] == 'quote' ? 'quote' : 'mention';
379
					unset($old_alerts[$content_action][$row['id_mentioned']]);
380
				}
381
				$smcFunc['db_free_result']($request);
382
383
				$conditions = array();
384
385
				if (!empty($old_alerts['quote']))
386
					$conditions[] = '(content_action = {literal:quote} AND id_member IN ({array_int:members_not_quoted}))';
387
388
				if (!empty($old_alerts['mention']))
389
					$conditions[] = '(content_action = {literal:mention} AND id_member IN ({array_int:members_not_mentioned}))';
390
391
				if (!empty($conditions))
392
				{
393
					$smcFunc['db_query']('', '
394
						DELETE FROM {db_prefix}user_alerts
395
						WHERE content_id = {int:msg_id}
396
							AND content_type = {literal:msg}
397
							AND (' . implode(' OR ', $conditions) . ')',
398
						array(
399
							'msg_id' => $msg_id,
400
							'members_not_quoted' => empty($old_alerts['quote']) ? array(0) : $old_alerts['quote'],
401
							'members_not_mentioned' => empty($old_alerts['mention']) ? array(0) : $old_alerts['mention'],
402
						)
403
					);
404
405
					foreach ($old_alerts as $member_ids)
406
						updateMemberData($member_ids, array('alerts' => '-'));
407
				}
408
			}
409
		}
410
411
		// Insert the new alerts.
412
		if (!empty($this->alert_rows))
413
		{
414
			$smcFunc['db_insert']('',
415
				'{db_prefix}user_alerts',
416
				array(
417
					'alert_time' => 'int',
418
					'id_member' => 'int',
419
					'id_member_started' => 'int',
420
					'member_name' => 'string',
421
					'content_type' => 'string',
422
					'content_id' => 'int',
423
					'content_action' => 'string',
424
					'is_read' => 'int',
425
					'extra' => 'string',
426
				),
427
				$this->alert_rows,
428
				array()
429
			);
430
431
			$new_alerts = array();
432
			foreach ($this->alert_rows as $row)
433
			{
434
				$group = implode(' ', array($row['content_type'], $row['content_id'], $row['content_action']));
435
				$new_alerts[$group] = $row['id_member'];
436
			}
437
438
			foreach ($new_alerts as $member_ids)
439
				updateMemberData($member_ids, array('alerts' => '+'));
440
		}
441
	}
442
443
	/**
444
	 * Notifies members about new posts in topics they are watching
445
	 * and new topics in boards they are watching.
446
	 */
447
	protected function handleWatchedNotifications()
448
	{
449
		global $smcFunc, $scripturl, $modSettings, $user_info;
450
451
		$msgOptions = &$this->_details['msgOptions'];
452
		$topicOptions = &$this->_details['topicOptions'];
453
		$posterOptions = &$this->_details['posterOptions'];
454
		$type = &$this->_details['type'];
455
456
		$members_info = $this->getMinUserInfo(array_keys($this->members['watching']));
457
458
		$parsed_message = array();
459
		foreach ($this->members['watching'] as $member_id => $member_data)
460
		{
461
			if (in_array($member_id, $this->members['done']))
462
				continue;
463
464
			$frequency = isset($this->prefs[$member_id]['msg_notify_pref']) ? $this->prefs[$member_id]['msg_notify_pref'] : self::FREQUENCY_NOTHING;
465
			$notify_types = !empty($this->prefs[$member_id]['msg_notify_type']) ? $this->prefs[$member_id]['msg_notify_type'] : self::NOTIFY_TYPE_REPLIES_AND_MODERATION;
466
467
			// Don't send a notification if:
468
			// 1. The watching member ignored the member who did the action.
469
			if (!empty($member_data['pm_ignore_list']) && in_array($member_data['id_member_updated'], explode(',', $member_data['pm_ignore_list'])))
470
				continue;
471
472
			// 2. The watching member is not interested in moderation on this topic.
473
			if (!in_array($type, array('reply', 'topic')) && ($notify_types == self::NOTIFY_TYPE_ONLY_REPLIES || ($notify_types == self::NOTIFY_TYPE_REPLIES_AND_OWN_TOPIC_MODERATION && $member_id != $member_data['id_member_started'])))
474
				continue;
475
476
			// 3. This is the watching member's own post.
477
			if (in_array($type, array('reply', 'topic')) && $member_id == $posterOptions['id'])
478
				continue;
479
480
			// 4. The watching member doesn't want any notifications at all.
481
			if ($notify_types == self::NOTIFY_TYPE_NOTHING)
482
				continue;
483
484
			// 5. The watching member doesn't want notifications until later.
485
			if (in_array($frequency, array(
486
				self::FREQUENCY_NOTHING,
487
				self::FREQUENCY_DAILY_DIGEST,
488
				self::FREQUENCY_WEEKLY_DIGEST)))
489
				continue;
490
491
			// 6. We already sent one and the watching member doesn't want more.
492
			if ($frequency == self::FREQUENCY_FIRST_UNREAD_MSG && $member_data['sent'])
493
				continue;
494
495
			// 7. The watching member isn't on club security's VIP list.
496
			if (!empty($this->_details['members_only']) && !in_array($member_id, $this->_details['members_only']))
497
				continue;
498
499
			// Watched topic?
500
			if (!empty($member_data['id_topic']) && $type != 'topic' && !empty($this->prefs[$member_id]))
501
			{
502
				$pref = !empty($this->prefs[$member_id]['topic_notify_' . $topicOptions['id']]) ?
503
					$this->prefs[$member_id]['topic_notify_' . $topicOptions['id']] :
504
					(!empty($this->prefs[$member_id]['topic_notify']) ? $this->prefs[$member_id]['topic_notify'] : 0);
505
506
				$message_type = 'notification_' . $type;
507
508
				if ($type == 'reply')
509
				{
510
					if (empty($modSettings['disallow_sendBody']) && !empty($this->prefs[$member_id]['msg_receive_body']))
511
						$message_type .= '_body';
512
513
					if (!empty($frequency))
514
						$message_type .= '_once';
515
				}
516
517
				$content_type = 'topic';
518
			}
519
			// A new topic in a watched board then?
520
			elseif ($type == 'topic')
521
			{
522
				$pref = !empty($this->prefs[$member_id]['board_notify_' . $topicOptions['board']]) ?
523
					$this->prefs[$member_id]['board_notify_' . $topicOptions['board']] :
524
					(!empty($this->prefs[$member_id]['board_notify']) ? $this->prefs[$member_id]['board_notify'] : 0);
525
526
				$content_type = 'board';
527
528
				$message_type = !empty($frequency) ? 'notify_boards_once' : 'notify_boards';
529
530
				if (empty($modSettings['disallow_sendBody']) && !empty($this->prefs[$member_id]['msg_receive_body']))
531
					$message_type .= '_body';
532
			}
533
534
			// If neither of the above, this might be a redundant row due to the OR clause in our SQL query, skip
535
			else
536
				continue;
537
538
			// We need to fake some of $user_info to make BBC parsing work correctly.
539
			if (isset($user_info))
540
				$real_user_info = $user_info;
541
542
			$user_info = $members_info[$member_id];
543
544
			loadLanguage('index+Modifications', $member_data['lngfile'], false);
545
546
			// Censor and parse BBC in the receiver's localization. Don't repeat unnecessarily.
547
			$localization = implode('|', array($member_data['lngfile'], $user_info['time_offset'], $user_info['time_format']));
548
			if (empty($parsed_message[$localization]))
549
			{
550
				$parsed_message[$localization]['subject'] = $msgOptions['subject'];
551
				$parsed_message[$localization]['body'] = $msgOptions['body'];
552
553
				censorText($parsed_message[$localization]['subject']);
554
				censorText($parsed_message[$localization]['body']);
555
556
				$parsed_message[$localization]['subject'] = un_htmlspecialchars($parsed_message[$localization]['subject']);
557
				$parsed_message[$localization]['body'] = trim(un_htmlspecialchars(strip_tags(strtr(parse_bbc($parsed_message[$localization]['body'], false), array('<br>' => "\n", '</div>' => "\n", '</li>' => "\n", '&#91;' => '[', '&#93;' => ']', '&#39;' => '\'', '</tr>' => "\n", '</td>' => "\t", '<hr>' => "\n---------------------------------------------------------------\n")))));
558
			}
559
560
			// Put $user_info back the way we found it.
561
			if (isset($real_user_info))
562
			{
563
				$user_info = $real_user_info;
564
				unset($real_user_info);
565
			}
566
			else
567
				$user_info = null;
568
569
			// Bitwise check: Receiving a alert?
570
			if ($pref & self::RECEIVE_NOTIFY_ALERT)
571
			{
572
				$this->alert_rows[] = array(
573
					'alert_time' => time(),
574
					'id_member' => $member_id,
575
					// Only tell sender's information for new topics and replies
576
					'id_member_started' => in_array($type, array('topic', 'reply')) ? $posterOptions['id'] : 0,
577
					'member_name' => in_array($type, array('topic', 'reply')) ? $posterOptions['name'] : '',
578
					'content_type' => $content_type,
579
					'content_id' => $topicOptions['id'],
580
					'content_action' => $type,
581
					'is_read' => 0,
582
					'extra' => $smcFunc['json_encode'](array(
583
						'topic' => $topicOptions['id'],
584
						'board' => $topicOptions['board'],
585
						'content_subject' => $parsed_message[$localization]['subject'],
586
						'content_link' => $scripturl . '?topic=' . $topicOptions['id'] . (in_array($type, array('reply', 'topic')) ? '.new;topicseen#new' : '.0'),
587
					)),
588
				);
589
			}
590
591
			// Bitwise check: Receiving a email notification?
592
			if ($pref & self::RECEIVE_NOTIFY_EMAIL)
593
			{
594
				$itemID = $content_type == 'board' ? $topicOptions['board'] : $topicOptions['id'];
595
596
				$token = createUnsubscribeToken($member_data['id_member'], $member_data['email_address'], $content_type, $itemID);
597
598
				$replacements = array(
599
					'TOPICSUBJECT' => $parsed_message[$localization]['subject'],
600
					'POSTERNAME' => un_htmlspecialchars($posterOptions['name']),
601
					'TOPICLINK' => $scripturl . '?topic=' . $topicOptions['id'] . '.new#new',
602
					'MESSAGE' => $parsed_message[$localization]['body'],
603
					'UNSUBSCRIBELINK' => $scripturl . '?action=notify' . $content_type . ';' . $content_type . '=' . $itemID . ';sa=off;u=' . $member_data['id_member'] . ';token=' . $token,
604
				);
605
606
				$emaildata = loadEmailTemplate($message_type, $replacements, $member_data['lngfile']);
607
				$mail_result = sendmail($member_data['email_address'], $emaildata['subject'], $emaildata['body'], null, 'm' . $topicOptions['id'], $emaildata['is_html']);
608
609
				if ($mail_result !== false)
610
					$this->members['emailed'][] = $member_id;
611
			}
612
613
			$this->members['done'][] = $member_id;
614
		}
615
	}
616
617
	/**
618
	 * Notifies members when their posts are quoted in other posts.
619
	 */
620
	protected function handleQuoteNotifications()
621
	{
622
		global $smcFunc, $modSettings, $language, $scripturl;
623
624
		$msgOptions = &$this->_details['msgOptions'];
625
		$posterOptions = &$this->_details['posterOptions'];
626
627
		foreach ($this->members['quoted'] as $member_id => $member_data)
628
		{
629
			if (in_array($member_id, $this->members['done']))
630
				continue;
631
632
			if (!isset($this->prefs[$member_id]) || empty($this->prefs[$member_id]['msg_quote']))
633
				continue;
634
			else
635
				$pref = $this->prefs[$member_id]['msg_quote'];
636
637
			// You don't need to be notified about quoting yourself.
638
			if ($member_id == $posterOptions['id'])
639
				continue;
640
641
			// Bitwise check: Receiving an alert?
642
			if ($pref & self::RECEIVE_NOTIFY_ALERT)
643
			{
644
				$this->alert_rows[] = array(
645
					'alert_time' => time(),
646
					'id_member' => $member_data['id'],
647
					'id_member_started' => $posterOptions['id'],
648
					'member_name' => $posterOptions['name'],
649
					'content_type' => 'msg',
650
					'content_id' => $msgOptions['id'],
651
					'content_action' => 'quote',
652
					'is_read' => 0,
653
					'extra' => $smcFunc['json_encode'](array(
654
						'content_subject' => $msgOptions['subject'],
655
						'content_link' => $scripturl . '?msg=' . $msgOptions['id'],
656
					)),
657
				);
658
			}
659
660
			// Bitwise check: Receiving a email notification?
661
			if (!($pref & self::RECEIVE_NOTIFY_EMAIL))
662
			{
663
				// Don't want an email, so forget this member in any respawned tasks.
664
				unset($msgOptions['quoted_members'][$member_id]);
665
			}
666
			elseif (TIME_START >= $this->mention_mail_time || in_array($member_id, $this->members['watched']))
667
			{
668
				$replacements = array(
669
					'CONTENTSUBJECT' => $msgOptions['subject'],
670
					'QUOTENAME' => $posterOptions['name'],
671
					'MEMBERNAME' => $member_data['real_name'],
672
					'CONTENTLINK' => $scripturl . '?msg=' . $msgOptions['id'],
673
				);
674
675
				$emaildata = loadEmailTemplate('msg_quote', $replacements, empty($member_data['lngfile']) || empty($modSettings['userLanguage']) ? $language : $member_data['lngfile']);
676
				$mail_result = sendmail($member_data['email_address'], $emaildata['subject'], $emaildata['body'], null, 'msg_quote_' . $msgOptions['id'], $emaildata['is_html'], 2);
677
678
				if ($mail_result !== false)
679
				{
680
					// Don't send multiple notifications about the same post.
681
					$this->members['emailed'][] = $member_id;
682
683
					// Ensure respawned tasks don't send this again.
684
					unset($msgOptions['quoted_members'][$member_id]);
685
				}
686
			}
687
688
			$this->members['done'][] = $member_id;
689
		}
690
	}
691
692
	/**
693
	 * Notifies members when they are mentioned in other members' posts.
694
	 */
695
	protected function handleMentionedNotifications()
696
	{
697
		global $smcFunc, $scripturl, $language, $modSettings;
698
699
		$msgOptions = &$this->_details['msgOptions'];
700
701
		foreach ($this->members['mentioned'] as $member_id => $member_data)
702
		{
703
			if (in_array($member_id, $this->members['done']))
704
				continue;
705
706
			if (empty($this->prefs[$member_id]) || empty($this->prefs[$member_id]['msg_mention']))
707
				continue;
708
			else
709
				$pref = $this->prefs[$member_id]['msg_mention'];
710
711
			// Mentioning yourself is silly, and we aren't going to notify you about it.
712
			if ($member_id == $member_data['mentioned_by']['id'])
713
				continue;
714
715
			// Bitwise check: Receiving an alert?
716
			if ($pref & self::RECEIVE_NOTIFY_ALERT)
717
			{
718
				$this->alert_rows[] = array(
719
					'alert_time' => time(),
720
					'id_member' => $member_data['id'],
721
					'id_member_started' => $member_data['mentioned_by']['id'],
722
					'member_name' => $member_data['mentioned_by']['name'],
723
					'content_type' => 'msg',
724
					'content_id' => $msgOptions['id'],
725
					'content_action' => 'mention',
726
					'is_read' => 0,
727
					'extra' => $smcFunc['json_encode'](array(
728
						'content_subject' => $msgOptions['subject'],
729
						'content_link' => $scripturl . '?msg=' . $msgOptions['id'],
730
					)),
731
				);
732
			}
733
734
735
			// Bitwise check: Receiving a email notification?
736
			if (!($pref & self::RECEIVE_NOTIFY_EMAIL))
737
			{
738
				// Don't want an email, so forget this member in any respawned tasks.
739
				unset($msgOptions['mentioned_members'][$member_id]);
740
			}
741
			elseif (TIME_START >= $this->mention_mail_time || in_array($member_id, $this->members['watched']))
742
			{
743
				$replacements = array(
744
					'CONTENTSUBJECT' => $msgOptions['subject'],
745
					'MENTIONNAME' => $member_data['mentioned_by']['name'],
746
					'MEMBERNAME' => $member_data['real_name'],
747
					'CONTENTLINK' => $scripturl . '?msg=' . $msgOptions['id'],
748
				);
749
750
				$emaildata = loadEmailTemplate('msg_mention', $replacements, empty($member_data['lngfile']) || empty($modSettings['userLanguage']) ? $language : $member_data['lngfile']);
751
				$mail_result = sendmail($member_data['email_address'], $emaildata['subject'], $emaildata['body'], null, 'msg_mention_' . $msgOptions['id'], $emaildata['is_html'], 2);
752
753
				if ($mail_result !== false)
754
				{
755
					// Don't send multiple notifications about the same post.
756
					$this->members['emailed'][] = $member_id;
757
758
					// Ensure respawned tasks don't send this again.
759
					unset($msgOptions['mentioned_members'][$member_id]);
760
				}
761
			}
762
763
			$this->members['done'][] = $member_id;
764
		}
765
	}
766
}
767
768
?>