Generate the tokens.

@throws Exception
764816
public function setTokens()
    {
        if (! isset($this->DMT_columns)) {
            throw new Exception("No Columns settings found in model, please see our package documentation https://github.com/F54it/laravel-token");
        }

        $table = $this->getTable();
        $token = new Token();
        foreach ($this->DMT_columns as $column => $settings) {
            $generated_token = null;
            switch ($settings['type']) {
                case Token::UNIQUE_NUMBER:
                    $generated_token = $token->uniqueNumber($table, $column, $settings['size'], $settings['special_chr']);

                    break;
                case Token::UNIQUE_STRING:
                    $generated_token = $token->uniqueString($table, $column, $settings['size'], $settings['special_chr']);

                    break;
                case Token::RANDOM:
                    $generated_token = $token->random($settings['size'], $settings['special_chr']);

                    break;
                case Token::RANDOM_NUMBER:
                    $generated_token = $token->randomNumber($settings['size'], $settings['special_chr']);

                    break;
                case Token::RANDOM_STRING:
                    $generated_token = $token->randomString($settings['size'], $settings['special_chr']);

                    break;
                case Token::UNIQUE:
                default:
                    $generated_token = $token->unique($table, $column, $settings['size'], $settings['special_chr']);
                    break;
            }
            $this->attributes[$column] = $generated_token;
        }
    }
453691
protected function processToken(): void
    {
        try {
            $this->checkAndRegisterMissingDocBlock();
            $this->checkAndRegisterNoMultiLine();
        } catch (CodeWarning $error) {
            $this->getExceptionHandler()->handleException($error);
        }
    }
1060610
public function Generate()
	{
		// check for all required fields
		if ( empty($_REQUEST["table_name"]) )
		{
			throw new Exception("Please select at least one table to generate");
		}

		$cstring = $this->GetConnectionString();

		// initialize the database connection
		$handler = new DBEventHandler();
		$connection = new DBConnection($cstring, $handler);
		$server = new DBServer($connection);
		$dbSchema = new DBSchema($server);

		$debug = isset($_REQUEST["debug"]) && $_REQUEST["debug"] == "1";
		$parameters = array();
		$tableNames = $_REQUEST["table_name"];
		$packageName = $_REQUEST["package"];
		$debug_output = "";
		
		$selectedTables = array();
		foreach ($tableNames as $tableName)
		{
			$selectedTables[] = $dbSchema->Tables[$tableName];
		}
		
		// see if arbitrary parameters were passed in - in which case they will be passed through to the templates
		$tmp = RequestUtil::Get('parameters');
		if ($tmp)
		{
			$pairs = explode("\n", str_replace("\r","", $tmp) );
			foreach ($pairs as $pair)
			{
				list($key,$val) = explode("=",$pair,2);
				$parameters[$key] = $val;
			}
		}
		
		// check for required parameters
		if (!array_key_exists('max_items_in_topnav', $parameters)) $parameters['max_items_in_topnav'] = self::$DEFAULT_MAX_ITEMS_IN_TOPNAV;

		$zipFile = new zipfile();

		$codeRoot = GlobalConfig::$APP_ROOT . '/code/';
		$tempRoot = GlobalConfig::$APP_ROOT . '/temp/';

		// initialize smarty
		$smarty = new Smarty();
		$smarty->template_dir = $codeRoot;
		$smarty->compile_dir = $tempRoot;
		$smarty->config_dir = $tempRoot;
		$smarty->cache_dir = $tempRoot;
		$smarty->caching = false;

		$appname = RequestUtil::Get("appname");
		$appRoot = RequestUtil::Get("appRoot");
		$includePath = RequestUtil::Get("includePath");
		$includePhar = RequestUtil::Get("includePhar");
		$enableLongPolling = RequestUtil::Get("enableLongPolling");

		$config = new AppConfig($codeRoot  . $packageName);
		
		foreach ($config->GetTemplateFiles() as $templateFile)
		{
			if ($templateFile->generate_mode == 3)
			{
				if ($includePhar == '1')
				{
					// proceed, copy the phar file
					$templateFile->generate_mode = 2;
				}
				else
				{
					// skip the phar file
					continue;
				}
			}
			
			if ($templateFile->generate_mode == 2)
			{
				// this is a template that is copied without parsing to the project (ie images, static files, etc)
				$templateFilename = str_replace(
						array('{$appname}','{$appname|lower}','{$appname|upper}'),
						array($appname,strtolower($appname),strtoupper($appname)),
						$templateFile->destination
				);

				$contents = file_get_contents($codeRoot . $templateFile->source);

				// this is a direct copy
				if ($debug)
				{
					$debug_output .= "\r\n###############################################################\r\n"
					. "# $templateFilename\r\n###############################################################\r\n"
					. "(contents of " . $codeRoot . $templateFile->source . ")\r\n";
				}
				else
				{
					$zipFile->addFile( $contents , $templateFilename);
				}
			}
			elseif ($templateFile->generate_mode == 1)
			{
				// single template where one is generated for the entire project instead of one for each selected table
				$templateFilename = str_replace(
						array('{$appRoot}','{$appRoot|lower}','{$appRoot|upper}'),
						array($appRoot,strtolower($appRoot),strtoupper($appRoot)),
						$templateFile->destination
				);

				$smarty->clearAllAssign();

				foreach ($parameters as $key => $val)
				{
					$smarty->assign($key,$val);
				}

				$smarty->assign("tableNames",$tableNames);
				$smarty->assign("templateFilename",$templateFilename);
				$smarty->assign("schema",$dbSchema);
				$smarty->assign("tables",$dbSchema->Tables);
				$smarty->assign("connection",$cstring);
				$smarty->assign("appname",$appname);
				$smarty->assign("appRoot",$appRoot);
				$smarty->assign("includePath",$includePath);
				$smarty->assign("includePhar",$includePhar);
				$smarty->assign("enableLongPolling",$enableLongPolling);
				$smarty->assign("PHREEZE_VERSION",Phreezer::$Version);

				$tableInfos = Array();
				
				// add all tables to a tableInfos array that can be used for cross-referencing by table name
						foreach ($dbSchema->Tables as $table)
				{
					if ($table->GetPrimaryKeyName())
					{
						$tableName = $table->Name;
						$tableInfos[$tableName] = Array();
						$tableInfos[$tableName]['table'] = $dbSchema->Tables[$tableName];
						$tableInfos[$tableName]['singular'] = $_REQUEST[$tableName."_singular"];
						$tableInfos[$tableName]['plural'] = $_REQUEST[$tableName."_plural"];
						$tableInfos[$tableName]['prefix'] = $_REQUEST[$tableName."_prefix"];
						$tableInfos[$tableName]['templateFilename'] = $templateFilename;
					}
				}
				
				$smarty->assign("tableInfos",$tableInfos);
				$smarty->assign("selectedTables",$selectedTables);

				if ($debug)
				{
					$debug_output .= "\r\n###############################################################\r\n"
					. "# $templateFilename\r\n###############################################################\r\n"
					. $smarty->fetch($templateFile->source) . "\r\n";
				}
				else
				{
					// we don't like bare linefeed characters
					$content = $body = preg_replace("/^(?=\n)|[^\r](?=\n)/", "\\0\r", $smarty->fetch($templateFile->source));

					$zipFile->addFile( $content , $templateFilename);
				}
			}
			else
			{
				// enumerate all selected tables and merge them with the selected template
				// append each to the zip file for output
				foreach ($tableNames as $tableName)
				{
					$singular = $_REQUEST[$tableName."_singular"];
					$plural = $_REQUEST[$tableName."_plural"];
					$prefix = $_REQUEST[$tableName."_prefix"];

					$templateFilename = str_replace(
							array('{$singular}','{$plural}','{$table}','{$appname}','{$singular|lower}','{$plural|lower}','{$table|lower}','{$appname|lower}','{$singular|upper}','{$plural|upper}','{$table|upper}','{$appname|upper}'),
							array($singular,$plural,$tableName,$appname,strtolower($singular),strtolower($plural),strtolower($tableName),strtolower($appname),strtoupper($singular),strtoupper($plural),strtoupper($tableName),strtoupper($appname)),
							$templateFile->destination);

					$smarty->clearAllAssign();
					$smarty->assign("appname",$appname);
					$smarty->assign("singular",$singular);
					$smarty->assign("plural",$plural);
					$smarty->assign("prefix",$prefix);
					$smarty->assign("templateFilename",$templateFilename);
					$smarty->assign("table",$dbSchema->Tables[$tableName]);
					$smarty->assign("connection",$cstring);
					$smarty->assign("appRoot",$appRoot);
					$smarty->assign("includePath",$includePath);
					$smarty->assign("includePhar",$includePhar);
					$smarty->assign("enableLongPolling",$enableLongPolling);
					$smarty->assign("PHREEZE_VERSION",Phreezer::$Version);

					$tableInfos = Array();
					
					// add all tables to a tableInfos array that can be used for cross-referencing by table name
					foreach ($dbSchema->Tables as $table)
					{
						if ($table->GetPrimaryKeyName())
						{
							$tableName = $table->Name;
							$tableInfos[$tableName] = Array();
							$tableInfos[$tableName]['table'] = $dbSchema->Tables[$tableName];
							$tableInfos[$tableName]['singular'] = $_REQUEST[$tableName."_singular"];
							$tableInfos[$tableName]['plural'] = $_REQUEST[$tableName."_plural"];
							$tableInfos[$tableName]['prefix'] = $_REQUEST[$tableName."_prefix"];
							$tableInfos[$tableName]['templateFilename'] = $templateFilename;
						}
					}
					
					$smarty->assign("tableInfos",$tableInfos);
					$smarty->assign("selectedTables",$selectedTables);
					
					foreach ($parameters as $key => $val)
					{
						$smarty->assign($key,$val);
					}

					//print "<pre>"; print_r($dbSchema->Tables[$tableName]->PrimaryKeyIsAutoIncrement()); die();
					if ($debug)
					{
						$debug_output .= "\r\n###############################################################\r\n"
						. "# $templateFilename\r\n###############################################################\r\n"
						. $smarty->fetch($templateFile->source) . "\r\n";
					}
					else
					{
						$zipFile->addFile( $smarty->fetch($templateFile->source) , $templateFilename);
					}

				}
			}

		}

		if ($debug)
		{
			header("Content-type: text/plain");
			print $debug_output;
		}
		else
		{
			// now output the zip as binary data to the browser
			header("Content-type: application/force-download");

			// laplix 2007-11-02.
			// Use the application name provided by the user in show_tables.
			//header("Content-disposition: attachment; filename=".str_replace(" ","_",$G_CONNSTR->DBName).".zip");
			header("Content-disposition: attachment; filename=".str_replace(" ","_",strtolower(str_replace("/","", $appRoot))).".zip");

			header("Content-Transfer-Encoding: Binary");
			header('Content-Type: application/zip');
			print $zipFile->file();
		}
	}
