Completed
Pull Request — master (#203)
by
unknown
40:36
created

ForumMemberProfile::RegistrationForm()   C

Complexity

Conditions 10
Paths 112

Size

Total Lines 58
Code Lines 30

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 58
rs 6.3559
c 0
b 0
f 0
cc 10
eloc 30
nc 112
nop 0

How to fix   Long Method    Complexity   

Long Method

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

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

Commonly applied refactorings include:

1
<?php
2
3
namespace SilverStripe\Forum\Controllers;
4
5
use SilverStripe\Control\Controller;
6
use SilverStripe\Control\Email\Email;
7
use SilverStripe\Control\HTTPRequest;
8
use SilverStripe\Control\HTTPResponse;
9
use SilverStripe\Control\HTTPResponse_Exception;
10
use SilverStripe\Core\Injector\Injector;
11
use SilverStripe\Forum\Models\Post;
12
use SilverStripe\Forum\Pages\ForumHolder;
13
use SilverStripe\ORM\ArrayList;
14
use SilverStripe\ORM\FieldType\DBHTMLText;
15
use SilverStripe\ORM\ManyManyList;
16
use SilverStripe\View\Requirements;
17
use SilverStripe\Core\Convert;
18
use SilverStripe\ORM\FieldType\DBField;
19
use SilverStripe\Control\Session;
20
use SilverStripe\Forms\HiddenField;
21
use SilverStripe\Forms\FormAction;
22
use SilverStripe\Forms\FieldList;
23
use SilverStripe\Forms\Form;
24
use SilverStripe\Forms\LiteralField;
25
use SilverStripe\Security\Member;
26
use SilverStripe\Logging\Log;
27
use SilverStripe\Security\Group;
28
use SilverStripe\Core\Object;
29
use SilverStripe\Forms\TextField;
30
use SilverStripe\Forms\RequiredFields;
31
use SilverStripe\Control\Director;
32
use SilverStripe\ORM\DataObject;
33
use SilverStripe\Forms\TextareaField;
34
use SilverStripe\Security\Security;
35
use PageController;
36
37
/**
38
 * ForumMemberProfile is the profile pages for a given ForumMember
39
 *
40
 * @package forum
41
 */
42
class ForumMemberProfile extends PageController
43
{
44
    /** @var array */
45
    private static $allowed_actions = array(
46
        'show',
47
        'register',
48
        'RegistrationForm',
49
        'registerwithopenid',
50
        'RegistrationWithOpenIDForm',
51
        'edit',
52
        'EditProfileForm',
53
        'thanks',
54
    );
55
56
    /** @var string */
57
    public $URLSegment = "ForumMemberProfile";
58
59
    /**
60
     * Return a set of {@link Forum} objects that
61
     * this member is a moderator of.
62
     *
63
     * @return ManyManyList
64
     */
65
    public function ModeratedForums()
66
    {
67
        $member = $this->Member();
68
69
        return ($member) ? $member->ModeratedForums() : null;
70
    }
71
72
    /**
73
     * Create breadcrumbs (just shows a forum holder link and name of user)
74
     *
75
     * @return string HTML code to display breadcrumbs
76
     */
77
    public function Breadcrumbs()
78
    {
79
        $nonPageParts = array();
80
        $parts        = array();
81
82
        $forumHolder = $this->getForumHolder();
83
84
        $parts[]        = '<a href="' . $forumHolder->Link() . '">' . $forumHolder->Title . '</a>';
85
        $nonPageParts[] = _t('ForumMemberProfile.USERPROFILE', 'User Profile');
86
87
        return implode(" &raquo; ", array_reverse(array_merge($nonPageParts, $parts)));
88
    }
89
90
    /**
91
     * Initialise the controller
92
     */
93
    public function init()
94
    {
95
        Requirements::themedCSS('Forum', 'all');
96
        $member       = $this->Member() ? $this->Member() : null;
97
        $nicknameText = ($member) ? ($member->Nickname . '\'s ') : '';
98
99
        $this->Title = DBField::create_field('HTMLText', Convert::raw2xml($nicknameText) . _t('ForumMemberProfile.USERPROFILE', 'User Profile'));
100
101
        parent::init();
102
    }
103
104
    /**
105
     * @param HTTPRequest $request
106
     *
107
     * @return DBHTMLText|void
108
     * @throws HTTPResponse_Exception
109
     */
110
    public function show($request)
111
    {
112
        $member = $this->Member();
113
        if (!$member) {
114
            return $this->httpError(404);
115
        }
116
117
        return $this->renderWith(array('ForumMemberProfile_show', 'Page'));
118
    }
119
120
    /**
121
     * Get the latest 10 posts by this member
122
     *
123
     * @return ArrayList
124
     */
125
    public function LatestPosts()
126
    {
127
        return Post::get()
128
            ->filter('AuthorID', (int)$this->urlParams['ID'])
129
            ->limit(10, 0)
130
            ->sort('Created', 'DESC')
131
            ->filterByCallback(function ($post) {
132
                /** @var Post $post */
133
                return $post->canView();
134
            });
135
    }
136
137
    /**
138
     * Show the registration form
139
     */
140
    public function register()
141
    {
142
        return array(
143
            "Title"    => _t('ForumMemberProfile.FORUMREGTITLE', 'Forum Registration'),
144
            "Subtitle" => _t('ForumMemberProfile.REGISTER', 'Register'),
145
            "Abstract" => $this->getForumHolder()->ProfileAbstract,
146
        );
147
    }
148
149
    /**
150
     * Factory method for the registration form
151
     *
152
     * @return Form Returns the registration form
153
     */
154
    public function RegistrationForm()
155
    {
156
        $data = Session::get("FormInfo.Form_RegistrationForm.data");
157
158
        $use_openid =
159
            ($this->getForumHolder()->OpenIDAvailable() == 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...
160
            (isset($data['IdentityURL']) && !empty($data['IdentityURL'])) ||
161
            (isset($_POST['IdentityURL']) && !empty($_POST['IdentityURL']));
162
163
        /** @var FieldList $fields */
164
        $fields = Member::singleton()->getForumFields($use_openid, true);
165
166
        // If a BackURL is provided, make it hidden so the post-registration
167
        // can direct to it.
168
        if (isset($_REQUEST['BackURL'])) {
169
            $fields->push(new HiddenField('BackURL', 'BackURL', $_REQUEST['BackURL']));
170
        }
171
172
        $validator = singleton(Member::class)->getForumValidator(!$use_openid);
173
        $form      = new Form(
174
            $this,
175
            'RegistrationForm',
176
            $fields,
177
            new FieldList(new FormAction("doregister", _t('ForumMemberProfile.REGISTER', 'Register'))),
178
            $validator
179
        );
180
181
        // Guard against automated spam registrations by optionally adding a field
182
        // that is supposed to stay blank (and is hidden from most humans).
183
        // The label and field name are intentionally common ("username"),
184
        // as most spam bots won't resist filling it out. The actual username field
185
        // on the forum is called "Nickname".
186
        if (ForumHolder::$useHoneypotOnRegister) {
187
            $form->Fields()->push(
188
                LiteralField::create(
189
                    'HoneyPot',
190
                    '<div style="position: absolute; left: -9999px;">' .
191
                    // We're super paranoid and don't mention "ignore" or "blank" in the label either
192
                    '<label for="RegistrationForm_username">' . _t('ForumMemberProfile.LeaveBlank',
193
                        'Don\'t enter anything here') . '</label>' .
194
                    '<input type="text" name="username" id="RegistrationForm_username" value="" />' .
195
                    '</div>'
196
                )
197
            );
198
        }
199
200
        // we should also load the data stored in the session. if failed
201
        if (is_array($data)) {
202
            $form->loadDataFrom($data);
203
        }
204
205
        // Optional spam protection
206
        if (class_exists('SpamProtectorManager') && ForumHolder::$useSpamProtectionOnRegister) {
207
            $form->enableSpamProtection();
208
        }
209
210
        return $form;
211
    }
212
213
    /**
214
     * Register a new member
215
     *
216
     * @param array $data User submitted data
217
     * @param Form  $form The used form
218
     *
219
     * @return array|bool|HTTPResponse
220
     */
221
    public function doregister($data, $form)
222
    {
223
        // Check if the honeypot has been filled out
224
        if (ForumHolder::$useHoneypotOnRegister) {
225
            if (isset($data['username'])) {
226
                Injector::inst()->get('Logger')->log(sprintf(
227
                    'Forum honeypot triggered (data: %s)',
228
                    http_build_query($data)
229
                ), Log::NOTICE);
230
231
                return $this->httpError(403);
232
            }
233
        }
234
235
        $forumGroup = Group::get()->filter('Code', 'forum-members')->first();
236
237
        if ($member = Member::get()->filter('Email', $data['Email'])->first()) {
238 View Code Duplication
            if ($member) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
239
                $form->setFieldMessage(
240
                    "Blurb",
241
                    _t(
242
                        'ForumMemberProfile.EMAILEXISTS',
243
                        'Sorry, that email address already exists. Please choose another.'
244
                    ),
245
                    "bad"
246
                );
247
248
                // Load errors into session and post back
249
                Session::set("FormInfo.Form_RegistrationForm.data", $data);
250
251
                return $this->redirectBack();
252
            }
253
        } elseif ($this->getForumHolder()->OpenIDAvailable() && isset($data['IdentityURL']) && ($member = Member::get()->filter('IdentityURL', $data['IdentityURL'])->first())) {
254
            $errorMessage = _t(
255
                'ForumMemberProfile.OPENIDEXISTS',
256
                'Sorry, that OpenID is already registered. Please choose another or register without OpenID.'
257
            );
258
259
            $form->setFieldMessage("Blurb", $errorMessage, "bad");
260
261
            // Load errors into session and post back
262
            Session::set("FormInfo.Form_RegistrationForm.data", $data);
263
264
            return $this->redirectBack();
265
266
        } elseif ($member = Member::get()->filter('Nickname', $data['Nickname'])->first()) {
0 ignored issues
show
Unused Code introduced by
$member is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
267
            $errorMessage = _t(
268
                'ForumMemberProfile.NICKNAMEEXISTS',
269
                'Sorry, that nickname already exists. Please choose another.'
270
            );
271
272
            $form->setFieldMessage("Blurb", $errorMessage, "bad");
273
274
            // Load errors into session and post back
275
            Session::set("FormInfo.Form_RegistrationForm.data", $data);
276
277
            return $this->redirectBack();
278
        }
279
280
        // create the new member
281
        $member = Member::create();
282
        $form->saveInto($member);
283
284
        $member->write();
285
        $member->logIn();
286
287
        $member->Groups()->add($forumGroup);
288
289
        $member->extend('onForumRegister', $this->request);
290
291
        if (isset($data['BackURL']) && $data['BackURL']) {
292
            return $this->redirect($data['BackURL']);
293
        }
294
295
        return ["Form" => ForumHolder::get()->first()->ProfileAdd];
296
    }
297
298
    /**
299
     * Start registration with OpenID
300
     *
301
     * @param array $data    Data passed by the director
302
     * @param array $message Message and message type to output
303
     *
304
     * @return array Returns the needed data to render the registration form.
305
     */
306
    public function registerwithopenid($data, $message = null)
307
    {
308
        if ($message) {
309
            $message = '<p class="' . $message['type'] . '">' . Convert::raw2xml($message['message']) . '</p>';
310
        } else {
311
            $message = "<p>" . _t('ForumMemberProfile.ENTEROPENID', 'Please enter your OpenID to continue the registration') . "</p>";
312
        }
313
314
        return array(
315
            "Title"    => _t('ForumMemberProfile.SSFORUM'),
316
            "Subtitle" => _t('ForumMemberProfile.REGISTEROPENID', 'Register with OpenID'),
317
            "Abstract" => $message,
318
            "Form"     => $this->RegistrationWithOpenIDForm(),
319
        );
320
    }
321
322
    /**
323
     * Factory method for the OpenID registration form
324
     *
325
     * @return Form Returns the OpenID registration form
326
     */
327
    public function RegistrationWithOpenIDForm()
328
    {
329
        $form = Form::create(
330
            $this,
331
            'RegistrationWithOpenIDForm',
332
            FieldList::create(TextField::create("OpenIDURL", "OpenID URL", "", null)),
333
            FieldList::create(FormAction::create("doregisterwithopenid", _t('ForumMemberProfile.REGISTER', 'Register'))),
334
            RequiredFields::create("OpenIDURL")
335
        );
336
337
        return $form;
338
    }
339
340
341
    /**
342
     * Register a new member
343
     *
344
     * @param                          $data
345
     * @param Form                     $form
346
     *
347
     * @return HTTPResponse
348
     */
349
    public function doregisterwithopenid($data, Form $form)
350
    {
351
        $openid = trim($data['OpenIDURL']);
352
        Session::set("FormInfo.Form_RegistrationWithOpenIDForm.data", $data);
353
354 View Code Duplication
        if (strlen($openid) == 0) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
355
            if (!is_null($form)) {
356
                $form->setFieldMessage(
357
                    "Blurb",
358
                    "Please enter your OpenID or your i-name.",
359
                    "bad"
360
                );
361
            }
362
363
            return $this->redirectBack();
364
        }
365
366
        $trust_root    = Director::absoluteBaseURL();
367
        $return_to_url = $trust_root . $this->Link('processopenidresponse');
368
369
        $consumer = new \Auth_OpenID_Consumer(new \OpenIDStorage(), new \SessionWrapper());
370
371
        // No auth request means we can't begin OpenID
372
        $auth_request = $consumer->begin($openid);
373 View Code Duplication
        if (!$auth_request) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
374
            if (!is_null($form)) {
375
                $form->setFieldMessage(
376
                    "Blurb",
377
                    "That doesn't seem to be a valid OpenID or i-name identifier. " .
378
                    "Please try again.",
379
                    "bad"
380
                );
381
            }
382
383
            return $this->redirectBack();
384
        }
385
386
        $identity = Convert::raw2sql($auth_request->endpoint->claimed_id);
387
        if ($member = Member::get()->filter('IdentityURL', $identity)->first()) {
0 ignored issues
show
Unused Code introduced by
$member is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
388
            if (!is_null($form)) {
389
                $form->setFieldMessage(
390
                    "Blurb",
391
                    "That OpenID or i-name is already registered. Use another one.",
392
                    "bad"
393
                );
394
            }
395
396
            return $this->redirectBack();
397
        }
398
399
        // Add the fields for which we wish to get the profile data
400
        $sreg_request = \Auth_OpenID_SRegRequest::build(
401
            null,
402
            ['nickname', 'fullname', 'email', 'country']
403
        );
404
405
        if ($sreg_request) {
406
            $auth_request->addExtension($sreg_request);
407
        }
408
409
410
        if ($auth_request->shouldSendRedirect()) {
411
            // For OpenID 1, send a redirect.
412
            $redirect_url = $auth_request->redirectURL($trust_root, $return_to_url);
413
414
            if (\Auth_OpenID::isFailure($redirect_url)) {
415
                displayError("Could not redirect to server: " .
416
                    $redirect_url->message);
417
            } else {
418
                return $this->redirect($redirect_url);
419
            }
420
        } else {
421
            // For OpenID 2, use a javascript form to send a POST request to the
422
            // server.
423
            $form_id   = 'openid_message';
424
            $form_html = $auth_request->formMarkup($trust_root, $return_to_url, false, array('id' => $form_id));
425
426
            if (\Auth_OpenID::isFailure($form_html)) {
427
                displayError("Could not redirect to server: " . $form_html->message);
428
            } else {
429
                $page_contents = array(
430
                    "<html><head><title>",
431
                    "OpenID transaction in progress",
432
                    "</title></head>",
433
                    "<body onload='document.getElementById(\"" . $form_id .
434
                    "\").submit()'>",
435
                    $form_html,
436
                    "<p>Click &quot;Continue&quot; to login. You are only seeing " .
437
                    "this because you appear to have JavaScript disabled.</p>",
438
                    "</body></html>"
439
                );
440
441
                print implode("\n", $page_contents);
442
            }
443
        }
444
    }
