Add comment.

Things to check
* The source UUID is defined
* The author UUID is defined

@return Response
177958
public function addComment()
    {
        $userIsAllowed = $this
            ->userCredentialsProvider
            ->isAllowed();
        if (!$userIsAllowed) {
            return new JsonResponse([
                'status' => 'Error',
                'message' => 'The user is not allowed to post a comment',
            ], 401);
        }

        $sourceUUID = $this->getSourceUUID();
        if (empty($sourceUUID)) {
            return new JsonResponse([
                'status' => 'Error',
                'message' => 'Source UUID header must be defined',
            ], 400);
        }

        $authorUUID = $this
            ->userCredentialsProvider
            ->getUUID();
        if (empty($authorUUID)) {
            return new JsonResponse([
                'status' => 'Error',
                'message' => 'Author UUID header must be defined',
            ], 400);
        }

        $now = new DateTime();
        $postParameterBag = $this
            ->request
            ->request;

        $authorIsModerator = $this->userCredentialsProvider->isModerator();
        $authorRole = $authorIsModerator
            ? Author::ROLE_MODERATOR
            : Author::ROLE_USER;

        $state = $authorIsModerator
            ? State::APPROVED
            : State::NEW;

        $comment = Comment::createFromArray([
            'id' => bin2hex(random_bytes(32)),
            'source' => $sourceUUID,
            'author_uuid' => $authorUUID,
            'author_name' => $this->userCredentialsProvider->getName(),
            'author_email' => $this->userCredentialsProvider->getEmail(),
            'author_avatar' => $this->userCredentialsProvider->getAvatar(),
            'author_role' => $authorRole,
            'content' => $postParameterBag->get('content'),
            'created_at' => $now->format(DATE_ATOM),
            'state' => $state,
            'rating' => (int) $postParameterBag->get('rating', 0),
        ]);

        $this
            ->commentRepository
            ->addComment($comment);
        $this->flushRepository();
        $comment->setEditable(true);

        return new JsonResponse([
            'status' => 'OK',
            'comment' => $comment->toArray(),
            'user' => $this->userCredentialsProvider->toArray(),
        ], 200);
    }
1164451
public function make_comment_header( $title, $data = array() ) {
		
		// get author
		$authors = \CCArr::get( 'authors', $data, \CCConfig::create( 'shipyard' )->get( 'defaults.authors' ) );
		
		// author
		if ( is_array( $authors ) )
		{
			foreach( $authors as $person ) 
			{
				$author_str .= $person['name']." ";
				if ( array_key_exists( 'email', $person ) ) 
				{
					$author_str .= "<".$person['email'].">";
				}
				$author_str .= ", ";
			}
			$author_str = substr( $author_str, 0, -2 );
		}
		
		return "$title\n".
			"*\n".
			"\n".
			"@package       ".\CCArr::get( 'package', $data, \CCConfig::create( 'shipyard' )->get( 'defaults.package' ) )."\n".
			"@author        ".$author_str."\n".
			"@version       ".\CCArr::get( 'version', $data, \CCConfig::create( 'shipyard' )->get( 'defaults.version' ) )."\n".
			"@copyright     ".\CCArr::get( 'copyright', $data, \CCConfig::create( 'shipyard' )->get( 'defaults.copyright' ) )."\n";
	}
