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
25defined('MOODLE_INTERNAL') || die();
26
27/**
28 * Helper class used to restore logs, converting all the information as needed
29 *
30 * This class allows each restore task to specify which logs (by action) will
31 * be handled on restore and which transformations will be performed in order
32 * to accomodate them into their new destination
33 *
34 * TODO: Complete phpdocs
35 */
36class restore_log_rule implements processable {
37
38    protected $module;   // module of the log record
39    protected $action;   // action of the log record
40
41    protected $urlread;   // url format of the log record in backup file
42    protected $inforead;  // info format of the log record in backup file
43
44    protected $modulewrite;// module of the log record to be written (defaults to $module if not specified)
45    protected $actionwrite;// action of the log record to be written (defaults to $action if not specified)
46
47    protected $urlwrite; // url format of the log record to be written (defaults to $urlread if not specified)
48    protected $infowrite;// info format of the log record to be written (defaults to $inforead if not specified)
49
50    protected $urlreadregexp; // Regexps for extracting information from url and info
51    protected $inforeadregexp;
52
53    protected $allpairs; // to acummulate all tokens and values pairs on each log record restored
54
55    protected $urltokens; // tokens present int the $urlread attribute
56    protected $infotokens;// tokens present in the $inforead attribute
57
58    protected $fixedvalues;    // Some values that will have precedence over mappings to save tons of DB mappings
59
60    protected $restoreid;
61
62    public function __construct($module, $action, $urlread, $inforead,
63                                $modulewrite = null, $actionwrite = null, $urlwrite = null, $infowrite = null) {
64        $this->module    = $module;
65        $this->action    = $action;
66        $this->urlread   = $urlread;
67        $this->inforead  = $inforead;
68        $this->modulewrite = is_null($modulewrite) ? $module : $modulewrite;
69        $this->actionwrite= is_null($actionwrite) ? $action : $actionwrite;
70        $this->urlwrite = is_null($urlwrite) ? $urlread : $urlwrite;
71        $this->infowrite= is_null($infowrite) ? $inforead : $infowrite;
72        $this->allpairs = array();
73        $this->urltokens = array();
74        $this->infotokens= array();
75        $this->urlreadregexp = null;
76        $this->inforeadregexp = null;
77        $this->fixedvalues = array();
78        $this->restoreid = null;
79
80        // TODO: validate module, action are valid => exception
81
82        // Calculate regexps and tokens, both for urlread and inforead
83        $this->calculate_url_regexp($this->urlread);
84        $this->calculate_info_regexp($this->inforead);
85    }
86
87    public function set_restoreid($restoreid) {
88        $this->restoreid = $restoreid;
89    }
90
91    public function set_fixed_values($values) {
92        //TODO: check $values is array => exception
93        $this->fixedvalues = $values;
94    }
95
96    public function get_key_name() {
97        return $this->module . '-' . $this->action;
98    }
99
100    public function process($inputlog) {
101
102        // There might be multiple rules that process this log, we can't alter it in the process of checking it.
103        $log = clone($inputlog);
104
105        // Reset the allpairs array
106        $this->allpairs = array();
107
108        $urlmatches  = array();
109        $infomatches = array();
110        // Apply urlreadregexp to the $log->url if necessary
111        if ($this->urlreadregexp) {
112            preg_match($this->urlreadregexp, $log->url, $urlmatches);
113            if (empty($urlmatches)) {
114                return false;
115            }
116        } else {
117            if (!is_null($this->urlread)) { // If not null, use it (null means unmodified)
118                $log->url = $this->urlread;
119            }
120        }
121        // Apply inforeadregexp to the $log->info if necessary
122        if ($this->inforeadregexp) {
123            preg_match($this->inforeadregexp, $log->info, $infomatches);
124            if (empty($infomatches)) {
125                return false;
126            }
127        } else {
128            if (!is_null($this->inforead)) { // If not null, use it (null means unmodified)
129                $log->info = $this->inforead;
130            }
131        }
132
133        // If there are $urlmatches, let's process them
134        if (!empty($urlmatches)) {
135            array_shift($urlmatches); // Take out first element
136            if (count($urlmatches) !== count($this->urltokens)) { // Number of matches must be number of tokens
137                return false;
138            }
139            // Let's process all the tokens and matches, using them to parse the urlwrite
140            $log->url = $this->parse_tokens_and_matches($this->urltokens, $urlmatches, $this->urlwrite);
141        }
142
143        // If there are $infomatches, let's process them
144        if (!empty($infomatches)) {
145            array_shift($infomatches); // Take out first element
146            if (count($infomatches) !== count($this->infotokens)) { // Number of matches must be number of tokens
147                return false;
148            }
149            // Let's process all the tokens and matches, using them to parse the infowrite
150            $log->info = $this->parse_tokens_and_matches($this->infotokens, $infomatches, $this->infowrite);
151        }
152
153        // Arrived here, if there is any pending token in $log->url or $log->info, stop
154        if ($this->extract_tokens($log->url) || $this->extract_tokens($log->info)) {
155            return false;
156        }
157
158        // Finally, set module and action
159        $log->module = $this->modulewrite;
160        $log->action = $this->actionwrite;
161
162        return $log;
163    }
164
165// Protected API starts here
166
167    protected function parse_tokens_and_matches($tokens, $values, $content) {
168
169        $pairs = array_combine($tokens, $values);
170        ksort($pairs); // First literals, then mappings
171        foreach ($pairs as $token => $value) {
172            // If one token has already been processed, continue
173            if (array_key_exists($token, $this->allpairs)) {
174                continue;
175            }
176
177            // If the pair is one literal token, just keep it unmodified
178            if (substr($token, 0, 1) == '[') {
179                $this->allpairs[$token] = $value;
180
181            // If the pair is one mapping token, let's process it
182            } else if (substr($token, 0, 1) == '{') {
183                $ctoken = $token;
184
185                // First, resolve mappings to literals if necessary
186                if (substr($token, 1, 1) == '[') {
187                    $literaltoken = trim($token, '{}');
188                    if (array_key_exists($literaltoken, $this->allpairs)) {
189                        $ctoken = '{' . $this->allpairs[$literaltoken] . '}';
190                    }
191                }
192
193                // Look for mapping in fixedvalues before going to DB
194                $plaintoken = trim($ctoken, '{}');
195                if (array_key_exists($plaintoken, $this->fixedvalues)) {
196                    $this->allpairs[$token] = $this->fixedvalues[$plaintoken];
197
198                 // Last chance, fetch value from backup_ids_temp, via mapping
199                } else {
200                    if ($mapping = restore_dbops::get_backup_ids_record($this->restoreid, $plaintoken, $value)) {
201                        $this->allpairs[$token] = $mapping->newitemid;
202                    }
203                }
204            }
205        }
206
207        // Apply all the conversions array (allpairs) to content
208        krsort($this->allpairs); // First mappings, then literals
209        $content = str_replace(array_keys($this->allpairs), $this->allpairs, $content);
210
211        return $content;
212    }
213
214    protected function calculate_url_regexp($urlexpression) {
215        // Detect all the tokens in the expression
216        if ($tokens = $this->extract_tokens($urlexpression)) {
217            $this->urltokens = $tokens;
218            // Now, build the regexp
219            $this->urlreadregexp = $this->build_regexp($urlexpression, $this->urltokens);
220        }
221    }
222
223    protected function calculate_info_regexp($infoexpression) {
224        // Detect all the tokens in the expression
225        if ($tokens = $this->extract_tokens($infoexpression)) {
226            $this->infotokens = $tokens;
227            // Now, build the regexp
228            $this->inforeadregexp = $this->build_regexp($infoexpression, $this->infotokens);
229        }
230    }
231
232    protected function extract_tokens($expression) {
233        // Extract all the tokens enclosed in square and curly brackets
234        preg_match_all('~\[[^\]]+\]|\{[^\}]+\}~', $expression, $matches);
235        return $matches[0];
236    }
237
238    protected function build_regexp($expression, $tokens) {
239        // Replace to temp (and preg_quote() safe) placeholders
240        foreach ($tokens as $token) {
241            $expression = preg_replace('~' . preg_quote($token, '~') . '~', '%@@%@@%', $expression, 1);
242        }
243        // quote the expression
244        $expression = preg_quote($expression, '~');
245        // Replace all the placeholders
246        $expression = preg_replace('~%@@%@@%~', '(.*)', $expression);
247        return '~' . $expression . '~';
248    }
249}
250