Scrutinizer GitHub App not installed

We could not synchronize checks via GitHub's checks API since Scrutinizer's GitHub App is not installed for this repository.

Install GitHub App

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.
Completed
Push — master ( ccdfd2...d635f9 )
by Sebastian
13s queued 11s
created

tx_dlf_solr::__set()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 15
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 6
dl 0
loc 15
rs 10
c 0
b 0
f 0
cc 4
nc 3
nop 2
1
<?php
2
/**
3
 * (c) Kitodo. Key to digital objects e.V. <[email protected]>
4
 *
5
 * This file is part of the Kitodo and TYPO3 projects.
6
 *
7
 * @license GNU General Public License version 3 or later.
8
 * For the full copyright and license information, please read the
9
 * LICENSE.txt file that was distributed with this source code.
10
 */
11
12
/**
13
 * Solr class 'tx_dlf_solr' for the 'dlf' extension.
14
 *
15
 * @author	Sebastian Meyer <[email protected]>
16
 * @author	Henrik Lochmann <[email protected]>
17
 * @package	TYPO3
18
 * @subpackage	tx_dlf
19
 * @access	public
20
 */
21
class tx_dlf_solr {
22
23
    /**
24
     * This holds the core name
25
     *
26
     * @var	string
27
     * @access protected
28
     */
29
    protected $core = '';
30
31
    /**
32
     * This holds the PID for the configuration
33
     *
34
     * @var	integer
35
     * @access protected
36
     */
37
    protected $cPid = 0;
38
39
    /**
40
     * The extension key
41
     *
42
     * @var	string
43
     * @access public
44
     */
45
    public static $extKey = 'dlf';
46
47
    /**
48
     * This holds the max results
49
     *
50
     * @var	integer
51
     * @access protected
52
     */
53
    protected $limit = 50000;
54
55
    /**
56
     * This holds the number of hits for last search
57
     *
58
     * @var	integer
59
     * @access protected
60
     */
61
    protected $numberOfHits = 0;
62
63
    /**
64
     * This holds the additional query parameters
65
     *
66
     * @var	array
67
     * @access protected
68
     */
69
    protected $params = array ();
70
71
    /**
72
     * Is the search instantiated successfully?
73
     *
74
     * @var	boolean
75
     * @access protected
76
     */
77
    protected $ready = FALSE;
78
79
    /**
80
     * This holds the singleton search objects with their core as array key
81
     *
82
     * @var	array(tx_dlf_solr)
83
     * @access protected
84
     */
85
    protected static $registry = array ();
86
87
    /**
88
     * This holds the Solr service object
89
     *
90
     * @var	Solarium\Client
91
     * @access protected
92
     */
93
    protected $service;
94
95
    /**
96
     * Escape all special characters in a query string
97
     *
98
     * @access	public
99
     *
100
     * @param	string		$query: The query string
101
     *
102
     * @return	string		The escaped query string
103
     */
104
    public static function escapeQuery($query) {
105
106
        $helper = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('Solarium\Core\Query\Helper');
107
108
        // Escape query phrase or term.
109
        if (preg_match('/^".*"$/', $query)) {
110
111
            return '"'.$helper->escapePhrase(trim($query, '"')).'"';
112
113
        } else {
114
115
            return $helper->escapeTerm($query);
116
117
        }
118
119
    }
120
121
    /**
122
     * Escape all special characters in a query string while retaining valid field queries
123
     *
124
     * @access	public
125
     *
126
     * @param	string		$query: The query string
127
     * @param	integer		$pid: The PID for the field configuration
128
     *
129
     * @return	string		The escaped query string
130
     */
131
    public static function escapeQueryKeepField($query, $pid) {
132
133
        // Is there a field query?
134
        if (preg_match('/^[[:alnum:]]+_[tu][su]i:\(?.*\)?$/', $query)) {
135
136
            // Get all indexed fields.
137
            $fields = array ();
138
139
            $result = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
140
                'tx_dlf_metadata.index_name,tx_dlf_metadata.index_tokenized,tx_dlf_metadata.index_stored',
141
                'tx_dlf_metadata',
142
                'tx_dlf_metadata.index_indexed=1 AND tx_dlf_metadata.pid='.intval($pid).' AND (tx_dlf_metadata.sys_language_uid IN (-1,0) OR tx_dlf_metadata.l18n_parent=0)'.tx_dlf_helper::whereClause('tx_dlf_metadata'),
143
                '',
144
                '',
145
                ''
146
            );
147
148
            if ($GLOBALS['TYPO3_DB']->sql_num_rows($result) > 0) {
149
150
                while ($resArray = $GLOBALS['TYPO3_DB']->sql_fetch_row($result)) {
151
152
                    $fields[] = $resArray[0].'_'.($resArray[1] ? 't' : 'u').($resArray[2] ? 's' : 'u').'i';
153
154
                }
155
156
            }
157
158
            // Check if queried field is valid.
159
            $splitQuery = explode(':', $query, 2);
160
161
            if (in_array($splitQuery[0], $fields)) {
162
163
                $query = $splitQuery[0].':('.self::escapeQuery(trim($splitQuery[1], '()')).')';
164
165
            } else {
166
167
                $query = self::escapeQuery($query);
168
169
            }
170
171
        } elseif (!empty($query) && $query !== '*') {
172
173
            // Don't escape plain asterisk search.
174
            $query = self::escapeQuery($query);
175
176
        }
177
178
        return $query;
179
180
    }
