public function testGetExt() { $this->assertEquals('.php', File::getExt('index.php')); $this->assertEquals('.jpeg', File::getExt('1.jpeg')); $this->assertEquals('.dat', File::getExt('data.dat')); $this->assertEquals('.binary', File::getExt('.binary')); $this->assertEquals(false, File::getExt('binary')); $this->assertEquals('.php', File::getExt('Store/Session1.php')); }
/** * Multiple upload files * * @property array $data - array of Request::files() items * @param string $path * @param boolean $formUpload - optional, default true * @return mixed - uploaded files Info / false on error */ public function start(array $files, $path, $formUpload = true) { $uploadedFiles = array(); foreach ($files as $k => $item) { if ($item['error']) { continue; } $item['name'] = str_replace(' ', '_', $item['name']); $item['name'] = strtolower(preg_replace("/[^A-Za-z0-9_\\-\\.]/i", '', $item['name'])); $item['ext'] = File::getExt($item['name']); $item['title'] = str_replace($item['ext'], '', $item['name']); $type = $this->_identifyType($item['ext']); if (!$type) { continue; } switch ($type) { case 'image': if (!isset($this->_uploaders['image'])) { $this->_uploaders['image'] = new Upload_Image($this->_config['image']); } $file = $this->_uploaders['image']->upload($item, $path, $formUpload); if (!empty($file)) { $file['type'] = $type; $file['title'] = $item['title']; if (isset($item['old_name'])) { $file['old_name'] = $item['old_name']; } else { $file['old_name'] = $item['name']; } $uploadedFiles[] = $file; } break; case 'audio': case 'video': case 'file': if (!isset($this->_uploaders['file'])) { $this->_uploaders['file'] = new Upload_File($this->_config[$type]); } $file = $this->_uploaders['file']->upload($item, $path, $formUpload); if (!empty($file)) { $file['type'] = $type; $file['title'] = $item['title']; if (isset($item['old_name'])) { $file['old_name'] = $item['old_name']; } else { $file['old_name'] = $item['name']; } $uploadedFiles[] = $file; } break; } } return $uploadedFiles; }
public function getSuitable(File $file) { $ext = $file->getExt(); $suitables = array(); foreach ($GLOBALS['phorkie']['tools'] as $class => $arSetup) { if (array_search($ext, $class::$arSupportedExtensions) !== false) { $suitables[] = new Tool_Info($class); } } return $suitables; }
/** * Upload file * * @param array $data- $_FILES array item * @param boolean $formUpload - optional, default true * @return array / false on error */ public function upload(array $data, $path, $formUpload = true) { if ($data['error']) { return false; } if (isset($this->_config['max_file_size']) && $this->_config['max_file_size']) { if ($data['size'] > $this->_config['max_file_size']) { return false; } } $result = array('name' => '', 'path' => '', 'size' => '', 'type' => ''); $name = str_replace(' ', '_', $data['name']); $name = preg_replace("/[^A-Za-z0-9_\\-\\.]/i", '', $name); $ext = File::getExt($name); if (!in_array($ext, $this->_config['extensions'])) { return false; } $namePart = str_replace($ext, '', $name); if (isset($this->_config['rewrite']) && $this->_config['rewrite']) { if (file_exists($path . $namePart . $ext)) { @unlink($path . $namePart . $ext); } } if (file_exists($path . $namePart . $ext)) { $namePart .= '-0'; } while (file_exists($path . $namePart . $ext)) { $parts = explode('-', $namePart); $el = array_pop($parts); $el = intval($el); $el++; $parts[] = $el; $namePart = implode('-', $parts); } $result['name'] = $namePart . $ext; $result['path'] = $path . $namePart . $ext; $result['ext'] = $ext; if ($formUpload) { if (!@move_uploaded_file($data['tmp_name'], $result['path'])) { return false; } } else { if (!@copy($data['tmp_name'], $result['path'])) { return false; } } $result['size'] = $data['size']; $result['type'] = $data['type']; @chmod($result['path'], 0644); return $result; }
public function getLanguageOptions(File $file = null) { $html = '<option value="_auto_">* automatic *</option>'; $fileExt = null; if ($file !== null) { $fileExt = $file->getExt(); } foreach ($GLOBALS['phorkie']['languages'] as $ext => $arLang) { if (isset($arLang['show']) && !$arLang['show']) { continue; } $html .= sprintf('<option value="%s"%s>%s</option>', $ext, $fileExt == $ext ? ' selected="selected"' : '', $arLang['title']) . "\n"; } return $html; }
/** * Static file serving (CSS, JS, images, etc.) * * @uses Request::param * @uses Request::uri * @uses Kohana::find_file * @uses Response::check_cache * @uses Response::body * @uses Response::headers * @uses Response::status * @uses File::mime_by_ext * @uses File::getExt * @uses Config::get * @uses Log::add * @uses System::mkdir */ public function action_serve() { // Get file theme from the request $theme = $this->request->param('theme', FALSE); // Get the file path from the request $file = $this->request->param('file'); // Find the file extension $ext = File::getExt($file); // Remove the extension from the filename $file = substr($file, 0, -(strlen($ext) + 1)); if ($file_name = Kohana::find_file('media', $file, $ext)) { // Check if the browser sent an "if-none-match: <etag>" header, and tell if the file hasn't changed $this->response->check_cache(sha1($this->request->uri()) . filemtime($file_name), $this->request); // Send the file content as the response $this->response->body(file_get_contents($file_name)); // Set the proper headers to allow caching $this->response->headers('content-type', File::mime_by_ext($ext)); $this->response->headers('last-modified', date('r', filemtime($file_name))); // This is ignored by check_cache $this->response->headers('cache-control', 'public, max-age=2592000'); if (Config::get('media.cache', FALSE)) { // Set base path $path = Config::get('media.public_dir', 'media'); // Override path if we're in admin if ($theme) { $path = $path . DS . $theme; } // Save the contents to the public directory for future requests $public_path = $path . DS . $file . '.' . $ext; $directory = dirname($public_path); if (!is_dir($directory)) { // Recursively create the directories needed for the file System::mkdir($directory, 0777, TRUE); } file_put_contents($public_path, $this->response->body()); } } else { Log::error('Media controller error while loading file: :file', array(':file' => $file)); // Return a 404 status $this->response->status(404); } }
/** * (non-PHPdoc) * @see Upload_File::upload() */ public function upload(array $data, $path, $formUpload = true) { $data = parent::upload($data, $path, $formUpload); if (!empty($data) && !empty($this->_config['sizes'])) { foreach ($this->_config['sizes'] as $name => $xy) { $ext = File::getExt($data['path']); $replace = '-' . $name . $ext; $newName = str_replace($ext, $replace, $data['path']); if ($this->_config['thumb_types'][$name] == 'crop') { Image_Resize::resize($data['path'], $xy[0], $xy[1], $newName, true, true); } else { Image_Resize::resize($data['path'], $xy[0], $xy[1], $newName, true, false); } if ($name == 'icon') { $data['thumb'] = $newName; } } } return $data; }
protected function renderFile(File $file, Tool_Result $res = null) { $ext = $file->getExt(); $class = '\\phorkie\\Renderer_Unknown'; if (isset($GLOBALS['phorkie']['languages'][$ext]['renderer'])) { $class = $GLOBALS['phorkie']['languages'][$ext]['renderer']; } else { if ($file->isText()) { $class = '\\phorkie\\Renderer_Geshi'; } else { if (isset($GLOBALS['phorkie']['languages'][$ext]['mime'])) { $type = $GLOBALS['phorkie']['languages'][$ext]['mime']; if (substr($type, 0, 6) == 'image/') { $class = '\\phorkie\\Renderer_Image'; } } } } $rend = new $class(); return $rend->toHtml($file, $res); }
/** * Save image to file * @param resource $resource - image resource * @param string $path - path to file * * @param int $imgInfo - image type constant deprecated */ protected static function saveImage($resource, $path, $imgType = false) { $ext = File::getExt(strtolower($path)); switch ($ext) { case '.jpg': case '.jpeg': $imgType = IMAGETYPE_JPEG; break; case '.gif': $imgType = IMAGETYPE_GIF; break; case 'png': $imgType = IMAGETYPE_PNG; break; } switch ($imgType) { case IMAGETYPE_GIF: imagegif($resource, $path); break; case IMAGETYPE_JPEG: imagejpeg($resource, $path, 100); break; case IMAGETYPE_PNG: imagepng($resource, $path); break; default: return false; } imagedestroy($resource); }
/** * Test if an uploaded file is an allowed file type, by extension * * Example: * ~~~ * $array->rule('file', 'Upload::type', array(':value', array('jpg', 'png', 'gif'))); * ~~~ * * @param array $file $_FILES item * @param array $allowed Allowed file extensions * * @return boolean * * @uses File::getExt */ public static function type(array $file, array $allowed) { if ($file['error'] !== UPLOAD_ERR_OK) { return TRUE; } $allowed = array_map('strtolower', $allowed); $ext = strtolower(File::getExt($file['name'])); return in_array($ext, $allowed); }
/** * (non-PHPdoc) * @see Filestorage_Abstract::add() */ public function add($filePath, $useName = false) { if (!file_exists($filePath)) { return false; } $path = $this->generateFilePath(); if (!is_dir($path) && !@mkdir($path, 0755, true)) { $this->logError('Cannot write FS ' . $path, self::ERROR_CANT_WRITE_FS); return false; } $uploadAdapter = $this->_config->get('uploader'); $uploaderConfig = $this->_config->get('uploader_config'); $uploader = new $uploadAdapter($uploaderConfig); $fileName = basename($filePath); $oldName = basename($filePath); if ($useName !== false) { $oldName = $useName; } if ($this->_config->get('rename')) { $fileName = time() . uniqid('-') . File::getExt($fileName); } $files = array('file' => array('name' => $fileName, 'old_name' => $oldName, 'type' => '', 'tmp_name' => $filePath, 'error' => 0, 'size' => filesize($filePath))); $uploaded = $uploader->start($files, $path, false); if (empty($uploaded)) { return array(); } foreach ($uploaded as $k => &$v) { $v['path'] = str_replace($this->_config->get('filepath'), '', $v['path']); $v['id'] = $v['path']; } unset($v); return $uploaded; }
/** * Create path for cache file * * @param string $basePath * @param string $fileName * @return string */ public static function createCachePath($basePath, $fileName) { $extension = File::getExt($fileName); $str = md5($fileName); $len = strlen($str); $path = ''; $count = 0; $parts = 0; for ($i = 0; $i < $len; $i++) { if ($count == 4) { $path .= '/'; $count = 0; $parts++; } if ($parts == 4) { break; } $path .= $str[$i]; $count++; } $path = $basePath . $path; if (!is_dir($path)) { mkdir($path, 0755, true); } return $path . $str . $extension; }
/** * Test if an uploaded file is an allowed file type, by extension * * Example: * ~~~ * $array->rule('file', 'Upload::type', array(':value', array('jpg', 'png', 'gif'))); * ~~~ * * @param array $file $_FILES item * @param array $allowed Allowed file extensions * * @return boolean * * @uses File::getExt */ public static function type(array $file, array $allowed) { if ($file['error'] !== UPLOAD_ERR_OK) { return TRUE; } $ext = File::getExt($file['name']); return in_array($ext, $allowed); }
protected static function _scanClassDir($path, &$map, &$mapPackaged, $exceptPath, $packages, $packagesCfg) { $path = File::fillEndSep($path); $items = File::scanFiles($path, array('.php'), false); if (empty($items)) { return; } foreach ($items as $item) { if (File::getExt($item) === '.php') { $parts = explode(DIRECTORY_SEPARATOR, str_replace($exceptPath, '', substr($item, 0, -4))); $parts = array_map('ucfirst', $parts); $class = implode('_', $parts); $package = false; if (isset($packages[$item]) && $packagesCfg['packages'][$packages[$item]]['active']) { $package = $packagesCfg->get('path') . $packages[$item] . '.php'; } else { $package = $item; } if (!isset($map[$class])) { $map[$class] = $item; } if (!isset($mapPackaged[$class])) { $mapPackaged[$class] = $package; } } else { self::_scanClassDir($item, $map, $mapPackaged, $exceptPath, $packages, $packagesCfg); } } }
/** * Gel list of JS files to include * (load and render designer project) * @param string $cacheKey * @param Designer_Project $project * @param boolean $selfInclude * @param array $replace * @return array */ public static function getProjectIncludes($cacheKey, Designer_Project $project, $selfInclude = true, $replace = array()) { $applicationConfig = Registry::get('main', 'config'); $designerConfig = Config::factory(Config::File_Array, $applicationConfig->get('configs') . 'designer.php'); $projectConfig = $project->getConfig(); $includes = array(); // include langs if (isset($projectConfig['langs']) && !empty($projectConfig['langs'])) { $language = Lang::getDefaultDictionary(); $lansPath = $designerConfig->get('langs_path'); $langsUrl = $designerConfig->get('langs_url'); foreach ($projectConfig['langs'] as $k => $file) { $file = $language . '/' . $file . '.js'; if (file_exists($lansPath . $file)) { $includes[] = $langsUrl . $file . '?' . filemtime($lansPath . $file); } } } if (isset($projectConfig['files']) && !empty($projectConfig['files'])) { foreach ($projectConfig['files'] as $file) { $ext = File::getExt($file); if ($ext === '.js' || $ext === '.css') { $includes[] = $designerConfig->get('js_url') . $file; } else { $projectFile = $designerConfig->get('configs') . $file; $subProject = Designer_Factory::loadProject($designerConfig, $projectFile); $projectKey = self::getProjectCacheKey($projectFile); $files = self::getProjectIncludes($projectKey, $subProject, true, $replace); unset($subProject); if (!empty($files)) { $includes = array_merge($includes, $files); } } } } Ext_Code::setRunNamespace($projectConfig['runnamespace']); Ext_Code::setNamespace($projectConfig['namespace']); if ($selfInclude) { $layoutCacheFile = Utils::createCachePath($applicationConfig->get('jsCacheSysPath'), $cacheKey . '.js'); /** * @todo remove slow operation */ if (!file_exists($layoutCacheFile)) { file_put_contents($layoutCacheFile, Code_Js_Minify::minify($project->getCode($replace))); } $includes[] = str_replace('./', '/', $layoutCacheFile); } /* * Project actions */ $actionFile = $project->getActionsFile(); /** * @todo slow operation */ $mTime = 0; if (file_exists('.' . $actionFile)) { $mTime = filemtime('.' . $actionFile); } $includes[] = $actionFile . '?' . $mTime; return $includes; }
/** * Get related projects * @param Designer_Project $project * @param array & $list - result */ protected function getRelatedProjects($project, &$list) { $projectConfig = $project->getConfig(); if (isset($projectConfig['files']) && !empty($projectConfig['files'])) { foreach ($projectConfig['files'] as $file) { if (File::getExt($file) === '.js' || File::getExt($file) === '.css') { continue; } $projectFile = $this->_config->get('configs') . $file; $subProject = Designer_Factory::loadProject($this->_config, $projectFile); $list[] = array('project' => $subProject, 'file' => $file); $this->getRelatedProjects($subProject, $list); } } }
public function indexAction() { if (!$this->_session->keyExists('loaded') || !$this->_session->get('loaded')) { Response::put(''); exit; } $designerConfig = Config::factory(Config::File_Array, $this->_configMain['configs'] . 'designer.php'); $res = Resource::getInstance(); $res->addJs('/js/lib/jquery.js', 0); Model::factory('Medialib')->includeScripts(); $res->addJs('/js/app/system/SearchPanel.js'); $res->addJs('/js/app/system/HistoryPanel.js', 0); $res->addJs('/js/lib/ext_ux/RowExpander.js', 0); $res->addJs('/js/app/system/RevisionPanel.js', 1); $res->addJs('/js/app/system/EditWindow.js', 2); $res->addJs('/js/app/system/ContentWindow.js', 3); $res->addJs('/js/app/system/designer/viewframe/main.js', 4); $res->addJs('/js/app/system/designer/lang/' . $designerConfig['lang'] . '.js', 5); $project = $this->_getProject(); $projectCfg = $project->getConfig(); Ext_Code::setRunNamespace($projectCfg['runnamespace']); Ext_Code::setNamespace($projectCfg['namespace']); $grids = $project->getGrids(); if (!empty($grids)) { foreach ($grids as $name => $object) { if ($object->isInstance()) { continue; } $cols = $object->getColumns(); if (!empty($cols)) { foreach ($cols as $column) { $column['data']->itemId = $column['id']; } } $object->addListener('columnresize', '{ fn:function( ct, column, width,eOpts){ app.application.onGridColumnResize("' . $name . '", ct, column, width, eOpts); } }'); $object->addListener('columnmove', '{ fn:function(ct, column, fromIdx, toIdx, eOpts){ app.application.onGridColumnMove("' . $name . '", ct, column, fromIdx, toIdx, eOpts); } }'); } } $dManager = new Dictionary_Manager(); $key = 'vf_' . md5($dManager->getDataHash() . serialize($project)); $templates = $designerConfig->get('templates'); $replaces = array(array('tpl' => $templates['wwwroot'], 'value' => $this->_configMain->get('wwwroot')), array('tpl' => $templates['adminpath'], 'value' => $this->_configMain->get('adminPath')), array('tpl' => $templates['urldelimiter'], 'value' => $this->_configMain->get('urlDelimiter'))); $includes = Designer_Factory::getProjectIncludes($key, $project, true, $replaces); if (!empty($includes)) { foreach ($includes as $file) { if (File::getExt($file) == '.css') { $res->addCss($file, false); } else { $res->addJs($file, false, false); } } } $names = $project->getRootPanels(); $basePaths = array(); $parts = explode('/', $this->_configMain->get('wwwroot')); if (is_array($parts) && !empty($parts)) { foreach ($parts as $item) { if (!empty($item)) { $basePaths[] = $item; } } } $basePaths[] = $this->_configMain['adminPath']; $basePaths[] = 'designer'; $basePaths[] = 'sub'; //' . $project->getCode($replaces) . ' $initCode = ' app.delimiter = "' . $this->_configMain['urlDelimiter'] . '"; app.admin = "' . $this->_configMain->get('wwwroot') . $this->_configMain->get('adminPath') . '"; app.wwwRoot = "' . $this->_configMain->get('wwwroot') . '"; var applicationClassesNamespace = "' . $projectCfg['namespace'] . '"; var applicationRunNamespace = "' . $projectCfg['runnamespace'] . '"; var designerUrlPaths = ["' . implode('","', $basePaths) . '"]; var canDelete = true; var canPublish = true; var canEdit = true; Ext.onReady(function(){ app.application.mainUrl = app.createUrl(designerUrlPaths); '; if (!empty($names)) { foreach ($names as $name) { if ($project->getObject($name)->isExtendedComponent()) { if ($project->getObject($name)->getConfig()->defineOnly) { continue; } $initCode .= Ext_Code::appendRunNamespace($name) . ' = Ext.create("' . Ext_Code::appendNamespace($name) . '",{});'; } $initCode .= ' app.viewFrame.add(' . Ext_Code::appendRunNamespace($name) . '); '; } } $initCode .= ' app.application.fireEvent("projectLoaded"); });'; $res->addInlineJs($initCode); $tpl = new Template(); $tpl->lang = $this->_configMain['language']; $tpl->development = $this->_configMain['development']; $tpl->resource = $res; $tpl->useCSRFToken = Registry::get('backend', 'config')->get('use_csrf_token'); Response::put($tpl->render(Application::getTemplatesPath() . 'designer/viewframe.php')); }