Example #1
0
 function admin_upload_photo($image = null)
 {
     $path = "img\\products\\";
     $dir = WWW_ROOT . $path;
     //trenutna lokacija slike
     $imageTmp = $image['Product']['file']['tmp_name'];
     $imageName = $image['Product']['file']['name'];
     $file = new File($imageTmp);
     //preverjanje koncnic za sliko
     $ext = $file->ext();
     /*  
     	    if($ext != 'jpg' || $ext != 'jpeg' || $ext != 'png' || $ext != 'gif'){
     	        pr('Wrong extension - ');
     	        print_r($file);
     	        die;
     	        return false;
     	    }*/
     $fileData = $file->read();
     $file->close();
     //zapis v nov fajl
     $file = new File($dir . $imageName, true);
     $file->write($fileData);
     $file->close();
     //nastavitev pd_image na ime slike (ker je se vedno array())
     return $imageName;
 }
 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 #3
0
 /**
  * Reads a MagicDb from various formats
  *
  * @var $magicDb mixed Can be an array containing the db, a magic db as a string, or a filename pointing to a magic db in .db or magic.db.php format
  * @return boolean Returns false if reading / validation failed or true on success.
  * @access private
  */
 public function read($magicDb = null)
 {
     if (!is_string($magicDb) && !is_array($magicDb)) {
         return false;
     }
     if (is_array($magicDb) || strpos($magicDb, '# FILE_ID DB') === 0) {
         $data = $magicDb;
     } else {
         $File = new File($magicDb);
         if (!$File->exists()) {
             return false;
         }
         if ($File->ext() == 'php') {
             include $File->pwd();
             $data = $magicDb;
         } else {
             // @TODO: Needs test coverage
             $data = $File->read();
         }
     }
     $magicDb = $this->toArray($data);
     if (!$this->validates($magicDb)) {
         return false;
     }
     return !!($this->db = $magicDb);
 }
Example #4
0
 /**
  * ImageHelper::findByExtention()
  *
  * @param mixed $extention
  * @return
  */
 function findByChildren($children = array())
 {
     $images = Configure::read('CoreImages.images');
     if (empty($children[1])) {
         return $this->Html->image(Configure::read('CoreImages.path') . 'folders/' . $images['folders']['empty'], $this->settings + array('title' => __('Empty Folder'), 'alt' => __('Empty Folder')));
     }
     App::import('File');
     foreach ($children[1] as $child) {
         $File = new File($child);
         $ext = $File->ext();
         if (!isset($data[$ext])) {
             $data[$ext] = 0;
             continue;
         }
         $data[$ext]++;
         unset($File);
     }
     $highest = 0;
     $_ext = '';
     foreach ($data as $k => $v) {
         if ($v > $highest) {
             $highest = $v;
             $_ext = $k;
         }
     }
     return $this->findByExtention($_ext);
 }
Example #5
0
 /**
  * Determine the format of given database
  *
  * @param mixed $db
  */
 function format($db)
 {
     if (empty($db)) {
         return null;
     }
     if (is_array($db)) {
         return 'Array';
     }
     if (!is_string($db)) {
         return null;
     }
     $File = new File($db);
     if ($File->exists()) {
         if ($File->ext() === 'php') {
             return 'PHP';
         }
         $File->open('rb');
         $head = $File->read(4096);
         if (preg_match('/^(\\d{2}:)?[-\\w.+]*\\/[-\\w.+]+:[\\*\\.a-zA-Z0-9]*$/m', $head)) {
             return 'Freedesktop Shared MIME-info Database';
         } elseif (preg_match('/^[-\\w.+]*\\/[-\\w.+]+\\s+[a-zA-Z0-9]*$/m', $head)) {
             return 'Apache Module mod_mime';
         }
     }
     return null;
 }
 protected function file_extension($value, $params)
 {
     $allowed_exts = $params['extension'];
     $f = new File($value['name']);
     $problems = array();
     if (is_array($allowed_exts)) {
         if (!in_array(strtolower($f->ext()), $allowed_exts)) {
             $problems[] = 'A extensão do arquivo deve ser ' . join(',', $allowed_exts);
         }
     } else {
         if ($f->ext() != $allowed_exts) {
             $problems[] = 'A extensão do arquivo deve ser ' . $allowed_exts;
         }
     }
     if (count($problems) == 0) {
         return false;
     }
     return $problems;
 }
