/*
References
- http://www.php.net/manual/en/function.com-create-guid.php
- http://guid.us/GUID/PHP
355967
public function generate($prefix = false, $braces = false) {
        mt_srand((double) microtime() * 10000);
        $charid = strtoupper(md5(uniqid($prefix === false ? rand() : $prefix, true)));
        $hyphen = chr(45); // "-"
        $uuid = substr($charid, 0, 8) . $hyphen
                 . substr($charid, 8, 4) . $hyphen
                 . substr($charid, 12, 4) . $hyphen
                 . substr($charid, 16, 4) . $hyphen
                 . substr($charid, 20, 12);
        
        // Add brackets or not? "{" ... "}"
        return $braces ? chr(123) . $uuid . chr(125) : $uuid;
    }
1007821
public function generateGuid()
    {
        if (function_exists('com_create_guid') === true) {
            return trim(com_create_guid(), '{}');
        }

        return sprintf(
            '%04X%04X-%04X-%04X-%04X-%04X%04X%04X',
            mt_rand(0, 65535),
            mt_rand(0, 65535),
            mt_rand(0, 65535),
            mt_rand(16384, 20479),
            mt_rand(32768, 49151),
            mt_rand(0, 65535),
            mt_rand(0, 65535),
            mt_rand(0, 65535)
        );
    }
209553
public function getPhpCode($value, array $referenceConfig = [], array $path = []): string
    {
        if (is_array($value)) {
            $level = count($path);
            if ($value === []) {
                $code = '[]';
            } else {
                $code = '[' . PHP_EOL;
                foreach ($value as $key => $arrayValue) {
                    // Indention
                    $code .= str_repeat('    ', $level + 1);
                    // Integer / string keys
                    $code .= is_int($key) ? $key . ' => ' : $this->getPhpCodeForPlaceholder($key, $referenceConfig, [], true) . ' => ';
                    if ($level === 2 && $path[0] === 'EXT' && $path[1] === 'extConf' && \is_array($arrayValue)) {
                        $code .= 'serialize(';
                        $code .= $this->getPhpCode($this->addDotsToTypoScript($arrayValue), $referenceConfig, array_merge($path, [$key]));
                        $code .= ')';
                    } else {
                        $code .= $this->getPhpCode($arrayValue, $referenceConfig, array_merge($path, [$key]));
                    }
                    $code .= ',' . PHP_EOL;
                }
                $code .= str_repeat('    ', $level) . ']';
            }
        } elseif (is_int($value) || is_float($value)) {
            $code = (string)$value;
        } elseif ($value === null) {
            $code = 'null';
        } elseif (is_bool($value)) {
            $code = $value ? 'true' : 'false';
        } elseif (is_string($value)) {
            $code = $this->getPhpCodeForPlaceholder($value, $referenceConfig, $path);
        } else {
            throw new \RuntimeException('Objects, closures and resources are not supported', 1519779656);
        }

        return $code;
    }
136260
function getReference( referenceFile ) {
  var text = '';

  // Read references file.
  var referencePath = path.join( process.cwd(), referenceFile );

  var stats = fs.statSync( referencePath );
  if (stats && stats.isFile()) {
    text = fs.readFileSync( referencePath, { encoding: 'utf8' } );

    // Find common root definitions (tilde references).
    var tildes = { };
    var re = /^\s*\[(~\d*)]\s*:/g;
    var source = text.split( '\n' );
    var target = [ ];
    for (var i = 0; i < source.length; i++) {
      var line = source[ i ].trim();
      // Search common root pattern.
      var result = re.exec( line );
      if (result)
      // Save common root value.
        tildes[ result[ 1 ] ] = line.substring( line.indexOf( ':' ) + 1 ).trim();
      else if (line[ 0 ] === '[')
      // Store reference link.
        target.push( line );
    }
    text = target.join( '\n' );

    // Replace tilde+number pairs with common roots.
    var noIndex = false;
    for (var attr in tildes) {
      if (tildes.hasOwnProperty( attr )) {
        if (attr === '~')
          noIndex = true;
        else {
          var re_n = new RegExp( ' ' + attr, 'g' );
          var re_value = ' ' + tildes[ attr ];
          text = text.replace( re_n, re_value );
        }
      }
    }
    // Finally replace tildes with its common root.
    if (noIndex)
      text = text.replace( / ~/g, ' ' + tildes[ '~' ] );
  }
  return text;
}
262221
private function generateFunctions()
    {
        $result = '<?php' . PHP_EOL;
        foreach($this->ref->getFunctions() as $function)
        {
            $args = [];
            $comments = [];
            foreach($function->getParameters() as $param)
            {
                // 方法参数定义
                $args[] = $this->getMethodParamDefine($param);
                $comments[] = '@var ' . ($param->getType() ?? 'mixed') . ' $' . $param->name;
            }
            $return = $function->getReturnType();
            if(null !== $return)
            {
                $comments[] = '@return ' . $return;
            }
            $args = implode(', ', $args);
            if([] === $comments)
            {
                $comment = '';
            }
            else
            {
                $comment = implode(PHP_EOL . ' * ', $comments);
                $comment = <<<COMMENT

/**
 * {$comment}
 */
COMMENT;
            }
            $result .= <<<CODE
{$comment}
function {$function->name}({$args}){}

CODE;
        }
        file_put_contents($this->savePath . '/functions.php', $result);
    }
1028279
public static function getPathPHP() {
		
		$manualPHP = Config::getOption("phpBin");
		$autoPHP   = new PhpExecutableFinder();
		$path      = $manualPHP ? $manualPHP : $autoPHP->find();
		
		if (!$path) {
			$configPath = Console::getHumanReadablePath(Config::getOption("configPath"));
			$examplePHP = (DIRECTORY_SEPARATOR === "/") ? "C:\wamp\bin\php\php5.5.12" : "/opt/local/lib/php54";
			Console::writeError("can't find PHP. add the path to PHP by adding the option \"phpBin\" to <path>".$configPath."</path>. it should look like \"phpBin\": \"".$examplePHP."\"");
		}
		
		return $path;
		
	}
272126
private function functionCall(Node $function_reference, $dynamic = FALSE) {
    if ($dynamic) {
      $node = new CallbackCallNode();
      $node->addChild($function_reference, 'callback');
    }
    else {
      if ($function_reference instanceof NameNode && $function_reference->childCount() === 1 && $function_reference == 'define') {
        $node = new DefineNode();
      }
      else {
        $node = new FunctionCallNode();
      }
      $node->addChild($function_reference, 'name');
    }
    $this->functionCallParameterList($node);
    return $this->objectDereference($this->arrayDeference($node));
  }
343732
public function createReference()
    {
        $documentId = $this->getId();
        if (null === $documentId) {
            throw new Exception('Document must be stored to get DBRef');
        }

        return $this
            ->getCollection()
            ->getMongoCollection()
            ->createDBRef($documentId);
    }
1058160
function IndexEntry($txt, $xref = '')
	{
		if ($xref) {
			$this->IndexEntrySee($txt, $xref);
			return;
		}

		// Search the reference (AND Ref/PageNo) in the array
		$Present = false;
		if ($this->keep_block_together) {
			// do nothing
		} /* -- TABLES -- */ elseif ($this->kwt) {
			$size = count($this->kwt_Reference);
			for ($i = 0; $i < $size; $i++) {
				if (isset($this->kwt_Reference[$i]['t']) && $this->kwt_Reference[$i]['t'] == $txt) {
					$Present = true;
					if ($this->page != $this->kwt_Reference[$i]['op']) {
						$this->kwt_Reference[$i]['op'] = $this->page;
					}
				}
			}
			if (!$Present) { // If not found, add it
				$this->kwt_Reference[] = ['t' => $txt, 'op' => $this->page];
			}
		} /* -- END TABLES -- */ else {
			$size = count($this->Reference);
			for ($i = 0; $i < $size; $i++) {
				if (isset($this->Reference[$i]['t']) && $this->Reference[$i]['t'] == $txt) {
					$Present = true;
					if (!in_array($this->page, $this->Reference[$i]['p'])) {
						$this->Reference[$i]['p'][] = $this->page;
					}
				}
			}
			if (!$Present) { // If not found, add it
				$this->Reference[] = ['t' => $txt, 'p' => [$this->page]];
			}
		}
	}
59180
protected function _Create() {
      $PrimaryKey = array();
      $UniqueKey = array();
      $FullTextKey = array();
      $AllowFullText = TRUE;
      $Indexes = array();
      $Keys = '';
      $Sql = '';
      
      $ForceDatabaseEngine = C('Database.ForceStorageEngine');
      if ($ForceDatabaseEngine && !$this->_TableStorageEngine) {
         $this->_TableStorageEngine = $ForceDatabaseEngine;
         $AllowFullText = $this->_SupportsFulltext();
      }

      foreach ($this->_Columns as $ColumnName => $Column) {
         if ($Sql != '')
            $Sql .= ',';

         $Sql .= "\n".$this->_DefineColumn($Column);

         $ColumnKeyTypes = (array)$Column->KeyType;

         foreach ($ColumnKeyTypes as $ColumnKeyType) {
            $KeyTypeParts = explode('.', $ColumnKeyType, 2);
            $ColumnKeyType = $KeyTypeParts[0];
            $IndexGroup = GetValue(1, $KeyTypeParts, '');
            
            if ($ColumnKeyType == 'primary')
               $PrimaryKey[] = $ColumnName;
            elseif ($ColumnKeyType == 'key')
               $Indexes['FK'][$IndexGroup][] = $ColumnName;
            elseif ($ColumnKeyType == 'index')
               $Indexes['IX'][$IndexGroup][] = $ColumnName;
            elseif ($ColumnKeyType == 'unique')
               $UniqueKey[] = $ColumnName;
            elseif ($ColumnKeyType == 'fulltext' && $AllowFullText)
               $FullTextKey[] = $ColumnName;
         }
      }
      // Build primary keys
      if (count($PrimaryKey) > 0)
         $Keys .= ",\nprimary key (`".implode('`, `', $PrimaryKey)."`)";
      // Build unique keys.
      if (count($UniqueKey) > 0)
         $Keys .= ",\nunique index `".Gdn_Format::AlphaNumeric('UX_'.$this->_TableName).'` (`'.implode('`, `', $UniqueKey)."`)";
      // Build full text index.
      if (count($FullTextKey) > 0)
         $Keys .= ",\nfulltext index `".Gdn_Format::AlphaNumeric('TX_'.$this->_TableName).'` (`'.implode('`, `', $FullTextKey)."`)";
      // Build the rest of the keys.
      foreach ($Indexes as $IndexType => $IndexGroups) {
         $CreateString = ArrayValue($IndexType, array('FK' => 'key', 'IX' => 'index'));
         foreach ($IndexGroups as $IndexGroup => $ColumnNames) {
            if (!$IndexGroup) {
               foreach ($ColumnNames as $ColumnName) {
                  $Keys .= ",\n{$CreateString} `{$IndexType}_{$this->_TableName}_{$ColumnName}` (`{$ColumnName}`)";
               }
            } else {
               $Keys .= ",\n{$CreateString} `{$IndexType}_{$this->_TableName}_{$IndexGroup}` (`".implode('`, `', $ColumnNames).'`)';
            }
         }
      }

      $Sql = 'create table `'.$this->_DatabasePrefix.$this->_TableName.'` ('
         .$Sql
         .$Keys
      ."\n)";

      // Check to see if there are any fulltext columns, otherwise use innodb.
      if (!$this->_TableStorageEngine) {
         $HasFulltext = FALSE;
         foreach ($this->_Columns as $Column) {
            $ColumnKeyTypes = (array)$Column->KeyType;
            array_map('strtolower', $ColumnKeyTypes);
            if (in_array('fulltext', $ColumnKeyTypes)) {
               $HasFulltext = TRUE;
               break;
            }
         }
         if ($HasFulltext)
            $this->_TableStorageEngine = 'myisam';
         else
            $this->_TableStorageEngine = C('Database.DefaultStorageEngine', 'innodb');
         
         if (!$this->HasEngine($this->_TableStorageEngine)) {
            $this->_TableStorageEngine = 'myisam';
         }
      }
      
      if ($this->_TableStorageEngine)
         $Sql .= ' engine='.$this->_TableStorageEngine;

      if ($this->_CharacterEncoding !== FALSE && $this->_CharacterEncoding != '')
         $Sql .= ' default character set '.$this->_CharacterEncoding;
         
      if (array_key_exists('Collate', $this->Database->ExtendedProperties)) {
         $Sql .= ' collate ' . $this->Database->ExtendedProperties['Collate'];
      }
      
      $Sql .= ';';

      $Result = $this->Query($Sql);
      $this->Reset();
      
      return $Result;
   }
438652
function referenced( $name, $where = null, $params = array() ) {

        $result = $this->db->createResult( $this, $name );

        if ( $where !== null ) {

            if ( !is_array( $params ) ) $params = array_slice( func_get_args(), 2 );
            $result = $result->where( $where, $params );

        }

        return $result;

    }
1123310
public function &buildLimitOffset()
    {
        $str = "";

        // Handle any user specified FIRST, SKIP ROWS functions
        // Set in the following order :-
        // User specified a limit and offset parameter else
        $limit = ReporticoUtility::getRequestItem("report_limit", "");
        $offset = ReporticoUtility::getRequestItem("report_offset", "");
        // User specified a page and row parameter  which else
        if (!$limit && !$offset) {
            $page = ReporticoUtility::getRequestItem("page", "");
            $rows = ReporticoUtility::getRequestItem("rows", "");
            if ($page && $page > 0 && $rows) {
                $offset = ($page - 1) * $rows;
                $limit = $rows;
            }
        }

        // report contains a default skip and offset definition
        if (!$limit && !$offset) {
            $limit = $this->sql_limit_first;
            $offset = $this->sql_skip_offset;
        }

        if (!$limit && !$offset) {
            return $str;
        }

        if (!$offset) {
            $offset = "0";
        }

        if ($this->datasource->_conn_driver != "pdo_informix" && $this->datasource->_conn_driver != "informix") {
            // Offset without limit doesnt work in Mysql
            if ($this->datasource->_conn_driver == "pdo_mysql") {
                if (!$limit) {
                    $limit = "18446744073709551615";
                }

            }

            $str .= " LIMIT $limit";

            if ($offset) {
                $str .= " OFFSET $offset";
            }

        } else {
            if ($rows) {
                $str .= " FIRST $limit";
            }

            if ($offset) {
                $str = " SKIP $offset" . $str;
            }

        }

        return $str;
    }
647045
public function phpdocContent()
    {
        $comment = preg_split('/(\n|\r\n)/', $this->comment);
        $comment[0] = preg_replace('/[ \t]*\\/\*\*/', '', $comment[0]); // strip '/**'
        $i = count($comment) - 1;
        $comment[$i] = preg_replace('/\*\/[ \t]*$/', '', $comment[$i]); // strip '*/'
        $lines = [];
        $append = false;
        foreach ($comment as $line) {
            $line = ltrim($line, "\t *");
            if (substr($line, 0, 1) === '@') {
                break;
            }
            if ($append) {
                $i = count($lines) - 1;
                $lines[$i] = substr($lines[$i], 0, -1) . $line;
            } else {
                $lines[] = $line;
            }
            $append = (substr($line, -1) === '\\');
        }
        $description = trim(implode("\n", $lines));
        if ($description === '') {
            return UNDEFINED;
        }

        return $description;
    }
639342
public function generateScopePhp()
    {

        $methodSignature = '';
        $paramsDoc       = '';
        $buildScope      = '';
        $buildScopeVars  = '';

        if ($this->hasMultipleScopes()) {

            $methodSignature = [];
            $buildScope      = [];
            $buildScopeVars  = [];
            $paramsDoc       = [];

            foreach ($this->getScopes() as $idx => $scope) {

                $column = $this->table->getColumn($scope);
                $param  = '$scope'.$column->getPhpName();

                $buildScope[]     = "    \$scope[] = $param;\n";
                $buildScopeVars[] = "    $param = \$scope[$idx];\n";
                $paramsDoc[]      = " * @param     ".$column->getPhpType()." $param Scope value for column `".$column->getPhpName()."`";

                if (!$column->isNotNull()) {
                    $param .= ' = null';
                }
                $methodSignature[] = $param;
            }

            $methodSignature = implode(', ', $methodSignature);
            $paramsDoc       = implode("\n", $paramsDoc);
            $buildScope      = "\n".implode('', $buildScope)."\n";
            $buildScopeVars  = "\n".implode('', $buildScopeVars)."\n";

        } elseif ($this->useScope()) {
            $methodSignature = '$scope';
            $column = $this->table->getColumn($this->getParameter('scope_column'));
            if ($column) {
                if (!$column->isNotNull()) {
                    $methodSignature .= ' = null';
                }
                $paramsDoc .= ' * @param '.$column->getPhpType().' $scope Scope to determine which objects node to return';
            }
        }

        return [$methodSignature, $paramsDoc, $buildScope, $buildScopeVars];
    }
