/**
  * Method to instantiate the view.
  *
  * @param Model             $model     The model object.
  * @param Container         $container DI Container.
  * @param array             $config    View config.
  * @param \SplPriorityQueue $paths     Paths queue.
  */
 public function __construct(Model $model = null, Container $container = null, $config = array(), \SplPriorityQueue $paths = null)
 {
     parent::__construct($model, $container, $config, $paths);
     if (!$this->toolbarConfig) {
         $this->toolbarConfig = ArrayHelper::getValue($config, 'toolbar', array());
     }
 }
 /**
  * Render the profiler log data, and echo it..
  *
  * @param   string   $namespace The JProfiler instance ID. Default is the core profiler "Application".
  * @param   boolean  $asString  Return as string.
  *
  * @return  string
  */
 public static function render($namespace = 'Windwalker', $asString = false)
 {
     $app = Container::getInstance()->get('app');
     if ($namespace == 'core' || !$namespace) {
         $namespace = 'Application';
     }
     if (isset(self::$profiler[$namespace])) {
         $_PROFILER = self::$profiler[$namespace];
         $buffer = $_PROFILER->getBuffer();
         $buffer = implode("\n<br />\n", $buffer);
     } else {
         $buffer = $app->getUserState('windwalker.system.profiler.' . $namespace, array());
         $buffer = $buffer ? implode("\n<br />\n", $buffer) : '';
     }
     $buffer = $buffer ? $buffer : 'No Profiler data.';
     // Get last page logs
     $state_buffer = ArrayHelper::getValue(self::$stateBuffer, $namespace);
     if ($state_buffer) {
         $state_buffer = implode("\n<br />\n", $state_buffer);
         $buffer = $state_buffer . "\n<br />---------<br />\n" . $buffer;
     }
     // Render
     $buffer = "<pre><h3>WindWalker Debug [namespace: {$namespace}]: </h3>" . $buffer . '</pre>';
     $app->setUserState('windwalker.system.profiler.' . $namespace, '');
     if ($asString) {
         return $buffer;
     }
     echo $buffer;
     return '';
 }
 /**
  * Method to get a form object.
  *
  * @param   string    $name    The name of the form.
  * @param   string    $source  The form source. Can be XML string if file flag is set to false.
  * @param   array     $options Optional array of options for the form creation.
  * @param   boolean   $clear   Optional argument to force load a new form.
  * @param   string    $xpath   An optional xpath to search for the fields.
  *
  * @throws \Exception
  * @return  mixed  JForm object on success, False on error.
  *
  * @see     JForm
  */
 protected function loadForm($name, $source = null, $options = array(), $clear = false, $xpath = null)
 {
     // Handle the optional arguments.
     $options['control'] = ArrayHelper::getValue($options, 'control', false);
     // Create a signature hash.
     $hash = sha1($source . serialize($options));
     // Check if we can use a previously loaded form.
     if (isset($this->forms[$hash]) && !$clear) {
         return $this->forms[$hash];
     }
     // Set Form paths
     static $formLoaded;
     if (!$formLoaded) {
         // Get the form.
         // Register the paths for the form
         $paths = new \SplPriorityQueue();
         $paths->insert(JPATH_COMPONENT . '/model/form', 'normal');
         $paths->insert(JPATH_COMPONENT . '/model/field', 'normal');
         $paths->insert(JPATH_COMPONENT . '/model/rule', 'normal');
         // Legacy support to be removed in 4.0.
         $paths->insert(JPATH_COMPONENT . '/models/forms', 'normal');
         $paths->insert(JPATH_COMPONENT . '/models/fields', 'normal');
         $paths->insert(JPATH_COMPONENT . '/models/rules', 'normal');
         \JForm::addFormPath(JPATH_COMPONENT . '/models/forms');
         \JForm::addFieldPath(JPATH_COMPONENT . '/models/fields');
         \JForm::addRulePath(JPATH_COMPONENT . '/models/rules');
         \JForm::addFormPath(JPATH_COMPONENT . '/model/form');
         \JForm::addFieldPath(JPATH_COMPONENT . '/model/field');
         \JForm::addRulePath(JPATH_COMPONENT . '/model/rule');
         // Set Form paths for Windwalker
         \JForm::addFormPath(JPATH_COMPONENT . '/model/form/' . strtolower($this->getName()));
         \JForm::addFieldPath(JPATH_COMPONENT . '/model/field/' . strtolower($this->getName()));
         \JForm::addRulePath(JPATH_COMPONENT . '/model/rule/' . strtolower($this->getName()));
         $formLoaded = true;
     }
     try {
         $form = \JForm::getInstance($name, $source, $options, false, $xpath);
         if (isset($options['load_data']) && $options['load_data']) {
             // Get the data for the form.
             $data = $this->loadFormData();
         } else {
             $data = array();
         }
         // Allow for additional modification of the form, and events to be triggered.
         // We pass the data because plugins may require it.
         $this->preprocessForm($form, $data);
         // Load the data into the form after the plugins have operated.
         $form->bind($data);
     } catch (\Exception $e) {
         throw $e;
     }
     // Store the form for later.
     $this->forms[$hash] = $form;
     return $form;
 }
