Dotclear

source: inc/admin/lib.dc.page.php @ 3418:f74c218a7b8e

Revision 3418:f74c218a7b8e, 35.0 KB checked in by franck <carnet.franck.paul@…>, 9 years ago (diff)

IE 7, 8 and 9 not more supported (should not be problematic for IE9 — gracefully degraded, but it will for IE7 and IE8 users)

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

Sites map