示例#1
0
 /**
  * Removes the current log entry
  * @param \System\Db\Database The database to operate on
  */
 public final function delete()
 {
     $query = new \System\Db\Query($this->getDatabase(), SQL_LOG_SYSERROR_DELETE);
     $query->bind($this->getId(), \System\Db\QueryType::TYPE_INTEGER);
     $this->getDatabase()->query($query);
     return true;
 }
示例#2
0
 /**
  * This functions outputs the message to the log
  * @param string The message to output to the given log.
  * @param integer The level of the logger
  */
 public function out($message, $level = \System\Log\LoggerLevel::LEVEL_INFO)
 {
     $register = \System\Register\Register::getInstance();
     assert($register->defaultDb);
     $db = $register->defaultDb;
     $query = new \System\Db\Query($db, SQL_ERRORLOGGER_INSERT);
     $query->bind($level);
     $query->bind($message, \System\Db\QueryType::TYPE_STRING);
     $query->bind($message, \System\Db\QueryType::TYPE_STRING);
     $db->query($query);
 }
示例#3
0
 /**
  * Dynamically loads objects from the relational database into xml based objects.
  * The object used must inherit from the \System\Base\DynamicBaseObj class.
  * @param \System\Db\Database The database object to query
  * @param string The full classname of the class to use as the base object.
  * @param string The condition string as described in the objects xml file
  * @param \System\Collection\Vector The parameters to be used in the condition. If an item in the vector is a vector itself, its items are imploded by ', ' and treated as a \System\Db\QueryType::TYPE_QUERY parameter
  * @param bool When true, the result will always be wrapped in a \System\Db\DatabaseResult vector, even if there is only one result.
  * @param bool When true, the secondary db connection pipe is used to read the data from.
  * @return mixed If there is one result, then only an instance of the requested object is returned; when there are multiple results a \System\Db\DatabaseResult vector is returned, also see the $alwaysUseContainer parameter. If there are no results, null is returned
  */
 public static final function load(\System\Db\Database $db, $className, $condition, \System\Collection\Vector $parameters = null, $alwaysUseContainer = false, $useSecondaryDatabasePipe = true)
 {
     $event = new \System\Event\Event\OnBeforeDynamicObjectLoadEvent();
     $event->setDatabase($db)->setDynamicClassName($className)->setCondition($condition)->setParameters($parameters ?: new \System\Collection\Vector())->setAlwaysUseContainer($alwaysUseContainer)->setUseSecondaryDatabasePipe($useSecondaryDatabasePipe);
     $event->raise();
     //if the event has listeners that want to override the call, we redirect it and call that instead, this will logically re-fire the event!
     if ($event->hasListeners('\\System\\Event\\Event\\OnBeforeDynamicObjectLoadEvent') && ($event->getDatabase() != $db || $event->getDynamicClassName() != $className || $event->getCondition() != $condition || !(!$parameters && $event->getParameters()->count() == 0 || $parameters == $event->getParameters()) || $event->getAlwaysUseContainer() != $alwaysUseContainer || $event->getUseSecondaryDatabasePipe() != $useSecondaryDatabasePipe)) {
         return self::load($event->getDatabase(), $event->getDynamicClassName(), $event->getCondition(), $event->getParameters(), $event->getAlwaysUseContainer(), $event->getUseSecondaryDatabasePipe());
     }
     if (!class_exists($className) || !is_subclass_of($className, '\\System\\Base\\DynamicBaseObj')) {
         throw new \System\Error\Exception\ObjectLoaderSourceException('The given class ' . $className . ' does not appear to be a valid child of \\System\\Base\\DynamicBaseObj or does not exist (is the Module loaded?).');
     }
     call_user_func(array($className, 'prepareObject'));
     $queryString = call_user_func(array($className, 'queryForCondition'), $condition);
     $query = new \System\Db\Query($db, $queryString);
     $query->setResultType($className);
     //Use or dont use the secondary connection pipe
     $query->setUseSecondaryPipe($useSecondaryDatabasePipe);
     /*
     we need the validator to check the type of the value.
     this is needed, because an integer can also be string containing numbers.
     */
     $val = new \System\Security\Validate();
     if ($parameters) {
         foreach ($parameters as $index => $param) {
             //we need to decide the type of the parameter. Currently we only support integers and strings and Vectors.
             $type = \System\Db\QueryType::TYPE_INTEGER;
             //if the item is a Vector, we implode the vector and add it as a \System\Db\QueryType::TYPE_QUERY type parameter.
             if ($param instanceof \System\Collection\Vector) {
                 $type = \System\Db\QueryType::TYPE_QUERY;
                 $param = $param->convertToString();
             } else {
                 if ($val->isInt($param, $index, null, null, true) == \System\Security\ValidateResult::VALIDATE_INVALIDVALUE) {
                     $type = \System\Db\QueryType::TYPE_STRING;
                 }
             }
             $query->bind($param, $type);
         }
     }
     //actually execute the query
     $results = $db->query($query);
     //if there is only 1 result, then we just return that instead of the entire Vector
     if ($results->count() == 1 && !$alwaysUseContainer) {
         return $results->current();
     }
     //we return null if there are no results
     if ($results->count() == 0 && !$alwaysUseContainer) {
         return null;
     }
     return $results;
 }
