Пример #1
0
    def __init__(self):
        '''
        First read the system webquizrc file and then read the
        to use some system settings and to override others.

        By default, there is no webquiz initialisation file. We first
        look for webquizrc in the webquiz source directory and then
        for .webquizrc file in the users home directory.
        '''
        self.settings['version']['default'] = metadata.version
        for key in self.settings:
            self.settings[key]['value'] = self.settings[key]['default']
            if not 'editable' in self.settings[key]:
                self.settings[key]['editable'] = False

        # define user and system rc file and load the ones that exist

        TEXMFLOCAL = ''
        try:
            TEXMFLOCAL = webquiz_util.kpsewhich('-var-value TEXMFLOCAL')
        except subprocess.CalledProcessError:
            pass

        if TEXMFLOCAL == '':
            TEXMFLOCAL = webquiz_util.kpsewhich('-var-value TEXMFMAIN')

        self.system_rcfile = os.path.join(TEXMFLOCAL, 'tex', 'latex',
                                          'webquiz', 'webquizrc')
        self.read_webquizrc(self.system_rcfile)

        # the user rc file defaults to:
        #   ~/.dotfiles/config/webquizrc if .dotfiles/config exists
        #   ~/.config/webquizrc if .config exists
        # and otherwise to ~/.webquizrc
        if os.path.isdir(
                os.path.join(os.path.expanduser('~'), '.dotfiles', 'config')):
            self.user_rcfile = os.path.join(os.path.expanduser('~'),
                                            '.dotfiles', 'config', 'webquizrc')
        elif os.path.isdir(os.path.join(os.path.expanduser('~'), '.config')):
            self.user_rcfile = os.path.join(os.path.expanduser('~'), '.config',
                                            'webquizrc')
        else:
            self.user_rcfile = os.path.join(os.path.expanduser('~'),
                                            '.webquizrc')

        self.read_webquizrc(self.user_rcfile)
Пример #2
0
    def tex_install(self):
        r'''
        Install the tex files into the standard locations in TEXMFMAIN:
            scripts -> TEXMFMAIN/scripts/webquiz
            doc     -> TEXMFMAIN/doc/latex/webquiz
            latex   -> TEXMFMAIN/tex/latex/webquiz
        It is assumed that this is run from the zipfile installation. There
        is little in the way of error checking or debugging.

        Undocumented feature - useful for debugging initialisation routine
        '''
        webquiz_top = os.path.abspath(webquiz_util.webquiz_file('..'))
        texmf = webquiz_util.kpsewhich('-var-value TEXMFMAIN')
        for (src, target) in [('scripts', 'scripts'), ('latex', 'tex/latex'),
                              ('doc', 'doc/latex')]:
            try:
                webquiz_util.copytree(os.path.join(webquiz_top, src),
                                      os.path.join(texmf, target, 'webquiz'))

            except (FileExistsError, FileNotFoundError):
                continue

            except PermissionError as err:
                print(webquiz_templates.insufficient_permissions.format(err))
                sys.exit(1)

        try:

            # add a link to webquiz.py
            texbin = os.path.dirname(shutil.which('pdflatex'))
            if sys.platform.startswith('win'):
                shutil.copyfile(
                    os.path.join(texmf, 'scripts', 'webquiz', 'webquiz.bat'),
                    os.path.join(texbin, 'webquiz.bat'))
            else:
                os.symlink(
                    os.path.join(texmf, 'scripts', 'webquiz', 'webquiz.py'),
                    os.path.join(texbin, 'webquiz'))
            subprocess.call('mktexlsr', shell=True)

        except (FileExistsError, FileNotFoundError):
            pass

        except PermissionError as err:
            print(webquiz_templates.insufficient_permissions.format(err))
            sys.exit(1)

        except subprocess.CalledProcessError as err:
            self.webquiz_error('There was a problem running mktexlsr', err)
Пример #3
0
    def __init__(self, quiz_name, quiz_file, options, settings, metadata):
        self.options = options
        self.settings = settings
        self.metadata = metadata
        self.quiz_name = quiz_name.split('.')[0]
        self.quiz_file, extension = quiz_file.split('.')
        self.webquiz_url = settings['webquiz_url']
        if self.webquiz_url[-1] == '/':
            self.webquiz_url = self.webquiz_url[:len(self.webquiz_url) - 1]

        # run htlatex only if quiz_file has a .tex extension
        if extension == 'tex':
            self.htlatex_quiz_file()

        self.read_xml_file()

        # use kpsewhich to fine the webquiz language file
        try:
            language_file = webquiz_util.kpsewhich('webquiz-{}.lang'.format(
                self.quiz.language))
        except subprocess.CalledProcessError:
            self.webquiz_error(
                'kpsewhich is unable to find language file for "{}"'.format(
                    self.quiz.language))
        # read the language file and store as a dictonary
        self.language = webquiz_util.MetaData(language_file)

        # initialise number of quiz and discussion items
        self.number_discussions = len(self.quiz.discussion_list)
        self.number_questions = len(self.quiz.question_list)

        # build the different components of the quiz web page
        self.add_meta_data()
        self.add_question_javascript()
        self.add_side_menu()
        self.add_quiz_header_and_questions()
        self.add_breadcrumbs()

        # add the initialisation warning if webquiz has not been initialised
        if self.settings.initialise_warning != '':
            self.breadcrumbs = self.settings.initialise_warning + self.breadcrumbs

        # now write the quiz to the html file
        with codecs.open(self.quiz_name + '.html',
                         'w',
                         encoding='utf8',
                         errors='replace') as file:
            # write the quiz in the specified format
            file.write(self.options.write_web_page(self))
Пример #4
0
    def tex_uninstall(self):
        r'''
        UnInstall the tex files into TEXMFMAIN. It is assumed that the files
        are installed in the natural locations in the TEXMFMAIN tree, namely:
            scripts -> TEXMFMAIN/scripts/webquiz
            doc     -> TEXMFMAIN/doc/latex/webquiz
            latex   -> TEXMFMAIN/tex/latex/webquiz
        There is little in the way of error checking or debugging.

        Undocumented feature - useful for debugging initialisation routine
        '''
        webquiz_top = os.path.abspath(webquiz_util.webquiz_file('..'))
        texmf = webquiz_util.kpsewhich('-var-value TEXMFMAIN')
        for target in ['scripts', 'tex/latex', 'doc/latex']:
            try:
                shutil.rmtree(os.path.join(texmf, target, 'webquiz'))

            except (FileExistsError, FileNotFoundError):
                pass

            except PermissionError as err:
                print(webquiz_templates.insufficient_permissions.format(err))
                sys.exit(1)

        try:
            # remove link from texbin to webquiz.py
            texbin = os.path.dirname(shutil.which('pdflatex'))
            if sys.platform.startswith('win'):
                os.remove(os.path.join(texbin, 'webquiz.bat'))
            else:
                os.remove(os.path.join(texbin, 'webquiz'))

        except (FileExistsError, FileNotFoundError):
            pass

        except PermissionError as err:
            print(webquiz_templates.insufficient_permissions.format(err))
            sys.exit(1)

        # remove any rcfiles that exist in obvious places
        try:
            if os.path.isfile(self.system_rcfile):
                os.remove(self.system_rcfile)
            if os.path.isfile(self.user_rcfile):
                os.remove(self.user_rcfile)
            if os.path.isfile(self.rcfile):
                os.remove(self.rcfile)
        except PermissionError:
            print(webquiz_templates.insufficient_permissions.format(err))
            sys.exit(1)

        # remove link to webquiz.py
        texbin = os.path.dirname(shutil.which('pdflatex'))
        try:
            if sys.platform.startswith('win'):
                webquiz = os.path.join(texbin, 'webquiz.bat')
                os.remove(webquiz)
            else:
                webquiz = os.path.join(texbin, 'webquiz')
                target = os.readlink(webquiz)
                if target == os.path.join(texmf, 'scripts', 'webquiz',
                                          'webquiz.py'):
                    os.remove(webquiz)

        except (FileExistsError, FileNotFoundError):
            pass

        except OSError as err:
            print(
                'There was a problem removing the link to webquiz: {}'.format(
                    err))
