public static function mm_update() { // Get the RSS feed from Morning Mail $xml = simplexml_load_file('http://morningmail.rpi.edu/rss'); // Begin the transaction Database::beginTransaction(); $count = 0; foreach ($xml->channel->item as $item) { // Check for duplicates (no DB-agnostic way // to ignore duplicate errors) if (self::find($item->link)) { continue; } // Parse data and construct Article objects, // save them to the DB $date = date_create($item->pubDate); $a = new Article($item->title, strip_tags($item->description), $date->format('Y-m-d H:i:s'), $item->link); // Increment row count $count++; if (!$a->save()) { Database::rollBack(); return false; } } // Commit transaction Database::commit(); return $count; }
public function insert_comment($sid, $msg, $parent, $author_name, $author_email) { // Connect to database try { $handler = new Database(); // Insert comment to database if ($parent !== 'NULL') { $handler->beginTransaction(); // If comment has a parent begin transaction } $res = $handler->prepare('INSERT INTO `comment`(`sid`, `author_name`, `author_email`, `message`, `parent`) VALUES (:sid, :author_name, :author_email, :message, :parent)'); $res->execute(array(':sid' => $sid, ':author_name' => $author_name, ':author_email' => $author_email, ':message' => $msg, ':parent' => $parent)); if ($res->rowCount() !== 1) { return false; } // Get cid of last comment $cid = $handler->lastInsertId(); if ($parent !== 'NULL') { $res = $handler->prepare('UPDATE `comment` SET `children` = 1 WHERE `cid` = :parent'); $res->execute(array(':parent' => $parent)); $handler->commit(); // Commit only if both queries succeed } } catch (PDOException $e) { if ($parent !== 'NULL') { $handler->rollback(); } return false; } return $cid; }
/** * Package metadata updates. * * @param Database $db * @param array $updates * @return bool * @throws TypeError */ function processUpdates(Database $db, array $updates = []) : bool { $db->beginTransaction(); foreach ($updates as $update) { $db->update('airship_package_cache', ['skyport_metadata' => \json_encode($update['metadata'])], ['packagetype' => $update['package']['type'], 'supplier' => $update['package']['supplier'], 'name' => $update['package']['name']]); } return $db->commit(); }
public function evolve($buildingId) { //check building $result = $this->db->prepare("SELECT id FROM buildings WHERE id = ?"); $result->execute([$buildingId]); if ($result->rowCount() < 0) { throw new \Exception("Building with such id does not exists"); } //get resources $resources = $this->db->prepare("\n SELECT\n (SELECT gold FROM building_levels WHERE building_id = b.id AND level = (SELECT level FROM building_levels WHERE id = ub.level_id) + 1) AS gold,\n (SELECT food FROM building_levels WHERE building_id = b.id AND level = (SELECT level FROM building_levels WHERE id = ub.level_id) + 1) AS food\n FROM buildings as b\n INNER JOIN user_buildings AS ub ON ub.building_id = b.id\n INNER JOIN building_levels AS bl ON bl.id = ub.level_id\n WHERE ub.user_id = ? AND b.id = ?;\n "); $resources->execute([$this->user->getId(), $buildingId]); $resourcesData = $resources->fetch(); if ($this->getUser()->getFood() < $resourcesData['food'] || $this->getUser()->getGold() < $resourcesData['gold']) { throw new \Exception("No resources"); } //max level $maxLevel = $this->db->prepare("\n SELECT\n MAX(bl.level) AS level\n FROM building_levels bl\n WHERE bl.building_id = ?\n "); $maxLevel->execute([$buildingId]); $maxLevelData = $maxLevel->fetch(); //current level $currentLevel = $this->db->prepare("\n SELECT\n bl.level\n FROM user_buildings ub\n JOIN building_levels bl ON bl.id = ub.level_id\n WHERE ub.building_id = ?\n "); $currentLevel->execute([$buildingId]); $currentLevelData = $currentLevel->fetch(); if ($maxLevelData['level'] < $currentLevelData['level']) { throw new \Exception("Max level reached"); } $this->db->beginTransaction(); $resourceUpdate = $this->db->prepare("\n UPDATE\n users\n SET\n gold = gold - ?, food = food - ?\n WHERE id = ?\n "); $resourceUpdate->execute([$resourcesData['gold'], $resourcesData['food'], $this->getUser()->getId()]); if ($resourceUpdate->rowCount() > 0) { $levelUpdate = $this->db->prepare("\n UPDATE\n user_buildings ub\n SET\n ub.level_id = (SELECT bl.id FROM building_levels bl WHERE level = ? AND bl.building_id = ub.building_id)\n WHERE ub.user_id = ? AND ub.building_id = ?\n "); $levelUpdate->execute([$currentLevelData['level'] + 1, $this->getUser()->getId(), $buildingId]); if ($levelUpdate->rowCount() > 0) { $this->db->commit(); return true; } else { $this->db->rollBack(); throw new \Exception("Level up error"); } } else { throw new \Exception("Resource update error"); } }
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 save() { // Clear out current clusters, TRUNCATE is implicitly // commited so it ruins the transaction, thats why its // out here Database::query("TRUNCATE centers;"); // Initiate a large transaction to the DB Database::beginTransaction(); // Save every cluster to the DB foreach (self::$clusters as $cluster) { if (!$cluster->save()) { // Undo all changes to the DB Database::rollBack(); return false; } } // Commit the entire transaction Database::commit(); return true; }
<?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.'; } }
<?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();
/** * Save multiple preferences at once. * * @param Database $db * @param array $prefs * * @throws Exception when a passed preference is no instance of 'Preference'. */ public function savePreferences(Database $db, array $prefs) { $db->beginTransaction(); $updateStatement = $db->prepare("\n\t\t\t\tUPDATE " . TABLE_PLUGINS_SETTINGS . "\n\t\t\t\tSET value = :value\n\t\t\t\tWHERE `key` = :key AND package = :package\n\t\t\t"); $insertStatement = $db->prepare("\n\t\t\t\tINSERT INTO " . TABLE_PLUGINS_SETTINGS . "\n\t\t\t\t(package, `key`, value)\n\t\t\t\tVALUES\n\t\t\t\t(?, ?, ?)\n\t\t\t"); foreach ($prefs as $pref) { if (!$pref instanceof Preference) { $db->rollback(); throw new Exception("Passed preference is no instance of 'Preference'.", 41); } if ($pref instanceof PreferenceCategory) { continue; } $oldValue = $this->getPreferenceValue($db, $pref->getKey()); if (is_null($oldValue)) { $insertStatement->execute(array($this->package, $pref->getKey(), is_null($pref->getValue()) ? $pref->getDefaultValue() : $pref->getValue())); } else { $updateStatement->execute(array(is_null($pref->getValue()) ? $pref->getDefaultValue() : $pref->getValue(), $pref->getKey(), $this->package)); } } $db->commit(); }
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()); }
public function insertToDB() { try { $TimeStart = microtime(true); // to mesaure the time this method takes $database = new Database(); $database->beginTransaction(); $zip = $this->zip(); $cityName = $this->cityName(); $cityName = htmlentities($cityName, ENT_COMPAT, 'UTF-8'); $countryCode = $this->countryCode(); $title = $this->title(); $price = $this->price(); $photos = $this->photos(); $details = $this->details(); $ownerID = $this->ownerID(); $language = $this->language(); $currencyID = $this->currencyID(); $description = $this->description(); $paymentMethod = $this->paymentMethod(); $subCategorieID = $this->subCategorieID(); // make sure if the new spec is actually new or maybe it already exist in the database $database->query('SELECT id FROM locations WHERE LOWER(city_name) = :cityName LIMIT 1'); $database->bind(':cityName', strtolower($cityName)); $location_row = $database->single(); if ($location_row) { $locationID = $location_row["id"]; } else { $database->query('INSERT INTO locations (city_name, zip, country_code) VALUES (:city_name, :zip, :country_code)'); $database->bind(':city_name', $cityName); $database->bind(':zip', $zip); $database->bind(':country_code', $countryCode); if (!$database->execute()) { throw new Exception(Translate::string("save_advertisement.error_saving_location"), 1); } $locationID = $database->lastInsertId(); } $database->query('INSERT INTO products ( user_id, sub_cat_id, title, price, currency_id, location_id, payment_method_id, description, lang_id, date_created) VALUES (:user_id,:sub_cat_id,:title,:price,:currency_id,:location_id,:payment_method_id,:description,:lang_id,:date_created)'); $database->bind(':user_id', $ownerID); $database->bind(':sub_cat_id', $subCategorieID); $database->bind(':title', $title); $database->bind(':price', $price); $database->bind(':currency_id', $currencyID); $database->bind(':location_id', $locationID); $database->bind(':payment_method_id', $paymentMethod); $database->bind(':description', $description); $database->bind(':lang_id', $language); $database->bind(':date_created', date("Y-m-d")); if ($database->execute()) { $productID = $database->lastInsertId(); $this->setID($productID); } else { throw new Exception(Translate::string("save_advertisement.error_saving_advertisement"), 1); } if (count($details) > 0) { // =============================================================================================== // ================================= HANDELING THE EXTRA DETAILS ================================= // =============================================================================================== if (isset($details["detail-label"]) && isset($details["detail-info"])) { $this->handleExtras($details, "detail-label", "detail-info", $database, $subCategorieID, $productID); } if (isset($details["detail-checkbox-label"]) && isset($details["detail-checkbox-value"])) { $this->handleExtras($details, "detail-checkbox-label", "detail-checkbox-value", $database, $subCategorieID, $productID); } // ================================================================================================ // ================================= HANDELING THE NORMAL DETAILS ================================= // ================================================================================================ $extra_details = array("detail-label", "detail-info", "detail-checkbox-label", "detail-checkbox-value"); foreach ($details as $attribute_ID => $value) { // skip extra details if (in_array($attribute_ID, $extra_details)) { continue; } // increase the count $database->query('UPDATE attributes SET count = count+1 WHERE id = :id LIMIT 1'); $database->bind(':id', $attribute_ID); if (!$database->execute()) { throw new Exception("The Attribute does not exist", 1); } $this->insertSpecs($value, $productID, $attribute_ID, $database); } // end of foreach $details } // end of if details > 0 // ============================================================================================== // ================================= SAVING IMGAGES TO DATABASE ================================= // ============================================================================================== foreach ($photos as $image_name) { $photo_exploded = explode(".", $image_name); $img_type = end($photo_exploded); $dir = '../images/uploads/'; // check if file exists, if not then die file_exists($dir . "temp/" . $image_name) or die(Translate::string("save_advertisement.temp_file_missing")); // change the temp file permission so that chmod($dir . "temp/" . $image_name, 0777) or die(Translate::string("save_advertisement.temp_file_missing")); $image = new SimpleImage(); $image->load($dir . 'temp/' . $image_name); $image->resizeToWidth(900); $image->save($dir . 'large/' . $image_name); $image->resizeToWidth(580); $image->save($dir . 'medium/' . $image_name); $image->resizeToWidth(220); $image->save($dir . 'small/' . $image_name); $image->resizeToWidth(85); $image->save($dir . 'thumbnail/' . $image_name); // copy temp file to orig folder copy($dir . 'temp/' . $image_name, $dir . 'orig/' . $image_name) or die(Translate::string("save_advertisement.temp_file_missing")); // delete temp file unlink($dir . 'temp/' . $image_name) or die(Translate::string("save_advertisement.temp_file_deleting")); // insert photo reference to database $database->query('INSERT INTO product_images ( product_id, img_type, date_uploaded, uuid) VALUES (:product_id,:img_type,:date_uploaded,:uuid)'); $database->bind(':product_id', $productID); $database->bind(':img_type', $img_type); $database->bind(':date_uploaded', date("Y-m-d")); $database->bind(':uuid', $image_name); if (!$database->execute()) { throw new Exception(Translate::string("save_advertisement.error_saving_img"), 1); } } $Difference = round(microtime(true) - $TimeStart, 3) * 1000; // get the time this method took // echo $Difference." : milliseconds"; $database->endTransaction(); echo $productID; } catch (Exception $e) { echo 'Error2: ' . $e->getMessage(); } }
/** * Register account recovery attempt * * @param string $username * @param string $ip * @return bool */ public function registerAccountRecoveryAttempt(string $username, string $ip) : bool { $this->db->beginTransaction(); $this->db->insert('airship_failed_logins', ['action' => self::ACTION_RECOVER, 'occurred' => (new \DateTime())->format(\AIRSHIP_DATE_FORMAT), 'username' => $username, 'ipaddress' => $ip, 'subnet' => $this->getSubnet($ip)]); return $this->db->commit(); }
$ok = false; $msg = "Could not create avatars dir. Check your permissions."; SystemEvent::raise(CINTIENT_LOG_SEVERITY_ERROR, $msg, "Installer"); sendResponse($ok, $msg); } // // Backup a previous version database, if found, and if possible // if ($upgrade && !@copy($get['appWorkDir'] . 'cintient.sqlite', $get['appWorkDir'] . "cintient_{$dateMarker}.sqlite")) { $msg = "Could not backup your previous version database. Continuing the upgrade, nevertheless."; SystemEvent::raise(CINTIENT_LOG_SEVERITY_ERROR, $msg, "Installer"); } // // Force an exclusive database transaction // if (!Database::beginTransaction(Database::EXCLUSIVE_TRANSACTION)) { $ok = false; $msg = "Problems obtaining an exclusive lock on the database."; SystemEvent::raise(CINTIENT_LOG_SEVERITY_ERROR, $msg, "Installer"); sendResponse($ok, $msg); } // // Setup all objects // if (!User::install()) { $ok = false; $msg = "Could not setup User object."; SystemEvent::raise(CINTIENT_LOG_SEVERITY_ERROR, $msg, "Installer"); sendResponse($ok, $msg); } if (!Project::install()) {
/** * {@inheritdoc} */ public function begin() { $this->connection->beginTransaction(); }
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; }