Example #1
0
 function replace($path)
 {
     $F = new File($path);
     $md5 = $F->md5();
     $this->path = appPATH . 'qg/file/' . $md5;
     $F->copy($this->path);
     $this->setVs(array('name' => $F->basename(), 'mime' => $F->mime(), 'text' => $F->getText(), 'md5' => $F->md5(), 'size' => $F->size()));
 }
Example #2
0
 /**
  * return an array of all controllers hashes
  *
  * @return array
  */
 public function get_current_controllers_hashes()
 {
     $controllers = $this->AclReflector->get_all_controllers();
     $current_controller_hashes = array();
     foreach ($controllers as $controller) {
         $ctler_file = new File($controller['file']);
         $current_controller_hashes[$controller['name']] = $ctler_file->md5();
     }
     return $current_controller_hashes;
 }
 /**
  * Retrieve (cached) metadata of a file
  *
  * @param Model $Model
  * @param string $file An absolute path to a file
  * @param integer $level level of amount of info to add, `0` disable, `1` for basic, `2` for detailed info
  * @return mixed Array with results or false if file is not readable
  */
 function metadata(&$Model, $file, $level = 1)
 {
     if ($level < 1) {
         return array();
     }
     extract($this->settings[$Model->alias]);
     $File = new File($file);
     if (!$File->readable()) {
         return false;
     }
     $checksum = $File->md5(true);
     if (isset($this->__cached[$Model->alias][$checksum])) {
         $data = $this->__cached[$Model->alias][$checksum];
     }
     if ($level > 0 && !isset($data[1])) {
         $data[1] = array('size' => $File->size(), 'mime_type' => Mime_Type::guessType($File->pwd()), 'checksum' => $checksum);
     }
     if ($level > 1 && !isset($data[2])) {
         $data[2] = array();
         try {
             $Info = Media_Info::factory(array('source' => $File->pwd()));
             foreach ($Info->all() as $key => $value) {
                 $data[2][Inflector::underscore($key)] = $value;
             }
         } catch (Exception $E) {
         }
     }
     for ($i = $level, $result = array(); $i > 0; $i--) {
         $result = array_merge($result, $data[$i]);
     }
     $this->__cached[$Model->alias][$checksum] = $data;
     return $result;
 }
Example #4
0
 /**
  * add_attachment method
  *
  * @return void
  */
 public function uploadAttachment($fileP, $realFileName, $malware, $eventId = null, $category = null, $extraPath = '', $fullFileName = '', $dist, $fromGFI = false)
 {
     // Check if there were problems with the file upload
     // only keep the last part of the filename, this should prevent directory attacks
     $filename = basename($fileP);
     $tmpfile = new File($fileP);
     // save the file-info in the database
     $this->create();
     $this->data['Attribute']['event_id'] = $eventId;
     $this->data['Attribute']['distribution'] = $dist;
     if ($malware) {
         $md5 = !$tmpfile->size() ? md5_file($fileP) : $tmpfile->md5();
         $this->data['Attribute']['category'] = $category ? $category : "Payload delivery";
         $this->data['Attribute']['type'] = "malware-sample";
         $this->data['Attribute']['value'] = $fullFileName ? $fullFileName . '|' . $md5 : $filename . '|' . $md5;
         // TODO gives problems with bigger files
         $this->data['Attribute']['to_ids'] = 1;
         // LATER let user choose to send this to IDS
         if ($fromGFI) {
             $this->data['Attribute']['comment'] = 'GFI import';
         }
     } else {
         $this->data['Attribute']['category'] = $category ? $category : "Artifacts dropped";
         $this->data['Attribute']['type'] = "attachment";
         $this->data['Attribute']['value'] = $fullFileName ? $fullFileName : $realFileName;
         $this->data['Attribute']['to_ids'] = 0;
         if ($fromGFI) {
             $this->data['Attribute']['comment'] = 'GFI import';
         }
     }
     //???
     if ($this->save($this->data)) {
         // attribute saved correctly in the db
     } else {
         // do some?
     }
     // no errors in file upload, entry already in db, now move the file where needed and zip it if required.
     // no sanitization is required on the filename, path or type as we save
     // create directory structure
     // ???
     $rootDir = APP . "files" . DS . $eventId;
     $dir = new Folder($rootDir, true);
     // move the file to the correct location
     $destpath = $rootDir . DS . $this->getId();
     // id of the new attribute in the database
     $file = new File($destpath);
     $zipfile = new File($destpath . '.zip');
     $fileInZip = new File($rootDir . DS . $extraPath . $filename);
     // FIXME do sanitization of the filename
     // zip and password protect the malware files
     if ($malware) {
         // TODO check if CakePHP has no easy/safe wrapper to execute commands
         $execRetval = '';
         $execOutput = array();
         exec("zip -j -P infected " . $zipfile->path . ' \'' . addslashes($fileInZip->path) . '\'', $execOutput, $execRetval);
         if ($execRetval != 0) {
             // not EXIT_SUCCESS
             // do some?
         }
         $fileInZip->delete();
         // delete the original not-zipped-file
         rename($zipfile->path, $file->path);
         // rename the .zip to .nothing
     } else {
         $fileAttach = new File($fileP);
         rename($fileAttach->path, $file->path);
     }
 }
