GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.

Issues (3647)

symphony/lib/toolkit/class.datasource.php (44 issues)

1
<?php
2
3
/**
4
 * @package toolkit
5
 */
6
/**
7
 * The Datasource class provides functionality to mainly process any parameters
8
 * that the fields will use in filters find the relevant Entries and return these Entries
9
 * data as XML so that XSLT can be applied on it to create your website. In Symphony,
10
 * there are four Datasource types provided, Section, Author, Navigation and Dynamic
11
 * XML. Section is the mostly commonly used Datasource, which allows the filtering
12
 * and searching for Entries in a Section to be returned as XML. Navigation datasources
13
 * expose the Symphony Navigation structure of the Pages in the installation. Authors
14
 * expose the Symphony Authors that are registered as users of the backend. Finally,
15
 * the Dynamic XML datasource allows XML pages to be retrieved. This is especially
16
 * helpful for working with Restful XML API's. Datasources are saved through the
17
 * Symphony backend, which uses a Datasource template defined in
18
 * `TEMPLATE . /datasource.tpl`.
19
 */
20
21
class Datasource
22
{
23
    /**
24
     * A constant that represents if this filter is an AND filter in which
25
     * an Entry must match all these filters. This filter is triggered when
26
     * the filter string contains a ` + `.
27
     *
28
     * @since Symphony 2.3.2
29
     * @var integer
30
     */
31
    const FILTER_AND = 1;
32
33
    /**
34
     * A constant that represents if this filter is an OR filter in which an
35
     * entry can match any or all of these filters
36
     *
37
     * @since Symphony 2.3.2
38
     * @var integer
39
     */
40
    const FILTER_OR = 2;
41
42
    /**
43
     * Holds all the environment variables which include parameters set by
44
     * other Datasources or Events.
45
     * @var array
46
     */
47
    protected $_env = array();
48
49
    /**
50
     * If true, this datasource only will be outputting parameters from the
51
     * Entries, and no actual content.
52
     * @var boolean
53
     */
54
    protected $_param_output_only;
55
56
    /**
57
     * An array of datasource dependancies. These are datasources that must
58
     * run first for this datasource to be able to execute correctly
59
     * @var array
60
     */
61
    protected $_dependencies = array();
62
63
    /**
64
     * When there is no entries found by the Datasource, this parameter will
65
     * be set to true, which will inject the default Symphony 'No records found'
66
     * message into the datasource's result
67
     * @var boolean
68
     */
69
    protected $_force_empty_result = false;
70
71
    /**
72
     * When there is a negating parameter, this parameter will
73
     * be set to true, which will inject the default Symphony 'Results Negated'
74
     * message into the datasource's result
75
     * @var boolean
76
     */
77
    protected $_negate_result = false;
78
79
    /**
80
     * Constructor for the datasource sets the parent, if `$process_params` is set,
81
     * the `$env` variable will be run through `Datasource::processParameters`.
82
     *
83
     * @see toolkit.Datasource#processParameters()
84
     * @param array $env
85
     *  The environment variables from the Frontend class which includes
86
     *  any params set by Symphony or Events or by other Datasources
87
     * @param boolean $process_params
88
     *  If set to true, `Datasource::processParameters` will be called. By default
89
     *  this is true
90
     * @throws FrontendPageNotFoundException
91
     */
92
    public function __construct(array $env = null, $process_params = true)
0 ignored issues
show
Incorrect spacing between argument "$env" and equals sign; expected 0 but found 1
Loading history...
Incorrect spacing between default value and equals sign for argument "$env"; expected 0 but found 1
Loading history...
Incorrect spacing between argument "$process_params" and equals sign; expected 0 but found 1
Loading history...
Incorrect spacing between default value and equals sign for argument "$process_params"; expected 0 but found 1
Loading history...
93
    {
94
        // Support old the __construct (for the moment anyway).
95
        // The old signature was array/array/boolean
96
        // The new signature is array/boolean
97
        $arguments = func_get_args();
98
99
        if (count($arguments) == 3 && is_bool($arguments[1]) && is_bool($arguments[2])) {
100
            $env = $arguments[0];
101
            $process_params = $arguments[1];
102
        }
103
104
        if ($process_params) {
105
            $this->processParameters($env);
106
        }
107
    }
108
109
    /**
110
     * This function is required in order to edit it in the datasource editor page.
111
     * Do not overload this function if you are creating a custom datasource. It is only
112
     * used by the datasource editor. If this is set to false, which is default, the
113
     * Datasource's `about()` information will be displayed.
114
     *
115
     * @return boolean
116
     *   true if the Datasource can be edited, false otherwise. Defaults to false
117
     */
118
    public function allowEditorToParse()
119
    {
120
        return false;
121
    }
122
123
    /**
124
     * This function is required in order to identify what section this Datasource is for. It
125
     * is used in the datasource editor. It must remain intact. Do not overload this function in
126
     * custom events. Other datasources may return a string here defining their datasource
127
     * type when they do not query a section.
128
     *
129
     * @return mixed
130
     */
131
    public function getSource()
132
    {
133
        return null;
134
    }
135
136
    /**
137
     * Accessor function to return this Datasource's dependencies
138
     *
139
     * @return array
140
     */
141
    public function getDependencies()
142
    {
143
        return $this->_dependencies;
144
    }
145
146
    /**
147
     * Returns an associative array of information about a datasource.
148
     *
149
     * @return array
150
     */
151
    public function about()
152
    {
153
        return array();
154
    }
155
156
    /**
157
     * @deprecated This function has been renamed to `execute` as of
158
     *  Symphony 2.3.1, please use `execute()` instead. This function will
159
     *  be removed in Symphony 3.0
160
     * @see execute()
161
     */
162
    public function grab(array &$param_pool = null)
0 ignored issues
show
Incorrect spacing between argument "$param_pool" and equals sign; expected 0 but found 1
Loading history...
Incorrect spacing between default value and equals sign for argument "$param_pool"; expected 0 but found 1
Loading history...
163
    {
164
        if (Symphony::Log()) {
165
            Symphony::Log()->pushDeprecateWarningToLog('Datasource::grab()', 'Datasource::execute()');
166
        }
0 ignored issues
show
No blank line found after control structure
Loading history...
167
        return $this->execute($param_pool);
168
    }
169
170
    /**
171
     * The meat of the Datasource, this function includes the datasource
172
     * type's file that will preform the logic to return the data for this datasource
173
     * It is passed the current parameters.
174
     *
175
     * @param array $param_pool
176
     *  The current parameter pool that this Datasource can use when filtering
177
     *  and finding Entries or data.
178
     * @return XMLElement
179
     *  The XMLElement to add into the XML for a page.
180
     */
181
    public function execute(array &$param_pool = null)
0 ignored issues
show
Incorrect spacing between argument "$param_pool" and equals sign; expected 0 but found 1
Loading history...
Incorrect spacing between default value and equals sign for argument "$param_pool"; expected 0 but found 1
Loading history...
182
    {
183
        $result = new XMLElement($this->dsParamROOTELEMENT);
0 ignored issues
show
Bug Best Practice introduced by
The property dsParamROOTELEMENT does not exist on Datasource. Did you maybe forget to declare it?
Loading history...
The assignment to $result is dead and can be removed.
Loading history...
184
185
        try {
186
            $result = $this->execute($param_pool);
187
        } catch (FrontendPageNotFoundException $e) {
188
            // Work around. This ensures the 404 page is displayed and
189
            // is not picked up by the default catch() statement below
190
            FrontendPageNotFoundExceptionHandler::render($e);
191
        } catch (Exception $e) {
192
            $result->appendChild(new XMLElement('error', General::wrapInCDATA($e->getMessage())));
193
            return $result;
194
        }
195
196
        if ($this->_force_empty_result) {
197
            $result = $this->emptyXMLSet();
198
        }
199
200
        if ($this->_negate_result) {
201
            $result = $this->negateXMLSet();
202
        }
203
204
        return $result;
205
    }
206
207
    /**
208
     * By default, all Symphony filters are considering to be OR and " + " filters
209
     * are used for AND. They are all used and Entries must match each filter to be included.
210
     * It is possible to use OR filtering in a field by using an ", " to separate the values.
211
     *
212
     * If the filter is "test1, test2", this will match any entries where this field
213
     * is test1 OR test2. If the filter is "test1 + test2", this will match entries
214
     * where this field is test1 AND test2. The spaces around the + are required.
215
     *
216
     * Not all fields supports this feature.
217
     *
218
     * This function is run on each filter (ie. each field) in a datasource.
219
     *
220
     * @param string $value
221
     *  The filter string for a field.
222
     * @return integer
223
     *  Datasource::FILTER_OR or Datasource::FILTER_AND
224
     */
225
    public static function determineFilterType($value)
226
    {
227
        // Check for two possible combos
228
        //  1. The old pattern, which is ' + '
229
        //  2. A new pattern, which accounts for '+' === ' ' in urls
230
        $pattern = '/(\s+\+\s+)|(\+\+\+)/';
231
        return preg_match($pattern, $value) === 1 ? Datasource::FILTER_AND : Datasource::FILTER_OR;
0 ignored issues
show
Inline shorthand IF statement requires brackets around comparison
Loading history...
232
    }
233
234
    /**
235
     * Splits the filter string value into an array.
236
     *
237
     * @since Symphony 2.7.0
238
     * @param int $filter_type
239
     *  The filter's type, as determined by `determineFilterType()`.
240
     *  Valid values are Datasource::FILTER_OR or Datasource::FILTER_AND
241
     * @param string $value
242
     *  The filter's value
243
     * @return array
244
     *  The splitted filter value, according to its type
245
     */
246
    public static function splitFilter($filter_type, $value)
247
    {
248
        $pattern = $filter_type === Datasource::FILTER_AND ? '\+' : '(?<!\\\\),';
0 ignored issues
show
Inline shorthand IF statement requires brackets around comparison
Loading history...
249
        $value = preg_split('/\s*' . $pattern . '\s*/', $value, -1, PREG_SPLIT_NO_EMPTY);
250
        $value = array_map('trim', $value);
0 ignored issues
show
It seems like $value can also be of type false; however, parameter $arr1 of array_map() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

250
        $value = array_map('trim', /** @scrutinizer ignore-type */ $value);
Loading history...
251
        $value = array_map(array('Datasource', 'removeEscapedCommas'), $value);
252
        return $value;
253
    }
254
255
    /**
256
     * If there is no results to return this function calls `Datasource::__noRecordsFound`
257
     * which appends an XMLElement to the current root element.
258
     *
259
     * @param XMLElement $xml
260
     *  The root element XMLElement for this datasource. By default, this will
261
     *  the handle of the datasource, as defined by `$this->dsParamROOTELEMENT`
262
     * @return XMLElement
263
     */
264
    public function emptyXMLSet(XMLElement $xml = null)
0 ignored issues
show
Incorrect spacing between argument "$xml" and equals sign; expected 0 but found 1
Loading history...
Incorrect spacing between default value and equals sign for argument "$xml"; expected 0 but found 1
Loading history...
265
    {
266
        if (is_null($xml)) {
267
            $xml = new XMLElement($this->dsParamROOTELEMENT);
0 ignored issues
show
Bug Best Practice introduced by
The property dsParamROOTELEMENT does not exist on Datasource. Did you maybe forget to declare it?
Loading history...
268
        }
269
270
        $xml->appendChild($this->__noRecordsFound());
271
272
        return $xml;
273
    }
274
275
    /**
276
     * If the datasource has been negated this function calls `Datasource::__negateResult`
277
     * which appends an XMLElement to the current root element.
278
     *
279
     * @param XMLElement $xml
280
     *  The root element XMLElement for this datasource. By default, this will
281
     *  the handle of the datasource, as defined by `$this->dsParamROOTELEMENT`
282
     * @return XMLElement
283
     */
284
    public function negateXMLSet(XMLElement $xml = null)
0 ignored issues
show
Incorrect spacing between argument "$xml" and equals sign; expected 0 but found 1
Loading history...
Incorrect spacing between default value and equals sign for argument "$xml"; expected 0 but found 1
Loading history...
285
    {
286
        if (is_null($xml)) {
287
            $xml = new XMLElement($this->dsParamROOTELEMENT);
0 ignored issues
show
Bug Best Practice introduced by
The property dsParamROOTELEMENT does not exist on Datasource. Did you maybe forget to declare it?
Loading history...
288
        }
289
290
        $xml->appendChild($this->__negateResult());
291
292
        return $xml;
293
    }
294
295
    /**
296
     * Returns an error XMLElement with 'No records found' text
297
     *
298
     * @return XMLElement
299
     */
300
    public function __noRecordsFound()
301
    {
302
        return new XMLElement('error', __('No records found.'));
303
    }
304
305
    /**
306
     * Returns an error XMLElement with 'Result Negated' text
307
     *
308
     * @return XMLElement
309
     */
310
    public function __negateResult()
311
    {
312
        $error = new XMLElement('error', __("Data source not executed, forbidden parameter was found."), array(
0 ignored issues
show
Coding Style Comprehensibility introduced by
The string literal Data source not executed...en parameter was found. does not require double quotes, as per coding-style, please use single quotes.

PHP provides two ways to mark string literals. Either with single quotes 'literal' or with double quotes "literal". The difference between these is that string literals in double quotes may contain variables with are evaluated at run-time as well as escape sequences.

String literals in single quotes on the other hand are evaluated very literally and the only two characters that needs escaping in the literal are the single quote itself (\') and the backslash (\\). Every other character is displayed as is.

Double quoted string literals may contain other variables or more complex escape sequences.

<?php

$singleQuoted = 'Value';
$doubleQuoted = "\tSingle is $singleQuoted";

print $doubleQuoted;

will print an indented: Single is Value

If your string literal does not contain variables or escape sequences, it should be defined using single quotes to make that fact clear.

For more information on PHP string literals and available escape sequences see the PHP core documentation.

Loading history...
313
            'forbidden-param' => $this->dsParamNEGATEPARAM
0 ignored issues
show
Bug Best Practice introduced by
The property dsParamNEGATEPARAM does not exist on Datasource. Did you maybe forget to declare it?
Loading history...
314
        ));
315
316
        return $error;
317
    }
318
319
    /**
320
     * This function will iterates over the filters and replace any parameters with their
321
     * actual values. All other Datasource variables such as sorting, ordering and
322
     * pagination variables are also set by this function
323
     *
324
     * @param array $env
325
     *  The environment variables from the Frontend class which includes
326
     *  any params set by Symphony or Events or by other Datasources
327
     * @throws FrontendPageNotFoundException
328
     */
329
    public function processParameters(array $env = null)
0 ignored issues
show
Incorrect spacing between argument "$env" and equals sign; expected 0 but found 1
Loading history...
Incorrect spacing between default value and equals sign for argument "$env"; expected 0 but found 1
Loading history...
330
    {
331
        if ($env) {
332
            $this->_env = $env;
333
        }
334
335
        if ((isset($this->_env) && is_array($this->_env)) && isset($this->dsParamFILTERS) && is_array($this->dsParamFILTERS) && !empty($this->dsParamFILTERS)) {
336
            foreach ($this->dsParamFILTERS as $key => $value) {
337
                $value = stripslashes($value);
338
                $new_value = $this->__processParametersInString($value, $this->_env);
339
340
                // If a filter gets evaluated to nothing, eg. ` + ` or ``, then remove
341
                // the filter. Respects / as this may be real from current-path. RE: #1759
342
                if (strlen(trim($new_value)) === 0 || !preg_match('/[^\s|+|,]+/u', $new_value)) {
343
                    unset($this->dsParamFILTERS[$key]);
344
                } else {
345
                    $this->dsParamFILTERS[$key] = $new_value;
0 ignored issues
show
Bug Best Practice introduced by
The property dsParamFILTERS does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
346
                }
347
            }
348
        }
349
350
        if (isset($this->dsParamORDER)) {
351
            $this->dsParamORDER = $this->__processParametersInString($this->dsParamORDER, $this->_env);
0 ignored issues
show
Bug Best Practice introduced by
The property dsParamORDER does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
352
        }
353
354
        if (isset($this->dsParamSORT)) {
355
            $this->dsParamSORT = $this->__processParametersInString($this->dsParamSORT, $this->_env);
0 ignored issues
show
Bug Best Practice introduced by
The property dsParamSORT does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
356
        }
357
358
        if (isset($this->dsParamSTARTPAGE)) {
359
            $this->dsParamSTARTPAGE = $this->__processParametersInString($this->dsParamSTARTPAGE, $this->_env);
0 ignored issues
show
Bug Best Practice introduced by
The property dsParamSTARTPAGE does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
360
            if ($this->dsParamSTARTPAGE === '') {
361
                $this->dsParamSTARTPAGE = '1';
362
            }
363
        }
364
365
        if (isset($this->dsParamLIMIT)) {
366
            $this->dsParamLIMIT = $this->__processParametersInString($this->dsParamLIMIT, $this->_env);
0 ignored issues
show
Bug Best Practice introduced by
The property dsParamLIMIT does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
367
        }
368
369
        if (
0 ignored issues
show
Expected 0 spaces after opening bracket; newline found
Loading history...
370
            isset($this->dsParamREQUIREDPARAM)
371
            && strlen(trim($this->dsParamREQUIREDPARAM)) > 0
372
            && $this->__processParametersInString(trim($this->dsParamREQUIREDPARAM), $this->_env, false) === ''
373
        ) {
374
            $this->_force_empty_result = true; // don't output any XML
375
            $this->dsParamPARAMOUTPUT = null; // don't output any parameters
0 ignored issues
show
Bug Best Practice introduced by
The property dsParamPARAMOUTPUT does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
376
            $this->dsParamINCLUDEDELEMENTS = null; // don't query any fields in this section
0 ignored issues
show
Bug Best Practice introduced by
The property dsParamINCLUDEDELEMENTS does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
377
            return;
378
        }
379
380
        if (
0 ignored issues
show
Expected 0 spaces after opening bracket; newline found
Loading history...
381
            isset($this->dsParamNEGATEPARAM)
382
            && strlen(trim($this->dsParamNEGATEPARAM)) > 0
383
            && $this->__processParametersInString(trim($this->dsParamNEGATEPARAM), $this->_env, false) !== ''
384
        ) {
385
            $this->_negate_result = true; // don't output any XML
386
            $this->dsParamPARAMOUTPUT = null; // don't output any parameters
387
            $this->dsParamINCLUDEDELEMENTS = null; // don't query any fields in this section
388
            return;
389
        }
390
391
        $this->_param_output_only = ((!isset($this->dsParamINCLUDEDELEMENTS) || !is_array($this->dsParamINCLUDEDELEMENTS) || empty($this->dsParamINCLUDEDELEMENTS)) && !isset($this->dsParamGROUP));
0 ignored issues
show
The property dsParamGROUP does not exist on Datasource. Did you mean dsParamSORT?
Loading history...
392
393
        if (isset($this->dsParamREDIRECTONEMPTY) && $this->dsParamREDIRECTONEMPTY === 'yes' && $this->_force_empty_result) {
394
            throw new FrontendPageNotFoundException;
395
        }
396
    }
397
398
    /**
399
     * This function will parse a string (usually a URL) and fully evaluate any
400
     * parameters (defined by {$param}) to return the absolute string value.
401
     *
402
     * @since Symphony 2.3
403
     * @param string $url
404
     *  The string (usually a URL) that contains the parameters (or doesn't)
405
     * @return string
406
     *  The parsed URL
407
     */
408
    public function parseParamURL($url = null)
0 ignored issues
show
Incorrect spacing between argument "$url" and equals sign; expected 0 but found 1
Loading history...
Incorrect spacing between default value and equals sign for argument "$url"; expected 0 but found 1
Loading history...
409
    {
410
        if (!isset($url)) {
411
            return null;
412
        }
413
414
        // urlencode parameters
415
        $params = array();
416
417
        if (preg_match_all('@{([^}]+)}@i', $url, $matches, PREG_SET_ORDER)) {
418
            foreach ($matches as $m) {
419
                $params[$m[1]] = array(
420
                    'param' => preg_replace('/:encoded$/', null, $m[1]),
421
                    'encode' => preg_match('/:encoded$/', $m[1])
422
                );
423
            }
424
        }
425
426
        foreach ($params as $key => $info) {
427
            $replacement = $this->__processParametersInString($info['param'], $this->_env, false);
428
            if ($info['encode'] == true) {
429
                $replacement = urlencode($replacement);
430
            }
0 ignored issues
show
No blank line found after control structure
Loading history...
431
            $url = str_replace("{{$key}}", $replacement, $url);
0 ignored issues
show
Coding Style Best Practice introduced by
As per coding-style, please use concatenation or sprintf for the variable $key instead of interpolation.

It is generally a best practice as it is often more readable to use concatenation instead of interpolation for variables inside strings.

// Instead of
$x = "foo $bar $baz";

// Better use either
$x = "foo " . $bar . " " . $baz;
$x = sprintf("foo %s %s", $bar, $baz);
Loading history...
432
        }
433
434
        return $url;
435
    }
436
437
    /**
438
     * This function will replace any parameters in a string with their value.
439
     * Parameters are defined by being prefixed by a `$` character. In certain
440
     * situations, the parameter will be surrounded by `{}`, which Symphony
441
     * takes to mean, evaluate this parameter to a value, other times it will be
442
     * omitted which is usually used to indicate that this parameter exists
443
     *
444
     * @param string $value
445
     *  The string with the parameters that need to be evaluated
446
     * @param array $env
447
     *  The environment variables from the Frontend class which includes
448
     *  any params set by Symphony or Events or by other Datasources
449
     * @param boolean $includeParenthesis
450
     *  Parameters will sometimes not be surrounded by `{}`. If this is the case
451
     *  setting this parameter to false will make this function automatically add
452
     *  them to the parameter. By default this is true, which means all parameters
453
     *  in the string already are surrounded by `{}`
454
     * @param boolean $escape
455
     *  If set to true, the resulting value will passed through `urlencode` before
456
     *  being returned. By default this is `false`
457
     * @return string
458
     *  The string with all parameters evaluated. If a parameter is not found, it will
459
     *  not be replaced and remain in the `$value`.
460
     */
461
    public function __processParametersInString($value, array $env, $includeParenthesis = true, $escape = false)
0 ignored issues
show
Incorrect spacing between argument "$includeParenthesis" and equals sign; expected 0 but found 1
Loading history...
Incorrect spacing between default value and equals sign for argument "$includeParenthesis"; expected 0 but found 1
Loading history...
Incorrect spacing between argument "$escape" and equals sign; expected 0 but found 1
Loading history...
Incorrect spacing between default value and equals sign for argument "$escape"; expected 0 but found 1
Loading history...
462
    {
463
        if (trim($value) == '') {
464
            return null;
465
        }
466
467
        if (!$includeParenthesis) {
468
            $value = '{'.$value.'}';
469
        }
470
471
        if (preg_match_all('@{([^}]+)}@i', $value, $matches, PREG_SET_ORDER)) {
472
            foreach ($matches as $match) {
473
                list($source, $cleaned) = $match;
474
475
                $replacement = null;
476
477
                $bits = preg_split('/:/', $cleaned, -1, PREG_SPLIT_NO_EMPTY);
478
479
                foreach ($bits as $param) {
480
                    if ($param{0} !== '$') {
481
                        $replacement = $param;
482
                        break;
483
                    }
484
485
                    $param = trim($param, '$');
486
487
                    $replacement = Datasource::findParameterInEnv($param, $env);
488
489
                    if (is_array($replacement)) {
490
                        $replacement = array_map(array('Datasource', 'escapeCommas'), $replacement);
491
                        if (count($replacement) > 1) {
492
                            $replacement = implode(',', $replacement);
493
                        } else {
494
                            $replacement = end($replacement);
495
                        }
496
                    }
497
498
                    if (!empty($replacement)) {
499
                        break;
500
                    }
501
                }
502
503
                if ($escape) {
504
                    $replacement = urlencode($replacement);
505
                }
506
507
                $value = str_replace($source, $replacement, $value);
508
            }
509
        }
510
511
        return $value;
512
    }
513
514
    /**
515
     * Using regexp, this escapes any commas in the given string
516
     *
517
     * @param string $string
518
     *  The string to escape the commas in
519
     * @return string
520
     */
521
    public static function escapeCommas($string)
522
    {
523
        return preg_replace('/(?<!\\\\),/', "\\,", $string);
0 ignored issues
show
Coding Style Comprehensibility introduced by
The string literal \\, does not require double quotes, as per coding-style, please use single quotes.

PHP provides two ways to mark string literals. Either with single quotes 'literal' or with double quotes "literal". The difference between these is that string literals in double quotes may contain variables with are evaluated at run-time as well as escape sequences.

String literals in single quotes on the other hand are evaluated very literally and the only two characters that needs escaping in the literal are the single quote itself (\') and the backslash (\\). Every other character is displayed as is.

Double quoted string literals may contain other variables or more complex escape sequences.

<?php

$singleQuoted = 'Value';
$doubleQuoted = "\tSingle is $singleQuoted";

print $doubleQuoted;

will print an indented: Single is Value

If your string literal does not contain variables or escape sequences, it should be defined using single quotes to make that fact clear.

For more information on PHP string literals and available escape sequences see the PHP core documentation.

Loading history...
524
    }
525
526
    /**
527
     * Used in conjunction with escapeCommas, this function will remove
528
     * the escaping pattern applied to the string (and commas)
529
     *
530
     * @param string $string
531
     *  The string with the escaped commas in it to remove
532
     * @return string
533
     */
534
    public static function removeEscapedCommas($string)
535
    {
536
        return preg_replace('/(?<!\\\\)\\\\,/', ',', $string);
537
    }
538
539
    /**
540
     * Parameters can exist in three different facets of Symphony; in the URL,
541
     * in the parameter pool or as an Symphony param. This function will attempt
542
     * to find a parameter in those three areas and return the value. If it is not found
543
     * null is returned
544
     *
545
     * @param string $needle
546
     *  The parameter name
547
     * @param array $env
548
     *  The environment variables from the Frontend class which includes
549
     *  any params set by Symphony or Events or by other Datasources
550
     * @return mixed
551
     *  If the value is not found, null, otherwise a string or an array is returned
552
     */
553
    public static function findParameterInEnv($needle, $env)
554
    {
555
        if (isset($env['env']['url'][$needle])) {
556
            return $env['env']['url'][$needle];
557
        }
558
559
        if (isset($env['env']['pool'][$needle])) {
560
            return $env['env']['pool'][$needle];
561
        }
562
563
        if (isset($env['param'][$needle])) {
564
            return $env['param'][$needle];
565
        }
566
567
        return null;
568
    }
569
570
    /**
571
     * By default, all Symphony filters are considering to be OR and "+" filters
572
     * are used for AND. They are all used and Entries must match each filter to be included.
573
     * It is possible to use OR filtering in a field by using an "," to separate the values.
574
     * eg. If the filter is "test1, test2", this will match any entries where this field
575
     * is test1 OR test2. If the filter is "test1 + test2", this will match entries
576
     * where this field is test1 AND test2. Not all fields supports this feature.
577
     * This function is run on each filter (ie. each field) in a datasource.
578
     *
579
     * @deprecated Since Symphony 2.6.0 it is recommended to use the static version,
580
     *  `Datasource::determineFilterType`
581
     * @param string $value
582
     *  The filter string for a field.
583
     * @return integer
584
     *  Datasource::FILTER_OR or Datasource::FILTER_AND
585
     */
586
    public function __determineFilterType($value)
587
    {
588
        if (Symphony::Log()) {
589
            Symphony::Log()->pushDeprecateWarningToLog('Datasource::__determineFilterType()', 'Datasource::determineFilterType()');
590
        }
0 ignored issues
show
No blank line found after control structure
Loading history...
591
        return self::determineFilterType($value);
592
    }
593
}
594