예제 #1
0
 function bootstrap()
 {
     //Set the application path.
     Nutshell::setAppPath('../private/application/');
     //Initiate the MVC.
     Nutshell::getInstance()->plugin->Mvc();
 }
예제 #2
0
 protected function parseConfig(Config $config)
 {
     parent::parseConfig($config);
     $this->parseConfigOption($config, 'connector');
     $this->parseConfigOption($config, 'table');
     if (!preg_match('/^[a-zA-Z_][a-zA-Z0-9_]*$/', $this->table)) {
         throw new LoggerException(sprintf("Invalid table name for DbWriter: %s", $this->table));
     }
     $this->activeConnector = Nutshell::getInstance()->plugin->Db->{$this->connector};
 }
예제 #3
0
 public static function registerBehaviours()
 {
     static::registerBehaviour(get_called_class(), 'NamedSession', function ($classInstance) {
         $session = Nutshell::getInstance()->plugin->Session;
         if (!isset($session->{ObjectHelper::getBaseClassName($classInstance)})) {
             $session->{ObjectHelper::getBaseClassName($classInstance)} = new stdClass();
         }
         $classInstance->session = $session->{ObjectHelper::getBaseClassName($classInstance)};
     });
 }
예제 #4
0
 public function __construct()
 {
     $this->nutshell = Nutshell::getInstance();
     if (isset($this->nutshell)) {
         $this->plugin = $this->nutshell->plugin;
         if ($connection = $this->nutshell->config->plugin->Mvc->connection) {
             //Make a shortcut reference to the
             $this->db = $this->plugin->Db->{$connection};
         }
     }
     parent::__construct();
 }
예제 #5
0
 /**
  * This object overloader is responsible for providing
  * shortcuts to commonly accessed objects within the
  * framework.
  * 
  * @param String $key - The shortcut.
  * @deprecated
  */
 public function __get($key)
 {
     switch ($key) {
         case 'config':
             return Nutshell::getInstance()->config;
         case 'core':
             return Nutshell::getInstance();
         case 'plugin':
             return Nutshell::getInstance()->plugin;
         case 'request':
             return Nutshell::getInstance()->request;
     }
 }
 public function __construct()
 {
     $config = Nutshell::getInstance()->config;
     $this->outputDirectory = $config->plugin->Plupload->thumbnail_dir;
     $this->thumbnails = $config->plugin->Plupload->thumbnails;
     // If 'thumbnails' is not an array of configurations, just use the thumbnail_whatever properties
     if (!is_array($this->thumbnails)) {
         $thumbnail = new \stdClass();
         $thumbnail->width = $config->plugin->Plupload->thumbnail_width;
         $thumbnail->height = $config->plugin->Plupload->thumbnail_height;
         $thumbnail->constraint = $config->plugin->Plupload->thumbnail_constraint;
         $this->thumbnails = array($thumbnail);
     }
 }
예제 #7
0
 public static function runFactory($engine, $args = null)
 {
     self::loadDependencies();
     $engine = strtolower($engine);
     $engines = self::getAvailableFormats();
     if (isset($engines[$engine])) {
         $className = __NAMESPACE__ . '\\' . $engines[$engine];
         return new $className($args);
     } else {
         $error_msg = "Engine {$engine} isn't supported.";
         Nutshell::getInstance()->plugin->Logger->fatal($error_msg);
         // just to be sure that the error message will be in the log.
         throw new FormatParserException(FormatParserException::ENGINE_NOT_SUPPORTED, $error_msg);
     }
 }
예제 #8
0
 public function __construct(Responder $responder, $request = null)
 {
     $this->core = Nutshell::getInstance();
     $this->plugin = $this->core->plugin;
     $this->responder = $responder;
     if (!is_null($request)) {
         $this->response['tid'] = $request->tid;
         $this->response['type'] = $request->type;
         $this->response['action'] = $request->action;
         $this->response['method'] = $request->method;
     } else {
         $this->response['type'] = 'polling';
     }
     $this->response['timestamp'] = time();
     //Link the response result to result.
     $this->response['result'] =& $this->result;
 }
