OSDN Git Service

fix sticky mode
[nucleus-jp/nucleus-plugins.git] / trunk / NP_ShowBlogs / NP_ShowBlogs.php
1 <?php 
2 /**
3  *
4  * SHOWING BLOGS PLUG-IN FOR NucleusCMS
5  * PHP versions 4 and 5
6  *
7  * This program is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License
9  * as published by the Free Software Foundation; either version 2
10  * of the License, or (at your option) any later version.
11  * (see nucleus/documentation/index.html#license for more info)
12  *
13  * @author    Original Author nakahara21
14  * @copyright 2005-2006 nakahara21
15  * @license   http://www.gnu.org/licenses/gpl.txt  GNU GENERAL PUBLIC LICENSE Version 2, June 1991
16  * @version   2.66
17  * @link      http://japan.nucleuscms.org/wiki/plugins:showblogs
18  *
19  * 2.66.1 fix sticky mode
20  * 2.66   default argument bug fix
21  * 2.65   add AD code control
22  *        add Category mode
23  *        fix stickies bug
24  * 2.64   fix page switch URL generate
25  * 2.62   security fix and tag related
26  * 2.61   security fix
27  * 2.6    security fix
28  *
29  ****************************************************************************
30  *
31  * THESE PLUG-INS ARE DEDICATED TO ALL THOSE NucleusCMS USERS
32  * WHO FIGHT CORRUPTION AND IRRATIONAL IN EVERY DAY OF THEIR LIVES.
33  *
34  ****************************************************************************/
35
36 class NP_ShowBlogs extends NucleusPlugin
37 {
38
39         function getName()
40         {
41                 return 'Show Blogs';
42         }
43
44         function getMinNucleusVersion()
45         {
46                 return '322';
47         }
48
49         function getAuthor()
50         {
51                 return 'Taka + nakahara21 + kimitake + shizuki';
52         }
53
54         function getURL()
55         {
56                 return 'http://japan.nucleuscms.org/wiki/plugins:showblogs';
57         }
58
59         function getVersion()
60         {
61                 return '2.66.1';
62         }
63
64         function getDescription()
65         {
66                 return _SHOWB_DESC; 
67         } 
68
69         function supportsFeature($what)
70         {
71                 switch($what){
72                         case 'SqlTablePrefix':
73                                 return 1;
74                         default:
75                                 return 0;
76                 }
77         }
78
79         function getEventList()
80         {
81                 return array(
82                         'InitSkinParse'
83                 );
84         }
85
86         function init()
87         {
88                 $language = ereg_replace( '[\\|/]', '', getLanguageName());
89                 if (file_exists($this->getDirectory()  . $language . '.php')) {
90                         include_once($this->getDirectory() . $language . '.php');
91                 }else {
92                         include_once($this->getDirectory() . 'english.php');
93                 }
94         }
95
96         function install()
97         {
98 //              $this->createOption('catnametoshow', '[allblog mode only] category name to show (0:catname on blogname, 1:catname only, 2:blogname only)','text','0');
99 //              $this->createOption('stickmode',        '[currentblog mode only] 0:show all stickyID, 1:show current blog stickyID only', 'text', '1');
100 //              $this->createOption('ads', '[Ads code] code displayed under first and second item of the page', 'textarea', '' . "\n");
101 // <mod by shizuki>
102                 $this->createOption('catformat',     _CAT_FORMAT,   'text',    '<%category%> on <%blogname%>');
103 //              $this->createOption('catnametoshow', CATNAME_SHOW, 'text',     '0');
104 //              $this->createOption('stickmode',    _STICKMODE,    'text',     '1');
105                 $this->createOption('stickmode',    _STICKMODE,    'select',   '1', _STICKSELECT);
106                 $this->createOption('ads',          _ADCODE_1,     'textarea', '' . "\n");
107                 $this->createOption('ads2',         _ADCODE_2,     'textarea', '' . "\n");
108                 $this->createOption('tagMode',      _TAG_MODE,     'select',   '2', _TAG_SELECT);
109 /* todo can't install ? only warning ?
110  * douyatte 'desc' ni keikoku wo daseba iinoka wakaranai desu
111                 $ver_min = (getNucleusVersion() < $this->getMinNucleusVersion());
112                 $pat_min = ((getNucleusVersion() == $this->getMinNucleusVersion()) &&
113                                 (getNucleusPatchLevel() < $this->getMinNucleusPatchLevel()));
114                 if ($ver_min) { // || $pat_min) {
115                         global $DIR_LIBS;
116                         // uninstall plugin again...
117                         include_once($DIR_LIBS . 'ADMIN.php');
118                         $admin = new ADMIN();
119                         $admin->deleteOnePlugin($this->getID());
120                 
121                         // ...and show error
122                         $admin->error(_ERROR_NUCLEUSVERSIONREQ .
123                         $this->getMinNucleusVersion() . ' patch ' .
124                         $this->getMinNucleusPatchLevel());
125                 }
126 */
127 // </mod by shizuki>
128         }
129
130         function doSkinVar($skinType,
131                                            $template      = 'default/index',
132                                            $amount        = 10,              // amount/page
133                                            $bmode         = '',              // show or hide Blogs
134                                            $type          = 1,               // pagw switch type
135                                            $sort          = 'DESC',          // item sort mode (DESC or ASC)
136                                            $sticky        = '',              // sticky item id
137                                            $sticktemplate = '',
138                                            $catmode       = 'all',           // show or hide categories
139                                            $showAdCode    = 1,               // AdCode switch
140                                            $catStick      = 0                // show sticky item when category selected ?
141                                           )
142         {
143                 global $manager, $CONF, $blog, $blogid, $catid, $itemid, $archive, $subcatid;
144
145                 if (!$template) {
146                         $template = 'default/index';
147                 }
148
149 // initialize hide blogID
150                 $hide = array();
151 // initialize show blogID
152                 $show = array();
153 // limit number of pages(months) 
154                 $pagelimit  = 0;
155                 $monthlimit = 0;
156                 $catformat  = $this->getOption('catformat');
157
158                 $params = func_get_args();
159                 switch ($amount) {
160                         case '0':
161                                 $type = $amount;
162                                 break;
163                         case 'all':
164                                 $bmode = $amount;
165                                 if (is_numeric($params[3]) ||is_float($params[3])) {
166                                         $type = $params[3];
167                                 }
168                                 break;
169                 }
170
171                 if (preg_match("/^(<>)?([0-9\/]+)$/", $bmode, $matches)) {
172                         if ($matches[1]) {
173                                 $hide = explode("/", $matches[2]);
174                                 $show = array();
175                         } else {
176                                 $hide = array();
177                                 $show = explode("/", $matches[2]);
178                         }
179                         $bmode = 'all';
180                 }
181
182                 $type             = (float) $type;
183                 $typeExp          = intval(($type - floor($type))*10); //0 or 1 or 9
184                 $this->showAdCode = $showAdCode;
185
186                 list ($pageamount, $offset) = sscanf($amount, '%d(%d)');
187                 if (!$pageamount) {
188                         $pageamount = 10;
189                 }
190
191                 if ($sort != 'ASC') {
192                         $sort = 'DESC';
193                 }
194
195 /*              if ($sort != 'ASC' && $sort != 'DESC') {
196                         $sticktemplate = $sticky;
197                         $sticky        = $sort;
198                         $sort          = 'DESC';
199                 }*/
200
201                 if (!empty($sticky) && empty($sticktemplate)) {
202                         $sticktemplate = $template;
203                 }
204
205                 if (preg_match("/^(<>)?([0-9\/]+)$/", $catmode, $matches)) {
206                         if ($matches[1]) {
207                                 $hideCat = explode("/", $matches[2]);
208                                 $showCat = array();
209                         } else {
210                                 $hideCat = array();
211                                 $showCat = explode("/", $matches[2]);
212                         }
213                         $catmode = 'all';
214                 }
215
216                 if ($blog) {
217                         $b =& $blog; 
218                 } else {
219                         $b =& $manager->getBlog($CONF['DefaultBlog']);
220                 }
221                 $this->nowbid = $nowbid = intval($b->getID());
222
223                 $where       = '';
224                 $catblogname = 0;
225
226                 if ($bmode != 'all') {
227                         $where .= ' AND i.iblog = ' . $nowbid;
228                 } elseif (isset($hide[0]) && $bmode == 'all') {
229                         foreach ($hide as $val) {
230                                 if (!is_numeric($val)) {
231                                         $val = getBlogIDFromName(intval($val));
232                                 }
233                                 $where .= ' AND i.iblog != ' . intval($val);
234                         }
235                         $catblogname = 1;
236                 } elseif (isset($show[0]) && $bmode == 'all') {
237                         foreach ($show as $val) {
238                                 if (!is_numeric($val)) {
239                                         $val = getBlogIDFromName(intval($val));
240                                 }
241                                 $w[] = intval($val);
242                         }
243                         $catblogname = (count($w) > 1) ? 1 : 0;
244                         $where .= ' AND i.iblog in (' . implode(',', $w) . ')';
245                 }
246
247                 if (isset($hidecat[0]) && $catmode == 'all') {
248                         foreach($hideCat as $val){
249                                 if(!is_numeric($val)){
250                                         $val = getCatIDFromName(intval($val));
251                                 }
252                                 $where .= ' AND i.icat != ' . intval($val);
253                         }
254                         $catblogname = 1;
255                 } elseif (isset($showCat[0]) && $catmode == 'all') {
256                         foreach ($showCat as $val) {
257                                 if (!is_numeric($val)) {
258                                         $val = getBlogIDFromName(intval($val));
259                                 }
260                                 $w[] = intval($val);
261                         }
262                         $catblogname = (count($w) > 1) ? 1 : 0;
263                         $where .= ' AND i.icat in (' . implode(',', $w) . ')';
264                 }
265 //              $stickWhere = $where;
266
267                 if ($skinType == 'item' || $skinType == 'index' || $skinType == 'archive') {
268                         $catformat = '"' . addslashes($catformat) . '"';
269                         $nArr      = array(
270                                                            '",c.cname,"',
271                                                            '",b.bname,"',
272                                                            '",c.cdesc,"'
273                                                           );
274                         $fArr      = array(
275                                                            '/<%category%>/',
276                                                            '/<%blogname%>/',
277                                                            '/<%catdesc%>/'
278                                                           );
279                         $catformat = preg_replace($fArr, $nArr, $catformat);
280                         $mtable    = "";
281                         if ($manager->pluginInstalled('NP_TagEX')) {
282                                 $t_where = $this->_getTagsInum($where, $skinType, $bmode, $amount);
283                                 $where .= $t_where['where'];
284                         }
285
286                         if ($skinType == 'item') {
287                                 $where .= ' and i.inumber != ' . intval($itemid);
288                         } else {
289
290                                 $sticCatFlag = (!$catid || (!empty($catStick) && $sticktemplate != ''));
291 //                              if (!$catid && $sticky != '') {
292                                 if ($sticCatFlag && $sticky != '') {
293                                         $stickys = explode('/',  $sticky);
294                                         foreach ($stickys as $stickynumber) {
295                                                 $where .= ' AND i.inumber <> ' . intval($stickynumber);
296                                         }
297                                 }
298
299 //                              $hidden = '';
300                                 $temp = $y = $m = $d = '';
301                                 if ($archive) {
302                                         sscanf($archive, '%d-%d-%d', $y, $m, $d);
303                                         if ($d) {
304                                                 $timestamp_start = mktime(0, 0, 0, $m, $d,   $y);
305                                                 $timestamp_end   = mktime(0, 0, 0, $m, $d+1, $y);
306                                                 $date_str        = 'SUBSTRING(i.itime, 1, 10)';
307                                         } else {
308                                                 $timestamp_start = mktime(0, 0, 0, $m,   1, $y);
309                                                 $timestamp_end   = mktime(0, 0, 0, $m+1, 1, $y);
310                                                 $date_str        = 'SUBSTRING(i.itime,1,7)';
311                                         }
312                                         $where .= ' AND i.itime >= ' . mysqldate($timestamp_start)
313                                                         . ' AND i.itime < ' . mysqldate($timestamp_end);
314                                 } elseif (!empty($monthlimit)) {
315                                         $timestamp_end   = mysqldate($b->getCorrectTime());
316                                         sscanf($timestamp_end, '"%d-%d-%d %s"', $y, $m, $d, $temp);
317                                         $timestamp_start = mktime(0, 0, 0, $m-$monthlimit, $d, $y);
318                                         $where .= ' AND i.itime >= ' . mysqldate($timestamp_start)
319                                                         . ' AND i.itime <= ' . $timestamp_end;
320                                 } else {
321                                         $where .= ' AND i.itime <= ' . mysqldate($b->getCorrectTime());
322                                 }
323
324                                 if (!empty($catid)) {
325                                         if ($manager->pluginInstalled('NP_MultipleCategories')) {
326                                                 $mcat_query = $this->_getSubcategoriesWhere($catid);
327                                                 $mtable     = $mcat_query['m'];
328                                                 $where     .= $mcat_query['w'];
329                                         } else {
330                                                 $where     .= ' AND i.icat=' . intval($catid);
331                                         }
332                                         $linkparams['catid'] = $todayparams['catid'] = intval($catid);
333                                 }
334
335                                 if ($type >= 1) {
336                                         $page_switch = $this->PageSwitch($type, $pageamount, $offset, $where, $sort, $mtable);
337                                         if ($typeExp != 9 && $skinType != 'item') {
338                                                 echo $page_switch['buf'];
339                                         }
340                                 }
341                         }
342
343                         $sh_query = 'SELECT '
344                                           . 'i.inumber               as itemid, '
345                                           . 'i.ititle                as title, '
346                                           . 'i.ibody                 as body, '
347                                           . 'm.mname                 as author, '
348                                           . 'm.mrealname             as authorname, '
349                                           . 'UNIX_TIMESTAMP(i.itime) as timestamp, '
350                                           . 'i.itime, '
351                                           . 'i.imore                 as more, '
352                                           . 'm.mnumber               as authorid,';
353                         if (!$catblogname) {
354                                 $sh_query .= ' c.cname as category,';
355                         } else {
356                                 $sh_query .= ' concat(' . $catformat . ') as category,';
357                         }
358                         $sh_query .= ' i.icat    as catid,'
359                                            . ' i.iclosed as closed'
360                                            . ' FROM '
361                                            . sql_table('member') .   ' as m, '
362                                            . sql_table('category') . ' as c, '
363                                            . sql_table('item') .     ' as i'
364                                            . $mtable;
365                         if ($bmode == 'all') {
366                                 $sh_query .= ', ' . sql_table('blog') . ' as b ';
367                         }
368                         $sh_query .= ' WHERE i.iauthor = m.mnumber'
369                                            . ' AND   i.icat    = c.catid';
370                         if ($bmode == 'all') {
371                                 $sh_query .= ' AND b.bnumber = c.cblog';
372                         }
373
374 //                      if ($page_switch['startpos'] == 0 && !$catid && $sticky != '' && $skinType != 'item' && !$this->tagSelected) {
375                         $ads         = 0;
376                         $sticCatFlag = ($page_switch['startpos'] == 0 && (!$catid || (!empty($catStick) && $sticktemplate != '')));
377                         if ($sticCatFlag && $sticky != '' && $skinType != 'item' && !$this->tagSelected) {
378                                 foreach ($stickys as $stickynumber) {
379                                         $sticky_query = $sh_query;
380                                         $tempblogid   = getBlogIDFromItemID($stickynumber);
381                                         if ($bmode != 'all' && $this->getOption('stickmode') == 1) {
382                                                 $sticky_query .= ' AND i.iblog = ' . $nowbid;
383                                         }
384                                         $sticky_query .= ' AND i.inumber = ' . intval($stickynumber)
385                                                                    . ' AND i.itime  <= ' . mysqldate($b->getCorrectTime())
386                                                                    . ' AND i.idraft  = 0';
387                                         if ($catid) {
388                                                 $sticky_query .= ' AND i.icat = ' . intval($catid);
389                                         }
390                                         if ($subcatid) {
391                                                 $sticky_query .= ' AND p.subcategories = ' . intval($subcatid);
392                                         }
393 /*                                      $sticky_query .= $stickWhere;
394                                         if ($bmode == 'all') {
395                                                 $b->showUsingQuery($sticktemplate, $sticky_query, 0, 1, 0); 
396                                         } elseif ($this->getOption('stickmode') == 1 && intval($nowbid) == $tempblogid) {
397                                                 $b->showUsingQuery($sticktemplate, $sticky_query, 0, 1, 0); 
398                                         } elseif (!$this->getOption('stickmode')) {
399                                                 $b->showUsingQuery($sticktemplate, $sticky_query, 0, 1, 0); 
400                                         }*/
401
402                                         if (
403                                             ($bmode == 'all') ||
404                                                 ($this->getOption('stickmode') == 1 && intval($nowbid) == $tempblogid) ||
405                                                 (!$this->getOption('stickmode'))
406                                            ) {
407                                                 $b->showUsingQuery($sticktemplate, $sticky_query, 0, 1, 0); 
408                                         }
409
410                                         //echo $stickynumber;
411                                         if ($showAdCode > 0 && mysql_num_rows(sql_query($sticky_query))) {
412                                                 if ($ads == 0) {
413                                                         echo $this->getOption('ads');
414                                                 } elseif ($ads == 1) {
415                                                         echo $this->getOption('ads2');
416                                                 } elseif ($ads >= 2) {
417                                                 }
418                                                 $ads++;
419                                         }
420                                 }
421                         }
422
423                         $sh_query .= ' AND i.idraft = 0' . $where;
424
425                         if ($skinType == 'item') {
426                                 $sh_query .= ' ORDER BY FIND_IN_SET(i.inumber,\'' . @join(',', $t_where['inumsres']) . '\')';
427                         } else {
428                                 $sh_query .= ' ORDER BY i.itime ' . $sort;
429                         }
430
431                         if ($skinType != 'item') {
432                                 $this->_showUsingQuery($template, $sh_query, $page_switch['startpos'], $pageamount, $b, $ads);
433                                 if ($type >= 1 && $typeExp != 1) echo $page_switch['buf'];
434                         } elseif ($skinType == 'item') {
435                                 $sh_query .= ' LIMIT 0, ' . $pageamount;
436                                 $b->showUsingQuery($template, $sh_query, 0, 1, 1); 
437                         }
438                 }
439         }
440
441         function _showUsingQuery($template, $showQuery, $q_startpos, $q_amount, $b, $ads)
442         {
443                 global $catid;
444                 $onlyone_query = $showQuery . ' LIMIT ' . intval($q_startpos) .', 1';
445                 $b->showUsingQuery($template, $onlyone_query, 0, 1, 1);
446                 if (intval($ads) == 0 && $this->showAdCode > 0) {
447                         echo $this->getOption('ads');
448 //              }
449 //------------SECOND AD CODE-------------
450                 } elseif (intval($ads) == 1 && $this->showAdCode > 0) {
451                         echo $this->getOption('ads2');
452                 }
453                 $q_startpos++;
454                 $q_amount--;
455                 if ($q_amount < 0) return;
456                 $onlyone_query = $showQuery . ' LIMIT ' . intval($q_startpos) . ', 1';
457                 $b->showUsingQuery($template, $onlyone_query, 0, 1, 1); 
458                 if (mysql_num_rows(sql_query($onlyone_query)) && empty($ads) && $this->showAdCode > 0) {
459                         echo $this->getOption('ads2');
460                 }
461 //------------SECOND AD CODE END-------------
462                 $q_startpos++;
463                 $q_amount--;
464                 if ($q_amount <= 0) return;
465                 $second_query = $showQuery . ' LIMIT ' . intval($q_startpos) . ',' . intval($q_amount);
466                 $b->showUsingQuery($template, $second_query, 0, 1, 1);
467         }
468
469         function event_InitSkinParse($data)
470         {
471                 global $CONF, $manager;
472                 $usePathInfo = ($CONF['URLMode'] == 'pathinfo');
473                 if (serverVar('REQUEST_URI') == '') {
474                         $uri = (serverVar('QUERY_STRING')) ?
475                                 serverVar('SCRIPT_NAME') . serverVar('QUERY_STRING') : serverVar('SCRIPT_NAME');
476                 } else { 
477                         $uri = serverVar('REQUEST_URI');
478                 }
479                 $page_str = ($usePathInfo) ? 'page/' : 'page=';
480                 if ($manager->pluginInstalled('NP_CustomURL') || $manager->pluginInstalled('NP_Magical')) {
481                         $page_str = 'page_';
482                 }
483                 list($org_uri, $currPage) = explode($page_str, $uri, 2);
484                 if (getVar('page')) {
485                         $currPage = intGetVar('page');
486                 }
487                 $_GET['page']   = intval($currPage);
488                 $this->currPage = intval($currPage);
489                 $this->pagestr  = $page_str;
490         }
491
492         function PageSwitch($type, $pageamount, $offset, $where, $sort, $mtable = '')
493         {
494                 global $CONF, $manager, $archive, $catid, $subcatid;
495
496 // initialize
497                 $startpos    = 0;
498                 $catid       = intval($catid);
499                 $subcatid    = intval($subcatid);
500                 $usePathInfo = ($CONF['URLMode'] == 'pathinfo');
501                 $pageamount  = intval($pageamount);
502                 $offset      = intval($offset);
503                 if ($archive) {
504                         $y = $m = $d = '';
505                         sscanf($archive, '%d-%d-%d', $y, $m, $d);
506                         if (!empty($d)) {
507                                 $archive = sprintf('%04d-%02d-%02d', $y, $m, $d);
508                         } else {
509                                 $archive = sprintf('%04d-%02d', $y, $m);
510                         }
511                 }
512
513                 $page_str    = $this->pagestr;
514                 $currentpage = $this->currPage; 
515
516 // createBaseURL
517                 if (!empty($catid)) {
518                         $catrequest = ($usePathInfo) ? $CONF['CategoryKey'] : 'catid';
519                         if (!empty($subcatid)) {
520                                 $mplugin =& $manager->getPlugin('NP_MultipleCategories');
521                                 $subrequest = $mplugin->getRequestName(array());
522                                 if (!empty($archive)) {
523                                         $linkParam = array(
524                                                                            $catrequest => $catid,
525                                                                            $subrequest => $subcatid
526                                                                           );
527                                         $pagelink  = createArchiveLink($archive, $linkParam);
528                                 } else {
529                                         $linkParam = array(
530                                                                            $subrequest => $subcatid
531                                                                           );
532                                         $pagelink  = createCategoryLink($catid, $linkParam);
533                                 }
534                         } else {
535                                 if (!empty($archive)) {
536                                         $linkParam = array(
537                                                                            $catrequest => $catid,
538                                                                           );
539                                         $pagelink  = createArchiveLink($archive, $linkParam);
540                                 } else {
541                                         $pagelink  = createCategoryLink($catid);
542                                 }
543                         }
544                 } else {
545                         if (!empty($archive)) {
546                                 $pagelink = createArchiveLink($this->nowbid, $archive);
547                         } else {
548                                 $pagelink = createBlogidLink($this->nowbid);
549                         }
550                 }
551                 if ($manager->pluginInstalled('NP_TagEX')) {
552                         $tplugin =& $manager->getPlugin('NP_TagEX');
553                         $requestTag = $tplugin->getNoDecodeQuery('tag');
554                         if (!empty($requestTag)) {
555                                 $requestTarray = $tplugin->splitRequestTags($requestTag);
556                                 $tag = array_shift($requestTarray['and']);
557                                 $tag = $tplugin->_rawdecode($tag);
558                                 if (!empty($requestTarray['and'])) {
559                                         $requestT = implode('+', $requestTarray['and']);
560                                 }
561                                 if (!empty($requestTarray['or'])) {
562                                         $requestTor = implode(':', $requestTarray['or']);
563                                 }
564                                 if (!empty($requestT)) {
565                                         if (!empty($requestTor)) {
566                                                 $reqtags  = $requestT . ':' . $requestTor;
567                                                 $pagelink = $tplugin->creatTagLink($tag, $this->getOption('tagMode'), $reqtags, '+');
568                                         } else {
569                                                 $pagelink = $tplugin->creatTagLink($tag, $this->getOption('tagMode'), $requestT, '+');
570                                         }
571                                 } elseif (empty($requestT) && !empty($requestTor)) {
572                                         $pagelink = $tplugin->creatTagLink($tag, $this->getOption('tagMode'), $requestTor, ':');
573                                 } else {
574                                         $pagelink = $tplugin->creatTagLink($tag, $this->getOption('tagMode'));
575                                 }
576                         }
577                 }
578
579                 if (strstr ($pagelink, '//')) {
580                         $pagelink = preg_replace("/([^:])\/\//", "$1/", $pagelink);
581                 }
582                 $uri = parse_url($pagelink);
583                 if (!$usePathInfo) {
584                         if ($pagelink == $CONF['BlogURL']) { // add
585                                 $pagelink .= '?';
586                         } elseif ($uri['query']) {
587                                 $pagelink .= '&amp;';
588                         }
589                         $pagelink = str_replace('&amp;&amp;', '&amp;', $pagelink);
590                 } elseif ($usePathInfo && substr($pagelink, -1) != '/') {
591                         if ($uri['query']) {
592                                 $pagelink .= '&amp;';
593                                 $page_str  = 'page=';
594                         } else {
595                                 $pagelink .= '/';
596                                 if (strstr ($pagelink, '//')) $link = preg_replace("/([^:])\/\//", "$1/", $pagelink);
597                         }
598                 }
599
600                 if ($currentpage > 0) {
601                         $startpos = ($currentpage - 1) * $pageamount;
602                 } else {
603                         $currentpage = 1;
604                 }
605
606                 $totalamount = 0;
607                 if (is_numeric($where)) {
608                         $totalamount = $where;
609                 } elseif (is_array($where)) {
610                         $totalamount = count($where);
611                 } else {
612                         $p_query = 'SELECT COUNT(i.inumber) FROM %s as i%s WHERE i.idraft = 0%s';
613                         $p_query = sprintf($p_query, sql_table('item'), $mtable, $where);
614 //                      $p_query = 'SELECT COUNT(i.inumber) FROM ' . sql_table('item') . ' as i' . $mtable . ' WHERE i.idraft=0' . $where;
615                         $entries = sql_query($p_query);
616                         if ($row = mysql_fetch_row($entries)) {
617                                 $totalamount = $row[0];
618                         }
619                 }
620                 $totalamount = intval($totalamount);
621                 if (!$archive && !empty($pagelimit) && ($pagelimit * $pageamount < $totalamount)) {
622                         $totalamount = intval($pagelimit) * $pageamount;
623                 }
624                 if ($offset) {
625                         $startpos += $offset;
626                         $totalamount -= $offset;
627                 }
628                 if ($this->maxamount && $this->maxamount < $totalamount) {
629                         $totalamount = intval($this->maxamount);
630                 }
631                 $totalpages = ceil($totalamount/$pageamount);
632                 $totalpages = intval($totalpages);
633                 if ($startpos > $totalamount) {
634                         $currentpage = $totalpages;
635                         $startpos    = $totalamount-$pageamount;
636                 }
637                 if ($offset) {
638                         $startpos += $offset;
639                         $totalamount -= $offset;
640                 }
641                 $totalpages = ceil($totalamount/$pageamount);
642                 if ($startpos > $totalamount) {
643                         $currentpage = $totalpages;
644                         $startpos    = $totalamount-$pageamount;
645                 }
646                 $prevpage      = ($currentpage > 1) ? $currentpage - 1 : 0;
647                 $nextpage      = $currentpage + 1;
648                 $firstpagelink = $pagelink . $page_str . '1';
649                 if ($page_str == 'page_') {
650                         $firstpagelink .= '.html';
651                 }
652                 $lastpagelink = $pagelink . $page_str . $totalpages;
653                 if ($page_str == 'page_') {
654                         $lastpagelink .= '.html';
655                 }
656
657                 if ($type >= 1) {
658                         $buf .= '<div class="pageswitch">' . "\n";
659 //                      $buf .= "<a rel=\"first\" title=\"first page\" href=\"{$firstpagelink}\">&lt;TOP&gt;</a> | \n";
660                         if (!empty($prevpage)) {
661                                 $prevpagelink = $pagelink . $page_str . $prevpage;
662                                 if ($page_str == 'page_') {
663                                         $prevpagelink .= '.html';
664                                 }
665                                 $buf .= '<a href="' . $prevpagelink . '" title="Previous page" rel="Prev">&laquo;Prev</a> |';
666                         } elseif ($type >= 2) {
667                                 $buf .= "&laquo;Prev |";
668                         }
669                         $buf .= "\n";
670                         if (intval($type) == 2) {
671                                 $sepstr = '&middot;';
672                                 $buf   .= "|";
673                                 for ($i=1; $i<=$totalpages; $i++) {
674                                         $i_pagelink = $pagelink . $page_str . $i;
675                                         if ($page_str == 'page_') {
676                                                 $i_pagelink .= '.html';
677                                         }
678                                         if ($i == $currentpage) {
679                                                 $buf .= ' <strong>' . $i . '</strong> |' . "\n";
680                                         } elseif ($totalpages<10 || $i<4 || $i>$totalpages-3) {
681                                                 $buf .= ' <a href="' . $i_pagelink . '" title="Page No.' . $i . '">'
682                                                           . $i . '</a> |' . "\n";
683                                         } else {
684                                                 if ($i<$currentpage-1 || $i>$currentpage+1) {
685                                                         if (($i == 4 && ($currentpage > 5 || $currentpage == 1)) || $i == $currentpage + 2) {
686                                                                 $buf  = rtrim($buf);
687                                                                 $buf .= "...|\n";
688                                                         }
689                                                 } else {
690                                                         $buf .= ' <a href="' . $i_pagelink . '" title=\"Page No.' . $i . '">'
691                                                                   . $i . '</a> |' . "\n";
692                                                 }
693                                         }
694                                 }
695                                 $buf = rtrim($buf);
696                         }
697                         if (intval($type) == 3) {
698                                 $buf .= '|';
699                                 $sepstr = '&middot;';
700                                 for ($i = 1; $i <= $totalpages; $i++) {
701                                         $i_pagelink = $pagelink . $page_str . $i;
702                                         if ($page_str == 'page_') {
703                                                 $i_pagelink .= '.html';
704                                         }
705                                         $paging = 5;
706                                         if ($i == $currentpage) {
707                                                 $buf .= ' <strong>' . $i . '</strong> ' . $sepstr . "\n";
708                                         } elseif ($totalpages < 10 || ($i < ($currentpage + $paging) && ($currentpage - $paging) < $i)) {
709                                                 $buf .= ' <a href="' . $i_pagelink . '" title="Page No.' . $i . '">'
710                                                           . $i . '</a> ' . $sepstr . "\n";
711                                         } elseif ($currentpage - $paging == $i) {
712                                                 $buf = rtrim($buf);
713                                                 $buf .= ' ...'."\n";
714                                         } elseif ($currentpage + $paging == $i) {
715                                                 $buf = rtrim($buf);
716                                                 $buf = preg_replace('/$sepstr$/', '', $buf);
717                                                 $buf .= "... |\n";
718                                         }
719                                 }
720                         }
721                         if ($totalpages >= $nextpage) {
722                                 $nextpagelink = $pagelink . $page_str . $nextpage;
723                                 if ($page_str == 'page_') {
724                                         $nextpagelink .= '.html';
725                                 }
726                                 $buf .= '| <a href="' . $nextpagelink . '" title="Next page" rel="Next">Next&raquo;</a>' . "\n";
727                         } elseif ($type >= 2) {
728                                 $buf .= "| Next&raquo;\n";
729                         }
730 //                      $buf .= " | <a rel=\"last\" title=\"Last page\" href=\"{$lastpagelink}\">&lt;LAST&gt;</a>\n";
731                         $buf .= "</div>\n";
732                         return array('buf' => $buf, 'startpos' => intval($startpos));
733                 }
734         }
735
736         function _getSubcategoriesWhere($catid)
737         {
738                 global $manager;
739                 $subcatTable =  sql_table('plug_multiple_categories_sub');
740                 $mwhere      =  '';
741                 $mwhere      =  ' AND ((i.inumber = p.item_id'
742                                          .  ' AND (p.categories REGEXP "(^|,)' . intval($catid) . '(,|$)"'
743                                          .  ' OR i.icat  = ' . intval($catid) . '))'
744                                          .  ' OR (i.icat = ' . intval($catid)
745                                          .  ' AND p.item_id IS NULL))';
746                 $mtable      =  ' LEFT JOIN ' . sql_table('plug_multiple_categories') . ' as p'
747                                          .  ' ON i.inumber = p.item_id';
748                 $mplugin     =& $manager->getPlugin('NP_MultipleCategories');
749                 if (method_exists($mplugin, 'getRequestName')) {
750                         $mplugin->event_PreSkinParse(array());
751                         global $subcatid;
752                         if ($subcatid) {
753                                 $subcatid = intval($subcatid);
754
755                                 $mque = 'SELECT * FROM %s WHERE scatid = %d';
756                                 $tres = sql_query(sprintf($mque, $subcatTable, $subcatid));
757 //                              $tres = sql_query('SELECT * FROM ' . sql_table('plug_multiple_categories_sub') .
758 //                                                              ' WHERE scatid = ' . intval($subcatid));
759                                 $ra   = mysql_fetch_array($tres, MYSQL_ASSOC);
760                                 if (array_key_exists('parentid', $ra)) {
761                                         $Children = array();
762                                         $Children = explode('/', $subcatid . $this->getChildren($subcatid));
763                                 }
764                                 if ($Children[1]) {
765                                         for ($i=0;$i<count($Children);$i++) {
766                                                 $temp_whr[] = ' p.subcategories REGEXP "(^|,)' . intval($Children[$i]) . '(,|$)" ';
767                                         }
768                                         $mwhere .= ' AND ( ';
769                                         $mwhere .= implode(' OR ', $temp_whr);
770                                         $mwhere .= ' )';
771                                 } else {
772                                         $mwhere .= ' AND p.subcategories REGEXP "(^|,)' . $subcatid . '(,|$)"';
773                                 }
774                         }
775                 }
776                 return array(
777                                          'w' => $mwhere,
778                                          'm' => $mtable
779                                         );
780         }
781
782         function getParents($subcat_id)
783         {
784                 $subcatTable = sql_table('plug_multiple_categories_sub');
785                 $que         = 'SELECT scatid, parentid, sname FROM %s WHERE scatid = %d';
786                 $que         = sprintf($que, $subcatTable, intval($subcat_id));
787                 $res         = sql_query($que);
788                 list($sid, $parent, $sname) = mysql_fetch_row($res);
789                 if ($parent != 0) {
790                         $r = $this->getParent(intval($parent)) . '/' . intval($sid);
791                 } else {
792                         $r = intval($sid);
793                 }
794                 return $r;
795         }
796
797         function getChildren($subcat_id)
798         {
799                 $subcatTable = sql_table('plug_multiple_categories_sub');
800                 $que         = 'SELECT scatid, parentid, sname FROM %s WHERE parentid = %d';
801                 $que         = sprintf($que, $subcatTable, intval($subcat_id));
802                 $res         = sql_query($que);
803                 while ($so =  mysql_fetch_object($res)) {
804                         $r .= $this->getChildren(intval($so->scatid)) . '/' . intval($so->scatid);
805                 }
806                 return $r;
807         }
808
809         function _getTagsInum($where, $skin_type, $bmode, $p_amount)
810         {
811                 global $manager, $itemid;
812                 $tagTable   =  sql_table('plug_tagex');
813                 $tplugin    =& $manager->getPlugin('NP_TagEX');
814                 $requestTag =  $tplugin->getNoDecodeQuery('tag');
815                 if (!empty($requestTag) || $skin_type == 'item') {
816                         $this->tagSelected = TRUE;
817                         if ($bmode=='all') {
818                                 $allTags = $tplugin->scanExistTags(0);
819                         } else {
820                                 $allTags = $tplugin->scanExistTags(2);
821                         }
822                         $arr = $tplugin->splitRequestTags($requestTag);
823                         if ($skin_type == 'item') {
824                                 $item =& $manager->getItem(intval($itemid), 0, 0);
825                                 $q    =  'SELECT * FROM %s WHERE inum = %d';
826                                 $res  =  sql_query(sprintf($q, $tagTable, intval($itemid)));
827                                 while ($o = mysql_fetch_object($res)) {
828                                         $temp_tags_array = preg_split('/[\n,]+/', trim($o->itags));
829                                         for ($i=0; $i < count($temp_tags_array); $i++) {
830                                                 $arr['or'][] = trim($temp_tags_array[$i]);
831                                         }
832                                 }
833                         }
834                         if ($skin_type != 'item') {
835                                 for ($i=0; $i < count($arr['and']); $i++) {
836                                         $deTag = $tplugin->_rawdecode($arr['and'][$i]);
837                                         if ($allTags[$deTag]) {
838                                                 if (empty($inumsand)) {
839                                                         $inumsand = $allTags[$deTag];
840                                                 } else {
841                                                         $inumsand = array_intersect($inumsand, $allTags[$deTag]);
842                                                 }
843                                         } else {
844                                                 $inumsand = array();
845                                         }
846                                         if (empty($inumsand)) {
847                                                 break;
848                                         }
849                                 }
850                                 if (!empty($inumsand)) {
851                                         $inumsres = array_values($inumsand);
852                                         unset($inumsand);
853                                 }
854                         }
855                         $inumsor = array();
856                         for ($i=0; $i < count($arr['or']); $i++) {
857                                 if ($skin_type == 'item') {
858                                         $deTag = $arr['or'][$i];
859                                 } else {
860                                         $deTag = $tplugin->_rawdecode($arr['or'][$i]);
861                                 }
862                                 if ($allTags[$deTag]) {
863                                         $inumsor = array_merge($inumsor, $allTags[$deTag]);
864                                 }
865                         }
866                         if ($inumsres && $inumsor) {
867                                 $inumsres = array_merge($inumsres, $inumsor);
868                                 $inumsres = array_unique($inumsres);
869                         } elseif (!$inumsres && $inumsor) {
870                                 $inumsres = array_unique($inumsor);
871                         }
872                         if ($inumsres) {
873                                 if ($skin_type == 'item') {
874                                         foreach ($inumsres as $resinum) {
875                                                 $iTags = array();
876                                                 $q     = 'SELECT itags FROM %s WHERE inum = %d';
877                                                 $q     = sprintf($q, $tagTable, intval($resinum));
878                                                 $res   = sql_query($q);
879                                                 while ($o = mysql_fetch_object($res)) {
880                                                         $resTags = preg_split("/[\n,]+/", trim($o->itags));
881                                                         for ($i=0; $i < count($resTags); $i++) {
882                                                                 $iTags[] = trim($resTags[$i]);
883                                                         }
884                                                 }
885                                                         $relatedTags        = array_intersect($arr['or'], $iTags);
886                                                         $tagCount[$resinum] = count($relatedTags);
887                                         }
888                                         asort($tagCount);
889                                         $inumsres = array();
890                                         foreach ($tagCount as $resinum => $val) {
891                                                 $relatedInums[] = intval($resinum);
892                                         }
893                                         for ($i=0; $i <= $p_amount; $i++) {
894                                                 $inumsres[$i] = array_pop($relatedInums);
895                                         }
896                                 }
897                                 $where .= ' and i.inumber IN ('. @join(',', $inumsres) . ')';
898                         } else {
899                                 $where .= ' and i.inumber=0';
900                         }
901                 }
902                 $retArray = array(
903                                                   'where'    => $where,
904                                                   'inumsres' => $inumsres
905                                                  );
906                 return $retArray;
907         }
908
909 }
910