name() public static method

Extract the file name from a file path.
public static name ( string $path ) : string
$path string
return string
Example #1
0
 public function execute()
 {
     // I18nProfile class: http://stackoverflow.com/questions/8433686/is-there-a-php-library-for-parsing-gettext-po-pot-files
     App::import('Lib', 'I18nJs.PoParser');
     $dir = new Folder(APP . 'Locale');
     $locales = $dir->read();
     foreach ($locales[0] as $localeDir) {
         $msgids = array();
         $language = $localeDir;
         $localeDir = new Folder(APP . 'Locale' . DS . $localeDir);
         $files = $localeDir->findRecursive('i18n_js.*\\.po');
         // Loop over PO i18n_js PO files
         foreach ($files as $file) {
             $file = new File($file);
             // Get language
             if (preg_match('%Locale/(.*?)/LC_MESSAGES%', $file->path, $regs)) {
                 $language = $regs[1];
             } else {
                 // todo return
                 $this->out(__d('i18n_js', '<error>Unable to determine language of PO file:</error>') . $file->path);
                 return;
             }
             // Get context, domain
             $context = '';
             if (strpos($file->name(), '.')) {
                 $context = explode('.', $file->name());
                 $context = $context[1];
             }
             // Parse PO file
             $poparser = new \Sepia\PoParser();
             $translations = $poparser->parse($file->path);
             foreach ($translations as $key => $translation) {
                 if (empty($key)) {
                     continue;
                 }
                 if (is_array($translation['msgid'])) {
                     $translation['msgid'] = implode('', $translation['msgid']);
                 }
                 if (is_array($translation['msgstr'])) {
                     $translation['msgstr'] = implode('', $translation['msgstr']);
                 }
                 $msgids[$context][$translation['msgid']] = $translation['msgstr'];
             }
         }
         if (empty($msgids)) {
             continue;
         }
         // Write JS file
         $outputFile = new File(WWW_ROOT . 'js' . DS . 'Locale' . DS . 'i18n_js.' . $language . '.js', true);
         $data = "I18nJs.locale = { ";
         $data .= "'pluralFormula': function (\$n) { return Number((\$n != 1)); }, ";
         $data .= "'strings': " . json_encode($msgids, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT) . " };";
         if ($outputFile->write($data)) {
             $this->out(__d('i18n_js', '<info>%s created</info>', $outputFile->path));
         } else {
             $this->out(__d('i18n_js', '<error>Unable to write: %s</error>', $outputFile->path));
         }
     }
 }
Example #2
0
 public function flags($current)
 {
     $dir = new Folder(WWW_ROOT . 'img/flags');
     $files = $dir->find('.*', true);
     if ($current != 'unknown') {
         $flag[$current] = $current;
     }
     $flag[''] = '';
     foreach ($files as $file) {
         $file = new File($dir->pwd() . DS . $file);
         $flag[Inflector::humanize($file->name())] = Inflector::humanize($file->name());
         $file->close();
         // Be sure to close the file when you're done
     }
     return $flag;
 }
Example #3
0
 /**
  * undocumented function
  *
  * @return void
  */
 function main()
 {
     $result = $folder = null;
     $mainfiles = explode(',', $this->args[0]);
     $target = !empty($this->params['ext']) ? $this->args[0] . '.' . $this->params['ext'] : $this->args[0] . '.min';
     $jsroot = $this->params['working'] . DS . $this->params['webroot'] . DS . 'js' . DS;
     foreach ((array) $mainfiles as $mainfile) {
         $mainfile = strpos($mainfile, '/') === false ? $jsroot . $mainfile : $mainfile;
         $Pack = new File(str_replace('.js', '', $mainfile) . '.js');
         $result .= JsMin::minify($Pack->read());
     }
     if (!empty($this->args[1])) {
         $folder = $this->args[1] . DS;
         $Js = new Folder($jsroot . $folder);
         list($ds, $files) = $Js->read();
         foreach ((array) $files as $file) {
             $file = strpos($file, '/') === false ? $jsroot . $folder . $file : $file;
             $Pack = new File(str_replace('.js', '', $file) . '.js');
             $result .= JsMin::minify($Pack->read());
         }
     }
     $Packed = new File($jsroot . $target . '.js');
     if ($Packed->write($result, 'w', true)) {
         $this->out($Packed->name() . ' created');
     }
 }
Example #4
0
 public function main()
 {
     $Folder = new Folder(dirname(dirname(dirname(__FILE__))) . DS . "features");
     $this->out("copy " . $Folder->pwd() . " to Cake Root...");
     $Folder->copy(array('to' => ROOT . DS . "features"));
     $File = new File(dirname(__FILE__) . DS . "behat.yml.default");
     $this->out("copy " . $File->name() . " to App/Config...");
     $File->copy(APP . DS . "Config" . DS . "behat.yml");
 }
Example #5
0
 /**
  * Constructor.
  *
  * @access  protected
  */
 protected function __construct()
 {
     $plugins_cache_id = '';
     $plugin_manifest = [];
     $plugin_settings = [];
     // Get Plugins List
     $plugins_list = Config::get('system.plugins');
     // If Plugins List isnt empty then create plugin cache ID
     if (is_array($plugins_list) && count($plugins_list) > 0) {
         // Go through...
         foreach ($plugins_list as $plugin) {
             if (File::exists($_plugin = PLUGINS_PATH . '/' . $plugin . '/' . $plugin . '.yml')) {
                 $plugins_cache_id .= filemtime($_plugin);
             }
         }
         // Create Unique Cache ID for Plugins
         $plugins_cache_id = md5('plugins' . ROOT_DIR . PLUGINS_PATH . $plugins_cache_id);
     }
     // Get plugins list from cache or scan plugins folder and create new plugins cache item
     if (Cache::driver()->contains($plugins_cache_id)) {
         Config::set('plugins', Cache::driver()->fetch($plugins_cache_id));
     } else {
         // If Plugins List isnt empty
         if (is_array($plugins_list) && count($plugins_list) > 0) {
             // Go through...
             foreach ($plugins_list as $plugin) {
                 if (File::exists($_plugin_manifest = PLUGINS_PATH . '/' . $plugin . '/' . $plugin . '.yml')) {
                     $plugin_manifest = Yaml::parseFile($_plugin_manifest);
                 }
                 if (File::exists($_plugin_settings = PLUGINS_PATH . '/' . $plugin . '/settings.yml')) {
                     $plugin_settings = Yaml::parseFile($_plugin_settings);
                 }
                 $_plugins_config[File::name($_plugin_manifest)] = array_merge($plugin_manifest, $plugin_settings);
             }
             Config::set('plugins', $_plugins_config);
             Cache::driver()->save($plugins_cache_id, $_plugins_config);
         }
     }
     // Include enabled plugins
     if (is_array(Config::get('plugins')) && count(Config::get('plugins')) > 0) {
         foreach (Config::get('plugins') as $plugin_name => $plugin) {
             if (Config::get('plugins.' . $plugin_name . '.enabled')) {
                 include_once PLUGINS_PATH . '/' . $plugin_name . '/' . $plugin_name . '.php';
             }
         }
     }
     // Run Actions on plugins_loaded
     Action::run('plugins_loaded');
 }
Example #6
0
 /**
  * @return array
  */
 public function info()
 {
     if ($this->info) {
         return $this->info;
     }
     $file = $this->getFullPath();
     if (!$this->exists()) {
         return '';
     }
     list($width, $height) = getimagesize($file);
     $extension = \File::extension($file);
     $name = \File::name($file);
     $info = ['extension' => $extension, 'name' => $name, 'width' => $width, 'height' => $height];
     return $info;
 }
 public function admin_view($id = null)
 {
     $filename = WWW_ROOT . FilesController::FILE_ROOT . DS . implode(DS, $this->request->params['pass']) . "." . $this->request->params['ext'];
     debug($filename);
     $file = new File($filename, false);
     if (!$file->exists()) {
         throw new NotFoundException(__('File not found: ') . $file->path);
     }
     debug($file->name);
     debug($file->ext());
     debug($file->Folder()->path);
     $this->viewClass = 'Media';
     $params = array('id' => $file->name, 'name' => $file->name(), 'download' => false, 'extension' => $file->ext(), 'path' => $file->Folder()->path . DS);
     $this->set($params);
     //$this->set('fee', $this->Fee->read(null, $id));
 }
Example #8
0
 /**
  * Twig Markup Filter 'flipCss'
  * @param $paths
  * @param bool $force
  * @return array|string
  */
 public function flipCss($paths)
 {
     if (!LanguageDetector::isRtl()) {
         return $paths;
     }
     if (!is_array($paths)) {
         $paths = [$paths];
     }
     $rPaths = [];
     foreach ($paths as $path) {
         $assetPath = $path;
         if (File::exists(dirname($assetPath) . '/' . File::name($assetPath) . '.rtl.' . File::extension($assetPath))) {
             $newPath = dirname($assetPath) . '.rtl.' . File::extension($assetPath);
         } else {
             $newPath = CssFlipper::flipCss($assetPath, true);
         }
         $rPaths[] = $newPath;
     }
     return $rPaths;
 }
