From 26402ad8935a8a43117283d98ee1cee3a769d13b Mon Sep 17 00:00:00 2001
From: Tyler Bannister <tyler.bannister@remote-learner.net>
Date: Fri, 25 Nov 2011 11:35:31 -0500
Subject: [PATCH] PREPCL-560 - Fix for question answer carriage return restore problem.

---
 backup/moodle2/restore_qtype_plugin.class.php |   19 +++++++++++++------
 1 files changed, 13 insertions(+), 6 deletions(-)

diff --git a/backup/moodle2/restore_qtype_plugin.class.php b/backup/moodle2/restore_qtype_plugin.class.php
index 42c6c1d..846816c 100644
--- a/backup/moodle2/restore_qtype_plugin.class.php
+++ b/backup/moodle2/restore_qtype_plugin.class.php
@@ -109,6 +109,7 @@ abstract class restore_qtype_plugin extends restore_plugin {
 
         $data = (object)$data;
         $oldid = $data->id;
+        $newitemid = 0;
 
         // Detect if the question is created or mapped
         $oldquestionid   = $this->get_old_parentid('question');
@@ -143,12 +144,18 @@ abstract class restore_qtype_plugin extends restore_plugin {
         // The question existed, we need to map the existing question_answers
         } else {
             // Look in question_answers by answertext matching
-            $sql = 'SELECT id
-                      FROM {question_answers}
-                     WHERE question = ?
-                       AND ' . $DB->sql_compare_text('answer', 255) . ' = ' . $DB->sql_compare_text('?', 255);
-            $params = array($newquestionid, $data->answertext);
-            $newitemid = $DB->get_field_sql($sql, $params);
+            $params = array('question' => $newquestionid);
+            $answers = $DB->get_records('question_answers', $params, '', 'id, answer');
+
+            if (is_array($answers)) {
+                foreach ($answers as $answer) {
+                    $clean = preg_replace('/[\x-\x8\xb-\xc\xe-\x1f\x7f]/is','', $answer->answer); // clean CTRL chars
+                    $clean = preg_replace("/\r\n|\r/", "\n", $clean); // Normalize line ending
+                    if ($clean === $data->answertext) {
+                        $newitemid = $data->id;
+                    }
+                }
+            }
             // If we haven't found the newitemid, something has gone really wrong, question in DB
             // is missing answers, exception
             if (!$newitemid) {
-- 
1.7.4.1

