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

Last change on this file since 11419 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
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') );
51    add_event_handler('blockmanager_apply', array(&$this, 'blockmanagerApply') );
[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            );
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
[4382]243    $blocks=Array();
244
[4395]245    if($menu->is_hidden('mbMenu'))
246    {
[8962]247      // if block is hidden, make a fake to manage AMM submenu features
[4395]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    {
[8962]259      // if block is hidden, make a fake to manage AMM submenu features
[4395]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
[4382]269    $menuItems=array_merge($blocks['menu']->data, $blocks['special']->data);
[8962]270    $this->sortCoreBlocksItems();
[4382]271
272    $blocks['menu']->data=Array();
273    $blocks['special']->data=Array();
[8962]274    $userGroups=$this->getUserGroups($user['id']);
[4382]275
[8962]276    foreach($this->config['amm_blocks_items'] as $key => $val)
[3681]277    {
[4382]278      if(isset($menuItems[$key]))
[3681]279      {
[4389]280        $access=explode("/",$val['visibility']);
[8962]281        $this->users->setAlloweds(str_replace(",", "/", $access[0]), false);
282        $this->groups->setAlloweds(str_replace(",", "/", $access[1]), false);
[4389]283
[8962]284        /*
285         * test if user status is allowed to access the menu item
[4389]286         * if access is managed by group, the user have to be associated with an allowed group to access the menu item
[8962]287         */
288        if($this->users->isAllowed($user['status']))
[4389]289        {
[8962]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];
[4389]296        }
[3681]297      }
298    }
[4382]299    if(count($blocks['menu']->data)==0) $menu->hide_block('mbMenu');
300    if(count($blocks['special']->data)==0) $menu->hide_block('mbSpecials');
301  }
[3681]302
[4389]303
[8962]304  /**
305   * return groups for a user
306   *
307   * @param String $userId
308   * @return Array
309   */
310  private function getUserGroups($userId)
[4389]311  {
[8962]312    global $user;
313
[4389]314    $returned=array();
[8962]315
316    $sql="SELECT group_id FROM ".USER_GROUP_TABLE." WHERE user_id='".$user['id']."';";
[4389]317    $result=pwg_query($sql);
318    if($result)
319    {
[5427]320      while($row=pwg_db_fetch_assoc($result))
[4389]321      {
[8962]322        $returned[]=$row['group_id'];
[4389]323      }
324    }
325    return($returned);
326  }
327
[8962]328
329  /**
330   * reordering blocks and manage access right
331   *
332   */
333  private function manageBlocks($menu)
[3681]334  {
[8962]335    $this->registeredBlocks=$this->getRegisteredBlocks(true);
[3681]336
[8962]337    foreach($menu->get_registered_blocks() as $key => $block)
[3681]338    {
[8962]339      if(!isset($this->registeredBlocks[$block->get_id()]))
[3681]340      {
[8962]341        $menu->hide_block($block->get_id());
[3681]342      }
343    }
[8962]344
[3681]345  }
346
347
[8962]348  /**
349   * sort menu blocks according to AMM rules (overriding piwigo's sort rules)
350   */
351  public function blockmanagerSortBlocks($blocks)
[3681]352  {
[8962]353    $this->registeredBlocks=$this->getRegisteredBlocks(true);
[3683]354
[11036]355    if(!isset($this->registeredBlocks['mbAMM_randompict'])) $this->displayRandomImageBlock=false;
356
[8962]357    foreach($blocks[0]->get_registered_blocks() as $key => $block)
358    {
359      if(isset($this->registeredBlocks[$block->get_id()]))
[3683]360      {
[8962]361        $blocks[0]->set_block_position($block->get_id(), $this->registeredBlocks[$block->get_id()]['order']);
[3683]362      }
[8962]363    }
364  }
[3681]365
366
367
[8962]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))
[3681]432      {
[8962]433        $row['section']='category';
434        $row['category']=array(
435          'id' => $row['catid'],
436          'name' => $row['name'],
437          'permalink' => $row['permalink']
[3681]438        );
439
[8962]440        $row['link']=make_picture_url($row);
441        $row['thumb']=get_thumbnail_url($row);
442
443        $returned[]=$row;
[3681]444      }
[8962]445    }
[3681]446
[8962]447    return($returned);
[3681]448  }
449
[4363]450
[8962]451
452
[4363]453  public function applyJS()
454  {
[4499]455    global $user, $template, $page;
[4363]456
[5421]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
[8962]469
[4499]470    if($this->displayRandomImageBlock && $page['body_id'] == 'theCategoryPage')
[4363]471    {
472      $local_tpl = new Template(AMM_PATH."admin/", "");
[5545]473      $local_tpl->set_filename('body_page', dirname($this->getFileLocation()).'/menu_templates/menubar_randompic.js.tpl');
[4363]474
[8962]475      $local_tpl->assign('data', $this->randomPictProp);
[4363]476
[8962]477      $template->append('head_elements', $local_tpl->parse('body_page', true));
478    }
479  }
[4363]480
[8962]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." ";
[4363]499    }
500
[8962]501    return($where);
[4363]502  }
503
[3681]504} // AMM_PIP class
505
506
507?>
Note: See TracBrowser for help on using the repository browser.