Proyectos de Subversion Moodle

Rev

| Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 1
<?php
2
 
3
// This file is part of Moodle - http://moodle.org/
4
//
5
// Moodle is free software: you can redistribute it and/or modify
6
// it under the terms of the GNU General Public License as published by
7
// the Free Software Foundation, either version 3 of the License, or
8
// (at your option) any later version.
9
//
10
// Moodle is distributed in the hope that it will be useful,
11
// but WITHOUT ANY WARRANTY; without even the implied warranty of
12
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
// GNU General Public License for more details.
14
//
15
// You should have received a copy of the GNU General Public License
16
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
17
 
18
/**
19
 * @package moodlecore
20
 * @subpackage backup-helper
21
 * @copyright 2010 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com}
22
 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23
 */
24
 
25
defined('MOODLE_INTERNAL') || die();
26
 
27
/**
28
 * Helper class used to decode links back to their original form
29
 *
30
 * This class allows each restore task to specify the changes that
31
 * will be applied to any encoded (by backup) link to revert it back
32
 * to its original form, recoding any parameter as needed.
33
 *
34
 * TODO: Complete phpdocs
35
 */
36
class restore_decode_rule {
37
 
38
    protected $linkname;    // How the link has been encoded in backup (CHOICEVIEWBYID, COURSEVIEWBYID...)
39
    protected $urltemplate; // How the original URL looks like, with dollar placeholders
40
    protected $mappings;    // Which backup_ids mappings do we need to apply for replacing the placeholders
41
    protected $restoreid;   // The unique restoreid we are executing
42
    protected $sourcewwwroot; // The original wwwroot of the backup file
43
    protected $targetwwwroot; // The targer wwwroot of the restore operation
44
 
45
    protected $cregexp;     // Calculated regular expresion we'll be looking for matches
46
 
47
    /** @var bool $urlencoded Whether to use urlencode() on the final URL. */
48
    protected bool $urlencoded;
49
 
50
    /**
51
     * Constructor
52
     *
53
     * @param string $linkname How the link has been encoded in backup (CHOICEVIEWBYID, COURSEVIEWBYID...)
54
     * @param string $urltemplate How the original URL looks like, with dollar placeholders
55
     * @param array|string $mappings Which backup_ids mappings do we need to apply for replacing the placeholders
56
     * @param bool $urlencoded Whether to use urlencode() on the final URL (defaults to false)
57
     */
58
    public function __construct(string $linkname, string $urltemplate, $mappings, bool $urlencoded = false) {
59
        // Validate all the params are ok
60
        $this->mappings = $this->validate_params($linkname, $urltemplate, $mappings);
61
        $this->linkname = $linkname;
62
        $this->urltemplate = $urltemplate;
63
        $this->restoreid = 0;
64
        $this->sourcewwwroot = '';
65
        $this->targetwwwroot = ''; // yes, uses to be $CFG->wwwroot, and? ;-)
66
        $this->urlencoded = $urlencoded;
67
        $this->cregexp = $this->get_calculated_regexp();
68
    }
69
 
70
    public function set_restoreid($restoreid) {
71
        $this->restoreid = $restoreid;
72
    }
73
 
74
    public function set_wwwroots($sourcewwwroot, $targetwwwroot) {
75
        $this->sourcewwwroot = $sourcewwwroot;
76
        $this->targetwwwroot = $targetwwwroot;
77
    }
78
 
79
    public function decode($content) {
80
        if (preg_match_all($this->cregexp, $content, $matches) === 0) { // 0 matches, nothing to change
81
            return $content;
82
        }
83
        // Have found matches, iterate over them
84
        foreach ($matches[0] as $key => $tosearch) {
85
            $mappingsok = true;             // To detect if any mapping has failed
86
            $placeholdersarr   = array();   // The placeholders to be replaced
87
            $mappingssourcearr = array();   // To store the original mappings values
88
            $mappingstargetarr = array();   // To store the target mappings values
89
            $toreplace = $this->urltemplate;// The template used to build the replacement
90
            foreach ($this->mappings as $mappingkey => $mappingsource) {
91
                $source = $matches[$mappingkey][$key];          // get source
92
                $mappingssourcearr[$mappingkey] = $source;      // set source arr
93
                $mappingstargetarr[$mappingkey] = 0;            // apply default mapping
94
                $placeholdersarr[$mappingkey] = '$'.$mappingkey;// set the placeholders arr
95
                if (!$mappingsok) {                             // already missing some mapping, continue
96
                    continue;
97
                }
98
                if (!$target = $this->get_mapping($mappingsource, $source)) {// mapping not found, mark and continue
99
                    $mappingsok = false;
100
                    continue;
101
                }
102
                $mappingstargetarr[$mappingkey] = $target;       // store found mapping
103
            }
104
            $toreplace = $this->apply_modifications($toreplace, $mappingsok); // Apply other changes before replacement
105
            if (!$mappingsok) { // Some mapping has failed, apply original values to the template
106
                $toreplace = str_replace($placeholdersarr, $mappingssourcearr, $toreplace);
107
 
108
            } else {            // All mappings found, apply target values to the template
109
                $toreplace = str_replace($placeholdersarr, $mappingstargetarr, $toreplace);
110
            }
111
            if ($this->urlencoded) {
112
                $toreplace = urlencode($toreplace);
113
            }
114
            // Finally, perform the replacement in original content
115
            $content = str_replace($tosearch, $toreplace, $content);
116
        }
117
        return $content; // return the decoded content, pointing to original or target values
118
    }
119
 
120
// Protected API starts here
121
 
122
    /**
123
     * Looks for mapping values in backup_ids table, simple wrapper over get_backup_ids_record
124
     */
125
    protected function get_mapping($itemname, $itemid) {
126
        // Check restoreid is set
127
        if (!$this->restoreid) {
128
            throw new restore_decode_rule_exception('decode_rule_restoreid_not_set');
129
        }
130
        if (!$found = restore_dbops::get_backup_ids_record($this->restoreid, $itemname, $itemid)) {
131
            return false;
132
        }
133
        return $found->newitemid;
134
    }
135
 
136
    /**
137
     * Apply other modifications, based in the result of $mappingsok before placeholder replacements
138
     *
139
     * Right now, simply prefix with the proper wwwroot (source/target)
140
     */
141
    protected function apply_modifications($toreplace, $mappingsok) {
142
        // Check wwwroots are set
143
        if (!$this->targetwwwroot || !$this->sourcewwwroot) {
144
            throw new restore_decode_rule_exception('decode_rule_wwwroots_not_set');
145
        }
146
        return ($mappingsok ? $this->targetwwwroot : $this->sourcewwwroot) . $toreplace;
147
    }
148
 
149
    /**
150
     * Perform all the validations and checks on the rule attributes
151
     */
152
    protected function validate_params($linkname, $urltemplate, $mappings) {
153
        // Check linkname is A-Z0-9
154
        if (empty($linkname) || preg_match('/[^A-Z0-9]/', $linkname)) {
155
            throw new restore_decode_rule_exception('decode_rule_incorrect_name', $linkname);
156
        }
157
        // Look urltemplate starts by /
158
        if (empty($urltemplate) || substr($urltemplate, 0, 1) != '/') {
159
            throw new restore_decode_rule_exception('decode_rule_incorrect_urltemplate', $urltemplate);
160
        }
161
        if (!is_array($mappings)) {
162
            $mappings = array($mappings);
163
        }
164
        // Look for placeholders in template
165
        $countph = preg_match_all('/(\$\d+)/', $urltemplate, $matches);
166
        $countma = count($mappings);
167
        // Check mappings number matches placeholders
168
        if ($countph != $countma) {
169
            $a = new stdClass();
170
            $a->placeholders = $countph;
171
            $a->mappings     = $countma;
172
            throw new restore_decode_rule_exception('decode_rule_mappings_incorrect_count', $a);
173
        }
174
        // Verify they are consecutive (starting on 1)
175
        $smatches = str_replace('$', '', $matches[1]);
176
        sort($smatches, SORT_NUMERIC);
177
        if (reset($smatches) != 1 || end($smatches) != $countma) {
178
            throw new restore_decode_rule_exception('decode_rule_nonconsecutive_placeholders', implode(', ', $smatches));
179
        }
180
        // No dupes in placeholders
181
        if (count($smatches) != count(array_unique($smatches))) {
182
            throw new restore_decode_rule_exception('decode_rule_duplicate_placeholders', implode(', ', $smatches));
183
        }
184
 
185
        // Return one array of placeholders as keys and mappings as values
186
        return array_combine($smatches, $mappings);
187
    }
188
 
189
    /**
190
     * based on rule definition, build the regular expression to execute on decode
191
     */
192
    protected function get_calculated_regexp() {
193
        $regexp = '/\$@' . $this->linkname;
194
        foreach ($this->mappings as $key => $value) {
195
            $regexp .= '\*(\d+)';
196
        }
197
        $regexp .= '@\$/';
198
        return $regexp;
199
    }
200
}
201
 
202
/*
203
 * Exception class used by all the @restore_decode_rule stuff
204
 */
205
class restore_decode_rule_exception extends backup_exception {
206
 
207
    public function __construct($errorcode, $a=NULL, $debuginfo=null) {
208
        return parent::__construct($errorcode, $a, $debuginfo);
209
    }
210
}