265541
public function submitComment()
    {
        $answerId = (isset($_POST['answerid']) && is_numeric($_POST['answerid'])) ? $_POST['answerid'] : null;
        $postId = (isset($_POST['postid']) && is_numeric($_POST['postid'])) ? $_POST['postid'] : null;
        $comment = (isset($_POST['comment']) && strlen($_POST['comment']) > 0) ? $_POST['comment'] : null;
        $commentType = (isset($_POST['commenttype']) && strlen($_POST['commenttype']) > 0) ? $_POST['commenttype'] : null;
        $email = (isset($_POST['email']) && strlen($_POST['email']) > 0) ? $_POST['email'] : null;
        $topicId = (isset($_POST['topicid']) && is_numeric($_POST['topicid'])) ? (int)$_POST['topicid'] : null;

        $theme = wp_get_theme();
        if (!is_user_logged_in() && ($theme->name == 'Municipio' || $theme->parent_theme == 'Municipio')) {
            $response = (isset($_POST['captcha']) && strlen($_POST['captcha']) > 0) ? $_POST['captcha'] : null;
            $reCaptcha = \Municipio\Helper\ReCaptcha::controlReCaptcha($response);

            if (!$reCaptcha) {
                echo 'false';
                wp_die();
            }
        }

        if ($answerId && $postId) {
            update_post_meta($answerId, 'customer_feedback_comment', $comment);
            update_post_meta($answerId, 'customer_feedback_comment_type', $commentType);
            update_post_meta($answerId, 'customer_feedback_email', $email);
            if ($topicId) {
                wp_set_post_terms($answerId, array($topicId), 'feedback_topic');
            }

            wp_update_post(array(
                'ID' => $answerId,
                'post_status' => 'pending'
            ));

            \CustomerFeedback\Forwarding::maybeForward($answerId, $postId, $comment, $email, $topicId);

            echo 'true';
        } else {
            echo 'false';
        }

        wp_die();
    }
1169682
def marvcli_comment_add(user, message, datasets):
    """"""
    app = create_app()
    try:
        db.session.query(User).filter(User.name==user).one()
    except NoResultFound:
        click.echo("ERROR: No such user '{}'".format(user), err=True)
        sys.exit(1)
    ids = parse_setids(datasets, dbids=True)
    app.site.comment(user, message, ids)
145438
public function author()
    {
        $user = $this->getWrappedObject()->user()->withTrashed()->first(['first_name', 'last_name']);

        if ($user) {
            return $user->first_name.' '.$user->last_name;
        }
    }
429548
public function index()
    {
        $this->authorize($this->model);
        
        $comments = $this->model
            ->with(['commentable', 'user'])
            ->orderBy('id', 'desc')
            ->paginate(25);

        return $this->makeResponse('index', compact('comments'));
    }
848884
public function author() {
		$author      = get_query_var('author');
		$author_name = get_the_author_meta('display_name', $author );

		$this->addCrumb(
			$this->label( $author_name ),
			get_author_posts_url( $author )
		);
	}
357206
public function addComment(EntityInterface $entity, string $comment, string $userId = null): ModelHistory
    {
        $add = $this->add($entity, ModelHistory::ACTION_COMMENT, $userId, [
            'data' => [
                'comment' => $comment
            ]
        ]);

        return $add;
    }
302175
public function prepare_item_for_response( $comment, $request ) {
		$data = array(
			'id'                 => (int) $comment->comment_ID,
			'post'               => (int) $comment->comment_post_ID,
			'parent'             => (int) $comment->comment_parent,
			'author'             => (int) $comment->user_id,
			'author_name'        => $comment->comment_author,
			'author_email'       => $comment->comment_author_email,
			'author_url'         => $comment->comment_author_url,
			'author_ip'          => $comment->comment_author_IP,
			'author_user_agent'  => $comment->comment_agent,
			'date'               => mysql_to_rfc3339( $comment->comment_date ),
			'date_gmt'           => mysql_to_rfc3339( $comment->comment_date_gmt ),
			'content'            => array(
				'rendered' => apply_filters( 'comment_text', $comment->comment_content, $comment ),
				'raw'      => $comment->comment_content,
			),
			'karma'              => (int) $comment->comment_karma,
			'link'               => get_comment_link( $comment ),
			'status'             => $this->prepare_status_response( $comment->comment_approved ),
			'type'               => get_comment_type( $comment->comment_ID ),
		);

		$schema = $this->get_item_schema();

		if ( ! empty( $schema['properties']['author_avatar_urls'] ) ) {
			$data['author_avatar_urls'] = rest_get_avatar_urls( $comment->comment_author_email );
		}

		if ( ! empty( $schema['properties']['meta'] ) ) {
			$data['meta'] = $this->meta->get_value( $comment->comment_ID, $request );
		}

		$context = ! empty( $request['context'] ) ? $request['context'] : 'view';
		$data = $this->add_additional_fields_to_object( $data, $request );
		$data = $this->filter_response_by_context( $data, $context );

		// Wrap the data in a response object
		$response = rest_ensure_response( $data );

		$response->add_links( $this->prepare_links( $comment ) );

		/**
		 * Filter a comment returned from the API.
		 *
		 * Allows modification of the comment right before it is returned.
		 *
		 * @param WP_REST_Response  $response   The response object.
		 * @param object            $comment    The original comment object.
		 * @param WP_REST_Request   $request    Request used to generate the response.
		 */
		return apply_filters( 'rest_prepare_comment', $response, $comment, $request );
	}