示例#4
0
 /**
  * Parse variable and replace it. This method is a simple template engine.
  *
  * Example: The {{ foo.bar.yoo }} will be replace to value of `$data['foo']['bar']['yoo']`
  *
  * @param   string $string The template to replace.
  * @param   array  $data   The data to find.
  * @param   array  $tags   The variable tags.
  *
  * @return  string Replaced template.
  */
 public static function parseVariable($string, $data = array(), $tags = array('{{', '}}'))
 {
     return preg_replace_callback('/\\{\\{\\s*(.+?)\\s*\\}\\}/', function ($match) use($data) {
         $return = ArrayHelper::getByPath($data, $match[1]);
         if (is_array($return) || is_object($return)) {
             return print_r($return, 1);
         } else {
             return $return;
         }
     }, $string);
 }
 /**
  * Instantiate the controller.
  *
  * @param   \JInput           $input   The input object.
  * @param   \JApplicationCms  $app     The application object.
  * @param   array             $config  Alternative config.
  */
 public function __construct(\JInput $input = null, \JApplicationCms $app = null, $config = array())
 {
     parent::__construct($input, $app, $config);
     // Guess the item view as the context.
     $this->viewList = $this->viewList ?: ArrayHelper::getValue($config, 'view_list', $this->getName());
     // Guess the list view as the plural of the item view.
     $this->viewItem = $this->viewItem ?: ArrayHelper::getValue($config, 'view_item');
     if (empty($this->viewItem)) {
         $inflector = Inflector::getInstance();
         $this->viewItem = $inflector->toSingular($this->viewList);
     }
 }
 /**
  * Method to run this controller.
  *
  * @return  mixed
  */
 protected function doExecute()
 {
     // Init Variables
     $data = $this->input->get($this->input->get('formctrl'), array(), 'array');
     $result = new \JRegistry();
     $result->set('Result', false);
     $model_name = $this->input->get('model_name');
     $component = $this->input->get('component');
     $extension = $this->input->get('extension');
     // Include Needed Classes
     \JModelLegacy::addIncludePath(JPATH_BASE . "/components/com_{$component}/models");
     \JForm::addFormPath(JPATH_BASE . "/components/com_{$component}/models/forms");
     \JForm::addFieldPath(JPATH_BASE . "/components/com_{$component}/models/fields");
     \JTable::addIncludePath(JPATH_BASE . "/components/com_{$component}/tables");
     LanguageHelper::loadLanguage($extension, null);
     // Get Model
     $model = \JModelLegacy::getInstance(ucfirst($model_name), ucfirst($component) . 'Model', array('ignore_request' => true));
     // For WindWalker Component only
     if (is_callable(array($model, 'getFieldsName'))) {
         $fields_name = $model->getFieldsName();
         $data = ArrayHelper::pivotToTwoDimension($data, $fields_name);
     }
     // Get Form
     $form = $model->getForm($data, false);
     if (!$form) {
         $result->set('errorMsg', $model->getError());
         jexit($result);
     }
     // Test whether the data is valid.
     $validData = $model->validate($form, $data);
     // Check for validation errors.
     if ($validData === false) {
         // Get the validation messages.
         $errors = $model->getErrors();
         $errorMsg = is_string($errors[0]) ? $errors[0] : $errors[0]->getMessage();
         $result->set('errorMsg', $errorMsg);
         jexit($result);
     }
     // Do Save
     if (!$model->save($validData)) {
         // Return Error Message.
         $result->set('errorMsg', \JText::sprintf('JLIB_APPLICATION_ERROR_SAVE_FAILED', $model->getError()));
         jexit($result);
     }
     // Set ID
     $data['id'] = $model->getstate($model_name . '.id');
     // Set Result
     $result->set('Result', true);
     $result->set('data', $data);
     jexit($result);
 }
 /**
  * doRender
  *
  * @param string            $name
  * @param XulEngine         $engine
  * @param \SimpleXmlElement $element
  * @param mixed             $data
  *
  * @throws \LogicException
  * @return  mixed
  */
 protected static function doRender($name, XulEngine $engine, \SimpleXmlElement $element, $data)
 {
     $itemsKey = XmlHelper::get($element, 'data', 'items');
     $items = (array) ArrayHelper::getByPath($data, $itemsKey);
     $rows = new HtmlElements();
     foreach ($items as $i => $item) {
         // Prepare data
         $item = new Data($item);
         $data->xulControl->currentItem = $item;
         // Prepare item for GridHelper
         $data->grid->setItem($item, $i);
         $rows[] = RowRenderer::render('row', $engine, $element, $data);
     }
     return $rows;
 }
    /**
     * The link to open modal.
     *
     * @param   string  $title    Modal title.
     * @param   string  $selector Modal select ID.
     * @param   array   $option   Modal params.
     *
     * @return  string  Link body text.
     */
    public static function modalLink($title, $selector, $option = array())
    {
        $tag = ArrayHelper::getValue($option, 'tag', 'a');
        $id = isset($option['id']) ? " id=\"{$option['id']}\"" : " id=\"{$selector}_link\"";
        $class = isset($option['class']) ? " class=\"{$option['class']} cursor-pointer\"" : ' class="cursor-pointer"';
        $onclick = isset($option['onclick']) ? " onclick=\"{$option['onclick']}\"" : '';
        $icon = ArrayHelper::getValue($option, 'icon', '');
        $button = <<<HTML
<{$tag} data-toggle="modal" data-target="#{$selector}"{$id}{$class}{$onclick}>
\t<i class="{$icon}" title="{$title}"></i>
\t{$title}
</{$tag}>
HTML;
        return $button;
    }
 /**
  * doRender
  *
  * @param string            $name
  * @param \SimpleXmlElement $element
  * @param mixed             $data
  *
  * @throws \LogicException
  * @return  mixed
  */
 protected static function doRender($name, XulEngine $engine, \SimpleXmlElement $element, $data)
 {
     $dataKey = XmlHelper::get($element, 'data');
     $sidebar = $dataKey ? ArrayHelper::getByPath($data, $dataKey) : $data->sidebar;
     if (empty($sidebar)) {
         return '';
     }
     $html = new HtmlElements();
     $html[] = new HtmlElement('h4', JText::_(XmlHelper::get($element, 'title', 'JOPTION_MENUS')));
     $html[] = $sidebar;
     $element->addChild('block', $html);
     if (!isset($data->view->colSpan)) {
         throw new \LogicException('Please put "sidebar" tag in "row" tag.');
     }
     return parent::doRender($name, $engine, $element, $data);
 }
示例#10
0
 /**
  * Constructor
  *
  * @param   array              $config    An array of configuration options (name, state, dbo, table_path, ignore_request).
  * @param   JoomlaContainer    $container Service container.
  * @param   \JRegistry         $state     The model state.
  * @param   \JDatabaseDriver   $db        The database adapter.
  */
 public function __construct($config = array(), JoomlaContainer $container = null, \JRegistry $state = null, \JDatabaseDriver $db = null)
 {
     parent::__construct($config, $container, $state, $db);
     if (!$this->reorderConditions) {
         $this->reorderConditions = ArrayHelper::getValue($config, 'reorder_conditions', array('catid'));
     }
     // Guess the item view as the context.
     if (empty($this->viewItem)) {
         $this->viewItem = $this->getName();
     }
     // Guess the list view as the plural of the item view.
     if (empty($this->viewList)) {
         $inflector = Inflector::getInstance();
         $this->viewList = $inflector->toPlural($this->viewItem);
     }
 }
 /**
  * Execute this command.
  *
  * @return int|void
  */
 protected function doExecute()
 {
     $tableModel = new Table();
     $statuses = $tableModel->status();
     $tables = ArrayHelper::getColumn($statuses, 'table');
     $maxLength = max(array_map('strlen', $tables));
     // Show message
     $this->out()->out('Track Status:')->out();
     $titleSpaces = $maxLength - 5;
     $this->out(sprintf("TABLE NAME %-{$titleSpaces}s STATUS", ''));
     $this->out('---------------------------------------------------------------');
     // List table & status
     foreach ($statuses as $status) {
         $spaces = $maxLength - strlen($status['table']) + 4;
         $this->out(sprintf("- %s %-{$spaces}s %s", $status['table'], '', $status['status']));
     }
 }
    /**
     * Add jQuery highlight plugin.
     *
     * @param  string  $selector  The selector to make highlight.
     * @param  string  $text      The text to mark.
     * @param  array   $options   The options of this script.
     *
     * @see  http://bartaz.github.io/sandbox.js/jquery.highlight.html
     *
     * @return  void
     */
    public static function highlight($selector = '.hasHighlight', $text = null, $options = array())
    {
        $asset = static::getAsset();
        if (!static::inited(__METHOD__)) {
            JQueryScript::core();
            $asset->addJS('jquery/jquery.highlight.js');
        }
        if (!static::inited(__METHOD__, func_get_args()) && $selector && $text) {
            if (is_array($text)) {
                $text = implode(' ', $text);
            }
            $defaultOptions = array('element' => 'mark', 'className' => 'windwalker-highlight');
            $options = $asset::getJSObject(ArrayHelper::merge($defaultOptions, $options));
            $js = <<<JS
// Highlight Text
jQuery(document).ready(function(\$)
{
\t\$('{$selector}').highlight('{$text}', {$options});
});
JS;
            $asset->internalJS($js);
        }
    }
示例#13
0
 /**
  * getArguments
  *
  * @param \SimpleXmlElement $element
  * @param mixed             $data
  *
  * @return  array
  */
 protected static function getArguments($element, $data, $argumrntTag = 'argument')
 {
     $args = $element->xpath($argumrntTag);
     $return = array();
     foreach ($args as $arg) {
         if (isset($arg['data'])) {
             $return[] = ArrayHelper::getByPath($data, (string) $arg['data']);
         } else {
             if (strtolower($arg) == 'null') {
                 $arg = null;
             }
             if (strtolower($arg) == 'false') {
                 $arg = false;
             }
             $return[] = String::parseVariable((string) $arg, $data);
         }
     }
     return $return;
 }
