From comment on http://php.net/manual/en/ref.bc.php
172687
static function bcconv($fNumber)
    {
        $sAppend = '';
        $iDecimals = ini_get('precision') - floor(log10(abs($fNumber)));
        if (0 > $iDecimals) {
            $fNumber *= pow(10, $iDecimals);
            $sAppend = str_repeat('0', -$iDecimals);
            $iDecimals = 0;
        }

        return number_format($fNumber, $iDecimals, '.', '').$sAppend;
    }
1015348
private function prepare_base_string() {
    $url = $this->request_settings['url'];

    # if the host header is set we need to rewrite the basestring to use
    # that, instead of the request host. otherwise the signature won't match
    # on the server side
    if (!empty($this->request_settings['headers']['Host'])) {
      $url = str_ireplace(
        $this->config['host'],
        $this->request_settings['headers']['Host'],
        $url
      );
    }

    $base = array(
      $this->request_settings['method'],
      $url,
      $this->request_settings['basestring_params']
    );
    $this->request_settings['basestring'] = implode('&', $this->safe_encode($base));
  }
329160
public function main()
    {
        // Check if all required data is present.
        $this->checkRequirements();

        $document               = new \DOMDocument('1.0', 'UTF-8');
        $document->formatOutput = true;

        // Create the root 'ruleset' element.
        $root_element = $document->createElement('ruleset');
        $root_element->setAttribute('name', 'NextEuropa_default');
        $document->appendChild($root_element);

        // Add the description.
        $element = $document->createElement(
            'description',
            'Default PHP CodeSniffer configuration for NextEuropa subsites.'
        );
        $root_element->appendChild($element);

        // Add the coding standards.
        foreach ($this->_standards as $standard) {
            if (substr($standard, -4) === '.xml') {
                if (file_exists($standard)) {
                    $element = $document->createElement('rule');
                    $element->setAttribute('ref', $standard);
                    $root_element->appendChild($element);
                }
            }
            else {
                $element = $document->createElement('rule');
                $element->setAttribute('ref', $standard);
                $root_element->appendChild($element);
            }
        }

        // Add the files to check.
        foreach ($this->_files as $file) {
            $element = $document->createElement('file', $file);
            $root_element->appendChild($element);
        }

        // Add file extensions.
        if (!empty($this->_extensions)) {
            $extensions = implode(',', $this->_extensions);
            $this->appendArgument(
                $document,
                $root_element,
                $extensions,
                'extensions'
            );
        }

        // Add ignore patterns.
        foreach ($this->_ignorePatterns as $pattern) {
            $element = $document->createElement('exclude-pattern', $pattern);
            $root_element->appendChild($element);
        }

        // Add the requested Reports..
        foreach ($this->_reports as $report) {
            // Add the report type.
            $this->appendArgument($document, $root_element, $report, 'report');
        }

        // Add the shorthand options.
        $shorthand_options = array(
            'p' => '_showProgress',
            's' => '_showSniffCodes',
        );

        $options = array_filter(
            $shorthand_options,
            function ($value) {
                return $this->$value;
            }
        );

        if (!empty($options)) {
            $this->appendArgument(
                $document,
                $root_element,
                implode('', array_flip($options))
            );
        }

        // Save the file.
        $configSaved = file_put_contents(
            $this->_configFile,
            $document->saveXML()
        );

    }
894774
function toHtml() {
        global $CFG, $USER, $COURSE, $PAGE, $OUTPUT;
        require_once("$CFG->dirroot/repository/lib.php");

        // security - never ever allow guest/not logged in user to upload anything or use this element!
        if (isguestuser() or !isloggedin()) {
            print_error('noguest');
        }

        if ($this->_flagFrozen) {
            return $this->getFrozenHtml();
        }

        $id          = $this->_attributes['id'];
        $elname      = $this->_attributes['name'];
        $subdirs     = $this->_options['subdirs'];
        $maxbytes    = $this->_options['maxbytes'];
        $draftitemid = $this->getValue();
        $accepted_types = $this->_options['accepted_types'];

        if (empty($draftitemid)) {
            // no existing area info provided - let's use fresh new draft area
            require_once("$CFG->libdir/filelib.php");
            $this->setValue(file_get_unused_draft_itemid());
            $draftitemid = $this->getValue();
        }

        $client_id = uniqid();

        // filemanager options
        $options = new stdClass();
        $options->mainfile  = $this->_options['mainfile'];
        $options->maxbytes  = $this->_options['maxbytes'];
        $options->maxfiles  = $this->getMaxfiles();
        $options->client_id = $client_id;
        $options->itemid    = $draftitemid;
        $options->subdirs   = $this->_options['subdirs'];
        $options->target    = $id;
        $options->accepted_types = $accepted_types;
        $options->return_types = $this->_options['return_types'];
        $options->context = $PAGE->context;
        $options->areamaxbytes = $this->_options['areamaxbytes'];

        $html = $this->_getTabs();
        $fm = new form_filemanager($options);
        $output = $PAGE->get_renderer('core', 'files');
        $html .= $output->render($fm);

        $html .= html_writer::empty_tag('input', array('value' => $draftitemid, 'name' => $elname, 'type' => 'hidden', 'id' => $id));

        if (!empty($options->accepted_types) && $options->accepted_types != '*') {
            $html .= html_writer::tag('p', get_string('filesofthesetypes', 'form'));
            $util = new \core_form\filetypes_util();
            $filetypes = $options->accepted_types;
            $filetypedescriptions = $util->describe_file_types($filetypes);
            $html .= $OUTPUT->render_from_template('core_form/filetypes-descriptions', $filetypedescriptions);
        }

        return $html;
    }
1076838
public static function generateDoxygenDocumentation()
	{
		foreach (static::$methods as $methodName => $m) {
			@ list($realMethod, $buffer, $label) = $m;
			echo "/**\n";
			echo "@memberof ", get_called_class(), "\n";
			if ($realMethod == 'setFlag') {
				echo "@fn $methodName()\n";
			} else {
				echo "@fn $methodName(\$sql_statement, ...)\n";
				echo "@param \$sql_statement SQL statement (a fragment of SQL query) with placeholders.\n";
				echo "@param ... Values of placeholders (when positional placeholders are used).\n";
			}
			echo "@public\n";
			if ($realMethod == 'setFlag') {
				echo "@brief Sets content of buffer `$buffer` to `$label`.\n";
			} else if (substr($realMethod, 0, 3) == 'add') {
				if ($label) {
					echo "@brief Appends `\$sql_statement` prefixed with `$label` to buffer `$buffer`.\n";
				} else {
					echo "@brief Appends `\$sql_statement` to buffer `$buffer`.\n";
				}
			} else {
				if ($label) {
					echo "@brief Replaces content of buffer `$buffer` with `\$sql_statement` prefixed with `$label`.\n";
				} else {
					echo "@brief Replaces content of buffer `$buffer` with `\$sql_statement`.\n";
				}
			}
			echo "\n";
			echo "@note This method is generated from FlupdoBuilder::\$methods array. See compileQuery() method for buffer usage.\n";
			echo "*/\n";
			echo "\n";
		}
	}
1265766
public function &_getPost() {
        $global = &$_POST;
        $json = file_get_contents('php://input');
        if (empty($global) && !empty($json)) {
            $global = (array)json_decode($json, true);
        }
        return $global;
    }
1293228
function UI($pollsecs=5)
	{
	global $ADODB_LOG_CONN;

    $perf_table = adodb_perf::table();
	$conn = $this->conn;

	$app = $conn->host;
	if ($conn->host && $conn->database) $app .= ', db=';
	$app .= $conn->database;

	if ($app) $app .= ', ';
	$savelog = $this->conn->LogSQL(false);
	$info = $conn->ServerInfo();
	if (isset($_GET['clearsql'])) {
		$this->clearsql();
	}
	$this->conn->LogSQL($savelog);

	// magic quotes

	if (isset($_GET['sql']) && get_magic_quotes_gpc()) {
		$_GET['sql'] = $_GET['sql'] = str_replace(array("\\'",'\"'),array("'",'"'),$_GET['sql']);
	}

	if (!isset($_SESSION['ADODB_PERF_SQL'])) $nsql = $_SESSION['ADODB_PERF_SQL'] = 10;
	else  $nsql = $_SESSION['ADODB_PERF_SQL'];

	$app .= $info['description'];


	if (isset($_GET['do'])) $do = $_GET['do'];
	else if (isset($_POST['do'])) $do = $_POST['do'];
	 else if (isset($_GET['sql'])) $do = 'viewsql';
	 else $do = 'stats';

	if (isset($_GET['nsql'])) {
		if ($_GET['nsql'] > 0) $nsql = $_SESSION['ADODB_PERF_SQL'] = (integer) $_GET['nsql'];
	}
	echo "<title>ADOdb Performance Monitor on $app</title><body bgcolor=white>";
	if ($do == 'viewsql') $form = "<td><form># SQL:<input type=hidden value=viewsql name=do> <input type=text size=4 name=nsql value=$nsql><input type=submit value=Go></td></form>";
	else $form = "<td>&nbsp;</td>";

	$allowsql = !defined('ADODB_PERF_NO_RUN_SQL');
	global $ADODB_PERF_MIN;
	$app .= " (Min sql timing \$ADODB_PERF_MIN=$ADODB_PERF_MIN secs)";

	if  (empty($_GET['hidem']))
	echo "<table border=1 width=100% bgcolor=lightyellow><tr><td colspan=2>
	<b><a href=http://adodb.sourceforge.net/?perf=1>ADOdb</a> Performance Monitor</b> <font size=1>for $app</font></tr><tr><td>
	<a href=?do=stats><b>Performance Stats</b></a> &nbsp; <a href=?do=viewsql><b>View SQL</b></a>
	 &nbsp; <a href=?do=tables><b>View Tables</b></a> &nbsp; <a href=?do=poll><b>Poll Stats</b></a>",
	 $allowsql ? ' &nbsp; <a href=?do=dosql><b>Run SQL</b></a>' : '',
	 "$form",
	 "</tr></table>";


	 	switch ($do) {
		default:
		case 'stats':
			if (empty($ADODB_LOG_CONN))
				echo "<p>&nbsp; <a href=\"?do=viewsql&clearsql=1\">Clear SQL Log</a><br>";
			echo $this->HealthCheck();
			//$this->conn->debug=1;
			echo $this->CheckMemory();
			break;
		case 'poll':
			$self = htmlspecialchars($_SERVER['PHP_SELF']);
			echo "<iframe width=720 height=80%
				src=\"{$self}?do=poll2&hidem=1\"></iframe>";
			break;
		case 'poll2':
			echo "<pre>";
			$this->Poll($pollsecs);
			break;

		case 'dosql':
			if (!$allowsql) break;

			$this->DoSQLForm();
			break;
		case 'viewsql':
			if (empty($_GET['hidem']))
				echo "&nbsp; <a href=\"?do=viewsql&clearsql=1\">Clear SQL Log</a><br>";
			echo($this->SuspiciousSQL($nsql));
			echo($this->ExpensiveSQL($nsql));
			echo($this->InvalidSQL($nsql));
			break;
		case 'tables':
			echo $this->Tables(); break;
		}
		global $ADODB_vers;
		echo "<p><div align=center><font size=1>$ADODB_vers Sponsored by <a href=http://phplens.com/>phpLens</a></font></div>";
	}
