Passed
Pull Request — master (#1917)
by Struan
34:42
created

COMMENT::create()   B

Complexity

Conditions 6
Paths 6

Size

Total Lines 105
Code Lines 43

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 22.9396

Importance

Changes 0
Metric Value
cc 6
eloc 43
nc 6
nop 1
dl 0
loc 105
ccs 10
cts 45
cp 0.2222
crap 22.9396
rs 8.6097
c 0
b 0
f 0

How to fix   Long Method   

Long Method

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

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

Commonly applied refactorings include:

1
<?php
2
3
/* A class for doing things with single comments.
4
5
    To access stuff about an existing comment you can do something like:
6
        $COMMENT = new COMMENT(37);
7
        $COMMENT->display();
8
    Where '37' is the comment_id.
9
10
    To create a new comment you should get a $data array prepared of
11
    the key/value pairs needed to create a new comment and do:
12
        $COMMENT = new COMMENT;
13
        $COMMENT->create ($data);
14
15
    You can delete a comment by doing $COMMENT->delete() (it isn't actually
16
    deleted from the database, just set to invisible.
17
18
    You can also do $COMMENT->set_modflag() which happens when a user
19
    posts a report about a comment. The flag is unset when/if the report is
20
    rejected.
21
22
*/
23
24
25
26
class COMMENT {
27
    public $comment_id = '';
28
    public $user_id = '';
29
    public $epobject_id = '';
30
    public $body = '';
31
    public $posted = '';
32
    public $visible = false;
33
    public $modflagged = null;	// Is a datetime when set.
34
    public $firstname = '';	// Of the person who posted it.
35
    public $lastname = '';
36
    public $url = '';
37
38
    // So that after trying to init a comment, we can test for
39
    // if it exists in the DB.
40
    public $exists = false;
41
42
43
    public function __construct($comment_id = '') {
44 3
45
        $this->db = new ParlDB();
0 ignored issues
show
Bug Best Practice introduced by
The property db does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
46 3
47
        // Set in init.php
48
        if (ALLOWCOMMENTS == true) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
introduced by
The condition ALLOWCOMMENTS == true is always true.
Loading history...
49 3
            $this->comments_enabled = true;
0 ignored issues
show
Bug Best Practice introduced by
The property comments_enabled does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
50 3
        } else {
51
            $this->comments_enabled = false;
52
        }
53
54
55
        if (is_numeric($comment_id)) {
56 3
            // We're getting the data for an existing comment from the DB.
57
58
            $q = $this->db->query(
59 3
                "SELECT user_id,
60
                                    epobject_id,
61
                                    body,
62
                                    posted,
63
                                    visible,
64
                                    modflagged
65
                            FROM	comments
66
                            WHERE 	comment_id=:comment_id",
67 3
                [':comment_id' => $comment_id]
68
            )->first();
69 3
70
            if ($q) {
71 3
72 3
                $this->comment_id 	= $comment_id;
73 3
                $this->user_id		= $q['user_id'];
74 3
                $this->epobject_id	= $q['epobject_id'];
75 3
                $this->body			= $q['body'];
76 3
                $this->posted		= $q['posted'];
77 3
                $this->visible		= $q['visible'];
78
                $this->modflagged	= $q['modflagged'];
79
80 3
                // Sets the URL and username for this comment. Duh.
81 3
                $this->_set_url();
82
                $this->_set_username();
83 3
84
                $this->exists = true;
85
            } else {
86
                $this->exists = false;
87
            }
88 3
        }
89
    }
90
91
92
    // Use these for accessing the object's variables externally.
93
    public function comment_id() {
94
        return $this->comment_id;
95
    }
96
    public function user_id() {
97
        return $this->user_id;
98
    }
99
    public function epobject_id() {
100
        return $this->epobject_id;
101
    }
102
    public function body() {
103
        return $this->body;
104
    }
105
    public function posted() {
106
        return $this->posted;
107
    }
108
    public function visible() {
109
        return $this->visible;
110
    }
111
    public function modflagged() {
112
        return $this->modflagged;
113
    }
114
    public function exists() {
115
        return $this->exists;
116
    }
117
    public function firstname() {
118
        return $this->firstname;
119
    }
120
    public function lastname() {
121
        return $this->lastname;
122
    }
123
    public function url() {
124
        return $this->url;
125
    }
126
127
    public function comments_enabled() {
128
        return $this->comments_enabled;
129
    }
130
131
132
    public function create($data) {
133
        // Inserts data for this comment into the database.
134
        // $data has 'epobject_id' and 'body' elements.
135
        // Returns the new comment_id if successful, false otherwise.
136
137
        global $THEUSER, $PAGE;
138
139
        if ($this->comments_enabled() == false) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
140
            $PAGE->error_message("Sorry, the posting of annotations has been temporarily disabled.");
141
            return;
142
        }
143
144
        if (!$THEUSER->is_able_to('addcomment')) {
145
            $message = 	array (
146
                'title' => 'Sorry',
147
                'text' => 'You are not allowed to post annotations.'
148
            );
149
            $PAGE->error_message($message);
150
            return false;
151
        }
152
153
        if (!is_numeric ($data['epobject_id'])) {
154
            $message = array (
155
                'title' => 'Sorry',
156
                'text' => "We don't have an epobject id."
157
            );
158
            $PAGE->error_message($message);
159
            return false;
160
        }
161
162
        if ($data['body'] == '') {
163
            $message = array (
164
                'title' => 'Whoops!',
165
                'text' => "You haven't entered an annotation!"
166
            );
167
            $PAGE->error_message($message);
168
            return false;
169
        }
170
171
/*
172
        if (is_numeric($THEUSER->user_id())) {
173
            // Flood check - make sure the user hasn't just posted a comment recently.
174
            // To help prevent accidental duplicates, among other nasty things.
175
176
            $flood_time_limit = 60; // How many seconds until a user can post again?
177
178
            $q = $this->db->query("SELECT comment_id
179
                            FROM	comments
180
                            WHERE	user_id = '" . $THEUSER->user_id() . "'
181
                            AND		posted + 0 > NOW() - $flood_time_limit");
182
183
            if ($q->rows() > 0) {
184
                $message = array (
185
                    'title' => 'Hold your horses!',
186
                    'text' => "We limit people to posting one comment per $flood_time_limit seconds to help prevent duplicate postings. Please go back and try again, thanks."
187
                );
188
                $PAGE->error_message($message);
189
                return false;
190
            }
191
        }
192
*/
193
194
        // OK, let's get on with it...
195
196
        // Tidy up the HTML tags
197
        // (but we don't make URLs into links; only when displaying the comment).
198
        $body = filter_user_input($data['body'], 'comment'); // In utility.php
199
200 3
        $posted = date('Y-m-d H:i:s', time());
201 3
202
203
        $q_gid = $this->db->query("select gid from hansard where epobject_id = :epobject_id", array(':epobject_id' => $data['epobject_id']));
204 3
        $data['gid'] = $q_gid->field(0, 'gid');
205
206 3
        $q = $this->db->query("INSERT INTO comments
207
            (user_id, epobject_id, body, posted, visible, original_gid)
208
            VALUES
209
            (
210 3
            :user_id,
211
            :epobject_id,
212 3
            :body,
213
            :posted,
214
            1,
215
            :gid
216
            )", array(
217
                ':user_id' => $THEUSER->user_id(),
218
                ':epobject_id' => $data['epobject_id'],
219
                ':body' => $body,
220
                ':posted' => $posted,
221
                ':gid' => $data['gid']
222
            ));
