Example #1
0
 /**
  * Goes through the update files, and updates them.
  */
 public function update()
 {
     try {
         $this->versionDao->find(array('number' => 1));
         // Throws exception if database not setup.
     } catch (DatabaseQueryException $e) {
         if ($this->initializeIfNecessary) {
             $this->executeUpdate(new DatabaseUpdate($this->initUpdateFilename, 0, 'sql'));
         } else {
             throw new DatabaseNotInitializedException();
         }
     }
     $this->db->startTransaction();
     $updates = $this->getAllUpdates();
     foreach ($updates as $update) {
         try {
             $this->executeUpdate($update);
         } catch (Exception $e) {
             $this->db->rollback();
             throw $e;
         }
     }
     if (count($this->executedUpdates) > 0) {
         $this->db->commit();
     }
 }
Example #2
0
 public static function user($uniID, $handle, $displayName = "", $timezone = "")
 {
     Database::startTransaction();
     if ($pass = Database::query("INSERT INTO `users` (`uni_id`, `clearance`, `handle`, `display_name`, `timezone`, `date_joined`) VALUES (?, ?, ?, ?, ?, ?)", array($uniID, 2, $handle, $displayName, $timezone, time()))) {
         $pass = Database::query("INSERT INTO `users_handles` (handle, uni_id) VALUES (?, ?)", array($handle, $uniID));
     }
     return Database::endTransaction($pass);
 }
 public static function copy($sourceTable, $destinationTable, $sqlWhere = "", $sqlArray = array(), $limit = 1000, $move = false)
 {
     // Protect Tables
     if (!IsSanitized::variable($destinationTable) or !IsSanitized::variable($sourceTable)) {
         return false;
     }
     // Make sure the backup table exists
     Database::exec("CREATE TABLE IF NOT EXISTS " . $destinationTable . " LIKE " . $sourceTable);
     // Begin the Database_Transfer
     Database::startTransaction();
     // Insert Rows into Database_Transfer Table
     Database::query("INSERT INTO " . $destinationTable . " SELECT * FROM " . $sourceTable . ($sqlWhere != "" ? " WHERE " . Sanitize::variable($sqlWhere, " ,`!=<>?()") : "") . ($limit ? ' LIMIT ' . (int) $limit : ''), $sqlArray);
     $newCount = Database::$rowsAffected;
     if ($move === true) {
         // Delete Rows from Original Table (if applicable)
         Database::query("DELETE FROM " . $sourceTable . ($sqlWhere != "" ? " WHERE " . Sanitize::variable($sqlWhere, " ,`!=<>?()") : ""), $sqlArray);
         // If the number of inserts matches the number of deletions, commit the transaction
         return Database::endTransaction($newCount == Database::$rowsAffected);
     }
     return Database::endTransaction();
 }
 public static function processForm($submittedData, $lookupID = null)
 {
     // We need to track what child data gets submitted
     $classSubmissions = [];
     $relatedClassList = [];
     // Make sure there is submitted data passed to the form
     if (!$submittedData) {
         return false;
     }
     // Loop through the schema's relationships and see if they were part of the submission
     // For example, if the "User" form includes "User_ContactData" in its relationships, check to see if
     // any "User_ContactData" records were included in this form.
     foreach (static::$schema['relationships'] as $relationName => $relatedClass) {
         // If a record of the relationship was found, we need to verify those values.
         // Otherwise, skip to the next relationship.
         if (!isset($submittedData[$relationName])) {
             continue;
         }
         $relatedClassList[] = $relatedClass;
         // A related class has content posted in this form.
         // Loop through the submitted data to extract the relevant pieces and verify it.
         foreach ($submittedData[$relationName] as $postedData) {
             $relatedClassType = get_parent_class($relatedClass);
             // Classes with the "Child" model are verified differently than classes with "Join" models
             if ($relatedClassType == "Model_Child") {
                 // If the user didn't change the default values (or left the row empty), we assume that they
                 // didn't want to create that record. Therefore, we don't check that row for errors.
                 if (!$relatedClass::checkIfSubmissionIsEmpty($postedData)) {
                     if ($relatedClass::verifySchema($postedData)) {
                         // Track this submission data so that it can be processed into the database - but only
                         // after the main table is processed (needs the lookup ID) and only if everything was
                         // processed successfully.
                         $classSubmissions[$relatedClass][] = $postedData;
                     }
                 }
             } else {
                 if ($relatedClassType == "Model_Join") {
                     // If the data provided isn't empty, just verify that it's a valid ID being linked
                     if ($postedData != "") {
                         // Get the class that was being joined
                         $joinedClass = $relatedClass::$relatedClass;
                         // Make sure the record exists
                         if (!$joinedClass::exists($postedData)) {
                             Alert::error($relationName . " Failed", "Provided an invalid option for `" . $relationName . "`.");
                             continue;
                         }
                         // Track this submission data so that it can be processed later.
                         $classSubmissions[$relatedClass][] = [$relatedClass::$relatedKey => $postedData];
                     }
                 }
             }
         }
     }
     // Validate each Schema Column
     static::verifySchema($submittedData);
     // Check if the entire form validated successfully
     if (!Validate::pass()) {
         // The form failed - end here with a failure
         return false;
     }
     // The form was successful. We need to run a series of updates on the database.
     // Begin a Database Transaction
     Database::startTransaction();
     // Create the Primary Table (if we were doing a "CREATE" form)
     if (!$lookupID) {
         $lookupID = static::create($submittedData);
     } else {
         static::update($lookupID, $submittedData);
     }
     // Loop through each class that has child records and purge existing linked records
     foreach ($relatedClassList as $relatedClass) {
         // Delete any existing child records related to this lookup ID
         $relatedClass::delete($lookupID);
     }
     // Add all of the related records
     foreach ($classSubmissions as $relatedClass => $postedRecord) {
         // Loop through the records posted and insert them into the database
         foreach ($postedRecord as $schemaEntry) {
             // Make sure that the child class is properly pointed at the primary class
             // We need to set the missing lookup key
             $schemaEntry[$relatedClass::$lookupKey] = $lookupID;
             // Run the creation process
             $relatedClass::create($schemaEntry);
         }
     }
     // Commit the transaction
     return Database::endTransaction();
 }
