/**
  * Save a new or existing album
  *
  * @static
  * @param Form $form
  * @return mixed
  */
 public static function SaveAlbum(Form $form)
 {
     /** @var GalleryAlbumModel $model */
     $model = $form->getModel('model');
     /** @var $page PageModel */
     $page = $form->getModel('page');
     $page->set('fuzzy', 1);
     if ($page->get('rewriteurl') == '/' || $page->get('rewriteurl') == '') {
         Core::SetMessage('Galleries cannot be installed on the root of your site!  Please change the URL to something other than "/".', 'error');
         return false;
     }
     // Update the model cache data
     $model->set('title', $page->get('title'));
     //var_dump($model); die();
     $model->save();
     // Make sure the directory exists.
     $dir = \Core\Filestore\Factory::Directory($model->getFullUploadDirectory());
     $dir->mkdir();
     // w00t
     return $page->getResolvedURL();
 }
Beispiel #2
0
 /**
  * Copy in all the assets for this theme into the assets location.
  *
  * Returns false if nothing changed, else will return an array of all the changes that occured.
  *
  * @param bool $install   Set to false to uninstall the assets instead of installing.
  * @param int  $verbosity 0 for standard output, 1 for real-time, 2 for real-time verbose output.
  *
  * @return false | array
  * @throws \InstallerException
  */
 public function _parseAssets($install = true, $verbosity = 0)
 {
     $assetbase = \Core\Filestore\get_asset_path();
     $coretheme = \ConfigHandler::Get('/theme/selected');
     // WHY is core theme set to blank?!?
     // Damn installer...
     // this happens in the installer.
     if ($coretheme === null) {
         $coretheme = 'default';
     }
     $theme = $this->getKeyName();
     $changes = [];
     foreach ($this->_xmlloader->getElements('/assets/file') as $node) {
         // Cannot install assets if the directory is not setup!
         if (!$this->getAssetDir()) {
             continue;
         }
         $b = $this->getBaseDir();
         // The base filename with the directory.
         $filename = $node->getAttribute('filename');
         // The new theme asset will be installed into the same directory as its theme.
         // This differs from usual components because they just follow whatever theme is currently running.
         //$nf = Core::File($assetbase . $theme . '/' . $filename);
         $trimmedfilename = substr($b . $node->getAttribute('filename'), strlen($this->getAssetDir()));
         $themespecificfilename = $assetbase . $theme . '/' . $trimmedfilename;
         $newfilename = 'assets/' . $trimmedfilename;
         // Before anything, check and see if this file has a custom override file present.
         if (file_exists(ROOT_PDIR . 'themes/custom/' . $newfilename)) {
             // If so, then copy that asset to the custom directory too!
             $f = \Core\Filestore\Factory::File(ROOT_PDIR . 'themes/custom/' . $newfilename);
             $srcname = '!CUSTOM!';
         } else {
             // Otherwise, the local file is guaranteed to be a local file.
             $f = new \Core\Filestore\Backends\FileLocal($b . $filename);
             $srcname = '-theme- ';
         }
         if ($verbosity == 2) {
             CLI::PrintActionStart('Installing ' . $srcname . ' asset ' . $f->getBasename());
         }
         $nf = \Core\Filestore\Factory::File($newfilename);
         /*
         			// The various replacement possibilities for this file.
         			// The new destination must be in the theme-specific directory, this is a
         			// bit of a hack from the usual behaviour of the filestore system.
         			// Since that's designed to return the default if the theme-specific doesn't exist.
         			$replacements = array(
         				// The theme is not default, but the system translated the path to the default directory.
         				// This is because the file doesn't exist in any theme.
         				// This is actually expected behaviour, except unwanted here.
         				'default/' . $trimmedfilename => $theme . '/' . $trimmedfilename,
         				// The theme is not the currently installed, but the system translated the path to the that directory.
         				// This is because the filename is the same as the installed theme, so the system just translated there.
         				// We don't want that.
         				$coretheme . '/' . $trimmedfilename => $theme . '/' . $trimmedfilename,
         			);
         
         
         			foreach($replacements as $k => $v){
         				if($k == $v) continue;
         				if(strpos($nf->getFilename(), $k) !== false){
         					$nf->setFilename( str_replace($k, $v, $nf->getFilename()) );
         				}
         			}
         */
         // Check if this file even needs updated. (this is primarily used for reporting reasons)
         if ($nf->exists() && $nf->identicalTo($f)) {
             //echo "Skipping file, it's identical.<br/>";
             if ($verbosity == 2) {
                 CLI::PrintActionStatus('skip');
             }
             continue;
         } elseif ($nf->exists()) {
             $action = 'Replaced';
         } else {
             $action = 'Installed';
         }
         if (!$f->isReadable()) {
             throw new \InstallerException('Source file [' . $f->getFilename() . '] is not readable.');
         }
         try {
             $f->copyTo($nf, true);
         } catch (\Exception $e) {
             throw new \InstallerException('Unable to copy [' . $f->getFilename() . '] to [' . $nf->getFilename() . ']');
         }
         $change = $action . ' ' . $nf->getFilename();
         $changes[] = $change;
         if ($verbosity == 1) {
             CLI::PrintLine($change);
         } elseif ($verbosity == 2) {
             CLI::PrintActionStatus('ok');
         }
     }
     // If there are custom assets not registered by any application, install them too!
     // This will allow an admin to upload additional css resources and images easily.
     $directory = \Core\Filestore\Factory::Directory('themes/custom/assets');
     $ls = $directory->ls(null, true);
     $baseStrLen = strlen(ROOT_PDIR . '/themes/custom/assets');
     foreach ($ls as $fileOrDir) {
         if ($fileOrDir instanceof File) {
             $newfilename = substr($fileOrDir->getFilename(), $baseStrLen);
             if ($verbosity == 2) {
                 CLI::PrintActionStart('Installing CUSTOM   asset ' . $newfilename);
             }
             $nf = \Core\Filestore\Factory::File('asset/' . $newfilename);
             if ($nf->exists() && $nf->identicalTo($fileOrDir)) {
                 //echo "Skipping file, it's identical.<br/>";
                 if ($verbosity == 2) {
                     CLI::PrintActionStatus('skip');
                 }
                 continue;
             } elseif ($nf->exists()) {
                 $action = 'Replaced';
             } else {
                 $action = 'Installed';
             }
             try {
                 $fileOrDir->copyTo($nf, true);
             } catch (\Exception $e) {
                 throw new \InstallerException('Unable to copy [' . $fileOrDir->getFilename() . '] to [' . $nf->getFilename() . ']');
             }
             $change = $action . ' ' . $nf->getFilename();
             $changes[] = $change;
             if ($verbosity == 1) {
                 CLI::PrintLine($change);
             } elseif ($verbosity == 2) {
                 CLI::PrintActionStatus('ok');
             }
         }
     }
     if (!sizeof($changes)) {
         if ($verbosity > 0) {
             CLI::PrintLine('No changes required');
         }
         return false;
     }
     // Make sure the asset cache is purged!
     \Core\Cache::Delete('asset-resolveurl');
     return $changes;
 }
	/**
	 * Get an array of alternative display templates for this instance.
	 *
	 * This is based on the widget's baseurl.
	 *
	 * @return array
	 */
	public function getAlternativeTemplateOptions(){
		$parts = $this->splitParts();

		// Figure out the template directory for custom pages, (if it exists)
		// In order to get the types, I need to sift through all the potential template directories and look for a directory
		// with the matching name.
		$tmpname = 'widgets' . strtolower('/' . substr($parts['controller'], 0, -6) . '/' . $parts['method']);

		$matches = [];

		foreach(\Core\Templates\Template::GetPaths() as $d){
			if(is_dir($d . $tmpname)){
				// Yay, sift through that and get the files!
				$dir = \Core\Filestore\Factory::Directory($d . $tmpname);
				foreach($dir->ls('tpl') as $file){
					// Skip directories
					if($file instanceof \Core\Filestore\Directory) continue;

					/** @var $file \Core\Filestore\File */
					//$fullpath = $tmpname . $file->getBaseFilename();
					$name = $fullpath = $file->getBaseFilename();
					// Do some template updates and make it a little more friendlier to read.
					$name = ucwords(str_replace('-', ' ', substr($name, 0, -4))) . ' Template';
					$matches[ $fullpath ] = $name;
				}
			}
		}

		return ['' => '-- Default Template --'] + $matches;
	}
Beispiel #4
0
	public function render(){

		if(!$this->get('templatename')){
			throw new Exception('Unable to render pageselectinput element without templatename set!');
		}
		// Figure out the template directory for custom pages, (if it exists)
		// In order to get the types, I need to sift through all the potential template directories and look for a directory
		// with the matching name.
		$tmpname = substr($this->get('templatename'), 0, -4) . '/';

		$matches = array();

		foreach(\Core\Templates\Template::GetPaths() as $d){
			if(is_dir($d . $tmpname)){
				// Yay, sift through that and get the files!
				$dir = \Core\Filestore\Factory::Directory($d . $tmpname);
				foreach($dir->ls('tpl') as $file){
					// Skip directories
					if($file instanceof \Core\Filestore\Directory) continue;

					/** @var $file \Core\Filestore\File */
					//$fullpath = $tmpname . $file->getBaseFilename();
					$fullpath = $file->getBaseFilename();
					$name = $file->getBaseFilename();
					// Do some template updates and make it a little more friendlier to read.
					$name = ucwords(str_replace('-', ' ', substr($name, 0, -4))) . ' Template';
					$matches[ $fullpath ] = $name;
				}
			}
		}

		// Are there any matches?  If not just return a blank string.
		if(!sizeof($matches)){
			return '';
		}

		$options = array_merge(array('' => '-- Default Page Template --'), $matches);
		$this->set('options', $options);

		return parent::render();
	}
 /**
  * View to display a list of currently installed themes, their templates, and be able to manage
  * their templates and set them as default.
  *
  * @todo Implement an Add/Upload Theme link on this page.
  */
 public function index2()
 {
     $view = $this->getView();
     $default = ConfigHandler::Get('/theme/selected');
     $themes = array();
     $dir = ROOT_PDIR . 'themes';
     $dh = opendir($dir);
     if ($dh) {
         while (($file = readdir($dh)) !== false) {
             if ($file[0] == '.') {
                 continue;
             }
             if (!is_dir($dir . '/' . $file)) {
                 continue;
             }
             // Load up the templates for this theme.
             $templates = ThemeHandler::GetTheme($file)->getTemplates();
             $themes[] = array('name' => $file, 'default' => $default == $file, 'templates' => $templates);
         }
         closedir($dh);
     }
     // Get the page templates that have widgetareas defined within.
     $components = Core::GetComponents();
     $pagetemplates = array();
     foreach ($components as $c) {
         /** @var $c Component_2_1 */
         $dir = $c->getViewSearchDir();
         if (!$dir) {
             continue;
         }
         $dirlen = strlen($dir);
         $component = $c->getName();
         $dh = \Core\Filestore\Factory::Directory($dir);
         $pagetplfiles = $dh->ls('tpl', true);
         // not sure why getFilename(path) isn't working as expected, but this works too.
         foreach ($pagetplfiles as $obj) {
             /** @var $obj \Core\Filestore\File */
             $file = substr($obj->getFilename(), $dirlen);
             // Since this is a template, it may actually be in a different location than where the package maintainer put it.
             // ie: user template user/templates/pages/user/view.tpl may be installed to themes/myawesometheme/pages/user/view.tpl instead.
             $resolved = Core\Templates\Template::ResolveFile($file);
             $newobj = \Core\Filestore\Factory::File($resolved);
             // Check the contents of the file and see if there is a {widgetarea...} here.
             $contents = $newobj->getContents();
             if (strpos($contents, '{widgetarea') !== false) {
                 $haswidgets = true;
             } else {
                 $haswidgets = false;
             }
             $pagetemplates[] = array('file' => $file, 'resolved' => $resolved, 'obj' => $newobj, 'haswidgets' => $haswidgets, 'component' => $component);
         }
     }
     // The CSS files for the current theme and every component.
     // This is keyed by the filename so that duplicate entries don't show up more than once,
     // ie: if an asset exists in both the component and the theme.
     $cssfiles = array();
     // Give me the current theme!
     $dir = ROOT_PDIR . 'themes/' . ConfigHandler::Get('/theme/selected') . '/assets';
     $dirlen = strlen($dir);
     $component = 'Theme/' . ConfigHandler::Get('/theme/selected');
     $dh = \Core\Filestore\Factory::Directory($dir);
     $cssls = $dh->ls('css', true);
     foreach ($cssls as $obj) {
         /** @var $obj \Core\Filestore\Backends\FileLocal */
         $file = 'assets' . substr($obj->getFilename(), $dirlen);
         // Since this is a template, it may actually be in a different location than where the package maintainer put it.
         // ie: user template user/templates/pages/user/view.tpl may be installed to themes/myawesometheme/pages/user/view.tpl instead.
         $newobj = \Core\Filestore\Factory::File($file);
         $cssfiles[$file] = array('file' => $file, 'obj' => $newobj, 'component' => $component);
     }
     // And the rest of the components... I suppose
     foreach ($components as $c) {
         // Now, give me all this component's CSS files!
         $dir = $c->getAssetDir();
         if (!$dir) {
             continue;
         }
         $dirlen = strlen($dir);
         $component = $c->getName();
         $dh = \Core\Filestore\Factory::Directory($dir);
         $cssls = $dh->ls('css', true);
         // not sure why getFilename(path) isn't working as expected, but this works too.
         foreach ($cssls as $obj) {
             /** @var $obj \Core\Filestore\Backends\FileLocal */
             $file = 'assets' . substr($obj->getFilename(), $dirlen);
             // Since this is a template, it may actually be in a different location than where the package maintainer put it.
             // ie: user template user/templates/pages/user/view.tpl may be installed to themes/myawesometheme/pages/user/view.tpl instead.
             $newobj = \Core\Filestore\Factory::File($file);
             $cssfiles[$file] = array('file' => $file, 'obj' => $newobj, 'component' => $component);
         }
     }
     $view->assign('pages', $pagetemplates);
     $view->assign('css', $cssfiles);
     $view->assign('themes', $themes);
     $view->title = 'Theme Manager';
 }
 /**
  * Get the repository XML as a string that can be returned to the browser or cached for future use.
  *
  * @return string
  */
 private function _getRepoXML()
 {
     $repo = new RepoXML();
     $repo->setDescription(ConfigHandler::Get('/package_repository/description'));
     $dir = Factory::Directory(\ConfigHandler::Get('/package_repository/base_directory'));
     $coredir = $dir->getPath() . 'core/';
     $componentdir = $dir->getPath() . 'components/';
     $themedir = $dir->getPath() . 'themes/';
     $tmpdir = Factory::Directory('tmp/exports/');
     $gpg = new Core\GPG\GPG();
     $keysfound = [];
     $private = ConfigHandler::Get('/package_repository/is_private') || strpos($dir->getPath(), ROOT_PDIR) !== 0;
     $addedpackages = 0;
     $failedpackages = 0;
     $iterator = new \Core\Filestore\DirectoryIterator($dir);
     // Only find signed packages.
     $iterator->findExtensions = ['asc'];
     // Recurse into sub directories
     $iterator->recursive = true;
     // No directories
     $iterator->findDirectories = false;
     // Just files
     $iterator->findFiles = true;
     // And sort them by their filename to make things easy.
     $iterator->sortBy('filename');
     // Ensure that the necessary temp directory exists.
     $tmpdir->mkdir();
     foreach ($iterator as $file) {
         /** @var \Core\Filestore\File $file */
         $fullpath = $file->getFilename();
         // Used in the XML file.
         if ($private) {
             $relpath = \Core\resolve_link('/packagerepository/download?file=' . substr($file->getFilename(), strlen($dir->getPath())));
         } else {
             $relpath = $file->getFilename(ROOT_PDIR);
         }
         // Drop the .asc extension.
         $basename = $file->getBasename(true);
         // Tarball of the temporary package
         $tgz = Factory::File($tmpdir->getPath() . $basename);
         $output = [];
         // I need to 1) retrieve and 2) verify the key for this package.
         try {
             $signature = $gpg->verifyFileSignature($fullpath);
             if (!in_array($signature->keyID, $keysfound)) {
                 $repo->addKey($signature->keyID, null, null);
                 $keysfound[] = $signature->keyID;
             }
         } catch (\Exception $e) {
             trigger_error($fullpath . ' was not able to be verified as authentic, (probably because the GPG public key was not available)');
             $failedpackages++;
             continue;
         }
         // decode and untar it in a temp directory to get the package.xml file.
         exec('gpg --homedir "' . GPG_HOMEDIR . '" -q -d "' . $fullpath . '" > "' . $tgz->getFilename() . '" 2>/dev/null', $output, $ret);
         if ($ret) {
             trigger_error('Decryption of file ' . $fullpath . ' failed!');
             $failedpackages++;
             continue;
         }
         exec('tar -xzf "' . $tgz->getFilename() . '" -C "' . $tmpdir->getPath() . '" ./package.xml', $output, $ret);
         if ($ret) {
             trigger_error('Unable to extract package.xml from' . $tgz->getFilename());
             unlink($tmpdir->getPath() . $basename);
             $failedpackages++;
             continue;
         }
         // Read in that package file and append it to the repo xml.
         $package = new PackageXML($tmpdir->getPath() . 'package.xml');
         $package->getRootDOM()->setAttribute('key', $signature->keyID);
         $package->setFileLocation($relpath);
         $repo->addPackage($package);
         $addedpackages++;
         // But I can still cleanup!
         unlink($tmpdir->getPath() . 'package.xml');
         $tgz->delete();
     }
     return $repo->asPrettyXML();
 }
