Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/python
- #
- # Script responsible to create courses based on Zope Plone JSON
- # extract file.
- #
- # By: Alisson Machado
- # By: Rafael Silva
- # ==================================================================
- import subprocess, json, sys, psycopg2, os
- from lxml import etree
- import hashlib
- # Define the dabatabase connection
- DB_HOST='localhost'
- DB_USER='postgres'
- DB_PASSWORD='123456'
- DB_NAME='moodle31'
- DB_PORT=5432
- # Define the moosh command using the moodle instalation directory
- MOODLE_PATH= '/var/www/html/moodle3.1/moodle'
- SCORM_FILE_DEFAULT_PATH='/mod/scorm/tests/packages/'
- MOODLE_CMD='moosh -n -p %s'%(MOODLE_PATH)
- ##
- # Execute SQL commands
- def query_sql(sql):
- conn_str = "host=%s dbname=%s user=%s password=%s port=%s" % (DB_HOST, DB_NAME, DB_USER, DB_PASSWORD, DB_PORT)
- conn = psycopg2.connect(conn_str)
- cursor = conn.cursor()
- cursor.execute(sql)
- conn.commit()
- cursor.close()
- ##
- # Responsible to create course
- def create_course(name, fullname=None, desc=None, idnumber=None, questions=None, scorm=None):
- # Generate course create command
- _id = None
- cmd = "%s course-create" % (MOODLE_CMD)
- if desc:
- cmd = cmd + ' --description "%s"' % (desc)
- if fullname:
- cmd = cmd + ' --fullname "%s"' % (fullname)
- if idnumber:
- cmd = cmd + ' --idnumber "%s"' % (idnumber)
- cmd = cmd + ' "%s"' % (name)
- print cmd
- output = subprocess.Popen(['' + cmd], stdout=subprocess.PIPE, shell=True).communicate()
- course_id = output[0].replace('\n', '')
- # Validate whether the course was created
- if course_id:
- # Generate course settings command
- cmd = '%s course-config-set course %s format topics' % (MOODLE_CMD, course_id)
- print subprocess.Popen(['' + cmd], stdout=subprocess.PIPE, shell=True).communicate()
- # Update the database information to the Course
- # to create only two topics.
- query_sql("UPDATE mdl_course_format_options SET format='topics',value=2 WHERE courseid='%s' AND name='numsections';" % (course_id))
- query_sql("UPDATE mdl_course_format_options SET format='topics' WHERE courseid='%s' AND name='coursedisplay';" % (course_id))
- query_sql("UPDATE mdl_course_format_options SET format='topics' WHERE courseid='%s' AND name='hiddensections';" % (course_id))
- if scorm is not None:
- print 'Starting scorm creation...'
- for scorm_file in get_scorm_file_list(scorm):
- print 'file %s' % scorm_file
- # Create the Scorm inside the first topics
- cmd = '%s activity-add --section 1 --name "%s" --options "packagefile=%s" scorm "%s"' % (MOODLE_CMD, name, scorm_file, course_id)
- scorm_id = subprocess.Popen(['' + cmd], stdout=subprocess.PIPE, shell=True).communicate()[0]
- print 'Scorms createad successfully'
- # Create the Quiz inside the seconds topics
- cmd = '%s activity-add --section 2 --name "%s" quiz "%s"' % (MOODLE_CMD, name, course_id)
- quiz_id = subprocess.Popen(['' + cmd], stdout=subprocess.PIPE, shell=True).communicate()[0]
- # If passed the questions to the function
- if questions:
- import_question(quiz_id, questions)
- get_scorm_file_list(scorm['folder'])
- # That's all folks
- return course_id
- ##
- # Create an XML file based on Moodle Format
- # from the JSON file and import the questions
- # using the moosh command
- def import_question(quiz_id, questions):
- # Creating the root XML element
- root = etree.Element('quiz')
- # Creating the first questions, On moodle XML format
- # the first questions define the XML structure
- question_0 = etree.SubElement(root, "question", type='category')
- question_0_cat = etree.SubElement(question_0, 'categoy')
- etree.SubElement(question_0_cat, 'text').text = '$course$/$cat2$/Quiz'
- # GO Through each question and generate the XML element
- for q in questions:
- question = etree.SubElement(root, 'question', type='multichoice')
- name = etree.SubElement(question, 'name')
- etree.SubElement(name, 'text').text = '<![CDATA[%s]]' % (q['title'])
- questiontext = etree.SubElement(question, 'questiontext', format="html")
- etree.SubElement(questiontext, 'text').text = '<![CDATA[%s]]' % (q['title'])
- generalfeedback = etree.SubElement(question, 'generalfeedback', format='html')
- etree.SubElement(generalfeedback, 'text').text = 'Parabeens ! Voce acertou'
- etree.SubElement(question, 'defaultgrade').text = '1.0000000'
- etree.SubElement(question, 'penalty').text = '0.3333333'
- etree.SubElement(question, 'hidden').text = '0'
- etree.SubElement(question, 'single').text = 'false'
- etree.SubElement(question, 'shuffleanswert').text = 'true'
- etree.SubElement(question, 'answernumbering').text = 'abc'
- correctfeedback = etree.SubElement(question, 'correctfeedback', format='html')
- etree.SubElement(correctfeedback, 'text').text = '<![CDATA[Voce acertou todas as altenativas]]'
- partiallycorrectfeedback = etree.SubElement(question, 'partiallycorrectfeedback', format='html')
- etree.SubElement(partiallycorrectfeedback, 'text').text = '<![CDATA[Voce acertou parcialmente esta questao]]'
- incorrectfeedback = etree.SubElement(question, 'incorrectfeedback', format='html')
- etree.SubElement(incorrectfeedback, 'text').text = '<![CDATA[Respota errada ;(]]'
- for alternative in q['alternatives']:
- answer = etree.SubElement(question, 'answer', fraction='0', format='html')
- etree.SubElement(answer, 'text').text = alternative['answer']
- # print (etree.tostring(root, pretty_print=True))
- with open('/tmp/course.xml', 'w') as f:
- obj = etree.ElementTree(root)
- obj.write(f, pretty_print=True)
- def get_scorm_file_list(scorm):
- paths = [os.path.join(scorm['folder'], nome) for nome in os.listdir(scorm['folder'])]
- files = []
- name = hashlib.md5(scorm['title']).hexdigest()
- for item in paths:
- if os.path.isdir(item):
- print "Creating .zip from %s"%(item)
- command = 'zip -r %s.zip %s'%(MOODLE_PATH + SCORM_FILE_DEFAULT_PATH + name, item)
- print command
- os.system(command)
- filename = '%s.zip'%(name)
- files.append(filename)
- print "File %s created!"%('%s.zip'%(name))
- return files
- if __name__ == '__main__':
- # validate the json_file
- if len(sys.argv) != 2:
- print "Usage: %s <json_file>.json" % (sys.argv[0])
- sys.exit(1)
- # Read json and parser to python dict array
- with open(sys.argv[1], 'r') as f:
- j = json.loads(f.read())
- # go thorugh each courses on the dict from json
- for curso in j.get('cursos'):
- print 'Creating course: ', curso.get('title')
- questions_info = None
- scorm_info = None
- if 'quiz' in curso:
- quiz = curso['quiz']
- if 'questions' in 'quiz':
- questions_info = quiz['questions']
- if 'scorm' in curso:
- scorm_info = curso['scorm']
- create_course(curso.get('title'), questions = questions_info, scorm = scorm_info)
- # That's all folks
- print "Script finished successfully"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement