exists() public static method

public static exists ( $file )
示例#1
0
 /**
  * Method for parsing ini files
  *
  * @param		string	$filename Path and name of the ini file to parse
  *
  * @return	array		Array of strings found in the file, the array indices will be the keys. On failure an empty array will be returned
  *
  * @since		2.5
  */
 public static function parseFile($filename)
 {
     if (!Filesystem::exists($filename)) {
         return array();
     }
     // Capture hidden PHP errors from the parsing
     $version = phpversion();
     $php_errormsg = null;
     $track_errors = ini_get('track_errors');
     ini_set('track_errors', true);
     if ($version >= '5.3.1') {
         $contents = file_get_contents($filename);
         $contents = str_replace('_QQ_', '"\\""', $contents);
         $strings = @parse_ini_string($contents);
         if ($strings === false) {
             return array();
         }
     } else {
         $strings = @parse_ini_file($filename);
         if ($strings === false) {
             return array();
         }
         if ($version == '5.3.0' && is_array($strings)) {
             foreach ($strings as $key => $string) {
                 $strings[$key] = str_replace('_QQ_', '"', $string);
             }
         }
     }
     return $strings;
 }
示例#2
0
 public function element($element, $data = array())
 {
     $element_path = Filesystem::path('app/views/') . $this->elementName($element);
     if (Filesystem::exists($element_path)) {
         return $this->renderView($element_path, $data);
     } else {
         throw new MissingViewException($this->filename($element) . ' could not be found');
     }
 }
示例#3
0
 public static function load($name)
 {
     if (!class_exists($name) && Filesystem::exists('lib/behaviors/' . $name . '.php')) {
         require_once 'lib/behaviors/' . $name . '.php';
     }
     if (!class_exists($name)) {
         throw new MissingBehaviorException(array('behavior' => $name));
     }
 }
示例#4
0
 public static function load($name)
 {
     if (!class_exists($name) && Filesystem::exists('lib/helpers/' . $name . '.php')) {
         require_once 'lib/helpers/' . $name . '.php';
     }
     if (!class_exists($name)) {
         $message = 'The helper <code>' . $name . '</code> was not found.';
         throw new RuntimeException('The helper <code>' . $name . '</code> was not found.');
     }
 }
示例#5
0
 public static function load($name)
 {
     $filename = 'lib/behaviors/' . $name . '.php';
     if (!class_exists($name) && Filesystem::exists($filename)) {
         require $filename;
     }
     if (!class_exists($name)) {
         throw new RuntimeException('The behavior <code>' . $name . '</code> was not found.');
     }
 }
示例#6
0
 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);
     }
 }
示例#7
0
 /**
  * Method for refreshing the cache in the database with the known language strings
  *
  * @return	boolean	True on success, Exception object otherwise
  *
  * @since		2.5
  */
 public function refresh()
 {
     require_once JPATH_COMPONENT . '/helpers/languages.php';
     $app = JFactory::getApplication();
     $app->setUserState('com_languages.overrides.cachedtime', null);
     // Empty the database cache first
     try {
         $this->_db->setQuery('TRUNCATE TABLE ' . $this->_db->qn('#__overrider'));
         $this->_db->query();
     } catch (RuntimeException $e) {
         return $e;
     }
     // Create the insert query
     $query = $this->_db->getQuery(true)->insert($this->_db->qn('#__overrider'))->columns('constant, string, file');
     // Initialize some variables
     $client = $app->getUserState('com_languages.overrides.filter.client', 'site') ? 'administrator' : 'site';
     $language = $app->getUserState('com_languages.overrides.filter.language', 'en-GB');
     $base = constant('JPATH_' . strtoupper($client));
     $path = $base . '/language/' . $language;
     $files = array();
     // Parse common language directory
     if (Filesystem::exists($path)) {
         $files = Filesystem::files($path, $language . '.*ini$', false, true);
     }
     // Parse language directories of components
     $files = array_merge($files, Filesystem::files($base . '/components', $language . '.*ini$', 3, true));
     // Parse language directories of modules
     $files = array_merge($files, Filesystem::files($base . '/modules', $language . '.*ini$', 3, true));
     // Parse language directories of templates
     $files = array_merge($files, Filesystem::files($base . '/templates', $language . '.*ini$', 3, true));
     // Parse language directories of plugins
     $files = array_merge($files, Filesystem::files(JPATH_PLUGINS, $language . '.*ini$', 3, true));
     // Parse all found ini files and add the strings to the database cache
     foreach ($files as $file) {
         $strings = LanguagesHelper::parseFile($file);
         if ($strings && count($strings)) {
             $query->clear('values');
             foreach ($strings as $key => $string) {
                 $query->values($this->_db->q($key) . ',' . $this->_db->q($string) . ',' . $this->_db->q(JPath::clean($file)));
             }
             try {
                 $this->_db->setQuery($query);
                 if (!$this->_db->query()) {
                     return new Exception($this->_db->getErrorMsg());
                 }
             } catch (RuntimeException $e) {
                 return $e;
             }
         }
     }
     // Update the cached time
     $app->setUserState('com_languages.overrides.cachedtime.' . $client . '.' . $language, time());
     return true;
 }
示例#8
0
 /**
  * Method to get the lang tag
  * @return string lang iso tag
  */
 function &getLangTag()
 {
     if (is_null($this->lang_tag)) {
         $this->lang_tag = Lang::getTag();
         if (!Filesystem::exists(JPATH_BASE . '/help/' . $this->lang_tag)) {
             $this->lang_tag = 'en-GB';
             // use english as fallback
         }
     }
     return $this->lang_tag;
 }
示例#9
0
 public function toString()
 {
     ob_end_clean();
     $this->header($this->status);
     if (Filesystem::exists('app/views/layouts/error.htm.php')) {
         $view = new View();
         return $view->renderView('app/views/layouts/error.htm.php', array('exception' => $this));
     } else {
         echo '<pre>';
         throw new Exception('error layout was not found');
     }
 }
示例#10
0
 public static function load($name, $instance = false)
 {
     if (!class_exists($name) && Filesystem::exists('lib/components/' . $name . '.php')) {
         require_once 'lib/components/' . $name . '.php';
     }
     if (class_exists($name)) {
         if ($instance) {
             return new $name();
         } else {
             return true;
         }
     } else {
         throw new MissingComponentException(array('component' => $name));
     }
 }
示例#11
0
 public static function load($name, $instance = false)
 {
     if (!class_exists($name) && Filesystem::exists('app/controllers/' . Inflector::underscore($name) . '.php')) {
         require_once 'app/controllers/' . Inflector::underscore($name) . '.php';
     }
     if (class_exists($name)) {
         if ($instance) {
             return new $name();
         } else {
             return true;
         }
     } else {
         throw new MissingControllerException(array('controller' => $name));
     }
 }
示例#12
0
 public static function load($name)
 {
     if (!array_key_exists($name, Model::$instances)) {
         if (!class_exists($name) && Filesystem::exists('app/models/' . Inflector::underscore($name) . '.php')) {
             require_once 'app/models/' . Inflector::underscore($name) . '.php';
         }
         if (class_exists($name)) {
             Model::$instances[$name] = new $name();
             Model::$instances[$name]->connection();
             Model::$instances[$name]->createLinks();
         } else {
             throw new MissingModelException(array('model' => $name));
         }
     }
     return Model::$instances[$name];
 }
示例#13
0
文件: Template.php 项目: bugotech/io
 /**
  * Registrar parametro do template.
  */
 public function param($name, $value = '')
 {
     // Se foi informado um array
     if (is_array($name)) {
         foreach ($name as $n => $v) {
             $this->param($n, $v);
         }
         return $this;
     }
     // Aplicar parâmetro nos filtros
     foreach ($this->filters as $filter_file) {
         if ($this->files->exists($filter_file) != true) {
             error('File %s not found', $filter_file);
         }
         $buffer = file_get_contents($filter_file);
         $buffer = str_replace('{{' . $name . '}}', $value, $buffer);
         file_put_contents($filter_file, $buffer);
     }
     return $this;
 }
示例#14
0
 protected function getTypeOptionsFromLayouts($component, $view)
 {
     // Initialise variables.
     $options = array();
     $layouts = array();
     $layoutNames = array();
     $templateLayouts = array();
     $lang = Lang::getRoot();
     // Get the layouts from the view folder.
     $path = PATH_CORE . '/components/' . $component . '/views/' . $view . '/tmpl';
     $path2 = PATH_CORE . '/components/' . $component . '/site/views/' . $view . '/tmpl';
     if (Filesystem::exists($path)) {
         $layouts = array_merge($layouts, Filesystem::files($path, '.xml$', false, true));
     } else {
         if (Filesystem::exists($path2)) {
             $layouts = array_merge($layouts, Filesystem::files($path2, '.xml$', false, true));
         } else {
             return $options;
         }
     }
     // build list of standard layout names
     foreach ($layouts as $layout) {
         $layout = trim($layout, '/');
         // Ignore private layouts.
         if (strpos(basename($layout), '_') === false) {
             $file = $layout;
             // Get the layout name.
             $layoutNames[] = Filesystem::name(basename($layout));
         }
     }
     // get the template layouts
     // TODO: This should only search one template -- the current template for this item (default of specified)
     $folders = Filesystem::directories(JPATH_SITE . '/templates', '', false, true);
     // Array to hold association between template file names and templates
     $templateName = array();
     foreach ($folders as $folder) {
         if (Filesystem::exists($folder . '/html/' . $component . '/' . $view)) {
             $template = basename($folder);
             $lang->load('tpl_' . $template . '.sys', JPATH_SITE, null, false, true) || $lang->load('tpl_' . $template . '.sys', JPATH_SITE . '/templates/' . $template, null, false, true);
             $templateLayouts = Filesystem::files($folder . '/html/' . $component . '/' . $view, '.xml$', false, true);
             foreach ($templateLayouts as $layout) {
                 $file = trim($layout, '/');
                 // Get the layout name.
                 $templateLayoutName = Filesystem::name(basename($layout));
                 // add to the list only if it is not a standard layout
                 if (array_search($templateLayoutName, $layoutNames) === false) {
                     $layouts[] = $layout;
                     // Set template name array so we can get the right template for the layout
                     $templateName[$layout] = basename($folder);
                 }
             }
         }
     }
     // Process the found layouts.
     foreach ($layouts as $layout) {
         $layout = trim($layout, '/');
         // Ignore private layouts.
         if (strpos(basename($layout), '_') === false) {
             $file = $layout;
             // Get the layout name.
             $layout = Filesystem::name(basename($layout));
             // Create the menu option for the layout.
             $o = new \Hubzero\Base\Object();
             $o->title = ucfirst($layout);
             $o->description = '';
             $o->request = array('option' => $component, 'view' => $view);
             // Only add the layout request argument if not the default layout.
             if ($layout != 'default') {
                 // If the template is set, add in format template:layout so we save the template name
                 $o->request['layout'] = isset($templateName[$file]) ? $templateName[$file] . ':' . $layout : $layout;
             }
             // Load layout metadata if it exists.
             if (is_file($file)) {
                 // Attempt to load the xml file.
                 if ($xml = simplexml_load_file($file)) {
                     // Look for the first view node off of the root node.
                     if ($menu = $xml->xpath('layout[1]')) {
                         $menu = $menu[0];
                         // If the view is hidden from the menu, discard it and move on to the next view.
                         if (!empty($menu['hidden']) && $menu['hidden'] == 'true') {
                             unset($xml);
                             unset($o);
                             continue;
                         }
                         // Populate the title and description if they exist.
                         if (!empty($menu['title'])) {
                             $o->title = trim((string) $menu['title']);
                         }
                         if (!empty($menu->message[0])) {
                             $o->description = trim((string) $menu->message[0]);
                         }
                     }
                 }
             }
             // Add the layout to the options array.
             $options[] = $o;
         }
     }
     return $options;
 }
