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,115 +1,130 @@
<?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.
//The number should be a multiple of 10
static $dmsFolderSize = 1000;
//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
public static $dmsFolderSize = 1000;
/**
* Factory method that returns an instance of the DMS. This could be any class that implements the DMSInterface.
* @static
* @return DMSInterface An instance of the Document Management System
*/
static function inst() {
$dmsPath = self::get_dms_path();
/**
* Factory method that returns an instance of the DMS. This could be any class that implements the DMSInterface.
* @static
* @return DMSInterface An instance of the Document Management System
*/
public static function inst()
{
$dmsPath = self::get_dms_path();
$dms = new DMS();
if (!is_dir($dmsPath)) {
self::create_storage_folder($dmsPath);
}
$dms = new DMS();
if (!is_dir($dmsPath)) {
self::create_storage_folder($dmsPath);
}
if (!file_exists($dmsPath . DIRECTORY_SEPARATOR . '.htaccess')) {
//restrict access to the storage folder
copy(BASE_PATH . DIRECTORY_SEPARATOR . DMS_DIR . DIRECTORY_SEPARATOR . 'resources' . DIRECTORY_SEPARATOR . '.htaccess', $dmsPath . DIRECTORY_SEPARATOR . '.htaccess');
copy(BASE_PATH . DIRECTORY_SEPARATOR . DMS_DIR . DIRECTORY_SEPARATOR . 'resources' . DIRECTORY_SEPARATOR . 'web.config', $dmsPath . DIRECTORY_SEPARATOR . 'web.config');
}
return $dms;
}
if (!file_exists($dmsPath . DIRECTORY_SEPARATOR . '.htaccess')) {
//restrict access to the storage folder
copy(BASE_PATH . DIRECTORY_SEPARATOR . DMS_DIR . DIRECTORY_SEPARATOR . 'resources' . DIRECTORY_SEPARATOR . '.htaccess', $dmsPath . DIRECTORY_SEPARATOR . '.htaccess');
copy(BASE_PATH . DIRECTORY_SEPARATOR . DMS_DIR . DIRECTORY_SEPARATOR . 'resources' . DIRECTORY_SEPARATOR . 'web.config', $dmsPath . DIRECTORY_SEPARATOR . 'web.config');
}
return $dms;
}
static function get_dms_path() {
return BASE_PATH . DIRECTORY_SEPARATOR . self::$dmsFolder;
}
public static function get_dms_path()
{
return BASE_PATH . DIRECTORY_SEPARATOR . self::$dmsFolder;
}
static function transform_file_to_file_path($file) {
//confirm we have a file
$filePath = null;
if (is_string($file)) $filePath = $file;
elseif (is_object($file) && $file->is_a("File")) $filePath = $file->Filename;
public static function transform_file_to_file_path($file)
{
//confirm we have a file
$filePath = null;
if (is_string($file)) {
$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;
}
/**
* Takes a File object or a String (path to a file) and copies it into the DMS. The original file remains unchanged.
* When storing a document, sets the fields on the File has "tag" metadata.
* @param $file File object, or String that is path to a file to store, e.g. "assets/documents/industry/supplied-v1-0.pdf"
/**
* Takes a File object or a String (path to a file) and copies it into the DMS. The original file remains unchanged.
* When storing a document, sets the fields on the File has "tag" metadata.
* @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) {
$filePath = self::transform_file_to_file_path($file);
//create a new document and get its ID
$doc = new DMSDocument();
$doc->write();
$doc->storeDocument($filePath);
*/
public function storeDocument($file)
{
$filePath = self::transform_file_to_file_path($file);
//create a new document and get its ID
$doc = new DMSDocument();
$doc->write();
$doc->storeDocument($filePath);
return $doc;
}
return $doc;
}
/**
*
* Returns a number of Document objects based on the a search by tags. You can search by category alone,
* by tag value alone, or by both. I.e: getByTag("fruits",null); getByTag(null,"banana"); getByTag("fruits","banana")
* @param null $category The metadata category to search for
* @param null $value The metadata value to search for
* @param bool $showEmbargoed Boolean that specifies if embargoed documents should be included in results
* @return DocumentInterface
*/
function getByTag($category = null, $value = null, $showEmbargoed = false) {
// TODO: Implement getByTag() method.
}
/**
*
* Returns a number of Document objects based on the a search by tags. You can search by category alone,
* by tag value alone, or by both. I.e: getByTag("fruits",null); getByTag(null,"banana"); getByTag("fruits","banana")
* @param null $category The metadata category to search for
* @param null $value The metadata value to search for
* @param bool $showEmbargoed Boolean that specifies if embargoed documents should be included in results
* @return DocumentInterface
*/
public function getByTag($category = null, $value = null, $showEmbargoed = false)
{
// TODO: Implement getByTag() method.
}
/**
* Returns a number of Document objects that match a full-text search of the Documents and their contents
* (if contents is searchable and compatible search module is installed - e.g. FullTextSearch module)
* @param $searchText String to search for
* @param bool $showEmbargoed Boolean that specifies if embargoed documents should be included in results
* @return DocumentInterface
*/
function getByFullTextSearch($searchText, $showEmbargoed = false) {
// TODO: Implement getByFullTextSearch() method.
}
/**
* Returns a number of Document objects that match a full-text search of the Documents and their contents
* (if contents is searchable and compatible search module is installed - e.g. FullTextSearch module)
* @param $searchText String to search for
* @param bool $showEmbargoed Boolean that specifies if embargoed documents should be included in results
* @return DocumentInterface
*/
public function getByFullTextSearch($searchText, $showEmbargoed = false)
{
// TODO: Implement getByFullTextSearch() method.
}
/**
* Returns a list of Document objects associated with a Page
* @param $page SiteTree to fetch the associated Documents from
* @param bool $showEmbargoed Boolean that specifies if embargoed documents should be included in results
* @return DataList Document list associated with the Page
*/
function getByPage($page, $showEmbargoed = false) {
// TODO: Implement getByPage() method.
}
/**
* Returns a list of Document objects associated with a Page
* @param $page SiteTree to fetch the associated Documents from
* @param bool $showEmbargoed Boolean that specifies if embargoed documents should be included in results
* @return DataList Document list associated with the Page
*/
public function getByPage($page, $showEmbargoed = false)
{
// TODO: Implement getByPage() method.
}
/**
* Creates a storage folder for the given path
* @param $path Path to create a folder for
*/
static function create_storage_folder($path) {
if (!is_dir($path)) {
mkdir($path, 0777);
}
}
/**
* Creates a storage folder for the given path
* @param $path Path to create a folder for
*/
public static function create_storage_folder($path)
{
if (!is_dir($path)) {
mkdir($path, 0777);
}
}
/**
* Calculates the storage path from a database DMSDocument ID
*/
static function get_storage_folder($id) {
$folderName = intval($id / self::$dmsFolderSize);
return $folderName;
}
}
/**
* Calculates the storage path from a database DMSDocument ID
*/
public static function get_storage_folder($id)
{
$folderName = intval($id / self::$dmsFolderSize);
return $folderName;
}
}

View File

@ -6,37 +6,37 @@
*
* @package dms
*/
class DMSShortcodeHandler {
class DMSShortcodeHandler
{
public static function handle(
$arguments, $content, ShortcodeParser $parser, $tag, array $extra = array()
) {
if(!empty($arguments['id'])) {
$document = DMSDocument::get()->byID($arguments['id']);
public static function handle(
$arguments, $content, ShortcodeParser $parser, $tag, array $extra = array()
) {
if (!empty($arguments['id'])) {
$document = DMSDocument::get()->byID($arguments['id']);
if($document && !$document->isHidden()) {
if($content) {
return sprintf(
'<a href="%s">%s</a>', $document->Link(), $parser->parse($content)
);
} else {
if(isset($extra['element'])) {
$extra['element']->setAttribute('data-ext', $document->getExtension());
$extra['element']->setAttribute('data-size', $document->getFileSizeFormatted());
}
if ($document && !$document->isHidden()) {
if ($content) {
return sprintf(
'<a href="%s">%s</a>', $document->Link(), $parser->parse($content)
);
} else {
if (isset($extra['element'])) {
$extra['element']->setAttribute('data-ext', $document->getExtension());
$extra['element']->setAttribute('data-size', $document->getFileSizeFormatted());
}
return $document->Link();
}
}
}
return $document->Link();
}
}
}
$error = ErrorPage::get()->filter('ErrorCode', '404')->First();
$error = ErrorPage::get()->filter('ErrorCode', '404')->First();
if($error) {
return $error->Link();
}
return '';
}
if ($error) {
return $error->Link();
}
return '';
}
}

View File

@ -4,239 +4,254 @@
* @package dms
*/
class DMSDocumentAddController extends LeftAndMain {
class DMSDocumentAddController extends LeftAndMain
{
private static $url_segment = 'pages/adddocument';
private static $url_priority = 60;
private static $required_permission_codes = 'CMS_ACCESS_AssetAdmin';
private static $menu_title = 'Edit Page';
private static $tree_class = 'SiteTree';
private static $session_namespace = 'CMSMain';
private static $url_segment = 'pages/adddocument';
private static $url_priority = 60;
private static $required_permission_codes = 'CMS_ACCESS_AssetAdmin';
private static $menu_title = 'Edit Page';
private static $tree_class = 'SiteTree';
private static $session_namespace = 'CMSMain';
static $allowed_extensions = array();
public static $allowed_extensions = array();
private static $allowed_actions = array (
'getEditForm',
'documentautocomplete',
'linkdocument',
'documentlist'
);
private static $allowed_actions = array(
'getEditForm',
'documentautocomplete',
'linkdocument',
'documentlist'
);
/**
* Add an array of additional allowed extensions
* @static
* @param $array
*/
static function add_allowed_extensions($array = null) {
if (empty($array)) return;
if (is_array($array)) self::$allowed_extensions = $array;
else self::$allowed_extensions = array($array);
}
/**
* Add an array of additional allowed extensions
* @static
* @param $array
*/
public static function add_allowed_extensions($array = null)
{
if (empty($array)) {
return;
}
if (is_array($array)) {
self::$allowed_extensions = $array;
} else {
self::$allowed_extensions = array($array);
}
}
/**
* Custom currentPage() method to handle opening the 'root' folder
*
* @return
*/
public function currentPage() {
$id = $this->currentPageID();
/**
* Custom currentPage() method to handle opening the 'root' folder
*
* @return
*/
public function currentPage()
{
$id = $this->currentPageID();
if($id && is_numeric($id) && $id > 0) {
return Versioned::get_by_stage('SiteTree', 'Stage', sprintf(
'ID = %s', (int) $id
))->first();
} else {
// ID is either '0' or 'root'
return singleton('SiteTree');
}
}
if ($id && is_numeric($id) && $id > 0) {
return Versioned::get_by_stage('SiteTree', 'Stage', sprintf(
'ID = %s', (int) $id
))->first();
} else {
// ID is either '0' or 'root'
return singleton('SiteTree');
}
}
/**
* Return fake-ID "root" if no ID is found (needed to upload files into the root-folder)
*/
public function currentPageID() {
return ($result = parent::currentPageID()) === null ? 0 : $result;
}
/**
* Return fake-ID "root" if no ID is found (needed to upload files into the root-folder)
*/
public function currentPageID()
{
return ($result = parent::currentPageID()) === null ? 0 : $result;
}
/**
* @return Form
* @todo what template is used here? AssetAdmin_UploadContent.ss doesn't seem to be used anymore
*/
public function getEditForm($id = null, $fields = null) {
Requirements::javascript(FRAMEWORK_DIR . '/javascript/AssetUploadField.js');
Requirements::css(FRAMEWORK_DIR . '/css/AssetUploadField.css');
Requirements::css(DMS_DIR.'/css/DMSMainCMS.css');
/**
* @return Form
* @todo what template is used here? AssetAdmin_UploadContent.ss doesn't seem to be used anymore
*/
public function getEditForm($id = null, $fields = null)
{
Requirements::javascript(FRAMEWORK_DIR . '/javascript/AssetUploadField.js');
Requirements::css(FRAMEWORK_DIR . '/css/AssetUploadField.css');
Requirements::css(DMS_DIR.'/css/DMSMainCMS.css');
$page = $this->currentPage();
$uploadField = DMSUploadField::create('AssetUploadField', '');
$uploadField->setConfig('previewMaxWidth', 40);
$uploadField->setConfig('previewMaxHeight', 30);
// Required to avoid Solr reindexing (often used alongside DMS) to
// return 503s because of too many concurrent reindex requests
$uploadField->setConfig('sequentialUploads', 1);
$uploadField->addExtraClass('ss-assetuploadfield');
$uploadField->removeExtraClass('ss-uploadfield');
$uploadField->setTemplate('AssetUploadField');
$uploadField->setRecord($page);
$page = $this->currentPage();
$uploadField = DMSUploadField::create('AssetUploadField', '');
$uploadField->setConfig('previewMaxWidth', 40);
$uploadField->setConfig('previewMaxHeight', 30);
// Required to avoid Solr reindexing (often used alongside DMS) to
// return 503s because of too many concurrent reindex requests
$uploadField->setConfig('sequentialUploads', 1);
$uploadField->addExtraClass('ss-assetuploadfield');
$uploadField->removeExtraClass('ss-uploadfield');
$uploadField->setTemplate('AssetUploadField');
$uploadField->setRecord($page);
$uploadField->getValidator()->setAllowedExtensions(array_filter(array_merge(Config::inst()->get('File', 'allowed_extensions'),self::$allowed_extensions)));
$exts = $uploadField->getValidator()->getAllowedExtensions();
$uploadField->getValidator()->setAllowedExtensions(array_filter(array_merge(Config::inst()->get('File', 'allowed_extensions'), self::$allowed_extensions)));
$exts = $uploadField->getValidator()->getAllowedExtensions();
asort($exts);
$backlink = $this->Backlink();
$done = "
asort($exts);
$backlink = $this->Backlink();
$done = "
<a class=\"ss-ui-button ss-ui-action-constructive cms-panel-link ui-corner-all\" href=\"".$backlink."\">
Done!
</a>";
$addExistingField = new DMSDocumentAddExistingField('AddExisting', 'Add Existing');
$addExistingField->setRecord($page);
$form = new Form(
$this,
'getEditForm',
new FieldList(
new TabSet('Main',
new Tab('From your computer',
new HiddenField('ID', false, $page->ID),
$uploadField,
new LiteralField(
'AllowedExtensions',
sprintf(
'<p>%s: %s</p>',
_t('AssetAdmin.ALLOWEDEXTS', 'Allowed extensions'),
implode('<em>, </em>', $exts)
)
)
),
new Tab('From the CMS',
$addExistingField
)
)
),
new FieldList(
new LiteralField('doneButton', $done)
)
);
$form->addExtraClass('center cms-edit-form ' . $this->BaseCSSClasses());
$form->Backlink = $backlink;
// Don't use AssetAdmin_EditForm, as it assumes a different panel structure
$form->setTemplate($this->getTemplatesWithSuffix('_EditForm'));
/*$form->Fields()->push(
new LiteralField(
'BackLink',
sprintf(
'<a href="%s" class="backlink ss-ui-button cms-panel-link" data-icon="back">%s</a>',
Controller::join_links(singleton('AssetAdmin')->Link('show'), $folder ? $folder->ID : 0),
_t('AssetAdmin.BackToFolder', 'Back to folder')
)
)
);*/
//$form->loadDataFrom($folder);
$addExistingField = new DMSDocumentAddExistingField('AddExisting', 'Add Existing');
$addExistingField->setRecord($page);
$form = new Form(
$this,
'getEditForm',
new FieldList(
new TabSet('Main',
new Tab('From your computer',
new HiddenField('ID', false, $page->ID),
$uploadField,
new LiteralField(
'AllowedExtensions',
sprintf(
'<p>%s: %s</p>',
_t('AssetAdmin.ALLOWEDEXTS', 'Allowed extensions'),
implode('<em>, </em>', $exts)
)
)
),
new Tab('From the CMS',
$addExistingField
)
)
),
new FieldList(
new LiteralField('doneButton', $done)
)
);
$form->addExtraClass('center cms-edit-form ' . $this->BaseCSSClasses());
$form->Backlink = $backlink;
// Don't use AssetAdmin_EditForm, as it assumes a different panel structure
$form->setTemplate($this->getTemplatesWithSuffix('_EditForm'));
/*$form->Fields()->push(
new LiteralField(
'BackLink',
sprintf(
'<a href="%s" class="backlink ss-ui-button cms-panel-link" data-icon="back">%s</a>',
Controller::join_links(singleton('AssetAdmin')->Link('show'), $folder ? $folder->ID : 0),
_t('AssetAdmin.BackToFolder', 'Back to folder')
)
)
);*/
//$form->loadDataFrom($folder);
return $form;
}
return $form;
}
/**
* @return ArrayList
*/
public function Breadcrumbs($unlinked = false) {
$items = parent::Breadcrumbs($unlinked);
/**
* @return ArrayList
*/
public function Breadcrumbs($unlinked = false)
{
$items = parent::Breadcrumbs($unlinked);
// The root element should explicitly point to the root node.
$items[0]->Link = Controller::join_links(singleton('CMSPageEditController')->Link('show'), 0);
// The root element should explicitly point to the root node.
$items[0]->Link = Controller::join_links(singleton('CMSPageEditController')->Link('show'), 0);
// Enforce linkage of hierarchy to AssetAdmin
foreach($items as $item) {
$baselink = $this->Link('show');
if(strpos($item->Link, $baselink) !== false) {
$item->Link = str_replace($baselink, singleton('CMSPageEditController')->Link('show'), $item->Link);
}
}
// Enforce linkage of hierarchy to AssetAdmin
foreach ($items as $item) {
$baselink = $this->Link('show');
if (strpos($item->Link, $baselink) !== false) {
$item->Link = str_replace($baselink, singleton('CMSPageEditController')->Link('show'), $item->Link);
}
}
$items->push(new ArrayData(array(
'Title' => 'Add Document',
'Link' => $this->Link()
)));
return $items;
}
public function Backlink(){
$pageID = $this->currentPageID();
return singleton('CMSPagesController')->Link().'edit/show/'.$pageID;
}
$items->push(new ArrayData(array(
'Title' => 'Add Document',
'Link' => $this->Link()
)));
return $items;
}
public function Backlink()
{
$pageID = $this->currentPageID();
return singleton('CMSPagesController')->Link().'edit/show/'.$pageID;
}
public function documentautocomplete() {
$term = (isset($_GET['term'])) ? $_GET['term'] : '';
$term_sql = Convert::raw2sql($term);
$data = DMSDocument::get()
->where("(\"ID\" LIKE '%".$term_sql."%' OR \"Filename\" LIKE '%".$term_sql."%' OR \"Title\" LIKE '%".$term_sql."%')")
->sort('ID ASC')
->limit(20);
public function documentautocomplete()
{
$term = (isset($_GET['term'])) ? $_GET['term'] : '';
$term_sql = Convert::raw2sql($term);
$data = DMSDocument::get()
->where("(\"ID\" LIKE '%".$term_sql."%' OR \"Filename\" LIKE '%".$term_sql."%' OR \"Title\" LIKE '%".$term_sql."%')")
->sort('ID ASC')
->limit(20);
$return = array();
foreach($data as $doc) {
$return[] = array(
'label' => $doc->ID . ' - ' . $doc->Title,
'value' => $doc->ID
);
}
$return = array();
foreach ($data as $doc) {
$return[] = array(
'label' => $doc->ID . ' - ' . $doc->Title,
'value' => $doc->ID
);
}
return json_encode($return);
}
return json_encode($return);
}
public function linkdocument() {
$return = array('error' => _t('UploadField.FIELDNOTSET', 'Could not add document to page'));
public function linkdocument()
{
$return = array('error' => _t('UploadField.FIELDNOTSET', 'Could not add document to page'));
$page = $this->currentPage();
if (!empty($page)) {
$document = DataObject::get_by_id('DMSDocument', (int) $_GET['documentID']);
$document->addPage($page);
$page = $this->currentPage();
if (!empty($page)) {
$document = DataObject::get_by_id('DMSDocument', (int) $_GET['documentID']);
$document->addPage($page);
$buttonText = '<button class="ss-uploadfield-item-edit ss-ui-button ui-corner-all" title="Edit this document" data-icon="pencil">'.
'Edit<span class="toggle-details"><span class="toggle-details-icon"></span></span></button>';
$buttonText = '<button class="ss-uploadfield-item-edit ss-ui-button ui-corner-all" title="Edit this document" data-icon="pencil">'.
'Edit<span class="toggle-details"><span class="toggle-details-icon"></span></span></button>';
// Collect all output data.
$return = array(
'id' => $document->ID,
'name' => $document->getTitle(),
'thumbnail_url' => $document->Icon($document->getExtension()),
'edit_url' => $this->getEditForm()->Fields()->fieldByName('Main.From your computer.AssetUploadField')->getItemHandler($document->ID)->EditLink(),
'size' => $document->getFileSizeFormatted(),
'buttons' => $buttonText,
'showeditform' => true
);
}
// Collect all output data.
$return = array(
'id' => $document->ID,
'name' => $document->getTitle(),
'thumbnail_url' => $document->Icon($document->getExtension()),
'edit_url' => $this->getEditForm()->Fields()->fieldByName('Main.From your computer.AssetUploadField')->getItemHandler($document->ID)->EditLink(),
'size' => $document->getFileSizeFormatted(),
'buttons' => $buttonText,
'showeditform' => true
);
}
return json_encode($return);
}
return json_encode($return);
}
public function documentlist() {
if(!isset($_GET['pageID'])) {
return $this->httpError(400);
}
public function documentlist()
{
if (!isset($_GET['pageID'])) {
return $this->httpError(400);
}
$page = SiteTree::get()->byId($_GET['pageID']);
$page = SiteTree::get()->byId($_GET['pageID']);
if($page && $page->Documents()->count() > 0) {
$list = '<ul>';
if ($page && $page->Documents()->count() > 0) {
$list = '<ul>';
foreach($page->Documents() as $document) {
$list .= sprintf(
'<li><a class="add-document" data-document-id="%s">%s</a></li>',
$document->ID,
$document->ID . ' - '. Convert::raw2xml($document->Title)
);
}
foreach ($page->Documents() as $document) {
$list .= sprintf(
'<li><a class="add-document" data-document-id="%s">%s</a></li>',
$document->ID,
$document->ID . ' - '. Convert::raw2xml($document->Title)
);
}
$list .= '</ul>';
$list .= '</ul>';
return $list;
}
return sprintf('<p>%s</p>',
_t('DMSDocumentAddController.NODOCUMENTS', 'There are no documents attached to the selected page.')
);
}
return $list;
}
return sprintf('<p>%s</p>',
_t('DMSDocumentAddController.NODOCUMENTS', 'There are no documents attached to the selected page.')
);
}
}

View File

@ -1,56 +1,63 @@
<?php
class DMSDocumentAddExistingField extends CompositeField {
class DMSDocumentAddExistingField extends CompositeField
{
public $useFieldContext = true;
public $useFieldContext = true;
function __construct($name, $title = null) {
$this->name = $name;
$this->title = ($title === null) ? $name : $title;
public function __construct($name, $title = null)
{
$this->name = $name;
$this->title = ($title === null) ? $name : $title;
parent::__construct(new TreeDropdownField('PageSelector', 'Add from another page', 'SiteTree', 'ID', 'TitleWithNumberOfDocuments'));
}
parent::__construct(new TreeDropdownField('PageSelector', 'Add from another page', 'SiteTree', 'ID', 'TitleWithNumberOfDocuments'));
}
/**
* Force a record to be used as "Parent" for uploaded Files (eg a Page with a has_one to File)
* @param DataObject $record
*/
public function setRecord($record) {
$this->record = $record;
return $this;
}
/**
* 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
*/
public function getRecord() {
if (!$this->record && $this->form) {
if ($this->form->getRecord() && is_a($this->form->getRecord(), 'DataObject')) {
$this->record = $this->form->getRecord();
} elseif ($this->form->Controller() && $this->form->Controller()->hasMethod('data')
&& $this->form->Controller()->data() && is_a($this->form->Controller()->data(), 'DataObject')) {
$this->record = $this->form->Controller()->data();
}
}
return $this->record;
}
/**
* Force a record to be used as "Parent" for uploaded Files (eg a Page with a has_one to File)
* @param DataObject $record
*/
public function setRecord($record)
{
$this->record = $record;
return $this;
}
/**
* 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
*/
public function getRecord()
{
if (!$this->record && $this->form) {
if ($this->form->getRecord() && is_a($this->form->getRecord(), 'DataObject')) {
$this->record = $this->form->getRecord();
} elseif ($this->form->Controller() && $this->form->Controller()->hasMethod('data')
&& $this->form->Controller()->data() && is_a($this->form->Controller()->data(), 'DataObject')) {
$this->record = $this->form->Controller()->data();
}
}
return $this->record;
}
public function FieldHolder($properties = array()) {
return $this->Field($properties);
}
public function FieldHolder($properties = array())
{
return $this->Field($properties);
}
public function Field($properties = array()) {
Requirements::javascript(DMS_DIR.'/javascript/DMSDocumentAddExistingField.js');
Requirements::javascript(DMS_DIR."/javascript/DocumentHtmlEditorFieldToolbar.js");
public function Field($properties = array())
{
Requirements::javascript(DMS_DIR.'/javascript/DMSDocumentAddExistingField.js');
Requirements::javascript(DMS_DIR."/javascript/DocumentHtmlEditorFieldToolbar.js");
return $this->renderWith('DMSDocumentAddExistingField');
}
return $this->renderWith('DMSDocumentAddExistingField');
}
/**
* 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
*/
public function setUseFieldClass($use = false) {
$this->useFieldContext = $use;
}
/**
* 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
*/
public function setUseFieldClass($use = false)
{
$this->useFieldContext = $use;
}
}

View File

@ -13,74 +13,84 @@
* @package dms
* @subpackage cms
*/
class DMSGridFieldDeleteAction extends GridFieldDeleteAction implements GridField_ColumnProvider, GridField_ActionProvider {
class DMSGridFieldDeleteAction extends GridFieldDeleteAction implements GridField_ColumnProvider, GridField_ActionProvider
{
/**
*
* @param GridField $gridField
* @param DataObject $record
* @param string $columnName
* @return string - the HTML for the column
*/
public function getColumnContent($gridField, $record, $columnName) {
if($this->removeRelation) {
$field = GridField_FormAction::create($gridField, 'UnlinkRelation'.$record->ID, false, "unlinkrelation", array('RecordID' => $record->ID))
->addExtraClass('gridfield-button-unlink')
->setAttribute('title', _t('GridAction.UnlinkRelation', "Unlink"))
->setAttribute('data-icon', 'chain--minus');
} else {
if(!$record->canDelete()) {
return;
}
$field = GridField_FormAction::create($gridField, 'DeleteRecord'.$record->ID, false, "deleterecord", array('RecordID' => $record->ID))
->addExtraClass('gridfield-button-delete')
->setAttribute('title', _t('GridAction.Delete', "Delete"))
->setAttribute('data-icon', 'cross-circle')
->setDescription(_t('GridAction.DELETE_DESCRIPTION','Delete'));
}
/**
*
* @param GridField $gridField
* @param DataObject $record
* @param string $columnName
* @return string - the HTML for the column
*/
public function getColumnContent($gridField, $record, $columnName)
{
if ($this->removeRelation) {
$field = GridField_FormAction::create($gridField, 'UnlinkRelation'.$record->ID, false, "unlinkrelation", array('RecordID' => $record->ID))
->addExtraClass('gridfield-button-unlink')
->setAttribute('title', _t('GridAction.UnlinkRelation', "Unlink"))
->setAttribute('data-icon', 'chain--minus');
} else {
if (!$record->canDelete()) {
return;
}
$field = GridField_FormAction::create($gridField, 'DeleteRecord'.$record->ID, false, "deleterecord", array('RecordID' => $record->ID))
->addExtraClass('gridfield-button-delete')
->setAttribute('title', _t('GridAction.Delete', "Delete"))
->setAttribute('data-icon', 'cross-circle')
->setDescription(_t('GridAction.DELETE_DESCRIPTION', 'Delete'));
}
//add a class to the field to if it is the last gridfield in the list
$numberOfRelations = $record->Pages()->Count();
$field->addExtraClass('dms-delete') //add a new class for custom JS to handle the delete action
->setAttribute('data-pages-count', $numberOfRelations) //add the number of pages attached to this field as a data-attribute
->removeExtraClass('gridfield-button-delete'); //remove the base gridfield behaviour
//add a class to the field to if it is the last gridfield in the list
$numberOfRelations = $record->Pages()->Count();
$field->addExtraClass('dms-delete') //add a new class for custom JS to handle the delete action
->setAttribute('data-pages-count', $numberOfRelations) //add the number of pages attached to this field as a data-attribute
->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
if ($numberOfRelations > 1) $field->addExtraClass('dms-delete-link-only');
else $field->addExtraClass('dms-delete-last-warning');
//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');
} else {
$field->addExtraClass('dms-delete-last-warning');
}
//set a class to show if the document is hidden
if ($record->isHidden()) {
$field->addExtraClass('dms-document-hidden');
}
//set a class to show if the document is hidden
if ($record->isHidden()) {
$field->addExtraClass('dms-document-hidden');
}
return $field->Field();
}
return $field->Field();
}
/**
* Handle the actions and apply any changes to the GridField
*
* @param GridField $gridField
* @param string $actionName
* @param mixed $arguments
* @param array $data - form data
* @return void
*/
public function handleAction(GridField $gridField, $actionName, $arguments, $data) {
if($actionName == 'deleterecord' || $actionName == 'unlinkrelation') {
$item = $gridField->getList()->byID($arguments['RecordID']);
if(!$item) {
return;
}
if($actionName == 'deleterecord' && !$item->canDelete()) {
throw new ValidationException(_t('GridFieldAction_Delete.DeletePermissionsFailure',"No delete permissions"),0);
}
/**
* Handle the actions and apply any changes to the GridField
*
* @param GridField $gridField
* @param string $actionName
* @param mixed $arguments
* @param array $data - form data
* @return void
*/
public function handleAction(GridField $gridField, $actionName, $arguments, $data)
{
if ($actionName == 'deleterecord' || $actionName == 'unlinkrelation') {
$item = $gridField->getList()->byID($arguments['RecordID']);
if (!$item) {
return;
}
if ($actionName == 'deleterecord' && !$item->canDelete()) {
throw new ValidationException(_t('GridFieldAction_Delete.DeletePermissionsFailure', "No delete permissions"), 0);
}
$delete = false;
if ($item->Pages()->Count() <= 1) $delete = true;
$delete = false;
if ($item->Pages()->Count() <= 1) {
$delete = true;
}
$gridField->getList()->remove($item); //remove the relation
if ($delete) $item->delete(); //delete the DMSDocument
}
}
$gridField->getList()->remove($item); //remove the relation
if ($delete) {
$item->delete();
} //delete the DMSDocument
}
}
}

View File

@ -3,23 +3,24 @@
/**
* Custom ItemRequest class the provides custom delete behaviour for the CMSFields of DMSDocument
*/
class DMSGridFieldDetailForm_ItemRequest extends GridFieldDetailForm_ItemRequest {
private static $allowed_actions = array('ItemEditForm');
class DMSGridFieldDetailForm_ItemRequest extends GridFieldDetailForm_ItemRequest
{
private static $allowed_actions = array('ItemEditForm');
function ItemEditForm() {
$form = parent::ItemEditForm();
public function ItemEditForm()
{
$form = parent::ItemEditForm();
//add a data attribute specifying how many pages this document is referenced on
if ($record = $this->record) {
$numberOfPageRelations = $record->Pages()->Count();
$relations = new ShortCodeRelationFinder();
$numberOfInlineRelations = $relations->findPageCount($record->ID);
//add the number of pages attached to this field as a data-attribute
$form->setAttribute('data-pages-count', $numberOfPageRelations);
$form->setAttribute('data-relation-count', $numberOfInlineRelations);
}
return $form;
}
//add a data attribute specifying how many pages this document is referenced on
if ($record = $this->record) {
$numberOfPageRelations = $record->Pages()->Count();
$relations = new ShortCodeRelationFinder();
$numberOfInlineRelations = $relations->findPageCount($record->ID);
//add the number of pages attached to this field as a data-attribute
$form->setAttribute('data-pages-count', $numberOfPageRelations);
$form->setAttribute('data-relation-count', $numberOfInlineRelations);
}
return $form;
}
}

View File

@ -12,195 +12,214 @@
* @author Julian Seidenberg
* @package dms
*/
class DMSUploadField extends UploadField {
private static $allowed_actions = array (
class DMSUploadField extends UploadField
{
private static $allowed_actions = array(
"upload",
);
);
protected $folderName = 'DMSTemporaryUploads';
protected $folderName = 'DMSTemporaryUploads';
public function __construct($name, $title = null, SS_List $items = null) {
parent::__construct($name, $title, $items);
public function __construct($name, $title = null, SS_List $items = null)
{
parent::__construct($name, $title, $items);
//set default DMS replace template to false
$this->setConfig('useDMSReplaceTemplate', 0);
}
//set default DMS replace template to false
$this->setConfig('useDMSReplaceTemplate', 0);
}
/**
* Override the default behaviour of the UploadField and take the uploaded file (uploaded to assets) and
* add it into the DMS storage, deleting the old/uploaded file.
* @param File
*/
protected function attachFile($file) {
$dms = DMS::inst();
$record = $this->getRecord();
/**
* Override the default behaviour of the UploadField and take the uploaded file (uploaded to assets) and
* add it into the DMS storage, deleting the old/uploaded file.
* @param File
*/
protected function attachFile($file)
{
$dms = DMS::inst();
$record = $this->getRecord();
if($record instanceof DMSDocument) {
// If the edited record is a document,
// assume we're replacing an existing file
$doc = $record;
$doc->ingestFile($file);
} else {
// Otherwise create it
$doc = $dms->storeDocument($file);
$file->delete();
// Relate to the underlying page being edited.
// Not applicable when editing the document itself and replacing it.
$doc->addPage($record);
}
if ($record instanceof DMSDocument) {
// If the edited record is a document,
// assume we're replacing an existing file
$doc = $record;
$doc->ingestFile($file);
} else {
// Otherwise create it
$doc = $dms->storeDocument($file);
$file->delete();
// Relate to the underlying page being edited.
// Not applicable when editing the document itself and replacing it.
$doc->addPage($record);
}
return $doc;
}
return $doc;
}
public function validate($validator) {
return true;
}
public function validate($validator)
{
return true;
}
public function isDisabled() {
return (parent::isDisabled() || !$this->isSaveable());
}
public function isDisabled()
{
return (parent::isDisabled() || !$this->isSaveable());
}
public function isSaveable() {
return (!empty($this->getRecord()->ID));
}
public function isSaveable()
{
return (!empty($this->getRecord()->ID));
}
/**
* Action to handle upload of a single file
*
* @param SS_HTTPRequest $request
* @return string json
*/
public function upload(SS_HTTPRequest $request) {
if($this->isDisabled() || $this->isReadonly()) return $this->httpError(403);
/**
* Action to handle upload of a single file
*
* @param SS_HTTPRequest $request
* @return string json
*/
public function upload(SS_HTTPRequest $request)
{
if ($this->isDisabled() || $this->isReadonly()) {
return $this->httpError(403);
}
// Protect against CSRF on destructive action
$token = $this->getForm()->getSecurityToken();
if(!$token->checkRequest($request)) return $this->httpError(400);
// Protect against CSRF on destructive action
$token = $this->getForm()->getSecurityToken();
if (!$token->checkRequest($request)) {
return $this->httpError(400);
}
$name = $this->getName();
$tmpfile = $request->postVar($name);
$record = $this->getRecord();
// Check if the file has been uploaded into the temporary storage.
if (!$tmpfile) {
$return = array('error' => _t('UploadField.FIELDNOTSET', 'File information not found'));
} else {
$return = array(
'name' => $tmpfile['name'],
'size' => $tmpfile['size'],
'type' => $tmpfile['type'],
'error' => $tmpfile['error']
);
}
$name = $this->getName();
$tmpfile = $request->postVar($name);
$record = $this->getRecord();
// Check if the file has been uploaded into the temporary storage.
if (!$tmpfile) {
$return = array('error' => _t('UploadField.FIELDNOTSET', 'File information not found'));
} else {
$return = array(
'name' => $tmpfile['name'],
'size' => $tmpfile['size'],
'type' => $tmpfile['type'],
'error' => $tmpfile['error']
);
}
// Check for constraints on the record to which the file will be attached.
if (!$return['error'] && $this->relationAutoSetting && $record && $record->exists()) {
$tooManyFiles = false;
// Some relationships allow many files to be attached.
if ($this->getConfig('allowedMaxFileNumber') && ($record->has_many($name) || $record->many_many($name))) {
if(!$record->isInDB()) $record->write();
$tooManyFiles = $record->{$name}()->count() >= $this->getConfig('allowedMaxFileNumber');
// has_one only allows one file at any given time.
} elseif($record->has_one($name)) {
$tooManyFiles = $record->{$name}() && $record->{$name}()->exists();
}
// Check for constraints on the record to which the file will be attached.
if (!$return['error'] && $this->relationAutoSetting && $record && $record->exists()) {
$tooManyFiles = false;
// Some relationships allow many files to be attached.
if ($this->getConfig('allowedMaxFileNumber') && ($record->has_many($name) || $record->many_many($name))) {
if (!$record->isInDB()) {
$record->write();
}
$tooManyFiles = $record->{$name}()->count() >= $this->getConfig('allowedMaxFileNumber');
// has_one only allows one file at any given time.
} elseif ($record->has_one($name)) {
$tooManyFiles = $record->{$name}() && $record->{$name}()->exists();
}
// Report the constraint violation.
if ($tooManyFiles) {
if(!$this->getConfig('allowedMaxFileNumber')) $this->setConfig('allowedMaxFileNumber', 1);
$return['error'] = _t(
'UploadField.MAXNUMBEROFFILES',
'Max number of {count} file(s) exceeded.',
array('count' => $this->getConfig('allowedMaxFileNumber'))
);
}
}
// Report the constraint violation.
if ($tooManyFiles) {
if (!$this->getConfig('allowedMaxFileNumber')) {
$this->setConfig('allowedMaxFileNumber', 1);
}
$return['error'] = _t(
'UploadField.MAXNUMBEROFFILES',
'Max number of {count} file(s) exceeded.',
array('count' => $this->getConfig('allowedMaxFileNumber'))
);
}
}
// Process the uploaded file
if (!$return['error']) {
$fileObject = null;
// Process the uploaded file
if (!$return['error']) {
$fileObject = null;
if ($this->relationAutoSetting) {
// Search for relations that can hold the uploaded files.
if ($relationClass = $this->getRelationAutosetClass()) {
// Create new object explicitly. Otherwise rely on Upload::load to choose the class.
$fileObject = Object::create($relationClass);
}
}
if ($this->relationAutoSetting) {
// Search for relations that can hold the uploaded files.
if ($relationClass = $this->getRelationAutosetClass()) {
// Create new object explicitly. Otherwise rely on Upload::load to choose the class.
$fileObject = Object::create($relationClass);
}
}
// Get the uploaded file into a new file object.
try {
$this->upload->loadIntoFile($tmpfile, $fileObject, $this->folderName);
} catch (Exception $e) {
// we shouldn't get an error here, but just in case
$return['error'] = $e->getMessage();
}
// Get the uploaded file into a new file object.
try {
$this->upload->loadIntoFile($tmpfile, $fileObject, $this->folderName);
} catch (Exception $e) {
// we shouldn't get an error here, but just in case
$return['error'] = $e->getMessage();
}
if (!$return['error']) {
if ($this->upload->isError()) {
$return['error'] = implode(' '.PHP_EOL, $this->upload->getErrors());
} else {
$file = $this->upload->getFile();
if (!$return['error']) {
if ($this->upload->isError()) {
$return['error'] = implode(' '.PHP_EOL, $this->upload->getErrors());
} else {
$file = $this->upload->getFile();
// CUSTOM Attach the file to the related record.
$document = $this->attachFile($file);
// Collect all output data.
$return = array_merge($return, array(
'id' => $document->ID,
'name' => $document->getTitle(),
'thumbnail_url' => $document->Icon($document->getExtension()),
'edit_url' => $this->getItemHandler($document->ID)->EditLink(),
'size' => $document->getFileSizeFormatted(),
'buttons' => (string) $document->renderWith($this->getTemplateFileButtons()),
'showeditform' => true
));
// CUSTOM Attach the file to the related record.
$document = $this->attachFile($file);
// Collect all output data.
$return = array_merge($return, array(
'id' => $document->ID,
'name' => $document->getTitle(),
'thumbnail_url' => $document->Icon($document->getExtension()),
'edit_url' => $this->getItemHandler($document->ID)->EditLink(),
'size' => $document->getFileSizeFormatted(),
'buttons' => (string) $document->renderWith($this->getTemplateFileButtons()),
'showeditform' => true
));
// CUSTOM END
}
}
}
$response = new SS_HTTPResponse(Convert::raw2json(array($return)));
$response->addHeader('Content-Type', 'text/plain');
return $response;
}
// CUSTOM END
}
}
}
$response = new SS_HTTPResponse(Convert::raw2json(array($return)));
$response->addHeader('Content-Type', 'text/plain');
return $response;
}
/**
* Never directly display items uploaded
* @return SS_List
*/
public function getItems() {
return new ArrayList();
}
/**
* Never directly display items uploaded
* @return SS_List
*/
public function getItems()
{
return new ArrayList();
}
public function Field($properties = array()) {
$fields = parent::Field($properties);
public function Field($properties = array())
{
$fields = parent::Field($properties);
// Replace the download template with a new one only when access the upload field through a GridField.
// Needs to be enabled through setConfig('downloadTemplateName', 'ss-dmsuploadfield-downloadtemplate');
Requirements::javascript('dms/javascript/DMSUploadField_downloadtemplate.js');
// In the add dialog, add the addtemplate into the set of file that load.
Requirements::javascript('dms/javascript/DMSUploadField_addtemplate.js');
// Replace the download template with a new one only when access the upload field through a GridField.
// Needs to be enabled through setConfig('downloadTemplateName', 'ss-dmsuploadfield-downloadtemplate');
Requirements::javascript('dms/javascript/DMSUploadField_downloadtemplate.js');
// In the add dialog, add the addtemplate into the set of file that load.
Requirements::javascript('dms/javascript/DMSUploadField_addtemplate.js');
return $fields;
}
return $fields;
}
/**
* @param int $itemID
* @return UploadField_ItemHandler
*/
public function getItemHandler($itemID) {
return DMSUploadField_ItemHandler::create($this, $itemID);
}
/**
* @param int $itemID
* @return UploadField_ItemHandler
*/
public function getItemHandler($itemID)
{
return DMSUploadField_ItemHandler::create($this, $itemID);
}
}
class DMSUploadField_ItemHandler extends UploadField_ItemHandler {
function getItem() {
return DataObject::get_by_id('DMSDocument', $this->itemID);
}
class DMSUploadField_ItemHandler extends UploadField_ItemHandler
{
public function getItem()
{
return DataObject::get_by_id('DMSDocument', $this->itemID);
}
}

View File

@ -4,26 +4,30 @@
*/
class DocumentHtmlEditorFieldToolbar extends Extension {
class DocumentHtmlEditorFieldToolbar extends Extension
{
function updateLinkForm(Form $form) {
$linkType = null;
$fieldList = null;
$fields = $form->Fields();//->fieldByName('Heading');
foreach($fields as $field) {
$linkType = ($field->fieldByName('LinkType'));
$fieldList = $field;
if ($linkType) break; //break once we have the object
}
public function updateLinkForm(Form $form)
{
$linkType = null;
$fieldList = null;
$fields = $form->Fields();//->fieldByName('Heading');
foreach ($fields as $field) {
$linkType = ($field->fieldByName('LinkType'));
$fieldList = $field;
if ($linkType) {
break;
} //break once we have the object
}
$source = $linkType->getSource();
$source['document'] = 'Download a document';
$linkType->setSource($source);
$source = $linkType->getSource();
$source['document'] = 'Download a document';
$linkType->setSource($source);
$addExistingField = new DMSDocumentAddExistingField('AddExisting', 'Add Existing');
$addExistingField->setForm($form);
$addExistingField->setUseFieldClass(false);
$fieldList->insertAfter($addExistingField,'Description');
$addExistingField = new DMSDocumentAddExistingField('AddExisting', 'Add Existing');
$addExistingField->setForm($form);
$addExistingField->setUseFieldClass(false);
$fieldList->insertAfter($addExistingField, 'Description');
// Requirements::javascript(SAPPHIRE_DIR . "/thirdparty/behaviour/behaviour.js");
// Requirements::javascript(SAPPHIRE_DIR . "/javascript/tiny_mce_improvements.js");
@ -35,6 +39,6 @@ class DocumentHtmlEditorFieldToolbar extends Extension {
// $documents->setTreeBaseID($baseFolder->ID);
//return $form;
}
}
//return $form;
}
}

View File

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

View File

@ -3,160 +3,175 @@
/**
* @package dms
*/
class DMSSiteTreeExtension extends DataExtension {
class DMSSiteTreeExtension extends DataExtension
{
private static $belongs_many_many = array(
'Documents' => 'DMSDocument'
);
private static $belongs_many_many = array(
'Documents' => 'DMSDocument'
);
private static $noDocumentsList = array();
private static $noDocumentsList = array();
private static $showDocumentsList = array();
private static $showDocumentsList = array();
/**
* Do not show the documents tab on the array of pages set here
* @static
* @param $mixed Array of page types to not show the Documents tab on
*/
static function no_documents_tab($array = array()) {
if (empty($array)) return;
if (is_array($array)) {
self::$noDocumentsList = $array;
} else {
self::$noDocumentsList = array($array);
}
}
/**
* Do not show the documents tab on the array of pages set here
* @static
* @param $mixed Array of page types to not show the Documents tab on
*/
public static function no_documents_tab($array = array())
{
if (empty($array)) {
return;
}
if (is_array($array)) {
self::$noDocumentsList = $array;
} else {
self::$noDocumentsList = array($array);
}
}
/**
* Only show the documents tab on the list of pages set here. Any pages set in the no_documents_tab array will
* still not be shown. If this isn't called, or if it is called with an empty array, all pages will get Document tabs.
* @static
* @param $array Array of page types to show the Documents tab on
*/
static function show_documents_tab($array = array()) {
if (empty($array)) return;
if (is_array($array)) {
self::$showDocumentsList = $array;
} else {
self::$showDocumentsList = array($array);
}
}
/**
* Only show the documents tab on the list of pages set here. Any pages set in the no_documents_tab array will
* still not be shown. If this isn't called, or if it is called with an empty array, all pages will get Document tabs.
* @static
* @param $array Array of page types to show the Documents tab on
*/
public static function show_documents_tab($array = array())
{
if (empty($array)) {
return;
}
if (is_array($array)) {
self::$showDocumentsList = $array;
} else {
self::$showDocumentsList = array($array);
}
}
function updateCMSFields(FieldList $fields){
//prevent certain pages from having a Document tab in the CMS
if (in_array($this->owner->ClassName,self::$noDocumentsList)) return;
if (count(self::$showDocumentsList) > 0 && !in_array($this->owner->ClassName,self::$showDocumentsList)) return;
public function updateCMSFields(FieldList $fields)
{
//prevent certain pages from having a Document tab in the CMS
if (in_array($this->owner->ClassName, self::$noDocumentsList)) {
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'
Requirements::javascript(DMS_DIR.'/javascript/DMSGridField.js');
Requirements::css(DMS_DIR.'/css/DMSMainCMS.css');
//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::css(DMS_DIR.'/css/DMSMainCMS.css');
//javascript for the link editor pop-up in TinyMCE
Requirements::javascript(DMS_DIR."/javascript/DocumentHtmlEditorFieldToolbar.js");
//javascript for the link editor pop-up in TinyMCE
Requirements::javascript(DMS_DIR."/javascript/DocumentHtmlEditorFieldToolbar.js");
// Document listing
$gridFieldConfig = GridFieldConfig::create()->addComponents(
new GridFieldToolbarHeader(),
new GridFieldFilterHeader(),
new GridFieldSortableHeader(),
new GridFieldOrderableRows('DocumentSort'),
new GridFieldDataColumns(),
new GridFieldEditButton(),
new DMSGridFieldDeleteAction(), //special delete dialog to handle custom behaviour of unlinking and deleting
new GridFieldDetailForm()
//GridFieldLevelup::create($folder->ID)->setLinkSpec('admin/assets/show/%d')
);
// Document listing
$gridFieldConfig = GridFieldConfig::create()->addComponents(
new GridFieldToolbarHeader(),
new GridFieldFilterHeader(),
new GridFieldSortableHeader(),
new GridFieldOrderableRows('DocumentSort'),
new GridFieldDataColumns(),
new GridFieldEditButton(),
new DMSGridFieldDeleteAction(), //special delete dialog to handle custom behaviour of unlinking and deleting
new GridFieldDetailForm()
//GridFieldLevelup::create($folder->ID)->setLinkSpec('admin/assets/show/%d')
);
if(class_exists('GridFieldPaginatorWithShowAll')){
$paginatorComponent = new GridFieldPaginatorWithShowAll(15);
}else{
$paginatorComponent = new GridFieldPaginator(15);
}
$gridFieldConfig->addComponent($paginatorComponent);
if (class_exists('GridFieldPaginatorWithShowAll')) {
$paginatorComponent = new GridFieldPaginatorWithShowAll(15);
} else {
$paginatorComponent = new GridFieldPaginator(15);
}
$gridFieldConfig->addComponent($paginatorComponent);
if(class_exists('GridFieldSortableRows')) {
$sortableComponent = new GridFieldSortableRows('DocumentSort');
//setUsePagenation method removed from newer version of SortableGridField.
if(method_exists($sortableComponent,'setUsePagination')){
$sortableComponent->setUsePagination(false)->setForceRedraw(true);
}
$gridFieldConfig->addComponent($sortableComponent);
}
if (class_exists('GridFieldSortableRows')) {
$sortableComponent = new GridFieldSortableRows('DocumentSort');
//setUsePagenation method removed from newer version of SortableGridField.
if (method_exists($sortableComponent, 'setUsePagination')) {
$sortableComponent->setUsePagination(false)->setForceRedraw(true);
}
$gridFieldConfig->addComponent($sortableComponent);
}
// HACK: Create a singleton of DMSDocument to ensure extensions are applied before we try to get display fields.
singleton('DMSDocument');
$gridFieldConfig->getComponentByType('GridFieldDataColumns')->setDisplayFields(Config::inst()->get('DMSDocument', 'display_fields'))
->setFieldCasting(array('LastChanged'=>"Datetime->Ago"))
->setFieldFormatting(array('FilenameWithoutID'=>'<a target=\'_blank\' class=\'file-url\' href=\'$Link\'>$FilenameWithoutID</a>'));
// HACK: Create a singleton of DMSDocument to ensure extensions are applied before we try to get display fields.
singleton('DMSDocument');
$gridFieldConfig->getComponentByType('GridFieldDataColumns')->setDisplayFields(Config::inst()->get('DMSDocument', 'display_fields'))
->setFieldCasting(array('LastChanged'=>"Datetime->Ago"))
->setFieldFormatting(array('FilenameWithoutID'=>'<a target=\'_blank\' class=\'file-url\' href=\'$Link\'>$FilenameWithoutID</a>'));
//override delete functionality with this class
$gridFieldConfig->getComponentByType('GridFieldDetailForm')->setItemRequestClass('DMSGridFieldDetailForm_ItemRequest');
//override delete functionality with this class
$gridFieldConfig->getComponentByType('GridFieldDetailForm')->setItemRequestClass('DMSGridFieldDetailForm_ItemRequest');
$gridField = GridField::create(
'Documents',
false,
$this->owner->Documents()->Sort('DocumentSort'),
$gridFieldConfig
);
$gridField->addExtraClass('documents');
$gridField = GridField::create(
'Documents',
false,
$this->owner->Documents()->Sort('DocumentSort'),
$gridFieldConfig
);
$gridField->addExtraClass('documents');
$uploadBtn = new LiteralField(
'UploadButton',
sprintf(
'<a class="ss-ui-button ss-ui-action-constructive cms-panel-link" data-pjax-target="Content" data-icon="add" href="%s">%s</a>',
Controller::join_links(singleton('DMSDocumentAddController')->Link(), '?ID=' . $this->owner->ID),
"Add Documents"
)
);
$uploadBtn = new LiteralField(
'UploadButton',
sprintf(
'<a class="ss-ui-button ss-ui-action-constructive cms-panel-link" data-pjax-target="Content" data-icon="add" href="%s">%s</a>',
Controller::join_links(singleton('DMSDocumentAddController')->Link(), '?ID=' . $this->owner->ID),
"Add Documents"
)
);
$fields->addFieldsToTab(
'Root.Documents (' . $this->owner->Documents()->Count() . ')',
array(
$uploadBtn,
$gridField
)
);
}
$fields->addFieldsToTab(
'Root.Documents (' . $this->owner->Documents()->Count() . ')',
array(
$uploadBtn,
$gridField
)
);
}
/**
* Enforce sorting for frontend
*/
function PageDocuments() {
return $this->owner->getManyManyComponents('Documents')->sort('DocumentSort');
}
/**
* Enforce sorting for frontend
*/
public function PageDocuments()
{
return $this->owner->getManyManyComponents('Documents')->sort('DocumentSort');
}
function onBeforeDelete() {
if(Versioned::current_stage() == 'Live') {
$existsOnOtherStage = !$this->owner->getIsDeletedFromStage();
} else {
$existsOnOtherStage = $this->owner->getExistsOnLive();
}
public function onBeforeDelete()
{
if (Versioned::current_stage() == 'Live') {
$existsOnOtherStage = !$this->owner->getIsDeletedFromStage();
} else {
$existsOnOtherStage = $this->owner->getExistsOnLive();
}
// Only remove if record doesn't still exist on live stage.
if(!$existsOnOtherStage) {
$dmsDocuments = $this->owner->Documents();
foreach($dmsDocuments as $document) {
//if the document is only associated with one page, i.e. only associated with this page
if ($document->Pages()->Count() <= 1) {
//delete the document before deleting this page
$document->delete();
}
}
}
}
// Only remove if record doesn't still exist on live stage.
if (!$existsOnOtherStage) {
$dmsDocuments = $this->owner->Documents();
foreach ($dmsDocuments as $document) {
//if the document is only associated with one page, i.e. only associated with this page
if ($document->Pages()->Count() <= 1) {
//delete the document before deleting this page
$document->delete();
}
}
}
}
function onBeforePublish() {
$embargoedDocuments = $this->owner->Documents()->filter('EmbargoedUntilPublished',true);
if ($embargoedDocuments->Count() > 0) {
foreach($embargoedDocuments as $doc) {
$doc->EmbargoedUntilPublished = false;
$doc->write();
}
}
public function onBeforePublish()
{
$embargoedDocuments = $this->owner->Documents()->filter('EmbargoedUntilPublished', true);
if ($embargoedDocuments->Count() > 0) {
foreach ($embargoedDocuments as $doc) {
$doc->EmbargoedUntilPublished = false;
$doc->write();
}
}
}
}
function getTitleWithNumberOfDocuments() {
return $this->owner->Title . ' (' . $this->owner->Documents()->Count() . ')';
}
public function getTitleWithNumberOfDocuments()
{
return $this->owner->Title . ' (' . $this->owner->Documents()->Count() . ')';
}
}

View File

@ -4,212 +4,212 @@
* 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
*/
interface DMSDocumentInterface {
interface DMSDocumentInterface
{
/**
* Deletes the DMSDocument, its underlying file, as well as any tags related to this DMSDocument.
*
* @todo Can't be applied to classes which already implement the DataObjectInterface (naming conflict)
*
* @abstract
* @return null
*/
// function delete();
/**
* Deletes the DMSDocument, its underlying file, as well as any tags related to this DMSDocument.
*
* @todo Can't be applied to classes which already implement the DataObjectInterface (naming conflict)
*
* @abstract
* @return null
*/
// function delete();
/**
* Associates this DMSDocument with a Page. This method does nothing if the association already exists.
* This could be a simple wrapper around $myDoc->Pages()->add($myPage) to add a many_many relation
* @abstract
* @param $pageObject Page object to associate this DMSDocument with
* @return null
*/
function addPage($pageObject);
/**
* Associates this DMSDocument with a set of Pages. This method loops through a set of page ids, and then associates this
* DMSDocument with the individual Page with the each page id in the set
* @abstract
* @param $pageIDs array of page ids used for the page objects associate this DMSDocument with
* @return null
*/
function addPages($pageIDs);
/**
* Associates this DMSDocument with a Page. This method does nothing if the association already exists.
* This could be a simple wrapper around $myDoc->Pages()->add($myPage) to add a many_many relation
* @abstract
* @param $pageObject Page object to associate this DMSDocument with
* @return null
*/
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
* DMSDocument with the individual Page with the each page id in the set
* @abstract
* @param $pageIDs array of page ids used for the page objects associate this DMSDocument with
* @return null
*/
public function addPages($pageIDs);
/**
* Removes the association between this DMSDocument and a Page. This method does nothing if the association does not exist.
* @abstract
* @param $pageObject Page object to remove the association to
* @return mixed
*/
function removePage($pageObject);
/**
* Removes the association between this DMSDocument and a Page. This method does nothing if the association does not exist.
* @abstract
* @param $pageObject Page object to remove the association to
* @return mixed
*/
public function removePage($pageObject);
/**
* Returns a list of the Page objects associated with this DMSDocument
* @abstract
* @return DataList
*/
function getPages();
/**
* Returns a list of the Page objects associated with this DMSDocument
* @abstract
* @return DataList
*/
public function getPages();
/**
* Removes all associated Pages from the DMSDocument
* @abstract
* @return null
*/
function removeAllPages();
/**
* Removes all associated Pages from the DMSDocument
* @abstract
* @return null
*/
public function removeAllPages();
/**
* Adds a metadata tag to the DMSDocument. The tag has a category and a value.
* Each category can have multiple values by default. So: addTag("fruit","banana") addTag("fruit", "apple") will add two items.
* However, if the third parameter $multiValue is set to 'false', then all updates to a category only ever update a single value. So:
* addTag("fruit","banana") addTag("fruit", "apple") would result in a single metadata tag: fruit->apple.
* Can could be implemented as a key/value store table (although it is more like category/value, because the
* same category can occur multiple times)
* @abstract
* @param $category String of a metadata category to add (required)
* @param $value String of a metadata value to add (required)
* @param bool $multiValue Boolean that determines if the category is multi-value or single-value (optional)
* @return null
*/
function addTag($category, $value, $multiValue = true);
/**
* Adds a metadata tag to the DMSDocument. The tag has a category and a value.
* Each category can have multiple values by default. So: addTag("fruit","banana") addTag("fruit", "apple") will add two items.
* However, if the third parameter $multiValue is set to 'false', then all updates to a category only ever update a single value. So:
* addTag("fruit","banana") addTag("fruit", "apple") would result in a single metadata tag: fruit->apple.
* Can could be implemented as a key/value store table (although it is more like category/value, because the
* same category can occur multiple times)
* @abstract
* @param $category String of a metadata category to add (required)
* @param $value String of a metadata value to add (required)
* @param bool $multiValue Boolean that determines if the category is multi-value or single-value (optional)
* @return null
*/
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
* tries to fetch that specific tag.
* @abstract
* @param $category String of the metadata category 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
*/
function getTagsList($category, $value = null);
/**
* Fetches all tags associated with this DMSDocument within a given category. If a value is specified this method
* tries to fetch that specific tag.
* @abstract
* @param $category String of the metadata category 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
*/
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.
* If you specify both a category and a value, then only that single category/value pair is deleted.
* Nothing happens if the category or the value do not exist.
* @abstract
* @param $category Category to remove (required)
* @param null $value Value to remove (optional)
* @return null
*/
function removeTag($category, $value = null);
/**
* Removes a tag from the DMSDocument. If you only set a category, then all values in that category are deleted.
* If you specify both a category and a value, then only that single category/value pair is deleted.
* Nothing happens if the category or the value do not exist.
* @abstract
* @param $category Category to remove (required)
* @param null $value Value to remove (optional)
* @return null
*/
public function removeTag($category, $value = null);
/**
* Deletes all tags associated with this DMSDocument.
* @abstract
* @return null
*/
function removeAllTags();
/**
* Deletes all tags associated with this DMSDocument.
* @abstract
* @return null
*/
public function removeAllTags();
/**
* Returns a link to download this DMSDocument from the DMS store
* @abstract
* @return String
*/
function getLink();
/**
* Return the extension of the file associated with the document
*/
function getExtension();
/**
* Returns the size of the file type in an appropriate format.
*
* @return string
*/
function getSize();
/**
* Returns a link to download this DMSDocument from the DMS store
* @abstract
* @return String
*/
public function getLink();
/**
* Return the extension of the file associated with the document
*/
public function getExtension();
/**
* Returns the size of the file type in an appropriate format.
*
* @return string
*/
public function getSize();
/**
* Return the size of the file associated with the document, in bytes.
*
* @return int
*/
function getAbsoluteSize();
/**
* Return the size of the file associated with the document, in bytes.
*
* @return int
*/
public function getAbsoluteSize();
/**
* Takes a File object or a String (path to a file) and copies it into the DMS, replacing the original document file
* but keeping the rest of the document unchanged.
* @param $file File object, or String that is path to a file to store
* @return DMSDocumentInstance Document object that we replaced the file in
*/
function replaceDocument($file);
/**
* Takes a File object or a String (path to a file) and copies it into the DMS, replacing the original document file
* but keeping the rest of the document unchanged.
* @param $file File object, or String that is path to a file to store
* @return DMSDocumentInstance Document object that we replaced the file in
*/
public function replaceDocument($file);
/**
* Hides the DMSDocument, so it does not show up when getByPage($myPage) is called
* (without specifying the $showEmbargoed = true parameter). This is similar to expire, except that this method
* should be used to hide DMSDocuments that have not yet gone live.
* @abstract
* @return null
*/
function embargoIndefinitely();
/**
* Hides the DMSDocument, so it does not show up when getByPage($myPage) is called
* (without specifying the $showEmbargoed = true parameter). This is similar to expire, except that this method
* should be used to hide DMSDocuments that have not yet gone live.
* @abstract
* @return null
*/
public function embargoIndefinitely();
/**
* Returns if this is DMSDocument is embargoed or expired.
* @abstract
* @return bool True or False depending on whether this DMSDocument is embargoed or expired
*/
function isHidden();
/**
* Returns if this is DMSDocument is embargoed or expired.
* @abstract
* @return bool True or False depending on whether this DMSDocument is embargoed or expired
*/
public function isHidden();
/**
* Returns if this is DMSDocument is embargoed.
* @abstract
* @return bool True or False depending on whether this DMSDocument is embargoed
*/
function isEmbargoed();
/**
* Returns if this is DMSDocument is embargoed.
* @abstract
* @return bool True or False depending on whether this DMSDocument is embargoed
*/
public function isEmbargoed();
/**
* Hides the DMSDocument, so it does not show up when getByPage($myPage) is called. Automatically un-hides the
* DMSDocument at a specific date.
* @abstract
* @param $datetime String date time value when this DMSDocument should expire
* @return null
*/
function embargoUntilDate($datetime);
/**
* Hides the DMSDocument, so it does not show up when getByPage($myPage) is called. Automatically un-hides the
* DMSDocument at a specific date.
* @abstract
* @param $datetime String date time value when this DMSDocument should expire
* @return null
*/
public function embargoUntilDate($datetime);
/**
* Hides the document until any page it is linked to is published
* @return null
*/
function embargoUntilPublished();
/**
* Hides the document until any page it is linked to is published
* @return null
*/
public function embargoUntilPublished();
/**
* Clears any previously set embargos, so the DMSDocument always shows up in all queries.
* @abstract
* @return null
*/
function clearEmbargo();
/**
* Clears any previously set embargos, so the DMSDocument always shows up in all queries.
* @abstract
* @return null
*/
public function clearEmbargo();
/**
* Returns if this is DMSDocument is expired.
* @abstract
* @return bool True or False depending on whether this DMSDocument is expired
*/
function isExpired();
/**
* Returns if this is DMSDocument is expired.
* @abstract
* @return bool True or False depending on whether this DMSDocument is expired
*/
public function isExpired();
/**
* Hides the DMSDocument at a specific date, so it does not show up when getByPage($myPage) is called.
* @abstract
* @param $datetime String date time value when this DMSDocument should expire
* @return null
*/
function expireAtDate($datetime);
/**
* Hides the DMSDocument at a specific date, so it does not show up when getByPage($myPage) is called.
* @abstract
* @param $datetime String date time value when this DMSDocument should expire
* @return null
*/
public function expireAtDate($datetime);
/**
* Clears any previously set expiry.
* @abstract
* @return null
*/
function clearExpiry();
/**
* Clears any previously set expiry.
* @abstract
* @return null
*/
public function clearExpiry();
/*---- FROM HERE ON: optional API features ----*/
/*---- FROM HERE ON: optional API features ----*/
/**
* Returns a DataList of all previous Versions of this DMSDocument (check the LastEdited date of each
* object to find the correct one)
* @abstract
* @return DataList List of DMSDocument objects
*/
function getVersions();
}
/**
* Returns a DataList of all previous Versions of this DMSDocument (check the LastEdited date of each
* object to find the correct one)
* @abstract
* @return DataList List of DMSDocument objects
*/
public function getVersions();
}

View File

@ -8,54 +8,55 @@
* 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.
* @static
* @abstract
* @return DMSInterface An instance of the Document Management System
*/
static function inst();
/**
* Factory method that returns an instance of the DMS. This could be any class that implements the DMSInterface.
* @static
* @abstract
* @return DMSInterface An instance of the Document Management System
*/
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.
* When storing a document, sets the fields on the File has "tag" metadata.
* @abstract
* @param $file File object, or String that is path to a file to store
* @return DMSDocumentInstance Document object that we just created
*/
function storeDocument($file);
/**
* Takes a File object or a String (path to a file) and copies it into the DMS. The original file remains unchanged.
* When storing a document, sets the fields on the File has "tag" metadata.
* @abstract
* @param $file File object, or String that is path to a file to store
* @return DMSDocumentInstance Document object that we just created
*/
public function storeDocument($file);
/**
*
* Returns a number of Document objects based on the a search by tags. You can search by category alone,
* by tag value alone, or by both. I.e: getByTag("fruits",null); getByTag(null,"banana"); getByTag("fruits","banana")
* @abstract
* @param null $category The metadata category to search for
* @param null $value The metadata value to search for
* @param bool $showEmbargoed Boolean that specifies if embargoed documents should be included in results
* @return DMSDocumentInterface
*/
function getByTag($category = null, $value = null, $showEmbargoed = false);
/**
*
* Returns a number of Document objects based on the a search by tags. You can search by category alone,
* by tag value alone, or by both. I.e: getByTag("fruits",null); getByTag(null,"banana"); getByTag("fruits","banana")
* @abstract
* @param null $category The metadata category to search for
* @param null $value The metadata value to search for
* @param bool $showEmbargoed Boolean that specifies if embargoed documents should be included in results
* @return DMSDocumentInterface
*/
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
* (if contents is searchable and compatible search module is installed - e.g. FullTextSearch module)
* @abstract
* @param $searchText String to search for
* @param bool $showEmbargoed Boolean that specifies if embargoed documents should be included in results
* @return DMSDocumentInterface
*/
function getByFullTextSearch($searchText, $showEmbargoed = false);
/**
* Returns a number of Document objects that match a full-text search of the Documents and their contents
* (if contents is searchable and compatible search module is installed - e.g. FullTextSearch module)
* @abstract
* @param $searchText String to search for
* @param bool $showEmbargoed Boolean that specifies if embargoed documents should be included in results
* @return DMSDocumentInterface
*/
public function getByFullTextSearch($searchText, $showEmbargoed = false);
/**
* Returns a list of Document objects associated with a Page
* @abstract
* @param $page SiteTree to fetch the associated Documents from
* @param bool $showEmbargoed Boolean that specifies if embargoed documents should be included in results
* @return DataList Document list associated with the Page
*/
function getByPage($page, $showEmbargoed = false);
}
/**
* Returns a list of Document objects associated with a Page
* @abstract
* @param $page SiteTree to fetch the associated Documents from
* @param bool $showEmbargoed Boolean that specifies if embargoed documents should be included in results
* @return DataList Document list associated with the Page
*/
public function getByPage($page, $showEmbargoed = false);
}

View File

@ -3,1260 +3,1366 @@
/**
* @package dms
*/
class DMSDocument extends DataObject implements DMSDocumentInterface {
private static $db = array(
"Filename" => "Varchar(255)", // eg. 3469~2011-energysaving-report.pdf
"Folder" => "Varchar(255)", // eg. 0
"Title" => 'Varchar(1024)', // eg. "Energy Saving Report for Year 2011, New Zealand LandCorp"
"Description" => 'Text',
"ViewCount" => 'Int',
"LastChanged" => 'SS_DateTime', //when this document's file was created or last replaced (small changes like updating title don't count)
"EmbargoedIndefinitely" => 'Boolean(false)',
"EmbargoedUntilPublished" => 'Boolean(false)',
"EmbargoedUntilDate" => 'SS_DateTime',
"ExpireAtDate" => 'SS_DateTime'
);
private static $many_many = array(
'Pages' => 'SiteTree',
'Tags' => 'DMSTag'
);
private static $many_many_extraFields = array(
'Pages' => array(
'DocumentSort' => 'Int'
)
);
private static $display_fields = array(
'ID' => 'ID',
'Title' => 'Title',
'FilenameWithoutID' => 'Filename',
'LastChanged' => 'LastChanged'
);
private static $singular_name = 'Document';
private static $plural_name = 'Documents';
private static $searchable_fields = array(
'ID' => array(
'filter' => 'ExactMatchFilter',
'field' => 'NumericField'
),
'Title',
'Filename',
'LastChanged'
);
/**
* @param Member $member
*
* @return boolean
*/
public function canView($member = null) {
if(!$member || !(is_a($member, 'Member')) || is_numeric($member)) {
$member = Member::currentUser();
}
// extended access checks
$results = $this->extend('canView', $member);
if($results && is_array($results)) {
if(!min($results)) return false;
}
if($member && $member->ID){
return true;
}
return false;
}
/**
* @param Member $member
*
* @return boolean
*/
public function canEdit($member = null) {
if(!$member || !(is_a($member, 'Member')) || is_numeric($member)) {
$member = Member::currentUser();
}
$results = $this->extend('canEdit', $member);
if($results && is_array($results)) {
if(!min($results)) return false;
}
return $this->canView();
}
/**
* @param Member $member
*
* @return boolean
*/
public function canCreate($member = null) {
if(!$member || !(is_a($member, 'Member')) || is_numeric($member)) {
$member = Member::currentUser();
}
$results = $this->extend('canCreate', $member);
if($results && is_array($results)) {
if(!min($results)) return false;
}
return $this->canView();
}
/**
* @param Member $member
*
* @return boolean
*/
public function canDelete($member = null) {
if(!$member || !(is_a($member, 'Member')) || is_numeric($member)) {
$member = Member::currentUser();
}
$results = $this->extend('canDelete', $member);
if($results && is_array($results)) {
if(!min($results)) return false;
}
return $this->canView();
}
/**
* Associates this document with a Page. This method does nothing if the
* association already exists.
*
* This could be a simple wrapper around $myDoc->Pages()->add($myPage) to
* add a many_many relation.
*
* @param SiteTree $pageObject Page object to associate this Document with
*
* @return DMSDocument
*/
public function addPage($pageObject) {
$this->Pages()->add($pageObject);
DB::query("UPDATE \"DMSDocument_Pages\" SET \"DocumentSort\"=\"DocumentSort\"+1 WHERE \"SiteTreeID\" = $pageObject->ID");
return $this;
}
/**
* Associates this DMSDocument with a set of Pages. This method loops
* through a set of page ids, and then associates this DMSDocument with the
* individual Page with the each page id in the set.
*
* @param array $pageIDs
*
* @return DMSDocument
*/
public function addPages($pageIDs) {
foreach($pageIDs as $id) {
$pageObject = DataObject::get_by_id("SiteTree", $id);
if($pageObject && $pageObject->exists()) {
$this->addPage($pageObject);
}
}
return $this;
}
/**
* Removes the association between this Document and a Page. This method
* does nothing if the association does not exist.
*
* @param SiteTree $pageObject Page object to remove the association to
*
* @return DMSDocument
*/
public function removePage($pageObject) {
$this->Pages()->remove($pageObject);
return $this;
}
/**
* @see getPages()
*
* @return DataList
*/
public function Pages() {
$pages = $this->getManyManyComponents('Pages');
$this->extend('updatePages', $pages);
return $pages;
}
/**
* Returns a list of the Page objects associated with this Document.
*
* @return DataList
*/
public function getPages() {
return $this->Pages();
}
/**
* Removes all associated Pages from the DMSDocument
*
* @return DMSDocument
*/
public function removeAllPages() {
$this->Pages()->removeAll();
return $this;
}
/**
* Increase ViewCount by 1, without update any other record fields such as
* LastEdited.
*
* @return DMSDocument
*/
public function trackView() {
if ($this->ID > 0) {
$count = $this->ViewCount + 1;
$this->ViewCount = $count;
DB::query("UPDATE \"DMSDocument\" SET \"ViewCount\"='$count' WHERE \"ID\"={$this->ID}");
}
return $this;
}
/**
* Adds a metadata tag to the Document. The tag has a category and a value.
*
* Each category can have multiple values by default. So:
* addTag("fruit","banana") addTag("fruit", "apple") will add two items.
*
* However, if the third parameter $multiValue is set to 'false', then all
* updates to a category only ever update a single value. So:
* addTag("fruit","banana") addTag("fruit", "apple") would result in a
* single metadata tag: fruit->apple.
*
* Can could be implemented as a key/value store table (although it is more
* like category/value, because the same category can occur multiple times)
*
* @param string $category of a metadata category to add (required)
* @param string $value of a metadata value to add (required)
* @param bool $multiValue Boolean that determines if the category is
* multi-value or single-value (optional)
*
* @return DMSDocument
*/
public function addTag($category, $value, $multiValue = true) {
if ($multiValue) {
//check for a duplicate tag, don't add the duplicate
$currentTag = $this->Tags()->filter(array('Category' => $category, 'Value' => $value));
if ($currentTag->Count() == 0) {
//multi value tag
$tag = new DMSTag();
$tag->Category = $category;
$tag->Value = $value;
$tag->MultiValue = true;
$tag->write();
$tag->Documents()->add($this);
} else {
//add the relation between the tag and document
foreach($currentTag as $tagObj) {
$tagObj->Documents()->add($this);
}
}
} else {
//single value tag
$currentTag = $this->Tags()->filter(array('Category' => $category));
$tag = null;
if ($currentTag->Count() == 0) {
//create the single-value tag
$tag = new DMSTag();
$tag->Category = $category;
$tag->Value = $value;
$tag->MultiValue = false;
$tag->write();
} else {
//update the single value tag
$tag = $currentTag->first();
$tag->Value = $value;
$tag->MultiValue = false;
$tag->write();
}
// regardless of whether we created a new tag or are just updating an
// existing one, add the relation
$tag->Documents()->add($this);
}
return $this;
}
/**
* @param string $category
* @param string $value
*
* @return DataList
*/
protected function getTagsObjects($category, $value = null) {
$valueFilter = array("Category" => $category);
if (!empty($value)) $valueFilter['Value'] = $value;
$tags = $this->Tags()->filter($valueFilter);
return $tags;
}
/**
* Fetches all tags associated with this DMSDocument within a given
* category. If a value is specified this method tries to fetch that
* specific tag.
*
* @param string $category metadata category to get
* @param string $value value of the tag to get
*
* @return array Strings of all the tags or null if there is no match found
*/
public function getTagsList($category, $value = null) {
$tags = $this->getTagsObjects($category, $value);
$returnArray = null;
if ($tags->Count() > 0) {
$returnArray = array();
foreach($tags as $t) {
$returnArray[] = $t->Value;
}
}
return $returnArray;
}
/**
* Removes a tag from the Document. If you only set a category, then all
* values in that category are deleted.
*
* If you specify both a category and a value, then only that single
* category/value pair is deleted.
*
* Nothing happens if the category or the value do not exist.
*
* @param string $category Category to remove
* @param string $value Value to remove
*
* @return DMSDocument
*/
public function removeTag($category, $value = null) {
$tags = $this->getTagsObjects($category, $value);
if ($tags->Count() > 0) {
foreach($tags as $t) {
$documentList = $t->Documents();
//remove the relation between the tag and the document
$documentList->remove($this);
//delete the entire tag if it has no relations left
if ($documentList->Count() == 0) $t->delete();
}
}
return $this;
}
/**
* Deletes all tags associated with this Document.
*
* @return DMSDocument
*/
public function removeAllTags() {
$allTags = $this->Tags();
foreach($allTags as $tag) {
$documentlist = $tag->Documents();
$documentlist->remove($this);
if ($tag->Documents()->Count() == 0) $tag->delete();
}
return $this;
}
/**
* Returns a link to download this document from the DMS store.
*
* @return string
*/
public function getLink() {
return Controller::join_links(Director::baseURL(),'dmsdocument/'.$this->ID);
}
/**
* @return string
*/
public function Link() {
return $this->getLink();
}
/**
* Hides the document, so it does not show up when getByPage($myPage) is
* called (without specifying the $showEmbargoed = true parameter).
*
* This is similar to expire, except that this method should be used to hide
* documents that have not yet gone live.
*
* @param bool $write Save change to the database
*
* @return DMSDocument
*/
public function embargoIndefinitely($write = true) {
$this->EmbargoedIndefinitely = true;
if ($write) $this->write();
return $this;
}
/**
* Hides the document until any page it is linked to is published
*
* @param bool $write Save change to database
*
* @return DMSDocument
*/
public function embargoUntilPublished($write = true) {
$this->EmbargoedUntilPublished = true;
if ($write) $this->write();
return $this;
}
/**
* Returns if this is Document is embargoed or expired.
*
* Also, returns if the document should be displayed on the front-end,
* respecting the current reading mode of the site and the embargo status.
*
class DMSDocument extends DataObject implements DMSDocumentInterface
{
private static $db = array(
"Filename" => "Varchar(255)", // eg. 3469~2011-energysaving-report.pdf
"Folder" => "Varchar(255)", // eg. 0
"Title" => 'Varchar(1024)', // eg. "Energy Saving Report for Year 2011, New Zealand LandCorp"
"Description" => 'Text',
"ViewCount" => 'Int',
"LastChanged" => 'SS_DateTime', //when this document's file was created or last replaced (small changes like updating title don't count)
"EmbargoedIndefinitely" => 'Boolean(false)',
"EmbargoedUntilPublished" => 'Boolean(false)',
"EmbargoedUntilDate" => 'SS_DateTime',
"ExpireAtDate" => 'SS_DateTime'
);
private static $many_many = array(
'Pages' => 'SiteTree',
'Tags' => 'DMSTag'
);
private static $many_many_extraFields = array(
'Pages' => array(
'DocumentSort' => 'Int'
)
);
private static $display_fields = array(
'ID' => 'ID',
'Title' => 'Title',
'FilenameWithoutID' => 'Filename',
'LastChanged' => 'LastChanged'
);
private static $singular_name = 'Document';
private static $plural_name = 'Documents';
private static $searchable_fields = array(
'ID' => array(
'filter' => 'ExactMatchFilter',
'field' => 'NumericField'
),
'Title',
'Filename',
'LastChanged'
);
/**
* @param Member $member
*
* @return boolean
*/
public function canView($member = null)
{
if (!$member || !(is_a($member, 'Member')) || is_numeric($member)) {
$member = Member::currentUser();
}
// extended access checks
$results = $this->extend('canView', $member);
if ($results && is_array($results)) {
if (!min($results)) {
return false;
}
}
if ($member && $member->ID) {
return true;
}
return false;
}
/**
* @param Member $member
*
* @return boolean
*/
public function canEdit($member = null)
{
if (!$member || !(is_a($member, 'Member')) || is_numeric($member)) {
$member = Member::currentUser();
}
$results = $this->extend('canEdit', $member);
if ($results && is_array($results)) {
if (!min($results)) {
return false;
}
}
return $this->canView();
}
/**
* @param Member $member
*
* @return boolean
*/
public function canCreate($member = null)
{
if (!$member || !(is_a($member, 'Member')) || is_numeric($member)) {
$member = Member::currentUser();
}
$results = $this->extend('canCreate', $member);
if ($results && is_array($results)) {
if (!min($results)) {
return false;
}
}
return $this->canView();
}
/**
* @param Member $member
*
* @return boolean
*/
public function canDelete($member = null)
{
if (!$member || !(is_a($member, 'Member')) || is_numeric($member)) {
$member = Member::currentUser();
}
$results = $this->extend('canDelete', $member);
if ($results && is_array($results)) {
if (!min($results)) {
return false;
}
}
return $this->canView();
}
/**
* Associates this document with a Page. This method does nothing if the
* association already exists.
*
* This could be a simple wrapper around $myDoc->Pages()->add($myPage) to
* add a many_many relation.
*
* @param SiteTree $pageObject Page object to associate this Document with
*
* @return DMSDocument
*/
public function addPage($pageObject)
{
$this->Pages()->add($pageObject);
DB::query("UPDATE \"DMSDocument_Pages\" SET \"DocumentSort\"=\"DocumentSort\"+1 WHERE \"SiteTreeID\" = $pageObject->ID");
return $this;
}
/**
* Associates this DMSDocument with a set of Pages. This method loops
* through a set of page ids, and then associates this DMSDocument with the
* individual Page with the each page id in the set.
*
* @param array $pageIDs
*
* @return DMSDocument
*/
public function addPages($pageIDs)
{
foreach ($pageIDs as $id) {
$pageObject = DataObject::get_by_id("SiteTree", $id);
if ($pageObject && $pageObject->exists()) {
$this->addPage($pageObject);
}
}
return $this;
}
/**
* Removes the association between this Document and a Page. This method
* does nothing if the association does not exist.
*
* @param SiteTree $pageObject Page object to remove the association to
*
* @return DMSDocument
*/
public function removePage($pageObject)
{
$this->Pages()->remove($pageObject);
return $this;
}
/**
* @see getPages()
*
* @return DataList
*/
public function Pages()
{
$pages = $this->getManyManyComponents('Pages');
$this->extend('updatePages', $pages);
return $pages;
}
/**
* Returns a list of the Page objects associated with this Document.
*
* @return DataList
*/
public function getPages()
{
return $this->Pages();
}
/**
* Removes all associated Pages from the DMSDocument
*
* @return DMSDocument
*/
public function removeAllPages()
{
$this->Pages()->removeAll();
return $this;
}
/**
* Increase ViewCount by 1, without update any other record fields such as
* LastEdited.
*
* @return DMSDocument
*/
public function trackView()
{
if ($this->ID > 0) {
$count = $this->ViewCount + 1;
$this->ViewCount = $count;
DB::query("UPDATE \"DMSDocument\" SET \"ViewCount\"='$count' WHERE \"ID\"={$this->ID}");
}
return $this;
}
/**
* Adds a metadata tag to the Document. The tag has a category and a value.
*
* Each category can have multiple values by default. So:
* addTag("fruit","banana") addTag("fruit", "apple") will add two items.
*
* However, if the third parameter $multiValue is set to 'false', then all
* updates to a category only ever update a single value. So:
* addTag("fruit","banana") addTag("fruit", "apple") would result in a
* single metadata tag: fruit->apple.
*
* Can could be implemented as a key/value store table (although it is more
* like category/value, because the same category can occur multiple times)
*
* @param string $category of a metadata category to add (required)
* @param string $value of a metadata value to add (required)
* @param bool $multiValue Boolean that determines if the category is
* multi-value or single-value (optional)
*
* @return DMSDocument
*/
public function addTag($category, $value, $multiValue = true)
{
if ($multiValue) {
//check for a duplicate tag, don't add the duplicate
$currentTag = $this->Tags()->filter(array('Category' => $category, 'Value' => $value));
if ($currentTag->Count() == 0) {
//multi value tag
$tag = new DMSTag();
$tag->Category = $category;
$tag->Value = $value;
$tag->MultiValue = true;
$tag->write();
$tag->Documents()->add($this);
} else {
//add the relation between the tag and document
foreach ($currentTag as $tagObj) {
$tagObj->Documents()->add($this);
}
}
} else {
//single value tag
$currentTag = $this->Tags()->filter(array('Category' => $category));
$tag = null;
if ($currentTag->Count() == 0) {
//create the single-value tag
$tag = new DMSTag();
$tag->Category = $category;
$tag->Value = $value;
$tag->MultiValue = false;
$tag->write();
} else {
//update the single value tag
$tag = $currentTag->first();
$tag->Value = $value;
$tag->MultiValue = false;
$tag->write();
}
// regardless of whether we created a new tag or are just updating an
// existing one, add the relation
$tag->Documents()->add($this);
}
return $this;
}
/**
* @param string $category
* @param string $value
*
* @return DataList
*/
protected function getTagsObjects($category, $value = null)
{
$valueFilter = array("Category" => $category);
if (!empty($value)) {
$valueFilter['Value'] = $value;
}
$tags = $this->Tags()->filter($valueFilter);
return $tags;
}
/**
* Fetches all tags associated with this DMSDocument within a given
* category. If a value is specified this method tries to fetch that
* specific tag.
*
* @param string $category metadata category to get
* @param string $value value of the tag to get
*
* @return array Strings of all the tags or null if there is no match found
*/
public function getTagsList($category, $value = null)
{
$tags = $this->getTagsObjects($category, $value);
$returnArray = null;
if ($tags->Count() > 0) {
$returnArray = array();
foreach ($tags as $t) {
$returnArray[] = $t->Value;
}
}
return $returnArray;
}
/**
* Removes a tag from the Document. If you only set a category, then all
* values in that category are deleted.
*
* If you specify both a category and a value, then only that single
* category/value pair is deleted.
*
* Nothing happens if the category or the value do not exist.
*
* @param string $category Category to remove
* @param string $value Value to remove
*
* @return DMSDocument
*/
public function removeTag($category, $value = null)
{
$tags = $this->getTagsObjects($category, $value);
if ($tags->Count() > 0) {
foreach ($tags as $t) {
$documentList = $t->Documents();
//remove the relation between the tag and the document
$documentList->remove($this);
//delete the entire tag if it has no relations left
if ($documentList->Count() == 0) {
$t->delete();
}
}
}
return $this;
}
/**
* Deletes all tags associated with this Document.
*
* @return DMSDocument
*/
public function removeAllTags()
{
$allTags = $this->Tags();
foreach ($allTags as $tag) {
$documentlist = $tag->Documents();
$documentlist->remove($this);
if ($tag->Documents()->Count() == 0) {
$tag->delete();
}
}
return $this;
}
/**
* Returns a link to download this document from the DMS store.
*
* @return string
*/
public function getLink()
{
return Controller::join_links(Director::baseURL(), 'dmsdocument/'.$this->ID);
}
/**
* @return string
*/
public function Link()
{
return $this->getLink();
}
/**
* Hides the document, so it does not show up when getByPage($myPage) is
* called (without specifying the $showEmbargoed = true parameter).
*
* This is similar to expire, except that this method should be used to hide
* documents that have not yet gone live.
*
* @param bool $write Save change to the database
*
* @return DMSDocument
*/
public function embargoIndefinitely($write = true)
{
$this->EmbargoedIndefinitely = true;
if ($write) {
$this->write();
}
return $this;
}
/**
* Hides the document until any page it is linked to is published
*
* @param bool $write Save change to database
*
* @return DMSDocument
*/
public function embargoUntilPublished($write = true)
{
$this->EmbargoedUntilPublished = true;
if ($write) {
$this->write();
}
return $this;
}
/**
* Returns if this is Document is embargoed or expired.
*
* Also, returns if the document should be displayed on the front-end,
* respecting the current reading mode of the site and the embargo status.
*
* I.e. if a document is embargoed until published, then it should still
* show up in draft mode.
*
* @return bool
*/
public function isHidden() {
$hidden = $this->isEmbargoed() || $this->isExpired();
$readingMode = Versioned::get_reading_mode();
if ($readingMode == "Stage.Stage") {
if($this->EmbargoedUntilPublished == true) {
$hidden = false;
}
}
return $hidden;
}
/**
* Returns if this is Document is embargoed.
*
* @return bool
*/
public function isEmbargoed() {
if (is_object($this->EmbargoedUntilDate)) {
$this->EmbargoedUntilDate = $this->EmbargoedUntilDate->Value;
}
$embargoed = false;
if ($this->EmbargoedIndefinitely) {
$embargoed = true;
} else if ($this->EmbargoedUntilPublished) {
$embargoed = true;
} else if (!empty($this->EmbargoedUntilDate)) {
if(SS_Datetime::now()->Value < $this->EmbargoedUntilDate) {
$embargoed = true;
}
}
return $embargoed;
}
/**
* Hides the document, so it does not show up when getByPage($myPage) is
* called. Automatically un-hides the Document at a specific date.
*
* @param string $datetime date time value when this Document should expire.
* @param bool $write
*
* @return DMSDocument
*/
public function embargoUntilDate($datetime, $write = true) {
$this->EmbargoedUntilDate = DBField::create_field('SS_Datetime', $datetime)->Format('Y-m-d H:i:s');
if ($write) $this->write();
return $this;
}
/**
* Clears any previously set embargos, so the Document always shows up in
* all queries.
*
* @param bool $write
*
* @return DMSDocument
*/
public function clearEmbargo($write = true) {
$this->EmbargoedIndefinitely = false;
$this->EmbargoedUntilPublished = false;
$this->EmbargoedUntilDate = null;
if ($write) $this->write();
return $this;
}
/**
* Returns if this is Document is expired.
*
* @return bool
*/
public function isExpired() {
if (is_object($this->ExpireAtDate)) {
$this->ExpireAtDate = $this->ExpireAtDate->Value;
}
$expired = false;
if (!empty($this->ExpireAtDate)) {
if(SS_Datetime::now()->Value >= $this->ExpireAtDate) {
$expired = true;
}
}
return $expired;
}
/**
* Hides the document at a specific date, so it does not show up when
* getByPage($myPage) is called.
*
* @param string $datetime date time value when this Document should expire
* @param bool $write
*
* @return DMSDocument
*/
public function expireAtDate($datetime, $write = true) {
$this->ExpireAtDate = DBField::create_field('SS_Datetime', $datetime)->Format('Y-m-d H:i:s');
if ($write) $this->write();
return $this;
}
/**
* Clears any previously set expiry.
*
* @param bool $write
*
* @return DMSDocument
*/
public function clearExpiry($write = true) {
$this->ExpireAtDate = null;
if ($write) $this->write();
return $this;
}
/**
* Returns a DataList of all previous Versions of this document (check the
* LastEdited date of each object to find the correct one).
*
* If {@link DMSDocument_versions::$enable_versions} is disabled then an
* Exception is thrown
*
* @throws Exception
*
* @return DataList List of Document objects
*/
public function getVersions() {
if (!DMSDocument_versions::$enable_versions) {
throw new Exception("DMSDocument versions are disabled");
}
return DMSDocument_versions::get_versions($this);
}
/**
* Returns the full filename of the document stored in this object.
*
* @return string
*/
public function getFullPath() {
if($this->Filename) {
return DMS::get_dms_path() . DIRECTORY_SEPARATOR . $this->Folder . DIRECTORY_SEPARATOR . $this->Filename;
}
return null;
}
/**
* Returns the filename of this asset.
*
* @return string
*/
public function getFileName() {
if($this->getField('Filename')) {
return $this->getField('Filename');
} else {
return ASSETS_DIR . '/';
}
}
/**
* @return string
*/
public function getName() {
return $this->getField('Title');
}
/**
* @return string
*/
public function getFilenameWithoutID() {
$filenameParts = explode('~',$this->Filename);
$filename = array_pop($filenameParts);
return $filename;
}
/**
* @return string
*/
public function getStorageFolder() {
return DMS::get_dms_path() . DIRECTORY_SEPARATOR . DMS::get_storage_folder($this->ID);
}
/**
* Deletes the DMSDocument, its underlying file, as well as any tags related
* to this DMSDocument. Also calls the parent DataObject's delete method in
* order to complete an cascade.
*
* @return void
*/
public function delete() {
// remove tags
$this->removeAllTags();
// delete the file (and previous versions of files)
$filesToDelete = array();
$storageFolder = $this->getStorageFolder();
if (file_exists($storageFolder)) {
if ($handle = opendir($storageFolder)) {
while (false !== ($entry = readdir($handle))) {
// only delete if filename starts the the relevant ID
if(strpos($entry,$this->ID.'~') === 0) {
$filesToDelete[] = $entry;
}
}
closedir($handle);
//delete all this files that have the id of this document
foreach($filesToDelete as $file) {
$filePath = $storageFolder .DIRECTORY_SEPARATOR . $file;
if (is_file($filePath)) {
unlink($filePath);
}
}
}
}
$this->removeAllPages();
// get rid of any versions have saved for this DMSDocument, too
if (DMSDocument_versions::$enable_versions) {
$versions = $this->getVersions();
if ($versions->Count() > 0) {
foreach($versions as $v) {
$v->delete();
}
}
}
parent::delete();
}
/**
* Relate an existing file on the filesystem to the document.
*
* Copies the file to the new destination, as defined in {@link get_DMS_path()}.
*
* @param string $filePath Path to file, relative to webroot.
*
* @return DMSDocument
*/
public function storeDocument($filePath) {
if (empty($this->ID)) {
user_error("Document must be written to database before it can store documents", E_USER_ERROR);
}
// calculate all the path to copy the file to
$fromFilename = basename($filePath);
$toFilename = $this->ID. '~' . $fromFilename; //add the docID to the start of the Filename
$toFolder = DMS::get_storage_folder($this->ID);
$toPath = DMS::get_dms_path() . DIRECTORY_SEPARATOR . $toFolder . DIRECTORY_SEPARATOR . $toFilename;
DMS::create_storage_folder(DMS::get_dms_path() . DIRECTORY_SEPARATOR . $toFolder);
//copy the file into place
$fromPath = BASE_PATH . DIRECTORY_SEPARATOR . $filePath;
//version the existing file (copy it to a new "very specific" filename
if (DMSDocument_versions::$enable_versions) {
DMSDocument_versions::create_version($this);
} else { //otherwise delete the old document file
$oldPath = $this->getFullPath();
if (file_exists($oldPath)) unlink($oldPath);
}
copy($fromPath, $toPath); //this will overwrite the existing file (if present)
//write the filename of the stored document
$this->Filename = $toFilename;
$this->Folder = $toFolder;
$extension = pathinfo($this->Filename, PATHINFO_EXTENSION);
if (empty($this->Title)) {
// don't overwrite existing document titles
$this->Title = basename($filePath,'.'.$extension);
}
$this->LastChanged = SS_Datetime::now()->Rfc2822();
$this->write();
return $this;
}
/**
* Takes a File object or a String (path to a file) and copies it into the
* DMS, replacing the original document file but keeping the rest of the
* document unchanged.
*
* @param File|string $file path to a file to store
*
* @return DMSDocument object that we replaced the file in
*/
public function replaceDocument($file) {
$filePath = DMS::transform_file_to_file_path($file);
$doc = $this->storeDocument($filePath); // replace the document
return $doc;
}
/**
* Return the type of file for the given extension
* on the current file name.
*
* @param string $ext
*
* @return string
*/
public static function get_file_type($ext) {
$types = array(
'gif' => 'GIF image - good for diagrams',
'jpg' => 'JPEG image - good for photos',
'jpeg' => 'JPEG image - good for photos',
'png' => 'PNG image - good general-purpose format',
'ico' => 'Icon image',
'tiff' => 'Tagged image format',
'doc' => 'Word document',
'xls' => 'Excel spreadsheet',
'zip' => 'ZIP compressed file',
'gz' => 'GZIP compressed file',
'dmg' => 'Apple disk image',
'pdf' => 'Adobe Acrobat PDF file',
'mp3' => 'MP3 audio file',
'wav' => 'WAV audo file',
'avi' => 'AVI video file',
'mpg' => 'MPEG video file',
'mpeg' => 'MPEG video file',
'js' => 'Javascript file',
'css' => 'CSS file',
'html' => 'HTML file',
'htm' => 'HTML file'
);
return isset($types[$ext]) ? $types[$ext] : $ext;
}
/**
* Returns the Description field with HTML <br> tags added when there is a
* line break.
*
* @return string
*/
public function getDescriptionWithLineBreak() {
return nl2br($this->getField('Description'));
}
/**
* @return FieldList
*/
public function getCMSFields() {
//include JS to handling showing and hiding of bottom "action" tabs
Requirements::javascript(DMS_DIR.'/javascript/DMSDocumentCMSFields.js');
Requirements::css(DMS_DIR.'/css/DMSDocumentCMSFields.css');
$fields = new FieldList(); //don't use the automatic scaffolding, it is slow and unnecessary here
$extraTasks = ''; //additional text to inject into the list of tasks at the bottom of a DMSDocument CMSfield
$extraFields = FormField::create('Empty');
//get list of shortcode page relations
$relationFinder = new ShortCodeRelationFinder();
$relationList = $relationFinder->getList($this->ID);
$fieldsTop = $this->getFieldsForFile($relationList->count());
$fields->add($fieldsTop);
$fields->add(new TextField('Title','Title'));
$fields->add(new TextareaField('Description','Description'));
//create upload field to replace document
$uploadField = new DMSUploadField('ReplaceFile', 'Replace file');
$uploadField->setConfig('allowedMaxFileNumber', 1);
$uploadField->setConfig('downloadTemplateName', 'ss-dmsuploadfield-downloadtemplate');
$uploadField->setRecord($this);
$gridFieldConfig = GridFieldConfig::create()->addComponents(
new GridFieldToolbarHeader(),
new GridFieldSortableHeader(),
new GridFieldDataColumns(),
new GridFieldPaginator(30),
//new GridFieldEditButton(),
new GridFieldDetailForm()
);
$gridFieldConfig->getComponentByType('GridFieldDataColumns')
->setDisplayFields(array(
'Title'=>'Title',
'ClassName'=>'Page Type',
'ID'=>'Page ID'
))
->setFieldFormatting(array(
'Title'=>sprintf(
'<a class=\"cms-panel-link\" href=\"%s/$ID\">$Title</a>',
singleton('CMSPageEditController')->Link('show')
)
));
$pagesGrid = GridField::create(
'Pages',
_t('DMSDocument.RelatedPages', 'Related Pages'),
$this->Pages(),
$gridFieldConfig
);
$referencesGrid = GridField::create(
'References',
_t('DMSDocument.RelatedReferences', 'Related References'),
$relationList,
$gridFieldConfig
);
if (DMSDocument_versions::$enable_versions) {
$versionsGridFieldConfig = GridFieldConfig::create()->addComponents(
new GridFieldToolbarHeader(),
new GridFieldSortableHeader(),
new GridFieldDataColumns(),
new GridFieldPaginator(30)
);
$versionsGridFieldConfig->getComponentByType('GridFieldDataColumns')->setDisplayFields(Config::inst()->get('DMSDocument_versions', 'display_fields'))
->setFieldCasting(array('LastChanged'=>"Datetime->Ago"))
->setFieldFormatting(array('FilenameWithoutID'=>'<a target=\'_blank\' class=\'file-url\' href=\'$Link\'>$FilenameWithoutID</a>'));
$versionsGrid = GridField::create(
'Versions',
_t('DMSDocument.Versions', 'Versions'),
$this->getVersions(),
$versionsGridFieldConfig
);
$extraTasks .= '<li class="ss-ui-button" data-panel="find-versions">Versions</li>';
//$extraFields = $versionsGrid->addExtraClass('find-versions');
}
$fields->add(new LiteralField('BottomTaskSelection',
'<div id="Actions" class="field actions"><label class="left">Actions</label><ul>'.
'<li class="ss-ui-button" data-panel="embargo">Embargo</li>'.
'<li class="ss-ui-button" data-panel="expiry">Expiry</li>'.
'<li class="ss-ui-button" data-panel="replace">Replace</li>'.
'<li class="ss-ui-button" data-panel="find-usage">Usage</li>'.
'<li class="ss-ui-button" data-panel="find-references">References</li>'.
$extraTasks.
'</ul></div>'));
$embargoValue = 'None';
if ($this->EmbargoedIndefinitely) $embargoValue = 'Indefinitely';
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);
$embargoDatetime = DatetimeField::create('EmbargoedUntilDate','');
$embargoDatetime->getDateField()->setConfig('showcalendar', true)->setConfig('dateformat', 'dd-MM-yyyy')->setConfig('datavalueformat', 'dd-MM-yyyy');
$expiryValue = 'None';
if (!empty($this->ExpireAtDate)) $expiryValue = 'Date';
$expiry = new OptionsetField('Expiry','Expiry',array('None'=>'None','Date'=>'Set document to expire on'),$expiryValue);
$expiryDatetime = DatetimeField::create('ExpireAtDate','');
$expiryDatetime->getDateField()->setConfig('showcalendar', true)->setConfig('dateformat', 'dd-MM-yyyy')->setConfig('datavalueformat', 'dd-MM-yyyy');
// This adds all the actions details into a group.
// Embargo, History, etc to go in here
// These are toggled on and off via the Actions Buttons above
// exit('hit');
$actionsPanel = FieldGroup::create(
FieldGroup::create(
$embargo,
$embargoDatetime
)->addExtraClass('embargo'),
FieldGroup::create(
$expiry,
$expiryDatetime
)->addExtraClass('expiry'),
FieldGroup::create(
$uploadField
)->addExtraClass('replace'),
FieldGroup::create(
$pagesGrid
)->addExtraClass('find-usage'),
FieldGroup::create(
$referencesGrid
)->addExtraClass('find-references'),
FieldGroup::create(
$versionsGrid
)->addExtraClass('find-versions')
);
$actionsPanel->setName("ActionsPanel");
$actionsPanel->addExtraClass("ActionsPanel");
$fields->push($actionsPanel);
// $fields->add(FieldGroup::create(
// FieldGroup::create(
// $embargo,
// $embargoDatetime
// )->addExtraClass('embargo'),
// FieldGroup::create(
// $expiry,
// $expiryDatetime
// )->addExtraClass('expiry'),
// $uploadField->addExtraClass('replace'),
// $pagesGrid->addExtraClass('find-usage'),
// $referencesGrid->addExtraClass('find-references'),
// $extraFields
// )->setName("ActionsPanel")->addExtraClass('dmsupload ss-uploadfield'));
$this->extend('updateCMSFields', $fields);
return $fields;
}
public function onBeforeWrite() {
parent::onBeforeWrite();
if (isset($this->Embargo)) {
//set the embargo options from the OptionSetField created in the getCMSFields method
//do not write after clearing the embargo (write happens automatically)
$savedDate = $this->EmbargoedUntilDate;
$this->clearEmbargo(false); //clear all previous settings and re-apply them on save
if ($this->Embargo == 'Published') $this->embargoUntilPublished(false);
if ($this->Embargo == 'Indefinitely') $this->embargoIndefinitely(false);
if ($this->Embargo == 'Date') $this->embargoUntilDate($savedDate, false);
}
if (isset($this->Expiry)) {
if ($this->Expiry == 'Date') $this->expireAtDate($this->ExpireAtDate, false);
else $this->clearExpiry(false); //clear all previous settings
}
}
/**
* Return the relative URL of an icon for the file type, based on the
* {@link appCategory()} value.
*
* Images are searched for in "dms/images/app_icons/".
*
* @return string
*/
public function Icon($ext) {
if(!Director::fileExists(DMS_DIR."/images/app_icons/{$ext}_32.png")) {
$ext = File::get_app_category($ext);
}
if(!Director::fileExists(DMS_DIR."/images/app_icons/{$ext}_32.png")) {
$ext = "generic";
}
return DMS_DIR."/images/app_icons/{$ext}_32.png";
}
/**
* Return the extension of the file associated with the document
*
* @return string
*/
public function getExtension() {
return strtolower(pathinfo($this->Filename, PATHINFO_EXTENSION));
}
/**
* @return string
*/
public function getSize() {
$size = $this->getAbsoluteSize();
return ($size) ? File::format_size($size) : false;
}
/**
* Return the size of the file associated with the document.
*
* @return string
*/
public function getAbsoluteSize() {
return file_exists($this->getFullPath()) ? filesize($this->getFullPath()) : null;
}
/**
* An alias to DMSDocument::getSize()
*
* @return string
*/
public function getFileSizeFormatted() {
return $this->getSize();
}
/**
* @return FieldList
*/
protected function getFieldsForFile($relationListCount) {
$extension = $this->getExtension();
$previewField = new LiteralField("ImageFull",
"<img id='thumbnailImage' class='thumbnail-preview' src='{$this->Icon($extension)}?r=" . rand(1,100000) . "' alt='{$this->Title}' />\n"
);
//count the number of pages this document is published on
$publishedOnCount = $this->Pages()->Count();
$publishedOnValue = "$publishedOnCount pages";
if ($publishedOnCount == 1) $publishedOnValue = "$publishedOnCount page";
$relationListCountValue = "$relationListCount pages";
if ($relationListCount == 1) $relationListCountValue = "$relationListCount page";
$fields = new FieldGroup(
$filePreview = CompositeField::create(
CompositeField::create(
$previewField
)->setName("FilePreviewImage")->addExtraClass('cms-file-info-preview'),
CompositeField::create(
CompositeField::create(
new ReadonlyField("ID", "ID number". ':', $this->ID),
new ReadonlyField("FileType", _t('AssetTableField.TYPE','File type') . ':', self::get_file_type($extension)),
new ReadonlyField("Size", _t('AssetTableField.SIZE','File size') . ':', $this->getFileSizeFormatted()),
$urlField = new ReadonlyField('ClickableURL', _t('AssetTableField.URL','URL'),
sprintf('<a href="%s" target="_blank" class="file-url">%s</a>', $this->getLink(), $this->getLink())
),
new ReadonlyField("FilenameWithoutIDField", "Filename". ':', $this->getFilenameWithoutID()),
new DateField_Disabled("Created", _t('AssetTableField.CREATED','First uploaded') . ':', $this->Created),
new DateField_Disabled("LastEdited", _t('AssetTableField.LASTEDIT','Last changed') . ':', $this->LastEdited),
new DateField_Disabled("LastChanged", _t('AssetTableField.LASTCHANGED','Last replaced') . ':', $this->LastChanged),
new ReadonlyField("PublishedOn", "Published on". ':', $publishedOnValue),
new ReadonlyField("ReferencedOn", "Referenced on". ':', $relationListCountValue),
new ReadonlyField("ViewCount", "View count". ':', $this->ViewCount)
)
)->setName("FilePreviewData")->addExtraClass('cms-file-info-data')
)->setName("FilePreview")->addExtraClass('cms-file-info')
);
$fields->setName('FileP');
$urlField->dontEscape = true;
return $fields;
}
/**
* Takes a file and adds it to the DMSDocument storage, replacing the
* current file.
*
* @param File $file
*
* @return DMSDocument
*/
public function ingestFile($file) {
$this->replaceDocument($file);
$file->delete();
return $this;
}
* @return bool
*/
public function isHidden()
{
$hidden = $this->isEmbargoed() || $this->isExpired();
$readingMode = Versioned::get_reading_mode();
if ($readingMode == "Stage.Stage") {
if ($this->EmbargoedUntilPublished == true) {
$hidden = false;
}
}
return $hidden;
}
/**
* Returns if this is Document is embargoed.
*
* @return bool
*/
public function isEmbargoed()
{
if (is_object($this->EmbargoedUntilDate)) {
$this->EmbargoedUntilDate = $this->EmbargoedUntilDate->Value;
}
$embargoed = false;
if ($this->EmbargoedIndefinitely) {
$embargoed = true;
} elseif ($this->EmbargoedUntilPublished) {
$embargoed = true;
} elseif (!empty($this->EmbargoedUntilDate)) {
if (SS_Datetime::now()->Value < $this->EmbargoedUntilDate) {
$embargoed = true;
}
}
return $embargoed;
}
/**
* Hides the document, so it does not show up when getByPage($myPage) is
* called. Automatically un-hides the Document at a specific date.
*
* @param string $datetime date time value when this Document should expire.
* @param bool $write
*
* @return DMSDocument
*/
public function embargoUntilDate($datetime, $write = true)
{
$this->EmbargoedUntilDate = DBField::create_field('SS_Datetime', $datetime)->Format('Y-m-d H:i:s');
if ($write) {
$this->write();
}
return $this;
}
/**
* Clears any previously set embargos, so the Document always shows up in
* all queries.
*
* @param bool $write
*
* @return DMSDocument
*/
public function clearEmbargo($write = true)
{
$this->EmbargoedIndefinitely = false;
$this->EmbargoedUntilPublished = false;
$this->EmbargoedUntilDate = null;
if ($write) {
$this->write();
}
return $this;
}
/**
* Returns if this is Document is expired.
*
* @return bool
*/
public function isExpired()
{
if (is_object($this->ExpireAtDate)) {
$this->ExpireAtDate = $this->ExpireAtDate->Value;
}
$expired = false;
if (!empty($this->ExpireAtDate)) {
if (SS_Datetime::now()->Value >= $this->ExpireAtDate) {
$expired = true;
}
}
return $expired;
}
/**
* Hides the document at a specific date, so it does not show up when
* getByPage($myPage) is called.
*
* @param string $datetime date time value when this Document should expire
* @param bool $write
*
* @return DMSDocument
*/
public function expireAtDate($datetime, $write = true)
{
$this->ExpireAtDate = DBField::create_field('SS_Datetime', $datetime)->Format('Y-m-d H:i:s');
if ($write) {
$this->write();
}
return $this;
}
/**
* Clears any previously set expiry.
*
* @param bool $write
*
* @return DMSDocument
*/
public function clearExpiry($write = true)
{
$this->ExpireAtDate = null;
if ($write) {
$this->write();
}
return $this;
}
/**
* Returns a DataList of all previous Versions of this document (check the
* LastEdited date of each object to find the correct one).
*
* If {@link DMSDocument_versions::$enable_versions} is disabled then an
* Exception is thrown
*
* @throws Exception
*
* @return DataList List of Document objects
*/
public function getVersions()
{
if (!DMSDocument_versions::$enable_versions) {
throw new Exception("DMSDocument versions are disabled");
}
return DMSDocument_versions::get_versions($this);
}
/**
* Returns the full filename of the document stored in this object.
*
* @return string
*/
public function getFullPath()
{
if ($this->Filename) {
return DMS::get_dms_path() . DIRECTORY_SEPARATOR . $this->Folder . DIRECTORY_SEPARATOR . $this->Filename;
}
return null;
}
/**
* Returns the filename of this asset.
*
* @return string
*/
public function getFileName()
{
if ($this->getField('Filename')) {
return $this->getField('Filename');
} else {
return ASSETS_DIR . '/';
}
}
/**
* @return string
*/
public function getName()
{
return $this->getField('Title');
}
/**
* @return string
*/
public function getFilenameWithoutID()
{
$filenameParts = explode('~', $this->Filename);
$filename = array_pop($filenameParts);
return $filename;
}
/**
* @return string
*/
public function getStorageFolder()
{
return DMS::get_dms_path() . DIRECTORY_SEPARATOR . DMS::get_storage_folder($this->ID);
}
/**
* Deletes the DMSDocument, its underlying file, as well as any tags related
* to this DMSDocument. Also calls the parent DataObject's delete method in
* order to complete an cascade.
*
* @return void
*/
public function delete()
{
// remove tags
$this->removeAllTags();
// delete the file (and previous versions of files)
$filesToDelete = array();
$storageFolder = $this->getStorageFolder();
if (file_exists($storageFolder)) {
if ($handle = opendir($storageFolder)) {
while (false !== ($entry = readdir($handle))) {
// only delete if filename starts the the relevant ID
if (strpos($entry, $this->ID.'~') === 0) {
$filesToDelete[] = $entry;
}
}
closedir($handle);
//delete all this files that have the id of this document
foreach ($filesToDelete as $file) {
$filePath = $storageFolder .DIRECTORY_SEPARATOR . $file;
if (is_file($filePath)) {
unlink($filePath);
}
}
}
}
$this->removeAllPages();
// get rid of any versions have saved for this DMSDocument, too
if (DMSDocument_versions::$enable_versions) {
$versions = $this->getVersions();
if ($versions->Count() > 0) {
foreach ($versions as $v) {
$v->delete();
}
}
}
parent::delete();
}
/**
* Relate an existing file on the filesystem to the document.
*
* Copies the file to the new destination, as defined in {@link get_DMS_path()}.
*
* @param string $filePath Path to file, relative to webroot.
*
* @return DMSDocument
*/
public function storeDocument($filePath)
{
if (empty($this->ID)) {
user_error("Document must be written to database before it can store documents", E_USER_ERROR);
}
// calculate all the path to copy the file to
$fromFilename = basename($filePath);
$toFilename = $this->ID. '~' . $fromFilename; //add the docID to the start of the Filename
$toFolder = DMS::get_storage_folder($this->ID);
$toPath = DMS::get_dms_path() . DIRECTORY_SEPARATOR . $toFolder . DIRECTORY_SEPARATOR . $toFilename;
DMS::create_storage_folder(DMS::get_dms_path() . DIRECTORY_SEPARATOR . $toFolder);
//copy the file into place
$fromPath = BASE_PATH . DIRECTORY_SEPARATOR . $filePath;
//version the existing file (copy it to a new "very specific" filename
if (DMSDocument_versions::$enable_versions) {
DMSDocument_versions::create_version($this);
} else { //otherwise delete the old document file
$oldPath = $this->getFullPath();
if (file_exists($oldPath)) {
unlink($oldPath);
}
}
copy($fromPath, $toPath); //this will overwrite the existing file (if present)
//write the filename of the stored document
$this->Filename = $toFilename;
$this->Folder = $toFolder;
$extension = pathinfo($this->Filename, PATHINFO_EXTENSION);
if (empty($this->Title)) {
// don't overwrite existing document titles
$this->Title = basename($filePath, '.'.$extension);
}
$this->LastChanged = SS_Datetime::now()->Rfc2822();
$this->write();
return $this;
}
/**
* Takes a File object or a String (path to a file) and copies it into the
* DMS, replacing the original document file but keeping the rest of the
* document unchanged.
*
* @param File|string $file path to a file to store
*
* @return DMSDocument object that we replaced the file in
*/
public function replaceDocument($file)
{
$filePath = DMS::transform_file_to_file_path($file);
$doc = $this->storeDocument($filePath); // replace the document
return $doc;
}
/**
* Return the type of file for the given extension
* on the current file name.
*
* @param string $ext
*
* @return string
*/
public static function get_file_type($ext)
{
$types = array(
'gif' => 'GIF image - good for diagrams',
'jpg' => 'JPEG image - good for photos',
'jpeg' => 'JPEG image - good for photos',
'png' => 'PNG image - good general-purpose format',
'ico' => 'Icon image',
'tiff' => 'Tagged image format',
'doc' => 'Word document',
'xls' => 'Excel spreadsheet',
'zip' => 'ZIP compressed file',
'gz' => 'GZIP compressed file',
'dmg' => 'Apple disk image',
'pdf' => 'Adobe Acrobat PDF file',
'mp3' => 'MP3 audio file',
'wav' => 'WAV audo file',
'avi' => 'AVI video file',
'mpg' => 'MPEG video file',
'mpeg' => 'MPEG video file',
'js' => 'Javascript file',
'css' => 'CSS file',
'html' => 'HTML file',
'htm' => 'HTML file'
);
return isset($types[$ext]) ? $types[$ext] : $ext;
}
/**
* Returns the Description field with HTML <br> tags added when there is a
* line break.
*
* @return string
*/
public function getDescriptionWithLineBreak()
{
return nl2br($this->getField('Description'));
}
/**
* @return FieldList
*/
public function getCMSFields()
{
//include JS to handling showing and hiding of bottom "action" tabs
Requirements::javascript(DMS_DIR.'/javascript/DMSDocumentCMSFields.js');
Requirements::css(DMS_DIR.'/css/DMSDocumentCMSFields.css');
$fields = new FieldList(); //don't use the automatic scaffolding, it is slow and unnecessary here
$extraTasks = ''; //additional text to inject into the list of tasks at the bottom of a DMSDocument CMSfield
$extraFields = FormField::create('Empty');
//get list of shortcode page relations
$relationFinder = new ShortCodeRelationFinder();
$relationList = $relationFinder->getList($this->ID);
$fieldsTop = $this->getFieldsForFile($relationList->count());
$fields->add($fieldsTop);
$fields->add(new TextField('Title', 'Title'));
$fields->add(new TextareaField('Description', 'Description'));
//create upload field to replace document
$uploadField = new DMSUploadField('ReplaceFile', 'Replace file');
$uploadField->setConfig('allowedMaxFileNumber', 1);
$uploadField->setConfig('downloadTemplateName', 'ss-dmsuploadfield-downloadtemplate');
$uploadField->setRecord($this);
$gridFieldConfig = GridFieldConfig::create()->addComponents(
new GridFieldToolbarHeader(),
new GridFieldSortableHeader(),
new GridFieldDataColumns(),
new GridFieldPaginator(30),
//new GridFieldEditButton(),
new GridFieldDetailForm()
);
$gridFieldConfig->getComponentByType('GridFieldDataColumns')
->setDisplayFields(array(
'Title'=>'Title',
'ClassName'=>'Page Type',
'ID'=>'Page ID'
))
->setFieldFormatting(array(
'Title'=>sprintf(
'<a class=\"cms-panel-link\" href=\"%s/$ID\">$Title</a>',
singleton('CMSPageEditController')->Link('show')
)
));
$pagesGrid = GridField::create(
'Pages',
_t('DMSDocument.RelatedPages', 'Related Pages'),
$this->Pages(),
$gridFieldConfig
);
$referencesGrid = GridField::create(
'References',
_t('DMSDocument.RelatedReferences', 'Related References'),
$relationList,
$gridFieldConfig
);
if (DMSDocument_versions::$enable_versions) {
$versionsGridFieldConfig = GridFieldConfig::create()->addComponents(
new GridFieldToolbarHeader(),
new GridFieldSortableHeader(),
new GridFieldDataColumns(),
new GridFieldPaginator(30)
);
$versionsGridFieldConfig->getComponentByType('GridFieldDataColumns')->setDisplayFields(Config::inst()->get('DMSDocument_versions', 'display_fields'))
->setFieldCasting(array('LastChanged'=>"Datetime->Ago"))
->setFieldFormatting(array('FilenameWithoutID'=>'<a target=\'_blank\' class=\'file-url\' href=\'$Link\'>$FilenameWithoutID</a>'));
$versionsGrid = GridField::create(
'Versions',
_t('DMSDocument.Versions', 'Versions'),
$this->getVersions(),
$versionsGridFieldConfig
);
$extraTasks .= '<li class="ss-ui-button" data-panel="find-versions">Versions</li>';
//$extraFields = $versionsGrid->addExtraClass('find-versions');
}
$fields->add(new LiteralField('BottomTaskSelection',
'<div id="Actions" class="field actions"><label class="left">Actions</label><ul>'.
'<li class="ss-ui-button" data-panel="embargo">Embargo</li>'.
'<li class="ss-ui-button" data-panel="expiry">Expiry</li>'.
'<li class="ss-ui-button" data-panel="replace">Replace</li>'.
'<li class="ss-ui-button" data-panel="find-usage">Usage</li>'.
'<li class="ss-ui-button" data-panel="find-references">References</li>'.
$extraTasks.
'</ul></div>'));
$embargoValue = 'None';
if ($this->EmbargoedIndefinitely) {
$embargoValue = 'Indefinitely';
} 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);
$embargoDatetime = DatetimeField::create('EmbargoedUntilDate', '');
$embargoDatetime->getDateField()->setConfig('showcalendar', true)->setConfig('dateformat', 'dd-MM-yyyy')->setConfig('datavalueformat', 'dd-MM-yyyy');
$expiryValue = 'None';
if (!empty($this->ExpireAtDate)) {
$expiryValue = 'Date';
}
$expiry = new OptionsetField('Expiry', 'Expiry', array('None'=>'None', 'Date'=>'Set document to expire on'), $expiryValue);
$expiryDatetime = DatetimeField::create('ExpireAtDate', '');
$expiryDatetime->getDateField()->setConfig('showcalendar', true)->setConfig('dateformat', 'dd-MM-yyyy')->setConfig('datavalueformat', 'dd-MM-yyyy');
// This adds all the actions details into a group.
// Embargo, History, etc to go in here
// These are toggled on and off via the Actions Buttons above
// exit('hit');
$actionsPanel = FieldGroup::create(
FieldGroup::create(
$embargo,
$embargoDatetime
)->addExtraClass('embargo'),
FieldGroup::create(
$expiry,
$expiryDatetime
)->addExtraClass('expiry'),
FieldGroup::create(
$uploadField
)->addExtraClass('replace'),
FieldGroup::create(
$pagesGrid
)->addExtraClass('find-usage'),
FieldGroup::create(
$referencesGrid
)->addExtraClass('find-references'),
FieldGroup::create(
$versionsGrid
)->addExtraClass('find-versions')
);
$actionsPanel->setName("ActionsPanel");
$actionsPanel->addExtraClass("ActionsPanel");
$fields->push($actionsPanel);
// $fields->add(FieldGroup::create(
// FieldGroup::create(
// $embargo,
// $embargoDatetime
// )->addExtraClass('embargo'),
// FieldGroup::create(
// $expiry,
// $expiryDatetime
// )->addExtraClass('expiry'),
// $uploadField->addExtraClass('replace'),
// $pagesGrid->addExtraClass('find-usage'),
// $referencesGrid->addExtraClass('find-references'),
// $extraFields
// )->setName("ActionsPanel")->addExtraClass('dmsupload ss-uploadfield'));
$this->extend('updateCMSFields', $fields);
return $fields;
}
public function onBeforeWrite()
{
parent::onBeforeWrite();
if (isset($this->Embargo)) {
//set the embargo options from the OptionSetField created in the getCMSFields method
//do not write after clearing the embargo (write happens automatically)
$savedDate = $this->EmbargoedUntilDate;
$this->clearEmbargo(false); //clear all previous settings and re-apply them on save
if ($this->Embargo == 'Published') {
$this->embargoUntilPublished(false);
}
if ($this->Embargo == 'Indefinitely') {
$this->embargoIndefinitely(false);
}
if ($this->Embargo == 'Date') {
$this->embargoUntilDate($savedDate, false);
}
}
if (isset($this->Expiry)) {
if ($this->Expiry == 'Date') {
$this->expireAtDate($this->ExpireAtDate, false);
} else {
$this->clearExpiry(false);
} //clear all previous settings
}
}
/**
* Return the relative URL of an icon for the file type, based on the
* {@link appCategory()} value.
*
* Images are searched for in "dms/images/app_icons/".
*
* @return string
*/
public function Icon($ext)
{
if (!Director::fileExists(DMS_DIR."/images/app_icons/{$ext}_32.png")) {
$ext = File::get_app_category($ext);
}
if (!Director::fileExists(DMS_DIR."/images/app_icons/{$ext}_32.png")) {
$ext = "generic";
}
return DMS_DIR."/images/app_icons/{$ext}_32.png";
}
/**
* Return the extension of the file associated with the document
*
* @return string
*/
public function getExtension()
{
return strtolower(pathinfo($this->Filename, PATHINFO_EXTENSION));
}
/**
* @return string
*/
public function getSize()
{
$size = $this->getAbsoluteSize();
return ($size) ? File::format_size($size) : false;
}
/**
* Return the size of the file associated with the document.
*
* @return string
*/
public function getAbsoluteSize()
{
return file_exists($this->getFullPath()) ? filesize($this->getFullPath()) : null;
}
/**
* An alias to DMSDocument::getSize()
*
* @return string
*/
public function getFileSizeFormatted()
{
return $this->getSize();
}
/**
* @return FieldList
*/
protected function getFieldsForFile($relationListCount)
{
$extension = $this->getExtension();
$previewField = new LiteralField("ImageFull",
"<img id='thumbnailImage' class='thumbnail-preview' src='{$this->Icon($extension)}?r=" . rand(1, 100000) . "' alt='{$this->Title}' />\n"
);
//count the number of pages this document is published on
$publishedOnCount = $this->Pages()->Count();
$publishedOnValue = "$publishedOnCount pages";
if ($publishedOnCount == 1) {
$publishedOnValue = "$publishedOnCount page";
}
$relationListCountValue = "$relationListCount pages";
if ($relationListCount == 1) {
$relationListCountValue = "$relationListCount page";
}
$fields = new FieldGroup(
$filePreview = CompositeField::create(
CompositeField::create(
$previewField
)->setName("FilePreviewImage")->addExtraClass('cms-file-info-preview'),
CompositeField::create(
CompositeField::create(
new ReadonlyField("ID", "ID number". ':', $this->ID),
new ReadonlyField("FileType", _t('AssetTableField.TYPE', 'File type') . ':', self::get_file_type($extension)),
new ReadonlyField("Size", _t('AssetTableField.SIZE', 'File size') . ':', $this->getFileSizeFormatted()),
$urlField = new ReadonlyField('ClickableURL', _t('AssetTableField.URL', 'URL'),
sprintf('<a href="%s" target="_blank" class="file-url">%s</a>', $this->getLink(), $this->getLink())
),
new ReadonlyField("FilenameWithoutIDField", "Filename". ':', $this->getFilenameWithoutID()),
new DateField_Disabled("Created", _t('AssetTableField.CREATED', 'First uploaded') . ':', $this->Created),
new DateField_Disabled("LastEdited", _t('AssetTableField.LASTEDIT', 'Last changed') . ':', $this->LastEdited),
new DateField_Disabled("LastChanged", _t('AssetTableField.LASTCHANGED', 'Last replaced') . ':', $this->LastChanged),
new ReadonlyField("PublishedOn", "Published on". ':', $publishedOnValue),
new ReadonlyField("ReferencedOn", "Referenced on". ':', $relationListCountValue),
new ReadonlyField("ViewCount", "View count". ':', $this->ViewCount)
)
)->setName("FilePreviewData")->addExtraClass('cms-file-info-data')
)->setName("FilePreview")->addExtraClass('cms-file-info')
);
$fields->setName('FileP');
$urlField->dontEscape = true;
return $fields;
}
/**
* Takes a file and adds it to the DMSDocument storage, replacing the
* current file.
*
* @param File $file
*
* @return DMSDocument
*/
public function ingestFile($file)
{
$this->replaceDocument($file);
$file->delete();
return $this;
}
}
/**
* @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(
'index'
);
private static $allowed_actions = array(
'index'
);
public function init() {
Versioned::choose_site_stage();
parent::init();
}
public function init()
{
Versioned::choose_site_stage();
parent::init();
}
/**
* Returns the document object from the request object's ID parameter.
* Returns null, if no document found
*/
protected function getDocumentFromID($request) {
$doc = null;
/**
* Returns the document object from the request object's ID parameter.
* Returns null, if no document found
*/
protected function getDocumentFromID($request)
{
$doc = null;
$id = Convert::raw2sql($request->param('ID'));
$id = Convert::raw2sql($request->param('ID'));
if (strpos($id, 'version') === 0) { //versioned document
$id = str_replace('version','',$id);
$doc = DataObject::get_by_id('DMSDocument_versions', $id);
$this->extend('updateVersionFromID', $doc, $request);
} else { //normal document
$doc = DataObject::get_by_id('DMSDocument', $id);
$this->extend('updateDocumentFromID', $doc, $request);
}
if (strpos($id, 'version') === 0) { //versioned document
$id = str_replace('version', '', $id);
$doc = DataObject::get_by_id('DMSDocument_versions', $id);
$this->extend('updateVersionFromID', $doc, $request);
} else { //normal document
$doc = DataObject::get_by_id('DMSDocument', $id);
$this->extend('updateDocumentFromID', $doc, $request);
}
return $doc;
}
return $doc;
}
/**
* Access the file download without redirecting user, so we can block direct
* access to documents.
*/
public function index(SS_HTTPRequest $request) {
$doc = $this->getDocumentFromID($request);
/**
* Access the file download without redirecting user, so we can block direct
* access to documents.
*/
public function index(SS_HTTPRequest $request)
{
$doc = $this->getDocumentFromID($request);
if (!empty($doc)) {
$canView = false;
if (!empty($doc)) {
$canView = false;
// Runs through all pages that this page links to and sets canView
// to true if the user can view ONE of these pages
if (method_exists($doc, 'Pages')) {
$pages = $doc->Pages();
if ($pages->Count() > 0) {
foreach($pages as $page) {
if ($page->CanView()) {
// just one canView is enough to know that we can
// view the file
$canView = true;
break;
}
}
} else {
// if the document isn't on any page, then allow viewing of
// the document (because there is no canView() to consult)
$canView = true;
}
}
// Runs through all pages that this page links to and sets canView
// to true if the user can view ONE of these pages
if (method_exists($doc, 'Pages')) {
$pages = $doc->Pages();
if ($pages->Count() > 0) {
foreach ($pages as $page) {
if ($page->CanView()) {
// just one canView is enough to know that we can
// view the file
$canView = true;
break;
}
}
} else {
// if the document isn't on any page, then allow viewing of
// the document (because there is no canView() to consult)
$canView = true;
}
}
// check for embargo or expiry
if ($doc->isHidden()) $canView = false;
// check for embargo or expiry
if ($doc->isHidden()) {
$canView = false;
}
//admins can always download any document, even if otherwise hidden
$member = Member::currentUser();
if ($member && Permission::checkMember($member, 'ADMIN')) $canView = true;
//admins can always download any document, even if otherwise hidden
$member = Member::currentUser();
if ($member && Permission::checkMember($member, 'ADMIN')) {
$canView = true;
}
if ($canView) {
$path = $doc->getFullPath();
if ( is_file($path) ) {
$fileBin = trim(`whereis file`);
if ( function_exists('finfo_file') ) {
// discover the mime type properly
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($finfo, $path);
}
else if ( is_executable($fileBin) ) {
// try to use the system tool
$mime = `$fileBin -i -b $path`;
$mime = explode(';', $mime);
$mime = trim($mime[0]);
}
else {
// make do with what we have
$ext = $doc->getExtension();
if ( $ext =='pdf') {
$mime = 'application/pdf';
}elseif ($ext == 'html' || $ext =='htm') {
$mime = 'text/html';
}else {
$mime = 'application/octet-stream';
}
}
if ($canView) {
$path = $doc->getFullPath();
if (is_file($path)) {
$fileBin = trim(`whereis file`);
if (function_exists('finfo_file')) {
// discover the mime type properly
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($finfo, $path);
} elseif (is_executable($fileBin)) {
// try to use the system tool
$mime = `$fileBin -i -b $path`;
$mime = explode(';', $mime);
$mime = trim($mime[0]);
} else {
// make do with what we have
$ext = $doc->getExtension();
if ($ext =='pdf') {
$mime = 'application/pdf';
} elseif ($ext == 'html' || $ext =='htm') {
$mime = 'text/html';
} else {
$mime = 'application/octet-stream';
}
}
if (self::$testMode) return $path;
if (self::$testMode) {
return $path;
}
//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.
$doc->trackView();
//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.
$doc->trackView();
header('Content-Type: ' . $mime);
header('Content-Length: ' . filesize($path), null);
if (!empty($mime) && $mime != "text/html") header('Content-Disposition: attachment; filename="'.$doc->getFilenameWithoutID().'"');
header('Content-transfer-encoding: 8bit');
header('Expires: 0');
header('Pragma: cache');
header('Cache-Control: private');
flush();
readfile($path);
exit;
}
}
}
header('Content-Type: ' . $mime);
header('Content-Length: ' . filesize($path), null);
if (!empty($mime) && $mime != "text/html") {
header('Content-Disposition: attachment; filename="'.$doc->getFilenameWithoutID().'"');
}
header('Content-transfer-encoding: 8bit');
header('Expires: 0');
header('Pragma: cache');
header('Cache-Control: private');
flush();
readfile($path);
exit;
}
}
}
if (self::$testMode) return 'This asset does not exist.';
$this->httpError(404, 'This asset does not exist.');
}
if (self::$testMode) {
return 'This asset does not exist.';
}
$this->httpError(404, 'This asset does not exist.');
}
}

View File

@ -9,249 +9,269 @@
*
* @package dms
*/
class DMSDocument_versions extends DataObject {
class DMSDocument_versions extends DataObject
{
/**
* @var bool $enable_versions Flag that turns on or off versions of
* documents when replacing them
*/
public static $enable_versions = true;
/**
* @var bool $enable_versions Flag that turns on or off versions of
* documents when replacing them
*/
public static $enable_versions = true;
private static $db = array(
'VersionCounter' => 'Int',
'VersionViewCount' => 'Int'
);
private static $db = array(
'VersionCounter' => 'Int',
'VersionViewCount' => 'Int'
);
private static $has_one = array(
'Document' => 'DMSDocument'
);
private static $has_one = array(
'Document' => 'DMSDocument'
);
private static $defaults = array(
'VersionCounter' => 0
);
private static $defaults = array(
'VersionCounter' => 0
);
private static $display_fields = array(
'VersionCounter' => 'Version Counter',
'FilenameWithoutID' => 'Filename',
'LastChanged' => 'Last Changed'
);
private static $display_fields = array(
'VersionCounter' => 'Version Counter',
'FilenameWithoutID' => 'Filename',
'LastChanged' => 'Last Changed'
);
private static $summary_fields = array(
'VersionCounter',
'FilenameWithoutID'
);
private static $summary_fields = array(
'VersionCounter',
'FilenameWithoutID'
);
private static $field_labels = array(
'FilenameWithoutID'=>'Filename'
);
private static $field_labels = array(
'FilenameWithoutID'=>'Filename'
);
private static $default_sort = array(
'LastChanged' => 'DESC'
);
private static $default_sort = array(
'LastChanged' => 'DESC'
);
/**
* Creates a new version of a document by moving the current file and
* renaming it to the versioned filename.
*
* This method assumes that the method calling this is just about to upload
* a new file to replace the old file.
*
* @static
* @param DMSDocument $doc
*
* @return bool Success or failure
*/
public static function create_version(DMSDocument $doc) {
$success = false;
/**
* Creates a new version of a document by moving the current file and
* renaming it to the versioned filename.
*
* This method assumes that the method calling this is just about to upload
* a new file to replace the old file.
*
* @static
* @param DMSDocument $doc
*
* @return bool Success or failure
*/
public static function create_version(DMSDocument $doc)
{
$success = false;
$existingPath = $doc->getFullPath();
if (is_file($existingPath)) {
$docData = $doc->toMap();
unset($docData['ID']);
$version = new DMSDocument_versions($docData); //create a copy of the current DMSDocument as a version
$existingPath = $doc->getFullPath();
if (is_file($existingPath)) {
$docData = $doc->toMap();
unset($docData['ID']);
$version = new DMSDocument_versions($docData); //create a copy of the current DMSDocument as a version
$previousVersionCounter = 0;
$newestExistingVersion = self::get_versions($doc)->sort(array('Created'=>'DESC','ID'=>'DESC'))->limit(1);
if ($newestExistingVersion && $newestExistingVersion->Count() > 0) {
$previousVersionCounter = $newestExistingVersion->first()->VersionCounter;
}
$previousVersionCounter = 0;
$newestExistingVersion = self::get_versions($doc)->sort(array('Created'=>'DESC', 'ID'=>'DESC'))->limit(1);
if ($newestExistingVersion && $newestExistingVersion->Count() > 0) {
$previousVersionCounter = $newestExistingVersion->first()->VersionCounter;
}
//change the filename field to a field containing the new soon-to-be versioned file
$version->VersionCounter = $previousVersionCounter + 1; //start versions at 1
$newFilename = $version->generateVersionedFilename($doc, $version->VersionCounter);
$version->Filename = $newFilename;
//change the filename field to a field containing the new soon-to-be versioned file
$version->VersionCounter = $previousVersionCounter + 1; //start versions at 1
$newFilename = $version->generateVersionedFilename($doc, $version->VersionCounter);
$version->Filename = $newFilename;
//add a relation back to the origin ID;
$version->DocumentID = $doc->ID;
$id = $version->write();
//add a relation back to the origin ID;
$version->DocumentID = $doc->ID;
$id = $version->write();
if (!empty($id)) {
rename($existingPath, $version->getFullPath());
$success = true;
}
}
if (!empty($id)) {
rename($existingPath, $version->getFullPath());
$success = true;
}
}
return $success;
}
return $success;
}
public function delete() {
$path = $this->getFullPath();
public function delete()
{
$path = $this->getFullPath();
if (file_exists($path)) unlink($path);
if (file_exists($path)) {
unlink($path);
}
parent::delete();
}
parent::delete();
}
/**
/**
* Returns a DataList of all previous Versions of a document (check the
* LastEdited date of each object to find the correct one).
*
* @static
* @param DMSDocument $doc
*
* @return DataList List of Document objects
*/
static function get_versions(DMSDocument $doc) {
if (!DMSDocument_versions::$enable_versions) user_error("DMSDocument versions are disabled",E_USER_WARNING);
return DMSDocument_versions::get()->filter(array('DocumentID' => $doc->ID));
}
* @static
* @param DMSDocument $doc
*
* @return DataList List of Document objects
*/
public static function get_versions(DMSDocument $doc)
{
if (!DMSDocument_versions::$enable_versions) {
user_error("DMSDocument versions are disabled", E_USER_WARNING);
}
return DMSDocument_versions::get()->filter(array('DocumentID' => $doc->ID));
}
public function __construct($record = null, $isSingleton = false, $model = null) {
//check what the constructor was passed
$dmsObject = null;
if ($record && is_subclass_of($record,'DMSDocumentInterface')) {
$dmsObject = $record;
$record = null; //cancel the record creation to just create an empty object
}
public function __construct($record = null, $isSingleton = false, $model = null)
{
//check what the constructor was passed
$dmsObject = null;
if ($record && is_subclass_of($record, 'DMSDocumentInterface')) {
$dmsObject = $record;
$record = null; //cancel the record creation to just create an empty object
}
//create the object
parent::__construct($record, $isSingleton, $model);
//create the object
parent::__construct($record, $isSingleton, $model);
//copy the DMSDocument object, if passed into the constructor
if ($dmsObject) {
foreach(array_keys(DataObject::custom_database_fields($dmsObject->ClassName)) as $key) {
$this->$key = $dmsObject->$key;
}
}
}
//copy the DMSDocument object, if passed into the constructor
if ($dmsObject) {
foreach (array_keys(DataObject::custom_database_fields($dmsObject->ClassName)) as $key) {
$this->$key = $dmsObject->$key;
}
}
}
/**
* Returns a link to download this document from the DMS store.
*
* @return string
*/
public function getLink() {
return Controller::join_links(Director::baseURL(),'dmsdocument/version'.$this->ID);
}
/**
* Returns a link to download this document from the DMS store.
*
* @return string
*/
public function getLink()
{
return Controller::join_links(Director::baseURL(), 'dmsdocument/version'.$this->ID);
}
/**
* Document versions are always hidden from outside viewing. Only admins can
* download them.
*
* @return bool
*/
public function isHidden() {
return true;
}
/**
* Document versions are always hidden from outside viewing. Only admins can
* download them.
*
* @return bool
*/
public function isHidden()
{
return true;
}
/**
* Returns the full filename of the document stored in this object. Can
* optionally specify which filename to use at the end.
*
* @param string
*
* @return string
*/
public function getFullPath($filename = null) {
if (!$filename) $filename = $this->Filename;
return DMS::get_dms_path() . DIRECTORY_SEPARATOR . $this->Folder . DIRECTORY_SEPARATOR . $filename;
}
/**
* Returns the full filename of the document stored in this object. Can
* optionally specify which filename to use at the end.
*
* @param string
*
* @return string
*/
public function getFullPath($filename = null)
{
if (!$filename) {
$filename = $this->Filename;
}
return DMS::get_dms_path() . DIRECTORY_SEPARATOR . $this->Folder . DIRECTORY_SEPARATOR . $filename;
}
/**
* @return string
*/
public function getFilenameWithoutID() {
$filenameParts = explode('~',$this->Filename);
$filename = array_pop($filenameParts);
/**
* @return string
*/
public function getFilenameWithoutID()
{
$filenameParts = explode('~', $this->Filename);
$filename = array_pop($filenameParts);
return $filename;
}
return $filename;
}
/**
* Creates a new filename for the current Document's file when replacing the
* current file with a new file.
*
* @param DMSDocument $filename The original filename
*
* @return string The new filename
*/
protected function generateVersionedFilename(DMSDocument $doc, $versionCounter) {
$filename = $doc->Filename;
/**
* Creates a new filename for the current Document's file when replacing the
* current file with a new file.
*
* @param DMSDocument $filename The original filename
*
* @return string The new filename
*/
protected function generateVersionedFilename(DMSDocument $doc, $versionCounter)
{
$filename = $doc->Filename;
do {
$versionPaddingString = str_pad($versionCounter, 4, '0', STR_PAD_LEFT); //add leading zeros to make sorting accurate up to 10,000 documents
$newVersionFilename = preg_replace('/([0-9]+~)(.*?)/','$1~'.$versionPaddingString.'~$2',$filename);
do {
$versionPaddingString = str_pad($versionCounter, 4, '0', STR_PAD_LEFT); //add leading zeros to make sorting accurate up to 10,000 documents
$newVersionFilename = preg_replace('/([0-9]+~)(.*?)/', '$1~'.$versionPaddingString.'~$2', $filename);
if ($newVersionFilename == $filename || empty($newVersionFilename)) { //sanity check for crazy document names
user_error('Cannot generate new document filename for file: '.$filename,E_USER_ERROR);
}
if ($newVersionFilename == $filename || empty($newVersionFilename)) { //sanity check for crazy document names
user_error('Cannot generate new document filename for file: '.$filename, E_USER_ERROR);
}
$versionCounter++; //increase the counter for the next loop run, if necessary
} while(file_exists($this->getFullPath($newVersionFilename)));
$versionCounter++; //increase the counter for the next loop run, if necessary
} while (file_exists($this->getFullPath($newVersionFilename)));
return $newVersionFilename;
}
return $newVersionFilename;
}
/**
* Return the extension of the file associated with the document.
*
* @return string
*/
public function getExtension() {
return strtolower(pathinfo($this->Filename, PATHINFO_EXTENSION));
}
/**
* Return the extension of the file associated with the document.
*
* @return string
*/
public function getExtension()
{
return strtolower(pathinfo($this->Filename, PATHINFO_EXTENSION));
}
/**
* @return string
*/
public function getSize() {
$size = $this->getAbsoluteSize();
/**
* @return string
*/
public function getSize()
{
$size = $this->getAbsoluteSize();
return ($size) ? File::format_size($size) : false;
}
return ($size) ? File::format_size($size) : false;
}
/**
* Return the size of the file associated with the document.
*
* @return string
*/
public function getAbsoluteSize() {
return filesize($this->getFullPath());
}
/**
* Return the size of the file associated with the document.
*
* @return string
*/
public function getAbsoluteSize()
{
return filesize($this->getFullPath());
}
/**
* An alias to DMSDocument::getSize()
*
* @return string
*/
public function getFileSizeFormatted() {
return $this->getSize();
}
/**
* An alias to DMSDocument::getSize()
*
* @return string
*/
public function getFileSizeFormatted()
{
return $this->getSize();
}
/**
* @return DMSDocument_versions
*/
public function trackView() {
if ($this->ID > 0) {
$this->VersionViewCount++;
/**
* @return DMSDocument_versions
*/
public function trackView()
{
if ($this->ID > 0) {
$this->VersionViewCount++;
$count = $this->VersionViewCount;
$count = $this->VersionViewCount;
DB::query("UPDATE \"DMSDocument_versions\" SET \"VersionViewCount\"='$count' WHERE \"ID\"={$this->ID}");
}
DB::query("UPDATE \"DMSDocument_versions\" SET \"VersionViewCount\"='$count' WHERE \"ID\"={$this->ID}");
}
return $this;
}
}
return $this;
}
}

View File

@ -5,15 +5,16 @@
*
* @package dms
*/
class DMSTag extends DataObject {
class DMSTag extends DataObject
{
private static $db = array(
'Category' => 'Varchar(1024)',
'Value' => 'Varchar(1024)',
'MultiValue' => 'Boolean(1)'
);
private static $db = array(
'Category' => 'Varchar(1024)',
'Value' => 'Varchar(1024)',
'MultiValue' => 'Boolean(1)'
);
private static $belongs_many_many = array(
'Documents' => 'DMSDocument'
);
private static $belongs_many_many = array(
'Documents' => 'DMSDocument'
);
}

View File

@ -9,73 +9,85 @@
* search across dozens of columns and tables - but for a couple of hundred pages
* and occasionally use its a feasible solution.
*/
class ShortCodeRelationFinder {
class ShortCodeRelationFinder
{
/**
* @var String Regex matching a {@link DBField} class name which is shortcode capable.
*
* This should really look for implementors of a ShortCodeParseable interface,
* but we can't extend the core Text and HTMLText class
* on existing like SiteTree.Content for this.
*/
protected $fieldSpecRegex = '/^(HTMLText)/';
/**
* @var String Regex matching a {@link DBField} class name which is shortcode capable.
*
* This should really look for implementors of a ShortCodeParseable interface,
* but we can't extend the core Text and HTMLText class
* on existing like SiteTree.Content for this.
*/
protected $fieldSpecRegex = '/^(HTMLText)/';
/**
* @param String Shortcode index number to find
* @return array IDs
*/
function findPageIDs($number) {
$list = $this->getList($number);
$found = $list->column();
return $found;
}
/**
* @param String Shortcode index number to find
* @return array IDs
*/
public function findPageIDs($number)
{
$list = $this->getList($number);
$found = $list->column();
return $found;
}
function findPageCount($number) {
$list = $this->getList($number);
return $list->count();
}
public function findPageCount($number)
{
$list = $this->getList($number);
return $list->count();
}
/**
* @return DataList
*/
function getList($number) {
$list = DataList::create('SiteTree');
$where = array();
$fields = $this->getShortCodeFields('SiteTree');
foreach($fields as $ancClass => $ancFields) {
foreach($ancFields as $ancFieldName => $ancFieldSpec) {
if ($ancClass != "SiteTree") $list = $list->leftJoin($ancClass,'"'.$ancClass.'"."ID" = "SiteTree"."ID"');
$where[] = "\"$ancClass\".\"$ancFieldName\" LIKE '%[dms_document_link,id=$number]%'"; //."%s" LIKE ""',
}
}
/**
* @return DataList
*/
public function getList($number)
{
$list = DataList::create('SiteTree');
$where = array();
$fields = $this->getShortCodeFields('SiteTree');
foreach ($fields as $ancClass => $ancFields) {
foreach ($ancFields as $ancFieldName => $ancFieldSpec) {
if ($ancClass != "SiteTree") {
$list = $list->leftJoin($ancClass, '"'.$ancClass.'"."ID" = "SiteTree"."ID"');
}
$where[] = "\"$ancClass\".\"$ancFieldName\" LIKE '%[dms_document_link,id=$number]%'"; //."%s" LIKE ""',
}
}
$list = $list->where(implode(' OR ', $where));
return $list;
}
$list = $list->where(implode(' OR ', $where));
return $list;
}
/**
* Returns a filtered list of fields which could contain shortcodes.
*
* @param String
* @return Array Map of class names to an array of field names on these classes.
*/
function getShortcodeFields($class) {
$fields = array();
$ancestry = array_values(ClassInfo::dataClassesFor($class));
/**
* Returns a filtered list of fields which could contain shortcodes.
*
* @param String
* @return Array Map of class names to an array of field names on these classes.
*/
public function getShortcodeFields($class)
{
$fields = array();
$ancestry = array_values(ClassInfo::dataClassesFor($class));
foreach($ancestry as $ancestor) {
if(ClassInfo::classImplements($ancestor, 'TestOnly')) continue;
foreach ($ancestry as $ancestor) {
if (ClassInfo::classImplements($ancestor, 'TestOnly')) {
continue;
}
$ancFields = DataObject::custom_database_fields($ancestor);
if($ancFields) foreach($ancFields as $ancFieldName => $ancFieldSpec) {
if(preg_match($this->fieldSpecRegex, $ancFieldSpec)) {
if(!@$fields[$ancestor]) $fields[$ancestor] = array();
$fields[$ancestor][$ancFieldName] = $ancFieldSpec;
}
}
}
return $fields;
}
$ancFields = DataObject::custom_database_fields($ancestor);
if ($ancFields) {
foreach ($ancFields as $ancFieldName => $ancFieldSpec) {
if (preg_match($this->fieldSpecRegex, $ancFieldSpec)) {
if (!@$fields[$ancestor]) {
$fields[$ancestor] = array();
}
$fields[$ancestor][$ancFieldName] = $ancFieldSpec;
}
}
}
}
return $fields;
}
}

View File

@ -1,155 +1,160 @@
<?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() {
self::$is_running_test = true;
$d = DataObject::get("DMSDocument");
foreach($d as $d1) {
$d1->delete();
}
$t = DataObject::get("DMSTag");
foreach($t as $t1) {
$t1->delete();
}
public function tearDownOnce()
{
self::$is_running_test = true;
$d = DataObject::get("DMSDocument");
foreach ($d as $d1) {
$d1->delete();
}
$t = DataObject::get("DMSTag");
foreach ($t as $t1) {
$t1->delete();
}
self::$is_running_test = $this->originalIsRunningTest;
}
self::$is_running_test = $this->originalIsRunningTest;
}
function testPageRelations() {
$s1 = $this->objFromFixture('SiteTree','s1');
$s2 = $this->objFromFixture('SiteTree','s2');
$s3 = $this->objFromFixture('SiteTree','s3');
$s4 = $this->objFromFixture('SiteTree','s4');
$s5 = $this->objFromFixture('SiteTree','s5');
$s6 = $this->objFromFixture('SiteTree','s6');
public function testPageRelations()
{
$s1 = $this->objFromFixture('SiteTree', 's1');
$s2 = $this->objFromFixture('SiteTree', 's2');
$s3 = $this->objFromFixture('SiteTree', 's3');
$s4 = $this->objFromFixture('SiteTree', 's4');
$s5 = $this->objFromFixture('SiteTree', 's5');
$s6 = $this->objFromFixture('SiteTree', 's6');
$d1 = $this->objFromFixture('DMSDocument','d1');
$d1 = $this->objFromFixture('DMSDocument', 'd1');
$pages = $d1->Pages();
$pagesArray = $pages->toArray();
$this->assertEquals($pagesArray[0]->ID, $s1->ID, "Page 1 associated correctly");
$this->assertEquals($pagesArray[1]->ID, $s2->ID, "Page 2 associated correctly");
$this->assertEquals($pagesArray[2]->ID, $s3->ID, "Page 3 associated correctly");
$this->assertEquals($pagesArray[3]->ID, $s4->ID, "Page 4 associated correctly");
$this->assertEquals($pagesArray[4]->ID, $s5->ID, "Page 5 associated correctly");
$this->assertEquals($pagesArray[5]->ID, $s6->ID, "Page 6 associated correctly");
}
$pages = $d1->Pages();
$pagesArray = $pages->toArray();
$this->assertEquals($pagesArray[0]->ID, $s1->ID, "Page 1 associated correctly");
$this->assertEquals($pagesArray[1]->ID, $s2->ID, "Page 2 associated correctly");
$this->assertEquals($pagesArray[2]->ID, $s3->ID, "Page 3 associated correctly");
$this->assertEquals($pagesArray[3]->ID, $s4->ID, "Page 4 associated correctly");
$this->assertEquals($pagesArray[4]->ID, $s5->ID, "Page 5 associated correctly");
$this->assertEquals($pagesArray[5]->ID, $s6->ID, "Page 6 associated correctly");
}
function testAddPageRelation() {
$s1 = $this->objFromFixture('SiteTree','s1');
$s2 = $this->objFromFixture('SiteTree','s2');
$s3 = $this->objFromFixture('SiteTree','s3');
public function testAddPageRelation()
{
$s1 = $this->objFromFixture('SiteTree', 's1');
$s2 = $this->objFromFixture('SiteTree', 's2');
$s3 = $this->objFromFixture('SiteTree', 's3');
$doc = new DMSDocument();
$doc->Filename = "test file";
$doc->Folder = "0";
$doc->write();
$doc = new DMSDocument();
$doc->Filename = "test file";
$doc->Folder = "0";
$doc->write();
$doc->addPage($s1);
$doc->addPage($s2);
$doc->addPage($s3);
$doc->addPage($s1);
$doc->addPage($s2);
$doc->addPage($s3);
$pages = $doc->Pages();
$pagesArray = $pages->toArray();
$this->assertEquals($pagesArray[0]->ID, $s1->ID, "Page 1 associated correctly");
$this->assertEquals($pagesArray[1]->ID, $s2->ID, "Page 2 associated correctly");
$this->assertEquals($pagesArray[2]->ID, $s3->ID, "Page 3 associated correctly");
$pages = $doc->Pages();
$pagesArray = $pages->toArray();
$this->assertEquals($pagesArray[0]->ID, $s1->ID, "Page 1 associated correctly");
$this->assertEquals($pagesArray[1]->ID, $s2->ID, "Page 2 associated correctly");
$this->assertEquals($pagesArray[2]->ID, $s3->ID, "Page 3 associated correctly");
$doc->removePage($s1);
$pages = $doc->Pages();
$pagesArray = $pages->toArray(); //page 1 is missing
$this->assertEquals($pagesArray[0]->ID, $s2->ID, "Page 2 still associated correctly");
$this->assertEquals($pagesArray[1]->ID, $s3->ID, "Page 3 still associated correctly");
$doc->removePage($s1);
$pages = $doc->Pages();
$pagesArray = $pages->toArray(); //page 1 is missing
$this->assertEquals($pagesArray[0]->ID, $s2->ID, "Page 2 still associated correctly");
$this->assertEquals($pagesArray[1]->ID, $s3->ID, "Page 3 still associated correctly");
$documents = $s2->Documents();
$documentsArray = $documents->toArray();
$this->assertDOSContains(array(array('Filename'=>$doc->Filename)), $documentsArray, "Document associated with page");
$documents = $s2->Documents();
$documentsArray = $documents->toArray();
$this->assertDOSContains(array(array('Filename'=>$doc->Filename)), $documentsArray, "Document associated with page");
$doc->removeAllPages();
$pages = $doc->Pages();
$this->assertEquals($pages->Count(), 0, "All pages removed");
$doc->removeAllPages();
$pages = $doc->Pages();
$this->assertEquals($pages->Count(), 0, "All pages removed");
$documents = $s2->Documents();
$documentsArray = $documents->toArray();
$this->assertNotContains($doc, $documentsArray, "Document no longer associated with page");
}
$documents = $s2->Documents();
$documentsArray = $documents->toArray();
$this->assertNotContains($doc, $documentsArray, "Document no longer associated with page");
}
function testDeletingPageWithAssociatedDocuments() {
$s1 = $this->objFromFixture('SiteTree','s1');
$s2 = $this->objFromFixture('SiteTree','s2');
$s2->publish('Stage', 'Live');
$s2ID = $s2->ID;
public function testDeletingPageWithAssociatedDocuments()
{
$s1 = $this->objFromFixture('SiteTree', 's1');
$s2 = $this->objFromFixture('SiteTree', 's2');
$s2->publish('Stage', 'Live');
$s2ID = $s2->ID;
$doc = new DMSDocument();
$doc->Filename = "delete test file";
$doc->Folder = "0";
$doc->write();
$doc = new DMSDocument();
$doc->Filename = "delete test file";
$doc->Folder = "0";
$doc->write();
$doc->addPage($s1);
$doc->addPage($s2);
$doc->addPage($s1);
$doc->addPage($s2);
$s1->delete();
$s1->delete();
$documents = DataObject::get("DMSDocument","\"Filename\" = 'delete test file'", false);
$this->assertEquals(
$documents->Count(),
'1',
"Deleting one of the associated page doesn't affect the single document we created"
);
$documents = DataObject::get("DMSDocument", "\"Filename\" = 'delete test file'", false);
$this->assertEquals(
$documents->Count(),
'1',
"Deleting one of the associated page doesn't affect the single document we created"
);
$s2->delete();
$documents = DataObject::get("DMSDocument","\"Filename\" = 'delete test file'");
$this->assertEquals(
$documents->Count(),
'1',
"Deleting a page from draft stage doesn't delete the associated docs,"
. "even if it's the last page they're associated with"
);
$s2->delete();
$documents = DataObject::get("DMSDocument", "\"Filename\" = 'delete test file'");
$this->assertEquals(
$documents->Count(),
'1',
"Deleting a page from draft stage doesn't delete the associated docs,"
. "even if it's the last page they're associated with"
);
$s2 = Versioned::get_one_by_stage('SiteTree', 'Live', sprintf('"SiteTree"."ID" = %d', $s2ID));
$s2->doDeleteFromLive();
$documents = DataObject::get("DMSDocument","\"Filename\" = 'delete test file'");
$this->assertEquals(
$documents->Count(),
'0',
"However, deleting the live version of the last page that a document is "
."associated with causes that document to be deleted as well"
);
}
$s2 = Versioned::get_one_by_stage('SiteTree', 'Live', sprintf('"SiteTree"."ID" = %d', $s2ID));
$s2->doDeleteFromLive();
$documents = DataObject::get("DMSDocument", "\"Filename\" = 'delete test file'");
$this->assertEquals(
$documents->Count(),
'0',
"However, deleting the live version of the last page that a document is "
."associated with causes that document to be deleted as well"
);
}
function testUnpublishPageWithAssociatedDocuments() {
$s2 = $this->objFromFixture('SiteTree','s2');
$s2->publish('Stage', 'Live');
$s2ID = $s2->ID;
public function testUnpublishPageWithAssociatedDocuments()
{
$s2 = $this->objFromFixture('SiteTree', 's2');
$s2->publish('Stage', 'Live');
$s2ID = $s2->ID;
$doc = new DMSDocument();
$doc->Filename = "delete test file";
$doc->Folder = "0";
$doc->write();
$doc = new DMSDocument();
$doc->Filename = "delete test file";
$doc->Folder = "0";
$doc->write();
$doc->addPage($s2);
$doc->addPage($s2);
$s2->doDeleteFromLive();
$documents = DataObject::get("DMSDocument","\"Filename\" = 'delete test file'");
$this->assertEquals(
$documents->Count(),
'1',
"Deleting a page from live stage doesn't delete the associated docs,"
. "even if it's the last page they're associated with"
);
$s2->doDeleteFromLive();
$documents = DataObject::get("DMSDocument", "\"Filename\" = 'delete test file'");
$this->assertEquals(
$documents->Count(),
'1',
"Deleting a page from live stage doesn't delete the associated docs,"
. "even if it's the last page they're associated with"
);
$s2 = Versioned::get_one_by_stage('SiteTree', 'Stage', sprintf('"SiteTree"."ID" = %d', $s2ID));
$s2->delete();
$documents = DataObject::get("DMSDocument","\"Filename\" = 'delete test file'");
$this->assertEquals(
$documents->Count(),
'0',
"However, deleting the draft version of the last page that a document is "
."associated with causes that document to be deleted as well"
);
}
}
$s2 = Versioned::get_one_by_stage('SiteTree', 'Stage', sprintf('"SiteTree"."ID" = %d', $s2ID));
$s2->delete();
$documents = DataObject::get("DMSDocument", "\"Filename\" = 'delete test file'");
$this->assertEquals(
$documents->Count(),
'0',
"However, deleting the draft version of the last page that a document is "
."associated with causes that document to be deleted as well"
);
}
}

View File

@ -1,196 +1,203 @@
<?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() {
self::$is_running_test = true;
$d = DataObject::get("DMSDocument");
foreach($d as $d1) {
$d1->delete();
}
$t = DataObject::get("DMSTag");
foreach($t as $t1) {
$t1->delete();
}
public function tearDownOnce()
{
self::$is_running_test = true;
$d = DataObject::get("DMSDocument");
foreach ($d as $d1) {
$d1->delete();
}
$t = DataObject::get("DMSTag");
foreach ($t as $t1) {
$t1->delete();
}
self::$is_running_test = $this->originalIsRunningTest;
}
self::$is_running_test = $this->originalIsRunningTest;
}
function createFakeHTTPRequest($id) {
$r = new SS_HTTPRequest('GET','index/'.$id);
$r->match('index/$ID');
return $r;
}
public function createFakeHTTPRequest($id)
{
$r = new SS_HTTPRequest('GET', 'index/'.$id);
$r->match('index/$ID');
return $r;
}
function testBasicEmbargo() {
$oldDMSFolder = DMS::$dmsFolder;
DMS::$dmsFolder = DMS_DIR; //sneakily setting the DMS folder to the folder where the test file lives
public function testBasicEmbargo()
{
$oldDMSFolder = DMS::$dmsFolder;
DMS::$dmsFolder = DMS_DIR; //sneakily setting the DMS folder to the folder where the test file lives
$doc = new DMSDocument();
$doc->Filename = "DMS-test-lorum-file.pdf";
$doc->Folder = "tests";
$docID = $doc->write();
$doc = new DMSDocument();
$doc->Filename = "DMS-test-lorum-file.pdf";
$doc->Folder = "tests";
$docID = $doc->write();
//fake a request for a document
$controller = new DMSDocument_Controller();
DMSDocument_Controller::$testMode = true;
$result = $controller->index($this->createFakeHTTPRequest($docID));
$this->assertEquals($doc->getFullPath(),$result,"Correct underlying file returned (in test mode)");
//fake a request for a document
$controller = new DMSDocument_Controller();
DMSDocument_Controller::$testMode = true;
$result = $controller->index($this->createFakeHTTPRequest($docID));
$this->assertEquals($doc->getFullPath(), $result, "Correct underlying file returned (in test mode)");
$doc->embargoIndefinitely();
$doc->embargoIndefinitely();
$this->logInWithPermission('ADMIN');
$result = $controller->index($this->createFakeHTTPRequest($docID));
$this->assertEquals($doc->getFullPath(),$result,"Admins can still download embargoed files");
$this->logInWithPermission('ADMIN');
$result = $controller->index($this->createFakeHTTPRequest($docID));
$this->assertEquals($doc->getFullPath(), $result, "Admins can still download embargoed files");
$this->logInWithPermission('random-user-group');
$result = $controller->index($this->createFakeHTTPRequest($docID));
$this->assertNotEquals($doc->getFullPath(),$result,"File no longer returned (in test mode) when switching to other user group");
$this->logInWithPermission('random-user-group');
$result = $controller->index($this->createFakeHTTPRequest($docID));
$this->assertNotEquals($doc->getFullPath(), $result, "File no longer returned (in test mode) when switching to other user group");
DMS::$dmsFolder = $oldDMSFolder;
}
DMS::$dmsFolder = $oldDMSFolder;
}
function testEmbargoIndefinitely() {
$doc = new DMSDocument();
$doc->Filename = "DMS-test-lorum-file.pdf";
$doc->Folder = "tests";
$doc->write();
public function testEmbargoIndefinitely()
{
$doc = new DMSDocument();
$doc->Filename = "DMS-test-lorum-file.pdf";
$doc->Folder = "tests";
$doc->write();
$doc->embargoIndefinitely();
$this->assertTrue($doc->isHidden(),"Document is hidden");
$this->assertTrue($doc->isEmbargoed(),"Document is embargoed");
$this->assertFalse($doc->isExpired(),"Document is not expired");
$doc->embargoIndefinitely();
$this->assertTrue($doc->isHidden(), "Document is hidden");
$this->assertTrue($doc->isEmbargoed(), "Document is embargoed");
$this->assertFalse($doc->isExpired(), "Document is not expired");
$doc->clearEmbargo();
$this->assertFalse($doc->isHidden(),"Document is not hidden");
$this->assertFalse($doc->isEmbargoed(),"Document is not embargoed");
$this->assertFalse($doc->isExpired(),"Document is not expired");
$doc->clearEmbargo();
$this->assertFalse($doc->isHidden(), "Document is not hidden");
$this->assertFalse($doc->isEmbargoed(), "Document is not embargoed");
$this->assertFalse($doc->isExpired(), "Document is not expired");
}
}
public function testExpireAtDate()
{
$doc = new DMSDocument();
$doc->Filename = "DMS-test-lorum-file.pdf";
$doc->Folder = "tests";
$doc->write();
function testExpireAtDate() {
$doc = new DMSDocument();
$doc->Filename = "DMS-test-lorum-file.pdf";
$doc->Folder = "tests";
$doc->write();
$doc->expireAtDate(strtotime('-1 second'));
$this->assertTrue($doc->isHidden(), "Document is hidden");
$this->assertFalse($doc->isEmbargoed(), "Document is not embargoed");
$this->assertTrue($doc->isExpired(), "Document is expired");
$doc->expireAtDate(strtotime('-1 second'));
$this->assertTrue($doc->isHidden(),"Document is hidden");
$this->assertFalse($doc->isEmbargoed(),"Document is not embargoed");
$this->assertTrue($doc->isExpired(),"Document is expired");
$expireTime = "2019-04-05 11:43:13";
$doc->expireAtDate($expireTime);
$this->assertFalse($doc->isHidden(), "Document is not hidden");
$this->assertFalse($doc->isEmbargoed(), "Document is not embargoed");
$this->assertFalse($doc->isExpired(), "Document is not expired");
$expireTime = "2019-04-05 11:43:13";
$doc->expireAtDate($expireTime);
$this->assertFalse($doc->isHidden(),"Document is not hidden");
$this->assertFalse($doc->isEmbargoed(),"Document is not embargoed");
$this->assertFalse($doc->isExpired(),"Document is not expired");
SS_Datetime::set_mock_now($expireTime);
$this->assertTrue($doc->isHidden(), "Document is hidden");
$this->assertFalse($doc->isEmbargoed(), "Document is not embargoed");
$this->assertTrue($doc->isExpired(), "Document is expired");
SS_Datetime::clear_mock_now();
SS_Datetime::set_mock_now($expireTime);
$this->assertTrue($doc->isHidden(),"Document is hidden");
$this->assertFalse($doc->isEmbargoed(),"Document is not embargoed");
$this->assertTrue($doc->isExpired(),"Document is expired");
SS_Datetime::clear_mock_now();
$doc->expireAtDate(strtotime('-1 second'));
$this->assertTrue($doc->isHidden(), "Document is hidden");
$this->assertFalse($doc->isEmbargoed(), "Document is not embargoed");
$this->assertTrue($doc->isExpired(), "Document is expired");
$doc->expireAtDate(strtotime('-1 second'));
$this->assertTrue($doc->isHidden(),"Document is hidden");
$this->assertFalse($doc->isEmbargoed(),"Document is not embargoed");
$this->assertTrue($doc->isExpired(),"Document is expired");
$doc->clearExpiry();
$this->assertFalse($doc->isHidden(), "Document is not hidden");
$this->assertFalse($doc->isEmbargoed(), "Document is not embargoed");
$this->assertFalse($doc->isExpired(), "Document is not expired");
}
$doc->clearExpiry();
$this->assertFalse($doc->isHidden(),"Document is not hidden");
$this->assertFalse($doc->isEmbargoed(),"Document is not embargoed");
$this->assertFalse($doc->isExpired(),"Document is not expired");
}
public function testEmbargoUntilDate()
{
$doc = new DMSDocument();
$doc->Filename = "DMS-test-lorum-file.pdf";
$doc->Folder = "tests";
$doc->write();
function testEmbargoUntilDate() {
$doc = new DMSDocument();
$doc->Filename = "DMS-test-lorum-file.pdf";
$doc->Folder = "tests";
$doc->write();
$doc->embargoUntilDate(strtotime('+1 minute'));
$this->assertTrue($doc->isHidden(), "Document is hidden");
$this->assertTrue($doc->isEmbargoed(), "Document is embargoed");
$doc->embargoUntilDate(strtotime('+1 minute'));
$this->assertTrue($doc->isHidden(),"Document is hidden");
$this->assertTrue($doc->isEmbargoed(),"Document is embargoed");
$this->assertFalse($doc->isExpired(), "Document is not expired");
$this->assertFalse($doc->isExpired(),"Document is not expired");
$doc->embargoUntilDate(strtotime('-1 second'));
$this->assertFalse($doc->isHidden(), "Document is not hidden");
$this->assertFalse($doc->isEmbargoed(), "Document is not embargoed");
$this->assertFalse($doc->isExpired(), "Document is not expired");
$doc->embargoUntilDate(strtotime('-1 second'));
$this->assertFalse($doc->isHidden(),"Document is not hidden");
$this->assertFalse($doc->isEmbargoed(),"Document is not embargoed");
$this->assertFalse($doc->isExpired(),"Document is not expired");
$embargoTime = "2019-04-05 11:43:13";
$doc->embargoUntilDate($embargoTime);
$this->assertTrue($doc->isHidden(), "Document is hidden");
$this->assertTrue($doc->isEmbargoed(), "Document is embargoed");
$this->assertFalse($doc->isExpired(), "Document is not expired");
$embargoTime = "2019-04-05 11:43:13";
$doc->embargoUntilDate($embargoTime);
$this->assertTrue($doc->isHidden(),"Document is hidden");
$this->assertTrue($doc->isEmbargoed(),"Document is embargoed");
$this->assertFalse($doc->isExpired(),"Document is not expired");
SS_Datetime::set_mock_now($embargoTime);
$this->assertFalse($doc->isHidden(), "Document is not hidden");
$this->assertFalse($doc->isEmbargoed(), "Document is not embargoed");
$this->assertFalse($doc->isExpired(), "Document is not expired");
SS_Datetime::set_mock_now($embargoTime);
$this->assertFalse($doc->isHidden(),"Document is not hidden");
$this->assertFalse($doc->isEmbargoed(),"Document is not embargoed");
$this->assertFalse($doc->isExpired(),"Document is not expired");
SS_Datetime::clear_mock_now();
SS_Datetime::clear_mock_now();
$doc->clearEmbargo();
$this->assertFalse($doc->isHidden(), "Document is not hidden");
$this->assertFalse($doc->isEmbargoed(), "Document is not embargoed");
$this->assertFalse($doc->isExpired(), "Document is not expired");
}
$doc->clearEmbargo();
$this->assertFalse($doc->isHidden(),"Document is not hidden");
$this->assertFalse($doc->isEmbargoed(),"Document is not embargoed");
$this->assertFalse($doc->isExpired(),"Document is not expired");
}
public function testEmbargoUntilPublished()
{
$s1 = $this->objFromFixture('SiteTree', 's1');
function testEmbargoUntilPublished() {
$s1 = $this->objFromFixture('SiteTree','s1');
$doc = new DMSDocument();
$doc->Filename = "test file";
$doc->Folder = "0";
$dID = $doc->write();
$doc = new DMSDocument();
$doc->Filename = "test file";
$doc->Folder = "0";
$dID = $doc->write();
$doc->addPage($s1);
$doc->addPage($s1);
$s1->publish('Stage', 'Live');
$s1->doPublish();
$this->assertFalse($doc->isHidden(), "Document is not hidden");
$this->assertFalse($doc->isEmbargoed(), "Document is not embargoed");
$this->assertFalse($doc->isExpired(), "Document is not expired");
$s1->publish('Stage','Live');
$s1->doPublish();
$this->assertFalse($doc->isHidden(),"Document is not hidden");
$this->assertFalse($doc->isEmbargoed(),"Document is not embargoed");
$this->assertFalse($doc->isExpired(),"Document is not expired");
$doc->embargoUntilPublished();
$this->assertTrue($doc->isHidden(), "Document is hidden");
$this->assertTrue($doc->isEmbargoed(), "Document is embargoed");
$this->assertFalse($doc->isExpired(), "Document is not expired");
$doc->embargoUntilPublished();
$this->assertTrue($doc->isHidden(),"Document is hidden");
$this->assertTrue($doc->isEmbargoed(),"Document is embargoed");
$this->assertFalse($doc->isExpired(),"Document is not expired");
$s1->publish('Stage', 'Live');
$s1->doPublish();
$doc = DataObject::get_by_id("DMSDocument", $dID);
$this->assertFalse($doc->isHidden(), "Document is not hidden");
$this->assertFalse($doc->isEmbargoed(), "Document is not embargoed");
$this->assertFalse($doc->isExpired(), "Document is not expired");
$s1->publish('Stage','Live');
$s1->doPublish();
$doc = DataObject::get_by_id("DMSDocument",$dID);
$this->assertFalse($doc->isHidden(),"Document is not hidden");
$this->assertFalse($doc->isEmbargoed(),"Document is not embargoed");
$this->assertFalse($doc->isExpired(),"Document is not expired");
$doc->embargoUntilPublished();
$doc = DataObject::get_by_id("DMSDocument", $dID);
$this->assertTrue($doc->isHidden(), "Document is hidden");
$this->assertTrue($doc->isEmbargoed(), "Document is embargoed");
$this->assertFalse($doc->isExpired(), "Document is not expired");
$doc->embargoUntilPublished();
$doc = DataObject::get_by_id("DMSDocument",$dID);
$this->assertTrue($doc->isHidden(),"Document is hidden");
$this->assertTrue($doc->isEmbargoed(),"Document is embargoed");
$this->assertFalse($doc->isExpired(),"Document is not expired");
$doc->embargoIndefinitely();
$doc = DataObject::get_by_id("DMSDocument", $dID);
$this->assertTrue($doc->isHidden(), "Document is hidden");
$this->assertTrue($doc->isEmbargoed(), "Document is embargoed");
$this->assertFalse($doc->isExpired(), "Document is not expired");
$doc->embargoIndefinitely();
$doc = DataObject::get_by_id("DMSDocument",$dID);
$this->assertTrue($doc->isHidden(),"Document is hidden");
$this->assertTrue($doc->isEmbargoed(),"Document is embargoed");
$this->assertFalse($doc->isExpired(),"Document is not expired");
$s1->publish('Stage', 'Live');
$s1->doPublish();
$doc = DataObject::get_by_id("DMSDocument", $dID);
$this->assertTrue($doc->isHidden(), "Document is still hidden because although the untilPublish flag is cleared, the indefinitely flag is still there");
$this->assertTrue($doc->isEmbargoed(), "Document is embargoed");
$this->assertFalse($doc->isExpired(), "Document is not expired");
$s1->publish('Stage','Live');
$s1->doPublish();
$doc = DataObject::get_by_id("DMSDocument",$dID);
$this->assertTrue($doc->isHidden(),"Document is still hidden because although the untilPublish flag is cleared, the indefinitely flag is still there");
$this->assertTrue($doc->isEmbargoed(),"Document is embargoed");
$this->assertFalse($doc->isExpired(),"Document is not expired");
$doc->clearEmbargo();
$doc = DataObject::get_by_id("DMSDocument",$dID);
$this->assertFalse($doc->isHidden(),"Document is not hidden");
$this->assertFalse($doc->isEmbargoed(),"Document is not embargoed");
$this->assertFalse($doc->isExpired(),"Document is not expired");
}
}
$doc->clearEmbargo();
$doc = DataObject::get_by_id("DMSDocument", $dID);
$this->assertFalse($doc->isHidden(), "Document is not hidden");
$this->assertFalse($doc->isEmbargoed(), "Document is not embargoed");
$this->assertFalse($doc->isExpired(), "Document is not expired");
}
}

View File

@ -5,22 +5,23 @@
* @package dms
* @subpackage tests
*/
class DMSShortcodeTest extends SapphireTest {
class DMSShortcodeTest extends SapphireTest
{
public function testShortcodeOperation() {
$file = 'dms/tests/DMS-test-lorum-file.pdf';
$document = DMS::inst()->storeDocument($file);
public function testShortcodeOperation()
{
$file = 'dms/tests/DMS-test-lorum-file.pdf';
$document = DMS::inst()->storeDocument($file);
$result = ShortcodeParser::get('default')->parse(sprintf(
'<p><a href="[dms_document_link id=\'%d\']">Document</a></p>', $document->ID
));
$result = ShortcodeParser::get('default')->parse(sprintf(
'<p><a href="[dms_document_link id=\'%d\']">Document</a></p>', $document->ID
));
$value = Injector::inst()->create('HTMLValue', $result);
$link = $value->query('//a')->item(0);
$this->assertStringEndsWith("/dmsdocument/$document->ID", $link->getAttribute('href'));
$this->assertEquals($document->getExtension(), $link->getAttribute('data-ext'));
$this->assertEquals($document->getFileSizeFormatted(), $link->getAttribute('data-size'));
}
$value = Injector::inst()->create('HTMLValue', $result);
$link = $value->query('//a')->item(0);
$this->assertStringEndsWith("/dmsdocument/$document->ID", $link->getAttribute('href'));
$this->assertEquals($document->getExtension(), $link->getAttribute('data-ext'));
$this->assertEquals($document->getFileSizeFormatted(), $link->getAttribute('data-size'));
}
}

View File

@ -1,118 +1,121 @@
<?php
class DMSTagTest extends SapphireTest {
class DMSTagTest extends SapphireTest
{
function tearDownOnce() {
self::$is_running_test = true;
public function tearDownOnce()
{
self::$is_running_test = true;
$d = DataObject::get("DMSDocument");
foreach($d as $d1) {
$d1->delete();
}
$t = DataObject::get("DMSTag");
foreach($t as $t1) {
$t1->delete();
}
$d = DataObject::get("DMSDocument");
foreach ($d as $d1) {
$d1->delete();
}
$t = DataObject::get("DMSTag");
foreach ($t as $t1) {
$t1->delete();
}
self::$is_running_test = $this->originalIsRunningTest;
}
self::$is_running_test = $this->originalIsRunningTest;
}
function testAddingTags() {
$doc = new DMSDocument();
$doc->Filename = "test file";
$doc->Folder = "0";
$doc->write();
public function testAddingTags()
{
$doc = new DMSDocument();
$doc->Filename = "test file";
$doc->Folder = "0";
$doc->write();
$doc->addTag("fruit","banana");
$doc->addTag("fruit","orange");
$doc->addTag("fruit","apple");
$doc->addTag("company","apple");
$doc->addTag("company","SilverStripe");
$doc->addTag("fruit", "banana");
$doc->addTag("fruit", "orange");
$doc->addTag("fruit", "apple");
$doc->addTag("company", "apple");
$doc->addTag("company", "SilverStripe");
$fruits = $doc->getTagsList("fruit");
$this->assertNotNull($fruits,"Something returned for fruit tags");
$this->assertEquals(count($fruits),3,"3 fruit tags returned");
$this->assertTrue(in_array("banana",$fruits),"correct fruit tags returned");
$fruits = $doc->getTagsList("fruit");
$this->assertNotNull($fruits, "Something returned for fruit tags");
$this->assertEquals(count($fruits), 3, "3 fruit tags returned");
$this->assertTrue(in_array("banana", $fruits), "correct fruit tags returned");
//sneakily create another document and link one of the tags to that, too
$doc2 = new DMSDocument();
$doc2->Filename = "sneaky file";
$doc2->Folder = "0";
$doc2->write();
$doc2->addTag("fruit","banana");
//sneakily create another document and link one of the tags to that, too
$doc2 = new DMSDocument();
$doc2->Filename = "sneaky file";
$doc2->Folder = "0";
$doc2->write();
$doc2->addTag("fruit", "banana");
$fruits = $doc2->getTagsList("fruit");
$this->assertNotNull($fruits,"Something returned for fruit tags");
$this->assertEquals(count($fruits),1,"Only 1 fruit tags returned");
$fruits = $doc2->getTagsList("fruit");
$this->assertNotNull($fruits, "Something returned for fruit tags");
$this->assertEquals(count($fruits), 1, "Only 1 fruit tags returned");
//tidy up by deleting all tags from doc 1 (But the banana fruit tag should remain)
$doc->removeAllTags();
//tidy up by deleting all tags from doc 1 (But the banana fruit tag should remain)
$doc->removeAllTags();
//banana fruit remains
$fruits = $doc2->getTagsList("fruit");
$this->assertNotNull($fruits,"Something returned for fruit tags");
$this->assertEquals(count($fruits),1,"Only 1 fruit tags returned");
//banana fruit remains
$fruits = $doc2->getTagsList("fruit");
$this->assertNotNull($fruits, "Something returned for fruit tags");
$this->assertEquals(count($fruits), 1, "Only 1 fruit tags returned");
$tags = DataObject::get("DMSTag");
$this->assertEquals($tags->Count(),1,"A single DMS tag objects remain after deletion of all tags on doc1");
$tags = DataObject::get("DMSTag");
$this->assertEquals($tags->Count(), 1, "A single DMS tag objects remain after deletion of all tags on doc1");
//delete all tags off doc2 to complete the tidy up
$doc2->removeAllTags();
//delete all tags off doc2 to complete the tidy up
$doc2->removeAllTags();
$tags = DataObject::get("DMSTag");
$this->assertEquals($tags->Count(),0,"No DMS tag objects remain after deletion");
}
$tags = DataObject::get("DMSTag");
$this->assertEquals($tags->Count(), 0, "No DMS tag objects remain after deletion");
}
function testRemovingTags() {
$doc = new DMSDocument();
$doc->Filename = "test file";
$doc->Folder = "0";
$doc->write();
public function testRemovingTags()
{
$doc = new DMSDocument();
$doc->Filename = "test file";
$doc->Folder = "0";
$doc->write();
$doc->addTag("fruit","banana");
$doc->addTag("fruit","orange");
$doc->addTag("fruit","apple");
$doc->addTag("company","apple");
$doc->addTag("company","SilverStripe");
$doc->addTag("fruit", "banana");
$doc->addTag("fruit", "orange");
$doc->addTag("fruit", "apple");
$doc->addTag("company", "apple");
$doc->addTag("company", "SilverStripe");
$companies = $doc->getTagsList("company");
$this->assertNotNull($companies,"Companies returned before deletion");
$this->assertEquals(count($companies),2,"Two companies returned before deletion");
$companies = $doc->getTagsList("company");
$this->assertNotNull($companies, "Companies returned before deletion");
$this->assertEquals(count($companies), 2, "Two companies returned before deletion");
//delete an entire category
$doc->removeTag("company");
//delete an entire category
$doc->removeTag("company");
$companies = $doc->getTagsList("company");
$this->assertNull($companies,"All companies deleted");
$companies = $doc->getTagsList("company");
$this->assertNull($companies, "All companies deleted");
$fruit = $doc->getTagsList("fruit");
$this->assertEquals(count($fruit),3,"Three fruits returned before deletion");
$fruit = $doc->getTagsList("fruit");
$this->assertEquals(count($fruit), 3, "Three fruits returned before deletion");
//delete a single tag
$doc->removeTag("fruit","apple");
//delete a single tag
$doc->removeTag("fruit", "apple");
$fruit = $doc->getTagsList("fruit");
$this->assertEquals(count($fruit),2,"Two fruits returned after deleting one");
$fruit = $doc->getTagsList("fruit");
$this->assertEquals(count($fruit), 2, "Two fruits returned after deleting one");
//delete a single tag
$doc->removeTag("fruit","orange");
//delete a single tag
$doc->removeTag("fruit", "orange");
$fruit = $doc->getTagsList("fruit");
$this->assertEquals(count($fruit),1,"One fruits returned after deleting two");
$fruit = $doc->getTagsList("fruit");
$this->assertEquals(count($fruit), 1, "One fruits returned after deleting two");
//nothing happens when deleting tag that doesn't exist
$doc->removeTag("fruit","jellybean");
//nothing happens when deleting tag that doesn't exist
$doc->removeTag("fruit", "jellybean");
$fruit = $doc->getTagsList("fruit");
$this->assertEquals(count($fruit),1,"One fruits returned after attempting to delete non-existent fruit");
$fruit = $doc->getTagsList("fruit");
$this->assertEquals(count($fruit), 1, "One fruits returned after attempting to delete non-existent fruit");
//delete the last fruit
$doc->removeTag("fruit","banana");
//delete the last fruit
$doc->removeTag("fruit", "banana");
$fruit = $doc->getTagsList("fruit");
$this->assertNull($fruit,"All fruits deleted");
$fruit = $doc->getTagsList("fruit");
$this->assertNull($fruit, "All fruits deleted");
$tags = DataObject::get("DMSTag");
$this->assertEquals($tags->Count(),0,"No DMS tag objects remain after deletion");
}
}
$tags = DataObject::get("DMSTag");
$this->assertEquals($tags->Count(), 0, "No DMS tag objects remain after deletion");
}
}

View File

@ -1,131 +1,139 @@
<?php
class DMSTest extends FunctionalTest {
class DMSTest extends FunctionalTest
{
static $testFile = 'dms/tests/DMS-test-lorum-file.pdf';
static $testFile2 = 'dms/tests/DMS-test-document-2.pdf';
public static $testFile = 'dms/tests/DMS-test-lorum-file.pdf';
public static $testFile2 = 'dms/tests/DMS-test-document-2.pdf';
//store values to reset back to after this test runs
static $dmsFolderOld;
static $dmsFolderSizeOld;
//store values to reset back to after this test runs
public static $dmsFolderOld;
public static $dmsFolderSizeOld;
function setUp() {
parent::setUp();
public function setUp()
{
parent::setUp();
self::$dmsFolderOld = DMS::$dmsFolder;
self::$dmsFolderSizeOld = DMS::$dmsFolderSize;
self::$dmsFolderOld = DMS::$dmsFolder;
self::$dmsFolderSizeOld = DMS::$dmsFolderSize;
//use a test DMS folder, so we don't overwrite the live one
DMS::$dmsFolder = 'dms-assets-test-1234';
//use a test DMS folder, so we don't overwrite the live one
DMS::$dmsFolder = 'dms-assets-test-1234';
//clear out the test folder (in case a broken test doesn't delete it)
$this->delete(BASE_PATH . DIRECTORY_SEPARATOR . 'dms-assets-test-1234');
}
//clear out the test folder (in case a broken test doesn't delete it)
$this->delete(BASE_PATH . DIRECTORY_SEPARATOR . 'dms-assets-test-1234');
}
function tearDown() {
parent::tearDown();
public function tearDown()
{
parent::tearDown();
self::$is_running_test = true;
self::$is_running_test = true;
$d = DataObject::get("DMSDocument");
foreach($d as $d1) {
$d1->delete();
}
$t = DataObject::get("DMSTag");
foreach($t as $t1) {
$t1->delete();
}
$d = DataObject::get("DMSDocument");
foreach ($d as $d1) {
$d1->delete();
}
$t = DataObject::get("DMSTag");
foreach ($t as $t1) {
$t1->delete();
}
//delete the test folder after the test runs
$this->delete(BASE_PATH . DIRECTORY_SEPARATOR . 'dms-assets-test-1234');
//delete the test folder after the test runs
$this->delete(BASE_PATH . DIRECTORY_SEPARATOR . 'dms-assets-test-1234');
//set the old DMS folder back again
DMS::$dmsFolder = self::$dmsFolderOld;
DMS::$dmsFolderSize = self::$dmsFolderSizeOld;
//set the old DMS folder back again
DMS::$dmsFolder = self::$dmsFolderOld;
DMS::$dmsFolderSize = self::$dmsFolderSizeOld;
self::$is_running_test = $this->originalIsRunningTest;
}
self::$is_running_test = $this->originalIsRunningTest;
}
public function delete($path) {
if (file_exists($path) || is_dir($path)) {
$it = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($path),
RecursiveIteratorIterator::CHILD_FIRST
);
foreach ($it as $file) {
if (in_array($file->getBasename(), array('.', '..'))) {
continue;
} elseif ($file->isDir()) {
rmdir($file->getPathname());
} elseif ($file->isFile() || $file->isLink()) {
unlink($file->getPathname());
}
}
rmdir($path);
}
}
public function delete($path)
{
if (file_exists($path) || is_dir($path)) {
$it = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($path),
RecursiveIteratorIterator::CHILD_FIRST
);
foreach ($it as $file) {
if (in_array($file->getBasename(), array('.', '..'))) {
continue;
} elseif ($file->isDir()) {
rmdir($file->getPathname());
} elseif ($file->isFile() || $file->isLink()) {
unlink($file->getPathname());
}
}
rmdir($path);
}
}
function testDMSStorage() {
$dms = DMS::inst();
public function testDMSStorage()
{
$dms = DMS::inst();
$file = self::$testFile;
$document = $dms->storeDocument($file);
$file = self::$testFile;
$document = $dms->storeDocument($file);
$this->assertNotNull($document, "Document object created");
$this->assertTrue(file_exists(DMS::get_dms_path() . DIRECTORY_SEPARATOR . $document->Folder . DIRECTORY_SEPARATOR . $document->Filename),"Document file copied into DMS folder");
$this->assertNotNull($document, "Document object created");
$this->assertTrue(file_exists(DMS::get_dms_path() . DIRECTORY_SEPARATOR . $document->Folder . DIRECTORY_SEPARATOR . $document->Filename), "Document file copied into DMS folder");
//$title = $document->getTag('title');
}
//$title = $document->getTag('title');
}
function testDMSFolderSpanning() {
DMS::$dmsFolderSize = 5;
$dms = DMS::inst();
public function testDMSFolderSpanning()
{
DMS::$dmsFolderSize = 5;
$dms = DMS::inst();
$file = self::$testFile;
$file = self::$testFile;
$documents = array();
for($i = 0; $i <= 16; $i++) {
$document = $dms->storeDocument($file);
$this->assertNotNull($document, "Document object created on run number: $i");
$this->assertTrue(file_exists($document->getFullPath()));
$documents[] = $document;
}
$documents = array();
for ($i = 0; $i <= 16; $i++) {
$document = $dms->storeDocument($file);
$this->assertNotNull($document, "Document object created on run number: $i");
$this->assertTrue(file_exists($document->getFullPath()));
$documents[] = $document;
}
//test document objects have their folders set
$folders = array();
for($i = 0; $i <= 16; $i++) {
$folderName = $documents[$i]->Folder;
$this->assertTrue(strpos($documents[$i]->getFullPath(), DIRECTORY_SEPARATOR . $folderName . DIRECTORY_SEPARATOR) !== false, "Correct folder name for the documents. Document path contains reference to folder name '$folderName'");
$folders[] = $folderName;
}
//test document objects have their folders set
$folders = array();
for ($i = 0; $i <= 16; $i++) {
$folderName = $documents[$i]->Folder;
$this->assertTrue(strpos($documents[$i]->getFullPath(), DIRECTORY_SEPARATOR . $folderName . DIRECTORY_SEPARATOR) !== false, "Correct folder name for the documents. Document path contains reference to folder name '$folderName'");
$folders[] = $folderName;
}
//test we created 4 folder to contain the 17 files
foreach($folders as $f) {
$this->assertTrue(is_dir(DMS::get_dms_path() . DIRECTORY_SEPARATOR . $f),"Document folder '$f' exists");
}
}
//test we created 4 folder to contain the 17 files
foreach ($folders as $f) {
$this->assertTrue(is_dir(DMS::get_dms_path() . DIRECTORY_SEPARATOR . $f), "Document folder '$f' exists");
}
}
function testReplaceDocument() {
$dms = DMS::inst();
public function testReplaceDocument()
{
$dms = DMS::inst();
//store the first document
$document = $dms->storeDocument(self::$testFile);
$document->Title = "My custom title";
$document->Description = "My custom description";
$document->write();
//store the first document
$document = $dms->storeDocument(self::$testFile);
$document->Title = "My custom title";
$document->Description = "My custom description";
$document->write();
//then overwrite with a second document
$document = $document->replaceDocument(self::$testFile2);
//then overwrite with a second document
$document = $document->replaceDocument(self::$testFile2);
$this->assertNotNull($document, "Document object created");
$this->assertTrue(file_exists(DMS::get_dms_path() . DIRECTORY_SEPARATOR . $document->Folder . DIRECTORY_SEPARATOR . $document->Filename),"Document file copied into DMS folder");
$this->assertContains("DMS-test-document-2",$document->Filename, "Original document filename is contain in the new filename");
$this->assertEquals("My custom title", $document->Title , "Custom title not modified");
$this->assertEquals("My custom description", $document->Description, "Custom description not modified");
}
$this->assertNotNull($document, "Document object created");
$this->assertTrue(file_exists(DMS::get_dms_path() . DIRECTORY_SEPARATOR . $document->Folder . DIRECTORY_SEPARATOR . $document->Filename), "Document file copied into DMS folder");
$this->assertContains("DMS-test-document-2", $document->Filename, "Original document filename is contain in the new filename");
$this->assertEquals("My custom title", $document->Title, "Custom title not modified");
$this->assertEquals("My custom description", $document->Description, "Custom description not modified");
}
function testDownloadDocument() {
// $dms = DMS::inst();
public function testDownloadDocument()
{
// $dms = DMS::inst();
//
// //store the first document
// $document = $dms->storeDocument(self::$testFile);
@ -136,7 +144,5 @@ class DMSTest extends FunctionalTest {
// $response = $d->index(new SS_HTTPRequest('GET',$link,array("ID"=>$document->ID)));
// //$response = $this->get($link);
// Debug::show($response);
}
}
}
}

View File

@ -1,95 +1,96 @@
<?php
class DMSVersioningTest extends SapphireTest {
class DMSVersioningTest extends SapphireTest
{
static $testFile = 'dms/tests/DMS-test-lorum-file.pdf';
static $testFile2 = 'dms/tests/DMS-test-document-2.pdf';
public static $testFile = 'dms/tests/DMS-test-lorum-file.pdf';
public static $testFile2 = 'dms/tests/DMS-test-document-2.pdf';
//store values to reset back to after this test runs
static $dmsFolderOld;
static $dmsFolderSizeOld;
static $dmsEnableVersionsOld;
//store values to reset back to after this test runs
public static $dmsFolderOld;
public static $dmsFolderSizeOld;
public static $dmsEnableVersionsOld;
function setUp() {
parent::setUp();
public function setUp()
{
parent::setUp();
self::$dmsFolderOld = DMS::$dmsFolder;
self::$dmsFolderSizeOld = DMS::$dmsFolderSize;
self::$dmsEnableVersionsOld = DMSDocument_versions::$enable_versions;
DMSDocument_versions::$enable_versions = true;
self::$dmsFolderOld = DMS::$dmsFolder;
self::$dmsFolderSizeOld = DMS::$dmsFolderSize;
self::$dmsEnableVersionsOld = DMSDocument_versions::$enable_versions;
DMSDocument_versions::$enable_versions = true;
//use a test DMS folder, so we don't overwrite the live one
DMS::$dmsFolder = 'dms-assets-test-versions';
//use a test DMS folder, so we don't overwrite the live one
DMS::$dmsFolder = 'dms-assets-test-versions';
//clear out the test folder (in case a broken test doesn't delete it)
$this->delete(BASE_PATH . DIRECTORY_SEPARATOR . 'dms-assets-test-versions');
}
//clear out the test folder (in case a broken test doesn't delete it)
$this->delete(BASE_PATH . DIRECTORY_SEPARATOR . 'dms-assets-test-versions');
}
function tearDown() {
$d = DataObject::get("DMSDocument");
foreach($d as $d1) {
$d1->delete();
}
$t = DataObject::get("DMSTag");
foreach($t as $t1) {
$t1->delete();
}
public function tearDown()
{
$d = DataObject::get("DMSDocument");
foreach ($d as $d1) {
$d1->delete();
}
$t = DataObject::get("DMSTag");
foreach ($t as $t1) {
$t1->delete();
}
//delete the test folder after the test runs
$this->delete(BASE_PATH . DIRECTORY_SEPARATOR . 'dms-assets-test-versions');
//delete the test folder after the test runs
$this->delete(BASE_PATH . DIRECTORY_SEPARATOR . 'dms-assets-test-versions');
parent::tearDown();
parent::tearDown();
//set the old DMS folder back again
DMS::$dmsFolder = self::$dmsFolderOld;
DMS::$dmsFolderSize = self::$dmsFolderSizeOld;
DMSDocument_versions::$enable_versions = self::$dmsEnableVersionsOld;
}
//set the old DMS folder back again
DMS::$dmsFolder = self::$dmsFolderOld;
DMS::$dmsFolderSize = self::$dmsFolderSizeOld;
DMSDocument_versions::$enable_versions = self::$dmsEnableVersionsOld;
}
public function delete($path) {
if (file_exists($path) || is_dir($path)) {
$it = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($path),
RecursiveIteratorIterator::CHILD_FIRST
);
foreach ($it as $file) {
if (in_array($file->getBasename(), array('.', '..'))) {
continue;
} elseif ($file->isDir()) {
rmdir($file->getPathname());
} elseif ($file->isFile() || $file->isLink()) {
unlink($file->getPathname());
}
}
rmdir($path);
}
}
public function delete($path)
{
if (file_exists($path) || is_dir($path)) {
$it = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($path),
RecursiveIteratorIterator::CHILD_FIRST
);
foreach ($it as $file) {
if (in_array($file->getBasename(), array('.', '..'))) {
continue;
} elseif ($file->isDir()) {
rmdir($file->getPathname());
} elseif ($file->isFile() || $file->isLink()) {
unlink($file->getPathname());
}
}
rmdir($path);
}
}
function testDMSVersionStorage() {
$dms = DMS::inst();
public function testDMSVersionStorage()
{
$dms = DMS::inst();
$document = $dms->storeDocument(self::$testFile);
$document = $dms->storeDocument(self::$testFile);
$this->assertNotNull($document, "Document object created");
$this->assertTrue(file_exists(DMS::get_dms_path() . DIRECTORY_SEPARATOR . $document->Folder . DIRECTORY_SEPARATOR . $document->Filename),"Document file copied into DMS folder");
$this->assertNotNull($document, "Document object created");
$this->assertTrue(file_exists(DMS::get_dms_path() . DIRECTORY_SEPARATOR . $document->Folder . DIRECTORY_SEPARATOR . $document->Filename), "Document file copied into DMS folder");
$document->replaceDocument(self::$testFile2);
$document->replaceDocument(self::$testFile);
$document->replaceDocument(self::$testFile2);
$document->replaceDocument(self::$testFile);
$document->replaceDocument(self::$testFile2);
$document->replaceDocument(self::$testFile);
$document->replaceDocument(self::$testFile2);
$document->replaceDocument(self::$testFile);
$versionsList = $document->getVersions();
$versionsList = $document->getVersions();
$this->assertEquals(4, $versionsList->Count(),"4 Versions created");
$versionsArray = $versionsList->toArray();
$this->assertEquals(4, $versionsList->Count(), "4 Versions created");
$versionsArray = $versionsList->toArray();
$this->assertEquals($versionsArray[0]->VersionCounter, 1,"Correct version count");
$this->assertEquals($versionsArray[1]->VersionCounter, 2,"Correct version count");
$this->assertEquals($versionsArray[2]->VersionCounter, 3,"Correct version count");
$this->assertEquals($versionsArray[3]->VersionCounter, 4,"Correct version count");
}
}
$this->assertEquals($versionsArray[0]->VersionCounter, 1, "Correct version count");
$this->assertEquals($versionsArray[1]->VersionCounter, 2, "Correct version count");
$this->assertEquals($versionsArray[2]->VersionCounter, 3, "Correct version count");
$this->assertEquals($versionsArray[3]->VersionCounter, 4, "Correct version count");
}
}