Example #7
0
 /**
  * Evalute a view file, rendering it's contents
  *
  * @return string The output
  */
 protected function _evaluate($viewFile, $dataForView)
 {
     $file = new File($viewFile);
     if ($file->ext() != self::$extension) {
         return parent::_evaluate($viewFile, $dataForView);
     }
     $file = $this->_createRenderedView($viewFile);
     $content = parent::_evaluate($file, $dataForView);
     $this->_deleteRenderedView($file);
     return $content;
 }
Example #8
0
 /**
  *
  * @param  $data
  * @return bool
  */
 function validate_file($data)
 {
     try {
         $file_name = $data['upload']['name'];
         if (!empty($file_name)) {
             $tempFile = new File($file_name);
             $ext = $tempFile->ext();
             $ext = strtolower($ext);
             $types = array("gif", "jpg", "jpeg", "png", "pjpeg", "x-png", "x-tiff");
             $val = in_array($ext, $types, true);
             if ($val) {
                 return true;
             }
             return false;
         }
         return true;
     } catch (Exception $exception) {
         echo $exception->getMessage();
     }
 }
Example #9
0
 protected function __new__($file_path)
 {
     $this->cmd = def("arbo.io.FFmpeg@cmd", "/usr/local/bin/ffmpeg");
     $info = Command::error(sprintf("%s -i %s", $this->cmd, $file_path));
     $file = new File($file_path);
     $this->name = $file->oname();
     $this->ext = $file->ext();
     $this->filename = $file_path;
     $this->framerate = preg_match("/frame rate: .+ -> ?([\\d\\.]+)/", $info, $match) ? (double) $match[1] : null;
     $this->bitrate = preg_match("/bitrate: (\\d+)/", $info, $match) ? (double) $match[1] : null;
     $this->duration = preg_match("/Duration: ([\\d\\:\\.]+)/", $info, $match) ? Date::parse_time($match[1]) : null;
     if (preg_match("/Video: (.+)/", $info, $match)) {
         $video = explode(",", $match[1]);
         if (isset($video[0])) {
             $this->video_codec = trim($video[0]);
         }
         if (isset($video[1])) {
             $this->format = trim($video[1]);
         }
         if (isset($video[2])) {
             list($this->width, $this->height) = explode("x", trim($video[2]));
             if (preg_match("/(\\d+) .+DAR (\\d+\\:\\d+)/", $this->height, $match)) {
                 list(, $this->height, $this->aspect) = $match;
             }
         }
         if (empty($this->aspect) && isset($video[3])) {
             $this->aspect = preg_match("/DAR (\\d+\\:\\d+)/", $video[3], $match) ? $match[1] : null;
         }
     }
     if (preg_match("/Audio: (.+)/", $info, $match)) {
         $audio = explode(",", $match[1]);
         if (isset($audio[0])) {
             $this->audio_codec = trim($audio[0]);
         }
         if (isset($audio[1])) {
             $this->samplerate = preg_match("/\\d+/", $audio[1], $match) ? $match[0] : null;
         }
     }
     $this->frame_count = ceil($this->duration * $this->framerate);
 }
 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 uploadPhoto($data)
 {
     $validtypes = array('png', 'gif', 'jpg', 'jpeg', 'pjpeg', 'bmp');
     $filetype = substr($data['photo']['type'], 6);
     if (in_array($filetype, $validtypes)) {
         $this->deletePhoto();
         // Delete previous photo.
         $tmp_file = new File($data['photo']['tmp_name']);
         if ($filetype == 'jpeg' || $filetype == 'pjpeg') {
             $filetype = 'jpg';
         }
         $filename = 'img/users/' . AuthComponent::user('username') . '.' . $filetype;
         $file = new File($filename, true);
         $file->write($tmp_file->read());
         // Write new photo.
         if ($file->executable() || !in_array($file->ext(), $validtypes)) {
             $file->delete();
             return false;
         }
         return true;
     }
     return false;
 }
Example #12
0
 static function import()
 {
     #>> import modules
     foreach (func_get_args() as $unit) {
         # get the real file name
         $unit = ABS_PATH . str_replace('.', '/', $unit);
         # get the dir from the unit name
         $dir = dirname($unit);
         # imports all the php scripts from the dir
         if (substr($unit, -1) == '*' && ($dh = opendir($dir))) {
             while (($file = readdir($dh)) !== false) {
                 if (File::ext($file) == 'php') {
                     # import the script
                     require_once $dir . '/' . $file;
                 }
             }
             closedir($dh);
         } else {
             if (is_file($unit .= '.php')) {
                 require_once $unit;
             }
         }
     }
 }
Example #13
0
 /**
  * Determine the format of given database
  *
  * @param mixed $db
  */
 function format($db)
 {
     if (empty($db)) {
         return null;
     }
     if (is_array($db)) {
         return 'Array';
     }
     if (!is_string($db)) {
         return null;
     }
     $File = new File($db);
     if ($File->exists()) {
         if ($File->ext() === 'php') {
             return 'PHP';
         }
         $File->open('rb');
         $head = $File->read(4096);
         if (substr($head, 0, 12) === "MIME-Magic\n") {
             return 'Freedesktop Shared MIME-info Database';
         }
         if (preg_match('/^(\\>*)(\\d+)\\t+(\\S+)\\t+([\\S^\\040]+)\\t*([-\\w.\\+]+\\/[-\\w.\\+]+)*\\t*(\\S*)$/m', $head)) {
             return 'Apache Module mod_mime_magic';
         }
     }
     return null;
 }
Example #14
0
 /**
  * Setup for display or download the given file.
  *
  * If $_SERVER['HTTP_RANGE'] is set a slice of the file will be
  * returned instead of the entire file.
  *
  * ### Options keys
  *
  * - name: Alternate download name
  * - download: If `true` sets download header and forces file to be downloaded rather than displayed in browser
  *
  * @param string $path Path to file. If the path is not an absolute path that resolves
  *   to a file, `APP` will be prepended to the path.
  * @param array $options Options See above.
  * @return void
  * @throws NotFoundException
  */
 public function file($path, $options = array())
 {
     $options += array('name' => null, 'download' => null);
     if (strpos($path, '../') !== false || strpos($path, '..\\') !== false) {
         throw new NotFoundException(__d('cake_dev', 'The requested file contains `..` and will not be read.'));
     }
     if (!is_file($path)) {
         $path = APP . $path;
     }
     $file = new File($path);
     if (!$file->exists() || !$file->readable()) {
         if (Configure::read('debug')) {
             throw new NotFoundException(__d('cake_dev', 'The requested file %s was not found or not readable', $path));
         }
         throw new NotFoundException(__d('cake', 'The requested file was not found'));
     }
     $extension = strtolower($file->ext());
     $download = $options['download'];
     if ((!$extension || $this->type($extension) === false) && $download === null) {
         $download = true;
     }
     $fileSize = $file->size();
     if ($download) {
         $agent = env('HTTP_USER_AGENT');
         if (preg_match('%Opera(/| )([0-9].[0-9]{1,2})%', $agent)) {
             $contentType = 'application/octet-stream';
         } elseif (preg_match('/MSIE ([0-9].[0-9]{1,2})/', $agent)) {
             $contentType = 'application/force-download';
         }
         if (!empty($contentType)) {
             $this->type($contentType);
         }
         if ($options['name'] === null) {
             $name = $file->name;
         } else {
             $name = $options['name'];
         }
         $this->download($name);
         $this->header('Content-Transfer-Encoding', 'binary');
     }
     $this->header('Accept-Ranges', 'bytes');
     $httpRange = env('HTTP_RANGE');
     if (isset($httpRange)) {
         $this->_fileRange($file, $httpRange);
     } else {
         $this->header('Content-Length', $fileSize);
     }
     $this->_clearBuffer();
     $this->_file = $file;
 }
