Issues (23)

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/MenuCache.php (19 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
class MenuCache extends DataExtension
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...
4
{
5
    /**
6
    * fields are typicall header, menu, footer
7
    */
8
9
    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...
10
        "CachedSection0" => "HTMLText",
11
        "CachedSection1" => "HTMLText",
12
        "CachedSection2" => "HTMLText",
13
        "CachedSection3" => "HTMLText",
14
        "CachedSection4" => "HTMLText"
15
    );
16
17
    private static $fields = array(
18
        0 => "Header",
19
        1 => "Menu",
20
        2 => "Footer",
21
        3 => "LayoutSection",
22
        4 => "other",
23
    );
24
25
    /* sets the cache number used for getting the "$Layout" of the individual page */
26
    private static $layout_field = 3;
0 ignored issues
show
The property $layout_field 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...
27
28
    private static $tables_to_clear = array("SiteTree", "SiteTree_Live", "SiteTree_versions");
0 ignored issues
show
The property $tables_to_clear 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...
29
30
    public static function field_maker($fieldNumber)
31
    {
32
        return "CachedSection".$fieldNumber;
33
    }
34
35
    public static function fields_exists($number)
36
    {
37
        return (isset(self::$fields[$number]));
38
    }
39
40
    public function updateCMSFields(FieldList $fields)
41
    {
42
        $fields->addFieldToTab("Root.Caching", new CheckboxField("DoNotCacheMenu", "Do Not Cache Menu"));
43
        $fields->addFieldToTab("Root.Caching", new LiteralField("ClearCache", "<a href=\"".$this->owner->Link("clearallfieldcaches")."\">clear cache (do this at the end of all edit sessions)</a>"));
44
        return $fields;
45
    }
46
47
    //-------------------- menu cache ------------------ ------------------ ------------------ ------------------ ------------------ ------------------
48
49
    public function clearfieldcache($showoutput = false)
50
    {
51
        $fieldsToClear = array();
52
        $fieldsForEach = Config::inst()->get("MenuCache", "fields");
53
        foreach ($fieldsForEach as $key => $field) {
54
            $fieldName = self::field_maker($key);
55
            $fieldsToClear[] = "\"".$fieldName."\" = ''";
56
        }
57
        if (count($fieldsToClear)) {
58
            $tablesForEach = Config::inst()->get("MenuCache", "tables_to_clear");
59
            foreach ($tablesForEach as $table) {
0 ignored issues
show
The expression $tablesForEach of type array|integer|double|string|boolean is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
60
                $msg = '';
61
                $sql = "UPDATE \"".$table."\" SET ".implode(", ", $fieldsToClear);
62
                if (Controller::curr()->getRequest()->param("ID") == "days" && $days = intval(Controller::curr()->getRequest()->param("OtherID"))) {
63
                    $sql .= ' WHERE \"LastEdited\" > ( NOW() - INTERVAL '.$days.' DAY )';
64
                    $msg .= ', created before the last '.$days.' days';
65
                } elseif (Controller::curr()->getRequest()->param("ID") == "thispage") {
66
                    $sql .= " WHERE  \"".$table."\".\"ID\" = ".$this->owner->ID;
67
                    $msg .= ', for page with ID = '.$this->owner->ID;
68
                }
69
                if ($showoutput) {
70
                    DB::alteration_message("Deleting cached data from $table, ".$msg);
71
                    debug::show($sql);
72
                }
73
                DB::query($sql);
74
            }
75
        }
76
        return array();
77
    }
78
79
    //add this function to your page class if needed
80
    public function onBeforeWrite()
81
    {
82
        //$this->clearfieldcache(); // technically this should be done, but it puts a lot of strain on saving so instead we encourage people to use ?flush=1
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...
83
        parent::onBeforeWrite();
84
    }
85
}
86
87
class MenuCache_Controller extends Extension
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...
88
{
89
    private static $allowed_actions = array("showcachedfield","clearfieldcache","showuncachedfield", "clearallfieldcaches");
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...
90
91
    protected function getHtml($fieldNumber)
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...
92
    {
93
        $layoutField = Config::inst()->get("MenuCache", "layout_field");
94
        if ($layoutField == $fieldNumber) {
95
            $className = $this->owner->ClassName;
96
            if ("Page" == $className) {
97
                $className = "PageCached";
98
            }
99
            return $this->owner->renderWith(array($className, "PageCached"));
100
        } else {
101
            return $this->owner->renderWith('UsedToCreateCache'.$fieldNumber);
102
        }
103
    }
104
105
    public function CachedField($fieldNumber)
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...
CachedField 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...
106
    {
107
        $fieldName = MenuCache::field_maker($fieldNumber);
108
        if (isset($_REQUEST["flush"])) {
109
            $this->owner->clearfieldcache();
110
        }
111
        if (!(MenuCache::fields_exists($fieldNumber))) {
112
            user_error("$fieldName is not a field that can be cached", E_USER_ERROR);
113
        } else {
114
            if (!$this->owner->$fieldName || $this->owner->DoNotCacheMenu) {
115
                $fieldID = $fieldNumber;
0 ignored issues
show
$fieldID 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...
116
                $content = $this->getHtml($fieldNumber);
117
                $sql = "Update \"SiteTree_Live\" Set \"".$fieldName."\" = '".$this->compressAndPrepareHTML($content)."' WHERE \"ID\" = ".$this->owner->ID." LIMIT 1";
118
                DB::query($sql);
119
                return $content;
120
            } else {
121
                return $this->owner->$fieldName;
122
            }
123
        }
124
    }
125
126
127
    private function compressAndPrepareHTML($html)
128
    {
129
        $pat[0] = "/^\s+/";
0 ignored issues
show
Coding Style Comprehensibility introduced by
$pat was never initialized. Although not strictly required by PHP, it is generally a good practice to add $pat = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
130
        $pat[1] = "/\s{2,}/";
131
        $pat[2] = "/\s+\$/";
132
        $rep[0] = "";
0 ignored issues
show
Coding Style Comprehensibility introduced by
$rep was never initialized. Although not strictly required by PHP, it is generally a good practice to add $rep = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
133
        $rep[1] = " ";
134
        $rep[2] = "";
135
        $html = preg_replace($pat, $rep, $html);
136
        $html = trim($html);
137
        return addslashes($html);
138
    }
139
140
141
142
    public function showcachedfield($httpRequest = null)
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...
143
    {
144
        $fieldNumber = $httpRequest->param("ID");
145
        return $this->getHtml($fieldNumber);
146
    }
147
148
    public function showuncachedfield($httpRequest = null)
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...
149
    {
150
        $this->owner->clearfieldcache();
151
        return $this->showcachedfield($httpRequest);
152
    }
153
154
    public function clearallfieldcaches($httpRequest = null)
0 ignored issues
show
The parameter $httpRequest 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...
155
    {
156
        $this->owner->clearfieldcache(true);
157
        return 'fields have been cleared, <a href="/?flush=all">click to continue...</a>';
158
    }
159
}
160