Dotclear

source: inc/admin/class.dc.admincontext.php @ 1153:1e48950b05af

Revision 1153:1e48950b05af, 13.0 KB checked in by Dsls <dsls@…>, 12 years ago (diff)

Merge

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

Sites map