예제 #9
0
 /**
  * (non-PHPdoc)
  * @see nutshell\plugin\session.Handler::parseConfig()
  */
 protected function parseConfig()
 {
     parent::parseConfig();
     if (!is_null($this->config->connector)) {
         try {
             $this->activeConnector = Nutshell::getInstance()->plugin->Db->{$this->config->connector};
         } catch (\Exception $e) {
             throw new SessionException(sprintf("Could not instantiate %s database connector for session handler: %s", $this->config->connector, $e->getMessage()), 0, $e);
         }
     } else {
         throw new SessionException(sprintf("Could not find a database connector definition in the config."));
     }
     if (!is_null($this->config->table)) {
         if (preg_match('/^[a-zA-Z_][a-zA-Z0-9_]*$/', $this->config->table)) {
             $this->table = $this->config->table;
         } else {
             throw new SessionException(sprintf("Invalid table definition name in the database session handler config: %s", $this->config->table));
         }
     } else {
         throw new SessionException(sprintf("Could not find a table definition in the database session handler config."));
     }
 }
예제 #10
0
 public function getVideoDuration($filename, $seconds = true)
 {
     $ffmpeg_dir = Nutshell::getInstance()->config->plugin->Plupload->ffmpeg_dir;
     if (!$ffmpeg_dir) {
         return;
     }
     ob_start();
     $command = "\"{$ffmpeg_dir}ffmpeg\" -i \"{$filename}\" 2>&1";
     \application\helper\DebugHelper::traceToFileShort('output.log', $command);
     passthru($command);
     $result = ob_get_contents();
     ob_end_clean();
     preg_match('/Duration: (.*?),/', $result, $matches);
     if (sizeof($matches) < 2) {
         throw new PluploadException("Failed to get video duration of {$filename}", $command, $result, $matches);
     }
     $duration = $matches[1];
     if ($seconds) {
         $duration_array = explode(':', $duration);
         $duration = $duration_array[0] * 3600 + $duration_array[1] * 60 + $duration_array[2];
     }
     return $duration;
 }
예제 #11
0
 protected static function forceRebuild()
 {
     return Nutshell::getInstance()->request->get(self::CONFIG_REBUILD_KEY);
 }
예제 #12
0
 /**
  * Removes the key from the cache.
  * @param string $key
  * @param string $subFolder
  */
 public function free($cacheKey, $subFolder = '')
 {
     $keyMD5 = md5($cacheKey);
     if (strlen($subFolder) > 0) {
         $subFolder = $subFolder . _DS_;
     }
     $fileName = $this->cacheFolder . $subFolder . self::CS_FILENAME . $keyMD5;
     try {
         if (file_exists($fileName)) {
             unlink($fileName);
         }
     } catch (\Exception $e) {
         Nutshell::getInstance()->plugin->Logger->fatal('Error while removing cache file: $fileName.');
         // nothing can be done when a cache free fails.
         // no exception should be provoked
     }
 }
예제 #13
0
 public static function executeSQLDump($file)
 {
     $config = Nutshell::getInstance()->config;
     $dbConfig = $config->plugin->Db->connections->{$config->plugin->Mvc->connection};
     $passwordSegment = $dbConfig->password == '' ? '' : '-p' . $dbConfig->password;
     $command = sprintf("mysql -u %s %s %s < \"%s\"", $dbConfig->username, $passwordSegment, $dbConfig->database, $file);
     exec($command, $output, $return);
     if ($return !== 0) {
         throw new NutshellException('Executing command failed', "command:", $command, "output:", $output, "return:", $return);
     }
 }
예제 #14
0
 public function getApi()
 {
     $config = Nutshell::getInstance()->config;
     $api = $config->plugin->Btl->toArray();
     return $api;
 }
