Dotclear

source: inc/admin/class.dc.admincontext.php @ 1316:751f3031bcc7

Revision 1316:751f3031bcc7, 14.0 KB checked in by Dsls, 12 years ago (diff)

Manual merge for remaining little things from default, need to cope with this 3px difference in search box...
Btw, fixes checkboxes problems

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          # Switch blog form
424          $sform = new dcForm($this->core,'search-menu','search.php','GET');
425          $sform
426               ->addField(
427                    new dcFieldText('q','',array(
428                    'maxlength'         => 255,
429                    'label' => __('Search:'))))
430               ->addField(
431                    new dcFieldSubmit('ok',__('OK'),array(
432                    )))
433               ->setup();
434     }
435     
436     /**
437     Get current blog information
438     */
439     protected function getCurrentBlog()
440     {
441          $this->protected_globals['current_blog'] = $this->core->auth->blog_count ?
442               new dcProxy($this->core->blog,array(
443                    'id','name','desc','url','host','creadt','upddt'
444               )) : array(
445                    'id'      => '',
446                    'name'    => '',
447                    'desc'    => '',
448                    'url'     => '',
449                    'host'    => '',
450                    'creadt'  => '',
451                    'upddt'   => ''
452               );
453     }
454     
455     /**
456     Get current user information
457     */
458     protected function getCurrentUser()
459     {
460          $infos = array(
461               'pwd','name','firstname','displayname',
462               'email','url','default_blog','lang','tz',
463               'post_status','creadt','upddt','cn'
464          );
465         
466          $user = array(
467               'id' => '',
468               'super' => false,
469               'lang' => 'en',
470               'options' => $this->core->userDefaults(),
471               'prefs' => array(),
472               'rights' => array(
473                    'media' => false
474               )
475          );
476         
477          foreach($infos as $i) {
478               $user[$i] = '';
479          }
480         
481          if ($this->core->auth->userID()) {
482         
483               $user = array(
484                    'id' => $this->core->auth->userID(),
485                    'super' => $this->core->auth->isSuperAdmin(),
486                    'options' => $this->core->auth->getOptions(),
487                    'rights' => array(
488                         'media' => $this->core->auth->check('media,media_admin',$this->core->blog->id)
489                    )
490               );
491               
492               foreach($infos as $i) {
493                    $user[$i] = $this->core->auth->getInfo('user_'.$i);
494               }
495               
496               foreach($this->core->auth->user_prefs->dumpWorkspaces() as $ws => $prefs) {
497                    $user['prefs'][$ws] = $prefs->dumpPrefs();
498               }
499          }
500         
501          $this->protected_globals['current_user'] = $user;
502     }
503     
504     /**
505     Get sidebar menus
506     */
507     protected function getMenus()
508     {
509          global $_menu;
510         
511          $this->protected_globals['menus'] = array();
512         
513          if (!isset($_menu)) {
514               return;
515          }
516         
517          foreach($_menu as $m) {
518               $this->protected_globals['menus'][] = array(
519                    'id'           => $m->getID(),
520                    'title'        => $m->getTitle(),
521                    'separator'    => $m->getSeparator(),
522                    'items'        => $m->getItems()
523               );
524          }
525     }
526     
527     /**
528     Get an array of debug/dev infos
529     */
530     public function getDebugInfo()
531     {
532          if (!DC_DEBUG) {
533               return array();
534          }
535         
536          $di = array(
537               'global_vars' => implode(', ',array_keys($GLOBALS)),
538               'memory' => array(
539                    'usage' => memory_get_usage(),
540                    'size' => files::size(memory_get_usage())
541               ),
542               'xdebug' => array()
543          );
544         
545          if (function_exists('xdebug_get_profiler_filename')) {
546         
547               $url = http::getSelfURI();
548               $url .= strpos($url,'?') === false ? '?' : '&';
549               $url .= 'XDEBUG_PROFILE';
550               
551               $di['xdebug'] = array(
552                    'elapse_time' => xdebug_time_index(),
553                    'profiler_file' => xdebug_get_profiler_filename(),
554                    'profiler_url' =>  $url
555               );
556               
557               /* xdebug configuration:
558               zend_extension = /.../xdebug.so
559               xdebug.auto_trace = On
560               xdebug.trace_format = 0
561               xdebug.trace_options = 1
562               xdebug.show_mem_delta = On
563               xdebug.profiler_enable = 0
564               xdebug.profiler_enable_trigger = 1
565               xdebug.profiler_output_dir = /tmp
566               xdebug.profiler_append = 0
567               xdebug.profiler_output_name = timestamp
568               */
569          }
570         
571          return $di;
572     }
573     
574     /**
575     Add a value in a namespace memory
576     
577     This help keep variable when recalling Twig macros
578     
579     @param string $ns A namespace
580     @param string $str A value to memorize in this namespace
581     */
582     public function setMemory($ns,$str)
583     {
584          if (!array_key_exists($ns,$this->memory) || !in_array($str,$this->memory[$ns])) {
585               $this->memory[$ns][] = $str;
586          }
587     }
588     
589     /**
590     Check if a value is previously memorized in a namespace
591     
592     @param string $ns A namespace
593     @param string $str A value to search in this namespace
594     @return array True if exists
595     */
596     public function getMemory($ns,$str)
597     {
598          return array_key_exists($ns,$this->memory) && in_array($str,$this->memory[$ns]);
599     }
600}
601?>
Note: See TracBrowser for help on using the repository browser.

Sites map