Example #5
0
 /**
  * Shorthand for: Dao->getDb()->beginTransaction()
  * Be careful: this starts a transaction on the database! So all Daos using the same database will be in the same transaction.
  */
 public function startTransaction()
 {
     $this->db->startTransaction();
 }
Example #6
0
 public static function buildDatabase($buildData)
 {
     var_dump($buildData);
     // Prepare Values
     if (!is_array($buildData)) {
         $buildData = json_decode($buildData, true);
     }
     $class = get_called_class();
     Database::startTransaction();
     // Loop through JSON entries
     foreach ($buildData as $entityID => $entry) {
         $prepData = [];
         foreach ($entry as $attribute => $value) {
             // Relationships (start with uppercase letter)
             if (ctype_upper($attribute[0])) {
                 $indexHash = self::prepIndexHash($this->class, $this->id, $attribute);
                 foreach ($value as $relatedEntity) {
                     Database::query("REPLACE INTO `entity_relationships` (index_hash, related_id) VALUES (?, ?)", [$indexHash, $relatedEntity]);
                 }
                 continue;
             }
             $prepData[$attribute] = $value;
         }
         static::update($entityID, $prepData);
     }
     return Database::endTransaction();
 }
 public function updateToVersion($versionIDTo, $versionIDFrom)
 {
     // If the versions are identical, we don't need to run this function
     if ($versionIDTo == $versionIDFrom) {
         return false;
     }
     // Prepare Values
     $orderDirection = $versionIDTo > $versionIDFrom ? "ASC" : "DESC";
     // TODO: Allow branchID to be something other than master
     $branchID = 0;
     // TODO: We need to run integrity checks on these versions
     if (!$this->verifyVersion($branchID, $versionIDTo)) {
         return false;
     }
     if (!$this->verifyVersion($branchID, $versionIDFrom)) {
         return false;
     }
     // Pull all instructions sets from current to previous, in appropriate order
     if ($results = Database::selectMultiple("SELECT instruction_set FROM version_control_commits WHERE branch_id=? AND commit_id BETWEEN ? AND ? ORDER BY commit_id " . $orderDirection, array($branchID, $versionIDTo, $versionIDFrom))) {
         $success = true;
         // Begin database transaction to preserve integrity
         Database::startTransaction();
         // Loop through each instruction set and process it
         foreach ($result as $ins) {
             // Process the instruction
             // If the instruction fails - end the transaction
             if (!($success = $this->processInstructions($ins))) {
                 break;
             }
         }
         // If everything was successful, finish the transaction
         return Database::endTransaction($success);
     }
     // Nothing processed
     return false;
 }
Example #8
0
if (Form::submitted("add-user-uni6")) {
    // Check if all of the input you sent is valid:
    Validate::variable("Handle", $_POST['handle'], 1, 22);
    Validate::text("Display Name", $_POST['display_name'], 3, 22);
    Validate::password($_POST['password']);
    Validate::email($_POST['email']);
    // Check if the handle has already been taken
    if (AppAccount::handleTaken($_POST['handle'])) {
        Alert::error("Handle Taken", "That handle has already been taken", 1);
    }
    if (Database::selectOne("SELECT email FROM users WHERE email=? LIMIT 1", array($_POST['email']))) {
        Alert::error("Email", "That email already exists.", 1);
    }
    // Final Validation Test
    if (Validate::pass()) {
        Database::startTransaction();
        $uniID = 0;
        // Check if the account already exists
        if ($checkAuth = Database::selectValue("SELECT uni_id FROM users WHERE handle=? LIMIT 1", array($_POST['handle']))) {
            $uniID = (int) $checkAuth;
        } else {
            if ($regSuccess = Database::query("INSERT INTO users (handle, display_name, email, password, date_joined, auth_token, verified) VALUES (?, ?, ?, ?, ?, ?, ?)", array($_POST['handle'], $_POST['display_name'], $_POST['email'], Security_HashPassword::set($_POST['password']), time(), Security_Hash::random(22, 72), 1))) {
                $uniID = (int) Database::$lastID;
                if (isset($_POST['send_email'])) {
                    // Email a verification letter
                    AppVerification::sendVerification($uniID);
                    Alert::success("Email Sent", "The account was created successfully! A verification email has been sent to " . $_POST['email'] . "!");
                } else {
                    Alert::success("User Added", "The account was created successfully!");
                }
            }