Example #1
0
 function test_javascript_tag()
 {
     $javascript = new JavaScriptHelper();
     //static call
     $this->AssertEqual(JavascriptHelper::javascript_tag("alert('test akelos');"), "<script type=\"text/javascript\">\n//<![CDATA[\nalert('test akelos');\n//]]>\n</script>");
     //object call
     $this->AssertEqual($javascript->javascript_tag("alert('test akelos');"), "<script type=\"text/javascript\">\n//<![CDATA[\nalert('test akelos');\n//]]>\n</script>");
 }
Example #2
0
 /**
  * Executed after a view has rendered, used to include bufferred code
  * blocks.
  *
  * @access public
  */
 function afterRender()
 {
     if (env('HTTP_X_UPDATE') != null && !empty($this->__ajaxBuffer)) {
         @ob_end_clean();
         $data = array();
         $divs = explode(' ', env('HTTP_X_UPDATE'));
         $keys = array_keys($this->__ajaxBuffer);
         if (count($divs) == 1 && in_array($divs[0], $keys)) {
             echo $this->__ajaxBuffer[$divs[0]];
         } else {
             foreach ($this->__ajaxBuffer as $key => $val) {
                 if (in_array($key, $divs)) {
                     $data[] = $key . ':"' . rawurlencode($val) . '"';
                 }
             }
             $out = 'var __ajaxUpdater__ = {' . implode(", \n", $data) . '};' . "\n";
             $out .= 'for (n in __ajaxUpdater__) { if (typeof __ajaxUpdater__[n] == "string"';
             $out .= ' && $(n)) Element.update($(n), unescape(decodeURIComponent(';
             $out .= '__ajaxUpdater__[n]))); }';
             echo $this->Javascript->codeBlock($out, false);
         }
         $scripts = $this->Javascript->getCache();
         if (!empty($scripts)) {
             echo $this->Javascript->codeBlock($scripts, false);
         }
         $this->_stop();
     }
 }
Example #3
0
 protected function makeJsProperty($strProp, $strKey)
 {
     $objValue = $this->{$strProp};
     if (null === $objValue) {
         return '';
     }
     return $strKey . ': ' . JavaScriptHelper::toJsObject($objValue) . ', ';
 }
Example #4
0
 public function toJsObject()
 {
     $a = array('value' => $this->strName, 'id' => $this->strValue);
     if ($this->strLabel) {
         $a['label'] = $this->strLabel;
     }
     if ($this->strItemGroup) {
         $a['category'] = $this->strItemGroup;
     }
     return JavaScriptHelper::toJsObject($a);
 }
 public function testJavascriptDataConversions()
 {
     $objCaseArray = array(array("Value" => "bob", "Expected" => "bob"), array("Value" => "Bob", "Expected" => "-bob"), array("Value" => "bobSmith", "Expected" => "bob-smith"), array("Value" => "bobSmithJones", "Expected" => "bob-smith-jones"));
     foreach ($objCaseArray as $objCase) {
         $newValue = JavaScriptHelper::dataNameFromCamelCase($objCase["Value"]);
         $this->assertEquals($objCase["Expected"], $newValue);
     }
     $objCaseArray = array(array("Value" => "bob", "Expected" => "bob"), array("Value" => "-bob", "Expected" => "Bob"), array("Value" => "bob-smith", "Expected" => "bobSmith"), array("Value" => "bob-smith-jones", "Expected" => "bobSmithJones"));
     foreach ($objCaseArray as $objCase) {
         $newValue = JavaScriptHelper::dataNameToCamelCase($objCase["Value"]);
         $this->assertEquals($objCase["Expected"], $newValue);
     }
 }
Example #6
0
 function test_for_JavascriptHelper()
 {
     require_once AK_LIB_DIR . DS . 'AkActionView' . DS . 'helpers' . DS . 'javascript_helper.php';
     $javascript = new JavaScriptHelper();
     $this->assertEqual($javascript->link_to_function('Greeting', "alert('Hello world!')"), '<a href="#" onclick="alert(\'Hello world!\'); return false;">Greeting</a>');
     $this->assertEqual($javascript->link_to_function('my link', "if confirm('Really?'){ do_delete(); }", array('href' => 'http://www.akelos.com')), '<a href="http://www.akelos.com" onclick="if confirm(\'Really?\'){ do_delete(); }; return false;">my link</a>');
     $this->assertEqual($javascript->button_to_function("Greeting", "alert('Hello world!')"), '<input onclick="alert(\'Hello world!\');" type="button" value="Greeting" />');
     $this->assertEqual($javascript->button_to_function("Delete", "if confirm('Really?'){ do_delete(); }", array('id' => 'confirm')), '<input id="confirm" onclick="if confirm(\'Really?\'){ do_delete(); };" type="button" value="Delete" />');
     $this->assertEqual($javascript->javascript_tag("alert('All is good')"), "<script type=\"text/javascript\">\n//<![CDATA[\nalert('All is good')\n//]]>\n</script>");
     $input = "\n        <div id='meesage'\n        \n         class=\"hisghtlight\" />\n        ";
     $expected = "\\n        <div id=\\'meesage\\'\\n        \\n         class=\\\"hisghtlight\\\" />\\n        ";
     $this->assertEqual($javascript->escape_javascript($input), $expected);
 }
Example #7
0
 /**
  * Create a text field with Jquery UI Autocomplete.
  *
  * Creates an autocomplete field with the given ID and options.
  * needs include jQuery UI Autocomplete file
  *
  * @param string $field DOM ID of field to observe
  * @param array $options Ajax options
  * @return string Ajax script
  * check out http://jqueryui.com/demos/autocomplete/
  */
 function autoComplete($field, $options = array())
 {
     $var = '';
     if (isset($options['var'])) {
         $var = 'var ' . $options['var'] . ' = ';
         unset($options['var']);
     }
     if (isset($options['source'])) {
         $options['source'] = "'" . Router::url($options['source']) . "'";
     }
     if (!isset($options['id'])) {
         $options['id'] = Inflector::camelize(str_replace(".", "_", $field));
     }
     $htmlOptions = $this->__getHtmlOptions($options);
     $htmlOptions['autocomplete'] = "off";
     foreach ($this->autoCompleteOptions as $opt) {
         unset($htmlOptions[$opt]);
     }
     $options = $this->_optionsToString($options, array('multipleSeparator'));
     $callbacks = array('formatItem', 'formatMatch', 'formatResult', 'highlight');
     foreach ($callbacks as $callback) {
         if (isset($options[$callback])) {
             $name = $callback;
             $code = $options[$callback];
             switch ($name) {
                 case 'formatResult':
                     $options[$name] = "function(data, i, max) {" . $code . "}";
                     break;
                 case 'highlight':
                     $options[$name] = "function(data, search) {" . $code . "}";
                     break;
                 default:
                     $options[$name] = "function(row, i, max, term) {" . $code . "}";
                     break;
             }
         }
     }
     $options = $this->_buildOptions($options, $this->autoCompleteOptions);
     $text = $this->Form->text($field, $htmlOptions);
     $script = "{$var} \$('#{$htmlOptions['id']}').autocomplete(";
     $script .= "{$options});";
     return "{$text}\n" . $this->Javascript->codeBlock($script);
 }
 /**
  * Default "toJsObject" handler
  * Specifies how the object should be displayed in JQuery UI lists and menus. Note that these lists use
  * value and label differently.
  *
  * value 	= The short form of what to display in the list and selection.
  * label 	= [optional] If defined, is what is displayed in the menu
  * id 		= Primary key of object.
  *
  * @return an array that specifies how to display the object
  */
 public function toJsObject()
 {
     return JavaScriptHelper::toJsObject(array('value' => $this->__toString(), 'id' => array($this->intSuggestionId, $this->intContextId, $this->intUserId)));
 }
 /**
  * Default "toJsObject" handler
  * Specifies how the object should be displayed in JQuery UI lists and menus. Note that these lists use
  * value and label differently.
  *
  * value 	= The short form of what to display in the list and selection.
  * label 	= [optional] If defined, is what is displayed in the menu
  * id 		= Primary key of object.
  *
  * @return an array that specifies how to display the object
  */
 public function toJsObject()
 {
     return JavaScriptHelper::toJsObject(array('value' => $this->__toString(), 'id' => array($this->intObjectId, $this->intTermTaxonomyId)));
 }
    /**
     * Renders the end of the form, including the closing form and body tags.
     * Renders the html for hidden controls.
     * @param bool $blnDisplayOutput should the output be returned or directly printed to screen.
     *
     * @return null|string
     * @throws QCallerException
     */
    public function RenderEnd($blnDisplayOutput = true)
    {
        // Ensure that RenderEnd() has not yet been called
        switch ($this->intFormStatus) {
            case QFormBase::FormStatusUnrendered:
                throw new QCallerException('$this->RenderBegin() was never called');
            case QFormBase::FormStatusRenderBegun:
                break;
            case QFormBase::FormStatusRenderEnded:
                throw new QCallerException('$this->RenderEnd() has already been called');
                break;
            default:
                throw new QCallerException('FormStatus is in an unknown status');
        }
        $strHtml = '';
        // This will be the final output
        /**** Render any controls that get automatically rendered ****/
        foreach ($this->GetAllControls() as $objControl) {
            if ($objControl->AutoRender && !$objControl->Rendered) {
                $strRenderMethod = $objControl->PreferredRenderMethod;
                $strHtml .= $objControl->{$strRenderMethod}(false) . _nl();
            }
        }
        /**** Prepare Javascripts ****/
        // Clear included javascript array since we are completely redrawing the page
        $this->strIncludedJavaScriptFileArray = array();
        $strControlIdToRegister = array();
        $strEventScripts = '';
        // Add form level javascripts and libraries
        $strJavaScriptArray = $this->ProcessJavaScriptList($this->GetFormJavaScripts());
        QApplication::AddJavaScriptFiles($strJavaScriptArray);
        $strFormJsFiles = QApplication::RenderFiles();
        // Render the form-level javascript files separately
        // Go through all controls and gather up any JS or CSS to run or Form Attributes to modify
        foreach ($this->GetAllControls() as $objControl) {
            if ($objControl->Rendered || $objControl->ScriptsOnly) {
                $strControlIdToRegister[] = $objControl->ControlId;
                /* Note: GetEndScript may cause the control to register additional commands, or even add javascripts, so those should be handled after this. */
                if ($strControlScript = $objControl->GetEndScript()) {
                    $strControlScript = JavaScriptHelper::TerminateScript($strControlScript);
                    // Add comments for developer version of output
                    if (!QApplication::$Minimize) {
                        // Render a comment
                        $strControlScript = _nl() . _nl() . sprintf('/*** EndScript -- Control Type: %s, Control Name: %s, Control Id: %s  ***/', get_class($objControl), $objControl->Name, $objControl->ControlId) . _nl() . _indent($strControlScript);
                    }
                    $strEventScripts .= $strControlScript;
                }
            }
            // Include the javascripts specified by each control.
            if ($strScriptArray = $this->ProcessJavaScriptList($objControl->JavaScripts)) {
                QApplication::AddJavaScriptFiles($strScriptArray);
            }
            // Include any StyleSheets?  The control would have a
            // comma-delimited list of stylesheet files to include (if applicable)
            if ($strScriptArray = $this->ProcessStyleSheetList($objControl->StyleSheets)) {
                QApplication::AddStyleSheets(array_keys($strScriptArray));
            }
            // Form Attributes?
            if ($objControl->FormAttributes) {
                QApplication::ExecuteControlCommand($this->strFormId, 'attr', $objControl->FormAttributes);
                foreach ($objControl->FormAttributes as $strKey => $strValue) {
                    if (!array_key_exists($strKey, $this->strFormAttributeArray)) {
                        $this->strFormAttributeArray[$strKey] = $strValue;
                    } else {
                        if ($this->strFormAttributeArray[$strKey] != $strValue) {
                            $this->strFormAttributeArray[$strKey] = $strValue;
                        }
                    }
                }
            }
        }
        // Add grouping commands to events (Used for deprecated drag and drop, but not removed yet)
        foreach ($this->objGroupingArray as $objGrouping) {
            $strGroupingScript = $objGrouping->Render();
            if (strlen($strGroupingScript) > 0) {
                $strGroupingScript = JavaScriptHelper::TerminateScript($strGroupingScript);
                $strEventScripts .= $strGroupingScript;
            }
        }
        /*** Build the javascript block ****/
        // Start with variable settings and initForm
        $strEndScript = sprintf('qc.initForm("%s"); ', $this->strFormId);
        // Register controls
        if ($strControlIdToRegister) {
            $strEndScript .= sprintf("qc.regCA(%s); \n", JavaScriptHelper::toJsObject($strControlIdToRegister));
        }
        // Design mode event
        if (defined('__DESIGN_MODE__') && __DESIGN_MODE__ == 1) {
            // attach an event listener to the form to send context menu selections to the designer dialog for processing
            $strEndScript .= sprintf('$j("#%s").on("contextmenu", "[id]", 
						function(event) {
							$j("#qconnectoreditdlg").trigger("qdesignerclick", 
								[{id: event.target.id ? event.target.id : $j(event.target).parents("[id]").attr("id"), for: $j(event.target).attr("for")}]
							);
							return false;
						}
					);', $this->FormId);
        }
        // Add any application level js commands.
        // This will include high and medimum level commands
        $strEndScript .= QApplication::RenderJavascript(true);
        // Add the javascript coming from controls and events just after the medium level commands
        $strEndScript .= ';' . $strEventScripts;
        // Add low level commands and other things that need to execute at the end
        $strEndScript .= ';' . QApplication::RenderJavascript(false);
        // Create Final EndScript Script
        $strEndScript = sprintf('<script type="text/javascript">$j(document).ready(function() { %s; });</script>', $strEndScript);
        /**** Render the HTML itself, appending the javascript we generated above ****/
        foreach ($this->GetAllControls() as $objControl) {
            if ($objControl->Rendered) {
                $strHtml .= $objControl->GetEndHtml();
            }
            $objControl->ResetFlags();
            // Make sure controls are serialized in a reset state
        }
        $strHtml .= $strFormJsFiles . _nl();
        // Add form level javascript files
        // put javascript environment defines up early for use by other js files.
        $strHtml .= '<script type="text/javascript">' . sprintf('qc.baseDir = "%s"; ', __VIRTUAL_DIRECTORY__ . __SUBDIRECTORY__) . sprintf('qc.jsAssets = "%s"; ', __VIRTUAL_DIRECTORY__ . __JS_ASSETS__) . sprintf('qc.phpAssets = "%s"; ', __VIRTUAL_DIRECTORY__ . __PHP_ASSETS__) . sprintf('qc.cssAssets = "%s"; ', __VIRTUAL_DIRECTORY__ . __CSS_ASSETS__) . sprintf('qc.imageAssets = "%s"; ', __VIRTUAL_DIRECTORY__ . __IMAGE_ASSETS__) . '</script>' . _nl();
        $strHtml .= QApplication::RenderFiles() . _nl();
        // add plugin and control js files
        // Render hidden controls related to the form
        $strHtml .= sprintf('<input type="hidden" name="Qform__FormId" id="Qform__FormId" value="%s" />', $this->strFormId) . _nl();
        $strHtml .= sprintf('<input type="hidden" name="Qform__FormControl" id="Qform__FormControl" value="" />') . _nl();
        $strHtml .= sprintf('<input type="hidden" name="Qform__FormEvent" id="Qform__FormEvent" value="" />') . _nl();
        $strHtml .= sprintf('<input type="hidden" name="Qform__FormParameter" id="Qform__FormParameter" value="" />') . _nl();
        $strHtml .= sprintf('<input type="hidden" name="Qform__FormCallType" id="Qform__FormCallType" value="" />') . _nl();
        $strHtml .= sprintf('<input type="hidden" name="Qform__FormUpdates" id="Qform__FormUpdates" value="" />') . _nl();
        $strHtml .= sprintf('<input type="hidden" name="Qform__FormCheckableControls" id="Qform__FormCheckableControls" value="" />') . _nl();
        // Serialize and write out the formstate
        $strHtml .= sprintf('<input type="hidden" name="Qform__FormState" id="Qform__FormState" value="%s" />', QForm::Serialize(clone $this)) . _nl();
        // close the form tag
        $strHtml .= "</form>";
        // Add the JavaScripts rendered above
        $strHtml .= $strEndScript;
        // close the body tag
        if ($this->blnRenderedBodyTag) {
            $strHtml .= '</body>';
        }
        /**** Cleanup ****/
        // Update Form Status
        $this->intFormStatus = QFormBase::FormStatusRenderEnded;
        // Display or Return
        if ($blnDisplayOutput) {
            if (!QApplication::$CliMode) {
                print $strHtml;
            }
            return null;
        } else {
            if (!QApplication::$CliMode) {
                return $strHtml;
            } else {
                return '';
            }
        }
    }
