]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - actions/apisearchatom.php
Merge branch '0.9.x' into merge
[quix0rs-gnu-social.git] / actions / apisearchatom.php
1 <?php
2 /**
3  * StatusNet, the distributed open-source microblogging tool
4  *
5  * Action for showing Twitter-like Atom search results
6  *
7  * PHP version 5
8  *
9  * LICENCE: This program is free software: you can redistribute it and/or modify
10  * it under the terms of the GNU Affero General Public License as published by
11  * the Free Software Foundation, either version 3 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU Affero General Public License for more details.
18  *
19  * You should have received a copy of the GNU Affero General Public License
20  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
21  *
22  * @category  Search
23  * @package   StatusNet
24  * @author    Zach Copley <zach@status.net>
25  * @copyright 2008-2010 StatusNet, Inc.
26  * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
27  * @link      http://status.net/
28  */
29
30 if (!defined('STATUSNET') && !defined('LACONICA')) {
31     exit(1);
32 }
33
34 require_once INSTALLDIR.'/lib/apiprivateauth.php';
35
36 /**
37  * Action for outputting search results in Twitter compatible Atom
38  * format.
39  *
40  * TODO: abstract Atom stuff into a ruseable base class like
41  * RSS10Action.
42  *
43  * @category Search
44  * @package  StatusNet
45  * @author   Zach Copley <zach@status.net>
46  * @license  http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
47  * @link     http://status.net/
48  *
49  * @see      ApiPrivateAuthAction
50  */
51 class ApiSearchAtomAction extends ApiPrivateAuthAction
52 {
53     var $cnt;
54     var $query;
55     var $lang;
56     var $rpp;
57     var $page;
58     var $since_id;
59     var $geocode;
60
61     /**
62      * Constructor
63      *
64      * Just wraps the Action constructor.
65      *
66      * @param string  $output URI to output to, default = stdout
67      * @param boolean $indent Whether to indent output, default true
68      *
69      * @see Action::__construct
70      */
71     function __construct($output='php://output', $indent=null)
72     {
73         parent::__construct($output, $indent);
74     }
75
76     /**
77      * Do we need to write to the database?
78      *
79      * @return boolean true
80      */
81     function isReadonly()
82     {
83         return true;
84     }
85
86     /**
87      * Read arguments and initialize members
88      *
89      * @param array $args Arguments from $_REQUEST
90      *
91      * @return boolean success
92      */
93     function prepare($args)
94     {
95         common_debug("in apisearchatom prepare()");
96
97         parent::prepare($args);
98
99         $this->query = $this->trimmed('q');
100         $this->lang  = $this->trimmed('lang');
101         $this->rpp   = $this->trimmed('rpp');
102
103         if (!$this->rpp) {
104             $this->rpp = 15;
105         }
106
107         if ($this->rpp > 100) {
108             $this->rpp = 100;
109         }
110
111         $this->page = $this->trimmed('page');
112
113         if (!$this->page) {
114             $this->page = 1;
115         }
116
117         // TODO: Suppport max_id -- we need to tweak the backend
118         // Search classes to support it.
119
120         $this->since_id = $this->trimmed('since_id');
121         $this->geocode  = $this->trimmed('geocode');
122
123         // TODO: Also, language and geocode
124
125         return true;
126     }
127
128     /**
129      * Handle a request
130      *
131      * @param array $args Arguments from $_REQUEST
132      *
133      * @return void
134      */
135     function handle($args)
136     {
137         parent::handle($args);
138         common_debug("In apisearchatom handle()");
139         $this->showAtom();
140     }
141
142     /**
143      * Get the notices to output as results. This also sets some class
144      * attrs so we can use them to calculate pagination, and output
145      * since_id and max_id.
146      *
147      * @return array an array of Notice objects sorted in reverse chron
148      */
149     function getNotices()
150     {
151         // TODO: Support search operators like from: and to:, boolean, etc.
152
153         $notices = array();
154         $notice = new Notice();
155
156         // lcase it for comparison
157         $q = strtolower($this->query);
158
159         $search_engine = $notice->getSearchEngine('notice');
160         $search_engine->set_sort_mode('chron');
161         $search_engine->limit(($this->page - 1) * $this->rpp,
162             $this->rpp + 1, true);
163         if (false === $search_engine->query($q)) {
164             $this->cnt = 0;
165         } else {
166             $this->cnt = $notice->find();
167         }
168
169         $cnt = 0;
170         $this->max_id = 0;
171
172         if ($this->cnt > 0) {
173             while ($notice->fetch()) {
174                 ++$cnt;
175
176                 if (!$this->max_id) {
177                     $this->max_id = $notice->id;
178                 }
179
180                 if ($this->since_id && $notice->id <= $this->since_id) {
181                     break;
182                 }
183
184                 if ($cnt > $this->rpp) {
185                     break;
186                 }
187
188                 $notices[] = clone($notice);
189             }
190         }
191
192         return $notices;
193     }
194
195     /**
196      * Output search results as an Atom feed
197      *
198      * @return void
199      */
200     function showAtom()
201     {
202         $notices = $this->getNotices();
203
204         $this->initAtom();
205         $this->showFeed();
206
207         foreach ($notices as $n) {
208             $profile = $n->getProfile();
209
210             // Don't show notices from deleted users
211
212             if (!empty($profile)) {
213                 $this->showEntry($n);
214             }
215         }
216
217         $this->endAtom();
218     }
219
220     /**
221      * Show feed specific Atom elements
222      *
223      * @return void
224      */
225     function showFeed()
226     {
227         // TODO: A9 OpenSearch stuff like search.twitter.com?
228
229         $server   = common_config('site', 'server');
230         $sitename = common_config('site', 'name');
231
232         // XXX: Use xmlns:statusnet instead?
233
234         $this->elementStart('feed',
235             array('xmlns' => 'http://www.w3.org/2005/Atom',
236
237                              // XXX: xmlns:twitter causes Atom validation to fail
238                              // It's used for the source attr on notices
239
240                              'xmlns:twitter' => 'http://api.twitter.com/',
241                              'xml:lang' => 'en-US')); // XXX Other locales ?
242
243         $taguribase = TagURI::base();
244         $this->element('id', null, "tag:$taguribase:search/$server");
245
246         $site_uri = common_path(false);
247
248         $search_uri = $site_uri . 'api/search.atom?q=' . urlencode($this->query);
249
250         if ($this->rpp != 15) {
251             $search_uri .= '&rpp=' . $this->rpp;
252         }
253
254         // FIXME: this alternate link is not quite right because our
255         // web-based notice search doesn't support a rpp (responses per
256         // page) param yet
257
258         $this->element('link', array('type' => 'text/html',
259                                      'rel'  => 'alternate',
260                                      'href' => $site_uri . 'search/notice?q=' .
261                                         urlencode($this->query)));
262
263         // self link
264
265         $self_uri = $search_uri;
266         $self_uri .= ($this->page > 1) ? '&page=' . $this->page : '';
267
268         $this->element('link', array('type' => 'application/atom+xml',
269                                      'rel'  => 'self',
270                                      'href' => $self_uri));
271
272         // @todo Needs i18n?
273         $this->element('title', null, "$this->query - $sitename Search");
274         $this->element('updated', null, common_date_iso8601('now'));
275
276         // XXX: The below "rel" links are not valid Atom, but it's what
277         // Twitter does...
278
279         // refresh link
280
281         $refresh_uri = $search_uri . "&since_id=" . $this->max_id;
282
283         $this->element('link', array('type' => 'application/atom+xml',
284                                      'rel'  => 'refresh',
285                                      'href' => $refresh_uri));
286
287         // pagination links
288
289         if ($this->cnt > $this->rpp) {
290
291             $next_uri = $search_uri . "&max_id=" . $this->max_id .
292                 '&page=' . ($this->page + 1);
293
294             $this->element('link', array('type' => 'application/atom+xml',
295                                          'rel'  => 'next',
296                                          'href' => $next_uri));
297         }
298
299         if ($this->page > 1) {
300
301             $previous_uri = $search_uri . "&max_id=" . $this->max_id .
302                 '&page=' . ($this->page - 1);
303
304             $this->element('link', array('type' => 'application/atom+xml',
305                                          'rel'  => 'previous',
306                                          'href' => $previous_uri));
307         }
308     }
309
310     /**
311      * Build an Atom entry similar to search.twitter.com's based on
312      * a given notice
313      *
314      * @param Notice $notice the notice to use
315      *
316      * @return void
317      */
318     function showEntry($notice)
319     {
320         $server  = common_config('site', 'server');
321         $profile = $notice->getProfile();
322         $nurl    = common_local_url('shownotice', array('notice' => $notice->id));
323
324         $this->elementStart('entry');
325
326         $taguribase = TagURI::base();
327
328         $this->element('id', null, "tag:$taguribase:$notice->id");
329         $this->element('published', null, common_date_w3dtf($notice->created));
330         $this->element('link', array('type' => 'text/html',
331                                      'rel'  => 'alternate',
332                                      'href' => $nurl));
333         $this->element('title', null, common_xml_safe_str(trim($notice->content)));
334         $this->element('content', array('type' => 'html'), $notice->rendered);
335         $this->element('updated', null, common_date_w3dtf($notice->created));
336         $this->element('link', array('type' => 'image/png',
337                                      // XXX: Twitter uses rel="image" (not valid)
338                                      'rel' => 'related',
339                                      'href' => $profile->avatarUrl()));
340
341         // @todo: Here is where we'd put in a link to an atom feed for threads
342
343         $source = null;
344
345         $ns = $notice->getSource();
346         if ($ns) {
347             if (!empty($ns->name) && !empty($ns->url)) {
348                 $source = '<a href="'
349                    . htmlspecialchars($ns->url)
350                    . '" rel="nofollow">'
351                    . htmlspecialchars($ns->name)
352                    . '</a>';
353             } else {
354                 $source = $ns->code;
355             }
356         }
357
358         $this->element("twitter:source", null, $source);
359
360         $this->elementStart('author');
361
362         $name = $profile->nickname;
363
364         if ($profile->fullname) {
365             // @todo Needs proper i18n?
366             $name .= ' (' . $profile->fullname . ')';
367         }
368
369         $this->element('name', null, $name);
370         $this->element('uri', null, common_profile_uri($profile));
371         $this->elementEnd('author');
372
373         $this->elementEnd('entry');
374     }
375
376     /**
377      * Initialize the Atom output, send headers
378      *
379      * @return void
380      */
381     function initAtom()
382     {
383         header('Content-Type: application/atom+xml; charset=utf-8');
384         $this->startXml();
385     }
386
387     /**
388      * End the Atom feed
389      *
390      * @return void
391      */
392     function endAtom()
393     {
394         $this->elementEnd('feed');
395     }
396 }