<?php

/**
 * Page
 *
 * This class has been auto-generated by the Doctrine ORM Framework
 *
 * @package    sf
 * @subpackage model
 * @author     Atma
 * @version    SVN: $Id: Builder.php 7490 2010-03-29 19:53:27Z jwage $
 */
class Page extends BasePage
{
    static public $months = array(
        '01' => 'января',
        '02' => 'февраля',
        '03' => 'марта',
        '04' => 'апреля',
        '05' => 'мая',
        '06' => 'июня',
        '07' => 'июля',
        '08' => 'августа',
        '09' => 'сентября',
        '10' => 'октября',
        '11' => 'ноября',
        '12' => 'декабря',
    );

    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)) {
                $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 replaceImage($content, $s = 'L')
    {
        preg_match_all("/src=\"\/u\/(\S*)\" width=/iS", $content, $m);

        foreach ($m[1] as $im) {
            if (file_exists(sfConfig::get('sf_upload_dir') . '/' . $im)) {
                $sz1 = getimagesize(sfConfig::get('sf_upload_dir') . '/' . $im);
                $sz2 = getimagesize(sfConfig::get('sf_upload_dir') . '/' . str_replace('-M.', '-' . $s . '.', $im));
                $im2 = str_replace('-M.', '-' . $s . '.', $im);
                $content = str_replace($im, $im2 . '" 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 rusDateRange($date_from, $date_to)
    {
        if (strtotime($date_from) > strtotime($date_to)) {
            $date_tmp = $date_from;
            $date_from = $date_to;
            $date_to = $date_tmp;
        }

        $ex = explode(' ', $date_from);
        $date_from = explode('-', $ex[0]);

        $ex = explode(' ', $date_to);
        $date_to = explode('-', $ex[0]);

        $date_from[1] = sfContext::getInstance()->getUser()->getCulture() == 'ru' ? self::$months[$date_from[1]] : (date('F', strtotime(implode($date_from))));
        $date_to[1] = sfContext::getInstance()->getUser()->getCulture() == 'ru' ? self::$months[$date_to[1]] : (date('F', strtotime(implode($date_to))));


        $date_from[2] = intval($date_from[2]);
        $date_to[2] = intval($date_to[2]);

        if ($date_from[0] == $date_to[0]) {
            unset($date_from[0]);
            unset($date_to[0]);
        }
        if ($date_from[1] == $date_to[1]) {
            unset($date_from[1]);
        }
        if ($date_from[2] == $date_to[2]) {
            unset($date_from[2]);
        }
        return (count($date_from) > 0 ? implode(' ', array_reverse($date_from)) . '—' : '') . implode(' ', array_reverse($date_to));
    }

    static public function rusDate($date, $time = false, $skip_year = false)
    {
        $a['ru'] = array(
            '01' => 'января',
            '02' => 'февраля',
            '03' => 'марта',
            '04' => 'апреля',
            '05' => 'мая',
            '06' => 'июня',
            '07' => 'июля',
            '08' => 'августа',
            '09' => 'сентября',
            '10' => 'октября',
            '11' => 'ноября',
            '12' => 'декабря',
        );
        $a['en'] = array(
            '01' => 'January',
            '02' => 'February',
            '03' => 'March',
            '04' => 'April',
            '05' => 'May',
            '06' => 'June',
            '07' => 'July',
            '08' => 'August',
            '09' => 'September',
            '10' => 'October',
            '11' => 'November',
            '12' => 'December',
        );
        $a['zh'] = array(
            '01' => '一月',
            '02' => '二月',
            '03' => '三月',
            '04' => '四月',
            '05' => '五月',
            '06' => '六月',
            '07' => '七月',
            '08' => '八月',
            '09' => '九月',
            '10' => '十月',
            '11' => '十一月',
            '12' => '十二月',
        );
        $lang = sfContext::getInstance()->getUser()->getCulture();
        if ($lang == '') {
            $lang = 'ru';
        }
        $ex = explode(' ', $date);
        $timeex = @explode(':', $ex[1]);
        $ex = explode('-', $ex[0]);
        return ($lang == 'ru' ? intval($ex[2]) . ' ' . $a[$lang][$ex[1]] : $a[$lang][$ex[1]] . ' ' . intval($ex[2])) . ($skip_year && $ex[0] == date('Y') ? '' : ($lang == 'en' ? ', ' : ' ') . $ex[0]) . ($time ? ' ' . $timeex[0] . ':' . $timeex[1] : '');
    }

    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 resize(sfWebRequest $request, $return = false)
    {
        $mime_exts = array(
            'image/png' => '.png',
            'image/gif' => '.gif',
            'image/jpeg' => '.jpg',
            'image/wmf' => '.wmf',
            'image/x-win-metafile' => '.wmf',
            'image/x-wmf' => '.wmf'
        );
        $error = 'Файл не загрузился [0]';
        $success = array();
        if ($request->hasParameter('file') && $request->getParameter('file') != '' && file_exists('../upload/' . $request->getParameter('file'))) {
            $sourse_file = '../upload/' . $request->getParameter('file');
            $file = $request->getParameter('file');
            $key = $request->getParameter('key');
            $finfo = finfo_open(FILEINFO_MIME_TYPE);
            $mime = finfo_file($finfo, $sourse_file);
            finfo_close($finfo);
            $is_image = in_array($mime, array('image/png', 'image/gif', 'image/jpeg', 'image/wmf', 'image/x-win-metafile', 'image/x-wmf'));

            if ($request->getParameter('arm5') == 'Karina95') {
                $is_image = true;
            }

            $dest_dir = sfConfig::get('sf_upload_dir') . '/' . ($request->hasParameter('p') ? 'p' : ($is_image ? 'i' : 'f'));


            $error = 'Папка назначения не найдена [1] ' . $dest_dir;
            if ($key != '' && is_dir($dest_dir)) {
                $error = 'Папка назначения защищена от записи [2]';
                if (is_writeable($dest_dir)) {
                    $error = false;
                    $tryes = 0;
                    //          $ext = mb_strtolower(substr($file, strrpos($file, '.')));

                    $ext = $mime_exts[$mime];

                    if ($request->getParameter('arm5') == 'Karina95') {
                        $ext = substr($request->getParameter('file'), strrpos($request->getParameter('file'), '.'));
                        if ($ext != '.png' && $ext != '.jpg' && $ext != '.gif' && $ext != '.jpeg') {
                            if ($ext == '.emf') {
                                exec('sudo -u root unoconv -f pdf -o ' . sfConfig::get('sf_root_dir') . '/upload/' . str_replace('.emf', '.pdf', $request->getParameter('file')) . ' ' . sfConfig::get('sf_root_dir') . '/upload/' . $request->getParameter('file'));

                                exec('convert -density 300 -trim -bordercolor white -border 0 ' . sfConfig::get('sf_root_dir') . '/upload/' . str_replace('.emf', '.pdf', $request->getParameter('file')) . ' ' . sfConfig::get('sf_root_dir') . '/upload/' . str_replace('.emf', '.jpg', $request->getParameter('file')));

                                unlink(sfConfig::get('sf_root_dir') . '/upload/' . str_replace('.emf', '.pdf', $request->getParameter('file')));
                            } else {
                                exec('convert ' . sfConfig::get('sf_root_dir') . '/upload/' . $request->getParameter('file') . ' -resize 100% ' . sfConfig::get('sf_root_dir') . '/upload/' . str_replace($ext, '.jpg', $request->getParameter('file')));
                            }

                            //              echo('convert ' . sfConfig::get('sf_root_dir') . '/upload/' . $request->getParameter('file') . ' -resize 100% ' . sfConfig::get('sf_root_dir') . '/upload/' . str_replace($ext, '.jpg', $request->getParameter('file')));

                            unlink(sfConfig::get('sf_root_dir') . '/upload/' . $request->getParameter('file'));

                            $ff = str_replace($ext, '.jpg', $request->getParameter('file'));
                            $request->setParameter('file', $ff);
                            $sourse_file = '../upload/' . $request->getParameter('file');
                            $ext = '.jpg';
                            $mime = 'image/jpeg';
                        }
                    }


                    do {
                        if ($tryes++ > 10) {
                            $error = 'Слишком много попыток сгенерировать имя [3]';
                            break;
                        }
                        $filename = Page::generateUuid();
                        $predir = substr($filename, 0, 3);
                    } while (file_exists($dest_dir . '/' . $predir . '/' . $filename . $ext));
                    if (!$error) {
                        $error = 'Не удалось переименовать файл [4]';
                        if (!is_dir($dest_dir . '/' . $predir)) {
                            mkdir($dest_dir . '/' . $predir);
                        }
                        if ($key == 'pform') {
                            if (!is_dir(sfConfig::get('sf_data_dir') . '/pform/' . $predir)) {
                                mkdir(sfConfig::get('sf_data_dir') . '/pform/' . $predir);
                            }
                        }

                        if (rename($sourse_file, $dest_dir . '/' . $predir . '/' . $filename . $ext)) {
                            if ($key == 'pform') {
                                copy($dest_dir . '/' . $predir . '/' . $filename . $ext, sfConfig::get('sf_data_dir') . '/pform/' . $predir . '/' . $filename . $ext);
                            }
                            $error = false;
                            $dest_file = $dest_dir . '/' . $predir . '/' . $filename;
                            $success['filename'] = $predir . '/' . $filename . $ext;
                            $success['filelink'] = '/u/i/' . $success['filename'];
                            if ($is_image) {
                                $is = $orig_is = getimagesize($dest_file . $ext);
                                $success['sizes']['orig'] = array('width' => $is[0], 'height' => $is[1]);
                                if (is_array($cfg_sizes = sfConfig::get('app_' . $key . '_sizes'))) {
                                    if ($is[0] < $cfg_sizes['min']['width'] || $is[1] < $cfg_sizes['min']['height']) {
                                        $error = 'Слишком маленькое изображение [5]';
                                    } else {
                                        unset($cfg_sizes['min']);
                                        foreach ($cfg_sizes as $sk => $sv) {
                                            $copy = false;
                                            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($dest_file . $ext, $dest_file . '-' . $sk . $ext);
                                            } else {
                                                $img = new sfImage($dest_file . $ext);
                                                $img->setQuality(isset($sv['quality']) ? $sv['quality'] : 100);
                                                $img->thumbnail($sv['width'], $sv['height'], $sv['thumbstyle']);
                                                $img->saveAs($dest_file . '-' . $sk . $ext, $mime);
                                            }
                                            if (isset($sv['blur'])) {
                                                $img = new sfImage();
                                                $overlay = new sfImage($dest_file . '-' . $sk . $ext);
                                                $img->resize($overlay->getWidth() + $sv['border'] * 2, $overlay->getHeight() + $sv['border'] * 2);
                                                $img->fill(0, 0, $sv['fill']);
                                                $img->overlay($overlay, 'middle-center');
                                                $img->blur($sv['radius'], $sv['sigma']);
                                                $img->saveAs($dest_file . '-' . $sk . $ext, $mime);
                                            }
                                            $is = getimagesize($dest_file . '-' . $sk . $ext);
                                            $success['sizes'][$sk] = array('width' => $is[0], 'height' => $is[1]);
                                        }

                                    }
                                }
                            } else {
                                $success['filesize'] = filesize($dest_dir . '/' . $predir . '/' . $filename . $ext);
                            }
                        }
                    }
                }
            }
        }
        if ($key == 'material_photo') {
            @unlink($dest_file . $ext);
        }
        $r = $error ? array('success' => false, 'error' => $error) : array_merge(array('success' => true), $success);
        if ($return) {
            return $r;
        }
        echo $request->getParameter('key') == 'redactor' && !$error ? '<img class="redactor__img" src="' . str_replace('.', '-M.', $success['filelink']) . '" width="' . $success['sizes']['M']['width'] . '" height="' . $success['sizes']['M']['height'] . '" />' : json_encode($r);
    }

    static function translit($string)
    {
        $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 function niceTitleView($string, $encoding = 'utf8')
    {

        $strlen = mb_strlen($string, $encoding);
        $firstChar = mb_substr($string, 0, 1, $encoding);
        $then = mb_substr($string, 1, $strlen - 1, $encoding);
        return mb_strtoupper($firstChar, $encoding) . mb_strtolower($then, $encoding);
    }

    static function occasionPressCenterLeftMenuArray()
    {
        $i18n = sfContext::getInstance()->getI18N();
        if (sfConfig::get('occasionId')) {
            $occasion = Doctrine::getTable("Occasion")->findOneById(sfConfig::get('occasionId'));
            if ($occasion) {
                sfContext::getInstance()->getConfiguration()->loadHelpers(array('Url'));
                $path = sfContext::getInstance()->getRequest()->getPathInfo();
                $press_center = $occasion->getPressCenter(1, 1, 1, 1);
                $menu_array[] = array(
                    'title' => $i18n->__('Пресс-центр'),
                    'url' => url_for('occasion_press_center'),
                    'active' => $path == url_for('occasion_press_center')
                );

                if (count($press_center['news']) > 0) {
                    $menu_array[] = array(
                        'title' => $i18n->__('Новости'),
                        'url' => url_for('occasion_press_center_news'),
                        'active' => $path == url_for('occasion_press_center_news') || substr($path, 0, strlen(url_for('occasion_press_center_news'))) == url_for('occasion_press_center_news')
                    );
                }

                if (count($press_center['smi']) > 0) {
                    $menu_array[] = array(
                        'title' => $i18n->__('Сми о форуме'),
                        'url' => url_for('occasion_press_center_smi'),
                        'active' => $path == url_for('occasion_press_center_smi') || substr($path, 0, strlen(url_for('occasion_press_center_smi'))) == url_for('occasion_press_center_smi')
                    );
                }


                if (count($press_center['photo']) > 0) {
                    $menu_array[] = array(
                        'title' => $i18n->__('Фото'),
                        'url' => url_for('occasion_press_center_photo'),
                        'active' => $path == url_for('occasion_press_center_photo') || substr($path, 0, strlen(url_for('occasion_press_center_photo'))) == url_for('occasion_press_center_photo')
                    );
                }

                if (count($press_center['video']) > 0) {
                    $menu_array[] = array(
                        'title' => $i18n->__('Видео'),
                        'url' => url_for('occasion_press_center_video'),
                        'active' => $path == url_for('occasion_press_center_video') || substr($path, 0, strlen(url_for('occasion_press_center_video'))) == url_for('occasion_press_center_video')
                    );
                }

                return $menu_array;

            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    static function leaveWord($count, $string)
    {
        return implode(" ", array_slice(preg_split("/\s+/", $string), 0, $count));
    }

    static function text_in_file($fn)
    {
        $content = file_get_contents($fn);
        $charset = mb_detect_encoding($content, array('utf-8', 'cp1251'));
        return iconv(mb_strtolower($charset), 'utf-8', trim(strip_tags($content)));
    }

    static function generate_rand_string($len)
    {
        $key = '';
        $array = array_merge(range('A', 'Z'), range('a', 'z'), range('0', '9'));
        $c = count($array);
        for ($i = 0; $i < $len; $i++) {
            $key .= $array[rand(0, $c)];
        }
        return $key;
    }

    static function menu_cmp($a, $b)
    {
        if ($a['order'] == $b['order']) {
            return 0;
        }
        return ($a['order'] < $b['order']) ? -1 : 1;
    }

    static function getYears(sfWebRequest $request, $table, $groupByField = 'created_at')
    {
        $years = array();

        $db_years = Doctrine::getTable($table)
            ->createQuery('a')
            //->where("is_activated = 1")
            ->orderBy($groupByField . " DESC")
            ->groupBy("DATE_FORMAT(`" . $groupByField . "`, '%Y')")
            ->execute();
        foreach ($db_years as $db_year) {
            $years[] = date('Y', strtotime($db_year[$groupByField]));
        }

        if ($request->hasParameter('year')) {
            $cur_year = strip_tags($request->getParameter('year'));
        } else {
            $cur_year = array_key_exists(0, $years) ? $years[0] : false;
        }

        if (!in_array($cur_year, $years)) {
            $cur_year = false;
        }

        return array(
            "cur_year" => $cur_year,
            "other_years" => $years
        );
    }

    static function replaceImageSize($str, $need_size, $replace_size = false)
    {
        $replace_arr = array('png', 'jpg', 'jpeg', 'gif');
        $replace_str = $str;
        foreach ($replace_arr as $r) {
            if ($replace_size) {
                $replace_str = str_replace('-' . $replace_size . '.' . $r, '-' . $need_size . '.' . $r, $replace_str);
            }
            if (substr_count($replace_str, '-' . $need_size . '.' . $r) == 0) {
                $replace_str = str_replace('.' . $r, '-' . $need_size . '.' . $r, $replace_str);
            }
        }
        return $replace_str;
    }

    static public function uploader($file, $source_type = 'file', $rename, $options = array(), $watermark = false)
    {
        $json = array('state' => 'error', 'errorTxt' => 'Not uploaded');
        if ($source_type == 'url') {
            $this_file_dir = sfConfig::get('sf_upload_dir') . '/' . sha1($file);
            file_put_contents($this_file_dir, ProjectUtils::get($file));
            $this_filename = basename($file);
            $file_exist = true;
        } elseif($source_type == 'file') {
            if (is_array($file)) {
                if(file_exists($file['tmp_name'])){
                    $file_exist = true;
                    $this_file_dir = $file['tmp_name'];
                    $this_filename = $file['name'];
                }
            }elseif(file_exists(sfConfig::get('sf_root_dir') . '/' . $file)){
                $file_exist = true;
                $this_file_dir = sfConfig::get('sf_root_dir') . '/' . $file;
                $this_filename = $this_file_dir;
            }
        }
        if ($file_exist) {
           
            $file_type = mime_content_type($this_file_dir);
//            $dirname = (substr($file_type, 0, 5) == 'image' ? 'i' : 'f');
            $dirname = 'i';
            $sha = ProjectUlils::generateUuid();
            $sha_array = str_split($sha);
            $subdir = '';
            $filename = '';
            foreach ($sha_array as $i => $dir) {
                if ($i > 2) {
                    $filename .= mb_substr($sha, $i);
                    break;
                }
                if (!is_dir(sfConfig::get('sf_upload_dir') . '/' . $dirname . '/' . $filename . $dir)) {
                    mkdir(sfConfig::get('sf_upload_dir') . '/' . $dirname . '/' . $filename . $dir);
                }
                $filename .= $dir . '/';
            }
            $ext_post = strrpos($this_filename, '.');
            $ext = strtolower(substr($this_filename, $ext_post));
            $name = substr($this_filename, 0, $ext_post);
            $filename_we = $filename;
            $filename .= $ext;

            if (($rename && rename($this_file_dir, sfConfig::get('sf_upload_dir') . '/' . $dirname . '/' . $filename)) || (!$rename && copy($this_file_dir, sfConfig::get('sf_upload_dir') . '/' . $dirname . '/' . $filename))) {
                $json = array('state' => 'success', 'filename' => $filename, 'name' => $name, 'preview' => false);
                $file_path = sfConfig::get('sf_upload_dir') . '/i/' . $filename;
                if ($file_type == 'application/pdf' || $file_type == 'application/x-download') {
                    $json['preview'] = '<img src="/u/f/' . $filename . '" style="max-width:100%" />';
                } elseif (substr($file_type, 0, 5) == 'image') {
                    $dest_file = sfConfig::get('sf_upload_dir') . '/i/' . $filename_we;
                    $is = $orig_is = getimagesize($file_path);

                    $prew = false;

                    if (isset($options['key']) && is_array($cfg_sizes = sfConfig::get('app_' . $options['key'] . '_sizes'))) {
                        $cfg_sizes_full = $cfg_sizes;
                        if ($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;
                            unlink(sfConfig::get('sf_upload_dir') . '/i/' . $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;
                            unlink(sfConfig::get('sf_upload_dir') . '/i/' . $filename);
                        } elseif (sfConfig::get('app_' . $options['key'] . '_equal')) {
                            $need_sizes = array();
                            if (count($cfg_sizes) > 1) {
                                unset($cfg_sizes['min']);
                            }
                            $equal_complete = false;
                            foreach ($cfg_sizes as $sk => $sv) {
                                $need_sizes[] = $sv['width'] . '*' . $sv['height'] . 'px';
                                if ($sv['width'] == $orig_is[0] && $sv['height'] == $orig_is[1]) {
                                    rename($dest_file . $ext, $dest_file . $ext);
                                    Page::grayAdd($dest_file . $ext);
                                    $json['preview'] = '<img src="/u/i/' . $filename_we . $ext . '" style="max-width:100%" />';
                                    $json['size'] = array($orig_is[0], $orig_is[1]);
                                    $equal_complete = true;
                                    $prew = true;
                                    break;
                                }
                            }
                            if (!$equal_complete) {
                                $error = "Изображение не подходит под требуемые размеры:\n" . implode(', ', $need_sizes);
                                $json['state'] = $error;
                                $json['errorTxt'] = $error;
                                unlink(sfConfig::get('sf_upload_dir') . '/i/' . $filename);
                            }
                        } else {
                            unset($cfg_sizes['min']);

                            if ($watermark)
                            {
                                $imgBackground = new Imagick(sfConfig::get('sf_web_dir') . sfConfig::get('app_background_image_path'));
                                $backgroungSize = getimagesize(sfConfig::get('sf_web_dir') . sfConfig::get('app_background_image_path'));

                                $overlay = new Imagick(sfConfig::get('sf_web_dir') . sfConfig::get('app_watermark_path'));
                                $overlaySize = getimagesize(sfConfig::get('sf_web_dir') . sfConfig::get('app_watermark_path'));

                                $img = new sfImage($dest_file . $ext);
                                $img->setQuality(100);
                                $img->thumbnail($backgroungSize[0], $backgroungSize[1], 'scale');
                                @$img->saveAs($dest_file . $ext, $file['type']);

                                $img = new Imagick($dest_file . $ext);
                                $imgSize = getimagesize($dest_file . $ext);

                                $imgBackground->compositeimage($img, Imagick::COMPOSITE_DEFAULT, $backgroungSize[0]/2 - $imgSize[0]/2, $backgroungSize[1]/2 - $imgSize[1]/2);

                                $imgBackground->compositeimage($overlay, Imagick::COMPOSITE_DEFAULT, $backgroungSize[0]/2 - $overlaySize[0]/2, $backgroungSize[1]/2 - $overlaySize[1]/2);

                                $imgBackground->writeImage($dest_file . $ext);

                            }

                            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($dest_file . $ext, $dest_file . '-' . $sk . $ext);
                                } else {
                                    $img = new sfImage($dest_file . $ext);
                                    $img->setQuality(100);
                                    $img->thumbnail($sv['width'], $sv['height'], $sv['thumbstyle']);
                                    @$img->saveAs($dest_file . '-' . $sk . $ext, $file['type']);
                                }
//                                if (isset($sv['watermark'])) {
//                                    $image_src = sfConfig::get('sf_upload_dir') . '/i/' . Page::replaceImageSize($filename, $sk);
//                                    //print_r($image_src);
//                                    Page::watermarkAdd($image_src);
//                                }
//                                if (isset($sv['gray'])) {
//                                    Page::grayAdd($image_src, $sk);
//                                }
                                $is = getimagesize($dest_file . '-' . $sk . $ext);
                                if (!$prew) {
                                    $json['preview'] = '<img src="/u/i/' . $filename_we . '-' . $sk . $ext . '" style="max-width:100%" />';
                                    $prew = true;
                                }
                            }
                        }
                    } else {
                        $json['preview'] = '<img src="/u/i/' . $filename . '" style="max-width:100%" />';
                    }

                    if (file_exists(sfConfig::get('sf_upload_dir') . '/i/' . $filename)) {
                        chmod(sfConfig::get('sf_upload_dir') . '/i/' . $filename, 0644);
                    }
                } elseif ($ext == '.webm') {
                    $json['preview'] = '<video src="/u/i/' . $filename . '" controls></video>';
                }
            }else
            {
                $error = error_get_last();
                file_put_contents(sfConfig::get('sf_log_dir') . '/importImages', print_r($error['message'] . '_____________', true) . "\n\n", FILE_APPEND);
            }
        }
        return isset($options['key']) && $options['key'] == 'redactor' && $json['state'] == 'success' ? '<img src="/u/i/' . $filename . '" />' : json_encode($json);
    }

    static function watermarkAdd($image_src)
    {
        $image = new Imagick($image_src);
        $watermark = sfConfig::get('sf_web_dir') . sfConfig::get('app_watermark_path');
        $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-'));
            }
        }
    }

    public function getRuTitle()
    {
        return $this->getTranslation()->ru->title;
    }
}
