Dotclear

source: inc/admin/lib.dc.page.php @ 3307:c3d5e26b6ed4

Revision 3307:c3d5e26b6ed4, 34.4 KB checked in by franck <carnet.franck.paul@…>, 9 years ago (diff)

Prevents CSP directive violation in media manager and post/page preview

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

Sites map