2 // This file is part of Moodle - http://moodle.org/
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.
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/>.
18 * Classes for converting files between different file formats.
21 * @copyright 2017 Andrew Nicols <andrew@nicols.co.uk>
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26 defined('MOODLE_INTERNAL') ||
die();
31 * Class representing a conversion currently in progress.
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
{
40 * Status value representing a conversion waiting to start.
42 const STATUS_PENDING
= 0;
45 * Status value representing a conversion in progress.
47 const STATUS_IN_PROGRESS
= 1;
50 * Status value representing a successful conversion.
52 const STATUS_COMPLETE
= 2;
55 * Status value representing a failed conversion.
57 const STATUS_FAILED
= -1;
60 * Table name for this persistent.
62 const TABLE
= 'file_conversion';
69 protected static function define_properties() {
75 'type' => PARAM_ALPHANUMEXT
,
81 self
::STATUS_IN_PROGRESS
,
82 self
::STATUS_COMPLETE
,
85 'default' => self
::STATUS_PENDING
,
89 'null' => NULL_ALLOWED
,
94 'null' => NULL_ALLOWED
,
99 'null' => NULL_ALLOWED
,
104 'null' => NULL_ALLOWED
,
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) {
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
136 conversionsourcefile.contenthash = :ccontenthash
137 AND c.targetformat = :cformat
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
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
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;
192 * Remove all old conversion records.
194 public static function remove_old_conversion_records() {
197 $DB->delete_records_select(self
::TABLE
, 'timemodified <= :weekagosecs', [
198 'weekagosecs' => time() - WEEKSECS
,
203 * Remove orphan records.
205 * Records are considered orphans when their source file not longer exists.
206 * In this scenario we do not want to keep the converted file any longer,
207 * in particular to be compliant with privacy laws.
209 public static function remove_orphan_records() {
214 FROM {" . self
::TABLE
. "} c
216 ON f.id = c.sourcefileid
218 $ids = $DB->get_fieldset_sql($sql, []);
224 list($insql, $inparams) = $DB->get_in_or_equal($ids, SQL_PARAMS_NAMED
);
225 $DB->delete_records_select(self
::TABLE
, "id $insql", $inparams);
229 * Set the source file id for the conversion.
231 * @param stored_file $file The file to convert
234 public function set_sourcefile(stored_file
$file) {
235 $this->raw_set('sourcefileid', $file->get_id());
241 * Fetch the source file.
243 * @return stored_file|false The source file
245 public function get_sourcefile() {
246 $fs = get_file_storage();
248 return $fs->get_file_by_id($this->get('sourcefileid'));
252 * Set the destination file for this conversion.
254 * @param string $filepath The path to the converted file
257 public function store_destfile_from_path($filepath) {
258 if ($record = $this->get_file_record()) {
259 $fs = get_file_storage();
260 $existing = $fs->get_file(
261 $record['contextid'],
262 $record['component'],
271 $file = $fs->create_file_from_pathname($record, $filepath);
273 $this->raw_set('destfileid', $file->get_id());
280 * Set the destination file for this conversion.
282 * @param string $content The content of the converted file
285 public function store_destfile_from_string($content) {
286 if ($record = $this->get_file_record()) {
287 $fs = get_file_storage();
288 $existing = $fs->get_file(
289 $record['contextid'],
290 $record['component'],
299 $file = $fs->create_file_from_string($record, $content);
301 $this->raw_set('destfileid', $file->get_id());
308 * Get the destination file.
310 * @return stored_file|bool Destination file
312 public function get_destfile() {
313 $fs = get_file_storage();
315 return $fs->get_file_by_id($this->get('destfileid'));
319 * Helper to ensure that the returned status is always an int.
323 protected function get_status() {
324 return (int) $this->raw_get('status');
328 * Get an instance of the current converter.
330 * @return converter_interface|false current converter instance
332 public function get_converter_instance() {
333 $currentconverter = $this->get('converter');
335 if ($currentconverter && class_exists($currentconverter)) {
336 return new $currentconverter();
343 * Transform data into a storable format.
345 * @param \stdClass $data The data to be stored
348 protected function set_data($data) {
349 $this->raw_set('data', json_encode($data));
355 * Transform data into a storable format.
357 * @return \stdClass The stored data
359 protected function get_data() {
360 $data = $this->raw_get('data');
363 return json_decode($data);
370 * Return the file record base for use in the files table.
374 protected function get_file_record() {
375 $file = $this->get_sourcefile();
378 // If the source file was removed before we completed, we must return early.
383 'contextid' => \context_system
::instance()->id
,
384 'component' => 'core',
385 'filearea' => 'documentconversion',
387 'filepath' => "/" . $this->get('targetformat') . "/",
388 'filename' => $file->get_contenthash(),