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

Last change on this file since 13895 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
RevLine 
[3681]1<?php
2/* -----------------------------------------------------------------------------
3  Plugin     : Advanced Menu Manager
4  Author     : Grum
[3690]5    email    : grum@piwigo.org
6    website  : http://photos.grum.fr
[3681]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');
[5545]19include_once(PHPWG_PLUGINS_PATH.'GrumPluginClasses/classes/GPCAjax.class.inc.php');
[3681]20
21class AMM_PIP extends AMM_root
22{
[4382]23  protected $displayRandomImageBlock=true;
[8962]24  protected $registeredBlocks;
25  protected $randomPictProp=null;
26  protected $users;
27  protected $groups;
28  protected $currentBuiltMenu=-1;
[3681]29
30  function AMM_PIP($prefixeTable, $filelocation)
31  {
32    parent::__construct($prefixeTable, $filelocation);
[5545]33    $this->css = new GPCCss(dirname($this->getFileLocation()).'/'.$this->getPluginNameFiles()."2.css");
[3681]34
[8962]35    $this->users=new GPCUsers();
36    $this->groups=new GPCGroups();
37
[5545]38    $this->loadConfig();
39    $this->initEvents();
[3681]40  }
41
42
[8962]43  /**
44   * initialize events call for the plugin
45   */
[5545]46  public function initEvents()
[3681]47  {
[5545]48    parent::initEvents();
[8962]49
50    add_event_handler('blockmanager_prepare_display', array(&$this, 'blockmanagerSortBlocks') );
[12665]51    add_event_handler('blockmanager_apply', array(&$this, 'blockmanagerApply'), 45 );
[5545]52    add_event_handler('loc_end_page_header', array(&$this->css, 'applyCSS'));
[8962]53    add_event_handler('loc_end_page_header', array(&$this, 'applyJS'));
54    add_event_handler('get_categories_menu_sql_where', array(&$this, 'buildMenuFromCat'), 75);
[3681]55  }
56
[8962]57
58  public function blockmanagerApply($menu_ref_arr)
[3681]59  {
[8962]60    $menu=&$menu_ref_arr[0];
[3681]61
[8962]62    $this->addBlockRandomPicture($menu);
63    $this->addBlockLinks($menu);
64    $this->addBlockPersonnal($menu);
65    $this->addBlockAlbum($menu);
66    $this->manageBlocksContent($menu);
67    $this->manageBlocks($menu);
[3681]68  }
69
[8962]70
71  /**
72   * Add a new random picture block
73   */
74  private function addBlockRandomPicture(&$menu)
[3681]75  {
[8962]76    global $user;
[3681]77
[8962]78    if((
79        ($block=$menu->get_block('mbAMM_randompict'))!=null) and
80        ($user['nb_total_images']>0) and
[11036]81        isset($this->config['amm_randompicture_title'][$user['language']]) and
82        $this->displayRandomImageBlock
[8962]83      )
84    {
[10247]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'));
[3681]87
[8962]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'])
[3690]97      );
[8962]98
99      if(count($this->randomPictProp['pictures'])==0) $this->displayRandomImageBlock=false;
[3681]100    }
[4382]101    else
102    {
103      $this->displayRandomImageBlock=false;
104    }
[8962]105  }
[3681]106
[8962]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      )
[3681]120    {
[8962]121      $urls=$this->getLinks(true);
122
123      if(count($urls)>0)
[3681]124      {
[8962]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
[5545]147        if($this->config['amm_links_show_icons']=='y')
[3681]148        {
[8962]149          foreach($urls as $key => $url)
[3681]150          {
[8962]151            $urls[$key]['icon']=get_root_url().'plugins/'.AMM_DIR."/links_pictures/".$url['icon'];
[3681]152          }
153        }
154
[8962]155        $block->set_title(base64_decode($this->config['amm_links_title'][$user['language']]));
156        $block->template=dirname(__FILE__).'/menu_templates/menubar_links.tpl';
[3681]157
158        $block->data = array(
159          'LINKS' => $urls,
[5545]160          'icons' => $this->config['amm_links_show_icons']
[3681]161        );
162      }
163    }
[8962]164  }
[3681]165
166
[8962]167  /**
168   * Add personnal blocks
169   */
170  private function addBlockPersonnal(&$menu)
171  {
172    $sections=$this->getPersonalisedBlocks(true);
173
[3681]174    if(count($sections))
175    {
[8962]176      $idDone=array();
[3681]177      foreach($sections as $key => $val)
178      {
[8962]179        if(!isset($idDone[$val['id']]))
[3681]180        {
[8962]181          if(($block=$menu->get_block('mbAMM_personalised'.$val['id']))!= null)
[3681]182          {
[8962]183            $block->set_title($val['title']);
[3681]184            $block->template = dirname(__FILE__).'/menu_templates/menubar_personalised.tpl';
185            $block->data = stripslashes($val['content']);
186          }
[8962]187          $idDone[$val['id']]="";
[3681]188        }
189      }
190    }
[8962]191  }
[3681]192
[4382]193
[8962]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            );
[12665]226/*
227            $nbImages=0;
228            foreach($block->data['album'] as $val)
229            {
230              $nbImages+=$val['nb_images'];
231            }
232            $block->data['nbPictures']="*** $nbImages";
233*/
[8962]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
[4382]251    $blocks=Array();
252
[4395]253    if($menu->is_hidden('mbMenu'))
254    {
[8962]255      // if block is hidden, make a fake to manage AMM submenu features
[4395]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    {
[8962]267      // if block is hidden, make a fake to manage AMM submenu features
[4395]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
[4382]277    $menuItems=array_merge($blocks['menu']->data, $blocks['special']->data);
[8962]278    $this->sortCoreBlocksItems();
[4382]279
280    $blocks['menu']->data=Array();
281    $blocks['special']->data=Array();
[8962]282    $userGroups=$this->getUserGroups($user['id']);
[4382]283
[8962]284    foreach($this->config['amm_blocks_items'] as $key => $val)
[3681]285    {
[4382]286      if(isset($menuItems[$key]))
[3681]287      {
[4389]288        $access=explode("/",$val['visibility']);
[8962]289        $this->users->setAlloweds(str_replace(",", "/", $access[0]), false);
290        $this->groups->setAlloweds(str_replace(",", "/", $access[1]), false);
[4389]291
[8962]292        /*
293         * test if user status is allowed to access the menu item
[4389]294         * if access is managed by group, the user have to be associated with an allowed group to access the menu item
[8962]295         */
296        if($this->users->isAllowed($user['status']))
[4389]297        {
[8962]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];
[4389]304        }
[3681]305      }
306    }
[4382]307    if(count($blocks['menu']->data)==0) $menu->hide_block('mbMenu');
308    if(count($blocks['special']->data)==0) $menu->hide_block('mbSpecials');
309  }
[3681]310
[4389]311
[8962]312  /**
313   * return groups for a user
314   *
315   * @param String $userId
316   * @return Array
317   */
318  private function getUserGroups($userId)
[4389]319  {
[8962]320    global $user;
321
[4389]322    $returned=array();
[8962]323
324    $sql="SELECT group_id FROM ".USER_GROUP_TABLE." WHERE user_id='".$user['id']."';";
[4389]325    $result=pwg_query($sql);
326    if($result)
327    {
[5427]328      while($row=pwg_db_fetch_assoc($result))
[4389]329      {
[8962]330        $returned[]=$row['group_id'];
[4389]331      }
332    }
333    return($returned);
334  }
335
[8962]336
337  /**
338   * reordering blocks and manage access right
339   *
340   */
341  private function manageBlocks($menu)
[3681]342  {
[8962]343    $this->registeredBlocks=$this->getRegisteredBlocks(true);
[3681]344
[8962]345    foreach($menu->get_registered_blocks() as $key => $block)
[3681]346    {
[8962]347      if(!isset($this->registeredBlocks[$block->get_id()]))
[3681]348      {
[8962]349        $menu->hide_block($block->get_id());
[3681]350      }
351    }
[8962]352
[3681]353  }
354
355
[8962]356  /**
357   * sort menu blocks according to AMM rules (overriding piwigo's sort rules)
358   */
359  public function blockmanagerSortBlocks($blocks)
[3681]360  {
[8962]361    $this->registeredBlocks=$this->getRegisteredBlocks(true);
[3683]362
[11036]363    if(!isset($this->registeredBlocks['mbAMM_randompict'])) $this->displayRandomImageBlock=false;
364
[8962]365    foreach($blocks[0]->get_registered_blocks() as $key => $block)
366    {
367      if(isset($this->registeredBlocks[$block->get_id()]))
[3683]368      {
[8962]369        $blocks[0]->set_block_position($block->get_id(), $this->registeredBlocks[$block->get_id()]['order']);
[3683]370      }
[8962]371    }
372  }
[3681]373
374
375
[8962]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))
[3681]440      {
[8962]441        $row['section']='category';
442        $row['category']=array(
443          'id' => $row['catid'],
444          'name' => $row['name'],
445          'permalink' => $row['permalink']
[3681]446        );
447
[8962]448        $row['link']=make_picture_url($row);
449        $row['thumb']=get_thumbnail_url($row);
450
451        $returned[]=$row;
[3681]452      }
[8962]453    }
[3681]454
[8962]455    return($returned);
[3681]456  }
457
[4363]458
[8962]459
460
[4363]461  public function applyJS()
462  {
[4499]463    global $user, $template, $page;
[4363]464
[5421]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
[8962]477
[4499]478    if($this->displayRandomImageBlock && $page['body_id'] == 'theCategoryPage')
[4363]479    {
480      $local_tpl = new Template(AMM_PATH."admin/", "");
[5545]481      $local_tpl->set_filename('body_page', dirname($this->getFileLocation()).'/menu_templates/menubar_randompic.js.tpl');
[4363]482
[8962]483      $local_tpl->assign('data', $this->randomPictProp);
[4363]484
[8962]485      $template->append('head_elements', $local_tpl->parse('body_page', true));
486    }
487  }
[4363]488
[8962]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." ";
[4363]507    }
508
[8962]509    return($where);
[4363]510  }
511
[3681]512} // AMM_PIP class
513
514
515?>
Note: See TracBrowser for help on using the repository browser.