3 * @copyright Copyright (C) 2010-2024, the Friendica project
5 * @license GNU AGPL version 3 or any later version
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.
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.
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/>.
22 namespace Friendica\Content\Conversation\Repository;
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;
37 class UserDefinedChannel extends \Friendica\BaseRepository
39 protected static $table_name = 'channel';
41 /** @var IManageConfigValues */
44 public function __construct(Database $database, LoggerInterface $logger, Factory\UserDefinedChannel $factory, IManageConfigValues $config)
46 parent::__construct($database, $logger, $factory);
48 $this->config = $config;
52 * @param array $condition
53 * @param array $params
54 * @return UserDefinedChannels
57 protected function _select(array $condition, array $params = []): BaseCollection
59 $rows = $this->db->selectToArray(static::$table_name, [], $condition, $params);
61 $Entities = new UserDefinedChannels();
62 foreach ($rows as $fields) {
63 $Entities[] = $this->factory->createFromTableRow($fields);
69 public function select(array $condition, array $params = []): UserDefinedChannels
71 return $this->_select($condition, $params);
75 * Fetch a single user channel
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
82 public function selectById(int $id, int $uid): Entity\UserDefinedChannel
84 return $this->_selectOne(['id' => $id, 'uid' => $uid]);
88 * Checks if the provided channel id exists for this user
94 public function existsById(int $id, int $uid): bool
96 return $this->exists(['id' => $id, 'uid' => $uid]);
100 * Delete the given channel
103 * @param integer $uid
106 public function deleteById(int $id, int $uid): bool
108 return $this->db->delete(self::$table_name, ['id' => $id, 'uid' => $uid]);
112 * Fetch all user channels
114 * @param integer $uid
115 * @return UserDefinedChannels
118 public function selectByUid(int $uid): UserDefinedChannels
120 return $this->_select(['uid' => $uid]);
123 public function save(Entity\UserDefinedChannel $Channel): Entity\UserDefinedChannel
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,
139 if ($Channel->code) {
140 $this->db->update(self::$table_name, $fields, ['uid' => $Channel->uid, 'id' => $Channel->code]);
142 $this->db->insert(self::$table_name, $fields, Database::INSERT_IGNORE);
144 $newChannelId = $this->db->lastInsertId();
146 $Channel = $this->selectById($newChannelId, $Channel->uid);
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.
157 * @param string $searchtext
158 * @param string $language
160 * @param int $media_type
163 public function match(string $searchtext, string $language, array $tags, int $media_type): bool
165 $users = $this->db->selectToArray('user', ['uid'], $this->getUserCondition());
170 $uids = array_column($users, 'uid');
172 $condition = ['uid' => $uids];
173 $condition = DBA::mergeConditions($condition, ["`languages` != ? AND `include-tags` = ? AND `full-text-search` = ? AND circle = ?", '', '', '', 0]);
175 foreach ($this->select($condition) as $channel) {
176 if (!empty($channel->languages) && in_array($language, $channel->languages)) {
181 return !empty($this->getMatches($searchtext, $language, $tags, $media_type, 0, 0, $uids, false));
185 * Fetch the channel users that have got matching channels
187 * @param string $searchtext
188 * @param string $language
190 * @param int $media_type
191 * @param int $owner_id
192 * @param int $reshare_id
195 public function getMatchingChannelUsers(string $searchtext, string $language, array $tags, int $media_type, int $owner_id, int $reshare_id): array
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);
203 return $this->getMatches($searchtext, $language, $tags, $media_type, $owner_id, $reshare_id, array_column($users, 'uid'), true);
206 private function getMatches(string $searchtext, string $language, array $tags, int $media_type, int $owner_id, int $reshare_id, array $channelUids, bool $relayMode): array
208 if (!in_array($language, User::getLanguages())) {
209 $this->logger->debug('Unwanted language found. No matched channel found.', ['language' => $language, 'searchtext' => $searchtext]);
213 $this->db->insert('check-full-text-search', ['pid' => getmypid(), 'searchtext' => $searchtext], Database::INSERT_UPDATE);
217 $condition = ['uid' => $channelUids];
219 $condition = DBA::mergeConditions($condition, ["`full-text-search` != ?", '']);
221 $condition = DBA::mergeConditions($condition, ['publish' => true]);
224 foreach ($this->select($condition) as $channel) {
225 if (in_array($channel->uid, $uids)) {
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)) {
233 if (!empty($channel->languages) && !in_array($channel->uid, $uids)) {
234 if (!in_array($language, $channel->languages)) {
237 } elseif (!in_array($language, User::getWantedLanguages($channel->uid))) {
240 if (!empty($channel->includeTags) && !in_array($channel->uid, $uids)) {
241 if (!$this->inTaglist($channel->includeTags, $tags)) {
245 if (!empty($channel->excludeTags) && !in_array($channel->uid, $uids)) {
246 if ($this->inTaglist($channel->excludeTags, $tags)) {
250 if (!empty($channel->mediaType) && !in_array($channel->uid, $uids)) {
251 if (!($channel->mediaType & $media_type)) {
255 if (!empty($channel->fullTextSearch) && !in_array($channel->uid, $uids)) {
256 if (!$this->inFulltext($channel->fullTextSearch)) {
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]);
267 $this->db->delete('check-full-text-search', ['pid' => getmypid()]);
271 private function inCircle(int $circleId, int $uid, int $cid): bool
277 $account = Contact::selectFirstAccountUser(['id'], ['pid' => $cid, 'uid' => $uid]);
278 if (empty($account['id'])) {
281 return $this->db->exists('group_member', ['gid' => $circleId, 'contact-id' => $account['id']]);
284 private function inTaglist(string $tagList, array $tags): bool
289 array_walk($tags, function (&$value) {
290 $value = mb_strtolower($value);
292 foreach (explode(',', $tagList) as $tag) {
293 if (in_array($tag, $tags)) {
300 private function inFulltext(string $fullTextSearch): bool
302 foreach (Engagement::KEYWORDS as $keyword) {
303 $fullTextSearch = preg_replace('~(' . $keyword . ':.[\w@\.-]+)~', '"$1"', $fullTextSearch);
305 return $this->db->exists('check-full-text-search', ["`pid` = ? AND MATCH (`searchtext`) AGAINST (? IN BOOLEAN MODE)", getmypid(), $fullTextSearch]);
308 private function getUserCondition()
310 $condition = ["`verified` AND NOT `blocked` AND NOT `account_removed` AND NOT `account_expired` AND `user`.`uid` > ?", 0];
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')]);