Beispiel #7
0
	public static function FlushCache(){
		
		$dir = \Core\Filestore\Factory::Directory(TMP_DIR . 'smarty_templates_c');
		foreach($dir->ls('php') as $file){
			/** @var \Core\Filestore\File $file */
			$file->delete();
		}

		$dir = \Core\Filestore\Factory::Directory(TMP_DIR . 'smarty_cache');
		foreach($dir->ls('php') as $file){
			/** @var \Core\Filestore\File $file */
			$file->delete();
		}
	}
Beispiel #8
0
			}
			else{
				CLI::PrintActionStatus('fail');
				CLI::PrintError('Unable to find required component ' . $dat['name']);
				die();
			}
		}
		else{
			CLI::PrintActionStatus('ok');
			CLI::PrintLine('Found ' . $dat['name'] . '-' . $compversion . ' in a local package.');
			$dat['tgz'] = $dat['src'] . '/' . $dat['keyname'] . '-' . $compversion . '.tgz';
		}

		CLI::PrintActionStart("Extracting tarball");
		if(!is_dir($dat['dest'])){
			$d = \Core\Filestore\Factory::Directory($dat['dest']);
			$d->mkdir();
		}
		exec('tar -xzf ' . $dat['tgz'] . ' -C ' . $dat['dest'] . ' --transform "s:\./data::" ./data', $out, $result);
		if($result != 0){
			CLI::PrintActionStatus('fail');
			CLI::PrintLine($out);
			die();
		}
		CLI::PrintActionStatus('ok');

		CLI::PrintActionStart("Processing CHANGELOG");
		if($dat['keyname'] == 'core'){
			$parser = new Core\Utilities\Changelog\Parser($dat['name'], $dat['dest'] . '/core/CHANGELOG');
		}
		else{
 public static function RebuildPackages()
 {
     $dir = \Core\Filestore\Factory::Directory(\ConfigHandler::Get('/package_repository/base_directory'));
     $coredir = $dir->getPath() . 'core/';
     $componentdir = $dir->getPath() . 'components/';
     $themedir = $dir->getPath() . 'themes/';
     $tmpdir = \Core\Filestore\Factory::Directory('tmp/exports/');
     $gpg = new Core\GPG\GPG();
     $keysfound = [];
     $addedpackages = 0;
     $failedpackages = 0;
     $skippedpackages = 0;
     $ls = $dir->ls('asc', true);
     \Core\CLI\CLI::PrintProgressBar(0);
     $totalPackages = sizeof($ls);
     $percentEach = 100 / $totalPackages;
     $currentPercent = 0;
     // Ensure that the necessary temp directory exists.
     $tmpdir->mkdir();
     foreach ($ls as $file) {
         /** @var \Core\Filestore\File $file */
         $fullpath = $file->getFilename();
         $relpath = substr($file->getFilename(), strlen($dir->getPath()));
         $tmpdirpath = $tmpdir->getPath();
         // Drop the .asc extension.
         $basename = $file->getBasename(true);
         // Tarball of the temporary package
         $tgz = \Core\Filestore\Factory::File($tmpdirpath . $basename);
         $output = [];
         // I need to 1) retrieve and 2) verify the key for this package.
         try {
             $signature = $gpg->verifyFileSignature($fullpath);
         } catch (\Exception $e) {
             trigger_error($fullpath . ' was not able to be verified as authentic, (probably because the GPG public key was not available)');
             $failedpackages++;
             continue;
         }
         // decode and untar it in a temp directory to get the package.xml file.
         exec('gpg --homedir "' . GPG_HOMEDIR . '" -q -d "' . $fullpath . '" > "' . $tgz->getFilename() . '" 2>/dev/null', $output, $ret);
         if ($ret) {
             trigger_error('Decryption of file ' . $fullpath . ' failed!');
             $failedpackages++;
             continue;
         }
         // Extract the package.xml metafile, this is critical!
         exec('tar -xzf "' . $tgz->getFilename() . '" -C "' . $tmpdirpath . '" ./package.xml', $output, $ret);
         if ($ret) {
             trigger_error('Unable to extract package.xml from' . $tgz->getFilename());
             unlink($tmpdirpath . $basename);
             $failedpackages++;
             continue;
         }
         // Read in that package file and append it to the repo xml.
         $package = new PackageXML($tmpdirpath . 'package.xml');
         $package->getRootDOM()->setAttribute('key', $signature->keyID);
         $package->setFileLocation($relpath);
         // Core has a few differences than most components.
         if ($package->getKeyName() == 'core') {
             $pkgName = 'Core Plus';
             $chngName = 'Core Plus';
             $type = 'core';
             $chngDepth = 3;
             $chngFile = './data/core/CHANGELOG';
             $xmlFile = './data/core/component.xml';
         } else {
             $pkgName = $package->getName();
             $chngName = ($package->getType() == 'theme' ? 'Theme/' : '') . $package->getName();
             $type = $package->getType();
             $chngDepth = 2;
             $chngFile = './data/CHANGELOG';
             $xmlFile = './data/' . ($package->getType() == 'theme' ? 'theme.xml' : 'component.xml');
         }
         // Lookup this package in the database or create if it doesn't exist.
         $model = PackageRepositoryPackageModel::Find(['type = ' . $package->getType(), 'key = ' . $package->getKeyName(), 'version = ' . $package->getVersion()], 1);
         if (!$model) {
             $model = new PackageRepositoryPackageModel();
             $model->set('type', $type);
             $model->set('key', $package->getKeyName());
             $model->set('version', $package->getVersion());
         }
         // Set the data provided by the package.xml file.
         $model->set('name', $pkgName);
         $model->set('gpg_key', $package->getKey());
         $model->set('packager', $package->getPackager());
         $model->set('file', $relpath);
         $model->set('description', $package->getDescription());
         $model->set('requires', $package->getRequires());
         $model->set('provides', $package->getProvides());
         $model->set('upgrades', $package->getUpgrades());
         unlink($tmpdirpath . 'package.xml');
         // Extract out the CHANGELOG file, this is not so critical.
         // I need strip-components=2 to drop off the "." and "data" prefixes.
         exec('tar -xzf "' . $tgz->getFilename() . '" -C "' . $tmpdirpath . '" --strip-components=' . $chngDepth . ' ' . $chngFile, $output, $ret);
         // If there is a CHANGELOG, parse that too!
         if (file_exists($tmpdirpath . 'CHANGELOG')) {
             try {
                 $ch = new Core\Utilities\Changelog\Parser($chngName, $tmpdirpath . 'CHANGELOG');
                 $ch->parse();
                 // Get the version for this iteration.
                 $chsec = $ch->getSection($model->get('version'));
                 $model->set('packager_name', $chsec->getPackagerName());
                 $model->set('packager_email', $chsec->getPackagerEmail());
                 $model->set('datetime_released', $chsec->getReleasedDateUTC());
                 $model->set('changelog', $chsec->fetchAsHTML(null));
             } catch (Exception $e) {
                 // meh, we just won't have a changelog.
             } finally {
                 if (file_exists($tmpdirpath . 'CHANGELOG')) {
                     // Cleanup
                     unlink($tmpdirpath . 'CHANGELOG');
                 }
             }
         }
         // Retrieve out the screenshots from this component.
         exec('tar -xzf "' . $tgz->getFilename() . '" -O ' . $xmlFile . ' > "' . $tmpdirpath . 'comp.xml"', $output, $ret);
         if (file_exists($tmpdirpath . 'comp.xml')) {
             try {
                 $images = [];
                 $c = new Component_2_1($tmpdirpath . 'comp.xml');
                 $screens = $c->getScreenshots();
                 if (sizeof($screens)) {
                     foreach ($screens as $s) {
                         // Extract out this screen and save it to the filesystem.
                         $archivedFile = dirname($xmlFile) . '/' . $s;
                         $localFile = \Core\Filestore\Factory::File('public/packagerepo-screens/' . $model->get('type') . '-' . $model->get('key') . '-' . $model->get('version') . '/' . basename($s));
                         // Write something into the file so that it exists on the filesystem.
                         $localFile->putContents('');
                         // And now tar can extract directly to that destination!
                         exec('tar -xzf "' . $tgz->getFilename() . '" -O ' . $archivedFile . ' > "' . $localFile->getFilename() . '"', $output, $ret);
                         if (!$ret) {
                             // Return code should be 0 on a successful write.
                             $images[] = $localFile->getFilename(false);
                         }
                     }
                 }
                 $model->set('screenshots', $images);
             } catch (Exception $e) {
                 // meh, we just won't have images..
             } finally {
                 if (file_exists($tmpdirpath . 'comp.xml')) {
                     // Cleanup
                     unlink($tmpdirpath . 'comp.xml');
                 }
             }
         }
         if ($model->changed()) {
             $model->save(true);
             $addedpackages++;
         } else {
             $skippedpackages++;
         }
         // But I can still cleanup!
         $tgz->delete();
         $currentPercent += $percentEach;
         \Core\CLI\CLI::PrintProgressBar($currentPercent);
     }
     // Commit everything!
     PackageRepositoryPackageModel::CommitSaves();
     return ['updated' => $addedpackages, 'skipped' => $skippedpackages, 'failed' => $failedpackages];
 }
	/**
	 * Call to check some of the core requirements on Core, such as file permissions and the like.
	 *
	 * @return array
	 */
	public static function _HealthCheckHook(){

		$checks      = [];

		if(version_compare(phpversion(), '5.5.0', '<')){
			$checks[] = \Core\HealthCheckResult::ConstructWarn(
				t('STRING_CHECK_PHP_S_TOO_OLD', phpversion()),
				t('MESSAGE_WARNING_PHP_S_TOO_OLD', phpversion()),
				''
			);
		}
		else{
			$checks[] = \Core\HealthCheckResult::ConstructGood(
				t('STRING_CHECK_PHP_S_OK', phpversion()),
				t('MESSAGE_SUCCESS_PHP_S_OK', phpversion())
			);
		}

		$dir = ROOT_PDIR . 'logs/';
		if(is_dir($dir) && is_writable($dir)){
			// Yay, everything is good here!
			$checks[] = \Core\HealthCheckResult::ConstructGood(
				t('STRING_CHECK_LOG_DIRECTORY_S_OK', $dir),
				t('MESSAGE_SUCCESS_LOG_DIRECTORY_S_OK', $dir)
			);
		}
		elseif(is_dir($dir)){
			$checks[] = \Core\HealthCheckResult::ConstructWarn(
				t('STRING_CHECK_LOG_DIRECTORY_S_NOT_WRITABLE', $dir),
				t('MESSAGE_WARNING_LOG_DIRECTORY_S_NOT_WRITABLE', $dir),
				''
			);
		}
		else{
			$checks[] = \Core\HealthCheckResult::ConstructWarn(
				t('STRING_CHECK_LOG_DIRECTORY_S_DOES_NOT_EXIST', $dir),
				t('MESSAGE_WARNING_LOG_DIRECTORY_S_DOES_NOT_EXIST', $dir),
				''
			);
		}

		$dir = ROOT_PDIR;
		if(is_dir($dir) && is_writable($dir)){
			// Yay, everything is good here!
			$checks[] = \Core\HealthCheckResult::ConstructGood(
				t('STRING_CHECK_ROOT_DIRECTORY_S_OK', $dir),
				t('MESSAGE_SUCCESS_ROOT_DIRECTORY_S_OK', $dir)
			);
		}
		elseif(is_dir($dir)){
			$checks[] = \Core\HealthCheckResult::ConstructWarn(
				t('STRING_CHECK_ROOT_DIRECTORY_S_NOT_WRITABLE', $dir),
				t('MESSAGE_WARNING_ROOT_DIRECTORY_S_NOT_WRITABLE', $dir),
				''
			);
		}
		else{
			$checks[] = \Core\HealthCheckResult::ConstructWarn(
				t('STRING_CHECK_ROOT_DIRECTORY_S_DOES_NOT_EXIST', $dir),
				t('MESSAGE_WARNING_ROOT_DIRECTORY_S_DOES_NOT_EXIST', $dir),
				''
			);
		}

		$dir = \Core\Filestore\Factory::Directory('public/');
		if($dir->exists() && $dir->isWritable()){
			// Yay, everything is good here!
			$checks[] = \Core\HealthCheckResult::ConstructGood(
				t('STRING_CHECK_PUBLIC_DIRECTORY_S_OK', $dir->getPath()),
				t('MESSAGE_SUCCESS_PUBLIC_DIRECTORY_S_OK', $dir->getPath())
			);
		}
		elseif($dir->exists()){
			$checks[] = \Core\HealthCheckResult::ConstructWarn(
				t('STRING_CHECK_PUBLIC_DIRECTORY_S_NOT_WRITABLE', $dir->getPath()),
				t('MESSAGE_WARNING_PUBLIC_DIRECTORY_S_NOT_WRITABLE', $dir->getPath()),
				''
			);
		}
		else{
			$checks[] = \Core\HealthCheckResult::ConstructWarn(
				t('STRING_CHECK_PUBLIC_DIRECTORY_S_DOES_NOT_EXIST', $dir->getPath()),
				t('MESSAGE_WARNING_PUBLIC_DIRECTORY_S_DOES_NOT_EXIST', $dir->getPath()),
				''
			);
		}

		$dir = \Core\Filestore\Factory::Directory('assets/');
		if($dir->exists() && $dir->isWritable()){
			// Yay, everything is good here!
			$checks[] = \Core\HealthCheckResult::ConstructGood(
				t('STRING_CHECK_ASSET_DIRECTORY_S_OK', $dir->getPath()),
				t('MESSAGE_SUCCESS_ASSET_DIRECTORY_S_OK', $dir->getPath())
			);
		}
		elseif($dir->exists()){
			$checks[] = \Core\HealthCheckResult::ConstructWarn(
				t('STRING_CHECK_ASSET_DIRECTORY_S_NOT_WRITABLE', $dir->getPath()),
				t('MESSAGE_WARNING_ASSET_DIRECTORY_S_NOT_WRITABLE', $dir->getPath()),
				''
			);
		}
		else{
			$checks[] = \Core\HealthCheckResult::ConstructWarn(
				t('STRING_CHECK_ASSET_DIRECTORY_S_DOES_NOT_EXIST', $dir->getPath()),
				t('MESSAGE_WARNING_ASSET_DIRECTORY_S_DOES_NOT_EXIST', $dir->getPath()),
				''
			);
		}
		
		if(defined('SERVER_ID') && strlen(SERVER_ID) == 32){
			$checks[] = \Core\HealthCheckResult::ConstructGood(
				t('STRING_CHECK_SERVER_ID_IS_S', wordwrap(SERVER_ID, 4, '-', true)),
				t('MESSAGE_SUCCESS_CHECK_SERVER_ID_IS_S', wordwrap(SERVER_ID, 4, '-', true))
			);
		}
		else{
			$checks[] = \Core\HealthCheckResult::ConstructWarn(
				t('STRING_CHECK_SERVER_ID_NOT_VALID'),
				t('MESSAGE_ERROR_CHECK_SERVER_ID_NOT_VALID'),
				'/admin/serverid'
			);
		}
		
		foreach(Core::GetComponents() as $c){
			/** @var Component_2_1 $c */
			
			$rc = $c->runRequirementChecks();
			
			foreach($rc as $result){
				$m = $c->getName() . ': ' . $result['result']['message'];
				if($result['result']['passed']){
					if($result['result']['available'] !== true){
						$m .= ' (' . $result['result']['available'] . ')';
					}
					$checks[] = \Core\HealthCheckResult::ConstructGood($m, '');
				}
				else{
					$checks[] = \Core\HealthCheckResult::ConstructWarn($m, '', '');
				}
			}
		}
		

		return $checks;
	}
 private function _setupFileBrowser(View $view, PageRequest $request, $type)
 {
     $view->templatename = 'pages/tinymce/browser-icons.tpl';
     $view->mastertemplate = 'blank.tpl';
     $view->record = false;
     $accesspermission = 'p:/tinymce/filebrowser/access';
     $uploadpermission = 'p:/tinymce/filebrowser/upload';
     $sandboxconfig = '/tinymce/filebrowser/sandbox-user-uploads';
     if ($type == 'image') {
         $accept = 'image/*';
     } else {
         $accept = '*';
     }
     if (!\Core\user()->checkAccess($accesspermission)) {
         return View::ERROR_ACCESSDENIED;
     }
     // Get a listing of files in the appropriate directory.
     if (ConfigHandler::Get($sandboxconfig)) {
         $basedirname = 'public/tinymce/' . \Core\user()->get('id') . '/';
     } else {
         $basedirname = 'public/tinymce/';
     }
     if ($request->getParameter('dir')) {
         $dirname = $basedirname . str_replace('..', '', $request->getParameter('dir'));
     } else {
         $dirname = $basedirname;
     }
     // This will create a navigatable tree of directory listings for the user.
     $tree = explode('/', substr($dirname, strlen($basedirname)));
     $treestack = '';
     foreach ($tree as $k => $v) {
         if (!trim($v)) {
             unset($tree[$k]);
         } else {
             $treestack .= '/' . $v;
             $tree[$k] = array('name' => $v, 'stack' => $treestack);
         }
     }
     $dir = \Core\Filestore\Factory::Directory($dirname);
     // Allow automatic creation of the root directory.
     if ($dirname == $basedirname && !$dir->exists()) {
         $dir->mkdir();
     }
     if (!$dir->exists()) {
         return View::ERROR_NOTFOUND;
     }
     $dirlen = strlen($dir->getPath());
     $directories = array();
     $files = array();
     foreach ($dir->ls() as $file) {
         if ($file instanceof \Core\Filestore\Directory) {
             // Give me a count of children in that directory.  I need to do the logic custom here because I only want directories and imgaes.
             $count = 0;
             foreach ($file->ls() as $subfile) {
                 if ($file instanceof \Core\Filestore\Directory) {
                     $count++;
                 } elseif ($file instanceof \Core\Filestore\File) {
                     if ($type == 'image' && $file->isImage() || $type == 'file') {
                         $count++;
                     }
                 }
             }
             $directories[$file->getBasename()] = array('object' => $file, 'name' => $file->getBasename(), 'browsename' => substr($file->getPath(), $dirlen), 'children' => $count);
         } elseif ($file instanceof \Core\Filestore\File) {
             // I only want images
             if ($type == 'image' && !$file->isImage()) {
                 continue;
             }
             $files[$file->getBaseFilename()] = array('object' => $file, 'name' => $file->getBaseFilename(), 'selectname' => $file->getURL());
         }
     }
     // Sorting would be nice!
     ksort($directories);
     ksort($files);
     // Size presets
     $size = \Core\user()->get('/tinymce/filebrowser/size');
     if (!$size) {
         $size = 'lg';
     }
     switch ($size) {
         case 'sm':
             $sizepx = 16;
             break;
         case 'med':
             $sizepx = 32;
             break;
         case 'lg':
             $sizepx = 64;
             break;
         case 'xl':
             $sizepx = 128;
             break;
         default:
             $size = 'lg';
             $sizepx = 64;
     }
     // Only certain people are allowed the rights to upload here.
     if (\Core\user()->checkAccess($uploadpermission)) {
         $uploadform = new Form();
         $uploadform->set('action', \Core\resolve_link('/tinymce/' . $type . '/upload'));
         $uploadform->addElement('multifile', array('basedir' => $dirname, 'title' => 'Upload Files', 'name' => 'files', 'accept' => $accept));
         //$uploadform->addElement('submit', array('value' => 'Bulk Upload'));
     } else {
         $uploadform = false;
     }
     // Give me some useful tips to show the user.
     $tips = array('You can drag and drop files from your local machine to upload them!', 'You can double click on a directory to browse that directory.', 'You can single click on a file or directory to view more information about that file.', 'You can use the direction arrows on your keyboard to navigate between files!', 'Pressing ESCAPE will deselect any selected files.', 'You are free to rename or delete files at will, but be aware, you may delete a file you need!');
     $view->assign('directories', array_values($directories));
     $view->assign('files', array_values($files));
     $view->assign('size', $size);
     $view->assign('sizepx', $sizepx);
     $view->assign('location_tree', $tree);
     $view->assign('location', $treestack);
     $view->assign('tip', $tips[rand(0, sizeof($tips) - 1)]);
     $view->assign('uploadform', $uploadform);
     return View::ERROR_NOERROR;
 }
	/**
	 * Display a listing of all widgets registered in the system.
	 */
	public function admin(){
		$view = $this->getView();
		$request = $this->getPageRequest();

		$viewer = \Core\user()->checkAccess('p:/core/widgets/manage');
		$manager = \Core\user()->checkAccess('p:/core/widgets/manage');
		if(!($viewer || $manager)){
			return View::ERROR_ACCESSDENIED;
		}

		// Build a list of create pages for all registered components.
		$components    = Core::GetComponents();
		$pages         = [];
		$skins         = [];
		$selected      = null;
		$selectedtype  = null;
		$baseurl       = null;
		$selectoptions = [];
		$links         = [];
		$theme         = ThemeHandler::GetTheme();
		$formtheme     = null;
		$formskin      = null;
		$formtemplate  = null;

		foreach($components as $c){
			/** @var Component_2_1 $c */

			$viewdir = $c->getViewSearchDir();
			if($viewdir){
				$dirlen = strlen($viewdir);
				$component = $c->getName();

				$dh = \Core\Filestore\Factory::Directory($viewdir);
				//$pagetplfiles = $dh->ls('tpl', true);
				$pagetplfiles = $dh->ls(null, true);

				// not sure why getFilename(path) isn't working as expected, but this works too.
				foreach($pagetplfiles as $obj){

					// I don't want directories.
					if($obj instanceof \Core\Filestore\Directory) continue;

					/** @var $obj \Core\Filestore\File */
					$file = substr($obj->getFilename(), $dirlen);

					// Since this is a template, it may actually be in a different location than where the package maintainer put it.
					// ie: user template user/templates/pages/user/view.tpl may be installed to themes/myawesometheme/pages/user/view.tpl instead.
					$tpl = Core\Templates\Template::Factory($file);

					if($tpl->hasWidgetAreas()){
						$pagetitle = $file;
						if(strpos($pagetitle, 'pages/') === 0){
							$pagetitle = substr($pagetitle, 6);
						}
						// Replace directory slashes with a space
						$pagetitle = str_replace(['/', '-'], ' ', $pagetitle);
						// Capitalize them
						$pagetitle = ucwords($pagetitle);
						// And trim off the ".tpl" suffix.
						$pagetitle = substr($pagetitle, 0, -4);
						$pages[$file] = $pagetitle;
					}
				}
			}

			foreach($c->getXML()->getElements('/widgets/widgetcreate') as $node){
				/** @var DOMElement $node */

				if($node->getAttribute('baseurl')){
					$nodebaseurl = $node->getAttribute('baseurl');
					$image = '';
				}
				elseif($node->getAttribute('class')){
					/** @var Widget_2_1 $obj */
					$obj = Widget_2_1::Factory($node->getAttribute('class'));
					$nodebaseurl = '/widget/create?class=' . $node->getAttribute('class');
					if($obj){
						$image = $obj->getPreviewImage();
					}
					else{
						\Core\set_message('Invalid "widgetcreate" found in ' .$node->getAttribute('class') . ', ' . $node->getAttribute('title'), 'error');
						$image = '';
					}
				}
				else{
					\Core\set_message('Invalid "widgetcreate" found in ' . $c->getName() . ', ' . $node->getAttribute('title'), 'error');
					continue;
				}

				$links[] = [
					'baseurl' => $nodebaseurl,
					'title' => $node->getAttribute('title'),
				    'preview' => $image,
				];
			}
		}

		// Build the array of skins for the current theme
		$themeskins  = $theme->getSkins();
		$defaultskin = null;
		foreach($themeskins as $dat){

			$skins[ 'skins/' . $dat['file'] ] = $dat['title'];

			if($dat['default']){
				$defaultskin = 'skins/' . $dat['file'];
			}
		}

		// Now that the various templates have been loaded into a flat array, I need to sort them.
		asort($pages);
		asort($skins);

		foreach($skins as $k => $v){
			$selectoptions[ $k ] = 'Skin: ' . $v;
		}
		foreach($pages as $k => $v){
			$selectoptions[ $k ] = 'Page: ' . $v;
		}

		if($request->getParameter('baseurl')){
			// It's a URL-specific request, lookup which template that page used last.
			$baseurl  = $request->getParameter('baseurl');
			$page     = PageModel::Construct($baseurl);

			if(!isset($pages[ $page->get('last_template') ])){
				\Core\set_message('Requested page template does not seem to contain any widget areas.', 'error');
				\Core\go_back();
			}

			$selected = $page->get('last_template');
			$selectedtype = 'url';
			$formtemplate = $selected;
		}
		elseif($request->getParameter('template')){
			$selected = $request->getParameter('template');

			if(isset($pages[ $selected ])){
				$selectedtype = 'page';
				$formtemplate = $selected;
			}
			else{
				$selectedtype = 'skin';
				$formtheme = $theme->getKeyName();
				$formskin  = $selected;
			}
		}
		else{
			// Just use the default theme skin.
			$selected = $defaultskin;
			$selectedtype = 'skin';$formtheme = $theme->getKeyName();
			$formskin  = $selected;
		}

		$template     = \Core\Templates\Template::Factory($selected);
		$areas        = $template->getWidgetAreas();
		$installables = [0 => ''];

		foreach($areas as $k => $dat){
			// Ensure that each area has a widgets array, (even if it's empty)
			$areas[$k]['widgets'] = [];
			$installables[] = $dat['installable'];
		}
		$installables = array_unique($installables);

		$factory = new ModelFactory('WidgetInstanceModel');
		$factory->order('weight');
		if(Core::IsComponentAvailable('multisite') && MultiSiteHelper::IsEnabled()){
			$factory->whereGroup('or', ['site = -1', 'site = ' . MultiSiteHelper::GetCurrentSiteID()]);
		}

		if($selectedtype == 'skin'){
			// First, the skin-level where clause.
			$skinwhere = new Core\Datamodel\DatasetWhereClause();
			$skinwhere->setSeparator('AND');
			//$skinwhere->addWhere('theme = ' . $theme->getKeyName());
			$skinwhere->addWhere('template = ' . $selected);
			$factory->where($skinwhere);
		}
		elseif($selectedtype == 'page'){
			$factory->where('template = ' . $selected);
		}
		elseif($selectedtype == 'url'){
			$factory->where('page_baseurl = ' . $baseurl);
		}
		else{
			\Core\set_message('Invalid/unknown template type', 'error');
			\Core\go_back();
		}


		foreach($factory->get() as $wi){
			/** @var $wi WidgetInstanceModel */

			$a = $wi->get('widgetarea');
			$areas[$a]['widgets'][] = $wi;
		}

		$available = WidgetModel::Find(['installable IN ' . implode(', ', $installables)]);

		/*
		$table = new Core\ListingTable\Table();
		$table->setName('/admin/widgets');
		$table->setModelName('WidgetModel');
		// Add in all the columns for this listing table.
		$table->addColumn('Title', 'title');
		if(Core::IsComponentAvailable('enterprise') && MultiSiteHelper::IsEnabled() && \Core\user()->checkAccess('g:admin')){
			$table->addColumn('Site', 'site', false);
			$ms = true;
		}
		else{
			$ms = false;
		}
		$table->getModelFactory()->where('installable IN ' . implode(', ', $installables));
		$table->addColumn('Base URL', 'baseurl');
		$table->addColumn('Installable', 'installable');
		$table->addColumn('Created', 'created');

		$table->loadFiltersFromRequest();
		*/

		$view->mastertemplate = 'admin';
		$view->title = 'All Widgets';
		//$view->assign('table', $table);
		$view->assign('available_widgets', $available);
		$view->assign('links', $links);
		$view->assign('manager', $manager);
		$view->assign('theme', $formtheme);
		$view->assign('skin', $formskin);
		$view->assign('template', $selected);
		$view->assign('page_template', $formtemplate);
		$view->assign('page_baseurl', $baseurl);
		$view->assign('options', $selectoptions);
		$view->assign('selected', $selected);
		$view->assign('areas', $areas);
		//$view->assign('multisite', $ms);
	}
Beispiel #13
0
 public function delete($old)
 {
     if (!$this->canupload) {
         throw new \Exception('Modify access denied!');
     }
     $old = trim($old);
     $old = trim($old, '/');
     // Sanitize the filenames
     if (strpos($old, '..') !== false || strpos($old, '/') !== false) {
         throw new \Exception('Invalid directory name');
     }
     $dir = Filestore\Factory::Directory($this->_basedir . $this->_cwd);
     $obj = $dir->get($old);
     if (!$obj) {
         throw new \Exception($old . ' does not exist!');
     }
     $obj->delete();
 }
/**
 * Instantiate a new Directory object, ready for manipulation or access.
 *
 * @since 2011.07.09
 * @param string $directory
 * @return \Directory_Backend
 */
function directory($directory){
	return \Core\Filestore\Factory::Directory($directory);
}
 public function parseURL($url)
 {
     $path = \ConfigHandler::Get('/markdownbrowser/basedir');
     $dir = \Core\Filestore\Factory::Directory($path);
     $dirbase = $dir->getPath();
     $dirlen = strlen($dirbase);
     $file = \Core\filestore\Factory::File($this->basedir . '/' . $url);
     if ($file->exists()) {
         // Is this a markdown file or image?
         // If it's a markdown file, trim the '.md' off the end and give the relative path to the controller.
         if (strpos($url, '.md') !== false) {
             return \Core\resolve_link('/markdownbrowser/view/' . substr($file->getFilename(), $dirlen, -3));
         } elseif ($file->isImage()) {
             return \Core\resolve_link('/markdownbrowser/img/' . substr($file->getFilename(), $dirlen));
         } else {
             return \Core\resolve_link('/markdownbrowser/download/' . substr($file->getFilename(), $dirlen));
         }
     } else {
         // Hmm....?
         return '';
     }
 }