445
446
    /**
447
     * Function to process the response of the OpenID server
448
     */
449
    public function processopenidresponse()
450
    {
451
        $consumer = new \Auth_OpenID_Consumer(new \OpenIDStorage(), new \SessionWrapper());
452
453
        $trust_root    = Director::absoluteBaseURL();
454
        $return_to_url = $trust_root . $this->Link('ProcessOpenIDResponse');
455
456
        // Complete the authentication process using the server's response.
457
        $response = $consumer->complete($return_to_url);
458
459
        if ($response->status == Auth_OpenID_SUCCESS) {
460
            Session::clear("FormInfo.Form_RegistrationWithOpenIDForm.data");
461
            $openid = $response->identity_url;
462
463
            if ($response->endpoint->canonicalID) {
464
                $openid = $response->endpoint->canonicalID;
465
            }
466
467
            $sreg_resp = \Auth_OpenID_SRegResponse::fromSuccessResponse($response);
468
            $sreg      = $sreg_resp->contents();
469
470
            // Convert the simple registration data to the needed format
471
            // try to split fullname to get firstname and surname
472
            $data = array('IdentityURL' => $openid);
473
            if (isset($sreg['nickname'])) {
474
                $data['Nickname'] = $sreg['nickname'];
475
            }
476
            if (isset($sreg['fullname'])) {
477
                $fullname = explode(' ', $sreg['fullname'], 2);
478
                if (count($fullname) == 2) {
479
                    $data['FirstName'] = $fullname[0];
480
                    $data['Surname']   = $fullname[1];
481
                } else {
482
                    $data['Surname'] = $fullname[0];
483
                }
484
            }
485
            if (isset($sreg['country'])) {
486
                $data['Country'] = $sreg['country'];
487
            }
488
            if (isset($sreg['email'])) {
489
                $data['Email'] = $sreg['email'];
490
            }
491
492
            Session::set("FormInfo.Form_RegistrationForm.data", $data);
493
494
            return $this->redirect($this->Link('register'));
495
        }
496
497
        // The server returned an error message, handle it!
498
        if ($response->status == Auth_OpenID_CANCEL) {
499
            $error_message = _t('ForumMemberProfile.CANCELLEDVERIFICATION',
500
                'The verification was cancelled. Please try again.');
501
        } elseif ($response->status == Auth_OpenID_FAILURE) {
502
            $error_message = _t('ForumMemberProfile.AUTHENTICATIONFAILED', 'The OpenID/i-name authentication failed.');
503
        } else {
504
            $error_message = _t('ForumMemberProfile.UNEXPECTEDERROR',
505
                'An unexpected error occured. Please try again or register without OpenID');
506
        }
507
508
        $this->RegistrationWithOpenIDForm()->setFieldMessage(
509
            "Blurb",
510
            $error_message,
511
            'bad'
512
        );
513
514
        return $this->redirect($this->Link('registerwithopenid'));
515
    }
