Dotclear

source: inc/admin/class.dc.favorites.php @ 3874:ab8368569446

Revision 3874:ab8368569446, 17.6 KB checked in by franck <carnet.franck.paul@…>, 7 years ago (diff)

short notation for array (array() → [])

Line 
1<?php
2/**
3 * @package Dotclear
4 * @subpackage Backend
5 *
6 * @copyright Olivier Meunier & Association Dotclear
7 * @copyright GPL-2.0-only
8 */
9
10if (!defined('DC_RC_PATH')) {return;}
11
12/**
13 * dcFavorites -- Favorites handling facilities
14 *
15 */
16class dcFavorites
17{
18    /** @var dcCore dotclear core instance */
19    protected $core;
20
21    /** @var array list of favorite definitions  */
22    protected $fav_defs;
23
24    /** @var dcWorkspace current favorite landing workspace */
25    protected $ws;
26
27    /** @var array list of user-defined favorite ids */
28    protected $local_prefs;
29
30    /** @var array list of globally-defined favorite ids */
31    protected $global_prefs;
32
33    /** @var array list of user preferences (either one of the 2 above, or not!) */
34    protected $user_prefs;
35
36    /**
37     * Class constructor
38     *
39     * @param mixed  $core   dotclear core
40     *
41     * @access public
42     *
43     * @return mixed Value.
44     */
45    public function __construct($core)
46    {
47        $this->core       = $core;
48        $this->fav_defs   = new ArrayObject();
49        $this->ws         = $core->auth->user_prefs->addWorkspace('dashboard');
50        $this->user_prefs = [];
51
52        if ($this->ws->prefExists('favorites')) {
53            $this->local_prefs  = $this->ws->getLocal('favorites');
54            $this->global_prefs = $this->ws->getGlobal('favorites');
55            // Since we never know what user puts through user:preferences ...
56            if (!is_array($this->local_prefs)) {
57                $this->local_prefs = [];
58            }
59            if (!is_array($this->global_prefs)) {
60                $this->global_prefs = [];
61            }
62        } else {
63            // No favorite defined ? Huhu, let's go for a migration
64            $this->migrateFavorites();
65        }
66    }
67
68    /**
69     * setup - sets up favorites, fetch user favorites (against his permissions)
70     *            This method is to be called after loading plugins
71     *
72     * @access public
73     *
74     */
75    public function setup()
76    {
77        defaultFavorites::initDefaultFavorites($this);
78        $this->legacyFavorites();
79        $this->core->callBehavior('adminDashboardFavorites', $this->core, $this);
80        $this->setUserPrefs();
81    }
82
83    /**
84     * getFavorite - retrieves a favorite (complete description) from its id.
85     *
86     * @param string  $id   the favorite id, or an array having 1 key 'name' set to id, ther keys are merged to favorite.
87     *
88     * @access public
89     *
90     * @return array the favorite, false if not found (or not permitted)
91     */
92    public function getFavorite($p)
93    {
94        if (is_array($p)) {
95            $fname = $p['name'];
96            if (!isset($this->fav_defs[$fname])) {
97                return false;
98            }
99            $fattr = $p;
100            unset($fattr['name']);
101            $fattr = array_merge($this->fav_defs[$fname], $fattr);
102        } else {
103            if (!isset($this->fav_defs[$p])) {
104                return false;
105            }
106            $fattr = $this->fav_defs[$p];
107        }
108        $fattr = array_merge(['id' => null, 'class' => null], $fattr);
109        if (isset($fattr['permissions'])) {
110            if (is_bool($fattr['permissions']) && !$fattr['permissions']) {
111                return false;
112            }
113            if (!$this->core->auth->check($fattr['permissions'], $this->core->blog->id)) {
114                return false;
115            }
116        } elseif (!$this->core->auth->isSuperAdmin()) {
117            return false;
118        }
119        return $fattr;
120    }
121
122    /**
123     * getFavorites - retrieves a list of favorites.
124     *
125     * @param string  $ids   an array of ids, as defined in getFavorite.
126     *
127     * @access public
128     *
129     * @return array array of favorites, can be empty if ids are not found (or not permitted)
130     */
131    public function getFavorites($ids)
132    {
133        $prefs = [];
134        foreach ($ids as $id) {
135            $f = $this->getFavorite($id);
136            if ($f !== false) {
137                $prefs[$id] = $f;
138            }
139        }
140        return $prefs;
141    }
142
143    /**
144     * setUserPrefs - get user favorites from settings. These are complete favorites, not ids only
145     *                 returned favorites are the first non-empty list from :
146     *                 * user-defined favorites
147     *                 * globally-defined favorites
148     *                 * a failback list "new post" (shall never be empty)
149     *                This method is called by ::setup()
150     * @access protected
151     *
152     */
153    protected function setUserPrefs()
154    {
155        $this->user_prefs = $this->getFavorites($this->local_prefs);
156        if (!count($this->user_prefs)) {
157            $this->user_prefs = $this->getFavorites($this->global_prefs);
158        }
159        if (!count($this->user_prefs)) {
160            $this->user_prefs = $this->getFavorites(['new_post']);
161        }
162        $u = explode('?', $_SERVER['REQUEST_URI']);
163        // Loop over prefs to enable active favorites
164        foreach ($this->user_prefs as $k => &$v) {
165            if (isset($v['active_cb']) && is_callable($v['active_cb'])) {
166                // Use callback if defined to match whether favorite is active or not
167                $v['active'] = call_user_func($v['active_cb'], $u[0], $_REQUEST);
168            } else {
169                                     // Failback active detection. We test against URI name & parameters
170                $v['active'] = true; // true until something proves it is false
171                $u           = explode('?', $v['url'], 2);
172                if (!preg_match('/' . preg_quote($u[0], "/") . '/', $_SERVER['REQUEST_URI'])) {
173                    $v['active'] = false; // no URI match
174                }
175                if (count($u) == 2) {
176                    parse_str($u[1], $p);
177                    // test against each request parameter.
178                    foreach ($p as $k2 => $v2) {
179                        if (!isset($_REQUEST[$k2]) || $_REQUEST[$k2] !== $v2) {
180                            $v['active'] = false;
181                        }
182                    }
183                }
184            }
185        }
186    }
187
188    /**
189     * migrateFavorites - migrate dc < 2.6 favorites to new format
190     *
191     * @access protected
192     *
193     */
194    protected function migrateFavorites()
195    {
196        $fav_ws             = $this->core->auth->user_prefs->addWorkspace('favorites');
197        $this->local_prefs  = [];
198        $this->global_prefs = [];
199        foreach ($fav_ws->dumpPrefs() as $k => $v) {
200            $fav = @unserialize($v['value']);
201            if (is_array($fav)) {
202                if ($v['global']) {
203                    $this->global_prefs[] = $fav['name'];
204                } else {
205                    $this->local_prefs[] = $fav['name'];
206                }
207            }
208        }
209        $this->ws->put('favorites', $this->global_prefs, 'array', 'User favorites', true, true);
210        $this->ws->put('favorites', $this->local_prefs);
211        $this->user_prefs = $this->getFavorites($this->local_prefs);
212    }
213
214    /**
215     * legacyFavorites - handle legacy favorites using adminDashboardFavs behavior
216     *
217     * @access protected
218     *
219     */
220    protected function legacyFavorites()
221    {
222        $f = new ArrayObject();
223        $this->core->callBehavior('adminDashboardFavs', $this->core, $f);
224        foreach ($f as $k => $v) {
225            $fav = [
226                'title'       => __($v[1]),
227                'url'         => $v[2],
228                'small-icon'  => $v[3],
229                'large-icon'  => $v[4],
230                'permissions' => $v[5],
231                'id'          => $v[6],
232                'class'       => $v[7]
233            ];
234            $this->register($v[0], $fav);
235        }
236
237    }
238
239    /**
240     * getUserFavorites - returns favorites that correspond to current user
241     *   (may be local, global, or failback favorites)
242     *
243     * @access public
244     *
245     * @return array array of favorites (enriched)
246     */
247    public function getUserFavorites()
248    {
249        return $this->user_prefs;
250    }
251
252    /**
253     * getFavoriteIDs - returns user-defined or global favorites ids list
254     *                    shall not be called outside preferences.php...
255     *
256     * @param boolean  $global   if true, retrieve global favs, user favs otherwise
257     *
258     * @access public
259     *
260     * @return array array of favorites ids (only ids, not enriched)
261     */
262    public function getFavoriteIDs($global = false)
263    {
264        return $global ? $this->global_prefs : $this->local_prefs;
265    }
266
267    /**
268     * setFavoriteIDs - stores user-defined or global favorites ids list
269     *                    shall not be called outside preferences.php...
270     *
271     * @param array  $ids   list of fav ids
272     * @param boolean  $global   if true, retrieve global favs, user favs otherwise
273     *
274     * @access public
275     */
276    public function setFavoriteIDs($ids, $global = false)
277    {
278        $this->ws->put('favorites', $ids, 'array', null, true, $global);
279    }
280
281    /**
282     * getAvailableFavoritesIDs - returns all available fav ids
283     *
284     * @access public
285     *
286     * @return array array of favorites ids (only ids, not enriched)
287     */
288    public function getAvailableFavoritesIDs()
289    {
290        return array_keys($this->fav_defs->getArrayCopy());
291    }
292
293    /**
294     * appendMenuTitle - adds favorites section title to sidebar menu
295     *                    shall not be called outside admin/prepend.php...
296     *
297     * @param dcMenu  $menu   admin menu instance
298     *
299     * @access public
300     */
301    public function appendMenuTitle($menu)
302    {
303        $menu['Favorites']        = new dcMenu('favorites-menu', 'My favorites');
304        $menu['Favorites']->title = __('My favorites');
305    }
306
307    /**
308     * appendMenu - adds favorites items title to sidebar menu
309     *                    shall not be called outside admin/prepend.php...
310     *
311     * @param dcMenu  $menu   admin menu instance
312     *
313     * @access public
314     */
315    public function appendMenu($menu)
316    {
317        foreach ($this->user_prefs as $k => $v) {
318            $menu['Favorites']->addItem(
319                $v['title'],
320                $v['url'],
321                $v['small-icon'],
322                $v['active'],
323                true,
324                $v['id'],
325                $v['class'],
326                true
327            );
328        }
329    }
330
331    /**
332     * appendDashboardIcons - adds favorites icons to index page
333     *                    shall not be called outside admin/index.php...
334     *
335     * @param array  $icons   dashboard icon list to enrich
336     *
337     * @access public
338     */
339    public function appendDashboardIcons($icons)
340    {
341        foreach ($this->user_prefs as $k => $v) {
342            if (isset($v['dashboard_cb']) && is_callable($v['dashboard_cb'])) {
343                $v = new ArrayObject($v);
344                call_user_func($v['dashboard_cb'], $this->core, $v);
345            }
346            $icons[$k] = new ArrayObject([$v['title'], $v['url'], $v['large-icon']]);
347            $this->core->callBehavior('adminDashboardFavsIcon', $this->core, $k, $icons[$k]);
348        }
349    }
350
351    /**
352     * register - registers a new favorite definition
353     *
354     * @param string  $id   favorite id
355     * @param array  $data favorite information. Array keys are :
356     *    'title' => favorite title (localized)
357     *    'url' => favorite URL,
358     *    'small-icon' => favorite small icon (for menu)
359     *    'large-icon' => favorite large icon (for dashboard)
360     *    'permissions' => (optional) comma-separated list of permissions for thie fav, if not set : no restriction
361     *    'dashboard_cb' => (optional) callback to modify title if dynamic, if not set : title is taken as is
362     *    'active_cb' => (optional) callback to tell whether current page matches favorite or not, for complex pages
363     *
364     * @access public
365     */
366    public function register($id, $data)
367    {
368        $this->fav_defs[$id] = $data;
369        return $this;
370    }
371
372    /**
373     * registerMultiple - registers a list of favorites definition
374     *
375     * @param array an array defining all favorites key is the id, value is the data.
376     *                see register method for data format
377     * @access public
378     */
379    public function registerMultiple($data)
380    {
381        foreach ($data as $k => $v) {
382            $this->register($k, $v);
383        }
384        return $this;
385    }
386
387    /**
388     * exists - tells whether a fav definition exists or not
389     *
390     * @param string $id : the fav id to test
391     *
392     * @access public
393     *
394     * @return true if the fav definition exists, false otherwise
395     */
396    public function exists($id)
397    {
398        return isset($this->fav_defs[$id]);
399    }
400
401}
402
403/**
404 * defaultFavorites -- default favorites definition
405 *
406 */
407class defaultFavorites
408{
409    public static function initDefaultFavorites($favs)
410    {
411        $core = &$GLOBALS['core'];
412        $favs->registerMultiple([
413            'prefs'      => [
414                'title'      => __('My preferences'),
415                'url'        => $core->adminurl->get("admin.user.preferences"),
416                'small-icon' => 'images/menu/user-pref.png',
417                'large-icon' => 'images/menu/user-pref-b.png'],
418            'new_post'   => [
419                'title'       => __('New entry'),
420                'url'         => $core->adminurl->get("admin.post"),
421                'small-icon'  => 'images/menu/edit.png',
422                'large-icon'  => 'images/menu/edit-b.png',
423                'permissions' => 'usage,contentadmin'],
424            'posts'      => [
425                'title'        => __('Posts'),
426                'url'          => $core->adminurl->get("admin.posts"),
427                'small-icon'   => 'images/menu/entries.png',
428                'large-icon'   => 'images/menu/entries-b.png',
429                'permissions'  => 'usage,contentadmin',
430                'dashboard_cb' => ['defaultFavorites', 'postsDashboard']],
431            'comments'   => [
432                'title'        => __('Comments'),
433                'url'          => $core->adminurl->get("admin.comments"),
434                'small-icon'   => 'images/menu/comments.png',
435                'large-icon'   => 'images/menu/comments-b.png',
436                'permissions'  => 'usage,contentadmin',
437                'dashboard_cb' => ['defaultFavorites', 'commentsDashboard']],
438            'search'     => [
439                'title'       => __('Search'),
440                'url'         => $core->adminurl->get("admin.search"),
441                'small-icon'  => 'images/menu/search.png',
442                'large-icon'  => 'images/menu/search-b.png',
443                'permissions' => 'usage,contentadmin'],
444            'categories' => [
445                'title'       => __('Categories'),
446                'url'         => $core->adminurl->get("admin.categories"),
447                'small-icon'  => 'images/menu/categories.png',
448                'large-icon'  => 'images/menu/categories-b.png',
449                'permissions' => 'categories'],
450            'media'      => [
451                'title'       => __('Media manager'),
452                'url'         => $core->adminurl->get("admin.media"),
453                'small-icon'  => 'images/menu/media.png',
454                'large-icon'  => 'images/menu/media-b.png',
455                'permissions' => 'media,media_admin'],
456            'blog_pref'  => [
457                'title'       => __('Blog settings'),
458                'url'         => $core->adminurl->get("admin.blog.pref"),
459                'small-icon'  => 'images/menu/blog-pref.png',
460                'large-icon'  => 'images/menu/blog-pref-b.png',
461                'permissions' => 'admin'],
462            'blog_theme' => [
463                'title'       => __('Blog appearance'),
464                'url'         => $core->adminurl->get("admin.blog.theme"),
465                'small-icon'  => 'images/menu/themes.png',
466                'large-icon'  => 'images/menu/blog-theme-b.png',
467                'permissions' => 'admin'],
468            'blogs'      => [
469                'title'       => __('Blogs'),
470                'url'         => $core->adminurl->get("admin.blogs"),
471                'small-icon'  => 'images/menu/blogs.png',
472                'large-icon'  => 'images/menu/blogs-b.png',
473                'permissions' => 'usage,contentadmin'],
474            'users'      => [
475                'title'      => __('Users'),
476                'url'        => $core->adminurl->get("admin.users"),
477                'small-icon' => 'images/menu/users.png',
478                'large-icon' => 'images/menu/users-b.png'],
479            'plugins'    => [
480                'title'      => __('Plugins management'),
481                'url'        => $core->adminurl->get("admin.plugins"),
482                'small-icon' => 'images/menu/plugins.png',
483                'large-icon' => 'images/menu/plugins-b.png'],
484            'langs'      => [
485                'title'      => __('Languages'),
486                'url'        => $core->adminurl->get("admin.langs"),
487                'small-icon' => 'images/menu/langs.png',
488                'large-icon' => 'images/menu/langs-b.png'],
489            'help'       => [
490                'title'      => __('Global help'),
491                'url'        => $core->adminurl->get("admin.help"),
492                'small-icon' => 'images/menu/help.png',
493                'large-icon' => 'images/menu/help-b.png']
494        ]);
495    }
496
497    public static function postsDashboard($core, $v)
498    {
499        $post_count  = $core->blog->getPosts([], true)->f(0);
500        $str_entries = __('%d post', '%d posts', $post_count);
501        $v['title']  = sprintf($str_entries, $post_count);
502    }
503
504    public static function commentsDashboard($core, $v)
505    {
506        $comment_count = $core->blog->getComments([], true)->f(0);
507        $str_comments  = __('%d comment', '%d comments', $comment_count);
508        $v['title']    = sprintf($str_comments, $comment_count);
509    }
510}
Note: See TracBrowser for help on using the repository browser.

Sites map