Issues (19)

Security Analysis    not enabled

This project does not seem to handle request data directly as such no vulnerable execution paths were found.

  Cross-Site Scripting
Cross-Site Scripting enables an attacker to inject code into the response of a web-request that is viewed by other users. It can for example be used to bypass access controls, or even to take over other users' accounts.
  File Exposure
File Exposure allows an attacker to gain access to local files that he should not be able to access. These files can for example include database credentials, or other configuration files.
  File Manipulation
File Manipulation enables an attacker to write custom data to files. This potentially leads to injection of arbitrary code on the server.
  Object Injection
Object Injection enables an attacker to inject an object into PHP code, and can lead to arbitrary code execution, file exposure, or file manipulation attacks.
  Code Injection
Code Injection enables an attacker to execute arbitrary code on the server.
  Response Splitting
Response Splitting can be used to send arbitrary responses.
  File Inclusion
File Inclusion enables an attacker to inject custom files into PHP's file loading mechanism, either explicitly passed to include, or for example via PHP's auto-loading mechanism.
  Command Injection
Command Injection enables an attacker to inject a shell command that is execute with the privileges of the web-server. This can be used to expose sensitive data, or gain access of your server.
  SQL Injection
SQL Injection enables an attacker to execute arbitrary SQL code on your database server gaining access to user data, or manipulating user data.
  XPath Injection
XPath Injection enables an attacker to modify the parts of XML document that are read. If that XML document is for example used for authentication, this can lead to further vulnerabilities similar to SQL Injection.
  LDAP Injection
LDAP Injection enables an attacker to inject LDAP statements potentially granting permission to run unauthorized queries, or modify content inside the LDAP tree.
  Header Injection
  Other Vulnerability
This category comprises other attack vectors such as manipulating the PHP runtime, loading custom extensions, freezing the runtime, or similar.
  Regex Injection
Regex Injection enables an attacker to execute arbitrary code in your PHP process.
  XML Injection
XML Injection enables an attacker to read files on your local filesystem including configuration files, or can be abused to freeze your web-server process.
  Variable Injection
Variable Injection enables an attacker to overwrite program variables with custom data, and can lead to further vulnerabilities.
Unfortunately, the security analysis is currently not available for your project. If you are a non-commercial open-source project, please contact support to gain access.

src/Searchable.php (1 issue)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
/**
3
 * @link https://github.com/vuongxuongminh/yii2-searchable
4
 * @copyright Copyright (c) 2019 Vuong Xuong Minh
5
 * @license [New BSD License](http://www.opensource.org/licenses/bsd-license.php)
6
 */
7
8
namespace vxm\searchable;
9
10
use Yii;
11
12
use yii\base\Component;
13
use yii\db\Connection;
14
use yii\di\Instance;
15
use yii\queue\Queue;
16
17
use vxm\searchable\queue\DeleteSearchable;
18
use vxm\searchable\queue\MakeSearchable;
19
20
/**
21
 * Class TNTSearch support full-text search via tnt search.
22
 *
23
 * @author Vuong Minh <[email protected]>
24
 * @since 1.0.0
25
 */
