Completed
Pull Request — master (#168)
by Franco
02:41
created

code/model/DMSDocument_versions.php (1 issue)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
3
/**
4
 * DataObject to store versions of uploaded Documents.
5
 *
6
 * Versions are only created when replacing a document, not on every save of the
7
 * DMSDocument dataobject. So, versions store the various versions of the
8
 * underlying Document, not the DataObject with information about that object.
9
 *
10
 * @package dms
11
 */
12
class DMSDocument_versions extends DataObject
13
{
14
15
    /**
16
     * @var bool $enable_versions Flag that turns on or off versions of
17
     * documents when replacing them
18
     */
19
    public static $enable_versions = true;
20
21
    private static $db = array(
22
        'VersionCounter' => 'Int',
23
        'VersionViewCount' => 'Int'
24
    );
25
26
    private static $has_one = array(
27
        'Document' => 'DMSDocument'
28
    );
29
30
    private static $defaults = array(
31
        'VersionCounter' => 0
32
    );
33
34
    private static $display_fields = array(
35
        'VersionCounter' => 'Version Counter',
36
        'FilenameWithoutID' => 'Filename',
37
        'LastEdited' => 'Last Changed'
38
    );
39
40
    private static $summary_fields = array(
41
        'VersionCounter',
42
        'FilenameWithoutID'
43
    );
44
45
    private static $field_labels = array(
46
        'FilenameWithoutID'=>'Filename'
47
    );
48
49
    private static $default_sort = array(
50
        'LastEdited' => 'DESC'
51
    );
52
53
54
    /**
55
     * Creates a new version of a document by moving the current file and
56
     * renaming it to the versioned filename.
57
     *
58
     * This method assumes that the method calling this is just about to upload
59
     * a new file to replace the old file.
60
     *
61
     * @static
62
     * @param DMSDocument $doc
63
     *
64
     * @return bool Success or failure
65
     */
66
    public static function create_version(DMSDocument $doc)
67
    {
68
        $success = false;
69
70
        $existingPath = $doc->getFullPath();
71
        if (is_file($existingPath)) {
72
            $docData = $doc->toMap();
73
            unset($docData['ID']);
74
            $version = new DMSDocument_versions($docData);  //create a copy of the current DMSDocument as a version
75
76
            $previousVersionCounter  = 0;
77
            $newestExistingVersion = self::get_versions($doc)->sort(array('Created'=>'DESC', 'ID'=>'DESC'))->limit(1);
78
            if ($newestExistingVersion && $newestExistingVersion->Count() > 0) {
79
                $previousVersionCounter = $newestExistingVersion->first()->VersionCounter;
80
            }
81
82
            //change the filename field to a field containing the new soon-to-be versioned file
83
            $version->VersionCounter = $previousVersionCounter + 1; //start versions at 1
84
            $newFilename = $version->generateVersionedFilename($doc, $version->VersionCounter);
85
            $version->Filename = $newFilename;
86
87
            //add a relation back to the origin ID;
88
            $version->DocumentID = $doc->ID;
89
            $id = $version->write();
90
91
            if (!empty($id)) {
92
                rename($existingPath, $version->getFullPath());
93
                $success = true;
94
            }
95
        }
96
97
        return $success;
98
    }
99
100
    public function delete()
101
    {
102
        $path = $this->getFullPath();
103
104
        if (file_exists($path)) {
105
            unlink($path);
106
        }
107
108
        parent::delete();
109
    }
110
111
    /**
112
     * Returns a DataList of all previous Versions of a document (check the
113
     * LastEdited date of each object to find the correct one).
114
     *
115
     * @static
116
     * @param DMSDocument $doc
117
     *
118
     * @return DataList List of Document objects
119
     */
120
    public static function get_versions(DMSDocument $doc)
121
    {
122
        if (!DMSDocument_versions::$enable_versions) {
123
            user_error("DMSDocument versions are disabled", E_USER_WARNING);
124
        }
125
        return DMSDocument_versions::get()->filter(array('DocumentID' => $doc->ID));
126
    }
127
128
    public function __construct($record = null, $isSingleton = false, $model = null)
129
    {
130
        //check what the constructor was passed
131
        $dmsObject = null;
132
        if ($record && is_subclass_of($record, 'DMSDocumentInterface')) {
133
            $dmsObject = $record;
134
            $record = null; //cancel the record creation to just create an empty object
135
        }
136
137
        //create the object
138
        parent::__construct($record, $isSingleton, $model);
139
140
        //copy the DMSDocument object, if passed into the constructor
141
        if ($dmsObject) {
142
            foreach (array_keys(DataObject::custom_database_fields($dmsObject->ClassName)) as $key) {
143
                $this->$key = $dmsObject->$key;
144
            }
145
        }
146
    }
147
148
    /**
149
     * Returns a link to download this document from the DMS store.
150
     *
151
     * @return string
152
     */
153
    public function getLink()
154
    {
155
        return Controller::join_links(Director::baseURL(), 'dmsdocument/version'.$this->ID);
156
    }
157
158
    /**
159
     * Document versions are always hidden from outside viewing. Only admins can
160
     * download them.
161
     *
162
     * @return bool
163
     */
164
    public function isHidden()
165
    {
166
        return true;
167
    }
168
169
    /**
170
     * Returns the full filename of the document stored in this object. Can
171
     * optionally specify which filename to use at the end.
172
     *
173
     * @param string
174
     *
175
     * @return string
176
     */
177
    public function getFullPath($filename = null)
178
    {
179
        if (!$filename) {
180
            $filename = $this->Filename;
181
        }
182
        return DMS::inst()->getStoragePath() . DIRECTORY_SEPARATOR . $this->Folder . DIRECTORY_SEPARATOR . $filename;
183
    }
184
185
    /**
186
     * @return string
187
     */
188
    public function getFilenameWithoutID()
189
    {
190
        $filenameParts = explode('~', $this->Filename);
191
        $filename = array_pop($filenameParts);
192
193
        return $filename;
194
    }
195
196
    /**
197
     * Creates a new filename for the current Document's file when replacing the
198
     * current file with a new file.
199
     *
200
     * @param DMSDocument $filename The original filename
0 ignored issues
show
There is no parameter named $filename. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
201
     *
202
     * @return string The new filename
203
     */
204
    protected function generateVersionedFilename(DMSDocument $doc, $versionCounter)
205
    {
206
        $filename = $doc->Filename;
207
208
        do {
209
            // Add leading zeros to make sorting accurate up to 10,000 documents
210
            $versionPaddingString = str_pad($versionCounter, 4, '0', STR_PAD_LEFT);
211
            $newVersionFilename = preg_replace('/([0-9]+~)(.*?)/', '$1~'.$versionPaddingString.'~$2', $filename);
212
213
            // Sanity check for crazy document names
214
            if ($newVersionFilename == $filename || empty($newVersionFilename)) {
215
                user_error('Cannot generate new document filename for file: '.$filename, E_USER_ERROR);
216
            }
217
218
            // Increase the counter for the next loop run, if necessary
219
            $versionCounter++;
220
        } while (file_exists($this->getFullPath($newVersionFilename)));
221
222
        return $newVersionFilename;
223
    }
224
225
    /**
226
     * Return the extension of the file associated with the document.
227
     *
228
     * @return string
229
     */
230
    public function getExtension()
231
    {
232
        return strtolower(pathinfo($this->Filename, PATHINFO_EXTENSION));
233
    }
234
235
    /**
236
     * @return string
237
     */
238
    public function getSize()
239
    {
240
        $size = $this->getAbsoluteSize();
241
242
        return ($size) ? File::format_size($size) : false;
243
    }
244
245
    /**
246
     * Return the size of the file associated with the document.
247
     *
248
     * @return string
249
     */
250
    public function getAbsoluteSize()
251
    {
252
        return filesize($this->getFullPath());
253
    }
254
255
    /**
256
     * An alias to DMSDocument::getSize()
257
     *
258
     * @return string
259
     */
260
    public function getFileSizeFormatted()
261
    {
262
        return $this->getSize();
263
    }
264
265
    /**
266
     * @return DMSDocument_versions
267
     */
268
    public function trackView()
269
    {
270
        if ($this->ID > 0) {
271
            $this->VersionViewCount++;
272
273
            $count = $this->VersionViewCount;
274
275
            DB::query("UPDATE \"DMSDocument_versions\" SET \"VersionViewCount\"='$count' WHERE \"ID\"={$this->ID}");
276
        }
277
278
        return $this;
279
    }
280
}
281