Dotclear

source: inc/admin/class.dc.admincontext.php @ 1414:ce67e9c592b7

Revision 1414:ce67e9c592b7, 14.6 KB checked in by Dsls, 12 years ago (diff)
  • reworked breadcrumb
  • tuned checkboxes (need to see if it works for multiple values)
  • magic methods for dcForm are more intuitive now, getField method added
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     Add a section to the breadcrumb
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 appendBreadCrumbItem($title,$url='',$class='')
368     {
369          $this->protected_globals['page_title'][] = array(
370               'title' => $title,
371               'link' => $url,
372               'class' => $class
373          );
374     }
375     
376     /**
377     Fill the page title
378     
379     $title can be:
380     a string for page title part or
381     TRUE to add blog name at the begining of title or
382     NULL to empty/reset title
383     
384     @param mixed $title A title part
385     @param boolean $url Link of the title part
386     @return object self
387     */
388     public function setBreadCrumb($breadcrumb, $with_home_link=true)
389     {
390          if ($with_home_link) {
391               $this->appendBreadCrumbItem('<img src="style/dashboard.png" alt="" />','index.php','go_home');
392          } else {
393               $this->appendBreadCrumbItem('<img src="style/dashboard-alt.png" alt="" />'.$breadcrumb);
394               return $this;
395          }
396          if (is_array($breadcrumb)) {
397               foreach ($breadcrumb as $title => $bc) {
398                    $this->appendBreadCrumbItem($title,$bc);
399               }
400          } else {
401               $this->appendBreadcrumbItem($breadcrumb);
402          }
403          return $this;
404     }
405     
406     /**
407     Check if a page title is set
408     */
409     public function hasPageTitle()
410     {
411          return !empty($this->protected_globals['page_title']);
412     }
413     
414     /**
415     Get list of blogs
416     */
417     protected function getBlogs()
418     {
419          $blog_id = '';
420         
421          # Blogs list
422          $blogs = array();
423          if ($this->core->auth->blog_count > 1 && $this->core->auth->blog_count < 20) {
424               $blog_id = $this->core->blog->id;
425               $rs_blogs = $this->core->getBlogs(array('order'=>'LOWER(blog_name)','limit'=>20));
426               while ($rs_blogs->fetch()) {
427                    $blogs[$rs_blogs->blog_id] = $rs_blogs->blog_name.' - '.$rs_blogs->blog_url;
428                    $this->protected_globals['blogs'][$rs_blogs->blog_id] = 
429                    new dcArrayProxy($rs_blogs, array(
430                         'blog_id','blog_name','blog_desc','blog_url','blog_creadt','blog_upddt'));
431               }
432          }
433         
434          # Switch blog form
435          $form = new dcForm($this->core,'switchblog_menu','index.php');
436          $form
437               ->addField(
438                    new dcFieldCombo('switchblog',$blog_id,$blogs,array(
439                    'label' => __('Blogs:'))))
440               ->addField(
441                    new dcFieldSubmit('switchblog_submit',__('ok'),array(
442                    'action' => 'switchblog')))
443               ->setup();
444          # Switch blog form
445          $sform = new dcForm($this->core,'search-menu','search.php','GET');
446          $sform
447               ->addField(
448                    new dcFieldText('q','',array(
449                    'maxlength'         => 255,
450                    'label' => __('Search:'))))
451               ->addField(
452                    new dcFieldSubmit(array('ok'),__('OK'),array(
453                    )))
454               ->setup();
455     }
456     
457     /**
458     Get current blog information
459     */
460     protected function getCurrentBlog()
461     {
462          $this->protected_globals['current_blog'] = $this->core->auth->blog_count ?
463               new dcProxy($this->core->blog,array(
464                    'id','name','desc','url','host','creadt','upddt'
465               )) : array(
466                    'id'      => '',
467                    'name'    => '',
468                    'desc'    => '',
469                    'url'     => '',
470                    'host'    => '',
471                    'creadt'  => '',
472                    'upddt'   => ''
473               );
474     }
475     
476     /**
477     Get current user information
478     */
479     protected function getCurrentUser()
480     {
481          $infos = array(
482               'pwd','name','firstname','displayname',
483               'email','url','default_blog','lang','tz',
484               'post_status','creadt','upddt','cn'
485          );
486         
487          $user = array(
488               'id' => '',
489               'super' => false,
490               'lang' => 'en',
491               'options' => $this->core->userDefaults(),
492               'prefs' => array(),
493               'rights' => array(
494                    'media' => false
495               )
496          );
497         
498          foreach($infos as $i) {
499               $user[$i] = '';
500          }
501         
502          if ($this->core->auth->userID()) {
503         
504               $user = array(
505                    'id' => $this->core->auth->userID(),
506                    'super' => $this->core->auth->isSuperAdmin(),
507                    'options' => $this->core->auth->getOptions(),
508                    'rights' => array(
509                         'media' => $this->core->auth->check('media,media_admin',$this->core->blog->id)
510                    )
511               );
512               
513               foreach($infos as $i) {
514                    $user[$i] = $this->core->auth->getInfo('user_'.$i);
515               }
516               
517               foreach($this->core->auth->user_prefs->dumpWorkspaces() as $ws => $prefs) {
518                    $user['prefs'][$ws] = $prefs->dumpPrefs();
519               }
520          }
521         
522          $this->protected_globals['current_user'] = $user;
523     }
524     
525     /**
526     Get sidebar menus
527     */
528     protected function getMenus()
529     {
530          global $_menu;
531         
532          $this->protected_globals['menus'] = array();
533         
534          if (!isset($_menu)) {
535               return;
536          }
537         
538          foreach($_menu as $m) {
539               $this->protected_globals['menus'][] = array(
540                    'id'           => $m->getID(),
541                    'title'        => $m->getTitle(),
542                    'separator'    => $m->getSeparator(),
543                    'items'        => $m->getItems()
544               );
545          }
546     }
547     
548     /**
549     Get an array of debug/dev infos
550     */
551     public function getDebugInfo()
552     {
553          if (!DC_DEBUG) {
554               return array();
555          }
556         
557          $di = array(
558               'global_vars' => implode(', ',array_keys($GLOBALS)),
559               'memory' => array(
560                    'usage' => memory_get_usage(),
561                    'size' => files::size(memory_get_usage())
562               ),
563               'xdebug' => array()
564          );
565         
566          if (function_exists('xdebug_get_profiler_filename')) {
567         
568               $url = http::getSelfURI();
569               $url .= strpos($url,'?') === false ? '?' : '&';
570               $url .= 'XDEBUG_PROFILE';
571               
572               $di['xdebug'] = array(
573                    'elapse_time' => xdebug_time_index(),
574                    'profiler_file' => xdebug_get_profiler_filename(),
575                    'profiler_url' =>  $url
576               );
577               
578               /* xdebug configuration:
579               zend_extension = /.../xdebug.so
580               xdebug.auto_trace = On
581               xdebug.trace_format = 0
582               xdebug.trace_options = 1
583               xdebug.show_mem_delta = On
584               xdebug.profiler_enable = 0
585               xdebug.profiler_enable_trigger = 1
586               xdebug.profiler_output_dir = /tmp
587               xdebug.profiler_append = 0
588               xdebug.profiler_output_name = timestamp
589               */
590          }
591         
592          return $di;
593     }
594     
595     /**
596     Add a value in a namespace memory
597     
598     This help keep variable when recalling Twig macros
599     
600     @param string $ns A namespace
601     @param string $str A value to memorize in this namespace
602     */
603     public function setMemory($ns,$str)
604     {
605          if (!array_key_exists($ns,$this->memory) || !in_array($str,$this->memory[$ns])) {
606               $this->memory[$ns][] = $str;
607          }
608     }
609     
610     /**
611     Check if a value is previously memorized in a namespace
612     
613     @param string $ns A namespace
614     @param string $str A value to search in this namespace
615     @return array True if exists
616     */
617     public function getMemory($ns,$str)
618     {
619          return array_key_exists($ns,$this->memory) && in_array($str,$this->memory[$ns]);
620     }
621}
622?>
Note: See TracBrowser for help on using the repository browser.

Sites map