zend-framework /Session.php

Language PHP Lines 899
MD5 Hash c2189dc4f94f9aa2ede57f4affa36430 Estimated Cost $11,301 (why?)
Repository https://bitbucket.org/bigstylee/zend-framework.git View Raw File View Project SPDX
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
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
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
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
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
<?php

/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Session
 * @copyright  Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Session.php 24819 2012-05-28 19:25:03Z rob $
 * @since      Preview Release 0.2
 */


/**
 * @see Zend_Session_Abstract
 */
require_once 'Zend/Session/Abstract.php';

/**
 * @see Zend_Session_Namespace
 */
require_once 'Zend/Session/Namespace.php';

/**
 * @see Zend_Session_SaveHandler_Interface
 */
require_once 'Zend/Session/SaveHandler/Interface.php';


/**
 * Zend_Session
 *
 * @category   Zend
 * @package    Zend_Session
 * @copyright  Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Session extends Zend_Session_Abstract
{
    /**
     * Whether or not Zend_Session is being used with unit tests
     *
     * @internal
     * @var bool
     */
    public static $_unitTestEnabled = false;

    /**
     * $_throwStartupException
     *
     * @var bool|bitset This could also be a combiniation of error codes to catch
     */
    protected static $_throwStartupExceptions = true;

    /**
     * Check whether or not the session was started
     *
     * @var bool
     */
    private static $_sessionStarted = false;

    /**
     * Whether or not the session id has been regenerated this request.
     *
     * Id regeneration state
     * <0 - regenerate requested when session is started
     * 0  - do nothing
     * >0 - already called session_regenerate_id()
     *
     * @var int
     */
    private static $_regenerateIdState = 0;

    /**
     * Private list of php's ini values for ext/session
     * null values will default to the php.ini value, otherwise
     * the value below will overwrite the default ini value, unless
     * the user has set an option explicity with setOptions()
     *
     * @var array
     */
    private static $_defaultOptions = array(
        'save_path'                 => null,
        'name'                      => null, /* this should be set to a unique value for each application */
        'save_handler'              => null,
        //'auto_start'                => null, /* intentionally excluded (see manual) */
        'gc_probability'            => null,
        'gc_divisor'                => null,
        'gc_maxlifetime'            => null,
        'serialize_handler'         => null,
        'cookie_lifetime'           => null,
        'cookie_path'               => null,
        'cookie_domain'             => null,
        'cookie_secure'             => null,
        'cookie_httponly'           => null,
        'use_cookies'               => null,
        'use_only_cookies'          => 'on',
        'referer_check'             => null,
        'entropy_file'              => null,
        'entropy_length'            => null,
        'cache_limiter'             => null,
        'cache_expire'              => null,
        'use_trans_sid'             => null,
        'bug_compat_42'             => null,
        'bug_compat_warn'           => null,
        'hash_function'             => null,
        'hash_bits_per_character'   => null
    );

    /**
     * List of options pertaining to Zend_Session that can be set by developers
     * using Zend_Session::setOptions(). This list intentionally duplicates
     * the individual declaration of static "class" variables by the same names.
     *
     * @var array
     */
    private static $_localOptions = array(
        'strict'                => '_strict',
        'remember_me_seconds'   => '_rememberMeSeconds',
        'throw_startup_exceptions' => '_throwStartupExceptions'
    );

    /**
     * Whether or not write close has been performed.
     *
     * @var bool
     */
    private static $_writeClosed = false;

    /**
     * Whether or not session id cookie has been deleted
     *
     * @var bool
     */
    private static $_sessionCookieDeleted = false;

    /**
     * Whether or not session has been destroyed via session_destroy()
     *
     * @var bool
     */
    private static $_destroyed = false;

    /**
     * Whether or not session must be initiated before usage
     *
     * @var bool
     */
    private static $_strict = false;

    /**
     * Default number of seconds the session will be remembered for when asked to be remembered
     *
     * @var int
     */
    private static $_rememberMeSeconds = 1209600; // 2 weeks

    /**
     * Whether the default options listed in Zend_Session::$_localOptions have been set
     *
     * @var bool
     */
    private static $_defaultOptionsSet = false;

    /**
     * A reference to the set session save handler
     *
     * @var Zend_Session_SaveHandler_Interface
     */
    private static $_saveHandler = null;


    /**
     * Constructor overriding - make sure that a developer cannot instantiate
     */
    protected function __construct()
    {
    }


    /**
     * setOptions - set both the class specified
     *
     * @param  array $userOptions - pass-by-keyword style array of <option name, option value> pairs
     * @throws Zend_Session_Exception
     * @return void
     */
    public static function setOptions(array $userOptions = array())
    {
        // set default options on first run only (before applying user settings)
        if (!self::$_defaultOptionsSet) {
            foreach (self::$_defaultOptions as $defaultOptionName => $defaultOptionValue) {
                if (isset(self::$_defaultOptions[$defaultOptionName])) {
                    ini_set("session.$defaultOptionName", $defaultOptionValue);
                }
            }

            self::$_defaultOptionsSet = true;
        }

        // set the options the user has requested to set
        foreach ($userOptions as $userOptionName => $userOptionValue) {

            $userOptionName = strtolower($userOptionName);

            // set the ini based values
            if (array_key_exists($userOptionName, self::$_defaultOptions)) {
                ini_set("session.$userOptionName", $userOptionValue);
            }
            elseif (isset(self::$_localOptions[$userOptionName])) {
                self::${self::$_localOptions[$userOptionName]} = $userOptionValue;
            }
            else {
                /** @see Zend_Session_Exception */
                require_once 'Zend/Session/Exception.php';
                throw new Zend_Session_Exception("Unknown option: $userOptionName = $userOptionValue");
            }
        }
    }

    /**
     * getOptions()
     *
     * @param string $optionName OPTIONAL
     * @return array|string
     */
    public static function getOptions($optionName = null)
    {
        $options = array();
        foreach (ini_get_all('session') as $sysOptionName => $sysOptionValues) {
            $options[substr($sysOptionName, 8)] = $sysOptionValues['local_value'];
        }
        foreach (self::$_localOptions as $localOptionName => $localOptionMemberName) {
            $options[$localOptionName] = self::${$localOptionMemberName};
        }

        if ($optionName) {
            if (array_key_exists($optionName, $options)) {
                return $options[$optionName];
            }
            return null;
        }

        return $options;
    }

    /**
     * setSaveHandler() - Session Save Handler assignment
     *
     * @param Zend_Session_SaveHandler_Interface $interface
     * @return void
     */
    public static function setSaveHandler(Zend_Session_SaveHandler_Interface $saveHandler)
    {
        self::$_saveHandler = $saveHandler;

        if (self::$_unitTestEnabled) {
            return;
        }

        session_set_save_handler(
            array(&$saveHandler, 'open'),
            array(&$saveHandler, 'close'),
            array(&$saveHandler, 'read'),
            array(&$saveHandler, 'write'),
            array(&$saveHandler, 'destroy'),
            array(&$saveHandler, 'gc')
            );
    }


    /**
     * getSaveHandler() - Get the session Save Handler
     *
     * @return Zend_Session_SaveHandler_Interface
     */
    public static function getSaveHandler()
    {
        return self::$_saveHandler;
    }


    /**
     * regenerateId() - Regenerate the session id.  Best practice is to call this after
     * session is started.  If called prior to session starting, session id will be regenerated
     * at start time.
     *
     * @throws Zend_Session_Exception
     * @return void
     */
    public static function regenerateId()
    {
        if (!self::$_unitTestEnabled && headers_sent($filename, $linenum)) {
            /** @see Zend_Session_Exception */
            require_once 'Zend/Session/Exception.php';
            throw new Zend_Session_Exception("You must call " . __CLASS__ . '::' . __FUNCTION__ .
                "() before any output has been sent to the browser; output started in {$filename}/{$linenum}");
        }

        if ( !self::$_sessionStarted ) {
            self::$_regenerateIdState = -1;
        } else {
            if (!self::$_unitTestEnabled) {
                session_regenerate_id(true);
            }
            self::$_regenerateIdState = 1;
        }
    }


    /**
     * rememberMe() - Write a persistent cookie that expires after a number of seconds in the future. If no number of
     * seconds is specified, then this defaults to self::$_rememberMeSeconds.  Due to clock errors on end users' systems,
     * large values are recommended to avoid undesirable expiration of session cookies.
     *
     * @param int $seconds OPTIONAL specifies TTL for cookie in seconds from present time
     * @return void
     */
    public static function rememberMe($seconds = null)
    {
        $seconds = (int) $seconds;
        $seconds = ($seconds > 0) ? $seconds : self::$_rememberMeSeconds;

        self::rememberUntil($seconds);
    }


    /**
     * forgetMe() - Write a volatile session cookie, removing any persistent cookie that may have existed. The session
     * would end upon, for example, termination of a web browser program.
     *
     * @return void
     */
    public static function forgetMe()
    {
        self::rememberUntil(0);
    }


    /**
     * rememberUntil() - This method does the work of changing the state of the session cookie and making
     * sure that it gets resent to the browser via regenerateId()
     *
     * @param int $seconds
     * @return void
     */
    public static function rememberUntil($seconds = 0)
    {
        if (self::$_unitTestEnabled) {
            self::regenerateId();
            return;
        }

        $cookieParams = session_get_cookie_params();

        session_set_cookie_params(
            $seconds,
            $cookieParams['path'],
            $cookieParams['domain'],
            $cookieParams['secure']
            );

        // normally "rememberMe()" represents a security context change, so should use new session id
        self::regenerateId();
    }


    /**
     * sessionExists() - whether or not a session exists for the current request
     *
     * @return bool
     */
    public static function sessionExists()
    {
        if ((bool)ini_get('session.use_cookies') == true && isset($_COOKIE[session_name()])) {
            return true;
        } elseif ((bool)ini_get('session.use_only_cookies') == false && isset($_REQUEST[session_name()])) {
            return true;
        } elseif (self::$_unitTestEnabled) {
            return true;
        }

        return false;
    }


    /**
     * Whether or not session has been destroyed via session_destroy()
     *
     * @return bool
     */
    public static function isDestroyed()
    {
        return self::$_destroyed;
    }


    /**
     * start() - Start the session.
     *
     * @param bool|array $options  OPTIONAL Either user supplied options, or flag indicating if start initiated automatically
     * @throws Zend_Session_Exception
     * @return void
     */
    public static function start($options = false)
    {
        // Check to see if we've been passed an invalid session ID
        if ( self::getId() && !self::_checkId(self::getId()) ) {
            // Generate a valid, temporary replacement
            self::setId(md5(self::getId()));
            // Force a regenerate after session is started
            self::$_regenerateIdState = -1;
        }

        if (self::$_sessionStarted && self::$_destroyed) {
            require_once 'Zend/Session/Exception.php';
            throw new Zend_Session_Exception('The session was explicitly destroyed during this request, attempting to re-start is not allowed.');
        }

        if (self::$_sessionStarted) {
            return; // already started
        }

        // make sure our default options (at the least) have been set
        if (!self::$_defaultOptionsSet) {
            self::setOptions(is_array($options) ? $options : array());
        }

        // In strict mode, do not allow auto-starting Zend_Session, such as via "new Zend_Session_Namespace()"
        if (self::$_strict && $options === true) {
            /** @see Zend_Session_Exception */
            require_once 'Zend/Session/Exception.php';
            throw new Zend_Session_Exception('You must explicitly start the session with Zend_Session::start() when session options are set to strict.');
        }

        $filename = $linenum = null;
        if (!self::$_unitTestEnabled && headers_sent($filename, $linenum)) {
            /** @see Zend_Session_Exception */
            require_once 'Zend/Session/Exception.php';
            throw new Zend_Session_Exception("Session must be started before any output has been sent to the browser;"
               . " output started in {$filename}/{$linenum}");
        }

        // See http://www.php.net/manual/en/ref.session.php for explanation
        if (!self::$_unitTestEnabled && defined('SID')) {
            /** @see Zend_Session_Exception */
            require_once 'Zend/Session/Exception.php';
            throw new Zend_Session_Exception('session has already been started by session.auto-start or session_start()');
        }

        /**
         * Hack to throw exceptions on start instead of php errors
         * @see http://framework.zend.com/issues/browse/ZF-1325
         */

        $errorLevel = (is_int(self::$_throwStartupExceptions)) ? self::$_throwStartupExceptions : E_ALL;

        /** @see Zend_Session_Exception */
        if (!self::$_unitTestEnabled) {

            if (self::$_throwStartupExceptions) {
                require_once 'Zend/Session/Exception.php';
                set_error_handler(array('Zend_Session_Exception', 'handleSessionStartError'), $errorLevel);
            }

            $startedCleanly = session_start();

            if (self::$_throwStartupExceptions) {
                restore_error_handler();
            }

            if (!$startedCleanly || Zend_Session_Exception::$sessionStartError != null) {
                if (self::$_throwStartupExceptions) {
                    set_error_handler(array('Zend_Session_Exception', 'handleSilentWriteClose'), $errorLevel);
                }
                session_write_close();
                if (self::$_throwStartupExceptions) {
                    restore_error_handler();
                    throw new Zend_Session_Exception(__CLASS__ . '::' . __FUNCTION__ . '() - ' . Zend_Session_Exception::$sessionStartError);
                }
            }
        }

        parent::$_readable = true;
        parent::$_writable = true;
        self::$_sessionStarted = true;
        if (self::$_regenerateIdState === -1) {
            self::regenerateId();
        }

        // run validators if they exist
        if (isset($_SESSION['__ZF']['VALID'])) {
            self::_processValidators();
        }

        self::_processStartupMetadataGlobal();
    }

    /**
     * Perform a hash-bits check on the session ID
     *
     * @param string $id Session ID
     * @return bool
     */
    protected static function _checkId($id)
    {
        $hashBitsPerChar = ini_get('session.hash_bits_per_character');
        if (!$hashBitsPerChar) {
            $hashBitsPerChar = 5; // the default value
        }
        switch($hashBitsPerChar) {
            case 4: $pattern = '^[0-9a-f]*$'; break;
            case 5: $pattern = '^[0-9a-v]*$'; break;
            case 6: $pattern = '^[0-9a-zA-Z-,]*$'; break;
        }
        return preg_match('#'.$pattern.'#', $id);
    }


    /**
     * _processGlobalMetadata() - this method initizes the sessions GLOBAL
     * metadata, mostly global data expiration calculations.
     *
     * @return void
     */
    private static function _processStartupMetadataGlobal()
    {
        // process global metadata
        if (isset($_SESSION['__ZF'])) {

            // expire globally expired values
            foreach ($_SESSION['__ZF'] as $namespace => $namespace_metadata) {

                // Expire Namespace by Time (ENT)
                if (isset($namespace_metadata['ENT']) && ($namespace_metadata['ENT'] > 0) && (time() > $namespace_metadata['ENT']) ) {
                    unset($_SESSION[$namespace]);
                    unset($_SESSION['__ZF'][$namespace]);
                }

                // Expire Namespace by Global Hop (ENGH) if it wasnt expired above
                if (isset($_SESSION['__ZF'][$namespace]) && isset($namespace_metadata['ENGH']) && $namespace_metadata['ENGH'] >= 1) {

                    $_SESSION['__ZF'][$namespace]['ENGH']--;

                    if ($_SESSION['__ZF'][$namespace]['ENGH'] === 0) {
                        if (isset($_SESSION[$namespace])) {
                            parent::$_expiringData[$namespace] = $_SESSION[$namespace];
                            unset($_SESSION[$namespace]);
                        }
                        unset($_SESSION['__ZF'][$namespace]);
                    }
                }

                // Expire Namespace Variables by Time (ENVT)
                if (isset($namespace_metadata['ENVT'])) {
                    foreach ($namespace_metadata['ENVT'] as $variable => $time) {
                        if (time() > $time) {
                            unset($_SESSION[$namespace][$variable]);
                            unset($_SESSION['__ZF'][$namespace]['ENVT'][$variable]);
                        }
                    }
                    if (empty($_SESSION['__ZF'][$namespace]['ENVT'])) {
                        unset($_SESSION['__ZF'][$namespace]['ENVT']);
                    }
                }

                // Expire Namespace Variables by Global Hop (ENVGH)
                if (isset($namespace_metadata['ENVGH'])) {
                    foreach ($namespace_metadata['ENVGH'] as $variable => $hops) {
                        $_SESSION['__ZF'][$namespace]['ENVGH'][$variable]--;

                        if ($_SESSION['__ZF'][$namespace]['ENVGH'][$variable] === 0) {
                            if (isset($_SESSION[$namespace][$variable])) {
                                parent::$_expiringData[$namespace][$variable] = $_SESSION[$namespace][$variable];
                                unset($_SESSION[$namespace][$variable]);
                            }
                            unset($_SESSION['__ZF'][$namespace]['ENVGH'][$variable]);
                        }
                    }
                    if (empty($_SESSION['__ZF'][$namespace]['ENVGH'])) {
                        unset($_SESSION['__ZF'][$namespace]['ENVGH']);
                    }
                }
                
                if (isset($namespace) && empty($_SESSION['__ZF'][$namespace])) {
                    unset($_SESSION['__ZF'][$namespace]);
                }
            }
        }

        if (isset($_SESSION['__ZF']) && empty($_SESSION['__ZF'])) {
            unset($_SESSION['__ZF']);
        }
    }


    /**
     * isStarted() - convenience method to determine if the session is already started.
     *
     * @return bool
     */
    public static function isStarted()
    {
        return self::$_sessionStarted;
    }


    /**
     * isRegenerated() - convenience method to determine if session_regenerate_id()
     * has been called during this request by Zend_Session.
     *
     * @return bool
     */
    public static function isRegenerated()
    {
        return ( (self::$_regenerateIdState > 0) ? true : false );
    }


    /**
     * getId() - get the current session id
     *
     * @return string
     */
    public static function getId()
    {
        return session_id();
    }


    /**
     * setId() - set an id to a user specified id
     *
     * @throws Zend_Session_Exception
     * @param string $id
     * @return void
     */
    public static function setId($id)
    {
        if (!self::$_unitTestEnabled && defined('SID')) {
            /** @see Zend_Session_Exception */
            require_once 'Zend/Session/Exception.php';
            throw new Zend_Session_Exception('The session has already been started.  The session id must be set first.');
        }

        if (!self::$_unitTestEnabled && headers_sent($filename, $linenum)) {
            /** @see Zend_Session_Exception */
            require_once 'Zend/Session/Exception.php';
            throw new Zend_Session_Exception("You must call ".__CLASS__.'::'.__FUNCTION__.
                "() before any output has been sent to the browser; output started in {$filename}/{$linenum}");
        }

        if (!is_string($id) || $id === '') {
            /** @see Zend_Session_Exception */
            require_once 'Zend/Session/Exception.php';
            throw new Zend_Session_Exception('You must provide a non-empty string as a session identifier.');
        }

        session_id($id);
    }


    /**
     * registerValidator() - register a validator that will attempt to validate this session for
     * every future request
     *
     * @param Zend_Session_Validator_Interface $validator
     * @return void
     */
    public static function registerValidator(Zend_Session_Validator_Interface $validator)
    {
        $validator->setup();
    }


    /**
     * stop() - Disable write access.  Optionally disable read (not implemented).
     *
     * @return void
     */
    public static function stop()
    {
        parent::$_writable = false;
    }


    /**
     * writeClose() - Shutdown the sesssion, close writing and detach $_SESSION from the back-end storage mechanism.
     * This will complete the internal data transformation on this request.
     *
     * @param bool $readonly - OPTIONAL remove write access (i.e. throw error if Zend_Session's attempt writes)
     * @return void
     */
    public static function writeClose($readonly = true)
    {
        if (self::$_unitTestEnabled) {
            return;
        }

        if (self::$_writeClosed) {
            return;
        }

        if ($readonly) {
            parent::$_writable = false;
        }

        session_write_close();
        self::$_writeClosed = true;
    }


    /**
     * destroy() - This is used to destroy session data, and optionally, the session cookie itself
     *
     * @param bool $remove_cookie - OPTIONAL remove session id cookie, defaults to true (remove cookie)
     * @param bool $readonly - OPTIONAL remove write access (i.e. throw error if Zend_Session's attempt writes)
     * @return void
     */
    public static function destroy($remove_cookie = true, $readonly = true)
    {
        if (self::$_unitTestEnabled) {
            return;
        }

        if (self::$_destroyed) {
            return;
        }

        if ($readonly) {
            parent::$_writable = false;
        }

        session_destroy();
        self::$_destroyed = true;

        if ($remove_cookie) {
            self::expireSessionCookie();
        }
    }


    /**
     * expireSessionCookie() - Sends an expired session id cookie, causing the client to delete the session cookie
     *
     * @return void
     */
    public static function expireSessionCookie()
    {
        if (self::$_unitTestEnabled) {
            return;
        }

        if (self::$_sessionCookieDeleted) {
            return;
        }

        self::$_sessionCookieDeleted = true;

        if (isset($_COOKIE[session_name()])) {
            $cookie_params = session_get_cookie_params();

            setcookie(
                session_name(),
                false,
                315554400, // strtotime('1980-01-01'),
                $cookie_params['path'],
                $cookie_params['domain'],
                $cookie_params['secure']
                );
        }
    }


    /**
     * _processValidator() - internal function that is called in the existence of VALID metadata
     *
     * @throws Zend_Session_Exception
     * @return void
     */
    private static function _processValidators()
    {
        foreach ($_SESSION['__ZF']['VALID'] as $validator_name => $valid_data) {
            if (!class_exists($validator_name)) {
                require_once 'Zend/Loader.php';
                Zend_Loader::loadClass($validator_name);
            }
            $validator = new $validator_name;
            if ($validator->validate() === false) {
                /** @see Zend_Session_Exception */
                require_once 'Zend/Session/Exception.php';
                throw new Zend_Session_Exception("This session is not valid according to {$validator_name}.");
            }
        }
    }


    /**
     * namespaceIsset() - check to see if a namespace is set
     *
     * @param string $namespace
     * @return bool
     */
    public static function namespaceIsset($namespace)
    {
        return parent::_namespaceIsset($namespace);
    }


    /**
     * namespaceUnset() - unset a namespace or a variable within a namespace
     *
     * @param string $namespace
     * @throws Zend_Session_Exception
     * @return void
     */
    public static function namespaceUnset($namespace)
    {
        parent::_namespaceUnset($namespace);
        Zend_Session_Namespace::resetSingleInstance($namespace);
    }


    /**
     * namespaceGet() - get all variables in a namespace
     * Deprecated: Use getIterator() in Zend_Session_Namespace.
     *
     * @param string $namespace
     * @return array
     */
    public static function namespaceGet($namespace)
    {
        return parent::_namespaceGetAll($namespace);
    }


    /**
     * getIterator() - return an iteratable object for use in foreach and the like,
     * this completes the IteratorAggregate interface
     *
     * @throws Zend_Session_Exception
     * @return ArrayObject
     */
    public static function getIterator()
    {
        if (parent::$_readable === false) {
            /** @see Zend_Session_Exception */
            require_once 'Zend/Session/Exception.php';
            throw new Zend_Session_Exception(parent::_THROW_NOT_READABLE_MSG);
        }

        $spaces  = array();
        if (isset($_SESSION)) {
            $spaces = array_keys($_SESSION);
            foreach($spaces as $key => $space) {
                if (!strncmp($space, '__', 2) || !is_array($_SESSION[$space])) {
                    unset($spaces[$key]);
                }
            }
        }

        return new ArrayObject(array_merge($spaces, array_keys(parent::$_expiringData)));
    }


    /**
     * isWritable() - returns a boolean indicating if namespaces can write (use setters)
     *
     * @return bool
     */
    public static function isWritable()
    {
        return parent::$_writable;
    }


    /**
     * isReadable() - returns a boolean indicating if namespaces can write (use setters)
     *
     * @return bool
     */
    public static function isReadable()
    {
        return parent::$_readable;
    }

}
Back to Top