223
224
        if ($q->success()) {
225
            // Set the object varibales up.
226 3
            $this->comment_id 	= $q->insert_id();
227
            $this->user_id	  	= $THEUSER->user_id();
228
            $this->epobject_id 	= $data['epobject_id'];
229
            $this->body			= $data['body'];
230 3
            $this->posted		= $posted;
231
            $this->visible		= 1;
232
233 3
            return $this->comment_id();
234 3
235
        } else {
236
            return false;
237
        }
238 3
    }
239
240 3
241 3
    public function display($format='html', $template='comments') {
242 3
        $data['comments'][0] =  [
0 ignored issues
show
Comprehensibility Best Practice introduced by
$data was never initialized. Although not strictly required by PHP, it is generally a good practice to add $data = array(); before regardless.
Loading history...
243
            'comment_id'	=> $this->comment_id,
244
            'user_id'		=> $this->user_id,
245 3
            'epobject_id'	=> $this->epobject_id,
246
            'body'			=> $this->body,
247
            'posted'		=> $this->posted,
248
            'modflagged'	=> $this->modflagged,
249
            'url'			=> $this->url,
250
            'firstname'		=> $this->firstname,
251
            'lastname'		=> $this->lastname,
252
            'visible'		=> $this->visible,
253
        ];
254
255
        // Use the same renderer as the COMMENTLIST class.
256
        $COMMENTLIST = new COMMENTLIST();
257
        $COMMENTLIST->render($data, $format, $template);
258
259
    }
