Example #1
0
 /**
  * This function will make directory writable.
  *
  * @param   string  path
  * @return  void
  * @throw   Kohana_Exception
  */
 public static function make_writable($path, $chmod = NULL)
 {
     try {
         $dir = new SplFileInfo($path);
         if ($dir->isFile()) {
             throw new Kohana_Exception('Could not make :path writable directory because it is regular file', array(':path' => Debug::path($path)));
         } elseif ($dir->isLink()) {
             throw new Kohana_Exception('Could not make :path writable directory because it is link', array(':path' => Debug::path($path)));
         } elseif (!$dir->isDir()) {
             // Try create directory
             Ku_Dir::make($path, $chmod);
             clearstatcache(TRUE, $path);
         }
         if (!$dir->isWritable()) {
             // Try make directory writable
             chmod($dir->getRealPath(), $chmod === NULL ? Ku_Dir::$default_dir_chmod : $chmod);
             clearstatcache(TRUE, $path);
             // Check result
             if (!$dir->isWritable()) {
                 throw new Exception('Make dir writable failed', 0);
             }
         }
     } catch (Kohana_Exception $e) {
         // Rethrow exception
         throw $e;
     } catch (Exception $e) {
         throw new Kohana_Exception('Could not make :path directory writable', array(':path' => Debug::path($path)));
     }
 }
Example #2
0
 public function action_index()
 {
     $value = $_FILES['upload'];
     if (is_array($value) and Ku_Upload::valid($value) and Ku_Upload::not_empty($value)) {
         $md5 = md5($value['name']);
         $save_path = DOCROOT . 'upload' . DIRECTORY_SEPARATOR . 'editor' . DIRECTORY_SEPARATOR . str_pad($this->site_id, 2, '0', STR_PAD_LEFT) . DIRECTORY_SEPARATOR . date('Y') . DIRECTORY_SEPARATOR . substr($md5, 0, 2) . DIRECTORY_SEPARATOR . substr($md5, 2, 2) . DIRECTORY_SEPARATOR;
         Ku_Dir::make_writable($save_path);
         $filename = Ku_File::safe_name($value['name'], TRUE, $this->max_filename_length);
         $prefix = uniqid() . '_';
         while (file_exists($save_path . $prefix . $filename)) {
             $prefix = uniqid() . '_';
         }
         $filename = Ku_Upload::save($value, $prefix . $filename, $save_path);
         $filename = 'upload' . str_replace(array(realpath(DOCROOT . 'upload'), DIRECTORY_SEPARATOR), array('', '/'), $filename);
         if (!$filename) {
             Kohana::$log->add(Log::ERROR, 'Exception occurred: :exception. [:file][:line] ', array(':file' => Debug::path(__FILE__), ':line' => __LINE__, ':exception' => 'File not saved'));
         }
         echo str_replace(array('{FUNCTION}', '{SRC}'), array(Request::initial()->query('CKEditorFuncNum'), URL::base() . $filename), $this->template);
     }
 }
Example #3
0
 * The following options are available:
 *
 * - string   base_url    path, and optionally domain, of your application   NULL
 * - string   index_file  name of your index file, usually "index.php"       index.php
 * - string   charset     internal character set used for input and output   utf-8
 * - string   cache_dir   set the internal cache directory                   APPPATH/cache
 * - integer  cache_life  lifetime, in seconds, of items cached              60
 * - boolean  errors      enable or disable error handling                   TRUE
 * - boolean  profile     enable or disable internal profiling               TRUE
 * - boolean  caching     enable or disable internal caching                 FALSE
 * - boolean  expose      set the X-Powered-By header                        FALSE
 */
