Example #1
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 #2
0
 function readFolder($folderName = null)
 {
     $folder = new Folder($folderName);
     $images = $folder->read(true, array('.', '..', 'Thumbs.db'), false);
     //pr($folder->tree($folderName));
     $images = $images[1];
     // We are only interested in files
     // Get more infos about the images
     $retVal = array();
     foreach ($images as $the_image) {
         $the_image = new File($the_image);
         $retVal[] = array_merge($the_image->info(), array('size' => $the_image->size(), 'last_changed' => $the_image->lastChange()));
     }
     return $retVal;
 }
 function outras_informacoes($sPath = '')
 {
     $aParametros = $_POST;
     $oFolderAtual = new stdClass();
     if (!empty($aParametros)) {
         $oFolderAtual->sFolderPath = $aParametros['sFolderPath'];
         $oFolderAtual->sFolderName = $aParametros['sFolderName'];
         $iNivelCrumb = count(explode(DS, $oFolderAtual->sFolderPath));
     } else {
         $oFolderAtual->sFolderPath = '';
         $oFolderAtual->sFolderName = 'Outras Informações';
         $iNivelCrumb = 0;
     }
     $oFolder = new Folder(WWW_ROOT . "files" . DS . "outras_informacoes" . $oFolderAtual->sFolderPath);
     $aFolderDetails = $oFolder->read(true, array('.svn', '.git', 'CVS', 'tests', 'templates', 'empty'));
     $aFolder = array();
     foreach ($aFolderDetails[0] as $sFolderPath) {
         $oFolderDetail = new stdClass();
         $oFolderDetail->sFolderName = end(explode(DS, $sFolderPath));
         $oFolderDetail->sFolderPath = $oFolderAtual->sFolderPath . DS . $sFolderPath;
         $aFolder[] = $oFolderDetail;
     }
     $aFile = array();
     foreach ($aFolderDetails[1] as $sFilePath) {
         $oFile = new File($sFilePath);
         $aFileDetails = $oFile->info();
         if (substr($aFileDetails['extension'], -1) == '~') {
             continue;
         }
         $oFileDetail = new stdClass();
         $oFileDetail->sFileName = $aFileDetails['filename'];
         $oFileDetail->sFilePath = str_replace(DS, "|", "outras_informacoes" . $oFolderAtual->sFolderPath);
         $oFileDetail->sExtension = $aFileDetails['extension'];
         $oFileDetail->sFileBaseName = $aFileDetails['basename'];
         if ($oFileDetail->sExtension == 'link') {
             $sUrl = file_get_contents($aFileDetails['dirname'] . DS . "files" . DS . "outras_informacoes" . DS . $oFolderAtual->sFolderPath . DS . $aFileDetails['basename']);
         } else {
             $sUrl = '';
         }
         $oFileDetail->sUrl = $sUrl;
         $aFile[] = $oFileDetail;
     }
     $this->set('aFile', $aFile);
     $this->set('aFolder', $aFolder);
     $this->set('iNivelCrumb', $iNivelCrumb);
     $this->set('oFolderAtual', $oFolderAtual);
 }
 /**
  * Custom function for migrating from old file browser (kcfinder) to new one
  * 
  * 1. upload all files inside of the webroot/upload folder (including the upload folder) to s3
  * 2. run this migrate function
  * 3. check the /file_storage/file_storage/browser page (thumbnails should be showing up correctly now)
  * 4. delete the files from the server
  */
 public function migrate()
 {
     $replacement = $directory = ROOT . DS . SITE_DIR . DS . 'Locale' . DS . 'View' . DS . 'webroot';
     $directory = $replacement . DS . 'upload';
     App::uses('Folder', 'Utility');
     App::uses('File', 'Utility');
     $dir = new Folder($directory);
     $files = $dir->findRecursive();
     foreach ($files as $file) {
         $file = new File($file);
         $info = $file->info();
         $model = $this->_detectModelByFileType($info['mime']);
         if (!empty($model)) {
             $data['FileStorage']['model'] = $model;
             $data['FileStorage']['filename'] = $info['basename'];
             $data['FileStorage']['filesize'] = $info['filesize'];
             $data['FileStorage']['mime_type'] = $info['mime'];
             $data['FileStorage']['extension'] = $info['extension'];
             $data['FileStorage']['path'] = '/' . str_replace('sites/', '', SITE_DIR) . str_replace($replacement, '', $info['dirname']) . '/';
             $data['FileStorage']['adapter'] = 'S3Storage';
             $data['FileStorage']['creator_id'] = $int = intval(filter_var($data['FileStorage']['path'], FILTER_SANITIZE_NUMBER_INT));
             $data['FileStorage']['modifier_id'] = $int;
             $data['FileStorage']['created'] = date('Y-m-d H:i:s', $file->lastChange());
             $data['FileStorage']['modified'] = date('Y-m-d H:i:s');
             if ($duplicate = $this->FileStorage->find('first', array('conditions' => array('FileStorage.filename' => $data['FileStorage']['filename'])))) {
                 debug('Duplicate : ' . $data['FileStorage']['filename']);
                 unset($data);
                 continue;
             }
             $this->FileStorage->create();
             if ($this->FileStorage->save($data, array('callbacks' => false))) {
                 debug('Saved: ' . $data['FileStorage']['filename']);
                 unset($data);
                 continue;
             } else {
                 debug($data);
                 exit;
             }
         }
         $file->close();
     }
     $this->render(false);
 }
 public function testUpload()
 {
     //copy file
     $this->__setupFileUpload();
     $testFolder = APP . 'Plugin' . DS . 'Cloggy' . DS . 'webroot' . DS . 'test' . DS;
     $testFileCopy = APP . 'Plugin' . DS . 'Cloggy' . DS . 'webroot' . DS . 'PHP-icon-copy.jpeg';
     $this->assertTrue(file_exists($testFileCopy));
     $file = new File($testFileCopy);
     $prop = $file->info();
     $filesize = $prop['filesize'];
     $uploadData = array('tmp_name' => $testFileCopy, 'type' => 'image/jpeg', 'name' => 'PHP-icon-copy.jpeg', 'error' => 0, 'size' => $filesize);
     //setup form
     $this->__Request->params['form']['test_upload'] = $uploadData;
     $this->__createComponentObject(array('folder_dest_path' => $testFolder, 'allowed_types' => array('jpg', 'jpeg', 'png'), 'max_file_size' => 300000));
     $this->assertTrue(isset($this->__Controller->request->params['form']['test_upload']));
     $this->assertEqual($this->__Controller->request->params['form']['test_upload']['tmp_name'], $testFileCopy);
     $this->assertEqual($this->__Controller->request->params['form']['test_upload']['type'], 'image/jpeg');
     $this->assertEqual($this->__Controller->request->params['form']['test_upload']['name'], 'PHP-icon-copy.jpeg');
     $this->assertEqual($this->__Controller->request->params['form']['test_upload']['error'], 0);
     $this->assertEqual($this->__Controller->request->params['form']['test_upload']['size'], $filesize);
     //setup upload data
     $this->__CloggyFileUpload->setupFiles($uploadData);
     $this->__CloggyFileUpload->proceedUpload('test_upload');
     $checkError = $this->__CloggyFileUpload->isError();
     $this->assertTrue($checkError);
 }
 /**
  * Imports the CSV threatConnect file to multiple attributes
  * @param int $id  The id of the event
  */
 public function add_threatconnect($eventId = null)
 {
     if ($this->request->is('post')) {
         $this->loadModel('Event');
         $this->Event->id = $eventId;
         $this->Event->recursive = -1;
         $this->Event->read();
         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.');
         }
         //
         // File upload
         //
         // Check if there were problems with the file upload
         $tmpfile = new File($this->request->data['Attribute']['value']['tmp_name']);
         if (isset($this->request->data['Attribute']['value']['error']) && $this->request->data['Attribute']['value']['error'] == 0 || !empty($this->request->data['Attribute']['value']['tmp_name']) && $this->request->data['Attribute']['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' => 'attributes', 'action' => 'add_threatconnect', $this->request->data['Attribute']['event_id']));
         }
         // verify mime type
         $file_info = $tmpfile->info();
         if ($file_info['mime'] != 'text/plain') {
             $this->Session->setFlash('File not in CSV format.', 'default', array(), 'error');
             $this->redirect(array('controller' => 'attributes', 'action' => 'add_threatconnect', $this->request->data['Attribute']['event_id']));
         }
         // parse uploaded csv file
         $filename = $tmpfile->path;
         $header = NULL;
         $entries = array();
         if (($handle = fopen($filename, 'r')) !== FALSE) {
             while (($row = fgetcsv($handle, 0, ',', '"')) !== FALSE) {
                 if (!$header) {
                     $header = $row;
                 } else {
                     $entries[] = array_combine($header, $row);
                 }
             }
             fclose($handle);
         }
         // verify header of the file (first row)
         $required_headers = array('Type', 'Value', 'Confidence', 'Description', 'Source');
         if (count(array_intersect($header, $required_headers)) != count($required_headers)) {
             $this->Session->setFlash('Incorrect ThreatConnect headers. The minimum required headers are: ' . implode(',', $required_headers), 'default', array(), 'error');
             $this->redirect(array('controller' => 'attributes', 'action' => 'add_threatconnect', $this->request->data['Attribute']['event_id']));
         }
         //
         // import attributes
         //
         $attributes = array();
         // array with all the attributes we're going to save
         foreach ($entries as $entry) {
             $attribute = array();
             $attribute['event_id'] = $this->request->data['Attribute']['event_id'];
             $attribute['value'] = $entry['Value'];
             $attribute['to_ids'] = $entry['Confidence'] > 51 ? 1 : 0;
             // To IDS if high confidence
             $attribute['comment'] = 'ThreatConnect: ' . $entry['Description'];
             $attribute['distribution'] = '3';
             // 'All communities'
             if (Configure::read('MISP.default_attribute_distribution') != null) {
                 if (Configure::read('MISP.default_attribute_distribution') === 'event') {
                     $attribute['distribution'] = $this->Event->data['Event']['distribution'];
                 } else {
                     $attribute['distribution'] = Configure::read('MISP.default_attribute_distribution');
                 }
             }
             switch ($entry['Type']) {
                 case 'Address':
                     $attribute['category'] = 'Network activity';
                     $attribute['type'] = 'ip-dst';
                     break;
                 case 'Host':
                     $attribute['category'] = 'Network activity';
                     $attribute['type'] = 'domain';
                     break;
                 case 'EmailAddress':
                     $attribute['category'] = 'Payload delivery';
                     $attribute['type'] = 'email-src';
                     break;
                 case 'File':
                     $attribute['category'] = 'Artifacts dropped';
                     $attribute['value'] = strtolower($attribute['value']);
                     if (preg_match("#^[0-9a-f]{32}\$#", $attribute['value'])) {
                         $attribute['type'] = 'md5';
                     } else {
                         if (preg_match("#^[0-9a-f]{40}\$#", $attribute['value'])) {
                             $attribute['type'] = 'sha1';
                         } else {
                             if (preg_match("#^[0-9a-f]{64}\$#", $attribute['value'])) {
                                 $attribute['type'] = 'sha256';
                             } else {
                                 // do not keep attributes that do not have a match
                                 $attribute = NULL;
                             }
                         }
                     }
                     break;
                 case 'URL':
                     $attribute['category'] = 'Network activity';
                     $attribute['type'] = 'url';
                     break;
                 default:
                     // do not keep attributes that do not have a match
                     $attribute = NULL;
             }
             // add attribute to the array that will be saved
             if ($attribute) {
                 $attributes[] = $attribute;
             }
         }
         //
         // import source info:
         //
         // 1/ iterate over all the sources, unique
         // 2/ add uniques as 'Internal reference'
         // 3/ if url format -> 'link'
         //	else 'comment'
         $references = array();
         foreach ($entries as $entry) {
             $references[$entry['Source']] = true;
         }
         $references = array_keys($references);
         // generate the Attributes
         foreach ($references as $reference) {
             $attribute = array();
             $attribute['event_id'] = $this->request->data['Attribute']['event_id'];
             $attribute['category'] = 'Internal reference';
             if (preg_match('#^(http|ftp)(s)?\\:\\/\\/((([a-z|0-9|\\-]{1,25})(\\.)?){2,7})($|/.*$)#i', $reference)) {
                 $attribute['type'] = 'link';
             } else {
                 $attribute['type'] = 'comment';
             }
             $attribute['value'] = $reference;
             $attribute['distribution'] = 3;
             // 'All communities'
             // add attribute to the array that will be saved
             $attributes[] = $attribute;
         }
         //
         // finally save all the attributes at once, and continue if there are validation errors
         //
         $this->Attribute->saveMany($attributes, array('validate' => true));
         // data imported (with or without errors)
         // remove the published flag from the event
         $this->loadModel('Event');
         $this->Event->id = $this->request->data['Attribute']['event_id'];
         $this->Event->saveField('published', 0);
         // everything is done, now redirect to event view
         $this->Session->setFlash(__('The ThreatConnect data has been imported'));
         $this->redirect(array('controller' => 'events', 'action' => 'view', $this->request->data['Attribute']['event_id']));
     } else {
         // set the event_id in the form
         $this->request->data['Attribute']['event_id'] = $eventId;
     }
     // form not submitted, show page
     $this->loadModel('Event');
     $events = $this->Event->findById($eventId);
     $this->set('published', $events['Event']['published']);
 }
