Completed
Pull Request — master (#110)
by Franco
02:08
created

DMSDocument::validate()   B

Complexity

Conditions 5
Paths 4

Size

Total Lines 24
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 24
rs 8.5125
c 0
b 0
f 0
cc 5
eloc 13
nc 4
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 DateTime LastChanged
12
 * @property Boolean EmbargoedIndefinitely
13
 * @property Boolean EmbargoedUntilPublished
14
 * @property DateTime EmbargoedUntilDate
15
 * @property DateTime ExpireAtDate
16
 * @property Enum DownloadBehavior
17
 * @property Enum CanViewType Enum('Anyone, LoggedInUsers, OnlyTheseUsers', 'Anyone')
18
 * @property Enum CanEditType Enum('LoggedInUsers, OnlyTheseUsers', 'LoggedInUsers')
19
 *
20
 * @method ManyManyList RelatedDocuments
21
 * @method ManyManyList Tags
22
 * @method ManyManyList ViewerGroups
23
 * @method ManyManyList EditorGroups
24
 *
25
 */
26
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...
27
{
28
    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...
29
        "Filename" => "Varchar(255)", // eg. 3469~2011-energysaving-report.pdf
30
        "Folder" => "Varchar(255)",    // eg.	0
31
        "Title" => 'Varchar(1024)', // eg. "Energy Saving Report for Year 2011, New Zealand LandCorp"
32
        "Description" => 'Text',
33
        "ViewCount" => 'Int',
34
        // When this document's file was created or last replaced (small changes like updating title don't count)
35
        "LastChanged" => 'SS_DateTime',
36
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 $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...
47
        'Pages' => 'SiteTree',
48
        'RelatedDocuments' => 'DMSDocument',
49
        'Tags' => 'DMSTag',
50
        'ViewerGroups' => 'Group',
51
        'EditorGroups' => 'Group',
52
    );
53
54
    private static $many_many_extraFields = 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_extraFields 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...
55
        'Pages' => array(
56
            'DocumentSort' => 'Int'
57
        )
58
    );
59
60
    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...
61
        'ID' => 'ID',
62
        'Title' => 'Title',
63
        'FilenameWithoutID' => 'Filename',
64
        'LastChanged' => 'LastChanged'
65
    );
66
67
    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...
68
69
    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...
70
71
    private static $searchable_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 $searchable_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...
72
        'ID' => array(
73
            'filter' => 'ExactMatchFilter',
74
            'field' => 'NumericField'
75
        ),
76
        'Title',
77
        'Filename',
78
        'LastChanged'
79
    );
80
81
    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...
82
        'Filename' => 'Filename',
83
        'Title' => 'Title',
84
        'ViewCount' => 'ViewCount',
85
        'getPages.count' => 'Page Use'
86
    );
87
88
    /**
89
     * @var string download|open
90
     * @config
91
     */
92
    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...
93
94
    public function canView($member = null)
95
    {
96
        if (!$member || !(is_a($member, 'Member')) || is_numeric($member)) {
97
            $member = Member::currentUser();
98
        }
99
100
        if (!$this->CanViewType || $this->CanViewType == 'Anyone') {
101
            return true;
102
        }
103
104 View Code Duplication
        if ($member && Permission::checkMember($member,
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...
105
                array(
106
                    'ADMIN',
107
                    'SITETREE_EDIT_ALL',
108
                    'SITETREE_VIEW_ALL',
109
                )
110
            )
111
        ) {
112
            return true;
113
        }
114
115
        if ($this->isHidden()) {
116
            return false;
117
        }
118
119
        if ($this->CanViewType == 'LoggedInUsers') {
120
            return $member && $member->exists();
121
        }
122
123
        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...
124
            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...
125
        }
126
127
        // extended access checks
128
        $results = $this->extend('canView', $member);
129
130
        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...
131
            if (!min($results)) {
132
                return false;
133
            }
134
        }
135
136
        if ($member && $member->ID) {
137
            return true;
138
        }
139
140
        return $this->canEdit($member);
141
    }
142
143
    public function canEdit($member = null)
144
    {
145
        if (!$member || !(is_a($member, 'Member')) || is_numeric($member)) {
146
            $member = Member::currentUser();
147
        }
148
149
        // Do early admin check
150 View Code Duplication
        if ($member && Permission::checkMember($member,
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...
151
                array(
152
                    'ADMIN',
153
                    'SITETREE_EDIT_ALL',
154
                    'SITETREE_VIEW_ALL',
155
                )
156
            )
157
        ) {
158
            return true;
159
        }
160
161
        if ($this->CanEditType === 'LoggedInUsers') {
162
            return $member && $member->exists();
163
        }
164
165
        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...
166
            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...
167
        }
168
169
        return ($member && Permission::checkMember($member, array('ADMIN', 'SITETREE_EDIT_ALL')));
170
    }
171
172
    /**
173
     * @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...
174
     *
175
     * @return boolean
176
     */
177
    public function canCreate($member = null)
178
    {
179
        $results = $this->extend('canCreate', $member);
180
181
        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...
182
            if (!min($results)) {
183
                return false;
184
            }
185
        }
186
187
        return $this->canEdit($member);
188
    }
189
190
    /**
191
     * @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...
192
     *
193
     * @return boolean
194
     */
195
    public function canDelete($member = null)
196
    {
197
        if (!$member || !(is_a($member, 'Member')) || is_numeric($member)) {
198
            $member = Member::currentUser();
199
        }
200
201
        $results = $this->extend('canDelete', $member);
202
203
        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...
204
            if (!min($results)) {
205
                return false;
206
            }
207
        }
208
209
        return $this->canView();
210
    }
211
212
213
214
    /**
215
     * Associates this document with a Page. This method does nothing if the
216
     * association already exists.
217
     *
218
     * This could be a simple wrapper around $myDoc->Pages()->add($myPage) to
219
     * add a many_many relation.
220
     *
221
     * @param SiteTree $pageObject Page object to associate this Document with
222
     *
223
     * @return DMSDocument
224
     */
225
    public function addPage($pageObject)
226
    {
227
        $this->Pages()->add($pageObject);
228
229
        DB::query(
230
            "UPDATE \"DMSDocument_Pages\" SET \"DocumentSort\"=\"DocumentSort\"+1"
231
            . " WHERE \"SiteTreeID\" = $pageObject->ID"
232
        );
233
234
        return $this;
235
    }