Kohana::init(array('base_url' => '/', 'index_file' => FALSE, 'profile' => Kohana::$environment !== Kohana::PRODUCTION, 'caching' => Kohana::$environment === Kohana::PRODUCTION, 'cache_life' => 3600 * 24));
define('DONT_USE_CACHE', Kohana::$environment !== Kohana::PRODUCTION);
define('FTP_UPLOAD', dirname(DOCROOT) . DIRECTORY_SEPARATOR . 'ftp_upload');
Cookie::$salt = 'btmem5sgcy4ydcu0j0fss1qwu7jx2aqm7wtrh4kf5v';
Route::$preview_salt = '10c4323c4f563c54a149ddbfdfc5c8eb' . date('y-m-d F l');
/**
 * Attach the file write to logging. Multiple writers are supported.
 */
Kohana::$log->attach(new Log_File(APPPATH . 'logs'));
/**
 * Attach a file reader to config. Multiple readers are supported.
 */
Kohana::$config->attach(new Config_File());
/**
 * Enable modules. Modules are referenced by a relative or absolute path.
 */
Kohana::modules(array('auth' => MODPATH . 'auth', 'cache' => MODPATH . 'cache', 'database' => MODPATH . 'database', 'image' => MODPATH . 'image', 'orm' => MODPATH . 'orm', 'captcha' => MODPATH . 'captcha', 'acl' => MODPATH . 'wouterrr/acl', 'a1' => MODPATH . 'wouterrr/a1', 'a2' => MODPATH . 'wouterrr/a2', 'kohana-sitemap' => MODPATH . 'kohana-sitemap', 'greor-core' => MODPATH . 'greor/core', 'greor-email' => MODPATH . 'greor/email', 'greor-thumb' => MODPATH . 'greor/thumb', 'greor-orm-helper' => MODPATH . 'greor/orm-helper', 'greor-main' => MODPATH . 'greor/main'));
Ku_Dir::$default_dir_chmod = 0775;
Example #4
0
 private function write_to_file($file_name, $str)
 {
     $file_name = str_replace('/', DIRECTORY_SEPARATOR, $file_name);
     if (strpos($file_name, DOCROOT) !== 0) {
         $file_name = DOCROOT . $file_name;
     }
     $dirname = dirname($file_name);
     if (!file_exists($dirname)) {
         Ku_Dir::make($dirname);
     }
     Ku_Dir::make_writable($dirname);
     $handle = fopen($file_name, 'w');
     fwrite($handle, $str);
     fclose($handle);
 }
