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

DMSDocument::addPermissionsFields()   B

Complexity

Conditions 4
Paths 4

Size

Total Lines 32
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

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