Author: Leonid Svyatov (leonid@svyatov.ru)
Beispiel #1
0
function test()
{
    $a = X::foo();
    $a();
    $a = Y::foo();
    $a();
    $a = X::bar();
    $a();
    $a = Y::bar();
    $a();
    $x = new X();
    $a = $x->bar();
    $a();
    $x = new Y();
    $a = $x->bar();
    $a();
    $a = X::bar_nonstatic();
    $a();
    $a = Y::bar_nonstatic();
    $a();
    $x = new X();
    $a = $x->bar_nonstatic();
    $a();
    $x = new Y();
    $a = $x->bar_nonstatic();
    $a();
}
Beispiel #2
0
 function f()
 {
     $y = new Y();
     $y->foo();
     static::g();
     $y->foo();
     self::g();
     Y::foo() && static::g();
 }
Beispiel #3
0
function test()
{
    $x = new X();
    $c = $x->f();
    var_dump($c(true));
    $y = new Y();
    $c = $y->f();
    var_dump($c("foo"));
}
Beispiel #4
0
function test($str)
{
    X::bar($str);
    (new X())->bar($str);
    Y::bar($str);
    (new Y())->bar($str);
}
Beispiel #5
0
 public function flushUploadDir()
 {
     $session = new CHttpSession();
     $session->open();
     $folder = $_SERVER['DOCUMENT_ROOT'] . '/upload/tmp/' . $session->SessionID;
     Y::recursiveRemDir($folder);
 }
Beispiel #6
0
 /**
  * 连接数据库
  *
  * @param string $dbFlag 数据库配置命名空间
  */
 public static function instance($dbFlag = '')
 {
     if (empty($dbFlag)) {
         throw new DbException('Empty param: dbFlag');
     }
     if (!isset(Y::$app->db[$dbFlag])) {
         throw new InvalidConfigException('Unknow db config: ' . $dbFlag);
     }
     if (!isset(static::$_links[$dbFlag]) || null === static::$_links[$dbFlag]) {
         $config = Y::$app->db[$dbFlag];
         $dsn = $config['dsn'];
         $driver = static::getDriverName($dsn);
         $dbClass = static::$_dbNamespace . '\\' . $driver . '\\Db';
         $dbFile = Y::namespaceTranslate($dbClass);
         if (!is_file($dbFile)) {
             throw new FileNotFoundException('The Classfile: ' . $dbFile . ' not found');
         }
         try {
             static::$_links[$dbFlag] = new $dbClass($dsn, $config['username'], $config['password']);
             static::$_links[$dbFlag]->initConnection($config);
         } catch (PDOException $e) {
             static::$_links[$dbFlag] = null;
             throw new DbException('Failed to connect to database');
         }
     }
     return static::$_links[$dbFlag];
 }
Beispiel #7
0
 public function __construct(&$config)
 {
     $this->cachePath = isset($config['cachePath']) ? Y::getPathAlias($config['cachePath']) : Y::getPathAlias($this->cachePath);
     if (!is_dir($this->cachePath)) {
         FileHelper::createDirectory($this->cachePath);
     }
 }
