Dotclear

source: inc/admin/class.dc.admincontext.php @ 1156:92f840a91f98

Revision 1156:92f840a91f98, 13.8 KB checked in by Dsls <dsls@…>, 12 years ago (diff)

Commented code, small tuning

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               'build_url' => new Twig_Function_Method($this,'buildUrl', array('is_safe' => array('html')))
212          );
213     }
214     
215
216    /**
217     * Builds an url given a base, and parameters
218     *
219     * @param mixed $url    the base url as string
220     * @param mixed $params the parameters.
221     *
222     * @access public
223     *
224     * @return string the resulting url.
225     */
226     public function buildUrl($url,$params=array()) {
227          if (is_array($url) && isset($url[0])) {
228               $base = $url[0];
229               if (isset($url[1]) && is_array($url[1])) {
230                    $p = array_merge($params,$url[1]);
231               }
232          } else {
233               $base = $url;
234               $p=$params;
235          }
236          if (empty($p)) {
237               return $base;
238          } else {
239               return $base.'?'.http_build_query($p);
240          }
241     }
242
243     /**
244     Returns a list of global variables to add to the existing list.
245     
246     This merges overloaded variables with defined variables.
247     
248     @return array An array of global variables
249     */
250     public function getGlobals()
251     {
252          $this->getBlogs();
253          $this->getCurrentBlog();
254          $this->getCurrentUser();
255          $this->getMenus();
256         
257          # Additional globals
258          $p = path::info($_SERVER['REQUEST_URI']);
259          $this->protected_globals['current_page'] = $p['base'];
260          $this->protected_globals['blog_count'] = $this->core->auth->blog_count;
261          $this->protected_globals['rtl'] = l10n::getTextDirection(
262               $this->protected_globals['current_user']['lang']) == 'rtl';
263          $this->protected_globals['session'] = array(
264               'id' => session_id(),
265               'uid' => isset($_SESSION['sess_browser_uid']) ? $_SESSION['sess_browser_uid'] : '',
266               'nonce' => $this->core->getNonce()
267          );
268         
269          # Keep protected globals safe
270          return array_merge($this->globals,$this->protected_globals);
271     }
272     
273     /**
274     Returns the name of the extension.
275     
276     @return string The extension name
277     */
278     public function getName()
279     {
280          return 'AdminContext';
281     }
282     
283     
284     /**
285     Add an informational message
286     
287     @param string $message A message
288     @return object self
289     */
290     public function setSafeMode($safe_mode)
291     {
292          $this->protected_globals['safe_mode'] = (boolean) $safe_mode;
293          return $this;
294     }
295     
296     /**
297     Add an informational message
298     
299     @param string $message A message
300     @return object self
301     */
302     public function addMessageStatic($message)
303     {
304          $this->protected_globals['messages']['static'][] = $message;
305          return $this;
306     }
307     
308     /**
309     Add a list of informational messages
310     
311     @param string $message A title
312     @param array $message A list of messages
313     @return object self
314     */
315     public function addMessagesList($title,$messages)
316     {
317          $this->protected_globals['messages']['lists'][$title] = $messages;
318          return $this;
319     }
320     
321     /**
322     Set an important message
323     
324     @param string $message A message
325     @return object self
326     */
327     public function setAlert($message)
328     {
329          $this->protected_globals['messages']['alert'] = $message;
330          return $this;
331     }
332     
333     /**
334     Add an error message
335     
336     @param string Error message
337     @return object self
338     */
339     public function addError($error)
340     {
341          $this->protected_globals['messages']['errors'][] = $error;
342          return $this;
343     }
344     
345     /**
346     Check if there is an error message
347     
348     @return boolean
349     */
350     public function hasError()
351     {
352          return !empty($this->protected_globals['messages']['errors']);
353     }
354     
355     /**
356     Fill the page title
357     
358     $title can be:
359     a string for page title part or
360     TRUE to add blog name at the begining of title or
361     NULL to empty/reset title
362     
363     @param mixed $title A title part
364     @param boolean $url Link of the title part
365     @return object self
366     */
367     public function fillPageTitle($title,$url='')
368     {
369          if (is_bool($title)) {
370               $this->protected_globals['page_global'] = $title;
371          }
372          elseif (null === $title) {
373               $this->protected_globals['page_global'] = false;
374               $this->protected_globals['page_title'] = array();
375          }
376          else {
377               $this->protected_globals['page_title'][] = array(
378                    'title' => $title,
379                    'link' => $url
380               );
381          }
382          return $this;
383     }
384     
385     /**
386     Check if a page title is set
387     */
388     public function hasPageTitle()
389     {
390          return !empty($this->protected_globals['page_title']);
391     }
392     
393     /**
394     Get list of blogs
395     */
396     protected function getBlogs()
397     {
398          $blog_id = '';
399         
400          # Blogs list
401          $blogs = array();
402          if ($this->core->auth->blog_count > 1 && $this->core->auth->blog_count < 20) {
403               $blog_id = $this->core->blog->id;
404               $rs_blogs = $this->core->getBlogs(array('order'=>'LOWER(blog_name)','limit'=>20));
405               while ($rs_blogs->fetch()) {
406                    $blogs[$rs_blogs->blog_id] = $rs_blogs->blog_name.' - '.$rs_blogs->blog_url;
407                    $this->protected_globals['blogs'][$rs_blogs->blog_id] = 
408                    new dcArrayProxy($rs_blogs, array(
409                         'blog_id','blog_name','blog_desc','blog_url','blog_creadt','blog_upddt'));
410               }
411          }
412         
413          # Switch blog form
414          $form = new dcForm($this->core,'switchblog_menu','index.php');
415          $form
416               ->addField(
417                    new dcFieldCombo('switchblog',$blog_id,$blogs,array(
418                    'label' => __('Blogs:'))))
419               ->addField(
420                    new dcFieldSubmit('switchblog_submit',__('ok'),array(
421                    'action' => 'switchblog')))
422               ->setup();
423     }
424     
425     /**
426     Get current blog information
427     */
428     protected function getCurrentBlog()
429     {
430          $this->protected_globals['current_blog'] = $this->core->auth->blog_count ?
431               new dcProxy($this->core->blog,array(
432                    'id','name','desc','url','host','creadt','upddt'
433               )) : array(
434                    'id'      => '',
435                    'name'    => '',
436                    'desc'    => '',
437                    'url'     => '',
438                    'host'    => '',
439                    'creadt'  => '',
440                    'upddt'   => ''
441               );
442     }
443     
444     /**
445     Get current user information
446     */
447     protected function getCurrentUser()
448     {
449          $infos = array(
450               'pwd','name','firstname','displayname',
451               'email','url','default_blog','lang','tz',
452               'post_status','creadt','upddt','cn'
453          );
454         
455          $user = array(
456               'id' => '',
457               'super' => false,
458               'lang' => 'en',
459               'options' => $this->core->userDefaults(),
460               'prefs' => array(),
461               'rights' => array(
462                    'media' => false
463               )
464          );
465         
466          foreach($infos as $i) {
467               $user[$i] = '';
468          }
469         
470          if ($this->core->auth->userID()) {
471         
472               $user = array(
473                    'id' => $this->core->auth->userID(),
474                    'super' => $this->core->auth->isSuperAdmin(),
475                    'options' => $this->core->auth->getOptions(),
476                    'rights' => array(
477                         'media' => $this->core->auth->check('media,media_admin',$this->core->blog->id)
478                    )
479               );
480               
481               foreach($infos as $i) {
482                    $user[$i] = $this->core->auth->getInfo('user_'.$i);
483               }
484               
485               foreach($this->core->auth->user_prefs->dumpWorkspaces() as $ws => $prefs) {
486                    $user['prefs'][$ws] = $prefs->dumpPrefs();
487               }
488          }
489         
490          $this->protected_globals['current_user'] = $user;
491     }
492     
493     /**
494     Get sidebar menus
495     */
496     protected function getMenus()
497     {
498          global $_menu;
499         
500          $this->protected_globals['menus'] = array();
501         
502          if (!isset($_menu)) {
503               return;
504          }
505         
506          foreach($_menu as $m) {
507               $this->protected_globals['menus'][] = array(
508                    'id'           => $m->getID(),
509                    'title'        => $m->getTitle(),
510                    'separator'    => $m->getSeparator(),
511                    'items'        => $m->getItems()
512               );
513          }
514     }
515     
516     /**
517     Get an array of debug/dev infos
518     */
519     public function getDebugInfo()
520     {
521          if (!DC_DEBUG) {
522               return array();
523          }
524         
525          $di = array(
526               'global_vars' => implode(', ',array_keys($GLOBALS)),
527               'memory' => array(
528                    'usage' => memory_get_usage(),
529                    'size' => files::size(memory_get_usage())
530               ),
531               'xdebug' => array()
532          );
533         
534          if (function_exists('xdebug_get_profiler_filename')) {
535         
536               $url = http::getSelfURI();
537               $url .= strpos($url,'?') === false ? '?' : '&';
538               $url .= 'XDEBUG_PROFILE';
539               
540               $di['xdebug'] = array(
541                    'elapse_time' => xdebug_time_index(),
542                    'profiler_file' => xdebug_get_profiler_filename(),
543                    'profiler_url' =>  $url
544               );
545               
546               /* xdebug configuration:
547               zend_extension = /.../xdebug.so
548               xdebug.auto_trace = On
549               xdebug.trace_format = 0
550               xdebug.trace_options = 1
551               xdebug.show_mem_delta = On
552               xdebug.profiler_enable = 0
553               xdebug.profiler_enable_trigger = 1
554               xdebug.profiler_output_dir = /tmp
555               xdebug.profiler_append = 0
556               xdebug.profiler_output_name = timestamp
557               */
558          }
559         
560          return $di;
561     }
562     
563     /**
564     Add a value in a namespace memory
565     
566     This help keep variable when recalling Twig macros
567     
568     @param string $ns A namespace
569     @param string $str A value to memorize in this namespace
570     */
571     public function setMemory($ns,$str)
572     {
573          if (!array_key_exists($ns,$this->memory) || !in_array($str,$this->memory[$ns])) {
574               $this->memory[$ns][] = $str;
575          }
576     }
577     
578     /**
579     Check if a value is previously memorized in a namespace
580     
581     @param string $ns A namespace
582     @param string $str A value to search in this namespace
583     @return array True if exists
584     */
585     public function getMemory($ns,$str)
586     {
587          return array_key_exists($ns,$this->memory) && in_array($str,$this->memory[$ns]);
588     }
589}
590?>
Note: See TracBrowser for help on using the repository browser.

Sites map