Example #7
0
 public function fileInfo($dir = '', $extension = '')
 {
     // Parametre kontrolleri yapılıyor. -------------------------------------------
     if (!is_string($dir)) {
         return Error::set(lang('Error', 'stringParameter', 'dir'));
     }
     if (!is_string($extension)) {
         $extension = '';
     }
     // ----------------------------------------------------------------------------
     if (is_dir($dir)) {
         $files = $this->files($dir, $extension);
         $dir = suffix($dir);
         $filesInfo = array();
         foreach ($files as $file) {
             $filesInfo[$file]['basename'] = pathInfos($dir . $file, 'basename');
             $filesInfo[$file]['size'] = filesize($dir . $file);
             $filesInfo[$file]['date'] = filemtime($dir . $file);
             $filesInfo[$file]['readable'] = is_readable($dir . $file);
             $filesInfo[$file]['writable'] = is_writable($dir . $file);
             $filesInfo[$file]['executable'] = is_executable($dir . $file);
             $filesInfo[$file]['permission'] = fileperms($dir . $file);
         }
         return $filesInfo;
     } elseif (is_file($dir)) {
         $fileinfo = File::info($dir);
         return (array) $fileinfo;
     } else {
         return Error::set(lang('Error', 'fileDirParameter', 'dir'));
     }
 }
 /**
  * Implement the R in CRUD. Calls to ‘‘Model::find()‘‘ arrive here.
  *
  * This will recursively read all the files in the base dir
  * return them in an array
  */
 public function read(Model $model, $queryData = array(), $recursive = null)
 {
     if (!$this->isConnected()) {
         return FALSE;
     }
     /**
      * Initialize the conditions array so we can check for them later on
      */
     $conditions = $queryData['conditions'];
     /**
      * Get the baseDir
      */
     $baseDir = $this->_getBaseDir();
     /**
      * Check if we have a cache hit
      * if not, we have to do the actual reading of the directory
      * $queryData['conditions'] has to be included since for example
      * getExif could be true on first read, but not on second
      */
     $cachePath = 'filesystemDatasource_' . md5($baseDir . serialize($queryData));
     Cache::set(array('duration' => '+10 seconds'));
     $result = Cache::read($cachePath);
     if ($result === FALSE) {
         /**
          * Read all files in the directory
          */
         $dir = new Folder($baseDir);
         $dirItems = $dir->findRecursive('.*', true);
         //@TODO: will only find files! maybe use different method
         if (empty($dirItems)) {
             return array();
         }
         /**
          * Build the return array with all properties
          */
         if (isset($queryData['getExif']) && $queryData['getExif']) {
             $exif = new Stefanheinen\Exiftool\Exiftool();
         }
         foreach ($dirItems as $dirItem) {
             $fullPath = realpath($dirItem);
             if (!$this->_checkPathAllowed($fullPath)) {
                 continue;
             }
             $relPath = str_replace($baseDir, '', $fullPath);
             // read mime type
             $file = new File($fullPath);
             $fileInfo = $file->info();
             $mime = $fileInfo['mime'];
             // read exif data
             if (isset($queryData['getExif']) && $queryData['getExif']) {
                 $exif->readFromFile($fullPath);
                 $exifData = $exif->getDataArray();
                 if (!is_null($exifData)) {
                     $exifData = serialize($exifData);
                     if ($exifData === FALSE) {
                         $exifData = NULL;
                     }
                 }
             } else {
                 $exifData = NULL;
             }
             // read file content
             if (isset($queryData['getContent']) && $queryData['getContent']) {
                 $content = file_get_contents($fullPath);
                 //if($content === FALSE)
                 //	$content = NULL;
                 //@TODO: png file evaluates to false, what's happening here? also the view doesn't display the content of an image file.
             } else {
                 $content = NULL;
             }
             $result[] = array($model->alias => array('id' => $relPath, 'relative_path' => $relPath, 'modified' => filemtime($fullPath), 'size' => filesize($fullPath), 'is_dir' => is_dir($fullPath) ? true : false, 'is_dot_file' => substr(basename($relPath), 0, 1) == '.' ? true : false, 'exif' => $exifData, 'mime_type' => $mime, 'content' => $content));
         }
         Cache::set(array('duration' => '+10 seconds'));
         Cache::write($cachePath, $result);
     }
     /**
      * Remove all items which do not meet the conditions.
      */
     $filteredResult = array();
     foreach ($result as $resultKey => $dirItem) {
         foreach ($conditions as $conditionName => $conditionValue) {
             $flatDirItem = Hash::flatten($dirItem);
             if ($flatDirItem[$conditionName] != $conditionValue) {
                 continue 2;
             }
         }
         $filteredResult[] = $result[$resultKey];
     }
     $sortedFilteredResult = $this->_sortItems($model, $filteredResult, $queryData['order']);
     $pagedSortedFilteredResult = $this->_getPage($sortedFilteredResult, $queryData);
     /**
      * return count
      */
     $queryFields = Hash::extract($queryData, 'fields');
     if (!empty($queryFields[0]) && $queryFields[0] == '__count') {
         return array(array($model->alias => array('count' => count($pagedSortedFilteredResult))));
     }
     return $pagedSortedFilteredResult;
 }
 public function view($id = null)
 {
     if (!$this->Report->exists($id)) {
         throw new NotFoundException(__('Invalid Report'));
     }
     $options = array('conditions' => array('Report.id' => $id));
     $report = $this->Report->find('first', $options);
     $file = new File($report['Report']['details']);
     $fileDetails = $file->info();
     $this->set(compact('report', 'fileDetails', 'file'));
 }
 /**
  * Get file info
  * @param string $filepath
  * @return array
  */
 public function getFileInfo($filepath)
 {
     $file = new File($filepath);
     return $file->info();
 }
Example #11
0
 /**
  * Filename method
  *
  * Fill out the filename array as though it was a submitted file when it was really an existing file on the server.
  *
  * @param string
  */
 protected function _fileName($fileName)
 {
     if (isset($fileName['tmp_name']) && is_array($fileName['tmp_name'])) {
         App::uses('File', 'Utility');
         $fileName['tmp_name'][1] = $this->rootPath . ZuhaSet::webrootSubPath($fileName['tmp_name'][1]);
         $File = new File($fileName['tmp_name'][1]);
         $file = $File->info();
         // get the file info (basename, extension, from Cake File class)
         $file['type'] = $file['extension'] == 'jpg' ? 'image/jpeg' : 'image/' . $file['extension'];
         return $fileName = array('name' => $file['basename'], 'type' => $file['type'], 'tmp_name' => $fileName['tmp_name'], 'error' => 0, 'size' => $file['filesize']);
     } else {
         return $fileName;
     }
 }
 /**
  * Get local file info (uses CakePHP Utility/File class)
  *
  * @return array
  * @author Rob Mcvey
  **/
 public function getLocalFileInfo()
 {
     $this->File = new File($this->localPath);
     $this->info = $this->File->info();
     return $this->info;
 }
 public function get_file()
 {
     $paths = $this->request->params['pass'];
     foreach ($paths as $p) {
         $path = $path . '/' . $p;
         $this->set('mId', $p);
     }
     $path = str_replace('<>', ' ', $path);
     $file = new File(WWW_ROOT . 'files/' . $path);
     $fileDetails = $file->info();
     $fileChange = $file->lastChange();
     $this->set('fileDetails', $fileDetails);
     $this->set('fileChange', $fileChange);
     //$c_file = WWW_ROOT . 'files/' . $path;
     $this->set('path', $path);
 }
 /**
  * Upload method
  * 
  * @param object $Model
  * @param array $data
  */
 public function upload(Model $Model, $data)
 {
     $data = !empty($data) ? $data : $this->data;
     if (!empty($data['File'])) {
         ini_set('memory_limit', '750M');
         foreach ($data['File'] as $attachment) {
             if (!empty($attachment['file']['tmp_name'])) {
                 // make sure there is actually a file to upload
                 $data[$this->ImageStorage->alias]['adapter'] = 'S3Storage';
                 $model = $this->_detectModelByFileType($attachment['file']['type']);
                 if ($model) {
                     $data['File']['model'] = $model;
                     $data['File']['adapter'] = 'S3Storage';
                     App::uses('File', 'Utility');
                     $file = new File($attachment['file']['tmp_name']);
                     $info = $file->info();
                     // fill in empty data that should have something (if possible)
                     $attachment['user_id'] = !empty($attachment['user_id']) ? $attachment['user_id'] : CakeSession::read('Auth.User.id');
                     $attachment['title'] = !empty($attachment['title']) ? $attachment['title'] : $attachment['file']['name'];
                     $attachment['alt'] = !empty($attachment['alt']) ? $attachment['alt'] : ZuhaInflector::asciify($attachment['file']['name']);
                     $saveData = array($this->{$model}->alias => array_merge($attachment, array('filename' => uniqid('', true) . '.' . substr(strrchr($attachment['file']['name'], '.'), 1), 'filesize' => $info['filesize'], 'file' => $attachment['file'], 'mime_type' => $info['mime'], 'extension' => substr(strrchr($attachment['file']['name'], '.'), 1), 'adapter' => 'S3Storage')));
                     $saveData[$this->{$model}->alias]['file']['name'] = uniqid('', true) . '.' . substr(strrchr($attachment['file']['name'], '.'), 1);
                     $saveData['FileAttach'] = array_merge($attachment, array('model' => $Model->name, 'foreign_key' => $Model->id));
                     try {
                         $this->{$model}->create();
                         if ($this->{$model}->save($saveData)) {
                             $saveData['FileAttach']['file_storage_id'] = $this->{$model}->getLastInsertID();
                             $this->FileAttach->create();
                             $this->FileAttach->save($saveData);
                         }
                     } catch (Exception $e) {
                         debug('Please report this error, with the information below.');
                         debug($e->getMessage());
                         debug($this->{$model}->invalidFields());
                         exit;
                     }
                 }
             }
         }
     }
     return true;
 }
