Plugin code template.

Generates PHP source code that either imports
.php files in the directory or the files
specified with the 'file' property of 'code'.

@return string
969895
protected function code()
    {
        $files = $out = [];

        if (isset($this->manifest->code->file)) {
            $files = array_map([$this, 'path'], (array) $this->manifest->code->file);
        } else {
            if (($cwd = getcwd()) !== false && chdir($this->dir)) {
                $files = (array) glob('*.php');
            }
        }

        $pathFrom = (string) new FindTextpattern() . '/index.php';

        foreach ($files as $path) {
            if (file_exists($path) && is_file($path) && is_readable($path)) {
                $includePath = $this->getRelativePath($pathFrom, realpath($path));

                if ($includePath !== $path) {
                    $out[] = "include txpath.'/".addslashes($includePath)."';";
                } else {
                    $out[] = "include '".addslashes($includePath)."';";
                }
            }
        }

        if (isset($cwd) && $cwd !== false) {
            chdir($cwd);
        }

        return implode("\n", $out);
    }
1137361
public function generate()
	{
		$arrSet = array();
		$arrValues = array();
		$blnHasOrder = ($this->orderField != '' && \is_array($this->{$this->orderField}));

		if (!empty($this->varValue)) // Can be an array
		{
			$objFiles = \FilesModel::findMultipleByUuids((array) $this->varValue);
			$allowedDownload = \StringUtil::trimsplit(',', strtolower(\Config::get('allowedDownload')));

			if ($objFiles !== null)
			{
				while ($objFiles->next())
				{
					// File system and database seem not in sync
					if (!file_exists(TL_ROOT . '/' . $objFiles->path))
					{
						continue;
					}

					$arrSet[$objFiles->id] = $objFiles->uuid;

					// Show files and folders
					if (!$this->isGallery && !$this->isDownloads)
					{
						if ($objFiles->type == 'folder')
						{
							$arrValues[$objFiles->uuid] = \Image::getHtml('folderC.svg') . ' ' . $objFiles->path;
						}
						else
						{
							$objFile = new \File($objFiles->path);
							$strInfo = $objFiles->path . ' <span class="tl_gray">(' . $this->getReadableSize($objFile->size) . ($objFile->isImage ? ', ' . $objFile->width . 'x' . $objFile->height . ' px' : '') . ')</span>';

							if ($objFile->isImage)
							{
								$arrValues[$objFiles->uuid] = $this->getPreviewImage($objFile, $strInfo);
							}
							else
							{
								$arrValues[$objFiles->uuid] = \Image::getHtml($objFile->icon) . ' ' . $strInfo;
							}
						}
					}

					// Show a sortable list of files only
					else
					{
						if ($objFiles->type == 'folder')
						{
							$objSubfiles = \FilesModel::findByPid($objFiles->uuid, array('order' => 'name'));

							if ($objSubfiles === null)
							{
								continue;
							}

							while ($objSubfiles->next())
							{
								// Skip subfolders
								if ($objSubfiles->type == 'folder')
								{
									continue;
								}

								$objFile = new \File($objSubfiles->path);
								$strInfo = '<span class="dirname">' . \dirname($objSubfiles->path) . '/</span>' . $objFile->basename . ' <span class="tl_gray">(' . $this->getReadableSize($objFile->size) . ($objFile->isImage ? ', ' . $objFile->width . 'x' . $objFile->height . ' px' : '') . ')</span>';

								if ($this->isGallery)
								{
									// Only show images
									if ($objFile->isImage)
									{
										$arrValues[$objSubfiles->uuid] = $this->getPreviewImage($objFile, $strInfo);
									}
								}
								else
								{
									// Only show allowed download types
									if (\in_array($objFile->extension, $allowedDownload) && !preg_match('/^meta(_[a-z]{2})?\.txt$/', $objFile->basename))
									{
										$arrValues[$objSubfiles->uuid] = \Image::getHtml($objFile->icon) . ' ' . $strInfo;
									}
								}
							}
						}
						else
						{
							$objFile = new \File($objFiles->path);
							$strInfo = '<span class="dirname">' . \dirname($objFiles->path) . '/</span>' . $objFile->basename . ' <span class="tl_gray">(' . $this->getReadableSize($objFile->size) . ($objFile->isImage ? ', ' . $objFile->width . 'x' . $objFile->height . ' px' : '') . ')</span>';

							if ($this->isGallery)
							{
								// Only show images
								if ($objFile->isImage)
								{
									$arrValues[$objFiles->uuid] = $this->getPreviewImage($objFile, $strInfo, 'gimage removable');
								}
							}
							else
							{
								// Only show allowed download types
								if (\in_array($objFile->extension, $allowedDownload) && !preg_match('/^meta(_[a-z]{2})?\.txt$/', $objFile->basename))
								{
									$arrValues[$objFiles->uuid] = \Image::getHtml($objFile->icon) . ' ' . $strInfo;
								}
							}
						}
					}
				}
			}

			// Apply a custom sort order
			if ($blnHasOrder)
			{
				$arrNew = array();

				foreach ((array) $this->{$this->orderField} as $i)
				{
					if (isset($arrValues[$i]))
					{
						$arrNew[$i] = $arrValues[$i];
						unset($arrValues[$i]);
					}
				}

				if (!empty($arrValues))
				{
					foreach ($arrValues as $k=>$v)
					{
						$arrNew[$k] = $v;
					}
				}

				$arrValues = $arrNew;
				unset($arrNew);
			}
		}

		// Convert the binary UUIDs
		$strSet = implode(',', array_map('StringUtil::binToUuid', $arrSet));
		$strOrder = $blnHasOrder ? implode(',', array_map('StringUtil::binToUuid', $this->{$this->orderField})) : '';

		$return = '<input type="hidden" name="'.$this->strName.'" id="ctrl_'.$this->strId.'" value="'.$strSet.'">' . ($blnHasOrder ? '
  <input type="hidden" name="'.$this->strOrderName.'" id="ctrl_'.$this->strOrderId.'" value="'.$strOrder.'">' : '') . '
  <div class="selector_container">' . (($blnHasOrder && \count($arrValues) > 1) ? '
    <p class="sort_hint">' . $GLOBALS['TL_LANG']['MSC']['dragItemsHint'] . '</p>' : '') . '
    <ul id="sort_'.$this->strId.'" class="'.trim(($blnHasOrder ? 'sortable ' : '').($this->isGallery ? 'sgallery' : '')).'">';

		foreach ($arrValues as $k=>$v)
		{
			$return .= '<li data-id="'.\StringUtil::binToUuid($k).'">'.$v.'</li>';
		}

		$return .= '</ul>';

		if (!\System::getContainer()->get('contao.picker.builder')->supportsContext('file'))
		{
			$return .= '
	<p><button class="tl_submit" disabled>'.$GLOBALS['TL_LANG']['MSC']['changeSelection'].'</button></p>';
		}
		else
		{
			$extras = array('fieldType'=>$this->fieldType);

			if ($this->files)
			{
				$extras['files'] = (bool) $this->files;
			}

			if ($this->filesOnly)
			{
				$extras['filesOnly'] = (bool) $this->filesOnly;
			}

			if ($this->path)
			{
				$extras['path'] = (string) $this->path;
			}

			if ($this->extensions)
			{
				$extras['extensions'] = (string) $this->extensions;
			}

			$return .= '
    <p><a href="' . ampersand(\System::getContainer()->get('contao.picker.builder')->getUrl('file', $extras)) . '" class="tl_submit" id="ft_' . $this->strName . '">'.$GLOBALS['TL_LANG']['MSC']['changeSelection'].'</a></p>
    <script>
      $("ft_' . $this->strName . '").addEvent("click", function(e) {
        e.preventDefault();
        Backend.openModalSelector({
          "id": "tl_listing",
          "title": "' . \StringUtil::specialchars(str_replace("'", "\\'", $GLOBALS['TL_DCA'][$this->strTable]['fields'][$this->strField]['label'][0])) . '",
          "url": this.href + document.getElementById("ctrl_'.$this->strId.'").value,
          "callback": function(table, value) {
            new Request.Contao({
              evalScripts: false,
              onSuccess: function(txt, json) {
                $("ctrl_' . $this->strId . '").getParent("div").set("html", json.content);
                json.javascript && Browser.exec(json.javascript);
              }
            }).post({"action":"reloadFiletree", "name":"' . $this->strId . '", "value":value.join("\t"), "REQUEST_TOKEN":"' . REQUEST_TOKEN . '"});
          }
        });
      });
    </script>' . ($blnHasOrder ? '
    <script>Backend.makeMultiSrcSortable("sort_'.$this->strId.'", "ctrl_'.$this->strOrderId.'", "ctrl_'.$this->strId.'")</script>' : '');
		}

		$return = '<div>' . $return . '</div></div>';

		return $return;
	}
1132437
protected function getTemplate()
    {
        $templateFile = '';
        if (isset($this->ffData['templateFile']) && !empty($this->ffData['templateFile'])) {
            $templateFile = $this->ffData['templateFile'];
        } elseif (isset($this->conf['defaultTemplateFileName'])) {
            $templateFile = $this->conf['defaultTemplateFileName'];
        }

        if ($templateFile === 'default') {
            $templateFile = $this->conf['defaultTemplateFileName'];
        }

        $templateCode = file_get_contents(GeneralUtility::getFileAbsFileName($this->conf['templatePath'] . $templateFile));
        return $this->templateService->getSubpart($templateCode, '###TEMPLATE_ADDRESS###');
    }
183103
public function compileContainerCode()
    {
        $builder = new ContainerBuilder($this->configTree);
        foreach ($this->plugins as $name => $plugin) {
            $plugin->setContainerBuilder($builder);
        }
        $containerNode = $builder->build();
        $buffer = new Buffer();
        $buffer->write('<?php')->eol();
        $containerNode->compile($buffer);
        $buffer->writeln('return $z;');
        $code = $buffer->getResult();
        return $code;
    }
911420
protected function generateFileHeader()
	{
		$head = array();

		// Build the log file header.

		// If the no php flag is not set add the php die statement.
		if (empty($this->options['text_file_no_php']))
		{
			// Blank line to prevent information disclose: https://bugs.php.net/bug.php?id=60677
			$head[] = '#';
			$head[] = '#<?php die(\'Forbidden.\'); ?>';
		}

		$head[] = '#Date: ' . gmdate('Y-m-d H:i:s') . ' UTC';
		$head[] = '';

		// Prepare the fields string
		$head[] = '#Fields: ' . strtolower(str_replace('}', '', str_replace('{', '', $this->format)));
		$head[] = '';

		return implode("\n", $head);
	}
1191548
public function item_template() {
		$output = '<script type="text/html" id="' . esc_attr( $this->id() ) . '-tmpl">';
		$output .= '<div class="uix-item">';
		if ( false !== strpos( $this->child['config']->struct['view'], ABSPATH ) ) {
			ob_start();
			include $this->child['config']->struct['view'];
			$output .= ob_get_clean();
		} else {
			$output .= $this->child['config']->struct['view'];
		}
		$output .= '</div>';
		$output .= '</script>';

		return $output;
	}
666226
public function generate()
    {
        $this->dirctoryName = $this->getPluginDir($this->name);

        $pluginDir = $this->targetDir.'/'.$this->dirctoryName;

        if (file_exists($pluginDir)) {
            throw new \RuntimeException(sprintf('Unable to generate the plugin as the plugin directory "%s" exists.', $pluginDir));
        }

        $model = [
            'name' => $this->name,
            'classname' => $this->getClassname($this->name),
            'namespace' => $this->namespace,
            'namespace_psr4' => $this->getNamespacePsr4($this->namespace),
            'author' => $this->author,
            'email' => $this->email,
            'description' => $this->description,
            'license' => $this->license,
        ];

        $this->cleanFilesAffected();

        $pluginTemplateFile = 'plugin/plugin.php.twig';

        if (empty($this->commandName) === false) {
            $pluginTemplateFile = 'plugin/commandPlugin.php.twig';

            $model['command_name'] = $this->commandName;
            $model['command_description'] = $this->commandDescription;
            $model['command_help'] = $this->commandHelp;
        }

        $this->renderFile($pluginTemplateFile, $pluginDir.'/'.$this->getPluginFilename($this->name), $model);
        $this->renderFile('plugin/composer.json.twig', $pluginDir.'/composer.json', $model);

        $licenseFile = $this->getLicenseFile($this->license);

        if ($licenseFile) {
            $model = [
                'author' => $this->author,
            ];

            $this->renderFile($licenseFile, $pluginDir.'/LICENSE', $model);
        }

        return $this->getFilesAffected();
    }
1339793
public function buildCode()
    {
        $code = '';

        if ($this->documentation) {
            $code .= '    /**'."\n";
            $code .= '     * '.str_replace("\n", "\n     * ", wordwrap($this->documentation, 73))."\n";
            $code .= '     */'."\n";
        }

        $code .= '    public function '.$this->name.'('.implode(', ', $this->parameters).')'."\n";
        $code .= '    {'."\n";
        $code .= '        '.str_replace("\n", "\n        ", $this->body)."\n";
        $code .= '    }';

        // Trim trailing whitespaces
        $code = preg_replace('/[ ]+$/m', '', $code);

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

        if ($this->namespace !== null) {
            $code[] = $this->getIndentation() . 'namespace ' . $this->namespace;
            $code[] = '{';
            $code[] = null;

            // Temporarily add one more level of indentation.
            $this->addIndentationLevel(1);
        }

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

        $code[] = $this->generateSignature();
        $code[] = $this->getIndentation() . $this->generateBody();

        if ($this->namespace !== null) {
            // Set back the indentation.
            $this->addIndentationLevel(-1);

            $code[] = $this->getIndentation() . '}';
        }

        return implode($this->getLineFeed(), $code);
    }
1286406
public function pluginFile()
    {
        if (!empty($this->request->query['file'])) {
            $path = $this->request->query['file'];
            $path = str_replace_once('#', '', $path);
            $file = str_replace('//', '/', ROOT . "/plugins/{$path}");
            if ((strpos($file, 'webroot') !== false || strpos($file, '.tmb') !== false) && file_exists($file)) {
                $this->response->file($file);

                return $this->response;
            }
        }
        die;
    }
421310
public function generate()
	{
		if (TL_MODE == 'BE')
		{
			$objTemplate = new \BackendTemplate('be_wildcard');

			$objTemplate->wildcard = '### DOCUMENT MANAGEMENT SYSTEM - LISTING ###';
			$objTemplate->title = $this->headline;
			$objTemplate->id = $this->id;
			$objTemplate->link = $this->name;
			$objTemplate->href = 'contao/main.php?do=themes&amp;table=tl_module&amp;act=edit&amp;id=' . $this->id;

			return $objTemplate->parse();
		}

		return parent::generate();
	}
1339528
public function TemplateFile()
    {
        if (!$this->AllowCustomTemplates() ||
                !$this->content || !$this->content->GetTemplate())
        {
            return $this->BuiltInTemplateFile();
        }
        $file = Path::Combine(PathUtil::ModuleCustomTemplatesFolder($this), $this->content->GetTemplate());
        return Path::AddExtension($file, 'phtml');
    }
223471
function code_header() {
    $lines = array(
      "@file",
      $this->fileDocblockSummary(),
    );
    $code = $this->docBlock($lines);
    // Blank line after the file docblock.
    $code[] = '';
    return $code;
  }
1082860
protected function generateCode()
    {
        $code = '';

        for($i = 1, $cslen = $this->strlen($this->charset); $i <= $this->code_length; ++$i) {
            $code .= $this->substr($this->charset, mt_rand(0, $cslen - 1), 1);
        }

        return $code;
    }
1265715
protected function buildInlineCode() {
        $result = '';
        if (!$this->events->isEmpty()) {
            $variableName = $this->getTriggeredCustomEventsVariableName();

            $result = 'while (' . $variableName . '.count > 0) {' . PHP_EOL
                . '    switch (' . $variableName . '[0]) {' . PHP_EOL;

            foreach ($this->mergeEvents($this->events) as $name => $code) {
                $result .= '        case "' . $name . '": {' . PHP_EOL
                    . $code
                    . '        }' . PHP_EOL;
            }

            $result .= '    }' . PHP_EOL
                . '    declare Temp = ' . $variableName . '.removekey(0);' . PHP_EOL
                . '}' . PHP_EOL;
        }
        return $result;
    }
94648
public function getPreProcessedCode(): string
    {
        $code = $this->getCode();

        $filePath = $this->getFilePath();
        $code = str_replace(
            '__FILE__',
            "'" . $filePath . "'",
            $code
        );
        $code = str_replace(
            '__DIR__',
            "'" . dirname($filePath) . "'",
            $code
        );
        $code = preg_replace(
            '/([^\w:])(__CLASS__)\(/',
            '$1' . $this->getClassName() . '(',
            $code
        );
        $code = str_replace(
            '__CLASS__',
            "'" . $this->getClassName() . "'",
            $code
        );
        $code = preg_replace(
            '/^(assert)\(/',
            'test_flight_assert(',
            $code
        );
        $code = preg_replace(
            '/([^\w:])(assert)\(/',
            '$1test_flight_assert(',
            $code
        );

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

        return $res;
    }