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

Last change on this file since 10247 was 10247, checked in by grum, 13 years ago

bug:2144
Compatibility with Piwigo 2.2

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