Example #9
0
 /**
  * beforeRender callback function
  *
  * @param Controller $controller
  * @return array contents for panel
  */
 public function beforeRender(Controller $controller)
 {
     $data = array();
     $dir = new Folder(LOGS);
     $files = $dir->find();
     foreach ($files as $log) {
         $file = new File(LOGS . $log);
         $name = $file->name();
         $data[$name] = array();
         if (!$file->readable()) {
             $data[$name]['content'] = __('This log file is unreadable.');
             continue;
         }
         $data[$name]['lastChange'] = date('Y-m-d H:i:s', $file->lastChange());
         if ($file->size() > $this->readBytes) {
             $file->offset(-$this->readBytes, SEEK_END);
         }
         $data[$name]['content'] = $file->read($this->readBytes);
     }
     return $data;
 }
 public static function ShortCode($arguments)
 {
     extract($arguments);
     // Obtain json file on public folder
     $id = $id ? $id : '';
     $json = '';
     $galleryFile = ROOT_DIR . '/public/gallery/gallery.json';
     if (File::exists($galleryFile)) {
         $json = json_decode(File::getContent($galleryFile), true);
     } else {
         die('OOps Whrere is media.json file!');
     }
     $num = 0;
     $photos = File::scan(ROOT_DIR . '/public/gallery/galleries/' . $id);
     $img = Url::getBase() . '/public/gallery/galleries/' . $id . '/' . File::name($photos[0]) . '.' . File::ext($photos[0]);
     // get plugin info
     //var_dump(json_encode(Config::get('plugins.gallery'),true));
     $template = Template::factory(PLUGINS_PATH . '/gallery/templates/');
     $template->setOptions(['strip' => false]);
     // show template
     return $template->fetch('slide.tpl', ['id' => $id, 'title' => $json[$id]['title'], 'description' => $json[$id]['desc'], 'first' => $img, 'photos' => $photos]);
 }
Example #11
0
 public function getFilename()
 {
     return $this->file->name();
 }
Example #12
0
 /**
  * Stores the media to a file and assures that the output file has the correct extension
  *
  * @param string $file Absolute path to a file
  * @param boolean $overwrite Enable overwriting of an existent file
  * @return mixed
  */
 function store($file, $overwrite = false, $guessExtension = true)
 {
     $File = new File($file);
     if ($overwrite) {
         $File->delete();
     }
     if ($File->exists()) {
         $message = "Media::store - File `{$file}` already exists.";
         trigger_error($message, E_USER_NOTICE);
         return false;
     }
     if ($guessExtension) {
         $file = $File->Folder->pwd() . DS . $File->name();
         $correctExtension = MimeType::guessExtension($this->mimeType);
         if ($correctExtension) {
             $file .= '.' . $correctExtension;
         } elseif (isset($extension)) {
             $file .= '.' . $File->ext();
         }
     }
     if ($this->Adapters->dispatchMethod($this, 'store', array($file))) {
         return $file;
     }
     return false;
 }
Example #13
0
 /**
  * Load a article
  */
 public function load()
 {
     // Get filename from params
     if (isset($this->request->pass)) {
         if (isset($this->request->pass[0])) {
             $selectedFilename = base64_decode($this->request->pass[0]);
         }
     }
     // Get current filename from Sesssion
     if (empty($selectedFilename)) {
         $selectedFilename = $this->Session->read("selected");
     }
     // Get all files name
     $filenames = $this->noteDir->find('.*\\.html');
     // Get current file from articles directory
     if (!empty($selectedFilename)) {
         $tmp = $this->noteDir->find('.*^' . $selectedFilename . '\\.html');
         $fileSelected = $tmp[0];
     } else {
         //If none selected we take the first artcle as selected
         $fileSelected = $filenames[0];
     }
     // Warning case : file set in Session not found
     if (empty($fileSelected)) {
         echo json_encode(array('code' => 2, 'message' => 'Warning! Selected file from Session not found'));
         die;
     }
     $notes = array();
     // Get short file name
     foreach ($filenames as $filename) {
         $file = new File($this->noteDir->pwd() . DS . $filename);
         $notes[] = $file->name();
         $file->close();
     }
     // Get Content of selected file
     $file = new File($this->noteDir->pwd() . DS . $fileSelected);
     $selectedFileContent = $file->read();
     $file->close();
     // Return values
     echo json_encode(array("fileSelected" => $fileSelected, "noteSelected" => $file->name(), "selectedFileContent" => $selectedFileContent, "notes" => $notes));
     exit;
 }
