Completed
Pull Request — master (#124)
by Robbie
02:25
created

DMSDocument::getRelatedDocumentsGridField()   B

Complexity

Conditions 1
Paths 1

Size

Total Lines 26
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 26
rs 8.8571
c 0
b 0
f 0
cc 1
eloc 14
nc 1
nop 0
1
<?php
2
3
/**
4
 * @package dms
5
 *
6
 * @property Varchar Filename
7
 * @property Varchar Folder
8
 * @property Varchar Title
9
 * @property Text Description
10
 * @property int ViewCount
11
 * @property Boolean EmbargoedIndefinitely
12
 * @property Boolean EmbargoedUntilPublished
13
 * @property DateTime EmbargoedUntilDate
14
 * @property DateTime ExpireAtDate
15
 * @property Enum DownloadBehavior
16
 * @property Enum CanViewType Enum('Anyone, LoggedInUsers, OnlyTheseUsers', 'Anyone')
17
 * @property Enum CanEditType Enum('LoggedInUsers, OnlyTheseUsers', 'LoggedInUsers')
18
 *
19
 * @method ManyManyList RelatedDocuments
20
 * @method ManyManyList ViewerGroups
21
 * @method ManyManyList EditorGroups
22
 *
23
 * @method Member CreatedBy
24
 * @property Int CreatedByID
25
 * @method Member LastEditedBy
26
 * @property Int LastEditedByID
27
 *
28
 */
29
class DMSDocument extends DataObject implements DMSDocumentInterface
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
30
{
31
    private static $db = array(
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
Unused Code introduced by
The property $db is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
32
        "Filename" => "Varchar(255)", // eg. 3469~2011-energysaving-report.pdf
33
        "Folder" => "Varchar(255)",    // eg.	0
34
        "Title" => 'Varchar(1024)', // eg. "Energy Saving Report for Year 2011, New Zealand LandCorp"
35
        "Description" => 'Text',
36
        "ViewCount" => 'Int',
37
        "EmbargoedIndefinitely" => 'Boolean(false)',
38
        "EmbargoedUntilPublished" => 'Boolean(false)',
39
        "EmbargoedUntilDate" => 'SS_DateTime',
40
        "ExpireAtDate" => 'SS_DateTime',
41
        "DownloadBehavior" => 'Enum(array("open","download"), "download")',
42
        "CanViewType" => "Enum('Anyone, LoggedInUsers, OnlyTheseUsers', 'Anyone')",
43
        "CanEditType" => "Enum('LoggedInUsers, OnlyTheseUsers', 'LoggedInUsers')",
44
    );
45
46
    private static $belongs_many_many = array(
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
Unused Code introduced by
The property $belongs_many_many is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
47
        'Sets' => 'DMSDocumentSet'
48
    );
49
50
    private static $has_one = array(
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
Unused Code introduced by
The property $has_one is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
51
        'CoverImage' => 'Image',
52
        'CreatedBy' => 'Member',
53
        'LastEditedBy' => 'Member',
54
    );
55
56
    private static $many_many = array(
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
Unused Code introduced by
The property $many_many is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
57
        'RelatedDocuments' => 'DMSDocument',
58
        'ViewerGroups' => 'Group',
59
        'EditorGroups' => 'Group',
60
    );
61
62
    private static $display_fields = array(
0 ignored issues
show
Unused Code introduced by
The property $display_fields is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
63
        'ID' => 'ID',
64
        'Title' => 'Title',
65
        'FilenameWithoutID' => 'Filename',
66
        'LastEdited' => 'Last Edited'
67
    );
68
69
    private static $singular_name = 'Document';
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
Unused Code introduced by
The property $singular_name is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
70
71
    private static $plural_name = 'Documents';
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
Unused Code introduced by
The property $plural_name is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
72
73
    private static $summary_fields = array(
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
Unused Code introduced by
The property $summary_fields is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
74
        'Filename' => 'Filename',
75
        'Title' => 'Title',
76
        'ViewCount' => 'ViewCount',
77
        'getRelatedPages.count' => 'Page Use'
78
    );
79
80
    /**
81
     * @var string download|open
82
     * @config
83
     */
84
    private static $default_download_behaviour = 'download';
0 ignored issues
show
Unused Code introduced by
The property $default_download_behaviour is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
85
86
    /**
87
     * A key value map of the "actions" tabs that will be added to the CMS fields
88
     *
89
     * @var array
90
     */
91
    protected $actionTasks = array(
92
        'embargo' => 'Embargo',
93
        'expiry' => 'Expiry',
94
        'replace' => 'Replace',
95
        'find-usage' => 'Usage',
96
        'find-references' => 'References',
97
        'find-relateddocuments' => 'Related Documents',
98
        'permissions' => 'Permissions'
99
    );
100
101
    public function canView($member = null)
102
    {
103
        if (!$member || !(is_a($member, 'Member')) || is_numeric($member)) {
104
            $member = Member::currentUser();
105
        }
106
107
        // extended access checks
108
        $results = $this->extend('canView', $member);
109
110
        if ($results && is_array($results)) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $results of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
111
            if (!min($results)) {
112
                return false;
113
            }
114
        }
115
116
        if (!$this->CanViewType || $this->CanViewType == 'Anyone') {
117
            return true;
118
        }
119
120 View Code Duplication
        if ($member && Permission::checkMember($member, array(
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
121
                'ADMIN',
122
                'SITETREE_EDIT_ALL',
123
                'SITETREE_VIEW_ALL',
124
            ))
125
        ) {
126
            return true;
127
        }
128
129
        if ($this->isHidden()) {
130
            return false;
131
        }
132
133
        if ($this->CanViewType == 'LoggedInUsers') {
134
            return $member && $member->exists();
135
        }
136
137
        if ($this->CanViewType == 'OnlyTheseUsers' && $this->ViewerGroups()->count()) {
0 ignored issues
show
Documentation Bug introduced by
The method ViewerGroups does not exist on object<DMSDocument>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
138
            return ($member && $member->inGroups($this->ViewerGroups()));
0 ignored issues
show
Documentation Bug introduced by
The method ViewerGroups does not exist on object<DMSDocument>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
139
        }
140
141
        return $this->canEdit($member);
142
    }
143
144
    public function canEdit($member = null)
145
    {
146
        if (!$member || !(is_a($member, 'Member')) || is_numeric($member)) {
147
            $member = Member::currentUser();
148
        }
149
150
        $results = $this->extend('canEdit', $member);
151
152
        if ($results && is_array($results)) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $results of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
153
            if (!min($results)) {
154
                return false;
155
            }
156
        }
157
158
        // Do early admin check
159 View Code Duplication
        if ($member && Permission::checkMember(
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
160
            $member,
161
            array(
162
                    'ADMIN',
163
                    'SITETREE_EDIT_ALL',
164
                    'SITETREE_VIEW_ALL',
165
                )
166
        )
167
        ) {
168
            return true;
169
        }
170
171
        if ($this->CanEditType === 'LoggedInUsers') {
172
            return $member && $member->exists();
173
        }
174
175
        if ($this->CanEditType === 'OnlyTheseUsers' && $this->EditorGroups()->count()) {
0 ignored issues
show
Documentation Bug introduced by
The method EditorGroups does not exist on object<DMSDocument>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
176
            return $member && $member->inGroups($this->EditorGroups());
0 ignored issues
show
Documentation Bug introduced by
The method EditorGroups does not exist on object<DMSDocument>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
177
        }
178
179
        return ($member && Permission::checkMember($member, array('ADMIN', 'SITETREE_EDIT_ALL')));
180
    }
181
182
    /**
183
     * @param Member $member
0 ignored issues
show
Documentation introduced by
Should the type for parameter $member not be Member|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
184
     *
185
     * @return boolean
186
     */
187 View Code Duplication
    public function canCreate($member = null)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
188
    {
189
        if (!$member || !(is_a($member, 'Member')) || is_numeric($member)) {
190
            $member = Member::currentUser();
191
        }
192
193
        $results = $this->extend('canCreate', $member);
194
195
        if ($results && is_array($results)) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $results of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
196
            if (!min($results)) {
197
                return false;
198
            }
199
        }
200
201
        return $this->canEdit($member);
202
    }
203
204
    /**
205
     * @param Member $member
0 ignored issues
show
Documentation introduced by
Should the type for parameter $member not be Member|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
206
     *
207
     * @return boolean
208
     */
209 View Code Duplication
    public function canDelete($member = null)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
210
    {
211
        if (!$member || !(is_a($member, 'Member')) || is_numeric($member)) {
212
            $member = Member::currentUser();
213
        }
214
215
        $results = $this->extend('canDelete', $member);
216
217
        if ($results && is_array($results)) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $results of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
218
            if (!min($results)) {
219
                return false;
220
            }
221
        }
222
223
        return $this->canView();
224
    }
225
226
    /**
227
     * Increase ViewCount by 1, without update any other record fields such as
228
     * LastEdited.
229
     *
230
     * @return DMSDocument
231
     */
232
    public function trackView()
233
    {
234
        if ($this->ID > 0) {
235
            $count = $this->ViewCount + 1;
236
237
            $this->ViewCount = $count;
238
239
            DB::query("UPDATE \"DMSDocument\" SET \"ViewCount\"='$count' WHERE \"ID\"={$this->ID}");
240
        }
241
242
        return $this;
243
    }
244
245
    /**
246
     * Returns a link to download this document from the DMS store.
247
     * Alternatively a basic javascript alert will be shown should the user not have view permissions. An extension
248
     * point for this was also added.
249
     *
250
     * To extend use the following from within an Extension subclass:
251
     *
252
     * <code>
253
     * public function updateGetLink($result)
254
     * {
255
     *     // Do something here
256
     * }
257
     * </code>
258
     *
259
     * @return string
260
     */
261
    public function getLink()
262
    {
263
        $result = Controller::join_links(Director::baseURL(), 'dmsdocument/' . $this->ID);
264
        if (!$this->canView()) {
265
            $result = sprintf("javascript:alert('%s')", $this->getPermissionDeniedReason());
266
        }
267
268
        $this->extend('updateGetLink', $result);
269
270
        return $result;
271
    }
272
273
    /**
274
     * @return string
275
     */
276
    public function Link()
277
    {
278
        return $this->getLink();
279
    }
280
281
    /**
282
     * Hides the document, so it does not show up when getByPage($myPage) is
283
     * called (without specifying the $showEmbargoed = true parameter).
284
     *
285
     * This is similar to expire, except that this method should be used to hide
286
     * documents that have not yet gone live.
287
     *
288
     * @param bool $write Save change to the database
289
     *
290
     * @return DMSDocument
291
     */
292
    public function embargoIndefinitely($write = true)
293
    {
294
        $this->EmbargoedIndefinitely = true;
295
296
        if ($write) {
297
            $this->write();
298
        }
299
300
        return $this;
301
    }
302
303
    /**
304
     * Hides the document until any page it is linked to is published
305
     *
306
     * @param bool $write Save change to database
307
     *
308
     * @return DMSDocument
309
     */
310
    public function embargoUntilPublished($write = true)
311
    {
312
        $this->EmbargoedUntilPublished = true;
313
314
        if ($write) {
315
            $this->write();
316
        }
317
318
        return $this;
319
    }
320
321
    /**
322
     * Returns if this is Document is embargoed or expired.
323
     *
324
     * Also, returns if the document should be displayed on the front-end,
325
     * respecting the current reading mode of the site and the embargo status.
326
     *
327
     * I.e. if a document is embargoed until published, then it should still
328
     * show up in draft mode.
329
     *
330
     * @return bool
331
     */
332
    public function isHidden()
333
    {
334
        $hidden = $this->isEmbargoed() || $this->isExpired();
335
        $readingMode = Versioned::get_reading_mode();
336
337
        if ($readingMode == "Stage.Stage") {
338
            if ($this->EmbargoedUntilPublished == true) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
339
                $hidden = false;
340
            }
341
        }
342
343
        return $hidden;
344
    }
345
346
    /**
347
     * Returns if this is Document is embargoed.
348
     *
349
     * @return bool
350
     */
351
    public function isEmbargoed()
