Overview

Namespaces

  • Simpletools
    • Autoload
    • Config
    • Db
      • Mysql
    • Event
    • Http
    • Mvc
    • Page
    • Store

Classes

  • Simpletools\Autoload\Loader
  • Simpletools\Config\Ini
  • Simpletools\Db\Mysql\Client
  • Simpletools\Db\Mysql\Iterator
  • Simpletools\Db\Mysql\Model
  • Simpletools\Db\Mysql\QueryBuilder
  • Simpletools\Db\Mysql\Result
  • Simpletools\Db\Mysql\Sql
  • Simpletools\Event\Event
  • Simpletools\Http\Ssl
  • Simpletools\Mvc\Common
  • Simpletools\Mvc\Controller
  • Simpletools\Mvc\Model
  • Simpletools\Mvc\Router
  • Simpletools\Mvc\RoutingHook
  • Simpletools\Mvc\View
  • Simpletools\Page\Layout
  • Simpletools\Store\Cookie
  • Simpletools\Store\Flash
  • Simpletools\Store\Session
  • Overview
  • Namespace
  • Class
  1: <?php
  2: /*
  3:  * Simpletools Framework.
  4:  * Copyright (c) 2009, Marcin Rosinski. (http://www.getsimpletools.com/)
  5:  * All rights reserved.
  6:  *
  7:  * LICENCE
  8:  *
  9:  * Redistribution and use in source and binary forms, with or without modification,
 10:  * are permitted provided that the following conditions are met:
 11:  *
 12:  * -    Redistributions of source code must retain the above copyright notice,
 13:  *      this list of conditions and the following disclaimer.
 14:  *
 15:  * -    Redistributions in binary form must reproduce the above copyright notice,
 16:  *      this list of conditions and the following disclaimer in the documentation and/or other
 17:  *      materials provided with the distribution.
 18:  *
 19:  * -    Neither the name of the Simpletools nor the names of its contributors may be used to
 20:  *      endorse or promote products derived from this software without specific prior written permission.
 21:  *
 22:  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
 23:  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
 24:  * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 25:  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 26:  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 27:  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
 28:  * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
 29:  * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 30:  *
 31:  * @framework       Simpletools
 32:  * @packages        Session
 33:  * @description     Session & Cookies Handler
 34:  * @copyright       Copyright (c) 2011 Marcin Rosinski. (http://www.getsimpletools.com/)
 35:  * @license         BSD
 36:  *
 37:  */
 38: 
 39:     namespace Simpletools\Store;
 40: 
 41:     class Cookie
 42:     {
 43:         private static $settings = array(
 44:             'expire'                            => 2592000,
 45:             'path'                              => '/',
 46:             'secure'                            => false,
 47:             'httpOnly'                          => false,
 48:             'jsonDecodeArray'                   => true,
 49:             'defaultReturn'                     => "ST__EXCEPTION",
 50: 
 51:             'encryptionPhrase'                  => "",
 52:             'encryptionSalt'                    => "sh%3tf$12Df&yuXgF£gf"
 53:         );
 54: 
 55:         public static function is($key)
 56:         {
 57:             return isset($_COOKIE[$key]);
 58:         }
 59: 
 60:         protected static function _getRaw($key)
 61:         {
 62:             $value  = isset($_COOKIE[$key]) ? $_COOKIE[$key] : null;
 63:             $prefix = substr($value,0,7);
 64: 
 65:             if($prefix=="_st_/p.")
 66:             {
 67:                 return array('st'=>json_decode(substr($value,7),self::$settings['jsonDecodeArray']),'raw'=>$value);
 68:             }
 69:             elseif($prefix=="_st_/e.")
 70:             {
 71:                 if(!($decryptedValue = self::_decrypt(substr($value,7))))
 72:                 {
 73:                     if(self::$settings['defaultReturn']=="ST__EXCEPTION")
 74:                     {
 75:                         throw new \Exception("Cookie with key: ".$key." can't be decrypted",500);
 76:                     }
 77:                     else
 78:                     {
 79:                         return array('raw'=>self::$settings['defaultReturn']);
 80:                     }
 81:                 }
 82:                 else
 83:                 {
 84:                     return array('st'=>json_decode($decryptedValue,self::$settings['jsonDecodeArray']),'raw'=>$value);
 85:                 }
 86:             }
 87:             else
 88:             {
 89:                 return array('raw'=>$value);
 90:             }
 91:         }
 92: 
 93:         public static function getMeta($key)
 94:         {
 95:             if(!isset($_COOKIE[$key]) && self::$settings['defaultReturn']=="ST__EXCEPTION")
 96:             {
 97:                 throw new \Exception("Cookie with key: ".$key." doesn't exist",404);
 98:             }
 99: 
100:             $value  = self::_getRaw($key);
101:             if(!isset($value['st']) OR !isset($value['st']['e']))
102:             {
103:                 return null;
104:             }
105: 
106:             $meta                       = array();
107:             $meta['dateSetOn']          = date(DATE_COOKIE,$value['st']['s']);
108:             $meta['dateExpireOn']       = date(DATE_COOKIE,$value['st']['e']);
109:             $meta['secondSetOn']        = $value['st']['s'];
110:             $meta['secondExpireOn']     = $value['st']['e'];
111:             $meta['secondDuration']     = $value['st']['e'] - $value['st']['s'];
112: 
113:             return $meta;
114:         }
115: 
116:         public static function get($key)
117:         {
118:             if(!isset($_COOKIE[$key]) && self::$settings['defaultReturn']=="ST__EXCEPTION")
119:             {
120:                 throw new \Exception("Cookie with key: ".$key." doesn't exist",404);
121:             }
122: 
123:             $value = self::_getRaw($key);
124: 
125:             return isset($value['st']['v']) ? $value['st']['v'] : $value['raw'];
126:         }
127: 
128:         public static function set($key,$value,$etc=array())
129:         {
130:             $expire = 0;
131: 
132:             if(isset($etc['expire']) && is_string($etc['expire']))
133:             {
134:                 $expire = strtotime($etc['expire']);
135:             }
136:             elseif(isset($etc['expire']) && $etc['expire'])
137:             {
138:                 $expire = $etc['expire'];
139:             }
140: 
141:             $expire = (!$expire) ? self::$settings['expire'] : $expire;
142: 
143:             if(!self::$settings['encryptionPhrase'])
144:             {
145:                 $data = '_st_/p.'.json_encode(array('v'=>$value,'e'=>$expire,'s'=>time()));
146:             }
147:             else
148:             {
149:                 $value  = self::_encrypt(json_encode(array('v'=>$value,'e'=>$expire,'s'=>time())));
150:                 $data   = '_st_/e.'.$value;
151:             }
152: 
153:             return setcookie(
154:                 $key,
155:                 $data,
156:                 $expire,
157:                 isset($etc['path']) ? $etc['path'] : self::$settings['path'],
158:                 isset($etc['domain']) ? $etc['domain'] : self::$settings['domain'],
159:                 isset($etc['secure']) ? $etc['secure'] : self::$settings['secure'],
160:                 isset($etc['httpOnly']) ? $etc['httpOnly'] : self::$settings['httpOnly']
161:             );
162:         }
163: 
164:         public static function remove($key)
165:         {
166:             if(is_array($key))
167:             {
168:                 foreach($key as $k)
169:                 {
170:                     self::set($k,null,array(
171:                         'expire' => "NOW - 1 YEAR"
172:                     ));
173:                 }
174:             }
175:             else
176:             {
177:                 self::set($key,null,array(
178:                     'expire' => "NOW - 1 YEAR"
179:                 ));
180:             }
181:         }
182: 
183:         public static function settings(array $options)
184:         {
185:             $SERVER_NAME = isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : 'localhost';
186: 
187:             if(isset($options['expire']) && !is_integer($options['expire']))
188:             {
189:                 $options['expire'] = strtotime($options['expire']);
190:             }
191: 
192:             self::$settings['expire']                   = isset($options['expire']) ? $options['expire'] : time()+2592000;
193:             self::$settings['path']                     = isset($options['path']) ? $options['path'] : '/';
194:             self::$settings['domain']                   = isset($options['domain']) ? $options['domain'] : $SERVER_NAME;
195:             self::$settings['secure']                   = isset($options['secure']) ? (boolean) $options['secure'] : false;
196:             self::$settings['httpOnly']                 = isset($options['httpOnly']) ? (boolean) $options['httpOnly'] : false;
197:             self::$settings['jsonDecodeArray']          = isset($options['jsonDecodeArray']) ? (boolean) $options['jsonDecodeArray'] : true;
198:             self::$settings['defaultReturn']            = (array_key_exists('defaultReturn',$options)) ? $options['defaultReturn'] : 'ST__EXCEPTION';
199: 
200:             self::$settings['encryptionPhrase']         = isset($options['encryptionPhrase']) ? hash('SHA256', $options['encryptionPhrase'].(isset($options['encryptionSalt']) ? $options['encryptionSalt'] : self::$settings['encryptionSalt']), true) : false;
201:         }
202: 
203:         protected static function _encrypt($string)
204:         {
205:             $key    = self::$settings['encryptionPhrase'];
206: 
207:             // Build $iv and $iv_base64.  We use a block size of 128 bits (AES compliant) and CBC mode.  (Note: ECB mode is inadequate as IV is not used.)
208:             srand(); $iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC), MCRYPT_RAND);
209:             if (strlen($iv_base64 = rtrim(base64_encode($iv), '=')) != 22) return false;
210:             // Encrypt $decrypted and an MD5 of $decrypted using $key.  MD5 is fine to use here because it's just to verify successful decryption.
211:             $encrypted = base64_encode(@mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $string . md5($string), MCRYPT_MODE_CBC, $iv));
212:             // We're done!
213:             return $iv_base64 . $encrypted;
214:         }
215: 
216:         protected static function _decrypt($encrypted)
217:         {
218:             $key    = self::$settings['encryptionPhrase'];
219: 
220:             // Retrieve $iv which is the first 22 characters plus ==, base64_decoded.
221:             $iv = base64_decode(substr($encrypted, 0, 22) . '==');
222:             // Remove $iv from $encrypted.
223:             $encrypted = substr($encrypted, 22);
224:             // Decrypt the data.  rtrim won't corrupt the data because the last 32 characters are the md5 hash; thus any \0 character has to be padding.
225:             $decrypted = rtrim(@mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, base64_decode($encrypted), MCRYPT_MODE_CBC, $iv), "\0\4");
226:             // Retrieve $hash which is the last 32 characters of $decrypted.
227:             $hash = substr($decrypted, -32);
228:             // Remove the last 32 characters from $decrypted.
229:             $decrypted = substr($decrypted, 0, -32);
230:             // Integrity check.  If this fails, either the data is corrupted, or the password/salt was incorrect.
231:             if (md5($decrypted) != $hash) return false;
232:             // Yay!
233:             return $decrypted;
234:         }
235:     }
236: 
237: ?>
API documentation generated by ApiGen