Searches for shortcodes in the post content and sets the generated
shortcode output if one is found.

@since  5.0.0
@access protected
@return string
429611
protected function locateShortcodeMedia() {

		// Finds matches for shortcodes in the content.
		preg_match_all( '/' . get_shortcode_regex() . '/s', $this->content, $matches, PREG_SET_ORDER );

		if ( empty( $matches ) ) {
			return '';
		}

		// Create a list of allowed shortcodes.
		$shortcodes = is_array( $this->shortcodes ) ? $this->shortcodes : [];

		// We need to add any known shortcodes for the given type.
		$property = "{$this->type}_shortcodes";

		if ( property_exists( $this, $property ) ) {

			$shortcodes = array_merge(
				$shortcodes,
				apply_filters(
					"hybrid/media/grabber/shortcodes/{$this->type}",
					$this->{$property}
				)
			);
		}

		// Loops through all of the shortcode matches. If we find one of
		// our shortcodes, run it.
		foreach ( $matches as $shortcode ) {

			if ( in_array( $shortcode[2], $shortcodes ) ) {

				$this->original_media = array_shift( $shortcode );

				return $this->doShortcode( $shortcode[2], $this->original_media );
			}
		}

		return '';
	}
598275
public function generate()
    {
        $code = array();

        $doc = $this->generateDocumentation();
        if ($doc !== null) {
            $code[] = $doc;
        }

        if ($this->isAbstract() === true) {
            $code[] = $this->generateSignature() . ';';
        } else {
            $code[] = $this->generateSignature();
            $code[] = $this->getIndentation() . $this->generateBody();
        }

        return implode($this->getLineFeed(), $code);
    }
1186013
protected function captureOutputExpression()
	{
		$parens = 0;
		$php = '';
		do
		{
			if ($this->tokens[$this->i] === ';')
			{
				break;
			}
			elseif ($this->tokens[$this->i] === '.' && !$parens)
			{
				break;
			}
			elseif ($this->tokens[$this->i] === '(')
			{
				++$parens;
			}
			elseif ($this->tokens[$this->i] === ')')
			{
				--$parens;
			}

			$php .= $this->serializeToken($this->tokens[$this->i]);
		}
		while (++$this->i < $this->cnt);

		return $php;
	}
781488
public function generate()
    {
        return sprintf(
            '<input type="hidden" id="ctrl_%s" name="%s" value="%s" /><div%s>%s</div>',
            $this->strId,
            $this->strName,
            StringUtil::specialchars($this->label ?: $this->varValue),
            $this->style ? ' style="' . $this->style . '"' : '',
            $this->label
        );
    }
1325945
protected function getShortCodes() {
        if (!$this->_shortCodes) {
            $this->_shortCodes = new ShortCodeList($this->version, $this->solution['sid']);
        }

        return $this->_shortCodes;
    }
1110045
protected function locate() {

		// Don't return a link if embeds don't work. Need media or nothing at all.
		add_filter( 'embed_maybe_make_link', '__return_false' );

		// Get the media if the post type is an attachment.
		if ( 'attachment' === get_post_type( $this->post_id ) ) {
			$this->media = $this->locateSelfMedia();
		}

		// Find media in the post content based on WordPress' media-related shortcodes.
		if ( ! $this->media && $this->shortcodes ) {
			$this->media = $this->locateShortcodeMedia();
		}

		// If no media is found and autoembeds are enabled, check for autoembeds.
		if ( ! $this->media && get_option( 'embed_autourls' ) && $this->autoembeds ) {
			$this->media = $this->locateAutoembedMedia();
		}

		// If no media is found, check for media HTML within the post content.
		if ( ! $this->media && $this->embedded ) {
			$this->media = $this->locatedEmbeddedMedia();
		}

		// If no media is found, check for media attached to the post.
		if ( ! $this->media && $this->attached ) {
			$this->media = $this->locateAttachedMedia();
		}

		// If media is found, let's run a few things.
		if ( $this->media ) {

			// Split the media from the content.
			if ( true === $this->split && ! empty( $this->original_media ) ) {
				add_filter( 'the_content', [ $this, 'split' ], 5 );
			}

			// Filter the media dimensions and add the before/after HTML.
			$this->media = $this->before . $this->filterDimensions( $this->media ) . $this->after;
		}

		// Remove our filter from earlier.
		remove_filter( 'embed_maybe_make_link', '__return_false' );

		return $this->media;
	}
