TJavaScript is a utility class containing commonly-used javascript-related functions.
Since: 3.0
Esempio n. 1
0
 /**
  * Adds on client-side event handler by wrapping the code within a
  * javascript function block. If the code begins with "javascript:", the
  * code is assumed to be a javascript function block rather than arbiturary
  * javascript statements.
  * @param string option name
  * @param string javascript statements.
  */
 protected function setFunction($name, $code)
 {
     if (!TJavaScript::isJsLiteral($code)) {
         $code = TJavaScript::quoteJsLiteral($this->ensureFunction($code));
     }
     $this->setOption($name, $code);
 }
Esempio n. 2
0
 /**
  * Displays the exceptions to the client-side TJavascriptLogger.
  * A HTTP 500 status code is sent and the stack trace is sent as JSON encoded.
  * @param Exception exception details.
  */
 protected function displayException($exception)
 {
     if ($this->getApplication()->getMode() === TApplication::STATE_DEBUG) {
         $response = $this->getApplication()->getResponse();
         $trace = $this->getExceptionStackTrace($exception);
         // avoid error on non-utf8 strings
         try {
             $trace = TJavaScript::jsonEncode($trace);
         } catch (Exception $e) {
             // strip everythin not 7bit ascii
             $trace = preg_replace('/[^(\\x20-\\x7F)]*/', '', serialize($trace));
         }
         // avoid exception loop if headers have already been sent
         try {
             $response->setStatusCode(500, 'Internal Server Error');
         } catch (Exception $e) {
         }
         $content = $response->createHtmlWriter();
         $content->getWriter()->setBoundary(TActivePageAdapter::CALLBACK_ERROR_HEADER);
         $content->write($trace);
     } else {
         error_log("Error happened while processing an existing error:\n" . $exception->__toString());
         header('HTTP/1.0 500 Internal Server Error', true, 500);
     }
     $this->getApplication()->getResponse()->flush();
 }
Esempio n. 3
0
 /**
  * Converts a value to string type.
  * Note, a boolean value will be converted to 'true' if it is true
  * and 'false' if it is false.
  * @param mixed the value to be converted.
  * @return string
  */
 public static function ensureString($value)
 {
     if (TJavaScript::isJsLiteral($value)) {
         return $value;
     }
     if (is_bool($value)) {
         return $value ? 'true' : 'false';
     } else {
         return (string) $value;
     }
 }
Esempio n. 4
0
 public function onPreRender($param)
 {
     parent::onPreRender($param);
     $cs = $this->Page->getClientScript();
     $cs->registerPradoScript('validator');
     // communicate validation status to the client side
     $value = $this->_isvalid === false ? '0' : '1';
     $cs->registerHiddenField($this->getClientID() . '_1', $value);
     // update validator display
     if ($control = $this->getValidationTarget()) {
         $fn = 'captchaUpdateValidatorStatus_' . $this->getClientID();
         $cs->registerEndScript($this->getClientID() . '::validate', implode(' ', array('function ' . $fn . '(valid)', '{', '  jQuery(' . TJavaScript::quoteString('#' . $this->getClientID() . '_1') . ').val(valid);', '  Prado.Validation.validateControl(' . TJavaScript::quoteString($control->ClientID) . '); ', '}', '', $this->Page->IsCallback ? $fn . '(' . $value . ');' : '', '', 'jQuery("#' . $control->getClientID() . '").on("change", ' . TJavaScript::quoteString('#' . $control->getResponseFieldName()) . ', function() { ', $fn . '("1");', '});')));
     }
 }
Esempio n. 5
0
 /**
  * Ensure that the ID attribute is rendered and registers the javascript code
  * for initializing the active control.
  */
 protected function addAttributesToRender($writer)
 {
     parent::addAttributesToRender($writer);
     $writer->addAttribute('id', $this->getClientID());
     $options = TJavaScript::encode($this->getPostBackOptions());
     $cs = $this->getPage()->getClientScript();
     $code = "jQuery('#" . $this->getWidgetID() . "')." . $this->getWidget() . "(" . $options . ");";
     $cs->registerEndScript(sprintf('%08X', crc32($code)), $code);
 }
Esempio n. 6
0
 /**
  * Publish the color picker assets.
  */
 protected function publishColorPickerAssets()
 {
     $cs = $this->getPage()->getClientScript();
     $key = "prado:" . get_class($this);
     $imgs['button.gif'] = $this->getAssetUrl('button.gif');
     $imgs['background.png'] = $this->getAssetUrl('background.png');
     $options = TJavaScript::encode($imgs);
     $code = "Prado.WebUI.TColorPicker.UIImages = {$options};";
     $cs->registerEndScript($key, $code);
     $cs->registerPradoScript("colorpicker");
     $url = $this->getAssetUrl($this->getColorPickerStyle() . '.css');
     if (!$cs->isStyleSheetFileRegistered($url)) {
         $cs->registerStyleSheetFile($url, $url);
     }
 }
