HideMailto_Controller::makeMailtoString()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 10
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 7
nc 2
nop 3
1
<?php
2
3
4
class HideMailto extends SiteTreeExtension
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...
5
{
6
    private static $email_field = "Email";
7
8
    private static $default_subject = "enquiry";
9
10
    private static $replace_characters = array(
0 ignored issues
show
Unused Code introduced by
The property $replace_characters 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...
11
        "." => "&#x2e;",
12
        "@" => "&#x40;",
13
        "a" => "&#x61;",
14
        "b" => "&#x62;",
15
        "c" => "&#x63;",
16
        "d" => "&#x64;",
17
        "e" => "&#x65;",
18
        "f" => "&#x66;",
19
        "g" => "&#x67;",
20
        "h" => "&#x68;",
21
        "i" => "&#x69;"
22
    );
23
24
    /**
25
     *
26
     * @param String $email
27
     * @param String $subject
28
     * @return Obj (MailTo, Text, Original, Subject)
0 ignored issues
show
Documentation introduced by
Should the return type not be ViewableData?

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...
29
     */
30
    public static function convert_email($email, $subject = '')
31
    {
32
        $obj = new ViewableData();
33
        if (!$subject) {
34
            $subject = self::$default_subject;
35
        }
36
        //mailto part
37
        $mailTo = "mailto:".$email."?subject=".Convert::raw2mailto($subject);
38
        $mailToConverted = self::string_encoder($mailTo);
39
        $convertedEmail = self::string_encoder($email);
40
        $obj->MailTo = $mailToConverted;
41
        $obj->Text = $convertedEmail;
42
        $obj->Original = $email;
43
        $obj->Subject = $subject;
44
        //$obj->OnClick = "jQuery(this).attr('href', HideMailto2Email('".self::get_dot_replacer()."', '".$array[0]."', '".$array[1]."', '".Convert::raw2mailto($subject)."')); return true;";
0 ignored issues
show
Unused Code Comprehensibility introduced by
62% 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...
45
        //TO DO: add a JS function that puts the
46
        Requirements::javascript(THIRDPARTY_DIR."/jquery/jquery.js");
47
        //Requirements::javascript("hidemailto/javascript/HideMailto2Email.js");
0 ignored issues
show
Unused Code Comprehensibility introduced by
72% 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...
48
        return $obj;
49
    }
50
51
52
    /**
53
     * encodes a string - randomly
54
     * @param String $string
55
     * @return String
56
     */
57
    private static function string_encoder($string)
58
    {
59
        $encodedString = '';
60
        $nowCodeString = '';
0 ignored issues
show
Unused Code introduced by
$nowCodeString 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...
61
        $originalLength = strlen($string);
62
        for ($i = 0; $i < $originalLength; $i++) {
63
            $encodeMode = rand(1, 2);
64
            switch ($encodeMode) {
65
                case 1: // Decimal code
66
                    $nowCodeString = '&#' . ord($string[$i]) . ';';
67
                    break;
68
                case 2: // Hexadecimal code
69
                    $nowCodeString = '&#x' . dechex(ord($string[$i])) . ';';
70
                    break;
71
                default:
72
                    return 'ERROR: wrong encoding mode.';
73
            }
74
            $encodedString .= $nowCodeString;
75
        }
76
        return $encodedString;
77
    }
78
79
    public function HideMailToObject()
80
    {
81
        if ($email = $this->getHiddenEmailData()) {
82
            $obj = self::convert_email($email);
83
            return $obj;
84
        }
85
    }
86
87
    private function getHiddenEmailData()
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...
88
    {
89
        if ($field = self::$email_field) {
90
            if ($email = $this->owner->$field) {
91
                return $this->isEmail($email);
92
            }
93
        }
94
    }
95
96
    private function isEmail($email)
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...
97
    {
98
        if (!preg_match("/^([A-Za-z0-9._-])+\@(([A-Za-z0-9-])+\.)+([A-Za-z0-9])+$/", trim($email))) {
99
            return "";
100
        } else {
101
            return $email;
102
        }
103
    }
104
}
105
106
class HideMailto_Role extends DataExtension
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...
107
{
108
109
    //member link
110
111
    public function HideMailtoLink()
112
    {
113
        return "mailto/" . $this->owner->ID;
114
    }
115
}
116
117
/**
118
 * Generates obfusticated links, and also holds the method called when /mailto/
119
 * is called via the URL. As noted above, take a look at the _config.php file to
120
 * see how mailto/ maps to this class.
121
 */
