Public: Save new comment into database

Returns id of new comment
964817
public function save()
    {
        // Email address validation tests are NOT handled here as different workflows may have different rules for auto validation
        $app = App::getInstance();

        // If an update
        if ($this->pk && $this->fields[$this->pk]->getValue()) {
            return parent::save();
        }

        $this->setIp($app['env']['RemoteIP']);
        $this->setUseragent($app['env']['RemoteUA']);
        $this->setReferer($app['env']['Referer']);

        if (!$this->getUser()) {
            // check key
            $key_check = $app['akismet']->keyCheck(
                $app->getOption('akismet_api_key', ''),
                $app->getOption('base_url')
            );

            if ($key_check == false) {
                throw new \FelixOnline\Exceptions\InternalException('Akismet key is invalid');
            }

            // check spam using akismet
            $check = $app['akismet']->check(array(
                'permalink' => $this->getArticle()->getURL(),
                'comment_type' => 'comment',
                'comment_author' => $this->fields['name']->getValue(),
                'comment_content' => $this->getComment(),
                'comment_author_email' => $this->getEmail(),
                'user_ip' => $this->getIp(),
                'user_agent' => $this->getUseragent(),
                'referrer' => $this->getReferer(),
            ));

            // check for akismet errors
            if (!is_null($app['akismet']->getError())) {
                throw new \FelixOnline\Exceptions\InternalException($app['akismet']->getError());
            }

            if ($check == true) { // if comment is spam
                $this->setActive(0);
                $this->setPending(0);
                $this->setSpam(1);
            } else { // Not spam
                $this->setActive(1);
                $this->setPending(1);
                $this->setSpam(0);
            }
        } else {
            $this->setActive(1);
            $this->setPending(0);
            $this->setSpam(0);
        }

        parent::save();

        if (!$this->getSpam()) {
            // Send emails
            if (!$this->getUser()) {
                $log_entry = new \FelixOnline\Core\AkismetLog();
                $log_entry->setCommentId($this)
                    ->setAction('check')
                    ->setIsSpam($check)
                    ->setError($app['akismet']->getError())
                    ->save();

                // If pending comment
                if (!$this->getSpam() && $this->getPending() && $this->getActive()) {
                    $this->emailComment();
                }
            }
        }

        return $this->getId(); // return new comment id
    }
331108
def add_comment(self, body, allow_create=False, allow_hashes=False,
                    summary=None):
        
        thread_id = self.lookup_thread_id()
        if not allow_create and not self.redis.exists(thread_id):
            raise ValueError('Tried to add comment to non-exist thread %s' % (
                thread_id))

        comment = comments.SingleComment(
            self.user, datetime.datetime.now(datetime.timezone.utc), body, 
            summary=summary)
        lpush = self.redis.lpush(thread_id, comment.to_json())
        logging.debug('Pushing comment to redis returned %s', str(lpush))
        if self.ltrim:
            ltrim = self.redis.ltrim(thread_id, 0, self.ltrim)
            logging.debug('Redis ltrim returend %s', str(ltrim))
        else:
            ltrim = None

        return {'status': 'OK', 'lpush': lpush, 'ltrim': ltrim}
202191
public function save()
    {
        // Can only update the name and output_params
        $params = array('id' => $this->getId(), 'name' => $this->getName());
        foreach ($this->_output_params as $key => $val) {
            $params[DataSift_Push_Definition::OUTPUT_PARAMS_PREFIX . $key] = $val;
        }

        // Call the API and pass the returned object into init to update this object
        $this->init($this->_user->post('push/update', $params));
    }
920140
def create_request_comment(self, issue_id_or_key, body, public=True):
        
        log.warning('Creating comment...')
        data = {"body": body, "public": public}

        return self.post('rest/servicedeskapi/request/{}/comment'.format(issue_id_or_key), data=data)
781422
def create_comment(ticket_id, input, options = {})
      make_request("tickets/#{ticket_id}", ({:update => Zendesk::Main.to_xml('comment', input)}), options)
    end
975941
def save(self, *args, **kwargs):
        
        if not self.id:
            self.is_public = settings.COMMENTS_DEFAULT_APPROVED
            self.site_id = current_site_id()
        super(ThreadedComment, self).save(*args, **kwargs)
1190390
def _get_comments_to_export(self, last_export_id=None):
        """"""
        qs = comments.get_model().objects.order_by('pk')\
                .filter(is_public=True, is_removed=False)
        if last_export_id is not None:
            print("Resuming after comment %s" % str(last_export_id))
            qs = qs.filter(id__gt=last_export_id)
        return qs
1081180
def commit_comment(self, comment_id):
        
        url = self._build_url('comments', str(comment_id), base_url=self._api)
        json = self._json(self._get(url), 200)
        return RepoComment(json, self) if json else None
1115918
def add(self, post_id):
        '''
        
        '''
        post_data = self.get_post_data()

        post_data['user_name'] = self.userinfo.user_name
        post_data['user_id'] = self.userinfo.uid
        post_data['post_id'] = post_id
        replyid = MReply.create_reply(post_data)
        if replyid:
            out_dic = {'pinglun': post_data['cnt_reply'],
                       'uid': replyid}
            logger.info('add reply result dic: {0}'.format(out_dic))
            return json.dump(out_dic, self)