516
517
    /**
518
     * Edit profile
519
     *
520
     * @return array Returns an array to render the edit profile page.
521
     */
522
    public function edit()
523
    {
524
        $holder = DataObject::get_one("ForumHolder");
525
        $form   = $this->EditProfileForm();
526
527
        if (!$form && Member::currentUser()) {
528
            $form = "<p class=\"error message\">" . _t('ForumMemberProfile.WRONGPERMISSION',
529
                    'You don\'t have the permission to edit that member.') . "</p>";
530
        } elseif (!$form) {
531
            return $this->redirect('ForumMemberProfile/show/' . $this->Member()->ID);
532
        }
533
534
        return array(
535
            "Title"    => "Forum",
536
            "Subtitle" => $holder->ProfileSubtitle,
537
            "Abstract" => $holder->ProfileAbstract,
538
            "Form"     => $form,
539
        );
540
    }
541
542
    /**
543
     * Factory method for the edit profile form
544
     *
545
     * @return Form Returns the edit profile form.
546
     */
547
    public function EditProfileForm()
548
    {
549
        $member      = $this->Member();
550
        $show_openid = (isset($member->IdentityURL) && !empty($member->IdentityURL));
551
552
        /** @var FieldList $fields */
553
        $fields    = $member ? $member->getForumFields($show_openid) : Member::singleton()->getForumFields($show_openid);
554
        $validator = $member ? $member->getForumValidator(false) : Member::singleton()->getForumValidator(false);
555
        if ($holder = ForumHolder::get()->filter(["DisplaySignatures" => '1'])) {
0 ignored issues
show
Unused Code introduced by
$holder is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
556
            $fields->push(TextareaField::create('Signature', 'Forum Signature'));
557
        }
558
559
        $form = new Form(
560
            $this,
561
            'EditProfileForm',
562
            $fields,
563
            FieldList::create(FormAction::create("dosave", _t('ForumMemberProfile.SAVECHANGES', 'Save changes'))),
564
            $validator
565
        );
566
567
        if ($member && $member->hasMethod('canEdit') && $member->canEdit()) {
568
            $member->Password = '';
569
            $form->loadDataFrom($member);
570
571
            return $form;
572
        }
573
574
        return null;
575
    }
576
577
    /**
578
     * Save member profile action
579
     *
580
     * @param array $data
581
     * @param Form  $form
582
     *
583
     * @return bool|HTTPResponse
584
     */
585
    public function dosave($data, Form $form)
586
    {
587
        $member = Member::currentUser();
588
589
        $email      = Convert::raw2sql($data['Email']);
590
        $forumGroup = Group::get()->filter(['Code' => 'forum-members']);
591
592
        // An existing member may have the requested email that doesn't belong to the
593
        // person who is editing their profile - if so, throw an error
594
        /** @var Member $existingMember */
595
        $existingMember = Member::get()->filter(['Email' => $email]);
596
        if ($existingMember) {
597 View Code Duplication
            if ($existingMember->ID != $member->ID) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
598
                $form->setFieldMessage(
599
                    'Blurb',
600
                    _t(
601
                        'ForumMemberProfile.EMAILEXISTS',
602
                        'Sorry, that email address already exists. Please choose another.'
603
                    ),
604
                    'bad'
605
                );
606
607
                return $this->redirectBack();
608
            }
609
        }
610
611
        $nicknameCheck = Member::get()->filter(
612
            [
613
                'Nickname' => Convert::raw2sql($data['Nickname']),
614
                'ID:not' => $member->ID
615
            ]
616
        );
