public function log($loggingLevel = 2) { if (!file_exists($this->logFile)) { try { Filesystem::write($this->logFile, ''); } catch (\Exception $e) { $this->emailError($this->logFile, 'NO_LOG'); } } if (is_writable($this->logFile)) { $message = 'Log info: '; $message .= $this->message; if (!empty($this->postback)) { $message .= "\n" . "Postback info: " . serialize($this->postback) . "\n"; } $message .= "\n"; $hzl = new \Hubzero\Log\Writer(new \Monolog\Logger(Config::get('application_env')), \JDispatcher::getInstance()); $hzl->useFiles($this->logFile); if ($loggingLevel == 0) { $hzl->error($this->caller . ': ' . $message); } elseif ($loggingLevel == 1) { $log = $hzl->warning($this->caller . ': ' . $message); return $log; } elseif ($loggingLevel == 2) { $log = $hzl->info($this->caller . ': ' . $message); return $log; } // If error, needs to send email to admin $this->emailError($this->message, 'POSTBACK'); } else { $this->emailError($this->logFile, 'LOG'); } }
protected function generateMigration($migration) { $version = date('YmdHis'); $migration = $version . '_' . $migration . '.sql'; $this->createDir('db/migrations'); $this->log('created', 'db/migrations/' . $migration); Filesystem::write('db/migrations/' . $migration, ''); }
/** * @testdox dispatch should render output when only view exists */ public function testDispatchShouldRenderOutputWhenViewExists() { // create a test view Filesystem::createDir('app/views/missing', 0777); Filesystem::write('app/views/missing/test.htm.php', 'working'); $output = Dispatcher::dispatch(array('controller' => 'missing', 'action' => 'test') + self::$defaults); // destroy the test view Filesystem::delete('app/views/missing'); $this->assertNotEquals('', $output); }
public function renderTemplate($source, $destination, $data = array()) { if (!Filesystem::exists($destination)) { $view = new View(); $content = $view->renderView(Filesystem::path($source), $data); Filesystem::write($destination, $content); $this->log('created', $destination); } else { $this->log('exists', $destination); } }
/** * Method to store the source file contents. * * @param array The souce data to save. * * @return boolean True on success, false otherwise and internal error set. * @since 1.6 */ public function save($data) { // Get the template. $template = $this->getTemplate(); if (empty($template)) { return false; } $fileName = $this->getState('filename'); $client = JApplicationHelper::getClientInfo($template->client_id); $filePath = \Hubzero\Filesystem\Util::normalizePath($client->path . '/templates/' . $template->element . '/' . $fileName); // Set FTP credentials, if given. JClientHelper::setCredentialsFromRequest('ftp'); $ftp = JClientHelper::getCredentials('ftp'); // Try to make the template file writeable. if (!$ftp['enabled'] && JPath::isOwner($filePath) && !Filesystem::setPermissions($filePath, '0644')) { $this->setError(Lang::txt('COM_TEMPLATES_ERROR_SOURCE_FILE_NOT_WRITABLE')); return false; } // Trigger the onExtensionBeforeSave event. $result = Event::trigger('extension.onExtensionBeforeSave', array('com_templates.source', &$data, false)); if (in_array(false, $result, true)) { $this->setError($table->getError()); return false; } // [!] HUBZERO - Force line endings to be consistent with the server environment $data['source'] = preg_replace('~\\R~u', PHP_EOL, $data['source']); $return = Filesystem::write($filePath, $data['source']); // Try to make the template file unwriteable. if (!$ftp['enabled'] && JPath::isOwner($filePath) && !Filesystem::setPermissions($filePath, '0444')) { $this->setError(Lang::txt('COM_TEMPLATES_ERROR_SOURCE_FILE_NOT_UNWRITABLE')); return false; } elseif (!$return) { $this->setError(Lang::txt('COM_TEMPLATES_ERROR_FAILED_TO_SAVE_FILENAME', $fileName)); return false; } // Trigger the onExtensionAfterSave event. Event::trigger('extension.onExtensionAfterSave', array('com_templates.source', &$table, false)); return true; }
/** * Method to rename the template in the XML files and rename the language files * * @return boolean true if successful, false otherwise * @since 2.5 */ protected function fixTemplateName() { // Rename Language files // Get list of language files $result = true; $files = Filesystem::files($this->getState('to_path'), '.ini', true, true); $newName = strtolower($this->getState('new_name')); $oldName = $this->getTemplate()->element; foreach ($files as $file) { $newFile = str_replace($oldName, $newName, $file); $result = Filesystem::move($file, $newFile) && $result; } // Edit XML file $xmlFile = $this->getState('to_path') . '/templateDetails.xml'; if (Filesystem::exists($xmlFile)) { $contents = Filesystem::read($xmlFile); $pattern[] = '#<name>\\s*' . $oldName . '\\s*</name>#i'; $replace[] = '<name>' . $newName . '</name>'; $pattern[] = '#<language(.*)' . $oldName . '(.*)</language>#'; $replace[] = '<language${1}' . $newName . '${2}</language>'; $contents = preg_replace($pattern, $replace, $contents); $result = Filesystem::write($xmlFile, $contents) && $result; } return $result; }
/** * Read SSH key * * @return string - .ssh/authorized_keys file content */ private function readKey() { // Webdav path $base = DS . 'webdav' . DS . 'home'; $user = DS . $this->member->get('username'); $ssh = DS . '.ssh'; $auth = DS . 'authorized_keys'; // Real home directory $homeDir = $this->member->get('homeDirectory'); $key = ''; // First, make sure webdav is there and that the necessary folders are there if (!Filesystem::exists($base)) { // Not sure what to do here return $key = false; } if (!Filesystem::exists($homeDir)) { // Try to create their home directory require_once PATH_CORE . DS . 'components' . DS . 'com_tools' . DS . 'helpers' . DS . 'utils.php'; if (!\Components\Tools\Helpers\Utils::createHomeDirectory($this->member->get('username'))) { return $key = false; } } if (!Filesystem::exists($base . $user . $ssh)) { // User doesn't have an ssh directory, so try to create one (with appropriate permissions) if (!Filesystem::makeDirectory($base . $user . $ssh, 0700)) { return $key = false; } } if (!Filesystem::exists($base . $user . $ssh . $auth)) { // Try to create their authorized keys file $content = ''; // J25 passes param by reference so couldn't use constant below Filesystem::write($base . $user . $ssh . $auth, $content); if (!Filesystem::exists($base . $user . $ssh . $auth)) { return $key = false; } else { // Set correct permissions on authorized_keys file JPath::setPermissions($base . $user . $ssh . $auth, '0600'); return $key; } } // Read the file contents $key = Filesystem::read($base . $user . $ssh . $auth); return $key; }
public function save($filename) { $this->render(); Filesystem::write($filename, $this->DomPdf->output()); }
/** * Runs a rappture job. * * This is more than just invoking a tool. We're expecting a driver file to pass to the * tool to be picked up and automatically run by rappture. * * @apiMethod POST * @apiUri /tools/run * @apiParameter { * "name": "app", * "description": "Name of app installed as a tool in the hub", * "type": "string", * "required": true, * } * @apiParameter { * "name": "revision", * "description": "The specific requested revision of the app", * "type": "string", * "required": false, * "default": "default", * } * @apiParameter { * "name": "xml", * "description": "Content of the driver file that rappture will use to invoke the given app", * "type": "string", * "required": true, * } * @return void */ public function runTask() { $this->requiresAuthentication(); // Get the user_id and attempt to load user profile $userid = App::get('authn')['user_id']; $profile = User::getInstance($userid); // Make sure we have a user if (!$profile->get('id')) { throw new Exception(Lang::txt('Unable to find user.'), 404); } // Grab tool name and version $tool_name = Request::getVar('app', ''); $tool_version = Request::getVar('revision', 'default'); // Build application object $app = new stdClass(); $app->name = trim(str_replace(':', '-', $tool_name)); $app->version = $tool_version; $app->ip = $_SERVER["REMOTE_ADDR"]; // Check to make sure we have an app to invoke if (!$app->name) { throw new Exception(Lang::txt('A valid app name must be provided'), 404); } // Include needed tool libraries require_once dirname(dirname(__DIR__)) . DS . 'tables' . DS . 'version.php'; require_once dirname(dirname(__DIR__)) . DS . 'tables' . DS . 'session.php'; require_once dirname(dirname(__DIR__)) . DS . 'tables' . DS . 'viewperm.php'; // Create database object $database = \App::get('db'); // Load the tool version $tv = new \Components\Tools\Tables\Version($database); switch ($app->version) { case 1: case 'default': $app->name = $tv->getCurrentVersionProperty($app->name, 'instance'); break; case 'test': case 'dev': $app->name .= '_dev'; break; default: $app->name .= '_r' . $app->version; break; } $app->toolname = $app->name; if ($parent = $tv->getToolname($app->name)) { $app->toolname = $parent; } // Check of the toolname has a revision indicator $r = substr(strrchr($app->name, '_'), 1); if (substr($r, 0, 1) != 'r' && substr($r, 0, 3) != 'dev') { $r = ''; } // No version passed and no revision if ((!$app->version || $app->version == 'default') && !$r) { // Get the latest version $app->version = $tv->getCurrentVersionProperty($app->toolname, 'revision'); $app->name = $app->toolname . '_r' . $app->version; } // Get the caption/session title $tv->loadFromInstance($app->name); $app->caption = stripslashes($tv->title); $app->title = stripslashes($tv->title); // Make sure we have a valid tool if ($app->title == '' || $app->toolname == '') { throw new Exception(Lang::txt('The tool "%s" does not exist on the HUB.', $tool_name), 404); } // Get tool access $toolAccess = \Components\Tools\Helpers\Utils::getToolAccess($app->name, $profile->get('username')); // Do we have access if ($toolAccess->valid != 1) { throw new Exception($toolAccess->error->message, 500); } // Log the launch attempt \Components\Tools\Helpers\Utils::recordToolUsage($app->toolname, $profile->get('id')); // Get the middleware database $mwdb = \Components\Tools\Helpers\Utils::getMWDBO(); // Find out how many sessions the user is running $ms = new \Components\Tools\Tables\Session($mwdb); $jobs = $ms->getCount($profile->get('username')); // Find out how many sessions the user is ALLOWED to run. include_once dirname(dirname(__DIR__)) . DS . 'tables' . DS . 'preferences.php'; $preferences = new \Components\Tools\Tables\Preferences($database); $preferences->loadByUser($profile->get('id')); if (!$preferences || !$preferences->id) { $default = $preferences->find('one', array('alias' => 'default')); $preferences->user_id = $profile->get('id'); $preferences->class_id = $default->id; $preferences->jobs = $default->jobs; $preferences->store(); } $remain = $preferences->jobs - $jobs; //can we open another session if ($remain <= 0) { throw new Exception(Lang::txt('You are using all (%s) your available job slots.', $jobs), 401); } // Check for an incoming driver file if ($driver = Request::getVar('xml', false, 'post', 'none', 2)) { // Build a path to where the driver file will go through webdav $base = DS . 'webdav' . DS . 'home'; $user = DS . $profile->get('username'); $data = DS . 'data'; $drvr = DS . '.queued_drivers'; $inst = DS . md5(time()) . '.xml'; // Real home directory $homeDir = $profile->get('homeDirectory'); // First, make sure webdav is there and that the necessary folders are there if (!\Filesystem::exists($base)) { throw new Exception(Lang::txt('Home directories are unavailable'), 500); } // Now see if the user has a home directory yet if (!\Filesystem::exists($homeDir)) { // Try to create their home directory require_once dirname(dirname(__DIR__)) . DS . 'helpers' . DS . 'utils.php'; if (!\Components\Tools\Helpers\Utils::createHomeDirectory($profile->get('username'))) { throw new Exception(Lang::txt('Failed to create user home directory'), 500); } } // Check for, and create if needed a session data directory if (!\Filesystem::exists($base . $user . $data) && !\Filesystem::makeDirectory($base . $user . $data, 0700)) { throw new Exception(Lang::txt('Failed to create data directory'), 500); } // Check for, and create if needed a queued drivers directory if (!\Filesystem::exists($base . $user . $data . $drvr) && !\Filesystem::makeDirectory($base . $user . $data . $drvr, 0700)) { throw new Exception(Lang::txt('Failed to create drivers directory'), 500); } // Write the driver file out if (!\Filesystem::write($base . $user . $data . $drvr . $inst, $driver)) { throw new Exception(Lang::txt('Failed to create driver file'), 500); } } else { throw new Exception(Lang::txt('No driver file provided'), 404); } // Now build params path that will be included with tool execution // We know from the checks above that this directory already exists $params = 'file(execute):' . $homeDir . DS . 'data' . DS . '.queued_drivers' . $inst; $encoded = ' params=' . rawurlencode($params) . ' '; $command = 'start user='******'username') . " ip={$app->ip} app={$app->name} version={$app->version}" . $encoded; $status = \Components\Tools\Helpers\Utils::middleware($command, $output); if (!$status) { throw new Exception(Lang::txt('Tool invocation failed'), 500); } $this->send(array('success' => true, 'session' => $output->session)); }
/** * Refresh the help * * @return void */ public function refreshHelp() { // Set FTP credentials, if given \JClientHelper::setCredentialsFromRequest('ftp'); if (($data = file_get_contents('http://help.joomla.org/helpsites.xml')) === false) { App::redirect(Route::url('index.php?option=com_config', false), Lang::txt('COM_CONFIG_ERROR_HELPREFRESH_FETCH'), 'error'); } elseif (!\Filesystem::write(JPATH_BASE . '/help/helpsites.xml', $data)) { App::redirect(Route::url('index.php?option=com_config', false), Lang::txt('COM_CONFIG_ERROR_HELPREFRESH_ERROR_STORE'), 'error'); } else { App::redirect(Route::url('index.php?option=com_config', false), Lang::txt('COM_CONFIG_HELPREFRESH_SUCCESS')); } }
/** * Method to save the form data. * * @param array $data The form data. * @param boolean $opposite_client Indicates whether the override should not be created for the current client * * @return boolean True on success, false otherwise. * * @since 2.5 */ public function save($data, $opposite_client = false) { require_once JPATH_COMPONENT . '/helpers/languages.php'; $client = User::getState('com_languages.overrides.filter.client', 0); $language = User::getState('com_languages.overrides.filter.language', 'en-GB'); // If the override should be created for both if ($opposite_client) { $client = 1 - $client; } $client = $client ? 'administrator' : 'site'; // Parse the override.ini file in oder to get the keys and strings $filename = PATH_APP . '/bootstrap/' . $client . '/language/overrides/' . $language . '.override.ini'; $strings = LanguagesHelper::parseFile($filename); if (isset($strings[$data['id']])) { // If an existent string was edited check whether // the name of the constant is still the same if ($data['key'] == $data['id']) { // If yes, simply override it $strings[$data['key']] = $data['override']; } else { // If no, delete the old string and prepend the new one unset($strings[$data['id']]); $strings = array($data['key'] => $data['override']) + $strings; } } else { // If it is a new override simply prepend it $strings = array($data['key'] => $data['override']) + $strings; } foreach ($strings as $key => $string) { $strings[$key] = str_replace('"', '"_QQ_"', $string); } // Write override.ini file with the strings $registry = new \Hubzero\Config\Registry($strings); if (!Filesystem::write($filename, $registry->toString('INI'))) { return false; } // If the override should be stored for both clients save // it also for the other one and prevent endless recursion if (isset($data['both']) && $data['both'] && !$opposite_client) { return $this->save($data, true); } return true; }
/** * Create manifest file for video * * @param $resource HUB Resource * @return Void */ private function createVideoManifestForResource($resource) { //base url for the resource $base = DS . trim($this->config->get('uploadpath'), DS); //build the rest of the resource path and combine with base $path = Html::build_path($resource->created, $resource->id, ''); //instantiate params object then parse resource attributes $attributes = new \Hubzero\Config\Registry($resource->attribs); //var to hold manifest data $manifest = new stdClass(); $manifest->presentation = new stdClass(); $manifest->presentation->title = $resource->title; $manifest->presentation->type = 'Video'; $manifest->presentation->width = intval($attributes->get('width', 0)); $manifest->presentation->height = intval($attributes->get('height', 0)); $manifest->presentation->duration = intval($attributes->get('duration', 0)); $manifest->presentation->media = array(); $manifest->presentation->subtitles = array(); //get the videos $videos = \Filesystem::files(PATH_APP . DS . $base . $path, '.mp4|.MP4|.ogv|.OGV|.webm|.WEBM'); //add each video to manifest foreach ($videos as $k => $video) { // get info about video $videoInfo = pathinfo($video); // object to hold media type & source $media = new stdClass(); $media->type = $videoInfo['extension']; $media->source = $path . DS . $video; // add media object to array of media $manifest->presentation->media[] = $media; } //get the subs $subtitles = \Filesystem::files(PATH_APP . DS . $base . $path, '.srt|.SRT'); //add each subtitle to manifest foreach ($subtitles as $k => $subtitle) { //get name $info = pathinfo($subtitle); $name = str_replace('-auto', '', $info['filename']); $name = ucfirst($name); // object to hold subtitle info $sub = new stdClass(); $sub->type = 'SRT'; $sub->name = $name; $sub->source = $path . DS . $subtitle; $sub->autoplay = strstr($subtitle, '-') ? 1 : 0; // add sub object to array of subtitles $manifest->presentation->subtitles[] = $sub; } //reset array of subs and media $manifest->presentation->media = array_values($manifest->presentation->media); $manifest->presentation->subtitles = array_values($manifest->presentation->subtitles); // json encode manifest $manifest = json_encode($manifest, JSON_PRETTY_PRINT); // attempt to create manifest file if (!\Filesystem::write(PATH_APP . DS . $base . $path . DS . 'presentation.json', $manifest)) { return false; } return true; }
public function testNoop() { $filesystem = new Filesystem(new Adapter\Local(__DIR__ . '/files'), new Cache\Noop()); $filesystem->write('test.txt', 'contents'); $this->assertTrue($filesystem->has('test.txt')); $this->assertInternalType('array', $filesystem->listContents()); $cache = $filesystem->getCache(); $cache->setComplete('', false); $cache->flush(); $cache->autosave(); $this->assertFalse($cache->isComplete('', false)); $this->assertFalse($cache->read('something')); $this->assertFalse($cache->getMetadata('something')); $this->assertFalse($cache->getMimetype('something')); $this->assertFalse($cache->getSize('something')); $this->assertFalse($cache->getTimestamp('something')); $this->assertFalse($cache->getVisibility('something')); $this->assertFalse($cache->listContents('', false)); $filesystem->delete('test.txt'); }
/** * Create a folder * * @param string $path Path of the folder to create * @since 1.5 */ public function create() { // Check for request forgeries Session::checkToken(['get', 'post']); $folder = Request::getCmd('foldername', ''); $folderCheck = Request::getVar('foldername', null, '', 'string', JREQUEST_ALLOWRAW); $parent = Request::getVar('folderbase', '', '', 'path'); $this->setRedirect('index.php?option=com_media&folder=' . $parent . '&tmpl=' . Request::getCmd('tmpl', 'index')); if (strlen($folder) > 0) { if (!User::authorise('core.create', 'com_media')) { // User is not authorised to delete Notify::warning(Lang::txt('JLIB_APPLICATION_ERROR_CREATE_NOT_PERMITTED')); return false; } // Set FTP credentials, if given JClientHelper::setCredentialsFromRequest('ftp'); Request::setVar('folder', $parent); if ($folderCheck !== null && $folder !== $folderCheck) { $this->setMessage(Lang::txt('COM_MEDIA_ERROR_UNABLE_TO_CREATE_FOLDER_WARNDIRNAME')); return false; } $path = \Hubzero\Filesystem\Util::normalizePath(COM_MEDIA_BASE . '/' . $parent . '/' . $folder); if (!is_dir($path) && !is_file($path)) { // Trigger the onContentBeforeSave event. $object_file = new \Hubzero\Base\Object(array('filepath' => $path)); $result = Event::trigger('content.onContentBeforeSave', array('com_media.folder', &$object_file, true)); if (in_array(false, $result, true)) { // There are some errors in the plugins Notify::warning(Lang::txts('COM_MEDIA_ERROR_BEFORE_SAVE', count($errors = $object_file->getErrors()), implode('<br />', $errors))); return false; } Filesystem::makeDirectory($path); $data = "<html>\n<body bgcolor=\"#FFFFFF\">\n</body>\n</html>"; Filesystem::write($path . "/index.html", $data); // Trigger the onContentAfterSave event. Event::trigger('content.onContentAfterSave', array('com_media.folder', &$object_file, true)); $this->setMessage(Lang::txt('COM_MEDIA_CREATE_COMPLETE', substr($path, strlen(COM_MEDIA_BASE)))); } Request::setVar('folder', $parent ? $parent . '/' . $folder : $folder); } }
/** * Chama parseIndex() e salva o xml final em um arquivo * * @version * 0.1 24/05/2010 * Inicial * 0.2 02/11/2010 * Adicionado o parâmetro $filename, para poder decidir onde o * sitemap será salvo. * * @param $filename string O arquivo final para salvamento * @return boolean True se for salvo com sucesso, e false se ocorrer algum erro */ public function saveIndex($filename = '/public/sitemap.xml') { return Filesystem::write($filename, $this->parseIndex()); }