]> git.mxchange.org Git - friendica.git/blob - src/Core/Search.php
48231f08247a94c1206e8c8f62a774dbc8253f53
[friendica.git] / src / Core / Search.php
1 <?php
2
3 namespace Friendica\Core;
4
5 use Friendica\BaseObject;
6 use Friendica\Database\DBA;
7 use Friendica\Model\Contact;
8 use Friendica\Network\HTTPException;
9 use Friendica\Network\Probe;
10 use Friendica\Object\Search\ContactResult;
11 use Friendica\Object\Search\ResultList;
12 use Friendica\Protocol\PortableContact;
13 use Friendica\Util\Network;
14 use Friendica\Util\Strings;
15
16 /**
17  * Specific class to perform searches for different systems. Currently:
18  * - Probe for contacts
19  * - Search in the local directory
20  * - Search in the global directory
21  */
22 class Search extends BaseObject
23 {
24         const DEFAULT_DIRECTORY = 'https://dir.friendica.social';
25
26         const TYPE_PEOPLE = 0;
27         const TYPE_FORUM  = 1;
28         const TYPE_ALL    = 2;
29
30         /**
31          * Search a user based on his/her profile address
32          * pattern: @username@domain.tld
33          *
34          * @param string $user The user to search for
35          *
36          * @return ResultList
37          * @throws HTTPException\InternalServerErrorException
38          * @throws \ImagickException
39          */
40         public static function getContactsFromProbe($user)
41         {
42                 $emptyResultList = new ResultList(1, 0, 1);
43
44                 if ((filter_var($user, FILTER_VALIDATE_EMAIL) && Network::isEmailDomainValid($user)) ||
45                     (substr(Strings::normaliseLink($user), 0, 7) == "http://")) {
46
47                         $user_data = Probe::uri($user);
48                         if (empty($user_data)) {
49                                 return $emptyResultList;
50                         }
51
52                         if (!(in_array($user_data["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::OSTATUS, Protocol::DIASPORA]))) {
53                                 return $emptyResultList;
54                         }
55
56                         $contactDetails = Contact::getDetailsByURL(defaults($user_data, 'url', ''), local_user());
57                         $itemUrl        = defaults($contactDetails, 'addr', defaults($user_data, 'url', ''));
58
59                         $result = new ContactResult(
60                                 defaults($user_data, 'name', ''),
61                                 defaults($user_data, 'addr', ''),
62                                 $itemUrl,
63                                 defaults($user_data, 'url', ''),
64                                 defaults($user_data, 'photo', ''),
65                                 defaults($user_data, 'network', ''),
66                                 defaults($contactDetails, 'cid', 0),
67                                 0,
68                                 defaults($user_data, 'tags', '')
69                         );
70
71                         return new ResultList(1, 1, 1, [$result]);
72                 } else {
73                         return $emptyResultList;
74                 }
75         }
76
77         /**
78          * Search in the global directory for occurrences of the search string
79          *
80          * @see https://github.com/friendica/friendica-directory/blob/master/docs/Protocol.md#search
81          *
82          * @param string $search
83          * @param int    $type specific type of searching
84          * @param int    $page
85          *
86          * @return ResultList
87          * @throws HTTPException\InternalServerErrorException
88          */
89         public static function getContactsFromGlobalDirectory($search, $type = self::TYPE_ALL, $page = 1)
90         {
91                 $config = self::getApp()->getConfig();
92                 $server = $config->get('system', 'directory', self::DEFAULT_DIRECTORY);
93
94                 $searchUrl = $server . '/search';
95
96                 switch ($type) {
97                         case self::TYPE_FORUM:
98                                 $searchUrl .= '/forum';
99                                 break;
100                         case self::TYPE_PEOPLE:
101                                 $searchUrl .= '/people';
102                                 break;
103                 }
104                 $searchUrl .= '?q=' . urlencode($search);
105
106                 if ($page > 1) {
107                         $searchUrl .= '&page=' . $page;
108                 }
109
110                 $red        = 0;
111                 $resultJson = Network::fetchUrl($searchUrl, false, $red, 0, 'application/json');
112
113                 $results = json_decode($resultJson, true);
114
115                 $resultList = new ResultList(
116                         defaults($results, 'page', 1),
117                         defaults($results, 'count', 0),
118                         defaults($results, 'itemsperpage', 30)
119                 );
120
121                 $profiles = defaults($results, 'profiles', []);
122
123                 foreach ($profiles as $profile) {
124                         $contactDetails = Contact::getDetailsByURL(defaults($profile, 'profile_url', ''), local_user());
125                         $itemUrl        = defaults($contactDetails, 'addr', defaults($profile, 'profile_url', ''));
126
127                         $result = new ContactResult(
128                                 defaults($profile, 'name', ''),
129                                 defaults($profile, 'addr', ''),
130                                 $itemUrl,
131                                 defaults($profile, 'profile_url', ''),
132                                 defaults($profile, 'photo', ''),
133                                 Protocol::DFRN,
134                                 defaults($contactDetails, 'cid', 0),
135                                 0,
136                                 defaults($profile, 'tags', ''));
137
138                         $resultList->addResult($result);
139                 }
140
141                 return $resultList;
142         }
143
144         /**
145          * Search in the local database for occurrences of the search string
146          *
147          * @param string $search
148          * @param int    $type
149          * @param int    $start
150          * @param int    $itemPage
151          *
152          * @return ResultList
153          * @throws HTTPException\InternalServerErrorException
154          */
155         public static function getContactsFromLocalDirectory($search, $type = self::TYPE_ALL, $start = 0, $itemPage = 80)
156         {
157                 $config = self::getApp()->getConfig();
158
159                 $diaspora = $config->get('system', 'diaspora_enabled') ? Protocol::DIASPORA : Protocol::DFRN;
160                 $ostatus  = !$config->get('system', 'ostatus_disabled') ? Protocol::OSTATUS : Protocol::DFRN;
161
162                 $wildcard = Strings::escapeHtml('%' . $search . '%');
163
164                 $count = DBA::count('gcontact', [
165                         'NOT `hide`
166                         AND `network` IN (?, ?, ?, ?)
167                         AND ((`last_contact` >= `last_failure`) OR (`updated` >= `last_failure`))
168                         AND (`url` LIKE ? OR `name` LIKE ? OR `location` LIKE ? 
169                                 OR `addr` LIKE ? OR `about` LIKE ? OR `keywords` LIKE ?)
170                         AND `community` = ?',
171                         Protocol::ACTIVITYPUB, Protocol::DFRN, $ostatus, $diaspora,
172                         $wildcard, $wildcard, $wildcard,
173                         $wildcard, $wildcard, $wildcard,
174                         ($type === self::TYPE_FORUM),
175                 ]);
176
177                 $resultList = new ResultList($start, $itemPage, $count);
178
179                 if (empty($count)) {
180                         return $resultList;
181                 }
182
183                 $data = DBA::select('gcontact', ['nurl'], [
184                         'NOT `hide`
185                         AND `network` IN (?, ?, ?, ?)
186                         AND ((`last_contact` >= `last_failure`) OR (`updated` >= `last_failure`))
187                         AND (`url` LIKE ? OR `name` LIKE ? OR `location` LIKE ? 
188                                 OR `addr` LIKE ? OR `about` LIKE ? OR `keywords` LIKE ?)
189                         AND `community` = ?',
190                         Protocol::ACTIVITYPUB, Protocol::DFRN, $ostatus, $diaspora,
191                         $wildcard, $wildcard, $wildcard,
192                         $wildcard, $wildcard, $wildcard,
193                         ($type === self::TYPE_FORUM),
194                 ], [
195                         'group_by' => ['nurl', 'updated'],
196                         'limit'    => [$start, $itemPage],
197                         'order'    => ['updated' => 'DESC']
198                 ]);
199
200                 if (!DBA::isResult($data)) {
201                         return $resultList;
202                 }
203
204                 while ($row = DBA::fetch($data)) {
205                         if (PortableContact::alternateOStatusUrl($row["nurl"])) {
206                                 continue;
207                         }
208
209                         $urlParts = parse_url($row["nurl"]);
210
211                         // Ignore results that look strange.
212                         // For historic reasons the gcontact table does contain some garbage.
213                         if (!empty($urlParts['query']) || !empty($urlParts['fragment'])) {
214                                 continue;
215                         }
216
217                         $contact = Contact::getDetailsByURL($row["nurl"], local_user());
218
219                         if ($contact["name"] == "") {
220                                 $contact["name"] = end(explode("/", $urlParts["path"]));
221                         }
222
223                         $result = new ContactResult(
224                                 $contact["name"],
225                                 $contact["addr"],
226                                 $contact["addr"],
227                                 $contact["url"],
228                                 $contact["photo"],
229                                 $contact["network"],
230                                 $contact["cid"],
231                                 $contact["zid"],
232                                 $contact["keywords"]
233                         );
234
235                         $resultList->addResult($result);
236                 }
237
238                 DBA::close($data);
239
240                 // Add found profiles from the global directory to the local directory
241                 Worker::add(PRIORITY_LOW, 'DiscoverPoCo', "dirsearch", urlencode($search));
242
243                 return $resultList;
244         }
245 }