Esempio n. 7
0
 /**
  * Render the javascript for validation summary.
  * @param array list of options for validation summary.
  */
 protected function renderJsSummary()
 {
     if (!$this->getEnabled(true) || !$this->getEnableClientScript()) {
         return;
     }
     $cs = $this->getPage()->getClientScript();
     $cs->registerPradoScript('validator');
     //need to register the validation manager is validation summary is alone.
     $formID = $this->getPage()->getForm()->getClientID();
     $scriptKey = "TBaseValidator:{$formID}";
     if ($this->getEnableClientScript() && !$cs->isEndScriptRegistered($scriptKey)) {
         $manager['FormID'] = $formID;
         $options = TJavaScript::encode($manager);
         $cs->registerPradoScript('validator');
         $cs->registerEndScript($scriptKey, "new Prado.ValidationManager({$options});");
     }
     $options = TJavaScript::encode($this->getClientScriptOptions());
     $script = "new Prado.WebUI.TValidationSummary({$options});";
     $cs->registerEndScript($this->getClientID(), $script);
 }
Esempio n. 8
0
 /**
  * Registers the relevant JavaScript.
  */
 protected function registerClientScript()
 {
     $options = TJavaScript::encode($this->getClientOptions());
     $className = $this->getClientClassName();
     $cs = $this->getPage()->getClientScript();
     $cs->registerPradoScript('keyboard');
     $cs->registerEndScript('prado:' . $this->getClientID(), "new {$className}({$options});");
 }
Esempio n. 9
0
 public function setOnSlide($javascript)
 {
     $code = TJavaScript::quoteJsLiteral("function (value) { {$javascript} }");
     $this->setFunction('onSlide', $code);
 }
Esempio n. 10
0
 /**
  * Renders the callback response by adding additional callback data and
  * javascript actions in the header and page state if required.
  * @param THtmlWriter html content writer.
  */
 protected function renderResponse($writer)
 {
     Prado::trace("ActivePage renderResponse()", 'Prado\\Web\\UI\\ActiveControls\\TActivePageAdapter');
     //renders all the defered render() calls.
     foreach ($this->_controlsToRender as $rid => $forRender) {
         $forRender[0]->render($forRender[1]);
     }
     $response = $this->getResponse();
     //send response data in header
     if ($response->getHasAdapter()) {
         $responseData = $response->getAdapter()->getResponseData();
         if ($responseData !== null) {
             $data = TJavaScript::jsonEncode($responseData);
             $this->appendContentPart($response, self::CALLBACK_DATA_HEADER, $data);
         }
     }
     //sends page state in header
     if (($handler = $this->getCallbackEventTarget()) !== null) {
         if ($handler->getActiveControl()->getClientSide()->getEnablePageStateUpdate()) {
             $pagestate = $this->getPage()->getClientState();
             $this->appendContentPart($response, self::CALLBACK_PAGESTATE_HEADER, $pagestate);
         }
     }
     //safari must receive at least 1 byte of data.
     $writer->write(" ");
     //output the end javascript
     if ($this->getPage()->getClientScript()->hasEndScripts()) {
         $writer = $response->createHtmlWriter();
         $this->getPage()->getClientScript()->renderEndScriptsCallback($writer);
         $this->getPage()->getCallbackClient()->evaluateScript($writer);
     }
     //output the actions
     $executeJavascript = $this->getCallbackClientHandler()->getClientFunctionsToExecute();
     $actions = TJavaScript::jsonEncode($executeJavascript);
     $this->appendContentPart($response, self::CALLBACK_ACTION_HEADER, $actions);
     $cs = $this->Page->getClientScript();
     // collect all stylesheet file references
     $stylesheets = $cs->getStyleSheetUrls();
     if (count($stylesheets) > 0) {
         $this->appendContentPart($response, self::CALLBACK_STYLESHEETLIST_HEADER, TJavaScript::jsonEncode($stylesheets));
     }
     // collect all stylesheet snippets references
     $stylesheets = $cs->getStyleSheetCodes();
     if (count($stylesheets) > 0) {
         $this->appendContentPart($response, self::CALLBACK_STYLESHEET_HEADER, TJavaScript::jsonEncode($stylesheets));
     }
     // collect all script file references
     $scripts = $cs->getScriptUrls();
     if (count($scripts) > 0) {
         $this->appendContentPart($response, self::CALLBACK_SCRIPTLIST_HEADER, TJavaScript::jsonEncode($scripts));
     }
     // collect all hidden field references
     $fields = $cs->getHiddenFields();
     if (count($fields) > 0) {
         $this->appendContentPart($response, self::CALLBACK_HIDDENFIELDLIST_HEADER, TJavaScript::jsonEncode($fields));
     }
 }
Esempio n. 11
0
 /**
  * Renders content provided by TJsonResponse::getJsonContent() as
  * javascript in JSON format.
  */
 protected function createJsonResponse($service, $properties, $config)
 {
     // init service properties
     foreach ($properties as $name => $value) {
         $service->setSubproperty($name, $value);
     }
     $service->init($config);
     //send content if not null
     if (($content = $service->getJsonContent()) !== null) {
         $response = $this->getResponse();
         $response->setContentType('application/json');
         $response->setCharset('UTF-8');
         //send content
         $response->write(TJavaScript::jsonEncode($content));
     }
 }
Esempio n. 12
0
 /**
  * @return Array of active control options
  */
 public function toArray()
 {
     $ret = $this->_options === null ? array() : $this->_options;
     foreach ($this->_control->getValidEvents() as $event) {
         if ($this->_control->hasEventHandler('on' . $event)) {
             $ret[$event] = new TJavaScriptLiteral("function( event, ui ) { Prado.JuiCallback(" . TJavaScript::encode($this->_control->getUniqueID()) . ", " . TJavaScript::encode($event) . ", event, ui, this); }");
         }
     }
     return $ret;
 }
Esempio n. 13
0
 protected function registerClientScript()
 {
     $id = $this->getClientID();
     $options = TJavaScript::encode($this->getClientOptions());
     $className = $this->getClientClassName();
     $cs = $this->Page->ClientScript;
     $code = "new {$className}({$options});";
     $cs->registerPradoScript('ajax');
     $cs->registerEndScript("grecaptcha:{$id}", $code);
 }
Esempio n. 14
0
 public function onPreRender($param)
 {
     parent::onPreRender($param);
     $cs = $this->Page->getClientScript();
     $cs->registerPradoScript('validator');
     // communicate validation status to the client side
     $value = $this->_isvalid === false ? '0' : '1';
     $cs->registerHiddenField($this->getClientID() . '_1', $value);
     // update validator display
     if ($control = $this->getValidationTarget()) {
         $fn = 'captchaUpdateValidatorStatus_' . $this->getClientID();
         // check if we need to request a new captcha too
         if ($this->Page->IsCallback) {
             if ($control->getVisible(true)) {
                 if (!is_null($this->_isvalid)) {
                     // if the response has been tested and we reach the pre-render phase
                     // then we need to regenerate the token, because it won't test positive
                     // anymore, even if solves correctly
                     $control->regenerateToken();
                 }
             }
         }
         $cs->registerEndScript($this->getClientID() . '::validate', implode(' ', array('function ' . $fn . '(valid)', '{', '  jQuery(' . TJavaScript::quoteString('#' . $this->getClientID() . '_1') . ').val(valid);', '  Prado.Validation.validateControl(' . TJavaScript::quoteString($control->ClientID) . '); ', '}', '', $this->Page->IsCallback ? $fn . '(' . $value . ');' : '', '', 'jQuery("#' . $control->getClientID() . '").on("keyup", ' . TJavaScript::quoteString('#' . $control->getResponseFieldName()) . ', function() { ', $fn . '("1");', '});')));
     }
 }
Esempio n. 15
0
 protected function renderClientControlScript($writer)
 {
     $cs = $this->getPage()->getClientScript();
     if (!$cs->isEndScriptRegistered('TDatePicker.spacer')) {
         $spacer = $this->getAssetUrl('spacer.gif');
         $code = "Prado.WebUI.TDatePicker.spacer = '{$spacer}';";
         $cs->registerEndScript('TDatePicker.spacer', $code);
     }
     $options = TJavaScript::encode($this->getDatePickerOptions());
     $code = "new Prado.WebUI.TActiveDatePicker({$options});";
     $cs->registerEndScript("prado:" . $this->getClientID(), $code);
 }
