source: extensions/MenuRandomPhoto/main.inc.php @ 31852

Last change on this file since 31852 was 31852, checked in by romanf, 7 years ago

New feature: Option to choose which categories to include in Random

  • Property svn:executable set to *
File size: 6.6 KB
Line 
1<?php
2/*
3Plugin Name: Menu Random Photo
4Version: 2.8.0
5Description: Adds a random picture block into menu
6Plugin URI: http://piwigo.org/ext/extension_view.php?eid=778
7Authors: JanisV, romanf
8*/
9
10global $conf;
11
12if (!defined('PHPWG_ROOT_PATH')) die('Hacking attempt!');
13
14define('MRP_ID',    basename(dirname(__FILE__)));
15define('MRP_PATH' , PHPWG_PLUGINS_PATH . MRP_ID . '/');
16define('MRP_ADMIN', get_root_url() . 'admin.php?page=plugin-' . MRP_ID);
17
18add_event_handler('init', 'MRP_init');
19add_event_handler('blockmanager_register_blocks', 'MRP_register_menubar_blocks', EVENT_HANDLER_PRIORITY_NEUTRAL-1);
20
21if (defined('IN_ADMIN'))
22{
23        add_event_handler('get_admin_plugin_menu_links', 'MRP_admin_menu');
24}
25else
26{
27        add_event_handler('blockmanager_apply', 'MRP_blockmanager_apply');
28        add_event_handler('loc_end_page_header', 'MRP_end_page_header');
29}
30
31function MRP_init()
32{
33        global $conf, $user;
34       
35        load_language('plugin.lang', MRP_PATH);
36       
37        $conf['MRP'] = unserialize($conf['MRP']);
38}
39
40function MRP_register_menubar_blocks($menu_ref_arr)
41        {
42        $menu = & $menu_ref_arr[0];
43        if ($menu->get_id() != 'menubar')
44                return;
45        $menu->register_block( new RegisteredBlock('mbRandomPhoto', 'Menu Random Photo', 'MRP'));
46}
47
48function MRP_blockmanager_apply($menu_ref_arr)
49{
50        global $user, $conf;
51       
52        $menu = & $menu_ref_arr[0];
53       
54        if((
55                ($block=$menu->get_block('mbRandomPhoto'))!=null) and
56                ($user['nb_total_images']>0)
57                )
58        {
59                $block->set_title($conf['MRP']['title']);
60                $block->template=realpath(MRP_PATH.'template/menu_random_photo.tpl');
61        }
62}
63
64function MRP_end_page_header()
65{
66        global $user, $template, $page, $conf;
67
68        if(!array_key_exists('body_id', $page))
69        {
70                /*
71                * it seems the error message reported on mantis:1476 is displayed because
72                * the 'body_id' doesn't exist in the $page
73                *
74                * not abble to reproduce the error, but initializing the key to an empty
75                * value if it doesn't exist may be a sufficient solution
76                */
77                $page['body_id']="";
78        }
79
80        if($page['body_id'] == 'theCategoryPage')
81        {
82                $randomPictProp = array(
83                        'delay' => $conf['MRP']['delay'],
84                        'blockHeight' => $conf['MRP']['height'],
85        //        'showname' => $this->config['amm_randompicture_showname'],
86        //        'showcomment' => $this->config['amm_randompicture_showcomment'],
87                        'pictures' => getRandomPictures($conf['MRP']['randompicture_preload']),
88                );
89
90                if (count($randomPictProp['pictures']) > 0)
91                {
92                        $local_tpl = new Template(MRP_PATH.'/template', "");
93                        $local_tpl->set_filename('body_page', realpath(MRP_PATH.'/template/menu_random_photo.js.tpl'));
94       
95                        $local_tpl->assign('data', $randomPictProp);
96       
97                        $template->append('head_elements', $local_tpl->parse('body_page', true));
98                }
99        }
100}
101
102/**
103* return a list of thumbnails
104* each array items is an array
105*  'imageId'   => (integer)
106*  'imageFile' => (String)
107*  'comment'   => (String)
108*  'path'      => (String)
109*  'catId'     => (String)
110*  'name'      => (String)
111*  'permalink' => (String)
112*  'imageName' => (String)
113*
114* @param Integer $number : number of returned images
115* @return Array
116*/
117function getRandomPictures($num=25)
118{
119        global $user, $conf, $page, $header_msgs;
120
121        $returned=array();
122
123        if (preg_match('/(Googlebot|bingbot|Baiduspider|yandex|AhrefsBot|msnbot|NCollector)/', $_SERVER["HTTP_USER_AGENT"]))
124        {
125                return($returned);
126        }
127
128        if (!isset($conf['MRP']['apply_to_albums']))
129        {
130                $page['errors'][] = l10n('MenuRandomPhoto seems not to be installed/configured properly. Please remove and reinstall.');
131                return ($returned);
132        }
133
134        $sql=array();
135
136        // If we use all pics for MRP, then we use the pre-fetch, if we only show
137        // some, then we can't use the pre-fetch but will limit to (hopefully) a few albums.
138
139        // pre-fetch:
140        // because ORDER BY RAND() can be very slow on a big database, let's
141        // make a first query with no join and by security take 5 times
142        // $num. We keep the result in session for 5 minutes.
143        if ($conf['MRP']['apply_to_albums'] == "all" &&
144                        (
145                        !isset($_SESSION['mrp_random_pics'])
146                        or !isset($_SESSION['mrp_random_pics_generated_on'])
147                        or $_SESSION['mrp_random_pics_generated_on'] < time() - 5*60 // 5 minutes ago
148                        )
149                )
150        {
151                $query = 'SELECT id FROM '.IMAGES_TABLE.' WHERE level <= '.$user['level'].' ORDER BY RAND() LIMIT '.($num*5).';';
152
153                $mrp = query2array($query, null, 'id');
154                if (!is_array($mrp) || count($mrp)<1)
155                {
156                        $page['errors'][] = l10n('No pictures for MenuRandomPhoto found.');
157                        return ($returned);
158                }
159
160                $_SESSION['mrp_random_pics'] = $mrp;
161                $_SESSION['mrp_random_pics_generated_on'] = time();
162        }
163       
164        $sql['select'] = '
165SELECT
166        i.id as image_id,
167        i.file as image_file,
168        i.comment,
169        i.path,
170        c.id as catid,
171        c.name,
172        c.permalink,
173        i.name as imgname
174';
175       
176        $sql['from'] = '
177FROM '.CATEGORIES_TABLE.' c
178        JOIN '.IMAGE_CATEGORY_TABLE.' ic ON ic.category_id = c.id
179        JOIN '.IMAGES_TABLE.' i ON i.id = ic.image_id
180';
181       
182        $sql['where'] = 'WHERE i.level<='.$user['level'];
183
184        if($user['forbidden_categories']!="")
185                $sql['where'].=" AND c.id NOT IN (".$user['forbidden_categories'].") ";
186
187        if ($conf['MRP']['apply_to_albums'] == "all")
188                $sql['where'].= " AND i.id IN (".implode(',', $_SESSION['mrp_random_pics']).")";
189        else
190                $sql['where'] .= " AND c.menurandomphoto_active='true' ";
191
192/*
193        switch($this->config['amm_randompicture_selectMode'])
194        {
195        case 'f':
196                $sql['from'].=", ".USER_INFOS_TABLE." ui
197                LEFT JOIN ".FAVORITES_TABLE." f ON ui.user_id=f.user_id ";
198                $sql['where'].=" AND ui.status='webmaster'
199                                                AND f.image_id = i.id ";
200                break;
201        case 'c':
202                $sql['where'].="AND (";
203                foreach($this->config['amm_randompicture_selectCat'] as $key => $val)
204                {
205                $sql['where'].=($key==0?'':' OR ')." FIND_IN_SET($val, c.uppercats) ";
206                }
207                $sql['where'].=") ";
208                break;
209        }
210*/
211        $sql = $sql['select'].$sql['from'].$sql['where']." ORDER BY RAND() LIMIT $num;";
212
213        $result = pwg_query($sql);
214        if($result)
215        {
216                if ($conf['MRP']['square'])
217                {
218                        $height = $conf['MRP']['height'];
219                        if($height == 0)
220                        $derivative_params = ImageStdParams::get_by_type(IMG_SQUARE);
221                        else
222                        $derivative_params = ImageStdParams::get_custom($height, $height, 1, $height, $height);
223                }
224                else
225                {
226                        $derivative_params = IMG_THUMB;
227                }
228       
229                while($row=pwg_db_fetch_assoc($result))
230                {
231                        $row['section']='categories';
232                        $row['category']=array(
233                        'id' => $row['catid'],
234                        'name' => $row['name'],
235                        'permalink' => $row['permalink']
236                        );
237       
238                        $row['link']=make_picture_url($row);
239                        $infos = array('id'=>$row['image_id'], 'path'=>$row['path']);
240                        $row['thumb']=DerivativeImage::url($derivative_params, $infos);
241       
242                        $returned[]=$row;
243                }
244        }
245
246        if (count($returned)<1)
247                $page['errors'][] = l10n('No pictures for MenuRandomPhoto found.');
248
249        return($returned);
250}
251
252function MRP_admin_menu($menu)
253{
254        $menu[] = array(
255                'NAME' => 'Menu Random Photo',
256                'URL'  => MRP_ADMIN,
257                );
258
259        return $menu;
260}
Note: See TracBrowser for help on using the repository browser.