Your IP : 216.73.217.79


Current Path : /var/www/v3.cesa.co.za/src/CoreBundle/Services/
Upload File :
Current File : /var/www/v3.cesa.co.za/src/CoreBundle/Services/Utils.php

<?php

namespace App\CoreBundle\Services;

use App\CoreBundle\Services\Openssl_EncryptDecrypt;

class Utils
{

    static public function slugify($text)
    {

        // replace all non letters or digits by -
        $text = preg_replace('/\W+/', '-', $text);

        // trim and lowercase
        $text = strtolower(trim($text, '-'));

        return $text;
    }

    static public function getWordScore($text)
    {

        $return = 0;
        $text = str_replace('The ', '', $text);
        $text = str_replace(' ', '', $text);
        $text = str_replace('"', '', $text);
        $text = str_replace("'", '', $text);
        $text = strtolower($text);

        for ($chr = 0; $chr <= 2; $chr++) {
            $return += 255 - ord(substr($text, $chr, 1)) + ((3 - $chr) * 50);
        }

        return $return;
    }

    /**
     * Get the date object for the first day of a month
     *
     * @param  \DateTime $dateTime
     * @return \DateTime
     */
    static public function getFirstDayOfMonth(\DateTime $dateTime)
    {
        $return = $dateTime->modify('first day of this month');
        $return->setTime(0, 0, 0);

        return $return;
    }

    /**
     * Get the date object for the last day of a month
     *
     * @param  \DateTime $dateTime
     * @return \DateTime
     */
    static public function getLastDayOfMonth(\DateTime $dateTime)
    {
        $return = $dateTime->modify('last day of this month');
        $return->setTime(0, 0, 0);

        return $return;
    }

    /**
     * Get the difference between two dates in days
     *
     * @param  \DateTime $firstDateTime
     * @param  \DateTime $secondDateTime
     * @return int
     */
    static public function getDaysDifference(\DateTime $firstDateTime, \DateTime $secondDateTime)
    {

        $firstDateTime->setTime(0, 0, 0);
        $secondDateTime->setTime(0, 0, 0);

        $interval = date_diff($firstDateTime, $secondDateTime);

        return $interval->days;
    }

    /**
     * Get the date object for a string
     *
     * @param  $dateTime
     * @return \DateTime
     */
    static public function getDateObject($dateTime)
    {

        if (is_object($dateTime)) {
            return $dateTime;
        }

        return new \DateTime($dateTime);
    }

    /**
     * Get the date object for a string
     *
     * @param  $moneyValue
     * @return string
     */
    static public function formatCurrency($moneyValue)
    {

        if (is_nan($moneyValue)) {
            $moneyValue = 0;
        }

        $moneyValue = floatval($moneyValue);

        return 'R ' . number_format($moneyValue, 2, '.', ' ');
    }

    static public function stripStringForSearch($text)
    {

        $text = urldecode(strtolower($text));

        $text = str_replace('/', '', $text);
        $text = str_replace('(', '', $text);
        $text = str_replace(')', '', $text);
        $text = str_replace('"', '', $text);
        $text = str_replace('.', ' ', $text);
        $text = str_replace(' and ', ' ', $text);
        $text = str_replace(', ', ' ', $text);
        $text = str_replace('@', '*', $text);
        $text = str_replace(';', '*', $text);
        $text = str_replace(':', '*', $text);
        $text = str_replace('  ', ' ', $text);
        $text = html_entity_decode($text);
        $text = urldecode($text);

        return $text;
    }

    static public function getFileDataFromBlob($blob)
    {

        $return = '';

        if (is_resource($blob)) {
            while (!feof($blob)) {
                $return .= fread($blob, 8192);
            }
        } else {
            $return = (string) $blob;
        }

        $return = str_replace('data:image/jpeg;base64,', '', $return);
        $return = str_replace('data:image/png;base64,', '', $return);

        //        echo strpos(' ' . $return, 'data:image/jpeg;base64,data:image/jpeg;base64') . "\r\n" . $return;
        //        exit;

        return $return;
    }