Пример #5
0
    def initialise_webquiz(self, need_to_initialise=False, developer=False):
        r'''
        Set the root for the WebQuiz web directory and copy the www files into
        this directory. Once this is done save the settings to webquizrc.
        This method should only be used when WebQuiz is being set up.

        If `need_to_initialise` is `True` then this is a forced initialisation.
        '''

        # keep track of whether we have initialised
        self.have_initialised = True

        if need_to_initialise:
            self.initialise_warning = webquiz_templates.web_initialise_warning
            initialise = input(webquiz_templates.initialise_invite)
            if initialise != '' and initialise.strip().lower()[0] != 'y':
                self[
                    'webquiz_url'] = 'http://www.maths.usyd.edu.au/u/mathas/WebQuiz'
                return

        if self['webquiz_url'] == '':
            self['webquiz_url'] = '/WebQuiz'

        # prompt for directory and copy files - are these reasonable defaults
        # for each OS?
        if sys.platform == 'darwin':
            default_root = '/Library/WebServer/Documents/WebQuiz'
            platform = 'Mac OSX'
        elif sys.platform.startswith('win'):
            default_root = 'c:\inetpub\wwwroot\WebQuiz'
            platform = 'Windows'
        else:
            default_root = '/var/www/html/WebQuiz'
            platform = sys.platform.capitalize()

        if self['webquiz_www'] != '':
            webquiz_root = self['webquiz_www']
        else:
            webquiz_root = default_root

        print(webquiz_templates.initialise_introduction)
        input('Press RETURN to continue... ')

        print(
            webquiz_templates.webroot_request.format(platform=platform,
                                                     webquiz_dir=webquiz_root))
        input('Press RETURN to continue... ')

        files_copied = False
        while not files_copied:
            web_dir = input(
                '\nWebQuiz web directory:\n[{}] '.format(webquiz_root))
            if web_dir == '':
                web_dir = webquiz_root
            else:
                web_dir = os.path.expanduser(web_dir)

            print('Web directory set to {}'.format(web_dir))
            if web_dir == 'SMS':
                # undocumented: allow links to SMS web pages
                self['webquiz_www'] = 'SMS'
                self[
                    'webquiz_url'] = 'http://www.maths.usyd.edu.au/u/mathas/WebQuiz'

            else:
                try:
                    # ...remove the doc directory
                    web_doc = os.path.join(web_dir, 'doc')
                    if os.path.isfile(web_doc) or os.path.islink(web_doc):
                        os.remove(web_doc)
                    elif os.path.isdir(web_doc):
                        shutil.rmtree(web_doc)

                    # Need to locate the www directory, which should be a subdirectory
                    # of the webquiz doc directory. First try using texdoc
                    webquiz_doc = ''
                    try:
                        webquiz_pdf = webquiz_util.shell_command(
                            'texdoc --list --machine webquiz.pdf').split()[-1]
                        if webquiz_pdf.endswith('webquiz.pdf'):
                            webquiz_doc = os.path.dirname(webquiz_pdf)
                    except subprocess.CalledProcessError:
                        pass

                    # if texdoc failed then try using TEXMFMAIN
                    if webquiz_doc == '':
                        try:
                            webquiz_doc = os.path.join(
                                webquiz_util.kpsewhich('-var-value TEXMFMAIN'),
                                'doc', 'latex', 'webquiz')
                        except subprocess.CalledProcessError:
                            pass

                    # if we still don't have webquiz_doc then try working backwards from webquiz.cls
                    # unlikely to work if TEXMFMAIN doesn't
                    if not os.path.isdir(webquiz_doc):
                        parent = os.path.dirname
                        try:
                            texdist_dir = parent(
                                parent(
                                    parent(
                                        parent(
                                            parent(
                                                webquiz_util.kpsewhich(
                                                    'webquiz.cls'))))))
                        except subprocess.CalledProcessError:
                            print(
                                webquiz_templates.not_installed.format(
                                    metadata.repository))
                            sys.exit(1)

                        webquiz_doc = os.path.join(texdist_dir, 'doc', 'latex',
                                                   'webquiz')

                    # get the root directory of the source code for developer
                    # mode and just in case webquiz_www still does not exist
                    webquiz_src = os.path.dirname(
                        os.path.dirname(os.path.realpath(__file__)))

                    webquiz_www = os.path.join(webquiz_doc, 'www')
                    if not os.path.isdir(webquiz_www):
                        webquiz_www = os.path.join(webquiz_src, 'doc', 'www')

                    if developer and os.path.isdir(
                            os.path.join(webquiz_src, 'doc')):
                        # this is a development version so add links from the
                        # web directory to the css,doc and js directories
                        print('\nInstalling files for development version')
                        print('Linking web files {} -> {} ...\n'.format(
                            web_dir, webquiz_src))
                        if not os.path.exists(web_dir):
                            os.makedirs(web_dir)

                        for (src, target) in [('javascript', 'js'),
                                              ('css', 'css'), ('doc', 'doc')]:
                            newlink = os.path.join(web_dir, target)
                            try:
                                os.remove(newlink)
                            except FileNotFoundError:
                                pass
                            try:
                                os.symlink(os.path.join(webquiz_src, src),
                                           newlink)
                            except OSError as err:
                                print('There was a problem linking {}: {}'.
                                      format(newlink, err))

                    else:
                        # loop until we find some files to install or exit
                        while not os.path.isdir(
                                webquiz_www) or webquiz_www == '':
                            print('\nUnable to find the WebQuiz web files')
                            webquiz_www = input(
                                'Please enter the location of the WebQuiz www directory\nor press RETURN to exit: '
                            )
                            webquiz_www = os.path.expanduser(webquiz_www)
                            if webquiz_www == '':
                                sys.exit()
                            if not (webquiz_www.endswith('www/')
                                    or webquiz_www.endswith('www')):
                                print(
                                    '\nThe webquiz web directory is called www, so\n  {}\ncannot be the right directory.'
                                    .format(webquiz_www))
                                webquiz_www = False

                        # the www directory exists so we copy it to web_dir
                        print('\nCopying web files to {} ...'.format(web_dir))
                        webquiz_util.copytree(webquiz_www, web_dir)

                    self['webquiz_www'] = web_dir
                    files_copied = True

                except PermissionError:
                    print(webquiz_templates.permission_error.format(web_dir))

                except OSError as err:
                    print(
                        webquiz_templates.oserror_copying.format(
                            web_dir=web_dir, err=err))

        if self['webquiz_www'] != 'SMS':
            # now prompt for the relative url
            webquiz_url = input(
                webquiz_templates.webquiz_url_message.format(
                    self['webquiz_url']))
            if webquiz_url != '':
                # removing trailing slashes from webquiz_url
                while webquiz_url[-1] == '/':
                    webquiz_url = webquiz_url[:len(webquiz_url) - 1]

                if webquiz_url[0] != '/':  # force URL to start with /
                    webquiz_url = '/' + webquiz_url

                if not web_dir.endswith(webquiz_url):
                    print(webquiz_templates.webquiz_url_warning)
                    input('Press RETURN to continue... ')

                self['webquiz_url'] = webquiz_url

        # save the settings and exit
        self.write_webquizrc()
        print(
            webquiz_templates.initialise_ending.format(
                web_dir=self['webquiz_www']))
Пример #6
0
import os
import re
import shutil
import signal
import subprocess
import sys

# imports of webquiz code
import webquiz_makequiz
import webquiz_templates
import webquiz_util

#################################################################################
# read in basic meta data such as author, version, ... and set debugging=False
try:
    metadata = webquiz_util.MetaData(webquiz_util.kpsewhich('webquiz.ini'),
                                     debugging=False)
except subprocess.CalledProcessError:
    # check to see if we are running from the zip file
    ini_file = os.path.join(webquiz_util.webquiz_file(''), '..', 'latex',
                            'webquiz.ini')
    try:
        metadata = webquiz_util.MetaData(ini_file, debugging=False)
    except (FileNotFoundError, subprocess.CalledProcessError):
        print(webquiz_templates.missing_webquiz_ini.format(ini_file))
        sys.exit(1)


# ---------------------------------------------------------------------------------------
def graceful_exit(sig, frame):
    ''' exit gracefully on SIGINT and SIGTERM'''
Пример #7
0
    def initialise_webquiz(self, need_to_initialise=False):
        r'''
        Set the root for the WebQuiz web directory and copy the www files into
        this directory. Once this is done save the settings to webquizrc.
        This method should only be used when WebQuiz is being set up.

        If `need_to_initialise` is `True` then this is a forced initialisation.
        '''

        if need_to_initialise:
            self.initialise_warning = webquiz_templates.web_initialise_warning
            initialise = input(webquiz_templates.initialise_invite)
            if initialise != '' and initialise.strip().lower()[0] != 'y':
                self[
                    'webquiz_url'] = 'http://www.maths.usyd.edu.au/u/mathas/WebQuiz'
                return

        if self['webquiz_url'] == '':
            self['webquiz_url'] = '/WebQuiz'

        # prompt for directory and copy files - are these reasonable defaults
        # for each OS?
        if sys.platform == 'darwin':
            default_root = '/Library/WebServer/Documents/WebQuiz'
            platform = 'Mac OSX'
        elif sys.platform.startswith('win'):
            default_root = ' c:\inetpub\wwwroot\WebQuiz'
            platform = 'Windows'
        else:
            default_root = '/var/www/html/WebQuiz'
            platform = sys.platform.capitalize()

        if self['webquiz_www'] != '':
            webquiz_root = self['webquiz_www']
        else:
            webquiz_root = default_root

        print(webquiz_templates.initialise_introduction)
        input('Press return to continue... ')

        print(
            webquiz_templates.webroot_request.format(platform=platform,
                                                     webquiz_dir=webquiz_root))
        input('Press return to continue... ')

        files_copied = False
        while not files_copied:
            web_dir = input(
                '\nWebQuiz web directory:\n[{}] '.format(webquiz_root))
            if web_dir == '':
                web_dir = webquiz_root
            else:
                web_dir = os.path.expanduser(web_dir)

            print('Web directory set to {}'.format(web_dir))
            if web_dir == 'SMS':
                # undocumented: allow links to SMS web pages
                self['webquiz_www'] = 'SMS'
                self[
                    'webquiz_url'] = 'http://www.maths.usyd.edu.au/u/mathas/WebQuiz'

            else:
                try:
                    # ...remove the doc directory
                    web_doc = os.path.join(web_dir, 'doc')
                    if os.path.isfile(web_doc) or os.path.islink(web_doc):
                        os.remove(web_doc)
                    elif os.path.isdir(web_doc):
                        shutil.rmtree(web_doc)

                    # the www directory is a subdirectory of the webquiz doc
                    # directory so we need to locate this
                    webquiz_doc = os.path.join(
                        webquiz_util.kpsewhich('-var TEXMFMAIN'), 'doc',
                        'latex', 'webquiz')
                    if not os.path.isdir(webquiz_doc):
                        parent = os.path.dirname
                        texdist_dir = parent(
                            parent(
                                parent(
                                    parent(
                                        parent(
                                            webquiz_util.kpsewhich(
                                                'webquiz.cls'))))))
                        webquiz_doc = os.path.join(texdist_dir, 'doc', 'latex',
                                                   'webquiz')

                    webquiz_www = os.path.join(webquiz_doc, 'www')

                    # get the root directory of the source code in case
                    # webquiz_www does not exist
                    webquiz_src = os.path.dirname(
                        os.path.dirname(os.path.realpath(__file__)))

                    if os.path.isdir(webquiz_www):
                        # if the www directory exists then copy it to web_dir
                        print(
                            '\nCopying web files to {} ...\n'.format(web_dir))
                        webquiz_util.copytree(webquiz_www, web_dir)

                    elif os.path.isdir(os.path.join(webquiz_src, 'doc')):
                        # assume this is a development version and add links
                        # from the web directory to the parent directory

                        print(
                            '\nAssuming that this is the development version')
                        print('Linking web files {} -> {} ...\n'.format(
                            web_dir, webquiz_src))
                        if not os.path.exists(web_dir):
                            os.makedirs(web_dir)

                        for (src, target) in [('javascript', 'js'),
                                              ('css', 'css'), ('doc', 'doc')]:
                            newlink = os.path.join(web_dir, target)
                            try:
                                os.remove(newlink)
                            except FileNotFoundError:
                                pass
                            os.symlink(os.path.join(webquiz_src, src), newlink)

                    else:
                        self.webquiz_error(
                            'unable to find webquiz source files')

                    self['webquiz_www'] = web_dir
                    files_copied = True

                except PermissionError:
                    print(webquiz_templates.permission_error.format(web_dir))

                except OSError as err:
                    print(
                        webquiz_templates.oserror_copying.format(
                            web_dir=web_dir, err=err))

        if self['webquiz_www'] != 'SMS':
            # now prompt for the relative url
            mq_url = input(
                webquiz_templates.webquiz_url_message.format(
                    self['webquiz_url']))
            if mq_url != '':
                # removing trailing slashes from mq_url
                while mq_url[-1] == '/':
                    mq_url = mq_url[:len(mq_url) - 1]

                if mq_url[0] != '/':  # force URL to start with /
                    print("  ** prepending '/' to webquiz_url **")
                    mq_url = '/' + mq_url

                if not web_dir.endswith(mq_url):
                    print(webquiz_templates.webquiz_url_warning)
                    input('Press return to continue... ')

                self['webquiz_url'] = mq_url

        # save the settings and exit
        self.write_webquizrc()
        print(
            webquiz_templates.initialise_ending.format(
                web_dir=self['webquiz_www']))
Пример #8
0
import os
import re
import shutil
import signal
import subprocess
import sys

# imports of webquiz code
import webquiz_makequiz
import webquiz_templates
import webquiz_util

#################################################################################
# read in basic meta data such as author, version, ... and set debugging=False
try:
    metadata = webquiz_util.MetaData(webquiz_util.kpsewhich('webquiz.ini'), debugging=False)
except subprocess.CalledProcessError:
    # check to see if we are running from the zip file
    ini_file = os.path.join(webquiz_util.webquiz_file(''), '..', 'latex', 'webquiz.ini')
    try:
        metadata = webquiz_util.MetaData(ini_file, debugging=False)
    except (FileNotFoundError, subprocess.CalledProcessError):
        print('webquiz installation error: unable to find webquiz.ini -> {}'.format(ini_file))
        sys.exit(1)

# ---------------------------------------------------------------------------------------
def graceful_exit(sig, frame):
    ''' exit gracefully on SIGINT and SIGTERM'''
    if metadata:
        webquiz_util.webquiz_error(False, 'program terminated (signal {}\n  {})'.format(sig, frame))
    else: