<?php
class CacheBehavior extends CActiveRecordBehavior
{
    public function afterSave($event)
    {
        $this->_updateCache();
        return true;
    }
    
    public function afterDelete($event)
    {
        $this->_updateCache();
        return true;
    }
    
    private function _updateCache()
    {
        $smiles = $smiliesType = $smilesArray = array();
        $i = 1;
        $types = $this->Owner->findAll(array('condition'=>'type=0','order'=>'displayorder DESC'));
        if (!empty($types))
        {
            foreach ($types as $type)
            {
                $result = $this->Owner->findAll(array('condition'=>'type='.$type->id));
                $smiliesType[] = "smilies_type[".$i."] = ['{$type->name}', '{$type->path}'];"; 
                if (!empty($result))
                {
                    $tmp = array();
                    foreach ($result as $item)
                    {
                        $smiles[$item->id] = array('type' => $item->type, 'code'=>$item['code'],'smile'=>$type->path.'/'.$item->path);
                        $width = 20;
                        $smileFile = $item->getSmilePath($type->path.'/'.$item->path);
                        if (is_file($smileFile))
                        {
                            $image = getimagesize($smileFile);
                            $width = $image[0] ? $image[0] : $width;
                        }
                        $tmp[] = "['{$item->id}', '{$item->code}','{$item->path}','20','20','{$width}']";
                    }
                    $smilesArray[] = $string = "smilies_array[{$i}] = new Array();smilies_array[{$i}][1]=[" . implode(',', $tmp).'];';
                }
                
                $smileType[$type->id] = array('name'=>$type->name,'path'=>$type->path);
                $i++;
            }
        }
        
        $jsCache = "var smthumb = '20';var smilies_type = new Array();";
        $jsCache .= implode("", $smiliesType);
        $jsCache .= "var smilies_array = new Array();";
        $jsCache .= implode('', $smilesArray);
        
        $smilesFile = ROOT_PATH . 'cache/bbs/smiles.php';
        $typesFile = ROOT_PATH . 'cache/bbs/smiles_type.php';
        $jsFile = ROOT_PATH . 'cache/smilies_var.js';
        file_put_contents($smilesFile, "<?php\nreturn ".var_export($smiles,true).';');
        file_put_contents($typesFile, "<?php\nreturn ".var_export($smileType, true).';');
        file_put_contents($jsFile, $jsCache);
    }
}