887165
public function buildCode()
    {
        $res = '';
        foreach ($this->styles as $href => $val) {
            $res .= '<link href="' . $href . '" rel="stylesheet" type="text/css" />' . "\r\n";
        }

        return $res;
    }
844702
public function search()
    {
        $pattern = $this->request->getQuery('p');

        //Checks if the pattern is at least 4 characters long
        if ($pattern && strlen($pattern) < 4) {
            $this->Flash->alert(__d('me_cms', 'You have to search at least a word of {0} characters', 4));

            return $this->redirect(['action' => $this->request->getParam('action')]);
        }

        //Checks the last search
        if ($pattern && !$this->checkLastSearch($pattern)) {
            $this->Flash->alert(__d(
                'me_cms',
                'You have to wait {0} seconds to perform a new search',
                getConfigOrFail('security.search_interval')
            ));

            return $this->redirect(['action' => $this->request->getParam('action')]);
        }

        if ($pattern) {
            $this->paginate['limit'] = getConfigOrFail('default.records_for_searches');

            $page = $this->request->getQuery('page', 1);

            //Sets the cache name
            $cache = sprintf('search_%s_limit_%s_page_%s', md5($pattern), $this->paginate['limit'], $page);

            //Tries to get data from the cache
            list($posts, $paging) = array_values(Cache::readMany(
                [$cache, sprintf('%s_paging', $cache)],
                $this->Posts->getCacheName()
            ));

            //If the data are not available from the cache
            if (empty($posts) || empty($paging)) {
                $query = $this->Posts->find('active')
                    ->select(['title', 'slug', 'text', 'created'])
                    ->where(['OR' => [
                        'title LIKE' => sprintf('%%%s%%', $pattern),
                        'subtitle LIKE' => sprintf('%%%s%%', $pattern),
                        'text LIKE' => sprintf('%%%s%%', $pattern),
                    ]])
                    ->order([sprintf('%s.created', $this->Posts->getAlias()) => 'DESC']);

                $posts = $this->paginate($query);

                //Writes on cache
                Cache::writeMany([
                    $cache => $posts,
                    sprintf('%s_paging', $cache) => $this->request->getParam('paging'),
                ], $this->Posts->getCacheName());
            //Else, sets the paging parameter
            } else {
                $this->request = $this->request->withParam('paging', $paging);
            }

            $this->set(compact('posts'));
        }

        $this->set(compact('pattern'));
    }
307266
public function getExcerpt()
    {
        $excerpt = $this->post_excerpt;
        if (!Utils::isValidStr($excerpt)) {
            $excerpt = strip_tags(strip_shortcodes($this->post_content));
            $excerpt = trim(preg_replace('/\s\s+/', ' ', $excerpt));
        }
        return Utils::getWordsByStr($excerpt, self::COUNT_EXCERPT);
    }
243493
protected function locateAutoembedMedia() {

		// Searches for URLs on a line by themselves in the post content.
		preg_match_all( '|^\s*(https?://[^\s"]+)\s*$|im', $this->content, $matches, PREG_SET_ORDER );

		if ( empty( $matches ) || ! is_array( $matches ) ) {
			return '';
		}

		foreach ( $matches as $value ) {

			// Let WP work its magic with the 'autoembed' method.
			$embed = $GLOBALS['wp_embed']->autoembed( $value[0] );

			if ( $embed ) {

				// If we're given a shortcode, roll with it.
				if ( preg_match( "/\[{$this->type}\s/", $embed ) ) {

					$this->original_media = $value[0];

					return $this->doShortcode( $this->type, $embed );
				}
			}
		}

		return '';
	}