312084
public function generate() {
        
        $session = new Session();

        if(false === $session -> has('_token')) {
            $session -> add('_token', []);
        }

        $name  = TokenHash :: create(20, true, true, true);
        $value = TokenHash :: create(40, true, true, true);

        $session -> add('_token', [$name => $value]);
        $amount = count($session -> get('_token'));
        $limit  = Application :: get(['token', 'amount'], self :: TOKEN_AMOUNT);

        if($amount >= $limit) {
            $session -> add('_token', array_slice($session -> pull('_token'), $amount - $limit, null, true));
        }

        return (object) ['name' => $name, 'value' => $value];
    }
1137753
public final void generate()
            throws Exception
    {
        VelocityContext context = createAndPopulateContext();

        Writer writer = WriterFactory.newWriter( config.getOutputFile(), config.getEncoding() );

        try
        {
            velocityTemplate.merge( context, writer );
            writer.flush();
        }
        catch ( Exception e )
        {
            throw new Exception(
                    "Could not generate the template " + velocityTemplate.getName() + ": " + e.getMessage(), e );
        }
        finally
        {
            writer.close();
        }

    }
1046960
protected AbstractTokenizer generateTokenizer() {
        Class<? extends AbstractTokenizer> tokenizer = parameters.getTokenizer();
        if(tokenizer==null) {
            return null;
        }

        try {
            return tokenizer.newInstance();
        } 
        catch (InstantiationException | IllegalAccessException ex) {
            throw new RuntimeException(ex);
        }
    }
287666
protected function generateClass()
    {
        if ($this->class != null) {
            throw new Exception("The class has already been generated");
        }

        $this->class = new PhpClass($this->phpIdentifier, false);

        $first = true;

        $names = array();
        foreach ($this->values as $value) {
            $name = Validator::validateConstant($value);

            $name = Validator::validateUnique($name, function ($name) use ($names) {
                    return !in_array($name, $names);
            });

            if ($first) {
                $this->class->addConstant($name, '__default');
                $first = false;
            }

            $this->class->addConstant($value, $name);
            $names[] = $name;
        }
    }
1060588
public void generate() throws IOException {
        final Document doc = DocumentFactory.getInstance().createDocument();
        final Element root = doc.addElement("project");
        //iterate through entities in correct order
        for (final ResourceXMLParser.Entity entity : entities) {
            if (NODE_ENTITY_TAG.equals(entity.getResourceType())) {
                final Element ent = genEntityCommon(root, entity);
                genNode(ent, entity);
            }
        }

        if (null != file) {
            FileOutputStream out=new FileOutputStream(file);
            try{
                serializeDocToStream(out, doc);
            }finally{
                out.close();
            }
        } else if (null != output) {
            serializeDocToStream(output, doc);
        }
    }