Example #5
0
 public function action_upload()
 {
     $this->auto_render = FALSE;
     $request = $this->request->current();
     $post = $request->post();
     $album_id = (int) Arr::get($post, 'album');
     $to_head = Arr::get($post, 'to_head') === 'true';
     $album_orm = ORM::factory('photo_Album')->where('id', '=', $album_id)->find();
     if (!$album_orm->loaded() or !$this->acl->is_allowed($this->user, $album_orm, 'edit')) {
         throw new HTTP_Exception_404();
     }
     $response = array('jsonrpc' => '2.0', 'id' => 'id');
     /* $target_dir */
     $target_dir = str_replace('/', DIRECTORY_SEPARATOR, DOCROOT . Kohana::$config->load('_photo.multiupload_dir'));
     if (!is_dir($target_dir)) {
         Ku_Dir::make($target_dir, 0755);
     }
     if (is_dir($target_dir) && ($dir = opendir($target_dir))) {
         while (($file = readdir($dir)) !== false) {
             $tmp_file_path = $target_dir . DIRECTORY_SEPARATOR . $file;
             /* Remove temp file if it is older than the max age and is not the current file */
             if (preg_match('/\\.part$/', $file) and filemtime($tmp_file_path) < time() - $this->max_file_age and $tmp_file_path != "{$file_path}.part") {
                 @unlink($tmp_file_path);
             }
         }
         closedir($dir);
     } else {
         $response['error'] = array('code' => 100, 'message' => 'Failed to open temp directory.');
         $this->json_send($response);
         return;
     }
     /* $chunk, $chunks */
     $chunk = Arr::get($post, 'chunk', 0);
     $chunks = Arr::get($post, 'chunks', 0);
     /* $file_name */
     $file_name = Arr::get($post, 'name', '');
     $file_name = preg_replace('/[^\\w\\._]+/', '_', $file_name);
     $ext = UTF8::strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
     if (!preg_match('/^jpe?g$/s', $ext)) {
         $response['error'] = array('code' => 105, 'message' => 'Invalid file type.');
         $this->json_send($response);
         return;
     }
     if ($chunks < 2 and file_exists($target_dir . DIRECTORY_SEPARATOR . $file_name)) {
         $ext = strrpos($file_name, '.');
         $file_name_a = substr($file_name, 0, $ext);
         $file_name_b = substr($file_name, $ext);
         $count = 1;
         while (file_exists($target_dir . DIRECTORY_SEPARATOR . $file_name_a . '_' . $count . $file_name_b)) {
             $count++;
         }
         $file_name = $file_name_a . '_' . $count . $file_name_b;
     }
     /* $file_path */
     $file_path = $target_dir . DIRECTORY_SEPARATOR . $file_name;
     $_h = $request->headers('http-content-type');
     $content_type = empty($_h) ? '' : $_h;
     $_h = $request->headers('content-type');
     $content_type = empty($_h) ? $content_type : $_h;
     /* Handle non multipart uploads older WebKit versions didn't support multipart in HTML5 */
     if (strpos($content_type, "multipart") !== false) {
         if (isset($_FILES['file']['tmp_name']) && is_uploaded_file($_FILES['file']['tmp_name'])) {
             if ($out = fopen("{$file_path}.part", $chunk == 0 ? "wb" : "ab")) {
                 if ($in = fopen($_FILES['file']['tmp_name'], "rb")) {
                     while ($buff = fread($in, 4096)) {
                         fwrite($out, $buff);
                     }
                 } else {
                     $response['error'] = array('code' => 101, 'message' => 'Failed to open input stream.');
                     $this->json_send($response);
                     return;
                 }
                 fclose($in);
                 fclose($out);
                 @unlink($_FILES['file']['tmp_name']);
             } else {
                 $response['error'] = array('code' => 102, 'message' => 'Failed to open output stream.');
                 $this->json_send($response);
                 return;
             }
         } else {
             $response['error'] = array('code' => 103, 'message' => 'Failed to move uploaded file.');
             $this->json_send($response);
             return;
         }
     } else {
         if ($out = fopen("{$file_path}.part", $chunk == 0 ? "wb" : "ab")) {
             if ($in = fopen("php://input", "rb")) {
                 while ($buff = fread($in, 4096)) {
                     fwrite($out, $buff);
                 }
             } else {
                 $response['error'] = array('code' => 101, 'message' => 'Failed to open input stream.');
                 $this->json_send($response);
                 return;
             }
             fclose($in);
             fclose($out);
         } else {
             $response['error'] = array('code' => 102, 'message' => 'Failed to open output stream.');
             $this->json_send($response);
             return;
         }
     }
     /* Check if file has been uploaded */
     if (!$chunks or $chunk == $chunks - 1) {
         /* Strip the temp .part suffix off */
         rename("{$file_path}.part", $file_path);
         $save_result = $this->save_file($file_path, $album_orm, $to_head);
         if ($save_result !== TRUE) {
             $response['error'] = array('code' => 104, 'message' => $save_result);
             $this->json_send($response);
             return;
         }
     }
     /* Return JSON-RPC response */
     $response['result'] = NULL;
     $this->json_send($response);
 }
Example #6
0
 /**
  * Generate thumb.
  *
  * @param   string   group of thumb config
  * @param   string   path to source file
  * @param   boolean  force process even if the thumb file already exists
  * @return  string|boolean Realpath of created file or FALSE if failure
  */
 public static function create($group, $file, $force = FALSE)
 {
     if (empty($file)) {
         return FALSE;
     }
     $file = str_replace('/', DIRECTORY_SEPARATOR, $file);
     if (strpos($file, '.' . DIRECTORY_SEPARATOR) !== FALSE) {
         // File is invalid: "./" and "../" not allowed
         return FALSE;
     }
     self::$_config === NULL and self::_load_config();
     self::$_route_tpl === NULL and self::_set_route_tpl();
     $config = self::$_config->get($group);
     if (!$config) {
         return FALSE;
     }
     // Detect realpath for base group path
     $path = rtrim(Arr::get($config, 'path', ''), '/');
     if (!$path) {
         $realpath = realpath(self::$docroot);
     } else {
         if ($realpath = realpath($path)) {
             // Path finded
         } else {
             if ($realpath = realpath(self::$docroot . $path)) {
                 // Path finded
             } else {
                 if ($realpath = realpath(DOCROOT . $path)) {
                     // Path finded
                 } else {
                     // Path not exists
                     return FALSE;
                 }
             }
         }
     }
     $path = $realpath;
     // Detect realpath for src file
     if ($realpath = realpath($file)) {
         // File finded
     } else {
         if ($realpath = realpath(self::$docroot . $file)) {
             // File finded
         } else {
             if ($realpath = realpath(DOCROOT . $file)) {
                 // File finded
             } else {
                 // File not found
                 return FALSE;
             }
         }
     }
     $file = $realpath;
     if (is_file($file) and is_dir($path) and strpos($file, $path) === 0) {
         $thumb_path = self::$docroot . sprintf(self::$_route_tpl, $group, str_replace($path, '', $file));
         $thumb_path = str_replace('/', DIRECTORY_SEPARATOR, $thumb_path);
         if ($force === TRUE or !is_file($thumb_path)) {
             $img = Image::factory($file);
             foreach ($config as $key => $params) {
                 switch ($key) {
                     case 'resize':
                         $params += array('width' => NULL, 'height' => NULL, 'master' => NULL);
                         $img->resize($params['width'], $params['height'], $params['master']);
                         break;
                     case 'crop':
                         $params += array('width' => NULL, 'height' => NULL, 'offset_x' => NULL, 'offset_y' => NULL);
                         $img->crop($params['width'], $params['height'], $params['offset_x'], $params['offset_y']);
                         break;
                     default:
                         if (is_callable($key)) {
                             call_user_func($key, $img, $params);
                         }
                 }
             }
             // Make directory writable
             Ku_Dir::make_writable(dirname($thumb_path));
             // Save file by requsted path
             if ($img->save($thumb_path, Arr::get($config, 'quality', 90)) === FALSE) {
                 return FALSE;
             }
         }
         return realpath($thumb_path);
     }
     return FALSE;
 }
