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;
 }
Example #2
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 #3
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;
 }
Example #4
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');
        }
    }
Example #5
0
 protected function tearDown()
 {
     global $wgRequest, $wgSQLMode;
     $status = ob_get_status();
     if (isset($status['name']) && $status['name'] === 'MediaWikiTestCase::wfResetOutputBuffersBarrier') {
         ob_end_flush();
     }
     $this->called['tearDown'] = true;
     // Cleaning up temporary files
     foreach ($this->tmpFiles as $fileName) {
         if (is_file($fileName) || is_link($fileName)) {
             unlink($fileName);
         } elseif (is_dir($fileName)) {
             wfRecursiveRemoveDir($fileName);
         }
     }
     if ($this->needsDB() && $this->db) {
         // Clean up open transactions
         while ($this->db->trxLevel() > 0) {
             $this->db->rollback(__METHOD__, 'flush');
         }
         if ($this->db->getType() === 'mysql') {
             $this->db->query("SET sql_mode = " . $this->db->addQuotes($wgSQLMode));
         }
     }
     // Restore mw globals
     foreach ($this->mwGlobals as $key => $value) {
         $GLOBALS[$key] = $value;
     }
     $this->mwGlobals = [];
     $this->restoreLoggers();
     if (self::$serviceLocator && MediaWikiServices::getInstance() !== self::$serviceLocator) {
         MediaWikiServices::forceGlobalInstance(self::$serviceLocator);
     }
     // TODO: move global state into MediaWikiServices
     RequestContext::resetMain();
     if (session_id() !== '') {
         session_write_close();
         session_id('');
     }
     $wgRequest = new FauxRequest();
     MediaWiki\Session\SessionManager::resetCache();
     MediaWiki\Auth\AuthManager::resetCache();
     $phpErrorLevel = intval(ini_get('error_reporting'));
     if ($phpErrorLevel !== $this->phpErrorLevel) {
         ini_set('error_reporting', $this->phpErrorLevel);
         $oldHex = strtoupper(dechex($this->phpErrorLevel));
         $newHex = strtoupper(dechex($phpErrorLevel));
         $message = "PHP error_reporting setting was left dirty: " . "was 0x{$oldHex} before test, 0x{$newHex} after test!";
         $this->fail($message);
     }
     parent::tearDown();
 }
Example #6
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;
 }
Example #7
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();
     }
 }
Example #8
0
            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);
    $str = "Aucun accès";
    if ($access == 'R') {
        $str = ' Utilisateur normal';
Example #9
0
     }
 }
 /*
  * 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
         //--
         $year = sql_string($_POST['YEAR']);
         if (strlen($year) != 4 || isNumber($year) == 0 || $year > 2100 || $year < 2000 || $year != round($year, 0)) {
             echo "{$year}" . _(" est une année invalide");
             $Res = $repo->exec_sql("delete from ac_dossier where dos_id={$l_id}");
Example #10
0
 /**
  * Shorthand for: Dao.getDb()->rollback()
  * Be careful: this starts a transaction on the database! So all Daos using the same database will be in the same transaction
  */
 public function rollback()
 {
     $this->db->rollback();
 }
Example #11
0
 /**
  * Unit test for the class
  */
 static function test_me()
 {
     $cn = new Database(25);
     $cn->start();
     echo h2info('Test object vide');
     $obj = new Fiche_Attr($cn);
     var_dump($obj);
     echo h2info('Test object NON vide');
     $obj->set_parameter('j_id', 3);
     $obj->load();
     var_dump($obj);
     echo h2info('Update');
     $obj->set_parameter('j_qcode', 'NOUVEAU CODE');
     $obj->save();
     $obj->load();
     var_dump($obj);
     echo h2info('Insert');
     $obj->set_parameter('j_id', 0);
     $obj->save();
     $obj->load();
     var_dump($obj);
     echo h2info('Delete');
     $obj->delete();
     echo $obj->load() == 0 ? 'Trouve' : 'non trouve';
     var_dump($obj);
     $cn->rollback();
 }
Example #12
0
 /**
  * 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();
 }
Example #13
0
File: test.php Project: pta/oes
$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;
}
?>
<head>
Example #14
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);
 }
Example #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();
     }
 }
Example #16
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();
}
Example #17
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();
     }
 }
Example #18
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();
     }
 }
Example #19
-15
 public function __construct($sql, $params, Connection $connection, Database $db)
 {
     try {
         $stmt = $connection->prepare($sql);
         $stmt->execute($params);
         $this->statement = $stmt;
         $this->connection = $connection;
     } catch (\PDOException $e) {
         // 服务端断开时重连一次
         if ($e->errorInfo[1] == 2006 || $e->errorInfo[1] == 2013) {
             $master_or_slave = $connection->getMasterOrSlave();
             $db->closeConnection($master_or_slave, $connection->getConnectionIndex());
             $connection = $db->getConnection($master_or_slave == Connection::MASTER_CONNECTION);
             try {
                 $stmt = $connection->prepare($sql);
                 $stmt->execute($params);
                 $this->statement = $stmt;
                 $this->connection = $connection;
             } catch (\PDOException $ex) {
                 $db->rollback();
                 throw $ex;
             }
         } else {
             $db->rollback();
             throw $e;
         }
     }
 }