/** * Returns an array of columns for a database table * * @param string $table * @return array (empty if table doesn't exist) e.g. array('ID' => 'int(11) not null auto_increment') */ public static function getTableColumns($table) { if (!self::tableExists($table)) { return array(); } return DB::fieldList($table); }
function Fields() { $fields = new DataObjectSet(); foreach (DB::fieldList($this->Name) as $name => $spec) { $fields->push(new DBP_Field($this->Name . '.' . $name)); } return $fields; }
function __construct($id = null) { parent::__construct(); if (preg_match('/^(\\w+)\\.(\\d+)$/i', $id, $match)) { $this->table = $match[1]; $this->id = $match[2]; $this->data = DB::query('SELECT * FROM "' . $match[1] . '" WHERE "ID" = \'' . $this->id . '\'')->first(); } else { if (preg_match('/^(\\w+)$/i', $id, $match)) { $this->table = $match[1]; foreach (DB::fieldList($match[1]) as $name => $spec) { $this->data[$name] = null; } } } }
/** * Return the names and datatypes of columns for this discount. * * @param bool $appliedOnly true to return only columns added to the extended model, false to return all columns * including ones that would be added next build * @return array */ public static function field_specs($appliedOnly = true) { $fields = array(StreakDiscountTypePercentageExtension::ColumnSuffix => self::PercentageFieldSchema); $discountCodes = array_unique(StreakDiscountTypePercentageExtension::discount_codes(true)); $fieldSpecs = array(); foreach ($discountCodes as $fieldName) { if ($fieldName) { foreach ($fields as $specName => $schema) { $fieldSpecs[$fieldName . $specName] = $schema; } } } $fieldList = DB::fieldList(static::ModelClass); if ($appliedOnly && $fieldSpecs) { $fieldSpecs = array_intersect_key($fieldSpecs, $fieldList); } return $fieldSpecs; }
function datatype() { if (!$this->Table) { return false; } $fl = DB::fieldList($this->Table); if (isset($fl[$this->Label])) { if (is_array($fl[$this->Label])) { $out = ''; foreach ($fl[$this->Label] as $key => $val) { $out .= "{$key}: {$val}<br />"; } return $fl[$this->Label]['data_type']; } else { return $fl[$this->Label]; } } else { return "__HIDE__"; } }
/** * Logs this member in * * @param bool $remember If set to TRUE, the member will be logged in automatically the next time. */ function logIn($remember = false) { self::session_regenerate_id(); Session::set("loggedInAs", $this->ID); // This lets apache rules detect whether the user has logged in if (self::$login_marker_cookie) { Cookie::set(self::$login_marker_cookie, 1, 0); } $this->NumVisit++; if ($remember) { $generator = new RandomGenerator(); $token = $generator->generateHash('sha1'); $this->RememberLoginToken = $token; Cookie::set('alc_enc', $this->ID . ':' . $token, 90, null, null, null, true); } else { $this->RememberLoginToken = null; Cookie::set('alc_enc', null); Cookie::forceExpiry('alc_enc'); } // Clear the incorrect log-in count if (self::$lock_out_after_incorrect_logins) { $this->FailedLoginCount = 0; } // Don't set column if its not built yet (the login might be precursor to a /dev/build...) if (array_key_exists('LockedOutUntil', DB::fieldList('Member'))) { $this->LockedOutUntil = null; } $this->write(); // Audit logging hook $this->extend('memberLoggedIn'); }
function backup($tables, $dialect) { global $databaseConfig; $commands = array('/*', ' SQL Dump of ' . get_class(DB::getConn()) . ' ' . DB::getConn()->currentDatabase() . (DB::getConn() instanceof Sqlite3Database ? ' in ' . $databaseConfig['path'] : ' on ' . $databaseConfig['server']), " SQL Dialect {$dialect}", ' Created on ' . date('r'), ' Created with Database Plumber for Silverstripe', " =============================================", " DISCLAIMER: NO WARRANTY, USE AT YOUR OWN RISC", " =============================================", '*/', ''); if ($dialect == 'MySQL') { $commands[] = "SET sql_mode = 'ANSI';"; } foreach ($tables as $table) { $fields = array(); if ($dialect == 'MSSQL' && ($idcol = DB::getConn()->getIdentityColumn($table))) { $commands[] = "SET IDENTITY_INSERT \"{$table}\" ON;"; } $commands[] = 'DELETE FROM "' . $table . '";'; foreach (DB::fieldList($table) as $name => $spec) { $fields[] = $name; } foreach (DB::query('SELECT * FROM "' . $table . '"') as $record) { $cells = array(); foreach ($record as $cell) { if (is_null($cell)) { $cell = 'NULL'; } else { if (is_string($cell)) { $cell = "'" . DBP_SQLDialect::get($dialect)->escape($cell) . "'"; } } $cells[] = $cell; } $commands[] = "INSERT INTO \"{$table}\" (\"" . implode('", "', $fields) . "\") VALUES (" . implode(", ", $cells) . ");"; } if ($dialect == 'MSSQL' && $idcol) { $commands[] = "SET IDENTITY_INSERT \"{$table}\" OFF;"; } } return $commands; }
/** * Checks the database is in a state to perform security checks. * @return bool */ public static function database_is_ready() { return ClassInfo::hasTable('Member') && ClassInfo::hasTable('Group') && ClassInfo::hasTable('Permission') && (($permissionFields = DB::fieldList('Permission')) && isset($permissionFields['Type'])) && (($memberFields = DB::fieldList('Member')) && isset($memberFields['RememberLoginToken'])); }
/** * Checks the database is in a state to perform security checks. * See {@link DatabaseAdmin->init()} for more information. * * @return bool */ public static function database_is_ready() { // Used for unit tests if (self::$force_database_is_ready !== NULL) { return self::$force_database_is_ready; } if (self::$database_is_ready) { return self::$database_is_ready; } $requiredTables = ClassInfo::dataClassesFor('Member'); $requiredTables[] = 'Group'; $requiredTables[] = 'Permission'; foreach ($requiredTables as $table) { // if any of the tables aren't created in the database if (!ClassInfo::hasTable($table)) { return false; } // HACK: DataExtensions aren't applied until a class is instantiated for // the first time, so create an instance here. singleton($table); // if any of the tables don't have all fields mapped as table columns $dbFields = DB::fieldList($table); if (!$dbFields) { return false; } $objFields = DataObject::database_fields($table); $missingFields = array_diff_key($objFields, $dbFields); if ($missingFields) { return false; } } self::$database_is_ready = true; return true; }
/** * Checks the database is in a state to perform security checks. * See {@link DatabaseAdmin->init()} for more information. * * @return bool */ public static function database_is_ready() { // Used for unit tests if (self::$force_database_is_ready !== NULL) { return self::$force_database_is_ready; } $requiredTables = ClassInfo::dataClassesFor('Member'); $requiredTables[] = 'Group'; $requiredTables[] = 'Permission'; foreach ($requiredTables as $table) { // if any of the tables aren't created in the database if (!ClassInfo::hasTable($table)) { return false; } // if any of the tables don't have all fields mapped as table columns $dbFields = DB::fieldList($table); if (!$dbFields) { return false; } $objFields = DataObject::database_fields($table); $missingFields = array_diff_key($objFields, $dbFields); if ($missingFields) { return false; } } return true; }
/** * Logs this member in * * @param bool $remember If set to TRUE, the member will be logged in automatically the next time. */ public function logIn($remember = false) { $this->extend('beforeMemberLoggedIn'); self::session_regenerate_id(); Session::set("loggedInAs", $this->ID); // This lets apache rules detect whether the user has logged in if (Member::config()->login_marker_cookie) { Cookie::set(Member::config()->login_marker_cookie, 1, 0); } $this->NumVisit++; if ($remember) { // Store the hash and give the client the cookie with the token. $generator = new RandomGenerator(); $token = $generator->randomToken('sha1'); $hash = $this->encryptWithUserSettings($token); $this->RememberLoginToken = $hash; Cookie::set('alc_enc', $this->ID . ':' . $token, 90, null, null, null, true); } else { $this->RememberLoginToken = null; Cookie::set('alc_enc', null); Cookie::force_expiry('alc_enc'); } // Clear the incorrect log-in count if (self::config()->lock_out_after_incorrect_logins) { $this->FailedLoginCount = 0; } // Don't set column if its not built yet (the login might be precursor to a /dev/build...) if (array_key_exists('LockedOutUntil', DB::fieldList('Member'))) { $this->LockedOutUntil = null; } $this->regenerateTempID(); $this->write(); // Audit logging hook $this->extend('memberLoggedIn'); }
/** * Add default records to database. * * This function is called whenever the database is built, after the * database tables have all been created. */ public function requireDefaultRecords() { parent::requireDefaultRecords(); // Add default content if blank if(!DB::query("SELECT ID FROM Permission")->value() && array_key_exists('CanCMSAdmin', DB::fieldList('Group'))) { $admins = DB::query("SELECT ID FROM `Group` WHERE CanCMSAdmin = 1") ->column(); if(isset($admins)) { foreach($admins as $admin) Permission::grant($admin, "ADMIN"); } $authors = DB::query("SELECT ID FROM `Group` WHERE CanCMS = 1") ->column(); if(isset($authors)) { foreach($authors as $author) { Permission::grant($author, "CMS_ACCESS_CMSMain"); Permission::grant($author, "CMS_ACCESS_AssetAdmin"); Permission::grant($author, "CMS_ACCESS_NewsletterAdmin"); Permission::grant($author, "CMS_ACCESS_ReportAdmin"); } } } }
/** * Checks the database is in a state to perform security checks. * @return bool */ public static function database_is_ready() { $requiredTables = ClassInfo::dataClassesFor('Member'); $requiredTables[] = 'Group'; $requiredTables[] = 'Permission'; foreach($requiredTables as $table) if(!ClassInfo::hasTable($table)) return false; return (($permissionFields = DB::fieldList('Permission')) && isset($permissionFields['Type'])) && (($memberFields = DB::fieldList('Member')) && isset($memberFields['RememberLoginToken'])); }
/** * Logs this member in * * @param bool $remember If set to TRUE, the member will be logged in automatically the next time. */ function logIn($remember = false) { self::session_regenerate_id(); Session::set("loggedInAs", $this->ID); $this->NumVisit++; if($remember) { $token = substr(md5(uniqid(rand(), true)), 0, 49 - strlen($this->ID)); $this->RememberLoginToken = $token; Cookie::set('alc_enc', $this->ID . ':' . $token); } else { $this->RememberLoginToken = null; Cookie::set('alc_enc', null); Cookie::forceExpiry('alc_enc'); } // Clear the incorrect log-in count if(self::$lock_out_after_incorrect_logins) { $failedLogins = Session::get('Member.FailedLogins'); $failedLogins[$this->Email] = 0; Session::set('Member.FailedLogins', $failedLogins); } // Don't set column if its not built yet (the login might be precursor to a /dev/build...) if(array_key_exists('LockedOutUntil', DB::fieldList('Member'))) { $this->LockedOutUntil = null; } $this->write(); // Audit logging hook $this->extend('memberLoggedIn'); }
private function deleteField($table, $field) { $fields = $this->swapArray(DB::fieldList($table)); $globalExeceptions = Config::inst()->get("DataIntegrityTest", "global_exceptions"); if (count($globalExeceptions)) { foreach ($globalExeceptions as $exceptionTable => $exceptionField) { if ($exceptionTable == $table && $exceptionField == $field) { DB::alteration_message("tried to delete {$table}.{$field} but this is listed as a global exception and can not be deleted", "created"); return false; } } } if (!DB::query("SHOW TABLES LIKE '" . $table . "'")->value()) { DB::alteration_message("tried to delete {$table}.{$field} but TABLE does not exist", "deleted"); return false; } if (!class_exists($table)) { DB::alteration_message("tried to delete {$table}.{$field} but CLASS does not exist", "deleted"); return false; } if (!in_array($field, $fields)) { DB::alteration_message("tried to delete {$table}.{$field} but FIELD does not exist", "deleted"); return false; } else { DB::alteration_message("Deleting {$field} in {$table}", "deleted"); DB::query('ALTER TABLE "' . $table . '" DROP "' . $field . '";'); $obj = singleton($table); //to do: make this more reliable - checking for versioning rather than SiteTree if ($obj instanceof SiteTree) { DB::query('ALTER TABLE "' . $table . '_Live" DROP "' . $field . '";'); DB::alteration_message("Deleted {$field} in {$table}_Live", "deleted"); DB::query('ALTER TABLE "' . $table . '_versions" DROP "' . $field . '";'); DB::alteration_message("Deleted {$field} in {$table}_versions", "deleted"); } return true; } }