1
0

Added DB Access + Error page

This commit is contained in:
2014-05-12 10:11:20 +02:00
parent 3efba81ebc
commit ffdc17efd5
124 changed files with 6346 additions and 82 deletions

View File

@@ -0,0 +1,148 @@
<?php
class Comment extends CActiveRecord
{
/**
* The followings are the available columns in table 'tbl_comment':
* @var integer $id
* @var string $content
* @var integer $status
* @var integer $create_time
* @var string $author
* @var string $email
* @var string $url
* @var integer $post_id
*/
const STATUS_PENDING=1;
const STATUS_APPROVED=2;
/**
* Returns the static model of the specified AR class.
* @return CActiveRecord the static model class
*/
public static function model($className=__CLASS__)
{
return parent::model($className);
}
/**
* @return string the associated database table name
*/
public function tableName()
{
return '{{comment}}';
}
/**
* @return array validation rules for model attributes.
*/
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('content, author, email', 'required'),
array('author, email, url', 'length', 'max'=>128),
array('email','email'),
array('url','url'),
);
}
/**
* @return array relational rules.
*/
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
'post' => array(self::BELONGS_TO, 'Post', 'post_id'),
);
}
/**
* @return array customized attribute labels (name=>label)
*/
public function attributeLabels()
{
return array(
'id' => 'Id',
'content' => 'Comment',
'status' => 'Status',
'create_time' => 'Create Time',
'author' => 'Name',
'email' => 'Email',
'url' => 'Website',
'post_id' => 'Post',
);
}
/**
* Approves a comment.
*/
public function approve()
{
$this->status=Comment::STATUS_APPROVED;
$this->update(array('status'));
}
/**
* @param Post the post that this comment belongs to. If null, the method
* will query for the post.
* @return string the permalink URL for this comment
*/
public function getUrl($post=null)
{
if($post===null)
$post=$this->post;
return $post->url.'#c'.$this->id;
}
/**
* @return string the hyperlink display for the current comment's author
*/
public function getAuthorLink()
{
if(!empty($this->url))
return CHtml::link(CHtml::encode($this->author),$this->url);
else
return CHtml::encode($this->author);
}
/**
* @return integer the number of comments that are pending approval
*/
public function getPendingCommentCount()
{
return $this->count('status='.self::STATUS_PENDING);
}
/**
* @param integer the maximum number of comments that should be returned
* @return array the most recently added comments
*/
public function findRecentComments($limit=10)
{
return $this->with('post')->findAll(array(
'condition'=>'t.status='.self::STATUS_APPROVED,
'order'=>'t.create_time DESC',
'limit'=>$limit,
));
}
/**
* This is invoked before the record is saved.
* @return boolean whether the record should be saved.
*/
protected function beforeSave()
{
if(parent::beforeSave())
{
if($this->isNewRecord)
$this->create_time=time();
return true;
}
else
return false;
}
}

View File

@@ -0,0 +1,42 @@
<?php
/**
* ContactForm class.
* ContactForm is the data structure for keeping
* contact form data. It is used by the 'contact' action of 'SiteController'.
*/
class ContactForm extends CFormModel
{
public $name;
public $email;
public $subject;
public $body;
public $verifyCode;
/**
* Declares the validation rules.
*/
public function rules()
{
return array(
// name, email, subject and body are required
array('name, email, subject, body', 'required'),
// email has to be a valid email address
array('email', 'email'),
// verifyCode needs to be entered correctly
array('verifyCode', 'captcha', 'allowEmpty'=>!CCaptcha::checkRequirements()),
);
}
/**
* Declares customized attribute labels.
* If not declared here, an attribute would have a label that is
* the same as its name with the first letter in upper case.
*/
public function attributeLabels()
{
return array(
'verifyCode'=>'Verification Code',
);
}
}

View File