1160932
function () {
                var comment;

                if (input.charAt(i) !== '/') { return; }

                if (input.charAt(i + 1) === '/') {
                    return new(tree.Comment)($re(/^\/\/.*/), true, i, env.currentFileInfo);
                }
                comment = $re(/^\/\*(?:[^*]|\*+[^\/*])*\*+\/\n?/);
                if (comment) {
                    return new(tree.Comment)(comment, false, i, env.currentFileInfo);
                }
            }
827294
function getComments(comments) {
  if (!comments || !comments.body) return {};

  Object.assign(comments, {
    create_time: formatTime(comments.created_at),
    update_time: formatTime(comments.updated_at)
  })

  return comments;
}
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();
    }
643486
def set_comment(self, key_name, new_comment):
        """"""
        kf = self.dct[key_name]
        kf['comment'] = new_comment
1144271
def post_comment(request, next=None, using=None):
    
    # Fill out some initial data fields from an authenticated user, if present
    data = request.POST.copy()
    if request.user.is_authenticated:
        data["user"] = request.user
    else:
        return CommentPostBadRequest("You must be logged in to comment")

    # Look up the object we're trying to comment about
    ctype = data.get("content_type")
    object_pk = data.get("object_pk")
    if ctype is None or object_pk is None:
        return CommentPostBadRequest("Missing content_type or object_pk field.")
    try:
        model = models.get_model(*ctype.split(".", 1))
        target = model._default_manager.using(using).get(pk=object_pk)
    except TypeError:
        return CommentPostBadRequest(
            "Invalid content_type value: %r" % escape(ctype))
    except AttributeError:
        return CommentPostBadRequest(
            "The given content-type %r does not resolve to a valid model." % \
                escape(ctype))
    except ObjectDoesNotExist:
        return CommentPostBadRequest(
            "No object matching content-type %r and object PK %r exists." % \
                (escape(ctype), escape(object_pk)))
    except (ValueError, ValidationError) as e:
        return CommentPostBadRequest(
            "Attempting go get content-type %r and object PK %r exists raised %s" % \
                (escape(ctype), escape(object_pk), e.__class__.__name__))

    # Construct the comment form
    form = comments.get_form()(target, data=data)

    # Check security information
    if form.security_errors():
        return CommentPostBadRequest(
            "The comment form failed security verification: %s" % \
                escape(str(form.security_errors())))

    # Check for next
    if not next:
        next = data.get("next")

    # If there are errors show the comment
    if form.errors:
        template_list = [
            "comments/%s/%s/form.html" % (model._meta.app_label, model._meta.module_name),
            "comments/%s/form.html" % model._meta.app_label,
            "comments/form.html",
        ]
        return render_to_response(
            template_list, {
                "comment": form.data.get("comment", ""),
                "form": form,
                "next": data.get("next", next),
            },
            RequestContext(request, {})
        )

    # Otherwise create the comment
    comment = form.get_comment_object()
    comment.ip_address = request.META.get("REMOTE_ADDR", None)
    if request.user.is_authenticated:
        comment.user = request.user

    # Signal that the comment is about to be saved
    responses = signals.comment_will_be_posted.send(
        sender=comment.__class__,
        comment=comment,
        request=request
    )

    for (receiver, response) in responses:
        if response == False:
            return CommentPostBadRequest(
                "comment_will_be_posted receiver %r killed the comment" % receiver.__name__)

    # Save the comment and signal that it was saved
    comment.save()
    signals.comment_was_posted.send(
        sender=comment.__class__,
        comment=comment,
        request=request
    )
    messages.success(request, 'Your comment was saved.')
    return redirect(next)
1029968
function save_post( $post_id )
	{	
		
		// do not save if this is an auto save routine
		if( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE )
		{
			return $post_id;
		}
		
		
		// verify nonce
		if( !isset($_POST['acf_nonce'], $_POST['fields']) || !wp_verify_nonce($_POST['acf_nonce'], 'input') )
		{
			return $post_id;
		}
		
		
		// if save lock contains a value, the save_post action is already running for another post.
		// this would imply that the user is hooking into an ACF update_value or save_post action and inserting a new post
		// if this is the case, we do not want to save all the $POST data to this post.
		if( isset($GLOBALS['acf_save_lock']) && $GLOBALS['acf_save_lock'] )
		{
			return $post_id;
		}
		
		
		// update the post (may even be a revision / autosave preview)
		do_action('acf/save_post', $post_id);
        
	}
1185321
def check_for_duplicate_comment(self, new):
        
        possible_duplicates = self.get_comment_model()._default_manager.using(
            self.target_object._state.db
        ).filter(
            content_type=new.content_type,
            object_pk=new.object_pk
        )
        for old in possible_duplicates:
            if old.post_date.date() == new.post_date.date() and old.text == new.text:
                return old

        return new
446428
def query_get_comment(comID):
    
    query1 = """SELECT id,
                       id_bibrec,
                       id_user,
                       body,
                       """ + \
        datetime_format('date_creation') + ', ' \
        """
                       star_score,
                       nb_votes_yes,
                       nb_votes_total,
                       title,
                       nb_abuse_reports,
                       round_name,
                       restriction
                FROM "cmtRECORDCOMMENT"
                WHERE id=%s"""
    params1 = (comID,)
    res1 = run_sql(query1, params1)
    if len(res1) > 0:
        return res1[0]
    else:
        return ()