Skip to content
This repository
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

file 469 lines (394 sloc) 14.929 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468
<?php
/**
* Represents a folder in the assets/ directory.
* The folder path is stored in the "Filename" property.
*
* Updating the "Name" or "Filename" properties on
* a folder object also updates all associated children
* (both {@link File} and {@link Folder} records).
*
* Deleting a folder will also remove the folder from the filesystem,
* including any subfolders and contained files. Use {@link deleteDatabaseOnly()}
* to avoid touching the filesystem.
*
* See {@link File} documentation for more details about the
* relationship between the database and filesystem in the sapphire file APIs.
*
* @package sapphire
* @subpackage filesystem
*/
class Folder extends File {

static $singular_name = "Folder";

static $plural_name = "Folders";

static $default_sort = "\"Sort\"";

/**
*
*/
public function populateDefaults() {
parent::populateDefaults();

if(!$this->Name) $this->Name = _t('AssetAdmin.NEWFOLDER',"NewFolder");
}

/**
* @param $folderPath string Absolute or relative path to the file.
* If path is relative, its interpreted relative to the "assets/" directory.
* @return Folder
* @deprecated in favor of the correct name find_or_make
*/
public static function findOrMake($folderPath) {
Deprecation::notice('3.0', "Folder::findOrMake() is deprecated in favor of Folder::find_or_make()");
return self::find_or_make($folderPath);
}

/**
* Find the given folder or create it both as {@link Folder} database records
* and on the filesystem. If necessary, creates parent folders as well.
*
* @param $folderPath string Absolute or relative path to the file.
* If path is relative, its interpreted relative to the "assets/" directory.
* @return Folder
*/
public static function find_or_make($folderPath) {
// Create assets directory, if it is missing
if(!file_exists(ASSETS_PATH)) Filesystem::makeFolder(ASSETS_PATH);

$folderPath = trim(Director::makeRelative($folderPath));
// replace leading and trailing slashes
$folderPath = preg_replace('/^\/?(.*)\/?$/', '$1', $folderPath);
$parts = explode("/",$folderPath);

$parentID = 0;
$item = null;
foreach($parts as $part) {
if(!$part) continue; // happens for paths with a trailing slash
$item = DataObject::get_one(
"Folder",
sprintf(
"\"Name\" = '%s' AND \"ParentID\" = %d",
Convert::raw2sql($part),
(int)$parentID
)
);
if(!$item) {
$item = new Folder();
$item->ParentID = $parentID;
$item->Name = $part;
$item->Title = $part;
$item->write();
}
if(!file_exists($item->getFullPath())) {
Filesystem::makeFolder($item->getFullPath());
}
$parentID = $item->ID;
}

return $item;
}

/**
* Syncronise the file database with the actual content of the assets folder
*/
function syncChildren() {
$parentID = (int)$this->ID; // parentID = 0 on the singleton, used as the 'root node';
$added = 0;
$deleted = 0;

// First, merge any children that are duplicates
$duplicateChildrenNames = DB::query("SELECT \"Name\" FROM \"File\" WHERE \"ParentID\" = $parentID GROUP BY \"Name\" HAVING count(*) > 1")->column();
if($duplicateChildrenNames) foreach($duplicateChildrenNames as $childName) {
$childName = Convert::raw2sql($childName);
// Note, we do this in the database rather than object-model; otherwise we get all sorts of problems about deleting files
$children = DB::query("SELECT \"ID\" FROM \"File\" WHERE \"Name\" = '$childName' AND \"ParentID\" = $parentID")->column();
if($children) {
$keptChild = array_shift($children);
foreach($children as $removedChild) {
DB::query("UPDATE \"File\" SET \"ParentID\" = $keptChild WHERE \"ParentID\" = $removedChild");
DB::query("DELETE FROM \"File\" WHERE \"ID\" = $removedChild");
}
} else {
user_error("Inconsistent database issue: SELECT ID FROM \"File\" WHERE Name = '$childName' AND ParentID = $parentID should have returned data", E_USER_WARNING);
}
}


// Get index of database content
// We don't use DataObject so that things like subsites doesn't muck with this.
$dbChildren = DB::query("SELECT * FROM \"File\" WHERE \"ParentID\" = $parentID");
$hasDbChild = array();
if($dbChildren) {
foreach($dbChildren as $dbChild) {
$className = $dbChild['ClassName'];
if(!$className) $className = "File";
$hasDbChild[$dbChild['Name']] = new $className($dbChild);
}
}
$unwantedDbChildren = $hasDbChild;


// Iterate through the actual children, correcting the database as necessary
$baseDir = $this->FullPath;

if(!$this->Filename) die($this->ID . " - " . $this->FullPath);


if(file_exists($baseDir)) {
$actualChildren = scandir($baseDir);
foreach($actualChildren as $actualChild) {
if($actualChild[0] == '.' || $actualChild[0] == '_' || substr($actualChild,0,6) == 'Thumbs' || $actualChild == 'web.config') {
continue;
}

// A record with a bad class type doesn't deserve to exist. It must be purged!
if(isset($hasDbChild[$actualChild])) {
$child = $hasDbChild[$actualChild];
if(( !( $child instanceof Folder ) && is_dir($baseDir . $actualChild) )
|| (( $child instanceof Folder ) && !is_dir($baseDir . $actualChild)) ) {
DB::query("DELETE FROM \"File\" WHERE \"ID\" = $child->ID");
unset($hasDbChild[$actualChild]);
}
}


if(isset($hasDbChild[$actualChild])) {
$child = $hasDbChild[$actualChild];
unset($unwantedDbChildren[$actualChild]);
} else {
$added++;
$childID = $this->constructChild($actualChild);
$child = DataObject::get_by_id("File", $childID);
}

if( $child && is_dir($baseDir . $actualChild)) {
$childResult = $child->syncChildren();
$added += $childResult['added'];
$deleted += $childResult['deleted'];
}

// Clean up the child record from memory after use. Important!
$child->destroy();
$child = null;
}

// Iterate through the unwanted children, removing them all
if(isset($unwantedDbChildren)) foreach($unwantedDbChildren as $unwantedDbChild) {
DB::query("DELETE FROM \"File\" WHERE \"ID\" = $unwantedDbChild->ID");
$deleted++;
}
} else {
DB::query("DELETE FROM \"File\" WHERE \"ID\" = $this->ID");
}

return array('added' => $added, 'deleted' => $deleted);
}

/**
* Construct a child of this Folder with the given name.
* It does this without actually using the object model, as this starts messing
* with all the data. Rather, it does a direct database insert.
*/
function constructChild($name) {
// Determine the class name - File, Folder or Image
$baseDir = $this->FullPath;
if(is_dir($baseDir . $name)) {
$className = "Folder";
} else {
$className = File::get_class_for_file_extension(pathinfo($name, PATHINFO_EXTENSION));
}

if(Member::currentUser()) $ownerID = Member::currentUser()->ID;
else $ownerID = 0;

$filename = Convert::raw2sql($this->Filename . $name);
if($className == 'Folder' ) $filename .= '/';

$name = Convert::raw2sql($name);

DB::query("INSERT INTO \"File\"
(\"ClassName\", \"ParentID\", \"OwnerID\", \"Name\", \"Filename\", \"Created\", \"LastEdited\", \"Title\")
VALUES ('$className', $this->ID, $ownerID, '$name', '$filename', " . DB::getConn()->now() . ',' . DB::getConn()->now() . ", '$name')");

return DB::getGeneratedID("File");
}

/**
* Take a file uploaded via a POST form, and save it inside this folder.
* File names are filtered through {@link FileNameFilter}, see class documentation
* on how to influence this behaviour.
*/
function addUploadToFolder($tmpFile) {
if(!is_array($tmpFile)) {
user_error("Folder::addUploadToFolder() Not passed an array. Most likely, the form hasn't got the right enctype", E_USER_ERROR);
}
if(!isset($tmpFile['size'])) {
return;
}

$base = BASE_PATH;
// $parentFolder = Folder::findOrMake("Uploads");

// Generate default filename
$nameFilter = Object::create('FileNameFilter');
$file = $nameFilter->filter($tmpFile['name']);
while($file[0] == '_' || $file[0] == '.') {
$file = substr($file, 1);
}

$file = $this->RelativePath . $file;
Filesystem::makeFolder(dirname("$base/$file"));

$doubleBarrelledExts = array('.gz', '.bz', '.bz2');

$ext = "";
if(preg_match('/^(.*)(\.[^.]+)$/', $file, $matches)) {
$file = $matches[1];
$ext = $matches[2];
// Special case for double-barrelled
if(in_array($ext, $doubleBarrelledExts) && preg_match('/^(.*)(\.[^.]+)$/', $file, $matches)) {
$file = $matches[1];
$ext = $matches[2] . $ext;
}
}
$origFile = $file;

$i = 1;
while(file_exists("$base/$file$ext")) {
$i++;
$oldFile = $file;

if(strpos($file, '.') !== false) {
$file = ereg_replace('[0-9]*(\.[^.]+$)', $i . '\\1', $file);
} elseif(strpos($file, '_') !== false) {
$file = ereg_replace('_([^_]+$)', '_' . $i, $file);
} else {
$file .= "_$i";
}

if($oldFile == $file && $i > 2) user_error("Couldn't fix $file$ext with $i", E_USER_ERROR);
}

if (move_uploaded_file($tmpFile['tmp_name'], "$base/$file$ext")) {
// Update with the new image
return $this->constructChild(basename($file . $ext));
} else {
if(!file_exists($tmpFile['tmp_name'])) user_error("Folder::addUploadToFolder: '$tmpFile[tmp_name]' doesn't exist", E_USER_ERROR);
else user_error("Folder::addUploadToFolder: Couldn't copy '$tmpFile[tmp_name]' to '$base/$file$ext'", E_USER_ERROR);
return false;
}
}

function validate() {
return new ValidationResult(true);
}

//-------------------------------------------------------------------------------------------------
// Data Model Definition

function getRelativePath() {
return parent::getRelativePath() . "/";
}

function onBeforeDelete() {
if($this->ID && ($children = $this->AllChildren())) {
foreach($children as $child) {
if(!$this->Filename || !$this->Name || !file_exists($this->getFullPath())) {
$child->setField('Name',null);
$child->Filename = null;
}
$child->delete();
}
}

// Do this after so a folder's contents are removed before we delete the folder.
if($this->Filename && $this->Name && file_exists($this->getFullPath())) {
$files = glob( $this->getFullPath() . '/*' );

if( !$files || ( count( $files ) == 1 && preg_match( '/\/_resampled$/', $files[0] ) ) )
Filesystem::removeFolder( $this->getFullPath() );
}

parent::onBeforeDelete();
}

/** Override setting the Title of Folders to that Name, Filename and Title are always in sync.
* Note that this is not appropriate for files, because someone might want to create a human-readable name
* of a file that is different from its name on disk. But folders should always match their name on disk. */
function setTitle($title) {
$this->setField('Title',$title);
parent::setName($title); //set the name and filename to match the title
}

function setName($name) {
$this->setField('Title',$name);
parent::setName($name);
}

function setFilename($filename) {
$this->setField('Title',pathinfo($filename, PATHINFO_BASENAME));
parent::setFilename($filename);
}

/**
* Delete the database record (recursively for folders) without touching the filesystem
*/
function deleteDatabaseOnly() {
if($children = $this->myChildren()) {
foreach($children as $child) $child->deleteDatabaseOnly();
}

parent::deleteDatabaseOnly();
}

public function myChildren() {
// Ugly, but functional.
$ancestors = ClassInfo::ancestry($this->class);
foreach($ancestors as $i => $a) {
if(isset($baseClass) && $baseClass === -1) {
$baseClass = $a;
break;
}
if($a == "DataObject") $baseClass = -1;
}

$g = DataObject::get($baseClass, "\"ParentID\" = " . $this->ID);
return $g;
}

/**
* Returns true if this folder has children
*/
public function hasChildren() {
return (bool)DB::query("SELECT COUNT(*) FROM \"File\" WHERE ParentID = "
. (int)$this->ID)->value();
}

/**
* Returns true if this folder has children
*/
public function hasChildFolders() {
$SQL_folderClasses = Convert::raw2sql(ClassInfo::subclassesFor('Folder'));

return (bool)DB::query("SELECT COUNT(*) FROM \"File\" WHERE \"ParentID\" = " . (int)$this->ID
. " AND \"ClassName\" IN ('" . implode("','", $SQL_folderClasses) . "')")->value();
}

/**
* Overloaded to call recursively on all contained {@link File} records.
*/
public function updateFilesystem() {
parent::updateFilesystem();

// Note: Folders will have been renamed on the filesystem already at this point,
// File->updateFilesystem() needs to take this into account.
if($this->ID && ($children = $this->AllChildren())) {
foreach($children as $child) {
$child->updateFilesystem();
$child->write();
}
}
}

/**
* Return the FieldList used to edit this folder in the CMS.
* You can modify this FieldList by subclassing folder, or by creating a {@link DataExtension}
* and implemeting updateCMSFields(FieldList $fields) on that extension.
*/
function getCMSFields() {
$config = GridFieldConfig::create();
$config->addComponent(new GridFieldFilter());
$config->addComponent(new GridFieldDefaultColumns());
$config->addComponent(new GridFieldSortableHeader());
$config->addComponent(new GridFieldPaginator(2));
$config->addComponent(new GridFieldAction_Delete());
$config->addComponent(new GridFieldAction_Edit());
$config->addComponent($gridFieldForm = new GridFieldPopupForms());
$gridFieldForm->setTemplate('CMSGridFieldPopupForms');
$files = DataList::create('File')->filter('ParentID', $this->ID)->exclude('ClassName', 'Folder');
$gridField = new GridField('File','Files', $files, $config);
$gridField->setDisplayFields(array(
'StripThumbnail' => '',
'Parent.FileName' => 'Folder',
'Title'=>'Title',
'Size'=>'Size',
));

$titleField = ($this->ID && $this->ID != "root") ? new TextField("Title", _t('Folder.TITLE')) : new HiddenField("Title");

$fields = new FieldList(
new TabSet('Root',
new Tab('Main',
$titleField,
$gridField,
new HiddenField("ID"),
new HiddenField("Name"),
new HiddenField("DestFolderID")
)
)
);

if(!$this->canEdit()) {
$fields->removeByName("Upload");
}

$this->extend('updateCMSFields', $fields);

return $fields;
}

/**
* Get the children of this folder that are also folders.
*/
function ChildFolders() {
return DataObject::get("Folder", "\"ParentID\" = " . (int)$this->ID);
}

/**
* @return String
*/
function CMSTreeClasses($controller) {
$classes = sprintf('class-%s', $this->class);

if(!$this->canDelete())
$classes .= " nodelete";

if($controller->isCurrentPage($this))
$classes .= " current";

if(!$this->canEdit())
$classes .= " disabled";

$classes .= $this->markingClasses();

return $classes;
}
}
Something went wrong with that request. Please try again.