FIxed db/build authentification errors, merged from gsoc r39559 and r37162

git-svn-id: svn://svn.silverstripe.com/silverstripe/open/modules/sapphire/trunk@39609 467b73ca-7a2a-4603-9d3b-597d59a354a9
This commit is contained in:
Andrew O'Neil 2007-08-06 00:47:31 +00:00
parent f545953c18
commit 4560135eb9
2 changed files with 190 additions and 113 deletions

View File

@ -1,27 +1,41 @@
<?php <?php
/** /**
* Database Administration
*
* @package sapphire * @package sapphire
* @subpackage core * @subpackage core
*/ */
require_once("core/model/DB.php");
/** /**
* Utility functions for administrating the database. These can be accessed via URL, * Include the DB class
* eg http://www,yourdomain.com/db/build.
*/ */
class DatabaseAdmin extends Controller { require_once("core/model/DB.php");
/**
* DatabaseAdmin class
*
* Utility functions for administrating the database. These can be accessed
* via URL, e.g. http://www.yourdomain.com/db/build.
*/
class DatabaseAdmin extends Controller {
/** /**
* Get the data classes, grouped by their root class * Get the data classes, grouped by their root class
* @return array *
* @return array Array of data classes, grouped by their root class
*/ */
function groupedDataClasses() { function groupedDataClasses() {
// Get all root data objects // Get all root data objects
$allClasses = get_declared_classes(); $allClasses = get_declared_classes();
foreach($allClasses as $class) { foreach($allClasses as $class) {
if(get_parent_class($class) == "DataObject") $rootClasses[$class] = array(); if(get_parent_class($class) == "DataObject")
$rootClasses[$class] = array();
} }
// Assign every other data object one of those // Assign every other data object one of those
foreach($allClasses as $class) { foreach($allClasses as $class) {
if(!isset($rootClasses[$class]) && is_subclass_of($class, "DataObject")) { if(!isset($rootClasses[$class]) && is_subclass_of($class, "DataObject")) {
@ -35,7 +49,8 @@ class DatabaseAdmin extends Controller {
} }
return $rootClasses; return $rootClasses;
} }
/** /**
* Display a simple HTML menu of database admin helpers. * Display a simple HTML menu of database admin helpers.
*/ */
@ -44,19 +59,28 @@ class DatabaseAdmin extends Controller {
echo "<p><a href=\"build\">Add missing database fields (similar to sanity check).</a></p>"; echo "<p><a href=\"build\">Add missing database fields (similar to sanity check).</a></p>";
echo "<p><a href=\"../images/flush\">Flush <b>all</b> of the generated images.</a></p>"; echo "<p><a href=\"../images/flush\">Flush <b>all</b> of the generated images.</a></p>";
} }
/** /**
* Updates the database schema, creating tables & fields as necessary. * Updates the database schema, creating tables & fields as necessary.
*/ */
function build() { function build() {
if(Director::isLive() && ClassInfo::hasTable('Member') && ClassInfo::hasTable('Group') && ClassInfo::hasTable('Permission')) { if((Director::isLive() && ClassInfo::hasTable('Member') &&
BasicAuth::requireLogin("SilverStripe developer access. Use your CMS login", "ADMIN"); ClassInfo::hasTable('Group') && ClassInfo::hasTable('Permission'))
&& (!Member::currentUser() || !Member::currentUser()->isAdmin())) {
Security::permissionFailure($this,
"This page is secured and you need administrator rights to access it. " .
"Enter your credentials below and we will send you right along.");
return;
} }
$this->doBuild(isset($_REQUEST['quiet']) || isset($_REQUEST['from_installer'])); // The default time limit of 30 seconds is normally not enough
set_time_limit(600);
$this->doBuild(isset($_REQUEST['quiet']) ||
isset($_REQUEST['from_installer']));
} }
/** /**
* Check if database needs to be built, and build it if it does. * Check if database needs to be built, and build it if it does.
*/ */
@ -71,21 +95,28 @@ class DatabaseAdmin extends Controller {
} }
} }
} }
/** /**
* Returns the timestamp of the time that the database was last built * Returns the timestamp of the time that the database was last built
* @return string *
*/ * @return string Returns the timestamp of the time that the database was
* last built
*/
static function lastBuilt() { static function lastBuilt() {
$file = TEMP_FOLDER . '/database-last-generated-' .str_replace(array('\\','/',':'),'.',Director::baseFolder()); $file = TEMP_FOLDER . '/database-last-generated-' .
str_replace(array('\\','/',':'), '.' , Director::baseFolder());
if(file_exists($file)) { if(file_exists($file)) {
return filemtime($file); return filemtime($file);
} }
} }
/** /**
* Updates the database schema, creating tables & fields as necessary. * Updates the database schema, creating tables & fields as necessary.
* @param boolean $quiet Don't show messages' *
* @param boolean $quiet Don't show messages
*/ */
function doBuild($quiet = false) { function doBuild($quiet = false) {
if($quiet) { if($quiet) {
@ -106,14 +137,14 @@ class DatabaseAdmin extends Controller {
ManifestBuilder::compileManifest(); ManifestBuilder::compileManifest();
ManifestBuilder::includeEverything(); ManifestBuilder::includeEverything();
// Build the database. Most of the hard work is handled by DataObject // Build the database. Most of the hard work is handled by DataObject
$dataClasses = ClassInfo::subclassesFor('DataObject'); $dataClasses = ClassInfo::subclassesFor('DataObject');
array_shift($dataClasses); array_shift($dataClasses);
if(!$quiet) { if(!$quiet) {
echo '<p><b>Creating database tables</b></p>'; echo '<p><b>Creating database tables</b></p>';
} }
foreach($dataClasses as $dataClass) { foreach($dataClasses as $dataClass) {
// Test_ indicates that it's the data class is part of testing system // Test_ indicates that it's the data class is part of testing system
@ -121,17 +152,17 @@ class DatabaseAdmin extends Controller {
if(!$quiet) { if(!$quiet) {
echo "<li>$dataClass"; echo "<li>$dataClass";
} }
singleton($dataClass)->requireTable(); singleton($dataClass)->requireTable();
} }
} }
ManifestBuilder::compileManifest(); ManifestBuilder::compileManifest();
if(!$quiet) { if(!$quiet) {
echo '<p><b>Creating database records</b></p>'; echo '<p><b>Creating database records</b></p>';
} }
foreach($dataClasses as $dataClass) { foreach($dataClasses as $dataClass) {
// Test_ indicates that it's the data class is part of testing system // Test_ indicates that it's the data class is part of testing system
@ -139,28 +170,30 @@ class DatabaseAdmin extends Controller {
if(!$quiet) { if(!$quiet) {
echo "<li>$dataClass"; echo "<li>$dataClass";
} }
singleton($dataClass)->requireDefaultRecords(); singleton($dataClass)->requireDefaultRecords();
} }
} }
touch(TEMP_FOLDER . '/database-last-generated-' .str_replace(array('\\','/',':'),'.', Director::baseFolder())); touch(TEMP_FOLDER . '/database-last-generated-' .str_replace(array('\\','/',':'),'.', Director::baseFolder()));
if(isset($_REQUEST['from_installer'])) { if(isset($_REQUEST['from_installer'])) {
echo "OK"; echo "OK";
} }
} }
/** /**
* Method used to check mod_rewrite is working correctly in the installer. * Method used to check mod_rewrite is working correctly in the installer.
*/ */
function testinstall() { function testinstall() {
echo "OK"; echo "OK";
} }
/** /**
* Remove invalid records from tables - that is, records that * Remove invalid records from tables - that is, records that don't have
* don't have corresponding records in their parent class tables. * corresponding records in their parent class tables.
*/ */
function cleanup() { function cleanup() {
$allClasses = get_declared_classes(); $allClasses = get_declared_classes();
@ -169,7 +202,7 @@ class DatabaseAdmin extends Controller {
$baseClasses[] = $class; $baseClasses[] = $class;
} }
} }
foreach($baseClasses as $baseClass) { foreach($baseClasses as $baseClass) {
// Get data classes // Get data classes
$subclasses = ClassInfo::subclassesFor($baseClass); $subclasses = ClassInfo::subclassesFor($baseClass);
@ -179,19 +212,22 @@ class DatabaseAdmin extends Controller {
unset($subclasses[$k]); unset($subclasses[$k]);
} }
} }
if($subclasses) { if($subclasses) {
$records = DB::query("SELECT * FROM `$baseClass`"); $records = DB::query("SELECT * FROM `$baseClass`");
foreach($subclasses as $subclass) { foreach($subclasses as $subclass) {
$recordExists[$subclass] = DB::query("SELECT ID FROM `$subclass")->keyedColumn(); $recordExists[$subclass] =
DB::query("SELECT ID FROM `$subclass")->keyedColumn();
} }
foreach($records as $record) { foreach($records as $record) {
foreach($subclasses as $subclass) { foreach($subclasses as $subclass) {
$id = $record['ID']; $id = $record['ID'];
if($record['ClassName'] != $subclass && !is_subclass_of($record['ClassName'], $subclass) && $recordExists[$subclass][$id]) { if(($record['ClassName'] != $subclass) &&
(!is_subclass_of($record['ClassName'], $subclass)) &&
($recordExists[$subclass][$id])) {
$sql = "DELETE FROM `$subclass` WHERE ID = $record[ID]"; $sql = "DELETE FROM `$subclass` WHERE ID = $record[ID]";
echo "<li>$sql"; echo "<li>$sql";
DB::query($sql); DB::query($sql);
@ -201,71 +237,80 @@ class DatabaseAdmin extends Controller {
} }
} }
} }
/** /**
* Imports objects based on a specified CSV file in $_GET['FileName'] * Imports objects based on a specified CSV file in $_GET['FileName']
*/ */
function import(){ function import(){
$FileName = $_GET['FileName']; $FileName = $_GET['FileName'];
$FileName = $_SERVER['DOCUMENT_ROOT'] . substr($_SERVER['PHP_SELF'],0,strlen($_SERVER['PHP_SELF'])-18) ."/assets/". $FileName; $FileName = $_SERVER['DOCUMENT_ROOT'] .
substr($_SERVER['PHP_SELF'], 0, strlen($_SERVER['PHP_SELF'])-18) .
"/assets/" . $FileName;
if(file_exists($FileName)) { if(file_exists($FileName)) {
$handle = fopen($FileName,'r'); $handle = fopen($FileName,'r');
if($handle){ if($handle){
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) { while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data); $num = count($data);
$row++; $row++;
if($row == 1){ if($row == 1){
for ($c=0; $c < $num; $c++) for ($c=0; $c < $num; $c++) {
$ColumnHeaders[] = str_replace(' ','',$data[$c]); $ColumnHeaders[] = str_replace(' ','',$data[$c]);
// Have to add code here to remove unsafe chars.. // Have to add code here to remove unsafe chars..
}
} else { } else {
$Product = new Product(); $Product = new Product();
for ($c=0; $c < $num; $c++) { for ($c=0; $c < $num; $c++) {
$Product->$ColumnHeaders[$c] = trim($data[$c]); $Product->$ColumnHeaders[$c] = trim($data[$c]);
} }
$MainCategory = DataObject::get("ProductGroup", "URLSegment LIKE '". $Product->generateURLSegment($Product->Category) ."'"); $MainCategory = DataObject::get("ProductGroup",
"URLSegment LIKE '" . $Product->generateURLSegment(
if(!$MainCategory){ $Product->Category) ."'");
// if we cant find a main category, create all three sub categories, as they must be unique.
if(!$MainCategory) {
// if we can't find a main category, create all three sub
// categories, as they must be unique.
$ProductGroup = new ProductGroup(); $ProductGroup = new ProductGroup();
$ProductGroup->Title = $Product->Category; $ProductGroup->Title = $Product->Category;
print_r("<ul><li>Created : $ProductGroup->Title</li>"); print_r("<ul><li>Created : $ProductGroup->Title</li>");
$ProductGroup->ParentID = 1; $ProductGroup->ParentID = 1;
$index = $ProductGroup->write(); $index = $ProductGroup->write();
$ProductGroup->flushCache(); $ProductGroup->flushCache();
if($Product->SubCategory){ if($Product->SubCategory) {
$ChildProductGroup = new ProductGroup(); $ChildProductGroup = new ProductGroup();
$ChildProductGroup->Title = $Product->SubCategory; $ChildProductGroup->Title = $Product->SubCategory;
print_r("<ul><li>Created : $ChildProductGroup->Title</li>"); print_r("<ul><li>Created : $ChildProductGroup->Title</li>");
$ChildProductGroup->ClassName = "ProductGroup"; $ChildProductGroup->ClassName = "ProductGroup";
$ChildProductGroup->ParentID = $index; $ChildProductGroup->ParentID = $index;
$index = $ChildProductGroup->write(); $index = $ChildProductGroup->write();
$ChildProductGroup->flushCache(); $ChildProductGroup->flushCache();
} }
if($Product->SubCategory2) { if($Product->SubCategory2) {
$NestedProductGroup = new ProductGroup(); $NestedProductGroup = new ProductGroup();
$NestedProductGroup->Title = $Product->SubCategory2; $NestedProductGroup->Title = $Product->SubCategory2;
print_r("<ul><li>Created : $NestedProductGroup->Title</li>"); print_r("<ul><li>Created : $NestedProductGroup->Title</li>");
$NestedProductGroup->ClassName = "ProductGroup"; $NestedProductGroup->ClassName = "ProductGroup";
$NestedProductGroup->ParentID = $index; $NestedProductGroup->ParentID = $index;
$index = $NestedProductGroup->write(); $index = $NestedProductGroup->write();
$NestedProductGroup->flushCache(); $NestedProductGroup->flushCache();
} }
} else { } else {
// We've found a main category. check if theres a second... // We've found a main category. check if theres a second...
print_r("<ul><li>USING : $MainCategory->Title</li>"); print_r("<ul><li>USING : $MainCategory->Title</li>");
$index = $MainCategory->ID; $index = $MainCategory->ID;
$SubCategory = DataObject::get_one("ProductGroup","URLSegment LIKE '". $Product->generateURLSegment($Product->SubCategory) ."'"); $SubCategory = DataObject::get_one("ProductGroup",
"URLSegment LIKE '" . $Product->generateURLSegment(
$Product->SubCategory) ."'");
if(!$SubCategory && $Product->SubCategory) { if(!$SubCategory && $Product->SubCategory) {
$ChildProductGroup = new ProductGroup(); $ChildProductGroup = new ProductGroup();
@ -274,57 +319,61 @@ class DatabaseAdmin extends Controller {
$ChildProductGroup->ClassName = "ProductGroup"; $ChildProductGroup->ClassName = "ProductGroup";
$ChildProductGroup->ParentID = $index; $ChildProductGroup->ParentID = $index;
$index = $ChildProductGroup->write(); $index = $ChildProductGroup->write();
$ChildProductGroup->flushCache(); $ChildProductGroup->flushCache();
if($Product->SubCategory2) { if($Product->SubCategory2) {
$NestedProductGroup = new ProductGroup(); $NestedProductGroup = new ProductGroup();
$NestedProductGroup->Title = $Product->SubCategory2; $NestedProductGroup->Title = $Product->SubCategory2;
print_r("<ul><li>$NestedProductGroup->Title</li>"); print_r("<ul><li>$NestedProductGroup->Title</li>");
$NestedProductGroup->ClassName = "ProductGroup"; $NestedProductGroup->ClassName = "ProductGroup";
$NestedProductGroup->ParentID = $index; $NestedProductGroup->ParentID = $index;
$index = $NestedProductGroup->write(); $index = $NestedProductGroup->write();
$NestedProductGroup->flushCache();
$index = $SubCategory2->ID;
}
} else if($Product->SubCategory){
print_r("<ul><li>USING : $SubCategory->Title</li>");
$index = $SubCategory->ID;
$SubCategory2 = DataObject::get_one("ProductGroup","URLSegment LIKE '". $Product->generateURLSegment($Product->SubCategory2) ."'");
if($Product->SubCategory2) {
$NestedProductGroup = new ProductGroup();
$NestedProductGroup->Title = $Product->SubCategory2;
print_r("<ul><li>$NestedProductGroup->Title</li>");
$NestedProductGroup->ClassName = "ProductGroup";
$NestedProductGroup->ParentID = $index;
$index = $NestedProductGroup->write();
$NestedProductGroup->flushCache(); $NestedProductGroup->flushCache();
$index = $SubCategory2->ID; $index = $SubCategory2->ID;
} }
} } else if($Product->SubCategory){
} print_r("<ul><li>USING : $SubCategory->Title</li>");
$index = $SubCategory->ID;
$MatchedProduct = DataObject::get_one("Product","URLSegment LIKE '". $Product->generateURLSegment($Product->Title) . "'");
$SubCategory2 = DataObject::get_one("ProductGroup",
"URLSegment LIKE '" . $Product->generateURLSegment(
$Product->SubCategory2) ."'");
if($Product->SubCategory2) {
$NestedProductGroup = new ProductGroup();
$NestedProductGroup->Title = $Product->SubCategory2;
print_r("<ul><li>$NestedProductGroup->Title</li>");
$NestedProductGroup->ClassName = "ProductGroup";
$NestedProductGroup->ParentID = $index;
$index = $NestedProductGroup->write();
$NestedProductGroup->flushCache();
$index = $SubCategory2->ID;
}
}
}
$MatchedProduct = DataObject::get_one("Product",
"URLSegment LIKE '" . $Product->generateURLSegment(
$Product->Title) . "'");
if($MatchedProduct) { if($MatchedProduct) {
// create the new parents / assign many many // create the new parents / assign many many
$MatchedProduct->ParentID = $index; $MatchedProduct->ParentID = $index;
// create the new product // create the new product
$MatchedProduct->write(); $MatchedProduct->write();
$MatchedProduct->flushCache(); $MatchedProduct->flushCache();
print_r(" <h4>UPDATED</h4></ul></ul></ul><br/><br/>"); print_r(" <h4>UPDATED</h4></ul></ul></ul><br/><br/>");
} else { } else {
// save the new product // save the new product
$Product->ParentID = $index; $Product->ParentID = $index;
$Product->write(); $Product->write();
$Product->flushCache(); $Product->flushCache();
print_r(" <h4>New Product $product->Title</h4></ul></ul></ul><br/><br/>"); print_r(" <h4>New Product $product->Title</h4></ul></ul></ul><br/><br/>");
} }
} }
} }
fclose($handle); fclose($handle);
} else { } else {
print_r("<h1>Error: Could not open file.</h1>"); print_r("<h1>Error: Could not open file.</h1>");
@ -334,20 +383,22 @@ class DatabaseAdmin extends Controller {
} }
} }
/** /**
* Imports objects based on a specified CSV file in $_GET['FileName'] * Imports objects based on a specified CSV file in $_GET['FileName']
*/ */
function generateProductGroups() { function generateProductGroups() {
$FileName = $_GET['FileName']; $FileName = $_GET['FileName'];
$FileName = $_SERVER['DOCUMENT_ROOT'] . substr($_SERVER['PHP_SELF'], 0, strlen($_SERVER['PHP_SELF']) - 18) ."/assets/". $FileName; $FileName = $_SERVER['DOCUMENT_ROOT'] .
substr($_SERVER['PHP_SELF'], 0, strlen($_SERVER['PHP_SELF']) - 18) .
if(file_exists($FileName)) { "/assets/" . $FileName;
if(file_exists($FileName)) {
$handle = fopen($FileName,'r'); $handle = fopen($FileName,'r');
if($handle){ if($handle) {
$i = 0; $i = 0;
while(($data = fgetcsv($handle, 1000, ",")) !== FALSE) { while(($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$ProductGroup[$i] = $data[0]; $ProductGroup[$i] = $data[0];
if($data[1]) { if($data[1]) {
$ProductGroup[$i][] = $data[1]; $ProductGroup[$i][] = $data[1];
@ -355,15 +406,21 @@ class DatabaseAdmin extends Controller {
if($data[2]) { if($data[2]) {
$ProductGroup[$i][][] = $data[2]; $ProductGroup[$i][][] = $data[2];
} }
} }
} else { } else {
print_r("<h1>Error: Could not open file.</h1>"); print_r("<h1>Error: Could not open file.</h1>");
} }
} else{ } else {
print_r("<h1>Error: Could not open file.</h1>"); print_r("<h1>Error: Could not open file.</h1>");
} }
} }
function makeURL() {}
/**
* This method does nothing at the moment...
*/
function makeURL() {}
} }
?>
?>

View File

@ -217,11 +217,31 @@ class Member extends DataObject {
/** /**
* Returns true if this user is an administrator. * Returns true if this user is an administrator.
* Administrators have access to everything. The lucky bastards! ;-) * Administrators have access to everything. The lucky bastards! ;-)
*
* @todo Should this function really exists? Is not {@link isAdmin()} the
* only right name for this?
* @todo Is {@link Group}::CanCMSAdmin not deprecated?
*/ */
function _isAdmin() { function _isAdmin() {
if($groups = $this->Groups()) { if($groups = $this->Groups()) {
foreach($groups as $group) if($group->CanCMSAdmin) return true; foreach($groups as $group) if($group->CanCMSAdmin) return true;
} }
return Permission::check('ADMIN');
}
/**
* Check if the user is an administrator
*
* Alias for {@link _isAdmin()} because the method is used in both ways
* all over the framework.
*
* @return Returns TRUE if this user is an administrator.
* @see _isAdmin()
*/
public function isAdmin() {
return $this->_isAdmin();
} }
function _isCMSUser() { function _isCMSUser() {
if($groups = $this->Groups()) { if($groups = $this->Groups()) {