    static public function getURLContent($url, $conf = array())
    {

        $user_agent = 'IGACore URL Getter';

        if (!isset($conf['method'])) {
            $conf['method'] = 'GET';
        }

        if (!isset($conf['post'])) {
            $conf['post'] = 0;
        }

        $options = array(
            CURLOPT_CUSTOMREQUEST => $conf['method'], //set request type post or get
            CURLOPT_POST => $conf['post'], //set to GET
            CURLOPT_USERAGENT => $user_agent, //set user agent
            CURLOPT_RETURNTRANSFER => 1, // return web page
            CURLOPT_HEADER => 0, // don't return headers
            CURLOPT_FOLLOWLOCATION => 1, // follow redirects
            CURLOPT_ENCODING => "", // handle all encodings
            CURLOPT_AUTOREFERER => 1, // set referer on redirect
            CURLOPT_CONNECTTIMEOUT => 120, // timeout on connect
            CURLOPT_TIMEOUT => 120, // timeout on response
            CURLOPT_MAXREDIRS => 10, // stop after 10 redirects
            CURLOPT_SSL_VERIFYPEER => 0, // don't check ssl
        );

        if (isset($conf['method']) && strlen($conf['method']) > 0 && $conf['method'] == 'PUT') {
            $options[CURLOPT_PUT] = 1;
            $options[CURLOPT_CUSTOMREQUEST] = 'PUT';
            unset($options[CURLOPT_AUTOREFERER]);
            unset($options[CURLOPT_ENCODING]);
            unset($options[CURLOPT_USERAGENT]);
        } elseif (isset($conf['method']) && strlen($conf['method']) > 0) {
            $options[CURLOPT_CUSTOMREQUEST] = $conf['method'];
        }

        if (isset($conf['put_data']) && is_array($conf['put_data']) && count($conf['put_data']) > 0) {
            $options[CURLOPT_POSTFIELDS] = $conf['put_data'];
        }

        if (isset($conf['header']) && count($conf['header']) > 0) {
            $options[CURLOPT_HTTPHEADER] = $conf['header'];
        }

        if (isset($conf['usr_pwd']) && !empty($conf['usr_pwd'])) {
            $options[CURLOPT_USERPWD] = $conf['usr_pwd'];
        }

        $ch = curl_init($url);
        curl_setopt_array($ch, $options);
        $content = curl_exec($ch);
        $err = curl_errno($ch);
        $errmsg = curl_error($ch);
        $header = curl_getinfo($ch);
        curl_close($ch);

        $header['errno'] = $err;
        $header['errmsg'] = $errmsg;
        $header['content'] = $content;

        return $header;
    }

    static public function getJsonFromURL($url)
    {
        $jsonString = self::getURLContent($url);

        //        echo 'response: ' . $jsonString['content'] . '<br /><br />';
        $jsonArray = json_decode($jsonString['content'], true);

        if (!is_array($jsonArray)) {
            $jsonArray = array();
        }

        //        var_dump($jsonArray);
        //        echo 'done in utils <br /><br />';

        return $jsonArray;
    }

    static public function getXmlFromURL($url)
    {
        $jsonString = self::getURLContent($url);

        //        echo 'response: ' . $jsonString['content'] . '<br /><br />';
        $p = xml_parser_create();
        $xmlArray = null;
        $index = null;
        xml_parse_into_struct($p, $jsonString['content'], $xmlArray, $index);
        xml_parser_free($p);

        if (!is_array($xmlArray)) {
            $xmlArray = array();
        }

        //        var_dump($jsonArray);
        //        echo 'done in utils <br /><br />';

        return $xmlArray;
    }

    static public function getShortURL($urlToShorten, $bitlyToken = '')
    {

        $ch = curl_init();

        if (strlen($bitlyToken) > 0) {

            curl_setopt($ch, CURLOPT_URL, 'https://api-ssl.bitly.com/v4/shorten');
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(array('long_url' => $urlToShorten)));

            $headers = array();
            $headers[] = 'Authorization: Bearer ' . $bitlyToken;
            $headers[] = 'Content-Type: application/json';
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        } else {

            curl_setopt($ch, CURLOPT_URL, 'https://api.shorte.st/v1/data/url');
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

            curl_setopt($ch, CURLOPT_POSTFIELDS, "urlToShorten=$urlToShorten");

            $headers = array();
            $headers[] = 'Public-Api-Token: a5e6fcda57af1827ed703440590f1bd3';
            $headers[] = 'Content-Type: application/x-www-form-urlencoded';
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        }

        $content = curl_exec($ch);
        $err = curl_errno($ch);
        $errmsg = curl_error($ch);
        $header = curl_getinfo($ch);
        curl_close($ch);