352
    {
353
        if (is_object($this->EmbargoedUntilDate)) {
354
            $this->EmbargoedUntilDate = $this->EmbargoedUntilDate->Value;
0 ignored issues
show
Bug introduced by
The property Value does not seem to exist in DateTime.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
355
        }
356
357
        $embargoed = false;
358
359
        if ($this->EmbargoedIndefinitely) {
360
            $embargoed = true;
361
        } elseif ($this->EmbargoedUntilPublished) {
362
            $embargoed = true;
363
        } elseif (!empty($this->EmbargoedUntilDate)) {
364
            if (SS_Datetime::now()->Value < $this->EmbargoedUntilDate) {
365
                $embargoed = true;
366
            }
367
        }
368
369
        return $embargoed;
370
    }
371
372
    /**
373
     * Hides the document, so it does not show up when getByPage($myPage) is
374
     * called. Automatically un-hides the Document at a specific date.
375
     *
376
     * @param string $datetime date time value when this Document should expire.
377
     * @param bool $write
378
     *
379
     * @return DMSDocument
380
     */
381 View Code Duplication
    public function embargoUntilDate($datetime, $write = true)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
382
    {
383
        $this->EmbargoedUntilDate = DBField::create_field('SS_Datetime', $datetime)->Format('Y-m-d H:i:s');
384
385
        if ($write) {
386
            $this->write();
387
        }
388
389
        return $this;
390
    }
391
392
    /**
393
     * Clears any previously set embargos, so the Document always shows up in
394
     * all queries.
395
     *
396
     * @param bool $write
397
     *
398
     * @return DMSDocument
399
     */
400
    public function clearEmbargo($write = true)
401
    {
402
        $this->EmbargoedIndefinitely = false;
403
        $this->EmbargoedUntilPublished = false;
404
        $this->EmbargoedUntilDate = null;
405
406
        if ($write) {
407
            $this->write();
408
        }
409
410
        return $this;
411
    }
412
413
    /**
414
     * Returns if this is Document is expired.
415
     *
416
     * @return bool
417
     */
418
    public function isExpired()
419
    {
420
        if (is_object($this->ExpireAtDate)) {
421
            $this->ExpireAtDate = $this->ExpireAtDate->Value;
0 ignored issues
show
Bug introduced by
The property Value does not seem to exist in DateTime.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
422
        }
423
424
        $expired = false;
425
426
        if (!empty($this->ExpireAtDate)) {
427
            if (SS_Datetime::now()->Value >= $this->ExpireAtDate) {
428
                $expired = true;
429
            }
430
        }
431
432
        return $expired;
433
    }
434
435
    /**
436
     * Hides the document at a specific date, so it does not show up when
437
     * getByPage($myPage) is called.
438
     *
439
     * @param string $datetime date time value when this Document should expire
440
     * @param bool $write
441
     *
442
     * @return DMSDocument
443
     */
444 View Code Duplication
    public function expireAtDate($datetime, $write = true)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
445
    {
446
        $this->ExpireAtDate = DBField::create_field('SS_Datetime', $datetime)->Format('Y-m-d H:i:s');
447
448
        if ($write) {
449
            $this->write();
450
        }
451
452
        return $this;
453
    }
454
455
    /**
456
     * Clears any previously set expiry.
457
     *
458
     * @param bool $write
459
     *
460
     * @return DMSDocument
461
     */
462
    public function clearExpiry($write = true)
463
    {
464
        $this->ExpireAtDate = null;
465
466
        if ($write) {
467
            $this->write();
468
        }
469
470
        return $this;
471
    }
472
473
    /**
474
     * Returns a DataList of all previous Versions of this document (check the
475
     * LastEdited date of each object to find the correct one).
476
     *
477
     * If {@link DMSDocument_versions::$enable_versions} is disabled then an
478
     * Exception is thrown
479
     *
480
     * @throws Exception
481
     *
482
     * @return DataList List of Document objects
483
     */
484
    public function getVersions()
485
    {
486
        if (!DMSDocument_versions::$enable_versions) {
487
            throw new Exception("DMSDocument versions are disabled");
488
        }
489
490
        return DMSDocument_versions::get_versions($this);
491
    }
492
493
    /**
494
     * Returns the full filename of the document stored in this object.
495
     *
496
     * @return string
0 ignored issues
show
Documentation introduced by
Should the return type not be string|null?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
497
     */
498
    public function getFullPath()
499
    {
500
        if ($this->Filename) {
501
            return DMS::get_dms_path() . DIRECTORY_SEPARATOR . $this->Folder . DIRECTORY_SEPARATOR . $this->Filename;
502
        }
503
504
        return null;
505
    }
506
507
    /**
508
     * Returns the filename of this asset.
509
     *
510
     * @return string
511
     */
512
    public function getFileName()
513
    {
514
        if ($this->getField('Filename')) {
515
            return $this->getField('Filename');
516
        } else {
517
            return ASSETS_DIR . '/';
518
        }
519
    }
520
521
    /**
522
     * @return string
523
     */
524
    public function getName()
525
    {
526
        return $this->getField('Title');
527
    }
528
529
530
    /**
531
     * @return string
532
     */
533
    public function getFilenameWithoutID()
534
    {
535
        $filenameParts = explode('~', $this->Filename);
536
        $filename = array_pop($filenameParts);
537
538
        return $filename;
539
    }
540
541
    /**
542
     * @return string
543
     */
544
    public function getStorageFolder()
545
    {
546
        return DMS::get_dms_path() . DIRECTORY_SEPARATOR . DMS::get_storage_folder($this->ID);
547
    }
548
549
    /**
550
     * Deletes the DMSDocument and its underlying file. Also calls the parent DataObject's delete method in
551
     * order to complete an cascade.
552
     *
553
     * @return void
554
     */
555
    public function delete()
556
    {
557
        // delete the file (and previous versions of files)
558
        $filesToDelete = array();
559
        $storageFolder = $this->getStorageFolder();
560
561
        if (file_exists($storageFolder)) {
562
            if ($handle = opendir($storageFolder)) {
563
                while (false !== ($entry = readdir($handle))) {
564
                    // only delete if filename starts the the relevant ID
565
                    if (strpos($entry, $this->ID.'~') === 0) {
566
                        $filesToDelete[] = $entry;
567
                    }
568
                }
569
570
                closedir($handle);
571
572
                //delete all this files that have the id of this document
573
                foreach ($filesToDelete as $file) {
574
                    $filePath = $storageFolder .DIRECTORY_SEPARATOR . $file;
575
576
                    if (is_file($filePath)) {
577
                        unlink($filePath);
578
                    }
579
                }
580
            }
581
        }
582
583
        // get rid of any versions have saved for this DMSDocument, too
584
        if (DMSDocument_versions::$enable_versions) {
585
            $versions = $this->getVersions();
586
587
            if ($versions->Count() > 0) {
588
                foreach ($versions as $v) {
589
                    $v->delete();
590
                }
591
            }
592
        }
593
594
        return parent::delete();
595
    }
596
597
    /**
598
     * Relate an existing file on the filesystem to the document.
599
     *
600
     * Copies the file to the new destination, as defined in {@link get_DMS_path()}.
601
     *
602
     * @param string $filePath Path to file, relative to webroot.
603
     *
604
     * @return DMSDocument
605
     */
606
    public function storeDocument($filePath)
607
    {
608
        if (empty($this->ID)) {
609
            user_error("Document must be written to database before it can store documents", E_USER_ERROR);
610
        }
611
612
        // calculate all the path to copy the file to
613
        $fromFilename = basename($filePath);
614
        $toFilename = $this->ID. '~' . $fromFilename; //add the docID to the start of the Filename
615
        $toFolder = DMS::get_storage_folder($this->ID);
616
        $toPath = DMS::get_dms_path() . DIRECTORY_SEPARATOR . $toFolder . DIRECTORY_SEPARATOR . $toFilename;
617
618
        DMS::create_storage_folder(DMS::get_dms_path() . DIRECTORY_SEPARATOR . $toFolder);
619
620
        //copy the file into place
621
        $fromPath = BASE_PATH . DIRECTORY_SEPARATOR . $filePath;
622
623
        //version the existing file (copy it to a new "very specific" filename
624
        if (DMSDocument_versions::$enable_versions) {
625
            DMSDocument_versions::create_version($this);
626
        } else {    //otherwise delete the old document file
627
            $oldPath = $this->getFullPath();
628
            if (file_exists($oldPath)) {
629
                unlink($oldPath);
630
            }
631
        }
632
633
        copy($fromPath, $toPath);   //this will overwrite the existing file (if present)
634
635
        //write the filename of the stored document
636
        $this->Filename = $toFilename;
637
        $this->Folder = strval($toFolder);
638
639
        $extension = pathinfo($this->Filename, PATHINFO_EXTENSION);
640
641
        if (empty($this->Title)) {
642
            // don't overwrite existing document titles
643
            $this->Title = basename($filePath, '.'.$extension);
644
        }
645
646
        $this->write();
647
648
        return $this;
649
    }
650
651
    /**
652
     * Takes a File object or a String (path to a file) and copies it into the
653
     * DMS, replacing the original document file but keeping the rest of the
654
     * document unchanged.
655
     *
656
     * @param File|string $file path to a file to store
657
     *
658
     * @return DMSDocument object that we replaced the file in
659
     */
660
    public function replaceDocument($file)
661
    {
662
        $filePath = DMS::transform_file_to_file_path($file);
663
        $doc = $this->storeDocument($filePath); // replace the document
664
665
        return $doc;
666
    }
667
668
669
    /**
670
     * Return the type of file for the given extension
671
     * on the current file name.
672
     *
673
     * @param string $ext
674
     *
675
     * @return string
676
     */
677
    public static function get_file_type($ext)
678
    {
679
        $types = array(
680
            'gif' => 'GIF image - good for diagrams',
681
            'jpg' => 'JPEG image - good for photos',
682
            'jpeg' => 'JPEG image - good for photos',
683
            'png' => 'PNG image - good general-purpose format',
684
            'ico' => 'Icon image',
685
            'tiff' => 'Tagged image format',
686
            'doc' => 'Word document',
687
            'xls' => 'Excel spreadsheet',
688
            'zip' => 'ZIP compressed file',
689
            'gz' => 'GZIP compressed file',
690
            'dmg' => 'Apple disk image',
691
            'pdf' => 'Adobe Acrobat PDF file',
692
            'mp3' => 'MP3 audio file',
693
            'wav' => 'WAV audo file',
694
            'avi' => 'AVI video file',
695
            'mpg' => 'MPEG video file',
696
            'mpeg' => 'MPEG video file',
697
            'js' => 'Javascript file',
698
            'css' => 'CSS file',
699
            'html' => 'HTML file',
700
            'htm' => 'HTML file'
701
        );
702
703
        return isset($types[$ext]) ? $types[$ext] : $ext;
704
    }
705
706
707
    /**
708
     * Returns the Description field with HTML <br> tags added when there is a
709
     * line break.
710
     *
711
     * @return string
712
     */
713
    public function getDescriptionWithLineBreak()
714
    {
715
        return nl2br($this->getField('Description'));
716
    }
717
718
    /**
719
     * @return FieldList
720
     */
721
    public function getCMSFields()
722
    {
723
        //include JS to handling showing and hiding of bottom "action" tabs
724
        Requirements::javascript(DMS_DIR . '/javascript/DMSDocumentCMSFields.js');
725
        Requirements::css(DMS_DIR . '/dist/css/cmsbundle.css');
726
727
        $fields = new FieldList();  //don't use the automatic scaffolding, it is slow and unnecessary here
728
729
        $extraTasks = '';   //additional text to inject into the list of tasks at the bottom of a DMSDocument CMSfield
0 ignored issues
show
Unused Code introduced by
$extraTasks is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
730
731
        //get list of shortcode page relations
732
        $relationFinder = new ShortCodeRelationFinder();
733
        $relationList = $relationFinder->getList($this->ID);
734
735
        $fieldsTop = $this->getFieldsForFile($relationList->count());
736
        $fields->add($fieldsTop);
737
738
        $fields->add(TextField::create('Title', _t('DMSDocument.TITLE', 'Title')));
739
        $fields->add(TextareaField::create('Description', _t('DMSDocument.DESCRIPTION', 'Description')));
740
741
        $coverImageField = UploadField::create('CoverImage', _t('DMSDocument.COVERIMAGE', 'Cover Image'));
742
        $coverImageField->getValidator()->setAllowedExtensions(array('jpg', 'jpeg', 'png', 'gif'));
743
        $coverImageField->setConfig('allowedMaxFileNumber', 1);
744
        $fields->add($coverImageField);
745
746
747
        $downloadBehaviorSource = array(
748
            'open' => _t('DMSDocument.OPENINBROWSER', 'Open in browser'),
749
            'download' => _t('DMSDocument.FORCEDOWNLOAD', 'Force download'),
750
        );
751
        $defaultDownloadBehaviour = Config::inst()->get('DMSDocument', 'default_download_behaviour');
752
        if (!isset($downloadBehaviorSource[$defaultDownloadBehaviour])) {
753
            user_error('Default download behaviour "' . $defaultDownloadBehaviour . '" not supported.', E_USER_WARNING);
754
        } else {
755
            $downloadBehaviorSource[$defaultDownloadBehaviour] .= ' (' . _t('DMSDocument.DEFAULT', 'default') . ')';
756
        }
757
758
        $fields->add(
759
            OptionsetField::create(
760
                'DownloadBehavior',
761
                _t('DMSDocument.DOWNLOADBEHAVIOUR', 'Download behavior'),
762
                $downloadBehaviorSource,
763
                $defaultDownloadBehaviour
764
            )
765
            ->setDescription(
766
                'How the visitor will view this file. <strong>Open in browser</strong> '
767
                . 'allows files to be opened in a new tab.'
768
            )
769
        );
770
771
        //create upload field to replace document
772
        $uploadField = new DMSUploadField('ReplaceFile', 'Replace file');
773
        $uploadField->setConfig('allowedMaxFileNumber', 1);
774
        $uploadField->setConfig('downloadTemplateName', 'ss-dmsuploadfield-downloadtemplate');
775
        $uploadField->setRecord($this);
776
777
        $gridFieldConfig = GridFieldConfig::create()->addComponents(
778
            new GridFieldToolbarHeader(),
779
            new GridFieldSortableHeader(),
780
            new GridFieldDataColumns(),
781
            new GridFieldPaginator(30),
782
            //new GridFieldEditButton(),
0 ignored issues
show
Unused Code Comprehensibility introduced by
67% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
783
            new GridFieldDetailForm()
784
        );
785
786
        $gridFieldConfig->getComponentByType('GridFieldDataColumns')
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface GridFieldComponent as the method setDisplayFields() does only exist in the following implementations of said interface: GridFieldDataColumns, GridFieldEditableColumns, GridFieldExternalLink.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
787
            ->setDisplayFields(array(
788
                'Title'=>'Title',
789
                'ClassName'=>'Page Type',
790
                'ID'=>'Page ID'
791
            ))
792
            ->setFieldFormatting(array(
793
                'Title'=>sprintf(
794
                    '<a class=\"cms-panel-link\" href=\"%s/$ID\">$Title</a>',
795
                    singleton('CMSPageEditController')->Link('show')
796
                )
797
            ));
798
799
        $pagesGrid = GridField::create(
800
            'Pages',
801
            _t('DMSDocument.RelatedPages', 'Related Pages'),
802
            $this->getRelatedPages(),
803
            $gridFieldConfig
804
        );
805
806
        $referencesGrid = GridField::create(
807
            'References',
808
            _t('DMSDocument.RelatedReferences', 'Related References'),
809
            $relationList,
810
            $gridFieldConfig
811
        );
812
813
        if (DMSDocument_versions::$enable_versions) {
814
            $versionsGridFieldConfig = GridFieldConfig::create()->addComponents(
815
                new GridFieldToolbarHeader(),
816
                new GridFieldSortableHeader(),
817
                new GridFieldDataColumns(),
818
                new GridFieldPaginator(30)
819
            );
820
            $versionsGridFieldConfig->getComponentByType('GridFieldDataColumns')
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface GridFieldComponent as the method setDisplayFields() does only exist in the following implementations of said interface: GridFieldDataColumns, GridFieldEditableColumns, GridFieldExternalLink.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
821
                ->setDisplayFields(Config::inst()->get('DMSDocument_versions', 'display_fields'))
822
                ->setFieldFormatting(
823
                    array(
824
                        'FilenameWithoutID' => '<a target=\'_blank\' class=\'file-url\' href=\'$Link\'>'
825
                            . '$FilenameWithoutID</a>'
826
                    )
827
                );
828
829
            $versionsGrid =  GridField::create(
830
                'Versions',
831
                _t('DMSDocument.Versions', 'Versions'),
832
                $this->getVersions(),
833
                $versionsGridFieldConfig
834
            );
835
            $this->addActionPanelTask('find-versions', 'Versions');
836
        }
837
838
        $fields->add(LiteralField::create('BottomTaskSelection', $this->getActionTaskHtml()));
839
840
        $embargoValue = 'None';
841
        if ($this->EmbargoedIndefinitely) {
842
            $embargoValue = 'Indefinitely';
843
        } elseif ($this->EmbargoedUntilPublished) {
844
            $embargoValue = 'Published';
845
        } elseif (!empty($this->EmbargoedUntilDate)) {
846
            $embargoValue = 'Date';
847
        }
848
        $embargo = new OptionsetField(
849
            'Embargo',
850
            _t('DMSDocument.EMBARGO', 'Embargo'),
851
            array(
852
                'None' => _t('DMSDocument.EMBARGO_NONE', 'None'),
853
                'Published' => _t('DMSDocument.EMBARGO_PUBLISHED', 'Hide document until page is published'),
854
                'Indefinitely' => _t('DMSDocument.EMBARGO_INDEFINITELY', 'Hide document indefinitely'),
855
                'Date' => _t('DMSDocument.EMBARGO_DATE', 'Hide until set date')
856
            ),
857
            $embargoValue
858
        );
859
        $embargoDatetime = DatetimeField::create('EmbargoedUntilDate', '');
860
        $embargoDatetime->getDateField()
861
            ->setConfig('showcalendar', true)
862
            ->setConfig('dateformat', 'dd-MM-yyyy')
863
            ->setConfig('datavalueformat', 'dd-MM-yyyy');
864
865
        $expiryValue = 'None';
866
        if (!empty($this->ExpireAtDate)) {
867
            $expiryValue = 'Date';
868
        }
869
        $expiry = new OptionsetField(
870
            'Expiry',
871
            'Expiry',
872
            array(
873
                'None' => 'None',
874
                'Date' => 'Set document to expire on'
875
            ),
876
            $expiryValue
877
        );
878
        $expiryDatetime = DatetimeField::create('ExpireAtDate', '');
879
        $expiryDatetime->getDateField()
880
            ->setConfig('showcalendar', true)
881
            ->setConfig('dateformat', 'dd-MM-yyyy')
882
            ->setConfig('datavalueformat', 'dd-MM-yyyy');
883
884
        // This adds all the actions details into a group.
885
        // Embargo, History, etc to go in here
886
        // These are toggled on and off via the Actions Buttons above
887
        // exit('hit');
0 ignored issues
show
Unused Code Comprehensibility introduced by
84% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
888
        $actionsPanel = FieldGroup::create(
889
            FieldGroup::create($embargo, $embargoDatetime)->addExtraClass('embargo'),
890
            FieldGroup::create($expiry, $expiryDatetime)->addExtraClass('expiry'),
891
            FieldGroup::create($uploadField)->addExtraClass('replace'),
892
            FieldGroup::create($pagesGrid)->addExtraClass('find-usage'),
893
            FieldGroup::create($referencesGrid)->addExtraClass('find-references'),
894
            FieldGroup::create($versionsGrid)->addExtraClass('find-versions'),
0 ignored issues
show
Bug introduced by
The variable $versionsGrid does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
895
            FieldGroup::create($this->getRelatedDocumentsGridField())->addExtraClass('find-relateddocuments'),
896
            FieldGroup::create($this->getPermissionsActionPanel())->addExtraClass('permissions')
897
        );
898
899
        $actionsPanel->setName("ActionsPanel");
900
        $actionsPanel->addExtraClass("DMSDocumentActionsPanel");
901
        $fields->push($actionsPanel);
902
903
        $this->extend('updateCMSFields', $fields);
904
905
        return $fields;
906
    }