731342
function SelectLimit($sql, $nrows=-1, $offset=-1, $inputarr=false, $secs=0)
	{
		$offsetStr =($offset>=0) ? "$offset," : '';
		// jason judge, see http://phplens.com/lens/lensforum/msgs.php?id=9220
		if ($nrows < 0) {
			$nrows = '18446744073709551615';
		}

		if ($secs) {
			$rs = $this->CacheExecute($secs, $sql . " LIMIT $offsetStr$nrows", $inputarr);
		} else {
			$rs = $this->Execute($sql . " LIMIT $offsetStr$nrows", $inputarr);
		}
		return $rs;
	}
736905
static function generatePHPCodeChildren( $useComments, $php, $tpl, &$nodeChildren, &$resourceData, &$parameters, $currentParameters )
    {
        foreach ( $nodeChildren as $node )
        {
            $newNode = false;
            $nodeType = $node[0];
            if ( $nodeType > eZTemplate::NODE_USER_CUSTOM )
            {
                // Do custom nodes
            }
            else if ( $nodeType > eZTemplate::NODE_INTERNAL )
            {
                // Do custom internal nodes
                if ( $nodeType == eZTemplate::NODE_INTERNAL_CODE_PIECE )
                {
                    $codePiece = $node[1];
                    $spacing = $currentParameters['spacing'];
                    if ( isset( $node[2]['spacing'] ) )
                        $spacing += $node[2]['spacing'];
                    $php->addCodePiece( $codePiece, array( 'spacing' => $spacing ) );
                }
                else if ( $nodeType == eZTemplate::NODE_INTERNAL_WARNING )
                {
                    $warningText = $php->thisVariableText( $node[1], 23, 0, false );
                    $warningLabel = false;
                    $warningLabelText = '';
                    if ( isset( $node[2] ) )
                        $warningLabelText = $php->thisVariableText( $node[2], 0, 0, false );
                    $spacing = $currentParameters['spacing'];
                    if ( isset( $node[3]['spacing'] ) )
                        $spacing += $node[3]['spacing'];
                    $placementText = 'false';
                    if ( isset( $node[4] ) )
                        $placementText = $php->thisVariableText( $node[4], 0, 0, false );
                    $php->addCodePiece( "\$tpl->warning( " . $warningLabelText . ", " . $warningText . ", " . $placementText . " );", array( 'spacing' => $spacing ) );
                }
                else if ( $nodeType == eZTemplate::NODE_INTERNAL_ERROR )
                {
                    $errorText = $php->thisVariableText( $node[1], 21, 0, false );
                    $errorLabel = false;
                    $errorLabelText = '';
                    if ( isset( $node[2] ) )
                        $errorLabelText = $php->thisVariableText( $node[2], 0, 0, false );
                    $spacing = $currentParameters['spacing'];
                    if ( isset( $node[3]['spacing'] ) )
                        $spacing += $node[3]['spacing'];
                    $placementText = 'false';
                    if ( isset( $node[4] ) )
                        $placementText = $php->thisVariableText( $node[4], 0, 0, false );
                    $php->addCodePiece( "\$tpl->error( " . $errorLabelText . ", " . $errorText . ", " . $placementText . " );", array( 'spacing' => $spacing ) );
                }
                else if ( $nodeType == eZTemplate::NODE_INTERNAL_OUTPUT_READ )
                {
                    $variableName = $node[1];
                    $spacing = $currentParameters['spacing'];
                    if ( isset( $node[2]['spacing'] ) )
                        $spacing += $node[2]['spacing'];
                    $textName = eZTemplateCompiler::currentTextName( $parameters );
                    $assignmentType = $node[3];
                    $assignmentText = $php->variableNameText( $variableName, $assignmentType, $node[2] );
                    $php->addCodePiece( "$assignmentText\$$textName;", array( 'spacing' => $spacing ) );
                }
                else if ( $nodeType == eZTemplate::NODE_INTERNAL_OUTPUT_ASSIGN )
                {
                    $variableName = $node[1];
                    $spacing = $currentParameters['spacing'];
                    if ( isset( $node[2]['spacing'] ) )
                        $spacing += $node[2]['spacing'];
                    $textName = eZTemplateCompiler::currentTextName( $parameters );
                    $assignmentType = $node[3];
                    $assignmentText = $php->variableNameText( $textName, $assignmentType, $node[2] );
                    $php->addCodePiece( "$assignmentText\$$variableName;", array( 'spacing' => $spacing ) );
                }
                else if ( $nodeType == eZTemplate::NODE_INTERNAL_OUTPUT_INCREASE )
                {
                    $spacing = $currentParameters['spacing'];
                    if ( isset( $node[1]['spacing'] ) )
                        $spacing += $node[1]['spacing'];
                    $textName = eZTemplateCompiler::currentTextName( $parameters );
                    $php->addCodePiece( "if " . ( $resourceData['use-comments'] ? ( "/*TC:" . __LINE__ . "*/" ) : "" ) . "( !isset( \$textStack ) )\n" .
                                        "    \$textStack = array();\n" .
                                        "\$textStack[] = \$$textName;\n" .
                                        "\$$textName = '';", array( 'spacing' => $spacing ) );
                }
                else if ( $nodeType == eZTemplate::NODE_INTERNAL_OUTPUT_DECREASE )
                {
                    $spacing = $currentParameters['spacing'];
                    if ( isset( $node[1]['spacing'] ) )
                        $spacing += $node[1]['spacing'];
                    $textName = eZTemplateCompiler::currentTextName( $parameters );
                    $php->addCodePiece( "\$$textName = array_pop( \$textStack );", array( 'spacing' => $spacing ) );
                }
                else if ( $nodeType == eZTemplate::NODE_INTERNAL_OUTPUT_SPACING_INCREASE )
                {
                    $spacing = $node[1];
                    $currentParameters['spacing'] += $spacing;
                    continue;
                }
                else if ( $nodeType == eZTemplate::NODE_INTERNAL_SPACING_DECREASE )
                {
                    $spacing = $node[1];
                    $currentParameters['spacing'] -= $spacing;
                    continue;
                }
                else if ( $nodeType == eZTemplate::NODE_INTERNAL_VARIABLE_SET )
                {
                    $variableName = $node[1];
                    $variableValue = $node[2];
                    $spacing = $currentParameters['spacing'];
                    if ( isset( $node[3]['spacing'] ) )
                        $spacing += $node[3]['spacing'];
                    $php->addVariable( $variableName, $variableValue, eZPHPCreator::VARIABLE_ASSIGNMENT, array( 'spacing' => $spacing ) );
                }
                else if ( $nodeType == eZTemplate::NODE_INTERNAL_VARIABLE_UNSET )
                {
                    $variableName = $node[1];
                    $spacing = $currentParameters['spacing'];
                    if ( isset( $node[2]['spacing'] ) )
                        $spacing += $node[2]['spacing'];

                    if ( is_array( $variableName ) )
                    {
                        $namespace = $variableName[0];
                        $namespaceScope = $variableName[1];
                        $variableName = $variableName[2];
                        $namespaceText = eZTemplateCompiler::generateMergeNamespaceCode( $php, $tpl, $namespace, $namespaceScope, array( 'spacing' => $spacing ), true );
                        if ( !is_string( $namespaceText ) )
                            $namespaceText = "\$namespace";
                        $variableNameText = $php->thisVariableText( $variableName, 0, 0, false );
                        if ( isset( $node[2]['remember_set'] ) and $node[2]['remember_set'] )
                        {
                            $php->addCodePiece( "if " . ( $resourceData['use-comments'] ? ( "/*TC:" . __LINE__ . "*/" ) : "" ) . "( isset( \$setArray[$namespaceText][$variableNameText] ) )\n".
                                                "{\n" );
                            $spacing += 4;
                        }
                        if ( isset( $node[2]['local-variable'] ) )
                        {
                            $php->addCodePiece( "\$tpl->unsetLocalVariable( $variableNameText, $namespaceText );\n",
                                                array( 'spacing' => $spacing ) );
                        }
                        else
                        {
                            $php->addCodePiece( "unset( \$vars[$namespaceText][$variableNameText] );",
                                                array( 'spacing' => $spacing ) );
                        }

                        if ( isset( $node[2]['remember_set'] ) and $node[2]['remember_set'] )
                        {
                            $php->addCodePiece( "\n}\n" );
                            $spacing -= 4;
                        }
                    }
                    else
                    {
                        $php->addVariableUnset( $variableName, array( 'spacing' => $spacing ) );
                    }
                }
                else if ( ( $nodeType == eZTemplate::NODE_INTERNAL_RESOURCE_ACQUISITION ) ||
                          ( $nodeType == eZTemplate::NODE_OPTIMIZED_RESOURCE_ACQUISITION ) )
                {
                    $resource = $node[1];
                    $resourceObject = $tpl->resourceHandler( $resource );
                    if ( !$resourceObject )
                        continue;

                    $spacing = $currentParameters['spacing'];
                    if ( isset( $node[7]['spacing'] ) )
                        $spacing += $node[7]['spacing'];
                    $newRootNamespace = $node[8];
                    $resourceVariableName = $node[9];
                    $resourceFilename = isset( $node[10] ) ? $node[10] : false;

                    /* We can only use fallback code if we know upfront which
                     * template is included; it does not work if we are using
                     * something from the ezobjectforwarder which makes the
                     * uriMap an array */
                    $useFallbackCode = true;
                    $uriMap = $node[2];
                    if ( is_string( $uriMap ) )
                    {
                        $uriMap = array( $uriMap );
                    }
                    else
                    {
                        $useFallbackCode = false;
                    }

                    $resourceMap = array();
                    $hasCompiledCode = false;
                    if ( is_array( $uriMap ) )
                    {
                        foreach ( $uriMap as $uriKey => $originalURI )
                        {
                            $uri = $originalURI;
                            if ( $resource )
                                $uri = $resource . ':' . $uri;
                            unset( $tmpResourceData );
                            $tmpResourceData = $tpl->resourceData( $resourceObject, $uri, $node[1], $originalURI );
                            $uriText = $php->thisVariableText( $uri, 0, 0, false );

                            $resourceCanCache = true;
                            if ( !$resourceObject->servesStaticData() )
                                $resourceCanCache = false;
                            if ( !$tpl->isCachingAllowed() )
                                $resourceCanCache = false;

                            $tmpResourceData['text'] = null;
                            $tmpResourceData['root-node'] = null;
                            $tmpResourceData['compiled-template'] = false;
                            $tmpResourceData['time-stamp'] = null;
                            $tmpResourceData['key-data'] = null;
                            $tmpResourceData['use-comments'] = eZTemplateCompiler::isCommentsEnabled();
                            $subSpacing = 0;
                            $hasResourceData = false;

                            $savedLocale = setlocale( LC_CTYPE, null );
                            if ( isset( $GLOBALS['eZTemplateCompilerResourceCache'][$tmpResourceData['template-filename']] ) )
                            {
                                $tmpFileName = $tmpResourceData['template-filename'];
                                unset( $tmpResourceData );
                                $tmpResourceData = $GLOBALS['eZTemplateCompilerResourceCache'][$tmpFileName];
                                $tmpResourceData['compiled-template'] = true;
                                $tmpResourceData['use-comments'] = eZTemplateCompiler::isCommentsEnabled();
                                $hasResourceData = true;
                                $hasCompiledCode = true;
                            }
                            else if ( $useFallbackCode )
                            {
                                // If we can use fallback code we don't need to compile the templates in advance
                                // Simply fake that it has been compiled by setting some variables
                                // Note: Yes this is a hack, but rewriting this code is not an easy task
                                if ( $resourceObject->handleResource( $tpl, $tmpResourceData, $node[4], $node[5] ) )
                                {
                                    $tmpResourceData['compiled-template'] = true;
                                    $hasResourceData = true;
                                    $hasCompiledCode = true;
                                }
                            }
                            else
                            {
                                if ( $resourceObject->handleResource( $tpl, $tmpResourceData, $node[4], $node[5] ) )
                                {
                                    if ( !$tmpResourceData['compiled-template'] and
                                         $tmpResourceData['root-node'] === null )
                                    {
                                        $root =& $tmpResourceData['root-node'];
                                        $root = array( eZTemplate::NODE_ROOT, false );
                                        $templateText =& $tmpResourceData["text"];
                                        $keyData = $tmpResourceData['key-data'];
                                        $rootNamespace = '';
                                        $tpl->parse( $templateText, $root, $rootNamespace, $tmpResourceData );
                                        $hasResourceData = false;
                                    }

                                    /* We always DO need to execute this part if we
                                     * don't have any fallback code. If we can
                                     * generate the fallback code we make the
                                     * included template compile on demand */
                                    if ( !$tmpResourceData['compiled-template'] and
                                         $resourceCanCache and
                                         $tpl->canCompileTemplate( $tmpResourceData, $node[5] ) and
                                         !$useFallbackCode )
                                    {
                                        $generateStatus = $tpl->compileTemplate( $tmpResourceData, $node[5] );

                                        // Time limit #2:
                                        /* We reset the time limit to 60 seconds to
                                         * ensure that remaining template has
                                         * enough time to compile. However if time
                                         * limit is unlimited (0) we leave it be */
                                        $maxExecutionTime = ini_get( 'max_execution_time' );
                                        if ( $maxExecutionTime != 0 && $maxExecutionTime < 60 )
                                        {
                                            @set_time_limit( 60 );
                                        }

                                        if ( $generateStatus )
                                            $tmpResourceData['compiled-template'] = true;
                                    }
                                }
                                $GLOBALS['eZTemplateCompilerResourceCache'][$tmpResourceData['template-filename']] =& $tmpResourceData;
                            }
                            setlocale( LC_CTYPE, $savedLocale );
                            $textName = eZTemplateCompiler::currentTextName( $parameters );
                            if ( $tmpResourceData['compiled-template'] )
                            {
                                $hasCompiledCode = true;
    //                            if ( !eZTemplateCompiler::isFallbackResourceCodeEnabled() )
    //                                $useFallbackCode = false;
                                $keyData = $tmpResourceData['key-data'];
                                $templatePath = $tmpResourceData['template-name'];
                                $key = $resourceObject->cacheKey( $keyData, $tmpResourceData, $templatePath, $node[5] );
                                $cacheFileName = eZTemplateCompiler::compilationFilename( $key, $tmpResourceData );

                                $directory = eZTemplateCompiler::compilationDirectory();
                                $phpScript = eZDir::path( array( $directory, $cacheFileName ) );
                                $phpScriptText = $php->thisVariableText( $phpScript, 0, 0, false );
                                $resourceMap[$uriKey] = array( 'key' => $uriKey,
                                                               'uri' => $uri,
                                                               'phpscript' => $phpScript );
                            }
                        }
                    }

                    if ( $useComments )
                    {
                        $variablePlacement = $node[6];
                        if ( $variablePlacement )
                        {
                            $originalText = eZTemplateCompiler::fetchTemplatePiece( $variablePlacement );
                            $php->addComment( "Resource Acquisition:", true, true, array( 'spacing' => $spacing ) );
                            $php->addComment( $originalText, true, true, array( 'spacing' => $spacing ) );
                        }
                    }

                    if ( $hasCompiledCode )
                    {
                        if ( $resourceVariableName )
                        {
                            $phpScriptText = '$phpScript';
                            $phpScriptArray = array();

                            foreach ( $resourceMap as $resourceMapItem )
                            {
                                $phpScriptArray[$resourceMapItem['key']] = $resourceMapItem['phpscript'];
                            }

                            if ( !$resourceFilename ) /* Not optimized version */
                            {
                                $php->addVariable( "phpScriptArray", $phpScriptArray, eZPHPCreator::VARIABLE_ASSIGNMENT, array( 'spacing' => $spacing ) );
                                $resourceVariableNameText = "\$$resourceVariableName";
                                $php->addCodePiece( "\$phpScript = isset( \$phpScriptArray[$resourceVariableNameText] ) ? \$phpScriptArray[$resourceVariableNameText] : false;\n", array( 'spacing' => $spacing ) );
                            }
                            else /* Optimised version */
                            {
                                $php->addVariable( "phpScript", $phpScriptArray[$node[10]], eZPHPCreator::VARIABLE_ASSIGNMENT, array('spacing' => $spacing ) );
                            }

                            // The default is to only check if it exists
                            $modificationCheckText = "file_exists( $phpScriptText )";
                            if  ( eZTemplateCompiler::isDevelopmentModeEnabled() )
                            {
                                $modificationCheckText = "file_exists( $phpScriptText ) && filemtime( $phpScriptText ) > filemtime( $uriText )";
                            }
                            $php->addCodePiece( "\$resourceFound = false;\nif " . ( $resourceData['use-comments'] ? ( "/*TC:" . __LINE__ . "*/" ) : "" ) . "( $phpScriptText !== false and $modificationCheckText )\n{\n", array( 'spacing' => $spacing ) );
                        }
                        else
                        {
                            $php->addCodePiece( "\$resourceFound = false;\n", array( 'spacing' => $spacing ) );
                            $phpScript = $resourceMap[0]['phpscript'];
                            $phpScriptText = $php->thisVariableText( $phpScript, 0, 0, false );
                            // Not sure where this should come from
//                         if ( $resourceIndex > 0 )
//                             $php->addCodePiece( "else " );
                            // The default is to only check if it exists
                            $modificationCheckText = "file_exists( $phpScriptText )";
                            if  ( eZTemplateCompiler::isDevelopmentModeEnabled() )
                            {
                                $modificationCheckText = "file_exists( $phpScriptText ) && filemtime( $phpScriptText ) > filemtime( $uriText )";
                            }
                            $php->addCodePiece( "if " . ( $resourceData['use-comments'] ? ( "/*TC:" . __LINE__ . "*/" ) : "" ) . "( $modificationCheckText )\n{\n", array( 'spacing' => $spacing ) );

                        }

                        /* Generate code to do a namespace switch and includes the template */
                        $code = "\$resourceFound = true;\n\$namespaceStack[] = array( \$rootNamespace, \$currentNamespace );\n";
                        if ( $newRootNamespace )
                        {
                            $newRootNamespaceText = $php->thisVariableText( $newRootNamespace, 0, 0, false );
                            $code .= "\$currentNamespace = \$rootNamespace = !\$currentNamespace ? $newRootNamespaceText : ( \$currentNamespace . ':' . $newRootNamespaceText );\n";
                        }
                        else
                        {
                            $code .= "\$rootNamespace = \$currentNamespace;\n";
                        }

                        $code .=
                            "\$tpl->createLocalVariablesList();\n" .
                            "\$tpl->appendTemplateFetch( $uriText );\n" . // Make sure the template file is recorded, like in loadURIRoot
                            "include( '" . eZTemplateCompiler::TemplatePrefix() . "' . $phpScriptText );\n" .
                            "\$tpl->unsetLocalVariables();\n" .
                            "\$tpl->destroyLocalVariablesList();\n" .
                            "list( \$rootNamespace, \$currentNamespace ) = array_pop( \$namespaceStack );\n";

                        $php->addCodePiece( $code, array( 'spacing' => $spacing + 4 ) );
                        if ( $useFallbackCode )
                            $php->addCodePiece( "}\nelse\n{\n    \$resourceFound = true;\n", array( 'spacing' => $spacing ) );
                        else
                            $php->addCodePiece( "}\n", array( 'spacing' => $spacing ) );
                        $subSpacing = 4;
                    }
                    else
                    {
                        /* Yes, this is a hack, but it is required because
                         * sometimes the generated nodes after this one emit an
                         * else statement while there is no accompanied if */
                        $php->addCodePiece( "\nif " . ( $resourceData['use-comments'] ? ( "/*TC:" . __LINE__ . "*/" ) : "" ) . "(false)\n{\n}\n" );
                    }

                    /* The fallback code will be added if we need to process an
                     * URI, this will also compile a template then. We need to
                     * do the namespace switch manually here otherwise the
                     * processed template will be run on the node from which
                     * the template was included from. */
                    if ( $useFallbackCode )
                    {
                        $code = "\$resourceFound = true;\n\$namespaceStack[] = array( \$rootNamespace, \$currentNamespace );\n";
                        if ( $newRootNamespace )
                        {
                            $newRootNamespaceText = $php->thisVariableText( $newRootNamespace, 0, 0, false );
                            $code .= "\$currentNamespace = \$rootNamespace = !\$currentNamespace ? $newRootNamespaceText : ( \$currentNamespace . ':' . $newRootNamespaceText );\n";
                        }
                        else
                        {
                            $code .= "\$rootNamespace = \$currentNamespace;\n";
                        }
                        $php->addCodePiece( $code );

                        $php->addCodePiece( "\$textElements = array();\n\$extraParameters = array();\n\$tpl->processURI( $uriText, true, \$extraParameters, \$textElements, \$rootNamespace, \$currentNamespace );\n\$$textName .= implode( '', \$textElements );\n", array( 'spacing' => $spacing + $subSpacing ) );
                        $php->addCodePiece( "list( \$rootNamespace, \$currentNamespace ) = array_pop( \$namespaceStack );\n" );
                    }

                    if ( $hasCompiledCode and $useFallbackCode )
                    {
                        $php->addCodePiece( "}\n", array( 'spacing' => $spacing ) );
                    }
                }
                else if ( $nodeType == eZTemplate::NODE_INTERNAL_NAMESPACE_CHANGE )
                {
                    $variableData = $node[1];
                    $spacing = $currentParameters['spacing'];
                    if ( isset( $node[2]['spacing'] ) )
                        $spacing += $node[2]['spacing'];
                    $php->addCodePiece( "\$namespaceStack[] = \$currentNamespace;\n", array( 'spacing' => $spacing ) );
                    $php->addCodePiece( '$currentNamespace .= ( $currentNamespace ? ":" : "" ) . \''. $variableData[0][1] . '\';' . "\n", array( 'spacing' => $spacing ) );
                }
                else if ( $nodeType == eZTemplate::NODE_INTERNAL_NAMESPACE_RESTORE )
                {
                    $spacing = $currentParameters['spacing'];
                    if ( isset( $node[1]['spacing'] ) )
                        $spacing += $node[1]['spacing'];
                    $php->addCodePiece( "\$currentNamespace = array_pop( \$namespaceStack );\n", array( 'spacing' => $spacing ) );
                }
                else if ( $nodeType == eZTemplate::NODE_OPTIMIZED_INIT )
                {
                    $code = <<<END
\$node = ( array_key_exists( \$rootNamespace, \$vars ) and array_key_exists( "node", \$vars[\$rootNamespace] ) ) ? \$vars[\$rootNamespace]["node"] : null;
if ( is_object( \$node ) )
\$object = \$node->attribute( 'object' );
if ( isset( \$object ) && is_object( \$object ) )
\$nod_{$resourceData['uniqid']} = \$object->attribute( 'data_map' );
else
\$nod_{$resourceData['uniqid']} = false;
unset( \$node, \$object );

END;
                    $php->addCodePiece($code);
                    // Tell the rest of the system that we have create the nod_* variable
                    $resourceData['node-object-cached'] = true;
                }
                else
                    eZDebug::writeWarning( "Unknown internal template node type $nodeType, ignoring node for code generation",
                                           'eZTemplateCompiler:generatePHPCodeChildren' );
            }
            else if ( $nodeType == eZTemplate::NODE_ROOT )
            {
                $children = $node[1];
                if ( $children )
                {
                    $newCurrentParameters = $currentParameters;
                    $newCurrentParameters['spacing'] += 4;
                    eZTemplateCompiler::generatePHPCodeChildren( $useComments, $php, $tpl, $children, $resourceData, $parameters, $newCurrentParameters );
                }
                continue;
            }
            else if ( $nodeType == eZTemplate::NODE_TEXT )
            {
                $text = $node[2];
                if ( $text != '' )
                {
                    $variablePlacement = $node[3];
                    $originalText = eZTemplateCompiler::fetchTemplatePiece( $variablePlacement );
                    if ( $useComments )
                    {
                        $php->addComment( "Text start:", true, true, array( 'spacing' => $currentParameters['spacing'] ) );
                        $php->addComment( $originalText, true, true, array( 'spacing' => $currentParameters['spacing'] ) );
                        $php->addComment( "Text end:", true, true, array( 'spacing' => $currentParameters['spacing'] ) );
                    }
                    $php->addVariable( eZTemplateCompiler::currentTextName( $parameters ),
                                       $text, eZPHPCreator::VARIABLE_APPEND_TEXT,
                                       array( 'spacing' => $currentParameters['spacing'] ) );
                }
                continue;
            }
            else if ( $nodeType == eZTemplate::NODE_VARIABLE )
            {
                $variableAssignmentName = $node[1];
                $variableData = $node[2];
                $variablePlacement = $node[3];

                $variableParameters = array();
                if ( isset( $node[4] ) and
                     $node[4] )
                    $variableParameters = $node[4];
                $variableOnlyExisting = isset( $node[5] ) ? $node[5] : false;
                $variableOverWrite = isset( $node[6] ) ? $node[6] : false;
                $rememberSet = isset( $node[7] ) ? $node[7] : false;

                $spacing = $currentParameters['spacing'];
                if ( isset( $variableParameters['spacing'] ) )
                    $spacing += $variableParameters['spacing'];
                $variableParameters = array_merge( array( 'variable-name' => 'var',
                                                          'text-result' => true ),
                                                   $variableParameters );
                $dataInspection = eZTemplateCompiler::inspectVariableData( $tpl,
                                                                           $variableData, $variablePlacement,
                                                                           $resourceData );
                $newNode = $node;
                $newNode[1] = false;

                $treatVariableDataAsNonObject = isset( $variableParameters['treat-value-as-non-object'] ) && $variableParameters['treat-value-as-non-object'];

                if ( $useComments )
                {
                    $php->addComment( "Variable data: " .
                                      "Is constant: " . ( $dataInspection['is-constant'] ? 'Yes' : 'No' ) .
                                      " Is variable: " . ( $dataInspection['is-variable'] ? 'Yes' : 'No' ) .
                                      " Has attributes: " . ( $dataInspection['has-attributes'] ? 'Yes' : 'No' ) .
                                      " Has operators: " . ( $dataInspection['has-operators'] ? 'Yes' : 'No' ),
                                      true, true, array( 'spacing' => $spacing )
                                      );
                    $originalText = eZTemplateCompiler::fetchTemplatePiece( $variablePlacement );
                    $php->addComment( '{' . $originalText . '}', true, true, array( 'spacing' => $spacing ) );
                }
                $generatedVariableName = $variableParameters['variable-name'];
                $assignVariable = false;
                if ( $variableAssignmentName !== false )
                {
                    if ( is_array( $variableAssignmentName ) )
                    {
                        $variableParameters['text-result'] = false;
                        $assignVariable = true;
                    }
                    else
                    {
                        $generatedVariableName = $variableAssignmentName;
                        $variableParameters['text-result'] = false;
                    }
                }

                $isStaticElement = false;
                $nodeElements = $node[2];
                $knownTypes = array();
                if ( eZTemplateNodeTool::isConstantElement( $nodeElements ) and
                     !$variableParameters['text-result'] )
                {
                    $variableText = $php->thisVariableText( eZTemplateNodeTool::elementConstantValue( $nodeElements ), 0, 0, false );
                    $isStaticElement = true;
                }
                else if ( eZTemplateNodeTool::isPHPVariableElement( $nodeElements ) and
                          !$variableParameters['text-result'] )
                {
                    $variableText = '$' . eZTemplateNodeTool::elementConstantValue( $nodeElements );
                    $isStaticElement = true;
                }
                else
                {
                    $variableText = "\$$generatedVariableName";
                    eZTemplateCompiler::generateVariableCode( $php, $tpl, $node, $knownTypes, $dataInspection,
                                                              array( 'spacing' => $spacing,
                                                                     'variable' => $generatedVariableName,
                                                                     'treat-value-as-non-object' => $treatVariableDataAsNonObject,
                                                                     'counter' => 0 ),
                                                              $resourceData );
                }

                if ( $variableParameters['text-result'] )
                {
                    $textName = eZTemplateCompiler::currentTextName( $parameters );
                    if ( count( $knownTypes ) == 0 or in_array( 'objectproxy', $knownTypes ) )
                    {
                        $php->addCodePiece( "\$$textName .= ( is_object( \$$generatedVariableName ) ? compiledFetchText( \$tpl, \$rootNamespace, \$currentNamespace, false, \$$generatedVariableName ) : \$$generatedVariableName );" .  ( $resourceData['use-comments'] ? ( "/*TC:" . __LINE__ . "*/" ) : "" ) . "\n" .
                                            "unset( \$$generatedVariableName );\n", array( 'spacing' => $spacing ) );
                    }
                    else
                    {
                        $php->addCodePiece( "\$$textName .= \$$generatedVariableName;\n" .
                                            "unset( \$$generatedVariableName );\n", array( 'spacing' => $spacing ) );
                    }
                }
                else if ( $assignVariable )
                {
                    $namespace = $variableAssignmentName[0];
                    $namespaceScope = $variableAssignmentName[1];
                    $variableName = $variableAssignmentName[2];
                    $namespaceText = eZTemplateCompiler::generateMergeNamespaceCode( $php, $tpl, $namespace, $namespaceScope, array( 'spacing' => $spacing ), true );
                    if ( !is_string( $namespaceText ) )
                        $namespaceText = "\$namespace";
                    $variableNameText = $php->thisVariableText( $variableName, 0, 0, false );
                    $unsetVariableText = false;
                    if ( $variableOnlyExisting )
                    {
                        if ( !$isStaticElement )
                            $unsetVariableText = "\n    unset( $variableText );";
                        $php->addCodePiece( "if " . ( $resourceData['use-comments'] ? ( "/*TC:" . __LINE__ . "*/" ) : "" ) . "( array_key_exists( $namespaceText, \$vars ) && array_key_exists( $variableNameText, \$vars[$namespaceText] ) )\n".
                                            "{\n".
                                            "    \$vars[$namespaceText][$variableNameText] = $variableText;$unsetVariableText\n".
                                            "}",
                                            array( 'spacing' => $spacing ) );
                    }
                    else if ( $variableOverWrite )
                    {
                        if ( !$isStaticElement )
                            $unsetVariableText = "\nunset( $variableText );";
                        if ( isset( $variableParameters['local-variable'] ) )
                        {
                            $php->addCodePiece( "if ( \$tpl->hasVariable( $variableNameText, $namespaceText ) )\n{\n" ); // if the variable already exists
                            $php->addCodePiece( "    \$tpl->warning( '" . eZTemplateDefFunction::DEF_FUNCTION_NAME . "', \"Variable '$variableName' is already defined.\", " . $php->thisVariableText( $variablePlacement ) . " );\n" );
                            $php->addCodePiece( "    \$tpl->setVariable( $variableNameText, $variableText, $namespaceText );\n}\nelse\n{\n" );
                            $php->addCodePiece( "    \$tpl->setLocalVariable( $variableNameText, $variableText, $namespaceText );\n}\n" ,
                                                array( 'spacing' => $spacing ) );
                        }
                        else
                        {
                            $php->addCodePiece( "\$vars[$namespaceText][$variableNameText] = $variableText;$unsetVariableText",
                                                array( 'spacing' => $spacing ) );
                        }

                    }
                    else if ( $rememberSet )
                    {
                        if ( !$isStaticElement )
                            $unsetVariableText = "\n    unset( $variableText );";
                        $php->addCodePiece( "if " . ( $resourceData['use-comments'] ? ( "/*TC:" . __LINE__ . "*/" ) : "" ) . "( !isset( \$vars[$namespaceText][$variableNameText] ) )\n".
                                            "{\n".
                                            "    \$vars[$namespaceText][$variableNameText] = $variableText;$unsetVariableText\n".
                                            "    \$setArray[$namespaceText][$variableNameText] = true;\n".
                                            "}\n",
                                            array( 'spacing' => $spacing ) );
                    }
                    else
                    {
                        if ( !$isStaticElement )
                            $unsetVariableText = "\n    unset( $variableText );";
                        $php->addCodePiece( "if " . ( $resourceData['use-comments'] ? ( "/*TC:" . __LINE__ . "*/" ) : "" ) . "( !isset( \$vars[$namespaceText][$variableNameText] ) )\n{\n    \$vars[$namespaceText][$variableNameText] = $variableText;$unsetVariableText\n}",
                                            array( 'spacing' => $spacing ) );
                    }
                }
                else if ( $variableAssignmentName !== false and $isStaticElement )
                {
                    $php->addCodePiece( "\$$generatedVariableName = $variableText;", array( 'spacing' => $spacing ) );
                }
                else if ( $variableAssignmentName !== false and !$isStaticElement and !$treatVariableDataAsNonObject )
                {
                    // Normal assignment from an expression, no need to anything extra
                }
                unset( $dataInspection );
            }
            else if ( $nodeType == eZTemplate::NODE_FUNCTION )
            {
                $functionChildren = $node[1];
                $functionName = $node[2];
                $functionParameters = $node[3];
                $functionPlacement = $node[4];

                $newNode = array( $nodeType,
                                  false,
                                  $functionName,
                                  $functionParameters,
                                  $functionPlacement );

                $parameterText = 'No parameters';
                if ( $functionParameters )
                {
                    $parameterText = "Parameters: ". implode( ', ', array_keys( $functionParameters ) );
                }
                if ( $useComments )
                {
                    $php->addComment( "Function: $functionName, $parameterText", true, true, array( 'spacing' => $currentParameters['spacing'] ) );
                    $originalText = eZTemplateCompiler::fetchTemplatePiece( $functionPlacement );
                    $php->addComment( '{' . $originalText . '}', true, true, array( 'spacing' => $currentParameters['spacing'] ) );
                }
                if ( isset( $node[5] ) )
                {
                    $functionHook = $node[5];
                    $functionHookCustomFunction = $functionHook['function'];
                    if ( $functionHookCustomFunction )
                    {
                        $functionHookCustomFunction = array_merge( array( 'add-function-name' => false,
                                                                          'add-hook-name' => false,
                                                                          'add-template-handler' => true,
                                                                          'add-function-hook-data' => false,
                                                                          'add-function-parameters' => true,
                                                                          'add-function-placement' => false,
                                                                          'add-calculated-namespace' => false,
                                                                          'add-namespace' => true,
                                                                          'add-input' => false,
                                                                          'return-value' => false ),
                                                                   $functionHookCustomFunction );
                        if ( !isset( $parameters['hook-result-variable-counter'][$functionName] ) )
                            $parameters['hook-result-variable-counter'][$functionName] = 0;
                        if ( $functionHookCustomFunction['return-value'] )
                            $parameters['hook-result-variable-counter'][$functionName]++;
                        $hookResultName = $functionName . 'Result' . $parameters['hook-result-variable-counter'][$functionName];
                        if ( $functionHookCustomFunction['add-input'] )
                            $parameters['hook-result-variable-counter'][$functionName]--;
                        $functionHookCustomFunctionName = $functionHookCustomFunction['name'];
                        $codeText = '';
                        if ( $functionHookCustomFunction['return-value'] )
                            $codeText = "\$$hookResultName = ";
                        if ( $functionHookCustomFunction['static'] )
                        {
                            $hookClassName = $functionHookCustomFunction['class-name'];
                            $codeText .= "$hookClassName::$functionHookCustomFunctionName( ";
                        }
                        else
                            $codeText .= "\$functionObject->$functionHookCustomFunctionName( ";
                        $codeTextLength = strlen( $codeText );

                        $functionNameText = $php->thisVariableText( $functionName, 0, 0, false );
                        $functionChildrenText = $php->thisVariableText( $functionChildren, $codeTextLength, 0, false );

                        $inputFunctionParameters = $functionParameters;
                        if ( $functionHookCustomFunction['add-calculated-namespace'] )
                            unset( $inputFunctionParameters['name'] );
                        $functionParametersText = $php->thisVariableText( $inputFunctionParameters, $codeTextLength, 0, false );

                        $functionPlacementText = $php->thisVariableText( $functionPlacement, $codeTextLength, 0, false );
                        $functionHookText = $php->thisVariableText( $functionHook, $codeTextLength, 0, false );

                        $functionHookName = $functionHook['name'];
                        $functionHookNameText = $php->thisVariableText( $functionHookName, 0, 0, false );

                        $codeParameters = array();
                        if ( $functionHookCustomFunction['add-function-name'] )
                            $codeParameters[] = $functionNameText;
                        if ( $functionHookCustomFunction['add-hook-name'] )
                            $codeParameters[] = $functionHookNameText;
                        if ( $functionHookCustomFunction['add-function-hook-data'] )
                            $codeParameters[] = $functionHookText;
                        if ( $functionHookCustomFunction['add-template-handler'] )
                            $codeParameters[] = "\$tpl";
                        if ( $functionHookCustomFunction['add-function-parameters'] )
                            $codeParameters[] = $functionParametersText;
                        if ( $functionHookCustomFunction['add-function-placement'] )
                            $codeParameters[] = $functionPlacementText;
                        if ( $functionHookCustomFunction['add-calculated-namespace'] )
                        {
                            $name = '';
                            if ( isset( $functionParameters['name'] ) )
                            {
                                $nameParameter = $functionParameters['name'];
                                $nameInspection = eZTemplateCompiler::inspectVariableData( $tpl,
                                                                                           $nameParameter, $functionPlacement,
                                                                                           $resourceData );
                                if ( $nameInspection['is-constant'] and
                                     !$nameInspection['is-variable'] and
                                     !$nameInspection['has-attributes'] and
                                     !$nameInspection['has-operators'] )
                                {
                                    $nameData = $nameParameter[0][1];
                                    $nameText = $php->thisVariableText( $nameData, 0, 0, false );
                                    $php->addCodePiece( "if ( \$currentNamespace != '' )
    \$name = \$currentNamespace . ':' . $nameText;
else
    \$name = $nameText;\n", array( 'spacing' => $currentParameters['spacing'] ) );
                                    $codeParameters[] = "\$name";
                                }
                                else
                                {
                                    $persistence = array();
                                    $knownTypes = array();
                                    eZTemplateCompiler::generateVariableDataCode( $php, $tpl, $nameParameter, $knownTypes, $nameInspection,
                                                                                  $persistence,
                                                                                  array( 'variable' => 'name',
                                                                                         'counter' => 0 ),
                                                                                  $resourceData );
                                    $php->addCodePiece( "if " . ( $resourceData['use-comments'] ? ( "/*TC:" . __LINE__ . "*/" ) : "" ) . "( \$currentNamespace != '' )
{
    if ( \$name != '' )
        \$name = \"\$currentNamespace:\$name\";
    else
        \$name = \$currentNamespace;
}\n", array( 'spacing' => $currentParameters['spacing'] ) );
                                    $codeParameters[] = "\$name";
                                }
                            }
                            else
                            {
                                $codeParameters[] = "\$currentNamespace";
                            }
                        }
                        if ( $functionHookCustomFunction['add-namespace'] )
                            $codeParameters[] = "\$rootNamespace, \$currentNamespace";
                        if ( $functionHookCustomFunction['add-input'] )
                            $codeParameters[] = "\$$hookResultName";
                        $codeText .= implode( ",\n" . str_repeat( ' ', $codeTextLength ),
                                              $codeParameters );
                        $codeText .= " );\n";
                        if ( $functionHookCustomFunction['static'] )
                        {
                            $hookFile = $functionHookCustomFunction['php-file'];
                            $hookFileText = $php->thisVariableText( $hookFile, 0, 0, false );
                            $php->addCodePiece( "include_once( $hookFileText );\n", array( 'spacing' => $currentParameters['spacing'] ) );
                        }
                        else
                            $php->addCodePiece( "\$functionObject = \$tpl->fetchFunctionObject( $functionNameText );\n", array( 'spacing' => $currentParameters['spacing'] ) );
                        $php->addCodePiece( $codeText, array( 'spacing' => $currentParameters['spacing'] ) );
                    }
                    else
                    {
                        $functionNameText = $php->thisVariableText( $functionName, 0, 0, false );
                        $functionChildrenText = $php->thisVariableText( $functionChildren, 52, 0, false );
                        $functionParametersText = $php->thisVariableText( $functionParameters, 52, 0, false );
                        $functionPlacementText = $php->thisVariableText( $functionPlacement, 52, 0, false );

                        $functionHookText = $php->thisVariableText( $functionHook, 52, 0, false );
                        $functionHookName = $functionHook['name'];
                        $functionHookNameText = $php->thisVariableText( $functionHookName, 0, 0, false );
                        $functionHookParameters = $functionHook['parameters'];
                        $php->addCodePiece( "\$functionObject = \$tpl->fetchFunctionObject( $functionNameText );
\$hookResult = \$functionObject->templateHookProcess( $functionNameText, $functionHookNameText,
                                                    $functionHookText,
                                                    \$tpl,
                                                    $functionParametersText,
                                                    $functionPlacementText,
                                                    \$rootNamespace, \$currentNamespace );
", array( 'spacing' => $currentParameters['spacing'] ) );
                    }
                }
                else
                {
                    $textName = eZTemplateCompiler::currentTextName( $parameters );
                    $functionNameText = $php->thisVariableText( $functionName, 0, 0, false );
                    $functionChildrenText = $php->thisVariableText( $functionChildren, 22, 0, false );
                    $functionParametersText = $php->thisVariableText( $functionParameters, 22, 0, false );
                    $functionPlacementText = $php->thisVariableText( $functionPlacement, 22, 0, false );
                    $php->addCodePiece( "\$textElements = array();
\$tpl->processFunction( $functionNameText, \$textElements,
                       $functionChildrenText,
                       $functionParametersText,
                       $functionPlacementText,
                       \$rootNamespace, \$currentNamespace );
\$$textName .= implode( '', \$textElements );\n", array( 'spacing' => $currentParameters['spacing'] ) );
                }
            }
            $php->addSpace();
        }
    }
902863
function invoke() {
        parent::invoke();

        $result = true;

        // Set own core attributes
        $this->does_generate = ACTION_GENERATE_HTML;

        // These are always here
        global $CFG, $XMLDB, $DB;

        // Calculate list of available SQL generators
        require_once("$CFG->libdir/ddl/sql_generator.php");
        $reserved_words = sql_generator::getAllReservedWords();

        // Now, calculate, looking into current DB (with AdoDB Metadata), which fields are
        // in the list of reserved words
        $wronguses = array();
        $dbtables = $DB->get_tables();
        if ($dbtables) {
            foreach ($dbtables as $table) {
                if (array_key_exists($table, $reserved_words)) {
                    $wronguses[] = $this->str['table'] . ' - ' . $table . ' (' . implode(', ',$reserved_words[$table]) . ')';

                }
                $dbfields = $DB->get_columns($table);
                if ($dbfields) {
                    foreach ($dbfields as $dbfield) {
                        if (array_key_exists($dbfield->name, $reserved_words)) {
                            $wronguses[] = $this->str['field'] . ' - ' . $table . '->' . $dbfield->name . ' (' . implode(', ',$reserved_words[$dbfield->name]) . ')';
                        }
                    }
                }
            }
        }

        // Sort the wrong uses
        sort($wronguses);

        // The back to edit table button
        $b = ' <p class="centerpara buttons">';
        $b .= '<a href="index.php">[' . $this->str['back'] . ']</a>';
        $b .= '</p>';
        $o = $b;

        // The list of currently wrong field names
        if ($wronguses) {
            $o.= '    <table id="formelements" class="boxaligncenter" cellpadding="5">';
            $o.= '      <tr><td align="center"><font color="red">' . $this->str['wrongreservedwords'] . '</font></td></tr>';
            $o.= '      <tr><td>';
            $o.= '        <ul><li>' . implode('</li><li>', $wronguses) . '</li></ul>';
            $o.= '      </td></tr>';
            $o.= '    </table>';
        }

        // The textarea showing all the reserved words
        $o.= '    <table id="formelements" class="boxaligncenter" cellpadding="5">';
        $o.= '      <tr><td align="center">' . $this->str['listreservedwords'].'</td></tr>';
        $o .= '      <tr><td><textarea cols="80" rows="32" class="form-control">';
        $o.= s(implode(', ', array_keys($reserved_words)));
        $o.= '</textarea></td></tr>';
        $o.= '    </table>';

        $this->output = $o;

        // Launch postaction if exists (leave this here!)
        if ($this->getPostAction() && $result) {
            return $this->launch($this->getPostAction());
        }

        // Return ok if arrived here
        return $result;
    }
763766
public function compileFrom()
    {
        $fromQuery = '';

        foreach ($this->query->getQueryFrom() as $key => $value) {
            if ($key == 0) {
                $fromQuery = "$value";
            } else {
                $fromQuery .= ",$value";
            }
        }

        $this->queryString = "{$this->queryString} FROM $fromQuery";
    }
3576
public function main()
    {
        $this->validate();

        $buf = "Database settings:\n"
            . " driver: " . ($this->databaseDriver ? $this->databaseDriver : "(default)" ). "\n"
            . " URL: " . $this->databaseUrl . "\n"
            . ($this->databaseUser ? " user: " . $this->databaseUser . "\n" : "")
            . ($this->databasePassword ? " password: " . $this->databasePassword . "\n" : "");

        $this->log($buf, Project::MSG_VERBOSE);

        // 1) First create the Data XML -> database name map.
        $this->createDataDbMap();

        // 2) Now go create the XML files from teh database(s)
        foreach ($this->getDataModels() as $dataModel) { // there is really one 1 db per datamodel
            foreach ($dataModel->getDatabases() as $database) {

                // if database name is specified, then we only want to dump that one db.
                if (empty($this->databaseName) || ($this->databaseName && $database->getName() == $this->databaseName)) {

                    $outFile = $this->getMappedFile($dataModel->getName());

                    $this->log("Dumping data to XML for database: " . $database->getName());
                    $this->log("Writing to XML file: " . $outFile->getName());

                    try {
                        $this->conn = $dataModel->getGeneratorConfig()->getBuildPDO($database->getName());

                        $doc = $this->createXMLDoc($database);
                        $doc->save($outFile->getAbsolutePath());
                    } catch (SQLException $se) {
                        $this->log("SQLException while connecting to DB: " . $se->getMessage(), Project::MSG_ERR);
                        throw new BuildException($se);
                    }
                } // if databaseName && database->getName == databaseName
            } // foreach database
        } // foreach datamodel
    }
739312
public function debugDumpParams()
    {
        $str  = "SQL: [".strlen($this->_statement)."] ".$this->_statement."\n";
        $str .= "Params: ".sizeof($this->_binds)."\n";
        foreach ($this->_binds as $key => $value) {
            $str .= "Key: Name: [".strlen($key)."] $key\n";
            $str .= "name=[".strlen($key)."] \"$key\"\n";
            $str .= "is_param=1\n";
        }
        echo substr($str, 0, strlen($str)-1);
    }
1061005
static function run_php($command, $background_mode = false, $ignore_duplicates = true)
    {
        if (!$ignore_duplicates || empty(self::$running_commands[$command])) {
            $config = Config::read('core');
            $php = empty($config['php']) ? 'php' : $config['php'];
            if (substr(php_uname(), 0, 7) == "Windows") {
                pclose(popen('start' . ($background_mode ? ' /B ' : ' ') . $php . ' ' . $command, "r"));
            } else {
                exec($php . ' ' . $command . ($background_mode ? " > /dev/null &" : ''));
            }
        }
        self::$running_commands[$command] = true;
    }
780912
function _doCapt($oID, $amt = 0, $currency = 'USD') {
    global $db, $messageStack;

    //@TODO: Read current order status and determine best status to set this to
    $new_order_status = (int)MODULE_PAYMENT_AUTHORIZENET_AIM_ORDER_STATUS_ID;
    if ($new_order_status == 0) $new_order_status = 1;

    $proceedToCapture = true;
    $captureNote = strip_tags(zen_db_input($_POST['captnote']));
    if (isset($_POST['captconfirm']) && $_POST['captconfirm'] == 'on') {
    } else {
      $messageStack->add_session(MODULE_PAYMENT_AUTHORIZENET_AIM_TEXT_CAPTURE_CONFIRM_ERROR, 'error');
      $proceedToCapture = false;
    }
    if (isset($_POST['btndocapture']) && $_POST['btndocapture'] == MODULE_PAYMENT_AUTHORIZENET_AIM_ENTRY_CAPTURE_BUTTON_TEXT) {
      $captureAmt = (float)$_POST['captamt'];
/*
      if ($captureAmt == 0) {
        $messageStack->add_session(MODULE_PAYMENT_AUTHORIZENET_AIM_TEXT_INVALID_CAPTURE_AMOUNT, 'error');
        $proceedToCapture = false;
      }
*/
    }
    if (isset($_POST['captauthid']) && trim($_POST['captauthid']) != '') {
      // okay to proceed
    } else {
      $messageStack->add_session(MODULE_PAYMENT_AUTHORIZENET_AIM_TEXT_TRANS_ID_REQUIRED_ERROR, 'error');
      $proceedToCapture = false;
    }
    /**
     * Submit capture request to Authorize.net
     */
    if ($proceedToCapture) {
      // Populate an array that contains all of the data to be sent to Authorize.net
      unset($submit_data);
      $submit_data = array(
                           'x_type' => 'PRIOR_AUTH_CAPTURE',
                           'x_amount' => number_format($captureAmt, 2),
                           'x_trans_id' => strip_tags(trim($_POST['captauthid'])),
//                         'x_invoice_num' => $new_order_id,
//                         'x_po_num' => $order->info['po_number'],
//                         'x_freight' => $order->info['shipping_cost'],
//                         'x_tax_exempt' => 'FALSE', /* 'TRUE' or 'FALSE' */
//                         'x_tax' => $order->info['tax'],
                           );

      $response = $this->_sendRequest($submit_data);
      $response_code = $response[0];
      $response_text = $response[3];
      $response_alert = $response_text . ($this->commError == '' ? '' : ' Communications Error - Please notify webmaster.');
      $this->reportable_submit_data['Note'] = $captureNote;
      $this->_debugActions($response);

      if ($response_code != '1' || ($response[0]==1 && $response[2] == 311) ) {
        $messageStack->add_session($response_alert, 'error');
      } else {
        // Success, so save the results
        $sql_data_array = array('orders_id' => (int)$oID,
                                'orders_status_id' => (int)$new_order_status,
                                'date_added' => 'now()',
                                'comments' => 'FUNDS COLLECTED. Auth Code: ' . $response[4] . "\n" . 'Trans ID: ' . $response[6] . "\n" . ' Amount: ' . ($response[9] == 0.00 ? 'Full Amount' : $response[9]) . "\n" . 'Time: ' . date('Y-m-D h:i:s') . "\n" . $captureNote,
                                'customer_notified' => 0
                             );
        zen_db_perform(TABLE_ORDERS_STATUS_HISTORY, $sql_data_array);
        $db->Execute("update " . TABLE_ORDERS  . "
                      set orders_status = '" . (int)$new_order_status . "'
                      where orders_id = '" . (int)$oID . "'");
        $messageStack->add_session(sprintf(MODULE_PAYMENT_AUTHORIZENET_AIM_TEXT_CAPT_INITIATED, ($response[9] == 0.00 ? 'Full Amount' : $response[9]), $response[6], $response[4]), 'success');
        return true;
      }
    }
    return false;
  }
1154558
function init()
    {
        // overiddable variables
        $this->file_new_name_body   = null;     // replace the name body
        $this->file_name_body_add   = null;     // append to the name body
        $this->file_name_body_pre   = null;     // prepend to the name body
        $this->file_new_name_ext    = null;     // replace the file extension
        $this->file_safe_name       = true;     // format safely the filename
        $this->file_force_extension = true;     // forces extension if there isn't one
        $this->file_overwrite       = false;    // allows overwritting if the file already exists
        $this->file_auto_rename     = true;     // auto-rename if the file already exists
        $this->dir_auto_create      = true;     // auto-creates directory if missing
        $this->dir_auto_chmod       = true;     // auto-chmod directory if not writeable
        $this->dir_chmod            = 0777;     // default chmod to use

        $this->no_script  = true;     // turns scripts into test files
        $this->mime_check = true;     // checks the mime type against the allowed list

        // these are the different MIME detection methods. if one of these method doesn't work on your
        // system, you can deactivate it here; just set it to false
        $this->mime_fileinfo     = true;     // MIME detection with Fileinfo PECL extension
        $this->mime_file         = true;     // MIME detection with UNIX file() command
        $this->mime_magic        = true;     // MIME detection with mime_magic (mime_content_type())
        $this->mime_getimagesize = true;     // MIME detection with getimagesize()

        // get the default max size from php.ini
        $this->file_max_size_raw = trim(ini_get('upload_max_filesize'));
        $this->file_max_size     = $this->getsize($this->file_max_size_raw);

        $this->image_resize  = false;    // resize the image
        $this->image_convert = '';       // convert. values :''; 'png'; 'jpeg'; 'gif'; 'bmp'

        $this->image_x                 = 150;
        $this->image_y                 = 150;
        $this->image_ratio             = false;    // keeps aspect ratio with x and y dimensions
        $this->image_ratio_crop        = false;    // keeps aspect ratio with x and y dimensions, filling the space
        $this->image_ratio_fill        = false;    // keeps aspect ratio with x and y dimensions, fitting the image in the space, and coloring the rest
        $this->image_ratio_pixels      = false;    // keeps aspect ratio, calculating x and y so that the image is approx the set number of pixels
        $this->image_ratio_no_zoom_in  = false;
        $this->image_ratio_no_zoom_out = false;
        $this->image_ratio_x           = false;    // calculate the $image_x if true
        $this->image_ratio_y           = false;    // calculate the $image_y if true
        $this->png_compression         = null;
        $this->jpeg_quality            = 85;
        $this->jpeg_size               = null;
        $this->image_interlace         = false;
        $this->preserve_transparency   = false;
        $this->image_is_transparent    = false;
        $this->image_transparent_color = null;
        $this->image_background_color  = null;
        $this->image_default_color     = '#ffffff';
        $this->image_is_palette        = false;

        $this->image_max_width  = null;
        $this->image_max_height = null;
        $this->image_max_pixels = null;
        $this->image_max_ratio  = null;
        $this->image_min_width  = null;
        $this->image_min_height = null;
        $this->image_min_pixels = null;
        $this->image_min_ratio  = null;

        $this->image_brightness        = null;
        $this->image_contrast          = null;
        $this->image_opacity           = null;
        $this->image_threshold         = null;
        $this->image_tint_color        = null;
        $this->image_overlay_color     = null;
        $this->image_overlay_opacity   = null;
        $this->image_overlay_percent   = null;
        $this->image_negative          = false;
        $this->image_greyscale         = false;
        $this->image_pixelate          = null;
        $this->image_unsharp           = false;
        $this->image_unsharp_amount    = 80;
        $this->image_unsharp_radius    = 0.5;
        $this->image_unsharp_threshold = 1;

        $this->image_text                    = null;
        $this->image_text_direction          = null;
        $this->image_text_color              = '#FFFFFF';
        $this->image_text_opacity            = 100;
        $this->image_text_percent            = 100;
        $this->image_text_background         = null;
        $this->image_text_background_opacity = 100;
        $this->image_text_background_percent = 100;
        $this->image_text_font               = 5;
        $this->image_text_x                  = null;
        $this->image_text_y                  = null;
        $this->image_text_position           = null;
        $this->image_text_padding            = 0;
        $this->image_text_padding_x          = null;
        $this->image_text_padding_y          = null;
        $this->image_text_alignment          = 'C';
        $this->image_text_line_spacing       = 0;

        $this->image_reflection_height  = null;
        $this->image_reflection_space   = 2;
        $this->image_reflection_color   = '#ffffff';
        $this->image_reflection_opacity = 60;

        $this->image_watermark             = null;
        $this->image_watermark_x           = null;
        $this->image_watermark_y           = null;
        $this->image_watermark_position    = null;
        $this->image_watermark_no_zoom_in  = true;
        $this->image_watermark_no_zoom_out = false;

        $this->image_flip        = null;
        $this->image_auto_rotate = true;
        $this->image_rotate      = null;
        $this->image_crop        = null;
        $this->image_precrop     = null;

        $this->image_bevel              = null;
        $this->image_bevel_color1       = '#FFFFFF';
        $this->image_bevel_color2       = '#000000';
        $this->image_border             = null;
        $this->image_border_color       = '#FFFFFF';
        $this->image_border_opacity     = 100;
        $this->image_border_transparent = null;
        $this->image_frame              = null;
        $this->image_frame_colors       = '#FFFFFF #999999 #666666 #000000';
        $this->image_frame_opacity      = 100;

        $this->forbidden = [];
        $this->allowed   = [
            'application/arj',
            'application/excel',
            'application/gnutar',
            'application/mspowerpoint',
            'application/msword',
            'application/octet-stream',
            'application/onenote',
            'application/pdf',
            'application/plain',
            'application/postscript',
            'application/powerpoint',
            'application/rar',
            'application/rtf',
            'application/vnd.ms-excel',
            'application/vnd.ms-excel.addin.macroEnabled.12',
            'application/vnd.ms-excel.sheet.binary.macroEnabled.12',
            'application/vnd.ms-excel.sheet.macroEnabled.12',
            'application/vnd.ms-excel.template.macroEnabled.12',
            'application/vnd.ms-office',
            'application/vnd.ms-officetheme',
            'application/vnd.ms-powerpoint',
            'application/vnd.ms-powerpoint.addin.macroEnabled.12',
            'application/vnd.ms-powerpoint.presentation.macroEnabled.12',
            'application/vnd.ms-powerpoint.slide.macroEnabled.12',
            'application/vnd.ms-powerpoint.slideshow.macroEnabled.12',
            'application/vnd.ms-powerpoint.template.macroEnabled.12',
            'application/vnd.ms-word',
            'application/vnd.ms-word.document.macroEnabled.12',
            'application/vnd.ms-word.template.macroEnabled.12',
            'application/vnd.oasis.opendocument.chart',
            'application/vnd.oasis.opendocument.database',
            'application/vnd.oasis.opendocument.formula',
            'application/vnd.oasis.opendocument.graphics',
            'application/vnd.oasis.opendocument.graphics-template',
            'application/vnd.oasis.opendocument.image',
            'application/vnd.oasis.opendocument.presentation',
            'application/vnd.oasis.opendocument.presentation-template',
            'application/vnd.oasis.opendocument.spreadsheet',
            'application/vnd.oasis.opendocument.spreadsheet-template',
            'application/vnd.oasis.opendocument.text',
            'application/vnd.oasis.opendocument.text-master',
            'application/vnd.oasis.opendocument.text-template',
            'application/vnd.oasis.opendocument.text-web',
            'application/vnd.openofficeorg.extension',
            'application/vnd.openxmlformats-officedocument.presentationml.presentation',
            'application/vnd.openxmlformats-officedocument.presentationml.slide',
            'application/vnd.openxmlformats-officedocument.presentationml.slideshow',
            'application/vnd.openxmlformats-officedocument.presentationml.template',
            'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
            'application/vnd.openxmlformats-officedocument.spreadsheetml.template',
            'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
            'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
            'application/vnd.openxmlformats-officedocument.wordprocessingml.template',
            'application/vocaltec-media-file',
            'application/wordperfect',
            'application/x-bittorrent',
            'application/x-bzip',
            'application/x-bzip2',
            'application/x-compressed',
            'application/x-excel',
            'application/x-gzip',
            'application/x-latex',
            'application/x-midi',
            'application/xml',
            'application/x-msexcel',
            'application/x-rar',
            'application/x-rar-compressed',
            'application/x-rtf',
            'application/x-shockwave-flash',
            'application/x-sit',
            'application/x-stuffit',
            'application/x-troff-msvideo',
            'application/x-zip',
            'application/x-zip-compressed',
            'application/zip',
            'audio/*',
            'image/*',
            'multipart/x-gzip',
            'multipart/x-zip',
            'text/plain',
            'text/rtf',
            'text/richtext',
            'text/xml',
            'video/*',
            'text/csv',
        ];

        $this->mime_types = [
            'jpg'     => 'image/jpeg',
            'jpeg'    => 'image/jpeg',
            'jpe'     => 'image/jpeg',
            'gif'     => 'image/gif',
            'png'     => 'image/png',
            'bmp'     => 'image/bmp',
            'flv'     => 'video/x-flv',
            'js'      => 'application/x-javascript',
            'json'    => 'application/json',
            'tiff'    => 'image/tiff',
            'css'     => 'text/css',
            'xml'     => 'application/xml',
            'doc'     => 'application/msword',
            'docx'    => 'application/msword',
            'xls'     => 'application/vnd.ms-excel',
            'xlt'     => 'application/vnd.ms-excel',
            'xlm'     => 'application/vnd.ms-excel',
            'xld'     => 'application/vnd.ms-excel',
            'xla'     => 'application/vnd.ms-excel',
            'xlc'     => 'application/vnd.ms-excel',
            'xlw'     => 'application/vnd.ms-excel',
            'xll'     => 'application/vnd.ms-excel',
            'ppt'     => 'application/vnd.ms-powerpoint',
            'pps'     => 'application/vnd.ms-powerpoint',
            'rtf'     => 'application/rtf',
            'pdf'     => 'application/pdf',
            'html'    => 'text/html',
            'htm'     => 'text/html',
            'php'     => 'text/html',
            'txt'     => 'text/plain',
            'mpeg'    => 'video/mpeg',
            'mpg'     => 'video/mpeg',
            'mpe'     => 'video/mpeg',
            'mp3'     => 'audio/mpeg3',
            'wav'     => 'audio/wav',
            'aiff'    => 'audio/aiff',
            'aif'     => 'audio/aiff',
            'avi'     => 'video/msvideo',
            'wmv'     => 'video/x-ms-wmv',
            'mov'     => 'video/quicktime',
            'zip'     => 'application/zip',
            'tar'     => 'application/x-tar',
            'swf'     => 'application/x-shockwave-flash',
            'odt'     => 'application/vnd.oasis.opendocument.text',
            'ott'     => 'application/vnd.oasis.opendocument.text-template',
            'oth'     => 'application/vnd.oasis.opendocument.text-web',
            'odm'     => 'application/vnd.oasis.opendocument.text-master',
            'odg'     => 'application/vnd.oasis.opendocument.graphics',
            'otg'     => 'application/vnd.oasis.opendocument.graphics-template',
            'odp'     => 'application/vnd.oasis.opendocument.presentation',
            'otp'     => 'application/vnd.oasis.opendocument.presentation-template',
            'ods'     => 'application/vnd.oasis.opendocument.spreadsheet',
            'ots'     => 'application/vnd.oasis.opendocument.spreadsheet-template',
            'odc'     => 'application/vnd.oasis.opendocument.chart',
            'odf'     => 'application/vnd.oasis.opendocument.formula',
            'odb'     => 'application/vnd.oasis.opendocument.database',
            'odi'     => 'application/vnd.oasis.opendocument.image',
            'oxt'     => 'application/vnd.openofficeorg.extension',
            'docx'    => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
            'docm'    => 'application/vnd.ms-word.document.macroEnabled.12',
            'dotx'    => 'application/vnd.openxmlformats-officedocument.wordprocessingml.template',
            'dotm'    => 'application/vnd.ms-word.template.macroEnabled.12',
            'xlsx'    => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
            'xlsm'    => 'application/vnd.ms-excel.sheet.macroEnabled.12',
            'xltx'    => 'application/vnd.openxmlformats-officedocument.spreadsheetml.template',
            'xltm'    => 'application/vnd.ms-excel.template.macroEnabled.12',
            'xlsb'    => 'application/vnd.ms-excel.sheet.binary.macroEnabled.12',
            'xlam'    => 'application/vnd.ms-excel.addin.macroEnabled.12',
            'pptx'    => 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
            'pptm'    => 'application/vnd.ms-powerpoint.presentation.macroEnabled.12',
            'ppsx'    => 'application/vnd.openxmlformats-officedocument.presentationml.slideshow',
            'ppsm'    => 'application/vnd.ms-powerpoint.slideshow.macroEnabled.12',
            'potx'    => 'application/vnd.openxmlformats-officedocument.presentationml.template',
            'potm'    => 'application/vnd.ms-powerpoint.template.macroEnabled.12',
            'ppam'    => 'application/vnd.ms-powerpoint.addin.macroEnabled.12',
            'sldx'    => 'application/vnd.openxmlformats-officedocument.presentationml.slide',
            'sldm'    => 'application/vnd.ms-powerpoint.slide.macroEnabled.12',
            'thmx'    => 'application/vnd.ms-officetheme',
            'onetoc'  => 'application/onenote',
            'onetoc2' => 'application/onenote',
            'onetmp'  => 'application/onenote',
            'onepkg'  => 'application/onenote',
            'csv'     => 'text/csv',
        ];
    }
948449
function indexWriter(&$doclet) {

        parent::MDWriter($doclet);

        $phpdoctor = & $this->_doclet->phpdoctor();
        $displayTree = $phpdoctor->getOption("tree");

        $rootDoc = & $this->_doclet->rootDoc();

        $classes = & $rootDoc->classes();
        if ($classes == NULL)
            $classes = array();

        $functions = & $rootDoc->functions();
        if ($functions == NULL)
            $functions = array();

        $globals = & $rootDoc->globals();
        if ($globals == NULL)
            $globals = array();

        $elements = array_merge($classes, $functions, $globals);
        uasort($elements, array($this, "compareElements"));

        ob_start();

        echo "#INDEX#";

        if(isset($this->_doclet->phpdoctor()->_options["github_sources_repository"])){
            echo "\n\n[View Source codes]({$this->getSourcesBaseURL()})";
        }
        
        if ($displayTree) {
            echo "\n\n[View class hierarchy]({$this->getDirBaseURL()}/overview-tree.md)";
        }
        
        echo "\n\n[View depreacted list]({$this->getDirBaseURL()}/deprecated-list.md)";

        echo "\n\n[View todo list]({$this->getDirBaseURL()}/todo-list.md)";

        echo "\n\n[View the list of all classes, functions and globals]({$this->getDirBaseURL()}/index-all.md)";

        $this->_output = ob_get_contents();
        ob_end_clean();

        $this->_write("README.md");

        ///------------------------------------------------------

        ob_start();

        $letter = 64;
        foreach ($elements as $name => $element) {
            $firstChar = strtoupper(substr($element->name(), 0, 1));
            if (is_object($element) && $firstChar != chr($letter)) {
                $letter = ord($firstChar);
                echo "<a href=\"#", strtolower(chr($letter)), "\">", chr($letter), "</a>\n";
            }
        }

        echo "- - -\n\n";

        $first = TRUE;
        foreach ($elements as $element) {
            if (is_object($element)) {
                if (strtoupper(substr($element->name(), 0, 1)) != chr($letter)) {
                    $letter = ord(strtoupper(substr($element->name(), 0, 1)));
                    if (!$first) {
                        echo "</dl>\n";
                    }
                    $first = FALSE;
                    echo "<h1 id=\"letter", chr($letter), "\">", chr($letter), "</h1>\n";
                    echo "<dl>\n";
                }
                $parent = & $element->containingClass();
                if ($parent && strtolower(get_class($parent)) != "rootdoc") {
                    $in = "class <a href=\"" . $this->_asURL($parent) . "\">" . $parent->qualifiedName() . "</a>";
                } else {
                    $package = & $element->containingPackage();
                    $in = "namespace <a href=\"" . $this->_asURL($package) . "/README.md\">" . $package->name() . "</a>";
                }
                switch (strtolower(get_class($element))) {
                    case "classdoc":
                        if ($element->isOrdinaryClass()) {
                            echo "<dt><a href=\"", $this->_asURL($element), "\">", $element->name(), "</a> - Class in ", $in, "</dt>\n";
                        } elseif ($element->isInterface()) {
                            echo "<dt><a href=\"", $this->_asURL($element), "\">", $element->name(), "</a> - Interface in ", $in, "</dt>\n";
                        } elseif ($element->isException()) {
                            echo "<dt><a href=\"", $this->_asURL($element), "\">", $element->name(), "</a> - Exception in ", $in, "</dt>\n";
                        }
                        break;
                    case 'methoddoc':
                        if ($element->isFunction()) {
                            echo '<dt><a href="', $this->_asURL($element), '">', $element->name(), '()</a> - Function in ', $in, "</dt>\n";
                        }
                        break;
                    case "fielddoc":
                        if ($element->isGlobal()) {
                            echo "<dt><a href=\"", $this->_asURL($element), "\">", $element->name(), "</a> - Global in ", $in, "</dt>\n";
                        }
                        break;
                }
                if ($textTag = & $element->tags("@text") && $firstSentenceTags = & $textTag->firstSentenceTags($this->_doclet)) {
                    echo "<dd>";
                    foreach ($firstSentenceTags as $firstSentenceTag) {
                        echo $firstSentenceTag->text($this->_doclet);
                    }
                    echo "</dd>\n";
                }
            }
        }
        echo "</dl>\n";

        $this->_output = ob_get_contents();
        ob_end_clean();

        $this->_write("index-all.md");
    }