113557
public function addComment($postId, $comment)
	{
		$token = $this->oauth->getToken();

		// Set parameters.
		$parameters = array(
			'oauth_token' => $token['key'],
		);

		// Set the success response code.
		$this->oauth->setOption('success_code', 201);

		// Set the API base
		$base = '/v1/posts/' . $postId . '/comments';

		// Build xml.
		$xml = '<comment><text>' . $comment . '</text></comment>';

		// Build the request path.
		$path = $this->getOption('api.url') . $base;

		$header['Content-Type'] = 'text/xml';

		// Send the request.
		$response = $this->oauth->oauthRequest($path, 'POST', $parameters, $xml, $header);

		// Return the comment id.
		$response = explode('comments/', $response->headers['Location']);

		return $response[1];
	}
713436
public function listCommentsAction($context, $source)
    {
        $comments = $this
            ->commentCache
            ->load($source, $context);

        return new Response(json_encode($comments));
    }
395200
public function show($uuid)
    {
        if ($uuid instanceof Service) {
            $uuid = $uuid->getUuid();
        }

        $response = $this->httpClient->get(
            $this->getResourceUrl($uuid),
            []
        );

        return ServiceResponse::createFromHttpResponse($response);
    }
856285
public function edit($id)
    {
        $this->loadModel('Comment.Comments');
        $comment = $this->Comments
            ->find()
            ->contain(['Users'])
            ->where(['Comments.id' => $id, 'Comments.table_alias' => $this->_manageTable])
            ->first();

        if (!$comment) {
            throw new RecordNotFoundException(__d('comment', 'Comment could not be found.'));
        }

        if ($this->request->data()) {
            $comment->accessible('*', false);
            $comment->accessible(['subject', 'body', 'author_name', 'author_email', 'author_web', 'status'], true);
            $validator = $comment->user_id ? 'default' : 'anonymous';
            $this->Comments->patchEntity($comment, $this->request->data(), ['validate' => $validator]);
            $errors = $comment->errors();

            if (empty($errors)) {
                $this->Comments->save($comment, ['associated' => false]);
                $this->Flash->success(__d('comment', 'Comment saved!.'));
                $this->redirect($this->referer());
            } else {
                $this->Flash->danger(__d('comment', 'Comment could not be saved, please check your information.'));
            }
        }

        $this->title(__d('comment', 'Editing Comment'));
        $this->set('comment', $comment);
    }
472622
def allow(self, comment, content_object, request):
        """"""
        
        POST = urlencode({
                "blog": settings.AKISMET_BLOG.encode("utf-8"),
                "user_ip": comment.ip_address,
                "user_agent": request.META.get('HTTP_USER_AGENT', "").
                                                encode("utf-8"),
                "referrer": request.META.get('HTTP_REFERRER', "").
                                                encode("utf-8"),
                "comment_author": comment.user_name.encode("utf-8"),
                "comment_author_email": comment.user_email.encode("utf-8"),
                "comment_author_url": comment.user_url.encode("utf-8"),
                "comment_content": comment.comment.encode("utf-8")})
        connection = HTTPConnection(AKISMET_URL, AKISMET_PORT)
        connection.request("POST", AKISMET_PATH, POST,
                           {"User-Agent": AKISMET_USERAGENT,
                            "Content-type":"application/x-www-form-urlencoded"
                            })
        response = connection.getresponse()
        status, result = response.status, response.read()
        if result == "false":
            return True
        elif result == "true" and settings.DISCARD_SPAM:
            return False
        elif result == "true":
            comment.is_removed = True
            comment.is_public = False
            return True
        else:
            raise AkismetError(status, result)
