Issues (62)

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/models/Comments.php (5 issues)

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
namespace ogheo\comments\models;
4
5
use Yii;
6
use yii\db\ActiveRecord;
7
use yii\behaviors\BlameableBehavior;
8
use yii\behaviors\TimestampBehavior;
9
use ogheo\comments\helpers\CommentsHelper;
10
use ogheo\comments\Module as CommentsModule;
11
12
/**
13
 * Class Comments This is the model class for table "comments".
14
 *
15
 * @property mixed id
16
 * @property mixed url
17
 * @property mixed model
18
 * @property mixed model_key
19
 * @property mixed main_parent_id
20
 * @property mixed parent_id
21
 * @property mixed email
22
 * @property mixed username
23
 * @property mixed content
24
 * @property mixed language
25
 * @property mixed created_by
26
 * @property mixed updated_by
27
 * @property mixed created_at
28
 * @property mixed updated_at
29
 * @property mixed ip
30
 * @property mixed status
31
 * @property mixed ratingAggregation
32
 * @property mixed lastUpdateAuthor
33
 * @property mixed postedDate
34
 * @property mixed authorAvatar
35
 * @property mixed authorName
36
 * @property mixed authorUrl
37
 * @property mixed author
38
 * @property mixed children
39
 *
40
 * @package ogheo\comments\models
41
 */
42
class Comments extends \yii\db\ActiveRecord
43
{
44
    /**
45
     * Statuses
46
     */
47
    const STATUS_PENDING = 0;
48
    const STATUS_PUBLISHED = 1;
49
    const STATUS_SPAM = 2;
50
51
    /**
52
     * Scenarios
53
     */
54
    const SCENARIO_GUEST = 'guest';
55
    const SCENARIO_USER = 'user';
56
57
    /**
58
     * Status for newly added comment.
59
     * By default comments are published without moderation.
60
     * @var int
61
     */
62
    public $newCommentStatus = self::STATUS_PUBLISHED;
63
64
    /**
65
     * Pattern that will be applied for user names on comment form.
66
     * @var string
67
     */
68
    public $usernameRegexp = '/^(\w|\p{L}|\d|_|\-| )+$/ui';
69
70
    /**
71
     * Pattern that will be applied for user names on comment form.
72
     * It contain regexp that should NOT be in username
73
     * Default pattern doesn't allow anything having "admin"
74
     * @var string
75
     */
76
    public $usernameBlackRegexp = '/^(.)*admin(.)*$/i';
77
78
    /**
79
     * @var string
80
     */
81
    public static $commentsQueryModelClass = 'ogheo\comments\models\CommentsQuery';
82
83
    /**
84
     * @inheritdoc
85
     */
86
    public static function tableName()
87
    {
88
        return 'comments';
89
    }
90
91
    /**
92
     * @inheritdoc
93
     */
94 View Code Duplication
    public function behaviors()
0 ignored issues
show
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
95
    {
96
        return [
97
            'blameable' => [
98
                'class' => BlameableBehavior::className(),
99
                'createdByAttribute' => 'created_by',
100
                'updatedByAttribute' => 'updated_by',
101
            ],
102
            'timestamp' => [
103
                'class' => TimestampBehavior::className(),
104
                'attributes' => [
105
                    ActiveRecord::EVENT_BEFORE_INSERT => ['created_at', 'updated_at'],
106
                    ActiveRecord::EVENT_BEFORE_UPDATE => ['updated_at'],
107
                ]
108
            ]
109
        ];
110
    }
111
112
    /**
113
     * @inheritdoc
114
     */
115
    public function scenarios()
116
    {
117
        $scenarios = parent::scenarios();
118
119
        $scenarios[self::SCENARIO_GUEST] = ['username', 'email', 'content', 'parent_id'];
120
        $scenarios[self::SCENARIO_USER] = ['content', 'parent_id'];
121
122
        return $scenarios;
123
    }
124
125
    /**
126
     * @inheritdoc
127
     */
128
    public function rules()
129
    {
130
        return [
131
            [['content'], 'required'],
132
            [['username', 'email'], 'required', 'on' => self::SCENARIO_GUEST],
133
            [['main_parent_id', 'created_by', 'updated_by', 'created_at', 'updated_at', 'status'], 'integer'],
134
            [['parent_id'], function ($attribute, $params, $validator) {
0 ignored issues
show
The parameter $params is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
The parameter $validator is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
135
                $parent_id = CommentsHelper::decodeId($this->$attribute);
136 View Code Duplication
                if ((!intval($parent_id)) || (!self::find()->where(['id' => $parent_id])->exists())) {
0 ignored issues
show
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
137
                    $this->addError(
138
                        $attribute, Yii::t('comments', 'Sorry, something went wrong. Please try again later.')
139
                    );
140
                }
141
            }, 'on' => [
142
                self::SCENARIO_GUEST,
143
                self::SCENARIO_USER
144
            ]],
145
            [['ip'], 'ip'],
146
            [['ip'], 'string', 'max' => 46],
147
            [['url'], 'string', 'max' => 255],
148
            [['language'], 'string', 'max' => 10],
149
            [['model', 'model_key'], 'string', 'max' => 64],
150
            [['email', 'username'], 'string', 'max' => 128],
151
            [['username', 'content'], 'string', 'min' => 4],
152
            ['username', 'match',
153
                'pattern' => $this->usernameRegexp,
154
                'on' => self::SCENARIO_GUEST
155
            ],
156
            ['username', 'match',
157
                'not' => true,
158
                'pattern' => $this->usernameBlackRegexp,
159
                'on' => self::SCENARIO_GUEST
160
            ],
161
            ['username', 'unique',
162
                'targetClass' => CommentsModule::getInstance()->userModel,
163
                'targetAttribute' => 'username',
164
                'on' => self::SCENARIO_GUEST,
165
            ],
166
            [['email'], 'email'],
167
            [['content', 'url', 'model', 'model_key'], 'filter', 'filter' => 'yii\helpers\HtmlPurifier::process'],
168
        ];
169
    }
170
171
    /**
172
     * @return \yii\db\ActiveQuery
173
     */
174
    public function getRating()
175
    {
176
        return $this->hasMany(CommentsModule::getInstance()->commentRatingModelClass, ['comment_id' => 'id']);
177
    }
178
179
    /**
180
     * Declares new relation based on 'rating', which provides aggregation.
181
     * @return \yii\db\ActiveQuery
182
     */
183
    public function getRatingAggregation()
184
    {
185
        return $this->getRating()->select(
186
            [
187
                'comment_id',
188
                'likes' => 'SUM(CASE status when 1 then 1 else 0 end)',
189
                'dislikes' => 'SUM(CASE status when 2 then 1 else 0 end)'
190
            ]
191
        )->groupBy('comment_id')->asArray(true);
192
    }
193
194
    /**
195
     * Get rating based on module settings.
196
     * @return int|null
197
     */
198
    public function getRatingCounter()
199
    {
200
        if ($this->isNewRecord) {
201
            return null;
202
        }
203
204
        if (!empty($this->ratingAggregation)) {
205
            return $this->ratingAggregation[0]['likes'] - $this->ratingAggregation[0]['dislikes'];
206
        }
207
208
        return 0;
209
    }
210
211
    /**
212
     * @return \yii\db\ActiveQuery
213
     */
214
    public function getAuthor()
215
    {
216
        return $this->hasOne(CommentsModule::getInstance()->userModel, ['id' => 'created_by']);
217
    }
218
219
    /**
220
     * @return \yii\db\ActiveQuery
221
     */
222
    public function getLastUpdateAuthor()
223
    {
224
        return $this->hasOne(CommentsModule::getInstance()->userModel, ['id' => 'updated_by']);
225
    }
226
227
    /**
228
     * Get author name.
229
     * @return mixed
230
     */
231
    public function getAuthorName()
232
    {
233
        if ($this->author !== null) {
234
            if ($this->author->hasMethod('getUsername')) {
235
                return $this->author->getUsername();
236
            }
237
238
            return $this->author->username;
239
        }
240
241
        return $this->username;
242
    }
243
244
    /**
245
     * Get author avatar.
246
     * @return null
247
     */
248
    public function getAuthorAvatar()
249
    {
250
        if ($this->author !== null) {
251
            if ($this->author->hasMethod('getAvatar')) {
252
                return $this->author->getAvatar();
253
            }
254
        }
255
256
        return null;
257
    }
258
259
    /**
260
     * Get link options for author url.
261
     * Return example:
262
     * ~~~
263
     * return [
264
     *     '/profile', 'id' => $this->id
265
     * ];
266
     * ~~~
267
     *
268
     * @return null|array
269
     */
270
    public function getAuthorUrl()
271
    {
272
        if ($this->author !== null) {
273
            if ($this->author->hasMethod('getUrl')) {
274
                return $this->author->getUrl();
275
            }
276
        }
277
278
        return null;
279
    }
280
281
    /**
282
     * @return string
283
     */
284
    public function getPostedDate()
285
    {
286
        return Yii::$app->formatter->asRelativeTime($this->created_at);
287
    }
288
289
    /**
290
     * Get counter for total number of comments
291
     * @param $params
292
     * @return CommentsQuery
293
     */
294
    public static function getCommentsCounter($params)
295
    {
296
        if ($params['model'] !== null) {
297
            $models = self::find()->byModel([
298
                'model' => $params['model'],
299
                'model_key' => $params['model_key']
300
            ]);
301
        } else {
302
            $models = self::find()->byUrl([
303
                'url' => $params['url']
304
            ]);
305
        }
306
307
        return $models;
308
    }
309
310
    /**
311
     * Get comments by model or url
312
     * @param $params
313
     * @return CommentsQuery
314
     */
315
    public static function getComments($params)
316
    {
317
        if ($params['model'] !== null) {
318
            $models = self::find($params)->byModel([
319
                'model' => $params['model'],
320
                'model_key' => $params['model_key']
321
            ])->withoutChildren()->with('author', 'ratingAggregation');
322
        } else {
323
            $models = self::find($params)->byUrl([
324
                'url' => $params['url']
325
            ])->withoutChildren()->with('author', 'ratingAggregation');
326
        }
327
328
        return $models;
329
    }
330
331
    /**
332
     * Check if comment has children
333
     * @return bool
334
     */
335
    public function hasChildren()
336
    {
337
        return !empty($this->children);
338
    }
339
340
    /**
341
     * Get children comment
342
     * @return mixed
343
     */
344
    public function getChildren()
345
    {
346
        return $this->children;
347
    }
348
349
    /**
350
     * Set children comment
351
     * @param $value
352
     */
353
    public function setChildren($value)
354
    {
355
        $this->children = $value;
356
    }
357
358
    /**
359
     * @inheritdoc
360
     * @param bool $insert
361
     * @return bool
362
     */
363
    public function beforeSave($insert)
364
    {
365
        if (parent::beforeSave($insert)) {
366
            if ($this->hasAttribute('status')) {
367
                if ($this->getAttribute('status') === null) {
368
                    $this->setAttribute('status', $this->newCommentStatus);
369
                }
370
            }
371
372
            if ($this->hasAttribute('language')) {
373
                if ($this->getAttribute('language') === null) {
374
                    $this->setAttribute('language', Yii::$app->language);
375
                }
376
            }
377
378 View Code Duplication
            if ($this->hasAttribute('ip')) {
0 ignored issues
show
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
379
                if ($this->getAttribute('ip') === null) {
380
                    $this->setAttribute('ip', Yii::$app->request->getUserIP());
381
                }
382
            }
383
384
            if ($this->hasAttribute('main_parent_id') && $this->hasAttribute('parent_id')) {
385
                if ($this->scenario !== 'default') {
386
                    $parent_id = CommentsHelper::decodeId($this->getAttribute('parent_id'));
387
                    if ($parent_id !== null && $parent_id) {
388
                        $parent = self::find()->where(['id' => $parent_id])->select('main_parent_id')->one();
389
                        $main_parent_id = isset($parent->main_parent_id) ? $parent->main_parent_id : $parent_id;
390
                        $this->setAttribute('main_parent_id', $main_parent_id);
391
                        $this->setAttribute('parent_id', $parent_id);
392
                    }
393
                }
394
            }
395
396
            return true;
397
        }
398
399
        return false;
400
    }
401
402
    /**
403
     * @inheritdoc
404
     * @param null $params
405
     * @return CommentsQuery the active query used by this AR class.
406
     */
407
    public static function find($params = null)
408
    {
409
        $query = Yii::createObject(self::$commentsQueryModelClass, [get_called_class()]);
410
411
        if ($params) {
412
            $query->loadParams = $params;
413
        }
414
415
        return $query;
416
    }
417
418
    /**
419
     * @inheritdoc
420
     */
421
    public function attributeLabels()
422
    {
423
        if ($this->scenario === null) {
424
            return [
425
                'id' => Yii::t('comments', 'ID'),
426
                'url' => Yii::t('comments', 'Url'),
427
                'model' => Yii::t('comments', 'Model'),
428
                'model_key' => Yii::t('comments', 'Model Key'),
429
                'main_parent_id' => Yii::t('comments', 'Main Parent ID'),
430
                'parent_id' => Yii::t('comments', 'Parent ID'),
431
                'email' => Yii::t('comments', 'Email'),
432
                'username' => Yii::t('comments', 'Name'),
433
                'content' => Yii::t('comments', 'Content'),
434
                'language' => Yii::t('comments', 'Language'),
435
                'created_by' => Yii::t('comments', 'Created By'),
436
                'updated_by' => Yii::t('comments', 'Updated By'),
437
                'created_at' => Yii::t('comments', 'Created At'),
438
                'updated_at' => Yii::t('comments', 'Updated At'),
439
                'ip' => Yii::t('comments', 'Ip'),
440
                'status' => Yii::t('comments', '
441
                    0-pending,
442
                    1-published,
443
                    2-spam
444
                '),
445
            ];
446
        } else {
447
            return [
448
                'email' => Yii::t('comments', 'Email'),
449
                'username' => Yii::t('comments', 'Name'),
450
                'content' => Yii::t('comments', 'Share your thoughts...')
451
            ];
452
        }
453
    }
454
}
455