示例#14
0
 /**
  * Query a two-dimensional array values to get second level array.
  *
  * This is a clone from Windwalke RAD 2.1, will be remove if RAD 2.1 released.
  *
  * @param   array    $array    An array to query.
  * @param   mixed    $queries  Query strings, may contain Comparison Operators: '>', '>=', '<', '<='.
  *                             Example:
  *                             array(
  *                                 'id'         => 6,   // Get all elements where id=6
  *                                 '>published' => 0    // Get all elements where published>0
  *                             );
  * @param   boolean  $strict   Use strict to compare equals.
  * @param   boolean  $keepKey  Keep origin array keys.
  *
  * @return  array  An new two-dimensional array queried.
  *
  * @since   2.0
  */
 public static function query($array, $queries = array(), $strict = false, $keepKey = false)
 {
     $results = array();
     $queries = (array) $queries;
     // Visit Array
     foreach ((array) $array as $k => $v) {
         $data = (array) $v;
         /*
          * Key: is query key
          * Val: is query value
          * Data: is array element
          */
         $boolean = array();
         // Visit Query Rules
         foreach ($queries as $key => $val) {
             if (substr($key, -2) == '>=') {
                 $boolean[] = ArrayHelper::getByPath($data, trim(substr($key, 0, -2))) >= $val;
             } elseif (substr($key, -2) == '<=') {
                 $boolean[] = ArrayHelper::getByPath($data, trim(substr($key, 0, -2))) <= $val;
             } elseif (substr($key, -1) == '>') {
                 $boolean[] = ArrayHelper::getByPath($data, trim(substr($key, 0, -1))) > $val;
             } elseif (substr($key, -1) == '<') {
                 $boolean[] = ArrayHelper::getByPath($data, trim(substr($key, 0, -1))) < $val;
             } else {
                 if ($strict) {
                     $boolean[] = ArrayHelper::getByPath($data, $key) === $val;
                 } else {
                     // Workaround for PHP 5.4 object compare bug, see: https://bugs.php.net/bug.php?id=62976
                     $compare1 = is_object(ArrayHelper::getByPath($data, $key)) ? get_object_vars(ArrayHelper::getByPath($data, $key)) : ArrayHelper::getByPath($data, $key);
                     $compare2 = is_object($val) ? get_object_vars($val) : $val;
                     $boolean[] = $compare1 == $compare2;
                 }
             }
         }
         // Set Query results
         if (!in_array(false, $boolean, true)) {
             if ($keepKey) {
                 $results[$k] = $v;
             } else {
                 $results[] = $v;
             }
         }
     }
     return $results;
 }
 /**
  * Register all buttons.
  *
  * @return  void
  */
 public function registerButtons()
 {
     $buttons = $this->buttonSet;
     $queue = new \SplPriorityQueue();
     foreach ($buttons as $name => $button) {
         $priority = isset($priority) ? ArrayHelper::getValue($button, 'priority', $priority + 10) : 9999;
         $queue->insert($name, $priority);
     }
     foreach ($queue as $name) {
         $this->register($name, $buttons[$name]);
     }
 }
示例#16
0
 /**
  * Gets the value of a user state variable and sets it in the session
  *
  * This is the same as the method in JApplication except that this also can optionally
  * force you back to the first page when a filter has changed
  *
  * @param   string   $key        The key of the user state variable.
  * @param   string   $request    The name of the variable passed in a request.
  * @param   string   $default    The default value for the variable if not found. Optional.
  * @param   string   $type       Filter for the variable, for valid values see {@link \JFilterInput::clean()}. Optional.
  * @param   boolean  $resetPage  If true, the limitstart in request is set to zero
  *
  * @return  array The request user state.
  */
 public function getUserStateFromRequest($key, $request, $default = null, $type = 'none', $resetPage = true)
 {
     /** @var \JApplicationCms $app */
     $app = $this->container->get('app');
     $input = $app->input;
     $oldState = $app->getUserState($key);
     $currentState = !is_null($oldState) ? $oldState : $default;
     $newState = $input->get($request, null, $type);
     /*
      * In RAD, filter & search is array with default elements,
      * so we can't directly compare them with empty value.
      * Here prepare some default value to compare them.
      */
     // Remove empty values from input, because session registry will remove empty values too.
     if ($request == 'filter' && is_array($newState)) {
         $newState = ArrayHelper::filterRecursive($newState, 'strlen');
     }
     // Add default field name '*' if we clear filter bar.
     if ($request == 'search' && '' === (string) ArrayHelper::getValue($currentState, 'field')) {
         $currentState['field'] = '*';
     }
     // Now compare them, and set start to 0 if there has any differences.
     if ($newState && $currentState != $newState && $resetPage) {
         $input->set('limitstart', 0);
     }
     // Save the new value only if it is set in this request.
     if ($newState !== null) {
         $app->setUserState($key, $newState);
     } else {
         $newState = $currentState;
     }
     return $newState;
 }
