RegisterAndEditDetailsPage   A
last analyzed

Complexity

Total Complexity 29

Size/Duplication

Total Lines 168
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 9

Importance

Changes 0
Metric Value
wmc 29
lcom 1
cbo 9
dl 0
loc 168
rs 10
c 0
b 0
f 0

6 Methods

Rating   Name   Duplication   Size   Complexity  
A showLoggedInFields() 0 6 3
A isCMSRead() 0 4 2
A link_for_going_to_page_via_making_user() 0 7 2
A getCMSFields() 0 17 1
A canCreate() 0 4 2
F requireDefaultRecords() 0 91 19
1
<?php
2
3
/**
4
    * Page containing an edit details form
5
    * Uses Member::getMemberFormFields() to know what to make available for editing
6
    */
7
class RegisterAndEditDetailsPage extends Page
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
8
{
9
    private static $icon = "userpage/images/treeicons/RegisterAndEditDetailsPage";
0 ignored issues
show
Unused Code introduced by
The property $icon is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
10
11
    private static $can_be_root = false;
0 ignored issues
show
Unused Code introduced by
The property $can_be_root is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
12
13
    private static $db = array(
0 ignored issues
show
Unused Code introduced by
The property $db is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
14
        "ThankYouTitle" => "Varchar(255)",
15
        "ThankYouContent" => "HTMLText",
16
        "WelcomeTitle" => "Varchar(255)",
17
        "WelcomeContent" => "HTMLText",
18
        "TitleLoggedIn" => "Varchar(255)",
19
        "MenuTitleLoggedIn" => "Varchar(255)",
20
        "ContentLoggedIn" => "HTMLText",
21
        "ErrorEmailAddressAlreadyExists" => "Varchar(255)",
22
        "ErrorBadEmail" => "Varchar(255)",
23
        "ErrorPasswordDoNotMatch" => "Varchar(255)",
24
        "ErrorMustSupplyPassword" => "Varchar(255)"
25
    );
26
27
    private static $register_group_title = "Registered users";
28
29
    private static $register_group_code = "registrations";
30
31
    private static $register_group_access_key = "REGISTRATIONS";
32
33
    protected function showLoggedInFields()
34
    {
35
        if (!$this->isCMSRead() && Member::currentUser()) {
36
            return true;
37
        }
38
    }
39
40
    protected function isCMSRead()
41
    {
42
        return $this->isCMS || Controller::curr()->getRequest()->param("URLSegment") == "admin";
43
    }
44
45
    /**
46
     * Returns a link to this page that will, on completion,
47
     * redirect back to the another page
48
     *@param String - $link
49
     *@return String - $link
50
     **/
0 ignored issues
show
Documentation introduced by
Should the return type not be string|null?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
51
52
    public function link_for_going_to_page_via_making_user($link)
53
    {
54
        $registerAndEditDetailsPage = RegisterAndEditDetailsPage::get()->first();
55
        if ($registerAndEditDetailsPage) {
56
            return $registerAndEditDetailsPage->Link()."?BackURL=".urlencode($link);
57
        }
58
    }
59
60
    public function getCMSFields()
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
61
    {
62
        $fields = parent::getCMSFields();
63
        $this->isCMS = true;
64
        $fields->addFieldToTab('Root.LoggedIn', new TextField('TitleLoggedIn', 'Title when user is Logged In'));
65
        $fields->addFieldToTab('Root.LoggedIn', new TextField('MenuTitleLoggedIn', 'Navigation Label when user is Logged In'));
66
        $fields->addFieldToTab('Root.Welcome', new TextField('WelcomeTitle', 'Welcome Title (afer user creates an account)'));
67
        $fields->addFieldToTab('Root.Welcome', new HtmlEditorField('WelcomeContent', 'Welcome message (afer user creates an account)'));
68
        $fields->addFieldToTab('Root.UpdatingDetails', new TextField('ThankYouTitle', 'Thank you Title (afer user updates their details)'));
69
        $fields->addFieldToTab('Root.UpdatingDetails', new HtmlEditorField('ThankYouContent', 'Thank you message (afer user updates their details)'));
70
        $fields->addFieldToTab('Root.LoggedIn', new HtmlEditorField('ContentLoggedIn', 'Content when user is Logged In'));
71
        $fields->addFieldToTab('Root.ErrorMessages', new TextField('ErrorEmailAddressAlreadyExists', 'Error shown when email address is already registered'));
72
        $fields->addFieldToTab('Root.ErrorMessages', new TextField('ErrorBadEmail', 'Bad email'));
73
        $fields->addFieldToTab('Root.ErrorMessages', new TextField('ErrorPasswordDoNotMatch', 'Error shown when passwords do not match'));
74
        $fields->addFieldToTab('Root.ErrorMessages', new TextField('ErrorMustSupplyPassword', 'Error shown when new user does not supply password'));
75
        return $fields;
76
    }
77
78
    public function canCreate($member = null)
79
    {
80
        return RegisterAndEditDetailsPage::get()->count() ? false : true;
81
    }
82
83
    public function requireDefaultRecords()
84
    {
85
        parent::requireDefaultRecords();
86
        $bt = defined('DB::USE_ANSI_SQL') ? "\"" : "`";
87
        $update = array();
88
        $group = Group::get()
89
            ->filter(array("Code" => self::$register_group_code))->first();
90
        if (!$group) {
91
            $group = new Group();
92
            $group->Code = self::$register_group_code;
93
            $group->Title = self::$register_group_title;
94
            $group->write();
95
            Permission::grant($group->ID, self::$register_group_access_key);
96
            DB::alteration_message("GROUP: ".self::$register_group_code.' ('.self::$register_group_title.')', "created");
97
        } elseif (DB::query("SELECT * FROM Permission WHERE {$bt}GroupID{$bt} = ".$group->ID." AND {$bt}Code{$bt} = '".self::$register_group_access_key."'")->numRecords() == 0) {
98
            Permission::grant($group->ID, self::$register_group_access_key);
99
        }
100
        $page = RegisterAndEditDetailsPage::get()->first();
101
        if (!$page) {
102
            $page = new RegisterAndEditDetailsPage();
103
            $page->Title = "Register";
104
            $page->URLSegment = "register";
105
            $page->MenuTitle = "Register";
106
            $update[] = "created RegisterAndEditDetailsPage";
107
        }
108
        if ($page) {
109
110
            //REGISTER
111
            if (strlen($page->Content) < 17) {
112
                $page->Content = "<p>Please log in or register here.</p>";
113
                $update[] =  "updated Content";
114
            }
115
116
            //WELCOME !
117
            if (!$page->WelcomeTitle) {
118
                $page->WelcomeTitle = "Thank you for registering";
119
                $update[] =  "updated WelcomeTitle";
120
            }
121
            if (strlen($page->WelcomeContent) < 17) {
122
                $page->WelcomeContent = "<p>Thank you for registration. Please make sure to remember your username and password.</p>";
123
                $update[] =  "updated WelcomeContent";
124
            }
125
126
            // WELCOME BACK
127
            if (!$page->TitleLoggedIn) {
128
                $page->TitleLoggedIn = "Welcome back";
129
                $update[] =  "updated TitleLoggedIn";
130
            }
131
            if (!$page->MenuTitleLoggedIn) {
132
                $page->MenuTitleLoggedIn = "Welcome back";
133
                $update[] =  "updated MenuTitleLoggedIn";
134
            }
135
            if (strlen($page->ContentLoggedIn) < 17) {
136
                $page->ContentLoggedIn = "<p>Welcome back - you can do the following ....</p>";
137
                $update[] =  "updated ContentLoggedIn";
138
            }
139
140
            //THANK YOU FOR UPDATING
141
            if (!$page->ThankYouTitle) {
142
                $page->ThankYouTitle = "Thank you for updating your details";
143
                $update[] =  "updated ThankYouTitle";
144
            }
145
            if (strlen($page->ThankYouContent) < 17) {
146
                $page->ThankYouContent = "<p>Thank you for updating your details. </p>";
147
                $update[] =  "updated ThankYouContent";
148
            }
149
150
            //ERRORS!
151
            if (!$page->ErrorEmailAddressAlreadyExists) {
152
                $page->ErrorEmailAddressAlreadyExists = "Sorry, that email address is already in use by someone else. You may have setup an account in the past or mistyped your email address.";
153
                $update[] =  "updated ErrorEmailAddressAlreadyExists";
154
            }
155
            if (!$page->ErrorBadEmail) {
156
                $page->ErrorBadEmail = "Sorry, that does not appear a valid email address.";
157
                $update[] =  "updated ErrorBadEmail";
158
            }
159
            if (!$page->ErrorPasswordDoNotMatch) {
160
                $page->ErrorPasswordDoNotMatch = "Your passwords do not match. Please try again.";
161
                $update[] =  "updated ErrorPasswordDoNotMatch";
162
            }
163
            if (!$page->ErrorMustSupplyPassword) {
164
                $page->ErrorMustSupplyPassword = "Your must supply a password.";
165
                $update[] =  "updated ErrorMustSupplyPassword";
166
            }
167
            if (count($update)) {
168
                $page->writeToStage('Stage');
169
                $page->publish('Stage', 'Live');
170
                DB::alteration_message($page->ClassName." created/updated: <ul><li>".implode("</li><li>", $update)."</li></ul>", 'created');
171
            }
172
        }
173
    }
174
}
175
176
class RegisterAndEditDetailsPage_Controller extends Page_Controller
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class should be in its own file to aid autoloaders.

Having each class in a dedicated file usually plays nice with PSR autoloaders and is therefore a well established practice. If you use other autoloaders, you might not want to follow this rule.

Loading history...
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
177
{
178
    private static $fields_to_remove = array("Locale","DateFormat", "TimeFormat");
179
180
181
    private static $required_fields = array("FirstName","Email");
182
183
184
    private static $minutes_before_member_is_not_new_anymore = 30;
0 ignored issues
show
Unused Code introduced by
The property $minutes_before_member_is_not_new_anymore is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
185
186
    public function init()
187
    {
188
        parent::init();
189
        if ($this->showLoggedInFields()) {
190
            $field = "TitleLoggedIn";
191
        } else {
192
            $field = "Title";
193
        }
194
        $this->Title = $this->getField($field);
195
        if ($this->showLoggedInFields()) {
196
            $field = "MenuTitleLoggedIn";
197
        } else {
198
            $field = "MenuTitle";
199
        }
200
        $this->MenuTitle =  $this->getField($field);
201
        if ($this->showLoggedInFields()) {
202
            $field = "ContentLoggedIn";
203
        } else {
204
            $field = "Content";
205
        }
206
        $this->Content =  $this->getField($field);
207
    }
208
209
    public function index()
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
210
    {
211
        if (Director::is_ajax()) {
212
            return $this->renderWith(array("RegisterAndEditDetailsPageAjax", "RegisterAndEditDetailsPage"));
213
        }
214
        return array();
215
    }
216
217
    public function Form()
0 ignored issues
show
Coding Style introduced by
Form uses the super-global variable $_REQUEST which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
218
    {
219
        if (isset($_REQUEST["BackURL"])) {
220
            Session::set('BackURL', $_REQUEST["BackURL"]);
221
        }
222
        $member = Member::currentUser();
223
        $fields = new FieldList();
224
225
        $passwordField = null;
226
        if ($member) {
227
            $name = $member->getName();
0 ignored issues
show
Unused Code introduced by
$name 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...
228
            //if($member && $member->Password != '') {$passwordField->setCanBeEmpty(true);}
0 ignored issues
show
Unused Code Comprehensibility introduced by
68% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
229
            $action = new FormAction("submit", "Update your details");
230
            $action->addExtraClass("updateButton");
231
            $actions = new FieldList($action);
232
        } else {
233
            $passwordField = new ConfirmedPasswordField("Password", "Password");
234
            $action = new FormAction("submit", "Register");
235
            $action->addExtraClass("registerButton");
236
            $actions = new FieldList($action);
237
            $member = new Member();
238
        }
239
        $memberFormFields = $member->getMemberFormFields();
240
241
        if ($memberFormFields) {
242
            if (is_array(self::$fields_to_remove) && count(self::$fields_to_remove)) {
243
                foreach (self::$fields_to_remove as $fieldName) {
244
                    $memberFormFields->removeByName($fieldName);
245
                }
246
            }
247
            $fields->merge($memberFormFields);
248
        }
249
        if ($passwordField) {
250
            $fields->push($passwordField);
251
        }
252
        foreach (self::$required_fields as $fieldName) {
253
            $fields->fieldByName($fieldName)->addExtraClass("RequiredField");
254
        }
255
        $requiredFields = new RequiredFields(self::$required_fields);
256
        $form = new Form($this, "Form", $fields, $actions, $requiredFields);
257
        // Load any data avaliable into the form.
258
        if ($member) {
259
            $member->Password = null;
260
            $form->loadDataFrom($member);
261
        }
262
        $data = Session::get("FormInfo.Form_Form.data");
263
        if (is_array($data)) {
264
            $form->loadDataFrom($data);
265
        }
266
267
        // Optional spam protection
268
        if (class_exists('SpamProtectorManager')) {
269
            SpamProtectorManager::update_form($form);
270
        }
271
        if (!isset($_REQUEST["Password"])) {
272
            $form->fields()->fieldByName("Password")->SetValue("");
273
        }
274
        return $form;
275
    }
276
277
278
    /**
279
     * Save the changes to the form
280
     */
281
    public function submit($data, $form)
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
Coding Style introduced by
submit uses the super-global variable $_REQUEST which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
282
    {
283
        $bt = defined('DB::USE_ANSI_SQL') ? "\"" : "`";
0 ignored issues
show
Unused Code introduced by
$bt 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...
284
        $member = Member::currentUser();
285
        $newMember = false;
286
        Session::set("FormInfo.Form_Form.data", $data);
287
        $emailField = new EmailField("Email");
288
        $emailField->setValue($data["Email"]);
289
        if ($emailField) {
290
            if (!$emailField->validate($form->validator)) {
291
                $form->addErrorMessage("Blurb", $this->ErrorBadEmail, "bad");
292
                $this->redirectBack();
293
                return;
294
            }
295
        }
296
        if (!$member) {
297
            $newMember = true;
298
            $member = Object::create('Member');
299
            $form->sessionMessage($this->WelcomeTitle, 'good');
300
            $id = 0;
301
        } else {
302
            $form->sessionMessage($this->ThankYouTitle, 'good');
303
            $id = $member->ID;
304
        }
305
306
        //validation
307
        if ($existingMember = Member::get()->filter(array("Email" => Convert::raw2sql($data['Email'])))->exclude(array("ID" => $id))->first()) {
0 ignored issues
show
Unused Code introduced by
$existingMember 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...
308
            $form->addErrorMessage("Blurb", $this->ErrorEmailAddressAlreadyExists, "bad");
309
            return $this->redirectBack();
310
        }
311
        // check password fields are the same before saving
312
        if ($data["Password"]["_Password"] != $data["Password"]["_ConfirmPassword"]) {
313
            $form->addErrorMessage("Password", $this->ErrorPasswordDoNotMatch, "bad");
314
            return $this->redirectBack();
315
        }
316
317
        if (!$id && !$data["Password"]["_Password"]) {
318
            $form->addErrorMessage("Password", $this->ErrorMustSupplyPassword, "bad");
319
            return $this->redirectBack();
320
        }
321
        $password = $member->Password;
322
        if (isset($data["Password"]["Password"]) && strlen($data["Password"]["Password"]) > 3) {
323
            $password = $data["Password"]["Password"];
324
        }
325
        $form->saveInto($member);
326
        $member->changePassword($password);
327
        $member->write();
0 ignored issues
show
Bug introduced by
The method write does only exist in DataObject, but not in RegisterAndEditDetailsPage_Controller.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
328
        if ($newMember) {
329
            $form->saveInto($member);
330
            $member->write();
331
        }
332
        //adding to group
333
        $group = Group::get()
334
            ->filter(array("Code" => self::$register_group_code))
335
            ->first();
336
        if ($group) {
337
            $member->Groups()->add($group);
338
        }
339
        if ($newMember) {
340
            $member->logIn();
341
            $link = ContentController::join_links($this->Link(), 'welcome');
342
        } else {
343
            $link = ContentController::join_links($this->Link(), 'thanks');
344
        }
345 View Code Duplication
        if (!isset($_REQUEST["BackURL"]) && Session::get('BackURL')) {
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...
346
            $_REQUEST["BackURL"] = Session::get('BackURL');
347
        }
348 View Code Duplication
        if (isset($_REQUEST["BackURL"])) {
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...
349
            $link = urldecode($_REQUEST["BackURL"]);
350
            Session::set('BackURL', '');
351
        }
352
        if ($link) {
353
            return $this->redirect($link);
354
        }
355
        return array();
356
    }
357
358
    public function thanks()
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
359
    {
360
        $member = Member::currentUser();
361
        if (!$member) {
362
            return $this->redirect($this->Link());
363
        }
364
        if ($this->numberOfMinutesMemberIsListed($member) < self::get_minutes_before_member_is_not_new_anymore()) {
365
            $this->Title = $this->WelcomeTitle;
366
            $this->Content = $this->WelcomeContent;
367
        } else {
368
            $this->Title = $this->ThankYouTitle;
369
            $this->Content = $this->ThankYouContent;
370
        }
371
        return array();
372
    }
373
374
    public function welcome()
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
375
    {
376
        if (!Member::currentUser()) {
377
            return $this->redirect($this->Link());
378
        }
379
        $this->Title = $this->WelcomeTitle;
380
        $this->Content = $this->WelcomeContent;
381
        return array();
382
    }
383
384
    public function numberOfMinutesMemberIsListed($member)
385
    {
386
        if ($member) {
387
            $timestamp = strtotime(strval($member->Created));
388
            $nowTimestamp = time();
389
            return ($nowTimestamp - $timestamp) / 60;
390
        }
391
        return 0;
392
    }
393
}
394