<?php
/**
 * Created by PhpStorm.
 * User: yakov
 * Date: 11.04.18
 * Time: 15:55
 */
class exchangeDeleteimageTask extends sfBaseTask
{
    protected function configure()
    {
        $this->addOptions(array(
            new sfCommandOption('application', null, sfCommandOption::PARAMETER_REQUIRED, 'The application name', 'www'),
            new sfCommandOption('env', null, sfCommandOption::PARAMETER_REQUIRED, 'The environment', 'arm'),
            new sfCommandOption('connection', null, sfCommandOption::PARAMETER_REQUIRED, 'The connection name', 'doctrine'),
            // add your own options here
        ));

        $this->namespace = 'exchange';
        $this->name = 'deleteimage';

    }

    protected function execute($arguments = array(), $options = array())
    {
        $time_start = microtime(true);

        $databaseManager = new sfDatabaseManager($this->configuration);
        $connection = $databaseManager->getDatabase($options['connection'])->getConnection();

        $instance = sfContext::createInstance($this->configuration);

        $allImage = array();
        $key = 0;

        $productImage = Doctrine_Query::create()
            ->select('product_img')
            ->from('Product')
            ->fetchArray();

        foreach ($productImage as $product) {
            $arr = explode(';', $product['product_img']);
            if (count($arr) > 0) {
                foreach ($arr as $image) {
                    if (strlen($image) > 2) {
                        $allImage[$key] = sfConfig::get('sf_web_dir') . '/u/i/' . $image;
                        $key++;
                        $sizes = sfConfig::get('app_product_sizes');
                        unset($sizes['min']);
                        foreach ($sizes as $namesize => $size) {
                            $allImage[$key] = sfConfig::get('sf_web_dir') . '/u/i/' . str_replace('.','-' . $namesize . '.', $image);
                            $key++;
                        }
                    }
                }
            }
        }
        unset($productImage);


        $catImage = Doctrine_Query::create()
            ->select('c.photo')
            ->from('Cat c')
            ->fetchArray();

        foreach ($catImage as $cat) {
            if (strlen($cat['photo']) > 2) {
                $allImage[$key] = sfConfig::get('sf_web_dir') . '/u/i/' . $cat['photo'];
                $key++;
                $sizes = sfConfig::get('app_cat_sizes');
                unset($sizes['min']);
                foreach ($sizes as $namesize => $size) {
                    $allImage[$key] = sfConfig::get('sf_web_dir') . '/u/i/' . str_replace('.','-' . $namesize . '.', $cat['photo']);
                    $key++;
                }
            }
        }
        unset($catImage);


        $offerImage = Doctrine_Query::create()
            ->select('o.img')
            ->from('Offer o')
            ->fetchArray();

        foreach ($offerImage as $offer) {
            if (strlen($offer['img']) > 2) {
                $allImage[$key] = sfConfig::get('sf_web_dir') . '/u/i/' . $offer['img'];
                $key++;
                $sizes = sfConfig::get('app_product_sizes');
                unset($sizes['min']);
                foreach ($sizes as $namesize => $size) {
                    $allImage[$key] = sfConfig::get('sf_web_dir') . '/u/i/' . str_replace('.','-' . $namesize . '.', $offer['img']);
                    $key++;
                }
            }
        }
        unset($offerImage);


        $partnersImage = Doctrine_Query::create()
            ->select('cover')
            ->from('Partners')
            ->fetchArray();

        foreach ($partnersImage as $partner) {
            if (strlen($partner['cover']) > 2) {
                $allImage[$key] = sfConfig::get('sf_web_dir') . '/u/i/' . $partner['cover'];
                $key++;
                $sizes = sfConfig::get('app_partner_sizes');
                unset($sizes['min']);
                foreach ($sizes as $namesize => $size) {
                    $allImage[$key] = sfConfig::get('sf_web_dir') . '/u/i/' . str_replace('.','-' . $namesize . '.', $partner['cover']);
                    $key++;
                }
            }
        }
        unset($partnersImage);


        $reviewImage = Doctrine_Query::create()
            ->select('file')
            ->from('Review')
            ->fetchArray();

        foreach ($reviewImage as $review) {
            if (strlen($review['file']) > 2) {
                $allImage[$key] = sfConfig::get('sf_web_dir') . '/u/i/' . $review['file'];
                $key++;
                $sizes = sfConfig::get('app_review_sizes');
                unset($sizes['min']);
                foreach ($sizes as $namesize => $size) {
                    $allImage[$key] = sfConfig::get('sf_web_dir') . '/u/i/' . str_replace('.','-' . $namesize . '.', $review['file']);
                    $key++;
                }
            }
        }
        unset($reviewImage);


        $videoImage = Doctrine_Query::create()
            ->select('cover')
            ->from('Video')
            ->fetchArray();

        foreach ($videoImage as $video) {
            if (strlen($video['cover']) > 2) {
                $allImage[$key] = sfConfig::get('sf_web_dir') . '/u/i/' . $video['cover'];
                $key++;
                $sizes = sfConfig::get('app_video_sizes');
                unset($sizes['min']);
                foreach ($sizes as $namesize => $size) {
                    $allImage[$key] = sfConfig::get('sf_web_dir') . '/u/i/' . str_replace('.','-' . $namesize . '.', $video['cover']);
                    $key++;
                }
            }
        }
        unset($videoImage);


        $articleImage = Doctrine_Query::create()
            ->select('a.cover, at.body')
            ->from('Article a')
            ->leftJoin('a.Translation at')
            ->fetchArray();

        foreach ($articleImage as $article) {
            if (strlen($article['cover']) > 2) {
                $allImage[$key] = sfConfig::get('sf_web_dir') . '/u/i/' . $article['cover'];
                $key++;
                $sizes = sfConfig::get('app_article_sizes');
                unset($sizes['min']);
                foreach ($sizes as $namesize => $size) {
                    $allImage[$key] = sfConfig::get('sf_web_dir') . '/u/i/' . str_replace('.','-' . $namesize . '.', $article['cover']);
                    $key++;
                }
            }
            $imageInBody = $this->findImageInStr($article['Translation']['ru']['body']);
            $imageInBody .= $this->findImageInStr($article['Translation']['en']['body']);
            if (strlen($imageInBody) > 2) {
                $arrayBodyImage = explode(';', $imageInBody);
                foreach ($arrayBodyImage as $image) {
                    if (strlen($image) > 2) {
                        $allImage[$key] = sfConfig::get('sf_web_dir') . '/u/i/' . $image;
                        $key++;
                    }
                }
            }
        }
        unset($articleImage);


        $pageImage = Doctrine_Query::create()
            ->select('p.id, pt.body')
            ->from('Page p')
            ->leftJoin('p.Translation pt')
            ->fetchArray();

        foreach ($pageImage as $page) {
            $imageInBody = $this->findImageInStr($page['Translation']['ru']['body']);
            $imageInBody .= $this->findImageInStr($page['Translation']['en']['body']);
            if (strlen($imageInBody) > 2) {
                $arrayBodyImage = explode(';', $imageInBody);
                foreach ($arrayBodyImage as $image) {
                    if (strlen($image) > 2) {
                        $allImage[$key] = sfConfig::get('sf_web_dir') . '/u/i/' . $image;
                        $key++;
                    }
                }
            }
        }
        $allImageInDir = explode(';', $this->removeImage(sfConfig::get('sf_web_dir') . '/u/i'));

        $notFind = array();
        foreach ($allImage as $item) {
            $searchKey = array_search($item, $allImageInDir);
            if ($searchKey) {
                unset($allImageInDir[$searchKey]);
            }else {
                $notFind[] = $item;
            }
        }
        $error = array();
        $countDel = 0;
        foreach ($allImageInDir as $item) {
            if (file_exists($item)) {
                chmod($item, 0777);
                unlink($item);
                $countDel++;
            }else {
                $error[] = 'file not found:' . $item;
            }
        }

        print_r($allImageInDir);
        $this->log('Count delete image: ' . $countDel);
        $this->log('Image delete done: [' . round((microtime(true) - $time_start) * 1000) . ' ms]');
    }

