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

Last change on this file since 31996 was 31972, checked in by romanf, 5 years ago

Protect access to $_SERVER with isset()

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