View File

@ -1,35 +1,36 @@
<?php
class ShortCodeRelationFinderTest extends SapphireTest {
class ShortCodeRelationFinderTest extends SapphireTest
{
static $fixture_file = array(
'dms/tests/dmstest.yml'
);
public static $fixture_file = array(
'dms/tests/dmstest.yml'
);
function testFindInRate() {
$d1 = $this->objFromFixture('DMSDocument', 'd1');
$d2 = $this->objFromFixture('DMSDocument', 'd2');
public function testFindInRate()
{
$d1 = $this->objFromFixture('DMSDocument', 'd1');
$d2 = $this->objFromFixture('DMSDocument', 'd2');
$page1 = new SiteTree();
$page1->Content = 'Condition: <a title="document test 1" href="[dms_document_link,id='.$d1->ID.']">';
$page1ID = $page1->write();
$page1 = new SiteTree();
$page1->Content = 'Condition: <a title="document test 1" href="[dms_document_link,id='.$d1->ID.']">';
$page1ID = $page1->write();
$page2 = new SiteTree();
$page2->Content = 'Condition: <a title="document test 2" href="[dms_document_link,id='.$d2->ID.']">';
$page2ID = $page2->write();
$page2 = new SiteTree();
$page2->Content = 'Condition: <a title="document test 2" href="[dms_document_link,id='.$d2->ID.']">';
$page2ID = $page2->write();
$page3 = new SiteTree();
$page3->Content = 'Condition: <a title="document test 1" href="[dms_document_link,id='.$d1->ID.']">';
$page3ID = $page3->write();
$page3 = new SiteTree();
$page3->Content = 'Condition: <a title="document test 1" href="[dms_document_link,id='.$d1->ID.']">';
$page3ID = $page3->write();
$finder = new ShortCodeRelationFinder();
$finder = new ShortCodeRelationFinder();
$ids = $finder->findPageIDs('UnknownShortcode');
$this->assertEquals(0, count($ids));
$ids = $finder->findPageIDs('UnknownShortcode');
$this->assertEquals(0, count($ids));
$ids = $finder->findPageIDs($d1->ID);
$this->assertNotContains($page2ID, $ids);
$this->assertContains($page1ID, $ids);
$this->assertContains($page3ID, $ids);
}
}
$ids = $finder->findPageIDs($d1->ID);
$this->assertNotContains($page2ID, $ids);
$this->assertContains($page1ID, $ids);
$this->assertContains($page3ID, $ids);
}
}