/** * Sets the id * @param int|Object $arg0 */ function setId($arg0) { if ($this->getIdType() == self::ID_TYPE_MONGO) { if (is_string($arg0) && \MongoId::isValid($arg0)) { parent::setId(new \MongoId($arg0)); } else { if ($arg0 instanceof \MongoId) { parent::setId($arg0); } else { if (is_null($arg0)) { parent::setId($arg0); } else { if (is_string($arg0) && trim($arg0) == '') { parent::setId(null); } else { if (is_int($arg0) && $arg0 == 0) { parent::setId(null); } else { try { throw new \Exception('Invalid ID set: ' . var_export($arg0, true)); } catch (\Exception $e) { \Mojavi\Logging\LoggerManager::error(__METHOD__ . " :: " . $e->getTraceAsString()); } parent::setId(null); } } } } } } else { if ($this->getIdType() == self::ID_TYPE_STRING) { if (is_string($arg0)) { parent::setId($arg0); } else { if ($arg0 instanceof \MongoId) { parent::setId((string) $arg0); } else { if (is_null($arg0)) { parent::setId($arg0); } else { if (is_string($arg0) && trim($arg0) == '') { parent::setId(null); } else { if (is_int($arg0) && $arg0 == 0) { parent::setId(null); } else { try { throw new \Exception('Invalid ID set: ' . var_export($arg0, true)); } catch (\Exception $e) { \Mojavi\Logging\LoggerManager::error(__METHOD__ . " :: " . $e->getTraceAsString()); } parent::setId(null); } } } } } } } }
/** * Execute this filter. * * @param FilterChain The filter chain. * * @return void * * @throws <b>FilterException</b> If an erro occurs during execution. */ public function execute($filterChain) { static $loaded; if (!isset($loaded)) { // load the filter $start_time = microtime(true); $need_to_rebuild = true; $loaded = true; $css_file = $this->getParameter('css_file', null); $less_file = $this->getParameter('less_file', null); if (!is_null($css_file) && !is_null($less_file)) { if (file_exists($less_file)) { if (file_exists($css_file)) { if (filemtime($css_file) >= filemtime($less_file)) { // css file is newer, so skip to the next filter $filterChain->execute(); $need_to_rebuild = false; } } if ($need_to_rebuild) { if (file_exists(MO_WEBAPP_DIR . "/vendor/oyejorge/less.php/lib/Less/Autoloader.php")) { \Mojavi\Logging\LoggerManager::error(__METHOD__ . " :: " . sprintf("Building new CSS file because date is %s and less file date is %s", filemtime($css_file), filemtime($less_file))); try { require_once MO_WEBAPP_DIR . "/vendor/oyejorge/less.php/lib/Less/Autoloader.php"; \Less_Autoloader::register(); $parser = new \Less_Parser(array('compress' => true)); $parser->parseFile($less_file, '/'); $css = $parser->getCss(); file_put_contents($css_file, $css); \Mojavi\Logging\LoggerManager::error(__METHOD__ . " :: " . sprintf("Generated less file in %ss", number_format(microtime(true) - $start_time, 4))); } catch (\Exception $e) { \Mojavi\Logging\LoggerManager::error(__METHOD__ . " :: " . $e->getMessage()); } // completed the caching, move on to the next filter $filterChain->execute(); } else { // we already loaded this filter, skip to the next filter \Mojavi\Logging\LoggerManager::error(__METHOD__ . " :: " . "Missing Less vendor library, use composer require oyejorge/less.php"); $filterChain->execute(); } } } else { // less file doesn't exist so skip to the next filter \Mojavi\Logging\LoggerManager::error(__METHOD__ . " :: " . "Cannot find less file to compile: " . $less_file); $filterChain->execute(); } } else { // less file or css file is not defined, so skip to the next filter \Mojavi\Logging\LoggerManager::error(__METHOD__ . " :: " . "less_file or css_file parameter is not defined"); $filterChain->execute(); } } else { // we already loaded this filter, skip to the next filter $filterChain->execute(); } }
/** * Clears the cache for this instance, if it exists * @return boolean */ function clearCache() { if (defined('MO_USE_APC') && MO_USE_APC == '1') { if (function_exists("apc_exists")) { if (apc_exists(get_class($this) . "_" . $this->getId()) && $this->getId() > 0) { // Clear out the cache apc_delete(get_class($this) . "_" . $this->getId()); } } else { LoggerManager::error(__METHOD__ . " :: " . "APC functions are not installed!"); } } return true; }
/** * Execute an SQL Statement and return result to be handled by calling function. * * @param mixed PreparedStatement or KeyBasedPreparedStatement * @param string Name of connection to be used * @param resource $connection Connection resource handler * @return mixed Resource if query executed successfully, otherwise false */ public function executeInsert(PreparedStatement $ps, $name = 'default', &$con = NULL, $debug = self::DEBUG) { $retval = false; try { // Connect to database if (is_null($con)) { if (self::DEBUG) { LoggerManager::error(__METHOD__ . ":: Retrieving New DB Connection for '" . $name . "'..."); } $con = $this->getDatabaseConnection($name); } // Get the prepared query /* @var $sth PDOStatement */ $sth = $ps->getPreparedStatement($con); if ($debug) { LoggerManager::error(__METHOD__ . " :: " . $sth); } // Execute the query $sth->execute(); return $con->lastInsertId(); } catch (MojaviException $e) { LoggerManager::fatal($e->printStackTrace('')); throw $e; } catch (PDOException $e) { ob_start(); $sth->debugDumpParams(); $stmt = ob_get_clean(); $e = new MojaviException($e->getMessage()); LoggerManager::fatal($sth->queryString); LoggerManager::fatal($stmt); LoggerManager::fatal($e->printStackTrace('')); throw $e; } catch (Exception $e) { $e = new MojaviException($e->getMessage()); LoggerManager::fatal($e->printStackTrace('')); throw $e; } }
/** * Execute this configuration handler. * * @param string An absolute filesystem path to a configuration file. * * @return string Data to be written to a cache file. * * @throws <b>ConfigurationException</b> If a requested configuration file * does not exist or is not readable. * @throws <b>ParseException</b> If a requested configuration file is * improperly formatted. */ public function &execute($config) { // available list of factories $factories = array('request', 'storage', 'user', 'security_filter'); // set our required categories list and initialize our handler $categories = array('required_categories' => $factories); $this->initialize($categories); // parse the ini $ini = $this->parseIni($config); // init our data and includes arrays $includes = array(); $inits = array(); $instances = array(); // let's do our fancy work foreach ($factories as $factory) { // see if the factory exists if (!isset($ini[$factory])) { // factory hasn't been registered $error = 'Configuration file "%s" must register "%s" factory'; $error = sprintf($config, $factory); throw new ParseException($error); } // get factory keys $keys = $ini[$factory]; if (!isset($keys['class'])) { // missing class key $error = 'Configuration file "%s" specifies category ' . '"%s" with missing class key'; $error = sprintf($error, $config, $factory); throw new ParseException($error); } $class = $keys['class']; if (isset($keys['file'])) { // we have a file to include $file =& $keys['file']; $file = $this->replaceConstants($file); $file = $this->replacePath($file); if (!is_readable($file)) { // factory file doesn't exist $error = 'Configuration file "%s" specifies class ' . '"%s" with nonexistent or unreadablefile ' . '"%s"'; $error = sprintf($error, $config, $class, $file); throw new ParseException($error); } // append our data $tmp = "require_once('%s');"; $includes[] = sprintf($tmp, $file); } // parse parameters $parameters = ParameterParser::parse($keys); // append new data switch ($factory) { case 'request': // append instance creation $tmp = "\$this->request = " . "\\Mojavi\\Request\\Request::newInstance('%s');"; $instances[] = sprintf($tmp, $class); // append instance initialization $tmp = "\$this->request->initialize(\$this->context, " . "%s);"; $inits[] = sprintf($tmp, $parameters); break; case 'security_filter': // append creation/initialization in one swipe $tmp = "\nif (MO_USE_SECURITY)\n{\n" . "\t\$this->securityFilter = " . "\\Mojavi\\Filter\\SecurityFilter::newInstance('%s');\n" . "\t\$this->securityFilter->initialize(" . "\$this->context, %s);\n}\n"; $inits[] = sprintf($tmp, $class, $parameters); break; case 'storage': // append instance creation $tmp = "\$this->storage = " . "\\Mojavi\\Storage\\Storage::newInstance('%s');"; $instances[] = sprintf($tmp, $class); // append instance initialization $tmp = "\$this->storage->initialize(\$this->context, " . "%s);"; $inits[] = sprintf($tmp, $parameters); break; case 'user': // append instance creation $tmp = "\$this->user = \\Mojavi\\User\\User::newInstance('%s');"; $instances[] = sprintf($tmp, $class); // append instance initialization $tmp = "\$this->user->initialize(\$this->context, %s);"; $inits[] = sprintf($tmp, $parameters); } } // context creation $context = "\$this->context = new \\Mojavi\\Core\\Context(%s, %s, %s, %s, %s);"; $context = sprintf($context, '$this', '$this->request', '$this->user', '$this->storage', '$this->databaseManager'); if (defined('MO_USE_LOGGING') && MO_USE_LOGGING) { LoggerManager::initialize(); } // compile data $retval = "<?php\n" . "// auth-generated by FactoryConfigHandler\n" . "// date: %s\n%s\n%s\n%s\n%s\n?>"; $retval = sprintf($retval, date('m/d/Y H:i:s'), implode("\n", $includes), implode("\n", $instances), $context, implode("\n", $inits)); return $retval; }
/** * logs an error message with priority of Logger::ERROR * * @param string A string message * * @return void * * @since 0.9.0 */ public static function fatal($message) { LoggerManager::log(new Message($message, Logger::FATAL)); }
/** * Sends the data to the api server and returns the result * @param Request $request * @param integer $method * @return Zend_Http_Response */ function send($request, $method = Request::GET, $url = null, $headers = array(), $remove_unsafe_params = true) { if ($this->getFunc() === '') { throw new \Exception('Param \'func\' is required.'); } if ($request instanceof Request) { $params = $request->getParameters(); } else { $params = $request; } try { /* @var $response Zend\Http\Response */ $response = $this->curl($url, $params, $method, $headers, $remove_unsafe_params); } catch (\Zend\Http\Client\Exception\RuntimeException $e) { if (self::DEBUG) { \Mojavi\Logging\LoggerManager::error('Error connecting to ' . $url . $this->getFunc()); } if (self::DEBUG) { \Mojavi\Logging\LoggerManager::error($e->getMessage()); } throw $e; } catch (\Exception $e) { throw $e; } if (is_object($response)) { if (!$response->isOk()) { $code = $response->getStatusCode(); switch ($code) { case 401: throw new \Exception($code . ' ' . $response->getReasonPhrase()); case 404: throw new \Exception($code . ' ' . $response->getReasonPhrase() . ' (' . $url . ')'); case 403: case 530: throw new \Exception('Access denied'); default: throw new \Exception($code . ' ' . $response->getReasonPhrase()); } } } return $response; }
/** * Returns the prepared statement with the values replaced. The statement will be * escaped for any string that was passed in. The internal string is not modified * during this process, so it can be used again and again with different values. * @return string */ function getPreparedStatement($con = null) { $retVal = $this->statement; foreach ($this->values as $name => $value) { if ($value['type'] == self::TYPE_BARE_STRING) { $retVal = str_replace("<<" . $name . ">>", $value['value'], $retVal); } else { if ($value['type'] == self::TYPE_UNESCAPED_STRING) { $retVal = str_replace("<<" . $name . ">>", $value['value'], $retVal); } else { if ($value['type'] == self::TYPE_ARRAY) { $retVal = str_replace("<<" . $name . ">>", "'" . implode("','", $value['value']) . "'", $retVal); } else { if (strpos($retVal, "<<" . $name . ">>") !== false) { $retVal = str_replace("<<" . $name . ">>", ":" . $name, $retVal); } else { unset($this->values[$name]); } } } } } /* @var $dbh PDOStatement */ if (is_null($con)) { $con = Controller::getInstance()->getContext()->getDatabaseConnection('default'); } if (is_null($con)) { LoggerManager::error(__METHOD__ . " :: " . var_export($con, true)); throw new \Exception('Cannot instantiate PDO object with query: ' . $retVal); } $dbh = $con->prepare($retVal); foreach ($this->values as $name => $value) { if ($value['type'] == self::TYPE_FLOAT) { $dbh->bindValue(":" . $name, $value["value"], \PDO::PARAM_INT); } else { if ($value['type'] == self::TYPE_INTEGER) { $dbh->bindValue(":" . $name, $value["value"], \PDO::PARAM_INT); } else { if ($value['type'] == self::TYPE_LONG) { $dbh->bindValue(":" . $name, $value["value"], \PDO::PARAM_INT); } else { if ($value['type'] == self::TYPE_DATE) { $dbh->bindValue(":" . $name, $value["value"], \PDO::PARAM_STR); } else { if ($value['type'] == self::TYPE_TIMESTAMP) { $dbh->bindValue(":" . $name, $value["value"], \PDO::PARAM_STR); } else { if ($value['type'] == self::TYPE_TIME) { $dbh->bindValue(":" . $name, $value["value"], \PDO::PARAM_STR); } else { if ($value['type'] == self::TYPE_NULL) { $dbh->bindValue(":" . $name, $value["value"], \PDO::PARAM_NULL); } else { if ($value['type'] == self::TYPE_BOOLEAN) { $dbh->bindValue(":" . $name, $value["value"], \PDO::PARAM_BOOL); } else { if ($value['type'] == self::TYPE_BARE_STRING) { continue; } else { if ($value['type'] == self::TYPE_UNESCAPED_STRING) { continue; } else { if ($value['type'] == self::TYPE_ARRAY) { continue; } else { if ($value['type'] == self::TYPE_BINARY_STRING) { $dbh->bindValue(":" . $name, $value["value"], \PDO::PARAM_STR); } else { $dbh->bindValue(":" . $name, $value["value"], \PDO::PARAM_STR); } } } } } } } } } } } } } return $dbh; }
/** * Execute an SQL Statement and return result to be handled by calling function. * * @param mixed PreparedStatement or KeyBasedPreparedStatement * @param string Name of connection to be used * @param resource $connection Connection resource handler * @return mixed Resource if query executed successfully, otherwise false */ public function executeInsert(PreparedStatement $ps, $name = 'default', $con = NULL, $debug = self::DEBUG) { if ($ps instanceof PdoPreparedStatement) { return parent::executeInsert($ps, $name, $con, $debug); } $retval = false; try { // Connect to database if (is_null($con)) { if (self::DEBUG) { LoggerManager::debug(__METHOD__ . ":: Retrieving New DB Connection for '" . $name . "'..."); } $con = $this->getContext()->getDatabaseConnection($name); } if (function_exists('mysql_ping')) { if (!mysql_ping($con)) { $this->getContext()->getDatabaseManager()->getDatabase($name)->shutdown(); $con = $this->getContext()->getDatabaseConnection($name); } } else { throw new Exception('Missing php-mysql libraries on this server'); } // Get the prepared query $query = $ps->getPreparedStatement($con); if ($debug) { LoggerManager::error(__METHOD__ . " :: " . $ps->getDebugQueryString()); } // Execute the query $rs = mysql_query($query, $con); if (!$rs) { throw new Exception(mysql_error($con)); } else { return mysql_insert_id($con); } } catch (MojaviException $e) { $this->getErrors()->addError('error', new Error($e->getMessage())); LoggerManager::fatal($e->printStackTrace('')); throw $e; } catch (PDOException $e) { $e = new MojaviException($e->getMessage()); LoggerManager::fatal($e->printStackTrace('')); throw $e; } catch (Exception $e) { $this->getErrors()->addError('error', new Error($e->getMessage())); $e = new MojaviException($e->getMessage()); LoggerManager::fatal($e->printStackTrace('')); throw $e; } }
/** * Execute an SQL Statement and return result to be handled by calling function. * * @param mixed PreparedStatement or KeyBasedPreparedStatement * @param string Name of connection to be used * @param resource $connection Connection resource handler * @return mixed Resource if query executed successfully, otherwise false */ public function executeInsert(PreparedStatement $ps, $name = 'default', $con = NULL, $debug = self::DEBUG) { $retval = false; try { // Connect to database if (is_null($con)) { if (self::DEBUG) { LoggerManager::debug(__METHOD__ . ":: Retrieving New DB Connection for '" . $name . "'..."); } $con = $this->getContext()->getDatabaseConnection($name); } // Get the prepared query /* @var $sth PDOStatement */ $sth = $ps->getPreparedStatement($con); // Debug the query to the log if ($debug) { LoggerManager::error(__METHOD__ . " :: " . $ps->getDebugQueryString()); } // Execute the query $sth->execute(); // Return the last insert id $retval = $con->lastInsertId(); } catch (PDOException $e) { // If the MySQL server has gone away, try reconnecting, otherwise throw an exception if ($e->getMessage() == 'SQLSTATE[HY000]: General error: 2006 MySQL server has gone away') { try { $this->getContext()->getDatabaseManager()->getDatabase($name)->shutdown(); // Connect to database $con = $this->getContext()->getDatabaseConnection($name); // Get the prepared query /* @var $sth PDOStatement */ $sth = $ps->getPreparedStatement($con); if ($debug) { LoggerManager::error(__METHOD__ . " :: " . $ps->getDebugQueryString()); } // Execute the query $sth->execute(); $retval = $sth; } catch (Exception $e) { ob_start(); $sth->debugDumpParams(); $stmt = ob_get_clean(); $this->getErrors()->addError('error', new Error($e->getMessage() . ": " . $sth->queryString)); $e = new MojaviException($e->getMessage()); LoggerManager::fatal($sth->queryString); LoggerManager::fatal($stmt); LoggerManager::fatal($e->printStackTrace('')); throw $e; } } else { if (strpos($e->getMessage(), 'Lock wait timeout exceeded; try restarting transaction') !== false) { // If there was a lock on the transaction, then try it again before failing try { $this->getContext()->getDatabaseManager()->getDatabase($name)->shutdown(); // Connect to database $con = $this->getContext()->getDatabaseConnection($name); // Get the prepared query /* @var $sth PDOStatement */ $sth = $ps->getPreparedStatement($con); if ($debug) { LoggerManager::error(__METHOD__ . " :: " . $ps->getDebugQueryString()); } // Execute the query $sth->execute(); $retval = $sth; } catch (Exception $e) { ob_start(); $sth->debugDumpParams(); $stmt = ob_get_clean(); $this->getErrors()->addError('error', new Error($e->getMessage() . ": " . $sth->queryString)); $e = new MojaviException($e->getMessage()); LoggerManager::fatal($sth->queryString); LoggerManager::fatal($stmt); LoggerManager::fatal($e->printStackTrace('')); throw $e; } } else { ob_start(); $sth->debugDumpParams(); $stmt = ob_get_clean(); $this->getErrors()->addError('error', new Error($e->getMessage() . ": " . $sth->queryString)); $e = new MojaviException($e->getMessage()); LoggerManager::fatal($sth->queryString); LoggerManager::fatal($stmt); LoggerManager::fatal($e->printStackTrace('')); throw $e; } } } catch (MojaviException $e) { // Output Mojavi Exceptions to the log and throw the Exception $this->getErrors()->addError('error', new Error($e->getMessage())); LoggerManager::fatal($e->printStackTrace('')); throw $e; } catch (Exception $e) { // Output Normal Exceptions to the log and throw the Exception $this->getErrors()->addError('error', new Error($e->getMessage())); $e = new MojaviException($e->getMessage()); LoggerManager::fatal($e->printStackTrace('')); throw $e; } return $retval; }