236
237
    /**
238
     * Associates this DMSDocument with a set of Pages. This method loops
239
     * through a set of page ids, and then associates this DMSDocument with the
240
     * individual Page with the each page id in the set.
241
     *
242
     * @param array $pageIDs
243
     *
244
     * @return DMSDocument
245
     */
246
    public function addPages($pageIDs)
247
    {
248
        foreach ($pageIDs as $id) {
249
            $pageObject = DataObject::get_by_id("SiteTree", $id);
250
251
            if ($pageObject && $pageObject->exists()) {
252
                $this->addPage($pageObject);
0 ignored issues
show
Compatibility introduced by
$pageObject of type object<DataObject> is not a sub-type of object<SiteTree>. It seems like you assume a child class of the class DataObject to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
253
            }
254
        }
255
256
        return $this;
257
    }
258
259
    /**
260
     * Removes the association between this Document and a Page. This method
261
     * does nothing if the association does not exist.
262
     *
263
     * @param SiteTree $pageObject Page object to remove the association to
264
     *
265
     * @return DMSDocument
266
     */
267
    public function removePage($pageObject)
268
    {
269
        $this->Pages()->remove($pageObject);
0 ignored issues
show
Documentation introduced by
$pageObject is of type object<SiteTree>, but the function expects a object<DataClass>.

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...
270
271
        return $this;
272
    }
273
274
    /**
275
     * @see getPages()
276
     *
277
     * @return DataList
278
     */
279
    public function Pages()
280
    {
281
        $pages = $this->getManyManyComponents('Pages');
282
        $this->extend('updatePages', $pages);
283
284
        return $pages;
285
    }
286
287
    /**
288
     * Returns a list of the Page objects associated with this Document.
289
     *
290
     * @return DataList
291
     */
292
    public function getPages()
293
    {
294
        return $this->Pages();
295
    }
296
297
    /**
298
     * Removes all associated Pages from the DMSDocument
299
     *
300
     * @return DMSDocument
301
     */
302
    public function removeAllPages()
303
    {
304
        $this->Pages()->removeAll();
305
306
        return $this;
307
    }
308
309
    /**
310
     * Increase ViewCount by 1, without update any other record fields such as
311
     * LastEdited.
312
     *
313
     * @return DMSDocument
314
     */
315
    public function trackView()
316
    {
317
        if ($this->ID > 0) {
318
            $count = $this->ViewCount + 1;
319
320
            $this->ViewCount = $count;
321
322
            DB::query("UPDATE \"DMSDocument\" SET \"ViewCount\"='$count' WHERE \"ID\"={$this->ID}");
323
        }
324
325
        return $this;
326
    }
327
328
329
    /**
330
     * Adds a metadata tag to the Document. The tag has a category and a value.
331
     *
332
     * Each category can have multiple values by default. So:
333
     * addTag("fruit","banana") addTag("fruit", "apple") will add two items.
334
     *
335
     * However, if the third parameter $multiValue is set to 'false', then all
336
     * updates to a category only ever update a single value. So:
337
     * addTag("fruit","banana") addTag("fruit", "apple") would result in a
338
     * single metadata tag: fruit->apple.
339
     *
340
     * Can could be implemented as a key/value store table (although it is more
341
     * like category/value, because the same category can occur multiple times)
342
     *
343
     * @param string $category of a metadata category to add (required)
344
     * @param string $value of a metadata value to add (required)
345
     * @param bool $multiValue Boolean that determines if the category is
346
     *                  multi-value or single-value (optional)
347
     *
348
     * @return DMSDocument
349
     */
350
    public function addTag($category, $value, $multiValue = true)
351
    {
352
        if ($multiValue) {
353
            //check for a duplicate tag, don't add the duplicate
354
            $currentTag = $this->Tags()->filter(array('Category' => $category, 'Value' => $value));
0 ignored issues
show
Documentation Bug introduced by
The method Tags 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...
355
            if ($currentTag->Count() == 0) {
356
                //multi value tag
357
                $tag = new DMSTag();
358
                $tag->Category = $category;
0 ignored issues
show
Documentation introduced by
The property Category does not exist on object<DMSTag>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write 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.");
        }
    }

}

Since the property has write access only, you can use the @property-write 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...
359
                $tag->Value = $value;
0 ignored issues
show
Documentation introduced by
The property Value does not exist on object<DMSTag>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write 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.");
        }
    }

}

Since the property has write access only, you can use the @property-write 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...
360
                $tag->MultiValue = true;
0 ignored issues
show
Documentation introduced by
The property MultiValue does not exist on object<DMSTag>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write 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.");
        }
    }

}

Since the property has write access only, you can use the @property-write 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...
361
                $tag->write();
362
                $tag->Documents()->add($this);
0 ignored issues
show
Documentation Bug introduced by
The method Documents does not exist on object<DMSTag>? 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...
363
            } else {
364
                //add the relation between the tag and document
365
                foreach ($currentTag as $tagObj) {
366
                    $tagObj->Documents()->add($this);
367
                }
368
            }
369
        } else {
370
            //single value tag
371
            $currentTag = $this->Tags()->filter(array('Category' => $category));
0 ignored issues
show
Documentation Bug introduced by
The method Tags 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...
372
            $tag = null;
0 ignored issues
show
Unused Code introduced by
$tag 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...
373
            if ($currentTag->Count() == 0) {
374
                //create the single-value tag
375
                $tag = new DMSTag();
376
                $tag->Category = $category;
0 ignored issues
show
Documentation introduced by
The property Category does not exist on object<DMSTag>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write 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.");
        }
    }

}

Since the property has write access only, you can use the @property-write 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...
377
                $tag->Value = $value;
0 ignored issues
show
Documentation introduced by
The property Value does not exist on object<DMSTag>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write 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.");
        }
    }

}

Since the property has write access only, you can use the @property-write 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...
378
                $tag->MultiValue = false;
0 ignored issues
show
Documentation introduced by
The property MultiValue does not exist on object<DMSTag>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write 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.");
        }
    }

}

Since the property has write access only, you can use the @property-write 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...
379
                $tag->write();