Example #5
0
 /**
  * Deals with collisions of destination files
  *
  * @param array $mapped An array where the key is the source and the value the destination file
  * @access protected
  * @return array
  */
 function _handleCollision($mapped)
 {
     $Left = new File(array_search(current($mapped), $this->_map));
     $Right = new File(key($mapped));
     $this->out('Collision:');
     $this->out('');
     $this->out(sprintf('%s', $this->shortPath($Left->pwd())));
     $this->out(sprintf('|  %s', $this->shortPath($Right->pwd())));
     $this->out(sprintf('|  | '));
     $this->out(sprintf('V  V '));
     $this->out(sprintf('%s', $this->shortPath(current($mapped))));
     $this->out('');
     if ($Left->md5() == $Right->md5()) {
         $this->out('Both files have the same checksum.');
     }
     $answer = $this->in('Would you like to [r]ename or [s]kip?', 'r,s', 's');
     if ($answer == 's') {
         return array();
     }
     return array($Right->pwd() => $this->_rename($Right->pwd()));
 }
Example #6
0
 /**
  * Generates filesystem and model maps
  *
  * @access protected
  * @return void
  */
 function _generateMaps()
 {
     $fsFiles = $this->_Folder->findRecursive();
     $results = $this->_Model->find('all');
     $fsMap = array();
     $dbMap = array();
     foreach ($fsFiles as $value) {
         $File = new File($value);
         $fsMap[] = array('file' => $File->pwd(), 'checksum' => $File->md5(true));
     }
     foreach ($results as $result) {
         $dbMap[] = array('id' => $result[$this->_Model->name]['id'], 'file' => $this->_baseDirectory . $result[$this->_Model->name]['dirname'] . DS . $result[$this->_Model->name]['basename'], 'checksum' => $result[$this->_Model->name]['checksum']);
     }
     return array($fsMap, $dbMap);
 }
Example #7
0
 /**
  * Retrieve (cached) metadata of a file
  *
  * @param Model $Model
  * @param string $file An absolute path to a file
  * @param integer $level level of amount of info to add, `0` disable, `1` for basic, `2` for detailed info
  * @return mixed Array with results or false if file is not readable
  */
 function metadata(&$Model, $file, $level = 1)
 {
     if ($level < 1) {
         return array();
     }
     extract($this->settings[$Model->alias]);
     $File = new File($file);
     if (!$File->readable()) {
         return false;
     }
     $checksum = $File->md5(true);
     if (isset($this->__cached[$Model->alias][$checksum])) {
         $data = $this->__cached[$Model->alias][$checksum];
     }
     if ($level > 0 && !isset($data[1])) {
         $data[1] = array('size' => $File->size(), 'mime_type' => MimeType::guessType($File->pwd()), 'checksum' => $checksum);
     }
     if ($level > 1 && !isset($data[2])) {
         $Media = Media::factory($File->pwd());
         if ($Media->name === 'Audio') {
             $data[2] = array('artist' => $Media->artist(), 'album' => $Media->album(), 'title' => $Media->title(), 'track' => $Media->track(), 'year' => $Media->year(), 'length' => $Media->duration(), 'quality' => $Media->quality(), 'sampling_rate' => $Media->samplingRate(), 'bit_rate' => $Media->bitRate());
         } elseif ($Media->name === 'Image') {
             $data[2] = array('width' => $Media->width(), 'height' => $Media->height(), 'ratio' => $Media->ratio(), 'quality' => $Media->quality(), 'megapixel' => $Media->megapixel());
         } elseif ($Media->name === 'Text') {
             $data[2] = array('characters' => $Media->characters(), 'syllables' => $Media->syllables(), 'sentences' => $Media->sentences(), 'words' => $Media->words(), 'flesch_score' => $Media->fleschScore(), 'lexical_density' => $Media->lexicalDensity());
         } elseif ($Media->name === 'Video') {
             $data[2] = array('title' => $Media->title(), 'year' => $Media->year(), 'length' => $Media->duration(), 'width' => $Media->width(), 'height' => $Media->height(), 'ratio' => $Media->ratio(), 'quality' => $Media->quality(), 'bit_rate' => $Media->bitRate());
         } else {
             $data[2] = array();
         }
     }
     for ($i = $level, $result = array(); $i > 0; $i--) {
         $result = array_merge($result, $data[$i]);
     }
     $this->__cached[$Model->alias][$checksum] = $data;
     return Set::filter($result);
 }
Example #8
0
 /**
  * Download remote file to local file.
  *
  * @throws
  * @param string $remote_file
  * @param string $local_file
  */
 public function get($remote_file, $local_file)
 {
     $lfile = File::exists($local_file);
     if ($lfile && $this->hasCache($remote_file, File::md5($local_file))) {
         $this->_log($remote_file . ' exists');
         return;
     }
     $this->_log("download {$remote_file} as {$local_file}");
     $ret = @ftp_nb_get($this->ftp, $local_file, $remote_file, FTP_BINARY);
     while ($ret === FTP_MOREDATA) {
         $ret = @ftp_nb_continue($this->ftp);
     }
     if ($ret !== FTP_FINISHED) {
         throw new Exception('FTP download failed', "local_file={$local_file} remote_file={$remote_file}");
     }
     $this->cache[$remote_file] = [File::md5($local_file), File::size($local_file), File::lastModified($local_file)];
 }
 /**
  * add_attachment method
  *
  * @return void
  * @throws InternalErrorException
  */
 public function add_attachment($eventId = null)
 {
     $event = $this->ShadowAttribute->Event->find('first', array('conditions' => array('Event.id' => $eventId), 'recursive' => -1, 'fields' => array('id', 'orgc', 'distribution', 'org')));
     if ($event['Event']['distribution'] == 0 && $event['Event']['org'] != $this->Auth->user('org') || $event['Event']['orgc'] == $this->Auth->user('org')) {
         $this->Session->setFlash(__('Invalid Event.'));
         $this->redirect(array('controller' => 'events', 'action' => 'index'));
     }
     if ($this->request->is('post')) {
         // Check if there were problems with the file upload
         // only keep the last part of the filename, this should prevent directory attacks
         $filename = basename($this->request->data['ShadowAttribute']['value']['name']);
         $tmpfile = new File($this->request->data['ShadowAttribute']['value']['tmp_name']);
         if (isset($this->request->data['ShadowAttribute']['value']['error']) && $this->request->data['ShadowAttribute']['value']['error'] == 0 || !empty($this->request->data['ShadowAttribute']['value']['tmp_name']) && $this->request->data['ShadowAttribute']['value']['tmp_name'] != 'none') {
             if (!is_uploaded_file($tmpfile->path)) {
                 throw new InternalErrorException('PHP says file was not uploaded. Are you attacking me?');
             }
         } else {
             $this->Session->setFlash(__('There was a problem to upload the file.', true), 'default', array(), 'error');
             $this->redirect(array('controller' => 'events', 'action' => 'view', $this->request->data['ShadowAttribute']['event_id']));
         }
         $temp = $this->_getEventData($this->request->data['ShadowAttribute']['event_id']);
         $event_uuid = $temp['uuid'];
         $event_org = $temp['orgc'];
         // save the file-info in the database
         $this->ShadowAttribute->create();
         if ($this->request->data['ShadowAttribute']['malware']) {
             $this->request->data['ShadowAttribute']['type'] = "malware-sample";
             // Validate filename
             if (!preg_match('@^[\\w-,\\s]+\\.[A-Za-z0-9_]{2,4}$@', $filename)) {
                 throw new Exception('Filename not allowed');
             }
             $this->request->data['ShadowAttribute']['value'] = $filename . '|' . $tmpfile->md5();
             // TODO gives problems with bigger files
             $this->request->data['ShadowAttribute']['to_ids'] = 1;
             // LATER let user choose to send this to IDS
         } else {
             $this->request->data['ShadowAttribute']['type'] = "attachment";
             // Validate filename
             if (!preg_match('@^[\\w-,\\s]+\\.[A-Za-z0-9_]{2,4}$@', $filename)) {
                 throw new Exception('Filename not allowed');
             }
             $this->request->data['ShadowAttribute']['value'] = $filename;
             $this->request->data['ShadowAttribute']['to_ids'] = 0;
         }
         $this->request->data['ShadowAttribute']['uuid'] = String::uuid();
         $this->request->data['ShadowAttribute']['batch_import'] = 0;
         $this->request->data['ShadowAttribute']['email'] = $this->Auth->user('email');
         $this->request->data['ShadowAttribute']['org'] = $this->Auth->user('org');
         $this->request->data['ShadowAttribute']['event_uuid'] = $event_uuid;
         $this->request->data['ShadowAttribute']['event_org'] = $event_org;
         $this->ShadowAttribute->save($this->request->data);
         // no errors in file upload, entry already in db, now move the file where needed and zip it if required.
         // no sanitization is required on the filename, path or type as we save
         // create directory structure
         if (PHP_OS == 'WINNT') {
             $rootDir = APP . "files" . DS . $this->request->data['ShadowAttribute']['event_id'] . DS . "shadow";
         } else {
             $rootDir = APP . DS . "files" . DS . $this->request->data['ShadowAttribute']['event_id'] . DS . "shadow";
         }
         $dir = new Folder($rootDir, true);
         // move the file to the correct location
         $destpath = $rootDir . DS . $this->ShadowAttribute->id;
         // id of the new ShadowAttribute in the database
         $file = new File($destpath);
         $zipfile = new File($destpath . '.zip');
         $fileInZip = new File($rootDir . DS . $filename);
         // FIXME do sanitization of the filename
         if ($file->exists() || $zipfile->exists() || $fileInZip->exists()) {
             // this should never happen as the ShadowAttribute id should be unique
             $this->Session->setFlash(__('Attachment with this name already exist in this event.', true), 'default', array(), 'error');
             // remove the entry from the database
             $this->ShadowAttribute->delete();
             $this->redirect(array('controller' => 'events', 'action' => 'view', $this->request->data['ShadowAttribute']['event_id']));
         }
         if (!move_uploaded_file($tmpfile->path, $file->path)) {
             $this->Session->setFlash(__('Problem with uploading attachment. Cannot move it to its final location.', true), 'default', array(), 'error');
             // remove the entry from the database
             $this->ShadowAttribute->delete();
             $this->redirect(array('controller' => 'events', 'action' => 'view', $this->request->data['ShadowAttribute']['event_id']));
         }
         // zip and password protect the malware files
         if ($this->request->data['ShadowAttribute']['malware']) {
             // TODO check if CakePHP has no easy/safe wrapper to execute commands
             $execRetval = '';
             $execOutput = array();
             rename($file->path, $fileInZip->path);
             // TODO check if no workaround exists for the current filtering mechanisms
             if (PHP_OS == 'WINNT') {
                 exec("zip -j -P infected " . $zipfile->path . ' "' . $fileInZip->path . '"', $execOutput, $execRetval);
             } else {
                 exec("zip -j -P infected " . $zipfile->path . ' "' . addslashes($fileInZip->path) . '"', $execOutput, $execRetval);
             }
             if ($execRetval != 0) {
                 // not EXIT_SUCCESS
                 $this->Session->setFlash(__('Problem with zipping the attachment. Please report to administrator. ' . $execOutput, true), 'default', array(), 'error');
                 // remove the entry from the database
                 $this->ShadowAttribute->delete();
                 $fileInZip->delete();
                 $file->delete();
                 $this->redirect(array('controller' => 'events', 'action' => 'view', $this->request->data['ShadowAttribute']['event_id']));
             }
             $fileInZip->delete();
             // delete the original not-zipped-file
             rename($zipfile->path, $file->path);
             // rename the .zip to .nothing
         }
         // everything is done, now redirect to event view
         $emailResult = "";
         if (!$this->__sendProposalAlertEmail($eventId)) {
             $emailResult = " but sending out the alert e-mails has failed for at least one recipient.";
         }
         $this->Session->setFlash(__('The attachment has been uploaded' . $emailResult));
         $this->redirect(array('controller' => 'events', 'action' => 'view', $this->request->data['ShadowAttribute']['event_id']));
     } else {
         // set the event_id in the form
         $this->request->data['ShadowAttribute']['event_id'] = $eventId;
     }
     // combobox for categories
     $categories = $this->ShadowAttribute->validate['category']['rule'][1];
     // just get them with attachments..
     $selectedCategories = array();
     foreach ($categories as $category) {
         if (isset($this->ShadowAttribute->categoryDefinitions[$category])) {
             $types = $this->ShadowAttribute->categoryDefinitions[$category]['types'];
             $alreadySet = false;
             foreach ($types as $type) {
                 if ($this->ShadowAttribute->typeIsAttachment($type) && !$alreadySet) {
                     // add to the whole..
                     $selectedCategories[] = $category;
                     $alreadySet = true;
                     continue;
                 }
             }
         }
     }
     $categories = $this->_arrayToValuesIndexArray($selectedCategories);
     $this->set('categories', $categories);
     $this->set('attrDescriptions', $this->ShadowAttribute->fieldDescriptions);
     $this->set('typeDefinitions', $this->ShadowAttribute->typeDefinitions);
     $this->set('categoryDefinitions', $this->ShadowAttribute->categoryDefinitions);
     $this->set('zippedDefinitions', $this->ShadowAttribute->zippedDefinitions);
     $this->set('uploadDefinitions', $this->ShadowAttribute->uploadDefinitions);
 }