示例#17
0
 /**
  * getItems
  *
  * @return  array
  */
 public function getItems()
 {
     $db = JFactory::getDbo();
     $q = $db->getQuery(true);
     $params = $this->getParams();
     $temp = $this->temp;
     $categories = $this->getCategories();
     $r = '';
     if (is_file($temp)) {
         $r = file_get_contents($temp);
     }
     $r = json_decode($r);
     if (isset($r->data)) {
         foreach ($r->data as $key => &$item) {
             $item = new JObject($item);
             $item->continue = false;
             if (!property_exists($item, 'message')) {
                 unset($r->data[$key]);
                 $item->continue = true;
                 continue;
             }
             // Separate First Line As Title
             // ====================================================================
             $item->message = nl2br($item->message);
             $item->message = explode('<br />', $item->message);
             $item->title = $title = array_shift($item->message);
             $item->title = str_ireplace('https://', '', $item->title);
             $item->title = str_ireplace('http://', '', $item->title);
             // Set message and id
             $item->message = implode('<br />', $item->message);
             $item->id = explode('_', $item->id);
             $item->id = $item->id[1];
             // Set Category Detect Rules
             // ====================================================================
             $escape = "[]{}()\$^.*?-=+&%#!";
             $lft = $params->get('category_match_left');
             $rgt = $params->get('category_match_right');
             if (strpos($escape, $lft) !== false) {
                 $lft = '\\' . $lft;
             }
             if (strpos($escape, $rgt) !== false) {
                 $rgt = '\\' . $rgt;
             }
             // Match Category Name
             // ====================================================================
             $regex = "/{$lft}(.*){$rgt}(.*)/";
             preg_match($regex, trim($title), $matches);
             // get cat name
             $item->catid = null;
             $item->cat_matched = 0;
             if (isset($matches[1]) && $matches[2]) {
                 $category_name = trim($matches[1]);
                 $result = \Windwalker\Helper\ArrayHelper::query($categories, array('title' => strtolower($category_name)));
                 if (count($result) > 0) {
                     $item->catid = $result[0]->id;
                     $item->title = trim($matches[2]);
                     $item->cat_name = $category_name;
                     $item->cat_matched = 1;
                 }
             } else {
                 // If not match, continue
                 if ($params->get('category_not_match_continue')) {
                     $item->continue = true;
                 }
             }
             // title Max Char
             // ====================================================================
             $max = $params->get('title_max_char');
             if ($max) {
                 if (JString::strlen($item->title) > $max) {
                     $item->message = JString::substr($item->title, $max) . "\n\n" . $item->message;
                     $title = JString::substr($item->title, 0, $max);
                     $title = explode(' ', $title);
                     $last_word = array_pop($title);
                     if ($last_word && JString::strlen($last_word) < 10) {
                         $item->message = $last_word . $item->message;
                     } else {
                         $title[] = $last_word;
                     }
                     $item->title = implode(' ', $title);
                 }
             }
             // Get date & alias
             // ====================================================================
             $q->clear();
             $item->date = JFactory::getDate($item->created_time, JFactory::getConfig()->get('offset'));
             $item->alias = JFilterOutput::stringURLSafe($item->title . ' ' . $item->date->format('Y-m-d-H-i-s', true));
             $q->select('id')->from('#__content')->where("alias = '{$item->alias}'");
             $db->setQuery($q);
             $itemid = $db->loadResult();
             $q->clear();
             $item->exists = $itemid;
         }
         return $r->data;
     } else {
         return array();
     }
 }
示例#18
0
 /**
  * Constructor
  *
  * @param   array              $config    An array of configuration options (name, state, dbo, table_path, ignore_request).
  * @param   JoomlaContainer    $container Service container.
  * @param   Registry           $state     The model state.
  * @param   \JDatabaseDriver   $db        The database adapter.
  *
  * @throws \Exception
  */
 public function __construct($config = array(), JoomlaContainer $container = null, Registry $state = null, \JDatabaseDriver $db = null)
 {
     $this->prefix = $this->getPrefix($config);
     $this->option = 'com_' . $this->prefix;
     // Guess name
     $this->name = $this->name ?: ArrayHelper::getValue($config, 'name', $this->getName());
     // Register the paths for the form
     $this->registerTablePaths($config);
     // Set the clean cache event
     $this->eventCleanCache = $this->eventCleanCache ?: ArrayHelper::getValue($config, 'event_clean_cache', 'onContentCleanCache');
     $this->container = $container ?: $this->getContainer();
     $this->resetCache();
     parent::__construct($state, $db);
     $this->state->loadArray($config);
     // Guess the context as Option.ModelName.
     $this->context = $this->context ?: ContextHelper::fromModel($this);
     // Set the internal state marker - used to ignore setting state from the request
     if (empty($config['ignore_request'])) {
         // Protected method to auto-populate the model state.
         $this->populateState();
     }
 }
示例#19
0
<?php

/**
 * Part of Windwalker project.
 *
 * @copyright  Copyright (C) 2011 - 2014 SMS Taiwan, Inc. All rights reserved.
 * @license    GNU General Public License version 2 or later; see LICENSE
 */
use Windwalker\Helper\ArrayHelper;
defined('JPATH_BASE') or die;
$data = $displayData['view'];
$textPrefix = $data->view->option ?: 'LIB_WINDWALKER';
$task = ArrayHelper::getValue($displayData, 'task_prefix', '');
?>

<div class="modal hide fade" id="batchModal">
	<div class="modal-header">
		<button type="button" role="presentation" class="close" data-dismiss="modal">x</button>
		<h3><?php 
echo JText::_($textPrefix . '_BATCH_OPTIONS');
?>
</h3>
	</div>

	<div class="modal-body form-horizontal">
		<p>
			<?php 
echo JText::_($textPrefix . '_BATCH_TIP');
?>
		</p>
示例#20
0
 /**
  * A download function to hide real file path. When call this function, will start download instantly.
  *
  * This function should call when view has not executed yet, if header sended,
  *  the file which downloaded will error, because download by stream will
  *  contain header in this file.
  *
  * @param   string  $path     The file system path with filename & type.
  * @param   boolean $absolute Absolute URL or not.
  * @param   boolean $stream   Use stream or redirect to download.
  * @param   array   $option   Some download options.
  *
  * @return  string
  */
 public static function download($path, $absolute = false, $stream = false, $option = array())
 {
     $test = self::$isTest;
     static::$headerBuffer = array();
     if ($stream) {
         if (!$absolute) {
             $path = JPATH_ROOT . '/' . $path;
         }
         if (!is_file($path)) {
             return $test ?: die;
         }
         $file = pathinfo($path);
         $filesize = filesize($path) + ArrayHelper::getValue($option, 'size_offset', 0);
         ini_set('memory_limit', ArrayHelper::getValue($option, 'memory_limit', '1540M'));
         // Set Header
         static::header('Content-Type: application/octet-stream');
         static::header('Cache-Control: no-store, no-cache, must-revalidate');
         static::header('Cache-Control: pre-check=0, post-check=0, max-age=0');
         static::header('Content-Transfer-Encoding: binary');
         static::header('Content-Encoding: none');
         static::header('Content-type: application/force-download');
         static::header('Content-length: ' . $filesize);
         static::header('Content-Disposition: attachment; filename="' . $file['basename'] . '"');
         $handle = fopen($path, 'rb');
         $chunksize = 1 * (1024 * 1024);
         // Start Download File by Stream
         while (!feof($handle)) {
             $buffer = fread($handle, $chunksize);
             echo $buffer;
             $test or ob_flush();
             $test or flush();
         }
         fclose($handle);
         $test or jexit();
     } else {
         if (!$absolute) {
             $path = \JURI::root() . $path;
         }
         // Redirect it.
         $app = Container::getInstance()->get('app');
         $test or $app->redirect($path);
         return $path;
     }
 }
 /**
  * Method to instantiate the view.
  *
  * @param Model      $model     The model object.
  * @param Container  $container DI Container.
  * @param array      $config    View config.
  */
 public function __construct(Model $model = null, Container $container = null, $config = array())
 {
     // Setup dependencies.
     if ($model) {
         $modelName = $model->getName();
         $this->defaultModel = strtolower($modelName);
         $this->model[strtolower($modelName)] = $model;
     }
     // Prepare data
     $this->data = $this->data ?: ArrayHelper::getValue($config, 'data', new Data());
     // Prepare prefix
     $this->prefix = $this->prefix ?: ArrayHelper::getValue($config, 'prefix', $this->getPrefix());
     // Prepare option
     $this->option = $this->option ?: ArrayHelper::getValue($config, 'option', 'com_' . $this->prefix);
     // Prepare name
     $this->name = $this->name ?: ArrayHelper::getValue($config, 'name', $this->getName());
     // Prepare textPrefix
     $this->textPrefix = $this->textPrefix ?: ArrayHelper::getValue($config, 'text_prefix', $this->option);
     $this->textPrefix = strtoupper($this->textPrefix);
     $this->container = $container ?: Container::getInstance($this->option);
 }
示例#22
0
 /**
  * Parse element data JSON format to array.
  *
  * @param    string $attrs A JSON string.
  *
  * @return   array     Attributes array.
  */
 public function parseAttrs($attrs)
 {
     if (!$attrs) {
         return false;
     }
     $array = (array) json_decode($attrs, true);
     // Rebuild Options
     // ==================================================================
     if (isset($array['options'])) {
         $array['options'] = ArrayHelper::pivotByKey($array['options']);
     }
     return $array;
 }
示例#23
0
 /**
  * Build route.
  *
  * @param   array  &$data The query data to build route.
  *
  * @return  string Route url.
  */
 public static function build(&$data = array())
 {
     $menu = \JFactory::getApplication()->getMenu();
     $items = $menu->getMenu();
     $Itemid = null;
     $data['view'] = isset($data['view']) ? $data['view'] : null;
     // If itemid exists and view not, use itemid as menu item
     if (isset($data['Itemid']) && empty($data['view'])) {
         if ($item = $menu->getItem($data['Itemid'])) {
             $data['Itemid'] = $item->id;
             return $data;
         }
     }
     // Find option, view and id
     if (!empty($data['id'])) {
         foreach ($items as $item) {
             $option = ArrayHelper::getValue($item->query, 'option');
             $view = ArrayHelper::getValue($item->query, 'view');
             $id = ArrayHelper::getValue($item->query, 'id');
             if ($option == $data['option'] && $view == $data['view'] && $id == $data['id']) {
                 $data['Itemid'] = $item->id;
                 return $data;
             }
         }
     }
     // Find option and view
     if (!$Itemid && !empty($data['view'])) {
         foreach ($items as $item) {
             $option = ArrayHelper::getValue($item->query, 'option');
             $view = ArrayHelper::getValue($item->query, 'view');
             if ($option == $data['option'] && $view == $data['view']) {
                 unset($data['view']);
                 $data['Itemid'] = $item->id;
                 return $data;
             }
         }
     }
     // Find option
     if (!$Itemid && empty($data['view'])) {
         foreach ($items as $item) {
             $option = ArrayHelper::getValue($item->query, 'option');
             if ($option == $data['option']) {
                 $data['Itemid'] = $item->id;
                 return $data;
             }
         }
     }
     return $data;
 }
 /**
  * Method to test merge
  *
  * @covers \Windwalker\Helper\ArrayHelper::merge
  *
  * @return void
  */
 public function testMerge()
 {
     $data1 = array('green' => 'Hulk', 'red' => 'empty', 'human' => array('dark' => 'empty', 'black' => array('male' => 'empty', 'female' => 'empty', 'no-gender' => 'empty')));
     $data2 = array('ai' => 'Jarvis', 'agent' => 'Phil Coulson', 'red' => array('left' => 'Pepper', 'right' => 'Iron Man'), 'human' => array('dark' => 'Nick Fury', 'black' => array('female' => 'Black Widow', 'male' => 'Loki')));
     $expected = array('ai' => 'Jarvis', 'agent' => 'Phil Coulson', 'green' => 'Hulk', 'red' => array('left' => 'Pepper', 'right' => 'Iron Man'), 'human' => array('dark' => 'Nick Fury', 'black' => array('male' => 'Loki', 'female' => 'Black Widow', 'no-gender' => 'empty')));
     $expected2 = array('ai' => 'Jarvis', 'agent' => 'Phil Coulson', 'green' => 'Hulk', 'red' => array('left' => 'Pepper', 'right' => 'Iron Man'), 'human' => array('dark' => 'Nick Fury', 'black' => array('male' => 'Loki', 'female' => 'Black Widow')));
     $this->assertEquals($expected, ArrayHelper::merge($data1, $data2));
     $this->assertEquals($expected2, ArrayHelper::merge($data1, $data2, false));
 }
 /**
  * Internal method to get a JavaScript object notation string from an array.
  *
  * You can add \\ before a function string that this string will keep as a real JS function.
  *
  * @param   mixed  $data      The data to convert to JS object.
  * @param   bool   $quoteKey  Quote key by double quote or not.
  *                            - TRUE:  {"key":"value"}
  *                            - FALSE: {key:"value"}
  *
  * @return  string  JavaScript object notation representation of the array
  */
 public static function getJSObject($data, $quoteKey = true)
 {
     if ($data === null) {
         return 'null';
     }
     $output = '';
     switch (gettype($data)) {
         case 'boolean':
             $output .= $data ? 'true' : 'false';
             break;
         case 'float':
         case 'double':
         case 'integer':
             $output .= $data + 0;
             break;
         case 'array':
             if (!ArrayHelper::isAssociative($data)) {
                 $child = array();
                 foreach ($data as $value) {
                     $child[] = static::getJSObject($value, $quoteKey);
                 }
                 $output .= '[' . implode(',', $child) . ']';
                 break;
             }
         case 'object':
             $array = is_object($data) ? get_object_vars($data) : $data;
             $row = array();
             foreach ($array as $key => $value) {
                 $key = json_encode($key);
                 if (!$quoteKey) {
                     $key = substr(substr($key, 0, -1), 1);
                 }
                 $row[] = $key . ':' . static::getJSObject($value, $quoteKey);
             }
             $output .= '{' . implode(',', $row) . '}';
             break;
         default:
             // anything else is treated as a string
             return strpos($data, '\\') === 0 ? substr($data, 1) : json_encode($data);
             break;
     }
     return $output;
 }
示例#26
0
 /**
  * Method to save the form data.
  *
  * @param   array  $data  The form data.
  *
  * @throws  \Exception
  * @return  boolean  True on success, False on error.
  */
 public function save($data)
 {
     $container = $this->getContainer();
     $table = $this->getTable();
     $dispatcher = $container->get('event.dispatcher');
     if (!empty($data['tags']) && $data['tags'][0] != '') {
         $table->newTags = $data['tags'];
     }
     $key = $table->getKeyName();
     $pk = ArrayHelper::getValue($data, $key, $this->getState($this->getName() . '.id'));
     $isNew = true;
     // Include the content plugins for the on save events.
     \JPluginHelper::importPlugin('content');
     // Load the row if saving an existing record.
     if ($pk) {
         $table->load($pk);
         $isNew = false;
     }
     // Bind the data.
     $table->bind($data);
     // Prepare the row for saving
     $this->prepareTable($table);
     // Check the data.
     if (!$table->check()) {
         throw new \Exception($table->getError());
     }
     // Trigger the onContentBeforeSave event.
     $result = $dispatcher->trigger($this->eventBeforeSave, array($this->option . '.' . $this->name, $table, $isNew));
     if (in_array(false, $result, true)) {
         throw new \Exception($table->getError());
     }
     // Store the data.
     if (!$table->store()) {
         throw new \Exception($table->getError());
     }
     // Clean the cache.
     $this->cleanCache();
     // Trigger the onContentAfterSave event.
     $dispatcher->trigger($this->eventAfterSave, array($this->option . '.' . $this->name, $table, $isNew));
     $pkName = $table->getKeyName();
     if (isset($table->{$pkName})) {
         $this->state->set($this->getName() . '.id', $table->{$pkName});
     }
     $this->state->set($this->getName() . '.new', $isNew);
     $this->postSaveHook($table);
     return true;
 }
 /**
  * Instantiate the controller.
  *
  * @param   \JInput          $input  The input object.
  * @param   \JApplicationCms $app    The application object.
  * @param   array            $config The config object.
  */
 public function __construct(\JInput $input = null, \JApplicationCms $app = null, $config = array())
 {
     parent::__construct($input, $app, $config);
     $this->key = $this->key ?: ArrayHelper::getValue($config, 'key');
     $this->urlVar = $this->urlVar ?: ArrayHelper::getValue($config, 'urlVar');
 }