380
            } else {
381
                //update the single value tag
382
                $tag = $currentTag->first();
383
                $tag->Value = $value;
384
                $tag->MultiValue = false;
385
                $tag->write();
386
            }
387
388
            // regardless of whether we created a new tag or are just updating an
389
            // existing one, add the relation
390
            $tag->Documents()->add($this);
391
        }
392
393
        return $this;
394
    }
395
396
    /**
397
     * @param string $category
398
     * @param string $value
0 ignored issues
show
Documentation introduced by
Should the type for parameter $value not be string|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...
399
     *
400
     * @return DataList
401
     */
402
    protected function getTagsObjects($category, $value = null)
403
    {
404
        $valueFilter = array("Category" => $category);
405
        if (!empty($value)) {
406
            $valueFilter['Value'] = $value;
407
        }
408
409
        $tags = $this->Tags()->filter($valueFilter);
0 ignored issues
show
Documentation Bug introduced by
The method Tags 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...
410
        return $tags;
411
    }
412
413
    /**
414
     * Fetches all tags associated with this DMSDocument within a given
415
     * category. If a value is specified this method tries to fetch that
416
     * specific tag.
417
     *
418
     * @param string $category metadata category to get
419
     * @param string $value value of the tag to get
0 ignored issues
show
Documentation introduced by
Should the type for parameter $value not be string|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...
420
     *
421
     * @return array Strings of all the tags or null if there is no match found
0 ignored issues
show
Documentation introduced by
Should the return type not be array|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...
422
     */
423
    public function getTagsList($category, $value = null)
424
    {
425
        $tags = $this->getTagsObjects($category, $value);
426
427
        $returnArray = null;
428
429
        if ($tags->Count() > 0) {
430
            $returnArray = array();
431
432
            foreach ($tags as $t) {
433
                $returnArray[] = $t->Value;
434
            }
435
        }
436
437
        return $returnArray;
438
    }
439
440
    /**
441
     * Removes a tag from the Document. If you only set a category, then all
442
     * values in that category are deleted.
443
     *
444
     * If you specify both a category and a value, then only that single
445
     * category/value pair is deleted.
446
     *
447
     * Nothing happens if the category or the value do not exist.
448
     *
449
     * @param string $category Category to remove
450
     * @param string $value Value to remove
0 ignored issues
show
Documentation introduced by
Should the type for parameter $value not be string|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...
451
     *
452
     * @return DMSDocument
453
     */
454
    public function removeTag($category, $value = null)
455
    {
456
        $tags = $this->getTagsObjects($category, $value);
457
458
        if ($tags->Count() > 0) {
459
            foreach ($tags as $t) {
460
                $documentList = $t->Documents();
461
462
                //remove the relation between the tag and the document
463
                $documentList->remove($this);
464
465
                //delete the entire tag if it has no relations left
466
                if ($documentList->Count() == 0) {
467
                    $t->delete();
468
                }
469
            }
470
        }
471
472
        return $this;
473
    }
474
475
    /**
476
     * Deletes all tags associated with this Document.
477
     *
478
     * @return DMSDocument
479
     */
480
    public function removeAllTags()
481
    {
482
        $allTags = $this->Tags();
0 ignored issues
show
Documentation Bug introduced by
The method Tags 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...
483
484
        foreach ($allTags as $tag) {
485
            $documentlist = $tag->Documents();
486
            $documentlist->remove($this);
487
            if ($tag->Documents()->Count() == 0) {
488
                $tag->delete();
489
            }
490
        }
491
492
        return $this;
493
    }
494
495
    /**
496
     * Returns a link to download this document from the DMS store.
497
     * Alternatively a basic javascript alert will be shown should the user not have view permissions. An extension
498
     * point for this was also added.
499
     *
500
     * To extend use the following from within an Extension subclass:
501
     *
502
     * <code>
503
     * public function updateGetLink($result){
504
     *  // Do something here
505
     * }
506
     * </code>
507
     *
508
     * @return string
509
     */
510
    public function getLink()
511
    {
512
        $result = Controller::join_links(Director::baseURL(), 'dmsdocument/' . $this->ID);
513
        if (!$this->canView()) {
514
            $result = sprintf("javascript:alert('%s')", $this->getPermissionDeniedReason());
515
        }
516
517
        $this->extend('updateGetLink', $result);
518
519
        return $result;
520
    }
521
522
    /**
523
     * @return string
524
     */
525
    public function Link()
526
    {
527
        return $this->getLink();
528
    }
529
530
    /**
531
     * Hides the document, so it does not show up when getByPage($myPage) is
532
     * called (without specifying the $showEmbargoed = true parameter).
533
     *
534
     * This is similar to expire, except that this method should be used to hide
535
     * documents that have not yet gone live.
536
     *
537
     * @param bool $write Save change to the database
538
     *
539
     * @return DMSDocument
540
     */
541
    public function embargoIndefinitely($write = true)
542
    {
543
        $this->EmbargoedIndefinitely = true;
544
545
        if ($write) {
546
            $this->write();
547
        }
548
549
        return $this;
550
    }
551
552
    /**
553
     * Hides the document until any page it is linked to is published
554
     *
555
     * @param bool $write Save change to database
556
     *
557
     * @return DMSDocument
558
     */
559
    public function embargoUntilPublished($write = true)
560
    {
561
        $this->EmbargoedUntilPublished = true;
562
563
        if ($write) {
564
            $this->write();
565
        }
566
567
        return $this;
568
    }
569
570
    /**
571
     * Returns if this is Document is embargoed or expired.
572
     *
573
     * Also, returns if the document should be displayed on the front-end,
574
     * respecting the current reading mode of the site and the embargo status.
575
     *
576
     * I.e. if a document is embargoed until published, then it should still
577
     * show up in draft mode.
578
     *
579
     * @return bool
580
     */
581
    public function isHidden()
582
    {
583
        $hidden = $this->isEmbargoed() || $this->isExpired();
584
        $readingMode = Versioned::get_reading_mode();
585
586
        if ($readingMode == "Stage.Stage") {
587
            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...
588
                $hidden = false;
589
            }
590
        }
591
592
        return $hidden;
593
    }
