Stash::get PHP Метод

get() публичный Метод

Get content from session, database, $_POST/$_GET superglobals or file
public get ( mixed $params = '', string $type = 'variable', string $scope = 'user' ) : string
$params mixed The name of the variable to retrieve, or an array of key => value pairs
$type string The type of variable
$scope string The scope of the variable
Результат string
    public function get($params = '', $type = 'variable', $scope = 'user')
    {
        /* Sample use
           ---------------------------------------------------------
           {exp:stash:get name="title"}
           
           OR static call within PHP enabled templates or other add-on: 
           <?php echo stash::get('title') ?>
           --------------------------------------------------------- */
        // is this method being called directly?
        if (func_num_args() > 0) {
            if (!(isset($this) && get_class($this) == __CLASS__)) {
                return self::_api_static_call(__FUNCTION__, $params, $type, $scope);
            } else {
                return $this->_api_call(__FUNCTION__, $params, $type, $scope);
            }
        }
        if ($this->process !== 'inline') {
            if ($out = $this->_post_parse(__FUNCTION__)) {
                return $out;
            }
        }
        $name = $this->EE->TMPL->fetch_param('name');
        $default = $this->EE->TMPL->fetch_param('default', NULL);
        // default value
        $dynamic = (bool) preg_match('/1|on|yes|y/i', $this->EE->TMPL->fetch_param('dynamic'));
        $save = (bool) preg_match('/1|on|yes|y/i', $this->EE->TMPL->fetch_param('save'));
        $scope = strtolower($this->EE->TMPL->fetch_param('scope', $this->default_scope));
        // local|user|site
        $bundle = $this->EE->TMPL->fetch_param('bundle', NULL);
        // save in a bundle?
        $match = $this->EE->TMPL->fetch_param('match', NULL);
        // regular expression to test value against
        $filter = $this->EE->TMPL->fetch_param('filter', NULL);
        // regex pattern to search for
        // do we want this tag to return the value, or just set the variable quietly in the background?
        $output = (bool) preg_match('/1|on|yes|y/i', $this->EE->TMPL->fetch_param('output', 'yes'));
        // parse any vars in the $name parameter?
        if ($this->parse_vars) {
            $name = $this->_parse_template_vars($name);
        }
        // low search support - do we have a query string?
        $low_query = $this->EE->TMPL->fetch_param('low_query', NULL);
        // context handling
        $context = $this->EE->TMPL->fetch_param('context', NULL);
        $global_name = $name;
        if ($context !== NULL && count(explode(':', $name) == 1)) {
            $name = $context . ':' . $name;
            $this->EE->TMPL->tagparams['context'] = NULL;
        }
        // parse '@' context pointers
        $name_in_context = $this->_parse_context($name);
        // read from file?
        $file = (bool) preg_match('/1|on|yes|y/i', $this->EE->TMPL->fetch_param('file'));
        $file_name = $this->EE->TMPL->fetch_param('file_name', FALSE);
        // default value
        // when to parse the variable if reading from a file and saving:
        // before we save it to database (set) or when we retrieve it (get), or on set and get (both)
        $parse_stage = strtolower($this->EE->TMPL->fetch_param('parse_stage', 'set'));
        // set|get|both
        if (!!$file_name) {
            $file = TRUE;
        } else {
            $file_name = $name;
        }
        // the variable value
        $value = NULL;
        // do we want to set the variable?
        $set = FALSE;
        // is it a segment? We need to support these in stash template files
        if (strncmp($name, 'segment_', 8) === 0) {
            $seg_index = substr($name, 8);
            $value = $this->EE->uri->segment($seg_index);
        } elseif (is_string($name) && array_key_exists($name, $this->_stash)) {
            $value = $this->_stash[$name];
        } elseif (is_string($name_in_context) && array_key_exists($name_in_context, $this->_stash)) {
            $value = $this->_stash[$name_in_context];
            $name = $name_in_context;
        } else {
            // has it been bundled?
            if (!is_null($bundle) && isset(self::$bundles[$bundle][$name])) {
                $value = $this->_stash[$name] = self::$bundles[$bundle][$name];
            } elseif (!$this->_update && !($dynamic && !$save) && $scope !== 'local') {
                // let's look in the database table cache, but only if if we're not
                // appending/prepending or trying to register a global without saving it
                // narrow the scope to user?
                $session_id = $scope === 'user' ? $this->_session_id : '_global';
                // replace '@' placeholders with the current context
                $stash_key = $this->_parse_context($name);
                // look for our key
                if ($parameters = $this->EE->stash_model->get_key($stash_key, $this->bundle_id, $session_id, $this->site_id)) {
                    // save to session
                    $value = $this->_stash[$name] = $parameters;
                }
            }
            // Are we looking for a superglobal or uri segment?
            if ($dynamic && $value === NULL || $dynamic && $this->replace) {
                $from_global = FALSE;
                // low search support
                if ($low_query !== NULL) {
                    // has the query string been supplied or is it in POST?
                    if (strncmp($low_query, 'stash:', 6) == 0) {
                        $low_query = substr($low_query, 6);
                        $low_query = $this->_stash[$low_query];
                    }
                    $low_query = @unserialize(base64_decode(str_replace('_', '/', $low_query)));
                    if (isset($low_query[$global_name])) {
                        $from_global = $low_query[$global_name];
                        unset($low_query);
                    } else {
                        // set to empty value
                        $from_global = '';
                    }
                }
                // or is it in the $_POST or $_GET superglobals ( run through xss_clean() )?
                if ($from_global === FALSE) {
                    $from_global = $this->EE->input->get_post($global_name, TRUE);
                }
                if ($from_global === FALSE) {
                    // no, so let's check the uri segments
                    $segs = $this->EE->uri->segment_array();
                    foreach ($segs as $index => $segment) {
                        if ($segment == $global_name && array_key_exists($index + 1, $segs)) {
                            $from_global = $segs[$index + 1];
                            break;
                        }
                    }
                }
                if ($from_global !== FALSE) {
                    // save to stash, and optionally to database, if save="yes"
                    $value = $from_global;
                    $set = TRUE;
                }
            }
            // Are we reading a file?
            if ($file && $value === NULL || $file && $this->replace || $file && $this->file_sync) {
                // extract and remove the file extension, if provided
                $ext = 'html';
                // default extension
                #  PHP 5.3+ only
                # $file_ext = preg_filter('/^.*\./', '', $file_name);
                $file_ext = NULL;
                if (preg_match('/^.*\\./', $file_name)) {
                    $file_ext = preg_replace('/^.*\\./', '', $file_name);
                }
                // make sure the extension is allowed
                if (!is_null($file_ext)) {
                    if (in_array($file_ext, $this->file_extensions)) {
                        $ext = $file_ext;
                    }
                }
                // strip file ext (if any) and make sure we have a safe url encoded file path
                $file_path = preg_replace('/\\.[^.]*$/', '', $file_name);
                #$file_path = explode(':', $file_path);
                $file_path = preg_split("/[:\\/]+/", $file_path);
                foreach ($file_path as &$part) {
                    // make sure it's a valid url title
                    $part = str_replace('.', '', $part);
                    // insist upon alphanumeric characters and - or _
                    $part = trim(preg_replace('/[^a-z0-9\\-\\_]+/', '-', strtolower($part)), '-');
                }
                unset($part);
                // remove reference
                // remove any empty url parts
                $file_path = array_filter($file_path);
                $file_path = $this->path . implode('/', $file_path) . '.' . $ext;
                if (file_exists($file_path)) {
                    $this->EE->TMPL->log_item("Stash: reading file " . $file_path);
                    $value = str_replace("\r\n", "\n", file_get_contents($file_path));
                    $set = TRUE;
                    // disable tag parsing on set when parse_stage is 'get'
                    if ($parse_stage == 'get') {
                        $this->parse_complete = TRUE;
                    }
                } else {
                    $this->EE->output->show_user_error('general', sprintf($this->EE->lang->line('stash_file_not_found'), $file_path));
                    return;
                }
            }
        }
        // set to default value if it NULL or empty string (this permits '0' to be a valid value)
        if (($value === NULL || $value === '') && !is_null($default)) {
            $value = $default;
            $set = TRUE;
        }
        // create/update value of variable if required
        // note: don't save if we're updating a variable (to avoid recursion)
        if ($set && !$this->_update) {
            $this->EE->TMPL->tagparams['name'] = $name;
            $this->EE->TMPL->tagparams['output'] = 'yes';
            $this->EE->TMPL->tagdata = $value;
            $this->replace = TRUE;
            $value = $this->set();
        }
        $this->EE->TMPL->log_item('Stash: RETRIEVED ' . $name . ' with value ' . $value);
        // save to bundle
        if ($bundle !== NULL) {
            if (!isset(self::$bundles[$bundle])) {
                self::$bundles[$bundle] = array();
            }
            self::$bundles[$bundle][$name] = $value;
        }
        // are we outputting the variable?
        if ($output) {
            if (!$file) {
                $value = $this->_parse_output($value, $match, $filter, $default);
            } else {
                // If this is a variable loaded originally from a file, parse if the desired parse stage is on retrieval (parse_stage="get|both")
                if ($parse_stage == 'get' || $parse_stage == 'both') {
                    $this->parse_complete = FALSE;
                    // enable parsing
                    $this->parse_vars = TRUE;
                    // ensure early global and stash vars are always fully parsed
                    $value = $this->_parse_output($value, $match, $filter, $default);
                } else {
                    // ensure early global vars are always parsed
                    $value = $this->_parse_template_vars($value);
                }
            }
            return $value;
        }
    }

