<?php
/**
* This is the model class for table "{{publics}}".
*/
class CPublic extends CActiveRecord {
private $_access = null;
/**
* @return string the associated database table name
*/
public function tableName() {
return '{{publics}}';
}
/**
* @return array validation rules for model attributes.
*/
public function rules() {
return array(
array('name', 'required'),
array('id, creator_id', 'length', 'max' => 10),
array('name', 'length', 'max' => 255),
// The following rule is used by search().
array('id, name', 'safe', 'on' => 'search'),
);
}
/**
* @return array relational rules.
*/
public function relations() {
return array(
'profile' => array(self::BELONGS_TO, 'Profile', 'id'),
'creator' => array(self::BELONGS_TO, 'User', 'creator_id'),
'moderators' => array(self::HAS_MANY, 'Moderator', 'public_id'),
'readers' => array(self::MANY_MANY, 'User', PublicReader::model()->tableName().'(public_id, user_id)'),
);
}
/**
* Returns the static model of the specified AR class.
* Please note that you should have this exact method in all your CActiveRecord descendants!
* @param string $className active record class name.
* @return CPublic the static model class
*/
public static function model($className=__CLASS__) {
return parent::model($className);
}
/**
* Creates a public
*/
public function create() {
$transaction = $this->dbConnection->beginTransaction();
$profile = new Profile;
$profile->type = 'public';
if (!$profile->save())
return false;
$public = new self;
$public->attributes = $this->attributes;
$public->id = $profile->id;
if (!$public->save())
return false;
$reading = new PublicReader;
$reading->public_id = $public->id;
$reading->user_id = Yii::app()->user->record->id;
$reading->role = PublicReader::READER;
if (!$reading->save())
return false;
$transaction->commit();
return $public;
}
/**
* Checks access for currently logged user
* @param int $role
*/
public function checkAccess($requiredRole, $allowCaching = true) {
if ($this->creator_id == Yii::app()->user->record->id)
return true;
if ($allowCaching && $this->_access !== null)
return PublicReader::checkAccess($this->_access, $requiredRole);
if (($reading = PublicReader::model()->findByAttributes(array('public_id' => $this->id, 'user_id' => Yii::app()->user->record->id))) == null)
return false;
if ($allowCaching)
$this->_access = $reading->role;
return PublicReader::checkAccess($reading->role, $requiredRole);
}
/**
* @param CActiveRecord|int $user model or User id
*/
public function hasSubscriber($user) {
if (is_object($user))
$user = $user->id;
return PublicReader::model()->exists((new CDbCriteria)->compare('public_id', $this->id)->compare('user_id', $user));
}
}