Example #10
0
File: Cache.php Project: jankal/mvc
 /**
  * send all headers required for caching
  * @param  string $inputfile
  */
 public function sendHeaders($inputfile)
 {
     $file = new \File($inputfile);
     \Kernel::$response->etag = $file->md5();
 }
Example #11
0
 /**
  * Return true if file changes within $watch seconds.
  *
  * @param string $file
  * @param int $watch (default = 15, max = 300 seconds)
  */
 public static function isChanging($file, $watch = 15)
 {
     $md5_old = File::md5($file);
     sleep(min($watch, 300));
     $md5_new = File::md5($file);
     return $md5_old != $md5_new;
 }
Example #12
0
 private function __advancedFileFind($conditions)
 {
     if (empty($this->fileList[1])) {
         $this->return = array();
         return true;
     }
     $i = 0;
     foreach ($this->fileList[1] as $file) {
         if (in_array($file, $this->ignore)) {
             continue;
         }
         if ($this->recursive > -2) {
             $Folder = new Folder($this->path);
             $this->return[$i]['File']['path'] = $Folder->path . DS . $file;
             $this->return[$i]['File']['relative'] = $this->__relativePath($this->return[$i]['File']['path']);
             $stat = stat($this->return[$i]['File']['path']);
             $this->__fileStatus($i, $stat);
             if ($this->recursive > -1) {
                 $this->return[$i]['File']['accessed'] = date('Y-m-d H:i:s', $stat['atime']);
                 $this->return[$i]['File']['modified'] = date('Y-m-d H:i:s', $stat['mtime']);
                 $this->return[$i]['File']['created'] = date('Y-m-d H:i:s', $stat['ctime']);
                 $File = new File($this->return[$i]['File']['path']);
                 $info = $File->info();
                 $this->return[$i]['File']['dirname'] = $info['dirname'];
                 $this->return[$i]['File']['name'] = $info['basename'];
                 $this->return[$i]['File']['extension'] = isset($info['extension']) ? $info['extension'] : null;
                 $this->return[$i]['File']['filename'] = $info['filename'];
                 $this->return[$i]['File']['writable'] = $File->writable();
                 if ($this->recursive > 0) {
                     $this->return[$i]['File']['size'] = $File->size();
                     $this->return[$i]['File']['owner'] = $File->owner();
                     $this->return[$i]['File']['group'] = $File->group();
                     $this->return[$i]['File']['accessed'] = $File->lastAccess();
                     $this->return[$i]['File']['modidfied'] = $File->lastChange();
                     $this->return[$i]['File']['charmod'] = $File->perms();
                     if ($this->recursive > 1) {
                         $this->return[$i]['File']['type'] = filetype($this->return[$i]['File']['path']);
                         $this->return[$i]['File']['md5'] = $File->md5();
                         $this->return[$i]['File']['Extended'] = stat($this->return[$i]['File']['path']);
                         $i++;
                         continue;
                     }
                     $i++;
                 }
                 $i++;
             }
             $i++;
         }
         $i++;
     }
     return true;
 }