Example #7
0
 /**
  * Saves file and returns file name
  *
  * @param   string   $field  File field name
  * @param   mixed    $value  File field value
  * @return  string
  */
 public function file_save($field, $value)
 {
     $this->_check_file_field($field);
     $config = $this->_file_fields[$field];
     $base_path = $this->file_path($field, '');
     // Upload a file?
     if (is_array($value) and Ku_Upload::valid($value) and Ku_Upload::not_empty($value)) {
         // Get path to save file
         $sub_dir = $this->file_sub_dir($field, $value['name']);
         $save_path = $base_path . $sub_dir;
         // Create and make directory writable
         Ku_Dir::make_writable($base_path . $sub_dir, $config['dir_chmod']);
         // Generate safe filename
         $filename = Ku_File::safe_name($value['name'], TRUE, $config['max_filename_length']);
         $prefix = '';
         if ($config['force_unique_prefix']) {
             // Make unique filename
             $prefix = uniqid() . '_';
         }
         while (file_exists($save_path . $prefix . $filename)) {
             // Make unique filename to prevent override existing file
             $prefix = uniqid() . '_';
         }
         $filename = $prefix . $filename;
         $filename = Ku_Upload::save($value, $filename, $save_path, $config['file_chmod']);
         if (!$filename) {
             throw new Kohana_Exception('File :filename not saved to a field :field of model :model', array(':filename' => $value['name'], ':field' => $field, ':model' => $this->_orm->object_name()));
         }
     } elseif (is_string($value) and is_file($value)) {
         // Test allowed source directories
         if (!is_array($config['allowed_src_dirs']) or empty($config['allowed_src_dirs'])) {
             throw new Kohana_Exception('Field :field of model :model has no allowed source directories', array(':field' => $field, ':model' => $this->_orm->object_name()));
         }
         foreach ($config['allowed_src_dirs'] as $dir) {
             if (strpos(realpath($value), realpath($dir)) === 0) {
                 // Allowed directory found
                 $allowed_dir = $dir;
                 break;
             }
         }
         if (!isset($allowed_dir)) {
             // Allowed directory not found
             throw new Kohana_Exception('File :filename is not in the allowed source directory of field :field of model :model', array(':filename' => Debug::path($value), ':field' => $field, ':model' => $this->_orm->object_name()));
         }
         // Get path to save file
         $sub_dir = $this->file_sub_dir($field, basename($value));
         $save_path = $base_path . $sub_dir;
         // Create and make directory writable
         Ku_Dir::make_writable($base_path . $sub_dir, Arr::get($config, 'dir_chmod'));
         // Generate safe filename
         $filename = Ku_File::safe_name(basename($value), TRUE, $config['max_filename_length']);
         if ($value !== $save_path . $filename) {
             $prefix = '';
             if ($config['force_unique_prefix']) {
                 // Make unique filename
                 $prefix = uniqid() . '_';
             }
             while (file_exists($save_path . $prefix . $filename)) {
                 // Make unique filename to prevent override existing file
                 $prefix = uniqid() . '_';
             }
             $filename = $prefix . $filename;
             if (rename($value, $save_path . $filename)) {
                 $filename = $save_path . $filename;
             } else {
                 // File not saved
                 throw new Kohana_Exception('File :filename not saved to a field :field of model :model', array(':filename' => Debug::path($value), ':field' => $field, ':model' => $this->_orm->object_name()));
             }
         } else {
             $filename = $value;
         }
     } else {
         throw new Kohana_Exception('Invalid file parameter :value for field :field of model :model', array(':value' => (string) $value, ':field' => $field, ':model' => $this->_orm->object_name()));
     }
     if (!empty($filename)) {
         try {
             chmod($filename, $config['file_chmod']);
         } catch (Exception $e) {
             Kohana::$log->add(Log::ERROR, 'Exception occurred: :exception. [:file][:line] ', array(':file' => Debug::path(__FILE__), ':line' => __LINE__, ':exception' => $e->getMessage()));
         }
         // Save only path relative base path
         $save_value = $sub_dir . basename($filename);
         $save_value = ltrim(str_replace('\\', '/', $save_value), '/');
         // Assign ORM field
         $this->_orm->{$field} = $save_value;
     }
     return $filename;
 }
Example #8
0
<?php

defined('SYSPATH') or die('No direct script access.');
$config = array('file' => array('driver' => 'file', 'cache_dir' => APPPATH . 'cache/other', 'default_expire' => 3600, 'ignore_on_delete' => array('.gitignore', '.git', '.svn')), 'struct' => array('driver' => 'file', 'cache_dir' => APPPATH . 'cache/struct', 'default_expire' => 3600, 'ignore_on_delete' => array('.gitignore', '.git', '.svn')), 'page-helper' => array('driver' => 'file', 'cache_dir' => APPPATH . 'cache/page-helper', 'default_expire' => 3600, 'ignore_on_delete' => array('.gitignore', '.git', '.svn')), 'sites' => array('driver' => 'file', 'cache_dir' => APPPATH . 'cache/sites', 'default_expire' => 3600, 'ignore_on_delete' => array('.gitignore', '.git', '.svn')), 'properties' => array('driver' => 'file', 'cache_dir' => APPPATH . 'cache/properties', 'default_expire' => 3600, 'ignore_on_delete' => array('.gitignore', '.git', '.svn')));
foreach ($config as $item) {
    if ($item['driver'] === 'file' and !is_dir($item['cache_dir'])) {
        Ku_Dir::make_writable($item['cache_dir']);
    }
}
return $config;