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