Example #11
0
 function _confirm_javascript_function($confirm)
 {
     return "confirm('" . JavaScriptHelper::escape_javascript($confirm) . "')";
 }
 /**
  * Render plugin javascript
  * @return string
  */
 public function RenderPlugins()
 {
     $strJS = '';
     if (!empty($this->aFixedColumns)) {
         $this->AddPluginJavascriptFile("datatables", __PLUGIN_ASSETS__ . "/datatables/extras/FixedColumns/js/dataTables.fixedColumns.js");
         $strJS .= sprintf("{var oTable = jQuery('#%s').%s();\n", $this->getJqControlId(), $this->getJqSetupFunction());
         $strJS .= 'new $j.fn.DataTable.FixedColumns( oTable, ' . JavaScriptHelper::toJsObject($this->aFixedColumns) . '); };';
     }
     return $strJS;
 }
Example #13
0
    /**
      * Adds AJAX autocomplete functionality to the text input field with the 
      * DOM ID specified by +field_id+.
      *
      * This function expects that the called action returns a HTML <ul> list,
      * or nothing if no entries should be displayed for autocompletion.
      *
      * You'll probably want to turn the browser's built-in autocompletion off,
      * so be sure to include a autocomplete="off" attribute with your text
      * input field.
      *
      * The autocompleter object is assigned to a Javascript variable named <tt>field_id</tt>_auto_completer.
      * This object is useful if you for example want to trigger the auto-complete suggestions through
      * other means than user input (for that specific case, call the <tt>activate</tt> method on that object). 
      * 
      * Required +options+ are:
      * <tt>url</tt>::       URL to call for autocompletion results
      *                       in url_for format.
      * 
      * Addtional +options+ are:
      * <tt>update</tt>::    Specifies the DOM ID of the element whose 
      *                       innerHTML should be updated with the autocomplete
      *                       entries returned by the AJAX request. 
      *                       Defaults to field_id + '_auto_complete'
      * <tt>with</tt>::      A JavaScript expression specifying the
      *                       parameters for the XMLHttpRequest. This defaults
      *                       to 'fieldname=value'.
      * <tt>indicator</tt>:: Specifies the DOM ID of an element which will be
      *                       displayed while autocomplete is running.
      * <tt>tokens</tt>::    A string or an array of strings containing
      *                       separator tokens for tokenized incremental 
      *                       autocompletion. Example: <tt>tokens => ','</tt> would
      *                       allow multiple autocompletion entries, separated
      *                       by commas.
      * <tt>min_chars</tt>:: The minimum number of characters that should be
      *                       in the input field before an Ajax call is made
      *                       to the server.
      * <tt>on_hide</tt>::   A Javascript expression that is called when the
      *                       autocompletion div is hidden. The expression
      *                       should take two variables: element and update.
      *                       Element is a DOM element for the field, update
      *                       is a DOM element for the div from which the
      *                       innerHTML is replaced.
      * <tt>on_show</tt>::   Like on_hide, only now the expression is called
      *                       then the div is shown.
      * <tt>select</tt>::    Pick the class of the element from which the value for 
      *                       insertion should be extracted. If this is not specified,
      *                       the entire element is used.
      * @deprecated 
      */
    function auto_complete_field($field_id, $options = array())
    {
        $function =  "var {$field_id}_auto_completer = new Ajax.Autocompleter(";
        $function .= "'{$field_id}', ";
        $function .= !empty($options['update']) ? "'{$options['update']}', " : "'{$field_id}_auto_complete', ";
        $function .= "'".UrlHelper::url_for($options['url'])."'";

        $js_options = array();
        if (!empty($options['tokens'])){
            $js_options['tokens'] = JavaScriptHelper::_array_or_string_for_javascript($options['tokens']) ;
        }
        if (!empty($options['with'])) {
            $js_options['callback'] = "function(element, value) { return {$options['with']} }";
        }
        if (!empty($options['indicator'])) {
            $js_options['indicator'] = "'{$options['indicator']}'";
        }
        if (!empty($options['select'])) {
            $js_options['select'] = "'{$options['select']}'";
        }

        $default_options = array(
        'on_show' => 'onShow',
        'on_hide' => 'onHide',
        'min_chars' => 'min_chars'
        );

        foreach ($default_options as $key=>$default_option) {
            if (!empty($options[$key])) {
                $js_options[$default_option] = $options[$key];
            }
        }
        $function .= ', '.JavaScriptHelper::_options_for_javascript($js_options).')';
        return JavaScriptHelper::javascript_tag($function);
    }