    function findImageInStr($string)
    {
        $string = stristr($string, 'src=');
        if (strlen($string) > 5) {
            $string_img = stristr($string, '"');
            $string_img = substr($string_img, 6);
            $string = $string_img;
            $string_img = stristr($string_img, '"', true);
            $newString = $string_img . ';';
            if (strlen(stristr($string, 'src=')) > 5) {
                $newString .= $this->findImageInStr($string);
            }
        }
        if (strlen($newString) > 0) {
            return $newString;
        }else {
            return null;
        }
    }

    function removeImage($path)
    {
        $str = '';

        if(file_exists($path) && is_dir($path))
        {
            $dirHandle = opendir($path);
            while (false !== ($file = readdir($dirHandle)))
            {
                if ($file!='.' && $file!='..')// исключаем папки с назварием '.' и '..'
                {
                    $tmpPath=$path.'/'.$file;
                    chmod($tmpPath, 0777);
                    if (is_dir($tmpPath))
                    {  // если папка
                        $str .= $this->removeImage($tmpPath);
                    }
                    else
                    {
                        if(file_exists($tmpPath))
                        {
                            $str .= $tmpPath . ';';
                            // удаляем файл
                            //unlink($tmpPath);
                        }
                    }
                }
            }
            closedir($dirHandle);
            return $str;
        }else {
            return 'ошибка ' . $path;
        }
    }
}
