CMSHelp::HelpFiles()   A
last analyzed

Complexity

Conditions 4
Paths 2

Size

Total Lines 12
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 12
rs 9.2
c 0
b 0
f 0
cc 4
eloc 8
nc 2
nop 0
1
<?php
2
3
class CMSHelp extends Page_Controller implements PermissionProvider
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
    /**
7
     *@var String name of the directory in which the help files are kept
8
     *
9
     */
10
    private static $help_file_directory_name = "_help";
0 ignored issues
show
Unused Code introduced by
The property $help_file_directory_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...
11
12
    /**
13
     *@var String name of the directory in which the help files are kept
14
     *
15
     */
16
    private static $dev_file_directory_name = "_dev";
0 ignored issues
show
Unused Code introduced by
The property $dev_file_directory_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...
17
18
19
    /**
20
     *@var String urlsegment for the controller
21
     *
22
     */
23
    private static $url_segment = "admin/help";
0 ignored issues
show
Unused Code introduced by
The property $url_segment 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
    private static $permission_code = "CMS_HELP_FILES_PERMISSION_CODE";
0 ignored issues
show
Unused Code introduced by
The property $permission_code 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...
26
27
    /**
28
     *@var String urlsegment for the controller
29
     *
30
     */
31
    private static $allowed_actions = array(
0 ignored issues
show
Unused Code introduced by
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...
32
        'download' => 'CMS_HELP_FILES_PERMISSION_CODE'
33
    );
34
35
    /**
36
     * standard SS Method
37
     *
38
     */
39
    public function init()
40
    {
41
        // Only administrators can run this method
42
        if (!Permission::check("CMS_HELP_FILES_PERMISSION_CODE")) {
43
            Security::permissionFailure($this, _t('Security.PERMFAILURE', ' This page is secured and you need rights to access it. Please contact the site administrator is you believe you should be able to access this page.'));
44
        }
45
        parent::init();
46
        Requirements::themedCSS("typography", "typography");
47
        Requirements::javascript(THIRDPARTY_DIR."/jquery/jquery.js");
48
    }
49
50
51
    /**
52
     * standard SS Method
53
     *
54
     */
55
    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...
56
    {
57
        return $this->renderWith('Page');
58
    }
59
60
    public function getContent()
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
        return $this->renderWith('CMSHelp');
63
    }
64
65
66
    /**
67
     * returns the Link to the controller
68
     *
69
     * @return String -
70
     */
71
    public function Link($action = "")
72
    {
73
        $str = "/".$this->config()->get("url_segment")."/";
74
        if ($action) {
75
            $str .= $action . '/';
76
        }
77
        return $str;
78
    }
79
80
    public function download($request)
81
    {
82
        $fileName = urldecode($request->getVar('file'));
83
        $files = self::get_list_of_files($this->Config()->get("help_file_directory_name"));
84
        foreach ($files as $file) {
85
            if ($fileName === $file['FileName']) {
86
                $fileName = $file['FullLocation'];
87
                if (file_exists($fileName)) {
88
                    return SS_HTTPRequest::send_file(file_get_contents($fileName), $file['FileName']);
89
                }
90
            }
91
        }
92
        die('ERROR');
0 ignored issues
show
Coding Style Compatibility introduced by
The method download() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
93
    }
94
95
    /**
96
     * @return ArrayList of help files
97
     *
98
     *
99
     */
100
    public function HelpFiles()
101
    {
102
        $dos = new ArrayList();
103
        $fileArray = self::get_list_of_files($this->Config()->get("help_file_directory_name"));
104
        if ($fileArray && count($fileArray)) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $fileArray of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
105
            $linkArray = array();
0 ignored issues
show
Unused Code introduced by
$linkArray 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...
106
            foreach ($fileArray as $file) {
107
                $dos->push(new ArrayData($file));
108
            }
109
        }
110
        return $dos;
111
    }
112
113
    /**
114
     * @return String - title for project
115
     *
116
     *
117
     */
118
    public function SiteTitle()
119
    {
120
        $sc = SiteConfig::current_site_config();
121
        if ($sc && $sc->Title) {
122
            return $sc->Title;
123
        }
124
        return Director::absoluteURL();
0 ignored issues
show
Bug introduced by
The call to absoluteURL() misses a required argument $url.

This check looks for function calls that miss required arguments.

Loading history...
125
    }
126
127
128
    /**
129
     * @param String $location - folder location without start and end slahs (e.g. assets/myfolder )
130
     * @return Array - array of help files
131
     *
132
     *
133
     */
134
    public static function get_list_of_files($location)
135
    {
136
        $fileArray = array();
137
        $directory = "/".$location."/";
138
        $baseDirectory = Director::baseFolder().$directory;
139
        //get all image files with a .jpg extension.
140
        $images = self::get_list_of_files_in_directory($baseDirectory, array("png", "jpg", "gif", 'pdf'));
141
        $me = Injector::inst()->get('CMSHelp');
142
        //print each file name
143
        if (is_array($images) && count($images)) {
144
            foreach ($images as $key => $image) {
145
                if ($image) {
146
                    if (file_exists($baseDirectory.$image)) {
147
                        $fileArray[$key]["FileName"] = $image;
148
                        $fileArray[$key]["FullLocation"] = $baseDirectory.$image;
149
                        $fileArray[$key]["Link"] = $me->Link('download').'?file='.urldecode($image);
150
                        $fileArray[$key]["Title"] = self::add_space_before_capital($image);
151
                    }
152
                }
153
            }
154
        }
155
        return $fileArray;
156
    }
157
158
159
    /**
160
     * @param String $directory - location of the directory
161
     * @param Array $extensionArray - array of extensions to include (e.g. Array("png", "mov");)
162
     *
163
     * @return Array - list of all files in a directory
0 ignored issues
show
Documentation introduced by
Should the return type not be false|array?

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...
164
     */
165
    public static function get_list_of_files_in_directory($directory, $extensionArray)
166
    {
167
        //	create an array to hold directory list
168
        $results = array();
169
        // create a handler for the directory
170
        $handler = @opendir($directory);
171
        if (!is_dir($directory)) {
172
            return false;
173
        }
174
        if ($handler) {
175
            //open directory and walk through the filenames
176
            while ($file = readdir($handler)) {
177
                // if file isn't this directory or its parent, add it to the results
178
                if ($file != "." && $file != ".." && !is_dir($file)) {
179
                    //echo $file;
180
                    $extension = substr(strrchr($file, '.'), 1);
181
                    if (in_array($extension, $extensionArray)) {
182
                        $results[] = $file;
183
                    }
184
                }
185
            }
186
            // tidy up: close the handler
187
            closedir($handler);
188
            // done!
189
            asort($results);
190
        }
191
        return $results;
192
    }
193
194
195
196
197
    /**
198
     * returns the Link to the controller
199
     * @param String $string - input
200
     * @return String
201
     */
202
    private static function add_space_before_capital($string)
203
    {
204
        $string = preg_replace('/(?<!\ )[A-Z\-]/', ' $0', $string);
205
        $extension = substr(strrchr($string, '.'), 0);
206
        $string = str_replace(array('-', $extension, '.'), "", $string);
207
        return $string;
208
    }
209
210
    public function providePermissions()
211
    {
212
        $perms[Config::inst()->get("CMSHelp", "permission_code")] = array(
0 ignored issues
show
Coding Style Comprehensibility introduced by
$perms was never initialized. Although not strictly required by PHP, it is generally a good practice to add $perms = 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...
213
            'name' => "Download Help Files",
214
            'category' => "Help",
215
            'sort' => 0
216
        );
217
        return $perms;
218
    }
219
}
220