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