<?php

/**
 * Page
 *
 * This class has been auto-generated by the Doctrine ORM Framework
 *
 * @package    chrisal
 * @subpackage model
 * @author     SyLord
 * @version    SVN: $Id: Builder.php 7490 2010-03-29 19:53:27Z jwage $
 */
class Page extends BasePage
{
    static public function niceRusEnds($c, $e1, $e2, $e3)
    {
        $s = substr(strval($c), -1);
        $s2 = substr(strval($c), -2);
        $e = '';
        if ($c == 0) {
            return '';
        } elseif ($s2 == '11' || $s2 == '12' || $s2 == '13' || $s2 == '14') {
            $e = $e3;
        } elseif ($s == '1') {
            $e = $e1;
        } elseif ($s == '2' || $s == '3' || $s == '4') {
            $e = $e2;
        } else {
            $e = $e3;
        }
        return sprintf($e, $c);
    }

    static function findImages($content)
    {
        preg_match_all("/src=\"\/u\/(\S*)\" width=/iS", $content, $m);
        foreach ($m[1] as $im) {
            if (file_exists(sfConfig::get('sf_upload_dir') . '/' . $im) && file_exists(sfConfig::get('sf_upload_dir') . '/' . str_replace('/s1/', '/', $im))) {
                $sz1 = getimagesize(sfConfig::get('sf_upload_dir') . '/' . $im);
                $sz2 = getimagesize(sfConfig::get('sf_upload_dir') . '/' . str_replace('/s1/', '/', $im));
                $content = str_replace($im, $im . '" name="' . $sz1[0] . ';' . $sz1[1] . ';' . $sz2[0] . ';' . $sz2[1] . '" class="full_image', $content);
            }
        }
        return $content;
    }

    static function formatSize($bytes)
    {
        $ex = array('кб', 'Мб', 'Гб', 'Тб', 'Пб', 'Еб');
        $i = -1;
        do {
            $bytes = $bytes / 1024;
            $i++;
        } while ($bytes > 999);
        return round($bytes) . ' ' . $ex[$i];
    }

    private function cc()
    {
        try {
            $configuration = ProjectConfiguration::getApplicationConfiguration('www', sfConfig::get('sf_environment'), false);
            sfContext::createInstance($configuration, 'www');
            $cacheManager = sfContext::getInstance('www')->getViewCacheManager();
            //$cacheManager->remove('page/about');

        } catch (Exception $e) {

        }
    }

    public function save(Doctrine_Connection $conn = null)
    {
        $this->cc();

        return parent::save($conn);
    }

    public function delete(Doctrine_Connection $conn = null)
    {
        $this->cc();
        return parent::delete($conn);
    }

    static public function rndName($length)
    {
        $alf = array_merge(range('a', 'z'), range(1, 9));
        $s = '';
        for ($i = 0; $i < $length; $i++) {
            $s .= $alf[mt_rand(0, count($alf) - 1)];
        }
        return $s;
    }