예제 #15
0
 public static function autoload($className)
 {
     $namespace = ObjectHelper::getNamespace($className);
     $className = ObjectHelper::getBaseClassName($className);
     //Check for an application plugin's library class.
     // if (strstr($namespace,'plugin\\'))
     // {
     // 	$namespaceParts	=explode('\\',$namespace);
     // 	$where			=array_shift($namespaceParts);
     // 	$filePath		=false;
     // 	if ($where==='nutshell')
     // 	{
     // 		$filePath=NS_HOME.implode(_DS_,$namespaceParts)._DS_.$className.'.php';
     // 	}
     // 	else if ($where==='application')
     // 	{
     // 		$filePath=APP_HOME.implode(_DS_,$namespaceParts)._DS_.$className.'.php';
     // 	}
     // 	if (is_file($filePath))
     // 	{
     // 		//Invoke the plugin.
     // 		require_once($filePath);
     // 	}
     // 	else
     // 	{
     // 		throw new ('Unable to autoload class "'.$namespace.'\\'.$className.'".');
     // 	}
     // }
     // //Check for a plugin behaviour.
     // else
     if (strstr($namespace, 'behaviour\\')) {
         list(, , $plugin) = explode('\\', $namespace);
         $pathSuffix = 'plugin' . _DS_ . $plugin . _DS_ . 'behaviour' . _DS_ . $className . '.php';
         if (is_file($file = NS_HOME . $pathSuffix)) {
             //Invoke the plugin.
             Nutshell::getInstance()->plugin->{ucfirst($plugin)};
         } else {
             if (is_file($file = APP_HOME . $pathSuffix)) {
                 Nutshell::getInstance()->plugin->{ucfirst($plugin)};
             } else {
                 throw new LoaderException(LoaderException::CANNOT_AUTOLOAD_CLASS, 'Unable to autoload class "' . $namespace . $className . '".');
             }
         }
     } else {
         $namespaceParts = explode('\\', $namespace);
         $where = array_shift($namespaceParts);
         $filePath = false;
         if ($where === 'nutshell') {
             $filePath = NS_HOME . implode(_DS_, $namespaceParts) . _DS_ . $className . '.php';
         } else {
             if ($where === 'application') {
                 $filePath = APP_HOME . implode(_DS_, $namespaceParts) . _DS_ . $className . '.php';
             }
         }
         if (is_file($filePath)) {
             //Invoke the plugin.
             require $filePath;
         } else {
             throw new LoaderException(LoaderException::CANNOT_AUTOLOAD_CLASS, 'Unable to autoload class "' . $namespace . '\\' . $className . '"', '"' . $filePath . '" does not exist');
         }
     }
 }
예제 #16
0
 /**
  * A magic method for fetching an instance of this plugin's config block.
  * 
  * @access public
  * @static
  * @return nutshell\core\config\Config
  */
 public static function config()
 {
     return Nutshell::getInstance()->config->plugin->{ObjectHelper::getBaseClassName(get_called_class())};
 }
