Converted to PSR-2

This commit is contained in:
helpfulrobot 2015-12-18 07:48:37 +13:00
parent 1aebe7e8d5
commit bd707c4ffc
23 changed files with 3335 additions and 3085 deletions

View File

@ -1,11 +1,12 @@
<?php <?php
class DMS implements DMSInterface { class DMS implements DMSInterface
{
static $dmsFolder = 'dms-assets'; //folder to store the documents in public static $dmsFolder = 'dms-assets'; //folder to store the documents in
//How many documents to store in a single folder. The square of this number is the maximum number of documents. //How many documents to store in a single folder. The square of this number is the maximum number of documents.
//The number should be a multiple of 10 //The number should be a multiple of 10
static $dmsFolderSize = 1000; public static $dmsFolderSize = 1000;
/** /**
@ -13,7 +14,8 @@ class DMS implements DMSInterface {
* @static * @static
* @return DMSInterface An instance of the Document Management System * @return DMSInterface An instance of the Document Management System
*/ */
static function inst() { public static function inst()
{
$dmsPath = self::get_dms_path(); $dmsPath = self::get_dms_path();
$dms = new DMS(); $dms = new DMS();
@ -29,17 +31,24 @@ class DMS implements DMSInterface {
return $dms; return $dms;
} }
static function get_dms_path() { public static function get_dms_path()
{
return BASE_PATH . DIRECTORY_SEPARATOR . self::$dmsFolder; return BASE_PATH . DIRECTORY_SEPARATOR . self::$dmsFolder;
} }
static function transform_file_to_file_path($file) { public static function transform_file_to_file_path($file)
{
//confirm we have a file //confirm we have a file
$filePath = null; $filePath = null;
if (is_string($file)) $filePath = $file; if (is_string($file)) {
elseif (is_object($file) && $file->is_a("File")) $filePath = $file->Filename; $filePath = $file;
} elseif (is_object($file) && $file->is_a("File")) {
$filePath = $file->Filename;
}
if (!$filePath) throw new FileNotFoundException(); if (!$filePath) {
throw new FileNotFoundException();
}
return $filePath; return $filePath;
} }
@ -50,7 +59,8 @@ class DMS implements DMSInterface {
* @param $file File object, or String that is path to a file to store, e.g. "assets/documents/industry/supplied-v1-0.pdf" * @param $file File object, or String that is path to a file to store, e.g. "assets/documents/industry/supplied-v1-0.pdf"
*/ */
function storeDocument($file) { public function storeDocument($file)
{
$filePath = self::transform_file_to_file_path($file); $filePath = self::transform_file_to_file_path($file);
//create a new document and get its ID //create a new document and get its ID
@ -70,7 +80,8 @@ class DMS implements DMSInterface {
* @param bool $showEmbargoed Boolean that specifies if embargoed documents should be included in results * @param bool $showEmbargoed Boolean that specifies if embargoed documents should be included in results
* @return DocumentInterface * @return DocumentInterface
*/ */
function getByTag($category = null, $value = null, $showEmbargoed = false) { public function getByTag($category = null, $value = null, $showEmbargoed = false)
{
// TODO: Implement getByTag() method. // TODO: Implement getByTag() method.
} }
@ -81,7 +92,8 @@ class DMS implements DMSInterface {
* @param bool $showEmbargoed Boolean that specifies if embargoed documents should be included in results * @param bool $showEmbargoed Boolean that specifies if embargoed documents should be included in results
* @return DocumentInterface * @return DocumentInterface
*/ */
function getByFullTextSearch($searchText, $showEmbargoed = false) { public function getByFullTextSearch($searchText, $showEmbargoed = false)
{
// TODO: Implement getByFullTextSearch() method. // TODO: Implement getByFullTextSearch() method.
} }
@ -91,7 +103,8 @@ class DMS implements DMSInterface {
* @param bool $showEmbargoed Boolean that specifies if embargoed documents should be included in results * @param bool $showEmbargoed Boolean that specifies if embargoed documents should be included in results
* @return DataList Document list associated with the Page * @return DataList Document list associated with the Page
*/ */
function getByPage($page, $showEmbargoed = false) { public function getByPage($page, $showEmbargoed = false)
{
// TODO: Implement getByPage() method. // TODO: Implement getByPage() method.
} }
@ -99,7 +112,8 @@ class DMS implements DMSInterface {
* Creates a storage folder for the given path * Creates a storage folder for the given path
* @param $path Path to create a folder for * @param $path Path to create a folder for
*/ */
static function create_storage_folder($path) { public static function create_storage_folder($path)
{
if (!is_dir($path)) { if (!is_dir($path)) {
mkdir($path, 0777); mkdir($path, 0777);
} }
@ -108,7 +122,8 @@ class DMS implements DMSInterface {
/** /**
* Calculates the storage path from a database DMSDocument ID * Calculates the storage path from a database DMSDocument ID
*/ */
static function get_storage_folder($id) { public static function get_storage_folder($id)
{
$folderName = intval($id / self::$dmsFolderSize); $folderName = intval($id / self::$dmsFolderSize);
return $folderName; return $folderName;
} }

View File

@ -6,7 +6,8 @@
* *
* @package dms * @package dms
*/ */
class DMSShortcodeHandler { class DMSShortcodeHandler
{
public static function handle( public static function handle(
$arguments, $content, ShortcodeParser $parser, $tag, array $extra = array() $arguments, $content, ShortcodeParser $parser, $tag, array $extra = array()
@ -38,5 +39,4 @@ class DMSShortcodeHandler {
return ''; return '';
} }
} }

View File

@ -4,7 +4,8 @@
* @package dms * @package dms
*/ */
class DMSDocumentAddController extends LeftAndMain { class DMSDocumentAddController extends LeftAndMain
{
private static $url_segment = 'pages/adddocument'; private static $url_segment = 'pages/adddocument';
private static $url_priority = 60; private static $url_priority = 60;
@ -13,7 +14,7 @@ class DMSDocumentAddController extends LeftAndMain {
private static $tree_class = 'SiteTree'; private static $tree_class = 'SiteTree';
private static $session_namespace = 'CMSMain'; private static $session_namespace = 'CMSMain';
static $allowed_extensions = array(); public static $allowed_extensions = array();
private static $allowed_actions = array( private static $allowed_actions = array(
'getEditForm', 'getEditForm',
@ -27,10 +28,16 @@ class DMSDocumentAddController extends LeftAndMain {
* @static * @static
* @param $array * @param $array
*/ */
static function add_allowed_extensions($array = null) { public static function add_allowed_extensions($array = null)
if (empty($array)) return; {
if (is_array($array)) self::$allowed_extensions = $array; if (empty($array)) {
else self::$allowed_extensions = array($array); return;
}
if (is_array($array)) {
self::$allowed_extensions = $array;
} else {
self::$allowed_extensions = array($array);
}
} }
/** /**
@ -38,7 +45,8 @@ class DMSDocumentAddController extends LeftAndMain {
* *
* @return * @return
*/ */
public function currentPage() { public function currentPage()
{
$id = $this->currentPageID(); $id = $this->currentPageID();
if ($id && is_numeric($id) && $id > 0) { if ($id && is_numeric($id) && $id > 0) {
@ -54,7 +62,8 @@ class DMSDocumentAddController extends LeftAndMain {
/** /**
* Return fake-ID "root" if no ID is found (needed to upload files into the root-folder) * Return fake-ID "root" if no ID is found (needed to upload files into the root-folder)
*/ */
public function currentPageID() { public function currentPageID()
{
return ($result = parent::currentPageID()) === null ? 0 : $result; return ($result = parent::currentPageID()) === null ? 0 : $result;
} }
@ -62,7 +71,8 @@ class DMSDocumentAddController extends LeftAndMain {
* @return Form * @return Form
* @todo what template is used here? AssetAdmin_UploadContent.ss doesn't seem to be used anymore * @todo what template is used here? AssetAdmin_UploadContent.ss doesn't seem to be used anymore
*/ */
public function getEditForm($id = null, $fields = null) { public function getEditForm($id = null, $fields = null)
{
Requirements::javascript(FRAMEWORK_DIR . '/javascript/AssetUploadField.js'); Requirements::javascript(FRAMEWORK_DIR . '/javascript/AssetUploadField.js');
Requirements::css(FRAMEWORK_DIR . '/css/AssetUploadField.css'); Requirements::css(FRAMEWORK_DIR . '/css/AssetUploadField.css');
Requirements::css(DMS_DIR.'/css/DMSMainCMS.css'); Requirements::css(DMS_DIR.'/css/DMSMainCMS.css');
@ -139,7 +149,8 @@ class DMSDocumentAddController extends LeftAndMain {
/** /**
* @return ArrayList * @return ArrayList
*/ */
public function Breadcrumbs($unlinked = false) { public function Breadcrumbs($unlinked = false)
{
$items = parent::Breadcrumbs($unlinked); $items = parent::Breadcrumbs($unlinked);
// The root element should explicitly point to the root node. // The root element should explicitly point to the root node.
@ -161,12 +172,14 @@ class DMSDocumentAddController extends LeftAndMain {
return $items; return $items;
} }
public function Backlink(){ public function Backlink()
{
$pageID = $this->currentPageID(); $pageID = $this->currentPageID();
return singleton('CMSPagesController')->Link().'edit/show/'.$pageID; return singleton('CMSPagesController')->Link().'edit/show/'.$pageID;
} }
public function documentautocomplete() { public function documentautocomplete()
{
$term = (isset($_GET['term'])) ? $_GET['term'] : ''; $term = (isset($_GET['term'])) ? $_GET['term'] : '';
$term_sql = Convert::raw2sql($term); $term_sql = Convert::raw2sql($term);
$data = DMSDocument::get() $data = DMSDocument::get()
@ -186,7 +199,8 @@ class DMSDocumentAddController extends LeftAndMain {
return json_encode($return); return json_encode($return);
} }
public function linkdocument() { public function linkdocument()
{
$return = array('error' => _t('UploadField.FIELDNOTSET', 'Could not add document to page')); $return = array('error' => _t('UploadField.FIELDNOTSET', 'Could not add document to page'));
$page = $this->currentPage(); $page = $this->currentPage();
@ -212,7 +226,8 @@ class DMSDocumentAddController extends LeftAndMain {
return json_encode($return); return json_encode($return);
} }
public function documentlist() { public function documentlist()
{
if (!isset($_GET['pageID'])) { if (!isset($_GET['pageID'])) {
return $this->httpError(400); return $this->httpError(400);
} }

View File

@ -1,10 +1,12 @@
<?php <?php
class DMSDocumentAddExistingField extends CompositeField { class DMSDocumentAddExistingField extends CompositeField
{
public $useFieldContext = true; public $useFieldContext = true;
function __construct($name, $title = null) { public function __construct($name, $title = null)
{
$this->name = $name; $this->name = $name;
$this->title = ($title === null) ? $name : $title; $this->title = ($title === null) ? $name : $title;
@ -15,7 +17,8 @@ class DMSDocumentAddExistingField extends CompositeField {
* Force a record to be used as "Parent" for uploaded Files (eg a Page with a has_one to File) * Force a record to be used as "Parent" for uploaded Files (eg a Page with a has_one to File)
* @param DataObject $record * @param DataObject $record
*/ */
public function setRecord($record) { public function setRecord($record)
{
$this->record = $record; $this->record = $record;
return $this; return $this;
} }
@ -23,7 +26,8 @@ class DMSDocumentAddExistingField extends CompositeField {
* Get the record to use as "Parent" for uploaded Files (eg a Page with a has_one to File) If none is set, it will use Form->getRecord() or Form->Controller()->data() * Get the record to use as "Parent" for uploaded Files (eg a Page with a has_one to File) If none is set, it will use Form->getRecord() or Form->Controller()->data()
* @return DataObject * @return DataObject
*/ */
public function getRecord() { public function getRecord()
{
if (!$this->record && $this->form) { if (!$this->record && $this->form) {
if ($this->form->getRecord() && is_a($this->form->getRecord(), 'DataObject')) { if ($this->form->getRecord() && is_a($this->form->getRecord(), 'DataObject')) {
$this->record = $this->form->getRecord(); $this->record = $this->form->getRecord();
@ -35,11 +39,13 @@ class DMSDocumentAddExistingField extends CompositeField {
return $this->record; return $this->record;
} }
public function FieldHolder($properties = array()) { public function FieldHolder($properties = array())
{
return $this->Field($properties); return $this->Field($properties);
} }
public function Field($properties = array()) { public function Field($properties = array())
{
Requirements::javascript(DMS_DIR.'/javascript/DMSDocumentAddExistingField.js'); Requirements::javascript(DMS_DIR.'/javascript/DMSDocumentAddExistingField.js');
Requirements::javascript(DMS_DIR."/javascript/DocumentHtmlEditorFieldToolbar.js"); Requirements::javascript(DMS_DIR."/javascript/DocumentHtmlEditorFieldToolbar.js");
@ -50,7 +56,8 @@ class DMSDocumentAddExistingField extends CompositeField {
* Sets or unsets the use of the "field" class in the template. The "field" class adds Javascript behaviour * Sets or unsets the use of the "field" class in the template. The "field" class adds Javascript behaviour
* that causes unwelcome hiding side-effects when this Field is used within the link editor pop-up * that causes unwelcome hiding side-effects when this Field is used within the link editor pop-up
*/ */
public function setUseFieldClass($use = false) { public function setUseFieldClass($use = false)
{
$this->useFieldContext = $use; $this->useFieldContext = $use;
} }
} }

View File

@ -13,7 +13,8 @@
* @package dms * @package dms
* @subpackage cms * @subpackage cms
*/ */
class DMSGridFieldDeleteAction extends GridFieldDeleteAction implements GridField_ColumnProvider, GridField_ActionProvider { class DMSGridFieldDeleteAction extends GridFieldDeleteAction implements GridField_ColumnProvider, GridField_ActionProvider
{
/** /**
* *
@ -22,7 +23,8 @@ class DMSGridFieldDeleteAction extends GridFieldDeleteAction implements GridFiel
* @param string $columnName * @param string $columnName
* @return string - the HTML for the column * @return string - the HTML for the column
*/ */
public function getColumnContent($gridField, $record, $columnName) { public function getColumnContent($gridField, $record, $columnName)
{
if ($this->removeRelation) { if ($this->removeRelation) {
$field = GridField_FormAction::create($gridField, 'UnlinkRelation'.$record->ID, false, "unlinkrelation", array('RecordID' => $record->ID)) $field = GridField_FormAction::create($gridField, 'UnlinkRelation'.$record->ID, false, "unlinkrelation", array('RecordID' => $record->ID))
->addExtraClass('gridfield-button-unlink') ->addExtraClass('gridfield-button-unlink')
@ -46,8 +48,11 @@ class DMSGridFieldDeleteAction extends GridFieldDeleteAction implements GridFiel
->removeExtraClass('gridfield-button-delete'); //remove the base gridfield behaviour ->removeExtraClass('gridfield-button-delete'); //remove the base gridfield behaviour
//set a class telling JS what kind of warning to display when clicking the delete button //set a class telling JS what kind of warning to display when clicking the delete button
if ($numberOfRelations > 1) $field->addExtraClass('dms-delete-link-only'); if ($numberOfRelations > 1) {
else $field->addExtraClass('dms-delete-last-warning'); $field->addExtraClass('dms-delete-link-only');
} else {
$field->addExtraClass('dms-delete-last-warning');
}
//set a class to show if the document is hidden //set a class to show if the document is hidden
if ($record->isHidden()) { if ($record->isHidden()) {
@ -66,7 +71,8 @@ class DMSGridFieldDeleteAction extends GridFieldDeleteAction implements GridFiel
* @param array $data - form data * @param array $data - form data
* @return void * @return void
*/ */
public function handleAction(GridField $gridField, $actionName, $arguments, $data) { public function handleAction(GridField $gridField, $actionName, $arguments, $data)
{
if ($actionName == 'deleterecord' || $actionName == 'unlinkrelation') { if ($actionName == 'deleterecord' || $actionName == 'unlinkrelation') {
$item = $gridField->getList()->byID($arguments['RecordID']); $item = $gridField->getList()->byID($arguments['RecordID']);
if (!$item) { if (!$item) {
@ -77,10 +83,14 @@ class DMSGridFieldDeleteAction extends GridFieldDeleteAction implements GridFiel
} }
$delete = false; $delete = false;
if ($item->Pages()->Count() <= 1) $delete = true; if ($item->Pages()->Count() <= 1) {
$delete = true;
}
$gridField->getList()->remove($item); //remove the relation $gridField->getList()->remove($item); //remove the relation
if ($delete) $item->delete(); //delete the DMSDocument if ($delete) {
$item->delete();
} //delete the DMSDocument
} }
} }
} }

View File

@ -3,10 +3,12 @@
/** /**
* Custom ItemRequest class the provides custom delete behaviour for the CMSFields of DMSDocument * Custom ItemRequest class the provides custom delete behaviour for the CMSFields of DMSDocument
*/ */
class DMSGridFieldDetailForm_ItemRequest extends GridFieldDetailForm_ItemRequest { class DMSGridFieldDetailForm_ItemRequest extends GridFieldDetailForm_ItemRequest
{
private static $allowed_actions = array('ItemEditForm'); private static $allowed_actions = array('ItemEditForm');
function ItemEditForm() { public function ItemEditForm()
{
$form = parent::ItemEditForm(); $form = parent::ItemEditForm();
//add a data attribute specifying how many pages this document is referenced on //add a data attribute specifying how many pages this document is referenced on
@ -21,5 +23,4 @@ class DMSGridFieldDetailForm_ItemRequest extends GridFieldDetailForm_ItemRequest
} }
return $form; return $form;
} }
} }

View File

@ -12,14 +12,16 @@
* @author Julian Seidenberg * @author Julian Seidenberg
* @package dms * @package dms
*/ */
class DMSUploadField extends UploadField { class DMSUploadField extends UploadField
{
private static $allowed_actions = array( private static $allowed_actions = array(
"upload", "upload",
); );
protected $folderName = 'DMSTemporaryUploads'; protected $folderName = 'DMSTemporaryUploads';
public function __construct($name, $title = null, SS_List $items = null) { public function __construct($name, $title = null, SS_List $items = null)
{
parent::__construct($name, $title, $items); parent::__construct($name, $title, $items);
//set default DMS replace template to false //set default DMS replace template to false
@ -32,7 +34,8 @@ class DMSUploadField extends UploadField {
* add it into the DMS storage, deleting the old/uploaded file. * add it into the DMS storage, deleting the old/uploaded file.
* @param File * @param File
*/ */
protected function attachFile($file) { protected function attachFile($file)
{
$dms = DMS::inst(); $dms = DMS::inst();
$record = $this->getRecord(); $record = $this->getRecord();
@ -53,16 +56,19 @@ class DMSUploadField extends UploadField {
return $doc; return $doc;
} }
public function validate($validator) { public function validate($validator)
{
return true; return true;
} }
public function isDisabled() { public function isDisabled()
{
return (parent::isDisabled() || !$this->isSaveable()); return (parent::isDisabled() || !$this->isSaveable());
} }
public function isSaveable() { public function isSaveable()
{
return (!empty($this->getRecord()->ID)); return (!empty($this->getRecord()->ID));
} }
@ -72,12 +78,17 @@ class DMSUploadField extends UploadField {
* @param SS_HTTPRequest $request * @param SS_HTTPRequest $request
* @return string json * @return string json
*/ */
public function upload(SS_HTTPRequest $request) { public function upload(SS_HTTPRequest $request)
if($this->isDisabled() || $this->isReadonly()) return $this->httpError(403); {
if ($this->isDisabled() || $this->isReadonly()) {
return $this->httpError(403);
}
// Protect against CSRF on destructive action // Protect against CSRF on destructive action
$token = $this->getForm()->getSecurityToken(); $token = $this->getForm()->getSecurityToken();
if(!$token->checkRequest($request)) return $this->httpError(400); if (!$token->checkRequest($request)) {
return $this->httpError(400);
}
$name = $this->getName(); $name = $this->getName();
$tmpfile = $request->postVar($name); $tmpfile = $request->postVar($name);
@ -100,7 +111,9 @@ class DMSUploadField extends UploadField {
$tooManyFiles = false; $tooManyFiles = false;
// Some relationships allow many files to be attached. // Some relationships allow many files to be attached.
if ($this->getConfig('allowedMaxFileNumber') && ($record->has_many($name) || $record->many_many($name))) { if ($this->getConfig('allowedMaxFileNumber') && ($record->has_many($name) || $record->many_many($name))) {
if(!$record->isInDB()) $record->write(); if (!$record->isInDB()) {
$record->write();
}
$tooManyFiles = $record->{$name}()->count() >= $this->getConfig('allowedMaxFileNumber'); $tooManyFiles = $record->{$name}()->count() >= $this->getConfig('allowedMaxFileNumber');
// has_one only allows one file at any given time. // has_one only allows one file at any given time.
} elseif ($record->has_one($name)) { } elseif ($record->has_one($name)) {
@ -109,7 +122,9 @@ class DMSUploadField extends UploadField {
// Report the constraint violation. // Report the constraint violation.
if ($tooManyFiles) { if ($tooManyFiles) {
if(!$this->getConfig('allowedMaxFileNumber')) $this->setConfig('allowedMaxFileNumber', 1); if (!$this->getConfig('allowedMaxFileNumber')) {
$this->setConfig('allowedMaxFileNumber', 1);
}
$return['error'] = _t( $return['error'] = _t(
'UploadField.MAXNUMBEROFFILES', 'UploadField.MAXNUMBEROFFILES',
'Max number of {count} file(s) exceeded.', 'Max number of {count} file(s) exceeded.',
@ -172,11 +187,13 @@ class DMSUploadField extends UploadField {
* Never directly display items uploaded * Never directly display items uploaded
* @return SS_List * @return SS_List
*/ */
public function getItems() { public function getItems()
{
return new ArrayList(); return new ArrayList();
} }
public function Field($properties = array()) { public function Field($properties = array())
{
$fields = parent::Field($properties); $fields = parent::Field($properties);
// Replace the download template with a new one only when access the upload field through a GridField. // Replace the download template with a new one only when access the upload field through a GridField.
@ -193,14 +210,16 @@ class DMSUploadField extends UploadField {
* @param int $itemID * @param int $itemID
* @return UploadField_ItemHandler * @return UploadField_ItemHandler
*/ */
public function getItemHandler($itemID) { public function getItemHandler($itemID)
{
return DMSUploadField_ItemHandler::create($this, $itemID); return DMSUploadField_ItemHandler::create($this, $itemID);
} }
} }
class DMSUploadField_ItemHandler extends UploadField_ItemHandler { class DMSUploadField_ItemHandler extends UploadField_ItemHandler
function getItem() { {
public function getItem()
{
return DataObject::get_by_id('DMSDocument', $this->itemID); return DataObject::get_by_id('DMSDocument', $this->itemID);
} }
} }

View File

@ -4,16 +4,20 @@
*/ */
class DocumentHtmlEditorFieldToolbar extends Extension { class DocumentHtmlEditorFieldToolbar extends Extension
{
function updateLinkForm(Form $form) { public function updateLinkForm(Form $form)
{
$linkType = null; $linkType = null;
$fieldList = null; $fieldList = null;
$fields = $form->Fields();//->fieldByName('Heading'); $fields = $form->Fields();//->fieldByName('Heading');
foreach ($fields as $field) { foreach ($fields as $field) {
$linkType = ($field->fieldByName('LinkType')); $linkType = ($field->fieldByName('LinkType'));
$fieldList = $field; $fieldList = $field;
if ($linkType) break; //break once we have the object if ($linkType) {
break;
} //break once we have the object
} }
$source = $linkType->getSource(); $source = $linkType->getSource();

View File

@ -3,6 +3,6 @@
* Simple exception extension so that we can tell the difference between internally * Simple exception extension so that we can tell the difference between internally
* raised exceptions and those thrown by DMS. * raised exceptions and those thrown by DMS.
*/ */
class FileNotFoundException extends Exception { class FileNotFoundException extends Exception
{
} }

View File

@ -3,7 +3,8 @@
/** /**
* @package dms * @package dms
*/ */
class DMSSiteTreeExtension extends DataExtension { class DMSSiteTreeExtension extends DataExtension
{
private static $belongs_many_many = array( private static $belongs_many_many = array(
'Documents' => 'DMSDocument' 'Documents' => 'DMSDocument'
@ -18,8 +19,11 @@ class DMSSiteTreeExtension extends DataExtension {
* @static * @static
* @param $mixed Array of page types to not show the Documents tab on * @param $mixed Array of page types to not show the Documents tab on
*/ */
static function no_documents_tab($array = array()) { public static function no_documents_tab($array = array())
if (empty($array)) return; {
if (empty($array)) {
return;
}
if (is_array($array)) { if (is_array($array)) {
self::$noDocumentsList = $array; self::$noDocumentsList = $array;
} else { } else {
@ -33,8 +37,11 @@ class DMSSiteTreeExtension extends DataExtension {
* @static * @static
* @param $array Array of page types to show the Documents tab on * @param $array Array of page types to show the Documents tab on
*/ */
static function show_documents_tab($array = array()) { public static function show_documents_tab($array = array())
if (empty($array)) return; {
if (empty($array)) {
return;
}
if (is_array($array)) { if (is_array($array)) {
self::$showDocumentsList = $array; self::$showDocumentsList = $array;
} else { } else {
@ -42,10 +49,15 @@ class DMSSiteTreeExtension extends DataExtension {
} }
} }
function updateCMSFields(FieldList $fields){ public function updateCMSFields(FieldList $fields)
{
//prevent certain pages from having a Document tab in the CMS //prevent certain pages from having a Document tab in the CMS
if (in_array($this->owner->ClassName,self::$noDocumentsList)) return; if (in_array($this->owner->ClassName, self::$noDocumentsList)) {
if (count(self::$showDocumentsList) > 0 && !in_array($this->owner->ClassName,self::$showDocumentsList)) return; return;
}
if (count(self::$showDocumentsList) > 0 && !in_array($this->owner->ClassName, self::$showDocumentsList)) {
return;
}
//javascript to customize the grid field for the DMS document (overriding entwine in FRAMEWORK_DIR.'/javascript/GridField.js' //javascript to customize the grid field for the DMS document (overriding entwine in FRAMEWORK_DIR.'/javascript/GridField.js'
Requirements::javascript(DMS_DIR.'/javascript/DMSGridField.js'); Requirements::javascript(DMS_DIR.'/javascript/DMSGridField.js');
@ -121,11 +133,13 @@ class DMSSiteTreeExtension extends DataExtension {
/** /**
* Enforce sorting for frontend * Enforce sorting for frontend
*/ */
function PageDocuments() { public function PageDocuments()
{
return $this->owner->getManyManyComponents('Documents')->sort('DocumentSort'); return $this->owner->getManyManyComponents('Documents')->sort('DocumentSort');
} }
function onBeforeDelete() { public function onBeforeDelete()
{
if (Versioned::current_stage() == 'Live') { if (Versioned::current_stage() == 'Live') {
$existsOnOtherStage = !$this->owner->getIsDeletedFromStage(); $existsOnOtherStage = !$this->owner->getIsDeletedFromStage();
} else { } else {
@ -145,7 +159,8 @@ class DMSSiteTreeExtension extends DataExtension {
} }
} }
function onBeforePublish() { public function onBeforePublish()
{
$embargoedDocuments = $this->owner->Documents()->filter('EmbargoedUntilPublished', true); $embargoedDocuments = $this->owner->Documents()->filter('EmbargoedUntilPublished', true);
if ($embargoedDocuments->Count() > 0) { if ($embargoedDocuments->Count() > 0) {
foreach ($embargoedDocuments as $doc) { foreach ($embargoedDocuments as $doc) {
@ -153,10 +168,10 @@ class DMSSiteTreeExtension extends DataExtension {
$doc->write(); $doc->write();
} }
} }
} }
function getTitleWithNumberOfDocuments() { public function getTitleWithNumberOfDocuments()
{
return $this->owner->Title . ' (' . $this->owner->Documents()->Count() . ')'; return $this->owner->Title . ' (' . $this->owner->Documents()->Count() . ')';
} }
} }

View File

@ -4,7 +4,8 @@
* instance of the DMSInterface. All write operations on the DMSDocument create a new relation, so we never need to * instance of the DMSInterface. All write operations on the DMSDocument create a new relation, so we never need to
* explicitly call the write() method on the DMSDocument DataObject * explicitly call the write() method on the DMSDocument DataObject
*/ */
interface DMSDocumentInterface { interface DMSDocumentInterface
{
/** /**
* Deletes the DMSDocument, its underlying file, as well as any tags related to this DMSDocument. * Deletes the DMSDocument, its underlying file, as well as any tags related to this DMSDocument.
@ -23,7 +24,7 @@ interface DMSDocumentInterface {
* @param $pageObject Page object to associate this DMSDocument with * @param $pageObject Page object to associate this DMSDocument with
* @return null * @return null
*/ */
function addPage($pageObject); public function addPage($pageObject);
/** /**
* Associates this DMSDocument with a set of Pages. This method loops through a set of page ids, and then associates this * Associates this DMSDocument with a set of Pages. This method loops through a set of page ids, and then associates this
@ -32,7 +33,7 @@ interface DMSDocumentInterface {
* @param $pageIDs array of page ids used for the page objects associate this DMSDocument with * @param $pageIDs array of page ids used for the page objects associate this DMSDocument with
* @return null * @return null
*/ */
function addPages($pageIDs); public function addPages($pageIDs);
/** /**
* Removes the association between this DMSDocument and a Page. This method does nothing if the association does not exist. * Removes the association between this DMSDocument and a Page. This method does nothing if the association does not exist.
@ -40,21 +41,21 @@ interface DMSDocumentInterface {
* @param $pageObject Page object to remove the association to * @param $pageObject Page object to remove the association to
* @return mixed * @return mixed
*/ */
function removePage($pageObject); public function removePage($pageObject);
/** /**
* Returns a list of the Page objects associated with this DMSDocument * Returns a list of the Page objects associated with this DMSDocument
* @abstract * @abstract
* @return DataList * @return DataList
*/ */
function getPages(); public function getPages();
/** /**
* Removes all associated Pages from the DMSDocument * Removes all associated Pages from the DMSDocument
* @abstract * @abstract
* @return null * @return null
*/ */
function removeAllPages(); public function removeAllPages();
/** /**
* Adds a metadata tag to the DMSDocument. The tag has a category and a value. * Adds a metadata tag to the DMSDocument. The tag has a category and a value.
@ -69,7 +70,7 @@ interface DMSDocumentInterface {
* @param bool $multiValue Boolean that determines if the category is multi-value or single-value (optional) * @param bool $multiValue Boolean that determines if the category is multi-value or single-value (optional)
* @return null * @return null
*/ */
function addTag($category, $value, $multiValue = true); public function addTag($category, $value, $multiValue = true);
/** /**
* Fetches all tags associated with this DMSDocument within a given category. If a value is specified this method * Fetches all tags associated with this DMSDocument within a given category. If a value is specified this method
@ -79,7 +80,7 @@ interface DMSDocumentInterface {
* @param null $value String of the value of the tag to get * @param null $value String of the value of the tag to get
* @return array of Strings of all the tags or null if there is no match found * @return array of Strings of all the tags or null if there is no match found
*/ */
function getTagsList($category, $value = null); public function getTagsList($category, $value = null);
/** /**
* Removes a tag from the DMSDocument. If you only set a category, then all values in that category are deleted. * Removes a tag from the DMSDocument. If you only set a category, then all values in that category are deleted.
@ -90,40 +91,40 @@ interface DMSDocumentInterface {
* @param null $value Value to remove (optional) * @param null $value Value to remove (optional)
* @return null * @return null
*/ */
function removeTag($category, $value = null); public function removeTag($category, $value = null);
/** /**
* Deletes all tags associated with this DMSDocument. * Deletes all tags associated with this DMSDocument.
* @abstract * @abstract
* @return null * @return null
*/ */
function removeAllTags(); public function removeAllTags();
/** /**
* Returns a link to download this DMSDocument from the DMS store * Returns a link to download this DMSDocument from the DMS store
* @abstract * @abstract
* @return String * @return String
*/ */
function getLink(); public function getLink();
/** /**
* Return the extension of the file associated with the document * Return the extension of the file associated with the document
*/ */
function getExtension(); public function getExtension();
/** /**
* Returns the size of the file type in an appropriate format. * Returns the size of the file type in an appropriate format.
* *
* @return string * @return string
*/ */
function getSize(); public function getSize();
/** /**
* Return the size of the file associated with the document, in bytes. * Return the size of the file associated with the document, in bytes.
* *
* @return int * @return int
*/ */
function getAbsoluteSize(); public function getAbsoluteSize();
/** /**
@ -132,7 +133,7 @@ interface DMSDocumentInterface {
* @param $file File object, or String that is path to a file to store * @param $file File object, or String that is path to a file to store
* @return DMSDocumentInstance Document object that we replaced the file in * @return DMSDocumentInstance Document object that we replaced the file in
*/ */
function replaceDocument($file); public function replaceDocument($file);
/** /**
* Hides the DMSDocument, so it does not show up when getByPage($myPage) is called * Hides the DMSDocument, so it does not show up when getByPage($myPage) is called
@ -141,14 +142,14 @@ interface DMSDocumentInterface {
* @abstract * @abstract
* @return null * @return null
*/ */
function embargoIndefinitely(); public function embargoIndefinitely();
/** /**
* Returns if this is DMSDocument is embargoed or expired. * Returns if this is DMSDocument is embargoed or expired.
* @abstract * @abstract
* @return bool True or False depending on whether this DMSDocument is embargoed or expired * @return bool True or False depending on whether this DMSDocument is embargoed or expired
*/ */
function isHidden(); public function isHidden();
/** /**
@ -156,7 +157,7 @@ interface DMSDocumentInterface {
* @abstract * @abstract
* @return bool True or False depending on whether this DMSDocument is embargoed * @return bool True or False depending on whether this DMSDocument is embargoed
*/ */
function isEmbargoed(); public function isEmbargoed();
/** /**
* Hides the DMSDocument, so it does not show up when getByPage($myPage) is called. Automatically un-hides the * Hides the DMSDocument, so it does not show up when getByPage($myPage) is called. Automatically un-hides the
@ -165,27 +166,27 @@ interface DMSDocumentInterface {
* @param $datetime String date time value when this DMSDocument should expire * @param $datetime String date time value when this DMSDocument should expire
* @return null * @return null
*/ */
function embargoUntilDate($datetime); public function embargoUntilDate($datetime);
/** /**
* Hides the document until any page it is linked to is published * Hides the document until any page it is linked to is published
* @return null * @return null
*/ */
function embargoUntilPublished(); public function embargoUntilPublished();
/** /**
* Clears any previously set embargos, so the DMSDocument always shows up in all queries. * Clears any previously set embargos, so the DMSDocument always shows up in all queries.
* @abstract * @abstract
* @return null * @return null
*/ */
function clearEmbargo(); public function clearEmbargo();
/** /**
* Returns if this is DMSDocument is expired. * Returns if this is DMSDocument is expired.
* @abstract * @abstract
* @return bool True or False depending on whether this DMSDocument is expired * @return bool True or False depending on whether this DMSDocument is expired
*/ */
function isExpired(); public function isExpired();
/** /**
* Hides the DMSDocument at a specific date, so it does not show up when getByPage($myPage) is called. * Hides the DMSDocument at a specific date, so it does not show up when getByPage($myPage) is called.
@ -193,14 +194,14 @@ interface DMSDocumentInterface {
* @param $datetime String date time value when this DMSDocument should expire * @param $datetime String date time value when this DMSDocument should expire
* @return null * @return null
*/ */
function expireAtDate($datetime); public function expireAtDate($datetime);
/** /**
* Clears any previously set expiry. * Clears any previously set expiry.
* @abstract * @abstract
* @return null * @return null
*/ */
function clearExpiry(); public function clearExpiry();
/*---- FROM HERE ON: optional API features ----*/ /*---- FROM HERE ON: optional API features ----*/
@ -210,6 +211,5 @@ interface DMSDocumentInterface {
* @abstract * @abstract
* @return DataList List of DMSDocument objects * @return DataList List of DMSDocument objects
*/ */
function getVersions(); public function getVersions();
} }

View File

@ -8,7 +8,8 @@
* 10000 files per folder is a good amount) * 10000 files per folder is a good amount)
* *
*/ */
interface DMSInterface { interface DMSInterface
{
/** /**
* Factory method that returns an instance of the DMS. This could be any class that implements the DMSInterface. * Factory method that returns an instance of the DMS. This could be any class that implements the DMSInterface.
@ -16,7 +17,7 @@ interface DMSInterface {
* @abstract * @abstract
* @return DMSInterface An instance of the Document Management System * @return DMSInterface An instance of the Document Management System
*/ */
static function inst(); public static function inst();
/** /**
* Takes a File object or a String (path to a file) and copies it into the DMS. The original file remains unchanged. * Takes a File object or a String (path to a file) and copies it into the DMS. The original file remains unchanged.
@ -25,7 +26,7 @@ interface DMSInterface {
* @param $file File object, or String that is path to a file to store * @param $file File object, or String that is path to a file to store
* @return DMSDocumentInstance Document object that we just created * @return DMSDocumentInstance Document object that we just created
*/ */
function storeDocument($file); public function storeDocument($file);
/** /**
* *
@ -37,7 +38,7 @@ interface DMSInterface {
* @param bool $showEmbargoed Boolean that specifies if embargoed documents should be included in results * @param bool $showEmbargoed Boolean that specifies if embargoed documents should be included in results
* @return DMSDocumentInterface * @return DMSDocumentInterface
*/ */
function getByTag($category = null, $value = null, $showEmbargoed = false); public function getByTag($category = null, $value = null, $showEmbargoed = false);
/** /**
* Returns a number of Document objects that match a full-text search of the Documents and their contents * Returns a number of Document objects that match a full-text search of the Documents and their contents
@ -47,7 +48,7 @@ interface DMSInterface {
* @param bool $showEmbargoed Boolean that specifies if embargoed documents should be included in results * @param bool $showEmbargoed Boolean that specifies if embargoed documents should be included in results
* @return DMSDocumentInterface * @return DMSDocumentInterface
*/ */
function getByFullTextSearch($searchText, $showEmbargoed = false); public function getByFullTextSearch($searchText, $showEmbargoed = false);
/** /**
@ -57,5 +58,5 @@ interface DMSInterface {
* @param bool $showEmbargoed Boolean that specifies if embargoed documents should be included in results * @param bool $showEmbargoed Boolean that specifies if embargoed documents should be included in results
* @return DataList Document list associated with the Page * @return DataList Document list associated with the Page
*/ */
function getByPage($page, $showEmbargoed = false); public function getByPage($page, $showEmbargoed = false);
} }

View File

@ -3,7 +3,8 @@
/** /**
* @package dms * @package dms
*/ */
class DMSDocument extends DataObject implements DMSDocumentInterface { class DMSDocument extends DataObject implements DMSDocumentInterface
{
private static $db = array( private static $db = array(
"Filename" => "Varchar(255)", // eg. 3469~2011-energysaving-report.pdf "Filename" => "Varchar(255)", // eg. 3469~2011-energysaving-report.pdf
@ -56,7 +57,8 @@ class DMSDocument extends DataObject implements DMSDocumentInterface {
* *
* @return boolean * @return boolean
*/ */
public function canView($member = null) { public function canView($member = null)
{
if (!$member || !(is_a($member, 'Member')) || is_numeric($member)) { if (!$member || !(is_a($member, 'Member')) || is_numeric($member)) {
$member = Member::currentUser(); $member = Member::currentUser();
} }
@ -65,7 +67,9 @@ class DMSDocument extends DataObject implements DMSDocumentInterface {
$results = $this->extend('canView', $member); $results = $this->extend('canView', $member);
if ($results && is_array($results)) { if ($results && is_array($results)) {
if(!min($results)) return false; if (!min($results)) {
return false;
}
} }
if ($member && $member->ID) { if ($member && $member->ID) {
@ -80,7 +84,8 @@ class DMSDocument extends DataObject implements DMSDocumentInterface {
* *
* @return boolean * @return boolean
*/ */
public function canEdit($member = null) { public function canEdit($member = null)
{
if (!$member || !(is_a($member, 'Member')) || is_numeric($member)) { if (!$member || !(is_a($member, 'Member')) || is_numeric($member)) {
$member = Member::currentUser(); $member = Member::currentUser();
} }
@ -88,7 +93,9 @@ class DMSDocument extends DataObject implements DMSDocumentInterface {
$results = $this->extend('canEdit', $member); $results = $this->extend('canEdit', $member);
if ($results && is_array($results)) { if ($results && is_array($results)) {
if(!min($results)) return false; if (!min($results)) {
return false;
}
} }
return $this->canView(); return $this->canView();
@ -99,7 +106,8 @@ class DMSDocument extends DataObject implements DMSDocumentInterface {
* *
* @return boolean * @return boolean
*/ */
public function canCreate($member = null) { public function canCreate($member = null)
{
if (!$member || !(is_a($member, 'Member')) || is_numeric($member)) { if (!$member || !(is_a($member, 'Member')) || is_numeric($member)) {
$member = Member::currentUser(); $member = Member::currentUser();
} }
@ -107,7 +115,9 @@ class DMSDocument extends DataObject implements DMSDocumentInterface {
$results = $this->extend('canCreate', $member); $results = $this->extend('canCreate', $member);
if ($results && is_array($results)) { if ($results && is_array($results)) {
if(!min($results)) return false; if (!min($results)) {
return false;
}
} }
return $this->canView(); return $this->canView();
@ -118,7 +128,8 @@ class DMSDocument extends DataObject implements DMSDocumentInterface {
* *
* @return boolean * @return boolean
*/ */
public function canDelete($member = null) { public function canDelete($member = null)
{
if (!$member || !(is_a($member, 'Member')) || is_numeric($member)) { if (!$member || !(is_a($member, 'Member')) || is_numeric($member)) {
$member = Member::currentUser(); $member = Member::currentUser();
} }
@ -126,7 +137,9 @@ class DMSDocument extends DataObject implements DMSDocumentInterface {
$results = $this->extend('canDelete', $member); $results = $this->extend('canDelete', $member);
if ($results && is_array($results)) { if ($results && is_array($results)) {
if(!min($results)) return false; if (!min($results)) {
return false;
}
} }
return $this->canView(); return $this->canView();
@ -146,7 +159,8 @@ class DMSDocument extends DataObject implements DMSDocumentInterface {
* *
* @return DMSDocument * @return DMSDocument
*/ */
public function addPage($pageObject) { public function addPage($pageObject)
{
$this->Pages()->add($pageObject); $this->Pages()->add($pageObject);
DB::query("UPDATE \"DMSDocument_Pages\" SET \"DocumentSort\"=\"DocumentSort\"+1 WHERE \"SiteTreeID\" = $pageObject->ID"); DB::query("UPDATE \"DMSDocument_Pages\" SET \"DocumentSort\"=\"DocumentSort\"+1 WHERE \"SiteTreeID\" = $pageObject->ID");
@ -163,7 +177,8 @@ class DMSDocument extends DataObject implements DMSDocumentInterface {
* *
* @return DMSDocument * @return DMSDocument
*/ */
public function addPages($pageIDs) { public function addPages($pageIDs)
{
foreach ($pageIDs as $id) { foreach ($pageIDs as $id) {
$pageObject = DataObject::get_by_id("SiteTree", $id); $pageObject = DataObject::get_by_id("SiteTree", $id);
@ -183,7 +198,8 @@ class DMSDocument extends DataObject implements DMSDocumentInterface {
* *
* @return DMSDocument * @return DMSDocument
*/ */
public function removePage($pageObject) { public function removePage($pageObject)
{
$this->Pages()->remove($pageObject); $this->Pages()->remove($pageObject);
return $this; return $this;
@ -194,7 +210,8 @@ class DMSDocument extends DataObject implements DMSDocumentInterface {
* *
* @return DataList * @return DataList
*/ */
public function Pages() { public function Pages()
{
$pages = $this->getManyManyComponents('Pages'); $pages = $this->getManyManyComponents('Pages');
$this->extend('updatePages', $pages); $this->extend('updatePages', $pages);
@ -206,7 +223,8 @@ class DMSDocument extends DataObject implements DMSDocumentInterface {
* *
* @return DataList * @return DataList
*/ */
public function getPages() { public function getPages()
{
return $this->Pages(); return $this->Pages();
} }
@ -215,7 +233,8 @@ class DMSDocument extends DataObject implements DMSDocumentInterface {
* *
* @return DMSDocument * @return DMSDocument
*/ */
public function removeAllPages() { public function removeAllPages()
{
$this->Pages()->removeAll(); $this->Pages()->removeAll();
return $this; return $this;
@ -227,7 +246,8 @@ class DMSDocument extends DataObject implements DMSDocumentInterface {
* *
* @return DMSDocument * @return DMSDocument
*/ */
public function trackView() { public function trackView()
{
if ($this->ID > 0) { if ($this->ID > 0) {
$count = $this->ViewCount + 1; $count = $this->ViewCount + 1;
@ -261,7 +281,8 @@ class DMSDocument extends DataObject implements DMSDocumentInterface {
* *
* @return DMSDocument * @return DMSDocument
*/ */
public function addTag($category, $value, $multiValue = true) { public function addTag($category, $value, $multiValue = true)
{
if ($multiValue) { if ($multiValue) {
//check for a duplicate tag, don't add the duplicate //check for a duplicate tag, don't add the duplicate
$currentTag = $this->Tags()->filter(array('Category' => $category, 'Value' => $value)); $currentTag = $this->Tags()->filter(array('Category' => $category, 'Value' => $value));
@ -312,9 +333,12 @@ class DMSDocument extends DataObject implements DMSDocumentInterface {
* *
* @return DataList * @return DataList
*/ */
protected function getTagsObjects($category, $value = null) { protected function getTagsObjects($category, $value = null)
{
$valueFilter = array("Category" => $category); $valueFilter = array("Category" => $category);
if (!empty($value)) $valueFilter['Value'] = $value; if (!empty($value)) {
$valueFilter['Value'] = $value;
}
$tags = $this->Tags()->filter($valueFilter); $tags = $this->Tags()->filter($valueFilter);
return $tags; return $tags;
@ -330,7 +354,8 @@ class DMSDocument extends DataObject implements DMSDocumentInterface {
* *
* @return array Strings of all the tags or null if there is no match found * @return array Strings of all the tags or null if there is no match found
*/ */
public function getTagsList($category, $value = null) { public function getTagsList($category, $value = null)
{
$tags = $this->getTagsObjects($category, $value); $tags = $this->getTagsObjects($category, $value);
$returnArray = null; $returnArray = null;
@ -360,7 +385,8 @@ class DMSDocument extends DataObject implements DMSDocumentInterface {
* *
* @return DMSDocument * @return DMSDocument
*/ */
public function removeTag($category, $value = null) { public function removeTag($category, $value = null)
{
$tags = $this->getTagsObjects($category, $value); $tags = $this->getTagsObjects($category, $value);
if ($tags->Count() > 0) { if ($tags->Count() > 0) {
@ -371,7 +397,9 @@ class DMSDocument extends DataObject implements DMSDocumentInterface {
$documentList->remove($this); $documentList->remove($this);
//delete the entire tag if it has no relations left //delete the entire tag if it has no relations left
if ($documentList->Count() == 0) $t->delete(); if ($documentList->Count() == 0) {
$t->delete();
}
} }
} }
@ -383,13 +411,16 @@ class DMSDocument extends DataObject implements DMSDocumentInterface {
* *
* @return DMSDocument * @return DMSDocument
*/ */
public function removeAllTags() { public function removeAllTags()
{
$allTags = $this->Tags(); $allTags = $this->Tags();
foreach ($allTags as $tag) { foreach ($allTags as $tag) {
$documentlist = $tag->Documents(); $documentlist = $tag->Documents();
$documentlist->remove($this); $documentlist->remove($this);
if ($tag->Documents()->Count() == 0) $tag->delete(); if ($tag->Documents()->Count() == 0) {
$tag->delete();
}
} }
return $this; return $this;
@ -400,14 +431,16 @@ class DMSDocument extends DataObject implements DMSDocumentInterface {
* *
* @return string * @return string
*/ */
public function getLink() { public function getLink()
{
return Controller::join_links(Director::baseURL(), 'dmsdocument/'.$this->ID); return Controller::join_links(Director::baseURL(), 'dmsdocument/'.$this->ID);
} }
/** /**
* @return string * @return string
*/ */
public function Link() { public function Link()
{
return $this->getLink(); return $this->getLink();
} }
@ -422,10 +455,13 @@ class DMSDocument extends DataObject implements DMSDocumentInterface {
* *
* @return DMSDocument * @return DMSDocument
*/ */
public function embargoIndefinitely($write = true) { public function embargoIndefinitely($write = true)
{
$this->EmbargoedIndefinitely = true; $this->EmbargoedIndefinitely = true;
if ($write) $this->write(); if ($write) {
$this->write();
}
return $this; return $this;
} }
@ -437,10 +473,13 @@ class DMSDocument extends DataObject implements DMSDocumentInterface {
* *
* @return DMSDocument * @return DMSDocument
*/ */
public function embargoUntilPublished($write = true) { public function embargoUntilPublished($write = true)
{
$this->EmbargoedUntilPublished = true; $this->EmbargoedUntilPublished = true;
if ($write) $this->write(); if ($write) {
$this->write();
}
return $this; return $this;
} }
@ -456,7 +495,8 @@ class DMSDocument extends DataObject implements DMSDocumentInterface {
* *
* @return bool * @return bool
*/ */
public function isHidden() { public function isHidden()
{
$hidden = $this->isEmbargoed() || $this->isExpired(); $hidden = $this->isEmbargoed() || $this->isExpired();
$readingMode = Versioned::get_reading_mode(); $readingMode = Versioned::get_reading_mode();
@ -474,7 +514,8 @@ class DMSDocument extends DataObject implements DMSDocumentInterface {
* *
* @return bool * @return bool
*/ */
public function isEmbargoed() { public function isEmbargoed()
{
if (is_object($this->EmbargoedUntilDate)) { if (is_object($this->EmbargoedUntilDate)) {
$this->EmbargoedUntilDate = $this->EmbargoedUntilDate->Value; $this->EmbargoedUntilDate = $this->EmbargoedUntilDate->Value;
} }
@ -503,10 +544,13 @@ class DMSDocument extends DataObject implements DMSDocumentInterface {
* *
* @return DMSDocument * @return DMSDocument
*/ */
public function embargoUntilDate($datetime, $write = true) { public function embargoUntilDate($datetime, $write = true)
{
$this->EmbargoedUntilDate = DBField::create_field('SS_Datetime', $datetime)->Format('Y-m-d H:i:s'); $this->EmbargoedUntilDate = DBField::create_field('SS_Datetime', $datetime)->Format('Y-m-d H:i:s');
if ($write) $this->write(); if ($write) {
$this->write();
}
return $this; return $this;
} }
@ -519,12 +563,15 @@ class DMSDocument extends DataObject implements DMSDocumentInterface {
* *
* @return DMSDocument * @return DMSDocument
*/ */
public function clearEmbargo($write = true) { public function clearEmbargo($write = true)
{
$this->EmbargoedIndefinitely = false; $this->EmbargoedIndefinitely = false;
$this->EmbargoedUntilPublished = false; $this->EmbargoedUntilPublished = false;
$this->EmbargoedUntilDate = null; $this->EmbargoedUntilDate = null;
if ($write) $this->write(); if ($write) {
$this->write();
}
return $this; return $this;
} }
@ -534,7 +581,8 @@ class DMSDocument extends DataObject implements DMSDocumentInterface {
* *
* @return bool * @return bool
*/ */
public function isExpired() { public function isExpired()
{
if (is_object($this->ExpireAtDate)) { if (is_object($this->ExpireAtDate)) {
$this->ExpireAtDate = $this->ExpireAtDate->Value; $this->ExpireAtDate = $this->ExpireAtDate->Value;
} }
@ -559,10 +607,13 @@ class DMSDocument extends DataObject implements DMSDocumentInterface {
* *
* @return DMSDocument * @return DMSDocument
*/ */
public function expireAtDate($datetime, $write = true) { public function expireAtDate($datetime, $write = true)
{
$this->ExpireAtDate = DBField::create_field('SS_Datetime', $datetime)->Format('Y-m-d H:i:s'); $this->ExpireAtDate = DBField::create_field('SS_Datetime', $datetime)->Format('Y-m-d H:i:s');
if ($write) $this->write(); if ($write) {
$this->write();
}
return $this; return $this;
} }
@ -574,10 +625,13 @@ class DMSDocument extends DataObject implements DMSDocumentInterface {
* *
* @return DMSDocument * @return DMSDocument
*/ */
public function clearExpiry($write = true) { public function clearExpiry($write = true)
{
$this->ExpireAtDate = null; $this->ExpireAtDate = null;
if ($write) $this->write(); if ($write) {
$this->write();
}
return $this; return $this;
} }
@ -593,7 +647,8 @@ class DMSDocument extends DataObject implements DMSDocumentInterface {
* *
* @return DataList List of Document objects * @return DataList List of Document objects
*/ */
public function getVersions() { public function getVersions()
{
if (!DMSDocument_versions::$enable_versions) { if (!DMSDocument_versions::$enable_versions) {
throw new Exception("DMSDocument versions are disabled"); throw new Exception("DMSDocument versions are disabled");
} }
@ -606,7 +661,8 @@ class DMSDocument extends DataObject implements DMSDocumentInterface {
* *
* @return string * @return string
*/ */
public function getFullPath() { public function getFullPath()
{
if ($this->Filename) { if ($this->Filename) {
return DMS::get_dms_path() . DIRECTORY_SEPARATOR . $this->Folder . DIRECTORY_SEPARATOR . $this->Filename; return DMS::get_dms_path() . DIRECTORY_SEPARATOR . $this->Folder . DIRECTORY_SEPARATOR . $this->Filename;
} }
@ -619,7 +675,8 @@ class DMSDocument extends DataObject implements DMSDocumentInterface {
* *
* @return string * @return string
*/ */
public function getFileName() { public function getFileName()
{
if ($this->getField('Filename')) { if ($this->getField('Filename')) {
return $this->getField('Filename'); return $this->getField('Filename');
} else { } else {
@ -630,7 +687,8 @@ class DMSDocument extends DataObject implements DMSDocumentInterface {
/** /**
* @return string * @return string
*/ */
public function getName() { public function getName()
{
return $this->getField('Title'); return $this->getField('Title');
} }
@ -638,7 +696,8 @@ class DMSDocument extends DataObject implements DMSDocumentInterface {
/** /**
* @return string * @return string
*/ */
public function getFilenameWithoutID() { public function getFilenameWithoutID()
{
$filenameParts = explode('~', $this->Filename); $filenameParts = explode('~', $this->Filename);
$filename = array_pop($filenameParts); $filename = array_pop($filenameParts);
@ -648,7 +707,8 @@ class DMSDocument extends DataObject implements DMSDocumentInterface {
/** /**
* @return string * @return string
*/ */
public function getStorageFolder() { public function getStorageFolder()
{
return DMS::get_dms_path() . DIRECTORY_SEPARATOR . DMS::get_storage_folder($this->ID); return DMS::get_dms_path() . DIRECTORY_SEPARATOR . DMS::get_storage_folder($this->ID);
} }
@ -659,7 +719,8 @@ class DMSDocument extends DataObject implements DMSDocumentInterface {
* *
* @return void * @return void
*/ */
public function delete() { public function delete()
{
// remove tags // remove tags
$this->removeAllTags(); $this->removeAllTags();
@ -716,7 +777,8 @@ class DMSDocument extends DataObject implements DMSDocumentInterface {
* *
* @return DMSDocument * @return DMSDocument
*/ */
public function storeDocument($filePath) { public function storeDocument($filePath)
{
if (empty($this->ID)) { if (empty($this->ID)) {
user_error("Document must be written to database before it can store documents", E_USER_ERROR); user_error("Document must be written to database before it can store documents", E_USER_ERROR);
} }
@ -737,7 +799,9 @@ class DMSDocument extends DataObject implements DMSDocumentInterface {
DMSDocument_versions::create_version($this); DMSDocument_versions::create_version($this);
} else { //otherwise delete the old document file } else { //otherwise delete the old document file
$oldPath = $this->getFullPath(); $oldPath = $this->getFullPath();
if (file_exists($oldPath)) unlink($oldPath); if (file_exists($oldPath)) {
unlink($oldPath);
}
} }
copy($fromPath, $toPath); //this will overwrite the existing file (if present) copy($fromPath, $toPath); //this will overwrite the existing file (if present)
@ -768,7 +832,8 @@ class DMSDocument extends DataObject implements DMSDocumentInterface {
* *
* @return DMSDocument object that we replaced the file in * @return DMSDocument object that we replaced the file in
*/ */
public function replaceDocument($file) { public function replaceDocument($file)
{
$filePath = DMS::transform_file_to_file_path($file); $filePath = DMS::transform_file_to_file_path($file);
$doc = $this->storeDocument($filePath); // replace the document $doc = $this->storeDocument($filePath); // replace the document
@ -784,7 +849,8 @@ class DMSDocument extends DataObject implements DMSDocumentInterface {
* *
* @return string * @return string
*/ */
public static function get_file_type($ext) { public static function get_file_type($ext)
{
$types = array( $types = array(
'gif' => 'GIF image - good for diagrams', 'gif' => 'GIF image - good for diagrams',
'jpg' => 'JPEG image - good for photos', 'jpg' => 'JPEG image - good for photos',
@ -819,14 +885,16 @@ class DMSDocument extends DataObject implements DMSDocumentInterface {
* *
* @return string * @return string
*/ */
public function getDescriptionWithLineBreak() { public function getDescriptionWithLineBreak()
{
return nl2br($this->getField('Description')); return nl2br($this->getField('Description'));
} }
/** /**
* @return FieldList * @return FieldList
*/ */
public function getCMSFields() { public function getCMSFields()
{
//include JS to handling showing and hiding of bottom "action" tabs //include JS to handling showing and hiding of bottom "action" tabs
Requirements::javascript(DMS_DIR.'/javascript/DMSDocumentCMSFields.js'); Requirements::javascript(DMS_DIR.'/javascript/DMSDocumentCMSFields.js');
Requirements::css(DMS_DIR.'/css/DMSDocumentCMSFields.css'); Requirements::css(DMS_DIR.'/css/DMSDocumentCMSFields.css');
@ -920,15 +988,21 @@ class DMSDocument extends DataObject implements DMSDocumentInterface {
'</ul></div>')); '</ul></div>'));
$embargoValue = 'None'; $embargoValue = 'None';
if ($this->EmbargoedIndefinitely) $embargoValue = 'Indefinitely'; if ($this->EmbargoedIndefinitely) {
elseif ($this->EmbargoedUntilPublished) $embargoValue = 'Published'; $embargoValue = 'Indefinitely';
elseif (!empty($this->EmbargoedUntilDate)) $embargoValue = 'Date'; } elseif ($this->EmbargoedUntilPublished) {
$embargoValue = 'Published';
} elseif (!empty($this->EmbargoedUntilDate)) {
$embargoValue = 'Date';
}
$embargo = new OptionsetField('Embargo', 'Embargo', array('None'=>'None', 'Published'=>'Hide document until page is published', 'Indefinitely'=>'Hide document indefinitely', 'Date'=>'Hide until set date'), $embargoValue); $embargo = new OptionsetField('Embargo', 'Embargo', array('None'=>'None', 'Published'=>'Hide document until page is published', 'Indefinitely'=>'Hide document indefinitely', 'Date'=>'Hide until set date'), $embargoValue);
$embargoDatetime = DatetimeField::create('EmbargoedUntilDate', ''); $embargoDatetime = DatetimeField::create('EmbargoedUntilDate', '');
$embargoDatetime->getDateField()->setConfig('showcalendar', true)->setConfig('dateformat', 'dd-MM-yyyy')->setConfig('datavalueformat', 'dd-MM-yyyy'); $embargoDatetime->getDateField()->setConfig('showcalendar', true)->setConfig('dateformat', 'dd-MM-yyyy')->setConfig('datavalueformat', 'dd-MM-yyyy');
$expiryValue = 'None'; $expiryValue = 'None';
if (!empty($this->ExpireAtDate)) $expiryValue = 'Date'; if (!empty($this->ExpireAtDate)) {
$expiryValue = 'Date';
}
$expiry = new OptionsetField('Expiry', 'Expiry', array('None'=>'None', 'Date'=>'Set document to expire on'), $expiryValue); $expiry = new OptionsetField('Expiry', 'Expiry', array('None'=>'None', 'Date'=>'Set document to expire on'), $expiryValue);
$expiryDatetime = DatetimeField::create('ExpireAtDate', ''); $expiryDatetime = DatetimeField::create('ExpireAtDate', '');
$expiryDatetime->getDateField()->setConfig('showcalendar', true)->setConfig('dateformat', 'dd-MM-yyyy')->setConfig('datavalueformat', 'dd-MM-yyyy'); $expiryDatetime->getDateField()->setConfig('showcalendar', true)->setConfig('dateformat', 'dd-MM-yyyy')->setConfig('datavalueformat', 'dd-MM-yyyy');
@ -993,7 +1067,8 @@ class DMSDocument extends DataObject implements DMSDocumentInterface {
return $fields; return $fields;
} }
public function onBeforeWrite() { public function onBeforeWrite()
{
parent::onBeforeWrite(); parent::onBeforeWrite();
if (isset($this->Embargo)) { if (isset($this->Embargo)) {
@ -1002,14 +1077,23 @@ class DMSDocument extends DataObject implements DMSDocumentInterface {
$savedDate = $this->EmbargoedUntilDate; $savedDate = $this->EmbargoedUntilDate;
$this->clearEmbargo(false); //clear all previous settings and re-apply them on save $this->clearEmbargo(false); //clear all previous settings and re-apply them on save
if ($this->Embargo == 'Published') $this->embargoUntilPublished(false); if ($this->Embargo == 'Published') {
if ($this->Embargo == 'Indefinitely') $this->embargoIndefinitely(false); $this->embargoUntilPublished(false);
if ($this->Embargo == 'Date') $this->embargoUntilDate($savedDate, false); }
if ($this->Embargo == 'Indefinitely') {
$this->embargoIndefinitely(false);
}
if ($this->Embargo == 'Date') {
$this->embargoUntilDate($savedDate, false);
}
} }
if (isset($this->Expiry)) { if (isset($this->Expiry)) {
if ($this->Expiry == 'Date') $this->expireAtDate($this->ExpireAtDate, false); if ($this->Expiry == 'Date') {
else $this->clearExpiry(false); //clear all previous settings $this->expireAtDate($this->ExpireAtDate, false);
} else {
$this->clearExpiry(false);
} //clear all previous settings
} }
} }
@ -1021,7 +1105,8 @@ class DMSDocument extends DataObject implements DMSDocumentInterface {
* *
* @return string * @return string
*/ */
public function Icon($ext) { public function Icon($ext)
{
if (!Director::fileExists(DMS_DIR."/images/app_icons/{$ext}_32.png")) { if (!Director::fileExists(DMS_DIR."/images/app_icons/{$ext}_32.png")) {
$ext = File::get_app_category($ext); $ext = File::get_app_category($ext);
} }
@ -1038,14 +1123,16 @@ class DMSDocument extends DataObject implements DMSDocumentInterface {
* *
* @return string * @return string
*/ */
public function getExtension() { public function getExtension()
{
return strtolower(pathinfo($this->Filename, PATHINFO_EXTENSION)); return strtolower(pathinfo($this->Filename, PATHINFO_EXTENSION));
} }
/** /**
* @return string * @return string
*/ */
public function getSize() { public function getSize()
{
$size = $this->getAbsoluteSize(); $size = $this->getAbsoluteSize();
return ($size) ? File::format_size($size) : false; return ($size) ? File::format_size($size) : false;
} }
@ -1055,7 +1142,8 @@ class DMSDocument extends DataObject implements DMSDocumentInterface {
* *
* @return string * @return string
*/ */
public function getAbsoluteSize() { public function getAbsoluteSize()
{
return file_exists($this->getFullPath()) ? filesize($this->getFullPath()) : null; return file_exists($this->getFullPath()) ? filesize($this->getFullPath()) : null;
} }
@ -1064,7 +1152,8 @@ class DMSDocument extends DataObject implements DMSDocumentInterface {
* *
* @return string * @return string
*/ */
public function getFileSizeFormatted() { public function getFileSizeFormatted()
{
return $this->getSize(); return $this->getSize();
} }
@ -1072,7 +1161,8 @@ class DMSDocument extends DataObject implements DMSDocumentInterface {
/** /**
* @return FieldList * @return FieldList
*/ */
protected function getFieldsForFile($relationListCount) { protected function getFieldsForFile($relationListCount)
{
$extension = $this->getExtension(); $extension = $this->getExtension();
$previewField = new LiteralField("ImageFull", $previewField = new LiteralField("ImageFull",
@ -1082,10 +1172,14 @@ class DMSDocument extends DataObject implements DMSDocumentInterface {
//count the number of pages this document is published on //count the number of pages this document is published on
$publishedOnCount = $this->Pages()->Count(); $publishedOnCount = $this->Pages()->Count();
$publishedOnValue = "$publishedOnCount pages"; $publishedOnValue = "$publishedOnCount pages";
if ($publishedOnCount == 1) $publishedOnValue = "$publishedOnCount page"; if ($publishedOnCount == 1) {
$publishedOnValue = "$publishedOnCount page";
}
$relationListCountValue = "$relationListCount pages"; $relationListCountValue = "$relationListCount pages";
if ($relationListCount == 1) $relationListCountValue = "$relationListCount page"; if ($relationListCount == 1) {
$relationListCountValue = "$relationListCount page";
}
$fields = new FieldGroup( $fields = new FieldGroup(
$filePreview = CompositeField::create( $filePreview = CompositeField::create(
@ -1126,27 +1220,29 @@ class DMSDocument extends DataObject implements DMSDocumentInterface {
* *
* @return DMSDocument * @return DMSDocument
*/ */
public function ingestFile($file) { public function ingestFile($file)
{
$this->replaceDocument($file); $this->replaceDocument($file);
$file->delete(); $file->delete();
return $this; return $this;
} }
} }
/** /**
* @package dms * @package dms
*/ */
class DMSDocument_Controller extends Controller { class DMSDocument_Controller extends Controller
{
static $testMode = false; //mode to switch for testing. Does not return document download, just document URL public static $testMode = false; //mode to switch for testing. Does not return document download, just document URL
private static $allowed_actions = array( private static $allowed_actions = array(
'index' 'index'
); );
public function init() { public function init()
{
Versioned::choose_site_stage(); Versioned::choose_site_stage();
parent::init(); parent::init();
} }
@ -1155,7 +1251,8 @@ class DMSDocument_Controller extends Controller {
* Returns the document object from the request object's ID parameter. * Returns the document object from the request object's ID parameter.
* Returns null, if no document found * Returns null, if no document found
*/ */
protected function getDocumentFromID($request) { protected function getDocumentFromID($request)
{
$doc = null; $doc = null;
$id = Convert::raw2sql($request->param('ID')); $id = Convert::raw2sql($request->param('ID'));
@ -1176,7 +1273,8 @@ class DMSDocument_Controller extends Controller {
* Access the file download without redirecting user, so we can block direct * Access the file download without redirecting user, so we can block direct
* access to documents. * access to documents.
*/ */
public function index(SS_HTTPRequest $request) { public function index(SS_HTTPRequest $request)
{
$doc = $this->getDocumentFromID($request); $doc = $this->getDocumentFromID($request);
if (!empty($doc)) { if (!empty($doc)) {
@ -1203,11 +1301,15 @@ class DMSDocument_Controller extends Controller {
} }
// check for embargo or expiry // check for embargo or expiry
if ($doc->isHidden()) $canView = false; if ($doc->isHidden()) {
$canView = false;
}
//admins can always download any document, even if otherwise hidden //admins can always download any document, even if otherwise hidden
$member = Member::currentUser(); $member = Member::currentUser();
if ($member && Permission::checkMember($member, 'ADMIN')) $canView = true; if ($member && Permission::checkMember($member, 'ADMIN')) {
$canView = true;
}
if ($canView) { if ($canView) {
$path = $doc->getFullPath(); $path = $doc->getFullPath();
@ -1217,14 +1319,12 @@ class DMSDocument_Controller extends Controller {
// discover the mime type properly // discover the mime type properly
$finfo = finfo_open(FILEINFO_MIME_TYPE); $finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($finfo, $path); $mime = finfo_file($finfo, $path);
} } elseif (is_executable($fileBin)) {
else if ( is_executable($fileBin) ) {
// try to use the system tool // try to use the system tool
$mime = `$fileBin -i -b $path`; $mime = `$fileBin -i -b $path`;
$mime = explode(';', $mime); $mime = explode(';', $mime);
$mime = trim($mime[0]); $mime = trim($mime[0]);
} } else {
else {
// make do with what we have // make do with what we have
$ext = $doc->getExtension(); $ext = $doc->getExtension();
if ($ext =='pdf') { if ($ext =='pdf') {
@ -1236,7 +1336,9 @@ class DMSDocument_Controller extends Controller {
} }
} }
if (self::$testMode) return $path; if (self::$testMode) {
return $path;
}
//if a DMSDocument can be downloaded and all the permissions/privileges has passed, //if a DMSDocument can be downloaded and all the permissions/privileges has passed,
//its ViewCount should be increased by 1 just before the browser sending the file to front. //its ViewCount should be increased by 1 just before the browser sending the file to front.
@ -1244,7 +1346,9 @@ class DMSDocument_Controller extends Controller {
header('Content-Type: ' . $mime); header('Content-Type: ' . $mime);
header('Content-Length: ' . filesize($path), null); header('Content-Length: ' . filesize($path), null);
if (!empty($mime) && $mime != "text/html") header('Content-Disposition: attachment; filename="'.$doc->getFilenameWithoutID().'"'); if (!empty($mime) && $mime != "text/html") {
header('Content-Disposition: attachment; filename="'.$doc->getFilenameWithoutID().'"');
}
header('Content-transfer-encoding: 8bit'); header('Content-transfer-encoding: 8bit');
header('Expires: 0'); header('Expires: 0');
header('Pragma: cache'); header('Pragma: cache');
@ -1256,7 +1360,9 @@ class DMSDocument_Controller extends Controller {
} }
} }
if (self::$testMode) return 'This asset does not exist.'; if (self::$testMode) {
return 'This asset does not exist.';
}
$this->httpError(404, 'This asset does not exist.'); $this->httpError(404, 'This asset does not exist.');
} }
} }

View File

@ -9,7 +9,8 @@
* *
* @package dms * @package dms
*/ */
class DMSDocument_versions extends DataObject { class DMSDocument_versions extends DataObject
{
/** /**
* @var bool $enable_versions Flag that turns on or off versions of * @var bool $enable_versions Flag that turns on or off versions of
@ -62,7 +63,8 @@ class DMSDocument_versions extends DataObject {
* *
* @return bool Success or failure * @return bool Success or failure
*/ */
public static function create_version(DMSDocument $doc) { public static function create_version(DMSDocument $doc)
{
$success = false; $success = false;
$existingPath = $doc->getFullPath(); $existingPath = $doc->getFullPath();
@ -95,10 +97,13 @@ class DMSDocument_versions extends DataObject {
return $success; return $success;
} }
public function delete() { public function delete()
{
$path = $this->getFullPath(); $path = $this->getFullPath();
if (file_exists($path)) unlink($path); if (file_exists($path)) {
unlink($path);
}
parent::delete(); parent::delete();
} }
@ -112,12 +117,16 @@ class DMSDocument_versions extends DataObject {
* *
* @return DataList List of Document objects * @return DataList List of Document objects
*/ */
static function get_versions(DMSDocument $doc) { public static function get_versions(DMSDocument $doc)
if (!DMSDocument_versions::$enable_versions) user_error("DMSDocument versions are disabled",E_USER_WARNING); {
if (!DMSDocument_versions::$enable_versions) {
user_error("DMSDocument versions are disabled", E_USER_WARNING);
}
return DMSDocument_versions::get()->filter(array('DocumentID' => $doc->ID)); return DMSDocument_versions::get()->filter(array('DocumentID' => $doc->ID));
} }
public function __construct($record = null, $isSingleton = false, $model = null) { public function __construct($record = null, $isSingleton = false, $model = null)
{
//check what the constructor was passed //check what the constructor was passed
$dmsObject = null; $dmsObject = null;
if ($record && is_subclass_of($record, 'DMSDocumentInterface')) { if ($record && is_subclass_of($record, 'DMSDocumentInterface')) {
@ -141,7 +150,8 @@ class DMSDocument_versions extends DataObject {
* *
* @return string * @return string
*/ */
public function getLink() { public function getLink()
{
return Controller::join_links(Director::baseURL(), 'dmsdocument/version'.$this->ID); return Controller::join_links(Director::baseURL(), 'dmsdocument/version'.$this->ID);
} }
@ -151,7 +161,8 @@ class DMSDocument_versions extends DataObject {
* *
* @return bool * @return bool
*/ */
public function isHidden() { public function isHidden()
{
return true; return true;
} }
@ -163,15 +174,19 @@ class DMSDocument_versions extends DataObject {
* *
* @return string * @return string
*/ */
public function getFullPath($filename = null) { public function getFullPath($filename = null)
if (!$filename) $filename = $this->Filename; {
if (!$filename) {
$filename = $this->Filename;
}
return DMS::get_dms_path() . DIRECTORY_SEPARATOR . $this->Folder . DIRECTORY_SEPARATOR . $filename; return DMS::get_dms_path() . DIRECTORY_SEPARATOR . $this->Folder . DIRECTORY_SEPARATOR . $filename;
} }
/** /**
* @return string * @return string
*/ */
public function getFilenameWithoutID() { public function getFilenameWithoutID()
{
$filenameParts = explode('~', $this->Filename); $filenameParts = explode('~', $this->Filename);
$filename = array_pop($filenameParts); $filename = array_pop($filenameParts);
@ -186,7 +201,8 @@ class DMSDocument_versions extends DataObject {
* *
* @return string The new filename * @return string The new filename
*/ */
protected function generateVersionedFilename(DMSDocument $doc, $versionCounter) { protected function generateVersionedFilename(DMSDocument $doc, $versionCounter)
{
$filename = $doc->Filename; $filename = $doc->Filename;
do { do {
@ -208,14 +224,16 @@ class DMSDocument_versions extends DataObject {
* *
* @return string * @return string
*/ */
public function getExtension() { public function getExtension()
{
return strtolower(pathinfo($this->Filename, PATHINFO_EXTENSION)); return strtolower(pathinfo($this->Filename, PATHINFO_EXTENSION));
} }
/** /**
* @return string * @return string
*/ */
public function getSize() { public function getSize()
{
$size = $this->getAbsoluteSize(); $size = $this->getAbsoluteSize();
return ($size) ? File::format_size($size) : false; return ($size) ? File::format_size($size) : false;
@ -226,7 +244,8 @@ class DMSDocument_versions extends DataObject {
* *
* @return string * @return string
*/ */
public function getAbsoluteSize() { public function getAbsoluteSize()
{
return filesize($this->getFullPath()); return filesize($this->getFullPath());
} }
@ -235,14 +254,16 @@ class DMSDocument_versions extends DataObject {
* *
* @return string * @return string
*/ */
public function getFileSizeFormatted() { public function getFileSizeFormatted()
{
return $this->getSize(); return $this->getSize();
} }
/** /**
* @return DMSDocument_versions * @return DMSDocument_versions
*/ */
public function trackView() { public function trackView()
{
if ($this->ID > 0) { if ($this->ID > 0) {
$this->VersionViewCount++; $this->VersionViewCount++;
@ -253,5 +274,4 @@ class DMSDocument_versions extends DataObject {
return $this; return $this;
} }
} }

View File

@ -5,7 +5,8 @@
* *
* @package dms * @package dms
*/ */
class DMSTag extends DataObject { class DMSTag extends DataObject
{
private static $db = array( private static $db = array(
'Category' => 'Varchar(1024)', 'Category' => 'Varchar(1024)',

View File

@ -9,7 +9,8 @@
* search across dozens of columns and tables - but for a couple of hundred pages * search across dozens of columns and tables - but for a couple of hundred pages
* and occasionally use its a feasible solution. * and occasionally use its a feasible solution.
*/ */
class ShortCodeRelationFinder { class ShortCodeRelationFinder
{
/** /**
* @var String Regex matching a {@link DBField} class name which is shortcode capable. * @var String Regex matching a {@link DBField} class name which is shortcode capable.
@ -24,13 +25,15 @@ class ShortCodeRelationFinder {
* @param String Shortcode index number to find * @param String Shortcode index number to find
* @return array IDs * @return array IDs
*/ */
function findPageIDs($number) { public function findPageIDs($number)
{
$list = $this->getList($number); $list = $this->getList($number);
$found = $list->column(); $found = $list->column();
return $found; return $found;
} }
function findPageCount($number) { public function findPageCount($number)
{
$list = $this->getList($number); $list = $this->getList($number);
return $list->count(); return $list->count();
} }
@ -38,13 +41,16 @@ class ShortCodeRelationFinder {
/** /**
* @return DataList * @return DataList
*/ */
function getList($number) { public function getList($number)
{
$list = DataList::create('SiteTree'); $list = DataList::create('SiteTree');
$where = array(); $where = array();
$fields = $this->getShortCodeFields('SiteTree'); $fields = $this->getShortCodeFields('SiteTree');
foreach ($fields as $ancClass => $ancFields) { foreach ($fields as $ancClass => $ancFields) {
foreach ($ancFields as $ancFieldName => $ancFieldSpec) { foreach ($ancFields as $ancFieldName => $ancFieldSpec) {
if ($ancClass != "SiteTree") $list = $list->leftJoin($ancClass,'"'.$ancClass.'"."ID" = "SiteTree"."ID"'); if ($ancClass != "SiteTree") {
$list = $list->leftJoin($ancClass, '"'.$ancClass.'"."ID" = "SiteTree"."ID"');
}
$where[] = "\"$ancClass\".\"$ancFieldName\" LIKE '%[dms_document_link,id=$number]%'"; //."%s" LIKE ""', $where[] = "\"$ancClass\".\"$ancFieldName\" LIKE '%[dms_document_link,id=$number]%'"; //."%s" LIKE ""',
} }
} }
@ -59,23 +65,29 @@ class ShortCodeRelationFinder {
* @param String * @param String
* @return Array Map of class names to an array of field names on these classes. * @return Array Map of class names to an array of field names on these classes.
*/ */
function getShortcodeFields($class) { public function getShortcodeFields($class)
{
$fields = array(); $fields = array();
$ancestry = array_values(ClassInfo::dataClassesFor($class)); $ancestry = array_values(ClassInfo::dataClassesFor($class));
foreach ($ancestry as $ancestor) { foreach ($ancestry as $ancestor) {
if(ClassInfo::classImplements($ancestor, 'TestOnly')) continue; if (ClassInfo::classImplements($ancestor, 'TestOnly')) {
continue;
}
$ancFields = DataObject::custom_database_fields($ancestor); $ancFields = DataObject::custom_database_fields($ancestor);
if($ancFields) foreach($ancFields as $ancFieldName => $ancFieldSpec) { if ($ancFields) {
foreach ($ancFields as $ancFieldName => $ancFieldSpec) {
if (preg_match($this->fieldSpecRegex, $ancFieldSpec)) { if (preg_match($this->fieldSpecRegex, $ancFieldSpec)) {
if(!@$fields[$ancestor]) $fields[$ancestor] = array(); if (!@$fields[$ancestor]) {
$fields[$ancestor] = array();
}
$fields[$ancestor][$ancFieldName] = $ancFieldSpec; $fields[$ancestor][$ancFieldName] = $ancFieldSpec;
} }
} }
} }
}
return $fields; return $fields;
} }
} }

View File

@ -1,9 +1,11 @@
<?php <?php
class DMSDocumentTest extends SapphireTest { class DMSDocumentTest extends SapphireTest
{
static $fixture_file = "dms/tests/dmstest.yml"; public static $fixture_file = "dms/tests/dmstest.yml";
function tearDownOnce() { public function tearDownOnce()
{
self::$is_running_test = true; self::$is_running_test = true;
$d = DataObject::get("DMSDocument"); $d = DataObject::get("DMSDocument");
@ -18,7 +20,8 @@ class DMSDocumentTest extends SapphireTest {
self::$is_running_test = $this->originalIsRunningTest; self::$is_running_test = $this->originalIsRunningTest;
} }
function testPageRelations() { public function testPageRelations()
{
$s1 = $this->objFromFixture('SiteTree', 's1'); $s1 = $this->objFromFixture('SiteTree', 's1');
$s2 = $this->objFromFixture('SiteTree', 's2'); $s2 = $this->objFromFixture('SiteTree', 's2');
$s3 = $this->objFromFixture('SiteTree', 's3'); $s3 = $this->objFromFixture('SiteTree', 's3');
@ -38,7 +41,8 @@ class DMSDocumentTest extends SapphireTest {
$this->assertEquals($pagesArray[5]->ID, $s6->ID, "Page 6 associated correctly"); $this->assertEquals($pagesArray[5]->ID, $s6->ID, "Page 6 associated correctly");
} }
function testAddPageRelation() { public function testAddPageRelation()
{
$s1 = $this->objFromFixture('SiteTree', 's1'); $s1 = $this->objFromFixture('SiteTree', 's1');
$s2 = $this->objFromFixture('SiteTree', 's2'); $s2 = $this->objFromFixture('SiteTree', 's2');
$s3 = $this->objFromFixture('SiteTree', 's3'); $s3 = $this->objFromFixture('SiteTree', 's3');
@ -77,7 +81,8 @@ class DMSDocumentTest extends SapphireTest {
$this->assertNotContains($doc, $documentsArray, "Document no longer associated with page"); $this->assertNotContains($doc, $documentsArray, "Document no longer associated with page");
} }
function testDeletingPageWithAssociatedDocuments() { public function testDeletingPageWithAssociatedDocuments()
{
$s1 = $this->objFromFixture('SiteTree', 's1'); $s1 = $this->objFromFixture('SiteTree', 's1');
$s2 = $this->objFromFixture('SiteTree', 's2'); $s2 = $this->objFromFixture('SiteTree', 's2');
$s2->publish('Stage', 'Live'); $s2->publish('Stage', 'Live');
@ -120,7 +125,8 @@ class DMSDocumentTest extends SapphireTest {
); );
} }
function testUnpublishPageWithAssociatedDocuments() { public function testUnpublishPageWithAssociatedDocuments()
{
$s2 = $this->objFromFixture('SiteTree', 's2'); $s2 = $this->objFromFixture('SiteTree', 's2');
$s2->publish('Stage', 'Live'); $s2->publish('Stage', 'Live');
$s2ID = $s2->ID; $s2ID = $s2->ID;
@ -151,5 +157,4 @@ class DMSDocumentTest extends SapphireTest {
."associated with causes that document to be deleted as well" ."associated with causes that document to be deleted as well"
); );
} }
} }

View File

@ -1,9 +1,11 @@
<?php <?php
class DMSEmbargoTest extends SapphireTest { class DMSEmbargoTest extends SapphireTest
{
static $fixture_file = "dms/tests/dmsembargotest.yml"; public static $fixture_file = "dms/tests/dmsembargotest.yml";
function tearDownOnce() { public function tearDownOnce()
{
self::$is_running_test = true; self::$is_running_test = true;
$d = DataObject::get("DMSDocument"); $d = DataObject::get("DMSDocument");
@ -18,13 +20,15 @@ class DMSEmbargoTest extends SapphireTest {
self::$is_running_test = $this->originalIsRunningTest; self::$is_running_test = $this->originalIsRunningTest;
} }
function createFakeHTTPRequest($id) { public function createFakeHTTPRequest($id)
{
$r = new SS_HTTPRequest('GET', 'index/'.$id); $r = new SS_HTTPRequest('GET', 'index/'.$id);
$r->match('index/$ID'); $r->match('index/$ID');
return $r; return $r;
} }
function testBasicEmbargo() { public function testBasicEmbargo()
{
$oldDMSFolder = DMS::$dmsFolder; $oldDMSFolder = DMS::$dmsFolder;
DMS::$dmsFolder = DMS_DIR; //sneakily setting the DMS folder to the folder where the test file lives DMS::$dmsFolder = DMS_DIR; //sneakily setting the DMS folder to the folder where the test file lives
@ -52,7 +56,8 @@ class DMSEmbargoTest extends SapphireTest {
DMS::$dmsFolder = $oldDMSFolder; DMS::$dmsFolder = $oldDMSFolder;
} }
function testEmbargoIndefinitely() { public function testEmbargoIndefinitely()
{
$doc = new DMSDocument(); $doc = new DMSDocument();
$doc->Filename = "DMS-test-lorum-file.pdf"; $doc->Filename = "DMS-test-lorum-file.pdf";
$doc->Folder = "tests"; $doc->Folder = "tests";
@ -67,10 +72,10 @@ class DMSEmbargoTest extends SapphireTest {
$this->assertFalse($doc->isHidden(), "Document is not hidden"); $this->assertFalse($doc->isHidden(), "Document is not hidden");
$this->assertFalse($doc->isEmbargoed(), "Document is not embargoed"); $this->assertFalse($doc->isEmbargoed(), "Document is not embargoed");
$this->assertFalse($doc->isExpired(), "Document is not expired"); $this->assertFalse($doc->isExpired(), "Document is not expired");
} }
function testExpireAtDate() { public function testExpireAtDate()
{
$doc = new DMSDocument(); $doc = new DMSDocument();
$doc->Filename = "DMS-test-lorum-file.pdf"; $doc->Filename = "DMS-test-lorum-file.pdf";
$doc->Folder = "tests"; $doc->Folder = "tests";
@ -104,7 +109,8 @@ class DMSEmbargoTest extends SapphireTest {
$this->assertFalse($doc->isExpired(), "Document is not expired"); $this->assertFalse($doc->isExpired(), "Document is not expired");
} }
function testEmbargoUntilDate() { public function testEmbargoUntilDate()
{
$doc = new DMSDocument(); $doc = new DMSDocument();
$doc->Filename = "DMS-test-lorum-file.pdf"; $doc->Filename = "DMS-test-lorum-file.pdf";
$doc->Folder = "tests"; $doc->Folder = "tests";
@ -140,7 +146,8 @@ class DMSEmbargoTest extends SapphireTest {
$this->assertFalse($doc->isExpired(), "Document is not expired"); $this->assertFalse($doc->isExpired(), "Document is not expired");
} }
function testEmbargoUntilPublished() { public function testEmbargoUntilPublished()
{
$s1 = $this->objFromFixture('SiteTree', 's1'); $s1 = $this->objFromFixture('SiteTree', 's1');
$doc = new DMSDocument(); $doc = new DMSDocument();

View File

@ -5,9 +5,11 @@
* @package dms * @package dms
* @subpackage tests * @subpackage tests
*/ */
class DMSShortcodeTest extends SapphireTest { class DMSShortcodeTest extends SapphireTest
{
public function testShortcodeOperation() { public function testShortcodeOperation()
{
$file = 'dms/tests/DMS-test-lorum-file.pdf'; $file = 'dms/tests/DMS-test-lorum-file.pdf';
$document = DMS::inst()->storeDocument($file); $document = DMS::inst()->storeDocument($file);
@ -22,5 +24,4 @@ class DMSShortcodeTest extends SapphireTest {
$this->assertEquals($document->getExtension(), $link->getAttribute('data-ext')); $this->assertEquals($document->getExtension(), $link->getAttribute('data-ext'));
$this->assertEquals($document->getFileSizeFormatted(), $link->getAttribute('data-size')); $this->assertEquals($document->getFileSizeFormatted(), $link->getAttribute('data-size'));
} }
} }

View File

@ -1,7 +1,9 @@
<?php <?php
class DMSTagTest extends SapphireTest { class DMSTagTest extends SapphireTest
{
function tearDownOnce() { public function tearDownOnce()
{
self::$is_running_test = true; self::$is_running_test = true;
$d = DataObject::get("DMSDocument"); $d = DataObject::get("DMSDocument");
@ -16,7 +18,8 @@ class DMSTagTest extends SapphireTest {
self::$is_running_test = $this->originalIsRunningTest; self::$is_running_test = $this->originalIsRunningTest;
} }
function testAddingTags() { public function testAddingTags()
{
$doc = new DMSDocument(); $doc = new DMSDocument();
$doc->Filename = "test file"; $doc->Filename = "test file";
$doc->Folder = "0"; $doc->Folder = "0";
@ -62,7 +65,8 @@ class DMSTagTest extends SapphireTest {
$this->assertEquals($tags->Count(), 0, "No DMS tag objects remain after deletion"); $this->assertEquals($tags->Count(), 0, "No DMS tag objects remain after deletion");
} }
function testRemovingTags() { public function testRemovingTags()
{
$doc = new DMSDocument(); $doc = new DMSDocument();
$doc->Filename = "test file"; $doc->Filename = "test file";
$doc->Folder = "0"; $doc->Folder = "0";
@ -114,5 +118,4 @@ class DMSTagTest extends SapphireTest {
$tags = DataObject::get("DMSTag"); $tags = DataObject::get("DMSTag");
$this->assertEquals($tags->Count(), 0, "No DMS tag objects remain after deletion"); $this->assertEquals($tags->Count(), 0, "No DMS tag objects remain after deletion");
} }
} }

View File

@ -1,14 +1,16 @@
<?php <?php
class DMSTest extends FunctionalTest { class DMSTest extends FunctionalTest
{
static $testFile = 'dms/tests/DMS-test-lorum-file.pdf'; public static $testFile = 'dms/tests/DMS-test-lorum-file.pdf';
static $testFile2 = 'dms/tests/DMS-test-document-2.pdf'; public static $testFile2 = 'dms/tests/DMS-test-document-2.pdf';
//store values to reset back to after this test runs //store values to reset back to after this test runs
static $dmsFolderOld; public static $dmsFolderOld;
static $dmsFolderSizeOld; public static $dmsFolderSizeOld;
function setUp() { public function setUp()
{
parent::setUp(); parent::setUp();
self::$dmsFolderOld = DMS::$dmsFolder; self::$dmsFolderOld = DMS::$dmsFolder;
@ -21,7 +23,8 @@ class DMSTest extends FunctionalTest {
$this->delete(BASE_PATH . DIRECTORY_SEPARATOR . 'dms-assets-test-1234'); $this->delete(BASE_PATH . DIRECTORY_SEPARATOR . 'dms-assets-test-1234');
} }
function tearDown() { public function tearDown()
{
parent::tearDown(); parent::tearDown();
self::$is_running_test = true; self::$is_running_test = true;
@ -45,7 +48,8 @@ class DMSTest extends FunctionalTest {
self::$is_running_test = $this->originalIsRunningTest; self::$is_running_test = $this->originalIsRunningTest;
} }
public function delete($path) { public function delete($path)
{
if (file_exists($path) || is_dir($path)) { if (file_exists($path) || is_dir($path)) {
$it = new RecursiveIteratorIterator( $it = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($path), new RecursiveDirectoryIterator($path),
@ -65,7 +69,8 @@ class DMSTest extends FunctionalTest {
} }
function testDMSStorage() { public function testDMSStorage()
{
$dms = DMS::inst(); $dms = DMS::inst();
$file = self::$testFile; $file = self::$testFile;
@ -77,7 +82,8 @@ class DMSTest extends FunctionalTest {
//$title = $document->getTag('title'); //$title = $document->getTag('title');
} }
function testDMSFolderSpanning() { public function testDMSFolderSpanning()
{
DMS::$dmsFolderSize = 5; DMS::$dmsFolderSize = 5;
$dms = DMS::inst(); $dms = DMS::inst();
@ -105,7 +111,8 @@ class DMSTest extends FunctionalTest {
} }
} }
function testReplaceDocument() { public function testReplaceDocument()
{
$dms = DMS::inst(); $dms = DMS::inst();
//store the first document //store the first document
@ -124,7 +131,8 @@ class DMSTest extends FunctionalTest {
$this->assertEquals("My custom description", $document->Description, "Custom description not modified"); $this->assertEquals("My custom description", $document->Description, "Custom description not modified");
} }
function testDownloadDocument() { public function testDownloadDocument()
{
// $dms = DMS::inst(); // $dms = DMS::inst();
// //
// //store the first document // //store the first document
@ -137,6 +145,4 @@ class DMSTest extends FunctionalTest {
// //$response = $this->get($link); // //$response = $this->get($link);
// Debug::show($response); // Debug::show($response);
} }
} }

View File

@ -1,15 +1,17 @@
<?php <?php
class DMSVersioningTest extends SapphireTest { class DMSVersioningTest extends SapphireTest
{
static $testFile = 'dms/tests/DMS-test-lorum-file.pdf'; public static $testFile = 'dms/tests/DMS-test-lorum-file.pdf';
static $testFile2 = 'dms/tests/DMS-test-document-2.pdf'; public static $testFile2 = 'dms/tests/DMS-test-document-2.pdf';
//store values to reset back to after this test runs //store values to reset back to after this test runs
static $dmsFolderOld; public static $dmsFolderOld;
static $dmsFolderSizeOld; public static $dmsFolderSizeOld;
static $dmsEnableVersionsOld; public static $dmsEnableVersionsOld;
function setUp() { public function setUp()
{
parent::setUp(); parent::setUp();
self::$dmsFolderOld = DMS::$dmsFolder; self::$dmsFolderOld = DMS::$dmsFolder;
@ -24,7 +26,8 @@ class DMSVersioningTest extends SapphireTest {
$this->delete(BASE_PATH . DIRECTORY_SEPARATOR . 'dms-assets-test-versions'); $this->delete(BASE_PATH . DIRECTORY_SEPARATOR . 'dms-assets-test-versions');
} }
function tearDown() { public function tearDown()
{
$d = DataObject::get("DMSDocument"); $d = DataObject::get("DMSDocument");
foreach ($d as $d1) { foreach ($d as $d1) {
$d1->delete(); $d1->delete();
@ -45,7 +48,8 @@ class DMSVersioningTest extends SapphireTest {
DMSDocument_versions::$enable_versions = self::$dmsEnableVersionsOld; DMSDocument_versions::$enable_versions = self::$dmsEnableVersionsOld;
} }
public function delete($path) { public function delete($path)
{
if (file_exists($path) || is_dir($path)) { if (file_exists($path) || is_dir($path)) {
$it = new RecursiveIteratorIterator( $it = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($path), new RecursiveDirectoryIterator($path),
@ -65,7 +69,8 @@ class DMSVersioningTest extends SapphireTest {
} }
function testDMSVersionStorage() { public function testDMSVersionStorage()
{
$dms = DMS::inst(); $dms = DMS::inst();
$document = $dms->storeDocument(self::$testFile); $document = $dms->storeDocument(self::$testFile);
@ -87,9 +92,5 @@ class DMSVersioningTest extends SapphireTest {
$this->assertEquals($versionsArray[1]->VersionCounter, 2, "Correct version count"); $this->assertEquals($versionsArray[1]->VersionCounter, 2, "Correct version count");
$this->assertEquals($versionsArray[2]->VersionCounter, 3, "Correct version count"); $this->assertEquals($versionsArray[2]->VersionCounter, 3, "Correct version count");
$this->assertEquals($versionsArray[3]->VersionCounter, 4, "Correct version count"); $this->assertEquals($versionsArray[3]->VersionCounter, 4, "Correct version count");
} }
} }

View File

@ -1,11 +1,13 @@
<?php <?php
class ShortCodeRelationFinderTest extends SapphireTest { class ShortCodeRelationFinderTest extends SapphireTest
{
static $fixture_file = array( public static $fixture_file = array(
'dms/tests/dmstest.yml' 'dms/tests/dmstest.yml'
); );
function testFindInRate() { public function testFindInRate()
{
$d1 = $this->objFromFixture('DMSDocument', 'd1'); $d1 = $this->objFromFixture('DMSDocument', 'd1');
$d2 = $this->objFromFixture('DMSDocument', 'd2'); $d2 = $this->objFromFixture('DMSDocument', 'd2');
@ -31,5 +33,4 @@ class ShortCodeRelationFinderTest extends SapphireTest {
$this->assertContains($page1ID, $ids); $this->assertContains($page1ID, $ids);
$this->assertContains($page3ID, $ids); $this->assertContains($page3ID, $ids);
} }
} }