Example #14
0
 /**
  * Displays the view.
  *
  * @param  string $tpl the template name
  *
  * @return void
  * @since  1.0
  */
 public function display($tpl = null)
 {
     $isNew = !JRequest::getInt('list_id', false);
     if ($isNew && !AclHelper::actionIsAllowed('list.add') || !$isNew && !AclHelper::actionIsAllowed('list.edit')) {
         $msg = $isNew ? 'JLIB_APPLICATION_ERROR_CREATE_RECORD_NOT_PERMITTED' : 'JLIB_APPLICATION_ERROR_EDIT_NOT_PERMITTED';
         JFactory::getApplication()->redirect(JRoute::_('index.php?option=com_newsletter&view=subscribers', false), JText::_($msg), 'error');
         return;
     }
     //TODO: Bulk-code. Need to refactor
     $listId = JRequest::getInt('list_id', 0);
     switch (JRequest::getString('subtask', '')) {
         case 'import':
             $this->subtask = 1;
             break;
         case 'exclude':
             $this->subtask = 2;
             break;
         default:
             $this->subtask = 0;
     }
     JavaScriptHelper::addStringVar('subtask', $this->subtask);
     $script = $this->get('Script');
     $this->script = $script;
     $this->listForm = $this->get('Form', 'list');
     $this->setModel(JModel::getInstance('subscribers', 'NewsletterModel'));
     $sess = JFactory::getSession();
     $data = $sess->get('list.' . $listId . '.file.uploaded');
     if ($data) {
         JavaScriptHelper::addObject('uploadData', $data);
     }
     $modelSubs = new NewsletterModelSubscribers();
     $modelSubs->setState('list.limit', 10);
     if (!empty($listId)) {
         $this->subs = $modelSubs->getSubscribersByList(array('list_id' => JRequest::getInt('list_id')));
         $items = $modelSubs->getUnsubscribedList(array('list_id' => JRequest::getInt('list_id')));
     } else {
         $items = array();
         $this->subs = array();
     }
     $ss = (object) array('items' => $items, 'state' => $modelSubs->getState(), 'listOrder' => $modelSubs->getState('list.unsubscribed.ordering'), 'listDirn' => $modelSubs->getState('list.unsubscribed.direction'));
     $this->assignRef('subscribers', $ss);
     // get data for "excluded"
     $model = JModel::getInstance('lists', 'NewsletterModel');
     // get only active lists
     $model->setState('filter.fields', array('a.state="1"', 'a.list_id<>' . JRequest::getInt('list_id')));
     $this->lists = (object) array('items' => $model->getItems(), 'state' => $model->getState(), 'listOrder' => $model->getState('list.ordering'), 'listDirn' => $model->getState('list.direction'));
     // Check for errors.
     if (count($errors = $this->get('Errors'))) {
         JError::raiseError(500, implode("\n", $errors));
         return false;
     }
     // We don't need toolbar in the modal window.
     $this->addToolbar();
     $config = JComponentHelper::getParams('com_media');
     $app = JFactory::getApplication();
     $lang = JFactory::getLanguage();
     $append = '';
     if ($config->get('enable_flash', 1)) {
         JHTML::stylesheet('media/com_newsletter/css/uploaders.css');
         JHTML::script(JURI::root() . "administrator/components/com_newsletter/views/list/uploaders.js");
         $fileTypes = $config->get('image_extensions', 'bmp,gif,jpg,png,jpeg');
         $types = explode(',', $fileTypes);
         $displayTypes = '';
         // this is what the user sees
         $filterTypes = '';
         // this is what controls the logic
         $firstType = true;
         foreach ($types as $type) {
             if (!$firstType) {
                 $displayTypes .= ', ';
                 $filterTypes .= '; ';
             } else {
                 $firstType = false;
             }
             $displayTypes .= '*.' . $type;
             $filterTypes .= '*.' . $type;
         }
         $typeString = '{ \'' . JText::_('COM_MEDIA_FILES', 'true') . ' (' . $displayTypes . ')\': \'' . $filterTypes . '\' }';
     }
     /*
      * Display form for FTP credentials?
      * Don't set them here, as there are other functions called before this one if there is any file write operation
      */
     jimport('joomla.client.helper');
     $ftp = !JClientHelper::hasCredentials('ftp');
     $this->assignRef('session', JFactory::getSession());
     $this->assignRef('config', $config);
     $this->assignRef('state', $this->get('state'));
     $this->assignRef('folderList', $this->get('folderList'));
     $this->assign('require_ftp', $ftp);
     $this->setStatisticsData();
     // Set the document
     $this->setDocument();
     parent::display($tpl);
 }
 /**
  * Our specialized json encoder. Strings will be converted to UTF-8. Arrays will be recursively searched and
  * both keys and values made UTF-8. Objects will be converted with json_encode, and so objects that need a special
  * encoding should implement the jsonSerializable interface. See below
  * @param mixed $objValue
  * @return string
  */
 public static function toJSON($objValue)
 {
     assert('is_array($objValue) || is_object($objValue)');
     // json spec says only arrays or objects can be encoded
     $objValue = JavaScriptHelper::MakeJsonEncodable($objValue);
     $strRet = json_encode($objValue);
     if ($strRet === false) {
         throw new QCallerException('Json Encoding Error: ' . json_last_error_msg());
     }
     return $strRet;
 }
 /**
  * PHP __set Magic method
  * @param string $strName Property Name
  * @param string $mixValue Property Value
  *
  * @throws Exception|QInvalidCastException
  */
 public function __set($strName, $mixValue)
 {
     switch ($strName) {
         case 'DataSource':
             // Assign data to a DataSource from within the data binder function only.
             // Data should be array items that at a minimum contain a 'value' and an 'id'
             // They can also contain a 'label', which will be displayed in the popup menu only
             if ($this->blnUseAjax) {
                 $this->prepareAjaxList($mixValue);
             } else {
                 $this->Source = $mixValue;
             }
             break;
         case 'SelectedId':
             // Set this at creation time to initialize the selected id.
             // This is also set by the javascript above to keep track of subsequent selections made by the user.
             try {
                 $this->strSelectedId = QType::Cast($mixValue, QType::String);
             } catch (QInvalidCastException $objExc) {
                 $objExc->IncrementOffset();
                 throw $objExc;
             }
             break;
         case 'MustMatch':
             try {
                 $this->blnMustMatch = QType::Cast($mixValue, QType::Boolean);
                 $this->blnModified = true;
                 // Be sure control gets redrawn
             } catch (QInvalidCastException $objExc) {
                 $objExc->IncrementOffset();
                 throw $objExc;
             }
             break;
         case 'Source':
             try {
                 if (is_array($mixValue) && count($mixValue) > 0 && $mixValue[0] instanceof QListItem) {
                     // figure out what item is selected
                     foreach ($mixValue as $objItem) {
                         if ($objItem->Selected) {
                             $this->strSelectedId = $objItem->Value;
                             $this->Text = $objItem->Name;
                         }
                     }
                 }
                 if ($this->MultipleValueDelimiter) {
                     $strBody = 'response(jQuery.ui.autocomplete.filter(' . JavaScriptHelper::toJsObject($mixValue) . ', this.element.data("curTerm")(this.element.get(0))))';
                     $mixValue = new QJsClosure($strBody, array('request', 'response'));
                 }
                 // do parent action too
                 parent::__set($strName, $mixValue);
             } catch (QInvalidCastException $objExc) {
                 $objExc->IncrementOffset();
                 throw $objExc;
             }
             break;
         case 'MultipleValueDelimiter':
             $a = $this->GetAllActions('QAutocomplete_SourceEvent');
             if (!empty($a)) {
                 throw new Exception('Must set MultipleValueDelimiter BEFORE calling SetDataBinder');
             }
             try {
                 $this->strMultipleValueDelimiter = QType::Cast($mixValue, QType::String);
             } catch (QInvalidCastException $objExc) {
                 $objExc->IncrementOffset();
                 throw $objExc;
             }
             break;
         case 'DisplayHtml':
             try {
                 $this->blnDisplayHtml = QType::Cast($mixValue, QType::Boolean);
             } catch (QInvalidCastException $objExc) {
                 $objExc->IncrementOffset();
                 throw $objExc;
             }
             break;
         default:
             try {
                 parent::__set($strName, $mixValue);
             } catch (QInvalidCastException $objExc) {
                 $objExc->IncrementOffset();
                 throw $objExc;
             }
             break;
     }
 }
Example #17
0
 public function RenderScript(QControl $objControl)
 {
     $strMessage = JavaScriptHelper::toJsObject($this->strMessage);
     return sprintf("alert(%s);", $strMessage);
 }
 /**
  * Default "toJsObject" handler
  * Specifies how the object should be displayed in JQuery UI lists and menus. Note that these lists use
  * value and label differently.
  *
  * value 	= The short form of what to display in the list and selection.
  * label 	= [optional] If defined, is what is displayed in the menu
  * id 		= Primary key of object.
  *
  * @return an array that specifies how to display the object
  */
 public function toJsObject()
 {
     return JavaScriptHelper::toJsObject(array('value' => $this->__toString(), 'id' => $this->intId));
 }
 /**
  * @deprecated since Qcubed 2.1.1. Please use QListItem
  * @return string
  */
 public function toJsObject()
 {
     trigger_error("QAutocompleteListItem has been deprecated. Please use QListItem", E_USER_NOTICE);
     return JavaScriptHelper::toJsObject(array("value" => $this->Name, "id" => $this->Value));
 }
Example #20
0
 /**
  * Call a JQuery UI Method on the object. 
  * 
  * A helper function to call a jQuery UI Method. Takes variable number of arguments.
  * 
  * @param string $strMethodName the method name to call
  * @internal param $mixed [optional] $mixParam1
  * @internal param $mixed [optional] $mixParam2
  */
 protected function CallJqUiMethod($strMethodName)
 {
     $args = func_get_args();
     $strArgs = JavaScriptHelper::toJsObject($args);
     $strJs = sprintf('jQuery("#%s").%s(%s)', $this->getJqControlId(), $this->getJqSetupFunction(), substr($strArgs, 1, strlen($strArgs) - 2));
     // params without brackets
     QApplication::ExecuteJavaScript($strJs);
 }
 /**
  * Applies CSS styles to a button that is already in the dialog.
  *
  * @param string $strButtonId Id of button to set the style on
  * @param array $styles Array of key/value style specifications
  */
 public function SetButtonStyle($strButtonId, $styles)
 {
     QApplication::ExecuteJavaScript(sprintf('$j("#%s").next().find("button[data-btnid=\'%s\']").css(%s)', $this->getJqControlId(), $strButtonId, JavaScriptHelper::toJsObject($styles)));
 }