示例#15
0
 /**
  * Upload a file or create a new folder
  *
  * @return  void
  */
 public function uploadTask()
 {
     // Check for request forgeries
     Request::checkToken();
     // Incoming directory (this should be a path built from a resource ID and its creation year/month)
     $listdir = Request::getVar('listdir', '', 'post');
     if (!$listdir) {
         $this->setError(Lang::txt('COM_RESOURCES_ERROR_NO_LISTDIR'));
         $this->displayTask();
         return;
     }
     // Incoming sub-directory
     $subdir = Request::getVar('dirPath', '', 'post');
     // Build the path
     $path = Utilities::buildUploadPath($listdir, $subdir);
     // Are we creating a new folder?
     $foldername = Request::getVar('foldername', '', 'post');
     if ($foldername != '') {
         // Make sure the name is valid
         if (preg_match("/[^0-9a-zA-Z_]/i", $foldername)) {
             $this->setError(Lang::txt('COM_RESOURCES_ERROR_DIR_INVALID_CHARACTERS'));
         } else {
             if (!is_dir($path . DS . $foldername)) {
                 if (!\Filesystem::makeDirectory($path . DS . $foldername)) {
                     $this->setError(Lang::txt('COM_RESOURCES_ERROR_UNABLE_TO_CREATE_UPLOAD_PATH'));
                 }
             } else {
                 $this->setError(Lang::txt('COM_RESOURCES_ERROR_DIR_EXISTS'));
             }
         }
         // Directory created
     } else {
         // Make sure the upload path exist
         if (!is_dir($path)) {
             if (!\Filesystem::makeDirectory($path)) {
                 $this->setError(Lang::txt('COM_RESOURCES_ERROR_UNABLE_TO_CREATE_UPLOAD_PATH'));
                 $this->displayTask();
                 return;
             }
         }
         // Incoming file
         $file = Request::getVar('upload', '', 'files', 'array');
         if (!$file['name']) {
             $this->setError(Lang::txt('COM_RESOURCES_ERROR_NO_FILE'));
             $this->displayTask();
             return;
         }
         // Make the filename safe
         $file['name'] = \Filesystem::clean($file['name']);
         // Ensure file names fit.
         $ext = \Filesystem::extension($file['name']);
         $file['name'] = str_replace(' ', '_', $file['name']);
         if (strlen($file['name']) > 230) {
             $file['name'] = substr($file['name'], 0, 230);
             $file['name'] .= '.' . $ext;
         }
         // Perform the upload
         if (!\Filesystem::upload($file['tmp_name'], $path . DS . $file['name'])) {
             $this->setError(Lang::txt('COM_RESOURCES_ERROR_UPLOADING'));
         } else {
             // File was uploaded
             // Was the file an archive that needs unzipping?
             $batch = Request::getInt('batch', 0, 'post');
             if ($batch) {
                 //build path
                 $path = rtrim($path, DS) . DS;
                 $escaped_file = escapeshellarg($path . $file['name']);
                 //determine command to uncompress
                 switch ($ext) {
                     case 'gz':
                         $cmd = "tar zxvf {$escaped_file} -C {$path}";
                         break;
                     case 'tar':
                         $cmd = "tar xvf {$escaped_file} -C {$path}";
                         break;
                     case 'zip':
                     default:
                         $cmd = "unzip -o {$escaped_file} -d {$path}";
                 }
                 //unzip file
                 if ($result = shell_exec($cmd)) {
                     // Remove original archive
                     \Filesystem::delete($path . $file['name']);
                     // Remove MACOSX dirs if there
                     if (\Filesystem::exists($path . '__MACOSX')) {
                         \Filesystem::deleteDirectory($path . '__MACOSX');
                     }
                     //remove ._ files
                     $dotFiles = \Filesystem::files($path, '._[^\\s]*', true, true);
                     foreach ($dotFiles as $dotFile) {
                         \Filesystem::delete($dotFile);
                     }
                 }
             }
         }
     }
     // Push through to the media view
     $this->displayTask();
 }
示例#16
0
 public static function loadConfiguration($sKey)
 {
     $aSegment = explode('.', $sKey);
     if (Arr::size($aSegment) > 0) {
         $sConfigName = Arr::first($aSegment);
         if (!isset(self::$aConfiguration[$sConfigName])) {
             self::initConfiguration();
             $aTmpConfig = array();
             // Common config
             $sCommonConfigPath = self::$sRealRootPath . RELATIVE_PATH_ROOT_TO_CONFIG . FOLDER_CONFIG_GLOBAL . $sConfigName . '.php';
             if (Filesystem::exists($sCommonConfigPath)) {
                 $aTmpConfig = (require $sCommonConfigPath);
             }
             // Env config
             $sCurrentEnvironment = self::getEnvironment();
             $sConfigEnvironmentPath = self::$sRealRootPath . RELATIVE_PATH_ROOT_TO_CONFIG . $sCurrentEnvironment . '/' . $sConfigName . '.php';
             if (Filesystem::exists($sConfigEnvironmentPath)) {
                 $aTmpConfig = array_merge($aTmpConfig, require $sConfigEnvironmentPath);
             }
             self::$aConfiguration[$sConfigName] = $aTmpConfig;
         }
     }
 }
示例#17
0
 /**
  * Create group folder id doesnt exist
  *
  * @param  [type] $path [description]
  * @return [type]       [description]
  */
 private function _createGroupFolder($path)
 {
     // create base group folder
     if (!Filesystem::exists($path)) {
         Filesystem::makeDirectory($path);
     }
     // create uploads file
     if (!Filesystem::exists($path . DS . 'uploads')) {
         Filesystem::makeDirectory($path . DS . 'uploads');
     }
 }
示例#18
0
 /**
  * Generate detailed responses CSV files and zip and offer up as download
  *
  * @return void
  **/
 private function downloadresponses()
 {
     require_once PATH_CORE . DS . 'components' . DS . 'com_courses' . DS . 'models' . DS . 'formReport.php';
     // Only allow for instructors
     if (!$this->course->offering()->section()->access('manage')) {
         App::abort(403, 'Sorry, you don\'t have permission to do this');
     }
     if (!($asset_ids = Request::getVar('assets', false))) {
         App::abort(422, 'Sorry, we don\'t know what results you\'re trying to retrieve');
     }
     $protected = 'site' . DS . 'protected';
     $tmp = $protected . DS . 'tmp';
     // We're going to temporarily house this in PATH_APP/site/protected/tmp
     if (!Filesystem::exists($protected)) {
         App::abort(500, 'Missing temporary directory');
     }
     // Make sure tmp folder exists
     if (!Filesystem::exists($tmp)) {
         Filesystem::makeDirectory($tmp);
     } else {
         // Folder was already there - do a sanity check and make sure no old responses zips are lying around
         $files = Filesystem::files($tmp);
         if ($files && count($files) > 0) {
             foreach ($files as $file) {
                 if (strstr($file, 'responses.zip') !== false) {
                     Filesystem::delete($tmp . DS . $file);
                 }
             }
         }
     }
     // Get the individual asset ids
     $asset_ids = explode('-', $asset_ids);
     // Set up our zip archive
     $zip = new ZipArchive();
     $path = PATH_APP . DS . $tmp . DS . time() . '.responses.zip';
     $zip->open($path, ZipArchive::CREATE);
     // Loop through the assets
     foreach ($asset_ids as $asset_id) {
         // Is it a number?
         if (!is_numeric($asset_id)) {
             continue;
         }
         // Get the rest of the asset row
         $asset = new \Components\Courses\Tables\Asset($this->db);
         $asset->load($asset_id);
         // Make sure asset is a part of this course
         if ($asset->get('course_id') != $this->course->get('id')) {
             continue;
         }
         if ($details = \Components\Courses\Models\FormReport::getLetterResponsesForAssetId($this->db, $asset_id, true, $this->course->offering()->section()->get('id'))) {
             $output = implode(',', $details['headers']) . "\n";
             if (isset($details['responses']) && count($details['responses']) > 0) {
                 foreach ($details['responses'] as $response) {
                     $output .= implode(',', $response) . "\n";
                 }
             }
             $zip->addFromString($asset_id . '.responses.csv', $output);
         } else {
             continue;
         }
     }
     // Close the zip archive handler
     $zip->close();
     if (is_file($path)) {
         // Set up the server
         $xserver = new \Hubzero\Content\Server();
         $xserver->filename($path);
         $xserver->saveas('responses.zip');
         $xserver->disposition('attachment');
         $xserver->acceptranges(false);
         // Serve the file
         $xserver->serve();
         // Now delete the file
         Filesystem::delete($path);
     }
     // All done!
     exit;
 }
