]> git.mxchange.org Git - friendica.git/blob - src/Content/Conversation/Repository/UserDefinedChannel.php
Language check added
[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 = []): UserDefinedChannels
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                         'publish'          => $Channel->publish,
137                 ];
138
139                 if ($Channel->code) {
140                         $this->db->update(self::$table_name, $fields, ['uid' => $Channel->uid, 'id' => $Channel->code]);
141                 } else {
142                         $this->db->insert(self::$table_name, $fields, Database::INSERT_IGNORE);
143
144                         $newChannelId = $this->db->lastInsertId();
145
146                         $Channel = $this->selectById($newChannelId, $Channel->uid);
147                 }
148
149                 return $Channel;
150         }
151
152         /**
153          * Checks, if one of the user defined channels matches with the given search text
154          * @todo Combine all the full text statements in a single search text to improve the performance.
155          * Add a "valid" field for the channel that is set when the full text statement doesn't contain errors.
156          *
157          * @param string $searchtext
158          * @param string $language
159          * @param array  $tags
160          * @param int    $media_type
161          * @return boolean
162          */
163         public function match(string $searchtext, string $language, array $tags, int $media_type): bool
164         {
165                 $users = $this->db->selectToArray('user', ['uid'], $this->getUserCondition());
166                 if (empty($users)) {
167                         return [];
168                 }
169
170                 $uids = array_column($users, 'uid');
171
172                 $condition = ['uid' => $uids];
173                 $condition = DBA::mergeConditions($condition, ["`languages` != ? AND `include-tags` = ? AND `full-text-search` = ? AND circle = ?", '', '', '', 0]);
174
175                 foreach ($this->select($condition) as $channel) {
176                         if (!empty($channel->languages) && in_array($language, $channel->languages)) {
177                                 return true;
178                         }
179                 }
180
181                 return !empty($this->getMatches($searchtext, $language, $tags, $media_type, 0, 0, $uids, false));
182         }
183
184         /**
185          * Fetch the channel users that have got matching channels
186          *
187          * @param string $searchtext
188          * @param string $language
189          * @param array  $tags
190          * @param int    $media_type
191          * @param int    $owner_id
192          * @param int    $reshare_id
193          * @return array
194          */
195         public function getMatchingChannelUsers(string $searchtext, string $language, array $tags, int $media_type, int $owner_id, int $reshare_id): array
196         {
197                 $condition = $this->getUserCondition();
198                 $condition = DBA::mergeConditions($condition, ["`account-type` IN (?, ?) AND `uid` != ?", User::ACCOUNT_TYPE_RELAY, User::ACCOUNT_TYPE_COMMUNITY, 0]);
199                 $users = $this->db->selectToArray('user', ['uid'], $condition);
200                 if (empty($users)) {
201                         return [];
202                 }
203                 return $this->getMatches($searchtext, $language, $tags, $media_type, $owner_id, $reshare_id, array_column($users, 'uid'), true);
204         }
205
206         private function getMatches(string $searchtext, string $language, array $tags, int $media_type, int $owner_id, int $reshare_id, array $channelUids, bool $relayMode): array
207         {
208                 if (!in_array($language, User::getLanguages())) {
209                         $this->logger->debug('Unwanted language found. No matched channel found.', ['language' => $language, 'searchtext' => $searchtext]);
210                         return [];
211                 }
212
213                 $this->db->insert('check-full-text-search', ['pid' => getmypid(), 'searchtext' => $searchtext], Database::INSERT_UPDATE);
214
215                 $uids = [];
216
217                 $condition = ['uid' => $channelUids];
218                 if (!$relayMode) {
219                         $condition = DBA::mergeConditions($condition, ["`full-text-search` != ?", '']);
220                 } else {
221                         $condition = DBA::mergeConditions($condition, ['publish' => true]);
222                 }
223
224                 foreach ($this->select($condition) as $channel) {
225                         if (in_array($channel->uid, $uids)) {
226                                 continue;
227                         }
228                         if (!empty($channel->circle) && ($channel->circle > 0) && !in_array($channel->uid, $uids)) {
229                                 if (!$this->inCircle($channel->circle, $channel->uid, $owner_id) && !$this->inCircle($channel->circle, $channel->uid, $reshare_id)) {
230                                         continue;
231                                 }
232                         }
233                         if (!empty($channel->languages) && !in_array($channel->uid, $uids)) {
234                                 if (!in_array($language, $channel->languages)) {
235                                         continue;
236                                 }
237                         } elseif (!in_array($language, User::getWantedLanguages($channel->uid))) {
238                                 continue;
239                         }
240                         if (!empty($channel->includeTags) && !in_array($channel->uid, $uids)) {
241                                 if (!$this->inTaglist($channel->includeTags, $tags)) {
242                                         continue;
243                                 }
244                         }
245                         if (!empty($channel->excludeTags) && !in_array($channel->uid, $uids)) {
246                                 if ($this->inTaglist($channel->excludeTags, $tags)) {
247                                         continue;
248                                 }
249                         }
250                         if (!empty($channel->mediaType) && !in_array($channel->uid, $uids)) {
251                                 if (!($channel->mediaType & $media_type)) {
252                                         continue;
253                                 }
254                         }
255                         if (!empty($channel->fullTextSearch) && !in_array($channel->uid, $uids)) {
256                                 if (!$this->inFulltext($channel->fullTextSearch)) {
257                                         continue;
258                                 }
259                         }
260                         $uids[] = $channel->uid;
261                         $this->logger->debug('Matching channel found.', ['uid' => $channel->uid, 'label' => $channel->label, 'language' => $language, 'tags' => $tags, 'media_type' => $media_type, 'searchtext' => $searchtext]);
262                         if (!$relayMode) {
263                                 return $uids;
264                         }
265                 }
266
267                 $this->db->delete('check-full-text-search', ['pid' => getmypid()]);
268                 return $uids;
269         }
270
271         private function inCircle(int $circleId, int $uid, int $cid): bool
272         {
273                 if ($cid == 0) {
274                         return false;
275                 }
276
277                 $account = Contact::selectFirstAccountUser(['id'], ['pid' => $cid, 'uid' => $uid]);
278                 if (empty($account['id'])) {
279                         return false;
280                 }
281                 return $this->db->exists('group_member', ['gid' => $circleId, 'contact-id' => $account['id']]);
282         }
283
284         private function inTaglist(string $tagList, array $tags): bool
285         {
286                 if (empty($tags)) {
287                         return false;
288                 }
289                 array_walk($tags, function (&$value) {
290                         $value = mb_strtolower($value);
291                 });
292                 foreach (explode(',', $tagList) as $tag) {
293                         if (in_array($tag, $tags)) {
294                                 return true;
295                         }
296                 }
297                 return false;
298         }
299
300         private function inFulltext(string $fullTextSearch): bool
301         {
302                 foreach (Engagement::KEYWORDS as $keyword) {
303                         $fullTextSearch = preg_replace('~(' . $keyword . ':.[\w@\.-]+)~', '"$1"', $fullTextSearch);
304                 }
305                 return $this->db->exists('check-full-text-search', ["`pid` = ? AND MATCH (`searchtext`) AGAINST (? IN BOOLEAN MODE)", getmypid(), $fullTextSearch]);
306         }
307
308         private function getUserCondition()
309         {
310                 $condition = ["`verified` AND NOT `blocked` AND NOT `account_removed` AND NOT `account_expired` AND `user`.`uid` > ?", 0];
311
312                 $abandon_days = intval($this->config->get('system', 'account_abandon_days'));
313                 if (!empty($abandon_days)) {
314                         $condition = DBA::mergeConditions($condition, ["`last-activity` > ?", DateTimeFormat::utc('now - ' . $abandon_days . ' days')]);
315                 }
316                 return $condition;
317         }
318 }