/** * 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))); } }
/** * 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 } } } }
/** * 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; }
/** * 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); } }
/** * 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; }
/** * Creates the model * * @return \MUtil_Model_ModelAbstract */ protected function createModel() { if (!$this->importModel instanceof \MUtil_Model_ModelAbstract) { // $model = new \MUtil_Model_TableModel $model = new \MUtil_Model_SessionModel('import_for_' . $this->request->getControllerName()); $model->set('trans', 'label', $this->_('Import definition'), 'default', $this->defaultImportTranslator, 'description', $this->_('See import field definitions table'), 'multiOptions', $this->getTranslatorDescriptions(), 'required', true, 'elementClass', 'Radio', 'separator', ' '); $model->set('mode', 'label', $this->_('Choose work mode'), 'default', 'file', 'multiOptions', array('file' => $this->_('Upload a file'), 'textarea' => $this->_('Copy and paste into a text field')), 'required', true, 'elementClass', 'Radio', 'separator', ' '); $model->set('file', 'label', $this->_('Import file'), 'count', 1, 'elementClass', 'File', 'extension', 'csv,txt,xml', 'required', true); if ($this->tempDirectory) { \MUtil_File::ensureDir($this->tempDirectory); $model->set('file', 'destination', $this->tempDirectory); } // Storage for local copy of the file, kept through process $model->set('import_id'); $model->set('content', 'label', $this->_('Import text - user header line - separate fields using tabs'), 'description', $this->_('Empty fields remove any existing values. Add a field only when used.'), 'cols', 120, 'elementClass', 'Textarea'); $this->importModel = $model; } return $this->importModel; }
/** * Creates a new file and adds it to the files array */ protected function addFile() { $tempFilename = GEMS_ROOT_DIR . '/var/tmp/export-' . md5(time() . rand()); \MUtil_File::ensureDir(dirname($tempFilename)); $this->tempFilename = $tempFilename; if ($basename = $this->getExportModelSource()->getFileName($this->filter)) { $basename = $this->cleanupName($basename); } else { $basename = $this->cleanupName($this->model->getName()); } $filename = $basename; $i = 1; while (isset($this->files[$filename . $this->fileExtension])) { $filename = $basename . '_' . $i; $i++; } $this->filename = $filename; $this->files[$filename . $this->fileExtension] = $tempFilename . $this->fileExtension; $file = fopen($tempFilename . $this->fileExtension, 'w'); fclose($file); }
/** * 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)); }