/
DMSDocumentSet.php
417 lines (373 loc) · 14.7 KB
/
DMSDocumentSet.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
<?php
/**
* A document set is attached to Pages, and contains many DMSDocuments
*
* @property Varchar Title
* @property Text KeyValuePairs
* @property Enum SortBy
* @property Enum SortByDirection
*/
class DMSDocumentSet extends DataObject
{
private static $db = array(
'Title' => 'Varchar(255)',
'KeyValuePairs' => 'Text',
'SortBy' => "Enum('LastEdited,Created,Title')')",
'SortByDirection' => "Enum('DESC,ASC')')",
);
private static $has_one = array(
'Page' => 'SiteTree',
);
private static $many_many = array(
'Documents' => 'DMSDocument',
);
private static $many_many_extraFields = array(
'Documents' => array(
// Flag indicating if a document was added directly to a set - in which case it is set - or added
// via the query-builder.
'ManuallyAdded' => 'Boolean(1)',
'DocumentSort' => 'Int'
),
);
private static $summary_fields = array(
'Title' => 'Title',
'Documents.Count' => 'No. Documents'
);
/**
* Retrieve a list of the documents in this set. An extension hook is provided before the result is returned.
*
* You can attach an extension to this event:
*
* <code>
* public function updateDocuments($document)
* {
* // do something
* }
* </code>
*
* @return DataList|null
*/
public function getDocuments()
{
$documents = $this->Documents();
$this->extend('updateDocuments', $documents);
return $documents;
}
/**
* Put the "documents" list into the main tab instead of its own tab, and replace the default "Add Document" button
* with a customised button for DMS documents
*
* @return FieldList
*/
public function getCMSFields()
{
// PHP 5.3 only
$self = $this;
$this->beforeUpdateCMSFields(function (FieldList $fields) use ($self) {
$fields->removeFieldsFromTab(
'Root.Main',
array('KeyValuePairs', 'SortBy', 'SortByDirection')
);
// Don't put the GridField for documents in until the set has been created
if (!$self->isInDB()) {
$fields->addFieldToTab(
'Root.Main',
LiteralField::create(
'GridFieldNotice',
'<p class="message warning">' . _t(
'DMSDocumentSet.GRIDFIELD_NOTICE',
'Managing documents will be available once you have created this document set.'
) . '</p>'
),
'Title'
);
} else {
$fields->removeByName('DocumentSetSort');
// Document listing
$gridFieldConfig = GridFieldConfig::create()
->addComponents(
new GridFieldButtonRow('before'),
new GridFieldToolbarHeader(),
new GridFieldFilterHeader(),
new GridFieldSortableHeader(),
new GridFieldDataColumns(),
new DMSGridFieldEditButton(),
// Special delete dialog to handle custom behaviour of unlinking and deleting
new GridFieldDeleteAction(true),
new GridFieldDetailForm()
);
if (class_exists('GridFieldPaginatorWithShowAll')) {
$paginatorComponent = new GridFieldPaginatorWithShowAll(15);
} else {
$paginatorComponent = new GridFieldPaginator(15);
}
$gridFieldConfig->addComponent($paginatorComponent);
if (class_exists('GridFieldSortableRows')) {
$gridFieldConfig->addComponent(new GridFieldSortableRows('DocumentSort'));
}
// Don't show which page this is if we're already editing within a page context
if (Controller::curr() instanceof CMSPageEditController) {
$fields->removeByName('PageID');
} else {
$fields->fieldByName('Root.Main.PageID')->setTitle(_t('DMSDocumentSet.SHOWONPAGE', 'Show on page'));
}
// Don't show which page this is if we're already editing within a page context
if (Controller::curr() instanceof CMSPageEditController) {
$fields->removeByName('PageID');
} else {
$fields->fieldByName('Root.Main.PageID')->setTitle(_t('DMSDocumentSet.SHOWONPAGE', 'Show on page'));
}
$gridFieldConfig->getComponentByType('GridFieldDataColumns')
->setDisplayFields($self->getDocumentDisplayFields())
->setFieldCasting(array('LastEdited' => 'Datetime->Ago'))
->setFieldFormatting(
array(
'FilenameWithoutID' => '<a target=\'_blank\' class=\'file-url\''
. ' href=\'$Link\'>$FilenameWithoutID</a>',
'ManuallyAdded' => function ($value) {
if ($value) {
return _t('DMSDocumentSet.MANUAL', 'Manually');
}
return _t('DMSDocumentSet.QUERYBUILDER', 'Query Builder');
}
)
);
// Override delete functionality with this class
$gridFieldConfig->getComponentByType('GridFieldDetailForm')
->setItemRequestClass('DMSGridFieldDetailForm_ItemRequest');
$gridField = GridField::create(
'Documents',
false,
$self->Documents(),
$gridFieldConfig
);
$gridField->setModelClass('DMSDocument');
$gridField->addExtraClass('documents');
$gridFieldConfig->addComponent(
$addNewButton = new DMSGridFieldAddNewButton('buttons-before-left'),
'GridFieldExportButton'
);
$addNewButton->setDocumentSetId($self->ID);
$fields->removeByName('Documents');
$fields->addFieldsToTab(
'Root.Main',
array(
$gridField,
HiddenField::create('DMSShortcodeHandlerKey', false, DMS::inst()->getShortcodeHandlerKey())
)
);
$self->addQueryFields($fields);
}
});
$this->addRequirements();
return parent::getCMSFields();
}
/**
* Add required CSS and Javascript requirements for managing documents
*
* @return $this
*/
protected function addRequirements()
{
// 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 . '/dist/css/dmsbundle.css');
// Javascript for the link editor pop-up in TinyMCE
Requirements::javascript(DMS_DIR . '/javascript/DocumentHtmlEditorFieldToolbar.js');
return $this;
}
/**
* Adds the query fields to build the document logic to the DMSDocumentSet.
*
* @param FieldList $fields
*/
public function addQueryFields($fields)
{
/** @var DMSDocument $doc */
$doc = singleton('DMSDocument');
/** @var FormField $field */
$dmsDocFields = $doc->scaffoldSearchFields(array('fieldClasses' => true));
$membersMap = Member::get()->map('ID', 'Name')->toArray();
asort($membersMap);
foreach ($dmsDocFields as $field) {
if ($field instanceof ListboxField) {
$map = ($field->getName() === 'Tags__ID') ? $doc->getAllTagsMap() : $membersMap;
$field->setMultiple(true)->setSource($map);
if ($field->getName() === 'Tags__ID') {
$field->setRightTitle(
_t(
'DMSDocumentSet.TAGS_RIGHT_TITLE',
'Tags can be set in the taxonomy area, and can be assigned when editing a document.'
)
);
}
}
}
$keyValPairs = DMSJsonField::create('KeyValuePairs', $dmsDocFields->toArray());
// Now lastly add the sort fields
$sortedBy = FieldGroup::create('SortedBy', array(
DropdownField::create('SortBy', '', array(
'LastEdited' => 'Last changed',
'Created' => 'Created',
'Title' => 'Document title',
), 'LastEdited'),
DropdownField::create(
'SortByDirection',
'',
array(
'DESC' => _t('DMSDocumentSet.DIRECTION_DESCENDING', 'Descending'),
'ASC' => _t('DMSDocumentSet.DIRECTION_ASCENDING', 'Ascending')
),
'DESC'
),
));
$sortedBy->setTitle(_t('DMSDocumentSet.SORTED_BY', 'Sort the document set by:'));
$fields->addFieldsToTab(
'Root.QueryBuilder',
array(
LiteralField::create(
'GridFieldNotice',
'<p class="message warning">' . _t(
'DMSDocumentSet.QUERY_BUILDER_NOTICE',
'The query builder provides the ability to add documents to a document set based on the ' .
'filters below. Please note that the set will be built using this criteria when you save the ' .
'form. This set will not be dynamically updated (see the documentation for more information).'
) . '</p>'
),
$keyValPairs,
$sortedBy
)
);
}
public function onBeforeWrite()
{
parent::onBeforeWrite();
$this->saveLinkedDocuments();
}
/**
* Retrieve a list of the documents in this set. An extension hook is provided before the result is returned.
*/
public function saveLinkedDocuments()
{
if (empty($this->KeyValuePairs) || !$this->isChanged('KeyValuePairs')) {
return;
}
$keyValuesPair = Convert::json2array($this->KeyValuePairs);
/** @var DMSDocument $dmsDoc */
$dmsDoc = singleton('DMSDocument');
$context = $dmsDoc->getDefaultSearchContext();
$sortBy = $this->SortBy ? $this->SortBy : 'LastEdited';
$sortByDirection = $this->SortByDirection ? $this->SortByDirection : 'DESC';
$sortedBy = sprintf('%s %s', $sortBy, $sortByDirection);
/** @var DataList $documents */
$documents = $context->getResults($keyValuesPair, $sortedBy);
$documents = $this->addEmbargoConditions($documents);
$documents = $this->addQueryBuilderSearchResults($documents);
}
/**
* Add embargo date conditions to a search query
*
* @param DataList $documents
* @return DataList
*/
protected function addEmbargoConditions(DataList $documents)
{
$now = SS_Datetime::now()->Rfc2822();
return $documents->where(
"\"EmbargoedIndefinitely\" = 0 AND "
. " \"EmbargoedUntilPublished\" = 0 AND "
. "(\"EmbargoedUntilDate\" IS NULL OR "
. "(\"EmbargoedUntilDate\" IS NOT NULL AND '{$now}' >= \"EmbargoedUntilDate\")) AND "
. "\"ExpireAtDate\" IS NULL OR (\"ExpireAtDate\" IS NOT NULL AND '{$now}' < \"ExpireAtDate\")"
);
}
/**
* Remove all ManuallyAdded = 0 original results and add in the new documents returned by the search context
*
* @param DataList $documents
* @return DataList
*/
protected function addQueryBuilderSearchResults(DataList $documents)
{
/** @var ManyManyList $originals Documents that belong to just this set. */
$originals = $this->Documents();
$originals->removeByFilter('"ManuallyAdded" = 0');
foreach ($documents as $document) {
$originals->add($document, array('ManuallyAdded' => 0));
}
return $originals;
}
/**
* Customise the display fields for the documents GridField
*
* @return array
*/
public function getDocumentDisplayFields()
{
return array_merge(
(array) DMSDocument::create()->config()->get('display_fields'),
array('ManuallyAdded' => _t('DMSDocumentSet.ADDEDMETHOD', 'Added'))
);
}
protected function validate()
{
$result = parent::validate();
if (!$this->getTitle()) {
$result->error(_t('DMSDocumentSet.VALIDATION_NO_TITLE', '\'Title\' is required.'));
}
return $result;
}
public function canView($member = null)
{
$extended = $this->extendedCan(__FUNCTION__, $member);
if ($extended !== null) {
return $extended;
}
return $this->getGlobalPermission($member);
}
public function canCreate($member = null)
{
$extended = $this->extendedCan(__FUNCTION__, $member);
if ($extended !== null) {
return $extended;
}
return $this->getGlobalPermission($member);
}
public function canEdit($member = null)
{
$extended = $this->extendedCan(__FUNCTION__, $member);
if ($extended !== null) {
return $extended;
}
return $this->getGlobalPermission($member);
}
public function canDelete($member = null)
{
$extended = $this->extendedCan(__FUNCTION__, $member);
if ($extended !== null) {
return $extended;
}
return $this->getGlobalPermission($member);
}
/**
* Checks if a then given (or logged in) member is either an ADMIN, SITETREE_EDIT_ALL or has access
* to the DMSDocumentAdmin module, in which case permissions is granted.
*
* @param Member $member
* @return bool
*/
public function getGlobalPermission(Member $member = null)
{
if (!$member || !(is_a($member, 'Member')) || is_numeric($member)) {
$member = Member::currentUser();
}
$result = ($member &&
Permission::checkMember(
$member,
array('ADMIN', 'SITETREE_EDIT_ALL', 'CMS_ACCESS_DMSDocumentAdmin')
)
);
return (bool) $result;
}
}