<?php

/**
 * Lifestyle Webconsulting GmbH
 *
 * LICENSE: This Software is the property of Lifestyle Webconsulting GmbH (Aschaffenburg, Germany)
 * and is private by copyright law - it is NOT Freeware.
 *
 * Any unauthorized use of this software without a valid license
 * is a violation of the license agreement and will be prosecuted by
 * civil and criminal law.
 *
 * @copyright  2018 Lifestyle Webconsulting GmbH
 * @link       http://www.life-style.de
 */

namespace LifeStyle\Tools\SamlBundle\Library\Utils;

/**
 * Class Security
 *
 * @copyright  2018 Lifestyle Webconsulting GmbH
 * @link       http://www.life-style.de
 */
class Security
{
    /**
     * @param string $username
     * @return string
     */
    public static function stringNiner($username)
    {
        return '4' . join('', array_map(function($vvv){ return $vvv . '2'; }, static::str_split_unicode($username)));
    }

    /**
     * A-N-N-A
     * @param string $username
     * @return string
     */
    public static function stringRewinder($username)
    {
        return join('', array_reverse(static::str_split_unicode($username,1)));
    }

    /**
     * @param string $str
     * @param int $chars
     * @return array|array[]|false|string[]
     */
    public static function str_split_unicode($str, $chars = 0) {
        if ($chars > 0) {
            $ret = array();
            $len = mb_strlen($str, "UTF-8");
            for ($idx = 0; $idx < $len; $idx += $chars) {
                $ret[] = mb_substr($str, $idx, $chars, "UTF-8");
            }
            return $ret;
        }
        return preg_split("//u", $str, -1, PREG_SPLIT_NO_EMPTY);
    }

    /**
     * Parse cookie file in COOKIEJAR format
     *
     * @param string $cookieFileName
     * @return bool|string
     */
    public static function getSessionIdFromCookie($cookieFileName)
    {
        $lines = file($cookieFileName);
        foreach($lines as $line) {
            if ($line[0] !== '#' || substr_count($line, "\t") !== 6) {
                continue;
            }
            $tokens = explode("\t", $line);
            $tokens = array_map('trim', $tokens);
            if ('SimpleSAMLSessionID' === urldecode($tokens[5])) {
                return urldecode($tokens[6]);
            }
        }
        return false;
    }
}