907
908
    /**
909
     * Adds permissions selection fields to a composite field and returns so it can be used in the "actions panel"
910
     *
911
     * @return CompositeField
912
     */
913
    public function getPermissionsActionPanel()
914
    {
915
        $fields = FieldList::create();
916
        $showFields = array(
917
            'CanViewType'  => '',
918
            'ViewerGroups' => 'hide',
919
            'CanEditType'  => '',
920
            'EditorGroups' => 'hide',
921
        );
922
        /** @var SiteTree $siteTree */
923
        $siteTree = singleton('SiteTree');
924
        $settingsFields = $siteTree->getSettingsFields();
925
926
        foreach ($showFields as $name => $extraCss) {
927
            $compositeName = "Root.Settings.$name";
928
            /** @var FormField $field */
929
            if ($field = $settingsFields->fieldByName($compositeName)) {
930
                $field->addExtraClass($extraCss);
931
                $title = str_replace('page', 'document', $field->Title());
932
                $field->setTitle($title);
933
934
                // Remove Inherited source option from DropdownField
935
                if ($field instanceof DropdownField) {
936
                    $options = $field->getSource();
937
                    unset($options['Inherit']);
938
                    $field->setSource($options);
939
                }
940
                $fields->push($field);
941
            }
942
        }
943
944
        $this->extend('updatePermissionsFields', $fields);
945
946
        return CompositeField::create($fields);
947
    }
948
949
    /**
950
     * Return a title to use on the frontend, preferably the "title", otherwise the filename without it's numeric ID
951
     *
952
     * @return string
953
     */
954
    public function getTitle()
955
    {
956
        if ($this->getField('Title')) {
957
            return $this->getField('Title');
958
        }
959
        return $this->FilenameWithoutID;
0 ignored issues
show
Bug introduced by
The property FilenameWithoutID does not seem to exist. Did you mean Filename?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
960
    }
961
962
    public function onBeforeWrite()
963
    {
964
        parent::onBeforeWrite();
965
966
        if (isset($this->Embargo)) {
967
            //set the embargo options from the OptionSetField created in the getCMSFields method
968
            //do not write after clearing the embargo (write happens automatically)
969
            $savedDate = $this->EmbargoedUntilDate;
970
            $this->clearEmbargo(false); // Clear all previous settings and re-apply them on save
971
972
            if ($this->Embargo == 'Published') {
0 ignored issues
show
Bug introduced by
The property Embargo does not seem to exist. Did you mean EmbargoedIndefinitely?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
973
                $this->embargoUntilPublished(false);
974
            }
975
            if ($this->Embargo == 'Indefinitely') {
0 ignored issues
show
Bug introduced by
The property Embargo does not seem to exist. Did you mean EmbargoedIndefinitely?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
976
                $this->embargoIndefinitely(false);
977
            }
978
            if ($this->Embargo == 'Date') {
0 ignored issues
show
Bug introduced by
The property Embargo does not seem to exist. Did you mean EmbargoedIndefinitely?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
979
                $this->embargoUntilDate($savedDate, false);
0 ignored issues
show
Documentation introduced by
$savedDate is of type object<DateTime>|null, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
980
            }
981
        }
982
983
        if (isset($this->Expiry)) {
984
            if ($this->Expiry == 'Date') {
0 ignored issues
show
Documentation introduced by
The property Expiry does not exist on object<DMSDocument>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
985
                $this->expireAtDate($this->ExpireAtDate, false);
0 ignored issues
show
Documentation introduced by
$this->ExpireAtDate is of type object<DateTime>|null, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
986
            } else {
987
                $this->clearExpiry(false);
988
            } // Clear all previous settings
989
        }
990
991
        // Set user fields
992
        if ($currentUserID = Member::currentUserID()) {
993
            if (!$this->CreatedByID) {
994
                $this->CreatedByID = $currentUserID;
995
            }
996
            $this->LastEditedByID = $currentUserID;
997
        }
998
    }
