Test Failed
Push — dependabot/composer/newinterna... ( fef629 )
by
unknown
16:20 queued 10:15
created
includes/Helpers/SearchHelpers/JobQueueSearchHelper.php 2 patches
Indentation   +63 added lines, -63 removed lines patch added patch discarded remove patch
@@ -13,67 +13,67 @@
 block discarded – undo
13 13
 
14 14
 class JobQueueSearchHelper extends SearchHelperBase
15 15
 {
16
-    protected function __construct(PdoDatabase $database)
17
-    {
18
-        parent::__construct($database, 'jobqueue', JobQueue::class, null);
19
-    }
20
-
21
-    /**
22
-     * @param PdoDatabase $database
23
-     *
24
-     * @return JobQueueSearchHelper
25
-     */
26
-    public static function get(PdoDatabase $database) {
27
-        $helper = new JobQueueSearchHelper($database);
28
-        return $helper;
29
-    }
30
-
31
-    /**
32
-     * @param string[] $statuses
33
-     *
34
-     * @return $this
35
-     */
36
-    public function statusIn($statuses) {
37
-        $this->inClause('status', $statuses);
38
-
39
-        return $this;
40
-    }
41
-
42
-    /**
43
-     * @return $this
44
-     */
45
-    public function notAcknowledged() {
46
-        $this->whereClause .= ' AND (acknowledged IS NULL OR acknowledged = 0)';
47
-
48
-        return $this;
49
-    }
50
-
51
-    public function byTask($task) {
52
-        $this->whereClause .= ' AND task = ?';
53
-        $this->parameterList[] = $task;
54
-
55
-        return $this;
56
-    }
57
-
58
-    public function byUser($userId) {
59
-        $this->whereClause .= ' AND user = ?';
60
-        $this->parameterList[] = $userId;
61
-
62
-        return $this;
63
-    }
64
-
65
-    public function byStatus($status) {
66
-        $this->whereClause .= ' AND status = ?';
67
-        $this->parameterList[] = $status;
68
-
69
-        return $this;
70
-    }
71
-
72
-    public function byRequest(int $request) : JobQueueSearchHelper
73
-    {
74
-        $this->whereClause .= ' AND request = ?';
75
-        $this->parameterList[] = $request;
76
-
77
-        return $this;
78
-    }
16
+	protected function __construct(PdoDatabase $database)
17
+	{
18
+		parent::__construct($database, 'jobqueue', JobQueue::class, null);
19
+	}
20
+
21
+	/**
22
+	 * @param PdoDatabase $database
23
+	 *
24
+	 * @return JobQueueSearchHelper
25
+	 */
26
+	public static function get(PdoDatabase $database) {
27
+		$helper = new JobQueueSearchHelper($database);
28
+		return $helper;
29
+	}
30
+
31
+	/**
32
+	 * @param string[] $statuses
33
+	 *
34
+	 * @return $this
35
+	 */
36
+	public function statusIn($statuses) {
37
+		$this->inClause('status', $statuses);
38
+
39
+		return $this;
40
+	}
41
+
42
+	/**
43
+	 * @return $this
44
+	 */
45
+	public function notAcknowledged() {
46
+		$this->whereClause .= ' AND (acknowledged IS NULL OR acknowledged = 0)';
47
+
48
+		return $this;
49
+	}
50
+
51
+	public function byTask($task) {
52
+		$this->whereClause .= ' AND task = ?';
53
+		$this->parameterList[] = $task;
54
+
55
+		return $this;
56
+	}
57
+
58
+	public function byUser($userId) {
59
+		$this->whereClause .= ' AND user = ?';
60
+		$this->parameterList[] = $userId;
61
+
62
+		return $this;
63
+	}
64
+
65
+	public function byStatus($status) {
66
+		$this->whereClause .= ' AND status = ?';
67
+		$this->parameterList[] = $status;
68
+
69
+		return $this;
70
+	}
71
+
72
+	public function byRequest(int $request) : JobQueueSearchHelper
73
+	{
74
+		$this->whereClause .= ' AND request = ?';
75
+		$this->parameterList[] = $request;
76
+
77
+		return $this;
78
+	}
79 79
 }
Please login to merge, or discard this patch.
Braces   +12 added lines, -6 removed lines patch added patch discarded remove patch
@@ -23,7 +23,8 @@  discard block
 block discarded – undo
23 23
      *
24 24
      * @return JobQueueSearchHelper
25 25
      */