1157336
public function generate()
    {
        if (is_null($this->publicKey)) {
            throw new \Exception('Public Key has not been set');
        }

        $compressedValue = $this->publicKey;

        if (empty($compressedValue)) {
            throw new \Exception('The Public Key needs to be generated.');
        }

        $step1 = Util::sha256(Util::binConv($compressedValue), true);

        $step2 = Util::ripe160($step1);

        $step3 = sprintf(
            '%s%s%s',
            self::SIN_VERSION,
            self::SIN_TYPE,
            $step2
        );

        $step4 = Util::twoSha256(Util::binConv($step3), true);

        $step5 = substr(bin2hex($step4), 0, 8);

        $step6 = $step3.$step5;

        $this->value = Base58::encode($step6);

        return $this;
    }
529522
private function _generateAlphaToken()
    {
        $timestamp = strtotime($this->_generateTimestamp());
        $characters = str_split('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ');
        shuffle($characters);
        $randomString = '';
        foreach (str_split((string) $timestamp) as $num) {
            $randomString .= $characters[$num];
        }
        return $randomString;
    }
531052
public static function generateSigningKeypair() : Keypair
    {
        try {
            $keypair = \sodium_crypto_sign_keypair();
            return new Keypair(
                \sodium_crypto_sign_secretkey($keypair),
                \sodium_crypto_sign_publickey($keypair)
            );
        } catch (SodiumException $e) {
            throw new Exception($e->getMessage());
        }
    }
1342001
def gen_token():
    """"""
    return ''.join(
        random.choice(
            string.ascii_uppercase + string.ascii_lowercase + string.digits)
        for _ in range(32))
205376
protected function generateAccessToken()
    {
        $tokenLen = 40;
        if (file_exists('/dev/urandom')) { // Get 100 bytes of random data
            $randomData = file_get_contents('/dev/urandom', false, null, 0, 100) . uniqid(mt_rand(), true);
        } else {
            $randomData = mt_rand() . mt_rand() . mt_rand() . mt_rand() . microtime(true) . uniqid(mt_rand(), true);
        }
        return substr(hash('sha512', $randomData), 0, $tokenLen);
    }
996108
public function generate()
    {
        if (count($this->functions) === 0) {
            throw new \Exception('function list empty');
        }

        $parts = [];
        foreach ($this->functions as $function) {
            $args = [];
            if ($function['args']) {
                $args = $this->generateArgs($function['args']);
            }
            $parts[] = $function['name'].'('.implode(', ', $args).')';
        }

        $class = $this->class['name'];
        $class .= count($this->class['args']) ? '('.implode(', ', $this->class['args']).')' : '';

        $result = $class.($this->isStatic() ? '::' : '->').implode($parts, '->');

        return $result;
    }
237106
public function generateToken() {
		if( !isset($_SESSION[self::SESSION_KEY][$this->name]) ) {
			$_SESSION[self::SESSION_KEY][$this->name]	= array();
		}
		$TOKEN_SESSION = &$_SESSION[self::SESSION_KEY][$this->name];
		do {
			$token = generatePassword(static::$TOKEN_LENGTH);
		} while( isset($TOKEN_SESSION[$token]) );
		if( count($TOKEN_SESSION) >= $this->maxToken ) {
			array_shift($TOKEN_SESSION);
		}
		$TOKEN_SESSION[$token]	= 0;
		return $token;
	}
597427
public static function generateUrl($name, array $tokens = [])
    {
        if ($name === null) {
            return;
        }

        if (isset(static::$routes[$name])) {
            $route = static::$routes[$name];
        } else {
            foreach (static::$routes as $r) {
                if ($r->name === $name) {
                    $route = $r;
                }
            }
        }

        if (isset($route)) {
            return $route->generateUrl($tokens);
        } else {
            throw new Exception("No route with name [{$name}]");
        }
    }
1218821
public function token() {
        $key = 'WeChatToken'.$this->get('appid');
        if (Factory::cache()->has($key)) {
            return Factory::cache()->get($key);
        }
        $args = $this->getToken()->json();
        if (!is_array($args)) {
            throw new Exception('HTTP ERROR!');
        }
        if (!array_key_exists('access_token', $args)) {
            throw new Exception(isset($args['errmsg']) ?
                $args['errmsg'] : 'GET ACCESS TOKEN ERROR!');
        }
        Factory::cache()->set($key, $args['access_token'], $args['expires_in']);
        return $args['access_token'];
    }