260
261
262
    public function set_modflag($switch) {
263
        // $switch is either 'on' or 'off'.
264
        // The comment's modflag goes to on when someone reports the comment.
265
        // It goes to off when a commentreport has been resolved but the
266
        // comment HASN'T been deleted.
267
        global $PAGE;
268
269
        if ($switch == 'on') {
270
            $date = gmdate("Y-m-d H:i:s");
271
            $flag = "'$date'";
272
273
        } elseif ($switch == 'off') {
274
            $date = null;
275
            $flag = 'NULL';
276
277
        } else {
278
            $PAGE->error_message("Why are you trying to switch this comment's modflag to '" . _htmlentities($switch) . "'!");
279
        }
280
281
        $q = $this->db->query("UPDATE comments
282
                        SET		modflagged = $flag
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $flag does not seem to be defined for all execution paths leading up to this point.
Loading history...
283
                        WHERE 	comment_id = '" . $this->comment_id . "'
284
                        ");
285
286
        if ($q->success()) {
287
            $this->modflagged = $date;
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $date does not seem to be defined for all execution paths leading up to this point.
Loading history...
288
            return true;
289
        } else {
290
            $message =  [
291
                'title' => 'Sorry',
292
                'text' => "We couldn't update the annotation's modflag.",
293
            ];
294
            $PAGE->error_message($message);
295
            return false;
296
        }
297
298
    }
299
300
301
    public function delete() {
302
        // Mark the comment as invisible.
303
304
        global $THEUSER, $PAGE;
305
306
        if ($THEUSER->is_able_to('deletecomment')) {
307
            $q = $this->db->query("UPDATE comments SET visible = '0' WHERE comment_id = '" . $this->comment_id . "'");
308
309
            if ($q->success()) {
310
                return true;
311
            } else {
312
                $message =  [
313
                    'title' => 'Sorry',
314
                    'text' => "We were unable to delete the annotation.",
315
                ];
316
                $PAGE->error_message($message);
317
                return false;
318
            }
319
320
        } else {
321
            $message =  [
322
                'title' => 'Sorry',
323
                'text' => "You are not authorised to delete annotations.",
324
            ];
325
            $PAGE->error_message($message);
326
            return false;
327
        }
328
329
    }
330
331
332
333
    public function _set_url() {
334
        global $hansardmajors;
335
        // Creates and sets the URL for the comment.
336
337
        if ($this->url == '') {
338
339
            $q = $this->db->query(
340
                "SELECT major,
341
                                    gid
342
                            FROM	hansard
343
                            WHERE	epobject_id = :epobject_id",
344
                [':epobject_id' => $this->epobject_id]
345
            )->first();
346
347
            if ($q) {
348
                // If you change stuff here, you might have to change it in
349
                // $COMMENTLIST->_get_comment_data() too...
350
351
                $gid = fix_gid_from_db($q['gid']); // In includes/utility.php
352
353
                $major = $q['major'];
354
                $page = $hansardmajors[$major]['page'];
355
356
                $URL = new \MySociety\TheyWorkForYou\Url($page);
357
                $URL->insert(['id' => $gid]);
358
                $this->url = $URL->generate() . '#c' . $this->comment_id;
359
            }
360
        }
361
    }
362
363
364
365
    public function _set_username() {
366
        // Gets and sets the user's name who posted the comment.
367
368
        if ($this->firstname == '' && $this->lastname == '') {
369
            $q = $this->db->query(
370
                "SELECT firstname,
371
                                    lastname
372
                            FROM	users
373
                            WHERE	user_id = :user_id",
374
                [':user_id' => $this->user_id]
375
            )->first();
376
377
            if ($q) {
378
                $this->firstname = $q['firstname'];
379
                $this->lastname = $q['lastname'];
380
            }
381
        }
382
    }
383
384
385
386
387
}
388