OSDN Git Service

FIX: NP_MediaUtilsをNucleus 3.65/PHP5.4/MySQL5.5で動作するよう修正
authorsakamocchi <o-takashi@sakamocchi.jp>
Sat, 20 Oct 2012 06:09:53 +0000 (15:09 +0900)
committersakamocchi <o-takashi@sakamocchi.jp>
Sat, 20 Oct 2012 06:09:53 +0000 (15:09 +0900)
NP_MediaUtils/NP_MediaUtils.php
NP_MediaUtils/mediautils/MediaUtils.php
NP_MediaUtils/mediautils/Medium.php

index a59d12a..f6be266 100755 (executable)
@@ -1,8 +1,8 @@
 <?php\r
 /**\r
  * MediaUtils plugin for Nucleus CMS\r
- * Version 0.9.6 (1.0 RC2) for PHP5\r
- * Written By Mocchi, Apr. 04, 2011\r
+ * Version 1.0.0 for PHP5\r
+ * Written By Mocchi, Oct. 20, 2011\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
  * of the License, or (at your option) any later version.\r
  */\r
 \r
-class NP_MediaUtils extends NucleusPlugin {\r
+class NP_MediaUtils extends NucleusPlugin\r
+{\r
        public function getName()                       { return 'MediaUtils'; }\r
        public function getAuthor()             { return 'Mocchi'; }\r
        public function getURL()                        { return 'http://japan.nucleuscms.org/wiki/plugins:mediautils'; }\r
-       public function getVersion()            { return '0.9.6 (1.0 RC2)'; }\r
+       public function getVersion()            { return '1.0.0'; }\r
        public function getDescription()        { return 'Load MediaUtils, static function set for media management. Another function of this plugin is keeping Cookies for identifying weblog id.'; }\r
        \r
        public function getMinNucleusVersion()  { return 340; }\r
        public function supportsFeature($feature) { return in_array ($feature, array ('SqlTablePrefix', 'SqlApi')); }\r
        public function getEventList()  { return array('PostAuthentication', 'InitSkinParse', 'PreSendContentType'); }\r
        \r
-       /*\r
-        * NOTICE: Event drivened method can get a correct blogid in initSkinParse.\r
-        */\r
-       public function event_PostAuthentication($data) {\r
+       public function init()\r
+       {\r
+               if ( !class_exists('MediaUtils', FALSE) )\r
+               {\r
+                       include ($this->getDirectory() . 'MediaUtils.php');\r
+               }\r
+               \r
+               return;\r
+       }\r
+       \r
+       public function event_PostAuthentication(&$data)\r
+       {\r
                global $CONF;\r
                static $blogid = 0;\r
                static $blogs = array();\r
                \r
-               if (!class_exists('MediaUtils', FALSE)) {\r
-                       include ($this->getDirectory() . 'MediaUtils.php');\r
-               }\r
-               \r
                MediaUtils::$lib_path = preg_replace('#/*$#', '', $this->getDirectory());\r
                MediaUtils::$prefix = (boolean) $CONF['MediaPrefix'];\r
                MediaUtils::$maxsize = (integer) $CONF['MaxUploadSize'];\r
                \r
                $suffixes = explode(',', $CONF['AllowedTypes']);\r
-               foreach ($suffixes as $suffix) {\r
+               foreach ( $suffixes as $suffix )\r
+               {\r
                        $suffix = trim($suffix);\r
                        if(!in_array($suffix, MediaUtils::$suffixes)) {\r
                                MediaUtils::$suffixes[] = strtolower($suffix);\r
@@ -46,77 +52,74 @@ class NP_MediaUtils extends NucleusPlugin {
                }\r
                \r
                $result = sql_query('SELECT bnumber, bshortname FROM ' . sql_table('blog') . ';');\r
-               while(FALSE !== ($row = sql_fetch_assoc($result))) {\r
+               while ( FALSE !== ($row = sql_fetch_assoc($result)) )\r
+               {\r
                        $blogs[$row['bnumber']] = $row['bshortname'];\r
                }\r
-               MediaUtils::$blogs = $blogs;\r
+               MediaUtils::$blogs =& $blogs;\r
                \r
-               if (array_key_exists('blogid', $_GET)) {\r
+               if ( array_key_exists('blogid', $_GET) )\r
+               {\r
                        $blogid = (integer) $_GET['blogid'];\r
-               } else if (array_key_exists('blogid', $_POST)) {\r
+               }\r
+               else if ( array_key_exists('blogid', $_POST) )\r
+               {\r
                        $blogid = (integer) $_POST['blogid'];\r
-               } else if (array_key_exists('itemid', $_GET)) {\r
+               }\r
+               else if ( array_key_exists('itemid', $_GET) && function_exists('getBlogIDFromItemID') )\r
+               {\r
                        $blogid = (integer) getBlogIDFromItemID((integer) $_GET['itemid']);\r
-               } else if (array_key_exists('itemid', $_POST)) {\r
-                       $blogid = (integer) getBlogIDFromItemID((integer) $_POST['itemid']);\r
-               } else if (array_key_exists(MediaUtils::$cookiename, $_COOKIE)) {\r
-                       $blogid = (integer) $_COOKIE['blogid'];\r
                }\r
-               \r
-               if (!$blogid || !array_key_exists($blogid, $blogs)) {\r
-                       self::setCookie(-1);\r
-                       return;\r
+               else if ( array_key_exists('itemid', $_POST) && function_exists('getBlogIDFromItemID') )\r
+               {\r
+                       $blogid = (integer) getBlogIDFromItemID((integer) $_POST['itemid']);\r
                }\r
-               \r
-               MediaUtils::$blogid = (integer) $blogid;\r
-               MediaUtils::$bshortname = (string) $blogs[$blogid];\r
-               self::setCookie(1);\r
-               \r
-               return;\r
-       }\r
-       \r
-       public function event_PreSendContentType($data) {\r
-               global $blog, $blogid;\r
-               if (MediaUtils::$blogid) {\r
-                       return;\r
+               else if ( array_key_exists(MediaUtils::$cookiename, $_COOKIE) )\r
+               {\r
+                       $blogid = (integer) $_COOKIE['blogid'];\r
                }\r
-               \r
-               if (!$blogid && !$blog) {\r
-                       self::setCookie(-1);\r
+               else\r
+               {\r
                        return;\r
                }\r
                \r
-               if (!$blogid) {\r
-                       MediaUtils::$blogid = $blog->getID();\r
-               } else {\r
-                       MediaUtils::$blogid = $blogid;\r
-               }\r
-               \r
-               if (!$blog) {\r
-                       MediaUtils::$bshortname = $manager->getBlog(MediaUtils::$blogid)->getShortName();\r
-               } else {\r
-                       MediaUtils::$bshortname = $blog->getShortName();\r
-               }\r
+               MediaUtils::$blogid =& $blogid;\r
+               MediaUtils::$bshortname =& MediaUtils::$blogs[MediaUtils::$blogid];\r
                \r
-               self::setCookie(1);\r
                return;\r
        }\r
        \r
-       public function event_InitSkinParse($data) {\r
+       /*\r
+        * When index.php is directly called, there is no $blogid at first.\r
+        * $blogid is set when selector() is called after globalfunctions is included (selectBlog() is optional).\r
+        * In this case, plugin can finally get correct $blogid in InitSkinParse event.\r
+        * (Nucleus CMS 3.64, Apr. 06, 2011)\r
+        */\r
+       public function event_InitSkinParse(&$data)\r
+       {\r
                global $blogid;\r
-               if (MediaUtils::$blogid != $blogid) {\r
+               if ( MediaUtils::$blogid == 0 )\r
+               {\r
                        MediaUtils::$blogid = $blogid;\r
                        MediaUtils::$bshortname = MediaUtils::$blogs[MediaUtils::$blogid];\r
-                       self::setCookie(1);\r
                }\r
                return;\r
        }\r
        \r
-       private function setCookie($factor) {\r
+       public function event_PreSendContentType($data)\r
+       {\r
                global $CONF;\r
-               $factor = (integer) $factor;\r
                \r
-               setcookie($CONF['CookiePrefix'] . MediaUtils::$cookiename, MediaUtils::$blogid, time()+180*$factor, $CONF['CookiePath'], $CONF['CookieDomain'], $CONF['CookieSecure']);\r
+               /* delete my cookie */\r
+               if ( MediaUtils::$blogid == 0 )\r
+               {\r
+                       setcookie($CONF['CookiePrefix'] . MediaUtils::$cookiename, MediaUtils::$blogid, -1, $CONF['CookiePath'], $CONF['CookieDomain'], $CONF['CookieSecure']);\r
+               }\r
+               /* set my cookie */\r
+               else\r
+               {\r
+                       setcookie($CONF['CookiePrefix'] . MediaUtils::$cookiename, MediaUtils::$blogid, time()+180, $CONF['CookiePath'], $CONF['CookieDomain'], $CONF['CookieSecure']);\r
+               }       \r
                return;\r
        }\r
 }\r
index 0766c01..054d205 100755 (executable)
@@ -1,8 +1,8 @@
 <?php
 /**
  * MediaUtils plugin for Nucleus CMS
- * Version 0.9.6 (1.0 RC2) for PHP5
- * Written By Mocchi, Apr. 04, 2011
+ * Version 1.0.0 for PHP5
+ * Written By Mocchi, Oct. 20, 2011
  * 
  * This program is free software; you can redistribute it and/or
  * modify it under the terms of the GNU General Public License
  * of the License, or (at your option) any later version.
  */
 
-class MediaUtils {
+class MediaUtils
+{
        static public $lib_path = '';
        
        static public $cookiename = 'blogid';
-       static public $blogid = FALSE;
+       static public $blogid = 0;
        static public $blogs = array();
        static public $bshortname = '';
        
@@ -23,167 +24,199 @@ class MediaUtils {
        static public $suffixes = array();
        
        static public $algorism = 'md5';
-       static public $image_mime
-               = array('image/jpeg'    => '.jpeg',
-                               'image/png'     => '.png',
-                       /*      'image/bmp'     => '.bmp', not implemented*/
-                               'image/gif'     => '.gif');
+       static public $image_mime = array(
+               'image/jpeg'    => '.jpeg',
+               'image/png'             => '.png',
+               'image/gif'             => '.gif');
        
-/**
- * error and exit
- * @access     Public  MediaUtils::error
- * @param      String  $message                Error message
- * @exit       
- */
-       static public function error ($message) {
-               (string)        $message;
+       /**
+        * error and exit
+        * @access      Public  MediaUtils::error
+        * @param       String  $message        Error message
+        * @exit        
+        */
+       static public function error($message)
+       {
+               $message = (string) $message;
                header("HTTP/1.0 404 Not Found");
                exit($message);
        }
        
-/**
- * send resampled image via HTTP
- * @access     Public  MediaUtils::responseResampledImage
- * @param      Object  $medium         Medium Object
- * @exit       
- */
-       static public function responseResampledImage ($medium) {
-               if (!class_exists('Medium', FALSE)) {
+       /**
+        * send resampled image via HTTP
+        * @access      Public  MediaUtils::responseResampledImage
+        * @param       Object  $medium         Medium Object
+        * @exit        
+        */
+       static public function responseResampledImage($medium)
+       {
+               if ( !class_exists('Medium', FALSE) )
+               {
                        include(self::$lib_path . '/Medium.php');
                }
                
-               if ('Medium' !== get_class($medium)) {
-                       self::error ('NP_MediaUtils: Fail to generate resampled image');
+               if ( 'Medium' !== get_class($medium) )
+               {
+                       self::error('NP_MediaUtils: Fail to generate resampled image');
                        return;
                }
                
-               if (FALSE === ($resampledimage = $medium->getResampledBinary(self::$image_mime))) {
-                       unset ($resampledimage);
-                       self::error ('NP_MediaUtils: Fail to generate resampled image');
+               if ( FALSE === ($resampledimage = $medium->getResampledBinary(self::$image_mime)) )
+               {
+                       unset($resampledimage);
+                       self::error('NP_MediaUtils: Fail to generate resampled image');
                        return;
                }
                
-               header ('Content-type: ' . $medium->mime);
+               header('Content-type: ' . $medium->mime);
                echo $resampledimage;
-               unset ($resampledimage);
+               unset($resampledimage);
                exit;
        }
        
-/**
- * Store resampled image binary to filesystem as file
- * @access     Public  MediaUtils::storeResampledImage
- * @param      String  $root                   root directory for media
- * @param      String  $path                   Relative path from root to destination
- * @param      Object  $medium         Medium Object
- * @return     Boolean TRUE/FALSE
- */
-       static public function storeResampledImage ($root, $target, $medium) {
-               if (!class_exists('Medium', FALSE)) {
+       /**
+        * Store resampled image binary to filesystem as file
+        * @access      Public  MediaUtils::storeResampledImage
+        * @param       String  $root                   root directory for media
+        * @param       String  $path                   Relative path from root to destination
+        * @param       Object  $medium         Medium Object
+        * @return      Boolean TRUE/FALSE
+        */
+       static public function storeResampledImage($root, $target, $medium)
+       {
+               if ( !class_exists('Medium', FALSE) )
+               {
                        include(self::$lib_path . '/Medium.php');
                }
                
-               if ('Medium' !== get_class($medium)) {
+               if ( 'Medium' !== get_class($medium) )
+               {
                        return FALSE;
                }
                
-               if (FALSE === ($resampledimage = $medium->getResampledBinary(self::$image_mime))) {
-                       unset ($resampledimage);
+               if ( FALSE === ($resampledimage = $medium->getResampledBinary(self::$image_mime)) )
+               {
+                       unset($resampledimage);
                        return FALSE;
                }
                
-               if (FALSE === ($handle = @fopen ("{$root}/{$target}", 'w'))) {
-                       unset ($resampledimage);
+               if ( FALSE === ($handle = @fopen("{$root}/{$target}", 'w')) )
+               {
+                       unset($resampledimage);
                        return FALSE;
                }
                
-               if (@fwrite ($handle, $resampledimage) === FALSE) {
-                       unset ($resampledimage);
-                       @unlink ("{$root}/{$target}");
+               if ( @fwrite($handle, $resampledimage) === FALSE )
+               {
+                       unset($resampledimage);
+                       @unlink("{$root}/{$target}");
                        return FALSE;
                }
                
-               unset ($resampledimage);
-               fclose ($handle);
+               unset($resampledimage);
+               fclose($handle);
                
-               if (@chmod ("{$root}/{$target}", 0744) === FALSE) {
-                       @unlink ("{$root}/{$target}");
+               if ( @chmod("{$root}/{$target}", 0744) === FALSE )
+               {
+                       @unlink("{$root}/{$target}");
                        return FALSE;
                }
                
                return TRUE;
        }
        
-/**
- * Check the path as directory and writable
- * @access     Public  MediaUtils::checkDir
- * @param      String  Fullpath
- * @return     Boolean TRUE/FALSE
- */
-       static public function checkDir ($fullpath) {
+       /**
+        * Check the path as directory and writable
+        * @access      Public  MediaUtils::checkDir
+        * @param       String  Fullpath
+        * @return      Boolean TRUE/FALSE
+        */
+       static public function checkDir($fullpath)
+       {
                $fullpath = (string) $fullpath;
                
-               if (file_exists ($fullpath)) {
-                       if (is_dir ($fullpath) && is_writable ($fullpath)) {
+               if ( file_exists($fullpath) )
+               {
+                       if ( is_dir($fullpath) && is_writable($fullpath) )
+                       {
                                return TRUE;
-                       } else {
+                       }
+                       else
+                       {
                                return FALSE;
                        }
-               } else {
-                       if (!@mkdir ($fullpath, 0777)) {
+               }
+               else
+               {
+                       if ( !@mkdir($fullpath, 0777) )
+                       {
                                return FALSE;
-                       } else {
+                       }
+                       else
+                       {
                                return TRUE;
                        }
                }
        }
        
-/**
- * Return file data list
- * @access     Public  MediaUtils::getMediaList
- * @param      String  $root           path to media root directory
- * @param      Boolean $hidden show hidden files (.*) or not
- * @param      Boolean $recursive      follow recursively or not
- * @param      Boolean $prefix analyze its prefix or not
- * @param      String  $suffix limit by suffix
- * @param      String  $path           relative path from root to destination
- * @return     Array           Array(Medium)
- */
-       static public function getMediaList ($root, $hidden=TRUE, $recursive=TRUE, $suffix='', $path='', $media=array()) {
+       /**
+        * Return file data list
+        * @access      Public  MediaUtils::getMediaList
+        * @param       String  $root           path to media root directory
+        * @param       Boolean $hidden show hidden files (.*) or not
+        * @param       Boolean $recursive      follow recursively or not
+        * @param       Boolean $prefix analyze its prefix or not
+        * @param       String  $suffix limit by suffix
+        * @param       String  $path           relative path from root to destination
+        * @return      Array   Array(Medium)
+        */
+       static public function getMediaList($root, $hidden=TRUE, $recursive=TRUE, $suffix='', $path='', $media=array())
+       {
                $root           = (string)      $root;
-               $hidden = (boolean) $hidden;
+               $hidden         = (boolean) $hidden;
                $recursive      = (boolean) $recursive;
-               $suffix = (string) $suffix;
+               $suffix         = (string) $suffix;
                $path           = (string) $path;
-               $media  = (array) $media;
+               $media          = (array) $media;
                
-               if (!class_exists('Medium', FALSE)) {
+               if ( !class_exists('Medium', FALSE) )
+               {
                        include(self::$lib_path . '/Medium.php');
                }
                
                $root = rtrim($root, '/');
-               if(!$root || !file_exists($root)) {
+               if ( !$root || !file_exists($root) )
+               {
                        return FALSE;
                }
                
                $fullpath = $root;
-               if ($path) {
+               if ( $path )
+               {
                        $path = trim($path, '/');
                        $fullpath = "{$root}/{$path}";
                }
                
-               if (FALSE === ($handle = @opendir($fullpath))) {
+               if ( FALSE === ($handle = @opendir($fullpath)) )
+               {
                        return FALSE;
                }
-               while(FALSE !== ($filename = readdir($handle))) {
-                       if ($filename !== '.' && $filename !== '..') {
-                               if (($hidden && preg_match("#^\.#", $filename))
-                                || ($suffix && !preg_match("#\.$suffix$#", $filename))) {
+               while ( FALSE !== ($filename = readdir($handle)) )
+               {
+                       if ( $filename !== '.' && $filename !== '..' )
+                       {
+                               if ( ($hidden && preg_match("#^\.#", $filename))
+                                  || ($suffix && !preg_match("#\.$suffix$#", $filename)) )
+                               {
                                        continue;
                                }
                                
-                               if($recursive && filetype("{$fullpath}/{$filename}") === "dir") {
+                               if ( $recursive && filetype("{$fullpath}/{$filename}") === "dir" )
+                               {
                                        $media = self::getMediaList($root, $hidden, $recursive, $suffix, trim("{$path}/{$filename}", '/'), $media);
-                               } else if ($path !== '' && filetype("{$fullpath}/{$filename}") === "file") {
+                               }
+                               else if ( $path !== '' && filetype("{$fullpath}/{$filename}") === "file" )
+                               {
                                        $media[] = new Medium($root, trim("{$path}/{$filename}", '/'), self::$prefix);
                                        continue;
                                }
@@ -193,102 +226,130 @@ class MediaUtils {
                return $media;
        }
        
-/*
- * Purge directory
* @access     Public  MediaUtils::purgeDir
* @param      String  $root           path to media root directory
* @param      String  $path           relative path from root to destination
- * @return     Array/FALSE             $logs           
- * 
- */
-       static public function purgeDir($root, $path='', $logs=array()) {
+       /**
       * Purge directory
       * @access      Public  MediaUtils::purgeDir
       * @param       String  $root           path to media root directory
       * @param       String  $path           relative path from root to destination
+        * @return      Mixed   $logs
+        */
+       static public function purgeDir($root, $path='', $logs=array())
+       {
                $root   = (string) $root;
                $path   = (string) $path;
                $logs   = (array) $logs;
                
                $root = rtrim($root, '/');
-               if(!$root || !file_exists($root)) {
+               if ( !$root || !file_exists($root) )
+               {
                        return FALSE;
                }
                
                $fullpath = $root;
-               if ($path) {
+               if ( $path )
+               {
                        $path = trim($path, '/');
                        $fullpath = "{$root}/{$path}";
                }
                
-               if (FALSE === ($handle = @opendir($fullpath))) {
+               if ( FALSE === ($handle = @opendir($fullpath)) )
+               {
                        return FALSE;
                }
-               while(FALSE !== ($filename = readdir($handle))) {
-                       if ($filename !== '.' && $filename !== '..') {
-                               if(filetype("{$fullpath}/{$filename}") === "dir") {
+               while ( FALSE !== ($filename = readdir($handle)) )
+               {
+                       if ( $filename !== '.' && $filename !== '..' )
+                       {
+                               if ( filetype("{$fullpath}/{$filename}") === "dir" )
+                               {
                                        $logs = self::purgeDir($root, "{$path}/{$filename}", $logs);
-                               } else {
-                                       if(!unlink("{$root}/{$path}/{$filename}")) {
+                               }
+                               else
+                               {
+                                       if ( !unlink("{$root}/{$path}/{$filename}") )
+                                       {
                                                $logs[] = "Exists: {$path}/{$filename}";
-                                       } else {
+                                       }
+                                       else
+                                       {
                                                $logs[] = "Removed: {$path}/{$filename}";
                                        }
                                        continue;
                                }
                        }
                }
-               if(!rmdir("{$root}/{$path}")) {
+               if ( !rmdir("{$root}/{$path}") )
+               {
                        $logs[] = "Exists: {$path}";
-               } else {
+               }
+               else
+               {
                        $logs[] = "Removed: {$path}";
                }
                return $logs;
        }
-
-/*
- * Return path list under root
* @access     Public  MediaUtils::getPathList
* @param      String  $root           full path to root directory
* @param      String  $path           certain path to search
* @param      Boolean $private        use private directory or not
* @param      Boolean $recursize      search recursively or not
* @param      Boolean $hidden do not list up the directory started with piriod or not
* @return     String  $name   
- * 
- */
-       static public function getPathList($root, $path='', $private=FALSE, $hidden=TRUE, $recursive=TRUE) {
+       
+       /**
       * Return path list under root
       * @access      Public  MediaUtils::getPathList
       * @param       String  $root           full path to root directory
       * @param       String  $path           certain path to search
       * @param       Boolean $private        use private directory or not
       * @param       Boolean $recursize      search recursively or not
       * @param       Boolean $hidden         do not list up the directory started with piriod or not
       * @return      String  $name   
+        */
+       static public function getPathList($root, $path='', $private=FALSE, $hidden=TRUE, $recursive=TRUE)
+       {
                $root           = (string) $root;
                $path           = (string) $path;
-               $hidden = (boolean) $hidden;
-               $recursive = (boolean) $recursive;
+               $hidden         = (boolean) $hidden;
+               $recursive      = (boolean) $recursive;
                
                $paths=array();
                
                $root = rtrim($root, '/');
-               if(!$root || !file_exists($root)) {
+               if ( !$root || !file_exists($root) )
+               {
                        return FALSE;
                }
                
                $fullpath = $root;
-               if ($path) {
+               if ( $path )
+               {
                        $path = trim($path, '/');
                        $fullpath = "{$root}/{$path}";
                }
                
-               if (FALSE === ($handle = @opendir($fullpath))) {
+               if ( FALSE === ($handle = @opendir($fullpath)) )
+               {
                        return FALSE;
                }
-               while (FALSE !== ($filename = readdir($handle))) {
-                       if (in_array($filename, array('.', '..', 'CVS'))) {
+               while ( FALSE !== ($filename = readdir($handle)) )
+               {
+                       if ( in_array($filename, array('.', '..', 'CVS')) )
+                       {
                                continue;
-                       } else if (is_file("{$fullpath}/{$filename}")) {
+                       }
+                       else if ( is_file("{$fullpath}/{$filename}") )
+                       {
                                continue;
-                       } else if ($hidden && preg_match('#^\.#', $filename)) {
+                       }
+                       else if ($hidden && preg_match('#^\.#', $filename) )
+                       {
                                continue;
-                       } else if ($private && is_numeric($filename) && $path==''&& $private != $filename) {
+                       }
+                       else if ( $private && is_numeric($filename) && $path==''&& $private != $filename )
+                       {
                                continue;
                        }
                        
-                       if (!$path) {
+                       if ( !$path )
+                       {
                                $relpath = $filename;
-                       } else {
+                       }
+                       else
+                       {
                                $relpath = "{$path}/{$filename}";
                        }
                        
@@ -296,8 +357,10 @@ class MediaUtils {
                }
                closedir($handle);
                
-               if ($path=='' && $private) {
-                       if (!array_key_exists($private, $paths)) {
+               if ( $path=='' && $private )
+               {
+                       if ( !array_key_exists($private, $paths) )
+                       {
                                $paths[$private] = array('root'=>$root , 'path'=>$private, 'files'=>0, 'dirs'=>0);
                        }
                        $paths[$private]['label'] = 'PRIVATE';
@@ -307,61 +370,76 @@ class MediaUtils {
                return $paths;
        }
        
-/*
- * Return path data
- * @access     Public  MediaUtils::getPathData
- * @param      String  $root                   full path to root directory
- * @param      String  $path                   relative path from root to target directory
- * @param      Boolean $private                use private directory or not
- * @param      Boolean $hidden         do not list up the directory started with piriod or not
- * @param      Boolean $recursive      search recursively or not
- * @return     Array           Array('root', 'parent', 'name', 'files', 'dirs', 'label')
- */
-       static public function getPathData($root, $path, $private=FALSE, $hidden=TRUE, $recursive=FALSE, $paths=array()) {
+       /**
+        * Return path data
+        * @access      Public  MediaUtils::getPathData
+        * @param       String  $root           full path to root directory
+        * @param       String  $path           relative path from root to target directory
+        * @param       Boolean $private        use private directory or not
+        * @param       Boolean $hidden         do not list up the directory started with piriod or not
+        * @param       Boolean $recursive      search recursively or not
+        * @return      Array   Array('root', 'parent', 'name', 'files', 'dirs', 'label')
+        */
+       static public function getPathData($root, $path, $private=FALSE, $hidden=TRUE, $recursive=FALSE, $paths=array())
+       {
                $root           = (string)      $root;
                $path           = (string)      $path;
                $private        = (boolean) $private;
-               $hidden = (boolean) $hidden;
-               $recursive = (boolean) $recursive;
+               $hidden         = (boolean) $hidden;
+               $recursive      = (boolean) $recursive;
                
                $cnt_files = 0;
                $cnt_dirs = 0;
                
                $root = rtrim($root, '/');
-               if(!$root || !file_exists($root)) {
+               if ( !$root || !file_exists($root) )
+               {
                        return FALSE;
                }
                
                $fullpath = $root;
-               if ($path) {
+               if ( $path )
+               {
                        $path = trim($path, '/');
                        $fullpath = "{$root}/{$path}";
                }
                
-               if (FALSE === ($handle = @opendir($fullpath))) {
+               if ( FALSE === ($handle = @opendir($fullpath)) )
+               {
                        return FALSE;
                }
-               while (FALSE !== ($filename = readdir($handle))) {
-                       if (in_array($filename, array('.', '..', 'CVS'))) {
+               while ( FALSE !== ($filename = readdir($handle)) )
+               {
+                       if ( in_array($filename, array('.', '..', 'CVS')) )
+                       {
                                continue;
-                       } else if (!is_dir("{$fullpath}/{$filename}")) {
-                               if (!$hidden || !preg_match('#^\.#', $filename)){
+                       }
+                       else if ( !is_dir("{$fullpath}/{$filename}") )
+                       {
+                               if ( !$hidden || !preg_match('#^\.#', $filename) )
+                               {
                                        $cnt_files++;
                                }
                                continue;
-                       } else if ($hidden && preg_match('#^\.#', $filename)) {
+                       }
+                       else if ( $hidden && preg_match('#^\.#', $filename) )
+                       {
                                continue;
                        }
                        
                        $cnt_dirs++;
                        
-                       if (!$path) {
+                       if ( !$path )
+                       {
                                $relpath = $filename;
-                       } else {
+                       }
+                       else
+                       {
                                $relpath = "{$path}/{$filename}";
                        }
                        
-                       if ($recursive) {
+                       if ( $recursive )
+                       {
                                $paths = self::getPathData($root, $relpath, $private, $recursive, $hidden, $paths);
                        }
                }
@@ -372,44 +450,52 @@ class MediaUtils {
                $paths[$path]['name'] = basename($fullpath);
                $paths[$path]['files'] = $cnt_files;
                $paths[$path]['dirs'] = $cnt_dirs;
-               if ($private) {
+               if ( $private )
+               {
                        $paths[$path]['label'] = preg_replace("#^$private#", 'PRIVATE', $path);
-               } else {
+               }
+               else
+               {
                        $paths[$path]['label'] = $path;
                }
                
                return $paths;
        }
        
-/*
- * Store uploaded binary to filesystem
- * @access     Public  MediaUtils::uploadMedium
- * @param      String  $root                   path to edia root directory
- * @param      String  $path                   relative path from root to target directory
- * @param      Array           $medium         uploaded binary data.
- * @param      String/FALSE    $overwrite      overwrite or not if the file already exists
- * @param      Object  $manager                Nucleus Manager Object
- * @return     String  $log                    Return '' if success, others is error messages
- * 
- */
-       static public function uploadMedium ($root, $path, &$temp, $overwrite='', &$manager='') {
-               $root    = (string) $root;
-               $path    = (string) $path;
-               $temp = (array) $temp;
-               $overwrite = (string) $overwrite;
-               $manager = (object) $manager;
+       /**
+        * Store uploaded binary to filesystem
+        * @access      Public  MediaUtils::uploadMedium
+        * @param       String  $root           path to edia root directory
+        * @param       String  $path           relative path from root to target directory
+        * @param       Array   $medium         uploaded binary data.
+        * @param       Mixed   $overwrite      overwrite or not if the file already exists
+        * @param       Object  $manager        Nucleus Manager Object
+        * @return      String  $log            Return '' if success, others is error messages
+        */
+       static public function uploadMedium($root, $path, &$temp, $overwrite='', &$manager='')
+       {
+               global $manager;
+               
+               $root           = (string) $root;
+               $path           = (string) $path;
+               $temp           = (array) $temp;
+               $overwrite      = (string) $overwrite;
+               $manager        = (object) $manager;
                
                /**
                 * $temp should be derived from $_FILE
                 */
-               foreach(array('name', 'tmp_name','size', 'error') as $key) {
-                       if (!array_key_exists($key, $temp)) {
+               foreach ( array('name', 'tmp_name','size', 'error') as $key )
+               {
+                       if ( !array_key_exists($key, $temp) )
+                       {
                                return 'NP_MediaUtils: Miss uploaded file.';
                        }
                }
                
                $root = rtrim($root, '/');
-               if(!$root || !file_exists($root) || !$path) {
+               if ( !$root || !file_exists($root) || !$path )
+               {
                        return 'NP_MediaUtils: Destination is invalid.';
                }
                $path = trim($path, '/');
@@ -417,7 +503,8 @@ class MediaUtils {
                /**
                 * see http://www.php.net/manual/en/features.file-upload.errors.php
                 */
-               switch ($temp['error']) {
+               switch ( $temp['error'] )
+               {
                        case UPLOAD_ERR_OK:
                                break;
                        case UPLOAD_ERR_INI_SIZE:
@@ -432,48 +519,68 @@ class MediaUtils {
                                return 'NP_MediaUtils: Request rejected';
                }
                
-               if (preg_match ("#(\\\\|/|\\n)#", $temp['name'])) {
+               if ( preg_match ("#(\\\\|/|\\n)#", $temp['name']) )
+               {
                        return 'NP_MediaUtils: invalid filename';
                }
                
-               if ($temp['size'] > self::$maxsize) {
+               if ( $temp['size'] > self::$maxsize )
+               {
                        return 'NP_MediaUtils: Binary is too big';
                }
                
-               if (!empty(self::$suffixes) && is_array(self::$suffixes)) {
+               if ( !empty(self::$suffixes) && is_array(self::$suffixes) )
+               {
                        preg_match("#\.(.+)$#", $temp['name'], $match);
                        $suffix = strtolower($match[1]);
-                       if (!in_array($suffix, self::$suffixes)) {
+                       if ( !in_array($suffix, self::$suffixes) )
+                       {
                                return 'NP_MediaUtils: Forbidden file suffix';
                        }
                }
                
-               if (!self::checkDir("{$root}/{$path}")) {
+               if ( !self::checkDir("{$root}/{$path}") )
+               {
                        return 'NP_MediaUtils: Invalid target directory';
                }
                
-               if ($overwrite) {
-                       if (!preg_match("#\.($suffix)$#", strtolower($overwrite), $match)) {
+               if ( $overwrite )
+               {
+                       if ( !preg_match("#\.($suffix)$#", strtolower($overwrite), $match) )
+                       {
                                return 'NP_MediaUtils: suffix is not the same.';
                        }
                        $temp['name'] = $overwrite;
-               } else if (self::$prefix) {
-                       $temp['name'] = strftime ("%Y%m%d-", time ()) . $temp['name'];
+               }
+               else if ( self::$prefix )
+               {
+                       $temp['name'] = strftime("%Y%m%d-", time()) . $temp['name'];
                }
                
-               if (!$overwrite && file_exists("{$root}/{$path}/{$temp['name']}")) {
+               if ( !$overwrite && file_exists("{$root}/{$path}/{$temp['name']}") )
+               {
                        return 'NP_MediaUtils: The same filename already exists in this target directory.';
                }
                
-               if ($manager) {
-                       $manager->notify('PreMediaUpload',array('collection' => &$path, 'uploadfile' => $temp['tmp_name'], 'filename' => $temp['name']));
+               if ( $manager )
+               {
+                       $params = array(
+                               'collection'    => &$path,
+                               'uploadfile'    =>  $temp['tmp_name'],
+                               'filename'              =>  $temp['name']
+                       );
+                       $manager->notify('PreMediaUpload', $params);
                }
                
-               if (is_uploaded_file($temp['tmp_name'])) {
-                       if (!@move_uploaded_file($temp['tmp_name'], "{$root}/{$path}/{$temp['name']}")) {
+               if ( is_uploaded_file($temp['tmp_name']) )
+               {
+                       if ( !@move_uploaded_file($temp['tmp_name'], "{$root}/{$path}/{$temp['name']}") )
+                       {
                                        return 'NP_MediaUtils: Fail to move uploaded binary to file sytem.';
                        }
-               } else if (!copy($temp['tmp_name'], "{$root}/{$path}/{$temp['name']}")) {
+               }
+               else if ( !copy($temp['tmp_name'], "{$root}/{$path}/{$temp['name']}") )
+               {
                                return 'NP_MediaUtils: Fail to copy uploaded binary to file sytem.';
                }
                
@@ -481,7 +588,8 @@ class MediaUtils {
                @chmod("{$root}/{$path}/{$temp['name']}", 0644);
                umask($oldumask);
                
-               if ($manager) {
+               if ( $manager )
+               {
                        $manager->notify('PostMediaUpload',array('collection' => $path, 'mediadir' => $root, 'filename' => $temp['name']));
                }
                
index 2ab43f0..a2f4b6e 100755 (executable)
@@ -1,8 +1,8 @@
 <?php
 /**
  * MediaUtils plugin for Nucleus CMS
- * Version 0.9.6 (1.0 RC2) for PHP5
- * Written By Mocchi, Apr. 04, 2011
+ * Version 1.0.0 for PHP5
+ * Written By Mocchi, Oct. 20, 2011
  * 
  * This program is free software; you can redistribute it and/or
  * modify it under the terms of the GNU General Public License
@@ -10,7 +10,8 @@
  * of the License, or (at your option) any later version.
  */
 
-class Medium  {
+class Medium
+{
        public $root = '';
        public $path = '';
        public $name = '';
@@ -25,28 +26,31 @@ class Medium  {
        public $resampledwidth = 0;
        public $resampledheight = 0;
        
-/**
- * Return MEDIUM Object
- * @access     Public  $this->__construnct
- * @param      String  $root
- * @param      String  $relativepath
- * @param      Boolean $prefix
- * @return     Object/FALSE
- */
-       public function __construct ($root, $relativepath, $prefix) {
+       /**
+        * construct instance of Medium
+        * @access      Public  $this->__construnct
+        * @param       String  $root
+        * @param       String  $relativepath
+        * @param       Boolean $prefix
+        * @return      Object/FALSE
+        */
+       public function __construct($root, $relativepath, $prefix)
+       {
                static $fullpath;
                static $info;
                
-               if ($root == '' || $relativepath == '') {
+               if ( $root == '' || $relativepath == '' )
+               {
                        return FALSE;
                }
                
                $root = preg_replace('#/*$#', '', $root);
-               if ($root == '' || $relativepath == ''
+               if ( $root == '' || $relativepath == ''
                 || !file_exists($root)
                 || FALSE === ($fullpath = realpath(rtrim($root . '/' . ltrim($relativepath, '/'), '/')))
                 || strpos($fullpath, $root) !== 0
-                || !file_exists($fullpath)) {
+                || !file_exists($fullpath) )
+                {
                        return FALSE;
                }
                
@@ -54,34 +58,41 @@ class Medium  {
                $this->name = basename($fullpath);
                $this->path = str_replace(array($this->root.'/', '/'.$this->name), '', $fullpath);
                
-               if ($this->path === $this->name) {
+               if ( $this->path === $this->name )
+               {
                        $this->path = ''; 
                }
                
-               if (FALSE === ($info = @getimagesize ($fullpath))) {
+               if ( FALSE === ($info = @getimagesize($fullpath)) )
+               {
                        $this->mime = 'application/octet-stream';
                        $this->width = 0;
                        $this->height = 0;
-               } else {
+               }
+               else
+               {
                        $this->mime = $info['mime'];
                        $this->width = $info[0];
                        $this->height = $info[1];
                }
                
                set_time_limit(ini_get('max_execution_time'));
-               if (defined('FILEINFO_MIME_TYPE')
-                && function_exists ('finfo_open')
-                && (FALSE !== ($info = finfo_open(FILEINFO_MIME_TYPE)))) {
+               if ( defined('FILEINFO_MIME_TYPE')
+                && function_exists('finfo_open')
+                && (FALSE !== ($info = finfo_open(FILEINFO_MIME_TYPE))) )
+                {
                        $this->mime = finfo_file($info, $fullpath);
                }
                
                $this->update = date("Y/m/d", @filemtime($fullpath));
                $this->size = ceil(filesize($fullpath) / 1000);
                
-               if (preg_match('#^(.*)\.([a-zA-Z0-9]{2,})$#', $this->name, $info) === 1) {
+               if ( preg_match('#^(.*)\.([a-zA-Z0-9]{2,})$#', $this->name, $info) === 1 )
+               {
                        $this->filename = $info[1];
                        $this->suffix = $info[2];
-                       if ($prefix && preg_match('#^([0-9]{8})\-(.*)$#', $this->filename, $info) == 1 ) {
+                       if ( $prefix && preg_match('#^([0-9]{8})\-(.*)$#', $this->filename, $info) == 1 )
+                       {
                                $this->prefix = preg_replace('#^([0-9]{4})([0-9]{2})([0-9]{2})$#', '$1/$2/$3', $info[1]);
                                $this->filename = $info[2];
                        }
@@ -90,30 +101,41 @@ class Medium  {
                return $this;
        }
        
-       public function __destruct () {
+       public function __destruct()
+       {
                return;
        }
        
-/**
- * Set resampled size
- * @access     Public  $this->setResampledSize
- * @param      Integer $maxwidth
- * @param      Integer $maxheight
- * @return     Boolean
- */
-       public function setResampledSize($maxwidth=0, $maxheight=0) {
-               if (($maxwidth == 0) && ($maxheight == 0)) {
+       /**
+        * Set resampled size
+        * @access      Public  $this->setResampledSize
+        * @param       Integer $maxwidth
+        * @param       Integer $maxheight
+        * @return      Boolean
+        */
+       public function setResampledSize($maxwidth=0, $maxheight=0)
+       {
+               if ( ($maxwidth == 0) && ($maxheight == 0) )
+               {
                        return FALSE;
-               } else if ($this->width == 0 || $this->height  == 0) {
+               }
+               else if ( $this->width == 0 || $this->height  == 0 )
+               {
                        return FALSE;
-               } else if ($this->width < $maxwidth && $this->height < $maxheight) {
+               }
+               else if ( $this->width < $maxwidth && $this->height < $maxheight )
+               {
                        $this->resampledwidth = $this->width;
                        $this->resampledheight = $this->height;
-               } else if ($maxheight == 0 || $this->width > $this->height) {
-                       $this->resampledheight = intval ($this->height * $maxwidth / $this->width);
+               }
+               else if ( $maxheight == 0 || $this->width > $this->height )
+               {
+                       $this->resampledheight = intval($this->height * $maxwidth / $this->width);
                        $this->resampledwidth = $maxwidth;
-               } else if ($maxwidth == 0 || $this->width <= $this->height) {
-                       $this->resampledwidth = intval ($this->width * $maxheight / $this->height);
+               }
+               else if ( $maxwidth == 0 || $this->width <= $this->height )
+               {
+                       $this->resampledwidth = intval($this->width * $maxheight / $this->height);
                        $this->resampledheight = $maxheight;
                }
                return TRUE;
@@ -126,104 +148,130 @@ class Medium  {
  * @param      Integer $maxheight
  * @return     Boolean
  */
-       public function getResampledBinary ($image_mime) {
+       public function getResampledBinary($image_mime)
+       {
                static $gdinfo;
                static $original;
                static $resampledimage;
                
                $gdinfo = gd_info();
                
-               if ($this->path !== '') {
+               if ( $this->path !== '' )
+               {
                        $fullpath = "{$this->root}/{$this->path}/{$this->name}";
-               } else {
+               }
+               else
+               {
                        $fullpath = "{$this->root}/{$this->name}";
                }
-               if (!file_exists($fullpath)) {
+               if ( !file_exists($fullpath) )
+               {
                        return FALSE;
                }
                
-               if (!array_key_exists($this->mime, $image_mime)
+               if ( !array_key_exists($this->mime, $image_mime)
                 || $this->width == 0
                 || $this->height == 0
                 || $this->resampledwidth == 0
-                || $this->resampledheight == 0) {
-                       return FALSE;
+                || $this->resampledheight == 0 )
+               {
+                       return FALSE;
                }
                
                // check current available memory
                $memorymax = trim(ini_get("memory_limit"));
-               switch (strtolower ($memorymax[strlen($memorymax)-1])) {
-                case 'g':
-                $memorymax *= 1024;
-                case 'm':
-                $memorymax *= 1024;
-                case 'k':
-                $memorymax *= 1024;
+               switch ( strtolower($memorymax[strlen($memorymax)-1]) )
+               {
+                       case 'g':
+                               $memorymax *= 1024;
+                       case 'm':
+                               $memorymax *= 1024;
+                       case 'k':
+                               $memorymax *= 1024;
                }
                
                // this code is based on analyze if gd.c in php source code
                // if you can read C/C++, please check these elements and notify us if you have some ideas
-               if ((memory_get_usage() + ($this->resampledwidth * $this->resampledheight * 5 + $this->resampledheight * 24 + 10000) + ($this->width * $this->height * 5 + $this->height * 24 + 10000)) > $memorymax) {
+               if ( (memory_get_usage() + ($this->resampledwidth * $this->resampledheight * 5 + $this->resampledheight * 24 + 10000) + ($this->width * $this->height * 5 + $this->height * 24 + 10000)) > $memorymax )
+               {
                        return FALSE;
                }
                
-               switch ($this->mime) {
+               switch ( $this->mime )
+               {
                        case 'image/gif':
-                               if (!$gdinfo['GIF Read Support'] && !$gdinfo['GIF Create Support']) {
+                               if ( !$gdinfo['GIF Read Support'] && !$gdinfo['GIF Create Support'] )
+                               {
                                        return FALSE;
                                }
-                               $original = imagecreatefromgif ($fullpath);
+                               $function = 'imagecreatefromgif';
                                break;
                        case 'image/jpeg':
-                               if ((array_key_exists('JPEG Support', $gdinfo) && !$gdinfo['JPEG Support']) && (array_key_exists('JPG Support', $gdinfo) && $gdinfo['JPG Support'])) {
+                               if ( (array_key_exists('JPEG Support', $gdinfo) && !$gdinfo['JPEG Support'])
+                                && (array_key_exists('JPG Support', $gdinfo) && $gdinfo['JPG Support']) )
+                                {
                                        return FALSE;
                                }
-                               $original = imagecreatefromjpeg ($fullpath);
+                               $function = 'imagecreatefromjpeg';
                                break;
                        case 'image/png':
-                               if (!$gdinfo['PNG Support']) {
+                               if ( !$gdinfo['PNG Support'] )
+                               {
                                        return FALSE;
                                }
-                               $original = imagecreatefrompng ($fullpath);
+                               $function = 'imagecreatefrompng';
                                break;
                        default:
                                return FALSE;
                }
                
-               $resampledimage = imagecreatetruecolor ($this->resampledwidth, $this->resampledheight);
+               if ( !is_callable($function) )
+               {
+                       return FALSE;
+               }
                
-               if (!$resampledimage) {
+               if ( FALSE === ($original = call_user_func_array($function,array(&$fullpath))) )
+               {
                        return FALSE;
                }
                
-               set_time_limit(ini_get('max_execution_time'));
-               if (!ImageCopyResampled ($resampledimage, $original, 0, 0, 0, 0, $this->resampledwidth, $this->resampledheight, $this->width, $this->height)) {
+               if ( FALSE === ($resampledimage = imagecreatetruecolor($this->resampledwidth, $this->resampledheight)) )
+               {
                        return FALSE;
                }
                
-               imagedestroy ($original);
+               @set_time_limit(ini_get('max_execution_time'));
+               if ( !ImageCopyResampled($resampledimage, $original, 0, 0, 0, 0, $this->resampledwidth, $this->resampledheight, $this->width, $this->height) )
+               {
+                       return FALSE;
+               }
+               
+               imagedestroy($original);
                
                ob_start();
                
-               switch ($this->mime) {
-                case 'image/gif':
-                 imagegif ($resampledimage);
-                 break;
-                case 'image/jpeg':
-                 imagejpeg ($resampledimage);
-                 break;
-                case 'image/png':
-                 imagepng ($resampledimage);
-                 break;
-                default:
+               switch ( $this->mime )
+               {
+                       case 'image/gif':
+                               imagegif($resampledimage);
+                               break;
+                       case 'image/jpeg':
+                               imagejpeg($resampledimage);
+                               break;
+                       case 'image/png':
+                               imagepng($resampledimage);
+                               break;
+                       default:
+                               return FALSE;
                }
                
-               imagedestroy ($resampledimage);
+               imagedestroy($resampledimage);
                
                return ob_get_clean();
        }
        
-       public function getHashedName($algorism) {
+       public function getHashedName($algorism)
+       {
                return (string) hash($algorism, "{$this->path}/{$this->name}", FALSE);
        }
 }