Example #15
0
 /**
  * Clean the generated CSS files
  *
  * @return array
  */
 public function cleanGeneratedCss()
 {
     $this->_removeCacheKey('sass_compiled');
     // Cleaned files that we will return
     $cleanedFiles = array();
     foreach ($this->_sassFolders as $key => $sassFolder) {
         foreach ($sassFolder->find() as $file) {
             $file = new File($file);
             if (($file->ext() == 'sass' || $file->ext() == 'scss') && substr($file->name, 0, 2) !== '._') {
                 $sassFile = $sassFolder->path . DS . $file->name;
                 $cssFile = $this->_cssFolders[$key]->path . DS . str_replace(array('.sass', '.scss'), '.css', $file->name);
                 if (file_exists($cssFile)) {
                     unlink($cssFile);
                     $cleanedFiles[] = $cssFile;
                 }
             }
         }
     }
     // Remove all cache files at once
     if (is_dir($this->_cacheFolder)) {
         @closedir($this->_cacheFolder);
         $folder = new Folder($this->_cacheFolder);
         $folder->delete();
         unset($folder);
         $cleanedFiles[] = $this->_cacheFolder . DS . '*';
     }
     mkdir($this->_cacheFolder);
     return $cleanedFiles;
 }
Example #16
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'] . '"/>
 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'));
         }
     }
 }
Example #18
0
 public function add_misp_export()
 {
     if (!$this->userRole['perm_modify']) {
         throw new UnauthorizedException('You do not have permission to do that.');
     }
     if ($this->request->is('post')) {
         if (!empty($this->data)) {
             $ext = '';
             if (isset($this->data['Event']['submittedfile'])) {
                 App::uses('File', 'Utility');
                 $file = new File($this->data['Event']['submittedfile']['name']);
                 $ext = $file->ext();
             }
             if (isset($this->data['Event']['submittedfile']) && ($ext != 'xml' && $ext != 'json') && $this->data['Event']['submittedfile']['size'] > 0 && is_uploaded_file($this->data['Event']['submittedxml']['tmp_name'])) {
                 $this->Session->setFlash(__('You may only upload MISP XML or MISP JSON files.'));
             }
             if (isset($this->data['Event']['submittedfile'])) {
                 if (Configure::read('MISP.take_ownership_xml_import') && (isset($this->data['Event']['takeownership']) && $this->data['Event']['takeownership'] == 1)) {
                     $results = $this->_addMISPExportFile($ext, true);
                 } else {
                     $results = $this->_addMISPExportFile($ext);
                 }
             }
         }
         $this->set('results', $results);
         $this->render('add_misp_export_result');
     }
 }
Example #19
0
 /**
  * Setup for display or download the given file
  *
  * @param string $path Path to file
  * @param array $options Options
  *	### Options keys
  *	- name: Alternate download name
  *	- download: If `true` sets download header and forces file to be downloaded rather than displayed in browser
  * @return void
  * @throws NotFoundException
  */
 public function file($path, $options = array())
 {
     $options += array('name' => null, 'download' => null);
     if (!is_file($path)) {
         $path = APP . $path;
     }
     $file = new File($path);
     if (!$file->exists() || !$file->readable()) {
         if (Configure::read('debug')) {
             throw new NotFoundException(__d('cake_dev', 'The requested file %s was not found or not readable', $path));
         }
         throw new NotFoundException(__d('cake', 'The requested file was not found'));
     }
     $extension = strtolower($file->ext());
     $download = $options['download'];
     if ((!$extension || $this->type($extension) === false) && is_null($download)) {
         $download = true;
     }
     $fileSize = $file->size();
     if ($download) {
         $agent = env('HTTP_USER_AGENT');
         if (preg_match('%Opera(/| )([0-9].[0-9]{1,2})%', $agent)) {
             $contentType = 'application/octetstream';
         } elseif (preg_match('/MSIE ([0-9].[0-9]{1,2})/', $agent)) {
             $contentType = 'application/force-download';
         }
         if (!empty($contentType)) {
             $this->type($contentType);
         }
         if (is_null($options['name'])) {
             $name = $file->name;
         } else {
             $name = $options['name'];
         }
         $this->download($name);
         $this->header('Accept-Ranges', 'bytes');
         $httpRange = env('HTTP_RANGE');
         if (isset($httpRange)) {
             list(, $range) = explode('=', $httpRange);
             $size = $fileSize - 1;
             $length = $fileSize - $range;
             $this->header(array('Content-Length' => $length, 'Content-Range' => 'bytes ' . $range . $size . '/' . $fileSize));
             $this->statusCode(206);
             $file->open('rb', true);
             $file->offset($range);
         } else {
             $this->header('Content-Length', $fileSize);
         }
     } else {
         $this->header('Content-Length', $fileSize);
     }
     $this->_clearBuffer();
     $this->_file = $file;
 }
