OSDN Git Service

NP_TrimImage v2.4.0
authorhsur <hsur@1ca29b6e-896d-4ea0-84a5-967f57386b96>
Wed, 10 Dec 2008 15:19:41 +0000 (15:19 +0000)
committerhsur <hsur@1ca29b6e-896d-4ea0-84a5-967f57386b96>
Wed, 10 Dec 2008 15:19:41 +0000 (15:19 +0000)
git-svn-id: https://svn.sourceforge.jp/svnroot/nucleus-jp/plugin@716 1ca29b6e-896d-4ea0-84a5-967f57386b96

trunk/NP_TrimImage/NP_TrimImage.php

index 3b6c4fa..2784958 100644 (file)
-<?php
-// vim: tabstop=2:shiftwidth=2
-
-/**
-  * NP_TrimImage ($Revision: 1.11 $)
-  * by nakahara21 ( http://nakahara21.com/ )
-  * by hsur ( http://blog.cles.jp/np_cles/ )
-  * $Id: NP_TrimImage.php,v 1.11 2008-05-02 17:23:20 hsur Exp $
-  *
-  * Based on NP_TrimImage 1.0 by nakahara21
-  * http://nakahara21.com/?itemid=512
-*/
-
-/*
-  * Copyright (C) 2004-2006 nakahara21 All rights reserved.
-  * Copyright (C) 2006-2008 cles All rights reserved.
-  *
-  * This program is free software; you can redistribute it and/or
-  * modify it under the terms of the GNU General Public License
-  * as published by the Free Software Foundation; either version 2
-  * of the License, or (at your option) any later version.
-  * 
-  * This program is distributed in the hope that it will be useful,
-  * but WITHOUT ANY WARRANTY; without even the implied warranty of
-  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-  * GNU General Public License for more details.
-  * 
-  * You should have received a copy of the GNU General Public License
-  * along with this program; if not, write to the Free Software
-  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
-  * 
-  * In addition, as a special exception, mamio and cles gives
-  * permission to link the code of this program with those files in the PEAR
-  * library that are licensed under the PHP License (or with modified versions
-  * of those files that use the same license as those files), and distribute
-  * linked combinations including the two. You must obey the GNU General Public
-  * License in all respects for all of the code used other than those files in
-  * the PEAR library that are licensed under the PHP License. If you modify
-  * this file, you may extend this exception to your version of the file,
-  * but you are not obligated to do so. If you do not wish to do so, delete
-  * this exception statement from your version.
-*/
-
-//history
-//     0.2:    $archive, $blogid and $catid suppot ($exmode=all ready)
-//                     echos 'no images' 
-//     0.3:    add strtolower 
-//                     Initialize $this->exquery
-//     0.5:    use createGlobalItemLink
-//                     sql_table support :-P
-//     0.6:    parameter supports blogid and catid
-//     0.7:    supports templatevar
-//                     supports popup() 
-//     0.8:    supports gif
-//     0.9:    doTemplateVar calls DB data for other PreItem Plugin
-//     0.9:    change '&' to '&amp;'
-//     1.1:    NP_Paint support.
-//             Security Fix.
-//     2.0:    use phpThumb() (http://phpthumb.sourceforge.net)
-//     2.1:    update regex
-//             add alt/title attribute
-//             bug fix
-//  2.2:       support <img /> tag. 
-//                             doTemplateVar() bug fix.
-//                             Add ENT_QUOTES to htmlspecialchars()
-//                             Add ExtractImageMode
-//  2.2.1:     update phpThumb() 1.7.7 . 
-//             bug fix 
-//  2.2.2:     update enableLeftTop.patch
-//  2.3.0:  add itemcat mode
-
-define('NP_TRIMIMAGE_FORCE_PASSTHRU', true); //passthru(standard)
-//define('NP_TRIMIMAGE_FORCE_PASSTHRU', false); //redirect(advanced)
-
-define('NP_TRIMIMAGE_CACHE_MAXAGE', 86400 * 30); // 30days
-define('NP_TRIMIMAGE_PREFER_IMAGEMAGICK', false);
-
-require_once(dirname(__FILE__).'/sharedlibs/sharedlibs.php');
-require_once('phpthumb/phpthumb.functions.php');
-require_once('phpthumb/phpthumb.class.php');
-
-class NP_TrimImage extends NucleusPlugin {
-       function getName() {
-               return 'TrimImage';
-       }
-
-       function getAuthor() {
-               return 'nakahara21 + hsur';
-       }
-
-       function getURL() {
-               return 'http://blog.cles.jp/np_cles/category/31/subcatid/15';
-       }
-
-       function getVersion() {
-               return '2.3.0';
-       }
-
-       function supportsFeature($what) {
-               switch ($what) {
-                       case 'SqlTablePrefix' :
-                               return 1;
-                       default :
-                               return 0;
-               }
-       }
-
-       function getDescription() {
-               return 'Trim image in items, and embed these images.';
-       }
-               
-       function getEventList() {
-               return array ('PostAddItem', 'PostUpdateItem', 'PostDeleteItem',);
-       }
-       
-       function event_PostAddItem(& $data) {
-               $this->_clearCache();
-       }
-       function event_PostUpdateItem(& $data) {
-               $this->_clearCache();
-       }
-       function event_PostDeleteItem(& $data) {
-               $this->_clearCache();
-       }
-       function _clearCache() {
-               /*
-               $phpThumb = new phpThumb();
-               foreach ($this->phpThumbParams as $paramKey => $paramValue) {
-                       $phpThumb->setParameter($paramKey, $paramValue);
-               }
-               $phpThumb->setParameter('config_cache_maxage', 1);
-               $phpThumb->CleanUpCacheDirectory();
-               var_dump($phpThumb);
-               */
-       }
-
-       function init() {
-               global $DIR_MEDIA;
-               $this->fileex = array ('.gif', '.jpg', '.png');
-               $cacheDir = $DIR_MEDIA.'phpthumb/';
-               $cacheDir = (is_dir($cacheDir) && @ is_writable($cacheDir)) ? $cacheDir : null;
-               
-               $this->phpThumbParams = array(
-                       'config_document_root' => $DIR_MEDIA,
-                       'config_cache_directory' => $cacheDir,
-                       'config_cache_disable_warning' => true,
-                       'config_cache_directory_depth' => 0,
-                       'config_cache_maxage' => NP_TRIMIMAGE_CACHE_MAXAGE,
-                       'config_cache_maxsize' => 10 * 1024 * 1024, // 10MB
-                       'config_cache_maxfiles' => 1000,
-                       'config_cache_source_filemtime_ignore_local' => true,
-                       'config_cache_cache_default_only_suffix' => '',
-                       'config_cache_prefix' => 'phpThumb_cache',
-                       'config_cache_force_passthru' => NP_TRIMIMAGE_FORCE_PASSTHRU,
-                       'config_max_source_pixels' => 3871488, //4Mpx
-                       'config_output_format' => 'jpg',
-                       'config_disable_debug' => true,
-                       'config_prefer_imagemagick' => NP_TRIMIMAGE_PREFER_IMAGEMAGICK,
-               );
-       }
-
-       function getCategoryIDFromItemID($itemid) {
-               return quickQuery('SELECT icat as result FROM ' . sql_table('item') . ' WHERE inumber=' . intval($itemid) );
-       }
-       
-       function doSkinVar($skinType, $amount = 10, $wsize = 80, $hsize = 80, $point = 0, $random = 0, $exmode = '', $titlemode = '', $includeImg = 'true') {
-               global $CONF, $manager, $blog;
-               if ($blog) {
-                       $b = & $blog;
-               } else {
-                       $b = & $manager->getBlog($CONF['DefaultBlog']);
-               }
-               
-               if (!is_numeric($amount))
-                       $amount = 10;
-               if (!is_numeric($hsize))
-                       $hsize = 80;
-               if (!is_numeric($wsize))
-                       $wsize = 80;
-               $point = ($point == 'lefttop') ? true : false;
-               $includeImg = ( $includeImg == 'true' ) ? true : false;
-               
-               $this->exquery = '';
-
-               switch ($skinType) {
-                       case 'archive' :
-                               global $archive;
-                               $year = $month = $day = '';
-                               sscanf($archive, '%d-%d-%d', $year, $month, $day);
-                               if (empty ($day)) {
-                                       $timestamp_start = mktime(0, 0, 0, $month, 1, $year);
-                                       $timestamp_end = mktime(0, 0, 0, $month +1, 1, $year); // also works when $month==12
-                               } else {
-                                       $timestamp_start = mktime(0, 0, 0, $month, $day, $year);
-                                       $timestamp_end = mktime(0, 0, 0, $month, $day +1, $year);
-                               }
-                               $this->exquery .= ' and itime >= ' . mysqldate($timestamp_start)
-                                                                       .' and itime < ' . mysqldate($timestamp_end);
-
-                               //break;
-                       default :
-                               if ($exmode == '' || $exmode == 'itemcat') {
-                                       global $catid, $itemid;
-                                       if ($catid)
-                                               $this->exquery .= ' and icat = '.intval($catid);
-                                       elseif( $exmode == 'itemcat' && $itemid )
-                                               $this->exquery .= ' and icat = '.intval( $this->getCategoryIDFromItemID($itemid) );
-                                       else
-                                               $this->exquery .= ' and iblog = '.intval($b->getID());
-                               } elseif ($exmode == 'all') {
-                                       // nothing
-                               } else {
-                                       $spbid = $spcid = array ();
-                                       $spid_array = explode('/', $exmode);
-                                       foreach ($spid_array as $spid) {
-                                               $type = substr($spid, 0, 1);
-                                               $type_id = intval(substr($spid, 1));
-                                               if( (!$type) || (!$type_id) ) continue;
-                                               
-                                               switch($type){
-                                                       case 'b':
-                                                               $spbid[] = $type_id;
-                                                               break;
-                                                       case 'c':
-                                                               $spcid[] = $type_id;
-                                                               break;
-                                               }
-                                       }
-                                       if ($spbid){
-                                               $this->exquery .= ' and iblog IN ('.implode(',', $spbid).') ';
-                                       }
-                                       if ($spcid) {
-                                               $this->exquery .= ' and icat IN ('.implode(',', $spcid).') ';
-                                       }
-                               }
-               }
-
-               $filelist = array ();
-               $this->imglists = array ();
-               $this->imgfilename = array ();
-               $random = $random ? true : false;
-               if (!($filelist = $this->listup($amount, $random, $includeImg))) {
-                       //echo 'No images here.';
-                       return;
-               }
-
-               $amount = min($amount, count($filelist));
-               echo '<div>';
-               for ($i = 0; $i < $amount; $i ++) {
-                       $itemlink = $this->createGlobalItemLink($filelist[$i][1], ''); // why not createItemLink ?
-                       //                      $itemlink = $this->createItemLink($filelist[$i][1]);
-                       echo '<a href="'.$itemlink.'">';
-
-                       $src = '';
-                       if (!$this->phpThumbParams['config_cache_force_passthru']) {
-                               $src = $this->createImage($filelist[$i][0], $wsize, $hsize, $point, true);
-                       }
-                       if (!$src) {
-                               $src = htmlspecialchars($CONF['ActionURL'], ENT_QUOTES)
-                                               .'?action=plugin&amp;name=TrimImage&amp;type=draw'.'&amp;p='
-                                               .$filelist[$i][0].'&amp;wsize='.$wsize.'&amp;hsize='.$hsize
-                                               . ($point ? '&amp;pnt=lefttop' : '');
-                       }
-                       
-                       if($titlemode == 'item')
-                               $title = ($filelist[$i][4]) ? $filelist[$i][4] : $filelist[$i][2];
-                       else
-                               $title = ($filelist[$i][2]) ? $filelist[$i][2] : $filelist[$i][4];
-
-                       echo '<img src="'.$src.'" '                     
-                               . ( $wsize ? 'width="'.$wsize.'"'  : '' )
-                               . ( $hsize ? 'height="'.$hsize.'"' : '' )
-                               . 'alt="'.htmlspecialchars($title, ENT_QUOTES)
-                               . '" title="'.htmlspecialchars($title, ENT_QUOTES).'"/>';
-                       echo "</a>\n";
-               }
-               echo "</div>\n";
-       }
-
-       function listup($amount = 10, $random = false, $includeImg = true) {
-               global $CONF, $manager, $blog;
-               if ($blog) {
-                       $b = & $blog;
-               } else {
-                       $b = & $manager->getBlog($CONF['DefaultBlog']);
-               }
-
-               $query = 'SELECT inumber as itemid, ititle as title, ibody as body, iauthor, itime, imore as more,';
-               $query .= ' icat as catid, iclosed as closed';
-               $query .= ' FROM '.sql_table('item');
-               $query .= ' WHERE idraft = 0';
-               $query .= ' and itime <= '.mysqldate($b->getCorrectTime()); // don't show future items!
-               $query .= $this->exquery;
-               $query .= ' ORDER BY itime DESC LIMIT '.intval($amount * 10);
-
-               $res = sql_query($query);
-
-               if (!mysql_num_rows($res))
-                       return FALSE;
-
-               while ($it = mysql_fetch_object($res)) {
-                       $txt = $it->body.$it->more;
-                       if (preg_match_all("/<%(image|popup|paint)\((.*?)\)%>/s", $txt, $imgpnt))
-                               @ array_walk($imgpnt[2], array (& $this, "exarray"), array ($it->itemid, $it->iauthor, $it->title));
-
-                       if ($includeImg && preg_match_all("/<img (.*?)>/s", $txt, $imgtmp)){
-                               foreach($imgtmp[1] as $tmp){
-                                       $this->exarray($tmp, null, array($it->itemid, $it->iauthor, $it->title), true);
-                               }
-                       }
-
-                       if (count($this->imglists) >= $amount)
-                               break;
-               }
-               mysql_free_result($res);
-
-               if ($random)
-                       shuffle($this->imglists);
-               $this->imglists = array_slice($this->imglists, 0, $amount);
-               return $this->imglists;
-       }
-
-       function exarray($imginfo, $key, $params, $isImg = false) {
-               global $CONF;
-               if ($isImg){
-                       if( preg_match_all('/(src|width|height|alt|title)=\"(.*?)\"/i', $imginfo, $matches) ) {
-                               $index = 0;
-                               $param = array();
-                               foreach( $matches[1] as $type ){
-                                       $param[$type] = $matches[2][$index];                                            
-                                       $index++;
-                               }
-                               if( $param['src'] && ( strpos($param['src'], $CONF['MediaURL']) === 0 ) ){
-                                       $imginfo = substr( $param['src'], strlen($CONF['MediaURL']) )
-                                       . '|' . $param['width']
-                                       . '|' . $param['height']
-                                       . '|' . ( $param['title'] ? $param['tiltle'] : $param['alt']);
-                               }
-                       } else {
-                               return;
-                       }
-               }
-               
-               list ($url, $w, $h, $alt, $ext) = explode("|", $imginfo, 5);
-               if (!in_array(strtolower(strrchr($url, ".")), $this->fileex))
-                       return;
-               if (in_array($url, $this->imgfilename))
-                       return;
-               $this->imgfilename[] = $url;
-               if (!strstr($url, '/')) {
-                       $url = $params[1].'/'.$url;
-               }
-               $this->imglists[] = array ($url, $params[0], $alt, $ext, $params[2]);
-       }
-
-       function doTemplateVar(& $item, $wsize = 80, $hsize = 80, $point = 0, $maxAmount = 0, $titlemode = '', $includeImg = 'true') {
-               global $CONF;
-               if (!is_numeric($hsize))
-                       $hsize = 80;
-               if (!is_numeric($wsize))
-                       $wsize = 80;
-               $point = ($point == 'lefttop') ? true : false;
-               $includeImg = ( $includeImg == 'true' ) ? true : false;
-               
-               $filelist = array ();
-               $this->imglists = array ();
-               $this->imgfilename = array ();
-               //$txt = $item->body.$item->more;
-               $txt = '';
-               $q = 'SELECT ibody as body, imore as more, ititle as title FROM '.sql_table('item').' WHERE inumber='.intval($item->itemid);
-               $r = sql_query($q);
-               while ($d = mysql_fetch_object($r)) {
-                       $txt .= $d->body.$d->more;
-               }
-
-               if (preg_match_all("/<%(image|popup|paint)\((.*?)\)%>/s", $txt, $imgpnt))
-                       @ array_walk($imgpnt[2], array (& $this, "exarray"), array ($item->itemid, $item->authorid, $item->title));
-                       
-               if ($includeImg && preg_match_all("/<img (.*?)>/s", $txt, $imgtmp)){
-                       foreach($imgtmp[1] as $tmp){
-                               $this->exarray($tmp, null, array ($item->itemid, $item->authorid, $item->title), true);
-                       }
-               }
-
-               $filelist = $this->imglists;
-               if (!$maxAmount)
-                       $amount = count($filelist);
-               else
-                       $amount = min($maxAmount, count($filelist));
-
-               if (!$amount) {
-                       $img_tag = '<img src="'.htmlspecialchars($CONF['ActionURL'], ENT_QUOTES).'?action=plugin&amp;name=TrimImage';
-                       $img_tag .= '&amp;type=draw&amp;p=non&amp;wsize='.$wsize.'&amp;hsize='.$hsize.$exq;
-                       $img_tag .= '" width="'.$wsize.'" height="'.$hsize.'" />';
-                       echo $img_tag;
-               } else {
-                       for ($i = 0; $i < $amount; $i ++) {
-                               $src = '';
-                               if (!$this->phpThumbParams['config_cache_force_passthru']) {
-                                       $src = $this->createImage($filelist[$i][0], $wsize, $hsize, $point, true);
-                               }
-                               if (!$src) {
-                                       $src = htmlspecialchars($CONF['ActionURL'], ENT_QUOTES).'?action=plugin&amp;name=TrimImage&amp;type=draw'.'&amp;p='.$filelist[$i][0].'&amp;wsize='.$wsize.'&amp;hsize='.$hsize. ($point ? '&amp;pnt=lefttop' : '');
-                               }
-                               
-                               if($titlemode == 'item')
-                                       $title = ($filelist[$i][4]) ? $filelist[$i][4] : $filelist[$i][2];
-                               else
-                                       $title = ($filelist[$i][2]) ? $filelist[$i][2] : $filelist[$i][4];
-                               
-                               echo '<img src="'.$src.'" '                     
-                                       . ( $wsize ? 'width="'.$wsize.'"'  : '' )
-                                       . ( $hsize ? 'height="'.$hsize.'"' : '' )
-                                       . 'alt="'.htmlspecialchars($title, ENT_QUOTES)
-                                       . '" title="'.htmlspecialchars($title, ENT_QUOTES).'"/>';
-                               }
-               }
-       }
-
-       function doAction($type) {
-               $w = is_numeric(requestVar('wsize')) ? requestVar('wsize') : 80;
-               $h = is_numeric(requestVar('hsize')) ? requestVar('hsize') : 80;
-               $isLefttop = (requestVar('pnt') == 'lefttop') ? true : false;
-
-               switch ($type) {
-                       case 'draw' :
-                               $this->createImage(requestVar('p'), $w, $h, $isLefttop);
-                               break;
-                       default :
-                               return 'No such action';
-                               break;
-               }
-       }
-
-       function createImage($p, $w, $h, $isLefttop, $cacheCheckOnly = false) {
-               $phpThumb = new phpThumb();
-               foreach ($this->phpThumbParams as $paramKey => $paramValue) {
-                       $phpThumb->setParameter($paramKey, $paramValue);
-               }
-
-               if($h) $phpThumb->setParameter('h', intval($h));
-               if($w) $phpThumb->setParameter('w', intval($w));
-
-               if ($p == 'non') {
-                       $bghexcolor = 'FFFFFF';
-                       if ($phpThumb->gdimg_source = phpthumb_functions::ImageCreateFunction($phpThumb->w, $phpThumb->h)) {
-                               $phpThumb->setParameter('is_alpha', true);
-                               ImageAlphaBlending($phpThumb->gdimg_source, false);
-                               ImageSaveAlpha($phpThumb->gdimg_source, true);
-                               $new_background_color = phpthumb_functions::ImageHexColorAllocate($phpThumb->gdimg_source, $bghexcolor, false, 127);
-                               ImageFilledRectangle($phpThumb->gdimg_source, 0, 0, $phpThumb->w, $phpThumb->h, $new_background_color);
-                       }
-               } else {
-                       $phpThumb->setParameter('src', '/'.$p);
-                       if( $w && $h  )
-                               $phpThumb->setParameter('zc', $isLefttop ? 2 : 1);
-                       else
-                               $phpThumb->setParameter('aoe', 1);
-               }
-
-               // getCache     
-               $phpThumb->cache_filename = null;
-               $phpThumb->CalculateThumbnailDimensions();
-               $phpThumb->SetCacheFilename();
-               if (file_exists($phpThumb->cache_filename)) {
-                       $nModified = filemtime($phpThumb->cache_filename);
-                       if (time() - $nModified < NP_TRIMIMAGE_CACHE_MAXAGE) {
-                               global $CONF;
-                               preg_match('/^'.preg_quote($this->phpThumbParams['config_document_root'], '/').'(.*)$/', $phpThumb->cache_filename, $matches);
-                               $fileUrl = $CONF['MediaURL'].$matches[1];
-                               if ($cacheCheckOnly)
-                                       return $fileUrl;
-
-                               header('Last-Modified: '.gmdate('D, d M Y H:i:s', $nModified).' GMT');
-                               if (@ serverVar('HTTP_IF_MODIFIED_SINCE') 
-                                       && ($nModified == strtotime(serverVar('HTTP_IF_MODIFIED_SINCE'))) 
-                                       && @ serverVar('SERVER_PROTOCOL')
-                               ) {
-                                       header(serverVar('SERVER_PROTOCOL').' 304 Not Modified');
-                                       return true;
-                               }
-                               if ($getimagesize = @ GetImageSize($phpThumb->cache_filename)) {
-                                       header('Content-Type: '.phpthumb_functions :: ImageTypeToMIMEtype($getimagesize[2]));
-                               }
-                               elseif (eregi('\.ico$', $phpThumb->cache_filename)) {
-                                       header('Content-Type: image/x-icon');
-                               }
-                               if ($this->phpThumbParams['config_cache_force_passthru']) {
-                                       @ readfile($phpThumb->cache_filename);
-                               } else {
-                                       header('Location: '.$fileUrl);
-                               }
-                               return true;
-                       }
-               }
-               if ($cacheCheckOnly) {
-                       unset ($phpThumb);
-                       return false;
-               }
-
-               // generate
-               $phpThumb->GenerateThumbnail();
-
-               // putCache
-               if (!rand(0, 20))
-                       $phpThumb->CleanUpCacheDirectory();
-               $phpThumb->RenderToFile($phpThumb->cache_filename);
-               @ chmod($phpThumb->cache_filename, 0666);
-
-               // to browser
-               $phpThumb->OutputThumbnail();
-               unset ($phpThumb);
-               return true;
-       }
-
-       function canEdit() {
-               global $member, $manager;
-               if (!$member->isLoggedIn())
-                       return 0;
-               return $member->isAdmin();
-       }
-
-       function createGlobalItemLink($itemid, $extra = '') {
-               global $CONF, $manager;
-               $itemid = intval($itemid);
-               if ($CONF['URLMode'] == 'pathinfo') {
-                       $link = $CONF['ItemURL'].'/item/'.$itemid;
-               } else {
-                       $blogid = getBlogIDFromItemID($itemid);
-                       $b_tmp = & $manager->getBlog($blogid);
-                       $blogurl = $b_tmp->getURL();
-                       if (!$blogurl) {
-                               $blogurl = $CONF['IndexURL'];
-                       }
-                       if (substr($blogurl, -4) != '.php') {
-                               if (substr($blogurl, -1) != '/')
-                                       $blogurl .= '/';
-                               $blogurl .= 'index.php';
-                       }
-                       $link = $blogurl.'?itemid='.$itemid;
-               }
-               return addLinkParams($link, $extra);
-       }
-}
+<?php\r
+// vim: tabstop=2:shiftwidth=2\r
+\r
+/**\r
+  * NP_TrimImage ($Revision: 1.64 $)\r
+  * by nakahara21 ( http://nakahara21.com/ )\r
+  * by hsur ( http://blog.cles.jp/np_cles/ )\r
+  * $Id: NP_TrimImage.php,v 1.64 2008/12/10 15:05:51 hsur Exp $\r
+  *\r
+  * Based on NP_TrimImage 1.0 by nakahara21\r
+  * http://nakahara21.com/?itemid=512\r
+*/\r
+\r
+/*\r
+  * Copyright (C) 2004-2006 nakahara21 All rights reserved.\r
+  * Copyright (C) 2006-2008 cles All rights reserved.\r
+  *\r
+  * This program is free software; you can redistribute it and/or\r
+  * modify it under the terms of the GNU General Public License\r
+  * as published by the Free Software Foundation; either version 2\r
+  * of the License, or (at your option) any later version.\r
+  * \r
+  * This program is distributed in the hope that it will be useful,\r
+  * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r
+  * GNU General Public License for more details.\r
+  * \r
+  * You should have received a copy of the GNU General Public License\r
+  * along with this program; if not, write to the Free Software\r
+  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA\r
+  * \r
+  * In addition, as a special exception, mamio and cles gives\r
+  * permission to link the code of this program with those files in the PEAR\r
+  * library that are licensed under the PHP License (or with modified versions\r
+  * of those files that use the same license as those files), and distribute\r
+  * linked combinations including the two. You must obey the GNU General Public\r
+  * License in all respects for all of the code used other than those files in\r
+  * the PEAR library that are licensed under the PHP License. If you modify\r
+  * this file, you may extend this exception to your version of the file,\r
+  * but you are not obligated to do so. If you do not wish to do so, delete\r
+  * this exception statement from your version.\r
+*/\r
+\r
+//history\r
+//     0.2:    $archive, $blogid and $catid suppot ($exmode=all ready)\r
+//                     echos 'no images' \r
+//     0.3:    add strtolower \r
+//                     Initialize $this->exquery\r
+//     0.5:    use createGlobalItemLink\r
+//                     sql_table support :-P\r
+//     0.6:    parameter supports blogid and catid\r
+//     0.7:    supports templatevar\r
+//                     supports popup() \r
+//     0.8:    supports gif\r
+//     0.9:    doTemplateVar calls DB data for other PreItem Plugin\r
+//     0.9:    change '&' to '&amp;'\r
+//     1.1:    NP_Paint support.\r
+//             Security Fix.\r
+//     2.0:    use phpThumb() (http://phpthumb.sourceforge.net)\r
+//     2.1:    update regex\r
+//             add alt/title attribute\r
+//             bug fix\r
+//  2.2:       support <img /> tag. \r
+//                             doTemplateVar() bug fix.\r
+//                             Add ENT_QUOTES to htmlspecialchars()\r
+//                             Add ExtractImageMode\r
+//  2.2.1:     update phpThumb() 1.7.7 . \r
+//             bug fix \r
+//  2.2.2:     update enableLeftTop.patch\r
+//  2.3.0:  add itemcat mode\r
+//  2.4.0:  multi-byte filename fix\r
+//                     refactor listup(), exarray()\r
+//                     add $maxPerPage\r
+\r
+\r
+//cles::blog\r
+//define('NP_TRIMIMAGE_FORCE_PASSTHRU', true); //passthru(standard)\r
+define('NP_TRIMIMAGE_FORCE_PASSTHRU', false); //redirect(advanced)\r
+//cles::blog\r
+\r
+define('NP_TRIMIMAGE_CACHE_MAXAGE', 86400 * 30); // 30days\r
+define('NP_TRIMIMAGE_PREFER_IMAGEMAGICK', false);\r
+\r
+require_once(dirname(__FILE__).'/sharedlibs/sharedlibs.php');\r
+require_once('phpthumb/phpthumb.functions.php');\r
+require_once('phpthumb/phpthumb.class.php');\r
+\r
+class NP_TrimImage extends NucleusPlugin {\r
+       function getName() {\r
+               return 'TrimImage';\r
+       }\r
+\r
+       function getAuthor() {\r
+               return 'nakahara21 + hsur';\r
+       }\r
+\r
+       function getURL() {\r
+               return 'http://blog.cles.jp/np_cles/category/31/subcatid/15';\r
+       }\r
+\r
+       function getVersion() {\r
+               return '2.4.0';\r
+       }\r
+\r
+       function supportsFeature($what) {\r
+               switch ($what) {\r
+                       case 'SqlTablePrefix' :\r
+                               return 1;\r
+                       default :\r
+                               return 0;\r
+               }\r
+       }\r
+\r
+       function getDescription() {\r
+               return 'Trim image in items, and embed these images.';\r
+       }\r
+               \r       function getEventList() {\r
+               return array ('PostAddItem', 'PostUpdateItem', 'PostDeleteItem',);\r
+       }\r
+       \r
+       function event_PostAddItem(& $data) {\r
+               $this->_clearCache();\r
+       }\r
+       function event_PostUpdateItem(& $data) {\r
+               $this->_clearCache();\r
+       }\r
+       function event_PostDeleteItem(& $data) {\r
+               $this->_clearCache();\r
+       }\r
+       function _clearCache() {\r
+/*\r
+               $phpThumb = new phpThumb();\r
+               foreach ($this->phpThumbParams as $paramKey => $paramValue) {\r
+                       $phpThumb->setParameter($paramKey, $paramValue);\r
+               }\r
+               $phpThumb->setParameter('config_cache_maxage', 1);\r
+               $phpThumb->CleanUpCacheDirectory();\r
+               var_dump($phpThumb);\r
+*/\r
+       }\r
+\r
+       function init() {\r
+               global $DIR_MEDIA;\r
+               $this->fileex = array ('.gif', '.jpg', '.png');\r
+               $cacheDir = $DIR_MEDIA.'phpthumb/';\r
+               $cacheDir = (is_dir($cacheDir) && @ is_writable($cacheDir)) ? $cacheDir : null;\r
+               \r
+               $this->phpThumbParams = array(\r
+                       'config_document_root' => $DIR_MEDIA,\r
+                       'config_cache_directory' => $cacheDir,\r
+                       'config_cache_disable_warning' => true,\r
+                       'config_cache_directory_depth' => 0,\r
+                       'config_cache_maxage' => NP_TRIMIMAGE_CACHE_MAXAGE,\r
+                       'config_cache_maxsize' => 10 * 1024 * 1024, // 10MB\r
+                       'config_cache_maxfiles' => 1000,\r
+                       'config_cache_source_filemtime_ignore_local' => true,\r
+                       'config_cache_cache_default_only_suffix' => '',\r
+                       'config_cache_prefix' => 'phpThumb_cache',\r
+                       'config_cache_force_passthru' => NP_TRIMIMAGE_FORCE_PASSTHRU,\r
+                       'config_max_source_pixels' => 3871488, //4Mpx\r
+                       'config_output_format' => 'jpg',\r
+                       'config_disable_debug' => true,\r
+                       'config_prefer_imagemagick' => NP_TRIMIMAGE_PREFER_IMAGEMAGICK,\r
+               );\r
+       }\r
+\r
+       function getCategoryIDFromItemID($itemid) {\r
+               return quickQuery('SELECT icat as result FROM ' . sql_table('item') . ' WHERE inumber=' . intval($itemid) );\r
+       }\r
+       \r
+       function doSkinVar($skinType, $amount = 10, $wsize = 80, $hsize = 80, $point = 0, $random = 0, $exmode = '', $titlemode = '', $includeImg = 'true') {\r
+               global $CONF, $manager, $blog;\r
+               if ($blog) {\r
+                       $b = & $blog;\r
+               } else {\r
+                       $b = & $manager->getBlog($CONF['DefaultBlog']);\r
+               }\r
+               \r
+               list($amount, $maxPerItem) = explode('/', $amount, 2);\r
+               if (!is_numeric($amount))      $amount = 10;\r
+               if (!is_numeric($hsize))       $hsize = 80;\r
+               if (!is_numeric($wsize))       $wsize = 80;\r
+               if (!is_numeric($maxPerItem)) $maxPerItem = 0;\r
+               $point = ($point == 'lefttop') ? true : false;\r
+               $includeImg = ( $includeImg == 'true' ) ? true : false;\r
+               \r
+               $this->exquery = '';\r
+\r
+               switch ($skinType) {\r
+                       case 'archive' :\r
+                               global $archive;\r
+                               $year = $month = $day = '';\r
+                               sscanf($archive, '%d-%d-%d', $year, $month, $day);\r
+                               if (empty ($day)) {\r
+                                       $timestamp_start = mktime(0, 0, 0, $month, 1, $year);\r
+                                       $timestamp_end = mktime(0, 0, 0, $month +1, 1, $year); // also works when $month==12\r
+                               } else {\r
+                                       $timestamp_start = mktime(0, 0, 0, $month, $day, $year);\r
+                                       $timestamp_end = mktime(0, 0, 0, $month, $day +1, $year);\r
+                               }\r
+                               $this->exquery .= ' and itime >= ' . mysqldate($timestamp_start)\r
+                                                                       .' and itime < ' . mysqldate($timestamp_end);\r
+\r
+                               //break;\r
+                       default :\r
+                               if ($exmode == '' || $exmode == 'itemcat') {\r
+                                       global $catid, $itemid;\r
+                                       if ($catid)\r
+                                               $this->exquery .= ' and icat = '.intval($catid);\r
+                                       elseif( $exmode == 'itemcat' && $itemid )\r
+                                               $this->exquery .= ' and icat = '.intval( $this->getCategoryIDFromItemID($itemid) );\r
+                                       else\r
+                                               $this->exquery .= ' and iblog = '.intval($b->getID());\r
+                               } elseif ($exmode == 'all') {\r
+                                       // nothing\r
+                               } else {\r
+                                       $spbid = $spcid = array ();\r
+                                       $spid_array = explode('/', $exmode);\r
+                                       foreach ($spid_array as $spid) {\r
+                                               $type = substr($spid, 0, 1);\r
+                                               $type_id = intval(substr($spid, 1));\r
+                                               if( (!$type) || (!$type_id) ) continue;\r
+                                               \r
+                                               switch($type){\r
+                                                       case 'b':\r
+                                                               $spbid[] = $type_id;\r
+                                                               break;\r
+                                                       case 'c':\r
+                                                               $spcid[] = $type_id;\r
+                                                               break;\r
+                                               }\r
+                                       }\r
+                                       if ($spbid){\r
+                                               $this->exquery .= ' and iblog IN ('.implode(',', $spbid).') ';\r
+                                       }\r
+                                       if ($spcid) {\r
+                                               $this->exquery .= ' and icat IN ('.implode(',', $spcid).') ';\r
+                                       }\r
+                               }\r
+               }\r
+\r
+               $filelist = array ();\r
+               $this->imglists = array ();\r
+               $this->imgfilename = array ();\r
+               $random = $random ? true : false;\r
+               if (!($filelist = $this->_listup($amount, $random, $includeImg, $maxPerItem))) {\r
+                       //echo 'No images here.';\r
+                       return;\r
+               }\r
+\r
+               $amount = min($amount, count($filelist));\r
+               echo '<div>';\r
+               for ($i = 0; $i < $amount; $i ++) {\r
+                       $itemlink = $this->createGlobalItemLink($filelist[$i][1], '');\r
+                       echo '<a href="'.$itemlink.'">';\r
+\r
+                       $src = '';\r
+                       if (!$this->phpThumbParams['config_cache_force_passthru']) {\r
+                               $src = $this->createImage($filelist[$i][0], $wsize, $hsize, $point, true);\r
+                       }\r
+                       if (!$src) {\r
+                               $src = htmlspecialchars($CONF['ActionURL'], ENT_QUOTES)\r
+                                               .'?action=plugin&amp;name=TrimImage&amp;type=draw'.'&amp;p='\r
+                                               .urlencode($filelist[$i][0]).'&amp;wsize='.$wsize.'&amp;hsize='.$hsize\r
+                                               . ($point ? '&amp;pnt=lefttop' : '');\r
+                       }\r
+                       \r
+                       if($titlemode == 'item')\r
+                               $title = ($filelist[$i][4]) ? $filelist[$i][4] : $filelist[$i][2];\r
+                       else\r
+                               $title = ($filelist[$i][2]) ? $filelist[$i][2] : $filelist[$i][4];\r
+\r
+                       echo '<img src="'.$src.'"'                      \r
+                               . ( $wsize ? ' width="'.$wsize.'"'  : '' )\r
+                               . ( $hsize ? ' height="'.$hsize.'"' : '' )\r
+                               . ' alt="'.htmlspecialchars($title, ENT_QUOTES)\r
+                               . '" title="'.htmlspecialchars($title, ENT_QUOTES).'"/>';\r
+                       echo "</a>\n";\r
+               }\r
+               echo "</div>\n";\r
+       }\r
+\r
+       function _listup($amount = 10, $random = false, $includeImg = true, $maxPerItem = 0) {\r
+               global $CONF, $manager, $blog;\r
+               if ($blog) {\r
+                       $b = & $blog;\r
+               } else {\r
+                       $b = & $manager->getBlog($CONF['DefaultBlog']);\r
+               }\r
+\r
+               $query = 'SELECT inumber as itemid, ititle as title, ibody as body, iauthor, itime, imore as more,';\r
+               $query .= ' icat as catid, iclosed as closed';\r
+               $query .= ' FROM '.sql_table('item');\r
+               $query .= ' WHERE idraft = 0';\r
+               $query .= ' and itime <= '.mysqldate($b->getCorrectTime()); // don't show future items!\r
+               $query .= $this->exquery;\r
+               $query .= ' ORDER BY itime DESC LIMIT '.intval($amount * 10);\r
+\r
+               $res = sql_query($query);\r
+\r
+               if (!mysql_num_rows($res))\r
+                       return FALSE;\r
+\r
+               while ($it = mysql_fetch_object($res)) {\r
+                       $this->_parseItem($it, $maxPerItem, $includeImg);\r
+                       \r
+                       if (count($this->imglists) >= $amount)\r
+                               break;\r
+               }\r
+               mysql_free_result($res);\r
+\r
+               if ($random)\r
+                       shuffle($this->imglists);\r
+               $this->imglists = array_slice($this->imglists, 0, $amount);\r
+               return $this->imglists;\r
+       }\r
+       \r
+       function _parseItem(&$item, $maxPerItem = 0, $includeImg = true){\r
+               $pattern = '/<%(image|popup|paint)\((.*?)\)%>/s';\r
+               if($includeImg){\r
+                       $pattern = '/(<%(image|popup|paint)\((.*?)\)%>)|(<img (.*?)>)/s';\r
+               }\r
+               \r
+               if (preg_match_all($pattern, $item->body.$item->more, $matched)){\r
+                       if($maxPerItem){\r
+                               array_splice($matched[3], $maxPerItem); // nucleus images attribute\r
+                       }\r
+                       foreach( $matched[3] as $index => $imgAttribute ){\r
+                               if($imgAttribute){\r
+                                       $this->_parseImageTag($imgAttribute, $item, false);\r
+                               } else {\r
+                                       $this->_parseImageTag($matched[5][$index], $item, true);\r
+                               }\r
+                       }\r
+               }\r
+       }\r
+\r
+       function _parseImageTag($imginfo, &$item, $isImg) {\r
+               global $CONF;\r
+               if ($isImg){\r
+                       if( preg_match_all('/(src|width|height|alt|title)=\"(.*?)\"/i', $imginfo, $matches) ) {\r
+                               $param = array();\r
+                               foreach( $matches[1] as $index => $type ){\r
+                                       $param[$type] = $matches[2][$index];                                            \r
+                               }\r
+                               \r
+                               if( $param['src'] && ( strpos($param['src'], $CONF['MediaURL']) === 0 ) ){\r
+                                       $imginfo = substr( $param['src'], strlen($CONF['MediaURL']) )\r
+                                       . '|' . $param['width']\r
+                                       . '|' . $param['height']\r
+                                       . '|' . ( $param['title'] ? $param['tiltle'] : $param['alt']);\r
+                               }\r
+                       } else {\r
+                               return;\r
+                       }\r
+               }\r
+               \r
+               list ($url, $w, $h, $alt, $ext) = explode("|", $imginfo, 5);\r
+               if (!in_array(strtolower(strrchr($url, ".")), $this->fileex))\r
+                       return;\r
+               if (in_array($url, $this->imgfilename))\r
+                       return;\r
+               $this->imgfilename[] = $url;\r
+               if (!strstr($url, '/')) {\r
+                       $url = $item->iauthor.'/'.$url;\r
+               }\r
+               $this->imglists[] = array ($url, $item->itemid, $alt, $ext, $item->title);\r
+       }\r
+\r
+       function doTemplateVar(& $item, $wsize = 80, $hsize = 80, $point = 0, $maxAmount = 0, $titlemode = '', $includeImg = 'true') {\r
+               global $CONF;\r
+               if (!is_numeric($hsize))\r
+                       $hsize = 80;\r
+               if (!is_numeric($wsize))\r
+                       $wsize = 80;\r
+               $point = ($point == 'lefttop') ? true : false;\r
+               $includeImg = ( $includeImg == 'true' ) ? true : false;\r
+               \r
+               $filelist = array ();\r
+               $this->imglists = array ();\r
+               $this->imgfilename = array ();\r
+\r
+               $q = 'SELECT ibody as body, imore as more, ititle as title FROM '.sql_table('item').' WHERE inumber='.intval($item->itemid);\r
+               $r = sql_query($q);\r
+               $it = mysql_fetch_object($r);\r
+               $this->_parseItem($it, $maxAmount, $includeImg);\r
+\r
+               if (!$this->imglists) {\r
+                       $img_tag = '<img src="'.htmlspecialchars($CONF['ActionURL'], ENT_QUOTES).'?action=plugin&amp;name=TrimImage';\r
+                       $img_tag .= '&amp;type=draw&amp;p=non&amp;wsize='.$wsize.'&amp;hsize='.$hsize.$exq;\r
+                       $img_tag .= '" width="'.$wsize.'" height="'.$hsize.'" />';\r
+                       echo $img_tag;\r
+               } else {\r
+                       foreach($this->imglists as $img) {\r
+                               $src = '';\r
+                               if (!$this->phpThumbParams['config_cache_force_passthru']) {\r
+                                       $src = $this->createImage($img[0], $wsize, $hsize, $point, true);\r
+                               }\r
+                               if (!$src) {\r
+                                       $src = htmlspecialchars($CONF['ActionURL'], ENT_QUOTES).'?action=plugin&amp;name=TrimImage&amp;type=draw'.'&amp;p='. urlencode($img[0]) .'&amp;wsize='.$wsize.'&amp;hsize='.$hsize. ($point ? '&amp;pnt=lefttop' : '');\r
+                               }\r
+                               \r
+                               $title = ($img[2]) ? $img[2] : $img[4];\r
+                               if($titlemode == 'item')\r
+                                       $title = ($img[4]) ? $img[4] : $img[2];\r
+                               \r
+                               echo '<img src="'.$src.'" '                     \r
+                                       . ( $wsize ? 'width="'.$wsize.'"'  : '' )\r
+                                       . ( $hsize ? 'height="'.$hsize.'"' : '' )\r
+                                       . 'alt="'.htmlspecialchars($title, ENT_QUOTES)\r
+                                       . '" title="'.htmlspecialchars($title, ENT_QUOTES).'"/>';\r
+                               }\r
+               }\r
+       }\r
+\r
+       function doAction($type) {\r
+               $w = is_numeric(requestVar('wsize')) ? requestVar('wsize') : 80;\r
+               $h = is_numeric(requestVar('hsize')) ? requestVar('hsize') : 80;\r
+               $isLefttop = (requestVar('pnt') == 'lefttop') ? true : false;\r
+\r
+               switch ($type) {\r
+                       case 'draw' :\r
+                               $this->createImage(requestVar('p'), $w, $h, $isLefttop);\r
+                               break;\r
+                       default :\r
+                               return 'No such action';\r
+                               break;\r
+               }\r
+       }\r
+\r
+       function createImage($p, $w, $h, $isLefttop, $cacheCheckOnly = false) {\r
+               $phpThumb = new phpThumb();\r
+               foreach ($this->phpThumbParams as $paramKey => $paramValue) {\r
+                       $phpThumb->setParameter($paramKey, $paramValue);\r
+               }\r
+\r
+               if($h) $phpThumb->setParameter('h', intval($h));\r
+               if($w) $phpThumb->setParameter('w', intval($w));\r
+\r
+               if ($p == 'non') {\r
+                       $bghexcolor = 'FFFFFF';\r
+                       if ($phpThumb->gdimg_source = phpthumb_functions::ImageCreateFunction($phpThumb->w, $phpThumb->h)) {\r
+                               $phpThumb->setParameter('is_alpha', true);\r
+                               ImageAlphaBlending($phpThumb->gdimg_source, false);\r
+                               ImageSaveAlpha($phpThumb->gdimg_source, true);\r
+                               $new_background_color = phpthumb_functions::ImageHexColorAllocate($phpThumb->gdimg_source, $bghexcolor, false, 127);\r
+                               ImageFilledRectangle($phpThumb->gdimg_source, 0, 0, $phpThumb->w, $phpThumb->h, $new_background_color);\r
+                       }\r
+               } else {\r
+                       $phpThumb->setParameter('src', '/'.$p);\r
+                       if( $w && $h  )\r
+                               $phpThumb->setParameter('zc', $isLefttop ? 2 : 1);\r
+                       else\r
+                               $phpThumb->setParameter('aoe', 1);\r
+               }\r
+\r
+               // getCache     \r
+               $phpThumb->cache_filename = null;\r
+               $phpThumb->CalculateThumbnailDimensions();\r
+               $phpThumb->SetCacheFilename();\r
+               if (file_exists($phpThumb->cache_filename)) {\r
+                       $nModified = filemtime($phpThumb->cache_filename);\r
+                       if (time() - $nModified < NP_TRIMIMAGE_CACHE_MAXAGE) {\r
+                               global $CONF;\r
+                               preg_match('/^'.preg_quote($this->phpThumbParams['config_document_root'], '/').'(.*)$/', $phpThumb->cache_filename, $matches);\r
+                               $fileUrl = $CONF['MediaURL'].$matches[1];\r
+                               if ($cacheCheckOnly)\r
+                                       return $fileUrl;\r
+\r
+                               header('Last-Modified: '.gmdate('D, d M Y H:i:s', $nModified).' GMT');\r
+                               if (@ serverVar('HTTP_IF_MODIFIED_SINCE') \r
+                                       && ($nModified == strtotime(serverVar('HTTP_IF_MODIFIED_SINCE'))) \r
+                                       && @ serverVar('SERVER_PROTOCOL')\r
+                               ) {\r
+                                       header(serverVar('SERVER_PROTOCOL').' 304 Not Modified');\r
+                                       return true;\r
+                               }\r
+                               if ($getimagesize = @ GetImageSize($phpThumb->cache_filename)) {\r
+                                       header('Content-Type: '.phpthumb_functions :: ImageTypeToMIMEtype($getimagesize[2]));\r
+                               }\r
+                               elseif (eregi('\.ico$', $phpThumb->cache_filename)) {\r
+                                       header('Content-Type: image/x-icon');\r
+                               }\r
+                               if ($this->phpThumbParams['config_cache_force_passthru']) {\r
+                                       @ readfile($phpThumb->cache_filename);\r
+                               } else {\r
+                                       header('Location: '.$fileUrl);\r
+                               }\r
+                               return true;\r
+                       }\r
+               }\r
+               if ($cacheCheckOnly) {\r
+                       unset ($phpThumb);\r
+                       return false;\r
+               }\r
+\r
+               // generate\r
+               $phpThumb->GenerateThumbnail();\r
+\r
+               // putCache\r
+               if (!rand(0, 20))\r
+                       $phpThumb->CleanUpCacheDirectory();\r
+               $phpThumb->RenderToFile($phpThumb->cache_filename);\r
+               @ chmod($phpThumb->cache_filename, 0666);\r
+\r
+               // to browser\r
+               $phpThumb->OutputThumbnail();\r
+               unset ($phpThumb);\r
+               return true;\r
+       }\r
+\r
+       function canEdit() {\r
+               global $member, $manager;\r
+               if (!$member->isLoggedIn())\r
+                       return 0;\r
+               return $member->isAdmin();\r
+       }\r
+\r
+       function createGlobalItemLink($itemid, $extra = '') {\r
+               global $CONF, $manager;\r
+               $itemid = intval($itemid);\r
+               if ($CONF['URLMode'] == 'pathinfo') {\r
+                       $link = $CONF['ItemURL'].'/item/'.$itemid;\r
+               } else {\r
+                       $blogid = getBlogIDFromItemID($itemid);\r
+                       $b_tmp = & $manager->getBlog($blogid);\r
+                       $blogurl = $b_tmp->getURL();\r
+                       if (!$blogurl) {\r
+                               $blogurl = $CONF['IndexURL'];\r
+                       }\r
+                       if (substr($blogurl, -4) != '.php') {\r
+                               if (substr($blogurl, -1) != '/')\r
+                                       $blogurl .= '/';\r
+                               $blogurl .= 'index.php';\r
+                       }\r
+                       $link = $blogurl.'?itemid='.$itemid;\r
+               }\r
+               return addLinkParams($link, $extra);\r
+       }\r
+}\r