Beispiel #8
0
 function recursiveRemDir($directory, $empty = FALSE)
 {
     if (substr($directory, -1) == '/') {
         $directory = substr($directory, 0, -1);
     }
     if (!file_exists($directory) || !is_dir($directory)) {
         return FALSE;
     } elseif (is_readable($directory)) {
         $handle = opendir($directory);
         while (FALSE !== ($item = readdir($handle))) {
             if ($item != '.' && $item != '..') {
                 $path = $directory . '/' . $item;
                 if (is_dir($path)) {
                     Y::recursiveRemDir($path);
                 } else {
                     unlink($path);
                 }
             }
         }
         closedir($handle);
         if ($empty == FALSE) {
             if (!rmdir($directory)) {
                 return FALSE;
             }
         }
     }
     return TRUE;
 }
	public function actionUpdate($dir, $fileName)
	{
		if (isset($_POST['fileContent'])) {
			FileSystem::write('./'.$dir.'/'.$fileName, $_POST['fileContent'], 'w');
            Y::end();
        }

		$content = '';
		$info = FileSystem::getInfo('./'.$dir.'/'.$fileName, array('name', 'ext'));
		if (in_array($info['ext'], array('js', 'css'))) {
			if (substr($dir, 0, 2) == 'js' || substr($dir, 0, 3) == 'css') {
				$content = FileSystem::read('./'.$dir.'/'.$fileName);
			}
		}
		
		$output = $this->renderPartial('fileDetails', array(
			'fileName' => $fileName,
			'content' => $content,
			'type' => $info['ext'] == 'css' ? 'css' : 'javascript',
			'filePath' => './'.$dir.'/'.$fileName
		), true);

        Y::tab('Содержимое файла', $output);

        $output = Y::getTabs('cssFileForm', true);
        Y::clientScript()->render($output);
        echo CHtml::tag('div', array(), $output);
	}
    public function actionAdmin($catPk, $opts = array())
	{
        $cat = Category::model()->findByPk($catPk);

		$model = $this->loadModel($catPk, null, 'search');

        $this->ajaxSetNextValue('published', $model, 'published', array(BaseDataType::PUBLISHED, BaseDataType::NOT_PUBLISHED));
		$model->unsetAttributes();  // clear any default values

        $model = $model->current($cat);

		if (isset($_GET[get_class($model)]))
			$model->attributes=$_GET[get_class($model)];

		$opts['model'] = $model;
        $opts['cat'] = $cat;

        $opts['columns'] = array();
        $opts = Y::hooks()->cmsAdminGetGridColumns($this, &$opts);

		if (isset($_GET['ajax'])) {
			$this->renderPartial('admingrid',$opts);
		} else {
    		$this->render('admin',$opts);
        }
	}
	/**
	 * Recovery password
	 */
	public function actionRecovery () {
		$form = new UserRecoveryForm;
		if (Y::userId()) {
    		$this->redirect(Y::module()->returnUrl);
			Y::end();
		}

		$email = isset($_GET['email']) ? $_GET['email'] : '';
		$activkey = isset($_GET['activkey']) ? $_GET['activkey'] : '';
		if ($email&&$activkey) {	//get new pass
			
			$find = User::model()->notsafe()->findByAttributes(array('email'=>$email));
    		if(isset($find)&&$find->activkey==$activkey) {
				$form2 = new UserChangePassword;
    			if(isset($_POST['UserChangePassword'])) {
					$form2->attributes=$_POST['UserChangePassword'];
					if($form2->validate()) {
						$find->password = UserModule::encrypting($form2->password);
						if ($find->status==0) {
							$find->status = 1;
						}
						$find->save();
						Y::flash('recoveryMessage',Users::t("New password is saved."));
						$this->redirect(Y::module()->recoveryUrl);
					}
				} 
				$this->render('changepassword',array('form'=>$form2));
    		} else {
    			Y::flash('recoveryMessage',Users::t("Incorrect recovery link."));
				$this->redirect(Y::module()->recoveryUrl);
    		}
    	} else {	//send email
	    	if(isset($_POST['UserRecoveryForm'])) {
	    		$form->attributes=$_POST['UserRecoveryForm'];
	    		
	    		if($form->validate()) {
	    			$user = User::model()->notsafe()->findbyPk($form->user_id);
	    			$user->activkey = Y::module()->encrypting(microtime().$user->password);	
	    			$user->save();
	    			$activation_url = 'http://' . $_SERVER['HTTP_HOST'].$this->siteUrl('user/recovery',array("activkey" => $user->activkey, "email" => urldecode($user->email)));
					
					$subject = Users::t("You have requested the password recovery site {site_name}",
	    					array(
	    						'{site_name}'=>Yii::app()->name,
	    					));
	    			$message = Users::t("You have requested the password recovery site {site_name}. To receive a new password, go to {activation_url}.",
	    					array(
	    						'{site_name}'=>Yii::app()->name,
	    						'{activation_url}'=>$activation_url,
	    					));
					
	    			UserModule::sendMail($user->email,$subject,$message);
	    			
					Y::flash('recoveryMessage',Users::t("Please check your email. An instructions was sent to your email address."));
	    			$this->refresh();
	    		}
	    	}
    		$this->render('recovery',array('form'=>$form));
    	}
	}
	/**
	 * Authenticates a user.
	 * The example implementation makes sure if the username and password
	 * are both 'demo'.
	 * In practical applications, this should be changed to authenticate
	 * against some persistent user identity storage (e.g. database).
	 * @return boolean whether authentication succeeds.
	 */
	public function authenticate()
	{
		if (strpos($this->username,"@")) {
			$user=User::model()->notsafe()->findByAttributes(array('email'=>$this->username));
		} else {
			$user=User::model()->notsafe()->findByAttributes(array('username'=>$this->username));
		}
		if($user===null)
			if (strpos($this->username,"@")) {
				$this->errorCode=self::ERROR_EMAIL_INVALID;
			} else {
				$this->errorCode=self::ERROR_USERNAME_INVALID;
			}
		else if(Y::module('users')->encrypting($this->password)!==$user->password)
			$this->errorCode=self::ERROR_PASSWORD_INVALID;
		else if($user->status==0&&Y::module('users')->loginNotActiv==false)
			$this->errorCode=self::ERROR_STATUS_NOTACTIV;
		else if($user->status==-1)
			$this->errorCode=self::ERROR_STATUS_BAN;
		else {
			$this->_id=$user->id;
			$this->username=$user->username;
			$this->errorCode=self::ERROR_NONE;
		}
		return !$this->errorCode;
	}
    public function getListView(&$criteria, $return = false)
    {
        $dp = new EActiveDataProvider(get_class($this->model), array(
            'criteria' => $criteria,
            //'pagination' => $this->settings['pagination'],
        ));

        //default params
        $params = array(
            'dataProvider'=>$dp,
            'pager'=>array(
                'id'=>$this->widgetModel->pk.'Pager', 'class'=>'LinkPager', 'htmlOptions'=>array('class'=>'pager'),
                'cssFile'=>Yii::app()->baseUrl.'/css/pager.css'
            ),
            'ajaxUpdate'=>true,
            'template'=>$this->render('listTemplate', array(), true),
            'afterAjaxUpdate' => ModelFactory::getAfterAjaxUpdateFunction($this->category->type),
            'beforeAjaxUpdate' => ModelFactory::getBeforeAjaxUpdateFunction($this->category->type),
            'category' => $this->category,
            'contextWidget' => $this
        );

        try {
            $res = Y::controller()->widget('ListView', $params, true);
        } catch (CException $e) {
            Y::dump($e->__toString());
        }

        if ($return)
            return $res;
        else
            echo $res;
    }
Beispiel #14
0
 public function __construct($config)
 {
     $this->logPath = isset($config['logPath']) ? Y::getPathAlias($config['logPath']) : Y::getPathAlias($this->logPath);
     $this->logFile = $this->generateTimeLogFile();
     if (!is_dir($this->logPath)) {
         FileHelper::createDirectory($this->logPath);
     }
 }
Beispiel #15
0
	/**
	 * @return array relational rules.
	 */
	public function relations()
	{	
		$relations = array(
			'profile'=>array(self::HAS_ONE, 'Profile', 'user_id'),
		);
		if (isset(Y::module('users')->relations)) $relations = array_merge($relations,Y::module('users')->relations);
		return $relations;
	}
Beispiel #16
0
	public function createPageUrl($controller,$page)
	{
		$params=$this->params===null ? $_GET : $this->params;
		if($page>0) // page 0 is the default
			$params[$this->pageVar]=$page+1;
		else
			unset($params[$this->pageVar]);
		return Y::url($this->route,$params);
	}
Beispiel #17
0
    public function init()
	{
        parent::init();
	    $this->setImport(array(
			'admin.models.*',
			'admin.components.*',
		));
        Y::clientScript()->registerScriptFile($this->scriptPath.'/js/cms/asc.js');
	}
Beispiel #18
0
	/**
	* @return boolean whether the dependency has changed.
	*/
	public function getHasChanged() 
	{
		$tags = array_map(function($i) { return FileCache::PREFIX.$i; }, $this->tags);
		$values = Y::cache()->mget($tags);
	
		foreach ($values as $value) {
			if ((integer)$value > $this->timestamp) { return true; }
		}
	
		return false;
	}
Beispiel #19
0
 public function run()
 {
     $model = Holes::model()->count(array('condition' => 'PREMODERATED=1'));
     $all = $model;
     $model = Holes::model()->count(array('condition' => 'PREMODERATED=1 AND STATE="inprogress"'));
     $ingibdd = $model;
     $model = Holes::model()->count(array('condition' => 'PREMODERATED=1 AND STATE="fixed"'));
     $fixed = $model;
     $this->registerCoreScripts();
     $this->render($this->itemview, array('all' => Y::declOfNum($all, array('дефект', 'дефекта', 'дефектов')), 'ingibdd' => $ingibdd, 'fixed' => $fixed));
 }
