/** * displays the topics on a forums * @return [type] [description] */ public function action_list() { //in case performing a search if (strlen($search = core::get('search')) >= 3) { return $this->action_search($search); } $this->template->styles = array('css/forums.css' => 'screen'); $this->template->scripts['footer'][] = 'js/forums.js'; $forum = new Model_Forum(); $forum->where('seoname', '=', $this->request->param('forum', NULL))->cached()->limit(1)->find(); if ($forum->loaded()) { //template header $this->template->title = $forum->name . ' - ' . __('Forum'); $this->template->meta_description = $forum->description; Breadcrumbs::add(Breadcrumb::factory()->set_title($forum->name)); //count all topics $count = DB::select(array(DB::expr('COUNT("id_post")'), 'count'))->from(array('posts', 'p'))->where('id_post_parent', 'IS', NULL)->where('id_forum', '=', $forum->id_forum)->cached()->execute(); $count = array_keys($count->as_array('count')); $pagination = Pagination::factory(array('view' => 'pagination', 'total_items' => isset($count[0]) ? $count[0] : 0))->route_params(array('controller' => $this->request->controller(), 'action' => $this->request->action(), 'forum' => $this->request->param('forum'))); $pagination->title($this->template->title); //getting all the topic for the forum $topics = DB::select('p.*')->select(array(DB::select(DB::expr('COUNT("id_post")'))->from(array('posts', 'pc'))->where('pc.id_post_parent', '=', DB::expr(Database::instance('default')->table_prefix() . 'p.id_post'))->where('pc.id_forum', '=', $forum->id_forum)->where('pc.status', '=', Model_Post::STATUS_ACTIVE)->group_by('pc.id_post_parent'), 'count_replies'))->select(array(DB::select('ps.created')->from(array('posts', 'ps'))->where('ps.id_post', '=', DB::expr(Database::instance('default')->table_prefix() . 'p.id_post'))->or_where('ps.id_post_parent', '=', DB::expr(Database::instance('default')->table_prefix() . 'p.id_post'))->where('ps.id_forum', '=', $forum->id_forum)->where('ps.status', '=', Model_Post::STATUS_ACTIVE)->order_by('ps.created', 'DESC')->limit(1), 'last_message'))->from(array('posts', 'p'))->where('id_post_parent', 'IS', NULL)->where('id_forum', '=', $forum->id_forum)->where('status', '=', Model_Post::STATUS_ACTIVE)->order_by('last_message', 'DESC')->limit($pagination->items_per_page)->offset($pagination->offset)->as_object()->execute(); $pagination = $pagination->render(); $this->template->bind('content', $content); $this->template->content = View::factory('pages/forum/list', array('topics' => $topics, 'forum' => $forum, 'pagination' => $pagination)); } else { //throw 404 throw HTTP_Exception::factory(404, __('Page not found')); } }
/** * Compile the SQL partial for a JOIN statement and return it. * * @param mixed $db Database instance or name of instance * * @return string */ public function compile($db = null) { if (!is_object($db)) { // Get the database instance $db = Database::instance($db); } if ($this->_type) { $sql = strtoupper($this->_type) . ' JOIN'; } else { $sql = 'JOIN'; } // Quote the table name that is being joined $sql .= ' ' . $db->quote_table($this->_table); if (!empty($this->_using)) { // Quote and concat the columns $sql .= ' USING (' . implode(', ', array_map([$db, 'quote_column'], $this->_using)) . ')'; } else { $conditions = []; foreach ($this->_on as $condition) { // Split the condition list($c1, $op, $c2) = $condition; if ($op) { // Make the operator uppercase and spaced $op = ' ' . strtoupper($op); } // Quote each of the columns used for the condition $conditions[] = $db->quote_column($c1) . $op . ' ' . $db->quote_column($c2); } // Concat the conditions "... AND ..." $sql .= ' ON (' . implode(' AND ', $conditions) . ')'; } return $sql; }
/** * Task to run pending migrations * * @return null */ protected function _execute(array $params) { $migrations = new MigrationManager(); Database::$default = $params['db']; $this->db = Database::instance(); $db_config = Kohana::$config->load('database')->{$params['db']}; if (!ORM::factory('Migration')->is_installed()) { /** * Get platform from database config */ $platform = strtolower($db_config['type']); if ('mysqli' == $platform) { $platform = 'mysql'; } /** * Get SQL from file for selected platform */ $file = realpath(substr(__DIR__, 0, strlen(__DIR__) - strlen('classes/Task/Db')) . 'sql/' . $platform . '.sql'); $handle = fopen($file, 'rb'); $sql_create = fread($handle, filesize($file)); $this->db->query(0, $sql_create); $msg = Minion_CLI::color("-----------------------------\n", 'green'); $msg .= Minion_CLI::color("| Migration table create!!! |\n", 'green'); $msg .= Minion_CLI::color("-----------------------------\n", 'green'); Minion_CLI::write($msg); } $migrations->migrate($params['db'], $params['step']); }
/** * 改变状态 */ function do_active($id) { //权限验证 role::check('user_charge'); if (!$id) { remind::set(Kohana::lang('o_global.bad_request'), 'user/user_charge'); } $db = Database::instance(); $data = array_shift($db->query('SELECT * FROM user_charge_order WHERE id=' . $id)->result_array(false)); if ($data['id'] <= 0 || $data['status'] > 0) { remind::set(Kohana::lang('o_global.bad_request'), 'user/user_charge'); } $logodata = array(); $logodata['manager_id'] = $this->manager_id; $logodata['ip'] = tool::get_str_ip(); $logodata['user_log_type'] = 27; $logodata['method'] = __CLASS__ . '::' . __METHOD__ . '()'; $logodata['memo'] = "充值订单号:" . $data['order_num'] . ", 购买拍点数:" . $data['price'] . ", 充值金额:" . $data['money']; $sql = "UPDATE user_charge_order SET status=1 WHERE id='" . $id . "' "; if ($db->query($sql)) { //充值用户Money $sql_reward = "UPDATE users \r\n SET user_money = user_money+" . $data['price'] . "\r\n WHERE id='" . $data['user_id'] . "'\r\n "; $db->query($sql_reward); //操作log ulog::add($logodata); remind::set(Kohana::lang('o_global.update_success'), 'user/user_charge', 'success'); } else { //操作log ulog::add($logodata, 1); remind::set(Kohana::lang('o_global.update_error'), 'user/user_charge', 'error'); } }
public function execute($db = NULL, $as_object = NULL, $object_params = NULL) { if ($db === NULL and $this->meta()) { $db = Database::instance($this->meta()->db()); } return parent::execute($db, $as_object, $object_params); }
public static function getInstance() { if (!self::$instance) { self::$instance = new Database(); } return self::$instance; }
public static function connect($dbDetails = array()) { if (self::$instance == NULL) { self::$instance = new Database($dbDetails); } return self::$instance; }
private function _dump_database() { // We now have a clean install with just the packages that we want. Make sure that the // database is clean too. $i = 1; foreach (array("blocks_dashboard_sidebar", "blocks_dashboard_center") as $key) { $blocks = array(); foreach (unserialize(module::get_var("gallery", $key)) as $rnd => $value) { $blocks[++$i] = $value; } module::set_var("gallery", $key, serialize($blocks)); } $db = Database::instance(); $db->query("TRUNCATE {sessions}"); $db->query("TRUNCATE {logs}"); $db->query("DELETE FROM {vars} WHERE `module_name` = 'core' AND `name` = '_cache'"); $db->update("users", array("password" => ""), array("id" => 1)); $db->update("users", array("password" => ""), array("id" => 2)); $dbconfig = Kohana::config('database.default'); $conn = $dbconfig["connection"]; $pass = $conn["pass"] ? "-p{$conn['pass']}" : ""; $sql_file = DOCROOT . "installer/install.sql"; if (!is_writable($sql_file)) { print "{$sql_file} is not writeable"; return; } $command = "mysqldump --compact --skip-extended-insert --add-drop-table -h{$conn['host']} " . "-u{$conn['user']} {$pass} {$conn['database']} > {$sql_file}"; exec($command, $output, $status); if ($status) { print "<pre>"; print "{$command}\n"; print "Failed to dump database\n"; print implode("\n", $output); return; } // Post-process the sql file $buf = ""; $root = ORM::factory("item", 1); $root_created_timestamp = $root->created; $root_updated_timestamp = $root->updated; $table_name = ""; foreach (file($sql_file) as $line) { // Prefix tables $line = preg_replace("/(CREATE TABLE|IF EXISTS|INSERT INTO) `{$dbconfig['table_prefix']}(\\w+)`/", "\\1 {\\2}", $line); if (preg_match("/CREATE TABLE {(\\w+)}/", $line, $matches)) { $table_name = $matches[1]; } // Normalize dates $line = preg_replace("/,{$root_created_timestamp},/", ",UNIX_TIMESTAMP(),", $line); $line = preg_replace("/,{$root_updated_timestamp},/", ",UNIX_TIMESTAMP(),", $line); // Remove ENGINE= specifications execpt for search records, it always needs to be MyISAM if ($table_name != "search_records") { $line = preg_replace("/ENGINE=\\S+ /", "", $line); } $buf .= $line; } $fd = fopen($sql_file, "wb"); fwrite($fd, $buf); fclose($fd); }
static function stats() { $remaining = Database::instance()->select("items.id")->from("items")->join("search_records", "items.id", "search_records.item_id", "left")->open_paren()->where("search_records.item_id", null)->orwhere("search_records.dirty", 1)->close_paren()->get()->count(); $total = ORM::factory("item")->count_all(); $percent = round(100 * ($total - $remaining) / $total); return array($remaining, $total, $percent); }
public function compile($db = NULL) { if ($this->context_model() and $meta = Jam::meta(Jam_Query_Builder::aliased_model($this->context_model()))) { $db = Database::instance($meta->db()); } $original_on = $this->_on; $original_using = $this->_using; $original_table = $this->_table; if (!empty($this->_on)) { foreach ($this->_on as &$condition) { $condition[0] = Jam_Query_Builder::resolve_attribute_name($condition[0], $this->model() ? $this->model() : $this->_table); $condition[2] = Jam_Query_Builder::resolve_attribute_name($condition[2], $this->context_model()); } } $this->_table = Jam_Query_Builder::resolve_table_alias($this->_table); if (!empty($this->_using)) { foreach ($this->_using as &$column) { $column = Jam_Query_Builder::resolve_attribute_name($column, $this->meta()); } } $additional_joins = ''; foreach ($this->_joins as $join) { $additional_joins .= ' ' . $join->compile($db); } $compiled = parent::compile($db) . $additional_joins; $this->_on = $original_on; $this->_using = $original_using; $this->_table = $original_table; return $compiled; }
/** * Construct load data * * @param Int $id */ public function __construct($site_id) { $this->db = Database::instance('old'); $sql = "SELECT `categories`.* FROM (`categories`) WHERE `site_id` = {$site_id} AND `virtual` = 0 AND `level_depth` != 1 ORDER BY `categories`.`id` ASC"; $categorys = $this->db->query($sql); /* $categorys = ORM::factory('category') ->where('site_id',$site_id) ->where('virtual',0) ->find_all(); echo $this->db->last_query(); exit; */ foreach ($categorys as $keyc => $_category) { $category_temp = array(); $category_temp['id'] = $_category->category_id; $category_temp['site_id'] = $_category->site_id; $category_temp['name'] = $_category->name; $category_temp['create_timestamp'] = time(); $category_temp['update_timestamp'] = time(); $category_temp['attribute_ids'] = $this->classify_attribute($site_id, $_category->category_id); $category_temp['feature_ids'] = $this->classify_feature($site_id, $_category->category_id); $category_temp['brand_ids'] = $this->classify_brand($site_id, $_category->category_id); $this->data[$keyc] = $category_temp; } $this->end = count($this->data); }
/** * Compile the SQL query and return it. * * @param mixed $db Database instance or name of instance * @return string */ public function compile($db = NULL) { if (!is_object($db)) { // Get the database instance $db = Database::instance($db); } // Start an update query $query = 'UPDATE ' . $db->quote_table($this->_table); // Add the columns to update $query .= ' SET ' . $this->_compile_set($db, $this->_set); if (!empty($this->_where)) { // Add selection conditions $query .= ' WHERE ' . $this->_compile_conditions($db, $this->_where); } if (!empty($this->_order_by)) { // Add sorting $query .= ' ' . $this->_compile_order_by($db, $this->_order_by); } if ($this->_limit !== NULL) { // Add limiting $query .= ' LIMIT ' . $this->_limit; } $this->_sql = $query; return parent::compile($db); }
static function install() { $db = Database::instance(); $db->query("CREATE TABLE IF NOT EXISTS {g2_maps} (\n `id` int(9) NOT NULL auto_increment,\n `g2_id` int(9) NOT NULL,\n `g3_id` int(9) NOT NULL,\n PRIMARY KEY (`id`),\n KEY (`g2_id`))\n DEFAULT CHARSET=utf8;"); module::set_version("g2_import", 1); mkdir(VARPATH . "modules/g2_import"); }
public function execute($db = 'default') { if (!is_object($db)) { // Get the database instance $db = Database::instance($db); } // Import the SQL locally $sql = $this->_sql; if (!empty($this->_values)) { // Quote all of the values $values = array_map(array($db, 'quote'), $this->_values); // Replace the values in the SQL $sql = strtr($sql, $values); } if ($this->profile === TRUE) { // Start profiling this query $token = Profiler::start('database (' . (string) $db . ')', $sql); } // Load the result $result = $db->query($this->_type, $sql); if (isset($token)) { // Stop profiling Profiler::stop($token); } return $result; }
static function uninstall() { // Delete the GPS table before uninstalling. $db = Database::instance(); $db->query("DROP TABLE IF EXISTS {tags_gpses};"); module::delete("tagsmap"); }
/** * getInstance * * @param object $error * * @return object */ public static function getInstance($error) { if (!isset(self::$instance)) { self::$instance = new Database($error); } return self::$instance; }
public function activate($validation_key) { if (!IN_PRODUCTION) { $profiler = new Profiler(); } // TODO: Figure out where to store magic constants. if ($validation_key && strlen($validation_key) == 32) { $db = Database::instance(); $email_users_set = $db->select('email_users.email', 'email_users.is_validated', 'user_details.public_api_key', 'user_details.private_api_key')->from('email_users')->join('user_details', array('email_users.user_id' => 'user_details.id'))->where('validation_key', $validation_key)->limit(1)->get(); if (count($email_users_set)) { $email_user_row = null; foreach ($email_users_set as $row) { $email_user_row = $row; break; } if (!$email_user_row->is_validated) { $db->from('email_users')->set('is_validated', '1')->set('validation_key', 'NULL', $disable_escaping = true)->where('email', $email_user_row->email)->update(); } if ($email_user_row->public_api_key) { $this->render_activation_succeeded_view(Kohana::lang('account_messages.activation.success_with_api_keys')); } else { $this->render_activation_succeeded_view(Kohana::lang('account_messages.activation.success_without_api_keys')); } } else { $this->render_activation_failed_view(Kohana::lang('account_messages.activation.key_not_found')); } } else { $this->render_activation_failed_view(Kohana::lang('account_messages.activation.key_not_found')); } }
static function uninstall() { $db = Database::instance(); $sql = "SELECT `item_id` FROM {comments}"; module::event("item_related_update_batch", $sql); $db->query("DROP TABLE IF EXISTS {comments};"); }
private function _dump_database() { // We now have a clean install with just the packages that we want. Make sure that the // database is clean too. $i = 1; foreach (array("dashboard_sidebar", "dashboard_center", "site_sidebar") as $key) { $blocks = array(); foreach (unserialize(module::get_var("gallery", "blocks_{$key}")) as $rnd => $value) { $blocks[++$i] = $value; } module::set_var("gallery", "blocks_{$key}", serialize($blocks)); } Database::instance()->query("TRUNCATE {caches}"); Database::instance()->query("TRUNCATE {sessions}"); Database::instance()->query("TRUNCATE {logs}"); db::build()->update("users")->set(array("password" => ""))->where("id", "in", array(1, 2))->execute(); $dbconfig = Kohana::config('database.default'); $conn = $dbconfig["connection"]; $sql_file = DOCROOT . "installer/install.sql"; if (!is_writable($sql_file)) { print "{$sql_file} is not writeable"; return; } $command = sprintf("mysqldump --compact --skip-extended-insert --add-drop-table %s %s %s %s > {$sql_file}", escapeshellarg("-h{$conn['host']}"), escapeshellarg("-u{$conn['user']}"), $conn['pass'] ? escapeshellarg("-p{$conn['pass']}") : "", escapeshellarg($conn['database'])); exec($command, $output, $status); if ($status) { print "<pre>"; print "{$command}\n"; print "Failed to dump database\n"; print implode("\n", $output); return; } // Post-process the sql file $buf = ""; $root = ORM::factory("item", 1); $root_created_timestamp = $root->created; $root_updated_timestamp = $root->updated; $table_name = ""; foreach (file($sql_file) as $line) { // Prefix tables $line = preg_replace("/(CREATE TABLE|IF EXISTS|INSERT INTO) `{$dbconfig['table_prefix']}(\\w+)`/", "\\1 {\\2}", $line); if (preg_match("/CREATE TABLE {(\\w+)}/", $line, $matches)) { $table_name = $matches[1]; } // Normalize dates $line = preg_replace("/,{$root_created_timestamp},/", ",UNIX_TIMESTAMP(),", $line); $line = preg_replace("/,{$root_updated_timestamp},/", ",UNIX_TIMESTAMP(),", $line); // Remove ENGINE= specifications execpt for search records, it always needs to be MyISAM if ($table_name != "search_records") { $line = preg_replace("/ENGINE=\\S+ /", "", $line); } // Null out ids in the vars table since it's an auto_increment table and this will result in // more stable values so we'll have less churn in install.sql. $line = preg_replace("/^INSERT INTO {vars} VALUES \\(\\d+/", "INSERT INTO {vars} VALUES (NULL", $line); $buf .= $line; } $fd = fopen($sql_file, "wb"); fwrite($fd, $buf); fclose($fd); }
/** * @see REST_Controller::_update($resource) */ public function _update($photo) { access::verify_csrf(); access::required("view", $photo); access::required("edit", $photo); $form = photo::get_edit_form($photo); if ($valid = $form->validate()) { if ($form->edit_photo->filename->value != $photo->name) { // Make sure that there's not a conflict if (Database::instance()->from("items")->where("parent_id", $photo->parent_id)->where("id <>", $photo->id)->where("name", $form->edit_photo->filename->value)->count_records()) { $form->edit_photo->filename->add_error("conflict", 1); $valid = false; } } } if ($valid) { $photo->title = $form->edit_photo->title->value; $photo->description = $form->edit_photo->description->value; $photo->rename($form->edit_photo->filename->value); $photo->save(); module::event("photo_edit_form_completed", $photo, $form); log::success("content", "Updated photo", "<a href=\"photos/{$photo->id}\">view</a>"); message::success(t("Saved photo %photo_title", array("photo_title" => p::clean($photo->title)))); print json_encode(array("result" => "success", "location" => url::site("photos/{$photo->id}"))); } else { print json_encode(array("result" => "error", "form" => $form->__toString())); } }
static function uninstall() { // Delete the face mapping table before uninstalling. $db = Database::instance(); $db->query("DROP TABLE IF EXISTS {picasa_faces};"); module::delete("picasa_faces"); }
public function compile($db = NULL) { if (!is_object($db)) { $db = Database::instance($db); } $query = 'INSERT INTO ' . $db->quote_table($this->_table); $query .= ' (' . implode(', ', array_map(array($db, 'quote_column'), $this->_columns)) . ') '; if (is_array($this->_values)) { $quote = array($db, 'quote'); $groups = array(); foreach ($this->_values as $group) { foreach ($group as $offset => $value) { if ((is_string($value) and array_key_exists($value, $this->_parameters)) === FALSE) { $group[$offset] = $db->quote($value); } } $groups[] = '(' . implode(', ', $group) . ')'; } $query .= 'VALUES ' . implode(', ', $groups); } else { $query .= (string) $this->_values; } $this->_sql = $query; return parent::compile($db); }
/** * Get Instance * * Gets the singleton instance for this object. This method should be called * statically in order to use the Database object: * * <code> * $db = MySqlDatabase::getInstance(); * </code> * * @return Database */ public static function getInstance() { if (!isset(self::$instance)) { self::$instance = new Database(); } return self::$instance->link; }
public static function getInstance() { if (is_null(self::$instance)) { self::$instance = new Database($GLOBALS['dbinfo']); } return self::$instance; }
public static function migrate_all(&$messages) { $migrations = static::get_migrations(); $messages = []; foreach (Migration::all() as $migration) { if (isset($migrations[$migration->hash])) { unset($migrations[$migration->hash]); } } $db = Database::instance(); foreach ($migrations as $key => $info) { $message = sprintf('Executing migration: \'%s\' with hash: %s', $info['class'], $key); $db->begin(); try { static::resolve($info['file'], $info['class'])->up(); if (Migration::create(['hash' => $key, 'name' => $info['class']])->saved()) { $messages[] = [$message]; } else { $messages[] = [$message, 'Failed to save migration to database']; } $db->commit(); } catch (Exception $e) { $db->rollback(); $messages[] = [$message, $e->getMessage()]; return $messages; } } return $messages; }
public static function connect() { if (!self::$instance) { self::$instance = new FileDBConnector(); } return self::$instance; }
/** * Singleton contoller * * @param array|null $config Configuration to pass to the constructor if needed * @return Database Singleton instance of Database */ public static function &instance($config = null) { if (empty(Database::$instance)) { Database::$instance = new Database($config); } return Database::$instance; }
public function __construct(array $config = NULL, $id = NULL) { if (!isset($config['group'])) { // Use the default group $config['group'] = 'default'; } // Load the database $this->_db = Database::instance($config['group']); if (isset($config['table'])) { // Set the table name $this->_table = (string) $config['table']; } if (isset($config['gc'])) { // Set the gc chance $this->_gc = (int) $config['gc']; } if (isset($config['columns'])) { // Overload column names $this->_columns = $config['columns']; } parent::__construct($config, $id); if (mt_rand(0, $this->_gc) === $this->_gc) { // Run garbage collection // This will average out to run once every X requests $this->_gc(); } }
static function install() { $db = Database::instance(); $db->query("CREATE TABLE IF NOT EXISTS {item_links} (\n `id` int(9) NOT NULL auto_increment,\n `item_id` int(9) NOT NULL,\n `url` text default NULL,\n PRIMARY KEY (`id`),\n KEY(`item_id`, `id`))\n DEFAULT CHARSET=utf8;"); // Set the module's version number. module::set_version("item_links", 1); }
/** * Construct load data * * @param Int $id */ public function __construct($site_id) { $this->db = Database::instance('old'); $sql = "SELECT `carriers`.* FROM (`carriers`) WHERE `site_id` = {$site_id} ORDER BY `carriers`.`id` ASC"; $carriers = $this->db->query($sql); foreach ($carriers as $keyc => $_carrier) { $carrier_temp = array(); $carrier_temp['id'] = $_carrier->carrier_id; $carrier_temp['site_id'] = $_carrier->site_id; $carrier_temp['name'] = $_carrier->name; $carrier_temp['url'] = $_carrier->url; $carrier_temp['delay'] = $_carrier->delay; $carrier_temp['type'] = 0; $carrier_temp['price'] = 0; $carrier_temp['country_relative'] = 1; $carrier_temp['position'] = $_carrier->position; $carrier_temp['active'] = 1; $carrier_temp['carrier_country'] = array(); $sql = "SELECT `carrier_countries`.* FROM (`carrier_countries`) WHERE `site_id` = {$site_id} AND `carrier_id` = {$_carrier->carrier_id} ORDER BY `carrier_countries`.`id` ASC"; $countries = $this->db->query($sql); foreach ($countries as $key_c => $_country) { $carrier_temp['carrier_country'][$key_c]['id'] = $_country->id; $carrier_temp['carrier_country'][$key_c]['country_id'] = $_country->country_id; $carrier_temp['carrier_country'][$key_c]['shipping_add'] = $_country->shipping_add; $carrier_temp['carrier_country'][$key_c]['position'] = 0; } $this->data[$keyc] = $carrier_temp; } $this->end = count($this->data); }