999
1000
    /**
1001
     * Return the relative URL of an icon for the file type, based on the
1002
     * {@link appCategory()} value.
1003
     *
1004
     * Images are searched for in "dms/images/app_icons/".
1005
     *
1006
     * @return string
1007
     */
1008
    public function Icon($ext)
1009
    {
1010
        if (!Director::fileExists(DMS_DIR."/images/app_icons/{$ext}_32.png")) {
1011
            $ext = File::get_app_category($ext);
1012
        }
1013
1014
        if (!Director::fileExists(DMS_DIR."/images/app_icons/{$ext}_32.png")) {
1015
            $ext = "generic";
1016
        }
1017
1018
        return DMS_DIR."/images/app_icons/{$ext}_32.png";
1019
    }
1020
1021
    /**
1022
     * Return the extension of the file associated with the document
1023
     *
1024
     * @return string
1025
     */
1026
    public function getExtension()
1027
    {
1028
        return strtolower(pathinfo($this->Filename, PATHINFO_EXTENSION));
1029
    }
1030
1031
    /**
1032
     * @return string
0 ignored issues
show
Documentation introduced by
Should the return type not be string|false?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
1033
     */
1034
    public function getSize()
1035
    {
1036
        $size = $this->getAbsoluteSize();
1037
        return ($size) ? File::format_size($size) : false;
1038
    }
1039
1040
    /**
1041
     * Return the size of the file associated with the document.
1042
     *
1043
     * @return string
0 ignored issues
show
Documentation introduced by
Should the return type not be integer|null?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
1044
     */
1045
    public function getAbsoluteSize()
1046
    {
1047
        return file_exists($this->getFullPath()) ? filesize($this->getFullPath()) : null;
1048
    }
1049
1050
    /**
1051
     * An alias to DMSDocument::getSize()
1052
     *
1053
     * @return string
0 ignored issues
show
Documentation introduced by
Should the return type not be string|false?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
1054
     */
1055
    public function getFileSizeFormatted()
1056
    {
1057
        return $this->getSize();
1058
    }
1059
1060
1061
    /**
1062
     * @return FieldList
0 ignored issues
show
Documentation introduced by
Should the return type not be FieldGroup?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
1063
     */
1064
    protected function getFieldsForFile($relationListCount)
1065
    {
1066
        $extension = $this->getExtension();
1067
1068
        $previewField = new LiteralField(
1069
            "ImageFull",
1070
            "<img id='thumbnailImage' class='thumbnail-preview' src='{$this->Icon($extension)}?r="
1071
            . rand(1, 100000) . "' alt='{$this->Title}' />\n"
1072
        );
1073
1074
        //count the number of pages this document is published on
1075
        $publishedOnCount = $this->getRelatedPages()->count();
1076
        $publishedOnValue = "$publishedOnCount pages";
1077
        if ($publishedOnCount == 1) {
1078
            $publishedOnValue = "$publishedOnCount page";
1079
        }
1080
1081
        $relationListCountValue = "$relationListCount pages";
1082
        if ($relationListCount == 1) {
1083
            $relationListCountValue = "$relationListCount page";
1084
        }
1085
1086
        $fields = new FieldGroup(
1087
            $filePreview = CompositeField::create(
1088
                CompositeField::create(
1089
                    $previewField
1090
                )->setName("FilePreviewImage")->addExtraClass('cms-file-info-preview'),
1091
                CompositeField::create(
1092
                    CompositeField::create(
1093
                        new ReadonlyField("ID", "ID number". ':', $this->ID),
1094
                        new ReadonlyField(
1095
                            "FileType",
1096
                            _t('AssetTableField.TYPE', 'File type') . ':',
1097
                            self::get_file_type($extension)
1098
                        ),
1099
                        new ReadonlyField(
1100
                            "Size",
1101
                            _t('AssetTableField.SIZE', 'File size') . ':',
1102
                            $this->getFileSizeFormatted()
1103
                        ),
1104
                        $urlField = new ReadonlyField(
1105
                            'ClickableURL',
1106
                            _t('AssetTableField.URL', 'URL'),
1107
                            sprintf(
1108
                                '<a href="%s" target="_blank" class="file-url">%s</a>',
1109
                                $this->getLink(),
1110
                                $this->getLink()
1111
                            )
1112
                        ),
1113
                        new ReadonlyField("FilenameWithoutIDField", "Filename". ':', $this->getFilenameWithoutID()),
1114
                        new DateField_Disabled(
1115
                            "Created",
1116
                            _t('AssetTableField.CREATED', 'First uploaded') . ':',
1117
                            $this->Created
1118
                        ),
1119
                        new DateField_Disabled(
1120
                            "LastEdited",
1121
                            _t('AssetTableField.LASTEDIT', 'Last changed') . ':',
1122
                            $this->LastEdited
1123
                        ),
1124
                        new ReadonlyField("PublishedOn", "Published on". ':', $publishedOnValue),
1125
                        new ReadonlyField("ReferencedOn", "Referenced on". ':', $relationListCountValue),
1126
                        new ReadonlyField("ViewCount", "View count". ':', $this->ViewCount)
1127
                    )
1128
                )->setName("FilePreviewData")->addExtraClass('cms-file-info-data')
1129
            )->setName("FilePreview")->addExtraClass('cms-file-info')
1130
        );
1131
1132
        $fields->setName('FileP');
1133
        $urlField->dontEscape = true;
1134
1135
        return $fields;
1136
    }
1137
1138
    /**
1139
     * Takes a file and adds it to the DMSDocument storage, replacing the
1140
     * current file.
1141
     *
1142
     * @param File $file
1143
     *
1144
     * @return $this
1145
     */
1146
    public function ingestFile($file)
1147
    {
1148
        $this->replaceDocument($file);
1149
        $file->delete();
1150
1151
        return $this;
1152
    }
1153
1154
    /**
1155
     * Get a data list of documents related to this document
1156
     *
1157
     * @return DataList
1158
     */
1159
    public function getRelatedDocuments()
1160
    {
1161
        $documents = $this->RelatedDocuments();
0 ignored issues
show
Bug introduced by
The method RelatedDocuments() does not exist on DMSDocument. Did you maybe mean getRelatedDocuments()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
1162
1163
        $this->extend('updateRelatedDocuments', $documents);
1164
1165
        return $documents;
1166
    }
