Failed Conditions
Branch release-2.1 (4e22cf)
by Rick
07:22
created

Birthday_Notify_Background   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 116
Duplicated Lines 8.62 %

Coupling/Cohesion

Components 0
Dependencies 1

Importance

Changes 0
Metric Value
dl 10
loc 116
rs 10
c 0
b 0
f 0
wmc 11
lcom 0
cbo 1

1 Method

Rating   Name   Duplication   Size   Complexity  
C execute() 10 109 11

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
3
/**
4
 * This file contains background notification code
5
 *
6
 * Simple Machines Forum (SMF)
7
 *
8
 * @package SMF
9
 * @author Simple Machines http://www.simplemachines.org
10
 * @copyright 2017 Simple Machines and individual contributors
11
 * @license http://www.simplemachines.org/about/smf/license.php BSD
12
 *
13
 * @version 2.1 Beta 4
14
 */
15
16
/**
17
 * Class Birthday_Notify_Background
18
 */
19
class Birthday_Notify_Background extends SMF_BackgroundTask
0 ignored issues
show
Coding Style introduced by
This class is not in CamelCase format.

Classes in PHP are usually named in CamelCase.

In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. The whole name starts with a capital letter as well.

Thus the name database provider becomes DatabaseProvider.

Loading history...
20
{
21
    /**
22
     * This executes the task. It loads up the birthdays, figures out the greeting, etc.
23
     * @return bool Always returns true
24
     */
25
	public function execute()
26
 	{
27
		global $txt, $smcFunc, $txtBirthdayEmails, $modSettings, $sourcedir;
28
29
		$greeting = isset($modSettings['birthday_email']) ? $modSettings['birthday_email'] : 'happy_birthday';
30
31
		// Get the month and day of today.
32
		$month = date('n'); // Month without leading zeros.
33
		$day = date('j'); // Day without leading zeros.
34
35
		// So who are the lucky ones?  Don't include those who are banned and those who don't want them.
36
		$result = $smcFunc['db_query']('', '
37
			SELECT id_member, real_name, lngfile, email_address
38
			FROM {db_prefix}members
39
			WHERE is_activated < 10
40
				AND MONTH(birthdate) = {int:month}
41
				AND DAYOFMONTH(birthdate) = {int:day}
42
				AND YEAR(birthdate) > {int:year}',
43
			array(
44
				'year' => 1,
45
				'month' => $month,
46
				'day' => $day,
47
			)
48
		);
49
50
		// Group them by languages.
51
		$birthdays = array();
52
		while ($row = $smcFunc['db_fetch_assoc']($result))
53
		{
54
			if (!isset($birthdays[$row['lngfile']]))
55
				$birthdays[$row['lngfile']] = array();
56
			$birthdays[$row['lngfile']][$row['id_member']] = array(
57
				'name' => $row['real_name'],
58
				'email' => $row['email_address']
59
			);
60
		}
61
		$smcFunc['db_free_result']($result);
62
63
		if (!empty($birthdays))
64
		{
65
			require_once($sourcedir . '/ScheduledTasks.php');
66
			loadEssentialThemeData();
67
			// We need this for sendmail and AddMailQueue
68
			require_once($sourcedir . '/Subs-Post.php');
69
70
			// Send out the greetings!
71
			foreach ($birthdays as $lang => $members)
72
			{
73
				// We need to do some shuffling to make this work properly.
74
				loadLanguage('EmailTemplates', $lang);
75
				$txt['happy_birthday_subject'] = $txtBirthdayEmails[$greeting . '_subject'];
76
				$txt['happy_birthday_body'] = $txtBirthdayEmails[$greeting . '_body'];
77
				require_once($sourcedir . '/Subs-Notify.php');
78
79
				$prefs = getNotifyPrefs(array_keys($members), array('birthday'), true);
80
81
				foreach ($members as $member_id => $member)
82
				{
83
					$pref = !empty($prefs[$member_id]['birthday']) ? $prefs[$member_id]['birthday'] : 0;
84
85
					// Let's load replacements ahead
86
					$replacements = array(
87
						'REALNAME' => $member['name'],
88
					);
89
90
					if ($pref & 0x01)
91
					{
92
						$alertdata = loadEmailTemplate('happy_birthday', $replacements, $lang, false);
93
						// For the alerts, we need to replace \n line breaks with <br> line breaks.
94
						// For space saving sake, we'll be removing extra line breaks
95
						$alertdata['body'] = preg_replace("~\s*[\r\n]+\s*~", '<br>', $alertdata['body']);
96
						$alert_rows[] = array(
0 ignored issues
show
Coding Style Comprehensibility introduced by
$alert_rows was never initialized. Although not strictly required by PHP, it is generally a good practice to add $alert_rows = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
97
							'alert_time' => time(),
98
							'id_member' => $member_id,
99
							'content_type' => 'birthday',
100
							'content_id' => 0,
101
							'content_action' => 'msg',
102
							'is_read' => 0,
103
							'extra' => $smcFunc['json_encode'](array('happy_birthday' => $alertdata['body'])),
104
						);
105
						updateMemberData($member_id, array('alerts' => '+'));
106
					}
107
108
					if ($pref & 0x02)
109
					{
110
						$emaildata = loadEmailTemplate('happy_birthday', $replacements, $lang, false);
111
						sendmail($member['email'], $emaildata['subject'], $emaildata['body'], null, 'birthday', $emaildata['is_html'], 4);
112
					}
113
				}
114
			}
115
116
			// Flush the mail queue, just in case.
117
			AddMailQueue(true);
118
119
			// Insert the alerts if any
120 View Code Duplication
			if (!empty($alert_rows))
121
				$smcFunc['db_insert']('',
122
					'{db_prefix}user_alerts',
123
					array(
124
						'alert_time' => 'int', 'id_member' => 'int', 'content_type' => 'string',
125
						'content_id' => 'int', 'content_action' => 'string', 'is_read' => 'int', 'extra' => 'string',
126
					),
127
					$alert_rows,
128
					array()
129
				);
130
		}
131
132
		return true;
133
	}
134
}
135
136
?>