Dotclear

source: inc/admin/lib.dc.page.php @ 3934:eab07f30f99b

Revision 3934:eab07f30f99b, 40.0 KB checked in by franck <carnet.franck.paul@…>, 7 years ago (diff)

Switching from inline JS variables to JSON script. CodeMirror? is on stage

Line 
1<?php
2/**
3 * @package Dotclear
4 * @subpackage Backend
5 *
6 * @copyright Olivier Meunier & Association Dotclear
7 * @copyright GPL-2.0-only
8 */
9
10if (!defined('DC_RC_PATH')) {return;}
11
12define('DC_AUTH_PAGE', 'auth.php');
13
14class dcPage
15{
16    private static $loaded_js     = [];
17    private static $loaded_css    = [];
18    private static $xframe_loaded = false;
19
20    private static function getCore()
21    {
22        return $GLOBALS['core'];
23    }
24
25    # Auth check
26    public static function check($permissions)
27    {
28        $core = self::getCore();
29
30        if ($core->blog && $core->auth->check($permissions, $core->blog->id)) {
31            return;
32        }
33
34        if (session_id()) {
35            $core->session->destroy();
36        }
37        http::redirect(DC_AUTH_PAGE);
38    }
39
40    # Check super admin
41    public static function checkSuper()
42    {
43        $core = self::getCore();
44
45        if (!$core->auth->isSuperAdmin()) {
46            if (session_id()) {
47                $core->session->destroy();
48            }
49            http::redirect(DC_AUTH_PAGE);
50        }
51    }
52
53    # Top of admin page
54    public static function open($title = '', $head = '', $breadcrumb = '', $options = [])
55    {
56        $core = self::getCore();
57        $js   = [];
58
59        # List of user's blogs
60        if ($core->auth->getBlogCount() == 1 || $core->auth->getBlogCount() > 20) {
61            $blog_box =
62            '<p>' . __('Blog:') . ' <strong title="' . html::escapeHTML($core->blog->url) . '">' .
63            html::escapeHTML($core->blog->name) . '</strong>';
64
65            if ($core->auth->getBlogCount() > 20) {
66                $blog_box .= ' - <a href="' . $core->adminurl->get("admin.blogs") . '">' . __('Change blog') . '</a>';
67            }
68            $blog_box .= '</p>';
69        } else {
70            $rs_blogs = $core->getBlogs(['order' => 'LOWER(blog_name)', 'limit' => 20]);
71            $blogs    = [];
72            while ($rs_blogs->fetch()) {
73                $blogs[html::escapeHTML($rs_blogs->blog_name . ' - ' . $rs_blogs->blog_url)] = $rs_blogs->blog_id;
74            }
75            $blog_box = '<p><label for="switchblog" class="classic">' . __('Blogs:') . '</label> ' .
76            $core->formNonce() . form::combo('switchblog', $blogs, $core->blog->id) .
77            '<input type="submit" value="' . __('ok') . '" class="hidden-if-js" /></p>';
78        }
79
80        $safe_mode = isset($_SESSION['sess_safe_mode']) && $_SESSION['sess_safe_mode'];
81
82        # Display
83        $headers = new ArrayObject([]);
84
85        # Content-Type
86        $headers['content-type'] = 'Content-Type: text/html; charset=UTF-8';
87
88        # Referrer Policy for admin pages
89        $headers['referrer'] = 'Referrer-Policy: strict-origin';
90
91        # Prevents Clickjacking as far as possible
92        if (isset($options['x-frame-allow'])) {
93            self::setXFrameOptions($headers, $options['x-frame-allow']);
94        } else {
95            self::setXFrameOptions($headers);
96        }
97
98        # Content-Security-Policy (only if safe mode if not active, it may help)
99        if (!$safe_mode && $core->blog->settings->system->csp_admin_on) {
100            // Get directives from settings if exist, else set defaults
101            $csp = new ArrayObject([]);
102
103                                                                                // SQlite Clearbricks driver does not allow using single quote at beginning or end of a field value
104                                                                                // so we have to use neutral values (localhost and 127.0.0.1) for some CSP directives
105            $csp_prefix = $core->con->syntax() == 'sqlite' ? 'localhost ' : ''; // Hack for SQlite Clearbricks syntax
106            $csp_suffix = $core->con->syntax() == 'sqlite' ? ' 127.0.0.1' : ''; // Hack for SQlite Clearbricks syntax
107
108            $csp['default-src'] = $core->blog->settings->system->csp_admin_default ?:
109            $csp_prefix . "'self'" . $csp_suffix;
110            $csp['script-src'] = $core->blog->settings->system->csp_admin_script ?:
111            $csp_prefix . "'self' 'unsafe-inline' 'unsafe-eval'" . $csp_suffix;
112            $csp['style-src'] = $core->blog->settings->system->csp_admin_style ?:
113            $csp_prefix . "'self' 'unsafe-inline'" . $csp_suffix;
114            $csp['img-src'] = $core->blog->settings->system->csp_admin_img ?:
115            $csp_prefix . "'self' data: http://media.dotaddict.org blob:";
116
117            # Cope with blog post preview (via public URL in iframe)
118            if (!is_null($core->blog->host)) {
119                $csp['default-src'] .= ' ' . parse_url($core->blog->host, PHP_URL_HOST);
120                $csp['script-src'] .= ' ' . parse_url($core->blog->host, PHP_URL_HOST);
121                $csp['style-src'] .= ' ' . parse_url($core->blog->host, PHP_URL_HOST);
122            }
123            # Cope with media display in media manager (via public URL)
124            if (!is_null($core->media)) {
125                $csp['img-src'] .= ' ' . parse_url($core->media->root_url, PHP_URL_HOST);
126            } elseif (!is_null($core->blog->host)) {
127                // Let's try with the blog URL
128                $csp['img-src'] .= ' ' . parse_url($core->blog->host, PHP_URL_HOST);
129            }
130            # Allow everything in iframe (used by editors to preview public content)
131            $csp['child-src'] = "*";
132
133            # --BEHAVIOR-- adminPageHTTPHeaderCSP
134            $core->callBehavior('adminPageHTTPHeaderCSP', $csp);
135
136            // Construct CSP header
137            $directives = [];
138            foreach ($csp as $key => $value) {
139                if ($value) {
140                    $directives[] = $key . ' ' . $value;
141                }
142            }
143            if (count($directives)) {
144                if (version_compare(phpversion(), '5.4', '>=')) {
145                    // csp_report.php needs PHP ≥ 5.4
146                    $directives[] = "report-uri " . DC_ADMIN_URL . "csp_report.php";
147                }
148                $report_only    = ($core->blog->settings->system->csp_admin_report_only) ? '-Report-Only' : '';
149                $headers['csp'] = "Content-Security-Policy" . $report_only . ": " . implode(" ; ", $directives);
150            }
151        }
152
153        # --BEHAVIOR-- adminPageHTTPHeaders
154        $core->callBehavior('adminPageHTTPHeaders', $headers);
155        foreach ($headers as $key => $value) {
156            header($value);
157        }
158
159        echo
160        '<!DOCTYPE html>' .
161        '<html lang="' . $core->auth->getInfo('user_lang') . '">' . "\n" .
162        "<head>\n" .
163        '  <meta charset="UTF-8" />' . "\n" .
164        '  <meta name="ROBOTS" content="NOARCHIVE,NOINDEX,NOFOLLOW" />' . "\n" .
165        '  <meta name="GOOGLEBOT" content="NOSNIPPET" />' . "\n" .
166        '  <meta name="viewport" content="width=device-width, initial-scale=1.0" />' . "\n" .
167        '  <title>' . $title . ' - ' . html::escapeHTML($core->blog->name) . ' - ' . html::escapeHTML(DC_VENDOR_NAME) . ' - ' . DC_VERSION . '</title>' . "\n";
168
169        if ($core->auth->user_prefs->interface->darkmode) {
170            $js['darkMode'] = 1;
171            echo self::cssLoad('style/default-dark.css');
172        } else {
173            $js['darkMode'] = 0;
174            echo self::cssLoad('style/default.css');
175        }
176        if (l10n::getTextDirection($GLOBALS['_lang']) == 'rtl') {
177            echo self::cssLoad('style/default-rtl.css');
178        }
179
180        $core->auth->user_prefs->addWorkspace('interface');
181        if (!$core->auth->user_prefs->interface->hide_std_favicon) {
182            echo
183                '<link rel="icon" type="image/png" href="images/favicon96-login.png" />' . "\n" .
184                '<link rel="shortcut icon" href="images/favicon.ico" type="image/x-icon" />' . "\n";
185        }
186        if ($core->auth->user_prefs->interface->htmlfontsize) {
187            $js['htmlFontSize'] = $core->auth->user_prefs->interface->htmlfontsize;
188        }
189        $js['hideMoreInfo']   = (boolean) $core->auth->user_prefs->interface->hidemoreinfo;
190        $js['showAjaxLoader'] = (boolean) $core->auth->user_prefs->interface->showajaxloader;
191
192        $core->auth->user_prefs->addWorkspace('accessibility');
193        $js['noDragDrop'] = (boolean) $core->auth->user_prefs->accessibility->nodragdrop;
194
195        // Set some JSON data
196        echo dcUtils::jsJson('dotclear_init', $js);
197
198        echo
199        self::jsCommon() .
200        self::jsToggles() .
201            $head;
202
203        # --BEHAVIOR-- adminPageHTMLHead
204        $core->callBehavior('adminPageHTMLHead');
205
206        echo
207        "</head>\n" .
208        '<body id="dotclear-admin' .
209        ($safe_mode ? ' safe-mode' : '') . '" class="no-js' .
210        ($core->auth->user_prefs->interface->dynfontsize ? ' responsive-font' : '') . '">' . "\n" .
211
212        '<ul id="prelude">' .
213        '<li><a href="#content">' . __('Go to the content') . '</a></li>' .
214        '<li><a href="#main-menu">' . __('Go to the menu') . '</a></li>' .
215        '<li><a href="#help">' . __('Go to help') . '</a></li>' .
216        '</ul>' . "\n" .
217        '<header id="header" role="banner">' .
218        '<h1><a href="' . $core->adminurl->get("admin.home") . '"><span class="hidden">' . DC_VENDOR_NAME . '</span></a></h1>' . "\n";
219
220        echo
221        '<form action="' . $core->adminurl->get("admin.home") . '" method="post" id="top-info-blog">' .
222        $blog_box .
223        '<p><a href="' . $core->blog->url . '" class="outgoing" title="' . __('Go to site') .
224        '">' . __('Go to site') . '<img src="images/outgoing-link.svg" alt="" /></a>' .
225        '</p></form>' .
226        '<ul id="top-info-user">' .
227        '<li><a class="' . (preg_match('/' . preg_quote($core->adminurl->get('admin.home')) . '$/', $_SERVER['REQUEST_URI']) ? ' active' : '') . '" href="' . $core->adminurl->get("admin.home") . '">' . __('My dashboard') . '</a></li>' .
228        '<li><a class="smallscreen' . (preg_match('/' . preg_quote($core->adminurl->get('admin.user.preferences')) . '(\?.*)?$/', $_SERVER['REQUEST_URI']) ? ' active' : '') .
229        '" href="' . $core->adminurl->get("admin.user.preferences") . '">' . __('My preferences') . '</a></li>' .
230        '<li><a href="' . $core->adminurl->get("admin.home", ['logout' => 1]) . '" class="logout"><span class="nomobile">' . sprintf(__('Logout %s'), $core->auth->userID()) .
231            '</span><img src="images/logout.png" alt="" /></a></li>' .
232            '</ul>' .
233            '</header>'; // end header
234
235        echo
236        '<div id="wrapper" class="clearfix">' . "\n" .
237        '<div class="hidden-if-no-js collapser-box"><button type="button" id="collapser" class="void-btn">' .
238        '<img class="collapse-mm visually-hidden" src="images/collapser-hide.png" alt="' . __('Hide main menu') . '" />' .
239        '<img class="expand-mm visually-hidden" src="images/collapser-show.png" alt="' . __('Show main menu') . '" />' .
240            '</button></div>' .
241            '<main id="main" role="main">' . "\n" .
242            '<div id="content" class="clearfix">' . "\n";
243
244        # Safe mode
245        if ($safe_mode) {
246            echo
247            '<div class="warning" role="alert"><h3>' . __('Safe mode') . '</h3>' .
248            '<p>' . __('You are in safe mode. All plugins have been temporarily disabled. Remind to log out then log in again normally to get back all functionalities') . '</p>' .
249                '</div>';
250        }
251
252        // Display breadcrumb (if given) before any error messages
253        echo $breadcrumb;
254
255        // Display notices and errors
256        echo $core->notices->getNotices();
257    }
258
259    /**
260    @deprecated Please use $core->notices->getNotices()
261     **/
262    public static function notices()
263    {
264        $core = self::getCore();
265        return $core->notices->getNotices();
266    }
267
268    /**
269    @deprecated Please use $core->notices->addNotice()
270     **/
271    public static function addNotice($type, $message, $options = [])
272    {
273        $core = self::getCore();
274        $core->notices->addNotice($type, $message, $options);
275    }
276
277    /**
278    @deprecated Please use $core->notices->addSuccessNotice()
279     **/
280    public static function addSuccessNotice($message, $options = [])
281    {
282        self::addNotice("success", $message, $options);
283    }
284
285    /**
286    @deprecated Please use $core->notices->addWarningNotice()
287     **/
288    public static function addWarningNotice($message, $options = [])
289    {
290        self::addNotice("warning", $message, $options);
291    }
292
293    /**
294    @deprecated Please use $core->notices->addErrorNotice()
295     **/
296    public static function addErrorNotice($message, $options = [])
297    {
298        self::addNotice("error", $message, $options);
299    }
300
301    public static function close()
302    {
303        $core = self::getCore();
304
305        if (!$GLOBALS['__resources']['ctxhelp']) {
306            if (!$core->auth->user_prefs->interface->hidehelpbutton) {
307                echo
308                '<p id="help-button"><a href="' . $core->adminurl->get("admin.help") . '" class="outgoing" title="' .
309                __('Global help') . '">' . __('Global help') . '</a></p>';
310            }
311        }
312
313        $menu = &$GLOBALS['_menu'];
314
315        echo
316        "</div>\n" .  // End of #content
317        "</main>\n" . // End of #main
318
319        '<nav id="main-menu" role="navigation">' . "\n" .
320
321        '<form id="search-menu" action="' . $core->adminurl->get("admin.search") . '" method="get" role="search">' .
322        '<p><label for="qx" class="hidden">' . __('Search:') . ' </label>' . form::field('qx', 30, 255, '') .
323        '<input type="submit" value="' . __('OK') . '" /></p>' .
324            '</form>';
325
326        foreach ($menu as $k => $v) {
327            echo $menu[$k]->draw();
328        }
329
330        $text = sprintf(__('Thank you for using %s.'), 'Dotclear ' . DC_VERSION);
331
332        # --BEHAVIOR-- adminPageFooter
333        $textAlt = $core->callBehavior('adminPageFooter', $core, $text);
334        if ($textAlt != '') {
335            $text = $textAlt;
336        }
337        $text = html::escapeHTML($text);
338
339        echo
340        '</nav>' . "\n" . // End of #main-menu
341        "</div>\n";       // End of #wrapper
342
343        echo '<p id="gototop"><a href="#wrapper">' . __('Page top') . '</a></p>' . "\n";
344
345        $figure = "
346  ♥‿♥
347              |    |    |
348             )_)  )_)  )_)
349            )___))___))___)\
350           )____)____)_____)\\
351         _____|____|____|____\\\__
352---------\                   /---------
353  ^^^^^ ^^^^^^^^^^^^^^^^^^^^^
354    ^^^^      ^^^^     ^^^    ^^
355         ^^^^      ^^^
356  ";
357
358        echo
359            '<footer id="footer" role="contentinfo">' .
360            '<a href="http://dotclear.org/" title="' . $text . '">' .
361            '<img src="style/dc_logos/w-dotclear90.png" alt="' . $text . '" /></a></footer>' . "\n" .
362            "<!-- " . "\n" .
363            $figure .
364            " -->" . "\n";
365
366        if (defined('DC_DEV') && DC_DEV === true) {
367            echo self::debugInfo();
368        }
369
370        echo
371            '</body></html>';
372    }
373
374    public static function openPopup($title = '', $head = '', $breadcrumb = '')
375    {
376        $core = self::getCore();
377        $js   = [];
378
379        # Display
380        header('Content-Type: text/html; charset=UTF-8');
381
382        # Referrer Policy for admin pages
383        header('Referrer-Policy: strict-origin');
384
385        # Prevents Clickjacking as far as possible
386        header('X-Frame-Options: SAMEORIGIN'); // FF 3.6.9+ Chrome 4.1+ IE 8+ Safari 4+ Opera 10.5+
387
388        echo
389        '<!DOCTYPE html>' .
390        '<html lang="' . $core->auth->getInfo('user_lang') . '">' . "\n" .
391        "<head>\n" .
392        '  <meta charset="UTF-8" />' . "\n" .
393        '  <meta name="viewport" content="width=device-width, initial-scale=1.0" />' . "\n" .
394        '  <title>' . $title . ' - ' . html::escapeHTML($core->blog->name) . ' - ' . html::escapeHTML(DC_VENDOR_NAME) . ' - ' . DC_VERSION . '</title>' . "\n" .
395            '  <meta name="ROBOTS" content="NOARCHIVE,NOINDEX,NOFOLLOW" />' . "\n" .
396            '  <meta name="GOOGLEBOT" content="NOSNIPPET" />' . "\n";
397
398        if ($core->auth->user_prefs->interface->darkmode) {
399            $js['darkMode'] = 1;
400            echo self::cssLoad('style/default-dark.css');
401        } else {
402            $js['darkMode'] = 0;
403            echo self::cssLoad('style/default.css');
404        }
405        if (l10n::getTextDirection($GLOBALS['_lang']) == 'rtl') {
406            echo self::cssLoad('style/default-rtl.css');
407        }
408
409        $core->auth->user_prefs->addWorkspace('interface');
410        if ($core->auth->user_prefs->interface->htmlfontsize) {
411            $js['htmlFontSize'] = $core->auth->user_prefs->interface->htmlfontsize;
412        }
413        $js['hideMoreInfo']   = (boolean) $core->auth->user_prefs->interface->hidemoreinfo;
414        $js['showAjaxLoader'] = (boolean) $core->auth->user_prefs->interface->showajaxloader;
415
416        $core->auth->user_prefs->addWorkspace('accessibility');
417        $js['noDragDrop'] = (boolean) $core->auth->user_prefs->accessibility->nodragdrop;
418
419        // Set JSON data
420        echo dcUtils::jsJson('dotclear_init', $js);
421
422        echo
423        self::jsCommon() .
424        self::jsToggles() .
425            $head;
426
427        # --BEHAVIOR-- adminPageHTMLHead
428        $core->callBehavior('adminPageHTMLHead');
429
430        echo
431            "</head>\n" .
432            '<body id="dotclear-admin" class="popup' .
433            ($core->auth->user_prefs->interface->dynfontsize ? ' responsive-font' : '') . '">' . "\n" .
434
435            '<h1>' . DC_VENDOR_NAME . '</h1>' . "\n";
436
437        echo
438            '<div id="wrapper">' . "\n" .
439            '<main id="main" role="main">' . "\n" .
440            '<div id="content">' . "\n";
441
442        // display breadcrumb if given
443        echo $breadcrumb;
444
445        // Display notices and errors
446        echo $core->notices->getNotices();
447    }
448
449    public static function closePopup()
450    {
451        echo
452        "</div>\n" .  // End of #content
453        "</main>\n" . // End of #main
454        "</div>\n" .  // End of #wrapper
455
456        '<p id="gototop"><a href="#wrapper">' . __('Page top') . '</a></p>' . "\n" .
457
458            '<footer id="footer" role="contentinfo"><p>&nbsp;</p></footer>' . "\n" .
459            '</body></html>';
460    }
461
462    public static function breadcrumb($elements = null, $options = [])
463    {
464        $core = self::getCore();
465
466        $with_home_link = isset($options['home_link']) ? $options['home_link'] : true;
467        $hl             = isset($options['hl']) ? $options['hl'] : true;
468        $hl_pos         = isset($options['hl_pos']) ? $options['hl_pos'] : -1;
469        // First item of array elements should be blog's name, System or Plugins
470        $res = '<h2>' . ($with_home_link ?
471            '<a class="go_home" href="' . $core->adminurl->get("admin.home") . '"><img src="style/dashboard.png" alt="' . __('Go to dashboard') . '" /></a>' :
472            '<img src="style/dashboard-alt.png" alt="" />');
473        $index = 0;
474        if ($hl_pos < 0) {
475            $hl_pos = count($elements) + $hl_pos;
476        }
477        foreach ($elements as $element => $url) {
478            if ($hl && $index == $hl_pos) {
479                $element = sprintf('<span class="page-title">%s</span>', $element);
480            }
481            $res .= ($with_home_link ? ($index == 1 ? ' : ' : ' &rsaquo; ') : ($index == 0 ? ' ' : ' &rsaquo; ')) .
482                ($url ? '<a href="' . $url . '">' : '') . $element . ($url ? '</a>' : '');
483            $index++;
484        }
485        $res .= '</h2>';
486        return $res;
487    }
488
489    /**
490    @deprecated Please use $core->notices->message()
491     **/
492    public static function message($msg, $timestamp = true, $div = false, $echo = true, $class = 'message')
493    {
494        $core = self::getCore();
495        return $core->notices->message($msg, $timestamp, $div, $echo, $class);
496    }
497
498    /**
499    @deprecated Please use $core->notices->success()
500     **/
501    public static function success($msg, $timestamp = true, $div = false, $echo = true)
502    {
503        return self::message($msg, $timestamp, $div, $echo, "success");
504    }
505
506    /**
507    @deprecated Please use $core->notices->warning()
508     **/
509    public static function warning($msg, $timestamp = true, $div = false, $echo = true)
510    {
511        return self::message($msg, $timestamp, $div, $echo, "warning-msg");
512    }
513
514    private static function debugInfo()
515    {
516        $global_vars = implode(', ', array_keys($GLOBALS));
517
518        $res =
519        '<div id="debug"><div>' .
520        '<p>memory usage: ' . memory_get_usage() . ' (' . files::size(memory_get_usage()) . ')</p>';
521
522        if (function_exists('xdebug_get_profiler_filename')) {
523            $res .= '<p>Elapsed time: ' . xdebug_time_index() . ' seconds</p>';
524
525            $prof_file = xdebug_get_profiler_filename();
526            if ($prof_file) {
527                $res .= '<p>Profiler file : ' . xdebug_get_profiler_filename() . '</p>';
528            } else {
529                $prof_url = http::getSelfURI();
530                $prof_url .= (strpos($prof_url, '?') === false) ? '?' : '&';
531                $prof_url .= 'XDEBUG_PROFILE';
532                $res .= '<p><a href="' . html::escapeURL($prof_url) . '">Trigger profiler</a></p>';
533            }
534
535            /* xdebug configuration:
536        zend_extension = /.../xdebug.so
537        xdebug.auto_trace = On
538        xdebug.trace_format = 0
539        xdebug.trace_options = 1
540        xdebug.show_mem_delta = On
541        xdebug.profiler_enable = 0
542        xdebug.profiler_enable_trigger = 1
543        xdebug.profiler_output_dir = /tmp
544        xdebug.profiler_append = 0
545        xdebug.profiler_output_name = timestamp
546         */
547        }
548
549        $res .=
550            '<p>Global vars: ' . $global_vars . '</p>' .
551            '</div></div>';
552
553        return $res;
554    }
555
556    public static function help($page, $index = '')
557    {
558        # Deprecated but we keep this for plugins.
559    }
560
561    public static function helpBlock(...$params)
562    {
563        $core = self::getCore();
564
565        if ($core->auth->user_prefs->interface->hidehelpbutton) {
566            return;
567        }
568
569        $args = new ArrayObject($params);
570
571        # --BEHAVIOR-- adminPageHelpBlock
572        $core->callBehavior('adminPageHelpBlock', $args);
573
574        if (empty($args)) {
575            return;
576        };
577
578        global $__resources;
579        if (empty($__resources['help'])) {
580            return;
581        }
582
583        $content = '';
584        foreach ($args as $v) {
585            if (is_object($v) && isset($v->content)) {
586                $content .= $v->content;
587                continue;
588            }
589
590            if (!isset($__resources['help'][$v])) {
591                continue;
592            }
593            $f = $__resources['help'][$v];
594            if (!file_exists($f) || !is_readable($f)) {
595                continue;
596            }
597
598            $fc = file_get_contents($f);
599            if (preg_match('|<body[^>]*?>(.*?)</body>|ms', $fc, $matches)) {
600                $content .= $matches[1];
601            } else {
602                $content .= $fc;
603            }
604        }
605
606        if (trim($content) == '') {
607            return;
608        }
609
610        // Set contextual help global flag
611        $GLOBALS['__resources']['ctxhelp'] = true;
612
613        echo
614        '<div id="help"><hr /><div class="help-content clear"><h3>' . __('Help about this page') . '</h3>' .
615        $content .
616        '</div>' .
617        '<div id="helplink"><hr />' .
618        '<p>' .
619        sprintf(__('See also %s'), sprintf('<a href="' . $core->adminurl->get("admin.help") . '">%s</a>', __('the global help'))) .
620            '.</p>' .
621            '</div></div>';
622    }
623
624    public static function cssLoad($src, $media = 'screen', $v = '')
625    {
626        $escaped_src = html::escapeHTML($src);
627        if (!isset(self::$loaded_css[$escaped_src])) {
628            self::$loaded_css[$escaped_src] = true;
629            $escaped_src                    = self::appendVersion($escaped_src, $v);
630
631            return '<link rel="stylesheet" href="' . $escaped_src . '" type="text/css" media="' . $media . '" />' . "\n";
632        }
633    }
634
635    public static function jsLoad($src, $v = '')
636    {
637        $escaped_src = html::escapeHTML($src);
638        if (!isset(self::$loaded_js[$escaped_src])) {
639            self::$loaded_js[$escaped_src] = true;
640            $escaped_src                   = self::appendVersion($escaped_src, $v);
641            return '<script type="text/javascript" src="' . $escaped_src . '"></script>' . "\n";
642        }
643    }
644
645    private static function appendVersion($src, $v = '')
646    {
647        $src .= (strpos($src, '?') === false ? '?' : '&amp;') . 'v=';
648        if (defined('DC_DEV') && DC_DEV === true) {
649            $src .= md5(uniqid());
650        } else {
651            $src .= ($v === '' ? DC_VERSION : $v);
652        }
653        return $src;
654    }
655
656    public static function jsVar($n, $v)
657    {
658        return $n . " = '" . html::escapeJS($v) . "';\n";
659    }
660
661    public static function jsVars($vars)
662    {
663        $ret = '<script type="text/javascript">' . "\n";
664        foreach ($vars as $var => $value) {
665            $ret .= $var . ' = ' . (is_string($value) ? "'" . html::escapeJS($value) . "'" : $value) . ';' . "\n";
666        }
667        $ret .= "</script>\n";
668
669        return $ret;
670    }
671
672    public static function jsJson($id, $vars)
673    {
674        return dcUtils::jsJson($id, $vars);
675    }
676
677    public static function jsToggles()
678    {
679        $core = self::getCore();
680
681        $js = [];
682        if ($core->auth->user_prefs->toggles) {
683            $unfolded_sections = explode(',', $core->auth->user_prefs->toggles->unfolded_sections);
684            foreach ($unfolded_sections as $k => &$v) {
685                if ($v !== '') {
686                    $js[$unfolded_sections[$k]] = true;
687                }
688            }
689        }
690        return
691        self::jsJson('dotclear_toggles', $js) .
692        self::jsLoad('js/toggles.js');
693    }
694
695    public static function jsCommon()
696    {
697        $core = self::getCore();
698
699        $js = [
700            'nonce'               => $core->getNonce(),
701
702            'img_plus_src'        => 'images/expand.png',
703            'img_plus_txt'        => '►',
704            'img_plus_alt'        => __('uncover'),
705
706            'img_minus_src'       => 'images/hide.png',
707            'img_minus_txt'       => '▼',
708            'img_minus_alt'       => __('hide'),
709
710            'img_menu_on'         => 'images/menu_on.png',
711            'img_menu_off'        => 'images/menu_off.png',
712
713            'img_plus_theme_src'  => 'images/plus-theme.png',
714            'img_plus_theme_txt'  => '►',
715            'img_plus_theme_alt'  => __('uncover'),
716
717            'img_minus_theme_src' => 'images/minus-theme.png',
718            'img_minus_theme_txt' => '▼',
719            'img_minus_theme_alt' => __('hide')
720        ];
721
722        $js_msg = [
723            'help'                                 => __('Need help?'),
724            'new_window'                           => __('new window'),
725            'help_hide'                            => __('Hide'),
726            'to_select'                            => __('Select:'),
727            'no_selection'                         => __('no selection'),
728            'select_all'                           => __('select all'),
729            'invert_sel'                           => __('Invert selection'),
730            'website'                              => __('Web site:'),
731            'email'                                => __('Email:'),
732            'ip_address'                           => __('IP address:'),
733            'error'                                => __('Error:'),
734            'entry_created'                        => __('Entry has been successfully created.'),
735            'edit_entry'                           => __('Edit entry'),
736            'view_entry'                           => __('view entry'),
737            'confirm_delete_posts'                 => __("Are you sure you want to delete selected entries (%s)?"),
738            'confirm_delete_medias'                => __("Are you sure you want to delete selected medias (%d)?"),
739            'confirm_delete_categories'            => __("Are you sure you want to delete selected categories (%s)?"),
740            'confirm_delete_post'                  => __("Are you sure you want to delete this entry?"),
741            'click_to_unlock'                      => __("Click here to unlock the field"),
742            'confirm_spam_delete'                  => __('Are you sure you want to delete all spams?'),
743            'confirm_delete_comments'              => __('Are you sure you want to delete selected comments (%s)?'),
744            'confirm_delete_comment'               => __('Are you sure you want to delete this comment?'),
745            'cannot_delete_users'                  => __('Users with posts cannot be deleted.'),
746            'confirm_delete_user'                  => __('Are you sure you want to delete selected users (%s)?'),
747            'confirm_delete_blog'                  => __('Are you sure you want to delete selected blogs (%s)?'),
748            'confirm_delete_category'              => __('Are you sure you want to delete category "%s"?'),
749            'confirm_reorder_categories'           => __('Are you sure you want to reorder all categories?'),
750            'confirm_delete_media'                 => __('Are you sure you want to remove media "%s"?'),
751            'confirm_delete_directory'             => __('Are you sure you want to remove directory "%s"?'),
752            'confirm_extract_current'              => __('Are you sure you want to extract archive in current directory?'),
753            'confirm_remove_attachment'            => __('Are you sure you want to remove attachment "%s"?'),
754            'confirm_delete_lang'                  => __('Are you sure you want to delete "%s" language?'),
755            'confirm_delete_plugin'                => __('Are you sure you want to delete "%s" plugin?'),
756            'confirm_delete_plugins'               => __('Are you sure you want to delete selected plugins?'),
757            'use_this_theme'                       => __('Use this theme'),
758            'remove_this_theme'                    => __('Remove this theme'),
759            'confirm_delete_theme'                 => __('Are you sure you want to delete "%s" theme?'),
760            'confirm_delete_themes'                => __('Are you sure you want to delete selected themes?'),
761            'confirm_delete_backup'                => __('Are you sure you want to delete this backup?'),
762            'confirm_revert_backup'                => __('Are you sure you want to revert to this backup?'),
763            'zip_file_content'                     => __('Zip file content'),
764            'xhtml_validator'                      => __('XHTML markup validator'),
765            'xhtml_valid'                          => __('XHTML content is valid.'),
766            'xhtml_not_valid'                      => __('There are XHTML markup errors.'),
767            'warning_validate_no_save_content'     => __('Attention: an audit of a content not yet registered.'),
768            'confirm_change_post_format'           => __('You have unsaved changes. Switch post format will loose these changes. Proceed anyway?'),
769            'confirm_change_post_format_noconvert' => __("Warning: post format change will not convert existing content. You will need to apply new format by yourself. Proceed anyway?"),
770            'load_enhanced_uploader'               => __('Loading enhanced uploader, please wait.'),
771
772            'module_author'                        => __('Author:'),
773            'module_details'                       => __('Details'),
774            'module_support'                       => __('Support'),
775            'module_help'                          => __('Help:'),
776            'module_section'                       => __('Section:'),
777            'module_tags'                          => __('Tags:'),
778
779            'close_notice'                         => __('Hide this notice')
780        ];
781
782        return
783        self::jsLoad('js/prepend.js') .
784        self::jsLoad('js/jquery/jquery.js') .
785        self::jsJson('dotclear_jquery', [
786            'mute' => (empty($core->blog) || $core->blog->settings->system->jquery_migrate_mute)
787        ]) .
788        self::jsLoad('js/jquery-mute.js') .
789        self::jsLoad('js/jquery/jquery-migrate.js') .
790        self::jsLoad('js/jquery/jquery.biscuit.js') .
791
792        self::jsJson('dotclear', $js) .
793        self::jsJson('dotclear_msg', $js_msg) .
794
795        self::jsLoad('js/common.js') .
796        self::jsLoad('js/services.js') .
797        self::jsLoad('js/prelude.js');
798    }
799
800    /**
801    @deprecated since version 2.11
802     */
803    public static function jsLoadIE7()
804    {
805        return '';
806    }
807
808    public static function jsConfirmClose(...$args)
809    {
810        $js = [
811            'prompt' => __('You have unsaved changes.'),
812            'forms'  => $args
813        ];
814        return
815        self::jsJson('confirm_close', $js) .
816        self::jsLoad('js/confirm-close.js');
817    }
818
819    public static function jsPageTabs($default = null)
820    {
821        $js = [
822            'default' => $default
823        ];
824        return
825        self::jsJson('page_tabs', $js) .
826        self::jsLoad('js/jquery/jquery.pageTabs.js') .
827        self::jsLoad('js/page-tabs.js');
828    }
829
830    public static function jsModal()
831    {
832        return
833        self::jsLoad('js/jquery/jquery.magnific-popup.js');
834    }
835
836    public static function jsColorPicker()
837    {
838        return
839        self::cssLoad('style/farbtastic/farbtastic.css') .
840        self::jsLoad('js/jquery/jquery.farbtastic.js') .
841        self::jsLoad('js/color-picker.js');
842    }
843
844    public static function jsDatePicker()
845    {
846        $js = [
847            'months'    => [
848                __('January'),
849                __('February'),
850                __('March'),
851                __('April'),
852                __('May'),
853                __('June'),
854                __('July'),
855                __('August'),
856                __('September'),
857                __('October'),
858                __('November'),
859                __('December')
860            ],
861            'days'      => [
862                __('Monday'),
863                __('Tuesday'),
864                __('Wednesday'),
865                __('Thursday'),
866                __('Friday'),
867                __('Saturday'),
868                __('Sunday')
869            ],
870            'img_src'   => 'images/date-picker.png',
871            'img_alt'   => __('Choose date'),
872            'close_msg' => __('close'),
873            'now_msg'   => __('now')
874        ];
875        return
876        self::cssLoad('style/date-picker.css') .
877        self::jsJson('date_picker', $js) .
878        self::jsLoad('js/date-picker.js');
879    }
880
881    public static function jsToolBar()
882    {
883        # Deprecated but we keep this for plugins.
884    }
885
886    public static function jsUpload($params = [], $base_url = null)
887    {
888        $core = self::getCore();
889
890        if (!$base_url) {
891            $base_url = path::clean(dirname(preg_replace('/(\?.*$)?/', '', $_SERVER['REQUEST_URI']))) . '/';
892        }
893
894        $params = array_merge($params, [
895            'sess_id=' . session_id(),
896            'sess_uid=' . $_SESSION['sess_browser_uid'],
897            'xd_check=' . $core->getNonce()
898        ]);
899
900        $js_msg = [
901            'enhanced_uploader_activate' => __('Temporarily activate enhanced uploader'),
902            'enhanced_uploader_disable'  => __('Temporarily disable enhanced uploader')
903        ];
904        $js = [
905            'msg'      => [
906                'limit_exceeded'             => __('Limit exceeded.'),
907                'size_limit_exceeded'        => __('File size exceeds allowed limit.'),
908                'canceled'                   => __('Canceled.'),
909                'http_error'                 => __('HTTP Error:'),
910                'error'                      => __('Error:'),
911                'choose_file'                => __('Choose file'),
912                'choose_files'               => __('Choose files'),
913                'cancel'                     => __('Cancel'),
914                'clean'                      => __('Clean'),
915                'upload'                     => __('Upload'),
916                'send'                       => __('Send'),
917                'file_successfully_uploaded' => __('File successfully uploaded.'),
918                'no_file_in_queue'           => __('No file in queue.'),
919                'file_in_queue'              => __('1 file in queue.'),
920                'files_in_queue'             => __('%d files in queue.'),
921                'queue_error'                => __('Queue error:')
922            ],
923            'base_url' => $base_url
924        ];
925
926        return
927        self::jsJson('file_upload', $js) .
928        self::jsJson('file_upload_msg', $js_msg) .
929        self::jsLoad('js/file-upload.js') .
930        self::jsLoad('js/jquery/jquery-ui.custom.js') .
931        self::jsLoad('js/jsUpload/tmpl.js') .
932        self::jsLoad('js/jsUpload/template-upload.js') .
933        self::jsLoad('js/jsUpload/template-download.js') .
934        self::jsLoad('js/jsUpload/load-image.js') .
935        self::jsLoad('js/jsUpload/jquery.iframe-transport.js') .
936        self::jsLoad('js/jsUpload/jquery.fileupload.js') .
937        self::jsLoad('js/jsUpload/jquery.fileupload-process.js') .
938        self::jsLoad('js/jsUpload/jquery.fileupload-resize.js') .
939        self::jsLoad('js/jsUpload/jquery.fileupload-ui.js');
940    }
941
942    public static function jsMetaEditor()
943    {
944        return self::jsLoad('js/meta-editor.js');
945    }
946
947    public static function jsFilterControl($show = true)
948    {
949        $js = [
950            'show_filters'      => (boolean) $show,
951            'filter_posts_list' => __('Show filters and display options'),
952            'cancel_the_filter' => __('Cancel filters and display options')
953        ];
954        return
955        self::jsJson('filter_controls', $js) .
956        self::jsLoad('js/filter-controls.js');
957    }
958
959    public static function jsLoadCodeMirror($theme = '', $multi = true, $modes = ['css', 'htmlmixed', 'javascript', 'php', 'xml'])
960    {
961        $ret =
962        self::cssLoad('js/codemirror/lib/codemirror.css') .
963        self::jsLoad('js/codemirror/lib/codemirror.js');
964        if ($multi) {
965            $ret .= self::jsLoad('js/codemirror/addon/mode/multiplex.js');
966        }
967        foreach ($modes as $mode) {
968            $ret .= self::jsLoad('js/codemirror/mode/' . $mode . '/' . $mode . '.js');
969        }
970        $ret .=
971        self::jsLoad('js/codemirror/addon/edit/closebrackets.js') .
972        self::jsLoad('js/codemirror/addon/edit/matchbrackets.js') .
973        self::cssLoad('js/codemirror/addon/display/fullscreen.css') .
974        self::jsLoad('js/codemirror/addon/display/fullscreen.js');
975        if ($theme != '') {
976            $ret .= self::cssLoad('js/codemirror/theme/' . $theme . '.css');
977        }
978        return $ret;
979    }
980
981    public static function jsRunCodeMirror($name, $id = null, $mode = null, $theme = '')
982    {
983        if (is_array($name)) {
984            $js = $name;
985        } else {
986            $js = [[
987                'name'  => $name,
988                'id'    => $id,
989                'mode'  => $mode,
990                'theme' => $theme
991            ]];
992        }
993
994        $ret =
995        self::jsJson('codemirror', $js) .
996        self::jsLoad('js/codemirror.js');
997        return $ret;
998    }
999
1000    public static function getCodeMirrorThemes()
1001    {
1002        $themes      = [];
1003        $themes_root = dirname(__FILE__) . '/../../admin' . '/js/codemirror/theme/';
1004        if (is_dir($themes_root) && is_readable($themes_root)) {
1005            if (($d = @dir($themes_root)) !== false) {
1006                while (($entry = $d->read()) !== false) {
1007                    if ($entry != '.' && $entry != '..' && substr($entry, 0, 1) != '.' && is_readable($themes_root . '/' . $entry)) {
1008                        $themes[] = substr($entry, 0, -4); // remove .css extension
1009                    }
1010                }
1011                sort($themes);
1012            }
1013        }
1014        return $themes;
1015    }
1016
1017    public static function getPF($file)
1018    {
1019        $core = self::getCore();
1020        return $core->adminurl->get('load.plugin.file', ['pf' => $file]);
1021    }
1022
1023    public static function getVF($file)
1024    {
1025        $core = self::getCore();
1026        return $core->adminurl->get('load.var.file', ['vf' => $file]);
1027    }
1028
1029    public static function setXFrameOptions($headers, $origin = null)
1030    {
1031        if (self::$xframe_loaded) {
1032            return;
1033        }
1034
1035        if ($origin !== null) {
1036            $url                        = parse_url($origin);
1037            $headers['x-frame-options'] = sprintf('X-Frame-Options: %s', is_array($url) && isset($url['host']) ?
1038                ("ALLOW-FROM " . (isset($url['scheme']) ? $url['scheme'] . ':' : '') . '//' . $url['host']) :
1039                'SAMEORIGIN');
1040        } else {
1041            $headers['x-frame-options'] = 'X-Frame-Options: SAMEORIGIN'; // FF 3.6.9+ Chrome 4.1+ IE 8+ Safari 4+ Opera 10.5+
1042        }
1043        self::$xframe_loaded = true;
1044    }
1045}
Note: See TracBrowser for help on using the repository browser.

Sites map