source: extensions/AMenuManager/amm_root.class.inc.php @ 27153

Last change on this file since 27153 was 21510, checked in by plg, 11 years ago

fix bug on single quotes in AMM custom menus

  • Property svn:executable set to *
File size: 20.0 KB
Line 
1<?php
2/* -----------------------------------------------------------------------------
3  Plugin     : Advanced Menu Manager
4  Author     : Grum
5    email    : grum@grum.fr
6    website  : http://photos.grum.fr
7    PWG user : http://forum.piwigo.org/profile.php?id=3706
8
9    << May the Little SpaceFrog be with you ! >>
10  ------------------------------------------------------------------------------
11  See main.inc.php for release information
12
13  AMM_root : root class for plugin
14
15  --------------------------------------------------------------------------- */
16
17if (!defined('PHPWG_ROOT_PATH')) { die('Hacking attempt!'); }
18
19include_once(PHPWG_ROOT_PATH.'include/block.class.php');
20include_once(PHPWG_PLUGINS_PATH.'GrumPluginClasses/classes/CommonPlugin.class.inc.php');
21include_once(PHPWG_PLUGINS_PATH.'GrumPluginClasses/classes/GPCUsersGroups.class.inc.php');
22
23
24class AMM_root extends CommonPlugin
25{
26  protected $defaultMenus = array(
27    /* about visibility & accessibility system :
28     *  - by default, everything is visible (users & groups)
29     *  - items not visibles are listed (in release < 3.3.4, this rule wa applied to groups only)
30     *
31     * on the user interface, checked items are visibles => not checked items are stored
32     */
33    'favorites' => array('container' => 'special', 'visibility' => '/', 'order' => 0, 'translation' => 'My favorites'),
34    'most_visited' => array('container' => 'special', 'visibility' => '/', 'order' => 1, 'translation' => 'Most visited'),
35    'best_rated' => array('container' => 'special', 'visibility' => '/', 'order' => 2, 'translation' => 'Best rated'),
36    'random' => array('container' => 'special', 'visibility' => '/', 'order' => 3, 'translation' => 'Random pictures'),
37    'recent_pics' => array('container' => 'special', 'visibility' => '/', 'order' => 4, 'translation' => 'Recent pictures'),
38    'recent_cats' => array('container' => 'special', 'visibility' => '/', 'order' => 5, 'translation' => 'Recent categories'),
39    'calendar' => array('container' => 'special', 'visibility' => '/', 'order' => 6, 'translation' => 'Calendar'),
40    'qsearch' => array('container' => 'menu', 'visibility' => '/', 'order' => 0, 'translation' => 'Quick search'),
41    'tags' => array('container' => 'menu', 'visibility' => '/', 'order' => 1, 'translation' => 'Tags'),
42    'search' => array('container' => 'menu', 'visibility' => '/', 'order' => 2, 'translation' => 'Search'),
43    'comments' => array('container' => 'menu', 'visibility' => '/', 'order' => 3, 'translation' => 'Comments'),
44    'about' => array('container' => 'menu', 'visibility' => '/', 'order' => 4, 'translation' => 'About'),
45    'rss' => array('container' => 'menu', 'visibility' => '/', 'order' => 5, 'translation' => 'Notification')
46  );
47  protected $urlsModes=array(0 => 'new_window', 1 => 'current_window');
48
49
50
51  public function __construct($prefixeTable, $filelocation)
52  {
53    $this->setPluginName("Advanced Menu Manager");
54    $this->setPluginNameFiles("amm");
55    parent::__construct($prefixeTable, $filelocation);
56
57    $list=array('urls', 'personalised', 'personalised_langs', 'blocks');
58    $this->setTablesList($list);
59  }
60
61  public function __destruct()
62  {
63    unset($this->defaultMenus);
64    parent::__destruct();
65  }
66
67  /*
68   * ---------------------------------------------------------------------------
69   * common AIP & PIP functions
70   * ---------------------------------------------------------------------------
71   */
72
73  /**
74   * this function initialize config var with default values
75   */
76  public function initConfig()
77  {
78    $this->config=array(
79      'amm_links_show_icons' => 'y',
80      'amm_links_title' => array(),
81      'amm_randompicture_preload' => 25,     //number preloaded random pictures
82      'amm_randompicture_showname' => 'n',     //n:no, o:over, u:under
83      'amm_randompicture_showcomment' => 'n',   //n:no, o:over, u:under
84      'amm_randompicture_periodicchange' => 0,   //0: no periodic change ; periodic change in milliseconds
85      'amm_randompicture_height' => 0,           //0: automatic, otherwise it's the fixed height in pixels
86      'amm_randompicture_title' => array(),
87      'amm_randompicture_selectMode' => 'a',     // a:all, f:webmaster's favorites, c:categories
88      'amm_randompicture_selectCat' => array(),  // categories id list
89      'amm_blocks_items' => $this->defaultMenus,
90      'amm_albums_to_menu' => array(),
91      'amm_old_blk_menubar' => '',                // keep a copy of piwigo's menubar config
92      'newInstall' => 'n'
93    );
94
95    $languages=get_languages();
96    foreach($languages as $key => $val)
97    {
98      if($key=='fr_FR')
99      {
100        $this->config['amm_links_title'][$key]=base64_encode('Liens');
101        $this->config['amm_randompicture_title'][$key]=base64_encode('Une image au hasard');
102      }
103      else
104      {
105        $this->config['amm_links_title'][$key]=base64_encode('Links');
106        $this->config['amm_randompicture_title'][$key]=base64_encode('A random picture');
107      }
108    }
109  }
110
111  public function registerBlocks( $menu_ref_arr )
112  {
113    $menu = & $menu_ref_arr[0];
114    if ($menu->get_id() != 'menubar') return;
115
116    $menu->register_block( new RegisteredBlock( 'mbAMM_randompict', 'Random pictures', 'AMM'));
117    $menu->register_block( new RegisteredBlock( 'mbAMM_links', 'Links', 'AMM'));
118
119    $blocks=$this->getPersonalisedBlocks();
120    if(count($blocks))
121    {
122      $idDone=array();
123      foreach($blocks as $key => $val)
124      {
125        if(!isset($idDone[$val['id']]))
126        {
127          $menu->register_block( new RegisteredBlock( 'mbAMM_personalised'.$val['id'], $val['title'], 'AMM'));
128          $idDone[$val['id']]="";
129        }
130      }
131    }
132
133    $this->loadConfig();
134
135    if(count($this->config['amm_albums_to_menu'])>0)
136    {
137      $sql="SELECT id, name
138            FROM ".CATEGORIES_TABLE."
139            WHERE id IN(".implode(',', $this->config['amm_albums_to_menu']).");";
140
141      $result=pwg_query($sql);
142      if($result)
143      {
144        while($row=pwg_db_fetch_assoc($result))
145        {
146          $row['name']=trigger_event('render_category_name', $row['name'], 'amm_album_to_menu');
147
148          $menu->register_block( new RegisteredBlock( 'mbAMM_album'.$row['id'], $row['name'].' ('.l10n('g002_album2menu').') ', 'AMM'));
149        }
150      }
151    }
152  }
153
154
155  /*
156   *  ---------------------------------------------------------------------------
157   *
158   * Links functions
159   *
160   * ---------------------------------------------------------------------------
161   */
162
163  /**
164   * return an array of links (each url is an array)
165   *
166   * @param Bool onlyVisible : if true, only visible links are returned
167   * @return Array
168   */
169  protected function getLinks($onlyVisible=false)
170  {
171    $returned=array();
172    $sql="SELECT id, label, url, mode, icon, position, visible, accessUsers, accessGroups
173          FROM ".$this->tables['urls'];
174    if($onlyVisible)
175    {
176      $sql.=" WHERE visible = 'y' ";
177    }
178    $sql.=" ORDER BY position ASC, id ASC";
179    $result=pwg_query($sql);
180    if($result)
181    {
182      while($row=pwg_db_fetch_assoc($result))
183      {
184        $returned[]=$row;
185      }
186    }
187    return($returned);
188  }
189
190  /**
191   * return values for a given link
192   *
193   * @param String $id : link id
194   * @return Array
195   */
196  protected function getLink($id)
197  {
198    $returned=array();
199    $sql="SELECT id, label, url, mode, icon, position, visible, accessUsers, accessGroups
200          FROM ".$this->tables['urls']."
201          WHERE id = '$id';";
202    $result=pwg_query($sql);
203    if($result)
204    {
205      while($row=pwg_db_fetch_assoc($result))
206      {
207        $returned=$row;
208      }
209    }
210    return($returned);
211  }
212
213  /**
214   * set values for a link
215   * if link id is empty : create a new link
216   * if not, update link
217   *
218   * @param String $id : link id
219   * @return Integer : -1 if fails
220   *                   otherwise link id
221   */
222  protected function setLink($id, $label, $url, $mode, $icon, $visible, $accessUsers, $accessGroups)
223  {
224    if($id=='')
225    {
226      $sql="INSERT INTO ".$this->tables['urls']." VALUES
227            ('',
228             '".$label."',
229             '".$url."',
230             '$mode',
231             '$icon',
232             0,
233             '$visible',
234             '$accessUsers',
235             '$accessGroups'
236            );";
237    }
238    else
239    {
240      $sql="UPDATE ".$this->tables['urls']."
241            SET label='".$label."',
242                url='".$url."',
243                mode='$mode',
244                icon='$icon',
245                visible='$visible',
246                accessUsers='".$accessUsers."',
247                accessGroups='".$accessGroups."'
248            WHERE id='$id';";
249    }
250    $result=pwg_query($sql);
251    if($result)
252    {
253      if($id=='')
254      {
255        return(pwg_db_insert_id());
256      }
257      else
258      {
259        return($id);
260      }
261    }
262    return(-1);
263  }
264
265  /**
266   * delete a given link
267   *
268   * @param String $id : link id
269   * @return Bool : true if deleted, otherwise false
270   */
271  protected function deleteLink($id)
272  {
273    $sql="DELETE FROM ".$this->tables['urls']."
274          WHERE id = '$id';";
275    $result=pwg_query($sql);
276    if($result) return(true);
277    return(false);
278  }
279
280
281
282  /**
283   * return number of links
284   *
285   * @param Bool onlyVisible : if true, only visible links are counted
286   * @return Array
287   */
288  protected function getLinksCount($onlyVisible=false)
289  {
290    $returned=0;
291    $sql="SELECT count(id) FROM ".$this->tables['urls'];
292    if($onlyVisible)
293    {
294      $sql.=" WHERE visible = 'y' ";
295    }
296    $result=pwg_query($sql);
297    if($result)
298    {
299      $tmp=pwg_db_fetch_row($result);
300      $returned=$tmp[0];
301    }
302    return($returned);
303  }
304
305  /**
306   * set order from given links
307   *
308   * @param Array $links : array
309   *                        each item is an array ('id' => '', 'order' =>'')
310   * @return Bool :
311   */
312  protected function setLinksOrder($links)
313  {
314    $returned=true;
315
316    foreach($links as $link)
317    {
318      $sql="UPDATE ".$this->tables['urls']."
319            SET position='".$link['order']."'
320            WHERE id='".$link['id']."';";
321      $result=pwg_query($sql);
322      if(!$result) $returned=false;
323    }
324    return($returned);
325  }
326
327
328  /*
329   *  ---------------------------------------------------------------------------
330   *
331   * Personalised Blocks functions
332   *
333   * ---------------------------------------------------------------------------
334   */
335
336
337  /**
338   * return an array of personalised blocks (each block is an array)
339   *
340   * @param Bool onlyVisible : if true, only visibles blocks are returned
341   * @return Array
342   */
343  protected function getPersonalisedBlocks($onlyVisible=false, $lang='', $emptyContent=false)
344  {
345    global $user;
346
347    if($lang=="") $lang=$user['language'];
348
349    $returned=array();
350    $sql="SELECT pt.id, pt.visible, pt.nfo, ptl.lang, ptl.title, ptl.content
351          FROM ".$this->tables['personalised']." pt
352            LEFT JOIN ".$this->tables['personalised_langs']." ptl
353            ON pt.id=ptl.id
354          WHERE (ptl.lang = '*' OR ptl.lang = '".pwg_db_real_escape_string($lang)."') ";
355
356    if($onlyVisible) $sql.=" AND pt.visible = 'y' ";
357    if($emptyContent==false) $sql.=" AND ptl.content != '' ";
358
359    $sql.=" ORDER BY pt.id, ptl.lang ASC ";
360
361    $result=pwg_query($sql);
362    if($result)
363    {
364      while($row=pwg_db_fetch_assoc($result))
365      {
366        $row['content'] = trigger_event('get_extended_desc', $row['content']);
367        $returned[]=$row;
368      }
369    }
370    return($returned);
371  }
372
373  /**
374   * return values for a given personalised block
375   *
376   * @param String $id : link id
377   * @return Array
378   */
379  protected function getPersonalisedBlock($id)
380  {
381    $returned=array(
382      'visible' => false,
383      'nfo' => '',
384      'langs' => array()
385    );
386
387    $sql="SELECT visible, nfo
388          FROM ".$this->tables['personalised']."
389          WHERE id='$id';";
390
391    $result=pwg_query($sql);
392    if($result)
393    {
394      while($row=pwg_db_fetch_assoc($result))
395      {
396        $returned['visible']=$row['visible'];
397        $returned['nfo']=$row['nfo'];
398      }
399
400      $sql="SELECT lang, title, content
401            FROM ".$this->tables['personalised_langs']."
402            WHERE id='$id'
403            ORDER BY lang ASC;";
404
405      $result=pwg_query($sql);
406      if($result)
407      {
408        while($row=pwg_db_fetch_assoc($result))
409        {
410          $returned['langs'][$row['lang']]=$row;
411        }
412      }
413    }
414    return($returned);
415  }
416
417  /**
418   * set values for a personalised block
419   * if block id is empty : create a new block
420   * if not, update block
421   *
422   * @param String $id : block id
423   * @return Integer : -1 if fails
424   *                   otherwise block id
425   */
426  protected function setPersonalisedBlock($id, $visible, $nfo, $langs)
427  {
428    $ok=false;
429
430    if($id=='')
431    {
432      $sql="INSERT INTO ".$this->tables['personalised']." VALUES
433            ('',
434             '$visible',
435             '".$nfo."'
436            );";
437      $result=pwg_query($sql);
438      if($result) $ok=true;
439      $id=pwg_db_insert_id();
440    }
441    else
442    {
443      $sql="UPDATE ".$this->tables['personalised']."
444            SET visible='$visible',
445                nfo='".pwg_db_real_escape_string(stripslashes($nfo))."'
446            WHERE id='$id';";
447      $result=pwg_query($sql);
448      if($result)
449      {
450        $sql="DELETE FROM ".$this->tables['personalised_langs']."
451              WHERE id='$id';";
452        $result=pwg_query($sql);
453
454        if($result) $ok=true;
455      }
456    }
457
458    if($ok)
459    {
460      $values=array();
461      foreach($langs as $key => $lang)
462      {
463        $values[]="('$id',
464                    '".$lang['lang']."',
465                    '".pwg_db_real_escape_string(stripslashes($lang['title']))."',
466                    '".pwg_db_real_escape_string(stripslashes($lang['content']))."')";
467      }
468      $sql="INSERT INTO ".$this->tables['personalised_langs']." VALUES ".implode(',', $values);
469      $result=pwg_query($sql);
470
471      if($result) $ok=true;
472    }
473
474    if($ok) return($id);
475    return(-1);
476  }
477
478  /**
479   * delete a given personalised block
480   *
481   * @param String $id : block id
482   * @return Bool : true if deleted, otherwise false
483   */
484  protected function deletePersonalisedBlock($id)
485  {
486    $sql="DELETE FROM ".$this->tables['personalised']."
487          WHERE id = '$id';";
488    $result=pwg_query($sql);
489    if($result)
490    {
491      $sql="DELETE FROM ".$this->tables['personalised_langs']."
492            WHERE id = '$id';";
493      $result=pwg_query($sql);
494
495      if($result) return(true);
496    }
497
498    return(false);
499  }
500
501
502
503  /**
504   * return an array of all registered blocks
505   * each array item is an array :
506   *  String  'id'      => ''
507   *  Integer 'order'   => 0
508   *  Array   'users'   => array()
509   *  Array   'groups'  => array()
510   *  String  'name'    => ''
511   *  String  'owner'   => ''
512   *
513   * @param Bool $userFiltered : true if returned blocks are filtered to current
514   *                             user
515   * @return Array
516   */
517  protected function getRegisteredBlocks($userFiltered=false)
518  {
519    global $conf, $user;
520
521    $returned=array();
522    $order=0;
523    $users=new GPCUsers();
524    $groups=new GPCGroups();
525
526    $menu = new BlockManager('menubar');
527    $menu->load_registered_blocks();
528    $registeredBlocks = $menu->get_registered_blocks();
529
530    $nbExistingGroups=0;
531    $sql="SELECT COUNT(id) AS nbGroup
532          FROM ".GROUPS_TABLE.";";
533    $result=pwg_query($sql);
534    if($result)
535    {
536      while($row=pwg_db_fetch_assoc($result))
537      {
538        $nbExistingGroups=$row['nbGroup'];
539      }
540    }
541
542
543    $userGroups=array();
544    $sql="SELECT group_id
545          FROM ".USER_GROUP_TABLE."
546          WHERE user_id = '".$user['id']."';";
547    $result=pwg_query($sql);
548    if($result)
549    {
550      while($row=pwg_db_fetch_assoc($result))
551      {
552        $userGroups[$row['group_id']]='';
553      }
554    }
555
556    $sql="SELECT id, `order`, users, groups
557          FROM ".$this->tables['blocks']."
558          ORDER BY `order`;";
559    $result=pwg_query($sql);
560    if($result)
561    {
562      while($row=pwg_db_fetch_assoc($result))
563      {
564        $row['users']=(trim($row['users'])=='')?array():explode(',', $row['users']);
565        $row['groups']=(trim($row['groups'])=='')?array():explode(',', $row['groups']);
566
567        if(isset($registeredBlocks[$row['id']]))
568        {
569          $ok=true;
570          if($userFiltered)
571          {
572            // filter access enabled
573
574            $users->setAlloweds($row['users'], false);
575            if($users->isAllowed($user['status']))
576            {
577              // user is authorized, check group
578              if(count($userGroups))
579              {
580                // users is attached to one group or more, check access for each group
581                // at least, one group must have right access
582                $nbOk=count($userGroups);
583
584                $groups->setAlloweds($row['groups'], false);
585                foreach($row['groups'] as $val)
586                {
587                  if(isset($userGroups[$val]) and !$groups->isAllowed($val)) $nbOk--;
588                }
589
590                // no group is authorized to access the menu
591                if($nbOk==0) $ok=false;
592              }
593              elseif($nbExistingGroups>0 and count($row['groups'])>0)
594              {
595                // if user is not attached to any group and if at least there 1
596                // existing group, no authorization to access to the menu
597                $ok=false;
598              }
599            }
600            else
601            {
602              // user not authorized
603              $ok=false;
604            }
605          }
606
607          if($ok)
608          {
609            $returned[$row['id']]=array(
610              'id'    => $row['id'],
611              'order' => $row['order'],
612              'users' => $row['users'],
613              'groups'=> $row['groups'],
614              'name'  => $registeredBlocks[$row['id']]->get_name(),
615              'owner' => $registeredBlocks[$row['id']]->get_owner()
616            );
617            $order=$row['order'];
618          }
619          unset($registeredBlocks[$row['id']]);
620        }
621      }
622    }
623
624    /*
625     * add new blocks, unknown from plugin
626     * by default, users & groups are visibles
627     */
628    foreach($registeredBlocks as $key=>$val)
629    {
630      $order+=10;
631
632      $returned[$key]=array(
633        'id'    => $key,
634        'order' => $order,
635        'users' => array(),
636        'groups'=> array(),
637        'name'  => $val->get_name(),
638        'owner' => $val->get_owner()
639      );
640    }
641
642    return($returned);
643  }
644
645
646  /**
647   * set order for registered blocks
648   *
649   * note : Piwigo's order is maintened
650   *
651   * @param Array $block : array of block ; each items is an array
652   *                        String  'id'    => ''
653   *                        Integer 'order' => ''
654   *                        Array   'users'   => array()
655   *                        Array   'groups'  => array()
656   * @return Bool : true, false is something is wrong
657   */
658  protected function setRegisteredBlocks($blocks)
659  {
660    $returned=true;
661
662    $sql="DELETE FROM ".$this->tables['blocks'];
663    pwg_query($sql);
664
665    foreach($blocks as $block)
666    {
667      $sql="INSERT INTO ".$this->tables['blocks']." VALUES (
668            '".$block['id']."',
669            '".$block['order']."',
670            '".implode(',', $block['users'])."',
671            '".implode(',', $block['groups'])."'
672            );";
673      $result=pwg_query($sql);
674      if(!$result) $returned=false;
675    }
676
677    return($returned);
678  }
679
680
681  static public function checkPluginRelease()
682  {
683    global $template, $prefixeTable, $conf;
684
685    $config=array();
686    GPCCore::loadConfig('amm', $config);
687
688    if($config['installed']!=AMM_VERSION2)
689    {
690      /* the plugin was updated without being deactivated
691       * deactivate + activate the plugin to process the database upgrade
692       */
693      include(AMM_PATH."amm_install.class.inc.php");
694      $amm=new AMM_Install($prefixeTable, dirname(__FILE__));
695      $amm->deactivate();
696      $amm->activate();
697      if(is_object($template)) $template->delete_compiled_templates();
698    }
699  }
700
701
702
703
704
705  protected function sortCoreBlocksItemsCompare($a, $b)
706  {
707    if($a['container']==$b['container'])
708    {
709      if($a['order']==$b['order']) return(0);
710      return(($a['order']<$b['order'])?-1:1);
711    }
712    else return(($a['container']<$b['container'])?-1:1);
713  }
714
715  protected function sortCoreBlocksItems()
716  {
717    uasort($this->config['amm_blocks_items'], array($this, "sortCoreBlocksItemsCompare"));
718  }
719
720} // amm_root  class
721
722
723
724?>
Note: See TracBrowser for help on using the repository browser.