1167
1168
    /**
1169
     * Get a list of related pages for this document by going through the associated document sets
1170
     *
1171
     * @return ArrayList
1172
     */
1173
    public function getRelatedPages()
1174
    {
1175
        $pages = ArrayList::create();
1176
1177
        foreach ($this->Sets() as $documentSet) {
0 ignored issues
show
Documentation Bug introduced by
The method Sets does not exist on object<DMSDocument>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
1178
            /** @var DocumentSet $documentSet */
1179
            $pages->add($documentSet->Page());
1180
        }
1181
        $pages->removeDuplicates();
1182
1183
        $this->extend('updateRelatedPages', $pages);
1184
1185
        return $pages;
1186
    }
1187
1188
    /**
1189
     * Get a GridField for managing related documents
1190
     *
1191
     * @return GridField
1192
     */
1193
    protected function getRelatedDocumentsGridField()
1194
    {
1195
        $gridField = GridField::create(
1196
            'RelatedDocuments',
1197
            _t('DMSDocument.RELATEDDOCUMENTS', 'Related Documents'),
1198
            $this->RelatedDocuments(),
0 ignored issues
show
Bug introduced by
The method RelatedDocuments() does not exist on DMSDocument. Did you maybe mean getRelatedDocuments()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
1199
            new GridFieldConfig_RelationEditor
1200
        );
1201
1202
        $gridField->getConfig()->removeComponentsByType('GridFieldAddNewButton');
1203
        // Move the autocompleter to the left
1204
        $gridField->getConfig()->removeComponentsByType('GridFieldAddExistingAutocompleter');
1205
        $gridField->getConfig()->addComponent(
1206
            $addExisting = new GridFieldAddExistingAutocompleter('buttons-before-left')
1207
        );
1208
1209
        // Ensure that current document doesn't get returned in the autocompleter
1210
        $addExisting->setSearchList($this->getRelatedDocumentsForAutocompleter());
1211
1212
        // Restrict search fields to specific fields only
1213
        $addExisting->setSearchFields(array('Title', 'Filename'));
1214
1215
        $this->extend('updateRelatedDocumentsGridField', $gridField);
1216
1217
        return $gridField;
1218
    }
1219
1220
    /**
1221
     * Get the list of documents to show in "related documents". This can be modified via the extension point, for
1222
     * example if you wanted to exclude embargoed documents or something similar.
1223
     *
1224
     * @return DataList
1225
     */
1226
    protected function getRelatedDocumentsForAutocompleter()
1227
    {
1228
        $documents = DMSDocument::get()->exclude('ID', $this->ID);
1229
        $this->extend('updateRelatedDocumentsForAutocompleter', $documents);
1230
        return $documents;
1231
    }
1232
1233
    /**
1234
     * Checks at least one group is selected if CanViewType || CanEditType == 'OnlyTheseUsers'
1235
     *
1236
     * @return ValidationResult
1237
     */
1238
    protected function validate()
1239
    {
1240
        $valid = parent::validate();
1241
1242
        if ($this->CanViewType == 'OnlyTheseUsers' && !$this->ViewerGroups()->count()) {
0 ignored issues
show
Documentation Bug introduced by
The method ViewerGroups does not exist on object<DMSDocument>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
1243
            $valid->error(
1244
                _t(
1245
                    'DMSDocument.VALIDATIONERROR_NOVIEWERSELECTED',
1246
                    "Selecting 'Only these people' from a viewers list needs at least one group selected."
1247
                )
1248
            );
1249
        }
1250
1251
        if ($this->CanEditType == 'OnlyTheseUsers' && !$this->EditorGroups()->count()) {
0 ignored issues
show
Documentation Bug introduced by
The method EditorGroups does not exist on object<DMSDocument>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
1252
            $valid->error(
1253
                _t(
1254
                    'DMSDocument.VALIDATIONERROR_NOEDITORSELECTED',
1255
                    "Selecting 'Only these people' from a editors list needs at least one group selected."
1256
                )
1257
            );
1258
        }
1259
1260
        return $valid;
1261
    }
1262
1263
    /**
1264
     * Returns a reason as to why this document cannot be viewed.
1265
     *
1266
     * @return string
1267
     */
1268
    public function getPermissionDeniedReason()
1269
    {
1270
        $result = '';
1271
1272
        if ($this->CanViewType == 'LoggedInUsers') {
1273
            $result = _t('DMSDocument.PERMISSIONDENIEDREASON_LOGINREQUIRED', 'Please log in to view this document');
1274
        }
1275
1276
        if ($this->CanViewType == 'OnlyTheseUsers') {
1277
            $result = _t(
1278
                'DMSDocument.PERMISSIONDENIEDREASON_NOTAUTHORISED',
1279
                'You are not authorised to view this document'
1280
            );
1281
        }
1282
1283
        return $result;
1284
    }
1285
1286
    /**
1287
     * Add an "action panel" task
1288
     *
1289
     * @param  string $panelKey
1290
     * @param  string $title
1291
     * @return $this
1292
     */
1293
    public function addActionPanelTask($panelKey, $title)
1294
    {
1295
        $this->actionTasks[$panelKey] = $title;
1296
        return $this;
1297
    }
1298
1299
    /**
1300
     * Returns a HTML representation of the action tasks for the CMS
1301
     *
1302
     * @return string
1303
     */
1304
    public function getActionTaskHtml()
1305
    {
1306
        $html = '<div id="Actions" class="field actions">'
1307
            . '<label class="left">' . _t('DMSDocument.ACTIONS_LABEL', 'Actions') . '</label>'
1308
            . '<ul>';
1309
1310
        foreach ($this->actionTasks as $panelKey => $title) {
1311
            $html .= '<li class="ss-ui-button" data-panel="' . $panelKey . '">'
1312
                . _t('DMSDocument.ACTION_' . strtoupper($panelKey), $title)
1313
                . '</li>';
1314
        }
1315
1316
        $html .= '</ul></div>';
1317
1318
        return $html;
1319
    }
1320
}
1321