/**
  * Used by mod_forumng_post when creating a reply. Do not call directly.
  * @param mod_forumng_post $parentpost Parent post object (NULL when creating root post)
  * @param string $subject Subject
  * @param string $message Message
  * @param int $format Moodle format used for message
  * @param bool $attachments True if post contains attachments
  * @param bool $setimportant If true, highlight the post
  * @param bool $mailnow If true, sends mail ASAP
  * @param int $userid User ID (0 = current)
  *
  * @return int ID of newly-created post
  */
 function create_reply($parentpost, $subject, $message, $format, $attachments = false, $setimportant = false, $mailnow = false, $userid = 0)
 {
     global $DB;
     $userid = mod_forumng_utils::get_real_userid($userid);
     // Prepare post object
     $postobj = new StdClass();
     $postobj->discussionid = $this->discussionfields->id;
     $postobj->parentpostid = $parentpost ? $parentpost->get_id() : null;
     $postobj->userid = $userid;
     $postobj->created = time();
     $postobj->modified = $postobj->created;
     $postobj->deleted = 0;
     $postobj->mailstate = $mailnow ? mod_forumng::MAILSTATE_NOW_NOT_MAILED : mod_forumng::MAILSTATE_NOT_MAILED;
     $postobj->important = $setimportant ? 1 : 0;
     $postobj->oldversion = 0;
     $postobj->edituserid = null;
     $postobj->subject = strlen(trim($subject)) == 0 ? null : $subject;
     $postobj->message = $message;
     $postobj->messageformat = $format;
     $postobj->attachments = $attachments ? 1 : 0;
     $transaction = $DB->start_delegated_transaction();
     // Create post
     $postobj->id = $DB->insert_record('forumng_posts', $postobj);
     $post = new mod_forumng_post($this, $postobj);
     // For replies, update last post id
     if ($parentpost) {
         $discussionchange = new stdClass();
         $discussionchange->id = $parentpost->get_discussion()->get_id();
         $discussionchange->lastpostid = $postobj->id;
         $DB->update_record('forumng_discussions', $discussionchange);
     }
     // Update search index (replies only)
     if ($parentpost) {
         $post->search_update();
     }
     // Update completion state
     $post->update_completion(true);
     // Outside the catch so we don't commit transaction if something
     // fails
     $transaction->allow_commit();
     return $post->get_id();
 }