示例#28
0
 /**
  * Configure the toolbar button set.
  *
  * @param   array   $buttonSet Customize button set.
  * @param   object  $canDo     Access object.
  *
  * @return  array
  */
 protected function configureToolbar($buttonSet = array(), $canDo = null)
 {
     $component = $this->container->get('component');
     $canDo = $canDo ?: $component->getActions($this->viewItem);
     $state = $this->data->state ?: new Registry();
     $grid = $this->data->grid;
     $filterState = $state->get('filter', array());
     return array('add' => array('handler' => 'addNew', 'args' => array($this->viewItem . '.edit.add'), 'access' => 'core.create', 'priority' => 1000), 'edit' => array('handler' => 'editList', 'args' => array($this->viewItem . '.edit.edit'), 'access' => 'core.edit', 'priority' => 900), 'duplicate' => array('handler' => 'duplicate', 'args' => array($this->viewList . '.batch.copy'), 'access' => 'core.create', 'priority' => 800), 'publish' => array('handler' => 'publish', 'args' => array($this->viewList . '.state.publish'), 'access' => 'core.edit.state', 'priority' => 700), 'unpublish' => array('handler' => 'unpublish', 'args' => array($this->viewList . '.state.unpublish'), 'access' => 'core.create', 'priority' => 600), 'checkin' => array('handler' => 'checkin', 'args' => array($this->viewList . '.check.checkin'), 'access' => 'core.create', 'priority' => 500), 'delete' => array('handler' => 'deleteList', 'args' => array($this->viewList . '.state.delete', 'JTOOLBAR_DELETE', 'LIB_WINDWALKER_TOOLBAR_CONFIRM_DELETE'), 'access' => ArrayHelper::getValue($filterState, $this->viewItem . '.' . $grid->config->get('field.state', 'state')) == -2 && $canDo->get('core.delete'), 'priority' => 400), 'trash' => array('handler' => 'trash', 'args' => array($this->viewList . '.state.trash'), 'access' => ArrayHelper::getValue($filterState, $this->viewItem . '.' . $grid->config->get('field.state', 'state')) != -2 && $canDo->get('core.edit.state'), 'priority' => 300), 'batch' => array('handler' => 'modal', 'access' => 'core.edit', 'priority' => 200), 'preferences' => array('handler' => 'preferences', 'access' => 'core.edit', 'priority' => 100));
 }
 /**
  * Process the search query.
  *
  * @param JDatabaseQuery $query    The query object.
  * @param array          $searches The search values.
  *
  * @return  JDatabaseQuery The db query object.
  */
 protected function processSearches(JDatabaseQuery $query, $searches = array())
 {
     $searches = $searches ?: $this->state->get('search', array());
     $searches = ArrayHelper::flatten($searches);
     $searches = $this->filterDataFields($searches);
     $searches = $this->mapDataFields($searches);
     $searchHelper = $this->getSearchHelper();
     $this->configureSearches($searchHelper);
     $query = $searchHelper->execute($query, $searches);
     return $query;
 }
 /**
  * Method to run this controller.
  *
  * @return  mixed
  */
 protected function doExecute()
 {
     // Init Variables
     $data = $this->input->get($this->input->get('formctrl'), array(), 'array');
     $result = new Registry();
     $result->set('Result', false);
     $model_name = $this->input->get('model_name');
     $component = $this->input->get('component');
     $extension = $this->input->get('extension');
     // Include Needed Classes
     JLoader::registerPrefix(ucfirst($component), JPATH_BASE . "/components/com_{$component}");
     JForm::addFormPath(JPATH_BASE . "/components/com_{$component}/models/forms");
     JForm::addFieldPath(JPATH_BASE . "/components/com_{$component}/models/fields");
     JTable::addIncludePath(JPATH_BASE . "/components/com_{$component}/tables");
     LanguageHelper::loadLanguage($extension, null);
     // Get Model
     /** @var $model CrudModel */
     $model = $this->getModel(ucfirst($model_name), ucfirst($component));
     if (!$model instanceof CrudModel) {
         $result->set('errorMsg', 'Model need extends to \\Windwalker\\Model\\CrudModel.');
         jexit($result);
     }
     // For WindWalker Component only
     if (method_exists($model, 'getFieldsName')) {
         $fields_name = $model->getFieldsName();
         $data = ArrayHelper::pivotToTwoDimension($data, $fields_name);
     }
     // Check for validation errors.
     try {
         // Get Form
         if (method_exists($model, 'getForm')) {
             $form = $model->getForm($data, false);
             if (!$form) {
                 $result->set('errorMsg', 'No form');
                 jexit($result);
             }
             // Test whether the data is valid.
             $validData = $model->validate($form, $data);
         } else {
             $validData = $data;
         }
         // Do Save
         $model->save($validData);
     } catch (ValidateFailException $e) {
         // Get the validation messages.
         $errors = $e->getErrors();
         $errors = array_map(function ($error) {
             return (string) $error->getMessage();
         }, $errors);
         $result->set('errorMsg', $errors);
         exit($result);
     } catch (\Exception $e) {
         // Return Error Message.
         $result->set('errorMsg', \JText::sprintf('JLIB_APPLICATION_ERROR_SAVE_FAILED', $e->getMessage()));
         jexit($result);
     }
     // Set ID
     $data['id'] = $model->getState()->get($model_name . '.id');
     // Set Result
     $result->set('Result', true);
     $result->set('data', $data);
     jexit($result);
 }