594
595
    /**
596
     * Returns if this is Document is embargoed.
597
     *
598
     * @return bool
599
     */
600
    public function isEmbargoed()
601
    {
602
        if (is_object($this->EmbargoedUntilDate)) {
603
            $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...
604
        }
605
606
        $embargoed = false;
607
608
        if ($this->EmbargoedIndefinitely) {
609
            $embargoed = true;
610
        } elseif ($this->EmbargoedUntilPublished) {
611
            $embargoed = true;
612
        } elseif (!empty($this->EmbargoedUntilDate)) {
613
            if (SS_Datetime::now()->Value < $this->EmbargoedUntilDate) {
614
                $embargoed = true;
615
            }
616
        }
617
618
        return $embargoed;
619
    }
620
621
    /**
622
     * Hides the document, so it does not show up when getByPage($myPage) is
623
     * called. Automatically un-hides the Document at a specific date.
624
     *
625
     * @param string $datetime date time value when this Document should expire.
626
     * @param bool $write
627
     *
628
     * @return DMSDocument
629
     */
630 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...
631
    {
632
        $this->EmbargoedUntilDate = DBField::create_field('SS_Datetime', $datetime)->Format('Y-m-d H:i:s');
633
634
        if ($write) {
635
            $this->write();
636
        }
637
638
        return $this;
639
    }
640
641
    /**
642
     * Clears any previously set embargos, so the Document always shows up in
643
     * all queries.
644
     *
645
     * @param bool $write
646
     *
647
     * @return DMSDocument
648
     */
649
    public function clearEmbargo($write = true)
650
    {
651
        $this->EmbargoedIndefinitely = false;
652
        $this->EmbargoedUntilPublished = false;
653
        $this->EmbargoedUntilDate = null;
654
655
        if ($write) {
656
            $this->write();
657
        }
658
659
        return $this;
660
    }
661
662
    /**
663
     * Returns if this is Document is expired.
664
     *
665
     * @return bool
666
     */
667
    public function isExpired()
668
    {
669
        if (is_object($this->ExpireAtDate)) {
670
            $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...
671
        }
672
673
        $expired = false;
674
675
        if (!empty($this->ExpireAtDate)) {
676
            if (SS_Datetime::now()->Value >= $this->ExpireAtDate) {
677
                $expired = true;
678
            }
679
        }
680
681
        return $expired;
682
    }
683
684
    /**
685
     * Hides the document at a specific date, so it does not show up when
686
     * getByPage($myPage) is called.
687
     *
688
     * @param string $datetime date time value when this Document should expire
689
     * @param bool $write
690
     *
691
     * @return DMSDocument
692
     */
693 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...
694
    {
695
        $this->ExpireAtDate = DBField::create_field('SS_Datetime', $datetime)->Format('Y-m-d H:i:s');
696
697
        if ($write) {
698
            $this->write();
699
        }
700
701
        return $this;
702
    }
703
704
    /**
705
     * Clears any previously set expiry.
706
     *
707
     * @param bool $write
708
     *
709
     * @return DMSDocument
710
     */
711
    public function clearExpiry($write = true)
712
    {
713
        $this->ExpireAtDate = null;
714
715
        if ($write) {
716
            $this->write();
717
        }
718
719
        return $this;
720
    }
721
722
    /**
723
     * Returns a DataList of all previous Versions of this document (check the
724
     * LastEdited date of each object to find the correct one).
725
     *
726
     * If {@link DMSDocument_versions::$enable_versions} is disabled then an
727
     * Exception is thrown
728
     *
729
     * @throws Exception
730
     *
731
     * @return DataList List of Document objects
732
     */
733
    public function getVersions()
734
    {
735
        if (!DMSDocument_versions::$enable_versions) {
736
            throw new Exception("DMSDocument versions are disabled");
737
        }
738
739
        return DMSDocument_versions::get_versions($this);
740
    }
741
742
    /**
743
     * Returns the full filename of the document stored in this object.
744
     *
745
     * @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...
746
     */
747
    public function getFullPath()
748
    {
749
        if ($this->Filename) {
750
            return DMS::get_dms_path() . DIRECTORY_SEPARATOR . $this->Folder . DIRECTORY_SEPARATOR . $this->Filename;
751
        }
752
753
        return null;
754
    }
755
756
    /**
757
     * Returns the filename of this asset.
758
     *
759
     * @return string
760
     */
761
    public function getFileName()
762
    {
763
        if ($this->getField('Filename')) {
764
            return $this->getField('Filename');
765
        } else {
766
            return ASSETS_DIR . '/';
767
        }
768
    }
769
770
    /**
771
     * @return string
772
     */
773
    public function getName()
774
    {
775
        return $this->getField('Title');
776
    }
777
778
779
    /**
780
     * @return string
781
     */
782
    public function getFilenameWithoutID()
783
    {
784
        $filenameParts = explode('~', $this->Filename);
785
        $filename = array_pop($filenameParts);
786
787
        return $filename;
788
    }
789
790
    /**
791
     * @return string
792
     */
793
    public function getStorageFolder()
794
    {
795
        return DMS::get_dms_path() . DIRECTORY_SEPARATOR . DMS::get_storage_folder($this->ID);
796
    }
797
798
    /**
799
     * Deletes the DMSDocument, its underlying file, as well as any tags related
800
     * to this DMSDocument. Also calls the parent DataObject's delete method in
801
     * order to complete an cascade.
802
     *
803
     * @return void
804
     */
805
    public function delete()
806
    {
807
        // remove tags
808
        $this->removeAllTags();
809
810
        // delete the file (and previous versions of files)
811
        $filesToDelete = array();
812
        $storageFolder = $this->getStorageFolder();
813
814
        if (file_exists($storageFolder)) {
815
            if ($handle = opendir($storageFolder)) {
816
                while (false !== ($entry = readdir($handle))) {
817
                    // only delete if filename starts the the relevant ID
818
                    if (strpos($entry, $this->ID.'~') === 0) {
819
                        $filesToDelete[] = $entry;
820
                    }
821
                }
822
823
                closedir($handle);
824
825
                //delete all this files that have the id of this document
826
                foreach ($filesToDelete as $file) {
827
                    $filePath = $storageFolder .DIRECTORY_SEPARATOR . $file;
828
829
                    if (is_file($filePath)) {
830
                        unlink($filePath);
831
                    }
832
                }
833
            }
834
        }
835
836
        $this->removeAllPages();
837
838
        // get rid of any versions have saved for this DMSDocument, too
839
        if (DMSDocument_versions::$enable_versions) {
840
            $versions = $this->getVersions();
841
842
            if ($versions->Count() > 0) {
843
                foreach ($versions as $v) {
844
                    $v->delete();
845
                }
846
            }
847
        }
848
849
        parent::delete();
850
    }
851
852
853
854
    /**
855
     * Relate an existing file on the filesystem to the document.
856
     *
857
     * Copies the file to the new destination, as defined in {@link get_DMS_path()}.
858
     *
859
     * @param string $filePath Path to file, relative to webroot.
860
     *
861
     * @return DMSDocument
862
     */
863
    public function storeDocument($filePath)
864
    {
865
        if (empty($this->ID)) {
866
            user_error("Document must be written to database before it can store documents", E_USER_ERROR);
867
        }
868
869
        // calculate all the path to copy the file to
870
        $fromFilename = basename($filePath);
871
        $toFilename = $this->ID. '~' . $fromFilename; //add the docID to the start of the Filename
872
        $toFolder = DMS::get_storage_folder($this->ID);
873
        $toPath = DMS::get_dms_path() . DIRECTORY_SEPARATOR . $toFolder . DIRECTORY_SEPARATOR . $toFilename;
874
875
        DMS::create_storage_folder(DMS::get_dms_path() . DIRECTORY_SEPARATOR . $toFolder);
876
877
        //copy the file into place
878
        $fromPath = BASE_PATH . DIRECTORY_SEPARATOR . $filePath;
879
880
        //version the existing file (copy it to a new "very specific" filename
881
        if (DMSDocument_versions::$enable_versions) {
882
            DMSDocument_versions::create_version($this);
883
        } else {    //otherwise delete the old document file
884
            $oldPath = $this->getFullPath();
885
            if (file_exists($oldPath)) {
886
                unlink($oldPath);
887
            }
888
        }
889
890
        copy($fromPath, $toPath);   //this will overwrite the existing file (if present)
891
892
        //write the filename of the stored document
893
        $this->Filename = $toFilename;
894
        $this->Folder = strval($toFolder);
895
896
        $extension = pathinfo($this->Filename, PATHINFO_EXTENSION);
897
898
        if (empty($this->Title)) {
899
            // don't overwrite existing document titles
900
            $this->Title = basename($filePath, '.'.$extension);
901
        }
902
903
        $this->LastChanged = SS_Datetime::now()->Rfc2822();
904
        $this->write();
905
906
        return $this;
907
    }
908
909
    /**
910
     * Takes a File object or a String (path to a file) and copies it into the
911
     * DMS, replacing the original document file but keeping the rest of the
912
     * document unchanged.
913
     *
914
     * @param File|string $file path to a file to store
915
     *
916
     * @return DMSDocument object that we replaced the file in
917
     */
918
    public function replaceDocument($file)
919
    {
920
        $filePath = DMS::transform_file_to_file_path($file);
921
        $doc = $this->storeDocument($filePath); // replace the document
922
923
        return $doc;
924
    }
925
926
927
    /**
928
     * Return the type of file for the given extension
929
     * on the current file name.
930
     *
931
     * @param string $ext
932
     *
933
     * @return string
934
     */
935
    public static function get_file_type($ext)
936
    {
937
        $types = array(
938
            'gif' => 'GIF image - good for diagrams',
939
            'jpg' => 'JPEG image - good for photos',
940
            'jpeg' => 'JPEG image - good for photos',
941
            'png' => 'PNG image - good general-purpose format',
942
            'ico' => 'Icon image',
943
            'tiff' => 'Tagged image format',
944
            'doc' => 'Word document',
945
            'xls' => 'Excel spreadsheet',
946
            'zip' => 'ZIP compressed file',
947
            'gz' => 'GZIP compressed file',
948
            'dmg' => 'Apple disk image',
949
            'pdf' => 'Adobe Acrobat PDF file',
950
            'mp3' => 'MP3 audio file',
951
            'wav' => 'WAV audo file',
952
            'avi' => 'AVI video file',
953
            'mpg' => 'MPEG video file',
954
            'mpeg' => 'MPEG video file',
955
            'js' => 'Javascript file',
956
            'css' => 'CSS file',
957
            'html' => 'HTML file',
958
            'htm' => 'HTML file'
959
        );
960
961
        return isset($types[$ext]) ? $types[$ext] : $ext;
962
    }
963
964
965
    /**
966
     * Returns the Description field with HTML <br> tags added when there is a
967
     * line break.
968
     *
969
     * @return string
970
     */
971
    public function getDescriptionWithLineBreak()
972
    {
973
        return nl2br($this->getField('Description'));
974
    }
975
976
    /**
977
     * @return FieldList
978
     */
979
    public function getCMSFields()