Esempio n. 16
0
 /**
  * Registers the editor javascript file and code to initialize the editor.
  */
 protected function registerEditorClientScript($writer)
 {
     $this->loadJavascriptLibrary();
     $scripts = $this->getPage()->getClientScript();
     $options = array('EditorOptions' => $this->getEditorOptions());
     $options = TJavaScript::encode($options, true, true);
     $script = "new {$this->getClientClassName()}({$options})";
     $scripts->registerEndScript('prado:THtmlArea4' . $this->ClientID, $script);
 }
 /**
  * @param string callback requestion options as javascript code.
  */
 public function getJsCallbackOptions()
 {
     return TJavaScript::encode($this->getClientSideOptions());
 }
Esempio n. 18
0
 /**
  * Ensure that the ID attribute is rendered and registers the javascript code
  * for initializing the active control. Also registers language specific global
  * settings for the first used date picker.
  */
 protected function addAttributesToRender($writer)
 {
     $cs = $this->getPage()->getClientScript();
     if (self::$_first) {
         $code = "jQuery(document).ready(function(){jQuery.datepicker.setDefaults(jQuery.datepicker.regional['{$this->getCurrentCulture()}']);});";
         $cs->registerEndScript(sprintf('%08X', crc32($code)), $code);
         self::$_first = false;
     }
     parent::addAttributesToRender($writer);
     $options = TJavaScript::encode($this->getOptions()->toArray());
     $code = "jQuery('#" . $this->getWidgetID() . "')." . $this->getWidget() . "(" . $options . ");";
     $cs->registerEndScript(sprintf('%08X', crc32($code)), $code);
 }
Esempio n. 19
0
 public function renderContents($writer)
 {
     $readyscript = 'jQuery(document).trigger(' . TJavaScript::quoteString('captchaready:' . $this->getClientID()) . ')';
     $cs = $this->Page->ClientScript;
     $id = $this->getClientID();
     $divid = $id . '_1_recaptchadiv';
     $writer->write('<div id="' . htmlspecialchars($divid) . '">');
     if (!$this->Page->IsCallback) {
         $writer->write(TJavaScript::renderScriptBlock('var RecaptchaOptions = ' . TJavaScript::jsonEncode($this->getClientSideOptions()) . ';'));
         $html = $this->recaptcha_get_html($this->getPublicKey());
         /*
         reCAPTCHA currently does not support multiple validations per page
         $html = str_replace(
         	array(self::ChallengeFieldName,self::ResponseFieldName),
         	array($this->getChallengeFieldName(),$this->getResponseFieldName()),
         	$html
         );
         */
         $writer->write($html);
         $cs->registerEndScript('ReCaptcha::EventScript', 'jQuery(document).ready(function() { ' . $readyscript . '; } );');
     } else {
         $options = $this->getClientSideOptions();
         $options['callback'] = new TJavaScriptLiteral('function() { ' . $readyscript . '; ' . $this->getCallbackScript() . '; }');
         $cs->registerScriptFile('ReCaptcha::AjaxScript', self::RECAPTCHA_JS);
         $cs->registerEndScript('ReCaptcha::CreateScript::' . $id, implode(' ', array('if (!jQuery(' . TJavaScript::quoteString('#' . $this->getResponseFieldName()) . '))', '{', 'Recaptcha.destroy();', 'Recaptcha.create(', TJavaScript::quoteString($this->getPublicKey()) . ', ', TJavaScript::quoteString($divid) . ', ', TJavaScript::encode($options), ');', '}')));
     }
     $writer->write('</div>');
 }