示例#19
0
 /**
  * Upload a file
  *
  * @since 1.5
  */
 function upload()
 {
     $params = Component::params('com_media');
     // Check for request forgeries
     if (!Session::checkToken(['get', 'post'], true)) {
         $response = array('status' => '0', 'error' => Lang::txt('JINVALID_TOKEN'));
         echo json_encode($response);
         return;
     }
     // Get the user
     $log = JLog::getInstance('upload.error.php');
     // Get some data from the request
     $file = Request::getVar('Filedata', '', 'files', 'array');
     $folder = Request::getVar('folder', '', '', 'path');
     $return = Request::getVar('return-url', null, 'post', 'base64');
     if ($_SERVER['CONTENT_LENGTH'] > $params->get('upload_maxsize', 0) * 1024 * 1024 || $_SERVER['CONTENT_LENGTH'] > (int) ini_get('upload_max_filesize') * 1024 * 1024 || $_SERVER['CONTENT_LENGTH'] > (int) ini_get('post_max_size') * 1024 * 1024 || $_SERVER['CONTENT_LENGTH'] > (int) ini_get('memory_limit') * 1024 * 1024) {
         $response = array('status' => '0', 'error' => Lang::txt('COM_MEDIA_ERROR_WARNFILETOOLARGE'));
         echo json_encode($response);
         return;
     }
     // Set FTP credentials, if given
     JClientHelper::setCredentialsFromRequest('ftp');
     // Make the filename safe
     $file['name'] = Filesystem::clean($file['name']);
     if (isset($file['name'])) {
         // The request is valid
         $err = null;
         $filepath = \Hubzero\Filesystem\Util::normalizePath(COM_MEDIA_BASE . '/' . $folder . '/' . strtolower($file['name']));
         if (!MediaHelper::canUpload($file, $err)) {
             $log->addEntry(array('comment' => 'Invalid: ' . $filepath . ': ' . $err));
             $response = array('status' => '0', 'error' => Lang::txt($err));
             echo json_encode($response);
             return;
         }
         // Trigger the onContentBeforeSave event.
         $object_file = new \Hubzero\Base\Object($file);
         $object_file->filepath = $filepath;
         $result = Event::trigger('content.onContentBeforeSave', array('com_media.file', &$object_file, true));
         if (in_array(false, $result, true)) {
             // There are some errors in the plugins
             $log->addEntry(array('comment' => 'Errors before save: ' . $filepath . ' : ' . implode(', ', $object_file->getErrors())));
             $response = array('status' => '0', 'error' => Lang::txts('COM_MEDIA_ERROR_BEFORE_SAVE', count($errors = $object_file->getErrors()), implode('<br />', $errors)));
             echo json_encode($response);
             return;
         }
         if (Filesystem::exists($filepath)) {
             // File exists
             $log->addEntry(array('comment' => 'File exists: ' . $filepath . ' by user_id ' . User::get('id')));
             $response = array('status' => '0', 'error' => Lang::txt('COM_MEDIA_ERROR_FILE_EXISTS'));
             echo json_encode($response);
             return;
         } elseif (!User::authorise('core.create', 'com_media')) {
             // File does not exist and user is not authorised to create
             $log->addEntry(array('comment' => 'Create not permitted: ' . $filepath . ' by user_id ' . User::get('id')));
             $response = array('status' => '0', 'error' => Lang::txt('COM_MEDIA_ERROR_CREATE_NOT_PERMITTED'));
             echo json_encode($response);
             return;
         }
         $file = (array) $object_file;
         if (!Filesystem::upload($file['tmp_name'], $file['filepath'])) {
             // Error in upload
             $log->addEntry(array('comment' => 'Error on upload: ' . $filepath));
             $response = array('status' => '0', 'error' => Lang::txt('COM_MEDIA_ERROR_UNABLE_TO_UPLOAD_FILE'));
             echo json_encode($response);
             return;
         } else {
             // Trigger the onContentAfterSave event.
             Event::trigger('content.onContentAfterSave', array('com_media.file', &$object_file, true));
             $log->addEntry(array('comment' => $folder));
             $response = array('status' => '1', 'error' => Lang::txt('COM_MEDIA_UPLOAD_COMPLETE', substr($file['filepath'], strlen(COM_MEDIA_BASE))));
             echo json_encode($response);
             return;
         }
     } else {
         $response = array('status' => '0', 'error' => Lang::txt('COM_MEDIA_ERROR_BAD_REQUEST'));
         echo json_encode($response);
         return;
     }
 }
