draftfiles_ajax.php 13.6 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<?php

// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

/**
 * Draft file ajax file manager
 *
 * @package    core
 * @subpackage repository
 * @copyright  2010 Dongsheng Cai <dongsheng@moodle.com>
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */

define('AJAX_SCRIPT', true);

require('../config.php');
require_once($CFG->libdir.'/filelib.php');
require_once($CFG->libdir.'/adminlib.php');
32
require_once($CFG->dirroot.'/repository/lib.php');
33
$PAGE->set_context(context_system::instance());
34
35
36
37
38
39
40
41
require_login();
if (isguestuser()) {
    print_error('noguest');
}
require_sesskey();

$action  = required_param('action', PARAM_ALPHA);
$draftid = required_param('itemid', PARAM_INT);
Dongsheng Cai's avatar
Dongsheng Cai committed
42
$filepath = optional_param('filepath', '/', PARAM_PATH);
43

44
$user_context = context_user::instance($USER->id);
45

46
47
echo $OUTPUT->header(); // send headers

48
49
50
51
52
53
//
//NOTE TO ALL DEVELOPERS: this script must deal only with draft area of current user, it has to use only file_storage and no file_browser!!
//

switch ($action) {
    case 'dir':
54
        $data = new stdClass();
55
56
57
58
59
60
61
        file_get_drafarea_folders($draftid, $filepath, $data);
        echo json_encode($data);
        die;

    case 'list':
        $filepath = optional_param('filepath', '/', PARAM_PATH);

62
        $data = repository::prepare_listing(file_get_drafarea_files($draftid, $filepath));
63
64
65
        $info = file_get_draft_area_info($draftid);
        $data->filecount = $info['filecount'];
        $data->filesize = $info['filesize'];
66
67
        $data->tree = new stdClass();
        file_get_drafarea_folders($draftid, '/', $data->tree);
68
69
70
71
72
73
74
75
76
        echo json_encode($data);
        die;

    case 'mkdir':
        $filepath   = required_param('filepath', PARAM_PATH);
        $newdirname = required_param('newdirname', PARAM_FILE);

        $fs = get_file_storage();
        $fs->create_directory($user_context->id, 'user', 'draft', $draftid, file_correct_filepath(file_correct_filepath($filepath).$newdirname));
77
        $return = new stdClass();
78
79
80
81
82
83
84
85
86
87
        $return->filepath = $filepath;
        echo json_encode($return);
        die;

    case 'delete':
        $filename   = required_param('filename', PARAM_FILE);
        $filepath   = required_param('filepath', PARAM_PATH);

        $fs = get_file_storage();
        $filepath = file_correct_filepath($filepath);
88
        $return = new stdClass();
89
90
        if ($stored_file = $fs->get_file($user_context->id, 'user', 'draft', $draftid, $filepath, $filename)) {
            $parent_path = $stored_file->get_parent_directory()->get_filepath();
91
92
93
94
95
96
            if ($stored_file->is_directory()) {
                $files = $fs->get_directory_files($user_context->id, 'user', 'draft', $draftid, $filepath, true);
                foreach ($files as $file) {
                    $file->delete();
                }
                $stored_file->delete();
97
98
99
                $return->filepath = $parent_path;
                echo json_encode($return);
            } else {
100
101
102
103
104
105
                if($result = $stored_file->delete()) {
                    $return->filepath = $parent_path;
                    echo json_encode($return);
                } else {
                    echo json_encode(false);
                }
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
            }
        } else {
            echo json_encode(false);
        }
        die;

    case 'setmainfile':
        $filename   = required_param('filename', PARAM_FILE);
        $filepath   = required_param('filepath', PARAM_PATH);

        $filepath = file_correct_filepath($filepath);
        // reset sort order
        file_reset_sortorder($user_context->id, 'user', 'draft', $draftid);
        // set main file
        $return = file_set_sortorder($user_context->id, 'user', 'draft', $draftid, $filepath, $filename, 1);
        echo json_encode($return);
        die;

124
125
126
127
128
    case 'updatefile':
        // Allows to Rename file, move it to another directory, change it's license and author information in one request
        $filename    = required_param('filename', PARAM_FILE);
        $filepath    = required_param('filepath', PARAM_PATH);
        $updatedata = array();
129
130
131
132
        $updatedata['filename'] = optional_param('newfilename', $filename, PARAM_FILE);
        $updatedata['filepath'] = $newfilepath = optional_param('newfilepath', $filepath, PARAM_PATH);
        if (($v = optional_param('newlicense', false, PARAM_TEXT)) !== false) {
            $updatedata['license'] = $v;
133
        }
134
135
136
137
138
139
140
        if (($v = optional_param('newauthor', false, PARAM_TEXT)) !== false) {
            $updatedata['author'] = $v;
        }
        try {
            repository::update_draftfile($draftid, $filepath, $filename, $updatedata);
        } catch (moodle_exception $e) {
            die(json_encode((object)array('error' => $e->getMessage())));
141
142
143
144
145
146
147
148
        }
        die(json_encode((object)array('filepath' => $newfilepath)));

    case 'updatedir':
        $filepath = required_param('filepath', PARAM_PATH);
        $newdirname = required_param('newdirname', PARAM_FILE);
        $parent = required_param('newfilepath', PARAM_PATH);
        $newfilepath = clean_param($parent . '/' . $newdirname . '/', PARAM_PATH);
149
150
151
152
        try {
            repository::update_draftfile($draftid, $filepath, '.', array('filepath' => $newfilepath));
        } catch (moodle_exception $e) {
            die(json_encode((object)array('error' => $e->getMessage())));
153
        }
154
        die(json_encode((object)array('filepath' => $parent)));
155

156
157
158
159
160
161
162
163
164
    case 'zip':
        $filepath = required_param('filepath', PARAM_PATH);

        $zipper = get_file_packer('application/zip');
        $fs = get_file_storage();

        $file = $fs->get_file($user_context->id, 'user', 'draft', $draftid, $filepath, '.');

        $parent_path = $file->get_parent_directory()->get_filepath();
165

166
167
        $filepath = explode('/', trim($file->get_filepath(), '/'));
        $filepath = array_pop($filepath);
168
        $zipfile = repository::get_unused_filename($draftid, $parent_path, $filepath . '.zip');
169

170
        if ($newfile = $zipper->archive_to_storage(array($filepath => $file), $user_context->id, 'user', 'draft', $draftid, $parent_path, $zipfile, $USER->id)) {
171
            $return = new stdClass();
172
173
174
175
176
177
178
179
180
181
182
183
            $return->filepath = $parent_path;
            echo json_encode($return);
        } else {
            echo json_encode(false);
        }
        die;

    case 'downloaddir':
        $filepath = required_param('filepath', PARAM_PATH);

        $zipper = get_file_packer('application/zip');
        $fs = get_file_storage();
184
185
        $area = file_get_draft_area_info($draftid, $filepath);
        if ($area['filecount'] == 0 && $area['foldercount'] == 0) {
186
187
188
189
190
191
192
193
            echo json_encode(false);
            die;
        }

        $stored_file = $fs->get_file($user_context->id, 'user', 'draft', $draftid, $filepath, '.');
        if ($filepath === '/') {
            $filename = get_string('files').'.zip';
        } else {
194
195
            $filename = explode('/', trim($filepath, '/'));
            $filename = array_pop($filename) . '.zip';
196
197
198
199
        }

        // archive compressed file to an unused draft area
        $newdraftitemid = file_get_unused_draft_itemid();
200
        if ($newfile = $zipper->archive_to_storage(array('/' => $stored_file), $user_context->id, 'user', 'draft', $newdraftitemid, '/', $filename, $USER->id)) {
201
            $return = new stdClass();
Petr Skoda's avatar
Petr Skoda committed
202
            $return->fileurl  = moodle_url::make_draftfile_url($newdraftitemid, '/', $filename)->out();
203
            $return->filepath = $filepath;
204
205
206
207
208
209
210
211
212
            echo json_encode($return);
        } else {
            echo json_encode(false);
        }
        die;

    case 'unzip':
        $filename = required_param('filename', PARAM_FILE);
        $filepath = required_param('filepath', PARAM_PATH);
213
        $areamaxbytes = required_param('areamaxbytes', PARAM_INT);
214

215
        $return = new stdClass();
216
217
218
        $zipper = get_file_packer('application/zip');
        $fs = get_file_storage();
        $file = $fs->get_file($user_context->id, 'user', 'draft', $draftid, $filepath, $filename);
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
        // Get the total size of the content in the archive.
        $filecontentsize = $file->get_total_content_size($zipper);

        // Return an error if the returned size of the content is NULL.
        // This means the utility class was unable to read the content of the archive.
        if (is_null($filecontentsize)) {
            $return->error = get_string('cannotunzipcontentunreadable', 'repository');
            die(json_encode($return));
        }

        // Check whether the maximum size allowed in this draft area will be exceeded with unzipping the file.
        // If the maximum size allowed is exceeded, return an error before attempting to unzip.
        if (file_is_draft_area_limit_reached($draftid, $areamaxbytes, $filecontentsize)) {
            $return->error = get_string('cannotunzipquotaexceeded', 'repository');
            die(json_encode($return));
        }
235

236
        // Find unused name for directory to extract the archive.
237
        $temppath = $fs->get_unused_dirname($user_context->id, 'user', 'draft', $draftid, $filepath. pathinfo($filename, PATHINFO_FILENAME). '/');
238
239
        $donotremovedirs = array();
        $doremovedirs = array($temppath);
240
241
242
243
244
245
246
247
248
249
250
251
252
253
        // Extract archive and move all files from $temppath to $filepath
        if ($file->extract_to_storage($zipper, $user_context->id, 'user', 'draft', $draftid, $temppath, $USER->id) !== false) {
            $extractedfiles = $fs->get_directory_files($user_context->id, 'user', 'draft', $draftid, $temppath, true);
            $xtemppath = preg_quote($temppath, '|');
            foreach ($extractedfiles as $file) {
                $realpath = preg_replace('|^'.$xtemppath.'|', $filepath, $file->get_filepath());
                if (!$file->is_directory()) {
                    // Set the source to the extracted file to indicate that it came from archive.
                    $file->set_source(serialize((object)array('source' => $filepath)));
                }
                if (!$fs->file_exists($user_context->id, 'user', 'draft', $draftid, $realpath, $file->get_filename())) {
                    // File or directory did not exist, just move it.
                    $file->rename($realpath, $file->get_filename());
                } else if (!$file->is_directory()) {
254
                    // File already existed, overwrite it
255
                    repository::overwrite_existing_draftfile($draftid, $realpath, $file->get_filename(), $file->get_filepath(), $file->get_filename());
256
257
258
259
                } else {
                    // Directory already existed, remove temporary dir but make sure we don't remove the existing dir
                    $doremovedirs[] = $file->get_filepath();
                    $donotremovedirs[] = $realpath;
260
261
                }
            }
262
263
            $return->filepath = $filepath;
        } else {
264
            $return = false;
265
        }
266
        // Remove remaining temporary directories.
267
268
269
270
        foreach (array_diff($doremovedirs, $donotremovedirs) as $filepath) {
            if ($file = $fs->get_file($user_context->id, 'user', 'draft', $draftid, $filepath, '.')) {
                $file->delete();
            }
271
272
        }
        die(json_encode($return));
273

274
275
276
277
278
279
280
281
282
283
284
285
286
287
    case 'getoriginal':
        $filename    = required_param('filename', PARAM_FILE);
        $filepath    = required_param('filepath', PARAM_PATH);

        $fs = get_file_storage();
        $file = $fs->get_file($user_context->id, 'user', 'draft', $draftid, $filepath, $filename);
        if (!$file) {
            echo json_encode(false);
        } else {
            $return = array('filename' => $filename, 'filepath' => $filepath, 'original' => $file->get_reference_details());
            echo json_encode((object)$return);
        }
        die;

288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
    case 'getreferences':
        $filename    = required_param('filename', PARAM_FILE);
        $filepath    = required_param('filepath', PARAM_PATH);

        $fs = get_file_storage();
        $file = $fs->get_file($user_context->id, 'user', 'draft', $draftid, $filepath, $filename);
        if (!$file) {
            echo json_encode(false);
        } else {
            $source = unserialize($file->get_source());
            $return = array('filename' => $filename, 'filepath' => $filepath, 'references' => array());
            $browser = get_file_browser();
            if (isset($source->original)) {
                $reffiles = $fs->search_references($source->original);
                foreach ($reffiles as $reffile) {
303
                    $refcontext = context::instance_by_id($reffile->get_contextid());
304
305
306
307
308
309
310
311
312
313
314
315
                    $fileinfo = $browser->get_file_info($refcontext, $reffile->get_component(), $reffile->get_filearea(), $reffile->get_itemid(), $reffile->get_filepath(), $reffile->get_filename());
                    if (empty($fileinfo)) {
                        $return['references'][] = get_string('undisclosedreference', 'repository');
                    } else {
                        $return['references'][] = $fileinfo->get_readable_fullname();
                    }
                }
            }
            echo json_encode((object)$return);
        }
        die;

316
317
318
319
320
    default:
        // no/unknown action?
        echo json_encode(false);
        die;
}