Esempio n. 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();
     }
 }
Esempio n. 2
0
 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;
 }
Esempio n. 3
0
 protected function do_add($data)
 {
     if (!isset($data['set']) || !is_array($data['set'])) {
         return array('success' => false);
     }
     if (!empty($data['start'])) {
         $utc = $data['utc'] + 240;
         $start = date('Y-m-d G:i:s', strtotime($data['start']) + $utc * 60);
     } else {
         $start = '';
     }
     $sets = array();
     foreach ($data['set'] as $set) {
         if (preg_match('/[^-\\d\\.a-z]/ui', $set)) {
             continue;
         }
         $set = Database::get_full_row('set', 'id = ?', $set);
         if (empty($set)) {
             continue;
         }
         $sets[] = $set;
         if (!$set['grabbed']) {
             Grabber::get_set($set['id']);
         }
     }
     Database::begin();
     Database::insert('game', array('id_user' => $this->user, 'pick_time' => isset($data['pick_time']) ? $data['pick_time'] : 0, 'pause_time' => isset($data['pause_time']) ? $data['pause_time'] : 0, 'type' => isset($data['type']) ? $data['type'] : 1, 'start' => $start));
     $id_game = Database::last_id();
     $order = 0;
     foreach ($sets as $set) {
         Database::insert('game_set', array('id_game' => $id_game, 'order' => ++$order, 'id_set' => $set['id']));
     }
     Database::commit();
     return array('success' => true);
 }
 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;
 }
