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 function registerUser($name, $role_id, $email, $password, $phone, $lang_id, $birthday, $company = false) { // Accepts 5 arguments in the array: name, email, password, phone, lang_id, birthday (optional) // $settings = array(string $name, string $email, string $phone, int $lang_id [, date(YYYY-MM-DD) $birthday ] ); // setting values from settings array $date_registered = date("Y-m-d"); // checking if email exists if ($this->userEmailExist($email)) { throw new Exception(Translate::string("user.email_already_exists"), 1); } else { $db = new Database(); $db->beginTransaction(); // setting the user properties and validating $this->setName($name); $this->setRole($role_id); $this->setEmail($email); $this->setPassword($password); $this->setPhone($phone); $this->setDateRegistred($date_registered); $this->setLangID($lang_id); $this->setBirthday($birthday); $db->query('INSERT INTO users ( name, role_id, email, password, phone, date_registered, lang_id, birthday) VALUES (:name,:role_id,:email,:password,:phone,:date_registered,:lang_id,:birthday) '); $db->bind(':name', $this->name()); $db->bind(':role_id', $this->role()); $db->bind(':email', $this->email()); $db->bind(':password', $this->password()); $db->bind(':phone', $this->phone()); $db->bind(':date_registered', $this->dateRegistred()); $db->bind(':lang_id', $this->langID()); $db->bind(':birthday', $this->birthday()); $db->execute(); $newUserID = $db->lastInsertId(); if ($company) { $db->query('INSERT INTO companies ( user_id, company_name, company_number, company_address, company_zip, phone_2) VALUES (:user_id, :company_name,:company_number,:company_address,:company_zip,:phone_2) '); $db->bind(':user_id', $newUserID); $db->bind(':company_name', $this->company_name); $db->bind(':company_number', $this->company_number); $db->bind(':company_address', $this->company_address); $db->bind(':company_zip', $this->company_zip); $db->bind(':phone_2', $this->phone_2); $db->execute(); } $db->endTransaction(); $this->setID($newUserID); $this->checkCredentials($this->email(), $password, 1, $_SERVER["HTTP_USER_AGENT"], $_SERVER["REMOTE_ADDR"], session_id()); } }
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(); }
<?php spl_autoload_register(function ($class) { require_once "../../lib/classes/" . $class . ".class.php"; }); if (!isset($_SESSION)) { session_start(); } if (isset($_POST["userID"])) { $db = new Database(); $db->beginTransaction(); $db->query("UPDATE users SET role_id=4 WHERE id = :id LIMIT 1"); $db->bind(':id', $_POST["userID"]); $update_user = $db->execute(); $db->query("UPDATE products SET status_id=4 WHERE user_id = :id "); $db->bind(':id', $_POST["userID"]); $update_products = $db->execute(); $db->endTransaction(); $db->insertAdminLog($_SESSION["employee"], "Deleted user " . $_POST["userID"] . " and all user advertisements", $_SERVER['HTTP_USER_AGENT'], $_SERVER['REMOTE_ADDR'], session_id()); if ($update_products && $update_user) { echo 'success'; } else { echo 'Deleting user was not successful. Please try again.'; } }
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(); }
<?php require "twitteroauth/autoload.php"; include "config.php"; include "db.php"; $database = new Database(); use Abraham\TwitterOAuth\TwitterOAuth; $connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET); $database->query('SELECT id,tweet,tweet_id from tweets WHERE sent=0'); $rows = $database->resultset(); $database->beginTransaction(); $database->query('UPDATE tweets SET sent = 1 where id = :id'); foreach ($rows as $tweet) { $result = $connection->post('statuses/update', array('in_reply_to_status_id' => $tweet['tweet_id'], 'status' => $tweet['tweet'])); print_r($result); if ($result->id > 0) { $database->bind(':id', $tweet['id']); $database->execute(); } } $database->endTransaction();
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; }
public static function display() { $r = ""; if ($_POST['cc_form'] == 'settings') { $name_lookup = array(); Database::beginTransaction(); foreach ($_POST as $key => $value) { if ($key == 'cc_form') { continue; } if (substr($key, 0, 12) == 'cc_settings_') { $name_lookup[substr($key, 12)] = explode('|', $value); continue; } $setting_name = $key; //var_dump(array_key_exists($key, $name_lookup),$name_lookup); if (!array_key_exists($setting_name, $name_lookup)) { continue; } if ($key == 'clean-urls') { $value = (bool) $value; } Database::update('settings', array('data'), array(serialize($value)), array('package = ? AND name = ?', $name_lookup[$setting_name][1], $name_lookup[$setting_name][0])); } $r .= Message::success(__('admin', 'settings-saved')); Database::endTransaction(); } $settings = Database::select('settings', '*', array('package = ? OR package = ? OR package = ? OR package = ?', 'core', 'admin', 'site', 'gui'), array('package', 'ASC', 'name', 'ASC')); $settings = $settings->fetchAll(PDO::FETCH_ASSOC); $rows = array(); foreach ($settings as $row) { if (!array_key_exists($row['package'], $rows)) { $rows[$row['package']] = array(); } $rows[$row['package']][] = $row; } ksort($rows); $form = new Form('self', 'POST', 'settings'); foreach ($rows as $cat => $catRows) { $form->startFieldset(__('settings', $cat)); foreach ($catRows as $row) { $data = unserialize($row['data']); $form->addHidden('cc_settings_' . UTF8::slugify($row['name']), $row['name'] . '|' . $row['package']); if ($row['name'] == 'clean urls') { $form->addSelectList(__('settings', $row['name']), UTF8::slugify($row['name']), array(1 => __('admin', 'yes'), 0 => __('admin', 'no')), true, $data); } else { if ($row['name'] == 'theme') { $themes = Themes::getThemeList(); $options = array(); foreach ($themes as $slug => $ini) { $options[$slug] = $ini['name']; } $form->addSelectList(__('settings', $row['name']), UTF8::slugify($row['name']), $options, true, $data); } else { if ($row['name'] == 'locale') { $locales = i18n::getLocales(); $form->addSelectList(__('settings', $row['name']), UTF8::slugify($row['name']), $locales, false, $data); } else { if ($row['name'] == 'homepage id') { $form->addSelectList(__('settings', $row['name']), UTF8::slugify($row['name']), Content::optionListArrayFromArray(Content::parseNavigation()), true, $data); } else { if ($row['name'] == 'site name') { $form->addInput(__('settings', $row['name']), 'text', UTF8::slugify($row['name']), $data); } else { if ($row['name'] == 'editor') { $editors = Editors::getNamesOfRegistered(); $form->addSelectList(__('settings', $row['name']), UTF8::slugify($row['name']), $editors, false, $data); } else { if ($row['name'] == 'homepage') { $form->addSelectList(__('settings', $row['name']), UTF8::slugify($row['name']), Admin::getAdminPageOptions(), true, $data); } } } } } } } } $form->endFieldset(); } $form->startFieldset(''); $form->addSubmit('', 'save-settings', __('admin', 'save')); $form->endFieldset(); return array(__('admin', 'settings'), $r . $form->endAndGetHTML()); }
if (!Project::install()) { $ok = false; $msg = "Could not setup Project object."; SystemEvent::raise(CINTIENT_LOG_SEVERITY_ERROR, $msg, "Installer"); sendResponse($ok, $msg); } if (!SystemSettings::install()) { $ok = false; $msg = "Could not setup SystemSettings object."; SystemEvent::raise(CINTIENT_LOG_SEVERITY_ERROR, $msg, "Installer"); sendResponse($ok, $msg); } // // Everything ok!!! // if (!Database::endTransaction()) { Database::rollbackTransaction(); $ok = false; $msg = "Problems commiting all changes to the database."; SystemEvent::raise(CINTIENT_LOG_SEVERITY_ERROR, $msg, "Installer"); sendResponse($ok, $msg); } $settings = SystemSettings::load(); $settings->setSetting(SystemSettings::VERSION, CINTIENT_INSTALLER_VERSION); if (!$upgrade) { // // Root user account // $user = new User(); $user->setEmail($get['email']); $user->setNotificationEmails($get['email'] . ',');
protected function _save($force = false) { if (!$this->_autoSave) { return true; } if (!$this->hasChanged()) { if (!$force) { return false; } SystemEvent::raise(SystemEvent::DEBUG, "Forced object save.", __METHOD__); } if (!Database::beginTransaction()) { return false; } // // The following is a workaround on the fact that the translation of this // serialized object to the database gets all broken, due to the fact of PHP // introducing NULL bytes around the '*' that is prepended before protected // variable members, in the serialized mode. This method replaces those // problematic NULL bytes with an identifier string '~~NULL_BYTE~~', // rendering serialization and unserialization of these specific kinds of // object safe. Credits to travis@travishegner.com on: // http://pt.php.net/manual/en/function.serialize.php#96504 // $serializedIntegrationBuilder = str_replace("", CINTIENT_NULL_BYTE_TOKEN, serialize($this->getIntegrationBuilder())); $serializedDeploymentBuilder = str_replace("", CINTIENT_NULL_BYTE_TOKEN, serialize($this->getDeploymentBuilder())); $sql = 'REPLACE INTO project' . ' (id,avatar,datecreation,' . ' description,title,visits,integrationbuilder,deploymentbuilder,status,' . ' releaselabel,statsnumbuilds,scmpassword,scmusername,workdir,' . ' scmremoterepository,scmconnectortype,scmcheckchangestimeout,' . ' datecheckedforchanges, specialtasks, optionreleasepackage,' . ' scmenvvars)' . " VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; $specialTasks = @serialize($this->getSpecialTasks()); if ($specialTasks === false) { $specialTasks = serialize(array()); } $val = array($this->getId(), $this->getAvatar(), $this->getDateCreation(), $this->getDescription(), $this->getTitle(), $this->getVisits(), $serializedIntegrationBuilder, $serializedDeploymentBuilder, $this->getStatus(), $this->getReleaseLabel(), $this->getStatsNumBuilds(), $this->getScmPassword(), $this->getScmUsername(), $this->getWorkDir(), $this->getScmRemoteRepository(), $this->getScmConnectorType(), $this->getScmCheckChangesTimeout(), $this->getDateCheckedForChanges(), $specialTasks, $this->getOptionReleasePackage(), $this->getScmEnvVars()); if ($this->_id === null) { if (!($id = Database::insert($sql, $val)) || !is_numeric($id)) { Database::rollbackTransaction(); SystemEvent::raise(SystemEvent::ERROR, "Problems saving project to db.", __METHOD__); return false; } $this->setId($id); } else { if (!Database::execute($sql, $val)) { Database::rollbackTransaction(); SystemEvent::raise(SystemEvent::ERROR, "Problems saving project to db.", __METHOD__); return false; } } // The project users Project_User::deleteByProject($this); // Reset it foreach ($this->_users as $projectUser) { if (!$projectUser->save(true)) { Database::rollbackTransaction(); SystemEvent::raise(SystemEvent::ERROR, "Problems saving project to db.", __METHOD__); return false; } } if (!Database::endTransaction()) { SystemEvent::raise(SystemEvent::ERROR, "Something occurred while finishing transaction. The project might not have been saved. [ID={$this->getId()}]", __METHOD__); return false; } #if DEBUG SystemEvent::raise(SystemEvent::DEBUG, "Saved project. [PID={$this->getId()}] [TITLE={$this->getTitle()}]", __METHOD__); #endif $this->resetSignature(); return true; }
} // Create the account if ($uniID) { $pass = Database::query("INSERT INTO users_handles (handle, uni_id) VALUES (?, ?)", array($_POST['handle'], $uniID)); if (Database::endTransaction($pass)) { // Create the ProfilePic for this Account $packet = array("uni_id" => $uniID, "title" => $_POST['display_name']); $response = API_Connect::to("profile_picture", "SetDefaultPic", $packet); // Reset Values $_POST['handle'] = ""; $_POST['display_name'] = ""; $_POST['email'] = ""; $_POST['password'] = ""; } } else { Database::endTransaction(false); Alert::error("Process Error", "An error has occurred while processing this registration.", 1); } } } else { $_POST['email'] = isset($_POST['email']) ? Sanitize::email($_POST['email']) : ""; $_POST['password'] = isset($_POST['password']) ? Sanitize::safeword($_POST['password']) : ""; $_POST['handle'] = isset($_POST['handle']) ? Sanitize::variable($_POST['handle']) : ""; $_POST['display_name'] = isset($_POST['display_name']) ? Sanitize::safeword($_POST['display_name'], ' ') : ""; } // Run Header require SYS_PATH . "/controller/includes/admin_header.php"; // Display the Editing Form echo ' <h3>Add a New User</h3> <form class="uniform" action="/admin/AppAccount/Add User" method="post">' . Form::prepare("add-user-uni6") . '