980
    {
981
        //include JS to handling showing and hiding of bottom "action" tabs
982
        Requirements::javascript(DMS_DIR.'/javascript/DMSDocumentCMSFields.js');
983
        Requirements::css(DMS_DIR.'/css/DMSDocumentCMSFields.css');
984
985
        $fields = new FieldList();  //don't use the automatic scaffolding, it is slow and unnecessary here
986
987
        $extraTasks = '';   //additional text to inject into the list of tasks at the bottom of a DMSDocument CMSfield
988
989
        //get list of shortcode page relations
990
        $relationFinder = new ShortCodeRelationFinder();
991
        $relationList = $relationFinder->getList($this->ID);
992
993
        $fieldsTop = $this->getFieldsForFile($relationList->count());
994
        $fields->add($fieldsTop);
995
996
        $fields->add(new TextField('Title', 'Title'));
997
        $fields->add(new TextareaField('Description', 'Description'));
998
999
        $downloadBehaviorSource = array(
1000
            'open' => _t('DMSDocument.OPENINBROWSER', 'Open in browser'),
1001
            'download' => _t('DMSDocument.FORCEDOWNLOAD', 'Force download'),
1002
        );
1003
        $defaultDownloadBehaviour = Config::inst()->get('DMSDocument', 'default_download_behaviour');
1004
        if (!isset($downloadBehaviorSource[$defaultDownloadBehaviour])) {
1005
            user_error('Default download behaviour "' . $defaultDownloadBehaviour . '" not supported.', E_USER_WARNING);
1006
        } else {
1007
            $downloadBehaviorSource[$defaultDownloadBehaviour] .= ' (' . _t('DMSDocument.DEFAULT', 'default') . ')';
1008
        }
1009
1010
        $fields->add(
1011
            OptionsetField::create(
1012
                'DownloadBehavior',
1013
                _t('DMSDocument.DOWNLOADBEHAVIOUR', 'Download behavior'),
1014
                $downloadBehaviorSource,
1015
                $defaultDownloadBehaviour
1016
            )
1017
            ->setDescription(
1018
                'How the visitor will view this file. <strong>Open in browser</strong> '
1019
                . 'allows files to be opened in a new tab.'
1020
            )
1021
        );
1022
1023
        //create upload field to replace document
1024
        $uploadField = new DMSUploadField('ReplaceFile', 'Replace file');
1025
        $uploadField->setConfig('allowedMaxFileNumber', 1);
1026
        $uploadField->setConfig('downloadTemplateName', 'ss-dmsuploadfield-downloadtemplate');
1027
        $uploadField->setRecord($this);
1028
1029
        $gridFieldConfig = GridFieldConfig::create()->addComponents(
1030
            new GridFieldToolbarHeader(),
1031
            new GridFieldSortableHeader(),
1032
            new GridFieldDataColumns(),
1033
            new GridFieldPaginator(30),
1034
            //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...
1035
            new GridFieldDetailForm()
1036
        );
1037
1038
        $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...
1039
            ->setDisplayFields(array(
1040
                'Title'=>'Title',
1041
                'ClassName'=>'Page Type',
1042
                'ID'=>'Page ID'
1043
            ))
1044
            ->setFieldFormatting(array(
1045
                'Title'=>sprintf(
1046
                    '<a class=\"cms-panel-link\" href=\"%s/$ID\">$Title</a>',
1047
                    singleton('CMSPageEditController')->Link('show')
1048
                )
1049
            ));
1050
1051
        $pagesGrid = GridField::create(
1052
            'Pages',
1053
            _t('DMSDocument.RelatedPages', 'Related Pages'),
1054
            $this->Pages(),
1055
            $gridFieldConfig
1056
        );
1057
1058
        $referencesGrid = GridField::create(
1059
            'References',
1060
            _t('DMSDocument.RelatedReferences', 'Related References'),
1061
            $relationList,
1062
            $gridFieldConfig
1063
        );
1064
1065
        if (DMSDocument_versions::$enable_versions) {
1066
            $versionsGridFieldConfig = GridFieldConfig::create()->addComponents(
1067
                new GridFieldToolbarHeader(),
1068
                new GridFieldSortableHeader(),
1069
                new GridFieldDataColumns(),
1070
                new GridFieldPaginator(30)
1071
            );
1072
            $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...
1073
                ->setDisplayFields(Config::inst()->get('DMSDocument_versions', 'display_fields'))
1074
                ->setFieldCasting(array('LastChanged'=>"Datetime->Ago"))
1075
                ->setFieldFormatting(
1076
                    array(
1077
                        'FilenameWithoutID' => '<a target=\'_blank\' class=\'file-url\' href=\'$Link\'>'
1078
                            . '$FilenameWithoutID</a>'
1079
                    )
1080
                );
1081
1082
            $versionsGrid =  GridField::create(
1083
                'Versions',
1084
                _t('DMSDocument.Versions', 'Versions'),
1085
                $this->getVersions(),
1086
                $versionsGridFieldConfig
1087
            );
1088
            $extraTasks .= '<li class="ss-ui-button" data-panel="find-versions">Versions</li>';
1089
        }
1090
1091
        $fields->add(new LiteralField(
1092
            'BottomTaskSelection',
1093
            '<div id="Actions" class="field actions"><label class="left">Actions</label><ul>'
1094
            . '<li class="ss-ui-button" data-panel="embargo">Embargo</li>'
1095
            . '<li class="ss-ui-button" data-panel="expiry">Expiry</li>'
1096
            . '<li class="ss-ui-button" data-panel="replace">Replace</li>'
1097
            . '<li class="ss-ui-button" data-panel="find-usage">Usage</li>'
1098
            . '<li class="ss-ui-button" data-panel="find-references">References</li>'
1099
            . '<li class="ss-ui-button" data-panel="find-relateddocuments">Related Documents</li>'
1100
            . $extraTasks
1101
            . '</ul></div>'
1102
        ));
1103
1104
        $embargoValue = 'None';
1105
        if ($this->EmbargoedIndefinitely) {
1106
            $embargoValue = 'Indefinitely';
1107
        } elseif ($this->EmbargoedUntilPublished) {
1108
            $embargoValue = 'Published';
1109
        } elseif (!empty($this->EmbargoedUntilDate)) {
1110
            $embargoValue = 'Date';
1111
        }
1112
        $embargo = new OptionsetField(
1113
            'Embargo',
1114
            'Embargo',
1115
            array(
1116
                'None' => 'None',
1117
                'Published' => 'Hide document until page is published',
1118
                'Indefinitely' => 'Hide document indefinitely',
1119
                'Date' => 'Hide until set date'
1120
            ),
1121
            $embargoValue
1122
        );
1123
        $embargoDatetime = DatetimeField::create('EmbargoedUntilDate', '');
1124
        $embargoDatetime->getDateField()
1125
            ->setConfig('showcalendar', true)
1126
            ->setConfig('dateformat', 'dd-MM-yyyy')
1127
            ->setConfig('datavalueformat', 'dd-MM-yyyy');
1128
1129
        $expiryValue = 'None';
1130
        if (!empty($this->ExpireAtDate)) {
1131
            $expiryValue = 'Date';
1132
        }
1133
        $expiry = new OptionsetField(
1134
            'Expiry',
1135
            'Expiry',
1136
            array(
1137
                'None' => 'None',
1138
                'Date' => 'Set document to expire on'
1139
            ),
1140
            $expiryValue
1141
        );
1142
        $expiryDatetime = DatetimeField::create('ExpireAtDate', '');
1143
        $expiryDatetime->getDateField()
1144
            ->setConfig('showcalendar', true)
1145
            ->setConfig('dateformat', 'dd-MM-yyyy')
1146
            ->setConfig('datavalueformat', 'dd-MM-yyyy');
1147
1148
        // This adds all the actions details into a group.
1149
        // Embargo, History, etc to go in here
1150
        // These are toggled on and off via the Actions Buttons above
1151
        // 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...
1152
        $actionsPanel = FieldGroup::create(
1153
            FieldGroup::create($embargo, $embargoDatetime)->addExtraClass('embargo'),
1154
            FieldGroup::create($expiry, $expiryDatetime)->addExtraClass('expiry'),
1155
            FieldGroup::create($uploadField)->addExtraClass('replace'),
1156
            FieldGroup::create($pagesGrid)->addExtraClass('find-usage'),
1157
            FieldGroup::create($referencesGrid)->addExtraClass('find-references'),
1158
            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...
1159
            FieldGroup::create($this->getRelatedDocumentsGridField())->addExtraClass('find-relateddocuments')
1160
        );
1161
1162
        $actionsPanel->setName("ActionsPanel");
1163
        $actionsPanel->addExtraClass("DMSDocumentActionsPanel");
1164
        $fields->push($actionsPanel);
1165
1166
        $this->addPermissionsFields($fields);
1167
        $this->extend('updateCMSFields', $fields);
1168
1169
        return $fields;
1170
    }
