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

Last change on this file since 16414 was 16006, checked in by grum, 12 years ago

feature:2642- compatibility with Piwigo 2.4

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