617
618
        if ($nicknameCheck) {
619
            $form->setFieldMessage(
620
                "Blurb",
621
                _t('ForumMemberProfile.NICKNAMEEXISTS', 'Sorry, that nickname already exists. Please choose another.'),
622
                "bad"
623
            );
624
625
            return $this->redirectBack();
626
        }
627
628
        $form->saveInto($member);
629
        $member->write();
630
631
        if (!$member->inGroup($forumGroup)) {
632
            $forumGroup->Members()->add($member);
633
        }
634
635
        $member->extend('onForumUpdateProfile', $this->request);
636
637
        return $this->redirect('thanks');
638
    }
639
640
    /**
641
     * Print the "thank you" page
642
     *
643
     * Used after saving changes to a member profile.
644
     *
645
     * @return array Returns the needed data to render the page.
646
     */
647
    public function thanks()
648
    {
649
        return [
650
            "Form" => ForumHolder::get()->first()->ProfileModify
651
        ];
652
    }
653
654
    /**
655
     * Create a link
656
     *
657
     * @param string $action Name of the action to link to
658
     *
659
     * @return string Returns the link to the passed action.
660
     */
661
    public function Link($action = null)
662
    {
663
        return Controller::join_links($this->class, $action);
664
    }
665
666
667
    /**
668
     * Return the with the passed ID (via URL parameters) or the current user
669
     *
670
     * @return null|Member Returns the member object or NULL if the member
671
     *                     was not found
672
     */