181
182
    /**
183
     * This is a singleton class, thus instances must be created by this method
184
     *
185
     * @access	public
186
     *
187
     * @param	mixed		$core: Name or UID of the core to load
188
     *
189
     * @return	tx_dlf_solr		Instance of this class
190
     */
191
    public static function getInstance($core) {
192
193
        // Save parameter for logging purposes.
194
        $_core = $core;
195
196
        // Get core name if UID is given.
197
        if (\TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($core)) {
198
199
            $core = tx_dlf_helper::getIndexName($core, 'tx_dlf_solrcores');
200
201
        }
202
203
        // Check if core is set.
204
        if (empty($core)) {
205
206
            if (TYPO3_DLOG) {
207
208
                \TYPO3\CMS\Core\Utility\GeneralUtility::devLog('[tx_dlf_solr->getInstance('.$_core.')] Invalid core name "'.$core.'" for Apache Solr', self::$extKey, SYSLOG_SEVERITY_ERROR);
0 ignored issues
show
Bug introduced by
The constant SYSLOG_SEVERITY_ERROR was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
209
210
            }
211
212
            return;
213
214
        }
215
216
        // Check if there is an instance in the registry already.
217
        if (is_object(self::$registry[$core]) && self::$registry[$core] instanceof self) {
218
219
            // Return singleton instance if available.
220
            return self::$registry[$core];
221
222
        }
223
224
        // Create new instance...
225
        $instance = new self($core);
226
227
        // ...and save it to registry.
228
        if ($instance->ready) {
229
230
            self::$registry[$core] = $instance;
231
232
            // Return new instance.
233
            return $instance;
234
235
        } else {
236
237
            if (TYPO3_DLOG) {
238
239
                \TYPO3\CMS\Core\Utility\GeneralUtility::devLog('[tx_dlf_solr->getInstance('.$_core.')] Could not connect to Apache Solr server', self::$extKey, SYSLOG_SEVERITY_ERROR);
240
241
            }
242
243
            return;
244
245
        }
246
247
    }
248
249
    /**
250
     * Returns the connection information for Solr
251
     *
252
     * @access	public
253
     *
254
     * @return	string		The connection parameters for a specific Solr core
255
     */