1271944
function guid() {
    function _s4() {
        return Math.floor(
            (1 + Math.random()) * 0x10000
        ).toString(16).substring(1);
    }
    return _s4() + _s4() + '-' + _s4() + '-' + _s4() + '-' + _s4() + '-' + _s4() + _s4() + _s4();
}
676626
public static function getParamsFromCallMap($function_id)
    {
        $call_map = self::getCallMap();

        $call_map_key = strtolower($function_id);

        if (!isset($call_map[$call_map_key])) {
            return null;
        }

        $call_map_functions = [];
        $call_map_functions[] = $call_map[$call_map_key];

        for ($i = 1; $i < 10; ++$i) {
            if (!isset($call_map[$call_map_key . '\'' . $i])) {
                break;
            }

            $call_map_functions[] = $call_map[$call_map_key . '\'' . $i];
        }

        $function_type_options = [];

        foreach ($call_map_functions as $call_map_function_args) {
            array_shift($call_map_function_args);

            $function_types = [];

            /** @var string $arg_name - key type changed with above array_shift */
            foreach ($call_map_function_args as $arg_name => $arg_type) {
                $by_reference = false;
                $optional = false;
                $variadic = false;

                if ($arg_name[0] === '&') {
                    $arg_name = substr($arg_name, 1);
                    $by_reference = true;
                }

                if (substr($arg_name, -1) === '=') {
                    $arg_name = substr($arg_name, 0, -1);
                    $optional = true;
                }

                if (substr($arg_name, 0, 3) === '...') {
                    $arg_name = substr($arg_name, 3);
                    $variadic = true;
                }

                $param_type = $arg_type
                    ? Type::parseString($arg_type)
                    : Type::getMixed();

                $function_types[] = new FunctionLikeParameter(
                    $arg_name,
                    $by_reference,
                    $param_type,
                    null,
                    null,
                    $optional,
                    false,
                    $variadic
                );
            }

            $function_type_options[] = $function_types;
        }

        return $function_type_options;
    }
789724
public function init()
    {
        if (!isset($this->attrs->server['FR_PATH'])) {
            $this->status(404);
            $this->finish();
            return;
        }
        $job = new \PHPDaemon\Core\ComplexJob(function ($job) {
            $this->wakeup();
        });
        $this->job = $job;
        $this->sleep(5, true);
        $this->attrs->server['FR_PATH'] = \PHPDaemon\FS\FileSystem::sanitizePath($this->attrs->server['FR_PATH']);
        $job('stat', function ($name, $job) {
            /** @var \PHPDaemon\Core\ComplexJob $job */
            \PHPDaemon\FS\FileSystem::stat($this->attrs->server['FR_PATH'], function ($path, $stat) use ($job) {
                if ($stat === -1) {
                    $this->fileNotFound();
                    $job->setResult('stat', false);
                    return;
                }
                if ($stat['type'] === 'd') {
                    if (!\PHPDaemon\FS\FileSystem::$supported) {
                        $this->file(rtrim($path, '/') . '/index.html');
                    } else {
                        $job('readdir', function ($name, $job) use ($path) {
                            /** @var \PHPDaemon\Core\ComplexJob $job */
                            \PHPDaemon\FS\FileSystem::readdir(rtrim($path, '/'), function ($path, $dir) use ($job) {
                                $found = false;
                                if (is_array($dir)) {
                                    foreach ($dir['dents'] as $file) {
                                        if ($file['type'] === \EIO_DT_REG) { // is file
                                            if (in_array($file['name'], $this->appInstance->indexFiles)) {
                                                $this->file($path . '/' . $file['name']);
                                                $found = true;
                                                break;
                                            }
                                        }
                                    }
                                }
                                if (!$found) {
                                    if (isset($this->attrs->server['FR_AUTOINDEX']) && $this->attrs->server['FR_AUTOINDEX']) {
                                        $this->autoindex($path, $dir);
                                    } else {
                                        $this->fileNotFound();
                                    }
                                }

                                $job->setResult('readdir');
                            }, \EIO_READDIR_STAT_ORDER | \EIO_READDIR_DENTS);
                        });
                    }
                } elseif ($stat['type'] === 'f') {
                    $this->file($path);
                }
                $job->setResult('stat', $stat);
            });
        });
        $job();
    }