]> git.mxchange.org Git - friendica.git/blob - src/Core/Search.php
9f8375da12f66e539a25d1da0954a3c14b34ca1a
[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::FEDERATED))) {
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                 $resultJson = Network::fetchUrl($searchUrl, false, 0, 'application/json');
111
112                 $results = json_decode($resultJson, true);
113
114                 $resultList = new ResultList(
115                         defaults($results, 'page', 1),
116                         defaults($results, 'count', 0),
117                         defaults($results, 'itemsperpage', 30)
118                 );
119
120                 $profiles = defaults($results, 'profiles', []);
121
122                 foreach ($profiles as $profile) {
123                         $contactDetails = Contact::getDetailsByURL(defaults($profile, 'profile_url', ''), local_user());
124                         $itemUrl        = defaults($contactDetails, 'addr', defaults($profile, 'profile_url', ''));
125
126                         $result = new ContactResult(
127                                 defaults($profile, 'name', ''),
128                                 defaults($profile, 'addr', ''),
129                                 $itemUrl,
130                                 defaults($profile, 'profile_url', ''),
131                                 defaults($profile, 'photo', ''),
132                                 Protocol::DFRN,
133                                 defaults($contactDetails, 'cid', 0),
134                                 0,
135                                 defaults($profile, 'tags', ''));
136
137                         $resultList->addResult($result);
138                 }
139
140                 return $resultList;
141         }
142
143         /**
144          * Search in the local database for occurrences of the search string
145          *
146          * @param string $search
147          * @param int    $type
148          * @param int    $start
149          * @param int    $itemPage
150          *
151          * @return ResultList
152          * @throws HTTPException\InternalServerErrorException
153          */
154         public static function getContactsFromLocalDirectory($search, $type = self::TYPE_ALL, $start = 0, $itemPage = 80)
155         {
156                 $config = self::getApp()->getConfig();
157
158                 $diaspora = $config->get('system', 'diaspora_enabled') ? Protocol::DIASPORA : Protocol::DFRN;
159                 $ostatus  = !$config->get('system', 'ostatus_disabled') ? Protocol::OSTATUS : Protocol::DFRN;
160
161                 $wildcard = Strings::escapeHtml('%' . $search . '%');
162
163                 $count = DBA::count('gcontact', [
164                         'NOT `hide`
165                         AND `network` IN (?, ?, ?, ?)
166                         AND ((`last_contact` >= `last_failure`) OR (`updated` >= `last_failure`))
167                         AND (`url` LIKE ? OR `name` LIKE ? OR `location` LIKE ? 
168                                 OR `addr` LIKE ? OR `about` LIKE ? OR `keywords` LIKE ?)
169                         AND `community` = ?',
170                         Protocol::ACTIVITYPUB, Protocol::DFRN, $ostatus, $diaspora,
171                         $wildcard, $wildcard, $wildcard,
172                         $wildcard, $wildcard, $wildcard,
173                         ($type === self::TYPE_FORUM),
174                 ]);
175
176                 $resultList = new ResultList($start, $itemPage, $count);
177
178                 if (empty($count)) {
179                         return $resultList;
180                 }
181
182                 $data = DBA::select('gcontact', ['nurl'], [
183                         'NOT `hide`
184                         AND `network` IN (?, ?, ?, ?)
185                         AND ((`last_contact` >= `last_failure`) OR (`updated` >= `last_failure`))
186                         AND (`url` LIKE ? OR `name` LIKE ? OR `location` LIKE ? 
187                                 OR `addr` LIKE ? OR `about` LIKE ? OR `keywords` LIKE ?)
188                         AND `community` = ?',
189                         Protocol::ACTIVITYPUB, Protocol::DFRN, $ostatus, $diaspora,
190                         $wildcard, $wildcard, $wildcard,
191                         $wildcard, $wildcard, $wildcard,
192                         ($type === self::TYPE_FORUM),
193                 ], [
194                         'group_by' => ['nurl', 'updated'],
195                         'limit'    => [$start, $itemPage],
196                         'order'    => ['updated' => 'DESC']
197                 ]);
198
199                 if (!DBA::isResult($data)) {
200                         return $resultList;
201                 }
202
203                 while ($row = DBA::fetch($data)) {
204                         if (PortableContact::alternateOStatusUrl($row["nurl"])) {
205                                 continue;
206                         }
207
208                         $urlParts = parse_url($row["nurl"]);
209
210                         // Ignore results that look strange.
211                         // For historic reasons the gcontact table does contain some garbage.
212                         if (!empty($urlParts['query']) || !empty($urlParts['fragment'])) {
213                                 continue;
214                         }
215
216                         $contact = Contact::getDetailsByURL($row["nurl"], local_user());
217
218                         if ($contact["name"] == "") {
219                                 $contact["name"] = end(explode("/", $urlParts["path"]));
220                         }
221
222                         $result = new ContactResult(
223                                 $contact["name"],
224                                 $contact["addr"],
225                                 $contact["addr"],
226                                 $contact["url"],
227                                 $contact["photo"],
228                                 $contact["network"],
229                                 $contact["cid"],
230                                 $contact["zid"],
231                                 $contact["keywords"]
232                         );
233
234                         $resultList->addResult($result);
235                 }
236
237                 DBA::close($data);
238
239                 // Add found profiles from the global directory to the local directory
240                 Worker::add(PRIORITY_LOW, 'DiscoverPoCo', "dirsearch", urlencode($search));
241
242                 return $resultList;
243         }
244 }