示例#20
0
 /**
  * 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;
 }
示例#21
0
 /**
  * Delete a screenshot
  *
  * @return     void
  */
 public function deleteTask()
 {
     // Incoming parent ID
     $pid = Request::getInt('pid', 0);
     $version = Request::getVar('version', 'dev');
     if (!$pid) {
         $this->setError(Lang::txt('COM_TOOLS_CONTRIBUTE_NO_ID'));
         $this->displayTask($pid, $version);
         return;
     }
     // Incoming child ID
     $file = Request::getVar('filename', '');
     if (!$file) {
         $this->setError(Lang::txt('COM_TOOLS_CONTRIBUTE_NO_CHILD_ID'));
         $this->displayTask($pid, $version);
         return;
     }
     // Load resource info
     $row = new \Components\Resources\Tables\Resource($this->database);
     $row->load($pid);
     // Get version id
     $objV = new \Components\Tools\Tables\Version($this->database);
     $vid = $objV->getVersionIdFromResource($pid, $version);
     if ($vid == NULL) {
         $this->setError(Lang::txt('COM_TOOLS_CONTRIBUTE_VERSION_ID_NOT_FOUND'));
         $this->displayTask($pid, $version);
         return;
     }
     include_once PATH_CORE . DS . 'components' . DS . 'com_resources' . DS . 'helpers' . DS . 'html.php';
     // Build the path
     $listdir = \Components\Resources\Helpers\Html::build_path($row->created, $pid, '');
     $listdir .= DS . $vid;
     $path = $this->_buildUploadPath($listdir, '');
     // Check if the folder even exists
     if (!is_dir($path) or !$path) {
         $this->setError(Lang::txt('COM_TOOLS_DIRECTORY_NOT_FOUND'));
         $this->displayTask($pid, $version);
         return;
     } else {
         if (!Filesystem::exists($path . DS . $file)) {
             $this->displayTask($pid, $version);
             return;
         }
         if (!Filesystem::delete($path . DS . $file)) {
             $this->setError(Lang::txt('COM_TOOLS_UNABLE_TO_DELETE_FILE'));
             $this->displayTask($pid, $version);
             return;
         } else {
             // Delete thumbnail
             $tn = \Components\Resources\Helpers\Html::thumbnail($file);
             Filesystem::delete($path . DS . $tn);
             // Instantiate a new screenshot object
             $ss = new \Components\Resources\Tables\Screenshot($this->database);
             $ss->deleteScreenshot($file, $pid, $vid);
         }
     }
     $this->_rid = $pid;
     // Push through to the screenshot view
     $this->displayTask($pid, $version);
 }
示例#22
0
 /**
  * Display the view
  */
 public function display($tpl = null)
 {
     $lang = Lang::getRoot();
     $this->items = $this->get('Items');
     $this->pagination = $this->get('Pagination');
     $this->state = $this->get('State');
     // Check for errors.
     if (count($errors = $this->get('Errors'))) {
         throw new Exception(implode("\n", $errors), 500);
     }
     $this->ordering = array();
     // Preprocess the list of items to find ordering divisions.
     foreach ($this->items as $item) {
         $this->ordering[$item->parent_id][] = $item->id;
         // item type text
         switch ($item->type) {
             case 'url':
                 $value = Lang::txt('COM_MENUS_TYPE_EXTERNAL_URL');
                 break;
             case 'alias':
                 $value = Lang::txt('COM_MENUS_TYPE_ALIAS');
                 break;
             case 'separator':
                 $value = Lang::txt('COM_MENUS_TYPE_SEPARATOR');
                 break;
             case 'component':
             default:
                 // load language
                 $lang->load($item->componentname . '.sys', PATH_APP, null, false, true) || $lang->load($item->componentname . '.sys', PATH_APP . '/components/' . $item->componentname . '/admin', null, false, true) || $lang->load($item->componentname . '.sys', PATH_CORE . '/components/' . $item->componentname . '/admin', null, false, true);
                 if (!empty($item->componentname)) {
                     $value = Lang::txt($item->componentname);
                     $vars = null;
                     parse_str($item->link, $vars);
                     if (isset($vars['view'])) {
                         // Attempt to load the view xml file.
                         $file = JPATH_SITE . '/components/' . $item->componentname . '/views/' . $vars['view'] . '/metadata.xml';
                         if (Filesystem::exists($file) && ($xml = simplexml_load_file($file))) {
                             // Look for the first view node off of the root node.
                             if ($view = $xml->xpath('view[1]')) {
                                 if (!empty($view[0]['title'])) {
                                     $vars['layout'] = isset($vars['layout']) ? $vars['layout'] : 'default';
                                     // Attempt to load the layout xml file.
                                     // If Alternative Menu Item, get template folder for layout file
                                     if (strpos($vars['layout'], ':') > 0) {
                                         // Use template folder for layout file
                                         $temp = explode(':', $vars['layout']);
                                         $file = JPATH_SITE . '/templates/' . $temp[0] . '/html/' . $item->componentname . '/' . $vars['view'] . '/' . $temp[1] . '.xml';
                                         // Load template language file
                                         $lang->load('tpl_' . $temp[0] . '.sys', JPATH_SITE, null, false, true) || $lang->load('tpl_' . $temp[0] . '.sys', JPATH_SITE . '/templates/' . $temp[0], null, false, true);
                                     } else {
                                         // Get XML file from component folder for standard layouts
                                         $file = JPATH_SITE . '/components/' . $item->componentname . '/views/' . $vars['view'] . '/tmpl/' . $vars['layout'] . '.xml';
                                     }
                                     if (Filesystem::exists($file) && ($xml = simplexml_load_file($file))) {
                                         // Look for the first view node off of the root node.
                                         if ($layout = $xml->xpath('layout[1]')) {
                                             if (!empty($layout[0]['title'])) {
                                                 $value .= ' » ' . Lang::txt(trim((string) $layout[0]['title']));
                                             }
                                         }
                                         if (!empty($layout[0]->message[0])) {
                                             $item->item_type_desc = Lang::txt(trim((string) $layout[0]->message[0]));
                                         }
                                     }
                                 }
                             }
                             unset($xml);
                         } else {
                             // Special case for absent views
                             $value .= ' » ' . Lang::txt($item->componentname . '_' . $vars['view'] . '_VIEW_DEFAULT_TITLE');
                         }
                     }
                 } else {
                     if (preg_match("/^index.php\\?option=([a-zA-Z\\-0-9_]*)/", $item->link, $result)) {
                         $value = Lang::txt('COM_MENUS_TYPE_UNEXISTING', $result[1]);
                     } else {
                         $value = Lang::txt('COM_MENUS_TYPE_UNKNOWN');
                     }
                 }
                 break;
         }
         $item->item_type = $value;
     }
     // Levels filter.
     $options = array();
     $options[] = Html::select('option', '1', Lang::txt('J1'));
     $options[] = Html::select('option', '2', Lang::txt('J2'));
     $options[] = Html::select('option', '3', Lang::txt('J3'));
     $options[] = Html::select('option', '4', Lang::txt('J4'));
     $options[] = Html::select('option', '5', Lang::txt('J5'));
     $options[] = Html::select('option', '6', Lang::txt('J6'));
     $options[] = Html::select('option', '7', Lang::txt('J7'));
     $options[] = Html::select('option', '8', Lang::txt('J8'));
     $options[] = Html::select('option', '9', Lang::txt('J9'));
     $options[] = Html::select('option', '10', Lang::txt('J10'));
     $this->f_levels = $options;
     parent::display($tpl);
     $this->addToolbar();
 }
示例#23
0
 public static function hasViewForAction($request)
 {
     return Filesystem::exists('app/views/' . $request['controller'] . '/' . $request['action'] . '.' . $request['extension']);
 }
示例#24
0
 /**
  * Saves a resource
  * Redirects to main listing
  *
  * @return  void
  */
 public function saveTask()
 {
     // Check for request forgeries
     Request::checkToken();
     // Initiate extended database class
     $row = new Resource($this->database);
     if (!$row->bind($_POST)) {
         throw new Exception($row->getError(), 400);
     }
     $isNew = 0;
     if ($row->id < 1) {
         $isNew = 1;
     }
     if ($isNew) {
         // New entry
         $row->created = $row->created ? $row->created : Date::toSql();
         $row->created_by = $row->created_by ? $row->created_by : User::get('id');
         $row->access = 0;
     } else {
         $old = new Resource($this->database);
         $old->load($row->id);
         $created_by_id = Request::getInt('created_by_id', 0);
         // Updating entry
         $row->modified = Date::toSql();
         $row->modified_by = User::get('id');
         if ($created_by_id) {
             $row->created_by = $row->created_by ? $row->created_by : $created_by_id;
         } else {
             $row->created_by = $row->created_by ? $row->created_by : User::get('id');
         }
     }
     // publish up
     $row->publish_up = Date::of($row->publish_up, Config::get('offset'))->toSql();
     // publish down
     if (!$row->publish_down || trim($row->publish_down) == '0000-00-00 00:00:00' || trim($row->publish_down) == 'Never') {
         $row->publish_down = '0000-00-00 00:00:00';
     } else {
         $row->publish_down = Date::of($row->publish_down, Config::get('offset'))->toSql();
     }
     // Get parameters
     $params = Request::getVar('params', array(), 'post');
     if (is_array($params)) {
         $txt = new \Hubzero\Config\Registry('');
         foreach ($params as $k => $v) {
             $txt->set($k, $v);
         }
         $row->params = $txt->toString();
     }
     // Get attributes
     $attribs = Request::getVar('attrib', array(), 'post');
     if (is_array($attribs)) {
         $txta = new \Hubzero\Config\Registry('');
         foreach ($attribs as $k => $v) {
             if ($k == 'timeof') {
                 if (strtotime(trim($v)) === false) {
                     $v = NULL;
                 }
                 $v = trim($v) ? Date::of($v, Config::get('offset'))->toSql() : NULL;
             }
             $txta->set($k, $v);
         }
         $row->attribs = $txta->toString();
     }
     // Get custom areas, add wrappers, and compile into fulltxt
     if (isset($_POST['nbtag'])) {
         $type = new Type($this->database);
         $type->load($row->type);
         include_once PATH_CORE . DS . 'components' . DS . 'com_resources' . DS . 'models' . DS . 'elements.php';
         $elements = new \Components\Resources\Models\Elements(array(), $type->customFields);
         $schema = $elements->getSchema();
         $fields = array();
         foreach ($schema->fields as $field) {
             $fields[$field->name] = $field;
         }
         $nbtag = $_POST['nbtag'];
         $found = array();
         foreach ($nbtag as $tagname => $tagcontent) {
             $f = '';
             $row->fulltxt .= "\n" . '<nb:' . $tagname . '>';
             if (is_array($tagcontent)) {
                 $c = count($tagcontent);
                 $num = 0;
                 foreach ($tagcontent as $key => $val) {
                     if (trim($val)) {
                         $num++;
                     }
                     $row->fulltxt .= '<' . $key . '>' . trim($val) . '</' . $key . '>';
                 }
                 if ($c == $num) {
                     $f = 'found';
                 }
             } else {
                 $f = trim($tagcontent);
                 if ($f) {
                     $row->fulltxt .= trim($tagcontent);
                 }
             }
             $row->fulltxt .= '</nb:' . $tagname . '>' . "\n";
             if (!$tagcontent && isset($fields[$tagname]) && $fields[$tagname]->required) {
                 throw new Exception(Lang::txt('RESOURCES_REQUIRED_FIELD_CHECK', $fields[$tagname]->label), 500);
             }
             $found[] = $tagname;
         }
         foreach ($fields as $field) {
             if (!in_array($field->name, $found) && $field->required) {
                 $found[] = $field->name;
                 $this->setError(Lang::txt('COM_CONTRIBUTE_REQUIRED_FIELD_CHECK', $field->label));
             }
         }
     }
     // Code cleaner for xhtml transitional compliance
     if ($row->type != 7) {
         $row->introtext = str_replace('<br>', '<br />', $row->introtext);
         $row->fulltxt = str_replace('<br>', '<br />', $row->fulltxt);
     }
     // Check content
     if (!$row->check()) {
         throw new Exception($row->getError(), 500);
     }
     // Store content
     if (!$row->store()) {
         throw new Exception($row->getError(), 500);
     }
     // Checkin resource
     $row->checkin();
     // Rename the temporary upload directory if it exist
     $tmpid = Request::getInt('tmpid', 0, 'post');
     if ($tmpid != Html::niceidformat($row->id)) {
         // Build the full paths
         $path = Html::dateToPath($row->created);
         $dir_id = Html::niceidformat($row->id);
         $tmppath = Utilities::buildUploadPath($path . DS . $tmpid);
         $newpath = Utilities::buildUploadPath($path . DS . $dir_id);
         // Attempt to rename the temp directory
         if (\Filesystem::exists($tmppath)) {
             $result = \Filesystem::move($tmppath, $newpath);
             if ($result !== true) {
                 $this->setError($result);
             }
         }
         $row->path = str_replace($tmpid, Html::niceidformat($row->id), $row->path);
         $row->store();
     }
     // Incoming tags
     $tags = Request::getVar('tags', '', 'post');
     // Save the tags
     $rt = new Tags($row->id);
     $rt->setTags($tags, User::get('id'), 1, 1);
     // Incoming authors
     if ($row->type != 7) {
         $authorsOldstr = Request::getVar('old_authors', '', 'post');
         $authorsNewstr = Request::getVar('new_authors', '', 'post');
         if (!$authorsNewstr) {
             $authorsNewstr = $authorsOldstr;
         }
         include_once dirname(dirname(__DIR__)) . DS . 'tables' . DS . 'contributor.php';
         $authorsNew = explode(',', $authorsNewstr);
         $authorsOld = explode(',', $authorsOldstr);
         // We have either a new ordering or new authors or both
         if ($authorsNewstr) {
             for ($i = 0, $n = count($authorsNew); $i < $n; $i++) {
                 $rc = new Contributor($this->database);
                 $rc->subtable = 'resources';
                 $rc->subid = $row->id;
                 if (is_numeric($authorsNew[$i])) {
                     $rc->authorid = $authorsNew[$i];
                 } else {
                     $rc->authorid = $rc->getUserId($authorsNew[$i]);
                 }
                 $rc->ordering = $i;
                 $rc->role = trim(Request::getVar($authorsNew[$i] . '_role', ''));
                 $rc->name = trim(Request::getVar($authorsNew[$i] . '_name', ''));
                 $rc->organization = trim(Request::getVar($authorsNew[$i] . '_organization', ''));
                 $authorsNew[$i] = $rc->authorid;
                 if (in_array($authorsNew[$i], $authorsOld)) {
                     //echo 'update: ' . $rc->authorid . ', ' . $rc->role . ', ' . $rc->name . ', ' . $rc->organization . '<br />';
                     // Updating record
                     $rc->updateAssociation();
                 } else {
                     //echo 'create: ' . $rc->authorid . ', ' . $rc->role . ', ' . $rc->name . ', ' . $rc->organization . '<br />';
                     // New record
                     $rc->createAssociation();
                 }
             }
         }
         // Run through previous author list and check to see if any IDs had been dropped
         if ($authorsOldstr) {
             $rc = new Contributor($this->database);
             for ($i = 0, $n = count($authorsOld); $i < $n; $i++) {
                 if (!in_array($authorsOld[$i], $authorsNew)) {
                     $rc->deleteAssociation($authorsOld[$i], $row->id, 'resources');
                 }
             }
         }
     }
     // If this is a child, add parent/child association
     $pid = Request::getInt('pid', 0, 'post');
     if ($isNew && $pid) {
         $this->_attachChild($row->id, $pid);
     }
     // Is this a standalone resource and we need to email approved submissions?
     if ($row->standalone == 1 && $this->config->get('email_when_approved')) {
         // If the state went from pending to published
         if ($row->published == 1 && $old->published == 3) {
             $this->_emailContributors($row, $this->database);
         }
     }
     // Redirect
     App::redirect($this->buildRedirectURL($pid), Lang::txt('COM_RESOURCES_ITEM_SAVED'));
 }
