Completed
Pull Request — newinternal (#285)
by Simon
07:17 queued 04:17
created
includes/StringFunctions.php 2 patches
Indentation   +64 added lines, -64 removed lines patch added patch discarded remove patch
@@ -10,77 +10,77 @@
 block discarded – undo
10 10
 
11 11
 class StringFunctions
12 12
 {
13
-    /**
14
-     * Formats a string to be used as a username.
15
-     *
16
-     * @param $username
17
-     *
18
-     * @return string
19
-     */
20
-    public function formatAsUsername($username)
21
-    {
22
-        // trim whitespace from the ends
23
-        $uname = mb_ereg_replace("^[ \t]+|[ \t]+$", "", $username);
13
+	/**
14
+	 * Formats a string to be used as a username.
15
+	 *
16
+	 * @param $username
17
+	 *
18
+	 * @return string
19
+	 */
20
+	public function formatAsUsername($username)
21
+	{
22
+		// trim whitespace from the ends
23
+		$uname = mb_ereg_replace("^[ \t]+|[ \t]+$", "", $username);
24 24
 
25
-        // convert first char to uppercase
26
-        $uname = $this->ucfirst($uname);
25
+		// convert first char to uppercase
26
+		$uname = $this->ucfirst($uname);
27 27
 
28
-        // replace spaces with underscores
29
-        $uname = mb_ereg_replace("[ ]+", "_", $uname);
28
+		// replace spaces with underscores
29
+		$uname = mb_ereg_replace("[ ]+", "_", $uname);
30 30
 
31
-        // trim underscores from the end
32
-        $uname = mb_ereg_replace("[_]+$", "", $uname);
31
+		// trim underscores from the end
32
+		$uname = mb_ereg_replace("[_]+$", "", $uname);
33 33
 
34
-        return $uname;
35
-    }
34
+		return $uname;
35
+	}
36 36
 
37
-    /**
38
-     * Formats a string to be used as an email (specifically strips whitespace
39
-     * from the beginning/end of the Email, as well as immediately before/after
40
-     * the @ in the Email).
41
-     *
42
-     * @param $email
43
-     *
44
-     * @return string
45
-     */
46
-    public static function formatAsEmail($email)
47
-    {
48
-        // trim whitespace from the ends
49
-        $newemail = mb_ereg_replace("^[ \t]+|[ \t]+$", "", $email);
37
+	/**
38
+	 * Formats a string to be used as an email (specifically strips whitespace
39
+	 * from the beginning/end of the Email, as well as immediately before/after
40
+	 * the @ in the Email).
41
+	 *
42
+	 * @param $email
43
+	 *
44
+	 * @return string
45
+	 */
46
+	public static function formatAsEmail($email)
47
+	{
48
+		// trim whitespace from the ends
49
+		$newemail = mb_ereg_replace("^[ \t]+|[ \t]+$", "", $email);
50 50
 
51
-        // trim whitespace from around the email address
52
-        $newemail = mb_ereg_replace("[ \t]+@", "@", $newemail);
53
-        $newemail = mb_ereg_replace("@[ \t]+", "@", $newemail);
51
+		// trim whitespace from around the email address
52
+		$newemail = mb_ereg_replace("[ \t]+@", "@", $newemail);
53
+		$newemail = mb_ereg_replace("@[ \t]+", "@", $newemail);
54 54
 
55
-        return $newemail;
56
-    }
55
+		return $newemail;
56
+	}
57 57
 
58
-    /**
59
-     * Returns true if a string is a multibyte string
60
-     *
61
-     * @param string $string
62
-     *
63
-     * @return bool
64
-     */
65
-    public function isMultibyte($string)
66
-    {
67
-        return strlen($string) !== mb_strlen($string);
68
-    }
58
+	/**
59
+	 * Returns true if a string is a multibyte string
60
+	 *
61
+	 * @param string $string
62
+	 *
63
+	 * @return bool
64
+	 */
65
+	public function isMultibyte($string)
66
+	{
67
+		return strlen($string) !== mb_strlen($string);
68
+	}
69 69
 
70
-    /**
71
-     * Make a string's first character uppercase
72
-     *
73
-     * @param string $string
74
-     *
75
-     * @return string
76
-     */
77
-    public function ucfirst($string)
78
-    {
79
-        if (ord($string) < 128) {
80
-            return ucfirst($string);
81
-        }
82
-        else {
83
-            return mb_strtoupper(mb_substr($string, 0, 1)) . mb_substr($string, 1);
84
-        }
85
-    }
70
+	/**
71
+	 * Make a string's first character uppercase
72
+	 *
73
+	 * @param string $string
74
+	 *
75
+	 * @return string
76
+	 */
77
+	public function ucfirst($string)
78
+	{
79
+		if (ord($string) < 128) {
80
+			return ucfirst($string);
81
+		}
82
+		else {
83
+			return mb_strtoupper(mb_substr($string, 0, 1)) . mb_substr($string, 1);
84
+		}
85
+	}
86 86
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -80,7 +80,7 @@
 block discarded – undo
80 80
             return ucfirst($string);
81 81
         }
82 82
         else {
83
-            return mb_strtoupper(mb_substr($string, 0, 1)) . mb_substr($string, 1);
83
+            return mb_strtoupper(mb_substr($string, 0, 1)).mb_substr($string, 1);
84 84
         }
85 85
     }
86 86
 }
Please login to merge, or discard this patch.
includes/ConsoleTasks/UpdateTorExitTask.php 1 patch
Indentation   +10 added lines, -10 removed lines patch added patch discarded remove patch
@@ -13,14 +13,14 @@
 block discarded – undo
13 13
 
14 14
 class UpdateTorExitTask extends ConsoleTaskBase
15 15
 {
16
-    /**
17
-     * @return void
18
-     */
19
-    public function execute()
20
-    {
21
-        TorExitProvider::regenerate(
22
-            $this->getDatabase(),
23
-            $this->getHttpHelper(),
24
-            $this->getSiteConfiguration()->getTorExitPaths());
25
-    }
16
+	/**
17
+	 * @return void
18
+	 */
19
+	public function execute()
20
+	{
21
+		TorExitProvider::regenerate(
22
+			$this->getDatabase(),
23
+			$this->getHttpHelper(),
24
+			$this->getSiteConfiguration()->getTorExitPaths());
25
+	}
26 26
 }
27 27
\ No newline at end of file
Please login to merge, or discard this patch.
includes/ConsoleTasks/ClearOAuthDataTask.php 1 patch
Indentation   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -12,14 +12,14 @@  discard block
 block discarded – undo
12 12
 
13 13
 class ClearOAuthDataTask extends ConsoleTaskBase
14 14
 {
15
-    public function execute()
16
-    {
17
-        // @fixme this is unsafe.
18
-        // What we should be doing is iterating over all OAuth users, fetching their username, and updating the onwiki
19
-        // name for the user at the same time as blatting out the OAuth credentials, otherwise we risk losing all links
20
-        // to the user's onwiki account.
15
+	public function execute()
16
+	{
17
+		// @fixme this is unsafe.
18
+		// What we should be doing is iterating over all OAuth users, fetching their username, and updating the onwiki
19
+		// name for the user at the same time as blatting out the OAuth credentials, otherwise we risk losing all links
20
+		// to the user's onwiki account.
21 21
 
22
-        $this->getDatabase()->exec(<<<SQL
22
+		$this->getDatabase()->exec(<<<SQL
23 23
         UPDATE user
24 24
         SET
25 25
             oauthrequesttoken = NULL,
@@ -28,6 +28,6 @@  discard block
 block discarded – undo
28 28
             oauthaccesssecret = NULL,
29 29
             oauthidentitycache = NULL;
30 30
 SQL
31
-        );
32
-    }
31
+		);
32
+	}
33 33
 }
34 34
\ No newline at end of file
Please login to merge, or discard this patch.
includes/ConsoleTasks/RecreateTrustedIpTableTask.php 2 patches
Indentation   +148 added lines, -148 removed lines patch added patch discarded remove patch
@@ -16,152 +16,152 @@
 block discarded – undo
16 16
 
17 17
 class RecreateTrustedIpTableTask extends ConsoleTaskBase
