Passed
Push — master ( 5c27dd...44ee66 )
by Rafael
34:18
created

EscapeService::escape()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 21
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 9
c 1
b 0
f 0
dl 0
loc 21
ccs 0
cts 14
cp 0
rs 9.9666
cc 4
nc 4
nop 1
crap 20
1
<?php
2
namespace ApacheSolrForTypo3\Solr\Domain\Search\Query\Helper;
3
4
/***************************************************************
5
 *  Copyright notice
6
 *
7
 *  (c) 2017 Timo Hund <[email protected]>
8
 *  All rights reserved
9
 *
10
 *  This script is part of the TYPO3 project. The TYPO3 project is
11
 *  free software; you can redistribute it and/or modify
12
 *  it under the terms of the GNU General Public License as published by
13
 *  the Free Software Foundation; either version 3 of the License, or
14
 *  (at your option) any later version.
15
 *
16
 *  The GNU General Public License can be found at
17
 *  http://www.gnu.org/copyleft/gpl.html.
18
 *
19
 *  This script is distributed in the hope that it will be useful,
20
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
21
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22
 *  GNU General Public License for more details.
23
 *
24
 *  This copyright notice MUST APPEAR in all copies of the script!
25
 ***************************************************************/
26
27
/**
28
 * The EscpaeService is responsible to escape the querystring as expected for Apache Solr.
29
 *
30
 * This class should have no dependencies since it only contains static functions
31
 *
32
 * @author Timo Hund <[email protected]>
33
 */
34
class EscapeService {
35
36
    /**
37
     * Quote and escape search strings
38
     *
39
     * @param string|int|double $string String to escape
40
     * @return string|int|double The escaped/quoted string
41
     */
42
    public static function escape($string)
43
    {
44
        // when we have a numeric string only, nothing needs to be done
45
        if (is_numeric($string)) {
46
            return $string;
47
        }
48
49
        // when no whitespaces are in the query we can also just escape the special characters
50
        if (preg_match('/\W/', $string) != 1) {
51
            return static::escapeSpecialCharacters($string);
52
        }
53
54
        // when there are no quotes inside the query string we can also just escape the whole string
55
        $hasQuotes = strrpos($string, '"') !== false;
56
        if (!$hasQuotes) {
57
            return static::escapeSpecialCharacters($string);
58
        }
59
60
        $result = static::tokenizeByQuotesAndEscapeDependingOnContext($string);
61
62
        return $result;
63
    }
64
65
    /**
66
     * Applies trim and htmlspecialchars on the querystring to use it as output.
67
     *
68
     * @param mixed $string
69
     * @return string
70
     */
71
    public static function clean($string): string
72
    {
73
        $string = trim($string);
74
        $string = htmlspecialchars($string);
75
        return $string;
76
    }
77
78
    /**
79
     * This method is used to escape the content in the query string surrounded by quotes
80
     * different then when it is not in a quoted context.
81
     *
82
     * @param string $string
83
     * @return string
84
     */
85
    protected static function tokenizeByQuotesAndEscapeDependingOnContext($string)
86
    {
87
        $result = '';
88
        $quotesCount = substr_count($string, '"');
89
        $isEvenAmountOfQuotes = $quotesCount % 2 === 0;
90
91
        // go over all quote segments and apply escapePhrase inside a quoted
92
        // context and escapeSpecialCharacters outside the quoted context.
93
        $segments = explode('"', $string);
94
        $segmentsIndex = 0;
95
        foreach ($segments as $segment) {
96
            $isInQuote = $segmentsIndex % 2 !== 0;
97
            $isLastQuote = $segmentsIndex === $quotesCount;
98
99
            if ($isLastQuote && !$isEvenAmountOfQuotes) {
100
                $result .= '\"';
101
            }
102
103
            if ($isInQuote && !$isLastQuote) {
104
                $result .= static::escapePhrase($segment);
105
            } else {
106
                $result .= static::escapeSpecialCharacters($segment);
107
            }
108
109
            $segmentsIndex++;
110
        }
111
112
        return $result;
113
    }
114
115
    /**
116
     * Escapes a value meant to be contained in a phrase with characters with
117
     * special meanings in Lucene query syntax.
118
     *
119
     * @param string $value Unescaped - "dirty" - string
120
     * @return string Escaped - "clean" - string
121
     */
122
    protected static function escapePhrase($value)
123
    {
124
        $pattern = '/("|\\\)/';
125
        $replace = '\\\$1';
126
127
        return '"' . preg_replace($pattern, $replace, $value) . '"';
128
    }
129
130
    /**
131
     * Escapes characters with special meanings in Lucene query syntax.
132
     *
133
     * @param string $value Unescaped - "dirty" - string
134
     * @return string Escaped - "clean" - string
135
     */
136
    protected static function escapeSpecialCharacters($value)
137
    {
138
        // list taken from http://lucene.apache.org/core/4_4_0/queryparser/org/apache/lucene/queryparser/classic/package-summary.html#package_description
139
        // which mentions: + - && || ! ( ) { } [ ] ^ " ~ * ? : \ /
140
        // of which we escape: ( ) { } [ ] ^ " ~ : \ /
141
        // and explicitly don't escape: + - && || ! * ?
142
        $pattern = '/(\\(|\\)|\\{|\\}|\\[|\\]|\\^|"|~|\:|\\\\|\\/)/';
143
        $replace = '\\\$1';
144
145
        return preg_replace($pattern, $replace, $value);
146
    }
147
}