        $header['errno'] = $err;
        $header['errmsg'] = $errmsg;
        $header['content'] = $content;

        return $header;
    }

    static public function getFormDataArrayFromContent($formData)
    {

        $items = explode("&", $formData);
        $return = array();

        foreach ($items as $oneVal) {
            $oneValArr = explode('=', $oneVal);
            $return[$oneValArr[0]] = $oneValArr[1];
        }

        return $return;
    }

    static public function getYesNoString($bool)
    {

        if ($bool) {
            return 'Yes';
        } else {
            return 'No';
        }
    }

    static public function getYesNoArray($languagePhrasesManager = null)
    {

        if (is_object($languagePhrasesManager)) {
            return array(
                $languagePhrasesManager->translate('Yes') => 1,
                $languagePhrasesManager->translate('No') => 0,
            );
        }

        return array(
            'Yes' => 1,
            'No' => 0,
        );
    }

    static public function getSystemMemInfo()
    {
        $data = explode("\n", file_get_contents("/proc/meminfo"));
        $meminfo = array();
        foreach ($data as $line) {

            if (empty($line)) {
                continue;
            }

            list($key, $val) = explode(":", $line);
            $meminfo[$key] = trim($val);
        }
        return $meminfo;
    }

    static public function leadingChars($number, $numChars, $paddedWith = '0')
    {
        return str_pad($number, $numChars, $paddedWith, STR_PAD_LEFT);
    }

    static public function getIdString($value)
    {
        $value = str_replace(' ', '-', ucwords($value));
        $value = str_replace('/', '-', ucwords($value));
        $value = str_replace('--', '-', ucwords($value));
        $value = str_replace('--', '-', ucwords($value));
        $value = str_replace('-', '_', ucwords($value));
        $value = str_replace('(', '_', ucwords($value));
        $value = str_replace(')', '_', ucwords($value));
        return $value;
    }

    static public function encryptString($strIn)
    {
        return base64_encode($strIn);
        //        return gzcompress($strIn);
        //        $OpensslEncryption = new Openssl_EncryptDecrypt();
        //        return $OpensslEncryption->encrypt($strIn);
    }

    static public function decryptString($strIn)
    {
        return base64_decode($strIn);
        //        return gzdecode($strIn);
        //        $OpensslEncryption = new Openssl_EncryptDecrypt();
        //        return $OpensslEncryption->decrypt($strIn);
    }

    /*
     * Get GCD
     */

    static public function getGcd($int1, $int2)
    {
        return ($int2 == 0) ? $int1 : self::getGcd($int2, $int1 % $int2);
    }

    static public function removeEmptyElements($arrIn)
    {

        $arrOut = array();

        foreach ($arrIn as $elem) {
            if (strlen($elem) > 0) {
                $arrOut[] = $elem;
            }
        }

        return $arrOut;
    }

    static public function formatArrayCsv($arrIn)
    {

        $oneRow = array();

        foreach ($arrIn as $oneVal) {

            if (is_object($oneVal) && $oneVal instanceof \DateTime) {
                $oneRow[] = $oneVal->format("Y-m-d H:i:s");
            } else {
                $oneRow[] = $oneVal;
            }
        } //foreach

        return $oneRow;
    }

    static public function arraySearchRemove($array, $value)
    {

        $pos = array_search($value, $array);

        if ($pos) {
            unset($array[$pos]);
        }
    }

    static public function getDOBFromSAID($SAIDNo): \DateTime
    {

        $dobY = substr($SAIDNo, 0, 2);

        if ($dobY < substr(date('Y'), 2, 2)) {
            $dobY = '20' . $dobY;
        } else {
            $dobY = '19' . $dobY;
        }

        $return = new \DateTime();

        $return->setDate($dobY, substr($SAIDNo, 2, 2), substr($SAIDNo, 4, 2));

        return $return;
    }

    static public function getDOBStringFromSAID($SAIDNo)
    {

        $dob = self::getDOBFromSAID($SAIDNo);

        if (is_null($dob)) {
            return '';
        }

        return $dob->format('d-m-Y');
    }

    /**
     * Check if string is a valid e-mail address
     *
     * @param string $email
     * @return bool
     */
    public static function isEmailAddressValid($email)
    {
        return filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
    }
}