122
class HideMailto_Controller extends ContentController
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...
123
{
124
    /**
125
     * The list of allowed domains to create a mailto: link to. By default, allow
126
     * all domains.
127
     *
128
     * TODO Maybe the default should be to allow the current domain only?
129
     */
130
    private static $allowed_domains = '*';
131
132
    public function __construct($dataRecord = null)
133
    {
134
        parent::__construct($dataRecord);
135
        return $this->index();
0 ignored issues
show
Bug introduced by
Constructors do not have meaningful return values, anything that is returned from here is discarded. Are you sure this is correct?
Loading history...
136
    }
137
138
    public function defaultAction($action)
139
    {
140
        return $this->index();
141
    }
142
143
    public $url = '';
144
145
    /**
146
     * This is called by default when this controller is executed.
147
     */
148
    public function index()
149
    {
150
        $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...
151
        $user = '';
152
        $domain = '';
153
        $subject = '';
0 ignored issues
show
Unused Code introduced by
$subject 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...
154
        // We have two situations to deal with, where urlParams['Action'] is an int (assume Member ID), or a string (assume username)
155
        if (is_numeric($this->getRequest()->param('Name'))) {
156
            // Action is numeric, assume it's a member ID and optional ID is the email subject
157
            $member = Member::get()->byID($this->getRequest()->param('Name'));
158
            if (!$member) {
159
                user_error("No member found with ID #" . $this->getRequest()->param('Name'), E_USER_ERROR); // No member found with this ID, perhaps we could redirect a user back instead of giving them a 500 error?
160
            }
161
            list($user, $domain) = explode('@', $member->Email);
162
            $subject = $this->getRequest()->param('ID');
163
        } else {
164
            // Action is not numeric, assume that Action is the username, ID is the domain and optional OtherID is the email subject
165
            $user = urldecode($this->getRequest()->param('Name'));
166
            $domain = urldecode($this->getRequest()->param('URL'));
167
            $subject = $this->getRequest()->param('Subject');
168
        }
169
        $emailString = "mailto: $user@$domain?subject=".$subject;
170
        // Make sure the domain is in the allowed domains
171
        if ((is_string(self::$allowed_domains) && self::$allowed_domains == '*') || in_array($domain, self::$allowed_domains)) {
172
            // Create the redirect
173
            header("Location: " . $emailString);
174
            header("Refresh: 0; url=". $emailString);
175
            echo $this->customise(array("RedirectBackURL" => $this->RedirectBackURL(), "Email" => $this->makeMailtoString($user, $domain, $subject)))->renderWith("HideMailto");
176
            $emailString = $this->makeMailtoString($user, $domain, $subject);
0 ignored issues
show
Unused Code introduced by
$emailString 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...
177
        } else {
178
            user_error("We're not allowed to redirect to the domain '$domain', because it's not listed in the _config.php file", E_USER_ERROR);
179
        }
180
    }
181
182
    public function RedirectBackURL()
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
RedirectBackURL uses the super-global variable $_SERVER 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...
183
    {
184
        if (isset($_SERVER['HTTP_REFERER'])) {
185
            $this->redirectBackURL = $_SERVER['HTTP_REFERER'];
0 ignored issues
show
Documentation introduced by
The property redirectBackURL does not exist on object<HideMailto_Controller>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
186
        }
187
        if (!$this->redirectBackURL) {
0 ignored issues
show
Documentation introduced by
The property redirectBackURL does not exist on object<HideMailto_Controller>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
188
            $this->redirectBackURL = Director::absoluteBaseURL();
0 ignored issues
show
Documentation introduced by
The property redirectBackURL does not exist on object<HideMailto_Controller>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
189
        }
190
        return $this->redirectBackURL;
0 ignored issues
show
Documentation introduced by
The property redirectBackURL does not exist on object<HideMailto_Controller>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
191
    }
192
193
194
    protected function makeMailtoString($user, $domain, $subject = '')
195
    {
196
        $target = 'mailto:' . $user . '@' . $domain;
197
        if ($subject) {
198
            $target .= '?subject=' . Convert::raw2mailto($subject);
199
        }
200
        $target = str_replace(".", "&x2e;", $target);
201
        $target = str_replace("@", "&x40;", $target);
202
        return $target;
203
    }
204
}
205