renaming
[friendica.git/.git] / src / Model / Search.php
1 <?php
2
3 namespace Friendica\Model;
4
5 use Friendica\BaseObject;
6 use Friendica\Core\Protocol;
7 use Friendica\Core\Worker;
8 use Friendica\Database\DBA;
9 use Friendica\Network\Probe;
10 use Friendica\Object\Search\ContactResult;
11 use Friendica\Object\Search\ContactResultList;
12 use Friendica\Protocol\PortableContact;
13 use Friendica\Util\Network;
14 use Friendica\Util\Strings;
15
16 /**
17  * Model for searches
18  */
19 class Search extends BaseObject
20 {
21         const DEFAULT_DIRECTORY = 'https://dir.friendica.social';
22
23         /**
24          * Returns the list of user defined tags (e.g. #Friendica)
25          *
26          * @return array
27          *
28          * @throws \Exception
29          */
30         public static function getUserTags()
31         {
32                 $termsStmt = DBA::p("SELECT DISTINCT(`term`) FROM `search`");
33
34                 $tags = [];
35
36                 while ($term = DBA::fetch($termsStmt)) {
37                         $tags[] = trim($term['term'], '#');
38                 }
39
40                 return $tags;
41         }
42
43         /**
44          * Search a user based on his/her profile address
45          * pattern: @username@domain.tld
46          *
47          * @param string $user The user to search for
48          *
49          * @return ContactResultList|null
50          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
51          * @throws \ImagickException
52          */
53         public static function searchUser($user)
54         {
55                 if ((filter_var($user, FILTER_VALIDATE_EMAIL) && Network::isEmailDomainValid($user)) ||
56                     (substr(Strings::normaliseLink($user), 0, 7) == "http://")) {
57
58                         $user_data = Probe::uri($user);
59                         if (empty($user_data)) {
60                                 return null;
61                         }
62
63                         if (!(in_array($user_data["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::OSTATUS, Protocol::DIASPORA]))) {
64                                 return null;
65                         }
66
67                         $contactDetails = Contact::getDetailsByURL(defaults($user_data, 'url', ''), local_user());
68                         $itemurl = (($contactDetails["addr"] != "") ? $contactDetails["addr"] : defaults($user_data, 'url', ''));
69
70                         $result = new ContactResult(
71                                 defaults($user_data, 'name', ''),
72                                 defaults($user_data, 'addr', ''),
73                                 $itemurl,
74                                 defaults($user_data, 'url', ''),
75                                 defaults($user_data, 'photo', ''),
76                                 defaults($user_data, 'network', ''),
77                                 defaults($contactDetails, 'cid', 0),
78                                 0,
79                                 defaults($user_data, 'tags', '')
80                         );
81
82                         return new ContactResultList(1, 1, 1, [$result]);
83
84                 } else {
85                         return null;
86                 }
87         }
88
89         /**
90          * Search in the global directory for occurrences of the search string
91          * This is mainly based on the JSON results of https://dir.friendica.social
92          *
93          * @param string $search
94          * @param int    $page
95          *
96          * @return ContactResultList|null
97          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
98          */
99         public static function searchDirectory($search, $page = 1)
100         {
101                 $config = self::getApp()->getConfig();
102                 $server = $config->get('system', 'directory', self::DEFAULT_DIRECTORY);
103
104                 $searchUrl = $server . '/search?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 ContactResultList(
116                         defaults($results, 'page', 1),
117                         defaults($results, 'count', 1),
118                         defaults($results, 'itemsperpage', 1)
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 = (!empty($contactDetails['addr']) ? $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    $start
149          * @param int    $itemPage
150          * @param bool   $community
151          *
152          * @return ContactResultList|null
153          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
154          */
155         public static function searchLocal($search, $start = 0, $itemPage = 80, $community = false)
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                         $community,
175                 ]);
176
177                 if (empty($count)) {
178                         return null;
179                 }
180
181                 $data = DBA::select('gcontact', ['nurl'], [
182                         'NOT `hide`
183                         AND `network` IN (?, ?, ?, ?)
184                         AND ((`last_contact` >= `last_failure`) OR (`updated` >= `last_failure`))
185                         AND (`url` LIKE ? OR `name` LIKE ? OR `location` LIKE ? 
186                                 OR `addr` LIKE ? OR `about` LIKE ? OR `keywords` LIKE ?)
187                         AND `community` = ?',
188                         Protocol::ACTIVITYPUB, Protocol::DFRN, $ostatus, $diaspora,
189                         $wildcard, $wildcard, $wildcard,
190                         $wildcard, $wildcard, $wildcard,
191                         $community,
192                 ], [
193                         'group_by' => ['nurl', 'updated'],
194                         'limit' => [$start, $itemPage],
195                         'order' => ['updated' => 'DESC']
196                 ]);
197
198                 if (!DBA::isResult($data)) {
199                         return null;
200                 }
201
202                 $resultList = new ContactResultList($start, $itemPage, $count);
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 }