Merge branch 'MDL-62175-master' of git://github.com/jleyva/moodle
[moodle.git] / files / classes / conversion.php
blobd207d6cab0fe65b49bcd6d3cb6d63341cfccf34f
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * Classes for converting files between different file formats.
20 * @package core_files
21 * @copyright 2017 Andrew Nicols <andrew@nicols.co.uk>
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24 namespace core_files;
26 defined('MOODLE_INTERNAL') || die();
28 use stored_file;
30 /**
31 * Class representing a conversion currently in progress.
33 * @package core_files
34 * @copyright 2017 Andrew Nicols <andrew@nicols.co.uk>
35 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
37 class conversion extends \core\persistent {
39 /**
40 * Status value representing a conversion waiting to start.
42 const STATUS_PENDING = 0;
44 /**
45 * Status value representing a conversion in progress.
47 const STATUS_IN_PROGRESS = 1;
49 /**
50 * Status value representing a successful conversion.
52 const STATUS_COMPLETE = 2;
54 /**
55 * Status value representing a failed conversion.
57 const STATUS_FAILED = -1;
59 /**
60 * Table name for this persistent.
62 const TABLE = 'file_conversion';
64 /**
65 * Define properties.
67 * @return array
69 protected static function define_properties() {
70 return array(
71 'sourcefileid' => [
72 'type' => PARAM_INT,
74 'targetformat' => [
75 'type' => PARAM_ALPHANUMEXT,
77 'status' => [
78 'type' => PARAM_INT,
79 'choices' => [
80 self::STATUS_PENDING,
81 self::STATUS_IN_PROGRESS,
82 self::STATUS_COMPLETE,
83 self::STATUS_FAILED,
85 'default' => self::STATUS_PENDING,
87 'statusmessage' => [
88 'type' => PARAM_RAW,
89 'null' => NULL_ALLOWED,
90 'default' => null,
92 'converter' => [
93 'type' => PARAM_RAW,
94 'null' => NULL_ALLOWED,
95 'default' => null,
97 'destfileid' => [
98 'type' => PARAM_INT,
99 'null' => NULL_ALLOWED,
100 'default' => null,
102 'data' => [
103 'type' => PARAM_RAW,
104 'null' => NULL_ALLOWED,
105 'default' => null,
111 * Fetch all conversions relating to the specified file.
113 * Only conversions which have a valid file are returned.
115 * @param stored_file $file The source file being converted
116 * @param string $format The targetforamt to filter to
117 * @return conversion[]
119 public static function get_conversions_for_file(stored_file $file, $format) {
120 global $DB;
121 $instances = [];
123 // Conversion records are intended for tracking a conversion in progress or recently completed.
124 // The record is removed periodically, but the destination file is not.
125 // We need to fetch all conversion records which match the source file and target, and also all source and
126 // destination files which do not have a conversion record.
127 $sqlfields = self::get_sql_fields('c', 'conversion');
129 // Fetch actual conversions which relate to the specified source file, and have a matching conversion record,
130 // and either have a valid destination file which still exists, or do not have a destination file at all.
131 $sql = "SELECT {$sqlfields}
132 FROM {" . self::TABLE . "} c
133 INNER JOIN {files} conversionsourcefile ON conversionsourcefile.id = c.sourcefileid
134 LEFT JOIN {files} conversiondestfile ON conversiondestfile.id = c.destfileid
135 WHERE
136 conversionsourcefile.contenthash = :ccontenthash
137 AND c.targetformat = :cformat
138 AND (
139 c.destfileid IS NULL OR conversiondestfile.id IS NOT NULL
142 // Fetch a empty conversion record for each source/destination combination that we find to match where the
143 // destination file is in the correct filearea/filepath/filename combination to meet the requirements.
144 // This ensures that existing conversions are used where possible, even if there is no 'conversion' record for
145 // them.
146 $sql .= "
147 UNION ALL
148 SELECT
149 NULL AS conversionid,
150 orphanedsourcefile.id AS conversionsourcefileid,
151 :oformat AS conversiontargetformat,
152 2 AS conversionstatus,
153 NULL AS conversionstatusmessage,
154 NULL AS conversionconverter,
155 orphaneddestfile.id AS conversiondestfileid,
156 NULL AS conversiondata,
157 0 AS conversiontimecreated,
158 0 AS conversiontimemodified,
159 0 AS conversionusermodified
160 FROM {files} orphanedsourcefile
161 INNER JOIN {files} orphaneddestfile ON (
162 orphaneddestfile.filename = orphanedsourcefile.contenthash
163 AND orphaneddestfile.component = 'core'
164 AND orphaneddestfile.filearea = 'documentconversion'
165 AND orphaneddestfile.filepath = :ofilepath
167 LEFT JOIN {" . self::TABLE . "} orphanedconversion ON orphanedconversion.destfileid = orphaneddestfile.id
168 WHERE
169 orphanedconversion.id IS NULL
171 orphanedsourcefile.id = :osourcefileid
173 $records = $DB->get_records_sql($sql, [
174 'ccontenthash' => $file->get_contenthash(),
175 'osourcefileid' => $file->get_id(),
176 'cfilepath' => "/{$format}/",
177 'ofilepath' => "/{$format}/",
178 'cformat' => $format,
179 'oformat' => $format,
182 foreach ($records as $record) {
183 $data = self::extract_record($record, 'conversion');
184 $newrecord = new static(0, $data);
185 $instances[] = $newrecord;
188 return $instances;
192 * Remove all old conversion records.
194 public static function remove_old_conversion_records() {
195 global $DB;
197 $DB->delete_records_select(self::TABLE, 'timemodified <= :weekagosecs', [
198 'weekagosecs' => time() - WEEKSECS,
203 * Set the source file id for the conversion.
205 * @param stored_file $file The file to convert
206 * @return $this
208 public function set_sourcefile(stored_file $file) {
209 $this->raw_set('sourcefileid', $file->get_id());
211 return $this;
215 * Fetch the source file.
217 * @return stored_file|false The source file
219 public function get_sourcefile() {
220 $fs = get_file_storage();
222 return $fs->get_file_by_id($this->get('sourcefileid'));
226 * Set the destination file for this conversion.
228 * @param string $filepath The path to the converted file
229 * @return $this
231 public function store_destfile_from_path($filepath) {
232 if ($record = $this->get_file_record()) {
233 $fs = get_file_storage();
234 $existing = $fs->get_file(
235 $record['contextid'],
236 $record['component'],
237 $record['filearea'],
238 $record['itemid'],
239 $record['filepath'],
240 $record['filename']
242 if ($existing) {
243 $existing->delete();
245 $file = $fs->create_file_from_pathname($record, $filepath);
247 $this->raw_set('destfileid', $file->get_id());
250 return $this;
254 * Set the destination file for this conversion.
256 * @param string $content The content of the converted file
257 * @return $this
259 public function store_destfile_from_string($content) {
260 if ($record = $this->get_file_record()) {
261 $fs = get_file_storage();
262 $existing = $fs->get_file(
263 $record['contextid'],
264 $record['component'],
265 $record['filearea'],
266 $record['itemid'],
267 $record['filepath'],
268 $record['filename']
270 if ($existing) {
271 $existing->delete();
273 $file = $fs->create_file_from_string($record, $content);
275 $this->raw_set('destfileid', $file->get_id());
278 return $this;
282 * Get the destination file.
284 * @return stored_file|bool Destination file
286 public function get_destfile() {
287 $fs = get_file_storage();
289 return $fs->get_file_by_id($this->get('destfileid'));
293 * Helper to ensure that the returned status is always an int.
295 * @return int status
297 protected function get_status() {
298 return (int) $this->raw_get('status');
302 * Get an instance of the current converter.
304 * @return converter_interface|false current converter instance
306 public function get_converter_instance() {
307 $currentconverter = $this->get('converter');
309 if ($currentconverter && class_exists($currentconverter)) {
310 return new $currentconverter();
311 } else {
312 return false;
317 * Transform data into a storable format.
319 * @param \stdClass $data The data to be stored
320 * @return $this
322 protected function set_data($data) {
323 $this->raw_set('data', json_encode($data));
325 return $this;
329 * Transform data into a storable format.
331 * @return \stdClass The stored data
333 protected function get_data() {
334 $data = $this->raw_get('data');
336 if (!empty($data)) {
337 return json_decode($data);
340 return (object) [];
344 * Return the file record base for use in the files table.
346 * @return array|bool
348 protected function get_file_record() {
349 $file = $this->get_sourcefile();
351 if (!$file) {
352 // If the source file was removed before we completed, we must return early.
353 return false;
356 return [
357 'contextid' => \context_system::instance()->id,
358 'component' => 'core',
359 'filearea' => 'documentconversion',
360 'itemid' => 0,
361 'filepath' => "/" . $this->get('targetformat') . "/",
362 'filename' => $file->get_contenthash(),