1277233
public function posts_search(
		/** @noinspection PhpUnusedParameterInspection */
		$search, $wp_query
	) {
		if ( ! $wp_query->is_search() || ! $wp_query->is_main_query() || ! is_admin() || empty( $wp_query->query_vars['search_terms'] ) ) {
			return $search;
		}

		$fields = $this->get_search_fields();
		if ( empty( $fields ) ) {
			return $search;
		}

		global $wpdb;

		$exclusion_prefix = apply_filters( 'wp_query_search_exclusion_prefix', '-' );
		$search           = '';
		$q                = $wp_query->query_vars;
		$n                = ! empty( $q['exact'] ) ? '' : '%';
		$table            = $this->app->db->get_table( $this->get_related_table_name() );

		foreach ( $q['search_terms'] as $term ) {
			$exclude = $exclusion_prefix && ( $exclusion_prefix === substr( $term, 0, 1 ) );
			if ( $exclude ) {
				$like_op  = 'NOT LIKE';
				$andor_op = 'AND';
				$term     = substr( $term, 1 );
			} else {
				$like_op  = 'LIKE';
				$andor_op = 'OR';
			}

			$conditions = [];
			$fields     = array_map( function ( $field ) use ( $table ) {
				return "{$table}.{$field}";
			}, $fields );
			$fields[]   = "{$wpdb->posts}.post_title";
			$fields[]   = "{$wpdb->posts}.post_excerpt";
			$fields[]   = "{$wpdb->posts}.post_content";
			$like       = $n . $wpdb->esc_like( $term ) . $n;
			foreach ( $fields as $field ) {
				$conditions[] = $wpdb->prepare( "({$field} $like_op %s)", $like );
			}
			$conditions = implode( " {$andor_op} ", $conditions );
			$search     .= " AND ({$conditions})";
		}

		return $search;
	}
1096554
public function get_wp_config_code() {
		$wp_config_path = Utils\locate_wp_config();

		$wp_config_code = explode( "\n", file_get_contents( $wp_config_path ) );

		$found_wp_settings = false;

		$lines_to_run = array();

		foreach ( $wp_config_code as $line ) {
			if ( preg_match( '/^\s*require.+wp-settings\.php/', $line ) ) {
				$found_wp_settings = true;
				continue;
			}

			$lines_to_run[] = $line;
		}

		if ( ! $found_wp_settings ) {
			WP_CLI::error( 'Strange wp-config.php file: wp-settings.php is not loaded directly.' );
		}

		$source = implode( "\n", $lines_to_run );
		$source = Utils\replace_path_consts( $source, $wp_config_path );
		return preg_replace( '|^\s*\<\?php\s*|', '', $source );
	}
668001
public function getEncoding()
    {
        $content = $this->getHeaderLine('content-type');
        if (!$content) {
            return null;
        }
        preg_match('/charset\s?=\s?[\'"]?([a-z0-9-_]+)[\'"]?/i', $content, $matches);
        if (empty($matches[1])) {
            return null;
        }

        return $matches[1];
    }
