git.gnu.io has moved to IP address 209.51.188.249 -- please double check where you are logging in.

action.php 52.9 KB
Newer Older
Evan Prodromou's avatar
Evan Prodromou committed
1
<?php
2
/**
3
 * StatusNet, the distributed open-source microblogging tool
Evan Prodromou's avatar
Evan Prodromou committed
4
 *
5 6 7 8 9
 * Base class for all actions (~views)
 *
 * PHP version 5
 *
 * LICENCE: This program is free software: you can redistribute it and/or modify
10 11 12
 * 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.
Evan Prodromou's avatar
Evan Prodromou committed
13
 *
14 15 16 17
 * 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.
Evan Prodromou's avatar
Evan Prodromou committed
18
 *
19 20
 * 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/>.
21 22
 *
 * @category  Action
23
 * @package   StatusNet
24 25
 * @author    Evan Prodromou <evan@status.net>
 * @author    Sarven Capadisli <csarven@status.net>
26
 * @copyright 2008 StatusNet, Inc.
27
 * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
28
 * @link      http://status.net/
29
 */
Evan Prodromou's avatar
Evan Prodromou committed
30

31
if (!defined('GNUSOCIAL')) { exit(1); }
32

33 34 35 36 37 38 39 40 41 42
/**
 * Base class for all actions
 *
 * This is the base class for all actions in the package. An action is
 * more or less a "view" in an MVC framework.
 *
 * Actions are responsible for extracting and validating parameters; using
 * model classes to read and write to the database; and doing ouput.
 *
 * @category Output
43
 * @package  StatusNet
44 45
 * @author   Evan Prodromou <evan@status.net>
 * @author   Sarven Capadisli <csarven@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 50 51 52
 *
 * @see      HTMLOutputter
 */
class Action extends HTMLOutputter // lawsuit
{
53 54 55 56 57 58 59
    // This should be protected/private in the future
    public $args = array();

    // Action properties, set per-class
    protected $action = false;
    protected $ajax   = false;
    protected $menus  = true;
60
    protected $needLogin = false;
mmn's avatar
mmn committed
61 62
    protected $needPost = false;    // implies canPost if true
    protected $canPost = false;     // can this action handle POST method?
63

64
    // The currently scoped profile (normally Profile::current; from $this->auth_user for API)
65 66
    protected $scoped = null;

67 68 69 70
    // Related to front-end user representation
    protected $format = null;
    protected $error  = null;
    protected $msg    = null;
71

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

88 89 90 91 92 93 94 95 96 97
    function getError()
    {
        return $this->error;
    }

    function getInfo()
    {
        return $this->msg;
    }

98 99 100 101 102 103 104 105 106 107 108 109
    public function handleError($e)
    {
        if ($e instanceof ClientException) {
            $this->clientError($e->getMessage(), $e->getCode());
        } elseif ($e instanceof ServerException) {
            $this->serverError($e->getMessage(), $e->getCode());
        } else {
            // If it wasn't specified more closely which kind of exception it was
            $this->serverError($e->getMessage(), 500);
        }
    }

110 111 112
    static public function run(array $args=array(), $output='php://output', $indent=null) {
        $class = get_called_class();
        $action = new $class($output, $indent);
113
        set_exception_handler(array($action, 'handleError'));
114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133
        $action->execute($args);
        return $action;
    }

