/** * @return void */ public function testInvalidMap() { $this->setExpectedException('Exception'); $handler = new Convert('[dummy]'); $record = $this->getMock('Migration\\ResourceModel\\Record', [], [], '', false); $record2 = $this->getMockBuilder('Migration\\ResourceModel\\Record')->disableOriginalConstructor()->getMock(); $handler->handle($record, $record2, 'dummy'); }
public function AddCompanyStatus($arg = false) { $model = $this->model; $arrayobject = $model->AddCompanyStatus($arg); $ObjectDTO = new Convert(); $companies = $ObjectDTO->toObject($arrayobject); $this->View->msg = $companies; $this->View->render('places_Ive_searched/index'); }
public function doUpload() { $id = $_POST['id']; $duration = $_POST['duration']; $sn = $_POST['sn']; $isLast = $_POST['last']; $mysql = new DbMysql(); $dashfile = new DashFile($id, $sn); $convert = new Convert($dashfile); if ($isLast == 1) { if (!$mysql->connect()) { return "ERROR: Sql server connect error!\n"; } if (!$mysql->updateStatus($id, '1')) { return "ERROR: Sql INSERT error\n"; } $segCount = $mysql->geSgmsCount($id); $dpl = new DashPlaylist($dashfile); $dpl->generateMPD($duration, 0, $segCount); $dpl->generateM3U8($segCount); $mysql->close(); } else { if (!$dashfile->isValid()) { return "ERROR: File is invalid!\n"; } if ($dashfile->saveFile()) { if (!$mysql->connect()) { return "ERROR: Sql server connect error!\n"; } if ($sn == 0) { $mysql->insertNewVideo($id, $sn, $id, $duration); } else { $mysql->updateNumSegs($id, $sn); } $mysql->close(); } else { return "ERROR: File save error!\n"; } if ($convert->doConvert()) { if (!$mysql->connect()) { return "ERROR: Sql server connect error!\n"; } if (!$mysql->updateNumConverted($id, $sn)) { return "ERROR: Sql UPDATE error\n"; } $mysql->close(); } $start = $sn - 1; //if ($sn >= 3) { // $start = $sn - 2; //} $dpl = new DashPlaylist($dashfile); $dpl->generateMPD($duration, $start, $sn); } return "SUCCESS"; }
public function curl_func() { $data = $_POST; //Set destination URL $url = "http://localhost/SwipeContest/index.php/Welcome"; $tst = new Convert(); $result = $tst->cURLSnippet($url, $data); print_r($result); echo "POST data forwarded via cURL to " . $url; }
protected function formatValue($record, $source, $info) { // Field sources //if(is_string($source)) { $val = Convert::raw2xml($record->{$source}); //} else { // $val = $record->val($source[0], $source[1]); //} // Casting, a la TableListField. We're deep-calling a helper method on TableListField that // should probably be pushed elsewhere... if (!empty($info['casting'])) { $val = TableListField::getCastedValue($val, $info['casting']); } // Formatting, a la TableListField if (!empty($info['formatting'])) { $format = str_replace('$value', "__VAL__", $info['formatting']); $format = preg_replace('/\\$([A-Za-z0-9-_]+)/', '$record->$1', $format); $format = str_replace('__VAL__', '$val', $format); $val = eval('return "' . $format . '";'); } $prefix = empty($info['newline']) ? "" : "<br>"; $classClause = ""; if (isset($info['title'])) { $cssClass = preg_replace('/[^A-Za-z0-9]+/', '', $info['title']); $classClause = "class=\"{$cssClass}\""; } if (isset($info['link']) && $info['link']) { $link = $info['link'] === true && $record->hasMethod('CMSEditLink') ? $record->CMSEditLink() : $info['link']; return $prefix . "<a {$classClause} href=\"{$link}\">{$val}</a>"; } else { return $prefix . "<span {$classClause}>{$val}</span>"; } }
public function load($request) { $response = new SS_HTTPResponse(); $response->addHeader('Content-Type', 'application/json'); $response->setBody(Convert::array2json(call_user_func($this->source, $request->getVar('val')))); return $response; }
public function Field($properties = array()) { $content = ''; Requirements::javascript(FRAMEWORK_DIR . '/thirdparty/jquery/jquery.js'); Requirements::javascript(FRAMEWORK_DIR . "/javascript/ToggleField.js"); if ($this->startClosed) { $this->addExtraClass('startClosed'); } $valforInput = $this->value ? Convert::raw2att($this->value) : ""; $rawInput = Convert::html2raw($valforInput); if ($this->charNum) { $reducedVal = substr($rawInput, 0, $this->charNum); } else { $reducedVal = DBField::create_field('Text', $rawInput)->{$this->truncateMethod}(); } // only create togglefield if the truncated content is shorter if (strlen($reducedVal) < strlen($rawInput)) { $content = <<<HTML \t\t\t<div class="readonly typography contentLess" style="display: none"> \t\t\t\t{$reducedVal} \t\t\t\t <a href="#" class="triggerMore">{$this->labelMore}</a> \t\t\t</div> \t\t\t<div class="readonly typography contentMore"> \t\t\t\t{$this->value} \t\t\t\t <a href="#" class="triggerLess">{$this->labelLess}</a> \t\t\t</div>\t \t\t\t<br /> \t\t\t<input type="hidden" name="{$this->name}" value="{$valforInput}" /> HTML; } else { $this->dontEscape = true; $content = parent::Field(); } return $content; }
function Field() { $XML_title = $this->allowHTML ? $this->title : Convert::raw2xml($this->title); // extraclass $XML_class = $this->extraClass() ? " class=\"{$this->extraClass()}\"" : ''; return "<h{$this->headingLevel}{$XML_class}>{$XML_title}</h{$this->headingLevel}>"; }
/** * Send email to subscribers, notifying them the thread has been created or post added. */ public function notifySubscribers() { // all members id except current user $member_id = Member::currentUserID(); $list = DataObject::get("Forum_Subscribers", "\"ForumID\" = '" . $this->owner->ForumID . "' AND \"MemberID\" != '{$member_id}'"); if ($list) { foreach ($list as $obj) { $SQL_id = Convert::raw2sql((int) $obj->MemberID); // Get the members details $member = DataObject::get_one("Member", "\"Member\".\"ID\" = '{$SQL_id}'"); if ($member) { //error_log("email sent ".$member->Email); $type = $obj->Type; switch ($type) { // send all email notification case 'all': $this->createEmail($member); break; // send new thread only email notification // send new thread only email notification case 'thread': //if($this->owner->isFirstPost()){ $this->createEmail($member); //} break; // // default: break; } } } } }
/** * The process to automatically construct data object output configurations, executed on project build. */ public function requireDefaultRecords() { parent::requireDefaultRecords(); // Grab the list of data objects that have been completely removed. foreach (DB::getConn()->tableList() as $table) { // Delete existing output configurations for these data objects. if (!class_exists($table)) { $existing = DataObjectOutputConfiguration::get_one('DataObjectOutputConfiguration', "IsFor = '" . Convert::raw2sql($table) . "'"); $this->deleteConfiguration($table, $existing); } } // Grab the list of all data object types, along with any inclusions/exclusions defined. $objects = ClassInfo::subclassesFor('DataObject'); $inclusions = self::$custom_inclusions; $exclusions = array_unique(array_merge(self::$exclusions, self::$custom_exclusions)); // Check existing output configurations for these data objects. foreach ($objects as $object) { $existing = DataObjectOutputConfiguration::get_one('DataObjectOutputConfiguration', "IsFor = '" . Convert::raw2sql($object) . "'"); // Delete existing output configurations for invalid data objects, or for those excluded. if ($existing && (self::$disabled || get_parent_class($object) !== 'DataObject' || ClassInfo::classImplements($object, 'TestOnly') || count($inclusions) > 0 && !in_array($object, $inclusions) || count($inclusions) === 0 && in_array($object, $exclusions))) { $this->deleteConfiguration($object, $existing); } else { if (!$existing && !self::$disabled && get_parent_class($object) === 'DataObject' && !ClassInfo::classImplements($object, 'TestOnly') && (count($inclusions) > 0 && in_array($object, $inclusions) || count($inclusions) === 0 && !in_array($object, $exclusions))) { $this->addConfiguration($object); } } } }
/** * Handles form submission * @param array $data * @return bool|\SS_HTTPResponse */ public function addtocart(array $data) { $groupedProduct = $this->getController()->data(); if (empty($data) || empty($data['Product']) || !is_array($data['Product'])) { $this->sessionMessage(_t('GroupedCartForm.EMPTY', 'Please select at least one product.'), 'bad'); $this->extend('updateErrorResponse', $this->request, $response, $groupedProduct, $data, $this); return $response ? $response : $this->controller->redirectBack(); } $cart = ShoppingCart::singleton(); foreach ($data['Product'] as $id => $prodReq) { if (!empty($prodReq['Quantity']) && $prodReq['Quantity'] > 0) { $prod = Product::get()->byID($id); if ($prod && $prod->exists()) { $saveabledata = !empty($this->saveablefields) ? Convert::raw2sql(array_intersect_key($data, array_combine($this->saveablefields, $this->saveablefields))) : $prodReq; $buyable = $prod; if (isset($prodReq['Attributes'])) { $buyable = $prod->getVariationByAttributes($prodReq['Attributes']); if (!$buyable || !$buyable->exists()) { $this->sessionMessage("{$prod->InternalItemID} is not available with the selected options.", "bad"); $this->extend('updateErrorResponse', $this->request, $response, $groupedProduct, $data, $this); return $response ? $response : $this->controller->redirectBack(); } } if (!$cart->add($buyable, (int) $prodReq['Quantity'], $saveabledata)) { $this->sessionMessage($cart->getMessage(), $cart->getMessageType()); $this->extend('updateErrorResponse', $this->request, $response, $groupedProduct, $data, $this); return $response ? $response : $this->controller->redirectBack(); } } } } $this->extend('updateGroupCartResponse', $this->request, $response, $groupedProduct, $data, $this); return $response ? $response : ShoppingCart_Controller::direct($cart->getMessageType()); }
public function perform() { set_time_limit(0); $log = new DeploynautLogFile($this->args['logfile']); $projects = DNProject::get()->filter('Name', Convert::raw2sql($this->args['projectName'])); $project = $projects->first(); $path = $project->getLocalCVSPath(); $env = $this->args['env']; $log->write('Starting git fetch for project "' . $project->Name . '"'); // if an alternate user has been configured for clone, run the command as that user // @todo Gitonomy doesn't seem to have any way to prefix the command properly, if you // set 'sudo -u composer git' as the "command" parameter, it tries to run the whole // thing as a single command and fails $user = DNData::inst()->getGitUser(); if (!empty($user)) { $command = sprintf('cd %s && sudo -u %s git fetch -p origin +refs/heads/*:refs/heads/* --tags', $path, $user); $process = new \Symfony\Component\Process\Process($command); $process->setEnv($env); $process->setTimeout(3600); $process->run(); if (!$process->isSuccessful()) { throw new RuntimeException($process->getErrorOutput()); } } else { $repository = new Gitonomy\Git\Repository($path, array('environment_variables' => $env)); $repository->run('fetch', array('-p', 'origin', '+refs/heads/*:refs/heads/*', '--tags')); } $log->write('Git fetch is finished'); }
/** * 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; }
public function load($request) { $response = new SS_HTTPResponse(); $response->addHeader('Content-Type', 'application/json'); $response->setBody(Convert::array2json(array("_memberID" => Member::currentUserID()))); return $response; }
/** * Return the title, description, keywords and language metatags. * * @todo Move <title> tag in separate getter for easier customization and more obvious usage * * @param boolean|string $includeTitle Show default <title>-tag, set to false for custom templating * @return string The XHTML metatags */ public function MetaTags($includeTitle = true) { $tags = ""; if ($includeTitle === true || $includeTitle == 'true') { $tags .= "<title>" . Convert::raw2xml($this->Title) . "</title>\n"; } $generator = trim(Config::inst()->get('SiteTree', 'meta_generator')); if (!empty($generator)) { $tags .= "<meta name=\"generator\" content=\"" . Convert::raw2att($generator) . "\" />\n"; } $charset = Config::inst()->get('ContentNegotiator', 'encoding'); $tags .= "<meta http-equiv=\"Content-type\" content=\"text/html; charset={$charset}\" />\n"; if ($this->MetaDescription) { $tags .= "<meta name=\"description\" content=\"" . Convert::raw2att($this->MetaDescription) . "\" />\n"; } if ($this->ExtraMeta) { $tags .= $this->ExtraMeta . "\n"; } if (Permission::check('CMS_ACCESS_CMSMain') && in_array('CMSPreviewable', class_implements($this)) && !$this instanceof ErrorPage) { $tags .= "<meta name=\"x-page-id\" content=\"{$this->ID}\" />\n"; $tags .= "<meta name=\"x-cms-edit-link\" content=\"" . $this->CMSEditLink() . "\" />\n"; } $this->extend('MetaTags', $tags); return $tags; }
function Presentations() { $Speaker = NULL; if (isset($_GET['key'])) { $key = Convert::raw2sql($_GET['key']); $username = SchedSpeaker::HashToUsername($key); $Speaker = SchedSpeaker::get()->filter('username', $username)->first(); } elseif ($speakerID = Session::get('UploadMedia.SpeakerID')) { $Speaker = SchedSpeaker::get()->byID($speakerID); } // Speaker not found if (!$Speaker) { return $this->httpError(404, 'Sorry, that does not appear to be a valid token.'); } Session::set('UploadMedia.SpeakerID', $Speaker->ID); $Presentations = $Speaker->PresentationsForThisSpeaker(); // No presentations if (!$Presentations) { return $this->httpError(404, 'Sorry, it does not appear that you have any presentations.'); } // IF there's only one presentation with no media, go ahead and forward to it's page if ($Presentations->count() == 1 && !$Presentations->first()->UploadedMedia()) { $PresentationID = $Presentations->first()->ID; $this->redirect($this->link() . 'Upload/' . $PresentationID); return; } $data["Speaker"] = $Speaker; $data["Presentations"] = $Presentations; return $this->Customise($data); }
/** * @todo Test the results of a publication better */ function testPublish() { $page1 = $this->objFromFixture('Page', "page1"); $page2 = $this->objFromFixture('Page', "page2"); $this->session()->inst_set('loggedInAs', $this->idFromFixture('Member', 'admin')); $response = $this->get("admin/cms/publishall?confirm=1"); $this->assertContains(sprintf(_t('CMSMain.PUBPAGES', "Done: Published %d pages"), 30), $response->getBody()); // Some modules (e.g., cmsworkflow) will remove this action if (isset(CMSBatchActionHandler::$batch_actions['publish'])) { $response = Director::test("admin/cms/batchactions/publish", array('csvIDs' => implode(',', array($page1->ID, $page2->ID)), 'ajax' => 1), $this->session()); $responseData = Convert::json2array($response->getBody()); $this->assertTrue(property_exists($responseData['modified'], $page1->ID)); $this->assertTrue(property_exists($responseData['modified'], $page2->ID)); } // Get the latest version of the redirector page $pageID = $this->idFromFixture('RedirectorPage', 'page5'); $latestID = DB::query('select max("Version") from "RedirectorPage_versions" where "RecordID"=' . $pageID)->value(); $dsCount = DB::query('select count("Version") from "RedirectorPage_versions" where "RecordID"=' . $pageID . ' and "Version"=' . $latestID)->value(); $this->assertEquals(1, $dsCount, "Published page has no duplicate version records: it has " . $dsCount . " for version " . $latestID); $this->session()->clear('loggedInAs'); //$this->assertRegexp('/Done: Published 4 pages/', $response->getBody()) /* $response = Director::test("admin/publishitems", array( 'ID' => '' 'Title' => '' 'action_publish' => 'Save and publish', ), $session); $this->assertRegexp('/Done: Published 4 pages/', $response->getBody()) */ }
/** * @param IQuerySpecification $specification * @return IQueryResult */ public function handle(IQuerySpecification $specification) { $params = $specification->getSpecificationParams(); $current_date = @$params['name_pattern']; $date_filter = ""; if ($current_date) { $current_date = Convert::raw2sql($current_date); $date_filter = "AND (\n (\n (DATE('{$current_date}') < TrainingCourseScheduleTime.EndDate)\n OR\n (TrainingCourse.Online=1 AND TrainingCourseScheduleTime.StartDate IS NULL AND TrainingCourseScheduleTime.EndDate IS NULL)\n )\n )"; } $sql = <<<SQL SELECT C.Name AS CompanyName FROM TrainingCourse INNER JOIN CompanyService ON CompanyService.ID = TrainingCourse.TrainingServiceID AND CompanyService.ClassName='TrainingService' INNER JOIN Company C on C.ID = CompanyService.CompanyID INNER JOIN TrainingCourseSchedule ON TrainingCourseSchedule.CourseID = TrainingCourse.ID LEFT JOIN TrainingCourseScheduleTime ON TrainingCourseScheduleTime.LocationID = TrainingCourseSchedule.ID WHERE CompanyService.Active = 1 {$date_filter} GROUP BY C.Name ORDER BY C.Name ASC; SQL; $results = DB::query($sql); $companies = array(); for ($i = 0; $i < $results->numRecords(); $i++) { $record = $results->nextRecord(); $company = $record['CompanyName']; $value = sprintf('%s', $company); array_push($companies, new SearchDTO($value, $value)); } return new OpenStackImplementationNamesQueryResult($companies); }
function FieldHolder() { $config = array('datetimeorder' => $this->getConfig('datetimeorder')); $config = array_filter($config); $this->addExtraClass(Convert::raw2json($config)); return parent::FieldHolder(); }
/** * Get the full form (e.g. /home/) relative link to the home page for the current HTTP_HOST value. Note that the * link is trimmed of leading and trailing slashes before returning to ensure consistency. * * @return string */ public static function get_homepage_link() { if (!self::$cached_homepage_link) { // TODO Move to 'homepagefordomain' module if (class_exists('HomepageForDomainExtension')) { $host = str_replace('www.', null, $_SERVER['HTTP_HOST']); $SQL_host = Convert::raw2sql($host); $candidates = DataObject::get('SiteTree', "\"HomepageForDomain\" LIKE '%{$SQL_host}%'"); if ($candidates) { foreach ($candidates as $candidate) { if (preg_match('/(,|^) *' . preg_quote($host) . ' *(,|$)/', $candidate->HomepageForDomain)) { self::$cached_homepage_link = trim($candidate->RelativeLink(true), '/'); } } } } if (!self::$cached_homepage_link) { // TODO Move to 'translatable' module if (class_exists('Translatable') && Object::has_extension('SiteTree', 'Translatable') && ($link = Translatable::get_homepage_link_by_locale(Translatable::get_current_locale()))) { self::$cached_homepage_link = $link; } else { self::$cached_homepage_link = self::get_default_homepage_link(); } } } return self::$cached_homepage_link; }
function Field($properties = array()) { $options = ''; $odd = 0; $source = $this->getSource(); foreach ($source as $key => $value) { // convert the ID to an HTML safe value (dots are not replaced, as they are valid in an ID attribute) $itemID = $this->id() . '_' . preg_replace('/[^\\.a-zA-Z0-9\\-\\_]/', '_', $key); if ($key == $this->value) { $useValue = false; $checked = " checked=\"checked\""; } else { $checked = ""; } $odd = ($odd + 1) % 2; $extraClass = $odd ? "odd" : "even"; $extraClass .= " val" . preg_replace('/[^a-zA-Z0-9\\-\\_]/', '_', $key); $disabled = $this->disabled || in_array($key, $this->disabledItems) ? "disabled=\"disabled\"" : ""; $ATT_key = Convert::raw2att($key); $options .= "<li class=\"" . $extraClass . "\"><input id=\"{$itemID}\" name=\"{$this->name}\" type=\"radio\" value=\"{$key}\"{$checked} {$disabled} class=\"radio\" /> <label title=\"{$ATT_key}\" for=\"{$itemID}\">{$value}</label></li>\n"; } // Add "custom" input field $value = $this->value && !array_key_exists($this->value, $this->source) ? $this->value : null; $checked = $value ? " checked=\"checked\"" : ''; $options .= "<li class=\"valCustom\">" . sprintf("<input id=\"%s_custom\" name=\"%s\" type=\"radio\" value=\"__custom__\" class=\"radio\" %s />", $itemID, $this->name, $checked) . sprintf('<label for="%s_custom">%s:</label>', $itemID, _t('MemberDatetimeOptionsetField.Custom', 'Custom')) . sprintf("<input class=\"customFormat\" name=\"%s_custom\" value=\"%s\" />\n", $this->name, $value) . sprintf("<input type=\"hidden\" class=\"formatValidationURL\" value=\"%s\" />", $this->Link() . '/validate'); $options .= $value ? sprintf('<span class="preview">(%s: "%s")</span>', _t('MemberDatetimeOptionsetField.Preview', 'Preview'), Zend_Date::now()->toString($value)) : ''; $options .= sprintf('<a class="cms-help-toggle" href="#%s">%s</a>', $this->id() . '_Help', _t('MemberDatetimeOptionsetField.TOGGLEHELP', 'Toggle formatting help')); $options .= "<div id=\"" . $this->id() . "_Help\">"; $options .= $this->getFormattingHelpText(); $options .= "</div>"; $options .= "</li>\n"; $id = $this->id(); return "<ul id=\"{$id}\" class=\"optionset {$this->extraClass()}\">\n{$options}</ul>\n"; }
/** * Generate an list of items that will be loaded into the custom menu * * @param $menu template slug for retriving a menu * @return ArrayList */ public function CustomMenu($menu = "") { $menu_items = new ArrayList(); if (isset($menu)) { // Ensure argument is safe for database $menu = Convert::raw2sql($menu); $filter = array('Slug' => $menu); if ($menu = CustomMenuHolder::get()->filter($filter)->first()) { // If a custom order is set, use it if ($menu->Order) { $order = explode(',', $menu->Order); } if (isset($order) && is_array($order) && count($order) > 0) { foreach ($order as $item) { $menu_items->push($menu->Pages()->find('ID', $item)); } } else { foreach ($menu->Pages() as $item) { $menu_items->push($item); } } } } return $menu_items; }
/** * Displays a random image with colorbox effect from a given assets subfolder * Uses template "csoft-shortcode/templates/Includes/RandomImage.ss" for output * * @param mixed $arguments (folder='subfolder_in_assets' align='left|right') * @param $content = null * @param $parser = null * @return processed template RandomImage.ss */ public static function cwsShortCodeRandomImageHandler($arguments, $content = null, $parser = null) { // only proceed if subfolder was defined if (!isset($arguments['folder'])) { return; } // sanitize user inputs $folder = Convert::raw2sql($arguments['folder']); $align = isset($arguments['align']) ? strtolower(Convert::raw2xml($arguments['align'])) : ''; // fetch all images in random order from the user defined folder $folder = Folder::get()->filter('Filename', "assets/{$folder}/")->First(); $randomImage = $folder ? Image::get()->filter('ParentID', $folder->ID)->sort('RAND()') : false; // exit if user defined folder does not contain any image if (!$randomImage) { return; } // extract image caption from image filename $caption = $randomImage->Title; if (preg_match('#(\\d*-)?(.+)\\.(jpg|gif|png)#i', $caption, $matches)) { $caption = ucfirst(str_replace('-', ' ', $matches[2])); } // prepare data for output $data = array('RandomImage' => $randomImage->First(), 'Alignment' => $align, 'Caption' => $caption); // load template and process data $template = new SSViewer('RandomImage'); return $template->process(new ArrayData($data)); }
/** * Method that turns this object into a field type, to be loaded into a form * * @return FormField */ public function Field() { if ($this->Title && $this->DisplayAs) { $name = "customise_{$this->ID}_" . Convert::raw2url($this->Title); $title = $this->Required ? $this->Title . ' *' : $this->Title; $options = $this->Options()->map('Title', 'ItemSummary'); $defaults = $this->DefaultOptions(); $default = $defaults->exists() ? $defaults->first()->Title : null; switch ($this->DisplayAs) { case 'Dropdown': $field = DropdownField::create($name, $title, $options, $default)->setEmptyString(_t('Commerce.PleaseSelect', 'Please Select'))->setAttribute("class", "dropdown btn"); break; case 'Radio': $field = OptionSetField::create($name, $title, $options, $default); break; case 'Checkboxes': $field = CheckboxSetField::create($name, $title, $options, $defaults->column('ID')); break; case 'TextEntry': $field = TextField::create($name, $title); if ($this->MaxLength) { $field->setMaxLength($this->MaxLength); } break; } $this->extend('updateField', $field); return $field; } else { return false; } }
/** * @param $data * @param $form * @return bool|SS_HTTPResponse|void * @throws ValidationException * @throws null */ public function Save($data, $form) { /** @var Form $form */ $data = $form->getData(); if ($CurrentMember = Member::currentUser()) { if ($member = DataObject::get_one('Member', "Email = '" . Convert::raw2sql($data['Email']) . "' AND ID != " . $CurrentMember->ID)) { $form->addErrorMessage('Email', 'Sorry, that Email already exists.', 'validation'); return $this->controller->redirectBack(); } else { /** If no password don't save the field */ if (!isset($data['password'])) { unset($data['password']); } $this->controller->setFlash('Your profile has been updated', 'success'); $form->saveInto($CurrentMember); $CurrentMember->write(); return $this->controller->redirect($this->controller->Link()); } } else { /** Get registration page otherwise display warning. * * @var RegistrationPage $registerPage */ if ($registerPage = DataObject::get_one('RegistrationPage')) { return Security::PermissionFailure($this->controller, 'You must <a href="' . $registerPage->Link() . '">registered</a> and logged in to edit your profile.'); } else { $this->controller->setFlash('You must registered and logged in to edit your profile.', 'warning'); return $this->controller->redirect(Director::absoluteBaseURL()); } } }
public function Results() { $list = Family::get(); $blockNo = Convert::raw2sql($this->request->getVar('BlockNo')); $unitNo = Convert::raw2sql($this->request->getVar('UnitNo')); $parishID = Convert::raw2sql($this->request->getVar('ParishID')); $pincode = Convert::raw2sql($this->request->getVar('Pincode')); $isPanchayat = Convert::raw2sql($this->request->getVar('IsPanchayat')); $isMunicipality = Convert::raw2sql($this->request->getVar('IsMunicipality')); $isCorporation = Convert::raw2sql($this->request->getVar('IsCorporation')); if ($parishID) { $list = $list->filter(array('ParishID' => $parishID)); } if ($blockNo) { $list = $list->filter(array('BlockNo' => $blockNo)); } if ($unitNo) { $list = $list->filter(array('UnitNo' => $unitNo)); } if ($pincode) { $list = $list->filter(array('Pincode' => $pincode)); } if ($isPanchayat) { $list = $list->filter(array('IsPanchayat' => $isPanchayat)); } if ($isMunicipality) { $list = $list->filter(array('IsMunicipality' => $isMunicipality)); } if ($isCorporation) { $list = $list->filter(array('IsCorporation' => $isCorporation)); } //$list = $list->leftJoin('Contact', "\"Contact\".\"FamilyID\" = \"Family\".\"ID\""); //Debug::show($list); return $list; }
/** * @return string */ public function tree($request) { $data = array(); $class = $request->getVar('class'); $id = $request->getVar('id'); if ($id == 0) { $items = singleton('WorkflowService')->getDefinitions(); $type = 'WorkflowDefinition'; } elseif ($class == 'WorkflowDefinition') { $items = DataObject::get('WorkflowAction', '"WorkflowDefID" = ' . (int) $id); $type = 'WorkflowAction'; } else { $items = DataObject::get('WorkflowTransition', '"ActionID" = ' . (int) $id); $type = 'WorkflowTransition'; } if ($items) { foreach ($items as $item) { $new = array('data' => array('title' => $item->Title, 'attr' => array('href' => $this->Link("{$type}/{$item->ID}/edit")), 'icon' => $item->stat('icon')), 'attr' => array('id' => "{$type}_{$item->ID}", 'title' => Convert::raw2att($item->Title), 'data-id' => $item->ID, 'data-type' => $type, 'data-class' => $item->class)); if ($item->numChildren() > 0) { $new['state'] = 'closed'; } $data[] = $new; } } return Convert::raw2json($data); }
public function testEnablePluginsByArrayWithPaths() { Config::inst()->update('Director', 'alternate_base_url', 'http://mysite.com/subdir'); $c = new TinyMCEConfig(); $c->setTheme('modern'); $c->setOption('language', 'es'); $c->disablePlugins('table', 'emoticons', 'paste', 'code', 'link', 'importcss'); $c->enablePlugins(array('plugin1' => 'mypath/plugin1.js', 'plugin2' => '/anotherbase/mypath/plugin2.js', 'plugin3' => 'https://www.google.com/plugin.js', 'plugin4' => null, 'plugin5' => null)); $attributes = $c->getAttributes(); $config = Convert::json2array($attributes['data-config']); $plugins = $config['external_plugins']; $this->assertNotEmpty($plugins); // Plugin specified via relative url $this->assertContains('plugin1', array_keys($plugins)); $this->assertEquals('http://mysite.com/subdir/mypath/plugin1.js', $plugins['plugin1']); // Plugin specified via root-relative url $this->assertContains('plugin2', array_keys($plugins)); $this->assertEquals('http://mysite.com/anotherbase/mypath/plugin2.js', $plugins['plugin2']); // Plugin specified with absolute url $this->assertContains('plugin3', array_keys($plugins)); $this->assertEquals('https://www.google.com/plugin.js', $plugins['plugin3']); // Plugin specified with standard location $this->assertContains('plugin4', array_keys($plugins)); $this->assertEquals('http://mysite.com/subdir/framework/thirdparty/tinymce/plugins/plugin4/plugin.min.js', $plugins['plugin4']); // Check that internal plugins are extractable separately $this->assertEquals(['plugin4', 'plugin5'], $c->getInternalPlugins()); // Test plugins included via gzip compresser Config::inst()->update('HTMLEditorField', 'use_gzip', true); $this->assertEquals('framework/thirdparty/tinymce/tiny_mce_gzip.php?js=1&plugins=plugin4,plugin5&themes=modern&languages=es&diskcache=true&src=true', $c->getScriptURL()); // If gzip is disabled only the core plugin is loaded Config::inst()->remove('HTMLEditorField', 'use_gzip'); $this->assertEquals('framework/thirdparty/tinymce/tinymce.min.js', $c->getScriptURL()); }
function __construct($controller, $name, $sourceClass, $fieldList, $detailFormFields, $sourceFilter = "", $sourceSort = "", $sourceJoin = "") { parent::__construct($controller, $name, $sourceClass, $fieldList, $detailFormFields, $sourceFilter, $sourceSort, $sourceJoin); $SNG_file = singleton('File'); // If search was request, filter the results here $SQL_search = (!empty($_REQUEST['FileSearch'])) ? Convert::raw2sql($_REQUEST['FileSearch']) : null; if($SQL_search) { $searchFilters = array(); foreach($SNG_file->searchableFields() as $fieldName => $fieldSpec) { if(strpos($fieldName, '.') === false) $searchFilters[] = "\"$fieldName\" LIKE '%{$SQL_search}%'"; } $this->sourceFilter = '(' . implode(' OR ', $searchFilters) . ')'; $this->searchingFor = $_REQUEST['FileSearch']; // @todo Integrate search form more closely and don't rely on deprecated // $extraLinkParams. $this->extraLinkParams = array( 'FileSearch' => $SQL_search ); } $this->sourceSort = 'Title'; $this->Markable = true; }
public function getHTMLFragments($gridField) { $fragments = parent::getHTMLFragments($gridField); $state = $gridField->getState(false); $fragments['before'] .= '<input type="hidden" name="' . $gridField->getName() . '_skey" value="' . Convert::raw2att($gridField->getState(false)->getSessionKey()) . '"/>'; return $fragments; }