18 18
 {
19
-    public function execute()
20
-    {
21
-
22
-        echo "Fetching file...\n";
23
-
24
-        $htmlfile = file($this->getSiteConfiguration()->getXffTrustedHostsFile(),
25
-            FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
26
-
27
-        $ip = array();
28
-        $iprange = array();
29
-        $dnsdomain = array();
30
-
31
-        echo "Sorting file...\n";
32
-        $this->readFile($htmlfile, $iprange, $ip, $dnsdomain);
33
-
34
-        echo "Exploding CIDRs...\n";
35
-        $this->explodeCidrs($iprange, $ip);
36
-
37
-        echo "Resolving DNS...\n";
38
-        $this->resolveDns($dnsdomain, $ip);
39
-
40
-        echo "Uniq-ing array...\n";
41
-
42
-        $ip = array_unique($ip);
43
-
44
-        $database = $this->getDatabase();
45
-
46
-        $database->exec('DELETE FROM xfftrustcache;');
47
-
48
-        $insert = $database->prepare('INSERT INTO xfftrustcache (ip) VALUES (:ip);');
49
-
50
-        $this->doInserts($ip, $insert);
51
-    }
52
-
53
-    /**
54
-     * @param string[] $dnsDomains  the DNS domains to resolve
55
-     * @param string[] $ipAddresses existing array of IPs to add to
56
-     */
57
-    protected function resolveDns($dnsDomains, &$ipAddresses)
58
-    {
59
-        foreach ($dnsDomains as $domain) {
60
-            $ipList = gethostbynamel($domain);
61
-
62
-            if ($ipList === false) {
63
-                echo "Invalid DNS name $domain\n";
64
-                continue;
65
-            }
66
-
67
-            foreach ($ipList as $ipAddress) {
68
-                $ipAddresses[] = $ipAddress;
69
-            }
70
-
71
-            // don't DoS
72
-            usleep(10000);
73
-        }
74
-    }
75
-
76
-    /**
77
-     * @param $iprange
78
-     * @param $ip
79
-     */
80
-    protected function explodeCidrs($iprange, &$ip)
81
-    {
82
-        foreach ($iprange as $r) {
83
-            $ips = $this->getXffTrustProvider()->explodeCidr($r);
84
-
85
-            foreach ($ips as $i) {
86
-                $ip[] = $i;
87
-            }
88
-        }
89
-    }
90
-
91
-    /**
92
-     * @param $htmlfile
93
-     * @param $iprange
94
-     * @param $ip
95
-     * @param $dnsdomain
96
-     */
97
-    protected function readFile($htmlfile, &$iprange, &$ip, &$dnsdomain)
98
-    {
99
-        foreach ($htmlfile as $line_num => $rawline) {
100
-            // remove the comments
101
-            $hashPos = strpos($rawline, '#');
102
-            if ($hashPos !== false) {
103
-                $line = substr($rawline, 0, $hashPos);
104
-            }
105
-            else {
106
-                $line = $rawline;
107
-            }
108
-
109
-            $line = trim($line);
110
-
111
-            // this was a comment or empty line...
112
-            if ($line == "") {
113
-                continue;
114
-            }
115
-
116
-            // match a regex of an CIDR range:
117
-            $ipcidr = '@' . RegexConstants::IPV4 . RegexConstants::IPV4_CIDR . '@';
118
-            if (preg_match($ipcidr, $line) === 1) {
119
-                $iprange[] = $line;
120
-                continue;
121
-            }
122
-
123
-            $ipnoncidr = '@' . RegexConstants::IPV4 . '@';
124
-            if (preg_match($ipnoncidr, $line) === 1) {
125
-                $ip[] = $line;
126
-                continue;
127
-            }
128
-
129
-            // it's probably a DNS name.
130
-            $dnsdomain[] = $line;
131
-        }
132
-    }
133
-
134
-    /**
135
-     * @param array        $ip
136
-     * @param PDOStatement $insert
137
-     *
138
-     * @throws Exception
139
-     */
140
-    protected function doInserts($ip, PDOStatement $insert)
141
-    {
142
-        $successful = true;
143
-
144
-        foreach ($ip as $i) {
145
-            if (count($i) > 15) {
146
-                echo "Rejected $i\n";
147
-                $successful = false;
148
-
149
-                continue;
150
-            }
151
-
152
-            try {
153
-                $insert->execute(array(':ip' => $i));
154
-            }
155
-            catch (PDOException $ex) {
156
-                echo "Exception on $i :\n";
157
-                echo $ex->getMessage();
158
-                $successful = false;
159
-                break;
160
-            }
161
-        }
162
-
163
-        if (!$successful) {
164
-            throw new Exception('Encountered errors during transaction processing');
165
-        }
166
-    }
19
+	public function execute()
20
+	{
21
+
22
+		echo "Fetching file...\n";
23
+
24
+		$htmlfile = file($this->getSiteConfiguration()->getXffTrustedHostsFile(),
25
+			FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
26
+
27
+		$ip = array();
28
+		$iprange = array();
29
+		$dnsdomain = array();
30
+
31
+		echo "Sorting file...\n";
32
+		$this->readFile($htmlfile, $iprange, $ip, $dnsdomain);
33
+
34
+		echo "Exploding CIDRs...\n";
35
+		$this->explodeCidrs($iprange, $ip);
36
+
37
+		echo "Resolving DNS...\n";
38
+		$this->resolveDns($dnsdomain, $ip);
39
+
40
+		echo "Uniq-ing array...\n";
41
+
42
+		$ip = array_unique($ip);
43
+
44
+		$database = $this->getDatabase();
45
+
46
+		$database->exec('DELETE FROM xfftrustcache;');
47
+
48
+		$insert = $database->prepare('INSERT INTO xfftrustcache (ip) VALUES (:ip);');
49
+
50
+		$this->doInserts($ip, $insert);
51
+	}
52
+
53
+	/**
54
+	 * @param string[] $dnsDomains  the DNS domains to resolve
55
+	 * @param string[] $ipAddresses existing array of IPs to add to
56
+	 */
57
+	protected function resolveDns($dnsDomains, &$ipAddresses)
58
+	{
59
+		foreach ($dnsDomains as $domain) {
60
+			$ipList = gethostbynamel($domain);
61
+
62
+			if ($ipList === false) {
63
+				echo "Invalid DNS name $domain\n";
64
+				continue;
65
+			}
66
+
67
+			foreach ($ipList as $ipAddress) {
68
+				$ipAddresses[] = $ipAddress;
69
+			}
70
+
71
+			// don't DoS
72
+			usleep(10000);
73
+		}
74
+	}
75
+
76
+	/**
77
+	 * @param $iprange
78
+	 * @param $ip
79
+	 */
80
+	protected function explodeCidrs($iprange, &$ip)
81
+	{
82
+		foreach ($iprange as $r) {
83
+			$ips = $this->getXffTrustProvider()->explodeCidr($r);
84
+
85
+			foreach ($ips as $i) {
86
+				$ip[] = $i;
87
+			}
88
+		}
89
+	}
90
+
91
+	/**
92
+	 * @param $htmlfile
93
+	 * @param $iprange
94
+	 * @param $ip
95
+	 * @param $dnsdomain
96
+	 */
97
+	protected function readFile($htmlfile, &$iprange, &$ip, &$dnsdomain)
98
+	{
99
+		foreach ($htmlfile as $line_num => $rawline) {
100
+			// remove the comments
101
+			$hashPos = strpos($rawline, '#');
102
+			if ($hashPos !== false) {
103
+				$line = substr($rawline, 0, $hashPos);
104
+			}
105
+			else {
106
+				$line = $rawline;
107
+			}
108
+
109
+			$line = trim($line);
110
+
111
+			// this was a comment or empty line...
112
+			if ($line == "") {
113
+				continue;
114
+			}
115
+
116
+			// match a regex of an CIDR range:
117
+			$ipcidr = '@' . RegexConstants::IPV4 . RegexConstants::IPV4_CIDR . '@';
118
+			if (preg_match($ipcidr, $line) === 1) {
119
+				$iprange[] = $line;
120
+				continue;
121
+			}
122
+
123
+			$ipnoncidr = '@' . RegexConstants::IPV4 . '@';
124
+			if (preg_match($ipnoncidr, $line) === 1) {
125
+				$ip[] = $line;
126
+				continue;
127
+			}
128
+
129
+			// it's probably a DNS name.
130
+			$dnsdomain[] = $line;
131
+		}
132
+	}
133
+
134
+	/**
135
+	 * @param array        $ip
136
+	 * @param PDOStatement $insert
137
+	 *
138
+	 * @throws Exception
139
+	 */
140
+	protected function doInserts($ip, PDOStatement $insert)
141
+	{
142
+		$successful = true;
143
+
144
+		foreach ($ip as $i) {
145
+			if (count($i) > 15) {
146
+				echo "Rejected $i\n";
147
+				$successful = false;
148
+
149
+				continue;
150
+			}
151
+
152
+			try {
153
+				$insert->execute(array(':ip' => $i));
154
+			}
155
+			catch (PDOException $ex) {
156
+				echo "Exception on $i :\n";
157
+				echo $ex->getMessage();
158
+				$successful = false;
159
+				break;
160
+			}
161
+		}
162
+
163
+		if (!$successful) {
164
+			throw new Exception('Encountered errors during transaction processing');
165
+		}
166
+	}
167 167
 }
168 168
\ No newline at end of file
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -114,13 +114,13 @@
 block discarded – undo
114 114
             }
115 115
 
116 116
             // match a regex of an CIDR range:
117
-            $ipcidr = '@' . RegexConstants::IPV4 . RegexConstants::IPV4_CIDR . '@';
117
+            $ipcidr = '@'.RegexConstants::IPV4.RegexConstants::IPV4_CIDR.'@';
118 118
             if (preg_match($ipcidr, $line) === 1) {
119 119
                 $iprange[] = $line;
120 120
                 continue;
121 121
             }
122 122
 
123
-            $ipnoncidr = '@' . RegexConstants::IPV4 . '@';
123
+            $ipnoncidr = '@'.RegexConstants::IPV4.'@';
124 124
             if (preg_match($ipnoncidr, $line) === 1) {
125 125
                 $ip[] = $line;
126 126
                 continue;
Please login to merge, or discard this patch.
includes/ConsoleTasks/ClearExpiredIdentificationData.php 1 patch
Indentation   +7 added lines, -7 removed lines patch added patch discarded remove patch
@@ -13,11 +13,11 @@
 block discarded – undo
13 13
 
14 14
 class ClearExpiredIdentificationData extends ConsoleTaskBase
15 15
 {
16
-    /**
17
-     * @return void
18
-     */
19
-    public function execute()
20
-    {
21
-        IdentificationVerifier::clearExpiredCacheEntries($this->getSiteConfiguration(), $this->getDatabase());
22
-    }
16
+	/**
17
+	 * @return void
18
+	 */
19
+	public function execute()
20
+	{
21
+		IdentificationVerifier::clearExpiredCacheEntries($this->getSiteConfiguration(), $this->getDatabase());
22
+	}
23 23
 }
Please login to merge, or discard this patch.
includes/ConsoleTasks/OldRequestCleanupTask.php 1 patch
Indentation   +15 added lines, -15 removed lines patch added patch discarded remove patch
@@ -12,28 +12,28 @@
 block discarded – undo
12 12
 
13 13
 class OldRequestCleanupTask extends ConsoleTaskBase
14 14
 {
15
-    private $expiryTime;
15
+	private $expiryTime;
16 16
 
17
-    /**
18
-     * OldRequestCleanupTask constructor.
19
-     */
20
-    public function __construct()
21
-    {
22
-        $this->expiryTime = $this->getSiteConfiguration()->getEmailConfirmationExpiryDays();
23
-    }
17
+	/**
18
+	 * OldRequestCleanupTask constructor.
19
+	 */
20
+	public function __construct()
21
+	{
22
+		$this->expiryTime = $this->getSiteConfiguration()->getEmailConfirmationExpiryDays();
23
+	}
24 24
 
25
-    public function execute()
26
-    {
27
-        $statement = $this->getDatabase()->prepare(<<<SQL
25
+	public function execute()
26
+	{
27
+		$statement = $this->getDatabase()->prepare(<<<SQL
28 28
             DELETE FROM request
29 29
             WHERE
30 30
                 date < DATE_SUB(CURRENT_TIMESTAMP(), INTERVAL :expiry DAY)
31 31
                 AND emailconfirm != 'Confirmed'
32 32
                 AND emailconfirm != '';
33 33
 SQL
34
-        );
34
+		);
35 35
 
36
-        $statement->bindValue(':expiry', $this->expiryTime);
37
-        $statement->execute();
38
-    }
36
+		$statement->bindValue(':expiry', $this->expiryTime);
37
+		$statement->execute();
38
+	}
39 39
 }
40 40
\ No newline at end of file
Please login to merge, or discard this patch.
includes/ApplicationBase.php 1 patch
Indentation   +151 added lines, -151 removed lines patch added patch discarded remove patch
@@ -25,155 +25,155 @@
 block discarded – undo
25 25
 
26 26
 abstract class ApplicationBase
27 27
 {
28
-    private $configuration;
29
-
30
-    public function __construct(SiteConfiguration $configuration)
31
-    {
32
-        $this->configuration = $configuration;
33
-    }
34
-
35
-    /**
36
-     * Application entry point.
37
-     *
38
-     * Sets up the environment and runs the application, performing any global cleanup operations when done.
39
-     */
40
-    public function run()
41
-    {
42
-        try {
43
-            if ($this->setupEnvironment()) {
44
-                $this->main();
45
-            }
46
-        }
47
-        catch (Exception $ex) {
48
-            print $ex->getMessage();
49
-        }
50
-        finally {
51
-            $this->cleanupEnvironment();
52
-        }
53
-    }
54
-
55
-    /**
56
-     * Environment setup
57
-     *
58
-     * This method initialises the tool environment. If the tool cannot be initialised correctly, it will return false
59
-     * and shut down prematurely.
60
-     *
61
-     * @return bool
62
-     * @throws EnvironmentException
63
-     */
64
-    protected function setupEnvironment()
65
-    {
66
-        $this->setupDatabase();
67
-
68
-        return true;
69
-    }
70
-
71
-    /**
72
-     * @return PdoDatabase
73
-     * @throws EnvironmentException
74
-     * @throws Exception
75
-     */
76
-    protected function setupDatabase()
77
-    {
78
-        // check the schema version
79
-        $database = PdoDatabase::getDatabaseConnection('acc');
80
-
81
-        /** @var int $actualVersion */
82
-        $actualVersion = (int)$database->query('SELECT version FROM schemaversion')->fetchColumn();
83
-        if ($actualVersion !== $this->getConfiguration()->getSchemaVersion()) {
84
-            throw new EnvironmentException('Database schema is wrong version! Please either update configuration or database.');
85
-        }
86
-
87
-        return $database;
88
-    }
89
-
90
-    /**
91
-     * @return SiteConfiguration
92
-     */
93
-    public function getConfiguration()
94
-    {
95
-        return $this->configuration;
96
-    }
97
-
98
-    /**
99
-     * Main application logic
100
-     * @return void
101
-     */
102
-    abstract protected function main();
103
-
104
-    /**
105
-     * Any cleanup tasks should go here
106
-     *
107
-     * Note that we need to be very careful here, as exceptions may have been thrown and handled.
108
-     * This should *only* be for cleaning up, no logic should go here.
109
-     *
110
-     * @return void
111
-     */
112
-    abstract protected function cleanupEnvironment();
113
-
114
-    /**
115
-     * @param ITask             $page
116
-     * @param SiteConfiguration $siteConfiguration
117
-     * @param PdoDatabase       $database
118
-     * @param PdoDatabase       $notificationsDatabase
119
-     *
120
-     * @return void
121
-     */
122
-    protected function setupHelpers(
123
-        ITask $page,
124
-        SiteConfiguration $siteConfiguration,
125
-        PdoDatabase $database,
126
-        PdoDatabase $notificationsDatabase = null
127
-    ) {
128
-        $page->setSiteConfiguration($siteConfiguration);
129
-
130
-        // setup the global database object
131
-        $page->setDatabase($database);
132
-
133
-        // set up helpers and inject them into the page.
134
-        $httpHelper = new HttpHelper(
135
-            $siteConfiguration->getUserAgent(),
136
-            $siteConfiguration->getCurlDisableVerifyPeer()
137
-        );
138
-
139
-        $page->setEmailHelper(new EmailHelper());
140
-        $page->setHttpHelper($httpHelper);
141
-        $page->setWikiTextHelper(new WikiTextHelper($siteConfiguration, $page->getHttpHelper()));
142
-
143
-        if ($siteConfiguration->getLocationProviderApiKey() === null) {
144
-            $page->setLocationProvider(new FakeLocationProvider());
145
-        }
146
-        else {
147
-            $page->setLocationProvider(
148
-                new IpLocationProvider(
149
-                    $database,
150
-                    $siteConfiguration->getLocationProviderApiKey(),
151
-                    $httpHelper
152
-                ));
153
-        }
154
-
155
-        $page->setXffTrustProvider(new XffTrustProvider($siteConfiguration->getSquidList(), $database));
156
-
157
-        $page->setRdnsProvider(new CachedRDnsLookupProvider($database));
158
-
159
-        $page->setAntiSpoofProvider(new CachedApiAntispoofProvider(
160
-            $database,
161
-            $this->getConfiguration()->getMediawikiWebServiceEndpoint(),
162
-            $httpHelper));
163
-
164
-        $page->setOAuthHelper(new OAuthHelper(
165
-            $siteConfiguration->getOAuthBaseUrl(),
166
-            $siteConfiguration->getOAuthConsumerToken(),
167
-            $siteConfiguration->getOAuthConsumerSecret(),
168
-            $httpHelper,
169
-            $siteConfiguration->getMediawikiWebServiceEndpoint()
170
-        ));
171
-
172
-        $page->setNotificationHelper(new IrcNotificationHelper(
173
-            $siteConfiguration,
174
-            $database,
175
-            $notificationsDatabase));
176
-
177
-        $page->setTorExitProvider(new TorExitProvider($database));
178
-    }
28
+	private $configuration;
29
+
30
+	public function __construct(SiteConfiguration $configuration)
31
+	{
32
+		$this->configuration = $configuration;
33
+	}
34
+
35
+	/**
36
+	 * Application entry point.
37
+	 *
38
+	 * Sets up the environment and runs the application, performing any global cleanup operations when done.
39
+	 */
40
+	public function run()
41
+	{
42
+		try {
43
+			if ($this->setupEnvironment()) {
44
+				$this->main();
45
+			}
46
+		}
47
+		catch (Exception $ex) {
48
+			print $ex->getMessage();
49
+		}
50
+		finally {
51
+			$this->cleanupEnvironment();
52
+		}
53
+	}
54
+
55
+	/**
56
+	 * Environment setup
57
+	 *
58
+	 * This method initialises the tool environment. If the tool cannot be initialised correctly, it will return false
59
+	 * and shut down prematurely.
60
+	 *
61
+	 * @return bool
62
+	 * @throws EnvironmentException
63
+	 */
64
+	protected function setupEnvironment()
65
+	{
66
+		$this->setupDatabase();
67
+
68
+		return true;
69
+	}
70
+
71
+	/**
72
+	 * @return PdoDatabase
73
+	 * @throws EnvironmentException
74
+	 * @throws Exception
75
+	 */
76
+	protected function setupDatabase()
77
+	{
78
+		// check the schema version
79
+		$database = PdoDatabase::getDatabaseConnection('acc');
80
+
81
+		/** @var int $actualVersion */
82
+		$actualVersion = (int)$database->query('SELECT version FROM schemaversion')->fetchColumn();
83
+		if ($actualVersion !== $this->getConfiguration()->getSchemaVersion()) {
84
+			throw new EnvironmentException('Database schema is wrong version! Please either update configuration or database.');
85
+		}
86
+
87
+		return $database;
88
+	}
89
+
90
+	/**
91
+	 * @return SiteConfiguration
92
+	 */
93
+	public function getConfiguration()
94
+	{
95
+		return $this->configuration;
96
+	}
97
+
98
+	/**
99
+	 * Main application logic
100
+	 * @return void
101
+	 */
102
+	abstract protected function main();
103
+
104
+	/**
105
+	 * Any cleanup tasks should go here
106
+	 *
107
+	 * Note that we need to be very careful here, as exceptions may have been thrown and handled.
108
+	 * This should *only* be for cleaning up, no logic should go here.
109
+	 *
110
+	 * @return void
111
+	 */
112
+	abstract protected function cleanupEnvironment();
113
+
114
+	/**
115
+	 * @param ITask             $page
116
+	 * @param SiteConfiguration $siteConfiguration
117
+	 * @param PdoDatabase       $database
118
+	 * @param PdoDatabase       $notificationsDatabase
119
+	 *
120
+	 * @return void
121
+	 */
122
+	protected function setupHelpers(
123
+		ITask $page,
124
+		SiteConfiguration $siteConfiguration,
125
+		PdoDatabase $database,
126
+		PdoDatabase $notificationsDatabase = null
127
+	) {
128
+		$page->setSiteConfiguration($siteConfiguration);
129
+
130
+		// setup the global database object
131
+		$page->setDatabase($database);
132
+
133
+		// set up helpers and inject them into the page.
134
+		$httpHelper = new HttpHelper(
135
+			$siteConfiguration->getUserAgent(),
136
+			$siteConfiguration->getCurlDisableVerifyPeer()
137
+		);
138
+
139
+		$page->setEmailHelper(new EmailHelper());
140
+		$page->setHttpHelper($httpHelper);
141
+		$page->setWikiTextHelper(new WikiTextHelper($siteConfiguration, $page->getHttpHelper()));
142
+
143
+		if ($siteConfiguration->getLocationProviderApiKey() === null) {
144
+			$page->setLocationProvider(new FakeLocationProvider());
145
+		}
146
+		else {
147
+			$page->setLocationProvider(
148
+				new IpLocationProvider(
149
+					$database,
150
+					$siteConfiguration->getLocationProviderApiKey(),
151
+					$httpHelper
152
+				));
153
+		}
154
+
155
+		$page->setXffTrustProvider(new XffTrustProvider($siteConfiguration->getSquidList(), $database));
156
+
157
+		$page->setRdnsProvider(new CachedRDnsLookupProvider($database));
158
+
159
+		$page->setAntiSpoofProvider(new CachedApiAntispoofProvider(
160
+			$database,
161
+			$this->getConfiguration()->getMediawikiWebServiceEndpoint(),
162
+			$httpHelper));
163
+
164
+		$page->setOAuthHelper(new OAuthHelper(
165
+			$siteConfiguration->getOAuthBaseUrl(),
166
+			$siteConfiguration->getOAuthConsumerToken(),
167
+			$siteConfiguration->getOAuthConsumerSecret(),
168
+			$httpHelper,
169
+			$siteConfiguration->getMediawikiWebServiceEndpoint()
170
+		));
171
+
172
+		$page->setNotificationHelper(new IrcNotificationHelper(
173
+			$siteConfiguration,
174
+			$database,
175
+			$notificationsDatabase));
176
+
177
+		$page->setTorExitProvider(new TorExitProvider($database));
178
+	}
179 179
 }
180 180
\ No newline at end of file
Please login to merge, or discard this patch.
includes/RegexConstants.php 1 patch
Indentation   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -10,8 +10,8 @@
 block discarded – undo
10 10
 
11 11
 class RegexConstants
12 12
 {
13
-    const IPV6_CIDR = '(?:/(?:12[0-8]|1[01][0-9]|[0-9]{1,2}))?';
14
-    const IPV4_CIDR = '(?:/(?:32|3[01]|[0-2]?[0-9]))?';
15
-    const IPV4 = '(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)';
16
-    const IPV6 = '(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))';
13
+	const IPV6_CIDR = '(?:/(?:12[0-8]|1[01][0-9]|[0-9]{1,2}))?';
14
+	const IPV4_CIDR = '(?:/(?:32|3[01]|[0-2]?[0-9]))?';
15
+	const IPV4 = '(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)';
16
+	const IPV6 = '(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))';
17 17
 }
18 18
\ No newline at end of file
Please login to merge, or discard this patch.
includes/Helpers/IrcNotificationHelper.php 2 patches
Indentation   +439 added lines, -439 removed lines patch added patch discarded remove patch
@@ -26,445 +26,445 @@
 block discarded – undo
26 26
  */
27 27
 class IrcNotificationHelper
28 28
 {
29
-    /** @var PdoDatabase $notificationsDatabase */
30
-    private $notificationsDatabase;
31
-    /** @var PdoDatabase $primaryDatabase */
32
-    private $primaryDatabase;
33
-    /** @var bool $notificationsEnabled */
34
-    private $notificationsEnabled;
35
-    /** @var int $notificationType */
36
-    private $notificationType;
37
-    /** @var User $currentUser */
38
-    private $currentUser;
39
-    /** @var string $instanceName */
40
-    private $instanceName;
41
-    /** @var string */
42
-    private $baseUrl;
43
-    /** @var array */
44
-    private $requestStates;
45
-
46
-    /**
47
-     * IrcNotificationHelper constructor.
48
-     *
49
-     * @param SiteConfiguration $siteConfiguration
50
-     * @param PdoDatabase       $primaryDatabase
51
-     * @param PdoDatabase       $notificationsDatabase
52
-     */
53
-    public function __construct(
54
-        SiteConfiguration $siteConfiguration,
55
-        PdoDatabase $primaryDatabase,
56
-        PdoDatabase $notificationsDatabase = null
57
-    ) {
58
-        $this->primaryDatabase = $primaryDatabase;
59
-
60
-        if ($this->notificationsDatabase !== null) {
61
-            $this->notificationsDatabase = $notificationsDatabase;
62
-            $this->notificationsEnabled = $siteConfiguration->getIrcNotificationsEnabled();
63
-        }
64
-        else {
65
-            $this->notificationsEnabled = false;
66
-        }
67
-
68
-        $this->notificationType = $siteConfiguration->getIrcNotificationType();
69
-        $this->instanceName = $siteConfiguration->getIrcNotificationsInstance();
70
-        $this->baseUrl = $siteConfiguration->getBaseUrl();
71
-        $this->requestStates = $siteConfiguration->getRequestStates();
72
-
73
-        $this->currentUser = User::getCurrent($primaryDatabase);
74
-    }
75
-
76
-    /**
77
-     * Send a notification
78
-     *
79
-     * @param string $message The text to send
80
-     */
81
-    protected function send($message)
82
-    {
83
-        $instanceName = $this->instanceName;
84
-
85
-        if (!$this->notificationsEnabled) {
86
-            return;
87
-        }
88
-
89
-        $blacklist = array("DCC", "CCTP", "PRIVMSG");
90
-        $message = str_replace($blacklist, "(IRC Blacklist)", $message); // Lets stop DCC etc
91
-
92
-        $msg = IrcColourCode::RESET . IrcColourCode::BOLD . "[$instanceName]" . IrcColourCode::RESET . ": $message";
93
-
94
-        try {
95
-            $notification = new Notification();
96
-            $notification->setDatabase($this->notificationsDatabase);
97
-            $notification->setType($this->notificationType);
98
-            $notification->setText($msg);
99
-
100
-            $notification->save();
101
-        }
102
-        catch (Exception $ex) {
103
-            // OK, so we failed to send the notification - that db might be down?
104
-            // This is non-critical, so silently fail.
105
-
106
-            // Disable notifications for remainder of request.
107
-            $this->notificationsEnabled = false;
108
-        }
109
-    }
110
-
111
-    #region user management
112
-
113
-    /**
114
-     * send a new user notification
115
-     *
116
-     * @param User $user
117
-     */
118
-    public function userNew(User $user)
119
-    {
120
-        $this->send("New user: {$user->getUsername()}");
121
-    }
122
-
123
-    /**
124
-     * send an approved notification
125
-     *
126
-     * @param User $user
127
-     */
128
-    public function userApproved(User $user)
129
-    {
130
-        $this->send("{$user->getUsername()} approved by " . $this->currentUser->getUsername());
131
-    }
132
-
133
-    /**
134
-     * send a promoted notification
135
-     *
136
-     * @param User $user
137
-     */
138
-    public function userPromoted(User $user)
139
-    {
140
-        $this->send("{$user->getUsername()} promoted to tool admin by " . $this->currentUser->getUsername());
141
-    }
142
-
143
-    /**
144
-     * send a declined notification
145
-     *
146
-     * @param User   $user
147
-     * @param string $reason the reason the user was declined
148
-     */
149
-    public function userDeclined(User $user, $reason)
150
-    {
151
-        $this->send("{$user->getUsername()} declined by " . $this->currentUser->getUsername() . " ($reason)");
152
-    }
153
-
154
-    /**
155
-     * send a demotion notification
156
-     *
157
-     * @param User   $user
158
-     * @param string $reason the reason the user was demoted
159
-     */
160
-    public function userDemoted(User $user, $reason)
161
-    {
162
-        $this->send("{$user->getUsername()} demoted by " . $this->currentUser->getUsername() . " ($reason)");
163
-    }
164
-
165
-    /**
166
-     * send a suspended notification
167
-     *
168
-     * @param User   $user
169
-     * @param string $reason The reason the user has been suspended
170
-     */
171
-    public function userSuspended(User $user, $reason)
172
-    {
173
-        $this->send("{$user->getUsername()} suspended by " . $this->currentUser->getUsername() . " ($reason)");
174
-    }
175
-
176
-    /**
177
-     * Send a preference change notification
178
-     *
179
-     * @param User $user
180
-     */
181
-    public function userPrefChange(User $user)
182
-    {
183
-        $this->send("{$user->getUsername()}'s preferences were changed by " . $this->currentUser->getUsername());
184
-    }
185
-
186
-    /**
187
-     * Send a user renamed notification
188
-     *
189
-     * @param User   $user
190
-     * @param string $old
191
-     */
192
-    public function userRenamed(User $user, $old)
193
-    {
194
-        $this->send($this->currentUser->getUsername() . " renamed $old to {$user->getUsername()}");
195
-    }
196
-
197
-    #endregion
198
-
199
-    #region Site Notice
200
-
201
-    /**
202
-     * Summary of siteNoticeEdited
203
-     */
204
-    public function siteNoticeEdited()
205
-    {
206
-        $this->send("Site notice edited by " . $this->currentUser->getUsername());
207
-    }
208
-    #endregion
209
-
210
-    #region Welcome Templates
211
-    /**
212
-     * Summary of welcomeTemplateCreated
213
-     *
214
-     * @param WelcomeTemplate $template
215
-     */
216
-    public function welcomeTemplateCreated(WelcomeTemplate $template)
217
-    {
218
-        $this->send("Welcome template {$template->getId()} created by " . $this->currentUser->getUsername());
219
-    }
220
-
221
-    /**
222
-     * Summary of welcomeTemplateDeleted
223
-     *
224
-     * @param int $templateid
225
-     */
226
-    public function welcomeTemplateDeleted($templateid)
227
-    {
228
-        $this->send("Welcome template {$templateid} deleted by " . $this->currentUser->getUsername());
229
-    }
230
-
231
-    /**
232
-     * Summary of welcomeTemplateEdited
233
-     *
234
-     * @param WelcomeTemplate $template
235
-     */
236
-    public function welcomeTemplateEdited(WelcomeTemplate $template)
237
-    {
238
-        $this->send("Welcome template {$template->getId()} edited by " . $this->currentUser->getUsername());
239
-    }
240
-
241
-    #endregion
242
-
243
-    #region bans
244
-    /**
245
-     * Summary of banned
246
-     *
247
-     * @param Ban $ban
248
-     */
249
-    public function banned(Ban $ban)
250
-    {
251
-        if ($ban->getDuration() == -1) {
252
-            $duration = "indefinitely";
253
-        }
254
-        else {
255
-            $duration = "until " . date("F j, Y, g:i a", $ban->getDuration());
256
-        }
257
-
258
-        $username = $this->currentUser->getUsername();
259
-
260
-        $this->send("{$ban->getTarget()} banned by {$username} for '{$ban->getReason()}' {$duration}");
261
-    }
262
-
263
-    /**
264
-     * Summary of unbanned
265
-     *
266
-     * @param Ban    $ban
267
-     * @param string $unbanreason
268
-     */
269
-    public function unbanned(Ban $ban, $unbanreason)
270
-    {
271
-        $this->send($ban->getTarget() . " unbanned by " . $this->currentUser
272
-                ->getUsername() . " (" . $unbanreason . ")");
273
-    }
274
-
275
-    #endregion
276
-
277
-    #region request management
278
-
279
-    /**
280
-     * Summary of requestReceived
281
-     *
282
-     * @param Request $request
283
-     */
284
-    public function requestReceived(Request $request)
285
-    {
286
-        $this->send(
287
-            IrcColourCode::DARK_GREY . "[["
288
-            . IrcColourCode::DARK_GREEN . "acc:"
289
-            . IrcColourCode::ORANGE . $request->getId()
290
-            . IrcColourCode::DARK_GREY . "]]"
291
-            . IrcColourCode::RED . " N "
292
-            . IrcColourCode::DARK_BLUE . $this->baseUrl . "/internal.php/viewRequest?id={$request->getId()} "
293
-            . IrcColourCode::DARK_RED . "* "
294
-            . IrcColourCode::DARK_GREEN . $request->getName()
295
-            . IrcColourCode::DARK_RED . " * "
296
-            . IrcColourCode::RESET
297
-        );
298
-    }
299
-
300
-    /**
301
-     * Summary of requestDeferred
302
-     *
303
-     * @param Request $request
304
-     */
305
-    public function requestDeferred(Request $request)
306
-    {
307
-        $availableRequestStates = $this->requestStates;
308
-
309
-        $deferTo = $availableRequestStates[$request->getStatus()]['deferto'];
310
-        $username = $this->currentUser->getUsername();
311
-
312
-        $this->send("Request {$request->getId()} ({$request->getName()}) deferred to {$deferTo} by {$username}");
313
-    }
314
-
315
-    /**
316
-     *
317
-     * Summary of requestDeferredWithMail
318
-     *
319
-     * @param Request $request
320
-     */
321
-    public function requestDeferredWithMail(Request $request)
322
-    {
323
-        $availableRequestStates = $this->requestStates;
324
-
325
-        $deferTo = $availableRequestStates[$request->getStatus()]['deferto'];
326
-        $username = $this->currentUser->getUsername();
327
-        $id = $request->getId();
328
-        $name = $request->getName();
329
-
330
-        $this->send("Request {$id} ({$name}) deferred to {$deferTo} with an email by {$username}");
331
-    }
332
-
333
-    /**
334
-     * Summary of requestClosed
335
-     *
336
-     * @param Request $request
337
-     * @param string  $closetype
338
-     */
339
-    public function requestClosed(Request $request, $closetype)
340
-    {
341
-        $username = $this->currentUser->getUsername();
342
-
343
-        $this->send("Request {$request->getId()} ({$request->getName()}) closed ($closetype) by {$username}");
344
-    }
345
-
346
-    /**
347
-     * Summary of sentMail
348
-     *
349
-     * @param Request $request
350
-     */
351
-    public function sentMail(Request $request)
352
-    {
353
-        $this->send($this->currentUser->getUsername()
354
-            . " sent an email related to Request {$request->getId()} ({$request->getName()})");
355
-    }
356
-
357
-    #endregion
358
-
359
-    #region reservations
360
-
361
-    /**
362
-     * Summary of requestReserved
363
-     *
364
-     * @param Request $request
365
-     */
366
-    public function requestReserved(Request $request)
367
-    {
368
-        $username = $this->currentUser->getUsername();
369
-
370
-        $this->send("Request {$request->getId()} ({$request->getName()}) reserved by {$username}");
371
-    }
372
-
373
-    /**
374
-     * Summary of requestReserveBroken
375
-     *
376
-     * @param Request $request
377
-     */
378
-    public function requestReserveBroken(Request $request)
379
-    {
380
-        $username = $this->currentUser->getUsername();
381
-
382
-        $this->send("Reservation on request {$request->getId()} ({$request->getName()}) broken by {$username}");
383
-    }
384
-
385
-    /**
386
-     * Summary of requestUnreserved
387
-     *
388
-     * @param Request $request
389
-     */
390
-    public function requestUnreserved(Request $request)
391
-    {
392
-        $this->send("Request {$request->getId()} ({$request->getName()}) is no longer being handled.");
393
-    }
394
-
395
-    /**
396
-     * Summary of requestReservationSent
397
-     *
398
-     * @param Request $request
399
-     * @param User    $target
400
-     */
401
-    public function requestReservationSent(Request $request, User $target)
402
-    {
403
-        $username = $this->currentUser->getUsername();
404
-
405
-        $this->send(
406
-            "Reservation of request {$request->getId()} ({$request->getName()}) sent to {$target->getUsername()} by "
407
-            . $username);
408
-    }
409
-
410
-    #endregion
411
-
412
-    #region comments
413
-
414
-    /**
415
-     * Summary of commentCreated
416
-     *
417
-     * @param Comment $comment
418
-     * @param Request $request
419
-     */
420
-    public function commentCreated(Comment $comment, Request $request)
421
-    {
422
-        $username = $this->currentUser->getUsername();
423
-        $visibility = ($comment->getVisibility() == "admin" ? "private " : "");
424
-
425
-        $this->send("{$username} posted a {$visibility}comment on request {$request->getId()} ({$request->getName()})");
426
-    }
427
-
428
-    /**
429
-     * Summary of commentEdited
430
-     *
431
-     * @param Comment $comment
432
-     * @param Request $request
433
-     */
434
-    public function commentEdited(Comment $comment, Request $request)
435
-    {
436
-        $username = $this->currentUser->getUsername();
437
-
438
-        $this->send(<<<TAG
29
+	/** @var PdoDatabase $notificationsDatabase */
30
+	private $notificationsDatabase;
31
+	/** @var PdoDatabase $primaryDatabase */
32
+	private $primaryDatabase;
33
+	/** @var bool $notificationsEnabled */
34
+	private $notificationsEnabled;
35
+	/** @var int $notificationType */
36
+	private $notificationType;
37
+	/** @var User $currentUser */
38
+	private $currentUser;
39
+	/** @var string $instanceName */
40
+	private $instanceName;
41
+	/** @var string */
42
+	private $baseUrl;
43
+	/** @var array */
44
+	private $requestStates;
45
+
46
+	/**
47
+	 * IrcNotificationHelper constructor.
48
+	 *
49
+	 * @param SiteConfiguration $siteConfiguration
50
+	 * @param PdoDatabase       $primaryDatabase
51
+	 * @param PdoDatabase       $notificationsDatabase
52
+	 */
53
+	public function __construct(
54
+		SiteConfiguration $siteConfiguration,
55
+		PdoDatabase $primaryDatabase,
56
+		PdoDatabase $notificationsDatabase = null
57
+	) {
58
+		$this->primaryDatabase = $primaryDatabase;
59
+
60
+		if ($this->notificationsDatabase !== null) {
61
+			$this->notificationsDatabase = $notificationsDatabase;
62
+			$this->notificationsEnabled = $siteConfiguration->getIrcNotificationsEnabled();
63
+		}
64
+		else {
65
+			$this->notificationsEnabled = false;
66
+		}
67
+
68
+		$this->notificationType = $siteConfiguration->getIrcNotificationType();
69
+		$this->instanceName = $siteConfiguration->getIrcNotificationsInstance();
70
+		$this->baseUrl = $siteConfiguration->getBaseUrl();
71
+		$this->requestStates = $siteConfiguration->getRequestStates();
72
+
73
+		$this->currentUser = User::getCurrent($primaryDatabase);
74
+	}
75
+
76
+	/**
77
+	 * Send a notification
78
+	 *
79
+	 * @param string $message The text to send
80
+	 */
81
+	protected function send($message)
82
+	{
83
+		$instanceName = $this->instanceName;
84
+
85
+		if (!$this->notificationsEnabled) {
86
+			return;
87
+		}
88
+
89
+		$blacklist = array("DCC", "CCTP", "PRIVMSG");
90
+		$message = str_replace($blacklist, "(IRC Blacklist)", $message); // Lets stop DCC etc
91
+
92
+		$msg = IrcColourCode::RESET . IrcColourCode::BOLD . "[$instanceName]" . IrcColourCode::RESET . ": $message";
93
+
94
+		try {
95
+			$notification = new Notification();
96
+			$notification->setDatabase($this->notificationsDatabase);
97
+			$notification->setType($this->notificationType);
98
+			$notification->setText($msg);
99
+
100
+			$notification->save();
101
+		}
102
+		catch (Exception $ex) {
103
+			// OK, so we failed to send the notification - that db might be down?
104
+			// This is non-critical, so silently fail.
105
+
106
+			// Disable notifications for remainder of request.
107
+			$this->notificationsEnabled = false;
108
+		}
109
+	}
110
+
111
+	#region user management
112
+
113
+	/**
114
+	 * send a new user notification
115
+	 *
116
+	 * @param User $user
117
+	 */
118
+	public function userNew(User $user)
119
+	{
120
+		$this->send("New user: {$user->getUsername()}");
121
+	}
122
+
123
+	/**
124
+	 * send an approved notification
125
+	 *
126
+	 * @param User $user
127
+	 */
128
+	public function userApproved(User $user)
129
+	{
130
+		$this->send("{$user->getUsername()} approved by " . $this->currentUser->getUsername());
131
+	}
132
+
133
+	/**
134
+	 * send a promoted notification
135
+	 *
136
+	 * @param User $user
137
+	 */
138
+	public function userPromoted(User $user)
139
+	{
140
+		$this->send("{$user->getUsername()} promoted to tool admin by " . $this->currentUser->getUsername());
141
+	}
142
+
143
+	/**
144
+	 * send a declined notification
145
+	 *
146
+	 * @param User   $user
147
+	 * @param string $reason the reason the user was declined
148
+	 */
149
+	public function userDeclined(User $user, $reason)
150
+	{
151
+		$this->send("{$user->getUsername()} declined by " . $this->currentUser->getUsername() . " ($reason)");
152
+	}
153
+
154
+	/**
155
+	 * send a demotion notification
156
+	 *
157
+	 * @param User   $user
158
+	 * @param string $reason the reason the user was demoted
159
+	 */
160
+	public function userDemoted(User $user, $reason)
161
+	{
162
+		$this->send("{$user->getUsername()} demoted by " . $this->currentUser->getUsername() . " ($reason)");
163
+	}
164
+
165
+	/**
166
+	 * send a suspended notification
167
+	 *
168
+	 * @param User   $user
169
+	 * @param string $reason The reason the user has been suspended
170
+	 */
171
+	public function userSuspended(User $user, $reason)
172
+	{
173
+		$this->send("{$user->getUsername()} suspended by " . $this->currentUser->getUsername() . " ($reason)");
174
+	}
175
+
176
+	/**
177
+	 * Send a preference change notification
178
+	 *
179
+	 * @param User $user
180
+	 */
181
+	public function userPrefChange(User $user)
182
+	{
183
+		$this->send("{$user->getUsername()}'s preferences were changed by " . $this->currentUser->getUsername());
184
+	}
185
+
186
+	/**
187
+	 * Send a user renamed notification
188
+	 *
189
+	 * @param User   $user
190
+	 * @param string $old
191
+	 */
192
+	public function userRenamed(User $user, $old)
193
+	{
194
+		$this->send($this->currentUser->getUsername() . " renamed $old to {$user->getUsername()}");
195
+	}
196
+
197
+	#endregion
198
+
199
+	#region Site Notice
200
+
201
+	/**
202
+	 * Summary of siteNoticeEdited
203
+	 */
204
+	public function siteNoticeEdited()
205
+	{
206
+		$this->send("Site notice edited by " . $this->currentUser->getUsername());
207
+	}
208
+	#endregion
209
+
210
+	#region Welcome Templates
211
+	/**
212
+	 * Summary of welcomeTemplateCreated
213
+	 *
214
+	 * @param WelcomeTemplate $template
215
+	 */
216
+	public function welcomeTemplateCreated(WelcomeTemplate $template)
217
+	{
218
+		$this->send("Welcome template {$template->getId()} created by " . $this->currentUser->getUsername());
219
+	}
220
+
221
+	/**
222
+	 * Summary of welcomeTemplateDeleted
223
+	 *
224
+	 * @param int $templateid
225
+	 */
226
+	public function welcomeTemplateDeleted($templateid)
227
+	{
228
+		$this->send("Welcome template {$templateid} deleted by " . $this->currentUser->getUsername());
229
+	}
230
+
231
+	/**
232
+	 * Summary of welcomeTemplateEdited
233
+	 *
234
+	 * @param WelcomeTemplate $template
235
+	 */
236
+	public function welcomeTemplateEdited(WelcomeTemplate $template)
237
+	{
238
+		$this->send("Welcome template {$template->getId()} edited by " . $this->currentUser->getUsername());
239
+	}
240
+
241
+	#endregion
242
+
243
+	#region bans
244
+	/**
245
+	 * Summary of banned
246
+	 *
247
+	 * @param Ban $ban
248
+	 */
249
+	public function banned(Ban $ban)
250
+	{
251
+		if ($ban->getDuration() == -1) {
252
+			$duration = "indefinitely";
253
+		}
254
+		else {
255
+			$duration = "until " . date("F j, Y, g:i a", $ban->getDuration());
256
+		}
257
+
258
+		$username = $this->currentUser->getUsername();
259
+
260
+		$this->send("{$ban->getTarget()} banned by {$username} for '{$ban->getReason()}' {$duration}");
261
+	}
262
+
263
+	/**
264
+	 * Summary of unbanned
265
+	 *
266
+	 * @param Ban    $ban
267
+	 * @param string $unbanreason
268
+	 */
269
+	public function unbanned(Ban $ban, $unbanreason)
270
+	{
271
+		$this->send($ban->getTarget() . " unbanned by " . $this->currentUser
272
+				->getUsername() . " (" . $unbanreason . ")");
273
+	}
274
+
275
+	#endregion
276
+
277
+	#region request management
278
+
279
+	/**
280
+	 * Summary of requestReceived
281
+	 *
282
+	 * @param Request $request
283
+	 */
284
+	public function requestReceived(Request $request)
285
+	{
286
+		$this->send(
287
+			IrcColourCode::DARK_GREY . "[["
288
+			. IrcColourCode::DARK_GREEN . "acc:"
289
+			. IrcColourCode::ORANGE . $request->getId()
290
+			. IrcColourCode::DARK_GREY . "]]"
291
+			. IrcColourCode::RED . " N "
292
+			. IrcColourCode::DARK_BLUE . $this->baseUrl . "/internal.php/viewRequest?id={$request->getId()} "
293
+			. IrcColourCode::DARK_RED . "* "
294
+			. IrcColourCode::DARK_GREEN . $request->getName()
295
+			. IrcColourCode::DARK_RED . " * "
296
+			. IrcColourCode::RESET
297
+		);
298
+	}
299
+
300
+	/**
301
+	 * Summary of requestDeferred
302
+	 *
303
+	 * @param Request $request
304
+	 */
305
+	public function requestDeferred(Request $request)
306
+	{
307
+		$availableRequestStates = $this->requestStates;
308
+
309
+		$deferTo = $availableRequestStates[$request->getStatus()]['deferto'];
310
+		$username = $this->currentUser->getUsername();
311
+
312
+		$this->send("Request {$request->getId()} ({$request->getName()}) deferred to {$deferTo} by {$username}");
313
+	}
314
+
315
+	/**
316
+	 *
317
+	 * Summary of requestDeferredWithMail
318
+	 *
319
+	 * @param Request $request
320
+	 */
321
+	public function requestDeferredWithMail(Request $request)
322
+	{
323
+		$availableRequestStates = $this->requestStates;
324
+
325
+		$deferTo = $availableRequestStates[$request->getStatus()]['deferto'];
326
+		$username = $this->currentUser->getUsername();
327
+		$id = $request->getId();
328
+		$name = $request->getName();
329
+
330
+		$this->send("Request {$id} ({$name}) deferred to {$deferTo} with an email by {$username}");
331
+	}
332
+
333
+	/**
334
+	 * Summary of requestClosed
335
+	 *
336
+	 * @param Request $request
337
+	 * @param string  $closetype
338
+	 */
339
+	public function requestClosed(Request $request, $closetype)
340
+	{
341
+		$username = $this->currentUser->getUsername();
342
+
343
+		$this->send("Request {$request->getId()} ({$request->getName()}) closed ($closetype) by {$username}");
344
+	}
345
+
346
+	/**
347
+	 * Summary of sentMail
348
+	 *
349
+	 * @param Request $request
350
+	 */
351
+	public function sentMail(Request $request)
352
+	{
353
+		$this->send($this->currentUser->getUsername()
354
+			. " sent an email related to Request {$request->getId()} ({$request->getName()})");
355
+	}
356
+
357
+	#endregion
358
+
359
+	#region reservations
360
+
361
+	/**
362
+	 * Summary of requestReserved
363
+	 *
364
+	 * @param Request $request
365
+	 */
366
+	public function requestReserved(Request $request)
367
+	{
368
+		$username = $this->currentUser->getUsername();
369
+
370
+		$this->send("Request {$request->getId()} ({$request->getName()}) reserved by {$username}");
371
+	}
372
+
373
+	/**
374
+	 * Summary of requestReserveBroken
375
+	 *
376
+	 * @param Request $request
377
+	 */
378
+	public function requestReserveBroken(Request $request)
379
+	{
380
+		$username = $this->currentUser->getUsername();
381
+
382
+		$this->send("Reservation on request {$request->getId()} ({$request->getName()}) broken by {$username}");
383
+	}
384
+
385
+	/**
386
+	 * Summary of requestUnreserved
387
+	 *
388
+	 * @param Request $request
389
+	 */
390
+	public function requestUnreserved(Request $request)
391
+	{
392
+		$this->send("Request {$request->getId()} ({$request->getName()}) is no longer being handled.");
393
+	}
394
+
395
+	/**
396
+	 * Summary of requestReservationSent
397
+	 *
398
+	 * @param Request $request
399
+	 * @param User    $target
400
+	 */
401
+	public function requestReservationSent(Request $request, User $target)
402
+	{
403
+		$username = $this->currentUser->getUsername();
404
+
405
+		$this->send(
406
+			"Reservation of request {$request->getId()} ({$request->getName()}) sent to {$target->getUsername()} by "
407
+			. $username);
408
+	}
409
+
410
+	#endregion
411
+
412
+	#region comments
413
+
414
+	/**
415
+	 * Summary of commentCreated
416
+	 *
417
+	 * @param Comment $comment
418
+	 * @param Request $request
419
+	 */
420
+	public function commentCreated(Comment $comment, Request $request)
421
+	{
422
+		$username = $this->currentUser->getUsername();
423
+		$visibility = ($comment->getVisibility() == "admin" ? "private " : "");
424
+
425
+		$this->send("{$username} posted a {$visibility}comment on request {$request->getId()} ({$request->getName()})");
426
+	}
427
+
428
+	/**
429
+	 * Summary of commentEdited
430
+	 *
431
+	 * @param Comment $comment
432
+	 * @param Request $request
433
+	 */
434
+	public function commentEdited(Comment $comment, Request $request)
435
+	{
436
+		$username = $this->currentUser->getUsername();
437
+
438
+		$this->send(<<<TAG
439 439
 Comment {$comment->getId()} on request {$request->getId()} ({$request->getName()}) edited by {$username}
440 440
 TAG
441
-        );
442
-    }
443
-
444
-    #endregion
445
-
446
-    #region email management (close reasons)
447
-
448
-    /**
449
-     * Summary of emailCreated
450
-     *
451
-     * @param EmailTemplate $template
452
-     */
453
-    public function emailCreated(EmailTemplate $template)
454
-    {
455
-        $username = $this->currentUser->getUsername();
456
-        $this->send("Email {$template->getId()} ({$template->getName()}) created by " . $username);
457
-    }
458
-
459
-    /**
460
-     * Summary of emailEdited
461
-     *
462
-     * @param EmailTemplate $template
463
-     */
464
-    public function emailEdited(EmailTemplate $template)
465
-    {
466
-        $username = $this->currentUser->getUsername();
467
-        $this->send("Email {$template->getId()} ({$template->getName()}) edited by " . $username);
468
-    }
469
-    #endregion
441
+		);
442
+	}
443
+
444
+	#endregion
445
+
446
+	#region email management (close reasons)
447
+
448
+	/**
449
+	 * Summary of emailCreated
450
+	 *
451
+	 * @param EmailTemplate $template
452
+	 */
453
+	public function emailCreated(EmailTemplate $template)
454
+	{
455
+		$username = $this->currentUser->getUsername();
456
+		$this->send("Email {$template->getId()} ({$template->getName()}) created by " . $username);
457
+	}
458
+
459
+	/**
460
+	 * Summary of emailEdited
461
+	 *
462
+	 * @param EmailTemplate $template
463
+	 */
464
+	public function emailEdited(EmailTemplate $template)
465
+	{
466
+		$username = $this->currentUser->getUsername();
467
+		$this->send("Email {$template->getId()} ({$template->getName()}) edited by " . $username);
468
+	}
469
+	#endregion
470 470
 }
471 471
\ No newline at end of file
Please login to merge, or discard this patch.
Spacing   +26 added lines, -26 removed lines patch added patch discarded remove patch
@@ -89,7 +89,7 @@  discard block
 block discarded – undo
89 89
         $blacklist = array("DCC", "CCTP", "PRIVMSG");
90 90
         $message = str_replace($blacklist, "(IRC Blacklist)", $message); // Lets stop DCC etc
91 91
 
92
-        $msg = IrcColourCode::RESET . IrcColourCode::BOLD . "[$instanceName]" . IrcColourCode::RESET . ": $message";
92
+        $msg = IrcColourCode::RESET.IrcColourCode::BOLD."[$instanceName]".IrcColourCode::RESET.": $message";
93 93
 
94 94
         try {
95 95
             $notification = new Notification();
@@ -127,7 +127,7 @@  discard block
 block discarded – undo
127 127
      */
128 128
     public function userApproved(User $user)
129 129
     {
130
-        $this->send("{$user->getUsername()} approved by " . $this->currentUser->getUsername());
130
+        $this->send("{$user->getUsername()} approved by ".$this->currentUser->getUsername());
131 131
     }
132 132
 
133 133
     /**
@@ -137,7 +137,7 @@  discard block
 block discarded – undo
137 137
      */
138 138
     public function userPromoted(User $user)
139 139
     {
140
-        $this->send("{$user->getUsername()} promoted to tool admin by " . $this->currentUser->getUsername());
140
+        $this->send("{$user->getUsername()} promoted to tool admin by ".$this->currentUser->getUsername());
141 141
     }
142 142
 
143 143
     /**
@@ -148,7 +148,7 @@  discard block
 block discarded – undo
148 148
      */
149 149
     public function userDeclined(User $user, $reason)
150 150
     {
151
-        $this->send("{$user->getUsername()} declined by " . $this->currentUser->getUsername() . " ($reason)");
151
+        $this->send("{$user->getUsername()} declined by ".$this->currentUser->getUsername()." ($reason)");
152 152
     }
153 153
 
154 154
     /**
@@ -159,7 +159,7 @@  discard block
 block discarded – undo
159 159
      */
160 160
     public function userDemoted(User $user, $reason)
161 161
     {
162
-        $this->send("{$user->getUsername()} demoted by " . $this->currentUser->getUsername() . " ($reason)");
162
+        $this->send("{$user->getUsername()} demoted by ".$this->currentUser->getUsername()." ($reason)");
163 163
     }
164 164
 
165 165
     /**
@@ -170,7 +170,7 @@  discard block
 block discarded – undo
170 170
      */
171 171
     public function userSuspended(User $user, $reason)
172 172
     {
173
-        $this->send("{$user->getUsername()} suspended by " . $this->currentUser->getUsername() . " ($reason)");
173
+        $this->send("{$user->getUsername()} suspended by ".$this->currentUser->getUsername()." ($reason)");
174 174
     }
175 175
 
176 176
     /**
@@ -180,7 +180,7 @@  discard block
 block discarded – undo
180 180
      */
181 181
     public function userPrefChange(User $user)
182 182
     {
183
-        $this->send("{$user->getUsername()}'s preferences were changed by " . $this->currentUser->getUsername());
183
+        $this->send("{$user->getUsername()}'s preferences were changed by ".$this->currentUser->getUsername());
184 184
     }
185 185
 
186 186
     /**
@@ -191,7 +191,7 @@  discard block
 block discarded – undo
191 191
      */
192 192
     public function userRenamed(User $user, $old)
193 193
     {
194
-        $this->send($this->currentUser->getUsername() . " renamed $old to {$user->getUsername()}");
194
+        $this->send($this->currentUser->getUsername()." renamed $old to {$user->getUsername()}");
195 195
     }
196 196
 
197 197
     #endregion
@@ -203,7 +203,7 @@  discard block
 block discarded – undo
203 203
      */
204 204
     public function siteNoticeEdited()
205 205
     {
206
-        $this->send("Site notice edited by " . $this->currentUser->getUsername());
206
+        $this->send("Site notice edited by ".$this->currentUser->getUsername());
207 207
     }
208 208
     #endregion
209 209
 
@@ -215,7 +215,7 @@  discard block
 block discarded – undo
215 215
      */
216 216
     public function welcomeTemplateCreated(WelcomeTemplate $template)
217 217
     {
218
-        $this->send("Welcome template {$template->getId()} created by " . $this->currentUser->getUsername());
218
+        $this->send("Welcome template {$template->getId()} created by ".$this->currentUser->getUsername());
219 219
     }
220 220
 
221 221
     /**
@@ -225,7 +225,7 @@  discard block
 block discarded – undo
225 225
      */
226 226
     public function welcomeTemplateDeleted($templateid)
227 227
     {
228
-        $this->send("Welcome template {$templateid} deleted by " . $this->currentUser->getUsername());
228
+        $this->send("Welcome template {$templateid} deleted by ".$this->currentUser->getUsername());
229 229
     }
230 230
 
231 231
     /**
@@ -235,7 +235,7 @@  discard block
 block discarded – undo
235 235
      */
236 236
     public function welcomeTemplateEdited(WelcomeTemplate $template)
237 237
     {
238
-        $this->send("Welcome template {$template->getId()} edited by " . $this->currentUser->getUsername());
238
+        $this->send("Welcome template {$template->getId()} edited by ".$this->currentUser->getUsername());
239 239
     }
240 240
 
241 241
     #endregion
@@ -252,7 +252,7 @@  discard block
 block discarded – undo
252 252
             $duration = "indefinitely";
253 253
         }
254 254
         else {
255
-            $duration = "until " . date("F j, Y, g:i a", $ban->getDuration());
255
+            $duration = "until ".date("F j, Y, g:i a", $ban->getDuration());
256 256
         }
257 257
 
258 258
         $username = $this->currentUser->getUsername();
@@ -268,8 +268,8 @@  discard block
 block discarded – undo
268 268
      */
269 269
     public function unbanned(Ban $ban, $unbanreason)
270 270
     {
271
-        $this->send($ban->getTarget() . " unbanned by " . $this->currentUser
272
-                ->getUsername() . " (" . $unbanreason . ")");
271
+        $this->send($ban->getTarget()." unbanned by ".$this->currentUser
272
+                ->getUsername()." (".$unbanreason.")");
273 273
     }
274 274
 
275 275
     #endregion
@@ -284,15 +284,15 @@  discard block
 block discarded – undo
284 284
     public function requestReceived(Request $request)
285 285
     {
286 286
         $this->send(
287
-            IrcColourCode::DARK_GREY . "[["
288
-            . IrcColourCode::DARK_GREEN . "acc:"
289
-            . IrcColourCode::ORANGE . $request->getId()
290
-            . IrcColourCode::DARK_GREY . "]]"
291
-            . IrcColourCode::RED . " N "
292
-            . IrcColourCode::DARK_BLUE . $this->baseUrl . "/internal.php/viewRequest?id={$request->getId()} "
293
-            . IrcColourCode::DARK_RED . "* "
294
-            . IrcColourCode::DARK_GREEN . $request->getName()
295
-            . IrcColourCode::DARK_RED . " * "
287
+            IrcColourCode::DARK_GREY."[["
288
+            . IrcColourCode::DARK_GREEN."acc:"
289
+            . IrcColourCode::ORANGE.$request->getId()
290
+            . IrcColourCode::DARK_GREY."]]"
291
+            . IrcColourCode::RED." N "
292
+            . IrcColourCode::DARK_BLUE.$this->baseUrl."/internal.php/viewRequest?id={$request->getId()} "
293
+            . IrcColourCode::DARK_RED."* "
294
+            . IrcColourCode::DARK_GREEN.$request->getName()
295
+            . IrcColourCode::DARK_RED." * "
296 296
             . IrcColourCode::RESET
297 297
         );
298 298
     }
@@ -453,7 +453,7 @@  discard block
 block discarded – undo
453 453
     public function emailCreated(EmailTemplate $template)
454 454
     {
455 455
         $username = $this->currentUser->getUsername();
456
-        $this->send("Email {$template->getId()} ({$template->getName()}) created by " . $username);
456
+        $this->send("Email {$template->getId()} ({$template->getName()}) created by ".$username);
457 457
     }
458 458
 
459 459
     /**
@@ -464,7 +464,7 @@  discard block
 block discarded – undo
464 464
     public function emailEdited(EmailTemplate $template)
465 465
     {
466 466
         $username = $this->currentUser->getUsername();
467
-        $this->send("Email {$template->getId()} ({$template->getName()}) edited by " . $username);
467
+        $this->send("Email {$template->getId()} ({$template->getName()}) edited by ".$username);
468 468
     }
469 469
     #endregion
470 470
 }
471 471
\ No newline at end of file
Please login to merge, or discard this patch.