@@ -0,0 +1,74 @@
<?php
/**
* LoginForm class.
* LoginForm is the data structure for keeping
* user login form data. It is used by the 'login' action of 'SiteController'.
*/
class LoginForm extends CFormModel
{
public $username;
public $password;
public $rememberMe;
private $_identity;
/**
* Declares the validation rules.
* The rules state that username and password are required,
* and password needs to be authenticated.
*/
public function rules()
{
return array(
// username and password are required
array('username, password', 'required'),
// rememberMe needs to be a boolean
array('rememberMe', 'boolean'),
// password needs to be authenticated
array('password', 'authenticate'),
);
}
/**
* Declares attribute labels.
*/
public function attributeLabels()
{
return array(
'rememberMe'=>'Remember me next time',
);
}
/**
* Authenticates the password.
* This is the 'authenticate' validator as declared in rules().
*/
public function authenticate($attribute,$params)
{
$this->_identity=new UserIdentity($this->username,$this->password);
if(!$this->_identity->authenticate())
$this->addError('password','Incorrect username or password.');
}
/**
* Logs in the user using the given username and password in the model.
* @return boolean whether login is successful
*/
public function login()
{
if($this->_identity===null)
{
$this->_identity=new UserIdentity($this->username,$this->password);
$this->_identity->authenticate();
}
if($this->_identity->errorCode===UserIdentity::ERROR_NONE)
{
$duration=$this->rememberMe ? 3600*24*30 : 0; // 30 days
Yii::app()->user->login($this->_identity,$duration);
return true;
}
else
return false;
}
}

View File

@@ -0,0 +1,76 @@
<?php
class Lookup extends CActiveRecord
{
/**
* The followings are the available columns in table 'tbl_lookup':
* @var integer $id
* @var string $object_type
* @var integer $code
* @var string $name_en
* @var string $name_fr
* @var integer $sequence
* @var integer $status
*/
private static $_items=array();
/**
* Returns the static model of the specified AR class.
* @return CActiveRecord the static model class
*/
public static function model($className=__CLASS__)
{
return parent::model($className);
}
/**
* @return string the associated database table name
*/
public function tableName()
{
return '{{lookup}}';
}
/**
* Returns the items for the specified type.
* @param string item type (e.g. 'PostStatus').
* @return array item names indexed by item code. The items are order by their position values.
* An empty array is returned if the item type does not exist.
*/
public static function items($type)
{
if(!isset(self::$_items[$type]))
self::loadItems($type);
return self::$_items[$type];
}
/**
* Returns the item name for the specified type and code.
* @param string the item type (e.g. 'PostStatus').
* @param integer the item code (corresponding to the 'code' column value)
* @return string the item name for the specified the code. False is returned if the item type or code does not exist.
*/
public static function item($type,$code)
{
if(!isset(self::$_items[$type]))
self::loadItems($type);
return isset(self::$_items[$type][$code]) ? self::$_items[$type][$code] : false;
}
/**
* Loads the lookup items for the specified type from the database.
* @param string the item type
*/
private static function loadItems($type)
{
self::$_items[$type]=array();
$models=self::model()->findAll(array(
'condition'=>'type=:type',
'params'=>array(':type'=>$type),
'order'=>'position',
));
foreach($models as $model)
self::$_items[$type][$model->code]=$model->name;
}
}

View File

@@ -0,0 +1,202 @@
<?php
class Post extends CActiveRecord
{
/**
* The followings are the available columns in table 'tbl_post':
* @var integer $id
* @var string $title
* @var string $content
* @var string $tags
* @var integer $status
* @var integer $create_time
* @var integer $update_time
* @var integer $author_id
*/
const STATUS_DRAFT=1;
const STATUS_PUBLISHED=2;
const STATUS_ARCHIVED=3;
private $_oldTags;
/**
* Returns the static model of the specified AR class.
* @return CActiveRecord the static model class
*/
public static function model($className=__CLASS__)
{
return parent::model($className);
}
/**
* @return string the associated database table name
*/
public function tableName()
{
return '{{post}}';
}
/**
* @return array validation rules for model attributes.
*/
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('title, content, status', 'required'),
array('status', 'in', 'range'=>array(1,2,3)),
array('title', 'length', 'max'=>128),
array('tags', 'match', 'pattern'=>'/^[\w\s,]+$/', 'message'=>'Tags can only contain word characters.'),
array('tags', 'normalizeTags'),
array('title, status', 'safe', 'on'=>'search'),
);
}
/**
* @return array relational rules.
*/
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
'author' => array(self::BELONGS_TO, 'User', 'author_id'),
'comments' => array(self::HAS_MANY, 'Comment', 'post_id', 'condition'=>'comments.status='.Comment::STATUS_APPROVED, 'order'=>'comments.create_time DESC'),
'commentCount' => array(self::STAT, 'Comment', 'post_id', 'condition'=>'status='.Comment::STATUS_APPROVED),
);
}
/**
* @return array customized attribute labels (name=>label)
*/
public function attributeLabels()
{
return array(
'id' => 'Id',
'title' => 'Title',
'content' => 'Content',
'tags' => 'Tags',
'status' => 'Status',
'create_time' => 'Create Time',
'update_time' => 'Update Time',
'author_id' => 'Author',
);
}
/**
* @return string the URL that shows the detail of the post
*/
public function getUrl()
{
return Yii::app()->createUrl('post/view', array(
'id'=>$this->id,
'title'=>$this->title,
));
}
/**
* @return array a list of links that point to the post list filtered by every tag of this post
*/
public function getTagLinks()
{
$links=array();
foreach(Tag::string2array($this->tags) as $tag)
$links[]=CHtml::link(CHtml::encode($tag), array('post/index', 'tag'=>$tag));
return $links;
}
/**
* Normalizes the user-entered tags.
*/
public function normalizeTags($attribute,$params)
{
$this->tags=Tag::array2string(array_unique(Tag::string2array($this->tags)));
}
/**
* Adds a new comment to this post.
* This method will set status and post_id of the comment accordingly.
* @param Comment the comment to be added
* @return boolean whether the comment is saved successfully
*/
public function addComment($comment)
{
if(Yii::app()->params['commentNeedApproval'])
$comment->status=Comment::STATUS_PENDING;
else
$comment->status=Comment::STATUS_APPROVED;
$comment->post_id=$this->id;
return $comment->save();
}
/**
* This is invoked when a record is populated with data from a find() call.
*/
protected function afterFind()
{
parent::afterFind();
$this->_oldTags=$this->tags;
}
/**
* This is invoked before the record is saved.
* @return boolean whether the record should be saved.
*/
protected function beforeSave()
{
if(parent::beforeSave())
{
if($this->isNewRecord)
{
$this->create_time=$this->update_time=time();
$this->author_id=Yii::app()->user->id;
}
else
$this->update_time=time();
return true;
}
else
return false;
}
/**
* This is invoked after the record is saved.
*/
protected function afterSave()
{
parent::afterSave();
Tag::model()->updateFrequency($this->_oldTags, $this->tags);
}
/**
* This is invoked after the record is deleted.
*/
protected function afterDelete()
{
parent::afterDelete();
Comment::model()->deleteAll('post_id='.$this->id);
Tag::model()->updateFrequency($this->tags, '');
}
/**
* Retrieves the list of posts based on the current search/filter conditions.
* @return CActiveDataProvider the data provider that can return the needed posts.
*/
public function search()
{
$criteria=new CDbCriteria;
$criteria->compare('title',$this->title,true);
$criteria->compare('status',$this->status);
return new CActiveDataProvider('Post', array(
'criteria'=>$criteria,
'sort'=>array(
'defaultOrder'=>'status, update_time DESC',
),
));
}
}

View File

