Proyectos de Subversion Moodle

Rev

| Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1441 ariadna 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.
13
//
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/>.
16
 
17
namespace core\output;
18
 
19
use core\context\system as context_system;
20
use core\exception\moodle_exception;
21
use core\exception\coding_exception;
22
use core\output\actions\component_action;
23
use moodle_page;
24
use moodle_url;
25
use stdClass;
26
use Mustache_Exception_UnknownTemplateException;
27
 
28
/**
29
 * Simple base class for Moodle renderers.
30
 *
31
 * Tracks the xhtml_container_stack to use, which is passed in in the constructor.
32
 *
33
 * Also has methods to facilitate generating HTML output.
34
 *
35
 * @copyright 2009 Tim Hunt
36
 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
37
 * @since Moodle 2.0
38
 * @package core
39
 * @category output
40
 */
41
class renderer_base {
42
    /**
43
     * @var xhtml_container_stack The xhtml_container_stack to use.
44
     */
45
    protected $opencontainers;
46
 
47
    /**
48
     * @var moodle_page The Moodle page the renderer has been created to assist with.
49
     */
50
    protected $page;
51
 
52
    /**
53
     * @var string The requested rendering target.
54
     */
55
    protected $target;
56
 
57
    /**
58
     * @var \Mustache_Engine The mustache template compiler
59
     */
60
    private $mustache;
61
 
62
    /**
63
     * @var array $templatecache The mustache template cache.
64
     */
65
    protected $templatecache = [];
66
 
67
    /**
68
     * Return an instance of the mustache class.
69
     *
70
     * @since 2.9
71
     * @return \Mustache_Engine
72
     */
73
    protected function get_mustache() {
74
        global $CFG;
75
 
76
        if ($this->mustache === null) {
77
            require_once("{$CFG->libdir}/filelib.php");
78
 
79
            $themename = $this->page->theme->name;
80
            $themerev = theme_get_revision();
81
 
82
            // Create new localcache directory.
83
            $cachedir = make_localcache_directory("mustache/$themerev/$themename");
84
 
85
            // Remove old localcache directories.
86
            $mustachecachedirs = glob("{$CFG->localcachedir}/mustache/*", GLOB_ONLYDIR);
87
            foreach ($mustachecachedirs as $localcachedir) {
88
                $cachedrev = [];
89
                preg_match("/\/mustache\/([0-9]+)$/", $localcachedir, $cachedrev);
90
                $cachedrev = isset($cachedrev[1]) ? intval($cachedrev[1]) : 0;
91
                if ($cachedrev > 0 && $cachedrev < $themerev) {
92
                    fulldelete($localcachedir);
93
                }
94
            }
95
 
96
            $loader = new mustache_filesystem_loader();
97
            $stringhelper = new mustache_string_helper();
98
            $cleanstringhelper = new mustache_clean_string_helper();
99
            $quotehelper = new mustache_quote_helper();
100
            $jshelper = new mustache_javascript_helper($this->page);
101
            $pixhelper = new mustache_pix_helper($this);
102
            $shortentexthelper = new mustache_shorten_text_helper();
103
            $userdatehelper = new mustache_user_date_helper();
104
 
105
            // We only expose the variables that are exposed to JS templates.
106
            $safeconfig = $this->page->requires->get_config_for_javascript($this->page, $this);
107
 
108
            $helpers = ['config' => $safeconfig,
109
                             'str' => [$stringhelper, 'str'],
110
                             'cleanstr' => [$cleanstringhelper, 'cleanstr'],
111
                             'quote' => [$quotehelper, 'quote'],
112
                             'js' => [$jshelper, 'help'],
113
                             'pix' => [$pixhelper, 'pix'],
114
                             'shortentext' => [$shortentexthelper, 'shorten'],
115
                             'userdate' => [$userdatehelper, 'transform'],
116
                         ];
117
 
118
            $this->mustache = new mustache_engine([
119
                'cache' => $cachedir,
120
                'escape' => 's',
121
                'loader' => $loader,
122
                'helpers' => $helpers,
123
                'pragmas' => [\Mustache_Engine::PRAGMA_BLOCKS],
124
                // Don't allow the JavaScript helper to be executed from within another
125
                // helper. If it's allowed it can be used by users to inject malicious
126
                // JS into the page.
127
                'disallowednestedhelpers' => ['js'],
128
                // Disable lambda rendering - content in helpers is already rendered, no need to render it again.
129
                'disable_lambda_rendering' => true,
130
            ]);
131
        }
132
 
133
        return $this->mustache;
134
    }
135
 
136
 
137
    /**
138
     * Constructor
139
     *
140
     * The constructor takes two arguments. The first is the page that the renderer
141
     * has been created to assist with, and the second is the target.
142
     * The target is an additional identifier that can be used to load different
143
     * renderers for different options.
144
     *
145
     * @param moodle_page $page the page we are doing output for.
146
     * @param string $target one of rendering target constants
147
     */
148
    public function __construct(moodle_page $page, $target) {
149
        $this->opencontainers = $page->opencontainers;
150
        $this->page = $page;
151
        $this->target = $target;
152
    }
153
 
154
    /**
155
     * Renders a template by name with the given context.
156
     *
157
     * The provided data needs to be array/stdClass made up of only simple types.
158
     * Simple types are array,stdClass,bool,int,float,string
159
     *
160
     * @since 2.9
161
     * @param string $templatename The template to render
162
     * @param array|stdClass $context Context containing data for the template.
163
     * @return string|boolean
164
     */
165
    public function render_from_template($templatename, $context) {
166
        $mustache = $this->get_mustache();
167
 
168
        if ($mustache->hasHelper('uniqid')) {
169
            // Grab a copy of the existing helper to be restored later.
170
            $uniqidhelper = $mustache->getHelper('uniqid');
171
        } else {
172
            // Helper doesn't exist.
173
            $uniqidhelper = null;
174
        }
175
 
176
        // Provide 1 random value that will not change within a template
177
        // but will be different from template to template. This is useful for
178
        // e.g. aria attributes that only work with id attributes and must be
179
        // unique in a page.
180
        $mustache->addHelper('uniqid', new mustache_uniqid_helper());
181
        if (isset($this->templatecache[$templatename])) {
182
            $template = $this->templatecache[$templatename];
183
        } else {
184
            try {
185
                $template = $mustache->loadTemplate($templatename);
186
                $this->templatecache[$templatename] = $template;
187
            } catch (Mustache_Exception_UnknownTemplateException $e) {
188
                throw new moodle_exception('Unknown template: ' . $templatename);
189
            }
190
        }
191
 
192
        $renderedtemplate = trim($template->render($context));
193
 
194
        // If we had an existing uniqid helper then we need to restore it to allow
195
        // handle nested calls of render_from_template.
196
        if ($uniqidhelper) {
197
            $mustache->addHelper('uniqid', $uniqidhelper);
198
        }
199
 
200
        return $renderedtemplate;
201
    }
202
 
203
 
204
    /**
205
     * Returns rendered widget.
206
     *
207
     * The provided widget needs to be an object that extends the renderable
208
     * interface.
209
     * If will then be rendered by a method based upon the classname for the widget.
210
     * For instance a widget of class `crazywidget` will be rendered by a protected
211
     * render_crazywidget method of this renderer.
212
     * If no render_crazywidget method exists and crazywidget implements templatable,
213
     * look for the 'crazywidget' template in the same component and render that.
214
     *
215
     * @param renderable $widget instance with renderable interface
216
     * @return string
217
     */
218
    public function render(renderable $widget) {
219
        $classparts = explode('\\', get_class($widget));
220
        // Strip namespaces.
221
        $classpartname = array_pop($classparts);
222
        // Remove _renderable suffixes.
223
        $classname = preg_replace('/_renderable$/', '', $classpartname);
224
 
225
        $rendermethods = [];
226
 
227
        // If the renderable is located within a namespace, and that namespace is within the `output` L2 API,
228
        // include the namespace as a possible renderer method name.
229
        if (array_search('output', $classparts) === 1 && count($classparts) > 2) {
230
            $concatenators = array_slice($classparts, 2);
231
            $concatenators[] = $classname;
232
            $rendermethods[] = "render_" . implode('__', $concatenators);
233
        }
234
 
235
        // Fall back to the last part of the class name.
236
        $rendermethods[] = "render_{$classname}";
237
 
238
        foreach ($rendermethods as $rendermethod) {
239
            if (method_exists($this, $rendermethod)) {
240
                // Call the render_[widget_name] function.
241
                // Note: This has a higher priority than the named_templatable to allow the theme to override the template.
242
                return $this->$rendermethod($widget);
243
            }
244
        }
245
 
246
        if ($widget instanceof named_templatable) {
247
            // This is a named templatable.
248
            // Fetch the template name from the get_template_name function instead.
249
            // Note: This has higher priority than the guessed template name.
250
            return $this->render_from_template(
251
                $widget->get_template_name($this),
252
                $widget->export_for_template($this)
253
            );
254
        }
255
 
256
        if ($widget instanceof templatable) {
257
            // Guess the templat ename based on the class name.
258
            // Note: There's no benefit to moving this aboved the named_templatable and this approach is more costly.
259
            $component = array_shift($classparts);
260
            if (!$component) {
261
                $component = 'core';
262
            }
263
            $template = $component . '/' . $classname;
264
            $context = $widget->export_for_template($this);
265
            return $this->render_from_template($template, $context);
266
        }
267
 
268
        $rendermethod = reset($rendermethods);
269
        throw new coding_exception("Can not render widget, renderer method ('{$rendermethod}') not found.");
270
    }
271
 
272
    /**
273
     * Adds a JS action for the element with the provided id.
274
     *
275
     * This method adds a JS event for the provided component action to the page
276
     * and then returns the id that the event has been attached to.
277
     * If no id has been provided then a new ID is generated by {@see html_writer::random_id()}
278
     *
279
     * @param component_action $action
280
     * @param string $id
281
     * @return string id of element, either original submitted or random new if not supplied
282
     */
283
    public function add_action_handler(component_action $action, $id = null) {
284
        if (!$id) {
285
            $id = html_writer::random_id($action->event);
286
        }
287
        $this->page->requires->event_handler("#$id", $action->event, $action->jsfunction, $action->jsfunctionargs);
288
        return $id;
289
    }
290
 
291
    /**
292
     * Returns true is output has already started, and false if not.
293
     *
294
     * @return boolean true if the header has been printed.
295
     */
296
    public function has_started() {
297
        return $this->page->state >= moodle_page::STATE_IN_BODY;
298
    }
299
 
300
    /**
301
     * Given an array or space-separated list of classes, prepares and returns the HTML class attribute value
302
     *
303
     * @param mixed $classes Space-separated string or array of classes
304
     * @return string HTML class attribute value
305
     */
306
    public static function prepare_classes($classes) {
307
        if (is_array($classes)) {
308
            return implode(' ', array_unique($classes));
309
        }
310
        return $classes;
311
    }
312
 
313
    /**
314
     * Return the direct URL for an image from the pix folder.
315
     *
316
     * Use this function sparingly and never for icons. For icons use pix_icon or the pix helper in a mustache template.
317
     *
318
     * @deprecated since Moodle 3.3
319
     * @param string $imagename the name of the icon.
320
     * @param string $component specification of one plugin like in get_string()
321
     * @return moodle_url
322
     */
323
    public function pix_url($imagename, $component = 'moodle') {
324
        debugging('pix_url is deprecated. Use image_url for images and pix_icon for icons.', DEBUG_DEVELOPER);
325
        return $this->page->theme->image_url($imagename, $component);
326
    }
327
 
328
    /**
329
     * Return the moodle_url for an image.
330
     *
331
     * The exact image location and extension is determined
332
     * automatically by searching for gif|png|jpg|jpeg, please
333
     * note there can not be diferent images with the different
334
     * extension. The imagename is for historical reasons
335
     * a relative path name, it may be changed later for core
336
     * images. It is recommended to not use subdirectories
337
     * in plugin and theme pix directories.
338
     *
339
     * There are three types of images:
340
     * 1/ theme images  - stored in theme/mytheme/pix/,
341
     *                    use component 'theme'
342
     * 2/ core images   - stored in /pix/,
343
     *                    overridden via theme/mytheme/pix_core/
344
     * 3/ plugin images - stored in mod/mymodule/pix,
345
     *                    overridden via theme/mytheme/pix_plugins/mod/mymodule/,
346
     *                    example: image_url('comment', 'mod_glossary')
347
     *
348
     * @param string $imagename the pathname of the image
349
     * @param string $component full plugin name (aka component) or 'theme'
350
     * @return moodle_url
351
     */
352
    public function image_url($imagename, $component = 'moodle') {
353
        return $this->page->theme->image_url($imagename, $component);
354
    }
355
 
356
    /**
357
     * Return the site's logo URL, if any.
358
     *
359
     * @param int $maxwidth The maximum width, or null when the maximum width does not matter.
360
     * @param int $maxheight The maximum height, or null when the maximum height does not matter.
361
     * @return moodle_url|false
362
     */
363
    public function get_logo_url($maxwidth = null, $maxheight = 200) {
364
        global $CFG;
365
        $logo = get_config('core_admin', 'logo');
366
        if (empty($logo)) {
367
            return false;
368
        }
369
 
370
        // 200px high is the default image size which should be displayed at 100px in the page to account for retina displays.
371
        // It's not worth the overhead of detecting and serving 2 different images based on the device.
372
 
373
        // Hide the requested size in the file path.
374
        $filepath = ((int) $maxwidth . 'x' . (int) $maxheight) . '/';
375
 
376
        // Use $CFG->themerev to prevent browser caching when the file changes.
377
        return moodle_url::make_pluginfile_url(
378
            context_system::instance()->id,
379
            'core_admin',
380
            'logo',
381
            $filepath,
382
            theme_get_revision(),
383
            $logo
384
        );
385
    }
386
 
387
    /**
388
     * Return the site's compact logo URL, if any.
389
     *
390
     * @param int $maxwidth The maximum width, or null when the maximum width does not matter.
391
     * @param int $maxheight The maximum height, or null when the maximum height does not matter.
392
     * @return moodle_url|false
393
     */
394
    public function get_compact_logo_url($maxwidth = 300, $maxheight = 300) {
395
        global $CFG;
396
        $logo = get_config('core_admin', 'logocompact');
397
        if (empty($logo)) {
398
            return false;
399
        }
400
 
401
        // Hide the requested size in the file path.
402
        $filepath = ((int) $maxwidth . 'x' . (int) $maxheight) . '/';
403
 
404
        // Use $CFG->themerev to prevent browser caching when the file changes.
405
        return moodle_url::make_pluginfile_url(
406
            context_system::instance()->id,
407
            'core_admin',
408
            'logocompact',
409
            $filepath,
410
            theme_get_revision(),
411
            $logo
412
        );
413
    }
414
 
415
    /**
416
     * Whether we should display the logo in the navbar.
417
     *
418
     * We will when there are no main logos, and we have compact logo.
419
     *
420
     * @return bool
421
     */
422
    public function should_display_navbar_logo() {
423
        $logo = $this->get_compact_logo_url();
424
        return !empty($logo);
425
    }
426
 
427
    /**
428
     * @deprecated since Moodle 4.0
429
     */
430
    #[\core\attribute\deprecated(null, reason: 'It is no longer used', since: '4.0', final: true)]
431
    public function should_display_main_logo() {
432
        \core\deprecation::emit_deprecation([self::class, __FUNCTION__]);
433
    }
434
 
435
    /**
436
     * Returns the moodle page object.
437
     *
438
     * @return moodle_page
439
     */
440
    public function get_page(): moodle_page {
441
        return $this->page;
442
    }
443
}
444
 
445
// Alias this class to the old name.
446
// This file will be autoloaded by the legacyclasses autoload system.
447
// In future all uses of this class will be corrected and the legacy references will be removed.
448
class_alias(renderer_base::class, \renderer_base::class);