26
-    public static function get(PdoDatabase $database) {
26
+    public static function get(PdoDatabase $database)
27
+    {
27 28
         $helper = new JobQueueSearchHelper($database);
28 29
         return $helper;
29 30
     }
@@ -33,7 +34,8 @@  discard block
 block discarded – undo
33 34
      *
34 35
      * @return $this
35 36
      */
36
-    public function statusIn($statuses) {
37
+    public function statusIn($statuses)
38
+    {
37 39
         $this->inClause('status', $statuses);
38 40
 
39 41
         return $this;
@@ -42,27 +44,31 @@  discard block
 block discarded – undo
42 44
     /**
43 45
      * @return $this
44 46
      */
45
-    public function notAcknowledged() {
47
+    public function notAcknowledged()
48
+    {
46 49
         $this->whereClause .= ' AND (acknowledged IS NULL OR acknowledged = 0)';
47 50
 
48 51
         return $this;
49 52
     }
50 53
 
51
-    public function byTask($task) {
54
+    public function byTask($task)
55
+    {
52 56
         $this->whereClause .= ' AND task = ?';
53 57
         $this->parameterList[] = $task;
54 58
 
55 59
         return $this;
56 60
     }
57 61
 
58
-    public function byUser($userId) {
62
+    public function byUser($userId)
63
+    {
59 64
         $this->whereClause .= ' AND user = ?';
60 65
         $this->parameterList[] = $userId;
61 66
 
62 67
         return $this;
63 68
     }
64 69
 
65
-    public function byStatus($status) {
70
+    public function byStatus($status)
71
+    {
66 72
         $this->whereClause .= ' AND status = ?';
67 73
         $this->parameterList[] = $status;
68 74
 
Please login to merge, or discard this patch.
includes/Helpers/SearchHelpers/SearchHelperBase.php 1 patch
Indentation   +271 added lines, -271 removed lines patch added patch discarded remove patch
@@ -16,275 +16,275 @@
 block discarded – undo
16 16
 
17 17
 abstract class SearchHelperBase
18 18
 {
19
-    /** @var PdoDatabase */
20
-    protected $database;
21
-    /** @var array */
22
-    protected $parameterList = array();
23
-    /** @var null|int */
24
-    private $limit = null;
25
-    /** @var null|int */
26
-    private $offset = null;
27
-    private $orderBy;
28
-    /**
29
-     * @var string The where clause.
30
-     *
31
-     * (the 1=1 condition will be optimised out of the query by the query planner, and simplifies our code here). Note
32
-     * that we use positional parameters instead of named parameters because we don't know many times different options
33
-     * will be called (looking at excluding() here, but there's the option for others).
34
-     */
35
-    protected $whereClause = ' WHERE 1 = 1';
36
-    /** @var string */
37
-    protected $table;
38
-    protected $joinClause = '';
39
-    protected $groupByClause = '';
40
-    protected $modifiersClause = '';
41
-    private $targetClass;
42
-
43
-    /**
44
-     * SearchHelperBase constructor.
45
-     *
46
-     * @param PdoDatabase $database
47
-     * @param string      $table
48
-     * @param             $targetClass
49
-     * @param null|string $order Order by clause, excluding ORDER BY.
50
-     */
51
-    protected function __construct(PdoDatabase $database, $table, $targetClass, $order = null)
52
-    {
53
-        $this->database = $database;
54
-        $this->table = $table;
55
-        $this->orderBy = $order;
56
-        $this->targetClass = $targetClass;
57
-    }
58
-
59
-    /**
60
-     * Finalises the database query, and executes it, returning a set of objects.
61
-     *
62
-     * @return DataObject[]
63
-     */
64
-    public function fetch()
65
-    {
66
-        $statement = $this->getData();
67
-
68
-        /** @var DataObject[] $returnedObjects */
69
-        $returnedObjects = $statement->fetchAll(PDO::FETCH_CLASS, $this->targetClass);
70
-        foreach ($returnedObjects as $req) {
71
-            $req->setDatabase($this->database);
72
-        }
73
-
74
-        return $returnedObjects;
75
-    }
76
-
77
-    /**
78
-     * @param string $whereClauseSection
79
-     * @param array  $values
80
-     *
81
-     * @return array
82
-     */
83
-    protected function fetchByParameter($whereClauseSection, $values)
84
-    {
85
-        $this->whereClause .= $whereClauseSection;
86
-
87
-        $countQuery = 'SELECT /* SearchHelper */ COUNT(*) FROM ' . $this->table . ' origin ';
88
-        $countQuery .= $this->joinClause . $this->whereClause;
89
-
90
-        $query = $this->buildQuery(array('*'));
91
-        $query .= $this->applyOrder();
92
-
93
-        // shuffle around parameters
94
-        // applyLimit() appends parameters to the parameter list, which is useless when we want to run
95
-        // many queries with different parameters. As such, we back up the parameter list, wipe it, apply the limit
96
-        // parameters, and hold them separately, merging again prior to running the actual query.
97
-        $localParameterList = $this->parameterList;
98
-        $this->parameterList = array();
99
-        $query .= $this->applyLimit();
100
-        $limitParameters = $this->parameterList;
101
-
102
-        $statement = $this->database->prepare($query);
103
-        $countStatement = $this->database->prepare($countQuery);
104
-
105
-        $result = array();
106
-        foreach ($values as $v) {
107
-            // reset parameter list
108
-            $params = $localParameterList;
109
-            $params[] = $v;
110
-
111
-            $countStatement->execute($params);
112
-
113
-            // reapply the limit parameters
114
-            $params = array_merge($params, $limitParameters);
115
-
116
-            $statement->execute($params);
117
-
118
-            /** @var DataObject[] $returnedObjects */
119
-            $returnedObjects = $statement->fetchAll(PDO::FETCH_CLASS, $this->targetClass);
120
-            foreach ($returnedObjects as $req) {
121
-                $req->setDatabase($this->database);
122
-            }
123
-
124
-            $result[$v] = array(
125
-                'count' => $countStatement->fetchColumn(0),
126
-                'data'  => $returnedObjects,
127
-            );
128
-        }
129
-
130
-        return $result;
131
-    }
132
-
133
-    /**
134
-     * Finalises the database query, and executes it, returning only the requested column.
135
-     *
136
-     * @param string $column The required column
137
-     *
138
-     * @param bool   $distinct
139
-     *
140
-     * @return array
141
-     * @throws ApplicationLogicException
142
-     */
143
-    public function fetchColumn($column, $distinct = false)
144
-    {
145
-        if ($distinct) {
146
-            if ($this->groupByClause !== '') {
147
-                throw new ApplicationLogicException('Cannot apply distinct to column fetch already using group by');
148
-            }
149
-
150
-            $this->groupByClause = ' GROUP BY origin.' . $column;
151
-        }
152
-
153
-        $statement = $this->getData(array($column));
154
-
155
-        return $statement->fetchAll(PDO::FETCH_COLUMN);
156
-    }
157
-
158
-    public function fetchMap($column)
159
-    {
160
-        $statement = $this->getData(array('id', $column));
161
-
162
-        $data = $statement->fetchAll(PDO::FETCH_ASSOC);
163
-        $map = array();
164
-
165
-        foreach ($data as $row) {
166
-            $map[$row['id']] = $row[$column];
167
-        }
168
-
169
-        return $map;
170
-    }
171
-
172
-    /**
173
-     * @param int $count Returns the record count of the result set
174
-     *
175
-     * @return $this
176
-     */
177
-    public function getRecordCount(&$count)
178
-    {
179
-        $query = 'SELECT /* SearchHelper */ COUNT(*) FROM ' . $this->table . ' origin ';
180
-        $query .= $this->joinClause . $this->whereClause;
181
-
182
-        $statement = $this->database->prepare($query);
183
-        $statement->execute($this->parameterList);
184
-
185
-        $count = $statement->fetchColumn(0);
186
-        $statement->closeCursor();
187
-
188
-        return $this;
189
-    }
190
-
191
-    /**
192
-     * Limits the results
193
-     *
194
-     * @param integer      $limit
195
-     * @param integer|null $offset
196
-     *
197
-     * @return $this
198
-     *
199
-     */
200
-    public function limit($limit, $offset = null)
201
-    {
202
-        $this->limit = $limit;
203
-        $this->offset = $offset;
204
-
205
-        return $this;
206
-    }
207
-
208
-    private function applyLimit()
209
-    {
210
-        $clause = '';
211
-        if ($this->limit !== null) {
212
-            $clause = ' LIMIT ?';
213
-            $this->parameterList[] = $this->limit;
214
-
215
-            if ($this->offset !== null) {
216
-                $clause .= ' OFFSET ?';
217
-                $this->parameterList[] = $this->offset;
218
-            }
219
-        }
220
-
221
-        return $clause;
222
-    }
223
-
224
-    private function applyOrder()
225
-    {
226
-        if ($this->orderBy !== null) {
227
-            return ' ORDER BY ' . $this->orderBy;
228
-        }
229
-
230
-        return '';
231
-    }
232
-
233
-    /**
234
-     * @param array $columns
235
-     *
236
-     * @return PDOStatement
237
-     */
238
-    private function getData($columns = array('*'))
239
-    {
240
-        $query = $this->buildQuery($columns);
241
-        $query .= $this->applyOrder();
242
-        $query .= $this->applyLimit();
243
-
244
-        /** @var PDOStatement $statement */
245
-        $statement = $this->database->prepare($query);
246
-        $statement->execute($this->parameterList);
247
-
248
-        return $statement;
249
-    }
250
-
251
-    /**
252
-     * @param array $columns
253
-     *
254
-     * @return string
255
-     */
256
-    protected function buildQuery($columns)
257
-    {
258
-        $colData = array();
259
-        foreach ($columns as $c) {
260
-            $colData[] = 'origin.' . $c;
261
-        }
262
-
263
-        $query = "SELECT {$this->modifiersClause} /* SearchHelper */ " . implode(', ', $colData) . ' FROM ' . $this->table . ' origin ';
264
-        $query .= $this->joinClause . $this->whereClause . $this->groupByClause;
265
-
266
-        return $query;
267
-    }
268
-
269
-    public function inIds($idList)
270
-    {
271
-        $this->inClause('id', $idList);
272
-
273
-        return $this;
274
-    }
275
-
276
-    protected function inClause($column, $values)
277
-    {
278
-        if (count($values) === 0) {
279
-            return;
280
-        }
281
-
282
-        // You can't use IN() with parameters directly, so let's munge something together.
283
-        // Let's create a string of question marks, which will do as positional parameters.
284
-        $valueCount = count($values);
285
-        $inSection = str_repeat('?,', $valueCount - 1) . '?';
286
-
287
-        $this->whereClause .= " AND {$column} IN ({$inSection})";
288
-        $this->parameterList = array_merge($this->parameterList, $values);
289
-    }
19
+	/** @var PdoDatabase */
20
+	protected $database;
21
+	/** @var array */
22
+	protected $parameterList = array();
23
+	/** @var null|int */
24
+	private $limit = null;
25
+	/** @var null|int */
26
+	private $offset = null;
27
+	private $orderBy;
28
+	/**
29
+	 * @var string The where clause.
30
+	 *
31
+	 * (the 1=1 condition will be optimised out of the query by the query planner, and simplifies our code here). Note
32
+	 * that we use positional parameters instead of named parameters because we don't know many times different options
33
+	 * will be called (looking at excluding() here, but there's the option for others).
34
+	 */
35
+	protected $whereClause = ' WHERE 1 = 1';
36
+	/** @var string */
37
+	protected $table;
38
+	protected $joinClause = '';
39
+	protected $groupByClause = '';
40
+	protected $modifiersClause = '';
41
+	private $targetClass;
42
+
43
+	/**
44
+	 * SearchHelperBase constructor.
45
+	 *
46
+	 * @param PdoDatabase $database
47
+	 * @param string      $table
48
+	 * @param             $targetClass
49
+	 * @param null|string $order Order by clause, excluding ORDER BY.
50
+	 */
51
+	protected function __construct(PdoDatabase $database, $table, $targetClass, $order = null)
52
+	{
53
+		$this->database = $database;
54
+		$this->table = $table;
55
+		$this->orderBy = $order;
56
+		$this->targetClass = $targetClass;
57
+	}
58
+
59
+	/**
60
+	 * Finalises the database query, and executes it, returning a set of objects.
61
+	 *
62
+	 * @return DataObject[]
63
+	 */
64
+	public function fetch()
65
+	{
66
+		$statement = $this->getData();
67
+
68
+		/** @var DataObject[] $returnedObjects */
69
+		$returnedObjects = $statement->fetchAll(PDO::FETCH_CLASS, $this->targetClass);
70
+		foreach ($returnedObjects as $req) {
71
+			$req->setDatabase($this->database);
72
+		}
73
+
74
+		return $returnedObjects;
75
+	}
76
+
77
+	/**
78
+	 * @param string $whereClauseSection
79
+	 * @param array  $values
80
+	 *
81
+	 * @return array
82
+	 */
83
+	protected function fetchByParameter($whereClauseSection, $values)
84
+	{
85
+		$this->whereClause .= $whereClauseSection;
86
+
87
+		$countQuery = 'SELECT /* SearchHelper */ COUNT(*) FROM ' . $this->table . ' origin ';
88
+		$countQuery .= $this->joinClause . $this->whereClause;
89
+
90
+		$query = $this->buildQuery(array('*'));
91
+		$query .= $this->applyOrder();
92
+
93
+		// shuffle around parameters
94
+		// applyLimit() appends parameters to the parameter list, which is useless when we want to run
95
+		// many queries with different parameters. As such, we back up the parameter list, wipe it, apply the limit
96
+		// parameters, and hold them separately, merging again prior to running the actual query.
97
+		$localParameterList = $this->parameterList;
98
+		$this->parameterList = array();
99
+		$query .= $this->applyLimit();
100
+		$limitParameters = $this->parameterList;
101
+
102
+		$statement = $this->database->prepare($query);
103
+		$countStatement = $this->database->prepare($countQuery);
104
+
105
+		$result = array();
106
+		foreach ($values as $v) {
107
+			// reset parameter list
108
+			$params = $localParameterList;
109
+			$params[] = $v;
110
+
111
+			$countStatement->execute($params);
112
+
113
+			// reapply the limit parameters
114
+			$params = array_merge($params, $limitParameters);
115
+
116
+			$statement->execute($params);
117
+
118
+			/** @var DataObject[] $returnedObjects */
119
+			$returnedObjects = $statement->fetchAll(PDO::FETCH_CLASS, $this->targetClass);
120
+			foreach ($returnedObjects as $req) {
121
+				$req->setDatabase($this->database);
122
+			}
123
+
124
+			$result[$v] = array(
125
+				'count' => $countStatement->fetchColumn(0),
126
+				'data'  => $returnedObjects,
127
+			);
128
+		}
129
+
130
+		return $result;
131
+	}
132
+
133
+	/**
134
+	 * Finalises the database query, and executes it, returning only the requested column.
135
+	 *
136
+	 * @param string $column The required column
137
+	 *
138
+	 * @param bool   $distinct
139
+	 *
140
+	 * @return array
141
+	 * @throws ApplicationLogicException
142
+	 */
143
+	public function fetchColumn($column, $distinct = false)
144
+	{
145
+		if ($distinct) {
146
+			if ($this->groupByClause !== '') {
147
+				throw new ApplicationLogicException('Cannot apply distinct to column fetch already using group by');
148
+			}
149
+
150
+			$this->groupByClause = ' GROUP BY origin.' . $column;
151
+		}
152
+
153
+		$statement = $this->getData(array($column));
154
+
155
+		return $statement->fetchAll(PDO::FETCH_COLUMN);
156
+	}
157
+
158
+	public function fetchMap($column)
159
+	{
160
+		$statement = $this->getData(array('id', $column));
161
+
162
+		$data = $statement->fetchAll(PDO::FETCH_ASSOC);
163
+		$map = array();
164
+
165
+		foreach ($data as $row) {
166
+			$map[$row['id']] = $row[$column];
167
+		}
168
+
169
+		return $map;
170
+	}
171
+
172
+	/**
173
+	 * @param int $count Returns the record count of the result set
174
+	 *
175
+	 * @return $this
176
+	 */
177
+	public function getRecordCount(&$count)
178
+	{
179
+		$query = 'SELECT /* SearchHelper */ COUNT(*) FROM ' . $this->table . ' origin ';
180
+		$query .= $this->joinClause . $this->whereClause;
181
+
182
+		$statement = $this->database->prepare($query);
183
+		$statement->execute($this->parameterList);
184
+
185
+		$count = $statement->fetchColumn(0);
186
+		$statement->closeCursor();
187
+
188
+		return $this;
189
+	}
190
+
191
+	/**
192
+	 * Limits the results
193
+	 *
194
+	 * @param integer      $limit
195
+	 * @param integer|null $offset
196
+	 *
197
+	 * @return $this
198
+	 *
199
+	 */
200
+	public function limit($limit, $offset = null)
201
+	{
202
+		$this->limit = $limit;
203
+		$this->offset = $offset;
204
+
205
+		return $this;
206
+	}
207
+
208
+	private function applyLimit()
209
+	{
210
+		$clause = '';
211
+		if ($this->limit !== null) {
212
+			$clause = ' LIMIT ?';
213
+			$this->parameterList[] = $this->limit;
214
+
215
+			if ($this->offset !== null) {
216
+				$clause .= ' OFFSET ?';
217
+				$this->parameterList[] = $this->offset;
218
+			}
219
+		}
220
+
221
+		return $clause;
222
+	}
223
+
224
+	private function applyOrder()
225
+	{
226
+		if ($this->orderBy !== null) {
227
+			return ' ORDER BY ' . $this->orderBy;
228
+		}
229
+
230
+		return '';
231
+	}
232
+
233
+	/**
234
+	 * @param array $columns
235
+	 *
236
+	 * @return PDOStatement
237
+	 */
238
+	private function getData($columns = array('*'))
239
+	{
240
+		$query = $this->buildQuery($columns);
241
+		$query .= $this->applyOrder();
242
+		$query .= $this->applyLimit();
243
+
244
+		/** @var PDOStatement $statement */
245
+		$statement = $this->database->prepare($query);
246
+		$statement->execute($this->parameterList);
247
+
248
+		return $statement;
249
+	}
250
+
251
+	/**
252
+	 * @param array $columns
253
+	 *
254
+	 * @return string
255
+	 */
256
+	protected function buildQuery($columns)
257
+	{
258
+		$colData = array();
259
+		foreach ($columns as $c) {
260
+			$colData[] = 'origin.' . $c;
261
+		}
262
+
263
+		$query = "SELECT {$this->modifiersClause} /* SearchHelper */ " . implode(', ', $colData) . ' FROM ' . $this->table . ' origin ';
264
+		$query .= $this->joinClause . $this->whereClause . $this->groupByClause;
265
+
266
+		return $query;
267
+	}
268
+
269
+	public function inIds($idList)
270
+	{
271
+		$this->inClause('id', $idList);
272
+
273
+		return $this;
274
+	}
275
+
276
+	protected function inClause($column, $values)
277
+	{
278
+		if (count($values) === 0) {
279
+			return;
280
+		}
281
+
282
+		// You can't use IN() with parameters directly, so let's munge something together.
283
+		// Let's create a string of question marks, which will do as positional parameters.
284
+		$valueCount = count($values);
285
+		$inSection = str_repeat('?,', $valueCount - 1) . '?';
286
+
287
+		$this->whereClause .= " AND {$column} IN ({$inSection})";
288
+		$this->parameterList = array_merge($this->parameterList, $values);
289
+	}
290 290
 }
Please login to merge, or discard this patch.
includes/Helpers/SearchHelpers/RequestSearchHelper.php 2 patches
Indentation   +174 added lines, -174 removed lines patch added patch discarded remove patch
@@ -15,178 +15,178 @@
 block discarded – undo
15 15
 
16 16
 class RequestSearchHelper extends SearchHelperBase
17 17
 {
18
-    /**
19
-     * RequestSearchHelper constructor.
20
-     *
21
-     * @param PdoDatabase $database
22
-     */
23
-    protected function __construct(PdoDatabase $database)
24
-    {
25
-        parent::__construct($database, 'request', Request::class);
26
-    }
27
-
28
-    /**
29
-     * Initiates a search for requests
30
-     *
31
-     * @param PdoDatabase $database
32
-     *
33
-     * @return RequestSearchHelper
34
-     */
35
-    public static function get(PdoDatabase $database)
36
-    {
37
-        $helper = new RequestSearchHelper($database);
38
-
39
-        return $helper;
40
-    }
41
-
42
-    /**
43
-     * Filters the results by IP address
44
-     *
45
-     * @param string $ipAddress
46
-     *
47
-     * @return $this
48
-     */
49
-    public function byIp($ipAddress)
50
-    {
51
-        $this->whereClause .= ' AND (ip LIKE ? OR forwardedip LIKE ?)';
52
-        $this->parameterList[] = $ipAddress;
53
-        $this->parameterList[] = '%' . trim($ipAddress, '%') . '%';
54
-
55
-        return $this;
56
-    }
57
-
58
-    /**
59
-     * Filters the results by email address
60
-     *
61
-     * @param string $emailAddress
62
-     *
63
-     * @return $this
64
-     */
65
-    public function byEmailAddress($emailAddress)
66
-    {
67
-        $this->whereClause .= ' AND email LIKE ?';
68
-        $this->parameterList[] = $emailAddress;
69
-
70
-        return $this;
71
-    }
72
-
73
-    /**
74
-     * Filters the results by name
75
-     *
76
-     * @param string $name
77
-     *
78
-     * @return $this
79
-     */
80
-    public function byName($name)
81
-    {
82
-        $this->whereClause .= ' AND name LIKE ?';
83
-        $this->parameterList[] = $name;
84
-
85
-        return $this;
86
-    }
87
-
88
-    /**
89
-     * Filters the requests to those with a defined status
90
-     *
91
-     * @param $status
92
-     *
93
-     * @return $this
94
-     */
95
-    public function byStatus($status)
96
-    {
97
-        $this->whereClause .= ' AND status = ?';
98
-        $this->parameterList[] = $status;
99
-
100
-        return $this;
101
-    }
102
-
103
-    /**
104
-     * Excludes a request from the results
105
-     *
106
-     * @param int $requestId
107
-     *
108
-     * @return $this
109
-     */
110
-    public function excludingRequest($requestId)
111
-    {
112
-        $this->whereClause .= ' AND id <> ?';
113
-        $this->parameterList[] = $requestId;
114
-
115
-        return $this;
116
-    }
117
-
118
-    /**
119
-     * Filters the results to only those with a confirmed email address
120
-     *
121
-     * @return $this
122
-     */
123
-    public function withConfirmedEmail()
124
-    {
125
-        $this->whereClause .= ' AND emailconfirm = ?';
126
-        $this->parameterList[] = 'Confirmed';
127
-
128
-        return $this;
129
-    }
130
-
131
-    /**
132
-     * Filters the results to exclude purged data
133
-     *
134
-     * @param SiteConfiguration $configuration
135
-     *
136
-     * @return $this
137
-     */
138
-    public function excludingPurgedData(SiteConfiguration $configuration)
139
-    {
140
-        $this->whereClause .= ' AND ip <> ? AND email <> ?';
141
-        $this->parameterList[] = $configuration->getDataClearIp();
142
-        $this->parameterList[] = $configuration->getDataClearEmail();
143
-
144
-        return $this;
145
-    }
146
-
147
-    /**
148
-     * Filters the requests to those without a defined status
149
-     *
150
-     * @param $status
151
-     *
152
-     * @return $this
153
-     */
154
-    public function excludingStatus($status)
155
-    {
156
-        $this->whereClause .= ' AND status <> ?';
157
-        $this->parameterList[] = $status;
158
-
159
-        return $this;
160
-    }
161
-
162
-    /**
163
-     * Filters the requests to those which have failed an auto-creation
164
-     *
165
-     * @return $this
166
-     */
167
-    public function isHospitalised()
168
-    {
169
-        $this->whereClause .= ' AND status = ?';
170
-        $this->parameterList[] =  RequestStatus::HOSPITAL;
171
-
172
-        return $this;
173
-    }
174
-
175
-    /**
176
-     * Filters the requests to those which have not failed an auto-creation
177
-     *
178
-     * @return $this
179
-     */
180
-    public function notHospitalised()
181
-    {
182
-        $this->whereClause .= ' AND status <> ?';
183
-        $this->parameterList[] =  RequestStatus::HOSPITAL;
184
-
185
-        return $this;
186
-    }
187
-
188
-    public function fetchByStatus($statuses)
189
-    {
190
-        return $this->fetchByParameter(' AND status = ?', $statuses);
191
-    }
18
+	/**
19
+	 * RequestSearchHelper constructor.
20
+	 *
21
+	 * @param PdoDatabase $database
22
+	 */
23
+	protected function __construct(PdoDatabase $database)
24
+	{
25
+		parent::__construct($database, 'request', Request::class);
26
+	}
27
+
28
+	/**
29
+	 * Initiates a search for requests
30
+	 *
31
+	 * @param PdoDatabase $database
32
+	 *
33
+	 * @return RequestSearchHelper
34
+	 */
35
+	public static function get(PdoDatabase $database)
36
+	{
37
+		$helper = new RequestSearchHelper($database);
38
+
39
+		return $helper;
40
+	}
41
+
42
+	/**
43
+	 * Filters the results by IP address
44
+	 *
45
+	 * @param string $ipAddress
46
+	 *
47
+	 * @return $this
48
+	 */
49
+	public function byIp($ipAddress)
50
+	{
51
+		$this->whereClause .= ' AND (ip LIKE ? OR forwardedip LIKE ?)';
52
+		$this->parameterList[] = $ipAddress;
53
+		$this->parameterList[] = '%' . trim($ipAddress, '%') . '%';
54
+
55
+		return $this;
56
+	}
57
+
58
+	/**
59
+	 * Filters the results by email address
60
+	 *
61
+	 * @param string $emailAddress
62
+	 *
63
+	 * @return $this
64
+	 */
65
+	public function byEmailAddress($emailAddress)
66
+	{
67
+		$this->whereClause .= ' AND email LIKE ?';
68
+		$this->parameterList[] = $emailAddress;
69
+
70
+		return $this;
71
+	}
72
+
73
+	/**
74
+	 * Filters the results by name
75
+	 *
76
+	 * @param string $name
77
+	 *
78
+	 * @return $this
79
+	 */
80
+	public function byName($name)
81
+	{
82
+		$this->whereClause .= ' AND name LIKE ?';
83
+		$this->parameterList[] = $name;
84
+
85
+		return $this;
86
+	}
87
+
88
+	/**
89
+	 * Filters the requests to those with a defined status
90
+	 *
91
+	 * @param $status
92
+	 *
93
+	 * @return $this
94
+	 */
95
+	public function byStatus($status)
96
+	{
97
+		$this->whereClause .= ' AND status = ?';
98
+		$this->parameterList[] = $status;
99
+
100
+		return $this;
101
+	}
102
+
103
+	/**
104
+	 * Excludes a request from the results
105
+	 *
106
+	 * @param int $requestId
107
+	 *
108
+	 * @return $this
109
+	 */
110
+	public function excludingRequest($requestId)
111
+	{
112
+		$this->whereClause .= ' AND id <> ?';
113
+		$this->parameterList[] = $requestId;
114
+
115
+		return $this;
116
+	}
117
+
118
+	/**
119
+	 * Filters the results to only those with a confirmed email address
120
+	 *
121
+	 * @return $this
122
+	 */
123
+	public function withConfirmedEmail()
124
+	{
125
+		$this->whereClause .= ' AND emailconfirm = ?';
126
+		$this->parameterList[] = 'Confirmed';
127
+
128
+		return $this;
129
+	}
130
+
131
+	/**
132
+	 * Filters the results to exclude purged data
133
+	 *
134
+	 * @param SiteConfiguration $configuration
135
+	 *
136
+	 * @return $this
137
+	 */
138
+	public function excludingPurgedData(SiteConfiguration $configuration)
139
+	{
140
+		$this->whereClause .= ' AND ip <> ? AND email <> ?';
141
+		$this->parameterList[] = $configuration->getDataClearIp();
142
+		$this->parameterList[] = $configuration->getDataClearEmail();
143
+
144
+		return $this;
145
+	}
146
+
147
+	/**
148
+	 * Filters the requests to those without a defined status
149
+	 *
150
+	 * @param $status
151
+	 *
152
+	 * @return $this
153
+	 */
154
+	public function excludingStatus($status)
155
+	{
156
+		$this->whereClause .= ' AND status <> ?';
157
+		$this->parameterList[] = $status;
158
+
159
+		return $this;
160
+	}
161
+
162
+	/**
163
+	 * Filters the requests to those which have failed an auto-creation
164
+	 *
165
+	 * @return $this
166
+	 */
167
+	public function isHospitalised()
168
+	{
169
+		$this->whereClause .= ' AND status = ?';
170
+		$this->parameterList[] =  RequestStatus::HOSPITAL;
171
+
172
+		return $this;
173
+	}
174
+
175
+	/**
176
+	 * Filters the requests to those which have not failed an auto-creation
177
+	 *
178
+	 * @return $this
179
+	 */
180
+	public function notHospitalised()
181
+	{
182
+		$this->whereClause .= ' AND status <> ?';
183
+		$this->parameterList[] =  RequestStatus::HOSPITAL;
184
+
185
+		return $this;
186
+	}
187
+
188
+	public function fetchByStatus($statuses)
189
+	{
190
+		return $this->fetchByParameter(' AND status = ?', $statuses);
191
+	}
192 192
 }
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -167,7 +167,7 @@  discard block
 block discarded – undo
167 167
     public function isHospitalised()
168 168
     {
169 169
         $this->whereClause .= ' AND status = ?';
170
-        $this->parameterList[] =  RequestStatus::HOSPITAL;
170
+        $this->parameterList[] = RequestStatus::HOSPITAL;
171 171
 
172 172
         return $this;
173 173
     }
@@ -180,7 +180,7 @@  discard block
 block discarded – undo
180 180
     public function notHospitalised()
181 181
     {
182 182
         $this->whereClause .= ' AND status <> ?';
183
-        $this->parameterList[] =  RequestStatus::HOSPITAL;
183
+        $this->parameterList[] = RequestStatus::HOSPITAL;
184 184
 
185 185
         return $this;
186 186
     }
Please login to merge, or discard this patch.
includes/Helpers/Interfaces/IMediaWikiClient.php 1 patch
Indentation   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -10,5 +10,5 @@
 block discarded – undo
10 10
 
11 11
 interface IMediaWikiClient
12 12
 {
13
-    function doApiCall($params, $method);
13
+	function doApiCall($params, $method);
14 14
 }
15 15
\ No newline at end of file
Please login to merge, or discard this patch.
includes/Helpers/Interfaces/IOAuthProtocolHelper.php 1 patch
Indentation   +44 added lines, -44 removed lines patch added patch discarded remove patch
@@ -15,52 +15,52 @@
 block discarded – undo
15 15
 
16 16
 interface IOAuthProtocolHelper
17 17
 {
18
-    /**
19
-     * @return stdClass
20
-     *
21
-     * @throws Exception
22
-     * @throws CurlException
23
-     */
24
-    public function getRequestToken();
18
+	/**
19
+	 * @return stdClass
20
+	 *
21
+	 * @throws Exception
22
+	 * @throws CurlException
23
+	 */
24
+	public function getRequestToken();
25 25
 
26
-    /**
27
-     * @param string $requestToken
28
-     *
29
-     * @return string
30
-     */
31
-    public function getAuthoriseUrl($requestToken);
26
+	/**
27
+	 * @param string $requestToken
28
+	 *
29
+	 * @return string
30
+	 */
31
+	public function getAuthoriseUrl($requestToken);
32 32
 
33
-    /**
34
-     * @param string $oauthRequestToken
35
-     * @param string $oauthRequestSecret
36
-     * @param string $oauthVerifier
37
-     *
38
-     * @return stdClass
39
-     * @throws CurlException
40
-     * @throws Exception
41
-     */
42
-    public function callbackCompleted($oauthRequestToken, $oauthRequestSecret, $oauthVerifier);
33
+	/**
34
+	 * @param string $oauthRequestToken
35
+	 * @param string $oauthRequestSecret
36
+	 * @param string $oauthVerifier
37
+	 *
38
+	 * @return stdClass
39
+	 * @throws CurlException
40
+	 * @throws Exception
41
+	 */
42
+	public function callbackCompleted($oauthRequestToken, $oauthRequestSecret, $oauthVerifier);
43 43
 
44
-    /**
45
-     * @param string $oauthAccessToken
46
-     * @param string $oauthAccessSecret
47
-     *
48
-     * @return stdClass
49
-     * @throws CurlException
50
-     * @throws Exception
51
-     */
52
-    public function getIdentityTicket($oauthAccessToken, $oauthAccessSecret);
44
+	/**
45
+	 * @param string $oauthAccessToken
46
+	 * @param string $oauthAccessSecret
47
+	 *
48
+	 * @return stdClass
49
+	 * @throws CurlException
50
+	 * @throws Exception
51
+	 */
52
+	public function getIdentityTicket($oauthAccessToken, $oauthAccessSecret);
53 53
 
54
-    /**
55
-     * @param array  $apiParams    array of parameters to send to the API
56
-     * @param string $accessToken  user's access token
57
-     * @param string $accessSecret user's secret
58
-     * @param string $method       HTTP method
59
-     *
60
-     * @return stdClass
61
-     * @throws ApplicationLogicException
62
-     * @throws CurlException
63
-     * @throws Exception
64
-     */
65
-    public function apiCall($apiParams, $accessToken, $accessSecret, $method = 'GET');
54
+	/**
55
+	 * @param array  $apiParams    array of parameters to send to the API
56
+	 * @param string $accessToken  user's access token
57
+	 * @param string $accessSecret user's secret
58
+	 * @param string $method       HTTP method
59
+	 *
60
+	 * @return stdClass
61
+	 * @throws ApplicationLogicException
62
+	 * @throws CurlException
63
+	 * @throws Exception
64
+	 */
65
+	public function apiCall($apiParams, $accessToken, $accessSecret, $method = 'GET');
66 66
 }
67 67
\ No newline at end of file
Please login to merge, or discard this patch.
includes/Helpers/Logger.php 1 patch
Indentation   +353 added lines, -353 removed lines patch added patch discarded remove patch
@@ -31,357 +31,357 @@
 block discarded – undo
31 31
  */
32 32
 class Logger
33 33
 {
34
-    /**
35
-     * @param PdoDatabase $database
36
-     * @param Request     $object
37
-     */
38
-    public static function emailConfirmed(PdoDatabase $database, Request $object)
39
-    {
40
-        self::createLogEntry($database, $object, "Email Confirmed", null, User::getCommunity());
41
-    }
42
-
43
-    /**
44
-     * @param PdoDatabase $database
45
-     * @param DataObject  $object
46
-     * @param string      $logAction
47
-     * @param null|string $comment
48
-     * @param User        $user
49
-     *
50
-     * @throws Exception
51
-     */
52
-    private static function createLogEntry(
53
-        PdoDatabase $database,
54
-        DataObject $object,
55
-        $logAction,
56
-        $comment = null,
57
-        $user = null
58
-    ) {
59
-        if ($user == null) {
60
-            $user = User::getCurrent($database);
61
-        }
62
-
63
-        $objectType = get_class($object);
64
-        if (strpos($objectType, 'Waca\\DataObjects\\') !== false) {
65
-            $objectType = str_replace('Waca\\DataObjects\\', '', $objectType);
66
-        }
67
-
68
-        $log = new Log();
69
-        $log->setDatabase($database);
70
-        $log->setAction($logAction);
71
-        $log->setObjectId($object->getId());
72
-        $log->setObjectType($objectType);
73
-        $log->setUser($user);
74
-        $log->setComment($comment);
75
-        $log->save();
76
-    }
77
-
78
-    #region Users
79
-
80
-    /**
81
-     * @param PdoDatabase $database
82
-     * @param User        $user
83
-     */
84
-    public static function newUser(PdoDatabase $database, User $user)
85
-    {
86
-        self::createLogEntry($database, $user, 'Registered', null, User::getCommunity());
87
-    }
88
-
89
-    /**
90
-     * @param PdoDatabase $database
91
-     * @param User        $object
92
-     */
93
-    public static function approvedUser(PdoDatabase $database, User $object)
94
-    {
95
-        self::createLogEntry($database, $object, "Approved");
96
-    }
97
-
98
-    /**
99
-     * @param PdoDatabase $database
100
-     * @param User        $object
101
-     * @param string      $comment
102
-     */
103
-    public static function declinedUser(PdoDatabase $database, User $object, $comment)
104
-    {
105
-        self::createLogEntry($database, $object, "Declined", $comment);
106
-    }
107
-
108
-    /**
109
-     * @param PdoDatabase $database
110
-     * @param User        $object
111
-     * @param string      $comment
112
-     */
113
-    public static function suspendedUser(PdoDatabase $database, User $object, $comment)
114
-    {
115
-        self::createLogEntry($database, $object, "Suspended", $comment);
116
-    }
117
-
118
-    /**
119
-     * @param PdoDatabase $database
120
-     * @param User        $object
121
-     * @param string      $comment
122
-     */
123
-    public static function demotedUser(PdoDatabase $database, User $object, $comment)
124
-    {
125
-        self::createLogEntry($database, $object, "Demoted", $comment);
126
-    }
127
-
128
-    /**
129
-     * @param PdoDatabase $database
130
-     * @param User        $object
131
-     */
132
-    public static function promotedUser(PdoDatabase $database, User $object)
133
-    {
134
-        self::createLogEntry($database, $object, "Promoted");
135
-    }
136
-
137
-    /**
138
-     * @param PdoDatabase $database
139
-     * @param User        $object
140
-     * @param string      $comment
141
-     */
142
-    public static function renamedUser(PdoDatabase $database, User $object, $comment)
143
-    {
144
-        self::createLogEntry($database, $object, "Renamed", $comment);
145
-    }
146
-
147
-    /**
148
-     * @param PdoDatabase $database
149
-     * @param User        $object
150
-     */
151
-    public static function userPreferencesChange(PdoDatabase $database, User $object)
152
-    {
153
-        self::createLogEntry($database, $object, "Prefchange");
154
-    }
155
-
156
-    /**
157
-     * @param PdoDatabase $database
158
-     * @param User        $object
159
-     * @param string      $reason
160
-     * @param array       $added
161
-     * @param array       $removed
162
-     */
163
-    public static function userRolesEdited(PdoDatabase $database, User $object, $reason, $added, $removed)
164
-    {
165
-        $logData = serialize(array(
166
-            'added'   => $added,
167
-            'removed' => $removed,
168
-            'reason'  => $reason,
169
-        ));
170
-
171
-        self::createLogEntry($database, $object, "RoleChange", $logData);
172
-    }
173
-
174
-    #endregion
175
-
176
-    /**
177
-     * @param PdoDatabase $database
178
-     * @param SiteNotice  $object
179
-     */
180
-    public static function siteNoticeEdited(PdoDatabase $database, SiteNotice $object)
181
-    {
182
-        self::createLogEntry($database, $object, "Edited");
183
-    }
184
-
185
-    #region Welcome Templates
186
-
187
-    /**
188
-     * @param PdoDatabase     $database
189
-     * @param WelcomeTemplate $object
190
-     */
191
-    public static function welcomeTemplateCreated(PdoDatabase $database, WelcomeTemplate $object)
192
-    {
193
-        self::createLogEntry($database, $object, "CreatedTemplate");
194
-    }
195
-
196
-    /**
197
-     * @param PdoDatabase     $database
198
-     * @param WelcomeTemplate $object
199
-     */
200
-    public static function welcomeTemplateEdited(PdoDatabase $database, WelcomeTemplate $object)
201
-    {
202
-        self::createLogEntry($database, $object, "EditedTemplate");
203
-    }
204
-
205
-    /**
206
-     * @param PdoDatabase     $database
207
-     * @param WelcomeTemplate $object
208
-     */
209
-    public static function welcomeTemplateDeleted(PdoDatabase $database, WelcomeTemplate $object)
210
-    {
211
-        self::createLogEntry($database, $object, "DeletedTemplate");
212
-    }
213
-
214
-    #endregion
215
-
216
-    #region Bans
217
-
218
-    /**
219
-     * @param PdoDatabase $database
220
-     * @param Ban         $object
221
-     * @param string      $reason
222
-     */
223
-    public static function banned(PdoDatabase $database, Ban $object, $reason)
224
-    {
225
-        self::createLogEntry($database, $object, "Banned", $reason);
226
-    }
227
-
228
-    /**
229
-     * @param PdoDatabase $database
230
-     * @param Ban         $object
231
-     * @param string      $reason
232
-     */
233
-    public static function unbanned(PdoDatabase $database, Ban $object, $reason)
234
-    {
235
-        self::createLogEntry($database, $object, "Unbanned", $reason);
236
-    }
237
-
238
-    #endregion
239
-
240
-    #region Requests
241
-
242
-    /**
243
-     * @param PdoDatabase $database
244
-     * @param Request     $object
245
-     * @param string      $target
246
-     */
247
-    public static function deferRequest(PdoDatabase $database, Request $object, $target)
248
-    {
249
-        self::createLogEntry($database, $object, "Deferred to $target");
250
-    }
251
-
252
-    /**
253
-     * @param PdoDatabase $database
254
-     * @param Request     $object
255
-     * @param integer     $target
256
-     * @param string      $comment
257
-     * @param User|null   $logUser
258
-     */
259
-    public static function closeRequest(PdoDatabase $database, Request $object, $target, $comment, User $logUser = null)
260
-    {
261
-        self::createLogEntry($database, $object, "Closed $target", $comment, $logUser);
262
-    }
263
-
264
-    /**
265
-     * @param PdoDatabase $database
266
-     * @param Request     $object
267
-     */
268
-    public static function reserve(PdoDatabase $database, Request $object)
269
-    {
270
-        self::createLogEntry($database, $object, "Reserved");
271
-    }
272
-
273
-    /**
274
-     * @param PdoDatabase $database
275
-     * @param Request     $object
276
-     */
277
-    public static function breakReserve(PdoDatabase $database, Request $object)
278
-    {
279
-        self::createLogEntry($database, $object, "BreakReserve");
280
-    }
281
-
282
-    /**
283
-     * @param PdoDatabase $database
284
-     * @param Request     $object
285
-     */
286
-    public static function unreserve(PdoDatabase $database, Request $object)
287
-    {
288
-        self::createLogEntry($database, $object, "Unreserved");
289
-    }
290
-
291
-    /**
292
-     * @param PdoDatabase $database
293
-     * @param Comment     $object
294
-     * @param Request     $request
295
-     */
296
-    public static function editComment(PdoDatabase $database, Comment $object, Request $request)
297
-    {
298
-        self::createLogEntry($database, $request, "EditComment-r");
299
-        self::createLogEntry($database, $object, "EditComment-c");
300
-    }
301
-
302
-    /**
303
-     * @param PdoDatabase $database
304
-     * @param Request     $object
305
-     * @param User        $target
306
-     */
307
-    public static function sendReservation(PdoDatabase $database, Request $object, User $target)
308
-    {
309
-        self::createLogEntry($database, $object, "SendReserved");
310
-        self::createLogEntry($database, $object, "ReceiveReserved", null, $target);
311
-    }
312
-
313
-    /**
314
-     * @param PdoDatabase $database
315
-     * @param Request     $object
316
-     * @param string      $comment
317
-     */
318
-    public static function sentMail(PdoDatabase $database, Request $object, $comment)
319
-    {
320
-        self::createLogEntry($database, $object, "SentMail", $comment);
321
-    }
322
-
323
-    /**
324
-     * @param PdoDatabase $database
325
-     * @param Request     $object
326
-     */
327
-    public static function enqueuedJobQueue(PdoDatabase $database, Request $object)
328
-    {
329
-        self::createLogEntry($database, $object, 'EnqueuedJobQueue');
330
-    }
331
-
332
-    public static function hospitalised(PdoDatabase $database, Request $object)
333
-    {
334
-        self::createLogEntry($database, $object, 'Hospitalised');
335
-    }
336
-    #endregion
337
-
338
-    #region Email templates
339
-
340
-    /**
341
-     * @param PdoDatabase   $database
342
-     * @param EmailTemplate $object
343
-     */
344
-    public static function createEmail(PdoDatabase $database, EmailTemplate $object)
345
-    {
346
-        self::createLogEntry($database, $object, "CreatedEmail");
347
-    }
348
-
349
-    /**
350
-     * @param PdoDatabase   $database
351
-     * @param EmailTemplate $object
352
-     */
353
-    public static function editedEmail(PdoDatabase $database, EmailTemplate $object)
354
-    {
355
-        self::createLogEntry($database, $object, "EditedEmail");
356
-    }
357
-
358
-    #endregion
359
-
360
-    #region Display
361
-
362
-    #endregion
363
-
364
-    #region Automation
365
-
366
-    public static function backgroundJobComplete(PdoDatabase $database, JobQueue $job)
367
-    {
368
-        self::createLogEntry($database, $job, 'JobCompleted', null, User::getCommunity());
369
-    }
370
-
371
-    public static function backgroundJobIssue(PdoDatabase $database, JobQueue $job)
372
-    {
373
-        $data = array('status' => $job->getStatus(), 'error' => $job->getError());
374
-        self::createLogEntry($database, $job, 'JobIssue', serialize($data), User::getCommunity());
375
-    }
376
-
377
-    public static function backgroundJobRequeued(PdoDatabase $database, JobQueue $job)
378
-    {
379
-        self::createLogEntry($database, $job, 'JobRequeued');
380
-    }
381
-
382
-    public static function backgroundJobAcknowledged(PdoDatabase $database, JobQueue $job)
383
-    {
384
-        self::createLogEntry($database, $job, 'JobAcknowledged');
385
-    }
386
-    #endregion
34
+	/**
35
+	 * @param PdoDatabase $database
36
+	 * @param Request     $object
37
+	 */
38
+	public static function emailConfirmed(PdoDatabase $database, Request $object)
39
+	{
40
+		self::createLogEntry($database, $object, "Email Confirmed", null, User::getCommunity());
41
+	}
42
+
43
+	/**
44
+	 * @param PdoDatabase $database
45
+	 * @param DataObject  $object
46
+	 * @param string      $logAction
47
+	 * @param null|string $comment
48
+	 * @param User        $user
49
+	 *
50
+	 * @throws Exception
51
+	 */
52
+	private static function createLogEntry(
53
+		PdoDatabase $database,
54
+		DataObject $object,
55
+		$logAction,
56
+		$comment = null,
57
+		$user = null
58
+	) {
59
+		if ($user == null) {
60
+			$user = User::getCurrent($database);
61
+		}
62
+
63
+		$objectType = get_class($object);
64
+		if (strpos($objectType, 'Waca\\DataObjects\\') !== false) {
65
+			$objectType = str_replace('Waca\\DataObjects\\', '', $objectType);
66
+		}
67
+
68
+		$log = new Log();
69
+		$log->setDatabase($database);
70
+		$log->setAction($logAction);
71
+		$log->setObjectId($object->getId());
72
+		$log->setObjectType($objectType);
73
+		$log->setUser($user);
74
+		$log->setComment($comment);
75
+		$log->save();
76
+	}
77
+
78
+	#region Users
79
+
80
+	/**
81
+	 * @param PdoDatabase $database
82
+	 * @param User        $user
83
+	 */
84
+	public static function newUser(PdoDatabase $database, User $user)
85
+	{
86
+		self::createLogEntry($database, $user, 'Registered', null, User::getCommunity());
87
+	}
88
+
89
+	/**
90
+	 * @param PdoDatabase $database
91
+	 * @param User        $object
92
+	 */
93
+	public static function approvedUser(PdoDatabase $database, User $object)
94
+	{
95
+		self::createLogEntry($database, $object, "Approved");
96
+	}
97
+
98
+	/**
99
+	 * @param PdoDatabase $database
100
+	 * @param User        $object
101
+	 * @param string      $comment
102
+	 */
103
+	public static function declinedUser(PdoDatabase $database, User $object, $comment)
104
+	{
105
+		self::createLogEntry($database, $object, "Declined", $comment);
106
+	}
107
+
108
+	/**
109
+	 * @param PdoDatabase $database
110
+	 * @param User        $object
111
+	 * @param string      $comment
112
+	 */
113
+	public static function suspendedUser(PdoDatabase $database, User $object, $comment)
114
+	{
115
+		self::createLogEntry($database, $object, "Suspended", $comment);
116
+	}
117
+
118
+	/**
119
+	 * @param PdoDatabase $database
120
+	 * @param User        $object
121
+	 * @param string      $comment
122
+	 */
123
+	public static function demotedUser(PdoDatabase $database, User $object, $comment)
124
+	{
125
+		self::createLogEntry($database, $object, "Demoted", $comment);
126
+	}
127
+
128
+	/**
129
+	 * @param PdoDatabase $database
130
+	 * @param User        $object
131
+	 */
132
+	public static function promotedUser(PdoDatabase $database, User $object)
133
+	{
134
+		self::createLogEntry($database, $object, "Promoted");
135
+	}
136
+
137
+	/**
138
+	 * @param PdoDatabase $database
139
+	 * @param User        $object
140
+	 * @param string      $comment
141
+	 */
142
+	public static function renamedUser(PdoDatabase $database, User $object, $comment)
143
+	{
144
+		self::createLogEntry($database, $object, "Renamed", $comment);
145
+	}
146
+
147
+	/**
148
+	 * @param PdoDatabase $database
149
+	 * @param User        $object
150
+	 */
151
+	public static function userPreferencesChange(PdoDatabase $database, User $object)
152
+	{
153
+		self::createLogEntry($database, $object, "Prefchange");
154
+	}
155
+
156
+	/**
157
+	 * @param PdoDatabase $database
158
+	 * @param User        $object
159
+	 * @param string      $reason
160
+	 * @param array       $added
161
+	 * @param array       $removed
162
+	 */
163
+	public static function userRolesEdited(PdoDatabase $database, User $object, $reason, $added, $removed)
164
+	{
165
+		$logData = serialize(array(
166
+			'added'   => $added,
167
+			'removed' => $removed,
168
+			'reason'  => $reason,
169
+		));
170
+
171
+		self::createLogEntry($database, $object, "RoleChange", $logData);
172
+	}
173
+
174
+	#endregion
175
+
176
+	/**
177
+	 * @param PdoDatabase $database
178
+	 * @param SiteNotice  $object
179
+	 */
180
+	public static function siteNoticeEdited(PdoDatabase $database, SiteNotice $object)
181
+	{
182
+		self::createLogEntry($database, $object, "Edited");
183
+	}
184
+
185
+	#region Welcome Templates
186
+
187
+	/**
188
+	 * @param PdoDatabase     $database
189
+	 * @param WelcomeTemplate $object
190
+	 */
191
+	public static function welcomeTemplateCreated(PdoDatabase $database, WelcomeTemplate $object)
192
+	{
193
+		self::createLogEntry($database, $object, "CreatedTemplate");
194
+	}
195
+
196
+	/**
197
+	 * @param PdoDatabase     $database
198
+	 * @param WelcomeTemplate $object
199
+	 */
200
+	public static function welcomeTemplateEdited(PdoDatabase $database, WelcomeTemplate $object)
201
+	{
202
+		self::createLogEntry($database, $object, "EditedTemplate");
203
+	}
204
+
205
+	/**
206
+	 * @param PdoDatabase     $database
207
+	 * @param WelcomeTemplate $object
208
+	 */
209
+	public static function welcomeTemplateDeleted(PdoDatabase $database, WelcomeTemplate $object)
210
+	{
211
+		self::createLogEntry($database, $object, "DeletedTemplate");
212
+	}
213
+
214
+	#endregion
215
+
216
+	#region Bans
217
+
218
+	/**
219
+	 * @param PdoDatabase $database
220
+	 * @param Ban         $object
221
+	 * @param string      $reason
222
+	 */
223
+	public static function banned(PdoDatabase $database, Ban $object, $reason)
224
+	{
225
+		self::createLogEntry($database, $object, "Banned", $reason);
226
+	}
227
+
228
+	/**
229
+	 * @param PdoDatabase $database
230
+	 * @param Ban         $object
231
+	 * @param string      $reason
232
+	 */
233
+	public static function unbanned(PdoDatabase $database, Ban $object, $reason)
234
+	{
235
+		self::createLogEntry($database, $object, "Unbanned", $reason);
236
+	}
237
+
238
+	#endregion
239
+
240
+	#region Requests
241
+
242
+	/**
243
+	 * @param PdoDatabase $database
244
+	 * @param Request     $object
245
+	 * @param string      $target
246
+	 */
247
+	public static function deferRequest(PdoDatabase $database, Request $object, $target)
248
+	{
249
+		self::createLogEntry($database, $object, "Deferred to $target");
250
+	}
251
+
252
+	/**
253
+	 * @param PdoDatabase $database
254
+	 * @param Request     $object
255
+	 * @param integer     $target
256
+	 * @param string      $comment
257
+	 * @param User|null   $logUser
258
+	 */
259
+	public static function closeRequest(PdoDatabase $database, Request $object, $target, $comment, User $logUser = null)
260
+	{
261
+		self::createLogEntry($database, $object, "Closed $target", $comment, $logUser);
262
+	}
263
+
264
+	/**
265
+	 * @param PdoDatabase $database
266
+	 * @param Request     $object
267
+	 */
268
+	public static function reserve(PdoDatabase $database, Request $object)
269
+	{
270
+		self::createLogEntry($database, $object, "Reserved");
271
+	}
272
+
273
+	/**
274
+	 * @param PdoDatabase $database
275
+	 * @param Request     $object
276
+	 */
277
+	public static function breakReserve(PdoDatabase $database, Request $object)
278
+	{
279
+		self::createLogEntry($database, $object, "BreakReserve");
280
+	}
281
+
282
+	/**
283
+	 * @param PdoDatabase $database
284
+	 * @param Request     $object
285
+	 */
286
+	public static function unreserve(PdoDatabase $database, Request $object)
287
+	{
288
+		self::createLogEntry($database, $object, "Unreserved");
289
+	}
290
+
291
+	/**
292
+	 * @param PdoDatabase $database
293
+	 * @param Comment     $object
294
+	 * @param Request     $request
295
+	 */
296
+	public static function editComment(PdoDatabase $database, Comment $object, Request $request)
297
+	{
298
+		self::createLogEntry($database, $request, "EditComment-r");
299
+		self::createLogEntry($database, $object, "EditComment-c");
300
+	}
301
+
302
+	/**
303
+	 * @param PdoDatabase $database
304
+	 * @param Request     $object
305
+	 * @param User        $target
306
+	 */
307
+	public static function sendReservation(PdoDatabase $database, Request $object, User $target)
308
+	{
309
+		self::createLogEntry($database, $object, "SendReserved");
310
+		self::createLogEntry($database, $object, "ReceiveReserved", null, $target);
311
+	}
312
+
313
+	/**
314
+	 * @param PdoDatabase $database
315
+	 * @param Request     $object
316
+	 * @param string      $comment
317
+	 */
318
+	public static function sentMail(PdoDatabase $database, Request $object, $comment)
319
+	{
320
+		self::createLogEntry($database, $object, "SentMail", $comment);
321
+	}
322
+
323
+	/**
324
+	 * @param PdoDatabase $database
325
+	 * @param Request     $object
326
+	 */
327
+	public static function enqueuedJobQueue(PdoDatabase $database, Request $object)
328
+	{
329
+		self::createLogEntry($database, $object, 'EnqueuedJobQueue');
330
+	}
331
+
332
+	public static function hospitalised(PdoDatabase $database, Request $object)
333
+	{
334
+		self::createLogEntry($database, $object, 'Hospitalised');
335
+	}
336
+	#endregion
337
+
338
+	#region Email templates
339
+
340
+	/**
341
+	 * @param PdoDatabase   $database
342
+	 * @param EmailTemplate $object
343
+	 */
344
+	public static function createEmail(PdoDatabase $database, EmailTemplate $object)
345
+	{
346
+		self::createLogEntry($database, $object, "CreatedEmail");
347
+	}
348
+
349
+	/**
350
+	 * @param PdoDatabase   $database
351
+	 * @param EmailTemplate $object
352
+	 */
353
+	public static function editedEmail(PdoDatabase $database, EmailTemplate $object)
354
+	{
355
+		self::createLogEntry($database, $object, "EditedEmail");
356
+	}
357
+
358
+	#endregion
359
+
360
+	#region Display
361
+
362
+	#endregion
363
+
364
+	#region Automation
365
+
366
+	public static function backgroundJobComplete(PdoDatabase $database, JobQueue $job)
367
+	{
368
+		self::createLogEntry($database, $job, 'JobCompleted', null, User::getCommunity());
369
+	}
370
+
371
+	public static function backgroundJobIssue(PdoDatabase $database, JobQueue $job)
372
+	{
373
+		$data = array('status' => $job->getStatus(), 'error' => $job->getError());
374
+		self::createLogEntry($database, $job, 'JobIssue', serialize($data), User::getCommunity());
375
+	}
376
+
377
+	public static function backgroundJobRequeued(PdoDatabase $database, JobQueue $job)
378
+	{
379
+		self::createLogEntry($database, $job, 'JobRequeued');
380
+	}
381
+
382
+	public static function backgroundJobAcknowledged(PdoDatabase $database, JobQueue $job)
383
+	{
384
+		self::createLogEntry($database, $job, 'JobAcknowledged');
385
+	}
386
+	#endregion
387 387
 }
Please login to merge, or discard this patch.
includes/Helpers/LogHelper.php 3 patches
Indentation   +403 added lines, -403 removed lines patch added patch discarded remove patch
@@ -27,414 +27,414 @@
 block discarded – undo
27 27
 
28 28
 class LogHelper
29 29
 {
30
-    /**
31
-     * Summary of getRequestLogsWithComments
32
-     *
33
-     * @param int             $requestId
34
-     * @param PdoDatabase     $db
35
-     * @param SecurityManager $securityManager
36
-     *
37
-     * @return DataObject[]
38
-     */
39
-    public static function getRequestLogsWithComments($requestId, PdoDatabase $db, SecurityManager $securityManager)
40
-    {
41
-        $logs = LogSearchHelper::get($db)->byObjectType('Request')->byObjectId($requestId)->fetch();
42
-
43
-        $currentUser = User::getCurrent($db);
44
-        $securityResult = $securityManager->allows('RequestData', 'seeRestrictedComments', $currentUser);
45
-        $showAllComments = $securityResult === SecurityManager::ALLOWED;
46
-
47
-        $comments = Comment::getForRequest($requestId, $db, $showAllComments, $currentUser->getId());
48
-
49
-        $items = array_merge($logs, $comments);
50
-
51
-        /**
52
-         * @param DataObject $item
53
-         *
54
-         * @return int
55
-         */
56
-        $sortKey = function(DataObject $item) {
57
-            if ($item instanceof Log) {
58
-                return $item->getTimestamp()->getTimestamp();
59
-            }
60
-
61
-            if ($item instanceof Comment) {
62
-                return $item->getTime()->getTimestamp();
63
-            }
64
-
65
-            return 0;
66
-        };
67
-
68
-        do {
69
-            $flag = false;
70
-
71
-            $loopLimit = (count($items) - 1);
72
-            for ($i = 0; $i < $loopLimit; $i++) {
73
-                // are these two items out of order?
74
-                if ($sortKey($items[$i]) > $sortKey($items[$i + 1])) {
75
-                    // swap them
76
-                    $swap = $items[$i];
77
-                    $items[$i] = $items[$i + 1];
78
-                    $items[$i + 1] = $swap;
79
-
80
-                    // set a flag to say we've modified the array this time around
81
-                    $flag = true;
82
-                }
83
-            }
84
-        }
85
-        while ($flag);
86
-
87
-        return $items;
88
-    }
89
-
90
-    /**
91
-     * Summary of getLogDescription
92
-     *
93
-     * @param Log $entry
94
-     *
95
-     * @return string
96
-     */
97
-    public static function getLogDescription(Log $entry)
98
-    {
99
-        $text = "Deferred to ";
100
-        if (substr($entry->getAction(), 0, strlen($text)) == $text) {
101
-            // Deferred to a different queue
102
-            // This is exactly what we want to display.
103
-            return $entry->getAction();
104
-        }
105
-
106
-        $text = "Closed custom-n";
107
-        if ($entry->getAction() == $text) {
108
-            // Custom-closed
109
-            return "closed (custom reason - account not created)";
110
-        }
111
-
112
-        $text = "Closed custom-y";
113
-        if ($entry->getAction() == $text) {
114
-            // Custom-closed
115
-            return "closed (custom reason - account created)";
116
-        }
117
-
118
-        $text = "Closed 0";
119
-        if ($entry->getAction() == $text) {
120
-            // Dropped the request - short-circuit the lookup
121
-            return "dropped request";
122
-        }
123
-
124
-        $text = "Closed ";
125
-        if (substr($entry->getAction(), 0, strlen($text)) == $text) {
126
-            // Closed with a reason - do a lookup here.
127
-            $id = substr($entry->getAction(), strlen($text));
128
-            /** @var EmailTemplate $template */
129
-            $template = EmailTemplate::getById((int)$id, $entry->getDatabase());
130
-
131
-            if ($template != false) {
132
-                return "closed (" . $template->getName() . ")";
133
-            }
134
-        }
135
-
136
-        // Fall back to the basic stuff
137
-        $lookup = array(
138
-            'Reserved'            => 'reserved',
139
-            'Email Confirmed'     => 'email-confirmed',
140
-            'Unreserved'          => 'unreserved',
141
-            'Approved'            => 'approved',
142
-            'Suspended'           => 'suspended',
143
-            'RoleChange'          => 'changed roles',
144
-            'Banned'              => 'banned',
145
-            'Edited'              => 'edited interface message',
146
-            'Declined'            => 'declined',
147
-            'EditComment-c'       => 'edited a comment',
148
-            'EditComment-r'       => 'edited a comment',
149
-            'Unbanned'            => 'unbanned',
150
-            'Promoted'            => 'promoted to tool admin',
151
-            'BreakReserve'        => 'forcibly broke the reservation',
152
-            'Prefchange'          => 'changed user preferences',
153
-            'Renamed'             => 'renamed',
154
-            'Demoted'             => 'demoted from tool admin',
155
-            'ReceiveReserved'     => 'received the reservation',
156
-            'SendReserved'        => 'sent the reservation',
157
-            'EditedEmail'         => 'edited email',
158
-            'DeletedTemplate'     => 'deleted template',
159
-            'EditedTemplate'      => 'edited template',
160
-            'CreatedEmail'        => 'created email',
161
-            'CreatedTemplate'     => 'created template',
162
-            'SentMail'            => 'sent an email to the requester',
163
-            'Registered'          => 'registered a tool account',
164
-            'JobIssue'            => 'ran a background job unsuccessfully',
165
-            'JobCompleted'        => 'completed a background job',
166
-            'JobAcknowledged'     => 'acknowledged a job failure',
167
-            'JobRequeued'         => 'requeued a job for re-execution',
168
-            'EnqueuedJobQueue'    => 'scheduled for creation',
169
-            'Hospitalised'        => 'sent to the hospital',
170
-        );
171
-
172
-        if (array_key_exists($entry->getAction(), $lookup)) {
173
-            return $lookup[$entry->getAction()];
174
-        }
175
-
176
-        // OK, I don't know what this is. Fall back to something sane.
177
-        return "performed an unknown action ({$entry->getAction()})";
178
-    }
179
-
180
-    /**
181
-     * @param PdoDatabase $database
182
-     *
183
-     * @return array
184
-     */
185
-    public static function getLogActions(PdoDatabase $database)
186
-    {
187
-        $lookup = array(
188
-            'Reserved'            => 'reserved',
189
-            'Email Confirmed'     => 'email-confirmed',
190
-            'Unreserved'          => 'unreserved',
191
-            'Approved'            => 'approved',
192
-            'Suspended'           => 'suspended',
193
-            'RoleChange'          => 'changed roles',
194
-            'Banned'              => 'banned',
195
-            'Edited'              => 'edited interface message',
196
-            'Declined'            => 'declined',
197
-            'EditComment-c'       => 'edited a comment (by comment ID)',
198
-            'EditComment-r'       => 'edited a comment (by request)',
199
-            'Unbanned'            => 'unbanned',
200
-            'Promoted'            => 'promoted to tool admin',
201
-            'BreakReserve'        => 'forcibly broke the reservation',
202
-            'Prefchange'          => 'changed user preferences',
203
-            'Renamed'             => 'renamed',
204
-            'Demoted'             => 'demoted from tool admin',
205
-            'ReceiveReserved'     => 'received the reservation',
206
-            'SendReserved'        => 'sent the reservation',
207
-            'EditedEmail'         => 'edited email',
208
-            'DeletedTemplate'     => 'deleted template',
209
-            'EditedTemplate'      => 'edited template',
210
-            'CreatedEmail'        => 'created email',
211
-            'CreatedTemplate'     => 'created template',
212
-            'SentMail'            => 'sent an email to the requester',
213
-            'Registered'          => 'registered a tool account',
214
-            'Closed 0'            => 'dropped request',
215
-            'JobIssue'            => 'ran a background job unsuccessfully',
216
-            'JobCompleted'        => 'completed a background job',
217
-            'JobAcknowledged'     => 'acknowledged a job failure',
218
-            'JobRequeued'         => 'requeued a job for re-execution',
219
-            'EnqueuedJobQueue'    => 'scheduled for creation',
220
-            'Hospitalised'        => 'sent to the hospital',
221
-        );
222
-
223
-        $statement = $database->query(<<<SQL
30
+	/**
31
+	 * Summary of getRequestLogsWithComments
32
+	 *
33
+	 * @param int             $requestId
34
+	 * @param PdoDatabase     $db
35
+	 * @param SecurityManager $securityManager
36
+	 *
37
+	 * @return DataObject[]
38
+	 */
39
+	public static function getRequestLogsWithComments($requestId, PdoDatabase $db, SecurityManager $securityManager)
40
+	{
41
+		$logs = LogSearchHelper::get($db)->byObjectType('Request')->byObjectId($requestId)->fetch();
42
+
43
+		$currentUser = User::getCurrent($db);
44
+		$securityResult = $securityManager->allows('RequestData', 'seeRestrictedComments', $currentUser);
45
+		$showAllComments = $securityResult === SecurityManager::ALLOWED;
46
+
47
+		$comments = Comment::getForRequest($requestId, $db, $showAllComments, $currentUser->getId());
48
+
49
+		$items = array_merge($logs, $comments);
50
+
51
+		/**
52
+		 * @param DataObject $item
53
+		 *
54
+		 * @return int
55
+		 */
56
+		$sortKey = function(DataObject $item) {
57
+			if ($item instanceof Log) {
58
+				return $item->getTimestamp()->getTimestamp();
59
+			}
60
+
61
+			if ($item instanceof Comment) {
62
+				return $item->getTime()->getTimestamp();
63
+			}
64
+
65
+			return 0;
66
+		};
67
+
68
+		do {
69
+			$flag = false;
70
+
71
+			$loopLimit = (count($items) - 1);
72
+			for ($i = 0; $i < $loopLimit; $i++) {
73
+				// are these two items out of order?
74
+				if ($sortKey($items[$i]) > $sortKey($items[$i + 1])) {
75
+					// swap them
76
+					$swap = $items[$i];
77
+					$items[$i] = $items[$i + 1];
78
+					$items[$i + 1] = $swap;
79
+
80
+					// set a flag to say we've modified the array this time around
81
+					$flag = true;
82
+				}
83
+			}
84
+		}
85
+		while ($flag);
86
+
87
+		return $items;
88
+	}
89
+
90
+	/**
91
+	 * Summary of getLogDescription
92
+	 *
93
+	 * @param Log $entry
94
+	 *
95
+	 * @return string
96
+	 */
97
+	public static function getLogDescription(Log $entry)
98
+	{
99
+		$text = "Deferred to ";
100
+		if (substr($entry->getAction(), 0, strlen($text)) == $text) {
101
+			// Deferred to a different queue
102
+			// This is exactly what we want to display.
103
+			return $entry->getAction();
104
+		}
105
+
106
+		$text = "Closed custom-n";
107
+		if ($entry->getAction() == $text) {
108
+			// Custom-closed
109
+			return "closed (custom reason - account not created)";
110
+		}
111
+
112
+		$text = "Closed custom-y";
113
+		if ($entry->getAction() == $text) {
114
+			// Custom-closed
115
+			return "closed (custom reason - account created)";
116
+		}
117
+
118
+		$text = "Closed 0";
119
+		if ($entry->getAction() == $text) {
120
+			// Dropped the request - short-circuit the lookup
121
+			return "dropped request";
122
+		}
123
+
124
+		$text = "Closed ";
125
+		if (substr($entry->getAction(), 0, strlen($text)) == $text) {
126
+			// Closed with a reason - do a lookup here.
127
+			$id = substr($entry->getAction(), strlen($text));
128
+			/** @var EmailTemplate $template */
129
+			$template = EmailTemplate::getById((int)$id, $entry->getDatabase());
130
+
131
+			if ($template != false) {
132
+				return "closed (" . $template->getName() . ")";
133
+			}
134
+		}
135
+
136
+		// Fall back to the basic stuff
137
+		$lookup = array(
138
+			'Reserved'            => 'reserved',
139
+			'Email Confirmed'     => 'email-confirmed',
140
+			'Unreserved'          => 'unreserved',
141
+			'Approved'            => 'approved',
142
+			'Suspended'           => 'suspended',
143
+			'RoleChange'          => 'changed roles',
144
+			'Banned'              => 'banned',
145
+			'Edited'              => 'edited interface message',
146
+			'Declined'            => 'declined',
147
+			'EditComment-c'       => 'edited a comment',
148
+			'EditComment-r'       => 'edited a comment',
149
+			'Unbanned'            => 'unbanned',
150
+			'Promoted'            => 'promoted to tool admin',
151
+			'BreakReserve'        => 'forcibly broke the reservation',
152
+			'Prefchange'          => 'changed user preferences',
153
+			'Renamed'             => 'renamed',
154
+			'Demoted'             => 'demoted from tool admin',
155
+			'ReceiveReserved'     => 'received the reservation',
156
+			'SendReserved'        => 'sent the reservation',
157
+			'EditedEmail'         => 'edited email',
158
+			'DeletedTemplate'     => 'deleted template',
159
+			'EditedTemplate'      => 'edited template',
160
+			'CreatedEmail'        => 'created email',
161
+			'CreatedTemplate'     => 'created template',
162
+			'SentMail'            => 'sent an email to the requester',
163
+			'Registered'          => 'registered a tool account',
164
+			'JobIssue'            => 'ran a background job unsuccessfully',
165
+			'JobCompleted'        => 'completed a background job',
166
+			'JobAcknowledged'     => 'acknowledged a job failure',
167
+			'JobRequeued'         => 'requeued a job for re-execution',
168
+			'EnqueuedJobQueue'    => 'scheduled for creation',
169
+			'Hospitalised'        => 'sent to the hospital',
170
+		);
171
+
172
+		if (array_key_exists($entry->getAction(), $lookup)) {
173
+			return $lookup[$entry->getAction()];
174
+		}
175
+
176
+		// OK, I don't know what this is. Fall back to something sane.
177
+		return "performed an unknown action ({$entry->getAction()})";
178
+	}
179
+
180
+	/**
181
+	 * @param PdoDatabase $database
182
+	 *
183
+	 * @return array
184
+	 */
185
+	public static function getLogActions(PdoDatabase $database)
186
+	{
187
+		$lookup = array(
188
+			'Reserved'            => 'reserved',
189
+			'Email Confirmed'     => 'email-confirmed',
190
+			'Unreserved'          => 'unreserved',
191
+			'Approved'            => 'approved',
192
+			'Suspended'           => 'suspended',
193
+			'RoleChange'          => 'changed roles',
194
+			'Banned'              => 'banned',
195
+			'Edited'              => 'edited interface message',
196
+			'Declined'            => 'declined',
197
+			'EditComment-c'       => 'edited a comment (by comment ID)',
198
+			'EditComment-r'       => 'edited a comment (by request)',
199
+			'Unbanned'            => 'unbanned',
200
+			'Promoted'            => 'promoted to tool admin',
201
+			'BreakReserve'        => 'forcibly broke the reservation',
202
+			'Prefchange'          => 'changed user preferences',
203
+			'Renamed'             => 'renamed',
204
+			'Demoted'             => 'demoted from tool admin',
205
+			'ReceiveReserved'     => 'received the reservation',
206
+			'SendReserved'        => 'sent the reservation',
207
+			'EditedEmail'         => 'edited email',
208
+			'DeletedTemplate'     => 'deleted template',
209
+			'EditedTemplate'      => 'edited template',
210
+			'CreatedEmail'        => 'created email',
211
+			'CreatedTemplate'     => 'created template',
212
+			'SentMail'            => 'sent an email to the requester',
213
+			'Registered'          => 'registered a tool account',
214
+			'Closed 0'            => 'dropped request',
215
+			'JobIssue'            => 'ran a background job unsuccessfully',
216
+			'JobCompleted'        => 'completed a background job',
217
+			'JobAcknowledged'     => 'acknowledged a job failure',
218
+			'JobRequeued'         => 'requeued a job for re-execution',
219
+			'EnqueuedJobQueue'    => 'scheduled for creation',
220
+			'Hospitalised'        => 'sent to the hospital',
221
+		);
222
+
223
+		$statement = $database->query(<<<SQL
224 224
 SELECT CONCAT('Closed ', id) AS k, CONCAT('closed (',name,')') AS v
225 225
 FROM emailtemplate;
226 226
 SQL
227
-        );
228
-        foreach ($statement->fetchAll(PDO::FETCH_ASSOC) as $row) {
229
-            $lookup[$row['k']] = $row['v'];
230
-        }
231
-
232
-        return $lookup;
233
-    }
234
-
235
-    public static function getObjectTypes()
236
-    {
237
-        return array(
238
-            'Ban'             => 'Ban',
239
-            'Comment'         => 'Comment',
240
-            'EmailTemplate'   => 'Email template',
241
-            'JobQueue'        => 'Job queue item',
242
-            'Request'         => 'Request',
243
-            'SiteNotice'      => 'Site notice',
244
-            'User'            => 'User',
245
-            'WelcomeTemplate' => 'Welcome template',
246
-        );
247
-    }
248
-
249
-    /**
250
-     * This returns a HTML
251
-     *
252
-     * @param string            $objectId
253
-     * @param string            $objectType
254
-     * @param PdoDatabase       $database
255
-     * @param SiteConfiguration $configuration
256
-     *
257
-     * @return null|string
258
-     * @category Security-Critical
259
-     */
260
-    private static function getObjectDescription(
261
-        $objectId,
262
-        $objectType,
263
-        PdoDatabase $database,
264
-        SiteConfiguration $configuration
265
-    ) {
266
-        if ($objectType == '') {
267
-            return null;
268
-        }
269
-
270
-        $baseurl = $configuration->getBaseUrl();
271
-
272
-        switch ($objectType) {
273
-            case 'Ban':
274
-                /** @var Ban $ban */
275
-                $ban = Ban::getById($objectId, $database);
276
-
277
-                if ($ban === false) {
278
-                    return 'Ban #' . $objectId . "</a>";
279
-                }
280
-
281
-                return 'Ban #' . $objectId . " (" . htmlentities($ban->getTarget()) . ")</a>";
282
-            case 'EmailTemplate':
283
-                /** @var EmailTemplate $emailTemplate */
284
-                $emailTemplate = EmailTemplate::getById($objectId, $database);
285
-                $name = htmlentities($emailTemplate->getName(), ENT_COMPAT, 'UTF-8');
286
-
287
-                return <<<HTML
227
+		);
228
+		foreach ($statement->fetchAll(PDO::FETCH_ASSOC) as $row) {
229
+			$lookup[$row['k']] = $row['v'];
230
+		}
231
+
232
+		return $lookup;
233
+	}
234
+
235
+	public static function getObjectTypes()
236
+	{
237
+		return array(
238
+			'Ban'             => 'Ban',
239
+			'Comment'         => 'Comment',
240
+			'EmailTemplate'   => 'Email template',
241
+			'JobQueue'        => 'Job queue item',
242
+			'Request'         => 'Request',
243
+			'SiteNotice'      => 'Site notice',
244
+			'User'            => 'User',
245
+			'WelcomeTemplate' => 'Welcome template',
246
+		);
247
+	}
248
+
249
+	/**
250
+	 * This returns a HTML
251
+	 *
252
+	 * @param string            $objectId
253
+	 * @param string            $objectType
254
+	 * @param PdoDatabase       $database
255
+	 * @param SiteConfiguration $configuration
256
+	 *
257
+	 * @return null|string
258
+	 * @category Security-Critical
259
+	 */
260
+	private static function getObjectDescription(
261
+		$objectId,
262
+		$objectType,
263
+		PdoDatabase $database,
264
+		SiteConfiguration $configuration
265
+	) {
266
+		if ($objectType == '') {
267
+			return null;
268
+		}
269
+
270
+		$baseurl = $configuration->getBaseUrl();
271
+
272
+		switch ($objectType) {
273
+			case 'Ban':
274
+				/** @var Ban $ban */
275
+				$ban = Ban::getById($objectId, $database);
276
+
277
+				if ($ban === false) {
278
+					return 'Ban #' . $objectId . "</a>";
279
+				}
280
+
281
+				return 'Ban #' . $objectId . " (" . htmlentities($ban->getTarget()) . ")</a>";
282
+			case 'EmailTemplate':
283
+				/** @var EmailTemplate $emailTemplate */
284
+				$emailTemplate = EmailTemplate::getById($objectId, $database);
285
+				$name = htmlentities($emailTemplate->getName(), ENT_COMPAT, 'UTF-8');
286
+
287
+				return <<<HTML
288 288
 <a href="{$baseurl}/internal.php/emailManagement/view?id={$objectId}">Email Template #{$objectId} ({$name})</a>
289 289
 HTML;
290
-            case 'SiteNotice':
291
-                return "<a href=\"{$baseurl}/internal.php/siteNotice\">the site notice</a>";
292
-            case 'Request':
293
-                /** @var Request $request */
294
-                $request = Request::getById($objectId, $database);
295
-                $name = htmlentities($request->getName(), ENT_COMPAT, 'UTF-8');
296
-
297
-                return <<<HTML
290
+			case 'SiteNotice':
291
+				return "<a href=\"{$baseurl}/internal.php/siteNotice\">the site notice</a>";
292
+			case 'Request':
293
+				/** @var Request $request */
294
+				$request = Request::getById($objectId, $database);
295
+				$name = htmlentities($request->getName(), ENT_COMPAT, 'UTF-8');
296
+
297
+				return <<<HTML
298 298
 <a href="{$baseurl}/internal.php/viewRequest?id={$objectId}">Request #{$objectId} ({$name})</a>
299 299
 HTML;
300
-            case 'User':
301
-                /** @var User $user */
302
-                $user = User::getById($objectId, $database);
303
-                $username = htmlentities($user->getUsername(), ENT_COMPAT, 'UTF-8');
304
-
305
-                return "<a href=\"{$baseurl}/internal.php/statistics/users/detail?user={$objectId}\">{$username}</a>";
306
-            case 'WelcomeTemplate':
307
-                /** @var WelcomeTemplate $welcomeTemplate */
308
-                $welcomeTemplate = WelcomeTemplate::getById($objectId, $database);
309
-
310
-                // some old templates have been completely deleted and lost to the depths of time.
311
-                if ($welcomeTemplate === false) {
312
-                    return "Welcome template #{$objectId}";
313
-                }
314
-                else {
315
-                    $userCode = htmlentities($welcomeTemplate->getUserCode(), ENT_COMPAT, 'UTF-8');
316
-
317
-                    return "<a href=\"{$baseurl}/internal.php/welcomeTemplates/view?template={$objectId}\">{$userCode}</a>";
318
-                }
319
-            case 'JobQueue':
320
-                /** @var JobQueue $job */
321
-                $job = JobQueue::getById($objectId, $database);
322
-
323
-                $taskDescriptions = JobQueue::getTaskDescriptions();
324
-
325
-                $task = $job->getTask();
326
-                if(isset($taskDescriptions[$task])){
327
-                    $description = $taskDescriptions[$task];
328
-                } else {
329
-                    $description = 'Unknown task';
330
-                }
331
-
332
-                return "<a href=\"{$baseurl}/internal.php/jobQueue/view?id={$objectId}\">Job #{$job->getId()} ({$description})</a>";
333
-            default:
334
-                return '[' . $objectType . " " . $objectId . ']';
335
-        }
336
-    }
337
-
338
-    /**
339
-     * @param Log[]             $logs
340
-     * @param PdoDatabase       $database
341
-     * @param SiteConfiguration $configuration
342
-     *
343
-     * @return array
344
-     * @throws Exception
345
-     */
346
-    public static function prepareLogsForTemplate($logs, PdoDatabase $database, SiteConfiguration $configuration)
347
-    {
348
-        $userIds = array();
349
-
350
-	    foreach ($logs as $logEntry) {
351
-            if (!$logEntry instanceof Log) {
352
-                // if this happens, we've done something wrong with passing back the log data.
353
-                throw new Exception('Log entry is not an instance of a Log, this should never happen.');
354
-            }
355
-
356
-            $user = $logEntry->getUser();
357
-            if ($user === -1) {
358
-                continue;
359
-            }
360
-
361
-            if (!array_search($user, $userIds)) {
362
-                $userIds[] = $user;
363
-            }
364
-        }
365
-
366
-        $users = UserSearchHelper::get($database)->inIds($userIds)->fetchMap('username');
367
-        $users[-1] = User::getCommunity()->getUsername();
368
-
369
-        $logData = array();
370
-
371
-	    foreach ($logs as $logEntry) {
372
-            $objectDescription = self::getObjectDescription($logEntry->getObjectId(), $logEntry->getObjectType(),
373
-                $database, $configuration);
374
-
375
-            // initialise to sane default
376
-            $comment = null;
377
-
378
-            switch ($logEntry->getAction()) {
379
-                case 'Renamed':
380
-                    $renameData = unserialize($logEntry->getComment());
381
-                    $oldName = htmlentities($renameData['old'], ENT_COMPAT, 'UTF-8');
382
-                    $newName = htmlentities($renameData['new'], ENT_COMPAT, 'UTF-8');
383
-                    $comment = 'Renamed \'' . $oldName . '\' to \'' . $newName . '\'.';
384
-                    break;
385
-                case 'RoleChange':
386
-                    $roleChangeData = unserialize($logEntry->getComment());
387
-
388
-                    $removed = array();
389
-                    foreach ($roleChangeData['removed'] as $r) {
390
-                        $removed[] = htmlentities($r, ENT_COMPAT, 'UTF-8');
391
-                    }
392
-
393
-                    $added = array();
394
-                    foreach ($roleChangeData['added'] as $r) {
395
-                        $added[] = htmlentities($r, ENT_COMPAT, 'UTF-8');
396
-                    }
397
-
398
-                    $reason = htmlentities($roleChangeData['reason'], ENT_COMPAT, 'UTF-8');
399
-
400
-                    $roleDelta = 'Removed [' . implode(', ', $removed) . '], Added [' . implode(', ', $added) . ']';
401
-                    $comment = $roleDelta . ' with comment: ' . $reason;
402
-                    break;
403
-                case 'JobIssue':
404
-                    $jobIssueData = unserialize($logEntry->getComment());
405
-                    $errorMessage = $jobIssueData['error'];
406
-                    $status = $jobIssueData['status'];
407
-
408
-                    $comment = 'Job ' . htmlentities($status, ENT_COMPAT, 'UTF-8') . ': ';
409
-                    $comment .= htmlentities($errorMessage, ENT_COMPAT, 'UTF-8');
410
-                    break;
411
-                case 'JobIssueRequest':
412
-                case 'JobCompletedRequest':
413
-                    $jobData = unserialize($logEntry->getComment());
414
-
415
-                    /** @var JobQueue $job */
416
-                    $job = JobQueue::getById($jobData['job'], $database);
417
-                    $descs = JobQueue::getTaskDescriptions();
418
-                    $comment = htmlentities($descs[$job->getTask()], ENT_COMPAT, 'UTF-8');
419
-                    break;
420
-
421
-                case 'JobCompleted':
422
-                    break;
423
-                default:
424
-                    $comment = $logEntry->getComment();
425
-                    break;
426
-            }
427
-
428
-            $logData[] = array(
429
-                'timestamp'         => $logEntry->getTimestamp(),
430
-                'userid'            => $logEntry->getUser(),
431
-                'username'          => $users[$logEntry->getUser()],
432
-                'description'       => self::getLogDescription($logEntry),
433
-                'objectdescription' => $objectDescription,
434
-                'comment'           => $comment,
435
-            );
436
-        }
437
-
438
-        return array($users, $logData);
439
-    }
300
+			case 'User':
301
+				/** @var User $user */
302
+				$user = User::getById($objectId, $database);
303
+				$username = htmlentities($user->getUsername(), ENT_COMPAT, 'UTF-8');
304
+
305
+				return "<a href=\"{$baseurl}/internal.php/statistics/users/detail?user={$objectId}\">{$username}</a>";
306
+			case 'WelcomeTemplate':
307
+				/** @var WelcomeTemplate $welcomeTemplate */
308
+				$welcomeTemplate = WelcomeTemplate::getById($objectId, $database);
309
+
310
+				// some old templates have been completely deleted and lost to the depths of time.
311
+				if ($welcomeTemplate === false) {
312
+					return "Welcome template #{$objectId}";
313
+				}
314
+				else {
315
+					$userCode = htmlentities($welcomeTemplate->getUserCode(), ENT_COMPAT, 'UTF-8');
316
+
317
+					return "<a href=\"{$baseurl}/internal.php/welcomeTemplates/view?template={$objectId}\">{$userCode}</a>";
318
+				}
319
+			case 'JobQueue':
320
+				/** @var JobQueue $job */
321
+				$job = JobQueue::getById($objectId, $database);
322
+
323
+				$taskDescriptions = JobQueue::getTaskDescriptions();
324
+
325
+				$task = $job->getTask();
326
+				if(isset($taskDescriptions[$task])){
327
+					$description = $taskDescriptions[$task];
328
+				} else {
329
+					$description = 'Unknown task';
330
+				}
331
+
332
+				return "<a href=\"{$baseurl}/internal.php/jobQueue/view?id={$objectId}\">Job #{$job->getId()} ({$description})</a>";
333
+			default:
334
+				return '[' . $objectType . " " . $objectId . ']';
335
+		}
336
+	}
337
+
338
+	/**
339
+	 * @param Log[]             $logs
340
+	 * @param PdoDatabase       $database
341
+	 * @param SiteConfiguration $configuration
342
+	 *
343
+	 * @return array
344
+	 * @throws Exception
345
+	 */
346
+	public static function prepareLogsForTemplate($logs, PdoDatabase $database, SiteConfiguration $configuration)
347
+	{
348
+		$userIds = array();
349
+
350
+		foreach ($logs as $logEntry) {
351
+			if (!$logEntry instanceof Log) {
352
+				// if this happens, we've done something wrong with passing back the log data.
353
+				throw new Exception('Log entry is not an instance of a Log, this should never happen.');
354
+			}
355
+
356
+			$user = $logEntry->getUser();
357
+			if ($user === -1) {
358
+				continue;
359
+			}
360
+
361
+			if (!array_search($user, $userIds)) {
362
+				$userIds[] = $user;
363
+			}
364
+		}
365
+
366
+		$users = UserSearchHelper::get($database)->inIds($userIds)->fetchMap('username');
367
+		$users[-1] = User::getCommunity()->getUsername();
368
+
369
+		$logData = array();
370
+
371
+		foreach ($logs as $logEntry) {
372
+			$objectDescription = self::getObjectDescription($logEntry->getObjectId(), $logEntry->getObjectType(),
373
+				$database, $configuration);
374
+
375
+			// initialise to sane default
376
+			$comment = null;
377
+
378
+			switch ($logEntry->getAction()) {
379
+				case 'Renamed':
380
+					$renameData = unserialize($logEntry->getComment());
381
+					$oldName = htmlentities($renameData['old'], ENT_COMPAT, 'UTF-8');
382
+					$newName = htmlentities($renameData['new'], ENT_COMPAT, 'UTF-8');
383
+					$comment = 'Renamed \'' . $oldName . '\' to \'' . $newName . '\'.';
384
+					break;
385
+				case 'RoleChange':
386
+					$roleChangeData = unserialize($logEntry->getComment());
387
+
388
+					$removed = array();
389
+					foreach ($roleChangeData['removed'] as $r) {
390
+						$removed[] = htmlentities($r, ENT_COMPAT, 'UTF-8');
391
+					}
392
+
393
+					$added = array();
394
+					foreach ($roleChangeData['added'] as $r) {
395
+						$added[] = htmlentities($r, ENT_COMPAT, 'UTF-8');
396
+					}
397
+
398
+					$reason = htmlentities($roleChangeData['reason'], ENT_COMPAT, 'UTF-8');
399
+
400
+					$roleDelta = 'Removed [' . implode(', ', $removed) . '], Added [' . implode(', ', $added) . ']';
401
+					$comment = $roleDelta . ' with comment: ' . $reason;
402
+					break;
403
+				case 'JobIssue':
404
+					$jobIssueData = unserialize($logEntry->getComment());
405
+					$errorMessage = $jobIssueData['error'];
406
+					$status = $jobIssueData['status'];
407
+
408
+					$comment = 'Job ' . htmlentities($status, ENT_COMPAT, 'UTF-8') . ': ';
409
+					$comment .= htmlentities($errorMessage, ENT_COMPAT, 'UTF-8');
410
+					break;
411
+				case 'JobIssueRequest':
412
+				case 'JobCompletedRequest':
413
+					$jobData = unserialize($logEntry->getComment());
414
+
415
+					/** @var JobQueue $job */
416
+					$job = JobQueue::getById($jobData['job'], $database);
417
+					$descs = JobQueue::getTaskDescriptions();
418
+					$comment = htmlentities($descs[$job->getTask()], ENT_COMPAT, 'UTF-8');
419
+					break;
420
+
421
+				case 'JobCompleted':
422
+					break;
423
+				default:
424
+					$comment = $logEntry->getComment();
425
+					break;
426
+			}
427
+
428
+			$logData[] = array(
429
+				'timestamp'         => $logEntry->getTimestamp(),
430
+				'userid'            => $logEntry->getUser(),
431
+				'username'          => $users[$logEntry->getUser()],
432
+				'description'       => self::getLogDescription($logEntry),
433
+				'objectdescription' => $objectDescription,
434
+				'comment'           => $comment,
435
+			);
436
+		}
437
+
438
+		return array($users, $logData);
439
+	}
440 440
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -323,7 +323,7 @@
 block discarded – undo
323 323
                 $taskDescriptions = JobQueue::getTaskDescriptions();
324 324
 
325 325
                 $task = $job->getTask();
326
-                if(isset($taskDescriptions[$task])){
326
+                if (isset($taskDescriptions[$task])) {
327 327
                     $description = $taskDescriptions[$task];
328 328
                 } else {
329 329
                     $description = 'Unknown task';
Please login to merge, or discard this patch.
Braces   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -53,7 +53,8 @@  discard block
 block discarded – undo
53 53
          *
54 54
          * @return int
55 55
          */
56
-        $sortKey = function(DataObject $item) {
56
+        $sortKey = function(DataObject $item)
57
+        {
57 58
             if ($item instanceof Log) {
58 59
                 return $item->getTimestamp()->getTimestamp();
59 60
             }
@@ -310,8 +311,7 @@  discard block
 block discarded – undo
310 311
                 // some old templates have been completely deleted and lost to the depths of time.
311 312
                 if ($welcomeTemplate === false) {
312 313
                     return "Welcome template #{$objectId}";
313
-                }
314
-                else {
314
+                } else {
315 315
                     $userCode = htmlentities($welcomeTemplate->getUserCode(), ENT_COMPAT, 'UTF-8');
316 316
 
317 317
                     return "<a href=\"{$baseurl}/internal.php/welcomeTemplates/view?template={$objectId}\">{$userCode}</a>";
@@ -323,7 +323,7 @@  discard block
 block discarded – undo
323 323
                 $taskDescriptions = JobQueue::getTaskDescriptions();
324 324
 
325 325
                 $task = $job->getTask();
326
-                if(isset($taskDescriptions[$task])){
326
+                if(isset($taskDescriptions[$task])) {
327 327
                     $description = $taskDescriptions[$task];
328 328
                 } else {
329 329
                     $description = 'Unknown task';
Please login to merge, or discard this patch.
includes/Tasks/InternalPageBase.php 2 patches
Indentation   +220 added lines, -220 removed lines patch added patch discarded remove patch
@@ -22,224 +22,224 @@
 block discarded – undo
22 22
 
23 23
 abstract class InternalPageBase extends PageBase
24 24
 {
25
-    use NavigationMenuAccessControl;
26
-
27
-    /** @var ITypeAheadHelper */
28
-    private $typeAheadHelper;
29
-    /** @var SecurityManager */
30
-    private $securityManager;
31
-    /** @var IBlacklistHelper */
32
-    private $blacklistHelper;
33
-
34
-    /**
35
-     * @return ITypeAheadHelper
36
-     */
37
-    public function getTypeAheadHelper()
38
-    {
39
-        return $this->typeAheadHelper;
40
-    }
41
-
42
-    /**
43
-     * @param ITypeAheadHelper $typeAheadHelper
44
-     */
45
-    public function setTypeAheadHelper(ITypeAheadHelper $typeAheadHelper)
46
-    {
47
-        $this->typeAheadHelper = $typeAheadHelper;
48
-    }
49
-
50
-    /**
51
-     * Runs the page code
52
-     *
53
-     * @throws Exception
54
-     * @category Security-Critical
55
-     */
56
-    final public function execute()
57
-    {
58
-        if ($this->getRouteName() === null) {
59
-            throw new Exception("Request is unrouted.");
60
-        }
61
-
62
-        if ($this->getSiteConfiguration() === null) {
63
-            throw new Exception("Page has no configuration!");
64
-        }
65
-
66
-        $this->setupPage();
67
-
68
-        $this->touchUserLastActive();
69
-
70
-        $currentUser = User::getCurrent($this->getDatabase());
71
-
72
-        // Hey, this is also a security barrier, in addition to the below. Separated out for readability.
73
-        if (!$this->isProtectedPage()) {
74
-            // This page is /not/ a protected page, as such we can just run it.
75
-            $this->runPage();
76
-
77
-            return;
78
-        }
79
-
80
-        // Security barrier.
81
-        //
82
-        // This code essentially doesn't care if the user is logged in or not, as the security manager hides all that
83
-        // away for us
84
-        $securityResult = $this->getSecurityManager()->allows(get_called_class(), $this->getRouteName(), $currentUser);
85
-        if ($securityResult === SecurityManager::ALLOWED) {
86
-            // We're allowed to run the page, so let's run it.
87
-            $this->runPage();
88
-        }
89
-        else {
90
-            $this->handleAccessDenied($securityResult);
91
-
92
-            // Send the headers
93
-            $this->sendResponseHeaders();
94
-        }
95
-    }
96
-
97
-    /**
98
-     * Performs final tasks needed before rendering the page.
99
-     */
100
-    final public function finalisePage()
101
-    {
102
-        parent::finalisePage();
103
-
104
-        $database = $this->getDatabase();
105
-        $currentUser = User::getCurrent($database);
106
-
107
-        if ($this->barrierTest('viewSiteNotice', User::getCurrent($database), 'GlobalInfo')) {
108
-            $siteNotice = SiteNotice::get($this->getDatabase());
109
-            $siteNoticeHash = sha1($siteNotice);
110
-
111
-            if (WebRequest::testSiteNoticeCookieValue($siteNoticeHash)) {
112
-                $this->assign('siteNoticeState', 'd-none');
113
-            }
114
-            else {
115
-                $this->assign('siteNoticeState', 'd-block');
116
-            }
117
-
118
-            $this->assign('siteNoticeText', $siteNotice);
119
-            $this->assign('siteNoticeVersion', $siteNoticeHash);
120
-        }
121
-
122
-        if ($this->barrierTest('viewOnlineUsers', User::getCurrent($database), 'GlobalInfo')) {
123
-            $sql = 'SELECT * FROM user WHERE lastactive > DATE_SUB(CURRENT_TIMESTAMP(), INTERVAL 5 MINUTE);';
124
-            $statement = $database->query($sql);
125
-            $activeUsers = $statement->fetchAll(PDO::FETCH_CLASS, User::class);
126
-            $this->assign('onlineusers', $activeUsers);
127
-        }
128
-
129
-        $this->setupNavMenuAccess($currentUser);
130
-    }
131
-
132
-    /**
133
-     * Configures whether the page respects roles or not. You probably want this to return true.
134
-     *
135
-     * Set to false for public pages. You probably want this to return true.
136
-     *
137
-     * This defaults to true unless you explicitly set it to false. Setting it to false means anybody can do anything
138
-     * on this page, so you probably want this to return true.
139
-     *
140
-     * @return bool
141
-     * @category Security-Critical
142
-     */
143
-    protected function isProtectedPage()
144
-    {
145
-        return true;
146
-    }
147
-
148
-    protected function handleAccessDenied($denyReason)
149
-    {
150
-        $currentUser = User::getCurrent($this->getDatabase());
151
-
152
-        // Not allowed to access this resource.
153
-        // Firstly, let's check if we're even logged in.
154
-        if ($currentUser->isCommunityUser()) {
155
-            // Not logged in, redirect to login page
156
-            WebRequest::setPostLoginRedirect();
157
-            $this->redirect("login");
158
-
159
-            return;
160
-        }
161
-        else {
162
-            // Decide whether this was a rights failure, or an identification failure.
163
-
164
-            if ($denyReason === SecurityManager::ERROR_NOT_IDENTIFIED) {
165
-                // Not identified
166
-                throw new NotIdentifiedException($this->getSecurityManager());
167
-            }
168
-            elseif ($denyReason === SecurityManager::ERROR_DENIED) {
169
-                // Nope, plain old access denied
170
-                throw new AccessDeniedException($this->getSecurityManager());
171
-            }
172
-            else {
173
-                throw new Exception('Unknown response from security manager.');
174
-            }
175
-        }
176
-    }
177
-
178
-    /**
179
-     * Tests the security barrier for a specified action.
180
-     *
181
-     * Don't use within templates
182
-     *
183
-     * @param string      $action
184
-     *
185
-     * @param User        $user
186
-     * @param null|string $pageName
187
-     *
188
-     * @return bool
189
-     * @category Security-Critical
190
-     */
191
-    final public function barrierTest($action, User $user, $pageName = null)
192
-    {
193
-        $page = get_called_class();
194
-        if ($pageName !== null) {
195
-            $page = $pageName;
196
-        }
197
-
198
-        $securityResult = $this->getSecurityManager()->allows($page, $action, $user);
199
-
200
-        return $securityResult === SecurityManager::ALLOWED;
201
-    }
202
-
203
-    /**
204
-     * Updates the lastactive timestamp
205
-     */
206
-    private function touchUserLastActive()
207
-    {
208
-        if (WebRequest::getSessionUserId() !== null) {
209
-            $query = 'UPDATE user SET lastactive = CURRENT_TIMESTAMP() WHERE id = :id;';
210
-            $this->getDatabase()->prepare($query)->execute(array(":id" => WebRequest::getSessionUserId()));
211
-        }
212
-    }
213
-
214
-    /**
215
-     * @return SecurityManager
216
-     */
217
-    public function getSecurityManager()
218
-    {
219
-        return $this->securityManager;
220
-    }
221
-
222
-    /**
223
-     * @param SecurityManager $securityManager
224
-     */
225
-    public function setSecurityManager(SecurityManager $securityManager)
226
-    {
227
-        $this->securityManager = $securityManager;
228
-    }
229
-
230
-    /**
231
-     * @return IBlacklistHelper
232
-     */
233
-    public function getBlacklistHelper()
234
-    {
235
-        return $this->blacklistHelper;
236
-    }
237
-
238
-    /**
239
-     * @param IBlacklistHelper $blacklistHelper
240
-     */
241
-    public function setBlacklistHelper(IBlacklistHelper $blacklistHelper)
242
-    {
243
-        $this->blacklistHelper = $blacklistHelper;
244
-    }
25
+	use NavigationMenuAccessControl;
26
+
27
+	/** @var ITypeAheadHelper */
28
+	private $typeAheadHelper;
29
+	/** @var SecurityManager */
30
+	private $securityManager;
31
+	/** @var IBlacklistHelper */
32
+	private $blacklistHelper;
33
+
34
+	/**
35
+	 * @return ITypeAheadHelper
36
+	 */
37
+	public function getTypeAheadHelper()
38
+	{
39
+		return $this->typeAheadHelper;
40
+	}
41
+
42
+	/**
43
+	 * @param ITypeAheadHelper $typeAheadHelper
44
+	 */
45
+	public function setTypeAheadHelper(ITypeAheadHelper $typeAheadHelper)
46
+	{
47
+		$this->typeAheadHelper = $typeAheadHelper;
48
+	}
49
+
50
+	/**
51
+	 * Runs the page code
52
+	 *
53
+	 * @throws Exception
54
+	 * @category Security-Critical
55
+	 */
56
+	final public function execute()
57
+	{
58
+		if ($this->getRouteName() === null) {
59
+			throw new Exception("Request is unrouted.");
60
+		}
61
+
62
+		if ($this->getSiteConfiguration() === null) {
63
+			throw new Exception("Page has no configuration!");
64
+		}
65
+
66
+		$this->setupPage();
67
+
68
+		$this->touchUserLastActive();
69
+
70
+		$currentUser = User::getCurrent($this->getDatabase());
71
+
72
+		// Hey, this is also a security barrier, in addition to the below. Separated out for readability.
73
+		if (!$this->isProtectedPage()) {
74
+			// This page is /not/ a protected page, as such we can just run it.
75
+			$this->runPage();
76
+
77
+			return;
78
+		}
79
+
80
+		// Security barrier.
81
+		//
82
+		// This code essentially doesn't care if the user is logged in or not, as the security manager hides all that
83
+		// away for us
84
+		$securityResult = $this->getSecurityManager()->allows(get_called_class(), $this->getRouteName(), $currentUser);
85
+		if ($securityResult === SecurityManager::ALLOWED) {
86
+			// We're allowed to run the page, so let's run it.
87
+			$this->runPage();
88
+		}
89
+		else {
90
+			$this->handleAccessDenied($securityResult);
91
+
92
+			// Send the headers
93
+			$this->sendResponseHeaders();
94
+		}
95
+	}
96
+
97
+	/**
98
+	 * Performs final tasks needed before rendering the page.
99
+	 */
100
+	final public function finalisePage()
101
+	{
102
+		parent::finalisePage();
103
+
104
+		$database = $this->getDatabase();
105
+		$currentUser = User::getCurrent($database);
106
+
107
+		if ($this->barrierTest('viewSiteNotice', User::getCurrent($database), 'GlobalInfo')) {
108
+			$siteNotice = SiteNotice::get($this->getDatabase());
109
+			$siteNoticeHash = sha1($siteNotice);
110
+
111
+			if (WebRequest::testSiteNoticeCookieValue($siteNoticeHash)) {
112
+				$this->assign('siteNoticeState', 'd-none');
113
+			}
114
+			else {
115
+				$this->assign('siteNoticeState', 'd-block');
116
+			}
117
+
118
+			$this->assign('siteNoticeText', $siteNotice);
119
+			$this->assign('siteNoticeVersion', $siteNoticeHash);
120
+		}
121
+
122
+		if ($this->barrierTest('viewOnlineUsers', User::getCurrent($database), 'GlobalInfo')) {
123
+			$sql = 'SELECT * FROM user WHERE lastactive > DATE_SUB(CURRENT_TIMESTAMP(), INTERVAL 5 MINUTE);';
124
+			$statement = $database->query($sql);
125
+			$activeUsers = $statement->fetchAll(PDO::FETCH_CLASS, User::class);
126
+			$this->assign('onlineusers', $activeUsers);
127
+		}
128
+
129
+		$this->setupNavMenuAccess($currentUser);
130
+	}
131
+
132
+	/**
133
+	 * Configures whether the page respects roles or not. You probably want this to return true.
134
+	 *
135
+	 * Set to false for public pages. You probably want this to return true.
136
+	 *
137
+	 * This defaults to true unless you explicitly set it to false. Setting it to false means anybody can do anything
138
+	 * on this page, so you probably want this to return true.
139
+	 *
140
+	 * @return bool
141
+	 * @category Security-Critical
142
+	 */
143
+	protected function isProtectedPage()
144
+	{
145
+		return true;
146
+	}
147
+
148
+	protected function handleAccessDenied($denyReason)
149
+	{
150
+		$currentUser = User::getCurrent($this->getDatabase());
151
+
152
+		// Not allowed to access this resource.
153
+		// Firstly, let's check if we're even logged in.
154
+		if ($currentUser->isCommunityUser()) {
155
+			// Not logged in, redirect to login page
156
+			WebRequest::setPostLoginRedirect();
157
+			$this->redirect("login");
158
+
159
+			return;
160
+		}
161
+		else {
162
+			// Decide whether this was a rights failure, or an identification failure.
163
+
164
+			if ($denyReason === SecurityManager::ERROR_NOT_IDENTIFIED) {
165
+				// Not identified
166
+				throw new NotIdentifiedException($this->getSecurityManager());
167
+			}
168
+			elseif ($denyReason === SecurityManager::ERROR_DENIED) {
169
+				// Nope, plain old access denied
170
+				throw new AccessDeniedException($this->getSecurityManager());
171
+			}
172
+			else {
173
+				throw new Exception('Unknown response from security manager.');
174
+			}
175
+		}
176
+	}
177
+
178
+	/**
179
+	 * Tests the security barrier for a specified action.
180
+	 *
181
+	 * Don't use within templates
182
+	 *
183
+	 * @param string      $action
184
+	 *
185
+	 * @param User        $user
186
+	 * @param null|string $pageName
187
+	 *
188
+	 * @return bool
189
+	 * @category Security-Critical
190
+	 */
191
+	final public function barrierTest($action, User $user, $pageName = null)
192
+	{
193
+		$page = get_called_class();
194
+		if ($pageName !== null) {
195
+			$page = $pageName;
196
+		}
197
+
198
+		$securityResult = $this->getSecurityManager()->allows($page, $action, $user);
199
+
200
+		return $securityResult === SecurityManager::ALLOWED;
201
+	}
202
+
203
+	/**
204
+	 * Updates the lastactive timestamp
205
+	 */
206
+	private function touchUserLastActive()
207
+	{
208
+		if (WebRequest::getSessionUserId() !== null) {
209
+			$query = 'UPDATE user SET lastactive = CURRENT_TIMESTAMP() WHERE id = :id;';
210
+			$this->getDatabase()->prepare($query)->execute(array(":id" => WebRequest::getSessionUserId()));
211
+		}
212
+	}
213
+
214
+	/**
215
+	 * @return SecurityManager
216
+	 */
217
+	public function getSecurityManager()
218
+	{
219
+		return $this->securityManager;
220
+	}
221
+
222
+	/**
223
+	 * @param SecurityManager $securityManager
224
+	 */
225
+	public function setSecurityManager(SecurityManager $securityManager)
226
+	{
227
+		$this->securityManager = $securityManager;
228
+	}
229
+
230
+	/**
231
+	 * @return IBlacklistHelper
232
+	 */
233
+	public function getBlacklistHelper()
234
+	{
235
+		return $this->blacklistHelper;
236
+	}
237
+
238
+	/**
239
+	 * @param IBlacklistHelper $blacklistHelper
240
+	 */
241
+	public function setBlacklistHelper(IBlacklistHelper $blacklistHelper)
242
+	{
243
+		$this->blacklistHelper = $blacklistHelper;
244
+	}
245 245
 }
Please login to merge, or discard this patch.
Braces   +5 added lines, -10 removed lines patch added patch discarded remove patch
@@ -85,8 +85,7 @@  discard block
 block discarded – undo
85 85
         if ($securityResult === SecurityManager::ALLOWED) {
86 86
             // We're allowed to run the page, so let's run it.
87 87
             $this->runPage();
88
-        }
89
-        else {
88
+        } else {
90 89
             $this->handleAccessDenied($securityResult);
91 90
 
92 91
             // Send the headers
@@ -110,8 +109,7 @@  discard block
 block discarded – undo
110 109
 
111 110
             if (WebRequest::testSiteNoticeCookieValue($siteNoticeHash)) {
112 111
                 $this->assign('siteNoticeState', 'd-none');
113
-            }
114
-            else {
112
+            } else {
115 113
                 $this->assign('siteNoticeState', 'd-block');
116 114
             }
117 115
 
@@ -157,19 +155,16 @@  discard block
 block discarded – undo
157 155
             $this->redirect("login");
158 156
 
159 157
             return;
160
-        }
161
-        else {
158
+        } else {
162 159
             // Decide whether this was a rights failure, or an identification failure.
163 160
 
164 161
             if ($denyReason === SecurityManager::ERROR_NOT_IDENTIFIED) {
165 162
                 // Not identified
166 163
                 throw new NotIdentifiedException($this->getSecurityManager());
167
-            }
168
-            elseif ($denyReason === SecurityManager::ERROR_DENIED) {
164
+            } elseif ($denyReason === SecurityManager::ERROR_DENIED) {
169 165
                 // Nope, plain old access denied
170 166
                 throw new AccessDeniedException($this->getSecurityManager());
171
-            }
172
-            else {
167
+            } else {
173 168
                 throw new Exception('Unknown response from security manager.');
174 169
             }
175 170
         }
Please login to merge, or discard this patch.
includes/Tasks/PageBase.php 3 patches
Indentation   +370 added lines, -370 removed lines patch added patch discarded remove patch
@@ -22,374 +22,374 @@
 block discarded – undo
22 22
 
23 23
 abstract class PageBase extends TaskBase implements IRoutedTask
24 24
 {
25
-    use TemplateOutput;
26
-    /** @var string Smarty template to display */
27
-    protected $template = "base.tpl";
28
-    /** @var string HTML title. Currently unused. */
29
-    protected $htmlTitle;
30
-    /** @var bool Determines if the page is a redirect or not */
31
-    protected $isRedirecting = false;
32
-    /** @var array Queue of headers to be sent on successful completion */
33
-    protected $headerQueue = array();
34
-    /** @var string The name of the route to use, as determined by the request router. */
35
-    private $routeName = null;
36
-    /** @var TokenManager */
37
-    protected $tokenManager;
38
-    /** @var ContentSecurityPolicyManager */
39
-    private $cspManager;
40
-    /** @var string[] Extra JS files to include */
41
-    private $extraJs = array();
42
-    /** @var bool Don't show (and hence clear) session alerts when this page is displayed  */
43
-    private $hideAlerts = false;
44
-
45
-    /**
46
-     * Sets the route the request will take. Only should be called from the request router or barrier test.
47
-     *
48
-     * @param string $routeName        The name of the route
49
-     * @param bool   $skipCallableTest Don't use this unless you know what you're doing, and what the implications are.
50
-     *
51
-     * @throws Exception
52
-     * @category Security-Critical
53
-     */
54
-    final public function setRoute($routeName, $skipCallableTest = false)
55
-    {
56
-        // Test the new route is callable before adopting it.
57
-        if (!$skipCallableTest && !is_callable(array($this, $routeName))) {
58
-            throw new Exception("Proposed route '$routeName' is not callable.");
59
-        }
60
-
61
-        // Adopt the new route
62
-        $this->routeName = $routeName;
63
-    }
64
-
65
-    /**
66
-     * Gets the name of the route that has been passed from the request router.
67
-     * @return string
68
-     */
69
-    final public function getRouteName()
70
-    {
71
-        return $this->routeName;
72
-    }
73
-
74
-    /**
75
-     * Performs generic page setup actions
76
-     */
77
-    final protected function setupPage()
78
-    {
79
-        $this->setUpSmarty();
80
-
81
-        $currentUser = User::getCurrent($this->getDatabase());
82
-        $this->assign('currentUser', $currentUser);
83
-        $this->assign('loggedIn', (!$currentUser->isCommunityUser()));
84
-    }
85
-
86
-    /**
87
-     * Runs the page logic as routed by the RequestRouter
88
-     *
89
-     * Only should be called after a security barrier! That means only from execute().
90
-     */
91
-    final protected function runPage()
92
-    {
93
-        $database = $this->getDatabase();
94
-
95
-        // initialise a database transaction
96
-        if (!$database->beginTransaction()) {
97
-            throw new Exception('Failed to start transaction on primary database.');
98
-        }
99
-
100
-        try {
101
-            // run the page code
102
-            $this->{$this->getRouteName()}();
103
-
104
-            $database->commit();
105
-        }
106
-        /** @noinspection PhpRedundantCatchClauseInspection */
107
-        catch (ApplicationLogicException $ex) {
108
-            // it's an application logic exception, so nothing went seriously wrong with the site. We can use the
109
-            // standard templating system for this.
110
-
111
-            // Firstly, let's undo anything that happened to the database.
112
-            $database->rollBack();
113
-
114
-            // Reset smarty
115
-            $this->setupPage();
116
-
117
-            $this->skipAlerts();
118
-
119
-            // Set the template
120
-            $this->setTemplate('exception/application-logic.tpl');
121
-            $this->assign('message', $ex->getMessage());
122
-
123
-            // Force this back to false
124
-            $this->isRedirecting = false;
125
-            $this->headerQueue = array();
126
-        }
127
-        /** @noinspection PhpRedundantCatchClauseInspection */
128
-        catch (OptimisticLockFailedException $ex) {
129
-            // it's an optimistic lock failure exception, so nothing went seriously wrong with the site. We can use the
130
-            // standard templating system for this.
131
-
132
-            // Firstly, let's undo anything that happened to the database.
133
-            $database->rollBack();
134
-
135
-            // Reset smarty
136
-            $this->setupPage();
137
-
138
-            // Set the template
139
-            $this->skipAlerts();
140
-            $this->setTemplate('exception/optimistic-lock-failure.tpl');
141
-            $this->assign('message', $ex->getMessage());
142
-
143
-            $this->assign('debugTrace', false);
144
-
145
-            if ($this->getSiteConfiguration()->getDebuggingTraceEnabled()) {
146
-                ob_start();
147
-                var_dump(ExceptionHandler::getExceptionData($ex));
148
-                $textErrorData = ob_get_contents();
149
-                ob_end_clean();
150
-
151
-                $this->assign('exceptionData', $textErrorData);
152
-                $this->assign('debugTrace', true);
153
-            }
154
-
155
-            // Force this back to false
156
-            $this->isRedirecting = false;
157
-            $this->headerQueue = array();
158
-        }
159
-        finally {
160
-            // Catch any hanging on transactions
161
-            if ($database->hasActiveTransaction()) {
162
-                $database->rollBack();
163
-            }
164
-        }
165
-
166
-        // run any finalisation code needed before we send the output to the browser.
167
-        $this->finalisePage();
168
-
169
-        // Send the headers
170
-        $this->sendResponseHeaders();
171
-
172
-        // Check we have a template to use!
173
-        if ($this->template !== null) {
174
-            $content = $this->fetchTemplate($this->template);
175
-            ob_clean();
176
-            print($content);
177
-            ob_flush();
178
-
179
-            return;
180
-        }
181
-    }
182
-
183
-    /**
184
-     * Performs final tasks needed before rendering the page.
185
-     */
186
-    protected function finalisePage()
187
-    {
188
-        if ($this->isRedirecting) {
189
-            $this->template = null;
190
-
191
-            return;
192
-        }
193
-
194
-        $this->assign('extraJs', $this->extraJs);
195
-
196
-        if (!$this->hideAlerts) {
197
-            // If we're actually displaying content, we want to add the session alerts here!
198
-            $this->assign('alerts', SessionAlert::getAlerts());
199
-            SessionAlert::clearAlerts();
200
-        }
201
-
202
-        $this->assign('htmlTitle', $this->htmlTitle);
203
-    }
204
-
205
-    /**
206
-     * @return TokenManager
207
-     */
208
-    public function getTokenManager()
209
-    {
210
-        return $this->tokenManager;
211
-    }
212
-
213
-    /**
214
-     * @param TokenManager $tokenManager
215
-     */
216
-    public function setTokenManager($tokenManager)
217
-    {
218
-        $this->tokenManager = $tokenManager;
219
-    }
220
-
221
-    /**
222
-     * @return ContentSecurityPolicyManager
223
-     */
224
-    public function getCspManager(): ContentSecurityPolicyManager
225
-    {
226
-        return $this->cspManager;
227
-    }
228
-
229
-    /**
230
-     * @param ContentSecurityPolicyManager $cspManager
231
-     */
232
-    public function setCspManager(ContentSecurityPolicyManager $cspManager): void
233
-    {
234
-        $this->cspManager = $cspManager;
235
-    }
236
-
237
-    /**
238
-     * Skip the display of session alerts in this page
239
-     */
240
-    public function skipAlerts(): void
241
-    {
242
-        $this->hideAlerts = true;
243
-    }
244
-
245
-    /**
246
-     * Sends the redirect headers to perform a GET at the destination page.
247
-     *
248
-     * Also nullifies the set template so Smarty does not render it.
249
-     *
250
-     * @param string      $page   The page to redirect requests to (as used in the UR)
251
-     * @param null|string $action The action to use on the page.
252
-     * @param null|array  $parameters
253
-     * @param null|string $script The script (relative to index.php) to redirect to
254
-     */
255
-    final protected function redirect($page = '', $action = null, $parameters = null, $script = null)
256
-    {
257
-        $currentScriptName = WebRequest::scriptName();
258
-
259
-        // Are we changing script?
260
-        if ($script === null || substr($currentScriptName, -1 * count($script)) === $script) {
261
-            $targetScriptName = $currentScriptName;
262
-        }
263
-        else {
264
-            $targetScriptName = $this->getSiteConfiguration()->getBaseUrl() . '/' . $script;
265
-        }
266
-
267
-        $pathInfo = array($targetScriptName);
268
-
269
-        $pathInfo[1] = $page;
270
-
271
-        if ($action !== null) {
272
-            $pathInfo[2] = $action;
273
-        }
274
-
275
-        $url = implode('/', $pathInfo);
276
-
277
-        if (is_array($parameters) && count($parameters) > 0) {
278
-            $url .= '?' . http_build_query($parameters);
279
-        }
280
-
281
-        $this->redirectUrl($url);
282
-    }
283
-
284
-    /**
285
-     * Sends the redirect headers to perform a GET at the new address.
286
-     *
287
-     * Also nullifies the set template so Smarty does not render it.
288
-     *
289
-     * @param string $path URL to redirect to
290
-     */
291
-    final protected function redirectUrl($path)
292
-    {
293
-        // 303 See Other = re-request at new address with a GET.
294
-        $this->headerQueue[] = 'HTTP/1.1 303 See Other';
295
-        $this->headerQueue[] = "Location: $path";
296
-
297
-        $this->setTemplate(null);
298
-        $this->isRedirecting = true;
299
-    }
300
-
301
-    /**
302
-     * Sets the name of the template this page should display.
303
-     *
304
-     * @param string $name
305
-     *
306
-     * @throws Exception
307
-     */
308
-    final protected function setTemplate($name)
309
-    {
310
-        if ($this->isRedirecting) {
311
-            throw new Exception('This page has been set as a redirect, no template can be displayed!');
312
-        }
313
-
314
-        $this->template = $name;
315
-    }
316
-
317
-    /**
318
-     * Adds an extra JS file to to the page
319
-     *
320
-     * @param string $path The path (relative to the application root) of the file
321
-     */
322
-    final protected function addJs($path){
323
-        if(in_array($path, $this->extraJs)){
324
-            // nothing to do
325
-            return;
326
-        }
327
-
328
-        $this->extraJs[] = $path;
329
-    }
330
-
331
-    /**
332
-     * Main function for this page, when no specific actions are called.
333
-     * @return void
334
-     */
335
-    abstract protected function main();
336
-
337
-    /**
338
-     * Takes a smarty template string and sets the HTML title to that value
339
-     *
340
-     * @param string $title
341
-     *
342
-     * @throws SmartyException
343
-     */
344
-    final protected function setHtmlTitle($title)
345
-    {
346
-        $this->htmlTitle = $this->smarty->fetch('string:' . $title);
347
-    }
348
-
349
-    public function execute()
350
-    {
351
-        if ($this->getRouteName() === null) {
352
-            throw new Exception('Request is unrouted.');
353
-        }
354
-
355
-        if ($this->getSiteConfiguration() === null) {
356
-            throw new Exception('Page has no configuration!');
357
-        }
358
-
359
-        $this->setupPage();
360
-
361
-        $this->runPage();
362
-    }
363
-
364
-    public function assignCSRFToken()
365
-    {
366
-        $token = $this->tokenManager->getNewToken();
367
-        $this->assign('csrfTokenData', $token->getTokenData());
368
-    }
369
-
370
-    public function validateCSRFToken()
371
-    {
372
-        if (!$this->tokenManager->validateToken(WebRequest::postString('csrfTokenData'))) {
373
-            throw new ApplicationLogicException('Form token is not valid, please reload and try again');
374
-        }
375
-    }
376
-
377
-    protected function sendResponseHeaders()
378
-    {
379
-        if (headers_sent()) {
380
-            throw new ApplicationLogicException('Headers have already been sent! This is likely a bug in the application.');
381
-        }
382
-
383
-        // send the CSP headers now
384
-        header($this->getCspManager()->getHeader());
385
-
386
-        foreach ($this->headerQueue as $item) {
387
-            if (mb_strpos($item, "\r") !== false || mb_strpos($item, "\n") !== false) {
388
-                // Oops. We're not allowed to do this.
389
-                throw new Exception('Unable to split header');
390
-            }
391
-
392
-            header($item);
393
-        }
394
-    }
25
+	use TemplateOutput;
26
+	/** @var string Smarty template to display */
27
+	protected $template = "base.tpl";
28
+	/** @var string HTML title. Currently unused. */
29
+	protected $htmlTitle;
30
+	/** @var bool Determines if the page is a redirect or not */
31
+	protected $isRedirecting = false;
32
+	/** @var array Queue of headers to be sent on successful completion */
33
+	protected $headerQueue = array();
34
+	/** @var string The name of the route to use, as determined by the request router. */
35
+	private $routeName = null;
36
+	/** @var TokenManager */
37
+	protected $tokenManager;
38
+	/** @var ContentSecurityPolicyManager */
39
+	private $cspManager;
40
+	/** @var string[] Extra JS files to include */
41
+	private $extraJs = array();
42
+	/** @var bool Don't show (and hence clear) session alerts when this page is displayed  */
43
+	private $hideAlerts = false;
44
+
45
+	/**
46
+	 * Sets the route the request will take. Only should be called from the request router or barrier test.
47
+	 *
48
+	 * @param string $routeName        The name of the route
49
+	 * @param bool   $skipCallableTest Don't use this unless you know what you're doing, and what the implications are.
50
+	 *
51
+	 * @throws Exception
52
+	 * @category Security-Critical
53
+	 */
54
+	final public function setRoute($routeName, $skipCallableTest = false)
55
+	{
56
+		// Test the new route is callable before adopting it.
57
+		if (!$skipCallableTest && !is_callable(array($this, $routeName))) {
58
+			throw new Exception("Proposed route '$routeName' is not callable.");
59
+		}
60
+
61
+		// Adopt the new route
62
+		$this->routeName = $routeName;
63
+	}
64
+
65
+	/**
66
+	 * Gets the name of the route that has been passed from the request router.
67
+	 * @return string
68
+	 */
69
+	final public function getRouteName()
70
+	{
71
+		return $this->routeName;
72
+	}
73
+
74
+	/**
75
+	 * Performs generic page setup actions
76
+	 */
77
+	final protected function setupPage()
78
+	{
79
+		$this->setUpSmarty();
80
+
81
+		$currentUser = User::getCurrent($this->getDatabase());
82
+		$this->assign('currentUser', $currentUser);
83
+		$this->assign('loggedIn', (!$currentUser->isCommunityUser()));
84
+	}
85
+
86
+	/**
87
+	 * Runs the page logic as routed by the RequestRouter
88
+	 *
89
+	 * Only should be called after a security barrier! That means only from execute().
90
+	 */
91
+	final protected function runPage()
92
+	{
93
+		$database = $this->getDatabase();
94
+
95
+		// initialise a database transaction
96
+		if (!$database->beginTransaction()) {
97
+			throw new Exception('Failed to start transaction on primary database.');
98
+		}
99
+
100
+		try {
101
+			// run the page code
102
+			$this->{$this->getRouteName()}();
103
+
104
+			$database->commit();
105
+		}
106
+		/** @noinspection PhpRedundantCatchClauseInspection */
107
+		catch (ApplicationLogicException $ex) {
108
+			// it's an application logic exception, so nothing went seriously wrong with the site. We can use the
109
+			// standard templating system for this.
110
+
111
+			// Firstly, let's undo anything that happened to the database.
112
+			$database->rollBack();
113
+
114
+			// Reset smarty
115
+			$this->setupPage();
116
+
117
+			$this->skipAlerts();
118
+
119
+			// Set the template
120
+			$this->setTemplate('exception/application-logic.tpl');
121
+			$this->assign('message', $ex->getMessage());
122
+
123
+			// Force this back to false
124
+			$this->isRedirecting = false;
125
+			$this->headerQueue = array();
126
+		}
127
+		/** @noinspection PhpRedundantCatchClauseInspection */
128
+		catch (OptimisticLockFailedException $ex) {
129
+			// it's an optimistic lock failure exception, so nothing went seriously wrong with the site. We can use the
130
+			// standard templating system for this.
131
+
132
+			// Firstly, let's undo anything that happened to the database.
133
+			$database->rollBack();
134
+
135
+			// Reset smarty
136
+			$this->setupPage();
137
+
138
+			// Set the template
139
+			$this->skipAlerts();
140
+			$this->setTemplate('exception/optimistic-lock-failure.tpl');
141
+			$this->assign('message', $ex->getMessage());
142
+
143
+			$this->assign('debugTrace', false);
144
+
145
+			if ($this->getSiteConfiguration()->getDebuggingTraceEnabled()) {
146
+				ob_start();
147
+				var_dump(ExceptionHandler::getExceptionData($ex));
148
+				$textErrorData = ob_get_contents();
149
+				ob_end_clean();
150
+
151
+				$this->assign('exceptionData', $textErrorData);
152
+				$this->assign('debugTrace', true);
153
+			}
154
+
155
+			// Force this back to false
156
+			$this->isRedirecting = false;
157
+			$this->headerQueue = array();
158
+		}
159
+		finally {
160
+			// Catch any hanging on transactions
161
+			if ($database->hasActiveTransaction()) {
162
+				$database->rollBack();
163
+			}
164
+		}
165
+
166
+		// run any finalisation code needed before we send the output to the browser.
167
+		$this->finalisePage();
168
+
169
+		// Send the headers
170
+		$this->sendResponseHeaders();
171
+
172
+		// Check we have a template to use!
173
+		if ($this->template !== null) {
174
+			$content = $this->fetchTemplate($this->template);
175
+			ob_clean();
176
+			print($content);
177
+			ob_flush();
178
+
179
+			return;
180
+		}
181
+	}
182
+
183
+	/**
184
+	 * Performs final tasks needed before rendering the page.
185
+	 */
186
+	protected function finalisePage()
187
+	{
188
+		if ($this->isRedirecting) {
189
+			$this->template = null;
190
+
191
+			return;
192
+		}
193
+
194
+		$this->assign('extraJs', $this->extraJs);
195
+
196
+		if (!$this->hideAlerts) {
197
+			// If we're actually displaying content, we want to add the session alerts here!
198
+			$this->assign('alerts', SessionAlert::getAlerts());
199
+			SessionAlert::clearAlerts();
200
+		}
201
+
202
+		$this->assign('htmlTitle', $this->htmlTitle);
203
+	}
204
+
205
+	/**
206
+	 * @return TokenManager
207
+	 */
208
+	public function getTokenManager()
209
+	{
210
+		return $this->tokenManager;
211
+	}
212
+
213
+	/**
214
+	 * @param TokenManager $tokenManager
215
+	 */
216
+	public function setTokenManager($tokenManager)
217
+	{
218
+		$this->tokenManager = $tokenManager;
219
+	}
220
+
221
+	/**
222
+	 * @return ContentSecurityPolicyManager
223
+	 */
224
+	public function getCspManager(): ContentSecurityPolicyManager
225
+	{
226
+		return $this->cspManager;
227
+	}
228
+
229
+	/**
230
+	 * @param ContentSecurityPolicyManager $cspManager
231
+	 */
232
+	public function setCspManager(ContentSecurityPolicyManager $cspManager): void
233
+	{
234
+		$this->cspManager = $cspManager;
235
+	}
236
+
237
+	/**
238
+	 * Skip the display of session alerts in this page
239
+	 */
240
+	public function skipAlerts(): void
241
+	{
242
+		$this->hideAlerts = true;
243
+	}
244
+
245
+	/**
246
+	 * Sends the redirect headers to perform a GET at the destination page.
247
+	 *
248
+	 * Also nullifies the set template so Smarty does not render it.
249
+	 *
250
+	 * @param string      $page   The page to redirect requests to (as used in the UR)
251
+	 * @param null|string $action The action to use on the page.
252
+	 * @param null|array  $parameters
253
+	 * @param null|string $script The script (relative to index.php) to redirect to
254
+	 */
255
+	final protected function redirect($page = '', $action = null, $parameters = null, $script = null)
256
+	{
257
+		$currentScriptName = WebRequest::scriptName();
258
+
259
+		// Are we changing script?
260
+		if ($script === null || substr($currentScriptName, -1 * count($script)) === $script) {
261
+			$targetScriptName = $currentScriptName;
262
+		}
263
+		else {
264
+			$targetScriptName = $this->getSiteConfiguration()->getBaseUrl() . '/' . $script;
265
+		}
266
+
267
+		$pathInfo = array($targetScriptName);
268
+
269
+		$pathInfo[1] = $page;
270
+
271
+		if ($action !== null) {
272
+			$pathInfo[2] = $action;
273
+		}
274
+
275
+		$url = implode('/', $pathInfo);
276
+
277
+		if (is_array($parameters) && count($parameters) > 0) {
278
+			$url .= '?' . http_build_query($parameters);
279
+		}
280
+
281
+		$this->redirectUrl($url);
282
+	}
283
+
284
+	/**
285
+	 * Sends the redirect headers to perform a GET at the new address.
286
+	 *
287
+	 * Also nullifies the set template so Smarty does not render it.
288
+	 *
289
+	 * @param string $path URL to redirect to
290
+	 */
291
+	final protected function redirectUrl($path)
292
+	{
293
+		// 303 See Other = re-request at new address with a GET.
294
+		$this->headerQueue[] = 'HTTP/1.1 303 See Other';
295
+		$this->headerQueue[] = "Location: $path";
296
+
297
+		$this->setTemplate(null);
298
+		$this->isRedirecting = true;
299
+	}
300
+
301
+	/**
302
+	 * Sets the name of the template this page should display.
303
+	 *
304
+	 * @param string $name
305
+	 *
306
+	 * @throws Exception
307
+	 */
308
+	final protected function setTemplate($name)
309
+	{
310
+		if ($this->isRedirecting) {
311
+			throw new Exception('This page has been set as a redirect, no template can be displayed!');
312
+		}
313
+
314
+		$this->template = $name;
315
+	}
316
+
317
+	/**
318
+	 * Adds an extra JS file to to the page
319
+	 *
320
+	 * @param string $path The path (relative to the application root) of the file
321
+	 */
322
+	final protected function addJs($path){
323
+		if(in_array($path, $this->extraJs)){
324
+			// nothing to do
325
+			return;
326
+		}
327
+
328
+		$this->extraJs[] = $path;
329
+	}
330
+
331
+	/**
332
+	 * Main function for this page, when no specific actions are called.
333
+	 * @return void
334
+	 */
335
+	abstract protected function main();
336
+
337
+	/**
338
+	 * Takes a smarty template string and sets the HTML title to that value
339
+	 *
340
+	 * @param string $title
341
+	 *
342
+	 * @throws SmartyException
343
+	 */
344
+	final protected function setHtmlTitle($title)
345
+	{
346
+		$this->htmlTitle = $this->smarty->fetch('string:' . $title);
347
+	}
348
+
349
+	public function execute()
350
+	{
351
+		if ($this->getRouteName() === null) {
352
+			throw new Exception('Request is unrouted.');
353
+		}
354
+
355
+		if ($this->getSiteConfiguration() === null) {
356
+			throw new Exception('Page has no configuration!');
357
+		}
358
+
359
+		$this->setupPage();
360
+
361
+		$this->runPage();
362
+	}
363
+
364
+	public function assignCSRFToken()
365
+	{
366
+		$token = $this->tokenManager->getNewToken();
367
+		$this->assign('csrfTokenData', $token->getTokenData());
368
+	}
369
+
370
+	public function validateCSRFToken()
371
+	{
372
+		if (!$this->tokenManager->validateToken(WebRequest::postString('csrfTokenData'))) {
373
+			throw new ApplicationLogicException('Form token is not valid, please reload and try again');
374
+		}
375
+	}
376
+
377
+	protected function sendResponseHeaders()
378
+	{
379
+		if (headers_sent()) {
380
+			throw new ApplicationLogicException('Headers have already been sent! This is likely a bug in the application.');
381
+		}
382
+
383
+		// send the CSP headers now
384
+		header($this->getCspManager()->getHeader());
385
+
386
+		foreach ($this->headerQueue as $item) {
387
+			if (mb_strpos($item, "\r") !== false || mb_strpos($item, "\n") !== false) {
388
+				// Oops. We're not allowed to do this.
389
+				throw new Exception('Unable to split header');
390
+			}
391
+
392
+			header($item);
393
+		}
394
+	}
395 395
 }
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -319,8 +319,8 @@
 block discarded – undo
319 319
      *
320 320
      * @param string $path The path (relative to the application root) of the file
321 321
      */
322
-    final protected function addJs($path){
323
-        if(in_array($path, $this->extraJs)){
322
+    final protected function addJs($path) {
323
+        if (in_array($path, $this->extraJs)) {
324 324
             // nothing to do
325 325
             return;
326 326
         }
Please login to merge, or discard this patch.
Braces   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -259,8 +259,7 @@  discard block
 block discarded – undo
259 259
         // Are we changing script?
260 260
         if ($script === null || substr($currentScriptName, -1 * count($script)) === $script) {
261 261
             $targetScriptName = $currentScriptName;
262
-        }
263
-        else {
262
+        } else {
264 263
             $targetScriptName = $this->getSiteConfiguration()->getBaseUrl() . '/' . $script;
265 264
         }
266 265
 
@@ -319,8 +318,9 @@  discard block
 block discarded – undo
319 318
      *
320 319
      * @param string $path The path (relative to the application root) of the file
321 320
      */
322
-    final protected function addJs($path){
323
-        if(in_array($path, $this->extraJs)){
321
+    final protected function addJs($path)
322
+    {
323
+        if(in_array($path, $this->extraJs)) {
324 324
             // nothing to do
325 325
             return;
326 326
         }
Please login to merge, or discard this patch.