    public function execute(array $args=array()) {
        // checkMirror stuff
        if (common_config('db', 'mirror') && $this->isReadOnly($args)) {
            if (is_array(common_config('db', 'mirror'))) {
                // "load balancing", ha ha
                $arr = common_config('db', 'mirror');
                $k = array_rand($arr);
                $mirror = $arr[$k];
            } else {
                $mirror = common_config('db', 'mirror');
            }

            // everyone else uses the mirror
            common_config_set('db', 'database', $mirror);
        }

134 135 136 137 138 139 140
        if (Event::handle('StartActionExecute', array($this, &$args))) {
            $prepared = $this->prepare($args);
            if ($prepared) {
                $this->handle($args);
            } else {
                common_debug('Prepare failed for Action.');
            }
141

142 143 144
            $this->flush();
            Event::handle('EndActionExecute', array($this));
        }
145 146
    }

Robin Millette's avatar
Robin Millette committed
147 148 149 150 151 152 153
    /**
     * For initializing members of the class.
     *
     * @param array $argarray misc. arguments
     *
     * @return boolean true
     */
154
    protected function prepare(array $args=array())
155
    {
156
        if ($this->needPost && !$this->isPost()) {
157
            // TRANS: Client error. POST is a HTTP command. It should not be translated.
158
            $this->clientError(_('This method requires a POST.'), 405);
159 160
        }

mmn's avatar
mmn committed
161 162 163 164 165
        // needPost, of course, overrides canPost if true
        if (!$this->canPost) {
            $this->canPost = $this->needPost;
        }

166
        $this->args = common_copy_args($args);
167

168 169 170
        // This could be set with get_called_action and then
        // chop off 'Action' from the class name. In lower case.
        $this->action = strtolower($this->trimmed('action'));
171 172

        if ($this->ajax || $this->boolean('ajax')) {
mmn's avatar
mmn committed
173 174
            // check with GNUsocial::isAjax()
            GNUsocial::setAjax(true);
175 176
        }

177 178 179 180
        if ($this->needLogin) {
            $this->checkLogin(); // if not logged in, this redirs/excepts
        }

181
        $this->updateScopedProfile();
182

183 184 185
        return true;
    }

186 187
    public function updateScopedProfile()
    {
188 189 190 191
        $this->scoped = Profile::current();
        return $this->scoped;
    }

192 193
    public function getScoped()
    {
194
        return ($this->scoped instanceof Profile) ? $this->scoped : null;
195 196
    }

197
    // Must be run _after_ prepare
198 199 200 201 202
    public function getActionName()
    {
        return $this->action;
    }

203 204 205 206 207 208 209 210 211 212 213 214 215
    public function isAction(array $names)
    {
        foreach ($names as $class) {
            // PHP is case insensitive, and we have stuff like ApiUpperCaseAction,
            // but we at least make a point out of wanting to do stuff case-sensitive.
            $class = ucfirst($class) . 'Action';
            if ($this instanceof $class) {
                return true;
            }
        }
        return false;
    }

Robin Millette's avatar
Robin Millette committed
216 217 218 219 220
    /**
     * Show page, a template method.
     *
     * @return nothing
     */
221
    public function showPage()
222
    {
mmn's avatar
mmn committed
223
        if (GNUsocial::isAjax()) {
224 225 226
            self::showAjax();
            return;
        }
227 228
        if (Event::handle('StartShowHTML', array($this))) {
            $this->startHTML();
Evan Prodromou's avatar
Evan Prodromou committed
229
            $this->flush();
230 231
            Event::handle('EndShowHTML', array($this));
        }
Brian's avatar
Brian committed
232
        if (Event::handle('StartShowHead', array($this))) {
233
            $this->showHead();
Evan Prodromou's avatar
Evan Prodromou committed
234
            $this->flush();
Brian's avatar
Brian committed
235 236 237
            Event::handle('EndShowHead', array($this));
        }
        if (Event::handle('StartShowBody', array($this))) {
238
            $this->showBody();
Brian's avatar
Brian committed
239 240 241
            Event::handle('EndShowBody', array($this));
        }
        if (Event::handle('StartEndHTML', array($this))) {
242
            $this->endHTML();
Brian's avatar
Brian committed
243 244
            Event::handle('EndEndHTML', array($this));
        }
245 246
    }

247 248 249 250 251
    public function showAjax()
    {
        $this->startHTML('text/xml;charset=utf-8');
        $this->elementStart('head');
        // TRANS: Title for conversation page.
252
        $this->element('title', null, $this->title());
253 254
        $this->elementEnd('head');
        $this->elementStart('body');
255
        if ($this->getError()) {
256
            $this->element('p', array('id'=>'error'), $this->getError());
257 258 259
        } else {
            $this->showContent();
        }
260 261 262 263
        $this->elementEnd('body');
        $this->endHTML();
    }

264 265 266 267 268 269 270 271 272 273 274 275 276
    function endHTML()
    {
        global $_startTime;

        if (isset($_startTime)) {
            $endTime = microtime(true);
            $diff = round(($endTime - $_startTime) * 1000);
            $this->raw("<!-- ${diff}ms -->");
        }

        return parent::endHTML();
    }

Robin Millette's avatar
Robin Millette committed
277 278 279 280 281
    /**
     * Show head, a template method.
     *
     * @return nothing
     */
282 283 284
    function showHead()
    {
        // XXX: attributes (profile?)
285
        $this->elementStart('head');
286
        if (Event::handle('StartShowHeadElements', array($this))) {
287 288 289 290
            if (Event::handle('StartShowHeadTitle', array($this))) {
                $this->showTitle();
                Event::handle('EndShowHeadTitle', array($this));
            }
291 292 293 294 295 296 297 298
            $this->showShortcutIcon();
            $this->showStylesheets();
            $this->showOpenSearch();
            $this->showFeeds();
            $this->showDescription();
            $this->extraHead();
            Event::handle('EndShowHeadElements', array($this));
        }
299
        $this->elementEnd('head');
300 301
    }

Robin Millette's avatar
Robin Millette committed
302 303 304 305 306
    /**
     * Show title, a template method.
     *
     * @return nothing
     */
307 308 309
    function showTitle()
    {
        $this->element('title', null,
310
                       // TRANS: Page title. %1$s is the title, %2$s is the site name.
311
                       sprintf(_('%1$s - %2$s'),
312 313 314 315
                               $this->title(),
                               common_config('site', 'name')));
    }

Robin Millette's avatar
Robin Millette committed
316 317 318 319 320 321 322
    /**
     * Returns the page title
     *
     * SHOULD overload
     *
     * @return string page title
     */
323 324 325

