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 To increase the performance, this functionality should be replaced with a single SQL call.
156 * @param string $searchtext
157 * @param string $language
159 * @param int $media_type
162 public function match(string $searchtext, string $language, array $tags, int $media_type): bool
164 $users = $this->db->selectToArray('user', ['uid'], $this->getUserCondition());
169 return !empty($this->getMatches($searchtext, $language, $tags, $media_type, 0, array_column($users, 'uid'), false));
173 * Fetch the channel users that have got matching channels
175 * @param string $searchtext
176 * @param string $language
178 * @param int $media_type
179 * @param int $owner_id
182 public function getMatchingChannelUsers(string $searchtext, string $language, array $tags, int $media_type, int $owner_id): array
184 $condition = $this->getUserCondition();
185 $condition = DBA::mergeConditions($condition, ["`account-type` IN (?, ?) AND `uid` != ?", User::ACCOUNT_TYPE_RELAY, User::ACCOUNT_TYPE_COMMUNITY, 0]);
186 $users = $this->db->selectToArray('user', ['uid'], $condition);
190 return $this->getMatches($searchtext, $language, $tags, $media_type, $owner_id, array_column($users, 'uid'), true);
193 private function getMatches(string $searchtext, string $language, array $tags, int $media_type, int $owner_id, array $channelUids, bool $relayMode): array
195 if (!in_array($language, User::getLanguages())) {
196 $this->logger->debug('Unwanted language found. No matched channel found.', ['language' => $language, 'searchtext' => $searchtext]);
200 array_walk($tags, function (&$value) {
201 $value = mb_strtolower($value);
204 $this->db->insert('check-full-text-search', ['pid' => getmypid(), 'searchtext' => $searchtext], Database::INSERT_UPDATE);
208 $condition = ['uid' => $channelUids];
210 $condition = DBA::mergeConditions($condition, ["`full-text-search` != ?", '']);
212 $condition = DBA::mergeConditions($condition, ['publish' => true]);
215 foreach ($this->select($condition) as $channel) {
216 if (in_array($channel->uid, $uids)) {
219 if (!empty($channel->circle) && ($channel->circle > 0) && !in_array($channel->uid, $uids)) {
220 $account = Contact::selectFirstAccountUser(['id'], ['pid' => $owner_id, 'uid' => $channel->uid]);
221 if (empty($account['id']) || !$this->db->exists('group_member', ['gid' => $channel->circle, 'contact-id' => $account['id']])) {
225 if (!empty($channel->languages) && !in_array($channel->uid, $uids)) {
226 if (!in_array($language, $channel->languages)) {
229 } elseif (!in_array($language, User::getWantedLanguages($channel->uid))) {
232 if (!empty($channel->includeTags) && !in_array($channel->uid, $uids)) {
237 foreach (explode(',', $channel->includeTags) as $tag) {
238 if (in_array($tag, $tags)) {
247 if (!empty($tags) && !empty($channel->excludeTags) && !in_array($channel->uid, $uids)) {
249 foreach (explode(',', $channel->excludeTags) as $tag) {
250 if (in_array($tag, $tags)) {
259 if (!empty($channel->mediaType) && !in_array($channel->uid, $uids)) {
260 if (!($channel->mediaType & $media_type)) {
264 if (!empty($channel->fullTextSearch) && !in_array($channel->uid, $uids)) {
265 $channelsearchtext = $channel->fullTextSearch;
266 foreach (Engagement::KEYWORDS as $keyword) {
267 $channelsearchtext = preg_replace('~(' . $keyword . ':.[\w@\.-]+)~', '"$1"', $channelsearchtext);
269 if (!$this->db->exists('check-full-text-search', ["`pid` = ? AND MATCH (`searchtext`) AGAINST (? IN BOOLEAN MODE)", getmypid(), $channelsearchtext])) {
273 $uids[] = $channel->uid;
274 $this->logger->debug('Matching channel found.', ['uid' => $channel->uid, 'label' => $channel->label, 'language' => $language, 'tags' => $tags, 'media_type' => $media_type, 'searchtext' => $searchtext]);
280 $this->db->delete('check-full-text-search', ['pid' => getmypid()]);
284 private function getUserCondition()
286 $condition = ["`verified` AND NOT `blocked` AND NOT `account_removed` AND NOT `account_expired` AND `user`.`uid` > ?", 0];
288 $abandon_days = intval($this->config->get('system', 'account_abandon_days'));
289 if (!empty($abandon_days)) {
290 $condition = DBA::mergeConditions($condition, ["`last-activity` > ?", DateTimeFormat::utc('now - ' . $abandon_days . ' days')]);