示例#25
0
 /**
  * getClassPath 
  * 
  * @param string $name 
  * @access public
  * @return void
  */
 public function getClassPath($name = '')
 {
     if ($name != '') {
         $baseDir = PATH_APP . DS . 'config' . DS . 'search' . DS . 'types';
         $filename = $baseDir . DS . $name . '.php';
         if (Filesystem::exists($filename)) {
             $config = (include $filename);
             $classpath = $config['classpath'];
             return $classpath;
         }
         return false;
     } else {
         return false;
     }
 }
示例#26
0
 /**
  * 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));
 }
示例#27
0
 /**
  * Perform a some setup needed for presenter()
  *
  * @return     array
  */
 protected function preWatch()
 {
     //var to hold error messages
     $errors = array();
     //inlude the HUBpresenter library
     require_once dirname(dirname(__DIR__)) . DS . 'helpers' . DS . 'hubpresenter.php';
     //get the presentation id
     //$id = Request::getVar('id', '');
     $resid = Request::getVar('resid', '');
     if (!$resid) {
         $this->setError(Lang::txt('Unable to find presentation.'));
     }
     //load resource
     $activechild = new Resource($this->database);
     $activechild->load($resid);
     $path = '';
     if ($activechild->path) {
         $activechild->path = trim($activechild->path, '/');
         // match YYYY/MM/#/something
         if (preg_match('/(\\d{4}\\/\\d{2}\\/\\d+)\\/.+/i', $activechild->path, $matches)) {
             $path = '/' . rtrim($matches[1], '/');
         }
     }
     //base url for the resource
     $base = substr(PATH_APP, strlen(PATH_ROOT)) . DS . trim($this->config->get('uploadpath', '/site/resources'), DS);
     //build the rest of the resource path and combine with base
     $path = $path ? $path : Html::build_path($activechild->created, $activechild->id, '');
     $path = $base . $path;
     // we must have a folder
     if (!\Filesystem::exists(PATH_ROOT . DS . $path)) {
         $this->setError(Lang::txt('Folder containing assets does nto exist.'));
         $return = array();
         $return['errors'] = $this->getErrors();
         $return['content_folder'] = $path;
         $return['manifest'] = null;
         return $return;
     }
     //check to make sure we have a presentation document defining cuepoints, slides, and media
     //$manifest_path_json = PATH_ROOT . $path . DS . 'presentation.json';
     $manifests = \Filesystem::files(PATH_ROOT . DS . $path, '.json');
     $manifest_path_json = isset($manifests[0]) ? $manifests[0] : null;
     $manifest_path_xml = PATH_ROOT . $path . DS . 'presentation.xml';
     //check if the formatted json exists
     if (!file_exists(PATH_ROOT . $path . DS . $manifest_path_json)) {
         //check to see if we just havent converted yet
         if (!file_exists($manifest_path_xml)) {
             $this->setError(Lang::txt('Missing outline used to build presentation.'));
         } else {
             $job = Hubpresenter::createJsonManifest($path, $manifest_path_xml);
             if ($job != '') {
                 $this->setError($job);
             }
         }
     }
     //path to media
     $media_path = PATH_ROOT . $path;
     //check if path exists
     if (!is_dir($media_path)) {
         $this->setError(Lang::txt('Path to media does not exist.'));
     } else {
         //get all files matching  /.mp4|.webs|.ogv|.m4v|.mp3/
         $media = \Filesystem::files($media_path, '.mp4|.webm|.ogv|.m4v|.mp3|.ogg', false, false);
         $ext = array();
         foreach ($media as $m) {
             $parts = explode('.', $m);
             $ext[] = array_pop($parts);
         }
         //if we dont have all the necessary media formats
         if (in_array('mp4', $ext) && count($ext) < 3 || in_array('mp3', $ext) && count($ext) < 2) {
             $this->setError(Lang::txt('Missing necessary media formats for video or audio.'));
         }
         //make sure if any slides are video we have three formats of video and backup image for mobile
         $slide_path = $media_path . DS . 'slides';
         $slides = \Filesystem::files($slide_path, '', false, false);
         //array to hold slides with video clips
         $slide_video = array();
         //build array for checking slide video formats
         if ($slides && is_array($slides)) {
             foreach ($slides as $s) {
                 $parts = explode('.', $s);
                 $ext = array_pop($parts);
                 $name = implode('.', $parts);
                 if (in_array($ext, array('mp4', 'm4v', 'webm', 'ogv'))) {
                     $slide_video[$name][$ext] = $name . '.' . $ext;
                 }
             }
         }
         //make sure for each of the slide videos we have all three formats
         //and has a backup image for the slide
         foreach ($slide_video as $k => $v) {
             if (count($v) < 3) {
                 $this->setError(Lang::txt('Video Slides must be Uploaded in the Three Standard Formats. You currently only have ' . count($v) . " ({$k}." . implode(", {$k}.", array_keys($v)) . ').'));
             }
             if (!file_exists($slide_path . DS . $k . '.png') && !file_exists($slide_path . DS . $k . '.jpg')) {
                 $this->setError(Lang::txt('Slides containing video must have a still image of the slide for mobile support. Please upload an image with the filename "' . $k . '.png" or "' . $k . '.jpg".'));
             }
         }
     }
     $return = array();
     $return['errors'] = $this->getErrors();
     $return['content_folder'] = $path;
     $return['manifest'] = $path . DS . $manifest_path_json;
     return $return;
 }
