]> git.mxchange.org Git - friendica.git/blob - src/Content/Conversation/Repository/UserDefinedChannel.php
Use owner instead of author
[friendica.git] / src / Content / Conversation / Repository / UserDefinedChannel.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2024, the Friendica project
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU Affero General Public License as
9  * published by the Free Software Foundation, either version 3 of the
10  * License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU Affero General Public License for more details.
16  *
17  * You should have received a copy of the GNU Affero General Public License
18  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
19  *
20  */
21
22 namespace Friendica\Content\Conversation\Repository;
23
24 use Friendica\BaseCollection;
25 use Friendica\Content\Conversation\Collection\UserDefinedChannels;
26 use Friendica\Content\Conversation\Entity;
27 use Friendica\Content\Conversation\Factory;
28 use Friendica\Core\Config\Capability\IManageConfigValues;
29 use Friendica\Database\Database;
30 use Friendica\Database\DBA;
31 use Friendica\Model\Contact;
32 use Friendica\Model\Post\Engagement;
33 use Friendica\Model\User;
34 use Friendica\Util\DateTimeFormat;
35 use Psr\Log\LoggerInterface;
36
37 class UserDefinedChannel extends \Friendica\BaseRepository
38 {
39         protected static $table_name = 'channel';
40
41         /** @var IManageConfigValues */
42         private $config;
43
44         public function __construct(Database $database, LoggerInterface $logger, Factory\UserDefinedChannel $factory, IManageConfigValues $config)
45         {
46                 parent::__construct($database, $logger, $factory);
47
48                 $this->config = $config;
49         }
50
51         /**
52          * @param array $condition
53          * @param array $params
54          * @return UserDefinedChannels
55          * @throws \Exception
56          */
57         protected function _select(array $condition, array $params = []): BaseCollection
58         {
59                 $rows = $this->db->selectToArray(static::$table_name, [], $condition, $params);
60
61                 $Entities = new UserDefinedChannels();
62                 foreach ($rows as $fields) {
63                         $Entities[] = $this->factory->createFromTableRow($fields);
64                 }
65
66                 return $Entities;
67         }
68
69         public function select(array $condition, array $params = []): BaseCollection
70         {
71                 return $this->_select($condition, $params);
72         }
73
74         /**
75          * Fetch a single user channel
76          *
77          * @param int $id  The id of the user defined channel
78          * @param int $uid The user that this channel belongs to. (Not part of the primary key)
79          * @return Entity\UserDefinedChannel
80          * @throws \Friendica\Network\HTTPException\NotFoundException
81          */
82         public function selectById(int $id, int $uid): Entity\UserDefinedChannel
83         {
84                 return $this->_selectOne(['id' => $id, 'uid' => $uid]);
85         }
86
87         /**
88          * Checks if the provided channel id exists for this user
89          *
90          * @param integer $id
91          * @param integer $uid
92          * @return boolean
93          */
94         public function existsById(int $id, int $uid): bool
95         {
96                 return $this->exists(['id' => $id, 'uid' => $uid]);
97         }
98
99         /**
100          * Delete the given channel
101          *
102          * @param integer $id
103          * @param integer $uid
104          * @return boolean
105          */
106         public function deleteById(int $id, int $uid): bool
107         {
108                 return $this->db->delete(self::$table_name, ['id' => $id, 'uid' => $uid]);
109         }
110
111         /**
112          * Fetch all user channels
113          *
114          * @param integer $uid
115          * @return UserDefinedChannels
116          * @throws \Exception
117          */
118         public function selectByUid(int $uid): UserDefinedChannels
119         {
120                 return $this->_select(['uid' => $uid]);
121         }
122
123         public function save(Entity\UserDefinedChannel $Channel): Entity\UserDefinedChannel
124         {
125                 $fields = [
126                         'label'            => $Channel->label,
127                         'description'      => $Channel->description,
128                         'access-key'       => $Channel->accessKey,
129                         'uid'              => $Channel->uid,
130                         'circle'           => $Channel->circle,
131                         'include-tags'     => $Channel->includeTags,
132                         'exclude-tags'     => $Channel->excludeTags,
133                         'full-text-search' => $Channel->fullTextSearch,
134                         'media-type'       => $Channel->mediaType,
135                         'languages'        => serialize($Channel->languages),
136                 ];
137
138                 if ($Channel->code) {
139                         $this->db->update(self::$table_name, $fields, ['uid' => $Channel->uid, 'id' => $Channel->code]);
140                 } else {
141                         $this->db->insert(self::$table_name, $fields, Database::INSERT_IGNORE);
142
143                         $newChannelId = $this->db->lastInsertId();
144
145                         $Channel = $this->selectById($newChannelId, $Channel->uid);
146                 }
147
148                 return $Channel;
149         }
150
151         /**
152          * Checks, if one of the user defined channels matches with the given search text
153          * @todo To increase the performance, this functionality should be replaced with a single SQL call.
154          *
155          * @param string $searchtext
156          * @param string $language
157          * @param array  $tags
158          * @param int    $media_type
159          * @return boolean
160          */
161         public function match(string $searchtext, string $language, array $tags, int $media_type): bool
162         {
163                 $condition = ["`verified` AND NOT `blocked` AND NOT `account_removed` AND NOT `account_expired` AND `user`.`uid` > ?", 0];
164
165                 $abandon_days = intval($this->config->get('system', 'account_abandon_days'));
166                 if (!empty($abandon_days)) {
167                         $condition = DBA::mergeConditions($condition, ["`last-activity` > ?", DateTimeFormat::utc('now - ' . $abandon_days . ' days')]);
168                 }
169
170                 $users = $this->db->selectToArray('user', ['uid'], $condition);
171                 if (empty($users)) {
172                         return [];
173                 }
174
175                 return !empty($this->getMatches($searchtext, $language, $tags, $media_type, 0, array_column($users, 'uid'), false));
176         }
177
178         /**
179          * Fetch the channel users that have got matching channels
180          *
181          * @param string $searchtext
182          * @param string $language
183          * @param array  $tags
184          * @param int    $media_type
185          * @param int    $owner_id
186          * @return array
187          */
188         public function getMatchingChannelUsers(string $searchtext, string $language, array $tags, int $media_type, int $owner_id): array
189         {
190                 $users = $this->db->selectToArray('user', ['uid'], ["`account-type` = ? AND `uid` != ?", User::ACCOUNT_TYPE_RELAY, 0]);
191                 if (empty($users)) {
192                         return [];
193                 }
194                 return $this->getMatches($searchtext, $language, $tags, $media_type, $owner_id, array_column($users, 'uid'), true);
195         }
196
197         private function getMatches(string $searchtext, string $language, array $tags, int $media_type, int $owner_id, array $channelUids, bool $relayMode): array
198         {
199                 if (!in_array($language, User::getLanguages())) {
200                         $this->logger->debug('Unwanted language found. No matched channel found.', ['language' => $language, 'searchtext' => $searchtext]);
201                         return [];
202                 }
203
204                 $this->db->insert('check-full-text-search', ['pid' => getmypid(), 'searchtext' => $searchtext], Database::INSERT_UPDATE);
205
206                 $uids = [];
207
208                 $condition = ['uid' => $channelUids];
209                 if (!$relayMode) {
210                         $condition = DBA::mergeConditions($condition, ["`full-text-search` != ?", '']);
211                 }
212
213                 foreach ($this->select($condition) as $channel) {
214                         if (in_array($channel->uid, $uids)) {
215                                 continue;
216                         }
217                         if (!empty($channel->circle) && ($channel->circle > 0) && !in_array($channel->uid, $uids)) {
218                                 $account = Contact::selectFirstAccountUser(['id'], ['pid' => $owner_id, 'uid' => $channel->uid]);
219                                 if (empty($account['id']) || !$this->db->exists('group_member', ['gid' => $channel->circle, 'contact-id' => $account['id']])) {
220                                         continue;
221                                 }
222                         }
223                         if (!empty($channel->languages) && !in_array($channel->uid, $uids)) {
224                                 if (!in_array($language, $channel->languages)) {
225                                         continue;
226                                 }
227                         } elseif (!in_array($language, User::getWantedLanguages($channel->uid))) {
228                                 continue;
229                         }
230                         if (!empty($channel->includeTags) && !in_array($channel->uid, $uids)) {
231                                 if (empty($tags)) {
232                                         continue;
233                                 }
234                                 $match = false;
235                                 foreach (explode(',', $channel->includeTags) as $tag) {
236                                         if (in_array($tag, $tags)) {
237                                                 $match = true;
238                                                 break;
239                                         }
240                                 }
241                                 if (!$match) {
242                                         continue;
243                                 }
244                         }
245                         if (!empty($tags) && !empty($channel->excludeTags) && !in_array($channel->uid, $uids)) {
246                                 $match = false;
247                                 foreach (explode(',', $channel->excludeTags) as $tag) {
248                                         if (in_array($tag, $tags)) {
249                                                 $match = true;
250                                                 break;
251                                         }
252                                 }
253                                 if ($match) {
254                                         continue;
255                                 }
256                         }
257                         if (!empty($channel->mediaType) && !in_array($channel->uid, $uids)) {
258                                 if (!($channel->mediaType & $media_type)) {
259                                         continue;
260                                 }
261                         }
262                         if (!empty($channel->fullTextSearch) && !in_array($channel->uid, $uids)) {
263                                 $channelsearchtext = $channel->fullTextSearch;
264                                 foreach (Engagement::KEYWORDS as $keyword) {
265                                         $channelsearchtext = preg_replace('~(' . $keyword . ':.[\w@\.-]+)~', '"$1"', $channelsearchtext);
266                                 }
267                                 if (!$this->db->exists('check-full-text-search', ["`pid` = ? AND MATCH (`searchtext`) AGAINST (? IN BOOLEAN MODE)", getmypid(), $channelsearchtext])) {
268                                         continue;
269                                 }
270                         }
271                         $uids[] = $channel->uid;
272                         $this->logger->debug('Matching channel found.', ['uid' => $channel->uid, 'label' => $channel->label, 'language' => $language, 'tags' => $tags, 'media_type' => $media_type, 'searchtext' => $searchtext]);
273                         if (!$relayMode) {
274                                 return $uids;
275                         }
276                 }
277
278                 $this->db->delete('check-full-text-search', ['pid' => getmypid()]);
279                 return $uids;
280         }
281 }