1<?php
2
3// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0.
4// See the LICENCE file in the repository root for full licence text.
5
6namespace App\Models;
7
8use DB;
9
10/**
11 * @property bool $foe
12 * @property bool $friend
13 * @property User $target
14 * @property User $user
15 * @property int $user_id
16 * @property int $zebra_id
17 */
18class UserRelation extends Model
19{
20 public $incrementing = false;
21 public $timestamps = false;
22
23 protected $casts = [
24 'foe' => 'boolean',
25 'friend' => 'boolean',
26 ];
27 protected $primaryKey = ':composite';
28 protected $primaryKeys = ['user_id', 'zebra_id'];
29 protected $table = 'phpbb_zebra';
30
31 public function user()
32 {
33 return $this->belongsTo(User::class, 'user_id', 'user_id');
34 }
35
36 public function target()
37 {
38 return $this->belongsTo(User::class, 'zebra_id', 'user_id');
39 }
40
41 public function scopeBlocks($query)
42 {
43 return $query->where('foe', true)->visible();
44 }
45
46 public function scopeFriends($query)
47 {
48 return $query->where('friend', true)->visible();
49 }
50
51 public function scopeOnline($query)
52 {
53 return $query->whereHas('target', fn ($q) => $q->online());
54 }
55
56 public function scopeVisible($query)
57 {
58 $query->whereHas('target', function ($q) {
59 $q->default();
60 });
61 }
62
63 public function scopeWithMutual($query)
64 {
65 $selfJoin =
66 'COALESCE((
67 SELECT phpbb_zebra.friend
68 FROM phpbb_zebra z
69 WHERE phpbb_zebra.zebra_id = z.user_id
70 AND z.zebra_id = phpbb_zebra.user_id
71 AND z.friend = 1
72 ), 0)';
73
74 if (count($GLOBALS['cfg']['osu']['user']['super_friendly']) > 0) {
75 $friendlyIds = implode(',', $GLOBALS['cfg']['osu']['user']['super_friendly']);
76 $raw = DB::raw(
77 "CASE WHEN phpbb_zebra.zebra_id IN ({$friendlyIds})
78 THEN 1
79 ELSE
80 {$selfJoin}
81 END as mutual"
82 );
83 } else {
84 $raw = DB::raw("{$selfJoin} as mutual");
85 }
86
87 return $query->addSelect('*', $raw);
88 }
89}