Beispiel #1
0
 /**
  * Should handle execution of the task, taking as much (optional) parameters as needed
  *
  * The parameters should be optional and failing to provide them should be handled by
  * the task
  *
  * @param string $file The file to move
  * @param string $destination The destionation (folder or new name
  * @param string $counter Name of coutner threshold - or leave empty for always move
  * @param int $min Optional minimum counter value
  * @param int $max Optional maximum counter value (use either minimum or both)
  */
 public function execute($file = null, $destination = null, $counter = null, $min = null, $max = null)
 {
     if (!file_exists($file)) {
         return;
     }
     $batch = $this->getBatch();
     if ($counter) {
         $value = $batch->getCounter($counter);
         if (null !== $min && $value < $min) {
             return;
         }
         if (null !== $max && $value > $max) {
             return;
         }
     }
     if (is_dir($destination)) {
         $destination = $destination . DIRECTORY_SEPARATOR . basename($file);
     }
     \MUtil_File::ensureDir(dirname($destination));
     if (@copy($file, $destination)) {
         $batch->addMessage(sprintf($this->_('Copied file to "%s".'), basename($destination)));
     } else {
         $batch->addMessage(sprintf($this->_('Could not copy "%s" to "%s".'), basename($file), basename($destination)));
     }
 }
 /**
  * Get the organization name/code used by the long term filename
  *
  * @return string
  */
 public function getOrganizationCode()
 {
     if (!$this->_orgCode) {
         $this->_orgCode = $this->currentOrganization->getCode();
         if (!$this->_orgCode) {
             $this->_orgCode = \MUtil_File::cleanupName($this->currentOrganization->getName());
         }
     }
     return $this->_orgCode;
 }
 /**
  * Returns the on empty texts for the autofilter snippets
  *
  * @static boolean $warned Listen very closely. I shall tell this only once!
  * @return string
  */
 public function getOnEmptyText()
 {
     static $warned;
     $dir = $this->getPath(false, 'index');
     if (!is_dir($dir)) {
         try {
             \MUtil_File::ensureDir($dir);
         } catch (\Zend_Exception $e) {
             $text = $e->getMessage();
             if (!$warned) {
                 $warned = true;
                 $this->addMessage($text);
             }
             return $text;
         }
     }
     return parent::getOnEmptyText();
 }
 /**
  * Accepts the form
  *
  * Takes two roundtrips:
  * - first we get a HEAD request that should be answerd with
  *   responsecode 204
  * - then we get a post that only submits $_FILES (so actual $_POST will be empty)
  *   this will be an xml file for the actuel response and optionally images and/or video
  *   proper responses are
  *      201 received and stored
  *      202 received ok, not stored
  */
 public function submissionAction()
 {
     $this->makeRosaResponse();
     if ($this->getRequest()->isHead()) {
         $this->getResponse()->setHttpResponseCode(204);
     } elseif ($this->getRequest()->isPost()) {
         //Post
         // We get $_FILES variable holding the formresults as xml and all possible
         // attachments like photo's and video's
         $upload = new \Zend_File_Transfer_Adapter_Http();
         // We should really add some validators here see http://framework.zend.com/manual/en/zend.file.transfer.validators.html
         // Returns all known internal file information
         $files = $upload->getFileInfo();
         foreach ($files as $file => $info) {
             // file uploaded ?
             if (!$upload->isUploaded($file)) {
                 print "Why haven't you uploaded the file ?";
                 continue;
             }
             // validators are ok ?
             if (!$upload->isValid($file)) {
                 print "Sorry but {$file} is not what we wanted";
                 continue;
             }
         }
         //Dit moet een filter worden (rename filter) http://framework.zend.com/manual/en/zend.file.transfer.filters.html
         $upload->setDestination($this->responseDir);
         //Hier moeten we denk ik eerst de xml_submission_file uitlezen, en daar
         //iets mee doen
         if ($upload->receive('xml_submission_file')) {
             $xmlFile = $upload->getFileInfo('xml_submission_file');
             $answerXmlFile = $xmlFile['xml_submission_file']['tmp_name'];
             $resultId = $this->processReceivedForm($answerXmlFile);
             if ($resultId === false) {
                 //form not accepted!
                 foreach ($xml->children() as $child) {
                     $log->log($child->getName() . ' -> ' . $child, \Zend_Log::ERR);
                 }
             } else {
                 //$log->log(print_r($files, true), \Zend_Log::ERR);
                 //$log->log($deviceId, \Zend_Log::ERR);
                 \MUtil_File::ensureDir($this->responseDir . 'forms/' . (int) $this->openrosaFormID . '/');
                 $upload->setDestination($this->responseDir . 'forms/' . (int) $this->openrosaFormID . '/');
                 foreach ($upload->getFileInfo() as $file => $info) {
                     if ($info['received'] != 1) {
                         //Rename to responseid_filename
                         //@@TODO: move to form subdir, for better separation
                         $upload->addFilter('Rename', $resultId . '_' . $info['name'], $file);
                     }
                 }
                 //Now receive the other files
                 if (!$upload->receive()) {
                     $messages = $upload->getMessages();
                     echo implode("\n", $messages);
                 }
                 $this->getResponse()->setHttpResponseCode(201);
                 //Form received ok
             }
         }
     }
 }
Beispiel #5
0
 /**
  * Save a single model item.
  *
  * @param array $newValues The values to store for a single model item.
  * @param array $filter If the filter contains old key values these are used
  * to decide on update versus insert.
  * @return array The values as they are after saving (they may change).
  */
 public function save(array $newValues, array $filter = null)
 {
     $filename = false;
     if ($this->recursive) {
         if (isset($newValues['relpath'])) {
             $filename = $newValues['relpath'];
         }
     }
     if (!$filename && isset($newValues['filename'])) {
         $filename = $newValues['filename'];
     }
     if (!$filename) {
         throw new \MUtil_Model_ModelException('Cannot save file: no filename known');
     }
     $filename = trim($filename, '\\/');
     if ($this->dir) {
         $filename = $this->dir . DIRECTORY_SEPARATOR . $filename;
     }
     $content = isset($newValues['content']) ? $newValues['content'] : '';
     \MUtil_File::ensureDir(dirname($filename));
     if (false === file_put_contents($filename, $content) || !file_exists($filename)) {
         throw new \MUtil_Model_ModelException(sprintf('Unable to save %s: %s', $filename, \MUtil_Error::getLastPhpErrorMessage('reason unknown')));
     }
     $this->setChanged(1);
     return $newValues;
 }
 /**
  * Hook that loads the form data from $_POST or the model
  *
  * Or from whatever other source you specify here.
  */
 protected function loadFormData()
 {
     $model = $this->getModel();
     if ($this->request->isPost()) {
         $this->formData = $model->loadPostData($this->request->getPost() + $this->formData, true);
     } else {
         // Assume that if formData is set it is the correct formData
         if (!$this->formData) {
             $this->formData = $model->loadNew();
         }
     }
     if (isset($this->formData['gtr_id_track']) && $this->formData['gtr_id_track']) {
         $this->trackEngine = $this->loader->getTracker()->getTrackEngine($this->formData['gtr_id_track']);
     }
     if (!(isset($this->formData['importId']) && $this->formData['importId'])) {
         $this->formData['importId'] = mt_rand(10000, 99999) . time();
     }
     $this->_session = new \Zend_Session_Namespace(__CLASS__ . '-' . $this->formData['importId']);
     if (!(isset($this->_session->localfile) && $this->_session->localfile)) {
         $importLoader = $this->loader->getImportLoader();
         $this->_session->localfile = \MUtil_File::createTemporaryIn($importLoader->getTempDirectory(), $this->request->getControllerName() . '_');
     }
     // \MUtil_Echo::track($this->formData);
 }
 /**
  * Clean a proposed filename up so it can be used correctly as a filename
  * @param  string $filename Proposed filename
  * @return string           filtered filename
  */
 protected function cleanupName($filename)
 {
     $filename = str_replace(array('/', '\\', ':', ' '), '_', $filename);
     // Remove dot if it starts with one
     $filename = trim($filename, '.');
     return \MUtil_File::cleanupName($filename);
 }