    function title()
    {
326
        // TRANS: Page title for a page without a title set.
327
        return _('Untitled page');
328 329
    }

330 331 332 333 334 335 336 337 338
    /**
     * Show themed shortcut icon
     *
     * @return nothing
     */
    function showShortcutIcon()
    {
        if (is_readable(INSTALLDIR . '/theme/' . common_config('site', 'theme') . '/favicon.ico')) {
            $this->element('link', array('rel' => 'shortcut icon',
339
                                         'href' => Theme::path('favicon.ico')));
340
        } else {
341
            // favicon.ico should be HTTPS if the rest of the page is
342
            $this->element('link', array('rel' => 'shortcut icon',
mmn's avatar
mmn committed
343
                                         'href' => common_path('favicon.ico', GNUsocial::isHTTPS())));
344
        }
345 346 347 348

        if (common_config('site', 'mobile')) {
            if (is_readable(INSTALLDIR . '/theme/' . common_config('site', 'theme') . '/apple-touch-icon.png')) {
                $this->element('link', array('rel' => 'apple-touch-icon',
349
                                             'href' => Theme::path('apple-touch-icon.png')));
350 351 352 353 354
            } else {
                $this->element('link', array('rel' => 'apple-touch-icon',
                                             'href' => common_path('apple-touch-icon.png')));
            }
        }
355 356
    }

Robin Millette's avatar
Robin Millette committed
357 358 359 360 361
    /**
     * Show stylesheets
     *
     * @return nothing
     */
362 363
    function showStylesheets()
    {
364
        if (Event::handle('StartShowStyles', array($this))) {
365

366 367
            // Use old name for StatusNet for compatibility on events

368
            if (Event::handle('StartShowStylesheets', array($this))) {
369
                $this->primaryCssLink(null, 'screen, projection, tv, print');
370
                Event::handle('EndShowStylesheets', array($this));
371
            }
372

373
            $this->cssLink('js/extlib/jquery-ui/css/smoothness/jquery-ui.css');
374

375 376 377
            if (Event::handle('StartShowUAStyles', array($this))) {
                Event::handle('EndShowUAStyles', array($this));
            }
378

379
            Event::handle('EndShowStyles', array($this));
380

381 382 383 384 385 386 387 388 389
            if (common_config('custom_css', 'enabled')) {
                $css = common_config('custom_css', 'css');
                if (Event::handle('StartShowCustomCss', array($this, &$css))) {
                    if (trim($css) != '') {
                        $this->style($css);
                    }
                    Event::handle('EndShowCustomCss', array($this));
                }
            }
390 391 392
        }
    }

393 394
    function primaryCssLink($mainTheme=null, $media=null)
    {
395 396
        $theme = new Theme($mainTheme);

Bob Mottram's avatar
Bob Mottram committed
397
        // Some themes may have external stylesheets
398 399 400 401
        foreach ($theme->getExternals() as $url) {
            $this->cssLink($url, $mainTheme, $media);
        }

402 403 404 405 406 407 408
        // If the currently-selected theme has dependencies on other themes,
        // we'll need to load their display.css files as well in order.
        $baseThemes = $theme->getDeps();
        foreach ($baseThemes as $baseTheme) {
            $this->cssLink('css/display.css', $baseTheme, $media);
        }
        $this->cssLink('css/display.css', $mainTheme, $media);
409 410 411

        // Additional styles for RTL languages
        if (is_rtl(common_language())) {
412 413 414
            if (file_exists(Theme::file('css/rtl.css'))) {
                $this->cssLink('css/rtl.css', $mainTheme, $media);
            }
415
        }
416 417
    }

Robin Millette's avatar
Robin Millette committed
418 419 420 421 422
    /**
     * Show javascript headers
     *
     * @return nothing
     */
423 424
    function showScripts()
    {
425 426
        if (Event::handle('StartShowScripts', array($this))) {
            if (Event::handle('StartShowJQueryScripts', array($this))) {
427 428 429 430
                $this->script('extlib/jquery.js');
                $this->script('extlib/jquery.form.js');
                $this->script('extlib/jquery-ui/jquery-ui.js');
                $this->script('extlib/jquery.cookie.js');
Shashi Gowda's avatar
Shashi Gowda committed
431

432 433
                Event::handle('EndShowJQueryScripts', array($this));
            }
mmn's avatar
mmn committed
434
            if (Event::handle('StartShowStatusNetScripts', array($this))) {
435 436 437
                $this->script('util.js');
                $this->script('xbImportNode.js');

438 439
                // This route isn't available in single-user mode.
                // Not sure why, but it causes errors here.
440
                $this->inlineScript('var _peopletagAC = "' .
441
                                    common_local_url('peopletagautocomplete') . '";');
442
                $this->showScriptMessages();
443
                $this->showScriptVariables();
444 445 446 447
                // Anti-framing code to avoid clickjacking attacks in older browsers.
                // This will show a blank page if the page is being framed, which is
                // consistent with the behavior of the 'X-Frame-Options: SAMEORIGIN'
                // header, which prevents framing in newer browser.
448
                if (common_config('javascript', 'bustframes')) {
449
                    $this->inlineScript('if (window.top !== window.self) { document.write = ""; window.top.location = window.self.location; setTimeout(function () { document.body.innerHTML = ""; }, 1); window.self.onload = function () { document.body.innerHTML = ""; }; }');
450
                }
451
                Event::handle('EndShowStatusNetScripts', array($this));
452 453 454
            }
            Event::handle('EndShowScripts', array($this));
        }
455 456
    }

457 458 459 460 461 462 463 464 465 466
    /**
     * Exports a map of localized text strings to JavaScript code.
     *
     * Plugins can add to what's exported by hooking the StartScriptMessages or EndScriptMessages
     * events and appending to the array. Try to avoid adding strings that won't be used, as
     * they'll be added to HTML output.
     */
    function showScriptMessages()
    {
        $messages = array();
467

468 469 470 471 472
        if (Event::handle('StartScriptMessages', array($this, &$messages))) {
            // Common messages needed for timeline views etc...

            // TRANS: Localized tooltip for '...' expansion button on overlong remote messages.
            $messages['showmore_tooltip'] = _m('TOOLTIP', 'Show more');
473
            $messages['popup_close_button'] = _m('TOOLTIP', 'Close popup');
474 475

            $messages = array_merge($messages, $this->getScriptMessages());
476

477
            Event::handle('EndScriptMessages', array($this, &$messages));
478
        }
479

480
        if (!empty($messages)) {
481 482
            $this->inlineScript('SN.messages=' . json_encode($messages));
        }
483

484 485 486
        return $messages;
    }

487 488 489 490 491 492 493 494 495 496 497 498 499
    protected function showScriptVariables()
    {
        $vars = array();

        if (Event::handle('StartScriptVariables', array($this, &$vars))) {
            $vars['urlNewNotice'] = common_local_url('newnotice');
        }
        if (!empty($vars)) {
            $this->inlineScript('SN.V = ' . json_encode($vars));
        }
        return $vars;
    }

500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522
    /**
     * If the action will need localizable text strings, export them here like so:
     *
     * return array('pool_deepend' => _('Deep end'),
     *              'pool_shallow' => _('Shallow end'));
     *
     * The exported map will be available via SN.msg() to JS code:
     *
     *   $('#pool').html('<div class="deepend"></div><div class="shallow"></div>');
     *   $('#pool .deepend').text(SN.msg('pool_deepend'));
     *   $('#pool .shallow').text(SN.msg('pool_shallow'));
     *
     * Exports a map of localized text strings to JavaScript code.
     *
     * Plugins can add to what's exported on any action by hooking the StartScriptMessages or
     * EndScriptMessages events and appending to the array. Try to avoid adding strings that won't
     * be used, as they'll be added to HTML output.
     */
    function getScriptMessages()
    {
        return array();
    }

Robin Millette's avatar
Robin Millette committed
523 524 525 526 527
    /**
     * Show OpenSearch headers
     *
     * @return nothing
     */
528 529
    function showOpenSearch()
    {
Robin Millette's avatar
Robin Millette committed
530 531
        $this->element('link', array('rel' => 'search',
                                     'type' => 'application/opensearchdescription+xml',
532 533
                                     'href' =>  common_local_url('opensearch', array('type' => 'people')),
                                     'title' => common_config('site', 'name').' People Search'));
534
        $this->element('link', array('rel' => 'search', 'type' => 'application/opensearchdescription+xml',
535 536 537 538
                                     'href' =>  common_local_url('opensearch', array('type' => 'notice')),
                                     'title' => common_config('site', 'name').' Notice Search'));
    }

Robin Millette's avatar
Robin Millette committed
539 540 541 542 543 544 545
    /**
     * Show feed headers
     *
     * MAY overload
     *
     * @return nothing
     */
546 547
    function showFeeds()
    {
548 549 550 551 552
        foreach ($this->getFeeds() as $feed) {
            $this->element('link', array('rel' => $feed->rel(),
                                         'href' => $feed->url,
                                         'type' => $feed->mimeType(),
                                         'title' => $feed->title));
553
        }
554 555
    }

Robin Millette's avatar
Robin Millette committed
556 557 558 559 560 561 562
    /**
     * Show description.
     *
     * SHOULD overload
     *
     * @return nothing
     */
563 564 565 566 567
    function showDescription()
    {
        // does nothing by default
    }

Robin Millette's avatar
Robin Millette committed
568 569 570 571 572 573 574
    /**
     * Show extra stuff in <head>.
     *
     * MAY overload
     *
     * @return nothing
     */
575 576 577 578 579
    function extraHead()
    {
        // does nothing by default
    }

Robin Millette's avatar
Robin Millette committed
580 581 582 583 584 585 586
    /**
     * Show body.
     *
     * Calls template methods
     *
     * @return nothing
     */
587 588
    function showBody()
    {
589 590 591 592 593
        $params = array('id' => $this->getActionName());
        if ($this->scoped instanceof Profile) {
            $params['class'] = 'user_in';
        }
        $this->elementStart('body', $params);
594
        $this->elementStart('div', array('id' => 'wrap'));
595 596
        if (Event::handle('StartShowHeader', array($this))) {
            $this->showHeader();
Evan Prodromou's avatar
Evan Prodromou committed
597
            $this->flush();
598 599
            Event::handle('EndShowHeader', array($this));
        }
600
        $this->showCore();
Evan Prodromou's avatar
Evan Prodromou committed
601
        $this->flush();
602 603
        if (Event::handle('StartShowFooter', array($this))) {
            $this->showFooter();
Evan Prodromou's avatar
Evan Prodromou committed
604
            $this->flush();
605 606
            Event::handle('EndShowFooter', array($this));
        }
sarven's avatar
sarven committed
607
        $this->elementEnd('div');
608
        $this->showScripts();
609
        $this->elementEnd('body');
610 611
    }

Robin Millette's avatar
Robin Millette committed
612 613 614 615 616 617 618
    /**
     * Show header of the page.
     *
     * Calls template methods
     *
     * @return nothing
     */
619 620
    function showHeader()
    {
sarven's avatar
sarven committed
621
        $this->elementStart('div', array('id' => 'header'));
622 623
        $this->showLogo();
        $this->showPrimaryNav();
624 625 626 627 628
        if (Event::handle('StartShowSiteNotice', array($this))) {
            $this->showSiteNotice();

            Event::handle('EndShowSiteNotice', array($this));
        }
629

sarven's avatar
sarven committed
630
        $this->elementEnd('div');
631 632
    }

Robin Millette's avatar
Robin Millette committed
633 634 635 636 637
    /**
     * Show configured logo.
     *
     * @return nothing
     */
638 639
    function showLogo()
    {
mmn's avatar
mmn committed
640
        $this->elementStart('address', array('id' => 'site_contact', 'class' => 'h-card'));
641
        if (Event::handle('StartAddressData', array($this))) {
Evan Prodromou's avatar
Evan Prodromou committed
642
            if (common_config('singleuser', 'enabled')) {
643
                $user = User::singleUser();
Evan Prodromou's avatar
Evan Prodromou committed
644
                $url = common_local_url('showstream',
645
                                        array('nickname' => $user->nickname));
646 647 648
            } else if (common_logged_in()) {
                $cur = common_current_user();
                $url = common_local_url('all', array('nickname' => $cur->nickname));
Evan Prodromou's avatar
Evan Prodromou committed
649 650 651
            } else {
                $url = common_local_url('public');
            }
652

mmn's avatar
mmn committed
653
            $this->elementStart('a', array('class' => 'home bookmark',
Evan Prodromou's avatar
Evan Prodromou committed
654
                                           'href' => $url));
655

mmn's avatar
mmn committed
656
            if (GNUsocial::isHTTPS()) {
657 658 659 660 661
                $logoUrl = common_config('site', 'ssllogo');
                if (empty($logoUrl)) {
                    // if logo is an uploaded file, try to fall back to HTTPS file URL
                    $httpUrl = common_config('site', 'logo');
                    if (!empty($httpUrl)) {
662
                        $f = File::getKV('url', $httpUrl);
663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678
                        if (!empty($f) && !empty($f->filename)) {
                            // this will handle the HTTPS case
                            $logoUrl = File::url($f->filename);
                        }
                    }
                }
            } else {
                $logoUrl = common_config('site', 'logo');
            }

            if (empty($logoUrl) && file_exists(Theme::file('logo.png'))) {
                // This should handle the HTTPS case internally
                $logoUrl = Theme::path('logo.png');
            }

            if (!empty($logoUrl)) {
mmn's avatar
mmn committed
679
                $this->element('img', array('class' => 'logo u-photo p-name',
680
                                            'src' => $logoUrl,
681 682
                                            'alt' => common_config('site', 'name')));
            }
683

684
            $this->elementEnd('a');
685

686
            Event::handle('EndAddressData', array($this));
sarven's avatar
sarven committed
687
        }
688
        $this->elementEnd('address');
689 690
    }

Robin Millette's avatar
Robin Millette committed
691 692 693 694 695
    /**
     * Show primary navigation.
     *
     * @return nothing
     */
696 697
    function showPrimaryNav()
    {
698
        $this->elementStart('div', array('id' => 'site_nav_global_primary'));
Evan Prodromou's avatar
Evan Prodromou committed
699 700 701 702 703 704 705 706

        $user = common_current_user();

        if (!empty($user) || !common_config('site', 'private')) {
            $form = new SearchForm($this);
            $form->show();
        }

707 708
        $pn = new PrimaryNav($this);
        $pn->show();
709
        $this->elementEnd('div');
710
    }
711

Robin Millette's avatar
Robin Millette committed
712 713 714 715 716
    /**
     * Show site notice.
     *
     * @return nothing
     */
717 718
    function showSiteNotice()
    {
Robin Millette's avatar
Robin Millette committed
719
        // Revist. Should probably do an hAtom pattern here
720 721
        $text = common_config('site', 'notice');
        if ($text) {
722
            $this->elementStart('div', array('id' => 'site_notice',
723
                                            'class' => 'system_notice'));
724
            $this->raw($text);
725
            $this->elementEnd('div');
726
        }
727
    }
728

Robin Millette's avatar
Robin Millette committed
729 730 731 732 733 734 735
    /**
     * Show notice form.
     *
     * MAY overload if no notice form needed... or direct message box????
     *
     * @return nothing
     */
736 737
    function showNoticeForm()
    {
738
        // TRANS: Tab on the notice form.
739 740
        $tabs = array('status' => array('title' => _m('TAB','Status'),
                                        'href'  => common_local_url('newnotice')));
741 742 743

        $this->elementStart('div', 'input_forms');

744 745
        $this->element('label', array('for'=>'input_form_nav'), _m('TAB', 'Share your:'));

746 747 748 749
        if (Event::handle('StartShowEntryForms', array(&$tabs))) {
            $this->elementStart('ul', array('class' => 'nav',
                                            'id' => 'input_form_nav'));

750 751
            foreach ($tabs as $tag => $data) {
                $tag = htmlspecialchars($tag);
752 753
                $attrs = array('id' => 'input_form_nav_'.$tag,
                               'class' => 'input_form_nav_tab');
754

755 756 757
                if ($tag == 'status') {
                    $attrs['class'] .= ' current';
                }
758 759 760
                $this->elementStart('li', $attrs);

                $this->element('a',
761 762 763
                               array('onclick' => 'return SN.U.switchInputFormTab("'.$tag.'");',
                                     'href' => $data['href']),
                               $data['title']);
764 765 766 767 768
                $this->elementEnd('li');
            }

            $this->elementEnd('ul');

769
            foreach ($tabs as $tag => $data) {
770 771
                $attrs = array('class' => 'input_form',
                               'id' => 'input_form_'.$tag);
772 773 774
                if ($tag == 'status') {
                    $attrs['class'] .= ' current';
                }
775 776 777 778 779 780 781

                $this->elementStart('div', $attrs);

                $form = null;

                if (Event::handle('StartMakeEntryForm', array($tag, $this, &$form))) {
                    if ($tag == 'status') {
782 783
                        $options = $this->noticeFormOptions();
                        $form = new NoticeForm($this, $options);
784 785 786 787 788 789 790
                    }
                    Event::handle('EndMakeEntryForm', array($tag, $this, $form));
                }

                if (!empty($form)) {
                    $form->show();
                }
791 792

                $this->elementEnd('div');
793 794
            }
        }
795 796

        $this->elementEnd('div');
797
    }
798

799 800 801 802 803
    function noticeFormOptions()
    {
        return array();
    }

Robin Millette's avatar
Robin Millette committed
804 805 806 807 808 809 810
    /**
     * Show anonymous message.
     *
     * SHOULD overload
     *
     * @return nothing
     */
811 812
    function showAnonymousMessage()
    {
813
        // needs to be defined by the class
814
    }
815

Robin Millette's avatar
Robin Millette committed
816 817 818 819 820 821 822
    /**
     * Show core.
     *
     * Shows local navigation, content block and aside.
     *
     * @return nothing
     */
823 824
    function showCore()
    {
sarven's avatar
sarven committed
825
        $this->elementStart('div', array('id' => 'core'));
826 827 828
        $this->elementStart('div', array('id' => 'aside_primary_wrapper'));
        $this->elementStart('div', array('id' => 'content_wrapper'));
        $this->elementStart('div', array('id' => 'site_nav_local_views_wrapper'));
829 830
        if (Event::handle('StartShowLocalNavBlock', array($this))) {
            $this->showLocalNavBlock();
Evan Prodromou's avatar
Evan Prodromou committed
831
            $this->flush();
832 833
            Event::handle('EndShowLocalNavBlock', array($this));
        }
834 835
        if (Event::handle('StartShowContentBlock', array($this))) {
            $this->showContentBlock();
Evan Prodromou's avatar
Evan Prodromou committed
836
            $this->flush();
837 838
            Event::handle('EndShowContentBlock', array($this));
        }
839 840
        if (Event::handle('StartShowAside', array($this))) {
            $this->showAside();
Evan Prodromou's avatar
Evan Prodromou committed
841
            $this->flush();
842 843
            Event::handle('EndShowAside', array($this));
        }
844
        $this->elementEnd('div');
845 846 847
        $this->elementEnd('div');
        $this->elementEnd('div');
        $this->elementEnd('div');
848 849
    }

Robin Millette's avatar
Robin Millette committed
850 851 852 853 854
    /**
     * Show local navigation block.
     *
     * @return nothing
     */
855 856
    function showLocalNavBlock()
    {
857 858 859
        // Need to have this ID for CSS; I'm too lazy to add it to
        // all menus
        $this->elementStart('div', array('id' => 'site_nav_local_views'));
860
        // Cheat cheat cheat!
861
        $this->showLocalNav();
862
        $this->elementEnd('div');
863 864
    }

865 866 867 868 869 870 871 872 873 874 875 876 877
    /**
     * If there's a logged-in user, show a bit of login context
     *
     * @return nothing
     */
    function showProfileBlock()
    {
        if (common_logged_in()) {
            $block = new DefaultProfileBlock($this);
            $block->show();
        }
    }

Robin Millette's avatar
Robin Millette committed
878 879 880 881 882 883 884
    /**
     * Show local navigation.
     *
     * SHOULD overload
     *
     * @return nothing
     */
885
    function showLocalNav()
886
    {
887 888
        $nav = new DefaultLocalNav($this);
        $nav->show();
889 890
    }

Robin Millette's avatar
Robin Millette committed
891
    /**
892 893
     * Show menu for an object (group, profile)
     *
894 895 896
     * This block will only show if a subclass has overridden
     * the showObjectNav() method.
     *
897 898 899 900
     * @return nothing
     */
    function showObjectNavBlock()
    {
901 902 903 904 905 906 907 908 909 910 911
        $rmethod = new ReflectionMethod($this, 'showObjectNav');
        $dclass = $rmethod->getDeclaringClass()->getName();

        if ($dclass != 'Action') {
            // Need to have this ID for CSS; I'm too lazy to add it to
            // all menus
            $this->elementStart('div', array('id' => 'site_nav_object',
                                             'class' => 'section'));
            $this->showObjectNav();
            $this->elementEnd('div');
        }
912 913 914 915 916 917 918 919 920 921 922 923
    }