1171
1172
    /**
1173
     * Adds permissions selection fields to the FieldList.
1174
     *
1175
     * @param FieldList $fields
1176
     */
1177
    public function addPermissionsFields($fields)
1178
    {
1179
        $showFields = array(
1180
            'CanViewType'  => '',
1181
            'ViewerGroups' => 'hide',
1182
            'CanEditType'  => '',
1183
            'EditorGroups' => 'hide',
1184
        );
1185
        /** @var SiteTree $siteTree */
1186
        $siteTree = singleton('SiteTree');
1187
        $settingsFields = $siteTree->getSettingsFields();
1188
1189
        foreach ($showFields as $name => $extraCss) {
1190
            $compositeName = "Root.Settings.$name";
1191
            /** @var FormField $field */
1192
            if ($field = $settingsFields->fieldByName($compositeName)) {
1193
                $field->addExtraClass($extraCss);
1194
                $title = str_replace('page', 'document', $field->Title());
1195
                $field->setTitle($title);
1196
1197
                // Remove Inherited source option from DropdownField
1198
                if ($field instanceof DropdownField) {
1199
                    $options = $field->getSource();
1200
                    unset($options['Inherit']);
1201
                    $field->setSource($options);
1202
                }
1203
                $fields->push($field);
1204
            }
1205
        }
1206
1207
        $this->extend('updatePermissionsFields', $fields);
1208
    }
1209
1210
    public function onBeforeWrite()
1211
    {
1212
        parent::onBeforeWrite();
1213
1214
        if (isset($this->Embargo)) {
1215
            //set the embargo options from the OptionSetField created in the getCMSFields method
1216
            //do not write after clearing the embargo (write happens automatically)
1217
            $savedDate = $this->EmbargoedUntilDate;
1218
            $this->clearEmbargo(false); //clear all previous settings and re-apply them on save
1219
1220
            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...
1221
                $this->embargoUntilPublished(false);
1222
            }
1223
            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...
1224
                $this->embargoIndefinitely(false);
1225
            }
1226
            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...
1227
                $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...
1228
            }
1229
        }
1230
1231
        if (isset($this->Expiry)) {
1232
            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...
1233
                $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...
1234
            } else {
1235
                $this->clearExpiry(false);
1236
            } //clear all previous settings
1237
        }
1238
    }
1239
1240
    /**
1241
     * Return the relative URL of an icon for the file type, based on the
1242
     * {@link appCategory()} value.
1243
     *
1244
     * Images are searched for in "dms/images/app_icons/".
1245
     *
1246
     * @return string
1247
     */
1248
    public function Icon($ext)
1249
    {
1250
        if (!Director::fileExists(DMS_DIR."/images/app_icons/{$ext}_32.png")) {
1251
            $ext = File::get_app_category($ext);
1252
        }
1253
1254
        if (!Director::fileExists(DMS_DIR."/images/app_icons/{$ext}_32.png")) {
1255
            $ext = "generic";
1256
        }
1257
1258
        return DMS_DIR."/images/app_icons/{$ext}_32.png";
1259
    }
1260
1261
    /**
1262
     * Return the extension of the file associated with the document
1263
     *
1264
     * @return string
1265
     */
1266
    public function getExtension()
1267
    {
1268
        return strtolower(pathinfo($this->Filename, PATHINFO_EXTENSION));
1269
    }
1270
1271
    /**
1272
     * @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...
1273
     */
1274
    public function getSize()
1275
    {
1276
        $size = $this->getAbsoluteSize();
1277
        return ($size) ? File::format_size($size) : false;
1278
    }
1279
1280
    /**
1281
     * Return the size of the file associated with the document.
1282
     *
1283
     * @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...
1284
     */
1285
    public function getAbsoluteSize()
1286
    {
1287
        return file_exists($this->getFullPath()) ? filesize($this->getFullPath()) : null;
1288
    }
1289
1290
    /**
1291
     * An alias to DMSDocument::getSize()
1292
     *
1293
     * @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...
1294
     */
1295
    public function getFileSizeFormatted()
1296
    {
1297
        return $this->getSize();
1298
    }
1299
1300
1301
    /**
1302
     * @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...
1303
     */
1304
    protected function getFieldsForFile($relationListCount)