/**
 * Returns a stringified version of a backtrace.
 * Set $blnShowArgs if you want to see a representation of the arguments. Note that if you are sending
 * in objects, this will unpack the entire structure and display its contents.
 * $intSkipTraces is how many back traces you want to skip. Set this to at least one to skip the
 * calling of this function itself.
 *
 * @param bool $blnShowArgs
 * @param int $intSkipTraces
 * @return string
 */
function QcubedGetBacktrace($blnShowArgs = false, $intSkipTraces = 1)
{
    if (!$blnShowArgs) {
        $b = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
    } else {
        $b = debug_backtrace(false);
    }
    $strRet = "";
    for ($i = $intSkipTraces; $i < count($b); $i++) {
        $item = $b[$i];
        $strFile = array_key_exists("file", $item) ? $item["file"] : "";
        $strLine = array_key_exists("line", $item) ? $item["line"] : "";
        $strClass = array_key_exists("class", $item) ? $item["class"] : "";
        $strType = array_key_exists("type", $item) ? $item["type"] : "";
        $strFunction = array_key_exists("function", $item) ? $item["function"] : "";
        $vals = [];
        if (!empty($item["args"])) {
            foreach ($item["args"] as $val) {
                $vals[] = JavaScriptHelper::toJsObject($val);
            }
        }
        $strArgs = implode(", ", $vals);
        $strRet .= sprintf("#%s %s(%s): %s%s%s(%s)\n", $i, $strFile, $strLine, $strClass, $strType, $strFunction, $strArgs);
    }
    return $strRet;
}
 /**
  * Removes the given data attribute.
  * @param $strName
  */
 public function RemoveDataAttribute($strName)
 {
     $strName = 'data-' . JavaScriptHelper::dataNameFromCamelCase($strName);
     $this->RemoveHtmlAttribute($strName);
 }