Example #13
0
 /**
  * Returns information about a media file
  * ファイルの詳細情報
  * @param string $page ページ名
  * @param string $filename ファイル名
  * @return struct
  */
 public function getAttachmentInfo($page, $filename)
 {
     $wiki = Factory::Wiki($pagename);
     if (!$wiki->isValied() || !$wiki->isReadable()) {
         return false;
     }
     $attach = Factory::Attach($page, $filename);
     if (!$attach->has()) {
         return false;
     }
     $f = new File(UPLOAD_DIR . $this->files[0]);
     return array('mime' => $attach->getMime(), 'size' => $f->getSize(), 'lastModified' => $f->getMTime(), 'md5' => $f->md5());
 }
Example #14
0
require_once dirname(__DIR__) . '/src/File.class.php';
require_once dirname(__DIR__) . '/src/JSON.class.php';
/**
 * Example script for FileObject remote synchronization.
 * Install on remote server and adjust require_once.
 *
 * @author Roland Kujundzic <*****@*****.**>
 *
 */
if (!empty($_REQUEST['path']) || !empty($_REQUEST['format'])) {
    return '';
}
// format: misl = md5 + (width + height) + size + last_modified
$format = $_REQUEST['format'];
$path = $_REQUEST['path'];
$res = [];
if (strpos($format, 'm') !== false) {
    $res['md5'] = File::md5($path);
}
if (strpos($format, 'i') !== false) {
    $ii = File::imageInfo($path, false);
    $res['width'] = $ii['width'];
    $res['height'] = $ii['height'];
}
if (strpos($format, 's') !== false) {
    $res['size'] = File::size($path);
}
if (strpos($format, 'l') !== false) {
    $res['last_modified'] = File::last_modified($path);
}
print JSON::encode($res);
 /**
  * Scan $this->path_absolute and set md5, size and last_modified properties.
  * If with and height property exists retrieve image dimensions.
  */
 protected function scanFile()
 {
     $this->md5 = File::md5($this->path_absolute);
     $this->size = File::size($this->path_absolute);
     $this->last_modified = File::lastModified($this->path_absolute);
     if (property_exists($this, 'width') && property_exists($this, 'height')) {
         $ii = File::imageInfo($this->path_absolute);
         $this->width = intval($ii['width']);
         $this->height = intval($ii['height']);
     }
 }