示例#4
0
 /**
  * Creates a new DbLookup object.
  * @param Database The database to create the connection in. This should be the DbLookup pool
  * @param string The unique name of the DbLookup entry
  * @param string The server or db host
  * @param string The connection user
  * @param string The connection password
  * @param string The name of the database used
  * @param int The port for the database connection
  * @param bool True to use persistant connections
  * @return DbLookup The newly created DbLookup object
  */
 public static final function create(\System\Db\Database $db, $name, $dbServer, $dbUser, $dbPassword, $dbName, $dbPort = self::DB_PORT_DEFAULT, $persistent = self::DB_PERSISTANT_DEFAULT)
 {
     $previousAutocommit = $db->getAutocommit();
     $db->setAutocommit(false);
     $query = new \System\Db\Query($db, SQL_DBLOOKUP_CREATE);
     $query->bind($name, \System\Db\QueryType::TYPE_STRING);
     $db->query($query);
     $insertId = $db->getInsertId();
     $dbLookup = self::loadPrimary($db, $insertId);
     assert($dbLookup);
     $dbLookup->setDbName($dbName)->setDbServer($dbServer)->setDbUser($dbUser)->setDbPassword($dbPassword)->setDbPort($dbPort)->setDbPersistent($persistent);
     $dbLookup->storePrimary();
     $db->setAutocommit($previousAutocommit);
     return $dbLookup;
 }
示例#5
0
 /**
  * Provides functionality to check if a given IP is blocked by a common blacklist
  * Do note this system requires the use of the PERMABAN_* directives
  * @param string The IP Address to check.
  * @return bool True if the IP is allowed, false otherwise
  */
 public static final function isIPAllowed($ipAddress)
 {
     //if there is an explicit empty PERMABAN, we accept everything
     if (PERMABAN_HOST == '') {
         return true;
     }
     $allowed = true;
     $mc = new \System\Cache\Memcache\Memcache();
     $key = self::MEMCACHE_KEY . $ipAddress;
     //we get the value from the memcache, and only recheck if the blocked user is on it.
     if (!($allowed = $mc->get($key))) {
         $db = \System\Db\Database::getConnection(PERMABAN_HOST, PERMABAN_USER, PERMABAN_PASS, PERMABAN_NAME, PERMABAN_PORT);
         $query = new \System\Db\Query($db, \System\HTTP\Visitor\PermaBan\SQL_PERMABAN_CHECK_PERMABAN);
         $query->bind($ipAddress, \System\Db\QueryType::TYPE_STRING);
         $results = $db->query($query);
         $allowed = $results->count() == 0;
         $mc->store($key, $allowed);
     }
     return $allowed;
 }
