User::announcements()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 2
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 2
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace App\Models\Eloquent;
4
5
use Illuminate\Notifications\Notifiable;
6
use Illuminate\Contracts\Auth\MustVerifyEmail;
7
use Illuminate\Foundation\Auth\User as Authenticatable;
8
use Laravel\Passport\HasApiTokens;
9
use App\Models\Eloquent\UserExtra;
10
use App\Models\Eloquent\Dojo\DojoProblem;
11
use Carbon;
12
use DB;
13
use Log;
14
use Exception;
15
use App\Models\Traits\LikeScope;
16
17
class User extends Authenticatable
18
{
19
    use HasApiTokens, Notifiable;
0 ignored issues
show
Bug introduced by
The trait Illuminate\Notifications\Notifiable requires the property $email which is not provided by App\Models\Eloquent\User.
Loading history...
20
    use LikeScope;
21
22
    protected $table='users';
23
24
    /**
25
     * The attributes that are mass assignable.
26
     *
27
     * @var array
28
     */
29
    protected $fillable=[
30
        'name', 'email', 'password', 'avatar', 'contest_account'
31
    ];
32
33
    /**
34
     * The attributes that should be hidden for arrays.
35
     *
36
     * @var array
37
     */
38
    protected $hidden=[
39
        'password', 'remember_token', 'tokens'
40
    ];
41
42
    public function submissions()
43
    {
44
        return $this->hasMany('App\Models\Eloquent\Submission', 'uid');
45
    }
46
47
    public function banneds() {
48
        return $this->hasMany('App\Models\Eloquent\UserBanned');
49
    }
50
51
    public function announcements() {
52
        return $this->hasMany('App\Models\Eloquent\Announcement');
53
    }
54
55
    public function permissions() {
56
        return $this->hasMany('App\Models\Eloquent\UserPermission');
57
    }
58
59
    public function imagehostings() {
60
        return $this->hasMany('App\Models\Eloquent\Tool\ImageHosting');
61
    }
62
63
    public function extras() {
64
        return $this->hasMany('App\Models\Eloquent\UserExtra', 'uid');
65
    }
66
67
    public function hasPermission($permissionID) {
68
        return ($this->permissions()->where(['permission_id'=>$permissionID])->count())>0;
69
    }
70
71
    public function hasIndependentPassword() {
72
        return filled($this->password);
73
    }
74
75
    public function hasIndependentEmail() {
76
        return !in_array(explode('@', $this->email)[1], ['temporary.email']) && !$this->contest_account;
77
    }
78
79
    public function isIndependent() {
80
        return $this->hasIndependentPassword() && $this->hasIndependentEmail();
81
    }
82
83
    public function getReadableNameAttribute()
84
    {
85
        return $this->name.' ('.$this->email.')';
86
    }
87
88
    /**
89
     * To get some extra info of a user.
90
     *
91
     * @param string|array $need An array is returned when an array is passed in, Only one value is returned when a string is passed in.
92
     * @param int|null $secretLevel the secret level this query currently running on
93
     * @return string|array $result
94
     */
95
    public function getExtra($need, $secretLevel=0) {
96
        $ret=$this->extras()->orderBy('key')->get()->toArray();
97
        $result=[];
98
        if (!empty($ret)) {
99
            if (is_string($need)) {
100
                foreach ($ret as $value) {
101
                    if (empty($value['secret_level']) || $value['secret_level']<=$secretLevel) {
102
                        $keyName=UserExtra::$extraMapping[$value['key']] ?? 'unknown';
103
                        if ($keyName==$need) {
104
                            return $value['value'];
105
                        }
106
                    }
107
                }
108
                return null;
109
            } else {
110
                foreach ($ret as $value) {
111
                    if (empty($value['secret_level']) || $value['secret_level']<=$secretLevel) {
112
                        $keyName=UserExtra::$extraMapping[$value['key']] ?? 'unknown';
113
                        if (in_array($keyName, $need)) {
114
                            $result[$keyName]=$value['value'];
115
                        }
116
                    }
117
                }
118
            }
119
        }
120
        return $result;
121
    }
122
123
    /**
124
     * To set some extra info of a user.
125
     *
126
     * @param string $keyName insert when key not found or update when key exists. Only values declared in UserExtra Model are accepted
127
     * @param string|null $value the extra info will be delete when value is null
128
     * @param int|null $secretLevel the secret level this query currently running on
129
     * @return mixed $result
130
     */
131
    public function setExtra($keyName, $value=null, $secretLevel=-1) {
132
        $key=array_search($keyName, UserExtra::$extraMapping);
133
        if ($key===false) {
134
            return false;
135
        }
136
        $ret=$this->extras()->where('key', $key)->limit(1)->get()->toArray();
137
        if (!empty($ret)) {
138
            $ret=$ret[0];
139
            unset($ret['id']);
140
            if (!is_null($value)) {
141
                $ret['value']=$value;
142
            } else {
143
                $this->extras()->where('key', $key)->delete();
144
                return true;
145
            }
146
            if ($secretLevel!=-1) {
147
                $ret['secret_level']=$secretLevel;
148
            }
149
            return $this->extras()->where('key', $key)->update($ret);
150
        } else {
151
            if ($value===null) {
152
                return true;
153
            }
154
            return $this->extras()->create([
155
                'key' => $key,
156
                'value' => $value,
157
                'secret_level' => $secretLevel==-1 ? 0 : $secretLevel,
158
            ])->id;
159
        }
160
    }
161
162
    public function getSocialiteInfo($secretLevel=-1)
0 ignored issues
show
Unused Code introduced by
The parameter $secretLevel is not used and could be removed. ( Ignorable by Annotation )

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

162
    public function getSocialiteInfo(/** @scrutinizer ignore-unused */ $secretLevel=-1)

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

Loading history...
163
    {
164
        $socialites=[];
165
        foreach (UserExtra::$socialite_support as $key => $value) {
166
            $id_keyname=$key.'_id';
167
            $id=$this->getExtra($id_keyname);
168
            if (!empty($id)) {
169
                $info=[
170
                    'id' => $id,
171
                ];
172
                foreach ($value as $info_name) {
173
                    $info_temp=$this->getExtra($key.'_'.$info_name);
174
                    if ($info_temp!==null) {
175
                        $info[$info_name]=$info_temp;
176
                    }
177
                }
178
                $socialites[$key]=$info;
179
            }
180
        }
181
182
        return $socialites;
183
    }
184
185
    public function problems_latest_submission($problems, $contestID = null, Carbon $till = null, $verdictFilter = [])
186
    {
187
        if (filled($contestID)) {
188
            $endedAt = Carbon::parse(Contest::findOrFail($contestID)->endedAt);
0 ignored issues
show
Bug introduced by
The property endedAt does not seem to exist on App\Models\Eloquent\Contest. Are you sure there is no database migration missing?

Checks if undeclared accessed properties appear in database migrations and if the creating migration is correct.

Loading history...
189
        }
190
191
        $lastRecordSubQuery = $this->submissions()->select('pid', DB::raw('MAX(submission_date) as submission_date'))->whereIntegerInRaw('pid', $problems)->where('cid', $contestID)->groupBy('pid');
192
193
        if (filled($contestID)) {
194
            $lastRecordSubQuery = $lastRecordSubQuery->where("submission_date", "<", $endedAt->timestamp);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $endedAt does not seem to be defined for all execution paths leading up to this point.
Loading history...
195
        }
196
197
        if (filled($till)) {
198
            $lastRecordSubQuery = $lastRecordSubQuery->where("submission_date", "<", $till->timestamp);
199
        }
200
201
        if(filled($verdictFilter)) {
202
            $lastRecordSubQuery = $lastRecordSubQuery->whereIn('verdict', $verdictFilter);
203
        }
204
205
        $query = DB::table(DB::raw("({$lastRecordSubQuery->toSql()}) last_sub"))->leftJoinSub(Submission::toBase(), 'submissions', function ($join) {
206
            $join->on('last_sub.submission_date', '=', 'submissions.submission_date')->on('last_sub.pid', '=', 'submissions.pid');
207
        })->select('sid', 'last_sub.submission_date as submission_date', 'last_sub.pid as pid', 'verdict', 'color')->orderBy('pid', 'ASC');
208
209
        return $query->mergeBindings($lastRecordSubQuery->toBase());
210
    }
211
212
    public function getDojoStatistics()
213
    {
214
        try {
215
            $statistics = [];
216
            $problemIDArr = DojoProblem::select('problem_id')->distinct()->get()->pluck('problem_id');
217
218
            foreach ($problemIDArr as $problemID) {
219
                $statistics[$problemID] = [
220
                    "icon" => "checkbox-blank-circle-outline",
221
                    "color" => "wemd-grey-text"
222
                ];
223
            }
224
225
            $problemCompleteIDArr = [];
226
227
            foreach ($this->problems_latest_submission($problemIDArr->diff($problemCompleteIDArr), null, null, ['Accepted'])->get() as $acceptedRecord) {
228
                $statistics[$acceptedRecord['pid']] = [
229
                    "icon" => "checkbox-blank-circle",
230
                    "color" => $acceptedRecord['color']
231
                ];
232
                $problemCompleteIDArr[] = $acceptedRecord['pid'];
233
            }
234
235
            foreach ($this->problems_latest_submission($problemIDArr->diff($problemCompleteIDArr), null, null, ['Partially Accepted'])->get() as $acceptedRecord) {
236
                $statistics[$acceptedRecord['pid']] = [
237
                    "icon" => "cisco-webex",
238
                    "color" => $acceptedRecord['color']
239
                ];
240
                $problemCompleteIDArr[] = $acceptedRecord['pid'];
241
            }
242
243
            foreach ($this->problems_latest_submission($problemIDArr->diff($problemCompleteIDArr), null, null)->get() as $acceptedRecord) {
244
                $statistics[$acceptedRecord['pid']] = [
245
                    "icon" => "cisco-webex",
246
                    "color" => $acceptedRecord['color']
247
                ];
248
                $problemCompleteIDArr[] = $acceptedRecord['pid'];
249
            }
250
251
            return $statistics;
252
        } catch (Exception $e) {
253
            Log::alert($e);
254
            return false;
255
        }
256
    }
257
}
258