/** * Remove a module from this project. * This is designed to be called from sake. * * Usage: sake dev/modules/remove ecommerce othermodule */ function remove() { if (!Director::is_cli()) { return new HTTPResponse('ModuleManager only currently works in command-line mode.', 403); } if (isset($_GET['args'])) { $modules = $_GET['args']; foreach ($modules as $module) { if (preg_match('/^[a-zA-Z0-9\\/_-]+$/', $module)) { $moduleDir = strtok($module, '/'); if (is_dir(Director::baseFolder() . '/' . $moduleDir)) { $moduleDir = strtok($module, '/'); echo "Removing directory '{$moduleDir}' from svn:externals...\n"; if ($this->svnRemoveExternal(Director::baseFolder(), $moduleDir)) { $CLI_moduleDir = escapeshellarg(Director::baseFolder() . '/' . $moduleDir); echo "Removing the physical directory {$CLI_moduleDir}...\n"; `rm -rf {$CLI_moduleDir}`; echo "Calling SVN update...\n"; $this->svnUpdate(Director::baseFolder()); // We call this through sake so that the _config.php files get reprocessed echo "Rebuilding...\n"; $CLI_baseFolder = Director::baseFolder(); `cd {$CLI_baseFolder}; ./sapphire/sake dev/build`; } else { echo "Directory '{$moduleDir}' didn't seem to be an svn external\n"; } } else { echo "Can't find the '{$moduleDir}' directory.\n"; } } else { echo "Bad module '{$module}'\n"; } } } }
public function run($request) { $this->nl = Director::is_cli() ? "\n" : "<br>"; $this->log("Start!"); $this->processCalendarData(); $this->log("Done!"); }
/** * Rebuilds the static cache for the pages passed through via $urls * @param array $urls The URLs of pages to re-fetch and cache. */ function rebuildCache($urls, $removeAll = true) { if (!is_array($urls)) { return; } // $urls must be an array if (!Director::is_cli()) { echo "<pre>\n"; } echo "Rebuilding cache.\nNOTE: Please ensure that this page ends with 'Done!' - if not, then something may have gone wrong.\n\n"; $page = singleton('Page'); foreach ($urls as $i => $url) { $url = Director::makeRelative($url); if (substr($url, -1) == '/') { $url = substr($url, 0, -1); } $urls[$i] = $url; } $urls = array_unique($urls); if ($removeAll && file_exists("../cache")) { echo "Removing old cache... \n"; flush(); Filesystem::removeFolder("../cache", true); echo "done.\n\n"; } echo "Republishing " . sizeof($urls) . " urls...\n\n"; $page->publishPages($urls); echo "\n\n== Done! =="; }
public function run($request) { if (!Director::is_cli()) { echo "<pre>"; } echo "* Sync filesystem with database...\n"; echo "* " . FileSystem::sync() . "\n"; echo "* Applying secure file rules...\n"; $secure = 0; $unsecure = 0; $folders = DataObject::get('Folder'); if ($folders) { foreach ($folders as $folder) { $folder->Secured ? $secure++ : $unsecure++; $folder->forceChange(); $folder->write(); } echo "* " . $folders->Count() . " folders processed: {$secure} secure, {$unsecure} unsecure\n"; } else { echo "* No folders found!\n"; } echo "* Task finished.\n"; if (!Director::is_cli()) { echo "</pre>"; } }
/** * Set an alternative database in a browser cookie, * with the cookie lifetime set to the browser session. * This is useful for integration testing on temporary databases. * * There is a strict naming convention for temporary databases to avoid abuse: * <prefix> (default: 'ss_') + tmpdb + <7 digits> * As an additional security measure, temporary databases will * be ignored in "live" mode. * * Note that the database will be set on the next request. * Set it to null to revert to the main database. */ public static function set_alternative_database_name($name = null) { // Skip if CLI if (Director::is_cli()) { return; } if ($name) { if (!self::valid_alternative_database_name($name)) { throw new InvalidArgumentException(sprintf('Invalid alternative database name: "%s"', $name)); } $key = Config::inst()->get('Security', 'token'); if (!$key) { throw new LogicException('"Security.token" not found, run "sake dev/generatesecuretoken"'); } if (!function_exists('mcrypt_encrypt')) { throw new LogicException('DB::set_alternative_database_name() requires the mcrypt PHP extension'); } $key = md5($key); // Ensure key is correct length for chosen cypher $ivSize = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CFB); $iv = mcrypt_create_iv($ivSize); $encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $name, MCRYPT_MODE_CFB, $iv); // Set to browser session lifetime, and restricted to HTTP access only Cookie::set("alternativeDatabaseName", base64_encode($encrypted), 0, null, null, false, true); Cookie::set("alternativeDatabaseNameIv", base64_encode($iv), 0, null, null, false, true); } else { Cookie::set("alternativeDatabaseName", null, 0, null, null, false, true); Cookie::set("alternativeDatabaseNameIv", null, 0, null, null, false, true); } }
/** * Filter executed before a request processes * * @param SS_HTTPRequest $request Request container object * @param Session $session Request session * @param DataModel $model Current DataModel * @return boolean Whether to continue processing other filters. Null or true will continue processing (optional) */ public function preRequest(SS_HTTPRequest $request, Session $session, DataModel $model) { if (!\Director::is_cli() && ($response = $this->redirector->getResponse($request))) { $response->output(); exit; } }
/** * @param SS_HTTPRequest $request */ public function run($request) { // Only allow execution from the command line (for simplicity). if (!Director::is_cli()) { echo "<p>Sorry, but this can only be run from the command line.</p>"; return; } try { // Get and validate desired maintenance mode setting. $get = $request->getVars(); if (empty($get["args"])) { throw new Exception("Please provide an argument (e.g. 'on' or 'off').", 1); } $arg = strtolower(current($get["args"])); if ($arg != "on" && $arg != "off") { throw new Exception("Invalid argument: '{$arg}' (expected 'on' or 'off')", 2); } // Get and write site configuration now. $config = SiteConfig::current_site_config(); $previous = !empty($config->MaintenanceMode) ? "on" : "off"; $config->MaintenanceMode = $arg == "on"; $config->write(); // Output status and exit. if ($arg != $previous) { $this->output("Maintenance mode is now '{$arg}'."); } else { $this->output("NOTE: Maintenance mode was already '{$arg}' (nothing has changed)."); } } catch (Exception $e) { $this->output("ERROR: " . $e->getMessage()); if ($e->getCode() <= 2) { $this->output("Usage: sake dev/tasks/MaintenanceMode [on|off]"); } } }
function init() { parent::init(); if (!(Director::isDev() || Director::is_cli() || Permission::check("ADMIN"))) { return Security::permissionFailure($this); } }
public function init() { parent::init(); if (!Director::is_cli() && !Permission::check('ADMIN')) { return Security::permissionFailure(); } }
public function run($request) { if (!Director::is_cli() && !isset($_GET['run'])) { DB::alteration_message('Must add ?run=1', 'error'); return false; } if (!Director::is_cli()) { // - Add UTF-8 so characters will render as they should when debugging (so you can visualize inproperly formatted characters easier) // - Add base_tag so that printing blocks of HTML works properly with relative links (helps with visualizing errors) ?> <head> <?php echo SSViewer::get_base_tag(''); ?> <meta charset="UTF-8"> </head> <?php } increase_time_limit_to(300); WordpressDatabase::$default_config = $this->config()->default_db; $this->db = $this->wordpressImportService->getDatabase(); // Login as default admin so 'canPublish()' definitely returns true in 'SiteTree::doPublish()' if (!Member::currentUser()) { $defaultAdmin = Member::default_admin(); if ($defaultAdmin && $defaultAdmin->exists()) { Session::set('loggedInAs', $defaultAdmin->ID); } } // Unsure if the importing functionality can ever hit this, but just incase. if (Versioned::current_stage() !== 'Stage') { throw new Exception('Versioned::current_stage() must be "Stage".'); } $this->runCustom($request); }
function run($request) { $br = Director::is_cli() ? "\n" : "<br/>"; $verbose = true; //TODO: include order total calculation, once that gets written //TODO: figure out how to make this run faster //TODO: better memory managment...the destroy calls are not enough it appears. if ($orders = DataObject::get("Order")) { echo $br . "Writing all order items "; foreach ($orders as $order) { if ($items = $order->Items()) { foreach ($items as $item) { if ($item->Product()) { if ($verbose) { echo $item->ID . " "; } $item->write(); //OrderItem->onBeforeWrite calls 'CalculateTotal' } $item->destroy(); } } $order->destroy(); } echo $br . "done." . $br; } }
public function init() { parent::init(); if (!Director::is_cli() && !Permission::check("ADMIN") && $_SERVER['REMOTE_ADDR'] != $_SERVER['SERVER_ADDR']) { return Security::permissionFailure(); } }
/** * will ask the target server to return the file list and the data object list * @param type $request */ public function run($request) { if (!$this->config()->target) { throw new Exception('Target not found in yml file. See readme.md for installation instructions.'); } if (!$this->config()->key) { throw new Exception('Key not found in yml file. See readme.md for installation instructions.'); } $myurl = Director::absoluteURL('/remoteassetdiff') . '/' . urlencode($this->config()->key); $downloadurl = Director::absoluteURL('/remoteassetdownload') . '/' . urlencode($this->config()->key) . '?m=' . time(); // download without javascript if (Director::is_cli()) { ini_set('memory_limit', '1024M'); set_time_limit(0); echo "Creating list of files to download" . PHP_EOL; $listoffiles = RemoteAssetTask::DownloadFile($myurl); $fullist = json_decode($listoffiles); if (!is_array($fullist->download)) { throw new Exception('Failure to download list of files'); } foreach ($fullist->download as $file) { echo "Downloading {$file} ... "; try { RemoteAssetTask::DownloadFile($downloadurl . '&download=' . $file); echo "Success" . PHP_EOL; } catch (Exception $e) { echo "Failure" . PHP_EOL; } } echo "Done" . PHP_EOL; return; } echo ArrayData::create(array('FetchURL' => $myurl, 'DownloadURL' => $downloadurl, 'Target' => $this->config()->target, 'ToMachine' => Director::absoluteURL('/')))->renderWith('RemoteAssetTask'); }
function init() { if (!Director::is_cli() && !Director::isDev() && !Permission::check("ADMIN")) { Security::permissionFailure(); } parent::init(); }
/** * Require basic authentication. Will request a username and password if none is given. * * Used by {@link Controller::init()}. * * @param string $realm * @param string|array $permissionCode * @return Member $member */ static function requireLogin($realm, $permissionCode) { if (!Security::database_is_ready() || Director::is_cli()) { return true; } if (isset($_SERVER['PHP_AUTH_USER']) && isset($_SERVER['PHP_AUTH_PW'])) { $member = MemberAuthenticator::authenticate(array('Email' => $_SERVER['PHP_AUTH_USER'], 'Password' => $_SERVER['PHP_AUTH_PW']), null); if ($member) { $authenticated = true; } } // If we've failed the authentication mechanism, then show the login form if (!isset($authenticated)) { header("WWW-Authenticate: Basic realm=\"{$realm}\""); header($_SERVER['SERVER_PROTOCOL'] . ' 401 Unauthorized'); if (isset($_SERVER['PHP_AUTH_USER'])) { echo _t('BasicAuth.ERRORNOTREC', "That username / password isn't recognised"); } else { echo _t('BasicAuth.ENTERINFO', "Please enter a username and password."); } die; } if (!Permission::checkMember($member->ID, $permissionCode)) { header("WWW-Authenticate: Basic realm=\"{$realm}\""); header($_SERVER['SERVER_PROTOCOL'] . ' 401 Unauthorized'); if (isset($_SERVER['PHP_AUTH_USER'])) { echo _t('BasicAuth.ERRORNOTADMIN', "That user is not an administrator."); } die; } return $member; }
public function run($request) { $log = function ($message) { $message = sprintf('[%s] ', date('Y-m-d H:i:s')) . $message; echo $message . PHP_EOL; }; if (!Director::is_cli()) { $log('This command can only run via CLI'); return; } $columns = DB::query('SHOW COLUMNS FROM "DNDeployment"')->column(); if (!in_array('Branch', $columns)) { $log('Migration has already been run'); return; } if (!in_array('RefName', $columns)) { $log('RefName column doesn\'t exist. Has dev/build been run?'); return; } foreach (DB::query('SELECT "ID", "Branch" FROM "DNDeployment"') as $record) { // This record looks to be already migrated or doesn't have a value to begin with. Skip. if (empty($record['Branch'])) { continue; } DB::query(sprintf('UPDATE "DNDeployment" SET "RefName" = \'%s\' WHERE "ID" = %s', $record['Branch'], $record['ID'])); // Blank out the old column, as it has been successfully migrated. DB::query(sprintf('UPDATE "DNDeployment" SET "Branch" = NULL WHERE "ID" = %s', $record['ID'])); $log(sprintf('DNDeployment record %s has been successfully migrated', $record['ID'])); } DB::query('ALTER TABLE "DNDeployment" DROP COLUMN "Branch"'); $log('Finished'); }
public function run($request) { if (!Director::is_cli()) { $this->writeln('This task works only on the command line. Exiting.'); return; } $dropping = (bool) $request->requestVar('dropping'); $artefacts = $this->artefacts(); if (empty($artefacts)) { $this->headerln('Schema is clean; nothing to drop.'); } else { if ($dropping) { $this->headerln('Dropping artefacts'); } else { $this->headerln('Listing artefacts'); } foreach ($artefacts as $table => $drop) { if (is_array($drop)) { $this->writeln('* ' . $this->dropColumns($table, $drop, $dropping)); } else { $this->writeln('* ' . $this->dropTable($table, $dropping)); } } $this->headerln('Next step'); if ($dropping) { $this->writeln('Re-check for artefacts: sake /dev/tasks/' . __CLASS__); } else { $this->writeln('Delete the artefacts (IRREVERSIBLE!): sake dev/tasks/' . __CLASS__ . " '' dropping=1"); } } }
public function init() { parent::init(); $canAccess = Director::isDev() || Director::is_cli() || Permission::check("ADMIN"); if (!$canAccess) { return Security::permissionFailure($this); } }
protected function writeOut($msg) { if (Director::is_cli()) { fwrite(STDOUT, $msg . PHP_EOL); } else { echo $msg . "<br>"; } }
/** * Print a debug message. * * @param string $string * @param string $tag * @param string $style */ public static function message($string, $tag = 'p', $style = '') { if (self::$verbose) { $caller = Debug::caller(); $file = basename($caller['file']); $string = "{$file}[{$caller['line']}]: {$string}"; echo Director::is_cli()? "{$string}\n": "<{$tag} style=\"{$style}\">{$string}</{$tag}>\n"; } }
function init() { parent::init(); $canAccess = Director::isDev() || Director::is_cli() || !self::$check_permission || Permission::check(self::$check_permission); if (!$canAccess) { return Security::permissionFailure($this); } }
public function run($request) { if (isset($_GET['Types']) && (Director::is_cli() || Permission::check('ADMIN'))) { $job = new ScheduledRepublishJob(explode(',', $_GET['Types']), isset($_GET['seconds']) ? $_GET['seconds'] : 86400); $start = isset($_GET['start']) ? $_GET['start'] : date('Y-m-d 00:30:00', time() + 86400); singleton('QueuedJobService')->queueJob($job, $start); } }
/** * Init method to check permissions * * @return null */ public function init() { if (!Director::is_cli() && !Permission::check('ADMIN')) { user_error('No access allowed'); exit; } parent::init(); }
protected function init() { parent::init(); // Unless called from the command line, all CliControllers need ADMIN privileges if (!Director::is_cli() && !Permission::check("ADMIN")) { return Security::permissionFailure(); } }
/** * Gets a formatter for standard output * * @return FormatterInterface */ protected function getFormatter() { // Get formatter $format = LineFormatter::SIMPLE_FORMAT; if (!Director::is_cli()) { $format = "<p>{$format}</p>"; } return Injector::inst()->createWithArgs('Monolog\\Formatter\\LineFormatter', array($format)); }
public function message($message) { if (!self::$quiet) { if (Director::is_cli()) { $message = strip_tags($message); } echo $message; } }
public function run($request) { $message = function ($content) { print \Director::is_cli() ? "{$content}\n" : "<p>{$content}</p>"; }; $message('Defining the mappings'); $this->service->define(); $message('Refreshing the index'); $this->service->refresh(); }
public function onAfterInit() { if (isset($_GET['flush']) && $_GET['flush'] == 'all') { // Check for permissions, but do not do anything when denying. // SSViewer will handle that. if (Director::isDev() || Director::is_cli() || Permission::check('ADMIN')) { $cache = SS_Cache::factory('cacheblock'); $cache->clean(Zend_Cache::CLEANING_MODE_ALL); } } }
/** * Render or return a backtrace from the given scope. * * @param unknown_type $returnVal * @param unknown_type $ignoreAjax * @return unknown */ static function backtrace($returnVal = false, $ignoreAjax = false, $ignoredFunctions = null) { $plainText = Director::is_cli() || Director::is_ajax() && !$ignoreAjax; $result = self::get_rendered_backtrace(debug_backtrace(), $plainText, $ignoredFunctions); if ($returnVal) { return $result; } else { echo $result; } }
function init() { parent::init(); if(Director::is_cli()) { echo "Error: JSTestRunner cannot be run in CLI mode\n"; die(); } if (!self::$default_reporter) self::set_reporter('DebugView'); }