Issues (27)

Security Analysis    not enabled

This project does not seem to handle request data directly as such no vulnerable execution paths were found.

  Cross-Site Scripting
Cross-Site Scripting enables an attacker to inject code into the response of a web-request that is viewed by other users. It can for example be used to bypass access controls, or even to take over other users' accounts.
  File Exposure
File Exposure allows an attacker to gain access to local files that he should not be able to access. These files can for example include database credentials, or other configuration files.
  File Manipulation
File Manipulation enables an attacker to write custom data to files. This potentially leads to injection of arbitrary code on the server.
  Object Injection
Object Injection enables an attacker to inject an object into PHP code, and can lead to arbitrary code execution, file exposure, or file manipulation attacks.
  Code Injection
Code Injection enables an attacker to execute arbitrary code on the server.
  Response Splitting
Response Splitting can be used to send arbitrary responses.
  File Inclusion
File Inclusion enables an attacker to inject custom files into PHP's file loading mechanism, either explicitly passed to include, or for example via PHP's auto-loading mechanism.
  Command Injection
Command Injection enables an attacker to inject a shell command that is execute with the privileges of the web-server. This can be used to expose sensitive data, or gain access of your server.
  SQL Injection
SQL Injection enables an attacker to execute arbitrary SQL code on your database server gaining access to user data, or manipulating user data.
  XPath Injection
XPath Injection enables an attacker to modify the parts of XML document that are read. If that XML document is for example used for authentication, this can lead to further vulnerabilities similar to SQL Injection.
  LDAP Injection
LDAP Injection enables an attacker to inject LDAP statements potentially granting permission to run unauthorized queries, or modify content inside the LDAP tree.
  Header Injection
  Other Vulnerability
This category comprises other attack vectors such as manipulating the PHP runtime, loading custom extensions, freezing the runtime, or similar.
  Regex Injection
Regex Injection enables an attacker to execute arbitrary code in your PHP process.
  XML Injection
XML Injection enables an attacker to read files on your local filesystem including configuration files, or can be abused to freeze your web-server process.
  Variable Injection
Variable Injection enables an attacker to overwrite program variables with custom data, and can lead to further vulnerabilities.
Unfortunately, the security analysis is currently not available for your project. If you are a non-commercial open-source project, please contact support to gain access.

code/SimpleDateField.php (25 issues)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
3
/**
4
 * @author nicolaas [at] sunnysideup.co.nz
5
 * To Do:
6
 * 1. write documenation
7
 * 2. change $config into NON-static
8
 */
9
10
11
class SimpleDateField extends DateField
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...
12
{
13
14
    /**
15
     * Americans should set this to TRUE.
16
     * For people who write
17
     * 10-Nov-2012, to mean 10 November, you an leave it as FALSE
18
     * For sites with customers from all over, you will have to tell them the
19
     * preferred format. You can use the placeholder value for this.
20
     *
21
     * @var Boolean
22
     */
23
    private static $month_before_day = false;
0 ignored issues
show
The property $month_before_day 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...
24
25
    /**
26
     * The PHP date function formatting for showing the final date.
27
     * @var String
28
     */
29
    private static $default_fancy_date_format = 'j F Y';
0 ignored issues
show
The property $default_fancy_date_format 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...
30
31
    /**
32
     * What would you like the place holder value to be?
33
     * @var String
34
     */
35
    private static $placeholder_value = '31 jan 2123';
0 ignored issues
show
The property $placeholder_value 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...
36
37
    public function __construct($name, $title = null, $value = null, $form = null, $config = array())
0 ignored issues
show
The parameter $config is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
38
    {
39
        parent::__construct($name, $title, $value, $form);
0 ignored issues
show
The call to DateField::__construct() has too many arguments starting with $form.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
40
        $this->setConfig("dmyfields", false);
41
        $this->setConfig("showcalendar", false);
42
    }
43
44
    public function Field($options = array())
45
    {
46
        //GENERAL
47
        Requirements::javascript(THIRDPARTY_DIR . '/jquery/jquery.js');
48
        Requirements::javascript("datefield_simplified/javascript/SimpleDateField.js");
49
        $this->addExtraClass("simpledatefield");
50
        $this->setAttribute("placeholder", $this->Config()->get("placeholder_value"));
51
        $html = parent::Field($options);
52
        $fieldID = $this->id();
53
        $url = Convert::raw2js(Director::absoluteBaseURL().Config::inst()->get("SimpleDateField_Controller", "url")."/ajaxvalidation/");
54
        $objectID = $fieldID."_OBJECT";
55
        Requirements::customScript(
56
            "
57
			var $objectID = new SimpleDateFieldAjaxValidationAPI('".$fieldID."');
58
			$objectID.init();
59
			$objectID.setVar('url', '$url');
60
			",
61
            'func_SimpleDateField'.$fieldID
62
        );
63
        return $html;
64
    }
65
66
    /**
67
     * Sets the internal value to ISO date format.
68
     *
69
     * @param String|Array $val
70
     */
71
    public function setValue($val)
72
    {
73
        $date = $this->ConvertToTSorERROR($val);
0 ignored issues
show
It seems like $val defined by parameter $val on line 71 can also be of type array; however, SimpleDateField::ConvertToTSorERROR() does only seem to accept string, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
74
        if (is_numeric($date)  && intval($date) == $date && $date > 0) {
75
            $val = date("Y-m-d", $date);
76
        } else {
77
            $val = null;
78
        }
79
        return parent::setValue($val);
80
    }
81
82
83
    /**
84
     * changes the raw input into TimeStamp Date OR ERROR String
85
     *
86
     * @param String $rawInput
87
     *
88
     * @return Int | String
0 ignored issues
show
Should the return type not be integer|double|string?

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...
89
     *
90
     */
91
    public function ConvertToTSorERROR($rawInput)
92
    {
93
        $settings = $this->getConfig();
94
        if (!isset($settings['dateformat'])) {
95
            $settings['dateformat'] = $this->Config()->get("default_fancy_date_format");
96
        }
97
        $tsOrError = null;
98
        if ($this->Config()->get("month_before_day")) {
99
            $cleanedInput = str_replace("-", "/", $rawInput);
100
        } else {
101
            $cleanedInput = str_replace("/", "-", $rawInput);
102
        }
103
        if ($cleanedInput) {
104
            $tsOrError = intval(strtotime($cleanedInput));
105
        }
106
        if (is_numeric($tsOrError) && $tsOrError > 0) {
107 View Code Duplication
            if (isset($settings['min']) && $minDate = $settings['min']) {
0 ignored issues
show
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...
108
                $minDate = strtotime($minDate);
109
                if ($minDate) {
110
                    if ($minDate > $tsOrError) {
111
                        $tsOrError = sprintf(_t('SimpleDateField.VALIDDATEMINDATE', "Your date can not be before %s."), date($settings['dateformat'], $minDate));
112
                    }
113
                }
114
            }
115 View Code Duplication
            if (isset($settings['max']) && $maxDate = $settings['max']) {
0 ignored issues
show
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...
116
                // ISO or strtotime()
0 ignored issues
show
Unused Code Comprehensibility introduced by
38% 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...
117
                $maxDate = strtotime($maxDate);
118
                if ($maxDate) {
119
                    if ($maxDate < $tsOrError) {
120
                        $tsOrError = sprintf(_t('SimpleDateField.VALIDDATEMAXDATE', "Your date can not be after %s."), date($settings['dateformat'], $maxDate));
121
                    }
122
                }
123
            }
124
        }
125
        if (!$tsOrError) {
126
            if (!trim($rawInput)) {
127
                $tsOrError = sprintf(_t('SimpleDateField.VALIDDATEDATE_NOENTRY', "You need to enter a date."), $rawInput);
128
            } else {
129
                $tsOrError = sprintf(_t('SimpleDateField.VALIDDATEDATE_CANTMAKEDATE', "We did not understand the date you entered '%s'."), $rawInput);
130
            }
131
        }
132
        return $tsOrError;
133
    }
134
135
    /**
136
     * Turns user input into a formatted Date or an Error Message ...
137
     *
138
     * @param String $rawInput
139
     * @return String
140
     */
141
    public function ConverToFancyDate($rawInput)
142
    {
143
        $settings = $this->getConfig();
0 ignored issues
show
$settings 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...
144
        $tsOrError = $this->ConvertToTSorERROR($rawInput);
145
        if (is_numeric($tsOrError) && intval($tsOrError)) {
146
            $array = array(
147
                "value" => date($this->Config()->get("default_fancy_date_format"), $tsOrError),
148
                "success" => 1
149
            );
150
        } else {
151
            $array = array(
152
                "value" =>  $tsOrError,
153
                "success" => 0
154
            );
155
        }
156
        return Convert::raw2json($array);
157
    }
158
}
159
160
161
class SimpleDateField_Controller extends 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...
162
{
163
    private static $allowed_actions = array(
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
The property $allowed_actions 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...
164
        "ajaxvalidation" => true
165
    );
166
167
    private static $url = 'formfields-simpledatefield';
0 ignored issues
show
The property $url 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...
168
169
    /**
170
     *
171
     * @param HTTPRequest
172
     * @return String (JSON)
173
     */
174
    public function ajaxvalidation($request)
0 ignored issues
show
The parameter $request is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
ajaxvalidation uses the super-global variable $_GET 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...
175
    {
176
        $rawInput = '';
177
        if (isset($_GET["value"])) {
178
            $rawInput = ($_GET["value"]);
179
        }
180
        $obj = Injector::inst()->get("SimpleDateField", $asSingleton = true, array("temp", "temp"));
181
        return $obj->ConverToFancyDate($rawInput);
182
    }
183
}
184
185
186
class SimpleDateField_Editable extends EditableFormField
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...
187
{
188
    private static $db = array(
0 ignored issues
show
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...
189
        "ShowCalendar" => "Boolean",
190
        "OnlyPastDates" => "Boolean",
191
        "OnlyFutureDates" => "Boolean",
192
        "MonthBeforeDay" => "Boolean",
193
        "ExplanationForEnteringDates" => "Varchar(120)"
194
    );
195
196
    private static $singular_name = 'Simple Date Field';
0 ignored issues
show
The property $singular_name 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...
197
198
    private static $plural_name = 'Simple Date Fields';
0 ignored issues
show
The property $plural_name 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...
199
200
    public function Icon()
201
    {
202
        return 'userforms/images/editabledatefield.png';
203
    }
204
205
    public function canEdit($member = null)
206
    {
207
        return true;
208
    }
209
210
    public function getFieldConfiguration()
0 ignored issues
show
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...
211
    {
212
        $fields = parent::getFieldConfiguration();
213
        // eventually replace hard-coded "Fields"?
214
        $baseName = "Fields[$this->ID]";
215
        $ShowCalendar = ($this->getSetting('ShowCalendar')) ? $this->getSetting('ShowCalendar') : '0';
216
        $OnlyPastDates = ($this->getSetting('OnlyPastDates')) ? $this->getSetting('OnlyPastDates') : '0';
217
        $OnlyFutureDates = ($this->getSetting('OnlyFutureDates')) ? $this->getSetting('OnlyFutureDates') : '0';
218
        $MonthBeforeDay = ($this->getSetting('MonthBeforeDay')) ? $this->getSetting('MonthBeforeDay') : '0';
219
        $ExplanationForEnteringDates = ($this->getSetting('ExplanationForEnteringDates')) ? $this->getSetting('ExplanationForEnteringDates') : '';
220
        $extraFields = new FieldList(
221
            new FieldGroup(
222
                _t('SimpleDateField_Editable.DATESETTINGS', 'Date Settings'),
223
                new CheckboxField($baseName . "[CustomSettings][ShowCalendar]", "Show Calendar", $ShowCalendar),
224
                new CheckboxField($baseName . "[CustomSettings][OnlyPastDates]", "Only Past Dates?", $OnlyPastDates),
225
                new CheckboxField($baseName . "[CustomSettings][OnlyFutureDates]", "Only Future Dates?", $OnlyFutureDates),
226
                new CheckboxField($baseName . "[CustomSettings][MonthBeforeDay]", "Month before day (e.g. Jan 11 2011)?", $MonthBeforeDay),
227
                new TextField($baseName . "[CustomSettings][ExplanationForEnteringDates]", "Explanation for entering dates", $ExplanationForEnteringDates)
228
            )
229
        );
230
        $fields->merge($extraFields);
231
        return $fields;
232
    }
233
234
    public function getFormField()
235
    {
236
        $field = new SimpleDateField($this->Name, $this->Title);
237
        if ($this->getSetting('ShowCalendar')) {
238
            $field->setConfig("showcalendar", true);
239
        }
240
        if ($this->getSetting('OnlyPastDates')) {
241
            $field->setConfig("max", "today");
242
            Config::inst()->update("SimpleDateField", "placeholder_value", '31 jan 1974');
243
        } elseif ($this->getSetting('OnlyFutureDates')) {
244
            $field->setConfig("min", "today");
245
            Config::inst()->update("SimpleDateField", "placeholder_value", '31 jan 2023');
246
        }
247
        if ($this->getSetting('MonthBeforeDay')) {
248
            $field->setConfig("dateformat", 'l F j Y');
249
            Config::inst()->update("SimpleDateField", "default_fancy_date_format", 'l F j Y');
250
            Config::inst()->update("SimpleDateField", "month_before_day", true);
251
        } else {
252
            Config::inst()->update("SimpleDateField", "default_fancy_date_format", 'l j F Y');
253
            Config::inst()->update("SimpleDateField", "month_before_day", false);
254
        }
255
        if ($this->getSetting('ExplanationForEnteringDates')) {
256
            $field->setRightTitle($this->getSetting('ExplanationForEnteringDates'));
257
        }
258
        return $field;
259
    }
260
}
261