Example #20
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 #21
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;
 }
Example #22
0
 public function addIOC($id)
 {
     $this->Event->recursive = -1;
     $this->Event->read(null, $id);
     if (!$this->_isSiteAdmin() && ($this->Event->data['Event']['orgc'] != $this->_checkOrg() || !$this->userRole['perm_modify'])) {
         throw new UnauthorizedException('You do not have permission to do that.');
     }
     if ($this->request->is('post')) {
         if (!empty($this->data)) {
             $ext = '';
             if (isset($this->data['Event']['submittedioc'])) {
                 App::uses('File', 'Utility');
                 $file = new File($this->data['Event']['submittedioc']['name']);
                 $ext = $file->ext();
             }
             if (isset($this->data['Event']['submittedioc']) && $ext != 'ioc' && $this->data['Event']['submittedioc']['size'] > 0 && is_uploaded_file($this->data['Event']['submittedioc']['tmp_name'])) {
                 $this->Session->setFlash(__('You may only upload OpenIOC ioc files.'));
             }
             if (isset($this->data['Event']['submittedioc'])) {
                 $this->_addIOCFile($id);
             }
             // redirect to the view of the newly created event
             if (!CakeSession::read('Message.flash')) {
                 $this->Session->setFlash(__('The event has been saved'));
             } else {
                 $existingFlash = CakeSession::read('Message.flash');
                 $this->Session->setFlash(__('The event has been saved. ' . $existingFlash['message']));
             }
         }
     }
     // combobox for distribution
     $distributions = array_keys($this->Event->distributionDescriptions);
     $distributions = $this->_arrayToValuesIndexArray($distributions);
     $this->set('distributions', $distributions);
     // tooltip for distribution
     $this->set('distributionDescriptions', $this->Event->distributionDescriptions);
     $this->set('distributionLevels', $this->Event->distributionLevels);
     // combobox for risks
     $risks = $this->Event->validate['risk']['rule'][1];
     $risks = $this->_arrayToValuesIndexArray($risks);
     $this->set('risks', $risks);
     // set the id
     $this->set('id', $id);
     // set whether it is published or not
     $this->set('published', $this->Event->data['Event']['published']);
     // tooltip for risk
     $this->set('riskDescriptions', $this->Event->riskDescriptions);
     // combobox for analysis
     $analysiss = $this->Event->validate['analysis']['rule'][1];
     $analysiss = $this->_arrayToValuesIndexArray($analysiss);
     $this->set('analysiss', $analysiss);
     // tooltip for analysis
     $this->set('analysisDescriptions', $this->Event->analysisDescriptions);
     $this->set('analysisLevels', $this->Event->analysisLevels);
     $this->set('eventDescriptions', $this->Event->fieldDescriptions);
 }
