Dotclear

source: inc/admin/class.dc.admincontext.php @ 2654:5818627b7cc1

Revision 2654:5818627b7cc1, 14.2 KB checked in by Dsls, 11 years ago (diff)

Twig no more in hg, welcome composer. Small tunings, need to see favs in index.

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

Sites map