function listjobtotalsAction() { $this->view->title = $this->view->translate->_("List of Job Totals"); // do Bacula ACLs $command = 'list'; if (!$this->bacula_acl->doOneBaculaAcl($command, 'command')) { $msg = sprintf($this->view->translate->_('You try to run Bacula Console with command "%s".'), $command); $this->_forward('bacula-access-denied', 'error', null, array('msg' => $msg)); // action, controller return; } $director = new Director(); if (!$director->isFoundBconsole()) { $this->view->result_error = 'NOFOUND_BCONSOLE'; $this->render(); return; } $astatusdir = $director->execDirector(" <<EOF\nlist jobtotals\n@quit\nEOF"); $this->view->command_output = $astatusdir['command_output']; // check return status of the executed command if ($astatusdir['return_var'] != 0) { $this->view->result_error = $astatusdir['result_error']; } $this->view->meta_refresh = 300; // meta http-equiv="refresh" }
function statusClientIdAction() { // http://localhost/webacula/client/status-client-id/id/1/name/local.fd $client_name = $this->_getParam('name'); $this->view->title = $this->view->translate->_("Client") . " " . $client_name; // do Bacula ACLs $command = 'status'; if (!$this->bacula_acl->doOneBaculaAcl($command, 'command')) { $msg = sprintf($this->view->translate->_('You try to run Bacula Console with command "%s".'), $command); $this->_forward('bacula-access-denied', 'error', null, array('msg' => $msg)); // action, controller return; } $director = new Director(); if (!$director->isFoundBconsole()) { $this->view->result_error = 'NOFOUND_BCONSOLE'; $this->render(); return; } $astatusdir = $director->execDirector(" <<EOF\nstatus client=\"{$client_name}\"\n.\n@quit\nEOF"); $this->view->command_output = $astatusdir['command_output']; // check return status of the executed command if ($astatusdir['return_var'] != 0) { $this->view->result_error = $astatusdir['result_error']; } $this->view->meta_refresh = 300; // meta http-equiv="refresh" }
function cmdAction() { $bcommand = addslashes(trim($this->_request->getPost('bcommand'))); $this->view->bcommand = $bcommand; if ($this->_helper->hasHelper('layout')) { $this->_helper->layout->disableLayout(); // disable layouts } list($cmd) = explode(' ', $bcommand); // do Bacula ACLs if (!$this->bacula_acl->doOneBaculaAcl($cmd, 'command')) { $this->view->msg = sprintf($this->view->translate->_('You try to run Bacula Console with command "%s".'), $cmd) . '<br><b>Bacula ACLs : ' . $this->view->translate->_('Access denied.') . '</b><br>'; $this->render(); return; } $director = new Director(); if (!$director->isFoundBconsole()) { $this->view->msg = '<b>' . $this->view->translate->_('ERROR: bconsole not found.') . '</b><br>'; $this->render(); return; } $astatusdir = $director->execDirector("<<EOF\n{$bcommand}\n@quit\nEOF"); $this->view->command_output = $astatusdir['command_output']; // check return status of the executed command $this->view->return_var = $astatusdir['return_var']; }
public function testBuilder() { $expect = "<header>Header</header>\n" + "<article>Content</article>\n" + "<footer>Footer</footer>\n"; $product = new Product(); $director = new Director(new ConcreteBuilder($product)); $director->construct(); $result = $product->show(); $this->assertEquals($result, $expect); }
public static function main() { $builder = new ConcreteBuilder(); $director = new Director($builder); $product = $director->getProduct(); $product->show(); $builder = null; $director = null; $product = null; }
public static function photo($reference, $maxWidth = 0) { if ((int) $maxWidth === 0) { $maxWidth = \App\Lib\Api\GooglePlace\Config::radius(); } $photoBuilder = new BuilderPhoto(); $photoBuilder->setupMaxWidth($maxWidth); $photoBuilder->setupPhotoReference($reference); $photoBuilder->setupDataType(); $director = new Director($photoBuilder); $director->construct(); $request = $director->getResult(); $response = $request->send(); return $response; }
/** * @uses ModelAsController::getNestedController() * @param SS_HTTPRequest $request * @param DataModel $model * @return SS_HTTPResponse */ public function handleRequest(SS_HTTPRequest $request, DataModel $model) { $this->setRequest($request); $this->setDataModel($model); $this->pushCurrent(); // Create a response just in case init() decides to redirect $this->response = new SS_HTTPResponse(); $this->init(); // If we had a redirection or something, halt processing. if ($this->response->isFinished()) { $this->popCurrent(); return $this->response; } // If the database has not yet been created, redirect to the build page. if (!DB::is_active() || !ClassInfo::hasTable('SiteTree')) { $this->response->redirect(Director::absoluteBaseURL() . 'dev/build?returnURL=' . (isset($_GET['url']) ? urlencode($_GET['url']) : null)); $this->popCurrent(); return $this->response; } try { $result = $this->getNestedController(); if ($result instanceof RequestHandler) { $result = $result->handleRequest($this->getRequest(), $model); } else { if (!$result instanceof SS_HTTPResponse) { user_error("ModelAsController::getNestedController() returned bad object type '" . get_class($result) . "'", E_USER_WARNING); } } } catch (SS_HTTPResponse_Exception $responseException) { $result = $responseException->getResponse(); } $this->popCurrent(); return $result; }
public function testFindLink() { $this->checkoutpage = $this->objFromFixture('CheckoutPage', 'checkout'); $this->checkoutpage->publish('Stage', 'Live'); $link = CheckoutPage::find_link(); $this->assertEquals(Director::baseURL() . 'checkout/', $link, 'find_link() returns the correct link to checkout.'); }
/** * 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; } }
/** * Form action handler for ContactInquiryForm. * * @param array $data The form request data submitted * @param Form $form The {@link Form} this was submitted on */ function dosave(array $data, Form $form, SS_HTTPRequest $request) { $SQLData = Convert::raw2sql($data); $attrs = $form->getAttributes(); if ($SQLData['Comment'] != '' || $SQLData['Url'] != '') { // most probably spam - terminate silently Director::redirect(Director::baseURL() . $this->URLSegment . "/success"); return; } $item = new ContactInquiry(); $form->saveInto($item); // $form->sessionMessage(_t("ContactPage.FORMMESSAGEGOOD", "Your inquiry has been submitted. Thanks!"), 'good'); $item->write(); $mailFrom = $this->currController->MailFrom ? $this->currController->MailFrom : $SQLData['Email']; $mailTo = $this->currController->MailTo ? $this->currController->MailTo : Email::getAdminEmail(); $mailSubject = $this->currController->MailSubject ? $this->currController->MailSubject . ' - ' . $SQLData['Ref'] : _t('ContactPage.SUBJECT', '[web] New contact inquiry - ') . ' ' . $data['Ref']; $email = new Email($mailFrom, $mailTo, $mailSubject); $email->replyTo($SQLData['Email']); $email->setTemplate("ContactInquiry"); $email->populateTemplate($SQLData); $email->send(); // $this->controller->redirectBack(); if ($email->send()) { $this->controller->redirect($this->controller->Link() . "success"); } else { $this->controller->redirect($this->controller->Link() . "error"); } return false; }
function testGetTagWithoutTitleContainingDots() { $image = $this->objFromFixture('Image', 'imageWithoutTitleContainingDots'); $expected = '<img src="' . Director::baseUrl() . 'assets/ImageTest/test.image.with.dots.png" alt="test.image.with.dots" />'; $actual = $image->getTag(); $this->assertEquals($expected, $actual); }
/** * @param array $properties * * @return string - HTML */ public function FieldHolder($properties = array()) { $moduleDir = substr(Director::makeRelative(dirname(dirname(dirname(__FILE__)))), 1); Requirements::css($moduleDir . '/css/WidgetAreaEditor.css'); Requirements::javascript($moduleDir . '/javascript/WidgetAreaEditor.js'); return $this->renderWith("WidgetAreaEditor"); }
/** * @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]"); } } }
public function onBeforeInit() { $host = GlobalNavSiteTreeExtension::get_toolbar_hostname(); if ((isset($_REQUEST['regenerate_nav']) || isset($_REQUEST['flush'])) && $host == Director::protocolAndHost() && (Permission::check('ADMIN') || Director::isDev())) { GlobalNavSiteTreeExtension::create_static_navs(); } }
function submitPoll($data, $form) { $choiceIDs = is_array($data['PollChoices']) ? $data['PollChoices'] : array($data['PollChoices']); $choicesIDs = implode(',', $choiceIDs); $choices = DataObject::get('PollChoice', sprintf('"ID" IN (%s)', $choicesIDs)); if ($choices) { foreach ($choices as $choice) { $choice->addVote(); } $form->poll->markAsVoted(); } // Redirect back to anchor (partly copied from Director::redirectBack) if (self::$redirect_to_anchor) { if ($this->request->requestVar('_REDIRECT_BACK_URL')) { $url = $this->request->requestVar('_REDIRECT_BACK_URL'); } else { if ($this->request->getHeader('Referer')) { $url = $this->request->getHeader('Referer'); } else { $url = Director::baseURL(); } } $url .= '#' . self::$redirect_to_anchor . '-' . $this->poll->ID; $this->controller->redirect($url); } else { $this->controller->redirectBack(); } }
/** * @todo fix this BIG mess. */ public static function postFacebook($message, $link = null, $impression = null) { $member = Member::currentUser(); $postresult = false; $SiteConfig = SiteConfig::current_site_config(); if ($member && $SiteConfig->FBAppID && $SiteConfig->FBSecret) { if ($link == null) { $link = Director::absoluteBaseURL(); } $page = '/' . $SiteConfig->FBPageID . '/feed'; $facebook = new Facebook(array('appId' => $SiteConfig->FBAppID, 'secret' => $SiteConfig->FBSecret)); $token = $facebook->api('/me/accounts'); foreach ($token['data'] as $pages) { if ($pages['id'] == $SiteConfig->FBPageID) { $facebook->setAccessToken($pages['access_token']); $verified = true; break; } } if ($verified) { $data = array('message' => $message, 'link' => $link, 'picture' => $impression); $postresult = $facebook->api($page, 'post', $data); } } return $postresult; }
/** * Process all incoming requests passed to this controller, checking * that the file exists and passing the file through if possible. */ public function handleRequest(SS_HTTPRequest $request, DataModel $model) { // Copied from Controller::handleRequest() $this->pushCurrent(); $this->urlParams = $request->allParams(); $this->request = $request; $this->response = new SS_HTTPResponse(); $this->setDataModel($model); $url = array_key_exists('url', $_GET) ? $_GET['url'] : $_SERVER['REQUEST_URI']; // remove any relative base URL and prefixed slash that get appended to the file path // e.g. /mysite/assets/test.txt should become assets/test.txt to match the Filename field on File record $url = Director::makeRelative(ltrim(str_replace(BASE_URL, '', $url), '/')); $file = File::find($url); if ($this->canDownloadFile($file)) { // If we're trying to access a resampled image. if (preg_match('/_resampled\\/[^-]+-/', $url)) { // File::find() will always return the original image, but we still want to serve the resampled version. $file = new Image(); $file->Filename = $url; } $this->extend('onBeforeSendFile', $file); return $this->sendFile($file); } else { if ($file instanceof File) { // Permission failure Security::permissionFailure($this, 'You are not authorised to access this resource. Please log in.'); } else { // File doesn't exist $this->response = new SS_HTTPResponse('File Not Found', 404); } } return $this->response; }
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); }
/** * It's preferable to use this as an access point in case we * add support for multiple property id's in the future (subsites for example) * @return string */ public static function get_property_id() { if (self::config()->disable_on_dev && !Director::isLive()) { return ''; } return self::config()->web_property_id; }
public function WebpackDevServer() { if (Director::isDev()) { $socket = @fsockopen('localhost', 3000, $errno, $errstr, 1); return !$socket ? false : true; } }
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 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'); }
function init() { if (!Director::is_cli() && !Director::isDev() && !Permission::check("ADMIN")) { Security::permissionFailure(); } parent::init(); }
public function preRequest(SS_HTTPRequest $request, Session $session, DataModel $model) { if (!$this->testSessionEnvironment->isRunningTests()) { return; } $testState = $this->testSessionEnvironment->getState(); // Date and time if (isset($testState->datetime)) { SS_Datetime::set_mock_now($testState->datetime); } // Register mailer if (isset($testState->mailer)) { $mailer = $testState->mailer; Email::set_mailer(new $mailer()); Config::inst()->update("Email", "send_all_emails_to", null); } // Allows inclusion of a PHP file, usually with procedural commands // to set up required test state. The file can be generated // through {@link TestSessionStubCodeWriter}, and the session state // set through {@link TestSessionController->set()} and the // 'testsession.stubfile' state parameter. if (isset($testState->stubfile)) { $file = $testState->stubfile; if (!Director::isLive() && $file && file_exists($file)) { // Connect to the database so the included code can interact with it global $databaseConfig; if ($databaseConfig) { DB::connect($databaseConfig); } include_once $file; } } }
function init() { parent::init(); $this->securityToken = new SecurityToken(); Requirements::css('news/code/ui/frontend/css/news.css'); Requirements::css(Director::protocol() . '://maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css'); }
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 . ' }); }); '); } }
/** * @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(); }
function Link($action = null) { if ($this->customLink) { return Director::baseURL() . 'ObjectSelectorField_Controller/find/?sourceObject=' . $this->sourceObject . '&displayField=' . $this->getDisplayFieldOptions() . '&multi=' . $this->hasMultiSortOptions(); } return parent::Link($action); }
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()); }
/** * Taken from MemberLoginForm::__construct with minor changes */ public function __construct($controller, $name, $fields = null, $actions = null, $checkCurrentUser = true) { $customCSS = project() . '/css/member_login.css'; if (Director::fileExists($customCSS)) { Requirements::css($customCSS); } if (isset($_REQUEST['BackURL'])) { $backURL = $_REQUEST['BackURL']; } else { $backURL = Session::get('BackURL'); } if ($checkCurrentUser && Member::currentUser() && Member::logged_in_session_exists()) { $fields = new FieldList(new HiddenField("AuthenticationMethod", null, $this->authenticator_class, $this)); $actions = new FieldList(new FormAction("logout", _t('Member.BUTTONLOGINOTHER', "Log in as someone else"))); } else { if (!$fields) { $fields = new FieldList(new HiddenField("AuthenticationMethod", null, $this->authenticator_class, $this)); } if (!$actions) { $actions = new FieldList(new FormAction('dologin', _t('GoogleAuthenticator.BUTTONLOGIN', "Log in with Google"))); } } if (isset($backURL)) { $fields->push(new HiddenField('BackURL', 'BackURL', $backURL)); } // Allow GET method for callback $this->setFormMethod('GET', true); parent::__construct($controller, $name, $fields, $actions); }