1150090
public function actionReply($id) {
        $comment = $this->findModel($id);
        $model = new Comment();
        $model->author_name = Yii::$app->user->identity->username;
        $model->author_email = Yii::$app->user->identity->email;
        $model->author_url = Url::base(true);
        $model->author_ip = request()->getUserIP();
        $model->obj_id = $comment->obj_id;
        $model->obj_type = $comment->obj_type;
        $model->type = $comment->type;
        $model->parent = $comment->id;
        $model->status = STATUS_PUBLIC;
        $model->author = Yii::$app->user->id;

        if ($model->loadAll(request()->post())) {
            if ($model->saveAll()) {
                set_flash_has_been_saved();
                return $this->redirect(['update', 'id' => $model->id]);
            } else {
                set_flash_has_not_been_saved();
            }
        }

        return $this->render('reply', [
            'comment' => $comment,
            'model' => $model,
        ]);

    }
905289
public function ProfileController_Comments_Create($Sender, $UserReference = '', $Username = '', $Page = '', $UserID = '') {
		$Sender->EditMode(FALSE);
		$View = $Sender->View;
      // Tell the ProfileController what tab to load
		$Sender->GetUserInfo($UserReference, $Username, $UserID);
      $Sender->_SetBreadcrumbs(T('Comments'), UserUrl($Sender->User, '', 'comments'));
      $Sender->SetTabView('Comments', 'profile', 'Discussion', 'Vanilla');
      
      $PageSize = Gdn::Config('Vanilla.Discussions.PerPage', 30);
      list($Offset, $Limit) = OffsetLimit($Page, $PageSize);
      
      $CommentModel = new CommentModel();
      $Comments = $CommentModel->GetByUser2($Sender->User->UserID, $Limit, $Offset, $Sender->Request->Get('lid'));
      $TotalRecords = $Offset + $CommentModel->LastCommentCount + 1;
      
      // Build a pager
      $PagerFactory = new Gdn_PagerFactory();
      $Sender->Pager = $PagerFactory->GetPager('MorePager', $Sender);
      $Sender->Pager->MoreCode = 'More Comments';
      $Sender->Pager->LessCode = 'Newer Comments';
      $Sender->Pager->ClientID = 'Pager';
      $Sender->Pager->Configure(
         $Offset,
         $Limit,
         $TotalRecords,
         UserUrl($Sender->User, '', 'comments').'?page={Page}' //?lid='.$CommentModel->LastCommentID
      );
      
      // Deliver JSON data if necessary
      if ($Sender->DeliveryType() != DELIVERY_TYPE_ALL && $Offset > 0) {
         $Sender->SetJson('LessRow', $Sender->Pager->ToString('less'));
         $Sender->SetJson('MoreRow', $Sender->Pager->ToString('more'));
         $Sender->View = 'profilecomments';
      }
		$Sender->SetData('Comments', $Comments);
      
      // Set the HandlerType back to normal on the profilecontroller so that it fetches it's own views
      $Sender->HandlerType = HANDLER_TYPE_NORMAL;
      
      // Do not show discussion options
      $Sender->ShowOptions = FALSE;
      
      if ($Sender->Head) {
         $Sender->Head->AddTag('meta', array('name' => 'robots', 'content' => 'noindex,noarchive'));
      }
      
      // Render the ProfileController
      $Sender->Render();
   }
1058855
protected function registerComment()
    {
        $this->app->singleton('jlourenco.comments.comment', function ($app) {
            $baseConfig = $app['config']->get('jlourenco.base');
            $config = $app['config']->get('jlourenco.comments');

            $model = array_get($config, 'models.comment');
            $users = array_get($baseConfig, 'models.User');

            if (class_exists($model) && method_exists($model, 'setUsersModel'))
                forward_static_call_array([$model, 'setUsersModel'], [$users]);

            return new CommentRepository($model);
        });
    }