256
    public static function getSolrConnectionInfo() {
257
258
        $solrInfo = array ();
259
260
        // Extract extension configuration.
261
        $conf = unserialize($GLOBALS['TYPO3_CONF_VARS']['EXT']['extConf'][self::$extKey]);
262
263
        // Derive Solr scheme
264
        $solrInfo['scheme'] = empty($conf['solrHttps']) ? 'http' : 'https';
265
266
        // Derive Solr host name.
267
        $solrInfo['host'] = ($conf['solrHost'] ? $conf['solrHost'] : '127.0.0.1');
268
269
        // Set username and password.
270
        $solrInfo['username'] = $conf['solrUser'];
271
        $solrInfo['password'] = $conf['solrPass'];
272
273
        // Set port if not set.
274
        $solrInfo['port'] = \TYPO3\CMS\Core\Utility\MathUtility::forceIntegerInRange($conf['solrPort'], 1, 65535, 8983);
275
276
        // Append core name to path.
277
        $solrInfo['path'] = trim($conf['solrPath'], '/');
278
279
        // Timeout
280
        $solrInfo['timeout'] = \TYPO3\CMS\Core\Utility\MathUtility::forceIntegerInRange($conf['solrTimeout'], 1, intval(ini_get('max_execution_time')), 10);
281
282
        return $solrInfo;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $solrInfo returns the type array which is incompatible with the documented return type string.
Loading history...
283
284
    }
285
286
    /**
287
     * Returns the request URL for a specific Solr core
288
     *
289
     * @access	public
290
     *
291
     * @param	string		$core: Name of the core to load
292
     *
293
     * @return	string		The request URL for a specific Solr core
294
     */
295
    public static function getSolrUrl($core = '') {
296
297
        // Get Solr connection information.
298
        $solrInfo = self::getSolrConnectionInfo();
299
300
        if ($solrInfo['username'] && $solrInfo['password']) {
301
302
            $host = $solrInfo['username'].':'.$solrInfo['password'].'@'.$solrInfo['host'];
303
304
        } else {
305
306
            $host = $solrInfo['host'];
307
308
        }
309
310
        // Return entire request URL.
311
        return $solrInfo['scheme'].'://'.$host.':'.$solrInfo['port'].'/'.$solrInfo['path'].'/'.$core;
312
313
    }
314
315
    /**
316
     * Get next unused Solr core number
317
     *
318
     * @access	public
319
     *
320
     * @param	integer		$start: Number to start with
321
     *
322
     * @return	integer		First unused core number found
323
     */
324
    public static function solrGetCoreNumber($start = 0) {
325
326
        $start = max(intval($start), 0);
327
328
        // Check if core already exists.
329
        if (self::getInstance('dlfCore'.$start) === NULL) {
330
331
            return $start;
332
333
        } else {
334
335
            return self::solrGetCoreNumber($start + 1);
336
337
        }
338
339
    }
340
341
    /**
342
     * Processes a search request.
343
     *
344
     * @access	public
345
     *
346
     * @return	tx_dlf_list		The result list
347
     */
348
    public function search() {
349
350
        $toplevel = array ();
351
352
        // Take over query parameters.
353
        $params = $this->params;
354
355
        $params['filterquery'] = isset($params['filterquery']) ? $params['filterquery'] : array ();
356
357
        // Set some query parameters.
358
        $params['start'] = 0;
359
        $params['rows'] = 0;
360
361
        // Perform search to determine the total number of hits without fetching them.
362
        $selectQuery = $this->service->createSelect($params);
363
        $results = $this->service->select($selectQuery);
364
365
        $this->numberOfHits = $results->getNumFound();
366
367
        // Restore query parameters
368
        $params = $this->params;
369
370
        $params['filterquery'] = isset($params['filterquery']) ? $params['filterquery'] : array ();
371
372
        // Restrict the fields to the required ones.
373
        $params['fields'] = 'uid,id';
374
375
        // Extend filter query to get all documents with the same uids.
376
        foreach ($params['filterquery'] as $key => $value) {
377
378
            if (isset($value['query'])) {
379
380
                $params['filterquery'][$key]['query'] = '{!join from=uid to=uid}'.$value['query'];
381
382
            }
383
384
        }
385
386
        // Set filter query to just get toplevel documents.
387
        $params['filterquery'][] = array ('query' => 'toplevel:true');
388
389
        // Set join query to get all documents with the same uids.
390
        $params['query'] = '{!join from=uid to=uid}'.$params['query'];
391
392
        // Perform search to determine the total number of toplevel hits and fetch the required rows.
393
        $selectQuery = $this->service->createSelect($params);
394
        $results = $this->service->select($selectQuery);
395
396
        $numberOfToplevelHits = $results->getNumFound();
397
398
        // Process results.
399
        foreach ($results as $doc) {
400
401
            $toplevel[$doc->id] = array (
402
                'u' => $doc->uid,
403
                'h' => '',
404
                's' => '',
405
                'p' => array ()
406
            );
407
408
        }
409
410
        // Save list of documents.
411
        $list = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('tx_dlf_list');
412
413
        $list->reset();
414
415
        $list->add(array_values($toplevel));
416
417
        // Set metadata for search.
418
        $list->metadata = array (
419
            'label' => '',
420
            'description' => '',
421
            'options' => array (
422
                'source' => 'search',
423
                'engine' => 'solr',
424
                'select' => $this->params['query'],
425
                'userid' => 0,
426
                'params' => $this->params,
427
                'core' => $this->core,
428
                'pid' => $this->cPid,
429
                'order' => 'score',
430
                'order.asc' => TRUE,
431
                'numberOfHits' => $this->numberOfHits,
432
                'numberOfToplevelHits' => $numberOfToplevelHits
433
            )
434
        );
435
436
        return $list;
437
438
    }
439
440
    /**
441
     * Processes a search request and returns the raw Apache Solr Documents.
442
     *
443
     * @access	public
444
     *
445
     * @param	string		$query: The search query
446
     * @param   array       $parameters: Additional search parameters
447
     *
448
     * @return	array       The Apache Solr Documents that were fetched
449
     */
450
    public function search_raw($query = '', $parameters = array ()) {
451
452
        // Set additional query parameters.
453
        $parameters['start'] = 0;
454
        $parameters['rows'] = $this->limit;
455
456
        // Set query.
457
        $parameters['query'] = $query;
458
459
        // Perform search.
460
        $selectQuery = $this->service->createSelect(array_merge($this->params, $parameters));
461
        $result = $this->service->select($selectQuery);
462
463
        $resultSet = array ();
464
465
        foreach ($result as $doc) {
466
467
            $resultSet[] = $doc;
468
469
        }
470
471
        return $resultSet;
472
 
473
    }
474
475
    /**
476
     * This returns $this->limit via __get()
477
     *
478
     * @access	protected
479
     *
480
     * @return	integer		The max number of results
481
     */
482
    protected function _getLimit() {
483
484
        return $this->limit;
485
486
    }
487
488
    /**
489
     * This returns $this->numberOfHits via __get()
490
     *
491
     * @access	protected
492
     *
493
     * @return	integer		Total number of hits for last search
494
     */
495
    protected function _getNumberOfHits() {
496
497
        return $this->numberOfHits;
498
499
    }
500
501
    /**
502
     * This returns $this->ready via __get()
503
     *
504
     * @access	protected
505
     *
506
     * @return	boolean		Is the search instantiated successfully?
507
     */
508
    protected function _getReady() {
509
510
        return $this->ready;
511
512
    }
513
514
    /**
515
     * This returns $this->service via __get()
516
     *
517
     * @access	protected
518
     *
519
     * @return	Solarium\Client		Apache Solr service object
520
     */
521
    protected function _getService() {
522
523
        return $this->service;
524
525
    }
526
527
    /**
528
     * This sets $this->cPid via __set()
529
     *
530
     * @access	protected
531
     *
532
     * @param	integer		$value: The new PID for the metadata definitions
533
     *
534
     * @return	void
535
     */
536
    protected function _setCPid($value) {
537
538
        $this->cPid = max(intval($value), 0);
539
540
    }
