Completed
Pull Request — develop (#716)
by Agel_Nash
12:56
created

tv.php ➔ getTVDisplayFormat()   F

Complexity

Conditions 84
Paths 2312

Size

Total Lines 339
Code Lines 250

Duplication

Lines 3
Ratio 0.88 %

Importance

Changes 0
Metric Value
cc 84
eloc 250
nc 2312
nop 7
dl 3
loc 339
rs 2
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
if (! function_exists('ProcessTVCommand')) {
4
    /**
5
     * @param string $value
6
     * @param string $name
7
     * @param string $docid
8
     * @param string $src
9
     * @param array $tvsArray
10
     * @return string
11
     */
12
    function ProcessTVCommand($value, $name = '', $docid = '', $src = 'docform', $tvsArray = array())
0 ignored issues
show
Coding Style introduced by
As per coding-style, this function should be in camelCase.

CamelCase (...) is the practice of writing compound words or phrases such that
each word or abbreviation begins with a capital letter.

Learn more about camelCase.

Loading history...
13
    {
14
        $modx = evolutionCMS();
15
        $docid = (int)$docid > 0 ? (int)$docid : $modx->documentIdentifier;
16
        $nvalue = trim($value);
17
        if (substr($nvalue, 0, 1) != '@') {
18
            return $value;
19
        } elseif (isset($modx->config['enable_bindings']) && $modx->config['enable_bindings'] != 1 && $src === 'docform') {
20
            return '@Bindings is disabled.';
21
        } else {
22
            list ($cmd, $param) = ParseCommand($nvalue);
23
            $cmd = trim($cmd);
24
            $param = parseTvValues($param, $tvsArray);
25
            switch ($cmd) {
26
                case "FILE" :
0 ignored issues
show
Coding Style introduced by
There must be no space before the colon in a CASE statement

As per the PSR-2 coding standard, there must not be a space in front of the colon in case statements.

switch ($selector) {
    case "A": //right
        doSomething();
        break;
    case "B" : //wrong
        doSomethingElse();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
27
                    $output = $modx->atBindFileContent($nvalue);
28
                    break;
29
30
                case "CHUNK" : // retrieve a chunk and process it's content
0 ignored issues
show
Coding Style introduced by
There must be no space before the colon in a CASE statement

As per the PSR-2 coding standard, there must not be a space in front of the colon in case statements.

switch ($selector) {
    case "A": //right
        doSomething();
        break;
    case "B" : //wrong
        doSomethingElse();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
31
                    $chunk = $modx->getChunk(trim($param));
32
                    $output = $chunk;
33
                    break;
34
35
                case "DOCUMENT" : // retrieve a document and process it's content
0 ignored issues
show
Coding Style introduced by
There must be no space before the colon in a CASE statement

As per the PSR-2 coding standard, there must not be a space in front of the colon in case statements.

switch ($selector) {
    case "A": //right
        doSomething();
        break;
    case "B" : //wrong
        doSomethingElse();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
36
                    $rs = $modx->getDocument($param);
0 ignored issues
show
Comprehensibility introduced by
Avoid variables with short names like $rs. Configured minimum length is 3.

Short variable names may make your code harder to understand. Variable names should be self-descriptive. This check looks for variable names who are shorter than a configured minimum.

Loading history...
37
                    if (is_array($rs)) {
38
                        $output = $rs['content'];
39
                    } else {
40
                        $output = "Unable to locate document $param";
41
                    }
42
                    break;
43
44
                case "SELECT" : // selects a record from the cms database
0 ignored issues
show
Coding Style introduced by
There must be no space before the colon in a CASE statement

As per the PSR-2 coding standard, there must not be a space in front of the colon in case statements.

switch ($selector) {
    case "A": //right
        doSomething();
        break;
    case "B" : //wrong
        doSomethingElse();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
45
                    $rt = array();
0 ignored issues
show
Unused Code introduced by
$rt 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...
Comprehensibility introduced by
Avoid variables with short names like $rt. Configured minimum length is 3.

Short variable names may make your code harder to understand. Variable names should be self-descriptive. This check looks for variable names who are shorter than a configured minimum.

Loading history...
46
                    $replacementVars = array(
47
                        'DBASE'  => $modx->db->config['dbase'],
48
                        'PREFIX' => $modx->db->config['table_prefix']
49
                    );
50
                    foreach ($replacementVars as $rvKey => $rvValue) {
51
                        $modx->setPlaceholder($rvKey, $rvValue);
52
                    }
53
                    $param = $modx->mergePlaceholderContent($param);
54
                    $rs = $modx->db->query("SELECT $param;");
55
                    $output = $rs;
56
                    break;
57
58
                case "EVAL" : // evaluates text as php codes return the results
0 ignored issues
show
Coding Style introduced by
There must be no space before the colon in a CASE statement

As per the PSR-2 coding standard, there must not be a space in front of the colon in case statements.

switch ($selector) {
    case "A": //right
        doSomething();
        break;
    case "B" : //wrong
        doSomethingElse();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
59
                    $output = eval ($param);
0 ignored issues
show
Coding Style introduced by
The function ProcessTVCommand() contains an eval expression.

On one hand, eval might be exploited by malicious users if they somehow manage to inject dynamic content. On the other hand, with the emergence of faster PHP runtimes like the HHVM, eval prevents some optimization that they perform.

Loading history...
60
                    break;
61
62
                case "INHERIT" :
0 ignored issues
show
Coding Style introduced by
There must be no space before the colon in a CASE statement

As per the PSR-2 coding standard, there must not be a space in front of the colon in case statements.

switch ($selector) {
    case "A": //right
        doSomething();
        break;
    case "B" : //wrong
        doSomethingElse();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
63
                    $output = $param; // Default to param value if no content from parents
64
                    $doc = $modx->getPageInfo($docid, 0, 'id,parent');
65
66
                    while ($doc['parent'] != 0) {
67
                        $parent_id = $doc['parent'];
68
69
                        // Grab document regardless of publish status
70
                        $doc = $modx->getPageInfo($parent_id, 0, 'id,parent,published');
71
                        if ($doc['parent'] != 0 && !$doc['published']) {
72
                            continue;
73
                        } // hide unpublished docs if we're not at the top
74
75
                        $tv = $modx->getTemplateVar($name, '*', $doc['id'], $doc['published']);
0 ignored issues
show
Comprehensibility introduced by
Avoid variables with short names like $tv. Configured minimum length is 3.

Short variable names may make your code harder to understand. Variable names should be self-descriptive. This check looks for variable names who are shorter than a configured minimum.

Loading history...
76
77
                        // if an inherited value is found and if there is content following the @INHERIT binding
78
                        // remove @INHERIT and output that following content. This content could contain other
79
                        // @ bindings, that are processed in the next step
80
                        if ((string)$tv['value'] !== '' && !preg_match('%^@INHERIT[\s\n\r]*$%im', $tv['value'])) {
81
                            $output = trim(str_replace('@INHERIT', '', (string)$tv['value']));
82
                            break 2;
83
                        }
84
                    }
85
                    break;
86
87
                case 'DIRECTORY' :
0 ignored issues
show
Coding Style introduced by
There must be no space before the colon in a CASE statement

As per the PSR-2 coding standard, there must not be a space in front of the colon in case statements.

switch ($selector) {
    case "A": //right
        doSomething();
        break;
    case "B" : //wrong
        doSomethingElse();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
88
                    $files = array();
89
                    $path = $modx->config['base_path'] . $param;
90
                    if (substr($path, -1, 1) != '/') {
91
                        $path .= '/';
92
                    }
93
                    if (!is_dir($path)) {
94
                        die($path);
0 ignored issues
show
Coding Style Compatibility introduced by
The function ProcessTVCommand() 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...
95
                        break;
0 ignored issues
show
Unused Code introduced by
break; does not seem to be reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
96
                    }
97
                    $dir = dir($path);
98
                    while (($file = $dir->read()) !== false) {
99
                        if (substr($file, 0, 1) != '.') {
100
                            $files[] = "{$file}=={$param}{$file}";
101
                        }
102
                    }
103
                    asort($files);
104
                    $output = implode('||', $files);
105
                    break;
106
107
                default :
0 ignored issues
show
Coding Style introduced by
There must be no space before the colon in a DEFAULT statement

As per the PSR-2 coding standard, there must not be a space in front of the colon in the default statement.

switch ($expr) {
    default : //wrong
        doSomething();
        break;
}

switch ($expr) {
    default: //right
        doSomething();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
108
                    $output = $value;
109
                    break;
110
111
            }
112
113
            // support for nested bindings
114
            return is_string($output) && ($output != $value) ? ProcessTVCommand($output, $name, $docid, $src,
115
                $tvsArray) : $output;
116
        }
117
    }
118
}
119
120
if (! function_exists('ProcessFile')) {
121
    /**
122
     * @param $file
123
     * @return string
124
     */
125
    function ProcessFile($file)
0 ignored issues
show
Coding Style introduced by
As per coding-style, this function should be in camelCase.

CamelCase (...) is the practice of writing compound words or phrases such that
each word or abbreviation begins with a capital letter.

Learn more about camelCase.

Loading history...
126
    {
127
        // get the file
128
        $buffer = @file_get_contents($file);
129
        if ($buffer === false) {
130
            $buffer = " Could not retrieve document '$file'.";
131
        }
132
133
        return $buffer;
134
    }
135
}
136
137
if (! function_exists('ParseCommand')) {
138
    /**
139
     * ParseCommand - separate @ cmd from params
140
     *
141
     * @param string $binding_string
142
     * @return array
143
     */
144
    function ParseCommand($binding_string)
0 ignored issues
show
Coding Style introduced by
As per coding-style, this function should be in camelCase.

CamelCase (...) is the practice of writing compound words or phrases such that
each word or abbreviation begins with a capital letter.

Learn more about camelCase.

Loading history...
145
    {
146
        $BINDINGS = array( // Array of supported bindings. must be upper case
147
            'FILE',
148
            'CHUNK',
149
            'DOCUMENT',
150
            'SELECT',
151
            'EVAL',
152
            'INHERIT',
153
            'DIRECTORY'
154
        );
155
156
        $binding_array = array();
157
        foreach ($BINDINGS as $cmd) {
158
            if (strpos($binding_string, '@' . $cmd) === 0) {
159
                $code = substr($binding_string, strlen($cmd) + 1);
160
                $binding_array = array($cmd, trim($code));
161
                break;
162
            }
163
        }
164
165
        return $binding_array;
166
    }
167
}
168
169
if (! function_exists('parseTvValues')) {
170
    /**
171
     * Parse MODX Template-Variables
172
     *
173
     * @param string $param
174
     * @param array $tvsArray
175
     * @return mixed
0 ignored issues
show
Documentation introduced by
Consider making the return type a bit more specific; maybe use string.

This check looks for the generic type array as a return type and suggests a more specific type. This type is inferred from the actual code.

Loading history...
176
     */
177
    function parseTvValues($param, $tvsArray)
178
    {
179
        $modx = evolutionCMS();
180
        $tvsArray = is_array($modx->documentObject) ? array_merge($tvsArray, $modx->documentObject) : $tvsArray;
181
        if (strpos($param, '[*') !== false) {
182
            $matches = $modx->getTagsFromContent($param, '[*', '*]');
183
            foreach ($matches[0] as $i => $match) {
184
                if (isset($tvsArray[$matches[1][$i]])) {
185
                    if (is_array($tvsArray[$matches[1][$i]])) {
186
                        $value = $tvsArray[$matches[1][$i]]['value'];
187
                        $value = $value === '' ? $tvsArray[$matches[1][$i]]['default_text'] : $value;
188
                    } else {
189
                        $value = $tvsArray[$matches[1][$i]];
190
                    }
191
                    $param = str_replace($match, $value, $param);
192
                }
193
            }
194
        }
195
196
        return $param;
197
    }
198
}
199
200
if (! function_exists('getTVDisplayFormat')) {
201
    /**
202
     * @param string $name
203
     * @param string $value
204
     * @param string $format
205
     * @param string $paramstring
206
     * @param string $tvtype
207
     * @param string $docid
208
     * @param string $sep
209
     * @return mixed|string
210
     */
211
    function getTVDisplayFormat($name, $value, $format, $paramstring = "", $tvtype = "", $docid = "", $sep = '')
212
    {
213
214
        $modx = evolutionCMS();
215
        $o = '';
0 ignored issues
show
Comprehensibility introduced by
Avoid variables with short names like $o. Configured minimum length is 3.

Short variable names may make your code harder to understand. Variable names should be self-descriptive. This check looks for variable names who are shorter than a configured minimum.

Loading history...
216
217
        // process any TV commands in value
218
        $docid = (int)$docid > 0 ? (int)$docid : $modx->documentIdentifier;
219
        $value = ProcessTVCommand($value, $name, $docid);
220
221
        $params = array();
222
        if ($paramstring) {
223
            $cp = explode("&", $paramstring);
0 ignored issues
show
Comprehensibility introduced by
Avoid variables with short names like $cp. Configured minimum length is 3.

Short variable names may make your code harder to understand. Variable names should be self-descriptive. This check looks for variable names who are shorter than a configured minimum.

Loading history...
224
            foreach ($cp as $p => $v) {
225
                $v = trim($v); // trim
226
                $ar = explode("=", $v);
227
                if (is_array($ar) && count($ar) == 2) {
228
                    $params[$ar[0]] = decodeParamValue($ar[1]);
229
                }
230
            }
231
        }
232
233
        $id = "tv$name";
234
        switch ($format) {
235
            case 'image':
236
                $images = parseInput($value, '||', 'array');
237
                foreach ($images as $image) {
0 ignored issues
show
Bug introduced by
The expression $images of type array|string 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...
238
                    if (!is_array($image)) {
239
                        $image = explode('==', $image);
240
                    }
241
                    $src = $image[0];
242
243
                    if ($src) {
244
                        // We have a valid source
245
                        $attributes = '';
246
                        $attr = array(
247
                            'class' => $params['class'],
248
                            'src'   => $src,
249
                            'id'    => ($params['id'] ? $params['id'] : ''),
250
                            'alt'   => $modx->htmlspecialchars($params['alttext']),
251
                            'style' => $params['style']
252
                        );
253
                        if (isset($params['align']) && $params['align'] != 'none') {
254
                            $attr['align'] = $params['align'];
255
                        }
256 View Code Duplication
                        foreach ($attr as $k => $v) {
257
                            $attributes .= ($v ? ' ' . $k . '="' . $v . '"' : '');
258
                        }
259
                        $attributes .= ' ' . $params['attrib'];
260
261
                        // Output the image with attributes
262
                        $o .= '<img' . rtrim($attributes) . ' />';
263
                    }
264
                }
265
                break;
266
267
            case "delim":    // display as delimitted list
268
                $value = parseInput($value, "||");
269
                $p = $params['format'] ? $params['format'] : " ";
270
                if ($p == "\\n") {
271
                    $p = "\n";
272
                }
273
                $o = str_replace("||", $p, $value);
274
                break;
275
276
            case "string":
277
                $value = parseInput($value);
278
                $format = strtolower($params['format']);
279
                if ($format == 'upper case') {
280
                    $o = strtoupper($value);
281
                } else {
282
                    if ($format == 'lower case') {
283
                        $o = strtolower($value);
284
                    } else {
285
                        if ($format == 'sentence case') {
286
                            $o = ucfirst($value);
287
                        } else {
288
                            if ($format == 'capitalize') {
289
                                $o = ucwords($value);
290
                            } else {
291
                                $o = $value;
292
                            }
293
                        }
294
                    }
295
                }
296
                break;
297
298
            case "date":
299
                if ($value != '' || $params['default'] == 'Yes') {
300
                    if (empty($value)) {
301
                        $value = 'now';
302
                    }
303
                    $timestamp = getUnixtimeFromDateString($value);
304
                    $p = $params['format'] ? $params['format'] : "%A %d, %B %Y";
305
                    $o = strftime($p, $timestamp);
306
                } else {
307
                    $value = '';
0 ignored issues
show
Unused Code introduced by
$value 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
                }
309
                break;
310
311
            case "hyperlink":
312
                $value = parseInput($value, "||", "array");
313
                $o = '';
314
                $countValue = count($value);
315
                for ($i = 0; $i < $countValue; $i++) {
316
                    list($name, $url) = is_array($value[$i]) ? $value[$i] : explode("==", $value[$i]);
317
                    if (!$url) {
318
                        $url = $name;
319
                    }
320
                    if ($url) {
321
                        if ($o) {
322
                            $o .= '<br />';
323
                        }
324
                        $attributes = '';
325
                        // setup the link attributes
326
                        $attr = array(
327
                            'href'   => $url,
328
                            'title'  => $params['title'] ? $modx->htmlspecialchars($params['title']) : $name,
329
                            'class'  => $params['class'],
330
                            'style'  => $params['style'],
331
                            'target' => $params['target'],
332
                        );
333 View Code Duplication
                        foreach ($attr as $k => $v) {
334
                            $attributes .= ($v ? ' ' . $k . '="' . $v . '"' : '');
335
                        }
336
                        $attributes .= ' ' . $params['attrib']; // add extra
337
338
                        // Output the link
339
                        $o .= '<a' . rtrim($attributes) . '>' . ($params['text'] ? $modx->htmlspecialchars($params['text']) : $name) . '</a>';
340
                    }
341
                }
342
                break;
343
344
            case "htmltag":
345
                $value = parseInput($value, "||", "array");
346
                $tagid = $params['tagid'];
347
                $tagname = ($params['tagname']) ? $params['tagname'] : 'div';
348
                $o = '';
349
                // Loop through a list of tags
350
                $countValue = count($value);
351
                for ($i = 0; $i < $countValue; $i++) {
352
                    $tagvalue = is_array($value[$i]) ? implode(' ', $value[$i]) : $value[$i];
353
                    if (!$tagvalue) {
354
                        continue;
355
                    }
356
357
                    $attributes = '';
358
                    $attr = array(
359
                        'id'    => ($tagid ? $tagid : $id),
360
                        // 'tv' already added to id
361
                        'class' => $params['class'],
362
                        'style' => $params['style'],
363
                    );
364 View Code Duplication
                    foreach ($attr as $k => $v) {
365
                        $attributes .= ($v ? ' ' . $k . '="' . $v . '"' : '');
366
                    }
367
                    $attributes .= ' ' . $params['attrib']; // add extra
368
369
                    // Output the HTML Tag
370
                    $o .= '<' . $tagname . rtrim($attributes) . '>' . $tagvalue . '</' . $tagname . '>';
371
                }
372
                break;
373
374
            case "richtext":
375
                $value = parseInput($value);
376
                $w = $params['w'] ? $params['w'] : '100%';
0 ignored issues
show
Comprehensibility introduced by
Avoid variables with short names like $w. Configured minimum length is 3.

Short variable names may make your code harder to understand. Variable names should be self-descriptive. This check looks for variable names who are shorter than a configured minimum.

Loading history...
377
                $h = $params['h'] ? $params['h'] : '400px';
0 ignored issues
show
Comprehensibility introduced by
Avoid variables with short names like $h. Configured minimum length is 3.

Short variable names may make your code harder to understand. Variable names should be self-descriptive. This check looks for variable names who are shorter than a configured minimum.

Loading history...
378
                $richtexteditor = $params['edt'] ? $params['edt'] : "";
379
                $o = '<div class="MODX_RichTextWidget"><textarea id="' . $id . '" name="' . $id . '" style="width:' . $w . '; height:' . $h . ';">';
380
                $o .= $modx->htmlspecialchars($value);
381
                $o .= '</textarea></div>';
382
                $replace_richtext = array($id);
383
                // setup editors
384
                if (!empty($replace_richtext) && !empty($richtexteditor)) {
385
                    // invoke OnRichTextEditorInit event
386
                    $evtOut = $modx->invokeEvent("OnRichTextEditorInit", array(
387
                        'editor'      => $richtexteditor,
388
                        'elements'    => $replace_richtext,
389
                        'forfrontend' => 1,
390
                        'width'       => $w,
391
                        'height'      => $h
392
                    ));
393
                    if (is_array($evtOut)) {
394
                        $o .= implode("", $evtOut);
395
                    }
396
                }
397
                break;
398
399
            case "unixtime":
400
                $value = parseInput($value);
401
                $o = getUnixtimeFromDateString($value);
0 ignored issues
show
Bug introduced by
It seems like $value defined by parseInput($value) on line 400 can also be of type array; however, getUnixtimeFromDateString() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
402
                break;
403
404
            case "viewport":
405
                $value = parseInput($value);
406
                $id = '_' . time();
407
                if (!$params['vpid']) {
408
                    $params['vpid'] = $id;
409
                }
410
                $sTag = "<iframe";
411
                $eTag = "</iframe>";
412
                $autoMode = "0";
413
                $w = $params['width'];
414
                $h = $params['height'];
415
                if ($params['stretch'] == 'Yes') {
416
                    $w = "100%";
417
                    $h = "100%";
418
                }
419
                if ($params['asize'] == 'Yes' || ($params['awidth'] == 'Yes' && $params['aheight'] == 'Yes')) {
420
                    $autoMode = "3";  //both
421
                } else {
422
                    if ($params['awidth'] == 'Yes') {
423
                        $autoMode = "1"; //width only
424
                    } else {
425
                        if ($params['aheight'] == 'Yes') {
426
                            $autoMode = "2";    //height only
427
                        }
428
                    }
429
                }
430
431
                $modx->regClientStartupScript(MODX_MANAGER_URL . "media/script/bin/viewport.js", array(
432
                    'name'      => 'viewport',
433
                    'version'   => '0',
434
                    'plaintext' => false
435
                ));
436
                $o = $sTag . " id='" . $params['vpid'] . "' name='" . $params['vpid'] . "' ";
437
                if ($params['class']) {
438
                    $o .= " class='" . $params['class'] . "' ";
439
                }
440
                if ($params['style']) {
441
                    $o .= " style='" . $params['style'] . "' ";
442
                }
443
                if ($params['attrib']) {
444
                    $o .= $params['attrib'] . " ";
445
                }
446
                $o .= "scrolling='" . ($params['sbar'] == 'No' ? "no" : ($params['sbar'] == 'Yes' ? "yes" : "auto")) . "' ";
447
                $o .= "src='" . $value . "' frameborder='" . $params['borsize'] . "' ";
448
                $o .= "onload=\"window.setTimeout('ResizeViewPort(\\'" . $params['vpid'] . "\\'," . $autoMode . ")',100);\" width='" . $w . "' height='" . $h . "' ";
449
                $o .= ">";
450
                $o .= $eTag;
451
                break;
452
453
            case "datagrid":
454
                include_once MODX_MANAGER_PATH . "includes/controls/datagrid.class.php";
455
                $grd = new DataGrid('', $value);
456
457
                $grd->noRecordMsg = $params['egmsg'];
458
459
                $grd->columnHeaderClass = $params['chdrc'];
460
                $grd->cssClass = $params['tblc'];
461
                $grd->itemClass = $params['itmc'];
462
                $grd->altItemClass = $params['aitmc'];
463
464
                $grd->columnHeaderStyle = $params['chdrs'];
465
                $grd->cssStyle = $params['tbls'];
466
                $grd->itemStyle = $params['itms'];
467
                $grd->altItemStyle = $params['aitms'];
468
469
                $grd->columns = $params['cols'];
470
                $grd->fields = $params['flds'];
471
                $grd->colWidths = $params['cwidth'];
472
                $grd->colAligns = $params['calign'];
473
                $grd->colColors = $params['ccolor'];
474
                $grd->colTypes = $params['ctype'];
475
476
                $grd->cellPadding = $params['cpad'];
477
                $grd->cellSpacing = $params['cspace'];
478
                $grd->header = $params['head'];
479
                $grd->footer = $params['foot'];
480
                $grd->pageSize = $params['psize'];
481
                $grd->pagerLocation = $params['ploc'];
482
                $grd->pagerClass = $params['pclass'];
483
                $grd->pagerStyle = $params['pstyle'];
484
                $o = $grd->render();
485
                break;
486
487
            case 'htmlentities':
488
                $value = parseInput($value);
489
                if ($tvtype == 'checkbox' || $tvtype == 'listbox-multiple') {
490
                    // remove delimiter from checkbox and listbox-multiple TVs
491
                    $value = str_replace('||', '', $value);
492
                }
493
                $o = htmlentities($value, ENT_NOQUOTES, $modx->config['modx_charset']);
494
                break;
495
496
            case 'custom_widget':
497
                $widget_output = '';
498
                $o = '';
499
                /* If we are loading a file */
500
                if (substr($params['output'], 0, 5) == "@FILE") {
501
                    $file_name = MODX_BASE_PATH . trim(substr($params['output'], 6));
502
                    if (!file_exists($file_name)) {
503
                        $widget_output = $file_name . ' does not exist';
504
                    } else {
505
                        $widget_output = file_get_contents($file_name);
506
                    }
507
                } elseif (substr($params['output'], 0, 8) == '@INCLUDE') {
508
                    $file_name = MODX_BASE_PATH . trim(substr($params['output'], 9));
509
                    if (!file_exists($file_name)) {
510
                        $widget_output = $file_name . ' does not exist';
511
                    } else {
512
                        /* The included file needs to set $widget_output. Can be string, array, object */
513
                        include $file_name;
514
                    }
515
                } elseif (substr($params['output'], 0, 6) == '@CHUNK' && $value !== '') {
516
                    $chunk_name = trim(substr($params['output'], 7));
517
                    $widget_output = $modx->getChunk($chunk_name);
518
                } elseif (substr($params['output'], 0, 5) == '@EVAL' && $value !== '') {
519
                    $eval_str = trim(substr($params['output'], 6));
520
                    $widget_output = eval($eval_str);
0 ignored issues
show
Coding Style introduced by
The function getTVDisplayFormat() contains an eval expression.

On one hand, eval might be exploited by malicious users if they somehow manage to inject dynamic content. On the other hand, with the emergence of faster PHP runtimes like the HHVM, eval prevents some optimization that they perform.

Loading history...
521
                } elseif ($value !== '') {
522
                    $widget_output = $params['output'];
523
                } else {
524
                    $widget_output = '';
525
                }
526
                if (is_string($widget_output)) {
527
                    $_ = $modx->config['enable_filter'];
0 ignored issues
show
Comprehensibility introduced by
Avoid variables with short names like $_. Configured minimum length is 3.

Short variable names may make your code harder to understand. Variable names should be self-descriptive. This check looks for variable names who are shorter than a configured minimum.

Loading history...
528
                    $modx->config['enable_filter'] = 1;
529
                    $widget_output = $modx->parseText($widget_output, array('value' => $value));
530
                    $modx->config['enable_filter'] = $_;
531
                    $o = $modx->parseDocumentSource($widget_output);
532
                } else {
533
                    $o = $widget_output;
534
                }
535
                break;
536
537
            default:
538
                $value = parseInput($value);
539
                if ($tvtype == 'checkbox' || $tvtype == 'listbox-multiple') {
540
                    // add separator
541
                    $value = explode('||', $value);
542
                    $value = implode($sep, $value);
543
                }
544
                $o = $value;
545
                break;
546
        }
547
548
        return $o;
549
    }
550
}
551
552
if (! function_exists('decodeParamValue')) {
553
    /**
554
     * @param string $s
555
     * @return string
556
     */
557
    function decodeParamValue($s)
0 ignored issues
show
Comprehensibility introduced by
Avoid variables with short names like $s. Configured minimum length is 3.

Short variable names may make your code harder to understand. Variable names should be self-descriptive. This check looks for variable names who are shorter than a configured minimum.

Loading history...
558
    {
559
        $s = str_replace("%3D", '=', $s); // =
560
561
        return str_replace("%26", '&', $s); // &
562
    }
563
}
564
565
if (! function_exists('parseInput')) {
566
    /**
567
     * returns an array if a delimiter is present. returns array is a recordset is present
568
     *
569
     * @param $src
570
     * @param string $delim
571
     * @param string $type
572
     * @param bool $columns
573
     * @return array|string
574
     */
575
    function parseInput($src, $delim = "||", $type = "string", $columns = true)
576
    { // type can be: string, array
577
        $modx = evolutionCMS();
578
        if ($modx->db->isResult($src)) {
579
            // must be a recordset
580
            $rows = array();
581
            while ($cols = $modx->db->getRow($src, 'num')) {
582
                $rows[] = ($columns) ? $cols : implode(" ", $cols);
583
            }
584
585
            return ($type == "array") ? $rows : implode($delim, $rows);
586
        } else {
587
            // must be a text
588
            if ($type == "array") {
589
                return explode($delim, $src);
590
            } else {
591
                return $src;
592
            }
593
        }
594
    }
595
}
596
597
if (! function_exists('getUnixtimeFromDateString')) {
598
    /**
599
     * @param string $value
600
     * @return bool|false|int
601
     */
602
    function getUnixtimeFromDateString($value)
603
    {
604
        $timestamp = false;
605
        // Check for MySQL or legacy style date
606
        $date_match_1 = '/^([0-9]{2})-([0-9]{2})-([0-9]{4})\ ([0-9]{2}):([0-9]{2}):([0-9]{2})$/';
607
        $date_match_2 = '/^([0-9]{4})-([0-9]{2})-([0-9]{2})\ ([0-9]{2}):([0-9]{2}):([0-9]{2})$/';
608
        $matches = array();
609
        if (strpos($value, '-') !== false) {
610
            if (preg_match($date_match_1, $value, $matches)) {
611
                $timestamp = mktime($matches[4], $matches[5], $matches[6], $matches[2], $matches[1], $matches[3]);
612
            } elseif (preg_match($date_match_2, $value, $matches)) {
613
                $timestamp = mktime($matches[4], $matches[5], $matches[6], $matches[2], $matches[3], $matches[1]);
614
            }
615
        }
616
        // If those didn't work, use strtotime to figure out the date
617
        if ($timestamp === false || $timestamp === -1) {
618
            $timestamp = strtotime($value);
619
        }
620
621
        return $timestamp;
622
    }
623
}
624
625
if (! function_exists('renderFormElement')) {
626
    /**
627
     * DISPLAY FORM ELEMENTS
628
     *
629
     * @param string $field_type
630
     * @param string $field_id
631
     * @param string $default_text
632
     * @param string $field_elements
633
     * @param string $field_value
634
     * @param string $field_style
635
     * @param array $row
636
     * @param array $tvsArray
637
     * @return string
638
     */
639
    function renderFormElement(
640
        $field_type,
641
        $field_id,
642
        $default_text = '',
643
        $field_elements = '',
644
        $field_value = '',
645
        $field_style = '',
646
        $row = array(),
647
        $tvsArray = array()
648
    ) {
649
        $modx = evolutionCMS();
650
        global $_style;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
651
        global $_lang;
652
        global $content;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
653
        global $which_browser;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
654
655
        if (substr($default_text, 0, 6) === '@@EVAL' && $field_value === $default_text) {
656
            $eval_str = trim(substr($default_text, 7));
657
            $default_text = eval($eval_str);
0 ignored issues
show
Coding Style introduced by
The function renderFormElement() contains an eval expression.

On one hand, eval might be exploited by malicious users if they somehow manage to inject dynamic content. On the other hand, with the emergence of faster PHP runtimes like the HHVM, eval prevents some optimization that they perform.

Loading history...
658
            $field_value = $default_text;
659
        }
660
661
        $field_html = '';
662
        $cimode = strpos($field_type, ':');
663
        if ($cimode === false) {
664
            switch ($field_type) {
665
666
                case "text": // handler for regular text boxes
667 View Code Duplication
                case "rawtext"; // non-htmlentity converted text boxes
0 ignored issues
show
Coding Style introduced by
case statements should be defined using a colon.

As per the PSR-2 coding standard, case statements should not be wrapped in curly braces. There is no need for braces, since each case is terminated by the next break.

There is also the option to use a semicolon instead of a colon, this is discouraged because many programmers do not even know it works and the colon is universal between programming languages.

switch ($expr) {
    case "A": { //wrong
        doSomething();
        break;
    }
    case "B"; //wrong
        doSomething();
        break;
    case "C": //right
        doSomething();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
668
                    $field_html .= '<input type="text" id="tv' . $field_id . '" name="tv' . $field_id . '" value="' . $modx->htmlspecialchars($field_value) . '" ' . $field_style . ' tvtype="' . $field_type . '" onchange="documentDirty=true;" style="width:100%" />';
669
                    break;
670 View Code Duplication
                case "email": // handles email input fields
671
                    $field_html .= '<input type="email" id="tv' . $field_id . '" name="tv' . $field_id . '" value="' . $modx->htmlspecialchars($field_value) . '" ' . $field_style . ' tvtype="' . $field_type . '" onchange="documentDirty=true;" style="width:100%"/>';
672
                    break;
673 View Code Duplication
                case "number": // handles the input of numbers
674
                    $field_html .= '<input type="number" id="tv' . $field_id . '" name="tv' . $field_id . '" value="' . $modx->htmlspecialchars($field_value) . '" ' . $field_style . ' tvtype="' . $field_type . '" onchange="documentDirty=true;" style="width:100%" onkeyup="this.value=this.value.replace(/[^\d-,.+]/,\'\')"/>';
675
                    break;
676 View Code Duplication
                case "textareamini": // handler for textarea mini boxes
677
                    $field_html .= '<textarea id="tv' . $field_id . '" name="tv' . $field_id . '" cols="40" rows="5" onchange="documentDirty=true;" style="width:100%">' . $modx->htmlspecialchars($field_value) . '</textarea>';
678
                    break;
679
                case "textarea": // handler for textarea boxes
680
                case "rawtextarea": // non-htmlentity convertex textarea boxes
681
                case "htmlarea": // handler for textarea boxes (deprecated)
682 View Code Duplication
                case "richtext": // handler for textarea boxes
683
                    $field_html .= '<textarea id="tv' . $field_id . '" name="tv' . $field_id . '" cols="40" rows="15" onchange="documentDirty=true;" style="width:100%">' . $modx->htmlspecialchars($field_value) . '</textarea>';
684
                    break;
685
                case "date":
686
                    $field_id = str_replace(array(
687
                        '-',
688
                        '.'
689
                    ), '_', urldecode($field_id));
690
                    if ($field_value == '') {
691
                        $field_value = 0;
692
                    }
693
                    $field_html .= '<input id="tv' . $field_id . '" name="tv' . $field_id . '" class="DatePicker" type="text" value="' . ($field_value == 0 || !isset($field_value) ? "" : $field_value) . '" onblur="documentDirty=true;" />';
694
                    $field_html .= ' <a onclick="document.forms[\'mutate\'].elements[\'tv' . $field_id . '\'].value=\'\';document.forms[\'mutate\'].elements[\'tv' . $field_id . '\'].onblur(); return true;" onmouseover="window.status=\'clear the date\'; return true;" onmouseout="window.status=\'\'; return true;" style="cursor:pointer; cursor:hand"><i class="' . $_style["actions_calendar_delete"] . '"></i></a>';
695
696
                    break;
697 View Code Duplication
                case "dropdown": // handler for select boxes
698
                    $field_html .= '<select id="tv' . $field_id . '" name="tv' . $field_id . '" size="1" onchange="documentDirty=true;">';
699
                    $index_list = ParseIntputOptions(ProcessTVCommand($field_elements, $field_id, '', 'tvform',
700
                        $tvsArray));
701
                    while (list($item, $itemvalue) = each($index_list)) {
702
                        list($item, $itemvalue) = (is_array($itemvalue)) ? $itemvalue : explode("==", $itemvalue);
703
                        if (strlen($itemvalue) == 0) {
704
                            $itemvalue = $item;
705
                        }
706
                        $field_html .= '<option value="' . $modx->htmlspecialchars($itemvalue) . '"' . ($itemvalue == $field_value ? ' selected="selected"' : '') . '>' . $modx->htmlspecialchars($item) . '</option>';
707
                    }
708
                    $field_html .= "</select>";
709
                    break;
710 View Code Duplication
                case "listbox": // handler for select boxes
711
                    $field_html .= '<select id="tv' . $field_id . '" name="tv' . $field_id . '" onchange="documentDirty=true;" size="8">';
712
                    $index_list = ParseIntputOptions(ProcessTVCommand($field_elements, $field_id, '', 'tvform',
713
                        $tvsArray));
714
                    while (list($item, $itemvalue) = each($index_list)) {
715
                        list($item, $itemvalue) = (is_array($itemvalue)) ? $itemvalue : explode("==", $itemvalue);
716
                        if (strlen($itemvalue) == 0) {
717
                            $itemvalue = $item;
718
                        }
719
                        $field_html .= '<option value="' . $modx->htmlspecialchars($itemvalue) . '"' . ($itemvalue == $field_value ? ' selected="selected"' : '') . '>' . $modx->htmlspecialchars($item) . '</option>';
720
                    }
721
                    $field_html .= "</select>";
722
                    break;
723
                case "listbox-multiple": // handler for select boxes where you can choose multiple items
724
                    $field_value = explode("||", $field_value);
725
                    $field_html .= '<select id="tv' . $field_id . '" name="tv' . $field_id . '[]" multiple="multiple" onchange="documentDirty=true;" size="8">';
726
                    $index_list = ParseIntputOptions(ProcessTVCommand($field_elements, $field_id, '', 'tvform',
727
                        $tvsArray));
728
                    while (list($item, $itemvalue) = each($index_list)) {
729
                        list($item, $itemvalue) = (is_array($itemvalue)) ? $itemvalue : explode("==", $itemvalue);
730
                        if (strlen($itemvalue) == 0) {
731
                            $itemvalue = $item;
732
                        }
733
                        $field_html .= '<option value="' . $modx->htmlspecialchars($itemvalue) . '"' . (in_array($itemvalue,
734
                                $field_value) ? ' selected="selected"' : '') . '>' . $modx->htmlspecialchars($item) . '</option>';
735
                    }
736
                    $field_html .= "</select>";
737
                    break;
738
                case "url": // handles url input fields
739
                    $urls = array(
740
                        ''         => '--',
741
                        'http://'  => 'http://',
742
                        'https://' => 'https://',
743
                        'ftp://'   => 'ftp://',
744
                        'mailto:'  => 'mailto:'
745
                    );
746
                    $field_html = '<table border="0" cellspacing="0" cellpadding="0"><tr><td><select id="tv' . $field_id . '_prefix" name="tv' . $field_id . '_prefix" onchange="documentDirty=true;">';
747
                    foreach ($urls as $k => $v) {
748
                        if (strpos($field_value, $v) === false) {
749
                            $field_html .= '<option value="' . $v . '">' . $k . '</option>';
750
                        } else {
751
                            $field_value = str_replace($v, '', $field_value);
752
                            $field_html .= '<option value="' . $v . '" selected="selected">' . $k . '</option>';
753
                        }
754
                    }
755
                    $field_html .= '</select></td><td>';
756
                    $field_html .= '<input type="text" id="tv' . $field_id . '" name="tv' . $field_id . '" value="' . $modx->htmlspecialchars($field_value) . '" width="100" ' . $field_style . ' onchange="documentDirty=true;" /></td></tr></table>';
757
                    break;
758
                case 'checkbox': // handles check boxes
759
                    $values = !is_array($field_value) ? explode('||', $field_value) : $field_value;
760
                    $index_list = ParseIntputOptions(ProcessTVCommand($field_elements, $field_id, '', 'tvform',
761
                        $tvsArray));
762
                    $tpl = '<label class="checkbox"><input type="checkbox" value="%s" id="tv_%s" name="tv%s[]" %s onchange="documentDirty=true;" />%s</label><br />';
763
                    static $i = 0;
764
                    $_ = array();
0 ignored issues
show
Comprehensibility introduced by
Avoid variables with short names like $_. Configured minimum length is 3.

Short variable names may make your code harder to understand. Variable names should be self-descriptive. This check looks for variable names who are shorter than a configured minimum.

Loading history...
765
                    foreach ($index_list as $c => $item) {
766
                        if (is_array($item)) {
767
                            $name = trim($item[0]);
768
                            $value = isset($item[1]) ? $item[1] : $name;
769
                        } else {
770
                            $item = trim($item);
771
                            list($name, $value) = (strpos($item, '==') !== false) ? explode('==', $item, 2) : array(
772
                                $item,
773
                                $item
774
                            );
775
                        }
776
                        $checked = in_array($value, $values) ? ' checked="checked"' : '';
777
                        $param = array(
778
                            $modx->htmlspecialchars($value),
779
                            $i,
780
                            $field_id,
781
                            $checked,
782
                            $name
783
                        );
784
                        $_[] = vsprintf($tpl, $param);
785
                        $i++;
786
                    }
787
                    $field_html = implode("\n", $_);
788
                    break;
789
                case "option": // handles radio buttons
790
                    $index_list = ParseIntputOptions(ProcessTVCommand($field_elements, $field_id, '', 'tvform',
791
                        $tvsArray));
792
                    static $i = 0;
793
                    while (list($item, $itemvalue) = each($index_list)) {
794
                        list($item, $itemvalue) = (is_array($itemvalue)) ? $itemvalue : explode("==", $itemvalue);
795
                        if (strlen($itemvalue) == 0) {
796
                            $itemvalue = $item;
797
                        }
798
                        $field_html .= '<input type="radio" value="' . $modx->htmlspecialchars($itemvalue) . '" id="tv_' . $i . '" name="tv' . $field_id . '" ' . ($itemvalue == $field_value ? 'checked="checked"' : '') . ' onchange="documentDirty=true;" /><label for="tv_' . $i . '" class="radio">' . $item . '</label><br />';
799
                        $i++;
800
                    }
801
                    break;
802 View Code Duplication
                case "image": // handles image fields using htmlarea image manager
803
                    global $_lang;
804
                    global $ResourceManagerLoaded;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
805
                    global $content, $use_editor, $which_editor;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
806
                    if (!$ResourceManagerLoaded && !(($content['richtext'] == 1 || $modx->manager->action == 4) && $use_editor == 1 && $which_editor == 3)) {
807
                        $field_html .= "
808
						<script type=\"text/javascript\">
809
							/* <![CDATA[ */
810
								var lastImageCtrl;
811
								var lastFileCtrl;
812
								function OpenServerBrowser(url, width, height ) {
813
									var iLeft = (screen.width  - width) / 2 ;
814
									var iTop  = (screen.height - height) / 2 ;
815
816
									var sOptions = 'toolbar=no,status=no,resizable=yes,dependent=yes' ;
817
									sOptions += ',width=' + width ;
818
									sOptions += ',height=' + height ;
819
									sOptions += ',left=' + iLeft ;
820
									sOptions += ',top=' + iTop ;
821
822
									var oWindow = window.open( url, 'FCKBrowseWindow', sOptions ) ;
823
								}			
824
								function BrowseServer(ctrl) {
825
									lastImageCtrl = ctrl;
826
									var w = screen.width * 0.5;
827
									var h = screen.height * 0.5;
828
									OpenServerBrowser('" . MODX_MANAGER_URL . "media/browser/{$which_browser}/browser.php?Type=images', w, h);
829
								}
830
								function BrowseFileServer(ctrl) {
831
									lastFileCtrl = ctrl;
832
									var w = screen.width * 0.5;
833
									var h = screen.height * 0.5;
834
									OpenServerBrowser('" . MODX_MANAGER_URL . "media/browser/{$which_browser}/browser.php?Type=files', w, h);
835
								}
836
								function SetUrlChange(el) {
837
									if ('createEvent' in document) {
838
										var evt = document.createEvent('HTMLEvents');
839
										evt.initEvent('change', false, true);
840
										el.dispatchEvent(evt);
841
									} else {
842
										el.fireEvent('onchange');
843
									}
844
								}
845
								function SetUrl(url, width, height, alt) {
846
									if(lastFileCtrl) {
847
										var c = document.getElementById(lastFileCtrl);
848
										if(c && c.value != url) {
849
										    c.value = url;
850
											SetUrlChange(c);
851
										}
852
										lastFileCtrl = '';
853
									} else if(lastImageCtrl) {
854
										var c = document.getElementById(lastImageCtrl);
855
										if(c && c.value != url) {
856
										    c.value = url;
857
											SetUrlChange(c);
858
										}
859
										lastImageCtrl = '';
860
									} else {
861
										return;
862
									}
863
								}
864
							/* ]]> */
865
						</script>";
866
                        $ResourceManagerLoaded = true;
867
                    }
868
                    $field_html .= '<input type="text" id="tv' . $field_id . '" name="tv' . $field_id . '"  value="' . $field_value . '" ' . $field_style . ' onchange="documentDirty=true;" /><input type="button" value="' . $_lang['insert'] . '" onclick="BrowseServer(\'tv' . $field_id . '\')" />';
869
                    break;
870 View Code Duplication
                case "file": // handles the input of file uploads
871
                    /* Modified by Timon for use with resource browser */
872
                    global $_lang;
873
                    global $ResourceManagerLoaded;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
874
                    global $content, $use_editor, $which_editor;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
875
                    if (!$ResourceManagerLoaded && !(($content['richtext'] == 1 || $modx->manager->action == 4) && $use_editor == 1 && $which_editor == 3)) {
876
                        /* I didn't understand the meaning of the condition above, so I left it untouched ;-) */
877
                        $field_html .= "
878
						<script type=\"text/javascript\">
879
							/* <![CDATA[ */
880
								var lastImageCtrl;
881
								var lastFileCtrl;
882
								function OpenServerBrowser(url, width, height ) {
883
									var iLeft = (screen.width  - width) / 2 ;
884
									var iTop  = (screen.height - height) / 2 ;
885
886
									var sOptions = 'toolbar=no,status=no,resizable=yes,dependent=yes' ;
887
									sOptions += ',width=' + width ;
888
									sOptions += ',height=' + height ;
889
									sOptions += ',left=' + iLeft ;
890
									sOptions += ',top=' + iTop ;
891
892
									var oWindow = window.open( url, 'FCKBrowseWindow', sOptions ) ;
893
								}
894
								function BrowseServer(ctrl) {
895
									lastImageCtrl = ctrl;
896
									var w = screen.width * 0.5;
897
									var h = screen.height * 0.5;
898
									OpenServerBrowser('" . MODX_MANAGER_URL . "media/browser/{$which_browser}/browser.php?Type=images', w, h);
899
								}
900
								function BrowseFileServer(ctrl) {
901
									lastFileCtrl = ctrl;
902
									var w = screen.width * 0.5;
903
									var h = screen.height * 0.5;
904
									OpenServerBrowser('" . MODX_MANAGER_URL . "media/browser/{$which_browser}/browser.php?Type=files', w, h);
905
								}
906
								function SetUrlChange(el) {
907
									if ('createEvent' in document) {
908
										var evt = document.createEvent('HTMLEvents');
909
										evt.initEvent('change', false, true);
910
										el.dispatchEvent(evt);
911
									} else {
912
										el.fireEvent('onchange');
913
									}
914
								}
915
								function SetUrl(url, width, height, alt) {
916
									if(lastFileCtrl) {
917
										var c = document.getElementById(lastFileCtrl);
918
										if(c && c.value != url) {
919
										    c.value = url;
920
											SetUrlChange(c);
921
										}
922
										lastFileCtrl = '';
923
									} else if(lastImageCtrl) {
924
										var c = document.getElementById(lastImageCtrl);
925
										if(c && c.value != url) {
926
										    c.value = url;
927
											SetUrlChange(c);
928
										}
929
										lastImageCtrl = '';
930
									} else {
931
										return;
932
									}
933
								}
934
							/* ]]> */
935
						</script>";
936
                        $ResourceManagerLoaded = true;
937
                    }
938
                    $field_html .= '<input type="text" id="tv' . $field_id . '" name="tv' . $field_id . '"  value="' . $field_value . '" ' . $field_style . ' onchange="documentDirty=true;" /><input type="button" value="' . $_lang['insert'] . '" onclick="BrowseFileServer(\'tv' . $field_id . '\')" />';
939
940
                    break;
941
942
                case 'custom_tv':
943
                    $custom_output = '';
944
                    /* If we are loading a file */
945
                    if (substr($field_elements, 0, 5) == "@FILE") {
946
                        $file_name = MODX_BASE_PATH . trim(substr($field_elements, 6));
947
                        if (!file_exists($file_name)) {
948
                            $custom_output = $file_name . ' does not exist';
949
                        } else {
950
                            $custom_output = file_get_contents($file_name);
951
                        }
952
                    } elseif (substr($field_elements, 0, 8) == '@INCLUDE') {
953
                        $file_name = MODX_BASE_PATH . trim(substr($field_elements, 9));
954 View Code Duplication
                        if (!file_exists($file_name)) {
955
                            $custom_output = $file_name . ' does not exist';
956
                        } else {
957
                            ob_start();
958
                            include $file_name;
959
                            $custom_output = ob_get_contents();
960
                            ob_end_clean();
961
                        }
962
                    } elseif (substr($field_elements, 0, 6) == "@CHUNK") {
963
                        $chunk_name = trim(substr($field_elements, 7));
964
                        $chunk_body = $modx->getChunk($chunk_name);
965
                        if ($chunk_body == false) {
966
                            $custom_output = $_lang['chunk_no_exist'] . '(' . $_lang['htmlsnippet_name'] . ':' . $chunk_name . ')';
967
                        } else {
968
                            $custom_output = $chunk_body;
969
                        }
970
                    } elseif (substr($field_elements, 0, 5) == "@EVAL") {
971
                        $eval_str = trim(substr($field_elements, 6));
972
                        $custom_output = eval($eval_str);
0 ignored issues
show
Coding Style introduced by
The function renderFormElement() contains an eval expression.

On one hand, eval might be exploited by malicious users if they somehow manage to inject dynamic content. On the other hand, with the emergence of faster PHP runtimes like the HHVM, eval prevents some optimization that they perform.

Loading history...
973
                    } else {
974
                        $custom_output = $field_elements;
975
                    }
976
                    $replacements = array(
977
                        '[+field_type+]'   => $field_type,
978
                        '[+field_id+]'     => $field_id,
979
                        '[+default_text+]' => $default_text,
980
                        '[+field_value+]'  => $modx->htmlspecialchars($field_value),
981
                        '[+field_style+]'  => $field_style,
982
                    );
983
                    $custom_output = str_replace(array_keys($replacements), $replacements, $custom_output);
984
                    $modx->documentObject = $content;
985
                    $modx->documentIdentifier = $content['id'];
986
                    $custom_output = $modx->parseDocumentSource($custom_output);
987
                    $field_html .= $custom_output;
988
                    break;
989
990 View Code Duplication
                default: // the default handler -- for errors, mostly
991
                    $field_html .= '<input type="text" id="tv' . $field_id . '" name="tv' . $field_id . '" value="' . $modx->htmlspecialchars($field_value) . '" ' . $field_style . ' onchange="documentDirty=true;" />';
992
993
            } // end switch statement
994
        } else {
995
            $custom = explode(":", $field_type);
996
            $custom_output = '';
997
            $file_name = MODX_BASE_PATH . 'assets/tvs/' . $custom['1'] . '/' . $custom['1'] . '.customtv.php';
998 View Code Duplication
            if (!file_exists($file_name)) {
999
                $custom_output = $file_name . ' does not exist';
1000
            } else {
1001
                ob_start();
1002
                include $file_name;
1003
                $custom_output = ob_get_contents();
1004
                ob_end_clean();
1005
            }
1006
            $replacements = array(
1007
                '[+field_type+]'   => $field_type,
1008
                '[+field_id+]'     => $field_id,
1009
                '[+default_text+]' => $default_text,
1010
                '[+field_value+]'  => $modx->htmlspecialchars($field_value),
1011
                '[+field_style+]'  => $field_style,
1012
            );
1013
            $custom_output = str_replace(array_keys($replacements), $replacements, $custom_output);
1014
            $modx->documentObject = $content;
1015
            $custom_output = $modx->parseDocumentSource($custom_output);
1016
            $field_html .= $custom_output;
1017
        }
1018
1019
        return $field_html;
1020
    } // end renderFormElement function
1021
}
1022
1023
if (! function_exists('ParseIntputOptions')) {
1024
    /**
1025
     * @param string|array|mysqli_result $v
1026
     * @return array
1027
     */
1028
    function ParseIntputOptions($v)
0 ignored issues
show
Comprehensibility introduced by
Avoid variables with short names like $v. Configured minimum length is 3.

Short variable names may make your code harder to understand. Variable names should be self-descriptive. This check looks for variable names who are shorter than a configured minimum.

Loading history...
Coding Style introduced by
As per coding-style, this function should be in camelCase.

CamelCase (...) is the practice of writing compound words or phrases such that
each word or abbreviation begins with a capital letter.

Learn more about camelCase.

Loading history...
1029
    {
1030
        $modx = evolutionCMS();
1031
        $a = array();
0 ignored issues
show
Comprehensibility introduced by
Avoid variables with short names like $a. Configured minimum length is 3.

Short variable names may make your code harder to understand. Variable names should be self-descriptive. This check looks for variable names who are shorter than a configured minimum.

Loading history...
1032
        if (is_array($v)) {
1033
            return $v;
1034
        } else {
1035
            if ($modx->db->isResult($v)) {
1036
                /**
1037
                 * @todo May be, should use DBAPI::makeArray($v);
0 ignored issues
show
Coding Style introduced by
Comment refers to a TODO task

This check looks TODO comments that have been left in the code.

``TODO``s show that something is left unfinished and should be attended to.

Loading history...
1038
                 */
1039
                while ($cols = $modx->db->getRow($v, 'num')) {
1040
                    $a[] = $cols;
1041
                }
1042
            } else {
1043
                $a = explode("||", $v);
1044
            }
1045
        }
1046
1047
        return $a;
1048
    }
1049
}
1050