Dotclear

source: inc/admin/class.dc.admincontext.php @ 2321:3ab5e6c3d301

Revision 2321:3ab5e6c3d301, 14.2 KB checked in by Dsls, 12 years ago (diff)

page layout readapted.

Line 
1<?php
2# -- BEGIN LICENSE BLOCK ---------------------------------------
3#
4# This file is part of Dotclear 2.
5#
6# Copyright (c) 2003-2011 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
14
15class dcProxy {
16     protected $object;
17     protected $attributes;
18     protected $methods;
19     protected $default;
20     protected $denyfirst;
21
22    /**
23     * valuesToArray - converts a list of strings to an array having these strings as keys.
24     *
25     * @param mixed $val the list to convert.
26     * @access protected
27     * @return mixed Value The resulting array
28     */
29     protected function valuesToArray($val) {
30          $arr = array();
31          foreach ($val as $k) {
32               $arr[$k]=true;
33          }
34          return $arr;
35     }
36
37     protected function isAllowed ($name,$list) {
38          if ($this->denyfirst) {
39               return isset($list[$name]);
40          } else {
41               return !isset($list[$name]);
42          }
43     }
44
45     public function __construct($object,$rights,$default='',$denyfirst=true) {
46          $this->object = $object;
47          $this->attributes = array();
48          $this->methods = array();
49          $this->denyfirst = $denyfirst;
50          if (isset($rights['attr'])) {
51               $this->attributes = $this->valuesToArray($rights['attr']);
52          }
53          if (isset($rights['methods'])) {
54               $this->methods = $this->valuesToArray($rights['methods']);
55          }
56     }
57
58     public function __get($name) {
59          if ($this->isAllowed($name,$this->attributes)) {
60               return $this->object->$name;
61          } else {
62               return $this->default;
63          }
64     }
65     
66     public function __isset($name) {
67          if ($this->isAllowed($name,$this->attributes)) {
68               return isset($this->object->$name);
69          } else {
70               return false;
71          }
72     }
73     
74
75     public function __call($name,$args) {
76          if ($this->isAllowed($name,$this->methods) &&
77               is_callable(array($this->object,$name))) {
78               return call_user_func_array(array($this->object,$name),$args);
79          } else {
80               return $this->default;
81          }
82
83     }
84}
85
86class dcArrayProxy extends dcProxy implements ArrayAccess {
87     public function offsetExists ($offset) {
88          return (isset($this->value[$offset]));
89     }
90     public function offsetGet ($offset) {
91          return new ProxyValue($this->object[$offset],$this->rights);
92     }
93     public function offsetSet ($offset ,$value ) {
94          // Do nothing, we are read only
95     }
96     public function offsetUnset ($offset) {
97          // Do nothing, we are read only
98     }
99}
100
101
102/**
103@ingroup DC_CORE
104@brief Template extension for admin context
105
106This extends template environment with tools required in admin context.
107*/
108class dcAdminContext extends Twig_Extension
109{
110     protected $core;
111     protected $globals = array();
112     protected $protected_globals = array();
113     protected $memory = array();
114     
115     public function __construct($core)
116     {
117          $this->core = $core;
118         
119          # Globals editable via context
120          $this->globals = array();
121         
122          # Globals not editable via context
123          $this->protected_globals = array(
124               'messages' => array(
125                    'static' => array(),
126                    'lists' => array(),
127                    'alert' => '',
128                    'errors' => array()
129               ),
130               
131               'page_title'   => array(),
132               'page_global'  => false,
133               
134               'admin_url'    => DC_ADMIN_URL,
135               'theme_url'    => '',
136               'plugin_url'   => DC_ADMIN_URL.'index.php?pf=',
137               
138               'version'           => DC_VERSION,
139               'vendor_name'  => DC_VENDOR_NAME,
140               
141               'safe_mode'    => isset($_SESSION['sess_safe_mode']) && $_SESSION['sess_safe_mode'],
142               'debug_mode'   => DC_DEBUG
143          );
144     }
145     
146     /**
147     Prevent call crash from template on method that return this class
148     */
149     public function __toString()
150     {
151          return '';
152     }
153     
154     /**
155     Test a global variable
156     
157     @param string $name Name of the variable to test
158     @return boolean
159     */
160     public function __isset($name)
161     {
162          return isset($this->globals[$name]);
163     }
164     
165     /**
166     Add a global variable
167     
168     @param string $name Name of the variable
169     @param mixed $value Value of the variable
170     */
171     public function __set($name,$value)
172     {
173/*
174          # Overload protect
175          if ($value === null && isset($this->globals[$name])) {
176               unset($this->globals[$name]);
177          }
178          elseif (!isset($this->globals[$name])) {
179               throw new Exception('Modification of overloaded globals has no effect');
180          }
181//*/
182          $this->globals[$name] = $value;
183     }
184     
185     /**
186     Get a global variable
187     
188     @param string $name Name of the variable
189     @return mixed Value of the variable or null
190     */
191     public function __get($name)
192     {
193          return isset($this->globals[$name]) ? $this->globals[$name] : null;
194     }
195     
196     /**
197     Returns a list of filters to add to the existing list.
198     
199     @return array An array of filters
200     */
201     public function getFilters()
202     {
203          return array(
204               'trans' => new Twig_Filter_Function("__", array('is_safe' => array('html')))
205          );
206     }
207     
208     /**
209     Returns a list of functions to add to the existing list.
210     
211     @return array An array of functions
212     */
213     public function getFunctions()
214     {
215          return array(
216               '__'           => new Twig_Function_Function("__", array('is_safe' => array('html'))),
217               'debug_info' => new Twig_Function_Method($this, 'getDebugInfo', array('is_safe' => array('html'))),
218               'memorize' => new Twig_Function_Method($this, 'setMemory', array('is_safe' => array('html'))),
219               'memorized' => new Twig_Function_Method($this, 'getMemory', array('is_safe' => array('html'))),
220               'build_url' => new Twig_Function_Method($this,'buildUrl', array('is_safe' => array('html')))
221          );
222     }
223     
224
225    /**
226     * Builds an url given a base, and parameters
227     *
228     * @param mixed $url    the base url as string
229     * @param mixed $params the parameters.
230     *
231     * @access public
232     *
233     * @return string the resulting url.
234     */
235     public function buildUrl($url,$params=array()) {
236          if (is_array($url) && isset($url[0])) {
237               $base = $url[0];
238               if (isset($url[1]) && is_array($url[1])) {
239                    $p = array_merge($params,$url[1]);
240               }
241          } else {
242               $base = $url;
243               $p=$params;
244          }
245          if (empty($p)) {
246               return $base;
247          } else {
248               return $base.'?'.http_build_query($p);
249          }
250     }
251
252     /**
253     Returns a list of global variables to add to the existing list.
254     
255     This merges overloaded variables with defined variables.
256     
257     @return array An array of global variables
258     */
259     public function getGlobals()
260     {
261          $this->getBlogs();
262          $this->getCurrentBlog();
263          $this->getCurrentUser();
264          $this->getMenus();
265         
266          # Additional globals
267          $p = path::info($_SERVER['REQUEST_URI']);
268          $this->protected_globals['current_page'] = $p['base'];
269          $this->protected_globals['blog_count'] = $this->core->auth->getBlogCount();
270          $this->protected_globals['rtl'] = l10n::getTextDirection(
271               $this->protected_globals['current_user']['lang']) == 'rtl';
272          $this->protected_globals['session'] = array(
273               'id' => session_id(),
274               'uid' => isset($_SESSION['sess_browser_uid']) ? $_SESSION['sess_browser_uid'] : '',
275               'nonce' => $this->core->getNonce()
276          );
277          # Keep protected globals safe
278          return array_merge($this->globals,$this->protected_globals);
279     }
280     
281     /**
282     Returns the name of the extension.
283     
284     @return string The extension name
285     */
286     public function getName()
287     {
288          return 'AdminContext';
289     }
290     
291     
292     /**
293     Add an informational message
294     
295     @param string $message A message
296     @return object self
297     */
298     public function setSafeMode($safe_mode)
299     {
300          $this->protected_globals['safe_mode'] = (boolean) $safe_mode;
301          return $this;
302     }
303     
304     /**
305     Add an informational message
306     
307     @param string $message A message
308     @return object self
309     */
310     public function addMessageStatic($message)
311     {
312          $this->protected_globals['messages']['static'][] = $message;
313          return $this;
314     }
315     
316     /**
317     Add a list of informational messages
318     
319     @param string $message A title
320     @param array $message A list of messages
321     @return object self
322     */
323     public function addMessagesList($title,$messages)
324     {
325          $this->protected_globals['messages']['lists'][$title] = $messages;
326          return $this;
327     }
328     
329     /**
330     Set an important message
331     
332     @param string $message A message
333     @return object self
334     */
335     public function setAlert($message)
336     {
337          $this->protected_globals['messages']['alert'] = $message;
338          return $this;
339     }
340     
341     /**
342     Add an error message
343     
344     @param string Error message
345     @return object self
346     */
347     public function addError($error)
348     {
349          $this->protected_globals['messages']['errors'][] = $error;
350          return $this;
351     }
352     
353     /**
354     Check if there is an error message
355     
356     @return boolean
357     */
358     public function hasError()
359     {
360          return !empty($this->protected_globals['messages']['errors']);
361     }
362     
363     /**
364     Add a section to the breadcrumb
365     
366     $title can be:
367     a string for page title part or
368     TRUE to add blog name at the begining of title or
369     NULL to empty/reset title
370     
371     @param mixed $title A title part
372     @param boolean $url Link of the title part
373     @return object self
374     */
375     public function appendBreadCrumbItem($title,$url='',$class='')
376     {
377          $this->protected_globals['page_title'][] = array(
378               'title' => $title,
379               'link' => $url,
380               'class' => $class
381          );
382     }
383     
384     /**
385     Fill the page title
386     
387     $title can be:
388     a string for page title part or
389     TRUE to add blog name at the begining of title or
390     NULL to empty/reset title
391     
392     @param mixed $title A title part
393     @param boolean $url Link of the title part
394     @return object self
395     */
396     public function setBreadCrumb($breadcrumb, $with_home_link=true)
397     {
398          if ($with_home_link) {
399               $this->appendBreadCrumbItem('<img src="style/dashboard.png" alt="" />','index.php','go_home');
400          } else {
401               $this->appendBreadCrumbItem('<img src="style/dashboard-alt.png" alt="" />'.$breadcrumb);
402               return $this;
403          }
404          if (is_array($breadcrumb)) {
405               foreach ($breadcrumb as $title => $bc) {
406                    $this->appendBreadCrumbItem($title,$bc);
407               }
408          } else {
409               $this->appendBreadcrumbItem($breadcrumb);
410          }
411          return $this;
412     }
413     
414     /**
415     Check if a page title is set
416     */
417     public function hasPageTitle()
418     {
419          return !empty($this->protected_globals['page_title']);
420     }
421     
422     /**
423     Get list of blogs
424     */
425     protected function getBlogs()
426     {
427          $blog_id = '';
428         
429          # Blogs list
430          $blogs = array();
431          $blog_count = $this->core->auth->getBlogCount();
432          if ($blog_count > 1 && $blog_count < 20) {
433               $blog_id = $this->core->blog->id;
434               $rs_blogs = $this->core->getBlogs(array('order'=>'LOWER(blog_name)','limit'=>20));
435               while ($rs_blogs->fetch()) {
436                    $blogs[$rs_blogs->blog_id] = $rs_blogs->blog_name.' - '.$rs_blogs->blog_url;
437                    $this->protected_globals['blogs'][$rs_blogs->blog_id] = 
438                    new dcArrayProxy($rs_blogs, array(
439                         'blog_id','blog_name','blog_desc','blog_url','blog_creadt','blog_upddt'));
440               }
441          }
442         
443          # Switch blog form
444          $form = new dcForm($this->core,'switchblog_menu','index.php');
445          $form
446               ->addField(
447                    new dcFieldCombo('switchblog',$blog_id,$blogs,array(
448                    'label' => __('Blogs:'))))
449               ->addField(
450                    new dcFieldSubmit('switchblog_submit',__('ok'),array(
451                    'action' => 'switchblog')))
452               ->setup();
453          # Switch blog form
454          $sform = new dcForm($this->core,'search-menu','search.php','GET');
455          $sform
456               ->addField(
457                    new dcFieldText('qx','',array(
458                    'maxlength'         => 255,
459                    'label' => __('Search:'))))
460               ->addField(
461                    new dcFieldSubmit(array('ok'),__('OK'),array(
462                    )))
463               ->setup();
464     }
465     
466     /**
467     Get current blog information
468     */
469     protected function getCurrentBlog()
470     {
471          $this->protected_globals['current_blog'] = $this->core->auth->getBlogCount() ?
472               new dcProxy($this->core->blog,array('attr' => array(
473                    'id','name','desc','url','host','creadt','upddt'
474               ))) : array(
475                    'id'      => '',
476                    'name'    => '',
477                    'desc'    => '',
478                    'url'     => '',
479                    'host'    => '',
480                    'creadt'  => '',
481                    'upddt'   => ''
482               );
483     }
484     
485     /**
486     Get current user information
487     */
488     protected function getCurrentUser()
489     {
490          $infos = array(
491               'pwd','name','firstname','displayname',
492               'email','url','default_blog','lang','tz',
493               'post_status','creadt','upddt','cn'
494          );
495         
496          $user = array(
497               'id' => '',
498               'super' => false,
499               'lang' => 'en',
500               'options' => $this->core->userDefaults(),
501               'prefs' => array(),
502               'rights' => array(
503                    'media' => false
504               )
505          );
506         
507          foreach($infos as $i) {
508               $user[$i] = '';
509          }
510         
511          if ($this->core->auth->userID()) {
512         
513               $user = array(
514                    'id' => $this->core->auth->userID(),
515                    'super' => $this->core->auth->isSuperAdmin(),
516                    'options' => $this->core->auth->getOptions(),
517                    'rights' => array(
518                         'media' => $this->core->auth->check('media,media_admin',$this->core->blog->id)
519                    )
520               );
521               
522               foreach($infos as $i) {
523                    $user[$i] = $this->core->auth->getInfo('user_'.$i);
524               }
525               
526               foreach($this->core->auth->user_prefs->dumpWorkspaces() as $ws => $prefs) {
527                    $user['prefs'][$ws] = $prefs->dumpPrefs();
528               }
529          }
530         
531          $this->protected_globals['current_user'] = $user;
532     }
533     
534     /**
535     Get sidebar menus
536     */
537     protected function getMenus()
538     {
539          global $_menu;
540         
541          $this->protected_globals['menus'] = array();
542         
543          if (!isset($_menu)) {
544               return;
545          }
546         
547          foreach($_menu as $m) {
548               $this->protected_globals['menus'][] = array(
549                    'id'           => $m->getID(),
550                    'title'        => $m->getTitle(),
551                    'separator'    => $m->getSeparator(),
552                    'items'        => $m->getItems()
553               );
554          }
555     }
556     
557     /**
558     Get an array of debug/dev infos
559     */
560     public function getDebugInfo()
561     {
562          if (!DC_DEBUG) {
563               return array();
564          }
565         
566          $di = array(
567               'global_vars' => implode(', ',array_keys($GLOBALS)),
568               'memory' => array(
569                    'usage' => memory_get_usage(),
570                    'size' => files::size(memory_get_usage())
571               ),
572               'xdebug' => array()
573          );
574         
575          if (function_exists('xdebug_get_profiler_filename')) {
576         
577               $url = http::getSelfURI();
578               $url .= strpos($url,'?') === false ? '?' : '&';
579               $url .= 'XDEBUG_PROFILE';
580               
581               $di['xdebug'] = array(
582                    'elapse_time' => xdebug_time_index(),
583                    'profiler_file' => xdebug_get_profiler_filename(),
584                    'profiler_url' =>  $url
585               );
586               
587               /* xdebug configuration:
588               zend_extension = /.../xdebug.so
589               xdebug.auto_trace = On
590               xdebug.trace_format = 0
591               xdebug.trace_options = 1
592               xdebug.show_mem_delta = On
593               xdebug.profiler_enable = 0
594               xdebug.profiler_enable_trigger = 1
595               xdebug.profiler_output_dir = /tmp
596               xdebug.profiler_append = 0
597               xdebug.profiler_output_name = timestamp
598               */
599          }
600         
601          return $di;
602     }
603     
604     /**
605     Add a value in a namespace memory
606     
607     This help keep variable when recalling Twig macros
608     
609     @param string $ns A namespace
610     @param string $str A value to memorize in this namespace
611     */
612     public function setMemory($ns,$str)
613     {
614          if (!array_key_exists($ns,$this->memory) || !in_array($str,$this->memory[$ns])) {
615               $this->memory[$ns][] = $str;
616          }
617     }
618     
619     /**
620     Check if a value is previously memorized in a namespace
621     
622     @param string $ns A namespace
623     @param string $str A value to search in this namespace
624     @return array True if exists
625     */
626     public function getMemory($ns,$str)
627     {
628          return array_key_exists($ns,$this->memory) && in_array($str,$this->memory[$ns]);
629     }
630}
631?>
Note: See TracBrowser for help on using the repository browser.

Sites map