541
542
    /**
543
     * This sets $this->limit via __set()
544
     *
545
     * @access	protected
546
     *
547
     * @param	integer		$value: The max number of results
548
     *
549
     * @return	void
550
     */
551
    protected function _setLimit($value) {
552
553
        $this->limit = max(intval($value), 0);
554
555
    }
556
557
    /**
558
     * This sets $this->params via __set()
559
     *
560
     * @access	protected
561
     *
562
     * @param	array		$value: The query parameters
563
     *
564
     * @return	void
565
     */
566
    protected function _setParams(array $value) {
567
568
        $this->params = $value;
569
570
    }
571
572
    /**
573
     * This magic method is called each time an invisible property is referenced from the object
574
     *
575
     * @access	public
576
     *
577
     * @param	string		$var: Name of variable to get
578
     *
579
     * @return	mixed		Value of $this->$var
580
     */
581
    public function __get($var) {
582
583
        $method = '_get'.ucfirst($var);
584
585
        if (!property_exists($this, $var) || !method_exists($this, $method)) {
586
587
            if (TYPO3_DLOG) {
588
589
                \TYPO3\CMS\Core\Utility\GeneralUtility::devLog('[tx_dlf_solr->__get('.$var.')] There is no getter function for property "'.$var.'"', self::$extKey, SYSLOG_SEVERITY_WARNING);
0 ignored issues
show
Bug introduced by
The constant SYSLOG_SEVERITY_WARNING was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
590
591
            }
592
593
            return;
594
595
        } else {
596
597
            return $this->$method();
598
599
        }
600
601
    }
602
603
    /**
604
     * This magic method is called each time an invisible property is referenced from the object
605
     *
606
     * @access	public
607
     *
608
     * @param	string		$var: Name of variable to set
609
     * @param	mixed		$value: New value of variable
610
     *
611
     * @return	void
612
     */
613
    public function __set($var, $value) {
614
615
        $method = '_set'.ucfirst($var);
616
617
        if (!property_exists($this, $var) || !method_exists($this, $method)) {
618
619
            if (TYPO3_DLOG) {
620
621
                \TYPO3\CMS\Core\Utility\GeneralUtility::devLog('[tx_dlf_solr->__set('.$var.', [data])] There is no setter function for property "'.$var.'"', self::$extKey, SYSLOG_SEVERITY_WARNING, $value);
0 ignored issues
show
Bug introduced by
The constant SYSLOG_SEVERITY_WARNING was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
622
623
            }
624
625
        } else {
626
627
            $this->$method($value);
628
629
        }
630
631
    }
632
633
    /**
634
     * This is a singleton class, thus the constructor should be private/protected
635
     *
636
     * @access	protected
637
     *
638
     * @param	string		$core: The name of the core to use
639
     *
640
     * @return	void
641
     */
642
    protected function __construct($core) {
643
644
        $solrInfo = self::getSolrConnectionInfo();
645
646
        $config = array (
647
            'endpoint' => array (
648
                'dlf' => array (
649
                    'scheme' => $solrInfo['scheme'],
650
                    'host' => $solrInfo['host'],
651
                    'port' => $solrInfo['port'],
652
                    'path' => '/'.$solrInfo['path'].'/',
653
                    'core' => $core,
654
                    'username' => $solrInfo['username'],
655
                    'password' => $solrInfo['password'],
656
                    'timeout' => $solrInfo['timeout']
657
                )
658
            )
659
        );
660
661
        // Instantiate Solarium\Client class.
662
        $this->service = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('Solarium\Client', $config);
663
664
        // Check if connection is established.
665
        $ping = $this->service->createPing();
666
667
        try {
668
669
            $this->service->ping($ping);
670
671
            // Set core name.
672
            $this->core = $core;
673
674
            // Instantiation successful!
675
            $this->ready = TRUE;
676
677
        } catch (Exception $e) {
678
679
            // Nothing to do here.
680
681
        }
682
683
    }
684
685
}
686