示例#28
0
 /**
  * Event after content has been displayed
  *
  * @param  string  $context  The context of the content being passed to the plugin.
  * @param  object  $article  The article object. Note $article->text is also available
  * @param  object  $params   The article params
  * @param  int     $page     The 'page' number
  */
 public function onContentAfterDisplay($context, &$article, &$params, $page = 0)
 {
     if (!App::isSite()) {
         return;
     }
     $view = Request::getCmd('view');
     // article, category, featured
     if ($view == 'featured' && $this->params->get('displayf', 1) == 0) {
         return;
     }
     if ($view == 'category' && $this->params->get('displayc', 1) == 0) {
         return;
     }
     if ((int) $this->pluginNr > 0) {
         // Second instance in featured view or category view
         return;
     }
     // We need help variables as we cannot change the $article variable - such then will influence global settings
     $suffix = '';
     $thisDesc = $article->metadesc;
     $thisTitle = $article->title;
     if ($view == 'featured' && $this->pluginNr == 0) {
         // Data from first article will be set
         $suffix = 'f';
         $this->pluginNr = 1;
     } else {
         if ($view == 'category' && $this->pluginNr == 0) {
             // Data from first article will be set
             $suffix = 'c';
             if (isset($article->catid) && (int) $article->catid > 0) {
                 $db = App::get('db');
                 $db->setQuery('SELECT c.metadesc, c.title FROM `#__categories` AS c WHERE c.id = ' . (int) $article->catid);
                 $cItem = $db->loadObjectList();
                 if (isset($cItem[0]->metadesc) && $cItem[0]->metadesc != '') {
                     $thisDesc = $cItem[0]->metadesc;
                 }
                 if (isset($cItem[0]->title) && $cItem[0]->title != '') {
                     $thisTitle = $cItem[0]->title;
                 }
             }
             $this->pluginNr = 1;
         }
     }
     // Title
     if ($title = $this->params->get('title' . $suffix, $thisTitle)) {
         Document::setMetadata('og:title', htmlspecialchars($title));
     }
     // Type
     Document::setMetadata('og:type', $this->params->get('type' . $suffix, 'article'));
     // Image
     if ($img = $this->params->get('image' . $suffix, '')) {
         Document::setMetadata('og:image', Request::base(false) . htmlspecialchars($img));
     } else {
         // Try to find image in article
         $img = 0;
         $fulltext = '';
         if (isset($article->fulltext) && $article->fulltext != '') {
             $fulltext = $article->fulltext;
         }
         $introtext = '';
         if (isset($article->introtext) && $article->introtext != '') {
             $fulltext = $article->introtext;
         }
         $content = $introtext . $fulltext;
         preg_match('/< *img[^>]*src *= *["\']?([^"\']*)/i', $content, $src);
         if (isset($src[1]) && $src[1] != '') {
             Document::setMetadata('og:image', Request::base(false) . htmlspecialchars($src[1]));
             $img = 1;
         }
         // Try to find image in images/phocaopengraph folder
         if ($img == 0) {
             if (isset($article->id) && (int) $article->id > 0) {
                 $imgPath = '';
                 $path = PATH_APP . DS . 'site' . DS . 'media' . DS . 'images' . DS . 'opengraph' . DS;
                 if (Filesystem::exists($path . DS . (int) $article->id . '.jpg')) {
                     $imgPath = Request::base(false) . 'images/opengraph/' . (int) $article->id . '.jpg';
                 } else {
                     if (Filesystem::exists($path . DS . (int) $article->id . '.png')) {
                         $imgPath = Request::base(false) . 'images/opengraph/' . (int) $article->id . '.png';
                     } else {
                         if (Filesystem::exists($path . DS . (int) $article->id . '.gif')) {
                             $imgPath = Request::base(false) . 'images/opengraph/' . (int) $article->id . '.gif';
                         }
                     }
                 }
                 if ($imgPath != '') {
                     Document::setMetadata('og:image', $imgPath);
                 }
             }
         }
     }
     // URL
     if ($url = $this->params->get('url' . $suffix, Request::current())) {
         Document::setMetadata('og:url', htmlspecialchars($url));
     }
     // Site Name
     if ($sitename = $this->params->get('site_name' . $suffix, Config::get('sitename'))) {
         Document::setMetadata('og:site_name', htmlspecialchars($sitename));
     }
     // Description
     if ($desc = $this->params->get('description' . $suffix, $thisDesc)) {
         Document::setMetadata('og:description', htmlspecialchars($desc));
     } else {
         if ($desc = Config::get('MetaDesc')) {
             Document::setMetadata('og:description', htmlspecialchars($desc));
         }
     }
     // FB App ID - COMMON
     if ($app_id = $this->params->get('app_id', '')) {
         Document::setMetadata('fb:app_id', htmlspecialchars($app_id));
     }
     // Other
     if ($other = $this->params->get('other', '')) {
         $other = explode(';', $other);
         if (!empty($other)) {
             foreach ($other as $v) {
                 if ($v != '') {
                     $vother = explode('=', $v);
                     if (!empty($vother)) {
                         if (isset($vother[0]) && isset($vother[1])) {
                             Document::setMetadata(htmlspecialchars(strip_tags($vother[0])), htmlspecialchars($vother[1]));
                         }
                     }
                 }
             }
         }
     }
 }
示例#29
0
 /**
  * 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;
 }
 /**
  * True if file exists
  *
  * @param  string $file, a php file template
  */
 public function exists($file)
 {
     $this->files->exists($file);
 }