Esempio n. 20
0
 /**
  * Sets Adapter to TActivePageAdapter and calls apter to process the
  * callback request.
  */
 protected function processCallbackRequest($writer)
 {
     $this->setAdapter(new TActivePageAdapter($this));
     $callbackEventParameter = $this->getRequest()->itemAt(TPage::FIELD_CALLBACK_PARAMETER);
     if (strlen($callbackEventParameter) > 0) {
         $this->_postData[TPage::FIELD_CALLBACK_PARAMETER] = TJavaScript::jsonDecode((string) $callbackEventParameter);
     }
     // Decode Callback postData from UTF-8 to current Charset
     if (($g = $this->getApplication()->getGlobalization(false)) !== null && strtoupper($enc = $g->getCharset()) != 'UTF-8') {
         foreach ($this->_postData as $k => $v) {
             $this->_postData[$k] = self::decodeUTF8($v, $enc);
         }
     }
     Prado::trace("Page onPreInit()", 'Prado\\Web\\UI\\TPage');
     $this->onPreInit(null);
     Prado::trace("Page initRecursive()", 'Prado\\Web\\UI\\TPage');
     $this->initRecursive();
     Prado::trace("Page onInitComplete()", 'Prado\\Web\\UI\\TPage');
     $this->onInitComplete(null);
     $this->_restPostData = new TMap();
     Prado::trace("Page loadPageState()", 'Prado\\Web\\UI\\TPage');
     $this->loadPageState();
     Prado::trace("Page processPostData()", 'Prado\\Web\\UI\\TPage');
     $this->processPostData($this->_postData, true);
     Prado::trace("Page onPreLoad()", 'Prado\\Web\\UI\\TPage');
     $this->onPreLoad(null);
     Prado::trace("Page loadRecursive()", 'Prado\\Web\\UI\\TPage');
     $this->loadRecursive();
     Prado::trace("Page processPostData()", 'Prado\\Web\\UI\\TPage');
     $this->processPostData($this->_restPostData, false);
     Prado::trace("Page raiseChangedEvents()", 'Prado\\Web\\UI\\TPage');
     $this->raiseChangedEvents();
     $this->getAdapter()->processCallbackEvent($writer);
     /*
     		Prado::trace("Page raisePostBackEvent()",'Prado\Web\UI\TPage');
     		$this->raisePostBackEvent();
     */
     Prado::trace("Page onLoadComplete()", 'Prado\\Web\\UI\\TPage');
     $this->onLoadComplete(null);
     Prado::trace("Page preRenderRecursive()", 'Prado\\Web\\UI\\TPage');
     $this->preRenderRecursive();
     Prado::trace("Page onPreRenderComplete()", 'Prado\\Web\\UI\\TPage');
     $this->onPreRenderComplete(null);
     Prado::trace("Page savePageState()", 'Prado\\Web\\UI\\TPage');
     $this->savePageState();
     Prado::trace("Page onSaveStateComplete()", 'Prado\\Web\\UI\\TPage');
     $this->onSaveStateComplete(null);
     /*
     		Prado::trace("Page renderControl()",'Prado\Web\UI\TPage');
     		$this->renderControl($writer);
     */
     $this->getAdapter()->renderCallbackResponse($writer);
     Prado::trace("Page unloadRecursive()", 'Prado\\Web\\UI\\TPage');
     $this->unloadRecursive();
 }
Esempio n. 21
0
 /**
  * Registers the individual validator client-side javascript code.
  */
 protected function registerClientScriptValidator()
 {
     $key = 'prado:' . $this->getClientID();
     if (!$this->getPage()->getClientScript()->isEndScriptRegistered($key)) {
         $options = TJavaScript::encode($this->getClientScriptOptions());
         $script = 'new ' . $this->getClientClassName() . '(' . $options . ');';
         $this->getPage()->getClientScript()->registerEndScript($key, $script);
     }
 }
Esempio n. 22
0
 /**
  * @param THtmlWriter writer for the rendering purpose
  */
 public function renderEndScriptsCallback($writer)
 {
     $writer->write(TJavaScript::renderScriptBlocksCallback($this->_endScripts));
 }
Esempio n. 23
0
 /**
  * Registers the relevant JavaScript.
  */
 protected function registerClientScript()
 {
     $id = $this->getClientID();
     $options = TJavaScript::encode($this->getClientOptions());
     $className = $this->getClientClassName();
     $cs = $this->getPage()->getClientScript();
     $cs->registerPradoScript('tabpanel');
     $code = "new {$className}({$options});";
     $cs->registerEndScript("prado:{$id}", $code);
     // ensure an item is always active and visible
     $index = $this->getActiveViewIndex();
     if (!$this->getViews()->itemAt($index)->Visible) {
         $index = 0;
     }
     $cs->registerHiddenField($id . '_1', $index);
 }
Esempio n. 24
0
 /**
  * Ensure that the ID attribute is rendered and registers the javascript code
  * for initializing the active control.
  */
 protected function addAttributesToRender($writer)
 {
     parent::addAttributesToRender($writer);
     $cs = $this->getPage()->getClientScript();
     if ($this->getGhosting() == TDraggableGhostingOptions::SuperGhosting) {
         $cs->registerPradoScript('dragdropextra');
     } else {
         $cs->registerPradoScript('dragdrop');
     }
     $writer->addAttribute('id', $this->getClientID());
     $options = TJavaScript::encode($this->getPostBackOptions());
     $class = $this->getClientClassName();
     $code = "new {$class}('{$this->getClientId()}', {$options}) ";
     $cs->registerEndScript(sprintf('%08X', crc32($code)), $code);
 }
Esempio n. 25
0
 /**
  * @return string header template with "Copy code" link.
  */
 protected function getHeaderTemplate()
 {
     $id = $this->getClientID();
     return TJavaScript::renderScriptBlock("new Prado.WebUI.TTextHighlighter('{$id}');");
 }