Esempio n. 5
0
    public function delete_unused_urls()
    {
        Database::begin();
        try {
            Database::sql('DELETE FROM post_link WHERE
				post_id NOT IN (SELECT id FROM post)');
            Database::sql('DELETE FROM post_update_link WHERE
				update_id NOT IN (SELECT id FROM post_update)');
            Database::sql('DELETE FROM post_link_url WHERE
				link_id NOT IN (SELECT id FROM post_link)');
            Database::sql('DELETE FROM post_update_link_url WHERE
				link_id NOT IN (SELECT id FROM post_update_link)');
            Database::sql('DELETE FROM post_url WHERE
				id NOT IN (SELECT url_id FROM post_link_url) AND
				id NOT IN (SELECT url_id FROM post_update_link_url)');
            $count = Database::count_affected();
            if ($count > self::MAX_LINK_DELETIONS) {
                Database::rollback();
                throw new Error_Cron('Too many post urls pending for deletion');
            }
            Database::commit();
        } catch (PDOException $e) {
            Database::rollback();
            throw new Error_Cron('Error with database, while deleting post urls');
        }
    }
Esempio n. 6
0
 /**
  * Apply a SQL source file to the database as part of running an installation step.
  *
  * @param string $sourceFileMethod
  * @param string $stepName
  * @param bool $archiveTableMustNotExist
  * @return Status
  */
 private function stepApplySourceFile($sourceFileMethod, $stepName, $archiveTableMustNotExist = false)
 {
     $status = $this->getConnection();
     if (!$status->isOK()) {
         return $status;
     }
     $this->db->selectDB($this->getVar('wgDBname'));
     if ($archiveTableMustNotExist && $this->db->tableExists('archive', __METHOD__)) {
         $status->warning("config-{$stepName}-tables-exist");
         $this->enableLB();
         return $status;
     }
     $this->db->setFlag(DBO_DDLMODE);
     // For Oracle's handling of schema files
     $this->db->begin(__METHOD__);
     $error = $this->db->sourceFile(call_user_func([$this, $sourceFileMethod], $this->db));
     if ($error !== true) {
         $this->db->reportQueryError($error, 0, '', __METHOD__);
         $this->db->rollback(__METHOD__);
         $status->fatal("config-{$stepName}-tables-failed", $error);
     } else {
         $this->db->commit(__METHOD__);
     }
     // Resume normal operations
     if ($status->isOK()) {
         $this->enableLB();
     }
     return $status;
 }
Esempio n. 7
0
 public function execute()
 {
     $dbh =& Database::connection();
     $this->result = $dbh->prepare($this->__toString());
     $this->result->execute();
     Database::commit();
     $dbh = null;
 }
Esempio n. 8
0
/**
 * 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();
}
Esempio n. 9
0
function shutdown()
{
    if (Database::hasBeenUsed()) {
        Database::commit();
    }
    // Jobs must not write to database!
    $queue = JobQueue::getInstance();
    $jobs = $queue->executeJobs();
    gfDebug("Request ended.\n");
}
 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");
     }
 }
Esempio n. 11
0
 public function setUp()
 {
     parent::setUp();
     LudoDBRegistry::set('FILE_UPLOAD_PATH', '/tmp/');
     $mv = new MetadataValue();
     $mv->drop()->yesImSure();
     $m = new Move();
     $m->drop()->yesImSure();
     $g = new Game();
     $g->drop()->yesImSure();
     $g->createTable();
     $m->createTable();
     $mv->createTable();
     $db = new Database(1);
     if (!$db->getId()) {
         $db->setTitle('My database');
         $db->commit();
     }
 }
Esempio n. 12
0
 public function start($users)
 {
     // Уже запущен
     if ($this->get('state') != 0) {
         return false;
     }
     $users = array_filter(explode(',', $users));
     $users[] = $this->get('id_user');
     $users = array_unique($users);
     shuffle($users);
     Database::begin();
     try {
         $this->create_data($users);
     } catch (Error $e) {
         Database::rollback();
         return false;
     }
     Database::commit();
     return true;
 }
Esempio n. 13
0
 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;
 }
Esempio n. 14
0
 public function main()
 {
     Database::begin();
     try {
         $data = $this->reader->get_data();
         foreach ($data as $key => $value) {
             if (method_exists($this, $key)) {
                 $this->{$key}($data);
             }
         }
         if (!empty($data['edit']) && !array_key_exists($data['edit'], $data) && method_exists($this, $data['edit'])) {
             $function = $data['edit'];
             $this->{$function}($data);
         }
         $this->save_changes();
         Database::commit();
     } catch (PDOException $e) {
         Database::rollback();
     }
 }
Esempio n. 15
0
 /**
  * @brief this function is intended to test this class
  */
 static function test_me($pCase = '')
 {
     if ($pCase == '') {
         echo Acc_Reconciliation::$javascript;
         html_page_start();
         $cn = new Database(dossier::id());
         $_SESSION['g_user'] = '******';
         $_SESSION['g_pass'] = '******';
         $id = isset($_REQUEST['p_jrn']) ? $_REQUEST['p_jrn'] : -1;
         $a = new Acc_Ledger($cn, $id);
         $a->with_concerned = true;
         // Vide
         echo '<FORM method="post">';
         echo $a->select_ledger()->input();
         echo HtmlInput::submit('go', 'Test it');
         echo '</form>';
         if (isset($_POST['go'])) {
             echo "Ok ";
             echo '<form method="post">';
             echo $a->show_form();
             echo HtmlInput::submit('post_id', 'Try me');
             echo '</form>';
             // Show the predef operation
             // Don't forget the p_jrn
             echo '<form>';
             echo dossier::hidden();
             echo '<input type="hidden" value="' . $id . '" name="p_jrn">';
             $op = new Pre_operation($cn);
             $op->p_jrn = $id;
             $op->od_direct = 't';
             if ($op->count() != 0) {
                 echo HtmlInput::submit('use_opd', 'Utilisez une opération pr&eacute;d&eacute;finie', "", "smallbutton");
                 echo $op->show_button();
             }
             echo '</form>';
             exit('test_me');
         }
         if (isset($_POST['post_id'])) {
             echo '<form method="post">';
             echo $a->show_form($_POST, 1);
             echo HtmlInput::button('add', 'Ajout d\'une ligne', 'onClick="quick_writing_add_row()"');
             echo HtmlInput::submit('save_it', _("Sauver"));
             echo '</form>';
             exit('test_me');
         }
         if (isset($_POST['save_it'])) {
             print 'saving';
             $array = $_POST;
             $array['save_opd'] = 1;
             try {
                 $a->save($array);
             } catch (Exception $e) {
                 alert($e->getMessage());
                 echo '<form method="post">';
                 echo $a->show_form($_POST);
                 echo HtmlInput::submit('post_id', 'Try me');
                 echo '</form>';
             }
             return;
         }
         // The GET at the end because automatically repost when you don't
         // specify the url in the METHOD field
         if (isset($_GET['use_opd'])) {
             $op = new Pre_op_advanced($cn);
             $op->set_od_id($_REQUEST['pre_def']);
             //$op->p_jrn=$id;
             $p_post = $op->compute_array();
             echo '<FORM method="post">';
             echo $a->show_form($p_post);
             echo HtmlInput::submit('post_id', 'Use predefined operation');
             echo '</form>';
             return;
         }
     }
     // if case = ''
     ///////////////////////////////////////////////////////////////////////////
     // search
     if ($pCase == 'search') {
         html_page_start();
         $cn = new Database(dossier::id());
         $ledger = new Acc_Ledger($cn, 0);
         $_SESSION['g_user'] = '******';
         $_SESSION['g_pass'] = '******';
         echo $ledger->search_form('ALL');
     }
     ///////////////////////////////////////////////////////////////////////////
     // reverse
     // Give yourself the var and check in your tables
     ///////////////////////////////////////////////////////////////////////////
     if ($pCase == 'reverse') {
         $cn = new Database(dossier::id());
         $jr_internal = 'OD-01-272';
         try {
             $cn->start();
             $jrn_def_id = $cn->get_value('select jr_def_id from jrn where jr_internal=$1', array($jr_internal));
             $ledger = new Acc_Ledger($cn, $jrn_def_id);
             $ledger->jr_id = $cn->get_value('select jr_id from jrn where jr_internal=$1', array($jr_internal));
             echo "Ouvrez le fichier " . __FILE__ . " à la ligne " . __LINE__ . " pour changer jr_internal et vérifier le résultat de l'extourne";
             $ledger->reverse('01.07.2010');
         } catch (Exception $e) {
             $cn->rollback();
             var_dump($e);
         }
         $cn->commit();
     }
 }
Esempio n. 16
0
 public function updateStatusEvent($estado, $evento)
 {
     $db = new Database();
     $q = "update invitado set asistencia = {$estado} where id = {$this->id} and idE = {$evento}";
     $r = $db->query($q);
     $db->commit();
     $db->close();
     return $r;
 }
Esempio n. 17
0
function insert_defaults()
{
    // {{{
    try {
        $db = new Database();
        $db->execute("INSERT INTO users(name, pass, joindate, class) VALUES(:name, :pass, now(), :class)", array("name" => 'Anonymous', "pass" => null, "class" => 'anonymous'));
        $db->execute("INSERT INTO config(name, value) VALUES(:name, :value)", array("name" => 'anon_id', "value" => $db->get_last_insert_id('users_id_seq')));
        if (check_im_version() > 0) {
            $db->execute("INSERT INTO config(name, value) VALUES(:name, :value)", array("name" => 'thumb_engine', "value" => 'convert'));
        }
        $db->commit();
    } catch (PDOException $e) {
        print <<<EOD
\t\t<div id="installer">
\t\t\t<h1>Shimmie Installer</h1>
\t\t\t<h3>Database Error:</h3>
\t\t\t<p>An error occured while trying to insert data into the database.</p>
\t\t\t<p>Please check and ensure that the database configuration options are all correct.</p>
\t\t\t<br/><br/>
\t\t</div>
EOD;
        exit($e->getMessage());
    } catch (Exception $e) {
        print <<<EOD
\t\t<div id="installer">
\t\t\t<h1>Shimmie Installer</h1>
\t\t\t<h3>Unknown Error:</h3>
\t\t\t<p>An unknown error occured while trying to insert data into the database.</p>
\t\t\t<p>Please check the server log files for more information.</p>
\t\t\t<br/><br/>
\t\t</div>
EOD;
        exit($e->getMessage());
    }
}
Esempio n. 18
0
    ctx_log_start("Loading themelets");
    foreach (_get_themelet_files(get_theme()) as $themelet) {
        require_once $themelet;
    }
    ctx_log_endok();
    _load_extensions();
    // start the page generation waterfall
    $page = class_exists("CustomPage") ? new CustomPage() : new Page();
    $user = _get_user();
    send_event(new InitExtEvent());
    if (!is_cli()) {
        // web request
        send_event(new PageRequestEvent(@$_GET["q"]));
        $page->display();
    } else {
        // command line request
        send_event(new CommandEvent($argv));
    }
    // saving cache data and profiling data to disk can happen later
    if (function_exists("fastcgi_finish_request")) {
        fastcgi_finish_request();
    }
    $database->commit();
    ctx_log_endok();
} catch (Exception $e) {
    if ($database) {
        $database->rollback();
    }
    _fatal_error($e);
    ctx_log_ender();
}
Esempio n. 19
0
        foreach ($a as $key) {
            $id = $key['ac_id'];
            $priv = sprintf("action%d", $id);
            if (!isset($_POST[$priv])) {
                $cn->exec_sql("delete from user_sec_act where ua_act_id=\$1", array($id));
                continue;
            }
            $count = $cn->get_value('select count(*) from user_sec_act where ua_login=$1 ' . ' and ua_act_id=$2', array($sec_User->login, $id));
            if ($_POST[$priv] == 1 && $count == 0) {
                $cn->exec_sql('insert into user_sec_act (ua_login,ua_act_id)' . ' values ($1,$2)', array($sec_User->login, $id));
            }
            if ($_POST[$priv] == 0) {
                $cn->exec_sql('delete from user_sec_act  where ua_login=$1 and ua_act_id=$2', array($sec_User->login, $id));
            }
        }
        $cn->commit();
    } catch (Exception $e) {
        echo_warning($e->getTraceAsString());
        $cn->rollback();
    }
}
//--------------------------------------------------------------------------------
// Action == View detail for users
//--------------------------------------------------------------------------------
if ($action == "view") {
    $l_Db = sprintf("dossier%d", $gDossier);
    $return = HtmlInput::button_anchor('Retour à la liste', '?&ac=' . $_REQUEST['ac'] . '&' . dossier::get(), 'retour');
    $repo = new Database();
    $User = new User($repo, $_GET['user_id']);
    $admin = 0;
    $access = $User->get_folder_access($gDossier);
Esempio n. 20
0
         echo '<span class="error">';
         echo _('le modele ') . domaine . 'mod' . $_POST["FMOD_ID"] . _(" doit être migré en unicode.");
         echo _('Pour le passer en unicode, faites-en un backup puis restaurez le fichier reçu') . '</span>';
         echo HtmlInput::button_anchor('Retour', 'admin_repo.php?action=dossier_mgt');
         return;
     }
 }
 /*
  * Insert new dossier with description
  */
 $desc = HtmlInput::default_value_post("DESCRIPTION", "");
 try {
     $repo->start();
     $Res = $repo->exec_sql("insert into ac_dossier(dos_name,dos_description)\n                           values (\$1,\$2)", array($dos, $desc));
     $l_id = $repo->get_current_seq('dossier_id');
     $repo->commit();
 } catch (Exception $e) {
     $msg = _("Desole la creation de ce dossier a echoue,\n la cause la plus probable est" . ' deux fois le même nom de dossier');
     alert($msg);
     $l_id = 0;
     $repo->rollback();
 }
 // If the id is not null, name successfully inserted
 // Database created
 if ($l_id != 0) {
     /*
      * We don't create  and empty database
      */
     if ($template != 0) {
         //--
         // setting the year
 protected function acceptRequest_rollback(Database $dbw, $user_id, $acd_id)
 {
     $dbw->begin();
     # DELETE the user in case something caused a COMMIT already somewhere.
     if ($user_id) {
         $dbw->delete('user', array('user_id' => $user_id), __METHOD__);
         $dbw->delete('user_groups', array('ug_user' => $user_id), __METHOD__);
     }
     # DELETE the new account_credentials row likewise.
     if ($acd_id) {
         $dbw->delete('account_credentials', array('acd_id' => $acd_id), __METHOD__);
     }
     $dbw->commit();
 }
Esempio n. 22
0
File: test.php Progetto: pta/oes
    header("Location: login.php");
}
$student = $_SESSION['student'];
$db = new Database(DB_HOST, DB_USER, DB_PASS);
$db->selectDatabase(DB_NAME);
if (isset($_GET['eid'])) {
    $eid = $_GET['eid'];
    $result = $db->query("select * from oes_Exam where ID = {$eid}");
    $exam = mysql_fetch_array($result);
    mysql_free_result($result);
    $test = $db->openTest($student, $eid);
    if ($test == null) {
        $db->begin();
        try {
            $test = $db->createTest($student, $eid, $exam['Subject'], $exam['NoQ']);
            $db->commit();
        } catch (Exception $e) {
            $db->rollback();
            ?>
					<head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"/></head>
					<center>Không thể tạo <b>Bài thi</b> mới.</center>
					<center><button onClick='history.back()'>Trở lại</button></center>
				<?php 
            echo $e->getMessage();
            return -1;
        }
    }
    $_SESSION['test'] = $test;
    header('Location: question.php');
    return;
}
Esempio n. 23
0
 private function getDatabaseId($request)
 {
     if (isset($request['importAsNew']) && $request['importAsNew']) {
         $db = new Database();
         $db->setTitle($request['newDatabase']);
         $db->setFolderId($request['folder']);
         $db->commit();
         return $db->getId();
     }
     return isset($request['database']) ? $request['database'] : $this->databaseId;
 }
Esempio n. 24
0
 public static function get_set($set, $transaction_started = false)
 {
     try {
         if (!$transaction_started) {
             Database::begin();
         }
         $count = 0;
         while ($count < 2000) {
             $doc = new DOMDocument();
             $url = 'http://www.mtg.ru/cards/search.phtml?Grp=' . $set . '&page=' . ++$count;
             @$doc->loadHTMLFile($url);
             $xpath = new DOMXpath($doc);
             $elements = $xpath->query(self::$queryCard);
             foreach ($elements as $element) {
                 $insert = array('mana_cost' => '');
                 //					$class = $element->getAttribute('class');
                 //					$class = explode(' ', $class);
                 //					$insert['color'] = str_replace('Color', '', $class[0]);
                 $rarity = $xpath->query(self::$queryRarity, $element)->item(0);
                 if (empty($rarity)) {
                     // Базовая земля или прочая хренька
                     $rarity = 0;
                 } else {
                     $rarity = self::$rarity[$rarity->getAttribute('alt')];
                 }
                 $name = $element->getElementsByTagName('h2')->item(0);
                 if (empty($name)) {
                     continue;
                 } else {
                     $name = $name->C14N();
                 }
                 preg_match('/.*?<h2>(.+?)(?:<\\/h2>\\s*$|\\/\\s*<wbr)/sui', $name, $name);
                 $insert['name'] = trim($name[1]);
                 $insert['image'] = $xpath->query(self::$queryImg, $element)->item(0)->getAttribute('src');
                 $insert['image'] = str_replace('/pictures', '', $insert['image']);
                 $insert['image'] = str_replace('_small/', '/', $insert['image']);
                 $manas = $xpath->query(self::$queryMana, $element);
                 $colors = '';
                 foreach ($manas as $mana) {
                     $mana_symbol = $mana->getAttribute('alt');
                     $insert['mana_cost'] .= '(' . $mana_symbol . ')';
                     $colors .= preg_replace('/[^WUBRG]/u', '', $mana_symbol);
                 }
                 $colors = array_filter(array_unique(str_split($colors)));
                 if (count($colors) > 1) {
                     $insert['color'] = 'M';
                 } elseif (!trim($insert['mana_cost'])) {
                     $insert['color'] = 'L';
                 } elseif (!empty($colors)) {
                     $insert['color'] = reset($colors);
                 } else {
                     $insert['color'] = 'A';
                 }
                 Database::insert('card', $insert);
                 Database::insert('set_card', array('id_set' => $set, 'id_card' => Database::last_id(), 'rarity' => $rarity));
             }
             $last = $xpath->query(self::$queryLast)->item(0);
             if (!strpos($last->C14N(), '|')) {
                 break;
             }
         }
         Database::update('set', array('grabbed' => 1), 'id = ?', $set);
         Database::commit();
     } catch (DOMException $e) {
         Database::rollback();
     }
 }
Esempio n. 25
0
 public function objectToDb()
 {
     $db = new Database();
     //TODO HACER CON TRANSACCIONES EN MYSQL
     $q = "insert into notificacion values({$this->id}, {$this->idJ1}, {$this->idG}, {$this->idE}, {$this->tn}, {$this->fecha})";
     $r = $db->query($q);
     $lastId = $db->last_id();
     $q = "insert into jugadorNotificacion values({$this->idJ2}, {$lastId}, {$this->visto})";
     $r = $db->query($q);
     $db->commit();
     $db->close();
 }
Esempio n. 26
0
 protected function do_set_deck($get)
 {
     if (!isset($get['c']) || !is_array($get['c']) || count($get['c']) < 40) {
         return array('success' => false, 'step' => 1);
     }
     Database::begin();
     try {
         $this->game->set_deck($this->user, $get['c']);
     } catch (Error $e) {
         Database::rollback();
     }
     Database::commit();
     return array('success' => true);
 }
Esempio n. 27
0
 /**
  * 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();
 }
Esempio n. 28
0
 public function update()
 {
     $db = new Database();
     $q = "update evento set nombre = '{$this->nombre}', tipo = {$this->tipo}, lugar = '{$this->lugar}', direccion = '{$this->direccion}', lat = {$this->lat}, lng = {$this->lng}, fecha = '{$this->fecha}', hora = '{$this->hora}', cantidad = {$this->cantidad} where id = {$this->id}";
     if ($db->query($q)) {
         $db->commit();
         return 1;
     } else {
         return 0;
     }
 }
Esempio n. 29
0
 /**
  *connect to folder and give to admin. the profile Admin(builtin)
  * @param int $p_id dossier::id()
  */
 static function synchro_admin($p_id)
 {
     // connect to target
     $cn = new Database($p_id);
     if (!$cn->exist_table("profile_menu")) {
         echo_warning("Dossier invalide");
         return;
     }
     // connect to repo
     $repo = new Database();
     $a_admin = $repo->get_array("select use_login from ac_users where\n\t\t\tuse_admin=1 and use_active=1");
     try {
         /**
          * synchro global
          */
         $cn->start();
         for ($i = 0; $i < count($a_admin); $i++) {
             $exist = $cn->get_value("select p_id from profile_user\n\t\t\t\t\twhere user_name=\$1", array($a_admin[$i]['use_login']));
             if ($exist == "") {
                 $cn->exec_sql("insert into profile_user(user_name,p_id) values(\$1,1)", array($a_admin[$i]['use_login']));
             }
         }
         $cn->commit();
     } catch (Exception $e) {
         echo_warning($e->getMessage());
         $cn->rollback();
     }
 }
Esempio n. 30
0
 /**
  * Shorthand for: Dao.getDb()->commit()
  * Be careful: this starts a transaction on the database! So all Daos using the same database will be in the same transaction
  */
 public function commit()
 {
     $this->db->commit();
 }