    static public function generateUuid()
    {
        mt_srand((double)microtime() * 10000);
        $charid = strtolower(md5(uniqid(rand(), 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);
        return $uuid;
    }

    static public function rusDate($date, $time = false, $time_prefix = false, $with_year = false)
    {
        $a = array('01' => 'января', '02' => 'февраля', '03' => 'марта', '04' => 'апреля', '05' => 'мая', '06' => 'июня', '07' => 'июля', '08' => 'августа', '09' => 'сентября', '10' => 'октября', '11' => 'ноября', '12' => 'декабря',);
        $ex = explode(' ', $date);
        $timeex = explode(':', $ex[1]);
        $ex = explode('-', $ex[0]);
        $year = ($ex[0] != date('Y') ? ' ' . $ex[0] : '');
        if($with_year){
            $year = ' ' . $ex[0];
        }
        return intval($ex[2]) . ' ' . $a[$ex[1]] . $year . ($time ? ($time_prefix ? $time_prefix : ' ') . $timeex[0] . ':' . $timeex[1] : '');
    }

    static public function rusMonthR($date)
    {
        $a = array(
            '01' => 'январе',
            '02' => 'Феврале',
            '03' => 'марте',
            '04' => 'апреле',
            '05' => 'мае',
            '06' => 'июне',
            '07' => 'июле',
            '08' => 'августе',
            '09' => 'сентябре',
            '10' => 'октябре',
            '11' => 'ноябре',
            '12' => 'декабре',
        );

        $ex = explode(' ', $date);
        $ex = explode('-', $ex[0]);
        if ($only_month) {
            return $a[$ex[1]];
        }
        return $a[$ex[1]] . ($skip_year && $ex[0] == date('Y') ? '' : ' ' . $ex[0]);
    }

    static public function rusMonth($date, $skip_year = true, $only_month = false)
    {
        $a = array(
            '01' => 'Январь',
            '02' => 'Февраль',
            '03' => 'Март',
            '04' => 'Апрель',
            '05' => 'Май',
            '06' => 'Июнь',
            '07' => 'Июль',
            '08' => 'Август',
            '09' => 'Сентябрь',
            '10' => 'Октябрь',
            '11' => 'Ноябрь',
            '12' => 'Декабрь',
        );

        $ex = explode(' ', $date);
        $ex = explode('-', $ex[0]);
        if ($only_month) {
            return $a[$ex[1]];
        }
        return $a[$ex[1]] . ($skip_year && $ex[0] == date('Y') ? '' : ' ' . $ex[0]);
    }

    static public function rusMonthOnly($month)
    {
        $a = array(
            '1' => 'Январь',
            '2' => 'Февраль',
            '3' => 'Март',
            '4' => 'Апрель',
            '5' => 'Май',
            '6' => 'Июнь',
            '7' => 'Июль',
            '8' => 'Август',
            '9' => 'Сентябрь',
            '10' => 'Октябрь',
            '11' => 'Ноябрь',
            '12' => 'Декабрь',
        );

        return $a[$month];
    }

    static public function uploader($file, $key, $type/* = 'file' || 'url' || 'path'*/, $norename = false)
    {
        $upload_path = sfConfig::get('sf_upload_dir') . '/f/';
        $json = array('state' => 'error', 'errorTxt' => 'Not uploaded');
        if(in_array($type, array('file', 'url', 'path'))){
            if(!file_exists($upload_path)){
                mkdir($upload_path, 0750, true);
            }
            $file_exist = false;
            if ($type === 'url') {
                $this_file_dir = sfConfig::get('sf_upload_dir') . '/f/' . sha1($file);
                $get_file = ProjectUtils::get($file);
                if(!is_null($get_file)){
                    file_put_contents($this_file_dir, ProjectUtils::get($file));
                    $this_filename = basename($this_file_dir);
                    $file_exist = true;
                }
            }elseif($type === 'file') {
                if(file_exists($file['tmp_name'])){
                    $file_exist = true;
                    $this_file_dir = $file['tmp_name'];
                    $this_filename = $file['name'];
                }
            }elseif($type === 'path'){
                if(file_exists($file)){
                    $file_exist = true;
                    $this_file_dir = $file;
                    $this_filename = $this_file_dir;
                }
            }
            if ($file_exist) {
                $filename = $file;
                if($norename){
                    $name_arr = explode('.', basename($filename));
                    $name = $name_arr[0];
                }else{
                    $sha = ProjectUtils::generateUuid();
                    $sha_array = str_split($sha);
                    $filename = $upload_path;
                    foreach ($sha_array as $i => $dir) {
                        if ($i > 2) {
                            $filename .= mb_substr($sha, $i);
                            break;
                        }
                        if (!is_dir($filename . $dir)) {
                            mkdir($filename . $dir);
                        }
                        $filename .= $dir . '/';
                    }
                    $ext_post = strrpos($this_filename, '.');
                    $mime_type = mime_content_type($this_file_dir);
                    if($mime_type === 'application/octet-stream' && extension_loaded('gd') && extension_loaded('exif')){
                        $mime_type = image_type_to_mime_type(exif_imagetype($this_file_dir));
                    }

                    if(ProjectUtils::getType($mime_type)){
                        $ext = '.' . ProjectUtils::getType($mime_type);
                    }else{
                        $ext = strtolower(substr($this_filename, $ext_post));
                    }
                    $name = substr($this_filename, 0, $ext_post);
                    $filename_we = $filename;
                    $filename .= $ext;
                }
                if ($norename || rename($this_file_dir, $filename)) {
                    $json = array('state' => 'success', 'filename' => str_replace($upload_path, '', $filename), 'name' => $name, 'preview' => false);
                    $file_path = $filename;
                    $file_type = mime_content_type($file_path);
                    if($file_type === 'application/octet-stream' && extension_loaded('gd') && extension_loaded('exif')){
                        $file_type = image_type_to_mime_type(exif_imagetype($file_path));
                    }
                    if (in_array($file_type, array('application/pdf', 'application/x-download'))) {
                        /*
                        exec('pdftoppm ' . $file_path . ' ' . $file_path . '.ppm');
                        foreach(glob($file_path . '.ppm-*.ppm') as $ppm)
                        {
                          exec('ppmtojpeg --quality=80 ' . $ppm . ' > ' . $ppm . '.jpg');
                        }
                        $image_height = 0;
                        $image_width = 0;
                        foreach(glob($file_path . '.ppm-*.ppm.jpg') as $jpg)
                        {
                          $is = getimagesize($jpg);
                          $image_width = max(array($image_width, $is[0]));
                          $image_height += $is[1];
                        }

                        $image = new Imagick();
                        $pixel = new ImagickPixel( 'gray' );
                        $image->newImage($image_width, $image_height, $pixel);

                        $y = 0;
                        foreach(glob($file_path . '.ppm-*.ppm.jpg') as $jpg)
                        {
                          $jpgimage = new Imagick($jpg);
                          $image->compositeImage($jpgimage, Imagick::COMPOSITE_DEFAULT, 0, $y);
                          $y += $jpgimage->getImageHeight();
                        }
                        if($image_width > 1000)
                        {
                          $image->scaleImage(1000, 0);
                        }
                        $image->writeImage($file_path . '.jpg');
                        $json['preview'] = '<img src="/u/i/' . $filename . '.jpg" style="max-width:100%" />';
              */
                    } elseif (substr($file_type, 0, 5) == 'image') {
                        $is = $orig_is = getimagesize($file_path);
                        $prew = false;
                        if (is_array($cfg_sizes = sfConfig::get('image_' . $key . '_sizes'))) {
                            if(isset($cfg_sizes['min']) && isset($cfg_sizes['max']) && serialize($cfg_sizes['min']) === serialize($cfg_sizes['max']) && ($is[0] !== $cfg_sizes['min']['width'] || $is[1] !== $cfg_sizes['min']['height'])){
                                $error = 'Требуются размеры изображения ' . $cfg_sizes['min']['width'] . 'px * ' . $cfg_sizes['min']['height'] . 'px';
                                $json['state'] = $error;
                                $json['errorTxt'] = $error;
                                if($type === 'file'){
                                    unlink($filename);
                                }
                            } elseif ($is[0] < $cfg_sizes['min']['width'] || $is[1] < $cfg_sizes['min']['height']) {
                                $error = 'Слишком маленькое изображение (не менее ' . $cfg_sizes['min']['width'] . 'px * ' . $cfg_sizes['min']['height'] . 'px)';
                                $json['state'] = $error;
                                $json['errorTxt'] = $error;
                                if($type === 'file'){
                                    unlink($filename);
                                }
                            } elseif(isset($cfg_sizes['max']) && ($is[0] > $cfg_sizes['max']['width'] || $is[1] > $cfg_sizes['max']['height'])){
                                $error = 'Слишком большое изображение (не более ' . $cfg_sizes['max']['width'] . 'px * ' . $cfg_sizes['max']['height'] . 'px)';
                                $json['state'] = $error;
                                $json['errorTxt'] = $error;
                                if($type === 'file'){
                                    unlink($filename);
                                }
                            } else {
                                unset($cfg_sizes['min']);
                                foreach ($cfg_sizes as $sk => $sv) {
                                    $copy = !extension_loaded('imagick');
                                    if ($sv['thumbstyle'] == 'scale') {
                                        if ($orig_is[0] < $sv['width'] && $orig_is[1] < $sv['height']) {
                                            $copy = true;
                                        }
                                    } else {
                                        $max_key_cfg = $sv['width'] < $sv['height'] ? 'width' : 'height';
                                        $max_key = $sv['width'] < $sv['height'] ? '0' : '1';
                                        if ($orig_is[$max_key] < $sv[$max_key_cfg]) {
                                            $copy = true;
                                        }
                                    }
                                    if ($copy) {
                                        copy($filename, Page::replaceImageSize($filename, $sk));
                                    } else {
                                        $img = new sfImage($filename);
                                        $img->setQuality(100);
                                        $img->thumbnail($sv['width'], $sv['height'], $sv['thumbstyle']);
                                        @$img->saveAs(Page::replaceImageSize($filename, $sk), $file['type']);
                                    }
                                    if (isset($sv['watermark']) && $sv['watermark']) {
                                        Page::watermarkAdd(Page::replaceImageSize($filename, $sk));
                                    }
                                    if(isset($sv['gray']) && $sv['gray']){
                                        Page::grayAdd(Page::replaceImageSize($filename, $sk), $sk);
                                    }
                                    if (!$prew) {
                                        $json['preview'] = '<img src="/u/f/' . str_replace($upload_path, '', Page::replaceImageSize($filename, $sk)) . '" style="max-width:100%" />';
                                        $prew = true;
                                    }
                                }
                            }
                        } else {
                            $json['preview'] = '<img src="/u/f/' . str_replace($upload_path, '', $filename) . '" style="max-width:100%" />';
                        }

                        if (file_exists($filename)) {
                            chmod($filename, 0644);
                        }
                    } elseif ($ext == '.webm') {
                        $json['preview'] = '<video src="/u/f/' . str_replace($upload_path, '', $filename) . '" controls></video>';
                    }
                }
            }
        }
        return json_encode($json);
    }

    public function maskPhone($phone, $is_main = false)
    {
        $response = '';
        if($phone)
        {
            $arr = explode(',',$phone);
            if(count($arr) > 0){
                foreach ($arr as $key => $item){
                    $p = preg_replace("/[^,.0-9]/", '', $item);
                    if(strlen($p) == 11){
                        if($key > 0){
                            $response .= ', ';
                        }
                        if($is_main === false){
                            $response .= '+7 ' . '(' .  $p[1] . $p[2] . $p[3] . ') ' . $p[4] . $p[5] . $p[6] . ' ' .  $p[7]  . $p[8] . ' ' . $p[9] . $p[10];
                        } else {
                            $response .= '8 ' . '(' .  $p[1] . $p[2] . $p[3] . ') ' . $p[4] . $p[5] . $p[6] . ' ' .  $p[7]  . $p[8] . ' ' . $p[9] . $p[10];
                        }
                    }
                }
            }

            //$p = str_replace(" ","",$p);
            //$phone = '+' . $p[0] . ' ' . $p[1] . $p[2] . $p[3] . ' ' . $p[4] . $p[5] . ' ' . $p[6] . $p[7] . ' ' . $p[8] . $p[9] . $p[10];

            return $response;
        }
    }

    static function perfectPhone($str, $beauty = false)
    {
        if(!in_array(gettype($str), array('string', 'integer', 'double'))){
            return null;
        }
        $str = trim(strip_tags($str));
        if (strlen($str) > 0) {
            $phones = explode(',', $str);
            if(count($phones) > 0){
                $phones_result = array();
                foreach ($phones as $phone){
                    $phone_str = preg_replace('/[^0-9]/', '', $phone);
                    if (strlen($phone_str) == 11) {
                        if($beauty){
                            $phone_result = '+7&nbsp;(';
                            if((int)substr($phone_str, 1, 1) === 9){
                                $phone_result .= substr($phone_str, 1, 3) . ')&nbsp;' . substr($phone_str, 4, 3) . '-' . substr($phone_str, 7, 2) . '-' . substr($phone_str, 9, 2);
                            }else{
                                $phone_result .= substr($phone_str, 1, 4) . ')&nbsp;' . substr($phone_str, 5, 2) . '-' . substr($phone_str, 7, 2) . '-' . substr($phone_str, 9, 2);
                            }
                        }else{
                            $phone_result = '7' . substr($phone_str, 1);
                        }
                        $phones_result[] = $phone_result;
                    }
                }
                return count($phones_result) === 0 ? null : implode(',', $phones_result);
            }
        }
        return null;
    }

    static function watermarkAdd($image_src)
    {
        $image = new Imagick($image_src);
        $watermark = sfConfig::get('sf_web_dir') . '/i/watermark_small.png';
        $overlay = new Imagick($watermark);
        $image_size = getimagesize($image_src);
        $watermark_size = getimagesize($watermark);
        $padding = 10;
        $image->compositeimage($overlay, Imagick::COMPOSITE_DEFAULT, $image_size[0] - $padding - $watermark_size[0], $image_size[1] - $padding - $watermark_size[1]);
        $image->writeImage($image_src);
    }

    static function grayAdd($image_src, $key = false)
    {
        if($image_src){
            if(file_exists($image_src)){
                $gray_img = new Imagick($image_src);
                $gray_img->transformImageColorspace(Imagick::COLORSPACE_GRAY);
                $gray_img->writeImage($key ? Page::replaceImageSize($image_src, $key . '-gray-', $key) : Page::replaceImageSize($image_src, 'gray-'));
            }
        }
    }

    static function replaceImageSize($str, $need_size, $replace_size = false)
    {
        if ($replace_size) {
            $str = preg_replace("/(-" . $replace_size . ")\.(png|jpe?g|gif)$/u", ".$2", $str);
        }
        $str = preg_replace("/\.(png|jpe?g|gif)$/u", "-" . $need_size . ".$1", $str);
        return $str;
    }

    static function translit($string, $ya = false)
    {

        /*
        $a = array(
            'ый' => 'iy',
            'ий' => 'iy',
            'ъе' => 'ye',
            'ё' => 'yo',
            'Ё' => 'Yo',
            'х' => 'kh',
            'Х' => 'Kh',
            'ц' => 'Ts',
            'Ц' => 'Ts',
            'ц' => 'Ts',
            'Ц' => 'Ts',
        );
        */

        $converter = array(
            'а' => 'a',   'б' => 'b',   'в' => 'v',
            'г' => 'g',   'д' => 'd',   'е' => 'e',
            'ё' => 'e',   'ж' => 'zh',  'з' => 'z',
            'и' => 'i',   'й' => 'y',   'к' => 'k',

            'л' => 'l',   'м' => 'm',   'н' => 'n',
            'о' => 'o',   'п' => 'p',   'р' => 'r',
            'с' => 's',   'т' => 't',   'у' => 'u',

            'ф' => 'f',   'х' => 'h',   'ц' => 'c',
            'ч' => 'ch',  'ш' => 'sh',  'щ' => 'sch',
            'ь' => '',    'ы' => 'y',   'ъ' => '',
            'э' => 'e',   'ю' => 'yu',  'я' => 'ya',

            'А' => 'A',   'Б' => 'B',   'В' => 'V',
            'Г' => 'G',   'Д' => 'D',   'Е' => 'E',

            'Ё' => 'E',   'Ж' => 'Zh',  'З' => 'Z',
            'И' => 'I',   'Й' => 'Y',   'К' => 'K',
            'Л' => 'L',   'М' => 'M',   'Н' => 'N',

            'О' => 'O',   'П' => 'P',   'Р' => 'R',
            'С' => 'S',   'Т' => 'T',   'У' => 'U',
            'Ф' => 'F',   'Х' => 'H',   'Ц' => 'C',

            'Ч' => 'Ch',  'Ш' => 'Sh',  'Щ' => 'Sch',
            'Ь' => '',    'Ы' => 'Y',   'Ъ' => '',
            'Э' => 'E',   'Ю' => 'Yu',  'Я' => 'Ya',

            ' ' => '-',   '#' => '',    '"' => '',
            '.' => '',    '+' => '-',   ',' => '',
            '!' => '',    '?' => '',    '/' => '-',
            '\\' =>'',    '\'' => '',   '&' => '_',
            '(' => '',    ')' => ''
        );
        return strtolower(strtr(trim($string), $converter));
    }
    static public function strCut($str, $max, $postfix = false)
    {
        if (mb_strlen($str) <= $max) {
            return $str;
        } else {
            $exp = explode(' ', $str);
            $res = '';
            for ($i = 0; $i < count($exp); $i++) {
                $length = $res . ($res != '' ? ' ' : '') . $exp[$i];
                if (mb_strlen($length) <= $max) {
                    $res .= ' ' . $exp[$i];
                } else {
                    if (substr($res, -1) == ',') {
                        $res = substr($res, 0, -1);
                    }
                    $res .= ($postfix === false ? '...' : $postfix);
                    break;
                }
            }
            return $res;
        }
    }

    static function generateCode($max)
    {
        $code = '';
        while ($max--) {
            $code .= rand(0, 9);
        }
        return $code;
    }
    static public function timeline($sec, $format = '%h% ч %m% мин %s% сек')
    {
        if(!is_int($sec) || $sec <= 0){
            return;
        }
        $hour = (int)($sec / 3600);
        $min = (int)($sec / 60) % 60;
        $sec = $sec % 60;

        $result = $format;
        foreach (array('h' => $hour, 'm' => $min, 's' => $sec) as $key => $item){
            $result = str_replace('%' . $key . '%', $item, $result);
        }
        return $result;
    }
}
