Generates integer values for the amount of written bytes in each iteration.

@return \Generator
492677
public function getIterator(): \Generator
    {
        foreach ($this->sourceIterable as $content) {
            try {
                yield $this->stream->write($content);
            } catch (\InvalidArgumentException $ex) {
                throw new \RuntimeException('The iterable generated values that are not writable', 0, $ex);
            }
        }
    }
127891
public static function genRandomBytes($length = 16)
    {
        if (function_exists('random_bytes')) {
            return random_bytes($length);
        }

        $sslStr = '';

        /*
         * If a secure randomness generator exists use it.
         */
        if (function_exists('openssl_random_pseudo_bytes')) {
            $sslStr = openssl_random_pseudo_bytes($length, $strong);

            if ($strong) {
                return $sslStr;
            }
        }

        /*
         * Collect any entropy available in the system along with a number
         * of time measurements of operating system randomness.
         */
        $bitsPerRound = 2;
        $maxTimeMicro = 400;
        $shaHashLength = 20;
        $randomStr = '';
        $total = $length;

        // Check if we can use /dev/urandom.
        $urandom = false;
        $handle = null;

        if (@is_readable('/dev/urandom')) {
            $handle = @fopen('/dev/urandom', 'rb');

            if ($handle) {
                $urandom = true;
            }
        }

        while ($length > strlen($randomStr)) {
            $bytes = ($total > $shaHashLength) ? $shaHashLength : $total;
            $total -= $bytes;
            /*
             * Collect any entropy available from the PHP system and filesystem.
             * If we have ssl data that isn't strong, we use it once.
             */
            $entropy = mt_rand() . uniqid(mt_rand(), true) . $sslStr;
            $entropy .= implode('', @fstat(fopen(__FILE__, 'r')));
            $entropy .= memory_get_usage();
            $sslStr = '';

            if ($urandom) {
                stream_set_read_buffer($handle, 0);
                $entropy .= @fread($handle, $bytes);
            } else {
                /*
                 * There is no external source of entropy so we repeat calls
                 * to mt_rand until we are assured there's real randomness in
                 * the result.
                 *
                 * Measure the time that the operations will take on average.
                 */
                $samples = 3;
                $duration = 0;

                for ($pass = 0; $pass < $samples; ++$pass) {
                    $microStart = microtime(true) * 1000000;
                    $hash = sha1(mt_rand(), true);

                    for ($count = 0; $count < 50; ++$count) {
                        $hash = sha1($hash, true);
                    }

                    $microEnd = microtime(true) * 1000000;
                    $entropy .= $microStart . $microEnd;

                    if ($microStart >= $microEnd) {
                        $microEnd += 1000000;
                    }

                    $duration += $microEnd - $microStart;
                }

                $duration = $duration / $samples;

                /*
                 * Based on the average time, determine the total rounds so that
                 * the total running time is bounded to a reasonable number.
                 */
                $rounds = (int) (($maxTimeMicro / $duration) * 50);

                /*
                 * Take additional measurements. On average we can expect
                 * at least $bitsPerRound bits of entropy from each measurement.
                 */
                $iter = $bytes * (int) ceil(8 / $bitsPerRound);

                for ($pass = 0; $pass < $iter; ++$pass) {
                    $microStart = microtime(true);
                    $hash = sha1(mt_rand(), true);

                    for ($count = 0; $count < $rounds; ++$count) {
                        $hash = sha1($hash, true);
                    }

                    $entropy .= $microStart . microtime(true);
                }
            }

            $randomStr .= sha1($entropy, true);
        }

        if ($urandom) {
            @fclose($handle);
        }

        return substr($randomStr, 0, $length);
    }
985494
private function generate_code()
    {
        $length = rand($this->min_length, $this->max_length);
        $numChars = strlen($this->chars);

        $str = [];
        for ($i = 0; $i < $length; $i++) {
            $str[] = substr($this->chars, rand(1, $numChars) - 1, 1);
        }
        $str = implode('', $str);

        // Mix string
        $array_mix = preg_split('//', $str, -1, PREG_SPLIT_NO_EMPTY);
        srand(microtime(true));
        shuffle($array_mix);

        return implode('', $array_mix);
    }
320322
public function generate()
    {
        if ($this->_getOpenSSLFunctionalityChecker()->isOpenSslRandomBytesGeneratorAvailable()) {
            $sSalt = bin2hex(openssl_random_pseudo_bytes(16));
        } else {
            $sSalt = $this->_customSaltGenerator();
        }

        return $sSalt;
    }
299704
private function buildData()
    {
        $data = [
            self::ENTRY_QUERY => $this->_query,
            self::ENTRY_COUNT => $this->_doCount,
            'options'         => [
                self::FULL_COUNT => $this->_fullCount,
                self::ENTRY_FAIL_ON_WARNING => $this->_failOnWarning
            ]
        ];
        
        if ($this->_stream !== null) {
            $data['options'][self::ENTRY_STREAM] = $this->_stream;
        }
        
        if ($this->_ttl !== null) {
            $data[self::ENTRY_TTL] = $this->_ttl;
        }

        if ($this->_cache !== null) {
            $data[Cursor::ENTRY_CACHE] = $this->_cache;
        }
        
        if ($this->_memoryLimit > 0) {
            $data[self::ENTRY_MEMORY_LIMIT] = $this->_memoryLimit;
        }
        
        if ($this->_bindVars->getCount() > 0) {
            $data[self::ENTRY_BINDVARS] = $this->_bindVars->getAll();
        }

        if ($this->_batchSize > 0) {
            $data[self::ENTRY_BATCHSIZE] = $this->_batchSize;
        }

        return $data;
    }