@@ -0,0 +1,159 @@
<?php
class Tag extends CActiveRecord
{
/**
* The followings are the available columns in table 'tbl_tag':
* @var integer $id
* @var string $name
* @var integer $frequency
*/
/**
* Returns the static model of the specified AR class.
* @return CActiveRecord the static model class
*/
public static function model($className=__CLASS__)
{
return parent::model($className);
}
/**
* @return string the associated database table name
*/
public function tableName()
{
return '{{tag}}';
}
/**
* @return array validation rules for model attributes.
*/
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('name', 'required'),
array('frequency', 'numerical', 'integerOnly'=>true),
array('name', 'length', 'max'=>128),
);
}
/**
* @return array relational rules.
*/
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
);
}
/**
* @return array customized attribute labels (name=>label)
*/
public function attributeLabels()
{
return array(
'id' => 'Id',
'name' => 'Name',
'frequency' => 'Frequency',
);
}
/**
* Returns tag names and their corresponding weights.
* Only the tags with the top weights will be returned.
* @param integer the maximum number of tags that should be returned
* @return array weights indexed by tag names.
*/
public function findTagWeights($limit=20)
{
$models=$this->findAll(array(
'order'=>'frequency DESC',
'limit'=>$limit,
));
$total=0;
foreach($models as $model)
$total+=$model->frequency;
$tags=array();
if($total>0)
{
foreach($models as $model)
$tags[$model->name]=8+(int)(16*$model->frequency/($total+10));
ksort($tags);
}
return $tags;
}
/**
* Suggests a list of existing tags matching the specified keyword.
* @param string the keyword to be matched
* @param integer maximum number of tags to be returned
* @return array list of matching tag names
*/
public function suggestTags($keyword,$limit=20)
{
$tags=$this->findAll(array(
'condition'=>'name LIKE :keyword',
'order'=>'frequency DESC, Name',
'limit'=>$limit,
'params'=>array(
':keyword'=>'%'.strtr($keyword,array('%'=>'\%', '_'=>'\_', '\\'=>'\\\\')).'%',
),
));
$names=array();
foreach($tags as $tag)
$names[]=$tag->name;
return $names;
}
public static function string2array($tags)
{
return preg_split('/\s*,\s*/',trim($tags),-1,PREG_SPLIT_NO_EMPTY);
}
public static function array2string($tags)
{
return implode(', ',$tags);
}
public function updateFrequency($oldTags, $newTags)
{
$oldTags=self::string2array($oldTags);
$newTags=self::string2array($newTags);
$this->addTags(array_values(array_diff($newTags,$oldTags)));
$this->removeTags(array_values(array_diff($oldTags,$newTags)));
}
public function addTags($tags)
{
$criteria=new CDbCriteria;
$criteria->addInCondition('name',$tags);
$this->updateCounters(array('frequency'=>1),$criteria);
foreach($tags as $name)
{
if(!$this->exists('name=:name',array(':name'=>$name)))
{
$tag=new Tag;
$tag->name=$name;
$tag->frequency=1;
$tag->save();
}
}
}
public function removeTags($tags)
{
if(empty($tags))
return;
$criteria=new CDbCriteria;
$criteria->addInCondition('name',$tags);
$this->updateCounters(array('frequency'=>-1),$criteria);
$this->deleteAll('frequency<=0');
}
}

View File

@@ -0,0 +1,90 @@
<?php
class User extends CActiveRecord
{
/**
* The followings are the available columns in table 'tbl_user':
* @var integer $id
* @var string $username
* @var string $password
* @var string $email
* @var string $profile
*/
/**
* Returns the static model of the specified AR class.
* @return CActiveRecord the static model class
*/
public static function model($className=__CLASS__)
{
return parent::model($className);
}
/**
* @return string the associated database table name
*/
public function tableName()
{
return '{{user}}';
}
/**
* @return array validation rules for model attributes.
*/
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('username, password, email', 'required'),
array('username, password, email', 'length', 'max'=>128),
array('profile', 'safe'),
);
}
/**
* @return array relational rules.
*/
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
'posts' => array(self::HAS_MANY, 'Post', 'author_id'),
);
}
/**
* @return array customized attribute labels (name=>label)
*/
public function attributeLabels()
{
return array(
'id' => 'Id',
'username' => 'Username',
'password' => 'Password',
'email' => 'Email',
'profile' => 'Profile',
);
}
/**
* Checks if the given password is correct.
* @param string the password to be validated
* @return boolean whether the password is valid
*/
public function validatePassword($password)
{
return CPasswordHelper::verifyPassword($password,$this->password);
}
/**
* Generates the password hash.
* @param string password
* @return string hash
*/
public function hashPassword($password)
{
return CPasswordHelper::hashPassword($password);
}
}