Beispiel #20
0
 public function registerScritps()
 {
     $options = empty($this->options) ? '' : CJavaScript::encode($this->options);
     Y::clientScript()
         ->registerScript($this->getId().'-form-submit', "
             $(document).ready(function(){
                 $('#{$this->getId()}').tabs({$options});
             });
         ")
         ->registerScriptFile('');
 }
 public function setPositions($ids, $table, $criteria = null)
 {
     $criteria = $criteria ? $criteria : new CDbCriteria();
     $owner = $this->getOwner();
     $pk = $owner->primaryKey();
     //last id have 0 priority => revers => first id have 0 priority => flip => every id have their priority
     $priorities = array_flip(array_reverse($ids));
     $data = array('priority' => Sql::arrToCase($pk, $priorities));
     $c = Yii::app()->db->commandBuilder->createUpdateCommand($table, $data, $criteria);
     Y::dump($c->execute());
 }
Beispiel #22
0
    public function renderBlock($alias)
    {
        if (!isset($this->cat)) {
            if (($module = Y::module()) != null) {
                $this->cat = $module->category;
            }
        }
        if (($block = $this->cat->getBlock($alias)) === null)
            return '{{ ' . $alias . ' }}';

        return $block->renderBlock($this->cat);
    }
	public function rules() {
		return array(    
			array('verifyCode', 'activeCaptcha', 'allowEmpty'=>!Y::isGuest() || !CCaptcha::checkRequirements()), // Во время AJAX запроса не забудьте установить сценарий для модели
		    //to captcha ajax validation    
			/*array('verifyCode','captcha',
               // авторизованным пользователям код можно не вводить
               ,
			   'captchaAction' => 'site/captcha'
            ),*/
            
		);
	}
	private function renderWidget($widget, $category)
	{
        $settings = CMap::mergeArray($widget->settings, array(
			'category' => $category,
            'blockModel' => $this,
            'widgetModel' => $widget,
            'block' => $this,
            'model' => isset(Y::controller()->model) ? Y::controller()->model : null
		));

		return Y::controller()->widget($widget->class.'Widget', $settings, true);
	}
 /**
  * This is the action to handle external exceptions.
  */
 public function actionError()
 {
     if ($error = Yii::app()->errorHandler->error){
         if (Y::isAjaxRequest()){
             echo $error['message'];
         }
         else {
             echo CHtml::tag('h2', array(), 'Error ' . $error['code']);
             echo CHtml::tag('div', array(), CHtml::encode($error['message']));
         }
     }
 }
    public function ajaxExclude($names)
    {
        if (Y::isAjaxRequest()) {
            $files = array();
            foreach ((array)$names as $name)
                $files[$name] = false;

            Y::clientScript()->scriptMap = CMap::mergeArray(
                Y::clientScript()->scriptMap,
                $files
            );
        }
    }
Beispiel #27
0
 /**
  * 得到视图所在路径
  *
  * @return string 视图路径
  */
 public function findViewFile($view)
 {
     $app = Y::$app;
     $path = '';
     if (null !== $app->moduleId) {
         $path = Y::namespaceTranslate($app->modules[$app->moduleId], '');
     } else {
         $path = Y::namespaceTranslate('app', '');
     }
     // 模块无子目录 普通控制器有子目录
     // 注意转换 namespace path 为目录路径
     return $path . '/views/' . (null === $app->routePrefix ? '.' : str_replace('\\', '/', $app->routePrefix)) . '/' . $view . $this->defaultExtension;
 }
	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('User', array(
			'criteria'=>array(
		        'condition'=>'status>'.User::STATUS_BANED,
		    ),
			'pagination'=>array(
				'pageSize'=>Y::module()->user_page_size,
			),
		));

		$this->render('/user/index',array(
			'dataProvider'=>$dataProvider,
		));
	}
    public  function init()
    {
        Y::clientScript()->registerScriptFile('/js/plugins/jquery.form.js');

        $options = CJavaScript::encode($this->options);
        Y::clientScript()->registerScript('save-button', "
            $(document).ready(function() {
                //form submit
                $('#$this->id').closest('form').bind('submit', function(e) {
                    e.preventDefault(); // <-- important
                    $(this).ajaxSubmit($options);
                });
            });
        ");
        parent::init();
    }
    public function init()
    {
        // Иерархию ролей расположим в файле auth.php в директории config приложения
        if($this->authFile===null){
            $this->authFile=Yii::getPathOfAlias('application.config.auth').'.php';
        }
 
        parent::init();
 
        // Для гостей у нас и так роль по умолчанию guest.
        if(!Y::isGuest()){
            // Связываем роль, заданную в БД с идентификатором пользователя,
            // возвращаемым UserIdentity.getId().
            $this->assign(Y::user()->role, Y::userId());
        }
    }