]> git.mxchange.org Git - friendica.git/blobdiff - src/Module/Api/Mastodon/Search.php
Merge pull request #13176 from MrPetovan/bug/warnings
[friendica.git] / src / Module / Api / Mastodon / Search.php
index 1730db68c3a0df7b6294d4b4e528a935f69f6284..956e3d73b82a22562a2149cca1218c79689ed03f 100644 (file)
@@ -1,6 +1,6 @@
 <?php
 /**
- * @copyright Copyright (C) 2010-2021, the Friendica project
+ * @copyright Copyright (C) 2010-2023, the Friendica project
  *
  * @license GNU AGPL version 3 or any later version
  *
 
 namespace Friendica\Module\Api\Mastodon;
 
+use Friendica\Core\Logger;
 use Friendica\Core\Protocol;
-use Friendica\Core\Search as CoreSearch;
 use Friendica\Core\System;
 use Friendica\Database\DBA;
 use Friendica\DI;
 use Friendica\Model\Contact;
+use Friendica\Model\Item;
 use Friendica\Model\Post;
 use Friendica\Model\Tag;
 use Friendica\Module\BaseApi;
-use Friendica\Object\Search\ContactResult;
+use Friendica\Util\Network;
 
 /**
  * @see https://docs.joinmastodon.org/methods/search/
@@ -45,7 +46,7 @@ class Search extends BaseApi
                self::checkAllowedScope(self::SCOPE_READ);
                $uid = self::getCurrentUserID();
 
-               $request = self::getRequest([
+               $request = $this->getRequest([
                        'account_id'         => 0,     // If provided, statuses returned will be authored only by this account
                        'max_id'             => 0,     // Return results older than this id
                        'min_id'             => 0,     // Return results immediately newer than this id
@@ -68,10 +69,24 @@ class Search extends BaseApi
 
                if (empty($request['type']) || ($request['type'] == 'accounts')) {
                        $result['accounts'] = self::searchAccounts($uid, $request['q'], $request['resolve'], $limit, $request['offset'], $request['following']);
+
+                       if (!is_array($result['accounts'])) {
+                               // Curbing the search if we got an exact result
+                               $request['type'] = 'accounts';
+                               $result['accounts'] = [$result['accounts']];
+                       }
                }
-               if ((empty($request['type']) || ($request['type'] == 'statuses')) && (strpos($request['q'], '@') == false)) {
+
+               if (empty($request['type']) || ($request['type'] == 'statuses')) {
                        $result['statuses'] = self::searchStatuses($uid, $request['q'], $request['account_id'], $request['max_id'], $request['min_id'], $limit, $request['offset']);
+
+                       if (!is_array($result['statuses'])) {
+                               // Curbing the search if we got an exact result
+                               $request['type'] = 'statuses';
+                               $result['statuses'] = [$result['statuses']];
+                       }
                }
+
                if ((empty($request['type']) || ($request['type'] == 'hashtags')) && (strpos($request['q'], '@') == false)) {
                        $result['hashtags'] = self::searchHashtags($request['q'], $request['exclude_unreviewed'], $limit, $request['offset'], $this->parameters['version']);
                }
@@ -79,56 +94,58 @@ class Search extends BaseApi
                System::jsonExit($result);
        }
 
+       /**
+        * @param int    $uid
+        * @param string $q
+        * @param bool   $resolve
+        * @param int    $limit
+        * @param int    $offset
+        * @param bool   $following
+        * @return array|\Friendica\Object\Api\Mastodon\Account Object if result is absolute (exact account match), list if not
+        * @throws \Friendica\Network\HTTPException\InternalServerErrorException
+        * @throws \Friendica\Network\HTTPException\NotFoundException
+        * @throws \ImagickException
+        */
        private static function searchAccounts(int $uid, string $q, bool $resolve, int $limit, int $offset, bool $following)
        {
-               $accounts = [];
-
-               if (!$following) {
-                       if ((strrpos($q, '@') > 0) && $resolve) {
-                               $results = CoreSearch::getContactsFromProbe($q);
-                       }
+               if (($offset == 0) && (strrpos($q, '@') > 0 || Network::isValidHttpUrl($q))
+                       && $id = Contact::getIdForURL($q, 0, $resolve ? null : false)
+               ) {
+                       return DI::mstdnAccount()->createFromContactId($id, $uid);
+               }
 
-                       if (empty($results)) {
-                               if (DI::config()->get('system', 'poco_local_search')) {
-                                       $results = CoreSearch::getContactsFromLocalDirectory($q, CoreSearch::TYPE_ALL, 0, $limit);
-                               } elseif (!empty(DI::config()->get('system', 'directory'))) {
-                                       $results = CoreSearch::getContactsFromGlobalDirectory($q, CoreSearch::TYPE_ALL, 1);
-                               }
-                       }
-                       if (!empty($results)) {
-                               $counter = 0;
-                               foreach ($results->getResults() as $result) {
-                                       if (++$counter > $limit) {
-                                               continue;
-                                       }
-                                       if ($result instanceof ContactResult) {
-                                               $id = Contact::getIdForURL($result->getUrl(), 0, false);
-
-                                               $accounts[] = DI::mstdnAccount()->createFromContactId($id, $uid);
-                                       }
-                               }
-                       }
-               } else {
-                       $contacts = Contact::searchByName($q, '', $uid);
-
-                       $counter = 0;
-                       foreach ($contacts as $contact) {
-                               if (!in_array($contact['rel'], [Contact::SHARING, Contact::FRIEND])) {
-                                       continue;
-                               }
-                               if (++$counter > $limit) {
-                                       continue;
-                               }
-                               $accounts[] = DI::mstdnAccount()->createFromContactId($contact['id'], $uid);
-                       }
-                       DBA::close($contacts);
+               $accounts = [];
+               foreach (Contact::searchByName($q, '', $following ? $uid : 0, false, $limit, $offset) as $contact) {
+                       $accounts[] = DI::mstdnAccount()->createFromContactId($contact['id'], $uid);
                }
 
                return $accounts;
        }
 
+       /**
+        * @param int    $uid
+        * @param string $q
+        * @param string $account_id
+        * @param int    $max_id
+        * @param int    $min_id
+        * @param int    $limit
+        * @param int    $offset
+        * @return array|\Friendica\Object\Api\Mastodon\Status Object is result is absolute (exact post match), list if not
+        * @throws \Friendica\Network\HTTPException\InternalServerErrorException
+        * @throws \Friendica\Network\HTTPException\NotFoundException
+        * @throws \ImagickException
+        */
        private static function searchStatuses(int $uid, string $q, string $account_id, int $max_id, int $min_id, int $limit, int $offset)
        {
+               if (Network::isValidHttpUrl($q)) {
+                       $q = Network::convertToIdn($q);
+                       // If the user-specific search failed, we search and probe a public post
+                       $item_id = Item::fetchByLink($q, $uid) ?: Item::fetchByLink($q);
+                       if ($item_id && $item = Post::selectFirst(['uri-id'], ['id' => $item_id])) {
+                               return DI::mstdnStatus()->createFromUriId($item['uri-id'], $uid, self::appSupportsQuotes());
+                       }
+               }
+
                $params = ['order' => ['uri-id' => true], 'limit' => [$offset, $limit]];
 
                if (substr($q, 0, 1) == '#') {
@@ -159,28 +176,34 @@ class Search extends BaseApi
 
                $items = DBA::select($table, ['uri-id'], $condition, $params);
 
+               $display_quotes = self::appSupportsQuotes();
+
                $statuses = [];
                while ($item = Post::fetch($items)) {
                        self::setBoundaries($item['uri-id']);
-                       $statuses[] = DI::mstdnStatus()->createFromUriId($item['uri-id'], $uid);
+                       try {
+                               $statuses[] = DI::mstdnStatus()->createFromUriId($item['uri-id'], $uid, $display_quotes);
+                       } catch (\Exception $exception) {
+                               Logger::info('Post not fetchable', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'exception' => $exception]);
+                       }
                }
                DBA::close($items);
 
                if (!empty($min_id)) {
-                       array_reverse($statuses);
+                       $statuses = array_reverse($statuses);
                }
 
                self::setLinkHeader();
                return $statuses;
        }
 
-       private static function searchHashtags(string $q, bool $exclude_unreviewed, int $limit, int $offset, int $version)
+       private static function searchHashtags(string $q, bool $exclude_unreviewed, int $limit, int $offset, int $version): array
        {
                $q = ltrim($q, '#');
 
                $params = ['order' => ['name'], 'limit' => [$offset, $limit]];
 
-               $condition = ["EXISTS(SELECT `tid` FROM `post-tag` WHERE `type` = ? AND `tid` = `id`) AND `name` LIKE ?", Tag::HASHTAG, $q . '%'];
+               $condition = ["`id` IN (SELECT `tid` FROM `post-tag` WHERE `type` = ?) AND `name` LIKE ?", Tag::HASHTAG, $q . '%'];
 
                $tags = DBA::select('tag', ['name'], $condition, $params);