<?php
namespace Moto\Website; use Moto; use Zend; class PasswordProtection { protected static $_initialized = false; protected static $_enabled = false; protected static $_password = null; protected static $_cryptMachine = null; protected static $_cookieLifetime = 0; protected static $_options = array( 'cryptCost' => 6, 'cookieName' => 'moto_page_auth', ); public static function init() { if (static::$_initialized) { return; } static::$_initialized = true; static::_initSettings(); } protected static function _initSettings() { $settings = Moto\Website\Settings::get('password_protection'); static::$_enabled = Moto\Util::getFrom($settings, 'enabled', static::$_enabled); $password = Moto\Util::getFrom($settings, 'password', null); $cookieLifetime = Moto\Util::getFrom($settings, 'cookie_lifetime', 0); if (is_string($password)) { $password = base64_decode($password); } if (is_string($password)) { static::$_password = $password; } if ($cookieLifetime > 0) { static::$_cookieLifetime = time() + $cookieLifetime; } } public static function getOption($name, $default = null) { return Moto\Util::getFrom(static::$_options, $name, $default); } protected static function setOption($name, $value) { if (!is_string($name)) { return false; } static::$_options[$name] = $value; return true; } public static function isEnabled() { return static::$_enabled; } public static function getPassword() { return static::$_password; } protected static function _getCryptMachine() { if (static::$_cryptMachine == null) { static::$_cryptMachine = new Zend\Crypt\Password\Bcrypt(); static::$_cryptMachine->setCost(static::getOption('cryptCost', 6)); } return static::$_cryptMachine; } public static function isVerifiedPasswordHash($password, $hash = null) { $crypt = static::_getCryptMachine(); if (!$crypt) { return false; } if ($hash === null) { $hash = static::getAccessPasswordHash(); } if (!$hash) { return false; } return $crypt->verify($password, $hash); } public static function createAccessHashByPassword($password) { $crypt = static::_getCryptMachine(); if (!$crypt) { return false; } $hash = $crypt->create($password); return $hash; } public static function sendAccessPasswordToken($password) { $hash = static::createAccessHashByPassword($password); if ($hash) { $hash = base64_encode($hash); Moto\System::sendCookie(static::getOption('cookieName'), $hash, array('expire' => static::$_cookieLifetime)); } } public static function getAccessPasswordHash() { $hash = Moto\Util::getFrom($_COOKIE, static::getOption('cookieName')); if (!$hash) { return false; } $hash = base64_decode($hash); return $hash; } public static function isVerifiedAccessPasswordPage($page, $password) { return ($password === $page->getContentPassword()); } } 