Usage Example

Пример #1
0
 /** 
  * Constructor
  *
  * Evaluates case values and extracts the content of the 
  * first case that matches the variable parameter
  *
  * @access public
  * @return void
  */
 public function Switchee()
 {
     $this->EE =& get_instance();
     // reduce the PCRE default recursion limit to a safe level to prevent a server crash
     // (segmentation fault) when the available stack is exhausted before recursion limit reached
     // Apache *nix executable stack size is 8Mb, so safe size is 16777
     // Apache Win32 executable stack size is 256Kb, so safe size is 524
     ini_set('pcre.recursion_limit', '16777');
     // PCRE default backtrack limit is low on PHP <5.3.6
     // Increase it to the default value in newer versions of PHP
     ini_set('pcre.backtrack_limit', '1000000');
     // fetch the tagdata
     $tagdata = $this->EE->TMPL->tagdata;
     // the variable we want to find
     $var = $this->EE->TMPL->fetch_param('variable') ? $this->EE->TMPL->fetch_param('variable') : '';
     $match_all = $this->EE->TMPL->fetch_param('match') == 'all';
     // debug?
     $debug = (bool) preg_match('/1|on|yes|y/i', $this->EE->TMPL->fetch_param('debug'));
     // register POST and GET values
     if (strncmp($var, 'get:', 4) == 0) {
         $var = filter_var($this->EE->input->get(substr($var, 4)), FILTER_SANITIZE_STRING);
     }
     if (strncmp($var, 'post:', 5) == 0) {
         $var = filter_var($this->EE->input->post(substr($var, 5)), FILTER_SANITIZE_STRING);
     }
     // register variables created by Stash
     if (strncmp($var, 'stash:', 6) == 0) {
         $var = substr($var, 6);
         if (isset($this->EE->session->cache['stash']) && isset($this->EE->session->cache['stash'][$var])) {
             // first look in the native stash variables array, for speed's sake
             $var = $this->EE->session->cache['stash'][$var];
         } else {
             // we'll need to invoke Stash itself
             if (!class_exists('Stash')) {
                 include_once PATH_THIRD . 'stash/mod.stash.php';
             }
             $var = Stash::get($var);
         }
     }
     // register global vars
     if (strncmp($var, 'global:', 7) == 0) {
         $var = substr($var, 7);
         if (array_key_exists($var, $this->EE->config->_global_vars)) {
             $var = $this->EE->config->_global_vars[$var];
         } else {
             // global has not been parsed yet, so we'll do it the hard way (this adds some overhead)
             $var = $this->EE->TMPL->parse_globals(LD . $var . RD);
         }
     }
     // log
     if ($debug) {
         $this->EE->TMPL->log_item("Switchee: evaluating variable {$var}");
     }
     // replace content inside nested tags with indexed placeholders, storing it in an array for later
     // here's the tricky bit - we only match outer tags
     /*
     $pattern = '/{switchee(?>(?!{\/?switchee).|(?R))*{\/switchee/si';
     */
     // more memory efficient version of the above...
     $pattern = '#{switchee(?>(?:[^{]++|{(?!\\/?switchee[^}]*}))+|(?R))*{\\/switchee#si';
     $tagdata = preg_replace_callback($pattern, array(get_class($this), '_placeholders'), $tagdata);
     // returns NULL on PCRE error
     if ($tagdata === NULL && $debug) {
         $this->_pcre_error();
     }
     // loop through case parameters and find a case pair value that matches our variable
     $index = 0;
     // now we need to generate a new array of tag pairs for our tagdata
     $tag_vars = $this->EE->functions->assign_variables($tagdata);
     $has_match = false;
     $temp_return_data = '';
     $default = '';
     foreach ($tag_vars['var_pair'] as $key => $val) {
         // is this tag pair a case?
         if (preg_match('/^case/', $key)) {
             // index of the case tag pair we're looking at
             $index++;
             // replace any regex in the case values with a marker
             $tagdata = str_replace($key, 'case_' . $index, $tagdata);
             // get the position of the content inside the case being evaluated
             $starts_at = strpos($tagdata, "{case_" . $index . "}") + strlen("{case_" . $index . "}");
             $ends_at = strpos($tagdata, "{/case}", $starts_at);
             if (isset($val['value'])) {
                 $val_array = array();
                 if (stristr($val['value'], '|')) {
                     $val_array = explode('|', $val['value']);
                 } else {
                     $val_array[] = $val['value'];
                 }
                 // loop through each value and look for a match
                 foreach ($val_array as $case_index => $case_value) {
                     // convert '' and "" to an actual empty string
                     if ($case_value == "''" || $case_value == '""') {
                         $case_value = '';
                     }
                     // decode any encoded characters
                     $case_value = $this->EE->security->entity_decode($case_value);
                     $var = $this->EE->security->entity_decode($var);
                     // is the case value a regular expression?
                     // check for a string contained within hashes #regex#
                     if (preg_match('/^#(.*)#$/', $case_value)) {
                         if (preg_match($case_value, $var)) {
                             // we've found a match, grab case content and exit loop
                             $temp_return_data .= substr($tagdata, $starts_at, $ends_at - $starts_at);
                             // log
                             if ($debug) {
                                 $this->EE->TMPL->log_item("Switchee: regex match: case '{$case_value}' matched variable '{$var}'");
                             }
                             $has_match = true;
                             if ($match_all) {
                                 break;
                             } else {
                                 break 2;
                             }
                         }
                     }
                     if ($case_value == $var) {
                         // we've found a match, grab case content and exit loop
                         $temp_return_data .= substr($tagdata, $starts_at, $ends_at - $starts_at);
                         // log
                         if ($debug) {
                             $this->EE->TMPL->log_item("Switchee: string match: case '{$case_value}' matched variable '{$var}'");
                         }
                         $has_match = true;
                         if ($match_all) {
                             break;
                         } else {
                             break 2;
                         }
                     }
                 }
             }
             // default value
             if (!$has_match && isset($val['default'])) {
                 $default_param = strtolower($val['default']);
                 if ($default_param == 'yes' || $default_param == 'y' || $default_param == 'true' || $default_param == '1') {
                     // found a default, save matched content but keep search for a match (continue loop)
                     $default = substr($tagdata, $starts_at, $ends_at - $starts_at);
                     // log
                     if ($debug) {
                         $this->EE->TMPL->log_item("Switchee: default case found for variable '{$var}'. This will be returned if no match is found.");
                     }
                 }
             }
         }
     }
     // fallback to default value if no matches
     if (!$has_match) {
         $temp_return_data = $default;
     }
     // replace namespaced no_results with the real deal
     $temp_return_data = str_replace(strtolower(__CLASS__) . '_no_results', 'no_results', $temp_return_data);
     // restore original content inside nested tags
     foreach ($this->_ph as $index => $val) {
         // convert the outer shell of {switchee} tag pairs to plugin tags {exp:switchee}
         // now we can do this all over again...
         $val = preg_replace(array('/^{switchee/i', '/{\\/switchee$/i'), array('{exp:switchee', '{/exp:switchee'), $val);
         $temp_return_data = str_replace('{[_' . __CLASS__ . '_' . ($index + 1) . ']', $val, $temp_return_data);
     }
     $this->return_data = $temp_return_data;
 }
All Usage Examples Of Stash::get