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

Last change on this file since 31883 was 31883, checked in by plg, 7 years ago

implement the auto-update mechanism

  • Property svn:executable set to *
File size: 6.8 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
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 (preg_match('/(Googlebot|bingbot|Baiduspider|yandex|AhrefsBot|msnbot|NCollector)/', $_SERVER["HTTP_USER_AGENT"]))
127        {
128                return($returned);
129        }
130
131        if (!isset($conf['MRP']['apply_to_albums']))
132        {
133                $page['errors'][] = l10n('MenuRandomPhoto seems not to be installed/configured properly. Please remove and reinstall.');
134                return ($returned);
135        }
136
137        $sql=array();
138
139        // If we use all pics for MRP, then we use the pre-fetch, if we only show
140        // some, then we can't use the pre-fetch but will limit to (hopefully) a few albums.
141
142        // pre-fetch:
143        // because ORDER BY RAND() can be very slow on a big database, let's
144        // make a first query with no join and by security take 5 times
145        // $num. We keep the result in session for 5 minutes.
146        if ($conf['MRP']['apply_to_albums'] == "all" &&
147                        (
148                        !isset($_SESSION['mrp_random_pics'])
149                        or !isset($_SESSION['mrp_random_pics_generated_on'])
150                        or $_SESSION['mrp_random_pics_generated_on'] < time() - 5*60 // 5 minutes ago
151                        )
152                )
153        {
154                $query = 'SELECT id FROM '.IMAGES_TABLE.' WHERE level <= '.$user['level'].' ORDER BY RAND() LIMIT '.($num*5).';';
155
156                $mrp = query2array($query, null, 'id');
157                if (!is_array($mrp) || count($mrp)<1)
158                {
159                        $page['errors'][] = l10n('No pictures for MenuRandomPhoto found.');
160                        return ($returned);
161                }
162
163                $_SESSION['mrp_random_pics'] = $mrp;
164                $_SESSION['mrp_random_pics_generated_on'] = time();
165        }
166       
167        $sql['select'] = '
168SELECT
169        i.id as image_id,
170        i.file as image_file,
171        i.comment,
172        i.path,
173        c.id as catid,
174        c.name,
175        c.permalink,
176        i.name as imgname
177';
178       
179        $sql['from'] = '
180FROM '.CATEGORIES_TABLE.' c
181        JOIN '.IMAGE_CATEGORY_TABLE.' ic ON ic.category_id = c.id
182        JOIN '.IMAGES_TABLE.' i ON i.id = ic.image_id
183';
184       
185        $sql['where'] = 'WHERE i.level<='.$user['level'];
186
187        if($user['forbidden_categories']!="")
188                $sql['where'].=" AND c.id NOT IN (".$user['forbidden_categories'].") ";
189
190        if ($conf['MRP']['apply_to_albums'] == "all")
191                $sql['where'].= " AND i.id IN (".implode(',', $_SESSION['mrp_random_pics']).")";
192        else
193                $sql['where'] .= " AND c.menurandomphoto_active='true' ";
194
195/*
196        switch($this->config['amm_randompicture_selectMode'])
197        {
198        case 'f':
199                $sql['from'].=", ".USER_INFOS_TABLE." ui
200                LEFT JOIN ".FAVORITES_TABLE." f ON ui.user_id=f.user_id ";
201                $sql['where'].=" AND ui.status='webmaster'
202                                                AND f.image_id = i.id ";
203                break;
204        case 'c':
205                $sql['where'].="AND (";
206                foreach($this->config['amm_randompicture_selectCat'] as $key => $val)
207                {
208                $sql['where'].=($key==0?'':' OR ')." FIND_IN_SET($val, c.uppercats) ";
209                }
210                $sql['where'].=") ";
211                break;
212        }
213*/
214        $sql = $sql['select'].$sql['from'].$sql['where']." ORDER BY RAND() LIMIT $num;";
215
216        $result = pwg_query($sql);
217        if($result)
218        {
219                if ($conf['MRP']['square'])
220                {
221                        $height = $conf['MRP']['height'];
222                        if($height == 0)
223                        $derivative_params = ImageStdParams::get_by_type(IMG_SQUARE);
224                        else
225                        $derivative_params = ImageStdParams::get_custom($height, $height, 1, $height, $height);
226                }
227                else
228                {
229                        $derivative_params = IMG_THUMB;
230                }
231       
232                while($row=pwg_db_fetch_assoc($result))
233                {
234                        $row['section']='categories';
235                        $row['category']=array(
236                        'id' => $row['catid'],
237                        'name' => $row['name'],
238                        'permalink' => $row['permalink']
239                        );
240       
241                        $row['link']=make_picture_url($row);
242                        $infos = array('id'=>$row['image_id'], 'path'=>$row['path']);
243                        $row['thumb']=DerivativeImage::url($derivative_params, $infos);
244       
245                        $returned[]=$row;
246                }
247        }
248
249        if (count($returned)<1)
250                $page['errors'][] = l10n('No pictures for MenuRandomPhoto found.');
251
252        return($returned);
253}
254
255function MRP_admin_menu($menu)
256{
257        $menu[] = array(
258                'NAME' => 'Menu Random Photo',
259                'URL'  => MRP_ADMIN,
260                );
261
262        return $menu;
263}
Note: See TracBrowser for help on using the repository browser.