예제 #17
0
 private function checkLockout($user, $success, $model)
 {
     $config = Nutshell::getInstance()->config->plugin->Auth;
     $loginAttemptsColumn = $config->loginAttemptsColumn;
     $lockTimeColumn = $config->lockTimeColumn;
     $maxLoginAttempts = $config->maxLoginAttempts;
     $lockTimeoutPeriod = $config->lockTimeoutPeriod;
     $now = time();
     // determine whetehr we are already locked out
     $loginAttempts = $user[$loginAttemptsColumn];
     $lockTime = $user[$lockTimeColumn];
     $lockedOut = false;
     if ($lockTime != 0) {
         $lockedOut = $loginAttempts > $maxLoginAttempts && $now < $lockTime + $lockTimeoutPeriod;
     }
     // establish what to do
     if ($success) {
         // login succeeded
         if ($lockedOut) {
             // but we are locked out
             $success = false;
             $this->debug = array('message' => self::ERROR_LOCKED_USER, 'exception_message' => self::EXCEPTION_LOCKED_USER, 'login_attempts' => $loginAttempts, 'lock_time' => $lockTime);
         } else {
             // if needed reset the login_attempt counter and lock time
             $lockTime = 0;
             $loginAttempts = 0;
         }
     } else {
         // login failed
         $loginAttempts++;
         if ($lockedOut) {
             // we are already locked out
             $this->debug = array('message' => self::ERROR_LOCKED_USER, 'exception_message' => self::EXCEPTION_LOCKED_USER, 'login_attempts' => $loginAttempts, 'lock_time' => $lockTime);
         } else {
             // we're not locked out, check if we should be
             if ($loginAttempts == $maxLoginAttempts) {
                 $lockTime = $now;
                 $this->debug = array('message' => self::ERROR_LOCKED_USER, 'exception_message' => self::EXCEPTION_LOCKED_USER, 'login_attempts' => $loginAttempts, 'lock_time' => $lockTime);
             }
         }
     }
     // update db to reflect attempts and lock time
     $model->update(array($loginAttemptsColumn => $loginAttempts, $lockTimeColumn => $lockTime), array('email' => $user['email']));
     return $success;
 }
예제 #18
0
 /**
  * The main internal method for executing the different types of statements.
  * 
  * @access private
  * @param $type - The type of statement to execute.
  * @param $args - Any arguments to pass to the statement (these are used as bound parameters). 
  * @return PDOStatement
  */
 public function executeStatement($type = 'query', $args = array(), $usePrepared = true)
 {
     $this->resetLastQueryParams();
     $return = false;
     if (!empty($args[0])) {
         if ($args[0] != $this->lastQuery['sql'] || !$usePrepared) {
             $this->lastQuery['sql'] = $args[0];
             $config = array();
             if (extension_loaded('pdo_mysql')) {
                 $config['PDO::MYSQL_ATTR_USE_BUFFERED_QUERY'] = true;
             }
             $this->lastQuery['statement'] = $this->connection->prepare($args[0], $config);
         }
     } else {
         if (empty($args[0]) && empty($this->lastQuery['sql'])) {
             throw new DbException('Unable to execute statement. Query was empty!');
         }
     }
     if (isset($args[1])) {
         if (!is_array($args[1])) {
             $this->lastQuery['params'] =& $args;
             for ($i = 1, $j = count($args); $i < $j; $i++) {
                 $this->lastQuery['statement']->bindParam($i, $args[$i]);
             }
         } else {
             $i = 1;
             $this->lastQuery['params'] =& $args[1];
             foreach ($args[1] as &$val) {
                 if (!is_object($this->lastQuery['statement'])) {
                     throw new DbException(DbException::INVALID_STATEMENT, $this->lastQuery);
                 }
                 if (is_object($val)) {
                     throw new DbException(DbException::INVALID_STATEMENT, "Cannot bind-param with an object", $val);
                 }
                 $this->lastQuery['statement']->bindParam($i, $val);
                 $i++;
             }
         }
     }
     // Execute the query
     if ($this->lastQuery['statement'] && $this->lastQuery['statement']->execute()) {
         $this->lastQuery['resultSet'] = $this->lastQuery['statement']->fetchAll();
         $this->lastQuery['numResults'] = count($this->lastQuery['resultSet']);
         $this->lastQuery['affectedRows'] = 0;
         switch ($type) {
             case 'query':
                 $this->lastQuery['affectedRows'] = $this->lastQuery['statement']->rowCount();
                 if (stristr($this->lastQuery['sql'], 'SELECT')) {
                     $return = $this->lastQuery['numResults'];
                 } else {
                     $return = $this->lastQuery['affectedRows'];
                 }
                 break;
             case 'select':
                 $return = $this->lastQuery['numResults'];
                 break;
             case 'insert':
                 $this->lastQuery['affectedRows'] = $this->lastQuery['statement']->rowCount();
                 $this->lastQuery['insertId'] = $this->connection->lastInsertId();
                 if ($this->lastQuery['insertId'] !== '0') {
                     $return = $this->lastQuery['insertId'];
                 } else {
                     $return = true;
                 }
                 break;
             case 'update':
                 $this->lastQuery['affectedRows'] = $this->lastQuery['statement']->rowCount();
                 $return = $this->lastQuery['affectedRows'];
                 break;
             case 'delete':
                 $this->lastQuery['affectedRows'] = $this->lastQuery['statement']->rowCount();
                 $return = $this->lastQuery['affectedRows'];
                 break;
         }
     }
     @(list(, , $this->lastQuery['lastError']) = $this->lastQuery['statement'] ? $this->lastQuery['statement']->errorInfo() : $this->connection->errorInfo());
     // throws an exception if there is a problem running the query and throwExceptionOnError
     if ($this->throwExceptionOnError && $this->lastQuery['lastError']) {
         $error_message = $this->lastQuery['lastError'];
         try {
             $faulty_sql = $this->lastQuery['statement'] ? $this->lastQuery['statement']->queryString : $this->lastQuery['sql'];
             if (strlen($faulty_sql) > 0) {
                 Nutshell::getInstance()->plugin->Logger('nutshell.plugin.db')->error($error_message . ":" . $faulty_sql);
             }
         } catch (\Exception $e) {
             // nothing can be done if the error treatment fails.
         }
         throw new DbException($error_message, $this->lastQuery);
     }
     return $return;
 }
