function run() { try { $election_input_path = Director::baseFolder() . '/' . ELECTION_VOTERS_INGEST_PATH; $files = scandir($election_input_path); $manager = new ElectionManager(new SapphireElectionRepository(), new SapphireFoundationMemberRepository(), new SapphireVoteRepository(), new SapphireVoterFileRepository(), new VoteFactory(), new VoterFileFactory(), new ElectionFactory(), SapphireTransactionManager::getInstance()); foreach ($files as $file_name) { if ($this->isCSV($file_name) && (list($election_id, $open_date, $close_date) = $this->isValidElectionFileName($file_name))) { try { echo printf('processing file %s' . PHP_EOL, $file_name); list($count, $not_processed) = $manager->ingestVotersForElection($election_input_path . '/' . $file_name, $election_id, $open_date, $close_date); echo printf('file %s - processed %d rows - not processed %d rows' . PHP_EOL, $file_name, $count, count($not_processed)); if (count($not_processed) > 0) { echo 'not processed details ... ' . PHP_EOL; echo var_dump($not_processed) . PHP_EOL; } echo printf('deleting file %s ...' . PHP_EOL, $file_name); unlink($election_input_path . '/' . $file_name); } catch (Exception $ex) { SS_Log::log($ex, SS_Log::ERR); echo $ex->getMessage(); } } } return 'OK'; } catch (Exception $ex) { SS_Log::log($ex, SS_Log::ERR); echo $ex->getMessage(); } }
function testUpload() { // create tmp file $tmpFileName = 'UploadTest-testUpload.txt'; $tmpFilePath = TEMP_FOLDER . '/' . $tmpFileName; $tmpFileContent = ''; for ($i = 0; $i < 10000; $i++) { $tmpFileContent .= '0'; } file_put_contents($tmpFilePath, $tmpFileContent); // emulates the $_FILES array $tmpFile = array('name' => $tmpFileName, 'type' => 'text/plaintext', 'size' => filesize($tmpFilePath), 'tmp_name' => $tmpFilePath, 'extension' => 'txt', 'error' => UPLOAD_ERR_OK); $v = new UploadTest_Validator(); // test upload into default folder $u1 = new Upload(); $u1->setValidator($v); $u1->load($tmpFile); $file1 = $u1->getFile(); $this->assertTrue(file_exists($file1->getFullPath()), 'File upload to standard directory in /assets'); $this->assertTrue(strpos($file1->getFullPath(), Director::baseFolder() . '/assets/' . Upload::$uploads_folder) !== false, 'File upload to standard directory in /assets'); $file1->delete(); // test upload into custom folder $customFolder = 'UploadTest-testUpload'; $u2 = new Upload(); $u2->load($tmpFile, $customFolder); $file2 = $u2->getFile(); $this->assertTrue(file_exists($file2->getFullPath()), 'File upload to custom directory in /assets'); $this->assertTrue(strpos($file2->getFullPath(), Director::baseFolder() . '/assets/' . $customFolder) !== false, 'File upload to custom directory in /assets'); $file2->delete(); unlink($tmpFilePath); rmdir(Director::baseFolder() . '/assets/' . $customFolder); }
/** * @param $locale */ public function __construct($locale = null) { $this->defaultLocale = $locale ? $locale : i18n::get_lang_from_locale(i18n::default_locale()); $this->basePath = Director::baseFolder(); $this->baseSavePath = Director::baseFolder(); parent::__construct(); }
public function updateSettingsFields(FieldList $fields) { $systemThemes = SiteConfig::current_site_config()->getAvailableThemes(); $partials = $themes = array('' => '', 'none' => '(none)'); foreach ($systemThemes as $key => $themeName) { if (file_exists(Director::baseFolder() . '/themes/' . $themeName . '/templates/Page.ss')) { $themes[$key] = $themeName; } else { $partials[$key] = $themeName; } } $themeDropdownField = new DropdownField("AppliedTheme", 'Applied Theme', $themes); $fields->addFieldToTab('Root.Theme', $themeDropdownField); $current = $this->appliedTheme(); if ($current) { $themeDropdownField->setRightTitle('Current effective theme: ' . $current); } else { $themeDropdownField->setRightTitle('Using default site theme'); } $themeDropdownField = new DropdownField("PartialTheme", 'Partial Theme', $partials); $fields->addFieldToTab('Root.Theme', $themeDropdownField); $current = $this->appliedPartialTheme(); if ($current) { $themeDropdownField->setRightTitle('Current effective partial theme: ' . $current); } else { $themeDropdownField->setRightTitle('Please only use a specific applied theme OR a partial theme, not both!'); } }
function init() { parent::init(); // Special case for dev/build: Defer permission checks to DatabaseAdmin->init() (see #4957) $requestedDevBuild = stripos($this->request->getURL(), 'dev/build') === 0; // We allow access to this controller regardless of live-status or ADMIN permission only // if on CLI. Access to this controller is always allowed in "dev-mode", or of the user is ADMIN. $canAccess = $requestedDevBuild || Director::isDev() || Director::is_cli() || Permission::check("ADMIN"); if (!$canAccess) { return Security::permissionFailure($this); } // check for valid url mapping // lacking this information can cause really nasty bugs, // e.g. when running Director::test() from a FunctionalTest instance global $_FILE_TO_URL_MAPPING; if (Director::is_cli()) { if (isset($_FILE_TO_URL_MAPPING)) { $fullPath = $testPath = BASE_PATH; while ($testPath && $testPath != "/" && !preg_match('/^[A-Z]:\\\\$/', $testPath)) { $matched = false; if (isset($_FILE_TO_URL_MAPPING[$testPath])) { $matched = true; break; } $testPath = dirname($testPath); } if (!$matched) { echo 'Warning: You probably want to define ' . 'an entry in $_FILE_TO_URL_MAPPING that covers "' . Director::baseFolder() . '"' . "\n"; } } else { echo 'Warning: You probably want to define $_FILE_TO_URL_MAPPING in ' . 'your _ss_environment.php as instructed on the "sake" page of the doc.silverstripe.org wiki' . "\n"; } } }
/** * Apply custom styles to the absolute description element. * * @parameter <{DESCRIPTION_CSS}> array(string) */ public static function customise_css($styles) { if (is_array($styles)) { // Determine the path to write against. $URL = DESCRIPTIVE_PATH . '/css/custom.css'; $path = Director::baseFolder() . "/{$URL}"; // Collate each custom style where appropriate. $CSS = '#cms-menu-descriptive {' . PHP_EOL; foreach ($styles as $style => $value) { if (!is_numeric($style)) { $CSS .= "\t{$style}: {$value} !important;" . PHP_EOL; // Apply any possible background change. if (strtolower($style) === 'background') { $background = '#cms-menu-descriptive:before,' . PHP_EOL . '#cms-menu-descriptive:after {' . PHP_EOL; $background .= "\tborder-top: 10px solid {$value} !important;" . PHP_EOL . '}' . PHP_EOL . PHP_EOL; $background .= '#cms-menu-descriptive:before {' . PHP_EOL; $background .= "\tborder-top: 13px solid !important;" . PHP_EOL; $background .= "\tborder-top-color: inherit !important;" . PHP_EOL . '}' . PHP_EOL; } } } $CSS .= '}' . PHP_EOL . PHP_EOL . $background; // Write the custom styles. file_put_contents($path, $CSS); chmod($path, 0664); LeftAndMain::require_css($URL); } }
/** * Setup the environment to point to a temporary location * * @param type $path */ protected function setTemporaryPath($path) { $this->envPath = $path; Filesystem::makeFolder($this->envPath); $this->envPath = realpath($this->envPath); Injector::inst()->load(array('DNData' => array('properties' => array('EnvironmentDir' => $this->envPath, 'KeyDir' => TEMP_FOLDER . '/deploynaut_test/gitkeys', 'DataTransferDir' => Director::baseFolder() . '/assets/transfers', 'GitUser' => '')))); }
public function Thumbnail($page = 1) { // Only thumbnail PDF files if (strtolower($this->owner->getExtension()) != 'pdf') { return false; } $file_filename = Director::baseFolder() . '/' . $this->owner->getFilename(); if (!file_exists($file_filename)) { return false; } $cache_filename = $this->owner->getFilename() . '.page-' . (int) $page . '.jpg'; // Check for existing cached thumbnail if (file_exists(Director::baseFolder() . '/' . $cache_filename) && filemtime(Director::baseFolder() . '/' . $cache_filename) > filemtime($file_filename)) { $img = DataObject::get_one('Image', "Filename = '" . $cache_filename . "'"); if ($img) { return $img; } } // Create and cache the thumbnail $command = self::$convert_path . ' -density 300x300 ' . escapeshellarg($file_filename . '[' . ((int) $page - 1) . ']') . ' -quality 100 -resize 2000x -units PixelsPerInch ' . escapeshellarg(Director::baseFolder() . '/' . $cache_filename); $out = shell_exec($command); //var_dump( $command ); if (!file_exists(Director::baseFolder() . '/' . $cache_filename)) { return false; } $img = new Image(); $img->setFilename($cache_filename); $img->write(); $img = DataObject::get_one('Image', "Filename = '" . $cache_filename . "'"); return $img; }
/** * * @param SilverStripeContentItem $item * @param type $parentObject * @param type $duplicateStrategy * @return TransformResult */ public function transform($item, $parentObject, $duplicateStrategy) { $newFile = $this->getTypeForFile($item->Name); $newFile = new $newFile(); $folderPath = $parentObject->getRelativePath(); $parentId = $parentObject ? $parentObject->ID : 0; $filter = '"ParentID" = \'' . Convert::raw2sql($parentId) . '\' and "Title" = \'' . Convert::raw2sql($item->Name) . '\''; $existing = DataObject::get_one('File', $filter); if ($existing && $duplicateStrategy == ExternalContentTransformer::DS_SKIP) { // just return the existing children return new TransformResult($existing, null); } else { if ($existing && $duplicateStrategy == ExternalContentTransformer::DS_OVERWRITE) { $newFile = $existing; } } $newFile->Name = $item->Name; $newFile->RemoteNodeId = $item->getSS_ID(); $newFile->RemoteSystemId = $item->getSource()->ID; $newFile->Title = $item->Title; $newFile->ParentID = $parentId; $newFile->write(); $filepath = Director::baseFolder() . '/' . $newFile->Filename; Filesystem::makeFolder(dirname($filepath)); $item->streamContent($filepath); return new TransformResult($newFile, null); }
function testFileLinkRewritingOnVirtualPages() { // File setup $this->logInWithPermission('ADMIN'); touch(Director::baseFolder() . '/assets/testscript-test-file.pdf'); // Publish the source page $page = $this->objFromFixture('SiteTree', 'page1'); $this->assertTrue($page->doPublish()); // Create a virtual page from it, and publish that $svp = new SubsitesVirtualPage(); $svp->CopyContentFromID = $page->ID; $svp->write(); $svp->doPublish(); // Rename the file $file = $this->objFromFixture('File', 'file1'); $file->Name = 'renamed-test-file.pdf'; $file->write(); // Verify that the draft and publish virtual pages both have the corrected link $this->assertContains('<img src="assets/renamed-test-file.pdf"', DB::query("SELECT \"Content\" FROM \"SiteTree\" WHERE \"ID\" = {$svp->ID}")->value()); $this->assertContains('<img src="assets/renamed-test-file.pdf"', DB::query("SELECT \"Content\" FROM \"SiteTree_Live\" WHERE \"ID\" = {$svp->ID}")->value()); // File teardown $testFiles = array('/assets/testscript-test-file.pdf', '/assets/renamed-test-file.pdf'); foreach ($testFiles as $file) { if (file_exists(Director::baseFolder() . $file)) { unlink(Director::baseFolder() . $file); } } }
/** * Return an image object representing the image in the given format. * This image will be generated using generateFormattedImage(). * The generated image is cached, to flush the cache append ?flush=1 to your URL. * * Just pass the correct number of parameters expected by the working function * * @param string $format The name of the format. * @return Image_Cached */ public function getFormattedImage($format) { $args = func_get_args(); if ($this->ID && $this->Filename && Director::fileExists($this->Filename)) { $cacheFile = call_user_func_array(array($this, "cacheFilename"), $args); $fullPath = Director::baseFolder() . "/" . $cacheFile; if (!file_exists($fullPath) || self::$flush) { call_user_func_array(array($this, "generateFormattedImage"), $args); // If this image should be compressed, compress it now if ($this->getCompressed()) { $compressor = $this->getCompressor(); try { $compressor->compress($fullPath)->writeTo($fullPath); } catch (Exception $e) { // Do nothing, leave the uncompressed image in-place } } } $cached = Injector::inst()->createWithArgs('Image_Cached', array($cacheFile)); // Pass through the title so the templates can use it $cached->Title = $this->Title; // Pass through the parent, to store cached images in correct folder. $cached->ParentID = $this->ParentID; return $cached; } }
public function process() { $post = $this->getObject(); if ($post) { $author = $post->Owner(); $balance = $author->Balance; if (self::$api_key && $post->Content != self::SPAM_CONTENT) { require_once Director::baseFolder() . '/microblog/thirdparty/defensio/Defensio.php'; $defensio = new Defensio(self::$api_key); $document = array('type' => 'comment', 'content' => $post->Content, 'platform' => 'silverstripe_microblog', 'client' => 'MicroBlog Defensio-PHP | 0.1 | Marcus Nyeholt | marcus@silverstripe.com.au', 'async' => 'false'); try { $result = $defensio->postDocument($document); if ($result && isset($result[1])) { if ($result[1]->allow == 'false') { $post->Content = self::SPAM_CONTENT; $post->Down += self::SPAM_DOWN; $post->write(); $author->Down += self::SPAM_DOWN; $author->write(); } } } catch (Exception $e) { SS_Log::log($e, SS_Log::WARN); } } if ($post->Content != self::SPAM_CONTENT) { $post->analyseContent(); $post->write(); } } $this->isComplete = true; }
function init() { parent::init(); // We allow access to this controller regardless of live-status or ADMIN permission only // if on CLI. Access to this controller is always allowed in "dev-mode", or of the user is ADMIN. $canAccess = Director::isDev() || Director::is_cli() || Permission::check("ADMIN"); if (!$canAccess) { return Security::permissionFailure($this, "This page is secured and you need administrator rights to access it. " . "Enter your credentials below and we will send you right along."); } // check for valid url mapping // lacking this information can cause really nasty bugs, // e.g. when running Director::test() from a FunctionalTest instance global $_FILE_TO_URL_MAPPING; if (Director::is_cli()) { if (isset($_FILE_TO_URL_MAPPING)) { $fullPath = $testPath = $_SERVER['SCRIPT_FILENAME']; while ($testPath && $testPath != "/" && !preg_match('/^[A-Z]:\\\\$/', $testPath)) { $matched = false; if (isset($_FILE_TO_URL_MAPPING[$testPath])) { $matched = true; break; } $testPath = dirname($testPath); } if (!$matched) { echo 'Warning: You probably want to define ' . 'an entry in $_FILE_TO_URL_MAPPING that covers "' . Director::baseFolder() . '"' . "\n"; } } else { echo 'Warning: You probably want to define $_FILE_TO_URL_MAPPING in ' . 'your _ss_environment.php as instructed on the "sake" page of the doc.silverstripe.com wiki' . "\n"; } } }
/** * Creates a content service asset object based on a given resampled file path * * @param type $filename * @return ContentServiceAsset */ protected function createResampledAsset($filename) { $fullpath = Director::baseFolder() . '/' . $filename; $asset = ContentServiceAsset::get()->filter('Filename', $filename)->first(); if (!$asset) { $asset = new ContentServiceAsset(); } $this->service = singleton('ContentService'); $asset->Filename = $filename; $asset->SourceID = $this->ID; $asset->ParentID = $this->ParentID; $mtime = time(); $writer = $this->service->getWriterFor($asset, 'FilePointer', $this->targetStore()); if ($writer) { if (file_exists($fullpath)) { // likely that cached image never got built correctly. $name = \Controller::join_links(dirname($filename), $mtime, basename($filename)); $writer->write(fopen($fullpath, 'r'), $name); $asset->FilePointer = $writer->getContentId(); $asset->write(); $reader = $writer->getReader(); if ($reader && $reader->exists()) { @unlink($fullpath); } } else { $asset = null; } } else { $asset = null; } return $asset; }
/** * Store the contents of a folder on a CDN. * * If processReferences is set, relative URL references are attempted to be * detected and stored remotely as well, with the file to be stored rewritten * to refer to the CDN value. This really is only useful for CSS * * @param string $folder * @param boolean $processReferences */ public function storeThemeFile($toCdn, $file, $forceUpdate = false, $processReferences = false) { $mtime = @filemtime($file); $relativeName = self::CDN_THEME_PREFIX . '/' . $mtime . '/' . trim(str_replace(Director::baseFolder(), '', $file), '/'); if (!$forceUpdate) { // see if the file already exists, if not we do NOT do an update $reader = $this->contentService->findReaderFor($toCdn, $relativeName); if ($reader && $reader->exists()) { return $reader->getURL(); } } $clear = false; if ($processReferences) { $clear = true; $file = $this->processFileReferences($toCdn, $file, $forceUpdate); } // otherwise, lets get a content writer $writer = $this->contentService->getWriter($toCdn); try { $writer->write($file, $relativeName); } catch (Exception $e) { SS_Log::log($e, SS_Log::WARN); } if ($clear && strpos($file, '.cdn') > 0) { @unlink($file); } $id = $writer->getContentId(); return $writer->getReader()->getURL(); }
public function generateFormattedImage($format, $arg1 = null, $arg2 = null) { $cacheFile = $this->cacheFilename($format, $arg1, $arg2); $gd = new GDBackend(Director::baseFolder() . "/" . $this->Filename); // Skip aktual generation return $gd; }
function setUp() { parent::setUp(); $this->alternateBasePath = Director::baseFolder() . "/sapphire/tests/i18n/_fakewebroot"; $this->alternateBaseSavePath = TEMP_FOLDER . '/i18nTextCollectorTest_webroot'; FileSystem::makeFolder($this->alternateBaseSavePath); // SSViewer and ManifestBuilder don't support different webroots, hence we set the paths manually global $_CLASS_MANIFEST; $_CLASS_MANIFEST['i18nTestModule'] = $this->alternateBasePath . '/i18ntestmodule/code/i18nTestModule.php'; $_CLASS_MANIFEST['i18nTestModule_Addition'] = $this->alternateBasePath . '/i18ntestmodule/code/i18nTestModule.php'; $_CLASS_MANIFEST['i18nTestModuleDecorator'] = $this->alternateBasePath . '/i18nothermodule/code/i18nTestModuleDecorator.php'; global $_ALL_CLASSES; $_ALL_CLASSES['parents']['i18nTestModule'] = array('DataObject'=>'DataObject','Object'=>'Object'); $_ALL_CLASSES['parents']['i18nTestModule_Addition'] = array('Object'=>'Object'); $_ALL_CLASSES['parents']['i18nTestModuleDecorator'] = array('DataObjectDecorator'=>'DataObjectDecorator','Object'=>'Object'); global $_TEMPLATE_MANIFEST; $_TEMPLATE_MANIFEST['i18nTestModule.ss'] = array( 'main' => $this->alternateBasePath . '/i18ntestmodule/templates/i18nTestModule.ss', 'Layout' => $this->alternateBasePath . '/i18ntestmodule/templates/Layout/i18nTestModule.ss', ); $_TEMPLATE_MANIFEST['i18nTestModuleInclude.ss'] = array( 'Includes' => $this->alternateBasePath . '/i18ntestmodule/templates/Includes/i18nTestModuleInclude.ss', ); $_TEMPLATE_MANIFEST['i18nTestModule.ss'] = array( 'main' => $this->alternateBasePath . '/i18ntestmodule/templates/i18nTestModule.ss', 'Layout' => $this->alternateBasePath . '/i18ntestmodule/templates/Layout/i18nTestModule.ss', ); }
public function clearResampledImages() { $files = glob(Director::baseFolder() . '/' . $this->Parent()->Filename . "_resampled/*-{$this->Name}"); foreach ($files as $file) { unlink($file); } }
/** * @param int $amount * @return array */ function getGoogleFonts($amount = 30) { $fontFile = Director::baseFolder() . '/boilerplate/fonts/google-web-fonts.txt'; //Total time the file will be cached in seconds, set to a week $cacheTime = 86400 * 7; if (file_exists($fontFile) && $cacheTime < filemtime($fontFile)) { $content = json_decode(file_get_contents($fontFile)); } else { $url = 'https://www.googleapis.com/webfonts/v1/webfonts?key=' . SiteConfig::current_site_config()->FontAPI; $ch = curl_init(); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($ch, CURLOPT_HEADER, false); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_REFERER, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); $fontContent = curl_exec($ch); curl_close($ch); $fp = fopen($fontFile, 'w'); fwrite($fp, $fontContent); fclose($fp); $content = json_decode($fontContent); } if ($amount == 'all') { return $content->items; } else { return array_slice($content->items, 0, $amount); } }
protected function userCaller() { $bt = debug_backtrace(2); if (!isset($bt[5])) { return; } $base = Director::baseFolder(); for ($i = 2, $c = count($bt); $i < $c; $i++) { $history = $bt[$i]; if (!isset($history['file'])) { continue; } $file = trim(str_replace($base, '', $history['file']), '/'); $bits = explode('/', $file); if (in_array($bits[0], $this->userCode) && $i < 15) { if (!isset($history['class'])) { $history['class'] = ''; } if (!isset($history['type'])) { $history['type'] = ''; } return $history; } } }
static function folderModTime($folder, $extensionList = null, $recursiveCall = false) { //$cacheID = $folder . ',' . implode(',', $extensionList); //if(!$recursiveCall && self::$cache_folderModTime[$cacheID]) return self::$cache_folderModTime[$cacheID]; $modTime = 0; if (!Filesystem::isAbsolute($folder)) { $folder = Director::baseFolder() . '/' . $folder; } $items = scandir($folder); foreach ($items as $item) { if ($item[0] != '.') { // Recurse into folders if (is_dir("{$folder}/{$item}")) { $modTime = max($modTime, self::folderModTime("{$folder}/{$item}", $extensionList, true)); // Check files } else { if ($extensionList) { $extension = strtolower(substr($item, strrpos($item, '.') + 1)); } if (!$extensionList || in_array($extension, $extensionList)) { $modTime = max($modTime, filemtime("{$folder}/{$item}")); } } } } //if(!$recursiveCall) self::$cache_folderModTime[$cacheID] = $modTime; return $modTime; }
public function squareImage() { Folder::find_or_make(Director::baseFolder() . '/assets/ytimages'); if (!file_exists(Director::baseFolder() . '/assets/ytimages/' . $this->Code . '.png')) { //Your Image $imgSrc = "http://img.youtube.com/vi/{$this->Code}/hqdefault.jpg"; //getting the image dimensions list($width, $height) = getimagesize($imgSrc); //saving the image into memory (for manipulation with GD Library) $myImage = imagecreatefromjpeg($imgSrc); // calculating the part of the image to use for thumbnail if ($width > $height) { $y = 0; $x = ($width - $height) / 2; $smallestSide = $height; } else { $x = 0; $y = ($height - $width) / 2; $smallestSide = $width; } // copying the part into thumbnail $thumbSize = 120; $thumb = imagecreatetruecolor($thumbSize, $thumbSize); imagecopyresampled($thumb, $myImage, 0, 0, $x, $y, $thumbSize, $thumbSize, $smallestSide, $smallestSide); imagepng($thumb, Director::baseFolder() . '/assets/ytimages/' . $this->Code . '.png'); } return '/assets/ytimages/' . $this->Code . '.png'; }
function publishPages($urls) { parent::publishPages($urls); $base = Director::baseFolder(); $framework = FRAMEWORK_DIR; // Get variable that can turn off the rsync component of publication if (isset($_GET['norsync']) && $_GET['norsync']) { return; } $extraArg = ""; if (self::$excluded_folders) { foreach (self::$excluded_folders as $folder) { $extraArg .= " --exclude " . escapeshellarg($folder); } } foreach (self::$targets as $target) { // Transfer non-PHP content from everything to the target; that will ensure that we have all the JS/CSS/etc $rsyncOutput = `cd {$base}; rsync -av -e ssh --exclude /.htaccess --exclude /web.config --exclude '*.php' --exclude '*.svn' --exclude '*.git' --exclude '*~' {$extraArg} --delete . {$target}`; // Then transfer "safe" PHP from the cache/ directory $rsyncOutput .= `cd {$base}; rsync -av -e ssh --exclude '*.svn' --exclude '*~' {$extraArg} --delete cache {$target}`; // Transfer framework/static-main.php to the target $rsyncOutput .= `cd {$base}; rsync -av -e ssh --delete {$framework}/static-main.php {$target}/{$framework}`; if (StaticPublisher::echo_progress()) { echo $rsyncOutput; } } }
public function getCMSFields() { $fields = parent::getCMSFields(); $localFileNames = array_values(FileSystemTools::nodot_files(FileSystemTools::build_path(Director::baseFolder(), Replicant::config()->get('files_path')))); $fields->addFieldToTab('Root.Main', new DropdownField('FileName', 'Database dump to restore', array_combine($localFileNames, $localFileNames))); return $fields; }
function init() { parent::init(); // check for valid url mapping // lacking this information can cause really nasty bugs, // e.g. when running Director::test() from a FunctionalTest instance global $_FILE_TO_URL_MAPPING; if(Director::is_cli()) { if(isset($_FILE_TO_URL_MAPPING)) { $fullPath = $testPath = $_SERVER['SCRIPT_FILENAME']; while($testPath && $testPath != "/") { $matched = false; if(isset($_FILE_TO_URL_MAPPING[$testPath])) { $matched = true; break; } $testPath = dirname($testPath); } if(!$matched) { echo 'Warning: You probably want to define '. 'an entry in $_FILE_TO_URL_MAPPING that covers "' . Director::baseFolder() . '"' . "\n"; } } else { echo 'Warning: You probably want to define $_FILE_TO_URL_MAPPING in '. 'your _ss_environment.php as instructed on the "sake" page of the doc.silverstripe.com wiki' . "\n"; } } }
/** * Finds the path for specified file. * * @param string $fileOrUrl * @return string|boolean */ protected static function path_for_file($fileOrUrl) { if (preg_match('{^//|http[s]?}', $fileOrUrl)) { return $fileOrUrl; } elseif (Director::fileExists($fileOrUrl)) { $filePath = preg_replace('/\\?.*/', '', Director::baseFolder() . '/' . $fileOrUrl); $prefix = Director::baseURL(); $mtimesuffix = ""; $suffix = ''; if (Requirements::get_suffix_requirements()) { $mtimesuffix = "?m=" . filemtime($filePath); $suffix = '&'; } if (strpos($fileOrUrl, '?') !== false) { if (strlen($suffix) == 0) { $suffix = '?'; } $suffix .= substr($fileOrUrl, strpos($fileOrUrl, '?') + 1); $fileOrUrl = substr($fileOrUrl, 0, strpos($fileOrUrl, '?')); } else { $suffix = ''; } return "{$prefix}{$fileOrUrl}{$mtimesuffix}{$suffix}"; } else { return false; } }
public function init() { parent::init(); $themeDir = SSViewer::get_theme_folder(); Requirements::javascript('framework/thirdparty/jquery/jquery.js'); if (Locator::getLocations()) { Requirements::javascript('http://maps.google.com/maps/api/js?sensor=false'); Requirements::javascript('locator/thirdparty/handlebars/handlebars-v1.3.0.js'); Requirements::javascript('locator/thirdparty/jquery-store-locator/js/jquery.storelocator.js'); } Requirements::css('locator/css/map.css'); $featured = Locator::getLocations(array('Featured' => 1))->count() > 0 ? 'featuredLocations: true' : 'featuredLocations: false'; // map config based on user input in Settings tab // AutoGeocode or Full Map $load = $this->data()->AutoGeocode ? 'autoGeocode: true, fullMapStart: false,' : 'autoGeocode: false, fullMapStart: true, storeLimit: 1000, maxDistance: true,'; $base = Director::baseFolder(); $themePath = $base . '/' . $themeDir; $listTemplatePath = file_exists($themePath . '/templates/location-list-description.html') ? $themeDir . '/templates/location-list-description.html' : 'locator/templates/location-list-description.html'; $infowindowTemplatePath = file_exists($themePath . '/templates/infowindow-description.html') ? $themeDir . '/templates/infowindow-description.html' : 'locator/templates/infowindow-description.html'; // in page or modal $modal = $this->data()->ModalWindow ? 'modalWindow: true' : 'modalWindow: false'; $kilometer = $this->data()->Unit == 'km' ? 'lengthUnit: "km"' : 'lengthUnit: "m"'; $link = $this->Link() . 'xml.xml'; // init map if (Locator::getLocations()) { Requirements::customScript("\n \$(function(\$) {\n \$('#map-container').storeLocator({\n " . $load . "\n dataLocation: '" . $link . "',\n listTemplatePath: '" . $listTemplatePath . "',\n infowindowTemplatePath: '" . $infowindowTemplatePath . "',\n originMarker: true,\n " . $modal . ', ' . $featured . ",\n slideMap: false,\n zoomLevel: 0,\n distanceAlert: 120,\n formID: 'Form_LocationSearch',\n inputID: 'Form_LocationSearch_address',\n categoryID: 'Form_LocationSearch_category',\n distanceAlert: -1,\n " . $kilometer . ' }); }); '); } }
function index() { $posts = $this->request->postVars(); $filename = $posts['filename']; $surveyID = intval($posts['surveyID']); if (!$filename || !Member::currentUser() || !$surveyID || !($Survey = Survey::get()->filter('ID', $surveyID)->first())) { return false; } $folder = Folder::find_or_make('jsonFormFiles'); $fullFileName = Director::baseFolder() . '/' . $folder->getRelativePath() . $filename . '.json'; $jsonString = '{"name":"' . $Survey->Name . '","startDate": "' . $Survey->StartDate . '", "endDate": "' . $Survey->EndDate . '","sections": ['; foreach ($Survey->Sections() as $Section) { $jsonString .= '{"Title": "' . $Section->Title . '","Descripton": "' . $Section->Description . '","sectionQuestions": ['; foreach ($Section->SurveyQuestions() as $SQ) { $jsonString .= '{"number": "' . $SQ->Number . '","title": "' . $SQ->Title . '","description":"' . $SQ->Description . '","helpText": "' . $SQ->HelpText . '","questions": ['; foreach ($SQ->Questions() as $Question) { $jsonString .= $Question->renderJson(); } $jsonString = rtrim($jsonString, ","); $jsonString .= ']},'; } $jsonString = rtrim($jsonString, ","); $jsonString .= ']},'; } $jsonString = rtrim($jsonString, ","); $jsonString .= ']}'; file_put_contents($fullFileName, $jsonString); $Survey->LastJsonGenerated = SS_Datetime::now()->getValue(); $Survey->write(); }
public function testRelativeFixturePath() { $relPath = FRAMEWORK_DIR . '/tests/testing/YamlFixtureTest.yml'; $obj = new YamlFixture($relPath); $this->assertEquals(Director::baseFolder() . '/' . $relPath, $obj->getFixtureFile()); $this->assertNull($obj->getFixtureString()); }
function testBlockedCombinedJavascript() { $combinedFilePath = Director::baseFolder() . '/' . 'RequirementsTest_bc.js'; /* BLOCKED COMBINED FILES ARE NOT INCLUDED */ $this->setupCombinedRequirements(); Requirements::block('RequirementsTest_bc.js'); Requirements::delete_combined_files('RequirementsTest_bc.js'); clearstatcache(); // needed to get accurate file_exists() results $html = Requirements::includeInHTML(false, self::$html_template); $this->assertFalse((bool) preg_match('/src=".*\\/RequirementsTest_bc\\.js/', $html), 'blocked combined files are not included '); Requirements::unblock('RequirementsTest_bc.js'); /* BLOCKED UNCOMBINED FILES ARE NOT INCLUDED */ // need to re-add requirements, as Requirements::process_combined_includes() alters the // original arrays grml... $this->setupCombinedRequirements(); Requirements::block('sapphire/tests/forms/RequirementsTest_b.js'); Requirements::delete_combined_files('RequirementsTest_bc.js'); clearstatcache(); // needed to get accurate file_exists() results $html = Requirements::includeInHTML(false, self::$html_template); $this->assertFalse(strpos(file_get_contents($combinedFilePath), "alert('b')") !== false, 'blocked uncombined files are not included'); Requirements::unblock('RequirementsTest_b.js'); /* A SINGLE FILE CAN'T BE INCLUDED IN TWO COMBINED FILES */ $this->setupCombinedRequirements(); clearstatcache(); // needed to get accurate file_exists() results // This throws a notice-level error, so we prefix with @ @Requirements::combine_files('RequirementsTest_ac.js', array('sapphire/tests/forms/RequirementsTest_a.js', 'sapphire/tests/forms/RequirementsTest_c.js')); $combinedFiles = Requirements::get_combine_files(); $this->assertEquals(array_keys($combinedFiles), array('RequirementsTest_bc.js'), "A single file can't be included in two combined files"); Requirements::delete_combined_files('RequirementsTest_bc.js'); }