apisearchatom.php 10.9 KB
Newer Older
1 2
<?php
/**
3
 * StatusNet, the distributed open-source microblogging tool
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
 *
 * Action for showing Twitter-like Atom search results
 *
 * PHP version 5
 *
 * LICENCE: This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * @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 32 33 34 35 36 37 38 39 40 41
    exit(1);
}

/**
 * Action for outputting search results in Twitter compatible Atom
 * format.
 *
 * TODO: abstract Atom stuff into a ruseable base class like
 * RSS10Action.
 *
 * @category Search
42
 * @package  StatusNet
43
 * @author   Zach Copley <zach@status.net>
44
 * @license  http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
45
 * @link     http://status.net/
46
 *
47
 * @see      ApiPrivateAuthAction
48
 */
49
class ApiSearchAtomAction extends ApiPrivateAuthAction
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
{
    var $cnt;
    var $query;
    var $lang;
    var $rpp;
    var $page;
    var $since_id;
    var $geocode;

    /**
     * Constructor
     *
     * Just wraps the Action constructor.
     *
     * @param string  $output URI to output to, default = stdout
     * @param boolean $indent Whether to indent output, default true
     *
     * @see Action::__construct
     */
69
    function __construct($output='php://output', $indent=null)
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
    {
        parent::__construct($output, $indent);
    }

    /**
     * Do we need to write to the database?
     *
     * @return boolean true
     */
    function isReadonly()
    {
        return true;
    }

    /**
     * Read arguments and initialize members
     *
     * @param array $args Arguments from $_REQUEST
     *
     * @return boolean success
     */
91
    function prepare(array $args = array())
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
    {
        parent::prepare($args);

        $this->query = $this->trimmed('q');
        $this->lang  = $this->trimmed('lang');
        $this->rpp   = $this->trimmed('rpp');

        if (!$this->rpp) {
            $this->rpp = 15;
        }

        if ($this->rpp > 100) {
            $this->rpp = 100;
        }

        $this->page = $this->trimmed('page');

        if (!$this->page) {
            $this->page = 1;
        }

113
        // TODO: Suppport max_id -- we need to tweak the backend
114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
        // Search classes to support it.

        $this->since_id = $this->trimmed('since_id');
        $this->geocode  = $this->trimmed('geocode');

        // TODO: Also, language and geocode

        return true;
    }

    /**
     * Handle a request
     *
     * @param array $args Arguments from $_REQUEST
     *
     * @return void
     */
131
    function handle()
132
    {
133
        parent::handle();
134
        common_debug("In apisearchatom handle()");
135 136 137 138 139 140 141 142 143 144 145 146 147 148
        $this->showAtom();
    }

    /**
     * Get the notices to output as results. This also sets some class
     * attrs so we can use them to calculate pagination, and output
     * since_id and max_id.
     *
     * @return array an array of Notice objects sorted in reverse chron
     */
    function getNotices()
    {
        // TODO: Support search operators like from: and to:, boolean, etc.

149
        $notices = array();
150 151 152 153 154
        $notice = new Notice();

        // lcase it for comparison
        $q = strtolower($this->query);

155
        $search_engine = $notice->getSearchEngine('notice');
156 157 158
        $search_engine->set_sort_mode('chron');
        $search_engine->limit(($this->page - 1) * $this->rpp,
            $this->rpp + 1, true);
159 160 161 162 163
        if (false === $search_engine->query($q)) {
            $this->cnt = 0;
        } else {
            $this->cnt = $notice->find();
        }
164 165

        $cnt = 0;
166
        $this->max_id = 0;
167

168 169 170
        if ($this->cnt > 0) {
            while ($notice->fetch()) {
                ++$cnt;
171

172 173 174
                if (!$this->max_id) {
                    $this->max_id = $notice->id;
                }
175

176 177 178 179
                if ($this->since_id && $notice->id <= $this->since_id) {
                    break;
                }

180 181 182
                if ($cnt > $this->rpp) {
                    break;
                }
183

184 185
                $notices[] = clone($notice);
            }
186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203
        }

        return $notices;
    }

    /**
     * Output search results as an Atom feed
     *
     * @return void
     */
    function showAtom()
    {
        $notices = $this->getNotices();

        $this->initAtom();
        $this->showFeed();

        foreach ($notices as $n) {
204 205 206 207 208 209 210
            $profile = $n->getProfile();

            // Don't show notices from deleted users

            if (!empty($profile)) {
                $this->showEntry($n);
            }
211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227
        }

        $this->endAtom();
    }

    /**
     * Show feed specific Atom elements
     *
     * @return void
     */
    function showFeed()
    {
        // TODO: A9 OpenSearch stuff like search.twitter.com?

        $server   = common_config('site', 'server');
        $sitename = common_config('site', 'name');

228
        // XXX: Use xmlns:statusnet instead?
229 230 231

        $this->elementStart('feed',
            array('xmlns' => 'http://www.w3.org/2005/Atom',
232 233 234 235

                             // XXX: xmlns:twitter causes Atom validation to fail
                             // It's used for the source attr on notices

236
                             'xmlns:twitter' => 'http://api.twitter.com/',
Zach Copley's avatar
Zach Copley committed
237
                             'xml:lang' => 'en-US')); // XXX Other locales ?
238

239
        $taguribase = TagURI::base();
240
        $this->element('id', null, "tag:$taguribase:search/$server");
241 242 243 244 245 246 247 248 249 250

        $site_uri = common_path(false);

        $search_uri = $site_uri . 'api/search.atom?q=' . urlencode($this->query);

        if ($this->rpp != 15) {
            $search_uri .= '&rpp=' . $this->rpp;
        }

        // FIXME: this alternate link is not quite right because our
251
        // web-based notice search doesn't support a rpp (responses per
252 253 254 255 256 257 258 259 260
        // page) param yet

        $this->element('link', array('type' => 'text/html',
                                     'rel'  => 'alternate',
                                     'href' => $site_uri . 'search/notice?q=' .
                                        urlencode($this->query)));

        // self link

261 262
        $self_uri = $search_uri;
        $self_uri .= ($this->page > 1) ? '&page=' . $this->page : '';
263 264 265 266 267

        $this->element('link', array('type' => 'application/atom+xml',
                                     'rel'  => 'self',
                                     'href' => $self_uri));

Siebrand Mazeland's avatar
Siebrand Mazeland committed
268
        // @todo Needs i18n?
269
        $this->element('title', null, "$this->query - $sitename Search");
270
        $this->element('updated', null, common_date_iso8601('now'));
271

Zach Copley's avatar
Zach Copley committed
272 273 274
        // XXX: The below "rel" links are not valid Atom, but it's what
        // Twitter does...

275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321
        // refresh link

        $refresh_uri = $search_uri . "&since_id=" . $this->max_id;

        $this->element('link', array('type' => 'application/atom+xml',
                                     'rel'  => 'refresh',
                                     'href' => $refresh_uri));

        // pagination links

        if ($this->cnt > $this->rpp) {

            $next_uri = $search_uri . "&max_id=" . $this->max_id .
                '&page=' . ($this->page + 1);

            $this->element('link', array('type' => 'application/atom+xml',
                                         'rel'  => 'next',
                                         'href' => $next_uri));
        }

        if ($this->page > 1) {

            $previous_uri = $search_uri . "&max_id=" . $this->max_id .
                '&page=' . ($this->page - 1);

            $this->element('link', array('type' => 'application/atom+xml',
                                         'rel'  => 'previous',
                                         'href' => $previous_uri));
        }
    }

    /**
     * Build an Atom entry similar to search.twitter.com's based on
     * a given notice
     *
     * @param Notice $notice the notice to use
     *
     * @return void
     */
    function showEntry($notice)
    {
        $server  = common_config('site', 'server');
        $profile = $notice->getProfile();
        $nurl    = common_local_url('shownotice', array('notice' => $notice->id));

        $this->elementStart('entry');

322
        $taguribase = TagURI::base();
323

324
        $this->element('id', null, "tag:$taguribase:$notice->id");
325 326 327 328 329
        $this->element('published', null, common_date_w3dtf($notice->created));
        $this->element('link', array('type' => 'text/html',
                                     'rel'  => 'alternate',
                                     'href' => $nurl));
        $this->element('title', null, common_xml_safe_str(trim($notice->content)));
330
        $this->element('content', array('type' => 'html'), $notice->getRendered());
331 332
        $this->element('updated', null, common_date_w3dtf($notice->created));
        $this->element('link', array('type' => 'image/png',
333 334
                                     // XXX: Twitter uses rel="image" (not valid)
                                     'rel' => 'related',
335 336
                                     'href' => $profile->avatarUrl()));

337 338 339
        // @todo: Here is where we'd put in a link to an atom feed for threads

        $source = null;
340
        $source_link = null;
341 342

        $ns = $notice->getSource();
343
        if ($ns instanceof Notice_source) {
344 345 346 347 348 349
            $source = $ns->code;
            if (!empty($ns->url)) {
                $source_link = $ns->url;
                if (!empty($ns->name)) {
                    $source = $ns->name;
                }
350 351
            }
        }
352

353
        $this->element("twitter:source", null, $source);
354
        $this->element("twitter:source_link", null, $source_link);
355 356 357 358 359 360

        $this->elementStart('author');

        $name = $profile->nickname;

        if ($profile->fullname) {
Siebrand Mazeland's avatar
Siebrand Mazeland committed
361
            // @todo Needs proper i18n?
362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392
            $name .= ' (' . $profile->fullname . ')';
        }

        $this->element('name', null, $name);
        $this->element('uri', null, common_profile_uri($profile));
        $this->elementEnd('author');

        $this->elementEnd('entry');
    }

    /**
     * Initialize the Atom output, send headers
     *
     * @return void
     */
    function initAtom()
    {
        header('Content-Type: application/atom+xml; charset=utf-8');
        $this->startXml();
    }

    /**
     * End the Atom feed
     *
     * @return void
     */
    function endAtom()
    {
        $this->elementEnd('feed');
    }
}