673
    public function Member()
674
    {
675
        $member = null;
0 ignored issues
show
Unused Code introduced by
$member is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
676
        if (!empty($this->urlParams['ID']) && is_numeric($this->urlParams['ID'])) {
677
            $member = Member::get()->byID($this->urlParams['ID']);
678
        } else {
679
            $member = Member::currentUser();
680
        }
681
682
        return $member;
683
    }
684
685
    /**
686
     * Get the forum holder controller. Sadly we can't work out which forum holder
687
     *
688
     * @return ForumHolder Returns the forum holder controller.
689
     */
690
    public function getForumHolder()
691
    {
692
        $holders = ForumHolder::get();
693
        if ($holders) {
694
            foreach ($holders as $holder) {
695
                if ($holder->canView()) {
696
                    return $holder;
697
                }
698
            }
699
        }
700
701
        // no usable forums
702
        $messageSet = array(
703
            'default'         => _t('Forum.LOGINTOPOST', "You'll need to login before you can post to that forum. Please do so below."),
704
            'alreadyLoggedIn' => _t('Forum.NOPOSTPERMISSION', "I'm sorry, but you do not have permission to this edit this profile."),
705
            'logInAgain'      => _t('Forum.LOGINTOPOSTAGAIN', 'You have been logged out of the forums.  If you would like to log in again to post, enter a username and password below.'),
706
        );
707
708
        return Security::permissionFailure($this, $messageSet);
709
    }
710
711
    /**
712
     * Get a subtitle
713
     *
714
     * @return string
715
     */
716
    public function getHolderSubtitle()
717
    {
718
        return _t('ForumMemberProfile.USERPROFILE', 'User profile');
719
    }
720
721
722
    /**
723
     * Get the URL segment of the forum holder
724
     *
725
     * @return string
726
     */
727
    public function URLSegment()
728
    {
729
        return $this->getForumHolder()->URLSegment;
730
    }
731
732
733
    /**
734
     * This needs MetaTags because it doesn't extend SiteTree at any point
735
     *
736
     * @return string
737
     */
738
    public function MetaTags($includeTitle = true)
739
    {
740
        $tags  = "";
741
        $title = _t('ForumMemberProfile.FORUMUSERPROFILE', 'Forum User Profile');
742
743
        if (isset($this->urlParams['Action'])) {
744
            if ($this->urlParams['Action'] == "register") {
745
                $title = _t('ForumMemberProfile.FORUMUSERREGISTER', 'Forum Registration');
746
            }
747
        }
748
        if ($includeTitle == 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...
749
            $tags .= sprintf("<title>%s</title>\n", $title);
750
        }
751
752
        return $tags;
753
    }
754
}
755