Example #14
0
                  <li><b>Filename: </b>' . File::name($path) . '</li>
                  <li><b>Extension: </b>' . File::ext($path) . '</li>
                  <li><b>Size: </b>' . $width . 'x' . $height . 'px</li>
                  <li class="code"><b>Markdown: </b><code>![text img](<a target="_blank" href="' . Panel::$site['url'] . '/public/uploads/' . $link . '">' . Panel::$site['url'] . '/public/uploads/' . $link . '</a>)</code></li>
                  <li class="code"><b>Html: </b><code>&lt;img src="<a target="_blank" href="' . Panel::$site['url'] . '/public/uploads/' . $link . '">' . Panel::$site['url'] . '/public/uploads/' . $link . '</a> /&gt;</code></li>
                  <li><a class="btn red" href="' . $p->url() . '/uploads">' . Panel::$lang['back_to_uploads'] . '</a></li>
                </ul>
              </div>
            </div>
          </div>';
        } else {
            // other template files
            $template = '
        <div class="box-1 col">
            <div class="media">
              <div class="info-media">
                <ul>
                  <li>' . Panel::$lang['no_preview_for_this_file'] . '</li>
                  <li><b>Filename: </b>' . File::name($path) . '</li>
                  <li><b>Extension: </b>' . File::ext($path) . '</li>
                  <li class="code"><b>Markdown: </b><code>[text link](<a target="_blank" href="' . Panel::$site['url'] . '/public/uploads/' . $link . '">' . Panel::$site['url'] . '/public/uploads/' . $link . '</a>)</code></li>
                  <li class="code"><b>Html: </b><code>&lt;a href="<a target="_blank" href="' . Panel::$site['url'] . '/public/uploads/' . $link . '">' . Panel::$site['url'] . '/public/uploads/' . $link . '</a>" download &gt;text link&lt;/a&gt;</code></li>
                  <li><a class="btn red" href="' . $p->url() . '/uploads">' . Panel::$lang['back_to_uploads'] . '</a></li>
                </ul>
              </div>
            </div>
          </div>';
        }
    }
    $p->view('actions', array('type' => 'Upload Preview', 'title' => Panel::$lang['Preview'], 'content' => $file, 'html' => $template));
});
Example #15
0
 function _makeFilePath(&$model, $field)
 {
     $config = $this->config[$model->alias][$field];
     $data = $this->_data[$model->alias][$field];
     $file = $config['dir'] . low($data['name']);
     $File = new File($this->fileRoot . $file);
     $file = str_replace($File->name() . '.', String::uuid() . '.', $file);
     if ($config['ext']) {
         $file = str_replace('.' . $File->ext(), '.' . $config['ext'], $file);
     }
     $file = strtr($file, DS, '/');
     return $file;
 }
 /**
  * Attach storage file
  *
  * @param string $file_path
  * @return void
  */
 public function admin_addStorageFile()
 {
     $this->layout = 'ajax';
     $notice = array();
     $storage_path = Configure::read('Nodeattachment.storageUploadDir');
     if (empty($storage_path) || empty($this->params['named']['node_id'])) {
         $this->cakeError('error404');
     }
     $node_id = $this->params['named']['node_id'];
     if (!empty($this->params['named']['file'])) {
         $File = new File($storage_path . DS . $this->params['named']['file']);
         // don't overwrite previous files that were uploaded and slug filename
         $file['name'] = Inflector::slug($File->name());
         $file['ext'] = $File->ext();
         $file = $this->__uniqeSlugableFilename($file);
         $file_name = $file['name'] . '.' . $file['ext'];
         // copy file and save nodeattachment
         if ($File->copy($this->uploads_path . DS . $file_name, true)) {
             $data = array('node_id' => $node_id, 'slug' => $file_name, 'path' => '/' . $this->uploads_dir . '/' . $file_name, 'title' => $file['name'], 'status' => 1, 'mime_type' => $this->__getMime($this->uploads_path . DS . $file_name));
             if ($this->Nodeattachment->save($data)) {
                 //unlink($storage_path . DS . $this->params['named']['file']);
                 $notice = array('text' => __('File attached', true), 'class' => 'success');
             } else {
                 $notice = array('text' => __('Error during nodeattachment saving', true), 'class' => 'error');
             }
         }
     }
     // list files
     $Folder = new Folder($storage_path);
     $content = $Folder->read();
     $this->set(compact('content', 'node_id', 'notice'));
 }
 /**
  * Snippets admin function
  */
 public static function main()
 {
     // Init vars
     $snippets_path = STORAGE . DS . 'snippets' . DS;
     $snippets_list = array();
     $errors = array();
     // Check for get actions
     // -------------------------------------
     if (Request::get('action')) {
         // Switch actions
         // -------------------------------------
         switch (Request::get('action')) {
             // Add snippet
             // -------------------------------------
             case "add_snippet":
                 if (Request::post('add_snippets') || Request::post('add_snippets_and_exit')) {
                     if (Security::check(Request::post('csrf'))) {
                         if (trim(Request::post('name')) == '') {
                             $errors['snippets_empty_name'] = __('Required field', 'snippets');
                         }
                         if (file_exists($snippets_path . Security::safeName(Request::post('name')) . '.snippet.php')) {
                             $errors['snippets_exists'] = __('This snippet already exists', 'snippets');
                         }
                         if (count($errors) == 0) {
                             // Save snippet
                             File::setContent($snippets_path . Security::safeName(Request::post('name')) . '.snippet.php', Request::post('content'));
                             Notification::set('success', __('Your changes to the snippet <i>:name</i> have been saved.', 'snippets', array(':name' => Security::safeName(Request::post('name')))));
                             if (Request::post('add_snippets_and_exit')) {
                                 Request::redirect('index.php?id=snippets');
                             } else {
                                 Request::redirect('index.php?id=snippets&action=edit_snippet&filename=' . Security::safeName(Request::post('name')));
                             }
                         }
                     } else {
                         die('Request was denied because it contained an invalid security token. Please refresh the page and try again.');
                     }
                 }
                 // Save fields
                 if (Request::post('name')) {
                     $name = Request::post('name');
                 } else {
                     $name = '';
                 }
                 if (Request::post('content')) {
                     $content = Request::post('content');
                 } else {
                     $content = '';
                 }
                 // Display view
                 View::factory('box/snippets/views/backend/add')->assign('content', $content)->assign('name', $name)->assign('errors', $errors)->display();
                 break;
                 // Edit snippet
                 // -------------------------------------
             // Edit snippet
             // -------------------------------------
             case "edit_snippet":
                 // Save current snippet action
                 if (Request::post('edit_snippets') || Request::post('edit_snippets_and_exit')) {
                     if (Security::check(Request::post('csrf'))) {
                         if (trim(Request::post('name')) == '') {
                             $errors['snippets_empty_name'] = __('Required field', 'snippets');
                         }
                         if (file_exists($snippets_path . Security::safeName(Request::post('name')) . '.snippet.php') and Security::safeName(Request::post('snippets_old_name')) !== Security::safeName(Request::post('name'))) {
                             $errors['snippets_exists'] = __('This snippet already exists', 'snippets');
                         }
                         // Save fields
                         if (Request::post('content')) {
                             $content = Request::post('content');
                         } else {
                             $content = '';
                         }
                         if (count($errors) == 0) {
                             $snippet_old_filename = $snippets_path . Request::post('snippets_old_name') . '.snippet.php';
                             $snippet_new_filename = $snippets_path . Security::safeName(Request::post('name')) . '.snippet.php';
                             if (!empty($snippet_old_filename)) {
                                 if ($snippet_old_filename !== $snippet_new_filename) {
                                     rename($snippet_old_filename, $snippet_new_filename);
                                     $save_filename = $snippet_new_filename;
                                 } else {
                                     $save_filename = $snippet_new_filename;
                                 }
                             } else {
                                 $save_filename = $snippet_new_filename;
                             }
                             // Save snippet
                             File::setContent($save_filename, Request::post('content'));
                             Notification::set('success', __('Your changes to the snippet <i>:name</i> have been saved.', 'snippets', array(':name' => basename($save_filename, '.snippet.php'))));
                             if (Request::post('edit_snippets_and_exit')) {
                                 Request::redirect('index.php?id=snippets');
                             } else {
                                 Request::redirect('index.php?id=snippets&action=edit_snippet&filename=' . Security::safeName(Request::post('name')));
                             }
                         }
                     } else {
                         die('Request was denied because it contained an invalid security token. Please refresh the page and try again.');
                     }
                 }
                 if (Request::post('name')) {
                     $name = Request::post('name');
                 } else {
                     $name = File::name(Request::get('filename'));
                 }
                 $content = File::getContent($snippets_path . Request::get('filename') . '.snippet.php');
                 // Display view
                 View::factory('box/snippets/views/backend/edit')->assign('content', $content)->assign('name', $name)->assign('errors', $errors)->display();
                 break;
             case "delete_snippet":
                 if (Security::check(Request::get('token'))) {
                     File::delete($snippets_path . Request::get('filename') . '.snippet.php');
                     Notification::set('success', __('Snippet <i>:name</i> deleted', 'snippets', array(':name' => File::name(Request::get('filename')))));
                     Request::redirect('index.php?id=snippets');
                 } else {
                     die('Request was denied because it contained an invalid security token. Please refresh the page and try again.');
                 }
                 break;
         }
     } else {
         // Get snippets
         $snippets_list = File::scan($snippets_path, '.snippet.php');
         // Display view
         View::factory('box/snippets/views/backend/index')->assign('snippets_list', $snippets_list)->display();
     }
 }
 /**
  * Returns a path to the generated thumbnail.
  * It will only generate a thumbnail for an image if the source is newer than the thumbnail,
  * or if the thumbnail doesn't exist yet.
  * 
  * Note: Changing the quality later on after a thumbnail is already generated would have 
  * no effect. Original source images would have to be updated (re-uploaded or modified via
  * "touch" command or some other means). Or the existing thumbnail would have to be destroyed
  * manually or with the flushVersions() method below.
  * 
  * @modified 2009-11-10 by Kevin DeCapite (www.decapite.net)
  * 		- Changed 2 return lines to use ImageVersionComponent::formatPath() method
  * 		- See that method's comment block for details
  *  
  * @modified 2010-05-03 by Tom Maiaroto
  *		- Added "letterbox" support so resized images don't need to stretch (when not cropping), changed up some resizing math
  *		- Changed version() method so it takes an array which makes it easier to add more options in the future, consolidated code a lot
  *		- Added sharpening support
  *
  * @param $options Array[required] Options that change the size and cropping method of the image
  * 		- image String[required] Location of the source image.
  * 		- size Array[optional] Size of the thumbnail. Default: 75x75
  * 		- quality Int[optional] Quality of the thumbnail. Default: 85%
  * 		- crop Boolean[optional] Whether to crop the image (when one dimension is larger than specified $size)
  * 		- letterbox Mixed[optional] If defined, it needs to be an array that defines the RGB background color to use. So when crop is set to false, this will fill in the rest of the image with a background color. Note: Transparent images will have a transparent letterbox unless forced.
  *		- force_letterbox_color Boolean[optional] Whether or not to force the letterbox color on images with transparency (gif and png images). Default: false (false meaning their letterboxes will be transparent, true meaning they get a colored letterbox which also floods behind any transparent/translucent areas of the image)
  *		- sharpen Boolean[optional] Whether to sharpen the image version or not. Default: true (note: png and gif images are not sharpened because of possible problems with transparency)	 
  *
  * @return String path to thumbnail image.
  */
 function version($options = array('image' => null, 'size' => array(75, 75), 'quality' => 85, 'crop' => false, 'letterbox' => null, 'force_letterbox_color' => false, 'sharpen' => true))
 {
     if (isset($options['image'])) {
         $source = $options['image'];
     } else {
         $source = null;
     }
     if (isset($options['size'])) {
         $thumbSize = $options['size'];
     } else {
         $thumbSize == array(75, 75);
     }
     if (isset($options['quality'])) {
         $thumbQuality = $options['quality'];
     } else {
         $thumbQuality = 85;
     }
     if (isset($options['crop'])) {
         $crop = $options['crop'];
     } else {
         $crop = false;
     }
     if (isset($options['letterbox'])) {
         $letterbox = $options['letterbox'];
     } else {
         $letterbox = null;
     }
     if (is_string($letterbox)) {
         $letterbox = $this->_html2rgb($options['letterbox']);
     }
     if (isset($options['sharpen'])) {
         $sharpen = $options['sharpen'];
     } else {
         $sharpen = true;
     }
     if (isset($options['force_letterbox_color'])) {
         $force_letterbox_color = $options['force_letterbox_color'];
     } else {
         $force_letterbox_color = false;
     }
     // if no source provided, don't do anything
     if (empty($source)) {
         return false;
     }
     // set defaults if null passed for any values
     if ($thumbSize == null) {
         $thumbSize = array(75, 75);
     }
     if ($thumbQuality == null) {
         $thumbQuality = 85;
     }
     if ($crop == null) {
         $crop = false;
     }
     $webroot = new Folder(WWW_ROOT);
     $this->webRoot = $webroot->path;
     // set the size
     $thumb_size_x = $original_thumb_size_x = $thumbSize[0];
     $thumb_size_y = $original_thumb_size_y = $thumbSize[1];
     // round the thumbnail quality in case someone provided a decimal
     $thumbQuality = ceil($thumbQuality);
     // or if a value was entered beyond the extremes
     if ($thumbQuality > 100) {
         $thumbQuality = 100;
     }
     if ($thumbQuality < 0) {
         $thumbQuality = 0;
     }
     // get full path of source file	(note: a beginning slash doesn't matter, the File class handles that I believe)
     $originalFile = new File($this->webRoot . $source);
     $source = $originalFile->Folder->path . DS . $originalFile->name() . '.' . $originalFile->ext();
     // if the source file doesn't exist, don't do anything
     if (!file_exists($source)) {
         return false;
     }
     // get the destination where the new file will be saved (including file name)
     $pathToSave = $this->createPath($originalFile->Folder->path . DS . $thumbSize[0] . 'x' . $thumbSize[1]);
     $dest = $originalFile->Folder->path . DS . $thumb_size_x . 'x' . $thumb_size_y . DS . $originalFile->name() . '.' . $originalFile->ext();
     // First make sure it's an image that we can use (bmp support isn't added, but could be)
     switch (strtolower($originalFile->ext())) {
         case 'jpg':
         case 'jpeg':
         case 'gif':
         case 'png':
             break;
         default:
             return false;
             break;
     }
     // Then see if the size version already exists and if so, is it older than our source image?
     if (file_exists($originalFile->Folder->path . DS . $thumb_size_x . 'x' . $thumb_size_y . DS . $originalFile->name() . '.' . $originalFile->ext())) {
         $existingFile = new File($dest);
         if (date('YmdHis', $existingFile->lastChange()) > date('YmdHis', $originalFile->lastChange())) {
             // if it's newer than the source, return the path. the source hasn't updated, so we don't need a new thumbnail.
             return $this->formatPath(substr(strstr($existingFile->Folder->path . DS . $existingFile->name() . '.' . $existingFile->ext(), 'webroot'), 7));
         }
     }
     // Get source image dimensions
     $size = getimagesize($source);
     $width = $size[0];
     $height = $size[1];
     // $x and $y here are the image source offsets
     $x = NULL;
     $y = NULL;
     $dx = $dy = 0;
     if ($thumb_size_x > $width && $thumb_size_y > $height) {
         $crop = false;
         // don't need to crop now do we?
     }
     // don't allow new width or height to be greater than the original
     if ($thumb_size_x > $width) {
         $thumb_size_x = $width;
     }
     if ($thumb_size_y > $height) {
         $thumb_size_y = $height;
     }
     // generate new w/h if not provided (cool, idiot proofing)
     if ($thumb_size_x && !$thumb_size_y) {
         $thumb_size_y = $height * ($thumb_size_x / $width);
     } elseif ($thumb_size_y && !$thumb_size_x) {
         $thumb_size_x = $width * ($thumb_size_y / $height);
     } elseif (!$thumb_size_x && !$thumb_size_y) {
         $thumb_size_x = $width;
         $thumb_size_y = $height;
     }
     // set some default values for other variables we set differently based on options like letterboxing, etc.
     // TODO: clean this up and consolidate variables so the image creation process is shorter and nicer
     $new_width = $thumb_size_x;
     $new_height = $thumb_size_y;
     $x_mid = ceil($new_width / 2);
     //horizontal middle // TODO: possibly add options to change where the crop is from
     $y_mid = ceil($new_height / 2);
     //vertical middle
     // If the thumbnail is square
     if ($thumbSize[0] == $thumbSize[1]) {
         if ($width > $height) {
             $x = ceil(($width - $height) / 2);
             $width = $height;
         } elseif ($height > $width) {
             $y = ceil(($height - $width) / 2);
             $height = $width;
         }
         // else if the thumbnail is rectangular, don't stretch it
     } else {
         // if we aren't cropping then keep aspect ratio and contain image within the specified size
         if ($crop === false) {
             $ratio_orig = $width / $height;
             if ($thumb_size_x / $thumb_size_y > $ratio_orig) {
                 $thumb_size_x = ceil($thumb_size_y * $ratio_orig);
             } else {
                 $thumb_size_y = ceil($thumb_size_x / $ratio_orig);
             }
         }
         // if we are cropping...
         if ($crop === true) {
             $ratio_orig = $width / $height;
             if ($thumb_size_x / $thumb_size_y > $ratio_orig) {
                 $new_height = ceil($thumb_size_x / $ratio_orig);
                 $new_width = $thumb_size_x;
             } else {
                 $new_width = ceil($thumb_size_y * $ratio_orig);
                 $new_height = $thumb_size_y;
             }
             $x_mid = ceil($new_width / 2);
             //horizontal middle // TODO: possibly add options to change where the crop is from
             $y_mid = ceil($new_height / 2);
             //vertical middle
         }
     }
     switch (strtolower($originalFile->ext())) {
         case 'png':
             if ($thumbQuality != 0) {
                 $thumbQuality = ($thumbQuality - 100) / 11.111111;
                 $thumbQuality = round(abs($thumbQuality));
             }
             $new_im = $this->_generateImage('png', $source, $dx, $dy, $x, $y, $x_mid, $y_mid, $new_width, $new_height, $original_thumb_size_x, $original_thumb_size_y, $thumb_size_x, $thumb_size_y, $height, $width, $letterbox, $crop, $sharpen, $force_letterbox_color);
             imagepng($new_im, $dest, $thumbQuality);
             imagedestroy($new_im);
             break;
         case 'gif':
             $new_im = $this->_generateImage('gif', $source, $dx, $dy, $x, $y, $x_mid, $y_mid, $new_width, $new_height, $original_thumb_size_x, $original_thumb_size_y, $thumb_size_x, $thumb_size_y, $height, $width, $letterbox, $crop, $sharpen, $force_letterbox_color);
             imagegif($new_im, $dest);
             // no quality setting
             imagedestroy($new_im);
             break;
         case 'jpg':
         case 'jpeg':
             $new_im = $this->_generateImage('jpg', $source, $dx, $dy, $x, $y, $x_mid, $y_mid, $new_width, $new_height, $original_thumb_size_x, $original_thumb_size_y, $thumb_size_x, $thumb_size_y, $height, $width, $letterbox, $crop, $sharpen, $force_letterbox_color);
             imagejpeg($new_im, $dest, $thumbQuality);
             imagedestroy($new_im);
             break;
         default:
             return false;
             break;
     }
     $outputPath = new File($dest);
     $finalPath = substr(strstr($outputPath->Folder->path . DS . $outputPath->name() . '.' . $outputPath->ext(), 'webroot'), 7);
     // PHP 5.3.0 would allow for a true flag as the third argument in strstr()... which would take out "webroot" so substr() wasn't required, but for older PHP...
     return $this->formatPath($finalPath);
 }
 function view()
 {
     $this->Form->setAttribute('action', extension_filemanager::baseURL() . 'properties/?file=' . $_GET['file']);
     $file = new File(DOCROOT . $this->_FileManager->getStartLocation() . $_GET['file']);
     $FileManager =& $this->_Parent->ExtensionManager->create('filemanager');
     $formHasErrors = is_array($this->_errors) && !empty($this->_errors);
     if ($formHasErrors) {
         $this->pageAlert('An error occurred while processing this form. <a href="#error">See below for details.</a>', AdministrationPage::PAGE_ALERT_ERROR);
     }
     if (isset($_GET['result'])) {
         switch ($_GET['result']) {
             case 'saved':
                 $this->pageAlert(__('%s updated successfully', array($file->isDir() ? 'Folder' : 'File')), Alert::SUCCESS);
                 break;
         }
     }
     $this->setPageType('form');
     $path = extension_filemanager::baseURL() . 'browse/';
     $breadcrumb = '';
     $pathelements = explode('/', $_GET['file']);
     foreach ($pathelements as $element) {
         if ($element != '') {
             $path .= $element . '/';
             $breadcrumb .= ' / ' . ($element == end($pathelements) ? $element : Widget::Anchor($element, $path)->generate());
         }
     }
     $this->appendSubheading(trim($FileManager->getStartLocationLink(), '/') . $breadcrumb);
     $fields = array();
     $fieldset = new XMLElement('fieldset');
     $fieldset->setAttribute('class', 'settings');
     $fieldset->appendChild(new XMLElement('legend', 'Essentials'));
     $div = new XMLElement('div');
     $div->setAttribute('class', 'group');
     $label = Widget::Label('Name');
     $label->appendChild(Widget::Input('fields[name]', General::sanitize($file->name())));
     if (isset($this->_errors['name'])) {
         $div->appendChild(Widget::wrapFormElementWithError($label, $this->_errors['name']));
     } else {
         $div->appendChild($label);
     }
     $label = Widget::Label('Permissions');
     $label->appendChild(Widget::Input('fields[permissions]', General::sanitize($file->permissions())));
     if (isset($this->_errors['permissions'])) {
         $div->appendChild(Widget::wrapFormElementWithError($label, $this->_errors['permissions']));
     } else {
         $div->appendChild($label);
     }
     $fieldset->appendChild($div);
     $this->Form->appendChild($fieldset);
     if (!$file->isDir() && in_array(File::fileType($file->name()), array(File::CODE, File::DOC))) {
         $fieldset = new XMLElement('fieldset');
         $fieldset->setAttribute('class', 'settings');
         $fieldset->appendChild(new XMLElement('legend', 'Editor'));
         $label = Widget::Label('Contents');
         $label->appendChild(Widget::Textarea('fields[contents]', '25', '50', General::sanitize($file->contents()), array('class' => 'code')));
         if (isset($this->_errors['contents'])) {
             $fieldset->appendChild(Widget::wrapFormElementWithError($label, $this->_errors['contents']));
         } else {
             $fieldset->appendChild($label);
         }
         $this->Form->appendChild($fieldset);
     }
     if (!$file->isDir() && File::fileType($file->name()) == File::IMAGE) {
         $fieldset = new XMLElement('fieldset');
         $fieldset->setAttribute('class', 'settings');
         $fieldset->appendChild(new XMLElement('legend', 'Preview'));
         $img = new XMLElement('img');
         $img->setAttribute('src', URL . $FileManager->getStartLocation() . $_GET['file']);
         $img->setAttribute('alt', $file->name());
         $fieldset->appendChild($img);
         $this->Form->appendChild($fieldset);
     }
     $div = new XMLElement('div');
     $div->setAttribute('class', 'actions');
     if (is_writeable(DOCROOT . $this->_FileManager->getStartLocation() . $_GET['file'])) {
         $div->appendChild(Widget::Input('action[save]', 'Save Changes', 'submit', array('accesskey' => 's')));
         $button = new XMLElement('button', 'Delete');
         $button->setAttributeArray(array('name' => 'action[delete]', 'class' => 'confirm delete', 'title' => 'Delete this ' . ($file->isDir() ? 'Folder' : 'File')));
         $div->appendChild($button);
     } else {
         $notice = new XMLElement('p', 'The server does not have permission to edit this file.');
         $notice->setAttribute('class', 'inactive');
         $div->appendChild($notice);
     }
     $this->Form->appendChild($div);
 }
 /**
  * Themes plugin admin
  */
 public static function main()
 {
     // Get current themes
     $current_site_theme = Option::get('theme_site_name');
     $current_admin_theme = Option::get('theme_admin_name');
     // Init vars
     $themes_site = Themes::getSiteThemes();
     $themes_admin = Themes::getAdminThemes();
     $templates = Themes::getTemplates();
     $chunks = Themes::getChunks();
     $styles = Themes::getStyles();
     $scripts = Themes::getScripts();
     $errors = array();
     $chunk_path = THEMES_SITE . DS . $current_site_theme . DS;
     $template_path = THEMES_SITE . DS . $current_site_theme . DS;
     $style_path = THEMES_SITE . DS . $current_site_theme . DS . 'css' . DS;
     $script_path = THEMES_SITE . DS . $current_site_theme . DS . 'js' . DS;
     // Save site theme
     if (Request::post('save_site_theme')) {
         if (Security::check(Request::post('csrf'))) {
             Option::update('theme_site_name', Request::post('themes'));
             // Clean Monstra TMP folder.
             Monstra::cleanTmp();
             // Increment Styles and Javascript version
             Stylesheet::stylesVersionIncrement();
             Javascript::javascriptVersionIncrement();
             Request::redirect('index.php?id=themes');
         } else {
             die('Request was denied because it contained an invalid security token. Please refresh the page and try again.');
         }
     }
     // Save site theme
     if (Request::post('save_admin_theme')) {
         if (Security::check(Request::post('csrf'))) {
             Option::update('theme_admin_name', Request::post('themes'));
             // Clean Monstra TMP folder.
             Monstra::cleanTmp();
             Request::redirect('index.php?id=themes');
         } else {
             die('Request was denied because it contained an invalid security token. Please refresh the page and try again.');
         }
     }
     // Its mean that you can add your own actions for this plugin
     Action::run('admin_themes_extra_actions');
     // Check for get actions
     // -------------------------------------
     if (Request::get('action')) {
         // Switch actions
         // -------------------------------------
         switch (Request::get('action')) {
             // Add chunk
             // -------------------------------------
             case "add_chunk":
                 if (Request::post('add_file') || Request::post('add_file_and_exit')) {
                     if (Security::check(Request::post('csrf'))) {
                         if (trim(Request::post('name')) == '') {
                             $errors['file_empty_name'] = __('Required field', 'themes');
                         }
                         if (file_exists($chunk_path . Security::safeName(Request::post('name'), null, false) . '.chunk.php')) {
                             $errors['file_exists'] = __('This chunk already exists', 'themes');
                         }
                         if (count($errors) == 0) {
                             // Save chunk
                             File::setContent($chunk_path . Security::safeName(Request::post('name'), null, false) . '.chunk.php', Request::post('content'));
                             Notification::set('success', __('Your changes to the chunk <i>:name</i> have been saved.', 'themes', array(':name' => Security::safeName(Request::post('name'), null, false))));
                             if (Request::post('add_file_and_exit')) {
                                 Request::redirect('index.php?id=themes');
                             } else {
                                 Request::redirect('index.php?id=themes&action=edit_chunk&filename=' . Security::safeName(Request::post('name'), null, false));
                             }
                         }
                     } else {
                         die('Request was denied because it contained an invalid security token. Please refresh the page and try again.');
                     }
                 }
                 // Save fields
                 if (Request::post('name')) {
                     $name = Request::post('name');
                 } else {
                     $name = '';
                 }
                 if (Request::post('content')) {
                     $content = Request::post('content');
                 } else {
                     $content = '';
                 }
                 // Display view
                 View::factory('box/themes/views/backend/add')->assign('name', $name)->assign('content', $content)->assign('errors', $errors)->assign('action', 'chunk')->display();
                 break;
                 // Add template
                 // -------------------------------------
             // Add template
             // -------------------------------------
             case "add_template":
                 if (Request::post('add_file') || Request::post('add_file_and_exit')) {
                     if (Security::check(Request::post('csrf'))) {
                         if (trim(Request::post('name')) == '') {
                             $errors['file_empty_name'] = __('Required field', 'themes');
                         }
                         if (file_exists($template_path . Security::safeName(Request::post('name'), null, false) . '.template.php')) {
                             $errors['file_exists'] = __('This template already exists', 'themes');
                         }
                         if (count($errors) == 0) {
                             // Save chunk
                             File::setContent($template_path . Security::safeName(Request::post('name'), null, false) . '.template.php', Request::post('content'));
                             Notification::set('success', __('Your changes to the chunk <i>:name</i> have been saved.', 'themes', array(':name' => Security::safeName(Request::post('name'), null, false))));
                             if (Request::post('add_file_and_exit')) {
                                 Request::redirect('index.php?id=themes');
                             } else {
                                 Request::redirect('index.php?id=themes&action=edit_template&filename=' . Security::safeName(Request::post('name'), null, false));
                             }
                         }
                     } else {
                         die('Request was denied because it contained an invalid security token. Please refresh the page and try again.');
                     }
                 }
                 // Save fields
                 if (Request::post('name')) {
                     $name = Request::post('name');
                 } else {
                     $name = '';
                 }
                 if (Request::post('content')) {
                     $content = Request::post('content');
                 } else {
                     $content = '';
                 }
                 // Display view
                 View::factory('box/themes/views/backend/add')->assign('name', $name)->assign('content', $content)->assign('errors', $errors)->assign('action', 'template')->display();
                 break;
                 // Add styles
                 // -------------------------------------
             // Add styles
             // -------------------------------------
             case "add_styles":
                 if (Request::post('add_file') || Request::post('add_file_and_exit')) {
                     if (Security::check(Request::post('csrf'))) {
                         if (trim(Request::post('name')) == '') {
                             $errors['file_empty_name'] = __('Required field', 'themes');
                         }
                         if (file_exists($style_path . Security::safeName(Request::post('name'), null, false) . '.css')) {
                             $errors['file_exists'] = __('This styles already exists', 'themes');
                         }
                         if (count($errors) == 0) {
                             // Save chunk
                             File::setContent($style_path . Security::safeName(Request::post('name'), null, false) . '.css', Request::post('content'));
                             Notification::set('success', __('Your changes to the styles <i>:name</i> have been saved.', 'themes', array(':name' => Security::safeName(Request::post('name'), null, false))));
                             // Clean Monstra TMP folder.
                             Monstra::cleanTmp();
                             // Increment Styles version
                             Stylesheet::stylesVersionIncrement();
                             if (Request::post('add_file_and_exit')) {
                                 Request::redirect('index.php?id=themes');
                             } else {
                                 Request::redirect('index.php?id=themes&action=edit_styles&filename=' . Security::safeName(Request::post('name'), null, false));
                             }
                         }
                     } else {
                         die('Request was denied because it contained an invalid security token. Please refresh the page and try again.');
                     }
                 }
                 // Save fields
                 if (Request::post('name')) {
                     $name = Request::post('name');
                 } else {
                     $name = '';
                 }
                 if (Request::post('content')) {
                     $content = Request::post('content');
                 } else {
                     $content = '';
                 }
                 // Display view
                 View::factory('box/themes/views/backend/add')->assign('name', $name)->assign('content', $content)->assign('errors', $errors)->assign('action', 'styles')->display();
                 break;
                 // Add script
                 // -------------------------------------
             // Add script
             // -------------------------------------
             case "add_script":
                 if (Request::post('add_file') || Request::post('add_file_and_exit')) {
                     if (Security::check(Request::post('csrf'))) {
                         if (trim(Request::post('name')) == '') {
                             $errors['file_empty_name'] = __('Required field', 'themes');
                         }
                         if (file_exists($script_path . Security::safeName(Request::post('name'), null, false) . '.js')) {
                             $errors['file_exists'] = __('This script already exists', 'themes');
                         }
                         if (count($errors) == 0) {
                             // Save chunk
                             File::setContent($script_path . Security::safeName(Request::post('name'), null, false) . '.js', Request::post('content'));
                             Notification::set('success', __('Your changes to the script <i>:name</i> have been saved.', 'themes', array(':name' => Security::safeName(Request::post('name'), null, false))));
                             // Clean Monstra TMP folder.
                             Monstra::cleanTmp();
                             // Increment Javascript version
                             Javascript::javascriptVersionIncrement();
                             if (Request::post('add_file_and_exit')) {
                                 Request::redirect('index.php?id=themes');
                             } else {
                                 Request::redirect('index.php?id=themes&action=edit_script&filename=' . Security::safeName(Request::post('name'), null, false));
                             }
                         }
                     } else {
                         die('Request was denied because it contained an invalid security token. Please refresh the page and try again.');
                     }
                 }
                 // Save fields
                 if (Request::post('name')) {
                     $name = Request::post('name');
                 } else {
                     $name = '';
                 }
                 if (Request::post('content')) {
                     $content = Request::post('content');
                 } else {
                     $content = '';
                 }
                 // Display view
                 View::factory('box/themes/views/backend/add')->assign('name', $name)->assign('content', $content)->assign('errors', $errors)->assign('action', 'script')->display();
                 break;
                 // Edit chunk
                 // -------------------------------------
             // Edit chunk
             // -------------------------------------
             case "edit_chunk":
                 // Save current chunk action
                 if (Request::post('edit_file') || Request::post('edit_file_and_exit')) {
                     if (Security::check(Request::post('csrf'))) {
                         if (trim(Request::post('name')) == '') {
                             $errors['file_empty_name'] = __('Required field', 'themes');
                         }
                         if (file_exists($chunk_path . Security::safeName(Request::post('name'), null, false) . '.chunk.php') and Security::safeName(Request::post('chunk_old_name'), null, false) !== Security::safeName(Request::post('name'), null, false)) {
                             $errors['file_exists'] = __('This chunk already exists', 'themes');
                         }
                         // Save fields
                         if (Request::post('content')) {
                             $content = Request::post('content');
                         } else {
                             $content = '';
                         }
                         if (count($errors) == 0) {
                             $chunk_old_filename = $chunk_path . Request::post('chunk_old_name') . '.chunk.php';
                             $chunk_new_filename = $chunk_path . Security::safeName(Request::post('name'), null, false) . '.chunk.php';
                             if (!empty($chunk_old_filename)) {
                                 if ($chunk_old_filename !== $chunk_new_filename) {
                                     rename($chunk_old_filename, $chunk_new_filename);
                                     $save_filename = $chunk_new_filename;
                                 } else {
                                     $save_filename = $chunk_new_filename;
                                 }
                             } else {
                                 $save_filename = $chunk_new_filename;
                             }
                             // Save chunk
                             File::setContent($save_filename, Request::post('content'));
                             Notification::set('success', __('Your changes to the chunk <i>:name</i> have been saved.', 'themes', array(':name' => basename($save_filename, '.chunk.php'))));
                             if (Request::post('edit_file_and_exit')) {
                                 Request::redirect('index.php?id=themes');
                             } else {
                                 Request::redirect('index.php?id=themes&action=edit_chunk&filename=' . Security::safeName(Request::post('name'), null, false));
                             }
                         }
                     } else {
                         die('Request was denied because it contained an invalid security token. Please refresh the page and try again.');
                     }
                 }
                 if (Request::post('name')) {
                     $name = Request::post('name');
                 } else {
                     $name = File::name(Request::get('filename'));
                 }
                 $content = File::getContent($chunk_path . Request::get('filename') . '.chunk.php');
                 // Display view
                 View::factory('box/themes/views/backend/edit')->assign('content', $content)->assign('name', $name)->assign('errors', $errors)->assign('action', 'chunk')->display();
                 break;
                 // Edit Template
                 // -------------------------------------
             // Edit Template
             // -------------------------------------
             case "edit_template":
                 // Save current chunk action
                 if (Request::post('edit_file') || Request::post('edit_file_and_exit')) {
                     if (Security::check(Request::post('csrf'))) {
                         if (trim(Request::post('name')) == '') {
                             $errors['file_empty_name'] = __('Required field', 'themes');
                         }
                         if (file_exists($template_path . Security::safeName(Request::post('name'), null, false) . '.template.php') and Security::safeName(Request::post('template_old_name'), null, false) !== Security::safeName(Request::post('name'), null, false)) {
                             $errors['template_exists'] = __('This template already exists', 'themes');
                         }
                         // Save fields
                         if (Request::post('content')) {
                             $content = Request::post('content');
                         } else {
                             $content = '';
                         }
                         if (count($errors) == 0) {
                             $template_old_filename = $template_path . Request::post('template_old_name') . '.template.php';
                             $template_new_filename = $template_path . Security::safeName(Request::post('name'), null, false) . '.template.php';
                             if (!empty($template_old_filename)) {
                                 if ($template_old_filename !== $template_new_filename) {
                                     rename($template_old_filename, $template_new_filename);
                                     $save_filename = $template_new_filename;
                                 } else {
                                     $save_filename = $template_new_filename;
                                 }
                             } else {
                                 $save_filename = $template_new_filename;
                             }
                             // Save chunk
                             File::setContent($save_filename, Request::post('content'));
                             Notification::set('success', __('Your changes to the template <i>:name</i> have been saved.', 'themes', array(':name' => basename($save_filename, '.template.php'))));
                             if (Request::post('edit_file_and_exit')) {
                                 Request::redirect('index.php?id=themes');
                             } else {
                                 Request::redirect('index.php?id=themes&action=edit_template&filename=' . Security::safeName(Request::post('name'), null, false));
                             }
                         }
                     } else {
                         die('Request was denied because it contained an invalid security token. Please refresh the page and try again.');
                     }
                 }
                 if (Request::post('name')) {
                     $name = Request::post('name');
                 } else {
                     $name = File::name(Request::get('filename'));
                 }
                 $content = File::getContent($chunk_path . Request::get('filename') . '.template.php');
                 // Display view
                 View::factory('box/themes/views/backend/edit')->assign('content', $content)->assign('name', $name)->assign('errors', $errors)->assign('action', 'template')->display();
                 break;
                 // Edit Styles
                 // -------------------------------------
             // Edit Styles
             // -------------------------------------
             case "edit_styles":
                 // Save current chunk action
                 if (Request::post('edit_file') || Request::post('edit_file_and_exit')) {
                     if (Security::check(Request::post('csrf'))) {
                         if (trim(Request::post('name')) == '') {
                             $errors['file_empty_name'] = __('Required field', 'themes');
                         }
                         if (file_exists($style_path . Security::safeName(Request::post('name'), null, false) . '.css') and Security::safeName(Request::post('styles_old_name'), null, false) !== Security::safeName(Request::post('name'), null, false)) {
                             $errors['file_exists'] = __('This styles already exists', 'themes');
                         }
                         // Save fields
                         if (Request::post('content')) {
                             $content = Request::post('content');
                         } else {
                             $content = '';
                         }
                         if (count($errors) == 0) {
                             $styles_old_filename = $style_path . Request::post('styles_old_name') . '.css';
                             $styles_new_filename = $style_path . Security::safeName(Request::post('name'), null, false) . '.css';
                             if (!empty($styles_old_filename)) {
                                 if ($styles_old_filename !== $styles_new_filename) {
                                     rename($styles_old_filename, $styles_new_filename);
                                     $save_filename = $styles_new_filename;
                                 } else {
                                     $save_filename = $styles_new_filename;
                                 }
                             } else {
                                 $save_filename = $styles_new_filename;
                             }
                             // Save chunk
                             File::setContent($save_filename, Request::post('content'));
                             Notification::set('success', __('Your changes to the styles <i>:name</i> have been saved.', 'themes', array(':name' => basename($save_filename, '.css'))));
                             // Clean Monstra TMP folder.
                             Monstra::cleanTmp();
                             // Increment Styles version
                             Stylesheet::stylesVersionIncrement();
                             if (Request::post('edit_file_and_exit')) {
                                 Request::redirect('index.php?id=themes');
                             } else {
                                 Request::redirect('index.php?id=themes&action=edit_styles&filename=' . Security::safeName(Request::post('name'), null, false));
                             }
                         }
                     } else {
                         die('Request was denied because it contained an invalid security token. Please refresh the page and try again.');
                     }
                 }
                 if (Request::post('name')) {
                     $name = Request::post('name');
                 } else {
                     $name = File::name(Request::get('filename'));
                 }
                 $content = File::getContent($style_path . Request::get('filename') . '.css');
                 // Display view
                 View::factory('box/themes/views/backend/edit')->assign('content', $content)->assign('name', $name)->assign('errors', $errors)->assign('action', 'styles')->display();
                 break;
                 // Edit Script
                 // -------------------------------------
             // Edit Script
             // -------------------------------------
             case "edit_script":
                 // Save current chunk action
                 if (Request::post('edit_file') || Request::post('edit_file_and_exit')) {
                     if (Security::check(Request::post('csrf'))) {
                         if (trim(Request::post('name')) == '') {
                             $errors['file_empty_name'] = __('Required field', 'themes');
                         }
                         if (file_exists($script_path . Security::safeName(Request::post('name'), null, false) . '.js') and Security::safeName(Request::post('script_old_name'), null, false) !== Security::safeName(Request::post('name'), null, false)) {
                             $errors['file_exists'] = __('This script already exists', 'themes');
                         }
                         // Save fields
                         if (Request::post('content')) {
                             $content = Request::post('content');
                         } else {
                             $content = '';
                         }
                         if (count($errors) == 0) {
                             $script_old_filename = $script_path . Request::post('script_old_name') . '.js';
                             $script_new_filename = $script_path . Security::safeName(Request::post('name'), null, false) . '.js';
                             if (!empty($script_old_filename)) {
                                 if ($script_old_filename !== $script_new_filename) {
                                     rename($script_old_filename, $script_new_filename);
                                     $save_filename = $script_new_filename;
                                 } else {
                                     $save_filename = $script_new_filename;
                                 }
                             } else {
                                 $save_filename = $script_new_filename;
                             }
                             // Save chunk
                             File::setContent($save_filename, Request::post('content'));
                             Notification::set('success', __('Your changes to the script <i>:name</i> have been saved.', 'themes', array(':name' => basename($save_filename, '.js'))));
                             // Clean Monstra TMP folder.
                             Monstra::cleanTmp();
                             // Increment Javascript version
                             Javascript::javascriptVersionIncrement();
                             if (Request::post('edit_file_and_exit')) {
                                 Request::redirect('index.php?id=themes');
                             } else {
                                 Request::redirect('index.php?id=themes&action=edit_script&filename=' . Security::safeName(Request::post('name'), null, false));
                             }
                         }
                     } else {
                         die('Request was denied because it contained an invalid security token. Please refresh the page and try again.');
                     }
                 }
                 if (Request::post('name')) {
                     $name = Request::post('name');
                 } else {
                     $name = File::name(Request::get('filename'));
                 }
                 $content = File::getContent($script_path . Request::get('filename') . '.js');
                 // Display view
                 View::factory('box/themes/views/backend/edit')->assign('content', $content)->assign('name', $name)->assign('errors', $errors)->assign('action', 'script')->display();
                 break;
                 // Delete chunk
                 // -------------------------------------
             // Delete chunk
             // -------------------------------------
             case "delete_chunk":
                 if (Security::check(Request::get('token'))) {
                     File::delete($chunk_path . Request::get('filename') . '.chunk.php');
                     Notification::set('success', __('Chunk <i>:name</i> deleted', 'themes', array(':name' => File::name(Request::get('filename')))));
                     Request::redirect('index.php?id=themes');
                 } else {
                     die('Request was denied because it contained an invalid security token. Please refresh the page and try again.');
                 }
                 break;
                 // Delete styles
                 // -------------------------------------
             // Delete styles
             // -------------------------------------
             case "delete_styles":
                 if (Security::check(Request::get('token'))) {
                     File::delete($style_path . Request::get('filename') . '.css');
                     Notification::set('success', __('Styles <i>:name</i> deleted', 'themes', array(':name' => File::name(Request::get('filename')))));
                     // Clean Monstra TMP folder.
                     Monstra::cleanTmp();
                     // Increment Styles version
                     Stylesheet::stylesVersionIncrement();
                     Request::redirect('index.php?id=themes');
                 } else {
                     die('Request was denied because it contained an invalid security token. Please refresh the page and try again.');
                 }
                 break;
                 // Delete script
                 // -------------------------------------
             // Delete script
             // -------------------------------------
             case "delete_script":
                 if (Security::check(Request::get('token'))) {
                     File::delete($script_path . Request::get('filename') . '.js');
                     Notification::set('success', __('Script <i>:name</i> deleted', 'themes', array(':name' => File::name(Request::get('filename')))));
                     // Clean Monstra TMP folder.
                     Monstra::cleanTmp();
                     // Increment Javascript version
                     Javascript::javascriptVersionIncrement();
                     Request::redirect('index.php?id=themes');
                 } else {
                     die('Request was denied because it contained an invalid security token. Please refresh the page and try again.');
                 }
                 break;
                 // Delete template
                 // -------------------------------------
             // Delete template
             // -------------------------------------
             case "delete_template":
                 if (Security::check(Request::get('token'))) {
                     File::delete($template_path . Request::get('filename') . '.template.php');
                     Notification::set('success', __('Template <i>:name</i> deleted', 'themes', array(':name' => File::name(Request::get('filename')))));
                     Request::redirect('index.php?id=themes');
                 }
                 break;
                 // Clone styles
                 // -------------------------------------
             // Clone styles
             // -------------------------------------
             case "clone_styles":
                 if (Security::check(Request::get('token'))) {
                     File::setContent(THEMES_SITE . DS . $current_site_theme . DS . 'css' . DS . Request::get('filename') . '_clone_' . date("Ymd_His") . '.css', File::getContent(THEMES_SITE . DS . $current_site_theme . DS . 'css' . DS . Request::get('filename') . '.css'));
                     // Clean Monstra TMP folder.
                     Monstra::cleanTmp();
                     // Increment Styles version
                     Stylesheet::stylesVersionIncrement();
                     Request::redirect('index.php?id=themes');
                 }
                 break;
                 // Clone script
                 // -------------------------------------
             // Clone script
             // -------------------------------------
             case "clone_script":
                 if (Security::check(Request::get('token'))) {
                     File::setContent(THEMES_SITE . DS . $current_site_theme . DS . 'js' . DS . Request::get('filename') . '_clone_' . date("Ymd_His") . '.js', File::getContent(THEMES_SITE . DS . $current_site_theme . DS . 'js' . DS . Request::get('filename') . '.js'));
                     // Clean Monstra TMP folder.
                     Monstra::cleanTmp();
                     // Increment Javascript version
                     Javascript::javascriptVersionIncrement();
                     Request::redirect('index.php?id=themes');
                 }
                 break;
                 // Clone template
                 // -------------------------------------
             // Clone template
             // -------------------------------------
             case "clone_template":
                 if (Security::check(Request::get('token'))) {
                     File::setContent(THEMES_SITE . DS . $current_site_theme . DS . Request::get('filename') . '_clone_' . date("Ymd_His") . '.template.php', File::getContent(THEMES_SITE . DS . $current_site_theme . DS . Request::get('filename') . '.template.php'));
                     Request::redirect('index.php?id=themes');
                 }
                 break;
                 // Clone chunk
                 // -------------------------------------
             // Clone chunk
             // -------------------------------------
             case "clone_chunk":
                 if (Security::check(Request::get('token'))) {
                     File::setContent(THEMES_SITE . DS . $current_site_theme . DS . Request::get('filename') . '_clone_' . date("Ymd_His") . '.chunk.php', File::getContent(THEMES_SITE . DS . $current_site_theme . DS . Request::get('filename') . '.chunk.php'));
                     Request::redirect('index.php?id=themes');
                 }
                 break;
         }
     } else {
         // Display view
         View::factory('box/themes/views/backend/index')->assign('themes_site', $themes_site)->assign('themes_admin', $themes_admin)->assign('templates', $templates)->assign('chunks', $chunks)->assign('styles', $styles)->assign('scripts', $scripts)->assign('current_site_theme', $current_site_theme)->assign('current_admin_theme', $current_admin_theme)->display();
     }
 }
 function __loadDbItems()
 {
     // variable used to determine the read dir time
     $acdate = strtotime("now");
     // check to see whether a valid directory was passed to the script
     if ($this->Session->read('User.dirname_get')) {
         // if it is valid, we'll set it as the directory to read data from
         $this->dirpath = $this->Session->read('User.dirname_get');
     } else {
         // if it is invalid, we'll use the default directory
         $this->dirpath = Configure::read('default_get_dir');
     }
     // use Folder class
     $dir = new Folder($this->dirpath);
     // try to change the current working directory to the one from wich i want to read contents from
     if (!$dir->cd($this->dirpath)) {
         // if the change failed, I'll use the default directory
         $this->dirpath = Configure::read('default_get_dir');
         $dir->cd(Configure::read('default_get_dir'));
     }
     // once the current working directory is set, it is opened and read from
     $dir_listing = $dir->read(true, false, true);
     if ($dir_listing) {
         // while there are still entries
         foreach ($dir_listing[1] as $entry) {
             // if the entry is to be shown (not part of the 'not_to_be_shown' array)
             if (!in_array($entry, Configure::read('not_to_be_shown'))) {
                 $file = new File($entry);
                 if ($file->readable()) {
                     // store the file extension
                     $fext = $file->ext();
                     // store the filename
                     $fname = $file->name;
                     // store the lowercased extension
                     $lfext = strtolower($fext);
                     // store size of file into KB
                     $fsize = round($file->size() / 1024, 2);
                     // store date of file
                     $fidate = $file->lastChange();
                     // store dirpath with file
                     $finfokey = $entry;
                     // store absfilename
                     $fnameabs = $file->name();
                     // define check for filestatus_status (if updated)
                     $update_status = Configure::read('msg_items_file_unselected');
                     // check table fileinfo for update or insert
                     $file_info = $this->FileInfo->find('first', array('conditions' => array('fileinfo_id' => $finfokey), 'fields' => array('fileinfo_id', 'fileinfo_filedate')));
                     if (!empty($file_info)) {
                         $this->FileInfo->read(null, $file_info['FileInfo']['fileinfo_id']);
                         $this->FileInfo->set(array('fileinfo_dirname' => $this->dirpath, 'fileinfo_filename' => $fname, 'fileinfo_absfilename' => $fnameabs, 'fileinfo_ext' => $lfext, 'fileinfo_size' => $fsize, 'fileinfo_filedate' => $fidate, 'fileinfo_timenow' => $acdate));
                         $this->FileInfo->save();
                         // check data modified file is changed
                         if ($fidate > $file_info['FileInfo']['fileinfo_filedate']) {
                             $update_status = Configure::read('msg_items_file_updated');
                         }
                     } else {
                         $this->FileInfo->create();
                         $this->FileInfo->set(array('fileinfo_id' => $finfokey, 'fileinfo_dirname' => $this->dirpath, 'fileinfo_filename' => $fname, 'fileinfo_absfilename' => $fnameabs, 'fileinfo_ext' => $lfext, 'fileinfo_size' => $fsize, 'fileinfo_filedate' => $fidate, 'fileinfo_timenow' => $acdate));
                         $this->FileInfo->save();
                     }
                     // check table filestatus for update or insert
                     $file_status = $this->FileStatus->find('first', array('conditions' => array('filestatus_fileinfo_key' => $finfokey, 'filestatus_users_id' => $this->Session->read('User.id')), 'fields' => array('filestatus_id', 'filestatus_status')));
                     if (!empty($file_status)) {
                         if ($file_status['FileStatus']['filestatus_status'] == Configure::read('msg_items_file_selected') && $update_status != Configure::read('msg_items_file_updated')) {
                             $update_status = Configure::read('msg_items_file_selected');
                         }
                         $this->FileStatus->read(null, $file_status['FileStatus']['filestatus_id']);
                         $this->FileStatus->set(array('filestatus_status' => $update_status, 'filestatus_users_id' => $this->Session->read('User.id'), 'filestatus_timenow' => $acdate));
                         $this->FileStatus->save();
                     } else {
                         $this->FileStatus->create();
                         $this->FileStatus->set(array('filestatus_fileinfo_key' => $finfokey, 'filestatus_status' => $update_status, 'filestatus_users_id' => $this->Session->read('User.id'), 'filestatus_timenow' => $acdate));
                         $this->FileStatus->save();
                     }
                 }
             }
         }
         // check consistency : delete from db files that's removed from directory
         $file_info_del = $this->FileInfo->deleteAll(array('fileinfo_timenow < ' => $acdate));
         if (!$file_info_del) {
             $this->log('DownloadsController:__loadDbItems - Unable delete FileInfo model record', Configure::read('log_file'));
         }
         // check consistency : delete from db files that's removed from directory
         $file_status_del = $this->FileStatus->deleteAll(array('filestatus_timenow < ' => $acdate, 'filestatus_users_id' => $this->Session->read('User.id')));
         if (!$file_status_del) {
             $this->log('DownloadsController:__loadDbItems - Unable delete FileStatus model record', Configure::read('log_file'));
         }
     }
 }
	/**
	 * File clean up process manager
	 *
	 * @return boolean true, if file passes all checks
	 */
	private function cleanFile() {
		$this->file['name'] = $this->cleanFilename($this->file['name']);
		$this->file['width'] = $this->getImageWidth($this->file['tmp_name']);
		$this->file['height'] = $this->getImageHeight($this->file['tmp_name']);
		$this->file['type'] = strtolower($this->file['type']);

		// find the best extension; PHP can figure out what images SHOULD use, or try MIME,
		$extension = '';
		$uploadFile = new File($this->file['name']);
		$supplied_extension = $uploadFile->extension();
		$basename = $uploadFile->name(false);

		if (stripos($this->file['type'], "image/") === 0) {
			$image_extension = $this->getImageExtension($this->file['tmp_name']);

			if ($supplied_extension == $image_extension) {
				// filename's extension matched what PHP thought it should be
				$extension = $image_extension;
			}
			else {
				// mismatch: user uploaded 'foo.gif'; PHP thinks it's a jpg; call it 'foo.gif.jpg'
				$basename  = $basename.'.'.$supplied_extension;
				$extension = $image_extension;
			}
		}
		elseif ($supplied_extension) {
			$extension = $supplied_extension;
		}
		elseif ($this->file['type'] != 'application/octet-stream') {
			// suggest ext, based on MIME, but not for generel type application/octet-stream
			$extension = MimeType::getExtensions($this->file['type'], true);
		}

		// last resort, use default_extenstion by setDefaultExtension()
		if (!$extension) {
			$extension = $this->default_extension;
		}

		// correct file array
		$this->file['extension'] = $extension;
		$this->file['basename'] = $basename;
		$this->file['name'] = $this->file['basename'].'.'.$this->file['extension'];

		return true;
	}