26
class Searchable extends Component
27
{
28
    /**
29
     * Search data with boolean mode.
30
     */
31
    const BOOLEAN_SEARCH = 'boolean';
32
33
    /**
34
     * Search data with fuzzy mode.
35
     */
36
    const FUZZY_SEARCH = 'fuzzy';
37
38
    /**
39
     * @var string default search mode for [[search()]] if `$mode` param not set.
40
     */
41
    public $defaultSearchMode = self::FUZZY_SEARCH;
42
43
    /**
44
     * @var string the TNTSearch class.
45
     */
46
    public $tntSearchClass = TNTSearch::class;
47
48
    /**
49
     * @var bool default as you type search config.
50
     */
51
    public $asYouType = false;
52
53
    /**
54
     * @var bool default fuzziness search config.
55
     */
56
    public $fuzziness = false;
57
58
    /**
59
     * @var int default fuzzy prefix length config.
60
     */
61
    public $fuzzyPrefixLength = 2;
62
63
    /**
64
     * @var int default fuzzy max expansions config.
65
     */
66
    public $fuzzyMaxExpansions = 50;
67
68
    /**
69
     * @var int default fuzzy distance config.
70
     */
71
    public $fuzzyDistance = 2;
72
73
    /**
74
     * @var string default storage path of index data.
75
     */
76
    public $storagePath = '@runtime/vxm/searchable';
77
78
    /**
79
     * @var Queue|null use for support make or delete index data via worker.
80
     */
81
    public $queue;
82
83
    /**
84
     * @inheritDoc
85
     * @throws \yii\base\InvalidConfigException
86
     */
87 13
    public function init()
88
    {
89 13
        $this->storagePath = Yii::getAlias($this->storagePath);
0 ignored issues
show
Documentation Bug introduced by
It seems like \Yii::getAlias($this->storagePath) can also be of type boolean. However, the property $storagePath is declared as type string. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
90
91 13
        if ($this->queue !== null) {
92
            $this->queue = Instance::ensure($this->queue, Queue::class);
93
        }
94
95 13
        parent::init();
96 13
    }
97
98
    /**
99
     * Search by model class via given query string.
100
     *
101
     * @param string $modelClass need to search.
102
     * @param string $query apply to search.
103
     * @param string $mode boolean or fuzzy search mode.
104
     * @param array $config of [[\vxm\searchable\TNTSearch]].
105
     * @param int $limit of values search.
106
     * @return array search results.
107
     * @throws \TeamTNT\TNTSearch\Exceptions\IndexNotFoundException
108
     * @throws \yii\base\InvalidConfigException
109
     */
110 8
    public function search(string $modelClass, string $query, ?string $mode = null, array $config = [], int $limit = 100): array
111
    {
112
        /** @var \yii\db\ActiveRecord $modelClass */
113 8
        $this->initIndex($modelClass, $config);
114 8
        $tnt = $this->createTNTSearch($modelClass::getDb(), $config);
115 8
        $tnt->selectIndex("{$modelClass::searchableIndex()}.index");
116 8
        $mode = $mode ?? $this->defaultSearchMode;
117
118 8
        if ($mode === self::BOOLEAN_SEARCH) {
119
120 1
            return $tnt->searchBoolean($query, $limit);
121
        } else {
122
123 8
            return $tnt->search($query, $limit);
124
        }
125
    }
126
127
    /**
128
     * Delete all instances of the model class from the search index.
129
     *
130
     * @param string $modelClass need to delete all instances.
131
     * @param array $config of [[\vxm\searchable\TNTSearch]].
132
     * @throws \yii\base\InvalidConfigException
133
     */
134 5
    public function deleteAllFromSearch(string $modelClass, array $config = []): void
135
    {
136
        /** @var \yii\db\ActiveRecord $modelClass */
137 5
        $tnt = $this->createTNTSearch($modelClass::getDb(), $config);
138 5
        $pathToIndex = $tnt->config['storage'] . "/{$modelClass::searchableIndex()}.index";
139
140 5
        if (file_exists($pathToIndex)) {
141 3
            unlink($pathToIndex);
142
        }
143 5
    }
144
145
    /**
146
     * Dispatch the job to make the given models unsearchable.
147
     *
148
     * @param \yii\db\ActiveRecord|\yii\db\ActiveRecord[]|static|static[] $models dispatch to queue.
149
     * @param array $config of [[\vxm\searchable\TNTSearch]].
150
     * @throws \TeamTNT\TNTSearch\Exceptions\IndexNotFoundException
151
     * @throws \yii\base\InvalidConfigException
152
     */
153 3
    public function queueDeleteFromSearch($models, array $config = []): void
154
    {
155 3
        $models = is_array($models) ? $models : [$models];
156
157 3
        if (empty($models)) {
158
159
            return;
160
        }
161
162 3
        if ($this->queue === null) {
163
164 3
            $this->delete($models, $config);
165
        } else {
166
167
            $job = new DeleteSearchable($models);
168
            $this->queue->push($job);
169
        }
170 3
    }
171
172
    /**
173
     * Dispatch the job to make the given models searchable.
174
     *
175
     * @param \yii\db\ActiveRecord|\yii\db\ActiveRecord[]|static|static[] $models dispatch to queue job.
176
     * @param array $config of [[\vxm\searchable\TNTSearch]].
177
     * @throws \TeamTNT\TNTSearch\Exceptions\IndexNotFoundException
178
     * @throws \yii\base\InvalidConfigException
179
     */
180 10
    public function queueMakeSearchable($models, array $config = []): void
181
    {
182 10
        $models = is_array($models) ? $models : [$models];
183
184 10
        if (empty($models)) {
185
186
            return;
187
        }
188
189 10
        if ($this->queue === null) {
190
191 10
            $this->upsert($models, $config);
192
        } else {
193
194
            $job = new MakeSearchable($models);
195
            $this->queue->push($job);
196
        }
197 10
    }
198
199
    /**
200
     * Update or insert models to search engine.
201
     *
202
     * @param \yii\db\ActiveRecord|\yii\db\ActiveRecord[]|static|static[] $models dispatch to queue.
203
     * @param array $config of [[\vxm\searchable\TNTSearch]].
204
     * @throws \TeamTNT\TNTSearch\Exceptions\IndexNotFoundException
205
     * @throws \yii\base\InvalidConfigException
206
     */
207 10
    public function upsert($models, array $config = []): void
208
    {
209 10
        $models = is_array($models) ? $models : [$models];
210
        /** @var \yii\db\ActiveRecord $modelClass */
211 10
        $modelClass = get_class(current($models));
212 10
        $this->initIndex($modelClass, $config);
213 10
        $tnt = $this->createTNTSearch($modelClass::getDb(), $config);
214 10
        $tnt->selectIndex("{$modelClass::searchableIndex()}.index");
215 10
        $index = $tnt->getIndex();
216 10
        $index->setPrimaryKey($modelClass::searchableKey());
217 10
        $index->indexBeginTransaction();
218
219 10
        foreach ($models as $model) {
220
221 10
            if ($data = $model->toSearchableArray()) {
222 10
                $index->update($model->getSearchableKey(), $data);
223
            }
224
        }
225
226 10
        $index->indexEndTransaction();
227 10
    }
228
229
    /**
230
     * Delete models from search engine.
231
     *
232
     * @param \yii\db\ActiveRecord|\yii\db\ActiveRecord[]|static|static[] $models need to delete.
233
     * @param array $config of [[\vxm\searchable\TNTSearch]].
234
     * @throws \TeamTNT\TNTSearch\Exceptions\IndexNotFoundException
235
     * @throws \yii\base\InvalidConfigException
236
     */
237 3
    public function delete($models, array $config = []): void
238
    {
239 3
        $models = is_array($models) ? $models : [$models];
240
        /** @var \yii\db\ActiveRecord $modelClass */
241 3
        $modelClass = get_class(current($models));
242 3
        $this->initIndex($modelClass, $config);
243 3
        $tnt = $this->createTNTSearch($modelClass::getDb(), $config);
244 3
        $tnt->selectIndex("{$modelClass::searchableIndex()}.index");
245 3
        $index = $tnt->getIndex();
246 3
        $index->setPrimaryKey($modelClass::searchableKey());
247
248 3
        foreach ($models as $model) {
249
            /** @var \yii\db\ActiveRecord $model */
250 3
            $index->delete($model->getSearchableKey());
251
        }
252 3
    }
253
254
    /**
255
     * Init index data of model class.
256
     *
257
     * @param string $modelClass to init index data.
258
     * @param array $config of [[\vxm\searchable\TNTSearch]].
259
     * @throws \yii\base\InvalidConfigException
260
     */
261 12
    public function initIndex(string $modelClass, array $config = []): void
262
    {
263
        /** @var \yii\db\ActiveRecord $modelClass */
264 12
        $index = $modelClass::searchableIndex() . '.index';
265 12
        $tnt = $this->createTNTSearch($modelClass::getDb(), $config);
266
267 12
        if (!file_exists($tnt->config['storage'] . "/{$index}")) {
268 4
            $indexer = $tnt->createIndex($index);
269 4
            $indexer->setPrimaryKey($modelClass::searchableKey());
270
        }
271 12
    }
272
273
    /**
274
     * Create tnt search object.
275
     *
276
     * @param Connection|null $db use to get database info.
277
     * @param array $config of [[\vxm\searchable\TNTSearch]].
278
     * @return object|TNTSearch
279
     * @throws \yii\base\InvalidConfigException
280
     */
281 12
    public function createTNTSearch(?Connection $db = null, array $config = []): TNTSearch
282
    {
283 12
        $db = $db ?? Yii::$app->getDb();
284 12
        $dbh = $db->getMasterPdo();
285 12
        $tnt = Yii::createObject([
286 12
            'class' => $this->tntSearchClass,
287 12
            'asYouType' => $config['asYouType'] ?? $this->asYouType,
288 12
            'fuzziness' => $config['fuzziness'] ?? $this->fuzziness,
289 12
            'fuzzy_distance' => $config['fuzzy_distance'] ?? $config['fuzzyDistance'] ?? $this->fuzzyDistance,
290 12
            'fuzzy_prefix_length' => $config['fuzzy_prefix_length'] ?? $config['fuzzyPrefixLength'] ?? $this->fuzzyPrefixLength,
291 12
            'fuzzy_max_expansions' => $config['fuzzy_max_expansions'] ?? $config['fuzzyMaxExpansions'] ?? $this->fuzzyMaxExpansions
292
        ]);
293 12
        $tnt->loadConfig(['storage' => $this->storagePath]);
294 12
        $tnt->setDatabaseHandle($dbh);
295
296 12
        return $tnt;
297
    }
298
299
300
}
301