1305
    {
1306
        $extension = $this->getExtension();
1307
1308
        $previewField = new LiteralField(
1309
            "ImageFull",
1310
            "<img id='thumbnailImage' class='thumbnail-preview' src='{$this->Icon($extension)}?r="
1311
            . rand(1, 100000) . "' alt='{$this->Title}' />\n"
1312
        );
1313
1314
        //count the number of pages this document is published on
1315
        $publishedOnCount = $this->Pages()->Count();
1316
        $publishedOnValue = "$publishedOnCount pages";
1317
        if ($publishedOnCount == 1) {
1318
            $publishedOnValue = "$publishedOnCount page";
1319
        }
1320
1321
        $relationListCountValue = "$relationListCount pages";
1322
        if ($relationListCount == 1) {
1323
            $relationListCountValue = "$relationListCount page";
1324
        }
1325
1326
        $fields = new FieldGroup(
1327
            $filePreview = CompositeField::create(
1328
                CompositeField::create(
1329
                    $previewField
1330
                )->setName("FilePreviewImage")->addExtraClass('cms-file-info-preview'),
1331
                CompositeField::create(
1332
                    CompositeField::create(
1333
                        new ReadonlyField("ID", "ID number". ':', $this->ID),
1334
                        new ReadonlyField(
1335
                            "FileType",
1336
                            _t('AssetTableField.TYPE', 'File type') . ':',
1337
                            self::get_file_type($extension)
1338
                        ),
1339
                        new ReadonlyField(
1340
                            "Size",
1341
                            _t('AssetTableField.SIZE', 'File size') . ':',
1342
                            $this->getFileSizeFormatted()
1343
                        ),
1344
                        $urlField = new ReadonlyField(
1345
                            'ClickableURL',
1346
                            _t('AssetTableField.URL', 'URL'),
1347
                            sprintf(
1348
                                '<a href="%s" target="_blank" class="file-url">%s</a>',
1349
                                $this->getLink(),
1350
                                $this->getLink()
1351
                            )
1352
                        ),
1353
                        new ReadonlyField("FilenameWithoutIDField", "Filename". ':', $this->getFilenameWithoutID()),
1354
                        new DateField_Disabled(
1355
                            "Created",
1356
                            _t('AssetTableField.CREATED', 'First uploaded') . ':',
1357
                            $this->Created
1358
                        ),
1359
                        new DateField_Disabled(
1360
                            "LastEdited",
1361
                            _t('AssetTableField.LASTEDIT', 'Last changed') . ':',
1362
                            $this->LastEdited
1363
                        ),
1364
                        new DateField_Disabled(
1365
                            "LastChanged",
1366
                            _t('AssetTableField.LASTCHANGED', 'Last replaced') . ':',
1367
                            $this->LastChanged
1368
                        ),
1369
                        new ReadonlyField("PublishedOn", "Published on". ':', $publishedOnValue),
1370
                        new ReadonlyField("ReferencedOn", "Referenced on". ':', $relationListCountValue),
1371
                        new ReadonlyField("ViewCount", "View count". ':', $this->ViewCount)
1372
                    )
1373
                )->setName("FilePreviewData")->addExtraClass('cms-file-info-data')
1374
            )->setName("FilePreview")->addExtraClass('cms-file-info')
1375
        );
1376
1377
        $fields->setName('FileP');
1378
        $urlField->dontEscape = true;
1379
1380
        return $fields;
1381
    }
1382
1383
    /**
1384
     * Takes a file and adds it to the DMSDocument storage, replacing the
1385
     * current file.
1386
     *
1387
     * @param File $file
1388
     *
1389
     * @return $this
1390
     */
1391
    public function ingestFile($file)
1392
    {
1393
        $this->replaceDocument($file);
1394
        $file->delete();
1395
1396
        return $this;
1397
    }
1398
1399
    /**
1400
     * Get a data list of documents related to this document
1401
     *
1402
     * @return DataList
1403
     */
1404
    public function getRelatedDocuments()
1405
    {
1406
        $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...
1407
1408
        $this->extend('updateRelatedDocuments', $documents);
1409
1410
        return $documents;
1411
    }
1412
1413
    /**
1414
     * Get a GridField for managing related documents
1415
     *
1416
     * @return GridField
1417
     */
1418
    protected function getRelatedDocumentsGridField()
1419
    {
1420
        $gridField = GridField::create(
1421
            'RelatedDocuments',
1422
            _t('DMSDocument.RELATEDDOCUMENTS', 'Related Documents'),
1423
            $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...
1424
            new GridFieldConfig_RelationEditor
1425
        );
1426
1427
        $gridField->getConfig()->removeComponentsByType('GridFieldAddNewButton');
1428
        // Move the autocompleter to the left
1429
        $gridField->getConfig()->removeComponentsByType('GridFieldAddExistingAutocompleter');
1430
        $gridField->getConfig()->addComponent(new GridFieldAddExistingAutocompleter('buttons-before-left'));
1431
1432
        $this->extend('updateRelatedDocumentsGridField', $gridField);
1433
1434
        return $gridField;
1435
    }
1436
1437
    /**
1438
     * Checks at least one group is selected if CanViewType || CanEditType == 'OnlyTheseUsers'
1439
     *
1440
     * @return ValidationResult
1441
     */
1442
    protected function validate()
1443
    {
1444
        $valid = parent::validate();
1445
1446
        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...
1447
            $valid->error(
1448
                _t(
1449
                    'DMSDocument.VALIDATIONERROR_NOVIEWERSELECTED',
1450
                    "Selecting 'Only these people' from a viewers list needs at least one group selected."
1451
                )
1452
            );
1453
        }
1454
1455
        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...
1456
            $valid->error(
1457
                _t(
1458
                    'DMSDocument.VALIDATIONERROR_NOEDITORSELECTED',
1459
                    "Selecting 'Only these people' from a editors list needs at least one group selected."
1460
                )
1461
            );
1462
        }
1463
1464
        return $valid;
1465
    }
1466
1467
    /**
1468
     * Returns a reason as to why this document cannot be viewed.
1469
     *
1470
     * @return string
1471
     */
1472
    public function getPermissionDeniedReason()
1473
    {
1474
        $result = '';
1475
1476
        if ($this->CanViewType == 'LoggedInUsers') {
1477
            $result = _t('DMSDocument.PERMISSIONDENIEDREASON_LOGINREQUIRED', 'Please log in to view this document');
1478
        }
1479
1480
        if ($this->CanViewType == 'OnlyTheseUsers') {
1481
            $result = _t('DMSDocument.PERMISSIONDENIEDREASON_NOTAUTHORISED',
1482
                'You are not authorised to view this document');
1483
        }
1484
1485
        return $result;
1486
    }
1487
}
1488