示例#6
0
 /**
  * Stores the current object back to the database. This function only does an incremental update, meaning that only the changed fields are updated.
  * The update reflects the changes made to the object, and does not consider updates to the database in the time between retrieval of this object
  * and the calling of this function.
  * This update is executed without the use of transactions.
  * @param string The condition to use for the update
  * @param \System\Collection\Vector The parameters for the condition
  * @return integer The amount of affected rows
  */
 public function store($condition, \System\Collection\Vector $parameters)
 {
     $fieldMap = self::validateMap(self::$fieldMap);
     $conditionMap = self::validateMap(self::$conditionMap);
     $modifications = $this->validateInstanceMap($this->modifications);
     $virtualModifications = $this->validateInstanceMap($this->virtualModifications);
     $dataMap = $this->validateInstanceMap($this->data);
     //we  dont do anything if we dont have anything to do, no modifications
     if (!$modifications->hasItems() && !$virtualModifications->hasItems()) {
         return 0;
     }
     if (!$conditionMap->keyExists($condition)) {
         throw new \System\Error\Exception\ObjectLoaderSourceException('Invalid condition given. Condition is not defined in ' . $this->getClassName() . '.');
     }
     //create the query
     $tuples = new \System\Collection\Vector();
     foreach ($modifications as $modification) {
         $dataField = $fieldMap->{$modification};
         $tuples[] = "`" . mb_strtolower((string) $dataField['dbkey']) . "` = %?%";
     }
     //iterate over all the virtual modifications as we do want to reflect those
     foreach ($virtualModifications as $virtualModification) {
         $tuples[] = "`" . mb_strtolower($virtualModification) . "` = %?%";
     }
     //we get the table definitions again. could have saved this at load, but now we reduce memory footprint at the cost of neglectable slower saving.
     $querySources = self::createQuerySources(self::$xmlTree[get_class($this)]);
     $conditionString = $conditionMap->{$condition};
     $sql = 'UPDATE ' . $querySources . ' SET ' . $tuples->convertToString() . ' ' . $conditionString;
     $query = new \System\Db\Query($this->getDatabase(), $sql);
     //bind the values to the query for setting the new values
     foreach ($modifications as $modification) {
         $fieldData = $fieldMap->{$modification};
         $modification = mb_strtolower($modification);
         //get the type of the parameter. only integers and strings are supported
         switch (mb_strtolower((string) $fieldData['type'])) {
             case \System\Type::TYPE_BOOL:
             case \System\Type::TYPE_BOOLEAN:
             case \System\Type::TYPE_INT:
             case \System\Type::TYPE_INTEGER:
                 $type = \System\Db\QueryType::TYPE_INTEGER;
                 break;
             default:
                 $type = \System\Db\QueryType::TYPE_STRING;
         }
         //we first check if the new value is set to nullify, if so, we actually store NULL
         if (isset($fieldData['nullify']) && (string) $fieldData['nullify'] == $dataMap->{$modification}) {
             $query->bind('NULL', \System\Db\QueryType::TYPE_QUERY);
         } elseif (isset($fieldData['encoding'])) {
             switch (mb_strtolower((string) $fieldData['encoding'])) {
                 case self::ENCRYPTION_BASE64:
                     $type = \System\Db\QueryType::TYPE_STRING;
                     $query->bind(self::encodeBase64($dataMap->{$modification}), $type);
                     break;
                 case self::ENCRYPTION_XOR:
                     $type = \System\Db\QueryType::TYPE_STRING;
                     $query->bind(self::encodeXOR($dataMap->{$modification}), $type);
                     break;
                 case self::ENCRYPTION_AES:
                     $type = \System\Db\QueryType::TYPE_STRING;
                     $query->bind(self::encodeAES($dataMap->{$modification}), $type);
                     break;
                 default:
                     throw new \System\Error\Exception\ObjectLoaderSourceException('The given encryptionmethod is not supported.');
             }
         } else {
             $query->bind($dataMap->{$modification}, $type);
         }
     }
     //bind the values to the query for setting the new values
     foreach ($virtualModifications as $virtualModification) {
         $type = \System\Db\QueryType::TYPE_STRING;
         $virtualField = 'virtual_' . $virtualModification;
         $value = $dataMap->{$virtualField};
         $query->bind((string) $value, $type);
     }
     //bind the condition values to the query
     $val = new \System\Security\Validate();
     foreach ($parameters as $index => $param) {
         //we need to decide the type of the parameter. Currently we only support integers and strings.
         $type = \System\Db\QueryType::TYPE_INTEGER;
         if ($val->isInt($param, $index, null, null, true) == \System\Security\ValidateResult::VALIDATE_INVALIDVALUE) {
             $type = \System\Db\QueryType::TYPE_STRING;
         }
         $query->bind($param, $type);
     }
     //execute the query
     $this->getDatabase()->query($query);
     //reset the modified list, because we already stored this. No need to store the same things at successive calls.
     $modifications->clear();
     return $this->getDatabase()->getAffectedRows();
 }
示例#7
0
 /**
  * Peeks at the queue, returning its value but
  * keeping the queue intact.
  * @return mixed The peeked item from the queue
  */
 public function peek()
 {
     $query = new \System\Db\Query($this->db, SQL_QUEUE_PEEK);
     $query->bind($this->queueTableName, \System\Db\QueryType::TYPE_QUERY);
     $result = $this->db->querySingle($query);
     if ($result) {
         return unserialize($result->value);
     }
     return null;
 }
