From f4daa0f9372166de9c04f3c0490b624dfb0eafb9 Mon Sep 17 00:00:00 2001
From: Friederike Schwager <schwager@itc.rwth-aachen.de>
Date: Mon, 16 Mar 2020 09:30:25 +0100
Subject: [PATCH] print comments with Moodle Latex API format_text() after
 retrieving comments from DB and not before inserting

---
 action.php               | 18 +++++++++---
 lang/en/pdfannotator.php |  1 +
 locallib.php             | 61 ++++++++++++++++++++++------------------
 model/comment.class.php  |  3 ++
 shared/index.js          | 39 ++++++++++++++++++++++---
 5 files changed, 86 insertions(+), 36 deletions(-)

diff --git a/action.php b/action.php
index 39c9b41..8c2049f 100644
--- a/action.php
+++ b/action.php
@@ -327,7 +327,6 @@ if ($action === 'addComment') {
 
     // Get the comment data.
     $content = required_param('content', PARAM_RAW);
-    $content = format_text($content, $format = FORMAT_MOODLE, $options = ['para' => false]);
     $visibility = required_param('visibility', PARAM_ALPHA);
     $isquestion = required_param('isquestion', PARAM_INT);
 
@@ -388,6 +387,18 @@ if ($action === 'getComments') {
     echo json_encode($data);
 }
 
+/* * ********************************* Retrieve content of a specific comment from db ********************************* */
+
+if ($action === 'getCommentContent') {
+    global $DB;
+    $commentid = required_param('commentId', PARAM_INT);
+
+    $content = $DB->get_field('pdfannotator_comments', 'content', ['id' => $commentid]);
+
+
+    echo json_encode($content);
+}
+
 /* * ****************************************** Hide a comment for participants ****************************************** */
 
 if ($action === 'hideComment') {
@@ -428,9 +439,8 @@ if ($action === 'editComment') {
     $editanypost = has_capability('mod/pdfannotator:editanypost', $context);
 
     $commentid = required_param('commentId', PARAM_INT);
-    $content = required_param('content', PARAM_RAW);
-    $content = format_text($content, $format = FORMAT_MOODLE, $options = ['para' => false]);
-    
+    $content = required_param('content', PARAM_RAW);    
+        
     $data = pdfannotator_comment::update($commentid, $content, $editanypost);
     echo json_encode($data);
 }
diff --git a/lang/en/pdfannotator.php b/lang/en/pdfannotator.php
index b0b8288..d53ead6 100644
--- a/lang/en/pdfannotator.php
+++ b/lang/en/pdfannotator.php
@@ -113,6 +113,7 @@ $string['error:missingAnnotationtype'] = 'Annotationtype does not exists. Possib
 $string['error:openingPDF'] = 'An error occurred while opening the PDF file.';
 $string['error:openprintview'] = 'An error has occured while trying to open the pdf in Acrobat Reader.';
 $string['error:printcomments'] = 'An error has occured while trying to open the comments in a pdf.';
+$string['error:printlatex'] = 'An error has occured while trying to add a LaTeX formula to the pdf.';
 $string['error:redisplayComment'] = 'An error has occured while redisplaying the comment.';
 $string['error:renderPage'] = 'An error has occured while rendering the page.';
 $string['error:reportComment'] = 'An error has occured while saving the report.';
diff --git a/locallib.php b/locallib.php
index e02d956..3a2e921 100644
--- a/locallib.php
+++ b/locallib.php
@@ -158,6 +158,35 @@ SIGN;
     foreach ($matches as $match) {
         $formulalength = strlen($match[0]);
         $formulaoffset = $match[1];
+        $string = $match[0];
+        $string = str_replace('\xrightarrow', '\rightarrow', $string);
+        $string = str_replace('\xlefttarrow', '\leftarrow', $string);
+
+        $pos = strpos($string, '\\[');
+        if ($pos !== false) {
+            $string = substr_replace($string, '', $pos, strlen('\\['));
+        }
+
+        $pos = strpos($string, '\\(');
+        if ($pos !== false) {
+            $string = substr_replace($string, '', $pos, strlen('\\('));
+        }
+
+        $string = str_replace('\\]', '', $string);
+
+        $string = str_replace('\\)', '', $string);
+
+        $string = str_replace('\begin{aligned}', '', $string);
+        $string = str_replace('\end{aligned}', '', $string);
+
+        $string = str_replace('\begin{align*}', '', $string);
+        $string = str_replace('\end{align*}', '', $string);
+
+        // Find any backslash preceding a ( or [ and replace it with \backslash
+        $pattern = '~\\\\(?=[\\\(\\\[])~';
+        $string = preg_replace($pattern, '\\backslash', $string);
+        $match[0] = $string;
+
         $result[] = trim(substr($subject, $textstart, $formulaoffset - $textstart));
         if($latexapi == LATEX_TO_PNG_GOOGLE_API) {
             $result[] = pdfannotator_process_latex_google($match[0]);
@@ -181,6 +210,9 @@ function pdfannotator_process_latex_moodle($context, $string) {
     $tex = new latex();
     $md5 = md5($string);
     $image = $tex->render($string, $md5 . 'png');
+    if($image == false) {
+        return false;
+    }
     $imagedata = file_get_contents($image);
     $result['image'] = IMAGE_PREFIX . base64_encode($imagedata);
     //imageinfo returns an array with the info of the size of the image. In Parameter 1 there is the height, which is the only thing needed here
@@ -196,35 +228,8 @@ function pdfannotator_process_latex_moodle($context, $string) {
  * @return type
  */
 function pdfannotator_process_latex_google(string $string) {
-    $string = str_replace('\xrightarrow', '\rightarrow', $string);
-    $string = str_replace('\xlefttarrow', '\leftarrow', $string);
-
-    $pos = strpos($string, '\\[');
-    if ($pos !== false) {
-        $string = substr_replace($string, '', $pos, strlen('\\['));
-    }
-
-    $pos = strpos($string, '\\(');
-    if ($pos !== false) {
-        $string = substr_replace($string, '', $pos, strlen('\\('));
-    }
-
-    $string = str_replace('\\]', '', $string);
-
-    $string = str_replace('\\)', '', $string);
-
-    $string = str_replace('\begin{aligned}', '', $string);
-    $string = str_replace('\end{aligned}', '', $string);
-
-    $string = str_replace('\begin{align*}', '', $string);
-    $string = str_replace('\end{align*}', '', $string);
-
-    // Find any backslash preceding a ( or [ and replace it with \backslash
-    $pattern = '~\\\\(?=[\\\(\\\[])~';
-    $string = preg_replace($pattern, '\\backslash', $string);
-
+    
     $length = strlen($string);
-
     $im = null;
     if ($length <= 200) { // Google API constraint XXX find better alternative if possible.
         $latexdata = urlencode($string);
diff --git a/model/comment.class.php b/model/comment.class.php
index 6c37987..e856ac6 100644
--- a/model/comment.class.php
+++ b/model/comment.class.php
@@ -66,6 +66,7 @@ class pdfannotator_comment {
             } else {
                 $datarecord->username = get_string('me', 'pdfannotator');
             }
+            $datarecord->content = format_text($datarecord->content, $format = FORMAT_MOODLE, $options = ['para' => false]);
             $datarecord->timecreated = pdfannotator_optional_timeago($datarecord->timecreated);
             $datarecord->timemodified = pdfannotator_optional_timeago($datarecord->timemodified);
             $datarecord->usevotes = pdfannotator_instance::use_votes($documentid);
@@ -186,6 +187,7 @@ class pdfannotator_comment {
                 $comment->content = get_string('deletedComment', 'pdfannotator');
             } else {
                 $comment->content = $data->content;
+                $comment->content = format_text($data->content, $format = FORMAT_MOODLE, $options = ['para' => false]);
             }
             $comment->userid = $data->userid; // Author of comment.
             self::set_username($comment);
@@ -401,6 +403,7 @@ class pdfannotator_comment {
         }
 
         if ($success) {
+            $content = format_text($content, $format = FORMAT_MOODLE, $options = ['para' => false]);
             $result = array('status' => 'success', 'timemodified' => $time, 'newContent' => $content);
             if ($comment->userid != $USER->id) {
                 $result['modifiedby'] = pdfannotator_get_username($USER->id);
diff --git a/shared/index.js b/shared/index.js
index 4f75b7d..cc15f5e 100644
--- a/shared/index.js
+++ b/shared/index.js
@@ -491,6 +491,23 @@ function startIndex(Y,_cm,_documentObject,_userid,_capabilities, _toolbarSetting
                     return JSON.parse(data);
                 });
             },
+            
+            /**
+             * Gets the content of a specific comment.
+             * @param {type} documentId
+             * @param {type} commentId
+             * @returns {unresolved}
+             */
+            getCommentContent(documentId, commentId){
+                return $.ajax({
+                    type: "POST",
+                    url: "action.php",
+                    data: { "documentId": documentId, "commentId": commentId, "action": 'getCommentContent', sesskey: M.cfg.sesskey}
+                }).then(function(data){
+                    return JSON.parse(data);
+                });
+            },
+
 
             /**
              * This function collects all Questions (Annotations with min. one comment)
@@ -847,8 +864,14 @@ function startIndex(Y,_cm,_documentObject,_userid,_capabilities, _toolbarSetting
                                     function printItem(item, index) {
                                         if (typeof item === "object") { //item.includes('data:image/png;base64,')) {
                                             printImage(item);
-                                        } else {
+                                        } else if (typeof item === "string"){
                                             printTextblock(null, null, item);
+                                        } else {
+                                            console.error(M.util.get_string('error:printlatex', 'pdfannotator'));
+                                            notification.addNotification({
+                                                message: M.util.get_string('error:printlatex','pdfannotator'),
+                                                type: "error"
+                                            });
                                         }
                                     }
                                     /**
@@ -1732,9 +1755,12 @@ function startIndex(Y,_cm,_documentObject,_userid,_capabilities, _toolbarSetting
                     var editArea = document.getElementById("editarea"+comment.uuid);
                     var text = document.getElementById("chatmessage"+comment.uuid);
                     if (editForm.style.display === "none") {
-                        editArea.innerHTML = comment.content;
-                        editForm.style.display = "block";
-                        text.innerHTML = "";
+                        _2.default.getStoreAdapter().getCommentContent(documentId, comment.uuid)
+                            .then(function(content){
+                                editArea.innerHTML = content;
+                                editForm.style.display = "block";
+                                text.innerHTML = "";
+                            });
                         // Add an event handler to the form for submitting any changes to the database.
                         editForm.onsubmit = function (e) {
                             let newContent = editArea.value.trim();
@@ -3478,6 +3504,11 @@ function startIndex(Y,_cm,_documentObject,_userid,_capabilities, _toolbarSetting
                                 (0,_abstractFunction2.default)('getComments');
                             }
                         },
+                        
+                        {key:'getCommentContent',value:function getCommentContent(documentId,commentId){
+                                (0,_abstractFunction2.default)('getCommentContent');
+                            }
+                        },
                         /**
                         * Get all the questions of one page
                         *
-- 
GitLab