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

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

bug:2371

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