本文整理汇总了PHP中Comment::setAttributes方法的典型用法代码示例。如果您正苦于以下问题:PHP Comment::setAttributes方法的具体用法?PHP Comment::setAttributes怎么用?PHP Comment::setAttributes使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Comment
的用法示例。
在下文中一共展示了Comment::setAttributes方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: actionAdd
public function actionAdd()
{
if (Yii::app()->request->isPostRequest && isset($_POST['Comment'])) {
$redirect = isset($_POST['redirectTo']) ? $_POST['redirectTo'] : Yii::app()->user->returnUrl;
$comment = new Comment();
$module = Yii::app()->getModule('comment');
$comment->setAttributes($_POST['Comment']);
$comment->status = $module->defaultCommentStatus;
if (Yii::app()->user->isAuthenticated()) {
$comment->setAttributes(array('user_id' => Yii::app()->user->getId(), 'name' => Yii::app()->user->getState('nick_name'), 'email' => Yii::app()->user->getState('email')));
if ($module->autoApprove) {
$comment->status = Comment::STATUS_APPROVED;
}
}
if ($comment->save()) {
if (Yii::app()->request->isAjaxRequest) {
Yii::app()->ajax->success(Yii::t('comment', 'Комментарий добавлен!'));
}
$message = $comment->status !== Comment::STATUS_APPROVED ? Yii::t('comment', 'Спасибо, Ваш комментарий добавлен и ожидает проверки!') : Yii::t('comment', 'Спасибо, Ваш комментарий добавлен!');
Yii::app()->user->setFlash(YFlashMessages::NOTICE_MESSAGE, $message);
$this->redirect($redirect);
} else {
if (Yii::app()->request->isAjaxRequest) {
Yii::app()->ajax->failure(Yii::t('comment', 'Комментарий не добавлен!'));
}
Yii::app()->user->setFlash(YFlashMessages::ERROR_MESSAGE, Yii::t('comment', 'Комментарий не добавлен! Заполните форму корректно!'));
$this->redirect($redirect);
}
}
throw new CHttpException(404, Yii::t('comment', 'Страница не найдена!'));
}
示例2: run
public function run()
{
$model = new Comment();
$module = Yii::app()->getModule('comment');
$model->setAttributes(array('model' => $this->model, 'model_id' => $this->modelId));
if ($this->allowGuestComment == false && !Yii::app()->user->isAuthenticated()) {
$this->view = 'commentnotallowed';
}
$this->render($this->view, array('redirectTo' => $this->redirectTo, 'model' => $model, 'module' => $module));
}
示例3: testApprove
public function testApprove()
{
$comment = new Comment();
$comment->setAttributes(array('content' => 'comment 1', 'status' => Comment::STATUS_PENDING, 'create_time' => time(), 'author' => 'me', 'email' => 'me@example.com', 'post_id' => $this->posts['sample1']['id']), false);
$this->assertTrue($comment->save(false));
$comment = Comment::model()->findByPk($comment->id);
$this->assertTrue($comment instanceof Comment);
$this->assertEquals(Comment::STATUS_PENDING, $comment->status);
$comment->approve();
$this->assertEquals(Comment::STATUS_APPROVED, $comment->status);
$comment = Comment::model()->findByPk($comment->id);
$this->assertEquals(Comment::STATUS_APPROVED, $comment->status);
}
示例4: create
/**
* @param $params
* @param $module
* @param $user
* @param null $request
* @return bool|Comment
* @throws CException
*/
public function create($params, $module, $user, $request = null)
{
if ($user->isAuthenticated()) {
$params = CMap::mergeArray($params, ['user_id' => $user->getId(), 'name' => $user->getState('nick_name'), 'email' => $user->getProfileField('email')]);
}
$comment = new Comment();
$comment->setAttributes($params);
$comment->status = (int) $module->defaultCommentStatus;
if ($module->autoApprove && $user->isAuthenticated()) {
$comment->status = Comment::STATUS_APPROVED;
}
/**
* Реализована проверка прав на возможность добавления комментария в конкретную модель
* Для того чтобы осушествить проверку у модели должен быть public метод: commitValidation()
* Если метод вернет значение: false, то предполагается что для данной сушности добавление комментария запрещено
**/
$model = YModel::model($comment->model)->findByPk($comment->model_id);
if ($model instanceof ICommentAllowed && $model->isCommentAllowed() === false) {
throw new CException(Yii::t('CommentModule.comment', 'Not have permission to add a comment!'));
}
$transaction = Yii::app()->getDb()->beginTransaction();
try {
Yii::app()->eventManager->fire(CommentEvents::BEFORE_ADD_COMMENT, new CommentEvent($comment, $user, $module, $request));
$root = null;
$parentId = (int) $comment->parent_id;
// Если указан parent_id просто добавляем новый комментарий.
if ($parentId) {
$root = Comment::model()->approved()->findByPk($parentId);
if (null === $root) {
throw new CException(Yii::t('CommentModule.comment', 'Root comment not found!'));
}
} else {
// Иначе если parent_id не указан...
$root = $comment->createRootOfCommentsIfNotExists($comment->model, $comment->model_id);
if (null === $root) {
throw new CException(Yii::t('CommentModule.comment', 'Root comment not created!'));
}
}
if ($comment->appendTo($root)) {
Yii::app()->eventManager->fire(CommentEvents::SUCCESS_ADD_COMMENT, new CommentEvent($comment, $user, $module));
$transaction->commit();
return $comment;
}
throw new CException(Yii::t('CommentModule.comment', 'Error append comment to root!'));
} catch (Exception $e) {
$transaction->rollback();
Yii::app()->eventManager->fire(CommentEvents::ERROR_ADD_COMMENT, new CommentEvent($comment, $user, $module));
Yii::log($e->__toString(), CLogger::LEVEL_ERROR, 'comment');
return false;
}
}
示例5: create
public function create($params, $module, $user)
{
$comment = new Comment();
$comment->setAttributes($params);
$comment->status = (int) $module->defaultCommentStatus;
if ($module->autoApprove && $user->isAuthenticated()) {
$comment->status = Comment::STATUS_APPROVED;
}
$transaction = Yii::app()->db->beginTransaction();
try {
$root = null;
$parentId = (int) $comment->getAttribute('parent_id');
// Если указан parent_id просто добавляем новый комментарий.
if ($parentId) {
$root = Comment::model()->approved()->findByPk($parentId);
if (null === $root) {
throw new CDbException(Yii::t('CommentModule.comment', 'Root comment not found!'));
}
} else {
// Иначе если parent_id не указан...
$root = $comment->createRootOfCommentsIfNotExists($comment->getAttribute("model"), $comment->getAttribute("model_id"));
if (null === $root) {
throw new CDbException(Yii::t('CommentModule.comment', 'Root comment not created!'));
}
}
if ($comment->appendTo($root)) {
//events
$event = new NewCommentEvent();
$event->comment = $comment;
$event->module = $module;
$this->onNewComment($event);
$transaction->commit();
// сбросить кэш
Yii::app()->cache->delete("Comment{$comment->model}{$comment->model_id}");
// метка для проверки спама
Yii::app()->cache->set('Comment::Comment::spam::' . $user->getId(), time(), (int) $module->antiSpamInterval);
return $comment;
}
throw new CDbException(Yii::t('CommentModule.comment', 'Error append comment to root!'));
} catch (Exception $e) {
Yii::log($e->__toString(), CLogger::LEVEL_ERROR, 'comment');
$transaction->rollback();
return false;
}
}
示例6: edit
/**
* Update an existing comment
*
* @param void
* @return null
*/
function edit()
{
$this->wireframe->print_button = false;
if ($this->active_comment->isNew()) {
$this->httpError(HTTP_ERR_NOT_FOUND);
}
// if
if (!$this->active_comment->canEdit($this->logged_user)) {
$this->httpError(HTTP_ERR_FORBIDDEN);
}
// if
$parent = $this->active_comment->getParent();
if (!instance_of($parent, 'ProjectObject')) {
$this->httpError(HTTP_ERR_NOT_FOUND);
}
// if
$parent->prepareProjectSectionBreadcrumb($this->wireframe);
$this->wireframe->addBreadCrumb($parent->getName(), $parent->getViewUrl());
$comment_data = $this->request->post('comment');
if (!is_array($comment_data)) {
$comment_data = array('body' => $this->active_comment->getBody());
}
// if
$this->smarty->assign('comment_data', $comment_data);
//BOF:task_1260
$active_object = ProjectObjects::findById($this->active_comment->getParentId());
$this->smarty->assign('subscribers', $active_object->getSubscribers());
$link = mysql_connect(DB_HOST, DB_USER, DB_PASS);
mysql_select_db(DB_NAME);
//$query = "select * from healingcrystals_assignments_action_request where comment_id='" . $this->active_comment->getId() . "' and selected_by_user_id='" . $this->logged_user->getId() . "'";
$query = "select * from healingcrystals_assignments_action_request where comment_id='" . $this->active_comment->getId() . "'";
$request = mysql_query($query);
$fyi_users = array();
$action_request_users = array();
while ($entry = mysql_fetch_array($request)) {
//BOF:mod 20130429
/*
//EOF:mod 20130429
if ($entry['is_action_request']=='1'){
//BOF:mod 20130429
*/
if (!empty($entry['is_action_request'])) {
//EOF:mod 20130429
$action_request_users[] = $entry['user_id'];
}
//BOF:mod 20130429
/*
//EOF:mod 20130429
if ($entry['is_fyi']=='1'){
$fyi_users[] = $entry['user_id'];
}
//BOF:mod 20130429
*/
//EOF:mod 20130429
}
$this->smarty->assign('fyi_users', $fyi_users);
$this->smarty->assign('action_request_users', $action_request_users);
$this->smarty->assign('logged_user', $this->logged_user);
//EOF:task_1260
if ($this->request->isSubmitted()) {
$this->active_comment->setAttributes($comment_data);
$save = $this->active_comment->save();
if ($save && !is_error($save)) {
//BOF:task_1260
//$subscribers_to_notify = array_var($comment_data, 'subscribers_to_notify');
$action_request_user_id = array_var($comment_data, 'action_request');
//mysql_query("update healingcrystals_assignments_action_request set is_action_request='0', is_fyi='0' where comment_id='" . $this->active_comment->getId() . "' and selected_by_user_id='" . $this->logged_user->getId() . "' and is_action_request<>'-1' and is_fyi<>'-1'");
//mysql_query("update healingcrystals_assignments_action_request set is_action_request='0', is_fyi='0' where comment_id='" . $this->active_comment->getId() . "' and selected_by_user_id='" . $this->logged_user->getId() . "' and is_action_request<>'-1' and is_fyi<>'-1'");
/*if (!empty($subscribers_to_notify)){
foreach ($subscribers_to_notify as $id){
$query = "select * from healingcrystals_assignments_action_request where comment_id='" . $this->active_comment->getId() . "' and selected_by_user_id='" . $this->logged_user->getId() . "' and user_id='" . $id . "'";
$result = mysql_query($query);
if (mysql_num_rows($result)){
$query = "update healingcrystals_assignments_action_request set is_fyi='1' where comment_id='" . $this->active_comment->getId() . "' and selected_by_user_id='" . $this->logged_user->getId() . "' and user_id='" . $id . "'";
mysql_query($query);
} else {
$query = "insert into healingcrystals_assignments_action_request (user_id, is_action_request, is_fyi, selected_by_user_id, comment_id, date_added) values ('" . $id . "', '0', '1', '" . $this->logged_user->getId() . "', '" . $this->active_comment->getId() . "', now())";
mysql_query($query);
}
}
}*/
$existing_ar_users = array();
$new_ar_users = array();
if (!empty($action_request_user_id)) {
foreach ($action_request_user_id as $id) {
$query = "select * from healingcrystals_assignments_action_request where comment_id='" . $this->active_comment->getId() . "' and user_id='" . $id . "'";
$result = mysql_query($query);
if (mysql_num_rows($result)) {
$info = mysql_fetch_assoc($result);
if ($info['is_action_request'] == '1') {
$existing_ar_users[] = $id;
} else {
$query = "update healingcrystals_assignments_action_request set is_action_request='1' where comment_id='" . $this->active_comment->getId() . "' and user_id='" . $id . "'";
mysql_query($query);
//.........这里部分代码省略.........
示例7: createRootOfCommentsIfNotExists
public function createRootOfCommentsIfNotExists($model, $model_id)
{
$rootNode = $this->getRootOfCommentsTree($model, $model_id);
if ($rootNode === null) {
$rootAttributes = array("user_id" => Yii::app()->user->getId(), "model" => $model, "model_id" => $model_id, "url" => "", "name" => "", "email" => "", "text" => "", "status" => self::STATUS_APPROVED, "ip" => Yii::app()->getRequest()->userHostAddress);
$rootNode = new Comment();
$rootNode->setAttributes($rootAttributes);
if ($rootNode->saveNode(false)) {
return $rootNode;
}
} else {
return $rootNode;
}
return false;
}
示例8: array
/**
* Add comment to object
*
*/
function add_comment()
{
$parent_id = $this->request->get('parent_id');
$parent = ProjectObjects::findById($parent_id);
if (!instance_of($parent, 'ProjectObject')) {
$this->httpError(HTTP_NOT_FOUND);
}
// if
if (!$parent->canComment($this->logged_user)) {
$this->httpError(HTTP_ERR_FORBIDDEN);
}
// if
$comment_data = $this->request->post('comment');
$this->smarty->assign(array('parent' => $parent, 'comment_data' => $comment_data, 'recent_comments' => Comments::findRecentObject($parent, 5, STATE_VISIBLE, $this->logged_user->getVisibility()), 'page_back_url' => mobile_access_module_get_view_url($parent)));
$this->addBreadcrumb(ucfirst(lang($parent->getModule())), assemble_url('mobile_access_view_' . $parent->getModule(), array('project_id' => $this->active_project->getId())));
$this->addBreadcrumb($parent->getName(), mobile_access_module_get_view_url($parent));
$this->addBreadcrumb('Add Comment');
if ($this->request->isSubmitted()) {
db_begin_work();
$comment = new Comment();
$comment->setAttributes($comment_data);
$comment->setParent($parent);
$comment->setProjectId($this->active_project->getId());
$comment->setState(STATE_VISIBLE);
$comment->setVisibility($parent->getVisibility());
$comment->setCreatedBy($this->logged_user);
$save = $comment->save();
if ($save && !is_error($save)) {
db_commit();
flash_success('Comment successfully posted');
$this->redirectToUrl(mobile_access_module_get_view_url($comment));
} else {
db_rollback();
$this->smarty->assign('errors', $save);
$this->render();
}
// if
}
// if
}
示例9: buildNestedSetsTree
protected function buildNestedSetsTree()
{
$db = $this->db;
// Получаем все коренные элементы на основе значения parent_id
$roots = $db->createCommand()->select('*')->from("{{comment_comment}}")->where("parent_id is null")->queryAll();
// Получаем все остальные элементы (не являющиеся корнем)
$others = $db->createCommand()->select('*')->from("{{comment_comment}}")->where("parent_id is not null")->queryAll();
// Очищаем таблицу комментариев
$db->createCommand()->truncateTable("{{comment_comment}}");
// Добавляем в таблицу коренные элементы
foreach ($roots as &$root) {
$comment = new \Comment();
$comment->setAttributes($root, false);
$comment->saveNode(false);
}
// Добавляем в таблицу все остальные элементы
foreach ($others as &$other) {
$rootNode = \Comment::model()->findByPk($other["parent_id"]);
if ($rootNode != null) {
$comment = new \Comment();
$comment->setAttributes($other, false);
$comment->appendTo($rootNode, false);
} else {
echo 'Bad comment which parent was deleted: ' . $other["id"] . "\n";
}
}
echo "Converted succesfully.\n";
}
示例10: actionComment_reply
public function actionComment_reply($post_id, $comment_id = 0)
{
$post_id = (int) $post_id;
$comment_id = (int) $comment_id;
if (!isset($_POST["Comment"])) {
$this->redirect("/blog/{$post_id}");
}
if ($comment_id) {
$parent = Comment::model()->with("post", "author")->findByPk($comment_id);
if (!$parent) {
throw new CHttpException(404, "Вы пытаетесь ответить на несуществующий комментарий");
}
} else {
$parent = new Comment();
$parent->post = BlogPost::model()->with("author", "seen")->findByPk($post_id);
$parent->post_id = $parent->post->id;
}
/** @todo тут бы хорошо проверять права доступа в пост */
$comment = new Comment();
$comment->setAttributes($_POST["Comment"]);
if ($parent->reply($comment)) {
$parent->post->afterCommentAdd($comment, $parent);
} else {
Yii::app()->user->setFlash("error", $comment->getErrorsString());
}
if ($_POST["ajax"]) {
if (Yii::app()->user->hasFlash("error")) {
echo json_encode(array("error" => Yii::app()->user->getFlash("error")));
} else {
$view = Yii::app()->user->ini["t.iface"] == 1 ? "//blog/_comment-1" : "//blog/_comment";
$comment->is_new = true;
echo json_encode(array("id" => $comment->id, "pid" => $comment->pid, "html" => $this->renderPartial($view, array("comment" => $comment), true)));
}
} else {
$this->redirect($parent->post->url . "#cmt_" . $comment->id);
}
}
示例11: actionComment_reply
public function actionComment_reply($book_id, $chap_id, $orig_id, $comment_id = 0)
{
$orig = $this->loadOrig($book_id, $chap_id, $orig_id);
$comment_id = (int) $comment_id;
if (!$orig->chap->can("comment")) {
throw new CHttpException(403, "Вы не можете комментировать этот перевод. " . $orig->chap->getWhoCanDoIt("comment", false));
}
if (!isset($_POST["Comment"])) {
$this->redirect($orig->chap->url);
}
if ($comment_id) {
$parent = Comment::model()->with("author")->findByPk($comment_id);
if (!$parent) {
throw new CHttpException(404, "Вы пытаетесь ответить на несуществующий комментарий.");
}
} else {
$parent = new Comment();
}
$parent->orig = $orig;
$parent->orig_id = $parent->orig->id;
$comment = new Comment();
$comment->setAttributes($_POST["Comment"]);
if ($parent->reply($comment)) {
$parent->orig->afterCommentAdd($comment, $parent);
} else {
Yii::app()->user->setFlash("error", $comment->getErrorsString());
}
if ($_POST["ajax"]) {
if (Yii::app()->user->hasFlash("error")) {
echo json_encode(array("error" => Yii::app()->user->getFlash("error")));
} else {
$view = Yii::app()->user->ini["t.iface"] == 1 ? "//blog/_comment-1" : "//blog/_comment";
$comment->is_new = true;
echo json_encode(array("id" => $comment->id, "pid" => $comment->pid, "html" => $this->renderPartial($view, array("comment" => $comment), true)));
}
} else {
$this->redirect($orig->chap->url);
}
}
示例12: actionIndex
/**
* Manages all models.
*/
public function actionIndex()
{
$model = new Comment('search');
$model->unsetAttributes();
// clear any default values
$model->setAttributes(Yii::app()->getRequest()->getParam('Comment', array()));
$this->render('index', array('model' => $model));
}
示例13: actionComment_reply
public function actionComment_reply($book_id, $post_id, $comment_id = 0)
{
$post_id = (int) $post_id;
$comment_id = (int) $comment_id;
if (!isset($_POST["Comment"])) {
$this->redirect("/book/{$book_id}/announces/{$post_id}");
}
$this->loadBook($book_id);
// анонсы у нас могут все неанонимы комментировать, я так понял?
// if(!$this->book->can("blog_c")) throw new CHttpException(403, "Вы не можете оставлять комментарии в блоге этого перевода. " . $this->book->getWhoCanDoIt("blog_c"));
if ($comment_id) {
$parent = Comment::model()->with("post", "author")->findByPk($comment_id, "post_id = :post_id", array(":post_id" => $post_id));
if (!$parent) {
throw new CHttpException(404, "Вы пытаетесь ответить на несуществующий комментарий.");
}
} else {
$parent = new Comment();
$parent->post = BlogPost::model()->with("author", "seen")->findByPk($post_id);
$parent->post_id = $parent->post->id;
}
if ($parent->post->book_id != $this->book->id) {
$this->redirect($this->book->getUrl("blog/{$post_id}/c{$comment_id}/reply"));
}
$comment = new Comment();
$comment->setAttributes($_POST["Comment"]);
if ($parent->reply($comment)) {
$parent->post->afterCommentAdd($comment, $parent);
} else {
Yii::app()->user->setFlash("error", $comment->getErrorsString());
}
if ($_POST["ajax"]) {
if (Yii::app()->user->hasFlash("error")) {
echo json_encode(array("error" => Yii::app()->user->getFlash("error")));
} else {
$comment->is_new = true;
echo json_encode(array("id" => $comment->id, "pid" => $comment->pid, "html" => $this->renderPartial("//blog/_comment", array("comment" => $comment), true)));
}
} else {
$this->redirect($parent->post->url . "#cmt_" . $comment->id);
}
}
示例14: run
/**
* @inheritdoc
*/
public function run()
{
$model = new Comment();
$model->setAttributes(['model' => get_class($this->model), 'model_id' => $this->model->id]);
$this->render($this->view, ['comments' => $this->getComments(), 'model' => $model, 'redirectTo' => $this->redirectTo, 'spamField' => Yii::app()->getUser()->getState('spamField'), 'spamFieldValue' => Yii::app()->getUser()->getState('spamFieldValue'), 'module' => Yii::app()->getModule('comment')]);
}
示例15: actionPostComment
public function actionPostComment()
{
if (isset($_POST['Comment']) && Yii::app()->request->isAjaxRequest) {
$a = var_export($_POST, true);
$a = $a . "\nInit user: " . Yii::app()->user->id . "\n";
$comment = new Comment();
$comment->setAttributes($_POST['Comment']);
$comment->count = $comment->getCommentCount($_POST['Comment']['owner_name'], $_POST['Comment']['owner_id']);
$result = array();
if ($comment->save()) {
$a = $a . "Creator: " . $comment->creator_id . "\n\n\n";
file_put_contents(Yii::getPathOfAlias('webroot') . "/upload/logs/comment.log", $a, FILE_APPEND);
//if the comment status is approved or if premoderation is false, send success message
if ($comment->status === 1 || !$comment->config['premoderate']) {
$result['message'] = 'Your comment was successfully posted!';
} else {
//send success + wait message
$result['message'] = 'Your comment was successfully posted and will be visible only after it is moderated!';
}
$result['code'] = 'success';
$this->beginClip("list");
$this->widget('comments.widgets.Comments', array('model' => $comment->ownerModel, 'showPopupForm' => false));
$this->endClip();
$this->beginClip('form');
$this->widget('comments.widgets.ECommentsFormWidget', array('model' => $comment->ownerModel));
$this->endClip();
$result['list'] = $this->clips['list'];
} else {
$result['code'] = 'fail';
$result['message'] = 'Your comment could not be posted because of errors!';
$this->beginClip('form');
$this->widget('comments.widgets.ECommentsFormWidget', array('model' => $comment->ownerModel, 'validatedComment' => $comment));
$this->endClip();
}
$result['form'] = $this->clips['form'];
echo CJSON::encode($result);
}
}