    /**
     * Show object navigation.
     *
     * If there are things to do with this object, show it here.
     *
     * @return nothing
     */
    function showObjectNav()
    {
        /* Nothing here. */
924 925
    }

Robin Millette's avatar
Robin Millette committed
926 927 928 929 930
    /**
     * Show content block.
     *
     * @return nothing
     */
931 932
    function showContentBlock()
    {
933
        $this->elementStart('div', array('id' => 'content'));
934 935 936 937 938 939
        if (common_logged_in()) {
            if (Event::handle('StartShowNoticeForm', array($this))) {
                $this->showNoticeForm();
                Event::handle('EndShowNoticeForm', array($this));
            }
        }
940 941 942 943
        if (Event::handle('StartShowPageTitle', array($this))) {
            $this->showPageTitle();
            Event::handle('EndShowPageTitle', array($this));
        }
944
        $this->showPageNoticeBlock();
945 946
        $this->elementStart('div', array('id' => 'content_inner'));
        // show the actual content (forms, lists, whatever)
947
        $this->showContent();
sarven's avatar
sarven committed
948
        $this->elementEnd('div');
949
        $this->elementEnd('div');
950 951
    }

Robin Millette's avatar
Robin Millette committed
952 953 954 955 956 957 958 959
    /**
     * Show page title.
     *
     * @return nothing
     */
    function showPageTitle()
    {
        $this->element('h1', null, $this->title());
960 961
    }

Robin Millette's avatar
Robin Millette committed
962 963 964
    /**
     * Show page notice block.
     *
965 966 967 968 969 970
     * Only show the block if a subclassed action has overrided
     * Action::showPageNotice(), or an event handler is registered for
     * the StartShowPageNotice event, in which case we assume the
     * 'page_notice' definition list is desired.  This is to prevent
     * empty 'page_notice' definition lists from being output everywhere.
     *
Robin Millette's avatar
Robin Millette committed
971 972
     * @return nothing
     */
973 974
    function showPageNoticeBlock()
    {
975 976 977 978 979
        $rmethod = new ReflectionMethod($this, 'showPageNotice');
        $dclass = $rmethod->getDeclaringClass()->getName();

        if ($dclass != 'Action' || Event::hasHandler('StartShowPageNotice')) {

980
            $this->elementStart('div', array('id' => 'page_notice',
981 982 983 984 985
                                            'class' => 'system_notice'));
            if (Event::handle('StartShowPageNotice', array($this))) {
                $this->showPageNotice();
                Event::handle('EndShowPageNotice', array($this));
            }
986
            $this->elementEnd('div');
987
        }
Robin Millette's avatar
Robin Millette committed
988
    }
989

Robin Millette's avatar
Robin Millette committed
990 991 992 993 994 995 996
    /**
     * Show page notice.
     *
     * SHOULD overload (unless there's not a notice)
     *
     * @return nothing
     */
997 998 999
    function showPageNotice()
    {
    }
1000

Robin Millette's avatar
Robin Millette committed
1001 1002 1003 1004 1005 1006 1007
    /**
     * Show content.
     *
     * MUST overload (unless there's not a notice)
     *
     * @return nothing
     */
1008
    protected function showContent()
1009 1010 1011
    {
    }

Robin Millette's avatar
Robin Millette committed
1012 1013 1014 1015 1016
    /**
     * Show Aside.
     *
     * @return nothing
     */
1017 1018
    function showAside()
    {
sarven's avatar
sarven committed
1019 1020
        $this->elementStart('div', array('id' => 'aside_primary',
                                         'class' => 'aside'));
1021
        $this->showProfileBlock();
1022 1023 1024 1025
        if (Event::handle('StartShowObjectNavBlock', array($this))) {
            $this->showObjectNavBlock();
            Event::handle('EndShowObjectNavBlock', array($this));
        }
1026 1027 1028 1029
        if (Event::handle('StartShowSections', array($this))) {
            $this->showSections();
            Event::handle('EndShowSections', array($this));
        }
1030 1031 1032 1033
        if (Event::handle('StartShowExportData', array($this))) {
            $this->showExportData();
            Event::handle('EndShowExportData', array($this));
        }
sarven's avatar
sarven committed
1034
        $this->elementEnd('div');
1035 1036
    }

Robin Millette's avatar
Robin Millette committed
1037 1038 1039
    /**
     * Show export data feeds.
     *
1040
     * @return void
Robin Millette's avatar
Robin Millette committed
1041
     */
1042 1043
    function showExportData()
    {
1044
        $feeds = $this->getFeeds();
1045 1046 1047
        if (!empty($feeds)) {
            $fl = new FeedList($this, $feeds);
            $fl->show();
1048
        }
1049 1050
    }

Robin Millette's avatar
Robin Millette committed
1051 1052 1053 1054 1055 1056 1057 1058 1059
    /**
     * Show sections.
     *
     * SHOULD overload
     *
     * @return nothing
     */
    function showSections()
    {
1060 1061 1062
        // for each section, show it
    }

Robin Millette's avatar
Robin Millette committed
1063 1064 1065 1066 1067
    /**
     * Show footer.
     *
     * @return nothing
     */
1068 1069
    function showFooter()
    {
sarven's avatar
sarven committed
1070
        $this->elementStart('div', array('id' => 'footer'));
1071 1072 1073 1074 1075
        if (Event::handle('StartShowInsideFooter', array($this))) {
            $this->showSecondaryNav();
            $this->showLicenses();
            Event::handle('EndShowInsideFooter', array($this));
        }
sarven's avatar
sarven committed
1076
        $this->elementEnd('div');
1077 1078
    }

Robin Millette's avatar
Robin Millette committed
1079 1080 1081 1082 1083
    /**
     * Show secondary navigation.
     *
     * @return nothing
     */
1084 1085
    function showSecondaryNav()
    {
1086 1087
        $sn = new SecondaryNav($this);
        $sn->show();
1088 1089
    }

Robin Millette's avatar
Robin Millette committed
1090 1091 1092 1093 1094
    /**
     * Show licenses.
     *
     * @return nothing
     */
1095 1096
    function showLicenses()
    {
1097
        $this->showGNUsocialLicense();
1098 1099 1100
        $this->showContentLicense();
    }

Robin Millette's avatar
Robin Millette committed
1101
    /**
1102
     * Show GNU social license.
Robin Millette's avatar
Robin Millette committed
1103 1104 1105
     *
     * @return nothing
     */
1106
    function showGNUsocialLicense()
1107 1108
    {
        if (common_config('site', 'broughtby')) {
1109
            // TRANS: First sentence of the GNU social site license. Used if 'broughtby' is set.
1110 1111 1112
            // TRANS: Text between [] is a link description, text between () is the link itself.
            // TRANS: Make sure there is no whitespace between "]" and "(".
            // TRANS: "%%site.broughtby%%" is the value of the variable site.broughtby
mattl's avatar
mattl committed
1113
            $instr = _('**%%site.name%%** is a social network, courtesy of [%%site.broughtby%%](%%site.broughtbyurl%%).');
1114
        } else {
1115
            // TRANS: First sentence of the GNU social site license. Used if 'broughtby' is not set.
mattl's avatar
mattl committed
1116
            $instr = _('**%%site.name%%** is a social network.');
1117
        }
1118
        $instr .= ' ';
1119
        // TRANS: Second sentence of the GNU social site license. Mentions the GNU social source code license.
1120
        // TRANS: Make sure there is no whitespace between "]" and "(".
1121 1122
        // TRANS: [%1$s](%2$s) is a link description followed by the link itself
        // TRANS: %3$s is the version of GNU social that is being used.
1123
        $instr .= sprintf(_('It runs on [%1$s](%2$s), version %3$s, available under the [GNU Affero General Public License](http://www.fsf.org/licensing/licenses/agpl-3.0.html).'), GNUSOCIAL_ENGINE, GNUSOCIAL_ENGINE_URL, GNUSOCIAL_VERSION);
1124
        $output = common_markup_to_html($instr);
1125
        $this->raw($output);
1126 1127 1128
        // do it
    }

Robin Millette's avatar
Robin Millette committed
1129 1130 1131 1132 1133
    /**
     * Show content license.
     *
     * @return nothing
     */
1134 1135
    function showContentLicense()
    {
1136
        if (Event::handle('StartShowContentLicense', array($this))) {
1137 1138
            switch (common_config('license', 'type')) {
            case 'private':
1139 1140
                // TRANS: Content license displayed when license is set to 'private'.
                // TRANS: %1$s is the site name.
1141 1142 1143 1144 1145
                $this->element('p', null, sprintf(_('Content and data of %1$s are private and confidential.'),
                                                  common_config('site', 'name')));
                // fall through
            case 'allrightsreserved':
                if (common_config('license', 'owner')) {
1146 1147
                    // TRANS: Content license displayed when license is set to 'allrightsreserved'.
                    // TRANS: %1$s is the copyright owner.
1148 1149 1150
                    $this->element('p', null, sprintf(_('Content and data copyright by %1$s. All rights reserved.'),
                                                      common_config('license', 'owner')));
                } else {
1151
                    // TRANS: Content license displayed when license is set to 'allrightsreserved' and no owner is set.
1152 1153 1154 1155 1156 1157
                    $this->element('p', null, _('Content and data copyright by contributors. All rights reserved.'));
                }
                break;
            case 'cc': // fall through
            default:
                $this->elementStart('p');
1158 1159 1160 1161

                $image    = common_config('license', 'image');
                $sslimage = common_config('license', 'sslimage');

mmn's avatar
mmn committed
1162
                if (GNUsocial::isHTTPS()) {
1163 1164 1165 1166
                    if (!empty($sslimage)) {
                        $url = $sslimage;
                    } else if (preg_match('#^http://i.creativecommons.org/#', $image)) {
                        // CC support HTTPS on their images
1167
                        $url = preg_replace('/^http/', 'https', $image, 1);
1168 1169 1170 1171 1172 1173 1174 1175
                    } else {
                        // Better to show mixed content than no content
                        $url = $image;
                    }
                } else {
                    $url = $image;
                }

1176
                $this->element('img', array('id' => 'license_cc',
1177
                                            'src' => $url,
1178 1179 1180
                                            'alt' => common_config('license', 'title'),
                                            'width' => '80',
                                            'height' => '15'));
1181
                $this->text(' ');
1182 1183
                // TRANS: license message in footer.
                // TRANS: %1$s is the site name, %2$s is a link to the license URL, with a licence name set in configuration.
1184
                $notice = _('All %1$s content and data are available under the %2$s license.');
mmn's avatar
mmn committed
1185 1186 1187
                $link = sprintf('<a class="license" rel="external license" href="%1$s">%2$s</a>',
                                htmlspecialchars(common_config('license', 'url')),
                                htmlspecialchars(common_config('license', 'title')));
1188
                $this->raw(@sprintf(htmlspecialchars($notice),
1189 1190
                                   htmlspecialchars(common_config('site', 'name')),
                                   $link));
1191 1192 1193 1194
                $this->elementEnd('p');
                break;
            }

1195 1196
            Event::handle('EndShowContentLicense', array($this));
        }
1197 1198
    }

Robin Millette's avatar
Robin Millette committed
1199 1200 1201 1202 1203 1204 1205
    /**
     * Return last modified, if applicable.
     *
     * MAY override
     *
     * @return string last modified http header
     */
1206
    function lastModified()
1207
    {
Robin Millette's avatar
Robin Millette committed
1208 1209
        // For comparison with If-Last-Modified
        // If not applicable, return null
1210 1211 1212
        return null;
    }

Robin Millette's avatar
Robin Millette committed
1213 1214 1215 1216 1217 1218 1219
    /**
     * Return etag, if applicable.
     *
     * MAY override
     *
     * @return string etag http header
     */
1220 1221 1222 1223 1224
    function etag()
    {
        return null;
    }

Robin Millette's avatar
Robin Millette committed
1225 1226 1227 1228 1229
    /**
     * Return true if read only.
     *
     * MAY override
     *
1230 1231
     * @param array $args other arguments
     *
Robin Millette's avatar
Robin Millette committed
1232 1233
     * @return boolean is read only action?
     */
Evan Prodromou's avatar
Evan Prodromou committed
1234
    function isReadOnly($args)
1235 1236 1237 1238
    {
        return false;
    }

Robin Millette's avatar
Robin Millette committed
1239 1240 1241 1242 1243 1244 1245 1246
    /**
     * Returns query argument or default value if not found
     *
     * @param string $key requested argument
     * @param string $def default value to return if $key is not provided
     *
     * @return boolean is read only action?
     */
1247 1248 1249 1250 1251 1252 1253 1254 1255
    function arg($key, $def=null)
    {
        if (array_key_exists($key, $this->args)) {
            return $this->args[$key];
        } else {
            return $def;
        }
    }

Robin Millette's avatar
Robin Millette committed
1256 1257 1258 1259 1260 1261 1262 1263
    /**
     * Returns trimmed query argument or default value if not found
     *
     * @param string $key requested argument
     * @param string $def default value to return if $key is not provided
     *
     * @return boolean is read only action?
     */
1264 1265 1266
    function trimmed($key, $def=null)
    {
        $arg = $this->arg($key, $def);
Robin Millette's avatar
Robin Millette committed
1267
        return is_string($arg) ? trim($arg) : $arg;
1268 1269
    }

Robin Millette's avatar
Robin Millette committed
1270 1271 1272 1273 1274
    /**
     * Handler method
     *
     * @return boolean is read only action?
     */
1275
    protected function handle()
1276
    {
1277
        header('Vary: Accept-Encoding,Cookie');
1278

Robin Millette's avatar
Robin Millette committed
1279
        $lm   = $this->lastModified();
1280
        $etag = $this->etag();
1281

1282 1283 1284
        if ($etag) {
            header('ETag: ' . $etag);
        }
1285

1286 1287
        if ($lm) {
            header('Last-Modified: ' . date(DATE_RFC1123, $lm));
1288 1289 1290
            if ($this->isCacheable()) {
                header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
                header( "Cache-Control: private, must-revalidate, max-age=0" );
1291
                header( "Pragma:");
1292 1293 1294
            }
        }

1295
        $checked = false;
1296 1297 1298
        if ($etag) {
            $if_none_match = (array_key_exists('HTTP_IF_NONE_MATCH', $_SERVER)) ?
              $_SERVER['HTTP_IF_NONE_MATCH'] : null;
1299 1300 1301 1302 1303 1304 1305
            if ($if_none_match) {
                // If this check fails, ignore the if-modified-since below.
                $checked = true;
                if ($this->_hasEtag($etag, $if_none_match)) {
                    header('HTTP/1.1 304 Not Modified');
                    // Better way to do this?
                    exit(0);
1306 1307 1308
                }
            }
        }
1309

1310
        if (!$checked && $lm && array_key_exists('HTTP_IF_MODIFIED_SINCE', $_SERVER)) {
1311 1312 1313 1314 1315 1316
            $if_modified_since = $_SERVER['HTTP_IF_MODIFIED_SINCE'];
            $ims = strtotime($if_modified_since);
            if ($lm <= $ims) {
                header('HTTP/1.1 304 Not Modified');
                // Better way to do this?
                exit(0);
1317
            }
1318 1319 1320
        }
    }

1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332
    /**
     * Is this action cacheable?
     *
     * If the action returns a last-modified
     *
     * @param array $argarray is ignored since it's now passed in in prepare()
     *
     * @return boolean is read only action?
     */
    function isCacheable()
    {
        return true;
1333 1334
    }

Robin Millette's avatar
Robin Millette committed
1335 1336 1337 1338 1339 1340 1341 1342
    /**
     * Has etag? (private)
     *
     * @param string $etag          etag http header
     * @param string $if_none_match ifNoneMatch http header
     *
     * @return boolean
     */
1343
    function _hasEtag($etag, $if_none_match)
1344
    {
1345 1346
        $etags = explode(',', $if_none_match);
        return in_array($etag, $etags) || in_array('*', $etags);
1347 1348
    }

Robin Millette's avatar
Robin Millette committed
1349 1350 1351
    /**
     * Boolean understands english (yes, no, true, false)
     *
1352
     * @param string $key query key we're interested in
Robin Millette's avatar
Robin Millette committed
1353 1354 1355 1356
     * @param string $def default value
     *
     * @return boolean interprets yes/no strings as boolean
     */
1357 1358 1359 1360 1361 1362
    function boolean($key, $def=false)
    {
        $arg = strtolower($this->trimmed($key));

        if (is_null($arg)) {
            return $def;
1363
        } else if (in_array($arg, array('true', 'yes', '1', 'on'))) {
1364 1365 1366 1367 1368 1369 1370 1371
            return true;
        } else if (in_array($arg, array('false', 'no', '0'))) {
            return false;
        } else {
            return $def;
        }
    }

1372 1373 1374 1375 1376 1377 1378 1379
    /**
     * This is a cheap hack to avoid a bug in DB_DataObject
     * where '' is non-type-aware compared to 0, which means it
     * will always be true for values like false and 0 too...
     *
     * Upstream bug is::
     * https://pear.php.net/bugs/bug.php?id=20291
     */
mmn's avatar
mmn committed
1380
    function booleanintstring($key, $def=false)
1381 1382 1383 1384
    {
        return $this->boolean($key, $def) ? '1' : '0';
    }

1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396
    /**
     * Integer value of an argument
     *
     * @param string $key      query key we're interested in
     * @param string $defValue optional default value (default null)
     * @param string $maxValue optional max value (default null)
     * @param string $minValue optional min value (default null)
     *
     * @return integer integer value
     */
    function int($key, $defValue=null, $maxValue=null, $minValue=null)
    {
1397
        $arg = intval($this->arg($key));
1398

1399
        if (!is_numeric($this->arg($key)) || $arg != $this->arg($key)) {
1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413
            return $defValue;
        }

        if (!is_null($maxValue)) {
            $arg = min($arg, $maxValue);
        }

        if (!is_null($minValue)) {
            $arg = max($arg, $minValue);
        }

        return $arg;
    }