示例#8
0
 /**
  * Retrieve the stored value from the LUT.
  * @param \System\Db\Database The database
  * @param string The key to use for the LUT. Max 255 chars.
  * @param mixed The variable to store the result in. Defaults to NULL and only gives result on \System\Cache\LUTCache\Status::CACHE_HIT
  * @return int The return value for the function. See \System\Cache\LUTCache\Status::CACHE_HIT, \System\Cache\LUTCache\Status::CACHE_MISS, \System\Cache\LUTCache\Status::CACHE_GENERATING
  */
 public static final function retrieve(\System\Db\Database $db, $key, &$value = null)
 {
     if (self::getLUTCacheCache($key, $value)) {
         return \System\Cache\LUTCache\Status::CACHE_HIT;
     }
     $query = new \System\Db\Query($db, \System\Cache\LUTCache\SQL_LUTCACHE_RETRIEVE);
     $query->bind($key, \System\Db\QueryType::TYPE_STRING);
     $results = $db->query($query);
     if ($results->count() == 0) {
         return Status::CACHE_MISS;
     }
     if ($results->current()->lutcache_status != \System\Cache\LUTCache\Status::CACHE_HIT) {
         return $results->current()->lutcache_status;
     }
     $value = $results->current()->lutcache_value;
     self::setLUTCacheCache($key, $value);
     return \System\Cache\LUTCache\Status::CACHE_HIT;
 }
示例#9
0
 /**
  * Returns a Vector with all table column names from the requested table
  * @param \System\Db\Database the database to query
  * @param string The tablename to retrieve the columns from
  * @return \System\Collection\Vector a Vector containing all the column names
  */
 public static final function getTableColumnNames(\System\Db\Database $db, $tableName)
 {
     $query = new \System\Db\Query($db, 'SHOW COLUMNS FROM %?%');
     $query->bind($tableName, \System\Db\QueryType::TYPE_QUERY);
     $results = $db->query($query);
     $columnNames = new \System\Collection\Vector();
     foreach ($results as $result) {
         $columnNames[] = $result->Field;
     }
     return $columnNames;
 }
示例#10
0
 /**
  * Iterates through the given resultset, dispatching every single mail with the given priority.
  * @param \System\Db\Database The database to use for the emailsystem queue
  * @param SMTP The smtp to use
  * @param \System\Db\DatabaseResult The results to iterate
  * @param int The priority level
  */
 private static final function iterateMailResults(\System\Db\Database $db, \System\Email\SMTP $smtp, \System\Db\DatabaseResult $results, $priority)
 {
     foreach ($results as $result) {
         $attachQuery = new \System\Db\Query($db, \System\Email\SQL_EMAILSYSTEM_GET_ATTACH);
         $attachQuery->bind($result->id, \System\Db\QueryType::TYPE_INTEGER);
         $attachQuery->bind($priority, \System\Db\QueryType::TYPE_INTEGER);
         $attachments = $db->query($attachQuery);
         self::addToLog('Processing ' . $results->count() . ' ' . self::$priorityNames[$priority][0] . ' priority mails');
         self::dispatchSingleMail($smtp, $result->from, self::convertAddressStringToArray($result->to), self::convertAddressStringToArray($result->cc), self::convertAddressStringToArray($result->bcc), $result->subject, $result->message, $attachments);
         $query = new \System\Db\Query($db, \System\Email\SQL_EMAILSSYTEM_DELETEMAIL);
         $query->bind(self::$priorityNames[$priority][1], \System\Db\QueryType::TYPE_QUERY);
         $query->bind($result->id, \System\Db\QueryType::TYPE_INTEGER);
         $db->query($query);
         $query = new \System\Db\Query($db, \System\Email\SQL_EMAILSYSTEM_DELETEATTACH);
         $query->bind($result->id, \System\Db\QueryType::TYPE_INTEGER);
         $query->bind($priority, \System\Db\QueryType::TYPE_INTEGER);
         $db->query($query);
     }
 }
示例#11
0
 /**
  * Delete an onetimecall. This invalidates the object in the db.
  * @param \System\Db\Database The database to query
  * @return null so we stop the chaining
  */
 public final function delete(\System\Db\Database $db)
 {
     $query = new \System\Db\Query($db, SQL_ONETIMECALL_DELETE);
     $query->bind($this->getId(), \System\Db\QueryType::TYPE_INTEGER);
     $db->query($query);
     return null;
 }
示例#12
0
 /**
  * Writes the session data to the session storage. Called by session_write_close(), when session_register_shutdown() fails, or during a normal shutdown.
  * @param string The session Id
  * @param mixed The encoded session data
  * @return bool Always true
  */
 public function write($sessionId, $sessionData)
 {
     $query = new \System\Db\Query($this->database, SQL_DATABASE_WRITE);
     $query->bind(self::SESSION_TABLE, \System\Db\QueryType::TYPE_QUERY);
     $query->bind($sessionId, \System\Db\QueryType::TYPE_STRING);
     $query->bind($this->sessionName, \System\Db\QueryType::TYPE_STRING);
     $query->bind($sessionData, \System\Db\QueryType::TYPE_STRING);
     $query->bind($this->sessionName, \System\Db\QueryType::TYPE_STRING);
     $query->bind($sessionData, \System\Db\QueryType::TYPE_STRING);
     $this->database->query($query);
     return true;
 }