Beispiel #8
0
 /**
  * Construct a logger with filename depending on $logRotate
  *
  * @param mixed $filename Start of the filename minus .log extension
  * @param mixed $logRotate One of the cosntants for log rotate
  * @param int One of the \Zend_Log constants
  */
 public function __construct($filename, $logRotate = null, $priority = null)
 {
     $this->_logFileRoot = $filename;
     $this->_logRotate = $logRotate;
     $this->_logFileName = $this->_getLogFileName();
     // Empty the file if it is on rotation after a year
     $this->_checkLogOverwrite();
     try {
         $writer = new \Zend_Log_Writer_Stream($this->_logFileName);
     } catch (\Exception $exc) {
         try {
             // Try to solve the problem, otherwise fail heroically
             \MUtil_File::ensureDir(dirname($this->_logFileName));
             $writer = new \Zend_Log_Writer_Stream($this->_logFileName);
         } catch (\Exception $exc) {
             $this->bootstrap(array('locale', 'translate'));
             die(sprintf($this->translate->_('Path %s not writable'), dirname($this->_logFileName)));
         }
     }
     parent::__construct($writer);
     if (null !== $priority) {
         $this->setLogPriority($priority);
     }
 }
 /**
  * Tell all about it
  *
  * @param string $directory
  * @return string
  */
 protected function getDirInfo($directory)
 {
     if (!is_dir($directory)) {
         return sprintf($this->_('%s - does not exist'), $directory);
     }
     $free = disk_free_space($directory);
     $total = disk_total_space($directory);
     if (false === $free || false === $total) {
         return sprintf($this->_('%s - no disk information available'), $directory);
     }
     $percent = intval($free / $total * 100);
     return sprintf($this->_('%s - %s free of %s = %d%% available'), $directory, \MUtil_File::getByteSized($free), \MUtil_File::getByteSized($total), $percent);
 }
 /**
  * FilesystemIterator::current — The current file
  *
  * @return mixed null or artray
  */
 public function current()
 {
     $file = parent::current();
     if (!$file instanceof SplFileInfo) {
         return null;
     }
     $real = \MUtil_File::cleanupSlashes($file->getRealPath());
     // The relative file name uses the windows directory seperator convention as this
     // does not screw up the use of this value as a parameter
     $rel = \MUtil_File::cleanupSlashes(\MUtil_String::stripStringLeft($real, $this->startPath));
     // Function was first implemented in PHP 5.3.6
     if (method_exists($file, 'getExtension')) {
         $extension = $file->getExtension();
     } else {
         $extension = pathinfo($file->getFilename(), PATHINFO_EXTENSION);
     }
     return array('fullpath' => $real, 'relpath' => $rel, 'urlpath' => str_replace(array('\\', '/'), '|', $rel), 'path' => \MUtil_File::cleanupSlashes($file->getPath()), 'filename' => $file->getFilename(), 'extension' => $extension, 'content' => \MUtil_Lazy::call('file_get_contents', $real), 'size' => $file->getSize(), 'changed' => new \MUtil_Date($file->getMTime()));
 }
 /**
  * Initialize the logger
  *
  * @return \Gems_Log
  */
 protected function _initLogger()
 {
     $this->bootstrap('project');
     // Make sure the project object is available
     $logger = \Gems_Log::getLogger();
     $logPath = GEMS_ROOT_DIR . '/var/logs';
     try {
         $writer = new \Zend_Log_Writer_Stream($logPath . '/errors.log');
     } catch (Exception $exc) {
         try {
             // Try to solve the problem, otherwise fail heroically
             \MUtil_File::ensureDir($logPath);
             $writer = new \Zend_Log_Writer_Stream($logPath . '/errors.log');
         } catch (Exception $exc) {
             $this->bootstrap(array('locale', 'translate'));
             die(str_replace(GEMS_ROOT_DIR . '/', '', sprintf($this->translateAdapter->_('Path %s not writable') . "\n%s\n", $logPath, $exc->getMessage())));
         }
     }
     $filter = new \Zend_Log_Filter_Priority($this->project->getLogLevel());
     $writer->addFilter($filter);
     $logger->addWriter($writer);
     // OPTIONAL STARTY OF FIREBUG LOGGING.
     if ($this->_startFirebird) {
         $logger->addWriter(new \Zend_Log_Writer_Firebug());
         //We do not add the logLevel here, as the firebug window is intended for use by
         //developers only and it is only written to the active users' own screen.
     }
     \Zend_Registry::set('logger', $logger);
     return $logger;
 }
 /**
  * Hook that loads the form data from $_POST or the model
  *
  * Or from whatever other source you specify here.
  */
 protected function loadFormData()
 {
     if ($this->request->isPost()) {
         $this->formData = $this->request->getPost() + $this->formData;
     } else {
         foreach ($this->importModel->getColNames('default') as $name) {
             if (!(isset($this->formData[$name]) && $this->formData[$name])) {
                 $this->formData[$name] = $this->importModel->get($name, 'default');
             }
         }
     }
     if (!(isset($this->formData['import_id']) && $this->formData['import_id'])) {
         $this->formData['import_id'] = mt_rand(10000, 99999) . time();
     }
     $this->_session = new \Zend_Session_Namespace(__CLASS__ . '-' . $this->formData['import_id']);
     if (isset($this->formData[$this->stepFieldName]) && $this->formData[$this->stepFieldName] > 1 && !(isset($this->_session->localfile) && $this->_session->localfile)) {
         $this->_session->localfile = \MUtil_File::createTemporaryIn($this->tempDirectory, $this->request->getControllerName() . '_');
     }
     // Must always exists
     $this->fileMode = 'file' === $this->formData['mode'];
     // Set the translator
     $translator = $this->getImportTranslator();
     if ($translator instanceof \MUtil_Model_ModelTranslatorInterface) {
         $this->importer->setImportTranslator($translator);
     }
     // \MUtil_Echo::track($_POST, $_FILES, $this->formData);
 }
 /**
  *
  * @return \Gems_Task_TaskRunnerBatch
  */
 protected function getExportBatch($load = true)
 {
     if ($this->_batch) {
         return $this->_batch;
     }
     $this->_batch = $this->loader->getTaskRunnerBatch('track_export_' . $this->trackEngine->getTrackId());
     if (!$load || $this->_batch->isFinished()) {
         return $this->_batch;
     }
     if (!$this->_batch->isLoaded()) {
         $filename = \MUtil_File::createTemporaryIn(GEMS_ROOT_DIR . '/var/tmp/export/track');
         $trackId = $this->trackEngine->getTrackId();
         $this->_batch->setSessionVariable('filename', $filename);
         $this->_batch->addTask('Tracker\\Export\\ProjectVersionExportTask');
         $this->_batch->addTask('Tracker\\Export\\MainTrackExportTask', $this->trackEngine->getTrackId(), $this->formData['orgs']);
         if (isset($this->formData['fields']) && is_array($this->formData['fields'])) {
             // \MUtil_Echo::track($this->formData['fields']);
             foreach ($this->formData['fields'] as $fieldId) {
                 $this->_batch->addTask('Tracker\\Export\\TrackFieldExportTask', $trackId, $fieldId);
             }
         }
         $model = $this->getModel();
         foreach ($model->getCol('surveyId') as $surveyId) {
             $this->_batch->addTask('Tracker\\Export\\TrackSurveyExportTask', $trackId, $surveyId);
         }
         if (isset($this->formData['rounds']) && is_array($this->formData['rounds'])) {
             foreach ($this->formData['rounds'] as $roundId) {
                 $this->_batch->addTask('Tracker\\Export\\TrackRoundExportTask', $trackId, $roundId);
             }
         }
     } else {
         $filename = $this->_batch->getSessionVariable('filename');
     }
     $this->_batch->setVariable('file', fopen($filename, 'a'));
     return $this->_batch;
 }
Beispiel #14
0
 /**
  * Save the monitors to the monitor file.
  *
  * @param array $monitors
  */
 private static function _setMonitors(array $monitors)
 {
     if (!self::$monitorDir) {
         self::$monitorDir = getcwd();
     } else {
         \MUtil_File::ensureDir(self::$monitorDir);
     }
     $file = self::$monitorDir . DIRECTORY_SEPARATOR . self::$monitorFilename;
     file_put_contents($file, json_encode($monitors));
 }