예제 #19
0
 /**
  * This method is called when an exception happens.
  * @param Exception $exception
  */
 public static function treatException($exception, $format = 'html')
 {
     if (!self::$blockRecursion) {
         self::$blockRecursion = true;
         // Create the message
         if ($exception instanceof ConfigException) {
             header('HTTP/1.1 500 Config Exception');
             die('ERROR: ' . $exception->getCode() . ' ' . $exception->debug[0]);
         } elseif ($exception->code == E_STRICT) {
             // The logger fails to load in the case of a "<function name>  should be compatible with that of <parent function name>" error
             // Not dying here, 'cause these can be logged. Will roll through again and cause a recursive error error.
             $message = 'ERROR: ' . $exception->getCode() . ' ' . $exception->debug[0];
         } elseif ($exception instanceof LoggerException) {
             header('HTTP/1.1 500 Logger Exception');
             die('ERROR: ' . $exception->getCode() . ' ' . $exception->debug[0]);
         } elseif ($exception instanceof NutshellException) {
             $message = $exception->getDescription($format);
         } else {
             $message = "NON NUTSHELL EXCEPTION! ";
             $message .= $exception->getTraceAsString();
             $message .= nl2br($exception);
         }
         // Log the message
         self::logMessage($message);
         // Echo the message
         if (Nutshell::getInstance()->config->application->mode == 'development') {
             header('HTTP/1.1 500 Application Error');
             echo $message;
         }
     } else {
         // Echo the message
         header('HTTP/1.1 500 Recursive Error Error');
         $message = 'ERROR: ' . $exception->getCode() . ' ' . $exception->debug[0];
         die($message);
     }
 }
예제 #20
0
 public function __construct()
 {
     parent::__construct();
     $this->config = Nutshell::getInstance()->config->plugin->{ObjectHelper::getBaseClassName($this->getParentPlugin())};
 }
예제 #21
0
 /**
  * Returns the nutshell instance.
  * 
  * @static
  * @access public
  * @return void
  */
 public static function getInstance()
 {
     if (!isset($GLOBALS['NUTSHELL'])) {
         return Nutshell::init();
     }
     return $GLOBALS['NUTSHELL'];
 }