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

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

fix bug:2311, bug:2312 (random pict bug)

  • Property svn:executable set to *
File size: 13.7 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']]) 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        }
228      }
229      $this->currentBuiltMenu=-1;
230    }
231  }
232
233  /**
234   * manage items from special & menu blocks
235   *  - reordering items
236   *  - grouping items
237   *  - managing rights to access
238   */
239  private function manageBlocksContent(&$menu)
240  {
241    global $user;
242
243    $blocks=Array();
244
245    if($menu->is_hidden('mbMenu'))
246    {
247      // if block is hidden, make a fake to manage AMM submenu features
248      // the fake block isn't displayed
249      $blocks['menu']=new DisplayBlock('amm_mbMenu');
250      $blocks['menu']->data=Array();
251    }
252    else
253    {
254      $blocks['menu']=$menu->get_block('mbMenu');
255    }
256
257    if($menu->is_hidden('mbSpecials'))
258    {
259      // if block is hidden, make a fake to manage AMM submenu features
260      // the fake block isn't displayed
261      $blocks['special']=new DisplayBlock('amm_mbSpecial');
262      $blocks['special']->data=Array();
263    }
264    else
265    {
266      $blocks['special']=$menu->get_block('mbSpecials');
267    }
268
269    $menuItems=array_merge($blocks['menu']->data, $blocks['special']->data);
270    $this->sortCoreBlocksItems();
271
272    $blocks['menu']->data=Array();
273    $blocks['special']->data=Array();
274    $userGroups=$this->getUserGroups($user['id']);
275
276    foreach($this->config['amm_blocks_items'] as $key => $val)
277    {
278      if(isset($menuItems[$key]))
279      {
280        $access=explode("/",$val['visibility']);
281        $this->users->setAlloweds(str_replace(",", "/", $access[0]), false);
282        $this->groups->setAlloweds(str_replace(",", "/", $access[1]), false);
283
284        /*
285         * test if user status is allowed to access the menu item
286         * if access is managed by group, the user have to be associated with an allowed group to access the menu item
287         */
288        if($this->users->isAllowed($user['status']))
289        {
290          $ok=true;
291          foreach($userGroups as $group)
292          {
293            if(!$this->groups->isAllowed($group)) $ok=false;
294          }
295          if($ok) $blocks[$val['container']]->data[$key]=$menuItems[$key];
296        }
297      }
298    }
299    if(count($blocks['menu']->data)==0) $menu->hide_block('mbMenu');
300    if(count($blocks['special']->data)==0) $menu->hide_block('mbSpecials');
301  }
302
303
304  /**
305   * return groups for a user
306   *
307   * @param String $userId
308   * @return Array
309   */
310  private function getUserGroups($userId)
311  {
312    global $user;
313
314    $returned=array();
315
316    $sql="SELECT group_id FROM ".USER_GROUP_TABLE." WHERE user_id='".$user['id']."';";
317    $result=pwg_query($sql);
318    if($result)
319    {
320      while($row=pwg_db_fetch_assoc($result))
321      {
322        $returned[]=$row['group_id'];
323      }
324    }
325    return($returned);
326  }
327
328
329  /**
330   * reordering blocks and manage access right
331   *
332   */
333  private function manageBlocks($menu)
334  {
335    $this->registeredBlocks=$this->getRegisteredBlocks(true);
336
337    foreach($menu->get_registered_blocks() as $key => $block)
338    {
339      if(!isset($this->registeredBlocks[$block->get_id()]))
340      {
341        $menu->hide_block($block->get_id());
342      }
343    }
344
345  }
346
347
348  /**
349   * sort menu blocks according to AMM rules (overriding piwigo's sort rules)
350   */
351  public function blockmanagerSortBlocks($blocks)
352  {
353    $this->registeredBlocks=$this->getRegisteredBlocks(true);
354
355    if(!isset($this->registeredBlocks['mbAMM_randompict'])) $this->displayRandomImageBlock=false;
356
357    foreach($blocks[0]->get_registered_blocks() as $key => $block)
358    {
359      if(isset($this->registeredBlocks[$block->get_id()]))
360      {
361        $blocks[0]->set_block_position($block->get_id(), $this->registeredBlocks[$block->get_id()]['order']);
362      }
363    }
364  }
365
366
367
368
369
370
371
372  /**
373   * return a list of thumbnails
374   * each array items is an array
375   *  'imageId'   => (integer)
376   *  'imageFile' => (String)
377   *  'comment'   => (String)
378   *  'path'      => (String)
379   *  'tn_ext'    => (String)
380   *  'catId'     => (String)
381   *  'name'      => (String)
382   *  'permalink' => (String)
383   *  'imageName' => (String)
384   *
385   * @param Integer $number : number of returned images
386   * @return Array
387   */
388  private function getRandomPictures($num=25)
389  {
390    global $user;
391
392    $returned=array();
393
394    $sql=array();
395
396    $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 ";
397    $sql['from']="FROM ".CATEGORIES_TABLE." c, ".IMAGES_TABLE." i, ".IMAGE_CATEGORY_TABLE." ic ";
398    $sql['where']="WHERE c.id = ic.category_id
399            AND ic.image_id = i.id
400            AND i.level <= ".$user['level']." ";
401
402    if($user['forbidden_categories']!="")
403    {
404      $sql['where'].=" AND c.id NOT IN (".$user['forbidden_categories'].") ";
405    }
406
407    switch($this->config['amm_randompicture_selectMode'])
408    {
409      case 'f':
410        $sql['from'].=", ".USER_INFOS_TABLE." ui
411          LEFT JOIN ".FAVORITES_TABLE." f ON ui.user_id=f.user_id ";
412        $sql['where'].=" AND ui.status='webmaster'
413                         AND f.image_id = i.id ";
414        break;
415      case 'c':
416        $sql['where'].="AND (";
417        foreach($this->config['amm_randompicture_selectCat'] as $key => $val)
418        {
419          $sql['where'].=($key==0?'':' OR ')." FIND_IN_SET($val, c.uppercats) ";
420        }
421        $sql['where'].=") ";
422        break;
423    }
424
425    $sql=$sql['select'].$sql['from'].$sql['where']." ORDER BY rndvalue LIMIT 0,$num";
426
427
428    $result = pwg_query($sql);
429    if($result)
430    {
431      while($row=pwg_db_fetch_assoc($result))
432      {
433        $row['section']='category';
434        $row['category']=array(
435          'id' => $row['catid'],
436          'name' => $row['name'],
437          'permalink' => $row['permalink']
438        );
439
440        $row['link']=make_picture_url($row);
441        $row['thumb']=get_thumbnail_url($row);
442
443        $returned[]=$row;
444      }
445    }
446
447    return($returned);
448  }
449
450
451
452
453  public function applyJS()
454  {
455    global $user, $template, $page;
456
457    if(!array_key_exists('body_id', $page))
458    {
459      /*
460       * it seems the error message reported on mantis:1476 is displayed because
461       * the 'body_id' doesn't exist in the $page
462       *
463       * not abble to reproduce the error, but initializing the key to an empty
464       * value if it doesn't exist may be a sufficient solution
465       */
466      $page['body_id']="";
467    }
468
469
470    if($this->displayRandomImageBlock && $page['body_id'] == 'theCategoryPage')
471    {
472      $local_tpl = new Template(AMM_PATH."admin/", "");
473      $local_tpl->set_filename('body_page', dirname($this->getFileLocation()).'/menu_templates/menubar_randompic.js.tpl');
474
475      $local_tpl->assign('data', $this->randomPictProp);
476
477      $template->append('head_elements', $local_tpl->parse('body_page', true));
478    }
479  }
480
481
482
483  public function buildMenuFromCat($where)
484  {
485    global $user;
486
487    if($this->currentBuiltMenu>-1)
488    {
489      if($user['expand'])
490      {
491        $where=preg_replace('/id_uppercat\s+is\s+NULL/i', 'id_uppercat is NOT NULL', $where);
492      }
493      else
494      {
495        $where=preg_replace('/id_uppercat\s+is\s+NULL/i', 'id_uppercat is NULL OR id_uppercat IN ('.$this->currentBuiltMenu.')', $where);
496      }
497
498      $where.=" AND FIND_IN_SET(".$this->currentBuiltMenu.", uppercats) AND cat_id!=".$this->currentBuiltMenu." ";
499    }
500
501    return($where);
502  }
503
504} // AMM_PIP class
505
506
507?>
Note: See TracBrowser for help on using the repository browser.