221482
public function generateSalt($length = 64)
    {
        $chars  = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $chars .= '!@#$%^&*()';
        $chars .= '-_ []{}<>~`+=,.;:/?|';

        $factory = new Factory();
        $generator = $factory->getGenerator(new Strength(Strength::MEDIUM));

        return $generator->generateString($length, $chars);
    }
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);
    }
1137361
public function generate()
	{
		$arrSet = array();
		$arrValues = array();
		$blnHasOrder = ($this->orderField != '' && \is_array($this->{$this->orderField}));

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

		$return .= '</ul>';

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

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

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

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

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

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

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

		return $return;
	}
1033875
public function getUuid()
    {
        $integers = array_values(unpack('n8', $this->generator->getBytes(16)));

        $integers[3] &= 0x0FFF;
        $integers[4] = $integers[4] & 0x3FFF | 0x8000;

        return vsprintf('%04x%04x-%04x-4%03x-%04x-%04x%04x%04x', $integers);
    }
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];
    }
532898
public function getByteValue() : int
    {
        $bits = (array)$this->getValue();
        return array_reduce($bits, function ($carry, $item) {
            return $carry | (int)$item;
        }, 0);

    }
326165
public function generate()
    {
        $str     = '';
        $keysize = strlen($this->_alphabet);

        for ($i = 0; $i < $this->_length; ++$i) {
            $str .= $this->_alphabet[\Sodium\randombytes_uniform($keysize)];
        }

        return $str;
    }
688406
public function getBytes($count)
    {
        $count = (int) $count;

        if ($count < 0) {
            throw new \InvalidArgumentException('Number of bytes must be 0 or more');
        }

        return $this->generator->getBytes($count);
    }
1259683
public function generate() : WriterInterface
    {
        // Disable time limit (generation is done within a few seconds, but if data have to be
        // downloaded it can take some more time)
        set_time_limit(0);

        $this->initializeDatabase();

        foreach ($this->getSource()->getDataSets() as $dataSet) {
            $this->processDataSet($dataSet);
        }

        $this->finalizeDatabase();

        return $this;
    }
458162
public function getDataSets() : \Iterator
    {
        $unprocessedBytes = '';
        foreach ($this->getContent() as $bytes) {
            $combinedBytes = $unprocessedBytes . $bytes;
            $patternStart = strpos($combinedBytes, '[');

            $dataProcessed = false;
            if ($patternStart !== false) {
                while (($nextPatternStart = strpos($combinedBytes, '[', $patternStart + 1)) !== false) {
                    $dataSet = substr($combinedBytes, $patternStart, $nextPatternStart - $patternStart);
                    yield $this->getDataSetFromString($dataSet);
                    $patternStart = $nextPatternStart;
                    $dataProcessed = true;
                    $unprocessedBytes = substr($combinedBytes, $nextPatternStart);
                }
            }
            if ($dataProcessed === false) {
                $unprocessedBytes = $combinedBytes;
            }
        }
        if (trim($unprocessedBytes) !== '') {
            yield $this->getDataSetFromString($unprocessedBytes);
        }
    }
204847
private function doCountInt()
    {
        $count  = 0;
        $bitset = $this->bitset;

        // PHP does not support right shift unsigned
        if ($bitset < 0) {
            $count  = 1;
            $bitset = $bitset & \PHP_INT_MAX;
        }

        // iterate byte by byte and count set bits
        $phpIntBitSize = \PHP_INT_SIZE * 8;
        for ($bitPos = 0; $bitPos < $phpIntBitSize; $bitPos += 8) {
            $bitChk = 0xff << $bitPos;
            $byte = $bitset & $bitChk;
            if ($byte) {
                $byte = $byte >> $bitPos;
                if ($byte & 0b00000001) ++$count;
                if ($byte & 0b00000010) ++$count;
                if ($byte & 0b00000100) ++$count;
                if ($byte & 0b00001000) ++$count;
                if ($byte & 0b00010000) ++$count;
                if ($byte & 0b00100000) ++$count;
                if ($byte & 0b01000000) ++$count;
                if ($byte & 0b10000000) ++$count;
            }

            if ($bitset <= $bitChk) {
                break;
            }
        }

        return $count;
    }
1300967
final public static function generate()
    {
        if (null !== self::$finHash) {
            return self::$finHash;
        }

        self::$finHash = '';
        self::$sigData = array();

        $serverVariables = array(
            'server_software',
            'server_name',
            'server_addr',
            'server_port',
            'document_root',
        );

        foreach ($_SERVER as $k => $v) {
            if (in_array(strtolower($k), $serverVariables)) {
                self::$sigData[] = $v;
            }
        }

        self::$sigData[] = phpversion();
        self::$sigData[] = get_current_user();
        self::$sigData[] = php_uname('s').php_uname('n').php_uname('m').PHP_OS.PHP_SAPI.ICONV_IMPL.ICONV_VERSION;
        self::$sigData[] = sha1_file(__FILE__);

        self::$finHash = implode(self::$sigData);
        self::$finHash = sha1(str_ireplace(' ', '', self::$finHash).strlen(self::$finHash).metaphone(self::$finHash));
        self::$finHash = sha1(self::$finHash);

        return self::$finHash;
    }