source: extensions/AMenuManager/amm_pip.class.inc.php @ 14518

Last change on this file since 14518 was 12665, checked in by grum, 12 years ago

feature:2522 - Incompatibility with other plugin managing the menu content

  • Property svn:executable set to *
File size: 13.9 KB
Line 
1<?php
2/* -----------------------------------------------------------------------------
3  Plugin     : Advanced Menu Manager
4  Author     : Grum
5    email    : grum@piwigo.org
6    website  : http://photos.grum.fr
7    PWG user : http://forum.phpwebgallery.net/profile.php?id=3706
8
9    << May the Little SpaceFrog be with you ! >>
10  ------------------------------------------------------------------------------
11  See main.inc.php for release information
12
13  PIP classe => manage integration in public interface
14
15  --------------------------------------------------------------------------- */
16if (!defined('PHPWG_ROOT_PATH')) { die('Hacking attempt!'); }
17
18include_once(PHPWG_PLUGINS_PATH.'AMenuManager/amm_root.class.inc.php');
19include_once(PHPWG_PLUGINS_PATH.'GrumPluginClasses/classes/GPCAjax.class.inc.php');
20
21class AMM_PIP extends AMM_root
22{
23  protected $displayRandomImageBlock=true;
24  protected $registeredBlocks;
25  protected $randomPictProp=null;
26  protected $users;
27  protected $groups;
28  protected $currentBuiltMenu=-1;
29
30  function AMM_PIP($prefixeTable, $filelocation)
31  {
32    parent::__construct($prefixeTable, $filelocation);
33    $this->css = new GPCCss(dirname($this->getFileLocation()).'/'.$this->getPluginNameFiles()."2.css");
34
35    $this->users=new GPCUsers();
36    $this->groups=new GPCGroups();
37
38    $this->loadConfig();
39    $this->initEvents();
40  }
41
42
43  /**
44   * initialize events call for the plugin
45   */
46  public function initEvents()
47  {
48    parent::initEvents();
49
50    add_event_handler('blockmanager_prepare_display', array(&$this, 'blockmanagerSortBlocks') );
51    add_event_handler('blockmanager_apply', array(&$this, 'blockmanagerApply'), 45 );
52    add_event_handler('loc_end_page_header', array(&$this->css, 'applyCSS'));
53    add_event_handler('loc_end_page_header', array(&$this, 'applyJS'));
54    add_event_handler('get_categories_menu_sql_where', array(&$this, 'buildMenuFromCat'), 75);
55  }
56
57
58  public function blockmanagerApply($menu_ref_arr)
59  {
60    $menu=&$menu_ref_arr[0];
61
62    $this->addBlockRandomPicture($menu);
63    $this->addBlockLinks($menu);
64    $this->addBlockPersonnal($menu);
65    $this->addBlockAlbum($menu);
66    $this->manageBlocksContent($menu);
67    $this->manageBlocks($menu);
68  }
69
70
71  /**
72   * Add a new random picture block
73   */
74  private function addBlockRandomPicture(&$menu)
75  {
76    global $user;
77
78    if((
79        ($block=$menu->get_block('mbAMM_randompict'))!=null) and
80        ($user['nb_total_images']>0) and
81        isset($this->config['amm_randompicture_title'][$user['language']]) and
82        $this->displayRandomImageBlock
83      )
84    {
85      GPCCore::addHeaderJS('jquery', 'themes/default/js/jquery.min.js');
86      GPCCore::addHeaderJS('amm.randomPictPublic', 'plugins/AMenuManager/js/amm_randomPictPublic'.GPCCore::getMinified().'.js', array('jquery'));
87
88      $block->set_title(base64_decode($this->config['amm_randompicture_title'][$user['language']]));
89      $block->template=dirname(__FILE__).'/menu_templates/menubar_randompic.tpl';
90
91      $this->randomPictProp = array(
92        'delay' => $this->config['amm_randompicture_periodicchange'],
93        'blockHeight' => $this->config['amm_randompicture_height'],
94        'showname' => $this->config['amm_randompicture_showname'],
95        'showcomment' => $this->config['amm_randompicture_showcomment'],
96        'pictures' => $this->getRandomPictures($this->config['amm_randompicture_preload'])
97      );
98
99      if(count($this->randomPictProp['pictures'])==0) $this->displayRandomImageBlock=false;
100    }
101    else
102    {
103      $this->displayRandomImageBlock=false;
104    }
105  }
106
107
108  /**
109   * Add a new block (links)
110   */
111  private function addBlockLinks(&$menu)
112  {
113    global $user;
114
115    $nbLink=0;
116
117    if(($block=$menu->get_block('mbAMM_links'))!=null &&
118       isset($this->config['amm_links_title'][$user['language']])
119      )
120    {
121      $urls=$this->getLinks(true);
122
123      if(count($urls)>0)
124      {
125        $userGroups=$this->getUserGroups($user['id']);;
126
127        foreach($urls as $key => $val)
128        {
129          $this->users->setAlloweds(explode(",", $val['accessUsers']), false);
130          $this->groups->setAlloweds(explode(",", $val['accessGroups']), false);
131
132          if(!$this->users->isAllowed($user['status']))
133          {
134            unset($urls[$key]);
135          }
136          else
137          {
138            $ok=true;
139            foreach($userGroups as $group)
140            {
141              if(!$this->groups->isAllowed($group)) $ok=false;
142            }
143            if(!$ok) unset($urls[$key]);
144          }
145        }
146
147        if($this->config['amm_links_show_icons']=='y')
148        {
149          foreach($urls as $key => $url)
150          {
151            $urls[$key]['icon']=get_root_url().'plugins/'.AMM_DIR."/links_pictures/".$url['icon'];
152          }
153        }
154
155        $block->set_title(base64_decode($this->config['amm_links_title'][$user['language']]));
156        $block->template=dirname(__FILE__).'/menu_templates/menubar_links.tpl';
157
158        $block->data = array(
159          'LINKS' => $urls,
160          'icons' => $this->config['amm_links_show_icons']
161        );
162      }
163    }
164  }
165
166
167  /**
168   * Add personnal blocks
169   */
170  private function addBlockPersonnal(&$menu)
171  {
172    $sections=$this->getPersonalisedBlocks(true);
173
174    if(count($sections))
175    {
176      $idDone=array();
177      foreach($sections as $key => $val)
178      {
179        if(!isset($idDone[$val['id']]))
180        {
181          if(($block=$menu->get_block('mbAMM_personalised'.$val['id']))!= null)
182          {
183            $block->set_title($val['title']);
184            $block->template = dirname(__FILE__).'/menu_templates/menubar_personalised.tpl';
185            $block->data = stripslashes($val['content']);
186          }
187          $idDone[$val['id']]="";
188        }
189      }
190    }
191  }
192
193
194
195
196  /**
197   * Add album to menu
198   */
199  private function addBlockAlbum(&$menu)
200  {
201    if(count($this->config['amm_albums_to_menu'])>0)
202    {
203      $sql="SELECT id, name, permalink, global_rank
204            FROM ".CATEGORIES_TABLE."
205            WHERE id IN(".implode(',', $this->config['amm_albums_to_menu']).");";
206
207      $result=pwg_query($sql);
208      if($result)
209      {
210        while($row=pwg_db_fetch_assoc($result))
211        {
212          $this->currentBuiltMenu=$row['id'];
213
214          $row['name']=trigger_event('render_category_name', $row['name'], 'amm_album_to_menu');
215
216          if(($block=$menu->get_block('mbAMM_album'.$row['id']))!= null)
217          {
218            $block->set_title($row['name']);
219            $block->template = dirname(__FILE__).'/menu_templates/menubar_album.tpl';
220            $block->data = array(
221              'album' => get_categories_menu(),
222              'name' => $row['name'],
223              'link' => make_index_url(array('category' => $row)),
224              'nbPictures' => ''
225            );
226/*
227            $nbImages=0;
228            foreach($block->data['album'] as $val)
229            {
230              $nbImages+=$val['nb_images'];
231            }
232            $block->data['nbPictures']="*** $nbImages";
233*/
234          }
235        }
236      }
237      $this->currentBuiltMenu=-1;
238    }
239  }
240
241  /**
242   * manage items from special & menu blocks
243   *  - reordering items
244   *  - grouping items
245   *  - managing rights to access
246   */
247  private function manageBlocksContent(&$menu)
248  {
249    global $user;
250
251    $blocks=Array();
252
253    if($menu->is_hidden('mbMenu'))
254    {
255      // if block is hidden, make a fake to manage AMM submenu features
256      // the fake block isn't displayed
257      $blocks['menu']=new DisplayBlock('amm_mbMenu');
258      $blocks['menu']->data=Array();
259    }
260    else
261    {
262      $blocks['menu']=$menu->get_block('mbMenu');
263    }
264
265    if($menu->is_hidden('mbSpecials'))
266    {
267      // if block is hidden, make a fake to manage AMM submenu features
268      // the fake block isn't displayed
269      $blocks['special']=new DisplayBlock('amm_mbSpecial');
270      $blocks['special']->data=Array();
271    }
272    else
273    {
274      $blocks['special']=$menu->get_block('mbSpecials');
275    }
276
277    $menuItems=array_merge($blocks['menu']->data, $blocks['special']->data);
278    $this->sortCoreBlocksItems();
279
280    $blocks['menu']->data=Array();
281    $blocks['special']->data=Array();
282    $userGroups=$this->getUserGroups($user['id']);
283
284    foreach($this->config['amm_blocks_items'] as $key => $val)
285    {
286      if(isset($menuItems[$key]))
287      {
288        $access=explode("/",$val['visibility']);
289        $this->users->setAlloweds(str_replace(",", "/", $access[0]), false);
290        $this->groups->setAlloweds(str_replace(",", "/", $access[1]), false);
291
292        /*
293         * test if user status is allowed to access the menu item
294         * if access is managed by group, the user have to be associated with an allowed group to access the menu item
295         */
296        if($this->users->isAllowed($user['status']))
297        {
298          $ok=true;
299          foreach($userGroups as $group)
300          {
301            if(!$this->groups->isAllowed($group)) $ok=false;
302          }
303          if($ok) $blocks[$val['container']]->data[$key]=$menuItems[$key];
304        }
305      }
306    }
307    if(count($blocks['menu']->data)==0) $menu->hide_block('mbMenu');
308    if(count($blocks['special']->data)==0) $menu->hide_block('mbSpecials');
309  }
310
311
312  /**
313   * return groups for a user
314   *
315   * @param String $userId
316   * @return Array
317   */
318  private function getUserGroups($userId)
319  {
320    global $user;
321
322    $returned=array();
323
324    $sql="SELECT group_id FROM ".USER_GROUP_TABLE." WHERE user_id='".$user['id']."';";
325    $result=pwg_query($sql);
326    if($result)
327    {
328      while($row=pwg_db_fetch_assoc($result))
329      {
330        $returned[]=$row['group_id'];
331      }
332    }
333    return($returned);
334  }
335
336
337  /**
338   * reordering blocks and manage access right
339   *
340   */
341  private function manageBlocks($menu)
342  {
343    $this->registeredBlocks=$this->getRegisteredBlocks(true);
344
345    foreach($menu->get_registered_blocks() as $key => $block)
346    {
347      if(!isset($this->registeredBlocks[$block->get_id()]))
348      {
349        $menu->hide_block($block->get_id());
350      }
351    }
352
353  }
354
355
356  /**
357   * sort menu blocks according to AMM rules (overriding piwigo's sort rules)
358   */
359  public function blockmanagerSortBlocks($blocks)
360  {
361    $this->registeredBlocks=$this->getRegisteredBlocks(true);
362
363    if(!isset($this->registeredBlocks['mbAMM_randompict'])) $this->displayRandomImageBlock=false;
364
365    foreach($blocks[0]->get_registered_blocks() as $key => $block)
366    {
367      if(isset($this->registeredBlocks[$block->get_id()]))
368      {
369        $blocks[0]->set_block_position($block->get_id(), $this->registeredBlocks[$block->get_id()]['order']);
370      }
371    }
372  }
373
374
375
376
377
378
379
380  /**
381   * return a list of thumbnails
382   * each array items is an array
383   *  'imageId'   => (integer)
384   *  'imageFile' => (String)
385   *  'comment'   => (String)
386   *  'path'      => (String)
387   *  'tn_ext'    => (String)
388   *  'catId'     => (String)
389   *  'name'      => (String)
390   *  'permalink' => (String)
391   *  'imageName' => (String)
392   *
393   * @param Integer $number : number of returned images
394   * @return Array
395   */
396  private function getRandomPictures($num=25)
397  {
398    global $user;
399
400    $returned=array();
401
402    $sql=array();
403
404    $sql['select']="SELECT i.id as image_id, i.file as image_file, i.comment, i.path, i.tn_ext, c.id as catid, c.name, c.permalink, RAND() as rndvalue, i.name as imgname ";
405    $sql['from']="FROM ".CATEGORIES_TABLE." c, ".IMAGES_TABLE." i, ".IMAGE_CATEGORY_TABLE." ic ";
406    $sql['where']="WHERE c.id = ic.category_id
407            AND ic.image_id = i.id
408            AND i.level <= ".$user['level']." ";
409
410    if($user['forbidden_categories']!="")
411    {
412      $sql['where'].=" AND c.id NOT IN (".$user['forbidden_categories'].") ";
413    }
414
415    switch($this->config['amm_randompicture_selectMode'])
416    {
417      case 'f':
418        $sql['from'].=", ".USER_INFOS_TABLE." ui
419          LEFT JOIN ".FAVORITES_TABLE." f ON ui.user_id=f.user_id ";
420        $sql['where'].=" AND ui.status='webmaster'
421                         AND f.image_id = i.id ";
422        break;
423      case 'c':
424        $sql['where'].="AND (";
425        foreach($this->config['amm_randompicture_selectCat'] as $key => $val)
426        {
427          $sql['where'].=($key==0?'':' OR ')." FIND_IN_SET($val, c.uppercats) ";
428        }
429        $sql['where'].=") ";
430        break;
431    }
432
433    $sql=$sql['select'].$sql['from'].$sql['where']." ORDER BY rndvalue LIMIT 0,$num";
434
435
436    $result = pwg_query($sql);
437    if($result)
438    {
439      while($row=pwg_db_fetch_assoc($result))
440      {
441        $row['section']='category';
442        $row['category']=array(
443          'id' => $row['catid'],
444          'name' => $row['name'],
445          'permalink' => $row['permalink']
446        );
447
448        $row['link']=make_picture_url($row);
449        $row['thumb']=get_thumbnail_url($row);
450
451        $returned[]=$row;
452      }
453    }
454
455    return($returned);
456  }
457
458
459
460
461  public function applyJS()
462  {
463    global $user, $template, $page;
464
465    if(!array_key_exists('body_id', $page))
466    {
467      /*
468       * it seems the error message reported on mantis:1476 is displayed because
469       * the 'body_id' doesn't exist in the $page
470       *
471       * not abble to reproduce the error, but initializing the key to an empty
472       * value if it doesn't exist may be a sufficient solution
473       */
474      $page['body_id']="";
475    }
476
477
478    if($this->displayRandomImageBlock && $page['body_id'] == 'theCategoryPage')
479    {
480      $local_tpl = new Template(AMM_PATH."admin/", "");
481      $local_tpl->set_filename('body_page', dirname($this->getFileLocation()).'/menu_templates/menubar_randompic.js.tpl');
482
483      $local_tpl->assign('data', $this->randomPictProp);
484
485      $template->append('head_elements', $local_tpl->parse('body_page', true));
486    }
487  }
488
489
490
491  public function buildMenuFromCat($where)
492  {
493    global $user;
494
495    if($this->currentBuiltMenu>-1)
496    {
497      if($user['expand'])
498      {
499        $where=preg_replace('/id_uppercat\s+is\s+NULL/i', 'id_uppercat is NOT NULL', $where);
500      }
501      else
502      {
503        $where=preg_replace('/id_uppercat\s+is\s+NULL/i', 'id_uppercat is NULL OR id_uppercat IN ('.$this->currentBuiltMenu.')', $where);
504      }
505
506      $where.=" AND FIND_IN_SET(".$this->currentBuiltMenu.", uppercats) AND cat_id!=".$this->currentBuiltMenu." ";
507    }
508
509    return($where);
510  }
511
512} // AMM_PIP class
513
514
515?>
Note: See TracBrowser for help on using the repository browser.