Example #23
0
    // init count to 0
    $count = 0;
    foreach ($scan as $item) {
        // remove storage\$dir
        $item = str_replace(THEMES, '', $item);
        // search query with preg_match
        if (preg_match('/' . urldecode($query) . '/i', $item)) {
            // count +1
            ++$count;
            // template
            $result .= '<li class="list-group-item clearfix">
							' . $item . '
							<a class="btn btn-primary pull-right" href="
							' . $p->Url() . '/action/themes/edit/' . Token::generate() . '/' . base64_encode($directory . $item) . '">
								' . File::name($item) . '.' . File::ext($item) . '
								' . File::name($item) . '
								| <i class="fa fa-arrow-right"></i>
							</a>
						</li>';
        }
    }
    $result .= '</ul>';
    // render view
    $p->view('actions', array('title' => Panel::$lang['Search'], 'html' => '<div class="row">
								<div class="col-lg-6">
									<h3><span class="btn btn-primary">' . $count . '</span>
									results for ' . $query . '</h3>
									' . $result . '
									<a class="btn btn-danger" href="javascript:void(0);" onclick="return history.back(1)">
										' . Panel::$lang['back'] . '
									</a>
Example #24
0
 function getAllModels()
 {
     $Inflector =& Inflector::getInstance();
     uses('Folder');
     $folder = new Folder(MODELS);
     $models = $folder->findRecursive('.*php');
     $folder = new Folder(BEHAVIORS);
     $behaviors = $folder->findRecursive('.*php');
     $models = array_diff($models, $behaviors);
     foreach ($models as $id => $model) {
         $file = new File($model);
         $models[$id] = $file->name();
     }
     $models = array_map(array(&$Inflector, 'camelize'), $models);
     App::import('Model', $models);
     return $models;
 }
Example #25
0
 }
 // get single id of album or all albums
 if (Request::get('action') == 'view' && Request::get('id')) {
     // id of album
     $id = Request::get('id');
     if ($id) {
         // get id on json
         $media = $json[$id];
         // get all images of this album
         $mediaImages = File::scan(ROOT_DIR . $media['images']);
         // get images of this album
         $albumImages = '';
         // check files
         if (count($mediaImages) > 0) {
             foreach ($mediaImages as $image) {
                 $albumImages .= '<img class="thumbnail img-responsive" src="public/media/albums/album_' . $id . '/' . File::name($image) . '.' . File::ext($image) . '">';
             }
         }
         // template
         $templateSingle = '<h3>' . toHtml($media['title']) . '</h3>
         ' . toHtml($media['desc']) . '
         <p><b>Tag: </b><span class="label label-info">' . toHtml($media['tag']) . '</span></p>' . $albumImages;
         // return
         echo $templateSingle;
     }
 } else {
     // all media files
     $templateAll = '';
     foreach ($json as $media) {
         $templateAll .= '<figure>
             <img width="' . $media['width'] . '" height="' . $media['height'] . '" src="' . Config::get('site.site_url') . $media['thumb'] . '"/>
Example #26
0
                            // redirect to edit index
                            request::redirect($p->url() . '/backups');
                        } else {
                            // if exists
                            $error = '<span class="well red">' . Panel::$lang['File_Name_Exists'] . '</span>';
                        }
                    } else {
                        // if empty input value
                        $error = '<span class="well red">' . Panel::$lang['File_Name_Required'] . '</span>';
                    }
                } else {
                    die('crsf detect');
                }
            }
            // template
            $p->view('actions', array('title' => Panel::$lang['Rename_File'], 'content' => $filename, 'html' => '<div class="info">
                    <form method="post">
                      <input type="hidden" name="token" value="' . Token::generate() . '">
                      <label>' . Panel::$lang['Rename_File'] . ' :<code>' . File::name(base64_decode($file)) . '</code></label>
                      <input type="text" name="rename_file_name" value="' . File::name(base64_decode($file)) . '" required>
                      <input class="btn blue" type="submit" name="rename" value="' . Panel::$lang['Rename_File'] . '">
                      <a class="btn red" href="' . $p->url() . '/backups">' . Panel::$lang['Cancel'] . '</a>
                    </form>
                    <br>
                    ' . $error . '
                  </div>'));
        } else {
            die('crsf Detect');
        }
    }
});
Example #27
0
    return ['code' => strtoupper($faker->bothify('??##??#?')), 'style' => rand(0, 4) ? ucwords(join(' ', $faker->words(rand(1, 4)))) : '', 'description' => $faker->paragraph, 'specs' => collect($specs)];
});
$factory->define(App\File::class, function (Faker\Generator $faker) {
    $generated = $faker->file('/tmp', storage_path());
    $filename = \File::name($generated) . '.pdf';
    $filepath = public_path() . '/files/' . $filename;
    $saved = \File::move($generated, $filepath);
    return ['path' => 'files/' . $filename, 'mime' => \File::mimeType($filepath), 'extension' => \File::extension($filepath), 'size' => \File::size($filepath)];
});
$factory->define(App\SafetyDataSheet::class, function (Faker\Generator $faker) {
    return ['title' => ucwords(join(' ', $faker->words(rand(1, 4))))];
});
$factory->define(App\DataSheet::class, function (Faker\Generator $faker) {
    return ['title' => ucwords(join(' ', $faker->words(rand(1, 4))))];
});
$factory->define(App\Brochure::class, function (Faker\Generator $faker) {
    return ['title' => ucwords(join(' ', $faker->words(rand(1, 4))))];
});
$factory->define(App\Image::class, function (Faker\Generator $faker) {
    $file = new App\File();
    $generated = $faker->image('/tmp', 1024, 768);
    $filename = \File::name($generated) . '.' . \File::extension($generated);
    $filepath = public_path() . '/files/' . $filename;
    $saved = \File::move($generated, $filepath);
    $fileEntity = App\File::create(['path' => 'files/' . $filename, 'mime' => \File::mimeType($filepath), 'extension' => \File::extension($filepath), 'size' => \File::size($filepath)]);
    return ['title' => ucwords(join(' ', $faker->words(rand(1, 4)))), 'file_id' => $fileEntity->id];
});
$factory->define(App\Industry::class, function (Faker\Generator $faker) {
    $name = ucwords(join(' ', $faker->words(rand(1, 4))));
    return ['name' => $name, 'slug' => str_slug($name)];
});
Example #28
0
 function attachFile($source)
 {
     /** @var Model $this */
     \DB::beginTransaction();
     try {
         if ($source instanceof UploadedFile) {
             //                $source    = new UploadedFile(1, 1);
             $ext = $source->getClientOriginalExtension();
             $file_name = mb_substr($source->getClientOriginalName(), 0, 0 - mb_strlen($ext) - 1);
         } else {
             $ext = \File::extension($source);
             $file_name = \File::name($source);
         }
         $ext = mb_strtolower($ext);
         $tmp = file_get_contents($source);
         $tmp_name = storage_path('/attaches/' . date('Y_m_d_H-i-s') . '/' . \Str::slug($this->getMorphClass()) . '.' . $ext);
         if (!file_exists(dirname($tmp_name))) {
             mkdir(dirname($tmp_name), 0777, true);
         }
         file_put_contents($tmp_name, $tmp);
         unset($tmp);
         if (!file_exists($tmp_name)) {
             throw new Exception(laralang('larakit::attach.errors.exists', ['file' => larasafepath($tmp_name)]));
         }
         $attach = Attach\Attach::fromModel($this);
         $config = $this->attachConfig();
         //проверка на максимальный размер
         $maxsize = Arr::get($config, 'maxsize');
         $size = \File::size($tmp_name);
         if ($maxsize < $size) {
             throw new Exception(laralang('larakit::attach.errors.maxsize', ['maxsize' => HelperText::fileSize($maxsize, 0)]));
         }
         //проверка на разрешенные EXT
         $enabled_exts = Arr::get($config, 'ext');
         if (!in_array($ext, $enabled_exts)) {
             throw new Exception(laralang('larakit::attach.errors.ext', ['enabled_exts' => implode(', ', $enabled_exts)]));
         }
         //проверка на разрешенные MIME
         $expected_mimes = HelperFile::mimes_by_ext($ext);
         $mime = HelperFile::mime($tmp_name);
         if (!in_array($mime, $expected_mimes)) {
             throw new Exception(laralang('larakit::attach.errors.ext', ['enabled_exts' => implode(', ', $enabled_exts)]));
         }
         $img = getimagesize($tmp_name);
         if (false !== $img) {
             $this->attach_w = Arr::get($img, 0);
             $this->attach_h = Arr::get($img, 1);
         }
         $this->attach_user_id = Me::id();
         $this->attach_ext = $ext;
         $this->attach_size = $size;
         $this->attach_mime = $mime;
         $this->attach_file = $file_name . '.' . $ext;
         $this->attach_name = $file_name;
         $this->save();
         $attach->setId($this->id)->processing($tmp_name);
         \DB::commit();
         $val = true;
     } catch (\Exception $e) {
         \DB::rollBack();
         $val = $e->getMessage();
     }
     if (file_exists($tmp_name)) {
         if (false !== mb_strpos($source, '//')) {
             unlink($tmp_name);
         }
     }
     return $val;
 }
 function admin_delete($file = '')
 {
     $args = func_get_args();
     $file = $this->_argsToFilePath($args);
     $file = new File($file);
     if ($file->delete()) {
         $this->Session->setFlash(__('Il file ' . $file->name() . ' è stato eliminato', true));
     } else {
         $this->Session->setFlash(__('Il file ' . $file->name() . ' non è stato eliminato a casua di un errore', true));
     }
     $this->redirect($this->referer());
 }
 /**
  * Callback
  *
  * Deletes file corresponding to record as well as generated versions of that file.
  *
  * If the file couldn't be deleted the callback won't stop the
  * delete operation to continue to delete the record.
  *
  * @param Model $Model
  * @param boolean $cascade
  * @return boolean
  */
 function beforeDelete(&$Model, $cascade = true)
 {
     extract($this->settings[$Model->alias]);
     $query = array('conditions' => array('id' => $Model->id), 'fields' => array('dirname', 'basename'), 'recursive' => -1);
     $result = $Model->find('first', $query);
     if (empty($result)) {
         return false;
         /* Record did not pass verification? */
     }
     $file = $baseDirectory;
     $file .= $result[$Model->alias]['dirname'];
     $file .= DS . $result[$Model->alias]['basename'];
     $File = new File($file);
     $Folder = new Folder($filterDirectory);
     list($versions, ) = $Folder->ls();
     foreach ($versions as $version) {
         $Folder->cd($filterDirectory . $version . DS . $result[$Model->alias]['dirname'] . DS);
         $basenames = $Folder->find($File->name() . '\\..*');
         if (count($basenames) > 1) {
             $message = "MediaBehavior::beforeDelete - Ambiguous filename ";
             $message .= "`" . $File->name() . "` in `" . $Folder->pwd() . "`.";
             trigger_error($message, E_USER_NOTICE);
             continue;
         } elseif (!isset($basenames[0])) {
             continue;
         }
         $FilterFile = new File($Folder->pwd() . $basenames[0]);
         $FilterFile->delete();
     }
     $File->delete();
     return true;
 }