Example #23
0
 /**
  * Get the File name
  *
  *  <code>
  *      echo File::name('filename.txt');
  *  </code>
  *
  * @param  string $filename The file name
  * @return string
  */
 public static function name($filename)
 {
     // Redefine vars
     $filename = (string) $filename;
     // Return filename
     return basename($filename, '.' . File::ext($filename));
 }
 /**
  * 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'));
 }
Example #25
0
<?php

$MODULE = array('script' => function () {
    $path = post('path');
    $FILE = new File($path);
    if ($FILE->ext() != 'sh') {
        throw new Exception('Not a .sh');
    }
    $script = $FILE->path;
    return shell_exec("\"{$script}\"");
    // return shell_exec("ps -x");
});
Example #26
0
 function document()
 {
     if (!Configure::read('feature.documents')) {
         $this->Session->setFlash(__('Document management is disabled on this site.', true), 'default', array('class' => 'info'));
         $this->redirect('/');
     }
     $id = $this->_arg('id');
     if (!$id) {
         $this->Session->setFlash(sprintf(__('Invalid %s', true), __('document', true)), 'default', array('class' => 'info'));
         $this->redirect('/');
     }
     $file_dir = Configure::read('folders.uploads');
     $this->Person->Upload->contain(array('Person', 'UploadType'));
     $document = $this->Person->Upload->read(null, $id);
     if (!$document) {
         $this->Session->setFlash(sprintf(__('Invalid %s', true), __('document', true)), 'default', array('class' => 'info'));
         $this->redirect('/');
     }
     if (!$this->is_admin && $document['Upload']['person_id'] != $this->UserCache->currentId()) {
         $this->Session->setFlash(__('You do not have permission to access this document.', true), 'default', array('class' => 'warning'));
         $this->redirect('/');
     }
     $this->view = 'Media';
     $f = new File($document['Upload']['filename']);
     $this->set(array('path' => $file_dir . DS, 'id' => $document['Upload']['filename'], 'extension' => $f->ext(), 'name' => $f->info['filename'], 'mimeType' => Configure::read('new_mime_types'), 'download' => !in_array($f->ext(), Configure::read('no_download_extensions'))));
 }
 /**
  * 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);
 }
Example #28
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 #29
0
 public function add_xml()
 {
     if (!$this->userRole['perm_modify']) {
         throw new UnauthorizedException('You do not have permission to do that.');
     }
     if ($this->request->is('post')) {
         if (!empty($this->data)) {
             $ext = '';
             if (isset($this->data['Event']['submittedxml'])) {
                 App::uses('File', 'Utility');
                 $file = new File($this->data['Event']['submittedxml']['name']);
                 $ext = $file->ext();
             }
             if (isset($this->data['Event']['submittedxml']) && $ext != 'xml' && $this->data['Event']['submittedxml']['size'] > 0 && is_uploaded_file($this->data['Event']['submittedxml']['tmp_name'])) {
                 $this->Session->setFlash(__('You may only upload MISP XML files.'));
             }
             if (isset($this->data['Event']['submittedxml'])) {
                 if (Configure::read('MISP.take_ownership_xml_import') && (isset($this->data['Event']['takeownership']) && $this->data['Event']['takeownership'] == 1)) {
                     $this->_addXMLFile(true);
                 } else {
                     $this->_addXMLFile();
                 }
             }
             // redirect to the view of the newly created event
             if (!CakeSession::read('Message.flash')) {
                 $this->Session->setFlash(__('The event has been saved'));
             } else {
                 $existingFlash = CakeSession::read('Message.flash');
                 $this->Session->setFlash(__('The event has been saved. ' . $existingFlash['message']));
             }
         }
     }
 }
Example #30
0
 if (Token::check($token)) {
     // directory
     $filename = base64_decode($file);
     // error
     $error = '';
     // submit function
     if (Request::post('rename')) {
         // check token
         if (Token::check(Request::post('token'))) {
             // if empty
             if (Request::post('rename_file_name') !== '') {
                 $to = str_replace(File::name($filename) . '.' . File::ext($filename), '', $filename);
                 // if exists
                 if (!File::exists($to . Request::post('rename_file_name') . '.' . File::ext($filename))) {
                     // rename file
                     File::rename($filename, $to . '/' . $p->SeoLink(Request::post('rename_file_name')) . '.' . File::ext($filename));
                     // set notification
                     $p->setMsg($p::$lang['Success_rename']);
                     // 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');
         }