339513
public function ShortcodeForm()
    {
        Config::inst()->update('SSViewer', 'theme_enabled', false);
        $classes = Shortcodable::get_shortcodable_classes_fordropdown();
        $classname = $this->shortcodableclass;

        if ($this->isnew) {
            $headingText = _t('Shortcodable.EDITSHORTCODE', 'Edit Shortcode');
        } else {
            $headingText =  sprintf(
                _t('Shortcodable.EDITSHORTCODE', 'Edit %s Shortcode'),
                singleton($this->shortcodableclass)->singular_name()
            );
        }

        // essential fields
        $fields = FieldList::create(array(
            CompositeField::create(
                LiteralField::create(
                    'Heading',
                    sprintf('<h3 class="htmleditorfield-shortcodeform-heading insert">%s</h3>', $headingText)
                )
            )->addExtraClass('CompositeField composite cms-content-header nolabel'),
            LiteralField::create('shortcodablefields', '<div class="ss-shortcodable content">'),
            DropdownField::create('ShortcodeType', _t('Shortcodable.SHORTCODETYPE', 'Shortcode type'), $classes, $classname)
                ->setHasEmptyDefault(true)
                ->addExtraClass('shortcode-type')
        ));

        // attribute and object id fields
        if ($classname && class_exists($classname)) {
            $class = singleton($classname);
            if (is_subclass_of($class, 'DataObject')) {
                if (singleton($classname)->hasMethod('getShortcodableRecords')) {
                    $dataObjectSource = singleton($classname)->getShortcodableRecords();
                } else {
                    $dataObjectSource = $classname::get()->map()->toArray();
                }
                $fields->push(
                    DropdownField::create('id', $class->singular_name(), $dataObjectSource)
                        ->setHasEmptyDefault(true)
                );
            }
            if (singleton($classname)->hasMethod('getShortcodeFields')) {
                if ($attrFields = singleton($classname)->getShortcodeFields()) {
                    $fields->push(
                        CompositeField::create($attrFields)
                            ->addExtraClass('attributes-composite')
                            ->setName('AttributesCompositeField')
                    );
                }
            }
        }

        // actions
        $actions = FieldList::create(array(
            FormAction::create('insert', _t('Shortcodable.BUTTONINSERTSHORTCODE', 'Insert shortcode'))
                ->addExtraClass('ss-ui-action-constructive')
                ->setAttribute('data-icon', 'accept')
                ->setUseButtonTag(true)
        ));

        // form
        $form = Form::create($this, 'ShortcodeForm', $fields, $actions)
            ->loadDataFrom($this)
            ->addExtraClass('htmleditorfield-form htmleditorfield-shortcodable cms-dialog-content');

        $this->extend('updateShortcodeForm', $form);

        $fields->push(LiteralField::create('shortcodablefieldsend', '</div>'));

        if ($data = $this->getShortcodeData()) {
            $form->loadDataFrom($data['atts']);

            // special treatment for setting value of UploadFields
            foreach ($form->Fields()->dataFields() as $field) {
                if (is_a($field, 'UploadField') && isset($data['atts'][$field->getName()])) {
                    $field->setValue(array('Files' => explode(',', $data['atts'][$field->getName()])));
                }
            }
        }

        return $form;
    }
973860
private function getCode()
    {
        $_paq = '';
        foreach ($this->options as $key => $values) {
            foreach ($values as &$value) {
                $value = "'".$value."'";
            }
            $_paq .= sprintf("_paq.push([%s]);\n", implode($values, ','));
        }

        return <<<PWK
<script>
var _paq = _paq || [];
{$_paq}
(function() {
    var u="{$this->piwikUrl}";
    _paq.push(['setSiteId', {$this->siteId}]);
    var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0];
    g.type='text/javascript'; g.async=true; g.defer=true; g.src=u+'piwik.js'; s.parentNode.insertBefore(g,s);
})();
</script>
<noscript><p><img src="{$this->piwikUrl}piwik.php?idsite={$this->siteId}" style="border:0;" alt="" /></p></noscript>
PWK;
    }
1031670
protected function generateVerifyCode()
    {
        if ($this->minLength > $this->maxLength) {
            $this->maxLength = $this->minLength;
        }
        if ($this->minLength < 3) {
            $this->minLength = 3;
        }
        if ($this->maxLength > 20) {
            $this->maxLength = 20;
        }
        $length = mt_rand($this->minLength, $this->maxLength);

        $letters = [0,1,2,3,4,5,6,7,8,9];
        return array_rand($letters).array_rand($letters).array_rand($letters).array_rand($letters);
		//$vowels = '01234';
        //$code = '';
       // for ($i = 0; $i < $length; ++$i) {
            //if ($i % 2 && mt_rand(0, 10) > 2 || !($i % 2) && mt_rand(0, 10) > 9) {
            //    $code .= $vowels[mt_rand(0, 4)];
            //} else {
               // $code .= $letters[mt_rand(0, 20)];
           // }
       // }

        //return $code;
    }
1217042
public function content()
    {
        $content = apply_filters('the_content', $this->thePost()->post_content);
        $content = str_replace(']]>', ']]&gt;', $content);

        return $content;
    }