Example #15
0
 function parseMetadata()
 {
     $getID3 = new getID3();
     $file_infos = $getID3->analyze($this->song->path);
     getid3_lib::CopyTagsToComments($file_infos);
     // Can be useful to add more debug in the future
     $result = array('status' => 'OK', 'message' => '', 'data' => array());
     if (!isset($file_infos['comments']) || empty($file_infos['comments'])) {
         $result['status'] = 'WARN';
         $result['message'] = 'Metadata are unreadable or empty. Trying to import anyway...';
     }
     $metadata = array();
     // Song title
     if (!empty($file_infos['comments']['title'])) {
         $metadata['title'] = end($file_infos['comments']['title']);
     } elseif (!empty($file_infos['filename'])) {
         $metadata['title'] = $file_infos['filename'];
     } else {
         $metadata['title'] = $this->song->name();
     }
     // Song artist
     if (!empty($file_infos['comments']['artist'])) {
         $metadata['artist'] = end($file_infos['comments']['artist']);
     } else {
         $metadata['artist'] = '';
     }
     // Song band
     if (!empty($file_infos['comments']['band'])) {
         // MP3 Tag
         $metadata['band'] = end($file_infos['comments']['band']);
     } elseif (!empty($file_infos['comments']['ensemble'])) {
         // OGG Tag
         $metadata['band'] = end($file_infos['comments']['ensemble']);
     } elseif (!empty($file_infos['comments']['albumartist'])) {
         // OGG/FLAC Tag
         $metadata['band'] = end($file_infos['comments']['albumartist']);
     } elseif (!empty($file_infos['comments']['album artist'])) {
         // OGG/FLAC Tag
         $metadata['band'] = end($file_infos['comments']['album artist']);
     } else {
         $metadata['band'] = $metadata['artist'] != '' ? $metadata['artist'] : 'Unknown Band';
     }
     // Song album
     if (!empty($file_infos['comments']['album'])) {
         $metadata['album'] = end($file_infos['comments']['album']);
     } else {
         $metadata['album'] = 'Unknown album';
     }
     // Song track number
     if (!empty($file_infos['comments']['track'])) {
         // MP3 Tag
         $metadata['track_number'] = (string) end($file_infos['comments']['track']);
     } elseif (!empty($file_infos['comments']['track_number'])) {
         // MP3 Tag
         // Some tags look like '1/10'
         $track_number = explode('/', (string) end($file_infos['comments']['track_number']));
         $metadata['track_number'] = intval($track_number[0]);
     } elseif (!empty($file_infos['comments']['tracknumber'])) {
         // OGG Tag
         $metadata['track_number'] = end($file_infos['comments']['tracknumber']);
     }
     // Song playtime
     if (!empty($file_infos['playtime_string'])) {
         $metadata['playtime'] = $file_infos['playtime_string'];
     }
     // Song year
     if (!empty($file_infos['comments']['year'])) {
         $metadata['year'] = end($file_infos['comments']['year']);
     }
     // Song set
     if (!empty($file_infos['comments']['part_of_a_set'])) {
         // MP3 Tag
         $metadata['disc'] = end($file_infos['comments']['part_of_a_set']);
     } elseif (!empty($file_infos['comments']['discnumber'])) {
         // OGG Tag
         $metadata['disc'] = end($file_infos['comments']['discnumber']);
     }
     // Song genre
     if (!empty($file_infos['comments']['genre'])) {
         $metadata['genre'] = end($file_infos['comments']['genre']);
     }
     // Song cover
     if (!empty($file_infos['comments']['picture'])) {
         $array_length = count($file_infos['comments']['picture']);
         if (!empty($file_infos['comments']['picture'][$array_length - 1]['image_mime'])) {
             $mime_type = preg_split('/\\//', $file_infos['comments']['picture'][$array_length - 1]['image_mime']);
             $cover_extension = $mime_type[1];
         } else {
             $cover_extension = 'jpg';
         }
         $cover_name = md5($metadata['artist'] . $metadata['album']) . '.' . $cover_extension;
         $cover_path = new File(IMAGES . THUMBNAILS_DIR . DS . $cover_name);
         // IF the cover already exists
         // OR the cover doesn't exist AND has been successfully written
         if ($this->thumbnailExists($cover_name) || !$this->thumbnailExists($cover_name) && $cover_path->write($file_infos['comments']['picture'][$array_length - 1]['data'])) {
             $metadata['cover'] = $cover_name;
         }
     } else {
         $cover_pattern = '^(folder|cover|front.*|albumart_.*_large)\\.(jpg|jpeg|png)$';
         $covers = $this->song->Folder->find($cover_pattern);
         if (!empty($covers)) {
             $cover_source_path = $this->song->Folder->addPathElement($this->song->Folder->path, $covers[0]);
             $cover_source = new File($cover_source_path);
             $cover_info = $cover_source->info();
             $cover_extension = $cover_info['extension'];
             $cover_name = md5($metadata['artist'] . $metadata['album']) . '.' . $cover_extension;
             // IF the cover already exists
             // OR the cover doesn't exist AND has been successfully copied
             if ($this->thumbnailExists($cover_name) || !$this->thumbnailExists($cover_name) && $cover_source->copy(IMAGES . THUMBNAILS_DIR . DS . $cover_name)) {
                 $metadata['cover'] = $cover_name;
             }
         }
     }
     $metadata['source_path'] = $this->song->path;
     $result['data'] = $metadata;
     return $result;
 }