<?php
class IndexAction extends BaseAction
{
    public function run()
    {
        if (Yii::app()->request->isPostRequest)
        {
            $table = Settings::model()->tableName();
            $criteria = new CDbCriteria();
            $array = array();
            
            if(!preg_match("/^([\+\-\*\/\.\d\(\)]|((extcredits[1-8]|digestposts|posts|oltime)([\+\-\*\/\(\)]|$)+))+$/", $_POST['settings']['cfg_creditsformula']) || !is_null(@eval(preg_replace("/(digestposts|posts|oltime|extcredits[1-8])/", "\$\\1", $_POST['settings']['cfg_creditsformula']).';')))
            {
                throw new CHttpException(500, '积分公式包含无效变量或运算符，请返回修改');                
            }
            
            foreach ($_POST['settings'] as $key => $value)
            {
                $criteria->condition = 'var=:var';
                $criteria->params = array(':var'=>$key);
                if ('cfg_extcredits' == $key)
                {
                    // 处理扩展积分
                    $extcredits = array();
                    foreach ($value as $k => &$v)
                    {
                        if ($v['available'] && !empty($v['title']))
                        {
                            unset($v['available']);
                            $extcredits[$k] = $v;
                        }
                    }
                    $array[$key] = $extcredits;
                    Yii::app()->db->getCommandBuilder()->createUpdateCommand($table, array('value'=>serialize($extcredits)), $criteria)->execute();
                }
                else
                {
                    $array[$key] = $value;
                    Yii::app()->db->getCommandBuilder()->createUpdateCommand($table, array('value'=>$value), $criteria)->execute();
                }
            }
            
            // 设置积分原算公式
            $array['cfg_creditsformula'] = empty($array['cfg_creditsformula']) ? 'extcredits1' : preg_replace("/(digestposts|posts|oltime|extcredits[1-8])/", "\$_IORANGE['user']['\\1']", $array['cfg_creditsformula']);
            Settings::createCache($array);
            
            //Yii::app()->end();
            $this->getController()->redirect(array('index'));
        }
        
        $settings = Settings::model()->getArrayResult();
        
        $this->getController()->render('index', array(
                'settings' => $settings,
            )
        );
    }
}