Advertisement
Guest User

Untitled

a guest
Aug 17th, 2016
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 7.16 KB | None | 0 0
  1. #!/usr/bin/python
  2. #
  3. # Script responsible to create courses based on Zope Plone JSON
  4. # extract file.
  5. #
  6. # By: Alisson Machado
  7. # By: Rafael Silva
  8. # ==================================================================
  9. import subprocess, json, sys, psycopg2, os
  10. from lxml import etree
  11. import hashlib
  12.  
  13. # Define the dabatabase connection
  14. DB_HOST='localhost'
  15. DB_USER='postgres'
  16. DB_PASSWORD='123456'
  17. DB_NAME='moodle31'
  18. DB_PORT=5432
  19.  
  20. # Define the moosh command using the moodle instalation directory
  21. MOODLE_PATH= '/var/www/html/moodle3.1/moodle'
  22. SCORM_FILE_DEFAULT_PATH='/mod/scorm/tests/packages/'
  23.  
  24. MOODLE_CMD='moosh -n -p %s'%(MOODLE_PATH)
  25.  
  26. ##
  27. # Execute SQL commands
  28. def query_sql(sql):
  29. conn_str = "host=%s dbname=%s user=%s password=%s port=%s" % (DB_HOST, DB_NAME, DB_USER, DB_PASSWORD, DB_PORT)
  30. conn = psycopg2.connect(conn_str)
  31. cursor = conn.cursor()
  32. cursor.execute(sql)
  33. conn.commit()
  34. cursor.close()
  35.  
  36. ##
  37. # Responsible to create course
  38. def create_course(name, fullname=None, desc=None, idnumber=None, questions=None, scorm=None):
  39.  
  40. # Generate course create command
  41. _id = None
  42. cmd = "%s course-create" % (MOODLE_CMD)
  43. if desc:
  44. cmd = cmd + ' --description "%s"' % (desc)
  45. if fullname:
  46. cmd = cmd + ' --fullname "%s"' % (fullname)
  47. if idnumber:
  48. cmd = cmd + ' --idnumber "%s"' % (idnumber)
  49. cmd = cmd + ' "%s"' % (name)
  50. print cmd
  51. output = subprocess.Popen(['' + cmd], stdout=subprocess.PIPE, shell=True).communicate()
  52. course_id = output[0].replace('\n', '')
  53.  
  54. # Validate whether the course was created
  55. if course_id:
  56. # Generate course settings command
  57. cmd = '%s course-config-set course %s format topics' % (MOODLE_CMD, course_id)
  58. print subprocess.Popen(['' + cmd], stdout=subprocess.PIPE, shell=True).communicate()
  59.  
  60. # Update the database information to the Course
  61. # to create only two topics.
  62. query_sql("UPDATE mdl_course_format_options SET format='topics',value=2 WHERE courseid='%s' AND name='numsections';" % (course_id))
  63. query_sql("UPDATE mdl_course_format_options SET format='topics' WHERE courseid='%s' AND name='coursedisplay';" % (course_id))
  64. query_sql("UPDATE mdl_course_format_options SET format='topics' WHERE courseid='%s' AND name='hiddensections';" % (course_id))
  65.  
  66. if scorm is not None:
  67. print 'Starting scorm creation...'
  68. for scorm_file in get_scorm_file_list(scorm):
  69. print 'file %s' % scorm_file
  70. # Create the Scorm inside the first topics
  71. cmd = '%s activity-add --section 1 --name "%s" --options "packagefile=%s" scorm "%s"' % (MOODLE_CMD, name, scorm_file, course_id)
  72. scorm_id = subprocess.Popen(['' + cmd], stdout=subprocess.PIPE, shell=True).communicate()[0]
  73.  
  74. print 'Scorms createad successfully'
  75.  
  76.  
  77. # Create the Quiz inside the seconds topics
  78. cmd = '%s activity-add --section 2 --name "%s" quiz "%s"' % (MOODLE_CMD, name, course_id)
  79. quiz_id = subprocess.Popen(['' + cmd], stdout=subprocess.PIPE, shell=True).communicate()[0]
  80.  
  81. # If passed the questions to the function
  82. if questions:
  83. import_question(quiz_id, questions)
  84. get_scorm_file_list(scorm['folder'])
  85. # That's all folks
  86. return course_id
  87.  
  88.  
  89. ##
  90. # Create an XML file based on Moodle Format
  91. # from the JSON file and import the questions
  92. # using the moosh command
  93. def import_question(quiz_id, questions):
  94. # Creating the root XML element
  95. root = etree.Element('quiz')
  96.  
  97. # Creating the first questions, On moodle XML format
  98. # the first questions define the XML structure
  99. question_0 = etree.SubElement(root, "question", type='category')
  100. question_0_cat = etree.SubElement(question_0, 'categoy')
  101. etree.SubElement(question_0_cat, 'text').text = '$course$/$cat2$/Quiz'
  102.  
  103. # GO Through each question and generate the XML element
  104. for q in questions:
  105. question = etree.SubElement(root, 'question', type='multichoice')
  106. name = etree.SubElement(question, 'name')
  107. etree.SubElement(name, 'text').text = '<![CDATA[%s]]' % (q['title'])
  108.  
  109. questiontext = etree.SubElement(question, 'questiontext', format="html")
  110. etree.SubElement(questiontext, 'text').text = '<![CDATA[%s]]' % (q['title'])
  111.  
  112. generalfeedback = etree.SubElement(question, 'generalfeedback', format='html')
  113. etree.SubElement(generalfeedback, 'text').text = 'Parabeens ! Voce acertou'
  114.  
  115. etree.SubElement(question, 'defaultgrade').text = '1.0000000'
  116. etree.SubElement(question, 'penalty').text = '0.3333333'
  117. etree.SubElement(question, 'hidden').text = '0'
  118. etree.SubElement(question, 'single').text = 'false'
  119. etree.SubElement(question, 'shuffleanswert').text = 'true'
  120. etree.SubElement(question, 'answernumbering').text = 'abc'
  121.  
  122. correctfeedback = etree.SubElement(question, 'correctfeedback', format='html')
  123. etree.SubElement(correctfeedback, 'text').text = '<![CDATA[Voce acertou todas as altenativas]]'
  124.  
  125. partiallycorrectfeedback = etree.SubElement(question, 'partiallycorrectfeedback', format='html')
  126. etree.SubElement(partiallycorrectfeedback, 'text').text = '<![CDATA[Voce acertou parcialmente esta questao]]'
  127.  
  128. incorrectfeedback = etree.SubElement(question, 'incorrectfeedback', format='html')
  129. etree.SubElement(incorrectfeedback, 'text').text = '<![CDATA[Respota errada ;(]]'
  130.  
  131. for alternative in q['alternatives']:
  132. answer = etree.SubElement(question, 'answer', fraction='0', format='html')
  133. etree.SubElement(answer, 'text').text = alternative['answer']
  134.  
  135. # print (etree.tostring(root, pretty_print=True))
  136. with open('/tmp/course.xml', 'w') as f:
  137. obj = etree.ElementTree(root)
  138. obj.write(f, pretty_print=True)
  139.  
  140.  
  141. def get_scorm_file_list(scorm):
  142.  
  143. paths = [os.path.join(scorm['folder'], nome) for nome in os.listdir(scorm['folder'])]
  144. files = []
  145. name = hashlib.md5(scorm['title']).hexdigest()
  146.  
  147. for item in paths:
  148. if os.path.isdir(item):
  149. print "Creating .zip from %s"%(item)
  150. command = 'zip -r %s.zip %s'%(MOODLE_PATH + SCORM_FILE_DEFAULT_PATH + name, item)
  151. print command
  152. os.system(command)
  153. filename = '%s.zip'%(name)
  154.  
  155. files.append(filename)
  156. print "File %s created!"%('%s.zip'%(name))
  157.  
  158. return files
  159.  
  160. if __name__ == '__main__':
  161.  
  162. # validate the json_file
  163. if len(sys.argv) != 2:
  164. print "Usage: %s <json_file>.json" % (sys.argv[0])
  165. sys.exit(1)
  166.  
  167. # Read json and parser to python dict array
  168. with open(sys.argv[1], 'r') as f:
  169. j = json.loads(f.read())
  170.  
  171. # go thorugh each courses on the dict from json
  172. for curso in j.get('cursos'):
  173. print 'Creating course: ', curso.get('title')
  174.  
  175. questions_info = None
  176. scorm_info = None
  177.  
  178. if 'quiz' in curso:
  179. quiz = curso['quiz']
  180. if 'questions' in 'quiz':
  181. questions_info = quiz['questions']
  182.  
  183. if 'scorm' in curso:
  184. scorm_info = curso['scorm']
  185.  
  186. create_course(curso.get('title'), questions = questions_info, scorm = scorm_info)
  187.  
  188. # That's all folks
  189. print "Script finished successfully"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement